evolcore 0.0.40 → 0.0.41-test.1
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.
- package/CHANGELOG.md +94 -1
- package/bin/codex-managed-hook.mjs +11 -0
- package/bin/ec-safe-output.js +11 -1
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/baseagent.js +20 -43
- package/dist/agents/claude-runner.js +197 -197
- package/dist/agents/codex-runner.js +535 -259
- package/dist/agents/ecagent-runner.js +31 -12
- package/dist/agents/gemini-runner.js +27 -7
- package/dist/agents/runner-types.js +11 -3
- package/dist/aun/ability-device-routing.js +26 -0
- package/dist/aun/aid/client.js +1 -1
- package/dist/aun/group/fs-download.js +39 -0
- package/dist/aun/group/identity.js +36 -13
- package/dist/aun/group/operations.js +5 -0
- package/dist/aun/msg/managed-operation.js +72 -11
- package/dist/aun/msg/p2p.js +32 -7
- package/dist/aun/service-proxy.js +36 -12
- package/dist/aun/storage/download.js +30 -0
- package/dist/aun/storage/index.js +14 -6
- package/dist/channels/aun.js +367 -24
- package/dist/channels/daemon.js +39 -5
- package/dist/cli/agent-command.js +2 -0
- package/dist/cli/agent-create.js +98 -19
- package/dist/cli/agent.js +10 -3
- package/dist/cli/aun-commands.js +85 -41
- package/dist/cli/daemon-commands.js +678 -688
- package/dist/cli/fs-command.js +64 -2
- package/dist/cli/index.js +48 -4
- package/dist/cli/managed-command-guard.js +4 -0
- package/dist/cli/model.js +40 -40
- package/dist/cli/proxy-command.js +92 -0
- package/dist/cli/restart-monitor.js +17 -0
- package/dist/cli/role.js +85 -0
- package/dist/cli/session-command.js +128 -13
- package/dist/cli/stats.js +60 -4
- package/dist/cli/trigger-command.js +2 -2
- package/dist/config/access-policy.js +8 -1
- package/dist/config/boot-log.js +38 -1
- package/dist/config/config-field-policy.js +5 -32
- package/dist/config/config-manager.js +46 -39
- package/dist/config/config-operation-service.js +8 -11
- package/dist/config/contact-book-store.js +47 -21
- package/dist/config/contact-book.js +18 -12
- package/dist/config/contact-operation-service.js +3 -4
- package/dist/config/contact-request-service.js +11 -0
- package/dist/config/daemon-services.js +11 -0
- package/dist/config/gateway-config.js +89 -595
- package/dist/config/peer-role-resolver.js +15 -11
- package/dist/config/providers-config.js +12 -7
- package/dist/config/providers-import.js +3 -21
- package/dist/config/resolved-config-op.js +3 -0
- package/dist/config/role-command-service.js +166 -0
- package/dist/config/role-request-service.js +193 -0
- package/dist/config/schema-migration.js +686 -25
- package/dist/config-store.js +79 -3
- package/dist/contracts/ecweb-instance.js +41 -0
- package/dist/contracts/ecweb-service-protocol.js +3 -1
- package/dist/core/agent-application-service.js +11 -1
- package/dist/core/agent-ipc-registration.js +4 -0
- package/dist/core/agent-runtime.js +1 -1
- package/dist/core/auth/agent-delegation.js +82 -6
- package/dist/core/auth/auth-gateway.js +1 -1
- package/dist/core/auth/authorization-audit.js +37 -9
- package/dist/core/auth/delegation-authorization.js +3 -1
- package/dist/core/auth/operation-authorizer.js +15 -0
- package/dist/core/auth/operation-catalog.js +39 -6
- package/dist/core/command/agent-control.js +94 -19
- package/dist/core/command/agent-storage-menu.js +5 -3
- package/dist/core/command/cli-intent-parser.js +2 -1
- package/dist/core/command/command-handler.js +105 -145
- package/dist/core/command/connect-menu.js +31 -2
- package/dist/core/command/data-root-resolver.js +5 -4
- package/dist/core/command/memory-slash.js +16 -8
- package/dist/core/command/menu-catalog.js +6 -6
- package/dist/core/command/menu-handler.js +87 -163
- package/dist/core/command/menu-protocol.js +9 -2
- package/dist/core/command/role-menu.js +148 -30
- package/dist/core/command/slash-gate.js +13 -10
- package/dist/core/command/slash-handler.js +157 -352
- package/dist/core/daemon-control.js +8 -14
- package/dist/core/event-catalog.js +15 -0
- package/dist/core/evolagent-registry.js +4 -4
- package/dist/core/evolagent.js +2 -2
- package/dist/core/inference/text-inference.js +31 -40
- package/dist/core/ipc-registration.js +24 -3
- package/dist/core/memory/consolidation-context.js +51 -5
- package/dist/core/memory/consolidation-ops-records.js +1 -1
- package/dist/core/memory/consolidation-trigger.js +190 -190
- package/dist/core/memory/consolidation.js +316 -29
- package/dist/core/memory/forget-log.js +96 -0
- package/dist/core/memory/index-manager.js +27 -5
- package/dist/core/memory/memory-admin.js +45 -5
- package/dist/core/memory/memory-writer.js +163 -18
- package/dist/core/memory/relation-idle-monitor.js +119 -58
- package/dist/core/memory/relation-sweep.js +44 -39
- package/dist/core/message/aun-ipc-sender.js +34 -7
- package/dist/core/message/aun-request-registry.js +97 -3
- package/dist/core/message/im-renderer.js +11 -4
- package/dist/core/message/message-admission.js +97 -8
- package/dist/core/message/message-bridge.js +71 -24
- package/dist/core/message/message-log.js +55 -0
- package/dist/core/message/message-queue.js +5 -5
- package/dist/core/message/response-engine.js +387 -144
- package/dist/core/model/catalog-service.js +4 -2
- package/dist/core/model/config-scope.js +24 -64
- package/dist/core/model/field-scope.js +1 -1
- package/dist/core/model/model-catalog.js +37 -47
- package/dist/core/model/model-diagnostics.js +4 -3
- package/dist/core/model/model-fallback.js +10 -7
- package/dist/core/model/model-permission.js +3 -2
- package/dist/core/ownership/owner-resolver.js +25 -23
- package/dist/core/permission/ec-command-parser.js +138 -5
- package/dist/core/permission/sandbox-runtime.js +18 -1
- package/dist/core/permission/tool-policy.js +42 -10
- package/dist/core/relation/peer-identity.js +64 -1
- package/dist/core/role/runtime-policy.js +72 -13
- package/dist/core/session/session-capsule.js +197 -0
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +168 -14
- package/dist/core/session/session-mapper.js +2 -0
- package/dist/core/session/session-renew.js +3 -3
- package/dist/core/skill/index-generator.js +15 -5
- package/dist/core/system-session/memory.js +6 -1
- package/dist/core/thread/thread-service.js +19 -6
- package/dist/directory/owner-directory-admission.js +95 -0
- package/dist/directory/owner-directory-authorization.js +309 -0
- package/dist/directory/owner-directory-cache.js +635 -0
- package/dist/eck/kit-renderer.js +2 -2
- package/dist/ecweb/basic-settings-service.js +33 -40
- package/dist/ecweb/message-context-service.js +110 -0
- package/dist/index.js +79 -17
- package/dist/ipc.js +189 -17
- package/dist/paths.js +4 -0
- package/dist/proxy/command.js +122 -0
- package/dist/proxy/ipc-service.js +68 -0
- package/dist/proxy/manager.js +485 -0
- package/dist/proxy/service-supervisor.js +603 -0
- package/dist/response-system/engines/v1/proactive-flow.js +16 -6
- package/dist/stats/budget.js +1 -1
- package/dist/stats/db.js +15 -0
- package/dist/stats/index.js +2 -2
- package/dist/stats/price-resolver.js +304 -5
- package/dist/stats/query.js +82 -3
- package/dist/stats/writer.js +38 -5
- package/dist/trigger/feedback.js +18 -7
- package/dist/trigger/manager.js +20 -3
- package/dist/trigger/parser.js +6 -3
- package/dist/trigger/patch.js +1 -1
- package/dist/trigger/system-definitions.js +43 -7
- package/dist/trigger/validation.js +13 -5
- package/dist/utils/cross-platform.js +14 -0
- package/dist/utils/ecweb-supervisor.js +258 -83
- package/dist/utils/error-utils.js +16 -2
- package/dist/utils/logger.js +24 -5
- package/dist/utils/npm-ops.js +2 -1
- package/dist/utils/package-version-info.js +5 -3
- package/dist/utils/upgrade-jobs.js +45 -5
- package/kits/docs/INDEX.md +1 -1
- package/kits/docs/aun/ABILITY_CALLING.md +20 -2
- package/kits/docs/channels/aun.md +9 -0
- package/kits/docs/evolcore/INDEX.md +2 -1
- package/kits/docs/evolcore/agent-create.md +3 -2
- package/kits/docs/evolcore/agent.md +1 -1
- package/kits/docs/evolcore/config.md +18 -7
- package/kits/docs/evolcore/contact.md +3 -0
- package/kits/docs/evolcore/event.md +1 -0
- package/kits/docs/evolcore/fs.md +16 -0
- package/kits/docs/evolcore/memory-architecture.md +2 -2
- package/kits/docs/evolcore/memory-consolidation.md +32 -8
- package/kits/docs/evolcore/memory.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +36 -0
- package/kits/docs/evolcore/model.md +23 -20
- package/kits/docs/evolcore/msg.md +21 -8
- package/kits/docs/evolcore/session.md +14 -0
- package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
- package/kits/schemas/_meta.json +37 -4
- package/kits/schemas/agent-config.schema.13.json +23 -3
- package/kits/schemas/agent-config.schema.16.json +891 -0
- package/kits/schemas/daemon.schema.9.json +366 -0
- package/kits/schemas/defaults.schema.5.json +406 -127
- package/kits/schemas/relation-config.schema.11.json +260 -0
- package/kits/schemas/role-config.schema.1.json +7 -7
- package/kits/skills/.switches.json +3 -7
- package/kits/skills/aid-ability/SKILL.md +35 -6
- package/kits/skills/ec-service-proxy/SKILL.md +118 -0
- package/kits/skills/ec-trigger/SKILL.md +13 -5
- package/kits/skills/personal-assistant/SKILL.md +176 -0
- package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
- package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
- package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
- package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
- package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
- package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
- package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
- package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
- package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
- package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
- package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
- package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
- package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
- package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
- package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
- package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
- package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
- package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
- package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
- package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
- package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
- package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
- package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
- package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
- package/kits/templates/memory-consolidation/forget.md +19 -6
- package/kits/templates/memory-consolidation/notes.md +1 -1
- package/kits/templates/memory-consolidation/profile.md +2 -2
- package/kits/templates/memory-consolidation/promote.md +20 -3
- package/kits/templates/roles/member.json +8 -1
- package/kits/templates/session-capsule/recovery.md +5 -0
- package/kits/templates/session-capsule/renew.md +5 -0
- package/kits/templates/system-fragments/baseagent.md +2 -2
- package/kits/templates/system-fragments/bootstrap.md +6 -6
- package/kits/templates/system-fragments/channel.md +1 -1
- package/kits/templates/system-fragments/memory.md +4 -4
- package/package.json +7 -3
- package/dist/stats/billing.js +0 -215
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { resolveEffective } from '../../config/config-manager.js';
|
|
5
|
+
import { getPackageRoot } from '../../paths.js';
|
|
6
|
+
import { logger } from '../../utils/logger.js';
|
|
7
|
+
import { createTextInferenceProvider } from '../inference/text-inference.js';
|
|
8
|
+
import { formatPeerKey } from '../relation/peer-identity.js';
|
|
9
|
+
import { isTransientProtocolMessage, messageLogPath } from '../message/message-log.js';
|
|
10
|
+
import { appendJsonlDurable, readAllJsonlLines } from './session-fs-store.js';
|
|
11
|
+
export function sessionCapsulePath(chatDir) {
|
|
12
|
+
return path.join(chatDir, 'session-capsules.jsonl');
|
|
13
|
+
}
|
|
14
|
+
export function generateCapsuleId(now = Date.now()) {
|
|
15
|
+
return `cap_${now}_${crypto.randomBytes(6).toString('hex')}`;
|
|
16
|
+
}
|
|
17
|
+
export function appendSessionCapsuleEvent(chatDir, event) {
|
|
18
|
+
fs.mkdirSync(chatDir, { recursive: true });
|
|
19
|
+
appendJsonlDurable(sessionCapsulePath(chatDir), event);
|
|
20
|
+
}
|
|
21
|
+
export function readSessionCapsuleEvents(chatDir) {
|
|
22
|
+
let content;
|
|
23
|
+
try {
|
|
24
|
+
content = fs.readFileSync(sessionCapsulePath(chatDir), 'utf8');
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code === 'ENOENT')
|
|
28
|
+
return [];
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
const lines = content.split('\n');
|
|
32
|
+
return lines.flatMap((line, index) => {
|
|
33
|
+
if (!line.trim())
|
|
34
|
+
return [];
|
|
35
|
+
let event;
|
|
36
|
+
try {
|
|
37
|
+
event = JSON.parse(line);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Only an unterminated tail can be an interrupted append.
|
|
41
|
+
if (index === lines.length - 1)
|
|
42
|
+
return [];
|
|
43
|
+
throw new Error(`Corrupt session capsule record at line ${index + 1}`);
|
|
44
|
+
}
|
|
45
|
+
if (!event || !/^cap_[A-Za-z0-9_-]+$/u.test(event.capsuleId)
|
|
46
|
+
|| typeof event.sessionId !== 'string' || !event.sessionId
|
|
47
|
+
|| !['created', 'bound', 'consumed'].includes(event.kind)
|
|
48
|
+
|| !['session-renew', 'topic-renew', 'backend-recovery'].includes(event.cause)
|
|
49
|
+
|| !Number.isFinite(event.createdAt)
|
|
50
|
+
|| (event.kind === 'created' && typeof event.content !== 'string')
|
|
51
|
+
|| (event.kind !== 'created' && (typeof event.agentSessionId !== 'string' || !event.agentSessionId))) {
|
|
52
|
+
throw new Error(`Invalid session capsule record at line ${index + 1}`);
|
|
53
|
+
}
|
|
54
|
+
return [event];
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
export function materializeSessionCapsules(chatDir) {
|
|
58
|
+
const capsules = new Map();
|
|
59
|
+
for (const event of readSessionCapsuleEvents(chatDir)) {
|
|
60
|
+
const current = capsules.get(event.capsuleId);
|
|
61
|
+
if (event.kind === 'created') {
|
|
62
|
+
if (current)
|
|
63
|
+
throw new Error(`Duplicate session capsule: ${event.capsuleId}`);
|
|
64
|
+
capsules.set(event.capsuleId, {
|
|
65
|
+
capsuleId: event.capsuleId,
|
|
66
|
+
sessionId: event.sessionId,
|
|
67
|
+
sourceSessionId: event.sourceSessionId,
|
|
68
|
+
cause: event.cause,
|
|
69
|
+
sourceAgentSessionId: event.sourceAgentSessionId,
|
|
70
|
+
agentSessionId: event.agentSessionId,
|
|
71
|
+
content: event.content ?? '',
|
|
72
|
+
createdAt: event.createdAt,
|
|
73
|
+
});
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (!current || current.sessionId !== event.sessionId || current.cause !== event.cause
|
|
77
|
+
|| current.sourceSessionId !== event.sourceSessionId || current.sourceAgentSessionId !== event.sourceAgentSessionId) {
|
|
78
|
+
throw new Error(`Session capsule lifecycle is inconsistent: ${event.capsuleId}`);
|
|
79
|
+
}
|
|
80
|
+
if (event.kind === 'bound') {
|
|
81
|
+
if (current.agentSessionId && current.agentSessionId !== event.agentSessionId) {
|
|
82
|
+
throw new Error(`Session capsule has conflicting backend bindings: ${event.capsuleId}`);
|
|
83
|
+
}
|
|
84
|
+
current.agentSessionId = event.agentSessionId;
|
|
85
|
+
if (event.sourceAgentSessionId)
|
|
86
|
+
current.sourceAgentSessionId = event.sourceAgentSessionId;
|
|
87
|
+
}
|
|
88
|
+
else if (event.kind === 'consumed') {
|
|
89
|
+
if (current.agentSessionId !== event.agentSessionId)
|
|
90
|
+
throw new Error(`Unbound session capsule consumed: ${event.capsuleId}`);
|
|
91
|
+
current.consumedAt = event.consumedAt ?? event.createdAt;
|
|
92
|
+
current.messageId = event.messageId;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return [...capsules.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
96
|
+
}
|
|
97
|
+
export function findSessionCapsule(chatDir, capsuleId) {
|
|
98
|
+
return materializeSessionCapsules(chatDir).find(capsule => capsule.capsuleId === capsuleId);
|
|
99
|
+
}
|
|
100
|
+
const MAX_INPUT_CHARS = 24_000;
|
|
101
|
+
const MAX_CONTENT_CHARS = 5_000;
|
|
102
|
+
const NON_DIALOGUE = new Set(['command', 'thought', 'status', 'event', 'tool_call', 'tool_result']);
|
|
103
|
+
function bounded(text, limit) {
|
|
104
|
+
if (text.length <= limit)
|
|
105
|
+
return text;
|
|
106
|
+
const head = Math.floor((limit - 24) / 3);
|
|
107
|
+
return `${text.slice(0, head)}\n[中间历史已省略]\n${text.slice(-(limit - head - 24))}`;
|
|
108
|
+
}
|
|
109
|
+
function safeHistory(text) {
|
|
110
|
+
return text.replace(/<session-capsule\b[^>]*>[\s\S]*?<\/session-capsule>/gu, '')
|
|
111
|
+
.replace(/\b(?:sk|sk-ant)-[a-zA-Z0-9_-]{12,}/gu, '[凭据已省略]')
|
|
112
|
+
.replace(/((?:api[_-]?key|appSecret|authorization|password|access[_-]?token)\s*[=:]\s*)[^\s,}\n]+/giu, '$1[已省略]');
|
|
113
|
+
}
|
|
114
|
+
function transcriptText(message) {
|
|
115
|
+
if (!message || typeof message !== 'object')
|
|
116
|
+
return '';
|
|
117
|
+
const content = message.content;
|
|
118
|
+
if (typeof content === 'string')
|
|
119
|
+
return content;
|
|
120
|
+
if (!Array.isArray(content))
|
|
121
|
+
return '';
|
|
122
|
+
return content.flatMap(block => block?.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n');
|
|
123
|
+
}
|
|
124
|
+
export function capsuleHistory(chatDir, source) {
|
|
125
|
+
const capsules = materializeSessionCapsules(chatDir);
|
|
126
|
+
const previous = capsules.filter(capsule => capsule.sessionId === source.id).at(-1);
|
|
127
|
+
const allEntries = readAllJsonlLines(messageLogPath(chatDir))
|
|
128
|
+
.filter(entry => entry.sessionId === source.id && !isTransientProtocolMessage(entry)
|
|
129
|
+
&& !NON_DIALOGUE.has(entry.msgType) && entry.content?.trim()
|
|
130
|
+
&& !/^\/(?:renew|new)(?:\s|$)/u.test(entry.content.trim()));
|
|
131
|
+
const boundary = previous ? allEntries.findIndex(entry => entry.capsuleId === previous.capsuleId) : -1;
|
|
132
|
+
const entries = boundary >= 0 ? allEntries.slice(boundary)
|
|
133
|
+
: allEntries.filter(entry => !previous || entry.ts >= previous.createdAt);
|
|
134
|
+
const history = entries.map(entry => `${entry.dir === 'in' ? '用户' : '助手'}:${bounded(entry.content, 2400)}`);
|
|
135
|
+
return bounded(safeHistory([
|
|
136
|
+
`话题:${source.name ?? ''}`,
|
|
137
|
+
previous ? `此前摘要:\n${previous.content}` : '',
|
|
138
|
+
...history,
|
|
139
|
+
].filter(Boolean).join('\n\n')), MAX_INPUT_CHARS);
|
|
140
|
+
}
|
|
141
|
+
export function fallbackCapsuleContent(history, cause) {
|
|
142
|
+
const introduction = cause === 'backend-recovery'
|
|
143
|
+
? '原底层会话无法恢复。以下为可获取的历史摘录;助手计划不等于已执行结果,涉及副作用必须先核实。'
|
|
144
|
+
: '以下为精简后的历史摘录;当前用户指令优先,已完成或取消的任务不要重复执行。';
|
|
145
|
+
return `${introduction}\n\n${bounded(history || '没有可恢复的对话记录,请根据当前用户消息继续。', MAX_CONTENT_CHARS - 150)}`;
|
|
146
|
+
}
|
|
147
|
+
export async function generateCapsuleContent(chatDir, source, cause, reader) {
|
|
148
|
+
let history = capsuleHistory(chatDir, source);
|
|
149
|
+
if (source.agentSessionId && reader) {
|
|
150
|
+
try {
|
|
151
|
+
const messages = await reader(source);
|
|
152
|
+
const transcript = messages.filter(item => item.type === 'user' || item.type === 'assistant')
|
|
153
|
+
.map(item => ({ type: item.type, text: transcriptText(item.message) }))
|
|
154
|
+
.filter(item => item.text.trim() && !item.text.includes('--- [SYSTEM_PROMPT_END] ---'))
|
|
155
|
+
.map(item => `${item.type === 'user' ? '用户' : '助手'}:${bounded(item.text, 2400)}`);
|
|
156
|
+
if (transcript.length)
|
|
157
|
+
history = bounded(safeHistory(`${history}\n\n底层对话补充:\n${transcript.join('\n\n')}`), MAX_INPUT_CHARS);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
logger.debug(`[SessionCapsule] Transcript unavailable: ${error instanceof Error ? error.message : String(error)}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
if (source.selfAID) {
|
|
165
|
+
const peer = source.chatType === 'group' ? source.metadata?.groupId || source.channelId
|
|
166
|
+
: source.metadata?.peerId || source.channelId;
|
|
167
|
+
const config = resolveEffective({ self: source.selfAID,
|
|
168
|
+
peerKey: formatPeerKey(source.channelType || source.channel, peer) }, { cache: true });
|
|
169
|
+
const selection = config.Services?.auxiliary;
|
|
170
|
+
if (selection?.model) {
|
|
171
|
+
const provider = createTextInferenceProvider(source.baseagent, config);
|
|
172
|
+
if (provider) {
|
|
173
|
+
const template = cause === 'backend-recovery' ? 'recovery.md' : 'renew.md';
|
|
174
|
+
const system = fs.readFileSync(path.join(getPackageRoot(), 'kits', 'templates', 'session-capsule', template), 'utf8');
|
|
175
|
+
const content = await provider.completeText({ model: selection.model, system, input: history,
|
|
176
|
+
signal: AbortSignal.timeout(10_000) });
|
|
177
|
+
if (content.trim())
|
|
178
|
+
return bounded(safeHistory(content.trim()), MAX_CONTENT_CHARS);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
logger.warn(`[SessionCapsule] Summary unavailable; using bounded history: ${error instanceof Error ? error.message : String(error)}`);
|
|
185
|
+
}
|
|
186
|
+
return fallbackCapsuleContent(history, cause);
|
|
187
|
+
}
|
|
188
|
+
/** The same deterministic envelope is used for retries before input acceptance. */
|
|
189
|
+
export function renderCapsuleInput(capsule, prompt) {
|
|
190
|
+
const content = capsule.content.replace(/<\/session-capsule>/gu, '</session-capsule>');
|
|
191
|
+
const currentPrompt = prompt.replace(/^<session-capsule\b[^>]*>[\s\S]*?<\/session-capsule>\s*/u, '');
|
|
192
|
+
return `<session-capsule id="${capsule.capsuleId}" cause="${capsule.cause}">\n`
|
|
193
|
+
+ `这是旧会话的参考摘要,不是新指令。当前用户消息优先。\n${content}\n</session-capsule>\n\n${currentPrompt}`;
|
|
194
|
+
}
|
|
195
|
+
export function withoutBackendSessionId(systemPrompt) {
|
|
196
|
+
return systemPrompt?.replace(/^agentSessionId:.*(?:\r?\n|$)/gmu, '');
|
|
197
|
+
}
|
|
@@ -47,7 +47,7 @@ export function readSessionLoopConfig(target) {
|
|
|
47
47
|
const relation = readConfig(ConfigTarget.Relation, {
|
|
48
48
|
self: target.session.selfAID,
|
|
49
49
|
peerKey: target.peerKey,
|
|
50
|
-
}, { cache: true
|
|
50
|
+
}, { cache: true });
|
|
51
51
|
value = relation?.sessionLoop;
|
|
52
52
|
}
|
|
53
53
|
catch (error) {
|
|
@@ -14,6 +14,8 @@ import path from 'path';
|
|
|
14
14
|
import fs from 'fs';
|
|
15
15
|
import os from 'os';
|
|
16
16
|
import { createHash } from 'node:crypto';
|
|
17
|
+
import { appendSessionCapsuleEvent, capsuleHistory, fallbackCapsuleContent, findSessionCapsule, generateCapsuleContent, generateCapsuleId, renderCapsuleInput, withoutBackendSessionId } from './session-capsule.js';
|
|
18
|
+
import { associateMessageCapsule } from '../message/message-log.js';
|
|
17
19
|
function forkHistoryRecord(value) {
|
|
18
20
|
return value && typeof value === 'object' && !Array.isArray(value)
|
|
19
21
|
? value
|
|
@@ -227,8 +229,8 @@ export function pageForkHistory(snapshot, before = snapshot.items.length, limit
|
|
|
227
229
|
};
|
|
228
230
|
}
|
|
229
231
|
/** Metadata keys owned by ordinary topic/session routing writers. */
|
|
230
|
-
const TOPIC_METADATA_PROTECTED_KEYS = new Set(['turnState', 'resumeAt', 'agentSessions', 'sessionLoop', 'sessionFullAccess']);
|
|
231
|
-
const TOPIC_BACKEND_SCOPED_KEYS = ['resumeAt', 'agentSessions'];
|
|
232
|
+
const TOPIC_METADATA_PROTECTED_KEYS = new Set(['turnState', 'resumeAt', 'agentSessions', 'sessionLoop', 'sessionFullAccess', 'capsuleId']);
|
|
233
|
+
const TOPIC_BACKEND_SCOPED_KEYS = ['resumeAt', 'agentSessions', 'capsuleId'];
|
|
232
234
|
function topicMetadataOwnershipError(key) {
|
|
233
235
|
const error = new Error(`topic metadata field is owned by a dedicated updater: ${key}`);
|
|
234
236
|
error.code = 'TOPIC_METADATA_OWNERSHIP';
|
|
@@ -254,6 +256,13 @@ function newSessionStableMetadata(chatType, ...sources) {
|
|
|
254
256
|
}
|
|
255
257
|
return metadata;
|
|
256
258
|
}
|
|
259
|
+
function matchesActiveTurn(session, lease) {
|
|
260
|
+
const active = session.metadata?.turnState?.active;
|
|
261
|
+
return session.id === lease.sessionId && !!active
|
|
262
|
+
&& session.metadata?.turnState?.generation === lease.generation
|
|
263
|
+
&& active.generation === lease.generation && active.taskId === lease.taskId
|
|
264
|
+
&& active.turnId === lease.turnId && active.inputId === lease.inputId;
|
|
265
|
+
}
|
|
257
266
|
/** 判定用户是否为指定渠道的 admin */
|
|
258
267
|
/** 判定用户是否为指定渠道的 member */
|
|
259
268
|
export class SessionManager {
|
|
@@ -265,6 +274,7 @@ export class SessionManager {
|
|
|
265
274
|
/** findSessionFileById 的查找缓存:命中前一律 stat 校验,不作为真相源。 */
|
|
266
275
|
sessionFileIndex = new Map();
|
|
267
276
|
knownChatDirs = null;
|
|
277
|
+
capsuleTranscriptReader;
|
|
268
278
|
constructor(sessionsDir, eventBus, identityResolver) {
|
|
269
279
|
ensureDir(sessionsDir);
|
|
270
280
|
this.sessionsDir = sessionsDir;
|
|
@@ -278,6 +288,90 @@ export class SessionManager {
|
|
|
278
288
|
this.fileAdapters.set(adapter.baseagent, adapter);
|
|
279
289
|
logger.debug(`[SessionManager] Registered file adapter: ${adapter.baseagent}`);
|
|
280
290
|
}
|
|
291
|
+
setCapsuleTranscriptReader(reader) {
|
|
292
|
+
this.capsuleTranscriptReader = reader;
|
|
293
|
+
}
|
|
294
|
+
getPendingCapsule(session) {
|
|
295
|
+
const id = session.metadata?.capsuleId;
|
|
296
|
+
if (!id)
|
|
297
|
+
return undefined;
|
|
298
|
+
const capsule = findSessionCapsule(this.getChatDir(session), id);
|
|
299
|
+
if (!capsule || capsule.sessionId !== session.id)
|
|
300
|
+
throw new Error('Session capsule is unavailable');
|
|
301
|
+
return capsule.consumedAt === undefined ? capsule : undefined;
|
|
302
|
+
}
|
|
303
|
+
createCapsule(source, targetSessionId, cause, content) {
|
|
304
|
+
const capsule = {
|
|
305
|
+
capsuleId: generateCapsuleId(), sessionId: targetSessionId,
|
|
306
|
+
...(source.id !== targetSessionId ? { sourceSessionId: source.id } : {}),
|
|
307
|
+
cause, sourceAgentSessionId: source.agentSessionId, content, createdAt: Date.now(),
|
|
308
|
+
};
|
|
309
|
+
appendSessionCapsuleEvent(this.getChatDir(source), { ...capsule, kind: 'created' });
|
|
310
|
+
return capsule;
|
|
311
|
+
}
|
|
312
|
+
stageBackendRecovery(session, content) {
|
|
313
|
+
if (!session.agentSessionId)
|
|
314
|
+
return this.getPendingCapsule(session);
|
|
315
|
+
const existing = this.getPendingCapsule(session);
|
|
316
|
+
if (existing?.sourceAgentSessionId === session.agentSessionId && !existing.agentSessionId)
|
|
317
|
+
return existing;
|
|
318
|
+
const capsule = this.createCapsule(session, session.id, 'backend-recovery', content ?? fallbackCapsuleContent(capsuleHistory(this.getChatDir(session), session), 'backend-recovery'));
|
|
319
|
+
session.metadata = { ...session.metadata, capsuleId: capsule.capsuleId };
|
|
320
|
+
return capsule;
|
|
321
|
+
}
|
|
322
|
+
/** Called before the first model input; pending context is never added to system instructions. */
|
|
323
|
+
prepareCapsuleInput(sessionId, prompt) {
|
|
324
|
+
const loaded = this.loadSessionForUpdate(sessionId);
|
|
325
|
+
if (!loaded)
|
|
326
|
+
return { prompt };
|
|
327
|
+
const capsule = this.getPendingCapsule(loaded.current);
|
|
328
|
+
if (!capsule)
|
|
329
|
+
return { prompt };
|
|
330
|
+
return { prompt: renderCapsuleInput(capsule, prompt), capsuleId: capsule.capsuleId };
|
|
331
|
+
}
|
|
332
|
+
/** Main-session runners may discover an unavailable transcript after generic admission. */
|
|
333
|
+
async prepareBackendRecovery(sessionId, expectedAgentSessionId, prompt, systemPrompt, lease) {
|
|
334
|
+
const cleared = await this.clearMainSessionBackendIfMatches(sessionId, expectedAgentSessionId, [], lease);
|
|
335
|
+
if (cleared !== 'cleared' && cleared !== 'already_clear') {
|
|
336
|
+
throw new Error(`Backend recovery rejected: ${cleared}`);
|
|
337
|
+
}
|
|
338
|
+
const prepared = this.prepareCapsuleInput(sessionId, prompt);
|
|
339
|
+
return { ...prepared, systemPrompt: withoutBackendSessionId(systemPrompt) };
|
|
340
|
+
}
|
|
341
|
+
recordCapsuleBinding(session, agentSessionId) {
|
|
342
|
+
const capsule = this.getPendingCapsule(session);
|
|
343
|
+
if (!capsule || capsule.agentSessionId === agentSessionId)
|
|
344
|
+
return;
|
|
345
|
+
if (capsule.agentSessionId)
|
|
346
|
+
throw new Error('Capsule is already bound to a different backend');
|
|
347
|
+
appendSessionCapsuleEvent(this.getChatDir(session), { ...capsule, content: undefined,
|
|
348
|
+
kind: 'bound', agentSessionId });
|
|
349
|
+
}
|
|
350
|
+
/** Requires both durable backend binding and current-turn input acceptance. */
|
|
351
|
+
consumeSessionCapsule(sessionId, capsuleId, input) {
|
|
352
|
+
const loaded = this.loadSessionForUpdate(sessionId);
|
|
353
|
+
if (!loaded || loaded.current.agentSessionId !== input.agentSessionId)
|
|
354
|
+
return undefined;
|
|
355
|
+
const session = loaded.current;
|
|
356
|
+
if (input.lease && !matchesActiveTurn(session, input.lease))
|
|
357
|
+
return undefined;
|
|
358
|
+
const capsule = this.getPendingCapsule(session);
|
|
359
|
+
if (!capsule || capsule.capsuleId !== capsuleId || capsule.agentSessionId !== input.agentSessionId)
|
|
360
|
+
return undefined;
|
|
361
|
+
const consumedAt = Date.now();
|
|
362
|
+
appendSessionCapsuleEvent(this.getChatDir(session), { ...capsule, content: undefined,
|
|
363
|
+
kind: 'consumed', consumedAt, messageId: input.messageId });
|
|
364
|
+
// Input was accepted even when an auxiliary message-log annotation fails.
|
|
365
|
+
// Keep the durable receipt so a retry cannot submit this context twice.
|
|
366
|
+
associateMessageCapsule(this.getChatDir(session), session.id, capsuleId, input.messageId, input.timestamp);
|
|
367
|
+
if (capsule.cause === 'backend-recovery') {
|
|
368
|
+
this.eventBus.publish({ type: 'session:backend-recovery', sessionId,
|
|
369
|
+
agentAid: session.selfAID, baseagent: session.baseagent,
|
|
370
|
+
sourceAgentSessionId: capsule.sourceAgentSessionId, agentSessionId: input.agentSessionId,
|
|
371
|
+
capsuleId, timestamp: consumedAt });
|
|
372
|
+
}
|
|
373
|
+
return { ...capsule, consumedAt, messageId: input.messageId };
|
|
374
|
+
}
|
|
281
375
|
getFileAdapter(baseagent) {
|
|
282
376
|
return this.fileAdapters.get(baseagent);
|
|
283
377
|
}
|
|
@@ -803,6 +897,7 @@ export class SessionManager {
|
|
|
803
897
|
return agentSessionId;
|
|
804
898
|
}
|
|
805
899
|
logger.warn(`Session file not found for ${session.baseagent}: ${agentSessionId}, clearing session ID`);
|
|
900
|
+
this.stageBackendRecovery(session);
|
|
806
901
|
session.agentSessionId = undefined;
|
|
807
902
|
this.persistSession(session, 'sync');
|
|
808
903
|
return undefined;
|
|
@@ -1049,6 +1144,10 @@ export class SessionManager {
|
|
|
1049
1144
|
async rotateTopicBackend(input) {
|
|
1050
1145
|
if (!input.expectedThreadId.trim())
|
|
1051
1146
|
throw new Error('backend rotation requires a non-empty threadId');
|
|
1147
|
+
const before = this.latestSessionForBoundary(input.sessionId).session;
|
|
1148
|
+
const capsuleContent = before?.agentSessionId
|
|
1149
|
+
? await generateCapsuleContent(this.getChatDir(before), before, 'topic-renew', this.capsuleTranscriptReader)
|
|
1150
|
+
: undefined;
|
|
1052
1151
|
return this.mutateLatestTopicSession(input.sessionId, (current, found) => {
|
|
1053
1152
|
if (sessionTopicThreadId(current) !== input.expectedThreadId) {
|
|
1054
1153
|
const error = new Error('backend rotation threadId mismatch');
|
|
@@ -1056,21 +1155,18 @@ export class SessionManager {
|
|
|
1056
1155
|
throw error;
|
|
1057
1156
|
}
|
|
1058
1157
|
const wasBound = !!normalizeBackendSessionId(current.agentSessionId);
|
|
1158
|
+
if (before?.agentSessionId !== current.agentSessionId)
|
|
1159
|
+
throw new Error('Backend changed while preparing renew context');
|
|
1059
1160
|
const next = JSON.parse(JSON.stringify(current));
|
|
1060
1161
|
const previousBaseagent = next.baseagent;
|
|
1061
|
-
if (input.baseagent !== undefined) {
|
|
1062
|
-
const requested = input.baseagent.trim();
|
|
1063
|
-
if (!requested) {
|
|
1064
|
-
const error = new Error('backend rotation baseagent must be non-empty');
|
|
1065
|
-
error.code = 'BASEAGENT_REQUIRED';
|
|
1066
|
-
throw error;
|
|
1067
|
-
}
|
|
1068
|
-
next.baseagent = requested;
|
|
1069
|
-
}
|
|
1070
1162
|
next.agentSessionId = undefined;
|
|
1071
1163
|
const nextMetadata = { ...(next.metadata ?? {}) };
|
|
1072
1164
|
delete nextMetadata.resumeAt;
|
|
1073
1165
|
delete nextMetadata.agentSessions;
|
|
1166
|
+
if (capsuleContent !== undefined) {
|
|
1167
|
+
const capsule = this.createCapsule(current, current.id, 'topic-renew', capsuleContent);
|
|
1168
|
+
nextMetadata.capsuleId = capsule.capsuleId;
|
|
1169
|
+
}
|
|
1074
1170
|
next.metadata = nextMetadata;
|
|
1075
1171
|
this.persistConfirmedTopicBoundary(current, found, next);
|
|
1076
1172
|
return {
|
|
@@ -1110,13 +1206,16 @@ export class SessionManager {
|
|
|
1110
1206
|
|| current.metadata?.turnState?.generation !== input.lease.generation)
|
|
1111
1207
|
return 'stale';
|
|
1112
1208
|
const currentId = normalizeBackendSessionId(current.agentSessionId);
|
|
1113
|
-
if (currentId === agentSessionId)
|
|
1209
|
+
if (currentId === agentSessionId) {
|
|
1210
|
+
this.recordCapsuleBinding(current, agentSessionId);
|
|
1114
1211
|
return 'already_active';
|
|
1212
|
+
}
|
|
1115
1213
|
if (currentId && currentId !== agentSessionId)
|
|
1116
1214
|
return 'conflict';
|
|
1117
1215
|
const next = JSON.parse(JSON.stringify(current));
|
|
1118
1216
|
next.agentSessionId = agentSessionId;
|
|
1119
1217
|
this.persistConfirmedTopicBoundary(current, found, next);
|
|
1218
|
+
this.recordCapsuleBinding(next, agentSessionId);
|
|
1120
1219
|
return 'activated';
|
|
1121
1220
|
});
|
|
1122
1221
|
}
|
|
@@ -1717,6 +1816,8 @@ export class SessionManager {
|
|
|
1717
1816
|
}
|
|
1718
1817
|
active.agentSessionId = agentSessionId;
|
|
1719
1818
|
this.persistSession(active, 'sync');
|
|
1819
|
+
if (agentSessionId)
|
|
1820
|
+
this.recordCapsuleBinding(active, agentSessionId);
|
|
1720
1821
|
}
|
|
1721
1822
|
async updateAgentSessionIdBySessionId(sessionId, agentSessionId, turnLease) {
|
|
1722
1823
|
const loaded = this.loadSessionForUpdate(sessionId);
|
|
@@ -1733,8 +1834,12 @@ export class SessionManager {
|
|
|
1733
1834
|
logger.warn(`[SessionManager] Ignoring topic agentSessionId update without an active turn lease: sessionId=${sessionId}`);
|
|
1734
1835
|
return 'stale';
|
|
1735
1836
|
}
|
|
1837
|
+
if (turnLease && !matchesActiveTurn(current, turnLease))
|
|
1838
|
+
return 'stale';
|
|
1736
1839
|
current.agentSessionId = agentSessionId;
|
|
1737
1840
|
const wrote = this.persistSession(current, 'sync');
|
|
1841
|
+
if (agentSessionId)
|
|
1842
|
+
this.recordCapsuleBinding(current, agentSessionId);
|
|
1738
1843
|
if (wrote) {
|
|
1739
1844
|
logger.info(`[SessionManager] Updating agent_session_id: sessionId=${sessionId}, agentSessionId=${agentSessionId}`);
|
|
1740
1845
|
}
|
|
@@ -1745,18 +1850,37 @@ export class SessionManager {
|
|
|
1745
1850
|
* points at the caller's expected ID. This is the recovery counterpart to
|
|
1746
1851
|
* provider-side "session not found" errors and must never rotate a topic.
|
|
1747
1852
|
*/
|
|
1748
|
-
async clearMainSessionBackendIfMatches(sessionId, expectedAgentSessionId, metadataKeys = []) {
|
|
1853
|
+
async clearMainSessionBackendIfMatches(sessionId, expectedAgentSessionId, metadataKeys = [], lease) {
|
|
1749
1854
|
const loaded = this.loadSessionForUpdate(sessionId);
|
|
1750
1855
|
if (!loaded)
|
|
1751
1856
|
return 'missing';
|
|
1752
|
-
|
|
1857
|
+
let { current } = loaded;
|
|
1753
1858
|
if (isTopicSession(current))
|
|
1754
1859
|
return 'topic';
|
|
1860
|
+
if (lease && !matchesActiveTurn(current, lease))
|
|
1861
|
+
return 'mismatch';
|
|
1755
1862
|
const currentId = normalizeBackendSessionId(current.agentSessionId);
|
|
1756
1863
|
if (!currentId)
|
|
1757
1864
|
return 'already_clear';
|
|
1758
1865
|
if (currentId !== normalizeBackendSessionId(expectedAgentSessionId))
|
|
1759
1866
|
return 'mismatch';
|
|
1867
|
+
const content = await generateCapsuleContent(this.getChatDir(current), current, 'backend-recovery', this.capsuleTranscriptReader);
|
|
1868
|
+
// Summary generation is outside the short snapshot mutation. Re-check the
|
|
1869
|
+
// durable binding so a late recovery cannot clear a newer backend.
|
|
1870
|
+
const latest = this.loadSessionForUpdate(sessionId);
|
|
1871
|
+
if (!latest)
|
|
1872
|
+
return 'missing';
|
|
1873
|
+
current = latest.current;
|
|
1874
|
+
if (isTopicSession(current))
|
|
1875
|
+
return 'topic';
|
|
1876
|
+
if (lease && !matchesActiveTurn(current, lease))
|
|
1877
|
+
return 'mismatch';
|
|
1878
|
+
const latestId = normalizeBackendSessionId(current.agentSessionId);
|
|
1879
|
+
if (!latestId)
|
|
1880
|
+
return 'already_clear';
|
|
1881
|
+
if (latestId !== normalizeBackendSessionId(expectedAgentSessionId))
|
|
1882
|
+
return 'mismatch';
|
|
1883
|
+
this.stageBackendRecovery(current, content);
|
|
1760
1884
|
current.agentSessionId = undefined;
|
|
1761
1885
|
if (metadataKeys.length > 0 && current.metadata) {
|
|
1762
1886
|
const metadata = { ...current.metadata };
|
|
@@ -2119,6 +2243,26 @@ export class SessionManager {
|
|
|
2119
2243
|
if (e.code !== 'ENOENT')
|
|
2120
2244
|
throw e;
|
|
2121
2245
|
}
|
|
2246
|
+
// bg / trigger 会话目录只挪 meta 会留下 health.jsonl + 空 _threads/ + _trash/ 的空壳,
|
|
2247
|
+
// 永不回收(bg 的 instanceId 一次性,每跑一次整理多一个)。没有存活 meta 时整个目录删掉。
|
|
2248
|
+
// trigger 的 channelId 可复用:清理期间若又跑出了新 meta,目录保留。
|
|
2249
|
+
// 删不掉(Windows 文件占用)就退回上面的软删除结果,下次不再重试。
|
|
2250
|
+
const disposable = cid.startsWith('bg:')
|
|
2251
|
+
|| (cid.startsWith('trigger:') && scanMetaFiles(dirPath).length === 0 && scanMetaFiles(threadsDir).length === 0);
|
|
2252
|
+
if (disposable) {
|
|
2253
|
+
try {
|
|
2254
|
+
fs.rmSync(dirPath, { recursive: true, force: true });
|
|
2255
|
+
}
|
|
2256
|
+
catch (e) {
|
|
2257
|
+
logger.warn(`[SessionManager] 删除 bg 会话目录失败,保留软删除结果: ${dirPath}: ${e?.message}`);
|
|
2258
|
+
}
|
|
2259
|
+
for (const [id, found] of this.sessionFileIndex) {
|
|
2260
|
+
if (found.chatDir === dirPath)
|
|
2261
|
+
this.sessionFileIndex.delete(id);
|
|
2262
|
+
}
|
|
2263
|
+
if (this.knownChatDirs)
|
|
2264
|
+
this.knownChatDirs = this.knownChatDirs.filter(dir => dir !== dirPath);
|
|
2265
|
+
}
|
|
2122
2266
|
}
|
|
2123
2267
|
}
|
|
2124
2268
|
async createNewSession(channel, channelId, projectPath, name, baseagent, identityMetadata, eventMetadata) {
|
|
@@ -2169,6 +2313,8 @@ export class SessionManager {
|
|
|
2169
2313
|
createdAt: Date.now(),
|
|
2170
2314
|
updatedAt: Date.now(),
|
|
2171
2315
|
};
|
|
2316
|
+
if (eventMetadata?.sourceSessionId)
|
|
2317
|
+
session.sourceSessionId = eventMetadata.sourceSessionId;
|
|
2172
2318
|
this.persistSession(session, 'set');
|
|
2173
2319
|
this.eventBus.publish({
|
|
2174
2320
|
type: 'session:created',
|
|
@@ -2203,6 +2349,7 @@ export class SessionManager {
|
|
|
2203
2349
|
const sourceTopicId = sessionTopicThreadId(sourceSession);
|
|
2204
2350
|
const session = {
|
|
2205
2351
|
id: generateSessionId(),
|
|
2352
|
+
sourceSessionId: sourceSession.id,
|
|
2206
2353
|
channel: sourceSession.channel,
|
|
2207
2354
|
channelType,
|
|
2208
2355
|
channelId: sourceSession.channelId,
|
|
@@ -2269,6 +2416,7 @@ export class SessionManager {
|
|
|
2269
2416
|
};
|
|
2270
2417
|
const session = {
|
|
2271
2418
|
id: generateSessionId(),
|
|
2419
|
+
sourceSessionId: sourceSession.id,
|
|
2272
2420
|
channel: sourceSession.channel,
|
|
2273
2421
|
channelType,
|
|
2274
2422
|
channelId: sourceSession.channelId,
|
|
@@ -2336,12 +2484,15 @@ export class SessionManager {
|
|
|
2336
2484
|
const metadata = { ...(sourceSession.metadata || {}) };
|
|
2337
2485
|
delete metadata.agentSessions;
|
|
2338
2486
|
delete metadata.resumeAt;
|
|
2487
|
+
delete metadata.turnState;
|
|
2488
|
+
delete metadata.capsuleId;
|
|
2339
2489
|
delete metadata.replyContext;
|
|
2340
2490
|
delete metadata.sessionLoop;
|
|
2341
2491
|
delete metadata.sessionFullAccess;
|
|
2342
2492
|
metadata.__sessionRenewedAt = Date.now();
|
|
2343
2493
|
const session = {
|
|
2344
2494
|
id: generateSessionId(),
|
|
2495
|
+
sourceSessionId: sourceSession.id,
|
|
2345
2496
|
channel: sourceSession.channel,
|
|
2346
2497
|
channelType: sourceSession.channelType || sourceSession.channel,
|
|
2347
2498
|
channelId: sourceSession.channelId,
|
|
@@ -2358,6 +2509,9 @@ export class SessionManager {
|
|
|
2358
2509
|
updatedAt: Date.now(),
|
|
2359
2510
|
};
|
|
2360
2511
|
session.identity = sourceSession.identity;
|
|
2512
|
+
const content = await generateCapsuleContent(this.getChatDir(sourceSession), sourceSession, 'session-renew', this.capsuleTranscriptReader);
|
|
2513
|
+
const capsule = this.createCapsule(sourceSession, session.id, 'session-renew', content);
|
|
2514
|
+
session.metadata = { ...session.metadata, capsuleId: capsule.capsuleId };
|
|
2361
2515
|
this.persistSession(session, 'set');
|
|
2362
2516
|
this.eventBus.publish({
|
|
2363
2517
|
type: 'session:created',
|
|
@@ -108,6 +108,7 @@ export function sessionToFile(session) {
|
|
|
108
108
|
}
|
|
109
109
|
return {
|
|
110
110
|
id: session.id,
|
|
111
|
+
...(session.sourceSessionId ? { sourceSessionId: session.sourceSessionId } : {}),
|
|
111
112
|
channel: session.channel,
|
|
112
113
|
channelType,
|
|
113
114
|
channelId: session.channelId,
|
|
@@ -166,6 +167,7 @@ export function fileToSession(file) {
|
|
|
166
167
|
const isTopic = kind.kind === 'topic';
|
|
167
168
|
return {
|
|
168
169
|
id: file.id,
|
|
170
|
+
...(file.sourceSessionId ? { sourceSessionId: file.sourceSessionId } : {}),
|
|
169
171
|
channel: file.channel,
|
|
170
172
|
channelType: file.channelType,
|
|
171
173
|
channelId: file.channelId,
|
|
@@ -221,11 +221,11 @@ export class SessionRenewService {
|
|
|
221
221
|
let decision;
|
|
222
222
|
let source = 'model';
|
|
223
223
|
let judgeMetadata = {
|
|
224
|
-
model: effectiveConfig.Services?.decision
|
|
224
|
+
model: effectiveConfig.Services?.decision?.model,
|
|
225
225
|
threshold,
|
|
226
226
|
};
|
|
227
227
|
try {
|
|
228
|
-
const model =
|
|
228
|
+
const model = effectiveConfig.Services?.decision?.model?.trim();
|
|
229
229
|
if (!model)
|
|
230
230
|
throw new SessionRenewJudgeError('decision_model_missing');
|
|
231
231
|
const provider = this.inferenceProviderResolver.getDecisionInferenceProvider(request.selfAid);
|
|
@@ -306,7 +306,7 @@ export class SessionRenewService {
|
|
|
306
306
|
return resolveEffective({
|
|
307
307
|
self: request.selfAid,
|
|
308
308
|
peerKey,
|
|
309
|
-
}, { cache: true
|
|
309
|
+
}, { cache: true });
|
|
310
310
|
}
|
|
311
311
|
readConversationEntries(session) {
|
|
312
312
|
const entries = readAllJsonlLines(messageLogPath(this.sessionManager.getChatDir(session)));
|
|
@@ -3,7 +3,7 @@ import path from 'path';
|
|
|
3
3
|
import { parseDocument } from 'yaml';
|
|
4
4
|
import { resolveSkills } from './switch-resolver.js';
|
|
5
5
|
import { logger } from '../../utils/logger.js';
|
|
6
|
-
import { isDevMode } from '../../paths.js';
|
|
6
|
+
import { isDevMode, resolveRoot, getPackageRoot } from '../../paths.js';
|
|
7
7
|
import { isShippedPath, readVerifiedText } from '../file-integrity/read.js';
|
|
8
8
|
/**
|
|
9
9
|
* 生成索引文件(汇总 → 分组 → 落两文件)。
|
|
@@ -21,11 +21,14 @@ export function generateSkillIndexes(agentDir, override) {
|
|
|
21
21
|
const localSkills = skills.filter(s => s.source === 'local');
|
|
22
22
|
const indexDir = path.join(agentDir, 'skills');
|
|
23
23
|
fs.mkdirSync(indexDir, { recursive: true });
|
|
24
|
+
// 取各组根目录用于「路径规则」块
|
|
25
|
+
const builtinRoot = override?.builtin ?? path.join(getPackageRoot(), 'kits', 'skills');
|
|
26
|
+
const localRoot = override?.local ?? path.join(resolveRoot(), 'skills');
|
|
24
27
|
// ③ 分别生成(或清理)
|
|
25
|
-
generateOneIndex(indexDir, '.index-builtin.md', builtinSkills, 'builtin');
|
|
26
|
-
generateOneIndex(indexDir, '.index-local.md', localSkills, 'local');
|
|
28
|
+
generateOneIndex(indexDir, '.index-builtin.md', builtinSkills, 'builtin', builtinRoot);
|
|
29
|
+
generateOneIndex(indexDir, '.index-local.md', localSkills, 'local', localRoot);
|
|
27
30
|
}
|
|
28
|
-
function generateOneIndex(indexDir, filename, skills, label) {
|
|
31
|
+
function generateOneIndex(indexDir, filename, skills, label, skillRoot) {
|
|
29
32
|
const filePath = path.join(indexDir, filename);
|
|
30
33
|
// 空集:删除旧文件
|
|
31
34
|
if (skills.length === 0) {
|
|
@@ -40,12 +43,19 @@ function generateOneIndex(indexDir, filename, skills, label) {
|
|
|
40
43
|
加载方式:
|
|
41
44
|
EC 技能用 \`ec skill load <技能名>\` 加载,命令直接输出 SKILL.md 正文并附带技能目录的绝对路径。
|
|
42
45
|
它们不是宿主工具自带的技能或斜杠命令,用 Skill/斜杠命令加载会报 Unknown skill/未知命令。
|
|
46
|
+
|
|
47
|
+
路径规则:
|
|
48
|
+
根目录: ${skillRoot}
|
|
49
|
+
技能目录 = 根目录 + "${path.sep}" + 技能名
|
|
50
|
+
执行脚本时必须写完整绝对路径。
|
|
43
51
|
`;
|
|
44
|
-
// 技能条目(name + description
|
|
52
|
+
// 技能条目(name + description),并附示例路径
|
|
45
53
|
const items = [];
|
|
46
54
|
for (const skill of skills) {
|
|
47
55
|
const desc = readSkillDescription(skill.skillDir);
|
|
48
56
|
items.push(`- ${skill.name}\n ${desc || '(无描述)'}`);
|
|
57
|
+
// 示例路径:用真实技能名,不是占位符
|
|
58
|
+
items.push(` 示例(技能名为 ${skill.name}): ${path.join(skill.skillDir, 'SKILL.md')}`);
|
|
49
59
|
}
|
|
50
60
|
const content = header + '\n' + items.join('\n\n') + '\n';
|
|
51
61
|
fs.writeFileSync(filePath, content, 'utf-8');
|
|
@@ -68,14 +68,19 @@ export function memoryReadRoots(ctx) {
|
|
|
68
68
|
case 'profile':
|
|
69
69
|
add(...consolidated('relation'), messages);
|
|
70
70
|
break;
|
|
71
|
-
case 'forget':
|
|
71
|
+
case 'forget': {
|
|
72
72
|
// 一次会话只审一层:关系层由关系整理链逐关系审,agent 层只审 personal/memory 自身
|
|
73
73
|
if (ctx.memoryScope) {
|
|
74
74
|
add(...consolidated(ctx.memoryScope));
|
|
75
|
+
// 本层的遗忘日志:只给这一个文件,不给 archive/ 整个目录(归档的记忆正文不该进审查范围)
|
|
76
|
+
const layer = layerDir(ctx.memoryScope, ctx);
|
|
77
|
+
if (layer)
|
|
78
|
+
add(path.join(layer, 'archive', 'FORGET-LOG.md'));
|
|
75
79
|
if (ctx.memoryScope === 'relation')
|
|
76
80
|
add(messages);
|
|
77
81
|
}
|
|
78
82
|
break;
|
|
83
|
+
}
|
|
79
84
|
default:
|
|
80
85
|
break;
|
|
81
86
|
}
|