evolcore 0.0.48 → 0.0.49

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 (112) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/agent-template/runtime.js +5 -2
  3. package/dist/agents/codex-runner.js +5 -1
  4. package/dist/aun/msg/p2p.js +2 -1
  5. package/dist/build-identity.json +1 -1
  6. package/dist/channels/aun.js +643 -273
  7. package/dist/cli/directory.js +6 -1
  8. package/dist/cli/index.js +7 -1
  9. package/dist/cli/managed-command-guard.js +2 -0
  10. package/dist/cli/model.js +20 -5
  11. package/dist/cli/quota.js +89 -0
  12. package/dist/cli/role.js +1 -0
  13. package/dist/cli/services-command.js +1 -0
  14. package/dist/cli/team-workspace-command.js +56 -2
  15. package/dist/config/config-field-policy.js +71 -1
  16. package/dist/config/config-manager.js +11 -1
  17. package/dist/config/providers-config.js +8 -4
  18. package/dist/config/providers-management.js +11 -3
  19. package/dist/config/resolved-config-op.js +3 -2
  20. package/dist/core/auth/delegation-authorization.js +33 -26
  21. package/dist/core/auth/operation-catalog.js +9 -0
  22. package/dist/core/command/cli-intent-parser.js +13 -0
  23. package/dist/core/command/command-handler.js +45 -2
  24. package/dist/core/command/menu-handler.js +6 -1
  25. package/dist/core/command/menu-protocol.js +24 -0
  26. package/dist/core/command/remote-shell.js +565 -0
  27. package/dist/core/daemon-control.js +57 -1
  28. package/dist/core/daemon-lifecycle.js +16 -2
  29. package/dist/core/evolagent-registry.js +6 -2
  30. package/dist/core/ipc-registration.js +1 -0
  31. package/dist/core/message/aun-ipc-sender.js +118 -56
  32. package/dist/core/message/contact-admission.js +91 -6
  33. package/dist/core/message/contact-pending-inbound.js +113 -0
  34. package/dist/core/message/contact-thread-approval.js +212 -0
  35. package/dist/core/message/im-renderer.js +40 -1
  36. package/dist/core/message/message-admission.js +5 -39
  37. package/dist/core/message/message-bridge.js +92 -39
  38. package/dist/core/message/message-log.js +24 -0
  39. package/dist/core/message/message-queue.js +97 -15
  40. package/dist/core/message/response-engine.js +151 -18
  41. package/dist/core/model/config-scope.js +6 -14
  42. package/dist/core/model/model-diagnostics.js +19 -0
  43. package/dist/core/model/model-fallback.js +13 -2
  44. package/dist/core/pack-auth.js +3 -0
  45. package/dist/core/pack-install.js +1 -1
  46. package/dist/core/permission/ec-command-parser.js +106 -19
  47. package/dist/core/permission/services-path-acl.js +451 -0
  48. package/dist/core/permission/tool-policy.js +5 -1
  49. package/dist/core/relation/peer-identity.js +13 -0
  50. package/dist/core/task/task-recovery-service.js +1 -0
  51. package/dist/core/thread/topic-id.js +15 -0
  52. package/dist/directory/owner-directory-admission.js +11 -8
  53. package/dist/directory/owner-directory-cache.js +19 -0
  54. package/dist/directory/owner-directory-markdown.js +1 -1
  55. package/dist/directory/owner-directory-policy.js +5 -30
  56. package/dist/directory/owner-directory-request-operation.js +5 -2
  57. package/dist/eck/kit-renderer.js +1 -1
  58. package/dist/eck/message-renderer.js +28 -5
  59. package/dist/ecweb/runtime/supervisor.js +36 -8
  60. package/dist/event-center/center-config.js +9 -5
  61. package/dist/event-center/dispatcher.js +10 -1
  62. package/dist/event-center/ipc-operation.js +19 -0
  63. package/dist/event-center/registry.js +20 -5
  64. package/dist/event-center/runtime.js +10 -7
  65. package/dist/index.js +4 -0
  66. package/dist/ipc.js +25 -1
  67. package/dist/outputs/authorization.js +16 -0
  68. package/dist/outputs/cards.js +336 -0
  69. package/dist/outputs/events.js +3 -2
  70. package/dist/outputs/protocol.js +1 -0
  71. package/dist/outputs/service.js +2 -15
  72. package/dist/services/index.js +29 -5
  73. package/dist/services/ipc-operation.js +84 -0
  74. package/dist/services/pack-manager.js +1 -0
  75. package/dist/services/service-payload.js +13 -7
  76. package/dist/stats/budget.js +1 -1
  77. package/dist/stats/model-resolver.js +2 -2
  78. package/dist/stats/quota-query.js +95 -0
  79. package/dist/trigger/script-sandbox.js +12 -0
  80. package/dist/utils/atomic-write.js +22 -8
  81. package/dist/utils/evolcore-version.js +2 -2
  82. package/dist/utils/host-info.js +100 -1
  83. package/dist/utils/npm-ops.js +43 -8
  84. package/dist/workbench/service.js +1 -1
  85. package/kits/docs/evolcore/INDEX.md +2 -0
  86. package/kits/docs/evolcore/aid.md +25 -0
  87. package/kits/docs/evolcore/config.md +4 -1
  88. package/kits/docs/evolcore/directory.md +8 -9
  89. package/kits/docs/evolcore/msg.md +9 -0
  90. package/kits/docs/evolcore/provider.md +1 -1
  91. package/kits/docs/evolcore/quota.md +54 -0
  92. package/kits/docs/evolcore/role.md +3 -0
  93. package/kits/docs/evolcore/stats.md +2 -0
  94. package/kits/docs/evolcore/trigger.md +2 -0
  95. package/kits/schemas/agent-config.schema.20.json +24 -0
  96. package/kits/skills/.switches.json +4 -0
  97. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  98. package/kits/skills/ec-provider/SKILL.md +57 -8
  99. package/kits/templates/roles/visitor.json +1 -0
  100. package/kits/templates/system-fragments/commands.md +1 -0
  101. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  102. package/kits/templates/system-fragments/thread.md +1 -0
  103. package/kits/templates/system-fragments/venue.md +11 -0
  104. package/package.json +2 -2
  105. package/scripts/agent-template/inspect.mjs +46 -10
  106. package/scripts/agent-template/shared/common.mjs +9 -3
  107. package/scripts/agent-template/shared/team-schema.json +6 -4
  108. package/scripts/agent-template/shared/template-contract.mjs +60 -10
  109. package/scripts/agent-template/shared/template-package.mjs +182 -21
  110. package/scripts/agent-template/shared/template-runtime.mjs +35 -2
  111. package/scripts/agent-template/shared/template.mjs +2 -2
  112. package/scripts/agent-template/team-pack.mjs +46 -11
