@dyyz1993/create-agent 2.1.0 → 2.1.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 (349) hide show
  1. package/package.json +5 -4
  2. package/src/__tests__/cli.test.ts +2 -0
  3. package/src/__tests__/copy.test.ts +110 -122
  4. package/src/__tests__/create-args.test.ts +113 -0
  5. package/src/__tests__/templates.test.ts +29 -3
  6. package/src/__tests__/update.test.ts +129 -0
  7. package/src/cli.ts +30 -32
  8. package/src/commands/create.ts +83 -24
  9. package/src/commands/update.ts +174 -0
  10. package/src/commands/workspace.ts +26 -6
  11. package/src/lib/copy.ts +233 -93
  12. package/src/lib/templates.ts +12 -0
  13. package/templates/agent/.husky/commit-msg +4 -0
  14. package/templates/agent/.husky/pre-commit +11 -0
  15. package/templates/agent/.husky/pre-push +6 -0
  16. package/templates/agent/.prettierignore +6 -0
  17. package/templates/agent/.prettierrc +9 -0
  18. package/templates/agent/CHANGELOG.md +15 -0
  19. package/templates/agent/commitlint.config.js +8 -0
  20. package/templates/agent/package.json +19 -4
  21. package/templates/agent/src/gateway/__tests__/ws-handler-token.test.ts +53 -39
  22. package/templates/agent/src/mainview/App.tsx +14 -12
  23. package/templates/agent/src/mainview/__tests__/hooks/use-rpc-init.test.ts +194 -190
  24. package/templates/agent/src/mainview/components/bash/BashPanel.tsx +210 -189
  25. package/templates/agent/src/mainview/components/chat/ChatPanel.tsx +45 -20
  26. package/templates/agent/src/mainview/components/common/ThemeToggle.tsx +41 -21
  27. package/templates/agent/src/mainview/components/debug/DebugPanel.tsx +181 -114
  28. package/templates/agent/src/mainview/components/debug/__tests__/DebugPanel.test.tsx +80 -80
  29. package/templates/agent/src/mainview/components/diff/__tests__/DiffViewerPanel.test.tsx +61 -58
  30. package/templates/agent/src/mainview/components/feed/FeedPanel.tsx +43 -41
  31. package/templates/agent/src/mainview/components/file-preview/FilePreviewOverlay.tsx +69 -50
  32. package/templates/agent/src/mainview/components/file-preview/VirtualizedCodeView.tsx +31 -18
  33. package/templates/agent/src/mainview/components/git/GitPanel.tsx +731 -490
  34. package/templates/agent/src/mainview/components/git/__tests__/GitPanel.test.tsx +157 -139
  35. package/templates/agent/src/mainview/components/layout/AppLayout.tsx +210 -161
  36. package/templates/agent/src/mainview/components/layout/__tests__/AppLayout.test.tsx +130 -122
  37. package/templates/agent/src/mainview/components/rules/RulesPanel.tsx +119 -109
  38. package/templates/agent/src/mainview/components/search/SearchPanel.tsx +123 -117
  39. package/templates/agent/src/mainview/components/search/__tests__/SearchPanel.test.tsx +64 -44
  40. package/templates/agent/src/mainview/components/sidebar/__tests__/PinButton.test.tsx +38 -38
  41. package/templates/agent/src/mainview/components/todo/TodoPanel.tsx +40 -38
  42. package/templates/agent/src/mainview/components/todo/__tests__/TodoPanel.test.tsx +72 -72
  43. package/templates/agent/src/mainview/lib/i18n/locales/en.json +175 -155
  44. package/templates/agent/src/mainview/lib/i18n/locales/zh.json +173 -155
  45. package/templates/agent/src/mainview/stores/use-app-store.ts +96 -86
  46. package/templates/agent/src/mainview/stores/use-explorer-store.ts +292 -275
  47. package/templates/agent/src/mainview/types/index.ts +23 -22
  48. package/templates/agent/src/mainview/utils/file-icon.tsx +17 -21
  49. package/templates/agent/src/shared/handlers/chat.ts +53 -53
  50. package/templates/agent/src/shared/handlers/debug.ts +13 -3
  51. package/templates/browser-agent/.env.example +19 -0
  52. package/templates/browser-agent/.husky/commit-msg +4 -0
  53. package/templates/browser-agent/.husky/pre-commit +11 -0
  54. package/templates/browser-agent/.husky/pre-push +6 -0
  55. package/templates/browser-agent/.prettierignore +6 -0
  56. package/templates/browser-agent/.prettierrc +9 -0
  57. package/templates/browser-agent/AGENTS.md +396 -0
  58. package/templates/browser-agent/CHANGELOG.md +15 -0
  59. package/templates/browser-agent/LICENSE +21 -0
  60. package/templates/browser-agent/README.md +103 -0
  61. package/templates/browser-agent/commitlint.config.js +8 -0
  62. package/templates/browser-agent/electrobun.config.ts +27 -0
  63. package/templates/browser-agent/electron/main.js +46 -0
  64. package/templates/browser-agent/electron/preload.js +5 -0
  65. package/templates/browser-agent/electron-builder.json +40 -0
  66. package/templates/browser-agent/eslint.config.mjs +79 -0
  67. package/templates/browser-agent/llms.txt +24 -0
  68. package/templates/browser-agent/package.json +140 -0
  69. package/templates/browser-agent/postcss.config.js +6 -0
  70. package/templates/browser-agent/scripts/dev.ts +138 -0
  71. package/templates/browser-agent/src/__tests__/hybrid-mode.test.ts +126 -0
  72. package/templates/browser-agent/src/__tests__/server-config-security.test.ts +55 -0
  73. package/templates/browser-agent/src/__tests__/server-config.test.ts +59 -0
  74. package/templates/browser-agent/src/bun/index.ts +130 -0
  75. package/templates/browser-agent/src/bun/three.d.ts +1 -0
  76. package/templates/browser-agent/src/gateway/http-routes.ts +1 -0
  77. package/templates/browser-agent/src/gateway/ipc-transport.ts +68 -0
  78. package/templates/browser-agent/src/gateway/sse-transport.ts +221 -0
  79. package/templates/browser-agent/src/mainview/App.tsx +45 -0
  80. package/templates/browser-agent/src/mainview/__tests__/hooks/use-rpc-init.test.ts +202 -0
  81. package/templates/browser-agent/src/mainview/__tests__/hooks/use-sidebar-resize.test.ts +127 -0
  82. package/templates/browser-agent/src/mainview/__tests__/i18n/i18n.test.ts +49 -0
  83. package/templates/browser-agent/src/mainview/__tests__/setup.ts +40 -0
  84. package/templates/browser-agent/src/mainview/__tests__/stores/use-chat-store.test.ts +73 -0
  85. package/templates/browser-agent/src/mainview/__tests__/stores/use-sidebar-store.test.ts +61 -0
  86. package/templates/browser-agent/src/mainview/__tests__/theme-variables.test.ts +36 -0
  87. package/templates/browser-agent/src/mainview/components/assets/AssetsPanel.tsx +139 -0
  88. package/templates/browser-agent/src/mainview/components/chat/ChatPanel.tsx +219 -0
  89. package/templates/browser-agent/src/mainview/components/chat/CommandBar.tsx +184 -0
  90. package/templates/browser-agent/src/mainview/components/chat/MessageBubble.tsx +249 -0
  91. package/templates/browser-agent/src/mainview/components/chat/ToolPicker.tsx +115 -0
  92. package/templates/browser-agent/src/mainview/components/common/ErrorBoundary.tsx +1 -0
  93. package/templates/browser-agent/src/mainview/components/common/LanguageSwitcher.tsx +15 -0
  94. package/templates/browser-agent/src/mainview/components/common/ThemeToggle.tsx +45 -0
  95. package/templates/browser-agent/src/mainview/components/common/__tests__/ErrorBoundary.test.tsx +74 -0
  96. package/templates/browser-agent/src/mainview/components/common/__tests__/LanguageSwitcher.test.tsx +44 -0
  97. package/templates/browser-agent/src/mainview/components/common/__tests__/ThemeToggle.test.tsx +41 -0
  98. package/templates/browser-agent/src/mainview/components/dev/NetworkPanel.tsx +155 -0
  99. package/templates/browser-agent/src/mainview/components/layout/AppLayout.tsx +311 -0
  100. package/templates/browser-agent/src/mainview/components/onboarding/SetupWizard.tsx +310 -0
  101. package/templates/browser-agent/src/mainview/components/process/ProcessPanel.tsx +329 -0
  102. package/templates/browser-agent/src/mainview/components/sidebar/SessionSidebar.tsx +122 -0
  103. package/templates/browser-agent/src/mainview/components/sidebar/SkillSidebar.tsx +115 -0
  104. package/templates/browser-agent/src/mainview/components/topbar/TopBar.tsx +350 -0
  105. package/templates/browser-agent/src/mainview/global.d.ts +13 -0
  106. package/templates/browser-agent/src/mainview/hooks/__tests__/use-breakpoint.test.ts +151 -0
  107. package/templates/browser-agent/src/mainview/hooks/use-agent-chat.ts +157 -0
  108. package/templates/browser-agent/src/mainview/hooks/use-breakpoint.ts +68 -0
  109. package/templates/browser-agent/src/mainview/hooks/use-rpc-init.ts +71 -0
  110. package/templates/browser-agent/src/mainview/hooks/use-sidebar-resize.ts +40 -0
  111. package/templates/browser-agent/src/mainview/index.css +71 -0
  112. package/templates/browser-agent/src/mainview/index.html +12 -0
  113. package/templates/browser-agent/src/mainview/lib/api-client.ts +397 -0
  114. package/templates/browser-agent/src/mainview/lib/i18n/index.ts +30 -0
  115. package/templates/browser-agent/src/mainview/lib/i18n/locales/en.json +130 -0
  116. package/templates/browser-agent/src/mainview/lib/i18n/locales/zh.json +128 -0
  117. package/templates/browser-agent/src/mainview/lib/network-bus.ts +92 -0
  118. package/templates/browser-agent/src/mainview/lib/rpc-cache.ts +94 -0
  119. package/templates/browser-agent/src/mainview/main.tsx +18 -0
  120. package/templates/browser-agent/src/mainview/stores/__tests__/use-connection-store.test.ts +26 -0
  121. package/templates/browser-agent/src/mainview/stores/__tests__/use-locale-store.test.ts +32 -0
  122. package/templates/browser-agent/src/mainview/stores/__tests__/use-log-store.test.ts +28 -0
  123. package/templates/browser-agent/src/mainview/stores/__tests__/use-theme-store.test.ts +59 -0
  124. package/templates/browser-agent/src/mainview/stores/message-batcher.ts +25 -0
  125. package/templates/browser-agent/src/mainview/stores/use-asset-store.ts +65 -0
  126. package/templates/browser-agent/src/mainview/stores/use-chat-store.ts +200 -0
  127. package/templates/browser-agent/src/mainview/stores/use-connection-store.ts +173 -0
  128. package/templates/browser-agent/src/mainview/stores/use-locale-store.ts +27 -0
  129. package/templates/browser-agent/src/mainview/stores/use-log-store.ts +16 -0
  130. package/templates/browser-agent/src/mainview/stores/use-network-panel-store.ts +18 -0
  131. package/templates/browser-agent/src/mainview/stores/use-record-store.ts +147 -0
  132. package/templates/browser-agent/src/mainview/stores/use-session-store.ts +151 -0
  133. package/templates/browser-agent/src/mainview/stores/use-sidebar-store.ts +161 -0
  134. package/templates/browser-agent/src/mainview/stores/use-theme-store.ts +46 -0
  135. package/templates/browser-agent/src/mainview/stores/use-view-store.ts +20 -0
  136. package/templates/browser-agent/src/mainview/types/index.ts +6 -0
  137. package/templates/browser-agent/src/server-config.ts +45 -0
  138. package/templates/browser-agent/src/server.ts +78 -0
  139. package/templates/browser-agent/src/shared/handlers/__tests__/chat-concurrency.test.ts +127 -0
  140. package/templates/browser-agent/src/shared/handlers/__tests__/chat-handler.test.ts +77 -0
  141. package/templates/browser-agent/src/shared/handlers/__tests__/file-handler.test.ts +100 -0
  142. package/templates/browser-agent/src/shared/handlers/__tests__/system-handler.test.ts +55 -0
  143. package/templates/browser-agent/src/shared/handlers/__tests__/timer-handler.test.ts +77 -0
  144. package/templates/browser-agent/src/shared/handlers/browser.ts +596 -0
  145. package/templates/browser-agent/src/shared/handlers/chat.ts +213 -0
  146. package/templates/browser-agent/src/shared/handlers/file.ts +99 -0
  147. package/templates/browser-agent/src/shared/handlers/index.ts +7 -0
  148. package/templates/browser-agent/src/shared/handlers/session.ts +167 -0
  149. package/templates/browser-agent/src/shared/handlers/system.ts +27 -0
  150. package/templates/browser-agent/src/shared/handlers/timer.ts +34 -0
  151. package/templates/browser-agent/src/shared/http-routes.ts +437 -0
  152. package/templates/browser-agent/src/shared/lib/__tests__/logger.test.ts +92 -0
  153. package/templates/browser-agent/src/shared/lib/__tests__/path-security.test.ts +77 -0
  154. package/templates/browser-agent/src/shared/lib/__tests__/web-server.test.ts +203 -0
  155. package/templates/browser-agent/src/shared/lib/agent.ts +384 -0
  156. package/templates/browser-agent/src/shared/lib/cdp.ts +448 -0
  157. package/templates/browser-agent/src/shared/lib/generate.ts +111 -0
  158. package/templates/browser-agent/src/shared/lib/logger.ts +152 -0
  159. package/templates/browser-agent/src/shared/lib/mock-stream.ts +147 -0
  160. package/templates/browser-agent/src/shared/lib/path-security.ts +38 -0
  161. package/templates/browser-agent/src/shared/lib/port-registry.ts +103 -0
  162. package/templates/browser-agent/src/shared/lib/web-server.ts +127 -0
  163. package/templates/browser-agent/src/shared/lib/xhs-extract.ts +71 -0
  164. package/templates/browser-agent/src/shared/modules/browser.ts +86 -0
  165. package/templates/browser-agent/src/shared/modules/chat.ts +20 -0
  166. package/templates/browser-agent/src/shared/modules/file.ts +40 -0
  167. package/templates/browser-agent/src/shared/modules/session.ts +55 -0
  168. package/templates/browser-agent/src/shared/modules/system.ts +8 -0
  169. package/templates/browser-agent/src/shared/modules/timer.ts +11 -0
  170. package/templates/browser-agent/src/shared/register-all-handlers.ts +36 -0
  171. package/templates/browser-agent/src/shared/rpc-schema.ts +34 -0
  172. package/templates/browser-agent/tailwind.config.js +15 -0
  173. package/templates/browser-agent/tsconfig.ipc.json +14 -0
  174. package/templates/browser-agent/tsconfig.json +36 -0
  175. package/templates/browser-agent/vite.config.ts +3 -0
  176. package/templates/browser-agent/vitest.config.ts +3 -0
  177. package/templates/chat/.husky/commit-msg +4 -0
  178. package/templates/chat/.husky/pre-commit +11 -0
  179. package/templates/chat/.husky/pre-push +6 -0
  180. package/templates/chat/CHANGELOG.md +15 -0
  181. package/templates/chat/commitlint.config.js +8 -0
  182. package/templates/chat/package.json +19 -4
  183. package/templates/chat/src/mainview/__tests__/hooks/use-input-history.test.ts +125 -0
  184. package/templates/chat/src/mainview/__tests__/setup.ts +32 -29
  185. package/templates/chat/src/mainview/components/chat/ChatPanel.tsx +80 -55
  186. package/templates/chat/src/mainview/components/common/ThemeToggle.tsx +40 -20
  187. package/templates/chat/src/mainview/lib/i18n/locales/en.json +175 -155
  188. package/templates/chat/src/mainview/lib/i18n/locales/zh.json +173 -155
  189. package/templates/chat/src/shared/handlers/chat.ts +17 -19
  190. package/templates/chat/src/shared/handlers/debug.ts +12 -2
  191. package/templates/cowork/.env.example +8 -0
  192. package/templates/cowork/.prettierignore +6 -0
  193. package/templates/cowork/.prettierrc +9 -0
  194. package/templates/cowork/AGENTS.md +236 -0
  195. package/templates/cowork/CHANGELOG.md +15 -0
  196. package/templates/cowork/LICENSE +21 -0
  197. package/templates/cowork/README.md +103 -0
  198. package/templates/cowork/commitlint.config.js +8 -0
  199. package/templates/cowork/docs/CODE-VIEW-PLAN.md +637 -0
  200. package/templates/cowork/docs/CODE-VIEW-V2.md +196 -0
  201. package/templates/cowork/docs/CODE-VIEW-V4.md +150 -0
  202. package/templates/cowork/electrobun.config.ts +27 -0
  203. package/templates/cowork/eslint.config.mjs +79 -0
  204. package/templates/cowork/llms.txt +24 -0
  205. package/templates/cowork/package.json +87 -0
  206. package/templates/cowork/postcss.config.js +6 -0
  207. package/templates/cowork/scripts/dev.ts +138 -0
  208. package/templates/cowork/src/__tests__/hybrid-mode.test.ts +126 -0
  209. package/templates/cowork/src/__tests__/server-config-security.test.ts +55 -0
  210. package/templates/cowork/src/__tests__/server-config.test.ts +59 -0
  211. package/templates/cowork/src/bun/index.ts +130 -0
  212. package/templates/cowork/src/bun/three.d.ts +1 -0
  213. package/templates/cowork/src/gateway/http-routes.ts +1 -0
  214. package/templates/cowork/src/gateway/ipc-transport.ts +68 -0
  215. package/templates/cowork/src/gateway/sse-transport.ts +231 -0
  216. package/templates/cowork/src/mainview/App.tsx +45 -0
  217. package/templates/cowork/src/mainview/__tests__/hooks/use-rpc-init.test.ts +202 -0
  218. package/templates/cowork/src/mainview/__tests__/hooks/use-sidebar-resize.test.ts +127 -0
  219. package/templates/cowork/src/mainview/__tests__/i18n/i18n.test.ts +49 -0
  220. package/templates/cowork/src/mainview/__tests__/setup.ts +40 -0
  221. package/templates/cowork/src/mainview/__tests__/stores/use-chat-store.test.ts +73 -0
  222. package/templates/cowork/src/mainview/__tests__/stores/use-sidebar-store.test.ts +61 -0
  223. package/templates/cowork/src/mainview/__tests__/theme-variables.test.ts +36 -0
  224. package/templates/cowork/src/mainview/components/chat/TaskChat.tsx +311 -0
  225. package/templates/cowork/src/mainview/components/chat/__tests__/localhost-links.test.ts +76 -0
  226. package/templates/cowork/src/mainview/components/common/ErrorBoundary.tsx +1 -0
  227. package/templates/cowork/src/mainview/components/common/LanguageSwitcher.tsx +15 -0
  228. package/templates/cowork/src/mainview/components/common/ThemeToggle.tsx +45 -0
  229. package/templates/cowork/src/mainview/components/common/__tests__/ErrorBoundary.test.tsx +74 -0
  230. package/templates/cowork/src/mainview/components/common/__tests__/LanguageSwitcher.test.tsx +44 -0
  231. package/templates/cowork/src/mainview/components/common/__tests__/ThemeToggle.test.tsx +41 -0
  232. package/templates/cowork/src/mainview/components/dev/NetworkPanel.tsx +155 -0
  233. package/templates/cowork/src/mainview/components/layout/AppLayout.tsx +216 -0
  234. package/templates/cowork/src/mainview/components/right/ArtifactsPanel.tsx +54 -0
  235. package/templates/cowork/src/mainview/components/right/ContextPanel.tsx +133 -0
  236. package/templates/cowork/src/mainview/components/right/ElementPicker.tsx +206 -0
  237. package/templates/cowork/src/mainview/components/right/PreviewBlock.tsx +155 -0
  238. package/templates/cowork/src/mainview/components/right/ProgressPanel.tsx +85 -0
  239. package/templates/cowork/src/mainview/components/sidebar/TaskSidebar.tsx +211 -0
  240. package/templates/cowork/src/mainview/components/topbar/TopBar.tsx +86 -0
  241. package/templates/cowork/src/mainview/global.d.ts +13 -0
  242. package/templates/cowork/src/mainview/hooks/__tests__/use-breakpoint.test.ts +123 -0
  243. package/templates/cowork/src/mainview/hooks/use-breakpoint.ts +53 -0
  244. package/templates/cowork/src/mainview/hooks/use-rpc-init.ts +26 -0
  245. package/templates/cowork/src/mainview/hooks/use-sidebar-resize.ts +40 -0
  246. package/templates/cowork/src/mainview/index.css +89 -0
  247. package/templates/cowork/src/mainview/index.html +12 -0
  248. package/templates/cowork/src/mainview/lib/api-client.ts +404 -0
  249. package/templates/cowork/src/mainview/lib/i18n/index.ts +30 -0
  250. package/templates/cowork/src/mainview/lib/i18n/locales/en.json +130 -0
  251. package/templates/cowork/src/mainview/lib/i18n/locales/zh.json +128 -0
  252. package/templates/cowork/src/mainview/lib/network-bus.ts +92 -0
  253. package/templates/cowork/src/mainview/lib/rpc-cache.ts +94 -0
  254. package/templates/cowork/src/mainview/main.tsx +18 -0
  255. package/templates/cowork/src/mainview/stores/__tests__/use-connection-store.test.ts +26 -0
  256. package/templates/cowork/src/mainview/stores/__tests__/use-locale-store.test.ts +32 -0
  257. package/templates/cowork/src/mainview/stores/__tests__/use-log-store.test.ts +28 -0
  258. package/templates/cowork/src/mainview/stores/__tests__/use-preview-store.test.ts +193 -0
  259. package/templates/cowork/src/mainview/stores/__tests__/use-sidebar-store.test.ts +81 -0
  260. package/templates/cowork/src/mainview/stores/__tests__/use-theme-store.test.ts +59 -0
  261. package/templates/cowork/src/mainview/stores/message-batcher.ts +25 -0
  262. package/templates/cowork/src/mainview/stores/use-chat-store.ts +198 -0
  263. package/templates/cowork/src/mainview/stores/use-connection-store.ts +168 -0
  264. package/templates/cowork/src/mainview/stores/use-context-store.ts +68 -0
  265. package/templates/cowork/src/mainview/stores/use-locale-store.ts +27 -0
  266. package/templates/cowork/src/mainview/stores/use-log-store.ts +16 -0
  267. package/templates/cowork/src/mainview/stores/use-network-panel-store.ts +18 -0
  268. package/templates/cowork/src/mainview/stores/use-output-store.ts +47 -0
  269. package/templates/cowork/src/mainview/stores/use-preview-store.ts +97 -0
  270. package/templates/cowork/src/mainview/stores/use-sidebar-store.ts +272 -0
  271. package/templates/cowork/src/mainview/stores/use-task-store.ts +86 -0
  272. package/templates/cowork/src/mainview/stores/use-theme-store.ts +46 -0
  273. package/templates/cowork/src/mainview/stores/use-view-store.ts +29 -0
  274. package/templates/cowork/src/mainview/types/index.ts +6 -0
  275. package/templates/cowork/src/server-config.ts +44 -0
  276. package/templates/cowork/src/server.ts +78 -0
  277. package/templates/cowork/src/shared/handlers/__tests__/chat-concurrency.test.ts +127 -0
  278. package/templates/cowork/src/shared/handlers/__tests__/chat-handler.test.ts +77 -0
  279. package/templates/cowork/src/shared/handlers/__tests__/file-handler.test.ts +100 -0
  280. package/templates/cowork/src/shared/handlers/__tests__/preview-handler.test.ts +172 -0
  281. package/templates/cowork/src/shared/handlers/__tests__/system-handler.test.ts +55 -0
  282. package/templates/cowork/src/shared/handlers/__tests__/timer-handler.test.ts +77 -0
  283. package/templates/cowork/src/shared/handlers/chat.ts +213 -0
  284. package/templates/cowork/src/shared/handlers/context.ts +72 -0
  285. package/templates/cowork/src/shared/handlers/file.ts +99 -0
  286. package/templates/cowork/src/shared/handlers/index.ts +9 -0
  287. package/templates/cowork/src/shared/handlers/output.ts +59 -0
  288. package/templates/cowork/src/shared/handlers/preview.ts +81 -0
  289. package/templates/cowork/src/shared/handlers/system.ts +27 -0
  290. package/templates/cowork/src/shared/handlers/task.ts +101 -0
  291. package/templates/cowork/src/shared/handlers/timer.ts +34 -0
  292. package/templates/cowork/src/shared/http-routes.ts +444 -0
  293. package/templates/cowork/src/shared/lib/__tests__/logger.test.ts +92 -0
  294. package/templates/cowork/src/shared/lib/__tests__/path-security.test.ts +77 -0
  295. package/templates/cowork/src/shared/lib/__tests__/web-server.test.ts +203 -0
  296. package/templates/cowork/src/shared/lib/logger.ts +152 -0
  297. package/templates/cowork/src/shared/lib/path-security.ts +38 -0
  298. package/templates/cowork/src/shared/lib/port-registry.ts +103 -0
  299. package/templates/cowork/src/shared/lib/web-server.ts +127 -0
  300. package/templates/cowork/src/shared/modules/chat.ts +20 -0
  301. package/templates/cowork/src/shared/modules/context.ts +32 -0
  302. package/templates/cowork/src/shared/modules/file.ts +40 -0
  303. package/templates/cowork/src/shared/modules/output.ts +20 -0
  304. package/templates/cowork/src/shared/modules/preview.ts +44 -0
  305. package/templates/cowork/src/shared/modules/system.ts +8 -0
  306. package/templates/cowork/src/shared/modules/task.ts +31 -0
  307. package/templates/cowork/src/shared/modules/timer.ts +11 -0
  308. package/templates/cowork/src/shared/register-all-handlers.ts +36 -0
  309. package/templates/cowork/src/shared/rpc-schema.ts +38 -0
  310. package/templates/cowork/tailwind.config.js +15 -0
  311. package/templates/cowork/test-upload.txt +0 -0
  312. package/templates/cowork/tsconfig.ipc.json +14 -0
  313. package/templates/cowork/tsconfig.json +36 -0
  314. package/templates/cowork/vite.config.ts +3 -0
  315. package/templates/cowork/vitest.config.ts +3 -0
  316. package/templates/general/.husky/commit-msg +4 -0
  317. package/templates/general/.husky/pre-commit +11 -0
  318. package/templates/general/.husky/pre-push +6 -0
  319. package/templates/general/CHANGELOG.md +15 -0
  320. package/templates/general/commitlint.config.js +8 -0
  321. package/templates/general/package.json +19 -4
  322. package/templates/general/src/mainview/__tests__/hooks/use-input-history.test.ts +125 -0
  323. package/templates/general/src/mainview/__tests__/setup.ts +32 -29
  324. package/templates/general/src/mainview/components/chat/ChatPanel.tsx +80 -55
  325. package/templates/general/src/mainview/components/common/ThemeToggle.tsx +40 -20
  326. package/templates/general/src/mainview/components/debug/DebugPanel.tsx +170 -156
  327. package/templates/general/src/mainview/components/debug/__tests__/DebugPanel.test.tsx +169 -0
  328. package/templates/general/src/mainview/components/explorer/ConfirmDialog.tsx +42 -42
  329. package/templates/general/src/mainview/components/explorer/ContextMenu.tsx +72 -67
  330. package/templates/general/src/mainview/components/feed/FeedPanel.tsx +7 -5
  331. package/templates/general/src/mainview/components/file-preview/FilePreviewOverlay.tsx +64 -45
  332. package/templates/general/src/mainview/components/file-preview/VirtualizedCodeView.tsx +24 -7
  333. package/templates/general/src/mainview/components/git/GitPanel.tsx +700 -473
  334. package/templates/general/src/mainview/components/layout/AppLayout.tsx +123 -114
  335. package/templates/general/src/mainview/components/search/SearchPanel.tsx +15 -19
  336. package/templates/general/src/mainview/lib/i18n/locales/en.json +175 -155
  337. package/templates/general/src/mainview/lib/i18n/locales/zh.json +173 -155
  338. package/templates/general/src/mainview/stores/__tests__/use-explorer-store.test.ts +259 -0
  339. package/templates/general/src/mainview/stores/__tests__/use-feed-store.test.ts +160 -0
  340. package/templates/general/src/mainview/stores/__tests__/use-git-store.test.ts +313 -0
  341. package/templates/general/src/mainview/stores/__tests__/use-notification-store.test.ts +115 -0
  342. package/templates/general/src/mainview/stores/__tests__/use-sidebar-store.test.ts +120 -0
  343. package/templates/general/src/mainview/stores/use-explorer-store.ts +277 -260
  344. package/templates/general/src/mainview/types/index.ts +21 -20
  345. package/templates/general/src/shared/handlers/chat.ts +1 -1
  346. package/templates/general/src/shared/handlers/debug.ts +12 -2
  347. package/templates/shared/components/ErrorBoundary.tsx +0 -1
  348. package/templates/shared/vite-base.config.ts +8 -7
  349. /package/templates/{shared → browser-agent}/test-upload.txt +0 -0
