evolcore 0.0.41-test.1 → 0.0.41

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
@@ -1,20 +1,163 @@
1
1
  import fs from 'node:fs';
2
2
  import { ownerResolver } from '../ownership/owner-resolver.js';
3
3
  import { agentFullAccessStatus, agentFullAccessWriteError } from '../role/runtime-policy.js';
4
- import { initializationSummary, validateInitializationModelArgs } from '../../cli/agent-create.js';
4
+ import { hasOrphanedInitializationMarker, initializationSummary, readInitialization, validateInitializationModelArgs } from '../../cli/agent-create.js';
5
5
  import { agentDelete, agentEnable, agentDisable, agentList, agentShow, agentSet, agentReload, } from '../../cli/agent.js';
6
6
  import { agentCreateNonInteractive } from '../../cli/agent-create.js';
7
7
  import { logger } from '../../utils/logger.js';
8
8
  import { resolvePaths, resolveRoot } from '../../paths.js';
9
9
  import path from 'path';
10
- import { ConfigTarget, ensureFile as cfgEnsure, read as cfgRead, write as cfgWrite, } from '../../config/config-manager.js';
11
- import { CreateStatusWriter, readCreateStatus } from '../message/create-status.js';
10
+ import { ConfigTarget, assertAgentAidAvailable, ensureFile as cfgEnsure, read as cfgRead, write as cfgWrite, } from '../../config/config-manager.js';
11
+ import { CreateStatusWriter, initializationCreateProgress, initializationOwnership, readCreateStatus } from '../agent-create-status.js';
12
12
  import { agentProjectRootFromDefaults, deriveAgentProjectPath } from '../../utils/project-path.js';
13
13
  import { uploadAvatar, uploadAvatarUrl } from '../../utils/avatar-upload.js';
14
14
  import { agentmdGet, agentmdPut, updateAgentMdFrontmatterName } from '../../aun/aid/agentmd.js';
15
15
  import { isValidAid } from '../../aun/aid/validation.js';
16
16
  import { isSupportedBaseagent } from '../../agents/baseagent.js';
17
17
  import { resolveProviderServiceForBaseagent } from '../../config/providers.js';
