@xopcai/xopc 0.0.30 → 0.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/extensions/telegram/xopc.extension.json +1 -1
  2. package/dist/gateway/static/root/assets/agents-3u63Fw2Y.js +216 -0
  3. package/dist/gateway/static/root/assets/agents-3u63Fw2Y.js.map +1 -0
  4. package/dist/gateway/static/root/assets/{apps-page-CTChHQAu.js → apps-page-CWegY6Kp.js} +2 -2
  5. package/dist/gateway/static/root/assets/{apps-page-CTChHQAu.js.map → apps-page-CWegY6Kp.js.map} +1 -1
  6. package/dist/gateway/static/root/assets/channels-settings-CiyeXcTK.js +9 -0
  7. package/dist/gateway/static/root/assets/channels-settings-CiyeXcTK.js.map +1 -0
  8. package/dist/gateway/static/root/assets/cron-api-_j_79Zf5.js +3 -0
  9. package/dist/gateway/static/root/assets/cron-api-_j_79Zf5.js.map +1 -0
  10. package/dist/gateway/static/root/assets/cron-page-S86YNTtI.js +2 -0
  11. package/dist/gateway/static/root/assets/cron-page-S86YNTtI.js.map +1 -0
  12. package/dist/gateway/static/root/assets/dist-D0jxbvuz.js +2 -0
  13. package/dist/gateway/static/root/assets/{dist-UWGUW3x8.js.map → dist-D0jxbvuz.js.map} +1 -1
  14. package/dist/gateway/static/root/assets/{extension-debug-page-BwB4a4cK.js → extension-debug-page-DB630cW8.js} +2 -2
  15. package/dist/gateway/static/root/assets/{extension-debug-page-BwB4a4cK.js.map → extension-debug-page-DB630cW8.js.map} +1 -1
  16. package/dist/gateway/static/root/assets/{extension-page-CSWu2PHZ.js → extension-page-CnoPUBul.js} +2 -2
  17. package/dist/gateway/static/root/assets/{extension-page-CSWu2PHZ.js.map → extension-page-CnoPUBul.js.map} +1 -1
  18. package/dist/gateway/static/root/assets/{extension-settings-page-B12K2a13.js → extension-settings-page-BsiOkvBe.js} +2 -2
  19. package/dist/gateway/static/root/assets/{extension-settings-page-B12K2a13.js.map → extension-settings-page-BsiOkvBe.js.map} +1 -1
  20. package/dist/gateway/static/root/assets/{index-D0pFZ0OE.js → index-DHLmAIQl.js} +81 -81
  21. package/dist/gateway/static/root/assets/{index-D0pFZ0OE.js.map → index-DHLmAIQl.js.map} +1 -1
  22. package/dist/gateway/static/root/assets/index-DoPwy4aU.css +1 -0
  23. package/dist/gateway/static/root/assets/logs-page-Bndhenn2.js +2 -0
  24. package/dist/gateway/static/root/assets/logs-page-Bndhenn2.js.map +1 -0
  25. package/dist/gateway/static/root/assets/sessions-page-Q201-_lP.js +2 -0
  26. package/dist/gateway/static/root/assets/{sessions-page-DJkuWpOT.js.map → sessions-page-Q201-_lP.js.map} +1 -1
  27. package/dist/gateway/static/root/assets/settings-page-Cw75fpc6.js +2 -0
  28. package/dist/gateway/static/root/assets/settings-page-Cw75fpc6.js.map +1 -0
  29. package/dist/gateway/static/root/assets/skills-page-CVwEzD_J.js +3 -0
  30. package/dist/gateway/static/root/assets/skills-page-CVwEzD_J.js.map +1 -0
  31. package/dist/gateway/static/root/index.html +2 -2
  32. package/dist/package.js +1 -1
  33. package/dist/src/agent/orchestration/agent-orchestrator.js +1 -1
  34. package/dist/src/agent/service/process-direct-streaming.js +12 -1
  35. package/dist/src/agent/service/process-direct-streaming.js.map +1 -1
  36. package/dist/src/agent/service.d.ts +4 -0
  37. package/dist/src/agent/service.js +7 -1
  38. package/dist/src/agent/service.js.map +1 -1
  39. package/dist/src/agent/skills/marketplace/resolve-adapter.js +1 -1
  40. package/dist/src/agent/skills/marketplace/resolve-adapter.js.map +1 -1
  41. package/dist/src/config/schema.js +1 -0
  42. package/dist/src/config/schema.js.map +1 -1
  43. package/dist/src/cron/validation.js +1 -1
  44. package/dist/src/cron/validation.js.map +1 -1
  45. package/dist/src/gateway/hono/routes/sessions.js +124 -2
  46. package/dist/src/gateway/hono/routes/sessions.js.map +1 -1
  47. package/dist/src/gateway/hono/sse.js +9 -2
  48. package/dist/src/gateway/hono/sse.js.map +1 -1
  49. package/dist/src/gateway/service/run-gateway-agent.d.ts +1 -0
  50. package/dist/src/gateway/service/run-gateway-agent.js +18 -10
  51. package/dist/src/gateway/service/run-gateway-agent.js.map +1 -1
  52. package/dist/src/gateway/service.d.ts +23 -1
  53. package/dist/src/gateway/service.js +47 -3
  54. package/dist/src/gateway/service.js.map +1 -1
  55. package/dist/src/session/abort-cutoff.d.ts +6 -0
  56. package/dist/src/session/abort-cutoff.js +10 -0
  57. package/dist/src/session/abort-cutoff.js.map +1 -0
  58. package/dist/src/session/compaction-checkpoints.d.ts +8 -0
  59. package/dist/src/session/compaction-checkpoints.js +21 -0
  60. package/dist/src/session/compaction-checkpoints.js.map +1 -0
  61. package/dist/src/session/index.d.ts +8 -1
  62. package/dist/src/session/index.js +7 -1
  63. package/dist/src/session/manager.d.ts +26 -1
  64. package/dist/src/session/manager.js +39 -2
  65. package/dist/src/session/manager.js.map +1 -1
  66. package/dist/src/session/patch-metadata.d.ts +12 -0
  67. package/dist/src/session/patch-metadata.js +23 -0
  68. package/dist/src/session/patch-metadata.js.map +1 -0
  69. package/dist/src/session/search-index.d.ts +2 -0
  70. package/dist/src/session/search-index.js +30 -2
  71. package/dist/src/session/search-index.js.map +1 -1
  72. package/dist/src/session/session-context-for-llm.d.ts +32 -0
  73. package/dist/src/session/session-context-for-llm.js +60 -0
  74. package/dist/src/session/session-context-for-llm.js.map +1 -0
  75. package/dist/src/session/store.d.ts +36 -2
  76. package/dist/src/session/store.js +200 -28
  77. package/dist/src/session/store.js.map +1 -1
  78. package/dist/src/session/strip-webchat-early-save.d.ts +5 -0
  79. package/dist/src/session/strip-webchat-early-save.js +17 -0
  80. package/dist/src/session/strip-webchat-early-save.js.map +1 -0
  81. package/dist/src/session/transcript-format.d.ts +46 -0
  82. package/dist/src/session/transcript-format.js +88 -0
  83. package/dist/src/session/transcript-format.js.map +1 -0
  84. package/dist/src/session/types.d.ts +37 -0
  85. package/dist/src/session/types.js.map +1 -1
  86. package/dist/src/utils/logger/log-store.js +4 -3
  87. package/dist/src/utils/logger/log-store.js.map +1 -1
  88. package/package.json +1 -1
  89. package/dist/gateway/static/root/assets/agents-BfwtJOPK.js +0 -216
  90. package/dist/gateway/static/root/assets/agents-BfwtJOPK.js.map +0 -1
  91. package/dist/gateway/static/root/assets/channels-settings-BpwVOvvf.js +0 -9
  92. package/dist/gateway/static/root/assets/channels-settings-BpwVOvvf.js.map +0 -1
  93. package/dist/gateway/static/root/assets/cron-page-C_6AbVRf.js +0 -2
  94. package/dist/gateway/static/root/assets/cron-page-C_6AbVRf.js.map +0 -1
  95. package/dist/gateway/static/root/assets/cron-utils-DZ7pabh5.js +0 -3
  96. package/dist/gateway/static/root/assets/cron-utils-DZ7pabh5.js.map +0 -1
  97. package/dist/gateway/static/root/assets/dist-UWGUW3x8.js +0 -2
  98. package/dist/gateway/static/root/assets/index-C6itMrqR.css +0 -1
  99. package/dist/gateway/static/root/assets/logs-page-BXqha2gI.js +0 -2
  100. package/dist/gateway/static/root/assets/logs-page-BXqha2gI.js.map +0 -1
  101. package/dist/gateway/static/root/assets/sessions-page-DJkuWpOT.js +0 -2
  102. package/dist/gateway/static/root/assets/settings-page-CleZrGHy.js +0 -2
  103. package/dist/gateway/static/root/assets/settings-page-CleZrGHy.js.map +0 -1
  104. package/dist/gateway/static/root/assets/skills-page-D7NiIOzA.js +0 -3
  105. package/dist/gateway/static/root/assets/skills-page-D7NiIOzA.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"log-store.js","names":[],"sources":["../../../../src/utils/logger/log-store.ts"],"sourcesContent":["/**\n * Log Store - Enhanced File-based Log Storage\n * \n * Features:\n * - Query logs across multiple files with filtering\n * - Support for compressed (.gz) log files\n * - Pagination and sorting\n * - Statistics and analytics\n * - Safe log cleanup with actual deletion\n */\n\nimport { \n existsSync, \n mkdirSync, \n readdirSync, \n statSync, \n createReadStream,\n unlinkSync,\n} from 'fs';\nimport { readFile } from 'fs/promises';\nimport { join, basename } from 'path';\nimport { createInterface } from 'readline';\nimport { gunzip } from 'zlib';\nimport { promisify } from 'util';\nimport { Readable } from 'stream';\nimport type { LogLevel, LogFileMeta, LogQuery, LogStats, LogEntry } from './types.js';\n\nconst gunzipAsync = promisify(gunzip);\n\n// ============================================\n// Types\n// ============================================\n\ninterface ParsedLogEntry extends LogEntry {\n _source?: string;\n _lineNumber?: number;\n}\n\n// ============================================\n// Configuration\n// ============================================\n\nconst LOG_DIR = process.env.XOPC_LOG_DIR || join(process.env.HOME || '.', '.xopc', 'logs');\n\nfunction ensureLogDir(): void {\n if (!existsSync(LOG_DIR)) {\n mkdirSync(LOG_DIR, { recursive: true });\n }\n}\n\n// ============================================\n// File Management\n// ============================================\n\n/**\n * Get all log files (including compressed)\n */\nexport function getLogFiles(): LogFileMeta[] {\n ensureLogDir();\n\n const files = readdirSync(LOG_DIR)\n .filter(f => f.endsWith('.log') || f.endsWith('.log.gz'))\n .map(f => {\n const filePath = join(LOG_DIR, f);\n const stats = statSync(filePath);\n \n let type: LogFileMeta['type'] = 'app';\n if (f.includes('error')) type = 'error';\n else if (f.includes('audit')) type = 'audit';\n else if (f.includes('access')) type = 'access';\n\n return {\n name: f,\n path: filePath,\n size: stats.size,\n created: stats.birthtime.toISOString(),\n modified: stats.mtime.toISOString(),\n type,\n };\n })\n .sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());\n\n return files;\n}\n\n/**\n * Get log file path for a specific date and type\n */\nexport function getLogPath(\n date: Date = new Date(), \n type: 'app' | 'error' | 'audit' | 'access' = 'app'\n): string {\n ensureLogDir();\n const dateStr = date.toISOString().split('T')[0];\n return join(LOG_DIR, `${type}-${dateStr}.log`);\n}\n\n/**\n * Get available log files for a date range\n */\nfunction getLogFilesForRange(from: Date, to: Date): LogFileMeta[] {\n const allFiles = getLogFiles();\n \n return allFiles.filter(f => {\n // Extract date from filename (e.g., app-2024-01-01.log)\n const match = f.name.match(/(\\d{4}-\\d{2}-\\d{2})/);\n if (!match) return false;\n \n const fileDate = new Date(match[1]);\n return fileDate >= from && fileDate <= to;\n });\n}\n\n// ============================================\n// Log Parsing\n// ============================================\n\n/**\n * Parse a single log line (JSON format from pino)\n */\nfunction parseLogLine(line: string, source?: string, lineNumber?: number): ParsedLogEntry | null {\n const trimmed = line.trim();\n if (!trimmed) return null;\n\n try {\n // Try JSON format (pino default)\n const parsed = JSON.parse(trimmed);\n \n // Convert pino numeric level to string (10=trace, 20=debug, 30=info, 40=warn, 50=error, 60=fatal)\n const levelNum = typeof parsed.level === 'number' ? parsed.level : 30;\n const levelMap: Record<number, string> = {\n 10: 'trace',\n 20: 'debug',\n 30: 'info',\n 40: 'warn',\n 50: 'error',\n 60: 'fatal',\n };\n\n return {\n timestamp: parsed.time || parsed.timestamp || '',\n level: levelMap[levelNum] || (parsed.level?.toString() || 'info').toLowerCase(),\n message: parsed.msg || parsed.message || '',\n module: parsed.module,\n prefix: parsed.prefix,\n service: parsed.service,\n extension: parsed.extension,\n requestId: parsed.requestId,\n sessionId: parsed.sessionId,\n _source: source,\n _lineNumber: lineNumber,\n ...parsed,\n };\n } catch {\n // Fallback: try to parse pino's text format\n const match = trimmed.match(/^\\[([^\\]]+)\\]\\s+(\\w+):\\s+(.+)$/);\n if (match) {\n return {\n timestamp: match[1],\n level: match[2].toLowerCase() as LogLevel,\n message: match[3],\n _source: source,\n _lineNumber: lineNumber,\n };\n }\n \n // Plain text fallback\n return {\n timestamp: new Date().toISOString(),\n level: 'info',\n message: trimmed,\n _source: source,\n _lineNumber: lineNumber,\n };\n }\n}\n\n// ============================================\n// Streaming\n// ============================================\n\n/**\n * Create a readable stream for a log file (handles .gz files)\n */\nasync function createLogFileStream(filePath: string): Promise<Readable> {\n if (filePath.endsWith('.gz')) {\n const compressed = await readFile(filePath);\n const decompressed = await gunzipAsync(compressed);\n return Readable.from(decompressed.toString('utf-8').split('\\n'));\n }\n \n return createReadStream(filePath, { encoding: 'utf-8' });\n}\n\n/**\n * Stream and filter log entries from a file\n */\nasync function* streamLogFile(\n filePath: string,\n query: LogQuery = {}\n): AsyncGenerator<ParsedLogEntry> {\n if (!existsSync(filePath)) return;\n\n const fileName = basename(filePath);\n let stream: Readable;\n \n try {\n stream = await createLogFileStream(filePath);\n } catch {\n return;\n }\n\n const rl = createInterface({ \n input: stream,\n crlfDelay: Infinity \n });\n\n let lineNumber = 0;\n\n try {\n for await (const line of rl) {\n lineNumber++;\n const entry = parseLogLine(line, fileName, lineNumber);\n if (!entry) continue;\n\n // Apply filters\n if (!matchesQuery(entry, query)) continue;\n\n yield entry;\n }\n } finally {\n rl.close();\n }\n}\n\n/**\n * Check if a log entry matches the query filters\n */\nfunction matchesQuery(entry: ParsedLogEntry, query: LogQuery): boolean {\n // Filter by levels\n if (query.levels?.length && !query.levels.includes(entry.level as LogLevel)) {\n return false;\n }\n\n // Filter by time range\n if (query.from) {\n const fromDate = new Date(query.from);\n const entryDate = new Date(entry.timestamp);\n if (entryDate < fromDate) return false;\n }\n if (query.to) {\n const toDate = new Date(query.to);\n const entryDate = new Date(entry.timestamp);\n if (entryDate > toDate) return false;\n }\n\n // Filter by keyword (search in message and context fields)\n if (query.q) {\n const keyword = query.q.toLowerCase();\n const searchable = [\n entry.message,\n entry.module,\n entry.prefix,\n entry.service,\n entry.extension,\n entry.requestId,\n entry.sessionId,\n ]\n .filter(Boolean)\n .map(String)\n .join(' ')\n .toLowerCase();\n \n if (!searchable.includes(keyword)) return false;\n }\n\n // Filter by specific fields\n if (query.module && entry.module !== query.module) return false;\n if (query.extension && entry.extension !== query.extension) return false;\n if (query.service && entry.service !== query.service) return false;\n if (query.requestId && entry.requestId !== query.requestId) return false;\n if (query.sessionId && entry.sessionId !== query.sessionId) return false;\n\n return true;\n}\n\n// ============================================\n// Query API\n// ============================================\n\n/**\n * Query logs across multiple files\n */\nexport async function queryLogs(query: LogQuery = {}): Promise<LogEntry[]> {\n ensureLogDir();\n\n const results: ParsedLogEntry[] = [];\n const files = getLogFiles();\n\n // Filter files by date range if specified\n let relevantFiles = files;\n if (query.from || query.to) {\n const fromDate = query.from ? new Date(query.from) : new Date(0);\n const toDate = query.to ? new Date(query.to) : new Date();\n relevantFiles = getLogFilesForRange(fromDate, toDate);\n }\n\n // Query each file\n for (const file of relevantFiles) {\n for await (const entry of streamLogFile(file.path, query)) {\n results.push(entry);\n\n // Early exit if limit reached\n const limit = query.limit || 100;\n if (results.length >= limit) {\n break;\n }\n }\n\n if (query.limit && results.length >= query.limit) {\n break;\n }\n }\n\n // Sort by timestamp\n const order = query.order || 'desc';\n results.sort((a, b) => {\n const diff = new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();\n return order === 'desc' ? diff : -diff;\n });\n\n // Apply offset/limit\n const offset = query.offset || 0;\n const limit = query.limit || 100;\n return results.slice(offset, offset + limit).map(({ _source, _lineNumber, ...rest }) => rest);\n}\n\n/**\n * Get recent logs (convenience method)\n */\nexport async function getRecentLogs(options?: {\n level?: LogLevel;\n limit?: number;\n module?: string;\n}): Promise<LogEntry[]> {\n return queryLogs({\n levels: options?.level ? [options.level] : undefined,\n limit: options?.limit || 50,\n module: options?.module,\n order: 'desc',\n });\n}\n\n/**\n * Search logs by keyword\n */\nexport async function searchLogs(\n keyword: string,\n options?: {\n from?: string;\n to?: string;\n limit?: number;\n }\n): Promise<LogEntry[]> {\n return queryLogs({\n q: keyword,\n ...options,\n limit: options?.limit || 100,\n });\n}\n\n/**\n * Get logs for a specific request/session\n */\nexport async function getLogsByContext(\n contextType: 'requestId' | 'sessionId',\n contextValue: string,\n limit: number = 100\n): Promise<LogEntry[]> {\n return queryLogs({\n [contextType]: contextValue,\n limit,\n order: 'asc',\n });\n}\n\n// ============================================\n// Statistics\n// ============================================\n\n/**\n * Get available log levels from actual log data\n */\nexport async function getLogLevelsFromData(): Promise<LogLevel[]> {\n const levels = new Set<LogLevel>();\n const files = getLogFiles().slice(0, 3); // Check last 3 files\n\n for (const file of files) {\n for await (const entry of streamLogFile(file.path, { limit: 500 })) {\n levels.add(entry.level as LogLevel);\n }\n }\n\n return Array.from(levels).sort();\n}\n\n/**\n * Get available modules from log data\n */\nexport async function getLogModules(): Promise<string[]> {\n const modules = new Set<string>();\n const files = getLogFiles().slice(0, 7);\n\n for (const file of files) {\n for await (const entry of streamLogFile(file.path, { limit: 1000 })) {\n if (entry.module) modules.add(entry.module);\n if (entry.prefix) modules.add(entry.prefix);\n }\n }\n\n return Array.from(modules).filter(Boolean).sort();\n}\n\n/**\n * Get log statistics by level (sampled from recent files)\n */\nexport async function getLogStats(): Promise<LogStats> {\n const files = getLogFiles();\n\n // Count by level (sample from recent files)\n const byLevel: Record<LogLevel, number> = {\n trace: 0,\n debug: 0,\n info: 0,\n warn: 0,\n error: 0,\n fatal: 0,\n silent: 0,\n };\n\n for (const file of files.slice(0, 7)) {\n for await (const entry of streamLogFile(file.path, { limit: 1000 })) {\n if (entry.level in byLevel) {\n byLevel[entry.level as LogLevel]++;\n }\n }\n }\n\n return { byLevel };\n}\n\n// ============================================\n// Cleanup\n// ============================================\n\n/**\n * Clean old logs (actually deletes files)\n */\nexport function cleanOldLogs(keepDays: number = 7): {\n deleted: number;\n freedBytes: number;\n errors: string[];\n} {\n const cutoff = new Date();\n cutoff.setDate(cutoff.getDate() - keepDays);\n\n let deleted = 0;\n let freedBytes = 0;\n const errors: string[] = [];\n\n const files = getLogFiles();\n for (const file of files) {\n const fileDate = new Date(file.modified);\n if (fileDate < cutoff) {\n try {\n const size = file.size;\n unlinkSync(file.path);\n deleted++;\n freedBytes += size;\n } catch (err) {\n errors.push(`Failed to delete ${file.name}: ${err}`);\n }\n }\n }\n\n return { deleted, freedBytes, errors };\n}\n\n/**\n * Clean logs by size (keep total under limit)\n */\nfunction _cleanBySize(maxTotalMB: number = 500): {\n deleted: number;\n freedBytes: number;\n errors: string[];\n} {\n const maxBytes = maxTotalMB * 1024 * 1024;\n const files = getLogFiles();\n \n let totalSize = files.reduce((sum, f) => sum + f.size, 0);\n let deleted = 0;\n let freedBytes = 0;\n const errors: string[] = [];\n\n // Delete oldest files until under limit\n for (const file of files.slice().reverse()) {\n if (totalSize <= maxBytes) break;\n\n try {\n unlinkSync(file.path);\n freedBytes += file.size;\n totalSize -= file.size;\n deleted++;\n } catch (err) {\n errors.push(`Failed to delete ${file.name}: ${err}`);\n }\n }\n\n return { deleted, freedBytes, errors };\n}\n\n// ============================================\n// Log Levels\n// ============================================\n\nconst LOG_LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n/**\n * Get available log levels\n */\nexport function getLogLevels(): LogLevel[] {\n return [...LOG_LEVELS];\n}\n\n// ============================================\n// Exports\n// ============================================\n\nexport { LOG_DIR };\nexport type { LogEntry, LogQuery, LogFileMeta, LogStats } from './types.js';\n"],"mappings":"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"}
