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
@@ -1,13 +1,14 @@
1
- import { initializationSummary } from '../cli/agent-create.js';
1
+ import { initializationSummary, readInitialization } from '../cli/agent-create.js';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { agentMdPath, resolvePaths, } from '../paths.js';
5
5
  import { loadAgent, saveAgent, } from '../config-store.js';
6
- import { ConfigTarget, ensureFile as cfgEnsure, initConfigManager, read as cfgRead, write as cfgWrite, } from '../config/config-manager.js';
6
+ import { ConfigTarget, assertAgentAidAvailable, assertAgentModelConfigured, ensureFile as cfgEnsure, initConfigManager, notifyConfigWrite, read as cfgRead, write as cfgWrite, } from '../config/config-manager.js';
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
10
  import { logger } from '../utils/logger.js';
11
+ import { initializationCreateProgress, initializationOwnership, removeAgentFiles } from './agent-create-status.js';
11
12
  function toPosix(value) {
12
13
  if (!value)
13
14
  return null;
@@ -68,8 +69,33 @@ export class AgentApplicationService {
68
69
  async show(aid) {
69
70
  const info = this.info(aid);
70
71
  const agent = this.deps.registry.get(aid);
71
- if (!info || !agent)
72
+ if (!info || !agent) {
73
+ try {
74
+ const record = readInitialization(aid);
75
+ if (record?.mode === 'one_shot') {
76
+ const config = loadAgent(aid);
77
+ const initialization = initializationSummary(aid);
78
+ const lifecycle = config?.lifecycle ?? null;
79
+ const progress = initializationCreateProgress(record, lifecycle, config?.initialization?.operationId);
80
+ const agentDir = path.join(resolvePaths().agentsDir, aid);
81
+ return {
82
+ ok: true, aid, status: record.status === 'failed' ? 'error' : 'stopped', lifecycle,
83
+ identity: { name: record.plan.name, description: record.plan.description },
84
+ config: { baseagent: record.plan.baseagent, model: record.plan.model ?? null, effort: record.plan.effort ?? null, chatmode: record.plan.chatmode ?? null, channels: [] },
85
+ connection: null, sessions: { active: 0, last_activity: null },
86
+ paths: { config: toPosix(path.join(agentDir, 'config.json')), agent_md: toPosix(agentMdPath(aid)), project: null, data: toPosix(path.join(agentDir, 'data')) },
87
+ mode: 'one_shot', creationId: record.creationId, operationId: record.operationId, clientRequestId: record.clientRequestId,
88
+ initialization: { ...initialization, complete: progress?.status === 'ready', ownerAid: record.plan.ownerAid,
89
+ retryable: progress?.retryable ?? false, nextStep: progress?.nextStep ?? null },
90
+ createProgress: progress, ownership: initializationOwnership(record), usable: false,
91
+ };
92
+ }
93
+ }
94
+ catch (error) {
95
+ return errorFrom(error);
96
+ }
72
97
  return { ok: false, error: `Agent "${aid}" not found`, code: 'NOT_FOUND' };
98
+ }
73
99
  const aidState = (this.deps.aunAids?.() ?? []).find(state => (state.aid === aid || state.agentName === aid));
74
100
  const stats = (this.deps.aunAidStats?.() ?? []).find(snapshot => snapshot.aid === aid);
75
101
  const connection = aidState
@@ -94,6 +120,22 @@ export class AgentApplicationService {
94
120
  const lifecycle = config?.lifecycle ?? null;
95
121
  const initialization = initializationSummary(aid);
96
122
  const initializationState = initialization && this.initialization?.status(aid);
123
+ let oneShot = {};
124
+ try {
125
+ const record = readInitialization(aid);
126
+ if (record?.mode === 'one_shot') {
127
+ const progress = initializationCreateProgress(record, lifecycle, config?.initialization?.operationId);
128
+ oneShot = { mode: 'one_shot', creationId: record.creationId, operationId: record.operationId, clientRequestId: record.clientRequestId,
129
+ initialization: { ...initialization, complete: progress?.status === 'ready', ownerAid: record.plan.ownerAid,
130
+ retryable: progress?.retryable ?? false, nextStep: progress?.nextStep ?? null },
131
+ createProgress: progress, ownership: initializationOwnership(record),
132
+ usable: progress?.status === 'ready' && initializationState?.usable === true,
133
+ };
134
+ }
135
+ }
136
+ catch (error) {
137
+ return errorFrom(error);
138
+ }
97
139
  return {
98
140
  ok: true,
99
141
  aid,
@@ -114,6 +156,7 @@ export class AgentApplicationService {
114
156
  ? initializationState.usable
115
157
  : initialization.complete === true && lifecycle === 'active' && connection?.status === 'connected',
116
158
  } : {}),
159
+ ...oneShot,
117
160
  sessions: {
118
161
  active: info.activeSessions ?? 0,
119
162
  last_activity: info.lastActivity ? new Date(info.lastActivity).toISOString() : null,
@@ -127,10 +170,17 @@ export class AgentApplicationService {
127
170
  };
128
171
  }
129
172
  async create(options) {
173
+ try {
174
+ assertAgentAidAvailable(options.aid);
175
+ }
176
+ catch (error) {
177
+ return errorFrom(error);
178
+ }
130
179
  return await this.deps.create(options);
131
180
  }
132
181
  async load(aid) {
133
182
  try {
183
+ assertAgentAidAvailable(aid);
134
184
  await this.deps.hotLoad(aid);
135
185
  return { ok: true, aid };
136
186
  }
@@ -146,6 +196,7 @@ export class AgentApplicationService {
146
196
  }
147
197
  return { ok: true, results: await this.deps.resync() };
148
198
  }
199
+ assertAgentAidAvailable(aid);
149
200
  await this.deps.reload(aid, options);
150
201
  return { ok: true };
151
202
  }
@@ -217,6 +268,8 @@ export class AgentApplicationService {
217
268
  async setEnabled(aid, enabled, force) {
218
269
  let config;
219
270
  try {
271
+ if (enabled)
272
+ assertAgentAidAvailable(aid);
220
273
  config = loadAgent(aid);
221
274
  }
222
275
  catch (error) {
@@ -228,6 +281,8 @@ export class AgentApplicationService {
228
281
  await this.initialization?.cancel(aid);
229
282
  const previousEnabled = config.enabled;
230
283
  try {
284
+ if (enabled)
285
+ assertAgentModelConfigured(aid);
231
286
  config.enabled = enabled;
232
287
  saveAgent(config);
233
288
  }
@@ -261,14 +316,8 @@ export class AgentApplicationService {
261
316
  if (!fs.existsSync(configPath))
262
317
  return { ok: false, error: `Agent "${aid}" not found`, code: 'NOT_FOUND' };
263
318
  try {
264
- if (purge) {
265
- fs.rmSync(agentDir, { recursive: true, force: true });
266
- }
267
- else {
268
- fs.unlinkSync(configPath);
269
- const { removeCreateStatus } = await import('./message/create-status.js');
270
- removeCreateStatus(agentDir);
271
- }
319
+ await removeAgentFiles(aid, purge);
320
+ notifyConfigWrite(ConfigTarget.Agent, { self: aid });
272
321
  let stopped = false;
273
322
  try {
274
323
  const result = await this.resync();
@@ -0,0 +1,203 @@
1
+ /** Agent 创建状态、初始化进度投影与删除后的磁盘清理。 */
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { creationOwnershipBinding } from './ownership/owner-resolver.js';
6
+ import { readAgentCreationClaim, removeAgentCreationClaim, updateAgentCreationClaim } from './agent-creation-claim.js';
7
+ import { resolvePaths } from '../paths.js';
8
+ import { removeRegisteredFile } from './file-integrity/store.js';
9
+ const FILE = 'create-status.json';
10
+ export function readCreateStatus(agentDir) {
11
+ try {
12
+ const raw = fs.readFileSync(path.join(agentDir, FILE), 'utf-8');
13
+ return JSON.parse(raw);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ /** 删除构建进度文件(agent 删除时清理)。非 purge 删除只移除 config.json,
20
+ * 故需显式清理本文件,避免目录残留陈旧进度。 */
21
+ export function removeCreateStatus(agentDir) {
22
+ try {
23
+ fs.rmSync(path.join(agentDir, FILE), { force: true });
24
+ }
25
+ catch { /* ignore */ }
26
+ }
27
+ /** 构建进度写入器。每次状态变更原子落盘(写临时文件 + rename)。 */
28
+ export class CreateStatusWriter {
29
+ agentDir;
30
+ status;
31
+ creationId;
32
+ constructor(agentDir, aid, context) {
33
+ this.agentDir = agentDir;
34
+ this.creationId = context?.creationId ?? randomUUID();
35
+ const now = Date.now();
36
+ this.status = { aid, creationId: this.creationId, ...context, status: 'in_progress', currentPhase: null, steps: [], error: null, startedAt: now, updatedAt: now };
37
+ fs.mkdirSync(agentDir, { recursive: true });
38
+ this.flush(true);
39
+ }
40
+ begin(phase) {
41
+ this.status.currentPhase = phase;
42
+ this.status.steps.push({ phase, state: 'in_progress', ts: Date.now() });
43
+ this.flush();
44
+ }
45
+ done(phase, detail) { this.mark(phase, 'done', detail); }
46
+ warn(phase, detail) { this.mark(phase, 'warn', detail); }
47
+ /** Immutable correlation; a later CLI bind/transfer must not replace it. */
48
+ setOwnershipBinding(binding) {
49
+ const expected = creationOwnershipBinding({
50
+ operation: binding.operation, operation_id: binding.operationId,
51
+ sub_aid: binding.subjectAid, owner_aid: binding.ownerAid,
52
+ base_relation_version: binding.baseRelationVersion, target_relation_version: binding.targetRelationVersion,
53
+ status: 'pending',
54
+ }, this.status.aid, this.status.ownerAid ?? '');
55
+ if (!this.status.requesterAid || binding.source !== 'agent_create' || !expected) {
56
+ throw new Error('Creation Ownership binding does not match the creation request');
57
+ }
58
+ if (this.status.ownershipBinding) {
59
+ if (this.status.ownershipBinding.operationId !== binding.operationId) {
60
+ throw new Error('Creation Ownership binding is already recorded');
61
+ }
62
+ return;
63
+ }
64
+ if (this.status.status !== 'in_progress')
65
+ throw new Error('Agent creation has already finished');
66
+ this.status.ownershipBinding = expected;
67
+ this.flush();
68
+ }
69
+ async finishReady() {
70
+ this.status.status = 'ready';
71
+ this.status.currentPhase = null;
72
+ this.flush();
73
+ await updateAgentCreationClaim(this.status.aid, this.creationId, { status: 'ready' });
74
+ }
75
+ async finishFailed(phase, error) {
76
+ this.mark(phase, 'failed', error);
77
+ this.status.status = 'failed';
78
+ this.status.error = error;
79
+ this.status.currentPhase = null;
80
+ this.flush();
81
+ await updateAgentCreationClaim(this.status.aid, this.creationId, { status: 'failed' });
82
+ }
83
+ mark(phase, state, detail) {
84
+ const step = [...this.status.steps].reverse().find(s => s.phase === phase);
85
+ if (step) {
86
+ step.state = state;
87
+ if (detail)
88
+ step.detail = detail;
89
+ step.ts = Date.now();
90
+ }
91
+ else {
92
+ this.status.steps.push({ phase, state, detail, ts: Date.now() });
93
+ }
94
+ this.flush();
95
+ }
96
+ flush(initial = false) {
97
+ // A failed worker or a deleted Agent must not overwrite a newer creation.
98
+ if (!initial && readCreateStatus(this.agentDir)?.creationId !== this.creationId) {
99
+ throw new Error('Agent creation record was removed or replaced');
100
+ }
101
+ this.status.updatedAt = Date.now();
102
+ const file = path.join(this.agentDir, FILE);
103
+ const tmp = `${file}.tmp`;
104
+ fs.writeFileSync(tmp, JSON.stringify(this.status, null, 2));
105
+ fs.renameSync(tmp, file);
106
+ }
107
+ }
108
+ /** Shared disk cleanup for CLI and daemon deletion after initialization stops. */
109
+ export async function removeAgentFiles(aid, purge) {
110
+ const agentsDir = path.resolve(resolvePaths().agentsDir);
111
+ const agentDir = path.resolve(agentsDir, aid);
112
+ if (path.dirname(agentDir) !== agentsDir)
113
+ throw new Error('Invalid Agent directory');
114
+ const configPath = path.join(agentDir, 'config.json');
115
+ removeRegisteredFile(configPath);
116
+ for (const suffix of ['_', '__'])
117
+ fs.rmSync(configPath + suffix, { force: true });
118
+ if (purge) {
119
+ fs.rmSync(agentDir, { recursive: true, force: true });
120
+ }
121
+ else {
122
+ removeCreateStatus(agentDir);
123
+ // Preserve initialization receipts; only a legacy attempt is reusable.
124
+ const claim = readAgentCreationClaim(aid);
125
+ if (claim?.mode === 'legacy')
126
+ await removeAgentCreationClaim(aid, claim.creationId);
127
+ }
128
+ }
129
+ const PHASES = {
130
+ planned: 'validating', registering_aid: 'registering_aid', config_saved: 'config_saved',
131
+ persona_saved: 'config_saved', publishing_agentmd: 'uploading_agentmd',
132
+ verifying_agentmd: 'uploading_agentmd', uploading_agentmd: 'uploading_agentmd',
133
+ uploading_avatar: 'uploading_avatar', hot_loading: 'hot_loading',
134
+ binding_owner: 'hot_loading', ownerpending: 'hot_loading',
135
+ activating: 'applying_config', active: 'applying_config', complete: 'applying_config',
136
+ };
137
+ const STEP_ORDER = [
138
+ 'validating', 'registering_aid', 'config_saved', 'uploading_agentmd',
139
+ 'uploading_avatar', 'hot_loading', 'applying_config',
140
+ ];
141
+ /** Reconstruct completed rows from durable checkpoints, without another progress journal. */
142
+ function progressSteps(record, phase, ready, failed) {
143
+ const current = STEP_ORDER.indexOf(phase);
144
+ const avatarRequested = !!(record.plan.avatarFile || record.plan.avatarUrl);
145
+ const checkpointDone = {
146
+ validating: record.phase !== 'planned',
147
+ registering_aid: record.aidRegistered === true || record.configSaved === true, config_saved: record.configSaved,
148
+ uploading_agentmd: record.verified, uploading_avatar: record.avatarUploaded,
149
+ hot_loading: record.hotLoaded === true && record.ownerConfirmed === true, applying_config: ready,
150
+ };
151
+ return STEP_ORDER.flatMap((step, index) => {
152
+ if (step === 'uploading_avatar' && !avatarRequested)
153
+ return [];
154
+ const active = index === current && !ready && (failed || checkpointDone[step] !== true);
155
+ const done = ready || checkpointDone[step] === true;
156
+ if (!active && !done)
157
+ return [];
158
+ return [{ phase: step, state: active ? failed ? 'failed' : 'in_progress' : 'done',
159
+ ...(active ? { detail: record.phase } : {}), ts: record.updatedAt }];
160
+ });
161
+ }
162
+ /** A read-only compatibility view. The initialization journal is the only authority. */
163
+ export function initializationCreateProgress(record, lifecycle, configOperationId) {
164
+ if (!record || record.mode !== 'one_shot')
165
+ return undefined;
166
+ const targetChanged = record.status === 'complete' && lifecycle === 'active' && configOperationId !== record.operationId;
167
+ const ready = record.status === 'complete' && lifecycle === 'active' && record.ownerConfirmed === true && !targetChanged;
168
+ const failed = record.status === 'failed' || record.status === 'cancelled' || targetChanged;
169
+ // The SDK may need Owner consensus to publish the first valid agent.md. Keep
170
+ // that wait on the existing card-upload row until the profile is verified.
171
+ const waitingForInitialCard = (record.phase === 'binding_owner' || record.phase === 'ownerpending')
172
+ && record.verified !== true;
173
+ const phase = waitingForInitialCard ? 'uploading_agentmd' : PHASES[record.phase] ?? 'validating';
174
+ const code = targetChanged ? 'INITIALIZE_TARGET_CHANGED' : record.status === 'cancelled' ? 'INITIALIZE_CANCELLED' : record.code ?? null;
175
+ return {
176
+ aid: record.plan.aid, creationId: record.creationId, requesterAid: record.requesterAid,
177
+ ownerAid: record.plan.ownerAid,
178
+ ...(record.ownershipBinding ? { ownershipBinding: record.ownershipBinding } : {}),
179
+ status: ready ? 'ready' : failed ? 'failed' : 'in_progress',
180
+ currentPhase: ready || failed ? null : phase, initializationPhase: record.phase,
181
+ steps: progressSteps(record, phase, ready, failed),
182
+ error: targetChanged ? 'Initialization target no longer matches the completed operation' : failed ? record.error ?? code : record.error ?? null, code,
183
+ retryable: !targetChanged && record.status === 'failed' && record.bindAttempt?.state !== 'unknown' && code !== 'INITIALIZE_STATE_INVALID',
184
+ nextStep: ready || targetChanged || record.status === 'cancelled' ? null
185
+ : record.bindAttempt?.state === 'unknown' ? 'await_owner_consensus'
186
+ : record.phase === 'ownerpending' ? 'await_owner'
187
+ : record.status === 'failed' ? 'resume' : null,
188
+ startedAt: record.startedAt, updatedAt: record.updatedAt,
189
+ };
190
+ }
191
+ export function initializationOwnership(record) {
192
+ const consensus = record.ownerConsensus;
193
+ return {
194
+ ownerAid: consensus?.ownerAid ?? null,
195
+ consensusStatus: consensus?.consensusStatus ?? (consensus?.status === 'confirmed' ? 'consensus' : consensus?.status ?? 'unbound'),
196
+ ...(consensus?.consensusStatus !== undefined ? { gateStatus: consensus.status } : {}),
197
+ checkedAt: consensus?.checkedAt ?? null,
198
+ ...(consensus?.relationVersion !== undefined ? { relationVersion: consensus.relationVersion } : {}),
199
+ ...(consensus?.lock !== undefined ? { lock: consensus.lock } : {}),
200
+ ...(consensus?.code !== undefined ? { code: consensus.code } : {}),
201
+ ...(consensus?.retryable !== undefined ? { retryable: consensus.retryable } : {}),
202
+ };
203
+ }
@@ -0,0 +1,177 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { agentConfig, agentDataDir, agentDir, aidLocalDir, resolveRoot } from '../paths.js';
6
+ import { atomicReplaceJson, withFileLock } from '../utils/atomic-write.js';
7
+ import { isProcessRunning } from '../utils/cross-platform.js';
8
+ export function agentCreationClaimPath(aid) {
9
+ return path.join(agentDataDir(aid), 'creation-claim.json');
10
+ }
11
+ /** Outside the Agent directory so purge cannot remove an active mutex. */
12
+ export function agentCreationMutationLockPath(aid) {
13
+ return path.join(resolveRoot(), 'data', 'agent-creation-locks', `${createHash('sha256').update(aid).digest('hex')}.lock`);
14
+ }
15
+ function readRaw(file) {
16
+ try {
17
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
18
+ if (!value || value.version !== 1 || typeof value.aid !== 'string'
19
+ || typeof value.mode !== 'string' || !['legacy', 'supplied', 'one_shot'].includes(value.mode)
20
+ || !['in_progress', 'failed', 'ready'].includes(value.status)
21
+ || typeof value.creationId !== 'string' || !value.creationId)
22
+ return null;
23
+ return value;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ export function readAgentCreationClaim(aid) {
30
+ const file = agentCreationClaimPath(aid);
31
+ if (!fs.existsSync(file))
32
+ return null;
33
+ return readRaw(file);
34
+ }
35
+ function writeNew(file, claim) {
36
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
37
+ const temporary = `${file}.${process.pid}.${randomUUID()}.claim`;
38
+ try {
39
+ const fd = fs.openSync(temporary, 'wx', 0o600);
40
+ try {
41
+ fs.writeFileSync(fd, JSON.stringify(claim, null, 2) + '\n', 'utf8');
42
+ fs.fsyncSync(fd);
43
+ }
44
+ finally {
45
+ fs.closeSync(fd);
46
+ }
47
+ try {
48
+ fs.linkSync(temporary, file);
49
+ return true;
50
+ }
51
+ catch (error) {
52
+ if (error.code === 'EEXIST')
53
+ return false;
54
+ throw error;
55
+ }
56
+ }
57
+ finally {
58
+ fs.rmSync(temporary, { force: true });
59
+ }
60
+ }
61
+ function canRecoverOrphanedLegacyClaim(request, claim) {
62
+ if (claim.aid !== request.aid || claim.mode !== 'legacy' || claim.status !== 'in_progress'
63
+ || claim.host !== os.hostname() || !request.requesterAid || !request.ownerAid
64
+ || claim.requesterAid !== request.requesterAid || claim.ownerAid !== request.ownerAid
65
+ || !Number.isSafeInteger(claim.pid) || claim.pid <= 0 || isProcessRunning(claim.pid))
66
+ return false;
67
+ // A partial identity or durable progress means creation may already have effects.
68
+ return [
69
+ agentConfig(request.aid),
70
+ path.join(agentDir(request.aid), 'create-status.json'),
71
+ path.join(agentDataDir(request.aid), 'initialization.json'),
72
+ aidLocalDir(request.aid),
73
+ ].every(file => {
74
+ try {
75
+ fs.lstatSync(file);
76
+ return false;
77
+ }
78
+ catch (error) {
79
+ return error.code === 'ENOENT';
80
+ }
81
+ });
82
+ }
83
+ async function reclaimLegacyClaim(file, existing) {
84
+ const current = readRaw(file);
85
+ if (!current || current.mode !== 'legacy' || current.creationId !== existing.creationId
86
+ || current.status !== existing.status) {
87
+ return { claimed: false, claim: current ?? existing };
88
+ }
89
+ const next = {
90
+ ...current,
91
+ creationId: randomUUID(),
92
+ status: 'in_progress',
93
+ pid: process.pid,
94
+ host: os.hostname(),
95
+ startedAt: Date.now(),
96
+ updatedAt: Date.now(),
97
+ };
98
+ await atomicReplaceJson(file, next);
99
+ return { claimed: true, claim: next };
100
+ }
101
+ /**
102
+ * Atomically admit a new AID or observe its existing reservation. Matching
103
+ * initializers can complete journal publication with the reserved IDs.
104
+ * Legacy retries use the async API below to serialize failed-claim updates.
105
+ */
106
+ export function claimAgentCreation(request) {
107
+ return claimAgentCreationLocked(request);
108
+ }
109
+ /** Creator entry points may also reconcile an abandoned legacy reservation with no creation output. */
110
+ export async function claimAgentCreationAsync(request, options = {}) {
111
+ const initial = claimAgentCreationLocked(request);
112
+ if (initial.claimed || request.mode !== 'legacy' || initial.claim.mode !== 'legacy'
113
+ || (initial.claim.status !== 'failed'
114
+ && !(options.recoverOrphanedLegacy && canRecoverOrphanedLegacyClaim(request, initial.claim))))
115
+ return initial;
116
+ return withFileLock(agentCreationMutationLockPath(request.aid), async () => {
117
+ const file = agentCreationClaimPath(request.aid);
118
+ const current = readRaw(file);
119
+ if (!current || current.mode !== 'legacy'
120
+ || (current.status !== 'failed'
121
+ && !(options.recoverOrphanedLegacy && canRecoverOrphanedLegacyClaim(request, current)))) {
122
+ return { claimed: false, claim: current ?? initial.claim };
123
+ }
124
+ return reclaimLegacyClaim(file, current);
125
+ });
126
+ }
127
+ function claimAgentCreationLocked(request) {
128
+ const now = Date.now();
129
+ const claim = {
130
+ version: 1,
131
+ aid: request.aid,
132
+ mode: request.mode,
133
+ status: 'in_progress',
134
+ creationId: request.creationId ?? randomUUID(),
135
+ ...(request.operationId ? { operationId: request.operationId } : {}),
136
+ ...(request.actor ? { actor: request.actor } : {}),
137
+ ...(request.requesterAid ? { requesterAid: request.requesterAid } : {}),
138
+ ...(request.ownerAid ? { ownerAid: request.ownerAid } : {}),
139
+ ...(request.clientRequestId ? { clientRequestId: request.clientRequestId } : {}),
140
+ ...(request.fingerprint ? { fingerprint: request.fingerprint } : {}),
141
+ pid: process.pid,
142
+ host: os.hostname(),
143
+ startedAt: now,
144
+ updatedAt: now,
145
+ };
146
+ const file = agentCreationClaimPath(request.aid);
147
+ if (writeNew(file, claim))
148
+ return { claimed: true, claim };
149
+ const existing = readRaw(file);
150
+ if (!existing) {
151
+ // A malformed claim is fail-closed. Do not replace it after another
152
+ // process has observed the same path, because that would reopen the race.
153
+ throw Object.assign(new Error('Agent creation claim is invalid'), { code: 'INITIALIZE_STATE_INVALID' });
154
+ }
155
+ return { claimed: false, claim: existing };
156
+ }
157
+ export function updateAgentCreationClaim(aid, identity, patch) {
158
+ return withFileLock(agentCreationMutationLockPath(aid), async () => {
159
+ const file = agentCreationClaimPath(aid);
160
+ const current = readRaw(file);
161
+ if (!current || (current.creationId !== identity && current.operationId !== identity))
162
+ return;
163
+ const next = { ...current, ...patch, updatedAt: patch.updatedAt ?? Date.now() };
164
+ await atomicReplaceJson(file, next);
165
+ });
166
+ }
167
+ export function removeAgentCreationClaim(aid, creationId) {
168
+ return withFileLock(agentCreationMutationLockPath(aid), async () => {
169
+ const file = agentCreationClaimPath(aid);
170
+ if (creationId) {
171
+ const current = readRaw(file);
172
+ if (!current || current.creationId !== creationId)
173
+ return;
174
+ }
175
+ fs.rmSync(file, { force: true });
176
+ });
177
+ }
@@ -1,7 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { parseAgentWelcomeArgs, parseInitializationArgs, resolveAgentCreateMode, resolveInitializationPlan, readInitializationPersona, } from '../cli/agent-create.js';
4
- import { trustedExecutionIdentityInput } from './auth/agent-delegation.js';
4
+ import { hasTrustedFullAccessDelegation, trustedExecutionIdentityInput } from './auth/agent-delegation.js';
5
5
  import { authorizeFreshOperation as authorizeOperation, buildAuthSubject } from './auth/auth-gateway.js';
6
6
  import { getDaemonOwners } from './ownership/owner-resolver.js';
7
7
  import { authorizationDenialData } from './auth/authorization-denial.js';
@@ -137,17 +137,26 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
137
137
  const result = await execAgentOptions({ options: 'all' }, agentApplicationService);
138
138
  if ('error' in result)
139
139
  return fail(result.code, result.error);
140
- const agents = Array.isArray(result.data?.agents) ? result.data.agents.map((agent) => ({
141
- aid: agent.aid,
142
- name: agent.name,
143
- personalName: agent.personalName ?? null,
144
- status: agent.status,
145
- channels: Array.isArray(agent.channels) ? agent.channels : [],
146
- projectPath: null,
147
- baseagent: agent.baseagent ?? null,
148
- model: agent.model ?? null,
149
- lastActivity: agent.lastActivity ?? null,
150
- })) : [];
140
+ const agents = Array.isArray(result.data?.agents) ? result.data.agents.map((agent) => {
141
+ return {
142
+ aid: agent.aid,
143
+ name: agent.name,
144
+ personalName: agent.personalName ?? null,
145
+ status: agent.status,
146
+ channels: Array.isArray(agent.channels) ? agent.channels : [],
147
+ projectPath: null,
148
+ baseagent: agent.baseagent ?? null,
149
+ model: agent.model ?? null,
150
+ lastActivity: agent.lastActivity ?? null,
151
+ ...(agent.mode === 'one_shot' ? {
152
+ mode: agent.mode,
153
+ lifecycle: agent.lifecycle,
154
+ initialization: agent.initialization,
155
+ createProgress: agent.createProgress,
156
+ ownership: agent.ownership,
157
+ } : {}),
158
+ };
159
+ }) : [];
151
160
  return { ok: true, result: { ok: true, agents, redacted: true } };
152
161
  }
153
162
  if (operation === 'agent.show') {
@@ -258,10 +267,6 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
258
267
  try {
259
268
  const parsed = parseInitializationArgs(argv.slice(1));
260
269
  const actor = delegation.grant.actorId;
261
- if (parsed.resume) {
262
- agentInitializationService.resume(parsed.aid, actor);
263
- return { ok: true, result: await agentInitializationService.wait(parsed.aid, parsed.wait) };
264
- }
265
270
  const createPermission = await authorizeOperation({
266
271
  source: 'agent-tool', subject,
267
272
  intent: { operation: 'agent.create', scope: 'control', source: 'agent-tool', args: { aid: parsed.aid } },
@@ -269,6 +274,13 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
269
274
  });
270
275
  if (!createPermission.allow)
271
276
  return fail(createPermission.code, createPermission.reason);
277
+ if (parsed.resume) {
278
+ if (parsed.clientRequestId === undefined)
279
+ agentInitializationService.resume(parsed.aid, actor);
280
+ else
281
+ agentInitializationService.resume(parsed.aid, actor, parsed.clientRequestId);
282
+ return { ok: true, result: await agentInitializationService.wait(parsed.aid, parsed.wait) };
283
+ }
272
284
  if (!argv.includes('--owner'))
273
285
  return fail('INITIALIZE_OWNER_MISMATCH', 'Explicit --owner is required');
274
286
  const plan = resolveInitializationPlan(argv.slice(1), {
@@ -289,7 +301,8 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
289
301
  .filter((root) => !!root && path.isAbsolute(root))
290
302
  .map(root => fs.realpathSync(root));
291
303
  const real = fs.realpathSync(candidate);
292
- if (!roots.some(root => isSameOrDescendant(real, root)) || isHClassPath(real) || isLClassPath(real)) {
304
+ if (!roots.some(root => isSameOrDescendant(real, root))
305
+ || (!hasTrustedFullAccessDelegation(delegation.grant) && (isHClassPath(real) || isLClassPath(real)))) {
293
306
  return fail('AVATAR_INVALID', '--avatar-file must be a current project/TMPDIR file or authorized relation attachment');
294
307
  }
295
308
  plan.avatarFile = real;
@@ -305,6 +318,13 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
305
318
  const aid = argv[2] && !argv[2].startsWith('--') ? argv[2] : undefined;
306
319
  if (!aid)
307
320
  return fail('INVALID_ARGS', 'ec agent new requires an AID');
321
+ const { assertAgentAidAvailable } = await import('../config/config-manager.js');
322
+ try {
323
+ assertAgentAidAvailable(aid);
324
+ }
325
+ catch (error) {
326
+ return fail('CONTROL_AID_RESERVED', error.message);
327
+ }
308
328
  const { agentCreateNonInteractive, resolveAgentCreatePlan, validateAgentCreatePlan, parseAgentOwnerArgs, parseAgentTags } = await import('../cli/agent-create.js');
309
329
  let ownerOptions;
310
330
  try {
@@ -367,7 +387,8 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
367
387
  .filter((root) => !!root && path.isAbsolute(root))
368
388
  .map(root => fs.realpathSync(root));
369
389
  const real = fs.realpathSync(candidate);
370
- if (!roots.some(root => isSameOrDescendant(real, root)) || isHClassPath(real) || isLClassPath(real)) {
390
+ if (!roots.some(root => isSameOrDescendant(real, root))
391
+ || (!hasTrustedFullAccessDelegation(delegation.grant) && (isHClassPath(real) || isLClassPath(real)))) {
371
392
  return fail('AVATAR_INVALID', '--avatar-file must be a current project/TMPDIR file or authorized relation attachment');
372
393
  }
373
394
  createOptions.avatarFile = real;