evolcore 0.0.43-test.7 → 0.0.45

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 (127) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +22 -9
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/claude-runner.js +1 -1
  9. package/dist/aun/aid/agentmd.js +56 -1
  10. package/dist/aun/aid/client.js +3 -1
  11. package/dist/aun/menu/client.js +3 -2
  12. package/dist/aun/msg/p2p.js +1 -1
  13. package/dist/channels/aun.js +47 -32
  14. package/dist/cli/agent-command.js +5 -0
  15. package/dist/cli/agent-create.js +5 -1
  16. package/dist/cli/agent-template.js +124 -0
  17. package/dist/cli/aun-commands.js +2 -2
  18. package/dist/cli/ctl-command.js +2 -1
  19. package/dist/cli/daemon-commands.js +5 -0
  20. package/dist/cli/ecmsg-gateway.js +2 -2
  21. package/dist/cli/events-command.js +45 -9
  22. package/dist/cli/index.js +29 -0
  23. package/dist/cli/net-check.js +1 -1
  24. package/dist/cli/restart-monitor.js +115 -36
  25. package/dist/cli/services-command.js +29 -3
  26. package/dist/cli/thread-command.js +97 -11
  27. package/dist/config/boot-log.js +8 -8
  28. package/dist/config/schema-migration.js +41 -16
  29. package/dist/core/agent-ipc-registration.js +25 -4
  30. package/dist/core/agent-runtime.js +2 -0
  31. package/dist/core/auth/operation-authorizer.js +2 -0
  32. package/dist/core/auth/operation-catalog.js +11 -2
  33. package/dist/core/channel-runtime.js +16 -9
  34. package/dist/core/command/agent-control.js +11 -1
  35. package/dist/core/command/agent-template-menu.js +147 -0
  36. package/dist/core/command/command-handler.js +27 -6
  37. package/dist/core/command/eventcenter-menu.js +158 -28
  38. package/dist/core/command/menu-catalog.js +8 -1
  39. package/dist/core/command/menu-handler.js +18 -6
  40. package/dist/core/command/menu-protocol.js +11 -2
  41. package/dist/core/daemon-control.js +14 -0
  42. package/dist/core/daemon-lifecycle.js +262 -189
  43. package/dist/core/handoff/runtime.js +42 -10
  44. package/dist/core/ipc-registration.js +5 -1
  45. package/dist/core/legacy-rename.js +41 -0
  46. package/dist/core/message/aun-ipc-sender.js +118 -13
  47. package/dist/core/message/im-renderer.js +88 -1
  48. package/dist/core/message/message-queue.js +66 -15
  49. package/dist/core/message/pending-hints.js +29 -5
  50. package/dist/core/message/response-engine.js +37 -7
  51. package/dist/core/message/send-routing.js +13 -6
  52. package/dist/core/pack-auth.js +94 -0
  53. package/dist/core/pack-install.js +194 -0
  54. package/dist/core/permission/ec-command-parser.js +49 -16
  55. package/dist/core/rate-window.js +48 -0
  56. package/dist/core/relation/peer-identity.js +28 -0
  57. package/dist/core/session/session-fs-store.js +66 -26
  58. package/dist/core/session/session-idle-monitor.js +59 -19
  59. package/dist/core/session/session-manager.js +13 -4
  60. package/dist/core/thread/thread-route.js +2 -2
  61. package/dist/core/thread/thread-service.js +52 -3
  62. package/dist/eck/kit-renderer.js +1 -1
  63. package/dist/eck/message-renderer.js +2 -0
  64. package/dist/event-center/admission-materializer.js +22 -12
  65. package/dist/event-center/bus-gate.js +20 -2
  66. package/dist/event-center/bus-host.js +46 -29
  67. package/dist/event-center/bus-resolver.js +1 -1
  68. package/dist/event-center/center-config.js +41 -14
  69. package/dist/event-center/daemon.js +1 -2
  70. package/dist/event-center/directory-source.js +3 -1
  71. package/dist/event-center/index-generator.js +12 -2
  72. package/dist/event-center/ipc-operation.js +140 -25
  73. package/dist/event-center/pack-loader.js +61 -56
  74. package/dist/event-center/pack-manager.js +2 -2
  75. package/dist/event-center/registry.js +242 -17
  76. package/dist/event-center/runtime.js +271 -75
  77. package/dist/event-center/types.js +20 -4
  78. package/dist/event-center/validation.js +34 -12
  79. package/dist/index.js +147 -44
  80. package/dist/ipc.js +44 -4
  81. package/dist/paths.js +2 -2
  82. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  83. package/dist/services/index.js +3 -3
  84. package/dist/services/ipc-operation.js +99 -7
  85. package/dist/services/pack-manager.js +17 -6
  86. package/dist/services/router.js +8 -5
  87. package/dist/services/validation.js +5 -5
  88. package/dist/trigger/scheduler.js +38 -0
  89. package/dist/trigger/script-sandbox.js +52 -2
  90. package/dist/utils/npm-ops.js +2 -1
  91. package/dist/utils/package-version-info.js +6 -3
  92. package/kits/docs/aun/ABILITY_CALLING.md +4 -3
  93. package/kits/docs/context-assembly.md +1 -1
  94. package/kits/docs/evolcore/INDEX.md +3 -3
  95. package/kits/docs/evolcore/agent.md +22 -1
  96. package/kits/docs/evolcore/event-center.md +30 -10
  97. package/kits/docs/evolcore/fs.md +4 -3
  98. package/kits/docs/evolcore/menu-protocol.md +7 -1
  99. package/kits/docs/evolcore/msg.md +8 -8
  100. package/kits/docs/evolcore/response.md +2 -2
  101. package/kits/docs/evolcore/services.md +27 -10
  102. package/kits/docs/evolcore/thread-chain.md +15 -3
  103. package/kits/rules/06-channel.md +1 -0
  104. package/kits/skills/ability/references/calling.md +2 -2
  105. package/kits/skills/ec-group/SKILL.md +5 -8
  106. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  107. package/kits/skills/ec-trigger/SKILL.md +4 -4
  108. package/kits/skills/thread-ops/SKILL.md +10 -10
  109. package/kits/templates/message-fragments/item.md +1 -1
  110. package/kits/templates/system-fragments/channel.md +1 -1
  111. package/kits/templates/system-fragments/commands.md +1 -1
  112. package/kits/templates/system-fragments/reply.md +1 -0
  113. package/kits/templates/system-fragments/thread.md +3 -2
  114. package/package.json +4 -3
  115. package/scripts/agent-template/index.mjs +40 -0
  116. package/scripts/agent-template/inspect.mjs +240 -0
  117. package/scripts/agent-template/overlay.mjs +71 -0
  118. package/scripts/agent-template/pack.mjs +169 -0
  119. package/scripts/agent-template/shared/common.mjs +235 -0
  120. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  121. package/scripts/agent-template/shared/plan.mjs +129 -0
  122. package/scripts/agent-template/shared/team-schema.json +70 -0
  123. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  124. package/scripts/agent-template/shared/template-package.mjs +265 -0
  125. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  126. package/scripts/agent-template/shared/template.mjs +142 -0
  127. package/dist/event-center/client-factory.js +0 -50
