evolcore 0.0.49 → 0.0.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +64 -1
- package/bin/ecmsg.js +9 -4
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +164 -0
- package/dist/ability/caller/contract.js +102 -0
- package/dist/ability/caller/daemon.js +158 -0
- package/dist/ability/caller/service.js +380 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +10 -3
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +173 -1
- package/dist/agent-template/runtime.js +280 -6
- package/dist/agent-template/service.js +1159 -40
- package/dist/agent-template/types.js +2 -1
- package/dist/agents/baseagent-availability.js +27 -3
- package/dist/agents/baseagent-capability-adapter.js +102 -0
- package/dist/agents/baseagent-plugin-descriptor.js +274 -0
- package/dist/agents/baseagent-plugin-loader.js +145 -0
- package/dist/agents/baseagent.js +68 -2
- package/dist/agents/claude-gateway/agent-registration.js +389 -0
- package/dist/agents/claude-gateway/binding.js +96 -0
- package/dist/agents/claude-gateway/inbox.js +138 -0
- package/dist/agents/claude-gateway/index.js +125 -0
- package/dist/agents/claude-gateway/listing.js +330 -0
- package/dist/agents/claude-gateway/router.js +328 -0
- package/dist/agents/claude-gateway/sessions.js +128 -0
- package/dist/agents/claude-gateway/terminal.js +250 -0
- package/dist/agents/claude-gateway/transcript.js +272 -0
- package/dist/agents/claude-gateway/types.js +14 -0
- package/dist/agents/claude-runner.js +6 -10
- package/dist/agents/codex-runner.js +4 -1
- package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
- package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
- package/dist/agents/gemini/index.js +51 -0
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/group/invite-service.js +6 -36
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +29 -1
- package/dist/aun/msg/upload.js +126 -3
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +537 -189
- package/dist/cli/ability-command.js +42 -0
- package/dist/cli/agent-command.js +20 -1
- package/dist/cli/agent-create.js +78 -18
- package/dist/cli/agent-template.js +5 -3
- package/dist/cli/agent.js +91 -0
- package/dist/cli/aun-commands.js +92 -34
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +245 -101
- package/dist/cli/ecmsg-gateway.js +11 -9
- package/dist/cli/index.js +23 -4
- package/dist/cli/init.js +39 -63
- package/dist/cli/managed-command-guard.js +1 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/services-command.js +11 -9
- package/dist/cli/thread-command.js +78 -12
- package/dist/config/access-policy.js +16 -3
- package/dist/config/config-field-policy.js +17 -8
- package/dist/config/config-manager.js +86 -46
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +9 -8
- package/dist/config/owner-config.js +0 -16
- package/dist/config/peer-role-resolver.js +1 -7
- package/dist/config/providers-config.js +99 -16
- package/dist/config/providers-management.js +35 -19
- package/dist/config/resolved-config-op.js +1 -42
- package/dist/config/schema-migration.js +78 -5
- package/dist/config/schema-registry.js +52 -7
- package/dist/config-store.js +1309 -17
- package/dist/core/agent-application-service.js +220 -1
- package/dist/core/agent-ipc-registration.js +19 -2
- package/dist/core/agent-reload-coordinator.js +5 -0
- package/dist/core/agent-runtime.js +198 -54
- package/dist/core/auth/agent-delegation.js +14 -0
- package/dist/core/auth/operation-authorizer.js +16 -1
- package/dist/core/auth/operation-catalog.js +50 -7
- package/dist/core/baseagent-loader.js +30 -3
- package/dist/core/capability/capability-manager.js +16 -7
- package/dist/core/channel-runtime.js +4 -2
- package/dist/core/command/agent-control.js +20 -2
- package/dist/core/command/agent-template-menu.js +4 -3
- package/dist/core/command/cli-intent-parser.js +15 -0
- package/dist/core/command/menu-catalog.js +20 -4
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +91 -72
- package/dist/core/command/menu-protocol.js +5 -0
- package/dist/core/command/menu-query-batch.js +2 -2
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/slash-handler.js +17 -26
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/topic-slash.js +7 -1
- package/dist/core/daemon-bootstrap.js +0 -4
- package/dist/core/daemon-control.js +2 -1
- package/dist/core/daemon-lifecycle.js +13 -5
- package/dist/core/evolagent-registry.js +12 -7
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/core/host-snapshot.js +8 -3
- package/dist/core/initialization/service.js +3 -0
- package/dist/core/interaction-router.js +130 -0
- package/dist/core/ipc-registration.js +4 -0
- package/dist/core/memory/consolidation-context.js +2 -1
- package/dist/core/memory/consolidation.js +35 -64
- package/dist/core/message/aun-ipc-sender.js +98 -21
- package/dist/core/message/aun-request-registry.js +31 -0
- package/dist/core/message/message-bridge.js +105 -6
- package/dist/core/message/message-log.js +8 -0
- package/dist/core/message/message-queue.js +5 -3
- package/dist/core/message/peer-mode.js +15 -4
- package/dist/core/message/response-engine.js +23 -8
- package/dist/core/message/send-options.js +37 -3
- package/dist/core/message/send-routing.js +11 -7
- package/dist/core/model/model-catalog.js +5 -5
- package/dist/core/ownership/owner-resolver.js +12 -86
- package/dist/core/pack-auth.js +4 -0
- package/dist/core/permission/ec-command-parser.js +182 -58
- package/dist/core/permission/protected-paths.js +64 -9
- package/dist/core/permission/services-path-acl.js +9 -2
- package/dist/core/permission/tool-policy.js +21 -9
- package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
- package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
- package/dist/core/session/session-manager.js +47 -10
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/skill/index-generator.js +2 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +4 -2
- package/dist/core/thread/thread-operation.js +25 -10
- package/dist/core/thread/thread-service.js +294 -55
- package/dist/core/thread/topic-id.js +52 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/eck/kit-renderer.js +2 -1
- package/dist/ecweb/basic-settings-service.js +5 -9
- package/dist/ecweb/providers-service.js +4 -2
- package/dist/index.js +116 -41
- package/dist/ipc.js +58 -2
- package/dist/paths.js +48 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +188 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +29 -2
- package/dist/services/dispatcher.js +23 -5
- package/dist/services/host/main.js +388 -0
- package/dist/services/host/protocol.js +118 -0
- package/dist/services/host/resident.js +310 -0
- package/dist/services/host-client.js +386 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +203 -0
- package/dist/services/host-runtime.js +802 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +176 -18
- package/dist/services/ipc-operation.js +204 -44
- package/dist/services/script-runner.js +515 -83
- package/dist/services/validation.js +109 -4
- package/dist/trigger/application-service.js +6 -4
- package/dist/trigger/local-files.js +19 -9
- package/dist/trigger/scheduler.js +22 -12
- package/dist/trigger/script-sandbox.js +51 -20
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +73 -0
- package/dist/utils/logger.js +2 -2
- package/dist/utils/media-cache.js +190 -43
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/windows-shell-trust.js +7 -3
- package/kits/docs/INDEX.md +3 -2
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/evolcore/INDEX.md +7 -6
- package/kits/docs/evolcore/agent.md +36 -1
- package/kits/docs/evolcore/aid.md +20 -3
- package/kits/docs/evolcore/config.md +1 -1
- package/kits/docs/evolcore/group.md +2 -1
- package/kits/docs/evolcore/memory-tags.md +2 -0
- package/kits/docs/evolcore/menu-client.md +3 -3
- package/kits/docs/evolcore/menu-protocol.md +7 -0
- package/kits/docs/evolcore/model.md +3 -0
- package/kits/docs/evolcore/msg.md +68 -10
- package/kits/docs/evolcore/pay.md +34 -0
- package/kits/docs/evolcore/provider.md +21 -0
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/thread-chain.md +2 -0
- package/kits/docs/evolcore/tool-authorization.md +10 -0
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +7 -0
- package/kits/rules/06-channel.md +3 -3
- package/kits/schemas/_meta.json +38 -5
- package/kits/schemas/agent-config.schema.21.json +974 -0
- package/kits/schemas/agent-config.schema.22.json +977 -0
- package/kits/schemas/agent-config.schema.23.json +958 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/providers.schema.3.json +18 -2
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +13 -1
- package/kits/skills/ability/SKILL.md +229 -34
- package/kits/skills/ability/STRUCTURE.md +333 -0
- package/kits/skills/ability/references/cli.md +208 -0
- package/kits/skills/ability/references/development.md +107 -37
- package/kits/skills/ability/references/management.md +106 -46
- package/kits/skills/ability/references/runtime-protocol.md +65 -63
- package/kits/skills/agent-output-cards/SKILL.md +12 -5
- package/kits/skills/ec-group/SKILL.md +8 -6
- package/kits/skills/ec-group/TASK.md +186 -0
- package/kits/skills/ec-group/WORKLOG.md +180 -0
- package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
- package/kits/skills/ec-pay/SKILL.md +101 -0
- package/kits/skills/ec-pay/references/pay-cli.md +110 -0
- package/kits/skills/ec-provider/SKILL.md +1 -1
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +135 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/reply.md +1 -0
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +27 -129
- package/kits/templates/system-fragments/venue.md +16 -0
- package/package.json +4 -5
- package/scripts/agent-template/inspect.mjs +37 -23
- package/scripts/agent-template/overlay.mjs +20 -2
- package/scripts/agent-template/shared/common.mjs +16 -4
- package/scripts/agent-template/shared/team-schema.json +20 -4
- package/scripts/agent-template/shared/template-contract.mjs +53 -13
- package/scripts/agent-template/shared/template-package.mjs +90 -26
- package/scripts/agent-template/shared/template-runtime.mjs +111 -1
- package/scripts/agent-template/shared/template.mjs +65 -7
- package/scripts/agent-template/team-pack.mjs +89 -33
- package/scripts/agent-template/team-preview.mjs +249 -5
- package/kits/docs/aun/ABILITY_CALLING.md +0 -280
- package/kits/docs/evolcore/ability.md +0 -185
- package/kits/skills/ability/references/calling.md +0 -56
- package/kits/skills/ability/references/contract-checklist.md +0 -37
- package/kits/skills/ability/references/recovery.md +0 -27
- /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { randomUUID } from 'node:crypto';
|
|
4
|
-
import { TemplateJobs, templateFingerprint, writeTemplateState, TEMPLATE_PREVIEW_ID } from './jobs.js';
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
+
import { TemplateJobs, templateFingerprint, writeTemplateState, TEMPLATE_PREVIEW_ID, compareTemplateVersions } from './jobs.js';
|
|
5
5
|
import { runTemplateTool } from './tool-runner.js';
|
|
6
6
|
import { templateError, templateJobAids } from './types.js';
|
|
7
7
|
import { logger } from '../utils/logger.js';
|
|
8
|
+
import { agentProjectRootFromDefaults, deriveAgentProjectPath } from '../utils/project-path.js';
|
|
9
|
+
import { isValidAid } from '../aun/aid/validation.js';
|
|
10
|
+
import { withFileLock } from '../utils/atomic-write.js';
|
|
11
|
+
const publicTemplate = await import(new URL('../../scripts/agent-template/shared/template-runtime.mjs', import.meta.url).href);
|
|
12
|
+
const templateContract = await import(new URL('../../scripts/agent-template/shared/template-contract.mjs', import.meta.url).href);
|
|
8
13
|
const SELECTION_MS = 15 * 60_000;
|
|
9
14
|
const JOB_MS = 30 * 60_000;
|
|
10
15
|
export class AgentTemplateService {
|
|
@@ -20,6 +25,9 @@ export class AgentTemplateService {
|
|
|
20
25
|
tool;
|
|
21
26
|
cleanupTimer;
|
|
22
27
|
disposed = false;
|
|
28
|
+
discoveryRun;
|
|
29
|
+
updateTimer;
|
|
30
|
+
updateRun;
|
|
23
31
|
constructor(deps) {
|
|
24
32
|
this.deps = deps;
|
|
25
33
|
this.jobs = new TemplateJobs(deps.root);
|
|
@@ -45,6 +53,8 @@ export class AgentTemplateService {
|
|
|
45
53
|
return;
|
|
46
54
|
this.disposed = true;
|
|
47
55
|
clearInterval(this.cleanupTimer);
|
|
56
|
+
if (this.updateTimer)
|
|
57
|
+
clearInterval(this.updateTimer);
|
|
48
58
|
for (const timer of this.timers.values())
|
|
49
59
|
clearTimeout(timer);
|
|
50
60
|
this.timers.clear();
|
|
@@ -53,14 +63,23 @@ export class AgentTemplateService {
|
|
|
53
63
|
&& job.freeze && !['released', 'transferred'].includes(job.freeze.state)) {
|
|
54
64
|
await this.cancelInternal(job.actor, job.jobId, 'runtime_disposed');
|
|
55
65
|
}
|
|
56
|
-
await Promise.allSettled([...this.work.values(), ...this.cancellations.values()]);
|
|
66
|
+
await Promise.allSettled([...this.work.values(), ...this.cancellations.values(), this.discoveryRun, this.updateRun]);
|
|
57
67
|
}
|
|
58
68
|
view(job) {
|
|
59
69
|
const { actor: _actor, fingerprint: _fingerprint, args: _args, checkpoint: _checkpoint, version: _version, activating: _activating, ...view } = job;
|
|
70
|
+
if (job.checkpoint.memberInstall) {
|
|
71
|
+
const binding = job.checkpoint.memberInstall;
|
|
72
|
+
const team = this.jobs.readTeam(binding.instanceId);
|
|
73
|
+
const slot = team.members.find(member => member.key === binding.memberKey);
|
|
74
|
+
Object.assign(view, { memberInstallation: { instanceId: team.instanceId, memberKey: slot.key,
|
|
75
|
+
state: slot.state, revision: team.revision, ...(slot.pending ? { pending: slot.pending } : {}) } });
|
|
76
|
+
}
|
|
60
77
|
if (job.action === 'deploy' && job.committed) {
|
|
61
78
|
const runtimeReady = templateJobAids(job).every(aid => this.deps.installation.ready(aid));
|
|
62
79
|
const directoryReady = this.deps.installation.directoryReady(templateJobAids(job));
|
|
63
|
-
return { ...view,
|
|
80
|
+
return { ...view, ...(!job.checkpoint.memberInstall && job.result?.installMode === 'create'
|
|
81
|
+
? { instanceId: 'team_' + templateFingerprint({ teamId: job.jobId, ownerAid: job.actor, hostAid: this.deps.hostAid }) } : {}),
|
|
82
|
+
readiness: { runtimeReady, directoryReady, teamReady: runtimeReady && directoryReady,
|
|
64
83
|
health: runtimeReady && directoryReady ? 'ready' : 'degraded' } };
|
|
65
84
|
}
|
|
66
85
|
return view;
|
|
@@ -117,15 +136,15 @@ export class AgentTemplateService {
|
|
|
117
136
|
if (current.status === 'cancelling' || ['cancelled', 'succeeded'].includes(current.status))
|
|
118
137
|
return;
|
|
119
138
|
current.error = { code: error.code ?? 'TEMPLATE_FAILED', message: error.message,
|
|
120
|
-
retryable:
|
|
139
|
+
retryable: ['deploy', 'preview-update'].includes(current.action), ...(error.details ? { details: error.details } : {}) };
|
|
121
140
|
if (['inspect', 'build'].includes(current.action)) {
|
|
122
141
|
await this.release(current, 'failed');
|
|
123
142
|
current.status = current.freeze?.state === 'released' ? 'failed' : 'cancelling';
|
|
124
143
|
current.resumable = false;
|
|
125
144
|
}
|
|
126
145
|
else {
|
|
127
|
-
current.status = current.action
|
|
128
|
-
current.resumable = current.action
|
|
146
|
+
current.status = ['deploy', 'preview-update'].includes(current.action) ? 'paused' : 'failed';
|
|
147
|
+
current.resumable = ['deploy', 'preview-update'].includes(current.action);
|
|
129
148
|
}
|
|
130
149
|
this.jobs.save(current);
|
|
131
150
|
}
|
|
@@ -144,22 +163,53 @@ export class AgentTemplateService {
|
|
|
144
163
|
}
|
|
145
164
|
async query(actor, args) {
|
|
146
165
|
await this.deps.installation.authorize(actor);
|
|
147
|
-
|
|
166
|
+
const job = this.jobs.get(actor, args);
|
|
167
|
+
if (job.committed && job.checkpoint.memberInstall) {
|
|
168
|
+
await this.ownedTeam(actor, job.checkpoint.memberInstall.instanceId);
|
|
169
|
+
await this.attachCommittedMember(job);
|
|
170
|
+
}
|
|
171
|
+
else if (job.committed && job.result?.installMode === 'create')
|
|
172
|
+
await this.recordCreatedTeam(job, this.previewRecord(job.args.previewId));
|
|
173
|
+
return this.view(job);
|
|
148
174
|
}
|
|
149
175
|
async action(actor, requestId, action, args) {
|
|
150
176
|
if (this.disposed)
|
|
151
177
|
throw templateError('RECOVERY_REQUIRED', 'Template runtime has been disposed');
|
|
178
|
+
if (typeof requestId !== 'string' || !requestId.trim() || requestId.length > 200)
|
|
179
|
+
throw templateError('INVALID_ARGUMENT', 'Stable requestId required');
|
|
152
180
|
await this.deps.installation.authorize(actor);
|
|
181
|
+
const preparedRequest = fs.existsSync(path.join(this.cache, 'member-install-requests', templateFingerprint({ actor, requestId }) + '.json'));
|
|
182
|
+
if (preparedRequest && action !== 'prepare-member-install' || action === 'prepare-member-install' && this.jobs.original(actor, requestId)) {
|
|
183
|
+
throw templateError('CONFLICT', 'Request ID is already used by another operation');
|
|
184
|
+
}
|
|
153
185
|
if (action === 'status')
|
|
154
186
|
return this.query(actor, args);
|
|
155
187
|
if (action === 'capabilities')
|
|
156
188
|
return this.tool('capabilities', {});
|
|
189
|
+
if (action === 'update-status')
|
|
190
|
+
return this.updateStatus(actor, args.targetAid);
|
|
191
|
+
if (action === 'bind-update-source')
|
|
192
|
+
return this.bindUpdateSource(actor, requestId, args);
|
|
193
|
+
if (action === 'confirm-update-source')
|
|
194
|
+
return this.confirmUpdateSource(actor, args);
|
|
195
|
+
if (action === 'read-update-notice')
|
|
196
|
+
return this.readUpdateNotice(actor, args.targetAid, args.noticeId);
|
|
197
|
+
if (action === 'register-team')
|
|
198
|
+
return this.registerTeam(actor, args.manifest, args.deliveryDigest);
|
|
199
|
+
if (action === 'team-members')
|
|
200
|
+
return this.discoveredTeamMembers(actor, args);
|
|
201
|
+
if (action === 'prepare-member-install')
|
|
202
|
+
return this.prepareMemberInstall(actor, requestId, args);
|
|
203
|
+
if (action === 'resume-member-join')
|
|
204
|
+
return this.resumeMemberJoin(actor, args.instanceId, args.memberKey);
|
|
157
205
|
if (action === 'cancel' || action === 'resume')
|
|
158
206
|
return this.control(actor, requestId, action, args.jobId);
|
|
159
207
|
const prior = this.jobs.original(actor, requestId);
|
|
160
208
|
if (prior) {
|
|
161
|
-
if (
|
|
209
|
+
if (!this.jobs.requestMatches(actor, requestId, action, args))
|
|
162
210
|
throw templateError('CONFLICT', 'Request has different arguments');
|
|
211
|
+
if (action === 'deploy')
|
|
212
|
+
return this.deploy(actor, requestId, args);
|
|
163
213
|
return this.view(prior);
|
|
164
214
|
}
|
|
165
215
|
if (action === 'inspect')
|
|
@@ -169,9 +219,744 @@ export class AgentTemplateService {
|
|
|
169
219
|
if (action === 'deploy')
|
|
170
220
|
return this.deploy(actor, requestId, args);
|
|
171
221
|
const { job } = this.jobs.accept(actor, requestId, action, args);
|
|
172
|
-
this.launch(job, value => action === 'push' ? this.push(value) : action === 'pull' ? this.pull(value)
|
|
222
|
+
this.launch(job, value => action === 'push' ? this.push(value) : action === 'pull' ? this.pull(value)
|
|
223
|
+
: action === 'check-update' ? this.runUpdateCheck(value) : action === 'preview-update' ? this.previewUpdate(value) : this.preview(value));
|
|
173
224
|
return this.view(job);
|
|
174
225
|
}
|
|
226
|
+
updateFile(targetAid) {
|
|
227
|
+
this.jobs.installationFile(targetAid);
|
|
228
|
+
return path.join(this.cache, 'updates', templateFingerprint(targetAid) + '.json');
|
|
229
|
+
}
|
|
230
|
+
snapshot(file) {
|
|
231
|
+
this.jobs.assertTeamPath(file);
|
|
232
|
+
if (!fs.existsSync(file))
|
|
233
|
+
return null;
|
|
234
|
+
const stat = fs.statSync(file);
|
|
235
|
+
if (!stat.isFile() || stat.nlink !== 1)
|
|
236
|
+
throw templateError('CONFLICT', 'Ordinary private managed file required');
|
|
237
|
+
// templateFingerprint is for JSON; file snapshots use the overlay's exact byte digest.
|
|
238
|
+
return { sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), mode: stat.mode & 0o777 };
|
|
239
|
+
}
|
|
240
|
+
async updateAuthority(targetAid, actor, recoveryJobId, allowDisabled = false) {
|
|
241
|
+
if (!this.deps.updates)
|
|
242
|
+
throw templateError('CATALOG_UNAVAILABLE', 'Template update runtime is unavailable');
|
|
243
|
+
const current = await this.deps.updates.context(targetAid);
|
|
244
|
+
if (!current.ownerAid || actor && actor !== current.ownerAid)
|
|
245
|
+
throw templateError('NOT_ALLOWED', 'Current direct Agent Owner required');
|
|
246
|
+
await this.deps.authorize(current.ownerAid, targetAid, recoveryJobId);
|
|
247
|
+
if (!allowDisabled && current.mode === 'disabled')
|
|
248
|
+
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before checking or upgrading');
|
|
249
|
+
return current;
|
|
250
|
+
}
|
|
251
|
+
installed(targetAid, ownerAid, projectPath) {
|
|
252
|
+
const installed = this.jobs.installation(targetAid);
|
|
253
|
+
if (installed && (installed.ownerAid !== ownerAid || installed.hostAid !== this.deps.hostAid || installed.projectPath !== projectPath)) {
|
|
254
|
+
throw templateError('SOURCE_CHANGED', 'Installation Owner, Host or project changed; explicit source binding is required');
|
|
255
|
+
}
|
|
256
|
+
return installed;
|
|
257
|
+
}
|
|
258
|
+
attestedRelease(source, detail) {
|
|
259
|
+
const member = detail.members?.find((value) => value.key === source.memberKey);
|
|
260
|
+
if (detail.revoked || detail.withdrawn || detail.deleted || detail.state && !['published', 'released'].includes(detail.state)) {
|
|
261
|
+
throw templateError('RELEASE_WITHDRAWN', 'The fixed release is no longer published');
|
|
262
|
+
}
|
|
263
|
+
if (detail.schema !== 1 || detail.templateId !== source.templateId || detail.publisher !== source.publisher
|
|
264
|
+
|| detail.publisherProof !== 'authenticated-AUN-service-submission' || !member?.publisherVerified
|
|
265
|
+
|| member.publisher !== source.publisher || !/^[a-f0-9]{64}$/.test(detail.releaseId ?? '')
|
|
266
|
+
|| !/^sha256:[a-f0-9]{64}$/.test(detail.digest ?? '')) {
|
|
267
|
+
throw templateError('UNVERIFIED_SOURCE', 'Registry did not attest the original author and member source');
|
|
268
|
+
}
|
|
269
|
+
compareTemplateVersions(member.version, member.version);
|
|
270
|
+
compareTemplateVersions(detail.version, detail.version);
|
|
271
|
+
return { source: structuredClone(source), releaseId: detail.releaseId, version: member.version,
|
|
272
|
+
packageVersion: detail.version, digest: detail.digest, ...(member.agentTemplateId ? { agentTemplateId: member.agentTemplateId } : {}) };
|
|
273
|
+
}
|
|
274
|
+
async fixedRelease(source, releaseId, operation) {
|
|
275
|
+
const detail = await this.deps.updates.catalog(source, 'detail', { releaseId }, operation);
|
|
276
|
+
const release = this.attestedRelease(source, detail);
|
|
277
|
+
if (release.releaseId !== releaseId)
|
|
278
|
+
throw templateError('SOURCE_CHANGED', 'Registry returned another release');
|
|
279
|
+
return release;
|
|
280
|
+
}
|
|
281
|
+
noticeFile(noticeId) {
|
|
282
|
+
if (!/^notice_[a-f0-9]{64}$/.test(noticeId))
|
|
283
|
+
throw templateError('INVALID_ARGUMENT', 'Invalid noticeId');
|
|
284
|
+
return path.join(this.cache, 'notifications', noticeId + '.json');
|
|
285
|
+
}
|
|
286
|
+
notices(targetAid, ownerAid, source) {
|
|
287
|
+
const directory = path.join(this.cache, 'notifications');
|
|
288
|
+
if (!fs.existsSync(directory) || !source)
|
|
289
|
+
return [];
|
|
290
|
+
return fs.readdirSync(directory).filter(name => /^notice_[a-f0-9]{64}\.json$/.test(name))
|
|
291
|
+
.map(name => JSON.parse(fs.readFileSync(path.join(directory, name), 'utf8')))
|
|
292
|
+
.filter(notice => notice.targetAid === targetAid && notice.ownerAid === ownerAid
|
|
293
|
+
&& templateFingerprint(notice.source) === templateFingerprint(source));
|
|
294
|
+
}
|
|
295
|
+
async updateStatus(actor, targetAid) {
|
|
296
|
+
const context = await this.updateAuthority(targetAid, actor, undefined, true);
|
|
297
|
+
const installation = this.installed(targetAid, actor, context.projectPath);
|
|
298
|
+
const file = this.updateFile(targetAid);
|
|
299
|
+
const check = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
|
|
300
|
+
const currentCheck = check?.ownerAid === actor && check?.installation === templateFingerprint(installation) ? check : null;
|
|
301
|
+
return { targetAid, mode: context.mode ?? null, automaticExecution: false,
|
|
302
|
+
sourceState: installation ? 'bound' : 'unbound', sourceLabel: installation ? '已绑定更新源' : '未绑定更新源',
|
|
303
|
+
installation, currentVersion: installation?.release?.version ?? null,
|
|
304
|
+
baselineKnown: installation?.baseline.known ?? false, check: currentCheck,
|
|
305
|
+
notices: this.notices(targetAid, actor, installation?.source),
|
|
306
|
+
activeJob: this.jobs.list().find(job => job.action === 'deploy' && !job.committed && !job.checkpoint.restored
|
|
307
|
+
&& Object.values(job.members).some(member => member.aid === targetAid))?.jobId ?? null };
|
|
308
|
+
}
|
|
309
|
+
async readUpdateNotice(actor, targetAid, noticeId) {
|
|
310
|
+
const context = await this.updateAuthority(targetAid, actor, undefined, true);
|
|
311
|
+
const installation = this.installed(targetAid, actor, context.projectPath);
|
|
312
|
+
const notice = this.notices(targetAid, actor, installation?.source).find(value => value.noticeId === noticeId);
|
|
313
|
+
if (!notice)
|
|
314
|
+
throw templateError('NOT_FOUND', 'Current Owner notification not found');
|
|
315
|
+
notice.unread = false;
|
|
316
|
+
writeTemplateState(this.noticeFile(noticeId), notice);
|
|
317
|
+
return { noticeId, unread: false };
|
|
318
|
+
}
|
|
319
|
+
async bindUpdateSource(actor, requestId, args) {
|
|
320
|
+
const context = await this.updateAuthority(args.targetAid, actor);
|
|
321
|
+
const sourceErrors = templateContract.validateTemplateRequest({ requestId, action: 'bind-update-source', args });
|
|
322
|
+
if (sourceErrors.length)
|
|
323
|
+
throw templateError('INVALID_ARGUMENT', sourceErrors.join('; '));
|
|
324
|
+
const release = await this.fixedRelease(args.source, args.releaseId, 'binding:' + templateFingerprint({ actor, requestId }));
|
|
325
|
+
const target = await this.deps.target(args.targetAid, actor);
|
|
326
|
+
const bindingId = 'binding_' + randomUUID();
|
|
327
|
+
const installation = { targetAid: args.targetAid, ownerAid: actor, hostAid: this.deps.hostAid,
|
|
328
|
+
projectPath: context.projectPath, source: args.source, bindingId, bindingReleaseId: release.releaseId, baseline: { known: false } };
|
|
329
|
+
const value = { bindingId, actor, installation, release, snapshot: templateFingerprint(target),
|
|
330
|
+
lock: this.snapshot(this.jobs.installationFile(args.targetAid)), expiresAt: Date.now() + SELECTION_MS };
|
|
331
|
+
const planDigest = 'sha256:' + templateFingerprint(value);
|
|
332
|
+
writeTemplateState(path.join(this.cache, 'update-bindings', bindingId + '.json'), { ...value, planDigest });
|
|
333
|
+
return { bindingId, planDigest, expiresAt: value.expiresAt, targetAid: args.targetAid, source: args.source,
|
|
334
|
+
selectedRelease: release, currentVersion: null, baselineKnown: false, requiresOwnerConfirmation: true,
|
|
335
|
+
warning: '来源绑定不会宣称当前内容已安装该版本;本地差异将在升级预览中逐项确认。' };
|
|
336
|
+
}
|
|
337
|
+
async confirmUpdateSource(actor, args) {
|
|
338
|
+
if (!/^binding_[a-f0-9-]{36}$/.test(args.bindingId ?? ''))
|
|
339
|
+
throw templateError('INVALID_ARGUMENT', 'Invalid bindingId');
|
|
340
|
+
const record = JSON.parse(fs.readFileSync(path.join(this.cache, 'update-bindings', args.bindingId + '.json'), 'utf8'));
|
|
341
|
+
const installation = record.installation;
|
|
342
|
+
return withFileLock(path.join(this.cache, 'update-targets', templateFingerprint(installation.targetAid) + '.lock'), async () => {
|
|
343
|
+
await this.updateAuthority(installation.targetAid, actor);
|
|
344
|
+
if (record.actor !== actor || args.planDigest !== record.planDigest)
|
|
345
|
+
throw templateError('NOT_ALLOWED', 'Original Owner confirmation and digest required');
|
|
346
|
+
const { planDigest: _digest, confirmed: _confirmed, ...boundInput } = record;
|
|
347
|
+
if ('sha256:' + templateFingerprint(boundInput) !== record.planDigest)
|
|
348
|
+
throw templateError('CONFLICT', 'Frozen source binding changed');
|
|
349
|
+
const existing = this.jobs.installation(installation.targetAid);
|
|
350
|
+
if (existing?.bindingId === record.bindingId && templateFingerprint(existing) === templateFingerprint(installation)) {
|
|
351
|
+
record.confirmed = true;
|
|
352
|
+
writeTemplateState(path.join(this.cache, 'update-bindings', args.bindingId + '.json'), record);
|
|
353
|
+
return { targetAid: installation.targetAid, sourceState: 'bound', currentVersion: null, bindingId: record.bindingId };
|
|
354
|
+
}
|
|
355
|
+
if (record.confirmed)
|
|
356
|
+
throw templateError('SOURCE_CHANGED', 'A later Owner source binding superseded this confirmation');
|
|
357
|
+
if (record.expiresAt <= Date.now())
|
|
358
|
+
throw templateError('EXPIRED', 'Source binding preview expired');
|
|
359
|
+
const target = await this.deps.target(installation.targetAid, actor);
|
|
360
|
+
if (templateFingerprint(target) !== record.snapshot || templateFingerprint(this.snapshot(this.jobs.installationFile(installation.targetAid))) !== templateFingerprint(record.lock)) {
|
|
361
|
+
throw templateError('TARGET_CHANGED', 'Binding target changed');
|
|
362
|
+
}
|
|
363
|
+
const release = await this.fixedRelease(installation.source, record.release.releaseId, args.bindingId + ':confirm');
|
|
364
|
+
if (templateFingerprint(release) !== templateFingerprint(record.release))
|
|
365
|
+
throw templateError('SOURCE_CHANGED', 'Selected source changed');
|
|
366
|
+
const active = this.jobs.list().find(job => job.action === 'deploy' && !job.committed && !job.checkpoint.restored
|
|
367
|
+
&& Object.values(job.members).some(member => member.aid === installation.targetAid));
|
|
368
|
+
if (active)
|
|
369
|
+
throw templateError('CONFLICT', 'Resume the original target job', { jobId: active.jobId });
|
|
370
|
+
writeTemplateState(this.jobs.installationFile(installation.targetAid), { schemaVersion: 2, installation });
|
|
371
|
+
record.confirmed = true;
|
|
372
|
+
writeTemplateState(path.join(this.cache, 'update-bindings', args.bindingId + '.json'), record);
|
|
373
|
+
return { targetAid: installation.targetAid, sourceState: 'bound', currentVersion: null, bindingId: record.bindingId };
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
async runUpdateCheck(job) {
|
|
377
|
+
job.result = await this.checkUpdate(job.args.targetAid, job.actor);
|
|
378
|
+
job.status = 'succeeded';
|
|
379
|
+
job.phase = 'completed';
|
|
380
|
+
this.jobs.save(job);
|
|
381
|
+
}
|
|
382
|
+
/** Read-only catalog work: never enters pull, preview, deploy or a model runner. */
|
|
383
|
+
async checkUpdate(targetAid, actor) {
|
|
384
|
+
return withFileLock(path.join(this.cache, 'update-checks', templateFingerprint(targetAid) + '.lock'), async () => {
|
|
385
|
+
const context = await this.updateAuthority(targetAid, actor);
|
|
386
|
+
const ownerAid = context.ownerAid;
|
|
387
|
+
const installation = this.installed(targetAid, ownerAid, context.projectPath);
|
|
388
|
+
if (!installation)
|
|
389
|
+
return { targetAid, sourceState: 'unbound', reason: 'SOURCE_UNBOUND', currentVersion: null };
|
|
390
|
+
const source = installation.source;
|
|
391
|
+
const releases = [];
|
|
392
|
+
// Revalidate the original source as well as the selected candidate; do not drift to another publisher.
|
|
393
|
+
const anchor = installation.release?.releaseId ?? installation.bindingReleaseId;
|
|
394
|
+
if (!anchor)
|
|
395
|
+
throw templateError('UNVERIFIED_SOURCE', 'Source attestation is absent');
|
|
396
|
+
const originalRelease = await this.fixedRelease(source, anchor, 'check-anchor:' + randomUUID());
|
|
397
|
+
if (installation.release && templateFingerprint(originalRelease) !== templateFingerprint(installation.release)) {
|
|
398
|
+
throw templateError('SOURCE_CHANGED', 'The original installed release no longer matches its trusted receipt');
|
|
399
|
+
}
|
|
400
|
+
for (let offset = 0;; offset += 50) {
|
|
401
|
+
if (offset >= 5000)
|
|
402
|
+
throw templateError('CATALOG_LIMIT', 'Too many releases; narrow the trusted source');
|
|
403
|
+
const page = await this.deps.updates.catalog(source, 'versions', { entity: 'agent', publisher: source.publisher,
|
|
404
|
+
templateId: source.templateId, memberKey: source.memberKey, offset, limit: 50 }, 'check:' + randomUUID());
|
|
405
|
+
if (!Array.isArray(page.releases) || !Number.isSafeInteger(page.total))
|
|
406
|
+
throw templateError('INVALID_CATALOG', 'Bounded release page required');
|
|
407
|
+
for (const row of page.releases) {
|
|
408
|
+
if (row.templateId !== source.templateId || row.key !== source.memberKey || row.publisher !== source.publisher
|
|
409
|
+
|| row.publisherVerified !== true || row.packagePublisher !== source.publisher)
|
|
410
|
+
throw templateError('UNVERIFIED_SOURCE', 'Author version source mismatch');
|
|
411
|
+
compareTemplateVersions(row.version, row.version);
|
|
412
|
+
const release = await this.fixedRelease(source, row.releaseId, 'check-detail:' + randomUUID());
|
|
413
|
+
if (release.version !== row.version || release.digest !== row.digest || release.packageVersion !== row.packageVersion) {
|
|
414
|
+
throw templateError('SOURCE_CHANGED', 'Catalog version and fixed release disagree');
|
|
415
|
+
}
|
|
416
|
+
releases.push(release);
|
|
417
|
+
}
|
|
418
|
+
if (offset + page.releases.length >= page.total)
|
|
419
|
+
break;
|
|
420
|
+
if (!page.releases.length)
|
|
421
|
+
throw templateError('INVALID_CATALOG', 'Catalog pagination stalled');
|
|
422
|
+
}
|
|
423
|
+
const known = new Map();
|
|
424
|
+
for (const release of [...releases, ...(installation.release ? [installation.release] : [])]) {
|
|
425
|
+
if (known.has(release.version) && known.get(release.version) !== release.digest)
|
|
426
|
+
throw templateError('VERSION_CONTENT_CONFLICT', 'The same author version has different content');
|
|
427
|
+
known.set(release.version, release.digest);
|
|
428
|
+
}
|
|
429
|
+
releases.sort((a, b) => compareTemplateVersions(b.version, a.version));
|
|
430
|
+
const candidate = releases.find(release => !installation.release || compareTemplateVersions(release.version, installation.release.version) > 0);
|
|
431
|
+
const current = await this.updateAuthority(targetAid, ownerAid);
|
|
432
|
+
if (templateFingerprint(this.installed(targetAid, ownerAid, current.projectPath)) !== templateFingerprint(installation)
|
|
433
|
+
|| current.mode !== context.mode)
|
|
434
|
+
throw templateError('SOURCE_CHANGED', 'Owner, source or policy changed during check');
|
|
435
|
+
const result = { targetAid, sourceState: 'bound', currentVersion: installation.release?.version ?? null,
|
|
436
|
+
state: candidate ? installation.release ? 'available' : 'current-version-unknown' : 'current', candidate: candidate ?? null };
|
|
437
|
+
writeTemplateState(this.updateFile(targetAid), { ...result, ownerAid, installation: templateFingerprint(installation),
|
|
438
|
+
mode: context.mode ?? null, checkedAt: Date.now(), nextCheckAt: Date.now() + 86400_000, failures: 0 });
|
|
439
|
+
if (candidate)
|
|
440
|
+
await this.deliverUpdateNotice(installation, candidate);
|
|
441
|
+
return result;
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
async deliverUpdateNotice(installation, candidate) {
|
|
445
|
+
const noticeId = 'notice_' + templateFingerprint({ targetAid: installation.targetAid, ownerAid: installation.ownerAid,
|
|
446
|
+
source: installation.source, version: candidate.version, digest: candidate.digest });
|
|
447
|
+
const file = this.noticeFile(noticeId);
|
|
448
|
+
const notice = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {
|
|
449
|
+
noticeId, targetAid: installation.targetAid, ownerAid: installation.ownerAid, source: installation.source,
|
|
450
|
+
candidate, currentVersion: installation.release?.version ?? null, createdAt: Date.now(), unread: true, delivery: 'pending'
|
|
451
|
+
};
|
|
452
|
+
if (notice.delivery === 'accepted' && notice.messageId)
|
|
453
|
+
return;
|
|
454
|
+
writeTemplateState(file, notice);
|
|
455
|
+
const context = await this.updateAuthority(notice.targetAid, notice.ownerAid);
|
|
456
|
+
if (templateFingerprint(this.installed(notice.targetAid, notice.ownerAid, context.projectPath)) !== templateFingerprint(installation)) {
|
|
457
|
+
throw templateError('SOURCE_CHANGED', 'Notification source changed');
|
|
458
|
+
}
|
|
459
|
+
const receipt = await this.deps.updates.notify(notice);
|
|
460
|
+
if (!receipt.messageId && !receipt.outboxId)
|
|
461
|
+
throw templateError('NOTIFICATION_FAILED', 'No durable notification receipt');
|
|
462
|
+
const latest = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
463
|
+
Object.assign(latest, receipt, { delivery: 'accepted' });
|
|
464
|
+
writeTemplateState(file, latest);
|
|
465
|
+
}
|
|
466
|
+
/** The actual runtime starts this once; persistent staggering and bounded backoff survive restart. */
|
|
467
|
+
startUpdateChecks() {
|
|
468
|
+
if (!this.deps.updates || this.updateTimer || this.disposed)
|
|
469
|
+
return;
|
|
470
|
+
const tick = () => {
|
|
471
|
+
if (this.updateRun || this.disposed)
|
|
472
|
+
return;
|
|
473
|
+
this.updateRun = this.checkDueUpdates().catch(error => logger.warn('[Template] Update scan: ' + String(error)))
|
|
474
|
+
.finally(() => { this.updateRun = undefined; });
|
|
475
|
+
};
|
|
476
|
+
this.updateTimer = setInterval(tick, 60_000);
|
|
477
|
+
this.updateTimer.unref?.();
|
|
478
|
+
tick();
|
|
479
|
+
}
|
|
480
|
+
async checkDueUpdates(now = Date.now()) {
|
|
481
|
+
for (const target of this.deps.updates?.targets() ?? []) {
|
|
482
|
+
if (this.disposed || !this.jobs.installation(target.aid))
|
|
483
|
+
continue;
|
|
484
|
+
const file = this.updateFile(target.aid);
|
|
485
|
+
let state = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
|
|
486
|
+
if (!state) {
|
|
487
|
+
writeTemplateState(file, { nextCheckAt: now + 60_000 + parseInt(templateFingerprint(target.aid).slice(0, 8), 16) % 600_000 });
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
if (target.mode === 'disabled') {
|
|
491
|
+
if (state.mode !== 'disabled')
|
|
492
|
+
writeTemplateState(file, { ...state, mode: 'disabled', nextCheckAt: now + 86400_000 });
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
const changed = state.installation && state.installation !== templateFingerprint(this.jobs.installation(target.aid))
|
|
496
|
+
|| state.mode === 'disabled' && target.mode !== 'disabled';
|
|
497
|
+
if (!changed && state.nextCheckAt > now)
|
|
498
|
+
continue;
|
|
499
|
+
try {
|
|
500
|
+
await this.checkUpdate(target.aid);
|
|
501
|
+
}
|
|
502
|
+
catch (error) {
|
|
503
|
+
state = { ...state, failures: (state.failures ?? 0) + 1, error: { code: error.code ?? 'CHECK_FAILED', message: error.message },
|
|
504
|
+
nextCheckAt: now + [300_000, 1800_000, 7200_000, 86400_000][Math.min(state.failures ?? 0, 3)] };
|
|
505
|
+
writeTemplateState(file, state);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
async previewUpdate(job) {
|
|
510
|
+
const context = await this.step(job, () => this.updateAuthority(job.args.targetAid, job.actor));
|
|
511
|
+
const installation = this.installed(job.args.targetAid, job.actor, context.projectPath);
|
|
512
|
+
if (!installation)
|
|
513
|
+
throw templateError('SOURCE_UNBOUND', '未绑定更新源;真实 Owner 须先选择并确认来源');
|
|
514
|
+
let frozen = job.checkpoint.update;
|
|
515
|
+
if (!frozen) {
|
|
516
|
+
await this.step(job, () => this.checkUpdate(job.args.targetAid, job.actor));
|
|
517
|
+
const release = await this.step(job, () => this.fixedRelease(installation.source, job.args.releaseId, job.jobId + ':detail'));
|
|
518
|
+
if (installation.release && compareTemplateVersions(release.version, installation.release.version) <= 0) {
|
|
519
|
+
throw templateError(release.version === installation.release.version && release.digest !== installation.release.digest
|
|
520
|
+
? 'VERSION_CONTENT_CONFLICT' : 'VERSION_NOT_NEWER', 'Choose a newer author member version');
|
|
521
|
+
}
|
|
522
|
+
frozen = job.checkpoint.update = { installation, release,
|
|
523
|
+
lock: this.snapshot(this.jobs.installationFile(job.args.targetAid)), packageId: 'package_' + randomUUID(), downloadGeneration: 1 };
|
|
524
|
+
job.resumable = true;
|
|
525
|
+
this.jobs.save(job);
|
|
526
|
+
}
|
|
527
|
+
if (templateFingerprint(installation) !== templateFingerprint(frozen.installation))
|
|
528
|
+
throw templateError('SOURCE_CHANGED', 'Original installed source changed');
|
|
529
|
+
const release = await this.step(job, () => this.fixedRelease(installation.source, frozen.release.releaseId, job.jobId + ':verify:' + job.attempt));
|
|
530
|
+
if (templateFingerprint(release) !== templateFingerprint(frozen.release))
|
|
531
|
+
throw templateError('SOURCE_CHANGED', 'Frozen candidate changed');
|
|
532
|
+
const directory = path.join(this.cache, 'packages', frozen.packageId);
|
|
533
|
+
const file = path.join(directory, 'record.json');
|
|
534
|
+
if (!fs.existsSync(file)) {
|
|
535
|
+
this.phase(job, 'authorizing_download');
|
|
536
|
+
if (frozen.downloadAuthorization && (frozen.downloadExpiresAt <= Date.now() || frozen.downloadError === 'ACCESS_DENIED')) {
|
|
537
|
+
frozen.downloadGeneration++;
|
|
538
|
+
delete frozen.downloadAuthorization;
|
|
539
|
+
delete frozen.downloadError;
|
|
540
|
+
this.jobs.save(job);
|
|
541
|
+
}
|
|
542
|
+
const download = frozen.downloadAuthorization ?? await this.step(job, () => this.deps.updates.catalog(installation.source, 'download', { releaseId: release.releaseId, targetHostAid: this.deps.hostAid }, job.jobId + ':download:' + frozen.downloadGeneration));
|
|
543
|
+
const errors = templateContract.validateTemplateRequest({ requestId: job.requestId, action: 'pull', args: { source: download.source } });
|
|
544
|
+
if (download.releaseId !== release.releaseId || download.targetHostAid !== this.deps.hostAid || errors.length
|
|
545
|
+
|| download.source?.kind !== 'remote' || download.source.digest !== release.digest)
|
|
546
|
+
throw templateError('INTEGRITY_FAILED', 'Fixed Host download authorization differs');
|
|
547
|
+
if (!frozen.downloadAuthorization) {
|
|
548
|
+
frozen.downloadAuthorization = download;
|
|
549
|
+
frozen.downloadExpiresAt = Date.now() + Math.min(download.expiresInSeconds ?? 300, 300) * 1000;
|
|
550
|
+
this.jobs.save(job);
|
|
551
|
+
}
|
|
552
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
553
|
+
const archivePath = path.join(directory, 'package.ectpl');
|
|
554
|
+
// Only this unpublished cache file is replaced when renewing credentials for the same frozen release.
|
|
555
|
+
fs.rmSync(archivePath, { force: true });
|
|
556
|
+
this.phase(job, 'downloading');
|
|
557
|
+
try {
|
|
558
|
+
await this.step(job, () => this.deps.download(download.source.download?.shareId, archivePath, download.source.location));
|
|
559
|
+
}
|
|
560
|
+
catch (error) {
|
|
561
|
+
frozen.downloadError = error.code ?? 'DOWNLOAD_FAILED';
|
|
562
|
+
this.jobs.save(job);
|
|
563
|
+
throw error;
|
|
564
|
+
}
|
|
565
|
+
const data = await this.executeTool(job, 'read-package', { archivePath, digest: release.digest });
|
|
566
|
+
const member = data.members?.[installation.source.memberKey];
|
|
567
|
+
const parameters = member ? publicTemplate.resolveMemberParameters(member) : {};
|
|
568
|
+
if (!member || parameters.version !== release.version || parameters.update?.publisher !== installation.source.publisher
|
|
569
|
+
|| data.metadata?.id !== installation.source.templateId || data.metadata?.version !== release.packageVersion || data.digest !== release.digest) {
|
|
570
|
+
throw templateError('INTEGRITY_FAILED', 'Package does not contain the attested original member declaration');
|
|
571
|
+
}
|
|
572
|
+
writeTemplateState(file, { actor: job.actor, packageId: frozen.packageId, createdAt: Date.now(),
|
|
573
|
+
data: { ...data, file: archivePath }, provenance: { kind: 'update', release } });
|
|
574
|
+
}
|
|
575
|
+
await this.preview(job, { packageId: frozen.packageId, installMode: 'overwrite',
|
|
576
|
+
members: { [installation.source.memberKey]: { target: { aid: installation.targetAid, project: installation.projectPath },
|
|
577
|
+
...(job.args.providers ? { providers: job.args.providers } : {}) } } }, frozen);
|
|
578
|
+
}
|
|
579
|
+
/** Canonical whitelist shared by automatic discovery and manual archive association. */
|
|
580
|
+
definitionManifest(input, strict = false) {
|
|
581
|
+
const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
582
|
+
const fields = (value, allowed) => record(value) && Object.keys(value).every(key => allowed.includes(key));
|
|
583
|
+
if (!record(input) || input.version !== 1 || typeof input.team_id !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(input.team_id)
|
|
584
|
+
|| !isValidAid(input.owner?.aid) || !isValidAid(input.team?.host?.aid) || input.owner.aid === input.team.host.aid || !Array.isArray(input.team?.agents) || !input.team.agents.length
|
|
585
|
+
|| input.team.agents.length > 200 || strict && (!fields(input, ['version', 'team_id', 'owner', 'team', 'member_references'])
|
|
586
|
+
|| !fields(input.owner, ['aid']) || !fields(input.team, ['host', 'assistantKey', 'agents']) || !fields(input.team.host, ['aid']))) {
|
|
587
|
+
throw templateError('INVALID_DEFINITION', 'A lightweight Team identity manifest is required');
|
|
588
|
+
}
|
|
589
|
+
const actual = input.team.agents.map((member) => {
|
|
590
|
+
if (!record(member) || !/^[a-z0-9][a-z0-9_-]{0,31}$/.test(member.key ?? '') || !isValidAid(member.aid)
|
|
591
|
+
|| strict && !fields(member, ['key', 'aid']))
|
|
592
|
+
throw templateError('INVALID_DEFINITION', 'Invalid actual Team member');
|
|
593
|
+
return { key: member.key, aid: member.aid };
|
|
594
|
+
});
|
|
595
|
+
if (new Set(actual.map((member) => member.key)).size !== actual.length || new Set(actual.map((member) => member.aid)).size !== actual.length
|
|
596
|
+
|| actual.some((member) => [input.owner.aid, input.team.host.aid].includes(member.aid)))
|
|
597
|
+
throw templateError('INVALID_DEFINITION', 'Distinct actual Team identities are required');
|
|
598
|
+
const references = input.member_references ?? { optional: [], external: [] };
|
|
599
|
+
if (!fields(references, ['optional', 'external']) || !Array.isArray(references.optional) || !Array.isArray(references.external)
|
|
600
|
+
|| references.optional.length > 200 || references.external.length > 200)
|
|
601
|
+
throw templateError('INVALID_DEFINITION', 'Invalid member_references');
|
|
602
|
+
if (input.assistantKey !== undefined && input.team.assistantKey !== undefined && input.assistantKey !== input.team.assistantKey) {
|
|
603
|
+
throw templateError('CONFLICT', 'Top-level and Team assistant keys conflict');
|
|
604
|
+
}
|
|
605
|
+
const assistantKey = strict ? input.team.assistantKey : input.assistantKey ?? input.team.assistantKey
|
|
606
|
+
?? actual.find((member) => !references.optional.some((reference) => reference?.key === member.key))?.key;
|
|
607
|
+
if (!actual.some((member) => member.key === assistantKey)
|
|
608
|
+
|| references.optional.some((member) => member?.key === assistantKey)
|
|
609
|
+
|| strict && references.optional.some((member) => actual.some((created) => created.key === member?.key))) {
|
|
610
|
+
throw templateError('INVALID_DEFINITION', 'An explicit actual required assistantKey is required');
|
|
611
|
+
}
|
|
612
|
+
const declarations = [...actual.filter((member) => !references.optional.some((value) => value?.key === member.key))
|
|
613
|
+
.map((member) => ({ key: member.key, profile: { name: member.key } })), ...references.optional];
|
|
614
|
+
const normalized = templateContract.normalizeTeam({ $schema_version: 1, id: 'team-definition', version: '1.0.0', host: { platform: [process.platform] },
|
|
615
|
+
agents: declarations, personal_assistant: declarations.findIndex(member => member.key === assistantKey), external_contacts: references.external });
|
|
616
|
+
if (normalized.errors.length)
|
|
617
|
+
throw templateError('INVALID_DEFINITION', normalized.errors.join('; '));
|
|
618
|
+
const identities = new Set([input.owner.aid, input.team.host.aid, ...actual.map((member) => member.aid)]);
|
|
619
|
+
if (references.external.some((member) => identities.has(member.aid)))
|
|
620
|
+
throw templateError('CONFLICT', 'External AID conflicts with a Team identity');
|
|
621
|
+
return { version: 1, team_id: input.team_id, owner: { aid: input.owner.aid },
|
|
622
|
+
team: { host: { aid: input.team.host.aid }, assistantKey, agents: actual }, member_references: structuredClone(references) };
|
|
623
|
+
}
|
|
624
|
+
/** Always recheck definitions on demand; pending consensus is never a permanent completed marker. */
|
|
625
|
+
async discoverTeams() {
|
|
626
|
+
if (this.disposed)
|
|
627
|
+
return [];
|
|
628
|
+
if (this.discoveryRun)
|
|
629
|
+
return this.discoveryRun;
|
|
630
|
+
const run = this.scanTeamDefinitions().finally(() => { if (this.discoveryRun === run)
|
|
631
|
+
this.discoveryRun = undefined; });
|
|
632
|
+
this.discoveryRun = run;
|
|
633
|
+
return run;
|
|
634
|
+
}
|
|
635
|
+
async scanTeamDefinitions() {
|
|
636
|
+
const results = [];
|
|
637
|
+
let files;
|
|
638
|
+
try {
|
|
639
|
+
files = this.jobs.definitionFiles();
|
|
640
|
+
}
|
|
641
|
+
catch (error) {
|
|
642
|
+
return [{ file: 'team-definitions', status: 'rejected', code: error.code ?? 'DEFINITION_READ_FAILED', message: error.message, checkedAt: Date.now() }];
|
|
643
|
+
}
|
|
644
|
+
for (const file of files) {
|
|
645
|
+
if (this.disposed)
|
|
646
|
+
break;
|
|
647
|
+
const result = { file, status: 'pending', checkedAt: Date.now() };
|
|
648
|
+
try {
|
|
649
|
+
const envelope = this.jobs.readDefinition(file);
|
|
650
|
+
if (!envelope || envelope.schemaVersion !== 1 || Object.keys(envelope).some(key => !['schemaVersion', 'definitionDigest', 'manifest'].includes(key))) {
|
|
651
|
+
throw templateError('INVALID_DEFINITION', 'Invalid Team definition envelope');
|
|
652
|
+
}
|
|
653
|
+
const manifest = this.definitionManifest(envelope.manifest, true);
|
|
654
|
+
result.teamId = manifest.team_id;
|
|
655
|
+
result.ownerAid = manifest.owner.aid;
|
|
656
|
+
result.hostAid = manifest.team.host.aid;
|
|
657
|
+
result.assistantAid = manifest.team.agents.find((member) => member.key === manifest.team.assistantKey).aid;
|
|
658
|
+
result.instanceId = 'team_' + templateFingerprint({ teamId: manifest.team_id, ownerAid: result.ownerAid, hostAid: result.hostAid });
|
|
659
|
+
result.definitionDigest = templateContract.contractDigest(manifest);
|
|
660
|
+
if (file !== manifest.team_id + '.json')
|
|
661
|
+
throw templateError('CONFLICT', 'Team definition filename differs from team_id');
|
|
662
|
+
if (envelope.definitionDigest !== templateContract.contractDigest(envelope.manifest))
|
|
663
|
+
throw templateError('INTEGRITY_FAILED', 'Team definition digest mismatch');
|
|
664
|
+
if (manifest.team.host.aid !== this.deps.hostAid)
|
|
665
|
+
throw templateError('NOT_ALLOWED', 'Team definition belongs to another Host');
|
|
666
|
+
if (!this.deps.discovery)
|
|
667
|
+
throw templateError('DISCOVERY_UNAVAILABLE', 'Internal Team ownership verification is unavailable');
|
|
668
|
+
await this.deps.discovery.verifyHost(manifest.owner.aid, manifest.team.host.aid);
|
|
669
|
+
if (this.disposed)
|
|
670
|
+
break;
|
|
671
|
+
await this.registerTeamRecord(manifest.owner.aid, manifest, { definitionDigest: result.definitionDigest, source: 'definition', verifySource: () => {
|
|
672
|
+
if (templateFingerprint(this.jobs.readDefinition(file)) !== templateFingerprint(envelope))
|
|
673
|
+
throw templateError('SOURCE_CHANGED', 'Team definition changed during ownership verification');
|
|
674
|
+
} });
|
|
675
|
+
result.status = 'registered';
|
|
676
|
+
}
|
|
677
|
+
catch (error) {
|
|
678
|
+
result.code = error.code ?? 'DEFINITION_READ_FAILED';
|
|
679
|
+
result.message = error.message;
|
|
680
|
+
result.status = ['DISCOVERY_UNAVAILABLE', 'OWNERSHIP_UNAVAILABLE', 'PROFILE_UNAVAILABLE', 'AUN_DISCONNECTED', 'NOT_FOUND', 'SOURCE_CHANGED'].includes(result.code) ? 'pending' : 'rejected';
|
|
681
|
+
}
|
|
682
|
+
results.push(result);
|
|
683
|
+
}
|
|
684
|
+
if (!this.disposed && files.length)
|
|
685
|
+
writeTemplateState(path.join(this.cache, 'team-discovery.json'), { version: 1, checkedAt: Date.now(), definitions: results });
|
|
686
|
+
return results;
|
|
687
|
+
}
|
|
688
|
+
async discoveredTeamMembers(actor, args) {
|
|
689
|
+
if ((typeof args.instanceId === 'string') === (typeof args.assistantAid === 'string')
|
|
690
|
+
|| Object.keys(args).some(key => !['instanceId', 'assistantAid'].includes(key)))
|
|
691
|
+
throw templateError('INVALID_ARGUMENT', 'Use instanceId or assistantAid, exclusively');
|
|
692
|
+
if (args.assistantAid) {
|
|
693
|
+
if (!isValidAid(args.assistantAid))
|
|
694
|
+
throw templateError('INVALID_ARGUMENT', 'Valid assistantAid required');
|
|
695
|
+
await this.deps.authorize(actor, args.assistantAid);
|
|
696
|
+
}
|
|
697
|
+
const discovery = await this.discoverTeams();
|
|
698
|
+
const failures = discovery.filter(item => item.ownerAid === actor && item.hostAid === this.deps.hostAid
|
|
699
|
+
&& (args.instanceId ? item.instanceId === args.instanceId : item.assistantAid === args.assistantAid) && item.status !== 'registered');
|
|
700
|
+
if (failures.length)
|
|
701
|
+
throw templateError(failures[0].status === 'pending' ? 'TEAM_DISCOVERY_PENDING' : failures[0].code, failures[0].message, { discovery: failures });
|
|
702
|
+
const teams = this.jobs.listTeams().filter(team => team.ownerAid === actor && team.hostAid === this.deps.hostAid
|
|
703
|
+
&& (args.instanceId ? team.instanceId === args.instanceId : team.members.some(member => member.key === team.assistantKey && member.aid === args.assistantAid)));
|
|
704
|
+
const invalidSource = discovery.find(item => item.status !== 'registered' && (item.file === 'team-definitions'
|
|
705
|
+
|| teams.some(team => item.file === team.teamId + '.json')));
|
|
706
|
+
if (invalidSource)
|
|
707
|
+
throw templateError(invalidSource.status === 'pending' ? 'TEAM_DISCOVERY_PENDING' : invalidSource.code, invalidSource.message, { discovery: [{ file: invalidSource.file, status: invalidSource.status, code: invalidSource.code }] });
|
|
708
|
+
if (teams.length > 1)
|
|
709
|
+
throw templateError('CONFLICT', 'Assistant belongs to multiple original Team instances');
|
|
710
|
+
if (!teams.length)
|
|
711
|
+
throw templateError('NOT_FOUND', 'Original Team instance not found', { discoveryPending: discovery.filter(item => item.status === 'pending').length,
|
|
712
|
+
invalidDefinitions: discovery.filter(item => item.status === 'rejected').length });
|
|
713
|
+
return this.teamMembers(actor, teams[0].instanceId);
|
|
714
|
+
}
|
|
715
|
+
async ownedTeam(actor, instanceId) {
|
|
716
|
+
const team = this.jobs.readTeam(instanceId);
|
|
717
|
+
if (team.ownerAid !== actor || team.hostAid !== this.deps.hostAid)
|
|
718
|
+
throw templateError('NOT_ALLOWED', 'Original Team Owner and Host required');
|
|
719
|
+
for (const member of team.members)
|
|
720
|
+
if (member.aid)
|
|
721
|
+
await this.deps.authorize(actor, member.aid);
|
|
722
|
+
return this.jobs.readTeam(instanceId);
|
|
723
|
+
}
|
|
724
|
+
/** Accept only identities already present on this Host; retain references without the source package. */
|
|
725
|
+
async registerTeam(actor, manifest, deliveryDigest) {
|
|
726
|
+
await this.deps.installation.authorize(actor);
|
|
727
|
+
const projected = this.definitionManifest(manifest);
|
|
728
|
+
const instanceId = await this.registerTeamRecord(actor, manifest, { deliveryDigest, definitionDigest: templateContract.contractDigest(projected), source: 'manual' });
|
|
729
|
+
return this.teamMembers(actor, instanceId);
|
|
730
|
+
}
|
|
731
|
+
async registerTeamRecord(actor, manifest, provenance) {
|
|
732
|
+
const projected = this.definitionManifest(manifest, provenance.source === 'definition');
|
|
733
|
+
if (!manifest || manifest.version !== 1 || typeof manifest.team_id !== 'string' || !manifest.team_id
|
|
734
|
+
|| provenance.source === 'manual' && !/^sha256:[a-f0-9]{64}$/.test(provenance.deliveryDigest ?? '') || manifest.owner?.aid !== actor
|
|
735
|
+
|| manifest.team?.host?.aid !== this.deps.hostAid || !Array.isArray(manifest.team?.agents) || !manifest.team.agents.length) {
|
|
736
|
+
throw templateError('INVALID_ARGUMENT', 'A matching Owner/Host delivery manifest and digest are required');
|
|
737
|
+
}
|
|
738
|
+
const refs = manifest.member_references ?? { optional: [], external: [] };
|
|
739
|
+
if (!Array.isArray(refs.optional) || !Array.isArray(refs.external)
|
|
740
|
+
|| Object.keys(refs).some(key => !['optional', 'external'].includes(key)))
|
|
741
|
+
throw templateError('INVALID_ARGUMENT', 'Invalid member_references');
|
|
742
|
+
const actual = [];
|
|
743
|
+
const targets = {};
|
|
744
|
+
for (const declaration of manifest.team.agents) {
|
|
745
|
+
if (!declaration || typeof declaration.key !== 'string' || !isValidAid(declaration.aid)
|
|
746
|
+
|| [actor, this.deps.hostAid].includes(declaration.aid) || actual.some(member => member.aid === declaration.aid || member.key === declaration.key)) {
|
|
747
|
+
throw templateError('INVALID_ARGUMENT', 'Delivery members must have distinct real AIDs and keys');
|
|
748
|
+
}
|
|
749
|
+
if (provenance.source === 'manual')
|
|
750
|
+
await this.deps.authorize(actor, declaration.aid);
|
|
751
|
+
const target = provenance.source === 'definition' ? await this.deps.discovery.member(declaration.aid, actor, this.deps.hostAid)
|
|
752
|
+
: await this.deps.target(declaration.aid, actor);
|
|
753
|
+
if (this.disposed)
|
|
754
|
+
throw templateError('RECOVERY_REQUIRED', 'Template runtime has been disposed');
|
|
755
|
+
if (target.targetAid !== declaration.aid || !path.isAbsolute(target.projectPath ?? ''))
|
|
756
|
+
throw templateError('NOT_FOUND', 'Delivery member is unavailable on this Host');
|
|
757
|
+
targets[declaration.key] = target;
|
|
758
|
+
actual.push({ key: declaration.key, aid: declaration.aid, projectPath: target.projectPath,
|
|
759
|
+
profile: structuredClone(target.profile), state: 'joined',
|
|
760
|
+
...(Object.hasOwn(target.targetConfig ?? {}, 'access') ? { config: { access: publicTemplate.validateAccessDeclaration(target.targetConfig.access) } } : {}) });
|
|
761
|
+
}
|
|
762
|
+
const references = new Map(refs.optional.map((value) => [value?.key, value]));
|
|
763
|
+
if (references.size !== refs.optional.length)
|
|
764
|
+
throw templateError('INVALID_ARGUMENT', 'Duplicate optional reference');
|
|
765
|
+
const required = actual.filter(member => !references.has(member.key));
|
|
766
|
+
const assistantKey = manifest.assistantKey ?? manifest.team.assistantKey ?? required[0]?.key;
|
|
767
|
+
const declarations = [...required, ...refs.optional];
|
|
768
|
+
const normalized = templateContract.normalizeTeam({ $schema_version: 1, id: 'delivered-team', version: '1.0.0',
|
|
769
|
+
host: { platform: [process.platform] }, agents: declarations.map(({ state: _state, aid: _aid, projectPath: _project, ...member }) => member),
|
|
770
|
+
external_contacts: refs.external, personal_assistant: declarations.findIndex(member => member.key === assistantKey) });
|
|
771
|
+
if (normalized.errors.length)
|
|
772
|
+
throw templateError('INVALID_ARGUMENT', normalized.errors.join('; '));
|
|
773
|
+
const partition = publicTemplate.partitionTeamMembers(normalized.team);
|
|
774
|
+
const identityAids = new Set([actor, this.deps.hostAid, ...actual.map(member => member.aid)]);
|
|
775
|
+
if (partition.externalContacts.some((contact) => identityAids.has(contact.aid)))
|
|
776
|
+
throw templateError('CONFLICT', 'External AID conflicts with a Team identity');
|
|
777
|
+
const instanceId = 'team_' + templateFingerprint({ teamId: manifest.team_id, ownerAid: actor, hostAid: this.deps.hostAid });
|
|
778
|
+
await this.jobs.withTeams(async () => {
|
|
779
|
+
if (this.disposed)
|
|
780
|
+
throw templateError('RECOVERY_REQUIRED', 'Template runtime has been disposed');
|
|
781
|
+
provenance.verifySource?.();
|
|
782
|
+
if (fs.existsSync(this.jobs.teamFile(instanceId))) {
|
|
783
|
+
const current = this.jobs.readTeam(instanceId);
|
|
784
|
+
const existing = current.definitionManifest ?? this.definitionManifest({ version: 1, team_id: current.teamId, owner: { aid: current.ownerAid },
|
|
785
|
+
team: { host: { aid: current.hostAid }, assistantKey: current.assistantKey,
|
|
786
|
+
agents: current.members.filter(member => member.aid && !member.installation).map(member => ({ key: member.key, aid: member.aid })) },
|
|
787
|
+
member_references: { optional: current.members.filter(member => member.optional).map(member => member.installation
|
|
788
|
+
? this.jobs.read(member.installation.jobId).checkpoint.memberInstall.declaration
|
|
789
|
+
: { key: member.key, optional: true, agentTemplateId: member.agentTemplateId, profile: member.profile, ...(member.config ? { config: member.config } : {}) }),
|
|
790
|
+
external: current.externalContacts } });
|
|
791
|
+
if (templateContract.contractDigest(existing) !== provenance.definitionDigest
|
|
792
|
+
|| current.definitionDigest && current.definitionDigest !== provenance.definitionDigest
|
|
793
|
+
|| current.deliveryDigest && provenance.deliveryDigest && current.deliveryDigest !== provenance.deliveryDigest) {
|
|
794
|
+
throw templateError('CONFLICT', 'Team already registered from a different definition or archive');
|
|
795
|
+
}
|
|
796
|
+
const revision = current.revision;
|
|
797
|
+
const before = templateFingerprint(current);
|
|
798
|
+
current.definitionDigest = provenance.definitionDigest;
|
|
799
|
+
current.definitionManifest = projected;
|
|
800
|
+
if (provenance.deliveryDigest)
|
|
801
|
+
current.deliveryDigest = provenance.deliveryDigest;
|
|
802
|
+
current.sources = [...new Set([...(current.sources ?? []), provenance.source])];
|
|
803
|
+
if (templateFingerprint(current) !== before)
|
|
804
|
+
this.jobs.saveTeam(current, revision);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
const members = actual.map(member => references.has(member.key)
|
|
808
|
+
? { ...structuredClone(references.get(member.key)), ...member, optional: true } : member);
|
|
809
|
+
for (const reference of partition.optionalReferences)
|
|
810
|
+
if (!actual.some(member => member.key === reference.key))
|
|
811
|
+
members.push({ ...reference, state: 'available' });
|
|
812
|
+
const team = { version: 1, instanceId, teamId: manifest.team_id, ownerAid: actor,
|
|
813
|
+
hostAid: this.deps.hostAid, ...(provenance.deliveryDigest ? { deliveryDigest: provenance.deliveryDigest } : {}),
|
|
814
|
+
definitionDigest: provenance.definitionDigest, definitionManifest: projected, sources: [provenance.source],
|
|
815
|
+
assistantKey, members, externalContacts: partition.externalContacts,
|
|
816
|
+
relationshipTargets: actual.filter(member => (targets[member.key].targetConfig?.team ?? [])
|
|
817
|
+
.some((aid) => actual.some(other => other.aid === aid))).map(member => member.aid),
|
|
818
|
+
revision: '', createdAt: Date.now(), updatedAt: Date.now() };
|
|
819
|
+
this.jobs.saveTeam(team);
|
|
820
|
+
});
|
|
821
|
+
return instanceId;
|
|
822
|
+
}
|
|
823
|
+
async teamMembers(actor, instanceId) {
|
|
824
|
+
let team = await this.ownedTeam(actor, instanceId);
|
|
825
|
+
for (const member of team.members)
|
|
826
|
+
if (member.installation) {
|
|
827
|
+
const job = this.jobs.read(member.installation.jobId);
|
|
828
|
+
if (job.committed)
|
|
829
|
+
await this.attachCommittedMember(job);
|
|
830
|
+
}
|
|
831
|
+
team = this.jobs.readTeam(instanceId);
|
|
832
|
+
return { instanceId, teamId: team.teamId, ownerAid: team.ownerAid, hostAid: team.hostAid,
|
|
833
|
+
...(team.definitionDigest ? { definitionDigest: team.definitionDigest } : {}), ...(team.deliveryDigest ? { deliveryDigest: team.deliveryDigest } : {}),
|
|
834
|
+
sources: team.sources ?? [],
|
|
835
|
+
assistantKey: team.assistantKey, revision: team.revision, members: team.members, externalContacts: team.externalContacts };
|
|
836
|
+
}
|
|
837
|
+
async prepareMemberInstall(actor, requestId, args) {
|
|
838
|
+
await this.ownedTeam(actor, args.instanceId);
|
|
839
|
+
return this.jobs.withTeams(async () => {
|
|
840
|
+
const file = path.join(this.cache, 'member-install-requests', templateFingerprint({ actor, requestId }) + '.json');
|
|
841
|
+
if (fs.existsSync(file)) {
|
|
842
|
+
const prior = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
843
|
+
if (prior.fingerprint !== templateFingerprint(args))
|
|
844
|
+
throw templateError('CONFLICT', 'Request has different slot arguments');
|
|
845
|
+
return this.memberInstallView(this.jobs.readMemberInstall(actor, prior.memberInstallId));
|
|
846
|
+
}
|
|
847
|
+
const team = this.jobs.readTeam(args.instanceId);
|
|
848
|
+
if (team.revision !== args.expectedRevision)
|
|
849
|
+
throw templateError('CONFLICT', 'Team revision changed', { revision: team.revision });
|
|
850
|
+
const member = team.members.find(value => value.key === args.memberKey);
|
|
851
|
+
if (!member?.optional)
|
|
852
|
+
throw templateError('INVALID_ARGUMENT', 'An optional slot in the original Team is required');
|
|
853
|
+
if (member.state !== 'available' || member.aid || member.installation)
|
|
854
|
+
throw templateError('CONFLICT', 'Slot already has an installation', { jobId: member.installation?.jobId, state: member.state });
|
|
855
|
+
const { key, profile, config, agentTemplateId } = member;
|
|
856
|
+
const value = { memberInstallId: 'member_install_' + randomUUID(), actor,
|
|
857
|
+
instanceId: team.instanceId, memberKey: key, ownerAid: team.ownerAid, hostAid: team.hostAid,
|
|
858
|
+
declaration: { key, optional: true, agentTemplateId, profile, ...(config ? { config } : {}) },
|
|
859
|
+
revision: team.revision, createdAt: Date.now() };
|
|
860
|
+
this.jobs.saveMemberInstall(value);
|
|
861
|
+
writeTemplateState(file, { fingerprint: templateFingerprint(args), memberInstallId: value.memberInstallId });
|
|
862
|
+
return this.memberInstallView(value);
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
memberInstallView(value) {
|
|
866
|
+
const { actor: _actor, ...view } = value;
|
|
867
|
+
return { ...view, catalogAvailable: !!this.deps.resolveMemberRelease };
|
|
868
|
+
}
|
|
869
|
+
async memberInstall(actor, id) {
|
|
870
|
+
const value = this.jobs.readMemberInstall(actor, id);
|
|
871
|
+
const team = await this.ownedTeam(actor, value.instanceId);
|
|
872
|
+
if (value.ownerAid !== actor || value.hostAid !== this.deps.hostAid || !team.members.some(member => member.key === value.memberKey
|
|
873
|
+
&& member.agentTemplateId === value.declaration.agentTemplateId))
|
|
874
|
+
throw templateError('CONFLICT', 'Original slot binding changed');
|
|
875
|
+
return value;
|
|
876
|
+
}
|
|
877
|
+
async updateTeamMember(instanceId, key, update) {
|
|
878
|
+
await this.jobs.withTeams(async () => {
|
|
879
|
+
const team = this.jobs.readTeam(instanceId);
|
|
880
|
+
const revision = team.revision;
|
|
881
|
+
const member = team.members.find(value => value.key === key);
|
|
882
|
+
if (!member)
|
|
883
|
+
throw templateError('RECOVERY_REQUIRED', 'Original slot is missing');
|
|
884
|
+
const before = templateFingerprint(team);
|
|
885
|
+
update(member, team);
|
|
886
|
+
if (before !== templateFingerprint(team))
|
|
887
|
+
this.jobs.saveTeam(team, revision);
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
/** Repair from the committed job, including a crash between commit and instance association. */
|
|
891
|
+
async attachCommittedMember(job) {
|
|
892
|
+
if (!job.committed || !job.checkpoint.memberInstall)
|
|
893
|
+
return;
|
|
894
|
+
const binding = job.checkpoint.memberInstall;
|
|
895
|
+
const record = this.previewRecord(job.args.previewId);
|
|
896
|
+
const sourceKey = binding.release.sourceMemberKey;
|
|
897
|
+
const installed = job.members[sourceKey];
|
|
898
|
+
if (job.actor !== binding.ownerAid || !installed?.aid || !installed.runtimeReady)
|
|
899
|
+
throw templateError('RECOVERY_REQUIRED', 'Committed member binding is invalid');
|
|
900
|
+
await this.updateTeamMember(binding.instanceId, binding.memberKey, (member, team) => {
|
|
901
|
+
if (team.ownerAid !== job.actor || team.hostAid !== binding.hostAid || member.installation?.jobId !== job.jobId
|
|
902
|
+
|| member.aid && member.aid !== installed.aid)
|
|
903
|
+
throw templateError('CONFLICT', 'Slot belongs to a different installation');
|
|
904
|
+
if (member.aid && ['installed', 'joining', 'joined'].includes(member.state))
|
|
905
|
+
return;
|
|
906
|
+
member.aid = installed.aid;
|
|
907
|
+
member.projectPath = installed.projectPath;
|
|
908
|
+
member.profile = structuredClone(record.data.profiles[sourceKey]);
|
|
909
|
+
const access = record.finalDeclaration?.config?.access;
|
|
910
|
+
member.config = access === undefined ? {} : { access: structuredClone(access) };
|
|
911
|
+
member.state = 'installed';
|
|
912
|
+
member.pending = { publicationId: 'publication_' + templateFingerprint({ instanceId: team.instanceId, key: member.key, jobId: job.jobId }),
|
|
913
|
+
aid: installed.aid, ownerAid: team.ownerAid, hostAid: team.hostAid, profile: structuredClone(member.profile),
|
|
914
|
+
ownerDirectoryMutation: { mode: 'add', requiresOwnerAuthorization: true, openPaContextAdd: [installed.aid],
|
|
915
|
+
entries: [{ aid: installed.aid, ...structuredClone(member.profile), type: 'agent', owner_aid: team.ownerAid, ownership_status: 'owned' }] } };
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
async resumeMemberJoin(actor, instanceId, memberKey) {
|
|
919
|
+
await this.ownedTeam(actor, instanceId);
|
|
920
|
+
return withFileLock(path.join(this.cache, 'teams', instanceId, templateFingerprint(memberKey) + '.join.lock'), async () => {
|
|
921
|
+
let team = await this.ownedTeam(actor, instanceId);
|
|
922
|
+
let member = team.members.find(value => value.key === memberKey);
|
|
923
|
+
if (!member?.installation)
|
|
924
|
+
throw templateError('INVALID_ARGUMENT', 'No optional installation in this slot');
|
|
925
|
+
const job = this.jobs.get(actor, { jobId: member.installation.jobId });
|
|
926
|
+
if (!job.committed)
|
|
927
|
+
throw templateError('RECOVERY_REQUIRED', 'Resume the original creation job first', { jobId: job.jobId });
|
|
928
|
+
await this.attachCommittedMember(job);
|
|
929
|
+
team = this.jobs.readTeam(instanceId);
|
|
930
|
+
member = team.members.find(value => value.key === memberKey);
|
|
931
|
+
if (member.state !== 'joined') {
|
|
932
|
+
await this.updateTeamMember(instanceId, memberKey, value => { value.state = 'joining'; delete value.pending.error; });
|
|
933
|
+
try {
|
|
934
|
+
if (!this.deps.joining)
|
|
935
|
+
throw templateError('OWNER_DIRECTORY_PENDING', 'Owner publication and verification dependencies are unavailable');
|
|
936
|
+
const evidence = await this.deps.joining.ownership(member.aid, actor, team.hostAid);
|
|
937
|
+
await this.updateTeamMember(instanceId, memberKey, value => { value.pending.ownershipEvidence = evidence; });
|
|
938
|
+
team = await this.ownedTeam(actor, instanceId);
|
|
939
|
+
member = team.members.find(value => value.key === memberKey);
|
|
940
|
+
const directory = await this.deps.joining.verifyDirectory(team, member);
|
|
941
|
+
if (!directory.revision)
|
|
942
|
+
throw templateError('OWNER_DIRECTORY_PENDING', 'Verified Owner directory revision required');
|
|
943
|
+
await this.updateTeamMember(instanceId, memberKey, value => { value.pending.directory = directory; });
|
|
944
|
+
await this.deps.joining.addRelationships(team, member);
|
|
945
|
+
// Revalidate after side effects. A lost response retries only idempotent membership additions.
|
|
946
|
+
await this.ownedTeam(actor, instanceId);
|
|
947
|
+
await this.deps.joining.ownership(member.aid, actor, team.hostAid);
|
|
948
|
+
await this.deps.joining.verifyDirectory(team, member);
|
|
949
|
+
await this.updateTeamMember(instanceId, memberKey, value => { value.pending.relationshipsApplied = true; value.state = 'joined'; });
|
|
950
|
+
}
|
|
951
|
+
catch (error) {
|
|
952
|
+
await this.updateTeamMember(instanceId, memberKey, value => {
|
|
953
|
+
value.pending.error = { code: error.code ?? 'JOIN_PENDING', message: error.message };
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
return this.teamMembers(actor, instanceId);
|
|
958
|
+
});
|
|
959
|
+
}
|
|
175
960
|
async inspect(actor, requestId, args) {
|
|
176
961
|
const members = Object.fromEntries(Object.entries(args.members).map(([key, member]) => [key, { aid: member.source.kind === 'agent' ? member.source.aid : '',
|
|
177
962
|
projectPath: member.source.kind === 'directory' ? member.source.path : '', requestId: randomUUID() }]));
|
|
@@ -271,6 +1056,7 @@ export class AgentTemplateService {
|
|
|
271
1056
|
const { job } = this.jobs.accept(actor, requestId, 'build', args, structuredClone(current.members));
|
|
272
1057
|
job.freeze = { ...current.freeze, state: 'held' };
|
|
273
1058
|
job.checkpoint.sources = current.checkpoint.sources;
|
|
1059
|
+
job.checkpoint.inventory = current.result;
|
|
274
1060
|
job.checkpoint.collectionKey = current.checkpoint.collectionKey;
|
|
275
1061
|
current.freeze = { ...current.freeze, state: 'transferred', buildJobId: job.jobId };
|
|
276
1062
|
current.status = 'succeeded';
|
|
@@ -294,6 +1080,8 @@ export class AgentTemplateService {
|
|
|
294
1080
|
}
|
|
295
1081
|
const data = await this.executeTool(value, 'build', { members: sources,
|
|
296
1082
|
selections: value.args.members, metadata: value.args.metadata, inventoryDigest: value.args.inventoryDigest,
|
|
1083
|
+
memberReferences: value.args.memberReferences, assistantKey: value.args.assistantKey,
|
|
1084
|
+
inventory: value.checkpoint.inventory,
|
|
297
1085
|
out: path.join(this.cache, 'packages', packageId) });
|
|
298
1086
|
this.current(value);
|
|
299
1087
|
const record = { actor, packageId, createdAt: Date.now(), data, provenance: {
|
|
@@ -348,10 +1136,22 @@ export class AgentTemplateService {
|
|
|
348
1136
|
const first = this.jobs.bindRequest(actor, requestId, action, { jobId }, jobId);
|
|
349
1137
|
if (!first)
|
|
350
1138
|
return this.view(job);
|
|
1139
|
+
if (action === 'resume' && job.committed && job.checkpoint.memberInstall) {
|
|
1140
|
+
await this.resumeMemberJoin(actor, job.checkpoint.memberInstall.instanceId, job.checkpoint.memberInstall.memberKey);
|
|
1141
|
+
return this.view(job);
|
|
1142
|
+
}
|
|
351
1143
|
if (action === 'cancel') {
|
|
352
1144
|
await this.cancelInternal(actor, jobId, 'user_cancel');
|
|
353
1145
|
}
|
|
354
1146
|
else {
|
|
1147
|
+
if (job.action === 'preview-update' && job.resumable && ['paused', 'failed'].includes(job.status)) {
|
|
1148
|
+
job.attempt++;
|
|
1149
|
+
job.status = 'queued';
|
|
1150
|
+
delete job.error;
|
|
1151
|
+
this.jobs.save(job);
|
|
1152
|
+
this.launch(job, value => this.previewUpdate(value));
|
|
1153
|
+
return this.view(job);
|
|
1154
|
+
}
|
|
355
1155
|
if (!job.resumable || job.action !== 'deploy' || !['paused', 'failed'].includes(job.status)) {
|
|
356
1156
|
throw templateError('CONFLICT', 'This job cannot resume');
|
|
357
1157
|
}
|
|
@@ -454,7 +1254,32 @@ export class AgentTemplateService {
|
|
|
454
1254
|
this.jobs.save(job);
|
|
455
1255
|
}
|
|
456
1256
|
async pull(job) {
|
|
457
|
-
|
|
1257
|
+
let source = job.args.source;
|
|
1258
|
+
let binding;
|
|
1259
|
+
if (job.args.memberInstallId) {
|
|
1260
|
+
binding = await this.step(job, () => this.memberInstall(job.actor, job.args.memberInstallId));
|
|
1261
|
+
if (!binding.release) {
|
|
1262
|
+
if (!this.deps.resolveMemberRelease)
|
|
1263
|
+
throw templateError('CATALOG_UNAVAILABLE', 'No trusted single-Agent release catalog is configured');
|
|
1264
|
+
const release = await this.step(job, () => this.deps.resolveMemberRelease({ actor: job.actor,
|
|
1265
|
+
hostAid: binding.hostAid, agentTemplateId: binding.declaration.agentTemplateId }));
|
|
1266
|
+
const errors = templateContract.validateTemplateRequest({ requestId: job.requestId, action: 'pull', args: { source: release?.source } });
|
|
1267
|
+
if (errors.length || release.agentTemplateId !== binding.declaration.agentTemplateId || !release.releaseId
|
|
1268
|
+
|| !/^sha256:[a-f0-9]{64}$/.test(release.digest) || release.source.kind !== 'remote'
|
|
1269
|
+
|| release.source.digest !== release.digest || !/^[a-z0-9][a-z0-9_-]{0,31}$/.test(release.sourceMemberKey)
|
|
1270
|
+
|| typeof release.version !== 'string' || !release.version)
|
|
1271
|
+
throw templateError('INTEGRITY_FAILED', 'Catalog did not attest an exact single-Agent release');
|
|
1272
|
+
await this.jobs.withTeams(async () => {
|
|
1273
|
+
const current = this.jobs.readMemberInstall(job.actor, binding.memberInstallId);
|
|
1274
|
+
if (!current.release) {
|
|
1275
|
+
current.release = structuredClone(release);
|
|
1276
|
+
this.jobs.saveMemberInstall(current);
|
|
1277
|
+
}
|
|
1278
|
+
binding = current;
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
source = binding.release.source;
|
|
1282
|
+
}
|
|
458
1283
|
if (source.kind === 'artifact') {
|
|
459
1284
|
const record = this.packageRecord(job.actor, source.packageId);
|
|
460
1285
|
const { file: _file, ...data } = record.data;
|
|
@@ -472,9 +1297,17 @@ export class AgentTemplateService {
|
|
|
472
1297
|
else
|
|
473
1298
|
fs.copyFileSync(source.path, archivePath);
|
|
474
1299
|
const data = await this.executeTool(job, 'read-package', { archivePath, digest: source.digest });
|
|
1300
|
+
if (binding) {
|
|
1301
|
+
const release = binding.release;
|
|
1302
|
+
if (data.digest !== release.digest || Object.keys(data.members).length !== 1 || !data.members[release.sourceMemberKey]
|
|
1303
|
+
|| data.memberReferences?.optional?.length || data.metadata.version !== release.version) {
|
|
1304
|
+
throw templateError('INTEGRITY_FAILED', 'Downloaded package differs from the attested single-Agent release');
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
475
1307
|
writeTemplateState(path.join(directory, 'record.json'), { actor: job.actor, packageId, createdAt: Date.now(),
|
|
476
|
-
data: { ...data, file: archivePath }, provenance: { kind: 'import', source
|
|
477
|
-
|
|
1308
|
+
data: { ...data, file: archivePath }, provenance: { kind: 'import', source,
|
|
1309
|
+
...(binding ? { memberInstallId: binding.memberInstallId, release: binding.release } : {}) } });
|
|
1310
|
+
job.result = { ...data, packageId, ...(binding ? { memberInstallId: binding.memberInstallId, release: binding.release } : {}) };
|
|
478
1311
|
}
|
|
479
1312
|
job.status = 'succeeded';
|
|
480
1313
|
job.phase = 'completed';
|
|
@@ -485,41 +1318,105 @@ export class AgentTemplateService {
|
|
|
485
1318
|
throw templateError('INVALID_ARGUMENT', 'Invalid previewId');
|
|
486
1319
|
return JSON.parse(fs.readFileSync(path.join(this.cache, 'previews', id, 'record.json'), 'utf8'));
|
|
487
1320
|
}
|
|
488
|
-
async preview(job) {
|
|
489
|
-
const
|
|
490
|
-
const
|
|
491
|
-
|
|
492
|
-
|
|
1321
|
+
async preview(job, overrideArgs, update) {
|
|
1322
|
+
const args = overrideArgs ?? job.args;
|
|
1323
|
+
const record = this.packageRecord(job.actor, args.packageId);
|
|
1324
|
+
const keys = update ? [update.installation.source.memberKey] : Object.keys(record.data.members).sort();
|
|
1325
|
+
const binding = args.memberInstallId ? await this.step(job, () => this.memberInstall(job.actor, args.memberInstallId)) : undefined;
|
|
1326
|
+
let finalDeclaration;
|
|
1327
|
+
let contextMembers;
|
|
1328
|
+
if (binding) {
|
|
1329
|
+
if (args.installMode !== 'create' || keys.length !== 1 || !binding.release
|
|
1330
|
+
|| record.provenance.memberInstallId !== binding.memberInstallId
|
|
1331
|
+
|| templateFingerprint(record.provenance.release) !== templateFingerprint(binding.release)
|
|
1332
|
+
|| record.data.digest !== binding.release.digest || keys[0] !== binding.release.sourceMemberKey) {
|
|
1333
|
+
throw templateError('INTEGRITY_FAILED', 'Optional preview requires the original catalog download receipt');
|
|
1334
|
+
}
|
|
1335
|
+
finalDeclaration = publicTemplate.mergeMemberDefaults(binding.declaration, record.data.members[keys[0]]);
|
|
1336
|
+
const team = this.jobs.readTeam(binding.instanceId);
|
|
1337
|
+
contextMembers = Object.fromEntries(team.members.filter(member => member.aid).map(member => [member.key,
|
|
1338
|
+
{ aid: member.aid, projectPath: member.projectPath }]));
|
|
1339
|
+
}
|
|
1340
|
+
if (keys.join() !== Object.keys(args.members).sort().join()
|
|
1341
|
+
|| args.installMode === 'overwrite' && keys.length !== 1)
|
|
493
1342
|
throw templateError('INVALID_ARGUMENT', 'Map every member; overwrite allows one');
|
|
494
1343
|
const previewId = 'preview_' + randomUUID();
|
|
495
1344
|
const out = path.join(this.cache, 'previews', previewId);
|
|
496
1345
|
const members = {};
|
|
497
1346
|
const targets = {};
|
|
498
1347
|
const snapshot = this.deps.installation.hostSnapshot();
|
|
1348
|
+
const projectKey = (project) => process.platform === 'win32' ? project.toLowerCase() : project;
|
|
1349
|
+
// Explicit selections reserve their names before automatic allocation, including later members.
|
|
1350
|
+
const selectedProjects = new Set(Object.values(args.members).flatMap((selected) => typeof selected.target.project === 'string' && path.isAbsolute(selected.target.project)
|
|
1351
|
+
? [projectKey(path.resolve(selected.target.project))] : []));
|
|
499
1352
|
for (const key of keys) {
|
|
500
|
-
const selected =
|
|
1353
|
+
const selected = args.members[key];
|
|
501
1354
|
const target = selected.target;
|
|
502
|
-
const aid = target.aid === 'auto' ? 'a' + randomUUID().replace(/-/g, '').slice(0, 14) + '.' +
|
|
503
|
-
|
|
504
|
-
|
|
1355
|
+
const aid = target.aid === 'auto' ? 'a' + randomUUID().replace(/-/g, '').slice(0, 14) + '.' + args.issuer : target.aid;
|
|
1356
|
+
let project = target.project;
|
|
1357
|
+
if (args.installMode === 'create') {
|
|
1358
|
+
try {
|
|
1359
|
+
if (project === undefined) {
|
|
1360
|
+
const root = agentProjectRootFromDefaults(snapshot.defaults, this.deps.root);
|
|
1361
|
+
project = deriveAgentProjectPath(root, aid, {
|
|
1362
|
+
existsSync: candidate => fs.existsSync(candidate) || selectedProjects.has(projectKey(candidate)),
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
if (typeof project !== 'string' || !project.trim() || project.includes('\0') || !path.isAbsolute(project)) {
|
|
1366
|
+
throw templateError('INVALID_ARGUMENT', 'Project directory must be an absolute path on the target host');
|
|
1367
|
+
}
|
|
1368
|
+
project = path.resolve(project);
|
|
1369
|
+
this.deps.installation.available(aid, project);
|
|
1370
|
+
selectedProjects.add(projectKey(project));
|
|
1371
|
+
}
|
|
1372
|
+
catch (error) {
|
|
1373
|
+
throw templateError(error.code ?? 'INVALID_ARGUMENT', `Member ${key} project directory: ${error.message}`, { memberKey: key, stage: 'resolve_project', field: `args.members.${key}.target.project`,
|
|
1374
|
+
...(error.details ? { cause: error.details } : {}) });
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
505
1377
|
else {
|
|
506
1378
|
await this.step(job, () => this.deps.authorize(job.actor, aid));
|
|
507
1379
|
targets[key] = await this.step(job, () => this.deps.target(aid, job.actor));
|
|
1380
|
+
if (targets[key].targetConfig?.update?.mode === 'disabled')
|
|
1381
|
+
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before overwrite');
|
|
1382
|
+
if (!update && this.jobs.installation(aid))
|
|
1383
|
+
throw templateError('USE_UPDATE_PREVIEW', 'Bound Agents require the fixed-candidate update preview');
|
|
508
1384
|
if (targets[key].projectPath !== target.project)
|
|
509
1385
|
throw templateError('TARGET_CHANGED', 'Overwrite must use the current default project');
|
|
510
1386
|
}
|
|
511
|
-
members[key] = { aid, projectPath: path.resolve(
|
|
1387
|
+
members[key] = { aid, projectPath: path.resolve(project), requestId: randomUUID() };
|
|
1388
|
+
}
|
|
1389
|
+
if (update) {
|
|
1390
|
+
const targetAid = update.installation.targetAid;
|
|
1391
|
+
const team = this.jobs.listTeams().find(value => value.members.some(member => member.aid === targetAid));
|
|
1392
|
+
contextMembers = Object.fromEntries((team?.members ?? []).filter(member => member.aid && member.aid !== targetAid)
|
|
1393
|
+
.map(member => [member.key, { aid: member.aid, projectPath: member.projectPath }]));
|
|
1394
|
+
for (const other of this.deps.updates.targets().filter(value => value.aid !== targetAid)) {
|
|
1395
|
+
const project = update.installation.projectPath;
|
|
1396
|
+
if (other.projectPath === project || other.projectPath.startsWith(project + path.sep) || project.startsWith(other.projectPath + path.sep)) {
|
|
1397
|
+
throw templateError('SHARED_RESOURCE_CONFLICT', 'The target workspace is shared with another Agent', { affectedAids: [other.aid] });
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
512
1400
|
}
|
|
513
1401
|
const values = Object.values(members);
|
|
1402
|
+
const identityAids = new Set([job.actor, this.deps.hostAid, ...values.map(member => member.aid),
|
|
1403
|
+
...Object.values(contextMembers ?? {}).map((member) => member.aid)]);
|
|
1404
|
+
if (record.data.memberReferences?.external?.some((contact) => identityAids.has(contact.aid))) {
|
|
1405
|
+
throw templateError('CONFLICT', 'External AID conflicts with a Team identity');
|
|
1406
|
+
}
|
|
514
1407
|
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)
|
|
515
1408
|
|| right.projectPath.startsWith(left.projectPath + path.sep)))))
|
|
516
1409
|
throw templateError('INVALID_ARGUMENT', 'Targets or projects overlap');
|
|
517
1410
|
const data = await this.executeTool(job, 'preview', { archivePath: record.data.file, digest: record.data.digest,
|
|
518
|
-
installMode:
|
|
1411
|
+
installMode: args.installMode, members, targets, selections: args.members,
|
|
519
1412
|
out, home: this.deps.root, ownerAid: job.actor, hostAid: this.deps.hostAid,
|
|
1413
|
+
...(binding ? { memberDefaults: { [keys[0]]: binding.declaration }, contextMembers } : {}),
|
|
1414
|
+
...(update ? { sourceMemberKey: keys[0], contextMembers, update: { installation: update.installation,
|
|
1415
|
+
resolutions: job.args.resolutions, approvals: job.args.approvals,
|
|
1416
|
+
otherAgents: this.deps.updates.targets().filter(target => target.aid !== update.installation.targetAid).map(target => target.aid) } } : {}),
|
|
520
1417
|
agentSchemaVersion: snapshot.schemaVersion, providers: snapshot.providers });
|
|
521
1418
|
const plans = {};
|
|
522
|
-
const unresolved = [];
|
|
1419
|
+
const unresolved = [...(data.update?.unresolved ?? [])];
|
|
523
1420
|
for (const key of keys) {
|
|
524
1421
|
const config = data.configs[key];
|
|
525
1422
|
const baseagent = config.active_baseagent;
|
|
@@ -527,7 +1424,7 @@ export class AgentTemplateService {
|
|
|
527
1424
|
const profile = data.profiles[key];
|
|
528
1425
|
try {
|
|
529
1426
|
await this.step(job, () => this.deps.validateModels(config, data.members.find((member) => member.key === key).providers));
|
|
530
|
-
if (
|
|
1427
|
+
if (args.installMode === 'create') {
|
|
531
1428
|
const plan = { aid: members[key].aid, project: members[key].projectPath, baseagent,
|
|
532
1429
|
provider: model?.provider, model: model?.model, effort: model?.effort, chatmode: config.chatmode,
|
|
533
1430
|
ownerAid: job.actor, name: profile.name, description: profile.description || 'EvolCore template member.',
|
|
@@ -540,9 +1437,31 @@ export class AgentTemplateService {
|
|
|
540
1437
|
unresolved.push({ memberKey: key, code: error.code ?? 'UNRESOLVED', message: error.message });
|
|
541
1438
|
}
|
|
542
1439
|
}
|
|
1440
|
+
if (binding) {
|
|
1441
|
+
const plan = JSON.parse(fs.readFileSync(data.planFile, 'utf8'));
|
|
1442
|
+
plan.memberInstall = { memberInstallId: binding.memberInstallId, instanceId: binding.instanceId, memberKey: binding.memberKey,
|
|
1443
|
+
sourceMemberKey: keys[0], ownerAid: binding.ownerAid, hostAid: binding.hostAid,
|
|
1444
|
+
agentTemplateId: binding.release.agentTemplateId, releaseId: binding.release.releaseId, digest: binding.release.digest,
|
|
1445
|
+
finalProfile: data.profiles[keys[0]], finalAccess: data.configs[keys[0]].access ?? null };
|
|
1446
|
+
writeTemplateState(data.planFile, plan);
|
|
1447
|
+
}
|
|
1448
|
+
let updateRecord;
|
|
1449
|
+
if (update) {
|
|
1450
|
+
const team = this.jobs.listTeams().find(value => value.members.some(member => member.aid === update.installation.targetAid));
|
|
1451
|
+
const teamMember = team?.members.find(member => member.aid === update.installation.targetAid);
|
|
1452
|
+
updateRecord = { installation: update.installation, release: update.release, lock: update.lock,
|
|
1453
|
+
mode: (await this.updateAuthority(update.installation.targetAid, job.actor)).mode ?? null,
|
|
1454
|
+
nextInstallation: { ...update.installation, release: update.release, baseline: data.update.baseline,
|
|
1455
|
+
...(team && teamMember ? { teamBaseline: { instanceId: team.instanceId, memberKey: teamMember.key, diverged: true } } : {}) } };
|
|
1456
|
+
const plan = JSON.parse(fs.readFileSync(data.planFile, 'utf8'));
|
|
1457
|
+
plan.update = updateRecord;
|
|
1458
|
+
writeTemplateState(data.planFile, plan);
|
|
1459
|
+
}
|
|
543
1460
|
const planDigest = unresolved.length ? null : 'sha256:' + templateFingerprint(JSON.parse(fs.readFileSync(data.planFile, 'utf8')));
|
|
544
1461
|
const preview = { actor: job.actor, previewId, packageId: record.packageId, createdAt: Date.now(),
|
|
545
|
-
installMode:
|
|
1462
|
+
installMode: args.installMode, snapshot: templateFingerprint(snapshot), members, plans, planDigest, data,
|
|
1463
|
+
...(updateRecord ? { update: updateRecord } : {}),
|
|
1464
|
+
...(binding ? { memberInstall: binding, finalDeclaration } : {}) };
|
|
546
1465
|
writeTemplateState(path.join(out, 'record.json'), preview);
|
|
547
1466
|
job.result = { previewId, planDigest, packageId: record.packageId, digest: record.data.digest, metadata: record.data.metadata,
|
|
548
1467
|
installMode: preview.installMode, members: Object.fromEntries(keys.map(key => [key, {
|
|
@@ -550,11 +1469,83 @@ export class AgentTemplateService {
|
|
|
550
1469
|
}])),
|
|
551
1470
|
bindingOwnerAid: job.actor, expiresAt: preview.createdAt + 3600_000, executable: !unresolved.length, unresolved,
|
|
552
1471
|
changes: data.changes ?? [], ignored: data.ignored ?? [], warnings: data.warnings ?? [] };
|
|
1472
|
+
if (binding)
|
|
1473
|
+
Object.assign(job.result, { memberInstallId: binding.memberInstallId, instanceId: binding.instanceId,
|
|
1474
|
+
memberKey: binding.memberKey, sourceMemberKey: keys[0], release: binding.release,
|
|
1475
|
+
finalProfile: data.profiles[keys[0]], finalAccess: data.configs[keys[0]].access ?? null });
|
|
1476
|
+
if (update)
|
|
1477
|
+
Object.assign(job.result, { targetAid: update.installation.targetAid, candidate: update.release,
|
|
1478
|
+
baselineKnown: data.update.baselineKnown, changes: data.update.changes, conflicts: data.update.conflicts,
|
|
1479
|
+
requiredApprovals: data.update.requiredApprovals });
|
|
553
1480
|
job.status = 'succeeded';
|
|
554
1481
|
job.phase = 'completed';
|
|
555
1482
|
this.jobs.save(job);
|
|
556
1483
|
}
|
|
557
1484
|
async deploy(actor, requestId, args) {
|
|
1485
|
+
const record = this.previewRecord(args.previewId);
|
|
1486
|
+
if (record.installMode === 'overwrite') {
|
|
1487
|
+
const aid = Object.values(record.members)[0];
|
|
1488
|
+
return withFileLock(path.join(this.cache, 'update-targets', templateFingerprint(aid.aid) + '.lock'), () => this.acceptDeployment(actor, requestId, args, record));
|
|
1489
|
+
}
|
|
1490
|
+
if (record.memberInstall) {
|
|
1491
|
+
await this.memberInstall(actor, record.memberInstall.memberInstallId);
|
|
1492
|
+
return this.jobs.withTeams(() => this.acceptDeployment(actor, requestId, args, record));
|
|
1493
|
+
}
|
|
1494
|
+
return this.acceptDeployment(actor, requestId, args, record);
|
|
1495
|
+
}
|
|
1496
|
+
async acceptDeployment(actor, requestId, args, record) {
|
|
1497
|
+
if (record.actor !== actor)
|
|
1498
|
+
throw templateError('NOT_ALLOWED', 'Preview belongs to another principal');
|
|
1499
|
+
if (!record.planDigest || record.planDigest !== args.planDigest)
|
|
1500
|
+
throw templateError('CONFLICT', 'Executable preview and matching planDigest required');
|
|
1501
|
+
const binding = record.memberInstall;
|
|
1502
|
+
let team;
|
|
1503
|
+
let slot;
|
|
1504
|
+
if (binding) {
|
|
1505
|
+
team = this.jobs.readTeam(binding.instanceId);
|
|
1506
|
+
slot = team.members.find(member => member.key === binding.memberKey);
|
|
1507
|
+
if (team.ownerAid !== actor || team.hostAid !== this.deps.hostAid || !slot?.optional
|
|
1508
|
+
|| slot.agentTemplateId !== binding.declaration.agentTemplateId)
|
|
1509
|
+
throw templateError('CONFLICT', 'Original Team binding changed');
|
|
1510
|
+
// Recover even if the process stopped after the job write but before the slot write.
|
|
1511
|
+
const prior = slot.installation ? this.jobs.read(slot.installation.jobId) : this.jobs.list().find(candidate => {
|
|
1512
|
+
if (candidate.action !== 'deploy' || candidate.actor !== actor)
|
|
1513
|
+
return false;
|
|
1514
|
+
const file = TEMPLATE_PREVIEW_ID.test(candidate.args.previewId ?? '')
|
|
1515
|
+
? path.join(this.cache, 'previews', candidate.args.previewId, 'record.json') : '';
|
|
1516
|
+
if (!file || !fs.existsSync(file))
|
|
1517
|
+
return false;
|
|
1518
|
+
const original = this.previewRecord(candidate.args.previewId).memberInstall;
|
|
1519
|
+
return original?.instanceId === binding.instanceId && original.memberKey === binding.memberKey;
|
|
1520
|
+
});
|
|
1521
|
+
if (prior) {
|
|
1522
|
+
const original = this.previewRecord(prior.args.previewId).memberInstall;
|
|
1523
|
+
if (!slot.installation) {
|
|
1524
|
+
slot.installation = { jobId: prior.jobId, memberInstallId: original.memberInstallId,
|
|
1525
|
+
sourceMemberKey: original.release.sourceMemberKey, release: original.release };
|
|
1526
|
+
slot.state = 'reserved';
|
|
1527
|
+
this.jobs.saveTeam(team, team.revision);
|
|
1528
|
+
}
|
|
1529
|
+
this.jobs.bindRequest(actor, requestId, 'deploy', args, prior.jobId);
|
|
1530
|
+
if (prior.status === 'queued' && !prior.checkpoint.memberInstall) {
|
|
1531
|
+
prior.checkpoint.memberInstall = structuredClone(original);
|
|
1532
|
+
prior.resumable = true;
|
|
1533
|
+
this.jobs.save(prior);
|
|
1534
|
+
try {
|
|
1535
|
+
this.jobs.associate(prior);
|
|
1536
|
+
this.launch(prior, job => this.runInstallation(job));
|
|
1537
|
+
}
|
|
1538
|
+
catch (error) {
|
|
1539
|
+
prior.status = 'paused';
|
|
1540
|
+
prior.error = { code: error.code ?? 'RECOVERY_REQUIRED', message: error.message, retryable: true };
|
|
1541
|
+
this.jobs.save(prior);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
return this.view(prior);
|
|
1545
|
+
}
|
|
1546
|
+
if (slot.aid || slot.state !== 'available')
|
|
1547
|
+
throw templateError('CONFLICT', 'Optional slot is occupied');
|
|
1548
|
+
}
|
|
558
1549
|
const prior = this.jobs.list().find(job => job.actor === actor && job.action === 'deploy' && job.args.previewId === args.previewId);
|
|
559
1550
|
if (prior) {
|
|
560
1551
|
if (prior.fingerprint !== templateFingerprint({ action: 'deploy', args }))
|
|
@@ -562,16 +1553,35 @@ export class AgentTemplateService {
|
|
|
562
1553
|
this.jobs.bindRequest(actor, requestId, 'deploy', args, prior.jobId);
|
|
563
1554
|
return this.view(prior);
|
|
564
1555
|
}
|
|
565
|
-
const record = this.previewRecord(args.previewId);
|
|
566
|
-
if (record.actor !== actor)
|
|
567
|
-
throw templateError('NOT_ALLOWED', 'Preview belongs to another principal');
|
|
568
|
-
if (!record.planDigest || record.planDigest !== args.planDigest)
|
|
569
|
-
throw templateError('CONFLICT', 'Executable preview and matching planDigest required');
|
|
570
1556
|
if (record.createdAt + 3600_000 <= Date.now())
|
|
571
1557
|
throw templateError('EXPIRED', 'Preview expired');
|
|
572
1558
|
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
573
1559
|
throw templateError('TARGET_CHANGED', 'Host configuration changed');
|
|
1560
|
+
if (record.installMode === 'overwrite') {
|
|
1561
|
+
const aid = Object.values(record.members)[0].aid;
|
|
1562
|
+
const active = this.jobs.list().find(job => job.action === 'deploy' && !job.committed && !job.checkpoint.restored
|
|
1563
|
+
&& Object.values(job.members).some(member => member.aid === aid));
|
|
1564
|
+
if (active)
|
|
1565
|
+
throw templateError('CONFLICT', 'Resume the original target job', { jobId: active.jobId });
|
|
1566
|
+
if (record.update)
|
|
1567
|
+
await this.verifyUpdatePreview(actor, record);
|
|
1568
|
+
else {
|
|
1569
|
+
await this.deps.authorize(actor, aid);
|
|
1570
|
+
const target = await this.deps.target(aid, actor);
|
|
1571
|
+
if (target.targetConfig?.update?.mode === 'disabled')
|
|
1572
|
+
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before overwrite');
|
|
1573
|
+
if (this.jobs.installation(aid))
|
|
1574
|
+
throw templateError('USE_UPDATE_PREVIEW', 'Bound Agents require the fixed-candidate update preview');
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
574
1577
|
const accepted = this.jobs.accept(actor, requestId, 'deploy', args, structuredClone(record.members));
|
|
1578
|
+
if (binding) {
|
|
1579
|
+
accepted.job.checkpoint.memberInstall = structuredClone(binding);
|
|
1580
|
+
slot.installation = { jobId: accepted.job.jobId, memberInstallId: binding.memberInstallId,
|
|
1581
|
+
sourceMemberKey: binding.release.sourceMemberKey, release: structuredClone(binding.release) };
|
|
1582
|
+
slot.state = 'reserved';
|
|
1583
|
+
this.jobs.saveTeam(team, team.revision);
|
|
1584
|
+
}
|
|
575
1585
|
accepted.job.resumable = true;
|
|
576
1586
|
this.jobs.save(accepted.job);
|
|
577
1587
|
try {
|
|
@@ -592,7 +1602,7 @@ export class AgentTemplateService {
|
|
|
592
1602
|
this.mutations = new Promise(resolve => { release = resolve; });
|
|
593
1603
|
await previous.catch(() => undefined);
|
|
594
1604
|
try {
|
|
595
|
-
await this.install(job);
|
|
1605
|
+
await withFileLock(path.join(this.cache, 'jobs', job.jobId + '.execution.lock'), () => this.install(job));
|
|
596
1606
|
}
|
|
597
1607
|
finally {
|
|
598
1608
|
release();
|
|
@@ -603,6 +1613,18 @@ export class AgentTemplateService {
|
|
|
603
1613
|
const record = JSON.parse(fs.readFileSync(path.join(this.cache, 'previews', job.args.previewId, 'record.json'), 'utf8'));
|
|
604
1614
|
if (record.installMode === 'overwrite')
|
|
605
1615
|
return this.runOverwrite(job, record);
|
|
1616
|
+
if (record.memberInstall) {
|
|
1617
|
+
const binding = await this.memberInstall(job.actor, record.memberInstall.memberInstallId);
|
|
1618
|
+
if (templateFingerprint(binding) !== templateFingerprint(record.memberInstall))
|
|
1619
|
+
throw templateError('CONFLICT', 'Frozen member installation changed');
|
|
1620
|
+
job.checkpoint.memberInstall = structuredClone(binding);
|
|
1621
|
+
this.jobs.save(job);
|
|
1622
|
+
await this.updateTeamMember(binding.instanceId, binding.memberKey, member => {
|
|
1623
|
+
if (member.installation?.jobId !== job.jobId)
|
|
1624
|
+
throw templateError('CONFLICT', 'Slot is reserved by another job');
|
|
1625
|
+
member.state = 'creating';
|
|
1626
|
+
});
|
|
1627
|
+
}
|
|
606
1628
|
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
607
1629
|
throw templateError('CONFLICT', 'Host configuration changed; team remains paused');
|
|
608
1630
|
const plan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
@@ -706,10 +1728,11 @@ export class AgentTemplateService {
|
|
|
706
1728
|
await this.step(job, () => this.deps.installation.authorize(job.actor));
|
|
707
1729
|
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
708
1730
|
throw templateError('CONFLICT', 'Host configuration changed before team commit');
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
1731
|
+
if (!record.memberInstall)
|
|
1732
|
+
writeTemplateState(path.join(this.cache, 'teams', job.jobId, 'team-members.json'), {
|
|
1733
|
+
version: 1, jobId: job.jobId, ownerAid: job.actor, hostAid: this.deps.hostAid,
|
|
1734
|
+
members: Object.entries(job.members).map(([key, member]) => ({ key, aid: member.aid, project: member.projectPath, profile: record.data.profiles[key] })),
|
|
1735
|
+
});
|
|
713
1736
|
job.committed = true;
|
|
714
1737
|
job.activating = false;
|
|
715
1738
|
job.status = 'succeeded';
|
|
@@ -719,9 +1742,38 @@ export class AgentTemplateService {
|
|
|
719
1742
|
installMode: record.installMode, committed: true, members: Object.fromEntries(Object.entries(job.members)
|
|
720
1743
|
.map(([key, member]) => [key, { aid: member.aid, project: member.projectPath }])) };
|
|
721
1744
|
this.jobs.save(job);
|
|
1745
|
+
if (record.memberInstall) {
|
|
1746
|
+
await this.attachCommittedMember(job);
|
|
1747
|
+
await this.resumeMemberJoin(job.actor, record.memberInstall.instanceId, record.memberInstall.memberKey);
|
|
1748
|
+
}
|
|
1749
|
+
else
|
|
1750
|
+
await this.recordCreatedTeam(job, record);
|
|
722
1751
|
for (const member of Object.values(job.members))
|
|
723
1752
|
await this.completeRecovery(member.aid);
|
|
724
1753
|
}
|
|
1754
|
+
async recordCreatedTeam(job, record) {
|
|
1755
|
+
const instanceId = 'team_' + templateFingerprint({ teamId: job.jobId, ownerAid: job.actor, hostAid: this.deps.hostAid });
|
|
1756
|
+
await this.jobs.withTeams(async () => {
|
|
1757
|
+
if (fs.existsSync(this.jobs.teamFile(instanceId)))
|
|
1758
|
+
return;
|
|
1759
|
+
const references = record.data.memberReferences ?? { optional: [], external: [] };
|
|
1760
|
+
const members = Object.entries(job.members).map(([key, member]) => ({
|
|
1761
|
+
key, aid: member.aid, projectPath: member.projectPath, profile: record.data.profiles[key], state: 'joined',
|
|
1762
|
+
...(record.data.configs[key].access === undefined ? {} : { config: { access: record.data.configs[key].access } }),
|
|
1763
|
+
}));
|
|
1764
|
+
const identityAids = new Set([job.actor, this.deps.hostAid, ...members.map(member => member.aid)]);
|
|
1765
|
+
if (references.external.some((contact) => identityAids.has(contact.aid)))
|
|
1766
|
+
throw templateError('CONFLICT', 'External AID conflicts with a Team identity');
|
|
1767
|
+
members.push(...references.optional.map((member) => ({ ...member, state: 'available' })));
|
|
1768
|
+
const team = { version: 1, instanceId, teamId: job.jobId, ownerAid: job.actor,
|
|
1769
|
+
hostAid: this.deps.hostAid, deliveryDigest: record.data.digest, sources: ['template'], assistantKey: record.data.assistantKey ?? Object.keys(job.members)[0],
|
|
1770
|
+
members, externalContacts: references.external, relationshipTargets: Object.entries(job.members)
|
|
1771
|
+
.filter(([key]) => record.data.configs[key].team?.some((aid) => identityAids.has(aid))).map(([, member]) => member.aid),
|
|
1772
|
+
revision: '', createdAt: Date.now(), updatedAt: Date.now() };
|
|
1773
|
+
this.jobs.saveTeam(team);
|
|
1774
|
+
});
|
|
1775
|
+
return instanceId;
|
|
1776
|
+
}
|
|
725
1777
|
async publishProfile(job, key, profile, legacyRecovery) {
|
|
726
1778
|
const member = job.members[key];
|
|
727
1779
|
const digest = (value) => templateFingerprint(Object.fromEntries(['name', 'description', 'avatar', 'tags', 'exttype'].filter(field => value[field] !== undefined).map(field => [field, value[field]])));
|
|
@@ -756,12 +1808,45 @@ export class AgentTemplateService {
|
|
|
756
1808
|
publication.confirmedVersion = confirmed.profileVersion;
|
|
757
1809
|
this.jobs.save(job);
|
|
758
1810
|
}
|
|
1811
|
+
async verifyUpdatePreview(actor, record, recoveryJobId) {
|
|
1812
|
+
const update = record.update;
|
|
1813
|
+
const context = await this.updateAuthority(update.installation.targetAid, actor, recoveryJobId);
|
|
1814
|
+
const installed = this.installed(update.installation.targetAid, actor, context.projectPath);
|
|
1815
|
+
if (templateFingerprint(installed) !== templateFingerprint(update.installation) || (context.mode ?? null) !== update.mode
|
|
1816
|
+
|| templateFingerprint(this.snapshot(this.jobs.installationFile(update.installation.targetAid))) !== templateFingerprint(update.lock)) {
|
|
1817
|
+
throw templateError('SOURCE_CHANGED', 'Owner, source, policy or installed lock changed since preview');
|
|
1818
|
+
}
|
|
1819
|
+
const release = await this.fixedRelease(installed.source, update.release.releaseId, 'execute:' + randomUUID());
|
|
1820
|
+
if (templateFingerprint(release) !== templateFingerprint(update.release))
|
|
1821
|
+
throw templateError('SOURCE_CHANGED', 'Frozen release changed or was withdrawn');
|
|
1822
|
+
const plan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
1823
|
+
if (templateFingerprint(plan.update) !== templateFingerprint(update)
|
|
1824
|
+
|| templateFingerprint(Object.fromEntries(plan.members.map((member) => [member.key, member.profile]))) !== templateFingerprint(record.data.profiles)) {
|
|
1825
|
+
throw templateError('CONFLICT', 'Frozen update source, plan or profile differs from its digest');
|
|
1826
|
+
}
|
|
1827
|
+
const profile = await this.deps.readProfile(update.installation.targetAid);
|
|
1828
|
+
const recoveredVersion = recoveryJobId ? this.jobs.read(recoveryJobId).checkpoint.restoredProfileVersion : undefined;
|
|
1829
|
+
if (profile.profileVersion !== (recoveredVersion ?? plan.members[0].profileVersion)
|
|
1830
|
+
|| templateFingerprint(profile.profile) !== templateFingerprint(plan.members[0].originalProfile)) {
|
|
1831
|
+
throw templateError('TARGET_CHANGED', 'Target profile changed since the confirmed preview');
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
759
1834
|
async runOverwrite(job, record) {
|
|
760
1835
|
const member = Object.values(job.members)[0];
|
|
761
1836
|
const key = Object.keys(job.members)[0];
|
|
762
1837
|
const release = await this.deps.hold(member.aid, job.jobId);
|
|
763
1838
|
let authorized = false;
|
|
764
1839
|
try {
|
|
1840
|
+
if (!job.checkpoint.executionConfirmedAt && record.createdAt + 3600_000 <= Date.now())
|
|
1841
|
+
throw templateError('EXPIRED', 'Confirmed preview expired before target work began');
|
|
1842
|
+
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
1843
|
+
throw templateError('TARGET_CHANGED', 'Host configuration changed');
|
|
1844
|
+
const frozenPlan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
1845
|
+
if (record.planDigest !== 'sha256:' + templateFingerprint(frozenPlan))
|
|
1846
|
+
throw templateError('CONFLICT', 'Frozen overwrite plan changed');
|
|
1847
|
+
for (const [key, config] of Object.entries(record.data.configs)) {
|
|
1848
|
+
await this.step(job, () => this.deps.validateModels(config, record.data.members.find((value) => value.key === key).providers));
|
|
1849
|
+
}
|
|
765
1850
|
await this.step(job, () => this.deps.authorize(job.actor, member.aid, job.jobId));
|
|
766
1851
|
authorized = true;
|
|
767
1852
|
if (job.checkpoint.backupDir && !job.checkpoint.restored)
|
|
@@ -775,20 +1860,47 @@ export class AgentTemplateService {
|
|
|
775
1860
|
const current = await this.step(job, () => this.deps.target(member.aid, job.actor));
|
|
776
1861
|
if (current.projectPath !== member.projectPath)
|
|
777
1862
|
throw templateError('TARGET_CHANGED', 'Target project changed');
|
|
1863
|
+
if (current.targetConfig?.update?.mode === 'disabled')
|
|
1864
|
+
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before overwrite');
|
|
1865
|
+
if (record.update)
|
|
1866
|
+
await this.step(job, () => this.verifyUpdatePreview(job.actor, record, job.jobId));
|
|
1867
|
+
else if (this.jobs.installation(member.aid))
|
|
1868
|
+
throw templateError('USE_UPDATE_PREVIEW', 'Bound Agents require the fixed-candidate update preview');
|
|
778
1869
|
job.checkpoint.runtimeStopped ??= current.runtimeStatus === 'stopped';
|
|
779
1870
|
job.checkpoint.runtimeInactive ??= current.targetConfig?.enabled === false || current.runtimeStatus === 'stopped';
|
|
1871
|
+
job.checkpoint.executionConfirmedAt ??= Date.now();
|
|
1872
|
+
this.jobs.save(job);
|
|
780
1873
|
await this.executeTool(job, 'overlay', { operation: 'verify', planFile: record.data.planFile });
|
|
1874
|
+
let planFile = record.data.planFile;
|
|
1875
|
+
if (record.update) {
|
|
1876
|
+
const plan = JSON.parse(fs.readFileSync(planFile, 'utf8'));
|
|
1877
|
+
const installation = { ...record.update.nextInstallation, committedJobId: job.jobId };
|
|
1878
|
+
const lock = { schemaVersion: 2, installation: record.update.installation, pending: { jobId: job.jobId, installation } };
|
|
1879
|
+
plan.writes.push({ path: this.jobs.installationFile(member.aid), content: Buffer.from(JSON.stringify(lock, null, 2) + '\n').toString('base64'),
|
|
1880
|
+
mode: 0o600, expected: record.update.lock });
|
|
1881
|
+
planFile = path.join(this.cache, 'previews', record.previewId, 'execution-' + job.jobId + '.json');
|
|
1882
|
+
writeTemplateState(planFile, plan);
|
|
1883
|
+
}
|
|
781
1884
|
const original = await this.step(job, () => this.deps.readProfile(member.aid));
|
|
782
1885
|
job.checkpoint.originalProfile = original;
|
|
783
1886
|
job.checkpoint.backupDir = path.join(this.cache, 'backups', job.jobId + '-' + job.attempt);
|
|
784
1887
|
job.checkpoint.installMode = 'overwrite';
|
|
785
1888
|
job.checkpoint.restored = false;
|
|
786
1889
|
this.jobs.save(job);
|
|
787
|
-
await this.executeTool(job, 'overlay', { planFile
|
|
1890
|
+
await this.executeTool(job, 'overlay', { planFile, backupDir: job.checkpoint.backupDir });
|
|
788
1891
|
job.checkpoint.resourcesApplied = true;
|
|
789
1892
|
this.jobs.save(job);
|
|
790
1893
|
await this.step(job, () => this.deps.reload(member.aid, job.jobId, job.checkpoint.runtimeStopped === true));
|
|
791
1894
|
await this.publishProfile(job, key, record.data.profiles[key], false);
|
|
1895
|
+
await this.executeTool(job, 'overlay', { operation: 'verify-applied', planFile });
|
|
1896
|
+
if (record.update) {
|
|
1897
|
+
const context = await this.step(job, () => this.updateAuthority(member.aid, job.actor, job.jobId));
|
|
1898
|
+
if ((context.mode ?? null) !== record.update.mode)
|
|
1899
|
+
throw templateError('SOURCE_CHANGED', 'Update policy changed before commit');
|
|
1900
|
+
const release = await this.step(job, () => this.fixedRelease(record.update.installation.source, record.update.release.releaseId, job.jobId + ':commit:' + job.attempt));
|
|
1901
|
+
if (templateFingerprint(release) !== templateFingerprint(record.update.release))
|
|
1902
|
+
throw templateError('SOURCE_CHANGED', 'Frozen release changed before commit');
|
|
1903
|
+
}
|
|
792
1904
|
job.activating = true;
|
|
793
1905
|
this.jobs.save(job);
|
|
794
1906
|
member.runtimeReady = this.deps.installation.ready(member.aid);
|
|
@@ -800,13 +1912,15 @@ export class AgentTemplateService {
|
|
|
800
1912
|
job.resumable = false;
|
|
801
1913
|
job.phase = 'completed';
|
|
802
1914
|
job.result = { packageId: record.packageId, previewId: record.previewId, planDigest: record.planDigest,
|
|
803
|
-
installMode: 'overwrite', committed: true, members: { [key]: { aid: member.aid, project: member.projectPath } }
|
|
1915
|
+
installMode: 'overwrite', committed: true, members: { [key]: { aid: member.aid, project: member.projectPath } },
|
|
1916
|
+
...(record.update ? { installedRelease: record.update.release,
|
|
1917
|
+
teamBaselineDiverged: record.update.nextInstallation.teamBaseline?.diverged ?? false } : {}) };
|
|
804
1918
|
this.jobs.save(job);
|
|
805
1919
|
await this.completeRecovery(member.aid);
|
|
806
1920
|
}
|
|
807
1921
|
catch (error) {
|
|
808
1922
|
const current = this.jobs.read(job.jobId);
|
|
809
|
-
if (authorized)
|
|
1923
|
+
if (authorized && !current.committed)
|
|
810
1924
|
await this.compensate(current);
|
|
811
1925
|
throw error;
|
|
812
1926
|
}
|
|
@@ -865,6 +1979,11 @@ export class AgentTemplateService {
|
|
|
865
1979
|
throw templateError('PROFILE_CONFLICT', 'Independent profile edit during rollback');
|
|
866
1980
|
await this.deps.publishProfile(member.aid, original.profile, current.profileVersion);
|
|
867
1981
|
}
|
|
1982
|
+
const confirmed = await this.deps.readProfile(member.aid);
|
|
1983
|
+
if (templateFingerprint(fields(confirmed.profile)) !== templateFingerprint(fields(original.profile))) {
|
|
1984
|
+
throw templateError('PROFILE_NOT_CONFIRMED', 'Original profile restoration is not confirmed');
|
|
1985
|
+
}
|
|
1986
|
+
job.checkpoint.restoredProfileVersion = confirmed.profileVersion;
|
|
868
1987
|
}
|
|
869
1988
|
await this.deps.reload(member.aid, job.jobId, job.checkpoint.runtimeStopped === true);
|
|
870
1989
|
job.checkpoint.restored = true;
|