evolcore 0.0.1 → 0.0.2

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 (371) hide show
  1. package/CHANGELOG.md +813 -0
  2. package/LICENSE +21 -0
  3. package/MIGRATION-0.5.0.md +378 -0
  4. package/README.md +318 -14
  5. package/ROLE_ACCESS_CONTROL.md +174 -0
  6. package/assets/.env.template +4 -0
  7. package/assets/brand/evolcore/README.md +19 -0
  8. package/assets/brand/evolcore/evolcore-app-icon.png +0 -0
  9. package/assets/brand/evolcore/evolcore-app-icon.svg +13 -0
  10. package/assets/brand/evolcore/evolcore-brand-board.png +0 -0
  11. package/assets/brand/evolcore/evolcore-brand-board.svg +126 -0
  12. package/assets/brand/evolcore/evolcore-logo-kit.zip +0 -0
  13. package/assets/brand/evolcore/evolcore-logo-reverse.png +0 -0
  14. package/assets/brand/evolcore/evolcore-logo-reverse.svg +14 -0
  15. package/assets/brand/evolcore/evolcore-logo.png +0 -0
  16. package/assets/brand/evolcore/evolcore-logo.svg +14 -0
  17. package/assets/brand/evolcore/evolcore-mark.png +0 -0
  18. package/assets/brand/evolcore/evolcore-mark.svg +10 -0
  19. package/bin/ec-safe-output.js +161 -0
  20. package/bin/ec.js +29 -0
  21. package/dist/agents/baseagent.js +163 -0
  22. package/dist/agents/claude-runner.js +2385 -0
  23. package/dist/agents/codex-app-server-client.js +448 -0
  24. package/dist/agents/codex-runner.js +2639 -0
  25. package/dist/agents/gemini-runner.js +666 -0
  26. package/dist/agents/runner-types.js +75 -0
  27. package/dist/aun/aid/agentmd.js +216 -0
  28. package/dist/aun/aid/client.js +132 -0
  29. package/dist/aun/aid/control-aid.js +91 -0
  30. package/dist/aun/aid/identity.js +518 -0
  31. package/dist/aun/aid/index.js +4 -0
  32. package/dist/aun/aid/store.js +74 -0
  33. package/dist/aun/aid/types.js +1 -0
  34. package/dist/aun/aid/validation.js +21 -0
  35. package/dist/aun/group-identity.js +10 -0
  36. package/dist/aun/msg/group-index.js +6 -0
  37. package/dist/aun/msg/group.js +1231 -0
  38. package/dist/aun/msg/history.js +123 -0
  39. package/dist/aun/msg/index.js +5 -0
  40. package/dist/aun/msg/p2p.js +393 -0
  41. package/dist/aun/msg/payload-type.js +27 -0
  42. package/dist/aun/msg/upload.js +137 -0
  43. package/dist/aun/outbox.js +160 -0
  44. package/dist/aun/rpc/caller.js +42 -0
  45. package/dist/aun/rpc/connection.js +25 -0
  46. package/dist/aun/rpc/index.js +2 -0
  47. package/dist/aun/service-proxy.js +225 -0
  48. package/dist/aun/storage/download.js +29 -0
  49. package/dist/aun/storage/index.js +3 -0
  50. package/dist/aun/storage/manage.js +10 -0
  51. package/dist/aun/storage/upload.js +68 -0
  52. package/dist/channels/aun.js +4147 -0
  53. package/dist/channels/daemon.js +422 -0
  54. package/dist/channels/dingtalk.js +649 -0
  55. package/dist/channels/feishu.js +1789 -0
  56. package/dist/channels/qqbot.js +409 -0
  57. package/dist/channels/wechat.js +817 -0
  58. package/dist/channels/wecom.js +565 -0
  59. package/dist/cli/agent-command.js +641 -0
  60. package/dist/cli/agent.js +1059 -0
  61. package/dist/cli/aun-commands.js +1948 -0
  62. package/dist/cli/bench.js +1228 -0
  63. package/dist/cli/cli-argv.js +66 -0
  64. package/dist/cli/code-stats.js +329 -0
  65. package/dist/cli/command-log.js +82 -0
  66. package/dist/cli/config-selector.js +69 -0
  67. package/dist/cli/config.js +261 -0
  68. package/dist/cli/ctl-command.js +62 -0
  69. package/dist/cli/daemon-commands.js +2887 -0
  70. package/dist/cli/fs-command.js +1447 -0
  71. package/dist/cli/handoff-command.js +302 -0
  72. package/dist/cli/help.js +31 -0
  73. package/dist/cli/index.js +358 -0
  74. package/dist/cli/init-channel.js +1377 -0
  75. package/dist/cli/init.js +553 -0
  76. package/dist/cli/link-rules.js +240 -0
  77. package/dist/cli/model.js +590 -0
  78. package/dist/cli/net-check.js +723 -0
  79. package/dist/cli/queue-command.js +126 -0
  80. package/dist/cli/response.js +345 -0
  81. package/dist/cli/restart-monitor.js +456 -0
  82. package/dist/cli/stats.js +607 -0
  83. package/dist/cli/task-context.js +80 -0
  84. package/dist/cli/trigger-command.js +505 -0
  85. package/dist/cli/version.js +88 -0
  86. package/dist/cli/watch-logs.js +33 -0
  87. package/dist/cli/watch-msg.js +673 -0
  88. package/dist/config/boot-log.js +266 -0
  89. package/dist/config/builtin-role-templates.js +30 -0
  90. package/dist/config/builtin-roles.js +85 -0
  91. package/dist/config/config-batch-get.js +11 -0
  92. package/dist/config/config-field-policy.js +261 -0
  93. package/dist/config/config-manager.js +916 -0
  94. package/dist/config/config-operation-service.js +384 -0
  95. package/dist/config/contact-book.js +371 -0
  96. package/dist/config/gateway-config.js +858 -0
  97. package/dist/config/lifecycle.js +17 -0
  98. package/dist/config/mention-mode.js +27 -0
  99. package/dist/config/merge.js +161 -0
  100. package/dist/config/owner-policy.js +4 -0
  101. package/dist/config/peer-role-resolver.js +139 -0
  102. package/dist/config/resolved-config-op.js +483 -0
  103. package/dist/config/role-config-v4-startup.js +32 -0
  104. package/dist/config/role-config-v5-startup.js +27 -0
  105. package/dist/config/role-schema.js +105 -0
  106. package/dist/config/role-service.js +159 -0
  107. package/dist/config/role-store.js +204 -0
  108. package/dist/config/roles.js +55 -0
  109. package/dist/config/schema-registry.js +154 -0
  110. package/dist/config/snapshot.js +598 -0
  111. package/dist/config-store.js +503 -0
  112. package/dist/core/auth/agent-delegation.js +111 -0
  113. package/dist/core/auth/auth-gateway.js +166 -0
  114. package/dist/core/auth/authenticated-actor.js +6 -0
  115. package/dist/core/auth/authorization-audit.js +110 -0
  116. package/dist/core/auth/operation-authorizer.js +718 -0
  117. package/dist/core/auth/operation-catalog.js +675 -0
  118. package/dist/core/baseagent-loader.js +54 -0
  119. package/dist/core/bootstrap-service.js +175 -0
  120. package/dist/core/capability/capability-manager.js +316 -0
  121. package/dist/core/capability/providers/claude-capability-provider.js +176 -0
  122. package/dist/core/capability/providers/codex-capability-provider.js +148 -0
  123. package/dist/core/capability/providers/gemini-capability-provider.js +10 -0
  124. package/dist/core/capability/types.js +27 -0
  125. package/dist/core/causation/audit.js +103 -0
  126. package/dist/core/causation/aun-association.js +111 -0
  127. package/dist/core/causation/context.js +93 -0
  128. package/dist/core/causation/index.js +4 -0
  129. package/dist/core/causation/types.js +2 -0
  130. package/dist/core/channel-loader.js +277 -0
  131. package/dist/core/command/agent-control.js +616 -0
  132. package/dist/core/command/cli-intent-parser.js +225 -0
  133. package/dist/core/command/command-handler.js +1638 -0
  134. package/dist/core/command/menu-handler.js +3354 -0
  135. package/dist/core/command/menu-protocol.js +247 -0
  136. package/dist/core/command/role-menu.js +1524 -0
  137. package/dist/core/command/slash-gate.js +148 -0
  138. package/dist/core/command/slash-handler.js +3056 -0
  139. package/dist/core/daemon-file-cache.js +216 -0
  140. package/dist/core/event-bus.js +32 -0
  141. package/dist/core/event-catalog.js +740 -0
  142. package/dist/core/evolagent-registry.js +546 -0
  143. package/dist/core/evolagent.js +331 -0
  144. package/dist/core/handoff/dispatcher.js +229 -0
  145. package/dist/core/handoff/mutex.js +46 -0
  146. package/dist/core/handoff/runtime.js +324 -0
  147. package/dist/core/handoff/store.js +537 -0
  148. package/dist/core/handoff/types.js +12 -0
  149. package/dist/core/inference/text-inference.js +173 -0
  150. package/dist/core/interaction-registration.js +10 -0
  151. package/dist/core/interaction-router.js +278 -0
  152. package/dist/core/message/create-status.js +67 -0
  153. package/dist/core/message/im-renderer.js +657 -0
  154. package/dist/core/message/items-formatter.js +76 -0
  155. package/dist/core/message/logical-queue-bridge.js +123 -0
  156. package/dist/core/message/message-bridge.js +803 -0
  157. package/dist/core/message/message-cache.js +56 -0
  158. package/dist/core/message/message-log.js +339 -0
  159. package/dist/core/message/message-processor.js +4 -0
  160. package/dist/core/message/message-queue.js +1436 -0
  161. package/dist/core/message/message-utils.js +70 -0
  162. package/dist/core/message/peer-mode.js +105 -0
  163. package/dist/core/message/pending-hints.js +232 -0
  164. package/dist/core/message/response-depth.js +33 -0
  165. package/dist/core/message/response-engine.js +3776 -0
  166. package/dist/core/message/response-snapshot.js +83 -0
  167. package/dist/core/message/stream-debouncer.js +130 -0
  168. package/dist/core/message/stream-idle-monitor.js +124 -0
  169. package/dist/core/model/config-scope.js +162 -0
  170. package/dist/core/model/field-scope.js +78 -0
  171. package/dist/core/model/model-catalog.js +227 -0
  172. package/dist/core/model/model-diagnostics.js +182 -0
  173. package/dist/core/model/model-permission.js +90 -0
  174. package/dist/core/permission/approval-gateway.js +1017 -0
  175. package/dist/core/permission/ec-command-parser.js +347 -0
  176. package/dist/core/permission/execution-sandbox.js +16 -0
  177. package/dist/core/permission/index.js +6 -0
  178. package/dist/core/permission/mode.js +24 -0
  179. package/dist/core/permission/sandbox-runtime.js +265 -0
  180. package/dist/core/permission/tool-policy.js +987 -0
  181. package/dist/core/permission/unix-socket-policy.js +99 -0
  182. package/dist/core/protected-paths.js +330 -0
  183. package/dist/core/relation/peer-identity.js +222 -0
  184. package/dist/core/relation/peer-key.js +1 -0
  185. package/dist/core/role/runtime-policy.js +141 -0
  186. package/dist/core/session/adapters/claude-session-file-adapter.js +218 -0
  187. package/dist/core/session/adapters/codex-session-file-adapter.js +333 -0
  188. package/dist/core/session/adapters/gemini-session-file-adapter.js +181 -0
  189. package/dist/core/session/session-file-adapter.js +7 -0
  190. package/dist/core/session/session-file-health.js +45 -0
  191. package/dist/core/session/session-fs-store.js +232 -0
  192. package/dist/core/session/session-key.js +24 -0
  193. package/dist/core/session/session-manager.js +1587 -0
  194. package/dist/core/session/session-mapper.js +100 -0
  195. package/dist/core/session/session-renew.js +314 -0
  196. package/dist/core/session/session-title.js +128 -0
  197. package/dist/core/session/session-turn-coordinator.js +205 -0
  198. package/dist/core/session/session-turns.js +67 -0
  199. package/dist/core/system-channels.js +29 -0
  200. package/dist/eck/baseagent-caps.js +18 -0
  201. package/dist/eck/detect.js +47 -0
  202. package/dist/eck/group-rules-sync.js +345 -0
  203. package/dist/eck/init.js +77 -0
  204. package/dist/eck/kit-renderer.js +359 -0
  205. package/dist/eck/manifest-engine.js +446 -0
  206. package/dist/eck/message-renderer.js +199 -0
  207. package/dist/eck/rules-loader.js +28 -0
  208. package/dist/index.js +2870 -4
  209. package/dist/ipc.js +748 -0
  210. package/dist/paths.js +262 -0
  211. package/dist/product.js +18 -0
  212. package/dist/response-system/context-builder.js +71 -0
  213. package/dist/response-system/coordinator.js +117 -0
  214. package/dist/response-system/decision-executor.js +86 -0
  215. package/dist/response-system/engines/v1/index.js +21 -0
  216. package/dist/response-system/engines/v1/interactive-flow.js +27 -0
  217. package/dist/response-system/engines/v1/proactive-flow.js +137 -0
  218. package/dist/response-system/engines/v1/types.js +1 -0
  219. package/dist/response-system/extensions.js +41 -0
  220. package/dist/response-system/index.js +6 -0
  221. package/dist/response-system/modes/index.js +7 -0
  222. package/dist/response-system/modes/single-session/index.js +72 -0
  223. package/dist/response-system/queues/fifo-queue.js +44 -0
  224. package/dist/response-system/queues/index.js +6 -0
  225. package/dist/response-system/queues/lifo-queue.js +42 -0
  226. package/dist/response-system/queues/priority-queue.js +63 -0
  227. package/dist/response-system/registry.js +97 -0
  228. package/dist/response-system/resolver.js +37 -0
  229. package/dist/response-system/selector.js +23 -0
  230. package/dist/response-system/types.js +7 -0
  231. package/dist/stats/billing.js +151 -0
  232. package/dist/stats/budget.js +93 -0
  233. package/dist/stats/db.js +403 -0
  234. package/dist/stats/eck-vars.js +89 -0
  235. package/dist/stats/index.js +11 -0
  236. package/dist/stats/normalizer.js +80 -0
  237. package/dist/stats/price-resolver.js +138 -0
  238. package/dist/stats/query.js +763 -0
  239. package/dist/stats/role-budget.js +168 -0
  240. package/dist/stats/writer.js +151 -0
  241. package/dist/trigger/anomaly-store.js +258 -0
  242. package/dist/trigger/audit.js +152 -0
  243. package/dist/trigger/event-source.js +119 -0
  244. package/dist/trigger/feedback.js +685 -0
  245. package/dist/trigger/history.js +290 -0
  246. package/dist/trigger/manager.js +291 -0
  247. package/dist/trigger/parser.js +520 -0
  248. package/dist/trigger/patch.js +148 -0
  249. package/dist/trigger/scheduler.js +1600 -0
  250. package/dist/trigger/script-executor.js +155 -0
  251. package/dist/trigger/state.js +145 -0
  252. package/dist/trigger/types.js +1 -0
  253. package/dist/trigger/validation.js +621 -0
  254. package/dist/types.js +12 -0
  255. package/dist/utils/aid-bind.js +299 -0
  256. package/dist/utils/atomic-write.js +95 -0
  257. package/dist/utils/avatar-upload.js +123 -0
  258. package/dist/utils/cross-platform.js +297 -0
  259. package/dist/utils/ecweb-utils.js +73 -0
  260. package/dist/utils/error-dict.json +153 -0
  261. package/dist/utils/error-utils.js +349 -0
  262. package/dist/utils/instance-registry.js +437 -0
  263. package/dist/utils/locale.js +21 -0
  264. package/dist/utils/log-writer.js +224 -0
  265. package/dist/utils/logger.js +89 -0
  266. package/dist/utils/markdown-to-plain-text.js +20 -0
  267. package/dist/utils/media-cache.js +271 -0
  268. package/dist/utils/model-prices.jsonl +17 -0
  269. package/dist/utils/npm-ops.js +210 -0
  270. package/dist/utils/process-introspect.js +133 -0
  271. package/dist/utils/process-tree-stats.js +271 -0
  272. package/dist/utils/project-path.js +74 -0
  273. package/dist/utils/stats.js +410 -0
  274. package/dist/utils/tool-summary.js +284 -0
  275. package/dist/utils/welcome.js +268 -0
  276. package/kits/docs/GUIDE.md +20 -0
  277. package/kits/docs/INDEX.md +65 -0
  278. package/kits/docs/aun/CHEATSHEET.md +19 -0
  279. package/kits/docs/aun/SYNC_PROTOCOL.md +15 -0
  280. package/kits/docs/channels/aun.md +65 -0
  281. package/kits/docs/channels/feishu.md +56 -0
  282. package/kits/docs/context-assembly.md +366 -0
  283. package/kits/docs/eck_templates/GUIDE.template.md +22 -0
  284. package/kits/docs/eck_templates/INDEX.template.md +28 -0
  285. package/kits/docs/eck_templates/path-registry.template.md +33 -0
  286. package/kits/docs/eck_templates/runtime.template.md +19 -0
  287. package/kits/docs/evolcore/INDEX.md +66 -0
  288. package/kits/docs/evolcore/agent.md +69 -0
  289. package/kits/docs/evolcore/aid.md +49 -0
  290. package/kits/docs/evolcore/config.md +149 -0
  291. package/kits/docs/evolcore/ctl.md +46 -0
  292. package/kits/docs/evolcore/event.md +216 -0
  293. package/kits/docs/evolcore/fs-architecture.md +1215 -0
  294. package/kits/docs/evolcore/fs.md +101 -0
  295. package/kits/docs/evolcore/group-fs.md +17 -0
  296. package/kits/docs/evolcore/group-rules.md +226 -0
  297. package/kits/docs/evolcore/group.md +141 -0
  298. package/kits/docs/evolcore/model.md +47 -0
  299. package/kits/docs/evolcore/msg.md +130 -0
  300. package/kits/docs/evolcore/response.md +80 -0
  301. package/kits/docs/evolcore/rpc.md +35 -0
  302. package/kits/docs/evolcore/self-summary.md +29 -0
  303. package/kits/docs/evolcore/stats.md +70 -0
  304. package/kits/docs/evolcore/storage.md +49 -0
  305. package/kits/docs/evolcore/trigger.md +524 -0
  306. package/kits/docs/identity/AID_PROFILE_SPEC.md +26 -0
  307. package/kits/docs/identity/PATH_OPS.md +16 -0
  308. package/kits/docs/identity/ROLE_DETAIL.md +23 -0
  309. package/kits/docs/identity/identity-tools.md +26 -0
  310. package/kits/docs/path-registry.md +43 -0
  311. package/kits/docs/prompt-loading-architecture.md +266 -0
  312. package/kits/docs/venues/aun-group.md +45 -0
  313. package/kits/docs/venues/aun-private.md +10 -0
  314. package/kits/docs/venues/client-desktop.md +10 -0
  315. package/kits/docs/venues/client-mobile.md +10 -0
  316. package/kits/docs/venues/feishu-group.md +13 -0
  317. package/kits/docs/venues/feishu-private.md +9 -0
  318. package/kits/docs/venues/group.md +25 -0
  319. package/kits/docs/venues/private.md +10 -0
  320. package/kits/eck_manifest.auxiliary.json +43 -0
  321. package/kits/eck_manifest.json +191 -0
  322. package/kits/eck_message_manifest.json +63 -0
  323. package/kits/migrations/README-role-config-v4.md +32 -0
  324. package/kits/migrations/migrate-role-config-v4.mjs +623 -0
  325. package/kits/migrations/migrate-role-config-v5.mjs +346 -0
  326. package/kits/migrations/rename-config-file.mjs +99 -0
  327. package/kits/rules/01-overview.md +142 -0
  328. package/kits/rules/02-navigation.md +76 -0
  329. package/kits/rules/03-identity.md +34 -0
  330. package/kits/rules/04-relation.md +59 -0
  331. package/kits/rules/05-venue.md +44 -0
  332. package/kits/rules/06-channel.md +59 -0
  333. package/kits/schemas/_meta.json +29 -0
  334. package/kits/schemas/agent-config.schema.1.json +177 -0
  335. package/kits/schemas/agent-config.schema.2.json +239 -0
  336. package/kits/schemas/agent-config.schema.3.json +119 -0
  337. package/kits/schemas/agent-config.schema.4.json +208 -0
  338. package/kits/schemas/agent-config.schema.5.json +326 -0
  339. package/kits/schemas/contact-book.schema.1.json +36 -0
  340. package/kits/schemas/daemon.schema.1.json +90 -0
  341. package/kits/schemas/defaults.schema.1.json +81 -0
  342. package/kits/schemas/menu-exec-schema-commands.md +208 -0
  343. package/kits/schemas/migrations/README.md +28 -0
  344. package/kits/schemas/relation-config.schema.1.json +158 -0
  345. package/kits/schemas/relation-config.schema.2.json +73 -0
  346. package/kits/schemas/relation-config.schema.3.json +50 -0
  347. package/kits/schemas/relation-config.schema.4.json +47 -0
  348. package/kits/schemas/role-config.schema.1.json +200 -0
  349. package/kits/schemas/role-registry.schema.1.json +35 -0
  350. package/kits/schemas/single-session.schema.1.json +31 -0
  351. package/kits/templates/bootstrap-welcome.md +15 -0
  352. package/kits/templates/message-fragments/handoff-request-to-target.md +13 -0
  353. package/kits/templates/message-fragments/handoff-response-to-origin.md +10 -0
  354. package/kits/templates/message-fragments/inject-default.md +2 -0
  355. package/kits/templates/message-fragments/item.md +2 -0
  356. package/kits/templates/roles/admin.json +8 -0
  357. package/kits/templates/roles/member.json +40 -0
  358. package/kits/templates/roles/owner.json +8 -0
  359. package/kits/templates/roles/visitor.json +39 -0
  360. package/kits/templates/system-fragments/baseagent.md +14 -0
  361. package/kits/templates/system-fragments/bootstrap.md +16 -0
  362. package/kits/templates/system-fragments/channel.md +48 -0
  363. package/kits/templates/system-fragments/commands.md +26 -0
  364. package/kits/templates/system-fragments/identity.md +11 -0
  365. package/kits/templates/system-fragments/relation.md +19 -0
  366. package/kits/templates/system-fragments/session.md +53 -0
  367. package/kits/templates/system-fragments/venue.md +31 -0
  368. package/package.json +50 -15
  369. package/dist/index.d.ts +0 -7
  370. package/dist/index.d.ts.map +0 -1
  371. package/dist/index.js.map +0 -1