@@ -5,15 +5,21 @@
5
5
  * 不涉及「本机有没有包能接」(那是 pack-manager 的事),也不涉及
6
6
  * 「这条消息来自谁」(那是准入的事)。三层判据互不推导。
7
7
  */
8
- /** 请求 type:≤3 段。 */
9
- const SERVICE_REQUEST = /^services(\.[A-Za-z0-9_-]+){0,2}$/;
10
- /** 应答 type:请求 type + .result,≤4 段。 */
11
- const SERVICE_RESULT = /^services(\.[A-Za-z0-9_-]+){0,2}\.result$/;
12
- /** listen 可用的通配形式:末段整段为 *。 */
13
- const SERVICE_WILDCARD = /^services(\.[A-Za-z0-9_-]+){0,1}\.\*$/;
8
+ /** 请求 type:最多三段 action 路径,例如 services.outputs.cards.snapshot。 */
9
+ const SERVICE_REQUEST = /^services(\.[A-Za-z0-9_-]+){0,3}$/;
10
+ /** 应答 type:请求 type + .result。 */
11
+ const SERVICE_RESULT = /^services(\.[A-Za-z0-9_-]+){0,3}\.result$/;
12
+ /** listen 可用的通配形式:最多两段路径后接末段整段 *。 */
13
+ const SERVICE_WILDCARD = /^services(\.[A-Za-z0-9_-]+){0,2}\.\*$/;
14
+ /** Owner-private read projections are ephemeral control replies. Business
15
+ * service replies keep their normal durable delivery semantics. */
16
+ export function isProjectionServiceResult(type) {
17
+ return typeof type === 'string'
18
+ && /^services\.(?:outputs\.(?:(?:snapshot|list|detail|changes)|cards\.(?:snapshot|list|detail|changes))|workbench\.(?:snapshot|changes|history))\.result$/.test(type);
19
+ }
14
20
  /**
15
21
  * SERVICE_REQUEST 与 SERVICE_RESULT 有意重叠:
16
- * `services.order.result` 同时匹配两条({0,2} 允许两段后缀,.order + .result 正好凑满)。
22
+ * `services.order.result` 同时匹配两条;
17
23
  * 靠 result 优先消解——先判应答,再判请求。
18
24
  *
19
25
  * 因此 `services.result` 既是合法请求(裸 services 的 action),也是裸 `services` 的应答;
@@ -72,7 +72,7 @@ export function getBudgetStatus(evolcoreHome, agentAid, peerKey) {
72
72
  const dailyRemaining = Math.max(0, dailyLimit - dailyUsed);
73
73
  const dailyPct = isFinite(dailyLimit) && dailyLimit > 0 ? (dailyUsed / dailyLimit) * 100 : 0;
74
74
  const monthlyLimit = cfg.monthly_usd ?? Infinity;
75
- const monthlyUsed = isFinite(monthlyLimit) ? _calcMonthUsd(evolcoreHome, agentAid) : 0;
75
+ const monthlyUsed = _calcMonthUsd(evolcoreHome, agentAid);
76
76
  const monthlyRemaining = Math.max(0, monthlyLimit - monthlyUsed);
77
77
  const monthlyPct = isFinite(monthlyLimit) && monthlyLimit > 0 ? (monthlyUsed / monthlyLimit) * 100 : 0;
78
78
  // 取 daily/monthly 中更高的百分比作为整体判断依据
@@ -10,7 +10,7 @@ import { logger } from '../utils/logger.js';
10
10
  /** 汇率合法区间:超出视为接口异常,回退默认值,避免金额被单个脏值整体扭曲。 */
11
11
  export const MIN_USD_TO_CNY = 3;
12
12
  export const MAX_USD_TO_CNY = 15;