18
+ import { claimAgentCreationAsync, removeAgentCreationClaim } from '../agent-creation-claim.js';
19
+ /** Enabled by default; an explicit 0 retains the host-scoped rollback switch. */
20
+ export function appOneShotCreateEnabled(env = process.env) {
21
+ return env.EVOLCORE_APP_ONE_SHOT_CREATE !== '0';
22
+ }
23
+ export function agentCreateCapabilities(env = process.env) {
24
+ return {
25
+ legacy: true, oneShot: appOneShotCreateEnabled(env), protocolVersion: 1,
26
+ resume: true, cancel: true, exactOwnershipBinding: true, activeReadyProjection: true,
27
+ };
28
+ }
29
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
30
+ function initializationError(error) {
31
+ return { error: error instanceof Error ? error.message : String(error), code: error?.code || 'INITIALIZE_FAILED' };
32
+ }
33
+ /** Compatibility receipt and query fields are always projected from the journal. */
34
+ export function oneShotCreationView(aid, lifecycle, state) {
35
+ const record = readInitialization(aid);
36
+ if (record?.mode !== 'one_shot')
37
+ return undefined;
38
+ const config = cfgRead(ConfigTarget.Agent, { self: aid });
39
+ const progress = initializationCreateProgress(record, lifecycle, config?.initialization?.operationId);
40
+ const summary = initializationSummary(aid);
41
+ const complete = progress?.status === 'ready';
42
+ return {
43
+ mode: 'one_shot', creationId: record.creationId, operationId: record.operationId,
44
+ clientRequestId: record.clientRequestId, lifecycle: lifecycle ?? null,
45
+ initialization: { ...summary, complete, ownerAid: record.plan.ownerAid,
46
+ retryable: progress?.retryable ?? false, nextStep: progress?.nextStep ?? null },
47
+ createProgress: progress, ownership: initializationOwnership(record),
48
+ usable: complete && state?.usable === true,
49
+ ...(record.plan.avatarUrl || record.plan.avatarFile ? { avatarAccepted: true } : {}),
50
+ ...(progress?.code ? { code: progress.code } : {}),
51
+ ...(progress?.error ? { error: progress.error } : {}),
52
+ };
53
+ }
54
+ async function execOneShotCreate(a, peerId, service, subject) {
55
+ if (!service?.initialization)
56
+ return { error: '初始化服务不可用', code: 'NOT_CONFIGURED' };
57
+ if (!peerId || !isValidAid(peerId))
58
+ return { error: '缺少有效发起者 AID', code: 'INVALID_ARGS' };
59
+ if (subject && !subject.isDaemonOwner && subject.processRole !== 'daemon-service') {
60
+ return { error: '一步创建需要 DaemonOwner', code: 'NOT_ALLOWED' };
61
+ }
62
+ if (a.protocolVersion !== 1)
63
+ return { error: '不支持的一步创建协议版本', code: 'INITIALIZE_PROTOCOL_UNSUPPORTED' };
64
+ if (a.dryRun !== undefined)
65
+ return { error: '一步创建兼容入口不接受 dryRun', code: 'INVALID_ARGS' };
66
+ if (typeof a.aid !== 'string' || !isValidAid(a.aid))
67
+ return { error: '无效 Agent AID', code: 'INVALID_ARGS' };
68
+ for (const field of ['resume', 'cancel']) {
69
+ if (a[field] !== undefined && typeof a[field] !== 'boolean')
70
+ return { error: `${field} 必须是布尔值`, code: 'INVALID_ARGS' };
71
+ }
72
+ if (a.resume === true && a.cancel === true)
73
+ return { error: 'resume 与 cancel 不能同时指定', code: 'INVALID_ARGS' };
74
+ const control = a.resume === true || a.cancel === true;
75
+ if (a.clientRequestId !== undefined
76
+ && (typeof a.clientRequestId !== 'string' || !UUID_V4.test(a.clientRequestId))) {
77
+ return { error: 'clientRequestId 必须是 UUID-v4', code: 'INVALID_ARGS' };
78
+ }
79
+ if (!control && a.clientRequestId === undefined) {
80
+ return { error: 'clientRequestId 必须是 UUID-v4', code: 'INVALID_ARGS' };
81
+ }
82
+ try {
83
+ const existing = readInitialization(a.aid);
84
+ if (control) {
85
+ if (Object.keys(a).some(key => !['aid', 'initialize', 'protocolVersion', 'clientRequestId', 'resume', 'cancel', 'context'].includes(key))) {
86
+ return { error: '恢复或取消不能携带新的初始化计划', code: 'INVALID_ARGS' };
87
+ }
88
+ if (a.clientRequestId === undefined) {
89
+ return { error: '恢复或取消需要原 clientRequestId', code: 'INITIALIZE_REQUEST_ID_REQUIRED' };
90
+ }
91
+ if (!existing)
92
+ return { error: '未找到初始化操作', code: 'NOT_FOUND' };
93
+ if (existing.mode !== 'one_shot' || existing.actor !== peerId
94
+ || existing.clientRequestId !== a.clientRequestId) {
95
+ return { error: '初始化操作与本次请求不匹配', code: 'INITIALIZE_PLAN_CONFLICT' };
96
+ }
97
+ if (a.cancel === true)
98
+ await service.initialization.cancel(a.aid, peerId);
99
+ else
100
+ service.initialization.resume(a.aid, peerId, a.clientRequestId);
101
+ }
102
+ else {
103
+ // The kill switch blocks new attempts, never recovery of accepted attempts.
104
+ if (!existing && !appOneShotCreateEnabled())
105
+ return { error: '主机尚未启用一步创建', code: 'INITIALIZE_DISABLED' };
106
+ for (const field of ['name', 'baseagent', 'project', 'owner', 'description', 'provider', 'model', 'effort', 'persona', 'avatarUrl']) {
107
+ if (a[field] !== undefined && typeof a[field] !== 'string')
108
+ return { error: `${field} 必须是字符串`, code: 'INVALID_ARGS' };
109
+ }
110
+ if (a.tags !== undefined && (!Array.isArray(a.tags) || a.tags.some((tag) => typeof tag !== 'string'))) {
111
+ return { error: 'tags 必须是字符串数组', code: 'INVALID_ARGS' };
112
+ }
113
+ if (a.type !== undefined && a.type !== 'agent')
114
+ return { error: 'type 必须为 agent', code: 'INVALID_ARGS' };
115
+ if (a.plan !== undefined || a.owners !== undefined || a.ownerAid !== undefined || a.avatarFile !== undefined || a.force !== undefined) {
116
+ return { error: '一步创建兼容入口不接受 plan/owners/ownerAid/avatarFile/force', code: 'INVALID_ARGS' };
117
+ }
118
+ if (a.chatmode !== undefined && (!a.chatmode || typeof a.chatmode !== 'object' || Array.isArray(a.chatmode)
119
+ || Object.entries(a.chatmode).some(([key, value]) => !['private', 'group', 'nothuman'].includes(key) || !['interactive', 'proactive'].includes(value)))) {
120
+ return { error: 'chatmode 必须包含有效的 private/group/nothuman 模式', code: 'INVALID_ARGS' };
121
+ }
122
+ let avatarUrl;
123
+ if (a.avatarUrl !== undefined) {
124
+ try {
125
+ const url = new URL(a.avatarUrl.trim());
126
+ if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443'))
127
+ throw new Error();
128
+ avatarUrl = url.toString();
129
+ }
130
+ catch {
131
+ return { error: 'avatarUrl 必须是不含认证信息的 HTTPS URL', code: 'INVALID_ARGS' };
132
+ }
133
+ }
134
+ const effort = a.effort?.trim();
135
+ const plan = {
136
+ aid: a.aid, project: a.project ?? '', baseagent: a.baseagent?.trim() ?? '',
137
+ ownerAid: a.owner?.trim() || peerId.trim(), name: a.name?.trim() ?? '',
138
+ description: a.description?.trim() || 'EvolCore AI agent.', tags: a.tags ?? [], type: 'agent',
139
+ ...(a.provider?.trim() ? { provider: a.provider.trim() } : {}),
140
+ ...(a.model?.trim() ? { model: a.model.trim() } : {}),
141
+ ...(effort && effort !== 'auto' ? { effort } : {}),
142
+ ...(a.chatmode !== undefined ? { chatmode: a.chatmode } : {}),
143
+ ...(a.persona !== undefined ? { persona: a.persona } : {}),
144
+ ...(avatarUrl ? { avatarUrl } : {}),
145
+ };
146
+ if (!existing) {
147
+ const modelError = await validateInitializationModelArgs(plan);
148
+ if (modelError)
149
+ return modelError;
150
+ }
151
+ service.initialization.startOneShot(plan, peerId, a.clientRequestId);
152
+ }
153
+ const state = service.initialization.status(a.aid);
154
+ const lifecycle = state.lifecycle ?? service.readConfig(a.aid)?.lifecycle;
155
+ return { data: { ...state, ...oneShotCreationView(a.aid, lifecycle, state), accepted: true, aid: a.aid } };
156
+ }
157
+ catch (error) {
158
+ return initializationError(error);
159
+ }
160
+ }
18
161
  const SUPPORTED_AGENT_PATCH_FIELDS = new Set(['aid', 'name', 'avatar', 'active_baseagent', 'baseagents', 'projects', 'owner', 'owners', 'fullaccess', 'chatmode', 'channels', 'channelOwners']);
