evolcore 0.0.43-test.6 → 0.0.43-test.7

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.
Files changed (197) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/bin/ecmsg.js +171 -54
  3. package/dist/agents/baseagent-availability.js +1 -1
  4. package/dist/agents/codex/app-server-client.js +22 -0
  5. package/dist/agents/codex-runner.js +69 -2
  6. package/dist/aun/msg/p2p.js +6 -1
  7. package/dist/channels/aun.js +234 -21
  8. package/dist/cli/agent-create.js +2 -2
  9. package/dist/cli/daemon-commands.js +6 -66
  10. package/dist/cli/daemon-lifecycle-client.js +61 -0
  11. package/dist/cli/ecmsg-gateway.js +35 -2
  12. package/dist/cli/events-command.js +73 -0
  13. package/dist/cli/index.js +31 -14
  14. package/dist/cli/invoke-command.js +182 -0
  15. package/dist/cli/managed-command-guard.js +6 -1
  16. package/dist/cli/restart-monitor.js +45 -47
  17. package/dist/cli/services-command.js +111 -0
  18. package/dist/cli/team-workspace-command.js +134 -0
  19. package/dist/cli/thread-command.js +6 -2
  20. package/dist/cli/watch-msg.js +1 -1
  21. package/dist/config/config-field-policy.js +2 -2
  22. package/dist/config/config-manager.js +0 -7
  23. package/dist/config/invoke-ipc-service.js +118 -0
  24. package/dist/config/schema-migration.js +6 -1
  25. package/dist/config-store.js +2 -1
  26. package/dist/core/agent-reload-coordinator.js +6 -4
  27. package/dist/core/agent-runtime.js +104 -10
  28. package/dist/core/auth/delegation-authorization.js +66 -0
  29. package/dist/core/auth/operation-catalog.js +20 -0
  30. package/dist/core/baseagent-loader.js +60 -130
  31. package/dist/core/channel-loader.js +10 -1
  32. package/dist/core/channel-runtime.js +4 -3
  33. package/dist/core/command/agent-control.js +1 -1
  34. package/dist/core/command/agent-storage-menu.js +1 -1
  35. package/dist/core/command/chatmode-config.js +2 -36
  36. package/dist/core/command/command-handler.js +53 -11
  37. package/dist/core/command/data-root-resolver.js +32 -23
  38. package/dist/core/command/eventcenter-menu.js +338 -0
  39. package/dist/core/command/menu-catalog.js +8 -0
  40. package/dist/core/command/menu-handler.js +198 -84
  41. package/dist/core/command/menu-protocol.js +60 -11
  42. package/dist/core/command/menu-query-batch.js +194 -0
  43. package/dist/core/command/slash-gate.js +1 -1
  44. package/dist/core/command/slash-handler.js +34 -42
  45. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  46. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  47. package/dist/core/command/team-workspace-initializer.js +2 -0
  48. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  49. package/dist/core/command/team-workspace-job-store.js +88 -0
  50. package/dist/core/command/team-workspace-management-service.js +2 -0
  51. package/dist/core/command/team-workspace-management-store.js +96 -0
  52. package/dist/core/command/team-workspace-management.js +265 -0
  53. package/dist/core/command/team-workspace-members-menu.js +88 -0
  54. package/dist/core/command/team-workspace-store.js +612 -0
  55. package/dist/core/command/team-workspace-team.js +193 -0
  56. package/dist/core/daemon-control.js +8 -5
  57. package/dist/core/daemon-lifecycle.js +132 -73
  58. package/dist/core/handoff/runtime.js +3 -3
  59. package/dist/core/invoke/executors/index.js +13 -0
  60. package/dist/core/invoke/executors/media.js +283 -0
  61. package/dist/core/invoke/executors/text.js +198 -0
  62. package/dist/core/invoke/invoke-service.js +157 -0
  63. package/dist/core/invoke/style-router.js +48 -0
  64. package/dist/core/invoke/types.js +19 -0
  65. package/dist/core/ipc-registration.js +46 -7
  66. package/dist/core/memory/consolidation.js +7 -5
  67. package/dist/core/message/aun-ipc-sender.js +147 -17
  68. package/dist/core/message/im-renderer.js +28 -84
  69. package/dist/core/message/message-bridge.js +4 -0
  70. package/dist/core/message/message-utils.js +10 -2
  71. package/dist/core/message/peer-mode.js +7 -34
  72. package/dist/core/message/response-engine.js +157 -54
  73. package/dist/core/message/send-options.js +7 -4
  74. package/dist/core/message/send-routing.js +43 -5
  75. package/dist/core/ownership/owner-resolver.js +7 -0
  76. package/dist/core/permission/ec-command-parser.js +3 -2
  77. package/dist/core/permission/protected-paths.js +12 -2
  78. package/dist/core/permission/shell-environment.js +9 -0
  79. package/dist/core/session/session-file-health.js +243 -0
  80. package/dist/core/session/session-fs-store.js +2 -3
  81. package/dist/core/task/task-recovery-service.js +13 -2
  82. package/dist/core/thread/command-parser.js +9 -2
  83. package/dist/core/thread/thread-operation.js +21 -2
  84. package/dist/core/thread/thread-route.js +13 -2
  85. package/dist/directory/owner-directory-admission.js +40 -53
  86. package/dist/directory/owner-directory-cache.js +89 -113
  87. package/dist/directory/owner-directory-query-operation.js +8 -10
  88. package/dist/eck/kit-renderer.js +7 -5
  89. package/dist/ecweb/basic-settings-service.js +1 -1
  90. package/dist/ecweb/message-context-service.js +0 -4
  91. package/dist/ecweb/runtime/lifecycle.js +6 -2
  92. package/dist/ecweb/runtime/supervisor.js +19 -4
  93. package/dist/event-center/admission-materializer.js +114 -0
  94. package/dist/event-center/bus-gate.js +136 -0
  95. package/dist/event-center/bus-host.js +290 -0
  96. package/dist/event-center/bus-resolver.js +120 -0
  97. package/dist/event-center/center-config.js +100 -0
  98. package/dist/event-center/client-factory.js +50 -0
  99. package/dist/event-center/daemon.js +45 -0
  100. package/dist/event-center/directory-source.js +53 -0
  101. package/dist/event-center/dispatcher.js +157 -0
  102. package/dist/event-center/event-log.js +110 -0
  103. package/dist/event-center/index-generator.js +63 -0
  104. package/dist/event-center/ipc-operation.js +308 -0
  105. package/dist/event-center/ledger.js +52 -0
  106. package/dist/event-center/pack-loader.js +202 -0
  107. package/dist/event-center/pack-manager.js +85 -0
  108. package/dist/event-center/registry.js +238 -0
  109. package/dist/event-center/runtime.js +641 -0
  110. package/dist/event-center/script-runner.js +356 -0
  111. package/dist/event-center/types.js +35 -0
  112. package/dist/event-center/validation.js +413 -0
  113. package/dist/index.js +285 -99
  114. package/dist/ipc.js +66 -12
  115. package/dist/paths.js +20 -0
  116. package/dist/product.js +14 -0
  117. package/dist/proxy/manager.js +5 -1
  118. package/dist/proxy/service-supervisor.js +13 -4
  119. package/dist/response-system/engines/v1/index.js +0 -1
  120. package/dist/response-system/modes/single-session/index.js +1 -1
  121. package/dist/services/dispatcher.js +100 -0
  122. package/dist/services/idempotency.js +90 -0
  123. package/dist/services/identity.js +52 -0
  124. package/dist/services/index-generator.js +70 -0
  125. package/dist/services/index.js +449 -0
  126. package/dist/services/ipc-operation.js +458 -0
  127. package/dist/services/ledger.js +52 -0
  128. package/dist/services/message-log.js +112 -0
  129. package/dist/services/pack-manager.js +204 -0
  130. package/dist/services/reply.js +55 -0
  131. package/dist/services/router.js +95 -0
  132. package/dist/services/script-runner.js +422 -0
  133. package/dist/services/service-payload.js +70 -0
  134. package/dist/services/types.js +18 -0
  135. package/dist/services/validation.js +297 -0
  136. package/dist/trigger/application-service.js +18 -0
  137. package/dist/trigger/event-source.js +1 -1
  138. package/dist/trigger/ipc-service.js +3 -1
  139. package/dist/trigger/script-sandbox.js +118 -22
  140. package/dist/utils/cross-platform.js +24 -10
  141. package/dist/utils/evolcore-version.js +69 -27
  142. package/dist/utils/instance-registry.js +19 -13
  143. package/dist/utils/process-introspect.js +45 -9
  144. package/dist/utils/startup-trace.js +74 -37
  145. package/dist/utils/windows-shell-trust.js +80 -6
  146. package/kits/docs/INDEX.md +2 -2
  147. package/kits/docs/aun/ABILITY_CALLING.md +7 -14
  148. package/kits/docs/context-assembly.md +1 -1
  149. package/kits/docs/evolcore/INDEX.md +2 -0
  150. package/kits/docs/evolcore/ability.md +4 -0
  151. package/kits/docs/evolcore/aid.md +1 -1
  152. package/kits/docs/evolcore/event-center.md +207 -0
  153. package/kits/docs/evolcore/file-navigation.md +10 -264
  154. package/kits/docs/evolcore/fs.md +3 -2
  155. package/kits/docs/evolcore/group.md +1 -1
  156. package/kits/docs/evolcore/memory-architecture.md +2 -0
  157. package/kits/docs/evolcore/menu-protocol.md +21 -0
  158. package/kits/docs/evolcore/msg.md +15 -3
  159. package/kits/docs/evolcore/provider.md +3 -1
  160. package/kits/docs/evolcore/response.md +5 -5
  161. package/kits/docs/evolcore/services.md +277 -0
  162. package/kits/docs/evolcore/task.md +2 -0
  163. package/kits/docs/evolcore/team-workspace.md +41 -0
  164. package/kits/eck_manifest.json +26 -0
  165. package/kits/rules/02-navigation.md +10 -1
  166. package/kits/schemas/_meta.json +17 -6
  167. package/kits/schemas/agent-config.schema.19.json +5 -7
  168. package/kits/schemas/agent-config.schema.20.json +936 -0
  169. package/kits/schemas/relation-config.schema.12.json +2 -3
  170. package/kits/schemas/role-config.schema.2.json +4 -4
  171. package/kits/skills/.switches.json +1 -5
  172. package/kits/skills/ability/SKILL.md +56 -0
  173. package/kits/skills/ability/references/calling.md +56 -0
  174. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  175. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  176. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  177. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  178. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  179. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  180. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  181. package/kits/skills/personal-assistant/SKILL.md +6 -6
  182. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  183. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  184. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  185. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  186. package/kits/templates/system-fragments/channel.md +3 -3
  187. package/kits/templates/system-fragments/commands.md +5 -3
  188. package/kits/templates/system-fragments/reply.md +0 -5
  189. package/kits/templates/system-fragments/thread.md +10 -8
  190. package/package.json +3 -5
  191. package/dist/cli/pa-workspace-command.js +0 -225
  192. package/dist/core/command/pa-workspace-store.js +0 -468
  193. package/dist/core/relation/pa-team.js +0 -132
  194. package/kits/docs/evolcore/pa-workspace.md +0 -51
  195. package/kits/skills/aid-ability/SKILL.md +0 -244
  196. package/kits/skills/ec-ability/SKILL.md +0 -67
  197. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -0,0 +1,120 @@
