-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.json
More file actions
930 lines (930 loc) · 221 KB
/
project.json
File metadata and controls
930 lines (930 loc) · 221 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
{
"projectId": "895875aa-8408-4bd0-925b-223c1182a8f9",
"commands": [
{
"command": "/admin_stats",
"description": "Handler for /admin_stats",
"example": "User: /admin_stats → bot replies."
},
{
"command": "/help",
"description": "Shows all public commands and example usage.",
"usage": "/help",
"examples": [
"User: /help → Bot: command list and examples"
],
"example": "User: /help → Bot: command list and examples",
"notes": "You can also just type things like “pdf to word” or “merge pdfs”."
},
{
"command": "/reset",
"description": "Clears your active workflow state and clears your stored memory.",
"usage": "/reset",
"examples": [
"User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs."
],
"example": "User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs.",
"notes": "If MongoDB is configured, this also deletes your memory records."
},
{
"command": "/start",
"description": "Explains what the bot can do and how to use it.",
"usage": "/start",
"examples": [
"User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs"
],
"example": "User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs",
"notes": "Send files as documents. Large files may be refused based on MAX_FILE_MB."
},
{
"command": "/status",
"description": "Shows the current selected mode, queued PDFs count, and last action.",
"usage": "/status",
"examples": [
"User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added"
],
"example": "User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added",
"notes": "Useful when you’re in the middle of merging."
}
],
"aiMessages": [
{
"role": "user",
"content": "Create a bot that can convert PDF files to Word documents and vice versa, as well as merge multiple PDF files into a single PDF file"
},
{
"role": "assistant",
"content": "Created a complete, production-ready grammY Telegram bot for PDF→Word, Word→PDF, and PDF merging. It uses session state for per-chat workflows, MongoDB-backed long-term memory when available (with in-memory fallback), CookMyBots AI gateway for intent parsing and friendly replies, pdf-lib for merging, and LibreOffice (soffice) for conversions with graceful failure messaging if the binary is missing. Long polling uses @grammyjs/runner with webhook cleanup and 409 conflict backoff.\n\nFiles touched (23): .env.sample, DOCS.md, README.md, package.json, project.json, src/bot.js…\nValidation: ✅ project passes syntax/basic checks after this edit."
}
],
"createdBy": "6990b2835884d0ec1bad5434",
"source": "ai-cold-start",
"description": "",
"platform": "telegram",
"planMarkdown": "Bot: Telegram Document Tools Bot (PDF <-> Word, PDF Merge)\n\nSummary:\nA production-ready Telegram bot built with Node.js (ESM) and grammY that helps users convert documents between PDF and Word formats (PDF to DOCX, DOCX to PDF) and merge multiple PDFs into a single PDF. The bot is designed to be simple in chat, reliable under real-world usage, and safe with user data.\n\nUsers interact via a guided flow: choose an operation, upload one or more files, confirm options, then receive the processed result. The system emphasizes predictable limits, clear progress messaging, robust validation, and secure temporary file handling.\n\nThe bot runs as a single Node.js service. MongoDB is used for persistence of jobs, user preferences, and audit metadata. File payloads are stored temporarily in simple filesystem storage or object storage, and cleaned up automatically based on retention rules.\n\nProduct goals:\nPrimary user goals\n1) Convert a PDF to a Word document (DOCX) with minimal friction.\n2) Convert a Word document (DOCX) to a PDF.\n3) Merge multiple PDFs into one combined PDF in user-defined order.\n\nProduct principles\n1) Chat-first UX: minimal commands, guided prompts, and inline buttons to reduce user error.\n2) Predictable outcomes: communicate limitations (scanned PDFs, complex layouts) and handle failures gracefully.\n3) Safety and privacy: validate inputs, restrict file sizes/types, isolate processing, and auto-delete temporary files.\n4) Production operability: job tracking, retries where safe, metrics, and clear admin diagnostics.\n\nNon-goals (explicit)\n1) Full OCR and perfect layout reconstruction for scanned/complex PDFs is not guaranteed. If OCR is added later, it should be presented as an optional mode.\n2) Editing documents inside Telegram is out of scope. The bot focuses on conversion and merging.\n3) Long-term document storage for users is out of scope; the bot provides short retention for processing and delivery.\n\nHigh-level architecture:\nHigh-level components (single Node.js service)\n1) Telegram Bot Layer (grammY)\n 1) Updates handler, command router, and conversational state management.\n 2) Inline keyboard interactions for selecting operation, confirming options, and controlling merge order.\n 3) File intake: download Telegram files after validating type and size.\n\n2) Job Orchestrator (in-process)\n 1) Creates and tracks jobs (convert or merge) and their steps.\n 2) Enforces concurrency limits per user and globally to protect CPU/memory.\n 3) Implements a simple in-process queue (no external queue) with backpressure.\n\n3) Document Processing Layer\n 1) Conversion workers that run the actual PDF <-> DOCX transformations.\n 2) PDF merge worker that combines multiple PDFs and validates the resulting file.\n 3) Sandboxed execution approach within the service process boundaries (resource limits at the application level), plus strict timeouts and file size limits.\n\n4) Storage Layer\n 1) Temporary file storage: simple filesystem storage (preferred for simplicity) or object storage if the runtime environment requires it.\n 2) Metadata persistence: MongoDB for user settings, job records, and minimal audit logs.\n 3) Automatic cleanup: TTL-based deletion of temp files and pruning of old job records.\n\n5) Observability and Admin Utilities\n 1) Structured logging with correlation IDs (jobId, userId, chatId).\n 2) Basic metrics (jobs created/completed/failed, processing duration, download/upload sizes).\n 3) Admin-only commands for health, queue depth, and recent failures.\n\nRequest lifecycle (end-to-end)\n1) User selects an operation and uploads file(s).\n2) Bot validates input, creates a job in MongoDB, stores files temporarily, and enqueues processing.\n3) Worker executes conversion/merge with timeouts and step-level status updates.\n4) Bot sends the output document back to the user, updates job status, and schedules cleanup.\n\nResilience strategy\n1) Idempotency: each job has a stable ID; repeated update deliveries do not duplicate processing.\n2) Safe retries: retry only steps that are safe (download, upload) and avoid retrying a conversion that could produce inconsistent results unless the previous attempt produced no output.\n3) Degraded mode: if processing is overloaded, the bot can accept jobs but estimate wait time and throttle per user.\n\nSecurity boundaries\n1) Treat all uploaded files as untrusted input.\n2) Validate MIME type, extension, and file signature where feasible.\n3) Enforce strict max file size, max pages (if detectable), and max number of merge inputs.\n4) Avoid storing user documents long-term; delete outputs shortly after delivery (configurable retention).\n\nData model:\nMongoDB collections (minimal, practical)\n\n1) users\nPurpose: store user preferences and usage limits.\nKey fields\n1) userId (Telegram user id)\n2) createdAt, updatedAt\n3) locale (optional)\n4) defaultOperation (optional)\n5) rateLimitTier (default or premium if you later add subscriptions)\n6) lastSeenAt\n\n2) jobs\nPurpose: track each conversion/merge request end-to-end.\nKey fields\n1) jobId (unique)\n2) userId, chatId\n3) type (pdftodocx, docxtopdf, pdfmerge)\n4) status (created, waitingforfiles, queued, processing, uploading, completed, failed, canceled, expired)\n5) createdAt, startedAt, finishedAt\n6) inputFiles: array of\n 1) telegramFileId (for reuse) and telegramUniqueFileId\n 2) originalName, mimeType, sizeBytes\n 3) tempStoragePathOrKey\n 4) orderIndex (for merge)\n7) outputFile\n 1) mimeType, sizeBytes\n 2) tempStoragePathOrKey\n 3) telegramFileId (after upload, for caching)\n8) options\n 1) mergeOrder (explicit order list)\n 2) outputName (optional)\n 3) conversionMode (future: fast vs accurate)\n9) error\n 1) code (validationerror, processingerror, timeout, unsupported, toolarge)\n 2) message (sanitized)\n 3) debugRef (internal correlation id)\n\n3) events (optional)\nPurpose: lightweight audit trail for debugging and support.\nKey fields\n1) eventId\n2) jobId, userId\n3) type (jobcreated, filereceived, processingstarted, processingfailed, outputsent, cleanupdone)\n4) timestamp\n5) meta (small payload)\n\nIndexes and retention\n1) jobs: index on userId + createdAt for history.\n2) jobs: index on status for operational queries.\n3) TTL index on jobs.finishedAt or jobs.createdAt (configurable retention, e.g., 24 hours to 7 days) depending on support needs.\n4) users: index on userId.\n\nIn-memory maps (supplemental, non-authoritative)\n1) per-user active job pointer for ongoing conversation.\n2) transient upload session state (e.g., expected number of PDFs for merge).\nThese should be recoverable from MongoDB so a restart does not break flows.\n\nKey flows:\nFlow A: PDF to Word (PDF -> DOCX)\n1) User starts with /start or taps Convert PDF to Word.\n2) Bot prompts: Send a PDF file.\n3) User uploads a document.\n4) Bot validates\n 1) Is it a document upload (not photo) and is it PDF.\n 2) Size within limit.\n 3) Optional: quick check that it’s not encrypted or corrupted (best effort).\n5) Bot creates a job with status queued and acknowledges with an estimated wait time.\n6) Worker downloads the file from Telegram to temporary storage.\n7) Worker runs conversion.\n8) Bot uploads DOCX result back to the user.\n9) Job marked completed; cleanup scheduled.\n\nUser-visible messaging\n1) Clear status updates: Received, Queued, Processing, Sending.\n2) If conversion quality may be imperfect (scans/complex layouts), mention this before processing and provide a fallback suggestion (e.g., try again with a different file, or in future add OCR mode).\n\nFlow B: Word to PDF (DOCX -> PDF)\n1) User selects Convert Word to PDF.\n2) Bot prompts: Send a DOCX file.\n3) Validate DOCX, size limit.\n4) Create job and enqueue.\n5) Download, convert, upload PDF.\n6) Cleanup.\n\nFlow C: Merge PDFs\n1) User selects Merge PDFs.\n2) Bot prompts: Send PDFs one by one. Provide inline buttons: Done, Cancel, Clear.\n3) User uploads multiple PDF documents.\n4) After each file, bot confirms count and shows current order.\n5) When user taps Done, bot shows an order management screen:\n 1) List files with numbers.\n 2) Controls: Move up/down for each entry, Remove entry, Add more.\n6) User confirms Merge.\n7) Bot creates job and enqueues.\n8) Worker downloads each input (if not already local), validates each PDF, merges in selected order.\n9) Bot uploads merged PDF with a sensible filename.\n10) Cleanup.\n\nFlow D: Error handling and recovery\n1) Unsupported file type\n 1) Bot explains accepted formats and asks the user to send the correct one.\n2) Too large\n 1) Bot rejects early and states the limit.\n 2) Suggest splitting or compressing before retry.\n3) Processing failure\n 1) Job marked failed with a user-friendly message.\n 2) Provide a Retry button that creates a new job referencing the same input file ids when possible.\n4) Timeout\n 1) Mark failed with suggestion to try smaller files.\n5) User cancels\n 1) Cancel button sets status canceled and triggers cleanup.\n\nFlow E: Rate limiting and abuse prevention\n1) Limit jobs per user per time window.\n2) Limit concurrent jobs per user (e.g., 1 active processing job, 1 queued).\n3) Hard caps\n 1) Max input size per file.\n 2) Max number of PDFs for merge.\n 3) Max total bytes across a merge job.\n4) If limits are hit, respond with a clear wait/try-later message.\n\nFlow F: Operational flows\n1) Startup health checks\n 1) Verify MongoDB connectivity.\n 2) Verify temp storage directory exists and is writable.\n2) Crash/restart recovery\n 1) On boot, find jobs in processing state older than a threshold and mark them failed or re-queue based on safe rules.\n 2) Clean orphaned temp files older than retention.\n3) Admin inspection\n 1) View recent failures and the sanitized reason.\n 2) Check queue depth and worker utilization.\n\nTech stack:\nRuntime and framework\n1) Node.js (ESM) single service.\n2) grammY for Telegram bot update handling, middleware, and conversational flows.\n3) Environment variables for configuration, including TELEGRAMBOTTOKEN.\n\nPersistence\n1) MongoDB for job and user metadata persistence.\n2) In-memory maps for ephemeral session state and per-process queue bookkeeping, with MongoDB as the source of truth for job status.\n\nFile handling\n1) Temporary storage in simple filesystem storage (local to the service) or object storage.\n2) Strict retention and cleanup policies to avoid accumulating user documents.\n\nDocument processing\n1) A pluggable processing layer that can call a conversion engine (library or bundled CLI tool) for:\n 1) PDF to DOCX conversion\n 2) DOCX to PDF conversion\n 3) PDF merge\n2) The processing layer must support:\n 1) timeouts per job\n 2) memory and file size safeguards\n 3) deterministic input/output paths\n 4) validation of produced files (non-empty, correct type)\n\nDeployment and configuration\n1) A generic Node.js server in the cloud.\n2) Webhook or long polling supported; webhook recommended for production if stable inbound connectivity is available.\n3) Configuration via environment variables:\n 1) TELEGRAMBOTTOKEN\n 2) MONGODBURI\n 3) TEMPSTORAGEPATH (if filesystem)\n 4) OBJECTSTORAGECONFIG (if used)\n 5) MAXFILESIZEMB, MAXMERGEFILES, MAXCONCURRENTJOBSGLOBAL, MAXCONCURRENTJOBSPERUSER\n 6) JOBRETENTIONHOURS\n\nNo additional infrastructure\n1) No additional databases beyond MongoDB.\n2) No external queues; the job queue is in-process with MongoDB-backed job records.\n\nNon-functional requirements:\nReliability\n1) Exactly-once user experience: avoid double-processing due to repeated Telegram updates by using job IDs and state checks.\n2) Safe restart behavior: recover or fail stale processing jobs deterministically.\n3) Bounded resources: hard limits on concurrency and file sizes to keep the single service stable.\n\nPerformance\n1) Concurrency caps: separate limits for download/upload and CPU-heavy conversion.\n2) Streaming where possible for Telegram file download/upload to reduce memory spikes.\n3) Fast feedback: acknowledge file receipt immediately and provide queue position or estimated wait.\n\nSecurity and privacy\n1) Validate all inputs, never trust filenames or MIME types alone.\n2) Store documents only as long as needed to process and deliver.\n3) Sanitize error messages returned to users; keep internal debug references in logs.\n4) Admin commands restricted by allowlist of Telegram user IDs.\n\nMaintainability\n1) Modular design: bot UI layer, job orchestration, processing adapters, storage adapter.\n2) Pluggable conversion engines: allow swapping conversion implementation without changing bot flows.\n3) Clear job state machine with explicit transitions.\n\nCompliance-like practices (practical)\n1) Data minimization: only store necessary metadata.\n2) Retention policy: automatic deletion with configurable retention.\n3) Transparency: a /privacy command explaining how files are handled and how long they are kept.\n\nTesting strategy\n1) Unit tests for validation, job state transitions, and merge order logic.\n2) Integration tests for Telegram file handling and end-to-end job lifecycle using test chats.\n3) Golden-file tests for conversions on a small set of known documents to detect regressions.\n\nOperational readiness\n1) Structured logs with jobId and userId.\n2) Alerting hooks are optional but logs should be actionable.\n3) Admin tooling to inspect failures and queue pressure without accessing user content.\n\nBot commands:\n• /start — Start the bot and show the main menu of document tools. (usage: /start) [general]\n• /help — Explain supported operations, limits, and how to use the bot. (usage: /help) [general]\n• /convert — Open a guided flow to choose conversion direction (PDF->DOCX or DOCX->PDF). (usage: /convert) [core]\n• /merge — Start a guided flow to collect multiple PDFs and merge them in a chosen order. (usage: /merge) [core]\n• /status — Show the status of your current or most recent job. (usage: /status) [core]\n• /cancel — Cancel the current active flow or queued/processing job when possible. (usage: /cancel) [core]\n• /limits — Display current file size limits, merge limits, and retention policy. (usage: /limits) [general]\n• /privacy — Explain how files are processed, stored temporarily, and deleted. (usage: /privacy) [general]\n• /adminhealth — Admin-only: show bot health, MongoDB connectivity, and temp storage status. (usage: /adminhealth) [admin]\n• /adminqueue — Admin-only: show queue depth, number of processing jobs, and recent throughput. (usage: /adminqueue) [admin]\n• /adminfailures — Admin-only: list recent failed jobs with sanitized reasons and debug references. (usage: /adminfailures) [admin]\n",
"planSections": {
"productGoals": "Primary user goals\n1) Convert a PDF to a Word document (DOCX) with minimal friction.\n2) Convert a Word document (DOCX) to a PDF.\n3) Merge multiple PDFs into one combined PDF in user-defined order.\n\nProduct principles\n1) Chat-first UX: minimal commands, guided prompts, and inline buttons to reduce user error.\n2) Predictable outcomes: communicate limitations (scanned PDFs, complex layouts) and handle failures gracefully.\n3) Safety and privacy: validate inputs, restrict file sizes/types, isolate processing, and auto-delete temporary files.\n4) Production operability: job tracking, retries where safe, metrics, and clear admin diagnostics.\n\nNon-goals (explicit)\n1) Full OCR and perfect layout reconstruction for scanned/complex PDFs is not guaranteed. If OCR is added later, it should be presented as an optional mode.\n2) Editing documents inside Telegram is out of scope. The bot focuses on conversion and merging.\n3) Long-term document storage for users is out of scope; the bot provides short retention for processing and delivery.",
"highLevelArchitecture": "High-level components (single Node.js service)\n1) Telegram Bot Layer (grammY)\n 1) Updates handler, command router, and conversational state management.\n 2) Inline keyboard interactions for selecting operation, confirming options, and controlling merge order.\n 3) File intake: download Telegram files after validating type and size.\n\n2) Job Orchestrator (in-process)\n 1) Creates and tracks jobs (convert or merge) and their steps.\n 2) Enforces concurrency limits per user and globally to protect CPU/memory.\n 3) Implements a simple in-process queue (no external queue) with backpressure.\n\n3) Document Processing Layer\n 1) Conversion workers that run the actual PDF <-> DOCX transformations.\n 2) PDF merge worker that combines multiple PDFs and validates the resulting file.\n 3) Sandboxed execution approach within the service process boundaries (resource limits at the application level), plus strict timeouts and file size limits.\n\n4) Storage Layer\n 1) Temporary file storage: simple filesystem storage (preferred for simplicity) or object storage if the runtime environment requires it.\n 2) Metadata persistence: MongoDB for user settings, job records, and minimal audit logs.\n 3) Automatic cleanup: TTL-based deletion of temp files and pruning of old job records.\n\n5) Observability and Admin Utilities\n 1) Structured logging with correlation IDs (jobId, userId, chatId).\n 2) Basic metrics (jobs created/completed/failed, processing duration, download/upload sizes).\n 3) Admin-only commands for health, queue depth, and recent failures.\n\nRequest lifecycle (end-to-end)\n1) User selects an operation and uploads file(s).\n2) Bot validates input, creates a job in MongoDB, stores files temporarily, and enqueues processing.\n3) Worker executes conversion/merge with timeouts and step-level status updates.\n4) Bot sends the output document back to the user, updates job status, and schedules cleanup.\n\nResilience strategy\n1) Idempotency: each job has a stable ID; repeated update deliveries do not duplicate processing.\n2) Safe retries: retry only steps that are safe (download, upload) and avoid retrying a conversion that could produce inconsistent results unless the previous attempt produced no output.\n3) Degraded mode: if processing is overloaded, the bot can accept jobs but estimate wait time and throttle per user.\n\nSecurity boundaries\n1) Treat all uploaded files as untrusted input.\n2) Validate MIME type, extension, and file signature where feasible.\n3) Enforce strict max file size, max pages (if detectable), and max number of merge inputs.\n4) Avoid storing user documents long-term; delete outputs shortly after delivery (configurable retention).",
"dataModel": "MongoDB collections (minimal, practical)\n\n1) users\nPurpose: store user preferences and usage limits.\nKey fields\n1) userId (Telegram user id)\n2) createdAt, updatedAt\n3) locale (optional)\n4) defaultOperation (optional)\n5) rateLimitTier (default or premium if you later add subscriptions)\n6) lastSeenAt\n\n2) jobs\nPurpose: track each conversion/merge request end-to-end.\nKey fields\n1) jobId (unique)\n2) userId, chatId\n3) type (pdftodocx, docxtopdf, pdfmerge)\n4) status (created, waitingforfiles, queued, processing, uploading, completed, failed, canceled, expired)\n5) createdAt, startedAt, finishedAt\n6) inputFiles: array of\n 1) telegramFileId (for reuse) and telegramUniqueFileId\n 2) originalName, mimeType, sizeBytes\n 3) tempStoragePathOrKey\n 4) orderIndex (for merge)\n7) outputFile\n 1) mimeType, sizeBytes\n 2) tempStoragePathOrKey\n 3) telegramFileId (after upload, for caching)\n8) options\n 1) mergeOrder (explicit order list)\n 2) outputName (optional)\n 3) conversionMode (future: fast vs accurate)\n9) error\n 1) code (validationerror, processingerror, timeout, unsupported, toolarge)\n 2) message (sanitized)\n 3) debugRef (internal correlation id)\n\n3) events (optional)\nPurpose: lightweight audit trail for debugging and support.\nKey fields\n1) eventId\n2) jobId, userId\n3) type (jobcreated, filereceived, processingstarted, processingfailed, outputsent, cleanupdone)\n4) timestamp\n5) meta (small payload)\n\nIndexes and retention\n1) jobs: index on userId + createdAt for history.\n2) jobs: index on status for operational queries.\n3) TTL index on jobs.finishedAt or jobs.createdAt (configurable retention, e.g., 24 hours to 7 days) depending on support needs.\n4) users: index on userId.\n\nIn-memory maps (supplemental, non-authoritative)\n1) per-user active job pointer for ongoing conversation.\n2) transient upload session state (e.g., expected number of PDFs for merge).\nThese should be recoverable from MongoDB so a restart does not break flows.",
"keyFlows": "Flow A: PDF to Word (PDF -> DOCX)\n1) User starts with /start or taps Convert PDF to Word.\n2) Bot prompts: Send a PDF file.\n3) User uploads a document.\n4) Bot validates\n 1) Is it a document upload (not photo) and is it PDF.\n 2) Size within limit.\n 3) Optional: quick check that it’s not encrypted or corrupted (best effort).\n5) Bot creates a job with status queued and acknowledges with an estimated wait time.\n6) Worker downloads the file from Telegram to temporary storage.\n7) Worker runs conversion.\n8) Bot uploads DOCX result back to the user.\n9) Job marked completed; cleanup scheduled.\n\nUser-visible messaging\n1) Clear status updates: Received, Queued, Processing, Sending.\n2) If conversion quality may be imperfect (scans/complex layouts), mention this before processing and provide a fallback suggestion (e.g., try again with a different file, or in future add OCR mode).\n\nFlow B: Word to PDF (DOCX -> PDF)\n1) User selects Convert Word to PDF.\n2) Bot prompts: Send a DOCX file.\n3) Validate DOCX, size limit.\n4) Create job and enqueue.\n5) Download, convert, upload PDF.\n6) Cleanup.\n\nFlow C: Merge PDFs\n1) User selects Merge PDFs.\n2) Bot prompts: Send PDFs one by one. Provide inline buttons: Done, Cancel, Clear.\n3) User uploads multiple PDF documents.\n4) After each file, bot confirms count and shows current order.\n5) When user taps Done, bot shows an order management screen:\n 1) List files with numbers.\n 2) Controls: Move up/down for each entry, Remove entry, Add more.\n6) User confirms Merge.\n7) Bot creates job and enqueues.\n8) Worker downloads each input (if not already local), validates each PDF, merges in selected order.\n9) Bot uploads merged PDF with a sensible filename.\n10) Cleanup.\n\nFlow D: Error handling and recovery\n1) Unsupported file type\n 1) Bot explains accepted formats and asks the user to send the correct one.\n2) Too large\n 1) Bot rejects early and states the limit.\n 2) Suggest splitting or compressing before retry.\n3) Processing failure\n 1) Job marked failed with a user-friendly message.\n 2) Provide a Retry button that creates a new job referencing the same input file ids when possible.\n4) Timeout\n 1) Mark failed with suggestion to try smaller files.\n5) User cancels\n 1) Cancel button sets status canceled and triggers cleanup.\n\nFlow E: Rate limiting and abuse prevention\n1) Limit jobs per user per time window.\n2) Limit concurrent jobs per user (e.g., 1 active processing job, 1 queued).\n3) Hard caps\n 1) Max input size per file.\n 2) Max number of PDFs for merge.\n 3) Max total bytes across a merge job.\n4) If limits are hit, respond with a clear wait/try-later message.\n\nFlow F: Operational flows\n1) Startup health checks\n 1) Verify MongoDB connectivity.\n 2) Verify temp storage directory exists and is writable.\n2) Crash/restart recovery\n 1) On boot, find jobs in processing state older than a threshold and mark them failed or re-queue based on safe rules.\n 2) Clean orphaned temp files older than retention.\n3) Admin inspection\n 1) View recent failures and the sanitized reason.\n 2) Check queue depth and worker utilization.",
"techStack": "Runtime and framework\n1) Node.js (ESM) single service.\n2) grammY for Telegram bot update handling, middleware, and conversational flows.\n3) Environment variables for configuration, including TELEGRAMBOTTOKEN.\n\nPersistence\n1) MongoDB for job and user metadata persistence.\n2) In-memory maps for ephemeral session state and per-process queue bookkeeping, with MongoDB as the source of truth for job status.\n\nFile handling\n1) Temporary storage in simple filesystem storage (local to the service) or object storage.\n2) Strict retention and cleanup policies to avoid accumulating user documents.\n\nDocument processing\n1) A pluggable processing layer that can call a conversion engine (library or bundled CLI tool) for:\n 1) PDF to DOCX conversion\n 2) DOCX to PDF conversion\n 3) PDF merge\n2) The processing layer must support:\n 1) timeouts per job\n 2) memory and file size safeguards\n 3) deterministic input/output paths\n 4) validation of produced files (non-empty, correct type)\n\nDeployment and configuration\n1) A generic Node.js server in the cloud.\n2) Webhook or long polling supported; webhook recommended for production if stable inbound connectivity is available.\n3) Configuration via environment variables:\n 1) TELEGRAMBOTTOKEN\n 2) MONGODBURI\n 3) TEMPSTORAGEPATH (if filesystem)\n 4) OBJECTSTORAGECONFIG (if used)\n 5) MAXFILESIZEMB, MAXMERGEFILES, MAXCONCURRENTJOBSGLOBAL, MAXCONCURRENTJOBSPERUSER\n 6) JOBRETENTIONHOURS\n\nNo additional infrastructure\n1) No additional databases beyond MongoDB.\n2) No external queues; the job queue is in-process with MongoDB-backed job records.",
"nonFunctional": "Reliability\n1) Exactly-once user experience: avoid double-processing due to repeated Telegram updates by using job IDs and state checks.\n2) Safe restart behavior: recover or fail stale processing jobs deterministically.\n3) Bounded resources: hard limits on concurrency and file sizes to keep the single service stable.\n\nPerformance\n1) Concurrency caps: separate limits for download/upload and CPU-heavy conversion.\n2) Streaming where possible for Telegram file download/upload to reduce memory spikes.\n3) Fast feedback: acknowledge file receipt immediately and provide queue position or estimated wait.\n\nSecurity and privacy\n1) Validate all inputs, never trust filenames or MIME types alone.\n2) Store documents only as long as needed to process and deliver.\n3) Sanitize error messages returned to users; keep internal debug references in logs.\n4) Admin commands restricted by allowlist of Telegram user IDs.\n\nMaintainability\n1) Modular design: bot UI layer, job orchestration, processing adapters, storage adapter.\n2) Pluggable conversion engines: allow swapping conversion implementation without changing bot flows.\n3) Clear job state machine with explicit transitions.\n\nCompliance-like practices (practical)\n1) Data minimization: only store necessary metadata.\n2) Retention policy: automatic deletion with configurable retention.\n3) Transparency: a /privacy command explaining how files are handled and how long they are kept.\n\nTesting strategy\n1) Unit tests for validation, job state transitions, and merge order logic.\n2) Integration tests for Telegram file handling and end-to-end job lifecycle using test chats.\n3) Golden-file tests for conversions on a small set of known documents to detect regressions.\n\nOperational readiness\n1) Structured logs with jobId and userId.\n2) Alerting hooks are optional but logs should be actionable.\n3) Admin tooling to inspect failures and queue pressure without accessing user content."
},
"runStatuses": {
"895875aa-8408-4bd0-925b-223c1182a8f9:mlmlnt45:1sg5c5": {
"phase": "done",
"stage": "cold_start",
"runId": "895875aa-8408-4bd0-925b-223c1182a8f9:mlmlnt45:1sg5c5",
"lastUserMessage": "Create a bot that can convert PDF files to Word documents and vice versa, as well as merge multiple PDF files into a single PDF file",
"startedAt": "2026-02-14T17:37:57.814Z",
"updatedAt": "2026-02-14T17:41:34.307Z",
"message": "GitHub auto-push skipped (no repo linked or GitHub not connected in session).",
"commands": [
{
"name": "admin_stats",
"file": "src/commands/admin_stats.js"
},
{
"name": "help",
"file": "src/commands/help.js"
},
{
"name": "reset",
"file": "src/commands/reset.js"
},
{
"name": "start",
"file": "src/commands/start.js"
},
{
"name": "status",
"file": "src/commands/status.js"
}
],
"ok": true,
"state": {
"projectId": "895875aa-8408-4bd0-925b-223c1182a8f9",
"fileStructure": {
".env.sample": {
"type": "file",
"content": "\nTELEGRAM_BOT_TOKEN=\nMONGODB_URI=\nCOOKMYBOTS_AI_ENDPOINT=https://api.cookmybots.com/api/ai\nCOOKMYBOTS_AI_KEY=\nAI_TIMEOUT_MS=600000\nAI_MAX_RETRIES=2\nCONCURRENCY=20\nMAX_FILE_MB=20\nADMIN_TELEGRAM_USER_ID=\n"
},
"CHANGELOG.md": {
"type": "file",
"content": "# Changelog\n\nAll notable changes to this bot project are recorded here.\n\n## 2026-02-14 17:41:34. UTC\n- Request: Create a bot that can convert PDF files to Word documents and vice versa, as well as merge multiple PDF files into a single PDF file\n- Summary: Created a complete, production-ready grammY Telegram bot for PDF→Word, Word→PDF, and PDF merging. It uses session state for per-chat workflows, MongoDB-backed long-term memory when available (with in-memory fallback), C…\n- Files: .env.sample, DOCS.md, README.md, package.json, project.json, src/bot.js, src/commands/admin_stats.js, src/commands/help.js, src/commands/loader.js, src/commands/reset.js, src/commands/start.js, src/commands/status.js, src/index.js, src/lib/ai.js (+9 more)\n\n"
},
"DOCS.md": {
"type": "file",
"content": "What this bot does\n\nThis Telegram bot converts documents and merges PDFs.\n\nSupported actions\n\n1) PDF to Word (.docx)\n2) Word (.doc/.docx) to PDF\n3) Merge multiple PDFs into one PDF\n\nPublic commands\n\n1) /start\nWhat it does: Welcome message and quick instructions.\nUsage: /start\n\n2) /help\nWhat it does: Shows help and examples.\nUsage: /help\n\n3) /status\nWhat it does: Shows your current mode (if any), merge queue count, and last action.\nUsage: /status\n\n4) /reset\nWhat it does: Clears your workflow state and clears your stored memory.\nUsage: /reset\n\nHow to use in chat\n\n1) Send “pdf to word” then upload a PDF.\n2) Send “word to pdf” then upload a DOC/DOCX.\n3) Send “merge pdfs” then upload PDFs in order. When ready, send “done” or press “Merge now”.\n\nWhile merging, you can also send “remove last” or “clear”.\n\nEnvironment variables\n\n1) TELEGRAM_BOT_TOKEN (required)\nTelegram bot token.\n\n2) COOKMYBOTS_AI_ENDPOINT (required)\nBase URL for the CookMyBots AI gateway. Must be a base URL ending with /api/ai.\n\n3) COOKMYBOTS_AI_KEY (required)\nAPI key for the CookMyBots AI gateway.\n\n4) MONGODB_URI (optional)\nMongoDB connection string for long-term memory.\n\n5) MAX_FILE_MB (optional)\nMaximum allowed file size in MB. Default is 20.\n\n6) ADMIN_TELEGRAM_USER_ID (optional)\nIf set, enables /admin_stats for that Telegram user id.\n\nRun\n\n1) Install: npm install\n2) Start: npm start\n3) Dev: npm run dev\n"
},
"README.md": {
"type": "file",
"content": "This is a Telegram bot (grammY) that provides document utilities:\n\n1) PDF to Word (.docx)\n2) Word (.doc/.docx) to PDF\n3) Merge multiple PDFs into one PDF\n\nIt’s designed to run as a single Node.js service on Render using long polling.\n\nSetup\n\n1) Install\n\nnpm install\n\n2) Configure environment variables\n\nCopy .env.sample to .env and fill in:\n\n1) TELEGRAM_BOT_TOKEN (required)\n2) COOKMYBOTS_AI_ENDPOINT (required for AI intent parsing and friendly replies)\n3) COOKMYBOTS_AI_KEY (required)\n4) MONGODB_URI (optional but recommended for long-term memory)\n5) MAX_FILE_MB (optional, defaults to 20)\n6) ADMIN_TELEGRAM_USER_ID (optional)\n\n3) Run locally\n\nnpm run dev\n\n4) Run in production\n\nnpm start\n\nCommands\n\n1) /start\nShows what the bot can do and how to use it.\n\n2) /help\nShows commands and examples.\n\n3) /status\nShows current mode, merge queue size, and last action.\n\n4) /reset\nClears the current workflow state and clears your stored memory.\n\nDocument processing backend\n\nPDF merge is implemented in-process using pdf-lib.\n\nPDF to Word and Word to PDF conversions require LibreOffice to be available on the system.\nThe bot will try to run the libreoffice binary (soffice). If it’s missing, the bot will fail gracefully and explain what’s needed.\n\nOn Render, you may need to use a Docker-based deployment or a build step that provides LibreOffice.\nIf LibreOffice is not present, PDF merge still works.\n\nDatabase and memory\n\nIf MONGODB_URI is set, the bot stores conversation turns in a MongoDB collection:\n\nmemory_messages\nFields: userId (string), platform (telegram), chatId (string), role (user|assistant), text, ts\n\nIf MONGODB_URI is not set, the bot uses an in-memory fallback and prints a warning log.\n\nTroubleshooting\n\n1) Bot does not respond\nMake sure TELEGRAM_BOT_TOKEN is set and valid.\n\n2) Conversion fails immediately\nLibreOffice is likely not installed or not on PATH. Deploy with LibreOffice available.\n\n3) File too large\nIncrease MAX_FILE_MB or send a smaller file.\n\nExtending\n\nAdd new commands in src/commands/*.js and they will be auto-registered by src/commands/loader.js.\nShared helpers live under src/lib and src/services.\n"
},
"package.json": {
"type": "file",
"content": "{\n \"scripts\": {\n \"install:root\": \"bash -lc \\\"set -e; if [ -f package-lock.json ]; then npm ci; else npm install; fi\\\"\",\n \"build\": \"npm run install:root && echo build\",\n \"start\": \"node src/index.js\",\n \"dev\": \"node --watch src/index.js\"\n },\n \"dependencies\": {\n \"@grammyjs/runner\": \"^2.0.3\",\n \"dotenv\": \"^16.4.5\",\n \"grammy\": \"^1.20.0\",\n \"mongodb\": \"^6.10.0\",\n \"pdf-lib\": \"latest\"\n },\n \"name\": \"document-tools-bot\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"devDependencies\": {}\n}\n"
},
"src": {
"type": "dir",
"children": {
"bot.js": {
"type": "file",
"content": "import { Bot, session } from \"grammy\";\n\nimport { registerCommands } from \"./commands/loader.js\";\nimport { cfg as readCfg } from \"./lib/config.js\";\nimport { safeErr } from \"./lib/safeErr.js\";\nimport {\n addTurn,\n getRecentTurns,\n clearUserMemory\n} from \"./lib/memory.js\";\nimport { aiChat } from \"./lib/ai.js\";\nimport { downloadTelegramDocument } from \"./services/telegramFiles.js\";\nimport { convertDocument } from \"./services/conversionService.js\";\nimport { mergePdfs } from \"./services/pdfMergeService.js\";\nimport {\n buildMainKeyboard,\n buildMergeKeyboard,\n isText\n} from \"./services/ui.js\";\n\nfunction initialSession() {\n return {\n store: {\n currentMode: null,\n mergeQueue: [],\n lastAction: \"\",\n lastPromptMsgId: null\n }\n };\n}\n\nfunction isAdmin(ctx, cfg) {\n const adminId = String(cfg.ADMIN_TELEGRAM_USER_ID || \"\").trim();\n if (!adminId) return false;\n return String(ctx.from?.id || \"\") === adminId;\n}\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nfunction inferModeFromFilename(name) {\n const n = String(name || \"\").toLowerCase();\n if (n.endsWith(\".pdf\")) return \"pdf_to_word\";\n if (n.endsWith(\".doc\") || n.endsWith(\".docx\")) return \"word_to_pdf\";\n return null;\n}\n\nasync function shouldHandleGroupMessage(ctx) {\n const chatType = ctx.chat?.type || \"private\";\n if (chatType === \"private\") return true;\n\n const botUsername = ctx.me?.username || ctx.botInfo?.username || \"\";\n if (!botUsername) return false;\n\n const msg = ctx.message;\n if (!msg) return false;\n\n const rawText = msg.text || \"\";\n const replyTo = msg.reply_to_message;\n const isReplyToBot =\n !!replyTo?.from?.is_bot &&\n String(replyTo?.from?.username || \"\").toLowerCase() ===\n String(botUsername).toLowerCase();\n\n const ents = Array.isArray(msg.entities) ? msg.entities : [];\n const isMentioned = ents.some((e) => {\n if (!e || e.type !== \"mention\") return false;\n const s = rawText.slice(e.offset, e.offset + e.length);\n return s.toLowerCase() === (\"@\" + botUsername.toLowerCase());\n });\n\n return isReplyToBot || isMentioned;\n}\n\nasync function saveUserTurn(ctx, text) {\n const userId = String(ctx.from?.id || \"\");\n const chatId = String(ctx.chat?.id || \"\");\n await addTurn({\n mongoUri: readCfg.MONGODB_URI,\n platform: \"telegram\",\n userId,\n chatId,\n role: \"user\",\n text: clampText(text)\n });\n}\n\nasync function saveAssistantTurn(ctx, text) {\n const userId = String(ctx.from?.id || \"\");\n const chatId = String(ctx.chat?.id || \"\");\n await addTurn({\n mongoUri: readCfg.MONGODB_URI,\n platform: \"telegram\",\n userId,\n chatId,\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nasync function aiInterpretText(ctx, text) {\n const userId = String(ctx.from?.id || \"\");\n const chatId = String(ctx.chat?.id || \"\");\n\n const history = await getRecentTurns({\n mongoUri: readCfg.MONGODB_URI,\n platform: \"telegram\",\n userId,\n chatId,\n limit: 16\n });\n\n const sys =\n \"You are a Telegram document utility bot. Your job is to interpret the user's intent and respond with a tiny JSON object only. \" +\n \"Allowed intents: set_mode_pdf_to_word, set_mode_word_to_pdf, set_mode_merge_pdfs, merge_done, merge_remove_last, merge_clear, status, reset, help, unknown. \" +\n \"Return JSON with keys: intent (string), reply (string). Keep reply short and friendly. Do not use markdown.\";\n\n const messages = [\n { role: \"system\", content: sys },\n ...history.map((t) => ({ role: t.role, content: t.text })),\n { role: \"user\", content: text }\n ];\n\n const out = await aiChat({\n messages,\n meta: {\n platform: \"telegram\",\n feature: \"intent\"\n }\n });\n\n const raw = String(out || \"\").trim();\n try {\n const json = JSON.parse(raw);\n return {\n intent: String(json.intent || \"unknown\"),\n reply: String(json.reply || \"\")\n };\n } catch {\n return {\n intent: \"unknown\",\n reply: \"\"\n };\n }\n}\n\nasync function handleDocument(ctx, cfg) {\n ctx.session.store ??= {};\n ctx.session.store.mergeQueue ??= [];\n\n const doc = ctx.message?.document;\n if (!doc) return;\n\n const fileName = doc.file_name || \"file\";\n const inferred = inferModeFromFilename(fileName);\n\n const mode = ctx.session.store.currentMode || inferred;\n if (!mode) {\n const msg =\n \"I can work with PDF and Word files. Tell me what you want first: pdf to word, word to pdf, or merge pdfs.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"asked_for_mode\";\n return;\n }\n\n const maxBytes = Math.max(1, Number(cfg.MAX_FILE_MB || 20)) * 1024 * 1024;\n const sizeBytes = Number(doc.file_size || 0);\n\n if (sizeBytes && sizeBytes > maxBytes) {\n const msg =\n \"That file is too large for this bot right now. Please send a smaller file (limit is \" +\n String(cfg.MAX_FILE_MB || 20) +\n \" MB).\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"rejected_too_large\";\n return;\n }\n\n if (mode === \"merge_pdfs\") {\n if (!String(fileName).toLowerCase().endsWith(\".pdf\")) {\n const msg = \"Merge mode only accepts PDFs. Please send a PDF document file.\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n ctx.session.store.mergeQueue.push({\n fileId: doc.file_id,\n fileUniqueId: doc.file_unique_id,\n fileName,\n sizeBytes,\n addedAt: new Date().toISOString()\n });\n\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.lastAction = \"merge_added\";\n\n const n = ctx.session.store.mergeQueue.length;\n const msg = \"Added. Now queued: \" + n + \". Send more PDFs, or press Merge now / send done.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (mode === \"pdf_to_word\") {\n if (!String(fileName).toLowerCase().endsWith(\".pdf\")) {\n const msg = \"For PDF to Word, please send a PDF as a document.\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n const receivedMsg = \"Got it. Converting your PDF to Word now.\";\n await ctx.reply(receivedMsg);\n await saveAssistantTurn(ctx, receivedMsg);\n\n const progress = await ctx.reply(\"Downloading file...\");\n\n try {\n console.log(\"[convert] start\", {\n mode,\n chatId: String(ctx.chat?.id || \"\"),\n userId: String(ctx.from?.id || \"\"),\n fileName,\n sizeBytes\n });\n\n const input = await downloadTelegramDocument(ctx.api, cfg.TELEGRAM_BOT_TOKEN, doc, {\n maxBytes\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Processing...\");\n\n const out = await convertDocument({\n direction: \"pdf_to_word\",\n inputBuffer: input.buffer,\n inputFilename: fileName\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Uploading...\");\n\n await ctx.api.sendDocument(\n ctx.chat.id,\n out.inputFile,\n {\n filename: out.outputFilename\n }\n );\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Done.\");\n\n ctx.session.store.lastAction = \"converted_pdf_to_word\";\n\n console.log(\"[convert] success\", {\n mode,\n outputFilename: out.outputFilename,\n outBytes: out.outputBytes\n });\n } catch (e) {\n console.error(\"[convert] failure\", { err: safeErr(e), mode });\n try {\n await ctx.api.editMessageText(\n ctx.chat.id,\n progress.message_id,\n \"Sorry, that conversion failed. Please try again or send a smaller/cleaner PDF.\"\n );\n } catch {}\n\n const helpMsg = await aiChat({\n messages: [\n {\n role: \"system\",\n content:\n \"You are a helpful Telegram bot. Write a short, friendly error message (1-2 lines) suggesting one next step. No markdown.\"\n },\n { role: \"user\", content: \"PDF to Word conversion failed. Error: \" + safeErr(e) }\n ],\n meta: { platform: \"telegram\", feature: \"error_copy\" }\n }).catch(() => \"Sorry, that conversion failed. Please retry with a smaller file.\");\n\n await ctx.reply(String(helpMsg || \"Sorry, that conversion failed. Please retry.\"));\n await saveAssistantTurn(ctx, String(helpMsg || \"Sorry, that conversion failed.\"));\n ctx.session.store.lastAction = \"convert_failed\";\n }\n\n return;\n }\n\n if (mode === \"word_to_pdf\") {\n const lower = String(fileName).toLowerCase();\n if (!(lower.endsWith(\".doc\") || lower.endsWith(\".docx\"))) {\n const msg = \"For Word to PDF, please send a .doc or .docx as a document.\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n const receivedMsg = \"Got it. Converting your Word document to PDF now.\";\n await ctx.reply(receivedMsg);\n await saveAssistantTurn(ctx, receivedMsg);\n\n const progress = await ctx.reply(\"Downloading file...\");\n\n try {\n console.log(\"[convert] start\", {\n mode,\n chatId: String(ctx.chat?.id || \"\"),\n userId: String(ctx.from?.id || \"\"),\n fileName,\n sizeBytes\n });\n\n const input = await downloadTelegramDocument(ctx.api, cfg.TELEGRAM_BOT_TOKEN, doc, {\n maxBytes\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Processing...\");\n\n const out = await convertDocument({\n direction: \"word_to_pdf\",\n inputBuffer: input.buffer,\n inputFilename: fileName\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Uploading...\");\n\n await ctx.api.sendDocument(ctx.chat.id, out.inputFile, {\n filename: out.outputFilename\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Done.\");\n\n ctx.session.store.lastAction = \"converted_word_to_pdf\";\n\n console.log(\"[convert] success\", {\n mode,\n outputFilename: out.outputFilename,\n outBytes: out.outputBytes\n });\n } catch (e) {\n console.error(\"[convert] failure\", { err: safeErr(e), mode });\n try {\n await ctx.api.editMessageText(\n ctx.chat.id,\n progress.message_id,\n \"Sorry, that conversion failed. Please try again or send a simpler/smaller DOCX.\"\n );\n } catch {}\n\n const helpMsg = await aiChat({\n messages: [\n {\n role: \"system\",\n content:\n \"You are a helpful Telegram bot. Write a short, friendly error message (1-2 lines) suggesting one next step. No markdown.\"\n },\n { role: \"user\", content: \"Word to PDF conversion failed. Error: \" + safeErr(e) }\n ],\n meta: { platform: \"telegram\", feature: \"error_copy\" }\n }).catch(() => \"Sorry, that conversion failed. Please retry with a smaller file.\");\n\n await ctx.reply(String(helpMsg || \"Sorry, that conversion failed. Please retry.\"));\n await saveAssistantTurn(ctx, String(helpMsg || \"Sorry, that conversion failed.\"));\n ctx.session.store.lastAction = \"convert_failed\";\n }\n\n return;\n }\n}\n\nasync function doMergeNow(ctx, cfg, requireConfirm = true) {\n ctx.session.store ??= {};\n ctx.session.store.mergeQueue ??= [];\n\n const q = ctx.session.store.mergeQueue;\n if (!q.length) {\n const msg = \"No PDFs queued yet. Send PDFs first (as documents).\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (q.length === 1) {\n const msg = \"You only have 1 PDF queued. Send at least 2 PDFs to merge.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (requireConfirm && !ctx.session.store.mergeConfirmed) {\n ctx.session.store.mergeConfirmed = true;\n const msg = \"You have \" + q.length + \" PDFs queued. Reply with yes to confirm merging, or send clear to start over.\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_asked_confirm\";\n return;\n }\n\n ctx.session.store.mergeConfirmed = false;\n\n const maxBytes = Math.max(1, Number(cfg.MAX_FILE_MB || 20)) * 1024 * 1024;\n\n const progress = await ctx.reply(\"Downloading PDFs...\");\n\n try {\n console.log(\"[merge] start\", {\n chatId: String(ctx.chat?.id || \"\"),\n userId: String(ctx.from?.id || \"\"),\n count: q.length\n });\n\n const buffers = [];\n for (const item of q) {\n const fakeDoc = {\n file_id: item.fileId,\n file_unique_id: item.fileUniqueId,\n file_name: item.fileName,\n file_size: item.sizeBytes\n };\n const input = await downloadTelegramDocument(ctx.api, cfg.TELEGRAM_BOT_TOKEN, fakeDoc, {\n maxBytes\n });\n buffers.push({ buffer: input.buffer, fileName: item.fileName });\n }\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Merging...\");\n\n const merged = await mergePdfs(buffers.map((b) => b.buffer));\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Uploading...\");\n\n const outName = \"merged.pdf\";\n await ctx.api.sendDocument(ctx.chat.id, merged.inputFile, {\n filename: outName\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Done.\");\n\n ctx.session.store.mergeQueue = [];\n ctx.session.store.currentMode = null;\n ctx.session.store.lastAction = \"merged_pdfs\";\n\n console.log(\"[merge] success\", { outBytes: merged.outputBytes });\n } catch (e) {\n console.error(\"[merge] failure\", { err: safeErr(e) });\n try {\n await ctx.api.editMessageText(\n ctx.chat.id,\n progress.message_id,\n \"Sorry, merging failed. Please try again, or send smaller PDFs.\"\n );\n } catch {}\n\n const helpMsg = await aiChat({\n messages: [\n {\n role: \"system\",\n content:\n \"You are a helpful Telegram bot. Write a short, friendly error message (1-2 lines) suggesting one next step. No markdown.\"\n },\n { role: \"user\", content: \"PDF merge failed. Error: \" + safeErr(e) }\n ],\n meta: { platform: \"telegram\", feature: \"error_copy\" }\n }).catch(() => \"Sorry, merging failed. Please retry with smaller PDFs.\");\n\n await ctx.reply(String(helpMsg || \"Sorry, merging failed. Please retry.\"));\n await saveAssistantTurn(ctx, String(helpMsg || \"Sorry, merging failed.\"));\n ctx.session.store.lastAction = \"merge_failed\";\n }\n}\n\nexport async function createBot(cfg) {\n const bot = new Bot(cfg.TELEGRAM_BOT_TOKEN);\n\n bot.use(\n session({\n initial: initialSession\n })\n );\n\n bot.catch(async (err) => {\n console.error(\"[bot] handler error\", {\n err: safeErr(err?.error || err),\n chatId: String(err?.ctx?.chat?.id || \"\"),\n userId: String(err?.ctx?.from?.id || \"\")\n });\n\n try {\n await err.ctx?.reply(\"Something went wrong. Please try again.\");\n } catch {}\n });\n\n await bot.init().catch(() => {});\n\n await registerCommands(bot, cfg);\n\n bot.on(\"message\", async (ctx, next) => {\n const ok = await shouldHandleGroupMessage(ctx);\n if (!ok) return next();\n return next();\n });\n\n bot.on(\"message:document\", async (ctx) => {\n await saveUserTurn(ctx, \"[document] \" + (ctx.message?.document?.file_name || \"file\"));\n await handleDocument(ctx, cfg);\n });\n\n bot.on(\"message\", async (ctx) => {\n const msg = ctx.message;\n if (!msg) return;\n\n if (msg.photo || msg.sticker || msg.voice || msg.video || msg.audio) {\n const t = \"Please send your file as a document upload (PDF, DOC, or DOCX).\";\n await ctx.reply(t);\n await saveAssistantTurn(ctx, t);\n }\n });\n\n bot.on(\"message:text\", async (ctx, next) => {\n const raw = isText(ctx) ? ctx.message.text : \"\";\n if (raw.startsWith(\"/\")) return next();\n\n await saveUserTurn(ctx, raw);\n\n ctx.session.store ??= {};\n ctx.session.store.mergeQueue ??= [];\n\n const t = raw.trim().toLowerCase();\n\n if (ctx.session.store.currentMode === \"merge_pdfs\") {\n if (t === \"done\" || t === \"merge\" || t === \"merge now\") {\n await doMergeNow(ctx, cfg, true);\n return;\n }\n\n if (t === \"remove last\") {\n const removed = ctx.session.store.mergeQueue.pop();\n const n = ctx.session.store.mergeQueue.length;\n const msg = removed\n ? \"Removed the last PDF. Now queued: \" + n + \".\"\n : \"Nothing to remove.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_remove_last\";\n return;\n }\n\n if (t === \"clear\") {\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n const msg = \"Cleared the merge queue. Send PDFs again in the order you want.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_cleared\";\n return;\n }\n\n if (t === \"yes\") {\n await doMergeNow(ctx, cfg, false);\n return;\n }\n }\n\n let interpreted;\n try {\n console.log(\"[ai] intent start\", {\n chatId: String(ctx.chat?.id || \"\"),\n userId: String(ctx.from?.id || \"\")\n });\n interpreted = await aiInterpretText(ctx, raw);\n console.log(\"[ai] intent success\", { intent: interpreted.intent });\n } catch (e) {\n console.error(\"[ai] intent failure\", { err: safeErr(e) });\n interpreted = { intent: \"unknown\", reply: \"\" };\n }\n\n const intent = interpreted.intent;\n\n if (intent === \"set_mode_pdf_to_word\") {\n ctx.session.store.currentMode = \"pdf_to_word\";\n const msg = interpreted.reply || \"OK. Send a PDF as a document and I’ll convert it to Word.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"mode_pdf_to_word\";\n return;\n }\n\n if (intent === \"set_mode_word_to_pdf\") {\n ctx.session.store.currentMode = \"word_to_pdf\";\n const msg = interpreted.reply || \"OK. Send a .doc or .docx as a document and I’ll convert it to PDF.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"mode_word_to_pdf\";\n return;\n }\n\n if (intent === \"set_mode_merge_pdfs\") {\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeConfirmed = false;\n const msg = interpreted.reply || \"OK. Send PDFs one by one. When you’re ready, press Merge now or send done.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"mode_merge_pdfs\";\n return;\n }\n\n if (intent === \"merge_done\") {\n ctx.session.store.currentMode = \"merge_pdfs\";\n await doMergeNow(ctx, cfg, true);\n return;\n }\n\n if (intent === \"merge_remove_last\") {\n ctx.session.store.currentMode = \"merge_pdfs\";\n const removed = ctx.session.store.mergeQueue.pop();\n const n = ctx.session.store.mergeQueue.length;\n const msg = removed\n ? \"Removed the last PDF. Now queued: \" + n + \".\"\n : \"Nothing to remove.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_remove_last\";\n return;\n }\n\n if (intent === \"merge_clear\") {\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n const msg = \"Cleared the merge queue. Send PDFs again in the order you want.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_cleared\";\n return;\n }\n\n if (intent === \"status\") {\n const mode = ctx.session.store.currentMode;\n const n = ctx.session.store.mergeQueue.length;\n const last = ctx.session.store.lastAction || \"\";\n const msg =\n \"Mode: \" +\n String(mode || \"none\") +\n \"\\nQueued PDFs: \" +\n String(n) +\n (last ? \"\\nLast: \" + last : \"\");\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (intent === \"reset\") {\n ctx.session.store.currentMode = null;\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n ctx.session.store.lastAction = \"reset\";\n\n await clearUserMemory({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\")\n });\n\n const msg = \"Reset done. Send a PDF, DOCX, or tell me what you want (pdf to word, word to pdf, merge pdfs).\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (intent === \"help\") {\n const msg =\n \"I can: PDF to Word, Word to PDF, and merge PDFs.\\n\\nTry saying: pdf to word, word to pdf, or merge pdfs.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n const fallback =\n interpreted.reply ||\n \"Tell me what you want: pdf to word, word to pdf, or merge pdfs. You can also just send a PDF or DOCX.\";\n await ctx.reply(fallback, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, fallback);\n });\n\n bot.callbackQuery(\"mode:pdf_to_word\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"pdf_to_word\";\n ctx.session.store.lastAction = \"mode_pdf_to_word\";\n await ctx.answerCallbackQuery();\n const msg = \"Send a PDF as a document and I’ll convert it to Word.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n });\n\n bot.callbackQuery(\"mode:word_to_pdf\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"word_to_pdf\";\n ctx.session.store.lastAction = \"mode_word_to_pdf\";\n await ctx.answerCallbackQuery();\n const msg = \"Send a .doc or .docx as a document and I’ll convert it to PDF.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n });\n\n bot.callbackQuery(\"mode:merge_pdfs\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeConfirmed = false;\n ctx.session.store.mergeQueue ??= [];\n ctx.session.store.lastAction = \"mode_merge_pdfs\";\n await ctx.answerCallbackQuery();\n const msg = \"Send PDFs one by one. When ready, press Merge now or send done.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n });\n\n bot.callbackQuery(\"merge:now\", async (ctx) => {\n await ctx.answerCallbackQuery();\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"merge_pdfs\";\n await doMergeNow(ctx, cfg, true);\n });\n\n bot.callbackQuery(\"merge:remove_last\", async (ctx) => {\n await ctx.answerCallbackQuery();\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeQueue ??= [];\n const removed = ctx.session.store.mergeQueue.pop();\n const n = ctx.session.store.mergeQueue.length;\n const msg = removed\n ? \"Removed the last PDF. Now queued: \" + n + \".\"\n : \"Nothing to remove.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_remove_last\";\n });\n\n bot.callbackQuery(\"merge:clear\", async (ctx) => {\n await ctx.answerCallbackQuery();\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n const msg = \"Cleared the merge queue. Send PDFs again in the order you want.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_cleared\";\n });\n\n return bot;\n}\n"
},
"commands": {
"type": "dir",
"children": {
"admin_stats.js": {
"type": "file",
"content": "import { getBootStats } from \"../services/stats.js\";\n\nexport default async function register(bot, cfg) {\n bot.command(\"admin_stats\", async (ctx) => {\n const adminId = String(cfg.ADMIN_TELEGRAM_USER_ID || \"\").trim();\n if (!adminId || String(ctx.from?.id || \"\") !== adminId) return;\n\n const s = getBootStats();\n const msg =\n \"Since boot:\\n\" +\n \"Conversions completed: \" +\n String(s.conversionsCompleted) +\n \"\\nMerges completed: \" +\n String(s.mergesCompleted);\n\n await ctx.reply(msg);\n });\n}\n"
},
"help.js": {
"type": "file",
"content": "import { buildMainKeyboard } from \"../services/ui.js\";\nimport { addTurn } from \"../lib/memory.js\";\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nasync function saveAssistantTurn(ctx, cfg, text) {\n await addTurn({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\"),\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nexport default async function register(bot, cfg) {\n bot.command(\"help\", async (ctx) => {\n const msg =\n \"Commands:\\n\" +\n \"/start Start\\n\" +\n \"/help Help\\n\" +\n \"/status Show current mode and merge queue\\n\" +\n \"/reset Clear workflow state and memory\\n\\n\" +\n \"Examples:\\n\" +\n \"1) pdf to word then send a PDF\\n\" +\n \"2) word to pdf then send a DOCX\\n\" +\n \"3) merge pdfs then send PDFs, then done\";\n\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, cfg, msg);\n });\n}\n"
},
"loader.js": {
"type": "file",
"content": "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nexport async function registerCommands(bot, cfg) {\n const dir = path.dirname(fileURLToPath(import.meta.url));\n\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(\".js\") && f !== \"loader.js\" && !f.startsWith(\"_\"))\n .sort();\n\n for (const f of files) {\n const url = pathToFileURL(path.join(dir, f)).href;\n const mod = await import(url);\n\n const handler =\n (mod && (mod.default || mod.register)) ||\n (typeof mod === \"function\" ? mod : null);\n\n if (typeof handler === \"function\") {\n await handler(bot, cfg);\n } else {\n console.warn(\"[commands] skipped\", { file: f });\n }\n }\n}\n"
},
"reset.js": {
"type": "file",
"content": "import { clearUserMemory, addTurn } from \"../lib/memory.js\";\nimport { buildMainKeyboard } from \"../services/ui.js\";\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nasync function saveAssistantTurn(ctx, cfg, text) {\n await addTurn({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\"),\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nexport default async function register(bot, cfg) {\n bot.command(\"reset\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.currentMode = null;\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n ctx.session.store.lastAction = \"reset\";\n\n await clearUserMemory({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\")\n });\n\n const msg = \"Reset done. Tell me: pdf to word, word to pdf, or merge pdfs.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, cfg, msg);\n });\n}\n"
},
"start.js": {
"type": "file",
"content": "import { buildMainKeyboard } from \"../services/ui.js\";\nimport { addTurn } from \"../lib/memory.js\";\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nasync function saveAssistantTurn(ctx, cfg, text) {\n await addTurn({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\"),\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nexport default async function register(bot, cfg) {\n bot.command(\"start\", async (ctx) => {\n const maxMb = String(cfg.MAX_FILE_MB || 20);\n\n const msg =\n \"Hi. I can convert documents and merge PDFs.\\n\\n\" +\n \"1) Send a PDF to convert it to Word\\n\" +\n \"2) Send a DOC or DOCX to convert it to PDF\\n\" +\n \"3) To merge PDFs: say merge pdfs, then send PDFs in order, then press Merge now or send done\\n\\n\" +\n \"Note: file limit is about \" +\n maxMb +\n \" MB per file. Please send files as documents.\";\n\n ctx.session.store ??= {};\n\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, cfg, msg);\n\n ctx.session.store.lastAction = \"start\";\n });\n}\n"
},
"status.js": {
"type": "file",
"content": "import { addTurn } from \"../lib/memory.js\";\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nasync function saveAssistantTurn(ctx, cfg, text) {\n await addTurn({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\"),\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nexport default async function register(bot, cfg) {\n bot.command(\"status\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.mergeQueue ??= [];\n\n const mode = ctx.session.store.currentMode;\n const queued = ctx.session.store.mergeQueue.length;\n const last = ctx.session.store.lastAction || \"\";\n\n const msg =\n \"Mode: \" +\n String(mode || \"none\") +\n \"\\nQueued PDFs: \" +\n String(queued) +\n (last ? \"\\nLast: \" + last : \"\");\n\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, cfg, msg);\n });\n}\n"
}
}
},
"index.js": {
"type": "file",
"content": "import \"dotenv/config\";\n\nimport process from \"node:process\";\n\nfunction safeErr(e) {\n return (\n e?.response?.data?.error?.message ||\n e?.response?.data?.message ||\n e?.message ||\n String(e)\n );\n}\n\nprocess.on(\"unhandledRejection\", (r) => {\n console.error(\"[process] unhandledRejection\", { err: safeErr(r) });\n process.exit(1);\n});\n\nprocess.on(\"uncaughtException\", (e) => {\n console.error(\"[process] uncaughtException\", { err: safeErr(e) });\n process.exit(1);\n});\n\nasync function boot() {\n console.log(\"[boot] starting\", {\n tokenSet: !!process.env.TELEGRAM_BOT_TOKEN,\n mongoSet: !!process.env.MONGODB_URI,\n aiEndpointSet: !!process.env.COOKMYBOTS_AI_ENDPOINT,\n aiKeySet: !!process.env.COOKMYBOTS_AI_KEY\n });\n\n try {\n const { cfg } = await import(\"./lib/config.js\");\n\n if (!cfg.TELEGRAM_BOT_TOKEN) {\n console.error(\n \"TELEGRAM_BOT_TOKEN is required. Set it in env and redeploy.\"\n );\n process.exit(1);\n }\n\n const { createBot } = await import(\"./bot.js\");\n const bot = await createBot(cfg);\n\n await bot.api.deleteWebhook({ drop_pending_updates: true });\n\n const { run } = await import(\"@grammyjs/runner\");\n\n let backoffMs = 2000;\n const maxBackoffMs = 20000;\n\n while (true) {\n try {\n console.log(\"[polling] starting runner\", { concurrency: cfg.CONCURRENCY });\n await run(bot, { concurrency: cfg.CONCURRENCY });\n console.warn(\"[polling] runner stopped unexpectedly; restarting\");\n } catch (e) {\n const msg = safeErr(e);\n const code = e?.error_code || e?.code;\n\n if (code === 409 || String(msg).includes(\"409\")) {\n console.warn(\"[polling] 409 conflict; backing off\", { backoffMs });\n await new Promise((r) => setTimeout(r, backoffMs));\n backoffMs = Math.min(maxBackoffMs, Math.floor(backoffMs * 2.5));\n continue;\n }\n\n console.error(\"[polling] runner error\", { err: msg });\n await new Promise((r) => setTimeout(r, backoffMs));\n backoffMs = Math.min(maxBackoffMs, Math.floor(backoffMs * 2.5));\n }\n }\n } catch (e) {\n console.error(\"[boot] failed\", { err: safeErr(e), code: e?.code });\n if (e?.code === \"ERR_MODULE_NOT_FOUND\") {\n console.error(\n \"A required module was not found. Check that all src/ files exist and imports include .js extensions.\"\n );\n }\n process.exit(1);\n }\n}\n\nboot();\n"
},
"lib": {
"type": "dir",
"children": {
"ai.js": {
"type": "file",
"content": "import { cfg } from \"./config.js\";\nimport { safeErr } from \"./safeErr.js\";\n\nfunction clampBaseUrl(u) {\n const s = String(u || \"\").trim();\n return s.replace(/\\/+$/, \"\");\n}\n\nasync function sleep(ms) {\n await new Promise((r) => setTimeout(r, ms));\n}\n\nexport async function aiChat({ messages, model, meta }) {\n const base = clampBaseUrl(cfg.COOKMYBOTS_AI_ENDPOINT);\n const url = base + \"/chat\";\n\n const timeoutMs = Number(cfg.AI_TIMEOUT_MS || 600000);\n const maxRetries = Number(cfg.AI_MAX_RETRIES || 2);\n\n if (!cfg.COOKMYBOTS_AI_KEY) {\n throw new Error(\"COOKMYBOTS_AI_KEY missing\");\n }\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), timeoutMs);\n\n try {\n console.log(\"[ai] call start\", {\n endpoint: \"/chat\",\n attempt: attempt + 1,\n meta: meta || {}\n });\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + cfg.COOKMYBOTS_AI_KEY\n },\n body: JSON.stringify({\n messages,\n model,\n meta\n }),\n signal: ctrl.signal\n });\n\n const json = await res.json().catch(() => null);\n if (!res.ok) {\n const msg =\n json?.error || json?.message || \"AI request failed with status \" + res.status;\n throw new Error(msg);\n }\n\n const content = json?.output?.content;\n if (typeof content !== \"string\") {\n throw new Error(\"AI response missing output.content\");\n }\n\n console.log(\"[ai] call success\", {\n endpoint: \"/chat\",\n meta: meta || {}\n });\n\n return content;\n } catch (e) {\n const msg = safeErr(e);\n console.error(\"[ai] call failure\", {\n endpoint: \"/chat\",\n attempt: attempt + 1,\n err: msg\n });\n if (attempt >= maxRetries) throw e;\n await sleep(400 * Math.pow(2, attempt));\n } finally {\n clearTimeout(t);\n }\n }\n\n throw new Error(\"AI request failed\");\n}\n"
},
"config.js": {
"type": "file",
"content": "export const cfg = {\n TELEGRAM_BOT_TOKEN: process.env.TELEGRAM_BOT_TOKEN || \"\",\n MONGODB_URI: process.env.MONGODB_URI || \"\",\n\n COOKMYBOTS_AI_ENDPOINT:\n process.env.COOKMYBOTS_AI_ENDPOINT || \"https://api.cookmybots.com/api/ai\",\n COOKMYBOTS_AI_KEY: process.env.COOKMYBOTS_AI_KEY || \"\",\n\n AI_TIMEOUT_MS: Number(process.env.AI_TIMEOUT_MS || 600000),\n AI_MAX_RETRIES: Number(process.env.AI_MAX_RETRIES || 2),\n CONCURRENCY: Number(process.env.CONCURRENCY || 20),\n\n MAX_FILE_MB: Number(process.env.MAX_FILE_MB || 20),\n ADMIN_TELEGRAM_USER_ID: process.env.ADMIN_TELEGRAM_USER_ID || \"\"\n};\n"
},
"db.js": {
"type": "file",
"content": "import { MongoClient } from \"mongodb\";\nimport { safeErr } from \"./safeErr.js\";\n\nlet _client = null;\nlet _db = null;\nlet _indexEnsured = false;\n\nexport async function getDb(mongoUri) {\n if (!mongoUri) return null;\n if (_db) return _db;\n\n try {\n _client = new MongoClient(mongoUri, { maxPoolSize: 5, ignoreUndefined: true });\n await _client.connect();\n _db = _client.db();\n\n console.log(\"[db] connected\", { mongoSet: true });\n\n if (!_indexEnsured) {\n await ensureIndexes(_db);\n _indexEnsured = true;\n }\n\n return _db;\n } catch (e) {\n console.error(\"[db] connect failed\", { err: safeErr(e) });\n _db = null;\n return null;\n }\n}\n\nasync function ensureIndexes(db) {\n try {\n const col = db.collection(\"memory_messages\");\n await col.createIndex({ platform: 1, userId: 1, chatId: 1, ts: -1 });\n } catch (e) {\n console.error(\"[db] ensureIndexes failed\", { err: safeErr(e) });\n }\n}\n"
},
"memory.js": {
"type": "file",
"content": "import { getDb } from \"./db.js\";\n\nconst COL = \"memory_messages\";\n\nconst inMem = new Map();\nlet warned = false;\n\nfunction keyOf({ platform, userId, chatId }) {\n return String(platform) + \":\" + String(userId) + \":\" + String(chatId || \"\");\n}\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nexport async function addTurn({ mongoUri, platform, userId, chatId, role, text }) {\n const doc = {\n platform: String(platform),\n userId: String(userId || \"\"),\n chatId: String(chatId || \"\"),\n role: String(role),\n text: clampText(text),\n ts: new Date()\n };\n\n const db = await getDb(mongoUri);\n if (db) {\n try {\n await db.collection(COL).insertOne(doc);\n return;\n } catch (e) {\n console.error(\"[memory] insert failed\", { err: e?.message || String(e) });\n }\n }\n\n if (!warned) {\n warned = true;\n console.warn(\"[memory] MONGODB_URI not set or DB unavailable; using in-memory fallback\");\n }\n\n const k = keyOf(doc);\n const arr = inMem.get(k) || [];\n arr.push({ role: doc.role, text: doc.text, ts: doc.ts });\n while (arr.length > 50) arr.shift();\n inMem.set(k, arr);\n}\n\nexport async function getRecentTurns({ mongoUri, platform, userId, chatId, limit = 14 }) {\n const db = await getDb(mongoUri);\n if (db) {\n const q = {\n platform: String(platform),\n userId: String(userId || \"\"),\n chatId: String(chatId || \"\")\n };\n\n const rows = await db\n .collection(COL)\n .find(q)\n .sort({ ts: -1 })\n .limit(limit)\n .toArray();\n\n return rows\n .reverse()\n .map((r) => ({ role: String(r.role), text: String(r.text || \"\") }));\n }\n\n if (!warned) {\n warned = true;\n console.warn(\"[memory] MONGODB_URI not set or DB unavailable; using in-memory fallback\");\n }\n\n const k = keyOf({ platform, userId, chatId });\n const arr = inMem.get(k) || [];\n return arr.slice(-limit).map((r) => ({ role: r.role, text: r.text }));\n}\n\nexport async function clearUserMemory({ mongoUri, platform, userId, chatId }) {\n const db = await getDb(mongoUri);\n if (db) {\n const q = {\n platform: String(platform),\n userId: String(userId || \"\"),\n chatId: String(chatId || \"\")\n };\n\n await db.collection(COL).deleteMany(q);\n return;\n }\n\n const k = keyOf({ platform, userId, chatId });\n inMem.delete(k);\n}\n"
},
"safeErr.js": {
"type": "file",
"content": "export function safeErr(e) {\n return (\n e?.response?.data?.error?.message ||\n e?.response?.data?.message ||\n e?.message ||\n String(e)\n );\n}\n"
}
}
},
"services": {
"type": "dir",
"children": {
"conversionService.js": {
"type": "file",
"content": "import { InputFile } from \"grammy\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport crypto from \"node:crypto\";\nimport { spawn } from \"node:child_process\";\nimport { safeErr } from \"../lib/safeErr.js\";\nimport { incConversionsCompleted } from \"./stats.js\";\n\nfunction rand() {\n return crypto.randomBytes(8).toString(\"hex\");\n}\n\nfunction extOf(name) {\n const n = String(name || \"\");\n const i = n.lastIndexOf(\".\");\n return i >= 0 ? n.slice(i + 1).toLowerCase() : \"\";\n}\n\nfunction stripExt(name) {\n const n = String(name || \"file\");\n const i = n.lastIndexOf(\".\");\n return i >= 0 ? n.slice(0, i) : n;\n}\n\nasync function runSofficeConvert({ inputPath, outDir, targetExt, timeoutMs = 240000 }) {\n return new Promise((resolve, reject) => {\n const args = [\n \"--headless\",\n \"--nologo\",\n \"--nolockcheck\",\n \"--nodefault\",\n \"--norestore\",\n \"--invisible\",\n \"--convert-to\",\n targetExt,\n \"--outdir\",\n outDir,\n inputPath\n ];\n\n const child = spawn(\"soffice\", args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"]\n });\n\n let stderr = \"\";\n child.stderr.on(\"data\", (d) => {\n stderr += String(d || \"\");\n if (stderr.length > 2000) stderr = stderr.slice(-2000);\n });\n\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(\"CONVERSION_TIMEOUT\"));\n }, timeoutMs);\n\n child.on(\"error\", (e) => {\n clearTimeout(timer);\n reject(e);\n });\n\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n if (code !== 0) {\n reject(new Error(\"LIBREOFFICE_FAILED: \" + code + \": \" + stderr));\n return;\n }\n resolve();\n });\n });\n}\n\nexport async function convertDocument({ direction, inputBuffer, inputFilename }) {\n const tmpBase = await fs.mkdtemp(path.join(os.tmpdir(), \"doc-tools-\"));\n\n const inExt = extOf(inputFilename);\n const base = stripExt(inputFilename) || \"file\";\n\n const inputPath = path.join(tmpBase, \"input.\" + (inExt || \"bin\"));\n await fs.writeFile(inputPath, inputBuffer);\n\n try {\n if (direction === \"pdf_to_word\") {\n const outExt = \"docx\";\n const outName = base + \".docx\";\n\n console.log(\"[convert] libreoffice start\", {\n direction,\n inputExt: inExt,\n outExt\n });\n\n await runSofficeConvert({\n inputPath,\n outDir: tmpBase,\n targetExt: outExt\n });\n\n const outPath = path.join(tmpBase, \"input.\" + outExt);\n const outBuf = await fs.readFile(outPath);\n\n if (!outBuf?.length) throw new Error(\"EMPTY_OUTPUT\");\n\n incConversionsCompleted();\n\n return {\n outputFilename: outName,\n mimeType:\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n outputBytes: outBuf.length,\n inputFile: new InputFile(outBuf, outName)\n };\n }\n\n if (direction === \"word_to_pdf\") {\n const outExt = \"pdf\";\n const outName = base + \".pdf\";\n\n console.log(\"[convert] libreoffice start\", {\n direction,\n inputExt: inExt,\n outExt\n });\n\n await runSofficeConvert({\n inputPath,\n outDir: tmpBase,\n targetExt: outExt\n });\n\n const outPath = path.join(tmpBase, \"input.\" + outExt);\n const outBuf = await fs.readFile(outPath);\n\n if (!outBuf?.length) throw new Error(\"EMPTY_OUTPUT\");\n\n incConversionsCompleted();\n\n return {\n outputFilename: outName,\n mimeType: \"application/pdf\",\n outputBytes: outBuf.length,\n inputFile: new InputFile(outBuf, outName)\n };\n }\n\n throw new Error(\"UNKNOWN_DIRECTION\");\n } catch (e) {\n const msg = safeErr(e);\n\n if (\n msg.includes(\"spawn soffice\") ||\n msg.includes(\"ENOENT\") ||\n msg.toLowerCase().includes(\"soffice\")\n ) {\n throw new Error(\n \"CONVERTER_MISSING: LibreOffice (soffice) is not installed or not on PATH\"\n );\n }\n\n throw e;\n } finally {\n try {\n await fs.rm(tmpBase, { recursive: true, force: true });\n } catch {}\n }\n}\n"
},
"pdfMergeService.js": {
"type": "file",
"content": "import { PDFDocument } from \"pdf-lib\";\nimport { InputFile } from \"grammy\";\nimport { safeErr } from \"../lib/safeErr.js\";\nimport { incMergesCompleted } from \"./stats.js\";\n\nexport async function mergePdfs(buffers) {\n try {\n const out = await PDFDocument.create();\n\n for (const b of buffers) {\n const doc = await PDFDocument.load(b, { ignoreEncryption: false });\n const pages = await out.copyPages(doc, doc.getPageIndices());\n for (const p of pages) out.addPage(p);\n }\n\n const bytes = await out.save();\n const buf = Buffer.from(bytes);\n\n if (!buf.length) throw new Error(\"EMPTY_OUTPUT\");\n\n incMergesCompleted();\n\n return {\n outputBytes: buf.length,\n inputFile: new InputFile(buf, \"merged.pdf\")\n };\n } catch (e) {\n const msg = safeErr(e);\n if (msg.toLowerCase().includes(\"encrypted\")) {\n throw new Error(\"ENCRYPTED_PDF\");\n }\n throw e;\n }\n}\n"
},
"stats.js": {
"type": "file",
"content": "const bootStats = {\n conversionsCompleted: 0,\n mergesCompleted: 0\n};\n\nexport function incConversionsCompleted() {\n bootStats.conversionsCompleted += 1;\n}\n\nexport function incMergesCompleted() {\n bootStats.mergesCompleted += 1;\n}\n\nexport function getBootStats() {\n return { ...bootStats };\n}\n"
},
"telegramFiles.js": {
"type": "file",
"content": "import https from \"node:https\";\nimport { safeErr } from \"../lib/safeErr.js\";\n\nfunction getFileUrl(token, filePath) {\n return \"https://api.telegram.org/file/bot\" + token + \"/\" + filePath;\n}\n\nfunction download(url, { maxBytes }) {\n return new Promise((resolve, reject) => {\n const req = https.get(url, (res) => {\n if (res.statusCode && res.statusCode >= 400) {\n reject(new Error(\"Download failed with status \" + res.statusCode));\n res.resume();\n return;\n }\n\n const chunks = [];\n let bytes = 0;\n\n res.on(\"data\", (d) => {\n bytes += d.length;\n if (maxBytes && bytes > maxBytes) {\n req.destroy(new Error(\"FILE_TOO_LARGE\"));\n return;\n }\n chunks.push(d);\n });\n\n res.on(\"end\", () => {\n resolve({ buffer: Buffer.concat(chunks), bytes });\n });\n\n res.on(\"error\", (e) => reject(e));\n });\n\n req.on(\"error\", (e) => reject(e));\n });\n}\n\nexport async function downloadTelegramDocument(api, token, document, { maxBytes }) {\n const fileId = document.file_id;\n\n console.log(\"[tgfile] getFile start\", {\n fileId: String(fileId).slice(0, 12) + \"...\",\n sizeBytes: Number(document.file_size || 0)\n });\n\n let file;\n try {\n file = await api.getFile(fileId);\n } catch (e) {\n console.error(\"[tgfile] getFile failed\", { err: safeErr(e) });\n throw e;\n }\n\n const filePath = file?.file_path;\n if (!filePath) throw new Error(\"TELEGRAM_FILE_PATH_MISSING\");\n\n const url = getFileUrl(token, filePath);\n\n console.log(\"[tgfile] download start\", {\n filePath: String(filePath).slice(0, 60),\n maxBytes: Number(maxBytes || 0)\n });\n\n try {\n const res = await download(url, { maxBytes });\n console.log(\"[tgfile] download success\", { bytes: res.bytes });\n return {\n buffer: res.buffer,\n bytes: res.bytes,\n filePath\n };\n } catch (e) {\n console.error(\"[tgfile] download failed\", { err: safeErr(e) });\n if (String(safeErr(e)).includes(\"FILE_TOO_LARGE\")) {\n throw new Error(\"FILE_TOO_LARGE\");\n }\n throw e;\n }\n}\n"
},
"ui.js": {
"type": "file",
"content": "import { InlineKeyboard } from \"grammy\";\n\nexport function buildMainKeyboard() {\n const kb = new InlineKeyboard()\n .text(\"PDF to Word\", \"mode:pdf_to_word\")\n .text(\"Word to PDF\", \"mode:word_to_pdf\")\n .row()\n .text(\"Merge PDFs\", \"mode:merge_pdfs\");\n\n return kb;\n}\n\nexport function buildMergeKeyboard() {\n const kb = new InlineKeyboard()\n .text(\"Merge now\", \"merge:now\")\n .row()\n .text(\"Remove last\", \"merge:remove_last\")\n .text(\"Clear\", \"merge:clear\");\n\n return kb;\n}\n\nexport function isText(ctx) {\n return !!ctx.message?.text;\n}\n"
}
}
}
}
}
},
"commands": [
{
"command": "/admin_stats",
"description": "Handler for /admin_stats",
"example": "User: /admin_stats → bot replies."
},
{
"command": "/help",
"description": "Shows all public commands and example usage.",
"usage": "/help",
"examples": [
"User: /help → Bot: command list and examples"
],
"example": "User: /help → Bot: command list and examples",
"notes": "You can also just type things like “pdf to word” or “merge pdfs”."
},
{
"command": "/reset",
"description": "Clears your active workflow state and clears your stored memory.",
"usage": "/reset",
"examples": [
"User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs."
],
"example": "User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs.",
"notes": "If MongoDB is configured, this also deletes your memory records."
},
{
"command": "/start",
"description": "Explains what the bot can do and how to use it.",
"usage": "/start",
"examples": [
"User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs"
],
"example": "User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs",
"notes": "Send files as documents. Large files may be refused based on MAX_FILE_MB."
},
{
"command": "/status",
"description": "Shows the current selected mode, queued PDFs count, and last action.",
"usage": "/status",
"examples": [
"User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added"
],
"example": "User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added",
"notes": "Useful when you’re in the middle of merging."
}
],
"envVarDocs": [
{
"key": "TELEGRAM_BOT_TOKEN",
"title": "Telegram Bot Token",
"description": "Token for your Telegram bot from BotFather.",
"usage": "Used by grammY to connect to Telegram.",
"howToGet": "Create a bot with BotFather in Telegram and copy the token.",
"example": "123456:ABCDEF...",
"isSecret": true,
"required": true
},
{
"key": "MONGODB_URI",
"title": "MongoDB Connection String",
"description": "MongoDB connection string for long-term memory storage.",
"usage": "If present, conversation turns are stored in memory_messages; otherwise in-memory fallback is used.",
"howToGet": "Use MongoDB Atlas or another Mongo provider to create a database and user.",
"example": "mongodb+srv://user:pass@cluster/dbname",
"isSecret": true,
"required": false
},
{
"key": "COOKMYBOTS_AI_ENDPOINT",
"title": "CookMyBots AI Endpoint",
"description": "Base URL for the CookMyBots AI gateway (must be a base URL ending with /api/ai).",
"usage": "The bot calls POST {endpoint}/chat for intent parsing and friendly replies.",
"howToGet": "Provided by CookMyBots.",
"example": "https://api.cookmybots.com/api/ai",
"isSecret": false,
"required": true
},
{
"key": "COOKMYBOTS_AI_KEY",
"title": "CookMyBots AI Key",
"description": "API key used to authenticate requests to the CookMyBots AI gateway.",
"usage": "Sent as Authorization: Bearer <key> for AI calls.",
"howToGet": "Provided by CookMyBots.",
"example": "cmb_ai_...",
"isSecret": true,
"required": true
},
{
"key": "AI_TIMEOUT_MS",
"title": "AI Timeout",
"description": "Timeout for AI gateway requests in milliseconds.",
"usage": "Controls fetch AbortController timeout for AI calls.",
"howToGet": "Optional setting.",
"example": "600000",
"isSecret": false,
"required": false
},
{
"key": "AI_MAX_RETRIES",
"title": "AI Retry Count",
"description": "How many times to retry AI calls on failure.",
"usage": "Used by src/lib/ai.js retry loop.",
"howToGet": "Optional setting.",
"example": "2",
"isSecret": false,
"required": false
},
{
"key": "CONCURRENCY",
"title": "Telegram Update Concurrency",
"description": "Number of updates processed concurrently by @grammyjs/runner.",
"usage": "Passed to run(bot,{concurrency}).",
"howToGet": "Optional setting.",
"example": "20",
"isSecret": false,
"required": false
},
{
"key": "MAX_FILE_MB",
"title": "Max File Size",
"description": "Maximum allowed upload size per document (in MB).",
"usage": "Validated against Telegram-reported size and enforced during download.",
"howToGet": "Optional setting.",
"example": "20",
"isSecret": false,
"required": false
},
{
"key": "ADMIN_TELEGRAM_USER_ID",
"title": "Admin Telegram User ID",
"description": "If set, enables /admin_stats for that user only.",
"usage": "Compared to ctx.from.id to authorize admin command.",
"howToGet": "Find your Telegram numeric user id (various bots/tools can show it).",
"example": "123456789",
"isSecret": false,
"required": false
}
],
"commandDocs": [
{
"command": "/start",
"description": "Explains what the bot can do and how to use it.",
"usage": "/start",
"examples": [
"User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs"
],
"notes": "Send files as documents. Large files may be refused based on MAX_FILE_MB."
},
{
"command": "/help",
"description": "Shows all public commands and example usage.",
"usage": "/help",
"examples": [
"User: /help → Bot: command list and examples"
],
"notes": "You can also just type things like “pdf to word” or “merge pdfs”."
},
{
"command": "/status",
"description": "Shows the current selected mode, queued PDFs count, and last action.",
"usage": "/status",
"examples": [
"User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added"
],
"notes": "Useful when you’re in the middle of merging."
},
{
"command": "/reset",
"description": "Clears your active workflow state and clears your stored memory.",
"usage": "/reset",
"examples": [
"User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs."
],
"notes": "If MongoDB is configured, this also deletes your memory records."
}
],
"aiMessages": [
{
"role": "user",
"content": "Create a bot that can convert PDF files to Word documents and vice versa, as well as merge multiple PDF files into a single PDF file"
},
{
"role": "assistant",
"content": "Created a complete, production-ready grammY Telegram bot for PDF→Word, Word→PDF, and PDF merging. It uses session state for per-chat workflows, MongoDB-backed long-term memory when available (with in-memory fallback), CookMyBots AI gateway for intent parsing and friendly replies, pdf-lib for merging, and LibreOffice (soffice) for conversions with graceful failure messaging if the binary is missing. Long polling uses @grammyjs/runner with webhook cleanup and 409 conflict backoff.\n\nFiles touched (23): .env.sample, DOCS.md, README.md, package.json, project.json, src/bot.js…\nValidation: ✅ project passes syntax/basic checks after this edit."
}
],
"createdBy": "",
"source": "",
"description": "",
"planMarkdown": "Bot: Telegram Document Tools Bot (PDF <-> Word, PDF Merge)\n\nSummary:\nA production-ready Telegram bot built with Node.js (ESM) and grammY that helps users convert documents between PDF and Word formats (PDF to DOCX, DOCX to PDF) and merge multiple PDFs into a single PDF. The bot is designed to be simple in chat, reliable under real-world usage, and safe with user data.\n\nUsers interact via a guided flow: choose an operation, upload one or more files, confirm options, then receive the processed result. The system emphasizes predictable limits, clear progress messaging, robust validation, and secure temporary file handling.\n\nThe bot runs as a single Node.js service. MongoDB is used for persistence of jobs, user preferences, and audit metadata. File payloads are stored temporarily in simple filesystem storage or object storage, and cleaned up automatically based on retention rules.\n\nProduct goals:\nPrimary user goals\n1) Convert a PDF to a Word document (DOCX) with minimal friction.\n2) Convert a Word document (DOCX) to a PDF.\n3) Merge multiple PDFs into one combined PDF in user-defined order.\n\nProduct principles\n1) Chat-first UX: minimal commands, guided prompts, and inline buttons to reduce user error.\n2) Predictable outcomes: communicate limitations (scanned PDFs, complex layouts) and handle failures gracefully.\n3) Safety and privacy: validate inputs, restrict file sizes/types, isolate processing, and auto-delete temporary files.\n4) Production operability: job tracking, retries where safe, metrics, and clear admin diagnostics.\n\nNon-goals (explicit)\n1) Full OCR and perfect layout reconstruction for scanned/complex PDFs is not guaranteed. If OCR is added later, it should be presented as an optional mode.\n2) Editing documents inside Telegram is out of scope. The bot focuses on conversion and merging.\n3) Long-term document storage for users is out of scope; the bot provides short retention for processing and delivery.\n\nHigh-level architecture:\nHigh-level components (single Node.js service)\n1) Telegram Bot Layer (grammY)\n 1) Updates handler, command router, and conversational state management.\n 2) Inline keyboard interactions for selecting operation, confirming options, and controlling merge order.\n 3) File intake: download Telegram files after validating type and size.\n\n2) Job Orchestrator (in-process)\n 1) Creates and tracks jobs (convert or merge) and their steps.\n 2) Enforces concurrency limits per user and globally to protect CPU/memory.\n 3) Implements a simple in-process queue (no external queue) with backpressure.\n\n3) Document Processing Layer\n 1) Conversion workers that run the actual PDF <-> DOCX transformations.\n 2) PDF merge worker that combines multiple PDFs and validates the resulting file.\n 3) Sandboxed execution approach within the service process boundaries (resource limits at the application level), plus strict timeouts and file size limits.\n\n4) Storage Layer\n 1) Temporary file storage: simple filesystem storage (preferred for simplicity) or object storage if the runtime environment requires it.\n 2) Metadata persistence: MongoDB for user settings, job records, and minimal audit logs.\n 3) Automatic cleanup: TTL-based deletion of temp files and pruning of old job records.\n\n5) Observability and Admin Utilities\n 1) Structured logging with correlation IDs (jobId, userId, chatId).\n 2) Basic metrics (jobs created/completed/failed, processing duration, download/upload sizes).\n 3) Admin-only commands for health, queue depth, and recent failures.\n\nRequest lifecycle (end-to-end)\n1) User selects an operation and uploads file(s).\n2) Bot validates input, creates a job in MongoDB, stores files temporarily, and enqueues processing.\n3) Worker executes conversion/merge with timeouts and step-level status updates.\n4) Bot sends the output document back to the user, updates job status, and schedules cleanup.\n\nResilience strategy\n1) Idempotency: each job has a stable ID; repeated update deliveries do not duplicate processing.\n2) Safe retries: retry only steps that are safe (download, upload) and avoid retrying a conversion that could produce inconsistent results unless the previous attempt produced no output.\n3) Degraded mode: if processing is overloaded, the bot can accept jobs but estimate wait time and throttle per user.\n\nSecurity boundaries\n1) Treat all uploaded files as untrusted input.\n2) Validate MIME type, extension, and file signature where feasible.\n3) Enforce strict max file size, max pages (if detectable), and max number of merge inputs.\n4) Avoid storing user documents long-term; delete outputs shortly after delivery (configurable retention).\n\nData model:\nMongoDB collections (minimal, practical)\n\n1) users\nPurpose: store user preferences and usage limits.\nKey fields\n1) userId (Telegram user id)\n2) createdAt, updatedAt\n3) locale (optional)\n4) defaultOperation (optional)\n5) rateLimitTier (default or premium if you later add subscriptions)\n6) lastSeenAt\n\n2) jobs\nPurpose: track each conversion/merge request end-to-end.\nKey fields\n1) jobId (unique)\n2) userId, chatId\n3) type (pdftodocx, docxtopdf, pdfmerge)\n4) status (created, waitingforfiles, queued, processing, uploading, completed, failed, canceled, expired)\n5) createdAt, startedAt, finishedAt\n6) inputFiles: array of\n 1) telegramFileId (for reuse) and telegramUniqueFileId\n 2) originalName, mimeType, sizeBytes\n 3) tempStoragePathOrKey\n 4) orderIndex (for merge)\n7) outputFile\n 1) mimeType, sizeBytes\n 2) tempStoragePathOrKey\n 3) telegramFileId (after upload, for caching)\n8) options\n 1) mergeOrder (explicit order list)\n 2) outputName (optional)\n 3) conversionMode (future: fast vs accurate)\n9) error\n 1) code (validationerror, processingerror, timeout, unsupported, toolarge)\n 2) message (sanitized)\n 3) debugRef (internal correlation id)\n\n3) events (optional)\nPurpose: lightweight audit trail for debugging and support.\nKey fields\n1) eventId\n2) jobId, userId\n3) type (jobcreated, filereceived, processingstarted, processingfailed, outputsent, cleanupdone)\n4) timestamp\n5) meta (small payload)\n\nIndexes and retention\n1) jobs: index on userId + createdAt for history.\n2) jobs: index on status for operational queries.\n3) TTL index on jobs.finishedAt or jobs.createdAt (configurable retention, e.g., 24 hours to 7 days) depending on support needs.\n4) users: index on userId.\n\nIn-memory maps (supplemental, non-authoritative)\n1) per-user active job pointer for ongoing conversation.\n2) transient upload session state (e.g., expected number of PDFs for merge).\nThese should be recoverable from MongoDB so a restart does not break flows.\n\nKey flows:\nFlow A: PDF to Word (PDF -> DOCX)\n1) User starts with /start or taps Convert PDF to Word.\n2) Bot prompts: Send a PDF file.\n3) User uploads a document.\n4) Bot validates\n 1) Is it a document upload (not photo) and is it PDF.\n 2) Size within limit.\n 3) Optional: quick check that it’s not encrypted or corrupted (best effort).\n5) Bot creates a job with status queued and acknowledges with an estimated wait time.\n6) Worker downloads the file from Telegram to temporary storage.\n7) Worker runs conversion.\n8) Bot uploads DOCX result back to the user.\n9) Job marked completed; cleanup scheduled.\n\nUser-visible messaging\n1) Clear status updates: Received, Queued, Processing, Sending.\n2) If conversion quality may be imperfect (scans/complex layouts), mention this before processing and provide a fallback suggestion (e.g., try again with a different file, or in future add OCR mode).\n\nFlow B: Word to PDF (DOCX -> PDF)\n1) User selects Convert Word to PDF.\n2) Bot prompts: Send a DOCX file.\n3) Validate DOCX, size limit.\n4) Create job and enqueue.\n5) Download, convert, upload PDF.\n6) Cleanup.\n\nFlow C: Merge PDFs\n1) User selects Merge PDFs.\n2) Bot prompts: Send PDFs one by one. Provide inline buttons: Done, Cancel, Clear.\n3) User uploads multiple PDF documents.\n4) After each file, bot confirms count and shows current order.\n5) When user taps Done, bot shows an order management screen:\n 1) List files with numbers.\n 2) Controls: Move up/down for each entry, Remove entry, Add more.\n6) User confirms Merge.\n7) Bot creates job and enqueues.\n8) Worker downloads each input (if not already local), validates each PDF, merges in selected order.\n9) Bot uploads merged PDF with a sensible filename.\n10) Cleanup.\n\nFlow D: Error handling and recovery\n1) Unsupported file type\n 1) Bot explains accepted formats and asks the user to send the correct one.\n2) Too large\n 1) Bot rejects early and states the limit.\n 2) Suggest splitting or compressing before retry.\n3) Processing failure\n 1) Job marked failed with a user-friendly message.\n 2) Provide a Retry button that creates a new job referencing the same input file ids when possible.\n4) Timeout\n 1) Mark failed with suggestion to try smaller files.\n5) User cancels\n 1) Cancel button sets status canceled and triggers cleanup.\n\nFlow E: Rate limiting and abuse prevention\n1) Limit jobs per user per time window.\n2) Limit concurrent jobs per user (e.g., 1 active processing job, 1 queued).\n3) Hard caps\n 1) Max input size per file.\n 2) Max number of PDFs for merge.\n 3) Max total bytes across a merge job.\n4) If limits are hit, respond with a clear wait/try-later message.\n\nFlow F: Operational flows\n1) Startup health checks\n 1) Verify MongoDB connectivity.\n 2) Verify temp storage directory exists and is writable.\n2) Crash/restart recovery\n 1) On boot, find jobs in processing state older than a threshold and mark them failed or re-queue based on safe rules.\n 2) Clean orphaned temp files older than retention.\n3) Admin inspection\n 1) View recent failures and the sanitized reason.\n 2) Check queue depth and worker utilization.\n\nTech stack:\nRuntime and framework\n1) Node.js (ESM) single service.\n2) grammY for Telegram bot update handling, middleware, and conversational flows.\n3) Environment variables for configuration, including TELEGRAMBOTTOKEN.\n\nPersistence\n1) MongoDB for job and user metadata persistence.\n2) In-memory maps for ephemeral session state and per-process queue bookkeeping, with MongoDB as the source of truth for job status.\n\nFile handling\n1) Temporary storage in simple filesystem storage (local to the service) or object storage.\n2) Strict retention and cleanup policies to avoid accumulating user documents.\n\nDocument processing\n1) A pluggable processing layer that can call a conversion engine (library or bundled CLI tool) for:\n 1) PDF to DOCX conversion\n 2) DOCX to PDF conversion\n 3) PDF merge\n2) The processing layer must support:\n 1) timeouts per job\n 2) memory and file size safeguards\n 3) deterministic input/output paths\n 4) validation of produced files (non-empty, correct type)\n\nDeployment and configuration\n1) A generic Node.js server in the cloud.\n2) Webhook or long polling supported; webhook recommended for production if stable inbound connectivity is available.\n3) Configuration via environment variables:\n 1) TELEGRAMBOTTOKEN\n 2) MONGODBURI\n 3) TEMPSTORAGEPATH (if filesystem)\n 4) OBJECTSTORAGECONFIG (if used)\n 5) MAXFILESIZEMB, MAXMERGEFILES, MAXCONCURRENTJOBSGLOBAL, MAXCONCURRENTJOBSPERUSER\n 6) JOBRETENTIONHOURS\n\nNo additional infrastructure\n1) No additional databases beyond MongoDB.\n2) No external queues; the job queue is in-process with MongoDB-backed job records.\n\nNon-functional requirements:\nReliability\n1) Exactly-once user experience: avoid double-processing due to repeated Telegram updates by using job IDs and state checks.\n2) Safe restart behavior: recover or fail stale processing jobs deterministically.\n3) Bounded resources: hard limits on concurrency and file sizes to keep the single service stable.\n\nPerformance\n1) Concurrency caps: separate limits for download/upload and CPU-heavy conversion.\n2) Streaming where possible for Telegram file download/upload to reduce memory spikes.\n3) Fast feedback: acknowledge file receipt immediately and provide queue position or estimated wait.\n\nSecurity and privacy\n1) Validate all inputs, never trust filenames or MIME types alone.\n2) Store documents only as long as needed to process and deliver.\n3) Sanitize error messages returned to users; keep internal debug references in logs.\n4) Admin commands restricted by allowlist of Telegram user IDs.\n\nMaintainability\n1) Modular design: bot UI layer, job orchestration, processing adapters, storage adapter.\n2) Pluggable conversion engines: allow swapping conversion implementation without changing bot flows.\n3) Clear job state machine with explicit transitions.\n\nCompliance-like practices (practical)\n1) Data minimization: only store necessary metadata.\n2) Retention policy: automatic deletion with configurable retention.\n3) Transparency: a /privacy command explaining how files are handled and how long they are kept.\n\nTesting strategy\n1) Unit tests for validation, job state transitions, and merge order logic.\n2) Integration tests for Telegram file handling and end-to-end job lifecycle using test chats.\n3) Golden-file tests for conversions on a small set of known documents to detect regressions.\n\nOperational readiness\n1) Structured logs with jobId and userId.\n2) Alerting hooks are optional but logs should be actionable.\n3) Admin tooling to inspect failures and queue pressure without accessing user content.\n\nBot commands:\n• /start — Start the bot and show the main menu of document tools. (usage: /start) [general]\n• /help — Explain supported operations, limits, and how to use the bot. (usage: /help) [general]\n• /convert — Open a guided flow to choose conversion direction (PDF->DOCX or DOCX->PDF). (usage: /convert) [core]\n• /merge — Start a guided flow to collect multiple PDFs and merge them in a chosen order. (usage: /merge) [core]\n• /status — Show the status of your current or most recent job. (usage: /status) [core]\n• /cancel — Cancel the current active flow or queued/processing job when possible. (usage: /cancel) [core]\n• /limits — Display current file size limits, merge limits, and retention policy. (usage: /limits) [general]\n• /privacy — Explain how files are processed, stored temporarily, and deleted. (usage: /privacy) [general]\n• /adminhealth — Admin-only: show bot health, MongoDB connectivity, and temp storage status. (usage: /adminhealth) [admin]\n• /adminqueue — Admin-only: show queue depth, number of processing jobs, and recent throughput. (usage: /adminqueue) [admin]\n• /adminfailures — Admin-only: list recent failed jobs with sanitized reasons and debug references. (usage: /adminfailures) [admin]\n",
"planSections": {
"productGoals": "Primary user goals\n1) Convert a PDF to a Word document (DOCX) with minimal friction.\n2) Convert a Word document (DOCX) to a PDF.\n3) Merge multiple PDFs into one combined PDF in user-defined order.\n\nProduct principles\n1) Chat-first UX: minimal commands, guided prompts, and inline buttons to reduce user error.\n2) Predictable outcomes: communicate limitations (scanned PDFs, complex layouts) and handle failures gracefully.\n3) Safety and privacy: validate inputs, restrict file sizes/types, isolate processing, and auto-delete temporary files.\n4) Production operability: job tracking, retries where safe, metrics, and clear admin diagnostics.\n\nNon-goals (explicit)\n1) Full OCR and perfect layout reconstruction for scanned/complex PDFs is not guaranteed. If OCR is added later, it should be presented as an optional mode.\n2) Editing documents inside Telegram is out of scope. The bot focuses on conversion and merging.\n3) Long-term document storage for users is out of scope; the bot provides short retention for processing and delivery.",
"highLevelArchitecture": "High-level components (single Node.js service)\n1) Telegram Bot Layer (grammY)\n 1) Updates handler, command router, and conversational state management.\n 2) Inline keyboard interactions for selecting operation, confirming options, and controlling merge order.\n 3) File intake: download Telegram files after validating type and size.\n\n2) Job Orchestrator (in-process)\n 1) Creates and tracks jobs (convert or merge) and their steps.\n 2) Enforces concurrency limits per user and globally to protect CPU/memory.\n 3) Implements a simple in-process queue (no external queue) with backpressure.\n\n3) Document Processing Layer\n 1) Conversion workers that run the actual PDF <-> DOCX transformations.\n 2) PDF merge worker that combines multiple PDFs and validates the resulting file.\n 3) Sandboxed execution approach within the service process boundaries (resource limits at the application level), plus strict timeouts and file size limits.\n\n4) Storage Layer\n 1) Temporary file storage: simple filesystem storage (preferred for simplicity) or object storage if the runtime environment requires it.\n 2) Metadata persistence: MongoDB for user settings, job records, and minimal audit logs.\n 3) Automatic cleanup: TTL-based deletion of temp files and pruning of old job records.\n\n5) Observability and Admin Utilities\n 1) Structured logging with correlation IDs (jobId, userId, chatId).\n 2) Basic metrics (jobs created/completed/failed, processing duration, download/upload sizes).\n 3) Admin-only commands for health, queue depth, and recent failures.\n\nRequest lifecycle (end-to-end)\n1) User selects an operation and uploads file(s).\n2) Bot validates input, creates a job in MongoDB, stores files temporarily, and enqueues processing.\n3) Worker executes conversion/merge with timeouts and step-level status updates.\n4) Bot sends the output document back to the user, updates job status, and schedules cleanup.\n\nResilience strategy\n1) Idempotency: each job has a stable ID; repeated update deliveries do not duplicate processing.\n2) Safe retries: retry only steps that are safe (download, upload) and avoid retrying a conversion that could produce inconsistent results unless the previous attempt produced no output.\n3) Degraded mode: if processing is overloaded, the bot can accept jobs but estimate wait time and throttle per user.\n\nSecurity boundaries\n1) Treat all uploaded files as untrusted input.\n2) Validate MIME type, extension, and file signature where feasible.\n3) Enforce strict max file size, max pages (if detectable), and max number of merge inputs.\n4) Avoid storing user documents long-term; delete outputs shortly after delivery (configurable retention).",
"dataModel": "MongoDB collections (minimal, practical)\n\n1) users\nPurpose: store user preferences and usage limits.\nKey fields\n1) userId (Telegram user id)\n2) createdAt, updatedAt\n3) locale (optional)\n4) defaultOperation (optional)\n5) rateLimitTier (default or premium if you later add subscriptions)\n6) lastSeenAt\n\n2) jobs\nPurpose: track each conversion/merge request end-to-end.\nKey fields\n1) jobId (unique)\n2) userId, chatId\n3) type (pdftodocx, docxtopdf, pdfmerge)\n4) status (created, waitingforfiles, queued, processing, uploading, completed, failed, canceled, expired)\n5) createdAt, startedAt, finishedAt\n6) inputFiles: array of\n 1) telegramFileId (for reuse) and telegramUniqueFileId\n 2) originalName, mimeType, sizeBytes\n 3) tempStoragePathOrKey\n 4) orderIndex (for merge)\n7) outputFile\n 1) mimeType, sizeBytes\n 2) tempStoragePathOrKey\n 3) telegramFileId (after upload, for caching)\n8) options\n 1) mergeOrder (explicit order list)\n 2) outputName (optional)\n 3) conversionMode (future: fast vs accurate)\n9) error\n 1) code (validationerror, processingerror, timeout, unsupported, toolarge)\n 2) message (sanitized)\n 3) debugRef (internal correlation id)\n\n3) events (optional)\nPurpose: lightweight audit trail for debugging and support.\nKey fields\n1) eventId\n2) jobId, userId\n3) type (jobcreated, filereceived, processingstarted, processingfailed, outputsent, cleanupdone)\n4) timestamp\n5) meta (small payload)\n\nIndexes and retention\n1) jobs: index on userId + createdAt for history.\n2) jobs: index on status for operational queries.\n3) TTL index on jobs.finishedAt or jobs.createdAt (configurable retention, e.g., 24 hours to 7 days) depending on support needs.\n4) users: index on userId.\n\nIn-memory maps (supplemental, non-authoritative)\n1) per-user active job pointer for ongoing conversation.\n2) transient upload session state (e.g., expected number of PDFs for merge).\nThese should be recoverable from MongoDB so a restart does not break flows.",
"keyFlows": "Flow A: PDF to Word (PDF -> DOCX)\n1) User starts with /start or taps Convert PDF to Word.\n2) Bot prompts: Send a PDF file.\n3) User uploads a document.\n4) Bot validates\n 1) Is it a document upload (not photo) and is it PDF.\n 2) Size within limit.\n 3) Optional: quick check that it’s not encrypted or corrupted (best effort).\n5) Bot creates a job with status queued and acknowledges with an estimated wait time.\n6) Worker downloads the file from Telegram to temporary storage.\n7) Worker runs conversion.\n8) Bot uploads DOCX result back to the user.\n9) Job marked completed; cleanup scheduled.\n\nUser-visible messaging\n1) Clear status updates: Received, Queued, Processing, Sending.\n2) If conversion quality may be imperfect (scans/complex layouts), mention this before processing and provide a fallback suggestion (e.g., try again with a different file, or in future add OCR mode).\n\nFlow B: Word to PDF (DOCX -> PDF)\n1) User selects Convert Word to PDF.\n2) Bot prompts: Send a DOCX file.\n3) Validate DOCX, size limit.\n4) Create job and enqueue.\n5) Download, convert, upload PDF.\n6) Cleanup.\n\nFlow C: Merge PDFs\n1) User selects Merge PDFs.\n2) Bot prompts: Send PDFs one by one. Provide inline buttons: Done, Cancel, Clear.\n3) User uploads multiple PDF documents.\n4) After each file, bot confirms count and shows current order.\n5) When user taps Done, bot shows an order management screen:\n 1) List files with numbers.\n 2) Controls: Move up/down for each entry, Remove entry, Add more.\n6) User confirms Merge.\n7) Bot creates job and enqueues.\n8) Worker downloads each input (if not already local), validates each PDF, merges in selected order.\n9) Bot uploads merged PDF with a sensible filename.\n10) Cleanup.\n\nFlow D: Error handling and recovery\n1) Unsupported file type\n 1) Bot explains accepted formats and asks the user to send the correct one.\n2) Too large\n 1) Bot rejects early and states the limit.\n 2) Suggest splitting or compressing before retry.\n3) Processing failure\n 1) Job marked failed with a user-friendly message.\n 2) Provide a Retry button that creates a new job referencing the same input file ids when possible.\n4) Timeout\n 1) Mark failed with suggestion to try smaller files.\n5) User cancels\n 1) Cancel button sets status canceled and triggers cleanup.\n\nFlow E: Rate limiting and abuse prevention\n1) Limit jobs per user per time window.\n2) Limit concurrent jobs per user (e.g., 1 active processing job, 1 queued).\n3) Hard caps\n 1) Max input size per file.\n 2) Max number of PDFs for merge.\n 3) Max total bytes across a merge job.\n4) If limits are hit, respond with a clear wait/try-later message.\n\nFlow F: Operational flows\n1) Startup health checks\n 1) Verify MongoDB connectivity.\n 2) Verify temp storage directory exists and is writable.\n2) Crash/restart recovery\n 1) On boot, find jobs in processing state older than a threshold and mark them failed or re-queue based on safe rules.\n 2) Clean orphaned temp files older than retention.\n3) Admin inspection\n 1) View recent failures and the sanitized reason.\n 2) Check queue depth and worker utilization.",
"techStack": "Runtime and framework\n1) Node.js (ESM) single service.\n2) grammY for Telegram bot update handling, middleware, and conversational flows.\n3) Environment variables for configuration, including TELEGRAMBOTTOKEN.\n\nPersistence\n1) MongoDB for job and user metadata persistence.\n2) In-memory maps for ephemeral session state and per-process queue bookkeeping, with MongoDB as the source of truth for job status.\n\nFile handling\n1) Temporary storage in simple filesystem storage (local to the service) or object storage.\n2) Strict retention and cleanup policies to avoid accumulating user documents.\n\nDocument processing\n1) A pluggable processing layer that can call a conversion engine (library or bundled CLI tool) for:\n 1) PDF to DOCX conversion\n 2) DOCX to PDF conversion\n 3) PDF merge\n2) The processing layer must support:\n 1) timeouts per job\n 2) memory and file size safeguards\n 3) deterministic input/output paths\n 4) validation of produced files (non-empty, correct type)\n\nDeployment and configuration\n1) A generic Node.js server in the cloud.\n2) Webhook or long polling supported; webhook recommended for production if stable inbound connectivity is available.\n3) Configuration via environment variables:\n 1) TELEGRAMBOTTOKEN\n 2) MONGODBURI\n 3) TEMPSTORAGEPATH (if filesystem)\n 4) OBJECTSTORAGECONFIG (if used)\n 5) MAXFILESIZEMB, MAXMERGEFILES, MAXCONCURRENTJOBSGLOBAL, MAXCONCURRENTJOBSPERUSER\n 6) JOBRETENTIONHOURS\n\nNo additional infrastructure\n1) No additional databases beyond MongoDB.\n2) No external queues; the job queue is in-process with MongoDB-backed job records.",
"nonFunctional": "Reliability\n1) Exactly-once user experience: avoid double-processing due to repeated Telegram updates by using job IDs and state checks.\n2) Safe restart behavior: recover or fail stale processing jobs deterministically.\n3) Bounded resources: hard limits on concurrency and file sizes to keep the single service stable.\n\nPerformance\n1) Concurrency caps: separate limits for download/upload and CPU-heavy conversion.\n2) Streaming where possible for Telegram file download/upload to reduce memory spikes.\n3) Fast feedback: acknowledge file receipt immediately and provide queue position or estimated wait.\n\nSecurity and privacy\n1) Validate all inputs, never trust filenames or MIME types alone.\n2) Store documents only as long as needed to process and deliver.\n3) Sanitize error messages returned to users; keep internal debug references in logs.\n4) Admin commands restricted by allowlist of Telegram user IDs.\n\nMaintainability\n1) Modular design: bot UI layer, job orchestration, processing adapters, storage adapter.\n2) Pluggable conversion engines: allow swapping conversion implementation without changing bot flows.\n3) Clear job state machine with explicit transitions.\n\nCompliance-like practices (practical)\n1) Data minimization: only store necessary metadata.\n2) Retention policy: automatic deletion with configurable retention.\n3) Transparency: a /privacy command explaining how files are handled and how long they are kept.\n\nTesting strategy\n1) Unit tests for validation, job state transitions, and merge order logic.\n2) Integration tests for Telegram file handling and end-to-end job lifecycle using test chats.\n3) Golden-file tests for conversions on a small set of known documents to detect regressions.\n\nOperational readiness\n1) Structured logs with jobId and userId.\n2) Alerting hooks are optional but logs should be actionable.\n3) Admin tooling to inspect failures and queue pressure without accessing user content."
},
"balanceCentsRemaining": 2,
"billing": {
"ok": true,
"charged": 42,
"remaining": 2,
"chargedCents": 42,
"remainingCents": 2,
"currency": "USD",
"baseUsd": 0.208478,
"markupUsd": 0.208478,
"platformFeeUsd": 0,
"totalUsd": 0.416956
},
"title": "Telegram Document Tools Bot"
}
}
},
"runStatus": {
"phase": "done",
"stage": "cold_start",
"runId": "895875aa-8408-4bd0-925b-223c1182a8f9:mlmlnt45:1sg5c5",
"lastUserMessage": "Create a bot that can convert PDF files to Word documents and vice versa, as well as merge multiple PDF files into a single PDF file",
"startedAt": "2026-02-14T17:37:57.814Z",
"updatedAt": "2026-02-14T17:41:34.307Z",
"message": "GitHub auto-push skipped (no repo linked or GitHub not connected in session).",
"commands": [
{
"name": "admin_stats",
"file": "src/commands/admin_stats.js"
},
{
"name": "help",
"file": "src/commands/help.js"
},
{
"name": "reset",
"file": "src/commands/reset.js"
},
{
"name": "start",
"file": "src/commands/start.js"
},
{
"name": "status",
"file": "src/commands/status.js"
}
],
"ok": true,
"state": {
"projectId": "895875aa-8408-4bd0-925b-223c1182a8f9",
"fileStructure": {
".env.sample": {
"type": "file",
"content": "\nTELEGRAM_BOT_TOKEN=\nMONGODB_URI=\nCOOKMYBOTS_AI_ENDPOINT=https://api.cookmybots.com/api/ai\nCOOKMYBOTS_AI_KEY=\nAI_TIMEOUT_MS=600000\nAI_MAX_RETRIES=2\nCONCURRENCY=20\nMAX_FILE_MB=20\nADMIN_TELEGRAM_USER_ID=\n"
},
"CHANGELOG.md": {
"type": "file",
"content": "# Changelog\n\nAll notable changes to this bot project are recorded here.\n\n## 2026-02-14 17:41:34. UTC\n- Request: Create a bot that can convert PDF files to Word documents and vice versa, as well as merge multiple PDF files into a single PDF file\n- Summary: Created a complete, production-ready grammY Telegram bot for PDF→Word, Word→PDF, and PDF merging. It uses session state for per-chat workflows, MongoDB-backed long-term memory when available (with in-memory fallback), C…\n- Files: .env.sample, DOCS.md, README.md, package.json, project.json, src/bot.js, src/commands/admin_stats.js, src/commands/help.js, src/commands/loader.js, src/commands/reset.js, src/commands/start.js, src/commands/status.js, src/index.js, src/lib/ai.js (+9 more)\n\n"
},
"DOCS.md": {
"type": "file",
"content": "What this bot does\n\nThis Telegram bot converts documents and merges PDFs.\n\nSupported actions\n\n1) PDF to Word (.docx)\n2) Word (.doc/.docx) to PDF\n3) Merge multiple PDFs into one PDF\n\nPublic commands\n\n1) /start\nWhat it does: Welcome message and quick instructions.\nUsage: /start\n\n2) /help\nWhat it does: Shows help and examples.\nUsage: /help\n\n3) /status\nWhat it does: Shows your current mode (if any), merge queue count, and last action.\nUsage: /status\n\n4) /reset\nWhat it does: Clears your workflow state and clears your stored memory.\nUsage: /reset\n\nHow to use in chat\n\n1) Send “pdf to word” then upload a PDF.\n2) Send “word to pdf” then upload a DOC/DOCX.\n3) Send “merge pdfs” then upload PDFs in order. When ready, send “done” or press “Merge now”.\n\nWhile merging, you can also send “remove last” or “clear”.\n\nEnvironment variables\n\n1) TELEGRAM_BOT_TOKEN (required)\nTelegram bot token.\n\n2) COOKMYBOTS_AI_ENDPOINT (required)\nBase URL for the CookMyBots AI gateway. Must be a base URL ending with /api/ai.\n\n3) COOKMYBOTS_AI_KEY (required)\nAPI key for the CookMyBots AI gateway.\n\n4) MONGODB_URI (optional)\nMongoDB connection string for long-term memory.\n\n5) MAX_FILE_MB (optional)\nMaximum allowed file size in MB. Default is 20.\n\n6) ADMIN_TELEGRAM_USER_ID (optional)\nIf set, enables /admin_stats for that Telegram user id.\n\nRun\n\n1) Install: npm install\n2) Start: npm start\n3) Dev: npm run dev\n"
},
"README.md": {
"type": "file",
"content": "This is a Telegram bot (grammY) that provides document utilities:\n\n1) PDF to Word (.docx)\n2) Word (.doc/.docx) to PDF\n3) Merge multiple PDFs into one PDF\n\nIt’s designed to run as a single Node.js service on Render using long polling.\n\nSetup\n\n1) Install\n\nnpm install\n\n2) Configure environment variables\n\nCopy .env.sample to .env and fill in:\n\n1) TELEGRAM_BOT_TOKEN (required)\n2) COOKMYBOTS_AI_ENDPOINT (required for AI intent parsing and friendly replies)\n3) COOKMYBOTS_AI_KEY (required)\n4) MONGODB_URI (optional but recommended for long-term memory)\n5) MAX_FILE_MB (optional, defaults to 20)\n6) ADMIN_TELEGRAM_USER_ID (optional)\n\n3) Run locally\n\nnpm run dev\n\n4) Run in production\n\nnpm start\n\nCommands\n\n1) /start\nShows what the bot can do and how to use it.\n\n2) /help\nShows commands and examples.\n\n3) /status\nShows current mode, merge queue size, and last action.\n\n4) /reset\nClears the current workflow state and clears your stored memory.\n\nDocument processing backend\n\nPDF merge is implemented in-process using pdf-lib.\n\nPDF to Word and Word to PDF conversions require LibreOffice to be available on the system.\nThe bot will try to run the libreoffice binary (soffice). If it’s missing, the bot will fail gracefully and explain what’s needed.\n\nOn Render, you may need to use a Docker-based deployment or a build step that provides LibreOffice.\nIf LibreOffice is not present, PDF merge still works.\n\nDatabase and memory\n\nIf MONGODB_URI is set, the bot stores conversation turns in a MongoDB collection:\n\nmemory_messages\nFields: userId (string), platform (telegram), chatId (string), role (user|assistant), text, ts\n\nIf MONGODB_URI is not set, the bot uses an in-memory fallback and prints a warning log.\n\nTroubleshooting\n\n1) Bot does not respond\nMake sure TELEGRAM_BOT_TOKEN is set and valid.\n\n2) Conversion fails immediately\nLibreOffice is likely not installed or not on PATH. Deploy with LibreOffice available.\n\n3) File too large\nIncrease MAX_FILE_MB or send a smaller file.\n\nExtending\n\nAdd new commands in src/commands/*.js and they will be auto-registered by src/commands/loader.js.\nShared helpers live under src/lib and src/services.\n"
},
"package.json": {
"type": "file",
"content": "{\n \"scripts\": {\n \"install:root\": \"bash -lc \\\"set -e; if [ -f package-lock.json ]; then npm ci; else npm install; fi\\\"\",\n \"build\": \"npm run install:root && echo build\",\n \"start\": \"node src/index.js\",\n \"dev\": \"node --watch src/index.js\"\n },\n \"dependencies\": {\n \"@grammyjs/runner\": \"^2.0.3\",\n \"dotenv\": \"^16.4.5\",\n \"grammy\": \"^1.20.0\",\n \"mongodb\": \"^6.10.0\",\n \"pdf-lib\": \"latest\"\n },\n \"name\": \"document-tools-bot\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"devDependencies\": {}\n}\n"
},
"src": {
"type": "dir",
"children": {
"bot.js": {
"type": "file",
"content": "import { Bot, session } from \"grammy\";\n\nimport { registerCommands } from \"./commands/loader.js\";\nimport { cfg as readCfg } from \"./lib/config.js\";\nimport { safeErr } from \"./lib/safeErr.js\";\nimport {\n addTurn,\n getRecentTurns,\n clearUserMemory\n} from \"./lib/memory.js\";\nimport { aiChat } from \"./lib/ai.js\";\nimport { downloadTelegramDocument } from \"./services/telegramFiles.js\";\nimport { convertDocument } from \"./services/conversionService.js\";\nimport { mergePdfs } from \"./services/pdfMergeService.js\";\nimport {\n buildMainKeyboard,\n buildMergeKeyboard,\n isText\n} from \"./services/ui.js\";\n\nfunction initialSession() {\n return {\n store: {\n currentMode: null,\n mergeQueue: [],\n lastAction: \"\",\n lastPromptMsgId: null\n }\n };\n}\n\nfunction isAdmin(ctx, cfg) {\n const adminId = String(cfg.ADMIN_TELEGRAM_USER_ID || \"\").trim();\n if (!adminId) return false;\n return String(ctx.from?.id || \"\") === adminId;\n}\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nfunction inferModeFromFilename(name) {\n const n = String(name || \"\").toLowerCase();\n if (n.endsWith(\".pdf\")) return \"pdf_to_word\";\n if (n.endsWith(\".doc\") || n.endsWith(\".docx\")) return \"word_to_pdf\";\n return null;\n}\n\nasync function shouldHandleGroupMessage(ctx) {\n const chatType = ctx.chat?.type || \"private\";\n if (chatType === \"private\") return true;\n\n const botUsername = ctx.me?.username || ctx.botInfo?.username || \"\";\n if (!botUsername) return false;\n\n const msg = ctx.message;\n if (!msg) return false;\n\n const rawText = msg.text || \"\";\n const replyTo = msg.reply_to_message;\n const isReplyToBot =\n !!replyTo?.from?.is_bot &&\n String(replyTo?.from?.username || \"\").toLowerCase() ===\n String(botUsername).toLowerCase();\n\n const ents = Array.isArray(msg.entities) ? msg.entities : [];\n const isMentioned = ents.some((e) => {\n if (!e || e.type !== \"mention\") return false;\n const s = rawText.slice(e.offset, e.offset + e.length);\n return s.toLowerCase() === (\"@\" + botUsername.toLowerCase());\n });\n\n return isReplyToBot || isMentioned;\n}\n\nasync function saveUserTurn(ctx, text) {\n const userId = String(ctx.from?.id || \"\");\n const chatId = String(ctx.chat?.id || \"\");\n await addTurn({\n mongoUri: readCfg.MONGODB_URI,\n platform: \"telegram\",\n userId,\n chatId,\n role: \"user\",\n text: clampText(text)\n });\n}\n\nasync function saveAssistantTurn(ctx, text) {\n const userId = String(ctx.from?.id || \"\");\n const chatId = String(ctx.chat?.id || \"\");\n await addTurn({\n mongoUri: readCfg.MONGODB_URI,\n platform: \"telegram\",\n userId,\n chatId,\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nasync function aiInterpretText(ctx, text) {\n const userId = String(ctx.from?.id || \"\");\n const chatId = String(ctx.chat?.id || \"\");\n\n const history = await getRecentTurns({\n mongoUri: readCfg.MONGODB_URI,\n platform: \"telegram\",\n userId,\n chatId,\n limit: 16\n });\n\n const sys =\n \"You are a Telegram document utility bot. Your job is to interpret the user's intent and respond with a tiny JSON object only. \" +\n \"Allowed intents: set_mode_pdf_to_word, set_mode_word_to_pdf, set_mode_merge_pdfs, merge_done, merge_remove_last, merge_clear, status, reset, help, unknown. \" +\n \"Return JSON with keys: intent (string), reply (string). Keep reply short and friendly. Do not use markdown.\";\n\n const messages = [\n { role: \"system\", content: sys },\n ...history.map((t) => ({ role: t.role, content: t.text })),\n { role: \"user\", content: text }\n ];\n\n const out = await aiChat({\n messages,\n meta: {\n platform: \"telegram\",\n feature: \"intent\"\n }\n });\n\n const raw = String(out || \"\").trim();\n try {\n const json = JSON.parse(raw);\n return {\n intent: String(json.intent || \"unknown\"),\n reply: String(json.reply || \"\")\n };\n } catch {\n return {\n intent: \"unknown\",\n reply: \"\"\n };\n }\n}\n\nasync function handleDocument(ctx, cfg) {\n ctx.session.store ??= {};\n ctx.session.store.mergeQueue ??= [];\n\n const doc = ctx.message?.document;\n if (!doc) return;\n\n const fileName = doc.file_name || \"file\";\n const inferred = inferModeFromFilename(fileName);\n\n const mode = ctx.session.store.currentMode || inferred;\n if (!mode) {\n const msg =\n \"I can work with PDF and Word files. Tell me what you want first: pdf to word, word to pdf, or merge pdfs.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"asked_for_mode\";\n return;\n }\n\n const maxBytes = Math.max(1, Number(cfg.MAX_FILE_MB || 20)) * 1024 * 1024;\n const sizeBytes = Number(doc.file_size || 0);\n\n if (sizeBytes && sizeBytes > maxBytes) {\n const msg =\n \"That file is too large for this bot right now. Please send a smaller file (limit is \" +\n String(cfg.MAX_FILE_MB || 20) +\n \" MB).\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"rejected_too_large\";\n return;\n }\n\n if (mode === \"merge_pdfs\") {\n if (!String(fileName).toLowerCase().endsWith(\".pdf\")) {\n const msg = \"Merge mode only accepts PDFs. Please send a PDF document file.\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n ctx.session.store.mergeQueue.push({\n fileId: doc.file_id,\n fileUniqueId: doc.file_unique_id,\n fileName,\n sizeBytes,\n addedAt: new Date().toISOString()\n });\n\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.lastAction = \"merge_added\";\n\n const n = ctx.session.store.mergeQueue.length;\n const msg = \"Added. Now queued: \" + n + \". Send more PDFs, or press Merge now / send done.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (mode === \"pdf_to_word\") {\n if (!String(fileName).toLowerCase().endsWith(\".pdf\")) {\n const msg = \"For PDF to Word, please send a PDF as a document.\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n const receivedMsg = \"Got it. Converting your PDF to Word now.\";\n await ctx.reply(receivedMsg);\n await saveAssistantTurn(ctx, receivedMsg);\n\n const progress = await ctx.reply(\"Downloading file...\");\n\n try {\n console.log(\"[convert] start\", {\n mode,\n chatId: String(ctx.chat?.id || \"\"),\n userId: String(ctx.from?.id || \"\"),\n fileName,\n sizeBytes\n });\n\n const input = await downloadTelegramDocument(ctx.api, cfg.TELEGRAM_BOT_TOKEN, doc, {\n maxBytes\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Processing...\");\n\n const out = await convertDocument({\n direction: \"pdf_to_word\",\n inputBuffer: input.buffer,\n inputFilename: fileName\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Uploading...\");\n\n await ctx.api.sendDocument(\n ctx.chat.id,\n out.inputFile,\n {\n filename: out.outputFilename\n }\n );\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Done.\");\n\n ctx.session.store.lastAction = \"converted_pdf_to_word\";\n\n console.log(\"[convert] success\", {\n mode,\n outputFilename: out.outputFilename,\n outBytes: out.outputBytes\n });\n } catch (e) {\n console.error(\"[convert] failure\", { err: safeErr(e), mode });\n try {\n await ctx.api.editMessageText(\n ctx.chat.id,\n progress.message_id,\n \"Sorry, that conversion failed. Please try again or send a smaller/cleaner PDF.\"\n );\n } catch {}\n\n const helpMsg = await aiChat({\n messages: [\n {\n role: \"system\",\n content:\n \"You are a helpful Telegram bot. Write a short, friendly error message (1-2 lines) suggesting one next step. No markdown.\"\n },\n { role: \"user\", content: \"PDF to Word conversion failed. Error: \" + safeErr(e) }\n ],\n meta: { platform: \"telegram\", feature: \"error_copy\" }\n }).catch(() => \"Sorry, that conversion failed. Please retry with a smaller file.\");\n\n await ctx.reply(String(helpMsg || \"Sorry, that conversion failed. Please retry.\"));\n await saveAssistantTurn(ctx, String(helpMsg || \"Sorry, that conversion failed.\"));\n ctx.session.store.lastAction = \"convert_failed\";\n }\n\n return;\n }\n\n if (mode === \"word_to_pdf\") {\n const lower = String(fileName).toLowerCase();\n if (!(lower.endsWith(\".doc\") || lower.endsWith(\".docx\"))) {\n const msg = \"For Word to PDF, please send a .doc or .docx as a document.\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n const receivedMsg = \"Got it. Converting your Word document to PDF now.\";\n await ctx.reply(receivedMsg);\n await saveAssistantTurn(ctx, receivedMsg);\n\n const progress = await ctx.reply(\"Downloading file...\");\n\n try {\n console.log(\"[convert] start\", {\n mode,\n chatId: String(ctx.chat?.id || \"\"),\n userId: String(ctx.from?.id || \"\"),\n fileName,\n sizeBytes\n });\n\n const input = await downloadTelegramDocument(ctx.api, cfg.TELEGRAM_BOT_TOKEN, doc, {\n maxBytes\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Processing...\");\n\n const out = await convertDocument({\n direction: \"word_to_pdf\",\n inputBuffer: input.buffer,\n inputFilename: fileName\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Uploading...\");\n\n await ctx.api.sendDocument(ctx.chat.id, out.inputFile, {\n filename: out.outputFilename\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Done.\");\n\n ctx.session.store.lastAction = \"converted_word_to_pdf\";\n\n console.log(\"[convert] success\", {\n mode,\n outputFilename: out.outputFilename,\n outBytes: out.outputBytes\n });\n } catch (e) {\n console.error(\"[convert] failure\", { err: safeErr(e), mode });\n try {\n await ctx.api.editMessageText(\n ctx.chat.id,\n progress.message_id,\n \"Sorry, that conversion failed. Please try again or send a simpler/smaller DOCX.\"\n );\n } catch {}\n\n const helpMsg = await aiChat({\n messages: [\n {\n role: \"system\",\n content:\n \"You are a helpful Telegram bot. Write a short, friendly error message (1-2 lines) suggesting one next step. No markdown.\"\n },\n { role: \"user\", content: \"Word to PDF conversion failed. Error: \" + safeErr(e) }\n ],\n meta: { platform: \"telegram\", feature: \"error_copy\" }\n }).catch(() => \"Sorry, that conversion failed. Please retry with a smaller file.\");\n\n await ctx.reply(String(helpMsg || \"Sorry, that conversion failed. Please retry.\"));\n await saveAssistantTurn(ctx, String(helpMsg || \"Sorry, that conversion failed.\"));\n ctx.session.store.lastAction = \"convert_failed\";\n }\n\n return;\n }\n}\n\nasync function doMergeNow(ctx, cfg, requireConfirm = true) {\n ctx.session.store ??= {};\n ctx.session.store.mergeQueue ??= [];\n\n const q = ctx.session.store.mergeQueue;\n if (!q.length) {\n const msg = \"No PDFs queued yet. Send PDFs first (as documents).\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (q.length === 1) {\n const msg = \"You only have 1 PDF queued. Send at least 2 PDFs to merge.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (requireConfirm && !ctx.session.store.mergeConfirmed) {\n ctx.session.store.mergeConfirmed = true;\n const msg = \"You have \" + q.length + \" PDFs queued. Reply with yes to confirm merging, or send clear to start over.\";\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_asked_confirm\";\n return;\n }\n\n ctx.session.store.mergeConfirmed = false;\n\n const maxBytes = Math.max(1, Number(cfg.MAX_FILE_MB || 20)) * 1024 * 1024;\n\n const progress = await ctx.reply(\"Downloading PDFs...\");\n\n try {\n console.log(\"[merge] start\", {\n chatId: String(ctx.chat?.id || \"\"),\n userId: String(ctx.from?.id || \"\"),\n count: q.length\n });\n\n const buffers = [];\n for (const item of q) {\n const fakeDoc = {\n file_id: item.fileId,\n file_unique_id: item.fileUniqueId,\n file_name: item.fileName,\n file_size: item.sizeBytes\n };\n const input = await downloadTelegramDocument(ctx.api, cfg.TELEGRAM_BOT_TOKEN, fakeDoc, {\n maxBytes\n });\n buffers.push({ buffer: input.buffer, fileName: item.fileName });\n }\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Merging...\");\n\n const merged = await mergePdfs(buffers.map((b) => b.buffer));\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Uploading...\");\n\n const outName = \"merged.pdf\";\n await ctx.api.sendDocument(ctx.chat.id, merged.inputFile, {\n filename: outName\n });\n\n await ctx.api.editMessageText(ctx.chat.id, progress.message_id, \"Done.\");\n\n ctx.session.store.mergeQueue = [];\n ctx.session.store.currentMode = null;\n ctx.session.store.lastAction = \"merged_pdfs\";\n\n console.log(\"[merge] success\", { outBytes: merged.outputBytes });\n } catch (e) {\n console.error(\"[merge] failure\", { err: safeErr(e) });\n try {\n await ctx.api.editMessageText(\n ctx.chat.id,\n progress.message_id,\n \"Sorry, merging failed. Please try again, or send smaller PDFs.\"\n );\n } catch {}\n\n const helpMsg = await aiChat({\n messages: [\n {\n role: \"system\",\n content:\n \"You are a helpful Telegram bot. Write a short, friendly error message (1-2 lines) suggesting one next step. No markdown.\"\n },\n { role: \"user\", content: \"PDF merge failed. Error: \" + safeErr(e) }\n ],\n meta: { platform: \"telegram\", feature: \"error_copy\" }\n }).catch(() => \"Sorry, merging failed. Please retry with smaller PDFs.\");\n\n await ctx.reply(String(helpMsg || \"Sorry, merging failed. Please retry.\"));\n await saveAssistantTurn(ctx, String(helpMsg || \"Sorry, merging failed.\"));\n ctx.session.store.lastAction = \"merge_failed\";\n }\n}\n\nexport async function createBot(cfg) {\n const bot = new Bot(cfg.TELEGRAM_BOT_TOKEN);\n\n bot.use(\n session({\n initial: initialSession\n })\n );\n\n bot.catch(async (err) => {\n console.error(\"[bot] handler error\", {\n err: safeErr(err?.error || err),\n chatId: String(err?.ctx?.chat?.id || \"\"),\n userId: String(err?.ctx?.from?.id || \"\")\n });\n\n try {\n await err.ctx?.reply(\"Something went wrong. Please try again.\");\n } catch {}\n });\n\n await bot.init().catch(() => {});\n\n await registerCommands(bot, cfg);\n\n bot.on(\"message\", async (ctx, next) => {\n const ok = await shouldHandleGroupMessage(ctx);\n if (!ok) return next();\n return next();\n });\n\n bot.on(\"message:document\", async (ctx) => {\n await saveUserTurn(ctx, \"[document] \" + (ctx.message?.document?.file_name || \"file\"));\n await handleDocument(ctx, cfg);\n });\n\n bot.on(\"message\", async (ctx) => {\n const msg = ctx.message;\n if (!msg) return;\n\n if (msg.photo || msg.sticker || msg.voice || msg.video || msg.audio) {\n const t = \"Please send your file as a document upload (PDF, DOC, or DOCX).\";\n await ctx.reply(t);\n await saveAssistantTurn(ctx, t);\n }\n });\n\n bot.on(\"message:text\", async (ctx, next) => {\n const raw = isText(ctx) ? ctx.message.text : \"\";\n if (raw.startsWith(\"/\")) return next();\n\n await saveUserTurn(ctx, raw);\n\n ctx.session.store ??= {};\n ctx.session.store.mergeQueue ??= [];\n\n const t = raw.trim().toLowerCase();\n\n if (ctx.session.store.currentMode === \"merge_pdfs\") {\n if (t === \"done\" || t === \"merge\" || t === \"merge now\") {\n await doMergeNow(ctx, cfg, true);\n return;\n }\n\n if (t === \"remove last\") {\n const removed = ctx.session.store.mergeQueue.pop();\n const n = ctx.session.store.mergeQueue.length;\n const msg = removed\n ? \"Removed the last PDF. Now queued: \" + n + \".\"\n : \"Nothing to remove.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_remove_last\";\n return;\n }\n\n if (t === \"clear\") {\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n const msg = \"Cleared the merge queue. Send PDFs again in the order you want.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_cleared\";\n return;\n }\n\n if (t === \"yes\") {\n await doMergeNow(ctx, cfg, false);\n return;\n }\n }\n\n let interpreted;\n try {\n console.log(\"[ai] intent start\", {\n chatId: String(ctx.chat?.id || \"\"),\n userId: String(ctx.from?.id || \"\")\n });\n interpreted = await aiInterpretText(ctx, raw);\n console.log(\"[ai] intent success\", { intent: interpreted.intent });\n } catch (e) {\n console.error(\"[ai] intent failure\", { err: safeErr(e) });\n interpreted = { intent: \"unknown\", reply: \"\" };\n }\n\n const intent = interpreted.intent;\n\n if (intent === \"set_mode_pdf_to_word\") {\n ctx.session.store.currentMode = \"pdf_to_word\";\n const msg = interpreted.reply || \"OK. Send a PDF as a document and I’ll convert it to Word.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"mode_pdf_to_word\";\n return;\n }\n\n if (intent === \"set_mode_word_to_pdf\") {\n ctx.session.store.currentMode = \"word_to_pdf\";\n const msg = interpreted.reply || \"OK. Send a .doc or .docx as a document and I’ll convert it to PDF.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"mode_word_to_pdf\";\n return;\n }\n\n if (intent === \"set_mode_merge_pdfs\") {\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeConfirmed = false;\n const msg = interpreted.reply || \"OK. Send PDFs one by one. When you’re ready, press Merge now or send done.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"mode_merge_pdfs\";\n return;\n }\n\n if (intent === \"merge_done\") {\n ctx.session.store.currentMode = \"merge_pdfs\";\n await doMergeNow(ctx, cfg, true);\n return;\n }\n\n if (intent === \"merge_remove_last\") {\n ctx.session.store.currentMode = \"merge_pdfs\";\n const removed = ctx.session.store.mergeQueue.pop();\n const n = ctx.session.store.mergeQueue.length;\n const msg = removed\n ? \"Removed the last PDF. Now queued: \" + n + \".\"\n : \"Nothing to remove.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_remove_last\";\n return;\n }\n\n if (intent === \"merge_clear\") {\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n const msg = \"Cleared the merge queue. Send PDFs again in the order you want.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_cleared\";\n return;\n }\n\n if (intent === \"status\") {\n const mode = ctx.session.store.currentMode;\n const n = ctx.session.store.mergeQueue.length;\n const last = ctx.session.store.lastAction || \"\";\n const msg =\n \"Mode: \" +\n String(mode || \"none\") +\n \"\\nQueued PDFs: \" +\n String(n) +\n (last ? \"\\nLast: \" + last : \"\");\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (intent === \"reset\") {\n ctx.session.store.currentMode = null;\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n ctx.session.store.lastAction = \"reset\";\n\n await clearUserMemory({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\")\n });\n\n const msg = \"Reset done. Send a PDF, DOCX, or tell me what you want (pdf to word, word to pdf, merge pdfs).\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n if (intent === \"help\") {\n const msg =\n \"I can: PDF to Word, Word to PDF, and merge PDFs.\\n\\nTry saying: pdf to word, word to pdf, or merge pdfs.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n return;\n }\n\n const fallback =\n interpreted.reply ||\n \"Tell me what you want: pdf to word, word to pdf, or merge pdfs. You can also just send a PDF or DOCX.\";\n await ctx.reply(fallback, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, fallback);\n });\n\n bot.callbackQuery(\"mode:pdf_to_word\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"pdf_to_word\";\n ctx.session.store.lastAction = \"mode_pdf_to_word\";\n await ctx.answerCallbackQuery();\n const msg = \"Send a PDF as a document and I’ll convert it to Word.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n });\n\n bot.callbackQuery(\"mode:word_to_pdf\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"word_to_pdf\";\n ctx.session.store.lastAction = \"mode_word_to_pdf\";\n await ctx.answerCallbackQuery();\n const msg = \"Send a .doc or .docx as a document and I’ll convert it to PDF.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, msg);\n });\n\n bot.callbackQuery(\"mode:merge_pdfs\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeConfirmed = false;\n ctx.session.store.mergeQueue ??= [];\n ctx.session.store.lastAction = \"mode_merge_pdfs\";\n await ctx.answerCallbackQuery();\n const msg = \"Send PDFs one by one. When ready, press Merge now or send done.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n });\n\n bot.callbackQuery(\"merge:now\", async (ctx) => {\n await ctx.answerCallbackQuery();\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"merge_pdfs\";\n await doMergeNow(ctx, cfg, true);\n });\n\n bot.callbackQuery(\"merge:remove_last\", async (ctx) => {\n await ctx.answerCallbackQuery();\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeQueue ??= [];\n const removed = ctx.session.store.mergeQueue.pop();\n const n = ctx.session.store.mergeQueue.length;\n const msg = removed\n ? \"Removed the last PDF. Now queued: \" + n + \".\"\n : \"Nothing to remove.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_remove_last\";\n });\n\n bot.callbackQuery(\"merge:clear\", async (ctx) => {\n await ctx.answerCallbackQuery();\n ctx.session.store ??= {};\n ctx.session.store.currentMode = \"merge_pdfs\";\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n const msg = \"Cleared the merge queue. Send PDFs again in the order you want.\";\n await ctx.reply(msg, { reply_markup: buildMergeKeyboard() });\n await saveAssistantTurn(ctx, msg);\n ctx.session.store.lastAction = \"merge_cleared\";\n });\n\n return bot;\n}\n"
},
"commands": {
"type": "dir",
"children": {
"admin_stats.js": {
"type": "file",
"content": "import { getBootStats } from \"../services/stats.js\";\n\nexport default async function register(bot, cfg) {\n bot.command(\"admin_stats\", async (ctx) => {\n const adminId = String(cfg.ADMIN_TELEGRAM_USER_ID || \"\").trim();\n if (!adminId || String(ctx.from?.id || \"\") !== adminId) return;\n\n const s = getBootStats();\n const msg =\n \"Since boot:\\n\" +\n \"Conversions completed: \" +\n String(s.conversionsCompleted) +\n \"\\nMerges completed: \" +\n String(s.mergesCompleted);\n\n await ctx.reply(msg);\n });\n}\n"
},
"help.js": {
"type": "file",
"content": "import { buildMainKeyboard } from \"../services/ui.js\";\nimport { addTurn } from \"../lib/memory.js\";\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nasync function saveAssistantTurn(ctx, cfg, text) {\n await addTurn({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\"),\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nexport default async function register(bot, cfg) {\n bot.command(\"help\", async (ctx) => {\n const msg =\n \"Commands:\\n\" +\n \"/start Start\\n\" +\n \"/help Help\\n\" +\n \"/status Show current mode and merge queue\\n\" +\n \"/reset Clear workflow state and memory\\n\\n\" +\n \"Examples:\\n\" +\n \"1) pdf to word then send a PDF\\n\" +\n \"2) word to pdf then send a DOCX\\n\" +\n \"3) merge pdfs then send PDFs, then done\";\n\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, cfg, msg);\n });\n}\n"
},
"loader.js": {
"type": "file",
"content": "import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nexport async function registerCommands(bot, cfg) {\n const dir = path.dirname(fileURLToPath(import.meta.url));\n\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(\".js\") && f !== \"loader.js\" && !f.startsWith(\"_\"))\n .sort();\n\n for (const f of files) {\n const url = pathToFileURL(path.join(dir, f)).href;\n const mod = await import(url);\n\n const handler =\n (mod && (mod.default || mod.register)) ||\n (typeof mod === \"function\" ? mod : null);\n\n if (typeof handler === \"function\") {\n await handler(bot, cfg);\n } else {\n console.warn(\"[commands] skipped\", { file: f });\n }\n }\n}\n"
},
"reset.js": {
"type": "file",
"content": "import { clearUserMemory, addTurn } from \"../lib/memory.js\";\nimport { buildMainKeyboard } from \"../services/ui.js\";\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nasync function saveAssistantTurn(ctx, cfg, text) {\n await addTurn({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\"),\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nexport default async function register(bot, cfg) {\n bot.command(\"reset\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.currentMode = null;\n ctx.session.store.mergeQueue = [];\n ctx.session.store.mergeConfirmed = false;\n ctx.session.store.lastAction = \"reset\";\n\n await clearUserMemory({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\")\n });\n\n const msg = \"Reset done. Tell me: pdf to word, word to pdf, or merge pdfs.\";\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, cfg, msg);\n });\n}\n"
},
"start.js": {
"type": "file",
"content": "import { buildMainKeyboard } from \"../services/ui.js\";\nimport { addTurn } from \"../lib/memory.js\";\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nasync function saveAssistantTurn(ctx, cfg, text) {\n await addTurn({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\"),\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nexport default async function register(bot, cfg) {\n bot.command(\"start\", async (ctx) => {\n const maxMb = String(cfg.MAX_FILE_MB || 20);\n\n const msg =\n \"Hi. I can convert documents and merge PDFs.\\n\\n\" +\n \"1) Send a PDF to convert it to Word\\n\" +\n \"2) Send a DOC or DOCX to convert it to PDF\\n\" +\n \"3) To merge PDFs: say merge pdfs, then send PDFs in order, then press Merge now or send done\\n\\n\" +\n \"Note: file limit is about \" +\n maxMb +\n \" MB per file. Please send files as documents.\";\n\n ctx.session.store ??= {};\n\n await ctx.reply(msg, { reply_markup: buildMainKeyboard() });\n await saveAssistantTurn(ctx, cfg, msg);\n\n ctx.session.store.lastAction = \"start\";\n });\n}\n"
},
"status.js": {
"type": "file",
"content": "import { addTurn } from \"../lib/memory.js\";\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nasync function saveAssistantTurn(ctx, cfg, text) {\n await addTurn({\n mongoUri: cfg.MONGODB_URI,\n platform: \"telegram\",\n userId: String(ctx.from?.id || \"\"),\n chatId: String(ctx.chat?.id || \"\"),\n role: \"assistant\",\n text: clampText(text)\n });\n}\n\nexport default async function register(bot, cfg) {\n bot.command(\"status\", async (ctx) => {\n ctx.session.store ??= {};\n ctx.session.store.mergeQueue ??= [];\n\n const mode = ctx.session.store.currentMode;\n const queued = ctx.session.store.mergeQueue.length;\n const last = ctx.session.store.lastAction || \"\";\n\n const msg =\n \"Mode: \" +\n String(mode || \"none\") +\n \"\\nQueued PDFs: \" +\n String(queued) +\n (last ? \"\\nLast: \" + last : \"\");\n\n await ctx.reply(msg);\n await saveAssistantTurn(ctx, cfg, msg);\n });\n}\n"
}
}
},
"index.js": {
"type": "file",
"content": "import \"dotenv/config\";\n\nimport process from \"node:process\";\n\nfunction safeErr(e) {\n return (\n e?.response?.data?.error?.message ||\n e?.response?.data?.message ||\n e?.message ||\n String(e)\n );\n}\n\nprocess.on(\"unhandledRejection\", (r) => {\n console.error(\"[process] unhandledRejection\", { err: safeErr(r) });\n process.exit(1);\n});\n\nprocess.on(\"uncaughtException\", (e) => {\n console.error(\"[process] uncaughtException\", { err: safeErr(e) });\n process.exit(1);\n});\n\nasync function boot() {\n console.log(\"[boot] starting\", {\n tokenSet: !!process.env.TELEGRAM_BOT_TOKEN,\n mongoSet: !!process.env.MONGODB_URI,\n aiEndpointSet: !!process.env.COOKMYBOTS_AI_ENDPOINT,\n aiKeySet: !!process.env.COOKMYBOTS_AI_KEY\n });\n\n try {\n const { cfg } = await import(\"./lib/config.js\");\n\n if (!cfg.TELEGRAM_BOT_TOKEN) {\n console.error(\n \"TELEGRAM_BOT_TOKEN is required. Set it in env and redeploy.\"\n );\n process.exit(1);\n }\n\n const { createBot } = await import(\"./bot.js\");\n const bot = await createBot(cfg);\n\n await bot.api.deleteWebhook({ drop_pending_updates: true });\n\n const { run } = await import(\"@grammyjs/runner\");\n\n let backoffMs = 2000;\n const maxBackoffMs = 20000;\n\n while (true) {\n try {\n console.log(\"[polling] starting runner\", { concurrency: cfg.CONCURRENCY });\n await run(bot, { concurrency: cfg.CONCURRENCY });\n console.warn(\"[polling] runner stopped unexpectedly; restarting\");\n } catch (e) {\n const msg = safeErr(e);\n const code = e?.error_code || e?.code;\n\n if (code === 409 || String(msg).includes(\"409\")) {\n console.warn(\"[polling] 409 conflict; backing off\", { backoffMs });\n await new Promise((r) => setTimeout(r, backoffMs));\n backoffMs = Math.min(maxBackoffMs, Math.floor(backoffMs * 2.5));\n continue;\n }\n\n console.error(\"[polling] runner error\", { err: msg });\n await new Promise((r) => setTimeout(r, backoffMs));\n backoffMs = Math.min(maxBackoffMs, Math.floor(backoffMs * 2.5));\n }\n }\n } catch (e) {\n console.error(\"[boot] failed\", { err: safeErr(e), code: e?.code });\n if (e?.code === \"ERR_MODULE_NOT_FOUND\") {\n console.error(\n \"A required module was not found. Check that all src/ files exist and imports include .js extensions.\"\n );\n }\n process.exit(1);\n }\n}\n\nboot();\n"
},
"lib": {
"type": "dir",
"children": {
"ai.js": {
"type": "file",
"content": "import { cfg } from \"./config.js\";\nimport { safeErr } from \"./safeErr.js\";\n\nfunction clampBaseUrl(u) {\n const s = String(u || \"\").trim();\n return s.replace(/\\/+$/, \"\");\n}\n\nasync function sleep(ms) {\n await new Promise((r) => setTimeout(r, ms));\n}\n\nexport async function aiChat({ messages, model, meta }) {\n const base = clampBaseUrl(cfg.COOKMYBOTS_AI_ENDPOINT);\n const url = base + \"/chat\";\n\n const timeoutMs = Number(cfg.AI_TIMEOUT_MS || 600000);\n const maxRetries = Number(cfg.AI_MAX_RETRIES || 2);\n\n if (!cfg.COOKMYBOTS_AI_KEY) {\n throw new Error(\"COOKMYBOTS_AI_KEY missing\");\n }\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), timeoutMs);\n\n try {\n console.log(\"[ai] call start\", {\n endpoint: \"/chat\",\n attempt: attempt + 1,\n meta: meta || {}\n });\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + cfg.COOKMYBOTS_AI_KEY\n },\n body: JSON.stringify({\n messages,\n model,\n meta\n }),\n signal: ctrl.signal\n });\n\n const json = await res.json().catch(() => null);\n if (!res.ok) {\n const msg =\n json?.error || json?.message || \"AI request failed with status \" + res.status;\n throw new Error(msg);\n }\n\n const content = json?.output?.content;\n if (typeof content !== \"string\") {\n throw new Error(\"AI response missing output.content\");\n }\n\n console.log(\"[ai] call success\", {\n endpoint: \"/chat\",\n meta: meta || {}\n });\n\n return content;\n } catch (e) {\n const msg = safeErr(e);\n console.error(\"[ai] call failure\", {\n endpoint: \"/chat\",\n attempt: attempt + 1,\n err: msg\n });\n if (attempt >= maxRetries) throw e;\n await sleep(400 * Math.pow(2, attempt));\n } finally {\n clearTimeout(t);\n }\n }\n\n throw new Error(\"AI request failed\");\n}\n"
},
"config.js": {
"type": "file",
"content": "export const cfg = {\n TELEGRAM_BOT_TOKEN: process.env.TELEGRAM_BOT_TOKEN || \"\",\n MONGODB_URI: process.env.MONGODB_URI || \"\",\n\n COOKMYBOTS_AI_ENDPOINT:\n process.env.COOKMYBOTS_AI_ENDPOINT || \"https://api.cookmybots.com/api/ai\",\n COOKMYBOTS_AI_KEY: process.env.COOKMYBOTS_AI_KEY || \"\",\n\n AI_TIMEOUT_MS: Number(process.env.AI_TIMEOUT_MS || 600000),\n AI_MAX_RETRIES: Number(process.env.AI_MAX_RETRIES || 2),\n CONCURRENCY: Number(process.env.CONCURRENCY || 20),\n\n MAX_FILE_MB: Number(process.env.MAX_FILE_MB || 20),\n ADMIN_TELEGRAM_USER_ID: process.env.ADMIN_TELEGRAM_USER_ID || \"\"\n};\n"
},
"db.js": {
"type": "file",
"content": "import { MongoClient } from \"mongodb\";\nimport { safeErr } from \"./safeErr.js\";\n\nlet _client = null;\nlet _db = null;\nlet _indexEnsured = false;\n\nexport async function getDb(mongoUri) {\n if (!mongoUri) return null;\n if (_db) return _db;\n\n try {\n _client = new MongoClient(mongoUri, { maxPoolSize: 5, ignoreUndefined: true });\n await _client.connect();\n _db = _client.db();\n\n console.log(\"[db] connected\", { mongoSet: true });\n\n if (!_indexEnsured) {\n await ensureIndexes(_db);\n _indexEnsured = true;\n }\n\n return _db;\n } catch (e) {\n console.error(\"[db] connect failed\", { err: safeErr(e) });\n _db = null;\n return null;\n }\n}\n\nasync function ensureIndexes(db) {\n try {\n const col = db.collection(\"memory_messages\");\n await col.createIndex({ platform: 1, userId: 1, chatId: 1, ts: -1 });\n } catch (e) {\n console.error(\"[db] ensureIndexes failed\", { err: safeErr(e) });\n }\n}\n"
},
"memory.js": {
"type": "file",
"content": "import { getDb } from \"./db.js\";\n\nconst COL = \"memory_messages\";\n\nconst inMem = new Map();\nlet warned = false;\n\nfunction keyOf({ platform, userId, chatId }) {\n return String(platform) + \":\" + String(userId) + \":\" + String(chatId || \"\");\n}\n\nfunction clampText(t, max = 4000) {\n const s = String(t || \"\");\n return s.length > max ? s.slice(0, max) : s;\n}\n\nexport async function addTurn({ mongoUri, platform, userId, chatId, role, text }) {\n const doc = {\n platform: String(platform),\n userId: String(userId || \"\"),\n chatId: String(chatId || \"\"),\n role: String(role),\n text: clampText(text),\n ts: new Date()\n };\n\n const db = await getDb(mongoUri);\n if (db) {\n try {\n await db.collection(COL).insertOne(doc);\n return;\n } catch (e) {\n console.error(\"[memory] insert failed\", { err: e?.message || String(e) });\n }\n }\n\n if (!warned) {\n warned = true;\n console.warn(\"[memory] MONGODB_URI not set or DB unavailable; using in-memory fallback\");\n }\n\n const k = keyOf(doc);\n const arr = inMem.get(k) || [];\n arr.push({ role: doc.role, text: doc.text, ts: doc.ts });\n while (arr.length > 50) arr.shift();\n inMem.set(k, arr);\n}\n\nexport async function getRecentTurns({ mongoUri, platform, userId, chatId, limit = 14 }) {\n const db = await getDb(mongoUri);\n if (db) {\n const q = {\n platform: String(platform),\n userId: String(userId || \"\"),\n chatId: String(chatId || \"\")\n };\n\n const rows = await db\n .collection(COL)\n .find(q)\n .sort({ ts: -1 })\n .limit(limit)\n .toArray();\n\n return rows\n .reverse()\n .map((r) => ({ role: String(r.role), text: String(r.text || \"\") }));\n }\n\n if (!warned) {\n warned = true;\n console.warn(\"[memory] MONGODB_URI not set or DB unavailable; using in-memory fallback\");\n }\n\n const k = keyOf({ platform, userId, chatId });\n const arr = inMem.get(k) || [];\n return arr.slice(-limit).map((r) => ({ role: r.role, text: r.text }));\n}\n\nexport async function clearUserMemory({ mongoUri, platform, userId, chatId }) {\n const db = await getDb(mongoUri);\n if (db) {\n const q = {\n platform: String(platform),\n userId: String(userId || \"\"),\n chatId: String(chatId || \"\")\n };\n\n await db.collection(COL).deleteMany(q);\n return;\n }\n\n const k = keyOf({ platform, userId, chatId });\n inMem.delete(k);\n}\n"
},
"safeErr.js": {
"type": "file",
"content": "export function safeErr(e) {\n return (\n e?.response?.data?.error?.message ||\n e?.response?.data?.message ||\n e?.message ||\n String(e)\n );\n}\n"
}
}
},
"services": {
"type": "dir",
"children": {
"conversionService.js": {
"type": "file",
"content": "import { InputFile } from \"grammy\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport crypto from \"node:crypto\";\nimport { spawn } from \"node:child_process\";\nimport { safeErr } from \"../lib/safeErr.js\";\nimport { incConversionsCompleted } from \"./stats.js\";\n\nfunction rand() {\n return crypto.randomBytes(8).toString(\"hex\");\n}\n\nfunction extOf(name) {\n const n = String(name || \"\");\n const i = n.lastIndexOf(\".\");\n return i >= 0 ? n.slice(i + 1).toLowerCase() : \"\";\n}\n\nfunction stripExt(name) {\n const n = String(name || \"file\");\n const i = n.lastIndexOf(\".\");\n return i >= 0 ? n.slice(0, i) : n;\n}\n\nasync function runSofficeConvert({ inputPath, outDir, targetExt, timeoutMs = 240000 }) {\n return new Promise((resolve, reject) => {\n const args = [\n \"--headless\",\n \"--nologo\",\n \"--nolockcheck\",\n \"--nodefault\",\n \"--norestore\",\n \"--invisible\",\n \"--convert-to\",\n targetExt,\n \"--outdir\",\n outDir,\n inputPath\n ];\n\n const child = spawn(\"soffice\", args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"]\n });\n\n let stderr = \"\";\n child.stderr.on(\"data\", (d) => {\n stderr += String(d || \"\");\n if (stderr.length > 2000) stderr = stderr.slice(-2000);\n });\n\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(\"CONVERSION_TIMEOUT\"));\n }, timeoutMs);\n\n child.on(\"error\", (e) => {\n clearTimeout(timer);\n reject(e);\n });\n\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n if (code !== 0) {\n reject(new Error(\"LIBREOFFICE_FAILED: \" + code + \": \" + stderr));\n return;\n }\n resolve();\n });\n });\n}\n\nexport async function convertDocument({ direction, inputBuffer, inputFilename }) {\n const tmpBase = await fs.mkdtemp(path.join(os.tmpdir(), \"doc-tools-\"));\n\n const inExt = extOf(inputFilename);\n const base = stripExt(inputFilename) || \"file\";\n\n const inputPath = path.join(tmpBase, \"input.\" + (inExt || \"bin\"));\n await fs.writeFile(inputPath, inputBuffer);\n\n try {\n if (direction === \"pdf_to_word\") {\n const outExt = \"docx\";\n const outName = base + \".docx\";\n\n console.log(\"[convert] libreoffice start\", {\n direction,\n inputExt: inExt,\n outExt\n });\n\n await runSofficeConvert({\n inputPath,\n outDir: tmpBase,\n targetExt: outExt\n });\n\n const outPath = path.join(tmpBase, \"input.\" + outExt);\n const outBuf = await fs.readFile(outPath);\n\n if (!outBuf?.length) throw new Error(\"EMPTY_OUTPUT\");\n\n incConversionsCompleted();\n\n return {\n outputFilename: outName,\n mimeType:\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n outputBytes: outBuf.length,\n inputFile: new InputFile(outBuf, outName)\n };\n }\n\n if (direction === \"word_to_pdf\") {\n const outExt = \"pdf\";\n const outName = base + \".pdf\";\n\n console.log(\"[convert] libreoffice start\", {\n direction,\n inputExt: inExt,\n outExt\n });\n\n await runSofficeConvert({\n inputPath,\n outDir: tmpBase,\n targetExt: outExt\n });\n\n const outPath = path.join(tmpBase, \"input.\" + outExt);\n const outBuf = await fs.readFile(outPath);\n\n if (!outBuf?.length) throw new Error(\"EMPTY_OUTPUT\");\n\n incConversionsCompleted();\n\n return {\n outputFilename: outName,\n mimeType: \"application/pdf\",\n outputBytes: outBuf.length,\n inputFile: new InputFile(outBuf, outName)\n };\n }\n\n throw new Error(\"UNKNOWN_DIRECTION\");\n } catch (e) {\n const msg = safeErr(e);\n\n if (\n msg.includes(\"spawn soffice\") ||\n msg.includes(\"ENOENT\") ||\n msg.toLowerCase().includes(\"soffice\")\n ) {\n throw new Error(\n \"CONVERTER_MISSING: LibreOffice (soffice) is not installed or not on PATH\"\n );\n }\n\n throw e;\n } finally {\n try {\n await fs.rm(tmpBase, { recursive: true, force: true });\n } catch {}\n }\n}\n"
},
"pdfMergeService.js": {
"type": "file",
"content": "import { PDFDocument } from \"pdf-lib\";\nimport { InputFile } from \"grammy\";\nimport { safeErr } from \"../lib/safeErr.js\";\nimport { incMergesCompleted } from \"./stats.js\";\n\nexport async function mergePdfs(buffers) {\n try {\n const out = await PDFDocument.create();\n\n for (const b of buffers) {\n const doc = await PDFDocument.load(b, { ignoreEncryption: false });\n const pages = await out.copyPages(doc, doc.getPageIndices());\n for (const p of pages) out.addPage(p);\n }\n\n const bytes = await out.save();\n const buf = Buffer.from(bytes);\n\n if (!buf.length) throw new Error(\"EMPTY_OUTPUT\");\n\n incMergesCompleted();\n\n return {\n outputBytes: buf.length,\n inputFile: new InputFile(buf, \"merged.pdf\")\n };\n } catch (e) {\n const msg = safeErr(e);\n if (msg.toLowerCase().includes(\"encrypted\")) {\n throw new Error(\"ENCRYPTED_PDF\");\n }\n throw e;\n }\n}\n"
},
"stats.js": {
"type": "file",
"content": "const bootStats = {\n conversionsCompleted: 0,\n mergesCompleted: 0\n};\n\nexport function incConversionsCompleted() {\n bootStats.conversionsCompleted += 1;\n}\n\nexport function incMergesCompleted() {\n bootStats.mergesCompleted += 1;\n}\n\nexport function getBootStats() {\n return { ...bootStats };\n}\n"
},
"telegramFiles.js": {
"type": "file",
"content": "import https from \"node:https\";\nimport { safeErr } from \"../lib/safeErr.js\";\n\nfunction getFileUrl(token, filePath) {\n return \"https://api.telegram.org/file/bot\" + token + \"/\" + filePath;\n}\n\nfunction download(url, { maxBytes }) {\n return new Promise((resolve, reject) => {\n const req = https.get(url, (res) => {\n if (res.statusCode && res.statusCode >= 400) {\n reject(new Error(\"Download failed with status \" + res.statusCode));\n res.resume();\n return;\n }\n\n const chunks = [];\n let bytes = 0;\n\n res.on(\"data\", (d) => {\n bytes += d.length;\n if (maxBytes && bytes > maxBytes) {\n req.destroy(new Error(\"FILE_TOO_LARGE\"));\n return;\n }\n chunks.push(d);\n });\n\n res.on(\"end\", () => {\n resolve({ buffer: Buffer.concat(chunks), bytes });\n });\n\n res.on(\"error\", (e) => reject(e));\n });\n\n req.on(\"error\", (e) => reject(e));\n });\n}\n\nexport async function downloadTelegramDocument(api, token, document, { maxBytes }) {\n const fileId = document.file_id;\n\n console.log(\"[tgfile] getFile start\", {\n fileId: String(fileId).slice(0, 12) + \"...\",\n sizeBytes: Number(document.file_size || 0)\n });\n\n let file;\n try {\n file = await api.getFile(fileId);\n } catch (e) {\n console.error(\"[tgfile] getFile failed\", { err: safeErr(e) });\n throw e;\n }\n\n const filePath = file?.file_path;\n if (!filePath) throw new Error(\"TELEGRAM_FILE_PATH_MISSING\");\n\n const url = getFileUrl(token, filePath);\n\n console.log(\"[tgfile] download start\", {\n filePath: String(filePath).slice(0, 60),\n maxBytes: Number(maxBytes || 0)\n });\n\n try {\n const res = await download(url, { maxBytes });\n console.log(\"[tgfile] download success\", { bytes: res.bytes });\n return {\n buffer: res.buffer,\n bytes: res.bytes,\n filePath\n };\n } catch (e) {\n console.error(\"[tgfile] download failed\", { err: safeErr(e) });\n if (String(safeErr(e)).includes(\"FILE_TOO_LARGE\")) {\n throw new Error(\"FILE_TOO_LARGE\");\n }\n throw e;\n }\n}\n"
},
"ui.js": {
"type": "file",
"content": "import { InlineKeyboard } from \"grammy\";\n\nexport function buildMainKeyboard() {\n const kb = new InlineKeyboard()\n .text(\"PDF to Word\", \"mode:pdf_to_word\")\n .text(\"Word to PDF\", \"mode:word_to_pdf\")\n .row()\n .text(\"Merge PDFs\", \"mode:merge_pdfs\");\n\n return kb;\n}\n\nexport function buildMergeKeyboard() {\n const kb = new InlineKeyboard()\n .text(\"Merge now\", \"merge:now\")\n .row()\n .text(\"Remove last\", \"merge:remove_last\")\n .text(\"Clear\", \"merge:clear\");\n\n return kb;\n}\n\nexport function isText(ctx) {\n return !!ctx.message?.text;\n}\n"
}
}
}
}
}
},
"commands": [
{
"command": "/admin_stats",
"description": "Handler for /admin_stats",
"example": "User: /admin_stats → bot replies."
},
{
"command": "/help",
"description": "Shows all public commands and example usage.",
"usage": "/help",
"examples": [
"User: /help → Bot: command list and examples"
],
"example": "User: /help → Bot: command list and examples",
"notes": "You can also just type things like “pdf to word” or “merge pdfs”."
},
{
"command": "/reset",
"description": "Clears your active workflow state and clears your stored memory.",
"usage": "/reset",
"examples": [
"User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs."
],
"example": "User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs.",
"notes": "If MongoDB is configured, this also deletes your memory records."
},
{
"command": "/start",
"description": "Explains what the bot can do and how to use it.",
"usage": "/start",
"examples": [
"User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs"
],
"example": "User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs",
"notes": "Send files as documents. Large files may be refused based on MAX_FILE_MB."
},
{
"command": "/status",
"description": "Shows the current selected mode, queued PDFs count, and last action.",
"usage": "/status",
"examples": [
"User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added"
],
"example": "User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added",
"notes": "Useful when you’re in the middle of merging."
}
],
"envVarDocs": [
{
"key": "TELEGRAM_BOT_TOKEN",
"title": "Telegram Bot Token",
"description": "Token for your Telegram bot from BotFather.",
"usage": "Used by grammY to connect to Telegram.",
"howToGet": "Create a bot with BotFather in Telegram and copy the token.",
"example": "123456:ABCDEF...",
"isSecret": true,
"required": true
},
{
"key": "MONGODB_URI",
"title": "MongoDB Connection String",
"description": "MongoDB connection string for long-term memory storage.",
"usage": "If present, conversation turns are stored in memory_messages; otherwise in-memory fallback is used.",
"howToGet": "Use MongoDB Atlas or another Mongo provider to create a database and user.",
"example": "mongodb+srv://user:pass@cluster/dbname",
"isSecret": true,
"required": false
},
{
"key": "COOKMYBOTS_AI_ENDPOINT",
"title": "CookMyBots AI Endpoint",
"description": "Base URL for the CookMyBots AI gateway (must be a base URL ending with /api/ai).",
"usage": "The bot calls POST {endpoint}/chat for intent parsing and friendly replies.",
"howToGet": "Provided by CookMyBots.",
"example": "https://api.cookmybots.com/api/ai",
"isSecret": false,
"required": true
},
{
"key": "COOKMYBOTS_AI_KEY",
"title": "CookMyBots AI Key",
"description": "API key used to authenticate requests to the CookMyBots AI gateway.",
"usage": "Sent as Authorization: Bearer <key> for AI calls.",
"howToGet": "Provided by CookMyBots.",
"example": "cmb_ai_...",
"isSecret": true,
"required": true
},
{
"key": "AI_TIMEOUT_MS",
"title": "AI Timeout",
"description": "Timeout for AI gateway requests in milliseconds.",
"usage": "Controls fetch AbortController timeout for AI calls.",
"howToGet": "Optional setting.",
"example": "600000",
"isSecret": false,
"required": false
},
{
"key": "AI_MAX_RETRIES",
"title": "AI Retry Count",
"description": "How many times to retry AI calls on failure.",
"usage": "Used by src/lib/ai.js retry loop.",
"howToGet": "Optional setting.",
"example": "2",
"isSecret": false,
"required": false
},
{
"key": "CONCURRENCY",
"title": "Telegram Update Concurrency",
"description": "Number of updates processed concurrently by @grammyjs/runner.",
"usage": "Passed to run(bot,{concurrency}).",
"howToGet": "Optional setting.",
"example": "20",
"isSecret": false,
"required": false
},
{
"key": "MAX_FILE_MB",
"title": "Max File Size",
"description": "Maximum allowed upload size per document (in MB).",
"usage": "Validated against Telegram-reported size and enforced during download.",
"howToGet": "Optional setting.",
"example": "20",
"isSecret": false,
"required": false
},
{
"key": "ADMIN_TELEGRAM_USER_ID",
"title": "Admin Telegram User ID",
"description": "If set, enables /admin_stats for that user only.",
"usage": "Compared to ctx.from.id to authorize admin command.",
"howToGet": "Find your Telegram numeric user id (various bots/tools can show it).",
"example": "123456789",
"isSecret": false,
"required": false
}
],
"commandDocs": [
{
"command": "/start",
"description": "Explains what the bot can do and how to use it.",
"usage": "/start",
"examples": [
"User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs"
],
"notes": "Send files as documents. Large files may be refused based on MAX_FILE_MB."
},
{
"command": "/help",
"description": "Shows all public commands and example usage.",
"usage": "/help",
"examples": [
"User: /help → Bot: command list and examples"
],
"notes": "You can also just type things like “pdf to word” or “merge pdfs”."
},
{
"command": "/status",
"description": "Shows the current selected mode, queued PDFs count, and last action.",
"usage": "/status",
"examples": [
"User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added"
],
"notes": "Useful when you’re in the middle of merging."
},
{
"command": "/reset",
"description": "Clears your active workflow state and clears your stored memory.",
"usage": "/reset",
"examples": [
"User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs."
],
"notes": "If MongoDB is configured, this also deletes your memory records."
}
],
"aiMessages": [
{
"role": "user",
"content": "Create a bot that can convert PDF files to Word documents and vice versa, as well as merge multiple PDF files into a single PDF file"
},
{
"role": "assistant",
"content": "Created a complete, production-ready grammY Telegram bot for PDF→Word, Word→PDF, and PDF merging. It uses session state for per-chat workflows, MongoDB-backed long-term memory when available (with in-memory fallback), CookMyBots AI gateway for intent parsing and friendly replies, pdf-lib for merging, and LibreOffice (soffice) for conversions with graceful failure messaging if the binary is missing. Long polling uses @grammyjs/runner with webhook cleanup and 409 conflict backoff.\n\nFiles touched (23): .env.sample, DOCS.md, README.md, package.json, project.json, src/bot.js…\nValidation: ✅ project passes syntax/basic checks after this edit."
}
],
"createdBy": "",
"source": "",
"description": "",
"planMarkdown": "Bot: Telegram Document Tools Bot (PDF <-> Word, PDF Merge)\n\nSummary:\nA production-ready Telegram bot built with Node.js (ESM) and grammY that helps users convert documents between PDF and Word formats (PDF to DOCX, DOCX to PDF) and merge multiple PDFs into a single PDF. The bot is designed to be simple in chat, reliable under real-world usage, and safe with user data.\n\nUsers interact via a guided flow: choose an operation, upload one or more files, confirm options, then receive the processed result. The system emphasizes predictable limits, clear progress messaging, robust validation, and secure temporary file handling.\n\nThe bot runs as a single Node.js service. MongoDB is used for persistence of jobs, user preferences, and audit metadata. File payloads are stored temporarily in simple filesystem storage or object storage, and cleaned up automatically based on retention rules.\n\nProduct goals:\nPrimary user goals\n1) Convert a PDF to a Word document (DOCX) with minimal friction.\n2) Convert a Word document (DOCX) to a PDF.\n3) Merge multiple PDFs into one combined PDF in user-defined order.\n\nProduct principles\n1) Chat-first UX: minimal commands, guided prompts, and inline buttons to reduce user error.\n2) Predictable outcomes: communicate limitations (scanned PDFs, complex layouts) and handle failures gracefully.\n3) Safety and privacy: validate inputs, restrict file sizes/types, isolate processing, and auto-delete temporary files.\n4) Production operability: job tracking, retries where safe, metrics, and clear admin diagnostics.\n\nNon-goals (explicit)\n1) Full OCR and perfect layout reconstruction for scanned/complex PDFs is not guaranteed. If OCR is added later, it should be presented as an optional mode.\n2) Editing documents inside Telegram is out of scope. The bot focuses on conversion and merging.\n3) Long-term document storage for users is out of scope; the bot provides short retention for processing and delivery.\n\nHigh-level architecture:\nHigh-level components (single Node.js service)\n1) Telegram Bot Layer (grammY)\n 1) Updates handler, command router, and conversational state management.\n 2) Inline keyboard interactions for selecting operation, confirming options, and controlling merge order.\n 3) File intake: download Telegram files after validating type and size.\n\n2) Job Orchestrator (in-process)\n 1) Creates and tracks jobs (convert or merge) and their steps.\n 2) Enforces concurrency limits per user and globally to protect CPU/memory.\n 3) Implements a simple in-process queue (no external queue) with backpressure.\n\n3) Document Processing Layer\n 1) Conversion workers that run the actual PDF <-> DOCX transformations.\n 2) PDF merge worker that combines multiple PDFs and validates the resulting file.\n 3) Sandboxed execution approach within the service process boundaries (resource limits at the application level), plus strict timeouts and file size limits.\n\n4) Storage Layer\n 1) Temporary file storage: simple filesystem storage (preferred for simplicity) or object storage if the runtime environment requires it.\n 2) Metadata persistence: MongoDB for user settings, job records, and minimal audit logs.\n 3) Automatic cleanup: TTL-based deletion of temp files and pruning of old job records.\n\n5) Observability and Admin Utilities\n 1) Structured logging with correlation IDs (jobId, userId, chatId).\n 2) Basic metrics (jobs created/completed/failed, processing duration, download/upload sizes).\n 3) Admin-only commands for health, queue depth, and recent failures.\n\nRequest lifecycle (end-to-end)\n1) User selects an operation and uploads file(s).\n2) Bot validates input, creates a job in MongoDB, stores files temporarily, and enqueues processing.\n3) Worker executes conversion/merge with timeouts and step-level status updates.\n4) Bot sends the output document back to the user, updates job status, and schedules cleanup.\n\nResilience strategy\n1) Idempotency: each job has a stable ID; repeated update deliveries do not duplicate processing.\n2) Safe retries: retry only steps that are safe (download, upload) and avoid retrying a conversion that could produce inconsistent results unless the previous attempt produced no output.\n3) Degraded mode: if processing is overloaded, the bot can accept jobs but estimate wait time and throttle per user.\n\nSecurity boundaries\n1) Treat all uploaded files as untrusted input.\n2) Validate MIME type, extension, and file signature where feasible.\n3) Enforce strict max file size, max pages (if detectable), and max number of merge inputs.\n4) Avoid storing user documents long-term; delete outputs shortly after delivery (configurable retention).\n\nData model:\nMongoDB collections (minimal, practical)\n\n1) users\nPurpose: store user preferences and usage limits.\nKey fields\n1) userId (Telegram user id)\n2) createdAt, updatedAt\n3) locale (optional)\n4) defaultOperation (optional)\n5) rateLimitTier (default or premium if you later add subscriptions)\n6) lastSeenAt\n\n2) jobs\nPurpose: track each conversion/merge request end-to-end.\nKey fields\n1) jobId (unique)\n2) userId, chatId\n3) type (pdftodocx, docxtopdf, pdfmerge)\n4) status (created, waitingforfiles, queued, processing, uploading, completed, failed, canceled, expired)\n5) createdAt, startedAt, finishedAt\n6) inputFiles: array of\n 1) telegramFileId (for reuse) and telegramUniqueFileId\n 2) originalName, mimeType, sizeBytes\n 3) tempStoragePathOrKey\n 4) orderIndex (for merge)\n7) outputFile\n 1) mimeType, sizeBytes\n 2) tempStoragePathOrKey\n 3) telegramFileId (after upload, for caching)\n8) options\n 1) mergeOrder (explicit order list)\n 2) outputName (optional)\n 3) conversionMode (future: fast vs accurate)\n9) error\n 1) code (validationerror, processingerror, timeout, unsupported, toolarge)\n 2) message (sanitized)\n 3) debugRef (internal correlation id)\n\n3) events (optional)\nPurpose: lightweight audit trail for debugging and support.\nKey fields\n1) eventId\n2) jobId, userId\n3) type (jobcreated, filereceived, processingstarted, processingfailed, outputsent, cleanupdone)\n4) timestamp\n5) meta (small payload)\n\nIndexes and retention\n1) jobs: index on userId + createdAt for history.\n2) jobs: index on status for operational queries.\n3) TTL index on jobs.finishedAt or jobs.createdAt (configurable retention, e.g., 24 hours to 7 days) depending on support needs.\n4) users: index on userId.\n\nIn-memory maps (supplemental, non-authoritative)\n1) per-user active job pointer for ongoing conversation.\n2) transient upload session state (e.g., expected number of PDFs for merge).\nThese should be recoverable from MongoDB so a restart does not break flows.\n\nKey flows:\nFlow A: PDF to Word (PDF -> DOCX)\n1) User starts with /start or taps Convert PDF to Word.\n2) Bot prompts: Send a PDF file.\n3) User uploads a document.\n4) Bot validates\n 1) Is it a document upload (not photo) and is it PDF.\n 2) Size within limit.\n 3) Optional: quick check that it’s not encrypted or corrupted (best effort).\n5) Bot creates a job with status queued and acknowledges with an estimated wait time.\n6) Worker downloads the file from Telegram to temporary storage.\n7) Worker runs conversion.\n8) Bot uploads DOCX result back to the user.\n9) Job marked completed; cleanup scheduled.\n\nUser-visible messaging\n1) Clear status updates: Received, Queued, Processing, Sending.\n2) If conversion quality may be imperfect (scans/complex layouts), mention this before processing and provide a fallback suggestion (e.g., try again with a different file, or in future add OCR mode).\n\nFlow B: Word to PDF (DOCX -> PDF)\n1) User selects Convert Word to PDF.\n2) Bot prompts: Send a DOCX file.\n3) Validate DOCX, size limit.\n4) Create job and enqueue.\n5) Download, convert, upload PDF.\n6) Cleanup.\n\nFlow C: Merge PDFs\n1) User selects Merge PDFs.\n2) Bot prompts: Send PDFs one by one. Provide inline buttons: Done, Cancel, Clear.\n3) User uploads multiple PDF documents.\n4) After each file, bot confirms count and shows current order.\n5) When user taps Done, bot shows an order management screen:\n 1) List files with numbers.\n 2) Controls: Move up/down for each entry, Remove entry, Add more.\n6) User confirms Merge.\n7) Bot creates job and enqueues.\n8) Worker downloads each input (if not already local), validates each PDF, merges in selected order.\n9) Bot uploads merged PDF with a sensible filename.\n10) Cleanup.\n\nFlow D: Error handling and recovery\n1) Unsupported file type\n 1) Bot explains accepted formats and asks the user to send the correct one.\n2) Too large\n 1) Bot rejects early and states the limit.\n 2) Suggest splitting or compressing before retry.\n3) Processing failure\n 1) Job marked failed with a user-friendly message.\n 2) Provide a Retry button that creates a new job referencing the same input file ids when possible.\n4) Timeout\n 1) Mark failed with suggestion to try smaller files.\n5) User cancels\n 1) Cancel button sets status canceled and triggers cleanup.\n\nFlow E: Rate limiting and abuse prevention\n1) Limit jobs per user per time window.\n2) Limit concurrent jobs per user (e.g., 1 active processing job, 1 queued).\n3) Hard caps\n 1) Max input size per file.\n 2) Max number of PDFs for merge.\n 3) Max total bytes across a merge job.\n4) If limits are hit, respond with a clear wait/try-later message.\n\nFlow F: Operational flows\n1) Startup health checks\n 1) Verify MongoDB connectivity.\n 2) Verify temp storage directory exists and is writable.\n2) Crash/restart recovery\n 1) On boot, find jobs in processing state older than a threshold and mark them failed or re-queue based on safe rules.\n 2) Clean orphaned temp files older than retention.\n3) Admin inspection\n 1) View recent failures and the sanitized reason.\n 2) Check queue depth and worker utilization.\n\nTech stack:\nRuntime and framework\n1) Node.js (ESM) single service.\n2) grammY for Telegram bot update handling, middleware, and conversational flows.\n3) Environment variables for configuration, including TELEGRAMBOTTOKEN.\n\nPersistence\n1) MongoDB for job and user metadata persistence.\n2) In-memory maps for ephemeral session state and per-process queue bookkeeping, with MongoDB as the source of truth for job status.\n\nFile handling\n1) Temporary storage in simple filesystem storage (local to the service) or object storage.\n2) Strict retention and cleanup policies to avoid accumulating user documents.\n\nDocument processing\n1) A pluggable processing layer that can call a conversion engine (library or bundled CLI tool) for:\n 1) PDF to DOCX conversion\n 2) DOCX to PDF conversion\n 3) PDF merge\n2) The processing layer must support:\n 1) timeouts per job\n 2) memory and file size safeguards\n 3) deterministic input/output paths\n 4) validation of produced files (non-empty, correct type)\n\nDeployment and configuration\n1) A generic Node.js server in the cloud.\n2) Webhook or long polling supported; webhook recommended for production if stable inbound connectivity is available.\n3) Configuration via environment variables:\n 1) TELEGRAMBOTTOKEN\n 2) MONGODBURI\n 3) TEMPSTORAGEPATH (if filesystem)\n 4) OBJECTSTORAGECONFIG (if used)\n 5) MAXFILESIZEMB, MAXMERGEFILES, MAXCONCURRENTJOBSGLOBAL, MAXCONCURRENTJOBSPERUSER\n 6) JOBRETENTIONHOURS\n\nNo additional infrastructure\n1) No additional databases beyond MongoDB.\n2) No external queues; the job queue is in-process with MongoDB-backed job records.\n\nNon-functional requirements:\nReliability\n1) Exactly-once user experience: avoid double-processing due to repeated Telegram updates by using job IDs and state checks.\n2) Safe restart behavior: recover or fail stale processing jobs deterministically.\n3) Bounded resources: hard limits on concurrency and file sizes to keep the single service stable.\n\nPerformance\n1) Concurrency caps: separate limits for download/upload and CPU-heavy conversion.\n2) Streaming where possible for Telegram file download/upload to reduce memory spikes.\n3) Fast feedback: acknowledge file receipt immediately and provide queue position or estimated wait.\n\nSecurity and privacy\n1) Validate all inputs, never trust filenames or MIME types alone.\n2) Store documents only as long as needed to process and deliver.\n3) Sanitize error messages returned to users; keep internal debug references in logs.\n4) Admin commands restricted by allowlist of Telegram user IDs.\n\nMaintainability\n1) Modular design: bot UI layer, job orchestration, processing adapters, storage adapter.\n2) Pluggable conversion engines: allow swapping conversion implementation without changing bot flows.\n3) Clear job state machine with explicit transitions.\n\nCompliance-like practices (practical)\n1) Data minimization: only store necessary metadata.\n2) Retention policy: automatic deletion with configurable retention.\n3) Transparency: a /privacy command explaining how files are handled and how long they are kept.\n\nTesting strategy\n1) Unit tests for validation, job state transitions, and merge order logic.\n2) Integration tests for Telegram file handling and end-to-end job lifecycle using test chats.\n3) Golden-file tests for conversions on a small set of known documents to detect regressions.\n\nOperational readiness\n1) Structured logs with jobId and userId.\n2) Alerting hooks are optional but logs should be actionable.\n3) Admin tooling to inspect failures and queue pressure without accessing user content.\n\nBot commands:\n• /start — Start the bot and show the main menu of document tools. (usage: /start) [general]\n• /help — Explain supported operations, limits, and how to use the bot. (usage: /help) [general]\n• /convert — Open a guided flow to choose conversion direction (PDF->DOCX or DOCX->PDF). (usage: /convert) [core]\n• /merge — Start a guided flow to collect multiple PDFs and merge them in a chosen order. (usage: /merge) [core]\n• /status — Show the status of your current or most recent job. (usage: /status) [core]\n• /cancel — Cancel the current active flow or queued/processing job when possible. (usage: /cancel) [core]\n• /limits — Display current file size limits, merge limits, and retention policy. (usage: /limits) [general]\n• /privacy — Explain how files are processed, stored temporarily, and deleted. (usage: /privacy) [general]\n• /adminhealth — Admin-only: show bot health, MongoDB connectivity, and temp storage status. (usage: /adminhealth) [admin]\n• /adminqueue — Admin-only: show queue depth, number of processing jobs, and recent throughput. (usage: /adminqueue) [admin]\n• /adminfailures — Admin-only: list recent failed jobs with sanitized reasons and debug references. (usage: /adminfailures) [admin]\n",
"planSections": {
"productGoals": "Primary user goals\n1) Convert a PDF to a Word document (DOCX) with minimal friction.\n2) Convert a Word document (DOCX) to a PDF.\n3) Merge multiple PDFs into one combined PDF in user-defined order.\n\nProduct principles\n1) Chat-first UX: minimal commands, guided prompts, and inline buttons to reduce user error.\n2) Predictable outcomes: communicate limitations (scanned PDFs, complex layouts) and handle failures gracefully.\n3) Safety and privacy: validate inputs, restrict file sizes/types, isolate processing, and auto-delete temporary files.\n4) Production operability: job tracking, retries where safe, metrics, and clear admin diagnostics.\n\nNon-goals (explicit)\n1) Full OCR and perfect layout reconstruction for scanned/complex PDFs is not guaranteed. If OCR is added later, it should be presented as an optional mode.\n2) Editing documents inside Telegram is out of scope. The bot focuses on conversion and merging.\n3) Long-term document storage for users is out of scope; the bot provides short retention for processing and delivery.",
"highLevelArchitecture": "High-level components (single Node.js service)\n1) Telegram Bot Layer (grammY)\n 1) Updates handler, command router, and conversational state management.\n 2) Inline keyboard interactions for selecting operation, confirming options, and controlling merge order.\n 3) File intake: download Telegram files after validating type and size.\n\n2) Job Orchestrator (in-process)\n 1) Creates and tracks jobs (convert or merge) and their steps.\n 2) Enforces concurrency limits per user and globally to protect CPU/memory.\n 3) Implements a simple in-process queue (no external queue) with backpressure.\n\n3) Document Processing Layer\n 1) Conversion workers that run the actual PDF <-> DOCX transformations.\n 2) PDF merge worker that combines multiple PDFs and validates the resulting file.\n 3) Sandboxed execution approach within the service process boundaries (resource limits at the application level), plus strict timeouts and file size limits.\n\n4) Storage Layer\n 1) Temporary file storage: simple filesystem storage (preferred for simplicity) or object storage if the runtime environment requires it.\n 2) Metadata persistence: MongoDB for user settings, job records, and minimal audit logs.\n 3) Automatic cleanup: TTL-based deletion of temp files and pruning of old job records.\n\n5) Observability and Admin Utilities\n 1) Structured logging with correlation IDs (jobId, userId, chatId).\n 2) Basic metrics (jobs created/completed/failed, processing duration, download/upload sizes).\n 3) Admin-only commands for health, queue depth, and recent failures.\n\nRequest lifecycle (end-to-end)\n1) User selects an operation and uploads file(s).\n2) Bot validates input, creates a job in MongoDB, stores files temporarily, and enqueues processing.\n3) Worker executes conversion/merge with timeouts and step-level status updates.\n4) Bot sends the output document back to the user, updates job status, and schedules cleanup.\n\nResilience strategy\n1) Idempotency: each job has a stable ID; repeated update deliveries do not duplicate processing.\n2) Safe retries: retry only steps that are safe (download, upload) and avoid retrying a conversion that could produce inconsistent results unless the previous attempt produced no output.\n3) Degraded mode: if processing is overloaded, the bot can accept jobs but estimate wait time and throttle per user.\n\nSecurity boundaries\n1) Treat all uploaded files as untrusted input.\n2) Validate MIME type, extension, and file signature where feasible.\n3) Enforce strict max file size, max pages (if detectable), and max number of merge inputs.\n4) Avoid storing user documents long-term; delete outputs shortly after delivery (configurable retention).",
"dataModel": "MongoDB collections (minimal, practical)\n\n1) users\nPurpose: store user preferences and usage limits.\nKey fields\n1) userId (Telegram user id)\n2) createdAt, updatedAt\n3) locale (optional)\n4) defaultOperation (optional)\n5) rateLimitTier (default or premium if you later add subscriptions)\n6) lastSeenAt\n\n2) jobs\nPurpose: track each conversion/merge request end-to-end.\nKey fields\n1) jobId (unique)\n2) userId, chatId\n3) type (pdftodocx, docxtopdf, pdfmerge)\n4) status (created, waitingforfiles, queued, processing, uploading, completed, failed, canceled, expired)\n5) createdAt, startedAt, finishedAt\n6) inputFiles: array of\n 1) telegramFileId (for reuse) and telegramUniqueFileId\n 2) originalName, mimeType, sizeBytes\n 3) tempStoragePathOrKey\n 4) orderIndex (for merge)\n7) outputFile\n 1) mimeType, sizeBytes\n 2) tempStoragePathOrKey\n 3) telegramFileId (after upload, for caching)\n8) options\n 1) mergeOrder (explicit order list)\n 2) outputName (optional)\n 3) conversionMode (future: fast vs accurate)\n9) error\n 1) code (validationerror, processingerror, timeout, unsupported, toolarge)\n 2) message (sanitized)\n 3) debugRef (internal correlation id)\n\n3) events (optional)\nPurpose: lightweight audit trail for debugging and support.\nKey fields\n1) eventId\n2) jobId, userId\n3) type (jobcreated, filereceived, processingstarted, processingfailed, outputsent, cleanupdone)\n4) timestamp\n5) meta (small payload)\n\nIndexes and retention\n1) jobs: index on userId + createdAt for history.\n2) jobs: index on status for operational queries.\n3) TTL index on jobs.finishedAt or jobs.createdAt (configurable retention, e.g., 24 hours to 7 days) depending on support needs.\n4) users: index on userId.\n\nIn-memory maps (supplemental, non-authoritative)\n1) per-user active job pointer for ongoing conversation.\n2) transient upload session state (e.g., expected number of PDFs for merge).\nThese should be recoverable from MongoDB so a restart does not break flows.",
"keyFlows": "Flow A: PDF to Word (PDF -> DOCX)\n1) User starts with /start or taps Convert PDF to Word.\n2) Bot prompts: Send a PDF file.\n3) User uploads a document.\n4) Bot validates\n 1) Is it a document upload (not photo) and is it PDF.\n 2) Size within limit.\n 3) Optional: quick check that it’s not encrypted or corrupted (best effort).\n5) Bot creates a job with status queued and acknowledges with an estimated wait time.\n6) Worker downloads the file from Telegram to temporary storage.\n7) Worker runs conversion.\n8) Bot uploads DOCX result back to the user.\n9) Job marked completed; cleanup scheduled.\n\nUser-visible messaging\n1) Clear status updates: Received, Queued, Processing, Sending.\n2) If conversion quality may be imperfect (scans/complex layouts), mention this before processing and provide a fallback suggestion (e.g., try again with a different file, or in future add OCR mode).\n\nFlow B: Word to PDF (DOCX -> PDF)\n1) User selects Convert Word to PDF.\n2) Bot prompts: Send a DOCX file.\n3) Validate DOCX, size limit.\n4) Create job and enqueue.\n5) Download, convert, upload PDF.\n6) Cleanup.\n\nFlow C: Merge PDFs\n1) User selects Merge PDFs.\n2) Bot prompts: Send PDFs one by one. Provide inline buttons: Done, Cancel, Clear.\n3) User uploads multiple PDF documents.\n4) After each file, bot confirms count and shows current order.\n5) When user taps Done, bot shows an order management screen:\n 1) List files with numbers.\n 2) Controls: Move up/down for each entry, Remove entry, Add more.\n6) User confirms Merge.\n7) Bot creates job and enqueues.\n8) Worker downloads each input (if not already local), validates each PDF, merges in selected order.\n9) Bot uploads merged PDF with a sensible filename.\n10) Cleanup.\n\nFlow D: Error handling and recovery\n1) Unsupported file type\n 1) Bot explains accepted formats and asks the user to send the correct one.\n2) Too large\n 1) Bot rejects early and states the limit.\n 2) Suggest splitting or compressing before retry.\n3) Processing failure\n 1) Job marked failed with a user-friendly message.\n 2) Provide a Retry button that creates a new job referencing the same input file ids when possible.\n4) Timeout\n 1) Mark failed with suggestion to try smaller files.\n5) User cancels\n 1) Cancel button sets status canceled and triggers cleanup.\n\nFlow E: Rate limiting and abuse prevention\n1) Limit jobs per user per time window.\n2) Limit concurrent jobs per user (e.g., 1 active processing job, 1 queued).\n3) Hard caps\n 1) Max input size per file.\n 2) Max number of PDFs for merge.\n 3) Max total bytes across a merge job.\n4) If limits are hit, respond with a clear wait/try-later message.\n\nFlow F: Operational flows\n1) Startup health checks\n 1) Verify MongoDB connectivity.\n 2) Verify temp storage directory exists and is writable.\n2) Crash/restart recovery\n 1) On boot, find jobs in processing state older than a threshold and mark them failed or re-queue based on safe rules.\n 2) Clean orphaned temp files older than retention.\n3) Admin inspection\n 1) View recent failures and the sanitized reason.\n 2) Check queue depth and worker utilization.",
"techStack": "Runtime and framework\n1) Node.js (ESM) single service.\n2) grammY for Telegram bot update handling, middleware, and conversational flows.\n3) Environment variables for configuration, including TELEGRAMBOTTOKEN.\n\nPersistence\n1) MongoDB for job and user metadata persistence.\n2) In-memory maps for ephemeral session state and per-process queue bookkeeping, with MongoDB as the source of truth for job status.\n\nFile handling\n1) Temporary storage in simple filesystem storage (local to the service) or object storage.\n2) Strict retention and cleanup policies to avoid accumulating user documents.\n\nDocument processing\n1) A pluggable processing layer that can call a conversion engine (library or bundled CLI tool) for:\n 1) PDF to DOCX conversion\n 2) DOCX to PDF conversion\n 3) PDF merge\n2) The processing layer must support:\n 1) timeouts per job\n 2) memory and file size safeguards\n 3) deterministic input/output paths\n 4) validation of produced files (non-empty, correct type)\n\nDeployment and configuration\n1) A generic Node.js server in the cloud.\n2) Webhook or long polling supported; webhook recommended for production if stable inbound connectivity is available.\n3) Configuration via environment variables:\n 1) TELEGRAMBOTTOKEN\n 2) MONGODBURI\n 3) TEMPSTORAGEPATH (if filesystem)\n 4) OBJECTSTORAGECONFIG (if used)\n 5) MAXFILESIZEMB, MAXMERGEFILES, MAXCONCURRENTJOBSGLOBAL, MAXCONCURRENTJOBSPERUSER\n 6) JOBRETENTIONHOURS\n\nNo additional infrastructure\n1) No additional databases beyond MongoDB.\n2) No external queues; the job queue is in-process with MongoDB-backed job records.",
"nonFunctional": "Reliability\n1) Exactly-once user experience: avoid double-processing due to repeated Telegram updates by using job IDs and state checks.\n2) Safe restart behavior: recover or fail stale processing jobs deterministically.\n3) Bounded resources: hard limits on concurrency and file sizes to keep the single service stable.\n\nPerformance\n1) Concurrency caps: separate limits for download/upload and CPU-heavy conversion.\n2) Streaming where possible for Telegram file download/upload to reduce memory spikes.\n3) Fast feedback: acknowledge file receipt immediately and provide queue position or estimated wait.\n\nSecurity and privacy\n1) Validate all inputs, never trust filenames or MIME types alone.\n2) Store documents only as long as needed to process and deliver.\n3) Sanitize error messages returned to users; keep internal debug references in logs.\n4) Admin commands restricted by allowlist of Telegram user IDs.\n\nMaintainability\n1) Modular design: bot UI layer, job orchestration, processing adapters, storage adapter.\n2) Pluggable conversion engines: allow swapping conversion implementation without changing bot flows.\n3) Clear job state machine with explicit transitions.\n\nCompliance-like practices (practical)\n1) Data minimization: only store necessary metadata.\n2) Retention policy: automatic deletion with configurable retention.\n3) Transparency: a /privacy command explaining how files are handled and how long they are kept.\n\nTesting strategy\n1) Unit tests for validation, job state transitions, and merge order logic.\n2) Integration tests for Telegram file handling and end-to-end job lifecycle using test chats.\n3) Golden-file tests for conversions on a small set of known documents to detect regressions.\n\nOperational readiness\n1) Structured logs with jobId and userId.\n2) Alerting hooks are optional but logs should be actionable.\n3) Admin tooling to inspect failures and queue pressure without accessing user content."
},
"balanceCentsRemaining": 2,
"billing": {
"ok": true,
"charged": 42,
"remaining": 2,
"chargedCents": 42,
"remainingCents": 2,
"currency": "USD",
"baseUsd": 0.208478,
"markupUsd": 0.208478,
"platformFeeUsd": 0,
"totalUsd": 0.416956
},
"title": "Telegram Document Tools Bot"
}
},
"envVarDocs": [
{
"key": "TELEGRAM_BOT_TOKEN",
"title": "Telegram Bot Token",
"description": "Token for your Telegram bot from BotFather.",
"usage": "Used by grammY to connect to Telegram.",
"howToGet": "Create a bot with BotFather in Telegram and copy the token.",
"example": "123456:ABCDEF...",
"isSecret": true,
"required": true
},
{
"key": "MONGODB_URI",
"title": "MongoDB Connection String",
"description": "MongoDB connection string for long-term memory storage.",
"usage": "If present, conversation turns are stored in memory_messages; otherwise in-memory fallback is used.",
"howToGet": "Use MongoDB Atlas or another Mongo provider to create a database and user.",
"example": "mongodb+srv://user:pass@cluster/dbname",
"isSecret": true,
"required": false
},
{
"key": "COOKMYBOTS_AI_ENDPOINT",
"title": "CookMyBots AI Endpoint",
"description": "Base URL for the CookMyBots AI gateway (must be a base URL ending with /api/ai).",
"usage": "The bot calls POST {endpoint}/chat for intent parsing and friendly replies.",
"howToGet": "Provided by CookMyBots.",
"example": "https://api.cookmybots.com/api/ai",
"isSecret": false,
"required": true
},
{
"key": "COOKMYBOTS_AI_KEY",
"title": "CookMyBots AI Key",
"description": "API key used to authenticate requests to the CookMyBots AI gateway.",
"usage": "Sent as Authorization: Bearer <key> for AI calls.",
"howToGet": "Provided by CookMyBots.",
"example": "cmb_ai_...",
"isSecret": true,
"required": true
},
{
"key": "AI_TIMEOUT_MS",
"title": "AI Timeout",
"description": "Timeout for AI gateway requests in milliseconds.",
"usage": "Controls fetch AbortController timeout for AI calls.",
"howToGet": "Optional setting.",
"example": "600000",
"isSecret": false,
"required": false
},
{
"key": "AI_MAX_RETRIES",
"title": "AI Retry Count",
"description": "How many times to retry AI calls on failure.",
"usage": "Used by src/lib/ai.js retry loop.",
"howToGet": "Optional setting.",
"example": "2",
"isSecret": false,
"required": false
},
{
"key": "CONCURRENCY",
"title": "Telegram Update Concurrency",
"description": "Number of updates processed concurrently by @grammyjs/runner.",
"usage": "Passed to run(bot,{concurrency}).",
"howToGet": "Optional setting.",
"example": "20",
"isSecret": false,
"required": false
},
{
"key": "MAX_FILE_MB",
"title": "Max File Size",
"description": "Maximum allowed upload size per document (in MB).",
"usage": "Validated against Telegram-reported size and enforced during download.",
"howToGet": "Optional setting.",
"example": "20",
"isSecret": false,
"required": false
},
{
"key": "ADMIN_TELEGRAM_USER_ID",
"title": "Admin Telegram User ID",
"description": "If set, enables /admin_stats for that user only.",
"usage": "Compared to ctx.from.id to authorize admin command.",
"howToGet": "Find your Telegram numeric user id (various bots/tools can show it).",
"example": "123456789",
"isSecret": false,
"required": false
}
],
"commandDocs": [
{
"command": "/start",
"description": "Explains what the bot can do and how to use it.",
"usage": "/start",
"examples": [
"User: /start → Bot: instructions for PDF to Word, Word to PDF, and merging PDFs"
],
"notes": "Send files as documents. Large files may be refused based on MAX_FILE_MB."
},
{
"command": "/help",
"description": "Shows all public commands and example usage.",
"usage": "/help",
"examples": [
"User: /help → Bot: command list and examples"
],
"notes": "You can also just type things like “pdf to word” or “merge pdfs”."
},
{
"command": "/status",
"description": "Shows the current selected mode, queued PDFs count, and last action.",
"usage": "/status",
"examples": [
"User: /status → Bot: Mode: merge_pdfs, Queued PDFs: 3, Last: merge_added"
],
"notes": "Useful when you’re in the middle of merging."
},
{
"command": "/reset",
"description": "Clears your active workflow state and clears your stored memory.",
"usage": "/reset",
"examples": [
"User: /reset → Bot: Reset done. Tell me: pdf to word, word to pdf, or merge pdfs."
],
"notes": "If MongoDB is configured, this also deletes your memory records."
}
],
"title": "Telegram Document Tools Bot"
}