evolcore 0.0.46 → 0.0.48

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 (237) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +139 -39
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +43 -18
  8. package/dist/agents/codex/app-server-client.js +32 -23
  9. package/dist/agents/codex-runner.js +31 -16
  10. package/dist/agents/ecagent-runner.js +7 -4
  11. package/dist/agents/gemini-runner.js +5 -2
  12. package/dist/agents/runner-types.js +5 -21
  13. package/dist/aun/aid/agentmd.js +5 -1
  14. package/dist/aun/group/fs-download.js +1 -1
  15. package/dist/aun/service-proxy.js +4 -2
  16. package/dist/build-identity.json +1 -0
  17. package/dist/channels/aun.js +100 -32
  18. package/dist/channels/daemon.js +10 -26
  19. package/dist/cli/aun-commands.js +86 -51
  20. package/dist/cli/code-stats.js +19 -8
  21. package/dist/cli/command-log.js +1 -1
  22. package/dist/cli/daemon-commands.js +65 -76
  23. package/dist/cli/daemon-lifecycle-client.js +17 -3
  24. package/dist/cli/directory.js +7 -1
  25. package/dist/cli/ecmsg-gateway.js +5 -2
  26. package/dist/cli/index.js +2 -8
  27. package/dist/cli/init-channel.js +6 -8
  28. package/dist/cli/init.js +74 -46
  29. package/dist/cli/invoke-command.js +1 -1
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/restart-monitor.js +104 -28
  32. package/dist/cli/role.js +61 -17
  33. package/dist/cli/stats.js +3 -3
  34. package/dist/cli/task-context.js +83 -15
  35. package/dist/cli/thread-command.js +16 -51
  36. package/dist/cli/upgrade-command.js +4 -2
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-manager.js +31 -23
  40. package/dist/config/daemon-services.js +30 -3
  41. package/dist/config/gateway-config.js +2 -2
  42. package/dist/config/invoke-ipc-service.js +6 -4
  43. package/dist/config/peer-bind-code.js +3 -4
  44. package/dist/config/peer-book-store.js +59 -218
  45. package/dist/config/peer-book.js +26 -27
  46. package/dist/config/peer-role-resolver.js +16 -1
  47. package/dist/config/provider-identity-migration.js +161 -6
  48. package/dist/config/provider-ipc-service.js +56 -11
  49. package/dist/config/provider-menu-request.js +24 -5
  50. package/dist/config/provider-templates.js +127 -0
  51. package/dist/config/providers-config.js +59 -8
  52. package/dist/config/providers-management.js +467 -49
  53. package/dist/config/role-command-service.js +248 -1
  54. package/dist/config/schema-migration.js +228 -20
  55. package/dist/config/schema-registry.js +6 -2
  56. package/dist/core/agent-application-service.js +6 -1
  57. package/dist/core/agent-runtime.js +10 -5
  58. package/dist/core/auth/agent-delegation.js +10 -4
  59. package/dist/core/auth/auth-gateway.js +2 -1
  60. package/dist/core/auth/delegation-authorization.js +3 -0
  61. package/dist/core/auth/delegation-diagnostics.js +56 -15
  62. package/dist/core/auth/operation-authorizer.js +26 -1
  63. package/dist/core/auth/operation-catalog.js +28 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/command-handler.js +81 -85
  68. package/dist/core/command/menu-catalog.js +1 -0
  69. package/dist/core/command/menu-handler.js +65 -153
  70. package/dist/core/command/menu-protocol.js +7 -1
  71. package/dist/core/command/provider-menu.js +13 -3
  72. package/dist/core/command/role-menu.js +47 -23
  73. package/dist/core/command/slash-handler.js +30 -49
  74. package/dist/core/command/team-workspace-items.js +81 -12
  75. package/dist/core/command/team-workspace-team.js +9 -71
  76. package/dist/core/command/topic-slash.js +9 -30
  77. package/dist/core/daemon-bootstrap.js +19 -10
  78. package/dist/core/daemon-control.js +8 -10
  79. package/dist/core/daemon-lifecycle.js +50 -40
  80. package/dist/core/evolagent-registry.js +22 -3
  81. package/dist/core/file-integrity/store.js +2 -0
  82. package/dist/core/handoff/runtime.js +37 -1
  83. package/dist/core/host-snapshot.js +9 -4
  84. package/dist/core/inference/text-inference.js +3 -1
  85. package/dist/core/initialization/service.js +31 -8
  86. package/dist/core/interaction-router.js +3 -0
  87. package/dist/core/invoke/executors/text.js +72 -19
  88. package/dist/core/ipc-registration.js +6 -4
  89. package/dist/core/memory/consolidation.js +6 -6
  90. package/dist/core/message/aun-ipc-sender.js +165 -55
  91. package/dist/core/message/im-renderer.js +1 -1
  92. package/dist/core/message/message-bridge.js +51 -334
  93. package/dist/core/message/message-log.js +5 -0
  94. package/dist/core/message/message-queue.js +22 -0
  95. package/dist/core/message/message-utils.js +8 -0
  96. package/dist/core/message/response-engine.js +429 -116
  97. package/dist/core/message/send-routing.js +5 -1
  98. package/dist/core/model/catalog-service.js +31 -11
  99. package/dist/core/model/model-capabilities.js +22 -4
  100. package/dist/core/model/model-catalog.js +1 -0
  101. package/dist/core/ownership/owner-resolver.js +355 -60
  102. package/dist/core/permission/protected-paths.js +6 -6
  103. package/dist/core/relation/peer-identity.js +28 -2
  104. package/dist/core/relation/same-owner-proof.js +81 -111
  105. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  106. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  107. package/dist/core/session/session-file-health.js +49 -14
  108. package/dist/core/session/session-fs-store.js +91 -35
  109. package/dist/core/session/session-manager.js +68 -24
  110. package/dist/core/session/session-mapper.js +14 -34
  111. package/dist/core/session/session-transcript.js +5 -1
  112. package/dist/core/task/task-activity-store.js +84 -0
  113. package/dist/core/task/task-image-resources.js +1 -1
  114. package/dist/core/task/task-recovery-service.js +12 -0
  115. package/dist/core/thread/command-parser.js +7 -12
  116. package/dist/core/thread/thread-context-storage.js +3 -2
  117. package/dist/core/thread/thread-operation.js +2 -13
  118. package/dist/core/thread/thread-service.js +15 -46
  119. package/dist/directory/owner-directory-admission.js +1 -1
  120. package/dist/directory/owner-directory-cache.js +45 -28
  121. package/dist/directory/owner-directory-markdown.js +13 -1
  122. package/dist/directory/owner-directory-query-operation.js +29 -3
  123. package/dist/directory/owner-directory-remarks.js +11 -3
  124. package/dist/eck/message-renderer.js +84 -24
  125. package/dist/ecweb/basic-settings-service.js +3 -1
  126. package/dist/ecweb/message-context-service.js +1 -1
  127. package/dist/ecweb/pairing.js +4 -3
  128. package/dist/ecweb/providers-service.js +26 -1
  129. package/dist/ecweb/runtime/lifecycle.js +82 -23
  130. package/dist/ecweb/runtime/proxy-access.js +74 -0
  131. package/dist/ecweb/runtime/supervisor.js +6 -17
  132. package/dist/event-center/registry.js +13 -2
  133. package/dist/event-center/runtime.js +103 -11
  134. package/dist/event-center/script-runner.js +5 -5
  135. package/dist/index.js +129 -93
  136. package/dist/ipc.js +15 -3
  137. package/dist/outputs/events.js +62 -0
  138. package/dist/outputs/protocol.js +102 -0
  139. package/dist/outputs/service.js +279 -0
  140. package/dist/paths.js +3 -0
  141. package/dist/proxy/manager.js +43 -13
  142. package/dist/services/index.js +89 -4
  143. package/dist/services/ipc-operation.js +4 -15
  144. package/dist/services/pack-manager.js +12 -1
  145. package/dist/services/router.js +21 -6
  146. package/dist/services/script-runner.js +5 -4
  147. package/dist/services/validation.js +1 -1
  148. package/dist/stats/budget.js +1 -1
  149. package/dist/stats/db.js +19 -0
  150. package/dist/stats/index.js +1 -1
  151. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  152. package/dist/stats/normalizer.js +2 -0
  153. package/dist/stats/query.js +35 -27
  154. package/dist/stats/role-budget.js +5 -2
  155. package/dist/stats/writer.js +10 -6
  156. package/dist/trigger/audit.js +7 -0
  157. package/dist/trigger/authorization.js +105 -11
  158. package/dist/trigger/feedback.js +10 -0
  159. package/dist/trigger/history.js +37 -11
  160. package/dist/trigger/ipc-service.js +12 -1
  161. package/dist/trigger/manager.js +1 -0
  162. package/dist/trigger/scheduler.js +11 -5
  163. package/dist/trigger/script-executor.js +2 -1
  164. package/dist/trigger/script-sandbox.js +9 -3
  165. package/dist/trigger/state.js +7 -0
  166. package/dist/trigger/validation.js +22 -0
  167. package/dist/utils/aid-bind.js +155 -18
  168. package/dist/utils/atomic-write.js +3 -3
  169. package/dist/utils/cross-platform.js +97 -31
  170. package/dist/utils/error-dict.json +94 -4
  171. package/dist/utils/error-utils.js +40 -4
  172. package/dist/utils/evolcore-version.js +36 -65
  173. package/dist/utils/instance-registry.js +61 -0
  174. package/dist/utils/msg-diag.js +1 -0
  175. package/dist/utils/process-introspect.js +158 -8
  176. package/dist/utils/process-tree.js +50 -2
  177. package/dist/utils/upgrade-jobs.js +4 -4
  178. package/dist/utils/windows-shell-trust.js +2 -0
  179. package/dist/workbench/protocol.js +80 -0
  180. package/dist/workbench/service.js +359 -0
  181. package/ecagent/dist/types.d.ts +6 -2
  182. package/kits/docs/context-assembly.md +1 -1
  183. package/kits/docs/evolcore/INDEX.md +2 -2
  184. package/kits/docs/evolcore/aid.md +3 -1
  185. package/kits/docs/evolcore/config.md +12 -0
  186. package/kits/docs/evolcore/directory.md +22 -3
  187. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  188. package/kits/docs/evolcore/model.md +10 -0
  189. package/kits/docs/evolcore/peer.md +19 -65
  190. package/kits/docs/evolcore/provider.md +133 -5
  191. package/kits/docs/evolcore/role.md +80 -0
  192. package/kits/docs/evolcore/services.md +6 -6
  193. package/kits/docs/evolcore/team-workspace.md +1 -1
  194. package/kits/docs/evolcore/thread-chain.md +14 -15
  195. package/kits/docs/evolcore/tool-authorization.md +5 -0
  196. package/kits/docs/evolcore/trigger.md +10 -0
  197. package/kits/eck_message_manifest.json +12 -0
  198. package/kits/provider-templates.json +1213 -0
  199. package/kits/rules/04-relation.md +3 -3
  200. package/kits/schemas/_meta.json +14 -2
  201. package/kits/schemas/contact-book.schema.4.json +52 -0
  202. package/kits/schemas/providers.schema.3.json +200 -0
  203. package/kits/skills/.switches.json +4 -0
  204. package/kits/skills/ability/references/calling.md +1 -1
  205. package/kits/skills/ec-group/SKILL.md +2 -2
  206. package/kits/skills/ec-identity/SKILL.md +19 -72
  207. package/kits/skills/ec-provider/SKILL.md +221 -0
  208. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  209. package/kits/skills/ec-trigger/SKILL.md +1 -1
  210. package/kits/skills/thread-ops/SKILL.md +34 -21
  211. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  212. package/kits/templates/message-fragments/group-batch.md +1 -1
  213. package/kits/templates/message-fragments/inject-default.md +1 -1
  214. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  215. package/kits/templates/message-fragments/item-group.md +1 -1
  216. package/kits/templates/message-fragments/item-private.md +1 -1
  217. package/kits/templates/message-fragments/thread-context.md +1 -1
  218. package/kits/templates/message-fragments/trigger-session.md +1 -1
  219. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  220. package/kits/templates/roles/admin.json +2 -19
  221. package/kits/templates/roles/member.json +0 -3
  222. package/kits/templates/system-fragments/baseagent.md +6 -0
  223. package/kits/templates/system-fragments/commands.md +3 -3
  224. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  225. package/kits/templates/system-fragments/relation.md +1 -1
  226. package/kits/templates/system-fragments/thread.md +6 -5
  227. package/package.json +6 -4
  228. package/scripts/agent-template/inspect.mjs +4 -1
  229. package/scripts/agent-template/shared/common.mjs +2 -3
  230. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  231. package/scripts/agent-template/shared/template-package.mjs +9 -2
  232. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  233. package/scripts/agent-template/team-pack.mjs +6 -3
  234. package/dist/cli/peer.js +0 -127
  235. package/dist/config/peer-operation-service.js +0 -132
  236. package/dist/config/peer-request-service.js +0 -532
  237. package/dist/core/command/connect-menu.js +0 -624
