evolcore 0.0.40 → 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 (100) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/claude-runner.js +21 -106
  5. package/dist/agents/codex-runner.js +451 -231
  6. package/dist/agents/ecagent-runner.js +30 -11
  7. package/dist/agents/gemini-runner.js +26 -6
  8. package/dist/agents/runner-types.js +11 -3
  9. package/dist/aun/ability-device-routing.js +26 -0
  10. package/dist/aun/aid/client.js +1 -1
  11. package/dist/aun/group/identity.js +8 -0
  12. package/dist/aun/msg/managed-operation.js +4 -4
  13. package/dist/aun/msg/p2p.js +27 -7
  14. package/dist/aun/storage/download.js +30 -0
  15. package/dist/aun/storage/index.js +14 -6
  16. package/dist/channels/aun.js +33 -4
  17. package/dist/channels/daemon.js +24 -4
  18. package/dist/cli/agent-command.js +2 -0
  19. package/dist/cli/agent-create.js +98 -19
  20. package/dist/cli/agent.js +10 -3
  21. package/dist/cli/aun-commands.js +82 -22
  22. package/dist/cli/daemon-commands.js +19 -10
  23. package/dist/cli/index.js +1 -1
  24. package/dist/cli/restart-monitor.js +17 -0
  25. package/dist/cli/session-command.js +128 -13
  26. package/dist/cli/stats.js +60 -4
  27. package/dist/cli/trigger-command.js +2 -2
  28. package/dist/config/access-policy.js +2 -0
  29. package/dist/config/config-operation-service.js +17 -6
  30. package/dist/config/gateway-config.js +1 -1
  31. package/dist/config/peer-role-resolver.js +10 -8
  32. package/dist/core/agent-application-service.js +11 -1
  33. package/dist/core/agent-ipc-registration.js +4 -0
  34. package/dist/core/auth/agent-delegation.js +80 -5
  35. package/dist/core/auth/authorization-audit.js +20 -3
  36. package/dist/core/auth/operation-catalog.js +8 -0
  37. package/dist/core/command/agent-control.js +91 -12
  38. package/dist/core/command/command-handler.js +57 -46
  39. package/dist/core/command/connect-menu.js +23 -2
  40. package/dist/core/command/menu-catalog.js +1 -0
  41. package/dist/core/command/menu-handler.js +38 -101
  42. package/dist/core/command/menu-protocol.js +9 -2
  43. package/dist/core/command/role-menu.js +7 -6
  44. package/dist/core/command/slash-gate.js +13 -10
  45. package/dist/core/command/slash-handler.js +34 -98
  46. package/dist/core/event-catalog.js +15 -0
  47. package/dist/core/ipc-registration.js +18 -1
  48. package/dist/core/memory/consolidation-trigger.js +1 -1
  49. package/dist/core/message/aun-ipc-sender.js +26 -5
  50. package/dist/core/message/aun-request-registry.js +97 -3
  51. package/dist/core/message/im-renderer.js +4 -0
  52. package/dist/core/message/message-admission.js +8 -4
  53. package/dist/core/message/message-bridge.js +40 -6
  54. package/dist/core/message/message-log.js +55 -0
  55. package/dist/core/message/message-queue.js +5 -5
  56. package/dist/core/message/response-engine.js +310 -136
  57. package/dist/core/model/model-catalog.js +7 -6
  58. package/dist/core/ownership/owner-resolver.js +2 -2
  59. package/dist/core/permission/ec-command-parser.js +110 -5
  60. package/dist/core/permission/tool-policy.js +28 -7
  61. package/dist/core/session/session-capsule.js +197 -0
  62. package/dist/core/session/session-manager.js +148 -14
  63. package/dist/core/session/session-mapper.js +2 -0
  64. package/dist/index.js +3 -3
  65. package/dist/ipc.js +22 -8
  66. package/dist/stats/budget.js +1 -1
  67. package/dist/stats/db.js +15 -0
  68. package/dist/stats/index.js +2 -2
  69. package/dist/stats/price-resolver.js +304 -5
  70. package/dist/stats/query.js +82 -3
  71. package/dist/stats/writer.js +38 -5
  72. package/dist/trigger/feedback.js +18 -7
  73. package/dist/trigger/manager.js +20 -3
  74. package/dist/trigger/parser.js +6 -3
  75. package/dist/trigger/patch.js +1 -1
  76. package/dist/trigger/system-definitions.js +43 -7
  77. package/dist/trigger/validation.js +13 -5
  78. package/dist/utils/error-utils.js +14 -0
  79. package/dist/utils/npm-ops.js +2 -1
  80. package/dist/utils/package-version-info.js +1 -1
  81. package/dist/utils/upgrade-jobs.js +45 -5
  82. package/kits/docs/INDEX.md +1 -1
  83. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  84. package/kits/docs/evolcore/INDEX.md +2 -1
  85. package/kits/docs/evolcore/agent-create.md +3 -2
  86. package/kits/docs/evolcore/agent.md +1 -1
  87. package/kits/docs/evolcore/config.md +1 -1
  88. package/kits/docs/evolcore/event.md +1 -0
  89. package/kits/docs/evolcore/fs.md +5 -0
  90. package/kits/docs/evolcore/menu-protocol.md +32 -0
  91. package/kits/docs/evolcore/msg.md +17 -1
  92. package/kits/docs/evolcore/session.md +14 -0
  93. package/kits/schemas/agent-config.schema.13.json +15 -0
  94. package/kits/skills/aid-ability/SKILL.md +35 -6
  95. package/kits/templates/session-capsule/recovery.md +5 -0
  96. package/kits/templates/session-capsule/renew.md +5 -0
  97. package/kits/templates/system-fragments/bootstrap.md +6 -6
  98. package/kits/templates/system-fragments/channel.md +1 -1
  99. package/package.json +3 -3
  100. package/dist/stats/billing.js +0 -215
