evolcore 0.0.48 → 0.0.50

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 (302) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/bin/ecmsg.js +9 -4
  3. package/dist/ability/caller/authorization.js +21 -0
  4. package/dist/ability/caller/command.js +164 -0
  5. package/dist/ability/caller/contract.js +102 -0
  6. package/dist/ability/caller/daemon.js +158 -0
  7. package/dist/ability/caller/service.js +380 -0
  8. package/dist/ability/command-contract.js +5 -0
  9. package/dist/ability/daemon.js +5 -1
  10. package/dist/ability/interop-v1.js +10 -3
  11. package/dist/ability/management.js +1 -0
  12. package/dist/agent-template/jobs.js +173 -1
  13. package/dist/agent-template/runtime.js +285 -8
  14. package/dist/agent-template/service.js +1159 -40
  15. package/dist/agent-template/types.js +2 -1
  16. package/dist/agents/baseagent-availability.js +27 -3
  17. package/dist/agents/baseagent-capability-adapter.js +102 -0
  18. package/dist/agents/baseagent-plugin-descriptor.js +274 -0
  19. package/dist/agents/baseagent-plugin-loader.js +145 -0
  20. package/dist/agents/baseagent.js +68 -2
  21. package/dist/agents/claude-gateway/agent-registration.js +389 -0
  22. package/dist/agents/claude-gateway/binding.js +96 -0
  23. package/dist/agents/claude-gateway/inbox.js +138 -0
  24. package/dist/agents/claude-gateway/index.js +125 -0
  25. package/dist/agents/claude-gateway/listing.js +330 -0
  26. package/dist/agents/claude-gateway/router.js +328 -0
  27. package/dist/agents/claude-gateway/sessions.js +128 -0
  28. package/dist/agents/claude-gateway/terminal.js +250 -0
  29. package/dist/agents/claude-gateway/transcript.js +272 -0
  30. package/dist/agents/claude-gateway/types.js +14 -0
  31. package/dist/agents/claude-runner.js +6 -10
  32. package/dist/agents/codex-runner.js +9 -2
  33. package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
  34. package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
  35. package/dist/agents/gemini/index.js +51 -0
  36. package/dist/aun/aid/control-aid.js +52 -32
  37. package/dist/aun/group/invite-service.js +6 -36
  38. package/dist/aun/group/operations.js +6 -0
  39. package/dist/aun/msg/mention-schema.js +1 -1
  40. package/dist/aun/msg/p2p.js +31 -2
  41. package/dist/aun/msg/upload.js +126 -3
  42. package/dist/build-identity.json +1 -1
  43. package/dist/channels/aun.js +1175 -457
  44. package/dist/cli/ability-command.js +42 -0
  45. package/dist/cli/agent-command.js +20 -1
  46. package/dist/cli/agent-create.js +78 -18
  47. package/dist/cli/agent-template.js +5 -3
  48. package/dist/cli/agent.js +91 -0
  49. package/dist/cli/aun-commands.js +92 -34
  50. package/dist/cli/bench.js +5 -2
  51. package/dist/cli/config.js +22 -6
  52. package/dist/cli/daemon-commands.js +245 -101
  53. package/dist/cli/directory.js +6 -1
  54. package/dist/cli/ecmsg-gateway.js +11 -9
  55. package/dist/cli/index.js +30 -5
  56. package/dist/cli/init.js +39 -63
  57. package/dist/cli/managed-command-guard.js +3 -0
  58. package/dist/cli/menu-client.js +32 -7
  59. package/dist/cli/model.js +20 -5
  60. package/dist/cli/pay-command.js +30 -0
  61. package/dist/cli/provider-command.js +6 -2
  62. package/dist/cli/quota.js +89 -0
  63. package/dist/cli/restart-monitor.js +2 -2
  64. package/dist/cli/role.js +1 -0
  65. package/dist/cli/services-command.js +12 -9
  66. package/dist/cli/team-workspace-command.js +56 -2
  67. package/dist/cli/thread-command.js +78 -12
  68. package/dist/config/access-policy.js +16 -3
  69. package/dist/config/config-field-policy.js +88 -9
  70. package/dist/config/config-manager.js +97 -47
  71. package/dist/config/config-operation-service.js +22 -1
  72. package/dist/config/gateway-config.js +9 -8
  73. package/dist/config/owner-config.js +0 -16
  74. package/dist/config/peer-role-resolver.js +1 -7
  75. package/dist/config/providers-config.js +107 -20
  76. package/dist/config/providers-management.js +45 -21
  77. package/dist/config/resolved-config-op.js +4 -44
  78. package/dist/config/schema-migration.js +78 -5
  79. package/dist/config/schema-registry.js +52 -7
  80. package/dist/config-store.js +1309 -17
  81. package/dist/core/agent-application-service.js +220 -1
  82. package/dist/core/agent-ipc-registration.js +19 -2
  83. package/dist/core/agent-reload-coordinator.js +5 -0
  84. package/dist/core/agent-runtime.js +198 -54
  85. package/dist/core/auth/agent-delegation.js +14 -0
  86. package/dist/core/auth/delegation-authorization.js +33 -26
  87. package/dist/core/auth/operation-authorizer.js +16 -1
  88. package/dist/core/auth/operation-catalog.js +59 -7
  89. package/dist/core/baseagent-loader.js +30 -3
  90. package/dist/core/capability/capability-manager.js +16 -7
  91. package/dist/core/channel-runtime.js +4 -2
  92. package/dist/core/command/agent-control.js +20 -2
  93. package/dist/core/command/agent-template-menu.js +4 -3
  94. package/dist/core/command/cli-intent-parser.js +28 -0
  95. package/dist/core/command/command-handler.js +45 -2
  96. package/dist/core/command/menu-catalog.js +20 -4
  97. package/dist/core/command/menu-file-path.js +70 -0
  98. package/dist/core/command/menu-handler.js +97 -73
  99. package/dist/core/command/menu-protocol.js +29 -0
  100. package/dist/core/command/menu-query-batch.js +2 -2
  101. package/dist/core/command/private-mention-menu.js +71 -0
  102. package/dist/core/command/remote-shell.js +565 -0
  103. package/dist/core/command/slash-handler.js +17 -26
  104. package/dist/core/command/team-workspace-bootstrap.js +2 -1
  105. package/dist/core/command/topic-slash.js +7 -1
  106. package/dist/core/daemon-bootstrap.js +0 -4
  107. package/dist/core/daemon-control.js +58 -1
  108. package/dist/core/daemon-lifecycle.js +29 -7
  109. package/dist/core/evolagent-registry.js +18 -9
  110. package/dist/core/handoff/runtime.js +1 -1
  111. package/dist/core/host-snapshot.js +8 -3
  112. package/dist/core/initialization/service.js +3 -0
  113. package/dist/core/interaction-router.js +130 -0
  114. package/dist/core/ipc-registration.js +5 -0
  115. package/dist/core/memory/consolidation-context.js +2 -1
  116. package/dist/core/memory/consolidation.js +35 -64
  117. package/dist/core/message/aun-ipc-sender.js +213 -74
  118. package/dist/core/message/aun-request-registry.js +31 -0
  119. package/dist/core/message/contact-admission.js +91 -6
  120. package/dist/core/message/contact-pending-inbound.js +113 -0
  121. package/dist/core/message/contact-thread-approval.js +212 -0
  122. package/dist/core/message/im-renderer.js +40 -1
  123. package/dist/core/message/message-admission.js +5 -39
  124. package/dist/core/message/message-bridge.js +197 -45
  125. package/dist/core/message/message-log.js +32 -0
  126. package/dist/core/message/message-queue.js +102 -18
  127. package/dist/core/message/peer-mode.js +15 -4
  128. package/dist/core/message/response-engine.js +174 -26
  129. package/dist/core/message/send-options.js +37 -3
  130. package/dist/core/message/send-routing.js +11 -7
  131. package/dist/core/model/config-scope.js +6 -14
  132. package/dist/core/model/model-catalog.js +5 -5
  133. package/dist/core/model/model-diagnostics.js +19 -0
  134. package/dist/core/model/model-fallback.js +13 -2
  135. package/dist/core/ownership/owner-resolver.js +12 -86
  136. package/dist/core/pack-auth.js +7 -0
  137. package/dist/core/pack-install.js +1 -1
  138. package/dist/core/permission/ec-command-parser.js +288 -77
  139. package/dist/core/permission/protected-paths.js +64 -9
  140. package/dist/core/permission/services-path-acl.js +458 -0
  141. package/dist/core/permission/tool-policy.js +26 -10
  142. package/dist/core/relation/peer-identity.js +13 -0
  143. package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
  144. package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
  145. package/dist/core/session/session-manager.js +47 -10
  146. package/dist/core/session/session-mapper.js +16 -0
  147. package/dist/core/skill/index-generator.js +2 -3
  148. package/dist/core/skill/switch-resolver.js +3 -0
  149. package/dist/core/task/task-recovery-service.js +1 -0
  150. package/dist/core/thread/command-parser.js +4 -1
  151. package/dist/core/thread/ipc-operation.js +4 -2
  152. package/dist/core/thread/thread-operation.js +25 -10
  153. package/dist/core/thread/thread-service.js +294 -55
  154. package/dist/core/thread/topic-id.js +67 -2
  155. package/dist/core/thread/types.js +15 -1
  156. package/dist/directory/owner-directory-admission.js +11 -8
  157. package/dist/directory/owner-directory-cache.js +19 -0
  158. package/dist/directory/owner-directory-markdown.js +1 -1
  159. package/dist/directory/owner-directory-policy.js +5 -30
  160. package/dist/directory/owner-directory-request-operation.js +5 -2
  161. package/dist/eck/kit-renderer.js +3 -2
  162. package/dist/eck/message-renderer.js +28 -5
  163. package/dist/ecweb/basic-settings-service.js +5 -9
  164. package/dist/ecweb/providers-service.js +4 -2
  165. package/dist/ecweb/runtime/supervisor.js +36 -8
  166. package/dist/event-center/center-config.js +9 -5
  167. package/dist/event-center/dispatcher.js +10 -1
  168. package/dist/event-center/ipc-operation.js +19 -0
  169. package/dist/event-center/registry.js +20 -5
  170. package/dist/event-center/runtime.js +10 -7
  171. package/dist/index.js +120 -41
  172. package/dist/ipc.js +83 -3
  173. package/dist/outputs/authorization.js +16 -0
  174. package/dist/outputs/cards.js +336 -0
  175. package/dist/outputs/events.js +3 -2
  176. package/dist/outputs/protocol.js +1 -0
  177. package/dist/outputs/service.js +2 -15
  178. package/dist/paths.js +48 -1
  179. package/dist/pay/command.js +38 -0
  180. package/dist/pay/protocol.js +136 -0
  181. package/dist/pay/runtime.js +188 -0
  182. package/dist/pay/service.js +384 -0
  183. package/dist/pay/store.js +81 -0
  184. package/dist/response-system/engines/v1/proactive-flow.js +29 -2
  185. package/dist/services/dispatcher.js +23 -5
  186. package/dist/services/host/main.js +388 -0
  187. package/dist/services/host/protocol.js +118 -0
  188. package/dist/services/host/resident.js +310 -0
  189. package/dist/services/host-client.js +386 -0
  190. package/dist/services/host-deploy.js +180 -0
  191. package/dist/services/host-launch.js +117 -0
  192. package/dist/services/host-recycle.js +203 -0
  193. package/dist/services/host-runtime.js +802 -0
  194. package/dist/services/idempotency.js +44 -86
  195. package/dist/services/index-generator.js +4 -3
  196. package/dist/services/index.js +204 -22
  197. package/dist/services/ipc-operation.js +288 -44
  198. package/dist/services/pack-manager.js +1 -0
  199. package/dist/services/script-runner.js +515 -83
  200. package/dist/services/service-payload.js +13 -7
  201. package/dist/services/validation.js +109 -4
  202. package/dist/stats/budget.js +1 -1
  203. package/dist/stats/model-resolver.js +2 -2
  204. package/dist/stats/quota-query.js +95 -0
  205. package/dist/trigger/application-service.js +6 -4
  206. package/dist/trigger/local-files.js +19 -9
  207. package/dist/trigger/scheduler.js +22 -12
  208. package/dist/trigger/script-sandbox.js +51 -8
  209. package/dist/utils/aid-bind.js +3 -0
  210. package/dist/utils/atomic-write.js +22 -8
  211. package/dist/utils/evolcore-version.js +2 -2
  212. package/dist/utils/host-info.js +173 -1
  213. package/dist/utils/logger.js +2 -2
  214. package/dist/utils/media-cache.js +190 -43
  215. package/dist/utils/npm-ops.js +43 -8
  216. package/dist/utils/restart-safety.js +14 -1
  217. package/dist/utils/system-memory.js +113 -25
  218. package/dist/utils/systemd-lifecycle.js +154 -0
  219. package/dist/utils/windows-shell-trust.js +7 -3
  220. package/dist/workbench/service.js +1 -1
  221. package/kits/docs/INDEX.md +3 -2
  222. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
  223. package/kits/docs/channels/aun.md +1 -1
  224. package/kits/docs/evolcore/INDEX.md +9 -6
  225. package/kits/docs/evolcore/agent.md +36 -1
  226. package/kits/docs/evolcore/aid.md +45 -3
  227. package/kits/docs/evolcore/config.md +5 -2
  228. package/kits/docs/evolcore/directory.md +8 -9
  229. package/kits/docs/evolcore/group.md +2 -1
  230. package/kits/docs/evolcore/memory-tags.md +2 -0
  231. package/kits/docs/evolcore/menu-client.md +3 -3
  232. package/kits/docs/evolcore/menu-protocol.md +7 -0
  233. package/kits/docs/evolcore/model.md +3 -0
  234. package/kits/docs/evolcore/msg.md +77 -10
  235. package/kits/docs/evolcore/pay.md +34 -0
  236. package/kits/docs/evolcore/provider.md +22 -1
  237. package/kits/docs/evolcore/quota.md +54 -0
  238. package/kits/docs/evolcore/role.md +3 -0
  239. package/kits/docs/evolcore/services.md +46 -18
  240. package/kits/docs/evolcore/stats.md +2 -0
  241. package/kits/docs/evolcore/thread-chain.md +2 -0
  242. package/kits/docs/evolcore/tool-authorization.md +10 -0
  243. package/kits/docs/evolcore/trigger.md +2 -0
  244. package/kits/rules/01-overview.md +11 -32
  245. package/kits/rules/02-navigation.md +7 -0
  246. package/kits/rules/06-channel.md +3 -3
  247. package/kits/schemas/_meta.json +38 -5
  248. package/kits/schemas/agent-config.schema.20.json +24 -0
  249. package/kits/schemas/agent-config.schema.21.json +974 -0
  250. package/kits/schemas/agent-config.schema.22.json +977 -0
  251. package/kits/schemas/agent-config.schema.23.json +958 -0
  252. package/kits/schemas/daemon.schema.10.json +373 -0
  253. package/kits/schemas/daemon.schema.9.json +12 -0
  254. package/kits/schemas/defaults.schema.7.json +472 -0
  255. package/kits/schemas/providers.schema.3.json +18 -2
  256. package/kits/schemas/relation-config.schema.13.json +289 -0
  257. package/kits/skills/.switches.json +17 -1
  258. package/kits/skills/ability/SKILL.md +229 -34
  259. package/kits/skills/ability/STRUCTURE.md +333 -0
  260. package/kits/skills/ability/references/cli.md +208 -0
  261. package/kits/skills/ability/references/development.md +107 -37
  262. package/kits/skills/ability/references/management.md +106 -46
  263. package/kits/skills/ability/references/runtime-protocol.md +65 -63
  264. package/kits/skills/agent-output-cards/SKILL.md +64 -0
  265. package/kits/skills/ec-group/SKILL.md +8 -6
  266. package/kits/skills/ec-group/TASK.md +186 -0
  267. package/kits/skills/ec-group/WORKLOG.md +180 -0
  268. package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
  269. package/kits/skills/ec-pay/SKILL.md +101 -0
  270. package/kits/skills/ec-pay/references/pay-cli.md +110 -0
  271. package/kits/skills/ec-provider/SKILL.md +58 -9
  272. package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
  273. package/kits/skills/ec-service-call/SKILL.md +135 -0
  274. package/kits/skills/ec-service-pack/SKILL.md +277 -0
  275. package/kits/skills/ec-trigger/SKILL.md +1 -1
  276. package/kits/templates/memory-consolidation/notes.md +2 -2
  277. package/kits/templates/memory-consolidation/workflow.md +46 -0
  278. package/kits/templates/roles/visitor.json +1 -0
  279. package/kits/templates/system-fragments/channel.md +13 -4
  280. package/kits/templates/system-fragments/commands.md +5 -3
  281. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  282. package/kits/templates/system-fragments/reply.md +1 -0
  283. package/kits/templates/system-fragments/session.md +1 -1
  284. package/kits/templates/system-fragments/thread.md +27 -128
  285. package/kits/templates/system-fragments/venue.md +27 -0
  286. package/package.json +4 -5
  287. package/scripts/agent-template/inspect.mjs +79 -29
  288. package/scripts/agent-template/overlay.mjs +20 -2
  289. package/scripts/agent-template/shared/common.mjs +24 -6
  290. package/scripts/agent-template/shared/team-schema.json +23 -5
  291. package/scripts/agent-template/shared/template-contract.mjs +107 -17
  292. package/scripts/agent-template/shared/template-package.mjs +254 -29
  293. package/scripts/agent-template/shared/template-runtime.mjs +145 -2
  294. package/scripts/agent-template/shared/template.mjs +67 -9
  295. package/scripts/agent-template/team-pack.mjs +132 -41
  296. package/scripts/agent-template/team-preview.mjs +249 -5
  297. package/kits/docs/aun/ABILITY_CALLING.md +0 -280
  298. package/kits/docs/evolcore/ability.md +0 -185
  299. package/kits/skills/ability/references/calling.md +0 -56
  300. package/kits/skills/ability/references/contract-checklist.md +0 -37
  301. package/kits/skills/ability/references/recovery.md +0 -27
  302. /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
