evolcore 0.0.47 → 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 (266) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +143 -40
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +34 -17
  8. package/dist/agents/codex-runner.js +36 -17
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/msg/p2p.js +2 -1
  14. package/dist/aun/service-proxy.js +4 -2
  15. package/dist/build-identity.json +1 -0
  16. package/dist/channels/aun.js +722 -295
  17. package/dist/channels/daemon.js +9 -25
  18. package/dist/cli/aun-commands.js +86 -51
  19. package/dist/cli/code-stats.js +19 -8
  20. package/dist/cli/command-log.js +1 -1
  21. package/dist/cli/daemon-commands.js +44 -43
  22. package/dist/cli/directory.js +13 -2
  23. package/dist/cli/ecmsg-gateway.js +5 -2
  24. package/dist/cli/index.js +9 -9
  25. package/dist/cli/init-channel.js +4 -6
  26. package/dist/cli/init.js +72 -50
  27. package/dist/cli/invoke-command.js +1 -1
  28. package/dist/cli/managed-command-guard.js +2 -0
  29. package/dist/cli/model.js +20 -5
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/quota.js +89 -0
  32. package/dist/cli/role.js +62 -17
  33. package/dist/cli/services-command.js +1 -0
  34. package/dist/cli/stats.js +3 -3
  35. package/dist/cli/team-workspace-command.js +56 -2
  36. package/dist/cli/thread-command.js +16 -51
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-field-policy.js +71 -1
  40. package/dist/config/config-manager.js +13 -7
  41. package/dist/config/daemon-services.js +30 -3
  42. package/dist/config/gateway-config.js +2 -2
  43. package/dist/config/invoke-ipc-service.js +6 -4
  44. package/dist/config/peer-bind-code.js +3 -4
  45. package/dist/config/peer-book-store.js +62 -229
  46. package/dist/config/peer-book.js +26 -27
  47. package/dist/config/peer-role-resolver.js +16 -1
  48. package/dist/config/provider-identity-migration.js +4 -1
  49. package/dist/config/provider-ipc-service.js +56 -11
  50. package/dist/config/provider-menu-request.js +24 -5
  51. package/dist/config/provider-templates.js +127 -0
  52. package/dist/config/providers-config.js +67 -12
  53. package/dist/config/providers-management.js +477 -51
  54. package/dist/config/resolved-config-op.js +3 -2
  55. package/dist/config/role-command-service.js +248 -1
  56. package/dist/config/schema-migration.js +105 -4
  57. package/dist/core/agent-application-service.js +6 -1
  58. package/dist/core/agent-runtime.js +4 -0
  59. package/dist/core/auth/agent-delegation.js +2 -1
  60. package/dist/core/auth/auth-gateway.js +2 -1
  61. package/dist/core/auth/delegation-authorization.js +36 -26
  62. package/dist/core/auth/operation-authorizer.js +25 -0
  63. package/dist/core/auth/operation-catalog.js +37 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/cli-intent-parser.js +13 -0
  68. package/dist/core/command/command-handler.js +126 -87
  69. package/dist/core/command/menu-catalog.js +1 -0
  70. package/dist/core/command/menu-handler.js +67 -150
  71. package/dist/core/command/menu-protocol.js +31 -1
  72. package/dist/core/command/provider-menu.js +13 -3
  73. package/dist/core/command/remote-shell.js +565 -0
  74. package/dist/core/command/role-menu.js +47 -23
  75. package/dist/core/command/slash-handler.js +26 -43
  76. package/dist/core/command/team-workspace-items.js +81 -12
  77. package/dist/core/command/team-workspace-team.js +9 -71
  78. package/dist/core/command/topic-slash.js +9 -30
  79. package/dist/core/daemon-bootstrap.js +8 -1
  80. package/dist/core/daemon-control.js +64 -8
  81. package/dist/core/daemon-lifecycle.js +16 -2
  82. package/dist/core/evolagent-registry.js +20 -3
  83. package/dist/core/file-integrity/store.js +2 -0
  84. package/dist/core/handoff/runtime.js +37 -1
  85. package/dist/core/inference/text-inference.js +3 -1
  86. package/dist/core/initialization/service.js +11 -6
  87. package/dist/core/interaction-router.js +3 -0
  88. package/dist/core/invoke/executors/text.js +72 -19
  89. package/dist/core/ipc-registration.js +3 -1
  90. package/dist/core/message/aun-ipc-sender.js +279 -107
  91. package/dist/core/message/contact-admission.js +91 -6
  92. package/dist/core/message/contact-pending-inbound.js +113 -0
  93. package/dist/core/message/contact-thread-approval.js +212 -0
  94. package/dist/core/message/im-renderer.js +41 -2
  95. package/dist/core/message/message-admission.js +5 -39
  96. package/dist/core/message/message-bridge.js +140 -370
  97. package/dist/core/message/message-log.js +29 -0
  98. package/dist/core/message/message-queue.js +119 -15
  99. package/dist/core/message/message-utils.js +8 -0
  100. package/dist/core/message/response-engine.js +580 -134
  101. package/dist/core/message/send-routing.js +5 -1
  102. package/dist/core/model/catalog-service.js +31 -11
  103. package/dist/core/model/config-scope.js +6 -14
  104. package/dist/core/model/model-capabilities.js +22 -4
  105. package/dist/core/model/model-catalog.js +1 -0
  106. package/dist/core/model/model-diagnostics.js +19 -0
  107. package/dist/core/model/model-fallback.js +13 -2
  108. package/dist/core/ownership/owner-resolver.js +328 -50
  109. package/dist/core/pack-auth.js +3 -0
  110. package/dist/core/pack-install.js +1 -1
  111. package/dist/core/permission/ec-command-parser.js +106 -19
  112. package/dist/core/permission/protected-paths.js +6 -6
  113. package/dist/core/permission/services-path-acl.js +451 -0
  114. package/dist/core/permission/tool-policy.js +5 -1
  115. package/dist/core/relation/peer-identity.js +36 -1
  116. package/dist/core/relation/same-owner-proof.js +81 -112
  117. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  118. package/dist/core/session/session-file-health.js +13 -7
  119. package/dist/core/session/session-fs-store.js +91 -35
  120. package/dist/core/session/session-manager.js +68 -24
  121. package/dist/core/session/session-mapper.js +14 -34
  122. package/dist/core/session/session-transcript.js +5 -1
  123. package/dist/core/task/task-activity-store.js +84 -0
  124. package/dist/core/task/task-recovery-service.js +13 -0
  125. package/dist/core/thread/command-parser.js +7 -12
  126. package/dist/core/thread/thread-context-storage.js +3 -2
  127. package/dist/core/thread/thread-operation.js +2 -13
  128. package/dist/core/thread/thread-service.js +15 -46
  129. package/dist/core/thread/topic-id.js +15 -0
  130. package/dist/directory/owner-directory-admission.js +12 -9
  131. package/dist/directory/owner-directory-cache.js +64 -28
  132. package/dist/directory/owner-directory-markdown.js +14 -2
  133. package/dist/directory/owner-directory-policy.js +5 -30
  134. package/dist/directory/owner-directory-query-operation.js +29 -3
  135. package/dist/directory/owner-directory-remarks.js +11 -3
  136. package/dist/directory/owner-directory-request-operation.js +5 -2
  137. package/dist/eck/kit-renderer.js +1 -1
  138. package/dist/eck/message-renderer.js +112 -29
  139. package/dist/ecweb/basic-settings-service.js +3 -1
  140. package/dist/ecweb/message-context-service.js +1 -1
  141. package/dist/ecweb/pairing.js +4 -3
  142. package/dist/ecweb/providers-service.js +26 -1
  143. package/dist/ecweb/runtime/lifecycle.js +18 -8
  144. package/dist/ecweb/runtime/proxy-access.js +74 -0
  145. package/dist/ecweb/runtime/supervisor.js +36 -6
  146. package/dist/event-center/center-config.js +9 -5
  147. package/dist/event-center/dispatcher.js +10 -1
  148. package/dist/event-center/ipc-operation.js +19 -0
  149. package/dist/event-center/registry.js +29 -3
  150. package/dist/event-center/runtime.js +106 -11
  151. package/dist/event-center/script-runner.js +5 -5
  152. package/dist/index.js +96 -59
  153. package/dist/ipc.js +38 -3
  154. package/dist/outputs/authorization.js +16 -0
  155. package/dist/outputs/cards.js +336 -0
  156. package/dist/outputs/events.js +63 -0
  157. package/dist/outputs/protocol.js +103 -0
  158. package/dist/outputs/service.js +266 -0
  159. package/dist/paths.js +3 -0
  160. package/dist/proxy/manager.js +43 -13
  161. package/dist/services/index.js +114 -5
  162. package/dist/services/ipc-operation.js +88 -15
  163. package/dist/services/pack-manager.js +13 -1
  164. package/dist/services/router.js +21 -6
  165. package/dist/services/script-runner.js +5 -4
  166. package/dist/services/service-payload.js +13 -7
  167. package/dist/services/validation.js +1 -1
  168. package/dist/stats/budget.js +2 -2
  169. package/dist/stats/db.js +19 -0
  170. package/dist/stats/index.js +1 -1
  171. package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
  172. package/dist/stats/normalizer.js +2 -0
  173. package/dist/stats/query.js +35 -27
  174. package/dist/stats/quota-query.js +95 -0
  175. package/dist/stats/role-budget.js +5 -2
  176. package/dist/stats/writer.js +10 -6
  177. package/dist/trigger/audit.js +7 -0
  178. package/dist/trigger/authorization.js +105 -11
  179. package/dist/trigger/feedback.js +10 -0
  180. package/dist/trigger/history.js +37 -11
  181. package/dist/trigger/ipc-service.js +12 -1
  182. package/dist/trigger/manager.js +1 -0
  183. package/dist/trigger/scheduler.js +7 -5
  184. package/dist/trigger/script-executor.js +2 -1
  185. package/dist/trigger/script-sandbox.js +21 -3
  186. package/dist/trigger/validation.js +22 -0
  187. package/dist/utils/atomic-write.js +22 -8
  188. package/dist/utils/cross-platform.js +73 -26
  189. package/dist/utils/error-dict.json +94 -4
  190. package/dist/utils/error-utils.js +27 -4
  191. package/dist/utils/evolcore-version.js +36 -65
  192. package/dist/utils/host-info.js +100 -1
  193. package/dist/utils/msg-diag.js +1 -0
  194. package/dist/utils/npm-ops.js +43 -8
  195. package/dist/utils/process-introspect.js +12 -7
  196. package/dist/utils/process-tree.js +50 -2
  197. package/dist/utils/windows-shell-trust.js +2 -0
  198. package/dist/workbench/protocol.js +80 -0
  199. package/dist/workbench/service.js +359 -0
  200. package/ecagent/dist/types.d.ts +6 -2
  201. package/kits/docs/context-assembly.md +1 -1
  202. package/kits/docs/evolcore/INDEX.md +4 -2
  203. package/kits/docs/evolcore/aid.md +25 -0
  204. package/kits/docs/evolcore/config.md +16 -1
  205. package/kits/docs/evolcore/directory.md +30 -12
  206. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  207. package/kits/docs/evolcore/model.md +10 -0
  208. package/kits/docs/evolcore/msg.md +9 -0
  209. package/kits/docs/evolcore/peer.md +19 -65
  210. package/kits/docs/evolcore/provider.md +124 -4
  211. package/kits/docs/evolcore/quota.md +54 -0
  212. package/kits/docs/evolcore/role.md +83 -0
  213. package/kits/docs/evolcore/services.md +6 -6
  214. package/kits/docs/evolcore/stats.md +2 -0
  215. package/kits/docs/evolcore/team-workspace.md +1 -1
  216. package/kits/docs/evolcore/thread-chain.md +14 -15
  217. package/kits/docs/evolcore/tool-authorization.md +5 -0
  218. package/kits/docs/evolcore/trigger.md +12 -0
  219. package/kits/eck_message_manifest.json +12 -0
  220. package/kits/provider-templates.json +1213 -0
  221. package/kits/rules/04-relation.md +3 -3
  222. package/kits/schemas/_meta.json +14 -2
  223. package/kits/schemas/agent-config.schema.20.json +24 -0
  224. package/kits/schemas/contact-book.schema.4.json +52 -0
  225. package/kits/schemas/providers.schema.3.json +200 -0
  226. package/kits/skills/.switches.json +8 -0
  227. package/kits/skills/ability/references/calling.md +1 -1
  228. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  229. package/kits/skills/ec-group/SKILL.md +2 -2
  230. package/kits/skills/ec-identity/SKILL.md +19 -72
  231. package/kits/skills/ec-provider/SKILL.md +270 -0
  232. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  233. package/kits/skills/ec-trigger/SKILL.md +1 -1
  234. package/kits/skills/thread-ops/SKILL.md +34 -21
  235. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  236. package/kits/templates/message-fragments/group-batch.md +1 -1
  237. package/kits/templates/message-fragments/inject-default.md +1 -1
  238. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  239. package/kits/templates/message-fragments/item-group.md +1 -1
  240. package/kits/templates/message-fragments/item-private.md +1 -1
  241. package/kits/templates/message-fragments/thread-context.md +1 -1
  242. package/kits/templates/message-fragments/trigger-session.md +1 -1
  243. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  244. package/kits/templates/roles/admin.json +2 -19
  245. package/kits/templates/roles/member.json +0 -3
  246. package/kits/templates/roles/visitor.json +1 -0
  247. package/kits/templates/system-fragments/baseagent.md +6 -0
  248. package/kits/templates/system-fragments/commands.md +4 -3
  249. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  250. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  251. package/kits/templates/system-fragments/relation.md +1 -1
  252. package/kits/templates/system-fragments/thread.md +7 -5
  253. package/kits/templates/system-fragments/venue.md +11 -0
  254. package/package.json +6 -4
  255. package/scripts/agent-template/inspect.mjs +50 -11
  256. package/scripts/agent-template/shared/common.mjs +11 -6
  257. package/scripts/agent-template/shared/team-schema.json +6 -4
  258. package/scripts/agent-template/shared/template-contract.mjs +62 -11
  259. package/scripts/agent-template/shared/template-package.mjs +189 -21
  260. package/scripts/agent-template/shared/template-runtime.mjs +54 -6
  261. package/scripts/agent-template/shared/template.mjs +2 -2
  262. package/scripts/agent-template/team-pack.mjs +52 -14
  263. package/dist/cli/peer.js +0 -127
  264. package/dist/config/peer-operation-service.js +0 -132
  265. package/dist/config/peer-request-service.js +0 -532
  266. package/dist/core/command/connect-menu.js +0 -624
