evolcore 0.0.46 → 0.0.48

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 (237) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +139 -39
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +43 -18
  8. package/dist/agents/codex/app-server-client.js +32 -23
  9. package/dist/agents/codex-runner.js +31 -16
  10. package/dist/agents/ecagent-runner.js +7 -4
  11. package/dist/agents/gemini-runner.js +5 -2
  12. package/dist/agents/runner-types.js +5 -21
  13. package/dist/aun/aid/agentmd.js +5 -1
  14. package/dist/aun/group/fs-download.js +1 -1
  15. package/dist/aun/service-proxy.js +4 -2
  16. package/dist/build-identity.json +1 -0
  17. package/dist/channels/aun.js +100 -32
  18. package/dist/channels/daemon.js +10 -26
  19. package/dist/cli/aun-commands.js +86 -51
  20. package/dist/cli/code-stats.js +19 -8
  21. package/dist/cli/command-log.js +1 -1
  22. package/dist/cli/daemon-commands.js +65 -76
  23. package/dist/cli/daemon-lifecycle-client.js +17 -3
  24. package/dist/cli/directory.js +7 -1
  25. package/dist/cli/ecmsg-gateway.js +5 -2
  26. package/dist/cli/index.js +2 -8
  27. package/dist/cli/init-channel.js +6 -8
  28. package/dist/cli/init.js +74 -46
  29. package/dist/cli/invoke-command.js +1 -1
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/restart-monitor.js +104 -28
  32. package/dist/cli/role.js +61 -17
  33. package/dist/cli/stats.js +3 -3
  34. package/dist/cli/task-context.js +83 -15
  35. package/dist/cli/thread-command.js +16 -51
  36. package/dist/cli/upgrade-command.js +4 -2
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-manager.js +31 -23
  40. package/dist/config/daemon-services.js +30 -3
  41. package/dist/config/gateway-config.js +2 -2
  42. package/dist/config/invoke-ipc-service.js +6 -4
  43. package/dist/config/peer-bind-code.js +3 -4
  44. package/dist/config/peer-book-store.js +59 -218
  45. package/dist/config/peer-book.js +26 -27
  46. package/dist/config/peer-role-resolver.js +16 -1
  47. package/dist/config/provider-identity-migration.js +161 -6
  48. package/dist/config/provider-ipc-service.js +56 -11
  49. package/dist/config/provider-menu-request.js +24 -5
  50. package/dist/config/provider-templates.js +127 -0
  51. package/dist/config/providers-config.js +59 -8
  52. package/dist/config/providers-management.js +467 -49
  53. package/dist/config/role-command-service.js +248 -1
  54. package/dist/config/schema-migration.js +228 -20
  55. package/dist/config/schema-registry.js +6 -2
  56. package/dist/core/agent-application-service.js +6 -1
  57. package/dist/core/agent-runtime.js +10 -5
  58. package/dist/core/auth/agent-delegation.js +10 -4
  59. package/dist/core/auth/auth-gateway.js +2 -1
  60. package/dist/core/auth/delegation-authorization.js +3 -0
  61. package/dist/core/auth/delegation-diagnostics.js +56 -15
  62. package/dist/core/auth/operation-authorizer.js +26 -1
  63. package/dist/core/auth/operation-catalog.js +28 -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/command-handler.js +81 -85
  68. package/dist/core/command/menu-catalog.js +1 -0
  69. package/dist/core/command/menu-handler.js +65 -153
  70. package/dist/core/command/menu-protocol.js +7 -1
  71. package/dist/core/command/provider-menu.js +13 -3
  72. package/dist/core/command/role-menu.js +47 -23
  73. package/dist/core/command/slash-handler.js +30 -49
  74. package/dist/core/command/team-workspace-items.js +81 -12
  75. package/dist/core/command/team-workspace-team.js +9 -71
  76. package/dist/core/command/topic-slash.js +9 -30
  77. package/dist/core/daemon-bootstrap.js +19 -10
  78. package/dist/core/daemon-control.js +8 -10
  79. package/dist/core/daemon-lifecycle.js +50 -40
  80. package/dist/core/evolagent-registry.js +22 -3
  81. package/dist/core/file-integrity/store.js +2 -0
  82. package/dist/core/handoff/runtime.js +37 -1
  83. package/dist/core/host-snapshot.js +9 -4
  84. package/dist/core/inference/text-inference.js +3 -1
  85. package/dist/core/initialization/service.js +31 -8
  86. package/dist/core/interaction-router.js +3 -0
  87. package/dist/core/invoke/executors/text.js +72 -19
  88. package/dist/core/ipc-registration.js +6 -4
  89. package/dist/core/memory/consolidation.js +6 -6
  90. package/dist/core/message/aun-ipc-sender.js +165 -55
  91. package/dist/core/message/im-renderer.js +1 -1
  92. package/dist/core/message/message-bridge.js +51 -334
  93. package/dist/core/message/message-log.js +5 -0
  94. package/dist/core/message/message-queue.js +22 -0
  95. package/dist/core/message/message-utils.js +8 -0
  96. package/dist/core/message/response-engine.js +429 -116
  97. package/dist/core/message/send-routing.js +5 -1
  98. package/dist/core/model/catalog-service.js +31 -11
  99. package/dist/core/model/model-capabilities.js +22 -4
  100. package/dist/core/model/model-catalog.js +1 -0
  101. package/dist/core/ownership/owner-resolver.js +355 -60
  102. package/dist/core/permission/protected-paths.js +6 -6
  103. package/dist/core/relation/peer-identity.js +28 -2
  104. package/dist/core/relation/same-owner-proof.js +81 -111
  105. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  106. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  107. package/dist/core/session/session-file-health.js +49 -14
  108. package/dist/core/session/session-fs-store.js +91 -35
  109. package/dist/core/session/session-manager.js +68 -24
  110. package/dist/core/session/session-mapper.js +14 -34
  111. package/dist/core/session/session-transcript.js +5 -1
  112. package/dist/core/task/task-activity-store.js +84 -0
  113. package/dist/core/task/task-image-resources.js +1 -1
  114. package/dist/core/task/task-recovery-service.js +12 -0
  115. package/dist/core/thread/command-parser.js +7 -12
  116. package/dist/core/thread/thread-context-storage.js +3 -2
  117. package/dist/core/thread/thread-operation.js +2 -13
  118. package/dist/core/thread/thread-service.js +15 -46
  119. package/dist/directory/owner-directory-admission.js +1 -1
  120. package/dist/directory/owner-directory-cache.js +45 -28
  121. package/dist/directory/owner-directory-markdown.js +13 -1
  122. package/dist/directory/owner-directory-query-operation.js +29 -3
  123. package/dist/directory/owner-directory-remarks.js +11 -3
  124. package/dist/eck/message-renderer.js +84 -24
  125. package/dist/ecweb/basic-settings-service.js +3 -1
  126. package/dist/ecweb/message-context-service.js +1 -1
  127. package/dist/ecweb/pairing.js +4 -3
  128. package/dist/ecweb/providers-service.js +26 -1
  129. package/dist/ecweb/runtime/lifecycle.js +82 -23
  130. package/dist/ecweb/runtime/proxy-access.js +74 -0
  131. package/dist/ecweb/runtime/supervisor.js +6 -17
  132. package/dist/event-center/registry.js +13 -2
  133. package/dist/event-center/runtime.js +103 -11
  134. package/dist/event-center/script-runner.js +5 -5
  135. package/dist/index.js +129 -93
  136. package/dist/ipc.js +15 -3
  137. package/dist/outputs/events.js +62 -0
  138. package/dist/outputs/protocol.js +102 -0
  139. package/dist/outputs/service.js +279 -0
  140. package/dist/paths.js +3 -0
  141. package/dist/proxy/manager.js +43 -13
  142. package/dist/services/index.js +89 -4
  143. package/dist/services/ipc-operation.js +4 -15
  144. package/dist/services/pack-manager.js +12 -1
  145. package/dist/services/router.js +21 -6
  146. package/dist/services/script-runner.js +5 -4
  147. package/dist/services/validation.js +1 -1
  148. package/dist/stats/budget.js +1 -1
  149. package/dist/stats/db.js +19 -0
  150. package/dist/stats/index.js +1 -1
  151. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  152. package/dist/stats/normalizer.js +2 -0
  153. package/dist/stats/query.js +35 -27
  154. package/dist/stats/role-budget.js +5 -2
  155. package/dist/stats/writer.js +10 -6
  156. package/dist/trigger/audit.js +7 -0
  157. package/dist/trigger/authorization.js +105 -11
  158. package/dist/trigger/feedback.js +10 -0
  159. package/dist/trigger/history.js +37 -11
  160. package/dist/trigger/ipc-service.js +12 -1
  161. package/dist/trigger/manager.js +1 -0
  162. package/dist/trigger/scheduler.js +11 -5
  163. package/dist/trigger/script-executor.js +2 -1
  164. package/dist/trigger/script-sandbox.js +9 -3
  165. package/dist/trigger/state.js +7 -0
  166. package/dist/trigger/validation.js +22 -0
  167. package/dist/utils/aid-bind.js +155 -18
  168. package/dist/utils/atomic-write.js +3 -3
  169. package/dist/utils/cross-platform.js +97 -31
  170. package/dist/utils/error-dict.json +94 -4
  171. package/dist/utils/error-utils.js +40 -4
  172. package/dist/utils/evolcore-version.js +36 -65
  173. package/dist/utils/instance-registry.js +61 -0
  174. package/dist/utils/msg-diag.js +1 -0
  175. package/dist/utils/process-introspect.js +158 -8
  176. package/dist/utils/process-tree.js +50 -2
  177. package/dist/utils/upgrade-jobs.js +4 -4
  178. package/dist/utils/windows-shell-trust.js +2 -0
  179. package/dist/workbench/protocol.js +80 -0
  180. package/dist/workbench/service.js +359 -0
  181. package/ecagent/dist/types.d.ts +6 -2
  182. package/kits/docs/context-assembly.md +1 -1
  183. package/kits/docs/evolcore/INDEX.md +2 -2
  184. package/kits/docs/evolcore/aid.md +3 -1
  185. package/kits/docs/evolcore/config.md +12 -0
  186. package/kits/docs/evolcore/directory.md +22 -3
  187. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  188. package/kits/docs/evolcore/model.md +10 -0
  189. package/kits/docs/evolcore/peer.md +19 -65
  190. package/kits/docs/evolcore/provider.md +133 -5
  191. package/kits/docs/evolcore/role.md +80 -0
  192. package/kits/docs/evolcore/services.md +6 -6
  193. package/kits/docs/evolcore/team-workspace.md +1 -1
  194. package/kits/docs/evolcore/thread-chain.md +14 -15
  195. package/kits/docs/evolcore/tool-authorization.md +5 -0
  196. package/kits/docs/evolcore/trigger.md +10 -0
  197. package/kits/eck_message_manifest.json +12 -0
  198. package/kits/provider-templates.json +1213 -0
  199. package/kits/rules/04-relation.md +3 -3
  200. package/kits/schemas/_meta.json +14 -2
  201. package/kits/schemas/contact-book.schema.4.json +52 -0
  202. package/kits/schemas/providers.schema.3.json +200 -0
  203. package/kits/skills/.switches.json +4 -0
  204. package/kits/skills/ability/references/calling.md +1 -1
  205. package/kits/skills/ec-group/SKILL.md +2 -2
  206. package/kits/skills/ec-identity/SKILL.md +19 -72
  207. package/kits/skills/ec-provider/SKILL.md +221 -0
  208. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  209. package/kits/skills/ec-trigger/SKILL.md +1 -1
  210. package/kits/skills/thread-ops/SKILL.md +34 -21
  211. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  212. package/kits/templates/message-fragments/group-batch.md +1 -1
  213. package/kits/templates/message-fragments/inject-default.md +1 -1
  214. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  215. package/kits/templates/message-fragments/item-group.md +1 -1
  216. package/kits/templates/message-fragments/item-private.md +1 -1
  217. package/kits/templates/message-fragments/thread-context.md +1 -1
  218. package/kits/templates/message-fragments/trigger-session.md +1 -1
  219. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  220. package/kits/templates/roles/admin.json +2 -19
  221. package/kits/templates/roles/member.json +0 -3
  222. package/kits/templates/system-fragments/baseagent.md +6 -0
  223. package/kits/templates/system-fragments/commands.md +3 -3
  224. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  225. package/kits/templates/system-fragments/relation.md +1 -1
  226. package/kits/templates/system-fragments/thread.md +6 -5
  227. package/package.json +6 -4
  228. package/scripts/agent-template/inspect.mjs +4 -1
  229. package/scripts/agent-template/shared/common.mjs +2 -3
  230. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  231. package/scripts/agent-template/shared/template-package.mjs +9 -2
  232. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  233. package/scripts/agent-template/team-pack.mjs +6 -3
  234. package/dist/cli/peer.js +0 -127
  235. package/dist/config/peer-operation-service.js +0 -132
  236. package/dist/config/peer-request-service.js +0 -532
  237. package/dist/core/command/connect-menu.js +0 -624
