Commit Graph

164 Commits

Author SHA1 Message Date
kappa
0b24cbdad0 feat: add dashboard API endpoints
- POST /api/auth/telegram - Telegram Login Widget verification
- GET /api/dashboard - Dashboard stats (servers, domains, deposit)
- GET /api/servers - User's server list
- GET /api/domains - User's domain list
- GET /api/deposit/transactions - Transaction history
- POST /api/server/action - Server start/stop/reboot

CORS enabled for my.anvil.it.com

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 19:08:54 +09:00
kappa
ec2d4da517 feat: add server page link to /server command
- Show "신청 가능한 서버보기" link when no servers
- Show link at bottom of server list

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:59:21 +09:00
kappa
6417dfec13 fix: remove remaining server recommendation references
- Remove start_consultation instruction from system prompt
- Clean ManageServerArgsSchema (remove recommend/consultation actions)
- Update SERVER_ACTION constant (remove RECOMMEND, add REBOOT/RENAME)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:51:13 +09:00
kappa
a774235244 refactor: fix unused imports after server recommendation removal
- Remove unused sendMessage import from openai-service.ts
- Mark chatIdStr as unused with underscore prefix

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:37:58 +09:00
kappa
7e3b4a10ab refactor: drop server_sessions table
Add migration to remove server consultation sessions table.
Update schema.sql to remove table definition.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:36:44 +09:00
kappa
1935d8bb5b refactor: update /server command to remove recommendation guide
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:35:36 +09:00
kappa
30b7a85ab0 refactor: remove SERVER_CONSULTATION_STATUS from constants
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:34:39 +09:00
kappa
648df55a0b refactor: remove ServerSession types from types.ts
Removed:
- ServerSessionStatus type
- ServerSession interface
- Recommendation-related fields from ManageServerArgs (tech_stack, expected_users, use_case, etc.)
- Updated ManageServerArgs actions to server management only (order, start, stop, reboot, delete, list, info, images, rename)

Commented out (temporary):
- ServerSessionManager class in session-manager.ts
- Server consultation session cleanup code in server-tool.ts (2 locations)
- Server order confirmation handler in api/chat.ts

These commented sections will be fully removed in subsequent commits when server-agent and related code are removed.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:33:39 +09:00
kappa
98002473f9 refactor: remove recommendation actions from server-tool
Removed:
- start_consultation, continue_consultation, cancel_consultation, recommend actions
- getRecommendationData(), formatRecommendations()
- CDN cache hit rate estimation (CDN_CACHE_HIT_RATES, estimateCdnCacheHitRate)
- Language detection (detectLanguage)
- callCloudOrchestratorApi() function
- isErrorResult() type guard
- Recommendation-related parameters (tech_stack, expected_users, use_case, traffic_pattern, region_preference, budget_limit, lang, message)
- RecommendResponse type import
- formatTrafficInfo import

Retained:
- order, list, info, delete, images, start, stop, reboot, rename actions
- callProvisionAPI() for provision operations
- Server management core functionality

File size reduced from 1484 to 1057 lines (427 lines removed).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:30:08 +09:00
kappa
7d43db3054 refactor: delete server-agent.ts (905 lines)
Remove server recommendation consultation system:
- 30-year expert AI persona
- Session-based information gathering
- Brave Search / Context7 tool integration
- Automatic spec inference

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:25:36 +09:00
kappa
6e3e8d8abb refactor: remove server order confirmation from message-handler
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:12:45 +09:00
kappa
fd20282f4e refactor: remove server consultation session routing from openai-service
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 18:11:13 +09:00
kappa
8a25fa02da style: add emojis to /security command
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:35 +09:00
kappa
f8d195325c feat: migrate existing message_buffer data to conversation tables
Migrated 2 users:
- 7265981403: 18 messages
- 821596605: 46 messages

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:35 +09:00
kappa
5ec224b53f feat: add migration script for existing conversations
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:35 +09:00
kappa
23785c9e5f feat: add conversation archive to daily cron
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>
2026-02-05 12:47:35 +09:00
kappa
e764dd683e feat: add /history and /search commands
- 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>
2026-02-05 12:47:35 +09:00
kappa
92ddc239ef feat: save messages to new conversation storage
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>
2026-02-05 12:47:35 +09:00
kappa
1ecbf19f66 feat: integrate smart context in AI response generation
- 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>
2026-02-05 12:47:35 +09:00
kappa
a14e640db9 feat: implement archive service for old conversations
- 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>
2026-02-05 12:47:35 +09:00
kappa
2a84f12d46 feat: implement conversation storage service
- ensureConversationTable(): 사용자별 동적 테이블 생성/확인
- saveConversationMessage(): 메시지 저장 + 메타 테이블 업데이트
- getRecentConversations(): 최근 N개 메시지 조회 (시간순 정렬)
- searchConversations(): 키워드 검색 (LIKE OR 조건)
- extractKeywords(): 불용어 제거 키워드 추출 (최대 5개)
- getSmartContext(): 최근 20개 + 키워드 매칭 10개 (중복 제거)
- getConversationStats(): 통계 조회 (메시지 수, 첫/마지막 메시지 시간)
- getConversationHistory(): 히스토리 조회 (페이지네이션)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:35 +09:00
kappa
a6d1c4ecd4 feat: add conversation_tables migration
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>
2026-02-05 12:47:35 +09:00
kappa
123b145bf9 feat: add conversation storage types
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>
2026-02-05 12:47:35 +09:00
kappa
02b18301a1 fix: resolve TypeScript errors after SessionManager refactoring
- Remove unused import types (*SessionStatus, OpenAIMessage)
- Replace deprecated session functions with SessionManager API
- Prefix unused base class parameters with underscore
- Update all session management calls across agents and tools