1
+ /**
2
+ * bus 占位符解析:$self / $owner / $pa / $pa.<role> / 字面 AID。
3
+ * 设计:detailed-design.md §三。$pa.<role> 多匹配取 AID 字典序第一个,不报错、不并发。
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { atomicWriteJson } from '../utils/atomic-write.js';
8
+ import { AID_PATTERN, ROLE_NAME_PATTERN } from './validation.js';
9
+ export class BusResolveError extends Error {
10
+ code;
11
+ constructor(code, message) {
12
+ super(message);
13
+ this.code = code;
14
+ this.name = 'BusResolveError';
15
+ }
16
+ }
17
+ export function isBusPlaceholder(ref) {
18
+ return ref === '$self' || ref === '$owner' || ref === '$pa' || ref.startsWith('$pa.');
19
+ }
20
+ /** 解析单个 bus 引用。失败抛 BusResolveError。 */
21
+ export function resolveBusRef(ref, context) {
22
+ if (ref === '$self') {
23
+ if (!context.self)
24
+ throw new BusResolveError('INVALID_AID', '$self resolved to empty AID');
25
+ return context.self;
26
+ }
27
+ if (ref === '$owner') {
28
+ if (!context.owner)
29
+ throw new BusResolveError('OWNER_MISSING', 'this AID has no owner');
30
+ return context.owner;
31
+ }
32
+ if (ref === '$pa') {
33
+ if (!context.pa)
34
+ throw new BusResolveError('PA_MISSING', 'contacts has no personal_assistant');
35
+ return context.pa;
36
+ }
37
+ if (ref.startsWith('$pa.')) {
38
+ const role = ref.slice('$pa.'.length);
39
+ if (!ROLE_NAME_PATTERN.test(role)) {
40
+ throw new BusResolveError('INVALID_ROLE', `invalid role name: ${role}`);
41
+ }
42
+ const candidates = context.paRoles?.[role];
43
+ if (!candidates || candidates.length === 0) {
44
+ throw new BusResolveError('ROLE_NOT_FOUND', `pa_roles has no role "${role}"`);
45
+ }
46
+ // 多匹配取字典序第一个:同一目录在多个 Agent 上解析结果稳定可复现。
47
+ return [...candidates].sort()[0];
48
+ }
49
+ if (!AID_PATTERN.test(ref)) {
50
+ throw new BusResolveError('INVALID_AID', `invalid literal AID: ${ref}`);
51
+ }
52
+ return ref;
53
+ }
54
+ /**
55
+ * 解析一个包内全部 bus 引用(publish + subscribe 去重)。
56
+ * strict:任一失败即失败(failures 非空,resolved 不含该引用)。
57
+ * keep-last:失败引用沿用 lastResolved 中的上次结果并记 degraded;无上次结果仍算失败。
58
+ */
59
+ export function resolvePackBuses(refs, context, strategy, lastResolved) {
60
+ const resolved = new Map();
61
+ const failures = [];
62
+ const degraded = [];
63
+ for (const ref of new Set(refs)) {
64
+ try {
65
+ resolved.set(ref, resolveBusRef(ref, context));
66
+ }
67
+ catch (error) {
68
+ if (error instanceof BusResolveError) {
69
+ const last = lastResolved?.get(ref);
70
+ if (strategy === 'keep-last' && last) {
71
+ resolved.set(ref, last);
72
+ degraded.push({ ref, lastAid: last });
73
+ }
74
+ else {
75
+ failures.push({ ref, code: error.code, message: error.message });
76
+ }
77
+ }
78
+ else {
79
+ throw error;
80
+ }
81
+ }
82
+ }
83
+ return { resolved, failures, degraded };
84
+ }
85
+ /** keep-last 上次成功解析的持久化:events/.bus-resolve-state.json,结构 { <packId>: { <ref>: aid } }。 */
86
+ export class BusResolveState {
87
+ filePath;
88
+ data = {};
89
+ constructor(filePath) {
90
+ this.filePath = filePath;
91
+ }
92
+ static forEventsDir(eventsDir) {
93
+ return new BusResolveState(path.join(eventsDir, '.bus-resolve-state.json'));
94
+ }
95
+ load() {
96
+ try {
97
+ const parsed = JSON.parse(fs.readFileSync(this.filePath, 'utf8'));
98
+ this.data = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
99
+ }
100
+ catch {
101
+ this.data = {};
102
+ }
103
+ }
104
+ get(packId) {
105
+ const entry = this.data[packId];
106
+ return new Map(Object.entries(entry ?? {}));
107
+ }
108
+ set(packId, resolved) {
109
+ this.data[packId] = Object.fromEntries(resolved);
110
+ }
111
+ save() {
112
+ try {
113
+ fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
114
+ atomicWriteJson(this.filePath, this.data);
115
+ }
116
+ catch {
117
+ // 持久化失败不致命:下次 keep-last 退化为 strict 行为。
118
+ }
119
+ }
120
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * center.json 管理:读、原子写、白名单增删查;变更联动 SDK updateConfig 由调用方(runtime)执行。
3
+ */
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { atomicWriteJson } from '../utils/atomic-write.js';
7
+ import { centerLedger } from './ledger.js';
8
+ import { CENTER_JSON } from './pack-loader.js';
9
+ import { EventCenterError } from './types.js';
10
+ import { validateCenterConfig } from './validation.js';
11
+ export class CenterConfigStore {
12
+ filePath;
13
+ ledger;
14
+ constructor(options) {
15
+ this.filePath = path.join(options.eventsDir, CENTER_JSON);
16
+ this.ledger = options.ledger ?? centerLedger(options.eventsDir);
17
+ }
18
+ /** 读取并校验;校验失败返回缺省并带 errors(Bus 不启动,不覆盖磁盘)。 */
19
+ read() {
20
+ let rawText;
21
+ try {
22
+ rawText = fs.readFileSync(this.filePath, 'utf8');
23
+ }
24
+ catch {
25
+ return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, allowlist: {} }, exists: false, errors: [] };
26
+ }
27
+ let raw;
28
+ try {
29
+ raw = JSON.parse(rawText);
30
+ }
31
+ catch (error) {
32
+ return {
33
+ config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, allowlist: {} },
34
+ exists: true,
35
+ errors: [`${CENTER_JSON} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`],
36
+ };
37
+ }
38
+ const validated = validateCenterConfig(raw);
39
+ if (!validated.ok) {
40
+ return { config: { enabled: false, authMode: 'allowlist', admission: { coupling: 'on', rematerializeMs: 300_000 }, allowlist: {} }, exists: true, errors: validated.errors };
41
+ }
42
+ return { config: validated.value, exists: true, errors: [] };
43
+ }
44
+ write(config) {
45
+ fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
46
+ atomicWriteJson(this.filePath, {
47
+ v: 1,
48
+ enabled: config.enabled,
49
+ authMode: config.authMode,
50
+ admission: config.admission,
51
+ allowlist: config.allowlist,
52
+ });
53
+ }
54
+ /** 白名单增删。返回更新后的配置;不做磁盘之外的生效动作。 */
55
+ mutateAllowlist(input) {
56
+ const { config } = this.read();
57
+ const current = config.allowlist[input.event];
58
+ const entry = current
59
+ ? { allow: { publish: [...current.allow.publish], subscribe: [...current.allow.subscribe] }, deny: { publish: [...current.deny.publish], subscribe: [...current.deny.subscribe] } }
60
+ : { allow: { publish: [], subscribe: [] }, deny: { publish: [], subscribe: [] } };
61
+ const rules = input.rule === 'deny' ? entry.deny : entry.allow;
62
+ const list = input.role === 'publish' ? rules.publish : rules.subscribe;
63
+ const added = [];
64
+ const removed = [];
65
+ for (const aid of input.aids) {
66
+ if (input.action === 'add') {
67
+ const opposite = input.role === 'publish'
68
+ ? (input.rule === 'deny' ? entry.allow.publish : entry.deny.publish)
69
+ : (input.rule === 'deny' ? entry.allow.subscribe : entry.deny.subscribe);
70
+ if (opposite.includes(aid)) {
71
+ throw new EventCenterError('INVALID_ARGS', `AID appears in both allow and deny for ${input.event}/${input.role}: ${aid}`);
72
+ }
73
+ if (!list.includes(aid)) {
74
+ list.push(aid);
75
+ added.push(aid);
76
+ }
77
+ }
78
+ else {
79
+ const index = list.indexOf(aid);
80
+ if (index >= 0) {
81
+ list.splice(index, 1);
82
+ removed.push(aid);
83
+ }
84
+ }
85
+ }
86
+ config.allowlist[input.event] = entry;
87
+ this.write(config);
88
+ this.ledger.append({
89
+ action: 'allowlist.update',
90
+ result: 'ok',
91
+ event: input.event,
92
+ ...(added.length ? { added } : {}),
93
+ ...(removed.length ? { removed } : {}),
94
+ ...(input.rule ? { rule: input.rule } : {}),
95
+ ...(input.by ? { by: input.by } : {}),
96
+ actor: input.by ? 'script' : 'menu',
97
+ });
98
+ return { config, changed: entry, added, removed };
99
+ }
100
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * 事件中心专用 AUN client 工厂:独立 slot(bus/sub/pub 三条连接,绝不复用 daemon 主连接)。
3
+ * 流程与旧 src/aun/event-bus/client-factory.ts 一致:getAidStore → loadClient → authenticate → connect。
4
+ */
5
+ import os from 'node:os';
6
+ import { getAidStore, loadClient } from '../aun/aid/store.js';
7
+ export const createEventClient = async (aid, slotId) => {
8
+ const store = await getAidStore({ slotId });
9
+ let client;
10
+ try {
11
+ client = await loadClient(store, aid);
12
+ await client.authenticate();
13
+ await client.connect({
14
+ extra_info: { app: 'evolcore', role: slotId, pid: process.pid, hostname: os.hostname() },
15
+ auto_reconnect: true,
16
+ background_sync: false,
17
+ retry_max_attempts: 0,
18
+ retry_initial_delay: 1.0,
19
+ retry_max_delay: 60.0,
20
+ });
21
+ const handle = client;
22
+ return {
23
+ client: handle,
24
+ async close() {
25
+ try {
26
+ await handle.close();
27
+ }
28
+ finally {
29
+ await store.close();
30
+ }
31
+ },
32
+ };
33
+ }
34
+ catch (error) {
35
+ try {
36
+ if (client)
37
+ await client.close();
38
+ }
39
+ catch {
40
+ // 已在失败路径上,二次关闭错误忽略。
41
+ }
42
+ try {
43
+ await store.close();
44
+ }
45
+ catch {
46
+ // 同上。
47
+ }
48
+ throw error;
49
+ }
50
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * daemon 接线:事件中心随 agent 的 Trigger 调度器启停(与旧事件总线相同的生命周期挂点)。
3
+ * daemon 自身的 Trigger owner 不是 agent,不承载事件中心。
4
+ */
5
+ import fs from 'node:fs';
6
+ import { agentDir } from '../paths.js';
7
+ import { createEventClient } from './client-factory.js';
8
+ import { EventCenterRegistry } from './registry.js';
9
+ /**
10
+ * 解析 agent 工程目录:只接受真实存在的目录。
11
+ *
12
+ * `EvolAgent.projectPath` 在 `projects.defaultPath` 为空时回落到 `process.cwd()`,
13
+ * 那会把整个 EvolCore 仓当成工程目录,沙箱边界与 trigger 的 cwd 都会漂。
14
+ * 这里改为 fail-closed 到 `undefined`:沙箱明确报 `SCRIPT_SANDBOX_UNAVAILABLE`,
15
+ * 而不是拿到一个语义可疑的目录继续跑。
16
+ */
17
+ export function resolveAgentProjectPath(aid, candidate) {
18
+ const trimmed = candidate?.trim();
19
+ if (!trimmed)
20
+ return undefined;
21
+ try {
22
+ return fs.statSync(trimmed).isDirectory() ? trimmed : undefined;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ export function createDaemonEventCenter(options) {
29
+ const registry = new EventCenterRegistry({
30
+ agentDir,
31
+ createClient: options.createClient ?? createEventClient,
32
+ getProjectPath: options.getProjectPath
33
+ ?? (aid => resolveAgentProjectPath(aid, options.agentRegistry.get(aid)?.projectPath)),
34
+ getScheduler: aid => options.triggerSchedulers.get(aid),
35
+ });
36
+ options.triggerSchedulers.addLifecycleListener({
37
+ started: aid => {
38
+ if (options.agentRegistry.get(aid))
39
+ void registry.ensureStarted(aid);
40
+ },
41
+ removed: aid => { void registry.remove(aid); },
42
+ suspending: () => { void registry.closeAll(); },
43
+ });
44
+ return registry;
45
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * 占位符解析上下文的数据源:直读 agents/<aid>/directory/contacts.json。
3
+ * 与 OwnerDirectoryCache 同一文件(cachePath('contacts')),只读、防御式:
4
+ * 文件缺失/字段非法 → 相应上下文项留空(strict 包会因此 invalid)。
5
+ * pa_roles 为新增顶层字段,暂不参与 content_digest。
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { AID_PATTERN } from './validation.js';
10
+ export function readBusResolverContext(aid, agentDir) {
11
+ const context = { self: aid, paRoles: {} };
12
+ let raw;
13
+ try {
14
+ raw = JSON.parse(fs.readFileSync(path.join(agentDir, 'directory', 'contacts.json'), 'utf8'));
15
+ }
16
+ catch {
17
+ return context;
18
+ }
19
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
20
+ return context;
21
+ const record = raw;
22
+ const ownerAid = identityAid(record.owner);
23
+ if (ownerAid)
24
+ context.owner = ownerAid;
25
+ const paAid = identityAid(record.personal_assistant);
26
+ if (paAid)
27
+ context.pa = paAid;
28
+ const paRoles = parsePaRoles(record.pa_roles);
29
+ if (paRoles)
30
+ context.paRoles = paRoles;
31
+ return context;
32
+ }
33
+ function identityAid(value) {
34
+ if (!value || typeof value !== 'object')
35
+ return undefined;
36
+ const aid = value.aid;
37
+ return typeof aid === 'string' && AID_PATTERN.test(aid) ? aid : undefined;
38
+ }
39
+ function parsePaRoles(value) {
40
+ if (!value || typeof value !== 'object' || Array.isArray(value))
41
+ return undefined;
42
+ const out = {};
43
+ for (const [role, aids] of Object.entries(value)) {
44
+ if (!/^[a-z0-9_-]+$/.test(role))
45
+ continue;
46
+ if (!Array.isArray(aids))
47
+ continue;
48
+ const valid = aids.filter((item) => typeof item === 'string' && AID_PATTERN.test(item));
49
+ if (valid.length > 0)
50
+ out[role] = valid;
51
+ }
52
+ return out;
53
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * 事件分发:SDK 事件 → 匹配包订阅 → received 日志 → filter → 队列 → 并发执行脚本 → handled 日志。
3
+ * 队列键 = 包:事件,每队列独立容量;全局并发上限。
4
+ */
5
+ import { logger } from '../utils/logger.js';
6
+ import { matchTriggerEvent } from '../trigger/event-source.js';
7
+ import { EventLog } from './event-log.js';
8
+ export const DEFAULT_DISPATCHER_LIMITS = { maxConcurrency: 5, queueSize: 100 };
9
+ /**
10
+ * 包内一条 subscribe 条目实际指向的 bus AID。
11
+ * 顺序与 handleEvent 一致:resolutions(占位符解析结果)→ busResolved → 字面 bus。
12
+ */
13
+ function resolveEntryBus(resolutions, packId, entry) {
14
+ return resolutions.get(packId)?.get(entry.bus) ?? entry.busResolved ?? entry.bus;
15
+ }
16
+ export class EventDispatcher {
17
+ scriptRunner;
18
+ limits;
19
+ queues = new Map();
20
+ running = 0;
21
+ closed = false;
22
+ idleResolvers = [];
23
+ constructor(scriptRunner, limits = DEFAULT_DISPATCHER_LIMITS) {
24
+ this.scriptRunner = scriptRunner;
25
+ this.limits = limits;
26
+ }
27
+ setLimits(limits) {
28
+ this.limits = { ...this.limits, ...limits };
29
+ }
30
+ /** SDK onEvent 回调入口;必须非阻塞(SDK 内按 bus 串行派发)。 */
31
+ handleEvent(packs, resolutions, event) {
32
+ if (this.closed)
33
+ return;
34
+ for (const pack of packs) {
35
+ for (const entry of pack.subscribe) {
36
+ const busAid = resolutions.get(pack.id)?.get(entry.bus) ?? entry.busResolved;
37
+ if (busAid !== event.busAid || entry.event !== event.eventName)
38
+ continue;
39
+ const log = EventLog.forPack(pack);
40
+ // 写前日志:received 一定先落盘。
41
+ log.writeReceived(event);
42
+ if (entry.filter && !this.matches(entry.filter, event)) {
43
+ log.writeFiltered(event, 'filter_mismatch');
44
+ continue;
45
+ }
46
+ const key = `${pack.id}\u0000${entry.event}`;
47
+ const queue = this.queues.get(key) ?? [];
48
+ if (queue.length >= this.limits.queueSize) {
49
+ log.writeDropped(event, 'queue_full');
50
+ continue;
51
+ }
52
+ queue.push({ pack, event, resolutions });
53
+ this.queues.set(key, queue);
54
+ void this.tick();
55
+ }
56
+ }
57
+ }
58
+ /** filter 求值复用 trigger 语义:伪事件 = 事件正文字段展开 + type=事件名(type 保留,正文里的同名键被覆盖)。 */
59
+ matches(filter, event) {
60
+ const pseudo = typeof event.data === 'object' && event.data !== null && !Array.isArray(event.data)
61
+ ? { ...event.data, type: event.eventName }
62
+ : { type: event.eventName };
63
+ return matchTriggerEvent({ type: 'event', eventPattern: '*', filter }, pseudo).matched;
64
+ }
65
+ async tick() {
66
+ while (this.running < this.limits.maxConcurrency) {
67
+ const item = this.dequeue();
68
+ if (!item)
69
+ break;
70
+ this.running++;
71
+ try {
72
+ await this.execute(item);
73
+ }
74
+ finally {
75
+ this.running--;
76
+ }
77
+ }
78
+ if (this.running === 0 && this.isEmpty()) {
79
+ const waiters = [...this.idleResolvers];
80
+ this.idleResolvers.length = 0;
81
+ for (const resolve of waiters)
82
+ resolve();
83
+ }
84
+ }
85
+ dequeue() {
86
+ for (const [key, queue] of this.queues) {
87
+ if (queue.length === 0)
88
+ continue;
89
+ const item = queue.shift();
90
+ if (queue.length === 0)
91
+ this.queues.delete(key);
92
+ return item;
93
+ }
94
+ return null;
95
+ }
96
+ isEmpty() {
97
+ for (const queue of this.queues.values()) {
98
+ if (queue.length > 0)
99
+ return false;
100
+ }
101
+ return true;
102
+ }
103
+ async execute(item) {
104
+ const log = EventLog.forPack(item.pack);
105
+ // 热重载后订阅 handler 可能已变:从当前包配置重新取 handler。
106
+ //
107
+ // bus 的解析结果在 `resolutions` 里,`$self` / `$owner` 这类占位符**不会**写回
108
+ // `entry.busResolved`。只比 `busResolved` 会让占位符写法的包全部匹配失败,
109
+ // 表现是 received 有、handled 没有、脚本静默不跑。这里用与 handleEvent 相同的
110
+ // `resolutions → busResolved → bus` 链路解析。
111
+ const entry = item.pack.subscribe.find(candidate => resolveEntryBus(item.resolutions, item.pack.id, candidate) === item.event.busAid
112
+ && candidate.event === item.event.eventName);
113
+ if (!entry)
114
+ return; // 包已改,事件不再处理(received 已落盘)
115
+ try {
116
+ const outcome = await this.scriptRunner.run(item.pack, entry.handler, item.event);
117
+ log.writeHandled(item.event, {
118
+ cmd: outcome.cmd,
119
+ exit: outcome.exitCode,
120
+ ms: outcome.durationMs,
121
+ outcome: outcome.outcome,
122
+ ...(outcome.error ? { reason: `${outcome.error.code}: ${outcome.error.message}`.slice(0, 240) } : {}),
123
+ // 无沙箱执行必须留痕:事后排查「这个脚本为什么能读到不该读的东西」靠它。
124
+ ...(outcome.sandboxAbsent ? { sandboxAbsent: outcome.sandboxAbsent } : {}),
125
+ });
126
+ if (outcome.outcome === 'error' || outcome.outcome === 'timeout') {
127
+ logger.warn(`[EventCenter] ${item.pack.id} handler for ${item.event.eventName} ${outcome.outcome}: ${outcome.error?.code ?? ''} ${outcome.error?.message ?? ''}`);
128
+ }
129
+ }
130
+ catch (error) {
131
+ // 执行器自身异常(不应发生):按 error 记,不中断队列。
132
+ log.writeHandled(item.event, {
133
+ cmd: 'unavailable',
134
+ exit: -1,
135
+ ms: 0,
136
+ outcome: 'error',
137
+ reason: `DISPATCHER_ERROR: ${error instanceof Error ? error.message : String(error)}`.slice(0, 240),
138
+ });
139
+ }
140
+ }
141
+ /** 关闭:停止接收;已排队事件丢弃(volatile 语义),等待运行中脚本结束。 */
142
+ async close(drainTimeoutMs = 5_000) {
143
+ this.closed = true;
144
+ this.queues.clear();
145
+ if (this.running > 0) {
146
+ await Promise.race([
147
+ new Promise(resolve => {
148
+ this.idleResolvers.push(resolve);
149
+ }),
150
+ new Promise(resolve => {
151
+ const timer = setTimeout(resolve, drainTimeoutMs);
152
+ timer.unref?.();
153
+ }),
154
+ ]);
155
+ }
156
+ }
157
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * 事件日志(logs/events-YYYYMMDD.jsonl):写前日志,先 received 再执行脚本,结束补 handled。
3
+ * 行结构按 docs/event-center/schema/event-log.schema.json(additionalProperties: false)。
4
+ * P0 恒落 data 原文(dataHash 逻辑留接口)。
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ /** data 只在是 JSON 对象时按原样落盘(Schema 要求 object),其它形态包成 {@raw: string}。 */
9
+ function normalizeData(data) {
10
+ if (data !== null && typeof data === 'object' && !Array.isArray(data))
11
+ return data;
12
+ return { '@raw': JSON.stringify(data) };
13
+ }
14
+ export class EventLog {
15
+ logsDir;
16
+ constructor(logsDir) {
17
+ this.logsDir = logsDir;
18
+ }
19
+ static forPack(pack) {
20
+ return new EventLog(pack.paths.logsDir);
21
+ }
22
+ writeReceived(event) {
23
+ this.write({
24
+ ts: Date.now(),
25
+ kind: 'received',
26
+ eventId: event.eventId,
27
+ event: event.eventName,
28
+ bus: event.busAid,
29
+ publisher: event.publisher,
30
+ data: normalizeData(event.data),
31
+ });
32
+ }
33
+ writeHandled(event, detail) {
34
+ this.write({
35
+ ts: Date.now(),
36
+ kind: 'handled',
37
+ eventId: event.eventId,
38
+ event: event.eventName,
39
+ bus: event.busAid,
40
+ cmd: detail.cmd,
41
+ exit: detail.exit,
42
+ ms: detail.ms,
43
+ outcome: detail.outcome,
44
+ ...(detail.reason !== undefined ? { reason: detail.reason } : {}),
45
+ ...(detail.sandboxAbsent !== undefined ? { sandbox_absent: detail.sandboxAbsent } : {}),
46
+ });
47
+ }
48
+ writeDropped(event, reason) {
49
+ this.write({
50
+ ts: Date.now(),
51
+ kind: 'dropped',
52
+ eventId: event.eventId,
53
+ event: event.eventName,
54
+ bus: event.busAid,
55
+ reason,
56
+ });
57
+ }
58
+ writeFiltered(event, reason) {
59
+ this.write({
60
+ ts: Date.now(),
61
+ kind: 'filtered',
62
+ eventId: event.eventId,
63
+ event: event.eventName,
64
+ bus: event.busAid,
65
+ reason,
66
+ });
67
+ }
68
+ /** 按天分文件(本地日期);IO 失败吞掉。 */
69
+ write(line) {
70
+ const now = new Date();
71
+ const date = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
72
+ try {
73
+ fs.mkdirSync(this.logsDir, { recursive: true });
74
+ fs.appendFileSync(path.join(this.logsDir, `events-${date}.jsonl`), `${JSON.stringify(line)}\n`, 'utf8');
75
+ }
76
+ catch {
77
+ // 日志写失败不中断事件处理。
78
+ }
79
+ }
80
+ /** 读某包最近的事件日志行(CLI tail 用)。 */
81
+ tail(count) {
82
+ let files;
83
+ try {
84
+ files = fs.readdirSync(this.logsDir).filter(name => /^events-\d{8}\.jsonl$/.test(name)).sort();
85
+ }
86
+ catch {
87
+ return [];
88
+ }
89
+ const lines = [];
90
+ for (const file of [...files].reverse()) {
91
+ try {
92
+ const text = fs.readFileSync(path.join(this.logsDir, file), 'utf8');
93
+ lines.unshift(...text.split('\n').filter(Boolean));
94
+ }
95
+ catch {
96
+ break;
97
+ }
98
+ if (lines.length >= count)
99
+ break;
100
+ }
101
+ return lines.slice(-count).map(line => {
102
+ try {
103
+ return JSON.parse(line);
104
+ }
105
+ catch {
106
+ return { ts: 0, kind: 'dropped', reason: 'unparseable log line' };
107
+ }
108
+ });
109
+ }
110
+ }