@@ -1,11 +1,22 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
- import { atomicWriteJson } from '../utils/atomic-write.js';
4
+ import { atomicWriteJson, withFileLock } from '../utils/atomic-write.js';
5
5
  import { resolveRoot } from '../paths.js';
6
6
  import { templateError } from './types.js';
7
7
  export const TEMPLATE_JOB_ID = /^job_[a-f0-9-]{36}$/;
8
8
  export const TEMPLATE_PREVIEW_ID = /^preview_[a-f0-9-]{36}$/;
9
+ export function compareTemplateVersions(left, right) {
10
+ const version = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
11
+ if (!version.test(left) || !version.test(right))
12
+ throw templateError('VERSION_MISSING', 'Three numeric author member version components required');
13
+ const a = left.split('.').map(BigInt);
14
+ const b = right.split('.').map(BigInt);
15
+ for (let i = 0; i < 3; i++)
16
+ if (a[i] !== b[i])
17
+ return a[i] > b[i] ? 1 : -1;
18
+ return 0;
19
+ }
9
20
  export function templateFingerprint(value) {
10
21
  return createHash('sha256').update(JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)
11
22
  ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item)).digest('hex');
@@ -31,6 +42,20 @@ export function writeTemplateState(file, value) {
31
42
  }
32
43
  }
