@brianli/kimaki 0.4.72-brianli.1

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 (328) hide show
  1. package/bin.js +2 -0
  2. package/dist/ai-tool-to-genai.js +233 -0
  3. package/dist/ai-tool-to-genai.test.js +267 -0
  4. package/dist/ai-tool.js +6 -0
  5. package/dist/bin.js +87 -0
  6. package/dist/bot-token.js +121 -0
  7. package/dist/bot-token.test.js +134 -0
  8. package/dist/channel-management.js +101 -0
  9. package/dist/cli-parsing.test.js +89 -0
  10. package/dist/cli.js +2529 -0
  11. package/dist/commands/abort.js +82 -0
  12. package/dist/commands/action-buttons.js +257 -0
  13. package/dist/commands/add-project.js +114 -0
  14. package/dist/commands/agent.js +291 -0
  15. package/dist/commands/ask-question.js +223 -0
  16. package/dist/commands/compact.js +120 -0
  17. package/dist/commands/context-usage.js +140 -0
  18. package/dist/commands/create-new-project.js +118 -0
  19. package/dist/commands/diff.js +128 -0
  20. package/dist/commands/file-upload.js +275 -0
  21. package/dist/commands/fork.js +217 -0
  22. package/dist/commands/gemini-apikey.js +70 -0
  23. package/dist/commands/login.js +490 -0
  24. package/dist/commands/mention-mode.js +51 -0
  25. package/dist/commands/merge-worktree.js +124 -0
  26. package/dist/commands/model.js +694 -0
  27. package/dist/commands/permissions.js +163 -0
  28. package/dist/commands/queue.js +217 -0
  29. package/dist/commands/remove-project.js +115 -0
  30. package/dist/commands/restart-opencode-server.js +116 -0
  31. package/dist/commands/resume.js +159 -0
  32. package/dist/commands/run-command.js +79 -0
  33. package/dist/commands/session-id.js +78 -0
  34. package/dist/commands/session.js +192 -0
  35. package/dist/commands/share.js +80 -0
  36. package/dist/commands/types.js +2 -0
  37. package/dist/commands/undo-redo.js +159 -0
  38. package/dist/commands/unset-model.js +152 -0
  39. package/dist/commands/upgrade.js +42 -0
  40. package/dist/commands/user-command.js +148 -0
  41. package/dist/commands/verbosity.js +60 -0
  42. package/dist/commands/worktree-settings.js +50 -0
  43. package/dist/commands/worktree.js +299 -0
  44. package/dist/condense-memory.js +33 -0
  45. package/dist/config.js +110 -0
  46. package/dist/database.js +1050 -0
  47. package/dist/db.js +159 -0
  48. package/dist/db.test.js +49 -0
  49. package/dist/discord-api.js +28 -0
  50. package/dist/discord-auth.js +231 -0
  51. package/dist/discord-auth.test.js +80 -0
  52. package/dist/discord-bot.js +997 -0
  53. package/dist/discord-utils.js +560 -0
  54. package/dist/discord-utils.test.js +115 -0
  55. package/dist/errors.js +167 -0
  56. package/dist/escape-backticks.test.js +429 -0
  57. package/dist/format-tables.js +122 -0
  58. package/dist/format-tables.test.js +199 -0
  59. package/dist/forum-sync/config.js +79 -0
  60. package/dist/forum-sync/discord-operations.js +154 -0
  61. package/dist/forum-sync/index.js +5 -0
  62. package/dist/forum-sync/markdown.js +117 -0
  63. package/dist/forum-sync/sync-to-discord.js +417 -0
  64. package/dist/forum-sync/sync-to-files.js +190 -0
  65. package/dist/forum-sync/types.js +53 -0
  66. package/dist/forum-sync/watchers.js +307 -0
  67. package/dist/gateway-consumer.js +232 -0
  68. package/dist/gateway-consumer.test.js +18 -0
  69. package/dist/genai-worker-wrapper.js +111 -0
  70. package/dist/genai-worker.js +311 -0
  71. package/dist/genai.js +232 -0
  72. package/dist/generated/browser.js +17 -0
  73. package/dist/generated/client.js +35 -0
  74. package/dist/generated/commonInputTypes.js +10 -0
  75. package/dist/generated/enums.js +30 -0
  76. package/dist/generated/internal/class.js +41 -0
  77. package/dist/generated/internal/prismaNamespace.js +239 -0
  78. package/dist/generated/internal/prismaNamespaceBrowser.js +209 -0
  79. package/dist/generated/models/bot_api_keys.js +1 -0
  80. package/dist/generated/models/bot_tokens.js +1 -0
  81. package/dist/generated/models/channel_agents.js +1 -0
  82. package/dist/generated/models/channel_directories.js +1 -0
  83. package/dist/generated/models/channel_mention_mode.js +1 -0
  84. package/dist/generated/models/channel_models.js +1 -0
  85. package/dist/generated/models/channel_verbosity.js +1 -0
  86. package/dist/generated/models/channel_worktrees.js +1 -0
  87. package/dist/generated/models/forum_sync_configs.js +1 -0
  88. package/dist/generated/models/global_models.js +1 -0
  89. package/dist/generated/models/ipc_requests.js +1 -0
  90. package/dist/generated/models/part_messages.js +1 -0
  91. package/dist/generated/models/scheduled_tasks.js +1 -0
  92. package/dist/generated/models/session_agents.js +1 -0
  93. package/dist/generated/models/session_models.js +1 -0
  94. package/dist/generated/models/session_start_sources.js +1 -0
  95. package/dist/generated/models/thread_sessions.js +1 -0
  96. package/dist/generated/models/thread_worktrees.js +1 -0
  97. package/dist/generated/models.js +1 -0
  98. package/dist/heap-monitor.js +95 -0
  99. package/dist/hrana-server.js +416 -0
  100. package/dist/hrana-server.test.js +368 -0
  101. package/dist/image-utils.js +112 -0
  102. package/dist/interaction-handler.js +327 -0
  103. package/dist/ipc-polling.js +251 -0
  104. package/dist/kimaki-digital-twin.e2e.test.js +165 -0
  105. package/dist/limit-heading-depth.js +25 -0
  106. package/dist/limit-heading-depth.test.js +105 -0
  107. package/dist/logger.js +160 -0
  108. package/dist/markdown.js +342 -0
  109. package/dist/markdown.test.js +253 -0
  110. package/dist/message-formatting.js +433 -0
  111. package/dist/message-formatting.test.js +73 -0
  112. package/dist/openai-realtime.js +228 -0
  113. package/dist/opencode-plugin-loading.e2e.test.js +91 -0
  114. package/dist/opencode-plugin.js +536 -0
  115. package/dist/opencode-plugin.test.js +98 -0
  116. package/dist/opencode.js +409 -0
  117. package/dist/privacy-sanitizer.js +105 -0
  118. package/dist/runtime-mode.js +51 -0
  119. package/dist/runtime-mode.test.js +115 -0
  120. package/dist/sentry.js +127 -0
  121. package/dist/session-handler/state.js +151 -0
  122. package/dist/session-handler.js +1874 -0
  123. package/dist/session-search.js +100 -0
  124. package/dist/session-search.test.js +40 -0
  125. package/dist/startup-service.js +153 -0
  126. package/dist/system-message.js +499 -0
  127. package/dist/task-runner.js +282 -0
  128. package/dist/task-schedule.js +191 -0
  129. package/dist/task-schedule.test.js +71 -0
  130. package/dist/thinking-utils.js +35 -0
  131. package/dist/thread-message-queue.e2e.test.js +781 -0
  132. package/dist/tools.js +359 -0
  133. package/dist/unnest-code-blocks.js +136 -0
  134. package/dist/unnest-code-blocks.test.js +641 -0
  135. package/dist/upgrade.js +114 -0
  136. package/dist/utils.js +109 -0
  137. package/dist/voice-handler.js +606 -0
  138. package/dist/voice.js +304 -0
  139. package/dist/voice.test.js +187 -0
  140. package/dist/wait-session.js +94 -0
  141. package/dist/worker-types.js +4 -0
  142. package/dist/worktree-utils.js +727 -0
  143. package/dist/xml.js +92 -0
  144. package/dist/xml.test.js +32 -0
  145. package/package.json +82 -0
  146. package/schema.prisma +246 -0
  147. package/skills/batch/SKILL.md +87 -0
  148. package/skills/critique/SKILL.md +129 -0
  149. package/skills/errore/SKILL.md +589 -0
  150. package/skills/goke/.prettierrc +5 -0
  151. package/skills/goke/CHANGELOG.md +40 -0
  152. package/skills/goke/LICENSE +21 -0
  153. package/skills/goke/README.md +666 -0
  154. package/skills/goke/SKILL.md +458 -0
  155. package/skills/goke/package.json +43 -0
  156. package/skills/goke/src/__test__/coerce.test.ts +411 -0
  157. package/skills/goke/src/__test__/index.test.ts +1798 -0
  158. package/skills/goke/src/__test__/types.test-d.ts +111 -0
  159. package/skills/goke/src/coerce.ts +547 -0
  160. package/skills/goke/src/goke.ts +1362 -0
  161. package/skills/goke/src/index.ts +16 -0
  162. package/skills/goke/src/mri.ts +164 -0
  163. package/skills/goke/tsconfig.json +15 -0
  164. package/skills/jitter/EDITOR.md +219 -0
  165. package/skills/jitter/EXPORT-INTERNALS.md +309 -0
  166. package/skills/jitter/SKILL.md +158 -0
  167. package/skills/jitter/jitter-clipboard.json +1042 -0
  168. package/skills/jitter/package.json +14 -0
  169. package/skills/jitter/tsconfig.json +15 -0
  170. package/skills/jitter/utils/actions.ts +212 -0
  171. package/skills/jitter/utils/export.ts +114 -0
  172. package/skills/jitter/utils/index.ts +141 -0
  173. package/skills/jitter/utils/snapshot.ts +154 -0
  174. package/skills/jitter/utils/traverse.ts +246 -0
  175. package/skills/jitter/utils/types.ts +279 -0
  176. package/skills/jitter/utils/wait.ts +133 -0
  177. package/skills/playwriter/SKILL.md +31 -0
  178. package/skills/security-review/SKILL.md +208 -0
  179. package/skills/simplify/SKILL.md +58 -0
  180. package/skills/termcast/SKILL.md +945 -0
  181. package/skills/tuistory/SKILL.md +250 -0
  182. package/skills/zustand-centralized-state/SKILL.md +582 -0
  183. package/src/__snapshots__/compact-session-context-no-system.md +35 -0
  184. package/src/__snapshots__/compact-session-context.md +41 -0
  185. package/src/__snapshots__/first-session-no-info.md +17 -0
  186. package/src/__snapshots__/first-session-with-info.md +23 -0
  187. package/src/__snapshots__/session-1.md +17 -0
  188. package/src/__snapshots__/session-2.md +5871 -0
  189. package/src/__snapshots__/session-3.md +17 -0
  190. package/src/__snapshots__/session-with-tools.md +5871 -0
  191. package/src/ai-tool-to-genai.test.ts +296 -0
  192. package/src/ai-tool-to-genai.ts +282 -0
  193. package/src/ai-tool.ts +39 -0
  194. package/src/bin.ts +108 -0
  195. package/src/bot-token.test.ts +171 -0
  196. package/src/bot-token.ts +159 -0
  197. package/src/channel-management.ts +172 -0
  198. package/src/cli-parsing.test.ts +132 -0
  199. package/src/cli.ts +3605 -0
  200. package/src/commands/abort.ts +112 -0
  201. package/src/commands/action-buttons.ts +376 -0
  202. package/src/commands/add-project.ts +152 -0
  203. package/src/commands/agent.ts +404 -0
  204. package/src/commands/ask-question.ts +330 -0
  205. package/src/commands/compact.ts +157 -0
  206. package/src/commands/context-usage.ts +199 -0
  207. package/src/commands/create-new-project.ts +179 -0
  208. package/src/commands/diff.ts +165 -0
  209. package/src/commands/file-upload.ts +389 -0
  210. package/src/commands/fork.ts +320 -0
  211. package/src/commands/gemini-apikey.ts +104 -0
  212. package/src/commands/login.ts +634 -0
  213. package/src/commands/mention-mode.ts +77 -0
  214. package/src/commands/merge-worktree.ts +177 -0
  215. package/src/commands/model.ts +961 -0
  216. package/src/commands/permissions.ts +261 -0
  217. package/src/commands/queue.ts +296 -0
  218. package/src/commands/remove-project.ts +155 -0
  219. package/src/commands/restart-opencode-server.ts +162 -0
  220. package/src/commands/resume.ts +242 -0
  221. package/src/commands/run-command.ts +123 -0
  222. package/src/commands/session-id.ts +109 -0
  223. package/src/commands/session.ts +250 -0
  224. package/src/commands/share.ts +106 -0
  225. package/src/commands/types.ts +25 -0
  226. package/src/commands/undo-redo.ts +221 -0
  227. package/src/commands/unset-model.ts +189 -0
  228. package/src/commands/upgrade.ts +52 -0
  229. package/src/commands/user-command.ts +193 -0
  230. package/src/commands/verbosity.ts +88 -0
  231. package/src/commands/worktree-settings.ts +79 -0
  232. package/src/commands/worktree.ts +431 -0
  233. package/src/condense-memory.ts +36 -0
  234. package/src/config.ts +148 -0
  235. package/src/database.ts +1530 -0
  236. package/src/db.test.ts +60 -0
  237. package/src/db.ts +190 -0
  238. package/src/discord-api.ts +35 -0
  239. package/src/discord-bot.ts +1316 -0
  240. package/src/discord-utils.test.ts +132 -0
  241. package/src/discord-utils.ts +767 -0
  242. package/src/errors.ts +213 -0
  243. package/src/escape-backticks.test.ts +469 -0
  244. package/src/format-tables.test.ts +223 -0
  245. package/src/format-tables.ts +145 -0
  246. package/src/forum-sync/config.ts +92 -0
  247. package/src/forum-sync/discord-operations.ts +241 -0
  248. package/src/forum-sync/index.ts +9 -0
  249. package/src/forum-sync/markdown.ts +176 -0
  250. package/src/forum-sync/sync-to-discord.ts +595 -0
  251. package/src/forum-sync/sync-to-files.ts +294 -0
  252. package/src/forum-sync/types.ts +175 -0
  253. package/src/forum-sync/watchers.ts +454 -0
  254. package/src/genai-worker-wrapper.ts +164 -0
  255. package/src/genai-worker.ts +386 -0
  256. package/src/genai.ts +321 -0
  257. package/src/generated/browser.ts +109 -0
  258. package/src/generated/client.ts +131 -0
  259. package/src/generated/commonInputTypes.ts +512 -0
  260. package/src/generated/enums.ts +46 -0
  261. package/src/generated/internal/class.ts +362 -0
  262. package/src/generated/internal/prismaNamespace.ts +2251 -0
  263. package/src/generated/internal/prismaNamespaceBrowser.ts +308 -0
  264. package/src/generated/models/bot_api_keys.ts +1288 -0
  265. package/src/generated/models/bot_tokens.ts +1577 -0
  266. package/src/generated/models/channel_agents.ts +1256 -0
  267. package/src/generated/models/channel_directories.ts +2104 -0
  268. package/src/generated/models/channel_mention_mode.ts +1300 -0
  269. package/src/generated/models/channel_models.ts +1288 -0
  270. package/src/generated/models/channel_verbosity.ts +1224 -0
  271. package/src/generated/models/channel_worktrees.ts +1308 -0
  272. package/src/generated/models/forum_sync_configs.ts +1452 -0
  273. package/src/generated/models/global_models.ts +1288 -0
  274. package/src/generated/models/ipc_requests.ts +1485 -0
  275. package/src/generated/models/part_messages.ts +1302 -0
  276. package/src/generated/models/scheduled_tasks.ts +2320 -0
  277. package/src/generated/models/session_agents.ts +1086 -0
  278. package/src/generated/models/session_models.ts +1114 -0
  279. package/src/generated/models/session_start_sources.ts +1408 -0
  280. package/src/generated/models/thread_sessions.ts +1599 -0
  281. package/src/generated/models/thread_worktrees.ts +1352 -0
  282. package/src/generated/models.ts +29 -0
  283. package/src/heap-monitor.ts +121 -0
  284. package/src/hrana-server.test.ts +428 -0
  285. package/src/hrana-server.ts +547 -0
  286. package/src/image-utils.ts +149 -0
  287. package/src/interaction-handler.ts +461 -0
  288. package/src/ipc-polling.ts +325 -0
  289. package/src/kimaki-digital-twin.e2e.test.ts +201 -0
  290. package/src/limit-heading-depth.test.ts +116 -0
  291. package/src/limit-heading-depth.ts +26 -0
  292. package/src/logger.ts +203 -0
  293. package/src/markdown.test.ts +360 -0
  294. package/src/markdown.ts +410 -0
  295. package/src/message-formatting.test.ts +81 -0
  296. package/src/message-formatting.ts +549 -0
  297. package/src/openai-realtime.ts +362 -0
  298. package/src/opencode-plugin-loading.e2e.test.ts +112 -0
  299. package/src/opencode-plugin.test.ts +108 -0
  300. package/src/opencode-plugin.ts +652 -0
  301. package/src/opencode.ts +554 -0
  302. package/src/privacy-sanitizer.ts +142 -0
  303. package/src/schema.sql +158 -0
  304. package/src/sentry.ts +137 -0
  305. package/src/session-handler/state.ts +232 -0
  306. package/src/session-handler.ts +2668 -0
  307. package/src/session-search.test.ts +50 -0
  308. package/src/session-search.ts +148 -0
  309. package/src/startup-service.ts +200 -0
  310. package/src/system-message.ts +568 -0
  311. package/src/task-runner.ts +425 -0
  312. package/src/task-schedule.test.ts +84 -0
  313. package/src/task-schedule.ts +287 -0
  314. package/src/thinking-utils.ts +61 -0
  315. package/src/thread-message-queue.e2e.test.ts +997 -0
  316. package/src/tools.ts +432 -0
  317. package/src/unnest-code-blocks.test.ts +679 -0
  318. package/src/unnest-code-blocks.ts +168 -0
  319. package/src/upgrade.ts +127 -0
  320. package/src/utils.ts +145 -0
  321. package/src/voice-handler.ts +852 -0
  322. package/src/voice.test.ts +219 -0
  323. package/src/voice.ts +444 -0
  324. package/src/wait-session.ts +147 -0
  325. package/src/worker-types.ts +64 -0
  326. package/src/worktree-utils.ts +988 -0
  327. package/src/xml.test.ts +38 -0
  328. package/src/xml.ts +121 -0
