evolcore 0.0.41-test.0 → 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 +49 -0
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/baseagent.js +20 -43
- package/dist/agents/claude-runner.js +177 -92
- package/dist/agents/codex-runner.js +84 -28
- package/dist/agents/ecagent-runner.js +1 -1
- package/dist/agents/gemini-runner.js +1 -1
- package/dist/aun/group/fs-download.js +39 -0
- package/dist/aun/group/identity.js +36 -21
- package/dist/aun/group/operations.js +5 -0
- package/dist/aun/msg/managed-operation.js +68 -7
- package/dist/aun/msg/p2p.js +5 -0
- package/dist/aun/service-proxy.js +36 -12
- package/dist/channels/aun.js +334 -20
- package/dist/channels/daemon.js +15 -1
- package/dist/cli/aun-commands.js +4 -20
- package/dist/cli/daemon-commands.js +678 -697
- 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/role.js +85 -0
- package/dist/config/access-policy.js +7 -2
- 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 +5 -19
- 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 +88 -594
- package/dist/config/peer-role-resolver.js +13 -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-runtime.js +1 -1
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +1 -1
- package/dist/core/auth/authorization-audit.js +17 -6
- 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 +31 -6
- package/dist/core/command/agent-control.js +3 -7
- 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 +48 -99
- package/dist/core/command/connect-menu.js +11 -3
- 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 +5 -6
- package/dist/core/command/menu-handler.js +49 -62
- package/dist/core/command/role-menu.js +147 -30
- package/dist/core/command/slash-handler.js +123 -254
- package/dist/core/daemon-control.js +8 -14
- 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 +6 -2
- 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 +189 -189
- 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 +8 -2
- package/dist/core/message/im-renderer.js +7 -4
- package/dist/core/message/message-admission.js +89 -4
- package/dist/core/message/message-bridge.js +31 -18
- package/dist/core/message/response-engine.js +77 -8
- 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 +30 -41
- 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 +23 -21
- package/dist/core/permission/ec-command-parser.js +30 -2
- package/dist/core/permission/sandbox-runtime.js +18 -1
- package/dist/core/permission/tool-policy.js +14 -3
- 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 +1 -1
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +20 -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 +76 -14
- package/dist/ipc.js +170 -12
- 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/utils/cross-platform.js +14 -0
- package/dist/utils/ecweb-supervisor.js +258 -83
- package/dist/utils/error-utils.js +2 -2
- package/dist/utils/logger.js +24 -5
- package/dist/utils/package-version-info.js +4 -2
- package/kits/docs/channels/aun.md +9 -0
- package/kits/docs/evolcore/agent.md +1 -1
- package/kits/docs/evolcore/config.md +17 -6
- package/kits/docs/evolcore/contact.md +3 -0
- package/kits/docs/evolcore/fs.md +11 -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 +4 -0
- package/kits/docs/evolcore/model.md +23 -20
- package/kits/docs/evolcore/msg.md +4 -7
- 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 +8 -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/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/system-fragments/baseagent.md +2 -2
- package/kits/templates/system-fragments/memory.md +4 -4
- package/package.json +6 -2
|
@@ -165,7 +165,7 @@ export async function generateCapsuleContent(chatDir, source, cause, reader) {
|
|
|
165
165
|
const peer = source.chatType === 'group' ? source.metadata?.groupId || source.channelId
|
|
166
166
|
: source.metadata?.peerId || source.channelId;
|
|
167
167
|
const config = resolveEffective({ self: source.selfAID,
|
|
168
|
-
peerKey: formatPeerKey(source.channelType || source.channel, peer) }, { cache: true
|
|
168
|
+
peerKey: formatPeerKey(source.channelType || source.channel, peer) }, { cache: true });
|
|
169
169
|
const selection = config.Services?.auxiliary;
|
|
170
170
|
if (selection?.model) {
|
|
171
171
|
const provider = createTextInferenceProvider(source.baseagent, config);
|
|
@@ -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) {
|
|
@@ -2243,6 +2243,26 @@ export class SessionManager {
|
|
|
2243
2243
|
if (e.code !== 'ENOENT')
|
|
2244
2244
|
throw e;
|
|
2245
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
|
+
}
|
|
2246
2266
|
}
|
|
2247
2267
|
}
|
|
2248
2268
|
async createNewSession(channel, channelId, projectPath, name, baseagent, identityMetadata, eventMetadata) {
|
|
@@ -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
|
}
|
|
@@ -210,7 +210,11 @@ export class ThreadService {
|
|
|
210
210
|
topicStatus: last.topicStatus ?? 'pending',
|
|
211
211
|
createdAt: last.createdAt ?? 0,
|
|
212
212
|
lastActiveAt: last.updatedAt ?? 0,
|
|
213
|
-
...(
|
|
213
|
+
...(typeof last.metadata?.nameUpdatedAt === 'number'
|
|
214
|
+
? { nameUpdatedAt: last.metadata.nameUpdatedAt }
|
|
215
|
+
: typeof last.nameUpdatedAt === 'number'
|
|
216
|
+
? { nameUpdatedAt: last.nameUpdatedAt }
|
|
217
|
+
: {}),
|
|
214
218
|
};
|
|
215
219
|
}
|
|
216
220
|
catch {
|
|
@@ -253,7 +257,7 @@ export class ThreadService {
|
|
|
253
257
|
peer, // channelId
|
|
254
258
|
'', // defaultProjectPath — threads are not bound to a project
|
|
255
259
|
threadId, // threadId
|
|
256
|
-
{ peerName: peer }, // metadata
|
|
260
|
+
{ peerName: peer, nameUpdatedAt: now }, // metadata
|
|
257
261
|
sanitized, // name
|
|
258
262
|
undefined, // userId
|
|
259
263
|
peerKind === 'group' ? 'group' : 'private', // chatType
|
|
@@ -271,6 +275,7 @@ export class ThreadService {
|
|
|
271
275
|
channelType: 'aun',
|
|
272
276
|
peerKind,
|
|
273
277
|
name: sanitized,
|
|
278
|
+
nameUpdatedAt: now,
|
|
274
279
|
label: label ?? null,
|
|
275
280
|
topicStatus: topicStatus ?? 'pending',
|
|
276
281
|
createdAt: now,
|
|
@@ -321,7 +326,7 @@ export class ThreadService {
|
|
|
321
326
|
throw new ThreadServiceError(`话题不存在: ${threadId}`, 'TOPIC_NOT_FOUND');
|
|
322
327
|
if (entry.name === sanitized)
|
|
323
328
|
return { changed: false, name: sanitized };
|
|
324
|
-
const nameUpdatedAt = Date.now();
|
|
329
|
+
const nameUpdatedAt = Math.max(Date.now(), Number(entry.nameUpdatedAt ?? entry.createdAt ?? 0) + 1);
|
|
325
330
|
entry.name = sanitized;
|
|
326
331
|
entry.nameUpdatedAt = nameUpdatedAt;
|
|
327
332
|
entry.lastActiveAt = nameUpdatedAt;
|
|
@@ -330,7 +335,7 @@ export class ThreadService {
|
|
|
330
335
|
// Sync to session
|
|
331
336
|
const session = await this.sessionManager.getThreadSession(entryChannelType(entry), entry.peer, threadId, selfAid);
|
|
332
337
|
if (session) {
|
|
333
|
-
await this.sessionManager.renameSession(session.id, sanitized);
|
|
338
|
+
await this.sessionManager.renameSession(session.id, sanitized, nameUpdatedAt);
|
|
334
339
|
}
|
|
335
340
|
return { changed: true, name: sanitized, nameUpdatedAt, peerKind: entry.peerKind };
|
|
336
341
|
}
|
|
@@ -390,7 +395,7 @@ export class ThreadService {
|
|
|
390
395
|
this.appendThreadSnapshot(input.selfAid, entry);
|
|
391
396
|
const session = await this.sessionManager.getThreadSession(entryChannelType(entry), entry.peer, input.threadId, input.selfAid);
|
|
392
397
|
if (session)
|
|
393
|
-
await this.sessionManager.renameSession(session.id, sanitized);
|
|
398
|
+
await this.sessionManager.renameSession(session.id, sanitized, input.nameUpdatedAt);
|
|
394
399
|
return { applied: true };
|
|
395
400
|
}
|
|
396
401
|
// ── P1a.1.6: 话题标签 ──
|
|
@@ -790,6 +795,11 @@ export class ThreadService {
|
|
|
790
795
|
channelType: parsedDir?.channelType ?? 'aun',
|
|
791
796
|
peerKind: last.chatType === 'group' ? 'group' : 'private',
|
|
792
797
|
name: last.name ?? last.threadId,
|
|
798
|
+
...(typeof last.metadata?.nameUpdatedAt === 'number'
|
|
799
|
+
? { nameUpdatedAt: last.metadata.nameUpdatedAt }
|
|
800
|
+
: typeof last.nameUpdatedAt === 'number'
|
|
801
|
+
? { nameUpdatedAt: last.nameUpdatedAt }
|
|
802
|
+
: {}),
|
|
793
803
|
label: last.label ?? null,
|
|
794
804
|
topicStatus: last.topicStatus ?? 'pending',
|
|
795
805
|
createdAt: last.createdAt ?? 0,
|
|
@@ -973,7 +983,10 @@ export class ThreadService {
|
|
|
973
983
|
id: latest.id ?? entry.sessionId,
|
|
974
984
|
projectPath: latest.projectPath ?? '',
|
|
975
985
|
chatType: entry.peerKind === 'group' ? 'group' : 'private',
|
|
976
|
-
metadata:
|
|
986
|
+
metadata: {
|
|
987
|
+
...(latest.metadata ?? {}),
|
|
988
|
+
...(entry.nameUpdatedAt !== undefined ? { nameUpdatedAt: entry.nameUpdatedAt } : {}),
|
|
989
|
+
},
|
|
977
990
|
// topic metadata — updated values
|
|
978
991
|
threadId: entry.threadId,
|
|
979
992
|
channelIdAlias: entry.peer,
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { agentDir } from '../paths.js';
|
|
4
|
+
import { ownerResolver } from '../core/ownership/owner-resolver.js';
|
|
5
|
+
import { OwnerDirectoryCache, OWNER_DIRECTORY_INITIAL_WAIT_MS, OWNER_DIRECTORY_SCOPES, } from './owner-directory-cache.js';
|
|
6
|
+
const liveDirectories = new Map();
|
|
7
|
+
// Coalesce negative lookups from unrelated senders as well as concurrent calls.
|
|
8
|
+
const MISS_REFRESH_INTERVAL_MS = 60_000;
|
|
9
|
+
/** Register only the channel's existing client-backed cache; no SDK connections are created here. */
|
|
10
|
+
export function registerOwnerDirectoryAdmission(input) {
|
|
11
|
+
const current = liveDirectories.get(input.selfAid);
|
|
12
|
+
if (current?.cache === input.cache)
|
|
13
|
+
return;
|
|
14
|
+
liveDirectories.set(input.selfAid, { ...input, missAttemptAt: {} });
|
|
15
|
+
}
|
|
16
|
+
/** Cache misses get one bounded synchronization attempt before admission, using the live channel. */
|
|
17
|
+
export async function prepareOwnerDirectoryAdmission(selfAid, aid) {
|
|
18
|
+
const live = liveDirectories.get(selfAid);
|
|
19
|
+
if (!live)
|
|
20
|
+
return;
|
|
21
|
+
if (!live.isCurrent()) {
|
|
22
|
+
liveDirectories.delete(selfAid);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (ownerResolver.owner(selfAid) !== live.ownerAid)
|
|
26
|
+
return;
|
|
27
|
+
const agents = live.cache.readSnapshot('agents');
|
|
28
|
+
if (agents?.entries.some(entry => entry.aid === aid)) {
|
|
29
|
+
// The higher-priority Agent category is already known. Only its stale refresh may run.
|
|
30
|
+
void live.cache.lookupByAid('agents', aid).catch(() => { });
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const contacts = live.cache.readSnapshot('contacts');
|
|
34
|
+
if (contacts?.entries.some(entry => entry.aid === aid)
|
|
35
|
+
&& (agents || live.cache.scopeAccess('agents') === 'not_authorized')) {
|
|
36
|
+
void live.cache.refreshIfNeeded().catch(() => { });
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const tasks = [];
|
|
40
|
+
for (const scope of OWNER_DIRECTORY_SCOPES) {
|
|
41
|
+
if (live.cache.scopeAccess(scope) !== 'authorized')
|
|
42
|
+
continue;
|
|
43
|
+
const found = live.cache.readSnapshot(scope)?.entries.some(entry => entry.aid === aid);
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
if (!found) {
|
|
46
|
+
if (now - (live.missAttemptAt[scope] ?? 0) < MISS_REFRESH_INTERVAL_MS)
|
|
47
|
+
continue;
|
|
48
|
+
live.missAttemptAt[scope] = now;
|
|
49
|
+
}
|
|
50
|
+
tasks.push(live.cache.lookupByAid(scope, aid));
|
|
51
|
+
}
|
|
52
|
+
if (tasks.length === 0)
|
|
53
|
+
return;
|
|
54
|
+
let timer;
|
|
55
|
+
try {
|
|
56
|
+
await Promise.race([
|
|
57
|
+
Promise.allSettled(tasks),
|
|
58
|
+
new Promise(resolve => { timer = setTimeout(resolve, OWNER_DIRECTORY_INITIAL_WAIT_MS); }),
|
|
59
|
+
]);
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
if (timer)
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Local-only classification. A stale or changed Owner can never authorize an old snapshot. */
|
|
67
|
+
export function readOwnerDirectoryMembership(selfAid, aid) {
|
|
68
|
+
const directory = path.join(agentDir(selfAid), 'directory');
|
|
69
|
+
const configured = ['authorization.json', 'authorization.json_', 'agents.json', 'contacts.json']
|
|
70
|
+
.some(name => fs.existsSync(path.join(directory, name)));
|
|
71
|
+
if (!configured)
|
|
72
|
+
return undefined;
|
|
73
|
+
const unknown = { agents: 'unavailable', contacts: 'unavailable' };
|
|
74
|
+
const ownerAid = ownerResolver.owner(selfAid);
|
|
75
|
+
if (!ownerAid)
|
|
76
|
+
return unknown;
|
|
77
|
+
try {
|
|
78
|
+
const cache = new OwnerDirectoryCache({ selfAid, ownerAid, directory });
|
|
79
|
+
const membership = { ...unknown };
|
|
80
|
+
for (const scope of OWNER_DIRECTORY_SCOPES) {
|
|
81
|
+
const access = cache.scopeAccess(scope);
|
|
82
|
+
if (access === 'not_authorized')
|
|
83
|
+
membership[scope] = 'not_authorized';
|
|
84
|
+
else if (access === 'authorized') {
|
|
85
|
+
const snapshot = cache.readSnapshot(scope);
|
|
86
|
+
if (snapshot)
|
|
87
|
+
membership[scope] = snapshot.entries.some(entry => entry.aid === aid) ? 'found' : 'not_found';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return membership;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return unknown;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import Ajv from 'ajv';
|
|
5
|
+
import { readAuthoritativePersonalFsObject } from '../aun/group/fs-download.js';
|
|
6
|
+
import { atomicReadJson, atomicWriteJson } from '../utils/atomic-write.js';
|
|
7
|
+
import { getAunRequestRegistry } from '../core/message/aun-request-registry.js';
|
|
8
|
+
import { parseOwnerDirectoryGrantAbilityResponse } from './owner-directory-cache.js';
|
|
9
|
+
import { logger } from '../utils/logger.js';
|
|
10
|
+
const ABILITY_PATH = 'directory/access';
|
|
11
|
+
const DEFINITION_ID = 'evol-directory-access-v1';
|
|
12
|
+
const REQUEST_TTL_SECONDS = 60;
|
|
13
|
+
const REQUEST_PARAMS = {
|
|
14
|
+
action: 'request', scopes: ['agents'], valid_for_seconds: 2_592_000,
|
|
15
|
+
purpose: '同步 Owner 的 Agent 名录,识别并联系同属 Owner 的 Agent',
|
|
16
|
+
};
|
|
17
|
+
/** Startup/Owner-message retries, with a durable stop only for a correlated Owner refusal. */
|
|
18
|
+
export class OwnerDirectoryAuthorization {
|
|
19
|
+
options;
|
|
20
|
+
inFlight;
|
|
21
|
+
retryTimer;
|
|
22
|
+
registry;
|
|
23
|
+
now;
|
|
24
|
+
constructor(options) {
|
|
25
|
+
this.options = options;
|
|
26
|
+
this.registry = options.registry ?? getAunRequestRegistry();
|
|
27
|
+
this.now = options.now ?? Date.now;
|
|
28
|
+
}
|
|
29
|
+
ensureAuthorization() {
|
|
30
|
+
if (this.inFlight) {
|
|
31
|
+
logger.debug(`[OwnerDirectory] Authorization request already in flight for ${this.options.selfAid} -> ${this.options.ownerAid}`);
|
|
32
|
+
return this.inFlight;
|
|
33
|
+
}
|
|
34
|
+
logger.info(`[OwnerDirectory] Starting authorization check: selfAid=${this.options.selfAid}, Owner=${this.options.ownerAid}`);
|
|
35
|
+
const task = this.requestIfNeeded().finally(() => {
|
|
36
|
+
if (this.inFlight === task)
|
|
37
|
+
this.inFlight = undefined;
|
|
38
|
+
});
|
|
39
|
+
this.inFlight = task;
|
|
40
|
+
return task;
|
|
41
|
+
}
|
|
42
|
+
dispose() {
|
|
43
|
+
if (this.retryTimer)
|
|
44
|
+
clearTimeout(this.retryTimer);
|
|
45
|
+
this.retryTimer = undefined;
|
|
46
|
+
}
|
|
47
|
+
scheduleCheck(at) {
|
|
48
|
+
this.dispose();
|
|
49
|
+
this.retryTimer = setTimeout(() => {
|
|
50
|
+
this.retryTimer = undefined;
|
|
51
|
+
if (!this.options.isCurrent())
|
|
52
|
+
return;
|
|
53
|
+
void this.ensureAuthorization().catch(() => {
|
|
54
|
+
if (this.options.isCurrent())
|
|
55
|
+
this.scheduleCheck(this.now() + 5_000);
|
|
56
|
+
});
|
|
57
|
+
}, Math.max(1, at - this.now()));
|
|
58
|
+
this.retryTimer.unref();
|
|
59
|
+
}
|
|
60
|
+
ownsRequest(record) {
|
|
61
|
+
return record.selfAid === this.options.selfAid && record.targetAid === this.options.ownerAid
|
|
62
|
+
&& record.requestId.startsWith('owner-directory-auto-');
|
|
63
|
+
}
|
|
64
|
+
/** Called only after the channel refreshes Ownership and the registry verifies the sender/device. */
|
|
65
|
+
async acceptResponse(record) {
|
|
66
|
+
const attempt = this.readAttempt();
|
|
67
|
+
const response = record.responsePayload;
|
|
68
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Received authorization response from ${record.targetAid}, state: ${record.state}, hasAttempt=${!!attempt}, hasResponse=${!!response}`);
|
|
69
|
+
if (response) {
|
|
70
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Response payload summary: type=${response.type}, role=${response.role}, ok=${response.ok}, ability_path=${response.ability_path}, definition_id=${response.definition_id}, call_id=${response.call_id}, operation_id=${response.operation_id}, error=${JSON.stringify(response.error)}`);
|
|
71
|
+
}
|
|
72
|
+
if (!this.options.isCurrent()) {
|
|
73
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - connection no longer current`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (!attempt) {
|
|
77
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - no local attempt on disk`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (!this.ownsRequest(record)) {
|
|
81
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - record not owned by this attempt (requestId=${record.requestId}, selfAid=${record.selfAid}, targetAid=${record.targetAid})`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (record.state !== 'completed') {
|
|
85
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - record.state=${record.state} (not completed)`);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (!record.targetDeviceId || record.responseDeviceId !== record.targetDeviceId) {
|
|
89
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - device mismatch: target=${record.targetDeviceId}, response=${record.responseDeviceId}`);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (!response || response.type !== 'ability' || response.role !== 'result'
|
|
93
|
+
|| response.call_id !== record.requestId || response.operation_id !== attempt.operationId
|
|
94
|
+
|| response.ability_path !== ABILITY_PATH || response.definition_id !== DEFINITION_ID) {
|
|
95
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - response validation failed. matches: type=${response?.type === 'ability'}, role=${response?.role === 'result'}, call_id=${response?.call_id === record.requestId}, operation_id=${response?.operation_id === attempt.operationId}, ability_path=${response?.ability_path === ABILITY_PATH}, definition_id=${response?.definition_id === DEFINITION_ID}`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
// An absent grant, an ACK, a timeout or a storage/transport error is not an Owner refusal.
|
|
99
|
+
if (response.ok === false && isRecord(response.error)
|
|
100
|
+
&& ['user_denied', 'permission_denied'].includes(String(response.error.code))) {
|
|
101
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: Authorization explicitly denied by Owner: ${response.error.code}, message=${response.error.message}`);
|
|
102
|
+
this.dispose();
|
|
103
|
+
this.writeAttempt({ ...attempt, status: 'denied' });
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (response.ok === false) {
|
|
107
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: Authorization request failed (retryable): ${JSON.stringify(response.error)}`);
|
|
108
|
+
this.writeAttempt({ ...attempt, status: 'retryable' });
|
|
109
|
+
if (attempt.action === 'status')
|
|
110
|
+
this.scheduleCheck(this.now() + 5_000);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const grant = parseOwnerDirectoryGrantAbilityResponse(response);
|
|
114
|
+
if (!grant || grant.owner_aid !== this.options.ownerAid || grant.grantee_aid !== this.options.selfAid) {
|
|
115
|
+
logger.warn(`[OwnerDirectory] Authorization response validation failed or identity mismatch`);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
logger.info(`[OwnerDirectory] Received valid authorization grant: status=${grant.status}, scopes=${JSON.stringify(grant.active_scopes)}`);
|
|
119
|
+
this.options.cache.saveAuthorization(grant);
|
|
120
|
+
const result = response.result;
|
|
121
|
+
if (this.options.cache.scopeAccess('agents') !== 'authorized' && isRecord(result)
|
|
122
|
+
&& result.status === 'sync_pending' && ['initializing', 'syncing'].includes(String(result.readiness))
|
|
123
|
+
&& isRecord(result.retry_request) && result.retry_request.action === 'status') {
|
|
124
|
+
const hint = result.retry_after_seconds;
|
|
125
|
+
const delay = typeof hint === 'number' && Number.isFinite(hint) ? Math.min(300, Math.max(1, hint)) : 5;
|
|
126
|
+
const retryAt = this.now() + Math.ceil(delay * 1_000);
|
|
127
|
+
logger.info(`[OwnerDirectory] Owner directory is ${result.readiness}, will check status in ${delay}s`);
|
|
128
|
+
this.writeAttempt({ ...attempt, status: 'initializing', action: 'status', retryAt });
|
|
129
|
+
this.scheduleCheck(retryAt);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
this.dispose();
|
|
133
|
+
const finalStatus = this.options.cache.scopeAccess('agents') === 'authorized' ? 'granted' : 'retryable';
|
|
134
|
+
logger.info(`[OwnerDirectory] Authorization completed with status: ${finalStatus}`);
|
|
135
|
+
this.writeAttempt({ ...attempt, action: 'request', retryAt: undefined, status: finalStatus });
|
|
136
|
+
logger.info(`[OwnerDirectory] Triggering directory cache refresh after authorization`);
|
|
137
|
+
await this.options.cache.handleOwnerChangedEvent(this.options.ownerAid);
|
|
138
|
+
}
|
|
139
|
+
async requestIfNeeded() {
|
|
140
|
+
if (!this.options.isCurrent()) {
|
|
141
|
+
logger.debug(`[OwnerDirectory] Authorization check skipped - connection no longer current for ${this.options.selfAid}`);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
let previous = this.readAttempt();
|
|
145
|
+
const scopeAccess = this.options.cache.scopeAccess('agents');
|
|
146
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Scope 'agents' access status: ${scopeAccess}, previous status: ${previous?.status || 'none'}`);
|
|
147
|
+
if (scopeAccess === 'authorized') {
|
|
148
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Already authorized for Owner ${this.options.ownerAid}, skipping request`);
|
|
149
|
+
this.dispose();
|
|
150
|
+
// A later valid grant supersedes an earlier refusal, including grants requested manually.
|
|
151
|
+
if (previous?.status === 'denied')
|
|
152
|
+
this.writeAttempt({ ...previous, status: 'granted' });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (previous?.status === 'denied') {
|
|
156
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: Authorization previously denied by Owner ${this.options.ownerAid}, not retrying`);
|
|
157
|
+
this.dispose();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (previous?.status === 'pending') {
|
|
161
|
+
const record = this.registry.get(this.options.selfAid, previous.callId);
|
|
162
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: found pending attempt, callId=${previous.callId.slice(0, 24)}..., record=${record ? `state=${record.state}` : 'not found'}, deadlineAt=${new Date(previous.deadlineAt).toISOString()}, expired=${previous.deadlineAt <= this.now()}`);
|
|
163
|
+
if (record?.state === 'completed') {
|
|
164
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: processing completed record`);
|
|
165
|
+
await this.acceptResponse(record);
|
|
166
|
+
previous = this.readAttempt();
|
|
167
|
+
if (previous?.status === 'denied' || this.options.cache.scopeAccess('agents') === 'authorized')
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
else if (previous.deadlineAt > this.now() && record && !['failed', 'unknown'].includes(record.state)) {
|
|
171
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: pending request still within deadline, skipping (record.state=${record.state})`);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: pending request expired or failed, will retry (record=${record ? `state=${record.state}` : 'not found'})`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (previous?.status === 'initializing' && (previous.retryAt ?? 0) > this.now()) {
|
|
179
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: initializing, retryAt=${new Date(previous.retryAt).toISOString()}, waiting`);
|
|
180
|
+
this.scheduleCheck(previous.retryAt);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const action = previous?.action === 'status' ? 'status' : 'request';
|
|
184
|
+
const params = action === 'status' ? { action: 'status' } : REQUEST_PARAMS;
|
|
185
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Discovering device for Owner ${this.options.ownerAid}, action: ${action}`);
|
|
186
|
+
let deviceId;
|
|
187
|
+
try {
|
|
188
|
+
deviceId = await this.discoverDevice(previous?.deviceId, params);
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: Device discovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Selected device: ${deviceId}`);
|
|
195
|
+
if (!this.options.isCurrent() || this.options.cache.scopeAccess('agents') === 'authorized'
|
|
196
|
+
|| this.readAttempt()?.status === 'denied')
|
|
197
|
+
return;
|
|
198
|
+
// Retain the logical operation across unanswered attempts for Provider idempotency.
|
|
199
|
+
const operationId = previous?.status === 'pending' ? previous.operationId : `directory-${randomUUID()}`;
|
|
200
|
+
const callId = `owner-directory-auto-${randomUUID()}`;
|
|
201
|
+
logger.info(`[OwnerDirectory] Sending authorization ${action} to Owner ${this.options.ownerAid}, operation: ${operationId.slice(0, 16)}..., call: ${callId.slice(0, 24)}...`);
|
|
202
|
+
const prepared = this.registry.prepare({
|
|
203
|
+
selfAid: this.options.selfAid, targetAid: this.options.ownerAid, targetDeviceId: deviceId,
|
|
204
|
+
timeoutMs: REQUEST_TTL_SECONDS * 1_000,
|
|
205
|
+
payload: { type: 'ability', role: 'call', call_id: callId, operation_id: operationId,
|
|
206
|
+
ability_path: ABILITY_PATH, definition_id: DEFINITION_ID, params,
|
|
207
|
+
ttl: REQUEST_TTL_SECONDS, async: false },
|
|
208
|
+
});
|
|
209
|
+
this.writeAttempt({ schemaVersion: 1, selfAid: this.options.selfAid, ownerAid: this.options.ownerAid,
|
|
210
|
+
operationId, callId, deviceId, action, deadlineAt: this.now() + REQUEST_TTL_SECONDS * 1_000, status: 'pending' });
|
|
211
|
+
if (action === 'status')
|
|
212
|
+
this.scheduleCheck(this.now() + REQUEST_TTL_SECONDS * 1_000);
|
|
213
|
+
this.registry.markSending(this.options.selfAid, callId);
|
|
214
|
+
try {
|
|
215
|
+
const sent = await this.options.send(prepared.payload, deviceId, REQUEST_TTL_SECONDS);
|
|
216
|
+
if (!sent.ok || !sent.message_id) {
|
|
217
|
+
logger.error(`[OwnerDirectory] Authorization request not accepted: ${sent.error}`);
|
|
218
|
+
throw new Error(sent.error ?? 'directory authorization request was not accepted');
|
|
219
|
+
}
|
|
220
|
+
logger.info(`[OwnerDirectory] Authorization request sent successfully, message_id: ${sent.message_id}`);
|
|
221
|
+
this.registry.markTransportAccepted(this.options.selfAid, callId, sent.message_id, sent.status);
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
logger.error(`[OwnerDirectory] Authorization request failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
225
|
+
this.registry.markFailed(this.options.selfAid, callId, error instanceof Error ? error.message : String(error));
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
async discoverDevice(preferred, params) {
|
|
230
|
+
logger.info(`[OwnerDirectory] discoverDevice: reading ability/index.json from Owner ${this.options.ownerAid}`);
|
|
231
|
+
let index;
|
|
232
|
+
try {
|
|
233
|
+
index = await this.readPublishedJson('/ability/index.json', 128 * 1024);
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
logger.warn(`[OwnerDirectory] discoverDevice: failed to read ability/index.json: ${error instanceof Error ? error.message : String(error)}`);
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
const capabilities = Array.isArray(index.capabilities) ? index.capabilities : [];
|
|
240
|
+
logger.info(`[OwnerDirectory] discoverDevice: ability/index.json has ${capabilities.length} capabilities`);
|
|
241
|
+
const entry = capabilities.find(value => isRecord(value)
|
|
242
|
+
&& value.path === ABILITY_PATH && value.definition_id === DEFINITION_ID);
|
|
243
|
+
if (!isRecord(entry) || !Array.isArray(entry.devices) || !entry.devices.length
|
|
244
|
+
|| entry.devices.some(device => typeof device !== 'string' || !device.trim())
|
|
245
|
+
|| typeof entry.detail_ref !== 'string') {
|
|
246
|
+
logger.warn(`[OwnerDirectory] discoverDevice: Owner has no valid directory/access entry. entry=${JSON.stringify(entry)}`);
|
|
247
|
+
throw new Error('Owner has no published directory/access device/contract');
|
|
248
|
+
}
|
|
249
|
+
logger.info(`[OwnerDirectory] discoverDevice: found entry, devices=${JSON.stringify(entry.devices)}, detail_ref=${entry.detail_ref}`);
|
|
250
|
+
const prefix = `${this.options.ownerAid}:/`;
|
|
251
|
+
if (!entry.detail_ref.startsWith(prefix)) {
|
|
252
|
+
logger.warn(`[OwnerDirectory] discoverDevice: detail_ref does not start with owner prefix: ${entry.detail_ref}`);
|
|
253
|
+
throw new Error('Owner directory contract must belong to the same Owner');
|
|
254
|
+
}
|
|
255
|
+
const contractPath = entry.detail_ref.slice(this.options.ownerAid.length + 1);
|
|
256
|
+
logger.info(`[OwnerDirectory] discoverDevice: reading contract at ${contractPath}`);
|
|
257
|
+
let contract;
|
|
258
|
+
try {
|
|
259
|
+
contract = await this.readPublishedJson(contractPath, 24 * 1024);
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
logger.warn(`[OwnerDirectory] discoverDevice: failed to read contract: ${error instanceof Error ? error.message : String(error)}`);
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
if (contract.path !== ABILITY_PATH || contract.definition_id !== DEFINITION_ID
|
|
266
|
+
|| contract.idempotency !== 'keyed' || contract.require_confirm !== entry.require_confirm
|
|
267
|
+
|| contract.auth_required !== entry.auth_required || !isRecord(contract.params_schema)
|
|
268
|
+
|| JSON.stringify(contract.effects) !== JSON.stringify(entry.effects)) {
|
|
269
|
+
logger.warn(`[OwnerDirectory] discoverDevice: contract mismatch. contract.path=${contract.path}, contract.idempotency=${contract.idempotency}, require_confirm=${contract.require_confirm}/${entry.require_confirm}, auth_required=${contract.auth_required}/${entry.auth_required}, effects_match=${JSON.stringify(contract.effects) === JSON.stringify(entry.effects)}`);
|
|
270
|
+
throw new Error('Owner directory index and contract do not match');
|
|
271
|
+
}
|
|
272
|
+
const validate = new Ajv({ strict: false }).compile(contract.params_schema);
|
|
273
|
+
if (!validate(params)) {
|
|
274
|
+
logger.warn(`[OwnerDirectory] discoverDevice: params schema validation failed: ${JSON.stringify(validate.errors)}`);
|
|
275
|
+
throw new Error('Owner directory contract does not accept the authorization parameters');
|
|
276
|
+
}
|
|
277
|
+
const devices = entry.devices;
|
|
278
|
+
const selected = preferred && devices.includes(preferred) ? preferred : [...devices].sort()[0];
|
|
279
|
+
logger.info(`[OwnerDirectory] discoverDevice: selected device=${selected}`);
|
|
280
|
+
return selected;
|
|
281
|
+
}
|
|
282
|
+
async readPublishedJson(remotePath, maxBytes) {
|
|
283
|
+
const { bytes } = await readAuthoritativePersonalFsObject(this.options.client, remotePath, this.options.ownerAid, maxBytes);
|
|
284
|
+
const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes).replace(/^\uFEFF/, ''));
|
|
285
|
+
if (!isRecord(value))
|
|
286
|
+
throw new Error('Owner ability document must be a JSON object');
|
|
287
|
+
return value;
|
|
288
|
+
}
|
|
289
|
+
readAttempt() {
|
|
290
|
+
const value = atomicReadJson(this.statePath());
|
|
291
|
+
if (!isRecord(value) || value.schemaVersion !== 1 || value.selfAid !== this.options.selfAid
|
|
292
|
+
|| value.ownerAid !== this.options.ownerAid || typeof value.operationId !== 'string'
|
|
293
|
+
|| typeof value.callId !== 'string' || typeof value.deviceId !== 'string' || !Number.isSafeInteger(value.deadlineAt)
|
|
294
|
+
|| !['pending', 'initializing', 'retryable', 'denied', 'granted'].includes(String(value.status))
|
|
295
|
+
|| (value.action !== undefined && !['request', 'status'].includes(String(value.action)))
|
|
296
|
+
|| (value.retryAt !== undefined && !Number.isSafeInteger(value.retryAt)))
|
|
297
|
+
return undefined;
|
|
298
|
+
return value;
|
|
299
|
+
}
|
|
300
|
+
writeAttempt(attempt) {
|
|
301
|
+
fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
|
|
302
|
+
atomicWriteJson(this.statePath(), attempt);
|
|
303
|
+
fs.chmodSync(this.statePath(), 0o600);
|
|
304
|
+
}
|
|
305
|
+
statePath() { return path.join(this.options.directory, 'authorization-request.json'); }
|
|
306
|
+
}
|
|
307
|
+
function isRecord(value) {
|
|
308
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
309
|
+
}
|