evolcore 0.0.41-test.1 → 0.0.41-test.2

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 (127) hide show
  1. package/CHANGELOG.md +49 -36
  2. package/dist/agents/baseagent.js +68 -6
  3. package/dist/agents/codex-runner.js +62 -43
  4. package/dist/aun/aid/agentmd.js +98 -11
  5. package/dist/aun/aid/client.js +1 -1
  6. package/dist/aun/aid/control-aid.js +26 -2
  7. package/dist/aun/aid/identity.js +91 -0
  8. package/dist/aun/aid/index.js +1 -1
  9. package/dist/aun/aid/managed-operation.js +1 -1
  10. package/dist/aun/aid/ownership-operation.js +23 -22
  11. package/dist/aun/menu/client.js +27 -0
  12. package/dist/aun/msg/p2p.js +3 -8
  13. package/dist/aun/service-proxy.js +17 -0
  14. package/dist/channels/aun.js +321 -34
  15. package/dist/cli/agent-command.js +5 -2
  16. package/dist/cli/agent-create.js +991 -233
  17. package/dist/cli/agent.js +49 -10
  18. package/dist/cli/aid-bind-command.js +48 -19
  19. package/dist/cli/aun-commands.js +44 -16
  20. package/dist/cli/daemon-commands.js +1 -0
  21. package/dist/cli/index.js +24 -1
  22. package/dist/cli/init-channel.js +1 -1
  23. package/dist/cli/init.js +75 -1
  24. package/dist/cli/managed-command-guard.js +13 -1
  25. package/dist/cli/provider-command.js +57 -0
  26. package/dist/cli/restart-monitor.js +4 -2
  27. package/dist/cli/stats.js +10 -3
  28. package/dist/cli/task-context.js +19 -0
  29. package/dist/config/boot-log.js +3 -2
  30. package/dist/config/config-field-policy.js +12 -7
  31. package/dist/config/config-manager.js +138 -6
  32. package/dist/config/owner-config.js +2 -2
  33. package/dist/config/peer-role-resolver.js +2 -1
  34. package/dist/config/provider-ipc-service.js +132 -0
  35. package/dist/config/provider-menu-request.js +58 -0
  36. package/dist/config/providers-management.js +78 -5
  37. package/dist/config/resolved-config-op.js +8 -1
  38. package/dist/config/schema-migration.js +322 -8
  39. package/dist/config-store.js +10 -1
  40. package/dist/contracts/ecweb-service-protocol.js +2 -1
  41. package/dist/core/agent-application-service.js +60 -11
  42. package/dist/core/agent-create-status.js +203 -0
  43. package/dist/core/agent-creation-claim.js +177 -0
  44. package/dist/core/agent-ipc-registration.js +39 -18
  45. package/dist/core/agent-runtime.js +193 -23
  46. package/dist/core/auth/agent-delegation.js +4 -2
  47. package/dist/core/auth/auth-gateway.js +66 -1
  48. package/dist/core/auth/authorization-audit.js +41 -5
  49. package/dist/core/auth/delegation-authorization.js +2 -1
  50. package/dist/core/auth/operation-authorizer.js +28 -6
  51. package/dist/core/auth/operation-catalog.js +14 -1
  52. package/dist/core/channel-loader.js +2 -0
  53. package/dist/core/command/agent-control.js +257 -14
  54. package/dist/core/command/cli-intent-parser.js +6 -2
  55. package/dist/core/command/command-handler.js +64 -55
  56. package/dist/core/command/memory-slash.js +1 -1
  57. package/dist/core/command/menu-catalog.js +5 -0
  58. package/dist/core/command/menu-handler.js +64 -18
  59. package/dist/core/command/menu-protocol.js +15 -1
  60. package/dist/core/command/provider-menu.js +46 -0
  61. package/dist/core/command/slash-handler.js +2 -1
  62. package/dist/core/daemon-control.js +18 -13
  63. package/dist/core/event-catalog.js +10 -0
  64. package/dist/core/evolagent-registry.js +3 -1
  65. package/dist/core/evolagent.js +8 -6
  66. package/dist/core/file-integrity/store.js +11 -0
  67. package/dist/core/handoff/ipc-registration.js +3 -0
  68. package/dist/core/initialization/service.js +491 -0
  69. package/dist/core/ipc-registration.js +34 -22
  70. package/dist/core/memory/consolidation-ops-records.js +95 -0
  71. package/dist/core/memory/consolidation-trigger.js +19 -2
  72. package/dist/core/memory/consolidation.js +19 -8
  73. package/dist/core/memory/memory-admin.js +1 -1
  74. package/dist/core/memory/relation-sweep.js +11 -6
  75. package/dist/core/message/aun-ipc-sender.js +73 -67
  76. package/dist/core/message/im-renderer.js +18 -0
  77. package/dist/core/message/message-bridge.js +35 -3
  78. package/dist/core/message/response-engine.js +32 -28
  79. package/dist/core/model/catalog-service.js +1 -1
  80. package/dist/core/model/config-scope.js +5 -7
  81. package/dist/core/ownership/owner-resolver.js +755 -143
  82. package/dist/core/permission/approval-gateway.js +103 -403
  83. package/dist/core/permission/ec-command-parser.js +32 -4
  84. package/dist/core/permission/index.js +1 -0
  85. package/dist/core/permission/permission-result.js +78 -0
  86. package/dist/core/permission/tool-policy.js +7 -43
  87. package/dist/core/system-session/memory.js +37 -7
  88. package/dist/directory/owner-directory-cache.js +2 -2
  89. package/dist/ecweb/init-menu.js +32 -0
  90. package/dist/index.js +17 -5
  91. package/dist/ipc.js +85 -25
  92. package/dist/paths.js +3 -0
  93. package/dist/proxy/manager.js +6 -7
  94. package/dist/trigger/authorization.js +27 -17
  95. package/dist/trigger/feedback.js +2 -3
  96. package/dist/trigger/ipc-service.js +105 -78
  97. package/dist/trigger/local-files.js +2 -1
  98. package/dist/trigger/manager.js +5 -3
  99. package/dist/trigger/scheduler.js +88 -6
  100. package/dist/utils/atomic-write.js +28 -0
  101. package/dist/utils/error-utils.js +24 -0
  102. package/dist/utils/logger.js +68 -1
  103. package/dist/utils/welcome.js +1 -1
  104. package/kits/docs/INDEX.md +1 -0
  105. package/kits/docs/aun/SDK.md +4 -1
  106. package/kits/docs/evolcore/INDEX.md +1 -0
  107. package/kits/docs/evolcore/agent.md +8 -1
  108. package/kits/docs/evolcore/aid.md +67 -17
  109. package/kits/docs/evolcore/config.md +11 -1
  110. package/kits/docs/evolcore/group.md +1 -1
  111. package/kits/docs/evolcore/provider.md +50 -0
  112. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  113. package/kits/rules/01-overview.md +3 -0
  114. package/kits/rules/04-relation.md +1 -1
  115. package/kits/schemas/_meta.json +2 -2
  116. package/kits/schemas/agent-config.schema.16.json +3 -3
  117. package/kits/schemas/relation-config.schema.11.json +17 -0
  118. package/kits/skills/.switches.json +8 -0
  119. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  120. package/kits/skills/ec-identity/SKILL.md +2 -2
  121. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  122. package/kits/skills/ec-trigger/SKILL.md +5 -13
  123. package/kits/skills/thread-ops/SKILL.md +5 -0
  124. package/kits/templates/system-fragments/venue.md +1 -1
  125. package/package.json +3 -3
  126. package/dist/core/memory/forget-log.js +0 -96
  127. package/dist/core/message/create-status.js +0 -96
