Add archiveOldConversations to the daily cron job (UTC 15:00 / KST 00:00).
Archives conversations older than 180 days by:
- Batching user messages into summaries (100 messages each)
- Using OpenAI to generate context-preserving summaries
- Deleting archived messages to reduce database size
Uses dynamic import for bundle size optimization and try-catch
to prevent errors from affecting other cron tasks.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add /history [N] command to view recent conversation history
- Default 20 messages, max 100
- Shows date/time, role (user/bot), and message preview
- Add /search <keyword> command to search conversations
- Uses extractKeywords() for smart keyword extraction
- Shows up to 15 results with date and content preview
- Update /stats command to use new conversation-storage service
- Shows total message count, first/last message dates
- Shows archived summary count
- Links to /history and /search commands
- Update /start and /help commands to include new commands
- Import conversation-storage functions
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Integrate new conversation-storage.ts system while maintaining backward
compatibility with existing message_buffer system:
- Import saveConversationMessage from conversation-storage.ts
- Save user messages to both new system (role: 'user') and old buffer
- Save assistant responses to both new system (role: 'assistant') and old buffer
- Preserve existing functionality during migration period
Changes:
- Add saveConversationMessage import
- Call saveConversationMessage before addToBuffer for user messages
- Call saveConversationMessage before addToBuffer for bot responses
- Updated step numbering in comments (1-7)
Note: Old buffer system will be removed after migration is complete.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add import for getSmartContext from conversation-storage service
- Modify generateAIResponse to use smart context (recent 20 + keyword-related 10 messages)
- Keep existing getAllSummaries for archived profile system
- Use smart context (max 30 messages) when available, fallback to legacy buffer (10 messages)
- Maintain backward compatibility with existing conversation system
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add archive-service.ts with 3 main functions:
1. generateArchiveSummary(): AI-powered conversation summarization
- Uses OpenAI for intelligent summaries
- Fallback to keyword-based simple summaries
- Format: [YYYY-MM-DD ~ YYYY-MM-DD archive] summary
2. archiveUserConversations(): Archive conversations per user
- Query messages older than 180 days (user messages only)
- Create summaries in batches of 100 messages
- Save to summaries table with incremented generation
- Delete original messages and update meta table
3. archiveOldConversations(): Archive all users (Cron job)
- Iterate through conversation_tables
- Call archiveUserConversations for each user
- Return ArchiveResult with stats
- Constants: ARCHIVE_DAYS=180, BATCH_SIZE=100
- Error handling: Comprehensive logging with structured errors
- Type safety: All functions use strict TypeScript types
- No breaking changes: Works with existing conversation storage
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- ensureConversationTable(): 사용자별 동적 테이블 생성/확인
- saveConversationMessage(): 메시지 저장 + 메타 테이블 업데이트
- getRecentConversations(): 최근 N개 메시지 조회 (시간순 정렬)
- searchConversations(): 키워드 검색 (LIKE OR 조건)
- extractKeywords(): 불용어 제거 키워드 추출 (최대 5개)
- getSmartContext(): 최근 20개 + 키워드 매칭 10개 (중복 제거)
- getConversationStats(): 통계 조회 (메시지 수, 첫/마지막 메시지 시간)
- getConversationHistory(): 히스토리 조회 (페이지네이션)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add migration for conversation_tables to support dynamic per-user conversation storage.
- CREATE TABLE conversation_tables with telegram_id, table_name, message_count
- Add indexes on last_message_at and message_count for query performance
- Tested successfully on local D1 database
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add type definitions for the new conversation storage system:
- ConversationMessage: Individual message structure with tool calls/results
- ConversationTableMeta: Metadata for per-user conversation tables
- ConversationStats: Aggregated statistics per user
- ArchiveResult: Results from archiving operations
These types will be used by the upcoming conversation storage implementation
that replaces the message_buffer + summaries system with dynamic per-user
tables and automatic archiving.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- domain-agent: use DomainSessionManager (handles target_domain)
- deposit-agent: use SessionManager<DepositSession>
- troubleshoot-agent: use SessionManager<TroubleshootSession>
- server-agent: use ServerSessionManager (handles last_recommendation)
- Remove ~760 lines of duplicated session CRUD code
- Use centralized constants from agent-config.ts
- Import OpenAI types from types.ts instead of local definitions
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Consolidate OpenAI types to types.ts
- Create reusable callOpenAI() function
- Add tool call parsing and result handling
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Comprehensive API documentation
- Migration examples (before/after)
- Specialized manager patterns
- Next steps for agent refactoring
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Create reusable SessionManager<T> with CRUD operations
- Support for session expiry, message limits
- Specialized managers for Domain and Server agents
- Reduce code duplication across 4 agents
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Remove unused config in commands.ts
- Remove deprecated formatDepositResult function in deposit-tool.ts
- Remove unused type imports in deposit-tool.ts
- Fix import path in deposit-agent.test.ts (src/deposit-agent → src/agents/deposit-agent)
This is a cleanup commit following the agent pattern unification work.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Change field names to snake_case (user_id, collected_info, last_recommendation, created_at, updated_at, expires_at)
- Extract system prompts to constants (SERVER_EXPERT_PROMPT, SERVER_REVIEW_PROMPT)
- Add __PASSTHROUGH__/__SESSION_END__ marker support
- Change handler signature to match other agents (db, userId, userMessage, env, options)
- Add helper functions for consistency (createServerSession, isSessionExpired, addMessageToSession, hasServerSession)
- Update saveSe rverSession signature to not need userId separately
- Rename tools constant from serverExpertTools to serverExpertTools (camelCase)
- Change AI call parameter order for consistency
- Add performance logging
- Update openai-service.ts routing to use hasServerSession
- Update server-tool.ts to use new session creation helpers
- Update message-handler.ts and api/chat.ts field references
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Create troubleshoot_sessions table in D1
- Replace KV session storage with D1
- Unify field names to snake_case (user_id, collected_info, created_at, updated_at, expires_at)
- Add __PASSTHROUGH__/__SESSION_END__ marker support
- Change handler signature to match domain/deposit pattern
- Extract system prompt to constant TROUBLESHOOT_EXPERT_PROMPT
- Add hasTroubleshootSession() for routing
- Update openai-service.ts to use new D1-based functions
- Update troubleshoot-tool.ts to use D1 instead of KV
- Add TroubleshootSessionStatus type
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add deposit session routing to openai-service.ts
- Convert deposit-tool to agent trigger (delegate to deposit-agent)
- Update CLAUDE.md with new agent architecture
Changes:
- openai-service.ts: Import and check hasDepositSession, route to processDepositConsultation
- deposit-tool.ts: Convert action → natural language → delegate to Deposit Agent
- CLAUDE.md: Update Core Services, Function Calling Tools, Data Layer, Deposit System sections
All tests passing (192/195), dev server starts successfully.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Modify executeManageDomain to delegate to domain agent
- Add buildDomainMessage helper for action-to-message conversion
- Keep internal functions for agent tool execution
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Import domain agent functions
- Add domain session check before main AI processing
- Route to domain agent when session exists
- Handle __PASSTHROUGH__ for non-domain messages
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add full conversation flow with session management
- Handle tool call execution
- Support __PASSTHROUGH__ and __SESSION_END__ markers
- Add hasDomainSession helper for routing
- Export executeDomainAction from domain-tool.ts
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add executeDomainToolCall function
- Integrate with existing domain-tool.ts functions
- Map AI tool calls to domain actions
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add domain expert system prompt
- Add domain tools for function calling
- Add callDomainExpertAI function
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add type definitions for domain and deposit agent sessions
- Follow existing ServerSession pattern
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Create src/agents/ directory for agent modules
- Move server-agent.ts to new location
- Update import paths in all dependent files:
- openai-service.ts
- tools/server-tool.ts
- routes/handlers/message-handler.ts
- routes/api/chat.ts
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Server Management:
- Fix /server command API auth (query param instead of header)
- Show server specs (vCPU/RAM/Bandwidth) in /server list
- Prevent AI from refusing server deletion based on expiration date
- Add explicit instructions in tool description and system prompt
Refund Display:
- Show before/after balance in server deletion refund message
- Format: 환불 전 잔액 → 환불 금액 → 환불 후 잔액
Other Changes:
- Add stopped status migration for server orders
- Clean up callback handler (remove deprecated code)
- Update constants and pattern utilities
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add security.test.ts: 36 tests for webhook validation, rate limiting
- Add circuit-breaker.test.ts: 31 tests for state transitions
- Add retry.test.ts: 25 tests for exponential backoff
- Add api-helper.test.ts: 25 tests for API abstraction
- Add optimistic-lock.test.ts: 11 tests for concurrency control
- Add summary-service.test.ts: 29 tests for profile system
Total: 157 new test cases (222 passing overall)
- Fix setup.ts D1 schema initialization for Miniflare
- Update vitest.config.ts to exclude demo files
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Create Hono router in api.ts
- Convert 6 API endpoints to Hono format:
- GET /api/deposit/balance
- POST /api/deposit/deduct
- POST /api/test
- POST /api/chat
- POST /api/contact
- GET /api/metrics
- Use Hono CORS middleware for /contact
- Remove manual handleApiRequest and handleContactPreflight
- Integrate with main app via app.route('/api', apiRouter)
Benefits:
- Cleaner declarative routing (44 insertions, 48 deletions)
- Built-in CORS middleware
- Better code organization
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Replace stub implementations with actual API calls
- POST /api/provision/orders/{order_id}/start
- POST /api/provision/orders/{order_id}/stop
- Add proper validation, logging, and error handling
- Follow existing code patterns (callProvisionAPI, __DIRECT__)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
P2-1: Tool selection fallback optimization
- Return only utility tools when no patterns match
- Reduces token usage by ~80% in fallback cases
P2-2: Minimum deposit amount validation
- Add MIN_DEPOSIT_AMOUNT = 1,000원
- Prevents spam with tiny deposits
P2-3: Standardize logging
- Replace console.log/error with structured logger
- bank-sms-parser.ts and security.ts
P2-4: Nameserver format validation
- Add validateNameservers() function
- Check minimum 2 NS, valid hostname format
- Clear error messages in Korean
P2-5: Optimistic lock error context
- Return specific error for version conflicts
- User-friendly message: "동시 요청으로 처리가 지연됨"
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
P1-1: Callback query error handling
- Add try-catch around domain registration and server order
- Send user-friendly error messages on failure
- Use answerCallbackQuery to acknowledge button clicks
- Add structured logging with createLogger
P1-2: Queue DLQ monitoring
- Add admin notification when server provisioning fails
- Update order status to 'failed' in database
- Include detailed context in notifications
- Apply rate limiting (1 notification per hour)
P1-3: Email handler error recovery
- Add admin notification when SMS parsing fails
- Include email preview in notifications
- Mask email addresses for privacy
- Add structured logging with emailLogger
Also add 'failed' status to ServerOrder type.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>