evolcore 0.0.43-test.6 → 0.0.43-test.8

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 (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  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/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -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
+ }
@@ -82,7 +82,7 @@ function baseagentDetails(codexAvailability, claude, claudeVersion, gemini) {
82
82
  },
83
83
  ];
84
84
  }
85
- /** Only loaded runners can be switched to; never infer this from PATH/config. */
85
+ /** Currently loaded runners only; configured on-demand choices are provided separately. */
86
86
  export function loadedBaseagentIds(keys, owner) {
87
87
  const result = new Set();
88
88
  for (const key of keys) {
@@ -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) {
@@ -227,6 +227,28 @@ export class CodexAppServerClient {
227
227
  async threadRead(threadId, includeTurns = true, timeoutMs) {
228
228
  return this.request('thread/read', { threadId, includeTurns }, timeoutMs);
229
229
  }
230
+ getModelProvider() {
231
+ return this.runtimeModelProvider();
232
+ }
233
+ isRunning() {
234
+ return this.proc !== null;
235
+ }
236
+ async threadLoadedList() {
237
+ const data = new Set();
238
+ const cursors = new Set();
239
+ let cursor;
240
+ do {
241
+ const page = await this.request('thread/loaded/list', cursor ? { cursor } : {}, 5000);
242
+ for (const id of page.data)
243
+ data.add(id);
244
+ cursor = page.nextCursor || undefined;
245
+ if (cursor && cursors.has(cursor))
246
+ throw new Error('Codex loaded thread pagination repeated a cursor');
247
+ if (cursor)
248
+ cursors.add(cursor);
249
+ } while (cursor);
250
+ return { data: [...data] };
251
+ }
230
252
  async threadRollback(threadId, numTurns) {
231
253
  return this.request('thread/rollback', { threadId, numTurns });
232
254
  }