@@ -1,15 +1,20 @@
1
1
  import path from 'path';
2
2
  import fs from 'fs';
3
3
  import { resolvePaths, resolveRoot } from '../paths.js';
4
+ import { authorizeLocalCommand } from './task-context.js';
5
+ import { findSessionCapsule, materializeSessionCapsules } from '../core/session/session-capsule.js';
4
6
  import { scanChatDirs, readLastJsonlLine, } from '../core/session/session-fs-store.js';
5
7
  const HELP_TEXT = `
6
8
  ec session <command> [options]
7
9
 
8
- 本地会话文件查询(不经过 daemon,直接读 $EVOLCORE_HOME/agents/ 下的 session 存档)。
10
+ 本地会话文件查询(读取 $EVOLCORE_HOME/agents/ 下的存档;托管任务先经 daemon 鉴权)。
9
11
 
10
12
  命令:
11
13
  find <sessionId> 按 ec 会话 id(meta_YYYYMMDD_<ts>)定位 session 文件,
12
14
  输出 agentSessionId 与所在位置等元数据
15
+ source <sessionId> 查询直接来源 EC 会话(根会话无来源)
16
+ capsule list <sessionId> 列出该 EC 会话使用的恢复/renew 胶囊
17
+ capsule show <capsuleId> 查看胶囊正文和底层会话轮换关系
13
18
  help 显示本帮助
14
19
 
15
20
  选项:
@@ -58,7 +63,52 @@ function findMetaInTrash(chatDir, metaFileName) {
58
63
  catch { /* 目录不存在,跳过 */ }
59
64
  return hits;
60
65
  }
61
- async function cmdFind(args) {
66
+ async function authorizedChatDirs(args) {
67
+ let scope;
68
+ if (process.env.EVOLCORE_SESSION_ID) {
69
+ scope = await authorizeLocalCommand(['session', ...args]);
70
+ if (!scope.selfAid || !scope.peerRole || scope.peerRole === 'none')
71
+ throw new Error('当前任务身份不可用');
72
+ }
73
+ return scanChatDirs(resolvePaths().sessionsDir).filter(chat => {
74
+ if (!scope)
75
+ return true;
76
+ if (chat.selfAID !== scope.selfAid)
77
+ return false;
78
+ if (scope.peerRole === 'owner' || scope.peerRole === 'admin')
79
+ return true;
80
+ return !!scope.channel && !!scope.channelId
81
+ && chat.channelType === scope.channel && chat.channelId === scope.channelId;
82
+ });
83
+ }
84
+ function findRecords(chats, sessionId) {
85
+ if (!/^meta_[A-Za-z0-9_-]+$/u.test(sessionId))
86
+ throw new Error('无效的 EC 会话 ID');
87
+ return chats.flatMap(chat => {
88
+ const locations = [...findMetaInChatDir(chat.dirPath, `${sessionId}.jsonl`), ...findMetaInTrash(chat.dirPath, `${sessionId}.jsonl`)];
89
+ const records = locations.flatMap(file => {
90
+ const meta = readLastJsonlLine(file);
91
+ return meta?.id === sessionId ? [{ chat, file, meta }] : [];
92
+ });
93
+ if (records.length)
94
+ return records;
95
+ const file = path.join(chat.dirPath, 'active.json');
96
+ const meta = readJsonFileSafe(file);
97
+ return meta?.id === sessionId ? [{ chat, file, meta }] : [];
98
+ });
99
+ }
100
+ function printCapsule(capsule) {
101
+ console.log(`胶囊: ${capsule.capsuleId}`);
102
+ console.log(` EC 会话: ${capsule.sessionId}`);
103
+ if (capsule.sourceSessionId)
104
+ console.log(` 来源 EC 会话: ${capsule.sourceSessionId}`);
105
+ console.log(` cause: ${capsule.cause}`);
106
+ console.log(` sourceAgentSessionId: ${capsule.sourceAgentSessionId ?? '(无)'}`);
107
+ console.log(` agentSessionId: ${capsule.agentSessionId ?? '(尚未绑定)'}`);
108
+ console.log(` 创建: ${new Date(capsule.createdAt).toISOString()}`);
109
+ console.log(` 消费: ${capsule.consumedAt === undefined ? '(待接收)' : new Date(capsule.consumedAt).toISOString()}`);
110
+ }
111
+ async function cmdFind(args, chatDirs) {
62
112
  const jsonFormat = hasFlag(args, '--format') && argValue(args, '--format') === 'json'
63
113
  || hasFlag(args, '--json');
64
114
  // 位置参数已在调用处剥掉子命令,第一个非 flag 参数即 sessionId
@@ -70,14 +120,12 @@ async function cmdFind(args) {
70
120
  }
71
121
  // 允许传入带或不带 .jsonl 后缀的 id
72
122
  const sessionId = rawId.endsWith('.jsonl') ? rawId.slice(0, -'.jsonl'.length) : rawId;
73
- if (!sessionId.startsWith('meta_')) {
123
+ if (!/^meta_[A-Za-z0-9_-]+$/u.test(sessionId)) {
74
124
  console.error(`✗ ec 会话 id 应以 meta_ 开头(如 meta_20261012_1791789158257),收到: ${rawId}`);
75
125
  process.exitCode = 1;
76
126
  return;
77
127
  }
78
128
  const metaFileName = `${sessionId}.jsonl`;
79
- const p = resolvePaths();
80
- const chatDirs = scanChatDirs(p.sessionsDir);
81
129
  const found = [];
82
130
  for (const chat of chatDirs) {
83
131
  const locations = [
@@ -90,6 +138,7 @@ async function cmdFind(args) {
90
138
  continue;
91
139
  found.push({
92
140
  sessionId: meta.id || sessionId,
141
+ sourceSessionId: meta.sourceSessionId ?? null,
93
142
  metaFile,
94
143
  sessionKey: meta.sessionKey,
95
144
  agentSessionId: meta.agentSessionId ?? null,
@@ -114,6 +163,7 @@ async function cmdFind(args) {
114
163
  if (active && active.id === sessionId) {
115
164
  found.push({
116
165
  sessionId,
166
+ sourceSessionId: active.sourceSessionId ?? null,
117
167
  metaFile: activeFile,
118
168
  sessionKey: active.sessionKey,
119
169
  agentSessionId: active.agentSessionId ?? null,
@@ -147,6 +197,8 @@ async function cmdFind(args) {
147
197
  }
148
198
  for (const f of found) {
149
199
  console.log(`ec 会话 id: ${f.sessionId}`);
200
+ if (f.sourceSessionId)
201
+ console.log(` sourceSessionId: ${f.sourceSessionId}`);
150
202
  console.log(` agentSessionId: ${f.agentSessionId ?? '(空)'}`);
151
203
  console.log(` baseagent: ${f.baseagent ?? '(未知)'}`);
152
204
  console.log(` threadId: ${f.threadId || '(主会话)'}`);
@@ -182,13 +234,76 @@ export async function runSessionCommand(args) {
182
234
  console.log(HELP_TEXT);
183
235
  return;
184
236
  }
185
- switch (sub) {
186
- case 'find':
187
- await cmdFind(args.slice(1));
188
- break;
189
- default:
190
- console.error(`✗ 未知子命令: ${sub}`);
191
- console.log(HELP_TEXT);
192
- process.exitCode = 1;
237
+ try {
238
+ const chats = await authorizedChatDirs(args);
239
+ const json = argValue(args, '--format') === 'json' || hasFlag(args, '--json');
240
+ switch (sub) {
241
+ case 'find':
242
+ await cmdFind(args.slice(1), chats);
243
+ break;
244
+ case 'source': {
245
+ const id = args[1];
246
+ if (!id || id.startsWith('-'))
247
+ throw new Error('用法: ec session source <sessionId>');
248
+ const found = findRecords(chats, id);
249
+ if (!found.length)
250
+ throw new Error(`未找到会话 ${id}`);
251
+ const sources = found.map(({ meta }) => ({ sessionId: meta.id, sourceSessionId: meta.sourceSessionId ?? null }));
252
+ if (json)
253
+ console.log(JSON.stringify({ ok: true, found: sources }, null, 2));
254
+ else
255
+ for (const source of sources)
256
+ console.log(source.sourceSessionId ?? '(根会话,无来源)');
257
+ break;
258
+ }
259
+ case 'capsule': {
260
+ const operation = args[1];
261
+ const id = args[2];
262
+ if (!id || id.startsWith('-'))
263
+ throw new Error('用法: ec session capsule list <sessionId> | show <capsuleId>');
264
+ if (operation === 'list') {
265
+ const found = findRecords(chats, id);
266
+ if (!found.length)
267
+ throw new Error(`未找到会话 ${id}`);
268
+ const capsules = [...new Set(found.map(record => record.chat.dirPath))]
269
+ .flatMap(chat => materializeSessionCapsules(chat).filter(capsule => capsule.sessionId === id));
270
+ if (json)
271
+ console.log(JSON.stringify({ ok: true, sessionId: id, capsules }, null, 2));
272
+ else if (!capsules.length)
273
+ console.log('(无胶囊)');
274
+ else
275
+ for (const capsule of capsules)
276
+ printCapsule(capsule);
277
+ }
278
+ else if (operation === 'show') {
279
+ if (!/^cap_[A-Za-z0-9_-]+$/u.test(id))
280
+ throw new Error('无效的胶囊 ID');
281
+ const capsules = chats.flatMap(chat => {
282
+ const capsule = findSessionCapsule(chat.dirPath, id);
283
+ return capsule ? [capsule] : [];
284
+ });
285
+ if (!capsules.length)
286
+ throw new Error(`未找到胶囊 ${id}`);
287
+ if (json)
288
+ console.log(JSON.stringify({ ok: true, capsules }, null, 2));
289
+ else
290
+ for (const capsule of capsules) {
291
+ printCapsule(capsule);
292
+ console.log(`\n${capsule.content}\n`);
293
+ }
294
+ }
295
+ else
296
+ throw new Error('用法: ec session capsule list <sessionId> | show <capsuleId>');
297
+ break;
298
+ }
299
+ default:
300
+ console.error(`✗ 未知子命令: ${sub}`);
301
+ console.log(HELP_TEXT);
302
+ process.exitCode = 1;
303
+ }
304
+ }
305
+ catch (error) {
306
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
307
+ process.exitCode = 1;
193
308
  }
194
309
  }
package/dist/cli/stats.js CHANGED
@@ -4,8 +4,9 @@
4
4
  import { resolveRoot } from '../paths.js';
5
5
  import { wantsHelp } from './help.js';
6
6
  import { authorizeLocalCommand } from './task-context.js';
7
- import { queryAggregated, querySessionTurns, queryContextBreakdown, queryTopPeers, queryTopModels, queryMessageAggregated, queryPeerList, querySummary, queryPeerDaily, queryTaskModelCalls, querySessionModelCalls } from '../stats/query.js';
7
+ import { queryAggregated, querySessionTurns, queryContextBreakdown, queryTopPeers, queryTopModels, queryMessageAggregated, queryPeerList, querySummary, queryPeerDaily, queryTaskModelCalls, querySessionModelCalls, queryTaskSummary } from '../stats/query.js';
8
8
  import { getBudgetStatus } from '../stats/budget.js';
9
+ import { normalizeUsage } from '../stats/normalizer.js';
9
10
  const HELP = `ec stats — Token 用量与费用统计
