evolcore 0.0.43-test.8 → 0.0.46

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 (204) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +13 -5
  12. package/dist/agents/codex/app-server-client.js +2 -4
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/menu/client.js +142 -182
  18. package/dist/aun/rpc/client.js +33 -17
  19. package/dist/aun/service-proxy.js +6 -23
  20. package/dist/channels/aun.js +656 -112
  21. package/dist/cli/agent-create.js +37 -10
  22. package/dist/cli/agent-template.js +105 -84
  23. package/dist/cli/agent.js +31 -18
  24. package/dist/cli/daemon-commands.js +15 -17
  25. package/dist/cli/daemon-lifecycle-client.js +40 -18
  26. package/dist/cli/directory.js +12 -4
  27. package/dist/cli/ecmsg-gateway.js +5 -2
  28. package/dist/cli/events-command.js +2 -1
  29. package/dist/cli/init.js +50 -20
  30. package/dist/cli/integrity-command.js +2 -0
  31. package/dist/cli/managed-command-guard.js +20 -1
  32. package/dist/cli/menu-client.js +7 -5
  33. package/dist/cli/restart-monitor.js +33 -20
  34. package/dist/cli/services-command.js +28 -5
  35. package/dist/config/config-field-policy.js +24 -0
  36. package/dist/config/config-manager.js +20 -2
  37. package/dist/config/peer-book-store.js +152 -120
  38. package/dist/config/peer-role-resolver.js +24 -4
  39. package/dist/config/provider-identity-migration.js +1 -1
  40. package/dist/config/provider-identity.js +10 -4
  41. package/dist/config/provider-ipc-service.js +10 -2
  42. package/dist/config/provider-local-sync.js +2 -2
  43. package/dist/config/providers-config.js +95 -10
  44. package/dist/config/providers-import.js +4 -6
  45. package/dist/config/providers.js +14 -3
  46. package/dist/config/role-store.js +1 -1
  47. package/dist/config-store.js +9 -1
  48. package/dist/core/agent-application-service.js +56 -29
  49. package/dist/core/agent-create-status.js +3 -1
  50. package/dist/core/agent-creation-claim.js +1 -0
  51. package/dist/core/agent-ipc-registration.js +2 -2
  52. package/dist/core/agent-reload-coordinator.js +38 -1
  53. package/dist/core/agent-runtime.js +85 -38
  54. package/dist/core/auth/agent-delegation.js +5 -0
  55. package/dist/core/auth/operation-authorizer.js +1 -1
  56. package/dist/core/auth/operation-catalog.js +3 -3
  57. package/dist/core/bootstrap-service.js +3 -0
  58. package/dist/core/capability/capability-manager.js +3 -1
  59. package/dist/core/channel-loader.js +29 -3
  60. package/dist/core/channel-runtime.js +1 -1
  61. package/dist/core/command/agent-control.js +6 -5
  62. package/dist/core/command/agent-template-menu.js +32 -97
  63. package/dist/core/command/eventcenter-menu.js +61 -13
  64. package/dist/core/command/menu-catalog.js +11 -4
  65. package/dist/core/command/menu-handler.js +35 -8
  66. package/dist/core/command/menu-protocol.js +8 -16
  67. package/dist/core/command/skill-slash.js +6 -2
  68. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  69. package/dist/core/command/team-workspace-management-store.js +83 -0
  70. package/dist/core/command/team-workspace-management.js +1 -2
  71. package/dist/core/command/team-workspace-team.js +26 -3
  72. package/dist/core/daemon-control.js +3 -4
  73. package/dist/core/daemon-lifecycle.js +146 -110
  74. package/dist/core/evolagent-registry.js +42 -0
  75. package/dist/core/evolagent.js +2 -1
  76. package/dist/core/file-integrity/read.js +9 -16
  77. package/dist/core/file-integrity/store.js +94 -34
  78. package/dist/core/handoff/dispatcher.js +33 -7
  79. package/dist/core/handoff/runtime.js +8 -0
  80. package/dist/core/inference/text-inference.js +12 -2
  81. package/dist/core/invoke/invoke-service.js +24 -3
  82. package/dist/core/ipc-registration.js +3 -0
  83. package/dist/core/message/aun-ipc-sender.js +109 -7
  84. package/dist/core/message/contact-admission.js +6 -2
  85. package/dist/core/message/message-bridge.js +13 -0
  86. package/dist/core/message/message-queue.js +131 -30
  87. package/dist/core/message/pending-hints.js +8 -0
  88. package/dist/core/message/response-engine.js +48 -2
  89. package/dist/core/message/send-routing.js +3 -12
  90. package/dist/core/model/catalog-service.js +13 -0
  91. package/dist/core/model/model-catalog.js +57 -18
  92. package/dist/core/pack-auth.js +163 -31
  93. package/dist/core/pack-install.js +42 -1
  94. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  95. package/dist/core/permission/ec-command-parser.js +3 -1
  96. package/dist/core/permission/shell-environment.js +23 -0
  97. package/dist/core/rate-window.js +6 -1
  98. package/dist/core/session/session-idle-monitor.js +0 -1
  99. package/dist/core/session/session-manager.js +14 -0
  100. package/dist/core/session/session-title.js +26 -6
  101. package/dist/core/skill/index-generator.js +3 -4
  102. package/dist/core/thread/thread-service.js +0 -1
  103. package/dist/core/thread/topic-id.js +8 -0
  104. package/dist/directory/owner-directory-admission.js +17 -0
  105. package/dist/directory/owner-directory-cache.js +3 -1
  106. package/dist/directory/owner-directory-markdown.js +145 -23
  107. package/dist/directory/owner-directory-policy.js +23 -0
  108. package/dist/directory/owner-directory-query-operation.js +20 -6
  109. package/dist/directory/owner-directory-search.js +47 -0
  110. package/dist/eck/message-renderer.js +171 -32
  111. package/dist/ecweb/basic-settings-service.js +7 -3
  112. package/dist/ecweb/providers-service.js +17 -10
  113. package/dist/ecweb/runtime/lifecycle.js +1 -1
  114. package/dist/ecweb/runtime/supervisor.js +77 -35
  115. package/dist/event-center/admission-materializer.js +1 -1
  116. package/dist/event-center/bus-gate.js +48 -4
  117. package/dist/event-center/bus-host.js +3 -3
  118. package/dist/event-center/center-config.js +57 -28
  119. package/dist/event-center/dispatcher.js +8 -0
  120. package/dist/event-center/event-log.js +69 -27
  121. package/dist/event-center/index-generator.js +6 -1
  122. package/dist/event-center/ipc-operation.js +66 -25
  123. package/dist/event-center/pack-loader.js +12 -55
  124. package/dist/event-center/pack-manager.js +5 -3
  125. package/dist/event-center/registry.js +48 -52
  126. package/dist/event-center/runtime.js +219 -81
  127. package/dist/event-center/script-runner.js +18 -7
  128. package/dist/event-center/types.js +9 -1
  129. package/dist/event-center/validation.js +33 -4
  130. package/dist/index.js +96 -42
  131. package/dist/ipc.js +33 -7
  132. package/dist/product.js +1 -0
  133. package/dist/proxy/manager.js +52 -11
  134. package/dist/proxy/service-supervisor.js +265 -67
  135. package/dist/services/dispatcher.js +26 -3
  136. package/dist/services/idempotency.js +128 -0
  137. package/dist/services/identity.js +3 -27
  138. package/dist/services/index-generator.js +5 -1
  139. package/dist/services/index.js +244 -45
  140. package/dist/services/ipc-operation.js +164 -20
  141. package/dist/services/pack-manager.js +37 -9
  142. package/dist/services/router.js +100 -31
  143. package/dist/services/script-runner.js +15 -4
  144. package/dist/services/service-payload.js +50 -2
  145. package/dist/services/validation.js +107 -3
  146. package/dist/trigger/scheduler.js +14 -4
  147. package/dist/trigger/script-sandbox.js +39 -2
  148. package/dist/utils/cross-platform.js +35 -11
  149. package/dist/utils/error-utils.js +13 -1
  150. package/dist/utils/instance-registry.js +33 -35
  151. package/dist/utils/process-introspect.js +35 -20
  152. package/dist/utils/project-path.js +47 -3
  153. package/dist/utils/windows-shell-trust.js +174 -68
  154. package/kits/docs/context-assembly.md +3 -3
  155. package/kits/docs/evolcore/agent.md +28 -10
  156. package/kits/docs/evolcore/config.md +22 -0
  157. package/kits/docs/evolcore/directory.md +46 -12
  158. package/kits/docs/evolcore/event-center.md +6 -6
  159. package/kits/docs/evolcore/group-collaboration.md +1 -1
  160. package/kits/docs/evolcore/menu-client.md +7 -5
  161. package/kits/docs/evolcore/menu-protocol.md +5 -3
  162. package/kits/docs/evolcore/msg.md +10 -3
  163. package/kits/docs/evolcore/provider.md +7 -3
  164. package/kits/docs/evolcore/services.md +145 -12
  165. package/kits/docs/evolcore/thread-chain.md +17 -9
  166. package/kits/docs/prompt-loading-architecture.md +4 -4
  167. package/kits/eck_message_manifest.json +46 -3
  168. package/kits/rules/04-relation.md +10 -2
  169. package/kits/rules/06-channel.md +2 -1
  170. package/kits/schemas/providers.schema.2.json +1 -0
  171. package/kits/skills/ec-group/SKILL.md +4 -0
  172. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  173. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  174. package/kits/skills/thread-ops/SKILL.md +8 -5
  175. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  176. package/kits/templates/message-fragments/group-batch.md +1 -0
  177. package/kits/templates/message-fragments/item-group.md +4 -0
  178. package/kits/templates/message-fragments/item-private.md +4 -0
  179. package/kits/templates/message-fragments/thread-context.md +1 -1
  180. package/kits/templates/system-fragments/commands.md +5 -5
  181. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  182. package/kits/templates/system-fragments/relation.md +11 -7
  183. package/package.json +3 -2
  184. package/scripts/agent-template/index.mjs +9 -4
  185. package/scripts/agent-template/inspect.mjs +16 -9
  186. package/scripts/agent-template/shared/plan.mjs +3 -33
  187. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  188. package/scripts/agent-template/shared/template-package.mjs +119 -10
  189. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  190. package/scripts/agent-template/shared/template.mjs +5 -5
  191. package/scripts/agent-template/team-pack.mjs +245 -0
  192. package/scripts/agent-template/team-preview.mjs +111 -0
  193. package/scripts/aid-batch/identity-batch.mjs +143 -0
  194. package/dist/ability/versions.js +0 -32
  195. package/dist/aun/model-headers.js +0 -17
  196. package/dist/channels/builtin-plugins.js +0 -19
  197. package/dist/core/command/team-workspace-initializer.js +0 -2
  198. package/dist/core/command/team-workspace-job-store.js +0 -88
  199. package/dist/core/command/team-workspace-management-service.js +0 -2
  200. package/dist/core/contact-bind-registry.js +0 -27
  201. package/dist/event-center/ledger.js +0 -52
  202. package/dist/services/reply.js +0 -55
  203. package/kits/templates/message-fragments/item.md +0 -3
  204. package/scripts/agent-template/pack.mjs +0 -169