@@ -23,7 +23,7 @@ import { resolveGlobalPkg } from '../../utils/npm-ops.js';
23
23
  import { executeUpgradeAction, parseUpgradeMode } from '../../utils/upgrade-jobs.js';
24
24
  import { launchMonitorAndConfirm, resolveCliEntry, isProcessRunning } from '../../utils/cross-platform.js';
25
25
  import { cachedCliVersion } from '../../utils/cross-platform.js';
26
- import { scanInstances } from '../../utils/instance-registry.js';
26
+ import { hasLiveRestartMonitor } from '../../utils/instance-registry.js';
27
27
  import { loadDefaults, loadDaemonConfig } from '../../config-store.js';
28
28
  import { buildEcwebPairingUrl } from '../../ecweb/pairing.js';
29
29
  import { WEB_PACKAGE_NAME, RESTART_REQUEST_ID_ENV, RUNTIME_HOME_ENV, SESSION_ID_ENV } from '../../product.js';
@@ -40,7 +40,7 @@ import { isCapabilityType, listCapabilityOptions, queryCapabilityTypes, resolveC
40
40
  import { normalizeCliArgv, parseCliIntent, parseLegacyCliCommand, validateCliArgv, withDefaultRelationContext } from './cli-intent-parser.js';
41
41
  import { auditCommandAuthorization, auditFullAccessEvent, hashArgv } from '../auth/authorization-audit.js';
42
42
  import { authorizeOperation, authorizeFreshOperation, buildAuthSubject } from '../auth/auth-gateway.js';
43
- import { ownerResolver, getDaemonOwners, refreshOwnershipForAuthorization, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
43
+ import { ownerResolver, getDaemonOwners, refreshOwnershipForAuthorization, OWNERSHIP_CACHE_MAX_AGE_MS, OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, } from '../ownership/owner-resolver.js';
44
44
  import { parseOwnershipCommand, executeOwnershipCommand, ownershipFailure } from '../../aun/aid/ownership-operation.js';
45
45
  import { authorizationDenialData, formatAuthorizationDenial } from '../auth/authorization-denial.js';
46
46
  import { evaluateRoleOperationCapability } from '../auth/operation-authorizer.js';
@@ -62,7 +62,6 @@ import { DEFAULT_SESSION_LOOP_SECONDS, MAX_SESSION_LOOP_SECONDS, MIN_SESSION_LOO
62
62
  import { remoteAccessService, validateAndRenewRemoteAccessToken } from '../auth/remote-access-store.js';
63
63
  import { listDiagnosticLogOptions, listRawConfigResources, queryDiagnosticLogs, readRawConfigResource, } from './daemon-diagnostics.js';
64
64
  import { roleMenuAction, roleMenuOperation, roleMenuOptions, roleMenuQuery, roleMenuUpdate, } from './role-menu.js';
65
- import { handleConnectMenu, connectMenuOperation } from './connect-menu.js';
66
65
  import { groupMenuAuthorizationArgs, groupMenuIntent, handleGroupMenu, } from './group-menu.js';
67
66
  import { getMenuCatalog, execMenuValueBatch, resolveExplicitMenuExecutionContext, resolveMenuCatalogContext, validateMenuCatalogArgs, validateMenuValueBatchArgs } from './menu-catalog.js';
68
67
  import { execMenuQueryBatch } from './menu-query-batch.js';
@@ -71,10 +70,13 @@ import { dataRootFailure, dataRootResolver } from './data-root-resolver.js';
71
70
  import { DataRootError, teamWorkspaceStore, readTeamWorkspaceNavigation } from './team-workspace-store.js';
72
71
  import { queryTeamWorkspaceCalendar } from './team-workspace-calendar.js';
73
72
  import { teamWorkspaceItemsIndex, validateTeamWorkspaceItemsArgs } from './team-workspace-items.js';
73
+ import { peekServiceRouter } from '../../services/index.js';
74
+ import { loadRouterConfig } from '../../services/router.js';
75
+ import { agentServicesDir } from '../../paths.js';
74
76
  import { executeTeamMembersAction, executeTeamMembersQuery, isTeamMembersMenuRequest } from './team-workspace-members-menu.js';
75
77
  import { agentStorageMenuService, isAgentStorageMenuRequest } from './agent-storage-menu.js';
76
78
  import { MAX_AUN_ATTACHMENT_SIZE } from '../../aun/msg/upload.js';
77
- import { normalizeTopicLabel, normalizeTopicStatus, resolveTopicArchiveFilter, } from '../session/session-mapper.js';
79
+ import { normalizeTopicStatus, resolveTopicArchiveFilter, } from '../session/session-mapper.js';
78
80
  import { notifyThreadRename } from '../thread/thread-operation.js';
79
81
  import { executeEventsQuery, executeEventsUpdate } from './eventcenter-menu.js';
80
82
  import { isAgentScopePath, isHClassPath, isLClassPath } from '../permission/protected-paths.js';
@@ -85,6 +87,27 @@ import { isAgentScopePath, isHClassPath, isLClassPath } from '../permission/prot
85
87
  function getBaseagentVersion(cmd) {
86
88
  return cachedCliVersion(cmd);
87
89
  }
90
+ /** Retained task details use immutable task relations and the current protocol Owner. */
91
+ async function canReadRetainedOwnerTask(input) {
92
+ const { selfAid, actorId, channelType, session, meta, requestedThreadId } = input;
93
+ if (channelType !== 'aun' || session.chatType !== 'private' || session.selfAID !== selfAid
94
+ || session.channelId !== actorId || meta.selfAid !== selfAid || meta.channel !== 'aun'
95
+ || meta.chatType !== 'private' || meta.peerId !== actorId || meta.channelId !== actorId
96
+ || requestedThreadId !== undefined && meta.threadId !== requestedThreadId)
97
+ return false;
98
+ try {
99
+ const owner = await ownerResolver.refresh(selfAid, { source: 'workbench.task-detail',
100
+ maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, allowTransient: false });
101
+ const current = ownerResolver.snapshot(selfAid);
102
+ return owner.authorizationStatus === 'verified' && !owner.refreshFailure?.fallbackUsed
103
+ && (owner.validUntil ?? 0) > Date.now() && owner.ownerAid === actorId
104
+ && current.authorizationStatus === 'verified' && !current.refreshFailure?.fallbackUsed
105
+ && (current.validUntil ?? 0) > Date.now() && current.ownerAid === actorId && current.revision === owner.revision;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
88
111
  const allEfforts = CONFIGURABLE_EFFORTS;
89
112
  const PERMISSION_MODE_KEYS = PUBLIC_PERMISSION_MODES;
90
113
  /** menu file: fetch 文件大小上限(与 /file 和 AUN sendFile 一致) */
@@ -225,10 +248,8 @@ export function buildTopicForkSourcePayload(session) {
225
248
  }
226
249
  function buildSessionPayload(session, name) {
227
250
  const payload = { id: session.id, name };
228
- if (session.label)
229
- payload.label = session.label;
230
251
  if (isTopicSession(session))
231
- payload.topicStatus = session.topicStatus ?? 'pending';
252
+ payload.topicStatus = session.topicStatus ?? 'active';
232
253
  if (session.agentSessionId)
233
254
  payload.agentSessionId = session.agentSessionId;
234
255
  const forkSource = buildTopicForkSourcePayload(session);
@@ -1136,6 +1157,8 @@ function buildMenuIntent(verb, cmdBase, args, action, value, fromControlChannel
1136
1157
  if (cmdBase === '/system')
1137
1158
  return intent('system.status', 'process');
1138
1159
  if (cmdBase === '/agent') {
1160
+ if (args?.view === 'access')
1161
+ return intent('agent.access.read', 'agent');
1139
1162
  return intent(fromControlChannel && !args?.aid ? 'agent.list' : 'agent.show', fromControlChannel ? 'control' : 'agent');
1140
1163
  }
1141
1164
  if (cmdBase === '/trigger')
@@ -1224,6 +1247,8 @@ function buildMenuIntent(verb, cmdBase, args, action, value, fromControlChannel
1224
1247
  return intent('system.paircode', 'process', { action });
1225
1248
  }
1226
1249
  if (cmdBase === '/agent') {
1250
+ if (action === 'set-access')
1251
+ return intent('agent.access.write', 'agent', { action });
1227
1252
  if (action === 'update' && args?.patch && Object.hasOwn(args.patch, 'avatar')) {
1228
1253
  return intent('ec.aid.avatar', 'agent', { action });
1229
1254
  }
@@ -1834,30 +1859,6 @@ export async function getSubMenuItems(cmd, channel, channelId, userId, args, ove
1834
1859
  throw authorized;
1835
1860
  return await roleMenuOptions(authorized.context, args);
1836
1861
  }
1837
- if (cmdBase0 === '/connect') {
1838
- const identity = overrideIdentity ?? this.sessionManager.resolveIdentity(channel, userId, ...menuIdentityArgs(session));
1839
- const authorized = await authorizeRoleMenu(this, {
1840
- kind: 'options', args, operation: connectMenuOperation('options', args), identity, subject: authSubject, session, channel, channelId,
1841
- userId, fromControlChannel, source,
1842
- });
1843
- if ('error' in authorized)
1844
- throw authorized;
1845
- try {
1846
- const result = await handleConnectMenu({ type: 'menu.options', subtype: 'options', args }, authorized.context);
1847
- if ('error' in result)
1848
- throw result.error;
1849
- const opts = result.data?.options ?? [];
1850
- return opts.map((opt) => ({
1851
- value: opt.option,
1852
- label: opt.label,
1853
- desc: opt.description,
1854
- ...(typeof opt.selected === 'boolean' ? { selected: opt.selected } : {}),
1855
- }));
1856
- }
1857
- catch (error) {
1858
- throw menuResultFailure(error);
1859
- }
1860
- }
1861
1862
  if (cmdBase0 === '/group') {
1862
1863
  const result = await executeGroupMenu(this, {
1863
1864
  kind: 'options', args,
@@ -2017,16 +2018,6 @@ export async function getSubMenuItems(cmd, channel, channelId, userId, args, ove
2017
2018
  forkHistoryVersion: 1,
2018
2019
  }));
2019
2020
  }
2020
- const hasLabel = args && (Object.hasOwn(args, 'label') || Object.hasOwn(args, 'lable'));
2021
- let label;
2022
- if (hasLabel) {
2023
- try {
2024
- label = normalizeTopicLabel(Object.hasOwn(args, 'label') ? args.label : args.lable);
2025
- }
2026
- catch (error) {
2027
- throw { code: 'INVALID_ARGS', message: error.message };
2028
- }
2029
- }
2030
2021
  let archiveFilter;
2031
2022
  try {
2032
2023
  archiveFilter = resolveTopicArchiveFilter(args?.archived === undefined && args?.topicStatus === 'archived' ? true : args?.archived);
@@ -2046,7 +2037,7 @@ export async function getSubMenuItems(cmd, channel, channelId, userId, args, ove
2046
2037
  }
2047
2038
  const metadataOnly = args?.metadataOnly === true;
2048
2039
  const topics = sessions.filter((s) => isTopicSession(s)
2049
- && (!hasLabel || s.label === label) && (!topicStatus || s.topicStatus === topicStatus));
2040
+ && (!topicStatus || s.topicStatus === topicStatus));
2050
2041
  const items = [];
2051
2042
  for (let offset = 0; offset < topics.length; offset += 4) {
2052
2043
  items.push(...await Promise.all(topics.slice(offset, offset + 4)
@@ -2058,10 +2049,10 @@ export async function getSubMenuItems(cmd, channel, channelId, userId, args, ove
2058
2049
  const sessions = await this.sessionManager.listSessions(channel, channelId);
2059
2050
  const active = cmd === '/del' ? await this.sessionManager.getActiveSession(channel, channelId) : null;
2060
2051
  const currentSession = session;
2061
- const items = sessions
2052
+ const items = [];
2053
+ for (const s of sessions
2062
2054
  .filter((s) => isMainSession(s))
2063
- .filter((s) => !active || s.id !== active.id)
2064
- .map((s) => {
2055
+ .filter((s) => !active || s.id !== active.id)) {
2065
2056
  const displayName = displaySessionTitle(s.name, s.id.slice(0, 8));
2066
2057
  const item = {
2067
2058
  value: s.name || s.id.slice(0, 8),
@@ -2070,17 +2061,17 @@ export async function getSubMenuItems(cmd, channel, channelId, userId, args, ove
2070
2061
  };
2071
2062
  if (s.agentSessionId) {
2072
2063
  item.agentSessionId = s.agentSessionId;
2073
- const fileInfo = this.sessionManager.getSessionFileInfo(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
2074
- if (fileInfo.turns)
2075
- item.turns = fileInfo.turns;
2076
- const firstMsg = this.sessionManager.readSessionFirstMessage(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
2064
+ const summary = await this.sessionManager.readSessionMenuSummary(s.projectPath, s.agentSessionId, s.baseagent, s.selfAID);
2065
+ if (summary.turns)
2066
+ item.turns = summary.turns;
2067
+ const firstMsg = summary.firstMessage;
2077
2068
  if (firstMsg)
2078
2069
  item.preview = firstMsg.length > 80 ? firstMsg.slice(0, 80) + '…' : firstMsg;
2079
2070
  }
2080
2071
  if (s.updatedAt)
2081
2072
  item.lastActive = s.updatedAt;
2082
- return item;
2083
- });
2073
+ items.push(item);
2074
+ }
2084
2075
  if (cmd === '/s' || cmd === '/session') {
2085
2076
  items.push({ value: 'cli', label: '查看 CLI 会话', desc: '列出未导入的 CLI 本地会话' });
2086
2077
  }
@@ -2558,28 +2549,6 @@ export async function execMenuQuery(cmd, channel, channelId, userId, args, expli
2558
2549
  return menuResultFailure(error);
2559
2550
  }
2560
2551
  }
2561
- if (cmdBase === '/connect') {
2562
- const authorized = await authorizeRoleMenu(this, {
2563
- kind: 'query', args, operation: connectMenuOperation('query', args), identity, subject, session, channel, channelId,
2564
- userId, fromControlChannel, source,
2565
- });
2566
- if ('error' in authorized)
2567
- return authorized;
2568
- try {
2569
- const result = await handleConnectMenu({ type: 'menu.query', subtype: 'query', args }, authorized.context);
2570
- if (result.error) {
2571
- return {
2572
- error: result.error.message,
2573
- code: result.error.code,
2574
- ...(result.error.data === undefined ? {} : { data: result.error.data }),
2575
- };
2576
- }
2577
- return { data: result.data };
2578
- }
2579
- catch (error) {
2580
- return menuResultFailure(error);
2581
- }
2582
- }
2583
2552
  if (cmdBase === '/group') {
2584
2553
  return await executeGroupMenu(this, {
2585
2554
  kind: 'query', args, identity, subject, session,
@@ -2620,12 +2589,15 @@ export async function execMenuQuery(cmd, channel, channelId, userId, args, expli
2620
2589
  if (!meta)
2621
2590
  return { error: 'Task not found', code: 'NOT_FOUND' };
2622
2591
  const groupId = session.metadata?.groupId || session.channelId;
2623
- if (meta.selfAid !== subject.selfAid || meta.sessionId !== session.id
2592
+ const sameSession = !(meta.selfAid !== subject.selfAid || meta.sessionId !== session.id
2624
2593
  || meta.channel !== (subject.channelType || channel.split('#')[0])
2625
2594
  || meta.chatType !== session.chatType
2626
2595
  || (meta.chatType === 'group'
2627
2596
  ? meta.groupId !== groupId || meta.channelId !== groupId
2628
- : meta.peerId !== subject.actorId || meta.channelId !== subject.actorId)) {
2597
+ : meta.peerId !== subject.actorId || meta.channelId !== subject.actorId));
2598
+ if (!sameSession && !await canReadRetainedOwnerTask({ selfAid: subject.selfAid, actorId: subject.actorId,
2599
+ channelType: subject.channelType || channel.split('#')[0], session, meta,
2600
+ requestedThreadId: transportReplyContext?.threadId })) {
2629
2601
  return { error: 'Task is not available in this session', code: 'FORBIDDEN' };
2630
2602
  }
2631
2603
  return { data: args.view === 'activities'
@@ -2702,7 +2674,16 @@ export async function execMenuQuery(cmd, channel, channelId, userId, args, expli
2702
2674
  return { error: 'agent-data-root does not accept args', code: 'INVALID_ARGUMENT' };
2703
2675
  }
2704
2676
  try {
2705
- return { data: dataRootResolver.issueAgentRoot(subject) };
2677
+ const root = dataRootResolver.issueAgentRoot(subject);
2678
+ return { data: { ...root, outputs: {
2679
+ protocolVersion: 1, enabled: peekServiceRouter(root.targetAid)?.enabled
2680
+ ?? loadRouterConfig(agentServicesDir(root.targetAid)).config.enabled,
2681
+ notifications: this.eventCenter?.get(root.targetAid)?.runtime.nativeOutputAvailable === true,
2682
+ }, workbench: {
2683
+ protocolVersion: 1, enabled: peekServiceRouter(root.targetAid)?.enabled
2684
+ ?? loadRouterConfig(agentServicesDir(root.targetAid)).config.enabled,
2685
+ notifications: this.eventCenter?.get(root.targetAid)?.runtime.nativeOutputAvailable === true,
2686
+ } } };
2706
2687
  }
2707
2688
  catch (error) {
2708
2689
  return dataRootFailure(error);
@@ -2847,7 +2828,7 @@ export async function execMenuQuery(cmd, channel, channelId, userId, args, expli
2847
2828
  }
2848
2829
  let turns = 0;
2849
2830
  if (session.agentSessionId) {
2850
- const fileInfo = this.sessionManager.getSessionFileInfo(session.projectPath, session.agentSessionId, session.baseagent, session.selfAID);
2831
+ const fileInfo = await this.sessionManager.getSessionFileInfoAsync(session.projectPath, session.agentSessionId, session.baseagent, session.selfAID);
2851
2832
  turns = fileInfo.turns;
2852
2833
  }
2853
2834
  const data = {
@@ -2976,13 +2957,12 @@ export async function execMenuQuery(cmd, channel, channelId, userId, args, expli
2976
2957
  }
2977
2958
  let turns = 0;
2978
2959
  if (topic.agentSessionId) {
2979
- turns = this.sessionManager.getSessionFileInfo(topic.projectPath, topic.agentSessionId, topic.baseagent, topic.selfAID).turns;
2960
+ turns = (await this.sessionManager.getSessionFileInfoAsync(topic.projectPath, topic.agentSessionId, topic.baseagent, topic.selfAID)).turns;
2980
2961
  }
2981
2962
  const data = {
2982
2963
  threadId: sessionLocalTopicId(topic) ?? '',
2983
2964
  name: topic.name || null,
2984
- label: topic.label || null,
2985
- topicStatus: topic.topicStatus ?? 'pending',
2965
+ topicStatus: topic.topicStatus ?? 'active',
2986
2966
  agentSessionId: topic.agentSessionId || null,
2987
2967
  status: executionState === 'interrupting' ? 'interrupting' : isProcessing || queueLength > 0 ? 'processing' : 'idle',
2988
2968
  createdAt: topic.createdAt,
@@ -3534,28 +3514,6 @@ export async function execMenuUpdate(cmd, value, channel, channelId, userId, ove
3534
3514
  return menuResultFailure(error);
3535
3515
  }
3536
3516
  }
3537
- if (cmdBase === '/connect') {
3538
- const authorized = await authorizeRoleMenu(this, {
3539
- kind: 'update', args, value: arg, operation: connectMenuOperation('update', args, arg), identity, subject: authSubject, session, channel, channelId,
3540
- userId, fromControlChannel, source,
3541
- });
3542
- if ('error' in authorized)
3543
- return authorized;
3544
- try {
3545
- const result = await handleConnectMenu({ type: 'menu.update', subtype: 'update', args, value: arg }, authorized.context);
3546
- if (result.error) {
3547
- return {
3548
- error: result.error.message,
3549
- code: result.error.code,
3550
- ...(result.error.data === undefined ? {} : { data: result.error.data }),
3551
- };
3552
- }
3553
- return { data: result.data };
3554
- }
3555
- catch (error) {
3556
- return menuResultFailure(error);
3557
- }
3558
- }
3559
3517
  if (cmdBase === '/group') {
3560
3518
  return await executeGroupMenu(this, {
3561
3519
  kind: 'update', args, value: arg, identity, subject, session,
@@ -4039,28 +3997,6 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
4039
3997
  return menuResultFailure(error);
4040
3998
  }
4041
3999
  }
4042
- if (cmdBase === '/connect') {
4043
- const authorized = await authorizeRoleMenu(this, {
4044
- kind: 'action', args, operation: connectMenuOperation('action', args), identity: authIdentity, subject, session: authSession,
4045
- channel, channelId, userId, fromControlChannel, source,
4046
- });
4047
- if ('error' in authorized)
4048
- return authorized;
4049
- try {
4050
- const result = await handleConnectMenu({ type: 'menu.action', subtype: 'action', action, args }, authorized.context);
4051
- if (result.error) {
4052
- return {
4053
- error: result.error.message,
4054
- code: result.error.code,
4055
- ...(result.error.data === undefined ? {} : { data: result.error.data }),
4056
- };
4057
- }
4058
- return { data: result.data };
4059
- }
4060
- catch (error) {
4061
- return menuResultFailure(error);
4062
- }
4063
- }
4064
4000
  if ((cmdBase === '/agent' || cmdBase === '/aid') && !args?.aid) {
4065
4001
  const selfAid = this.getOwningAgent?.(channel)?.aid;
4066
4002
  if (selfAid)
@@ -4498,16 +4434,6 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
4498
4434
  return { error: `不支持的 trigger action: ${action}`, code: 'INVALID_ARGS' };
4499
4435
  }
4500
4436
  if (cmdBase === '/topic') {
4501
- const hasLabel = args && (Object.hasOwn(args, 'label') || Object.hasOwn(args, 'lable'));
4502
- let label;
4503
- if (hasLabel && (action === 'fork' || action === 'label')) {
4504
- try {
4505
- label = normalizeTopicLabel(Object.hasOwn(args, 'label') ? args.label : args.lable);
4506
- }
4507
- catch (error) {
4508
- return { error: error.message, code: 'INVALID_ARGS' };
4509
- }
4510
- }
4511
4437
  if (action === 'fork') {
4512
4438
  if (!this.canReadTopics(identity.role))
4513
4439
  return { error: '无权限创建话题分支', code: 'FORBIDDEN' };
@@ -4599,7 +4525,6 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
4599
4525
  const forkedAgentSessionId = await currentAgent.forkSessionAt(current.agentSessionId, current.projectPath, actualSourceMessageId, name || undefined, { sessionId: current.id, permissionMode: subject.permissionMode, role: subject.role });
4600
4526
  const topic = await this.sessionManager.createForkedThreadSession(current, forkedAgentSessionId, targetThreadId, {
4601
4527
  name: name || undefined,
4602
- ...(hasLabel ? { label: label ?? null } : {}),
4603
4528
  creatorPeerId: userId,
4604
4529
  sourceAssistantMessageId: actualSourceMessageId,
4605
4530
  sourceTurn: forkTurn.index,
@@ -4721,7 +4646,7 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
4721
4646
  topicForkTargetsInFlight.delete(targetKey);
4722
4647
  }
4723
4648
  }
4724
- if (action !== 'delete' && action !== 'rename' && action !== 'label' && action !== 'status') {
4649
+ if (action !== 'delete' && action !== 'rename' && action !== 'status') {
4725
4650
  return { error: `不支持的 topic action: ${action}`, code: 'NOT_SUPPORTED' };
4726
4651
  }
4727
4652
  const target = (args?.target ?? '').toString().trim();
@@ -4730,8 +4655,6 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
4730
4655
  const renameName = action === 'rename' ? getRenameName(args) : '';
4731
4656
  if (action === 'rename' && !renameName)
4732
4657
  return { error: '缺少 args.name', code: 'MISSING_VALUE' };
4733
- if (action === 'label' && !hasLabel)
4734
- return { error: '缺少 args.label', code: 'MISSING_VALUE' };
4735
4658
  let topicStatus;
4736
4659
  if (action === 'status') {
4737
4660
  try {
@@ -4753,18 +4676,7 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
4753
4676
  ? 'private'
4754
4677
  : this.resolveMenuChatType(channel, channelId, explicitChatType);
4755
4678
  if (!this.canDeleteTopic(identity.role, chatType, topic, userId)) {
4756
- return { error: action === 'label' ? '无权限修改话题分类' : action === 'status' ? '无权限修改话题状态' : action === 'rename' ? '无权限重命名话题' : '无权限删除话题', code: 'FORBIDDEN' };
4757
- }
4758
- if (action === 'label') {
4759
- const success = await this.sessionManager.setTopicLabel(topic.id, label ?? null);
4760
- if (!success)
4761
- return { error: '话题不存在', code: 'NOT_FOUND' };
4762
- return {
4763
- data: {
4764
- action: 'label', success: true,
4765
- topic: { ...buildSessionPayload(topic, topic.name || ''), threadId: sessionLocalTopicId(topic) ?? '', label: label ?? null },
4766
- },
4767
- };
4679
+ return { error: action === 'status' ? '无权限修改话题状态' : action === 'rename' ? '无权限重命名话题' : '无权限删除话题', code: 'FORBIDDEN' };
4768
4680
  }
4769
4681
  if (action === 'status') {
4770
4682
  const success = await this.sessionManager.setTopicStatus(topic.id, topicStatus);
@@ -5007,7 +4919,7 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
5007
4919
  data: { reasonCode: 'RESTART_ENTRY_MISSING', entry: monitorEntry.entry },
5008
4920
  };
5009
4921
  }
5010
- if (scanInstances().restartMonitors.some(item => item.alive)
4922
+ if (await hasLiveRestartMonitor()
5011
4923
  || !createRestartRequest(pendingFile, restartInfo, isProcessRunning)) {
5012
4924
  return { error: '已有重启请求正在处理,请等待其结果,不要重复发起。', code: 'RESTART_ALREADY_PENDING' };
5013
4925
  }
@@ -5022,12 +4934,12 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
5022
4934
  [SESSION_ID_ENV]: '',
5023
4935
  [AGENT_DELEGATION_TOKEN_ENV]: '',
5024
4936
  [RESTART_REQUEST_ID_ENV]: requestId,
5025
- }, () => accepted(), () => scanInstances().restartMonitors.some(item => item.alive && item.record.requestId === requestId && item.record.phase === 'accepted'), {
4937
+ }, () => accepted(), () => hasLiveRestartMonitor({ requestId, phase: 'accepted' }), {
5026
4938
  requestId,
5027
4939
  timeoutMs: 8_000,
5028
4940
  logFilePath,
5029
4941
  onSpawn: pid => { updateRestartRequest(pendingFile, requestId, { launcherPid: pid }); },
5030
- isPendingInRegistry: () => scanInstances().restartMonitors.some(item => item.alive && item.record.requestId === requestId),
4942
+ isPendingInRegistry: () => hasLiveRestartMonitor({ requestId }),
5031
4943
  });
5032
4944
  if (!restartLaunch.ok) {
5033
4945
  if (restartLaunch.pending) {
@@ -36,6 +36,13 @@ export async function deliverMenuResponse(send, options) {
36
36
  await send();
37
37
  }
38
38
  catch (error) {
39
+ // Directory synchronization has its own recovery lifecycle. Retrying the
40
+ // same response at 250/750/2000ms cannot supply a missing snapshot. Keep
41
+ // the error retryable for callers, but end this short transport retry loop.
42
+ if (error && typeof error === 'object'
43
+ && error.code === 'CONTACT_DIRECTORY_UNAVAILABLE') {
44
+ fail('dependency-unavailable', error);
45
+ }
39
46
  const delay = RETRY_DELAYS_MS[attempt];
40
47
  if (!isRetryableMenuTransportError(error))
41
48
  fail('transport-error', error);
@@ -211,7 +218,6 @@ export const MENU_NAME_COMMANDS = Object.freeze({
211
218
  config: '/config',
212
219
  capability: '/capability',
213
220
  role: '/role',
214
- connect: '/connect',
215
221
  events: '/events',
216
222
  });
217
223
  export function menuCommandForName(name) {
@@ -1,4 +1,5 @@
1
- import { createProvider, parseProviderImport, readProvidersSnapshot, updateProvider } from '../../config/providers-management.js';
1
+ import { applyProviderTemplate, createProvider, parseProviderImport, previewProviderTemplate, readProvidersSnapshot, updateProvider } from '../../config/providers-management.js';
2
+ import { providerTemplateDetail, readProviderTemplates } from '../../config/provider-templates.js';
2
3
  import { parseProviderObject, providerFailure } from '../../config/provider-ipc-service.js';
3
4
  import { resolveProviderId } from '../../config/providers-config.js';
4
5
  import { validateProviderMenuRequest } from '../../config/provider-menu-request.js';
@@ -14,8 +15,9 @@ export async function executeProviderMenu(request, subject, source) {
14
15
  return { error: 'Provider mutations require an encrypted Control Menu request', code: 'FORBIDDEN' };
15
16
  }
16
17
  const args = request.args;
17
- const operation = request.type === 'menu.query' ? args.view === 'detail' ? 'show' : 'list'
18
- : request.type === 'menu.update' ? 'update' : request.action;
18
+ const operation = request.action === 'preview-template' || args.view === 'templates' ? 'templates'
19
+ : request.type === 'menu.query' ? args.view === 'detail' ? 'show' : 'list'
20
+ : request.type === 'menu.update' ? 'update' : request.action;
19
21
  const decision = await authorizeFreshOperation({
20
22
  source, subject,
21
23
  intent: { operation: 'provider.' + operation, scope: 'process', source,
@@ -25,6 +27,14 @@ export async function executeProviderMenu(request, subject, source) {
25
27
  if (!decision.allow)
26
28
  return { error: 'Provider operation is not permitted', code: 'FORBIDDEN' };
27
29
  try {
30
+ if (operation === 'templates')
31
+ return { data: request.action === 'preview-template'
32
+ ? previewProviderTemplate(args.templateId, args.config)
33
+ : args.templateId ? providerTemplateDetail(args.templateId) : readProviderTemplates() };
34
+ if (args.templateId)
35
+ return { data: await applyProviderTemplate({ templateId: args.templateId,
36
+ config: request.type === 'menu.update' ? JSON.parse(String(request.value)) : args.config,
37
+ providerId: request.type === 'menu.update' ? args.providerId : undefined, revision: args.expectedRevision }) };
28
38
  if (operation === 'list' || operation === 'show') {
29
39
  const snapshot = readProvidersSnapshot();
30
40
  if (operation === 'list')
@@ -23,7 +23,7 @@ import { resolveAunTargetKind } from '../../aun/group/identity.js';
23
23
  import { readJsonFile, readLastJsonlLine, scanChatDirs, scanMetaFiles } from '../session/session-fs-store.js';
24
24
  import { constrainResolvedModelForRole } from '../model/model-permission.js';
25
25
  import { resolveRuntimePermissionMode, resolveRuntimeStringField } from '../role/runtime-policy.js';
26
- import { mutatePeerBookTransactionSync } from '../../config/peer-book-store.js';
26
+ import { commitAgentConfigTransactionSync } from '../../config/peer-book-store.js';
27
27
  import { readRoleDefinition, readRoleRegistry, registerRole, writeRoleDefinition, writeRoleRegistry, } from '../../config/role-service.js';
28
28
  import { clearRoleStoreCache, readRoleStore, roleRegistryExists } from '../../config/role-store.js';
29
29
  const ROLE_MENU_SCHEMA_VERSION = 1;
@@ -57,9 +57,9 @@ export function roleMenuOperation(kind, args, value) {
57
57
  }
58
58
  if (kind === 'action')
59
59
  return 'role.policy.write';
60
- if (args?.resource !== 'assignment' && args?.resource !== 'admin')
60
+ if (!['assignment', 'admin', 'defaultRoles'].includes(String(args?.resource)))
61
61
  return 'role.policy.write';
62
- if (args?.resource === 'admin')
62
+ if (args?.resource === 'admin' || args?.resource === 'defaultRoles')
63
63
  return 'role.assign';
64
64
  try {
65
65
  return JSON.parse(value ?? '') === null ? 'role.revoke' : 'role.assign';
@@ -74,7 +74,13 @@ export async function roleMenuOptions(context, args) {
74
74
  assertRoleDomainReady(context.self);
75
75
  const option = stringArg(args?.option);
76
76
  if (option === 'roles')
77
- return roleItems(context.self);
77
+ return roleItems(context.self).map(item => ({
78
+ ...item,
79
+ assignable: item.assignable && canAssignRoles(context),
80
+ editable: item.editable && (context.trustedFullAccess === true || context.isDaemonOwner === true),
81
+ deletable: item.deletable && (context.trustedFullAccess === true || context.isDaemonOwner === true),
82
+ resettable: item.resettable && (context.trustedFullAccess === true || context.isDaemonOwner === true),
83
+ }));
78
84
  if (option === 'operations') {
79
85
  return listOperations().map(operation => ({
80
86
  value: operation.id,
@@ -114,15 +120,19 @@ export async function roleMenuQuery(context, args) {
114
120
  const policyRevision = revision(policyDocument(agent));
115
121
  if (view === 'capabilities') {
116
122
  const hasAunDirectory = context.aunAvailable !== false;
123
+ const policyWrite = context.trustedFullAccess === true || context.isDaemonOwner === true;
124
+ const assignmentWrite = canAssignRoles(context);
117
125
  return {
118
126
  $schema_version: ROLE_MENU_SCHEMA_VERSION,
119
127
  self: context.self,
120
128
  capabilities: {
121
- roleList: true, roleRead: true, roleWrite: true, roleCreate: true, roleDelete: true, roleReset: true,
122
- defaultRoleRead: true, defaultRoleWrite: true, permissionFields: true, permissionValues: true,
129
+ roleList: true, roleRead: true, roleWrite: policyWrite, roleCreate: policyWrite,
130
+ roleDelete: policyWrite, roleReset: policyWrite,
131
+ defaultRoleRead: true, defaultRoleWrite: assignmentWrite, permissionFields: true, permissionValues: true,
123
132
  operations: true, privateTargetsList: true, joinedGroupsList: hasAunDirectory, assignmentInventory: true,
124
- relationSnapshot: hasAunDirectory, privateRoleAssign: hasAunDirectory, groupRoleAssign: hasAunDirectory,
125
- deleteWithReplacement: true, jsonStringUpdateValue: true,
133
+ relationSnapshot: hasAunDirectory, privateRoleAssign: hasAunDirectory && assignmentWrite,
134
+ groupRoleAssign: hasAunDirectory && assignmentWrite,
135
+ deleteWithReplacement: policyWrite, jsonStringUpdateValue: true,
126
136
  },
127
137
  };
128
138
  }
@@ -144,7 +154,14 @@ export async function roleMenuQuery(context, args) {
144
154
  self: context.self,
145
155
  policyRevision,
146
156
  roleId,
147
- meta: roleMeta(context.self, roleId),
157
+ meta: {
158
+ ...roleMeta(context.self, roleId),
159
+ editable: context.trustedFullAccess === true || context.isDaemonOwner === true,
160
+ deletable: roleMeta(context.self, roleId).deletable
161
+ && (context.trustedFullAccess === true || context.isDaemonOwner === true),
162
+ resettable: roleMeta(context.self, roleId).resettable
163
+ && (context.trustedFullAccess === true || context.isDaemonOwner === true),
164
+ },
148
165
  definition: clone(definition),
149
166
  };
150
167
  }
@@ -178,6 +195,10 @@ export async function roleMenuGroupCount(context) {
178
195
  }
179
196
  export async function roleMenuUpdate(context, args, rawValue) {
180
197
  assertRequest(context, args);
198
+ if (args?.resource === 'definition')
199
+ assertRolePolicyMutationTarget(context, args);
200
+ else
201
+ assertRoleAssignmentAuthority(context);
181
202
  const value = parseUpdateValue(rawValue, context.self);
182
203
  return withAgentMutation(context.self, async () => {
183
204
  recoverRoleMutationSync(context.self);
@@ -186,7 +207,6 @@ export async function roleMenuUpdate(context, args, rawValue) {
186
207
  const resource = stringArg(args?.resource);
187
208
  let result;
188
209
  if (resource === 'definition') {
189
- assertRolePolicyMutationTarget(context, args);
190
210
  result = updateDefinition(context.self, args, value);
191
211
  }
192
212
  else if (resource === 'defaultRoles')
@@ -203,6 +223,7 @@ export async function roleMenuUpdate(context, args, rawValue) {
203
223
  }
204
224
  export async function roleMenuAction(context, action, args) {
205
225
  assertRequest(context, args);
226
+ assertRolePolicyMutationTarget(context, args);
206
227
  return withAgentMutation(context.self, async () => {
207
228
  recoverRoleMutationSync(context.self);
208
229
  assertRoleDomainReady(context.self);
@@ -211,7 +232,6 @@ export async function roleMenuAction(context, action, args) {
211
232
  if (action === 'create')
212
233
  result = createRole(context.self, args);
213
234
  else if (action === 'reset') {
214
- assertRolePolicyMutationTarget(context, args);
215
235
  result = resetRole(context.self, args);
216
236
  }
217
237
  else if (action === 'delete')
@@ -345,7 +365,8 @@ function assertRequest(context, args) {
345
365
  receivingSelf: context.self,
346
366
  });
347
367
  }
348
- if (!isDaemonOwnerControl(context) && context.actorRole !== 'owner' && context.actorRole !== 'admin') {
368
+ if (!context.trustedFullAccess && context.isDaemonOwner !== true
369
+ && context.actorRole !== 'owner' && context.actorRole !== 'admin') {
349
370
  throw roleError('PERMISSION_DENIED', 'Role management requires Agent owner or admin', context.self, {
350
371
  kind: 'role_permission_denied',
351
372
  actorRole: context.actorRole,
@@ -353,12 +374,19 @@ function assertRequest(context, args) {
353
374
  }
354
375
  }
355
376
  function assertRolePolicyMutationTarget(context, args) {
356
- const roleId = requiredRoleId(args, context.self);
357
- if (!isDaemonOwnerControl(context) && context.actorRole === 'admin' && roleId === 'owner') {
358
- throw roleError('PERMISSION_DENIED', 'Agent admin cannot modify the owner role policy', context.self, {
359
- kind: 'role_hierarchy_violation',
360
- actorRole: context.actorRole,
361
- targetRole: roleId,
377
+ if (!context.trustedFullAccess && context.isDaemonOwner !== true) {
378
+ throw roleError('PERMISSION_DENIED', 'Role definitions require DaemonOwner authorization', context.self, {
379
+ kind: 'daemon_owner_required', actorRole: context.actorRole,
380
+ });
381
+ }
382
+ }
383
+ function canAssignRoles(context) {
384
+ return context.trustedFullAccess === true || isDaemonOwnerControl(context) || context.actorRole === 'owner';
385
+ }
386
+ function assertRoleAssignmentAuthority(context) {
387
+ if (!canAssignRoles(context)) {
388
+ throw roleError('PERMISSION_DENIED', 'Role assignment requires the Agent Owner', context.self, {
389
+ kind: 'agent_owner_required', actorRole: context.actorRole,
362
390
  });
363
391
  }
364
392
  }
@@ -1573,11 +1601,7 @@ function normalizeRelationForScene(value, scene) {
1573
1601
  return normalized;
1574
1602
  }
1575
1603
  function commitJournal(self, changes) {
1576
- mutatePeerBookTransactionSync({
1577
- selfAid: self,
1578
- actor: 'role-delete-transaction',
1579
- mutation: { type: 'sync-management-roles' },
1580
- }, changes);
1604
+ commitAgentConfigTransactionSync(self, changes);
1581
1605
  }
1582
1606
  function removeJournalFiles(journalFile) {
1583
1607
  // Remove backups first. If the process exits mid-cleanup, a committed main