evolcore 0.0.45 → 0.0.47
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 +113 -0
- package/bin/ecmsg.js +33 -23
- package/dist/ability/application-service.js +1 -2
- package/dist/ability/package.js +28 -0
- package/dist/agent-template/jobs.js +158 -36
- package/dist/agent-template/runtime.js +401 -34
- package/dist/agent-template/service.js +764 -369
- package/dist/agent-template/tool-runner.js +35 -17
- package/dist/agent-template/types.js +7 -4
- package/dist/agents/baseagent.js +10 -9
- package/dist/agents/claude-runner.js +22 -6
- package/dist/agents/codex/app-server-client.js +34 -27
- package/dist/agents/codex/diagnostics.js +18 -1
- package/dist/agents/codex-runner.js +3 -1
- package/dist/agents/ecagent-runner.js +3 -1
- package/dist/agents/gemini-runner.js +2 -1
- package/dist/aun/group/fs-download.js +1 -1
- package/dist/aun/menu/client.js +142 -182
- package/dist/aun/rpc/client.js +33 -17
- package/dist/aun/service-proxy.js +6 -23
- package/dist/channels/aun.js +675 -120
- package/dist/channels/daemon.js +1 -1
- package/dist/cli/agent-create.js +37 -10
- package/dist/cli/agent-template.js +105 -84
- package/dist/cli/agent.js +31 -18
- package/dist/cli/daemon-commands.js +42 -56
- package/dist/cli/daemon-lifecycle-client.js +55 -19
- package/dist/cli/directory.js +12 -4
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/events-command.js +2 -1
- package/dist/cli/init-channel.js +2 -2
- package/dist/cli/init.js +57 -21
- package/dist/cli/integrity-command.js +2 -0
- package/dist/cli/managed-command-guard.js +20 -1
- package/dist/cli/menu-client.js +7 -5
- package/dist/cli/restart-monitor.js +135 -46
- package/dist/cli/services-command.js +28 -5
- package/dist/cli/task-context.js +83 -15
- package/dist/cli/upgrade-command.js +4 -2
- package/dist/config/config-field-policy.js +24 -0
- package/dist/config/config-manager.js +49 -19
- package/dist/config/peer-book-store.js +167 -127
- package/dist/config/peer-role-resolver.js +24 -4
- package/dist/config/provider-identity-migration.js +158 -6
- package/dist/config/provider-identity.js +10 -4
- package/dist/config/provider-ipc-service.js +10 -2
- package/dist/config/provider-local-sync.js +2 -2
- package/dist/config/providers-config.js +95 -10
- package/dist/config/providers-import.js +4 -6
- package/dist/config/providers.js +14 -3
- package/dist/config/role-store.js +1 -1
- package/dist/config/schema-migration.js +123 -16
- package/dist/config/schema-registry.js +6 -2
- package/dist/config-store.js +9 -1
- package/dist/core/agent-application-service.js +56 -29
- package/dist/core/agent-create-status.js +3 -1
- package/dist/core/agent-creation-claim.js +1 -0
- package/dist/core/agent-ipc-registration.js +2 -2
- package/dist/core/agent-reload-coordinator.js +38 -1
- package/dist/core/agent-runtime.js +91 -43
- package/dist/core/auth/agent-delegation.js +13 -3
- package/dist/core/auth/delegation-diagnostics.js +56 -15
- package/dist/core/auth/operation-authorizer.js +2 -2
- package/dist/core/auth/operation-catalog.js +3 -3
- package/dist/core/bootstrap-service.js +3 -0
- package/dist/core/capability/capability-manager.js +3 -1
- package/dist/core/channel-loader.js +29 -3
- package/dist/core/channel-runtime.js +1 -1
- package/dist/core/command/agent-control.js +6 -5
- package/dist/core/command/agent-template-menu.js +32 -97
- package/dist/core/command/eventcenter-menu.js +61 -13
- package/dist/core/command/menu-catalog.js +11 -4
- package/dist/core/command/menu-handler.js +39 -12
- package/dist/core/command/menu-protocol.js +8 -16
- package/dist/core/command/skill-slash.js +6 -2
- package/dist/core/command/slash-handler.js +4 -6
- package/dist/core/command/team-workspace-bootstrap.js +1 -2
- package/dist/core/command/team-workspace-management-store.js +83 -0
- package/dist/core/command/team-workspace-management.js +1 -2
- package/dist/core/command/team-workspace-team.js +26 -3
- package/dist/core/daemon-bootstrap.js +11 -9
- package/dist/core/daemon-control.js +4 -7
- package/dist/core/daemon-lifecycle.js +189 -143
- package/dist/core/evolagent-registry.js +50 -2
- package/dist/core/evolagent.js +2 -1
- package/dist/core/file-integrity/read.js +9 -16
- package/dist/core/file-integrity/store.js +94 -34
- package/dist/core/handoff/dispatcher.js +33 -7
- package/dist/core/handoff/runtime.js +8 -0
- package/dist/core/host-snapshot.js +9 -4
- package/dist/core/inference/text-inference.js +12 -2
- package/dist/core/initialization/service.js +22 -4
- package/dist/core/invoke/invoke-service.js +24 -3
- package/dist/core/ipc-registration.js +7 -3
- package/dist/core/memory/consolidation.js +6 -6
- package/dist/core/message/aun-ipc-sender.js +109 -7
- package/dist/core/message/contact-admission.js +6 -2
- package/dist/core/message/message-bridge.js +13 -0
- package/dist/core/message/message-queue.js +131 -30
- package/dist/core/message/pending-hints.js +8 -0
- package/dist/core/message/response-engine.js +48 -2
- package/dist/core/message/send-routing.js +3 -12
- package/dist/core/model/catalog-service.js +13 -0
- package/dist/core/model/model-catalog.js +57 -18
- package/dist/core/ownership/owner-resolver.js +27 -10
- package/dist/core/pack-auth.js +163 -31
- package/dist/core/pack-install.js +42 -1
- package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
- package/dist/core/permission/ec-command-parser.js +3 -1
- package/dist/core/permission/shell-environment.js +23 -0
- package/dist/core/rate-window.js +6 -1
- package/dist/core/relation/peer-identity.js +5 -1
- package/dist/core/relation/same-owner-proof.js +2 -1
- package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
- package/dist/core/session/session-file-health.js +36 -7
- package/dist/core/session/session-idle-monitor.js +0 -1
- package/dist/core/session/session-manager.js +14 -0
- package/dist/core/session/session-title.js +26 -6
- package/dist/core/skill/index-generator.js +3 -4
- package/dist/core/task/task-image-resources.js +1 -1
- package/dist/core/thread/thread-service.js +0 -1
- package/dist/core/thread/topic-id.js +8 -0
- package/dist/directory/owner-directory-admission.js +17 -0
- package/dist/directory/owner-directory-cache.js +3 -1
- package/dist/directory/owner-directory-markdown.js +145 -23
- package/dist/directory/owner-directory-policy.js +23 -0
- package/dist/directory/owner-directory-query-operation.js +20 -6
- package/dist/directory/owner-directory-search.js +47 -0
- package/dist/eck/message-renderer.js +171 -32
- package/dist/ecweb/basic-settings-service.js +7 -3
- package/dist/ecweb/providers-service.js +17 -10
- package/dist/ecweb/runtime/lifecycle.js +65 -16
- package/dist/ecweb/runtime/supervisor.js +79 -50
- package/dist/event-center/admission-materializer.js +1 -1
- package/dist/event-center/bus-gate.js +48 -4
- package/dist/event-center/bus-host.js +3 -3
- package/dist/event-center/center-config.js +57 -28
- package/dist/event-center/dispatcher.js +8 -0
- package/dist/event-center/event-log.js +69 -27
- package/dist/event-center/index-generator.js +6 -1
- package/dist/event-center/ipc-operation.js +66 -25
- package/dist/event-center/pack-loader.js +12 -55
- package/dist/event-center/pack-manager.js +5 -3
- package/dist/event-center/registry.js +48 -52
- package/dist/event-center/runtime.js +219 -81
- package/dist/event-center/script-runner.js +18 -7
- package/dist/event-center/types.js +9 -1
- package/dist/event-center/validation.js +33 -4
- package/dist/index.js +132 -75
- package/dist/ipc.js +35 -8
- package/dist/product.js +1 -0
- package/dist/proxy/manager.js +52 -11
- package/dist/proxy/service-supervisor.js +265 -67
- package/dist/services/dispatcher.js +26 -3
- package/dist/services/idempotency.js +128 -0
- package/dist/services/identity.js +3 -27
- package/dist/services/index-generator.js +5 -1
- package/dist/services/index.js +244 -45
- package/dist/services/ipc-operation.js +164 -20
- package/dist/services/pack-manager.js +37 -9
- package/dist/services/router.js +100 -31
- package/dist/services/script-runner.js +15 -4
- package/dist/services/service-payload.js +50 -2
- package/dist/services/validation.js +107 -3
- package/dist/trigger/scheduler.js +18 -4
- package/dist/trigger/script-sandbox.js +39 -2
- package/dist/trigger/state.js +7 -0
- package/dist/utils/aid-bind.js +155 -18
- package/dist/utils/atomic-write.js +3 -3
- package/dist/utils/cross-platform.js +59 -16
- package/dist/utils/error-utils.js +26 -1
- package/dist/utils/instance-registry.js +94 -35
- package/dist/utils/process-introspect.js +187 -27
- package/dist/utils/project-path.js +47 -3
- package/dist/utils/upgrade-jobs.js +4 -4
- package/dist/utils/windows-shell-trust.js +174 -68
- package/kits/docs/context-assembly.md +3 -3
- package/kits/docs/evolcore/agent.md +28 -10
- package/kits/docs/evolcore/aid.md +3 -1
- package/kits/docs/evolcore/config.md +22 -0
- package/kits/docs/evolcore/directory.md +46 -12
- package/kits/docs/evolcore/event-center.md +6 -6
- package/kits/docs/evolcore/group-collaboration.md +1 -1
- package/kits/docs/evolcore/menu-client.md +7 -5
- package/kits/docs/evolcore/menu-protocol.md +5 -3
- package/kits/docs/evolcore/msg.md +10 -3
- package/kits/docs/evolcore/provider.md +17 -5
- package/kits/docs/evolcore/services.md +145 -12
- package/kits/docs/evolcore/thread-chain.md +17 -9
- package/kits/docs/prompt-loading-architecture.md +4 -4
- package/kits/eck_message_manifest.json +46 -3
- package/kits/rules/04-relation.md +10 -2
- package/kits/rules/06-channel.md +2 -1
- package/kits/schemas/providers.schema.2.json +1 -0
- package/kits/skills/ec-group/SKILL.md +4 -0
- package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
- package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
- package/kits/skills/thread-ops/SKILL.md +8 -5
- package/kits/templates/message-fragments/group-batch-item.md +3 -0
- package/kits/templates/message-fragments/group-batch.md +1 -0
- package/kits/templates/message-fragments/item-group.md +4 -0
- package/kits/templates/message-fragments/item-private.md +4 -0
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/system-fragments/commands.md +5 -5
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +11 -7
- package/package.json +3 -2
- package/scripts/agent-template/index.mjs +9 -4
- package/scripts/agent-template/inspect.mjs +16 -9
- package/scripts/agent-template/shared/plan.mjs +3 -33
- package/scripts/agent-template/shared/template-contract.mjs +186 -3
- package/scripts/agent-template/shared/template-package.mjs +119 -10
- package/scripts/agent-template/shared/template-runtime.mjs +49 -6
- package/scripts/agent-template/shared/template.mjs +5 -5
- package/scripts/agent-template/team-pack.mjs +245 -0
- package/scripts/agent-template/team-preview.mjs +111 -0
- package/scripts/aid-batch/identity-batch.mjs +143 -0
- package/dist/ability/versions.js +0 -32
- package/dist/aun/model-headers.js +0 -17
- package/dist/channels/builtin-plugins.js +0 -19
- package/dist/core/command/team-workspace-initializer.js +0 -2
- package/dist/core/command/team-workspace-job-store.js +0 -88
- package/dist/core/command/team-workspace-management-service.js +0 -2
- package/dist/core/contact-bind-registry.js +0 -27
- package/dist/event-center/ledger.js +0 -52
- package/dist/services/reply.js +0 -55
- package/kits/templates/message-fragments/item.md +0 -3
- package/scripts/agent-template/pack.mjs +0 -169
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { inspectPackage } from './inspect.mjs';
|
|
4
|
+
import { assert, isRecord, unpack, jsonBytes, atomicBytes, sha256, regularPath } from './shared/common.mjs';
|
|
5
|
+
import { inspectTemplatePackage } from './shared/template-package.mjs';
|
|
6
|
+
|
|
7
|
+
export function readPackage(options) {
|
|
8
|
+
const checked = inspectTemplatePackage(fs.readFileSync(options.archivePath), { digest: options.digest });
|
|
9
|
+
return { metadata: { id: checked.metadata.id, name: checked.metadata.name, version: checked.metadata.version, description: checked.metadata.description, platforms: checked.metadata.compat.platforms }, members: Object.fromEntries(checked.team.agents.map(member => [member.key, member])), digest: checked.digest,
|
|
10
|
+
size: fs.statSync(options.archivePath).size, externalAids: checked.metadata.externalAids ?? [], scan: { findings: [] }, excluded: [] };
|
|
11
|
+
}
|
|
12
|
+
export async function previewInstallation(options) {
|
|
13
|
+
const bytes = fs.readFileSync(options.archivePath);
|
|
14
|
+
const checked = inspectTemplatePackage(bytes, { digest: options.digest });
|
|
15
|
+
assert(checked.team.host.platform.includes(process.platform), 'INCOMPATIBLE', 'Template does not support this platform');
|
|
16
|
+
const keys = checked.team.agents.map(member => member.key);
|
|
17
|
+
assert(isRecord(options.members) && keys.sort().join() === Object.keys(options.members).sort().join(), 'INVALID_ARGUMENT', 'Map every template member');
|
|
18
|
+
const root = path.join(options.out, 'package'); assert(!fs.existsSync(root), 'CONFLICT', 'Preview exists');
|
|
19
|
+
unpack(bytes, root); const targets = {};
|
|
20
|
+
for (const key of keys) {
|
|
21
|
+
const input = options.members[key];
|
|
22
|
+
assert(isRecord(input) && typeof input.aid === 'string' && path.isAbsolute(input.projectPath), 'INVALID_ARGUMENT', 'Agent and project required');
|
|
23
|
+
targets[key] = options.installMode === 'overwrite' ? options.targets[key] : {
|
|
24
|
+
home: options.home, targetAid: input.aid, targetConfig: { $schema_version: options.agentSchemaVersion, aid: input.aid,
|
|
25
|
+
enabled: true, lifecycle: 'ownerpending', channels: [], projects: { defaultPath: input.projectPath } },
|
|
26
|
+
projectPath: input.projectPath, ownerAid: options.ownerAid, hostAid: options.hostAid, providers: options.providers,
|
|
27
|
+
profile: {}, profileVersion: 'new-agent',
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const data = await inspectPackage({ packageDir: root, targets, members: options.selections,
|
|
31
|
+
packageRoot: options.packageRoot, out: options.out, digest: checked.digest,
|
|
32
|
+
planMode: options.installMode === 'create' ? 'create_on_host' : 'overlay_existing' });
|
|
33
|
+
const plan = JSON.parse(fs.readFileSync(data.planFile, 'utf8'));
|
|
34
|
+
const configs = {};
|
|
35
|
+
for (const member of plan.members) {
|
|
36
|
+
const write = plan.writes.find(item => item.path === path.join(options.home, 'agents', member.targetAid, 'config.json'));
|
|
37
|
+
assert(write, 'CONFLICT', 'Missing member configuration');
|
|
38
|
+
configs[member.key] = JSON.parse(Buffer.from(write.content, 'base64').toString('utf8'));
|
|
39
|
+
}
|
|
40
|
+
atomicBytes(path.join(options.out, 'source.ectpl'), bytes, 0o600);
|
|
41
|
+
return { ...data, configs, profiles: Object.fromEntries(plan.members.map(member => [member.key, member.profile])),
|
|
42
|
+
metadata: { id: checked.metadata.id, name: checked.metadata.name, version: checked.metadata.version, platforms: checked.metadata.compat.platforms }, digest: checked.digest, ignored: [], sourceDigest: sha256(bytes) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function applyInstallationPlan(options) {
|
|
46
|
+
const { overlay } = await import('./overlay.mjs');
|
|
47
|
+
const { snapshot } = await import('./shared/common.mjs');
|
|
48
|
+
const plan = JSON.parse(fs.readFileSync(options.planFile, 'utf8'));
|
|
49
|
+
const journalFile = path.join(options.backupDir, 'journal.json');
|
|
50
|
+
if (fs.existsSync(journalFile)) {
|
|
51
|
+
const prior = JSON.parse(fs.readFileSync(journalFile, 'utf8'));
|
|
52
|
+
if (prior.applied && !prior.restored) {
|
|
53
|
+
const final = JSON.parse(fs.readFileSync(path.join(path.dirname(options.planFile), 'creation-plan.json'), 'utf8'));
|
|
54
|
+
assert(final.writes.every(write => write.remove ? !fs.existsSync(write.path)
|
|
55
|
+
: fs.existsSync(write.path) && fs.readFileSync(write.path).equals(Buffer.from(write.content, 'base64'))), 'CONFLICT', 'Applied team resources changed');
|
|
56
|
+
return { applied: true, recovered: true };
|
|
57
|
+
}
|
|
58
|
+
const planned = JSON.parse(fs.readFileSync(path.join(path.dirname(options.planFile), 'creation-plan.json'), 'utf8'));
|
|
59
|
+
for (const entry of prior.entries) {
|
|
60
|
+
regularPath(entry.path);
|
|
61
|
+
const current = fs.existsSync(entry.path) ? fs.readFileSync(entry.path) : null;
|
|
62
|
+
const original = entry.existed ? fs.readFileSync(path.join(options.backupDir, entry.backup)) : null;
|
|
63
|
+
const write = planned.writes.find(value => value.path === entry.path);
|
|
64
|
+
assert(write, 'CONFLICT', 'Recovery journal has an unknown target');
|
|
65
|
+
const desired = write.remove ? null : Buffer.from(write.content, 'base64');
|
|
66
|
+
const equal = bytes => current === null ? bytes === null : bytes !== null && current.equals(bytes);
|
|
67
|
+
assert(equal(original) || equal(desired), 'CONFLICT', 'Interrupted team target was independently modified');
|
|
68
|
+
}
|
|
69
|
+
await overlay({ operation: 'restore', backupDir: options.backupDir });
|
|
70
|
+
fs.renameSync(options.backupDir, options.backupDir + '-restored-' + Date.now());
|
|
71
|
+
}
|
|
72
|
+
for (const write of plan.writes) {
|
|
73
|
+
if (!write.path.includes(path.sep + 'agents' + path.sep)) continue;
|
|
74
|
+
const member = plan.members.find(value => write.path.startsWith(path.join(plan.home, 'agents', value.targetAid) + path.sep));
|
|
75
|
+
assert(member, 'INVALID_ARGUMENT', 'Unexpected Agent write');
|
|
76
|
+
const expected = options.baselines?.[member.key]?.[write.path];
|
|
77
|
+
assert(expected !== undefined && JSON.stringify(snapshot(write.path)) === JSON.stringify(expected), 'CONFLICT', 'Prepared Agent changed');
|
|
78
|
+
write.expected = expected;
|
|
79
|
+
if (write.path === path.join(plan.home, 'agents', member.targetAid, 'config.json')) {
|
|
80
|
+
const config = JSON.parse(Buffer.from(write.content, 'base64').toString('utf8'));
|
|
81
|
+
const current = JSON.parse(fs.readFileSync(write.path, 'utf8'));
|
|
82
|
+
config.initialization = current.initialization;
|
|
83
|
+
config.lifecycle = 'ownerpending';
|
|
84
|
+
write.content = jsonBytes(config).toString('base64');
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const final = path.join(path.dirname(options.planFile), 'creation-plan.json');
|
|
88
|
+
atomicBytes(final, jsonBytes(plan), 0o600);
|
|
89
|
+
return await overlay({ planFile: final, backupDir: options.backupDir });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Compare all planned bytes after restart/activation; lifecycle is controlled by Core. */
|
|
93
|
+
export async function verifyInstallationPlan(options) {
|
|
94
|
+
const plan = JSON.parse(fs.readFileSync(path.join(path.dirname(options.planFile), 'creation-plan.json'), 'utf8'));
|
|
95
|
+
for (const write of plan.writes) {
|
|
96
|
+
if (write.remove) { assert(!fs.existsSync(write.path), 'CONFLICT', 'Removed team resource reappeared'); continue; }
|
|
97
|
+
regularPath(write.path);
|
|
98
|
+
assert(fs.existsSync(write.path), 'CONFLICT', 'Team resource is missing');
|
|
99
|
+
const bytes = fs.readFileSync(write.path);
|
|
100
|
+
const desired = Buffer.from(write.content, 'base64');
|
|
101
|
+
const config = plan.members.some(member => write.path === path.join(plan.home, 'agents', member.targetAid, 'config.json'));
|
|
102
|
+
if (config) {
|
|
103
|
+
const current = JSON.parse(bytes); const expected = JSON.parse(desired);
|
|
104
|
+
assert(['ownerpending', 'active'].includes(current.lifecycle), 'CONFLICT', 'Team lifecycle changed');
|
|
105
|
+
current.lifecycle = expected.lifecycle;
|
|
106
|
+
assert(JSON.stringify(current) === JSON.stringify(expected), 'CONFLICT', 'Team configuration changed');
|
|
107
|
+
} else assert(bytes.equals(desired), 'CONFLICT', 'Team resource changed');
|
|
108
|
+
if (process.platform !== 'win32') assert((fs.statSync(write.path).mode & 0o777) === write.mode, 'CONFLICT', 'Team resource permissions changed');
|
|
109
|
+
}
|
|
110
|
+
return { verified: true };
|
|
111
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/** Shared AID preparation kernel. No registry, Host creation, profiles, Core paths or SDK internals. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
export const AID_BATCH_CONTRACT_VERSION = 1;
|
|
5
|
+
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
+
const fail = (code, message, details) => { throw Object.assign(new Error(message), { code, ...(details ? { details } : {}) }); };
|
|
7
|
+
const stable = value => JSON.stringify(value, Object.keys(value).sort());
|
|
8
|
+
const fingerprint = value => createHash('sha256').update(stable(value)).digest('hex');
|
|
9
|
+
const aidPattern = /^[a-z0-9][a-z0-9_-]*\.(?:[a-z0-9-]+\.)*[a-z0-9-]+$/;
|
|
10
|
+
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
11
|
+
|
|
12
|
+
export function createMemoryAidCheckpoints() {
|
|
13
|
+
const entries = new Map();
|
|
14
|
+
return {
|
|
15
|
+
durable: false,
|
|
16
|
+
read: key => entries.has(key) ? structuredClone(entries.get(key)) : null,
|
|
17
|
+
write(key, next, expectedRevision) {
|
|
18
|
+
if ((entries.get(key)?.revision ?? null) !== expectedRevision) fail('CONFLICT', 'AID checkpoint revision changed');
|
|
19
|
+
entries.set(key, structuredClone(next));
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A pending Owner is a resumable result. Wrong identity/Owner/version is never accepted. */
|
|
25
|
+
export async function waitForAidConsensus({ subject, ownerAid, readConsensus, attempts = 20, delayMs = 500, wait = delay, signal }) {
|
|
26
|
+
if (!Number.isInteger(attempts) || attempts < 1 || attempts > 100 || typeof readConsensus !== 'function') fail('INVALID_ARGUMENT', 'Invalid consensus query');
|
|
27
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
28
|
+
signal?.throwIfAborted();
|
|
29
|
+
const view = await readConsensus();
|
|
30
|
+
if (view?.status === 'consensus') {
|
|
31
|
+
if (view.owner_aid !== ownerAid || view.sub_aid !== subject.aid || view.lock !== 'locked'
|
|
32
|
+
|| !Number.isSafeInteger(view.relation_version) || view.relation_version !== (subject.relationVersion ?? 1)) {
|
|
33
|
+
fail('OWNERSHIP_MISMATCH', 'Ownership consensus mismatch', { aid: subject.aid });
|
|
34
|
+
}
|
|
35
|
+
return structuredClone(view);
|
|
36
|
+
}
|
|
37
|
+
if (view?.owner_aid && view.owner_aid !== ownerAid) fail('OWNERSHIP_MISMATCH', 'Ownership belongs to another Owner', { aid: subject.aid });
|
|
38
|
+
if (attempt + 1 < attempts) await wait(delayMs);
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* transport: authorize,register,connect,bind,consensus,close; recover is mandatory on unknown results.
|
|
45
|
+
* Checkpoint persistence belongs to the caller; members mode requires a durable CAS implementation.
|
|
46
|
+
* register/bind receive stable requestId+operationId. A transport must query authoritative effects on recovery.
|
|
47
|
+
*/
|
|
48
|
+
export async function prepareAidBatch({ subjects, context, transport, checkpoints, concurrency = 1,
|
|
49
|
+
consensusAttempts = 20, consensusDelayMs = 500, wait = delay, signal } = {}) {
|
|
50
|
+
if (!record(context) || !['team', 'members'].includes(context.mode) || !aidPattern.test(context.ownerAid ?? '')
|
|
51
|
+
|| !aidPattern.test(context.hostAid ?? '') || typeof context.requestId !== 'string' || !context.requestId
|
|
52
|
+
|| !Array.isArray(subjects) || !subjects.length || !Number.isInteger(concurrency) || concurrency < 1 || concurrency > 32) fail('INVALID_ARGUMENT', 'Invalid AID batch context');
|
|
53
|
+
if (!checkpoints || typeof checkpoints.read !== 'function' || typeof checkpoints.write !== 'function'
|
|
54
|
+
|| context.mode === 'members' && checkpoints.durable !== true) fail('INVALID_ARGUMENT', 'Members mode requires durable AID checkpoints');
|
|
55
|
+
for (const method of ['authorize', 'register', 'connect', 'bind', 'consensus', 'close']) if (typeof transport?.[method] !== 'function') fail('INVALID_ARGUMENT', 'Missing identity transport: ' + method);
|
|
56
|
+
const aids = new Set(), keys = new Set();
|
|
57
|
+
for (const s of subjects) {
|
|
58
|
+
if (!record(s) || !/^[a-z0-9][a-z0-9_-]{0,31}$/.test(s.key ?? '') || !aidPattern.test(s.aid ?? '')
|
|
59
|
+
|| s.relationVersion !== undefined && (!Number.isSafeInteger(s.relationVersion) || s.relationVersion < 1)
|
|
60
|
+
|| !['agent', 'host'].includes(s.type) || aids.has(s.aid) || keys.has(s.key) || s.aid === context.ownerAid
|
|
61
|
+
|| context.mode === 'members' && (s.type !== 'agent' || s.aid === context.hostAid)
|
|
62
|
+
|| s.type === 'host' && s.aid !== context.hostAid) fail('INVALID_ARGUMENT', 'Invalid or duplicate identity subject');
|
|
63
|
+
aids.add(s.aid); keys.add(s.key);
|
|
64
|
+
}
|
|
65
|
+
const processSubject = async subject => {
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
const authorize = async () => {
|
|
68
|
+
const authorization = await transport.authorize(subject, context);
|
|
69
|
+
if (authorization?.ownerAid !== context.ownerAid || authorization?.hostAid !== context.hostAid) fail('NOT_ALLOWED', 'Trusted Owner/Host authorization required');
|
|
70
|
+
};
|
|
71
|
+
await authorize();
|
|
72
|
+
const identity = { aid: subject.aid, type: subject.type, ownerAid: context.ownerAid, hostAid: context.hostAid,
|
|
73
|
+
requestId: context.requestId + ':' + subject.key, relationVersion: subject.relationVersion ?? 1 };
|
|
74
|
+
const requestFingerprint = fingerprint(identity), key = identity.requestId;
|
|
75
|
+
let state = await checkpoints.read(key);
|
|
76
|
+
if (state && (state.fingerprint !== requestFingerprint || state.version !== AID_BATCH_CONTRACT_VERSION)) fail('CONFLICT', 'AID request already belongs to another identity');
|
|
77
|
+
const save = async patch => {
|
|
78
|
+
const revision = state?.revision ?? null;
|
|
79
|
+
const next = { ...(state ?? {}), ...structuredClone(patch), revision: (revision ?? -1) + 1 };
|
|
80
|
+
await checkpoints.write(key, next, revision);
|
|
81
|
+
state = next;
|
|
82
|
+
};
|
|
83
|
+
if (!state) await save({ version: AID_BATCH_CONTRACT_VERSION, fingerprint: requestFingerprint, ...identity,
|
|
84
|
+
operationId: randomUUID(), status: 'running', registration: 'not_started', binding: 'not_started' });
|
|
85
|
+
const operation = () => ({ requestId: state.requestId, operationId: state.operationId, ownerAid: context.ownerAid, hostAid: context.hostAid, signal });
|
|
86
|
+
const effect = async (field, action, client) => {
|
|
87
|
+
if (state[field] === 'confirmed') return;
|
|
88
|
+
if (['intent', 'unknown'].includes(state[field])) {
|
|
89
|
+
if (typeof transport.recover !== 'function') fail('RECOVERY_REQUIRED', 'Unknown ' + field + ' outcome requires authoritative recovery', { aid: subject.aid, requestId: state.requestId });
|
|
90
|
+
const recovered = await transport.recover(field, subject, state, operation());
|
|
91
|
+
if (recovered?.state === 'confirmed' && recovered.proven === true && recovered.operationId === state.operationId && recovered.fingerprint === state.fingerprint) { await save({ [field]: 'confirmed', status: 'running' }); return; }
|
|
92
|
+
if (recovered?.state !== 'not_started' || recovered.proven !== true || recovered.operationId !== state.operationId || recovered.fingerprint !== state.fingerprint) fail('RECOVERY_REQUIRED', 'Identity effect remains unknown', { aid: subject.aid, requestId: state.requestId });
|
|
93
|
+
await save({ [field]: 'not_started', status: 'running' });
|
|
94
|
+
}
|
|
95
|
+
signal?.throwIfAborted();
|
|
96
|
+
await authorize();
|
|
97
|
+
await save({ [field]: 'intent', status: 'running' });
|
|
98
|
+
try {
|
|
99
|
+
const result = await action(subject, client, operation());
|
|
100
|
+
if (result?.ok === false) throw Object.assign(new Error(result.error?.message ?? field + ' failed'), { code: result.error?.code });
|
|
101
|
+
await save({ [field]: 'confirmed', status: 'running' });
|
|
102
|
+
} catch (error) {
|
|
103
|
+
await save({ [field]: 'unknown', status: 'recovery_required', error: { code: error.code ?? 'UNKNOWN_EFFECT', phase: field } });
|
|
104
|
+
fail('RECOVERY_REQUIRED', field + ' result is unknown: ' + error.message, { aid: subject.aid, requestId: state.requestId });
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
await effect('registration', (s, _client, op) => transport.register(s, op));
|
|
108
|
+
let client, failure, result;
|
|
109
|
+
try {
|
|
110
|
+
signal?.throwIfAborted();
|
|
111
|
+
client = await transport.connect(subject, operation());
|
|
112
|
+
if (!client) fail('INVALID_IDENTITY', 'Subject connection required');
|
|
113
|
+
if (typeof client.getType === 'function' && client.getType() !== subject.type) fail('INVALID_IDENTITY', 'Subject type mismatch');
|
|
114
|
+
await effect('binding', (s, active, op) => transport.bind(s, active, op), client);
|
|
115
|
+
await authorize();
|
|
116
|
+
const consensus = await waitForAidConsensus({ subject, ownerAid: context.ownerAid, attempts: consensusAttempts,
|
|
117
|
+
delayMs: consensusDelayMs, wait, signal, readConsensus: () => transport.consensus(subject, client, operation()) });
|
|
118
|
+
if (!consensus) {
|
|
119
|
+
await save({ status: 'awaiting_owner' });
|
|
120
|
+
result = { key: subject.key, aid: subject.aid, status: 'awaiting_owner', requestId: state.requestId, operationId: state.operationId };
|
|
121
|
+
} else {
|
|
122
|
+
await save({ status: 'ready', consensus });
|
|
123
|
+
result = { key: subject.key, aid: subject.aid, status: 'ready', requestId: state.requestId, operationId: state.operationId, consensus };
|
|
124
|
+
}
|
|
125
|
+
} catch (error) { failure = error; }
|
|
126
|
+
finally {
|
|
127
|
+
if (client) try { await transport.close(client, subject); }
|
|
128
|
+
catch (error) { failure ??= error; }
|
|
129
|
+
}
|
|
130
|
+
if (failure) throw failure;
|
|
131
|
+
return result;
|
|
132
|
+
};
|
|
133
|
+
const results = new Array(subjects.length);
|
|
134
|
+
let cursor = 0, failure;
|
|
135
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, subjects.length) }, async () => {
|
|
136
|
+
while (!failure && cursor < subjects.length) {
|
|
137
|
+
const index = cursor++;
|
|
138
|
+
try { results[index] = await processSubject(subjects[index]); } catch (error) { failure ??= error; }
|
|
139
|
+
}
|
|
140
|
+
}));
|
|
141
|
+
if (failure) throw failure;
|
|
142
|
+
return { status: results.every(result => result.status === 'ready') ? 'ready' : 'awaiting_owner', subjects: results };
|
|
143
|
+
}
|
package/dist/ability/versions.js
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'node:module';
|
|
2
|
-
import canonicalize from 'canonicalize';
|
|
3
|
-
import { abilityAssert } from './types.js';
|
|
4
|
-
const semver = createRequire(import.meta.url)('semver');
|
|
5
|
-
export const sameJson = (a, b) => canonicalize(a) === canonicalize(b);
|
|
6
|
-
export const dataVersion = (pkg) => pkg.manifest.data?.schemaVersion ?? 1;
|
|
7
|
-
export function versionImpact(instance, previous, candidate) {
|
|
8
|
-
const oldPaths = previous.definitions.map(row => String(row.definition.path));
|
|
9
|
-
const newPaths = candidate.definitions.map(row => String(row.definition.path));
|
|
10
|
-
const changedPaths = newPaths.filter(path => {
|
|
11
|
-
const old = previous.definitions.find(row => row.definition.path === path);
|
|
12
|
-
return old && !sameJson(old, candidate.definitions.find(row => row.definition.path === path));
|
|
13
|
-
});
|
|
14
|
-
return {
|
|
15
|
-
fromVersion: previous.manifest.version, toVersion: candidate.manifest.version,
|
|
16
|
-
downgrade: semver.lt(candidate.manifest.version, previous.manifest.version), samePackage: previous.digest === candidate.digest,
|
|
17
|
-
addedPaths: newPaths.filter(path => !oldPaths.includes(path)), removedPaths: oldPaths.filter(path => !newPaths.includes(path)), changedPaths,
|
|
18
|
-
contracts: changedPaths.map(path => ({ path, before: previous.definitions.find(row => row.definition.path === path), after: candidate.definitions.find(row => row.definition.path === path) })),
|
|
19
|
-
configSchemaChanged: !sameJson(previous.configSchema, candidate.configSchema),
|
|
20
|
-
configuration: { before: previous.configSchema, after: candidate.configSchema },
|
|
21
|
-
permissionsChanged: !sameJson(previous.manifest.permissions, candidate.manifest.permissions),
|
|
22
|
-
permissions: { before: previous.manifest.permissions, after: candidate.manifest.permissions },
|
|
23
|
-
data: { fromVersion: dataVersion(previous), toVersion: dataVersion(candidate), migrationRequired: dataVersion(previous) !== dataVersion(candidate) },
|
|
24
|
-
invalidatedGrantIds: instance.grants.filter(grant => grant.permission === 'remote-call' && !grant.revokedAt).map(grant => grant.id),
|
|
25
|
-
externalDataWarning: instance.grants.some(grant => grant.permission === 'workspace' && !grant.revokedAt
|
|
26
|
-
&& (grant.expiresAt ?? 0) > Date.now() && grant.issuedByAid === instance.approvedByAid && grant.value.mode === 'read-write'),
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
export function assertPackageVersion(store, candidate) {
|
|
30
|
-
for (const previous of store.list('package'))
|
|
31
|
-
abilityAssert(previous.manifest.id !== candidate.manifest.id || previous.manifest.version !== candidate.manifest.version || previous.digest === candidate.digest, 'VERSION_CONTENT_CONFLICT', 'A plugin version already identifies different content on this host; publish a new version', 409);
|
|
32
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
/** Per-message authenticated metadata. Never read the Agent's mutable model here:
|
|
2
|
-
* an in-flight turn must keep its model even after a configuration change. */
|
|
3
|
-
export function aunProtectedHeaders(context) {
|
|
4
|
-
const headers = {};
|
|
5
|
-
const raw = context?.metadata?.protectedHeaders;
|
|
6
|
-
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
7
|
-
for (const [key, value] of Object.entries(raw)) {
|
|
8
|
-
const name = key.trim().toLowerCase();
|
|
9
|
-
if (/^[a-z0-9_-]+$/.test(name) && typeof value === 'string')
|
|
10
|
-
headers[name] = value;
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
const model = context?.model?.trim();
|
|
14
|
-
if (model)
|
|
15
|
-
headers.model = model;
|
|
16
|
-
return Object.keys(headers).length > 0 ? headers : undefined;
|
|
17
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { AUNChannelPlugin } from './aun.js';
|
|
2
|
-
export async function registerBuiltinChannelPlugins(channelLoader) {
|
|
3
|
-
channelLoader.register(new AUNChannelPlugin());
|
|
4
|
-
const providers = [
|
|
5
|
-
['feishu', async () => new (await import('./feishu.js')).FeishuChannelPlugin()],
|
|
6
|
-
['wechat', async () => new (await import('./wechat.js')).WechatChannelPlugin()],
|
|
7
|
-
['dingtalk', async () => new (await import('./dingtalk.js')).DingtalkChannelPlugin()],
|
|
8
|
-
['qqbot', async () => new (await import('./qqbot.js')).QQBotChannelPlugin()],
|
|
9
|
-
['wecom', async () => new (await import('./wecom.js')).WecomChannelPlugin()],
|
|
10
|
-
];
|
|
11
|
-
for (const [channelType, load] of providers) {
|
|
12
|
-
try {
|
|
13
|
-
channelLoader.register(await load());
|
|
14
|
-
}
|
|
15
|
-
catch (error) {
|
|
16
|
-
channelLoader.recordProviderFailure(channelType, error);
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
}
|
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import path from 'node:path';
|
|
2
|
-
import crypto from 'node:crypto';
|
|
3
|
-
import { agentDataDir } from '../../paths.js';
|
|
4
|
-
import { atomicReadJson, atomicWriteJson } from '../../utils/atomic-write.js';
|
|
5
|
-
import { isValidAid } from '../../aun/aid/validation.js';
|
|
6
|
-
export class TeamWorkspaceJobError extends Error {
|
|
7
|
-
code;
|
|
8
|
-
constructor(code, message) {
|
|
9
|
-
super(message);
|
|
10
|
-
this.code = code;
|
|
11
|
-
this.name = 'TeamWorkspaceJobError';
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
const JOB_FILE = 'team-workspace-jobs-v1.json';
|
|
15
|
-
const JOB_TTL_MS = 24 * 60 * 60 * 1000;
|
|
16
|
-
function jobPath(agentAid) { return path.join(agentDataDir(agentAid), JOB_FILE); }
|
|
17
|
-
export class TeamWorkspaceJobStore {
|
|
18
|
-
now;
|
|
19
|
-
constructor(now = () => Date.now()) {
|
|
20
|
-
this.now = now;
|
|
21
|
-
}
|
|
22
|
-
create(input) {
|
|
23
|
-
if (!isValidAid(input.agentAid) || !isValidAid(input.ownerAid) || !isValidAid(input.principalId)) {
|
|
24
|
-
throw new TeamWorkspaceJobError('INVALID_ARGUMENT', 'Invalid Team workspace job identity');
|
|
25
|
-
}
|
|
26
|
-
const now = this.now();
|
|
27
|
-
const jobs = this.readAll(input.agentAid).filter(job => job.expiresAt > now);
|
|
28
|
-
const existing = jobs.find(job => job.operationId === input.operationId);
|
|
29
|
-
if (existing) {
|
|
30
|
-
if (existing.fingerprint !== input.fingerprint || existing.principalId !== input.principalId) {
|
|
31
|
-
throw new TeamWorkspaceJobError('OPERATION_ID_REUSED', 'operationId was already used with different arguments');
|
|
32
|
-
}
|
|
33
|
-
return existing;
|
|
34
|
-
}
|
|
35
|
-
const job = {
|
|
36
|
-
...input,
|
|
37
|
-
jobId: `teamj_${crypto.randomBytes(18).toString('base64url')}`,
|
|
38
|
-
status: 'accepted', progress: 0, createdAt: now, updatedAt: now, expiresAt: now + JOB_TTL_MS,
|
|
39
|
-
};
|
|
40
|
-
this.writeAll(input.agentAid, [...jobs, job]);
|
|
41
|
-
return job;
|
|
42
|
-
}
|
|
43
|
-
update(agentAid, jobId, patch) {
|
|
44
|
-
const jobs = this.readAll(agentAid);
|
|
45
|
-
const index = jobs.findIndex(job => job.jobId === jobId);
|
|
46
|
-
if (index < 0)
|
|
47
|
-
throw new TeamWorkspaceJobError('JOB_EXPIRED', 'Team workspace job is no longer available');
|
|
48
|
-
const job = { ...jobs[index], ...patch, updatedAt: this.now() };
|
|
49
|
-
jobs[index] = job;
|
|
50
|
-
this.writeAll(agentAid, jobs);
|
|
51
|
-
return job;
|
|
52
|
-
}
|
|
53
|
-
get(agentAid, jobId, principalId) {
|
|
54
|
-
const job = this.readAll(agentAid).find(candidate => candidate.jobId === jobId);
|
|
55
|
-
if (!job || job.expiresAt <= this.now())
|
|
56
|
-
throw new TeamWorkspaceJobError('JOB_EXPIRED', 'Team workspace job is no longer available');
|
|
57
|
-
if (job.principalId !== principalId)
|
|
58
|
-
throw new TeamWorkspaceJobError('FORBIDDEN', 'Team workspace job belongs to another principal');
|
|
59
|
-
return job;
|
|
60
|
-
}
|
|
61
|
-
readAll(agentAid) {
|
|
62
|
-
try {
|
|
63
|
-
const value = atomicReadJson(jobPath(agentAid));
|
|
64
|
-
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
65
|
-
return [];
|
|
66
|
-
const jobs = value.jobs;
|
|
67
|
-
return Array.isArray(jobs) ? jobs.filter(job => this.validJob(job)) : [];
|
|
68
|
-
}
|
|
69
|
-
catch {
|
|
70
|
-
return [];
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
writeAll(agentAid, jobs) {
|
|
74
|
-
atomicWriteJson(jobPath(agentAid), { version: 1, jobs: jobs.slice(-100) });
|
|
75
|
-
}
|
|
76
|
-
validJob(value) {
|
|
77
|
-
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
78
|
-
return false;
|
|
79
|
-
const job = value;
|
|
80
|
-
return typeof job.jobId === 'string' && typeof job.operationId === 'string'
|
|
81
|
-
&& typeof job.fingerprint === 'string' && isValidAid(String(job.agentAid))
|
|
82
|
-
&& isValidAid(String(job.ownerAid)) && isValidAid(String(job.principalId))
|
|
83
|
-
&& job.type === 'initialize'
|
|
84
|
-
&& ['accepted', 'running', 'succeeded', 'failed', 'expired'].includes(String(job.status))
|
|
85
|
-
&& Number.isFinite(job.createdAt) && Number.isFinite(job.updatedAt) && Number.isFinite(job.expiresAt);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
export const teamWorkspaceJobStore = new TeamWorkspaceJobStore();
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/** Public Phase 2 entry point; kept separate for App/Core integration imports. */
|
|
2
|
-
export { TeamWorkspaceManagementService, TEAM_WORKSPACE_MANAGEMENT_PROTOCOL, TEAM_WORKSPACE_MANAGEMENT_VERSION, scanWorkspaceStatistics, teamWorkspaceManagementService, } from './team-workspace-management.js';
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
export class ContactBindRegistry {
|
|
2
|
-
providers = new Map();
|
|
3
|
-
register(channelType, provider) {
|
|
4
|
-
const normalizedType = channelType.trim().toLowerCase();
|
|
5
|
-
if (!normalizedType)
|
|
6
|
-
throw new Error('Contact-bind channel type must not be empty');
|
|
7
|
-
if (this.providers.has(normalizedType)) {
|
|
8
|
-
throw new Error(`Contact-bind provider '${normalizedType}' already registered`);
|
|
9
|
-
}
|
|
10
|
-
this.providers.set(normalizedType, provider);
|
|
11
|
-
}
|
|
12
|
-
get(channelType) {
|
|
13
|
-
return this.providers.get(channelType.trim().toLowerCase());
|
|
14
|
-
}
|
|
15
|
-
channelTypes() {
|
|
16
|
-
return [...this.providers.keys()];
|
|
17
|
-
}
|
|
18
|
-
handle(channelType, context) {
|
|
19
|
-
return this.get(channelType)?.handle(context) ?? { handled: false };
|
|
20
|
-
}
|
|
21
|
-
registerPending(channelType, request) {
|
|
22
|
-
const provider = this.get(channelType);
|
|
23
|
-
return provider
|
|
24
|
-
? provider.register(request)
|
|
25
|
-
: { ok: false, error: `contact bind provider not configured for channel '${channelType}'` };
|
|
26
|
-
}
|
|
27
|
-
}
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 台账(ledger.jsonl / .center-ledger.jsonl):append-only,只记生命周期,不记事件正文。
|
|
3
|
-
* 行结构按 docs/event-center/schema/ledger.schema.json(additionalProperties: false)。
|
|
4
|
-
*/
|
|
5
|
-
import fs from 'node:fs';
|
|
6
|
-
import path from 'node:path';
|
|
7
|
-
export class Ledger {
|
|
8
|
-
filePath;
|
|
9
|
-
constructor(filePath) {
|
|
10
|
-
this.filePath = filePath;
|
|
11
|
-
}
|
|
12
|
-
/** 追加一行;IO 失败吞掉(台账不应中断运行时)。 */
|
|
13
|
-
append(line) {
|
|
14
|
-
const { ts, action, ...rest } = line;
|
|
15
|
-
const full = { ts: ts ?? Date.now(), action, ...rest };
|
|
16
|
-
try {
|
|
17
|
-
fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
|
|
18
|
-
fs.appendFileSync(this.filePath, `${JSON.stringify(full)}\n`, 'utf8');
|
|
19
|
-
}
|
|
20
|
-
catch {
|
|
21
|
-
// 台账写失败不致命:运行继续,`ec events ledger` 读不到时再排查磁盘。
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
/** 读最后 N 行(CLI tail 用)。 */
|
|
25
|
-
tail(count) {
|
|
26
|
-
let text;
|
|
27
|
-
try {
|
|
28
|
-
text = fs.readFileSync(this.filePath, 'utf8');
|
|
29
|
-
}
|
|
30
|
-
catch {
|
|
31
|
-
return [];
|
|
32
|
-
}
|
|
33
|
-
const lines = text.split('\n').filter(Boolean).slice(-count);
|
|
34
|
-
const out = [];
|
|
35
|
-
for (const line of lines) {
|
|
36
|
-
try {
|
|
37
|
-
out.push(JSON.parse(line));
|
|
38
|
-
}
|
|
39
|
-
catch {
|
|
40
|
-
// 跳过坏行
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return out;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
export function packLedger(pack) {
|
|
47
|
-
return new Ledger(pack.paths.ledger);
|
|
48
|
-
}
|
|
49
|
-
/** center 级动作(bus.start / bus.stop / allowlist.update)的台账,放 events/ 根。 */
|
|
50
|
-
export function centerLedger(eventsDir) {
|
|
51
|
-
return new Ledger(path.join(eventsDir, '.center-ledger.jsonl'));
|
|
52
|
-
}
|
package/dist/services/reply.js
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 回复构造:脚本只决定「回什么」,daemon 决定「怎么发」。
|
|
3
|
-
*
|
|
4
|
-
* 回复 type 一律是「请求 type + .result」;脚本不能指定 type(reply.payloadTypes
|
|
5
|
-
* 只是允许派生出的形状,当前唯一合法值是 service-result)。失败信息放 error.code。
|
|
6
|
-
*/
|
|
7
|
-
import { resultTypeFor } from './service-payload.js';
|
|
8
|
-
/** 成功:{type, request_id, ok:true, data}。 */
|
|
9
|
-
export function buildSuccessReply(requestType, requestId, data) {
|
|
10
|
-
const type = resultTypeFor(requestType);
|
|
11
|
-
return {
|
|
12
|
-
type,
|
|
13
|
-
requestId,
|
|
14
|
-
shouldSend: true,
|
|
15
|
-
payload: {
|
|
16
|
-
type,
|
|
17
|
-
request_id: requestId,
|
|
18
|
-
ok: true,
|
|
19
|
-
...(data !== undefined ? { data } : {}),
|
|
20
|
-
},
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
/** 失败:{type, request_id, ok:false, error:{code,message}}。 */
|
|
24
|
-
export function buildErrorReply(requestType, requestId, code, message, extra) {
|
|
25
|
-
const type = resultTypeFor(requestType);
|
|
26
|
-
return {
|
|
27
|
-
type,
|
|
28
|
-
requestId: requestId ?? '',
|
|
29
|
-
shouldSend: true,
|
|
30
|
-
payload: {
|
|
31
|
-
type,
|
|
32
|
-
request_id: requestId,
|
|
33
|
-
ok: false,
|
|
34
|
-
error: { code, message },
|
|
35
|
-
...(extra ?? {}),
|
|
36
|
-
},
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
/** 静默:不回,调用方只能等到超时(blocked / unmatched=silent / 总闸关闭)。 */
|
|
40
|
-
export function buildSilentReply(requestType, requestId) {
|
|
41
|
-
return {
|
|
42
|
-
type: resultTypeFor(requestType),
|
|
43
|
-
requestId,
|
|
44
|
-
shouldSend: false,
|
|
45
|
-
payload: {},
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
/** 脚本执行结果 → 回复。noop 不回。 */
|
|
49
|
-
export function replyFromOutcome(requestType, requestId, outcome) {
|
|
50
|
-
if (outcome.outcome === 'noop')
|
|
51
|
-
return buildSilentReply(requestType, requestId);
|
|
52
|
-
if (outcome.outcome === 'success')
|
|
53
|
-
return buildSuccessReply(requestType, requestId, outcome.data);
|
|
54
|
-
return buildErrorReply(requestType, requestId, outcome.error?.code ?? 'HANDLER_FAILED', outcome.error?.message ?? 'service handler failed');
|
|
55
|
-
}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
‹{{now}} · from:{{peerId}}{{?peerName}}({{peerName}}){{/}}{{?selfAddressed}} · 跨话题自派{{/}}{{?peerRole}} · role:{{peerRole}}{{/}}{{?chatType=group}} → 群:{{groupLabel}} · self:{{selfAid}}{{/}}{{?chatType=private}} → self:{{selfAid}}{{/}}{{?chatMode=proactive}} · chatMode:proactive{{/}}{{?chatMode=interactive}} · chatMode:interactive{{/}}{{?sameDevice}} · 📍同设备{{/}}{{?sameNetwork}} · 🌐同网络{{/}}{{?sameEgressIp}} · 🔀同出口IP{{/}}{{?mentionAids}} · @:{{mentionAids}}{{/}}›
|
|
2
|
-
{{?lifecycle=bootstrapping}}(本轮只推进首次设定:按 Owner 这条回复更新名片和头像,然后完成激活;回复里的普通任务记为激活后待办,不在本轮执行。)
|
|
3
|
-
{{/}}{{?isHandoff!=true}}{{content}}{{/}}
|