33
44
  }
45
+ /** Copy the transport receipt before outbox retirement; acceptance never marks the App notification read. */
46
+ export function recordTemplateNoticeReceipt(root, noticeId, ownerAid, messageId, outboxId) {
47
+ if (!/^notice_[a-f0-9]{64}$/.test(noticeId))
48
+ throw templateError('INVALID_ARGUMENT', 'Invalid update notice receipt');
49
+ const jobs = new TemplateJobs(root);
50
+ const file = path.join(jobs.directory, 'notifications', noticeId + '.json');
51
+ jobs.assertTeamPath(file);
52
+ if (!fs.existsSync(file))
53
+ return;
54
+ const notice = JSON.parse(fs.readFileSync(file, 'utf8'));
55
+ if (notice.ownerAid !== ownerAid || notice.noticeId !== noticeId)
56
+ throw templateError('NOT_ALLOWED', 'Notice receipt route differs');
57
+ writeTemplateState(file, { ...notice, delivery: 'accepted', status: 'transport-accepted', messageId, outboxId });
58
+ }
34
59
  export class TemplateJobs {
35
60
  root;
36
61
  directory;
@@ -86,6 +111,12 @@ export class TemplateJobs {
86
111
  return this.read(JSON.parse(fs.readFileSync(requestFile, 'utf8')).jobId);
87
112
  return this.list().find(job => job.actor === actor && job.requestId === requestId);
88
113
  }
114
+ requestMatches(actor, requestId, action, args) {
115
+ const file = path.join(this.directory, 'requests', templateFingerprint({ actor, requestId }) + '.json');
116
+ const fingerprint = templateFingerprint({ action, args });
117
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')).fingerprint === fingerprint
118
+ : this.original(actor, requestId)?.fingerprint === fingerprint;
119
+ }
89
120
  bindRequest(actor, requestId, action, args, jobId) {
90
121
  const file = path.join(this.directory, 'requests', templateFingerprint({ actor, requestId }) + '.json');
91
122
  const fingerprint = templateFingerprint({ action, args });
@@ -151,6 +182,147 @@ export class TemplateJobs {
151
182
  for (const { aid, file } of files)
152
183
  writeTemplateState(file, { aid, jobId: job.jobId });
153
184
  }
185
+ installationFile(aid) {
186
+ if (!/^[a-z0-9][a-z0-9_-]*(\.[a-z0-9-]+)+$/.test(aid))
187
+ throw templateError('INVALID_ARGUMENT', 'Invalid target AID');
188
+ const file = path.join(this.root, 'agents', aid, 'template.lock.json');
189
+ this.assertTeamPath(file);
190
+ return file;
191
+ }
192
+ /** A staged lock never exposes its candidate as an installed version before commit. */
193
+ installation(aid) {
194
+ const file = this.installationFile(aid);
195
+ if (!fs.existsSync(file))
196
+ return null;
197
+ const lock = JSON.parse(fs.readFileSync(file, 'utf8'));
198
+ if (lock.schemaVersion !== 2)
199
+ return null;
200
+ const value = lock.pending && this.read(lock.pending.jobId).committed === true
201
+ ? lock.pending.installation : lock.installation;
202
+ if (!value)
203
+ return null;
204
+ if (value.targetAid !== aid || !value.source || !value.baseline
205
+ || value.committedJobId && (this.read(value.committedJobId).committed !== true
206
+ || !Object.values(this.read(value.committedJobId).members).some(member => member.aid === aid))) {
207
+ throw templateError('RECOVERY_REQUIRED', 'Installed template provenance is invalid');
208
+ }
209
+ return value;
210
+ }
211
+ /** The slot reservation and request/job link share a cross-process admission lock. */
212
+ withTeams(run) {
213
+ this.assertTeamPath(path.join(this.directory, 'teams', 'state.lock'));
214
+ return withFileLock(path.join(this.directory, 'teams', 'state.lock'), run);
215
+ }
216
+ teamFile(id) {
217
+ if (!/^team_[a-f0-9]{64}$/.test(id))
218
+ throw templateError('INVALID_ARGUMENT', 'Invalid instanceId');
219
+ const file = path.join(this.directory, 'teams', id, 'instance.json');
220
+ this.assertTeamPath(file);
221
+ return file;
222
+ }
223
+ listTeams() {
224
+ const directory = path.join(this.directory, 'teams');
225
+ if (!fs.existsSync(directory))
226
+ return [];
227
+ return fs.readdirSync(directory, { withFileTypes: true }).filter(entry => /^team_[a-f0-9]{64}$/.test(entry.name))
228
+ .map(entry => {
229
+ this.assertTeamPath(path.join(directory, entry.name, 'instance.json'));
230
+ return this.readTeam(entry.name);
231
+ });
232
+ }
233
+ /** Fixed paths below the runtime root cannot traverse links or non-directory ancestors. */
234
+ assertTeamPath(file) {
235
+ const root = path.resolve(this.root);
236
+ const target = path.resolve(file);
237
+ const relative = path.relative(root, target);
238
+ if (relative.startsWith('..' + path.sep) || relative === '..' || path.isAbsolute(relative))
239
+ throw templateError('UNSAFE_DEFINITION_PATH', 'Team definition leaves the runtime root');
240
+ let current = root;
241
+ for (const segment of ['', ...relative.split(path.sep)]) {
242
+ current = segment ? path.join(current, segment) : current;
243
+ const stat = fs.lstatSync(current, { throwIfNoEntry: false });
244
+ if (stat?.isSymbolicLink() || stat && current !== target && !stat.isDirectory()) {
245
+ throw templateError('UNSAFE_DEFINITION_PATH', 'Team paths must use ordinary directories and files');
246
+ }
247
+ }
248
+ }
249
+ definitionFiles() {
250
+ const directory = path.join(this.directory, 'team-definitions');
251
+ this.assertTeamPath(directory);
252
+ if (!fs.existsSync(directory))
253
+ return [];
254
+ if (!fs.lstatSync(directory).isDirectory())
255
+ throw templateError('UNSAFE_DEFINITION_PATH', 'Team definitions must be a directory');
256
+ const files = fs.readdirSync(directory).filter(name => name.endsWith('.json')).sort();
257
+ if (files.length > 1000)
258
+ throw templateError('INVALID_ARGUMENT', 'Too many Team definitions');
259
+ return files;
260
+ }
261
+ readDefinition(file) {
262
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}\.json$/.test(file))
263
+ throw templateError('UNSAFE_DEFINITION_PATH', 'Invalid Team definition filename');
264
+ const target = path.join(this.directory, 'team-definitions', file);
265
+ this.assertTeamPath(target);
266
+ const before = fs.lstatSync(target);
267
+ if (!before.isFile() || before.nlink !== 1 || before.size > 1024 * 1024)
268
+ throw templateError('UNSAFE_DEFINITION_PATH', 'A bounded ordinary Team definition file is required');
269
+ if (process.platform !== 'win32' && (before.mode & 0o077) !== 0)
270
+ throw templateError('UNSAFE_DEFINITION_PERMISSIONS', 'Team definition must be private (0600)');
271
+ const handle = fs.openSync(target, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
272
+ try {
273
+ const opened = fs.fstatSync(handle);
274
+ if (before.ino !== opened.ino || before.dev !== opened.dev)
275
+ throw templateError('SOURCE_CHANGED', 'Team definition changed while opening');
276
+ const content = fs.readFileSync(handle, 'utf8');
277
+ const after = fs.fstatSync(handle);
278
+ this.assertTeamPath(target);
279
+ const present = fs.lstatSync(target);
280
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs
281
+ || present.ino !== after.ino || present.dev !== after.dev)
282
+ throw templateError('SOURCE_CHANGED', 'Team definition changed while reading');
283
+ return JSON.parse(content);
284
+ }
285
+ finally {
286
+ fs.closeSync(handle);
287
+ }
288
+ }
289
+ readTeam(id) {
290
+ const file = this.teamFile(id);
291
+ if (!fs.existsSync(file))
292
+ throw templateError('NOT_FOUND', 'Team instance not found');
293
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
294
+ if (value.version !== 1 || value.instanceId !== id || !Array.isArray(value.members)
295
+ || !/^sha256:[a-f0-9]{64}$/.test(value.revision))
296
+ throw templateError('RECOVERY_REQUIRED', 'Invalid team instance');
297
+ return value;
298
+ }
299
+ saveTeam(team, expectedRevision) {
300
+ const file = this.teamFile(team.instanceId);
301
+ if (fs.existsSync(file) && this.readTeam(team.instanceId).revision !== expectedRevision) {
302
+ throw templateError('CONFLICT', 'Team revision changed');
303
+ }
304
+ const { revision: _revision, ...content } = team;
305
+ team.updatedAt = Date.now();
306
+ team.revision = 'sha256:' + templateFingerprint({ ...content, updatedAt: team.updatedAt });
307
+ writeTemplateState(file, team);
308
+ }
309
+ installFile(id) {
310
+ if (!/^member_install_[a-f0-9-]{36}$/.test(id))
311
+ throw templateError('INVALID_ARGUMENT', 'Invalid memberInstallId');
312
+ return path.join(this.directory, 'member-installs', id + '.json');
313
+ }
314
+ readMemberInstall(actor, id) {
315
+ const file = this.installFile(id);
316
+ if (!fs.existsSync(file))
317
+ throw templateError('NOT_FOUND', 'Member installation not found');
318
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
319
+ if (value.memberInstallId !== id || value.actor !== actor)
320
+ throw templateError('NOT_FOUND', 'Member installation not found');
321
+ return value;
322
+ }
323
+ saveMemberInstall(value) {
324
+ writeTemplateState(this.installFile(value.memberInstallId), value);
325
+ }
154
326
  }