@@ -0,0 +1,673 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { resolvePaths } from '../paths.js';
4
+ import { decodeDirSegment, readAllJsonlLines } from '../core/session/session-fs-store.js';
5
+ import { isTransientProtocolMessage } from '../core/message/message-log.js';
6
+ // ==================== ANSI ====================
7
+ const isTTY = !!process.stdout.isTTY;
8
+ const RST = isTTY ? '\x1b[0m' : '';
9
+ const DIM = isTTY ? '\x1b[2m' : '';
10
+ const BOLD = isTTY ? '\x1b[1m' : '';
11
+ const CYAN = isTTY ? '\x1b[36m' : '';
12
+ const GREEN = isTTY ? '\x1b[32m' : '';
13
+ const BLUE = isTTY ? '\x1b[34m' : '';
14
+ const ORANGE = isTTY ? '\x1b[38;5;208m' : '';
15
+ const MAGENTA = isTTY ? '\x1b[35m' : '';
16
+ const YELLOW = isTTY ? '\x1b[33m' : '';
17
+ const BG_SEL = isTTY ? '\x1b[48;5;236m' : ''; // dark gray background for selected row
18
+ // ==================== Helpers ====================
19
+ function visualWidth(s) {
20
+ const stripped = s.replace(/\x1b\[[0-9;]*m/g, '');
21
+ let w = 0;
22
+ for (const ch of stripped) {
23
+ const code = ch.charCodeAt(0);
24
+ w += (code >= 0x4e00 && code <= 0x9fff) || (code >= 0x3000 && code <= 0x30ff) ||
25
+ (code >= 0xff00 && code <= 0xffef) ? 2 : 1;
26
+ }
27
+ return w;
28
+ }
29
+ function padRight(s, width) {
30
+ const pad = Math.max(0, width - visualWidth(s));
31
+ return s + ' '.repeat(pad);
32
+ }
33
+ function truncate(s, maxWidth) {
34
+ let w = 0;
35
+ let i = 0;
36
+ for (const ch of s) {
37
+ const code = ch.charCodeAt(0);
38
+ const cw = (code >= 0x4e00 && code <= 0x9fff) || (code >= 0x3000 && code <= 0x30ff) ||
39
+ (code >= 0xff00 && code <= 0xffef) ? 2 : 1;
40
+ if (w + cw > maxWidth - 1)
41
+ return s.slice(0, i) + '…';
42
+ w += cw;
43
+ i += ch.length;
44
+ }
45
+ return s;
46
+ }
47
+ function wrapText(s, lineWidth, maxLines) {
48
+ const result = [];
49
+ let remaining = s;
50
+ while (remaining.length > 0 && result.length < maxLines) {
51
+ let w = 0;
52
+ let cutIdx = 0;
53
+ for (const ch of remaining) {
54
+ const code = ch.charCodeAt(0);
55
+ const cw = (code >= 0x4e00 && code <= 0x9fff) || (code >= 0x3000 && code <= 0x30ff) ||
56
+ (code >= 0xff00 && code <= 0xffef) ? 2 : 1;
57
+ if (w + cw > lineWidth)
58
+ break;
59
+ w += cw;
60
+ cutIdx += ch.length;
61
+ }
62
+ if (cutIdx === 0)
63
+ break;
64
+ const isLast = result.length === maxLines - 1;
65
+ if (isLast && cutIdx < remaining.length) {
66
+ result.push(truncate(remaining, lineWidth));
67
+ }
68
+ else {
69
+ result.push(remaining.slice(0, cutIdx));
70
+ }
71
+ remaining = remaining.slice(cutIdx);
72
+ }
73
+ if (result.length === 0)
74
+ result.push('');
75
+ return result;
76
+ }
77
+ function formatTimeAgo(ms) {
78
+ const sec = Math.floor(ms / 1000);
79
+ if (sec < 60)
80
+ return `${sec}s`;
81
+ const min = Math.floor(sec / 60);
82
+ if (min < 60)
83
+ return `${min}m`;
84
+ const hour = Math.floor(min / 60);
85
+ if (hour < 24)
86
+ return `${hour}h`;
87
+ return `${Math.floor(hour / 24)}d`;
88
+ }
89
+ function getCodeTime(pkgRoot) {
90
+ let latestMtime = 0;
91
+ const scanDir = fs.existsSync(path.join(pkgRoot, 'dist')) ? path.join(pkgRoot, 'dist') : path.join(pkgRoot, 'src');
92
+ const scanRecursive = (dir) => {
93
+ try {
94
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
95
+ if (entry.name === 'node_modules')
96
+ continue;
97
+ const full = path.join(dir, entry.name);
98
+ if (entry.isDirectory()) {
99
+ scanRecursive(full);
100
+ continue;
101
+ }
102
+ if (entry.name.endsWith('.js') || entry.name.endsWith('.ts')) {
103
+ const mt = fs.statSync(full).mtimeMs;
104
+ if (mt > latestMtime)
105
+ latestMtime = mt;
106
+ }
107
+ }
108
+ }
109
+ catch { }
110
+ };
111
+ scanRecursive(scanDir);
112
+ if (!latestMtime)
113
+ return '?';
114
+ const d = new Date(latestMtime);
115
+ return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
116
+ }
117
+ function formatNumber(n) {
118
+ return n.toLocaleString('en-US');
119
+ }
120
+ function formatTime(ts) {
121
+ const d = new Date(ts);
122
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
123
+ }
124
+ function formatDateTime(ts) {
125
+ const d = new Date(ts);
126
+ const mo = String(d.getMonth() + 1).padStart(2, '0');
127
+ const dd = String(d.getDate()).padStart(2, '0');
128
+ const hh = String(d.getHours()).padStart(2, '0');
129
+ const mm = String(d.getMinutes()).padStart(2, '0');
130
+ return `${mo}-${dd} ${hh}:${mm}`;
131
+ }
132
+ function shortAid(aid) {
133
+ return aid.split('.')[0];
134
+ }
135
+ // ==================== Data Layer ====================
136
+ export function getSessionsAunDir() {
137
+ const p = resolvePaths();
138
+ return path.join(p.sessionsDir, 'aun');
139
+ }
140
+ export function listLocalAids(aunDir) {
141
+ try {
142
+ return fs.readdirSync(aunDir, { withFileTypes: true })
143
+ .filter(e => e.isDirectory())
144
+ .map(e => decodeDirSegment(e.name));
145
+ }
146
+ catch {
147
+ return [];
148
+ }
149
+ }
150
+ export function listPeers(aunDir, localAid) {
151
+ const aidDir = path.join(aunDir, encodeSegment(localAid));
152
+ try {
153
+ return fs.readdirSync(aidDir, { withFileTypes: true })
154
+ .filter(e => e.isDirectory() && !e.name.startsWith('_'))
155
+ .map(e => decodeDirSegment(e.name));
156
+ }
157
+ catch {
158
+ return [];
159
+ }
160
+ }
161
+ export function readMessages(aunDir, localAid, peerId) {
162
+ const msgPath = path.join(aunDir, encodeSegment(localAid), encodeSegment(peerId), 'messages.jsonl');
163
+ return readAllJsonlLines(msgPath)
164
+ .filter(m => !isTransientProtocolMessage(m));
165
+ }
166
+ function readPeerName(aunDir, localAid, peerId) {
167
+ const activePath = path.join(aunDir, encodeSegment(localAid), encodeSegment(peerId), 'active.json');
168
+ try {
169
+ const data = JSON.parse(fs.readFileSync(activePath, 'utf-8'));
170
+ return data?.metadata?.peerName || null;
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ }
176
+ function encodeSegment(s) {
177
+ return s.replace(/[/%\\:*?"<>|]/g, ch => '%' + ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0'));
178
+ }
179
+ export function loadAidInfo(aunDir, aid) {
180
+ const peers = listPeers(aunDir, aid);
181
+ let totalIn = 0, totalOut = 0;
182
+ for (const peer of peers) {
183
+ const msgs = readMessages(aunDir, aid, peer);
184
+ for (const m of msgs) {
185
+ if (m.dir === 'in')
186
+ totalIn++;
187
+ else
188
+ totalOut++;
189
+ }
190
+ }
191
+ return { aid, totalIn, totalOut, peerCount: peers.length };
192
+ }
193
+ export function loadPeerInfos(aunDir, localAid) {
194
+ const peers = listPeers(aunDir, localAid);
195
+ const infos = [];
196
+ for (const peerId of peers) {
197
+ const msgs = readMessages(aunDir, localAid, peerId);
198
+ let inbound = 0, outbound = 0, lastAt = 0;
199
+ for (const m of msgs) {
200
+ if (m.dir === 'in')
201
+ inbound++;
202
+ else
203
+ outbound++;
204
+ if (m.ts > lastAt)
205
+ lastAt = m.ts;
206
+ }
207
+ const peerName = readPeerName(aunDir, localAid, peerId);
208
+ infos.push({ peerId, peerName, inbound, outbound, lastAt });
209
+ }
210
+ infos.sort((a, b) => b.lastAt - a.lastAt);
211
+ return infos;
212
+ }
213
+ export function loadAllMessages(aunDir, localAid) {
214
+ const peers = listPeers(aunDir, localAid);
215
+ const all = [];
216
+ for (const peer of peers) {
217
+ all.push(...readMessages(aunDir, localAid, peer));
218
+ }
219
+ all.sort((a, b) => a.ts - b.ts);
220
+ if (all.length > 1000)
221
+ return all.slice(-1000);
222
+ return all;
223
+ }
224
+ // ==================== Rendering ====================
225
+ function renderScrollbar(totalLines, visibleLines, offset, height) {
226
+ if (totalLines <= visibleLines)
227
+ return Array(height).fill(' ');
228
+ const thumbSize = Math.max(1, Math.floor(height * visibleLines / totalLines));
229
+ const maxOffset = totalLines - visibleLines;
230
+ const thumbPos = Math.floor((maxOffset - offset) / maxOffset * (height - thumbSize));
231
+ const bar = [];
232
+ for (let i = 0; i < height; i++) {
233
+ bar.push(i >= thumbPos && i < thumbPos + thumbSize ? `${DIM}█${RST}` : `${DIM}░${RST}`);
234
+ }
235
+ return bar;
236
+ }
237
+ function renderScopePanel(state, width, height) {
238
+ const lines = [];
239
+ const title = `${DIM}─ Scope ─${RST}`;
240
+ lines.push(padRight(title, width));
241
+ const isActive = state.activePanel === 'scope';
242
+ for (let i = 0; i < state.localAids.length && lines.length < height; i++) {
243
+ const a = state.localAids[i];
244
+ const sel = isActive && i === state.scopeIndex;
245
+ const chosen = state.selectedLocalAid === a.aid;
246
+ const bg = sel ? BG_SEL : '';
247
+ const marker = sel ? `${bg}${CYAN}${BOLD}▸ ` : (chosen ? `${CYAN} ` : ' ');
248
+ const name = truncate(shortAid(a.aid), width - 4);
249
+ lines.push(padRight(`${marker}${name}${RST}`, width));
250
+ const statsBg = sel ? BG_SEL : '';
251
+ const stats = `${statsBg} ${DIM}↓${a.totalIn} ↑${a.totalOut} peers:${a.peerCount}${RST}`;
252
+ lines.push(padRight(stats, width));
253
+ if (lines.length < height)
254
+ lines.push(padRight('', width));
255
+ }
256
+ while (lines.length < height)
257
+ lines.push(padRight('', width));
258
+ return lines.slice(0, height);
259
+ }
260
+ function renderStatsPanel(state, width, height) {
261
+ const lines = [];
262
+ const title = `${DIM}─ Stats ─${RST}`;
263
+ lines.push(padRight(title, width));
264
+ if (!state.selectedLocalAid) {
265
+ lines.push(padRight(`${DIM} select an AID${RST}`, width));
266
+ while (lines.length < height)
267
+ lines.push(padRight('', width));
268
+ return lines.slice(0, height);
269
+ }
270
+ const isActive = state.activePanel === 'stats';
271
+ const now = Date.now();
272
+ // "All" item at index 0
273
+ const allSel = isActive && state.statsIndex === 0;
274
+ const allBg = allSel ? BG_SEL : '';
275
+ const allMarker = allSel ? `${allBg}${CYAN}${BOLD}▸ ` : ' ';
276
+ lines.push(padRight(`${allMarker}All (${state.peers.length} peers)${RST}`, width));
277
+ if (lines.length < height)
278
+ lines.push(padRight('', width));
279
+ for (let i = 0; i < state.peers.length && lines.length < height; i++) {
280
+ const p = state.peers[i];
281
+ const sel = isActive && state.statsIndex === i + 1;
282
+ const bg = sel ? BG_SEL : '';
283
+ const marker = sel ? `${bg}${CYAN}${BOLD}▸ ` : ' ';
284
+ const displayName = p.peerName || shortAid(p.peerId);
285
+ const name = truncate(displayName, width - 4);
286
+ lines.push(padRight(`${marker}${name}${RST}`, width));
287
+ const detailBg = sel ? BG_SEL : '';
288
+ const ago = p.lastAt ? formatTimeAgo(now - p.lastAt) : '-';
289
+ const detail = `${detailBg} ${DIM}↓${p.inbound} ↑${p.outbound} ${ago}${RST}`;
290
+ lines.push(padRight(detail, width));
291
+ if (lines.length < height)
292
+ lines.push(padRight('', width));
293
+ }
294
+ while (lines.length < height)
295
+ lines.push(padRight('', width));
296
+ return lines.slice(0, height);
297
+ }
298
+ // ==================== Messages Panel ====================
299
+ function renderMessagesPanel(state, width, height) {
300
+ const lines = [];
301
+ const lastTs = state.messages.length > 0 ? state.messages[state.messages.length - 1].ts : 0;
302
+ const lastTimeStr = lastTs ? formatDateTime(lastTs) : '--';
303
+ const title = `${DIM}─ Messages (${state.messages.length}, last: ${lastTimeStr}) ─${RST}`;
304
+ lines.push(padRight(title, width));
305
+ const contentHeight = height - 1;
306
+ const msgs = state.messages;
307
+ const totalMsgs = msgs.length;
308
+ const msgWidth = width - 3;
309
+ const contentLineWidth = msgWidth - 2;
310
+ const maxContentLines = 3;
311
+ // 先构造每条消息的渲染行,从最末尾的可见消息往回收集,直到填满 contentHeight
312
+ function renderOneMsg(m) {
313
+ const time = formatDateTime(m.ts);
314
+ const dir = m.dir === 'in' ? `${GREEN}↓${RST}` : `${BLUE}↑${RST}`;
315
+ const isGroup = m.chatType === 'group';
316
+ const chatTag = isGroup ? `${MAGENTA}[群聊]${RST}` : '';
317
+ const encLabel = m.encrypt ? '密文' : '明文';
318
+ const modeLabel = m.chatmode === 'proactive' ? '自主' : '响应';
319
+ const metaTags = (m.encrypt != null || m.chatmode) ? `${MAGENTA}[${encLabel}|${modeLabel}]${RST}` : '';
320
+ // observer 插话:醒目标记,与对端真实消息区分
321
+ const injectTag = m.source === 'owner-inject' ? `${YELLOW}[插话]${RST}` : '';
322
+ let typeTag = '';
323
+ if (m.dir === 'out' && m.source !== 'owner-inject') {
324
+ const rawSource = m.source;
325
+ // 4 种来源: daemon | ctl | msg | cli
326
+ const source = (rawSource === 'ctl' || rawSource === 'msg' || rawSource === 'cli') ? rawSource : 'daemon';
327
+ const method = m.msgType === 'thought' ? 'thought' : (m.payloadType || m.msgType || 'send');
328
+ typeTag = `${DIM}[${source}|${method}]${RST}`;
329
+ }
330
+ const byteLen = Buffer.byteLength(m.content, 'utf-8');
331
+ const lenTag = `${DIM}${formatNumber(byteLen)}B${RST}`;
332
+ const fromDisplay = isGroup && m.groupId && m.dir === 'in' ? m.groupId : m.from.split('.')[0];
333
+ const toDisplay = isGroup && m.groupId && m.dir === 'out' ? m.groupId : m.to.split('.')[0];
334
+ const header = `${DIM}${time}${RST} ${dir}${chatTag}${injectTag}${metaTags}${typeTag} ${ORANGE}${fromDisplay}${RST}${DIM}→${RST}${GREEN}${toDisplay}${RST} ${lenTag}`;
335
+ const out = [padRight(header, msgWidth)];
336
+ const rawContent = m.content.replace(/\n/g, ' ');
337
+ const wrappedLines = wrapText(rawContent, contentLineWidth, maxContentLines);
338
+ for (const wl of wrappedLines) {
339
+ out.push(padRight(` ${wl}`, msgWidth));
340
+ }
341
+ return out;
342
+ }
343
+ // 从 endIdx-1 开始倒序,往回累积,直到行数填满 contentHeight
344
+ const endIdx = Math.max(0, totalMsgs - state.messageScrollOffset);
345
+ const collected = []; // 每条消息的行数组
346
+ let totalLines = 0;
347
+ let firstShownIdx = endIdx; // 首条可见消息的下标
348
+ for (let i = endIdx - 1; i >= 0; i--) {
349
+ const rendered = renderOneMsg(msgs[i]);
350
+ if (totalLines + rendered.length > contentHeight && collected.length > 0)
351
+ break;
352
+ collected.unshift(rendered);
353
+ totalLines += rendered.length;
354
+ firstShownIdx = i;
355
+ if (totalLines >= contentHeight)
356
+ break;
357
+ }
358
+ const visibleMsgCount = endIdx - firstShownIdx;
359
+ const scrollbar = renderScrollbar(totalMsgs, visibleMsgCount, state.messageScrollOffset, contentHeight);
360
+ // 正序输出(旧→新)
361
+ for (const rendered of collected) {
362
+ for (const line of rendered) {
363
+ if (lines.length - 1 >= contentHeight)
364
+ break;
365
+ const sbIdx = lines.length - 1;
366
+ lines.push(`${line} ${scrollbar[sbIdx] || ' '}`);
367
+ }
368
+ if (lines.length - 1 >= contentHeight)
369
+ break;
370
+ }
371
+ while (lines.length < height) {
372
+ const sbIdx = lines.length - 1;
373
+ lines.push(padRight('', msgWidth) + ` ${scrollbar[sbIdx] || ' '}`);
374
+ }
375
+ return lines.slice(0, height);
376
+ }
377
+ // ==================== Main Render ====================
378
+ function renderFrame(state) {
379
+ const cols = process.stdout.columns || 120;
380
+ const rows = (process.stdout.rows || 40);
381
+ const bodyHeight = rows - 4;
382
+ const leftW = Math.max(20, Math.floor(cols * 0.20));
383
+ const midW = Math.max(24, Math.floor(cols * 0.22));
384
+ const rightW = Math.max(40, cols - leftW - midW - 4);
385
+ const leftLines = renderScopePanel(state, leftW, bodyHeight);
386
+ const midLines = renderStatsPanel(state, midW, bodyHeight);
387
+ const msgLines = renderMessagesPanel(state, rightW, bodyHeight);
388
+ const sep = `${DIM}│${RST}`;
389
+ let buf = '\x1b[H';
390
+ const topBorder = `${DIM}┌${'─'.repeat(leftW)}┬${'─'.repeat(midW)}┬${'─'.repeat(rightW + 1)}┐${RST}`;
391
+ buf += `\x1b[2K${topBorder}\n`;
392
+ for (let i = 0; i < bodyHeight; i++) {
393
+ const l = leftLines[i] || padRight('', leftW);
394
+ const m = midLines[i] || padRight('', midW);
395
+ const r = msgLines[i] || padRight('', rightW);
396
+ buf += `\x1b[2K${sep}${l}${sep}${m}${sep}${r}${sep}\n`;
397
+ }
398
+ const bottomBorder = `${DIM}├${'─'.repeat(leftW)}┴${'─'.repeat(midW)}┴${'─'.repeat(rightW + 1)}┤${RST}`;
399
+ buf += `\x1b[2K${bottomBorder}\n`;
400
+ const helpText = `Tab: panel ↑↓: nav Enter: select Backspace: back ESC: exit`;
401
+ const helpLine = `${DIM}│ ${helpText.slice(0, cols - 4)} ${RST}`;
402
+ buf += `\x1b[2K${helpLine}\n`;
403
+ const closeBorder = `${DIM}└${'─'.repeat(cols - 2)}┘${RST}`;
404
+ buf += `\x1b[2K${closeBorder}`;
405
+ return buf;
406
+ }
407
+ // ==================== Main ====================
408
+ export async function cmdWatchMsg() {
409
+ const aunDir = getSessionsAunDir();
410
+ if (!fs.existsSync(aunDir)) {
411
+ console.log('No session data found.');
412
+ return;
413
+ }
414
+ let watcher = null;
415
+ const state = {
416
+ activePanel: 'scope',
417
+ localAids: [],
418
+ scopeIndex: 0,
419
+ selectedLocalAid: null,
420
+ peers: [],
421
+ statsIndex: 0,
422
+ selectedPeer: null,
423
+ messages: [],
424
+ messageScrollOffset: 0,
425
+ dirty: true,
426
+ };
427
+ function loadScope() {
428
+ const aids = listLocalAids(aunDir);
429
+ state.localAids = aids.map(aid => loadAidInfo(aunDir, aid));
430
+ state.localAids.sort((a, b) => (b.totalIn + b.totalOut) - (a.totalIn + a.totalOut));
431
+ }
432
+ function selectAid(aid) {
433
+ state.selectedLocalAid = aid;
434
+ state.peers = loadPeerInfos(aunDir, aid);
435
+ state.statsIndex = 0;
436
+ state.selectedPeer = null;
437
+ state.messages = loadAllMessages(aunDir, aid);
438
+ state.messageScrollOffset = 0;
439
+ startWatching(aid);
440
+ }
441
+ function selectPeer(peerId) {
442
+ state.selectedPeer = peerId;
443
+ if (!state.selectedLocalAid)
444
+ return;
445
+ if (peerId) {
446
+ state.messages = readMessages(aunDir, state.selectedLocalAid, peerId);
447
+ if (state.messages.length > 1000)
448
+ state.messages = state.messages.slice(-1000);
449
+ }
450
+ else {
451
+ state.messages = loadAllMessages(aunDir, state.selectedLocalAid);
452
+ }
453
+ state.messageScrollOffset = 0;
454
+ }
455
+ function startWatching(aid) {
456
+ if (watcher) {
457
+ watcher.close();
458
+ watcher = null;
459
+ }
460
+ const aidDir = path.join(aunDir, encodeSegment(aid));
461
+ try {
462
+ watcher = fs.watch(aidDir, { recursive: true }, (_, filename) => {
463
+ if (filename && filename.endsWith('messages.jsonl')) {
464
+ refreshData();
465
+ render();
466
+ }
467
+ });
468
+ }
469
+ catch { /* directory may not exist */ }
470
+ }
471
+ function refreshData() {
472
+ if (!state.selectedLocalAid)
473
+ return;
474
+ state.peers = loadPeerInfos(aunDir, state.selectedLocalAid);
475
+ const prevCount = state.messages.length;
476
+ if (state.selectedPeer) {
477
+ state.messages = readMessages(aunDir, state.selectedLocalAid, state.selectedPeer);
478
+ if (state.messages.length > 1000)
479
+ state.messages = state.messages.slice(-1000);
480
+ }
481
+ else {
482
+ state.messages = loadAllMessages(aunDir, state.selectedLocalAid);
483
+ }
484
+ // 有新消息时自动滚到底部
485
+ if (state.messages.length > prevCount) {
486
+ state.messageScrollOffset = 0;
487
+ }
488
+ // Also refresh scope stats for the selected AID
489
+ const idx = state.localAids.findIndex(a => a.aid === state.selectedLocalAid);
490
+ if (idx >= 0) {
491
+ state.localAids[idx] = loadAidInfo(aunDir, state.selectedLocalAid);
492
+ }
493
+ }
494
+ function render() {
495
+ process.stdout.write(renderFrame(state));
496
+ }
497
+ function cleanup() {
498
+ if (watcher) {
499
+ watcher.close();
500
+ watcher = null;
501
+ }
502
+ clearInterval(pollTimer);
503
+ if (process.stdin.isTTY)
504
+ try {
505
+ process.stdin.setRawMode(false);
506
+ }
507
+ catch { }
508
+ process.stdin.pause();
509
+ process.stdout.write('\x1b[?25h\x1b[2J\x1b[H');
510
+ }
511
+ function handleKey(data) {
512
+ // ESC
513
+ if (data[0] === 0x1b && data.length === 1) {
514
+ cleanup();
515
+ process.exit(0);
516
+ }
517
+ // Ctrl+C
518
+ if (data[0] === 0x03) {
519
+ cleanup();
520
+ process.exit(0);
521
+ }
522
+ // Arrow keys
523
+ if (data[0] === 0x1b && data[1] === 0x5b) {
524
+ const code = data[2];
525
+ if (code === 0x41)
526
+ handleUp();
527
+ else if (code === 0x42)
528
+ handleDown();
529
+ else if (code === 0x43)
530
+ handleRight();
531
+ else if (code === 0x44)
532
+ handleLeft();
533
+ else if (code === 0x35)
534
+ handlePageUp(); // Page Up: \x1b[5~
535
+ else if (code === 0x36)
536
+ handlePageDown(); // Page Down: \x1b[6~
537
+ render();
538
+ return;
539
+ }
540
+ // Tab
541
+ if (data[0] === 0x09) {
542
+ handleRight();
543
+ render();
544
+ return;
545
+ }
546
+ // Shift+Tab (some terminals: \x1b[Z)
547
+ if (data[0] === 0x1b && data[1] === 0x5b && data[2] === 0x5a) {
548
+ handleLeft();
549
+ render();
550
+ return;
551
+ }
552
+ // Enter
553
+ if (data[0] === 0x0d) {
554
+ handleEnter();
555
+ render();
556
+ return;
557
+ }
558
+ // Backspace
559
+ if (data[0] === 0x7f || data[0] === 0x08) {
560
+ handleBackspace();
561
+ render();
562
+ return;
563
+ }
564
+ }
565
+ function handleUp() {
566
+ if (state.activePanel === 'scope') {
567
+ state.scopeIndex = Math.max(0, state.scopeIndex - 1);
568
+ }
569
+ else if (state.activePanel === 'stats') {
570
+ state.statsIndex = Math.max(0, state.statsIndex - 1);
571
+ }
572
+ else if (state.activePanel === 'messages') {
573
+ state.messageScrollOffset = Math.min(Math.max(0, state.messages.length - 5), state.messageScrollOffset + 3);
574
+ }
575
+ }
576
+ function handleDown() {
577
+ if (state.activePanel === 'scope') {
578
+ state.scopeIndex = Math.min(state.localAids.length - 1, state.scopeIndex + 1);
579
+ }
580
+ else if (state.activePanel === 'stats') {
581
+ state.statsIndex = Math.min(state.peers.length, state.statsIndex + 1);
582
+ }
583
+ else if (state.activePanel === 'messages') {
584
+ state.messageScrollOffset = Math.max(0, state.messageScrollOffset - 3);
585
+ }
586
+ }
587
+ function handleLeft() {
588
+ if (state.activePanel === 'messages')
589
+ state.activePanel = 'stats';
590
+ else if (state.activePanel === 'stats')
591
+ state.activePanel = 'scope';
592
+ }
593
+ function handleRight() {
594
+ if (state.activePanel === 'scope')
595
+ state.activePanel = 'stats';
596
+ else if (state.activePanel === 'stats')
597
+ state.activePanel = 'messages';
598
+ }
599
+ function handlePageUp() {
600
+ if (state.activePanel === 'messages') {
601
+ const pageSize = (process.stdout.rows || 40) - 6;
602
+ state.messageScrollOffset = Math.min(Math.max(0, state.messages.length - 5), state.messageScrollOffset + pageSize);
603
+ }
604
+ }
605
+ function handlePageDown() {
606
+ if (state.activePanel === 'messages') {
607
+ const pageSize = (process.stdout.rows || 40) - 6;
608
+ state.messageScrollOffset = Math.max(0, state.messageScrollOffset - pageSize);
609
+ }
610
+ }
611
+ function handleEnter() {
612
+ if (state.activePanel === 'scope' && state.localAids.length > 0) {
613
+ const aid = state.localAids[state.scopeIndex];
614
+ selectAid(aid.aid);
615
+ state.activePanel = 'stats';
616
+ }
617
+ else if (state.activePanel === 'stats') {
618
+ if (state.statsIndex === 0) {
619
+ selectPeer(null);
620
+ }
621
+ else {
622
+ const peer = state.peers[state.statsIndex - 1];
623
+ if (peer)
624
+ selectPeer(peer.peerId);
625
+ }
626
+ state.activePanel = 'messages';
627
+ }
628
+ }
629
+ function handleBackspace() {
630
+ if (state.activePanel === 'messages') {
631
+ state.activePanel = 'stats';
632
+ state.messageScrollOffset = 0;
633
+ }
634
+ else if (state.activePanel === 'stats') {
635
+ state.activePanel = 'scope';
636
+ state.selectedLocalAid = null;
637
+ state.peers = [];
638
+ state.messages = [];
639
+ if (watcher) {
640
+ watcher.close();
641
+ watcher = null;
642
+ }
643
+ }
644
+ }
645
+ // ── Init ──
646
+ process.on('SIGINT', () => { cleanup(); process.exit(0); });
647
+ process.on('SIGTERM', () => { cleanup(); process.exit(0); });
648
+ loadScope();
649
+ process.stdout.write('\x1b[?25l\x1b[2J\x1b[H');
650
+ render();
651
+ // 定时轮询:5 秒检查一次,有变化才刷新
652
+ let lastMsgCount = state.messages.length;
653
+ let lastMsgTs = state.messages.length > 0 ? state.messages[state.messages.length - 1].ts : 0;
654
+ const pollTimer = setInterval(() => {
655
+ if (!state.selectedLocalAid)
656
+ return;
657
+ refreshData();
658
+ const newCount = state.messages.length;
659
+ const newTs = newCount > 0 ? state.messages[newCount - 1].ts : 0;
660
+ if (newCount !== lastMsgCount || newTs !== lastMsgTs) {
661
+ lastMsgCount = newCount;
662
+ lastMsgTs = newTs;
663
+ render();
664
+ }
665
+ }, 5000);
666
+ if (process.stdin.isTTY) {
667
+ process.stdin.setRawMode(true);
668
+ process.stdin.resume();
669
+ process.stdin.on('data', handleKey);
670
+ }
671
+ // Keep process alive
672
+ await new Promise(() => { });
673
+ }