19
162
  const HIDDEN_VALUE = '[hidden]';
20
163
  const SENSITIVE_CONFIG_KEYS = new Set([
@@ -90,6 +233,12 @@ export async function execAidAvatar(args) {
90
233
  };
91
234
  }
92
235
  async function updateAgentMdName(aid, value) {
236
+ try {
237
+ assertAgentAidAvailable(aid);
238
+ }
239
+ catch (error) {
240
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
241
+ }
93
242
  const name = typeof value === 'string' ? value.trim() : '';
94
243
  if (!name)
95
244
  return { ok: false, error: 'name 不能为空', code: 'INVALID_ARGS' };
@@ -356,6 +505,9 @@ function buildCreateProgressOnlyAgent(aid, progress) {
356
505
  };
357
506
  }
358
507
  function failedCreateRetryAllowed(aid, agentDir, service) {
508
+ if (hasOrphanedInitializationMarker(aid)) {
509
+ return { allowed: false, force: false, error: '初始化状态无效,拒绝覆盖', code: 'INITIALIZE_STATE_INVALID' };
510
+ }
359
511
  const progress = readCreateStatus(agentDir);
360
512
  if ((!progress && fs.existsSync(path.join(agentDir, 'create-status.json')))
361
513
  || (progress && (!Array.isArray(progress.steps)
@@ -430,6 +582,7 @@ async function runCreateInBackground(opts, w, service) {
430
582
  // onPhase 把 agentCreateNonInteractive 内部环节(0-3、5)映射到进度文件
431
583
  const createOptions = {
432
584
  aid: opts.aid, name: opts.name, baseagent: opts.baseagent,
585
+ creationId: opts.creationId,
433
586
  project: opts.project, owner: opts.owner,
434
587
  description: opts.description,
435
588
  tags: opts.tags,
@@ -447,7 +600,7 @@ async function runCreateInBackground(opts, w, service) {
447
600
  else if (state === 'warn')
448
601
  w.warn(phase, detail);
449
602
  else if (state === 'failed')
450
- w.finishFailed(phase, detail ?? 'failed');
603
+ curPhase = phase;
451
604
  },
452
605
  };
453
606
  const res = service
@@ -456,7 +609,7 @@ async function runCreateInBackground(opts, w, service) {
456
609
  if (!('ok' in res) || res.ok !== true) {
457
610
  // Service adapters may return a failure without emitting an onPhase callback.
458
611
  const err = String(res.error || 'Agent creation failed');
459
- w.finishFailed(curPhase, err);
612
+ await w.finishFailed(curPhase, err);
460
613
  logger.warn(`[agent-control] create ${opts.aid} failed: ${err}`);
461
614
  return;
462
615
  }
@@ -518,7 +671,7 @@ async function runCreateInBackground(opts, w, service) {
518
671
  else
519
672
  w.done('applying_config');
520
673
  }
521
- w.finishReady();
674
+ await w.finishReady();
522
675
  opts.eventBus?.publish({
523
676
  type: 'agent:created',
524
677
  aid: opts.aid,
@@ -533,7 +686,7 @@ async function runCreateInBackground(opts, w, service) {
533
686
  catch (e) {
534
687
  const msg = e?.message || String(e);
535
688
  logger.warn(`[agent-control] create ${opts.aid} threw at ${curPhase}: ${msg}`);
536
- w.finishFailed(curPhase, msg); // 兜底终态,标注真实失败环节
689
+ await w.finishFailed(curPhase, msg); // 兜底终态,标注真实失败环节
537
690
  opts.eventBus?.publish({ type: 'agent:error', aid: opts.aid, action: 'create', error: msg, timestamp: Date.now() });
538
691
  }
539
692
  }
@@ -542,6 +695,15 @@ async function runCreateInBackground(opts, w, service) {
542
695
  * 调用方负责传入已兜底的 args.project(见 command-handler 装配)。 */
543
696
  export async function execAgentAction(action, args, peerId, eventBus, service, subject) {
544
697
  const a = args ?? {};
698
+ if (action === 'create') {
699
+ if (a.initialize !== undefined && typeof a.initialize !== 'boolean')
700
+ return { error: 'initialize 必须是布尔值', code: 'INVALID_ARGS' };
701
+ if (a.initialize === true)
702
+ return execOneShotCreate(a, peerId, service, subject);
703
+ if (['protocolVersion', 'clientRequestId', 'resume', 'cancel'].some(key => a[key] !== undefined)) {
704
+ return { error: '一步创建字段必须同时指定 initialize:true', code: 'INVALID_ARGS' };
705
+ }
706
+ }
545
707
  if (action === 'initialize') {
546
708
  if (!service?.initialization)
547
709
  return { error: '初始化服务不可用', code: 'NOT_CONFIGURED' };
@@ -554,11 +716,13 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
554
716
  const aid = typeof a.aid === 'string' ? a.aid.trim() : '';
555
717
  if (!aid || !isValidAid(aid))
556
718
  return { error: 'resume 需要有效的 aid', code: 'INVALID_ARGS' };
557
- if (Object.keys(a).some(key => !['aid', 'resume', 'context'].includes(key))) {
719
+ if (Object.keys(a).some(key => !['aid', 'resume', 'clientRequestId', 'context'].includes(key))) {
558
720
  return { error: '恢复请求不能携带新的初始化计划', code: 'INVALID_ARGS' };
559
721
  }
560
722
  try {
561
- return { data: service.initialization.resume(aid, peerId) };
723
+ return { data: a.clientRequestId === undefined
724
+ ? service.initialization.resume(aid, peerId)
725
+ : service.initialization.resume(aid, peerId, a.clientRequestId) };
562
726
  }
563
727
  catch (error) {
564
728
  return { error: error instanceof Error ? error.message : String(error), code: error.code || 'INITIALIZE_FAILED' };
@@ -631,6 +795,21 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
631
795
  }
632
796
  if (typeof a.aid !== 'string' || !isValidAid(a.aid))
633
797
  return { error: '无效 Agent AID', code: 'INVALID_ARGS' };
798
+ try {
799
+ assertAgentAidAvailable(a.aid);
800
+ }
801
+ catch (error) {
802
+ return { code: 'CONTROL_AID_RESERVED', error: error.message };
803
+ }
804
+ try {
805
+ if (readInitialization(a.aid))
806
+ return { error: '已有初始化记录,请恢复原操作', code: 'INITIALIZE_PLAN_CONFLICT' };
807
+ }
808
+ catch (error) {
809
+ return initializationError(error);
810
+ }
811
+ if (hasOrphanedInitializationMarker(a.aid))
812
+ return { error: '初始化状态无效,拒绝覆盖', code: 'INITIALIZE_STATE_INVALID' };
634
813
  const owner = typeof a.owner === 'string' && a.owner.trim() ? a.owner.trim() : peerId.trim();
635
814
  if (!owner)
636
815
  return { error: '缺少 owner AID', code: 'INVALID_ARGS' };
@@ -677,18 +856,41 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
677
856
  const agentDir = path.join(resolvePaths().agentsDir, a.aid);
678
857
  const retry = failedCreateRetryAllowed(a.aid, agentDir, service);
679
858
  if (!retry.allowed)
680
- return { error: retry.error || 'Agent 已存在', code: 'CONFLICT' };
859
+ return { error: retry.error || 'Agent 已存在', code: retry.code || 'CONFLICT' };
860
+ // Claim the AID in the shared admission sidecar immediately before the
861
+ // legacy progress marker is created. The one-shot initializer uses the
862
+ // same gate, so its journal cannot race this older path between check and
863
+ // marker publication.
864
+ let claim;
865
+ try {
866
+ const existingProgress = readCreateStatus(agentDir);
867
+ claim = await claimAgentCreationAsync({
868
+ aid: a.aid,
869
+ mode: 'legacy',
870
+ creationId: existingProgress?.creationId,
871
+ requesterAid: peerId,
872
+ ownerAid: owner,
873
+ }, { recoverOrphanedLegacy: true });
874
+ }
875
+ catch (error) {
876
+ return initializationError(error);
877
+ }
878
+ if (!claim.claimed) {
879
+ return { error: '该 Agent 正在创建或已有其他创建操作', code: 'INITIALIZE_PLAN_CONFLICT' };
880
+ }
681
881
  // D3: accepted=true 必须意味着后续 query 能查到该 AID 的创建状态。
682
882
  let progressWriter;
683
883
  try {
684
- progressWriter = new CreateStatusWriter(agentDir, a.aid, { requesterAid: peerId, ownerAid: owner });
884
+ progressWriter = new CreateStatusWriter(agentDir, a.aid, { requesterAid: peerId, ownerAid: owner, creationId: claim.claim.creationId });
685
885
  }
686
886
  catch (e) {
887
+ if (claim.claimed)
888
+ await removeAgentCreationClaim(a.aid, claim.claim.creationId);
687
889
  return { error: `创建进度状态初始化失败: ${e?.message || e}`, code: 'INTERNAL' };
688
890
  }
689
891
  // 重副作用转后台,后台内部有 try/catch;这里 catch 只兜底未预期拒绝。
690
892
  void runCreateInBackground({
691
- aid: a.aid, name: a.name, baseagent: a.baseagent,
893
+ aid: a.aid, name: a.name, baseagent: a.baseagent, creationId: claim.claim.creationId,
692
894
  project: a.project, owner,
693
895
  provider, model, effort, description, tags, chatmode: a.chatmode, avatarUrl,
694
896
  retryFailedCreate: retry.force,
@@ -918,15 +1120,37 @@ export async function execAgentQuery(args, service, subject) {
918
1120
  const aid = args?.aid;
919
1121
  if (!aid)
920
1122
  return { error: '缺少 aid', code: 'INVALID_ARGS' };
1123
+ if (typeof aid !== 'string' || !isValidAid(aid))
1124
+ return { error: '无效 Agent AID', code: 'INVALID_ARGS' };
921
1125
  const agentDir = path.join(resolvePaths().agentsDir, aid);
922
- const progress = readCreateStatus(agentDir);
923
1126
  const initialization = initializationSummary(aid);
1127
+ if (initialization?.code === 'INITIALIZE_STATE_INVALID') {
1128
+ return { data: {
1129
+ aid, lifecycle: service?.readConfig(aid)?.lifecycle ?? null,
1130
+ usable: false, initialization,
1131
+ } };
1132
+ }
1133
+ let oneShot;
1134
+ try {
1135
+ const record = readInitialization(aid);
1136
+ if (args?.clientRequestId !== undefined && (!record || record.clientRequestId !== args.clientRequestId
1137
+ || (subject?.actorId && record.actor !== subject.actorId))) {
1138
+ return { error: '未找到本次初始化操作', code: 'NOT_FOUND' };
1139
+ }
1140
+ oneShot = oneShotCreationView(aid, service?.readConfig(aid)?.lifecycle);
1141
+ }
1142
+ catch (error) {
1143
+ return initializationError(error);
1144
+ }
1145
+ const progress = oneShot?.createProgress ?? readCreateStatus(agentDir);
924
1146
  let usable;
925
1147
  if (initialization && service?.initialization) {
926
1148
  try {
927
1149
  const state = service.initialization.status(aid);
928
1150
  if (typeof state.usable === 'boolean')
929
1151
  usable = state.usable;
1152
+ if (oneShot)
1153
+ oneShot = oneShotCreationView(aid, state.lifecycle, state);
930
1154
  }
931
1155
  catch {
932
1156
  usable = false;
@@ -944,6 +1168,7 @@ export async function execAgentQuery(args, service, subject) {
944
1168
  lifecycle: service?.readConfig(aid)?.lifecycle ?? null,
945
1169
  initialization,
946
1170
  ...(usable === undefined ? {} : { usable }),
1171
+ ...(oneShot ?? {}),
947
1172
  },
948
1173
  };
949
1174
  if (code === 'NOT_FOUND' && progress)
@@ -978,6 +1203,7 @@ export async function execAgentQuery(args, service, subject) {
978
1203
  ...fullaccessStatus,
979
1204
  canConfigure: agentFullAccessWriteError(aid, subject) === undefined,
980
1205
  },
1206
+ ...(oneShot ? oneShotCreationView(aid, res.lifecycle ?? config?.lifecycle, { usable: usable === true }) : {}),
981
1207
  };
982
1208
  // 叠加构建进度(create 受理后、ready 前可见;ready 后文件仍在,可反映软失败 warn)
983
1209
  return { data: progress ? { ...data, createProgress: progress } : data };
@@ -1001,8 +1227,25 @@ export async function execAgentOptions(args, service) {
1001
1227
  : await agentList();
1002
1228
  if (!('ok' in res) || res.ok !== true)
1003
1229
  return { error: res.error, code: classifyError(res.error) };
1004
- const agents = scope === 'all'
1230
+ const listed = scope === 'all'
1005
1231
  ? res.agents
1006
1232
  : res.agents.filter((x) => x.status !== 'disabled');
1233
+ let agents;
1234
+ try {
1235
+ agents = listed.map((agent) => {
1236
+ const initialization = oneShotCreationView(agent.aid, agent.lifecycle);
1237
+ return initialization ? {
1238
+ ...agent,
1239
+ mode: initialization.mode,
1240
+ lifecycle: initialization.lifecycle,
1241
+ initialization: initialization.initialization,
1242
+ createProgress: initialization.createProgress,
1243
+ ownership: initialization.ownership,
1244
+ } : agent;
1245
+ });
1246
+ }
1247
+ catch (error) {
1248
+ return initializationError(error);
1249
+ }
1007
1250
  return { data: { agents, scope } };
1008
1251
  }
@@ -240,15 +240,19 @@ function parseAgentCommand(argv, source) {
240
240
  }
241
241
  function parseAidCommand(argv, source, defaultSelfAid) {
242
242
  const subcmd = argv[1];
243
- if (subcmd === 'bind') {
243
+ if (subcmd === 'bind' || subcmd === 'transfer') {
244
244
  try {
245
245
  const command = parseOwnershipCommand(argv.slice(1));
246
246
  const subjectAid = command.subjectAid ?? defaultSelfAid;
247
247
  const isMutation = command.action !== 'status';
248
- return recognized(isMutation ? 'ec.aid.bind' : 'ec.aid.bind.status', 'agent', source, {
248
+ const operation = command.action === 'transfer' ? 'ec.aid.transfer'
249
+ : isMutation ? 'ec.aid.bind' : 'ec.aid.bind.status';
250
+ return recognized(operation, 'agent', source, {
249
251
  ...(subjectAid ? { self: subjectAid } : {}),
250
252
  ...(command.subjectAid ? { subjectAid: command.subjectAid } : {}),
253
+ ...(command.action === 'status' && command.refresh ? { refresh: true } : {}),
251
254
  ...(command.action === 'bind' ? { ownerAid: command.ownerAid } : {}),
255
+ ...(command.action === 'transfer' ? { subAid: command.subAid, newOwnerAid: command.newOwnerAid } : {}),
252
256
  ...(command.action === 'accept' || command.action === 'reject'
253
257
  ? { decision: command.action, operationId: command.operationId } : {}),
254
258
  }, argv, isMutation);