10
11
 
11
12
  Usage: ec stats [options]
@@ -266,6 +267,48 @@ export async function handleStats(args) {
266
267
  }
267
268
  }
268
269
  console.log(`${GREEN}✓ 回填完成:${updated} 条事件${RESET}`);
270
+ // 步骤1b:回填 model_calls 的 cost 字段(逐次调用明细,同样只处理金额为 NULL 的行)
271
+ // 明细行与 usage_events 走同一套价目,回填后 task 级金额可直接 SUM 对账。
272
+ let callsUpdated = 0;
273
+ try {
274
+ const pendingCalls = db.prepare(`
275
+ SELECT id, ts, agent_aid, peer_key, session_id, model,
276
+ input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens
277
+ FROM model_calls WHERE cost_official_usd IS NULL
278
+ `).all();
279
+ for (let i = 0; i < pendingCalls.length; i += batchSize) {
280
+ db.exec('BEGIN');
281
+ const batch = pendingCalls.slice(i, i + batchSize);
282
+ for (const call of batch) {
283
+ const event = normalizeUsage({
284
+ input_tokens: call.input_tokens ?? 0,
285
+ output_tokens: call.output_tokens ?? 0,
286
+ cache_creation_input_tokens: call.cache_creation_tokens ?? 0,
287
+ cache_read_input_tokens: call.cache_read_tokens ?? 0,
288
+ }, {
289
+ ts: call.ts,
290
+ agent_aid: call.agent_aid ?? '',
291
+ peer_key: call.peer_key ?? '',
292
+ session_id: call.session_id ?? undefined,
293
+ model: call.model || 'unknown',
294
+ turns: 1,
295
+ });
296
+ const prices = resolvePrices(home, event);
297
+ db.prepare(`
298
+ UPDATE model_calls
299
+ SET cost_official_usd = ?, cost_official_cny = ?,
300
+ cost_gateway_usd = ?, cost_gateway_cny = ?
301
+ WHERE id = ?
302
+ `).run(prices.official?.usd ?? null, prices.official?.cny ?? null, prices.gateway?.usd ?? null, prices.gateway?.cny ?? null, call.id);
303
+ callsUpdated++;
304
+ }
305
+ db.exec('COMMIT');
306
+ }
307
+ console.log(`${GREEN}✓ 模型调用明细回填完成:${callsUpdated} 条${RESET}`);
308
+ }
309
+ catch (e) {
310
+ console.log(`${YELLOW}⚠ 模型调用明细回填跳过:${e?.message || e}${RESET}`);
311
+ }
269
312
  // 步骤2:重建 usage_daily(会自动聚合 cost 字段)
