evolcore 0.0.39 → 0.0.41-test.0

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 (153) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +31 -20
  3. package/bin/codex-managed-hook.mjs +11 -0
  4. package/bin/ec-safe-output.js +25 -3
  5. package/dist/agents/baseagent-availability.js +1 -0
  6. package/dist/agents/claude-runner.js +53 -152
  7. package/dist/agents/codex-runner.js +485 -241
  8. package/dist/agents/ecagent-runner.js +48 -18
  9. package/dist/agents/gemini-runner.js +27 -8
  10. package/dist/agents/runner-types.js +39 -9
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/aid/control-aid.js +23 -98
  14. package/dist/aun/aid/ownership-operation.js +1 -3
  15. package/dist/aun/group/identity.js +8 -0
  16. package/dist/aun/group/invite-service.js +6 -0
  17. package/dist/aun/msg/managed-operation.js +4 -4
  18. package/dist/aun/msg/p2p.js +28 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +99 -52
  22. package/dist/channels/daemon.js +24 -4
  23. package/dist/channels/dingtalk.js +8 -2
  24. package/dist/channels/feishu.js +6 -1
  25. package/dist/channels/wecom.js +7 -3
  26. package/dist/cli/agent-command.js +2 -0
  27. package/dist/cli/agent-create.js +121 -23
  28. package/dist/cli/agent.js +10 -3
  29. package/dist/cli/aid-bind-command.js +4 -1
  30. package/dist/cli/aun-commands.js +82 -22
  31. package/dist/cli/daemon-commands.js +260 -26
  32. package/dist/cli/index.js +25 -13
  33. package/dist/cli/memory-command.js +33 -14
  34. package/dist/cli/restart-monitor.js +52 -13
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/task-context.js +1 -0
  38. package/dist/cli/trigger-command.js +2 -2
  39. package/dist/config/access-policy.js +2 -0
  40. package/dist/config/config-field-policy.js +1 -0
  41. package/dist/config/config-operation-service.js +17 -6
  42. package/dist/config/gateway-config.js +1 -1
  43. package/dist/config/peer-role-resolver.js +10 -8
  44. package/dist/contracts/ecweb-service-protocol.js +44 -0
  45. package/dist/core/agent-application-service.js +11 -1
  46. package/dist/core/agent-ipc-registration.js +4 -0
  47. package/dist/core/agent-runtime.js +6 -0
  48. package/dist/core/auth/agent-delegation.js +87 -9
  49. package/dist/core/auth/auth-gateway.js +3 -1
  50. package/dist/core/auth/authorization-audit.js +25 -4
  51. package/dist/core/auth/debug-context.js +5 -1
  52. package/dist/core/auth/operation-catalog.js +24 -0
  53. package/dist/core/command/agent-control.js +91 -12
  54. package/dist/core/command/command-handler.js +64 -47
  55. package/dist/core/command/connect-menu.js +23 -2
  56. package/dist/core/command/menu-catalog.js +49 -12
  57. package/dist/core/command/menu-handler.js +110 -105
  58. package/dist/core/command/menu-protocol.js +29 -3
  59. package/dist/core/command/role-menu.js +7 -6
  60. package/dist/core/command/slash-gate.js +22 -5
  61. package/dist/core/command/slash-handler.js +121 -102
  62. package/dist/core/event-catalog.js +17 -0
  63. package/dist/core/interaction-router.js +2 -1
  64. package/dist/core/ipc-registration.js +44 -8
  65. package/dist/core/memory/batch-meta.js +2 -0
  66. package/dist/core/memory/consolidation-context.js +42 -51
  67. package/dist/core/memory/consolidation-ops-records.js +39 -7
  68. package/dist/core/memory/consolidation-trigger.js +72 -65
  69. package/dist/core/memory/consolidation.js +226 -20
  70. package/dist/core/memory/memory-writer.js +160 -34
  71. package/dist/core/memory/relation-idle-monitor.js +287 -0
  72. package/dist/core/memory/relation-sweep.js +206 -0
  73. package/dist/core/message/aun-ipc-sender.js +31 -5
  74. package/dist/core/message/aun-request-registry.js +97 -3
  75. package/dist/core/message/im-renderer.js +4 -0
  76. package/dist/core/message/message-admission.js +8 -4
  77. package/dist/core/message/message-bridge.js +96 -53
  78. package/dist/core/message/message-log.js +72 -0
  79. package/dist/core/message/message-queue.js +11 -5
  80. package/dist/core/message/outbound.js +70 -0
  81. package/dist/core/message/peer-mode.js +7 -2
  82. package/dist/core/message/response-engine.js +633 -191
  83. package/dist/core/model/model-catalog.js +7 -6
  84. package/dist/core/ownership/owner-resolver.js +384 -178
  85. package/dist/core/permission/ec-command-parser.js +129 -8
  86. package/dist/core/permission/tool-policy.js +35 -14
  87. package/dist/core/role/runtime-policy.js +64 -0
  88. package/dist/core/session/session-capsule.js +197 -0
  89. package/dist/core/session/session-manager.js +172 -18
  90. package/dist/core/session/session-mapper.js +2 -0
  91. package/dist/core/system-session/memory.js +3 -18
  92. package/dist/ecweb/basic-settings-service.js +709 -0
  93. package/dist/ecweb/providers-service.js +172 -0
  94. package/dist/index.js +95 -7
  95. package/dist/ipc.js +100 -19
  96. package/dist/stats/budget.js +1 -1
  97. package/dist/stats/db.js +48 -0
  98. package/dist/stats/index.js +3 -3
  99. package/dist/stats/price-resolver.js +304 -5
  100. package/dist/stats/query.js +328 -3
  101. package/dist/stats/writer.js +79 -6
  102. package/dist/trigger/application-service.js +12 -0
  103. package/dist/trigger/authorization.js +2 -2
  104. package/dist/trigger/feedback.js +18 -7
  105. package/dist/trigger/history.js +36 -0
  106. package/dist/trigger/manager.js +20 -3
  107. package/dist/trigger/parser.js +6 -3
  108. package/dist/trigger/patch.js +1 -1
  109. package/dist/trigger/scheduler.js +3 -0
  110. package/dist/trigger/system-definitions.js +43 -7
  111. package/dist/trigger/validation.js +13 -5
  112. package/dist/utils/ecweb-supervisor.js +31 -10
  113. package/dist/utils/error-utils.js +22 -4
  114. package/dist/utils/evolcore-version.js +3 -2
  115. package/dist/utils/host-info.js +52 -0
  116. package/dist/utils/npm-ops.js +2 -1
  117. package/dist/utils/package-version-info.js +1 -1
  118. package/dist/utils/upgrade-jobs.js +45 -5
  119. package/ecagent/dist/harness/agent-harness.js +4 -1
  120. package/kits/docs/INDEX.md +1 -1
  121. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  122. package/kits/docs/evolcore/INDEX.md +3 -2
  123. package/kits/docs/evolcore/agent-create.md +3 -2
  124. package/kits/docs/evolcore/agent.md +1 -1
  125. package/kits/docs/evolcore/aid.md +29 -12
  126. package/kits/docs/evolcore/config.md +9 -7
  127. package/kits/docs/evolcore/event.md +1 -0
  128. package/kits/docs/evolcore/fs.md +5 -0
  129. package/kits/docs/evolcore/memory-architecture.md +3 -4
  130. package/kits/docs/evolcore/memory-consolidation.md +28 -7
  131. package/kits/docs/evolcore/memory-tags.md +1 -1
  132. package/kits/docs/evolcore/memory.md +1 -1
  133. package/kits/docs/evolcore/menu-client.md +1 -1
  134. package/kits/docs/evolcore/menu-protocol.md +38 -0
  135. package/kits/docs/evolcore/msg.md +18 -2
  136. package/kits/docs/evolcore/session.md +14 -0
  137. package/kits/eck_manifest.json +3 -3
  138. package/kits/rules/04-relation.md +3 -2
  139. package/kits/schemas/agent-config.schema.13.json +20 -1
  140. package/kits/skills/aid-ability/SKILL.md +35 -6
  141. package/kits/templates/memory-consolidation/generalize.md +32 -4
  142. package/kits/templates/memory-consolidation/notes.md +2 -2
  143. package/kits/templates/memory-consolidation/promote.md +10 -2
  144. package/kits/templates/session-capsule/recovery.md +5 -0
  145. package/kits/templates/session-capsule/renew.md +5 -0
  146. package/kits/templates/system-fragments/baseagent.md +5 -0
  147. package/kits/templates/system-fragments/bootstrap.md +6 -6
  148. package/kits/templates/system-fragments/channel.md +1 -1
  149. package/kits/templates/system-fragments/memory.md +12 -3
  150. package/kits/templates/system-fragments/session.md +1 -1
  151. package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
  152. package/package.json +3 -3
  153. package/dist/stats/billing.js +0 -215