@@ -0,0 +1,465 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { atomicWriteJson } from '../core/session/session-fs-store.js';
5
+ import { TemplateJobs, templateFingerprint } from './jobs.js';
6
+ import { runTemplateTool } from './tool-runner.js';
7
+ import { templateError, templateJobAids } from './types.js';
8
+ import { logger } from '../utils/logger.js';
9
+ export class AgentTemplateService {
10
+ deps;
11
+ jobs;
12
+ cache;
13
+ work = new Map();
14
+ mutations = Promise.resolve();
15
+ ready;
16
+ tool;
17
+ constructor(deps) {
18
+ this.deps = deps;
19
+ this.cache = path.join(deps.root, 'data', 'template-cache');
20
+ this.jobs = new TemplateJobs(path.join(this.cache, 'jobs'));
21
+ 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 });
46
+ }
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 });
50
+ }
51
+ }
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() {
66
+ 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);
70
+ }
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
+ }
97
+ }
98
+ catch {
99
+ rolledBack = false;
100
+ for (const aid of templateJobAids(job))
101
+ this.deps.block(aid);
102
+ }
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);
108
+ }
109
+ this.cleanup();
110
+ }
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);
120
+ }
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);
127
+ }
128
+ async pauseTargets(aids) {
129
+ const callbacks = [];
130
+ const resume = async () => {
131
+ const errors = [];
132
+ for (const callback of callbacks.splice(0).reverse()) {
133
+ try {
134
+ await callback();
135
+ }
136
+ catch (error) {
137
+ errors.push(error);
138
+ }
139
+ }
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));
146
+ }
147
+ catch (error) {
148
+ await resume();
149
+ throw error;
150
+ }
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 }];
156
+ }
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);
167
+ }
168
+ }
169
+ if (errors.length)
170
+ throw errors[0];
171
+ }
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));
176
+ }
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;
184
+ }
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 };
224
+ }
225
+ async wait(jobId) { await this.work.get(jobId); }
226
+ progress(job, phase, message) {
227
+ this.jobs.update(job, { phase, message });
228
+ }
229
+ async execute(job) {
230
+ 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 });
236
+ }
237
+ 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 }) });
240
+ }
241
+ finally {
242
+ this.audit(job);
243
+ }
244
+ }
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 });
253
+ }
254
+ finally {
255
+ await resume();
256
+ }
257
+ });
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 };
262
+ }
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');
269
+ }
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);
296
+ }
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;
306
+ }
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);
313
+ 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;
322
+ 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 });
414
+ }
415
+ finally {
416
+ if (!broken && !resumed)
417
+ await resume();
418
+ }
419
+ });
420
+ }
421
+ finally {
422
+ release();
423
+ }
424
+ }
425
+ }
426
+ let activeService;
427
+ export function setAgentTemplateService(service) { activeService = service; }
428
+ export function getAgentTemplateService() {
429
+ if (!activeService)
430
+ throw templateError('NOT_CONFIGURED', 'Template service is not initialized');
431
+ return activeService;
432
+ }
433
+ export function subscribeTemplateJob(jobId, actor, send) {
434
+ let stopped = false;
435
+ let pending = false;
436
+ let seq = 0;
437
+ const timer = setInterval(() => { void poll(); }, 500);
438
+ timer.unref?.();
439
+ const stop = () => { stopped = true; clearInterval(timer); };
440
+ const poll = async () => {
441
+ if (stopped || pending)
442
+ return;
443
+ pending = true;
444
+ try {
445
+ const service = getAgentTemplateService();
446
+ const job = service.jobs.get(actor, { jobId });
447
+ if (job.event.seq <= seq)
448
+ return;
449
+ const event = await service.query(actor, { jobId });
450
+ await send(event);
451
+ seq = event.seq;
452
+ if (event.event === 'template.result')
453
+ stop();
454
+ }
455
+ catch (error) {
456
+ logger.warn('[Template] Event delivery stopped: ' + (error instanceof Error ? error.message : String(error)));
457
+ stop();
458
+ }
459
+ finally {
460
+ pending = false;
461
+ }
462
+ };
463
+ void poll();
464
+ return stop;
465
+ }
@@ -0,0 +1,45 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { getPackageRoot } from '../paths.js';
6
+ import { templateError } from './types.js';
7
+ const execute = promisify(execFile);
8
+ export async function runTemplateTool(command, options) {
9
+ const base = process.env.TMPDIR;
10
+ if (!base || !path.isAbsolute(base))
11
+ throw templateError('TEMP_UNAVAILABLE', 'Template tools require absolute TMPDIR');
12
+ fs.mkdirSync(base, { recursive: true });
13
+ const temporary = fs.mkdtempSync(path.join(base, 'template-tool-'));
14
+ const input = path.join(temporary, 'input.json');
15
+ fs.writeFileSync(input, JSON.stringify({ ...options, packageRoot: getPackageRoot() }), { mode: 0o600 });
16
+ try {
17
+ let stdout;
18
+ try {
19
+ ({ stdout } = await execute(process.execPath, [path.join(getPackageRoot(), 'scripts', 'agent-template', 'index.mjs'),
20
+ command, '--options-file', input], { env: { ...process.env }, maxBuffer: 32 * 1024 * 1024, timeout: 5 * 60_000 }));
21
+ }
22
+ catch (error) {
23
+ const output = error.stdout;
24
+ if (!output)
25
+ throw templateError('TOOL_FAILED', 'Template tool failed before returning a result');
26
+ stdout = output;
27
+ }
28
+ const lines = stdout.split(/\r?\n/).filter(Boolean);
29
+ const result = lines.map(line => { try {
30
+ return JSON.parse(line);
31
+ }
32
+ catch {
33
+ return null;
34
+ } })
35
+ .filter(item => item?.type === 'result').at(-1);
36
+ if (!result)
37
+ throw templateError('TOOL_FAILED', 'Template tool returned no structured result');
38
+ if (!result.ok)
39
+ throw templateError(result.code ?? 'TOOL_FAILED', result.message, result.data);
40
+ return result.data;
41
+ }
42
+ finally {
43
+ fs.rmSync(temporary, { recursive: true, force: true });
44
+ }
45
+ }
@@ -0,0 +1,5 @@
1
+ export const TEMPLATE_ACTIONS = ['inspect', 'build', 'push', 'pull', 'deploy'];
2
+ export function templateJobAids(job) { return job.aids ?? [job.aid]; }
3
+ export function templateError(code, message, data) {
4
+ return Object.assign(new Error(message), { code, ...(data === undefined ? {} : { data }) });
5
+ }
@@ -2410,7 +2410,7 @@ export class AgentRunner {
2410
2410
  dangerouslyDisableSandbox: true,
2411
2411
  });