270
313
  console.log(`${CYAN}正在重建日聚合表...${RESET}`);
271
314
  const n = rebuildDailyRollup(home);
@@ -432,17 +475,30 @@ export async function handleStats(args) {
432
475
  return;
433
476
  }
434
477
  console.log(`\n${BOLD}📊 模型用量明细 — ${key}${RESET}\n`);
435
- const headers = ['#', 'Model', 'Source', 'Input', 'Output', 'CacheR', 'CacheW', 'Provider Thread', 'Task', 'Deg'];
478
+ const headers = ['#', 'Model', 'Source', 'Input', 'Output', 'CacheR', 'CacheW', 'Official', 'Gateway', 'Provider Thread', 'Deg'];
436
479
  const tableRows = rows.map(r => [
437
480
  String(r.call_index),
438
481
  r.model.split('-').slice(0, 3).join('-'),
439
482
  r.source,
440
483
  fmtTokens(r.input_tokens), fmtTokens(r.output_tokens),
441
484
  fmtTokens(r.cache_read_tokens), fmtTokens(r.cache_creation_tokens),
485
+ r.cost_official_usd != null && r.cost_official_usd > 0 ? '$' + r.cost_official_usd.toFixed(4) : '—',
486
+ r.cost_gateway_usd != null && r.cost_gateway_usd > 0 ? '$' + r.cost_gateway_usd.toFixed(4) : '—',
442
487
  r.provider_thread_id ?? '',
443
- r.task_id, r.degraded ? 'Y' : '',
488
+ r.degraded ? 'Y' : '',
444
489
  ]);