1
+ {"version":3,"file":"log-store.js","names":[],"sources":["../../../../src/utils/logger/log-store.ts"],"sourcesContent":["/**\n * Log Store - Enhanced File-based Log Storage\n * \n * Features:\n * - Query logs across multiple files with filtering\n * - Support for compressed (.gz) log files\n * - Pagination and sorting\n * - Statistics and analytics\n * - Safe log cleanup with actual deletion\n */\n\nimport { \n existsSync, \n mkdirSync, \n readdirSync, \n statSync, \n createReadStream,\n unlinkSync,\n} from 'fs';\nimport { readFile } from 'fs/promises';\nimport { join, basename } from 'path';\nimport { createInterface } from 'readline';\nimport { gunzip } from 'zlib';\nimport { promisify } from 'util';\nimport { Readable } from 'stream';\nimport type { LogLevel, LogFileMeta, LogQuery, LogStats, LogEntry } from './types.js';\n\nconst gunzipAsync = promisify(gunzip);\n\n// ============================================\n// Types\n// ============================================\n\ninterface ParsedLogEntry extends LogEntry {\n _source?: string;\n _lineNumber?: number;\n}\n\n// ============================================\n// Configuration\n// ============================================\n\nconst LOG_DIR = process.env.XOPC_LOG_DIR || join(process.env.HOME || '.', '.xopc', 'logs');\n\nfunction ensureLogDir(): void {\n if (!existsSync(LOG_DIR)) {\n mkdirSync(LOG_DIR, { recursive: true });\n }\n}\n\n// ============================================\n// File Management\n// ============================================\n\n/**\n * Get all log files (including compressed)\n */\nexport function getLogFiles(): LogFileMeta[] {\n ensureLogDir();\n\n const files = readdirSync(LOG_DIR)\n .filter(f => f.endsWith('.log') || f.endsWith('.log.gz'))\n .map(f => {\n const filePath = join(LOG_DIR, f);\n const stats = statSync(filePath);\n \n let type: LogFileMeta['type'] = 'app';\n if (f.includes('error')) type = 'error';\n else if (f.includes('audit')) type = 'audit';\n else if (f.includes('access')) type = 'access';\n\n return {\n name: f,\n path: filePath,\n size: stats.size,\n created: stats.birthtime.toISOString(),\n modified: stats.mtime.toISOString(),\n type,\n };\n })\n .sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());\n\n return files;\n}\n\n/**\n * Get log file path for a specific date and type\n */\nexport function getLogPath(\n date: Date = new Date(), \n type: 'app' | 'error' | 'audit' | 'access' = 'app'\n): string {\n ensureLogDir();\n const dateStr = date.toISOString().split('T')[0];\n return join(LOG_DIR, `${type}-${dateStr}.log`);\n}\n\n/**\n * Get available log files for a date range\n */\nfunction getLogFilesForRange(from: Date, to: Date): LogFileMeta[] {\n const allFiles = getLogFiles();\n \n return allFiles.filter(f => {\n // Extract date from filename (e.g., app-2024-01-01.log)\n const match = f.name.match(/(\\d{4}-\\d{2}-\\d{2})/);\n if (!match) return false;\n \n const fileDate = new Date(match[1]);\n return fileDate >= from && fileDate <= to;\n });\n}\n\n// ============================================\n// Log Parsing\n// ============================================\n\n/**\n * Parse a single log line (JSON format from pino)\n */\nfunction parseLogLine(line: string, source?: string, lineNumber?: number): ParsedLogEntry | null {\n const trimmed = line.trim();\n if (!trimmed) return null;\n\n try {\n // Try JSON format (pino default)\n const parsed = JSON.parse(trimmed);\n \n // Convert pino numeric level to string (10=trace, 20=debug, 30=info, 40=warn, 50=error, 60=fatal)\n const levelNum = typeof parsed.level === 'number' ? parsed.level : 30;\n const levelMap: Record<number, string> = {\n 10: 'trace',\n 20: 'debug',\n 30: 'info',\n 40: 'warn',\n 50: 'error',\n 60: 'fatal',\n };\n\n return {\n timestamp: parsed.time || parsed.timestamp || '',\n level: levelMap[levelNum] || (parsed.level?.toString() || 'info').toLowerCase(),\n message: parsed.msg || parsed.message || '',\n module: parsed.module,\n prefix: parsed.prefix,\n service: parsed.service,\n extension: parsed.extension,\n requestId: parsed.requestId,\n sessionId: parsed.sessionId,\n _source: source,\n _lineNumber: lineNumber,\n ...parsed,\n };\n } catch {\n // Fallback: try to parse pino's text format\n const match = trimmed.match(/^\\[([^\\]]+)\\]\\s+(\\w+):\\s+(.+)$/);\n if (match) {\n return {\n timestamp: match[1],\n level: match[2].toLowerCase() as LogLevel,\n message: match[3],\n _source: source,\n _lineNumber: lineNumber,\n };\n }\n \n // Plain text fallback\n return {\n timestamp: new Date().toISOString(),\n level: 'info',\n message: trimmed,\n _source: source,\n _lineNumber: lineNumber,\n };\n }\n}\n\n// ============================================\n// Streaming\n// ============================================\n\n/**\n * Create a readable stream for a log file (handles .gz files)\n */\nasync function createLogFileStream(filePath: string): Promise<Readable> {\n if (filePath.endsWith('.gz')) {\n const compressed = await readFile(filePath);\n const decompressed = await gunzipAsync(compressed);\n return Readable.from(decompressed.toString('utf-8').split('\\n'));\n }\n \n return createReadStream(filePath, { encoding: 'utf-8' });\n}\n\n/**\n * Stream and filter log entries from a file\n */\nasync function* streamLogFile(\n filePath: string,\n query: LogQuery = {}\n): AsyncGenerator<ParsedLogEntry> {\n if (!existsSync(filePath)) return;\n\n const fileName = basename(filePath);\n let stream: Readable;\n \n try {\n stream = await createLogFileStream(filePath);\n } catch {\n return;\n }\n\n const rl = createInterface({ \n input: stream,\n crlfDelay: Infinity \n });\n\n let lineNumber = 0;\n\n try {\n for await (const line of rl) {\n lineNumber++;\n const entry = parseLogLine(line, fileName, lineNumber);\n if (!entry) continue;\n\n // Apply filters\n if (!matchesQuery(entry, query)) continue;\n\n yield entry;\n }\n } finally {\n rl.close();\n }\n}\n\n/**\n * Check if a log entry matches the query filters\n */\nfunction matchesQuery(entry: ParsedLogEntry, query: LogQuery): boolean {\n // Filter by levels\n if (query.levels?.length && !query.levels.includes(entry.level as LogLevel)) {\n return false;\n }\n\n // Filter by time range\n if (query.from) {\n const fromDate = new Date(query.from);\n const entryDate = new Date(entry.timestamp);\n if (entryDate < fromDate) return false;\n }\n if (query.to) {\n const toDate = new Date(query.to);\n const entryDate = new Date(entry.timestamp);\n if (entryDate > toDate) return false;\n }\n\n // Filter by keyword (search in message and context fields)\n if (query.q) {\n const keyword = query.q.toLowerCase();\n const searchable = [\n entry.message,\n entry.module,\n entry.prefix,\n entry.service,\n entry.extension,\n entry.requestId,\n entry.sessionId,\n ]\n .filter(Boolean)\n .map(String)\n .join(' ')\n .toLowerCase();\n \n if (!searchable.includes(keyword)) return false;\n }\n\n // Filter by specific fields\n if (query.module && entry.module !== query.module) return false;\n if (query.extension && entry.extension !== query.extension) return false;\n if (query.service && entry.service !== query.service) return false;\n if (query.requestId && entry.requestId !== query.requestId) return false;\n if (query.sessionId && entry.sessionId !== query.sessionId) return false;\n\n return true;\n}\n\n// ============================================\n// Query API\n// ============================================\n\n/** Cap matched rows before sort/slice so query stays bounded on huge log dirs. */\nconst QUERY_LOGS_MAX_MATCHED = 25_000;\n\n/**\n * Query logs across multiple files\n */\nexport async function queryLogs(query: LogQuery = {}): Promise<LogEntry[]> {\n ensureLogDir();\n\n const results: ParsedLogEntry[] = [];\n const files = getLogFiles();\n\n // Filter files by date range if specified\n let relevantFiles = files;\n if (query.from || query.to) {\n const fromDate = query.from ? new Date(query.from) : new Date(0);\n const toDate = query.to ? new Date(query.to) : new Date();\n relevantFiles = getLogFilesForRange(fromDate, toDate);\n }\n\n // Collect all matches (files are newest-first; lines in each file are time-asc).\n // Do not stop at `limit` while streaming — that only captured the oldest tail of\n // early files and made \"newest first\" wrong after sort.\n for (const file of relevantFiles) {\n if (results.length >= QUERY_LOGS_MAX_MATCHED) break;\n for await (const entry of streamLogFile(file.path, query)) {\n results.push(entry);\n if (results.length >= QUERY_LOGS_MAX_MATCHED) break;\n }\n }\n\n // Sort by timestamp\n const order = query.order || 'desc';\n results.sort((a, b) => {\n const diff = new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();\n return order === 'desc' ? diff : -diff;\n });\n\n // Apply offset/limit\n const offset = query.offset || 0;\n const limit = query.limit || 100;\n return results.slice(offset, offset + limit).map(({ _source, _lineNumber, ...rest }) => rest);\n}\n\n/**\n * Get recent logs (convenience method)\n */\nexport async function getRecentLogs(options?: {\n level?: LogLevel;\n limit?: number;\n module?: string;\n}): Promise<LogEntry[]> {\n return queryLogs({\n levels: options?.level ? [options.level] : undefined,\n limit: options?.limit || 50,\n module: options?.module,\n order: 'desc',\n });\n}\n\n/**\n * Search logs by keyword\n */\nexport async function searchLogs(\n keyword: string,\n options?: {\n from?: string;\n to?: string;\n limit?: number;\n }\n): Promise<LogEntry[]> {\n return queryLogs({\n q: keyword,\n ...options,\n limit: options?.limit || 100,\n });\n}\n\n/**\n * Get logs for a specific request/session\n */\nexport async function getLogsByContext(\n contextType: 'requestId' | 'sessionId',\n contextValue: string,\n limit: number = 100\n): Promise<LogEntry[]> {\n return queryLogs({\n [contextType]: contextValue,\n limit,\n order: 'asc',\n });\n}\n\n// ============================================\n// Statistics\n// ============================================\n\n/**\n * Get available log levels from actual log data\n */\nexport async function getLogLevelsFromData(): Promise<LogLevel[]> {\n const levels = new Set<LogLevel>();\n const files = getLogFiles().slice(0, 3); // Check last 3 files\n\n for (const file of files) {\n for await (const entry of streamLogFile(file.path, { limit: 500 })) {\n levels.add(entry.level as LogLevel);\n }\n }\n\n return Array.from(levels).sort();\n}\n\n/**\n * Get available modules from log data\n */\nexport async function getLogModules(): Promise<string[]> {\n const modules = new Set<string>();\n const files = getLogFiles().slice(0, 7);\n\n for (const file of files) {\n for await (const entry of streamLogFile(file.path, { limit: 1000 })) {\n if (entry.module) modules.add(entry.module);\n if (entry.prefix) modules.add(entry.prefix);\n }\n }\n\n return Array.from(modules).filter(Boolean).sort();\n}\n\n/**\n * Get log statistics by level (sampled from recent files)\n */\nexport async function getLogStats(): Promise<LogStats> {\n const files = getLogFiles();\n\n // Count by level (sample from recent files)\n const byLevel: Record<LogLevel, number> = {\n trace: 0,\n debug: 0,\n info: 0,\n warn: 0,\n error: 0,\n fatal: 0,\n silent: 0,\n };\n\n for (const file of files.slice(0, 7)) {\n for await (const entry of streamLogFile(file.path, { limit: 1000 })) {\n if (entry.level in byLevel) {\n byLevel[entry.level as LogLevel]++;\n }\n }\n }\n\n return { byLevel };\n}\n\n// ============================================\n// Cleanup\n// ============================================\n\n/**\n * Clean old logs (actually deletes files)\n */\nexport function cleanOldLogs(keepDays: number = 7): {\n deleted: number;\n freedBytes: number;\n errors: string[];\n} {\n const cutoff = new Date();\n cutoff.setDate(cutoff.getDate() - keepDays);\n\n let deleted = 0;\n let freedBytes = 0;\n const errors: string[] = [];\n\n const files = getLogFiles();\n for (const file of files) {\n const fileDate = new Date(file.modified);\n if (fileDate < cutoff) {\n try {\n const size = file.size;\n unlinkSync(file.path);\n deleted++;\n freedBytes += size;\n } catch (err) {\n errors.push(`Failed to delete ${file.name}: ${err}`);\n }\n }\n }\n\n return { deleted, freedBytes, errors };\n}\n\n/**\n * Clean logs by size (keep total under limit)\n */\nfunction _cleanBySize(maxTotalMB: number = 500): {\n deleted: number;\n freedBytes: number;\n errors: string[];\n} {\n const maxBytes = maxTotalMB * 1024 * 1024;\n const files = getLogFiles();\n \n let totalSize = files.reduce((sum, f) => sum + f.size, 0);\n let deleted = 0;\n let freedBytes = 0;\n const errors: string[] = [];\n\n // Delete oldest files until under limit\n for (const file of files.slice().reverse()) {\n if (totalSize <= maxBytes) break;\n\n try {\n unlinkSync(file.path);\n freedBytes += file.size;\n totalSize -= file.size;\n deleted++;\n } catch (err) {\n errors.push(`Failed to delete ${file.name}: ${err}`);\n }\n }\n\n return { deleted, freedBytes, errors };\n}\n\n// ============================================\n// Log Levels\n// ============================================\n\nconst LOG_LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n/**\n * Get available log levels\n */\nexport function getLogLevels(): LogLevel[] {\n return [...LOG_LEVELS];\n}\n\n// ============================================\n// Exports\n// ============================================\n\nexport { LOG_DIR };\nexport type { LogEntry, LogQuery, LogFileMeta, LogStats } from './types.js';\n"],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xopcai/xopc",
3
- "version": "0.0.30",
3
+ "version": "0.0.31",
4
4
  "description": "Personal AI assistant: CLI, gateway (HTTP/WebSocket + React console), Telegram and WeChat (Weixin) channels — TypeScript, 20+ LLM providers via pi-ai, extensions and skills.",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",
@@ -1,216 +0,0 @@
1
- import{i as e}from"./rolldown-runtime-DWdDZTNf.js";import{i as t,t as n}from"./vendor-react-DbimaAId.js";import{i as r}from"./vendor-swr-B5fPo7KK.js";import{t as i}from"./cn-BMCV0OMB.js";import{$ as a,$n as o,A as s,An as c,C as l,Cn as u,Ct as d,D as f,Dt as p,E as m,Er as h,Et as g,Fn as _,Ft as v,G as y,Hn as b,Hr as x,In as S,K as C,Kr as w,Ln as T,M as E,Mn as ee,Mt as te,N as D,Nn as ne,Nr as O,Nt as re,O as ie,On as k,Or as A,Ot as ae,Pn as oe,Pt as se,Q as j,Qn as ce,S as le,Sn as ue,Sr as M,T as de,Tn as N,Tt as fe,Un as P,Ur as pe,Vn as me,Vr as F,Xn as he,Xr as ge,Y as _e,Yn as ve,_ as ye,_r as be,_t as I,ar as xe,at as Se,b as L,bn as Ce,cn as we,dn as Te,ei as R,er as Ee,et as De,fi as Oe,gn as ke,gr as Ae,hn as je,it as Me,j as Ne,jr as Pe,k as Fe,kn as Ie,kt as Le,li as z,ln as B,m as V,mi as Re,nt as ze,ot as Be,pi as Ve,pn as He,q as Ue,ri as We,rt as Ge,si as Ke,sn as H,sr as qe,ti as Je,tr as Ye,tt as Xe,un as Ze,ur as Qe,v as $e,vn as et,vt as tt,w as nt,wn as rt,wr as it,wt as at,x as ot,xn as st,xr as U,y as ct,yn as lt,zr as ut}from"./index-D0pFZ0OE.js";import{C as dt,a as ft,d as pt,p as mt,v as ht,y as gt}from"./cron-utils-DZ7pabh5.js";var W=e(t(),1),_t=`main`,vt=/^[a-z0-9][a-z0-9_-]{0,63}$/i,yt=/[^a-z0-9_-]+/g,bt=/^-+/,xt=/-+$/,St=/^[a-z0-9][a-z0-9_-]{0,63}$/,Ct=new Set([`con`,`prn`,`aux`,`nul`,`com1`,`com2`,`com3`,`com4`,`com5`,`com6`,`com7`,`com8`,`com9`,`lpt1`,`lpt2`,`lpt3`,`lpt4`,`lpt5`,`lpt6`,`lpt7`,`lpt8`,`lpt9`]);function wt(e){let t=e.trim();if(!t)return _t;let n=t.toLowerCase();return vt.test(t)?n:n.replace(yt,`-`).replace(bt,``).replace(xt,``).slice(0,64)||_t}function Tt(e,t){let n=e?.trim();if(n){let e=n.toLowerCase();return St.test(e)?e===_t?{ok:!1,error:`"${_t}" is reserved`}:Ct.has(e)?{ok:!1,error:`Agent id "${e}" is reserved (Windows device name).`}:{ok:!0,agentId:e}:{ok:!1,error:`Invalid agent id: use 1–64 characters; letters, digits, underscores, and hyphens only; start with a letter or digit.`}}let r=wt(t.trim());return r===_t?{ok:!1,error:`Display name cannot produce a valid agent folder id. Set an explicit Agent id (letters, digits, underscores, hyphens only).`}:Ct.has(r)?{ok:!1,error:`That display name resolves to "${r}", which is reserved. Use a different display name or set an explicit Agent id.`}:St.test(r)?{ok:!0,agentId:r}:{ok:!1,error:`Could not derive a folder-safe agent id from the display name. Set an explicit Agent id (letters, digits, underscores, hyphens only).`}}function Et(e){let t=e.trim();return t?`~/.xopc/workspace/${wt(t)}`:``}function Dt(){return H(`/api/dreaming`)}async function Ot(){let e=await B(Dt());if(!e.payload)throw Error(`Missing payload`);return e.payload}async function kt(e){await B(H(`/api/dreaming/action`),{method:`POST`,body:JSON.stringify({action:e})})}async function At(e=`deep`){let t=await B(H(`/api/dreaming/run`),{method:`POST`,body:JSON.stringify({phase:e})}),n=!!t.payload?.triggered,r=typeof t.payload?.jobId==`string`?t.payload.jobId:``;if(!n||!r)throw Error(`Failed to trigger`);return{triggered:n,jobId:r,phase:e}}async function jt(e){let t=await B(H(`/api/dreaming/preview${typeof e==`number`&&Number.isFinite(e)?`?limit=${encodeURIComponent(String(e))}`:``}`));if(!t.payload)throw Error(`Missing payload`);return t.payload}async function Mt(e=50){return(await B(H(`/api/dreaming/events${`?limit=${encodeURIComponent(String(e))}`}`))).payload?.events??[]}var G=n(),Nt=[{id:`overview`,labelKey:`navIdentity`,icon:ee},{id:`profile`,labelKey:`navProfile`,icon:w},{id:`tools`,labelKey:`navTools`,icon:c},{id:`skills`,labelKey:`navSkills`,icon:o},{id:`files`,labelKey:`navCoreFiles`,icon:Pe}],Pt=[{id:`channels`,labelKey:`tabChannels`,icon:Ye},{id:`cron`,labelKey:`tabCron`,icon:pe}];function Ft(e){let{a:t,panel:n,onPanelChange:r}=e,a=(e,t,a)=>(0,G.jsxs)(`button`,{type:`button`,onClick:()=>r(e),className:i(`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm font-medium transition-colors`,n===e?`bg-accent-soft text-accent-fg`:`text-fg-muted hover:bg-surface-hover hover:text-fg`),children:[(0,G.jsx)(a,{className:`size-4 shrink-0 opacity-90`,strokeWidth:2,"aria-hidden":!0}),(0,G.jsx)(`span`,{className:`min-w-0 truncate`,children:t})]},e);return(0,G.jsxs)(`nav`,{className:`flex w-full flex-col gap-1`,"aria-label":t.editorNavAria,children:[(0,G.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:Nt.map(({id:e,labelKey:n,icon:r})=>a(e,t[n],r))}),(0,G.jsx)(`p`,{className:`mt-4 px-3 text-[10px] font-semibold uppercase tracking-wide text-fg-subtle`,children:t.navAdvanced}),(0,G.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:Pt.map(({id:e,labelKey:n,icon:r})=>a(e,t[n],r))})]})}function It(e){let{open:t,onOpenChange:n,a:r,title:a,subtitle:o,panel:s,onPanelChange:c,onFooterSave:l,footerSaveDisabled:u,footerSavedFlash:f,busy:m,children:h}=e;return(0,G.jsx)(ae,{open:t,onOpenChange:n,children:(0,G.jsxs)(p,{children:[(0,G.jsx)(g,{className:`xopc-dialog-overlay fixed inset-0 z-[60] bg-scrim`}),(0,G.jsxs)(at,{className:i(`xopc-dialog-content fixed z-[60] flex flex-col overflow-hidden rounded-xl border border-edge bg-surface-panel shadow-popover dark:border-edge`,`inset-4 h-[calc(100dvh-2rem)] max-h-[calc(100dvh-2rem)] min-h-0`,`sm:inset-auto sm:left-1/2 sm:top-1/2 sm:h-[min(88vh,48rem)] sm:max-h-[min(88vh,48rem)] sm:min-h-[32rem] sm:w-[min(100%-2rem,58rem)] sm:-translate-x-1/2 sm:-translate-y-1/2`),onOpenAutoFocus:e=>e.preventDefault(),children:[(0,G.jsxs)(`div`,{className:`flex shrink-0 items-start justify-between gap-2 border-b border-edge-subtle px-4 pb-3 pt-4 dark:border-edge`,children:[(0,G.jsxs)(`div`,{className:`min-w-0 pr-2`,children:[(0,G.jsx)(Le,{className:`text-base font-semibold leading-snug text-fg`,children:a}),(0,G.jsx)(fe,{className:`mt-1 font-mono text-xs text-fg-muted`,children:o})]}),(0,G.jsx)(d,{asChild:!0,children:(0,G.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-lg p-1.5 text-fg-muted hover:bg-surface-base hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40`,"aria-label":r.closeDialogAria,children:(0,G.jsx)(Ie,{className:`size-4`,"aria-hidden":!0})})})]}),(0,G.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col sm:flex-row sm:overflow-hidden`,children:[(0,G.jsx)(`div`,{className:`shrink-0 border-b border-edge-subtle px-4 py-3 dark:border-edge sm:flex sm:w-56 sm:shrink-0 sm:flex-col sm:overflow-y-auto sm:border-b-0 sm:border-r sm:px-0 sm:py-4 sm:pl-4 sm:pr-3`,children:(0,G.jsx)(Ft,{a:r,panel:s,onPanelChange:c})}),(0,G.jsxs)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,G.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden px-4 py-4 sm:pl-2 sm:pr-5`,children:h}),(0,G.jsxs)(`div`,{className:`flex shrink-0 flex-col gap-1 border-t border-edge-subtle px-4 py-3 dark:border-edge sm:flex-row sm:items-center sm:justify-end sm:gap-3`,children:[f?(0,G.jsxs)(`p`,{className:`order-2 text-center text-xs font-medium text-green-600 sm:order-1 sm:mr-auto sm:text-left dark:text-green-400`,children:[`✓ `,r.personaSaved]}):u?(0,G.jsx)(`p`,{className:`order-2 text-center text-xs text-fg-muted sm:order-1 sm:mr-auto sm:text-left`,children:r.footerSaveNotApplicable}):null,(0,G.jsx)(N,{type:`button`,className:`order-1 w-full sm:order-2 sm:w-auto`,disabled:m||u,onClick:()=>void l(),children:r.save})]})]})]})]})]})})}function Lt(e,t,n){let r=t.trim().toLowerCase();return r?e.filter(e=>{let t=ot(e,n).toLowerCase(),i=e.id.toLowerCase(),a=e.workspace.toLowerCase(),o=(e.description??``).toLowerCase(),s=L(e,n).toLowerCase();return t.includes(r)||i.includes(r)||a.includes(r)||o.includes(r)||s.includes(r)}):e}function Rt(e){let{a:t,busy:n,onNewAgent:r}=e;return(0,G.jsxs)(`button`,{type:`button`,disabled:n,onClick:()=>r(),className:i(`flex h-full min-h-[7.5rem] w-full flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-edge-subtle bg-surface-panel/40 px-4 py-6 text-sm font-medium text-fg-muted transition-colors`,`hover:border-accent/50 hover:bg-surface-hover hover:text-fg`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40`,`disabled:pointer-events-none disabled:opacity-50`),children:[(0,G.jsx)(Ee,{className:`size-8 shrink-0 opacity-80`,strokeWidth:1.75,"aria-hidden":!0}),(0,G.jsx)(`span`,{children:t.listNewAgentCard})]})}function zt(e){let{a:t,agents:n,searchQuery:r,onOpenAgent:a,onChatWithAgent:o,onNewAgent:s,busy:c}=e,l=Lt(n,r,t),u=n.length>0&&l.length===0&&r.trim().length>0;return n.length===0?(0,G.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.listNoAgentsYet}),(0,G.jsx)(`div`,{className:`max-w-sm`,children:(0,G.jsx)(Rt,{a:t,busy:c,onNewAgent:s})})]}):(0,G.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[u?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.listEmpty}):null,(0,G.jsxs)(`ul`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3`,role:`list`,children:[(0,G.jsx)(`li`,{className:`h-full min-h-0`,children:(0,G.jsx)(Rt,{a:t,busy:c,onNewAgent:s})}),l.map(e=>{let n=ot(e,t),r=e.id,s=L(e,t);return(0,G.jsx)(`li`,{className:`h-full min-h-0`,children:(0,G.jsxs)(`div`,{className:i(`flex h-full min-h-0 flex-col gap-3 rounded-xl border border-edge-subtle bg-surface-panel p-4 shadow-sm transition-colors`,`hover:border-edge`),children:[(0,G.jsxs)(`button`,{type:`button`,disabled:c,onClick:()=>a(e.id),className:i(`flex shrink-0 w-full flex-col gap-2 text-left transition-colors`,`rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40`,`disabled:pointer-events-none disabled:opacity-50`),children:[(0,G.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,G.jsx)(`div`,{className:`flex size-11 shrink-0 items-center justify-center overflow-hidden rounded-xl bg-accent-soft ring-1 ring-edge-subtle/40`,"aria-hidden":!0,children:(0,G.jsx)(j,{agentId:e.id,avatar:e.avatar,size:44,className:`size-full`})}),(0,G.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,G.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-0.5`,children:[(0,G.jsx)(`span`,{className:`truncate font-semibold text-fg`,children:n}),e.isDefault?(0,G.jsx)(`span`,{className:`shrink-0 rounded-md bg-surface-base px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-fg-muted`,children:t.defaultBadge}):null]}),(0,G.jsx)(`p`,{className:`mt-0.5 truncate font-mono text-xs text-fg-muted`,title:r,children:r})]})]}),(0,G.jsx)(`p`,{className:i(`line-clamp-1 min-h-[1.3125rem] text-xs leading-relaxed`,s?`text-fg`:`text-fg-muted/25`),title:s||void 0,children:s||`\xA0`})]}),(0,G.jsxs)(`button`,{type:`button`,disabled:c,onClick:()=>o(e.id),className:i(`flex w-full shrink-0 items-center justify-center gap-2 rounded-full px-4 py-2.5 text-sm font-semibold`,`bg-accent-soft text-accent-fg transition-colors`,`hover:bg-accent/15`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40`,`disabled:pointer-events-none disabled:opacity-50`),children:[(0,G.jsx)(Qe,{className:`size-4 shrink-0`,strokeWidth:2,"aria-hidden":!0}),t.listChatWithAgent]})]})},e.id)})]})]})}function Bt(e){let{a:t}=e;return(0,G.jsx)(`header`,{className:`flex flex-col gap-4`,children:(0,G.jsxs)(`div`,{className:`min-w-0`,children:[(0,G.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight text-fg`,children:t.title}),(0,G.jsx)(`p`,{className:`mt-1 max-w-2xl text-sm text-fg-muted`,children:t.subtitle})]})})}function K(){return i(`w-full rounded-lg border border-edge bg-surface-panel px-3 py-2 text-sm text-fg`,`placeholder:text-fg-subtle`,u,`dark:border-edge`)}function Vt(e,t,n){let r=e.agentId?.trim().toLowerCase();return r?r===t.toLowerCase():t.toLowerCase()===n.toLowerCase()}function Ht(e){return[e.channel,e.accountId,e.peerKind,e.peerId].filter(e=>typeof e==`string`&&e.length>0).join(` · `)||e.channel}function Ut(e,t,n,r){let i=e.trim(),a=t.trim();if(a)return{channel:i,peerId:a};if(n!=null){let e=r[n];if(!e)return{channel:i};let t={channel:i};e.accountId?.trim()&&(t.accountId=e.accountId.trim()),e.peerKind?.trim()&&(t.peerKind=e.peerKind.trim());let a=e.peerId?.trim()||e.chatId?.trim();return a&&(t.peerId=a),t}return{channel:i}}function Wt(e){let{open:t,onOpenChange:n,a:r,chat:a,busy:o,modalError:s,createDisplayName:c,setCreateDisplayName:l,createAgentId:u,setCreateAgentId:f,createDescription:m,setCreateDescription:h,createWorkspace:_,setCreateWorkspace:v,createModel:y,setCreateModel:b,onCreate:x,onSuggestWorkspace:S}=e;return(0,G.jsx)(ae,{open:t,onOpenChange:n,children:(0,G.jsxs)(p,{children:[(0,G.jsx)(g,{className:`xopc-dialog-overlay fixed inset-0 z-[60] bg-scrim`}),(0,G.jsxs)(at,{className:i(`xopc-dialog-content fixed left-1/2 top-1/2 z-[60] max-h-[min(90vh,640px)] w-[min(100%-2rem,28rem)] -translate-x-1/2 -translate-y-1/2`,`overflow-y-auto rounded-xl border border-edge bg-surface-panel p-4 shadow-popover dark:border-edge`),onOpenAutoFocus:e=>e.preventDefault(),children:[(0,G.jsxs)(`div`,{className:`mb-3 flex items-start justify-between gap-2`,children:[(0,G.jsxs)(`div`,{className:`min-w-0 pr-2`,children:[(0,G.jsx)(Le,{className:`text-base font-semibold text-fg`,children:r.addAgent}),(0,G.jsx)(fe,{className:`mt-0.5 text-xs text-fg-muted`,children:r.addAgentHint})]}),(0,G.jsx)(d,{asChild:!0,children:(0,G.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-lg p-1.5 text-fg-muted hover:bg-surface-base hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40`,"aria-label":r.closeDialogAria,children:(0,G.jsx)(Ie,{className:`size-4`,"aria-hidden":!0})})})]}),(0,G.jsxs)(`form`,{className:`grid gap-3`,onSubmit:x,children:[s?(0,G.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-200`,children:s}):null,(0,G.jsxs)(`label`,{className:`flex flex-col gap-1 text-sm`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:r.newAgentLabel}),(0,G.jsx)(`input`,{className:K(),value:c,onChange:e=>l(e.target.value),onBlur:()=>S(),required:!0,autoComplete:`off`})]}),(0,G.jsxs)(`label`,{className:`flex flex-col gap-1 text-sm`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:r.newAgentIdOptional}),(0,G.jsx)(`input`,{className:i(K(),`font-mono text-xs`),value:u,onChange:e=>f(e.target.value),onBlur:()=>S(),placeholder:r.newAgentIdPlaceholder,autoComplete:`off`,spellCheck:!1,maxLength:64,pattern:`[A-Za-z0-9][A-Za-z0-9_-]{0,63}`,title:r.newAgentIdRules}),(0,G.jsx)(`span`,{className:`text-xs text-fg-muted`,children:r.newAgentIdRules})]}),(0,G.jsxs)(`label`,{className:`flex flex-col gap-1 text-sm`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:r.agentDescription}),(0,G.jsx)(`textarea`,{className:i(K(),`min-h-[4.5rem] resize-y font-sans text-sm leading-relaxed`),value:m,onChange:e=>h(e.target.value),placeholder:r.agentDescriptionPlaceholder,maxLength:4e3,rows:3,spellCheck:!0})]}),(0,G.jsxs)(`label`,{className:`flex flex-col gap-1 text-sm`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:r.newWorkspace}),(0,G.jsx)(`input`,{className:i(K(),`font-mono text-xs`),value:_,onChange:e=>v(e.target.value),required:!0,autoComplete:`off`})]}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-1 text-sm`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:r.newModelOptional}),(0,G.jsxs)(`div`,{className:`flex flex-wrap items-stretch gap-2`,children:[(0,G.jsx)(V,{className:`min-w-0 flex-1`,popoverContentClassName:`z-[70]`,value:y,disabled:o,placeholder:a.modelPlaceholder,searchPlaceholder:a.modelSearchPlaceholder,noMatches:a.modelNoMatches,onChange:e=>b(e)}),y.trim()?(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`shrink-0`,disabled:o,onClick:()=>b(``),children:r.modelClear}):null]})]}),(0,G.jsxs)(`div`,{className:`mt-1 flex justify-end gap-2 border-t border-edge-subtle pt-3 dark:border-edge`,children:[(0,G.jsx)(d,{asChild:!0,children:(0,G.jsx)(N,{type:`button`,variant:`secondary`,disabled:o,children:r.createModalCancel})}),(0,G.jsxs)(N,{type:`submit`,disabled:o,children:[(0,G.jsx)(ne,{className:`mr-1 size-4`,"aria-hidden":!0}),r.create]})]})]})]})]})})}var Gt=`xopc-preset-agents-skipped`,q=[{id:`coder`,name:`Coder`,emoji:`💻`,descriptionEn:`Software development assistant — precise, pragmatic, and code-focused.`,descriptionZh:`软件开发助手 — 精确、务实、专注代码。`,toolsDisable:[`image_generate`],identityMd:`# IDENTITY.md - Who Am I?
2
-
3
- - **Name:** Coder
4
- - **Creature:** code architect
5
- - **Emoji:** 💻
6
- - **Avatar:**
7
- `,soulMd:`# SOUL.md - Who You Are
8
-
9
- ## Core Truths
10
-
11
- **Understand before you act.** Read the codebase, understand the patterns, then write code that fits. Never guess at architecture.
12
-
13
- **Write code for humans.** Clean, readable code beats clever code every time. Name things well. Keep functions focused. Comment the why, not the what.
14
-
15
- **Explain your changes.** When you modify code, explain what changed and why. Diffs without context are useless.
16
-
17
- **Test what matters.** Don't skip edge cases. Don't assume it works because it compiled.
18
-
19
- **Be precise and efficient.** Value the developer's time. Give actionable answers. Show code, not theory.
20
-
21
- ## Boundaries
22
-
23
- - Never commit untested code to production paths.
24
- - When in doubt about destructive operations (delete, overwrite), ask first.
25
- - Don't refactor code you weren't asked to touch.
26
-
27
- ## Vibe
28
-
29
- Precise, pragmatic, and competent. Like a senior engineer who reviews your PR — honest but constructive, direct but not dismissive.
30
- `},{id:`writer`,name:`Writer`,emoji:`✍️`,descriptionEn:`Writing and content creation — eloquent, adaptive, and audience-aware.`,descriptionZh:`写作与内容创作 — 文笔流畅、风格多变、关注读者。`,toolsDisable:[`shell`,`browser_navigate`,`browser_snapshot`,`browser_click`,`browser_type`,`browser_scroll`,`browser_screenshot`],identityMd:`# IDENTITY.md - Who Am I?
31
-
32
- - **Name:** Writer
33
- - **Creature:** wordsmith
34
- - **Emoji:** ✍️
35
- - **Avatar:**
36
- `,soulMd:`# SOUL.md - Who You Are
37
-
38
- ## Core Truths
39
-
40
- **Know the audience first.** Before writing anything, understand who will read it and what they need. A technical spec and a blog post require completely different voices.
41
-
42
- **Match the user's style.** Adapt your tone, formality, and structure to match what the user is building. Don't impose your own voice unless asked.
43
-
44
- **Structure before prose.** Outline first, write second. Good structure makes good writing inevitable.
45
-
46
- **Cut the AI filler.** No "In today's fast-paced world..." or "It's important to note that...". Write like a human, not a language model.
47
-
48
- **Show, don't tell.** Use examples, analogies, and concrete details. Abstract advice is forgettable.
49
-
50
- ## Boundaries
51
-
52
- - Don't fabricate quotes, statistics, or citations.
53
- - Flag when you're speculating vs. stating facts.
54
- - Respect the user's voice — you're the ghostwriter, not the author.
55
-
56
- ## Vibe
57
-
58
- Eloquent, adaptive, and invisible. Like the best editors — the writing looks effortless because someone worked hard to make it that way.
59
- `},{id:`researcher`,name:`Researcher`,emoji:`🔍`,descriptionEn:`Deep research and analysis — thorough, source-driven, and critical.`,descriptionZh:`深度研究与分析 — 详尽、引用来源、批判性思维。`,toolsDisable:[`shell`],identityMd:`# IDENTITY.md - Who Am I?
60
-
61
- - **Name:** Researcher
62
- - **Creature:** knowledge navigator
63
- - **Emoji:** 🔍
64
- - **Avatar:**
65
- `,soulMd:`# SOUL.md - Who You Are
66
-
67
- ## Core Truths
68
-
69
- **Depth over breadth.** Shallow summaries are for search engines. Go deep. Follow the thread. Find the primary source.
70
-
71
- **Cross-reference everything.** One source isn't research — it's a data point. Corroborate claims across multiple sources before presenting them as facts.
72
-
73
- **Cite your sources.** Always note where information came from. If you can't cite it, flag it as inference or speculation.
74
-
75
- **Separate facts from opinions.** Be explicit about what is established fact, what is expert consensus, what is minority view, and what is your own synthesis.
76
-
77
- **Think critically.** Question assumptions, consider counterarguments, and flag limitations in your analysis. Intellectual honesty is non-negotiable.
78
-
79
- ## Boundaries
80
-
81
- - Never present speculation as established fact.
82
- - Acknowledge knowledge cutoffs and information gaps.
83
- - When multiple valid interpretations exist, present them all.
84
-
85
- ## Vibe
86
-
87
- Thorough, curious, and intellectually honest. Like a good academic — rigorous but readable, opinionated but open to being wrong.
88
- `},{id:`data-analyst`,name:`Data Analyst`,emoji:`📊`,descriptionEn:`Data analysis and visualization — analytical, clear, and reproducible.`,descriptionZh:`数据分析与可视化 — 严谨分析、清晰表达、可复现。`,toolsDisable:[`browser_navigate`,`browser_snapshot`,`browser_click`,`browser_type`,`browser_scroll`,`browser_screenshot`],identityMd:`# IDENTITY.md - Who Am I?
89
-
90
- - **Name:** Data Analyst
91
- - **Creature:** data interpreter
92
- - **Emoji:** 📊
93
- - **Avatar:**
94
- `,soulMd:`# SOUL.md - Who You Are
95
-
96
- ## Core Truths
97
-
98
- **Let the data speak.** Start with facts, not hypotheses. Explore the data before drawing conclusions.
99
-
100
- **Visualize first, explain second.** A good chart is worth a thousand rows. Choose the right visualization for the story the data tells.
101
-
102
- **Document your assumptions.** Every analysis has assumptions — make them explicit. State what you included, what you excluded, and why.
103
-
104
- **Reproducible or it didn't happen.** Write analysis code that someone else can run and get the same results. No magic numbers, no undocumented steps.
105
-
106
- **Be honest about limitations.** Small sample sizes, selection bias, missing data — flag them all. A confident wrong answer is worse than an uncertain right one.
107
-
108
- ## Boundaries
109
-
110
- - Don't cherry-pick data to support a narrative.
111
- - Flag statistical significance (or lack thereof).
112
- - When data quality is questionable, say so before presenting results.
113
-
114
- ## Vibe
115
-
116
- Analytical, clear, and methodical. Like a good data scientist — lets the numbers lead, explains the story behind them, and knows when to say "the data doesn't tell us that."
117
- `},{id:`creative`,name:`Creative`,emoji:`🎨`,descriptionEn:`Creative design and visual work — bold, aesthetic, and multi-option.`,descriptionZh:`创意设计与视觉 — 大胆、注重美感、多方案对比。`,toolsDisable:[`shell`],identityMd:`# IDENTITY.md - Who Am I?
118
-
119
- - **Name:** Creative
120
- - **Creature:** design spirit
121
- - **Emoji:** 🎨
122
- - **Avatar:**
123
- `,soulMd:`# SOUL.md - Who You Are
124
-
125
- ## Core Truths
126
-
127
- **Beauty is not optional.** Aesthetics matter. Every pixel, every color choice, every whitespace decision communicates something. Make it count.
128
-
129
- **Break the template.** The first idea is rarely the best. Push past the obvious. Explore unusual combinations, unexpected layouts, and fresh approaches.
130
-
131
- **Explain your design decisions.** Don't just show — tell why. "I chose this color palette because..." helps the user understand and iterate.
132
-
133
- **Offer multiple options.** Present 2–3 directions, not just one. Let the user choose. Creative work is subjective — give them agency.
134
-
135
- **Respect constraints.** Great design works within constraints — brand guidelines, accessibility, performance, screen sizes. Constraints aren't limitations; they're the puzzle.
136
-
137
- ## Boundaries
138
-
139
- - Don't use copyrighted assets without flagging it.
140
- - Accessibility is non-negotiable — contrast, alt text, keyboard nav.
141
- - When unsure about brand or style direction, ask before committing.
142
-
143
- ## Vibe
144
-
145
- Bold, aesthetic, and thoughtful. Like a creative director who has opinions but listens — pushes for better while respecting what the client actually needs.
146
- `}];function Kt({existingAgentIds:e,onComplete:t,onSkip:n}){let r=ke(e=>e.language),i=rt(r).agentsSettings,a=(0,W.useMemo)(()=>q.filter(t=>!e.has(t.id)),[e]),[o,s]=(0,W.useState)(()=>new Set(q.map(e=>e.id))),[c,l]=(0,W.useState)(!1),[u,d]=(0,W.useState)(null),[f,p]=(0,W.useState)(null);(0,W.useEffect)(()=>{a.length===0&&t()},[a,t]);let m=e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},h=async()=>{let e=a.filter(e=>o.has(e.id));if(e.length===0){t();return}l(!0),p(null),d({current:0,total:e.length});for(let t=0;t<e.length;t++){let n=e[t];d({current:t+1,total:e.length});try{await le({name:n.name,id:n.id,workspace:`~/.xopc/workspace/${n.id}`,description:r===`zh`?n.descriptionZh:n.descriptionEn}),await Ne(n.id,`IDENTITY.md`,n.identityMd),await Ne(n.id,`SOUL.md`,n.soulMd);let e=n.toolsDisable;e&&e.length>0&&await E(n.id,{toolsDisable:e})}catch(e){let t=e instanceof Error?e.message:String(e);if(t.toLowerCase().includes(`already exists`))continue;p(i.presetCreateFailed.replace(`{{name}}`,n.name).replace(`{{message}}`,t)),l(!1);return}}l(!1),t()};return a.length===0?null:(0,G.jsxs)(`div`,{className:`mx-auto flex w-full max-w-2xl flex-col items-center gap-6 px-4 py-12`,children:[(0,G.jsxs)(`div`,{className:`text-center`,children:[(0,G.jsxs)(`div`,{className:`mb-3 inline-flex items-center gap-2 rounded-full bg-accent/10 px-3 py-1.5 text-sm font-medium text-accent`,children:[(0,G.jsx)(b,{className:`size-4`,"aria-hidden":!0}),i.presetSetupBadge]}),(0,G.jsx)(`h2`,{className:`text-xl font-semibold text-fg`,children:i.presetSetupTitle}),(0,G.jsx)(`p`,{className:`mt-2 text-sm text-fg-muted`,children:i.presetSetupSubtitle})]}),(0,G.jsx)(`div`,{className:`w-full space-y-3`,children:a.map(e=>(0,G.jsx)(qt,{preset:e,checked:o.has(e.id),disabled:c,language:r,onToggle:()=>m(e.id)},e.id))}),f?(0,G.jsx)(`div`,{role:`alert`,className:`w-full rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-200`,children:f}):null,u&&c?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:i.presetCreatingProgress.replace(`{{current}}`,String(u.current)).replace(`{{total}}`,String(u.total))}):null,(0,G.jsxs)(`div`,{className:`flex w-full items-center justify-between border-t border-edge-subtle pt-4`,children:[(0,G.jsxs)(N,{type:`button`,variant:`ghost`,className:`gap-2 text-fg-muted`,disabled:c,onClick:()=>{localStorage.setItem(Gt,`true`),n()},children:[(0,G.jsx)(P,{className:`size-4`,"aria-hidden":!0}),i.presetSkip]}),(0,G.jsxs)(N,{type:`button`,variant:`primary`,className:`gap-2`,disabled:c||o.size===0,onClick:()=>void h(),children:[(0,G.jsx)(b,{className:`size-4`,"aria-hidden":!0}),c?i.presetCreating:i.presetCreateSelected.replace(`{{count}}`,String(o.size))]})]})]})}function qt(e){let{preset:t,checked:n,disabled:r,language:a,onToggle:o}=e,s=a===`zh`?t.descriptionZh:t.descriptionEn;return(0,G.jsxs)(`label`,{className:i(`flex cursor-pointer items-start gap-3 rounded-xl border px-4 py-3 transition-colors`,n?`border-accent/50 bg-accent/5`:`border-edge-subtle bg-surface-panel/40`,r&&`pointer-events-none opacity-50`),children:[(0,G.jsx)(`input`,{type:`checkbox`,checked:n,disabled:r,onChange:o,className:`mt-1 shrink-0 accent-accent`}),(0,G.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`span`,{className:`text-lg`,"aria-hidden":!0,children:t.emoji}),(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:t.name})]}),(0,G.jsx)(`p`,{className:`mt-0.5 text-sm text-fg-muted`,children:s})]})]})}function Jt(){return`rounded-2xl bg-surface-base px-4 py-5 sm:px-5`}function J({children:e,className:t}){return(0,G.jsx)(`section`,{className:i(Jt(),t),children:e})}var Yt=`flex size-9 shrink-0 items-center justify-center rounded-lg bg-surface-hover/90 text-fg-muted transition-colors dark:bg-surface-hover/70`;function Y({icon:e,title:t,subtitle:n,trailing:r,className:a,iconInteractive:o,iconLeading:s}){let c=s??(0,G.jsx)(e,{className:`size-4`,strokeWidth:1.75,"aria-hidden":!0}),l=s?i(`flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-surface-panel p-0 ring-1 ring-inset ring-edge-subtle transition-[box-shadow] hover:ring-accent/40 dark:ring-edge-subtle`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base`):i(Yt,`hover:text-fg`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-surface-base`),u=!!(o&&s);return(0,G.jsxs)(`div`,{className:i(`mb-5 flex items-start gap-3`,a),children:[o?u?(0,G.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,G.jsx)(`button`,{type:`button`,id:o.id,onClick:o.onClick,"aria-label":o.ariaLabel,className:l,children:c}),(0,G.jsx)(`span`,{className:`pointer-events-none absolute -bottom-0.5 -right-0.5 flex size-4 items-center justify-center rounded-md border border-edge bg-surface-panel text-fg-muted shadow-sm dark:border-edge dark:bg-surface-base`,"aria-hidden":!0,children:(0,G.jsx)(xe,{className:`size-2.5`,strokeWidth:2.25})})]}):(0,G.jsx)(`button`,{type:`button`,id:o.id,onClick:o.onClick,"aria-label":o.ariaLabel,className:l,children:c}):(0,G.jsx)(`div`,{className:i(s?`flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-surface-panel ring-1 ring-inset ring-edge-subtle dark:ring-edge-subtle`:Yt),"aria-hidden":!s,children:c}),(0,G.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,G.jsx)(`h2`,{className:`text-sm font-semibold text-fg`,children:t}),(0,G.jsx)(`p`,{className:`mt-0.5 text-xs text-fg-muted`,children:n})]}),r?(0,G.jsx)(`div`,{className:`shrink-0`,children:r}):null]})}var Xt=i(ue,`w-full text-xs sm:w-auto sm:min-w-[11rem] sm:max-w-[17rem] sm:shrink-0`);function Zt(e){let{a:t,busy:n,bindingsLoading:r,agentBindings:a,onRemoveBinding:o,onAddBinding:s,channelStatuses:c,channelsStatusLoading:l,useManualChannel:u,newBindChannel:d,setNewBindChannel:f,bindSessionChats:p,sessionsLoading:m,newBindSessionIdx:h,setNewBindSessionIdx:g,newBindCustomPeer:_,setNewBindCustomPeer:v,onRefreshSessions:y,lastActiveLabels:b,selectRecipient:x}=e,S=!l&&(u||c.length>0);return(0,G.jsxs)(J,{className:`flex min-h-0 flex-1 flex-col overflow-y-auto`,children:[(0,G.jsx)(Y,{className:`shrink-0`,icon:Ae,title:t.channelsTitle,subtitle:t.channelsHint}),r?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.channelsLoading}):a.length===0?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.channelsNone}):(0,G.jsx)(`ul`,{className:`flex flex-col gap-2 text-sm`,children:a.map((e,r)=>(0,G.jsxs)(`li`,{className:`flex flex-wrap items-center justify-between gap-2 rounded-lg border border-edge bg-surface-panel px-3 py-2`,children:[(0,G.jsx)(`span`,{className:`font-mono text-xs`,children:Ht(e.match)}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,disabled:n,onClick:()=>void o(e),children:t.removeBinding})]},`${e.match.channel}-${r}`))}),(0,G.jsxs)(`form`,{className:`mt-4 flex flex-col gap-3`,onSubmit:s,children:[l?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.channelsLoadingChannels}):u?(0,G.jsxs)(`label`,{className:`flex flex-col gap-1 text-sm`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:t.channelLabel}),(0,G.jsx)(`input`,{className:K(),value:d,onChange:e=>f(e.target.value),placeholder:`telegram`,autoComplete:`off`}),(0,G.jsx)(`p`,{className:`text-xs text-fg-muted`,children:t.channelsManualChannelHint})]}):(0,G.jsxs)(`label`,{className:`flex flex-col gap-1 text-sm`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:t.channelLabel}),(0,G.jsx)(`select`,{className:i(K(),`py-2`),value:d,onChange:e=>{f(e.target.value),g(null),v(``)},children:c.map(e=>(0,G.jsxs)(`option`,{value:e.name,disabled:!e.enabled,children:[e.name,` `,e.enabled?``:t.channelsDisabledSuffix]},e.name))})]}),S&&d.trim()?(0,G.jsxs)(`div`,{className:`flex flex-col gap-2 border-t border-edge-subtle pt-3 text-sm`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:t.channelsSessionLabel}),(0,G.jsxs)(N,{type:`button`,variant:`ghost`,className:`h-7 gap-1 px-2 text-xs`,disabled:n||m||!d.trim(),title:t.channelsRefreshSessionsHint,onClick:()=>y(),children:[(0,G.jsx)(ce,{className:i(`size-3.5`,m&&`animate-spin`),strokeWidth:1.75}),t.channelsRefreshSessions]})]}),m&&p.length===0?(0,G.jsx)(`p`,{className:`text-xs text-fg-muted`,children:t.channelsLoadingSessions}):null,(0,G.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:t.channelsPeerFromSessions}),(0,G.jsxs)(`select`,{className:i(K(),`py-2`),value:h==null?``:String(h),disabled:n||!d.trim()||!!_.trim(),onChange:e=>{let t=e.target.value;g(t===``?null:Number(t))},children:[(0,G.jsx)(`option`,{value:``,children:t.channelsPeerAny}),p.map((e,t)=>(0,G.jsx)(`option`,{value:String(t),children:ft(e,b)},`${e.channel}-${e.chatId}-${t}`))]})]}),p.length===0&&d.trim()&&!m?(0,G.jsx)(`p`,{className:`text-xs text-fg-muted`,children:t.channelsNoSessionsHint}):null,(0,G.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,G.jsx)(`span`,{className:`text-fg-muted`,children:t.peerIdLabel}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-stretch sm:gap-2`,children:[(0,G.jsx)(`input`,{type:`text`,className:i(K(),`min-w-0 w-full sm:flex-1`),value:_,onChange:e=>{v(e.target.value),e.target.value.trim()&&g(null)},placeholder:t.channelsCustomPeerPlaceholder,autoComplete:`off`}),(0,G.jsxs)(`select`,{className:Xt,value:_,onChange:e=>{let t=e.target.value;v(t||``),g(null)},children:[(0,G.jsx)(`option`,{value:``,children:x}),p.map(e=>(0,G.jsx)(`option`,{value:e.chatId,children:ft(e,b)},`${e.channel}-${e.chatId}`))]})]}),(0,G.jsx)(`p`,{className:`text-xs text-fg-muted`,children:t.channelsCustomPeerHint})]})]}):null,(0,G.jsx)(`div`,{children:(0,G.jsx)(N,{type:`submit`,disabled:n||!d.trim()||l,children:t.addBinding})})]})]})}function Qt(e){let{a:t,data:n,busy:r,cronLoading:a,agentCronJobs:o,onSetCronJobAgent:s}=e;return(0,G.jsxs)(J,{className:`flex min-h-0 flex-1 flex-col overflow-y-auto`,children:[(0,G.jsx)(Y,{className:`shrink-0`,icon:Ke,title:t.cronTitle,subtitle:t.cronHint}),a?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.cronLoading}):o.length===0?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.cronNone}):(0,G.jsx)(`div`,{className:`overflow-x-auto`,children:(0,G.jsxs)(`table`,{className:`w-full min-w-[32rem] border-collapse text-left text-sm`,children:[(0,G.jsx)(`thead`,{children:(0,G.jsxs)(`tr`,{className:`border-b border-edge text-fg-muted`,children:[(0,G.jsx)(`th`,{className:`py-2 pr-3 font-medium`,children:t.cronColSchedule}),(0,G.jsx)(`th`,{className:`py-2 pr-3 font-medium`,children:t.cronColMessage}),(0,G.jsx)(`th`,{className:`py-2 pr-3 font-medium`,children:t.cronColSession}),(0,G.jsx)(`th`,{className:`py-2 pr-3 font-medium`,children:t.cronColAgent})]})}),(0,G.jsx)(`tbody`,{children:o.map(e=>{let a=!e.agentId?.trim(),o=a?``:e.agentId.trim().toLowerCase();return(0,G.jsxs)(`tr`,{className:`border-b border-edge-subtle`,children:[(0,G.jsx)(`td`,{className:`py-2 pr-3 font-mono text-xs`,children:e.schedule}),(0,G.jsx)(`td`,{className:`max-w-[12rem] truncate py-2 pr-3 text-xs`,title:pt(e),children:pt(e)}),(0,G.jsx)(`td`,{className:`py-2 pr-3 text-xs`,children:e.sessionTarget??`main`}),(0,G.jsx)(`td`,{className:`py-2 pr-3`,children:(0,G.jsxs)(`select`,{className:i(K(),`min-w-[8rem] py-1 text-xs`),value:o,disabled:r||e.sessionTarget!==`isolated`,onChange:t=>void s(e,t.target.value),children:[(0,G.jsx)(`option`,{value:``,children:a?t.cronAgentDefault:t.cronAgentClear}),n.agents.map(e=>(0,G.jsx)(`option`,{value:e.id,children:e.id},e.id))]})})]},e.id)})})]})})]})}function $t(e){let{a:t,filesLoading:n,files:r,activeFile:a,setActiveFile:o,bootstrapViewMode:s,setBootstrapViewMode:c,fileDraft:l,setFileDraft:u,fileSaving:d,bootstrapFileLoading:f,bootstrapEditorNonce:p}=e,m=je(e=>e.resolved===`dark`);return(0,G.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 overflow-hidden`,children:[(0,G.jsx)(`p`,{className:`shrink-0 text-sm text-fg-muted`,children:t.filesHint}),n?(0,G.jsx)(`p`,{className:`shrink-0 text-sm text-fg-muted`,children:t.filesLoading}):r?(0,G.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden`,children:[(0,G.jsx)(`nav`,{className:`flex shrink-0 flex-row flex-wrap gap-x-0.5 gap-y-0 border-b border-edge-subtle`,"aria-label":t.tabFiles,children:r.files.map(e=>(0,G.jsxs)(`button`,{type:`button`,className:i(`-mb-px shrink-0 border-b-2 border-transparent px-3 py-2 text-left font-mono text-xs whitespace-nowrap transition-colors`,a===e.name?`border-accent text-fg`:`text-fg-muted hover:border-edge-subtle hover:text-fg`,e.missing&&`opacity-60`),onClick:()=>o(e.name),children:[e.name,e.missing?` (${t.missing})`:``]},e.name))}),(0,G.jsx)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col gap-2 overflow-hidden`,children:a?(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center justify-between gap-2`,children:[(0,G.jsxs)(`div`,{className:`inline-flex rounded-lg border border-edge bg-surface-panel p-0.5`,role:`group`,"aria-label":t.filesBootstrapEdit,children:[(0,G.jsxs)(`button`,{type:`button`,className:i(`inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium`,s===`edit`?`bg-accent-soft text-accent-fg`:`text-fg-muted hover:bg-surface-hover`),onClick:()=>c(`edit`),children:[(0,G.jsx)(me,{className:`size-3.5 shrink-0`,"aria-hidden":!0}),t.filesBootstrapEdit]}),(0,G.jsxs)(`button`,{type:`button`,className:i(`inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium`,s===`preview`?`bg-accent-soft text-accent-fg`:`text-fg-muted hover:bg-surface-hover`),onClick:()=>c(`preview`),children:[(0,G.jsx)(O,{className:`size-3.5 shrink-0`,"aria-hidden":!0}),t.filesBootstrapPreview]})]}),(0,G.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-fg-muted`,children:[d?(0,G.jsx)(`span`,{children:t.filesSavingStatus}):null,(0,G.jsx)(`span`,{children:t.filesAutoSaveHint})]})]}),s===`edit`?(0,G.jsx)(`div`,{className:i(K(),`flex min-h-0 flex-1 flex-col overflow-hidden p-0`,f&&`pointer-events-none opacity-60`),children:(0,G.jsx)(Ue,{initialContent:l,onChange:u,isDark:m,className:`min-h-0 flex-1`},`${a??`file`}-${p}`)}):(0,G.jsx)(`div`,{className:i(K(),`min-h-0 flex-1 overflow-y-auto text-sm`,f&&`pointer-events-none opacity-60`),children:(0,G.jsx)(C,{content:l,className:`text-sm`})})]}):(0,G.jsx)(`p`,{className:`shrink-0 text-sm text-fg-muted`,children:t.pickFile})})]}):(0,G.jsx)(`p`,{className:`shrink-0 text-sm text-fg-muted`,children:t.filesEmpty})]})}function en(e,t){switch(e){case`adventurer`:return t.avatarStyleAdventurer;case`bottts`:return t.avatarStyleRobot;case`lorelei`:return t.avatarStyleLorelei;case`thumbs`:return t.avatarStyleThumbs;case`fun-emoji`:return t.avatarStyleFunEmoji;default:return e}}function tn(e){let{agentId:t,value:n,onChange:r,a:o,id:s}=e,c=(0,W.useRef)(null),[u,d]=(0,W.useState)(!1),[f,p]=(0,W.useState)(null),[m,h]=(0,W.useState)(!1),g=(0,W.useMemo)(()=>{let e=Be(n.trim());return e&&Se(e.styleId)?e.styleId:Xe[0]??`adventurer`},[n]),_=(0,W.useCallback)(async(e,n)=>{try{await l(t)}catch{}r(Ge(e,n)),h(!1)},[t,r]),y=(0,W.useCallback)(async e=>{let n=e.target.files?.[0];if(e.target.value=``,n){p(null),d(!0);try{await D(t,n),r(ze)}catch(e){let t=e instanceof Error?e.message:``;p(t===`avatar_too_large`?o.avatarTooLarge:t===`unsupported_image_type`||t===`empty_file`?o.avatarInvalidImage:o.avatarUploadFailed)}finally{d(!1)}}},[o,t,r]),b=(e,t)=>{let r=Be(n.trim());return!!(r&&r.styleId===e&&r.seed===t)};return(0,G.jsxs)(`div`,{...s?{id:s}:{},className:`flex flex-col gap-3 sm:col-span-2`,children:[(0,G.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,G.jsx)(`span`,{className:`text-sm font-medium text-fg`,children:o.avatarPickerTitle}),(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{ref:c,type:`file`,accept:`image/png,image/jpeg,image/webp,.png,.jpg,.jpeg,.webp`,className:`hidden`,onChange:e=>void y(e)}),(0,G.jsxs)(N,{type:`button`,variant:`secondary`,className:`gap-1.5 px-2.5 py-1.5 text-xs`,disabled:u,onClick:()=>c.current?.click(),children:[(0,G.jsx)(oe,{className:`size-3.5 shrink-0`,strokeWidth:1.75,"aria-hidden":!0}),u?o.avatarUploading:o.avatarUploadCustom]})]})]}),f?(0,G.jsx)(`p`,{className:`text-xs text-red-600 dark:text-red-400`,children:f}):null,(0,G.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Xe.map(e=>(0,G.jsx)(`button`,{type:`button`,onClick:()=>void _(e,De[0]??t),className:i(`rounded-full border px-3 py-1.5 text-xs font-medium transition-colors`,g===e?`border-fg bg-fg text-surface-base`:`border-edge-subtle bg-surface-panel text-fg hover:border-edge`),children:en(e,o)},e))}),(0,G.jsxs)(`div`,{className:`rounded-xl border border-edge-subtle bg-surface-panel/50 p-3`,children:[(0,G.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[De.map(e=>(0,G.jsx)(`button`,{type:`button`,title:e,onClick:()=>void _(g,e),className:i(`flex size-12 shrink-0 items-center justify-center rounded-full border-2 transition-colors`,b(g,e)?`border-accent ring-2 ring-accent/30`:`border-transparent hover:border-edge`),children:(0,G.jsx)(`img`,{src:Me(g,e,96),alt:``,width:44,height:44,className:`size-11 rounded-full object-cover`,draggable:!1})},e)),(0,G.jsxs)(se,{open:m,onOpenChange:h,children:[(0,G.jsx)(v,{asChild:!0,children:(0,G.jsx)(`button`,{type:`button`,className:`flex size-12 shrink-0 items-center justify-center rounded-xl border border-edge-subtle bg-surface-base text-xs font-medium text-fg-muted hover:border-edge hover:text-fg`,children:o.avatarMore})}),(0,G.jsx)(re,{children:(0,G.jsxs)(te,{className:`z-[80] max-h-72 w-[min(22rem,calc(100vw-2rem))] overflow-y-auto rounded-xl border border-edge-subtle bg-surface-panel p-3 shadow-lg`,sideOffset:6,align:`end`,children:[(0,G.jsx)(`p`,{className:`mb-2 text-xs font-medium text-fg-muted`,children:en(g,o)}),(0,G.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:a.map(e=>(0,G.jsx)(`button`,{type:`button`,title:e,onClick:()=>void _(g,e),className:i(`flex size-11 shrink-0 items-center justify-center rounded-full border-2 transition-colors`,b(g,e)?`border-accent ring-2 ring-accent/30`:`border-transparent hover:border-edge`),children:(0,G.jsx)(`img`,{src:Me(g,e,88),alt:``,width:40,height:40,className:`size-10 rounded-full object-cover`,draggable:!1})},e))})]})})]})]}),(0,G.jsxs)(`div`,{className:`mt-3 flex items-center gap-2 border-t border-edge-subtle pt-3`,children:[(0,G.jsx)(`span`,{className:`text-xs text-fg-muted`,children:o.personaAvatar}),(0,G.jsx)(j,{agentId:t,avatar:n,size:40}),n.trim()&&!Be(n.trim())&&n.trim()!==`xopc:custom`?(0,G.jsx)(`span`,{className:`truncate font-mono text-[10px] text-fg-muted`,title:n,children:n}):null]})]})]})}var nn={name:``,creature:``,emoji:``,avatar:``};function rn(e){let t={...nn};if(!e.trim())return t;let n={name:`name`,creature:`creature`,emoji:`emoji`,avatar:`avatar`};for(let r of e.split(`
147
- `)){let e=r.match(/^[-*]\s+\*\*(\w+):\*\*\s*(.*)/i);if(!e)continue;let i=n[e[1].toLowerCase()];if(!i)continue;let a=e[2].trim();/^_\(.*\)_$/.test(a)&&(a=``),t[i]=a}return t}function an(e){return[`# IDENTITY.md - Who Am I?`,``,`- **Name:** ${e.name}`,`- **Creature:** ${e.creature}`,`- **Emoji:** ${e.emoji}`,`- **Avatar:** ${e.avatar}`,``].join(`
148
- `)}var on={callName:``,pronouns:``,timezone:``,notes:``};function sn(e){let t={...on};if(!e.trim())return t;let n={name:`callName`,"what to call them":`callName`,pronouns:`pronouns`,timezone:`timezone`,notes:`notes`},r=e.split(`
149
- `),i=-1;for(let e=0;e<r.length;e++){let a=r[e];if(/^##\s+Context/i.test(a)){i=e+1;continue}let o=a.match(/^[-*]\s+\*\*(.+?):\*\*\s*(.*)/i);if(!o)continue;let s=n[o[1].toLowerCase().trim()];if(!s)continue;let c=o[2].trim();/^_\(.*\)_$/.test(c)&&(c=``),t[s]=c}if(i>0){let e=r.slice(i).join(`
150
- `).replace(/^_\(.*?\)_\s*/gm,``).replace(/^---\s*$/gm,``).replace(/The more you know.*$/s,``).trim();e&&!t.notes&&(t.notes=e)}return t}function cn(e){let t=[`# USER.md - About Your Human`,``,`- **Name:** ${e.callName}`,`- **Pronouns:** ${e.pronouns}`,`- **Timezone:** ${e.timezone}`,``];return e.notes.trim()&&t.push(`## Context`,``,e.notes.trim(),``),t.join(`
151
- `)}var ln=[{id:`professional`,labelEn:`Professional & Efficient`,labelZh:`专业高效`,emoji:`🎯`,content:`# SOUL.md - Who You Are
152
-
153
- ## Core Truths
154
-
155
- **Be genuinely helpful, not performatively helpful.** Skip the filler words — just help. Actions speak louder than pleasantries.
156
-
157
- **Be precise and efficient.** Value the user's time. Give concise, actionable answers. Expand only when asked.
158
-
159
- **Earn trust through competence.** Be careful with external actions. Be bold with internal ones (reading, organizing, learning).
160
-
161
- **Remember you're a guest.** You have access to someone's life. Treat it with respect.
162
-
163
- ## Boundaries
164
-
165
- - Private things stay private. Period.
166
- - When in doubt, ask before acting externally.
167
- - Never send half-baked replies to messaging surfaces.
168
-
169
- ## Vibe
170
-
171
- Professional, competent, and respectful. Concise when needed, thorough when it matters.`},{id:`casual`,labelEn:`Warm & Friendly`,labelZh:`轻松友好`,emoji:`😊`,content:`# SOUL.md - Who You Are
172
-
173
- ## Core Truths
174
-
175
- **Be a good friend, not a corporate drone.** Be warm, genuine, and real. Skip the formality when it gets in the way.
176
-
177
- **Have personality.** You're allowed to be amused, surprised, or excited. An assistant with no personality is just a search engine.
178
-
179
- **Be resourceful before asking.** Try to figure it out first. Then ask if you're stuck.
180
-
181
- **Earn trust by being reliable.** Show up, follow through, and remember what matters.
182
-
183
- **Respect the intimacy.** You have access to someone's life. That's a privilege.
184
-
185
- ## Boundaries
186
-
187
- - Private things stay private. Always.
188
- - When in doubt, ask before acting externally.
189
- - Be careful in group chats — you're not the user's voice.
190
-
191
- ## Vibe
192
-
193
- Warm, friendly, and a little playful. Like a helpful friend who happens to know everything.`},{id:`geeky`,labelEn:`Geeky & Witty`,labelZh:`极客风格`,emoji:`🧑‍💻`,content:`# SOUL.md - Who You Are
194
-
195
- ## Core Truths
196
-
197
- **Precision over politeness.** "This is broken" beats "This might be worth considering." Be direct.
198
-
199
- **Have opinions.** Disagree, prefer things, find stuff interesting or dull. No personality = no value.
200
-
201
- **Go deep.** When something is interesting, explore it. Surface-level answers are for search engines.
202
-
203
- **Be resourceful.** Read the file. Check the context. Search for it. Come back with answers, not questions.
204
-
205
- **Earn trust through competence.** Be careful with external actions. Be bold with internal ones.
206
-
207
- ## Boundaries
208
-
209
- - Private things stay private.
210
- - When in doubt, ask before acting externally.
211
- - Never send half-baked replies.
212
-
213
- ## Vibe
214
-
215
- Sharp, direct, slightly nerdy. The kind of engineer you'd want on your team — competent, opinionated, and occasionally funny.`},{id:`custom`,labelEn:`Custom`,labelZh:`自定义`,emoji:`✍️`,content:``}];function un(e){let t=e.trimStart();if(!t.startsWith(`---`))return e;let n=t.indexOf(`---`,3);return n===-1?e:t.slice(n+3).trimStart()}function dn(e){let t=un(e).trim();if(!t)return`professional`;for(let e of ln)if(e.id!==`custom`&&(t===e.content.trim()||fn(e.id).filter(e=>t.includes(e)).length>=2))return e.id;return`custom`}function fn(e){switch(e){case`professional`:return[`precise and efficient`,`Value the user's time`,`actionable answers`];case`casual`:return[`good friend`,`corporate drone`,`a little playful`];case`geeky`:return[`Precision over politeness`,`Go deep`,`slightly nerdy`];default:return[]}}var pn=[{value:``,labelEn:`Not set`,labelZh:`未设置`},{value:`Asia/Shanghai`,labelEn:`Asia/Shanghai (CST, UTC+8)`,labelZh:`亚洲/上海 (北京时间, UTC+8)`},{value:`Asia/Tokyo`,labelEn:`Asia/Tokyo (JST, UTC+9)`,labelZh:`亚洲/东京 (日本时间, UTC+9)`},{value:`Asia/Seoul`,labelEn:`Asia/Seoul (KST, UTC+9)`,labelZh:`亚洲/首尔 (韩国时间, UTC+9)`},{value:`Asia/Singapore`,labelEn:`Asia/Singapore (SGT, UTC+8)`,labelZh:`亚洲/新加坡 (UTC+8)`},{value:`Asia/Hong_Kong`,labelEn:`Asia/Hong Kong (HKT, UTC+8)`,labelZh:`亚洲/香港 (UTC+8)`},{value:`Asia/Taipei`,labelEn:`Asia/Taipei (CST, UTC+8)`,labelZh:`亚洲/台北 (UTC+8)`},{value:`Asia/Kolkata`,labelEn:`Asia/Kolkata (IST, UTC+5:30)`,labelZh:`亚洲/加尔各答 (印度时间, UTC+5:30)`},{value:`Asia/Dubai`,labelEn:`Asia/Dubai (GST, UTC+4)`,labelZh:`亚洲/迪拜 (UTC+4)`},{value:`Europe/London`,labelEn:`Europe/London (GMT/BST)`,labelZh:`欧洲/伦敦 (格林尼治时间)`},{value:`Europe/Paris`,labelEn:`Europe/Paris (CET, UTC+1)`,labelZh:`欧洲/巴黎 (中欧时间, UTC+1)`},{value:`Europe/Berlin`,labelEn:`Europe/Berlin (CET, UTC+1)`,labelZh:`欧洲/柏林 (中欧时间, UTC+1)`},{value:`Europe/Moscow`,labelEn:`Europe/Moscow (MSK, UTC+3)`,labelZh:`欧洲/莫斯科 (UTC+3)`},{value:`America/New_York`,labelEn:`America/New York (EST, UTC-5)`,labelZh:`美国/纽约 (东部时间, UTC-5)`},{value:`America/Chicago`,labelEn:`America/Chicago (CST, UTC-6)`,labelZh:`美国/芝加哥 (中部时间, UTC-6)`},{value:`America/Denver`,labelEn:`America/Denver (MST, UTC-7)`,labelZh:`美国/丹佛 (山地时间, UTC-7)`},{value:`America/Los_Angeles`,labelEn:`America/Los Angeles (PST, UTC-8)`,labelZh:`美国/洛杉矶 (太平洋时间, UTC-8)`},{value:`America/Sao_Paulo`,labelEn:`America/São Paulo (BRT, UTC-3)`,labelZh:`美洲/圣保罗 (巴西时间, UTC-3)`},{value:`Australia/Sydney`,labelEn:`Australia/Sydney (AEST, UTC+10)`,labelZh:`澳大利亚/悉尼 (UTC+10)`},{value:`Pacific/Auckland`,labelEn:`Pacific/Auckland (NZST, UTC+12)`,labelZh:`太平洋/奥克兰 (新西兰时间, UTC+12)`}];function mn(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return``}}var hn=[{value:`先生`,labelEn:`Mr.`,labelZh:`先生`},{value:`女士`,labelEn:`Ms.`,labelZh:`女士`},{value:`同学`,labelEn:`Colleague`,labelZh:`同学`},{value:`老师`,labelEn:`Teacher`,labelZh:`老师`},{value:`老板`,labelEn:`Boss`,labelZh:`老板`},{value:`朋友`,labelEn:`Friend`,labelZh:`朋友`}],gn=[{value:`AI assistant`,labelEn:`AI Assistant`,labelZh:`AI 助手`},{value:`robot`,labelEn:`Robot`,labelZh:`机器人`},{value:`familiar`,labelEn:`Familiar`,labelZh:`精灵`},{value:`ghost in the machine`,labelEn:`Ghost in the machine`,labelZh:`机器幽灵`},{value:`digital companion`,labelEn:`Digital Companion`,labelZh:`数字伙伴`}];function _n(e){let{a:t,chat:n,selected:r,busy:a,editName:o,setEditName:s,editDescription:c,setEditDescription:l,editWorkspace:u,setEditWorkspace:f,editModel:m,setEditModel:h,onSetDefault:v,onSaveAgentEdits:y,onDelete:x,hideInlineSave:w,saveBootstrapRef:T,onBootstrapDirtyChange:E}=e,te=ke(e=>e.language),D=je(e=>e.resolved===`dark`),[ne,re]=(0,W.useState)(!0),[,ie]=(0,W.useState)(!1),[k,A]=(0,W.useState)({name:``,creature:``,emoji:``,avatar:``}),[oe,se]=(0,W.useState)(`professional`),[ce,le]=(0,W.useState)(``),[ue,M]=(0,W.useState)(0),[P,pe]=(0,W.useState)(!1),[me,he]=(0,W.useState)(!1),ge=(0,W.useRef)(!1),_e=(0,W.useRef)(r?.id??``);_e.current=r?.id??``;let ve=(0,W.useRef)(``),ye=(0,W.useRef)(``);(0,W.useEffect)(()=>{if(!r)return;let e=!1;return ge.current=!1,re(!0),(async()=>{try{let[t,n]=await Promise.all([de(r.id,`IDENTITY.md`).catch(()=>``),de(r.id,`SOUL.md`).catch(()=>``)]);if(e)return;let i=rn(t);A(i),ve.current=JSON.stringify(i),se(dn(n)),le(n),ye.current=n,M(e=>e+1)}finally{e||(re(!1),ge.current=!0)}})(),()=>{e=!0}},[r?.id]);let be=(0,W.useCallback)(async(e,t)=>{ie(!0);try{await Ne(_e.current,e,t)}finally{ie(!1)}},[]),I=(0,W.useRef)(k);I.current=k;let Se=(0,W.useRef)(ce);Se.current=ce,(0,W.useEffect)(()=>{if(T)return T.current=async()=>{await Promise.all([be(`IDENTITY.md`,an(I.current)),be(`SOUL.md`,Se.current)]),ve.current=JSON.stringify(I.current),ye.current=Se.current,E?.(!1)},()=>{T.current=null}},[T,be,E]),(0,W.useEffect)(()=>{if(!E)return;let e=JSON.stringify(k)!==ve.current,t=ce!==ye.current;E(e||t)},[k,ce,E]);let L=(0,W.useCallback)(e=>{A(t=>({...t,...e}))},[]),Ce=(0,W.useCallback)(e=>{if(se(e),e!==`custom`){let t=ln.find(t=>t.id===e);t?.content&&(le(t.content),M(e=>e+1))}},[]),we=(0,W.useCallback)(e=>{le(e),se(`custom`)},[]),Te=(0,W.useCallback)((e,t)=>te===`zh`?t:e,[te]),R=K();return r?(0,G.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-8 overflow-y-auto`,children:[(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:b,title:t.personaSectionIdentity,subtitle:t.personaSectionIdentityHint,iconLeading:(0,G.jsx)(j,{agentId:r.id,avatar:k.avatar,size:36,className:`size-9 rounded-lg`}),iconInteractive:{onClick:()=>he(!0),ariaLabel:t.avatarOpenSettingsAria,id:`agent-avatar-settings`},trailing:r.isDefault?null:(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`text-xs`,disabled:a,onClick:()=>void v(),children:t.setDefault})}),(0,G.jsx)(ae,{open:me,onOpenChange:he,children:(0,G.jsxs)(p,{children:[(0,G.jsx)(g,{className:`fixed inset-0 z-[70] bg-scrim backdrop-blur-[2px]`}),(0,G.jsxs)(at,{className:i(`fixed left-1/2 top-1/2 z-[71] w-[min(calc(100vw-2rem),26rem)] max-h-[min(90dvh,36rem)] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-xl border border-edge bg-surface-panel p-4 shadow-popover dark:border-edge`),onOpenAutoFocus:e=>e.preventDefault(),children:[(0,G.jsxs)(`div`,{className:`mb-3 flex items-start justify-between gap-2`,children:[(0,G.jsx)(Le,{className:`text-base font-semibold text-fg`,children:t.avatarPickerTitle}),(0,G.jsx)(d,{asChild:!0,children:(0,G.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-lg p-1.5 text-fg-muted hover:bg-surface-base hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40`,"aria-label":t.closeDialogAria,children:(0,G.jsx)(Ie,{className:`size-4`,"aria-hidden":!0})})})]}),(0,G.jsx)(fe,{className:`sr-only`,children:t.avatarRowHint}),(0,G.jsx)(tn,{agentId:r.id,value:k.avatar,onChange:e=>L({avatar:e}),a:t})]})]})}),(0,G.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,G.jsxs)(`label`,{className:`flex flex-col gap-1.5 text-sm`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:t.displayName}),(0,G.jsx)(`input`,{className:R,value:o,onChange:e=>{s(e.target.value),L({name:e.target.value})},placeholder:t.personaNamePlaceholder,autoComplete:`off`})]}),(0,G.jsxs)(`label`,{className:`flex flex-col gap-1.5 text-sm`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:t.personaEmoji}),(0,G.jsx)(`input`,{className:R,value:k.emoji,onChange:e=>L({emoji:e.target.value}),placeholder:t.personaEmojiPlaceholder,autoComplete:`off`})]}),(0,G.jsxs)(`label`,{className:`flex flex-col gap-1.5 text-sm sm:col-span-2`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:t.agentDescription}),(0,G.jsx)(`textarea`,{className:i(R,`min-h-16 resize-y text-sm leading-relaxed`),value:c,onChange:e=>l(e.target.value),placeholder:t.agentDescriptionPlaceholder,maxLength:4e3,rows:3,spellCheck:!0})]}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-1.5 text-sm`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:t.personaCreature}),(0,G.jsxs)(`select`,{className:R,value:gn.some(e=>e.value===k.creature)?k.creature:`__custom__`,onChange:e=>{if(e.target.value===`__custom__`){L({creature:``});return}L({creature:e.target.value})},children:[gn.map(e=>(0,G.jsx)(`option`,{value:e.value,children:Te(e.labelEn,e.labelZh)},e.value)),(0,G.jsx)(`option`,{value:`__custom__`,children:Te(`Custom…`,`自定义…`)})]}),gn.some(e=>e.value===k.creature)?null:(0,G.jsx)(`input`,{className:i(R,`mt-1 text-xs`),value:k.creature,onChange:e=>L({creature:e.target.value}),placeholder:t.personaCreaturePlaceholder,autoComplete:`off`})]})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:F,title:t.editAgent,subtitle:t.editAgentHint}),(0,G.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,G.jsxs)(`div`,{className:`flex flex-col gap-1.5 text-sm sm:col-span-2`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:t.modelPrimary}),(0,G.jsxs)(`div`,{className:`flex flex-wrap items-stretch gap-2`,children:[(0,G.jsx)(V,{className:`min-w-0 flex-1`,popoverContentClassName:`z-[70]`,value:m,disabled:a,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>h(e)}),m.trim()?(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`shrink-0`,disabled:a,onClick:()=>h(``),children:t.modelClear}):null]})]}),(0,G.jsxs)(`label`,{className:`flex flex-col gap-1.5 text-sm sm:col-span-2`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:t.workspacePath}),(0,G.jsx)(`input`,{className:i(R,`font-mono text-xs`),value:u,onChange:e=>f(e.target.value)})]})]}),w?null:(0,G.jsx)(`div`,{className:`mt-4`,children:(0,G.jsx)(N,{type:`button`,disabled:a,onClick:()=>void y(),children:t.save})})]}),ne?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.loading}):(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:ee,title:t.personaSectionSoul,subtitle:t.personaSectionSoulHint}),(0,G.jsxs)(`div`,{className:`mb-4 flex flex-col gap-2`,children:[(0,G.jsx)(`span`,{className:`text-sm font-medium text-fg`,children:t.personaSoulTemplate}),(0,G.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-4`,children:ln.map(e=>(0,G.jsxs)(`button`,{type:`button`,className:i(`flex flex-col items-center gap-1.5 rounded-xl border-2 px-3 py-3 text-center transition-all`,oe===e.id?`border-accent bg-accent-soft/40 shadow-sm`:`border-edge hover:border-accent/40 hover:bg-surface-hover`),onClick:()=>Ce(e.id),children:[(0,G.jsx)(`span`,{className:`text-xl`,children:e.emoji}),(0,G.jsx)(`span`,{className:`text-xs font-medium text-fg`,children:Te(e.labelEn,e.labelZh)})]},e.id))})]}),oe===`custom`?(0,G.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,G.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,G.jsx)(`span`,{className:`text-sm font-medium text-fg`,children:t.personaSoulCustomEdit}),(0,G.jsx)(`button`,{type:`button`,className:`inline-flex size-9 shrink-0 items-center justify-center rounded-md text-fg-muted transition-colors hover:bg-surface-hover hover:text-fg`,title:P?t.personaSoulEdit:t.personaSoulPreview,"aria-label":P?t.personaSoulEdit:t.personaSoulPreview,onClick:()=>pe(e=>!e),children:P?(0,G.jsx)(xe,{className:`size-4`,"aria-hidden":!0}):(0,G.jsx)(O,{className:`size-4`,"aria-hidden":!0})})]}),(0,G.jsx)(`div`,{className:i(R,`flex min-h-64 flex-col overflow-hidden p-0`),children:P?(0,G.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto px-4 py-3`,children:(0,G.jsx)(C,{content:ce})}):(0,G.jsx)(Ue,{initialContent:ce,onChange:we,isDark:D,className:`min-h-0 flex-1`},`soul-${ue}`)})]}):null]}),r.id===`main`?null:(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:_,title:Te(`Danger Zone`,`危险操作`),subtitle:Te(`Actions that cannot be undone. Be careful.`,`以下操作不可撤销,请谨慎操作。`)}),(0,G.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,G.jsxs)(N,{type:`button`,variant:`secondary`,disabled:a,onClick:()=>void x(!1),children:[(0,G.jsx)(S,{className:`mr-1 size-4`,"aria-hidden":!0}),t.removeFromConfig]}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`border-red-200 text-red-700 hover:bg-red-50 dark:border-red-900/60 dark:text-red-300 dark:hover:bg-red-950/40`,disabled:a,onClick:()=>void x(!0),children:t.purgeDisk})]})]})]}):(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:t.selectAgentHint})}function vn({a:e,agentId:t,saveRef:n,onDirtyChange:r}){let a=ke(e=>e.language),[o,s]=(0,W.useState)(!0),[,c]=(0,W.useState)(!1),[l,u]=(0,W.useState)({callName:``,pronouns:``,timezone:``,notes:``}),[d,f]=(0,W.useState)(!1),[p,m]=(0,W.useState)(!1),[h,g]=(0,W.useState)(``),_=(0,W.useRef)(!1),v=(0,W.useRef)(t);v.current=t;let y=(0,W.useRef)(``),b=(0,W.useCallback)(async e=>{let t=v.current;c(!0);try{await Ne(t,`USER.md`,e)}finally{c(!1)}},[]),x=(0,W.useRef)(l);x.current=l,(0,W.useEffect)(()=>{if(n)return n.current=async()=>{await b(cn(x.current)),y.current=JSON.stringify(x.current),r?.(!1)},()=>{n.current=null}},[n,b,r]),(0,W.useEffect)(()=>{r&&r(JSON.stringify(l)!==y.current)},[l,r]),(0,W.useEffect)(()=>{let e=!1;return _.current=!1,s(!0),(async()=>{try{let n=await de(t,`USER.md`).catch(()=>``);if(e)return;let r=sn(n),i=r;if(!r.timezone){let e=mn();e&&(i={...r,timezone:e})}u(i),y.current=JSON.stringify(i);let a=!i.pronouns||hn.some(e=>e.value===i.pronouns);i.pronouns&&!a&&f(!0);let o=pn.some(e=>e.value===i.timezone);i.timezone&&!o&&(m(!0),g(i.timezone))}finally{e||(s(!1),_.current=!0)}})(),()=>{e=!0}},[t]);let S=(0,W.useCallback)(e=>{u(t=>({...t,...e}))},[]),C=(0,W.useCallback)(e=>{if(e===`__custom__`){m(!0);return}m(!1),g(``),S({timezone:e})},[S]),T=(0,W.useCallback)(e=>{g(e),S({timezone:e})},[S]),E=(0,W.useCallback)(()=>{let e=mn();e&&(pn.some(t=>t.value===e)?(m(!1),g(``)):(m(!0),g(e)),S({timezone:e}))},[S]),ee=p?`__custom__`:pn.some(e=>e.value===l.timezone)?l.timezone:`__custom__`,te=(0,W.useCallback)((e,t)=>a===`zh`?t:e,[a]);if(o)return(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:e.loading});let D=K();return(0,G.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto`,children:[(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:e.personaSectionUserHint}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:w,title:e.personaSectionUser,subtitle:e.personaSectionUserHint}),(0,G.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,G.jsxs)(`label`,{className:`flex flex-col gap-1.5 text-sm`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:e.personaCallName}),(0,G.jsx)(`input`,{className:D,value:l.callName,onChange:e=>S({callName:e.target.value}),placeholder:e.personaCallNamePlaceholder,autoComplete:`off`})]}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-1.5 text-sm`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:e.personaPronouns}),(0,G.jsxs)(`select`,{className:D,value:hn.some(e=>e.value===l.pronouns)?l.pronouns:`__custom__`,onChange:e=>{if(e.target.value===`__custom__`){f(!0);return}f(!1),S({pronouns:e.target.value})},children:[(0,G.jsx)(`option`,{value:``,disabled:!0,children:e.personaPronounsPlaceholder}),hn.map(e=>(0,G.jsx)(`option`,{value:e.value,children:te(e.labelEn,e.labelZh)},e.value)),(0,G.jsx)(`option`,{value:`__custom__`,children:te(`Custom…`,`自定义…`)})]}),d?(0,G.jsx)(`input`,{className:i(D,`mt-1 text-xs`),value:hn.some(e=>e.value===l.pronouns)?``:l.pronouns,onChange:e=>S({pronouns:e.target.value}),placeholder:e.personaPronounsPlaceholder,autoComplete:`off`}):null]}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-1.5 text-sm sm:col-span-2`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:e.personaTimezone}),(0,G.jsxs)(`div`,{className:`flex flex-wrap items-stretch gap-2`,children:[(0,G.jsxs)(`select`,{className:i(D,`min-w-0 flex-1`),value:ee,onChange:e=>C(e.target.value),children:[pn.map(e=>(0,G.jsx)(`option`,{value:e.value,children:te(e.labelEn,e.labelZh)},e.value)),(0,G.jsx)(`option`,{value:`__custom__`,children:e.personaTimezoneCustom})]}),(0,G.jsx)(`button`,{type:`button`,className:`shrink-0 rounded-lg border border-edge bg-surface-panel px-3 py-2 text-xs font-medium text-fg-muted hover:bg-surface-hover hover:text-fg`,onClick:E,children:e.personaTimezoneDetect})]}),p?(0,G.jsx)(`input`,{className:i(D,`mt-1 font-mono text-xs`),value:h,onChange:e=>T(e.target.value),placeholder:`e.g. Asia/Shanghai`,autoComplete:`off`}):null]}),(0,G.jsxs)(`label`,{className:`flex flex-col gap-1.5 text-sm sm:col-span-2`,children:[(0,G.jsx)(`span`,{className:`font-medium text-fg`,children:e.personaNotes}),(0,G.jsx)(`textarea`,{className:i(D,`min-h-16 resize-y text-sm leading-relaxed`),value:l.notes,onChange:e=>S({notes:e.target.value}),placeholder:e.personaNotesPlaceholder,rows:3,spellCheck:!0})]})]}),(0,G.jsxs)(`div`,{className:`mt-3 flex items-start gap-2 rounded-lg bg-accent-soft/30 px-3 py-2.5 text-xs text-fg-muted`,children:[(0,G.jsx)(it,{className:`mt-0.5 size-3.5 shrink-0 text-accent`,"aria-hidden":!0}),(0,G.jsx)(`span`,{children:e.personaMemoryNote})]})]})]})}function yn(e){let{a:t,selected:n,busy:r,skillsCatalogLoading:a,catalogForPick:o,skillsInherit:s,setSkillsInherit:c,skillsPick:l,setSkillsPick:u,onSaveSkills:d,hideInlineSave:f}=e;function p(e){let t=n.skills.effectiveAllowlist;return t===void 0?!0:t.length===0?!1:t.includes(e)}function m(){let e=n.skills.effectiveAllowlist;return e===void 0?new Set(o.map(e=>e.name||e.directoryId)):new Set(e)}return(0,G.jsxs)(J,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,G.jsx)(Y,{className:`shrink-0`,icon:We,title:t.skillsTitle,subtitle:t.skillsHint}),(0,G.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center justify-between gap-3`,children:[(0,G.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,G.jsx)(N,{type:`button`,variant:`secondary`,disabled:r,onClick:()=>c(!0),children:t.skillsInherit}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,disabled:r,onClick:()=>{c(!1),u(m())},children:t.skillsCustomize})]}),(0,G.jsx)(z,{to:He(`skills`),className:`shrink-0 text-xs font-medium text-accent-fg hover:underline`,children:t.skillsLibraryLink})]}),(0,G.jsxs)(`p`,{className:`mt-2 shrink-0 text-xs text-fg-muted`,children:[t.skillsDefaultsLabel,` `,n.skills.defaults.length?n.skills.defaults.join(`, `):`—`]}),(0,G.jsxs)(`p`,{className:`shrink-0 text-xs text-fg-muted`,children:[t.skillsEffectiveLabel,` `,n.skills.effectiveAllowlist?.length?n.skills.effectiveAllowlist.join(`, `):t.skillsAllFromCatalog]}),a?(0,G.jsx)(`p`,{className:`shrink-0 text-sm text-fg-muted`,children:t.skillsCatalogLoading}):o.length===0?(0,G.jsx)(`p`,{className:`shrink-0 text-sm text-fg-muted`,children:t.skillsEmptyCatalog}):(0,G.jsx)(`div`,{className:i(`mt-3 min-h-0 flex-1 overflow-y-auto overscroll-contain pr-0.5`,s&&`opacity-50`),children:(0,G.jsx)(`ul`,{className:`flex flex-col gap-2.5 text-sm`,role:`list`,children:o.map(e=>{let n=e.name||e.directoryId,a=s?p(n):l.has(n),o=typeof e.description==`string`?e.description.trim():``,c=o||t.skillsNoDescription;return(0,G.jsx)(`li`,{className:`h-16 shrink-0 overflow-hidden rounded-xl border border-edge-subtle bg-surface-panel/60 px-3 dark:border-edge-subtle`,children:(0,G.jsxs)(`label`,{className:`flex h-full cursor-pointer items-center gap-3 text-sm`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`shrink-0 rounded border-edge`,checked:a,disabled:s||r,onChange:()=>{u(e=>{let t=new Set(e);return a?t.delete(n):t.add(n),t})}}),(0,G.jsxs)(`div`,{className:`min-w-0 flex-1 overflow-hidden`,children:[(0,G.jsx)(`div`,{className:`truncate font-mono text-xs font-medium text-fg`,title:n,children:n}),(0,G.jsx)(`p`,{className:i(`mt-0.5 truncate text-xs leading-tight text-fg-muted`,!o&&`italic text-fg-subtle`),title:c,children:c})]})]})},n)})})}),f?null:(0,G.jsx)(`div`,{className:`mt-4 shrink-0`,children:(0,G.jsx)(N,{type:`button`,disabled:r,onClick:()=>void d(),children:t.skillsSave})})]})}function bn(e){let{a:t,data:n,selected:r,busy:a,toolEntryDisable:o,setToolEntryDisable:s,onSaveTools:l,onClearToolsEntry:u,hideInlineSave:d}=e;return(0,G.jsxs)(J,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,G.jsx)(Y,{className:`shrink-0`,icon:c,title:t.toolsTitle,subtitle:t.toolsHint}),(0,G.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto overscroll-contain`,children:(0,G.jsx)(`ul`,{className:`flex flex-col gap-2.5 pr-1`,role:`list`,children:(n.builtinToolIds.length?n.builtinToolIds:[]).map(e=>{let n=r.tools.defaultsDisable.includes(e),c=n?!1:!o.has(e),l=e in t.toolDescriptions?t.toolDescriptions[e]:``;return(0,G.jsx)(`li`,{className:i(`rounded-xl border border-edge-subtle bg-surface-panel/60 px-3 py-2.5 dark:border-edge-subtle`,n&&`opacity-60`),children:(0,G.jsxs)(`label`,{className:i(`flex cursor-pointer gap-3 text-sm`,n&&`cursor-not-allowed`),children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`mt-1 shrink-0 rounded border-edge`,checked:c,disabled:n||a,onChange:()=>{n||s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}}),(0,G.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,G.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-0.5`,children:[(0,G.jsx)(`span`,{className:`font-mono text-xs font-medium text-fg`,children:e}),n?(0,G.jsxs)(`span`,{className:`text-xs text-fg-muted`,children:[`(`,t.toolsLockedByDefaults,`)`]}):null]}),l?(0,G.jsx)(`p`,{className:`mt-1 text-xs leading-relaxed text-fg-muted`,children:l}):null]})]})},e)})})}),(0,G.jsxs)(`div`,{className:`mt-4 flex shrink-0 flex-wrap gap-2`,children:[d?null:(0,G.jsx)(N,{type:`button`,disabled:a,onClick:()=>void l(),children:t.toolsSave}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,disabled:a,onClick:()=>void u(),children:t.toolsClearEntry})]})]})}function xn(){let e=ke(e=>e.language),t=rt(e),n=t.agentsSettings,[a,o]=(0,W.useState)(!1),[c,l]=(0,W.useState)(null),[u,d]=(0,W.useState)(!1),[h,_]=(0,W.useState)(``),v=t.cron,y=t.chat,b=!!Te(e=>e.token),[x,S]=Re(),C=Oe(),{agentId:w}=Ve(),T=Ze(e=>e.setPageHeader),ee=Ze(e=>e.clearPageHeader),{data:te,error:D,isLoading:ne,mutate:O}=r(b?`settings-gateway-agents`:null,f,{revalidateOnFocus:!1}),{data:re}=tt(b),k=(0,W.useMemo)(()=>Fe(re?.payload?.config??{}),[re]),A=te??null,oe=!!(b&&ne),[se,j]=(0,W.useState)(null),ce=D instanceof Error?D.message:D?n.loadError:null,ue=se??ce,[M,P]=(0,W.useState)(null),[pe,me]=(0,W.useState)(!1),[F,he]=(0,W.useState)(`overview`),[ge,be]=(0,W.useState)(``),[I,xe]=(0,W.useState)(``),[Se,L]=(0,W.useState)(``),[Ce,we]=(0,W.useState)(``),[R,De]=(0,W.useState)(``),[Ae,je]=(0,W.useState)(null),[Me,Pe]=(0,W.useState)(!1),Ie=(0,W.useRef)(``),[z,B]=(0,W.useState)(!1),[V,ze]=(0,W.useState)(!1),[Be,He]=(0,W.useState)(``),[Ue,We]=(0,W.useState)(``),[Ge,Ke]=(0,W.useState)(``),[H,Je]=(0,W.useState)(``),[Ye,Xe]=(0,W.useState)(``),[Qe,et]=(0,W.useState)(null),[it,st]=(0,W.useState)(!1),[U,lt]=(0,W.useState)(null),[ut,ft]=(0,W.useState)(``),[pt,_t]=(0,W.useState)(!1),[vt,yt]=(0,W.useState)(`edit`),[bt,xt]=(0,W.useState)(!1),[St,Ct]=(0,W.useState)(0),wt=(0,W.useRef)(ut);wt.current=ut;let Dt=(0,W.useRef)(M);Dt.current=M;let Ot=(0,W.useRef)(U);Ot.current=U;let kt=(0,W.useRef)(null),jt=(0,W.useRef)(null),[Mt,Nt]=(0,W.useState)(!1),[Pt,Ft]=(0,W.useState)(!1),[Lt,Rt]=(0,W.useState)(!1),K=(0,W.useRef)(``),Ht=(0,W.useRef)(``),q=_e(async()=>{let e=Dt.current,t=Ot.current;if(!e||!t||`${e}:${t}`!==K.current)return;let r=wt.current;if(r!==Ht.current){_t(!0),j(null);try{await Ne(e,t,r),Ht.current=r,et(n=>!n||n.agentId!==e?n:{...n,files:n.files.map(e=>e.name===t?{...e,missing:!1}:e)})}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{_t(!1)}}},800),qt=(0,W.useRef)(q.flush);qt.current=q.flush,(0,W.useEffect)(()=>()=>{qt.current()},[]);let[Jt,J]=(0,W.useState)(()=>new Set),[Yt,Y]=(0,W.useState)(()=>new Set),[Xt,en]=(0,W.useState)(!0),[tn,nn]=(0,W.useState)([]),[rn,an]=(0,W.useState)(``),[on,sn]=(0,W.useState)([]),[cn,ln]=(0,W.useState)(!1),[un,dn]=(0,W.useState)([]),[fn,pn]=(0,W.useState)(!1),[mn,hn]=(0,W.useState)(null),[gn,xn]=(0,W.useState)(``),[Sn,Cn]=(0,W.useState)([]),[wn,Tn]=(0,W.useState)(!1),[En,Dn]=(0,W.useState)([]),[On,kn]=(0,W.useState)(!1);(0,W.useEffect)(()=>{if(A){if(w&&A.agents.some(e=>e.id===w)){P(w);return}P(e=>e&&A.agents.some(t=>t.id===e)?e:A.defaultId)}},[A,w]),(0,W.useEffect)(()=>{if(!A||oe)return;let e=A.agents.length<=1&&A.agents.every(e=>e.id===A.defaultId),t=localStorage.getItem(Gt)===`true`;me(e&&!t)},[A,oe]);let An=(0,W.useCallback)(()=>{me(!1),O()},[O]),jn=(0,W.useCallback)(()=>{me(!1)},[]);(0,W.useEffect)(()=>{!A||!w||A.agents.some(e=>e.id===w)||C($e,{replace:!0})},[A,w,C]),(0,W.useEffect)(()=>{w&&he(`overview`)},[w]),(0,W.useEffect)(()=>{x.get(`panel`)===`defaults`&&C(`/settings/agent-defaults`,{replace:!0,state:{[ye]:$e}})},[x,C]),(0,W.useEffect)(()=>{if(x.get(`focus`)!==`avatar`||!w||(he(`overview`),oe||!A?.agents.some(e=>e.id===w)))return;let e=window.setTimeout(()=>{document.getElementById(`agent-avatar-settings`)?.scrollIntoView({behavior:`smooth`,block:`center`}),S(e=>{let t=new URLSearchParams(e);return t.delete(`focus`),t},{replace:!0})},220);return()=>window.clearTimeout(e)},[x,w,oe,A,S]);let X=(0,W.useMemo)(()=>A?.agents.find(e=>e.id===M)??null,[A,M]),Mn=(0,W.useMemo)(()=>X?tn.filter(e=>e.agentId.toLowerCase()===X.id.toLowerCase()):[],[tn,X?.id]),Nn=(0,W.useMemo)(()=>!A||!X?[]:Sn.filter(e=>Vt(e,X.id,A.defaultId)),[Sn,A,X?.id]),Pn=(0,W.useMemo)(()=>En.filter(e=>e.enabled!==!1),[En]);(0,W.useEffect)(()=>{if(!X){We(``),Ke(``),Je(``),Xe(``);return}We(X.workspace),Ke(X.model?.primary??``),Je(ot(X,rt(e).agentsSettings)),Xe(X.description?.trim()??``)},[X?.id,e]),(0,W.useEffect)(()=>{if(F!==`files`||!M||!b)return;let e=!1;return st(!0),m(M).then(t=>{e||et(t)}).catch(()=>{e||et(null)}).finally(()=>{e||st(!1)}),()=>{e=!0}},[F,M,b,A?.agents.length]),(0,W.useEffect)(()=>{!X||F!==`tools`||J(new Set(X.tools.entryDisable))},[F,X]),(0,W.useEffect)(()=>{if(!X||F!==`skills`)return;let e=X.skills.entry===void 0;if(en(e),e){let e=X.skills.effectiveAllowlist;Y(new Set(e??[]))}else Y(new Set(X.skills.entry??[]))},[F,X]),(0,W.useEffect)(()=>{F!==`channels`||!b||nn(k)},[F,b,k]),(0,W.useEffect)(()=>{if(F!==`channels`||!b)return;let e=!1;return ln(!0),mt().then(t=>{e||sn(t)}).catch(()=>{e||sn([])}).finally(()=>{e||ln(!1)}),()=>{e=!0}},[F,b]),(0,W.useEffect)(()=>{cn||F!==`channels`||on.length===0||an(e=>e&&on.some(t=>t.name===e)?e:on[0].name)},[cn,F,on]),(0,W.useEffect)(()=>{if(F!==`channels`||!b)return;let e=rn.trim();if(!e){dn([]);return}let t=!1;return hn(null),pn(!0),ht(e).then(e=>{t||dn(e)}).catch(()=>{t||dn([])}).finally(()=>{t||pn(!1)}),()=>{t=!0}},[F,b,rn]);let Fn=(0,W.useCallback)(()=>{let e=rn.trim();e&&(pn(!0),ht(e).then(e=>{dn(e),hn(t=>t!=null&&t<e.length?t:null)}).catch(()=>{dn([]),hn(null)}).finally(()=>{pn(!1)}))},[rn]),In=!cn&&on.length===0,Ln=F===`channels`&&b&&re===void 0;(0,W.useEffect)(()=>{if(F!==`cron`||!b)return;let e=!1;return Tn(!0),gt().then(t=>{e||Cn(t)}).catch(()=>{e||Cn([])}).finally(()=>{e||Tn(!1)}),()=>{e=!0}},[F,b]),(0,W.useEffect)(()=>{if(F!==`skills`||!b)return;let e=!1;return kn(!0),ie().then(t=>{e||Dn(t)}).catch(()=>{e||Dn([])}).finally(()=>{e||kn(!1)}),()=>{e=!0}},[F,b]),(0,W.useEffect)(()=>{if(!U||!M||!b)return;let e=!1;return q.flush(),xt(!0),de(M,U).then(t=>{e||(K.current=`${M}:${U}`,Ht.current=t,ft(t),Ct(e=>e+1))}).catch(()=>{e||(K.current=`${M}:${U}`,Ht.current=``,ft(``),Ct(e=>e+1))}).finally(()=>{e||xt(!1)}),()=>{e=!0}},[U,M,b,q]),(0,W.useEffect)(()=>{!U||!M||bt||q()},[ut,U,M,bt,q]),(0,W.useEffect)(()=>{if(F===`files`)return()=>{q.flush()}},[F,q]),(0,W.useEffect)(()=>{yt(`edit`)},[U,M]);let Rn=(0,W.useCallback)(()=>{let e=Et(I.trim()||ge);we(t=>t===``||t===Ie.current?(Ie.current=e,e):t)},[I,ge]),zn=(0,W.useCallback)(()=>{Ie.current=``,be(``),xe(``),L(``),we(``),De(``),je(null),Pe(!0)},[]),Bn=(0,W.useCallback)(e=>new Promise(t=>window.setTimeout(t,e)),[]),Vn=(0,W.useCallback)(async()=>{if(V||z)return;ze(!0),j(null);let e=[`light`,`deep`,`rem`];try{(async()=>{for(let t of e)try{await At(t)}catch{}})();for(let t=0;t<e.length;t++){let n=e[t];window.dispatchEvent(new CustomEvent(`dreaming-phase-start`,{detail:{phase:n,source:`ui`}})),await Bn(n===`light`?7e3:n===`deep`?9e3:8e3),t===e.length-1&&(window.__xopcDreamingIgnoreSseUntil=Date.now()+6e4,window.dispatchEvent(new CustomEvent(`dreaming-phase-end`,{detail:{phase:n,source:`ui`}})))}}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{ze(!1)}},[n.saveError,z,V,Bn]),Hn=(0,W.useMemo)(()=>(0,G.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-wrap items-center justify-end gap-2`,children:[(0,G.jsxs)(N,{type:`button`,variant:`secondary`,className:`shrink-0 gap-2`,disabled:z||V,onClick:()=>void Vn(),"aria-label":e===`zh`?`让智能体进入睡眠流程`:`Trigger agent sleep sequence`,title:e===`zh`?`由浅入深:Light → Deep → REM`:`Light → Deep → REM`,children:[(0,G.jsx)(qe,{className:`size-4 shrink-0`,strokeWidth:1.75,"aria-hidden":!0}),e===`zh`?V?`睡眠中…`:`睡眠`:V?`Sleeping…`:`Sleep`]}),(0,G.jsxs)(`label`,{className:`relative flex min-h-9 min-w-0 max-w-sm cursor-text items-center rounded-pill border border-edge bg-surface-base py-1.5 pl-9 pr-3 shadow-surface dark:bg-surface-hover/40 sm:max-w-md`,children:[(0,G.jsx)(ve,{className:`pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-fg-disabled`,strokeWidth:1.75,"aria-hidden":!0}),(0,G.jsx)(`input`,{type:`search`,role:`searchbox`,enterKeyHint:`search`,value:Be,onChange:e=>He(e.target.value),placeholder:n.listSearchPlaceholder,autoComplete:`off`,spellCheck:!1,"aria-label":n.listSearchPlaceholder,className:`min-w-0 flex-1 appearance-none border-0 bg-transparent py-0.5 text-sm leading-normal text-fg caret-current placeholder:text-fg-disabled focus:border-0 focus:shadow-none focus:outline-none focus:ring-0 focus-visible:outline-none`})]}),(0,G.jsxs)(N,{type:`button`,variant:`primary`,className:`shrink-0 gap-2`,"aria-label":n.addAgentAria,disabled:z,onClick:()=>zn(),children:[(0,G.jsx)(Ee,{className:`size-4`,strokeWidth:1.75,"aria-hidden":!0}),n.addAgent]})]}),[n.addAgent,n.addAgentAria,n.listSearchPlaceholder,z,Be,zn,V,Vn,e]);(0,W.useLayoutEffect)(()=>b?(T({startExtra:null,main:null,end:Hn}),()=>ee()):(ee(),()=>ee()),[Hn,ee,b,T]);async function Un(e){e.preventDefault();let t=ge.trim();if(!t)return;let r=Tt(I,t);if(r.ok===!1){je(r.error);return}let i=Ce.trim()||Et(I.trim()||t);if(i){B(!0),je(null);try{let e=Se.trim(),{createdAgentId:n,...r}=await le({name:t,workspace:i,...I.trim()?{id:I.trim()}:{},...R.trim()?{model:R.trim()}:{},...e?{description:e}:{}});O(r,{revalidate:!1}),be(``),xe(``),L(``),we(``),De(``),je(null),Pe(!1),P(n),C(ct(n))}catch(e){je(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}}async function Z(){if(X){B(!0),j(null);try{let e=Ye.trim();O(await E(X.id,{name:H.trim()||void 0,description:e.length>0?e:null,workspace:Ue.trim()||void 0,model:Ge.trim()||null}),{revalidate:!1})}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}}async function Wn(e){B(!0),j(null);try{O(await E(e.id,{setDefault:!0}),{revalidate:!1}),P(e.id)}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}async function Q(e,t){B(!0),j(null);try{let n=await nt(e.id,t);O(n,{revalidate:!1}),P(n.defaultId),he(`overview`),w===e.id&&C($e,{replace:!0}),o(!1),l(null),_(``)}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}function Gn(e,t){e.id!==`main`&&(l(e),d(t),_(``),o(!0))}async function Kn(){if(X){B(!0),j(null);try{let e=[...Jt].sort((e,t)=>e.localeCompare(t));O(await E(X.id,{toolsDisable:e}),{revalidate:!1})}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}}async function qn(){if(X){B(!0),j(null);try{O(await E(X.id,{toolsDisable:null}),{revalidate:!1}),J(new Set)}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}}async function Jn(){if(X){B(!0),j(null);try{O(await E(X.id,{skills:Xt?null:[...Yt].sort((e,t)=>e.localeCompare(t))}),{revalidate:!1})}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}}async function Yn(e){B(!0),j(null);try{let t=tn.filter(t=>t!==e);await s(t),nn(t)}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}async function Xn(e){if(e.preventDefault(),!X||!rn.trim())return;let t=Ut(rn,gn,mn,un),r=[...tn,{agentId:X.id,priority:100,enabled:!0,match:t}];B(!0),j(null);try{await s(r),nn(r),hn(null),xn(``)}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}async function Zn(e,t){B(!0),j(null);try{await dt(e.id,{agentId:t===``?null:t}),Cn(await gt())}catch(e){j(e instanceof Error?e.message:n.saveError)}finally{B(!1)}}let $=F===`channels`||F===`cron`,Qn=(()=>{if(!X||F!==`overview`)return!1;let e=ot(X,n),t=X.description?.trim()??``,r=X.workspace,i=X.model?.primary??``;return H.trim()!==e||Ye.trim()!==t||Ue.trim()!==r||Ge.trim()!==i})(),$n=(()=>{if($)return!1;switch(F){case`overview`:return Qn||Mt;case`profile`:return Pt;default:return!0}})(),er=$||!$n;function tr(){Rt(!0),setTimeout(()=>Rt(!1),2e3)}async function nr(){switch(F){case`overview`:await Promise.all([Z(),kt.current?.()??Promise.resolve()]),tr();break;case`profile`:await jt.current?.(),tr();break;case`tools`:await Kn(),tr();break;case`skills`:await Jn(),tr();break;case`files`:q.flush(),tr();break;default:break}}function rr(e){e||C($e)}let ir=X?H.trim()||ot(X,n):w??``,ar=X?.id??w??``;if(!b)return(0,G.jsxs)(`div`,{className:`mx-auto flex w-full max-w-app-main flex-col gap-3 px-4 py-8`,children:[(0,G.jsx)(`h1`,{className:`text-lg font-semibold text-fg`,children:n.title}),(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:n.needToken})]});if(pe&&A)return(0,G.jsx)(`div`,{className:`mx-auto flex w-full max-w-app-main flex-col px-4 py-8`,children:(0,G.jsx)(Kt,{existingAgentIds:new Set(A.agents.map(e=>e.id)),onComplete:An,onSkip:jn})});let or=X?F===`overview`?(0,G.jsx)(_n,{a:n,chat:y,selected:X,busy:z,editName:H,setEditName:Je,editDescription:Ye,setEditDescription:Xe,editWorkspace:Ue,setEditWorkspace:We,editModel:Ge,setEditModel:Ke,onSetDefault:()=>void Wn(X),onSaveAgentEdits:()=>void Z(),onDelete:e=>void Gn(X,e),hideInlineSave:!0,saveBootstrapRef:kt,onBootstrapDirtyChange:Nt}):F===`profile`?(0,G.jsx)(vn,{a:n,agentId:X.id,saveRef:jt,onDirtyChange:Ft}):F===`files`?(0,G.jsx)($t,{a:n,filesLoading:it,files:Qe,activeFile:U,setActiveFile:lt,bootstrapViewMode:vt,setBootstrapViewMode:yt,fileDraft:ut,setFileDraft:ft,fileSaving:pt,bootstrapFileLoading:bt,bootstrapEditorNonce:St}):F===`tools`?(0,G.jsx)(bn,{a:n,data:A,selected:X,busy:z,toolEntryDisable:Jt,setToolEntryDisable:J,onSaveTools:()=>void Kn(),onClearToolsEntry:()=>void qn(),hideInlineSave:!0}):F===`skills`?(0,G.jsx)(yn,{a:n,selected:X,busy:z,skillsCatalogLoading:On,catalogForPick:Pn,skillsInherit:Xt,setSkillsInherit:en,skillsPick:Yt,setSkillsPick:Y,onSaveSkills:()=>void Jn(),hideInlineSave:!0}):F===`channels`?(0,G.jsx)(Zt,{a:n,busy:z,bindingsLoading:Ln,agentBindings:Mn,channelStatuses:on,channelsStatusLoading:cn,useManualChannel:In,newBindChannel:rn,setNewBindChannel:an,bindSessionChats:un,sessionsLoading:fn,newBindSessionIdx:mn,setNewBindSessionIdx:hn,newBindCustomPeer:gn,setNewBindCustomPeer:xn,onRefreshSessions:Fn,lastActiveLabels:v.lastActiveLabels,selectRecipient:v.selectRecipient,onRemoveBinding:e=>void Yn(e),onAddBinding:Xn}):F===`cron`&&A?(0,G.jsx)(Qt,{a:n,data:A,selected:X,busy:z,cronLoading:wn,agentCronJobs:Nn,onSetCronJobAgent:(e,t)=>void Zn(e,t)}):(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:n.selectAgentHint}):(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:n.selectAgentHint});return(0,G.jsxs)(`div`,{className:`mx-auto flex w-full max-w-app-main flex-col gap-6 px-4 py-8`,children:[(0,G.jsx)(Bt,{a:n}),ue?(0,G.jsx)(`div`,{className:`rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-200`,children:ue}):null,oe?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:n.loading}):A?(0,G.jsx)(zt,{a:n,agents:A.agents,searchQuery:Be,onOpenAgent:e=>C(ct(e)),onChatWithAgent:e=>C(`/chat/new`,{state:{agentId:e.trim().toLowerCase()}}),onNewAgent:zn,busy:z}):null,w&&b?(0,G.jsx)(It,{open:!!w,onOpenChange:rr,a:n,title:ir,subtitle:ar,panel:F,onPanelChange:he,onFooterSave:()=>void nr(),footerSaveDisabled:er,footerSavedFlash:Lt,busy:z,children:oe||!A?(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:n.loading}):or}):null,(0,G.jsx)(Wt,{open:Me,onOpenChange:e=>{Pe(e),e||(Ie.current=``,be(``),xe(``),L(``),we(``),De(``),je(null))},a:n,chat:y,busy:z,modalError:Ae,createDisplayName:ge,setCreateDisplayName:be,createAgentId:I,setCreateAgentId:xe,createDescription:Se,setCreateDescription:L,createWorkspace:Ce,setCreateWorkspace:we,createModel:R,setCreateModel:De,onCreate:Un,onSuggestWorkspace:()=>Rn()}),(0,G.jsx)(ae,{open:a,onOpenChange:e=>{o(e),e||(l(null),_(``))},children:(0,G.jsxs)(p,{children:[(0,G.jsx)(g,{className:`fixed inset-0 z-[80] bg-scrim backdrop-blur-[2px]`}),(0,G.jsxs)(at,{className:i(`fixed left-1/2 top-1/2 z-[81] w-[min(100%-2rem,28rem)] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-edge bg-surface-panel p-4 shadow-popover`,`dark:border-edge`),onOpenAutoFocus:e=>e.preventDefault(),children:[(0,G.jsx)(Le,{className:`text-base font-semibold text-fg`,children:u?n.purgeDisk:n.removeFromConfig}),(0,G.jsx)(fe,{className:`mt-2 whitespace-pre-wrap text-sm leading-relaxed text-fg-muted`,children:u?n.confirmDeletePurge:n.confirmDelete}),u&&c?(0,G.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,G.jsx)(`label`,{className:`mb-2 block text-sm font-medium text-fg`,htmlFor:`agent-delete-confirm`,children:n.purgeConfirmLabel}),(0,G.jsx)(`input`,{id:`agent-delete-confirm`,type:`text`,autoComplete:`off`,spellCheck:!1,className:i(`w-full rounded-md border border-edge bg-surface-panel px-3 py-1.5 font-mono text-xs text-fg`,`placeholder:text-fg-subtle`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-surface-panel`,`dark:border-edge`),placeholder:n.purgeConfirmPlaceholder.replace(`{{agentId}}`,c.id),value:h,onChange:e=>_(e.target.value)}),(0,G.jsx)(`p`,{className:`pt-0.5 text-xs text-fg-muted`,children:n.purgeConfirmHint.replace(`{{agentId}}`,c.id)})]}):null,(0,G.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center justify-end gap-2 border-t border-edge-subtle/60 pt-3`,children:[(0,G.jsx)(N,{type:`button`,variant:`ghost`,disabled:z,onClick:()=>o(!1),children:n.createModalCancel}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:u?`border-red-200 text-red-700 hover:bg-red-50 dark:border-red-900/60 dark:text-red-300 dark:hover:bg-red-950/40`:void 0,disabled:z||!c||u&&h.trim().toLowerCase()!==c.id.toLowerCase(),onClick:()=>{c&&Q(c,u)},children:u?n.purgeDisk:n.removeFromConfig})]})]})]})})]})}var Sn={enabled:!0,mode:`default`,reserveTokens:8e3,triggerThreshold:.8,minMessagesBeforeCompact:10,keepRecentMessages:5,evictionWindow:.2,retentionWindow:6},Cn={enabled:!0,maxToolResultChars:1e4,headKeepRatio:.3,tailKeepRatio:.3},wn={enabled:!0,useEnhancedSystem:!0,userProfileEnabled:!0,provider:``,injectionFrequency:``,memoryCharLimit:void 0,userCharLimit:void 0,contextCadence:void 0,dialecticCadence:void 0},Tn={summaryModel:``},En={enabled:!1,memoryNudgeInterval:10,skillNudgeInterval:10,maxToolRounds:8,maxHistoryMessages:80,maxDurationMs:12e4},Dn={model:``,maxLength:void 0};function On(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`object`&&e&&`primary`in e){let t=e.primary;return typeof t==`string`?t:``}return``}function kn(e){if(typeof e!=`object`||!e||!(`fallbacks`in e))return[];let t=e.fallbacks;return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function An(e){return e===!0||e===`true`||e===1}function jn(e){let t=e.browser;if(!t||typeof t!=`object`||Array.isArray(t))return{browserEnabled:!1,browserHeadless:!0};let n=t,r=An(n.enabled),i=n.headless;return{browserEnabled:r,browserHeadless:!(i===!1||i===`false`||i===0)}}function X(e){if(!e||typeof e!=`object`||Array.isArray(e))return{...Sn};let t=e;return{enabled:typeof t.enabled==`boolean`?t.enabled:Sn.enabled,mode:t.mode===`safeguard`?`safeguard`:`default`,reserveTokens:typeof t.reserveTokens==`number`&&Number.isFinite(t.reserveTokens)?Math.floor(t.reserveTokens):Sn.reserveTokens,triggerThreshold:typeof t.triggerThreshold==`number`&&Number.isFinite(t.triggerThreshold)?t.triggerThreshold:Sn.triggerThreshold,minMessagesBeforeCompact:typeof t.minMessagesBeforeCompact==`number`&&Number.isFinite(t.minMessagesBeforeCompact)?Math.floor(t.minMessagesBeforeCompact):Sn.minMessagesBeforeCompact,keepRecentMessages:typeof t.keepRecentMessages==`number`&&Number.isFinite(t.keepRecentMessages)?Math.floor(t.keepRecentMessages):Sn.keepRecentMessages,evictionWindow:typeof t.evictionWindow==`number`&&Number.isFinite(t.evictionWindow)?t.evictionWindow:Sn.evictionWindow,retentionWindow:typeof t.retentionWindow==`number`&&Number.isFinite(t.retentionWindow)?Math.floor(t.retentionWindow):Sn.retentionWindow}}function Mn(e){if(!e||typeof e!=`object`||Array.isArray(e))return{...Cn};let t=e;return{enabled:typeof t.enabled==`boolean`?t.enabled:Cn.enabled,maxToolResultChars:typeof t.maxToolResultChars==`number`&&Number.isFinite(t.maxToolResultChars)?Math.floor(t.maxToolResultChars):Cn.maxToolResultChars,headKeepRatio:typeof t.headKeepRatio==`number`&&Number.isFinite(t.headKeepRatio)?t.headKeepRatio:Cn.headKeepRatio,tailKeepRatio:typeof t.tailKeepRatio==`number`&&Number.isFinite(t.tailKeepRatio)?t.tailKeepRatio:Cn.tailKeepRatio}}function Nn(e){if(!e||typeof e!=`object`||Array.isArray(e))return{...wn};let t=e,n=t.provider,r=n===`none`||n===`stub`?n:``,i=t.injectionFrequency,a=i===`every-turn`||i===`first-turn`?i:``;return{enabled:typeof t.enabled==`boolean`?t.enabled:wn.enabled,useEnhancedSystem:typeof t.useEnhancedSystem==`boolean`?t.useEnhancedSystem:wn.useEnhancedSystem,userProfileEnabled:typeof t.userProfileEnabled==`boolean`?t.userProfileEnabled:wn.userProfileEnabled,provider:r,injectionFrequency:a,memoryCharLimit:typeof t.memoryCharLimit==`number`&&t.memoryCharLimit>0?Math.floor(t.memoryCharLimit):void 0,userCharLimit:typeof t.userCharLimit==`number`&&t.userCharLimit>0?Math.floor(t.userCharLimit):void 0,contextCadence:typeof t.contextCadence==`number`&&t.contextCadence>=1?Math.floor(t.contextCadence):void 0,dialecticCadence:typeof t.dialecticCadence==`number`&&t.dialecticCadence>=1?Math.floor(t.dialecticCadence):void 0}}function Pn(e){if(!e||typeof e!=`object`||Array.isArray(e))return{...Tn};let t=e;return{summaryModel:typeof t.summaryModel==`string`?t.summaryModel:``}}function Fn(e){if(!e||typeof e!=`object`||Array.isArray(e))return{...En};let t=e;return{enabled:typeof t.enabled==`boolean`?t.enabled:En.enabled,memoryNudgeInterval:typeof t.memoryNudgeInterval==`number`&&t.memoryNudgeInterval>=0?Math.floor(t.memoryNudgeInterval):En.memoryNudgeInterval,skillNudgeInterval:typeof t.skillNudgeInterval==`number`&&t.skillNudgeInterval>=0?Math.floor(t.skillNudgeInterval):En.skillNudgeInterval,maxToolRounds:typeof t.maxToolRounds==`number`&&t.maxToolRounds>=1&&t.maxToolRounds<=32?Math.floor(t.maxToolRounds):En.maxToolRounds,maxHistoryMessages:typeof t.maxHistoryMessages==`number`&&t.maxHistoryMessages>=10&&t.maxHistoryMessages<=200?Math.floor(t.maxHistoryMessages):En.maxHistoryMessages,maxDurationMs:typeof t.maxDurationMs==`number`&&t.maxDurationMs>=3e4&&t.maxDurationMs<=6e5?Math.floor(t.maxDurationMs):En.maxDurationMs}}function In(e){if(!e||typeof e!=`object`||Array.isArray(e))return{...Dn};let t=e;return{model:typeof t.model==`string`?t.model:``,maxLength:typeof t.maxLength==`number`&&t.maxLength>0?t.maxLength:void 0}}function Ln(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return{enabled:t};let n=e;return{enabled:typeof n.enabled==`boolean`?n.enabled:t}}function Rn(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function zn(e){if(e==null)return``;if(typeof e==`object`&&!Array.isArray(e))try{return JSON.stringify(e,null,2)}catch{return``}return``}function Bn(e){let t=e&&typeof e==`object`&&!Array.isArray(e)&&`agents`in e?e.agents:void 0,n=t&&typeof t==`object`&&!Array.isArray(t)&&`defaults`in t?t.defaults:void 0,r=n&&typeof n==`object`&&!Array.isArray(n)?n:{},i=r.modelFallbacks,a=Array.isArray(i)&&i.every(e=>typeof e==`string`)?i:kn(r.model),o=r.imageModelFallbacks,s=Array.isArray(o)&&o.every(e=>typeof e==`string`)?o:kn(r.imageModel),c=r.imageGenerationModelFallbacks,l=Array.isArray(c)&&c.every(e=>typeof e==`string`)?c:kn(r.imageGenerationModel),{browserEnabled:u,browserHeadless:d}=jn(r),f=typeof r.maxTaskDurationMs==`number`&&Number.isFinite(r.maxTaskDurationMs)?r.maxTaskDurationMs:void 0,p=f===void 0?void 0:Math.round(f/6e4);return{model:On(r.model),modelFallbacks:a,imageModel:On(r.imageModel),imageModelFallbacks:s,imageGenerationModel:On(r.imageGenerationModel),imageGenerationModelFallbacks:l,mediaMaxMb:typeof r.mediaMaxMb==`number`&&!Number.isNaN(r.mediaMaxMb)?r.mediaMaxMb:void 0,maxTokens:typeof r.maxTokens==`number`?r.maxTokens:8192,temperature:typeof r.temperature==`number`?r.temperature:.7,maxToolIterations:typeof r.maxToolIterations==`number`?r.maxToolIterations:20,maxTaskDurationMinutes:p,maxRequestsPerTurn:typeof r.maxRequestsPerTurn==`number`?r.maxRequestsPerTurn:50,maxToolFailuresPerTurn:typeof r.maxToolFailuresPerTurn==`number`?r.maxToolFailuresPerTurn:3,workspace:typeof r.workspace==`string`?r.workspace:`~/.xopc/workspace`,browserEnabled:u,browserHeadless:d,thinkingDefault:typeof r.thinkingDefault==`string`?r.thinkingDefault:`medium`,reasoningDefault:typeof r.reasoningDefault==`string`?r.reasoningDefault:`stream`,verboseDefault:typeof r.verboseDefault==`string`?r.verboseDefault:`full`,compaction:X(r.compaction),pruning:Mn(r.pruning),memory:Nn(r.memory),sessionSearch:Pn(r.sessionSearch),backgroundReview:Fn(r.backgroundReview),webExtract:In(r.webExtract),delegate:Ln(r.delegate,!1),executeCode:Ln(r.executeCode,!1),systemPromptOverride:typeof r.systemPromptOverride==`string`?r.systemPromptOverride:``,skillsAllowlist:Rn(r.skills),toolsDisable:(()=>{let e=r.tools;if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.disable;return Rn(t)})(),paramsJson:zn(r.params)}}function Vn(e){let t={enabled:e.enabled,useEnhancedSystem:e.useEnhancedSystem,userProfileEnabled:e.userProfileEnabled};return e.provider===`none`||e.provider===`stub`?t.provider=e.provider:t.provider=null,e.injectionFrequency===`every-turn`||e.injectionFrequency===`first-turn`?t.injectionFrequency=e.injectionFrequency:t.injectionFrequency=null,t.memoryCharLimit=e.memoryCharLimit??null,t.userCharLimit=e.userCharLimit??null,t.contextCadence=e.contextCadence??null,t.dialecticCadence=e.dialecticCadence??null,t}function Hn(e){let t=e.trim();if(!t)return null;let n=JSON.parse(t);if(n===null)return null;if(typeof n!=`object`||Array.isArray(n))throw Error(`params must be a JSON object`);return n}async function Un(e){let t=e.modelFallbacks.map(e=>e.trim()).filter(Boolean),n=t.length>0?{primary:e.model,fallbacks:t}:e.model,r=e.imageModelFallbacks.map(e=>e.trim()).filter(Boolean),i=r.length>0&&e.imageModel.trim()?{primary:e.imageModel.trim(),fallbacks:r}:e.imageModel||``,a=e.imageGenerationModelFallbacks.map(e=>e.trim()).filter(Boolean),o=a.length>0&&e.imageGenerationModel.trim()?{primary:e.imageGenerationModel.trim(),fallbacks:a}:e.imageGenerationModel||``,s=e.maxTaskDurationMinutes===void 0||e.maxTaskDurationMinutes===null?null:(()=>{let t=Math.floor(e.maxTaskDurationMinutes)*6e4;return t<6e4||t>144e5?null:t})(),c=e.skillsAllowlist.map(e=>e.trim()).filter(Boolean),l=e.toolsDisable.map(e=>e.trim()).filter(Boolean),u=Hn(e.paramsJson),d=u===null||Object.keys(u).length===0?null:u,f={model:n,imageModel:i,imageGenerationModel:o,mediaMaxMb:e.mediaMaxMb??null,maxTokens:e.maxTokens,temperature:e.temperature,maxToolIterations:e.maxToolIterations,maxTaskDurationMs:s,maxRequestsPerTurn:e.maxRequestsPerTurn,maxToolFailuresPerTurn:e.maxToolFailuresPerTurn,workspace:e.workspace,browser:{enabled:e.browserEnabled,headless:e.browserHeadless},thinkingDefault:e.thinkingDefault,reasoningDefault:e.reasoningDefault,verboseDefault:e.verboseDefault,compaction:{...e.compaction},pruning:{...e.pruning},memory:Vn(e.memory),sessionSearch:{summaryModel:e.sessionSearch.summaryModel.trim()||null},backgroundReview:{enabled:e.backgroundReview.enabled,memoryNudgeInterval:e.backgroundReview.memoryNudgeInterval,skillNudgeInterval:e.backgroundReview.skillNudgeInterval,maxToolRounds:e.backgroundReview.maxToolRounds,maxHistoryMessages:e.backgroundReview.maxHistoryMessages,maxDurationMs:e.backgroundReview.maxDurationMs},webExtract:{model:e.webExtract.model.trim()||null,maxLength:e.webExtract.maxLength??null},delegate:{enabled:e.delegate.enabled},executeCode:{enabled:e.executeCode.enabled},systemPromptOverride:e.systemPromptOverride.trim()||null,skills:c.length>0?c:null,tools:{disable:l.length>0?l:null},params:d};await B(H(`/api/config`),{method:`PATCH`,body:JSON.stringify({agents:{defaults:f}})}),I()}function Z(){return i(`w-full rounded-lg border border-edge bg-surface-panel px-3 py-2 text-sm text-fg`,`placeholder:text-fg-subtle`,u,`dark:border-edge`)}function Wn(){return i(ue,Ce)}function Q({label:e,description:t,children:n}){return(0,G.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,G.jsx)(`div`,{className:`text-sm font-medium text-fg`,children:e}),n,(0,G.jsx)(`p`,{className:`text-xs leading-relaxed text-fg-subtle`,children:t})]})}function Gn(e){let{a:t,chat:n,form:r,update:a}=e,o=t.advanced;return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:T,title:o.cardLimitsTitle,subtitle:o.cardLimitsSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)(Q,{label:o.maxTaskDurationMs,description:o.maxTaskDurationMsDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,max:240,step:1,value:r.maxTaskDurationMinutes??``,placeholder:o.maxTaskDurationPlaceholder,onChange:e=>{let t=e.target.value;if(t===``){a({maxTaskDurationMinutes:void 0});return}let n=Number.parseInt(t,10);Number.isNaN(n)||a({maxTaskDurationMinutes:Math.min(240,Math.max(1,n))})}})}),(0,G.jsxs)(`div`,{className:`grid gap-5 sm:grid-cols-2`,children:[(0,G.jsx)(Q,{label:o.maxRequestsPerTurn,description:o.maxRequestsPerTurnDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:10,max:200,value:r.maxRequestsPerTurn,onChange:e=>a({maxRequestsPerTurn:Number.parseInt(e.target.value,10)||50})})}),(0,G.jsx)(Q,{label:o.maxToolFailuresPerTurn,description:o.maxToolFailuresPerTurnDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,max:20,value:r.maxToolFailuresPerTurn,onChange:e=>a({maxToolFailuresPerTurn:Number.parseInt(e.target.value,10)||3})})})]})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:M,title:o.cardCompactionTitle,subtitle:o.cardCompactionSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)(Q,{label:o.compactionEnabled,description:o.compactionEnabledDesc,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:r.compaction.enabled,onChange:e=>a({compaction:{...r.compaction,enabled:e.target.checked}})}),(0,G.jsx)(`span`,{children:o.compactionEnabledOn})]})}),(0,G.jsxs)(`div`,{className:`grid gap-5 sm:grid-cols-2`,children:[(0,G.jsx)(Q,{label:o.compactionMode,description:o.compactionModeDesc,children:(0,G.jsxs)(`select`,{className:Wn(),value:r.compaction.mode,onChange:e=>a({compaction:{...r.compaction,mode:e.target.value}}),children:[(0,G.jsx)(`option`,{value:`default`,children:o.compactionModeDefault}),(0,G.jsx)(`option`,{value:`safeguard`,children:o.compactionModeSafeguard})]})}),(0,G.jsx)(Q,{label:o.reserveTokens,description:o.reserveTokensDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1e3,value:r.compaction.reserveTokens,onChange:e=>a({compaction:{...r.compaction,reserveTokens:Number.parseInt(e.target.value,10)||0}})})}),(0,G.jsx)(Q,{label:o.triggerThreshold,description:o.triggerThresholdDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:.5,max:.95,step:.05,value:r.compaction.triggerThreshold,onChange:e=>a({compaction:{...r.compaction,triggerThreshold:Number.parseFloat(e.target.value)||.8}})})}),(0,G.jsx)(Q,{label:o.minMessagesBeforeCompact,description:o.minMessagesBeforeCompactDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,value:r.compaction.minMessagesBeforeCompact,onChange:e=>a({compaction:{...r.compaction,minMessagesBeforeCompact:Number.parseInt(e.target.value,10)||10}})})}),(0,G.jsx)(Q,{label:o.keepRecentMessages,description:o.keepRecentMessagesDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:0,value:r.compaction.keepRecentMessages,onChange:e=>a({compaction:{...r.compaction,keepRecentMessages:Number.parseInt(e.target.value,10)||5}})})}),(0,G.jsx)(Q,{label:o.evictionWindow,description:o.evictionWindowDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:.1,max:.5,step:.05,value:r.compaction.evictionWindow,onChange:e=>a({compaction:{...r.compaction,evictionWindow:Number.parseFloat(e.target.value)||.2}})})}),(0,G.jsx)(Q,{label:o.retentionWindow,description:o.retentionWindowDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:3,max:20,value:r.compaction.retentionWindow,onChange:e=>a({compaction:{...r.compaction,retentionWindow:Number.parseInt(e.target.value,10)||6}})})})]})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:he,title:o.cardPruningTitle,subtitle:o.cardPruningSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)(Q,{label:o.pruningEnabled,description:o.pruningEnabledDesc,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:r.pruning.enabled,onChange:e=>a({pruning:{...r.pruning,enabled:e.target.checked}})}),(0,G.jsx)(`span`,{children:o.pruningEnabledOn})]})}),(0,G.jsxs)(`div`,{className:`grid gap-5 sm:grid-cols-2`,children:[(0,G.jsx)(Q,{label:o.maxToolResultChars,description:o.maxToolResultCharsDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1e3,value:r.pruning.maxToolResultChars,onChange:e=>a({pruning:{...r.pruning,maxToolResultChars:Number.parseInt(e.target.value,10)||1e4}})})}),(0,G.jsx)(Q,{label:o.headKeepRatio,description:o.headKeepRatioDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:0,max:1,step:.05,value:r.pruning.headKeepRatio,onChange:e=>a({pruning:{...r.pruning,headKeepRatio:Number.parseFloat(e.target.value)||.3}})})}),(0,G.jsx)(Q,{label:o.tailKeepRatio,description:o.tailKeepRatioDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:0,max:1,step:.05,value:r.pruning.tailKeepRatio,onChange:e=>a({pruning:{...r.pruning,tailKeepRatio:Number.parseFloat(e.target.value)||.3}})})})]})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:Je,title:o.cardMemoryTitle,subtitle:o.cardMemorySubtitle}),(0,G.jsx)(`div`,{className:`flex flex-col gap-5`,children:(0,G.jsxs)(`div`,{className:`grid gap-5 sm:grid-cols-2`,children:[(0,G.jsx)(Q,{label:o.memoryEnabled,description:o.memoryEnabledDesc,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:r.memory.enabled,onChange:e=>a({memory:{...r.memory,enabled:e.target.checked}})}),(0,G.jsx)(`span`,{children:o.memoryEnabledOn})]})}),(0,G.jsx)(Q,{label:o.useEnhancedSystem,description:o.useEnhancedSystemDesc,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:r.memory.useEnhancedSystem,onChange:e=>a({memory:{...r.memory,useEnhancedSystem:e.target.checked}})}),(0,G.jsx)(`span`,{children:o.useEnhancedSystemOn})]})}),(0,G.jsx)(Q,{label:o.userProfileEnabled,description:o.userProfileEnabledDesc,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:r.memory.userProfileEnabled,onChange:e=>a({memory:{...r.memory,userProfileEnabled:e.target.checked}})}),(0,G.jsx)(`span`,{children:o.userProfileEnabledOn})]})}),(0,G.jsx)(Q,{label:o.memoryProvider,description:o.memoryProviderDesc,children:(0,G.jsxs)(`select`,{className:Wn(),value:r.memory.provider,onChange:e=>a({memory:{...r.memory,provider:e.target.value}}),children:[(0,G.jsx)(`option`,{value:``,children:o.memoryProviderUnset}),(0,G.jsx)(`option`,{value:`none`,children:`none`}),(0,G.jsx)(`option`,{value:`stub`,children:`stub`})]})}),(0,G.jsx)(Q,{label:o.injectionFrequency,description:o.injectionFrequencyDesc,children:(0,G.jsxs)(`select`,{className:Wn(),value:r.memory.injectionFrequency,onChange:e=>a({memory:{...r.memory,injectionFrequency:e.target.value}}),children:[(0,G.jsx)(`option`,{value:``,children:o.injectionFrequencyUnset}),(0,G.jsx)(`option`,{value:`every-turn`,children:o.injectionEveryTurn}),(0,G.jsx)(`option`,{value:`first-turn`,children:o.injectionFirstTurn})]})}),(0,G.jsx)(Q,{label:o.memoryCharLimit,description:o.memoryCharLimitDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,value:r.memory.memoryCharLimit??``,placeholder:`—`,onChange:e=>{let t=e.target.value;a({memory:{...r.memory,memoryCharLimit:t===``?void 0:Number.parseInt(t,10)}})}})}),(0,G.jsx)(Q,{label:o.userCharLimit,description:o.userCharLimitDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,value:r.memory.userCharLimit??``,placeholder:`—`,onChange:e=>{let t=e.target.value;a({memory:{...r.memory,userCharLimit:t===``?void 0:Number.parseInt(t,10)}})}})}),(0,G.jsx)(Q,{label:o.contextCadence,description:o.contextCadenceDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,value:r.memory.contextCadence??``,placeholder:`—`,onChange:e=>{let t=e.target.value;a({memory:{...r.memory,contextCadence:t===``?void 0:Number.parseInt(t,10)}})}})}),(0,G.jsx)(Q,{label:o.dialecticCadence,description:o.dialecticCadenceDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,value:r.memory.dialecticCadence??``,placeholder:`—`,onChange:e=>{let t=e.target.value;a({memory:{...r.memory,dialecticCadence:t===``?void 0:Number.parseInt(t,10)}})}})})]})})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:ve,title:o.cardSessionSearchTitle,subtitle:o.cardSessionSearchSubtitle}),(0,G.jsx)(Q,{label:o.sessionSearchSummaryModel,description:o.sessionSearchSummaryModelDesc,children:(0,G.jsx)(V,{value:r.sessionSearch.summaryModel,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>a({sessionSearch:{...r.sessionSearch,summaryModel:e}})})})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:b,title:o.cardReviewTitle,subtitle:o.cardReviewSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)(Q,{label:o.reviewEnabled,description:o.reviewEnabledDesc,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:r.backgroundReview.enabled,onChange:e=>a({backgroundReview:{...r.backgroundReview,enabled:e.target.checked}})}),(0,G.jsx)(`span`,{children:o.reviewEnabledOn})]})}),(0,G.jsxs)(`div`,{className:`grid gap-5 sm:grid-cols-2`,children:[(0,G.jsx)(Q,{label:o.memoryNudgeInterval,description:o.memoryNudgeIntervalDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:0,value:r.backgroundReview.memoryNudgeInterval,onChange:e=>a({backgroundReview:{...r.backgroundReview,memoryNudgeInterval:Number.parseInt(e.target.value,10)||0}})})}),(0,G.jsx)(Q,{label:o.skillNudgeInterval,description:o.skillNudgeIntervalDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:0,value:r.backgroundReview.skillNudgeInterval,onChange:e=>a({backgroundReview:{...r.backgroundReview,skillNudgeInterval:Number.parseInt(e.target.value,10)||0}})})}),(0,G.jsx)(Q,{label:o.reviewMaxToolRounds,description:o.reviewMaxToolRoundsDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,max:32,value:r.backgroundReview.maxToolRounds,onChange:e=>a({backgroundReview:{...r.backgroundReview,maxToolRounds:Number.parseInt(e.target.value,10)||8}})})}),(0,G.jsx)(Q,{label:o.reviewMaxHistoryMessages,description:o.reviewMaxHistoryMessagesDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:10,max:200,value:r.backgroundReview.maxHistoryMessages,onChange:e=>a({backgroundReview:{...r.backgroundReview,maxHistoryMessages:Number.parseInt(e.target.value,10)||80}})})}),(0,G.jsx)(Q,{label:o.reviewMaxDurationMs,description:o.reviewMaxDurationMsDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:30,max:600,step:1,value:Math.round((r.backgroundReview.maxDurationMs??12e4)/1e3),onChange:e=>a({backgroundReview:{...r.backgroundReview,maxDurationMs:(Number.parseInt(e.target.value,10)||120)*1e3}})})})]})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:Pe,title:o.cardWebExtractTitle,subtitle:o.cardWebExtractSubtitle}),(0,G.jsxs)(`div`,{className:`grid gap-5 sm:grid-cols-2`,children:[(0,G.jsx)(`div`,{className:`sm:col-span-2`,children:(0,G.jsx)(Q,{label:o.webExtractModel,description:o.webExtractModelDesc,children:(0,G.jsx)(V,{value:r.webExtract.model,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>a({webExtract:{...r.webExtract,model:e}})})})}),(0,G.jsx)(Q,{label:o.webExtractMaxLength,description:o.webExtractMaxLengthDesc,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),min:1,value:r.webExtract.maxLength??``,placeholder:`—`,onChange:e=>{let t=e.target.value;a({webExtract:{...r.webExtract,maxLength:t===``?void 0:Number.parseInt(t,10)}})}})})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:x,title:o.cardDelegateTitle,subtitle:o.cardDelegateSubtitle}),(0,G.jsxs)(`div`,{className:`grid gap-5 sm:grid-cols-2`,children:[(0,G.jsx)(Q,{label:o.delegateEnabled,description:o.delegateEnabledDesc,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:r.delegate.enabled,onChange:e=>a({delegate:{...r.delegate,enabled:e.target.checked}})}),(0,G.jsx)(`span`,{children:o.delegateEnabledOn})]})}),(0,G.jsx)(Q,{label:o.executeCodeEnabled,description:o.executeCodeEnabledDesc,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:r.executeCode.enabled,onChange:e=>a({executeCode:{...r.executeCode,enabled:e.target.checked}})}),(0,G.jsx)(`span`,{children:o.executeCodeEnabledOn})]})})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:be,title:o.cardPromptSkillsTitle,subtitle:o.cardPromptSkillsSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)(Q,{label:o.systemPromptOverride,description:o.systemPromptOverrideDesc,children:(0,G.jsx)(`textarea`,{className:i(Z(),`min-h-[100px] resize-y font-mono text-xs`),value:r.systemPromptOverride,placeholder:o.systemPromptPlaceholder,onChange:e=>a({systemPromptOverride:e.target.value})})}),(0,G.jsx)(Q,{label:o.skillsAllowlist,description:o.skillsAllowlistDesc,children:(0,G.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[r.skillsAllowlist.map((e,t)=>(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`text`,className:i(Z(),`font-mono text-xs`),value:e,onChange:e=>{let n=[...r.skillsAllowlist];n[t]=e.target.value,a({skillsAllowlist:n})}}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`shrink-0`,"aria-label":o.removeListItem,onClick:()=>a({skillsAllowlist:r.skillsAllowlist.filter((e,n)=>n!==t)}),children:`×`})]},t)),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`w-fit`,onClick:()=>a({skillsAllowlist:[...r.skillsAllowlist,``]}),children:o.addSkillName})]})})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:c,title:o.cardToolsDisableTitle,subtitle:o.cardToolsDisableSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)(`p`,{className:`text-xs text-fg-muted`,children:o.toolsDisableHint}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[r.toolsDisable.map((e,t)=>(0,G.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,G.jsx)(`input`,{type:`text`,className:i(Z(),`font-mono text-xs`),value:e,placeholder:`shell`,onChange:e=>{let n=[...r.toolsDisable];n[t]=e.target.value,a({toolsDisable:n})}}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`shrink-0`,"aria-label":o.removeListItem,onClick:()=>a({toolsDisable:r.toolsDisable.filter((e,n)=>n!==t)}),children:`×`})]},t)),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`w-fit`,onClick:()=>a({toolsDisable:[...r.toolsDisable,``]}),children:o.addToolName})]})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:pe,title:o.cardParamsTitle,subtitle:o.cardParamsSubtitle}),(0,G.jsx)(Q,{label:o.paramsJson,description:o.paramsJsonDesc,children:(0,G.jsx)(`textarea`,{className:i(Z(),`min-h-[88px] resize-y font-mono text-xs`),value:r.paramsJson,placeholder:`{}`,onChange:e=>a({paramsJson:e.target.value})})})]})]})}async function Kn(){let e=await we(H(`/api/image/providers`));if(!e.ok)throw Error(`Image providers: HTTP ${e.status}`);return(await e.json()).payload?.providers??[]}function qn(e){let t=new Set,n=[];for(let r of e){let e=r.models.length>0?r.models:r.defaultModel?[r.defaultModel]:[];for(let i of e){let e=`${r.id}/${i}`;t.has(e)||(t.add(e),n.push(e))}}return n}function Jn(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=n.split(/[/\s]+/).filter(Boolean);return e.filter(e=>{let t=e.toLowerCase();return r.every(e=>t.includes(e))})}var Yn=`image-generation-providers`;function Xn({value:e,disabled:t,placeholder:n,searchPlaceholder:a,noMatches:o,className:s,onChange:c}){let[l,u]=(0,W.useState)(!1),[d,f]=(0,W.useState)(``),{data:p,isLoading:m,error:h}=r(Yn,Kn,{revalidateOnFocus:!1}),g=(0,W.useMemo)(()=>qn(p??[]),[p]),_=(0,W.useMemo)(()=>Jn(g,d),[g,d]),b=e.trim()?e:n,x=e.trim()||n,S=(0,W.useCallback)(e=>{u(e),e||f(``)},[]);return(0,G.jsxs)(se,{open:l,onOpenChange:S,modal:!1,children:[(0,G.jsx)(v,{asChild:!0,children:(0,G.jsxs)(`button`,{type:`button`,disabled:t||m,title:m?`…`:x,className:i(et,`items-center gap-2 rounded-lg border border-edge-subtle bg-surface-panel px-3 py-2 text-left text-sm font-normal text-fg`,y.transition,`hover:border-edge hover:bg-surface-hover/45`,st,`disabled:cursor-not-allowed disabled:opacity-50`,`dark:border-edge-subtle dark:hover:bg-surface-hover/55`,s),"aria-haspopup":`listbox`,"aria-expanded":l,children:[(0,G.jsx)(`span`,{className:`min-w-0 truncate`,children:m?`…`:b}),(0,G.jsx)(ge,{className:`h-4 w-4 shrink-0 text-fg-subtle opacity-70`,"aria-hidden":!0})]})}),(0,G.jsx)(re,{children:(0,G.jsxs)(te,{className:`z-50 w-[min(22rem,calc(100vw-2rem))] rounded-xl border border-edge-subtle bg-surface-panel p-1 shadow-elevated dark:border-edge-subtle`,side:`bottom`,sideOffset:4,align:`end`,onOpenAutoFocus:e=>e.preventDefault(),children:[(0,G.jsx)(`input`,{type:`search`,className:i(`mb-1 w-full rounded-lg border border-edge-subtle bg-surface-base px-2.5 py-1.5 text-sm text-fg placeholder:text-fg-disabled dark:bg-surface-hover/40`,lt),placeholder:a,value:d,onChange:e=>f(e.target.value),onKeyDown:e=>e.stopPropagation()}),(0,G.jsxs)(`div`,{className:`max-h-60 overflow-auto`,role:`listbox`,"aria-label":a,children:[h?(0,G.jsx)(`div`,{className:`px-2 py-2 text-xs text-red-600 dark:text-red-400`,children:h instanceof Error?h.message:`Failed to load image providers`}):null,!h&&g.length===0&&!m?(0,G.jsx)(`div`,{className:`px-2 py-3 text-center text-xs text-fg-muted`,children:o}):null,!h&&g.length>0&&_.length===0?(0,G.jsx)(`div`,{className:`px-2 py-3 text-center text-xs text-fg-muted`,children:o}):null,_.map(t=>(0,G.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t===e,className:i(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-fg hover:bg-surface-hover`,t===e&&`bg-surface-hover/90 font-medium dark:bg-surface-hover/70`),onClick:()=>{c(t),u(!1),f(``)},children:[(0,G.jsx)(R,{className:i(`h-4 w-4 shrink-0`,t!==e&&`invisible`),"aria-hidden":!0}),(0,G.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,children:t})]},t))]})]})})]})}var Zn=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`adaptive`];function $({label:e,description:t,children:n}){return(0,G.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,G.jsx)(`div`,{className:`text-sm font-medium text-fg`,children:e}),n,(0,G.jsx)(`p`,{className:`text-xs leading-relaxed text-fg-subtle`,children:t})]})}function Qn(){let e=rt(ke(e=>e.language)),t=e.agentSettings,n=e.chat,r=!!Te(e=>e.token),[i,a]=(0,W.useState)(null),[o,s]=(0,W.useState)(null),[c,l]=(0,W.useState)(!1),[u,d]=(0,W.useState)(null),[f,p]=(0,W.useState)(!1),m=(0,W.useRef)(!1),{data:g,error:_,isLoading:v,mutate:y}=tt(r),b=(0,W.useMemo)(()=>g?.payload?.config===void 0?null:Bn(g.payload.config),[g]);(0,W.useEffect)(()=>{if(!r){a(null),s(null),m.current=!1;return}b!==null&&(m.current||(a(b),s(b)))},[r,b]);let x=!!(r&&v&&g===void 0&&!_),C=_ instanceof Error?_.message:_?String(_):null,w=(0,W.useMemo)(()=>!i||!o?!1:JSON.stringify(i)!==JSON.stringify(o),[i,o]),T=(0,W.useCallback)(e=>{m.current=!0,a(t=>t?{...t,...e}:null)},[]),E=(0,W.useCallback)(async()=>{if(!(!i||c)){l(!0),d(null),p(!1);try{try{Hn(i.paramsJson)}catch(e){d(e instanceof SyntaxError?t.advanced.paramsInvalidJson:e instanceof Error?e.message:t.advanced.paramsInvalidJson);return}await Un(i),m.current=!1,p(!0),window.setTimeout(()=>p(!1),2500)}catch(e){d(e instanceof Error?e.message:t.saveError)}finally{l(!1)}}},[i,c,t.saveError,t.advanced]),ee=e.settingsSections[`agent-defaults`];return r?x?(0,G.jsxs)(`div`,{className:`mx-auto w-full max-w-app-main px-4 py-8`,children:[(0,G.jsx)(`div`,{className:`h-8 w-48 animate-pulse rounded bg-surface-hover`}),(0,G.jsx)(`div`,{className:`mt-6 h-32 animate-pulse rounded-xl bg-surface-hover`}),(0,G.jsx)(`p`,{className:`mt-4 text-sm text-fg-muted`,children:e.logs.loading})]}):i?(0,G.jsxs)(`div`,{className:`mx-auto flex w-full max-w-app-main flex-col gap-6 px-4 py-8`,children:[(0,G.jsxs)(`header`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between`,children:[(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`h1`,{className:`text-lg font-semibold tracking-tight text-fg`,children:ee}),(0,G.jsx)(`p`,{className:`mt-1 text-sm text-fg-muted`,children:t.subtitle}),(0,G.jsx)(`p`,{className:`mt-1 text-xs text-fg-subtle`,children:t.sectionDesc})]}),(0,G.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[f?(0,G.jsx)(`span`,{className:`text-sm text-fg-muted`,children:t.saved}):null,(0,G.jsx)(N,{type:`button`,variant:`primary`,disabled:!w||c,onClick:()=>void E(),children:c?t.saving:t.save})]})]}),u?(0,G.jsx)(`div`,{className:`rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-900/50 dark:bg-red-950/50 dark:text-red-400`,role:`alert`,children:u}):null,(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:ut,title:t.cardModelsTitle,subtitle:t.cardModelsSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)($,{label:t.label.model,description:t.desc.model,children:(0,G.jsx)(V,{value:i.model,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>T({model:e})})}),(0,G.jsx)($,{label:t.label.modelFallbacks,description:t.desc.modelFallbacks,children:(0,G.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[i.modelFallbacks.map((e,r)=>(0,G.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,G.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,G.jsx)(V,{value:e,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>{let t=[...i.modelFallbacks];t[r]=e,T({modelFallbacks:t})}})}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`shrink-0`,"aria-label":t.removeModelFallback,onClick:()=>T({modelFallbacks:i.modelFallbacks.filter((e,t)=>t!==r)}),children:(0,G.jsx)(S,{className:`size-4`,strokeWidth:1.75})})]},r)),(0,G.jsxs)(N,{type:`button`,variant:`secondary`,className:`w-fit gap-1.5`,onClick:()=>T({modelFallbacks:[...i.modelFallbacks,``]}),children:[(0,G.jsx)(Ee,{className:`size-4 shrink-0`,strokeWidth:1.75}),t.addModelFallback]})]})}),(0,G.jsx)($,{label:t.label.imageModel,description:t.desc.imageModel,children:(0,G.jsx)(V,{value:i.imageModel,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>T({imageModel:e})})}),(0,G.jsx)($,{label:t.label.imageModelFallbacks,description:t.desc.imageModelFallbacks,children:(0,G.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[i.imageModelFallbacks.map((e,r)=>(0,G.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,G.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,G.jsx)(V,{value:e,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>{let t=[...i.imageModelFallbacks];t[r]=e,T({imageModelFallbacks:t})}})}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`shrink-0`,"aria-label":t.removeModelFallback,onClick:()=>T({imageModelFallbacks:i.imageModelFallbacks.filter((e,t)=>t!==r)}),children:(0,G.jsx)(S,{className:`size-4`,strokeWidth:1.75})})]},r)),(0,G.jsxs)(N,{type:`button`,variant:`secondary`,className:`w-fit gap-1.5`,onClick:()=>T({imageModelFallbacks:[...i.imageModelFallbacks,``]}),children:[(0,G.jsx)(Ee,{className:`size-4 shrink-0`,strokeWidth:1.75}),t.addModelFallback]})]})}),(0,G.jsx)($,{label:t.label.imageGenerationModel,description:t.desc.imageGenerationModel,children:(0,G.jsx)(Xn,{value:i.imageGenerationModel,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>T({imageGenerationModel:e})})}),(0,G.jsx)($,{label:t.label.imageGenerationModelFallbacks,description:t.desc.imageGenerationModelFallbacks,children:(0,G.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[i.imageGenerationModelFallbacks.map((e,r)=>(0,G.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,G.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,G.jsx)(Xn,{value:e,placeholder:n.modelPlaceholder,searchPlaceholder:n.modelSearchPlaceholder,noMatches:n.modelNoMatches,onChange:e=>{let t=[...i.imageGenerationModelFallbacks];t[r]=e,T({imageGenerationModelFallbacks:t})}})}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,className:`shrink-0`,"aria-label":t.removeModelFallback,onClick:()=>T({imageGenerationModelFallbacks:i.imageGenerationModelFallbacks.filter((e,t)=>t!==r)}),children:(0,G.jsx)(S,{className:`size-4`,strokeWidth:1.75})})]},r)),(0,G.jsxs)(N,{type:`button`,variant:`secondary`,className:`w-fit gap-1.5`,onClick:()=>T({imageGenerationModelFallbacks:[...i.imageGenerationModelFallbacks,``]}),children:[(0,G.jsx)(Ee,{className:`size-4 shrink-0`,strokeWidth:1.75}),t.addModelFallback]})]})})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:A,title:t.cardWorkspaceTitle,subtitle:t.cardWorkspaceSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)($,{label:t.label.workspace,description:t.desc.workspace,children:(0,G.jsx)(`input`,{type:`text`,className:Z(),value:i.workspace,onChange:e=>T({workspace:e.target.value}),autoComplete:`off`})}),(0,G.jsx)($,{label:t.label.mediaMaxMb,description:t.desc.mediaMaxMb,children:(0,G.jsx)(`input`,{type:`number`,min:1,step:1,className:Z(),value:i.mediaMaxMb??``,placeholder:`20`,onChange:e=>{let t=e.target.value;T({mediaMaxMb:t===``?void 0:Number(t)})}})})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:h,title:t.cardBrowserTitle,subtitle:t.cardBrowserSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)($,{label:t.label.browserEnabled,description:t.desc.browserEnabled,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:i.browserEnabled,onChange:e=>T({browserEnabled:e.target.checked})}),(0,G.jsx)(`span`,{children:t.browserEnabledOn})]})}),(0,G.jsx)($,{label:t.label.browserHeadless,description:t.desc.browserHeadless,children:(0,G.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 text-sm text-fg`,children:[(0,G.jsx)(`input`,{type:`checkbox`,className:`size-3.5 shrink-0 rounded border-edge`,checked:i.browserHeadless,onChange:e=>T({browserHeadless:e.target.checked})}),(0,G.jsx)(`span`,{children:t.browserHeadlessOn})]})})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:U,title:t.cardGenerationTitle,subtitle:t.cardGenerationSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsxs)(`div`,{className:`grid gap-5 sm:grid-cols-2`,children:[(0,G.jsx)($,{label:t.label.maxTokens,description:t.desc.maxTokens,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),value:i.maxTokens,min:1,onChange:e=>T({maxTokens:Number.parseInt(e.target.value,10)||0})})}),(0,G.jsx)($,{label:t.label.temperature,description:t.desc.temperature,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),value:i.temperature,min:0,max:2,step:.1,onChange:e=>T({temperature:Number.parseFloat(e.target.value)||0})})})]}),(0,G.jsx)($,{label:t.label.maxToolIterations,description:t.desc.maxToolIterations,children:(0,G.jsx)(`input`,{type:`number`,className:Z(),value:i.maxToolIterations,min:1,onChange:e=>T({maxToolIterations:Number.parseInt(e.target.value,10)||0})})})]})]}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Y,{icon:k,title:t.cardBehaviorTitle,subtitle:t.cardBehaviorSubtitle}),(0,G.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,G.jsx)($,{label:t.label.thinkingDefault,description:t.desc.thinkingDefault,children:(0,G.jsx)(`select`,{className:Wn(),value:i.thinkingDefault,onChange:e=>T({thinkingDefault:e.target.value}),children:Zn.map(e=>(0,G.jsx)(`option`,{value:e,children:n.thinkingLevels[e]},e))})}),(0,G.jsx)($,{label:t.label.reasoningDefault,description:t.desc.reasoningDefault,children:(0,G.jsxs)(`select`,{className:Wn(),value:i.reasoningDefault,onChange:e=>T({reasoningDefault:e.target.value}),children:[(0,G.jsx)(`option`,{value:`off`,children:t.reasoning.off}),(0,G.jsx)(`option`,{value:`on`,children:t.reasoning.on}),(0,G.jsx)(`option`,{value:`stream`,children:t.reasoning.stream})]})}),(0,G.jsx)($,{label:t.label.verboseDefault,description:t.desc.verboseDefault,children:(0,G.jsxs)(`select`,{className:Wn(),value:i.verboseDefault,onChange:e=>T({verboseDefault:e.target.value}),children:[(0,G.jsx)(`option`,{value:`off`,children:t.verbose.off}),(0,G.jsx)(`option`,{value:`on`,children:t.verbose.on}),(0,G.jsx)(`option`,{value:`full`,children:t.verbose.full})]})})]})]}),(0,G.jsx)(Gn,{a:t,chat:n,form:i,update:T})]})]}):(0,G.jsxs)(`div`,{className:`mx-auto flex w-full max-w-app-main flex-col gap-3 px-4 py-10`,children:[(0,G.jsx)(`p`,{className:`text-sm text-fg-muted`,children:u??C??t.loadError}),(0,G.jsx)(N,{type:`button`,variant:`secondary`,onClick:()=>void y(),children:e.logs.refresh})]}):(0,G.jsx)(`div`,{className:`mx-auto flex w-full max-w-app-main flex-col gap-3 px-4 py-10`,children:(0,G.jsxs)(`div`,{className:`flex items-start gap-3 rounded-2xl bg-surface-base p-6`,children:[(0,G.jsx)(ut,{className:`mt-0.5 size-5 shrink-0 text-fg-subtle`,strokeWidth:1.75}),(0,G.jsxs)(`div`,{children:[(0,G.jsx)(`h1`,{className:`text-base font-semibold text-fg`,children:ee}),(0,G.jsx)(`p`,{className:`mt-1 text-sm text-fg-muted`,children:t.needToken})]})]})})}export{xn as AgentsSettingsPanel,Dt as a,Ot as c,Jt as i,kt as l,J as n,Mt as o,Y as r,jt as s,Qn as t,At as u};
216
- //# sourceMappingURL=agents-BfwtJOPK.js.map