@@ -12,13 +12,17 @@
12
12
  */
13
13
  import fs from 'fs';
14
14
  import path from 'path';
15
- import Ajv from 'ajv';
15
+ import { createRequire } from 'node:module';
16
16
  import { kitsSchemasDir } from '../paths.js';
17
17
  import { createErrorCapturingReader, fileCache } from '../core/daemon-file-cache.js';
18
18
  let _ajv = null;
19
+ const requireSchemaDependency = createRequire(import.meta.url);
19
20
  function ajv() {
20
21
  if (!_ajv) {
21
- _ajv = new Ajv({ allErrors: true, strict: false, useDefaults: false });
22
+ // Version/metadata readers do not compile schemas. Keep the synchronous
23
+ // validator contract without loading Ajv into every lifecycle client.
24
+ const AjvConstructor = requireSchemaDependency('ajv');
25
+ _ajv = new AjvConstructor({ allErrors: true, strict: false, useDefaults: false });
22
26
  }
23
27
  return _ajv;
24
28
  }
@@ -7,6 +7,7 @@ import { ConfigTarget, assertAgentAidAvailable, assertAgentModelConfigured, ensu
7
7
  import { executeResolvedConfigCommand, } from '../config/config-operation-service.js';
8
8
  import { resolveConfigCommand } from '../config/resolved-config-op.js';
9
9
  import { AgentReloadBusyError } from './agent-reload-coordinator.js';
10
+ import { assertTemplateInstallationReady } from '../agent-template/jobs.js';
10
11
  import { logger } from '../utils/logger.js';
11
12
  import { initializationCreateProgress, initializationOwnership, removeAgentFiles } from './agent-create-status.js';
12
13
  import { resolveRuntimeBaseagentModelSelection } from '../agents/baseagent.js';
@@ -197,6 +198,7 @@ export class AgentApplicationService {
197
198
  async load(aid) {
198
199
  try {
199
200
  await this.deps.beforeAgentOperation?.(aid);
201
+ assertTemplateInstallationReady(aid);
200
202
  assertAgentAidAvailable(aid);
201
203
  await this.deps.hotLoad(aid);
202
204
  return { ok: true, aid };
@@ -215,6 +217,7 @@ export class AgentApplicationService {
215
217
  return { ok: true, results: await this.deps.resync() };
216
218
  }
217
219
  assertAgentAidAvailable(aid);
220
+ assertTemplateInstallationReady(aid);
218
221
  await this.deps.reload(aid, options);
219
222
  return { ok: true };
220
223
  }
@@ -290,8 +293,10 @@ export class AgentApplicationService {
290
293
  try {
291
294
  await this.deps.beforeAgentOperation?.(aid);
292
295
  guard?.();
293
- if (enabled)
296
+ if (enabled) {
294
297
  assertAgentAidAvailable(aid);
298
+ assertTemplateInstallationReady(aid);
299
+ }
295
300
  config = loadAgent(aid);
296
301
  }
297
302
  catch (error) {
@@ -235,18 +235,19 @@ export async function createStartupAgentRunners({ agentRegistry, agentLoader, se
235
235
  export async function completeStartupAgentRuntime(agentRegistry, current) {
236
236
  try {
237
237
  const { watchAgentSkills } = await import('./skill/startup.js');
238
- for (const info of agentRegistry.list()) {
239
- if (info.status === 'running')
240
- watchAgentSkills(info.aid);
238
+ for (const agent of agentRegistry.allAgents()) {
239
+ if (agent.status === 'running')
240
+ watchAgentSkills(agent.aid);
241
241
  }
242
242
  }
243
243
  catch (error) {
244
244
  logger.warn(`[skill] agent 监控注册失败: ${error instanceof Error ? error.message : String(error)}`);
245
245
  }
246
- if (agentRegistry.list().some(info => info.status === 'running')) {
246
+ const agents = agentRegistry.allAgents();
247
+ if (agents.some(agent => agent.status === 'running')) {
247
248
  return { state: 'running', error: undefined };
248
249
  }
249
- if (agentRegistry.runnableAgents().length === 0 && agentRegistry.list().length === 0) {
250
+ if (agents.length === 0) {
250
251
  return { ...current, state: 'empty' };
251
252
  }
252
253
  if (current.state === 'starting') {
@@ -733,6 +734,10 @@ const AUDITED_WORKFLOW_SHA256 = {
733
734
  '0.5.33': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
734
735
  // 0.5.34 retains this exact workflow; real SDK read/execute boundaries were revalidated.
735
736
  '0.5.34': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
737
+ // 0.5.35 adds mail/UDP-standby/pull-channel modules; workflow bytes are byte-identical.
738
+ '0.5.35': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
739
+ // 0.5.36 retains the audited workflow; installed SDK preflight and execute boundaries were revalidated.
740
+ '0.5.36': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
736
741
  };
737
742
  export function initializationBindPreflightFailure(error) {
738
743
  if (!(error instanceof Error) || error.code !== 'ECONNRESET')
@@ -27,7 +27,7 @@ export function readDelegationCredential(env = process.env) {
27
27
  return sessionToken || undefined;
28
28
  }
29
29
  export class AgentDelegationRegistry {
30
- runtimeEpoch = crypto.randomBytes(16).toString('hex');
30
+ runtimeEpoch;
31
31
  diagnostics;
32
32
  grantsByHash = new Map();
33
33
  activeHashBySession = new Map();
@@ -36,8 +36,13 @@ export class AgentDelegationRegistry {
36
36
  approvedCommandBindings = new Map();
37
37
  internalGrants = new Map();
38
38
  debugRegistry = new DebugDelegationRegistry();
39
- constructor() {
40
- this.diagnostics = new DelegationDiagnostics(this.runtimeEpoch);
39
+ constructor(runtimeEpoch = crypto.randomBytes(16).toString('hex'), diagnostics = new DelegationDiagnostics(runtimeEpoch)) {
40
+ this.runtimeEpoch = runtimeEpoch;
41
+ this.diagnostics = diagnostics;
42
+ }
43
+ static async createAsync() {
44
+ const runtimeEpoch = crypto.randomBytes(16).toString('hex');
45
+ return new AgentDelegationRegistry(runtimeEpoch, await DelegationDiagnostics.createAsync(runtimeEpoch));
41
46
  }
42
47
  getRuntimeEpoch() {
43
48
  return this.runtimeEpoch;
@@ -511,7 +516,8 @@ export function trustedExecutionIdentityInput(grant) {
511
516
  : PUBLIC_PERMISSION_MODES.includes(grant.permissionMode)
512
517
  ? grant.permissionMode
513
518
  : undefined;
514
- return { sessionId: grant.sessionId, ...(permissionMode ? { permissionMode } : {}), ...fullAccess };
519
+ return { sessionId: grant.sessionId, ...(permissionMode ? { permissionMode } : {}),
520
+ ...(grant.trustedProcessRole === 'daemon-service' ? { trustedProcessRole: 'daemon-service' } : {}), ...fullAccess };
515
521
  }
516
522
  export function hasTrustedFullAccessDelegation(grant) {
517
523
  return !!grant.executionIdentity && isValidFullAccessExecutionIdentity(grant.executionIdentity);
@@ -127,7 +127,8 @@ export async function authorizeFreshOperation(params) {
127
127
  await refreshOwnershipForAuthorization(subject.selfAid, {
128
128
  force: force || forceAgentMdEditor,
129
129
  ...(sensitive ? {} : { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS }),
130
- includeDaemon: subject.isDaemonOwner || subject.processRole === 'fullaccess-run'
130
+ includeDaemon: subject.isDaemonOwner || params.intent.operation === 'role.policy.write'
131
+ || subject.processRole === 'fullaccess-run'
131
132
  || params.intent.scope === 'process' || params.intent.scope === 'control' || force,
132
133
  allowTransient: !force && !forceAgentMdEditor,
133
134
  });
@@ -78,6 +78,9 @@ export function createDelegatedProviderOperationExecutor({ agentDelegationRegist
78
78
  let parsed;
79
79
  try {
80
80
  parsed = parseProviderCommand(params.argv);
81
+ if (parsed.templateId && parsed.operation !== 'templates' && (!parsed.file || parsed.templateInput)) {
82
+ throw new Error('Managed template operations require --file; inline parameters are only available in a host terminal');
83
+ }
81
84
  }
82
85
  catch (error) {
83
86
  return { ok: false, code: 'INVALID_ARGUMENT', error: error instanceof Error ? error.message : String(error) };
@@ -3,6 +3,8 @@ import crypto from 'node:crypto';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { StringDecoder } from 'node:string_decoder';
6
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
7
+ import { performance } from 'node:perf_hooks';
6
8
  import { isDelegationDiagnosticsEnabled } from '../../config-store.js';
7
9
  import { resolvePaths } from '../../paths.js';
8
10
  import { PRODUCT_DISPLAY_NAME } from '../../product.js';
@@ -106,15 +108,37 @@ export class DelegationDiagnostics {
106
108
  persistenceState;
107
109
  sequence = 0;
108
110
  lastWarnings = new Map();
109
- constructor(runtimeEpoch) {
111
+ constructor(runtimeEpoch, initialize = true) {
110
112
  this.runtimeEpoch = runtimeEpoch;
111
113
  const paths = resolvePaths();
112
114
  this.logDir = paths.logs;
113
115
  this.indexPath = path.join(paths.dataDir, 'delegation-diagnostics', 'index.json');
116
+ if (!initialize)
117
+ return;
114
118
  this.load();
115
119
  this.record('runtime.started');
116
120
  this.save();
117
121
  }
122
+ /** Hydrate fully before exposing the registry, yielding during history replay. */
123
+ static async createAsync(runtimeEpoch) {
124
+ const diagnostics = new DelegationDiagnostics(runtimeEpoch, false);
125
+ diagnostics.loadIndex();
126
+ let batchStarted = performance.now();
127
+ for (const state of diagnostics.scanHistory()) {
128
+ if (state !== null) {
129
+ diagnostics.restoreHistoryState(state);
130
+ continue;
131
+ }
132
+ // Each input chunk provides a checkpoint, even if it has no valid rows.
133
+ if (performance.now() - batchStarted >= 8) {
134
+ await yieldToIo();
135
+ batchStarted = performance.now();
136
+ }
137
+ }
138
+ diagnostics.record('runtime.started');
139
+ diagnostics.save();
140
+ return diagnostics;
141
+ }
118
142
  close() {
119
143
  this.writer?.close();
120
144
  }
@@ -284,6 +308,13 @@ export class DelegationDiagnostics {
284
308
  }
285
309
  }
286
310
  load() {
311
+ this.loadIndex();
312
+ for (const state of this.scanHistory()) {
313
+ if (state !== null)
314
+ this.restoreHistoryState(state);
315
+ }
316
+ }
317
+ loadIndex() {
287
318
  try {
288
319
  const index = JSON.parse(fs.readFileSync(this.indexPath, 'utf8'));
289
320
  if (index.version !== 1 || !Array.isArray(index.states))
@@ -298,16 +329,16 @@ export class DelegationDiagnostics {
298
329
  if (error.code !== 'ENOENT')
299
330
  this.warn('诊断索引读取失败,尝试从审计事件重建', error);
300
331
  }
301
- this.scanHistory(state => {
302
- if (!this.retained(state))
303
- return;
304
- const previous = this.states.get(stateKey(state));
305
- if (!previous || (state.sequence !== undefined && previous.sequence !== undefined
306
- ? state.sequence > previous.sequence : state.updatedAt > previous.updatedAt))
307
- this.store(state);
308
- });
309
332
  }
310
- scanHistory(visit) {
333
+ restoreHistoryState(state) {
334
+ if (!state || !this.retained(state))
335
+ return;
336
+ const previous = this.states.get(stateKey(state));
337
+ if (!previous || (state.sequence !== undefined && previous.sequence !== undefined
338
+ ? state.sequence > previous.sequence : state.updatedAt > previous.updatedAt))
339
+ this.store(state);
340
+ }
341
+ *scanHistory() {
311
342
  try {
312
343
  if (!fs.existsSync(this.logDir))
313
344
  return;
@@ -319,9 +350,18 @@ export class DelegationDiagnostics {
319
350
  return;
320
351
  try {
321
352
  const event = JSON.parse(line);
322
- const state = event.version === 1 ? readState(event.state) : undefined;
323
- if (state)
324
- visit(state);
353
+ const raw = event.version === 1 ? event.state : undefined;
354
+ if (!raw)
355
+ return;
356
+ // A covered revision cannot replace this key. Avoid sanitizing and
357
+ // checking retention for it again; legacy counters still use the
358
+ // timestamp comparison after normal validation.
359
+ const previous = this.states.get(stateKey(raw));
360
+ if (previous?.sequence !== undefined && typeof raw.sequence === 'number'
361
+ && Number.isSafeInteger(raw.sequence) && raw.sequence >= 0
362
+ && raw.sequence <= previous.sequence)
363
+ return;
364
+ return readState(raw);
325
365
  }
326
366
  catch (error) {
327
367
  this.warn(`忽略损坏的审计记录 ${name}`, error);
@@ -339,7 +379,7 @@ export class DelegationDiagnostics {
339
379
  let newline;
340
380
  while ((newline = pending.indexOf('\n')) >= 0) {
341
381
  if (!skipping && newline <= 64 * 1024)
342
- consume(pending.slice(0, newline));
382
+ yield consume(pending.slice(0, newline));
343
383
  pending = pending.slice(newline + 1);
344
384
  skipping = false;
345
385
  }
@@ -348,9 +388,10 @@ export class DelegationDiagnostics {
348
388
  skipping = true;
349
389
  this.warn(`忽略过长的审计记录 ${name}`, new Error('oversized record'));
350
390
  }
391
+ yield null; // End of this read, independent of record validity.
351
392
  }
352
393
  if (!skipping)
353
- consume(pending + decoder.end());
394
+ yield consume(pending + decoder.end());
354
395
  }
355
396
  catch (error) {
356
397
  this.warn(`历史审计读取失败 ${name}`, error);
@@ -5,7 +5,7 @@ import { isResolvedConfigMutation, } from '../../config/resolved-config-op.js';
5
5
  import { normalizePeer } from '../model/config-scope.js';
6
6
  import { getOperationMeta } from './operation-catalog.js';
7
7
  import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
8
- import { sameGroupAid } from '../../aun/group/index.js';
8
+ import { sameGroupAid } from '../../aun/group/identity.js';
9
9
  import { ownerResolver } from '../ownership/owner-resolver.js';
10
10
  const DAEMON_OWNER_PROCESS_OPERATIONS = new Set([
11
11
  ...['inspect', 'build', 'push', 'pull', 'preview', 'deploy', 'status', 'resume', 'cancel', 'capabilities'].map(action => 'agent.template.' + action),
@@ -133,6 +133,14 @@ function authorizeCommandInternal(ctx, resolvedConfigCommand) {
133
133
  if (isFieldConfigOperation(operation) && !resolvedConfigCommand) {
134
134
  return denyDecision(ctx, 'NOT_ALLOWED', 'Resolved config operation is required', operation, intent.scope, opMeta.dangerous);
135
135
  }
136
+ // This human card is a bound repair, never delegated provider management.
137
+ // Its callback separately verifies E2EE, card ownership and connection binding.
138
+ if (operation === 'provider.connection.repair'
139
+ && (intent.scope !== 'process' || ctx.source !== 'menu' || ctx.chatType !== 'private' || ctx.channel?.split('#')[0] !== 'aun'
140
+ || !ctx.principalId || ctx.actorId !== ctx.principalId || !ctx.isDaemonOwner
141
+ || ctx.processRole !== 'daemon-owner')) {
142
+ return denyDecision(ctx, 'NOT_ALLOWED', 'Provider connection cards require the authenticated daemon Owner', operation, intent.scope, true);
143
+ }
136
144
  if (resolvedConfigCommand
137
145
  && (resolvedConfigCommand.operationId !== operation || resolvedConfigCommand.commandScope !== intent.scope)) {
138
146
  return denyDecision(ctx, 'NOT_ALLOWED', 'Resolved config operation does not match the command intent', operation, intent.scope, opMeta.dangerous);
@@ -185,6 +193,23 @@ function authorizeCommandInternal(ctx, resolvedConfigCommand) {
185
193
  const authorizationOverride = authorizeCatalogPolicy(ctx, opMeta);
186
194
  if (authorizationOverride)
187
195
  return authorizationOverride;
196
+ // Role definitions are host policy. Relation roles, including Owner, cannot
197
+ // grant this authority through a role file. Trusted fullaccess was handled above.
198
+ if (operation === 'role.policy.write') {
199
+ if (intent.scope !== 'agent' || ctx.processRole === 'daemon-service'
200
+ || !(ctx.isDaemonOwner === true || ctx.processRole === 'daemon-owner')) {
201
+ return denyDecision(ctx, 'NOT_ALLOWED', 'Role definitions require DaemonOwner authorization', operation, intent.scope, opMeta.dangerous, 'role-policy-daemon-owner-only', 'DAEMON_OWNER_REQUIRED');
202
+ }
203
+ return { allow: true, operation, scope: intent.scope, role: 'daemon-owner',
204
+ dangerous: opMeta.dangerous, matchedRule: 'role-policy-daemon-owner-only' };
205
+ }
206
+ if (operation === 'role.assign' || operation === 'role.revoke') {
207
+ const daemonControl = ctx.fromControlChannel && ctx.isDaemonOwner === true
208
+ && ctx.processRole !== 'daemon-service';
209
+ if (!daemonControl && !(role === 'owner' && isCurrentAgentTarget(ctx))) {
210
+ return denyDecision(ctx, 'NOT_ALLOWED', 'Role assignment requires the target Agent Owner', operation, intent.scope, opMeta.dangerous, 'role-assignment-owner-only');
211
+ }
212
+ }
188
213
  if (operation === 'ec.aid.bind.status') {
189
214
  if (intent.scope !== 'agent') {
190
215
  return denyDecision(ctx, 'NOT_ALLOWED', 'Ownership status is only available for an Agent subject', operation, intent.scope, opMeta.dangerous);
@@ -144,18 +144,26 @@ const QUEUE_OPERATIONS = [['read', 'Read the current Agent message queue'], ['cl
144
144
  *
145
145
  * 参照设计文档 docs/command-execution-role-permission-design.md 第 5 节
146
146
  */
147
- const PROVIDER_OPERATIONS = ['list', 'show', 'create', 'import', 'update', 'delete', 'sync'].map(action => ({
147
+ const PROVIDER_OPERATIONS = ['list', 'show', 'templates', 'create', 'import', 'update', 'delete', 'sync'].map(action => ({
148
148
  id: 'provider.' + action,
149
- category: action === 'list' || action === 'show' ? 'read' : 'process',
150
- dangerous: action !== 'list' && action !== 'show',
149
+ category: ['list', 'show', 'templates'].includes(action) ? 'read' : 'process',
150
+ dangerous: !['list', 'show', 'templates'].includes(action),
151
151
  defaultScopes: ['process'],
152
152
  description: 'Manage the daemon Provider registry: ' + action,
153
153
  sources: action === 'sync' ? ['control']
154
- : action === 'list' || action === 'show' ? ['menu', 'control', 'ecweb', 'agent-tool'] : ['menu', 'control', 'ecweb'],
154
+ : ['list', 'show', 'templates'].includes(action) ? ['menu', 'control', 'ecweb', 'agent-tool'] : ['menu', 'control', 'ecweb'],
155
155
  authorizationPolicy: { authority: 'daemon-owner', scope: 'process', channel: 'control',
156
- allowDelegatedRead: action === 'list' || action === 'show' },
156
+ allowDelegatedRead: ['list', 'show', 'templates'].includes(action) },
157
157
  }));
158
158
  const OPERATIONS = [
159
+ { id: 'invoke.execute', category: 'process', dangerous: false, defaultScopes: ['process'],
160
+ description: 'Invoke an already configured Provider', sources: ['agent-tool', 'control'],
161
+ authorizationPolicy: { authority: 'daemon-owner', scope: 'process', channel: 'control', allowDelegatedRead: true } },
162
+ {
163
+ id: 'provider.connection.repair', category: 'process', dangerous: true, defaultScopes: ['process'],
164
+ description: 'Submit a daemon-bound Provider connection repair card', sources: ['menu'],
165
+ requiredChannelType: 'aun', requiredChatType: 'private',
166
+ },
159
167
  ...[
160
168
  ['event.center.current', 'Read event center status'],
161
169
  ['event.center.update', 'Update event center status'],
@@ -712,7 +720,7 @@ const OPERATIONS = [
712
720
  category: 'write-agent',
713
721
  dangerous: false,
714
722
  defaultScopes: ['agent'],
715
- description: 'Assign a role to a private or group relation',
723
+ description: 'Assign an existing role to defaults or a private or group relation',
716
724
  sources: ['menu', 'menu.cli', 'ecweb', 'control', 'agent-tool'],
717
725
  },
718
726
  {
@@ -729,7 +737,7 @@ const OPERATIONS = [
729
737
  dangerous: false,
730
738
  defaultScopes: ['agent'],
731
739
  description: 'Read role definitions, command permissions, default roles, and usage limits',
732
- sources: ['menu', 'ecweb', 'control'],
740
+ sources: ['menu', 'ecweb', 'control', 'agent-tool'],
733
741
  },
734
742
  {
735
743
  id: 'role.relation.read',
@@ -744,73 +752,29 @@ const OPERATIONS = [
744
752
  category: 'write-agent',
745
753
  dangerous: true,
746
754
  defaultScopes: ['agent'],
747
- description: 'Modify role definitions, command permissions, default roles, or usage limits',
748
- sources: ['menu', 'ecweb', 'control'],
749
- },
750
- {
751
- id: 'peer.read',
752
- category: 'read',
753
- dangerous: false,
754
- defaultScopes: ['agent'],
755
- description: 'Read the Agent peer registry and locally blocked peers',
756
- sources: ['agent-tool'],
755
+ description: 'Manage role definitions, command permissions, and usage limits (DaemonOwner)',
756
+ sources: ['menu', 'ecweb', 'control', 'agent-tool'],
757
757
  },
758
758
  {
759
- id: 'peer.block',
759
+ id: 'ec.directory.block',
760
760
  category: 'write-agent',
761
761
  dangerous: false,
762
762
  defaultScopes: ['agent'],
763
- description: 'Block or unblock a canonical peer on this Agent',
763
+ description: 'Manage the Agent local blacklist',
764
764
  sources: ['agent-tool'],
765
+ authorizationTarget: 'current-agent',
766
+ authorizationPolicy: { authority: 'agent-owner', permissionMode: 'bypass', mode: 'require' },
765
767
  },
766
- {
767
- id: 'connect.read',
768
- category: 'read',
769
- dangerous: false,
770
- defaultScopes: ['agent'],
771
- description: 'Read contacts, groups, assignments, or contact details',
772
- sources: ['menu', 'ecweb', 'control'],
773
- },
774
- {
775
- id: 'connect.assign',
776
- category: 'write-agent',
777
- dangerous: false,
778
- defaultScopes: ['agent'],
779
- description: 'Assign a role to a relation',
780
- sources: ['menu', 'ecweb', 'control'],
781
- },
782
- {
783
- id: 'connect.revoke',
784
- category: 'write-agent',
785
- dangerous: false,
786
- defaultScopes: ['agent'],
787
- description: 'Revoke a role assignment from a relation',
788
- sources: ['menu', 'ecweb', 'control'],
789
- },
790
- {
791
- id: 'connect.admin',
792
- category: 'write-agent',
793
- dangerous: false,
794
- defaultScopes: ['agent'],
795
- description: 'Grant or revoke admin status',
796
- sources: ['menu', 'ecweb', 'control'],
797
- },
798
- {
799
- id: 'connect.write',
800
- category: 'write-agent',
801
- dangerous: false,
802
- defaultScopes: ['agent'],
803
- description: 'Manage contacts and contact requests',
804
- sources: ['menu', 'ecweb', 'control'],
805
- },
806
- {
807
- id: 'connect.access.write',
808
- category: 'write-agent',
768
+ ...['read', 'write'].map(action => ({
769
+ id: 'agent.access.' + action,
770
+ category: action === 'read' ? 'read' : 'write-agent',
809
771
  dangerous: false,
810
772
  defaultScopes: ['agent'],
811
- description: 'Manage owner-only Agent access policy and request limit settings',
773
+ description: 'Read or modify the Agent access policy',
812
774
  sources: ['menu', 'ecweb', 'control'],
813
- },
775
+ authorizationTarget: 'current-agent',
776
+ minimumAgentRole: 'owner',
777
+ })),
814
778
  // Agent Operations
815
779
  {
816
780
  id: 'agent.list',
@@ -1,6 +1,6 @@
1
1
  import os from 'os';
2
2
  import path from 'path';
3
- import { execCodexCliSync } from '../../../agents/baseagent.js';
3
+ import { execCodexCli } from '../../../agents/baseagent.js';
4
4
  import { discoverSkillDirectories } from '../skill-discovery.js';
5
5
  function discoverSkills(ctx) {
6
6
  const roots = [
@@ -21,12 +21,11 @@ function discoverSkills(ctx) {
21
21
  }
22
22
  return out;
23
23
  }
24
- function runCodexJson(args) {
24
+ async function runCodexJson(args) {
25
25
  try {
26
- const output = execCodexCliSync(args, {
26
+ const output = await execCodexCli(args, {
27
27
  encoding: 'utf-8',
28
28
  timeout: 3000,
29
- stdio: ['ignore', 'pipe', 'pipe'],
30
29
  });
31
30
  return JSON.parse(output);
32
31
  }
@@ -83,8 +82,8 @@ function normalizeMcpServerConfig(entry) {
83
82
  }
84
83
  return Object.keys(config).length > 0 ? config : undefined;
85
84
  }
86
- function discoverMcp() {
87
- const parsed = runCodexJson(['mcp', 'list', '--json']);
85
+ async function discoverMcp() {
86
+ const parsed = await runCodexJson(['mcp', 'list', '--json']);
88
87
  const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.servers) ? parsed.servers : [];
89
88
  return list.map((entry) => {
90
89
  const id = String(entry.name ?? entry.id ?? '').trim();
@@ -101,8 +100,8 @@ function discoverMcp() {
101
100
  };
102
101
  }).filter(Boolean);
103
102
  }
104
- function discoverPlugins() {
105
- const parsed = runCodexJson(['plugin', 'list', '--json']);
103
+ async function discoverPlugins() {
104
+ const parsed = await runCodexJson(['plugin', 'list', '--json']);
106
105
  const installed = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.installed) ? parsed.installed : [];
107
106
  return installed.map((entry) => {
108
107
  const id = String(entry.id ?? entry.name ?? entry.pluginId ?? '').trim();
@@ -592,6 +592,24 @@ export function buildReloadHooks(deps) {
592
592
  },
593
593
  };
594
594
  }
595
+ export async function registerBuiltinChannelPlugins(channelLoader) {
596
+ channelLoader.register(new (await import('../channels/aun.js')).AUNChannelPlugin());
597
+ const providers = [
598
+ ['feishu', async () => new (await import('../channels/feishu.js')).FeishuChannelPlugin()],
599
+ ['wechat', async () => new (await import('../channels/wechat.js')).WechatChannelPlugin()],
600
+ ['dingtalk', async () => new (await import('../channels/dingtalk.js')).DingtalkChannelPlugin()],
601
+ ['qqbot', async () => new (await import('../channels/qqbot.js')).QQBotChannelPlugin()],
602
+ ['wecom', async () => new (await import('../channels/wecom.js')).WecomChannelPlugin()],
603
+ ];
604
+ for (const [channelType, load] of providers) {
605
+ try {
606
+ channelLoader.register(await load());
607
+ }
608
+ catch (error) {
609
+ channelLoader.recordProviderFailure(channelType, error);
610
+ }
611
+ }
612
+ }
595
613
  export class ContactBindRegistry {
596
614
  providers = new Map();
597
615
  register(channelType, provider) {
@@ -1,4 +1,6 @@
1
1
  import fs from 'node:fs';
2
+ import { readAccessPolicySnapshot, mutateAccessPolicy } from '../../config/access-policy.js';
3
+ import { refreshDirectoryMarkdown } from '../../directory/owner-directory-admission.js';
2
4
  import { ownerResolver } from '../ownership/owner-resolver.js';
3
5
  import { agentFullAccessStatus, agentFullAccessWriteError } from '../role/runtime-policy.js';
4
6
  import { hasOrphanedInitializationMarker, initializationSummary, readInitialization, validateInitializationModelArgs } from '../../cli/agent-create.js';
@@ -725,6 +727,28 @@ async function runCreateInBackground(opts, w, service) {
725
727
  * 调用方负责传入已兜底的 args.project(见 command-handler 装配)。 */
726
728
  export async function execAgentAction(action, args, peerId, eventBus, service, subject) {
727
729
  const a = args ?? {};
730
+ if (action === 'set-access') {
731
+ const resources = ['allowInternalContacts', 'allowExternalContacts', 'allowAllContacts', 'allowedAids', 'deniedAids', 'requestLimit'];
732
+ if (!isValidAid(a.aid ?? '') || !resources.includes(a.resource)
733
+ || !Object.hasOwn(a, 'value') || typeof a.accessRevision !== 'string') {
734
+ return { error: 'set-access requires aid, resource, value and accessRevision', code: 'INVALID_ARGUMENT' };
735
+ }
736
+ try {
737
+ const result = mutateAccessPolicy({
738
+ selfAid: a.aid, actorAid: subject?.principalId ?? subject?.actorId ?? '',
739
+ actorRole: subject?.role, resource: ('access.' + a.resource),
740
+ expectedAccessRevision: a.accessRevision,
741
+ update: policy => ({ ...policy, [a.resource]: a.value }),
742
+ });
743
+ if (result.changed)
744
+ refreshDirectoryMarkdown(a.aid);
745
+ return { data: result };
746
+ }
747
+ catch (error) {
748
+ return { error: error instanceof Error ? error.message : String(error),
749
+ code: error.code ?? 'ACCESS_WRITE_FAILED' };
750
+ }
751
+ }
728
752
  if (action === 'create') {
729
753
  if (a.initialize !== undefined && typeof a.initialize !== 'boolean')
730
754
  return { error: 'initialize 必须是布尔值', code: 'INVALID_ARGS' };
@@ -1167,6 +1191,14 @@ export async function execAgentQuery(args, service, subject, runtime) {
1167
1191
  return { error: '缺少 aid', code: 'INVALID_ARGS' };
1168
1192
  if (typeof aid !== 'string' || !isValidAid(aid))
1169
1193
  return { error: '无效 Agent AID', code: 'INVALID_ARGS' };
1194
+ if (args?.view === 'access') {
1195
+ try {
1196
+ return { data: readAccessPolicySnapshot(aid) };
1197
+ }
1198
+ catch (error) {
1199
+ return { error: error instanceof Error ? error.message : String(error), code: 'ACCESS_UNAVAILABLE' };
1200
+ }
1201
+ }
1170
1202
  const agentDir = path.join(resolvePaths().agentsDir, aid);
1171
1203
  const initialization = initializationSummary(aid);
1172
1204
  if (initialization?.code === 'INITIALIZE_STATE_INVALID') {