Files affected:
- src/agents/*.ts (removed unused imports)
- src/utils/session-manager.ts (unused param prefixes)
- src/tools/server-tool.ts (SessionManager migration)
- src/tools/troubleshoot-tool.ts (SessionManager migration)
- src/routes/api/chat.ts (SessionManager migration)
- src/routes/handlers/message-handler.ts (SessionManager migration)

Verification:
- TypeScript: compiles without errors
- Tests: 223 passed (10 pre-existing failures)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:35 +09:00
kappa
edf1bbc9a2 refactor: apply SessionManager to all agents
- 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>
2026-02-05 12:47:35 +09:00
kappa
ffd310c903 feat: add OpenAI types and AI caller utility
- 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>
2026-02-05 12:47:34 +09:00
kappa
c8e1362375 feat: add centralized agent configuration
- Create src/constants/agent-config.ts
- Consolidate TTL, MAX_MESSAGES, AI settings
- Add type-safe getSessionConfig() helper

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:34 +09:00
kappa
1160719a78 docs: add SessionManager usage guide
- 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>
2026-02-05 12:47:34 +09:00
kappa
36fdc4fe3d feat: add SessionManager generic class for agent sessions
- 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>
2026-02-05 12:47:34 +09:00
kappa
c6345a8f2f chore: clean up unused code and fix test imports
- 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>
2026-02-05 12:47:34 +09:00
kappa
de36978de4 refactor: unify server-agent to new pattern
- 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>
2026-02-05 12:47:34 +09:00
kappa
5d8150e67c refactor: migrate troubleshoot-agent from KV to D1
- 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>
2026-02-05 12:47:34 +09:00
kappa
2bd9bc4c2b feat: complete agent refactoring integration
- 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>
2026-02-05 12:47:34 +09:00
kappa
f5c38ad909 refactor: move deposit-agent to agents/ and add session support
- Move deposit-agent.ts to src/agents/
- Add D1 session CRUD functions (getDepositSession, saveDepositSession, etc.)
- Add Deposit Expert AI with function calling
- Add processDepositConsultation handler for session-based flow
- Add deposit_sessions table migration (006_add_deposit_sessions.sql)
- Update import paths in deposit-tool.ts
- Add DEPOSIT_BANK_* environment variables to Env interface

Session flow: collecting_amount → collecting_name → confirming → completed
Smart parsing: "홍길동 5만원" → Go directly to confirming

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:34 +09:00
kappa
cb2bd48ad6 refactor: convert domain-tool to agent trigger
- 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>
2026-02-05 12:47:34 +09:00
kappa
d069e84efd feat: add domain session routing to openai-service
- 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>
2026-02-05 12:47:34 +09:00
kappa
f9f577f25c feat: implement processDomainConsultation main handler
- 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>
2026-02-05 12:47:34 +09:00
kappa
160569bf8c feat: add domain tool execution dispatcher
- 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>
2026-02-05 12:47:34 +09:00
kappa
69aac96daa feat: add domain agent AI call functions
- Add domain expert system prompt
- Add domain tools for function calling
- Add callDomainExpertAI function

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:34 +09:00
kappa
e463a88803 feat: create domain-agent basic structure
- Add D1 session CRUD functions (getDomainSession, saveDomainSession, deleteDomainSession)
- Add session helper functions (createDomainSession, isSessionExpired, addMessageToSession)
- Add placeholder for main consultation handler (processDomainConsultation)
- Fix server-agent import paths in server-tool.ts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:34 +09:00
kappa
676f3866e8 feat: add DomainSession and DepositSession types
- Add type definitions for domain and deposit agent sessions
- Follow existing ServerSession pattern

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:34 +09:00
kappa
8f16de40cc refactor: move troubleshoot-agent to agents directory
- Move troubleshoot-agent.ts to src/agents/
- Update import paths in dependent files

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:34 +09:00
kappa
4642c1ff94 refactor: move server-agent to agents directory
- 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>
2026-02-05 12:47:34 +09:00
kappa
f3596fb509 chore: add domain/deposit agent session tables migration
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 12:47:34 +09:00
kaffa
356eb6ccc8 Add Gitea Actions CI workflow 2026-02-03 11:39:08 +09:00
kaffa
94d615a3bf Add MIT LICENSE 2026-02-03 11:20:55 +09:00
kappa
619e952520 docs: restructure CLAUDE.md for better readability
- Add numbered sections (1-9) for clear navigation
- Remove verbose agent descriptions, keep concise
- Consolidate duplicate content
- Improve formatting consistency

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 23:47:20 +09:00
kappa
2b1bc6a371 feat: improve server management and refund display
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>
2026-01-30 05:30:59 +09:00
kappa
18e7d3ca6e test: add comprehensive unit tests for utils and security
- 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>
2026-01-29 11:38:49 +09:00
kappa
fbe696b88c refactor: complete P0-P1 improvements
Constants migration:
- server-agent.ts: SERVER_CONSULTATION_STATUS, LANGUAGE_CODE
- troubleshoot-agent.ts: TROUBLESHOOT_STATUS
- notification.ts: NOTIFICATION_TYPE

API improvements:
- search-tool.ts: Zod schema validation for Brave/Context7 APIs
- api-helper.ts: Centralized API call utility with retry/timeout

Testing:
- kv-cache.test.ts: 38 test cases for cache abstraction

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 11:02:27 +09:00