@@ -1,12 +1,23 @@
1
1
  import fs from 'fs';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { isValidAid } from '../aun/aid/validation.js';
3
4
  import { agentConfig } from '../paths.js';
5
+ import { isManagementRole } from './builtin-roles.js';
6
+ import { isRoleName } from './role-store.js';
7
+ import { roleMenuQuery, roleMenuUpdate } from '../core/command/role-menu.js';
8
+ import { getRoleBudgetStatus, resolveRoleUsageLimits } from '../stats/role-budget.js';
9
+ import { resolveRoot } from '../paths.js';
10
+ import { authorizeFreshOperation, buildAuthSubject } from '../core/auth/auth-gateway.js';
11
+ import { ownerResolver, refreshOwnershipForAuthorization } from '../core/ownership/owner-resolver.js';
12
+ import { logger } from '../utils/logger.js';
4
13
  import { listRoleRequests, reviewRoleRequest, submitRoleRequest, } from './role-request-service.js';
5
14
  export function resolveRoleCommand(argv) {
6
15
  const args = argv[0] === 'role' ? argv.slice(1) : [...argv];
7
16
  const selfAid = String(argValue(args, '--self') || '').trim();
8
17
  if (!isValidAid(selfAid))
9
18
  return invalid('INVALID_SELF', '--self must be a valid Agent AID');
19
+ if (args[0] === 'quota')
20
+ return resolveQuotaCommand(args, selfAid);
10
21
  const positional = stripOptions(args);
11
22
  const [command, subcommand, ...extra] = positional;
12
23
  if (extra.length > 0)
@@ -61,10 +72,61 @@ export function resolveRoleCommand(argv) {
61
72
  }
62
73
  return invalid('UNKNOWN_COMMAND', `Unknown role command: ${positional.join(' ')}`);
63
74
  }
