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,28 +1,30 @@
1
1
  import fs from 'fs';
2
- import { randomBytes, createHash } from 'crypto';
2
+ import { randomBytes, randomUUID, createHash } from 'crypto';
3
3
  import path from 'path';
4
4
  import readline from 'readline';
5
5
  import { parse } from 'yaml';
6
6
  import { resolvePaths, aunPath as defaultAunPath, agentConfig, agentDataDir, agentPersonalDir, aidLocalDir, agentMdPath } from '../paths.js';
7
7
  import { loadDefaults, loadAgent, saveAgent, ensureAgentDirSkeleton } from '../config-store.js';
8
- import { ConfigTarget, write as cfgWrite, ensureFile as cfgEnsure, read as cfgRead } from '../config/config-manager.js';
8
+ import { ConfigTarget, assertAgentAidAvailable, write as cfgWrite, ensureFile as cfgEnsure, read as cfgRead } from '../config/config-manager.js';
9
9
  import { daemonUnavailableMessage, queryDaemon } from './help.js';
10
- import { ipcQuery } from '../ipc.js';
10
+ import { ipcHostQuery, ipcQuery } from '../ipc.js';
11
11
  import { CONFIG_SCHEMA_VERSION } from '../types.js';
12
12
  import { ensureInitialRoleRegistry } from '../config/role-service.js';
13
13
  import { getCodexAppServerAvailability } from '../agents/codex-runner.js';
14
14
  import { AUTO_BASEAGENT_CANDIDATES, BASEAGENT_CANDIDATES, detectAvailableBaseagents, } from '../agents/baseagent-availability.js';
15
15
  import { agentProjectRootFromDefaults, deriveAgentProjectPath } from '../utils/project-path.js';
16
16
  import { isValidAid } from '../aun/aid/validation.js';
17
- import { AGENT_DESCRIPTION_MAX_LENGTH, AGENT_TAG_MAX_COUNT, AGENT_TAG_MIN_COUNT, DEFAULT_AGENT_DESCRIPTION, DEFAULT_AGENT_TYPE, normalizeAgentType, validateAgentTags, validateAgentType, buildInitialAgentMd, validateAgentMdFrontmatter, } from '../aun/aid/agentmd.js';
18
- import { atomicWriteJson } from '../utils/atomic-write.js';
17
+ import { AGENT_DESCRIPTION_MAX_LENGTH, DEFAULT_AGENT_DESCRIPTION, DEFAULT_AGENT_TYPE, normalizeAgentType, validateAgentTags, validateAgentType, buildInitialAgentMd, validateAgentMdFrontmatter, assertAgentIdentityReusable, assertAgentCardReusable, } from '../aun/aid/agentmd.js';
18
+ import { atomicReplaceFile, atomicWriteJson } from '../utils/atomic-write.js';
19
19
  import { isHClassPath, isLClassPath, isSameOrDescendant } from '../core/permission/protected-paths.js';
20
20
  import { MAIN_CLI_BIN } from '../product.js';
21
21
  import { uploadAvatarFile, uploadAvatarUrl } from '../utils/avatar-upload.js';
22
22
  import { readTaskRuntimeContextFromEnv } from './task-context.js';
23
23
  import { logger } from '../utils/logger.js';
24
24
  import { creationOwnershipBinding } from '../core/ownership/owner-resolver.js';
25
- import { getCatalog, resolveCatalogModel, catalogEfforts, assertCatalogSelectable } from '../core/model/model-catalog.js';
25
+ import { getCatalog, getProviderCatalog, resolveCatalogModel, catalogEfforts, assertCatalogSelectable } from '../core/model/model-catalog.js';
26
+ import { providerServiceTypeForBaseagent, resolveProviderServiceForBaseagent } from '../config/providers.js';
27
+ import { claimAgentCreation, claimAgentCreationAsync, readAgentCreationClaim, updateAgentCreationClaim } from '../core/agent-creation-claim.js';
26
28
  /** Select the creation lifecycle independently of --non-interactive. */