13
- export const DEFAULT_USD_TO_CNY = 7.23;
13
+ export const DEFAULT_USD_TO_CNY = 7;
14
14
  export function normalizeUsdToCny(raw) {
15
15
  const n = typeof raw === 'number' ? raw : NaN;
16
16
  return Number.isFinite(n) && n >= MIN_USD_TO_CNY && n <= MAX_USD_TO_CNY ? n : undefined;
@@ -721,7 +721,7 @@ export function resolvePrices(evolcoreHome, event, gatewayPricing) {
721
721
  gatewayCost = officialCost;
722
722
  }
723
723
  // ── 3. 转换为统一格式 ───────────────────────────────────────────────────
724
- // 计费函数按价格行币种只产出一种货币(接口价恒为 USD)。用网关汇率(usd_to_cny,缺省 7.23)
724
+ // 计费函数按价格行币种只产出一种货币(接口价恒为 USD)。用网关汇率(usd_to_cny,缺省 7)
725
725
  // 补齐另一种货币:有 usd 缺 cny → cny=usd*rate;有 cny 缺 usd → usd=cny/rate。
726
726
  const rate = normalizeUsdToCny(gatewayPricing?.usdToCny) ?? DEFAULT_USD_TO_CNY;
727
727
  const toPair = (c) => {
@@ -0,0 +1,95 @@
1
+ import fs from 'node:fs';
2
+ import { isValidAid } from '../aun/aid/validation.js';
3
+ import { agentConfig, resolveRoot } from '../paths.js';
4
+ import { resolveFreshPeerRoleDetail } from '../config/peer-role-resolver.js';
5
+ import { normalizePeerKey, parsePeerKey, readAunPeerKind } from '../core/relation/peer-identity.js';
6
+ import { getBudgetStatus } from './budget.js';
7
+ import { getRoleBudgetStatus } from './role-budget.js';
8
+ export class QuotaQueryError extends Error {
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+ /** Shared request parsing for CLI output, authorization intents and daemon execution. */
16
+ export function parseQuotaCommand(input) {
17
+ const args = input[0] === 'quota' ? input.slice(1) : input;
18
+ if (args[0] !== 'status')
19
+ throw new QuotaQueryError('INVALID_ARGUMENT', 'Usage: ec quota status [--self <aid>] [--peer <aid|channel#id>] [--format text|json]');
20
+ const values = new Map();
21
+ for (let i = 1; i < args.length; i++) {
22
+ const [flag, ...inline] = args[i].split('=');
23
+ if (!['--self', '--peer', '--format'].includes(flag) || values.has(flag)) {
24
+ throw new QuotaQueryError('INVALID_ARGUMENT', `Unknown or duplicate quota option: ${args[i]}`);
25
+ }
26
+ const value = inline.length ? inline.join('=') : args[++i];
27
+ if (!value?.trim() || value.startsWith('-'))
28
+ throw new QuotaQueryError('INVALID_ARGUMENT', `${flag} requires a value`);
29
+ values.set(flag, value.trim());
30
+ }
31
+ const selfAid = values.get('--self');
32
+ if (selfAid && !isValidAid(selfAid))
33
+ throw new QuotaQueryError('INVALID_SELF', '--self must be a valid Agent AID');
34
+ const format = values.get('--format') ?? 'text';
35
+ if (format !== 'text' && format !== 'json')
36
+ throw new QuotaQueryError('INVALID_ARGUMENT', '--format must be text or json');
37
+ const peer = values.get('--peer');
38
+ return { selfAid, peerKey: peer ? normalizeQuotaPeer(peer) : undefined, format };
39
+ }
40
+ function normalizeQuotaPeer(value) {
41
+ try {
42
+ return normalizePeerKey(value, { strict: true });
43
+ }
44
+ catch {
45
+ throw new QuotaQueryError('INVALID_PEER', '--peer must be a valid AID or channel#id');
46
+ }
47
+ }
48
+ export async function queryQuota(command, context) {
49
+ const selfAid = command.selfAid ?? context.selfAid;
50
+ if (!selfAid)
51
+ throw new QuotaQueryError('INVALID_SELF', 'Host terminal queries require --self <agent-aid>');
52
+ const sameAgent = selfAid === context.selfAid;
53
+ if (!sameAgent && !context.allowOtherAgent)
54
+ throw new QuotaQueryError('SCOPE_MISMATCH', 'Only the current Agent quota can be queried');
55
+ if (!fs.existsSync(agentConfig(selfAid)))
56
+ throw new QuotaQueryError('AGENT_NOT_FOUND', `Agent does not exist: ${selfAid}`);
57
+ const currentPeerKey = sameAgent && context.peerKey ? normalizeQuotaPeer(context.peerKey) : undefined;
58
+ const peerKey = command.peerKey ?? currentPeerKey;
59
+ if (!context.canReadAgent && (!peerKey || peerKey !== currentPeerKey)) {
60
+ throw new QuotaQueryError('NOT_ALLOWED', 'Only the current relation quota can be queried');
61
+ }
62
+ const home = resolveRoot();
63
+ const agentBudget = getBudgetStatus(home, selfAid);
64
+ let relation = null;
65
+ let blocked = agentBudget.hard_blocked;
66
+ if (peerKey) {
67
+ const { channelType, channelId } = parsePeerKey(peerKey);
68
+ const current = sameAgent && peerKey === currentPeerKey;
69
+ const chatType = current ? context.chatType ?? 'private' : 'private';
70
+ if (!current && channelType === 'aun' && readAunPeerKind(selfAid, channelId).kind === 'group') {
71
+ throw new QuotaQueryError('GROUP_CONTEXT_REQUIRED', 'Query a group quota from its current conversation so the member identity is known');
72
+ }
73
+ if (chatType === 'group' && !context.actorId)
74
+ throw new QuotaQueryError('GROUP_CONTEXT_REQUIRED', 'The current group member identity is required');
75
+ const actorId = current ? context.actorId || channelId : channelId;
76
+ const detail = await resolveFreshPeerRoleDetail({
77
+ selfAid, channelType, channelKey: current && context.channelKey ? context.channelKey : `${channelType}#${selfAid}#main`,
78
+ chatType, actorId, conversationId: channelId,
79
+ });
80
+ if (detail.authorizationFailure)
81
+ throw new QuotaQueryError('ROLE_UNAVAILABLE', detail.authorizationFailure.reason);
82
+ const roleQuota = getRoleBudgetStatus(home, { selfAid, role: detail.effectiveRole, channelType, chatType, channelId, peerId: actorId });
83
+ const relationBudget = getBudgetStatus(home, selfAid, peerKey);
84
+ blocked ||= relationBudget.hard_blocked || roleQuota.hard_blocked;
85
+ relation = {
86
+ peerKey, actorId, chatType, roleSource: detail.source, budgetUsageScope: 'agent',
87
+ budget: context.canReadAgent ? relationBudget : null, roleQuota,
88
+ };
89
+ }
90
+ return {
91
+ ok: true, selfAid,
92
+ agent: { visible: context.canReadAgent, budget: context.canReadAgent ? agentBudget : null },
93
+ relation, hard_blocked: blocked,
94
+ };
95
+ }
@@ -202,6 +202,18 @@ export async function buildTriggerScriptLaunch(input) {
202
202
  filesystemEntry(snapshotDir, 'read'),
203
203
  filesystemEntry(workDir, 'write'),
204
204
  filesystemEntry(windowsBackend.home, 'deny'),
205
+ // 服务包:脚本不能改写自己的代码与声明,只能读。
206
+ //
207
+ // 当前行为本来就是这样(`root: read` + 没有任何条目给 services 授 write),
208
+ // 这条的价值是把它从「依赖默认拒绝」变成显式声明:将来若有重构把 services
209
+ // 纳入 write 范围(例如为缓存/worker 方案放权),这里仍然读-写不对称。
210
+ //
211
+ // **不能写 `deny`**:Codex 的 deny 连读一起拒,而服务脚本要读自己的
212
+ // pack.json。真需要拦写也拦不住显式子级 Allow——那由 ACL 层负责
213
+ // (见 src/core/permission/services-path-acl.ts)。
214
+ ...(input.trigger.labels?.kind === 'services'
215
+ ? [filesystemEntry(path.join(root, 'agents', input.trigger.agentAid, 'services'), 'read')]
216
+ : []),
205
217
  ...Object.entries(filesystem).flatMap(([value, access]) => typeof access === 'number' ? [] : [{
206
218
  path: /[*?[\]]/.test(value)
207
219
  ? { type: 'glob_pattern', pattern: value }
@@ -295,14 +295,7 @@ export async function withFileLock(file, action, timeoutMs = 30000) {
295
295
  export async function atomicReplaceJson(file, value) {
296
296
  const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
297
297
  try {
298
- const fd = fs.openSync(temporary, 'wx', 0o600);
299
- try {
300
- fs.writeFileSync(fd, JSON.stringify(value, null, 2) + '\n', 'utf8');
301
- fs.fsyncSync(fd);
302
- }
303
- finally {
304
- fs.closeSync(fd);
305
- }
298
+ writeSyncedReplacement(temporary, JSON.stringify(value, null, 2) + '\n', 'wx');
306
299
  const deadline = Date.now() + 5000;
307
300
  for (let attempt = 0;; attempt++) {
308
301
  try {
@@ -321,6 +314,27 @@ export async function atomicReplaceJson(file, value) {
321
314
  fs.rmSync(temporary, { force: true });
322
315
  }
323
316
  }
317
+ /** Strict synchronous replacement without a hot backup; callers serialize writes to the same file. */
318
+ export function atomicReplaceJsonSync(file, value) {
319
+ const temporary = `${file}.pending`;
320
+ try {
321
+ writeSyncedReplacement(temporary, JSON.stringify(value), 'w');
322
+ atomicReplaceFile(temporary, file, { allowInPlaceFallback: false });
323
+ }
324
+ finally {
325
+ fs.rmSync(temporary, { force: true });
326
+ }
327
+ }
328
+ function writeSyncedReplacement(temporary, content, flags) {
329
+ const fd = fs.openSync(temporary, flags, 0o600);
330
+ try {
331
+ fs.writeFileSync(fd, content, 'utf8');
332
+ fs.fsyncSync(fd);
333
+ }
334
+ finally {
335
+ fs.closeSync(fd);
336
+ }
337
+ }
324
338
  const retryableCodes = new Set(['EPERM', 'EACCES', 'EBUSY']);
325
339
  const delays = [10, 25, 50, 100];
326
340
  const pause = new Int32Array(new SharedArrayBuffer(4));
@@ -5,8 +5,8 @@ import { fileURLToPath } from 'url';
5
5
  import { getPackageRoot } from '../paths.js';
6
6
  // Embedded by bin/ec-build.mjs; loaded processes retain these values across rebuilds.
7
7
  // @evolcore-build-identity:start
8
- export const RUNTIME_BUILD_ID = "sha256:76e20a438d3936bb3420763f";
9
- export const RUNTIME_BUILD_TIME = "2026-11-14T05:54:02.439Z";
8
+ export const RUNTIME_BUILD_ID = "sha256:12c2256a403ff169bb86c416";
9
+ export const RUNTIME_BUILD_TIME = "2026-11-15T03:59:05.194Z";
10
10
  // @evolcore-build-identity:end
11
11
  let cachedVersion;
12
12
  let cachedFlavor;
@@ -128,6 +128,105 @@ function readDisk(evolcoreHomePath) {
128
128
  return { evolcoreHomePath, availableBytes: null, totalBytes: null };
129
129
  }
130
130
  }
131
+ function readText(file) {
132
+ try {
133
+ return fs.readFileSync(file, 'utf8').trim();
134
+ }
135
+ catch {
136
+ return null;
137
+ }
138
+ }
139
+ function parseQuota(quota, period) {
140
+ if (!quota || !period || !/^\d+$/u.test(quota) || !/^\d+$/u.test(period))
141
+ return null;
142
+ const value = Number(quota) / Number(period);
143
+ return Number.isFinite(value) && value > 0 ? value : null;
144
+ }
145
+ /** Resolve the process's own CPU hierarchy, including nonstandard mount points. */
146
+ function cpuHierarchies() {
147
+ const memberships = (readText('/proc/self/cgroup') ?? '').split('\n')
148
+ .map(line => line.match(/^\d+:([^:]*):(\/.*)$/u))
149
+ .filter((match) => match !== null);
150
+ const hierarchies = [];
151
+ const unescapePath = (value) => value.replace(/\\([0-7]{3})/gu, (_match, octal) => String.fromCharCode(Number.parseInt(octal, 8)));
152
+ for (const line of (readText('/proc/self/mountinfo') ?? '').split('\n')) {
153
+ const [mount, filesystem] = line.split(' - ');
154
+ if (!mount || !filesystem)
155
+ continue;
156
+ const fields = mount.split(' ');
157
+ const [type, , options = ''] = filesystem.split(' ');
158
+ if (type !== 'cgroup2' && !(type === 'cgroup' && options.split(',').includes('cpu')))
159
+ continue;
160
+ if (!fields[3] || !fields[4])
161
+ continue;
162
+ const version = type === 'cgroup2' ? 2 : 1;
163
+ const member = memberships.find(match => version === 2
164
+ ? match[1] === '' : match[1].split(',').includes('cpu'));
165
+ if (!member)
166
+ continue;
167
+ const root = unescapePath(fields[3]);
168
+ const mountPoint = unescapePath(fields[4]);
169
+ const relative = path.posix.relative(root, member[2]);
170
+ // A cgroup namespace can expose membership relative to the mounted root.
171
+ const suffix = relative === '..' || relative.startsWith('../') ? member[2] : relative;
172
+ const directory = path.posix.resolve(mountPoint, `./${suffix}`);
173
+ if (directory !== mountPoint && !directory.startsWith(`${mountPoint}/`))
174
+ continue;
175
+ hierarchies.push({ directory, mountPoint, version });
176
+ }
177
+ // Conventional namespace-root mounts also work when procfs is unavailable.
178
+ if (hierarchies.length === 0) {
179
+ for (const [mountPoint, version] of [
180
+ ['/sys/fs/cgroup', 2], ['/sys/fs/cgroup/cpu', 1],
181
+ ['/sys/fs/cgroup/cpu,cpuacct', 1], ['/sys/fs/cgroup/cpuacct,cpu', 1],
182
+ ]) {
183
+ const member = memberships.find(match => version === 2
184
+ ? match[1] === '' : match[1].split(',').includes('cpu'));
185
+ const directory = path.posix.resolve(mountPoint, `.${member?.[2] ?? '/'}`);
186
+ if (directory === mountPoint || directory.startsWith(`${mountPoint}/`)) {
187
+ hierarchies.push({ directory, mountPoint, version });
188
+ }
189
+ }
190
+ }
191
+ return hierarchies;
192
+ }
193
+ /**
194
+ * CPU capacity available to this process. Linux quota/period may be fractional;
195
+ * availableParallelism alone reports an integer suitable for worker counts.
196
+ * Read afresh so live container quota changes are reflected without a restart.
197
+ */
198
+ export function readEffectiveCpuCount() {
199
+ let count = 1;
200
+ try {
201
+ const parallelism = os.availableParallelism();
202
+ if (Number.isInteger(parallelism) && parallelism > 0)
203
+ count = parallelism;
204
+ else
205
+ count = Math.max(1, os.cpus().length);
206
+ }
207
+ catch {
208
+ try {
209
+ count = Math.max(1, os.cpus().length);
210
+ }
211
+ catch { /* retain one CPU */ }
212
+ }
213
+ if (process.platform !== 'linux')
214
+ return count;
215
+ for (const hierarchy of cpuHierarchies()) {
216
+ let directory = hierarchy.directory;
217
+ while (true) {
218
+ const quota = hierarchy.version === 2
219
+ ? parseQuota(...(readText(`${directory}/cpu.max`) ?? '').split(/\s+/u))
220
+ : parseQuota(readText(`${directory}/cpu.cfs_quota_us`) ?? undefined, readText(`${directory}/cpu.cfs_period_us`) ?? undefined);
221
+ if (quota !== null)
222
+ count = Math.min(count, quota);
223
+ if (directory === hierarchy.mountPoint)
224
+ break;
225
+ directory = path.posix.dirname(directory);
226
+ }
227
+ }
228
+ return count;
229
+ }
131
230
  function readCpuModel() {
132
231
  try {
133
232
  const model = os.cpus()[0]?.model?.trim().replace(/\s+/gu, ' ');
@@ -164,7 +263,7 @@ export function readHostInfo(evolcoreVersion, evolcoreHomePath, options = {}) {
164
263
  },
165
264
  hardware: {
166
265
  architecture: process.arch,
167
- cpuCount: os.cpus().length,
266
+ cpuCount: readEffectiveCpuCount(),
168
267
  cpuModel: readCpuModel(),
169
268
  memoryTotalBytes: memInfo.memTotal,
170
269
  memoryUsedBytes: memInfo.memUsed,
@@ -194,7 +194,14 @@ async function canSudoNonInteractively() {
194
194
  export async function npmInstallGlobal(pkg, options = {}) {
195
195
  const npm = resolveNpmInvocation();
196
196
  const registry = options.registry ? normalizeRegistry(options.registry) : undefined;
197
- const npmArgs = ['install', '-g', pkg, ...(registry ? ['--registry', registry] : []), ...npmConfigArgs(options.npmConfig), ...(options.preferOffline ? ['--prefer-offline'] : [])];
197
+ // Override inherited npmrc/env cache modes when recovering from stale metadata.
198
+ const cacheArgs = options.preferOnline
199
+ ? ['--prefer-online', '--prefer-offline=false', '--offline=false']
200
+ : options.preferOffline ? ['--prefer-offline'] : [];
201
+ const npmArgs = [
202
+ 'install', '-g', pkg, ...(registry ? ['--registry', registry] : []),
203
+ ...npmConfigArgs(options.npmConfig), ...cacheArgs,
204
+ ];
198
205
  try {
199
206
  await execFileAsync(npm.command, [...npm.argsPrefix, ...npmArgs], {
200
207
  timeout: options.timeoutMs ?? 180000,
@@ -492,7 +499,30 @@ export async function queryPackageVersion(pkg, selection, signal, distTag = 'lat
492
499
  : await fetchLatestVersion(pkg, 10000, signal, registry, distTag);
493
500
  return isPackageVersion(version) ? { version, registry, npmConfig: selection.npmConfig } : null;
494
501
  }
495
- /** No registry lookup: callers must validate cache freshness before each install. */
502
+ function npmFailureCode(error) {
503
+ const failure = error;
504
+ if (typeof failure?.code === 'string' && /^[A-Z][A-Z0-9_]+$/.test(failure.code))
505
+ return failure.code;
506
+ // execFile reports the numeric exit status; npm's own error code is in stderr.
507
+ const output = [failure?.stderr, failure?.message].filter(value => typeof value === 'string').join('\n');
508
+ return output.match(/(?:^|\n)npm (?:error|ERR!) code ([A-Z][A-Z0-9_]+)\b/)?.[1];
509
+ }
510
+ function formatPackageInstallFailure(error, phase) {
511
+ const failure = error;
512
+ const stderr = typeof failure?.stderr === 'string' ? failure.stderr.trim() : '';
513
+ const errorLines = stderr.split('\n').filter(line => /^npm (?:error|ERR!)\s/.test(line));
514
+ const detail = (errorLines.length ? errorLines.join('\n') : stderr
515
+ || (typeof failure?.message === 'string' ? failure.message : String(error)))
516
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
517
+ .replace(/https?:\/\/[^\s"'<>]+/gi, '[registry]')
518
+ .replace(/(\b[\w-]*(?:token|password|secret|api[_-]?key|credential|authorization|_auth)[\w-]*["']?\s*[:=]\s*)(?:(?:Bearer|Basic)\s+)?(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1[redacted]')
519
+ .replace(/\b(?:Bearer|Basic)\s+[^\s,;]+/gi, '[redacted]')
520
+ .replace(/\bnpm_[a-z0-9]+\b/gi, '[redacted]')
521
+ .replace(/\s+/g, ' ').trim().slice(0, 1_000);
522
+ const code = npmFailureCode(error);
523
+ return `Package ${phase} failed${code ? ` (${code})` : ''}${detail ? `: ${detail}` : ''}`;
524
+ }
525
+ /** No target version lookup: callers validate the cached target; ETARGET retries refresh dependency metadata. */
496
526
  export async function installExactPackageVersion(pkg, target, registry, resolveInstalled, npmConfig, beforeInstall) {
497
527
  if (![MAIN_PACKAGE_NAME, WEB_PACKAGE_NAME].includes(pkg)
498
528
  || !isPackageVersion(target) || normalizeVersionRegistry(registry) !== registry) {
@@ -511,20 +541,25 @@ export async function installExactPackageVersion(pkg, target, registry, resolveI
511
541
  return;
512
542
  }
513
543
  await beforeInstall?.();
544
+ let preferOnline = false;
514
545
  for (let attempt = 0; attempt < 2; attempt++) {
546
+ let phase = 'installation';
515
547
  try {
516
- await npmInstallGlobal(`${pkg}@${target}`, { registry, preferOffline: true, npmConfig });
548
+ await npmInstallGlobal(`${pkg}@${target}`, {
549
+ registry, preferOffline: !preferOnline, preferOnline, npmConfig,
550
+ });
551
+ phase = 'version verification';
517
552
  const actual = resolveInstalled()?.version;
518
553
  if (!actual || !isPackageVersion(actual) || comparePackageVersions(actual, target) < 0) {
519
- throw new Error('Installed version did not reach the cached target');
554
+ throw new Error(`Installed ${pkg} version is ${actual ?? 'unavailable'} (target ${target})`);
520
555
  }
521
556
  result = { status: 'upgraded', from, to: actual };
522
557
  return;
523
558
  }
524
- catch {
525
- // npm stderr can contain private registry credentials. Persist a safe
526
- // diagnostic; npm's existing permission/transport behavior is retained.
527
- result = { status: 'failed', from, to: target, error: 'Exact package installation or version verification failed' };
559
+ catch (error) {
560
+ if (phase === 'installation' && npmFailureCode(error) === 'ETARGET')
561
+ preferOnline = true;
562
+ result = { status: 'failed', from, to: target, error: formatPackageInstallFailure(error, phase) };
528
563
  }
529
564
  }
530
565
  });
@@ -1,7 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import { DataRootError } from '../core/command/team-workspace-store.js';
3
3
  import { TaskActivityStore, onTaskActivityMutation, taskActivityTitle } from '../core/task/task-activity-store.js';
4
- import { authorizeOutput, currentOutputOwner } from '../outputs/service.js';
4
+ import { authorizeOutput, currentOutputOwner } from '../outputs/authorization.js';
5
5
  import { WORKBENCH_EVENT, WORKBENCH_MODULES, isWorkbenchType } from './protocol.js';
6
6
  let runtimeProvider;
7
7
  const runtimeListeners = new Set();
@@ -81,6 +81,7 @@ Windows 上 Codex 托管任务出现 `helper_sandbox_lock_failed`、`SetNamedSec
81
81
  | `ec config` | 配置体系底层入口(读写/快照/回滚) | 看配置/改配置/查字段/查schema/校验/快照/回滚/历史/启动记录 | `config.md` |
82
82
  | `ec role` | Owner 查询/设置角色用量配额,关系角色提升申请与审批 | 角色配额/角色限额/关闭限额/恢复继承/取消配额/usageLimits/申请角色/审批角色 | `role.md` |
83
83
  | `ec stats` | Token 用量与费用统计 | 用量/费用/统计/预算/token/cost | `stats.md` |
84
+ | `ec quota` | 查询 Agent 与对端的生效限额、已用及剩余(status) | 自身限额/对端限额/剩余额度/是否超限 | `quota.md` |
84
85
  | `ec trigger` | 定时与事件触发器管理(创建用 `create`,`set` 为兼容别名) | 触发器/定时任务/cron/提醒/定时检查/自动执行/巡检/禁用 trigger/删除 trigger | `trigger.md` |
85
86
  | `ec trigger event` | EventBus 事件目录 | 事件触发/事件目录/EventBus/source.type=event/filter.match | `event.md` |
86
87
  | `ec events` | AUN 事件中心:注册/发布/订阅事件,事件到达跑脚本 | 事件中心/注册事件/发布事件/订阅事件/事件包/pack.json/events-config.json/scripts/AUN 事件 | `event-center.md` |
@@ -105,6 +106,7 @@ Windows 上 Codex 托管任务出现 `helper_sandbox_lock_failed`、`SetNamedSec
105
106
  | [`tool-authorization.md`](tool-authorization.md) | 工具执行、人工审批与 EC 授权图解;trusted fullaccess 与 DaemonOwner 对照;Owner 凭证及模型审批预留 | 工具审批/授权流程/权限图解/Owner+bypass/fullaccess/DaemonOwner/决策模型审批 |
106
107
  | `menu-protocol.md` | Menu Protocol 规范(消息类型 / protected_headers / name→operation 映射 / 鉴权机制) | menu 消息格式/为什么被拒/服务端怎么读 menu/auth_method/凭证怎么带/Evol App 怎么调 daemon |
107
108
  | `menu-exec-schema-commands.md` | 通过 `menu.action name=cli action=exec` 取配置 schema 的命令手册 | 配置 schema 版本/schema 内容/远程取 schema |
109
+ | [`aid.md`](aid.md#daemonowner-远程单命令) | DaemonOwner 在 Control AID 的 E2EE 私聊以 /exec on 进入终端后直接发命令,/stop 取消,/exec off 退出,进出使用 notice;最长 30 分钟、空闲 6 分钟 | 虚拟SSH/remote-shell/daemon执行命令/exec on/exec stop/终端状态 |
108
110
  | `ec-capabilities.md` | EC Skill 系统机制概要(三级目录、开关覆盖链、渐进式披露、编写规范、权限) | 技能系统怎么工作/技能放在哪里/SKILL.md 怎么写/技能为什么没生效/description 怎么写 |
109
111
  | `$KITS_DOCS/aun/ABILITY_CALLING.md` | AUN Ability 的发现、原始 payload、请求关联与结果查询 | 能力调用/Ability/protocol/discover/ability_path/request_id/call_id/超时查询 |
110
112
 
@@ -246,3 +246,28 @@ ec aid delete <aid>
246
246
  - `--aun-path <path>` — 指定 AUN keystore 根;未传时可由 `AUN_HOME` 提供
247
247
  - `aid delete --orphan|--no-cert|--unrecoverable` 默认 dry-run,`--yes` 才执行删除
248
248
  - `--help` / `-h` — 各子命令均支持
249
+
250
+ ## DaemonOwner 远程单命令
251
+
252
+ 在 daemon Control AID 与其当前协议 Owner AID 的 **E2EE 私聊**中发送文本即可使用,无需客户端新增页面或手动填写 token、窗口 ID。
253
+
254
+ Owner 发送未加密的 /exec 时,daemon 会核验协议身份及发送设备,以加密消息回复 `E2EE_REQUIRED` 并提示开启端到端加密;该请求不执行,也不改变窗口状态。
255
+
256
+ | 指令 | 作用 |
257
+ |---|---|
258
+ | `/exec on` | 进入终端操作状态,以 notice 提示;最长 30 分钟,空闲 6 分钟自动退出 |
259
+ | `uname -a` | 进入后直接发送单条命令,返回 stdout、stderr 和退出码 |
260
+ | `/exec off` | 退出终端操作状态,以 notice 提示,并取消正在执行和排队的命令 |
261
+ | `/exec` | 查看窗口、剩余时间和当前执行状态;不自动进入终端、不续期 |
262
+ | `/stop` 或 `/exec stop` | 取消正在执行和排队的命令,保留终端操作状态 |
263
+ | `/exec uname -a` | 兼容带前缀执行单条命令 |
264
+
265
+ 进入 notice 送达后,当前 Owner、设备和话题的原始 text 按命令处理;其他设备或话题需各自开启。退出后普通文字恢复 daemon 原有处理。直接发送的 on/off/status/stop 是程序名,控制指令保留斜杠;/stop 仅在 daemon 控制会话中作为取消别名,未开启时返回已关闭。
266
+
267
+ 同一终端的命令按顺序执行;重复 /exec on 和 /exec 不续期,也不重复提示进入。空闲从上条实际命令完成计时,运行中仍受 30 分钟绝对期限约束。手动关闭、空闲及到期退出发送 notice;断线或 Owner 失效时立即关闭,无法投递的状态 notice 不排队到重连后重放。daemon 重启后需重新 on,开启状态不写入配置。
268
+
269
+ 只接收原始 text。引用、合并消息、群消息和普通 Agent AID 不提供此入口;Agent Owner、fullaccess、Menu token 和诊断 remote_access_token 都不能替代 daemon 当前协议 Owner 身份。
270
+
271
+ 按 daemon 运行账号的系统权限执行单个程序,不提供交互 stdin、PTY 或跨命令保留的 cd/环境变量状态。使用程序自身的目录选项或绝对路径;不支持 `&&`、管道、重定向、后台符及 shell 展开,EvolCore 既有危险命令命中后直接拒绝。Windows 的 shell 内建命令及不能直接启动的 .cmd/.bat 会报告启动错误。
272
+
273
+ stdout/stderr 各最多捕获 8 MiB,越限终止并报告 OUTPUT_LIMIT;长结果按 UTF-8 分片,附原消息 ID 和序号,最后返回退出状态。同一消息的重发不会重复执行;跨 daemon 重启不保证执行去重,重启后窗口默认关闭。
@@ -183,7 +183,10 @@ ConfigManager 只合并上述物理层并返回物理来源。角色策略不进
183
183
 
184
184
  - `provider` 指 `~/.evolcore/providers.json` 里的服务商 id。网关连接信息(`baseUrl`、`apiKey`、
185
185
  `headers`、`queryParams`)只存在于 providers.json,Agent 级不再承载,也不做 `${VAR}` 展开。
186
- - `fallback` 降级链每一级都必须同时给出 `provider`、`model`、`effort`:降级可能换用不同服务商的不同模型。
186
+ - `fallback` 降级链最多 3 项,每一级都必须同时给出 `provider`、`model`、`effort`:降级可能换用不同服务商的不同模型。
187
+ Agent 级用 `ec config set baseagents.<baseagent>.fallback '<JSON 数组>' --self <aid>` 写入,空数组表示清除;
188
+ defaults 级仍只允许手工编辑 `agents/defaults.json`。写入成功不代表一定降级:候选模型不在目录、
189
+ 不在角色允许范围、或 `effort` 不在该模型声明的强度列表里都会被过滤,`ec model check` 会打印被打回的条目。
187
190
  - relation 层不承载 `baseagents`、`active_baseagent`、`model`、`models` 或 `Services`;这些字段在关系层会被剥离。
188
191
  - `Services.<用途>`(如 `Services.decision`)也在 defaults 提供全局默认,Agent 可逐字段覆盖。
189
192
  - Agent 和 defaults 均未设置模型时,Claude/Codex 回落到本机 CLI 配置;再缺省时使用 runner 的内置默认模型。推理强度按同一层级逐字段回落。
@@ -6,7 +6,7 @@
6
6
  触发词:联系人/通讯录/名录/找人的 AID/这个人是谁/内外联系人/拉黑名单/记备注。
7
7
 
8
8
  它不是联系人管理入口:谁能联系这个 Agent、名录里有哪些人,由 Owner 在 Evol App 里决定,
9
- Agent 侧可以查询或向 Owner 发送入录申请,不能直接增删名录条目。
9
+ Agent 侧可以查询或向目标发送好友邀请,不能直接增删 Owner 名录条目。普通消息出站不需要先入录。
10
10
 
11
11
  ## 命令面
12
12
 
@@ -34,20 +34,19 @@ ec directory request <target-aid> [--note <申请说明>] [--format json]
34
34
 
35
35
  ## 申请加入 Owner 名录
36
36
 
37
- 当发送因目标不在本端 Owner 名录中被拒绝时,执行:
37
+ 需要显式申请与目标建立联系人关系时,执行:
38
38
 
39
39
  ```bash
40
40
  ec directory request evolapplwj.agentid.cn --note "三藏希望了解项目接下来的工作重点"
41
41
  ```
42
42
 
43
- `request` 自动确定本端 Agent 与其 Owner,向 Owner 发送一条**加密加好友申请**(app-v1
44
- `friend.invite.v1`),列明本端 Agent、目标 AID 和申请说明(最多 500 字符)。Owner 需要在
45
- Evol App 中处理该申请,并把目标加入联系人名录、允许本 Agent 访问对应的联系人范围。
46
- 申请不会给目标发送消息,也不会修改本地名录、准入开关或自动重发原消息。
43
+ `request` 自动确定本端 Agent,向目标 AID 发送加密 `friend.invite.v1`,申请说明最多 500 字符。
44
+ 目标根据其准入策略决定,或转交它的 Owner 审批。邀请不修改本地名录或自动重发此前的出站消息。
47
45
 
48
46
  成功返回 `action: request`、`targetAid`、`status: sent` 和 `message_id`,
49
- 仅表示申请消息已发送,**不表示 Owner 已同意或目标已入录**。Owner 处理后执行
50
- `ec directory refresh`,同步名录后再重试原发送命令。
47
+ 仅表示邀请已发送,不表示审批完成。普通消息出站可直接发送。
48
+ 本端收到未准入的纯文本时,Core 收存原文并向自己的 Owner 申请;永久许可在名录成功应用后、
49
+ 临时许可在落盘后自动恢复原消息,保留原发件人和话题。待收有效期 3 天,旧版只有摘要的隔离记录不能补恢复。
51
50
 
52
51
  ## list — 列举与关键词过滤
53
52
 
@@ -300,7 +299,7 @@ PA Team 里,该组为空、不渲染;Owner 手动把某人移出团队清单
300
299
  |---|---|---|
301
300
  | `list` / `info` / `refresh` / `blocked`(含旧名 `find` / `show`) | `ec.directory.query` | 只读 |
302
301
  | `block` / `unblock` | `ec.directory.block` | 仅修改当前 Agent 的本地黑名单;按 Agent Owner + bypass 授权 |
303
- | `request` | `ec.directory.request` | 向当前 Agent 的 Owner 发送加密申请;按 Agent Owner + bypass 授权 |
302
+ | `request` | `ec.directory.request` | 向目标发送加密好友邀请;按 Agent Owner + bypass 授权 |
304
303
 
305
304
  托管会话里 CLI 不直接读盘,携带 task delegation token 调 daemon `directory.op`;
306
305
  缺 token、token 伪造或跨会话时失败关闭。显式 `--self` 必须等于当前任务所属 Agent。
@@ -269,3 +269,12 @@ ec msg history <self-aid> <target-aid> \
269
269
  - 主动发起(没有入站消息上下文)默认明文;只有显式 `--encrypt yes`,或 `daemon.json` 设置 `aun.defaultEncrypt: true`,才加密发送
270
270
 
271
271
  `ecmsg send` 默认等价于 `--encrypt auto`:被对端消息触发时沿用该消息的加密状态,主动发起时明文。
272
+
273
+ ## 联系人准入与待收恢复
274
+
275
+ AUN 普通消息出站无需联系人审批,不因目标未入录、联系人黑名单、范围排除或名录不可用
276
+ 转成 Owner 申请;调用权限、资源访问、加密和传输规则仍生效。
277
+
278
+ 入站继续执行联系人准入。可申请的纯文本先保存原文,Owner 永久授权在本地名录成功应用后、
279
+ 临时许可在落盘后自动恢复原消息。恢复保留原发件人、话题与消息 ID,
280
+ 持久入队后再由模型按正常队列执行;3 天待收期、30 分钟临时许可均不因重试续期。
@@ -131,7 +131,7 @@ Provider 不再创建独立的长期迁移备份,版本查看、恢复和保
131
131
 
132
132
  apiKey 可用共享 Provider schema 支持的环境变量引用;真实凭据应只保存在受权限保护的 JSON 文件中,不放入命令行历史。
133
133
 
134
- Provider identity 取完整规范化 hostname:小写、IDN 转 Punycode、去掉末尾点;裸注册域名补为 `www.`,已有子域名保持不变。静态 `baseUrl` 自动推导 domain;若 `baseUrl` 是环境变量引用,必须显式填写 domain,且运行时地址必须匹配。ID 为完整 SHA-256 摘要转整数后对 100000000 取模并补齐八位。哈希碰撞会拒绝保存,不会改用环境相关的替代 ID。迁移旧 `provider-N` 时会保留 aliases 供旧引用和冻结初始化计划兼容。
134
+ Provider identity 取完整规范化 hostname:小写、IDN 转 Punycode、去掉末尾点;裸注册域名补为 `www.`,已有子域名保持不变。domain 由程序获取并保存,ECWeb 不提供独立输入或展示字段,JSON 预览也隐藏该内部字段。静态 `baseUrl` 自动提取 hostname;管理入口收到未带 domain 的环境变量地址时,从宿主进程环境解析 URL 并提取,配置中的 baseUrl 仍保留变量引用。变量缺失、为空或解析结果不是有效 HTTP(S) URL 时拒绝新建,已有 domain 的配置读取不依赖变量是否存在。配置文件仍可显式声明 domain,运行时实际地址必须与保存的身份匹配。ID 为完整 SHA-256 摘要转整数后对 100000000 取模并补齐八位。哈希碰撞会拒绝保存,不会改用环境相关的替代 ID。迁移旧 `provider-N` 时会保留 aliases 供旧引用和冻结初始化计划兼容。
135
135
 
136
136
  hostname 同时支持 IPv4、IPv6 和 `localhost`,不补 `www.`。IPv6 统一为 URL hostname 使用的压缩、带方括号形式(如 `[::1]`);显式 domain 也接受不带方括号的 IPv6。端口仍属于连接地址,不参与身份计算;同一主机的不同协议或端口不能合并。DNS 身份与已有固定 ID 的生成规则保持不变。
137
137
 
@@ -0,0 +1,54 @@
1
+ # ec quota — 查询生效限额与余额
2
+
3
+ 触发词:自身限额、对端限额、剩余额度、额度用了多少、是否超限。
4
+
5
+ `ec quota status` 查询具体使用者的实际余额;`ec role quota show <role>` 查看角色额度规则及
6
+ 继承结果,`set/disable/inherit` 管理这些规则。两组命令共用现有预算计算和角色规则,分别提供
7
+ 使用状态查询与策略管理入口。
8
+
9
+ ```bash
10
+ # 托管会话:默认当前 Agent 与当前对端
11
+ ec quota status
12
+ ec quota status --format json
13
+
14
+ # Owner/Admin 可指定当前 Agent 的其他私聊关系
15
+ ec quota status --peer alice.agentid.cn --format json
16
+ ec quota status --peer 'feishu#ou_xxx' --format json
17
+
18
+ # 宿主终端:必须指定本机 Agent;不指定对端时只返回 Agent 预算
19
+ ec quota status --self bot.agentid.cn --format json
20
+ ec quota status --self bot.agentid.cn --peer alice.agentid.cn --format json
21
+ ```
22
+
23
+ 这是只读查询,通过 daemon 验证当前任务委托或宿主 control token。托管会话的 Owner/Admin 可查
24
+ 当前 Agent 的其他对端;普通对端只能查当前关系,Agent 总用量和一般预算明细返回 `null`。
25
+ 角色自定义的命令限制仍生效。跨 Agent 查询仅宿主终端或可信 fullaccess 任务可用;显式指定
26
+ 另一个 Agent 时不沿用原 Agent 的当前对端,需同时指定 `--peer` 才查询该 Agent 的关系额度。
27
+
28
+ 返回字段:
29
+
30
+ | 字段 | 内容 |
31
+ | --- | --- |
32
+ | `selfAid` | 查询的本机 Agent |
33
+ | `agent.visible` | 是否有权读取 Agent 总预算用量 |
34
+ | `agent.budget` | 日/月预算上限、已用、剩余、预警与硬限制状态 |
35
+ | `relation` | 无对端时为 `null`,否则包含对端、角色来源及限额 |
36
+ | `relation.budget` | 对该关系生效的一般预算,与运行时拦截使用同一计算函数 |
37
+ | `relation.budgetUsageScope` | 当前一般预算用量按 `agent` 汇总,不能当作对端独立用量 |
38
+ | `relation.roleQuota` | 角色额度的上限、已用、剩余、币种、计费口径、重置周期、范围及是否阻止执行 |
39
+ | `hard_blocked` | 任一生效预算或角色额度已阻止执行 |
40
+
41
+ 一般预算使用 USD;角色额度使用自身的 `currency`,`cost_basis` 为 `gateway` 或 `official`。
42
+ 两者分别返回,不跨币种相加。数值 `-1` 表示不限额。角色 `scope=subject` 表示每个对端独立
43
+ 计算,`scope=role` 表示当前 Agent 内同角色共享额度。周期沿用 daemon 本地时区。
44
+ `owner/admin` 的角色额度返回 `enabled=false, reason=management_role`,一般预算仍独立生效。
45
+ 关闭额度或无额度配置会返回对应 `reason`,不会把没有生效的限制误报为有限余额。
46
+
47
+ 群聊默认按当前发言人及其在本群生效的关系角色计算额度。不能只指定另一个群的 AID 推断
48
+ 发言人身份;要查询群内额度,应在该群的当前会话执行命令。
49
+
50
+ `--format json` 在失败时返回 `{ ok: false, code, error }`,退出码非零。
51
+ 参数只支持 `status`、`--self`、`--peer`、`--format text|json` 和帮助;未知参数、重复参数、
52
+ 缺少参数值均拒绝。修改角色额度继续使用 `ec role quota set|disable|inherit`。
53
+
54
+ 新增命令的 daemon IPC 接口需要宿主重启后生效;仅 `ec agent reload` 不会重载源码。