64
- export async function executeResolvedRoleCommand(command, actorAid, apply) {
75
+ export async function executeResolvedRoleCommand(command, actorAid, apply, context) {
65
76
  if (!fs.existsSync(agentConfig(command.selfAid))) {
66
77
  return { ok: false, code: 'AGENT_NOT_FOUND', error: `Agent does not exist: ${command.selfAid}` };
67
78
  }
79
+ if (command.kind === 'quota') {
80
+ if (!context || context.self !== command.selfAid) {
81
+ return { ok: false, code: 'PERMISSION_DENIED', error: 'Role quota operations require an authorized Agent context' };
82
+ }
83
+ const current = await roleMenuQuery(context, { self: command.selfAid, view: 'role', roleId: command.roleId });
84
+ let result = current;
85
+ if (command.action !== 'show') {
86
+ if (isManagementRole(command.roleId)) {
87
+ return { ok: false, code: 'NOT_SUPPORTED', error: 'Owner and admin are exempt from role usage limits' };
88
+ }
89
+ const updateArgs = {
90
+ self: command.selfAid,
91
+ resource: 'definition',
92
+ roleId: command.roleId,
93
+ expectedPolicyRevision: current.policyRevision,
94
+ };
95
+ if (command.action === 'inherit') {
96
+ updateArgs.remove = { usageLimits: true };
97
+ result = await roleMenuUpdate(context, updateArgs, '{}');
98
+ }
99
+ else {
100
+ const inheritedLimits = resolveRoleUsageLimits(command.roleId, command.selfAid);
101
+ const usageLimits = {
102
+ ...inheritedLimits,
103
+ ...current.definition.usageLimits,
104
+ ...command.patch,
105
+ };
106
+ if (command.patch.enabled === undefined) {
107
+ usageLimits.enabled = current.definition.usageLimits?.enabled ?? inheritedLimits?.enabled ?? false;
108
+ }
109
+ if (usageLimits.enabled === true && usageLimits.limitAmount === undefined) {
110
+ return { ok: false, code: 'INVALID_ARGUMENT', error: 'Enabling a quota requires --limit <amount|unlimited>' };
111
+ }
112
+ result = await roleMenuUpdate(context, updateArgs, JSON.stringify({ usageLimits }));
113
+ }
114
+ }
115
+ const effectiveUsageLimits = resolveRoleUsageLimits(command.roleId, command.selfAid);
116
+ return {
117
+ ok: true,
118
+ operation: 'quota',
119
+ selfAid: command.selfAid,
120
+ roleId: command.roleId,
121
+ changed: result.changed === true,
122
+ applicable: !isManagementRole(command.roleId),
123
+ enforced: !isManagementRole(command.roleId)
124
+ && effectiveUsageLimits?.enabled !== false
125
+ && typeof effectiveUsageLimits?.limitAmount === 'number',
126
+ usageLimits: result.definition.usageLimits ?? null,
127
+ effectiveUsageLimits,
128
+ };
129
+ }
68
130
  if (command.kind === 'request') {
69
131
  const submission = await submitRoleRequest({
70
132
  selfAid: command.selfAid,
@@ -124,6 +186,191 @@ export async function executeResolvedRoleCommand(command, actorAid, apply) {
124
186
  requests: listRoleRequests({ selfAid: command.selfAid, status: command.status }),
125
187
  };
126
188
  }
189
+ /** The daemon asks its authenticated Owner; the exhausted Agent never approves its own quota. */
190
+ export class RoleQuotaQuestions {
191
+ router;
192
+ pending = new Map();
193
+ constructor(router) {
194
+ this.router = router;
195
+ }
196
+ async present(input) {
197
+ const self = input.request.selfAid;
198
+ if (!self)
199
+ return false;
200
+ const budget = getRoleBudgetStatus(resolveRoot(), input.request);
201
+ if (!budget.hard_blocked)
202
+ return false;
203
+ await refreshOwnershipForAuthorization(input.daemonAid, { includeDaemon: true, allowTransient: false });
204
+ const ownerAid = ownerResolver.owner(input.daemonAid);
205
+ if (!ownerAid)
206
+ return false;
207
+ const authorize = async () => {
208
+ const subject = buildAuthSubject({ selfAid: self, actorId: ownerAid,
209
+ channel: input.transport.channelKey, channelType: 'aun', channelId: ownerAid,
210
+ chatType: 'private', fromControlChannel: true, peerType: 'human' });
211
+ const decision = await authorizeFreshOperation({ source: 'menu', subject,
212
+ intent: { operation: 'role.policy.write', scope: 'agent', source: 'menu',
213
+ args: { self, targetAgentAid: self, roleId: budget.role } } });
214
+ return decision.allow && ownerResolver.owner(input.daemonAid) === ownerAid;
215
+ };
216
+ if (!(await authorize()))
217
+ return false;
218
+ const context = { self, actorRole: 'none', actorAid: ownerAid,
219
+ isDaemonOwner: true, fromControlChannel: true, chatType: 'private' };
220
+ const policy = await roleMenuQuery(context, { self, view: 'role', roleId: budget.role });
221
+ // A quota change applies to the whole role, so one pending request covers
222
+ // all exhausted subjects of that role under this policy and reset period.
223
+ const key = JSON.stringify([self, budget.role, budget.period_start_ts, policy.policyRevision, ownerAid]);
224
+ for (const [oldKey, entry] of this.pending) {
225
+ if (entry.expiresAt <= Date.now()) {
226
+ this.pending.delete(oldKey);
227
+ await this.router.cancel(entry.id, 'expired');
228
+ }
229
+ }
230
+ const previous = this.pending.get(key);
231
+ if (previous)
232
+ return (await previous.delivery ?? false) && previous.open;
233
+ const id = `rqq-${randomUUID()}`;
234
+ const expiresAt = Date.now() + 15 * 60_000;
235
+ const entry = { id, expiresAt, open: true };
236
+ this.pending.set(key, entry);
237
+ const close = () => { entry.open = false; };
238
+ const isCurrent = async () => {
239
+ if (!entry.open || Date.now() >= expiresAt || !(await authorize()))
240
+ return false;
241
+ const current = getRoleBudgetStatus(resolveRoot(), input.request);
242
+ if (!current.hard_blocked || current.period_start_ts !== budget.period_start_ts)
243
+ return false;
244
+ const latest = await roleMenuQuery(context, { self, view: 'role', roleId: budget.role });
245
+ return entry.open && latest.policyRevision === policy.policyRevision;
246
+ };
247
+ const notice = (text) => input.transport.notice(ownerAid, text);
248
+ this.router.register(id, `role-quota:${self}`, async (action, values) => {
249
+ if (action === 'reject' || action === 'dismiss' || values?.behavior === 'dismiss') {
250
+ close();
251
+ return true;
252
+ }
253
+ if (!(await isCurrent())) {
254
+ await this.router.cancel(id, 'quota_or_owner_changed');
255
+ return false;
256
+ }
257
+ const raw = action === '_custom_input' && typeof values?.custom_text === 'string'
258
+ ? values.custom_text.trim() : '';
259
+ const amount = Number(raw);
260
+ if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/u.test(raw) || !Number.isFinite(amount)
261
+ || amount <= getRoleBudgetStatus(resolveRoot(), input.request).used_amount) {
262
+ await notice('请输入高于当前已用金额的新额度上限,币种保持不变。');
263
+ return false;
264
+ }
265
+ try {
266
+ await roleMenuUpdate(context, { self, resource: 'definition', roleId: budget.role,
267
+ expectedPolicyRevision: policy.policyRevision }, JSON.stringify({ usageLimits: {
268
+ ...resolveRoleUsageLimits(budget.role, self), limitAmount: amount,
269
+ } }));
270
+ }
271
+ catch {
272
+ await this.router.cancel(id, 'quota_changed');
273
+ await notice('额度未修改,角色配置或权限已变化,请重新申请。');
274
+ return false;
275
+ }
276
+ close();
277
+ await notice(`${self} 的 ${budget.role} 角色额度已调整为 ${budget.currency} ${amount}。请在原会话重试。`)
278
+ .catch(error => logger.warn(`[RoleQuota] Quota saved but confirmation failed: ${error instanceof Error ? error.message : String(error)}`));
279
+ return true;
280
+ }, { blocking: false, retainOnRejected: true, requireEncrypted: true,
281
+ initiatorId: ownerAid, initiatorChannelKey: input.transport.channelKey,
282
+ timeoutMs: 15 * 60_000,
283
+ onCancel: async () => { close(); await input.transport.invalidate(id); } });
284
+ try {
285
+ entry.delivery = input.transport.send(ownerAid, {
286
+ type: 'interaction', id, sessionId: `role-quota:${self}`, channelId: ownerAid,
287
+ initiatorId: ownerAid, blocking: false, sensitive: true, expiresAt,
288
+ kind: { kind: 'action', title: '申请调整角色额度', allowCustomInput: true,
289
+ body: `Agent:${self}\n角色:${budget.role}\n已用 / 上限:${budget.currency} ${budget.used_amount} / ${budget.limit_amount}`
290
+ + `\n计费对象:${budget.usage_subject_key}\n请输入新的金额上限;这会修改该角色所有关系使用的额度配置。`,
291
+ buttons: [{ key: 'reject', label: '暂不调整' }] },
292
+ }).catch(() => false);
293
+ const sent = await entry.delivery;
294
+ if (sent)
295
+ return true;
296
+ }
297
+ catch { /* Delivery failure must leave the next blocked request retryable. */ }
298
+ this.pending.delete(key);
299
+ await this.router.cancel(id, 'delivery_failed');
300
+ return false;
301
+ }
302
+ }
303
+ function resolveQuotaCommand(args, selfAid) {
304
+ const fields = new Map([
305
+ ['--enabled', 'enabled'], ['--limit', 'limitAmount'], ['--currency', 'currency'],
306
+ ['--reset', 'resetMode'], ['--cost-basis', 'costBasis'], ['--scope', 'scope'],
307
+ ]);
308
+ const options = new Map();
309
+ const positional = [];
310
+ for (let index = 0; index < args.length; index += 1) {
311
+ const token = args[index];
312
+ if (!token.startsWith('-')) {
313
+ positional.push(token);
314
+ continue;
315
+ }
316
+ if (!fields.has(token) && !['--self', '--format'].includes(token)) {
317
+ return invalid('INVALID_ARGUMENT', `Unknown quota option: ${token}`);
318
+ }
319
+ if (options.has(token))
320
+ return invalid('INVALID_ARGUMENT', `Duplicate option: ${token}`);
321
+ const value = args[++index];
322
+ if (!value || value.startsWith('--'))
323
+ return invalid('INVALID_ARGUMENT', `${token} requires a value`);
324
+ options.set(token, value);
325
+ }
326
+ const [, action, roleId, ...extra] = positional;
327
+ if (!['show', 'set', 'disable', 'inherit'].includes(action) || !isRoleName(roleId) || extra.length) {
328
+ return invalid('INVALID_ARGUMENT', 'Expected role quota show|set|disable|inherit <role-id>');
329
+ }
330
+ if (options.has('--format') && options.get('--format') !== 'json') {
331
+ return invalid('INVALID_ARGUMENT', '--format only supports json');
332
+ }
333
+ const patch = {};
334
+ for (const [flag, field] of fields) {
335
+ const value = options.get(flag);
336
+ if (value === undefined)
337
+ continue;
338
+ if (action !== 'set')
339
+ return invalid('INVALID_ARGUMENT', `${flag} is only supported by quota set`);
340
+ if (field === 'enabled') {
341
+ if (value !== 'true' && value !== 'false')
342
+ return invalid('INVALID_ARGUMENT', '--enabled must be true or false');
343
+ patch.enabled = value === 'true';
344
+ }
345
+ else if (field === 'limitAmount') {
346
+ if (value === 'unlimited')
347
+ patch.limitAmount = null;
348
+ else if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value) || !Number.isFinite(Number(value))) {
349
+ return invalid('INVALID_ARGUMENT', '--limit must be a non-negative amount or unlimited');
350
+ }
351
+ else
352
+ patch.limitAmount = Number(value);
353
+ }
354
+ else {
355
+ const choices = {
356
+ currency: ['CNY', 'USD'], resetMode: ['never', 'daily', 'weekly', 'monthly'],
357
+ costBasis: ['gateway', 'official'], scope: ['subject', 'role'],
358
+ };
359
+ if (!choices[field].includes(value))
360
+ return invalid('INVALID_ARGUMENT', `${flag} must be ${choices[field].join('|')}`);
361
+ Object.assign(patch, { [field]: value });
362
+ }
363
+ }
364
+ if (action === 'set' && !Object.keys(patch).length) {
365
+ return invalid('INVALID_ARGUMENT', 'quota set requires at least one quota option');
366
+ }
367
+ if (action === 'disable')
368
+ patch.enabled = false;
369
+ return { ok: true, command: {
370
+ kind: 'quota', action: action, selfAid, roleId, patch,
371
+ canonicalArgv: canonicalArgv(['role', ...args]),
372
+ } };
373
+ }
127
374
  function parseStatus(value) {
128
375
  return value === 'pending' || value === 'approved' || value === 'rejected' || value === 'expired'
129
376
  ? value
@@ -10,6 +10,8 @@ import { planProviderIdentityMigration, validateProviderIdentityMigrationPlan }
10
10
  import { providerIdentity } from './provider-identity.js';
11
11
  import { snapshot } from './snapshot.js';
12
12
  import { logger } from '../utils/logger.js';
13
+ import { parseContactAlias } from './peer-alias.js';
14
+ import { recoverAllPeerBookMutationsSync } from './peer-book-store.js';
13
15
  import { atomicReplaceFile } from '../utils/atomic-write.js';
14
16
  const MIGRATION_KIND = {
15
17
  'auxiliary-model-v1': 'auxiliary-model',
@@ -22,6 +24,7 @@ const MIGRATION_KIND = {
22
24
  'legacy-model-selection-v1': 'agent-only-model',
23
25
  'access-policy-v17-v1': 'agent-only-model',
24
26
  'peer-file-v1': 'agent-only-model',
27
+ 'peer-state-v4': 'agent-only-model',
25
28
  };
26
29
  const SUPPORTED_BASEAGENTS = new Set(['claude', 'codex', 'gemini', 'ecagent']);
27
30
  const BASEAGENT_ALIASES = new Map([
@@ -2076,8 +2079,8 @@ export async function ensureAccessPolicyMigrationOnStartup() {
2076
2079
  * `contact.json` 只承载本 Agent 的身份映射、displayName 与本地拉黑,和 Owner 名录副本
2077
2080
  * `contacts.json` 名字太近。v17 起改称 `peers.json`,这里把既有文件搬过去。
2078
2081
  *
2079
- * 只做搬移,不改内容;目标已存在时保留目标、把旧文件留在原地由 Owner 复核,
2080
- * 避免覆盖一份可能更完整的新文件。
2082
+ * 有身份绑定或本地拉黑时搬移;只有已退役数据时归档,不创建 peers.json。
2083
+ * 目标已存在时保留目标、把旧文件留在原地由 Owner 复核。
2081
2084
  */
2082
2085
  function planPeerFileRename(home) {
2083
2086
  const changes = [];
@@ -2103,9 +2106,25 @@ function planPeerFileRename(home) {
2103
2106
  continue;
2104
2107
  }
2105
2108
  const text = fs.readFileSync(legacy, 'utf8');
2106
- changes.push({ file: target, kind: 'agent-only-model', before: null, after: text });
2109
+ const value = JSON.parse(text);
2110
+ if (!isRecord(value) || !isRecord(value.contacts)
2111
+ || ![1, 2, 3].includes(Number(value.$schema_version))
2112
+ || !loadSchema('contact-book', Number(value.$schema_version)).validate(value)) {
2113
+ throw new Error(`Invalid legacy peer state: ${legacy}`);
2114
+ }
2115
+ const useful = Object.values(value.contacts).some(contact => isRecord(contact)
2116
+ && ((Array.isArray(contact.aliases) && contact.aliases.length > 0)
2117
+ || contact.status === 'blocked' || contact.blocked === true));
2118
+ const destination = useful ? target : `${legacy}.migrated`;
2119
+ const before = fs.existsSync(destination) ? fs.readFileSync(destination, 'utf8') : null;
2120
+ if (before !== null && before !== text) {
2121
+ throw new Error(`Legacy peer archive conflicts with existing data: ${destination}`);
2122
+ }
2123
+ if (before !== text)
2124
+ changes.push({ file: destination, kind: 'agent-only-model', before, after: text });
2107
2125
  legacyFiles.push(legacy);
2108
- details.push({ file: path.relative(home, legacy), removed: ['contact.json'], migrated: ['→peers.json'] });
2126
+ details.push({ file: path.relative(home, legacy), removed: ['contact.json'],
2127
+ migrated: [useful ? '→peers.json' : '→contact.json.migrated (no peer state needed)'] });
2109
2128
  summary.filesChanged += 1;
2110
2129
  }
2111
2130
  return { home, changes, summary, details, legacyFiles };
@@ -2165,3 +2184,85 @@ export async function ensurePeerFileRenameOnStartup() {
2165
2184
  throw new ConfigError('PEER_FILE_RENAME_MIGRATION_FAILED', `Automatic peer file rename migration failed: ${detail}`, { cause: error });
2166
2185
  }
2167
2186
  }
2187
+ /** One-time retirement of contact membership, display names and management projections. */
2188
+ export function runPeerStateMigration(options = {}) {
2189
+ const id = 'peer-state-v4';
2190
+ const home = path.resolve(options.home || resolvePaths().root);
2191
+ const release = acquireLock(home, id);
2192
+ try {
2193
+ assertDaemonStopped(home);
2194
+ recoverJournal(home, id);
2195
+ const changes = [];
2196
+ const root = path.join(home, 'agents');
2197
+ const entries = fs.existsSync(root) ? fs.readdirSync(root, { withFileTypes: true }) : [];
2198
+ const schema = loadSchema('contact-book', 4);
2199
+ for (const entry of entries) {
2200
+ if (!entry.isDirectory() || !validAid(entry.name))
2201
+ continue;
2202
+ const file = path.join(root, entry.name, 'peers.json');
2203
+ if (!fs.existsSync(file))
2204
+ continue;
2205
+ const configFile = path.join(root, entry.name, 'config.json');
2206
+ if (!fs.existsSync(configFile))
2207
+ continue;
2208
+ const agent = JSON.parse(fs.readFileSync(configFile, 'utf8'));
2209
+ const channelKeys = new Set((Array.isArray(agent.channels) ? agent.channels : [])
2210
+ .filter((channel) => channel && channel.type !== 'aun' && typeof channel.name === 'string')
2211
+ .map((channel) => channel.type + '#' + entry.name + '#' + channel.name));
2212
+ const before = fs.readFileSync(file, 'utf8');
2213
+ const old = JSON.parse(before);
2214
+ if (!isRecord(old) || !isRecord(old.contacts)
2215
+ || ![1, 2, 3, 4].includes(Number(old.$schema_version))) {
2216
+ throw new Error('Invalid peer state: ' + file);
2217
+ }
2218
+ if (!loadSchema('contact-book', Number(old.$schema_version)).validate(old)) {
2219
+ throw new Error('Invalid legacy peer state: ' + file);
2220
+ }
2221
+ if (old.$schema_version === 4) {
2222
+ if (!schema.validate(old))
2223
+ throw new Error('Invalid peer state: ' + file);
2224
+ continue;
2225
+ }
2226
+ const contacts = {};
2227
+ const aliases = new Set();
2228
+ for (const [aid, value] of Object.entries(old.contacts)) {
2229
+ if (!validAid(aid) || !isRecord(value))
2230
+ throw new Error('Invalid peer entry: ' + file);
2231
+ const kept = {};
2232
+ if (value.aliases !== undefined) {
2233
+ if (!Array.isArray(value.aliases))
2234
+ throw new Error('Invalid peer aliases: ' + file);
2235
+ for (const alias of value.aliases) {
2236
+ const parsed = parseContactAlias(alias, entry.name);
2237
+ if (!parsed || !channelKeys.has(parsed.channelKey) || aliases.has(alias)) {
2238
+ throw new Error('Invalid or conflicting peer alias: ' + file);
2239
+ }
2240
+ aliases.add(alias);
2241
+ }
2242
+ if (value.aliases.length)
2243
+ kept.aliases = [...value.aliases];
2244
+ }
2245
+ if (value.status === 'blocked' || value.blocked === true)
2246
+ kept.status = 'blocked';
2247
+ if (kept.aliases || kept.status)
2248
+ contacts[aid] = kept;
2249
+ }
2250
+ const next = { $schema_version: 4, contacts };
2251
+ if (!schema.validate(next))
2252
+ throw new Error('Invalid migrated peer state: ' + file);
2253
+ changes.push({ file, kind: 'agent-only-model', before, after: jsonText(next) });
2254
+ }
2255
+ const plan = { home, changes, summary: { filesChanged: changes.length } };
2256
+ const backup = options.apply ? applyMigration(plan, id) : null;
2257
+ return { changedFiles: changes.length, backup };
2258
+ }
2259
+ finally {
2260
+ release();
2261
+ }
2262
+ }
2263
+ export async function ensurePeerStateOnStartup() {
2264
+ recoverAllPeerBookMutationsSync();
2265
+ const result = runPeerStateMigration({ apply: true });
2266
+ if (result.changedFiles)
2267
+ logger.info('[peers] Retired contact membership in ' + result.changedFiles + ' peer state files');
2268
+ }
@@ -7,6 +7,7 @@ import { ConfigTarget, assertAgentAidAvailable, assertAgentModelConfigured, ensu
7
7
  import { executeResolvedConfigCommand, } from '../config/config-operation-service.js';
8
8
  import { resolveConfigCommand } from '../config/resolved-config-op.js';
9
9
  import { AgentReloadBusyError } from './agent-reload-coordinator.js';
10
+ import { assertTemplateInstallationReady } from '../agent-template/jobs.js';
10
11
  import { logger } from '../utils/logger.js';
11
12
  import { initializationCreateProgress, initializationOwnership, removeAgentFiles } from './agent-create-status.js';
12
13
  import { resolveRuntimeBaseagentModelSelection } from '../agents/baseagent.js';
@@ -197,6 +198,7 @@ export class AgentApplicationService {
197
198
  async load(aid) {
198
199
  try {
199
200
  await this.deps.beforeAgentOperation?.(aid);
201
+ assertTemplateInstallationReady(aid);
200
202
  assertAgentAidAvailable(aid);
201
203
  await this.deps.hotLoad(aid);
202
204
  return { ok: true, aid };
@@ -215,6 +217,7 @@ export class AgentApplicationService {
215
217
  return { ok: true, results: await this.deps.resync() };
216
218
  }
217
219
  assertAgentAidAvailable(aid);
220
+ assertTemplateInstallationReady(aid);
218
221
  await this.deps.reload(aid, options);
219
222
  return { ok: true };
220
223
  }
@@ -290,8 +293,10 @@ export class AgentApplicationService {
290
293
  try {
291
294
  await this.deps.beforeAgentOperation?.(aid);
292
295
  guard?.();
293
- if (enabled)
296
+ if (enabled) {
294
297
  assertAgentAidAvailable(aid);
298
+ assertTemplateInstallationReady(aid);
299
+ }
295
300
  config = loadAgent(aid);
296
301
  }
297
302
  catch (error) {
@@ -734,6 +734,10 @@ const AUDITED_WORKFLOW_SHA256 = {
734
734
  '0.5.33': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
735
735
  // 0.5.34 retains this exact workflow; real SDK read/execute boundaries were revalidated.
736
736
  '0.5.34': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
737
+ // 0.5.35 adds mail/UDP-standby/pull-channel modules; workflow bytes are byte-identical.
738
+ '0.5.35': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
739
+ // 0.5.36 retains the audited workflow; installed SDK preflight and execute boundaries were revalidated.
740
+ '0.5.36': '55b6d41331b4dfc6b377be9f4ff28d322af5e06fc4539c5d0120cb15419623f6',
737
741
  };
738
742
  export function initializationBindPreflightFailure(error) {
739
743
  if (!(error instanceof Error) || error.code !== 'ECONNRESET')
@@ -516,7 +516,8 @@ export function trustedExecutionIdentityInput(grant) {
516
516
  : PUBLIC_PERMISSION_MODES.includes(grant.permissionMode)
517
517
  ? grant.permissionMode
518
518
  : undefined;
519
- return { sessionId: grant.sessionId, ...(permissionMode ? { permissionMode } : {}), ...fullAccess };
519
+ return { sessionId: grant.sessionId, ...(permissionMode ? { permissionMode } : {}),
520
+ ...(grant.trustedProcessRole === 'daemon-service' ? { trustedProcessRole: 'daemon-service' } : {}), ...fullAccess };
520
521
  }
521
522
  export function hasTrustedFullAccessDelegation(grant) {
522
523
  return !!grant.executionIdentity && isValidFullAccessExecutionIdentity(grant.executionIdentity);
@@ -127,7 +127,8 @@ export async function authorizeFreshOperation(params) {
127
127
  await refreshOwnershipForAuthorization(subject.selfAid, {
128
128
  force: force || forceAgentMdEditor,
129
129
  ...(sensitive ? {} : { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS }),
130
- includeDaemon: subject.isDaemonOwner || subject.processRole === 'fullaccess-run'
130
+ includeDaemon: subject.isDaemonOwner || params.intent.operation === 'role.policy.write'
131
+ || subject.processRole === 'fullaccess-run'
131
132
  || params.intent.scope === 'process' || params.intent.scope === 'control' || force,
132
133
  allowTransient: !force && !forceAgentMdEditor,
133
134
  });
@@ -78,6 +78,9 @@ export function createDelegatedProviderOperationExecutor({ agentDelegationRegist
78
78
  let parsed;
79
79
  try {
80
80
  parsed = parseProviderCommand(params.argv);
81
+ if (parsed.templateId && parsed.operation !== 'templates' && (!parsed.file || parsed.templateInput)) {
82
+ throw new Error('Managed template operations require --file; inline parameters are only available in a host terminal');
83
+ }
81
84
  }
82
85
  catch (error) {
83
86
  return { ok: false, code: 'INVALID_ARGUMENT', error: error instanceof Error ? error.message : String(error) };
@@ -196,35 +199,42 @@ export function createDelegatedInvokeOperationExecutor({ agentDelegationRegistry
196
199
  });
197
200
  };
198
201
  }
202
+ /** Resolve task identity once; each operation still authorizes its own target and scope. */
203
+ export async function resolveDelegatedIdentity(params, dependencies, invalidSessionCode = 'INVALID_DELEGATION') {
204
+ const validation = params.delegationGrant
205
+ ? { ok: true, grant: params.delegationGrant }
206
+ : dependencies.agentDelegationRegistry?.validate(params.delegationToken, params.sessionId, params.delegationCommandHash);
207
+ if (!validation?.ok)
208
+ return {
209
+ ok: false, code: validation?.code ?? 'DELEGATION_REQUIRED',
210
+ error: validation?.reason ?? 'Valid task delegation is required',
211
+ };
212
+ const grant = validation.grant;
213
+ const session = await dependencies.sessionManager.getSessionById(params.sessionId);
214
+ if (!session || session.selfAID !== grant.selfAid || grant.sessionId !== params.sessionId) {
215
+ return { ok: false, code: invalidSessionCode, error: 'Delegation does not match the current session' };
216
+ }
217
+ let conversationId;
218
+ try {
219
+ conversationId = parsePeerKey(grant.peerKey).channelId;
220
+ }
221
+ catch {
222
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'delegation contains an invalid relation key' };
223
+ }
224
+ const subject = buildAuthSubject({
225
+ selfAid: grant.selfAid, sessionId: params.sessionId, actorId: grant.actorId,
226
+ channel: grant.channel, channelType: grant.channelType, channelId: conversationId,
227
+ chatType: grant.chatType, conversationId, processOwners: dependencies.getProcessOwners(),
228
+ ...trustedExecutionIdentityInput(grant),
229
+ });
230
+ return { ok: true, grant, session, subject };
231
+ }
199
232
  export function createDelegationAuthorizer({ agentDelegationRegistry, sessionManager, getProcessOwners, }) {
200
233
  return async function authorizeManagedAgentOperation(params, operation) {
201
- const delegation = params.delegationGrant
202
- ? { ok: true, grant: params.delegationGrant }
203
- : agentDelegationRegistry.validate(params.delegationToken, params.sessionId, params.delegationCommandHash);
234
+ const delegation = await resolveDelegatedIdentity(params, { agentDelegationRegistry, sessionManager, getProcessOwners });
204
235
  if (!delegation.ok)
205
- return { ok: false, code: delegation.code, error: delegation.reason };
206
- const session = await sessionManager.getSessionById(params.sessionId);
207
- if (!session || session.selfAID !== delegation.grant.selfAid) {
208
- return { ok: false, code: 'INVALID_DELEGATION', error: 'delegation does not match the current session' };
209
- }
210
- let conversationId;
211
- try {
212
- conversationId = parsePeerKey(delegation.grant.peerKey).channelId;
213
- }
214
- catch {
215
- return { ok: false, code: 'INVALID_DELEGATION', error: 'delegation contains an invalid relation key' };
216
- }
217
- const subject = buildAuthSubject({
218
- selfAid: delegation.grant.selfAid,
219
- actorId: delegation.grant.actorId,
220
- channel: delegation.grant.channel,
221
- channelType: delegation.grant.channelType,
222
- channelId: conversationId,
223
- chatType: delegation.grant.chatType,
224
- conversationId,
225
- processOwners: getProcessOwners(),
226
- ...trustedExecutionIdentityInput(delegation.grant),
227
- });
236
+ return delegation;
237
+ const { subject } = delegation;
228
238
  if (params.targetAid
229
239
  && params.targetAid !== delegation.grant.selfAid
230
240
  && subject.dataScope !== 'daemon'
@@ -133,6 +133,14 @@ function authorizeCommandInternal(ctx, resolvedConfigCommand) {
133
133
  if (isFieldConfigOperation(operation) && !resolvedConfigCommand) {
134
134
  return denyDecision(ctx, 'NOT_ALLOWED', 'Resolved config operation is required', operation, intent.scope, opMeta.dangerous);
135
135
  }
136
+ // This human card is a bound repair, never delegated provider management.
137
+ // Its callback separately verifies E2EE, card ownership and connection binding.
138
+ if (operation === 'provider.connection.repair'
139
+ && (intent.scope !== 'process' || ctx.source !== 'menu' || ctx.chatType !== 'private' || ctx.channel?.split('#')[0] !== 'aun'
140
+ || !ctx.principalId || ctx.actorId !== ctx.principalId || !ctx.isDaemonOwner
141
+ || ctx.processRole !== 'daemon-owner')) {
142
+ return denyDecision(ctx, 'NOT_ALLOWED', 'Provider connection cards require the authenticated daemon Owner', operation, intent.scope, true);
143
+ }
136
144
  if (resolvedConfigCommand
137
145
  && (resolvedConfigCommand.operationId !== operation || resolvedConfigCommand.commandScope !== intent.scope)) {
138
146
  return denyDecision(ctx, 'NOT_ALLOWED', 'Resolved config operation does not match the command intent', operation, intent.scope, opMeta.dangerous);
@@ -185,6 +193,23 @@ function authorizeCommandInternal(ctx, resolvedConfigCommand) {
185
193
  const authorizationOverride = authorizeCatalogPolicy(ctx, opMeta);
186
194
  if (authorizationOverride)
187
195
  return authorizationOverride;
196
+ // Role definitions are host policy. Relation roles, including Owner, cannot
197
+ // grant this authority through a role file. Trusted fullaccess was handled above.
198
+ if (operation === 'role.policy.write') {
199
+ if (intent.scope !== 'agent' || ctx.processRole === 'daemon-service'
200
+ || !(ctx.isDaemonOwner === true || ctx.processRole === 'daemon-owner')) {
201
+ return denyDecision(ctx, 'NOT_ALLOWED', 'Role definitions require DaemonOwner authorization', operation, intent.scope, opMeta.dangerous, 'role-policy-daemon-owner-only', 'DAEMON_OWNER_REQUIRED');
202
+ }
203
+ return { allow: true, operation, scope: intent.scope, role: 'daemon-owner',
204
+ dangerous: opMeta.dangerous, matchedRule: 'role-policy-daemon-owner-only' };
205
+ }
206
+ if (operation === 'role.assign' || operation === 'role.revoke') {
207
+ const daemonControl = ctx.fromControlChannel && ctx.isDaemonOwner === true
208
+ && ctx.processRole !== 'daemon-service';
209
+ if (!daemonControl && !(role === 'owner' && isCurrentAgentTarget(ctx))) {
210
+ return denyDecision(ctx, 'NOT_ALLOWED', 'Role assignment requires the target Agent Owner', operation, intent.scope, opMeta.dangerous, 'role-assignment-owner-only');
211
+ }
212
+ }
188
213
  if (operation === 'ec.aid.bind.status') {
189
214
  if (intent.scope !== 'agent') {
190
215
  return denyDecision(ctx, 'NOT_ALLOWED', 'Ownership status is only available for an Agent subject', operation, intent.scope, opMeta.dangerous);