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
@@ -1,468 +0,0 @@
1
- import crypto from 'node:crypto';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { agentDataDir } from '../../paths.js';
5
- import { isValidAid } from '../../aun/aid/validation.js';
6
- import { atomicReplaceFile } from '../../utils/atomic-write.js';
7
- export class DataRootError extends Error {
8
- code;
9
- data;
10
- constructor(code, message, data) {
11
- super(message);
12
- this.name = 'DataRootError';
13
- this.code = code;
14
- this.data = data;
15
- }
16
- }
17
- const STATE_FILE = 'pa-workspace-state.json';
18
- const MAX_ENTRIES = 200;
19
- const MAX_PATH_LENGTH = 2048;
20
- const lockDelay = new Int32Array(new SharedArrayBuffer(4));
21
- const DEFAULT_NAVIGATION_ENTRIES = [
22
- { id: 'reports', title: '报告', path: 'output/reports', kind: 'directory', order: 10, icon: 'report' },
23
- { id: 'tasks', title: '任务', path: 'output/tasks', kind: 'directory', order: 20, icon: 'task' },
24
- { id: 'knowledge', title: '沉淀', path: 'output/knowledge', kind: 'directory', order: 30, icon: 'memory' },
25
- { id: 'conversations', title: '对话档案', path: 'capture/conversation', kind: 'directory', order: 40, icon: 'conversation' },
26
- { id: 'notes', title: '笔记', path: 'capture/notes', kind: 'directory', order: 50, icon: 'notes' },
27
- { id: 'links', title: '链接收藏', path: 'capture/links', kind: 'directory', order: 60, icon: 'links' },
28
- ];
29
- const LEGACY_AUTO_ENTRY_PATHS = new Set(['capture', 'output', 'README.md', 'INDEX.md']);
30
- function statePath(paAid) {
31
- return path.join(agentDataDir(paAid), STATE_FILE);
32
- }
33
- function fail(code, message, data) {
34
- throw new DataRootError(code, message, data);
35
- }
36
- function canonicalDirectory(value) {
37
- if (typeof value !== 'string' || !value.trim() || !path.isAbsolute(value)) {
38
- return fail('INVALID_ARGUMENT', 'workspace rootPath must be an absolute path');
39
- }
40
- let real;
41
- try {
42
- real = fs.realpathSync(value);
43
- }
44
- catch {
45
- return fail('ROOT_NOT_FOUND', 'PA workspace does not exist');
46
- }
47
- try {
48
- if (!fs.statSync(real).isDirectory())
49
- return fail('ROOT_NOT_FOUND', 'PA workspace is not a directory');
50
- }
51
- catch {
52
- return fail('ROOT_NOT_FOUND', 'PA workspace does not exist');
53
- }
54
- return real;
55
- }
56
- function isInside(root, candidate) {
57
- const relative = path.relative(root, candidate);
58
- return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
59
- }
60
- /** Paths which can contain runtime state are never PA user-facing content. */
61
- export function isPaHiddenPath(relativePath) {
62
- const parts = relativePath.replaceAll('\\', '/').split('/').filter(Boolean);
63
- if (parts.some(part => part === '.' || part.startsWith('.')))
64
- return true;
65
- for (let i = 0; i + 1 < parts.length; i++) {
66
- if (parts[i].toLowerCase() === 'capture' && parts[i + 1].toLowerCase() === '_manifest')
67
- return true;
68
- }
69
- return false;
70
- }
71
- function normalizeRelative(value, allowRoot = false) {
72
- if (typeof value !== 'string' || !value.trim() || value.length > MAX_PATH_LENGTH) {
73
- return fail('INVALID_ROOT_PATH', 'A PA workspace path is required');
74
- }
75
- const raw = value.trim().replaceAll('\\', '/');
76
- if (raw.startsWith('/') || path.isAbsolute(raw) || path.win32.isAbsolute(raw)
77
- || raw.includes(':') || raw.includes('\0') || raw.split('/').includes('..')) {
78
- return fail('INVALID_ROOT_PATH', 'PA workspace paths must be relative and cannot contain traversal');
79
- }
80
- const normalized = raw.split('/').filter(part => part && part !== '.').join('/');
81
- if ((!normalized && !allowRoot) || isPaHiddenPath(normalized))
82
- return fail('INVALID_ROOT_PATH', 'PA workspace path is not user-facing content');
83
- return normalized || '.';
84
- }
85
- function entryId(relativePath) {
86
- return `pa-${crypto.createHash('sha256').update(relativePath).digest('hex').slice(0, 16)}`;
87
- }
88
- function validateEntry(entry, rootPath, index) {
89
- if (!entry || typeof entry !== 'object' || Array.isArray(entry))
90
- return fail('INVALID_ARGUMENT', `entries[${index}] must be an object`);
91
- const value = entry;
92
- const relativePath = normalizeRelative(value.path);
93
- const title = typeof value.title === 'string' && value.title.trim() ? value.title.trim() : path.posix.basename(relativePath);
94
- if (title.length > 200)
95
- return fail('INVALID_ARGUMENT', `entries[${index}].title is too long`);
96
- const requestedKind = value.kind;
97
- if (requestedKind !== 'file' && requestedKind !== 'directory')
98
- return fail('INVALID_ARGUMENT', `entries[${index}].kind is invalid`);
99
- if (value.availability !== undefined && value.availability !== 'available' && value.availability !== 'unavailable') {
100
- return fail('INVALID_ARGUMENT', `entries[${index}].availability is invalid`);
101
- }
102
- const unavailable = value.availability === 'unavailable';
103
- const reason = typeof value.reason === 'string' && value.reason.trim() ? value.reason.trim().slice(0, 500) : undefined;
104
- if (unavailable && !reason)
105
- return fail('INVALID_ARGUMENT', `entries[${index}].reason is required for unavailable entries`);
106
- const order = Number.isSafeInteger(value.order) ? Number(value.order) : index;
107
- if (order < 0 || order > 1_000_000)
108
- return fail('INVALID_ARGUMENT', `entries[${index}].order is invalid`);
109
- const id = typeof value.id === 'string' && value.id.trim() ? value.id.trim() : entryId(relativePath);
110
- if (id.length > 200)
111
- return fail('INVALID_ARGUMENT', `entries[${index}].id is too long`);
112
- const icon = typeof value.icon === 'string' && value.icon.trim() ? value.icon.trim().slice(0, 100) : undefined;
113
- const candidate = path.resolve(rootPath, relativePath);
114
- let realPath;
115
- let stat;
116
- try {
117
- realPath = fs.realpathSync(candidate);
118
- stat = fs.statSync(realPath);
119
- }
120
- catch {
121
- if (!unavailable)
122
- return fail('NOT_FOUND', `PA workspace entry does not exist: ${relativePath}`);
123
- return {
124
- id,
125
- title,
126
- path: relativePath,
127
- kind: requestedKind,
128
- order,
129
- availability: 'unavailable',
130
- reason,
131
- ...(icon ? { icon } : {}),
132
- };
133
- }
134
- if (!isInside(rootPath, realPath))
135
- return fail('INVALID_ROOT_PATH', 'PA workspace entry escapes the workspace');
136
- const kind = stat.isDirectory() ? 'directory' : stat.isFile() ? 'file' : undefined;
137
- if (!kind)
138
- return fail('NOT_SUPPORTED', `PA workspace entry is not a regular file or directory: ${relativePath}`);
139
- if (requestedKind !== kind)
140
- return fail('INVALID_ARGUMENT', `entries[${index}].kind does not match the target`);
141
- const result = { id, title, path: relativePath, kind, order, availability: 'available' };
142
- if (icon)
143
- result.icon = icon;
144
- return result;
145
- }
146
- function sortEntries(entries) {
147
- return [...entries].sort((a, b) => a.order - b.order || a.title.localeCompare(b.title) || a.path.localeCompare(b.path));
148
- }
149
- function defaultEntries(rootPath) {
150
- return DEFAULT_NAVIGATION_ENTRIES.map(entry => {
151
- try {
152
- const realPath = fs.realpathSync(path.resolve(rootPath, entry.path));
153
- if (!isInside(rootPath, realPath) || !fs.statSync(realPath).isDirectory()) {
154
- return { ...entry, availability: 'unavailable', reason: '栏目暂不可用' };
155
- }
156
- return { ...entry, availability: 'available' };
157
- }
158
- catch {
159
- return { ...entry, availability: 'unavailable', reason: '栏目尚未创建' };
160
- }
161
- });
162
- }
163
- function migratedDefaultEntries(state, rootPath) {
164
- const defaults = defaultEntries(rootPath);
165
- const defaultsByPath = new Map(defaults.map(entry => [entry.path, entry]));
166
- const existing = state.navigationRevision === 1
167
- ? state.entries.filter(entry => !LEGACY_AUTO_ENTRY_PATHS.has(entry.path))
168
- : state.entries;
169
- const migrated = existing.map(entry => {
170
- const preset = defaultsByPath.get(entry.path);
171
- return state.navigationRevision === 1 && preset ? preset : entry;
172
- });
173
- const paths = new Set(migrated.map(entry => entry.path));
174
- const ids = new Set(migrated.map(entry => entry.id));
175
- const additions = defaults.filter(entry => !paths.has(entry.path)).map(entry => {
176
- let id = entry.id;
177
- let suffix = 1;
178
- while (ids.has(id))
179
- id = `${entry.id}-preset-${suffix++}`;
180
- ids.add(id);
181
- return { ...entry, id };
182
- });
183
- return sortEntries([...migrated, ...additions]);
184
- }
185
- export class PaWorkspaceStore {
186
- read(paAid) {
187
- if (!isValidAid(paAid))
188
- return null;
189
- let value;
190
- try {
191
- value = JSON.parse(fs.readFileSync(statePath(paAid), 'utf8'));
192
- }
193
- catch {
194
- return null;
195
- }
196
- if (!value || typeof value !== 'object' || Array.isArray(value))
197
- return null;
198
- const state = value;
199
- if (state.version !== 1 || typeof state.workspaceId !== 'string' || !state.workspaceId
200
- || typeof state.ownerAid !== 'string' || typeof state.rootPath !== 'string'
201
- || !Number.isSafeInteger(state.navigationRevision) || !Array.isArray(state.entries))
202
- return null;
203
- const navigationRevision = state.navigationRevision;
204
- return {
205
- version: 1,
206
- workspaceId: state.workspaceId,
207
- ownerAid: state.ownerAid,
208
- rootPath: state.rootPath,
209
- navigationRevision,
210
- entries: sortEntries(state.entries),
211
- defaultNavigationSeeded: state.defaultNavigationSeeded === true,
212
- };
213
- }
214
- bind(paAid, ownerAid, rootPath) {
215
- if (!isValidAid(paAid) || !isValidAid(ownerAid))
216
- return fail('INVALID_ARGUMENT', 'paAid and ownerAid must be valid AIDs');
217
- const canonical = canonicalDirectory(rootPath);
218
- return this.withLock(paAid, () => {
219
- const current = this.read(paAid);
220
- if (current && current.ownerAid === ownerAid && this.samePath(current.rootPath, canonical))
221
- return current;
222
- const state = {
223
- version: 1,
224
- workspaceId: `paw1_${crypto.randomBytes(18).toString('base64url')}`,
225
- ownerAid,
226
- rootPath: canonical,
227
- navigationRevision: 1,
228
- entries: defaultEntries(canonical),
229
- defaultNavigationSeeded: true,
230
- };
231
- this.write(paAid, state);
232
- return state;
233
- });
234
- }
235
- updateNavigation(paAid, expectedNavigationRevision, entries) {
236
- return this.withLock(paAid, () => {
237
- const state = this.require(paAid);
238
- if (!Number.isSafeInteger(expectedNavigationRevision))
239
- return fail('INVALID_ARGUMENT', 'expectedNavigationRevision must be an integer');
240
- if (expectedNavigationRevision !== state.navigationRevision)
241
- return fail('CONFLICT', 'Navigation revision is stale', { expectedNavigationRevision, navigationRevision: state.navigationRevision });
242
- if (!Array.isArray(entries) || entries.length > MAX_ENTRIES)
243
- return fail('INVALID_ARGUMENT', `entries must contain at most ${MAX_ENTRIES} items`);
244
- const normalized = sortEntries(entries.map((entry, index) => validateEntry(entry, this.root(state), index)));
245
- const ids = new Set();
246
- const paths = new Set();
247
- for (const entry of normalized) {
248
- if (ids.has(entry.id))
249
- return fail('INVALID_ARGUMENT', `Duplicate navigation entry id: ${entry.id}`);
250
- if (paths.has(entry.path))
251
- return fail('INVALID_ARGUMENT', `Duplicate navigation entry path: ${entry.path}`);
252
- ids.add(entry.id);
253
- paths.add(entry.path);
254
- }
255
- const next = { ...state, navigationRevision: state.navigationRevision + 1, entries: normalized, defaultNavigationSeeded: true };
256
- this.write(paAid, next);
257
- return next;
258
- });
259
- }
260
- require(paAid) {
261
- const state = this.read(paAid);
262
- if (!state)
263
- return fail('NOT_CONFIGURED', 'PA workspace is not configured');
264
- try {
265
- if (!fs.statSync(this.root(state)).isDirectory())
266
- throw new Error();
267
- }
268
- catch {
269
- return fail('WORKSPACE_UNAVAILABLE', 'PA workspace is unavailable');
270
- }
271
- return state;
272
- }
273
- root(state) { return canonicalDirectory(state.rootPath); }
274
- resolvePath(state, relativePath) {
275
- const normalized = normalizeRelative(relativePath, true);
276
- const root = this.root(state);
277
- const candidate = path.resolve(root, normalized);
278
- let realPath;
279
- let stat;
280
- try {
281
- realPath = fs.realpathSync(candidate);
282
- stat = fs.statSync(realPath);
283
- }
284
- catch {
285
- return fail('NOT_FOUND', 'File or directory does not exist');
286
- }
287
- if (!isInside(root, realPath))
288
- return fail('INVALID_ROOT_PATH', 'Path escapes the PA workspace');
289
- const relative = path.relative(root, realPath).split(path.sep).join('/') || '.';
290
- if (relative !== '.' && isPaHiddenPath(relative))
291
- return fail('INVALID_ROOT_PATH', 'PA workspace path is not user-facing content');
292
- return { realPath, relativePath: relative, stat };
293
- }
294
- entryAvailability(state, entry) {
295
- try {
296
- const resolved = this.resolvePath(state, entry.path);
297
- const actualKind = resolved.stat.isDirectory() ? 'directory' : resolved.stat.isFile() ? 'file' : undefined;
298
- if (actualKind !== entry.kind)
299
- return { ...entry, availability: 'unavailable', reason: '入口类型已变化' };
300
- const { reason: _reason, ...available } = entry;
301
- return { ...available, availability: 'available' };
302
- }
303
- catch (error) {
304
- const reason = error instanceof DataRootError && error.code === 'NOT_FOUND'
305
- ? entry.reason === '栏目尚未创建' ? entry.reason : '栏目尚未创建或内容已移动'
306
- : '入口不可用';
307
- return { ...entry, availability: 'unavailable', reason };
308
- }
309
- }
310
- navigation(state) {
311
- return {
312
- workspaceId: state.workspaceId,
313
- navigationRevision: state.navigationRevision,
314
- title: '个人助理',
315
- entries: sortEntries(state.entries).filter(entry => !isPaHiddenPath(entry.path)),
316
- };
317
- }
318
- readNavigation(paAid) {
319
- return this.withLock(paAid, () => {
320
- const state = this.require(paAid);
321
- const baseEntries = state.defaultNavigationSeeded
322
- ? sortEntries(state.entries)
323
- : migratedDefaultEntries(state, this.root(state));
324
- const entries = baseEntries
325
- .filter(entry => !isPaHiddenPath(entry.path))
326
- .map(entry => this.entryAvailability(state, entry));
327
- const changed = JSON.stringify(entries) !== JSON.stringify(state.entries);
328
- const next = changed || !state.defaultNavigationSeeded
329
- ? { ...state, navigationRevision: state.navigationRevision + (changed ? 1 : 0), entries, defaultNavigationSeeded: true }
330
- : state;
331
- if (changed || !state.defaultNavigationSeeded)
332
- this.write(paAid, next);
333
- return this.navigation(next);
334
- });
335
- }
336
- calendarArtifacts(state, navigation, from, to, limit = 500) {
337
- const pending = [];
338
- const items = [];
339
- const visitedPaths = new Set();
340
- let visited = 0;
341
- let truncated = false;
342
- for (const entry of navigation.entries) {
343
- if (entry.availability === 'available')
344
- pending.push({ path: entry.path, kind: entry.kind });
345
- }
346
- while (pending.length > 0 && !truncated) {
347
- const current = pending.pop();
348
- if (visitedPaths.has(current.path))
349
- continue;
350
- visitedPaths.add(current.path);
351
- let resolved;
352
- try {
353
- resolved = this.resolvePath(state, current.path);
354
- }
355
- catch {
356
- truncated = true;
357
- continue;
358
- }
359
- if (current.kind === 'file') {
360
- if (!resolved.stat.isFile())
361
- continue;
362
- const at = Math.floor(resolved.stat.mtimeMs);
363
- if (at >= from && at < to) {
364
- items.push({ path: resolved.relativePath, title: path.posix.basename(resolved.relativePath), at });
365
- }
366
- continue;
367
- }
368
- if (!resolved.stat.isDirectory())
369
- continue;
370
- let entries;
371
- try {
372
- entries = fs.readdirSync(resolved.realPath, { withFileTypes: true });
373
- }
374
- catch {
375
- truncated = true;
376
- continue;
377
- }
378
- entries.sort((a, b) => a.name.localeCompare(b.name));
379
- for (const entry of entries) {
380
- const relativePath = `${resolved.relativePath}/${entry.name}`;
381
- if (isPaHiddenPath(relativePath))
382
- continue;
383
- if (++visited > 20_000) {
384
- truncated = true;
385
- break;
386
- }
387
- if (entry.isDirectory())
388
- pending.push({ path: relativePath, kind: 'directory' });
389
- else if (entry.isFile())
390
- pending.push({ path: relativePath, kind: 'file' });
391
- }
392
- }
393
- items.sort((a, b) => a.at - b.at || a.path.localeCompare(b.path));
394
- if (items.length > limit) {
395
- items.splice(0, items.length - limit);
396
- truncated = true;
397
- }
398
- return { items, truncated };
399
- }
400
- write(paAid, state) {
401
- const destination = statePath(paAid);
402
- fs.mkdirSync(path.dirname(destination), { recursive: true });
403
- const temporary = `${destination}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
404
- fs.writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
405
- try {
406
- atomicReplaceFile(temporary, destination);
407
- }
408
- catch (error) {
409
- try {
410
- fs.rmSync(temporary, { force: true });
411
- }
412
- catch { }
413
- throw error;
414
- }
415
- }
416
- withLock(paAid, action) {
417
- const directory = agentDataDir(paAid);
418
- fs.mkdirSync(directory, { recursive: true });
419
- const lockPath = path.join(directory, `${STATE_FILE}.lock`);
420
- let fd;
421
- const deadline = Date.now() + 10_000;
422
- while (fd === undefined) {
423
- try {
424
- fd = fs.openSync(lockPath, 'wx', 0o600);
425
- }
426
- catch (error) {
427
- if (error.code !== 'EEXIST')
428
- throw error;
429
- try {
430
- if (Date.now() - fs.statSync(lockPath).mtimeMs > 120_000)
431
- fs.rmSync(lockPath, { force: true });
432
- }
433
- catch { /* another process may have released it */ }
434
- if (Date.now() >= deadline)
435
- return fail('CONFLICT', 'PA workspace is being updated; retry shortly');
436
- Atomics.wait(lockDelay, 0, 0, 20);
437
- }
438
- }
439
- try {
440
- return action();
441
- }
442
- finally {
443
- fs.closeSync(fd);
444
- fs.rmSync(lockPath, { force: true });
445
- }
446
- }
447
- samePath(a, b) {
448
- try {
449
- return fs.realpathSync(a) === b;
450
- }
451
- catch {
452
- return path.resolve(a) === b;
453
- }
454
- }
455
- }
456
- export const paWorkspaceStore = new PaWorkspaceStore();
457
- /** Explicit Core-side binding hook for PA initialization/--workspace callers. */
458
- export function bindPaWorkspace(paAid, ownerAid, rootPath) {
459
- return paWorkspaceStore.bind(paAid, ownerAid, rootPath);
460
- }
461
- /** Core-side capability used by PA initialization and conversation tooling. */
462
- export function readPaWorkspaceNavigation(paAid) {
463
- return paWorkspaceStore.readNavigation(paAid);
464
- }
465
- /** Core-side capability used by PA conversation tooling; App has no write route. */
466
- export function updatePaWorkspaceNavigation(paAid, expectedNavigationRevision, entries) {
467
- return paWorkspaceStore.navigation(paWorkspaceStore.updateNavigation(paAid, expectedNavigationRevision, entries));
468
- }
@@ -1,132 +0,0 @@
1
- import { createHash } from 'crypto';
2
- import { agentmdGet } from '../../aun/aid/agentmd.js';
3
- import { isValidAid } from '../../aun/aid/validation.js';
4
- import { parseAgentMdFrontmatter } from './peer-identity.js';
5
- export const PA_TEAM_MAX_AGE_MS = 30_000;
6
- const PA_TEAM_TIMEOUT_MS = 8_000;
7
- const runtimes = new Map();
8
- const knownTeams = new Map();
9
- let revision = 0;
10
- export function registerPaTeamClient(selfAid, client, store) {
11
- unregisterPaTeamClient(selfAid);
12
- const peers = knownTeams.get(selfAid) ?? new Set();
13
- knownTeams.set(selfAid, peers);
14
- const runtime = { client, store, generation: 0, entries: new Map(), pending: new Map(), knownTeams: peers, subscriptions: [] };
15
- runtimes.set(selfAid, runtime);
16
- const invalidate = () => {
17
- if (runtimes.get(selfAid) !== runtime)
18
- return;
19
- runtime.generation++;
20
- runtime.entries.clear();
21
- runtime.pending.clear();
22
- revision++;
23
- };
24
- for (const event of ['agentmd.changed', 'storage.object_changed', 'ownership.completed', 'ownership.rejected',
25
- 'ownership.stopped', 'ownership.error', 'disconnected']) {
26
- runtime.subscriptions.push(client.on(event, invalidate));
27
- }
28
- }
29
- export function unregisterPaTeamClient(selfAid, client) {
30
- const runtime = runtimes.get(selfAid);
31
- if (!runtime || (client && runtime.client !== client))
32
- return;
33
- runtimes.delete(selfAid);
34
- revision++;
35
- for (const subscription of runtime.subscriptions)
36
- subscription.unsubscribe();
37
- }
38
- export function paTeamQualification(selfAid, peerAid) {
39
- const runtime = runtimes.get(selfAid);
40
- const entry = runtime?.entries.get(peerAid);
41
- return runtime?.client.isReady && entry && entry.expiresAt > Date.now()
42
- ? entry.qualification : 'unavailable';
43
- }
44
- export function paTeamRevision(selfAid) {
45
- const runtime = runtimes.get(selfAid);
46
- const entries = [...(runtime?.entries ?? [])].map(([peerAid, entry]) => [peerAid, entry.revision, entry.expiresAt > Date.now()]);
47
- return JSON.stringify([revision, runtime?.client.isReady === true, entries]);
48
- }
49
- export function requiresPaTeamVerification(selfAid, peerAid) {
50
- return knownTeams.get(selfAid)?.has(peerAid) === true;
51
- }
52
- export async function preparePaTeamQualification(selfAid, peerAid) {
53
- if (!selfAid || !peerAid || selfAid === peerAid || !isValidAid(selfAid) || !isValidAid(peerAid))
54
- return;
55
- const runtime = runtimes.get(selfAid);
56
- if (!runtime?.client.isReady)
57
- return;
58
- const cached = runtime.entries.get(peerAid);
59
- if (cached && cached.expiresAt > Date.now())
60
- return;
61
- const pending = runtime.pending.get(peerAid);
62
- if (pending)
63
- return pending;
64
- const generation = runtime.generation;
65
- const startedAt = Date.now();
66
- const query = async () => {
67
- const cards = await Promise.all([selfAid, peerAid].map(aid => agentmdGet(aid, { store: runtime.store, withVerification: true, remoteOnly: true })));
68
- const profiles = cards.map((card, index) => {
69
- if (card.source !== 'remote' || card.verification.status !== 'verified')
70
- throw new Error('Unverified PA profile');
71
- const profile = parseAgentMdFrontmatter(card.content);
72
- if (profile.aid !== [selfAid, peerAid][index])
73
- throw new Error('Mismatched PA profile');
74
- return profile;
75
- });
76
- // The same-owner proof is now the internal-agent qualification. Keep the
77
- // pa-team API names for registry/config compatibility, but do not require
78
- // an exttype prefix: non-PA agents owned by the same Owner are internal
79
- // contacts as well. Human/service/device identities do not participate in
80
- // this automatic role because they cannot provide the required agent.md
81
- // ownership statement used by the protocol consensus check.
82
- if (!profiles.every(profile => String(profile.type || '').trim().toLowerCase() === 'agent'))
83
- return 'unmatched';
84
- const consensuses = await Promise.all([selfAid, peerAid].map(aid => runtime.client.checkOwnershipConsensus(aid, true)));
85
- for (const [index, consensus] of consensuses.entries()) {
86
- const digest = createHash('sha256').update(cards[index].content, 'utf8').digest('hex');
87
- if (consensus.status !== 'consensus' || consensus.sub_aid !== [selfAid, peerAid][index]
88
- || consensus.lock !== 'locked' || !consensus.owner_aid || !isValidAid(consensus.owner_aid)
89
- || !Number.isSafeInteger(consensus.relation_version) || consensus.relation_version < 1
90
- || consensus.agent_md_sha256 !== digest
91
- || profiles[index].owner !== consensus.owner_aid)
92
- return 'unavailable';
93
- }
94
- return consensuses[0].owner_aid === consensuses[1].owner_aid ? 'matched' : 'unmatched';
95
- };
96
- const task = (async () => {
97
- let timeout;
98
- let qualification = 'unavailable';
99
- try {
100
- qualification = await Promise.race([query(), new Promise(resolve => {
101
- timeout = setTimeout(() => resolve('unavailable'), PA_TEAM_TIMEOUT_MS);
102
- timeout.unref?.();
103
- })]);
104
- }
105
- catch {
106
- qualification = 'unavailable';
107
- }
108
- finally {
109
- if (timeout)
110
- clearTimeout(timeout);
111
- }
112
- if (runtimes.get(selfAid) !== runtime || runtime.generation !== generation || !runtime.client.isReady)
113
- return;
114
- if (qualification === 'matched')
115
- runtime.knownTeams.add(peerAid);
116
- if (qualification === 'unmatched')
117
- runtime.knownTeams.delete(peerAid);
118
- runtime.entries.set(peerAid, {
119
- qualification,
120
- expiresAt: startedAt + (qualification === 'unavailable' ? 2_000 : PA_TEAM_MAX_AGE_MS),
121
- revision: ++revision,
122
- });
123
- })();
124
- runtime.pending.set(peerAid, task);
125
- try {
126
- await task;
127
- }
128
- finally {
129
- if (runtime.pending.get(peerAid) === task)
130
- runtime.pending.delete(peerAid);
131
- }
132
- }
@@ -1,51 +0,0 @@
1
- # `ec pa-workspace`
2
-
3
- 个人助理工作区的入口导航由 Core 保存。这个命令只在当前 Agent 与其 Owner 的 AUN 私聊托管会话中可用;App 通过 `pa-workspace` Menu 查询读取结果。
4
-
5
- ## 初始化工作区
6
-
7
- ```bash
8
- ec pa-workspace init --workspace "<工作区绝对路径>"
9
- ```
10
-
11
- Core 会运行原有 `personal-assistant` Skill 初始化脚本;只有 Skill 成功完成后,Core 才登记传入的同一工作区路径并发布默认入口。目录已有非工作区内容时,Skill 会拒绝初始化且 Core 保持未绑定;确认保留现有内容并初始化后,可显式加 `--force` 重试。需要安装 Skill 自带 trigger 时可加 `--with-triggers`。
12
-
13
- 已有工作区若不需要再次运行 Skill,可用 `ec pa-workspace bind --workspace "<工作区绝对路径>"` 登记。绑定只保存访问映射,不搬动或改写工作区文件。
14
-
15
- ## 先查看当前导航
16
-
17
- ```bash
18
- ec pa-workspace navigation show
19
- ```
20
-
21
- 输出包含 `workspaceId`、`navigationRevision` 和 `entries`。`entries` 中每项至少有:
22
-
23
- - `id`:入口稳定标识;修改标题或排序时应保留
24
- - `title`:App 展示的入口名称
25
- - `path`:工作区根目录下的相对路径,不能是绝对路径、不能穿越根目录、不能指向隐藏运行时目录
26
- - `kind`:`file` 或 `directory`
27
- - `order`:数值越小越靠前
28
- - `availability`:`available` 或 `unavailable`
29
-
30
- 初始化工作区时 Core 会注册报告、任务、沉淀、对话档案、笔记和链接收藏等默认入口,即使目录暂时没有内容也会保留入口并标记为不可用。
31
-
32
- ## 更新导航
33
-
34
- 更新前必须先读取当前 revision。把完整的新入口数组作为 JSON 传入,并使用读取到的 revision 做并发校验:
35
-
36
- ```bash
37
- ec pa-workspace navigation update --expected-revision 3 --entries-json '[{"id":"reports","title":"报告","path":"output/reports","kind":"directory","order":10}]'
38
- ```
39
-
40
- 更新是完整替换,不是局部 patch。要保留的入口必须一并传回;`id` 和 `path` 不能重复。目标不存在时可以显式使用 `"availability":"unavailable"` 并提供 `"reason"`,这样可以先发布入口,目录创建后再刷新状态。
41
-
42
- 成功后 revision 会递增,返回新的导航状态。若 revision 已变化,命令返回 `CONFLICT`;重新执行 `navigation show`、合并用户仍要保留的入口后再提交,不能覆盖并发修改。
43
-
44
- ## 约束
45
-
46
- - 这是导航元数据写入,不是文件写入;App 仍然只读。
47
- - 入口路径只能落在已绑定的 PA 工作区内,Core 会再次校验真实路径和入口类型。
48
- - `bind` 只用于 PA 初始化或更换工作区,不能在普通关系、群聊或只读任务中调用。
49
- - 不要把 `manifest` 作为对象名称,也不要把绝对主机路径发给 App。
50
-
51
- 示例参数和权限行为对应 `src/cli/pa-workspace-command.ts`、`src/ipc.ts` 与 `src/core/command/pa-workspace-store.ts`。