445
490
  printTable(headers, tableRows);
491
+ // 汇总行
492
+ if (byTask) {
493
+ const sum = queryTaskSummary(home, key);
494
+ console.log(`\n Tokens: input ${fmtTokens(sum.input_tokens)} output ${fmtTokens(sum.output_tokens)} cache_read ${fmtTokens(sum.cache_read_tokens)} cache_write ${fmtTokens(sum.cache_creation_tokens)}`);
495
+ if (sum.cost_official_usd > 0 || sum.cost_official_cny > 0) {
496
+ console.log(` Official: ${GREEN}$${sum.cost_official_usd.toFixed(4)}${RESET} ¥${sum.cost_official_cny.toFixed(4)}`);
497
+ }
498
+ if (sum.cost_gateway_usd > 0 || sum.cost_gateway_cny > 0) {
499
+ console.log(` Gateway: ${GREEN}$${sum.cost_gateway_usd.toFixed(4)}${RESET} ¥${sum.cost_gateway_cny.toFixed(4)}`);
500
+ }
501
+ }
446
502
  console.log();
447
503
  return;
448
504
  }
@@ -610,7 +666,7 @@ export async function handleStats(args) {
610
666
  const totCacheAll = totIn + totCacheRead;
611
667
  const sessionCacheHitRate = totCacheAll > 0 ? totCacheRead / totCacheAll : 0;
612
668
  // model_spec
613
- const { resolveModelSpec } = await import('../stats/billing.js');
669
+ const { resolveModelSpec } = await import('../stats/price-resolver.js');
614
670
  const spec = resolveModelSpec(home, last.model);
615
671
  const result = {
616
672
  turn: {
@@ -365,7 +365,7 @@ export async function buildTriggerCreateRequest(args, fileScope, defaultAgentAid
365
365
  ...(parsed.targetSession === 'thread' ? { threadId: parsed.targetThreadId } : {}),
366
366
  },
367
367
  },
368
- reliability: { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 0, backoffMs: 30_000 } },
368
+ reliability: { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 1, backoffMs: 30_000 } },
369
369
  limits: limitsFromParsed(parsed),