@@ -226,6 +226,11 @@ export function createAgentInitializationRuntime({ agentRegistry, agentMap, chan
226
226
  bindOwner: async (aid, ownerAid) => {
227
227
  await ownerResolver.bind(aid, ownerAid);
228
228
  },
229
+ ownerBindActive: (aid, ownerAid) => {
230
+ const task = ownerResolver.snapshot(aid).task;
231
+ return task?.operation === 'bind' && task.owner_aid === ownerAid
232
+ && (task.status === 'pending' || task.status === 'completed');
233
+ },
229
234
  checkOwner: async (aid, expectedOwnerAid) => {
230
235
  const view = await ownerResolver.refresh(aid, { maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS });
231
236
  if (view.consensusStatus === 'consensus')
@@ -257,6 +262,7 @@ export function createAgentInitializationRuntime({ agentRegistry, agentMap, chan
257
262
  const agent = agentRegistry.get(aid);
258
263
  return !!agent && agent.config.enabled !== false && agentMap.has(`${aid}::${agent.baseagent}`) && isConnected(aid);
259
264
  },
265
+ authorize: actor => actor === 'local-control' || ownerResolver.daemonOwners().includes(actor),
260
266
  });
261
267
  }
262
268
  export function recoverIncompleteAgentInitializations(service, agentsDir = resolvePaths().agentsDir) {
@@ -10,6 +10,7 @@ import { DebugDelegationRegistry, DEBUG_TOKEN_PREFIX } from './debug-context.js'
10
10
  import { DelegationDiagnostics, } from './delegation-diagnostics.js';
11
11
  export const AGENT_DELEGATION_TOKEN_ENV = 'EVOLCORE_DELEGATION_TOKEN';
12
12
  export const CODEX_SESSION_TOKEN_ENV = 'EVOLCORE_CODEX_SESSION_TOKEN';
13
+ export const DELEGATED_EXECUTION_SPEC_ENV = 'EVOLCORE_DELEGATED_EXECUTION_SPEC';
13
14
  export const AGENT_DELEGATION_COMMAND_TTL_MS = 5 * 60_000;
14
15
  const INTERNAL_DELEGATION_TTL_MS = 30_000;
15
16
  /**
@@ -169,6 +170,7 @@ export class AgentDelegationRegistry {
169
170
  return false;
170
171
  const sessionToken = input.sessionToken ?? input.carrierToken;
171
172
  if (!sessionToken || !isDelegationCommandHash(input.commandHash)
173
+ || (input.specHash !== undefined && !isDelegationCommandHash(input.specHash))
172
174
  || !input.approvalId || input.approvalId.length > 512 || input.approvalId.includes('\0'))
173
175
  return false;
174
176
  this.deleteExpiredApprovedCommands();
@@ -186,7 +188,7 @@ export class AgentDelegationRegistry {
186
188
  this.approvedCommandBindings.delete(bindingKey);
187
189
  }
188
190
  else {
189
- return existingBinding.commandHash === input.commandHash;
191
+ return existingBinding.commandHash === input.commandHash && existingBinding.specHash === input.specHash;
190
192
  }
191
193
  }
192
194
  const key = approvedCommandKey(sessionTokenHash, input.sessionId, input.commandHash);
@@ -213,6 +215,7 @@ export class AgentDelegationRegistry {
213
215
  approvalId: input.approvalId,
214
216
  activeTokenHash,
215
217
  commandHash: input.commandHash,
218
+ specHash: input.specHash,
216
219
  expiresAt,
217
220
  consumed: false,
218
221
  });
@@ -440,7 +443,7 @@ export async function authorizeDelegatedAunMsgSend(registry, input) {
440
443
  catch {
441
444
  return { ok: false, code: 'INVALID_DELEGATION', reason: 'Delegation relation key is invalid' };
442
445
  }
443
- await refreshOwnershipForAuthorization(grant.selfAid);
446
+ await refreshOwnershipForAuthorization(grant.selfAid, { allowTransient: true });
444
447
  const builtSubject = buildAuthSubject({
445
448
  selfAid: grant.selfAid,
446
449
  actorId: grant.actorId,
@@ -503,10 +506,13 @@ function isValidFullAccessExecutionIdentity(identity) {
503
506
  || identity.processRole !== 'fullaccess-run'
504
507
  || identity.dataScope !== 'daemon')
505
508
  return false;
506
- if (identity.source === 'fullaccess-command' || identity.source === 'agent-policy') {
509
+ if (identity.source === 'fullaccess-command' || identity.source === 'agent-policy' || identity.source === 'session-policy') {
507
510
  return typeof identity.authorizedBy === 'string' && identity.authorizedBy.length > 0
508
- && (identity.source !== 'agent-policy'
509
- || (typeof identity.agentAid === 'string' && identity.agentAid.length > 0));
511
+ && (identity.source === 'fullaccess-command'
512
+ || (typeof identity.agentAid === 'string'
513
+ && identity.agentAid.length > 0
514
+ && (identity.source !== 'session-policy'
515
+ || (typeof identity.sessionId === 'string' && identity.sessionId.length > 0))));
510
516
  }
511
517
  return identity.source === 'trigger'
512
518
  && typeof identity.authorizedBy === 'string' && identity.authorizedBy.length > 0
@@ -541,17 +547,89 @@ function delegationFailureDetailCode(cause) {
541
547
  return 'APPROVED_COMMAND_UNAVAILABLE';
542
548
  }
543
549
  }
544
- export function hashDelegatedCommandArgv(argv) {
550
+ export function hashDelegatedCommandArgv(argv, executionSpec) {
545
551
  if (argv.length === 0 || argv.some(value => typeof value !== 'string' || value.includes('\0')))
546
552
  return undefined;
553
+ if (executionSpec !== undefined && (hashDelegatedCommandSpec(executionSpec) === undefined
554
+ || JSON.stringify(executionSpec.argv) !== JSON.stringify(argv)))
555
+ return undefined;
556
+ return crypto.createHash('sha256')
557
+ .update(executionSpec ? 'evolcore-agent-delegation-command-v2\0' : 'evolcore-agent-delegation-command-v1\0')
558
+ .update(JSON.stringify(executionSpec ? { argv, executionSpec } : argv))
559
+ .digest('hex');
560
+ }
561
+ export function readDelegatedExecutionSpec(env = process.env) {
562
+ const raw = env[DELEGATED_EXECUTION_SPEC_ENV]?.trim();
563
+ if (!raw || raw.length > 16 * 1024)
564
+ return undefined;
565
+ try {
566
+ const spec = parseDelegatedExecutionSpec(raw);
567
+ const currentArgv = currentDelegatedCommandArgv();
568
+ return spec && currentArgv
569
+ && JSON.stringify(spec.argv) === JSON.stringify([MAIN_CLI_BIN, ...currentArgv])
570
+ ? spec
571
+ : undefined;
572
+ }
573
+ catch {
574
+ return undefined;
575
+ }
576
+ }
577
+ export function parseDelegatedExecutionSpec(raw) {
578
+ if (typeof raw !== 'string' || !raw || raw.length > 16 * 1024)
579
+ return undefined;
580
+ let value;
581
+ try {
582
+ value = JSON.parse(raw);
583
+ }
584
+ catch {
585
+ return undefined;
586
+ }
587
+ if (!value || typeof value !== 'object' || Array.isArray(value))
588
+ return undefined;
589
+ const spec = value;
590
+ if (spec.version !== 1 || !['posix', 'powershell', 'cmd'].includes(String(spec.dialect))
591
+ || !['bounded-output', 'cd-prefixed'].includes(String(spec.wrapper))
592
+ || !Array.isArray(spec.argv) || spec.argv.some(arg => typeof arg !== 'string' || arg.includes('\0'))
593
+ || spec.argv[0] !== MAIN_CLI_BIN)
594
+ return undefined;
595
+ if (spec.cwd !== undefined && (typeof spec.cwd !== 'string' || spec.cwd.includes('\0')))
596
+ return undefined;
597
+ if (spec.outputPath !== undefined && (typeof spec.outputPath !== 'string' || spec.outputPath.includes('\0')))
598
+ return undefined;
599
+ if (spec.mergeStderr !== undefined && typeof spec.mergeStderr !== 'boolean')
600
+ return undefined;
601
+ if (spec.suffixArgv !== undefined && (!Array.isArray(spec.suffixArgv)
602
+ || spec.suffixArgv.some(arg => typeof arg !== 'string' || arg.includes('\0'))))
603
+ return undefined;
604
+ if (spec.filterChain !== undefined && (!Array.isArray(spec.filterChain)
605
+ || spec.filterChain.some(stage => !Array.isArray(stage)
606
+ || stage.some(arg => typeof arg !== 'string' || arg.includes('\0')))))
607
+ return undefined;
608
+ return spec;
609
+ }
610
+ /** Bind an approval to the complete shell-independent execution shape. */
611
+ export function hashDelegatedCommandSpec(spec) {
612
+ const values = [
613
+ ...spec.argv,
614
+ spec.dialect,
615
+ spec.wrapper,
616
+ spec.cwd,
617
+ spec.outputPath,
618
+ ...(spec.filterChain ?? []).flat(),
619
+ ...(spec.suffixArgv ?? []),
620
+ ];
621
+ if (spec.version !== 1 || values.some(value => value !== undefined && (typeof value !== 'string' || value.includes('\0')))) {
622
+ return undefined;
623
+ }
547
624
  return crypto.createHash('sha256')
548
- .update('evolcore-agent-delegation-command-v1\0')
549
- .update(JSON.stringify(argv))
625
+ .update('evolcore-agent-delegation-spec-v1\0')
626
+ .update(JSON.stringify(spec))
550
627
  .digest('hex');
551
628
  }
552
629
  export function hashCurrentDelegatedCommand(processArgv = process.argv) {
553
630
  const argv = currentDelegatedCommandArgv(processArgv);
554
- return argv ? hashDelegatedCommandArgv([MAIN_CLI_BIN, ...argv]) : undefined;
631
+ const spec = readDelegatedExecutionSpec();
632
+ return argv ? hashDelegatedCommandArgv([MAIN_CLI_BIN, ...argv], spec) : undefined;
555
633
  }
556
634
  /**
557
635
  * Return the command arguments used by a delegated CLI invocation.
@@ -107,7 +107,8 @@ export async function authorizeFreshOperation(params) {
107
107
  const configCommand = params.resolvedConfigCommand;
108
108
  const changesOwner = configCommand?.kind === 'field' && configCommand.subcommand !== 'get'
109
109
  && ['owner', 'owners'].includes(configCommand.field.split('.')[0]);
110
- const force = changesOwner || params.intent.operation === 'ec.aid.bind' || params.intent.operation === 'config.restore';
110
+ const force = changesOwner || ['ec.aid.bind', 'ec.aid.bind.status', 'ec.aid.unbind', 'ec.aid.transfer']
111
+ .includes(params.intent.operation) || params.intent.operation === 'config.restore';
111
112
  const operation = getOperationMeta(params.intent.operation);
112
113
  const sensitive = force || params.intent.dangerous || operation?.dangerous || operation?.category !== 'read'
113
114
  || configCommand?.dangerous || subject.processRole === 'fullaccess-run';
@@ -116,6 +117,7 @@ export async function authorizeFreshOperation(params) {
116
117
  ...(sensitive ? {} : { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS }),
117
118
  includeDaemon: subject.isDaemonOwner || subject.processRole === 'fullaccess-run'
118
119
  || params.intent.scope === 'process' || params.intent.scope === 'control' || force,
120
+ allowTransient: !force,
119
121
  });
120
122
  const current = buildAuthSubject({
121
123
  selfAid: subject.selfAid, agentName: subject.agentName, actorId: subject.actorId,
@@ -25,11 +25,15 @@ export function auditCommandAuthorization(event) {
25
25
  }
26
26
  export function auditFullAccessEvent(input) {
27
27
  const configurationEvent = input.event === 'fullaccess.trigger.configured'
28
- || input.event === 'fullaccess.trigger.deescalated';
28
+ || input.event === 'fullaccess.trigger.deescalated'
29
+ || input.event === 'fullaccess.session-policy.configured'
30
+ || input.event === 'fullaccess.session-policy.deescalated';
29
31
  const executionEvent = input.event === 'fullaccess.execution.started'
30
32
  || input.event === 'fullaccess.execution.ended'
31
33
  || input.event === 'fullaccess.agent-policy.execution.started'
32
34
  || input.event === 'fullaccess.agent-policy.execution.ended'
35
+ || input.event === 'fullaccess.session-policy.execution.started'
36
+ || input.event === 'fullaccess.session-policy.execution.ended'
33
37
  || input.event === 'fullaccess.trigger.execution.started'
34
38
  || input.event === 'fullaccess.trigger.execution.ended';
35
39
  // The scheduler triggers a run, but the executing subject is the task-bound
@@ -363,8 +367,9 @@ function buildAuditRecord(event) {
363
367
  : undefined;
364
368
  const errorCode = classification?.errorCode;
365
369
  const ecwebRequestId = event.source === 'ecweb' ? event.ecwebRequestId : undefined;
366
- const requestId = event.requestId ?? ecwebRequestId;
367
- const correlationId = event.correlationId ?? event.callId ?? requestId;
370
+ const sourceRequestId = event.requestId ?? ecwebRequestId;
371
+ const requestId = namespaceAuditRequestId(event.source, event.sessionId, sourceRequestId);
372
+ const correlationId = event.correlationId ?? event.callId ?? sourceRequestId;
368
373
  return {
369
374
  type: 'authorization:audit',
370
375
  ts: event.ts,
@@ -376,13 +381,14 @@ function buildAuditRecord(event) {
376
381
  sessionId: event.sessionId,
377
382
  callId: event.callId,
378
383
  correlationId,
379
- requestId,
384
+ requestId: sourceRequestId,
380
385
  operation: event.operation,
381
386
  })),
382
387
  eventPhase: event.eventPhase,
383
388
  callId: event.callId,
384
389
  correlationId,
385
390
  requestId,
391
+ sourceRequestId,
386
392
  sessionId: event.sessionId,
387
393
  ...(event.source === 'ecweb' && !event.sessionId ? { sessionScope: 'not_applicable' } : {}),
388
394
  agentAid: redactIdentifier(event.agentAid ?? event.selfAid),
@@ -434,6 +440,15 @@ function buildAuditRecord(event) {
434
440
  exitCode: event.exitCode,
435
441
  };
436
442
  }
443
+ function namespaceAuditRequestId(source, sessionId, sourceRequestId) {
444
+ if (sourceRequestId === undefined)
445
+ return undefined;
446
+ const namespace = source === 'ecweb' && !sessionId ? [source] : [source, sessionId ?? 'unknown'];
447
+ // JSON escaping also preserves unpaired UTF-16 surrogates from source IDs;
448
+ // encodeURIComponent alone would throw and interrupt authorization auditing.
449
+ const parts = [...namespace, sourceRequestId].map(part => encodeURIComponent(JSON.stringify(part).slice(1, -1)));
450
+ return `audit:v1:${parts.join(':')}`;
451
+ }
437
452
  function resolveAgentName(event) {
438
453
  const displayName = typeof event.agentName === 'string' ? event.agentName.trim() : '';
439
454
  if (displayName && !isUnknownAgentLabel(displayName))
@@ -489,6 +504,7 @@ function logAuditEvent(record) {
489
504
  record.taskId ? `task=${record.taskId}` : null,
490
505
  record.messageId ? `message=${record.messageId}` : null,
491
506
  record.requestId ? `request=${record.requestId}` : null,
507
+ record.sourceRequestId ? `sourceRequest=${JSON.stringify(record.sourceRequestId)}` : null,
492
508
  record.callId ? `call=${record.callId}` : null,
493
509
  record.correlationId ? `correlation=${record.correlationId}` : null,
494
510
  record.eventKey ? `eventKey=${record.eventKey}` : null,
@@ -597,6 +613,11 @@ function summarizeAuthorizationArgs(operation, args) {
597
613
  ? Math.max(0, Math.floor(diagnostic.inputLength)) : undefined;
598
614
  if (issue && offset !== undefined && tokenIndex !== undefined && dialect && inputLength !== undefined) {
599
615
  summary.parseFailure = { issue, offset, tokenIndex, dialect, inputLength };
616
+ for (const field of ['canonicalizationStage', 'wrapper', 'redirectDetected', 'managedTempPath', 'managedTempResolved']) {
617
+ if (typeof diagnostic[field] === 'string' || typeof diagnostic[field] === 'boolean') {
618
+ summary.parseFailure[field] = diagnostic[field];
619
+ }
620
+ }
600
621
  }
601
622
  continue;
602
623
  }
@@ -127,7 +127,11 @@ export function buildDebugTaskContext(input) {
127
127
  chatType,
128
128
  selfAid: session.selfAID,
129
129
  peerId,
130
- peerKey: channel && peerKeyId ? formatPeerKey(channel, peerKeyId) : undefined,
130
+ // 系统会话的目标关系在 metadata.peerKey(与 response-engine 的任务上下文同源),
131
+ // 不能从后台伪对端 peerId 推。
132
+ peerKey: meta.systemSession && typeof meta.peerKey === 'string' && meta.peerKey
133
+ ? meta.peerKey
134
+ : (channel && peerKeyId ? formatPeerKey(channel, peerKeyId) : undefined),
131
135
  peerName: meta.peerName,
132
136
  peerType: meta.peerType,
133
137
  threadId,
@@ -323,6 +323,22 @@ const OPERATIONS = [
323
323
  description: '更新当前主会话或话题的 idle 触发设置',
324
324
  sources: ['slash', 'menu', 'ecweb', 'control'],
325
325
  },
326
+ {
327
+ id: 'session.fullaccess.current',
328
+ category: 'read',
329
+ dangerous: true,
330
+ defaultScopes: ['relation'],
331
+ description: '查看当前 EC 会话的 fullaccess 状态',
332
+ sources: ['slash', 'menu'],
333
+ },
334
+ {
335
+ id: 'session.fullaccess.update',
336
+ category: 'dangerous',
337
+ dangerous: true,
338
+ defaultScopes: ['relation'],
339
+ description: '更新当前 EC 会话的 fullaccess 状态',
340
+ sources: ['slash', 'menu'],
341
+ },
326
342
  {
327
343
  id: 'session.topic.current',
328
344
  category: 'read',
@@ -1030,6 +1046,14 @@ const OPERATIONS = [
1030
1046
  description: '删除云存储对象',
1031
1047
  sources: ['menu.cli', 'agent-tool', 'control'],
1032
1048
  },
1049
+ {
1050
+ id: 'storage.get_by_share',
1051
+ category: 'write-agent',
1052
+ dangerous: true,
1053
+ defaultScopes: ['agent', 'control'],
1054
+ description: '通过分享短码从云存储下载文件',
1055
+ sources: ['menu.cli', 'agent-tool', 'control'],
1056
+ },
1033
1057
  // ── Gateway & Config Operations ──
1034
1058
  {
1035
1059
  id: 'gateway.read',
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import { ownerResolver } from '../ownership/owner-resolver.js';
3
3
  import { agentFullAccessStatus, agentFullAccessWriteError } from '../role/runtime-policy.js';
4
- import { initializationSummary } from '../../cli/agent-create.js';
4
+ import { initializationSummary, validateInitializationModelArgs } from '../../cli/agent-create.js';
5
5
  import { agentDelete, agentEnable, agentDisable, agentList, agentShow, agentSet, agentReload, } from '../../cli/agent.js';
6
6
  import { agentCreateNonInteractive } from '../../cli/agent-create.js';
7
7
  import { logger } from '../../utils/logger.js';
@@ -546,18 +546,78 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
546
546
  if (action === 'initialize') {
547
547
  if (!service?.initialization)
548
548
  return { error: '初始化服务不可用', code: 'NOT_CONFIGURED' };
549
- const plan = a.plan && typeof a.plan === 'object' ? a.plan : {
550
- aid: a.aid,
551
- project: typeof a.project === 'string' ? a.project : '',
552
- baseagent: a.baseagent,
553
- owners: Array.isArray(a.owners) ? a.owners : (a.owner ? [a.owner] : []),
554
- name: a.name,
555
- description: a.description,
556
- type: a.type || 'agent',
557
- tags: a.tags,
558
- ...(typeof a.persona === 'string' ? { persona: a.persona } : {}),
549
+ if (!peerId)
550
+ return { error: '缺少发起者 AID', code: 'INVALID_ARGS' };
551
+ if (a.resume !== undefined && typeof a.resume !== 'boolean') {
552
+ return { error: 'resume 必须是布尔值', code: 'INVALID_ARGS' };
553
+ }
554
+ if (a.resume === true) {
555
+ const aid = typeof a.aid === 'string' ? a.aid.trim() : '';
556
+ if (!aid || !isValidAid(aid))
557
+ return { error: 'resume 需要有效的 aid', code: 'INVALID_ARGS' };
558
+ if (Object.keys(a).some(key => !['aid', 'resume', 'context'].includes(key))) {
559
+ return { error: '恢复请求不能携带新的初始化计划', code: 'INVALID_ARGS' };
560
+ }
561
+ try {
562
+ return { data: service.initialization.resume(aid, peerId) };
563
+ }
564
+ catch (error) {
565
+ return { error: error instanceof Error ? error.message : String(error), code: error.code || 'INITIALIZE_FAILED' };
566
+ }
567
+ }
568
+ if (a.plan !== undefined && (!a.plan || typeof a.plan !== 'object' || Array.isArray(a.plan))) {
569
+ return { error: 'plan 必须是对象', code: 'INVALID_ARGS' };
570
+ }
571
+ const supplied = a.plan && typeof a.plan === 'object' && !Array.isArray(a.plan) ? a.plan : {};
572
+ if (a.project !== undefined && supplied.project !== undefined
573
+ && typeof a.project === 'string' && typeof supplied.project === 'string'
574
+ && a.project.trim() && supplied.project.trim()
575
+ && a.project.trim() !== supplied.project.trim()) {
576
+ return { error: 'project 与 plan.project 必须一致', code: 'INVALID_ARGS' };
577
+ }
578
+ const aid = supplied.aid ?? a.aid;
579
+ if (typeof aid !== 'string' || !isValidAid(aid))
580
+ return { error: '无效 Agent AID', code: 'INVALID_ARGS' };
581
+ if (a.aid !== undefined && a.aid !== aid) {
582
+ return { error: 'aid 与 plan.aid 必须一致', code: 'INVALID_ARGS' };
583
+ }
584
+ for (const owners of [supplied.owners, a.owners]) {
585
+ if (owners !== undefined && (!Array.isArray(owners) || owners.length !== 1)) {
586
+ return { error: '初始化必须指定一位 Owner', code: 'INVALID_ARGS' };
587
+ }
588
+ }
589
+ const ownerAid = supplied.ownerAid ?? supplied.owner
590
+ ?? a.ownerAid ?? a.owner
591
+ ?? (Array.isArray(supplied.owners) ? supplied.owners[0] : undefined)
592
+ ?? (Array.isArray(a.owners) ? a.owners[0] : undefined);
593
+ const rawModel = supplied.model ?? a.model;
594
+ const rawEffort = supplied.effort ?? a.effort;
595
+ for (const [field, value] of [['model', rawModel], ['effort', rawEffort]]) {
596
+ if (value !== undefined && typeof value !== 'string') {
597
+ return { error: `${field} 必须是字符串`, code: 'INVALID_ARGS' };
598
+ }
599
+ }
600
+ const effort = typeof rawEffort === 'string' && rawEffort.trim() && rawEffort.trim() !== 'auto'
601
+ ? rawEffort.trim() : undefined;
602
+ const plan = {
603
+ aid,
604
+ project: supplied.project ?? a.project ?? '',
605
+ baseagent: supplied.baseagent ?? a.baseagent,
606
+ ...(typeof rawModel === 'string' && rawModel.trim() ? { model: rawModel.trim() } : {}),
607
+ ...(effort ? { effort } : {}),
608
+ ownerAid,
609
+ name: supplied.name ?? a.name,
610
+ description: supplied.description ?? a.description,
611
+ type: supplied.type ?? a.type ?? 'agent',
612
+ tags: supplied.tags ?? a.tags,
613
+ ...(typeof (supplied.persona ?? a.persona) === 'string' ? { persona: supplied.persona ?? a.persona } : {}),
614
+ ...(typeof (supplied.avatarFile ?? a.avatarFile) === 'string' ? { avatarFile: supplied.avatarFile ?? a.avatarFile } : {}),
615
+ ...(typeof (supplied.avatarUrl ?? a.avatarUrl) === 'string' ? { avatarUrl: supplied.avatarUrl ?? a.avatarUrl } : {}),
559
616
  };
560
617
  try {
618
+ const modelError = await validateInitializationModelArgs(plan);
619
+ if (modelError)
620
+ return modelError;
561
621
  return { data: service.initialization.start(plan, peerId, a.dryRun === true) };
562
622
  }
563
623
  catch (error) {
@@ -865,13 +925,31 @@ export async function execAgentQuery(args, service, subject) {
865
925
  const agentDir = path.join(resolvePaths().agentsDir, aid);
866
926
  const progress = readCreateStatus(agentDir);
867
927
  const initialization = initializationSummary(aid);
928
+ let usable;
929
+ if (initialization && service?.initialization) {
930
+ try {
931
+ const state = service.initialization.status(aid);
932
+ if (typeof state.usable === 'boolean')
933
+ usable = state.usable;
934
+ }
935
+ catch {
936
+ usable = false;
937
+ }
938
+ }
868
939
  const res = service
869
940
  ? await service.show(aid)
870
941
  : await agentShow(aid);
871
942
  if (!('ok' in res) || res.ok !== true) {
872
943
  const code = classifyError(res.error);
873
944
  if (code === 'NOT_FOUND' && initialization)
874
- return { data: { aid, lifecycle: service?.readConfig(aid)?.lifecycle ?? null, initialization } };
945
+ return {
946
+ data: {
947
+ aid,
948
+ lifecycle: service?.readConfig(aid)?.lifecycle ?? null,
949
+ initialization,
950
+ ...(usable === undefined ? {} : { usable }),
951
+ },
952
+ };
875
953
  if (code === 'NOT_FOUND' && progress)
876
954
  return { data: buildCreateProgressOnlyAgent(aid, progress) };
877
955
  return { error: res.error, code };
@@ -884,6 +962,7 @@ export async function execAgentQuery(args, service, subject) {
884
962
  const data = {
885
963
  ...res,
886
964
  ...(initialization ? { initialization } : {}),
965
+ ...(usable === undefined ? {} : { usable }),
887
966
  config: {
888
967
  ...(res.config ?? {}),
889
968
  active_baseagent: safeAgentConfig.active_baseagent ?? res.config?.baseagent ?? null,
@@ -804,7 +804,7 @@ export class CommandHandler {
804
804
  reliability: {
805
805
  concurrency: 'forbid',
806
806
  missedPolicy: 'run_once',
807
- retry: { maxAttempts: 0, backoffMs: 30_000 },
807
+ retry: { maxAttempts: 1, backoffMs: 30_000 },
808
808
  },
809
809
  limits: this.limitsFromParsed(parsed),
810
810
  };
@@ -1380,6 +1380,7 @@ export class CommandHandler {
1380
1380
  ? {
1381
1381
  kind: 'system.error',
1382
1382
  text: result.text,
1383
+ ...(result.raw !== undefined ? { raw: result.raw } : {}),
1383
1384
  subtype: `session.${content.trim().toLowerCase().startsWith('/new') ? 'new' : 'renew'}.error`,
1384
1385
  recoverable: true,
1385
1386
  }
@@ -1394,7 +1395,12 @@ export class CommandHandler {
1394
1395
  catch (error) {
1395
1396
  if (error instanceof BaseagentRunnerUnavailableError) {
1396
1397
  logger.error(`[CommandHandler] baseagent mismatch blocked: channel=${channel} requested=${error.baseagent} owner=${error.evolagentName} available=${error.availableBaseagents.join(',') || '<none>'}`);
1397
- return { kind: 'command.error', text: this.formatBaseagentUnavailable(error), reason: error.code };
1398
+ return {
1399
+ kind: 'command.error',
1400
+ text: this.formatBaseagentUnavailable(error),
1401
+ raw: error.message,
1402
+ reason: error.code,
1403
+ };
1398
1404
  }
1399
1405
  throw error;
1400
1406
  }
@@ -2736,21 +2742,49 @@ export class CommandHandler {
2736
2742
  if (sessionSelfAid && sessionSelfAid !== actorAid) {
2737
2743
  return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation self agent does not match the active session' };
2738
2744
  }
2739
- const isSelfPersonalTarget = parsed.command.targetAid === actorAid;
2740
- let currentPrivatePeer;
2741
- let currentGroup;
2742
- if (grant.channelType === 'aun' && grant.chatType === 'private') {
2745
+ let relationId;
2746
+ try {
2747
+ const relation = parsePeerKey(grant.peerKey);
2748
+ if (relation.channelType !== grant.channelType)
2749
+ throw new Error('relation channel mismatch');
2750
+ relationId = relation.channelId;
2751
+ }
2752
+ catch {
2753
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation contains an invalid relation key' };
2754
+ }
2755
+ const isSelfTarget = parsed.command.targetAid === actorAid;
2756
+ const isCurrentPrivatePeerCat = grant.channelType === 'aun'
2757
+ && grant.chatType === 'private'
2758
+ && parsed.command.kind === 'cat'
2759
+ && parsed.command.targetAid === relationId;
2760
+ let storageBackend;
2761
+ if (isSelfTarget) {
2762
+ storageBackend = 'personal';
2763
+ }
2764
+ else {
2765
+ let targetType;
2743
2766
  try {
2744
- currentPrivatePeer = parsePeerKey(grant.peerKey).channelId;
2767
+ const card = await agentmdGet(parsed.command.targetAid, { withVerification: true, remoteOnly: true });
2768
+ if (card.verification.status !== 'verified') {
2769
+ return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md verification did not succeed' };
2770
+ }
2771
+ const frontmatter = card.content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
2772
+ const document = frontmatter ? parseDocument(frontmatter) : undefined;
2773
+ const rawTargetType = document && document.errors.length === 0
2774
+ ? document.toJS()?.type
2775
+ : undefined;
2776
+ targetType = typeof rawTargetType === 'string' ? rawTargetType.trim().toLowerCase() : undefined;
2777
+ if (!targetType) {
2778
+ return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md has no valid type' };
2779
+ }
2745
2780
  }
2746
2781
  catch {
2747
- return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation contains an invalid relation key' };
2782
+ return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md could not be verified' };
2748
2783
  }
2784
+ storageBackend = targetType === 'group' ? 'group' : 'personal';
2749
2785
  }
2750
- const isCurrentPrivatePeerCat = parsed.command.kind === 'cat'
2751
- && currentPrivatePeer !== undefined
2752
- && parsed.command.targetAid === currentPrivatePeer;
2753
- if (isSelfPersonalTarget) {
2786
+ let currentGroup;
2787
+ if (storageBackend === 'personal' && isSelfTarget) {
2754
2788
  if (grant.issuedRole !== 'owner' && !hasTrustedFullAccessDelegation(grant)) {
2755
2789
  return { ok: false, code: 'NO_PERMISSION', error: 'Managed personal storage requires the current Agent owner relation' };
2756
2790
  }
@@ -2758,56 +2792,39 @@ export class CommandHandler {
2758
2792
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Only the current Agent can access its personal storage' };
2759
2793
  }
2760
2794
  }
2761
- else if (isCurrentPrivatePeerCat) {
2795
+ else if (storageBackend === 'personal' && isCurrentPrivatePeerCat) {
2762
2796
  if (parsed.command.actorAid && parsed.command.actorAid !== actorAid) {
2763
2797
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Managed fs cannot switch the execution identity with --as' };
2764
2798
  }
2765
2799
  }
2766
- else {
2767
- const trustedFullAccess = hasTrustedFullAccessDelegation(grant);
2768
- if (trustedFullAccess) {
2769
- let targetType;
2770
- try {
2771
- const card = await agentmdGet(parsed.command.targetAid, { withVerification: true, remoteOnly: true });
2772
- if (card.verification.status !== 'verified') {
2773
- return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md verification did not succeed' };
2774
- }
2775
- const frontmatter = card.content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
2776
- const document = frontmatter ? parseDocument(frontmatter) : undefined;
2777
- targetType = document && document.errors.length === 0
2778
- ? String(document.toJS()?.type ?? '').trim().toLowerCase()
2779
- : undefined;
2780
- }
2781
- catch {
2782
- return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md could not be verified' };
2783
- }
2784
- if (targetType !== 'group') {
2785
- return { ok: false, code: 'INVALID_TARGET', error: 'Managed group storage requires a verified group AID' };
2786
- }
2787
- }
2800
+ else if (storageBackend === 'group') {
2788
2801
  if (!hasTrustedFullAccessDelegation(grant) && (grant.channelType !== 'aun' || grant.chatType !== 'group')) {
2789
- return { ok: false, code: 'SCOPE_MISMATCH', error: 'Managed group fs operations require the current AUN group relation' };
2790
- }
2791
- try {
2792
- currentGroup = parsePeerKey(grant.peerKey).channelId;
2793
- }
2794
- catch {
2795
- return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation contains an invalid relation key' };
2802
+ return { ok: false, code: 'SCOPE_MISMATCH', error: 'Group storage requires the current AUN group relation' };
2796
2803
  }
2804
+ if (grant.channelType === 'aun' && grant.chatType === 'group')
2805
+ currentGroup = relationId;
2797
2806
  if (parsed.command.actorAid && parsed.command.actorAid !== actorAid) {
2798
2807
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Managed fs cannot switch the execution identity with --as' };
2799
2808
  }
2800
2809
  if (!hasTrustedFullAccessDelegation(grant)
2801
- && !sameGroupAid(parsed.command.targetAid, currentGroup)) {
2810
+ && (!currentGroup || !sameGroupAid(parsed.command.targetAid, currentGroup))) {
2802
2811
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Only the current AUN group can be targeted' };
2803
2812
  }
2804
2813
  }
2814
+ else {
2815
+ return {
2816
+ ok: false,
2817
+ code: 'SCOPE_MISMATCH',
2818
+ error: 'Managed personal storage is limited to the current Agent and cat of the current AUN private peer',
2819
+ };
2820
+ }
2805
2821
  const resolvedCommand = parsed.command;
2806
- resolvedCommand.storageBackend = isSelfPersonalTarget || isCurrentPrivatePeerCat ? 'personal' : 'group';
2807
- resolvedCommand.actorAid = hasTrustedFullAccessDelegation(grant) && !isSelfPersonalTarget && !isCurrentPrivatePeerCat
2822
+ resolvedCommand.storageBackend = storageBackend;
2823
+ resolvedCommand.actorAid = hasTrustedFullAccessDelegation(grant) && !isSelfTarget && !isCurrentPrivatePeerCat
2808
2824
  ? (resolvedCommand.actorAid ?? actorAid)
2809
2825
  : actorAid;
2810
- const relationTarget = currentPrivatePeer ?? currentGroup;
2826
+ const relationTarget = currentGroup
2827
+ ?? (grant.channelType === 'aun' && grant.chatType === 'private' ? relationId : undefined);
2811
2828
  const subject = buildAuthSubject({
2812
2829
  selfAid: grant.selfAid,
2813
2830
  actorId: grant.actorId,
@@ -2840,7 +2857,7 @@ export class CommandHandler {
2840
2857
  subject,
2841
2858
  intent: {
2842
2859
  operation: parsed.command.operationId,
2843
- scope: isSelfPersonalTarget ? 'agent' : 'relation',
2860
+ scope: isSelfTarget ? 'agent' : 'relation',
2844
2861
  source: 'agent-tool',
2845
2862
  args: intentArgs,
2846
2863
  },