@@ -0,0 +1,122 @@
1
+ // Markdown table formatter for Discord.
2
+ // Converts GFM tables to Discord Components V2 (ContainerBuilder with TextDisplay
3
+ // key-value pairs and Separators between row groups). Large tables are split
4
+ // across multiple Container components to stay within the 40-component limit.
5
+ import { Lexer } from 'marked';
6
+ import { SeparatorSpacingSize, } from 'discord.js';
7
+ // Max 40 components per message (nested components count toward the limit).
8
+ // Each container uses: 1 (container) + M (TextDisplays) + M-1 (separators) = 2M children.
9
+ // So max rows per container = floor((40 - 1) / 2) = 19.
10
+ const MAX_COMPONENTS = 40;
11
+ const MAX_ROWS_PER_CONTAINER = Math.floor((MAX_COMPONENTS - 1) / 2);
12
+ /**
13
+ * Split markdown into text and table component segments.
14
+ * Tables are rendered as CV2 Container components with bold key-value TextDisplay
15
+ * pairs. Large tables are split across multiple component segments.
16
+ */
17
+ export function splitTablesFromMarkdown(markdown) {
18
+ const lexer = new Lexer();
19
+ const tokens = lexer.lex(markdown);
20
+ const segments = [];
21
+ let textBuffer = '';
22
+ for (const token of tokens) {
23
+ if (token.type === 'table') {
24
+ if (textBuffer.trim()) {
25
+ segments.push({ type: 'text', text: textBuffer });
26
+ textBuffer = '';
27
+ }
28
+ const componentSegments = buildTableComponents(token);
29
+ segments.push(...componentSegments);
30
+ }
31
+ else {
32
+ textBuffer += token.raw;
33
+ }
34
+ }
35
+ if (textBuffer.trim()) {
36
+ segments.push({ type: 'text', text: textBuffer });
37
+ }
38
+ return segments;
39
+ }
40
+ /**
41
+ * Build CV2 components for a table. Each data row becomes a single TextDisplay
42
+ * with all key-value pairs joined by newlines (header bold as key). Separator
43
+ * dividers are placed between row groups.
44
+ * Large tables are split into multiple component segments, each containing a
45
+ * Container with up to MAX_ROWS_PER_CONTAINER rows.
46
+ */
47
+ export function buildTableComponents(table) {
48
+ const headers = table.header.map((cell) => {
49
+ return extractCellText(cell.tokens);
50
+ });
51
+ const rows = table.rows.map((row) => {
52
+ return row.map((cell) => {
53
+ return extractCellText(cell.tokens);
54
+ });
55
+ });
56
+ // Split rows into chunks that fit within the component limit
57
+ const chunks = [];
58
+ for (let i = 0; i < rows.length; i += MAX_ROWS_PER_CONTAINER) {
59
+ chunks.push(rows.slice(i, i + MAX_ROWS_PER_CONTAINER));
60
+ }
61
+ return chunks.map((chunkRows) => {
62
+ const children = [];
63
+ for (let i = 0; i < chunkRows.length; i++) {
64
+ if (i > 0) {
65
+ children.push({
66
+ type: 14,
67
+ divider: true,
68
+ spacing: SeparatorSpacingSize.Small,
69
+ });
70
+ }
71
+ const row = chunkRows[i];
72
+ const lines = headers.map((key, j) => {
73
+ const value = row[j] || '';
74
+ return `**${key}** ${value}`;
75
+ });
76
+ children.push({ type: 10, content: lines.join('\n') });
77
+ }
78
+ const container = {
79
+ type: 17,
80
+ components: children,
81
+ };
82
+ return {
83
+ type: 'components',
84
+ components: [container],
85
+ };
86
+ });
87
+ }
88
+ function extractCellText(tokens) {
89
+ const parts = [];
90
+ for (const token of tokens) {
91
+ parts.push(extractTokenText(token));
92
+ }
93
+ return parts.join('').trim();
94
+ }
95
+ function extractTokenText(token) {
96
+ switch (token.type) {
97
+ case 'text':
98
+ case 'codespan':
99
+ case 'escape':
100
+ return token.text;
101
+ case 'link':
102
+ return token.href;
103
+ case 'image':
104
+ return token.href;
105
+ case 'strong':
106
+ case 'em':
107
+ case 'del':
108
+ return token.tokens ? extractCellText(token.tokens) : token.text;
109
+ case 'br':
110
+ return ' ';
111
+ default: {
112
+ const tokenAny = token;
113
+ if (tokenAny.tokens && Array.isArray(tokenAny.tokens)) {
114
+ return extractCellText(tokenAny.tokens);
115
+ }
116
+ if (typeof tokenAny.text === 'string') {
117
+ return tokenAny.text;
118
+ }
119
+ return '';
120
+ }
121
+ }
122
+ }
@@ -0,0 +1,199 @@
1
+ import { test, expect, describe } from 'vitest';
2
+ import { splitTablesFromMarkdown, buildTableComponents, } from './format-tables.js';
3
+ import { Lexer } from 'marked';
4
+ function parseTable(markdown) {
5
+ const lexer = new Lexer();
6
+ const tokens = lexer.lex(markdown);
7
+ return tokens.find((t) => t.type === 'table');
8
+ }
9
+ /** Extract the first container's children from buildTableComponents result */
10
+ function getContainerChildren(segments) {
11
+ const seg = segments[0];
12
+ if (seg.type !== 'components') {
13
+ throw new Error('Expected components segment');
14
+ }
15
+ const container = seg.components[0];
16
+ return container.components;
17
+ }
18
+ describe('buildTableComponents', () => {
19
+ test('builds container with key-value TextDisplays', () => {
20
+ const table = parseTable(`| Name | Age |
21
+ | --- | --- |
22
+ | Alice | 30 |
23
+ | Bob | 25 |`);
24
+ const result = buildTableComponents(table);
25
+ expect(result).toMatchInlineSnapshot(`
26
+ [
27
+ {
28
+ "components": [
29
+ {
30
+ "components": [
31
+ {
32
+ "content": "**Name** Alice
33
+ **Age** 30",
34
+ "type": 10,
35
+ },
36
+ {
37
+ "divider": true,
38
+ "spacing": 1,
39
+ "type": 14,
40
+ },
41
+ {
42
+ "content": "**Name** Bob
43
+ **Age** 25",
44
+ "type": 10,
45
+ },
46
+ ],
47
+ "type": 17,
48
+ },
49
+ ],
50
+ "type": "components",
51
+ },
52
+ ]
53
+ `);
54
+ });
55
+ test('adds separators between row groups', () => {
56
+ const table = parseTable(`| Key | Value |
57
+ | --- | --- |
58
+ | a | 1 |
59
+ | b | 2 |
60
+ | c | 3 |`);
61
+ const result = buildTableComponents(table);
62
+ const types = getContainerChildren(result).map((c) => c.type);
63
+ // type 10 = TextDisplay, type 14 = Separator
64
+ expect(types).toMatchInlineSnapshot(`
65
+ [
66
+ 10,
67
+ 14,
68
+ 10,
69
+ 14,
70
+ 10,
71
+ ]
72
+ `);
73
+ });
74
+ test('single-row table has one TextDisplay, no separators', () => {
75
+ const table = parseTable(`| Method | Endpoint |
76
+ | --- | --- |
77
+ | GET | /api/users |`);
78
+ const result = buildTableComponents(table);
79
+ const children = getContainerChildren(result);
80
+ expect(children).toHaveLength(1);
81
+ expect(children[0].type).toBe(10);
82
+ expect(children[0].content).toMatchInlineSnapshot(`
83
+ "**Method** GET
84
+ **Endpoint** /api/users"
85
+ `);
86
+ });
87
+ test('splits large table into multiple container segments', () => {
88
+ // 25 rows: exceeds 19 rows per container, so splits into 2 containers
89
+ const headers = '| A | B |';
90
+ const sep = '| --- | --- |';
91
+ const rows = Array.from({ length: 25 }, (_, i) => {
92
+ return `| ${i}a | ${i}b |`;
93
+ }).join('\n');
94
+ const table = parseTable(`${headers}\n${sep}\n${rows}`);
95
+ const result = buildTableComponents(table);
96
+ expect(result).toHaveLength(2);
97
+ expect(result[0].type).toBe('components');
98
+ expect(result[1].type).toBe('components');
99
+ // First container has 19 rows (19 TDs + 18 seps = 37 children)
100
+ const firstChildren = getContainerChildren([result[0]]);
101
+ expect(firstChildren).toHaveLength(19 + 18);
102
+ // Second container has 6 rows (6 TDs + 5 seps = 11 children)
103
+ const secondChildren = getContainerChildren([result[1]]);
104
+ expect(secondChildren).toHaveLength(6 + 5);
105
+ });
106
+ test('strips formatting from cells', () => {
107
+ const table = parseTable(`| Header | Value |
108
+ | --- | --- |
109
+ | **Bold text** | Normal |
110
+ | *Italic* | \`code\` |`);
111
+ const result = buildTableComponents(table);
112
+ const children = getContainerChildren(result);
113
+ expect(children[0].content).toMatchInlineSnapshot(`
114
+ "**Header** Bold text
115
+ **Value** Normal"
116
+ `);
117
+ });
118
+ });
119
+ describe('splitTablesFromMarkdown', () => {
120
+ test('returns single text segment for content without tables', () => {
121
+ const result = splitTablesFromMarkdown('Just some text.\n\nMore text.');
122
+ expect(result).toHaveLength(1);
123
+ expect(result[0].type).toBe('text');
124
+ });
125
+ test('returns single components segment for table-only content', () => {
126
+ const result = splitTablesFromMarkdown(`| A | B |
127
+ | --- | --- |
128
+ | 1 | 2 |`);
129
+ expect(result).toHaveLength(1);
130
+ expect(result[0].type).toBe('components');
131
+ });
132
+ test('splits text before and after table into separate segments', () => {
133
+ const result = splitTablesFromMarkdown(`Text before.
134
+
135
+ | Key | Value |
136
+ | --- | --- |
137
+ | a | 1 |
138
+
139
+ Text after.`);
140
+ expect(result).toHaveLength(3);
141
+ expect(result[0].type).toBe('text');
142
+ expect(result[1].type).toBe('components');
143
+ expect(result[2].type).toBe('text');
144
+ });
145
+ test('handles multiple tables with text between', () => {
146
+ const result = splitTablesFromMarkdown(`First table:
147
+
148
+ | A | B |
149
+ | --- | --- |
150
+ | 1 | 2 |
151
+
152
+ Middle text.
153
+
154
+ | X | Y |
155
+ | --- | --- |
156
+ | a | b |`);
157
+ expect(result).toHaveLength(4);
158
+ expect(result.map((s) => s.type)).toMatchInlineSnapshot(`
159
+ [
160
+ "text",
161
+ "components",
162
+ "text",
163
+ "components",
164
+ ]
165
+ `);
166
+ });
167
+ test('splits oversized table into multiple component segments', () => {
168
+ const headers = '| A | B |';
169
+ const sep = '| --- | --- |';
170
+ const rows = Array.from({ length: 25 }, (_, i) => {
171
+ return `| ${i}a | ${i}b |`;
172
+ }).join('\n');
173
+ const result = splitTablesFromMarkdown(`${headers}\n${sep}\n${rows}`);
174
+ // 25 rows splits into 2 container segments
175
+ expect(result).toHaveLength(2);
176
+ expect(result.every((s) => s.type === 'components')).toBe(true);
177
+ });
178
+ test('preserves code blocks alongside tables', () => {
179
+ const result = splitTablesFromMarkdown(`Some code:
180
+
181
+ \`\`\`js
182
+ const x = 1
183
+ \`\`\`
184
+
185
+ | Key | Value |
186
+ | --- | --- |
187
+ | a | 1 |
188
+
189
+ Done.`);
190
+ const types = result.map((s) => s.type);
191
+ expect(types).toMatchInlineSnapshot(`
192
+ [
193
+ "text",
194
+ "components",
195
+ "text",
196
+ ]
197
+ `);
198
+ });
199
+ });
@@ -0,0 +1,79 @@
1
+ // Forum sync configuration from SQLite database.
2
+ // Reads forum_sync_configs table and resolves relative output dirs.
3
+ // On first run, migrates any existing forum-sync.json into the DB.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import yaml from 'js-yaml';
7
+ import { getDataDir } from '../config.js';
8
+ import { getForumSyncConfigs, upsertForumSyncConfig } from '../database.js';
9
+ import { createLogger } from '../logger.js';
10
+ const forumLogger = createLogger('FORUM');
11
+ const LEGACY_CONFIG_FILE = 'forum-sync.json';
12
+ function isForumSyncDirection(value) {
13
+ return value === 'discord-to-files' || value === 'bidirectional';
14
+ }
15
+ function resolveOutputDir(outputDir) {
16
+ if (path.isAbsolute(outputDir))
17
+ return outputDir;
18
+ return path.resolve(getDataDir(), outputDir);
19
+ }
20
+ /**
21
+ * One-time migration: if the legacy forum-sync.json exists, import its entries
22
+ * into the DB and rename the file so it's not re-imported on next startup.
23
+ */
24
+ async function migrateLegacyConfig({ appId }) {
25
+ const configPath = path.join(getDataDir(), LEGACY_CONFIG_FILE);
26
+ if (!fs.existsSync(configPath))
27
+ return;
28
+ forumLogger.log(`Migrating legacy ${LEGACY_CONFIG_FILE} into database...`);
29
+ const raw = fs.readFileSync(configPath, 'utf8');
30
+ let parsed;
31
+ try {
32
+ parsed = yaml.load(raw);
33
+ }
34
+ catch {
35
+ forumLogger.warn(`Failed to parse legacy ${LEGACY_CONFIG_FILE}, skipping migration`);
36
+ return;
37
+ }
38
+ if (!parsed || typeof parsed !== 'object')
39
+ return;
40
+ const forums = parsed.forums;
41
+ if (!Array.isArray(forums))
42
+ return;
43
+ for (const item of forums) {
44
+ if (!item || typeof item !== 'object')
45
+ continue;
46
+ const entry = item;
47
+ const forumChannelId = typeof entry.forumChannelId === 'string' ? entry.forumChannelId : '';
48
+ const outputDir = typeof entry.outputDir === 'string' ? entry.outputDir : '';
49
+ const direction = isForumSyncDirection(entry.direction)
50
+ ? entry.direction
51
+ : 'bidirectional';
52
+ if (!forumChannelId || !outputDir)
53
+ continue;
54
+ await upsertForumSyncConfig({
55
+ appId,
56
+ forumChannelId,
57
+ outputDir: resolveOutputDir(outputDir),
58
+ direction,
59
+ });
60
+ }
61
+ // Rename so we don't re-import next time
62
+ const backupPath = configPath + '.migrated';
63
+ fs.renameSync(configPath, backupPath);
64
+ forumLogger.log(`Legacy config migrated and renamed to ${path.basename(backupPath)}`);
65
+ }
66
+ export async function readForumSyncConfig({ appId }) {
67
+ if (!appId)
68
+ return [];
69
+ // Migrate legacy JSON file on first run
70
+ await migrateLegacyConfig({ appId });
71
+ const rows = await getForumSyncConfigs({ appId });
72
+ return rows.map((row) => ({
73
+ forumChannelId: row.forumChannelId,
74
+ outputDir: resolveOutputDir(row.outputDir),
75
+ direction: isForumSyncDirection(row.direction)
76
+ ? row.direction
77
+ : 'bidirectional',
78
+ }));
79
+ }
@@ -0,0 +1,154 @@
1
+ // Discord API operations for forum sync.
2
+ // Resolves forum channels, fetches threads (active + archived) with pagination,
3
+ // fetches thread messages, loads existing forum files from disk, and ensures directories.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { ChannelType, } from 'discord.js';
7
+ import { createLogger } from '../logger.js';
8
+ import { parseFrontmatter, getStringValue } from './markdown.js';
9
+ import { DEFAULT_RATE_LIMIT_DELAY_MS, ForumChannelResolveError, ForumSyncOperationError, delay, } from './types.js';
10
+ const forumLogger = createLogger('FORUM');
11
+ export function getCanonicalThreadFilePath({ outputDir, threadId, subfolder, }) {
12
+ if (subfolder) {
13
+ return path.join(outputDir, subfolder, `${threadId}.md`);
14
+ }
15
+ return path.join(outputDir, `${threadId}.md`);
16
+ }
17
+ export async function ensureDirectory({ directory }) {
18
+ const result = await fs.promises.mkdir(directory, { recursive: true }).catch((cause) => new ForumSyncOperationError({
19
+ forumChannelId: 'unknown',
20
+ reason: directory,
21
+ cause,
22
+ }));
23
+ if (result instanceof Error)
24
+ return result;
25
+ }
26
+ export async function resolveForumChannel({ discordClient, forumChannelId, }) {
27
+ const channel = await discordClient.channels
28
+ .fetch(forumChannelId)
29
+ .catch((cause) => new ForumChannelResolveError({ forumChannelId, cause }));
30
+ if (channel instanceof Error)
31
+ return channel;
32
+ if (!channel || channel.type !== ChannelType.GuildForum) {
33
+ return new ForumChannelResolveError({ forumChannelId });
34
+ }
35
+ return channel;
36
+ }
37
+ export async function fetchForumThreads({ forumChannel, }) {
38
+ const byId = new Map();
39
+ const active = await forumChannel.threads.fetchActive().catch((cause) => new ForumSyncOperationError({
40
+ forumChannelId: forumChannel.id,
41
+ reason: 'fetchActive failed',
42
+ cause,
43
+ }));
44
+ if (active instanceof Error)
45
+ return active;
46
+ for (const [id, thread] of active.threads) {
47
+ byId.set(id, thread);
48
+ }
49
+ let before;
50
+ while (true) {
51
+ const archived = await forumChannel.threads
52
+ .fetchArchived({ type: 'public', limit: 100, before })
53
+ .catch((cause) => new ForumSyncOperationError({
54
+ forumChannelId: forumChannel.id,
55
+ reason: 'fetchArchived failed',
56
+ cause,
57
+ }));
58
+ if (archived instanceof Error)
59
+ return archived;
60
+ const threads = Array.from(archived.threads.values());
61
+ for (const thread of threads) {
62
+ byId.set(thread.id, thread);
63
+ }
64
+ if (!archived.hasMore || threads.length === 0)
65
+ break;
66
+ const timestamps = threads
67
+ .map((thread) => thread.archiveTimestamp ?? thread.createdTimestamp)
68
+ .filter((value) => value !== null);
69
+ const oldestTimestamp = Math.min(...timestamps);
70
+ if (!Number.isFinite(oldestTimestamp))
71
+ break;
72
+ before = new Date(oldestTimestamp - 1);
73
+ await delay({ ms: DEFAULT_RATE_LIMIT_DELAY_MS });
74
+ }
75
+ return Array.from(byId.values());
76
+ }
77
+ export async function fetchThreadMessages({ thread, }) {
78
+ const byId = new Map();
79
+ let before;
80
+ while (true) {
81
+ const fetched = await thread.messages.fetch({ limit: 100, before }).catch((cause) => new ForumSyncOperationError({
82
+ forumChannelId: thread.parentId || 'unknown',
83
+ reason: `message fetch failed for thread ${thread.id}`,
84
+ cause,
85
+ }));
86
+ if (fetched instanceof Error)
87
+ return fetched;
88
+ const messages = Array.from(fetched.values());
89
+ for (const message of messages) {
90
+ byId.set(message.id, message);
91
+ }
92
+ if (messages.length < 100 || messages.length === 0)
93
+ break;
94
+ // Find oldest message for cursor - messages are sorted by Discord, last is oldest
95
+ const oldest = messages[messages.length - 1];
96
+ if (!oldest)
97
+ break;
98
+ before = oldest.id;
99
+ await delay({ ms: DEFAULT_RATE_LIMIT_DELAY_MS });
100
+ }
101
+ return Array.from(byId.values()).sort((a, b) => a.createdTimestamp - b.createdTimestamp);
102
+ }
103
+ /**
104
+ * Recursively walks a directory collecting all .md files with their relative subfolder path.
105
+ */
106
+ async function collectMarkdownFiles({ dir, outputDir, }) {
107
+ if (!fs.existsSync(dir))
108
+ return [];
109
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
110
+ const relativeSub = path.relative(outputDir, dir);
111
+ const subfolder = relativeSub && relativeSub !== '.' ? relativeSub : undefined;
112
+ const mdFiles = entries
113
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
114
+ .map((entry) => ({ filePath: path.join(dir, entry.name), subfolder }));
115
+ const subdirs = entries.filter((entry) => entry.isDirectory());
116
+ const nestedResults = await Promise.all(subdirs.map((subdir) => collectMarkdownFiles({
117
+ dir: path.join(dir, subdir.name),
118
+ outputDir,
119
+ })));
120
+ return [...mdFiles, ...nestedResults.flat()];
121
+ }
122
+ export async function loadExistingForumFiles({ outputDir, }) {
123
+ const markdownEntries = await collectMarkdownFiles({
124
+ dir: outputDir,
125
+ outputDir,
126
+ });
127
+ const loaded = await Promise.all(markdownEntries.map(async ({ filePath, subfolder }) => {
128
+ const content = await fs.promises
129
+ .readFile(filePath, 'utf8')
130
+ .catch((cause) => {
131
+ forumLogger.warn(`Failed to read forum file ${filePath}:`, cause);
132
+ return null;
133
+ });
134
+ if (content === null)
135
+ return null;
136
+ const parsed = parseFrontmatter({ markdown: content });
137
+ const threadIdFromFrontmatter = getStringValue({
138
+ value: parsed.frontmatter.threadId,
139
+ });
140
+ const threadIdFromFilename = path.basename(filePath, '.md');
141
+ const threadId = threadIdFromFrontmatter ||
142
+ (/^\d+$/.test(threadIdFromFilename) ? threadIdFromFilename : '');
143
+ if (!threadId)
144
+ return null;
145
+ const result = {
146
+ filePath,
147
+ threadId,
148
+ frontmatter: parsed.frontmatter,
149
+ subfolder,
150
+ };
151
+ return result;
152
+ }));
153
+ return loaded.filter((item) => item !== null);
154
+ }
@@ -0,0 +1,5 @@
1
+ // Forum sync module entry point.
2
+ // Re-exports the public API for forum <-> markdown synchronization.
3
+ export { startConfiguredForumSync, stopConfiguredForumSync, } from './watchers.js';
4
+ export { syncForumToFiles } from './sync-to-files.js';
5
+ export { syncFilesToForum } from './sync-to-discord.js';
@@ -0,0 +1,117 @@
1
+ // Markdown parsing, serialization, and section formatting for forum sync.
2
+ // Handles frontmatter extraction, message section building, and
3
+ // conversion between Discord messages and markdown format.
4
+ import yaml from 'js-yaml';
5
+ import * as errore from 'errore';
6
+ import { ForumFrontmatterParseError, } from './types.js';
7
+ export function toStringArray({ value }) {
8
+ if (!Array.isArray(value))
9
+ return [];
10
+ return value.filter((item) => typeof item === 'string');
11
+ }
12
+ export function getStringValue({ value }) {
13
+ if (typeof value !== 'string')
14
+ return '';
15
+ return value;
16
+ }
17
+ export function parseFrontmatter({ markdown, }) {
18
+ if (!markdown.startsWith('---\n')) {
19
+ return { frontmatter: {}, body: markdown.trim() };
20
+ }
21
+ const end = markdown.indexOf('\n---\n', 4);
22
+ if (end === -1) {
23
+ return { frontmatter: {}, body: markdown.trim() };
24
+ }
25
+ const rawFrontmatter = markdown.slice(4, end);
26
+ const body = markdown.slice(end + 5).trim();
27
+ const parsed = errore.try({
28
+ try: () => yaml.load(rawFrontmatter),
29
+ catch: (cause) => new ForumFrontmatterParseError({ reason: 'yaml parse failed', cause }),
30
+ });
31
+ if (parsed instanceof Error || !parsed || typeof parsed !== 'object') {
32
+ return { frontmatter: {}, body };
33
+ }
34
+ return { frontmatter: parsed, body };
35
+ }
36
+ export function stringifyFrontmatter({ frontmatter, body, }) {
37
+ const yamlText = yaml
38
+ .dump(frontmatter, {
39
+ lineWidth: 120,
40
+ noRefs: true,
41
+ sortKeys: false,
42
+ })
43
+ .trim();
44
+ return `---\n${yamlText}\n---\n\n${body.trim()}\n`;
45
+ }
46
+ export function splitSections({ body }) {
47
+ return body
48
+ .split(/\r?\n---\r?\n/g)
49
+ .map((part) => part.trim())
50
+ .filter((part) => part.length > 0);
51
+ }
52
+ export function extractStarterContent({ body }) {
53
+ const sections = splitSections({ body });
54
+ const firstSection = sections[0] || '';
55
+ const match = firstSection.match(/^\*\*.+?\*\* \(\d+\) - .+?(?: \(edited .+?\))?\r?\n\r?\n([\s\S]*)$/);
56
+ if (!match)
57
+ return body.trim();
58
+ return (match[1] || '').trim();
59
+ }
60
+ export function buildMessageSections({ messages, }) {
61
+ return messages.map((message) => {
62
+ const attachmentLines = Array.from(message.attachments.values()).map((attachment) => `Attachment: ${attachment.url}`);
63
+ const contentParts = [];
64
+ const trimmedContent = message.content.trim();
65
+ if (trimmedContent) {
66
+ contentParts.push(trimmedContent);
67
+ }
68
+ if (attachmentLines.length > 0) {
69
+ contentParts.push(attachmentLines.join('\n'));
70
+ }
71
+ const content = contentParts.length > 0
72
+ ? contentParts.join('\n\n')
73
+ : '_(no text content)_';
74
+ return {
75
+ messageId: message.id,
76
+ authorName: message.author.username,
77
+ authorId: message.author.id,
78
+ createdAt: new Date(message.createdTimestamp).toISOString(),
79
+ editedAt: message.editedTimestamp
80
+ ? new Date(message.editedTimestamp).toISOString()
81
+ : null,
82
+ content,
83
+ };
84
+ });
85
+ }
86
+ export function formatMessageSection({ section, }) {
87
+ const editedSuffix = section.editedAt ? ` (edited ${section.editedAt})` : '';
88
+ return `**${section.authorName}** (${section.authorId}) - ${section.createdAt}${editedSuffix}\n\n${section.content}`;
89
+ }
90
+ // Channel mention footer stored in the Discord starter message so
91
+ // projectChannelId survives a full re-sync from Discord (no local files).
92
+ // Uses <#id> so Discord renders it as a clickable channel link.
93
+ // Matches at start-of-string or after a newline so it works even when the
94
+ // footer is the only content in the message (e.g. empty body).
95
+ const PROJECT_CHANNEL_FOOTER_RE = /(?:^|\n)channel: <#(\d{17,20})>\s*$/;
96
+ const MAX_STARTER_MESSAGE_LENGTH = 2_000;
97
+ /** Append a channel mention footer, truncating the body so the total
98
+ * never exceeds Discord's 2000-char starter message limit. */
99
+ export function appendProjectChannelFooter({ content, projectChannelId, }) {
100
+ if (!projectChannelId)
101
+ return content;
102
+ const footer = `\nchannel: <#${projectChannelId}>`;
103
+ const maxContentLength = MAX_STARTER_MESSAGE_LENGTH - footer.length;
104
+ const truncated = content.length > maxContentLength
105
+ ? content.slice(0, maxContentLength)
106
+ : content;
107
+ return `${truncated}${footer}`;
108
+ }
109
+ export function extractProjectChannelFromContent({ content, }) {
110
+ const match = content.match(PROJECT_CHANNEL_FOOTER_RE);
111
+ if (!match)
112
+ return { cleanContent: content };
113
+ return {
114
+ cleanContent: content.replace(PROJECT_CHANNEL_FOOTER_RE, '').trim(),
115
+ projectChannelId: match[1],
116
+ };
117
+ }