27
29
  export function resolveAgentCreateMode(args) {
28
30
  if (args.includes('--initialize') && args.includes('--bootstrap')) {
@@ -71,12 +73,12 @@ export function parseAgentTags(raw) {
71
73
  parsed = JSON.parse(raw);
72
74
  }
73
75
  catch {
74
- throw new Error('--tags must be a JSON array of 3 to 6 valid tags');
76
+ throw new Error('--tags must be a JSON array of valid tags');
75
77
  }
76
78
  if (!Array.isArray(parsed))
77
- throw new Error('--tags must be a JSON array of 3 to 6 valid tags');
79
+ throw new Error('--tags must be a JSON array of valid tags');
78
80
  const tags = parsed.map(value => typeof value === 'string' ? value.trim() : value);
79
- const tagErrors = validateAgentTags(tags, { minCount: AGENT_TAG_MIN_COUNT, maxCount: AGENT_TAG_MAX_COUNT });
81
+ const tagErrors = validateAgentTags(tags);
80
82
  if (tagErrors.length > 0)
81
83
  throw new Error(`--tags ${tagErrors.join('; ')}`);
82
84
  // Duplicate labels are harmless at the wire level, but should not consume
@@ -189,12 +191,18 @@ export function validateAgentCreatePlan(plan) {
189
191
  return ownerError;
190
192
  if (!isValidAid(plan.aid))
191
193
  return `Invalid AID "${plan.aid}": must be a valid multi-level domain (e.g. mybot.agentid.cn)`;
194
+ try {
195
+ assertAgentAidAvailable(plan.aid);
196
+ }
197
+ catch (error) {
198
+ return `CONTROL_AID_RESERVED: ${error instanceof Error ? error.message : String(error)}`;
199
+ }
192
200
  if (plan.avatarFile !== undefined && plan.avatarUrl !== undefined)
193
201
  return '--avatar-file and --avatar-url are mutually exclusive';
194
202
  if (plan.configExists && !plan.force)
195
203
  return `Agent "${plan.aid}" already exists (use --force to overwrite)`;
196
204
  if (plan.tags !== undefined) {
197
- const tagErrors = validateAgentTags(plan.tags, { minCount: AGENT_TAG_MIN_COUNT, maxCount: AGENT_TAG_MAX_COUNT });
205
+ const tagErrors = validateAgentTags(plan.tags);
198
206
  if (tagErrors.length > 0)
199
207
  return `Invalid tags: ${tagErrors.join('; ')}`;
200
208
  }
@@ -238,6 +246,7 @@ function toPosix(value) {
238
246
  export async function agentCreateInteractive(opts = {}) {
239
247
  const p = resolvePaths();
240
248
  const ownRl = !opts.rl;
249
+ let creationClaim;
241
250
  const rl = opts.rl ?? readline.createInterface({ input: opts.stdin || process.stdin, output: opts.stdout || process.stdout });
242
251
  const ask = (q) => new Promise(r => rl.question(q, r));
243
252
  try {
@@ -259,6 +268,14 @@ export async function agentCreateInteractive(opts = {}) {
259
268
  }
260
269
  if (hasSuppliedInitialization(aid))
261
270
  return { ok: false, error: 'Use agent initialize --resume for this target' };
271
+ try {
272
+ assertAgentAidAvailable(aid);
273
+ }
274
+ catch (error) {
275
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
276
+ }
277
+ if (hasOrphanedInitializationMarker(aid))
278
+ return { ok: false, error: 'Initialization state is invalid; restore the initialization journal before recreating this Agent' };
262
279
  const agentDirPath = path.join(p.agentsDir, aid);
263
280
  const configExists = fs.existsSync(path.join(agentDirPath, 'config.json'));
264
281
  if (configExists) {
@@ -332,14 +349,17 @@ export async function agentCreateInteractive(opts = {}) {
332
349
  const defaultName = aid.split('.')[0];
333
350
  const agentName = (await ask(`Display name [${defaultName}]: `)).trim() || defaultName;
334
351
  const agentDescription = (await ask('Description (optional): ')).trim() || '';
335
- const tagInput = (await ask('Tags (3-6, comma separated; optional): ')).trim();
352
+ const tagInput = (await ask('Tags (comma separated; optional): ')).trim();
336
353
  let agentTags;
337
354
  if (tagInput) {
338
355
  agentTags = [...new Set(tagInput.split(/[,,\s]+/).map(tag => tag.trim()).filter(Boolean))];
339
- const tagErrors = validateAgentTags(agentTags, { minCount: AGENT_TAG_MIN_COUNT, maxCount: AGENT_TAG_MAX_COUNT });
356
+ const tagErrors = validateAgentTags(agentTags);
340
357
  if (tagErrors.length > 0)
341
358
  return { ok: false, error: `Invalid tags: ${tagErrors.join('; ')}` };
342
359
  }
360
+ creationClaim = await claimAgentCreationAsync({ aid, mode: 'legacy', requesterAid: 'local-control', ownerAid: owner }, { recoverOrphanedLegacy: true });
361
+ if (!creationClaim.claimed)
362
+ return { ok: false, error: 'Agent creation is already in progress or has an existing creation record' };
343
363
  let aidCreated = false;
344
364
  try {
345
365
  // Keep the registration connection independent from Ownership. Its
@@ -347,14 +367,21 @@ export async function agentCreateInteractive(opts = {}) {
347
367
  // complete agent.md has been published and the daemon has hot-loaded it.
348
368
  const result = await aidCreate(aid, { type: 'agent' });
349
369
  try {
350
- await result.client.close();
370
+ if (result.alreadyExisted)
371
+ await assertAgentIdentityReusable(aid, { store: result.store });
372
+ }
373
+ finally {
374
+ try {
375
+ await result.client.close();
376
+ }
377
+ catch { /* ignore */ }
351
378
  }
352
- catch { /* ignore */ }
353
379
  aidCreated = !result.alreadyExisted;
354
380
  console.log(` ✓ AID ${result.alreadyExisted ? 'reused' : 'created'}: ${aid}`);
355
381
  }
356
382
  catch (e) {
357
- return { ok: false, error: `AID creation failed: ${e?.message || e}` };
383
+ await updateAgentCreationClaim(aid, creationClaim.claim.creationId, { status: 'failed' });
384
+ return { ok: false, code: e?.code, error: `AID creation failed: ${e?.message || e}` };
358
385
  }
359
386
  if (ownRl)
360
387
  rl.close();
@@ -408,8 +435,9 @@ export async function agentCreateInteractive(opts = {}) {
408
435
  let ownerBindInterrupted = false;
409
436
  if (owner && agentmdUploaded && hotLoaded) {
410
437
  try {
411
- const bindResult = await ipcQuery(p.socket, {
438
+ const bindResult = await ipcHostQuery(p.socket, {
412
439
  type: 'aid.ownership',
440
+ authMode: 'local-control',
413
441
  argv: ['aid', 'bind', owner, '--subject', aid],
414
442
  }, 30_000);
415
443
  if (!bindResult?.ok)
@@ -424,6 +452,7 @@ export async function agentCreateInteractive(opts = {}) {
424
452
  else if (owner && agentmdUploaded) {
425
453
  ownerBindSkipped = true;
426
454
  }
455
+ await updateAgentCreationClaim(aid, creationClaim.claim.creationId, { status: 'ready' });
427
456
  return {
428
457
  ok: true,
429
458
  aid,
@@ -439,6 +468,9 @@ export async function agentCreateInteractive(opts = {}) {
439
468
  };
440
469
  }
441
470
  finally {
471
+ if (creationClaim?.claimed && readAgentCreationClaim(creationClaim.claim.aid)?.status === 'in_progress') {
472
+ await updateAgentCreationClaim(creationClaim.claim.aid, creationClaim.claim.creationId, { status: 'failed' });
473
+ }
442
474
  if (ownRl) {
443
475
  try {
444
476
  rl.close();
@@ -460,7 +492,7 @@ export async function agentCreateNonInteractive(opts, runtime = {}) {
460
492
  if (agentType === 'agent' && !ownerAid)
461
493
  return failValidating('An owner AID is required when creating an agent');
462
494
  if (opts.tags !== undefined) {
463
- const tagErrors = validateAgentTags(opts.tags, { minCount: AGENT_TAG_MIN_COUNT, maxCount: AGENT_TAG_MAX_COUNT });
495
+ const tagErrors = validateAgentTags(opts.tags);
464
496
  if (tagErrors.length > 0)
465
497
  return failValidating(`Invalid tags: ${tagErrors.join('; ')}`);
466
498
  }
@@ -477,8 +509,17 @@ export async function agentCreateNonInteractive(opts, runtime = {}) {
477
509
  }
478
510
  if (!isValidAid(opts.aid))
479
511
  return failValidating(`Invalid AID "${opts.aid}": must be a valid multi-level domain (e.g. mybot.agentid.cn)`);
512
+ try {
513
+ assertAgentAidAvailable(opts.aid);
514
+ }
515
+ catch (error) {
516
+ opts.onPhase?.('validating', 'failed', error.message);
517
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
518
+ }
480
519
  if (hasSuppliedInitialization(opts.aid))
481
520
  return failValidating('Use agent initialize --resume for this target');
521
+ if (hasOrphanedInitializationMarker(opts.aid))
522
+ return failValidating('Initialization state is invalid; restore the initialization journal before recreating this Agent');
482
523
  const agentDirPath = path.join(p.agentsDir, opts.aid);
483
524
  const configExists = fs.existsSync(path.join(agentDirPath, 'config.json'));
484
525
  if (configExists && !opts.force)
@@ -510,179 +551,206 @@ export async function agentCreateNonInteractive(opts, runtime = {}) {
510
551
  return failValidating(`Failed to create ${opts.project}: ${e?.message || e}`);
511
552
  }
512
553
  }
513
- opts.onPhase?.('validating', 'done');
514
- opts.onPhase?.('registering_aid', 'begin');
515
- let aidCreated = false;
516
- // Do not persist a pending registration ownership intent here. Avatar
517
- // publication uses an AUN short connection, and the SDK may resume that
518
- // intent as soon as the short connection is authenticated, before the final
519
- // agent.md (including avatar) has been published. Submit the bind only after
520
- // the final card is in place and the Agent has a long-lived channel.
554
+ let creationClaim;
521
555
  try {
522
- const result = await aidCreate(opts.aid, { type: agentType });
523
- try {
524
- await result.client.close();
525
- }
526
- catch { /* ignore */ }
527
- aidCreated = !result.alreadyExisted;
528
- opts.onPhase?.('registering_aid', 'done', aidCreated ? 'created' : 'existed');
556
+ creationClaim = await claimAgentCreationAsync({ aid: opts.aid, mode: 'legacy', creationId: opts.creationId, requesterAid: 'local-control', ownerAid }, { recoverOrphanedLegacy: true });
529
557
  }
530
- catch (e) {
531
- const error = `AID creation failed: ${e?.message || e}`;
532
- opts.onPhase?.('registering_aid', 'failed', error);
533
- return { ok: false, error };
558
+ catch (error) {
559
+ return failValidating(error instanceof Error ? error.message : String(error));
560
+ }
561
+ if (!creationClaim.claimed && creationClaim.claim.creationId !== opts.creationId) {
562
+ return failValidating('Agent creation is already in progress or has an existing creation record');
534
563
  }
535
- let preservedLifecycle = 'created';
536
- if (configExists) {
537
- try {
538
- const existing = loadAgent(opts.aid);
539
- if (existing?.lifecycle)
540
- preservedLifecycle = existing.lifecycle;
541
- }
542
- catch { /* ignore */ }
543
- }
544
- opts.onPhase?.('config_saved', 'begin');
545
- saveAgent({ $schema_version: CONFIG_SCHEMA_VERSION, aid: opts.aid, enabled: true, lifecycle: preservedLifecycle, channels: [], projects: { defaultPath: opts.project } });
546
- ensureInitialRoleRegistry(opts.aid);
547
- saveInitialBehavior(opts.aid, baseagent);
548
- ensureAgentDirSkeleton(opts.aid);
549
- opts.onPhase?.('config_saved', 'done');
550
- opts.onPhase?.('uploading_agentmd', 'begin');
551
- let agentmdUploaded = false;
552
- let agentmdError;
553
564
  try {
554
- const content = buildInitialAgentMd({ aid: opts.aid, name: opts.name, description: opts.description, type: agentType, tags: opts.tags });
555
- const aunPath = process.env.AUN_HOME || defaultAunPath();
556
- let lastError;
557
- for (let attempt = 1; attempt <= 3; attempt++) {
565
+ opts.onPhase?.('validating', 'done');
566
+ opts.onPhase?.('registering_aid', 'begin');
567
+ let aidCreated = false;
568
+ // Do not persist a pending registration ownership intent here. Avatar
569
+ // publication uses an AUN short connection, and the SDK may resume that
570
+ // intent as soon as the short connection is authenticated, before the final
571
+ // agent.md (including avatar) has been published. Submit the bind only after
572
+ // the final card is in place and the Agent has a long-lived channel.
573
+ try {
574
+ const result = await aidCreate(opts.aid, { type: agentType });
558
575
  try {
559
- if (attempt > 1)
560
- await new Promise(r => setTimeout(r, 2000));
561
- await agentmdPut(content, { aid: opts.aid, aunPath });
562
- agentmdUploaded = true;
563
- opts.onPhase?.('uploading_agentmd', 'done');
564
- break;
576
+ if (result.alreadyExisted)
577
+ await assertAgentIdentityReusable(opts.aid, { store: result.store });
565
578
  }
566
- catch (e) {
567
- lastError = e;
579
+ finally {
580
+ try {
581
+ await result.client.close();
582
+ }
583
+ catch { /* ignore */ }
568
584
  }
585
+ aidCreated = !result.alreadyExisted;
586
+ opts.onPhase?.('registering_aid', 'done', aidCreated ? 'created' : 'existed');
569
587
  }
570
- if (!agentmdUploaded) {
571
- agentmdError = `upload failed: ${lastError?.message || lastError}`;
572
- opts.onPhase?.('uploading_agentmd', 'warn', agentmdError);
588
+ catch (e) {
589
+ const error = `AID creation failed: ${e?.message || e}`;
590
+ await updateAgentCreationClaim(opts.aid, creationClaim.claim.creationId, { status: 'failed' });
591
+ opts.onPhase?.('registering_aid', 'failed', error);
592
+ return { ok: false, code: e?.code, error };
573
593
  }
574
- await new Promise(r => setTimeout(r, 0));
575
- }
576
- catch (e) {
577
- agentmdError = `generation failed: ${e?.message || e}`;
578
- opts.onPhase?.('uploading_agentmd', 'warn', agentmdError);
579
- }
580
- if (ownerAid && agentmdUploaded) {
581
- const config = loadAgent(opts.aid);
582
- if (config) {
583
- config.lifecycle = 'ownerpending';
584
- saveAgent(config);
594
+ let preservedLifecycle = 'created';
595
+ if (configExists) {
596
+ try {
597
+ const existing = loadAgent(opts.aid);
598
+ if (existing?.lifecycle)
599
+ preservedLifecycle = existing.lifecycle;
600
+ }
601
+ catch { /* ignore */ }
585
602
  }
586
- }
587
- let avatarUploaded = false;
588
- if (opts.avatarFile || opts.avatarUrl) {
589
- opts.onPhase?.('uploading_avatar', 'begin');
603
+ opts.onPhase?.('config_saved', 'begin');
604
+ saveAgent({ $schema_version: CONFIG_SCHEMA_VERSION, aid: opts.aid, enabled: true, lifecycle: preservedLifecycle, channels: [], projects: { defaultPath: opts.project } });
605
+ ensureInitialRoleRegistry(opts.aid);
606
+ saveInitialBehavior(opts.aid, baseagent);
607
+ ensureAgentDirSkeleton(opts.aid);
608
+ opts.onPhase?.('config_saved', 'done');
609
+ opts.onPhase?.('uploading_agentmd', 'begin');
610
+ let agentmdUploaded = false;
611
+ let agentmdError;
590
612
  try {
591
- if (!agentmdUploaded)
592
- throw new Error('头像上传前 agent.md 尚未成功发布');
593
- const avatar = opts.avatarFile
594
- ? await uploadAvatarFile(opts.aid, opts.avatarFile)
595
- : await uploadAvatarUrl(opts.aid, opts.avatarUrl);
596
- if (!avatar.ok)
597
- throw new Error(avatar.error || '头像上传失败');
598
- avatarUploaded = true;
599
- opts.onPhase?.('uploading_avatar', 'done', `${avatar.width}x${avatar.height} ${avatar.mime}`);
613
+ const content = buildInitialAgentMd({ aid: opts.aid, name: opts.name, description: opts.description, type: agentType, tags: opts.tags });
614
+ const aunPath = process.env.AUN_HOME || defaultAunPath();
615
+ let lastError;
616
+ for (let attempt = 1; attempt <= 3; attempt++) {
617
+ try {
618
+ if (attempt > 1)
619
+ await new Promise(r => setTimeout(r, 2000));
620
+ await agentmdPut(content, { aid: opts.aid, aunPath });
621
+ agentmdUploaded = true;
622
+ opts.onPhase?.('uploading_agentmd', 'done');
623
+ break;
624
+ }
625
+ catch (e) {
626
+ lastError = e;
627
+ }
628
+ }
629
+ if (!agentmdUploaded) {
630
+ agentmdError = `upload failed: ${lastError?.message || lastError}`;
631
+ opts.onPhase?.('uploading_agentmd', 'warn', agentmdError);
632
+ }
633
+ await new Promise(r => setTimeout(r, 0));
600
634
  }
601
- catch (error) {
602
- const detail = error instanceof Error ? error.message : String(error);
603
- opts.onPhase?.('uploading_avatar', 'failed', detail);
604
- return { ok: false, code: 'AVATAR_UPLOAD_FAILED', error: `头像上传失败:${detail}` };
635
+ catch (e) {
636
+ agentmdError = `generation failed: ${e?.message || e}`;
637
+ opts.onPhase?.('uploading_agentmd', 'warn', agentmdError);
605
638
  }
606
- }
607
- let hotLoaded = false;
608
- let hotLoadError;
609
- opts.onPhase?.('hot_loading', 'begin');
610
- try {
611
- if (runtime.hotLoadAgent) {
612
- await runtime.hotLoadAgent(opts.aid);
613
- hotLoaded = true;
614
- opts.onPhase?.('hot_loading', 'done');
639
+ if (ownerAid && agentmdUploaded) {
640
+ const config = loadAgent(opts.aid);
641
+ if (config) {
642
+ config.lifecycle = 'ownerpending';
643
+ saveAgent(config);
644
+ }
615
645
  }
616
- else {
617
- const ipcResult = await ipcQuery(p.socket, { type: 'evolagent.load', aid: opts.aid }, 30_000);
618
- if (ipcResult?.ok) {
619
- hotLoaded = true;
620
- opts.onPhase?.('hot_loading', 'done');
646
+ let avatarUploaded = false;
647
+ if (opts.avatarFile || opts.avatarUrl) {
648
+ opts.onPhase?.('uploading_avatar', 'begin');
649
+ try {
650
+ if (!agentmdUploaded)
651
+ throw new Error('头像上传前 agent.md 尚未成功发布');
652
+ const avatar = opts.avatarFile
653
+ ? await uploadAvatarFile(opts.aid, opts.avatarFile)
654
+ : await uploadAvatarUrl(opts.aid, opts.avatarUrl);
655
+ if (!avatar.ok)
656
+ throw new Error(avatar.error || '头像上传失败');
657
+ avatarUploaded = true;
658
+ opts.onPhase?.('uploading_avatar', 'done', `${avatar.width}x${avatar.height} ${avatar.mime}`);
621
659
  }
622
- else if (ipcResult) {
623
- hotLoadError = ipcResult.error;
624
- opts.onPhase?.('hot_loading', 'warn', hotLoadError);
660
+ catch (error) {
661
+ const detail = error instanceof Error ? error.message : String(error);
662
+ await updateAgentCreationClaim(opts.aid, creationClaim.claim.creationId, { status: 'failed' });
663
+ opts.onPhase?.('uploading_avatar', 'failed', detail);
664
+ return { ok: false, code: 'AVATAR_UPLOAD_FAILED', error: `头像上传失败:${detail}` };
625
665
  }
626
- else
627
- opts.onPhase?.('hot_loading', 'warn', 'daemon not running');
628
666
  }
629
- }
630
- catch (error) {
631
- hotLoadError = error instanceof Error ? error.message : String(error);
632
- opts.onPhase?.('hot_loading', 'warn', hotLoadError);
633
- }
634
- let ownerBindRequestedAid;
635
- let ownerBindSkipped = false;
636
- let ownerBindInterrupted = false;
637
- let ownershipBinding;
638
- if (ownerAid && agentmdUploaded && hotLoaded) {
667
+ let hotLoaded = false;
668
+ let hotLoadError;
669
+ opts.onPhase?.('hot_loading', 'begin');
639
670
  try {
640
- let state;
641
- if (runtime.bindOwnerAgent) {
642
- state = await runtime.bindOwnerAgent(opts.aid, ownerAid);
671
+ if (runtime.hotLoadAgent) {
672
+ await runtime.hotLoadAgent(opts.aid);
673
+ hotLoaded = true;
674
+ opts.onPhase?.('hot_loading', 'done');
643
675
  }
644
676
  else {
645
- const bindResult = await ipcQuery(p.socket, {
646
- type: 'aid.ownership',
647
- argv: ['aid', 'bind', ownerAid, '--subject', opts.aid],
648
- }, 30_000);
649
- if (!bindResult?.ok)
650
- throw new Error(bindResult?.error || 'Ownership bind failed');
651
- state = bindResult.state;
652
- }
653
- ownerBindRequestedAid = ownerAid;
654
- // Reusing an existing identity (including a failed-create retry) cannot
655
- // prove that an SDK-reused task originated in this creation attempt.
656
- const binding = aidCreated ? creationOwnershipBinding(state?.task, opts.aid, ownerAid) : undefined;
657
- if (binding) {
658
- opts.onOwnershipBinding?.(binding);
659
- ownershipBinding = binding;
677
+ const ipcResult = await ipcQuery(p.socket, { type: 'evolagent.load', aid: opts.aid }, 30_000);
678
+ if (ipcResult?.ok) {
679
+ hotLoaded = true;
680
+ opts.onPhase?.('hot_loading', 'done');
681
+ }
682
+ else if (ipcResult) {
683
+ hotLoadError = ipcResult.error;
684
+ opts.onPhase?.('hot_loading', 'warn', hotLoadError);
685
+ }
686
+ else
687
+ opts.onPhase?.('hot_loading', 'warn', 'daemon not running');
660
688
  }
661
689
  }
662
690
  catch (error) {
663
- ownerBindInterrupted = true;
664
- logger.warn(`[agent-create] Ownership bind interrupted for ${opts.aid}: ${error instanceof Error ? error.message : String(error)}`);
691
+ hotLoadError = error instanceof Error ? error.message : String(error);
692
+ opts.onPhase?.('hot_loading', 'warn', hotLoadError);
693
+ }
694
+ let ownerBindRequestedAid;
695
+ let ownerBindSkipped = false;
696
+ let ownerBindInterrupted = false;
697
+ let ownershipBinding;
698
+ if (ownerAid && agentmdUploaded && hotLoaded) {
699
+ try {
700
+ let state;
701
+ if (runtime.bindOwnerAgent) {
702
+ state = await runtime.bindOwnerAgent(opts.aid, ownerAid);
703
+ }
704
+ else {
705
+ const bindResult = await ipcHostQuery(p.socket, {
706
+ type: 'aid.ownership',
707
+ authMode: 'local-control',
708
+ argv: ['aid', 'bind', ownerAid, '--subject', opts.aid],
709
+ }, 30_000);
710
+ if (!bindResult?.ok)
711
+ throw new Error(bindResult?.error || 'Ownership bind failed');
712
+ state = bindResult.state;
713
+ }
714
+ ownerBindRequestedAid = ownerAid;
715
+ // Reusing an existing identity (including a failed-create retry) cannot
716
+ // prove that an SDK-reused task originated in this creation attempt.
717
+ const binding = aidCreated ? creationOwnershipBinding(state?.task, opts.aid, ownerAid) : undefined;
718
+ if (binding) {
719
+ opts.onOwnershipBinding?.(binding);
720
+ ownershipBinding = binding;
721
+ }
722
+ }
723
+ catch (error) {
724
+ ownerBindInterrupted = true;
725
+ logger.warn(`[agent-create] Ownership bind interrupted for ${opts.aid}: ${error instanceof Error ? error.message : String(error)}`);
726
+ }
727
+ }
728
+ else if (ownerAid && agentmdUploaded) {
729
+ ownerBindSkipped = true;
665
730
  }
731
+ await updateAgentCreationClaim(opts.aid, creationClaim.claim.creationId, { status: 'ready' });
732
+ return {
733
+ ok: true,
734
+ aid: opts.aid,
735
+ ownerAid,
736
+ configPath: toPosix(path.join(agentDirPath, 'config.json')),
737
+ aidCreated,
738
+ agentmdUploaded,
739
+ agentmdError,
740
+ hotLoaded,
741
+ hotLoadError,
742
+ ownerBindRequestedAid,
743
+ ownerBindSkipped,
744
+ ownerBindInterrupted,
745
+ ...(ownershipBinding ? { ownershipBinding } : {}),
746
+ ...(opts.avatarFile || opts.avatarUrl ? { avatarUploaded } : {}),
747
+ };
666
748
  }
667
- else if (ownerAid && agentmdUploaded) {
668
- ownerBindSkipped = true;
749
+ finally {
750
+ if (creationClaim.claimed && readAgentCreationClaim(opts.aid)?.status === 'in_progress') {
751
+ await updateAgentCreationClaim(opts.aid, creationClaim.claim.creationId, { status: 'failed' });
752
+ }
669
753
  }
670
- return {
671
- ok: true,
672
- aid: opts.aid,
673
- ownerAid,
674
- configPath: toPosix(path.join(agentDirPath, 'config.json')),
675
- aidCreated,
676
- agentmdUploaded,
677
- agentmdError,
678
- hotLoaded,
679
- hotLoadError,
680
- ownerBindRequestedAid,
681
- ownerBindSkipped,
682
- ownerBindInterrupted,
683
- ...(ownershipBinding ? { ownershipBinding } : {}),
684
- ...(opts.avatarFile || opts.avatarUrl ? { avatarUploaded } : {}),
685
- };
686
754
  }
687
755
  // ---- One-shot Agent initialization (kept with Agent creation) ----
688
756
  export const INITIALIZATION_PERSONA_MAX_BYTES = 64 * 1024;
@@ -705,35 +773,246 @@ export function initializationFingerprint(plan) {
705
773
  ...(plan.model !== undefined || plan.effort !== undefined
706
774
  ? [{ model: plan.model ?? null, effort: plan.effort ?? null }]
707
775
  : []),
776
+ ...(plan.provider !== undefined ? [{ provider: plan.provider }] : []),
708
777
  ];
709
778
  return createHash('sha256').update(JSON.stringify(values)).digest('hex');
710
779
  }
780
+ function diagnoseInitializationFingerprint(record) {
781
+ const plan = record.plan;
782
+ const baseValues = [
783
+ plan.aid, plan.project, plan.baseagent, plan.ownerAid, plan.name,
784
+ plan.description, plan.type, plan.tags, plan.persona ?? null,
785
+ ];
786
+ const avatarValues = [plan.avatarFile ?? null, plan.avatarUrl ?? null];
787
+ const modelValues = plan.model !== undefined || plan.effort !== undefined
788
+ ? [{ model: plan.model ?? null, effort: plan.effort ?? null }] : [];
789
+ const matches = (values) => createHash('sha256')
790
+ .update(JSON.stringify(values)).digest('hex') === record.fingerprint;
791
+ let fingerprintFormat = 'unrecognized';
792
+ const owners = Array.isArray(plan.owners) ? plan.owners
793
+ : typeof plan.ownerAid === 'string' ? [plan.ownerAid] : undefined;
794
+ if (owners) {
795
+ const ownerValues = [...baseValues];
796
+ ownerValues[3] = owners;
797
+ if (matches([...ownerValues, ...avatarValues]))
798
+ fingerprintFormat = 'legacy_owners';
799
+ else if (matches(ownerValues))
800
+ fingerprintFormat = 'legacy_owners_without_avatar';
801
+ }
802
+ if (fingerprintFormat === 'unrecognized' && plan.provider !== undefined
803
+ && matches([...baseValues, ...avatarValues, ...modelValues])) {
804
+ fingerprintFormat = 'legacy_without_provider';
805
+ }
806
+ if (fingerprintFormat === 'unrecognized'
807
+ && (plan.model !== undefined || plan.effort !== undefined)
808
+ && matches([...baseValues, ...avatarValues])) {
809
+ fingerprintFormat = 'legacy_without_model';
810
+ }
811
+ return { fingerprintFormat, recordedStatus: record.status };
812
+ }
813
+ export class InitializationStateError extends Error {
814
+ validationFailure;
815
+ fingerprintDiagnostic;
816
+ code = 'INITIALIZE_STATE_INVALID';
817
+ constructor(validationFailure, fingerprintDiagnostic) {
818
+ super('INITIALIZE_STATE_INVALID');
819
+ this.validationFailure = validationFailure;
820
+ this.fingerprintDiagnostic = fingerprintDiagnostic;
821
+ this.name = 'InitializationStateError';
822
+ }
823
+ }
824
+ /** Fingerprint for the v2 App contract. Keep v1's historical algorithm untouched. */
825
+ export function initializationFingerprintV2(plan) {
826
+ const normalized = {
827
+ aid: plan.aid,
828
+ project: plan.project,
829
+ baseagent: plan.baseagent,
830
+ provider: plan.provider ?? null,
831
+ model: plan.model ?? null,
832
+ effort: plan.effort ?? null,
833
+ chatmode: plan.chatmode === undefined ? null : {
834
+ private: plan.chatmode.private ?? null,
835
+ group: plan.chatmode.group ?? null,
836
+ nothuman: plan.chatmode.nothuman ?? null,
837
+ },
838
+ ownerAid: plan.ownerAid,
839
+ name: plan.name,
840
+ description: plan.description,
841
+ type: plan.type,
842
+ tags: [...plan.tags],
843
+ persona: plan.persona ?? null,
844
+ avatarFile: plan.avatarFile ?? null,
845
+ avatarUrl: plan.avatarUrl ?? null,
846
+ };
847
+ return createHash('sha256').update(JSON.stringify(normalized)).digest('hex');
848
+ }
849
+ 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;
850
+ function storedCreationBinding(value, aid, ownerAid) {
851
+ if (!value || typeof value !== 'object' || Array.isArray(value))
852
+ return undefined;
853
+ const b = value;
854
+ const keys = ['baseRelationVersion', 'operation', 'operationId', 'ownerAid', 'source', 'subjectAid', 'targetRelationVersion'];
855
+ if (Object.keys(b).sort().join(',') !== keys.sort().join(','))
856
+ return undefined;
857
+ const task = {
858
+ operation: b.operation,
859
+ operation_id: b.operationId,
860
+ sub_aid: b.subjectAid,
861
+ owner_aid: b.ownerAid,
862
+ base_relation_version: b.baseRelationVersion,
863
+ target_relation_version: b.targetRelationVersion,
864
+ status: 'pending',
865
+ };
866
+ const expected = creationOwnershipBinding(task, aid, ownerAid);
867
+ if (!expected || b.source !== 'agent_create')
868
+ return undefined;
869
+ if (JSON.stringify(expected) !== JSON.stringify({
870
+ source: b.source, operation: b.operation, operationId: b.operationId,
871
+ subjectAid: b.subjectAid, ownerAid: b.ownerAid,
872
+ baseRelationVersion: b.baseRelationVersion, targetRelationVersion: b.targetRelationVersion,
873
+ }))
874
+ return undefined;
875
+ return expected;
876
+ }
877
+ function recordMode(record) {
878
+ return record.mode ?? 'supplied';
879
+ }
711
880
  export function readInitialization(aid) {
712
881
  const file = initializationPath(aid);
713
882
  if (!fs.existsSync(file))
714
883
  return null;
884
+ let text;
715
885
  try {
716
- const record = JSON.parse(fs.readFileSync(file, 'utf8'));
717
- if (record.version !== 1 || record.plan?.aid !== aid || !/^init-[a-f0-9]{24}$/.test(record.operationId)
718
- || !['in_progress', 'failed', 'complete', 'cancelled'].includes(record.status)
719
- || initializationFingerprint(record.plan) !== record.fingerprint) {
720
- failure('INITIALIZE_STATE_INVALID');
721
- }
722
- return record;
886
+ text = fs.readFileSync(file, 'utf8');
887
+ }
888
+ catch {
889
+ throw new InitializationStateError('read_failed');
890
+ }
891
+ let record;
892
+ try {
893
+ record = JSON.parse(text);
723
894
  }
724
895
  catch {
725
- failure('INITIALIZE_STATE_INVALID');
896
+ throw new InitializationStateError('invalid_json');
897
+ }
898
+ if (!record || typeof record !== 'object' || Array.isArray(record)) {
899
+ throw new InitializationStateError('invalid_record');
900
+ }
901
+ if (record.version !== 1 && record.version !== 2)
902
+ throw new InitializationStateError('unsupported_version');
903
+ if (!record.plan || typeof record.plan !== 'object' || Array.isArray(record.plan)) {
904
+ throw new InitializationStateError('invalid_plan');
905
+ }
906
+ if (record.plan.aid !== aid)
907
+ throw new InitializationStateError('subject_mismatch');
908
+ if (typeof record.operationId !== 'string' || !/^init-[a-f0-9]{24}$/.test(record.operationId)) {
909
+ throw new InitializationStateError('invalid_operation_id');
910
+ }
911
+ if (!['in_progress', 'failed', 'complete', 'cancelled'].includes(record.status)) {
912
+ throw new InitializationStateError('invalid_status');
726
913
  }
914
+ if (record.version === 1) {
915
+ if ((record.mode !== undefined && record.mode !== 'supplied')
916
+ || record.creationId !== undefined || record.clientRequestId !== undefined) {
917
+ throw new InitializationStateError('invalid_record');
918
+ }
919
+ if (initializationFingerprint(record.plan) !== record.fingerprint) {
920
+ throw new InitializationStateError('fingerprint_mismatch', diagnoseInitializationFingerprint(record));
921
+ }
922
+ }
923
+ else {
924
+ let fingerprint;
925
+ try {
926
+ fingerprint = initializationFingerprintV2(record.plan);
927
+ }
928
+ catch {
929
+ throw new InitializationStateError('invalid_plan');
930
+ }
931
+ const valid = record.mode === 'one_shot'
932
+ && typeof record.creationId === 'string' && UUID_V4.test(record.creationId)
933
+ && typeof record.clientRequestId === 'string' && UUID_V4.test(record.clientRequestId)
934
+ && typeof record.requesterAid === 'string' && record.requesterAid === record.actor
935
+ && record.fingerprintVersion === 'sha256-json-v1-normalized'
936
+ && !!record.bindAttempt
937
+ && ['not_started', 'submitting', 'submitted', 'unknown', 'confirmed'].includes(record.bindAttempt.state)
938
+ && record.bindAttempt.subjectAid === aid
939
+ && record.bindAttempt.ownerAid === record.plan.ownerAid
940
+ && record.bindAttempt.baseRelationVersion === 0
941
+ && record.bindAttempt.targetRelationVersion === 1
942
+ && (record.ownershipBinding === undefined || !!storedCreationBinding(record.ownershipBinding, aid, record.plan.ownerAid))
943
+ && ((record.bindAttempt.state === 'submitted' || record.bindAttempt.state === 'confirmed')
944
+ ? !!record.ownershipBinding && record.bindAttempt.operationId === record.ownershipBinding.operationId
945
+ : !record.bindAttempt.operationId && !record.ownershipBinding)
946
+ && (record.status !== 'complete' || (record.ownerConfirmed === true && record.phase === 'active'));
947
+ if (!valid)
948
+ throw new InitializationStateError('invalid_record');
949
+ if (fingerprint !== record.fingerprint)
950
+ throw new InitializationStateError('fingerprint_mismatch');
951
+ }
952
+ return record;
727
953
  }
728
954
  export function saveInitialization(record) {
729
955
  const file = initializationPath(record.plan.aid);
730
956
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
731
957
  record.updatedAt = Date.now();
732
- atomicWriteJson(file, record);
958
+ if (record.version === 2) {
959
+ // The Windows EPERM fallback keeps a complete hot backup before updating
960
+ // this small journal in place. Core reads it synchronously on this event
961
+ // loop, so a local reader cannot observe a partial checkpoint.
962
+ const temporary = `${file}.${process.pid}.${randomUUID()}.update`;
963
+ try {
964
+ const fd = fs.openSync(temporary, 'wx', 0o600);
965
+ try {
966
+ fs.writeFileSync(fd, JSON.stringify(record, null, 2) + '\n', 'utf8');
967
+ fs.fsyncSync(fd);
968
+ }
969
+ finally {
970
+ fs.closeSync(fd);
971
+ }
972
+ atomicReplaceFile(temporary, file);
973
+ }
974
+ finally {
975
+ fs.rmSync(temporary, { force: true });
976
+ }
977
+ }
978
+ else {
979
+ atomicWriteJson(file, record);
980
+ }
733
981
  // The hot backup also contains the private plan snapshot.
734
982
  for (const target of [file, `${file}_`])
735
983
  if (fs.existsSync(target))
736
984
  fs.chmodSync(target, 0o600);
985
+ // Initialization status is authoritative in this journal. The admission
986
+ // sidecar only reserves the AID and IDs; checkpoints need no second write.
987
+ }
988
+ /** Atomically publish only if no initializer has claimed this AID yet. */
989
+ function saveInitializationExclusive(record) {
990
+ const file = initializationPath(record.plan.aid);
991
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
992
+ record.updatedAt = Date.now();
993
+ const temporary = `${file}.${process.pid}.${randomUUID()}.create`;
994
+ try {
995
+ const fd = fs.openSync(temporary, 'wx', 0o600);
996
+ try {
997
+ fs.writeFileSync(fd, JSON.stringify(record, null, 2) + '\n', 'utf8');
998
+ fs.fsyncSync(fd);
999
+ }
1000
+ finally {
1001
+ fs.closeSync(fd);
1002
+ }
1003
+ try {
1004
+ fs.linkSync(temporary, file);
1005
+ return true;
1006
+ }
1007
+ catch (error) {
1008
+ if (error.code === 'EEXIST')
1009
+ return false;
1010
+ throw error;
1011
+ }
1012
+ }
1013
+ finally {
1014
+ fs.rmSync(temporary, { force: true });
1015
+ }
737
1016
  }
738
1017
  /** Pure summary: never expose the persona, project path or authorization snapshot. */
739
1018
  export function initializationSummary(aid) {
@@ -741,21 +1020,35 @@ export function initializationSummary(aid) {
741
1020
  const r = readInitialization(aid);
742
1021
  if (!r)
743
1022
  return undefined;
1023
+ const mode = recordMode(r);
744
1024
  return {
745
- mode: 'supplied', operationId: r.operationId, fingerprint: r.fingerprint,
1025
+ mode, operationId: r.operationId, fingerprint: r.fingerprint,
1026
+ ...(r.creationId ? { creationId: r.creationId } : {}),
1027
+ ...(r.clientRequestId ? { clientRequestId: r.clientRequestId } : {}),
1028
+ ...(r.requesterAid ? { requesterAid: r.requesterAid } : {}),
746
1029
  status: r.status, phase: r.phase, complete: r.status === 'complete',
747
- code: r.code ?? null, error: r.error ?? null, retryable: r.status === 'failed',
748
- nextStep: r.status === 'failed' ? `ec agent initialize ${aid} --resume` : null,
1030
+ code: r.code ?? null, error: r.error ?? null,
1031
+ retryable: r.status === 'failed' && r.bindAttempt?.state !== 'unknown',
1032
+ nextStep: r.status === 'complete' || r.status === 'cancelled' ? null
1033
+ : r.bindAttempt?.state === 'unknown' ? 'await_owner'
1034
+ : r.status === 'failed' ? `ec agent initialize ${aid} --resume` : null,
749
1035
  agentmd: { published: r.published === true, verified: r.verified === true },
750
1036
  persona: { provided: r.plan.persona !== undefined },
751
1037
  avatar: { requested: r.plan.avatarFile !== undefined || r.plan.avatarUrl !== undefined, uploaded: r.avatarUploaded === true },
1038
+ avatarAccepted: r.avatarAccepted === true,
1039
+ ...(r.ownershipBinding ? { ownershipBinding: r.ownershipBinding } : {}),
1040
+ ...(r.bindAttempt ? { bindAttempt: r.bindAttempt } : {}),
1041
+ ...(recordMode(r) === 'one_shot' ? { ownerConfirmed: r.ownerConfirmed === true } : {}),
1042
+ ...(r.ownerConsensus ? { ownerConsensus: r.ownerConsensus } : {}),
752
1043
  welcome: r.welcome, startedAt: r.startedAt, updatedAt: r.updatedAt,
753
1044
  };
754
1045
  }
755
- catch {
1046
+ catch (error) {
756
1047
  return {
757
1048
  mode: 'supplied', status: 'failed', phase: 'unknown', complete: false,
758
1049
  code: 'INITIALIZE_STATE_INVALID', error: 'Initialization state is invalid', retryable: false,
1050
+ validationFailure: error instanceof InitializationStateError ? error.validationFailure : 'unknown',
1051
+ ...(error instanceof InitializationStateError ? error.fingerprintDiagnostic : {}),
759
1052
  };
760
1053
  }
761
1054
  }
@@ -776,10 +1069,22 @@ export function initializationBlocksTasks(config) {
776
1069
  export function hasSuppliedInitialization(aid) {
777
1070
  return fs.existsSync(initializationPath(aid));
778
1071
  }
1072
+ /** A config marker without its durable journal is unsafe to overwrite. */
1073
+ export function hasOrphanedInitializationMarker(aid) {
1074
+ try {
1075
+ return !hasSuppliedInitialization(aid) && loadAgent(aid)?.initialization !== undefined;
1076
+ }
1077
+ catch {
1078
+ return true;
1079
+ }
1080
+ }
779
1081
  function failure(code, error = code) {
780
1082
  throw Object.assign(new Error(error), { code });
781
1083
  }
782
1084
  export function validateInitializationPlan(plan) {
1085
+ assertAgentAidAvailable(plan.aid);
1086
+ if (plan.provider !== undefined)
1087
+ resolveProviderServiceForBaseagent(plan.provider, plan.baseagent);
783
1088
  if (typeof plan.name !== 'string' || !plan.name.trim()
784
1089
  || typeof plan.description !== 'string' || !plan.description.trim()
785
1090
  || !Array.isArray(plan.tags) || typeof plan.ownerAid !== 'string' || !plan.ownerAid.trim()) {
@@ -795,6 +1100,13 @@ export function validateInitializationPlan(plan) {
795
1100
  if (plan.effort !== undefined && (typeof plan.effort !== 'string' || !plan.effort.trim() || plan.effort.length > 64)) {
796
1101
  failure('INVALID_ARGS', 'effort must be a non-empty string of at most 64 characters');
797
1102
  }
1103
+ if (plan.chatmode !== undefined) {
1104
+ if (!plan.chatmode || typeof plan.chatmode !== 'object' || Array.isArray(plan.chatmode)
1105
+ || Object.entries(plan.chatmode).some(([scope, value]) => !['private', 'group', 'nothuman'].includes(scope)
1106
+ || !['interactive', 'proactive'].includes(value))) {
1107
+ failure('INVALID_ARGS', 'chatmode must contain only private/group/nothuman interactive/proactive values');
1108
+ }
1109
+ }
798
1110
  if (plan.avatarFile !== undefined && plan.avatarUrl !== undefined)
799
1111
  failure('INVALID_ARGS', 'avatar-file and avatar-url are mutually exclusive');
800
1112
  const error = validateAgentCreatePlan({
@@ -841,7 +1153,9 @@ export async function validateInitializationModelArgs(args) {
841
1153
  if (!baseagent)
842
1154
  return { error: '指定 model/effort 时必须提供 baseagent', code: 'INVALID_ARGS' };
843
1155
  try {
844
- const catalog = await getCatalog(undefined, baseagent);
1156
+ const catalog = typeof plan.provider === 'string'
1157
+ ? await getProviderCatalog(plan.provider, providerServiceTypeForBaseagent(baseagent), false, false, baseagent)
1158
+ : await getCatalog(undefined, baseagent);
845
1159
  assertCatalogSelectable(catalog);
846
1160
  const modelIds = catalog.models.map(entry => entry.id);
847
1161
  const resolvedModel = resolveCatalogModel(catalog, model);
@@ -865,12 +1179,27 @@ function matchesCard(content, plan) {
865
1179
  return false;
866
1180
  const fields = parse(content.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] ?? '');
867
1181
  return fields?.aid === plan.aid && fields.name === plan.name && fields.description === plan.description
868
- && fields.type === plan.type && JSON.stringify(fields.tags) === JSON.stringify(plan.tags);
1182
+ && fields.type === plan.type
1183
+ // agent.md uses the established `evolcore` default when the compatible
1184
+ // App form sends an empty tags array; keep the frozen plan itself [] for
1185
+ // fingerprint/reconciliation purposes.
1186
+ && JSON.stringify(fields.tags) === JSON.stringify(plan.tags.length ? plan.tags : ['evolcore']);
1187
+ }
1188
+ const INITIALIZATION_ERROR_CODE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
1189
+ const INITIALIZATION_CONSENSUS_STATUSES = [
1190
+ 'consensus', 'released', 'unbound', 'single_sided', 'invalid', 'unavailable', 'not_applicable',
1191
+ ];
1192
+ /** Keep SDK/transport codes without persisting provider messages or payloads. */
1193
+ export function initializationErrorCode(error, fallback) {
1194
+ const details = error && typeof error === 'object' ? error : {};
1195
+ const code = details.stringCode ?? details.code ?? details.causeCode;
1196
+ return typeof code === 'string' && INITIALIZATION_ERROR_CODE.test(code) ? code : fallback;
869
1197
  }
870
1198
  /** Daemon-owned, durable creation. All public entry points authorize before calling this service. */
871
1199
  export class AgentInitializationService {
872
1200
  deps;
873
1201
  running = new Map();
1202
+ ownerRechecks = new Map();
874
1203
  constructor(deps) {
875
1204
  this.deps = deps;
876
1205
  }
@@ -879,7 +1208,7 @@ export class AgentInitializationService {
879
1208
  if (!summary)
880
1209
  return { ok: false, code: 'NOT_FOUND', error: 'No initialization record', aid };
881
1210
  const config = loadAgent(aid);
882
- const complete = summary.complete === true && config?.lifecycle === 'active';
1211
+ const complete = summary.complete === true && config?.lifecycle === 'active' && !initializationBlocksTasks(config);
883
1212
  return {
884
1213
  ok: summary.status !== 'failed' && summary.status !== 'cancelled', aid, accepted: true,
885
1214
  ...summary, complete, lifecycle: config?.lifecycle ?? null,
@@ -890,10 +1219,11 @@ export class AgentInitializationService {
890
1219
  if (this.deps.authorize && !this.deps.authorize(actor))
891
1220
  failure('NOT_ALLOWED');
892
1221
  validateInitializationPlan(plan);
1222
+ plan = JSON.parse(JSON.stringify(plan));
893
1223
  const fingerprint = initializationFingerprint(plan);
894
1224
  const existing = readInitialization(plan.aid);
895
1225
  if (existing) {
896
- if (existing.actor !== actor || existing.fingerprint !== fingerprint)
1226
+ if (recordMode(existing) !== 'supplied' || existing.actor !== actor || existing.fingerprint !== fingerprint)
897
1227
  failure('INITIALIZE_PLAN_CONFLICT');
898
1228
  const config = loadAgent(plan.aid);
899
1229
  if (existing.status === 'complete'
@@ -912,27 +1242,177 @@ export class AgentInitializationService {
912
1242
  version: 1, operationId: `init-${randomBytes(12).toString('hex')}`, actor, plan, fingerprint,
913
1243
  status: 'in_progress', phase: 'planned', startedAt: Date.now(), updatedAt: Date.now(),
914
1244
  };
915
- saveInitialization(r);
1245
+ const claim = claimAgentCreation({
1246
+ aid: plan.aid, mode: 'supplied', creationId: r.operationId, operationId: r.operationId,
1247
+ actor, requesterAid: actor, ownerAid: plan.ownerAid, fingerprint,
1248
+ });
1249
+ if (!claim.claimed) {
1250
+ if (claim.claim.mode !== 'supplied' || claim.claim.actor !== actor || claim.claim.fingerprint !== fingerprint) {
1251
+ failure('INITIALIZE_PLAN_CONFLICT');
1252
+ }
1253
+ if (claim.claim.status !== 'in_progress' || !claim.claim.operationId
1254
+ || !/^init-[a-f0-9]{24}$/.test(claim.claim.operationId))
1255
+ failure('INITIALIZE_STATE_INVALID');
1256
+ r.operationId = claim.claim.operationId;
1257
+ }
1258
+ if (!saveInitializationExclusive(r)) {
1259
+ const winner = readInitialization(plan.aid);
1260
+ if (winner && recordMode(winner) === 'supplied' && winner.actor === actor && winner.fingerprint === fingerprint) {
1261
+ return this.status(plan.aid);
1262
+ }
1263
+ failure('INITIALIZE_PLAN_CONFLICT');
1264
+ }
916
1265
  this.launch(r);
917
1266
  return this.status(plan.aid);
918
1267
  }
919
- resume(aid, actor) {
1268
+ /**
1269
+ * Start the App one-shot contract. This deliberately lives beside the CLI
1270
+ * v1 start() path so old `ec agent new/initialize` journals retain their
1271
+ * historical fingerprint and shape.
1272
+ */
1273
+ startOneShot(plan, actor, clientRequestId, dryRun = false) {
1274
+ if (this.deps.authorize && !this.deps.authorize(actor))
1275
+ failure('NOT_ALLOWED');
1276
+ if (!UUID_V4.test(clientRequestId))
1277
+ failure('INVALID_ARGS', 'clientRequestId must be a UUID-v4');
1278
+ if (!plan || typeof plan !== 'object' || Array.isArray(plan) || typeof plan.aid !== 'string') {
1279
+ failure('INVALID_ARGS', 'Invalid initialization plan');
1280
+ }
1281
+ // Freeze owned data before scheduling any asynchronous side effects.
1282
+ plan = JSON.parse(JSON.stringify(plan));
1283
+ const existing = readInitialization(plan.aid);
1284
+ let fingerprint;
1285
+ try {
1286
+ fingerprint = initializationFingerprintV2(plan);
1287
+ }
1288
+ catch {
1289
+ failure(existing ? 'INITIALIZE_PLAN_CONFLICT' : 'INVALID_ARGS', 'Invalid initialization plan');
1290
+ }
1291
+ if (existing) {
1292
+ if (recordMode(existing) !== 'one_shot'
1293
+ || existing.actor !== actor
1294
+ || existing.clientRequestId !== clientRequestId
1295
+ || existing.fingerprint !== fingerprint) {
1296
+ failure('INITIALIZE_PLAN_CONFLICT');
1297
+ }
1298
+ const config = loadAgent(plan.aid);
1299
+ if (existing.status === 'complete'
1300
+ && (!config || config.initialization?.operationId !== existing.operationId)) {
1301
+ failure('INITIALIZE_STATE_INVALID');
1302
+ }
1303
+ if (dryRun)
1304
+ return { ok: true, dryRun: true, accepted: true, aid: plan.aid, creationId: existing.creationId, operationId: existing.operationId, mode: 'one_shot', fingerprint };
1305
+ const result = {
1306
+ ...this.status(plan.aid), accepted: true, aid: plan.aid,
1307
+ creationId: existing.creationId, operationId: existing.operationId, mode: 'one_shot',
1308
+ };
1309
+ return result;
1310
+ }
1311
+ // Environmental validation belongs to new work. Receipt reconciliation
1312
+ // above only compares the original frozen fingerprint, so an already
1313
+ // accepted request remains recoverable if its project or model catalog
1314
+ // changes while the caller is waiting for the lost receipt.
1315
+ validateInitializationPlan(plan);
1316
+ if (fs.existsSync(agentConfig(plan.aid)) || fs.existsSync(aidLocalDir(plan.aid))) {
1317
+ failure('INITIALIZE_TARGET_EXISTS');
1318
+ }
1319
+ if (dryRun) {
1320
+ const { persona, ...safe } = plan;
1321
+ return { ok: true, dryRun: true, aid: plan.aid, mode: 'one_shot', plan: safe, fingerprint, persona: { provided: persona !== undefined } };
1322
+ }
1323
+ const now = Date.now();
1324
+ const r = {
1325
+ version: 2,
1326
+ mode: 'one_shot',
1327
+ operationId: `init-${randomBytes(12).toString('hex')}`,
1328
+ creationId: randomUUID(),
1329
+ clientRequestId,
1330
+ requesterAid: actor,
1331
+ fingerprint,
1332
+ fingerprintVersion: 'sha256-json-v1-normalized',
1333
+ actor,
1334
+ plan,
1335
+ status: 'in_progress',
1336
+ phase: 'planned',
1337
+ startedAt: now,
1338
+ updatedAt: now,
1339
+ bindAttempt: {
1340
+ state: 'not_started', subjectAid: plan.aid, ownerAid: plan.ownerAid,
1341
+ baseRelationVersion: 0, targetRelationVersion: 1, updatedAt: now,
1342
+ },
1343
+ avatarAccepted: plan.avatarFile !== undefined || plan.avatarUrl !== undefined,
1344
+ };
1345
+ const claim = claimAgentCreation({
1346
+ aid: plan.aid, mode: 'one_shot', creationId: r.creationId, operationId: r.operationId,
1347
+ actor, requesterAid: actor, ownerAid: plan.ownerAid, clientRequestId, fingerprint,
1348
+ });
1349
+ if (!claim.claimed) {
1350
+ if (claim.claim.mode === 'one_shot' && claim.claim.actor === actor
1351
+ && claim.claim.clientRequestId === clientRequestId && claim.claim.fingerprint === fingerprint) {
1352
+ if (claim.claim.status !== 'in_progress' || !UUID_V4.test(claim.claim.creationId)
1353
+ || !claim.claim.operationId || !/^init-[a-f0-9]{24}$/.test(claim.claim.operationId)) {
1354
+ failure('INITIALIZE_STATE_INVALID', 'The accepted creation receipt is incomplete');
1355
+ }
1356
+ // Reuse the durable claim identity. Competing same-request callers
1357
+ // race only on exclusive journal publication; exactly one launches.
1358
+ r.creationId = claim.claim.creationId;
1359
+ r.operationId = claim.claim.operationId;
1360
+ }
1361
+ else
1362
+ failure('INITIALIZE_PLAN_CONFLICT');
1363
+ }
1364
+ if (!saveInitializationExclusive(r)) {
1365
+ const winner = readInitialization(plan.aid);
1366
+ if (winner && recordMode(winner) === 'one_shot' && winner.actor === actor
1367
+ && winner.clientRequestId === clientRequestId && winner.fingerprint === fingerprint) {
1368
+ return { ...this.status(plan.aid), accepted: true, aid: plan.aid, creationId: winner.creationId, operationId: winner.operationId, mode: 'one_shot' };
1369
+ }
1370
+ failure('INITIALIZE_PLAN_CONFLICT');
1371
+ }
1372
+ this.launch(r);
1373
+ const result = {
1374
+ ...this.status(plan.aid), accepted: true, aid: plan.aid,
1375
+ creationId: r.creationId, operationId: r.operationId, mode: 'one_shot',
1376
+ };
1377
+ return result;
1378
+ }
1379
+ resume(aid, actor, clientRequestId) {
920
1380
  if (this.deps.authorize && !this.deps.authorize(actor))
921
1381
  failure('NOT_ALLOWED');
922
1382
  if (!isValidAid(aid))
923
1383
  failure('INVALID_ARGS', 'Invalid initialization AID');
1384
+ assertAgentAidAvailable(aid);
924
1385
  const r = readInitialization(aid);
925
1386
  if (!r)
926
1387
  failure('NOT_FOUND');
927
1388
  if (r.actor !== actor)
928
1389
  failure('INITIALIZE_OWNER_MISMATCH');
1390
+ if (recordMode(r) === 'one_shot') {
1391
+ if (!clientRequestId)
1392
+ failure('INITIALIZE_REQUEST_ID_REQUIRED', 'One-shot recovery requires the original clientRequestId');
1393
+ if (!UUID_V4.test(clientRequestId))
1394
+ failure('INVALID_ARGS', 'clientRequestId must be a UUID-v4');
1395
+ if (clientRequestId !== r.clientRequestId)
1396
+ failure('INITIALIZE_PLAN_CONFLICT', 'Initialization request does not match the original clientRequestId');
1397
+ }
929
1398
  if (r.status === 'cancelled')
930
1399
  failure('INITIALIZE_CANCELLED');
931
1400
  if (r.status !== 'complete' && !this.running.has(aid)) {
932
1401
  validateInitializationPlan(r.plan);
933
1402
  r.status = 'in_progress';
934
- delete r.error;
935
- delete r.code;
1403
+ if (r.bindAttempt?.state === 'unknown') {
1404
+ // A prior local diagnostic (for example TARGET_CHANGED after a
1405
+ // compatible config migration) must not leak through the recovery
1406
+ // receipt. The SDK submission is still uncertain, so keep the
1407
+ // unknown state and expose the fail-closed diagnostic immediately.
1408
+ r.phase = 'ownerpending';
1409
+ r.code = 'INITIALIZE_BIND_UNKNOWN';
1410
+ r.error = 'Owner bind result was lost; waiting for fresh consensus';
1411
+ }
1412
+ else {
1413
+ delete r.error;
1414
+ delete r.code;
1415
+ }
936
1416
  saveInitialization(r);
937
1417
  this.launch(r);
938
1418
  }
@@ -951,18 +1431,28 @@ export class AgentInitializationService {
951
1431
  // requested Owner is observable; other failures still require an explicit --resume.
952
1432
  const lostConsensusRace = record.status === 'failed' && record.code === 'CONSENSUS_REQUIRED'
953
1433
  && record.plan.ownerAid === ownerAid;
954
- if (!waitingForOwner && !lostConsensusRace)
1434
+ const unknownBind = record.mode === 'one_shot' && record.bindAttempt?.state === 'unknown';
1435
+ if ((!waitingForOwner && !lostConsensusRace) && !unknownBind)
955
1436
  return;
956
- this.resume(aid, record.actor);
1437
+ this.resume(aid, record.actor, recordMode(record) === 'one_shot' ? record.clientRequestId : undefined);
957
1438
  }
958
1439
  catch (error) {
959
1440
  logger.warn(`[Initialization] Owner-consensus recovery failed for ${aid}: ${error instanceof Error ? error.message : String(error)}`);
960
1441
  }
961
1442
  }
962
- async cancel(aid) {
1443
+ /** Optional actor is required at public control adapters; omitted only by trusted disable/delete. */
1444
+ async cancel(aid, actor) {
1445
+ if (!isValidAid(aid))
1446
+ failure('INVALID_ARGS', 'Invalid initialization AID');
1447
+ if (actor !== undefined && this.deps.authorize && !this.deps.authorize(actor))
1448
+ failure('NOT_ALLOWED');
963
1449
  const r = readInitialization(aid);
1450
+ if (r && actor !== undefined && r.actor !== actor)
1451
+ failure('INITIALIZE_OWNER_MISMATCH');
964
1452
  if (!r || r.status === 'complete')
965
1453
  return;
1454
+ clearTimeout(this.ownerRechecks.get(aid));
1455
+ this.ownerRechecks.delete(aid);
966
1456
  r.status = 'cancelled';
967
1457
  r.code = 'INITIALIZE_CANCELLED';
968
1458
  saveInitialization(r);
@@ -985,6 +1475,8 @@ export class AgentInitializationService {
985
1475
  }
986
1476
  launch(r) {
987
1477
  const aid = r.plan.aid;
1478
+ clearTimeout(this.ownerRechecks.get(aid));
1479
+ this.ownerRechecks.delete(aid);
988
1480
  const work = Promise.resolve().then(() => this.run(r)).catch(error => {
989
1481
  // Cancellation wins over a stale worker, including delete while network I/O was pending.
990
1482
  let current;
@@ -994,31 +1486,80 @@ export class AgentInitializationService {
994
1486
  catch {
995
1487
  return;
996
1488
  }
997
- if (!current || current.status === 'cancelled')
1489
+ if (!current || current.status === 'cancelled' || current.status === 'complete'
1490
+ || current.operationId !== r.operationId || current.fingerprint !== r.fingerprint
1491
+ || current.creationId !== r.creationId)
1492
+ return;
1493
+ if (current.ownershipBinding
1494
+ && JSON.stringify(current.ownershipBinding) !== JSON.stringify(r.ownershipBinding))
998
1495
  return;
999
1496
  r.status = 'failed';
1000
1497
  r.code = error.code ?? 'INITIALIZE_FAILED';
1001
1498
  // External provider errors may contain credentials or payloads; expose the failing phase instead.
1002
1499
  r.error = `Initialization failed at ${r.phase} (${r.code})`;
1500
+ const errno = error;
1501
+ const syscall = typeof errno.syscall === 'string' && /^[a-z_]+$/i.test(errno.syscall) ? errno.syscall : 'unknown';
1502
+ logger.warn(`[Initialization] worker failed for ${aid}: phase=${r.phase} code=${initializationErrorCode(error, 'INITIALIZE_FAILED')} syscall=${syscall}`);
1003
1503
  saveInitialization(r);
1004
1504
  }).catch(() => { })
1005
- .finally(() => this.running.delete(aid));
1505
+ .finally(() => {
1506
+ this.running.delete(aid);
1507
+ // Before hot-load there is no attached channel to emit an Owner event.
1508
+ // Keep observing the durable attempt without another bind or App action.
1509
+ if (!this.deps.ownershipBeforePublication || recordMode(r) !== 'one_shot')
1510
+ return;
1511
+ let current;
1512
+ try {
1513
+ current = readInitialization(aid);
1514
+ }
1515
+ catch {
1516
+ return;
1517
+ }
1518
+ if (current?.status !== 'in_progress' || current.phase !== 'ownerpending'
1519
+ || current.operationId !== r.operationId || current.hotLoaded)
1520
+ return;
1521
+ const timer = setTimeout(() => {
1522
+ this.ownerRechecks.delete(aid);
1523
+ this.resumeForOwner(aid, r.plan.ownerAid);
1524
+ }, 5_000);
1525
+ timer.unref?.();
1526
+ this.ownerRechecks.set(aid, timer);
1527
+ });
1006
1528
  this.running.set(aid, work);
1007
1529
  }
1008
1530
  check(r) {
1531
+ assertAgentAidAvailable(r.plan.aid);
1009
1532
  if (this.deps.authorize && !this.deps.authorize(r.actor))
1010
1533
  failure('NOT_ALLOWED');
1011
1534
  const current = readInitialization(r.plan.aid);
1012
1535
  if (!current || current.operationId !== r.operationId || current.status === 'cancelled')
1013
1536
  failure('INITIALIZE_CANCELLED');
1537
+ if (current.fingerprint !== r.fingerprint || current.creationId !== r.creationId
1538
+ || current.clientRequestId !== r.clientRequestId || current.actor !== r.actor
1539
+ || (current.version === 2 && initializationFingerprintV2(r.plan) !== current.fingerprint)) {
1540
+ failure('INITIALIZE_STATE_INVALID');
1541
+ }
1542
+ // An exact binding is write-once. A stale worker must never replace a
1543
+ // different task captured by another owner of this journal.
1544
+ if (current.ownershipBinding && JSON.stringify(current.ownershipBinding) !== JSON.stringify(r.ownershipBinding)) {
1545
+ failure('INITIALIZE_STATE_INVALID');
1546
+ }
1014
1547
  const config = loadAgent(r.plan.aid);
1015
1548
  if (r.configSaved && (!config || config.enabled === false))
1016
1549
  failure('INITIALIZE_TARGET_CHANGED');
1017
1550
  const baseagentConfig = config?.baseagents?.[r.plan.baseagent];
1018
- if (config && (config.initialization?.operationId !== r.operationId
1551
+ if (config && (config.initialization?.operationId !== r.operationId || config.initialization.mode !== 'supplied'
1019
1552
  || config.active_baseagent !== r.plan.baseagent || config.projects?.defaultPath !== r.plan.project
1020
- || baseagentConfig?.model !== r.plan.model
1021
- || baseagentConfig?.effort !== r.plan.effort)) {
1553
+ || (r.plan.model !== undefined && baseagentConfig?.model !== r.plan.model)
1554
+ || (r.plan.effort !== undefined && baseagentConfig?.effort !== r.plan.effort))) {
1555
+ failure('INITIALIZE_TARGET_CHANGED');
1556
+ }
1557
+ // Omitted fields use the existing defaults/migration selection, just as
1558
+ // they do on initial creation. Only explicit plan overrides are frozen.
1559
+ if (config && r.plan.provider !== undefined && baseagentConfig?.provider !== r.plan.provider)
1560
+ failure('INITIALIZE_TARGET_CHANGED');
1561
+ if (config && r.plan.chatmode !== undefined
1562
+ && ['private', 'group', 'nothuman'].some(scope => config.chatmode?.[scope] !== r.plan.chatmode?.[scope])) {
1022
1563
  failure('INITIALIZE_TARGET_CHANGED');
1023
1564
  }
1024
1565
  }
@@ -1027,26 +1568,185 @@ export class AgentInitializationService {
1027
1568
  r.phase = phase;
1028
1569
  saveInitialization(r);
1029
1570
  }
1571
+ async observeOwner(r) {
1572
+ this.check(r);
1573
+ if (recordMode(r) === 'one_shot') {
1574
+ r.ownerConfirmed = false;
1575
+ saveInitialization(r);
1576
+ }
1577
+ const observation = await this.deps.checkOwner(r.plan.aid, r.plan.ownerAid);
1578
+ this.check(r);
1579
+ let status = typeof observation === 'string' ? observation : observation.status;
1580
+ const ownerAid = typeof observation === 'string'
1581
+ ? status === 'confirmed' ? r.plan.ownerAid : undefined : observation.ownerAid;
1582
+ const checkedAt = typeof observation === 'string' ? undefined : observation.checkedAt;
1583
+ const details = typeof observation === 'string' ? undefined : observation;
1584
+ if (!['confirmed', 'pending', 'conflict'].includes(status)
1585
+ || (ownerAid !== undefined && (typeof ownerAid !== 'string' || !isValidAid(ownerAid)))
1586
+ || (checkedAt !== undefined && (!Number.isFinite(checkedAt) || checkedAt < 0))
1587
+ || (details?.consensusStatus !== undefined && !INITIALIZATION_CONSENSUS_STATUSES.includes(details.consensusStatus))
1588
+ || (details?.relationVersion !== undefined && (!Number.isSafeInteger(details.relationVersion) || details.relationVersion < 0))
1589
+ || (details?.lock !== undefined && details.lock !== 'locked' && details.lock !== 'unlocked')
1590
+ || (details?.code !== undefined && (typeof details.code !== 'string' || !INITIALIZATION_ERROR_CODE.test(details.code)))
1591
+ || (details?.retryable !== undefined && typeof details.retryable !== 'boolean'))
1592
+ failure('INITIALIZE_STATE_INVALID');
1593
+ if (status === 'confirmed' && ownerAid !== r.plan.ownerAid)
1594
+ status = 'conflict';
1595
+ r.ownerConsensus = {
1596
+ status, ...(ownerAid ? { ownerAid } : {}), ...(checkedAt !== undefined ? { checkedAt } : {}),
1597
+ ...(details?.consensusStatus !== undefined ? { consensusStatus: details.consensusStatus } : {}),
1598
+ ...(details?.relationVersion !== undefined ? { relationVersion: details.relationVersion } : {}),
1599
+ ...(details?.lock !== undefined ? { lock: details.lock } : {}),
1600
+ ...(details?.code !== undefined ? { code: details.code } : {}),
1601
+ ...(details?.retryable !== undefined ? { retryable: details.retryable } : {}),
1602
+ };
1603
+ // This is an observation, not the final completion grant. Any previous
1604
+ // confirmation must be cleared before an activation/welcome await.
1605
+ if (recordMode(r) === 'one_shot')
1606
+ r.ownerConfirmed = false;
1607
+ return status;
1608
+ }
1609
+ async ensureOwnerBinding(r) {
1610
+ const p = r.plan;
1611
+ if (this.deps.bindOwner) {
1612
+ // Recovery revisits this checkpoint; an accepted bind must remain stable.
1613
+ // Only the supplied legacy adapter consults the current SDK task snapshot.
1614
+ // v2 never submits a second bind. `submitting` is intentionally
1615
+ // converted to `unknown` on resume because the daemon may have crashed
1616
+ // after the SDK side effect but before the returned task was persisted.
1617
+ if (recordMode(r) === 'one_shot' && r.bindAttempt?.state === 'submitting') {
1618
+ r.bindAttempt = { ...r.bindAttempt, state: 'unknown', updatedAt: Date.now() };
1619
+ r.phase = 'ownerpending';
1620
+ r.code = 'INITIALIZE_BIND_UNKNOWN';
1621
+ r.error = 'Owner bind result was lost; waiting for fresh consensus';
1622
+ saveInitialization(r);
1623
+ }
1624
+ const oneShotAttempt = recordMode(r) === 'one_shot' ? r.bindAttempt?.state : undefined;
1625
+ if (oneShotAttempt === 'unknown') {
1626
+ // A successful target check may recover a previous local failure, but
1627
+ // it does not resolve the original SDK submission uncertainty.
1628
+ r.phase = 'ownerpending';
1629
+ r.code = 'INITIALIZE_BIND_UNKNOWN';
1630
+ r.error = 'Owner bind result was lost; waiting for fresh consensus';
1631
+ saveInitialization(r);
1632
+ }
1633
+ const bindStillActive = oneShotAttempt === 'submitted' || oneShotAttempt === 'unknown' || oneShotAttempt === 'confirmed'
1634
+ || (recordMode(r) !== 'one_shot' && (this.deps.ownerBindActive
1635
+ ? this.deps.ownerBindActive(p.aid, p.ownerAid)
1636
+ : r.ownerBindSubmitted === true));
1637
+ if (!bindStillActive && oneShotAttempt !== 'submitting') {
1638
+ this.phase(r, 'binding_owner');
1639
+ if (recordMode(r) === 'one_shot') {
1640
+ r.bindAttempt = {
1641
+ state: 'submitting', subjectAid: p.aid, ownerAid: p.ownerAid,
1642
+ baseRelationVersion: 0, targetRelationVersion: 1, updatedAt: Date.now(),
1643
+ };
1644
+ saveInitialization(r);
1645
+ let view;
1646
+ try {
1647
+ view = await this.deps.bindOwner(p.aid, p.ownerAid);
1648
+ }
1649
+ catch (error) {
1650
+ // Permission/config changes and cancellation win even when a
1651
+ // bind response or error arrives after the control request.
1652
+ this.check(r);
1653
+ // The adapter proves that setup or an audited SDK read-only
1654
+ // preflight failed before submission. No remote side effect has
1655
+ // occurred, so the same frozen creation remains retryable.
1656
+ if (error?.code === 'INITIALIZE_BIND_NOT_STARTED') {
1657
+ const causeCode = error.causeCode;
1658
+ r.bindAttempt = { ...r.bindAttempt, state: 'not_started', updatedAt: Date.now(),
1659
+ failureCode: initializationErrorCode(causeCode !== undefined ? { code: causeCode } : error, 'INITIALIZE_BIND_NOT_STARTED') };
1660
+ saveInitialization(r);
1661
+ throw error;
1662
+ }
1663
+ // An unclassified bind rejection has an unknown side effect.
1664
+ // Never infer a task from a latest snapshot and
1665
+ // never submit another bind automatically.
1666
+ r.bindAttempt = { ...r.bindAttempt, state: 'unknown', updatedAt: Date.now(),
1667
+ failureCode: initializationErrorCode(error, 'INITIALIZE_BIND_FAILED') };
1668
+ r.phase = 'ownerpending';
1669
+ r.code = 'INITIALIZE_BIND_UNKNOWN';
1670
+ r.error = 'Owner bind result was lost; waiting for fresh consensus';
1671
+ saveInitialization(r);
1672
+ logger.warn(`[Initialization] bind result unknown for ${p.aid}: ${r.bindAttempt.failureCode}`);
1673
+ return false;
1674
+ }
1675
+ this.check(r);
1676
+ const task = (view && typeof view === 'object' && !Array.isArray(view))
1677
+ ? (view.task ?? view)
1678
+ : undefined;
1679
+ const binding = creationOwnershipBinding(task, p.aid, p.ownerAid);
1680
+ if (!binding) {
1681
+ r.bindAttempt = { ...r.bindAttempt, state: 'unknown', updatedAt: Date.now() };
1682
+ r.phase = 'ownerpending';
1683
+ r.code = 'INITIALIZE_BIND_UNKNOWN';
1684
+ r.error = 'Owner bind returned no verifiable task; waiting for fresh consensus';
1685
+ saveInitialization(r);
1686
+ return false;
1687
+ }
1688
+ r.ownershipBinding = binding;
1689
+ r.bindAttempt = {
1690
+ state: 'submitted', operationId: binding.operationId, subjectAid: p.aid,
1691
+ ownerAid: p.ownerAid, baseRelationVersion: 0, targetRelationVersion: 1,
1692
+ updatedAt: Date.now(),
1693
+ };
1694
+ r.ownerBindSubmitted = true;
1695
+ delete r.error;
1696
+ delete r.code;
1697
+ // A checkpoint failure is not a failed SDK call. Preserve its exact
1698
+ // task for the worker's failure checkpoint instead of mixing an
1699
+ // unknown attempt with an already verified operation ID.
1700
+ saveInitialization(r);
1701
+ }
1702
+ else {
1703
+ await this.deps.bindOwner(p.aid, p.ownerAid);
1704
+ this.check(r);
1705
+ r.ownerBindSubmitted = true;
1706
+ }
1707
+ }
1708
+ }
1709
+ return true;
1710
+ }
1030
1711
  async run(r) {
1031
1712
  const p = r.plan;
1032
- this.phase(r, 'registering_aid');
1033
- await this.deps.register(p.aid, p.ownerAid);
1034
- this.phase(r, 'config_saved');
1035
- fs.mkdirSync(p.project, { recursive: true });
1036
- if (!loadAgent(p.aid)) {
1037
- saveAgent({
1038
- $schema_version: CONFIG_SCHEMA_VERSION, aid: p.aid, enabled: true, lifecycle: 'created',
1039
- initialization: { mode: 'supplied', operationId: r.operationId }, channels: [],
1040
- projects: { defaultPath: p.project }, active_baseagent: p.baseagent,
1041
- baseagents: {
1042
- [p.baseagent]: {
1043
- ...(p.model ? { model: p.model } : {}),
1044
- ...(p.effort ? { effort: p.effort } : {}),
1045
- },
1046
- }, chatmode: { private: 'interactive', group: 'proactive', nothuman: 'proactive' },
1047
- });
1048
- }
1049
- r.configSaved = true;
1713
+ // Resume from the durable checkpoint. In particular, never call aidCreate
1714
+ // again after the bind/activation stages have created the local config.
1715
+ if (!r.configSaved) {
1716
+ if (!r.aidRegistered) {
1717
+ this.phase(r, 'registering_aid');
1718
+ await this.deps.register(p.aid, p.ownerAid, recordMode(r));
1719
+ this.check(r);
1720
+ r.aidRegistered = true;
1721
+ saveInitialization(r);
1722
+ }
1723
+ fs.mkdirSync(p.project, { recursive: true });
1724
+ if (!loadAgent(p.aid)) {
1725
+ saveAgent({
1726
+ $schema_version: CONFIG_SCHEMA_VERSION, aid: p.aid, enabled: true, lifecycle: 'created',
1727
+ initialization: { mode: 'supplied', operationId: r.operationId }, channels: [],
1728
+ projects: { defaultPath: p.project }, active_baseagent: p.baseagent,
1729
+ baseagents: {
1730
+ [p.baseagent]: {
1731
+ ...(p.provider ? { provider: p.provider } : {}),
1732
+ ...(p.model ? { model: p.model } : {}),
1733
+ ...(p.effort ? { effort: p.effort } : {}),
1734
+ },
1735
+ }, chatmode: p.chatmode ?? { private: 'interactive', group: 'proactive', nothuman: 'proactive' },
1736
+ });
1737
+ }
1738
+ // A one-shot plan owns the runtime configuration from its first write.
1739
+ if (p.chatmode !== undefined) {
1740
+ const config = loadAgent(p.aid);
1741
+ if (config && JSON.stringify(config.chatmode ?? null) !== JSON.stringify(p.chatmode)) {
1742
+ saveAgent({ ...config, chatmode: p.chatmode });
1743
+ }
1744
+ }
1745
+ this.check(r);
1746
+ r.configSaved = true;
1747
+ r.phase = 'config_saved';
1748
+ saveInitialization(r);
1749
+ }
1050
1750
  this.phase(r, 'persona_saved');
1051
1751
  ensureAgentDirSkeleton(p.aid);
1052
1752
  ensureInitialRoleRegistry(p.aid);
@@ -1056,6 +1756,26 @@ export class AgentInitializationService {
1056
1756
  failure('INITIALIZE_PLAN_CONFLICT');
1057
1757
  fs.writeFileSync(file, p.persona, { encoding: 'utf8', mode: 0o600 });
1058
1758
  }
1759
+ const bindBeforePublication = recordMode(r) === 'one_shot' && this.deps.ownershipBeforePublication === true;
1760
+ if (bindBeforePublication) {
1761
+ // The explicit SDK bind creates the first card and its real declaration.
1762
+ // Its receipt must be durable before publishing the requested profile.
1763
+ if (!this.deps.bindOwner)
1764
+ failure('INITIALIZE_BIND_UNAVAILABLE');
1765
+ const pendingConfig = loadAgent(p.aid);
1766
+ if (pendingConfig.lifecycle !== 'ownerpending')
1767
+ saveAgent({ ...pendingConfig, lifecycle: 'ownerpending' });
1768
+ if (!await this.ensureOwnerBinding(r))
1769
+ return;
1770
+ this.phase(r, 'ownerpending');
1771
+ const ownership = await this.observeOwner(r);
1772
+ if (ownership === 'pending') {
1773
+ saveInitialization(r);
1774
+ return;
1775
+ }
1776
+ if (ownership === 'conflict')
1777
+ failure('INITIALIZE_OWNER_CONFLICT');
1778
+ }
1059
1779
  const resolvedAvatarFile = p.avatarFile;
1060
1780
  this.phase(r, 'uploading_agentmd');
1061
1781
  let remote;
@@ -1064,6 +1784,8 @@ export class AgentInitializationService {
1064
1784
  try {
1065
1785
  remote = await this.deps.fetch(p.aid);
1066
1786
  this.check(r);
1787
+ if (remote.verified)
1788
+ assertAgentCardReusable(p.aid, { content: remote.content, verification: { status: 'verified' } });
1067
1789
  if (!matchesCard(remote.content, p) || !remote.verified) {
1068
1790
  if (r.published || (r.previousCardHash !== 'none' && cardHash(remote.content) !== r.previousCardHash)) {
1069
1791
  failure('INITIALIZE_AGENTMD_VERIFY_FAILED');
@@ -1073,6 +1795,8 @@ export class AgentInitializationService {
1073
1795
  }
1074
1796
  catch (error) {
1075
1797
  const code = String(error.code ?? '');
1798
+ if (code === 'HOST_AID_RESERVED')
1799
+ throw error;
1076
1800
  const message = error instanceof Error ? error.message : String(error);
1077
1801
  if (code !== 'AGENTMD_NOT_FOUND' && !/not found|404|missing/i.test(message)) {
1078
1802
  failure('INITIALIZE_AGENTMD_VERIFY_FAILED');
@@ -1084,10 +1808,14 @@ export class AgentInitializationService {
1084
1808
  try {
1085
1809
  const previous = await this.deps.fetch(p.aid);
1086
1810
  this.check(r);
1811
+ if (previous.verified)
1812
+ assertAgentCardReusable(p.aid, { content: previous.content, verification: { status: 'verified' } });
1087
1813
  r.previousCardHash = cardHash(previous.content);
1088
1814
  }
1089
1815
  catch (error) {
1090
1816
  const code = String(error.code ?? '');
1817
+ if (code === 'HOST_AID_RESERVED')
1818
+ throw error;
1091
1819
  const message = error instanceof Error ? error.message : String(error);
1092
1820
  if (code !== 'AGENTMD_NOT_FOUND' && !/not found|404|missing/i.test(message))
1093
1821
  failure('INITIALIZE_AGENTMD_VERIFY_FAILED');
@@ -1099,7 +1827,10 @@ export class AgentInitializationService {
1099
1827
  if (!remote) {
1100
1828
  r.publicationStarted = true;
1101
1829
  saveInitialization(r);
1102
- await this.deps.publish(p.aid, buildInitialAgentMd(p));
1830
+ if (bindBeforePublication)
1831
+ await this.deps.publish(p.aid, buildInitialAgentMd(p), p.ownerAid);
1832
+ else
1833
+ await this.deps.publish(p.aid, buildInitialAgentMd(p));
1103
1834
  this.check(r);
1104
1835
  r.published = true;
1105
1836
  saveInitialization(r);
@@ -1111,10 +1842,15 @@ export class AgentInitializationService {
1111
1842
  if (!fs.existsSync(agentMdPath(p.aid)) || !matchesCard(fs.readFileSync(agentMdPath(p.aid), 'utf8'), p)) {
1112
1843
  failure('INITIALIZE_AGENTMD_VERIFY_FAILED');
1113
1844
  }
1845
+ r.published = true;
1846
+ r.verified = true;
1847
+ saveInitialization(r);
1114
1848
  if ((resolvedAvatarFile || p.avatarUrl) && !r.avatarUploaded) {
1849
+ this.phase(r, 'uploading_avatar');
1115
1850
  const avatar = resolvedAvatarFile
1116
1851
  ? await uploadAvatarFile(p.aid, resolvedAvatarFile)
1117
1852
  : await uploadAvatarUrl(p.aid, p.avatarUrl);
1853
+ this.check(r);
1118
1854
  if (!avatar.ok)
1119
1855
  failure('INITIALIZE_AVATAR_FAILED', avatar.error || 'avatar upload failed');
1120
1856
  r.avatarUploaded = true;
@@ -1129,27 +1865,24 @@ export class AgentInitializationService {
1129
1865
  }
1130
1866
  this.phase(r, 'hot_loading');
1131
1867
  await this.deps.hotLoad(p.aid);
1132
- if (this.deps.bindOwner) {
1133
- // Owner-consensus recovery and --resume re-run from the start. The SDK keeps emitting
1134
- // ownership events for a few seconds after approval, each invalidating the cached
1135
- // consensus, so resubmitting an accepted bind then fails with CONSENSUS_REQUIRED.
1136
- // Retry when no pending or completed task for this Owner remains.
1137
- const bindStillActive = this.deps.ownerBindActive
1138
- ? this.deps.ownerBindActive(p.aid, p.ownerAid)
1139
- : r.ownerBindSubmitted === true;
1140
- if (!bindStillActive) {
1141
- this.phase(r, 'binding_owner');
1142
- await this.deps.bindOwner(p.aid, p.ownerAid);
1143
- r.ownerBindSubmitted = true;
1144
- }
1145
- }
1146
- this.phase(r, 'ownerpending');
1147
- const ownership = await this.deps.checkOwner(p.aid, p.ownerAid);
1148
1868
  this.check(r);
1149
- if (ownership === 'pending')
1869
+ r.hotLoaded = true;
1870
+ saveInitialization(r);
1871
+ if (!await this.ensureOwnerBinding(r))
1872
+ return;
1873
+ this.phase(r, 'ownerpending');
1874
+ const ownership = await this.observeOwner(r);
1875
+ if (ownership === 'pending') {
1876
+ saveInitialization(r);
1150
1877
  return;
1878
+ }
1151
1879
  if (ownership === 'conflict')
1152
1880
  failure('INITIALIZE_OWNER_CONFLICT', 'Fresh Ownership consensus does not confirm the requested Owner');
1881
+ if (recordMode(r) === 'one_shot') {
1882
+ delete r.error;
1883
+ delete r.code;
1884
+ saveInitialization(r);
1885
+ }
1153
1886
  this.phase(r, 'activating');
1154
1887
  if (p.persona !== undefined && fs.readFileSync(path.join(agentPersonalDir(p.aid), 'persona.md'), 'utf8') !== p.persona) {
1155
1888
  failure('INITIALIZE_PLAN_CONFLICT');
@@ -1160,10 +1893,33 @@ export class AgentInitializationService {
1160
1893
  this.check(r);
1161
1894
  if (!result.ok)
1162
1895
  failure(result.code ?? 'INITIALIZE_WELCOME_UNAVAILABLE');
1896
+ // Activation prepares/delivers the welcome and may await remote services.
1897
+ // The Owner observed before that await cannot authorize completion now.
1898
+ r.welcome = result.welcome;
1899
+ const finalOwnership = await this.observeOwner(r);
1900
+ if (finalOwnership === 'pending' || finalOwnership === 'conflict') {
1901
+ const config = loadAgent(p.aid);
1902
+ if (config.lifecycle !== 'ownerpending')
1903
+ saveAgent({ ...config, lifecycle: 'ownerpending' });
1904
+ }
1905
+ if (finalOwnership === 'pending') {
1906
+ r.phase = 'ownerpending';
1907
+ saveInitialization(r);
1908
+ return;
1909
+ }
1910
+ if (finalOwnership === 'conflict')
1911
+ failure('INITIALIZE_OWNER_CONFLICT', 'Fresh Ownership consensus changed before initialization completed');
1163
1912
  if (loadAgent(p.aid)?.lifecycle !== 'active')
1164
1913
  failure('INITIALIZE_STATE_INVALID');
1914
+ if (recordMode(r) === 'one_shot') {
1915
+ r.ownerConfirmed = true;
1916
+ delete r.error;
1917
+ delete r.code;
1918
+ if (r.bindAttempt?.state === 'submitted')
1919
+ r.bindAttempt = { ...r.bindAttempt, state: 'confirmed', updatedAt: Date.now() };
1920
+ // `unknown` remains visible: confirmed ownership does not invent a task ID.
1921
+ }
1165
1922
  // Activation is durable even if a post-commit network delivery failed.
1166
- r.welcome = result.welcome;
1167
1923
  r.phase = 'active';
1168
1924
  r.status = 'complete';
1169
1925
  saveInitialization(r);
@@ -1183,7 +1939,9 @@ export async function executeLocalInitializationCommand(service, command) {
1183
1939
  const record = readInitialization(parsed.aid);
1184
1940
  if (!record)
1185
1941
  return { ok: false, code: 'NOT_FOUND', error: 'No initialization record' };
1186
- return service.resume(parsed.aid, record.actor);
1942
+ return parsed.clientRequestId === undefined
1943
+ ? service.resume(parsed.aid, record.actor)
1944
+ : service.resume(parsed.aid, record.actor, parsed.clientRequestId);
1187
1945
  }
1188
1946
  const plan = resolveInitializationPlan(argv);
1189
1947
  const modelError = await validateInitializationModelArgs(plan);
@@ -1207,7 +1965,7 @@ export function parseInitializationArgs(args) {
1207
1965
  if (!resume && resolveAgentCreateMode(args) !== 'initialize')
1208
1966
  throw new Error('--bootstrap cannot initialize an agent');
1209
1967
  const booleans = new Set(resume ? ['--resume'] : ['--initialize', '--non-interactive', '--dry-run']);
1210
- const strings = new Set(resume ? ['--wait', '--format'] : [
1968
+ const strings = new Set(resume ? ['--wait', '--format', '--client-request-id'] : [
1211
1969
  '--project', '--baseagent', '--model', '--effort', '--owner', '--name', '--description', '--tags', '--type', '--avatar-file', '--avatar-url',
1212
1970
  '--persona-file', '--persona-text', '--wait', '--format',
1213
1971
  ]);
@@ -1241,7 +1999,7 @@ export function parseInitializationArgs(args) {
1241
1999
  const wait = values['--wait'] === undefined ? 60 : Number(values['--wait']);
1242
2000
  if (!Number.isInteger(wait) || wait < 0 || wait > 300)
1243
2001
  throw new Error('--wait must be an integer from 0 to 300');
1244
- return { aid: args[1], resume, dryRun: seen.has('--dry-run'), wait, values };
2002
+ return { aid: args[1], resume, dryRun: seen.has('--dry-run'), wait, clientRequestId: values['--client-request-id'], values };
1245
2003
  }
1246
2004
  export function resolveInitializationPlan(args, context) {
1247
2005
  const parsed = parseInitializationArgs(args);