Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 | /** * Intelligence Layer Unified Client * * Provides a unified API for intelligence operations that: * - Uses Rust backend (via Tauri commands) when running in Tauri environment * - Falls back to localStorage-based implementation in browser environment * * This replaces direct usage of: * - agent-memory.ts * - heartbeat-engine.ts * - context-compactor.ts * - reflection-engine.ts * - agent-identity.ts * * Usage: * ```typescript * import { intelligenceClient, toFrontendMemory, toBackendMemoryInput } from './intelligence-client'; * * // Store memory * const id = await intelligenceClient.memory.store({ * agent_id: 'agent-1', * memory_type: 'fact', * content: 'User prefers concise responses', * importance: 7, * }); * * // Search memories * const memories = await intelligenceClient.memory.search({ * agent_id: 'agent-1', * query: 'user preference', * limit: 10, * }); * * // Convert to frontend format if needed * const frontendMemories = memories.map(toFrontendMemory); * ``` */ import { invoke } from '@tauri-apps/api/core'; import { intelligence, type MemoryEntryInput, type PersistentMemory, type MemorySearchOptions as BackendSearchOptions, type MemoryStats as BackendMemoryStats, type HeartbeatConfig, type HeartbeatResult, type CompactableMessage, type CompactionResult, type CompactionCheck, type CompactionConfig, type MemoryEntryForAnalysis, type PatternObservation, type ImprovementSuggestion, type ReflectionIdentityProposal, type ReflectionResult, type ReflectionState, type ReflectionConfig, type IdentityFiles, type IdentityChangeProposal, type IdentitySnapshot, } from './intelligence-backend'; // === Environment Detection === /** * Check if running in Tauri environment */ export function isTauriEnv(): boolean { return typeof window !== 'undefined' && '__TAURI__' in window; } // === Frontend Types (for backward compatibility) === export type MemoryType = 'fact' | 'preference' | 'lesson' | 'context' | 'task'; export type MemorySource = 'auto' | 'user' | 'reflection' | 'llm-reflection'; export interface MemoryEntry { id: string; agentId: string; content: string; type: MemoryType; importance: number; source: MemorySource; tags: string[]; createdAt: string; lastAccessedAt: string; accessCount: number; conversationId?: string; } export interface MemorySearchOptions { agentId?: string; type?: MemoryType; types?: MemoryType[]; tags?: string[]; query?: string; limit?: number; minImportance?: number; } export interface MemoryStats { totalEntries: number; byType: Record<string, number>; byAgent: Record<string, number>; oldestEntry: string | null; newestEntry: string | null; storageSizeBytes: number; } // === Re-export types from intelligence-backend === export type { HeartbeatConfig, HeartbeatResult, HeartbeatAlert, CompactableMessage, CompactionResult, CompactionCheck, CompactionConfig, PatternObservation, ImprovementSuggestion, ReflectionResult, ReflectionState, ReflectionConfig, ReflectionIdentityProposal, IdentityFiles, IdentityChangeProposal, IdentitySnapshot, MemoryEntryForAnalysis, } from './intelligence-backend'; // === Mesh Types === export interface BehaviorPattern { id: string; pattern_type: PatternTypeVariant; frequency: number; last_occurrence: string; first_occurrence: string; confidence: number; context: PatternContext; } export function getPatternTypeString(patternType: PatternTypeVariant): string { if (typeof patternType === 'string') { return patternType; } return patternType.type; } export type PatternTypeVariant = | { type: 'SkillCombination'; skill_ids: string[] } | { type: 'TemporalTrigger'; hand_id: string; time_pattern: string } | { type: 'TaskPipelineMapping'; task_type: string; pipeline_id: string } | { type: 'InputPattern'; keywords: string[]; intent: string }; export interface PatternContext { skill_ids?: string[]; recent_topics?: string[]; intent?: string; time_of_day?: number; day_of_week?: number; } export interface WorkflowRecommendation { id: string; pipeline_id: string; confidence: number; reason: string; suggested_inputs: Record<string, unknown>; patterns_matched: string[]; timestamp: string; } export interface MeshConfig { enabled: boolean; min_confidence: number; max_recommendations: number; analysis_window_hours: number; } export interface MeshAnalysisResult { recommendations: WorkflowRecommendation[]; patterns_detected: number; timestamp: string; } export type ActivityType = | { type: 'skill_used'; skill_ids: string[] } | { type: 'pipeline_executed'; task_type: string; pipeline_id: string } | { type: 'input_received'; keywords: string[]; intent: string }; // === Persona Evolver Types === export type EvolutionChangeType = | 'instruction_addition' | 'instruction_refinement' | 'trait_addition' | 'style_adjustment' | 'domain_expansion'; export type InsightCategory = | 'communication_style' | 'technical_expertise' | 'task_efficiency' | 'user_preference' | 'knowledge_gap'; export type IdentityFileType = 'soul' | 'instructions'; export type ProposalStatus = 'pending' | 'approved' | 'rejected'; export interface EvolutionProposal { id: string; agent_id: string; target_file: IdentityFileType; change_type: EvolutionChangeType; reason: string; current_content: string; proposed_content: string; confidence: number; evidence: string[]; status: ProposalStatus; created_at: string; } export interface ProfileUpdate { section: string; previous: string; updated: string; source: string; } export interface EvolutionInsight { category: InsightCategory; observation: string; recommendation: string; confidence: number; } export interface EvolutionResult { agent_id: string; timestamp: string; profile_updates: ProfileUpdate[]; proposals: EvolutionProposal[]; insights: EvolutionInsight[]; evolved: boolean; } export interface PersonaEvolverConfig { auto_profile_update: boolean; min_preferences_for_update: number; min_conversations_for_evolution: number; enable_instruction_refinement: boolean; enable_soul_evolution: boolean; max_proposals_per_cycle: number; } export interface PersonaEvolverState { last_evolution: string | null; total_evolutions: number; pending_proposals: number; profile_enrichment_score: number; } // === Type Conversion Utilities === /** * Convert backend PersistentMemory to frontend MemoryEntry format */ export function toFrontendMemory(backend: PersistentMemory): MemoryEntry { return { id: backend.id, agentId: backend.agent_id, content: backend.content, type: backend.memory_type as MemoryType, importance: backend.importance, source: backend.source as MemorySource, tags: parseTags(backend.tags), createdAt: backend.created_at, lastAccessedAt: backend.last_accessed_at, accessCount: backend.access_count, conversationId: backend.conversation_id ?? undefined, }; } /** * Convert frontend MemoryEntry to backend MemoryEntryInput format */ export function toBackendMemoryInput(entry: Omit<MemoryEntry, 'id' | 'createdAt' | 'lastAccessedAt' | 'accessCount'>): MemoryEntryInput { return { agent_id: entry.agentId, memory_type: entry.type, content: entry.content, importance: entry.importance, source: entry.source, tags: entry.tags, conversation_id: entry.conversationId, }; } /** * Convert frontend search options to backend format */ export function toBackendSearchOptions(options: MemorySearchOptions): BackendSearchOptions { return { agent_id: options.agentId, memory_type: options.type, tags: options.tags, query: options.query, limit: options.limit, min_importance: options.minImportance, }; } /** * Convert backend stats to frontend format */ export function toFrontendStats(backend: BackendMemoryStats): MemoryStats { return { totalEntries: backend.total_entries, byType: backend.by_type, byAgent: backend.by_agent, oldestEntry: backend.oldest_entry, newestEntry: backend.newest_entry, storageSizeBytes: backend.storage_size_bytes ?? 0, }; } /** * Parse tags from backend (JSON string or array) */ function parseTags(tags: string | string[]): string[] { if (Array.isArray(tags)) return tags; if (!tags) return []; try { return JSON.parse(tags); } catch { return []; } } // === LocalStorage Fallback Implementation === const FALLBACK_STORAGE_KEY = 'zclaw-intelligence-fallback'; interface FallbackMemoryStore { memories: MemoryEntry[]; } function getFallbackStore(): FallbackMemoryStore { try { const stored = localStorage.getItem(FALLBACK_STORAGE_KEY); if (stored) { return JSON.parse(stored); } } catch { // ignore } return { memories: [] }; } function saveFallbackStore(store: FallbackMemoryStore): void { try { localStorage.setItem(FALLBACK_STORAGE_KEY, JSON.stringify(store)); } catch { console.warn('[IntelligenceClient] Failed to save to localStorage'); } } // Fallback Memory API const fallbackMemory = { async init(): Promise<void> { // No-op for localStorage }, async store(entry: MemoryEntryInput): Promise<string> { const store = getFallbackStore(); const id = `mem_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; const now = new Date().toISOString(); const memory: MemoryEntry = { id, agentId: entry.agent_id, content: entry.content, type: entry.memory_type as MemoryType, importance: entry.importance ?? 5, source: (entry.source as MemorySource) ?? 'auto', tags: entry.tags ?? [], createdAt: now, lastAccessedAt: now, accessCount: 0, conversationId: entry.conversation_id, }; store.memories.push(memory); saveFallbackStore(store); return id; }, async get(id: string): Promise<MemoryEntry | null> { const store = getFallbackStore(); return store.memories.find(m => m.id === id) ?? null; }, async search(options: MemorySearchOptions): Promise<MemoryEntry[]> { const store = getFallbackStore(); let results = store.memories; if (options.agentId) { results = results.filter(m => m.agentId === options.agentId); } if (options.type) { results = results.filter(m => m.type === options.type); } if (options.minImportance !== undefined) { results = results.filter(m => m.importance >= options.minImportance!); } if (options.query) { const queryLower = options.query.toLowerCase(); results = results.filter(m => m.content.toLowerCase().includes(queryLower) || m.tags.some(t => t.toLowerCase().includes(queryLower)) ); } if (options.limit) { results = results.slice(0, options.limit); } return results; }, async delete(id: string): Promise<void> { const store = getFallbackStore(); store.memories = store.memories.filter(m => m.id !== id); saveFallbackStore(store); }, async deleteAll(agentId: string): Promise<number> { const store = getFallbackStore(); const before = store.memories.length; store.memories = store.memories.filter(m => m.agentId !== agentId); saveFallbackStore(store); return before - store.memories.length; }, async stats(): Promise<MemoryStats> { const store = getFallbackStore(); const byType: Record<string, number> = {}; const byAgent: Record<string, number> = {}; for (const m of store.memories) { byType[m.type] = (byType[m.type] ?? 0) + 1; byAgent[m.agentId] = (byAgent[m.agentId] ?? 0) + 1; } const sorted = [...store.memories].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime() ); // Estimate storage size from serialized data let storageSizeBytes = 0; try { const serialized = JSON.stringify(store.memories); storageSizeBytes = new Blob([serialized]).size; } catch { // Ignore serialization errors } return { totalEntries: store.memories.length, byType, byAgent, oldestEntry: sorted[0]?.createdAt ?? null, newestEntry: sorted[sorted.length - 1]?.createdAt ?? null, storageSizeBytes, }; }, async export(): Promise<MemoryEntry[]> { const store = getFallbackStore(); return store.memories; }, async import(memories: MemoryEntry[]): Promise<number> { const store = getFallbackStore(); store.memories.push(...memories); saveFallbackStore(store); return memories.length; }, async dbPath(): Promise<string> { return 'localStorage://zclaw-intelligence-fallback'; }, }; // Fallback Compactor API const fallbackCompactor = { async estimateTokens(text: string): Promise<number> { // Simple heuristic: ~4 chars per token for English, ~1.5 for CJK const cjkChars = (text.match(/[\u4e00-\u9fff\u3040-\u30ff]/g) ?? []).length; const otherChars = text.length - cjkChars; return Math.ceil(cjkChars * 1.5 + otherChars / 4); }, async estimateMessagesTokens(messages: CompactableMessage[]): Promise<number> { let total = 0; for (const m of messages) { total += await fallbackCompactor.estimateTokens(m.content); } return total; }, async checkThreshold( messages: CompactableMessage[], config?: CompactionConfig ): Promise<CompactionCheck> { const threshold = config?.soft_threshold_tokens ?? 15000; const currentTokens = await fallbackCompactor.estimateMessagesTokens(messages); return { should_compact: currentTokens >= threshold, current_tokens: currentTokens, threshold, urgency: currentTokens >= (config?.hard_threshold_tokens ?? 20000) ? 'hard' : currentTokens >= threshold ? 'soft' : 'none', }; }, async compact( messages: CompactableMessage[], _agentId: string, _conversationId?: string, config?: CompactionConfig ): Promise<CompactionResult> { // Simple rule-based compaction: keep last N messages const keepRecent = config?.keep_recent_messages ?? 10; const retained = messages.slice(-keepRecent); return { compacted_messages: retained, summary: `[Compacted ${messages.length - retained.length} earlier messages]`, original_count: messages.length, retained_count: retained.length, flushed_memories: 0, tokens_before_compaction: await fallbackCompactor.estimateMessagesTokens(messages), tokens_after_compaction: await fallbackCompactor.estimateMessagesTokens(retained), }; }, }; // Fallback Reflection API const fallbackReflection = { _conversationCount: 0, _lastReflection: null as string | null, _history: [] as ReflectionResult[], async init(_config?: ReflectionConfig): Promise<void> { // No-op }, async recordConversation(): Promise<void> { fallbackReflection._conversationCount++; }, async shouldReflect(): Promise<boolean> { return fallbackReflection._conversationCount >= 5; }, async reflect(agentId: string, memories: MemoryEntryForAnalysis[]): Promise<ReflectionResult> { fallbackReflection._conversationCount = 0; fallbackReflection._lastReflection = new Date().toISOString(); // Analyze patterns (simple rule-based implementation) const patterns: PatternObservation[] = []; const improvements: ImprovementSuggestion[] = []; const identityProposals: ReflectionIdentityProposal[] = []; // Count memory types const typeCounts: Record<string, number> = {}; for (const m of memories) { typeCounts[m.memory_type] = (typeCounts[m.memory_type] || 0) + 1; } // Pattern: Too many tasks const taskCount = typeCounts['task'] || 0; if (taskCount >= 5) { const taskMemories = memories.filter(m => m.memory_type === 'task').slice(0, 3); patterns.push({ observation: `积累了 ${taskCount} 个待办任务,可能存在任务管理不善`, frequency: taskCount, sentiment: 'negative', evidence: taskMemories.map(m => m.content), }); improvements.push({ area: '任务管理', suggestion: '清理已完成的任务记忆,对长期未处理的任务降低重要性', priority: 'high', }); } // Pattern: Strong preference accumulation const prefCount = typeCounts['preference'] || 0; if (prefCount >= 5) { const prefMemories = memories.filter(m => m.memory_type === 'preference').slice(0, 3); patterns.push({ observation: `已记录 ${prefCount} 个用户偏好,对用户习惯有较好理解`, frequency: prefCount, sentiment: 'positive', evidence: prefMemories.map(m => m.content), }); } // Pattern: Lessons learned const lessonCount = typeCounts['lesson'] || 0; if (lessonCount >= 5) { patterns.push({ observation: `积累了 ${lessonCount} 条经验教训,知识库在成长`, frequency: lessonCount, sentiment: 'positive', evidence: memories.filter(m => m.memory_type === 'lesson').slice(0, 3).map(m => m.content), }); } // Pattern: High-access important memories const highAccessMemories = memories.filter(m => m.access_count >= 5 && m.importance >= 7); if (highAccessMemories.length >= 3) { patterns.push({ observation: `有 ${highAccessMemories.length} 条高频访问的重要记忆,核心知识正在形成`, frequency: highAccessMemories.length, sentiment: 'positive', evidence: highAccessMemories.slice(0, 3).map(m => m.content), }); } // Pattern: Low importance memories accumulating const lowImportanceCount = memories.filter(m => m.importance <= 3).length; if (lowImportanceCount > 20) { patterns.push({ observation: `有 ${lowImportanceCount} 条低重要性记忆,建议清理`, frequency: lowImportanceCount, sentiment: 'neutral', evidence: [], }); improvements.push({ area: '记忆管理', suggestion: '执行记忆清理,移除30天以上未访问且重要性低于3的记忆', priority: 'medium', }); } // Generate identity proposal if negative patterns exist const negativePatterns = patterns.filter(p => p.sentiment === 'negative'); if (negativePatterns.length >= 2) { const additions = negativePatterns.map(p => `- 注意: ${p.observation}`).join('\n'); identityProposals.push({ agent_id: agentId, field: 'instructions', current_value: '...', proposed_value: `\n\n## 自我反思改进\n${additions}`, reason: `基于 ${negativePatterns.length} 个负面模式观察,建议在指令中增加自我改进提醒`, }); } // Suggestion: User profile enrichment if (prefCount < 3) { improvements.push({ area: '用户理解', suggestion: '主动在对话中了解用户偏好(沟通风格、技术栈、工作习惯),丰富用户画像', priority: 'medium', }); } const result: ReflectionResult = { patterns, improvements, identity_proposals: identityProposals, new_memories: patterns.filter(p => p.frequency >= 3).length + improvements.filter(i => i.priority === 'high').length, timestamp: new Date().toISOString(), }; // Store in history fallbackReflection._history.push(result); if (fallbackReflection._history.length > 20) { fallbackReflection._history = fallbackReflection._history.slice(-10); } return result; }, async getHistory(limit?: number): Promise<ReflectionResult[]> { const l = limit ?? 10; return fallbackReflection._history.slice(-l).reverse(); }, async getState(): Promise<ReflectionState> { return { conversations_since_reflection: fallbackReflection._conversationCount, last_reflection_time: fallbackReflection._lastReflection, last_reflection_agent_id: null, }; }, }; // Fallback Identity API with localStorage persistence const IDENTITY_STORAGE_KEY = 'zclaw-fallback-identities'; const PROPOSALS_STORAGE_KEY = 'zclaw-fallback-proposals'; const SNAPSHOTS_STORAGE_KEY = 'zclaw-fallback-snapshots'; function loadIdentitiesFromStorage(): Map<string, IdentityFiles> { try { const stored = localStorage.getItem(IDENTITY_STORAGE_KEY); if (stored) { const parsed = JSON.parse(stored) as Record<string, IdentityFiles>; return new Map(Object.entries(parsed)); } } catch { console.warn('[IntelligenceClient] Failed to load identities from localStorage'); } return new Map(); } function saveIdentitiesToStorage(identities: Map<string, IdentityFiles>): void { try { const obj = Object.fromEntries(identities); localStorage.setItem(IDENTITY_STORAGE_KEY, JSON.stringify(obj)); } catch { console.warn('[IntelligenceClient] Failed to save identities to localStorage'); } } function loadProposalsFromStorage(): IdentityChangeProposal[] { try { const stored = localStorage.getItem(PROPOSALS_STORAGE_KEY); if (stored) { return JSON.parse(stored) as IdentityChangeProposal[]; } } catch { console.warn('[IntelligenceClient] Failed to load proposals from localStorage'); } return []; } function saveProposalsToStorage(proposals: IdentityChangeProposal[]): void { try { localStorage.setItem(PROPOSALS_STORAGE_KEY, JSON.stringify(proposals)); } catch { console.warn('[IntelligenceClient] Failed to save proposals to localStorage'); } } function loadSnapshotsFromStorage(): IdentitySnapshot[] { try { const stored = localStorage.getItem(SNAPSHOTS_STORAGE_KEY); if (stored) { return JSON.parse(stored) as IdentitySnapshot[]; } } catch { console.warn('[IntelligenceClient] Failed to load snapshots from localStorage'); } return []; } function saveSnapshotsToStorage(snapshots: IdentitySnapshot[]): void { try { localStorage.setItem(SNAPSHOTS_STORAGE_KEY, JSON.stringify(snapshots)); } catch { console.warn('[IntelligenceClient] Failed to save snapshots to localStorage'); } } const fallbackIdentities = loadIdentitiesFromStorage(); let fallbackProposals = loadProposalsFromStorage(); let fallbackSnapshots = loadSnapshotsFromStorage(); const fallbackIdentity = { async get(agentId: string): Promise<IdentityFiles> { if (!fallbackIdentities.has(agentId)) { const defaults: IdentityFiles = { soul: '# Agent Soul\n\nA helpful AI assistant.', instructions: '# Instructions\n\nBe helpful and concise.', user_profile: '# User Profile\n\nNo profile yet.', }; fallbackIdentities.set(agentId, defaults); saveIdentitiesToStorage(fallbackIdentities); } return fallbackIdentities.get(agentId)!; }, async getFile(agentId: string, file: string): Promise<string> { const files = await fallbackIdentity.get(agentId); return files[file as keyof IdentityFiles] ?? ''; }, async buildPrompt(agentId: string, memoryContext?: string): Promise<string> { const files = await fallbackIdentity.get(agentId); let prompt = `${files.soul}\n\n## Instructions\n${files.instructions}\n\n## User Profile\n${files.user_profile}`; if (memoryContext) { prompt += `\n\n## Memory Context\n${memoryContext}`; } return prompt; }, async updateUserProfile(agentId: string, content: string): Promise<void> { const files = await fallbackIdentity.get(agentId); files.user_profile = content; fallbackIdentities.set(agentId, files); saveIdentitiesToStorage(fallbackIdentities); }, async appendUserProfile(agentId: string, addition: string): Promise<void> { const files = await fallbackIdentity.get(agentId); files.user_profile += `\n\n${addition}`; fallbackIdentities.set(agentId, files); saveIdentitiesToStorage(fallbackIdentities); }, async proposeChange( agentId: string, file: 'soul' | 'instructions', suggestedContent: string, reason: string ): Promise<IdentityChangeProposal> { const files = await fallbackIdentity.get(agentId); const proposal: IdentityChangeProposal = { id: `prop_${Date.now()}`, agent_id: agentId, file, reason, current_content: files[file] ?? '', suggested_content: suggestedContent, status: 'pending', created_at: new Date().toISOString(), }; fallbackProposals.push(proposal); saveProposalsToStorage(fallbackProposals); return proposal; }, async approveProposal(proposalId: string): Promise<IdentityFiles> { const proposal = fallbackProposals.find(p => p.id === proposalId); if (!proposal) throw new Error('Proposal not found'); const files = await fallbackIdentity.get(proposal.agent_id); // Create snapshot before applying change const snapshot: IdentitySnapshot = { id: `snap_${Date.now()}`, agent_id: proposal.agent_id, files: { ...files }, timestamp: new Date().toISOString(), reason: `Before applying: ${proposal.reason}`, }; fallbackSnapshots.unshift(snapshot); // Keep only last 20 snapshots per agent const agentSnapshots = fallbackSnapshots.filter(s => s.agent_id === proposal.agent_id); if (agentSnapshots.length > 20) { const toRemove = agentSnapshots.slice(20); fallbackSnapshots = fallbackSnapshots.filter(s => !toRemove.includes(s)); } saveSnapshotsToStorage(fallbackSnapshots); proposal.status = 'approved'; files[proposal.file] = proposal.suggested_content; fallbackIdentities.set(proposal.agent_id, files); saveIdentitiesToStorage(fallbackIdentities); saveProposalsToStorage(fallbackProposals); return files; }, async rejectProposal(proposalId: string): Promise<void> { const proposal = fallbackProposals.find(p => p.id === proposalId); if (proposal) { proposal.status = 'rejected'; saveProposalsToStorage(fallbackProposals); } }, async getPendingProposals(agentId?: string): Promise<IdentityChangeProposal[]> { return fallbackProposals.filter(p => p.status === 'pending' && (!agentId || p.agent_id === agentId) ); }, async updateFile(agentId: string, file: string, content: string): Promise<void> { const files = await fallbackIdentity.get(agentId); if (file in files) { // IdentityFiles has known properties, update safely const key = file as keyof IdentityFiles; if (key in files) { files[key] = content; fallbackIdentities.set(agentId, files); saveIdentitiesToStorage(fallbackIdentities); } } }, async getSnapshots(agentId: string, limit?: number): Promise<IdentitySnapshot[]> { const agentSnapshots = fallbackSnapshots.filter(s => s.agent_id === agentId); return agentSnapshots.slice(0, limit ?? 10); }, async restoreSnapshot(agentId: string, snapshotId: string): Promise<void> { const snapshot = fallbackSnapshots.find(s => s.id === snapshotId && s.agent_id === agentId); if (!snapshot) throw new Error('Snapshot not found'); // Create a snapshot of current state before restore const currentFiles = await fallbackIdentity.get(agentId); const beforeRestoreSnapshot: IdentitySnapshot = { id: `snap_${Date.now()}`, agent_id: agentId, files: { ...currentFiles }, timestamp: new Date().toISOString(), reason: 'Auto-backup before restore', }; fallbackSnapshots.unshift(beforeRestoreSnapshot); saveSnapshotsToStorage(fallbackSnapshots); // Restore the snapshot fallbackIdentities.set(agentId, { ...snapshot.files }); saveIdentitiesToStorage(fallbackIdentities); }, async listAgents(): Promise<string[]> { return Array.from(fallbackIdentities.keys()); }, async deleteAgent(agentId: string): Promise<void> { fallbackIdentities.delete(agentId); }, }; // Fallback Heartbeat API const fallbackHeartbeat = { _configs: new Map<string, HeartbeatConfig>(), async init(agentId: string, config?: HeartbeatConfig): Promise<void> { if (config) { fallbackHeartbeat._configs.set(agentId, config); } }, async start(_agentId: string): Promise<void> { // No-op for fallback (no background tasks in browser) }, async stop(_agentId: string): Promise<void> { // No-op }, async tick(_agentId: string): Promise<HeartbeatResult> { return { status: 'ok', alerts: [], checked_items: 0, timestamp: new Date().toISOString(), }; }, async getConfig(agentId: string): Promise<HeartbeatConfig> { return fallbackHeartbeat._configs.get(agentId) ?? { enabled: false, interval_minutes: 30, quiet_hours_start: null, quiet_hours_end: null, notify_channel: 'ui', proactivity_level: 'standard', max_alerts_per_tick: 5, }; }, async updateConfig(agentId: string, config: HeartbeatConfig): Promise<void> { fallbackHeartbeat._configs.set(agentId, config); }, async getHistory(_agentId: string, _limit?: number): Promise<HeartbeatResult[]> { return []; }, }; // === Unified Client Export === /** * Unified intelligence client that automatically selects backend or fallback */ export const intelligenceClient = { memory: { init: async (): Promise<void> => { if (isTauriEnv()) { await intelligence.memory.init(); } else { await fallbackMemory.init(); } }, store: async (entry: MemoryEntryInput): Promise<string> => { if (isTauriEnv()) { return intelligence.memory.store(entry); } return fallbackMemory.store(entry); }, get: async (id: string): Promise<MemoryEntry | null> => { if (isTauriEnv()) { const result = await intelligence.memory.get(id); return result ? toFrontendMemory(result) : null; } return fallbackMemory.get(id); }, search: async (options: MemorySearchOptions): Promise<MemoryEntry[]> => { if (isTauriEnv()) { const results = await intelligence.memory.search(toBackendSearchOptions(options)); return results.map(toFrontendMemory); } return fallbackMemory.search(options); }, delete: async (id: string): Promise<void> => { if (isTauriEnv()) { await intelligence.memory.delete(id); } else { await fallbackMemory.delete(id); } }, deleteAll: async (agentId: string): Promise<number> => { if (isTauriEnv()) { return intelligence.memory.deleteAll(agentId); } return fallbackMemory.deleteAll(agentId); }, stats: async (): Promise<MemoryStats> => { if (isTauriEnv()) { const stats = await intelligence.memory.stats(); return toFrontendStats(stats); } return fallbackMemory.stats(); }, export: async (): Promise<MemoryEntry[]> => { if (isTauriEnv()) { const results = await intelligence.memory.export(); return results.map(toFrontendMemory); } return fallbackMemory.export(); }, import: async (memories: MemoryEntry[]): Promise<number> => { if (isTauriEnv()) { // Convert to backend format const backendMemories = memories.map(m => ({ ...m, agent_id: m.agentId, memory_type: m.type, last_accessed_at: m.lastAccessedAt, created_at: m.createdAt, access_count: m.accessCount, conversation_id: m.conversationId ?? null, tags: JSON.stringify(m.tags), embedding: null, })); return intelligence.memory.import(backendMemories as PersistentMemory[]); } return fallbackMemory.import(memories); }, dbPath: async (): Promise<string> => { if (isTauriEnv()) { return intelligence.memory.dbPath(); } return fallbackMemory.dbPath(); }, }, heartbeat: { init: async (agentId: string, config?: HeartbeatConfig): Promise<void> => { if (isTauriEnv()) { await intelligence.heartbeat.init(agentId, config); } else { await fallbackHeartbeat.init(agentId, config); } }, start: async (agentId: string): Promise<void> => { if (isTauriEnv()) { await intelligence.heartbeat.start(agentId); } else { await fallbackHeartbeat.start(agentId); } }, stop: async (agentId: string): Promise<void> => { if (isTauriEnv()) { await intelligence.heartbeat.stop(agentId); } else { await fallbackHeartbeat.stop(agentId); } }, tick: async (agentId: string): Promise<HeartbeatResult> => { if (isTauriEnv()) { return intelligence.heartbeat.tick(agentId); } return fallbackHeartbeat.tick(agentId); }, getConfig: async (agentId: string): Promise<HeartbeatConfig> => { if (isTauriEnv()) { return intelligence.heartbeat.getConfig(agentId); } return fallbackHeartbeat.getConfig(agentId); }, updateConfig: async (agentId: string, config: HeartbeatConfig): Promise<void> => { if (isTauriEnv()) { await intelligence.heartbeat.updateConfig(agentId, config); } else { await fallbackHeartbeat.updateConfig(agentId, config); } }, getHistory: async (agentId: string, limit?: number): Promise<HeartbeatResult[]> => { if (isTauriEnv()) { return intelligence.heartbeat.getHistory(agentId, limit); } return fallbackHeartbeat.getHistory(agentId, limit); }, updateMemoryStats: async ( agentId: string, taskCount: number, totalEntries: number, storageSizeBytes: number ): Promise<void> => { if (isTauriEnv()) { await invoke('heartbeat_update_memory_stats', { agent_id: agentId, task_count: taskCount, total_entries: totalEntries, storage_size_bytes: storageSizeBytes, }); } // Fallback: store in localStorage for non-Tauri environment const cache = { taskCount, totalEntries, storageSizeBytes, lastUpdated: new Date().toISOString(), }; localStorage.setItem(`zclaw-memory-stats-${agentId}`, JSON.stringify(cache)); }, recordCorrection: async (agentId: string, correctionType: string): Promise<void> => { if (isTauriEnv()) { await invoke('heartbeat_record_correction', { agent_id: agentId, correction_type: correctionType, }); } // Fallback: store in localStorage for non-Tauri environment const key = `zclaw-corrections-${agentId}`; const stored = localStorage.getItem(key); const counters = stored ? JSON.parse(stored) : {}; counters[correctionType] = (counters[correctionType] || 0) + 1; localStorage.setItem(key, JSON.stringify(counters)); }, recordInteraction: async (agentId: string): Promise<void> => { if (isTauriEnv()) { await invoke('heartbeat_record_interaction', { agent_id: agentId, }); } // Fallback: store in localStorage for non-Tauri environment localStorage.setItem(`zclaw-last-interaction-${agentId}`, new Date().toISOString()); }, }, compactor: { estimateTokens: async (text: string): Promise<number> => { if (isTauriEnv()) { return intelligence.compactor.estimateTokens(text); } return fallbackCompactor.estimateTokens(text); }, estimateMessagesTokens: async (messages: CompactableMessage[]): Promise<number> => { if (isTauriEnv()) { return intelligence.compactor.estimateMessagesTokens(messages); } return fallbackCompactor.estimateMessagesTokens(messages); }, checkThreshold: async ( messages: CompactableMessage[], config?: CompactionConfig ): Promise<CompactionCheck> => { if (isTauriEnv()) { return intelligence.compactor.checkThreshold(messages, config); } return fallbackCompactor.checkThreshold(messages, config); }, compact: async ( messages: CompactableMessage[], agentId: string, conversationId?: string, config?: CompactionConfig ): Promise<CompactionResult> => { if (isTauriEnv()) { return intelligence.compactor.compact(messages, agentId, conversationId, config); } return fallbackCompactor.compact(messages, agentId, conversationId, config); }, }, reflection: { init: async (config?: ReflectionConfig): Promise<void> => { if (isTauriEnv()) { await intelligence.reflection.init(config); } else { await fallbackReflection.init(config); } }, recordConversation: async (): Promise<void> => { if (isTauriEnv()) { await intelligence.reflection.recordConversation(); } else { await fallbackReflection.recordConversation(); } }, shouldReflect: async (): Promise<boolean> => { if (isTauriEnv()) { return intelligence.reflection.shouldReflect(); } return fallbackReflection.shouldReflect(); }, reflect: async (agentId: string, memories: MemoryEntryForAnalysis[]): Promise<ReflectionResult> => { if (isTauriEnv()) { return intelligence.reflection.reflect(agentId, memories); } return fallbackReflection.reflect(agentId, memories); }, getHistory: async (limit?: number): Promise<ReflectionResult[]> => { if (isTauriEnv()) { return intelligence.reflection.getHistory(limit); } return fallbackReflection.getHistory(limit); }, getState: async (): Promise<ReflectionState> => { if (isTauriEnv()) { return intelligence.reflection.getState(); } return fallbackReflection.getState(); }, }, identity: { get: async (agentId: string): Promise<IdentityFiles> => { if (isTauriEnv()) { return intelligence.identity.get(agentId); } return fallbackIdentity.get(agentId); }, getFile: async (agentId: string, file: string): Promise<string> => { if (isTauriEnv()) { return intelligence.identity.getFile(agentId, file); } return fallbackIdentity.getFile(agentId, file); }, buildPrompt: async (agentId: string, memoryContext?: string): Promise<string> => { if (isTauriEnv()) { return intelligence.identity.buildPrompt(agentId, memoryContext); } return fallbackIdentity.buildPrompt(agentId, memoryContext); }, updateUserProfile: async (agentId: string, content: string): Promise<void> => { if (isTauriEnv()) { await intelligence.identity.updateUserProfile(agentId, content); } else { await fallbackIdentity.updateUserProfile(agentId, content); } }, appendUserProfile: async (agentId: string, addition: string): Promise<void> => { if (isTauriEnv()) { await intelligence.identity.appendUserProfile(agentId, addition); } else { await fallbackIdentity.appendUserProfile(agentId, addition); } }, proposeChange: async ( agentId: string, file: 'soul' | 'instructions', suggestedContent: string, reason: string ): Promise<IdentityChangeProposal> => { if (isTauriEnv()) { return intelligence.identity.proposeChange(agentId, file, suggestedContent, reason); } return fallbackIdentity.proposeChange(agentId, file, suggestedContent, reason); }, approveProposal: async (proposalId: string): Promise<IdentityFiles> => { if (isTauriEnv()) { return intelligence.identity.approveProposal(proposalId); } return fallbackIdentity.approveProposal(proposalId); }, rejectProposal: async (proposalId: string): Promise<void> => { if (isTauriEnv()) { await intelligence.identity.rejectProposal(proposalId); } else { await fallbackIdentity.rejectProposal(proposalId); } }, getPendingProposals: async (agentId?: string): Promise<IdentityChangeProposal[]> => { if (isTauriEnv()) { return intelligence.identity.getPendingProposals(agentId); } return fallbackIdentity.getPendingProposals(agentId); }, updateFile: async (agentId: string, file: string, content: string): Promise<void> => { if (isTauriEnv()) { await intelligence.identity.updateFile(agentId, file, content); } else { await fallbackIdentity.updateFile(agentId, file, content); } }, getSnapshots: async (agentId: string, limit?: number): Promise<IdentitySnapshot[]> => { if (isTauriEnv()) { return intelligence.identity.getSnapshots(agentId, limit); } return fallbackIdentity.getSnapshots(agentId, limit); }, restoreSnapshot: async (agentId: string, snapshotId: string): Promise<void> => { if (isTauriEnv()) { await intelligence.identity.restoreSnapshot(agentId, snapshotId); } else { await fallbackIdentity.restoreSnapshot(agentId, snapshotId); } }, listAgents: async (): Promise<string[]> => { if (isTauriEnv()) { return intelligence.identity.listAgents(); } return fallbackIdentity.listAgents(); }, deleteAgent: async (agentId: string): Promise<void> => { if (isTauriEnv()) { await intelligence.identity.deleteAgent(agentId); } else { await fallbackIdentity.deleteAgent(agentId); } }, }, }; export default intelligenceClient; |