@@ -0,0 +1,448 @@
1
+ /**
2
+ * xbrowser 采集编排 — 通用网页采集流程
3
+ *
4
+ * 使用 xbrowser CLI 操作浏览器(对应 PRD §6.2 Checklist):
5
+ * 启动浏览器 → 打开页面 → 采集内容 → 下载图片 → 截图 → 生成文件 → 打包 ZIP
6
+ */
7
+
8
+ import { spawn } from "child_process";
9
+ import { statSync } from "fs";
10
+ import { join } from "path";
11
+ import { tmpdir } from "os";
12
+ import { mkdirSync } from "fs";
13
+
14
+ import {
15
+ toCSV,
16
+ toJSON,
17
+ toMarkdownReport,
18
+ packZip,
19
+ writeFile,
20
+ type NoteItem,
21
+ type Summary,
22
+ } from "./generate";
23
+ import { XHS_EXTRACT_EXPR } from "./xhs-extract";
24
+
25
+ const XBROWSER_CMD = process.env.XBROWSER_CMD || "/usr/local/bin/xbrowser";
26
+ const CDP_ENDPOINT = process.env.CDP_ENDPOINT || "http://localhost:9221";
27
+
28
+ export interface ScrapeResult {
29
+ notes: NoteItem[];
30
+ summary: Summary;
31
+ assets: any[];
32
+ steps: { label: string; status: string; detail?: string }[];
33
+ }
34
+
35
+ export type ProgressFn = (steps: { label: string; status: string; detail?: string }[]) => void;
36
+
37
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
38
+
39
+ // ===== xbrowser CLI 调用 =====
40
+
41
+ export async function xbrowserCli(args: string[], useCdp = true): Promise<any> {
42
+ const allArgs = useCdp
43
+ ? [...args, "--cdp", CDP_ENDPOINT, "--json"]
44
+ : [...args, "--json"];
45
+ return new Promise((resolve, reject) => {
46
+ const child = spawn(XBROWSER_CMD, allArgs, {
47
+ stdio: ["ignore", "pipe", "pipe"],
48
+ env: { ...process.env, NODE_OPTIONS: "" },
49
+ });
50
+
51
+ const chunks: Buffer[] = [];
52
+ child.stdout.on("data", (d: Buffer) => chunks.push(d));
53
+
54
+ const timeout = setTimeout(() => {
55
+ child.kill("SIGTERM");
56
+ reject(new Error("xbrowser 超时 (75s)"));
57
+ }, 75000);
58
+
59
+ child.on("error", (err) => {
60
+ clearTimeout(timeout);
61
+ reject(err);
62
+ });
63
+
64
+ child.on("close", () => {
65
+ clearTimeout(timeout);
66
+ const stdout = Buffer.concat(chunks as any).toString("utf8").trim();
67
+ const firstBrace = stdout.indexOf("{");
68
+ const lastBrace = stdout.lastIndexOf("}");
69
+ if (firstBrace >= 0 && lastBrace > firstBrace) {
70
+ const jsonStr = stdout.slice(firstBrace, lastBrace + 1);
71
+ try {
72
+ resolve(JSON.parse(jsonStr));
73
+ return;
74
+ } catch {}
75
+ }
76
+ reject(new Error(`xbrowser 输出解析失败: ${stdout.slice(0, 300)}`));
77
+ });
78
+ });
79
+ }
80
+
81
+ // ===== 下载封面图片 =====
82
+
83
+ async function downloadCoverImages(
84
+ notes: NoteItem[],
85
+ dir: string,
86
+ sessionId: string,
87
+ taskId: string,
88
+ onProgress: (current: number, total: number, success: number) => void,
89
+ ): Promise<any[]> {
90
+ const assets: any[] = [];
91
+ const coverUrls = notes.map((n) => n.coverUrl).filter(Boolean);
92
+ if (coverUrls.length === 0) return assets;
93
+
94
+ let successCount = 0;
95
+ for (let i = 0; i < coverUrls.length; i++) {
96
+ const url = coverUrls[i];
97
+ if (!url) continue;
98
+ try {
99
+ const response = await fetch(url, {
100
+ headers: {
101
+ Referer: "https://www.xiaohongshu.com/",
102
+ "User-Agent":
103
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
104
+ },
105
+ signal: AbortSignal.timeout(15000),
106
+ } as RequestInit);
107
+
108
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
109
+
110
+ const buffer = Buffer.from(await response.arrayBuffer());
111
+ const contentType = response.headers.get("content-type") || "image/webp";
112
+ const ext = contentType.includes("png")
113
+ ? "png"
114
+ : contentType.includes("jpeg") || contentType.includes("jpg")
115
+ ? "jpg"
116
+ : "webp";
117
+ const name = `xhs-img-${String(i + 1).padStart(3, "0")}.${ext}`;
118
+ const { path: fp, size } = writeFile(dir, name, buffer);
119
+
120
+ assets.push({
121
+ id: `ast_${Date.now().toString(36)}${i.toString(36)}`,
122
+ kind: "image",
123
+ name,
124
+ size,
125
+ mime: contentType,
126
+ url,
127
+ path: fp,
128
+ source: {
129
+ pageUrl: "",
130
+ sessionId,
131
+ taskId,
132
+ browserConn: "",
133
+ createdAt: Date.now(),
134
+ },
135
+ });
136
+ successCount++;
137
+ } catch (err: any) {
138
+ assets.push({
139
+ id: `ast_${Date.now().toString(36)}${i.toString(36)}`,
140
+ kind: "image",
141
+ name: `xhs-img-url-${String(i + 1).padStart(3, "0")}.txt`,
142
+ mime: "text/plain",
143
+ url,
144
+ source: {
145
+ pageUrl: "",
146
+ sessionId,
147
+ taskId,
148
+ browserConn: "",
149
+ createdAt: Date.now(),
150
+ },
151
+ });
152
+ }
153
+ onProgress(i + 1, coverUrls.length, successCount);
154
+ if (i < coverUrls.length - 1) await sleep(200);
155
+ }
156
+
157
+ return assets;
158
+ }
159
+
160
+ // ===== 会话目录 =====
161
+
162
+ function sessionDir(sessionId: string): string {
163
+ const dir = join(tmpdir(), "browser-agent-assets", sessionId);
164
+ mkdirSync(dir, { recursive: true });
165
+ return dir;
166
+ }
167
+
168
+ // ===== 采集主流程 =====
169
+
170
+ export async function scrapeXhs(
171
+ _pluginId: string,
172
+ sessionId: string,
173
+ taskId: string,
174
+ browserConn: string,
175
+ onProgress: ProgressFn,
176
+ opts: {
177
+ url?: string;
178
+ aiSummary?: (prompt: string) => Promise<string>;
179
+ } = {},
180
+ ): Promise<ScrapeResult> {
181
+ const dir = sessionDir(sessionId);
182
+ const startMs = Date.now();
183
+ const targetUrl = opts.url || "https://www.xiaohongshu.com/explore";
184
+
185
+ const steps: { label: string; status: string; detail?: string }[] = [
186
+ { label: "启动浏览器", status: "pending" },
187
+ { label: "打开目标页面", status: "pending" },
188
+ { label: "采集笔记列表", status: "pending" },
189
+ { label: "下载封面图片", status: "pending" },
190
+ { label: "截图存档", status: "pending" },
191
+ { label: "生成 CSV / JSON / 报告", status: "pending" },
192
+ { label: "打包 ZIP", status: "pending" },
193
+ ];
194
+
195
+ const step = (i: number, status: string, detail?: string) => {
196
+ steps[i] = { ...steps[i]!, status, detail };
197
+ onProgress(steps);
198
+ };
199
+
200
+ let pageUrl = targetUrl;
201
+ let notes: NoteItem[] = [];
202
+ let screenshotAsset: any | undefined;
203
+ let imageAssets: any[] = [];
204
+ let fileAssets: any[] = [];
205
+ let zipAssets: any[] = [];
206
+
207
+ try {
208
+ // 1. 检查 xbrowser
209
+ step(0, "running", "使用 xbrowser 引擎...");
210
+ step(0, "done", "xbrowser 就绪");
211
+
212
+ // 2. 打开页面 + 截图(链式调用)
213
+ step(1, "running", `正在加载: ${targetUrl}`);
214
+ step(4, "running", "等待页面加载完成后截图...");
215
+
216
+ const escapedUrl = targetUrl.replace(/"/g, '\\"');
217
+ const chainCmd = `goto "${escapedUrl}" && screenshot --full-page --base64`;
218
+ const chainResult = await xbrowserCli([chainCmd]);
219
+
220
+ if (!chainResult?.success && !chainResult?.steps) {
221
+ const errMsg = chainResult?.data?.error || "页面加载失败";
222
+ step(1, "error", errMsg);
223
+ return {
224
+ notes: [],
225
+ summary: {
226
+ noteCount: 0,
227
+ imageCount: 0,
228
+ successRate: "0%",
229
+ durationMs: Date.now() - startMs,
230
+ },
231
+ assets: [],
232
+ steps,
233
+ };
234
+ }
235
+
236
+ const steps0 = chainResult.steps || [];
237
+ let screenshotData: string | null = null;
238
+ for (const s of steps0) {
239
+ if (s.command?.startsWith("screenshot") && s.success && s.data?.data) {
240
+ screenshotData = s.data.data;
241
+ }
242
+ }
243
+ pageUrl = targetUrl;
244
+ step(1, "done", `页面已加载: ${pageUrl}`);
245
+
246
+ // 3. 截图存档
247
+ step(4, "running");
248
+ if (screenshotData) {
249
+ const name = `xhs-screenshot-${Date.now()}.png`;
250
+ const { path: fp, size } = writeFile(
251
+ dir,
252
+ name,
253
+ Buffer.from(screenshotData, "base64"),
254
+ );
255
+ screenshotAsset = {
256
+ id: `ast_${Date.now().toString(36)}`,
257
+ kind: "screenshot",
258
+ name,
259
+ size,
260
+ mime: "image/png",
261
+ dataUrl: "data:image/png;base64," + screenshotData.slice(0, 2000),
262
+ path: fp,
263
+ source: {
264
+ pageUrl,
265
+ sessionId,
266
+ taskId,
267
+ browserConn,
268
+ createdAt: Date.now(),
269
+ },
270
+ };
271
+ step(4, "done", "截图完成");
272
+ } else {
273
+ step(4, "error", "截图返回为空");
274
+ }
275
+
276
+ // 4. eval 提取数据
277
+ step(2, "running", "执行数据提取...");
278
+ const evalResult = await xbrowserCli(["eval", XHS_EXTRACT_EXPR]);
279
+
280
+ if (evalResult?.success && evalResult.data?.result) {
281
+ try {
282
+ const parsed = JSON.parse(evalResult.data.result);
283
+ const raw: any[] = parsed.notes || [];
284
+ notes = raw
285
+ .filter((n: any) => n.noteUrl || n.coverUrl)
286
+ .map((n: any) => ({
287
+ title: n.title || "",
288
+ author: n.author || "",
289
+ noteUrl: n.noteUrl || pageUrl,
290
+ coverUrl: n.coverUrl || "",
291
+ likes: n.likes || "",
292
+ }));
293
+ } catch {}
294
+ }
295
+
296
+ if (notes.length === 0) {
297
+ step(2, "error", "未提取到笔记数据");
298
+ } else {
299
+ step(2, "done", `提取到 ${notes.length} 条笔记`);
300
+ }
301
+
302
+ // 5. 下载封面图
303
+ step(3, "running");
304
+ const coverUrls = notes.map((n) => n.coverUrl).filter(Boolean);
305
+ if (coverUrls.length > 0) {
306
+ imageAssets = await downloadCoverImages(notes, dir, sessionId, taskId, (current, total, success) => {
307
+ step(3, "running", `下载图片 ${current}/${total}(成功 ${success} 张)`);
308
+ });
309
+ const successCount = imageAssets.filter((a: any) => a.path).length;
310
+ step(3, "done", `图片 ${successCount}/${coverUrls.length} 张已下载`);
311
+ } else {
312
+ step(3, "done", "无封面图可下载");
313
+ }
314
+
315
+ // 6. 生成文件
316
+ step(5, "running");
317
+
318
+ const csvName = `xhs-notes-${Date.now()}.csv`;
319
+ const { path: csvPath, size: csvSize } = writeFile(dir, csvName, toCSV(notes));
320
+ fileAssets.push({
321
+ id: `ast_${Date.now().toString(36)}`,
322
+ kind: "csv",
323
+ name: csvName,
324
+ size: csvSize,
325
+ mime: "text/csv",
326
+ path: csvPath,
327
+ recordCount: notes.length,
328
+ source: { pageUrl, sessionId, taskId, browserConn, createdAt: Date.now() },
329
+ });
330
+
331
+ const jsonName = `xhs-notes-${Date.now()}.json`;
332
+ const { path: jsonPath, size: jsonSize } = writeFile(
333
+ dir,
334
+ jsonName,
335
+ toJSON(notes, { pageUrl, scrapedAt: new Date().toISOString(), count: notes.length }),
336
+ );
337
+ fileAssets.push({
338
+ id: `ast_${Date.now().toString(36)}`,
339
+ kind: "json",
340
+ name: jsonName,
341
+ size: jsonSize,
342
+ mime: "application/json",
343
+ path: jsonPath,
344
+ recordCount: notes.length,
345
+ source: { pageUrl, sessionId, taskId, browserConn, createdAt: Date.now() },
346
+ });
347
+
348
+ // AI 报告
349
+ let aiSummaryText = "";
350
+ if (opts.aiSummary) {
351
+ try {
352
+ aiSummaryText = await opts.aiSummary(
353
+ `你采集了小红书页面,共 ${notes.length} 条笔记。\n标题示例:${notes
354
+ .slice(0, 8)
355
+ .map((n) => n.title || "(无标题)")
356
+ .join(" / ")}\n请生成简洁中文报告(不超过 200 字):1)这批笔记的整体主题 2)3 个值得关注的要点。`,
357
+ );
358
+ } catch {}
359
+ }
360
+
361
+ const summary: Summary = {
362
+ noteCount: notes.length,
363
+ imageCount: imageAssets.filter((a: any) => a.path).length,
364
+ successRate:
365
+ coverUrls.length > 0
366
+ ? Math.round(
367
+ (imageAssets.filter((a: any) => a.path).length / coverUrls.length) * 100,
368
+ ) + "%"
369
+ : "—",
370
+ durationMs: Date.now() - startMs,
371
+ };
372
+
373
+ const reportName = `xhs-report-${Date.now()}.md`;
374
+ const { path: reportPath, size: reportSize } = writeFile(
375
+ dir,
376
+ reportName,
377
+ toMarkdownReport(notes, summary, aiSummaryText, pageUrl),
378
+ );
379
+ fileAssets.push({
380
+ id: `ast_${Date.now().toString(36)}`,
381
+ kind: "report",
382
+ name: reportName,
383
+ size: reportSize,
384
+ mime: "text/markdown",
385
+ path: reportPath,
386
+ source: { pageUrl, sessionId, taskId, browserConn, createdAt: Date.now() },
387
+ });
388
+ step(5, "done", "CSV + JSON + 报告已生成");
389
+
390
+ // 7. 打包 ZIP
391
+ step(6, "running");
392
+ try {
393
+ const zipPathResult = packZip(dir, `xhs-bundle-${Date.now()}.zip`);
394
+ const zipName = join(dir, zipPathResult).split("/").pop() || "bundle.zip";
395
+ zipAssets.push({
396
+ id: `ast_${Date.now().toString(36)}`,
397
+ kind: "zip",
398
+ name: zipName,
399
+ size: statSync(zipPathResult).size,
400
+ mime: "application/zip",
401
+ path: zipPathResult,
402
+ source: { pageUrl, sessionId, taskId, browserConn, createdAt: Date.now() },
403
+ });
404
+ step(6, "done", "ZIP 打包完成");
405
+ } catch (e: any) {
406
+ step(6, "error", "ZIP 打包失败:" + e.message);
407
+ }
408
+
409
+ const assets = [
410
+ ...(screenshotAsset ? [screenshotAsset] : []),
411
+ ...imageAssets,
412
+ ...fileAssets,
413
+ ...zipAssets,
414
+ ];
415
+
416
+ return { notes, summary, assets, steps };
417
+ } catch (e: any) {
418
+ const idx = steps.findIndex((s) => s.status === "pending" || s.status === "running");
419
+ if (idx >= 0) step(idx, "error", e.message);
420
+ return {
421
+ notes: [],
422
+ assets: [],
423
+ summary: { noteCount: 0, imageCount: 0, successRate: "0%", durationMs: Date.now() - startMs },
424
+ steps,
425
+ };
426
+ }
427
+ }
428
+
429
+ // ===== 检测浏览器连接 =====
430
+
431
+ export async function getOnlineBrowser(
432
+ _pluginId?: string,
433
+ ): Promise<{ pluginId: string; name: string; tabs: number } | null> {
434
+ try {
435
+ // 用 tab list 验证真实连接 — 能列出 tab 才说明 Chrome 真的连上了
436
+ const result = await xbrowserCli(["tab", "list"]);
437
+ if (result?.success && Array.isArray(result?.data?.tabs)) {
438
+ return {
439
+ pluginId: "xbrowser",
440
+ name: "xbrowser 引擎",
441
+ tabs: result.data.tabs.length,
442
+ };
443
+ }
444
+ return null;
445
+ } catch {
446
+ return null;
447
+ }
448
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * 文件生成器 — CSV / JSON / Markdown 报告 / ZIP
3
+ *
4
+ * 对应 PRD §4.6 资源管理 — CSV/JSON/MD/ZIP 生成
5
+ */
6
+
7
+ import { execSync } from "child_process";
8
+ import { writeFileSync, unlinkSync, statSync } from "fs";
9
+ import { join, dirname } from "path";
10
+
11
+ // ===== 类型 =====
12
+
13
+ export interface NoteItem {
14
+ title: string;
15
+ author: string;
16
+ noteUrl: string;
17
+ coverUrl: string;
18
+ likes?: string;
19
+ }
20
+
21
+ export interface Summary {
22
+ noteCount: number;
23
+ imageCount: number;
24
+ successRate: string;
25
+ durationMs: number;
26
+ }
27
+
28
+ // ===== CSV =====
29
+
30
+ function csvEscape(v: unknown): string {
31
+ if (v === undefined || v === null) return "";
32
+ const s = String(v);
33
+ if (/[",\n\r"]/.test(s)) return '"' + s.replace(/"/g, '""') + '"';
34
+ return s;
35
+ }
36
+
37
+ export function toCSV(notes: NoteItem[]): string {
38
+ const headers = ["序号", "标题", "作者", "笔记链接", "封面图链接", "点赞数"];
39
+ const rows = notes.map((n, i) =>
40
+ [i + 1, n.title, n.author, n.noteUrl, n.coverUrl, n.likes || ""]
41
+ .map(csvEscape)
42
+ .join(","),
43
+ );
44
+ return "\ufeff" + [headers.join(","), ...rows].join("\n");
45
+ }
46
+
47
+ // ===== JSON =====
48
+
49
+ export function toJSON(notes: NoteItem[], meta?: Record<string, unknown>): string {
50
+ return JSON.stringify({ meta: meta || {}, notes }, null, 2);
51
+ }
52
+
53
+ // ===== Markdown 报告 =====
54
+
55
+ export function toMarkdownReport(
56
+ notes: NoteItem[],
57
+ summary: Summary,
58
+ aiSummary: string,
59
+ pageUrl: string,
60
+ ): string {
61
+ const lines: string[] = [];
62
+ lines.push("# 采集报告");
63
+ lines.push("");
64
+ lines.push(
65
+ `> 采集时间:${new Date(
66
+ summary.durationMs ? Date.now() - 0 : Date.now(),
67
+ ).toLocaleString("zh-CN")}`,
68
+ );
69
+ lines.push(`> 来源页面:${pageUrl}`);
70
+ lines.push("");
71
+ lines.push("## 采集摘要");
72
+ lines.push("");
73
+ lines.push(`- 笔记数量:**${summary.noteCount}** 条`);
74
+ lines.push(`- 图片数量:**${summary.imageCount}** 张`);
75
+ lines.push(`- 下载成功率:**${summary.successRate}**`);
76
+ lines.push("");
77
+ lines.push("## AI 总结");
78
+ lines.push("");
79
+ lines.push(aiSummary || "(AI 总结暂不可用)");
80
+ lines.push("");
81
+ lines.push("## 笔记列表");
82
+ lines.push("");
83
+ notes.forEach((n, i) => {
84
+ lines.push(`### ${i + 1}. ${n.title}`);
85
+ if (n.author) lines.push(`- 作者:${n.author}`);
86
+ if (n.likes) lines.push(`- 点赞:${n.likes}`);
87
+ if (n.noteUrl) lines.push(`- 链接:${n.noteUrl}`);
88
+ if (n.coverUrl) lines.push(`- 封面:${n.coverUrl}`);
89
+ lines.push("");
90
+ });
91
+ return lines.join("\n");
92
+ }
93
+
94
+ // ===== ZIP =====
95
+
96
+ export function packZip(srcDir: string, outName: string): string {
97
+ const zipPath = join(dirname(srcDir), outName);
98
+ try {
99
+ unlinkSync(zipPath);
100
+ } catch {}
101
+ execSync(`cd "${srcDir}" && zip -rq "${zipPath}" ./`);
102
+ return zipPath;
103
+ }
104
+
105
+ // ===== 文件工具 =====
106
+
107
+ export function writeFile(dir: string, name: string, data: string | Buffer): { path: string; size: number } {
108
+ const filePath = join(dir, name);
109
+ writeFileSync(filePath, data as any);
110
+ return { path: filePath, size: statSync(filePath).size };
111
+ }
@@ -0,0 +1,152 @@
1
+ import {
2
+ appendFile,
3
+ mkdir as mkdirAsync,
4
+ readdir as readdirAsync,
5
+ unlink as unlinkAsync,
6
+ stat as statAsync,
7
+ } from "fs/promises";
8
+ import { mkdirSync, existsSync } from "fs";
9
+ import { join } from "path";
10
+
11
+ export type LogModule =
12
+ | "server"
13
+ | "gateway"
14
+ | "system"
15
+ | "chat"
16
+ | "file"
17
+ | "timer"
18
+ | "git"
19
+ | "feed"
20
+ | "web-server";
21
+ type LogLevel = "debug" | "info" | "warn" | "error";
22
+
23
+ interface LogEntry {
24
+ timestamp: string;
25
+ level: LogLevel;
26
+ module: LogModule;
27
+ message: string;
28
+ data?: Record<string, unknown>;
29
+ }
30
+
31
+ let _logDir: string | null = null;
32
+ let _maxAgeDays = 30;
33
+
34
+ export async function configureLogDir(
35
+ dir: string,
36
+ options?: { maxAgeDays?: number }
37
+ ): Promise<void> {
38
+ _logDir = dir;
39
+ if (options?.maxAgeDays !== undefined) {
40
+ _maxAgeDays = options.maxAgeDays;
41
+ }
42
+ if (!existsSync(dir)) {
43
+ mkdirSync(dir, { recursive: true });
44
+ }
45
+ await cleanOldLogs(dir, _maxAgeDays);
46
+ }
47
+
48
+ function getLogDir(): string {
49
+ if (!_logDir) {
50
+ _logDir = "logs";
51
+ if (!existsSync(_logDir)) {
52
+ mkdirSync(_logDir, { recursive: true });
53
+ }
54
+ }
55
+ return _logDir;
56
+ }
57
+
58
+ async function cleanOldLogs(dir: string, maxAgeDays: number): Promise<void> {
59
+ try {
60
+ if (!existsSync(dir)) return;
61
+ const files = await readdirAsync(dir);
62
+ const cutoff = Date.now() - maxAgeDays * 86400000;
63
+ for (const f of files) {
64
+ if (!f.endsWith(".log")) continue;
65
+ const filePath = join(dir, f);
66
+ const s = await statAsync(filePath);
67
+ if (s.mtimeMs < cutoff) {
68
+ await unlinkAsync(filePath);
69
+ }
70
+ }
71
+ } catch {
72
+ /* ignore */
73
+ }
74
+ }
75
+
76
+ function formatLine(entry: LogEntry): string {
77
+ const base = `[${entry.timestamp}] [${entry.level.toUpperCase()}] [${entry.module}] ${entry.message}`;
78
+ return entry.data ? `${base} ${JSON.stringify(entry.data)}` : base;
79
+ }
80
+
81
+ let writeQueue: Promise<void> = Promise.resolve();
82
+
83
+ function writeToFile(line: string): void {
84
+ writeQueue = writeQueue.then(async () => {
85
+ try {
86
+ const date = new Date().toISOString().slice(0, 10);
87
+ const dir = getLogDir();
88
+ if (!existsSync(dir)) {
89
+ await mkdirAsync(dir, { recursive: true });
90
+ }
91
+ await appendFile(join(dir, `${date}.log`), `${line}\n`);
92
+ } catch {
93
+ /* ignore */
94
+ }
95
+ });
96
+ }
97
+
98
+ export function flushLogs(): Promise<void> {
99
+ return writeQueue;
100
+ }
101
+
102
+ export class Logger {
103
+ private readonly module: LogModule;
104
+
105
+ constructor(module: LogModule) {
106
+ this.module = module;
107
+ }
108
+
109
+ debug(message: string, data?: Record<string, unknown>): void {
110
+ this.write("debug", message, data);
111
+ }
112
+
113
+ info(message: string, data?: Record<string, unknown>): void {
114
+ this.write("info", message, data);
115
+ }
116
+
117
+ warn(message: string, data?: Record<string, unknown>): void {
118
+ this.write("warn", message, data);
119
+ }
120
+
121
+ error(message: string, data?: Record<string, unknown>): void {
122
+ this.write("error", message, data);
123
+ }
124
+
125
+ private write(level: LogLevel, message: string, data?: Record<string, unknown>): void {
126
+ const entry: LogEntry = {
127
+ timestamp: new Date().toISOString(),
128
+ level,
129
+ module: this.module,
130
+ message,
131
+ ...(data ? { data } : {}),
132
+ };
133
+
134
+ const line = formatLine(entry);
135
+
136
+ if (level === "error") {
137
+ console.error(line);
138
+ } else if (level === "warn") {
139
+ console.warn(line);
140
+ } else {
141
+ console.log(line);
142
+ }
143
+
144
+ if (process.env.NODE_ENV !== "production" || level !== "debug") {
145
+ writeToFile(line);
146
+ }
147
+ }
148
+ }
149
+
150
+ export function createLogger(module: LogModule): Logger {
151
+ return new Logger(module);
152
+ }