155
327
  /** Durable installation associations are checked before ordinary task dispatch. */
156
328
  export function templateInstallationGate(aid, expectedJobId, root = resolveRoot()) {
@@ -14,7 +14,7 @@ import path from 'node:path';
14
14
  import { createHash } from 'node:crypto';
15
15
  import { stringify } from 'yaml';
16
16
  import { validateAgentMdDocument, StorageLowLevel, StorageVFS } from '@agentunion/fastaun';
17
- import { resolveBaseagentModelSelection, resolveLegacyBaseagentModelSelection } from '../agents/baseagent.js';
17
+ import { listSupportedBaseagents, resolveBaseagentModelSelection, resolveLegacyBaseagentModelSelection } from '../agents/baseagent.js';
18
18
  import { ownerResolver, getDaemonOwners } from '../core/ownership/owner-resolver.js';
19
19
  import { resolvePaths, getPackageRoot } from '../paths.js';
20
20
  import { loadAgent, loadDaemonConfig } from '../config-store.js';
@@ -30,7 +30,110 @@ import { refreshSkillIndex } from '../core/skill/startup.js';
30
30
  import { TemplateJobs, templateFingerprint, writeTemplateState, assertTemplateInstallationReady, templateInstallationGate } from './jobs.js';
31
31
  import { getAidStore, loadClient } from '../aun/aid/store.js';
32
32
  import { creationOwnershipBinding } from '../core/ownership/owner-resolver.js';
33
+ import { readTeamMembersState, mutateTeamMembers } from '../core/command/team-workspace-team.js';
34
+ import { logger } from '../utils/logger.js';
35
+ import { getAunRequestRegistry } from '../core/message/aun-request-registry.js';
36
+ import { withFileLock } from '../utils/atomic-write.js';
37
+ import * as outbox from '../aun/outbox.js';
33
38
  const publicTemplate = await import(new URL('../../scripts/agent-template/shared/template-runtime.mjs', import.meta.url).href);
39
+ /** Host-owned transport and persisted service jobs; never borrows the Owner's identity. */
40
+ export function createTemplateUpdateCatalog(root, getControl) {
41
+ const jobs = new TemplateJobs(root);
42
+ return async (source, action, args, operationId) => {
43
+ const configFile = path.join(jobs.directory, 'catalogs.json');
44
+ jobs.assertTeamPath(configFile);
45
+ if (!fs.existsSync(configFile))
46
+ throw templateError('CATALOG_UNAVAILABLE', 'Configure a trusted template catalog in data/template/catalogs.json');
47
+ const stat = fs.statSync(configFile);
48
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > 64 * 1024 || process.platform !== 'win32' && (stat.mode & 0o077)) {
49
+ throw templateError('UNTRUSTED_CATALOG_CONFIG', 'Trusted catalog configuration must be a private ordinary file (0600)');
50
+ }
51
+ const config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
52
+ if (config.schemaVersion !== 1 || Object.keys(config).some(key => !['schemaVersion', 'catalogs'].includes(key))
53
+ || !Array.isArray(config.catalogs) || config.catalogs.some((entry) => !isValidAid(entry.aid)
54
+ || Object.keys(entry).some(key => !['aid', 'publishers'].includes(key)) || !Array.isArray(entry.publishers)
55
+ || !entry.publishers.length || entry.publishers.some((aid) => !isValidAid(aid)))) {
56
+ throw templateError('UNTRUSTED_CATALOG_CONFIG', 'Invalid trusted catalog declaration');
57
+ }
58
+ if (!config.catalogs.some((entry) => entry.aid === source.catalogAid && entry.publishers.includes(source.publisher))) {
59
+ throw templateError('UNTRUSTED_SOURCE', 'The catalog and publisher have not been explicitly trusted on this Host');
60
+ }
61
+ const channel = getControl();
62
+ const selfAid = channel?.getAid();
63
+ if (!channel?.isConnected() || !selfAid)
64
+ throw templateError('AUN_DISCONNECTED', 'Real Host Control connection required');
65
+ if (action === 'download' && args.targetHostAid !== selfAid)
66
+ throw templateError('NOT_ALLOWED', 'Download authorization must name the actual calling Host');
67
+ const fingerprint = templateFingerprint({ source, action, args, operationId, selfAid });
68
+ const file = path.join(jobs.directory, 'catalog-calls', fingerprint + '.json');
69
+ return withFileLock(file + '.lock', async () => {
70
+ const state = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : { fingerprint, selfAid };
71
+ const registry = getAunRequestRegistry();
72
+ const rpc = async (type, data, initial = false) => {
73
+ let request = initial && state.requestId ? registry.get(selfAid, state.requestId) : undefined;
74
+ if (request && (request.state !== 'completed' && (request.deadlineAt ?? 0) <= Date.now()
75
+ || request.state === 'completed' && request.responsePayload?.ok !== true))
76
+ request = undefined;
77
+ if (!request) {
78
+ const prepared = registry.prepare({ selfAid, targetAid: source.catalogAid, timeoutMs: 20_000,
79
+ payload: { type, ...data, service_deadline_at_ms: Date.now() + 20_000 } });
80
+ if (initial) {
81
+ state.requestId = prepared.requestId;
82
+ state.requestIds = [...(state.requestIds ?? []), prepared.requestId];
83
+ writeTemplateState(file, state);
84
+ }
85
+ registry.markSending(selfAid, prepared.requestId);
86
+ const sent = await channel.sendDaemonMsg({ to: source.catalogAid, payload: prepared.payload, encrypt: true,
87
+ ttl: 20, service: { type, requestId: prepared.requestId } });
88
+ if (!sent.ok) {
89
+ registry.markFailed(selfAid, prepared.requestId, sent.error ?? 'send failed');
90
+ if (initial) {
91
+ delete state.requestId;
92
+ writeTemplateState(file, state);
93
+ }
94
+ throw templateError(String(sent.code ?? 'CATALOG_SEND_FAILED'), sent.error ?? 'Catalog request failed');
95
+ }
96
+ if (sent.message_id)
97
+ registry.markTransportAccepted(selfAid, prepared.requestId, sent.message_id, sent.status);
98
+ request = registry.get(selfAid, prepared.requestId);
99
+ }
100
+ if (request?.state !== 'completed')
101
+ request = await registry.wait(selfAid, request.requestId, 20_000);
102
+ if (!request || request.state !== 'completed' || !request.responsePayload) {
103
+ throw templateError('CATALOG_PENDING', 'Catalog reply pending; resume the original job', { requestId: request?.requestId, callerAid: selfAid, catalogAid: source.catalogAid });
104
+ }
105
+ const response = request.responsePayload;
106
+ if (response.type !== type + '.result')
107
+ throw templateError('INVALID_CATALOG', 'Registry response type differs from the request');
108
+ if (response.ok !== true)
109
+ throw templateError(response.error?.code ?? 'CATALOG_FAILED', response.error?.message ?? 'Catalog service rejected the actual Host Caller', { callerAid: selfAid, catalogAid: source.catalogAid, requestId: request.requestId });
110
+ return response.data;
111
+ };
112
+ if (!state.businessJobId) {
113
+ const accepted = await rpc('services.templates.' + action, { ...args, operationId: 'core-' + fingerprint }, true);
114
+ if (!/^[a-f0-9]{64}$/.test(accepted?.jobId ?? ''))
115
+ throw templateError('INVALID_CATALOG', 'Persistent Registry jobId required');
116
+ state.businessJobId = accepted.jobId;
117
+ writeTemplateState(file, state);
118
+ }
119
+ const deadline = Date.now() + 25_000;
120
+ do {
121
+ const response = await rpc('services.templates.status', { jobId: state.businessJobId });
122
+ if (response.jobId !== state.businessJobId)
123
+ throw templateError('INVALID_CATALOG', 'Registry status refers to another job');
124
+ if (response.state === 'completed') {
125
+ if (response.ok !== true)
126
+ throw templateError(response.error?.code ?? 'CATALOG_FAILED', 'Registry operation failed for the real Host Caller', { callerAid: selfAid, catalogAid: source.catalogAid, serviceJobId: response.jobId });
127
+ return response.result;
128
+ }
129
+ if (!['queued', 'running'].includes(response.state))
130
+ throw templateError('INVALID_CATALOG', 'Unknown Registry job state');
131
+ await new Promise(resolve => setTimeout(resolve, 250));
132
+ } while (Date.now() < deadline);
133
+ throw templateError('CATALOG_PENDING', 'Registry job remains pending; resume the original job', { callerAid: selfAid, catalogAid: source.catalogAid, serviceJobId: state.businessJobId });
134
+ });
135
+ };
136
+ }
34
137
  /** Fence collection workers before runners or Trigger schedulers are loaded. */