package/dist/cli/stats.js CHANGED
@@ -142,9 +142,16 @@ async function resolveManagedStatsScope(flags, isJson, argv) {
142
142
  if (!selfAid || !role || role === 'none') {
143
143
  fail(isJson, 'NOT_ALLOWED', 'stats 在托管任务中需要已解析的关系身份与角色');
144
144
  }
145
- for (const flag of MANAGED_FORBIDDEN_FLAGS) {
146
- if (flags[flag])
147
- fail(isJson, 'NOT_ALLOWED', `--${flag} 在托管任务中不可用`);
145
+ const fullAccessTask = runtime?.processRole === 'fullaccess-run'
146
+ && runtime.dataScope === 'daemon' && runtime.permissionMode === 'fullaccess';
147
+ if (!fullAccessTask) {
148
+ for (const flag of MANAGED_FORBIDDEN_FLAGS) {
149
+ if (flags[flag])
150
+ fail(isJson, 'NOT_ALLOWED', `--${flag} 在托管任务中不可用`);
151
+ }
152
+ }
153
+ if (fullAccessTask) {
154
+ return { agentWide: true, agentAid: selfAid, role: 'fullaccess-run' };
148
155
  }
149
156
  if (AGENT_SCOPE_ROLES.has(role))
150
157
  return { agentWide: true, agentAid: selfAid, role };
@@ -384,6 +384,25 @@ export async function readTaskRuntimeContextFromDaemon(sessionId, timeoutMs = 50
384
384
  return undefined;
385
385
  }
386
386
  }
387
+ /**
388
+ * Fullaccess is a daemon-issued execution identity. Never infer it from the
389
+ * environment copy alone: child processes can receive that copy through an
390
+ * ordinary shell environment, while the daemon validates the bearer token and
391
+ * the live task grant before returning this context.
392
+ */
393
+ export function isTrustedFullAccessRuntimeContext(context) {
394
+ return context?.permissionMode === 'fullaccess'
395
+ && context.processRole === 'fullaccess-run'
396
+ && context.dataScope === 'daemon'
397
+ && typeof context.authorizedBy === 'string'
398
+ && context.authorizedBy.length > 0;
399
+ }
400
+ export async function readVerifiedTaskRuntimeContext(env = process.env, timeoutMs = 1_000) {
401
+ const sessionId = env.EVOLCORE_SESSION_ID;
402
+ if (!sessionId || !readDelegationCredential(env))
403
+ return undefined;
404
+ return readTaskRuntimeContextFromDaemon(sessionId, timeoutMs, env);
405
+ }
387
406
  export async function readBestTaskRuntimeContext(env = process.env) {
388
407
  const envContext = readTaskRuntimeContextFromEnv(env);
389
408
  const sessionId = env.EVOLCORE_SESSION_ID || envContext?.sessionId;
@@ -36,12 +36,13 @@ export async function prepareStartupConfig(recoverRoleMutations) {
36
36
  }
37
37
  const agentOnlyModelMigration = await ensureAgentOnlyModelMigrationOnStartup();
38
38
  if (agentOnlyModelMigration) {
39
- const message = `✓ Agent-only model migration applied automatically: removed relation/defaults model parameters from ${agentOnlyModelMigration.changedFiles} file(s)`
39
+ const message = `✓ Agent model migration applied automatically: normalized ${agentOnlyModelMigration.changedFiles} file(s), registered ${agentOnlyModelMigration.summary.defaultsBaseagentsAdded ?? 0} backend name(s) in defaults`
40
40
  + (agentOnlyModelMigration.backup ? `; backup: ${agentOnlyModelMigration.backup}` : '');
41
41
  logger.info(message);
42
42
  console.error(message);
43
43
  for (const detail of agentOnlyModelMigration.details) {
44
- logger.info(`[config] ${detail.file}: removed ${detail.removed.join(', ')}`);
44
+ const actions = [...(detail.migrated ?? []), ...detail.removed];
45
+ logger.info(`[config] ${detail.file}: ${actions.length ? actions.join(', ') : 'registered missing backend names'}`);
45
46
  }
46
47
  }
47
48
  const modelProviderMigration = await ensureAgentModelProviderMigrationOnStartup();
@@ -26,6 +26,18 @@ const BASEAGENT_BEHAVIOR_FIELDS = new Set([
26
26
  'excludeDynamicSections',
27
27
  'enableRequestUserInput',
28
28
  ]);
29
+ /** Model selection is Agent-owned; relation selectors may never read or write it. */
30
+ export function isAgentOnlyModelField(fieldPath) {
31
+ const parts = fieldPath.split('.');
32
+ return parts.length === 3
33
+ && parts[0] === 'baseagents'
34
+ && SUPPORTED_BASEAGENTS.has(parts[1])
35
+ && (parts[2] === 'model' || parts[2] === 'effort' || parts[2] === 'reasoning');
36
+ }
37
+ /** Baseagent selection is Agent-owned as well. */
38
+ export function isAgentOnlyBaseagentField(fieldPath) {
39
+ return fieldPath === 'active_baseagent' || fieldPath === 'baseagents' || isAgentOnlyModelField(fieldPath);
40
+ }
29
41
  const SUPPORTED_BASEAGENTS = new Set(['claude', 'codex', 'gemini', 'ecagent']);
30
42
  /** Public behavior fields for a runner this version does not implement. */
31
43
  export function isUnsupportedBaseagentConfigField(fieldPath) {
@@ -250,13 +262,6 @@ export function relationFieldWriteOperation(fieldPath) {
250
262
  }
251
263
  if (field === 'mentionMode')
252
264
  return 'mentionmode.update';
253
- if (/^baseagents\.[^.]+\.model$/.test(field))
254
- return 'model.use';
255
- if (/^baseagents\.[^.]+\.auxiliaryModel$/.test(field))
256
- return 'model.use';
257
- if (/^baseagents\.[^.]+\.(?:effort|reasoning|auxiliaryEffort)$/.test(field)) {
258
- return 'model.effort';
259
- }
260
265
  return undefined;
261
266
  }
262
267
  export function parseConfigFieldValue(fieldPath, rawValue) {
@@ -25,19 +25,47 @@ import { parseContactAlias } from './contact-alias.js';
25
25
  import { loadSchema, listSchemaVersions, currentVersion, isSchemaName, } from './schema-registry.js';
26
26
  import { mergeLayers } from './merge.js';
27
27
  import { normalizeAgentLifecycle } from './lifecycle.js';
28
- import { isBehaviorConfigFieldPath } from './config-field-policy.js';
28
+ import { isAgentOnlyBaseagentField, isBehaviorConfigFieldPath } from './config-field-policy.js';
29
29
  import { clearRoleStoreCache, isRoleName } from './role-store.js';
30
30
  import { writeRoleDefinition, writeRoleRegistry } from './role-service.js';
31
31
  import { mutateContactBookTransactionSync, resolveContactAidKind } from './contact-book-store.js';
32
32
  import { DAEMON_SCHEMA_NAME } from '../product.js';
33
33
  import { normalizeDaemonServices } from './daemon-services.js';
34
34
  import { assertProviderSelectionWrite, resolveProviderModelOverrides, validateProvidersFile } from './providers-config.js';
35
- import { assertOwnerConfigRecord, configuredOwnerList, firstConfiguredOwner, normalizeOwnerConfigTree, withOwnerListCompatibility } from './owner-config.js';
35
+ import { assertOwnerConfigRecord, configuredOwnerList, normalizeOwnerConfigTree, withOwnerListCompatibility } from './owner-config.js';
36
36
  import { getOwners, getPrimaryOwner, ownerResolver } from '../core/ownership/owner-resolver.js';
37
37
  // AUN gateway discovery belongs to fastaun. Keep the retired gatewayUrl
38
38
  // compatibility handling beside the rest of the configuration read/write
39
39
  // policy so all config callers share one implementation.
40
40
  const warnedLegacyGatewayFiles = new Set();
41
+ /** Control identities must never acquire an Agent runtime, regardless of their name. */
42
+ export function assertAgentAidAvailable(aid) {
43
+ if (typeof aid !== 'string')
44
+ return;
45
+ const normalized = aid.trim().toLowerCase();
46
+ const configured = atomicReadJson(resolvePaths().daemonConfig)?.aid;
47
+ // Keep the live control identity reserved until the daemon restarts after a
48
+ // daemon.json change; persisted and in-process identities can differ briefly.
49
+ const active = ownerResolver.getDaemonAid();
50
+ if ([configured, active].some(control => typeof control === 'string' && control.trim().toLowerCase() === normalized)) {
51
+ throw new ConfigError('CONTROL_AID_RESERVED', `AID "${aid}" is reserved for the daemon control identity`);
52
+ }
53
+ }
54
+ /** Only identity changes are rejected; unrelated writes can preserve a legacy conflict for diagnosis. */
55
+ export function assertControlAidAvailable(aid) {
56
+ if (typeof aid !== 'string' || !isValidAid(aid))
57
+ return;
58
+ const paths = resolvePaths();
59
+ const normalized = aid.toLowerCase();
60
+ const previous = atomicReadJson(paths.daemonConfig)?.aid;
61
+ if (typeof previous === 'string' && previous.toLowerCase() === normalized)
62
+ return;
63
+ const directories = fs.existsSync(paths.agentsDir) ? fs.readdirSync(paths.agentsDir, { withFileTypes: true }) : [];
64
+ if (directories.some(entry => entry.isDirectory() && entry.name.toLowerCase() === normalized
65
+ && fs.existsSync(path.join(paths.agentsDir, entry.name, 'config.json')))) {
66
+ throw new ConfigError('CONTROL_AID_CONFLICT', `AID "${aid}" is already registered as an Agent`);
67
+ }
68
+ }
41
69
  export function legacyAunGatewayConfigPaths(value) {
42
70
  if (!value || typeof value !== 'object' || Array.isArray(value))
43
71
  return [];
@@ -817,6 +845,30 @@ export function normalizeProcessConfigCompat(value) {
817
845
  }
818
846
  function normalizeRelationConfigForWrite(value) {
819
847
  const mutable = normalizeBaseagentEffortCompat({ ...value });
848
+ if (mutable.baseagents && typeof mutable.baseagents === 'object' && !Array.isArray(mutable.baseagents)) {
849
+ for (const rawBlock of Object.values(mutable.baseagents)) {
850
+ if (!rawBlock || typeof rawBlock !== 'object' || Array.isArray(rawBlock))
851
+ continue;
852
+ if (Object.keys(rawBlock).some(field => ['headers', 'queryParams', 'apiKey', 'baseUrl'].includes(field))) {
853
+ throw new ConfigError('READ_ONLY_LEGACY_CONFIG', 'relation baseagent gateway metadata is read-only legacy configuration; use providers.json');
854
+ }
855
+ }
856
+ }
857
+ const agentOnlyFields = ['active_baseagent', 'model', 'models']
858
+ .filter(field => Object.prototype.hasOwnProperty.call(mutable, field));
859
+ if (mutable.baseagents && typeof mutable.baseagents === 'object' && !Array.isArray(mutable.baseagents)) {
860
+ for (const [baseagent, rawBlock] of Object.entries(mutable.baseagents)) {
861
+ if (!rawBlock || typeof rawBlock !== 'object' || Array.isArray(rawBlock))
862
+ continue;
863
+ for (const field of ['model', 'effort', 'reasoning']) {
864
+ if (Object.prototype.hasOwnProperty.call(rawBlock, field))
865
+ agentOnlyFields.push(`baseagents.${baseagent}.${field}`);
866
+ }
867
+ }
868
+ }
869
+ if (agentOnlyFields.length > 0) {
870
+ throw new ConfigError('SCOPE_MISMATCH', `Relation config cannot store Agent-level model settings: ${agentOnlyFields.join(', ')}`);
871
+ }
820
872
  normalizeShowActivitiesCompat(mutable);
821
873
  return mutable;
822
874
  }
@@ -896,6 +948,13 @@ export function write(target, value, sel, opts = {}) {
896
948
  : target === ConfigTarget.Providers
897
949
  ? normalizeProvidersConfig(canonicalized)
898
950
  : canonicalized;
951
+ if (target === ConfigTarget.Agent && (normalized.enabled !== false || !fs.existsSync(file))) {
952
+ assertAgentAidAvailable(normalized.aid);
953
+ if (sel?.self)
954
+ assertAgentAidAvailable(sel.self);
955
+ }
956
+ if (target === ConfigTarget.Process)
957
+ assertControlAidAvailable(normalized.aid);
899
958
  // 1. Schema 校验
900
959
  if (!opts.skipValidate) {
901
960
  validateOrThrow(schema, normalized, target);
@@ -994,6 +1053,34 @@ export function mutateConfig(target, sel, mutate) {
994
1053
  release();
995
1054
  }
996
1055
  }
1056
+ /** Remove only the local compatibility entries matching a freshly confirmed protocol Owner. */
1057
+ export function clearConfiguredOwnerAfterConsensus(subjectAid, ownerAid) {
1058
+ const normalizedOwnerAid = ownerAid.trim();
1059
+ if (!isValidAid(normalizedOwnerAid) || subjectAid === ownerResolver.getDaemonAid())
1060
+ return false;
1061
+ const isConfirmed = () => {
1062
+ const state = ownerResolver.snapshot(subjectAid);
1063
+ return ownerResolver.owner(subjectAid) === normalizedOwnerAid && state.authorizationStatus === 'verified'
1064
+ && state.consensus?.lock === 'locked' && state.consensus.sub_aid === subjectAid && !state.refreshFailure;
1065
+ };
1066
+ if (!isConfirmed())
1067
+ return false;
1068
+ return mutateConfig(ConfigTarget.Agent, { self: subjectAid }, config => {
1069
+ if (!isConfirmed())
1070
+ return;
1071
+ if (typeof config.owner === 'string' && config.owner.trim() === normalizedOwnerAid)
1072
+ delete config.owner;
1073
+ if (!Array.isArray(config.owners))
1074
+ return;
1075
+ const owners = config.owners.filter((owner) => typeof owner !== 'string' || owner.trim() !== normalizedOwnerAid);
1076
+ if (owners.length === config.owners.length)
1077
+ return;
1078
+ if (owners.length > 0)
1079
+ config.owners = owners;
1080
+ else
1081
+ delete config.owners;
1082
+ }).changed;
1083
+ }
997
1084
  function cloneConfigValue(value) {
998
1085
  return JSON.parse(JSON.stringify(value));
999
1086
  }
@@ -1283,6 +1370,14 @@ export function validateConfig(target, value) {
1283
1370
  ...validateProcessAidDomain(target, normalized),
1284
1371
  ...validateProcessServiceNames(target, normalized),
1285
1372
  ];
1373
+ if (target === ConfigTarget.Agent) {
1374
+ try {
1375
+ assertAgentAidAvailable(normalized?.aid);
1376
+ }
1377
+ catch (error) {
1378
+ errors.push(`CONTROL_AID_RESERVED: ${error.message}`);
1379
+ }
1380
+ }
1286
1381
  if (target === ConfigTarget.Defaults || target === ConfigTarget.Agent || target === ConfigTarget.Relation) {
1287
1382
  try {
1288
1383
  validateResponseModeParams(normalized?.responseModeParams, target);
@@ -1340,6 +1435,8 @@ export function ensureFile(target, sel) {
1340
1435
  if (fs.existsSync(file))
1341
1436
  return;
1342
1437
  const skeleton = configSkeleton(target, sel);
1438
+ if (target === ConfigTarget.Agent)
1439
+ assertAgentAidAvailable(sel?.self ?? skeleton.aid);
1343
1440
  if (target === ConfigTarget.Providers) {
1344
1441
  write(target, skeleton, sel);
1345
1442
  return;
@@ -1477,7 +1574,27 @@ function stripRelationRoleData(config) {
1477
1574
  && !Object.prototype.hasOwnProperty.call(config, 'decision_model')
1478
1575
  && !Object.prototype.hasOwnProperty.call(config, 'sessionFullAccess')))
1479
1576
  return config;
1480
- const { role: _role, roles: _legacyRoles, active_baseagent: _activeBaseagent, baseagents: _baseagents, model: _model, models: _models, Services: _services, decision_model: _decisionModel, sessionFullAccess: _sessionFullAccess, ...rest } = config;
1577
+ const { role: _role, roles: _legacyRoles, active_baseagent: _activeBaseagent, model: _model, models: _models, Services: _services, decision_model: _decisionModel, sessionFullAccess: _sessionFullAccess, ...rest } = config;
1578
+ if (rest.baseagents && typeof rest.baseagents === 'object' && !Array.isArray(rest.baseagents)) {
1579
+ const baseagents = {};
1580
+ for (const [baseagent, rawBlock] of Object.entries(rest.baseagents)) {
1581
+ if (!rawBlock || typeof rawBlock !== 'object' || Array.isArray(rawBlock)) {
1582
+ baseagents[baseagent] = rawBlock;
1583
+ continue;
1584
+ }
1585
+ const block = { ...rawBlock };
1586
+ delete block.model;
1587
+ delete block.effort;
1588
+ delete block.reasoning;
1589
+ if (Object.keys(block).length > 0)
1590
+ baseagents[baseagent] = block;
1591
+ }
1592
+ const mutableRest = rest;
1593
+ if (Object.keys(baseagents).length > 0)
1594
+ mutableRest.baseagents = baseagents;
1595
+ else
1596
+ delete mutableRest.baseagents;
1597
+ }
1481
1598
  return rest;
1482
1599
  }
1483
1600
  // ── effective(合并视图)─────────────────────────────────────────────────
@@ -1495,8 +1612,8 @@ export function resolveEffective(sel, opts = {}) {
1495
1612
  lifecycle: config.lifecycle,
1496
1613
  initialized: config.initialized,
1497
1614
  initialization: config.initialization,
1498
- owner: getPrimaryOwner(sel.self ?? config.aid ?? '') ?? firstConfiguredOwner(config),
1499
- owners: [...new Set([...getOwners(sel.self ?? config.aid ?? ''), ...configuredOwnerList(config)])],
1615
+ owner: getPrimaryOwner(sel.self ?? config.aid ?? ''),
1616
+ owners: getOwners(sel.self ?? config.aid ?? ''),
1500
1617
  fullaccess: config.fullaccess,
1501
1618
  aun: config.aun,
1502
1619
  channels: config.channels ?? [],
@@ -1530,6 +1647,17 @@ export function resolveEffective(sel, opts = {}) {
1530
1647
  };
1531
1648
  return normalizeEffectiveCompatibility(effective);
1532
1649
  }
1650
+ /** Validate the same effective selection used by runtime before enabling or switching an Agent. */
1651
+ export function assertAgentModelConfigured(self, baseagent) {
1652
+ const config = resolveEffective({ self }, { cache: false });
1653
+ const backend = baseagent ?? config.active_baseagent;
1654
+ if (!backend)
1655
+ throw new ConfigError('BASEAGENT_REQUIRED', 'Configure active_baseagent before enabling this Agent');
1656
+ const model = config.baseagents?.[backend]?.model;
1657
+ if (typeof model !== 'string' || !model.trim()) {
1658
+ throw new ConfigError('MODEL_NOT_CONFIGURED', `Configure baseagents.${backend}.model before enabling or selecting this backend`);
1659
+ }
1660
+ }
1533
1661
  function normalizeEffectiveCompatibility(effective) {
1534
1662
  normalizeShowActivitiesCompat(effective);
1535
1663
  const behavior = {};
@@ -1571,6 +1699,9 @@ export function routeField(topField, scope) {
1571
1699
  */
1572
1700
  export function routeFieldPath(fieldPath, scope) {
1573
1701
  const topField = fieldPath.split('.')[0];
1702
+ if (scope === 'relation' && isAgentOnlyBaseagentField(fieldPath)) {
1703
+ throw new ConfigError('SCOPE_MISMATCH', `${fieldPath} is Agent-scoped and cannot be configured per relation`);
1704
+ }
1574
1705
  if (topField === 'sessionLoop') {
1575
1706
  throw new ConfigError('SESSION_LOOP_MANAGED', 'sessionLoop is managed through the dedicated /loop or session Menu entry');
1576
1707
  }
@@ -1687,8 +1818,9 @@ export function readConfiguredFieldWithSource(field, sel, opts = {}) {
1687
1818
  const topField = parts[0];
1688
1819
  // 按覆盖链顺序查找:relation → agent → defaults
1689
1820
  const targets = [];
1690
- if (sel.self && sel.peerKey)
1821
+ if (sel.self && sel.peerKey && !isAgentOnlyBaseagentField(field) && !['Services', 'model', 'models', 'decision_model'].includes(topField)) {
1691
1822
  targets.push(ConfigTarget.Relation);
1823
+ }
1692
1824
  if (sel.self)
1693
1825
  targets.push(ConfigTarget.Agent);
1694
1826
  targets.push(ConfigTarget.Defaults);
@@ -4,7 +4,7 @@ function normalizeOwnerValue(value) {
4
4
  const owner = value.trim();
5
5
  return owner || undefined;
6
6
  }
7
- /** Resolve the canonical owner, preferring the new scalar field. */
7
+ /** Resolve the configured binding target, preferring the new scalar field. */
8
8
  export function firstConfiguredOwner(value) {
9
9
  if (!value || typeof value !== 'object' || Array.isArray(value))
10
10
  return undefined;
@@ -21,7 +21,7 @@ export function firstConfiguredOwner(value) {
21
21
  }
22
22
  return undefined;
23
23
  }
24
- /** Runtime compatibility projection for code that still consumes an owner list. */
24
+ /** Runtime compatibility projection for binding-target input; this is not an authorization list. */
25
25
  export function configuredOwnerList(value) {
26
26
  if (!value || typeof value !== 'object' || Array.isArray(value))
27
27
  return [];
@@ -16,13 +16,14 @@ import { getOwners, ownerResolver } from '../core/ownership/owner-resolver.js';
16
16
  export function isAuthenticated(userId) {
17
17
  return isValidAid(String(userId || '').trim());
18
18
  }
19
+ /** Return the protocol Owner, or the legacy configured Owner only before any protocol relation exists. */
19
20
  export function listStaticAgentOwners(aid, opts = {}) {
20
21
  try {
21
22
  const config = read(ConfigTarget.Agent, { self: aid }, { cache: opts.fresh !== true });
22
23
  ownerResolver.setAgentConfiguredOwners(aid, configuredOwnerList(config));
23
24
  }
24
25
  catch { }
25
- return getOwners(aid);
26
+ return ownerResolver.owners(aid);
26
27
  }
27
28
  /** Direct AUN relations with role=admin are the addressable Agent admin set. */
28
29
  export function listStaticAgentAdmins(aid, opts = {}) {
@@ -0,0 +1,132 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { TextDecoder } from 'node:util';
4
+ import { auditCommandAuthorization } from '../core/auth/authorization-audit.js';
5
+ import { createProvider, parseProviderImport, readProvidersSnapshot, updateProvider } from './providers-management.js';
6
+ export const PROVIDER_INPUT_LIMIT = 1024 * 1024;
7
+ export function providerArgumentError(message) {
8
+ throw Object.assign(new Error(message), { code: 'INVALID_ARGUMENT' });
9
+ }
10
+ export function assertProviderId(value) {
11
+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/u.test(value)
12
+ || ['__proto__', 'constructor', 'prototype'].includes(value)) {
13
+ providerArgumentError('A valid Provider ID is required');
14
+ }
15
+ }
16
+ export function parseProviderCommand(argv) {
17
+ if (!Array.isArray(argv) || argv.some(value => typeof value !== 'string') || argv[0] !== 'provider') {
18
+ providerArgumentError('provider.op requires Provider argv');
19
+ }
20
+ const operation = argv[1];
21
+ if (!['list', 'show', 'create', 'import', 'update', 'delete'].includes(operation)) {
22
+ providerArgumentError('Unsupported Provider command');
23
+ }
24
+ const options = new Map();
25
+ const positional = [];
26
+ for (let index = 2; index < argv.length; index++) {
27
+ const token = argv[index];
28
+ if (!token.startsWith('-')) {
29
+ positional.push(token);
30
+ continue;
31
+ }
32
+ const separator = token.indexOf('=');
33
+ const name = separator < 0 ? token : token.slice(0, separator);
34
+ if (!['--file', '--format'].includes(name) || options.has(name))
35
+ providerArgumentError('Unknown or duplicate Provider option');
36
+ const value = separator < 0 ? argv[++index] : token.slice(separator + 1);
37
+ if (typeof value !== 'string' || !value || value.startsWith('--'))
38
+ providerArgumentError('Provider option requires a value');
39
+ options.set(name, value);
40
+ }
41
+ if (options.has('--format') && options.get('--format') !== 'json')
42
+ providerArgumentError('Only --format json is supported');
43
+ const needsId = ['show', 'update', 'delete'].includes(operation);
44
+ const needsFile = ['create', 'import', 'update'].includes(operation);
45
+ if (positional.length !== (needsId ? 1 : 0))
46
+ providerArgumentError('Unexpected or missing Provider ID');
47
+ if (needsId)
48
+ assertProviderId(positional[0]);
49
+ if (needsFile !== options.has('--file'))
50
+ providerArgumentError(needsFile ? '--file is required' : '--file is not supported by this command');
51
+ return { operation, providerId: positional[0], file: options.get('--file'), json: options.has('--format') };
52
+ }
53
+ export function parseProviderObject(text) {
54
+ if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > PROVIDER_INPUT_LIMIT) {
55
+ providerArgumentError('Provider JSON must be UTF-8 text under 1 MiB');
56
+ }
57
+ let value;
58
+ try {
59
+ value = JSON.parse(text.replace(/^\uFEFF/u, ''));
60
+ }
61
+ catch {
62
+ providerArgumentError('Provider configuration must be valid JSON');
63
+ }
64
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !Object.hasOwn(value, 'common')) {
65
+ providerArgumentError('Expected one complete Provider object');
66
+ }
67
+ return value;
68
+ }
69
+ export function providerFailure(error) {
70
+ const failure = error;
71
+ if (failure?.code === 'NOT_FOUND')
72
+ return { ok: false, code: 'NOT_FOUND', error: 'Provider not found' };
73
+ if (failure?.code === 'CONFLICT' || failure?.statusCode === 409) {
74
+ return { ok: false, code: 'CONFLICT', error: 'Provider configuration changed or is still referenced', data: failure.data };
75
+ }
76
+ if (failure?.code === 'LOCK_TIMEOUT')
77
+ return { ok: false, code: 'CONFLICT', error: 'Provider configuration is busy' };
78
+ return { ok: false, code: 'INVALID_ARGUMENT', error: 'Invalid Provider configuration or arguments; expected one valid Provider under 1 MiB' };
79
+ }
80
+ function readProviderInput(file) {
81
+ if (!path.isAbsolute(file))
82
+ providerArgumentError('Provider input path must be absolute');
83
+ const descriptor = fs.openSync(file, 'r');
84
+ try {
85
+ const stat = fs.fstatSync(descriptor);
86
+ if (!stat.isFile() || stat.size > PROVIDER_INPUT_LIMIT)
87
+ providerArgumentError('Provider input must be a file under 1 MiB');
88
+ const buffer = Buffer.alloc(PROVIDER_INPUT_LIMIT + 1);
89
+ let length = 0;
90
+ while (length < buffer.length) {
91
+ const read = fs.readSync(descriptor, buffer, length, buffer.length - length, null);
92
+ if (!read)
93
+ break;
94
+ length += read;
95
+ }
96
+ if (length > PROVIDER_INPUT_LIMIT)
97
+ providerArgumentError('Provider input exceeds 1 MiB');
98
+ return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length));
99
+ }
100
+ finally {
101
+ fs.closeSync(descriptor);
102
+ }
103
+ }
104
+ export async function executeProviderOperation(command) {
105
+ try {
106
+ const parsed = parseProviderCommand(command.argv);
107
+ auditCommandAuthorization({ ts: Date.now(), source: 'control', operation: 'provider.' + parsed.operation,
108
+ scope: 'process', dangerous: parsed.operation !== 'list' && parsed.operation !== 'show',
109
+ actorId: 'local-control', role: 'daemon-owner', processRole: 'daemon-owner', dataScope: 'daemon',
110
+ isDaemonOwner: true, fromControlChannel: true, decision: 'allow', executed: false,
111
+ argsSummary: parsed.providerId ? { providerId: parsed.providerId } : {}, matchedRule: 'local-control-token' });
112
+ const text = parsed.file ? readProviderInput(parsed.file) : undefined;
113
+ const snapshot = readProvidersSnapshot();
114
+ if (parsed.operation === 'list')
115
+ return { ok: true, data: snapshot };
116
+ if (parsed.operation === 'show') {
117
+ const provider = snapshot.providers[parsed.providerId];
118
+ if (!provider)
119
+ throw Object.assign(new Error('Provider not found'), { code: 'NOT_FOUND' });
120
+ return { ok: true, data: { providerId: parsed.providerId, provider, revision: snapshot.revision } };
121
+ }
122
+ const value = parsed.operation === 'import' ? parseProviderImport(text)
123
+ : text === undefined ? undefined : parseProviderObject(text);
124
+ const data = parsed.operation === 'create' || parsed.operation === 'import'
125
+ ? await createProvider({ revision: snapshot.revision, value })
126
+ : await updateProvider({ providerId: parsed.providerId, revision: snapshot.revision, value, remove: parsed.operation === 'delete' });
127
+ return { ok: true, data };
128
+ }
129
+ catch (error) {
130
+ return providerFailure(error);
131
+ }
132
+ }
@@ -0,0 +1,58 @@
1
+ import { assertProviderId, parseProviderObject, PROVIDER_INPUT_LIMIT, providerArgumentError } from './provider-ipc-service.js';
2
+ export function validateProviderMenuRequest(request) {
3
+ try {
4
+ if ((request.name !== undefined && request.name !== 'provider')
5
+ || (request.cmd !== undefined && request.cmd !== '/provider')
6
+ || Object.keys(request).some(key => !['type', 'id', 'name', 'cmd', 'args', 'value', 'action'].includes(key))) {
7
+ providerArgumentError('Provider requests do not accept Agent addressing or extra fields');
8
+ }
9
+ const args = request.args;
10
+ if (!args || typeof args !== 'object' || Array.isArray(args) || args.scope !== 'process') {
11
+ providerArgumentError('Provider requests require args.scope="process"');
12
+ }
13
+ if (args.context !== undefined) {
14
+ const context = args.context;
15
+ if (!context || typeof context !== 'object' || Array.isArray(context)
16
+ || context.kind !== 'process' || Object.keys(context).length !== 1) {
17
+ providerArgumentError('Provider requests only accept process context');
18
+ }
19
+ }
20
+ let fields;
21
+ if (request.type === 'menu.query' && args.view === 'list')
22
+ fields = ['view'];
23
+ else if (request.type === 'menu.query' && args.view === 'detail')
24
+ fields = ['view', 'providerId'];
25
+ else if (request.type === 'menu.update' && args.resource === 'provider')
26
+ fields = ['resource', 'providerId', 'expectedRevision'];
27
+ else if (request.type === 'menu.action' && request.action === 'create')
28
+ fields = ['expectedRevision', 'provider'];
29
+ else if (request.type === 'menu.action' && request.action === 'import')
30
+ fields = ['expectedRevision', 'text'];
31
+ else if (request.type === 'menu.action' && request.action === 'delete')
32
+ fields = ['expectedRevision', 'providerId'];
33
+ else
34
+ return { code: 'NOT_SUPPORTED', message: 'Unsupported Provider Menu method, view, resource or action' };
35
+ if (Object.keys(args).some(key => !['scope', 'context', ...fields].includes(key)))
36
+ providerArgumentError('Unknown Provider argument');
37
+ if (fields.includes('providerId'))
38
+ assertProviderId(args.providerId);
39
+ if (fields.includes('expectedRevision') && (typeof args.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/u.test(args.expectedRevision))) {
40
+ providerArgumentError('A valid args.expectedRevision is required');
41
+ }
42
+ if (request.type !== 'menu.action' && request.action !== undefined)
43
+ providerArgumentError('Unexpected Provider action');
44
+ if (request.type !== 'menu.update' && request.value !== undefined)
45
+ providerArgumentError('Unexpected Provider value');
46
+ if (request.type === 'menu.update')
47
+ parseProviderObject(request.value);
48
+ if (request.action === 'create')
49
+ parseProviderObject(JSON.stringify(args.provider));
50
+ if (request.action === 'import' && (typeof args.text !== 'string' || !args.text.trim()
51
+ || Buffer.byteLength(args.text, 'utf8') > PROVIDER_INPUT_LIMIT))
52
+ providerArgumentError('Import requires JSON text under 1 MiB');
53
+ return null;
54
+ }
55
+ catch {
56
+ return { code: 'INVALID_ARGUMENT', message: 'Invalid Provider request; use process scope, valid identifiers, revision and JSON under 1 MiB' };
57
+ }
58
+ }