@@ -1,433 +1,830 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
- import { atomicWriteJson } from '../core/session/session-fs-store.js';
5
- import { TemplateJobs, templateFingerprint } from './jobs.js';
4
+ import { TemplateJobs, templateFingerprint, writeTemplateState, TEMPLATE_PREVIEW_ID } from './jobs.js';
6
5
  import { runTemplateTool } from './tool-runner.js';
7
6
  import { templateError, templateJobAids } from './types.js';
8
7
  import { logger } from '../utils/logger.js';
8
+ const SELECTION_MS = 15 * 60_000;
9
+ const JOB_MS = 30 * 60_000;
9
10
  export class AgentTemplateService {
10
11
  deps;
11
12
  jobs;
12
13
  cache;
13
14
  work = new Map();
15
+ controllers = new Map();
16
+ collections = new Map();
17
+ timers = new Map();
18
+ cancellations = new Map();
14
19
  mutations = Promise.resolve();
15
- ready;
16
20
  tool;
21
+ cleanupTimer;
22
+ disposed = false;
17
23
  constructor(deps) {
18
24
  this.deps = deps;
19
- this.cache = path.join(deps.root, 'data', 'template-cache');
20
- this.jobs = new TemplateJobs(path.join(this.cache, 'jobs'));
25
+ this.jobs = new TemplateJobs(deps.root);
26
+ this.cache = this.jobs.directory;
21
27
  this.tool = deps.tool ?? runTemplateTool;
22
- this.ready = Promise.resolve().then(() => this.recover());
23
- void this.ready.catch(error => { logger.error('[Template] Recovery unavailable: ' + String(error)); });
24
- }
25
- audit(job) {
26
- const directory = path.join(this.deps.root, 'logs', 'template-audit');
27
- fs.mkdirSync(directory, { recursive: true });
28
- fs.appendFileSync(path.join(directory, new Date().toISOString().slice(0, 10) + '.jsonl'), JSON.stringify({
29
- at: Date.now(), actor: job.actor, aid: job.aid, aids: templateJobAids(job), hostAid: this.deps.hostAid,
30
- jobId: job.jobId, requestId: job.requestId, action: job.action, status: job.event.status, code: job.event.code,
31
- }) + '\n');
32
- }
33
- cleanup() {
34
- const jobs = this.jobs.list();
35
- const retained = new Set(jobs.filter(j => j.event.status === 'running' || j.event.code === 'INSTALL_BROKEN')
36
- .flatMap(j => [j.args.buildId, j.args.pullId]).filter(Boolean));
37
- for (const name of fs.readdirSync(this.cache))
38
- if (/^(?:build|pull)_[a-f0-9-]{36}$/.test(name) && !retained.has(name)) {
39
- const file = path.join(this.cache, name, 'record.json');
40
- if (!fs.existsSync(file))
41
- continue;
42
- const value = JSON.parse(fs.readFileSync(file, 'utf8'));
43
- const ttl = name.startsWith('build_') ? 7 * 86400_000 : 2 * 86400_000;
44
- if (value.createdAt < Date.now() - ttl)
45
- fs.rmSync(path.join(this.cache, name), { recursive: true, force: true });
28
+ this.cleanupTimer = setInterval(() => {
29
+ try {
30
+ for (const job of this.jobs.list())
31
+ if (job.status === 'cancelling' && !this.work.has(job.jobId)) {
32
+ void this.cancelInternal(job.actor, job.jobId, job.freeze?.releaseReason ?? 'user_cancel')
33
+ .catch(error => logger.warn('[Template] Cleanup remains pending: ' + String(error)));
34
+ }
46
35
  }
47
- for (const job of jobs)
48
- if (job.event.status !== 'running' && job.event.code !== 'INSTALL_BROKEN' && job.updatedAt < Date.now() - 86400_000) {
49
- fs.rmSync(this.jobs.file(job.jobId), { force: true });
36
+ catch (error) {
37
+ logger.warn('[Template] Cleanup scan failed: ' + String(error));
50
38
  }
39
+ }, 5_000);
40
+ this.cleanupTimer.unref?.();
51
41
  }
52
- record(id, prefix) {
53
- if (!new RegExp('^' + prefix + '_[a-f0-9-]{36}$').test(id))
54
- throw templateError('INVALID_ARGUMENT', 'Invalid ' + prefix + 'Id');
55
- const dir = path.join(this.cache, id);
56
- const file = path.join(dir, 'record.json');
57
- if (!fs.existsSync(file))
58
- throw templateError('NOT_FOUND', 'Cached template not found');
59
- const value = JSON.parse(fs.readFileSync(file, 'utf8'));
60
- const ttl = prefix === 'build' ? 7 * 86400_000 : 86400_000;
61
- if (value.createdAt < Date.now() - ttl)
62
- throw templateError('NOT_FOUND', 'Cached template expired');
63
- return { dir, value };
64
- }
65
- async recover() {
42
+ /** Stop watchers before disposing an isolated runtime or replacing its storage root. */
43
+ async dispose() {
44
+ if (this.disposed)
45
+ return;
46
+ this.disposed = true;
47
+ clearInterval(this.cleanupTimer);
48
+ for (const timer of this.timers.values())
49
+ clearTimeout(timer);
50
+ this.timers.clear();
66
51
  for (const job of this.jobs.list())
67
- if (job.event.code === 'INSTALL_BROKEN') {
68
- for (const aid of templateJobAids(job))
69
- this.deps.block(aid);
52
+ if (['inspect', 'build'].includes(job.action)
53
+ && job.freeze && !['released', 'transferred'].includes(job.freeze.state)) {
54
+ await this.cancelInternal(job.actor, job.jobId, 'runtime_disposed');
70
55
  }
71
- for (const job of this.jobs.list())
72
- if (job.event.status === 'running') {
73
- let rolledBack = true;
74
- try {
75
- if (job.action === 'deploy' && job.backupDir && fs.existsSync(path.join(job.backupDir, 'journal.json'))) {
76
- await this.withTargets(templateJobAids(job), async () => {
77
- const resume = await this.pauseTargets(templateJobAids(job));
78
- let restored = false;
79
- try {
80
- if (!job.localRecoveryComplete)
81
- await this.tool('overlay', { operation: 'restore', backupDir: job.backupDir });
82
- if (job.profileAttempted) {
83
- const { value } = this.record(job.args.pullId, 'pull');
84
- const plan = JSON.parse(fs.readFileSync(value.data.planFile, 'utf8'));
85
- await this.restoreProfiles(job, plan);
86
- }
87
- for (const aid of templateJobAids(job))
88
- await this.deps.reload(aid);
89
- restored = true;
90
- }
91
- finally {
92
- if (restored)
93
- await resume();
94
- }
95
- });
96
- }
56
+ await Promise.allSettled([...this.work.values(), ...this.cancellations.values()]);
57
+ }
58
+ view(job) {
59
+ const { actor: _actor, fingerprint: _fingerprint, args: _args, checkpoint: _checkpoint, version: _version, activating: _activating, ...view } = job;
60
+ if (job.action === 'deploy' && job.committed) {
61
+ const runtimeReady = templateJobAids(job).every(aid => this.deps.installation.ready(aid));
62
+ const directoryReady = this.deps.installation.directoryReady(templateJobAids(job));
63
+ return { ...view, readiness: { runtimeReady, directoryReady, teamReady: runtimeReady && directoryReady,
64
+ health: runtimeReady && directoryReady ? 'ready' : 'degraded' } };
65
+ }
66
+ return view;
67
+ }
68
+ current(job) {
69
+ const current = this.jobs.read(job.jobId);
70
+ if (current.seq !== job.seq || !['queued', 'running'].includes(current.status)) {
71
+ throw templateError('CONFLICT', 'Workflow lost its revision', { jobId: job.jobId });
72
+ }
73
+ }
74
+ async step(job, work) {
75
+ this.current(job);
76
+ const result = await work();
77
+ this.current(job);
78
+ return result;
79
+ }
80
+ phase(job, phase) {
81
+ this.current(job);
82
+ job.phase = phase;
83
+ this.jobs.save(job);
84
+ }
85
+ async executeTool(job, command, options) {
86
+ return this.step(job, () => this.tool(command, options, {
87
+ signal: this.controllers.get(job.jobId)?.signal,
88
+ onSpawn: worker => { this.current(job); job.checkpoint.worker = worker; this.jobs.save(job); },
89
+ onExit: () => {
90
+ const current = this.jobs.read(job.jobId);
91
+ if (current.checkpoint.worker) {
92
+ delete current.checkpoint.worker;
93
+ this.jobs.save(current);
94
+ job.seq = current.seq;
95
+ job.updatedAt = current.updatedAt;
97
96
  }
98
- catch {
99
- rolledBack = false;
100
- for (const aid of templateJobAids(job))
101
- this.deps.block(aid);
97
+ },
98
+ }));
99
+ }
100
+ launch(job, run) {
101
+ const controller = new AbortController();
102
+ this.controllers.set(job.jobId, controller);
103
+ const watchdog = setTimeout(() => {
104
+ void this.cancelInternal(job.actor, job.jobId, 'execution_timeout')
105
+ .catch(error => logger.warn('[Template] Watchdog cleanup failed: ' + String(error)));
106
+ }, JOB_MS);
107
+ watchdog.unref?.();
108
+ const work = Promise.resolve().then(async () => {
109
+ this.current(job);
110
+ job.status = 'running';
111
+ this.jobs.save(job);
112
+ try {
113
+ await run(job);
114
+ }
115
+ catch (error) {
116
+ const current = this.jobs.read(job.jobId);
117
+ if (current.status === 'cancelling' || ['cancelled', 'succeeded'].includes(current.status))
118
+ return;
119
+ current.error = { code: error.code ?? 'TEMPLATE_FAILED', message: error.message,
120
+ retryable: current.action === 'deploy', ...(error.details ? { details: error.details } : {}) };
121
+ if (['inspect', 'build'].includes(current.action)) {
122
+ await this.release(current, 'failed');
123
+ current.status = current.freeze?.state === 'released' ? 'failed' : 'cancelling';
124
+ current.resumable = false;
125
+ }
126
+ else {
127
+ current.status = current.action === 'deploy' ? 'paused' : 'failed';
128
+ current.resumable = current.action === 'deploy';
102
129
  }
103
- this.jobs.update(job, { event: 'template.result', status: 'failed',
104
- code: rolledBack ? 'TASK_INTERRUPTED' : 'INSTALL_BROKEN', message: 'Task interrupted by daemon restart',
105
- data: { rolledBack } });
106
- for (const aid of templateJobAids(job))
107
- this.deps.recoveryComplete?.(aid, rolledBack);
130
+ this.jobs.save(current);
108
131
  }
109
- this.cleanup();
132
+ }).catch(error => { logger.error('[Template] Job cleanup failed: ' + String(error)); })
133
+ .finally(() => { clearTimeout(watchdog); this.work.delete(job.jobId); this.controllers.delete(job.jobId); });
134
+ this.work.set(job.jobId, work);
110
135
  }
111
- async restoreProfile(aid, original, applied) {
112
- const visible = (value) => Object.fromEntries(['name', 'description', 'avatar', 'tags', 'exttype'].filter(k => value?.[k] !== undefined).map(k => [k, value[k]]));
113
- const current = await this.deps.readProfile(aid);
114
- if (templateFingerprint(visible(current.profile)) === templateFingerprint(visible(original)))
115
- return;
116
- if (templateFingerprint(visible(current.profile)) !== templateFingerprint(visible(applied))) {
117
- throw templateError('CONFLICT', 'Profile was edited independently; refusing to overwrite that edit during recovery');
118
- }
119
- await this.deps.publishProfile(aid, original, current.profileVersion);
136
+ async wait(jobId) { await this.work.get(jobId); }
137
+ async query(actor, args) {
138
+ await this.deps.installation.authorize(actor);
139
+ return this.view(this.jobs.get(actor, args));
120
140
  }
121
- /** Sorted acquisition prevents deadlocks when two packages contain overlapping targets. */
122
- withTargets(aids, work) {
123
- const ordered = [...new Set(aids)].sort();
124
- const acquire = (i) => i === ordered.length ? work()
125
- : this.deps.exclusive(ordered[i], () => acquire(i + 1));
126
- return acquire(0);
141
+ async action(actor, requestId, action, args) {
142
+ if (this.disposed)
143
+ throw templateError('RECOVERY_REQUIRED', 'Template runtime has been disposed');
144
+ await this.deps.installation.authorize(actor);
145
+ if (action === 'status')
146
+ return this.query(actor, args);
147
+ if (action === 'capabilities')
148
+ return this.tool('capabilities', {});
149
+ if (action === 'cancel' || action === 'resume')
150
+ return this.control(actor, requestId, action, args.jobId);
151
+ const prior = this.jobs.original(actor, requestId);
152
+ if (prior) {
153
+ if (prior.fingerprint !== templateFingerprint({ action, args }))
154
+ throw templateError('CONFLICT', 'Request has different arguments');
155
+ return this.view(prior);
156
+ }
157
+ if (action === 'inspect')
158
+ return this.inspect(actor, requestId, args);
159
+ if (action === 'build')
160
+ return this.build(actor, requestId, args);
161
+ if (action === 'deploy')
162
+ return this.deploy(actor, requestId, args);
163
+ const { job } = this.jobs.accept(actor, requestId, action, args);
164
+ this.launch(job, value => action === 'push' ? this.push(value) : action === 'pull' ? this.pull(value) : this.preview(value));
165
+ return this.view(job);
127
166
  }
128
- async pauseTargets(aids) {
129
- const callbacks = [];
130
- const resume = async () => {
131
- const errors = [];
132
- for (const callback of callbacks.splice(0).reverse()) {
167
+ async inspect(actor, requestId, args) {
168
+ const members = Object.fromEntries(Object.entries(args.members).map(([key, member]) => [key, { aid: member.source.kind === 'agent' ? member.source.aid : '',
169
+ projectPath: member.source.kind === 'directory' ? member.source.path : '', requestId: randomUUID() }]));
170
+ for (const member of Object.values(members))
171
+ if (member.aid)
172
+ await this.deps.authorize(actor, member.aid);
173
+ const accepted = this.jobs.accept(actor, requestId, 'inspect', args, members);
174
+ if (accepted.reused)
175
+ return this.view(accepted.job);
176
+ const job = accepted.job;
177
+ const generation = 1;
178
+ const collectionKey = job.jobId + ':' + generation;
179
+ job.checkpoint.collectionKey = collectionKey;
180
+ job.freeze = { state: 'acquiring', generation, frozenAt: null, selectionExpiresAt: null };
181
+ job.status = 'running';
182
+ job.phase = 'acquiring';
183
+ this.jobs.save(job);
184
+ const held = { owner: job.jobId, releases: [] };
185
+ this.collections.set(collectionKey, held);
186
+ try {
187
+ for (const [key, member] of Object.entries(members).sort((a, b) => a[1].aid.localeCompare(b[1].aid))) {
188
+ if (!member.aid)
189
+ continue;
190
+ job.checkpoint.tokens = { ...job.checkpoint.tokens, [key]: collectionKey + ':' + key };
191
+ this.jobs.save(job);
133
192
  try {
134
- await callback();
193
+ held.releases.push({ key, release: await this.deps.hold(member.aid, collectionKey + ':' + key) });
135
194
  }
136
195
  catch (error) {
137
- errors.push(error);
196
+ throw templateError(error.code ?? 'AGENT_BUSY', error.message, { memberKey: key });
138
197
  }
139
198
  }
140
- if (errors.length)
141
- throw errors[0];
142
- };
143
- try {
144
- for (const aid of [...aids].sort())
145
- callbacks.push(await this.deps.pause(aid));
199
+ job.freeze.state = 'held';
200
+ job.freeze.frozenAt = Date.now();
201
+ job.freeze.selectionExpiresAt = job.freeze.frozenAt + SELECTION_MS;
202
+ this.jobs.save(job);
203
+ const timer = setTimeout(() => {
204
+ void this.cancelInternal(actor, job.jobId, 'selection_expired')
205
+ .catch(error => logger.warn('[Template] Selection cleanup failed: ' + String(error)));
206
+ }, SELECTION_MS);
207
+ timer.unref?.();
208
+ this.timers.set(job.jobId, timer);
209
+ this.launch(job, async (current) => {
210
+ this.phase(current, 'inventory');
211
+ const sources = {};
212
+ for (const [key, member] of Object.entries(current.args.members)) {
213
+ sources[key] = member.source.kind === 'agent'
214
+ ? await this.step(current, () => this.deps.source(member.source.aid, actor))
215
+ : { kind: 'directory', path: member.source.path, key };
216
+ }
217
+ current.checkpoint.sources = sources;
218
+ this.jobs.save(current);
219
+ const data = await this.executeTool(current, 'inspect', { members: sources });
220
+ current.freeze.inventoryDigest = data.inventoryDigest;
221
+ current.result = data;
222
+ current.status = 'paused';
223
+ current.phase = 'awaiting_selection';
224
+ current.resumable = false;
225
+ this.jobs.save(current);
226
+ });
146
227
  }
147
228
  catch (error) {
148
- await resume();
149
- throw error;
229
+ job.error = { code: error.code ?? 'AGENT_BUSY', message: error.message, retryable: false, details: error.details };
230
+ await this.release(job, 'failed');
231
+ job.status = job.freeze.state === 'released' ? 'failed' : 'cancelling';
232
+ this.jobs.save(job);
150
233
  }
151
- return resume;
152
- }
153
- planMembers(plan) {
154
- return plan.members ?? [{ targetAid: plan.targetAid, projectPath: plan.projectPath,
155
- profile: plan.profile, originalProfile: plan.originalProfile, profileVersion: plan.profileVersion, providers: plan.providers }];
234
+ return this.view(job);
156
235
  }
157
- async restoreProfiles(job, plan) {
158
- const attempted = new Set(job.profileAttemptedAids ?? (job.profileAttempted ? [job.aid] : []));
159
- const errors = [];
160
- for (const member of [...this.planMembers(plan)].reverse())
161
- if (attempted.has(member.targetAid)) {
162
- try {
163
- await this.restoreProfile(member.targetAid, member.originalProfile, member.profile);
164
- }
165
- catch (error) {
166
- errors.push(error);
236
+ async build(actor, requestId, args) {
237
+ const inspection = this.jobs.get(actor, { jobId: args.inspectionJobId });
238
+ if (inspection.action !== 'inspect')
239
+ throw templateError('INVALID_ARGUMENT', 'inspectionJobId must identify inspect');
240
+ if (inspection.freeze?.buildJobId) {
241
+ const built = this.jobs.read(inspection.freeze.buildJobId);
242
+ if (built.fingerprint !== templateFingerprint({ action: 'build', args }))
243
+ throw templateError('CONFLICT', 'Inspection was already used');
244
+ this.jobs.bindRequest(actor, requestId, 'build', args, built.jobId);
245
+ return this.view(built);
246
+ }
247
+ if (inspection.freeze?.state !== 'held' || inspection.freeze.selectionExpiresAt <= Date.now()) {
248
+ throw templateError('EXPIRED', 'Inspection is no longer frozen');
249
+ }
250
+ if (inspection.phase !== 'awaiting_selection' || inspection.result?.inventoryDigest !== args.inventoryDigest
251
+ || Object.keys(inspection.members).sort().join() !== Object.keys(args.members).sort().join()) {
252
+ throw templateError('CONFLICT', 'Complete member selection and original inventoryDigest required');
253
+ }
254
+ await this.tool('validate-selection', { inventory: inspection.result, metadata: args.metadata, members: args.members });
255
+ for (const aid of templateJobAids(inspection))
256
+ await this.deps.authorize(actor, aid);
257
+ const current = this.jobs.read(inspection.jobId);
258
+ const held = this.collections.get(current.checkpoint.collectionKey);
259
+ if (current.seq !== inspection.seq || current.freeze?.state !== 'held'
260
+ || current.freeze.selectionExpiresAt <= Date.now() || held?.owner !== current.jobId) {
261
+ throw templateError('EXPIRED', 'Inspection expired while validating selection');
262
+ }
263
+ const { job } = this.jobs.accept(actor, requestId, 'build', args, structuredClone(current.members));
264
+ job.freeze = { ...current.freeze, state: 'held' };
265
+ job.checkpoint.sources = current.checkpoint.sources;
266
+ job.checkpoint.collectionKey = current.checkpoint.collectionKey;
267
+ current.freeze = { ...current.freeze, state: 'transferred', buildJobId: job.jobId };
268
+ current.status = 'succeeded';
269
+ current.phase = 'handed_off';
270
+ this.jobs.save(job);
271
+ this.jobs.save(current);
272
+ held.owner = job.jobId;
273
+ clearTimeout(this.timers.get(current.jobId));
274
+ this.timers.delete(current.jobId);
275
+ this.launch(job, async (value) => {
276
+ this.phase(value, 'collecting');
277
+ const packageId = 'package_' + randomUUID();
278
+ value.checkpoint.packageId = packageId;
279
+ this.jobs.save(value);
280
+ const sources = structuredClone(value.checkpoint.sources);
281
+ for (const [key, source] of Object.entries(sources))
282
+ if (source.agentAid) {
283
+ const fresh = await this.step(value, () => this.deps.source(source.agentAid, actor));
284
+ if (templateFingerprint(fresh) !== templateFingerprint(source))
285
+ throw templateError('SOURCE_CHANGED', 'Source profile or configuration changed', { memberKey: key });
167
286
  }
287
+ const data = await this.executeTool(value, 'build', { members: sources,
288
+ selections: value.args.members, metadata: value.args.metadata, inventoryDigest: value.args.inventoryDigest,
289
+ out: path.join(this.cache, 'packages', packageId) });
290
+ this.current(value);
291
+ const record = { actor, packageId, createdAt: Date.now(), data, provenance: {
292
+ kind: 'build', sourceAids: templateJobAids(value), sources: value.args.inspectionJobId
293
+ } };
294
+ writeTemplateState(path.join(this.cache, 'packages', packageId, 'record.json'), record);
295
+ await this.release(value, 'completed');
296
+ if (value.freeze?.state !== 'released')
297
+ throw templateError('RECOVERY_REQUIRED', 'Source release is incomplete');
298
+ const { file: _file, ...publicData } = data;
299
+ value.result = { ...publicData, packageId };
300
+ value.status = 'succeeded';
301
+ value.phase = 'completed';
302
+ this.jobs.save(value);
303
+ });
304
+ return this.view(job);
305
+ }
306
+ async release(job, reason) {
307
+ if (!job.freeze || ['released', 'transferred'].includes(job.freeze.state))
308
+ return;
309
+ job.freeze.state = 'releasing';
310
+ job.freeze.releaseReason = reason;
311
+ this.jobs.save(job);
312
+ const held = this.collections.get(job.checkpoint.collectionKey);
313
+ if (!held || held.owner !== job.jobId) {
314
+ job.error = { code: 'RECOVERY_REQUIRED', message: 'Collection release ownership is unavailable', retryable: true };
315
+ return;
316
+ }
317
+ const pending = [];
318
+ for (const item of [...held.releases].reverse()) {
319
+ try {
320
+ await item.release();
321
+ }
322
+ catch {
323
+ pending.unshift(item);
324
+ }
325
+ }
326
+ held.releases = pending;
327
+ job.freeze.pendingReleases = pending.map(item => ({ memberKey: item.key }));
328
+ if (!pending.length) {
329
+ job.freeze.state = 'released';
330
+ this.collections.delete(job.checkpoint.collectionKey);
331
+ clearTimeout(this.timers.get(job.jobId));
332
+ this.timers.delete(job.jobId);
333
+ }
334
+ else
335
+ job.error = { code: 'RECOVERY_REQUIRED', message: 'Some sources still require release', retryable: true };
336
+ this.jobs.save(job);
337
+ }
338
+ async control(actor, requestId, action, jobId) {
339
+ const job = this.jobs.get(actor, { jobId });
340
+ const first = this.jobs.bindRequest(actor, requestId, action, { jobId }, jobId);
341
+ if (!first)
342
+ return this.view(job);
343
+ if (action === 'cancel') {
344
+ await this.cancelInternal(actor, jobId, 'user_cancel');
345
+ }
346
+ else {
347
+ if (!job.resumable || job.action !== 'deploy' || !['paused', 'failed'].includes(job.status)) {
348
+ throw templateError('CONFLICT', 'This job cannot resume');
168
349
  }
169
- if (errors.length)
170
- throw errors[0];
350
+ this.jobs.associate(job);
351
+ job.attempt++;
352
+ job.status = 'queued';
353
+ delete job.error;
354
+ this.jobs.save(job);
355
+ this.launch(job, value => this.runInstallation(value));
356
+ }
357
+ return this.view(this.jobs.read(jobId));
171
358
  }
172
- async inspect(actor, aid) {
173
- await this.ready;
174
- await this.deps.authorize(actor, aid);
175
- return this.tool('inspect-agent', await this.deps.source(aid, actor));
359
+ async cancelInternal(actor, jobId, reason) {
360
+ const job = this.jobs.get(actor, { jobId });
361
+ if (job.action === 'inspect' && job.freeze?.state === 'transferred') {
362
+ if (reason !== 'user_cancel')
363
+ return;
364
+ throw templateError('CONFLICT', 'Cancel the build that owns this collection', { buildJobId: job.freeze.buildJobId });
365
+ }
366
+ if (job.committed)
367
+ throw templateError('CONFLICT', 'Committed deployment cannot be cancelled');
368
+ if (['cancelled', 'succeeded'].includes(job.status))
369
+ return;
370
+ const previous = this.cancellations.get(jobId);
371
+ if (previous)
372
+ return previous;
373
+ job.status = 'cancelling';
374
+ job.resumable = false;
375
+ this.jobs.save(job);
376
+ this.controllers.get(jobId)?.abort();
377
+ const cancel = (async () => {
378
+ await this.work.get(jobId);
379
+ const current = this.jobs.read(jobId);
380
+ if (current.action === 'deploy')
381
+ await this.compensate(current);
382
+ else {
383
+ const packageId = current.checkpoint.packageId;
384
+ if (packageId)
385
+ fs.rmSync(path.join(this.cache, 'packages', packageId), { recursive: true, force: true });
386
+ await this.release(current, reason);
387
+ }
388
+ if (!current.freeze || current.freeze.state === 'released') {
389
+ current.status = 'cancelled';
390
+ current.phase = reason;
391
+ this.jobs.save(current);
392
+ }
393
+ })().finally(() => { this.cancellations.delete(jobId); });
394
+ this.cancellations.set(jobId, cancel);
395
+ return cancel;
176
396
  }
177
- async query(actor, query) {
178
- await this.ready;
179
- this.cleanup();
180
- const job = this.jobs.get(actor, query);
181
- for (const aid of templateJobAids(job))
182
- await this.deps.authorize(actor, aid);
183
- return job.event;
397
+ packageRecord(actor, packageId) {
398
+ if (!/^package_[a-f0-9-]{36}$/.test(packageId))
399
+ throw templateError('INVALID_ARGUMENT', 'Invalid packageId');
400
+ const file = path.join(this.cache, 'packages', packageId, 'record.json');
401
+ if (!fs.existsSync(file))
402
+ throw templateError('NOT_FOUND', 'Package not found');
403
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'));
404
+ if (record.actor !== actor)
405
+ throw templateError('NOT_ALLOWED', 'Package belongs to another principal');
406
+ const pinned = this.jobs.list().some(job => job.args.packageId === packageId && job.action === 'deploy'
407
+ && !job.committed && !job.checkpoint.restored);
408
+ if (!pinned && record.createdAt < Date.now() - 7 * 86400_000)
409
+ throw templateError('EXPIRED', 'Package expired');
410
+ return record;
184
411
  }
185
- async action(actor, requestId, action, args) {
186
- await this.ready;
187
- if (!requestId || requestId.length > 200)
188
- throw templateError('INVALID_ARGUMENT', 'A stable request id is required');
189
- if (action === 'inspect')
190
- return this.inspect(actor, args.aid);
191
- let aids = action === 'build' ? [args.aid] : args.targets ? Object.values(args.targets) : [args.targetAid];
192
- if (action === 'pull' && (args.targets !== undefined && (args.targetAid !== undefined
193
- || !args.targets || typeof args.targets !== 'object' || Array.isArray(args.targets)
194
- || !Object.keys(args.targets).length || Object.keys(args.targets).some(key => !/^[a-z0-9][a-z0-9_-]{0,31}$/.test(key)))
195
- || aids.some(aid => typeof aid !== 'string' || !aid) || new Set(aids).size !== aids.length)) {
196
- throw templateError('INVALID_ARGUMENT', 'Map each member to a distinct existing Agent');
197
- }
198
- if (action === 'push' || action === 'deploy') {
199
- const cached = this.record(args[action === 'push' ? 'buildId' : 'pullId'], action === 'push' ? 'build' : 'pull');
200
- if (cached.value.actor !== actor)
201
- throw templateError('NOT_ALLOWED', 'Cached template belongs to another requester');
202
- aids = cached.value.aids ?? [cached.value.aid];
203
- }
204
- for (const aid of aids)
205
- await this.deps.authorize(actor, aid);
206
- const existing = this.jobs.list();
207
- const overlaps = (j) => templateJobAids(j).some(aid => aids.includes(aid));
208
- const blocked = existing.some(j => overlaps(j) && j.event.code === 'INSTALL_BROKEN');
209
- if (blocked)
210
- throw templateError('INSTALL_BROKEN', 'Agent requires manual installation recovery');
211
- if (['build', 'deploy'].includes(action) && existing.some(j => overlaps(j) && j.event.status === 'running'
212
- && ['build', 'deploy'].includes(j.action) && !(j.actor === actor && (j.requestId === requestId
213
- || action === 'deploy' && j.args.pullId === args.pullId)))) {
214
- throw templateError('AGENT_BUSY', 'Agent already has a template mutation in progress');
215
- }
216
- const phase = { build: 'building', push: 'uploading', pull: 'downloading', deploy: 'backup' }[action];
217
- const { job, reused } = this.jobs.accept(actor, aids[0], requestId, action, args, phase, aids);
218
- if (!reused) {
219
- this.audit(job);
220
- const running = Promise.resolve().then(() => this.execute(job)).finally(() => this.work.delete(job.jobId));
221
- this.work.set(job.jobId, running);
222
- }
223
- return { jobId: job.jobId, status: job.event.status, reused };
412
+ async push(job) {
413
+ const record = this.packageRecord(job.actor, job.args.packageId);
414
+ for (const aid of record.provenance.sourceAids ?? [])
415
+ await this.step(job, () => this.deps.authorize(job.actor, aid));
416
+ if (record.data.scan.findings.some((item) => !job.args.releasedFindings.includes(item.id))) {
417
+ throw templateError('SCAN_BLOCKED', 'Release the package scan findings before upload');
418
+ }
419
+ const { aid, path: remote } = job.args.location;
420
+ const metadata = record.data.metadata;
421
+ if (remote !== '/templates/' + metadata.id + '/' + metadata.id + '-' + metadata.version + '.ectpl') {
422
+ throw templateError('INVALID_ARGUMENT', 'Upload path must match metadata id/version');
423
+ }
424
+ this.phase(job, 'uploading');
425
+ job.checkpoint.uploadIntent = true;
426
+ this.jobs.save(job);
427
+ await this.step(job, () => this.deps.upload(aid, remote, record.data.file, true));
428
+ job.result = { packageId: record.packageId, location: job.args.location, digest: record.data.digest,
429
+ size: record.data.size, metadata };
430
+ job.status = 'succeeded';
431
+ job.phase = 'completed';
432
+ this.jobs.save(job);
224
433
  }
225
- async wait(jobId) { await this.work.get(jobId); }
226
- progress(job, phase, message) {
227
- this.jobs.update(job, { phase, message });
434
+ async pull(job) {
435
+ const source = job.args.source;
436
+ if (source.kind === 'artifact') {
437
+ const record = this.packageRecord(job.actor, source.packageId);
438
+ const { file: _file, ...data } = record.data;
439
+ job.result = { ...data, packageId: record.packageId };
440
+ }
441
+ else {
442
+ const packageId = 'package_' + randomUUID();
443
+ const directory = path.join(this.cache, 'packages', packageId);
444
+ fs.mkdirSync(directory, { recursive: true });
445
+ job.checkpoint.packageId = packageId;
446
+ this.jobs.save(job);
447
+ const archivePath = path.join(directory, 'package.ectpl');
448
+ if (source.kind === 'remote')
449
+ await this.step(job, () => this.deps.download(source.download.shareId, archivePath, source.location));
450
+ else
451
+ fs.copyFileSync(source.path, archivePath);
452
+ const data = await this.executeTool(job, 'read-package', { archivePath, digest: source.digest });
453
+ writeTemplateState(path.join(directory, 'record.json'), { actor: job.actor, packageId, createdAt: Date.now(),
454
+ data: { ...data, file: archivePath }, provenance: { kind: 'import', source } });
455
+ job.result = { ...data, packageId };
456
+ }
457
+ job.status = 'succeeded';
458
+ job.phase = 'completed';
459
+ this.jobs.save(job);
460
+ }
461
+ previewRecord(id) {
462
+ if (!TEMPLATE_PREVIEW_ID.test(id))
463
+ throw templateError('INVALID_ARGUMENT', 'Invalid previewId');
464
+ return JSON.parse(fs.readFileSync(path.join(this.cache, 'previews', id, 'record.json'), 'utf8'));
465
+ }
466
+ async preview(job) {
467
+ const record = this.packageRecord(job.actor, job.args.packageId);
468
+ const keys = Object.keys(record.data.members).sort();
469
+ if (keys.join() !== Object.keys(job.args.members).sort().join()
470
+ || job.args.installMode === 'overwrite' && keys.length !== 1)
471
+ throw templateError('INVALID_ARGUMENT', 'Map every member; overwrite allows one');
472
+ const previewId = 'preview_' + randomUUID();
473
+ const out = path.join(this.cache, 'previews', previewId);
474
+ const members = {};
475
+ const targets = {};
476
+ const snapshot = this.deps.installation.hostSnapshot();
477
+ for (const key of keys) {
478
+ const selected = job.args.members[key];
479
+ const target = selected.target;
480
+ const aid = target.aid === 'auto' ? 'a' + randomUUID().replace(/-/g, '').slice(0, 14) + '.' + job.args.issuer : target.aid;
481
+ if (job.args.installMode === 'create')
482
+ this.deps.installation.available(aid, target.project);
483
+ else {
484
+ await this.step(job, () => this.deps.authorize(job.actor, aid));
485
+ targets[key] = await this.step(job, () => this.deps.target(aid, job.actor));
486
+ if (targets[key].projectPath !== target.project)
487
+ throw templateError('TARGET_CHANGED', 'Overwrite must use the current default project');
488
+ }
489
+ members[key] = { aid, projectPath: path.resolve(target.project), requestId: randomUUID() };
490
+ }
491
+ const values = Object.values(members);
492
+ if (new Set(values.map(value => value.aid)).size !== keys.length || values.some((left, i) => values.some((right, j) => i !== j && (left.projectPath === right.projectPath || left.projectPath.startsWith(right.projectPath + path.sep)
493
+ || right.projectPath.startsWith(left.projectPath + path.sep)))))
494
+ throw templateError('INVALID_ARGUMENT', 'Targets or projects overlap');
495
+ const data = await this.executeTool(job, 'preview', { archivePath: record.data.file, digest: record.data.digest,
496
+ installMode: job.args.installMode, members, targets, selections: job.args.members,
497
+ out, home: this.deps.root, ownerAid: job.actor, hostAid: this.deps.hostAid,
498
+ agentSchemaVersion: snapshot.schemaVersion, providers: snapshot.providers });
499
+ const plans = {};
500
+ const unresolved = [];
501
+ for (const key of keys) {
502
+ const config = data.configs[key];
503
+ const baseagent = config.active_baseagent;
504
+ const model = config.baseagents?.[baseagent];
505
+ const profile = data.profiles[key];
506
+ try {
507
+ await this.step(job, () => this.deps.validateModels(config, data.members.find((member) => member.key === key).providers));
508
+ if (job.args.installMode === 'create') {
509
+ const plan = { aid: members[key].aid, project: members[key].projectPath, baseagent,
510
+ provider: model?.provider, model: model?.model, effort: model?.effort, chatmode: config.chatmode,
511
+ ownerAid: job.actor, name: profile.name, description: profile.description || 'EvolCore template member.',
512
+ tags: profile.tags ?? [], type: 'agent', ...(profile.avatar ? { avatarUrl: profile.avatar } : {}) };
513
+ await this.step(job, () => this.deps.installation.validatePlan(plan));
514
+ plans[key] = plan;
515
+ }
516
+ }
517
+ catch (error) {
518
+ unresolved.push({ memberKey: key, code: error.code ?? 'UNRESOLVED', message: error.message });
519
+ }
520
+ }
521
+ const planDigest = unresolved.length ? null : 'sha256:' + templateFingerprint(JSON.parse(fs.readFileSync(data.planFile, 'utf8')));
522
+ const preview = { actor: job.actor, previewId, packageId: record.packageId, createdAt: Date.now(),
523
+ installMode: job.args.installMode, snapshot: templateFingerprint(snapshot), members, plans, planDigest, data };
524
+ writeTemplateState(path.join(out, 'record.json'), preview);
525
+ job.result = { previewId, planDigest, packageId: record.packageId, digest: record.data.digest, metadata: record.data.metadata,
526
+ installMode: preview.installMode, members: Object.fromEntries(keys.map(key => [key, {
527
+ target: { aid: members[key].aid, project: members[key].projectPath }, changes: data.members.find((member) => member.key === key)
528
+ }])),
529
+ bindingOwnerAid: job.actor, expiresAt: preview.createdAt + 3600_000, executable: !unresolved.length, unresolved,
530
+ changes: data.changes ?? [], ignored: data.ignored ?? [], warnings: data.warnings ?? [] };
531
+ job.status = 'succeeded';
532
+ job.phase = 'completed';
533
+ this.jobs.save(job);
228
534
  }
229
- async execute(job) {
535
+ async deploy(actor, requestId, args) {
536
+ const prior = this.jobs.list().find(job => job.actor === actor && job.action === 'deploy' && job.args.previewId === args.previewId);
537
+ if (prior) {
538
+ if (prior.fingerprint !== templateFingerprint({ action: 'deploy', args }))
539
+ throw templateError('CONFLICT', 'Preview has a different deployment');
540
+ this.jobs.bindRequest(actor, requestId, 'deploy', args, prior.jobId);
541
+ return this.view(prior);
542
+ }
543
+ const record = this.previewRecord(args.previewId);
544
+ if (record.actor !== actor)
545
+ throw templateError('NOT_ALLOWED', 'Preview belongs to another principal');
546
+ if (!record.planDigest || record.planDigest !== args.planDigest)
547
+ throw templateError('CONFLICT', 'Executable preview and matching planDigest required');
548
+ if (record.createdAt + 3600_000 <= Date.now())
549
+ throw templateError('EXPIRED', 'Preview expired');
550
+ if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
551
+ throw templateError('TARGET_CHANGED', 'Host configuration changed');
552
+ const accepted = this.jobs.accept(actor, requestId, 'deploy', args, structuredClone(record.members));
553
+ accepted.job.resumable = true;
554
+ this.jobs.save(accepted.job);
230
555
  try {
231
- for (const aid of templateJobAids(job))
232
- await this.deps.authorize(job.actor, aid);
233
- const data = await this[job.action](job);
234
- if (job.event.status === 'running')
235
- this.jobs.update(job, { event: 'template.result', status: 'succeeded', message: 'Completed', data });
556
+ this.jobs.associate(accepted.job);
236
557
  }
237
558
  catch (error) {
238
- this.jobs.update(job, { event: 'template.result', status: 'failed', code: error.code ?? 'TEMPLATE_FAILED',
239
- message: error.message, ...(error.data === undefined ? {} : { data: error.data }) });
559
+ accepted.job.status = 'paused';
560
+ accepted.job.error = { code: error.code ?? 'CONFLICT', message: error.message, retryable: true };
561
+ this.jobs.save(accepted.job);
562
+ return this.view(accepted.job);
563
+ }
564
+ this.launch(accepted.job, job => this.runInstallation(job));
565
+ return this.view(accepted.job);
566
+ }
567
+ async runInstallation(job) {
568
+ const previous = this.mutations;
569
+ let release;
570
+ this.mutations = new Promise(resolve => { release = resolve; });
571
+ await previous.catch(() => undefined);
572
+ try {
573
+ await this.install(job);
240
574
  }
241
575
  finally {
242
- this.audit(job);
576
+ release();
243
577
  }
244
578
  }
245
- async build(job) {
246
- const buildId = 'build_' + randomUUID();
247
- const dir = path.join(this.cache, buildId);
248
- const data = await this.deps.exclusive(job.aid, async () => {
249
- const resume = await this.deps.pause(job.aid);
250
- try {
251
- const options = await this.deps.source(job.aid, job.actor);
252
- return await this.tool('pack', { ...options, template: job.args.template, include: job.args.include, out: dir });
579
+ async install(job) {
580
+ this.current(job);
581
+ const record = JSON.parse(fs.readFileSync(path.join(this.cache, 'previews', job.args.previewId, 'record.json'), 'utf8'));
582
+ if (record.installMode === 'overwrite')
583
+ return this.runOverwrite(job, record);
584
+ if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
585
+ throw templateError('CONFLICT', 'Host configuration changed; team remains paused');
586
+ const plan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
587
+ if (record.planDigest !== 'sha256:' + templateFingerprint(plan))
588
+ throw templateError('CONFLICT', 'Frozen team plan changed');
589
+ for (const [key, config] of Object.entries(record.data.configs)) {
590
+ await this.step(job, () => this.deps.installation.validatePlan(record.plans[key]));
591
+ await this.step(job, () => this.deps.validateModels(config, record.data.members.find((member) => member.key === key).providers));
592
+ }
593
+ const legacyProfiles = false;
594
+ if (job.checkpoint.resourcesApplied)
595
+ await this.step(job, () => this.executeTool(job, 'verify-installation', { planFile: record.data.planFile }));
596
+ await this.step(job, () => this.deps.installation.reserve(job, record.plans));
597
+ const identities = await this.step(job, () => this.deps.installation.prepareIdentities(job, this.controllers.get(job.jobId)?.signal));
598
+ if (identities.status !== 'ready') {
599
+ job.phase = 'awaiting_owner';
600
+ job.status = 'paused';
601
+ this.jobs.save(job);
602
+ return;
603
+ }
604
+ if (!legacyProfiles)
605
+ job.checkpoint.profileProtocol = 1;
606
+ this.jobs.associate(job);
607
+ job.phase = 'preparing';
608
+ this.jobs.save(job);
609
+ const baselines = job.checkpoint.baselines ?? {};
610
+ for (const [key, member] of Object.entries(job.members)) {
611
+ await this.step(job, () => this.deps.installation.authorize(job.actor));
612
+ if (!member.initialized) {
613
+ member.phase = 'initializing';
614
+ this.jobs.save(job);
615
+ const state = await this.step(job, () => this.deps.installation.prepare(member.aid, record.plans[key], job.actor, member.requestId));
616
+ member.phase = state.phase;
617
+ member.code = state.error;
618
+ this.jobs.save(job);
619
+ if (state.error)
620
+ throw templateError(state.error, 'Team member initialization failed');
621
+ if (state.phase !== 'team_prepared' && !state.complete) {
622
+ job.phase = 'awaiting_owner';
623
+ job.status = 'paused';
624
+ this.jobs.save(job);
625
+ return;
626
+ }
253
627
  }
254
- finally {
255
- await resume();
628
+ await this.step(job, () => this.deps.installation.verify(member.aid));
629
+ if (!baselines[key]) {
630
+ const { createHash } = await import('node:crypto');
631
+ this.current(job);
632
+ baselines[key] = Object.fromEntries(plan.writes.filter((write) => write.path.startsWith(path.join(this.deps.root, 'agents', member.aid) + path.sep))
633
+ .map((write) => [write.path, fs.existsSync(write.path) ? { sha256: createHash('sha256').update(fs.readFileSync(write.path)).digest('hex'), mode: fs.statSync(write.path).mode & 0o777 } : null]));
256
634
  }
635
+ member.initialized = true;
636
+ job.checkpoint.baselines = baselines;
637
+ this.jobs.save(job);
638
+ }
639
+ if (!job.checkpoint.resourcesApplied) {
640
+ job.phase = 'applying';
641
+ this.jobs.save(job);
642
+ await this.step(job, () => this.executeTool(job, 'apply-installation', { planFile: record.data.planFile, baselines,
643
+ backupDir: path.join(this.cache, 'backups', job.jobId) }));
644
+ job.checkpoint.resourcesApplied = true;
645
+ this.jobs.save(job);
646
+ }
647
+ job.phase = 'publishing';
648
+ this.jobs.save(job);
649
+ for (const [key, member] of Object.entries(job.members)) {
650
+ await this.step(job, () => this.deps.installation.authorize(job.actor));
651
+ await this.step(job, () => this.deps.reload(member.aid));
652
+ const profile = { ...record.data.profiles[key], description: record.plans[key].description };
653
+ await this.publishProfile(job, key, profile, legacyProfiles);
654
+ }
655
+ job.activating = true;
656
+ job.phase = 'activating';
657
+ this.jobs.save(job);
658
+ for (const member of Object.values(job.members)) {
659
+ await this.step(job, () => this.deps.installation.authorize(job.actor));
660
+ await this.step(job, () => this.deps.installation.verify(member.aid));
661
+ member.phase = 'activating';
662
+ this.jobs.save(job);
663
+ if (!await this.step(job, () => this.deps.installation.activate(member.aid, job.actor, member.requestId))) {
664
+ job.activating = false;
665
+ job.status = 'paused';
666
+ job.phase = 'awaiting_owner';
667
+ this.jobs.save(job);
668
+ return;
669
+ }
670
+ member.phase = 'active';
671
+ member.runtimeReady = true;
672
+ this.jobs.save(job);
673
+ }
674
+ this.current(job);
675
+ job.phase = 'verifying';
676
+ this.jobs.save(job);
677
+ await this.step(job, () => this.executeTool(job, 'verify-installation', { planFile: record.data.planFile }));
678
+ for (const [key, member] of Object.entries(job.members)) {
679
+ await this.step(job, () => this.deps.installation.verify(member.aid));
680
+ if (!this.deps.installation.ready(member.aid))
681
+ throw templateError('TEAM_NOT_READY', 'A prepared member is unavailable');
682
+ await this.publishProfile(job, key, { ...record.data.profiles[key], description: record.plans[key].description }, false);
683
+ }
684
+ await this.step(job, () => this.deps.installation.authorize(job.actor));
685
+ if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
686
+ throw templateError('CONFLICT', 'Host configuration changed before team commit');
687
+ writeTemplateState(path.join(this.cache, 'teams', job.jobId, 'team-members.json'), {
688
+ version: 1, jobId: job.jobId, ownerAid: job.actor, hostAid: this.deps.hostAid,
689
+ members: Object.entries(job.members).map(([key, member]) => ({ key, aid: member.aid, project: member.projectPath, profile: record.data.profiles[key] })),
257
690
  });
258
- this.progress(job, 'scanning', 'Scanned template contents');
259
- atomicWriteJson(path.join(dir, 'record.json'), { actor: job.actor, aid: job.aid, createdAt: Date.now(), data });
260
- const { file: _file, ...publicData } = data;
261
- return { buildId, ...publicData };
691
+ job.committed = true;
692
+ job.activating = false;
693
+ job.status = 'succeeded';
694
+ job.phase = 'completed';
695
+ job.resumable = false;
696
+ job.result = { packageId: record.packageId, previewId: record.previewId, planDigest: record.planDigest,
697
+ installMode: record.installMode, committed: true, members: Object.fromEntries(Object.entries(job.members)
698
+ .map(([key, member]) => [key, { aid: member.aid, project: member.projectPath }])) };
699
+ this.jobs.save(job);
262
700
  }
263
- async push(job) {
264
- const { dir, value } = this.record(job.args.buildId, 'build');
265
- const { ownerAid, targetPath } = job.args;
266
- if (value.uploaded) {
267
- if (value.uploaded.location.aid !== ownerAid || value.uploaded.location.path !== targetPath) {
268
- throw templateError('CONFLICT', 'buildId is already uploaded to another location');
701
+ async publishProfile(job, key, profile, legacyRecovery) {
702
+ const member = job.members[key];
703
+ const digest = (value) => templateFingerprint(Object.fromEntries(['name', 'description', 'avatar', 'tags', 'exttype'].filter(field => value[field] !== undefined).map(field => [field, value[field]])));
704
+ const expectedDigest = digest(profile);
705
+ const current = await this.step(job, () => this.deps.readProfile(member.aid));
706
+ let publication = member.profilePublication;
707
+ if (!publication) {
708
+ if (legacyRecovery && digest(current.profile) !== expectedDigest)
709
+ throw templateError('CONFLICT', 'Profile checkpoint missing; independent edits cannot be ruled out');
710
+ publication = member.profilePublication = { state: 'intent', originalDigest: digest(current.profile),
711
+ expectedDigest, originalVersion: current.profileVersion };
712
+ this.jobs.save(job);
713
+ }
714
+ if (publication.expectedDigest !== expectedDigest)
715
+ throw templateError('CONFLICT', 'Frozen team profile changed');
716
+ if (publication.state === 'confirmed') {
717
+ if (digest(current.profile) !== expectedDigest || publication.confirmedVersion !== current.profileVersion) {
718
+ throw templateError('CONFLICT', 'Confirmed team profile was independently changed');
269
719
  }
270
- return value.uploaded;
271
- }
272
- const released = new Set(job.args.releasedFindings ?? []);
273
- if (value.data.scan.findings.some((f) => !released.has(f.findingId)))
274
- throw templateError('SCAN_BLOCKED', 'Release each scan finding before upload');
275
- if (targetPath !== '/templates/' + value.data.template.id + '/' + value.data.template.id + '-' + value.data.template.version + '.ectpl') {
276
- throw templateError('INVALID_ARGUMENT', 'Upload path must match the package id and version');
277
- }
278
- const recoverExisting = value.uploadIntent?.ownerAid === ownerAid && value.uploadIntent?.targetPath === targetPath;
279
- atomicWriteJson(path.join(dir, 'record.json'), { ...value, uploadIntent: { ownerAid, targetPath } });
280
- await this.deps.upload(ownerAid, targetPath, value.data.file, recoverExisting);
281
- const data = { buildId: job.args.buildId, location: { aid: ownerAid, path: targetPath }, digest: value.data.digest, size: value.data.size };
282
- atomicWriteJson(path.join(dir, 'record.json'), { ...value, uploaded: data });
283
- return data;
284
- }
285
- async pull(job) {
286
- const pullId = 'pull_' + randomUUID();
287
- const dir = path.join(this.cache, pullId);
288
- fs.mkdirSync(dir, { recursive: true });
289
- const archivePath = path.join(dir, 'package.ectpl');
290
- await this.deps.download(job.args.download.shareId, archivePath, job.args.location);
291
- this.progress(job, 'verifying', 'Verifying downloaded package');
292
- const targets = {};
293
- if (job.args.targets)
294
- for (const [key, aid] of Object.entries(job.args.targets)) {
295
- targets[key] = await this.deps.target(aid, job.actor);
720
+ return;
721
+ }
722
+ if (digest(current.profile) !== expectedDigest) {
723
+ if (digest(current.profile) !== publication.originalDigest || current.profileVersion !== publication.originalVersion) {
724
+ throw templateError('CONFLICT', 'Profile changed while publication outcome was unknown');
296
725
  }
297
- const options = { ...(job.args.targets ? { targets } : await this.deps.target(job.aid, job.actor)),
298
- archivePath, out: dir, digest: job.args.digest, pullId };
299
- const data = await this.tool('inspect-package', options);
300
- this.progress(job, 'preflight', 'Prepared installation preview');
301
- delete options.archivePath;
302
- options.packageDir = path.join(dir, 'unpacked');
303
- atomicWriteJson(path.join(dir, 'record.json'), { actor: job.actor, aid: job.aid, aids: templateJobAids(job), createdAt: Date.now(), options, data });
304
- const { planFile: _planFile, ...publicData } = data;
305
- return publicData;
726
+ await this.step(job, () => this.deps.publishProfile(member.aid, profile, publication.originalVersion));
727
+ }
728
+ const confirmed = await this.step(job, () => this.deps.readProfile(member.aid));
729
+ if (digest(confirmed.profile) !== expectedDigest)
730
+ throw templateError('PROFILE_NOT_CONFIRMED', 'Team profile publication is not confirmed');
731
+ publication.state = 'confirmed';
732
+ publication.confirmedVersion = confirmed.profileVersion;
733
+ this.jobs.save(job);
306
734
  }
307
- async deploy(job) {
308
- // Shared skill/project writes are serialized across Agent installs, in addition to the per-Agent work gate.
309
- const previous = this.mutations;
310
- let release;
311
- this.mutations = new Promise(resolve => { release = resolve; });
312
- await previous.catch(() => undefined);
735
+ async runOverwrite(job, record) {
736
+ const member = Object.values(job.members)[0];
737
+ const key = Object.keys(job.members)[0];
738
+ const release = await this.deps.hold(member.aid, job.jobId);
313
739
  try {
314
- return await this.withTargets(templateJobAids(job), async () => {
315
- const { dir, value } = this.record(job.args.pullId, 'pull');
316
- const planFile = value.data.planFile;
317
- const originalPlan = JSON.parse(fs.readFileSync(planFile, 'utf8'));
318
- const resume = await this.pauseTargets(templateJobAids(job));
319
- let broken = false;
320
- let touched = false;
321
- let resumed = false;
740
+ await this.step(job, () => this.deps.authorize(job.actor, member.aid));
741
+ const current = await this.step(job, () => this.deps.target(member.aid, job.actor));
742
+ if (current.projectPath !== member.projectPath)
743
+ throw templateError('TARGET_CHANGED', 'Target project changed');
744
+ await this.executeTool(job, 'overlay', { operation: 'verify', planFile: record.data.planFile });
745
+ const original = await this.step(job, () => this.deps.readProfile(member.aid));
746
+ job.checkpoint.originalProfile = original;
747
+ job.checkpoint.backupDir = path.join(this.cache, 'backups', job.jobId);
748
+ job.checkpoint.installMode = 'overwrite';
749
+ this.jobs.save(job);
750
+ await this.executeTool(job, 'overlay', { planFile: record.data.planFile, backupDir: job.checkpoint.backupDir });
751
+ job.checkpoint.resourcesApplied = true;
752
+ this.jobs.save(job);
753
+ await this.step(job, () => this.deps.reload(member.aid));
754
+ await this.publishProfile(job, key, record.data.profiles[key], false);
755
+ job.activating = true;
756
+ this.jobs.save(job);
757
+ member.runtimeReady = this.deps.installation.ready(member.aid);
758
+ if (!member.runtimeReady)
759
+ throw templateError('RECOVERY_REQUIRED', 'Reloaded target is not ready');
760
+ job.committed = true;
761
+ job.activating = false;
762
+ job.status = 'succeeded';
763
+ job.resumable = false;
764
+ job.phase = 'completed';
765
+ job.result = { packageId: record.packageId, previewId: record.previewId, planDigest: record.planDigest,
766
+ installMode: 'overwrite', committed: true, members: { [key]: { aid: member.aid, project: member.projectPath } } };
767
+ this.jobs.save(job);
768
+ }
769
+ catch (error) {
770
+ const current = this.jobs.read(job.jobId);
771
+ await this.compensate(current);
772
+ throw error;
773
+ }
774
+ finally {
775
+ const current = this.jobs.read(job.jobId);
776
+ if (current.committed || current.checkpoint.restored || !current.checkpoint.backupDir)
777
+ await release();
778
+ else
779
+ this.deps.block(member.aid);
780
+ }
781
+ }
782
+ async compensate(job) {
783
+ const record = this.previewRecord(job.args.previewId);
784
+ if (record.installMode === 'create') {
785
+ const pending = [];
786
+ for (const member of Object.values(job.members)) {
787
+ if (!this.deps.installation.ownsMember(job, member.aid))
788
+ continue;
322
789
  try {
323
- for (const aid of templateJobAids(job))
324
- await this.deps.authorize(job.actor, aid);
325
- await this.tool('overlay', { operation: 'verify', planFile });
326
- const currentTargets = {};
327
- const profiles = new Map();
328
- const multi = !!value.options.targets;
329
- if (multi && (Object.keys(job.args.providers ?? {}).length || Object.keys(job.args.externalAids ?? {}).length)
330
- || !multi && job.args.members !== undefined)
331
- throw templateError('INVALID_ARGUMENT', 'Use member selections only with a targets mapping');
332
- for (const member of this.planMembers(originalPlan)) {
333
- const aid = member.targetAid;
334
- const profile = await this.deps.readProfile(aid);
335
- if (profile.profileVersion !== member.profileVersion)
336
- throw templateError('CONFLICT', 'Target profile changed after preview: ' + aid);
337
- profiles.set(aid, profile);
338
- const current = await this.deps.target(aid, job.actor);
339
- if (current.projectPath !== member.projectPath)
340
- throw templateError('CONFLICT', 'Default project changed after preview: ' + aid);
341
- currentTargets[member.key ?? 'agent'] = current;
342
- }
343
- const data = await this.tool('inspect-package', { ...value.options,
344
- ...(multi ? { targets: currentTargets, members: job.args.members ?? {} }
345
- : { ...currentTargets.agent, selections: job.args.providers ?? {}, externalAids: job.args.externalAids ?? {} }) });
346
- const plan = JSON.parse(fs.readFileSync(data.planFile, 'utf8'));
347
- for (const member of this.planMembers(plan)) {
348
- const write = plan.writes.find((w) => w.path === path.join(this.deps.root, 'agents', member.targetAid, 'config.json'));
349
- if (!write)
350
- throw templateError('INVALID_ARGUMENT', 'Missing target configuration');
351
- await this.deps.validateModels(JSON.parse(Buffer.from(write.content, 'base64').toString()), member.providers);
352
- }
353
- await this.tool('overlay', { operation: 'verify', plan: originalPlan });
354
- job.backupDir = path.join(dir, 'backup');
355
- this.jobs.save(job);
356
- this.progress(job, 'applying', 'Applying selected template contents');
357
- touched = true;
358
- await this.tool('overlay', { planFile: data.planFile, backupDir: job.backupDir });
359
- this.progress(job, 'reloading', 'Reloading target Agent');
360
- for (const aid of templateJobAids(job))
361
- await this.deps.reload(aid);
362
- this.progress(job, 'publishing-profile', 'Publishing Agent profile');
363
- for (const member of this.planMembers(plan)) {
364
- job.profileAttempted = true;
365
- job.profileAttemptedAids = [...(job.profileAttemptedAids ?? []), member.targetAid];
366
- this.jobs.save(job);
367
- await this.deps.publishProfile(member.targetAid, member.profile, profiles.get(member.targetAid).profileVersion);
368
- }
369
- const outcome = (preview, member) => ({ targetAid: member.targetAid,
370
- applied: { soul: preview.soul.add.length + preview.soul.overwrite.length,
371
- triggers: preview.triggers.add.length + preview.triggers.overwrite.length,
372
- skills: preview.skills.length, files: preview.files.add + preview.files.overwrite },
373
- providers: Object.fromEntries(member.providers.map((r) => [r.baseagent, r.provider])) });
374
- const result = { ...(multi ? { members: plan.members.map((member) => ({ key: member.key,
375
- ...outcome(data.members.find((m) => m.key === member.key).preview, member) })) }
376
- : outcome(data.preview, this.planMembers(plan)[0])),
377
- template: { id: plan.package.id, version: plan.package.version, digest: value.options.digest },
378
- reloaded: true, profilePublished: true, warnings: [] };
379
- await resume();
380
- resumed = true;
381
- this.jobs.update(job, { event: 'template.result', status: 'succeeded', message: 'Completed', data: result });
382
- try {
383
- fs.rmSync(job.backupDir, { recursive: true, force: true });
384
- }
385
- catch (error) {
386
- logger.warn('[Template] Backup cleanup deferred: ' + String(error));
387
- }
388
- return result;
389
- }
390
- catch (error) {
391
- if (error.code === 'BACKUP_FAILED')
392
- throw error;
393
- if (!touched)
394
- throw error;
395
- this.progress(job, 'rollback', 'Restoring previous contents');
396
- try {
397
- if (job.backupDir && fs.existsSync(path.join(job.backupDir, 'journal.json'))) {
398
- await this.tool('overlay', { operation: 'restore', backupDir: job.backupDir });
399
- }
400
- if (job.profileAttempted) {
401
- const applied = JSON.parse(fs.readFileSync(planFile, 'utf8'));
402
- await this.restoreProfiles(job, applied);
403
- }
404
- for (const aid of templateJobAids(job))
405
- await this.deps.reload(aid);
406
- }
407
- catch (restoreError) {
408
- broken = true;
409
- for (const aid of templateJobAids(job))
410
- this.deps.block(aid);
411
- throw templateError('INSTALL_BROKEN', error.message + '; restore failed: ' + restoreError.message, { rolledBack: false });
412
- }
413
- throw templateError('INSTALL_FAILED', error.message, { rolledBack: true });
790
+ await this.deps.installation.stop(member.aid, job);
414
791
  }
415
- finally {
416
- if (!broken && !resumed)
417
- await resume();
792
+ catch {
793
+ pending.push(member.aid);
418
794
  }
419
- });
795
+ }
796
+ if (pending.length)
797
+ throw templateError('RECOVERY_REQUIRED', 'Some created members still require stopping', { pending });
798
+ return;
420
799
  }
421
- finally {
422
- release();
800
+ const member = Object.values(job.members)[0];
801
+ const key = Object.keys(job.members)[0];
802
+ if (job.checkpoint.backupDir && fs.existsSync(path.join(job.checkpoint.backupDir, 'journal.json'))) {
803
+ await this.tool('overlay', { operation: 'restore', backupDir: job.checkpoint.backupDir });
804
+ }
805
+ const original = job.checkpoint.originalProfile;
806
+ if (original) {
807
+ const current = await this.deps.readProfile(member.aid);
808
+ const fields = (value) => Object.fromEntries(['name', 'description', 'avatar', 'tags', 'exttype']
809
+ .filter(field => value?.[field] !== undefined).map(field => [field, value[field]]));
810
+ const digest = templateFingerprint(fields(current.profile));
811
+ if (digest !== templateFingerprint(fields(original.profile))) {
812
+ if (digest !== templateFingerprint(fields(record.data.profiles[key])))
813
+ throw templateError('PROFILE_CONFLICT', 'Independent profile edit during rollback');
814
+ await this.deps.publishProfile(member.aid, original.profile, current.profileVersion);
815
+ }
423
816
  }
817
+ await this.deps.reload(member.aid);
818
+ job.checkpoint.restored = true;
819
+ job.activating = false;
820
+ this.jobs.save(job);
424
821
  }
425
822
  }
426
823
  let activeService;
427
824
  export function setAgentTemplateService(service) { activeService = service; }
428
825
  export function getAgentTemplateService() {
429
826
  if (!activeService)
430
- throw templateError('NOT_CONFIGURED', 'Template service is not initialized');
827
+ throw templateError('NOT_FOUND', 'Template service is not initialized');
431
828
  return activeService;
432
829
  }
433
830
  export function subscribeTemplateJob(jobId, actor, send) {
@@ -442,18 +839,16 @@ export function subscribeTemplateJob(jobId, actor, send) {
442
839
  return;
443
840
  pending = true;
444
841
  try {
445
- const service = getAgentTemplateService();
446
- const job = service.jobs.get(actor, { jobId });
447
- if (job.event.seq <= seq)
842
+ const job = await getAgentTemplateService().query(actor, { jobId });
843
+ if (job.seq <= seq)
448
844
  return;
449
- const event = await service.query(actor, { jobId });
450
- await send(event);
451
- seq = event.seq;
452
- if (event.event === 'template.result')
845
+ await send({ type: 'menu.event', event: 'template.job', ...job });
846
+ seq = job.seq;
847
+ if (['succeeded', 'cancelled', 'failed'].includes(job.status))
453
848
  stop();
454
849
  }
455
850
  catch (error) {
456
- logger.warn('[Template] Event delivery stopped: ' + (error instanceof Error ? error.message : String(error)));
851
+ logger.warn('[Template] Event delivery stopped: ' + String(error));
457
852
  stop();
458
853
  }
459
854
  finally {