370
370
  };
371
371
  const files = script ? [{
@@ -654,7 +654,7 @@ function loadDefinitionWithFiles(inputPath, fileScope) {
654
654
  const stat = fs.statSync(inputPath);
655
655
  const baseDir = stat.isDirectory() ? inputPath : path.dirname(inputPath);
656
656
  const jsonPath = stat.isDirectory() ? path.join(inputPath, 'trigger.json') : inputPath;
657
- const definition = normalizeTriggerDefinition(JSON.parse(readTriggerLocalFile(jsonPath, fileScope).toString('utf8')));
657
+ const definition = normalizeTriggerDefinition(JSON.parse(readTriggerLocalFile(jsonPath, fileScope).toString('utf8')), { allowLegacyZeroRetryAttempts: true });
658
658
  if (fileScope && definition.agentAid !== fileScope.selfAid)
659
659
  throw new Error('imported Trigger must belong to the authorized Agent');
660
660
  const files = [];
@@ -91,6 +91,8 @@ function assertAccessPolicyWrite(input, agent, policy) {
91
91
  function clonePolicy(policy) {
92
92
  return {
93
93
  policyMode: policy.policyMode,
94
+ allowExternalContacts: policy.allowExternalContacts ?? true,
95
+ allowedAids: [...(policy.allowedAids ?? [])],
94
96
  requestLimit: { ...policy.requestLimit },
95
97
  };
96
98
  }
@@ -6,8 +6,9 @@ import fs from 'fs';
6
6
  import path from 'path';
7
7
  import { resolvePaths, agentDir, agentRelationConfig } from '../paths.js';
8
8
  import { roleMenuQuery, roleMenuUpdate } from '../core/command/role-menu.js';
9
- import { parsePeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
10
- import { isExplicitGroupId } from '../aun/group/index.js';
9
+ import { parseAgentMdFrontmatter, parsePeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
10
+ import { agentmdGet } from '../aun/aid/agentmd.js';
11
+ import { isLegacyNamedGroupIdHint } from '../aun/group/index.js';
11
12
  import { isUnsupportedBaseagentConfigField } from './config-field-policy.js';
12
13
  export const AUTHENTICATED_CONFIG_ROLE_ENV = 'EVOLCORE_AUTHENTICATED_CONFIG_ROLE';
13
14
  export function executeResolvedConfigCommand(command, options = {}) {
@@ -64,7 +65,6 @@ async function executeRelationRoleCommand(op, options) {
64
65
  if (!op.self || !op.peerKey) {
65
66
  return { ok: false, code: 'PEER_REQUIRED', error: 'role requires --self <aid> --peer <peer-aid>' };
66
67
  }
67
- const target = roleTargetFromPeerKey(op.self, op.peerKey);
68
68
  const context = options.roleContext ?? {
69
69
  self: op.self,
70
70
  actorRole: options.role || 'owner',
@@ -76,6 +76,7 @@ async function executeRelationRoleCommand(op, options) {
76
76
  if (context.self !== op.self) {
77
77
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Role target does not match the receiving Agent' };
78
78
  }
79
+ const target = await roleTargetFromPeerKey(op.self, op.peerKey);
79
80
  const targetArgs = { self: op.self, view: 'target', target };
80
81
  const current = await roleMenuQuery(context, targetArgs);
81
82
  const explicitRole = current?.assignment?.explicitRole
@@ -140,7 +141,7 @@ async function executeRelationRoleCommand(op, options) {
140
141
  roleDetails: updatedDetails,
141
142
  };
142
143
  }
143
- function roleTargetFromPeerKey(self, peerKey) {
144
+ async function roleTargetFromPeerKey(self, peerKey) {
144
145
  let parsed;
145
146
  try {
146
147
  parsed = parsePeerKey(peerKey);
@@ -153,10 +154,20 @@ function roleTargetFromPeerKey(self, peerKey) {
153
154
  }
154
155
  const relation = read(ConfigTarget.Relation, { self, peerKey });
155
156
  const identity = PeerIdentityCache.get('aun', parsed.channelId, agentDir(self));
156
- const verifiedType = identity?.aid === parsed.channelId && identity.source === 'agentmd' && identity.verifiedAt > 0
157
+ let verifiedType = identity?.aid === parsed.channelId && identity.source === 'agentmd' && identity.verifiedAt > 0
157
158
  ? identity.type : undefined;
159
+ if (!relation?.targetKind && !verifiedType) {
160
+ try {
161
+ const result = await agentmdGet(parsed.channelId, { withVerification: true });
162
+ if (result.verification.status === 'verified') {
163
+ const metadata = parseAgentMdFrontmatter(result.content);
164
+ verifiedType = typeof metadata.type === 'string' ? metadata.type : undefined;
165
+ }
166
+ }
167
+ catch { }
168
+ }
158
169
  const isGroup = relation?.targetKind ? relation.targetKind === 'group'
159
- : verifiedType ? verifiedType === 'group' : isExplicitGroupId(parsed.channelId);
170
+ : verifiedType ? verifiedType.toLowerCase() === 'group' : isLegacyNamedGroupIdHint(parsed.channelId);
160
171
  return isGroup
161
172
  ? { kind: 'group', groupId: parsed.channelId }
162
173
  : { kind: 'private', peerAid: parsed.channelId };
@@ -18,7 +18,7 @@ import { saveDefaultsSafe, saveAgent } from '../config-store.js';
18
18
  import { resolveAnthropicConfig, resolveEcagentConfig, resolveOpenaiConfig } from '../agents/baseagent.js';
19
19
  import { buildModelRequestHeaders } from '../agents/request-identity.js';
20
20
  import { appendV1RequestPath } from '../agents/request-identity.js';
21
- import { resolvePriceRow } from '../stats/billing.js';
21
+ import { resolvePriceRow } from '../stats/price-resolver.js';
22
22
  import { ipcQuery } from '../ipc.js';
23
23
  import { logger } from '../utils/logger.js';
24
24
  import { ConfigTarget, read as readConfig, stripLegacyAunGatewayConfig } from './config-manager.js';
@@ -43,12 +43,11 @@ export function listStaticAgentAdmins(aid, opts = {}) {
43
43
  catch {
44
44
  continue;
45
45
  }
46
- if (parsed.channelType !== 'aun'
47
- || !isValidAid(parsed.channelId)
48
- || isExplicitGroupId(parsed.channelId))
46
+ if (parsed.channelType !== 'aun' || !isValidAid(parsed.channelId))
49
47
  continue;
50
48
  const config = read(ConfigTarget.Relation, { self: aid, peerKey: entry.name }, { cache: opts.fresh !== true });
51
- if (config?.targetKind === 'group')
49
+ if (config?.targetKind === 'group'
50
+ || (!config?.targetKind && isExplicitGroupId(parsed.channelId)))
52
51
  continue;
53
52
  if (config?.role === 'admin')
54
53
  admins.add(parsed.channelId);
@@ -76,10 +75,12 @@ export function isStaticAgentOwner(aid, actorId) {
76
75
  return !!aid && !!actorId && listStaticAgentOwners(aid).includes(actorId);
77
76
  }
78
77
  export function isStaticAgentAdmin(aid, actorId) {
79
- if (!aid || !isValidAid(actorId) || isExplicitGroupId(actorId))
78
+ if (!aid || !isValidAid(actorId))
80
79
  return false;
81
80
  const config = read(ConfigTarget.Relation, { self: aid, peerKey: formatPeerKey('aun', actorId) }, { cache: true });
82
- return config?.targetKind !== 'group' && config?.role === 'admin';
81
+ if (config?.targetKind === 'group' || (!config?.targetKind && isExplicitGroupId(actorId)))
82
+ return false;
83
+ return config?.role === 'admin';
83
84
  }
84
85
  export function addStaticAgentOwner(aid, ownerAid) {
85
86
  throw new Error('Owner is protocol-managed; use ec aid bind');
@@ -213,12 +214,13 @@ function readAgentDefaultRole(aid, chatType) {
213
214
  function readDirectRelationRole(selfAid, channelType, channelId, expectedTargetKind) {
214
215
  if (!selfAid || !channelType || !channelId)
215
216
  return undefined;
216
- if (expectedTargetKind === 'private' && channelType === 'aun' && isExplicitGroupId(channelId))
217
- return undefined;
218
217
  const peerKey = formatPeerKey(channelType, channelId);
219
218
  const config = read(ConfigTarget.Relation, { self: selfAid, peerKey }, { cache: true });
220
219
  if (expectedTargetKind && config?.targetKind && config.targetKind !== expectedTargetKind)
221
220
  return undefined;
221
+ if (expectedTargetKind === 'private' && channelType === 'aun'
222
+ && !config?.targetKind && isExplicitGroupId(channelId))
223
+ return undefined;
222
224
  return config?.role;
223
225
  }
224
226
  function normalizeRelationRole(value, selfAid) {
@@ -1,3 +1,4 @@
1
+ import { initializationSummary } from '../cli/agent-create.js';
1
2
  import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { agentMdPath, resolvePaths, } from '../paths.js';
@@ -90,11 +91,14 @@ export class AgentApplicationService {
90
91
  const config = (loadAgent(aid) ?? agent.config);
91
92
  const identity = readAgentMdIdentity(aid);
92
93
  const paths = resolvePaths();
94
+ const lifecycle = config?.lifecycle ?? null;
95
+ const initialization = initializationSummary(aid);
96
+ const initializationState = initialization && this.initialization?.status(aid);
93
97
  return {
94
98
  ok: true,
95
99
  aid,
96
100
  status: info.status || 'stopped',
97
- lifecycle: config?.lifecycle ?? null,
101
+ lifecycle,
98
102
  identity,
99
103
  config: {
100
104
  baseagent: info.baseagent || null,
@@ -104,6 +108,12 @@ export class AgentApplicationService {
104
108
  channels: info.channels ?? [],
105
109
  },
106
110
  connection,
111
+ ...(initialization ? {
112
+ initialization,
113
+ usable: typeof initializationState?.usable === 'boolean'
114
+ ? initializationState.usable
115
+ : initialization.complete === true && lifecycle === 'active' && connection?.status === 'connected',
116
+ } : {}),
107
117
  sessions: {
108
118
  active: info.activeSessions ?? 0,
109
119
  last_activity: info.lastActivity ? new Date(info.lastActivity).toISOString() : null,
@@ -274,6 +274,10 @@ export function registerAgentOperationExecutor({ ipcServer, sessionManager, agen
274
274
  const plan = resolveInitializationPlan(argv.slice(1), {
275
275
  projectCwd: taskSession.projectPath, tempDir: delegation.grant.sessionRuntimeDir,
276
276
  });
277
+ const { validateInitializationModelArgs } = await import('../cli/agent-create.js');
278
+ const modelError = await validateInitializationModelArgs(plan);
279
+ if (modelError)
280
+ return fail(modelError.code, modelError.error);
277
281
  if (plan.avatarFile?.startsWith('attachment:')) {
278
282
  const { readRelationAttachment } = await import('../utils/media-cache.js');
279
283
  plan.avatarFile = readRelationAttachment(taskAid, delegation.grant.peerKey, plan.avatarFile.slice('attachment:'.length)).attachment.filePath;
@@ -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
  });
@@ -544,17 +547,89 @@ function delegationFailureDetailCode(cause) {
544
547
  return 'APPROVED_COMMAND_UNAVAILABLE';
545
548
  }
546
549
  }
547
- export function hashDelegatedCommandArgv(argv) {
550
+ export function hashDelegatedCommandArgv(argv, executionSpec) {
548
551
  if (argv.length === 0 || argv.some(value => typeof value !== 'string' || value.includes('\0')))
549
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
+ }
550
624
  return crypto.createHash('sha256')
551
- .update('evolcore-agent-delegation-command-v1\0')
552
- .update(JSON.stringify(argv))
625
+ .update('evolcore-agent-delegation-spec-v1\0')
626
+ .update(JSON.stringify(spec))
553
627
  .digest('hex');
554
628
  }
555
629
  export function hashCurrentDelegatedCommand(processArgv = process.argv) {
556
630
  const argv = currentDelegatedCommandArgv(processArgv);
557
- return argv ? hashDelegatedCommandArgv([MAIN_CLI_BIN, ...argv]) : undefined;
631
+ const spec = readDelegatedExecutionSpec();
632
+ return argv ? hashDelegatedCommandArgv([MAIN_CLI_BIN, ...argv], spec) : undefined;
558
633
  }
559
634
  /**
560
635
  * Return the command arguments used by a delegated CLI invocation.