2412
2412
  }
2413
- // proactive 模式行为策略(首次工具调用必须是 ec msg send)
2413
+ // proactive 模式行为策略(首次工具调用必须是 ecmsg send)
2414
2414
  const sessionPolicyHook = this.permissionContexts.get(sessionId)?.policyHook;
2415
2415
  let policyResult;
2416
2416
  if (sessionPolicyHook) {
@@ -496,6 +496,59 @@ export function stripAgentMdSignature(content) {
496
496
  function escapeRegExp(value) {
497
497
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
498
498
  }
499
+ /**
500
+ * 统计一个被折行的 YAML 标量值在后续行里占用的续行数。
501
+ *
502
+ * `yaml` 的 stringify 默认按 80 列折行,历史名片里会留下
503
+ * `avatar: "https://…-2d\` + 换行 + 缩进续行 + `"` 这种写法。
504
+ * 替换字段时只改第一行、把续行留下,会让整个 frontmatter 无法解析,
505
+ * 所以这里按引号状态把续行一并算出来。
506
+ *
507
+ * 只处理以引号开头的值:未加引号的普通标量也可能跨行,但那种写法
508
+ * 目前只出现在手写名片里,按单行处理至少会在校验阶段明确报错,
509
+ * 不会静默吞掉后面的成块映射(如 ownership.statement)。
510
+ */
511
+ function countScalarContinuationLines(valueText, followingLines) {
512
+ const head = valueText.trimStart();
513
+ const quote = head[0];
514
+ if (quote !== '"' && quote !== "'")
515
+ return 0;
516
+ let open = true;
517
+ let escaped = false;
518
+ const scan = (text) => {
519
+ for (let index = 0; index < text.length; index++) {
520
+ const char = text[index];
521
+ if (quote === '"') {
522
+ if (escaped)
523
+ escaped = false;
524
+ else if (char === '\\')
525
+ escaped = true;
526
+ else if (char === '"') {
527
+ open = false;
528
+ return;
529
+ }
530
+ }
531
+ else if (char === "'") {
532
+ // 单引号串里 `''` 表示一个字面量单引号
533
+ if (text[index + 1] === "'")
534
+ index++;
535
+ else {
536
+ open = false;
537
+ return;
538
+ }
539
+ }
540
+ }
541
+ // 行尾的 `\` 转义的是换行本身,续行仍然在引号内
542
+ escaped = false;
543
+ };
544
+ scan(head.slice(1));
545
+ let continuation = 0;
546
+ while (open && continuation < followingLines.length) {
547
+ scan(followingLines[continuation] ?? '');
548
+ continuation++;
549
+ }
550
+ return continuation;
551
+ }
499
552
  function updateAgentMdFrontmatterField(content, key, value, insertAfterKey) {
500
553
  const original = content;
501
554
  const payload = stripAgentMdSignature(content);
@@ -514,7 +567,9 @@ function updateAgentMdFrontmatterField(content, key, value, insertAfterKey) {
514
567
  const fieldIndex = fmLines.findIndex(line => fieldPattern.test(lineValue(line)));
515
568
  if (fieldIndex >= 0) {
516
569
  const existingLine = fmLines[fieldIndex] ?? '';
517
- fmLines[fieldIndex] = `${key}: ${yamlDoubleQuote(value)}${lineEnding(existingLine, defaultEol)}`;
570
+ const existingText = lineValue(existingLine);
571
+ const continuation = countScalarContinuationLines(existingText.slice(existingText.indexOf(':') + 1), fmLines.slice(fieldIndex + 1).map(lineValue));
572
+ fmLines.splice(fieldIndex, 1 + continuation, `${key}: ${yamlDoubleQuote(value)}${lineEnding(existingLine, defaultEol)}`);
518
573
  }
519
574
  else {
520
575
  const anchorPattern = insertAfterKey ? new RegExp(`^${escapeRegExp(insertAfterKey)}\\s*:`) : null;
@@ -14,6 +14,8 @@ export function suppressSdkLogs() {
14
14
  const _origStderrWrite = process.stderr.write.bind(process.stderr);
15
15
  const SDK_LOG_RE = /^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\]\[(?:DEBUG|INFO|WARN|ERROR)\]/;
16
16
  const KEYSTORE_WARN_RE = /seed migration failed; continuing with legacy \.seed/;
17
+ // Node 自带的实验特性警告(SDK 的 SQLite store 触发),与命令结果无关。
18
+ const NODE_SQLITE_WARN_RE = /ExperimentalWarning: SQLite is an experimental feature|Use `node --trace-warnings \.\.\.` to show where the warning was created/;
17
19
  console.log = (...args) => { if (typeof args[0] === 'string' && SDK_LOG_RE.test(args[0]))
18
20
  return; _origLog(...args); };
19
21
  console.info = (...args) => { if (typeof args[0] === 'string' && SDK_LOG_RE.test(args[0]))
@@ -26,7 +28,7 @@ export function suppressSdkLogs() {
26
28
  process.stderr.write = function (chunk, encoding, callback) {
27
29
  const str = String(chunk);
28
30
  // Filter out keystore migration warnings and other SDK logs
29
- if (SDK_LOG_RE.test(str) || KEYSTORE_WARN_RE.test(str)) {
31
+ if (SDK_LOG_RE.test(str) || KEYSTORE_WARN_RE.test(str) || NODE_SQLITE_WARN_RE.test(str)) {
30
32
  if (typeof encoding === 'function') {
31
33
  encoding(); // callback is in encoding position
32
34
  }
@@ -45,7 +45,7 @@ export class ManagedMenuClient {
45
45
  const key = this.key(fromAid, event.requestId);
46
46
  const entry = this.eventHandlers.get(key);
47
47
  entry?.handler(event);
48
- if (event.event === 'upgrade.result' && entry) {
48
+ if ((event.event === 'upgrade.result' || event.event === 'template.result') && entry) {
49
49
  clearTimeout(entry.timer);
50
50
  this.eventHandlers.delete(key);
51
51
  }
@@ -106,7 +106,8 @@ export class ManagedMenuClient {
106
106
  error: { code: 'NOT_ALLOWED', message: 'Remote query was denied; authorization denial cached for up to 30 minutes or until reconnect.' },
107
107
  };
108
108
  }
109
- if (options.onEvent && request.type === 'menu.action' && request.action === 'upgrade' && request.args?.mode === 'update') {
109
+ if (options.onEvent && request.type === 'menu.action' && (request.action === 'upgrade' && request.args?.mode === 'update'
110
+ || (request.name === 'agent' || request.cmd === '/agent') && ['build', 'push', 'pull', 'deploy'].includes(String(request.action)))) {
110
111
  const existing = this.eventHandlers.get(key);
111
112
  if (existing)
112
113
  clearTimeout(existing.timer);
@@ -203,7 +203,7 @@ async function daemonMsgSendResult(args, payload, runtimeContext, daemonResult)
203
203
  request_diagnostics: daemonResult.request_diagnostics,
204
204
  transport_error: daemonResult.transport_error,
205
205
  };
206
- // 自发(`--to <本端AID>`)不写出站日志:chatDir 会算成「我↔我」目录,
206
+ // 跨话题自派(`--to <本端AID>`)不写出站日志:chatDir 会算成「我↔我」目录,
207
207
  // daemon 侧 `sendDaemonMsg` 同样跳过;这里是对「daemon 未写日志」的兜底,
208
208
  // 不跳过就会在 CLI 侧把那个目录补造出来。
209
209
  const selfAddressed = String(args.to ?? '').replace(/^@/, '').toLowerCase()