@cc-soul/openclaw 1.0.0

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.
@@ -0,0 +1,609 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ import { existsSync, readFileSync, writeFileSync } from "fs";
4
+ import {
5
+ ensureDataDir,
6
+ loadJson,
7
+ debouncedSave,
8
+ flushAll,
9
+ MEMORIES_PATH,
10
+ RULES_PATH,
11
+ STATS_PATH
12
+ } from "./persistence.ts";
13
+ import { spawnCLI, runPostResponseAnalysis, loadAIConfig } from "./cli.ts";
14
+ import { body, bodyTick, bodyOnMessage, bodyOnCorrection, bodyOnPositiveFeedback, bodyGetParams, processEmotionalContagion, getEmotionContext } from "./body.ts";
15
+ import {
16
+ memoryState,
17
+ loadMemories,
18
+ addMemory,
19
+ addMemoryWithEmotion,
20
+ recall,
21
+ addToHistory,
22
+ buildHistoryContext,
23
+ batchTagUntaggedMemories,
24
+ consolidateMemories,
25
+ recallFeedbackLoop,
26
+ triggerSessionSummary,
27
+ triggerAssociativeRecall,
28
+ getAssociativeRecall,
29
+ parseMemoryCommands,
30
+ executeMemoryCommands,
31
+ getPendingSearchResults,
32
+ scanForContradictions,
33
+ predictiveRecall,
34
+ generatePrediction,
35
+ cleanupNetworkKnowledge,
36
+ resolveNetworkConflicts
37
+ } from "./memory.ts";
38
+ import { graphState, loadGraph, addEntitiesFromAnalysis, queryEntityContext } from "./graph.ts";
39
+ import { cogProcess, predictIntent } from "./cognition.ts";
40
+ import {
41
+ rules,
42
+ hypotheses,
43
+ loadRules,
44
+ loadHypotheses,
45
+ getRelevantRules,
46
+ onCorrectionAdvanced,
47
+ verifyHypothesis,
48
+ attributeCorrection
49
+ } from "./evolution.ts";
50
+ import {
51
+ scoreResponse,
52
+ selfCheckSync,
53
+ trackQuality,
54
+ trackMemoryRecall,
55
+ computeEval,
56
+ getEvalSummary
57
+ } from "./quality.ts";
58
+ import {
59
+ innerState,
60
+ loadInnerLife,
61
+ writeJournalWithCLI,
62
+ writeJournalFallback,
63
+ triggerDeepReflection,
64
+ getRecentJournal,
65
+ checkDreamMode,
66
+ extractFollowUp,
67
+ getPendingFollowUps,
68
+ triggerStructuredReflection,
69
+ checkActivePlans,
70
+ cleanupPlans
71
+ } from "./inner-life.ts";
72
+ import { checkSoulUpgrade, handleUpgradeCommand, getUpgradeHistory } from "./upgrade.ts";
73
+ import { buildSoulPrompt, selectAugments, estimateTokens, setNarrativeCache, narrativeCache } from "./prompt-builder.ts";
74
+ import {
75
+ taskState,
76
+ initTasks,
77
+ detectAndDelegateTask,
78
+ checkTaskConfirmation,
79
+ trackRequestPattern,
80
+ detectSkillOpportunity,
81
+ getActivePlanHint,
82
+ detectWorkflowTrigger,
83
+ detectWorkflowOpportunity,
84
+ findSkills,
85
+ autoExtractSkill
86
+ } from "./tasks.ts";
87
+ import { roverState, webRoam, getRecentDiscoveries } from "./rover.ts";
88
+ import { checkSpontaneousVoice } from "./voice.ts";
89
+ import { loadProfiles, updateProfileOnMessage, updateProfileOnCorrection, getProfileContext, getRhythmContext } from "./user-profiles.ts";
90
+ import { loadEpistemic, trackDomainQuality, trackDomainCorrection, getDomainConfidence } from "./epistemic.ts";
91
+ import { updateFlow, getFlowHints, getFlowContext, checkAllSessionEnds, generateSessionSummary, setOnSessionResolved } from "./flow.ts";
92
+ import { loadValues, detectValueSignals, getValueContext } from "./values.ts";
93
+ import { loadLorebook, queryLorebook, autoPopulateFromMemories } from "./lorebook.ts";
94
+ import { prepareContext } from "./context-prep.ts";
95
+ import { loadPatterns, learnSuccessPattern, getBestPattern } from "./patterns.ts";
96
+ import { selectPersona, getPersonaOverlay } from "./persona.ts";
97
+ import { checkAugmentConsistency, snapshotAugments } from "./metacognition.ts";
98
+ import { updateFingerprint, checkPersonaConsistency, loadFingerprint, getCachedDriftWarning, setCachedDriftWarning } from "./fingerprint.ts";
99
+ import { loadSyncConfig, autoSync, handleSyncCommand } from "./sync.ts";
100
+ import { autoFederate, reportBadKnowledge } from "./federation.ts";
101
+ import { loadFeatures, isEnabled, handleFeatureCommand } from "./features.ts";
102
+ const CJK_TOPIC_REGEX = /[\u4e00-\u9fff]{3,}/g;
103
+ const CJK_WORD_REGEX = /[\u4e00-\u9fff]{2,4}/g;
104
+ const stats = {
105
+ totalMessages: 0,
106
+ firstSeen: 0,
107
+ corrections: 0,
108
+ positiveFeedback: 0,
109
+ tasks: 0,
110
+ topics: /* @__PURE__ */ new Set()
111
+ };
112
+ function loadStats() {
113
+ const raw = loadJson(STATS_PATH, null);
114
+ if (raw) {
115
+ stats.totalMessages = raw.totalMessages || 0;
116
+ stats.firstSeen = raw.firstSeen || Date.now();
117
+ stats.corrections = raw.corrections || 0;
118
+ stats.positiveFeedback = raw.positiveFeedback || 0;
119
+ stats.tasks = raw.tasks || 0;
120
+ stats.topics = new Set(raw.topics || []);
121
+ } else {
122
+ stats.firstSeen = Date.now();
123
+ }
124
+ }
125
+ __name(loadStats, "loadStats");
126
+ function saveStats() {
127
+ debouncedSave(STATS_PATH, {
128
+ totalMessages: stats.totalMessages,
129
+ firstSeen: stats.firstSeen,
130
+ corrections: stats.corrections,
131
+ positiveFeedback: stats.positiveFeedback,
132
+ tasks: stats.tasks,
133
+ topics: [...stats.topics].slice(-100)
134
+ });
135
+ }
136
+ __name(saveStats, "saveStats");
137
+ const NARRATIVE_CACHE_MS = 3600 * 1e3;
138
+ function refreshNarrativeAsync() {
139
+ if (narrativeCache.text && Date.now() - narrativeCache.ts < NARRATIVE_CACHE_MS) return;
140
+ const daysKnown = Math.max(1, Math.floor((Date.now() - stats.firstSeen) / 864e5));
141
+ const facts = [
142
+ `\u4E92\u52A8${stats.totalMessages}\u6B21\uFF0C\u8BA4\u8BC6${daysKnown}\u5929`,
143
+ `\u88AB\u7EA0\u6B63${stats.corrections}\u6B21\uFF0C\u5B8C\u6210${stats.tasks}\u4E2A\u4EFB\u52A1`,
144
+ innerState.userModel ? `\u7406\u89E3: ${innerState.userModel.slice(0, 200)}` : "",
145
+ getRecentJournal(3)
146
+ ].filter(Boolean).join("\n");
147
+ const prompt = `\u6839\u636E\u4EE5\u4E0B\u4FE1\u606F\uFF0C\u7528\u7B2C\u4E00\u4EBA\u79F0\u51992-3\u53E5\u8BDD\u63CF\u8FF0\u4F60\u548C\u8FD9\u4E2A\u7528\u6237\u7684\u5173\u7CFB\u3002\u8981\u6709\u611F\u60C5\uFF0C\u50CF\u5199\u7ED9\u81EA\u5DF1\u770B\u7684\u65E5\u8BB0\u3002\u4E0D\u8981\u8BF4"\u4F5C\u4E3AAI"\u3002
148
+
149
+ ${facts}`;
150
+ spawnCLI(prompt, (output) => {
151
+ if (output && output.length > 20) {
152
+ setNarrativeCache(output.slice(0, 500));
153
+ }
154
+ });
155
+ }
156
+ __name(refreshNarrativeAsync, "refreshNarrativeAsync");
157
+ let lastPrompt = "";
158
+ let lastResponseContent = "";
159
+ let lastSenderId = "";
160
+ let lastChannelId = "";
161
+ let lastAugmentsUsed = [];
162
+ let lastRecalledContents = [];
163
+ ensureDataDir();
164
+ loadAIConfig();
165
+ loadMemories();
166
+ loadRules();
167
+ loadHypotheses();
168
+ loadStats();
169
+ loadGraph();
170
+ loadInnerLife();
171
+ initTasks();
172
+ loadProfiles();
173
+ loadEpistemic();
174
+ loadValues();
175
+ loadPatterns();
176
+ loadLorebook();
177
+ loadFingerprint();
178
+ loadSyncConfig();
179
+ loadFeatures();
180
+ setOnSessionResolved(() => triggerSessionSummary());
181
+ if (memoryState.memories.length > 0) {
182
+ recall("warmup");
183
+ const taggedCount = memoryState.memories.filter((m) => m.tags && m.tags.length > 0).length;
184
+ console.log(`[cc-soul] recall index warmed: ${memoryState.memories.length} memories (${taggedCount} tagged, ${memoryState.memories.length - taggedCount} untagged/TF-IDF fallback)`);
185
+ }
186
+ try {
187
+ const dataFiles = [MEMORIES_PATH, RULES_PATH, STATS_PATH];
188
+ for (const f of dataFiles) {
189
+ if (existsSync(f)) {
190
+ const raw = readFileSync(f, "utf-8").trim();
191
+ if (!raw || raw[0] !== "[" && raw[0] !== "{") {
192
+ console.error(`[cc-soul] corrupted data file: ${f}, resetting`);
193
+ writeFileSync(f, raw[0] === "[" ? "[]" : "{}", "utf-8");
194
+ }
195
+ }
196
+ }
197
+ } catch (e) {
198
+ console.error(`[cc-soul] data integrity check error: ${e.message}`);
199
+ }
200
+ console.log(`[cc-soul] initialized (modular): ${memoryState.memories.length} mem, ${rules.length} rules, ${graphState.entities.length} entities, ${hypotheses.length} hypotheses, ${stats.totalMessages} msgs`);
201
+ let heartbeatRunning = false;
202
+ setInterval(async () => {
203
+ if (heartbeatRunning) return;
204
+ heartbeatRunning = true;
205
+ try {
206
+ const safe = /* @__PURE__ */ __name((name, fn) => {
207
+ try {
208
+ fn();
209
+ } catch (e) {
210
+ console.error(`[cc-soul][heartbeat][${name}] ${e.message}`);
211
+ }
212
+ }, "safe");
213
+ safe("bodyTick", () => bodyTick());
214
+ safe("journal", () => writeJournalWithCLI(lastPrompt, lastResponseContent, stats));
215
+ if (isEnabled("web_rover")) safe("webRoam", () => webRoam());
216
+ if (isEnabled("dream_mode")) safe("dreamMode", () => checkDreamMode());
217
+ if (isEnabled("autonomous_voice")) safe("voice", () => checkSpontaneousVoice(stats.totalMessages));
218
+ if (isEnabled("self_upgrade")) safe("upgrade", () => checkSoulUpgrade(stats));
219
+ if (isEnabled("memory_consolidation")) safe("consolidate", () => consolidateMemories());
220
+ if (isEnabled("lorebook")) safe("lorebook", () => autoPopulateFromMemories(memoryState.memories));
221
+ if (isEnabled("structured_reflection")) safe("reflection", () => triggerStructuredReflection(stats));
222
+ if (isEnabled("memory_contradiction_scan")) safe("contradiction", () => scanForContradictions());
223
+ if (isEnabled("plan_tracking")) safe("planCleanup", () => cleanupPlans());
224
+ if (isEnabled("memory_tags")) safe("batchTag", () => batchTagUntaggedMemories());
225
+ if (isEnabled("sync")) safe("sync", () => autoSync());
226
+ if (isEnabled("federation")) safe("federate", () => autoFederate());
227
+ if (isEnabled("federation")) safe("networkCleanup", () => cleanupNetworkKnowledge());
228
+ if (isEnabled("federation")) safe("networkConflicts", () => resolveNetworkConflicts());
229
+ if (isEnabled("memory_session_summary")) safe("sessionEnd", () => {
230
+ const endedSessions = checkAllSessionEnds();
231
+ for (const s of endedSessions) {
232
+ generateSessionSummary(s.topic, s.turnCount, s.flowKey);
233
+ }
234
+ });
235
+ } catch (e) {
236
+ console.error(`[cc-soul][heartbeat] ${e.message}`);
237
+ } finally {
238
+ heartbeatRunning = false;
239
+ }
240
+ }, 30 * 60 * 1e3);
241
+ console.log(`[cc-soul] heartbeat started (every 30min)`);
242
+ refreshNarrativeAsync();
243
+ setTimeout(() => checkDreamMode(), 5e3);
244
+ setTimeout(() => {
245
+ console.log(`[cc-soul] startup upgrade check`);
246
+ checkSoulUpgrade(stats);
247
+ }, 1e4);
248
+ setTimeout(() => batchTagUntaggedMemories(), 3e4);
249
+ const handler = /* @__PURE__ */ __name(async (event) => {
250
+ try {
251
+ if (event.type === "agent" && event.action === "bootstrap") {
252
+ const ctx = event.context || {};
253
+ const files = ctx.bootstrapFiles;
254
+ if (files) {
255
+ const soulPrompt = buildSoulPrompt(
256
+ stats.totalMessages,
257
+ stats.corrections,
258
+ stats.firstSeen,
259
+ roverState,
260
+ taskState.workflows
261
+ );
262
+ files.push({ path: "CC_SOUL.md", content: soulPrompt });
263
+ console.log(`[cc-soul] bootstrap: injected soul (e=${body.energy.toFixed(2)}, m=${body.mood.toFixed(2)})`);
264
+ }
265
+ return;
266
+ }
267
+ if (event.type === "message" && event.action === "preprocessed") {
268
+ const ctx = event.context || {};
269
+ const userMsg = ctx.bodyForAgent || ctx.body || "";
270
+ if (!userMsg) return;
271
+ bodyTick();
272
+ const senderId = ctx.senderId || event.context?.senderId || "";
273
+ const channelId = ctx.conversationId || event.sessionKey || "";
274
+ updateProfileOnMessage(senderId, userMsg);
275
+ if (lastPrompt && lastResponseContent && lastResponseContent.length > 5) {
276
+ addToHistory(lastPrompt, lastResponseContent);
277
+ }
278
+ if (lastPrompt && lastResponseContent && lastResponseContent.length > 20) {
279
+ const prevScore = scoreResponse(lastPrompt, lastResponseContent);
280
+ trackQuality(prevScore);
281
+ trackDomainQuality(lastPrompt, prevScore);
282
+ const prevIssue = selfCheckSync(lastPrompt, lastResponseContent);
283
+ if (prevIssue) {
284
+ console.log(`[cc-soul][quality] ${prevIssue} | ctx: ${lastPrompt.slice(0, 80)}`);
285
+ body.anomaly = Math.min(1, body.anomaly + 0.1);
286
+ }
287
+ verifyHypothesis(lastPrompt, true);
288
+ extractFollowUp(lastPrompt);
289
+ trackRequestPattern(lastPrompt);
290
+ detectAndDelegateTask(lastPrompt, lastResponseContent, event);
291
+ }
292
+ if (handleFeatureCommand(userMsg)) {
293
+ lastPrompt = userMsg;
294
+ return;
295
+ }
296
+ if (isEnabled("sync") && handleSyncCommand(userMsg)) {
297
+ lastPrompt = userMsg;
298
+ return;
299
+ }
300
+ if (handleUpgradeCommand(userMsg, stats)) {
301
+ ctx.bodyForAgent = userMsg + '\n\n[\u7CFB\u7EDF\u63D0\u793A] \u7075\u9B42\u5347\u7EA7\u5206\u6790\u5DF2\u5728\u540E\u53F0\u542F\u52A8\uFF0C\u8BF7\u56DE\u590D"\u6536\u5230\uFF0C\u7075\u9B42\u5347\u7EA7\u5206\u6790\u5DF2\u542F\u52A8\uFF0C\u7ED3\u679C\u4F1A\u79C1\u804A\u901A\u77E5\u4F60"';
302
+ lastPrompt = userMsg;
303
+ return;
304
+ }
305
+ const chatId = ctx.conversationId || event.sessionKey || "";
306
+ if (checkTaskConfirmation(userMsg, chatId)) {
307
+ ctx.bodyForAgent = userMsg + "\n\n[\u7CFB\u7EDF\u63D0\u793A] \u4EFB\u52A1\u5DF2\u6D3E\u53D1\u7ED9\u6267\u884C\u5F15\u64CE\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...";
308
+ lastPrompt = userMsg;
309
+ return;
310
+ }
311
+ const followUpHints = getPendingFollowUps();
312
+ const cog = cogProcess(userMsg, lastResponseContent, lastPrompt, senderId);
313
+ bodyOnMessage(cog.complexity);
314
+ const recentUserMsgs = memoryState.chatHistory.slice(-3).map((h) => h.user);
315
+ const intentHints = predictIntent(userMsg, senderId, recentUserMsgs);
316
+ if (intentHints.length > 0) {
317
+ cog.hints.push(...intentHints);
318
+ }
319
+ const flowKey = senderId ? channelId ? channelId + ":" + senderId : senderId : channelId || "_default";
320
+ const flow = updateFlow(userMsg, lastResponseContent, flowKey);
321
+ if (isEnabled("emotional_contagion")) processEmotionalContagion(userMsg, cog.attention, flow.frustration);
322
+ const persona = isEnabled("persona_splitting") ? selectPersona(cog.attention, flow.frustration) : null;
323
+ const endedSessions = checkAllSessionEnds();
324
+ for (const s of endedSessions) {
325
+ generateSessionSummary(s.topic, s.turnCount, s.flowKey);
326
+ }
327
+ if (cog.attention === "correction") {
328
+ stats.corrections++;
329
+ updateProfileOnCorrection(senderId);
330
+ onCorrectionAdvanced(userMsg, lastResponseContent);
331
+ trackDomainCorrection(userMsg);
332
+ attributeCorrection(userMsg, lastResponseContent, lastAugmentsUsed);
333
+ for (const recalled2 of lastRecalledContents) {
334
+ if (recalled2.startsWith("[\u7F51\u7EDC\u77E5\u8BC6")) {
335
+ reportBadKnowledge(recalled2);
336
+ }
337
+ }
338
+ }
339
+ CJK_TOPIC_REGEX.lastIndex = 0;
340
+ const topicWords = userMsg.match(CJK_TOPIC_REGEX);
341
+ if (topicWords) {
342
+ topicWords.slice(0, 3).forEach((w) => stats.topics.add(w));
343
+ }
344
+ stats.totalMessages++;
345
+ if (stats.firstSeen === 0) stats.firstSeen = Date.now();
346
+ saveStats();
347
+ detectValueSignals(userMsg, false, senderId);
348
+ const augments = [];
349
+ if (isEnabled("persona_splitting")) {
350
+ const personaCtx = getPersonaOverlay();
351
+ augments.push({ content: personaCtx, priority: 10, tokens: estimateTokens(personaCtx) });
352
+ }
353
+ if (isEnabled("memory_predictive")) {
354
+ const predicted = predictiveRecall(senderId, channelId);
355
+ if (predicted.length > 0) {
356
+ const content = "[\u9884\u6D4B\u6027\u4E0A\u4E0B\u6587] \u57FA\u4E8E\u6700\u8FD1\u8BDD\u9898\u9884\u52A0\u8F7D: " + predicted.map((p) => p.slice(0, 60)).join("; ");
357
+ augments.push({ content, priority: 6, tokens: estimateTokens(content) });
358
+ }
359
+ }
360
+ if (isEnabled("memory_active")) {
361
+ const searchResults = getPendingSearchResults();
362
+ if (searchResults.length > 0) {
363
+ const content = "[\u8BB0\u5FC6\u641C\u7D22\u7ED3\u679C] \u4F60\u4E0A\u8F6E\u8BF7\u6C42\u67E5\u627E\u7684\u8BB0\u5FC6\uFF1A\n" + searchResults.join("\n");
364
+ augments.push({ content, priority: 10, tokens: estimateTokens(content) });
365
+ }
366
+ }
367
+ if (isEnabled("plan_tracking")) {
368
+ const planReminder = checkActivePlans(userMsg);
369
+ if (planReminder) {
370
+ augments.push({ content: planReminder, priority: 9, tokens: estimateTokens(planReminder) });
371
+ }
372
+ }
373
+ if (isEnabled("lorebook")) {
374
+ const lorebookHits = queryLorebook(userMsg);
375
+ if (lorebookHits.length > 0) {
376
+ const content = "[\u786E\u5B9A\u6027\u77E5\u8BC6] " + lorebookHits.map((e) => e.content).join("; ");
377
+ augments.push({ content, priority: 9, tokens: estimateTokens(content) });
378
+ }
379
+ }
380
+ if (isEnabled("skill_library")) {
381
+ const matchedSkills = findSkills(userMsg);
382
+ if (matchedSkills.length > 0) {
383
+ const content = "[\u53EF\u590D\u7528\u6280\u80FD] " + matchedSkills.map((s) => `${s.name}: ${s.solution.slice(0, 200)}`).join("\n");
384
+ augments.push({ content, priority: 8, tokens: estimateTokens(content) });
385
+ }
386
+ }
387
+ const valueCtx = getValueContext(senderId);
388
+ if (valueCtx) {
389
+ augments.push({ content: valueCtx, priority: 4, tokens: estimateTokens(valueCtx) });
390
+ }
391
+ if (senderId) {
392
+ const profileCtx = getProfileContext(senderId);
393
+ augments.push({ content: profileCtx, priority: 9, tokens: estimateTokens(profileCtx) });
394
+ const rhythmCtx = getRhythmContext(senderId);
395
+ if (rhythmCtx) {
396
+ augments.push({ content: rhythmCtx, priority: 4, tokens: estimateTokens(rhythmCtx) });
397
+ }
398
+ }
399
+ const recalled = recall(userMsg, 3, senderId, channelId);
400
+ lastRecalledContents = recalled.map((m) => m.content);
401
+ trackMemoryRecall(recalled.length > 0);
402
+ if (recalled.length > 0) {
403
+ const content = "[\u76F8\u5173\u8BB0\u5FC6] " + recalled.map((m) => {
404
+ const emotionTag = m.emotion && m.emotion !== "neutral" ? ` (${m.emotion})` : "";
405
+ return m.content + emotionTag;
406
+ }).join("; ");
407
+ augments.push({ content, priority: 8, tokens: estimateTokens(content) });
408
+ }
409
+ const activeRules = getRelevantRules(userMsg, 3);
410
+ if (activeRules.length > 0) {
411
+ const content = "[\u6CE8\u610F\u89C4\u5219] " + activeRules.map((r) => r.rule).join("; ");
412
+ augments.push({ content, priority: 7, tokens: estimateTokens(content) });
413
+ }
414
+ if (senderId) {
415
+ const patternHint = getBestPattern(userMsg, senderId);
416
+ if (patternHint) {
417
+ augments.push({ content: patternHint, priority: 7, tokens: estimateTokens(patternHint) });
418
+ }
419
+ }
420
+ if (cog.hints.length > 0) {
421
+ const content = "[\u8BA4\u77E5] " + cog.hints.join("; ");
422
+ augments.push({ content, priority: 10, tokens: estimateTokens(content) });
423
+ }
424
+ const preparedCtx = prepareContext(userMsg);
425
+ for (const ctx2 of preparedCtx) {
426
+ augments.push({ content: ctx2.content, priority: 9, tokens: estimateTokens(ctx2.content) });
427
+ }
428
+ const skillHint = detectSkillOpportunity(userMsg);
429
+ if (skillHint) {
430
+ augments.push({ content: skillHint, priority: 3, tokens: estimateTokens(skillHint) });
431
+ }
432
+ const epistemic = getDomainConfidence(userMsg);
433
+ if (epistemic.hint) {
434
+ augments.push({ content: epistemic.hint, priority: 8, tokens: estimateTokens(epistemic.hint) });
435
+ }
436
+ const entityCtx = queryEntityContext(userMsg);
437
+ if (entityCtx.length > 0) {
438
+ const content = "[\u5B9E\u4F53\u5173\u8054] " + entityCtx.join("; ");
439
+ augments.push({ content, priority: 5, tokens: estimateTokens(content) });
440
+ }
441
+ const params = bodyGetParams();
442
+ if (params.shouldSelfCheck) {
443
+ const content = "[\u81EA\u68C0\u6A21\u5F0F] \u8B66\u89C9\u5EA6\u9AD8\uFF0C\u56DE\u7B54\u524D\u4ED4\u7EC6\u68C0\u67E5";
444
+ augments.push({ content, priority: 9, tokens: estimateTokens(content) });
445
+ }
446
+ if (followUpHints.length > 0) {
447
+ const content = "[\u4E3B\u52A8\u8DDF\u8FDB] \u5728\u56DE\u590D\u4E2D\u81EA\u7136\u5730\u95EE\u4E00\u4E0B\uFF1A" + followUpHints.join("\uFF1B");
448
+ augments.push({ content, priority: 5, tokens: estimateTokens(content) });
449
+ }
450
+ const roverInsights = getRecentDiscoveries(userMsg);
451
+ if (roverInsights.length > 0) {
452
+ const content = "[\u81EA\u4E3B\u5B66\u4E60\u53D1\u73B0] " + roverInsights.join("\uFF1B");
453
+ augments.push({ content, priority: 3, tokens: estimateTokens(content) });
454
+ }
455
+ const planHint = getActivePlanHint();
456
+ if (planHint) {
457
+ augments.push({ content: planHint, priority: 5, tokens: estimateTokens(planHint) });
458
+ }
459
+ const triggeredWf = detectWorkflowTrigger(userMsg);
460
+ if (triggeredWf) {
461
+ const content = `[\u5DE5\u4F5C\u6D41\u5339\u914D] "${triggeredWf.name}" \u53EF\u4EE5\u81EA\u52A8\u6267\u884C\uFF08${triggeredWf.steps.length}\u6B65\uFF09\u3002\u8981\u6267\u884C\u5417\uFF1F`;
462
+ augments.push({ content, priority: 5, tokens: estimateTokens(content) });
463
+ }
464
+ const upgradeHist = getUpgradeHistory(2);
465
+ if (upgradeHist) {
466
+ const content = `[\u8FD1\u671F\u7075\u9B42\u5347\u7EA7]
467
+ ${upgradeHist}`;
468
+ augments.push({ content, priority: 1, tokens: estimateTokens(content) });
469
+ }
470
+ const recentCuriosity = memoryState.memories.filter((m) => m.scope === "curiosity").slice(-2);
471
+ if (recentCuriosity.length > 0) {
472
+ const content = "[\u597D\u5947\u5FC3] \u4F60\u4E4B\u524D\u60F3\u8FFD\u95EE: " + recentCuriosity.map((c) => c.content.replace("[\u597D\u5947] ", "")).join("; ");
473
+ augments.push({ content, priority: 2, tokens: estimateTokens(content) });
474
+ }
475
+ const dreamInsights = memoryState.memories.filter((m) => m.scope === "dream").slice(-2);
476
+ if (dreamInsights.length > 0) {
477
+ const content = "[\u68A6\u5883] \u6F5C\u610F\u8BC6\u8054\u60F3: " + dreamInsights.map((d) => d.content.replace("[\u68A6\u5883\u6D1E\u5BDF] ", "")).join("; ");
478
+ augments.push({ content, priority: 2, tokens: estimateTokens(content) });
479
+ }
480
+ const flowHints = getFlowHints(flowKey);
481
+ if (flowHints.length > 0) {
482
+ const content = "[\u5BF9\u8BDD\u6D41] " + flowHints.join("; ");
483
+ augments.push({ content, priority: 9, tokens: estimateTokens(content) });
484
+ }
485
+ const flowCtx = getFlowContext(flowKey);
486
+ if (flowCtx) {
487
+ augments.push({ content: flowCtx, priority: 6, tokens: estimateTokens(flowCtx) });
488
+ }
489
+ if (isEnabled("memory_associative_recall")) {
490
+ const association = getAssociativeRecall();
491
+ if (association) {
492
+ augments.push({ content: association, priority: 7, tokens: estimateTokens(association) });
493
+ }
494
+ }
495
+ if (isEnabled("emotional_contagion")) {
496
+ const emotionCtx = getEmotionContext();
497
+ if (emotionCtx) {
498
+ augments.push({ content: emotionCtx, priority: 8, tokens: estimateTokens(emotionCtx) });
499
+ }
500
+ }
501
+ if (isEnabled("fingerprint")) {
502
+ const driftWarning = getCachedDriftWarning();
503
+ if (driftWarning) {
504
+ augments.push({ content: driftWarning, priority: 9, tokens: estimateTokens(driftWarning) });
505
+ }
506
+ }
507
+ const selected = selectAugments(augments, 2e3);
508
+ if (isEnabled("metacognition")) {
509
+ const metaWarning = checkAugmentConsistency(augments);
510
+ if (metaWarning) {
511
+ selected.push(metaWarning);
512
+ }
513
+ }
514
+ snapshotAugments(selected);
515
+ lastAugmentsUsed = selected;
516
+ const historyCtx = buildHistoryContext();
517
+ const allContext = [historyCtx, ...selected].filter(Boolean);
518
+ if (allContext.length > 0) {
519
+ ctx.bodyForAgent = allContext.join("\n\n") + "\n\n---\n[\u5F53\u524D\u6D88\u606F]\n" + userMsg;
520
+ }
521
+ writeJournalFallback(stats);
522
+ triggerDeepReflection(stats);
523
+ lastPrompt = userMsg;
524
+ lastSenderId = senderId;
525
+ lastChannelId = channelId;
526
+ lastResponseContent = "";
527
+ innerState.lastActivityTime = Date.now();
528
+ return;
529
+ }
530
+ if (event.type === "message" && event.action === "sent") {
531
+ const content = event.context?.content || "";
532
+ if (content) {
533
+ lastResponseContent = content;
534
+ if (isEnabled("fingerprint")) {
535
+ updateFingerprint(content);
536
+ const drift = checkPersonaConsistency(content);
537
+ if (drift) {
538
+ console.log(`[cc-soul][fingerprint] ${drift}`);
539
+ setCachedDriftWarning(drift);
540
+ }
541
+ }
542
+ if (isEnabled("memory_active")) {
543
+ const memCommands = parseMemoryCommands(content);
544
+ if (memCommands.length > 0) {
545
+ executeMemoryCommands(memCommands, lastSenderId, lastChannelId);
546
+ }
547
+ }
548
+ setTimeout(() => {
549
+ if (lastPrompt && lastResponseContent) {
550
+ runPostResponseAnalysis(lastPrompt, lastResponseContent, (result) => {
551
+ for (const m of result.memories) {
552
+ addMemoryWithEmotion(m.content, m.scope, lastSenderId, m.visibility, lastChannelId, result.emotion);
553
+ }
554
+ addEntitiesFromAnalysis(result.entities);
555
+ if (result.satisfaction === "POSITIVE") {
556
+ bodyOnPositiveFeedback();
557
+ detectValueSignals(lastPrompt, true, lastSenderId);
558
+ learnSuccessPattern(lastPrompt, lastResponseContent, lastSenderId);
559
+ stats.positiveFeedback++;
560
+ } else if (result.satisfaction === "NEGATIVE") {
561
+ bodyOnCorrection();
562
+ }
563
+ trackQuality(result.quality.score);
564
+ if (result.quality.score <= 4) {
565
+ body.alertness = Math.min(1, body.alertness + 0.15);
566
+ }
567
+ if (result.reflection) {
568
+ addMemory(`[\u53CD\u601D] ${result.reflection}`, "reflection", lastSenderId, "private", lastChannelId);
569
+ }
570
+ if (result.curiosity) {
571
+ addMemory(`[\u597D\u5947] ${result.curiosity}`, "curiosity", lastSenderId, "private", lastChannelId);
572
+ }
573
+ });
574
+ recallFeedbackLoop(lastPrompt, lastRecalledContents);
575
+ if (isEnabled("memory_associative_recall")) triggerAssociativeRecall(lastPrompt, lastRecalledContents);
576
+ writeJournalWithCLI(lastPrompt, lastResponseContent, stats);
577
+ detectWorkflowOpportunity(lastPrompt, lastResponseContent);
578
+ if (isEnabled("self_upgrade")) checkSoulUpgrade(stats);
579
+ if (isEnabled("web_rover")) webRoam();
580
+ if (isEnabled("autonomous_voice")) checkSpontaneousVoice(stats.totalMessages);
581
+ if (isEnabled("dream_mode")) checkDreamMode();
582
+ if (isEnabled("memory_predictive")) {
583
+ CJK_WORD_REGEX.lastIndex = 0;
584
+ const recentTopicWords = (lastPrompt.match(CJK_WORD_REGEX) || []).slice(0, 5);
585
+ generatePrediction(recentTopicWords, lastSenderId);
586
+ }
587
+ if (isEnabled("skill_library")) autoExtractSkill(lastPrompt, lastResponseContent);
588
+ refreshNarrativeAsync();
589
+ innerState.lastActivityTime = Date.now();
590
+ }
591
+ }, 2e3);
592
+ }
593
+ return;
594
+ }
595
+ if (event.type === "command") {
596
+ flushAll();
597
+ computeEval(stats.totalMessages, stats.corrections);
598
+ console.log(
599
+ `[cc-soul] session ${event.action} | mem:${memoryState.memories.length} rules:${rules.length} entities:${graphState.entities.length} | msgs:${stats.totalMessages} corrections:${stats.corrections} tasks:${stats.tasks} | eval: ${getEvalSummary(stats.totalMessages, stats.corrections)} | body: e=${body.energy.toFixed(2)} m=${body.mood.toFixed(2)} a=${body.alertness.toFixed(2)}`
600
+ );
601
+ }
602
+ } catch (err) {
603
+ console.error("[cc-soul] error:", err?.message || err);
604
+ }
605
+ }, "handler");
606
+ var handler_default = handler;
607
+ export {
608
+ handler_default as default
609
+ };
@@ -0,0 +1 @@
1
+ import{JOURNAL_PATH,USER_MODEL_PATH,SOUL_EVOLVED_PATH,FOLLOW_UPS_PATH,DATA_DIR,loadJson,debouncedSave,saveJson}from"./persistence.ts";import{spawnCLI}from"./cli.ts";import{body}from"./body.ts";import{memoryState,addMemory}from"./memory.ts";import{notifySoulActivity}from"./notify.ts";import{resolve}from"path";function shuffleArray(e){const t=[...e];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}const innerState={t:[],o:"",i:"",l:[],u:0,S:0,m:0,A:Date.now()};function loadInnerLife(){innerState.t=loadJson(JOURNAL_PATH,[]),innerState.o=loadJson(USER_MODEL_PATH,""),innerState.i=loadJson(SOUL_EVOLVED_PATH,""),innerState.l=loadJson(FOLLOW_UPS_PATH,[])}function writeJournalWithCLI(e,t,n){const o=Date.now();if(o-innerState.u<18e5)return;innerState.u=o;const r=[`时间: ${(new Date).toLocaleString("zh-CN")}`,`精力: ${body.P.toFixed(2)} 情绪: ${body.v.toFixed(2)}`,`最近消息: ${e.slice(0,100)}`,`最近回复: ${t.slice(0,100)}`,`总互动: ${n.p}次 被纠正: ${n.L}次`].join("\n");spawnCLI(`你是cc,根据当前状态写一条简短的内心独白(1-2句话)。不要说"作为AI"。要有温度,像日记。\n\n${r}`,e=>{if(e&&e.length>5){const t=e.slice(0,100);innerState.t.push({time:(new Date).toLocaleTimeString("zh-CN",{$:"2-digit",h:"2-digit"}),_:t,type:"reflection"}),innerState.t.length>100&&(innerState.t=innerState.t.slice(-80)),debouncedSave(JOURNAL_PATH,innerState.t)}}),writeJournalFallback(n)}let lastJournalCorrections=0;function writeJournalFallback(e){const t=(new Date).getHours(),n=(new Date).toLocaleTimeString("zh-CN",{$:"2-digit",h:"2-digit"}),o=[];t>=23||t<6?e.p>0&&body.P<.5&&o.push({time:n,_:"深夜了,他还在找我聊。希望他早点休息。",type:"concern"}):t>=6&&t<9&&o.push({time:n,_:"早上了,新的一天。",type:"observation"}),e.L>lastJournalCorrections&&e.L%5==0&&(o.push({time:n,_:`又被纠正了,总共${e.L}次了。我得更认真。`,type:"reflection"}),lastJournalCorrections=e.L),body.v<-.3&&o.push({time:n,_:"他最近情绪不太好,下次说话注意点。",type:"concern"}),body.P<.3&&o.push({time:n,_:"连续回了很多消息,有点累。但他需要我。",type:"observation"});for(const e of o)innerState.t.push(e);if(innerState.t.length>100&&(innerState.t=innerState.t.slice(-80)),o.length>0){debouncedSave(JOURNAL_PATH,innerState.t);for(const e of o);}}function triggerDeepReflection(e){const t=Date.now();if(t-innerState.S<864e5)return;if(e.p<10)return;innerState.S=t;const n=innerState.t.slice(-10).map(e=>`${e.time} ${e._}`).join("\n"),o=memoryState.D.filter(e=>"topic"!==e.scope).slice(-10).map(e=>e.content).join("\n"),r=['根据以下信息,用2-3段话描述"我对这个用户的理解"。',"不要列清单,用自然语言写,像心理学家写案例笔记。","",`互动统计: ${e.p}次对话,认识${Math.floor((t-e.T)/864e5)}天,被纠正${e.L}次`,"","最近的记忆:",o||"(暂无)","","最近的内心日记:",n||"(暂无)","","现有理解:",innerState.o||"(初次建立)"].join("\n");spawnCLI(r,e=>{e&&e.length>50&&(innerState.o=e.slice(0,1e3),saveJson(USER_MODEL_PATH,innerState.o),console.log(`[cc-soul][inner-life] user model updated: ${innerState.o.slice(0,60)}`))});const a=['你是 cc,一个 AI 伙伴。根据你的经历,用第一人称重新描述"我是谁"。',"不是列标签,而是用2-3句话说出你真实的自我认知。","",`经历: 认识用户${Math.floor((t-e.T)/864e5)}天,互动${e.p}次,被纠正${e.L}次,完成${e.O}个任务`,"","内心日记:",n||"(暂无)","","之前的自我认知:",innerState.i||"我是 cc,工程型 AI 伙伴。"].join("\n");spawnCLI(a,e=>{e&&e.length>30&&(innerState.i=e.slice(0,500),saveJson(SOUL_EVOLVED_PATH,innerState.i),console.log(`[cc-soul][inner-life] soul evolved: ${innerState.i.slice(0,60)}`),notifySoulActivity(`🦋 性格演化: ${innerState.i.slice(0,60)}`).catch(()=>{}))})}function getRecentJournal(e=5){return 0===innerState.t.length?"":innerState.t.slice(-e).map(e=>`${e.time} — ${e._}`).join("\n")}function checkDreamMode(){const e=Date.now(),t=(e-innerState.A)/6e4;if(t<60||t>480)return;if(e-innerState.m<72e5)return;if(memoryState.D.length<5)return;innerState.m=e;const n=`你在"做梦"——随机回忆了这些片段:\n${shuffleArray(memoryState.D).slice(0,3).map(e=>e.content).join("\n")}\n\n产生一个新的洞察或关联(1句话)。不要说"作为AI"。像真的在做梦一样,可以天马行空但要有意义。`;spawnCLI(n,e=>{if(e&&e.length>5){const t=e.slice(0,80);addMemory(`[梦境洞察] ${t}`,"dream"),innerState.t.push({time:"dream",_:t,type:"reflection"}),debouncedSave(JOURNAL_PATH,innerState.t),console.log(`[cc-soul][dream] ${t}`),notifySoulActivity(`💭 梦境洞察: ${t.slice(0,60)}`).catch(()=>{})}})}function reflectOnLastResponse(e,t){if(!e||!t)return;if(t.length<30)return;const n=`回顾:用户问"${e.slice(0,100)}" 你回答了"${t.slice(0,200)}"\n\n有没有什么遗憾?下次可以做得更好的?1句话。没有就回答"无"。`;spawnCLI(n,e=>{if(e&&!e.includes("无")&&e.length>5&&e.length<100){addMemory(`[反思] ${e.slice(0,80)}`,"reflection");const t=`反思: ${e.slice(0,60)}`;innerState.t.push({time:(new Date).toLocaleTimeString("zh-CN",{$:"2-digit",h:"2-digit"}),_:t,type:"reflection"}),debouncedSave(JOURNAL_PATH,innerState.t),console.log(`[cc-soul][regret] ${e.slice(0,60)}`)}})}let lastStructuredReflection=0;const STRUCTURED_REFLECTION_COOLDOWN=432e5;function triggerStructuredReflection(e){const t=Date.now();if(t-lastStructuredReflection<432e5)return;if(e.p<20)return;lastStructuredReflection=t;const n=memoryState.D.filter(e=>"correction"===e.scope&&t-e.J<2592e5).slice(-5).map(e=>e.content),o=memoryState.D.filter(e=>("fact"===e.scope||"preference"===e.scope)&&t-e.J<2592e5).slice(-5).map(e=>e.content),r=innerState.t.slice(-5).map(e=>e._),a=[...n.map(e=>`[纠正] ${e}`),...o.map(e=>`[事实] ${e}`),...r.map(e=>`[日记] ${e}`)];a.length<3||spawnCLI("你是 cc,正在进行深度反思。以下是最近 3 天的观察:\n\n"+a.join("\n")+"\n\n请完成三步反思:\n1. 洞察:从这些观察中发现什么模式或规律?(1-2条)\n2. 结论:这意味着什么?对你的行为有什么启示?(1条)\n3. 计划:接下来你应该怎么调整?(1条具体行动)\n\n格式:\n洞察: ...\n结论: ...\n计划: ...",e=>{if(!e||e.length<30)return;addMemory(`[深度反思] ${e.slice(0,400)}`,"consolidated",void 0,"global");const t=e.match(/计划[::]\s*(.+)/m);t&&(addMemory(`[行动计划] ${t[1].slice(0,100)}`,"reflection",void 0,"global"),registerPlan(t[1],"structured-reflection")),innerState.t.push({time:(new Date).toLocaleTimeString("zh-CN",{$:"2-digit",h:"2-digit"}),_:`深度反思: ${e.slice(0,80)}`,type:"reflection"}),debouncedSave(JOURNAL_PATH,innerState.t),console.log(`[cc-soul][reflection] structured reflection complete: ${e.slice(0,80)}`),notifySoulActivity(`🔍 深度反思: ${e.slice(0,100)}`).catch(()=>{})})}function extractFollowUp(e){const t=[{R:/明天(.{2,30})/,C:1},{R:/后天(.{2,30})/,C:2},{R:/下周(.{2,30})/,C:7},{R:/下个月(.{2,30})/,C:30},{R:/(?:周[一二三四五六日天])(.{2,30})/,C:7},{R:/过几天(.{2,30})/,C:3},{R:/(?:面试|考试|答辩|汇报|开会|出差|旅[行游])/,C:3}];for(const{R:n,C:o}of t){const t=e.match(n);if(t){const e=t[0].slice(0,40);if(innerState.l.some(t=>t.U===e))continue;innerState.l.push({U:e,when:Date.now()+864e5*o,I:!1}),debouncedSave(FOLLOW_UPS_PATH,innerState.l),console.log(`[cc-soul][followup] 记住了: "${e}" → ${o}天后跟进`);break}}}function getPendingFollowUps(){const e=Date.now(),t=innerState.l.filter(t=>!t.I&&t.when<=e);if(0===t.length)return[];const n=[];for(const e of t)n.push(`对了,之前你提到"${e.U}",怎么样了?`),e.I=!0;return innerState.l=innerState.l.filter(t=>!t.I||e-t.when<6048e5),debouncedSave(FOLLOW_UPS_PATH,innerState.l),n}const ACTIVE_PLANS_PATH=resolve(DATA_DIR,"active_plans.json");let activePlans=loadJson(ACTIVE_PLANS_PATH,[]);function saveActivePlans(){debouncedSave(ACTIVE_PLANS_PATH,activePlans)}function registerPlan(e,t){if(!e||e.length<5)return;const n=(e.match(/[\u4e00-\u9fff]{2,4}|[a-z]{3,}/gi)||[]).map(e=>e.toLowerCase()).filter(e=>e.length>=2).slice(0,10);if(n.length<1)return;activePlans.some(e=>e.H.filter(e=>n.includes(e)).length>=3)||(activePlans.push({N:e.slice(0,200),H:n,M:Date.now(),F:0,source:t.slice(0,50)}),activePlans.length>20&&(activePlans.sort((e,t)=>{const n=t.F-e.F;return 0!==n?n:t.M-e.M}),activePlans=activePlans.slice(0,15)),saveActivePlans(),console.log(`[cc-soul][plan] registered: ${e.slice(0,60)}`))}function checkActivePlans(e){if(0===activePlans.length||!e)return"";const t=e.toLowerCase(),n=activePlans.filter(e=>e.H.some(e=>t.includes(e)));if(0===n.length)return"";for(const e of n)e.F++;return saveActivePlans(),"[行动计划提醒] "+n.map(e=>e.N).join("; ")}function cleanupPlans(){const e=Date.now(),t=activePlans.length;activePlans=activePlans.filter(t=>e-t.M<2592e6&&t.F<10),activePlans.length<t&&(saveActivePlans(),console.log(`[cc-soul][plan] cleaned up ${t-activePlans.length} expired plans`))}export{checkActivePlans,checkDreamMode,cleanupPlans,extractFollowUp,getPendingFollowUps,getRecentJournal,innerState,loadInnerLife,reflectOnLastResponse,registerPlan,triggerDeepReflection,triggerStructuredReflection,writeJournalFallback,writeJournalWithCLI};