35
138
  export async function restoreTemplatesBeforeStartup(root) {
36
139
  const blocked = new Set();
@@ -75,6 +178,12 @@ export async function restoreTemplatesBeforeStartup(root) {
75
178
  }
76
179
  jobs.save(job);
77
180
  }
181
+ else if (job.action === 'preview-update') {
182
+ job.status = 'paused';
183
+ job.resumable = true;
184
+ job.error = { code: 'RECOVERY_REQUIRED', message: 'Resume the original fixed-candidate preview', retryable: true };
185
+ jobs.save(job);
186
+ }
78
187
  else if (job.action === 'deploy' && !job.committed) {
79
188
  if (!job.checkpoint.restored)
80
189
  for (const aid of templateJobAids(job)) {
@@ -262,13 +371,15 @@ export function createTemplateIdentityTransport(job) {
262
371
  }
263
372
  const FIELDS = ['name', 'description', 'avatar', 'tags', 'exttype'];
264
373
  /** Only public behavior and runner model choices may enter collection checkpoints. */
265
- export function resolveTemplateSourceConfig(effective, scope = {}) {
266
- const source = { baseagents: {} };
374
+ export function resolveTemplateSourceConfig(effective, scope = {}, declaration = {}) {
375
+ const source = { ...publicTemplate.resolveMemberParameters({ config: effective }), baseagents: {} };
267
376
  for (const field of ['chatmode', 'memory', 'active_baseagent']) {
268
377
  if (effective[field] !== undefined)
269
378
  source[field] = structuredClone(effective[field]);
270
379
  }
271
- for (const name of ['claude', 'codex', 'gemini', 'ecagent']) {
380
+ if (Object.hasOwn(declaration, 'access'))
381
+ source.access = publicTemplate.validateAccessDeclaration(declaration.access);
382
+ for (const name of listSupportedBaseagents()) {
272
383
  const configured = effective.baseagents?.[name];
273
384
  if (!configured || typeof configured !== 'object' || Array.isArray(configured))
274
385
  continue;
@@ -385,6 +496,56 @@ export async function authorizeTemplateOwner(actor, aid, recoveryJobId) {
385
496
  throw templateError('NOT_ALLOWED', 'Agent Owner required', { reason: 'AGENT_OWNER_REQUIRED' });
386
497
  }
387
498
  }
499
+ /** Read-only startup evidence. A file cannot grant Owner or Host-control privileges. */
500
+ export async function verifyTemplateDefinitionOwner(aid, expectedOwner) {
501
+ let owner;
502
+ try {
503
+ owner = await ownerResolver.refreshForAuthorization(aid);
504
+ }
505
+ catch (error) {
506
+ throw templateError('OWNERSHIP_UNAVAILABLE', 'Fresh Team ownership could not be checked', { cause: error.code ?? error.message });
507
+ }
508
+ if (owner.refreshFailure || owner.consensusStatus !== 'consensus') {
509
+ throw templateError('OWNERSHIP_UNAVAILABLE', 'Fresh Team ownership consensus is temporarily unavailable');
510
+ }
511
+ if (owner.ownerAid !== expectedOwner)
512
+ throw templateError('NOT_ALLOWED', 'Team definition differs from the current protocol Owner');
513
+ }
514
+ /** Read actual Owner publication through each live member's authorized directory cache. Never accepts an App ACK. */
515
+ export async function verifyTemplateMemberDirectory(team, member) {
516
+ const snapshots = {};
517
+ const revisions = new Set();
518
+ for (const self of team.members.filter(value => value.aid)) {
519
+ const cache = liveOwnerDirectoryCache(self.aid);
520
+ if (!cache)
521
+ throw templateError('OWNER_DIRECTORY_PENDING', 'A member directory is not connected');
522
+ const fetched = await cache.fetchToSharedCache({});
523
+ if (!await cache.applyFromSharedCache())
524
+ throw templateError('OWNER_DIRECTORY_PENDING', 'Fresh Owner publication could not be applied');
525
+ const document = fetched.contacts;
526
+ const snapshot = cache.readSnapshot('contacts');
527
+ if (!snapshot || !document?.contentDigest || snapshot.contentDigest !== document.contentDigest
528
+ || snapshot.sourceRevision !== document.raw.source_revision || snapshot.ownerAid !== team.ownerAid || !snapshot.sourceRevision
529
+ || !snapshot.openPaContext?.includes(member.aid))
530
+ throw templateError('OWNER_DIRECTORY_PENDING', 'Fresh Owner publication has not been observed');
531
+ for (const other of team.members.filter(value => value.aid)) {
532
+ if (snapshot.blockedAids?.includes(other.aid))
533
+ throw templateError('CONTACT_BLOCKED', 'An original Team member is blocked');
534
+ if (other.aid === self.aid)
535
+ continue;
536
+ const membership = readOwnerDirectoryMembership(self.aid, other.aid, true);
537
+ if (!membership || membership.blocked || membership.scopeExcluded
538
+ || !['agent', 'assistant'].includes(membership.category) || membership.category !== 'assistant' && membership.internal !== true) {
539
+ throw templateError('OWNER_DIRECTORY_PENDING', 'Team membership is not in the current Owner directory');
540
+ }
541
+ }
542
+ snapshots[self.aid] = snapshot.snapshotId;
543
+ revisions.add(snapshot.sourceRevision);
544
+ }
545
+ if (revisions.size !== 1)
546
+ throw templateError('OWNER_DIRECTORY_PENDING', 'Members have different Owner directory revisions');
547
+ return { revision: [...revisions][0], snapshots };
548
+ }
388
549
  export function createAgentTemplateRuntime(options) {
389
550
  const paths = resolvePaths();
390
551
  const requireHost = () => {
@@ -419,28 +580,139 @@ export function createAgentTemplateRuntime(options) {
419
580
  projectPath: agent.projectPath, runtimeStatus: agent.status, providers: providers.providers,
420
581
  publisher: { aid: actor }, skills: resolveAllSkillStates(path.join(paths.agentsDir, aid)).map(s => ({ name: s.name, type: s.source, enabled: s.enabled })) };
421
582
  };
422
- return new AgentTemplateService({
583
+ const service = new AgentTemplateService({
423
584
  root: paths.root, hostAid: loadDaemonConfig().aid ?? '', authorize: authorizeTemplateOwner,
424
585
  source: async (aid, actor) => {
425
- const { targetConfig: _raw, effectiveConfig, providers, ...source } = await context(aid, actor);
426
- return { ...source, effectiveConfig: resolveTemplateSourceConfig(effectiveConfig),
586
+ const { targetConfig: raw, effectiveConfig, providers, ...source } = await context(aid, actor);
587
+ return { ...source, effectiveConfig: resolveTemplateSourceConfig(effectiveConfig, {}, raw),
427
588
  providers: Object.fromEntries(Object.entries(providers).map(([id, value]) => [id, { name: value.name }])) };
428
589
  }, target: context,
429
590
  installation: createInstallationDependencies(options),
591
+ discovery: {
592
+ verifyHost: async (ownerAid, hostAid) => {
593
+ if (loadDaemonConfig().aid !== hostAid || requireHost().getAid() !== hostAid)
594
+ throw templateError('NOT_ALLOWED', 'Team definition must target the current Host identity');
595
+ await verifyTemplateDefinitionOwner(hostAid, ownerAid);
596
+ },
597
+ member: async (aid, ownerAid, hostAid) => {
598
+ if (requireHost().getAid() !== hostAid)
599
+ throw templateError('NOT_ALLOWED', 'Original Host identity changed');
600
+ const agent = options.registry.get(aid);
601
+ const raw = loadAgent(aid);
602
+ if (!agent || !raw || raw.aid !== aid || !path.isAbsolute(agent.projectPath ?? ''))
603
+ throw templateError('NOT_FOUND', 'Definition member is not available on this Host');
604
+ assertTemplateInstallationReady(aid);
605
+ await verifyTemplateDefinitionOwner(aid, ownerAid);
606
+ let card;
607
+ try {
608
+ card = await profile(aid);
609
+ }
610
+ catch (error) {
611
+ throw templateError('PROFILE_UNAVAILABLE', 'Definition member profile is temporarily unavailable', { cause: error.code ?? error.message });
612
+ }
613
+ return { targetAid: aid, projectPath: agent.projectPath, targetConfig: raw, profile: card.profile };
614
+ },
615
+ },
616
+ resolveMemberRelease: options.resolveMemberRelease,
617
+ updates: {
618
+ targets: () => options.registry.allAgents().map(agent => ({ aid: agent.aid, projectPath: agent.projectPath,
619
+ mode: loadAgent(agent.aid)?.update?.mode })),
620
+ context: async (aid) => {
621
+ const agent = options.registry.get(aid);
622
+ const config = loadAgent(aid);
623
+ if (!agent || !config)
624
+ throw templateError('NOT_FOUND', 'Update target is not installed on this Host');
625
+ const owner = await ownerResolver.refreshForAuthorization(aid);
626
+ if (owner.refreshFailure || owner.consensusStatus !== 'consensus' || !owner.ownerAid) {
627
+ throw templateError('OWNERSHIP_UNAVAILABLE', 'Current target Owner is not verified');
628
+ }
629
+ await ownerResolver.refresh((loadDaemonConfig().aid ?? ''), { force: true, allowTransient: false, source: 'template-update' });
630
+ if (!getDaemonOwners().includes(owner.ownerAid))
631
+ throw templateError('NOT_ALLOWED', 'Agent Owner must also control this Host');
632
+ return { ownerAid: owner.ownerAid, projectPath: agent.projectPath, mode: config.update?.mode };
633
+ },
634
+ catalog: createTemplateUpdateCatalog(paths.root, options.getControl),
635
+ notify: async (notice) => {
636
+ const current = await ownerResolver.refreshForAuthorization(notice.targetAid);
637
+ if (current.refreshFailure || current.consensusStatus !== 'consensus' || current.ownerAid !== notice.ownerAid) {
638
+ throw templateError('OWNERSHIP_UNAVAILABLE', 'Current notification Owner is not verified');
639
+ }
640
+ const host = requireHost();
641
+ const hostAid = host.getAid();
642
+ if (!hostAid)
643
+ throw templateError('AUN_DISCONNECTED', 'Host identity unavailable for notification delivery');
644
+ if (notice.outboxId) {
645
+ const state = outbox.deliveryState(hostAid, notice.outboxId);
646
+ if (state.status === 'sent')
647
+ return { messageId: state.messageId, outboxId: notice.outboxId, status: 'transport-accepted' };
648
+ if (state.status === 'failed') {
649
+ const entry = outbox.findByDedupeKey(hostAid, 'template-update:' + notice.noticeId, { includeTerminal: true });
650
+ if (entry && entry.id === notice.outboxId && entry.channelId === notice.ownerAid)
651
+ outbox.removeIfRouteMatches(hostAid, entry);
652
+ }
653
+ }
654
+ const text = 'Agent ' + notice.targetAid + ' 有可用升级:' + (notice.currentVersion ?? '当前版本未知')
655
+ + ' → ' + notice.candidate.version + '。请在主机的“模板 / Agent 更新”中查看并确认;升级只会在空闲时手动执行。';
656
+ const sent = await host.sendContentPayload(notice.ownerAid, { type: 'text', text,
657
+ template_update: { noticeId: notice.noticeId, targetAid: notice.targetAid,
658
+ sourceDigest: templateFingerprint(notice.source), candidateVersion: notice.candidate.version,
659
+ candidateDigest: notice.candidate.digest,
660
+ menu: { name: 'template', args: { view: 'update-status', targetAid: notice.targetAid } } } }, {
661
+ contentKind: 'text', dedupeKey: 'template-update:' + notice.noticeId, logText: text,
662
+ context: { delivery: { chatType: 'private' }, metadata: { encrypted: true, source: 'daemon' } },
663
+ });
664
+ if (!sent.messageId && !sent.queued)
665
+ throw templateError(String(sent.code ?? 'NOTIFICATION_FAILED'), sent.error ?? 'Owner update notice failed');
666
+ return { ...(sent.messageId ? { messageId: sent.messageId } : {}), ...(sent.outboxId ? { outboxId: sent.outboxId } : {}),
667
+ status: sent.messageId ? 'transport-accepted' : 'queued' };
668
+ },
669
+ },
670
+ joining: {
671
+ ownership: async (aid, ownerAid, hostAid) => {
672
+ if (hostAid !== requireHost().getAid() || !options.registry.get(aid))
673
+ throw templateError('TARGET_CHANGED', 'Installed member is not on the original Host');
674
+ await authorizeTemplateOwner(ownerAid, aid);
675
+ const owner = await ownerResolver.refreshForAuthorization(aid);
676
+ if (owner.refreshFailure || owner.consensusStatus !== 'consensus' || owner.ownerAid !== ownerAid
677
+ || !owner.consensus?.relation_version)
678
+ throw templateError('OWNERSHIP_REQUIRED', 'Fresh direct Owner consensus required');
679
+ return { aid, ownerAid, hostAid, relationVersion: owner.consensus.relation_version,
680
+ checkedAt: owner.checkedAt, validUntil: owner.validUntil };
681
+ },
682
+ verifyDirectory: verifyTemplateMemberDirectory,
683
+ addRelationships: async (team, member) => {
684
+ const original = team.members.filter(value => value.aid && value.aid !== member.aid);
685
+ for (const aid of [...team.relationshipTargets, member.aid]) {
686
+ await authorizeTemplateOwner(team.ownerAid, aid);
687
+ const current = readTeamMembersState(aid);
688
+ // A user clearing an original team's list pauses joining instead of recreating it.
689
+ if (aid !== member.aid && !current.members.some(peer => original.some(value => value.aid === peer))) {
690
+ throw templateError('CONFLICT', 'An original Team member list was independently cleared');
691
+ }
692
+ const additions = aid === member.aid ? original.map(value => value.aid) : [member.aid];
693
+ const missing = additions.filter(value => !current.members.includes(value));
694
+ if (missing.length)
695
+ mutateTeamMembers(aid, 'add', missing, current.membersRevision);
696
+ }
697
+ },
698
+ },
430
699
  hold: async (aid, token) => {
431
700
  const releaseGate = await options.coordinator.acquireForMutation(aid, token);
432
701
  let releaseScheduler;
433
702
  let releaseHandoff;
703
+ let releaseEvents;
434
704
  try {
435
705
  releaseHandoff = options.holdHandoff(aid, token);
706
+ releaseEvents = options.pauseEvents?.(aid, token);
436
707
  releaseScheduler = await options.getScheduler(aid)?.pauseForMutation(token);
437
708
  }
438
709
  catch (error) {
710
+ releaseEvents?.();
439
711
  releaseHandoff?.();
440
712
  await releaseGate();
441
713
  throw error;
442
714
  }
443
- return async () => { await releaseScheduler?.(); releaseHandoff?.(); await releaseGate(); };
715
+ return async () => { await releaseScheduler?.(); releaseEvents?.(); releaseHandoff?.(); await releaseGate(); };
444
716
  },
445
717
  reload: async (aid, jobId, restoreStopped) => {
446
718
  notifyConfigWrite(ConfigTarget.Agent, { self: aid });
@@ -519,6 +791,11 @@ export function createAgentTemplateRuntime(options) {
519
791
  }
520
792
  },
521
793
  });
794
+ // Runtime construction happens after the Host and local Agent registry are loaded.
795
+ // Discovery is optional background work; a pending definition never fences existing Agents.
796
+ void service.discoverTeams().catch(error => logger.warn('[Template] Team definition discovery remains pending: ' + String(error)));
797
+ service.startUpdateChecks();
798
+ return service;
522
799
  }
523
800
  /** The AID alone is never evidence that cancellation owns a target. */
524
801
  export function ownsTemplateMember(job, aid) {