evolcore 0.0.49 → 0.0.51
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 +103 -3
- package/bin/ec-build.mjs +60 -0
- package/bin/ecmsg.js +64 -57
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +173 -0
- package/dist/ability/caller/contract.js +117 -0
- package/dist/ability/caller/credential-files.js +132 -0
- package/dist/ability/caller/daemon.js +183 -0
- package/dist/ability/caller/schema-view.js +157 -0
- package/dist/ability/caller/service.js +519 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +156 -106
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +79 -3
- package/dist/agent-template/runtime.js +459 -47
- package/dist/agent-template/service.js +1242 -198
- package/dist/agent-template/share.js +103 -0
- package/dist/agent-template/tool-runner.js +25 -0
- package/dist/agent-template/types.js +10 -2
- package/dist/agents/claude/availability.js +94 -0
- package/dist/agents/claude/capability-provider.js +154 -0
- package/dist/agents/claude/index.js +145 -0
- package/dist/agents/{claude-runner.js → claude/runner.js} +78 -166
- package/dist/agents/claude/session-file-adapter.js +246 -0
- package/dist/agents/codex/app-server-client.js +90 -10
- package/dist/agents/codex/availability.js +164 -0
- package/dist/agents/codex/capability-provider.js +138 -0
- package/dist/agents/codex/cli.js +38 -0
- package/dist/agents/codex/index.js +345 -0
- package/dist/agents/codex/mcp-elicitation.js +135 -0
- package/dist/agents/{codex-runner.js → codex/runner.js} +652 -383
- package/dist/agents/codex/session-file-adapter.js +834 -0
- package/dist/agents/dsh/availability.js +28 -0
- package/dist/agents/dsh/capability-provider.js +56 -0
- package/dist/agents/dsh/desktop-locations.ps1 +66 -0
- package/dist/agents/dsh/desktop-probe.cjs +37 -0
- package/dist/agents/dsh/index.js +98 -0
- package/dist/agents/dsh/installation.js +400 -0
- package/dist/agents/dsh/resources.js +755 -0
- package/dist/agents/dsh/runner.js +1183 -0
- package/dist/agents/dsh/runtime/README.md +243 -0
- package/dist/agents/dsh/runtime/authorization.js +23 -0
- package/dist/agents/dsh/runtime/bridge.js +837 -0
- package/dist/agents/dsh/runtime/config.js +271 -0
- package/dist/agents/dsh/runtime/entry.js +229 -0
- package/dist/agents/dsh/runtime/session-inspector.js +340 -0
- package/dist/agents/dsh/runtime/tool-policy.js +49 -0
- package/dist/agents/dsh/session-file-adapter.js +145 -0
- package/dist/agents/ecagent/index.js +215 -0
- package/dist/agents/{ecagent-runner.js → ecagent/runner.js} +592 -106
- package/dist/agents/ecagent/session-file-adapter.js +134 -0
- package/dist/agents/gemini/index.js +96 -0
- package/dist/agents/{gemini-runner.js → gemini/runner.js} +18 -23
- package/dist/{core/session/adapters/gemini-session-file-adapter.js → agents/gemini/session-file-adapter.js} +2 -2
- package/dist/aun/ability-device-routing.js +11 -17
- package/dist/aun/aid/agentmd.js +27 -1
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/aid/managed-operation.js +6 -4
- package/dist/aun/group/invite-service.js +7 -37
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/menu/client.js +1 -1
- package/dist/aun/msg/history.js +1 -1
- package/dist/aun/msg/managed-operation.js +93 -21
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +32 -4
- package/dist/aun/msg/upload.js +126 -3
- package/dist/aun/service-proxy.js +1 -1
- package/dist/aun/storage/index.js +242 -0
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +698 -213
- package/dist/channels/daemon.js +3 -2
- package/dist/channels/dingtalk.js +1 -1
- package/dist/channels/feishu.js +9 -9
- package/dist/channels/qqbot.js +1 -1
- package/dist/channels/wechat.js +2 -2
- package/dist/channels/wecom.js +1 -1
- package/dist/claude-gateway/agent-registration.js +389 -0
- package/dist/claude-gateway/binding.js +96 -0
- package/dist/claude-gateway/inbox.js +138 -0
- package/dist/claude-gateway/index.js +125 -0
- package/dist/claude-gateway/listing.js +330 -0
- package/dist/claude-gateway/router.js +328 -0
- package/dist/claude-gateway/sessions.js +128 -0
- package/dist/claude-gateway/terminal.js +250 -0
- package/dist/claude-gateway/transcript.js +272 -0
- package/dist/claude-gateway/types.js +14 -0
- package/dist/cli/ability-command.js +45 -0
- package/dist/cli/ability-output.js +182 -0
- package/dist/cli/agent-command.js +21 -2
- package/dist/cli/agent-create.js +197 -56
- package/dist/cli/agent-template.js +400 -27
- package/dist/cli/agent.js +105 -11
- package/dist/cli/aun-commands.js +237 -123
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +283 -109
- package/dist/cli/data-command.js +1 -1
- package/dist/cli/debug-mode.js +9 -0
- package/dist/cli/directory.js +1 -2
- package/dist/cli/ecmsg-gateway.js +64 -26
- package/dist/cli/fs-command.js +67 -39
- package/dist/cli/index.js +45 -12
- package/dist/cli/init.js +161 -90
- package/dist/cli/managed-command-guard.js +3 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/model.js +1 -1
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/restart-monitor.js +4 -4
- package/dist/cli/services-command.js +35 -10
- package/dist/cli/skill-command.js +4 -4
- package/dist/cli/task-context.js +24 -14
- package/dist/cli/team-workspace-command.js +50 -52
- package/dist/cli/thread-command.js +81 -14
- package/dist/cli/trigger-command.js +47 -12
- package/dist/cli/watch-logs.js +2 -1
- package/dist/config/access-policy.js +16 -3
- package/dist/config/boot-log.js +3 -0
- package/dist/config/builtin-role-templates.js +1 -1
- package/dist/config/config-field-policy.js +26 -13
- package/dist/config/config-manager.js +113 -52
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +29 -44
- package/dist/config/invoke-ipc-service.js +1 -1
- package/dist/config/owner-config.js +5 -19
- package/dist/config/peer-book-store.js +2 -3
- package/dist/config/peer-book.js +2 -2
- package/dist/config/peer-role-resolver.js +3 -9
- package/dist/config/provider-identity-migration.js +24 -105
- package/dist/config/provider-ipc-service.js +13 -3
- package/dist/config/provider-local-sync.js +4 -1
- package/dist/config/provider-menu-request.js +21 -3
- package/dist/config/provider-templates.js +1 -1
- package/dist/config/providers-config.js +138 -31
- package/dist/config/providers-import.js +3 -3
- package/dist/config/providers-management.js +109 -118
- package/dist/config/resolved-config-op.js +1 -42
- package/dist/config/schema-migration.js +254 -15
- package/dist/config/schema-registry.js +53 -8
- package/dist/config-store.js +1343 -63
- package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +228 -9
- package/dist/core/{agent-create-status.js → agent/agent-create-status.js} +112 -4
- package/dist/core/{agent-creation-claim.js → agent/agent-creation-claim.js} +3 -3
- package/dist/core/{agent-ipc-registration.js → agent/agent-ipc-registration.js} +119 -25
- package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +65 -0
- package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +249 -79
- package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +23 -18
- package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
- package/dist/core/auth/agent-delegation.js +15 -8
- package/dist/core/auth/delegation-authorization.js +28 -0
- package/dist/core/auth/operation-authorizer.js +20 -2
- package/dist/core/auth/operation-catalog.js +80 -8
- package/dist/core/baseagent/baseagent-availability.js +197 -0
- package/dist/core/baseagent/baseagent-capability-adapter.js +288 -0
- package/dist/core/baseagent/baseagent-config-shared.js +56 -0
- package/dist/core/baseagent/baseagent-identity.js +68 -0
- package/dist/core/{baseagent-loader.js → baseagent/baseagent-loader.js} +89 -6
- package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
- package/dist/core/baseagent/baseagent-plugin-descriptor.js +357 -0
- package/dist/core/baseagent/baseagent-plugin-loader.js +367 -0
- package/dist/core/baseagent/baseagent.js +157 -0
- package/dist/{agents → core/baseagent}/runner-types.js +36 -4
- package/dist/core/capability/capability-manager.js +91 -33
- package/dist/core/capability/providers/claude-capability-provider.js +2 -154
- package/dist/core/capability/providers/codex-capability-provider.js +2 -136
- package/dist/core/{channel-loader.js → channel/channel-loader.js} +226 -38
- package/dist/core/{channel-runtime.js → channel/channel-runtime.js} +21 -19
- package/dist/core/command/agent-control.js +80 -17
- package/dist/core/command/agent-template-menu.js +23 -10
- package/dist/core/command/agentmd-menu-request.js +19 -8
- package/dist/core/command/agentmd-menu.js +14 -5
- package/dist/core/command/cli-intent-parser.js +15 -0
- package/dist/core/command/command-handler.js +127 -57
- package/dist/core/command/context-policy-menu.js +122 -0
- package/dist/core/command/data-root-resolver.js +157 -20
- package/dist/core/command/memory-slash.js +6 -6
- package/dist/core/command/menu-catalog.js +95 -19
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +392 -93
- package/dist/core/command/menu-protocol.js +47 -8
- package/dist/core/command/menu-query-batch.js +9 -5
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/provider-menu.js +7 -11
- package/dist/core/command/role-menu.js +1 -1
- package/dist/core/command/skill-slash.js +17 -5
- package/dist/core/command/slash-gate.js +2 -4
- package/dist/core/command/slash-handler.js +143 -121
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/team-workspace-team.js +3 -3
- package/dist/core/command/topic-slash.js +16 -10
- package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -18
- package/dist/core/{daemon-control.js → daemon/daemon-control.js} +48 -21
- package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +28 -20
- package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +10 -5
- package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +101 -37
- package/dist/core/{lifecycle-notice.js → daemon/lifecycle-notice.js} +4 -5
- package/dist/core/file-integrity/store.js +1 -1
- package/dist/core/handoff/ipc-registration.js +3 -3
- package/dist/core/handoff/runtime.js +2 -2
- package/dist/{agents → core/inference}/request-identity.js +2 -2
- package/dist/core/inference/text-inference.js +4 -4
- package/dist/core/{bootstrap-messages.js → initialization/bootstrap-messages.js} +10 -10
- package/dist/core/{bootstrap-service.js → initialization/bootstrap-service.js} +24 -23
- package/dist/core/initialization/service.js +57 -9
- package/dist/core/invoke/executors/media.js +1 -1
- package/dist/core/invoke/executors/text.js +1 -1
- package/dist/core/memory/consolidation-context.js +3 -2
- package/dist/core/memory/consolidation-trigger.js +9 -3
- package/dist/core/memory/consolidation.js +39 -68
- package/dist/core/memory/memory-admin.js +6 -6
- package/dist/core/memory/memory-writer.js +1 -1
- package/dist/core/memory/relation-idle-monitor.js +1 -1
- package/dist/core/message/aun-ipc-sender.js +204 -88
- package/dist/core/message/aun-request-registry.js +44 -5
- package/dist/core/message/auto-mention-gate.js +1 -1
- package/dist/core/message/contact-admission.js +1 -1
- package/dist/core/message/im-renderer.js +19 -0
- package/dist/core/{interaction-router.js → message/interaction-router.js} +131 -1
- package/dist/core/message/items-formatter.js +5 -5
- package/dist/core/message/message-admission.js +1 -1
- package/dist/core/message/message-bridge.js +239 -59
- package/dist/core/message/message-log.js +8 -0
- package/dist/core/message/message-queue.js +88 -7
- package/dist/core/message/message-utils.js +1 -1
- package/dist/core/message/peer-mode.js +16 -5
- package/dist/core/message/response-engine.js +351 -152
- package/dist/core/message/send-options.js +44 -7
- package/dist/core/message/send-routing.js +55 -115
- package/dist/core/message/stream-idle-monitor.js +1 -1
- package/dist/core/{data-migration.js → migration/data-migration.js} +29 -1
- package/dist/core/model/catalog-service.js +29 -8
- package/dist/core/model/model-capabilities.js +88 -0
- package/dist/core/model/model-catalog.js +18 -7
- package/dist/core/model/model-diagnostics.js +4 -4
- package/dist/core/ownership/owner-resolver.js +107 -101
- package/dist/core/{pack-auth.js → pack/pack-auth.js} +34 -3
- package/dist/core/{pack-install.js → pack/pack-install.js} +95 -17
- package/dist/core/permission/approval-gateway.js +9 -18
- package/dist/core/permission/ec-command-parser.js +242 -82
- package/dist/core/permission/managed-file.js +234 -0
- package/dist/core/permission/protected-paths.js +120 -9
- package/dist/core/permission/sandbox-runtime.js +267 -3
- package/dist/core/permission/services-path-acl.js +9 -2
- package/dist/core/permission/session-path-grants.js +1 -1
- package/dist/core/permission/shell-environment.js +15 -1
- package/dist/core/permission/tool-policy.js +21 -9
- package/dist/core/plugin/plugin-lifecycle.js +442 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +2 -242
- package/dist/core/session/adapters/codex-session-file-adapter.js +2 -562
- package/dist/core/session/adapters/ecagent-session-file-adapter.js +2 -134
- package/dist/core/{background-session → session/background}/session-cleanup.js +2 -2
- package/dist/core/{background-session → session/background}/types.js +1 -1
- package/dist/core/session/session-file-health.js +2 -272
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +76 -12
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/session/session-terminal.js +185 -0
- package/dist/core/session/session-title.js +8 -11
- package/dist/core/{system-session → session/system}/memory.js +43 -9
- package/dist/core/{system-session → session/system}/registry.js +1 -1
- package/dist/core/{system-session → session/system}/types.js +1 -1
- package/dist/core/skill/index-generator.js +3 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/task/task-activity-store.js +112 -0
- package/dist/core/task/task-recovery-service.js +2 -2
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +6 -4
- package/dist/core/thread/thread-operation.js +27 -11
- package/dist/core/thread/thread-route.js +5 -3
- package/dist/core/thread/thread-service.js +307 -58
- package/dist/core/thread/topic-id.js +52 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/directory/{owner-directory-admission.js → admission.js} +3 -3
- package/dist/directory/{owner-directory-cache.js → cache.js} +90 -8
- package/dist/directory/{owner-directory-markdown.js → markdown.js} +2 -2
- package/dist/directory/{owner-directory-query-operation.js → query-operation.js} +83 -9
- package/dist/directory/{owner-directory-search.js → search.js} +50 -2
- package/dist/directory/{owner-directory-store.js → store.js} +2 -2
- package/dist/eck/kit-renderer.js +3 -2
- package/dist/eck/manifest-engine.js +64 -2
- package/dist/eck/message-renderer.js +35 -0
- package/dist/ecweb/basic-settings-service.js +12 -10
- package/dist/{contracts → ecweb/contracts}/ecweb-service-protocol.js +2 -1
- package/dist/ecweb/dsh-native-service.js +413 -0
- package/dist/ecweb/providers-service.js +5 -3
- package/dist/ecweb/runtime/lifecycle.js +1 -1
- package/dist/ecweb/runtime/supervisor.js +1 -1
- package/dist/event-center/center-config.js +2 -2
- package/dist/event-center/dispatcher.js +1 -1
- package/dist/event-center/ipc-operation.js +12 -3
- package/dist/event-center/pack-loader.js +2 -2
- package/dist/event-center/registry.js +6 -6
- package/dist/event-center/runtime.js +2 -2
- package/dist/index.js +181 -77
- package/dist/ipc.js +161 -12
- package/dist/outputs/authorization.js +27 -0
- package/dist/outputs/events.js +10 -1
- package/dist/outputs/panel-cards.js +960 -0
- package/dist/paths.js +60 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +196 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +30 -3
- package/dist/services/dispatcher.js +25 -7
- package/dist/services/host/main.js +397 -0
- package/dist/services/host/protocol.js +125 -0
- package/dist/services/host/resident.js +347 -0
- package/dist/services/host-client.js +398 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +208 -0
- package/dist/services/host-runtime.js +841 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +258 -36
- package/dist/services/ipc-operation.js +503 -78
- package/dist/services/pack-manager.js +2 -2
- package/dist/services/router.js +43 -3
- package/dist/services/script-runner.js +541 -100
- package/dist/services/service-payload.js +28 -1
- package/dist/services/validation.js +136 -5
- package/dist/stats/context-usage.js +110 -0
- package/dist/stats/model-resolver.js +103 -17
- package/dist/stats/query.js +5 -0
- package/dist/trigger/application-service.js +9 -6
- package/dist/trigger/authorization.js +36 -33
- package/dist/trigger/ipc-service.js +4 -4
- package/dist/trigger/local-files.js +8 -166
- package/dist/trigger/manager.js +2 -2
- package/dist/trigger/parser.js +48 -0
- package/dist/trigger/scheduler.js +35 -13
- package/dist/trigger/script-executor.js +21 -0
- package/dist/trigger/script-sandbox.js +77 -232
- package/dist/trigger/system-definitions.js +25 -0
- package/dist/trigger/validation.js +1 -1
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/atomic-write.js +88 -1
- package/dist/utils/cross-platform.js +4 -42
- package/dist/utils/error-dict.json +22 -1
- package/dist/utils/error-utils.js +193 -6
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +74 -1
- package/dist/utils/logger.js +5 -3
- package/dist/utils/media-cache.js +284 -42
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/startup-trace.js +20 -4
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/welcome.js +64 -20
- package/dist/utils/windows-shell-trust.js +7 -3
- package/ecagent/README.md +35 -0
- package/ecagent/dist/agent-loop.js +80 -30
- package/ecagent/dist/harness/env/nodejs.d.ts +16 -0
- package/ecagent/dist/harness/env/nodejs.js +49 -20
- package/ecagent/dist/harness/messages.js +3 -2
- package/ecagent/dist/harness/types.d.ts +1 -0
- package/ecagent/dist/runtime/types.d.ts +2 -0
- package/ecagent/dist/runtime/utils/validation.d.ts +7 -1
- package/ecagent/dist/runtime/utils/validation.js +42 -0
- package/ecagent/dist/types.d.ts +2 -0
- 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/channels/feishu.md +1 -1
- package/kits/docs/evolcore/INDEX.md +13 -9
- package/kits/docs/evolcore/agent-create.md +2 -0
- package/kits/docs/evolcore/agent.md +133 -11
- package/kits/docs/evolcore/aid.md +39 -6
- package/kits/docs/evolcore/config.md +95 -1
- package/kits/docs/evolcore/ctl.md +2 -1
- package/kits/docs/evolcore/ec-capabilities.md +7 -10
- package/kits/docs/evolcore/ecweb-lifecycle.md +5 -1
- package/kits/docs/evolcore/event.md +1 -1
- package/kits/docs/evolcore/fs.md +49 -3
- package/kits/docs/evolcore/group.md +5 -4
- package/kits/docs/evolcore/memory-consolidation.md +1 -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 +31 -2
- package/kits/docs/evolcore/model.md +12 -1
- package/kits/docs/evolcore/msg.md +96 -36
- package/kits/docs/evolcore/pay.md +22 -0
- package/kits/docs/evolcore/plugin.md +74 -0
- package/kits/docs/evolcore/provider.md +29 -2
- package/kits/docs/evolcore/rpc.md +2 -2
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/skill.md +17 -1
- package/kits/docs/evolcore/stats.md +5 -0
- package/kits/docs/evolcore/storage.md +22 -0
- package/kits/docs/evolcore/thread-chain.md +20 -9
- package/kits/docs/evolcore/tool-authorization.md +14 -0
- package/kits/docs/evolcore/trigger.md +89 -13
- package/kits/docs/identity/AID_PROFILE_SPEC.md +1 -1
- package/kits/docs/venues/feishu-group.md +3 -2
- package/kits/docs/venues/feishu-private.md +3 -2
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +20 -6
- package/kits/rules/06-channel.md +20 -4
- package/kits/schemas/_meta.json +42 -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 +974 -0
- package/kits/schemas/agent-config.schema.24.json +986 -0
- package/kits/schemas/agent-config.schema.25.json +986 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.11.json +487 -0
- package/kits/schemas/daemon.schema.12.json +505 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/defaults.schema.8.json +484 -0
- package/kits/schemas/providers.schema.1.json +1 -1
- package/kits/schemas/providers.schema.2.json +1 -1
- package/kits/schemas/providers.schema.3.json +26 -4
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +17 -1
- package/kits/skills/ability/SKILL.md +395 -33
- package/kits/skills/ability/STRUCTURE.md +338 -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 +80 -37
- package/kits/skills/agent-output-cards/examples/html-surface.json +11 -0
- package/kits/skills/agent-output-cards/examples/meeting-followups.json +16 -0
- package/kits/skills/agent-output-cards/examples/meeting-latest.json +24 -0
- package/kits/skills/agent-output-cards/examples/project-metrics.json +16 -0
- package/kits/skills/agent-output-cards/examples/quick-links.json +18 -0
- package/kits/skills/agent-output-cards/examples/surface.html +8 -0
- package/kits/skills/agent-template-project/SKILL.md +51 -0
- package/kits/skills/agent-template-project/references/01-collect-and-pack.md +174 -0
- package/kits/skills/agent-template-project/references/02-upload-and-share.md +109 -0
- package/kits/skills/agent-template-project/references/03-download-and-install.md +189 -0
- package/kits/skills/agent-template-project/references/04-upgrade-and-recovery.md +74 -0
- package/kits/skills/agent-template-project/references/05-publish-to-platform.md +62 -0
- 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 +5 -5
- package/kits/skills/ec-identity/SKILL.md +9 -6
- package/kits/skills/ec-pay/SKILL.md +223 -0
- package/kits/skills/ec-provider/SKILL.md +6 -6
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +138 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-skill/SKILL.md +25 -9
- package/kits/skills/ec-skill/scripts/cli.mjs +7 -7
- package/kits/skills/ec-skill/scripts/skill.mjs +55 -41
- package/kits/skills/ec-skill/scripts/template/SKILL.md.tmpl +9 -0
- package/kits/skills/ec-trigger/SKILL.md +3 -3
- package/kits/skills/personal-assistant/SKILL.md +22 -22
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +1 -1
- package/kits/skills/scrapling-article-fetch/SKILL.md +5 -5
- package/kits/skills/thread-ops/SKILL.md +19 -9
- package/kits/skills/wechat-article-media-download/SKILL.md +2 -2
- package/kits/skills/wechat-article-reader/SKILL.md +2 -2
- 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 +5 -4
- package/kits/templates/system-fragments/personal-assistant.md +2 -2
- package/kits/templates/system-fragments/reply.md +15 -9
- package/kits/templates/system-fragments/session.md +2 -2
- package/kits/templates/system-fragments/thread.md +30 -127
- package/kits/templates/system-fragments/venue.md +16 -0
- package/package.json +7 -7
- package/scripts/agent-template/index.mjs +7 -1
- package/scripts/agent-template/inspect.mjs +99 -39
- package/scripts/agent-template/overlay.mjs +126 -2
- package/scripts/agent-template/shared/common.mjs +49 -5
- package/scripts/agent-template/shared/plan.mjs +4 -2
- package/scripts/agent-template/shared/service-packs.mjs +104 -0
- package/scripts/agent-template/shared/team-schema.json +468 -39
- package/scripts/agent-template/shared/template-contract.mjs +93 -51
- package/scripts/agent-template/shared/template-package.mjs +225 -44
- package/scripts/agent-template/shared/template-runtime.mjs +137 -15
- package/scripts/agent-template/shared/template.mjs +31 -8
- package/scripts/agent-template/team-pack.mjs +528 -56
- package/scripts/agent-template/team-preview.mjs +102 -9
- package/scripts/aid-batch/identity-batch.mjs +1 -1
- package/dist/agents/baseagent-availability.js +0 -152
- package/dist/agents/baseagent.js +0 -750
- package/dist/agents/codex/catalog.js +0 -80
- package/dist/agents/ecagent-plugin-lazy.js +0 -41
- package/dist/agents/tool-time-context.js +0 -55
- package/dist/core/legacy-rename.js +0 -41
- package/dist/core/plugin-lifecycle.js +0 -137
- package/dist/core/rate-window.js +0 -53
- package/dist/core/runner-reload-transaction.js +0 -60
- package/dist/core/runtime-lock.js +0 -90
- package/dist/core/soul.js +0 -66
- package/dist/core/system-session/grants.js +0 -40
- package/dist/directory/owner-directory-agentmd-sync.js +0 -89
- package/dist/directory/owner-directory-request-operation.js +0 -79
- package/dist/directory/owner-directory-text.js +0 -60
- 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/gemini-capability-provider.js → agents/gemini/capability-provider.js} +0 -0
- /package/dist/core/{system-channels.js → channel/system-channels.js} +0 -0
- /package/dist/core/{daemon-file-cache.js → daemon/daemon-file-cache.js} +0 -0
- /package/dist/core/{event-bus.js → event/event-bus.js} +0 -0
- /package/dist/core/{event-catalog.js → event/event-catalog.js} +0 -0
- /package/dist/core/{pack-ledger.js → pack/pack-ledger.js} +0 -0
- /package/dist/directory/{owner-directory-identity.js → identity.js} +0 -0
- /package/dist/directory/{owner-directory-policy.js → policy.js} +0 -0
- /package/dist/directory/{owner-directory-remarks.js → remarks.js} +0 -0
- /package/dist/directory/{owner-directory-scope.js → scope.js} +0 -0
- /package/dist/{contracts → ecweb/contracts}/ecweb-instance.js +0 -0
- /package/kits/templates/{bootstrap-welcome.md → bootstrap-intro.md} +0 -0
|
@@ -1,12 +1,20 @@
|
|
|
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, templateInstallationGate } from './jobs.js';
|
|
5
5
|
import { runTemplateTool } from './tool-runner.js';
|
|
6
|
-
import { templateError, templateJobAids } from './types.js';
|
|
6
|
+
import { templateError, templateJobAids, templateOwnerRequiredError, TEMPLATE_ACTIONS } from './types.js';
|
|
7
7
|
import { logger } from '../utils/logger.js';
|
|
8
|
-
|
|
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);
|
|
13
|
+
const templatePackage = await import(new URL('../../scripts/agent-template/shared/template-package.mjs', import.meta.url).href);
|
|
9
14
|
const JOB_MS = 30 * 60_000;
|
|
15
|
+
const PACK_VALIDATION_ERRORS = new Set(['INVALID_ARGUMENT', 'SENSITIVE_CONTENT', 'SOURCE_CHANGED',
|
|
16
|
+
'INTEGRITY_FAILED', 'INCOMPATIBLE', 'PACKAGE_TOO_LARGE', 'VERSION_CONFLICT', 'ACCESS_DENIED', 'NOT_ALLOWED',
|
|
17
|
+
'NOT_FOUND', 'CONFLICT', 'ENOENT', 'EACCES']);
|
|
10
18
|
export class AgentTemplateService {
|
|
11
19
|
deps;
|
|
12
20
|
jobs;
|
|
@@ -20,6 +28,7 @@ export class AgentTemplateService {
|
|
|
20
28
|
tool;
|
|
21
29
|
cleanupTimer;
|
|
22
30
|
disposed = false;
|
|
31
|
+
updateRun;
|
|
23
32
|
constructor(deps) {
|
|
24
33
|
this.deps = deps;
|
|
25
34
|
this.jobs = new TemplateJobs(deps.root);
|
|
@@ -49,18 +58,24 @@ export class AgentTemplateService {
|
|
|
49
58
|
clearTimeout(timer);
|
|
50
59
|
this.timers.clear();
|
|
51
60
|
for (const job of this.jobs.list())
|
|
52
|
-
if (['inspect', 'build'].includes(job.action)
|
|
61
|
+
if (['inspect', 'collect', 'build'].includes(job.action)
|
|
53
62
|
&& job.freeze && !['released', 'transferred'].includes(job.freeze.state)) {
|
|
54
63
|
await this.cancelInternal(job.actor, job.jobId, 'runtime_disposed');
|
|
55
64
|
}
|
|
56
|
-
|
|
65
|
+
for (const jobId of this.work.keys())
|
|
66
|
+
this.controllers.get(jobId)?.abort();
|
|
67
|
+
await Promise.allSettled([...this.work.values(), ...this.cancellations.values(), this.updateRun]);
|
|
57
68
|
}
|
|
58
69
|
view(job) {
|
|
59
70
|
const { actor: _actor, fingerprint: _fingerprint, args: _args, checkpoint: _checkpoint, version: _version, activating: _activating, ...view } = job;
|
|
71
|
+
if (['collect', 'build'].includes(job.action) && job.checkpoint.executionContext?.remote && view.result?.workspace) {
|
|
72
|
+
view.result = { ...view.result, workspace: undefined };
|
|
73
|
+
}
|
|
60
74
|
if (job.action === 'deploy' && job.committed) {
|
|
61
75
|
const runtimeReady = templateJobAids(job).every(aid => this.deps.installation.ready(aid));
|
|
62
76
|
const directoryReady = this.deps.installation.directoryReady(templateJobAids(job));
|
|
63
|
-
return { ...view,
|
|
77
|
+
return { ...view,
|
|
78
|
+
readiness: { runtimeReady, directoryReady, teamReady: runtimeReady && directoryReady,
|
|
64
79
|
health: runtimeReady && directoryReady ? 'ready' : 'degraded' } };
|
|
65
80
|
}
|
|
66
81
|
return view;
|
|
@@ -85,6 +100,11 @@ export class AgentTemplateService {
|
|
|
85
100
|
async executeTool(job, command, options) {
|
|
86
101
|
return this.step(job, () => this.tool(command, options, {
|
|
87
102
|
signal: this.controllers.get(job.jobId)?.signal,
|
|
103
|
+
onProgress: phase => {
|
|
104
|
+
if (['inventory', 'validating_selection', 'collecting', 'validating', 'assembling', 'sealing'].includes(phase)) {
|
|
105
|
+
this.phase(job, phase);
|
|
106
|
+
}
|
|
107
|
+
},
|
|
88
108
|
onSpawn: worker => { this.current(job); job.checkpoint.worker = worker; this.jobs.save(job); },
|
|
89
109
|
onExit: () => {
|
|
90
110
|
const current = this.jobs.read(job.jobId);
|
|
@@ -116,16 +136,26 @@ export class AgentTemplateService {
|
|
|
116
136
|
const current = this.jobs.read(job.jobId);
|
|
117
137
|
if (current.status === 'cancelling' || ['cancelled', 'succeeded'].includes(current.status))
|
|
118
138
|
return;
|
|
139
|
+
const recoverable = ['deploy', 'upgrade'].includes(current.action)
|
|
140
|
+
|| current.action === 'pack' && !PACK_VALIDATION_ERRORS.has(error.code)
|
|
141
|
+
|| current.action === 'publish' && !PACK_VALIDATION_ERRORS.has(error.code)
|
|
142
|
+
&& !['PUBLISHER_MISMATCH', 'INVALID_PUBLICATION'].includes(error.code) && !error.details?.remoteFailure
|
|
143
|
+
|| ['list', 'detail', 'download'].includes(current.action)
|
|
144
|
+
&& (!PACK_VALIDATION_ERRORS.has(error.code) || current.action === 'download' && error.code === 'ACCESS_DENIED')
|
|
145
|
+
&& !['INVALID_STORE_RESPONSE', 'SOURCE_CHANGED'].includes(error.code) && !error.details?.remoteFailure;
|
|
119
146
|
current.error = { code: error.code ?? 'TEMPLATE_FAILED', message: error.message,
|
|
120
|
-
retryable:
|
|
121
|
-
if (['inspect', 'build'].includes(current.action)) {
|
|
147
|
+
retryable: recoverable, ...(error.details ? { details: error.details } : {}) };
|
|
148
|
+
if (['inspect', 'collect', 'build'].includes(current.action)) {
|
|
122
149
|
await this.release(current, 'failed');
|
|
123
|
-
current.status = current.freeze
|
|
150
|
+
current.status = !current.freeze || current.freeze.state === 'released' ? 'failed' : 'cancelling';
|
|
124
151
|
current.resumable = false;
|
|
152
|
+
if (current.status === 'failed' && current.checkpoint.packageId) {
|
|
153
|
+
fs.rmSync(path.join(this.cache, 'packages', current.checkpoint.packageId), { recursive: true, force: true });
|
|
154
|
+
}
|
|
125
155
|
}
|
|
126
156
|
else {
|
|
127
|
-
current.status =
|
|
128
|
-
current.resumable =
|
|
157
|
+
current.status = recoverable ? 'paused' : 'failed';
|
|
158
|
+
current.resumable = recoverable;
|
|
129
159
|
}
|
|
130
160
|
this.jobs.save(current);
|
|
131
161
|
}
|
|
@@ -144,173 +174,566 @@ export class AgentTemplateService {
|
|
|
144
174
|
}
|
|
145
175
|
async query(actor, args) {
|
|
146
176
|
await this.deps.installation.authorize(actor);
|
|
147
|
-
|
|
177
|
+
let job = this.jobs.get(actor, args);
|
|
178
|
+
if (job.committed && job.action === 'deploy' && job.result?.installMode === 'create') {
|
|
179
|
+
job = await withFileLock(path.join(this.cache, 'jobs', job.jobId + '.execution.lock'), async () => {
|
|
180
|
+
const current = this.jobs.read(job.jobId);
|
|
181
|
+
await this.completeCreation(current);
|
|
182
|
+
return current;
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
else if (job.committed && job.checkpoint.initialInstallation && !job.checkpoint.installationRecorded) {
|
|
186
|
+
await this.recordInitialInstallation(job);
|
|
187
|
+
}
|
|
188
|
+
if (job.action === 'upgrade' && job.committed && !job.result?.backupCleanup && job.checkpoint.executionPlanFile) {
|
|
189
|
+
try {
|
|
190
|
+
job.result.backupCleanup = await this.tool('overlay', { operation: 'cleanup-upgrade',
|
|
191
|
+
planFile: job.checkpoint.executionPlanFile, backupDir: job.checkpoint.backupDir });
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
job.result.backupCleanup = { backupDir: job.checkpoint.backupDir, retainedAll: true, reason: 'CLEANUP_FAILED', error: error.message };
|
|
195
|
+
}
|
|
196
|
+
this.jobs.save(job);
|
|
197
|
+
}
|
|
198
|
+
return this.view(job);
|
|
148
199
|
}
|
|
149
|
-
async action(actor, requestId, action, args) {
|
|
200
|
+
async action(actor, requestId, action, args, context = {}) {
|
|
150
201
|
if (this.disposed)
|
|
151
202
|
throw templateError('RECOVERY_REQUIRED', 'Template runtime has been disposed');
|
|
152
|
-
|
|
203
|
+
if (!TEMPLATE_ACTIONS.includes(action))
|
|
204
|
+
throw templateError('INVALID_ARGUMENT', 'Unknown template action');
|
|
205
|
+
if (typeof requestId !== 'string' || !requestId.trim() || requestId.length > 200)
|
|
206
|
+
throw templateError('INVALID_ARGUMENT', 'Stable requestId required');
|
|
207
|
+
try {
|
|
208
|
+
await this.deps.installation.authorize(actor);
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
if (action === 'pull' && error.code === 'NOT_ALLOWED' && error.details?.reasonCode === 'DAEMON_OWNER_REQUIRED') {
|
|
212
|
+
throw templateOwnerRequiredError(action, error.message, error.details);
|
|
213
|
+
}
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
if (['inspect', 'collect', 'pack', 'push', 'list', 'detail', 'publish', 'download'].includes(action)) {
|
|
217
|
+
args = templateContract.normalizeTemplateRequest({ requestId, action, args }).args;
|
|
218
|
+
}
|
|
153
219
|
if (action === 'status')
|
|
154
220
|
return this.query(actor, args);
|
|
155
221
|
if (action === 'capabilities')
|
|
156
222
|
return this.tool('capabilities', {});
|
|
223
|
+
if (action === 'update-status')
|
|
224
|
+
return this.updateStatus(actor, args.targetAid);
|
|
225
|
+
if (action === 'upgrade')
|
|
226
|
+
return this.acceptUpgrade(actor, requestId, args);
|
|
157
227
|
if (action === 'cancel' || action === 'resume')
|
|
158
|
-
return this.control(actor, requestId, action, args.jobId);
|
|
228
|
+
return this.control(actor, requestId, action, args.jobId, context);
|
|
159
229
|
const prior = this.jobs.original(actor, requestId);
|
|
160
230
|
if (prior) {
|
|
161
|
-
if (
|
|
231
|
+
if (!this.jobs.requestMatches(actor, requestId, action, args))
|
|
162
232
|
throw templateError('CONFLICT', 'Request has different arguments');
|
|
233
|
+
if (['collect', 'pack', 'push', 'list', 'detail', 'publish', 'download'].includes(action)
|
|
234
|
+
&& prior.checkpoint.executionContext?.executionAgentAid !== context.executionAgentAid) {
|
|
235
|
+
throw templateError('CONFLICT', 'Request belongs to another execution identity');
|
|
236
|
+
}
|
|
237
|
+
if (action === 'deploy')
|
|
238
|
+
return this.deploy(actor, requestId, args);
|
|
163
239
|
return this.view(prior);
|
|
164
240
|
}
|
|
165
241
|
if (action === 'inspect')
|
|
166
242
|
return this.inspect(actor, requestId, args);
|
|
167
|
-
if (action === '
|
|
168
|
-
return this.
|
|
243
|
+
if (action === 'collect')
|
|
244
|
+
return this.collect(actor, requestId, args, context);
|
|
245
|
+
if (action === 'pack')
|
|
246
|
+
return this.pack(actor, requestId, args, context);
|
|
169
247
|
if (action === 'deploy')
|
|
170
248
|
return this.deploy(actor, requestId, args);
|
|
249
|
+
if (action === 'publish')
|
|
250
|
+
this.packageRecord(actor, args.packageId);
|
|
171
251
|
const { job } = this.jobs.accept(actor, requestId, action, args);
|
|
172
|
-
|
|
252
|
+
job.checkpoint.executionContext = context;
|
|
253
|
+
this.jobs.save(job);
|
|
254
|
+
this.launch(job, value => action === 'push' ? this.push(value) : action === 'pull' ? this.pull(value)
|
|
255
|
+
: action === 'publish' ? this.publish(value)
|
|
256
|
+
: ['list', 'detail', 'download'].includes(action) ? this.store(value)
|
|
257
|
+
: action === 'check-update' ? this.runUpdateCheck(value) : this.preview(value));
|
|
173
258
|
return this.view(job);
|
|
174
259
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
260
|
+
updateFile(targetAid) {
|
|
261
|
+
this.jobs.installationFile(targetAid);
|
|
262
|
+
return path.join(this.cache, 'updates', templateFingerprint(targetAid) + '.json');
|
|
263
|
+
}
|
|
264
|
+
snapshot(file) {
|
|
265
|
+
this.jobs.assertStatePath(file);
|
|
266
|
+
if (!fs.existsSync(file))
|
|
267
|
+
return null;
|
|
268
|
+
return { sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), mode: fs.statSync(file).mode & 0o777 };
|
|
269
|
+
}
|
|
270
|
+
async updateAuthority(targetAid, actor, recoveryJobId, allowDisabled = false) {
|
|
271
|
+
if (!this.deps.updates)
|
|
272
|
+
throw templateError('CATALOG_UNAVAILABLE', 'Template update runtime unavailable');
|
|
273
|
+
const current = await this.deps.updates.context(targetAid);
|
|
274
|
+
if (!current.ownerAid || actor && actor !== current.ownerAid)
|
|
275
|
+
throw templateError('NOT_ALLOWED', 'Current direct Owner required');
|
|
276
|
+
await this.deps.authorize(current.ownerAid, targetAid, recoveryJobId);
|
|
277
|
+
const config = JSON.parse(fs.readFileSync(path.join(this.deps.root, 'agents', targetAid, 'config.json'), 'utf8'));
|
|
278
|
+
const eligible = ['manual', 'auto'].includes(config.update?.mode) && typeof config.update?.key === 'string' && isValidAid(config.update.key)
|
|
279
|
+
&& typeof config.update?.registryAid === 'string' && isValidAid(config.update.registryAid) && typeof config.version === 'string'
|
|
280
|
+
&& /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(config.version);
|
|
281
|
+
if (!allowDisabled && !eligible)
|
|
282
|
+
throw templateError(config.update?.mode === 'disabled' ? 'UPDATE_DISABLED' : 'UPDATE_INFORMATION_INCOMPLETE', 'Upgrade requires an enabled mode, original key, registryAid and local version');
|
|
283
|
+
return { ...current, mode: config.update?.mode, key: config.update?.key, registryAid: config.update?.registryAid,
|
|
284
|
+
version: config.version, eligible, config };
|
|
285
|
+
}
|
|
286
|
+
attestedRelease(source, row, enabled = true) {
|
|
287
|
+
if (!row || Array.isArray(row) || row.key !== source.key || typeof row.publisher !== 'string' || !isValidAid(row.publisher) || !/^[a-f0-9]{64}$/.test(row.releaseId ?? '')
|
|
288
|
+
|| !/^sha256:[a-f0-9]{64}$/.test(row.digest ?? '') || !Number.isSafeInteger(row.size) || row.size <= 0
|
|
289
|
+
|| enabled && (row.reviewStatus !== 'approved' || row.upgradeStatus !== 'enabled')) {
|
|
290
|
+
throw templateError('INVALID_UPGRADE_TARGET', 'Registry did not return one approved, enabled single-Agent release');
|
|
291
|
+
}
|
|
292
|
+
compareTemplateVersions(row.version, row.version);
|
|
293
|
+
return { source, key: row.key, publisher: row.publisher, releaseId: row.releaseId, version: row.version,
|
|
294
|
+
packageVersion: row.version, digest: row.digest, size: row.size };
|
|
295
|
+
}
|
|
296
|
+
async resolveUpgrade(context, operationId) {
|
|
297
|
+
const source = { key: context.key, registryAid: context.registryAid };
|
|
298
|
+
const response = await this.deps.updates.catalog(source, 'versions', { key: context.key, currentVersion: context.version }, operationId);
|
|
299
|
+
if (response.registryAid !== source.registryAid || response.key !== source.key || response.currentVersion !== context.version
|
|
300
|
+
|| typeof response.updateAvailable !== 'boolean' || response.target === undefined)
|
|
301
|
+
throw templateError('INVALID_CATALOG', 'Upgrade query source mismatch');
|
|
302
|
+
const candidate = response.target === null ? null : this.attestedRelease(source, response.target);
|
|
303
|
+
const updateAvailable = !!candidate && compareTemplateVersions(candidate.version, context.version) > 0;
|
|
304
|
+
if (response.updateAvailable !== updateAvailable)
|
|
305
|
+
throw templateError('INVALID_CATALOG', 'Upgrade comparison differs from local numeric version comparison');
|
|
306
|
+
return { source, candidate, updateAvailable };
|
|
307
|
+
}
|
|
308
|
+
async updateStatus(actor, targetAid) {
|
|
309
|
+
const context = await this.updateAuthority(targetAid, actor, undefined, true);
|
|
310
|
+
const file = this.updateFile(targetAid);
|
|
311
|
+
const check = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
|
|
312
|
+
return { targetAid, eligible: context.eligible, mode: context.mode ?? null, key: context.key ?? null,
|
|
313
|
+
registryAid: context.registryAid ?? null, currentVersion: context.version ?? null, automaticExecution: false,
|
|
314
|
+
check: check?.ownerAid === actor && check?.key === context.key && check?.registryAid === context.registryAid ? check : null,
|
|
315
|
+
activeJob: this.jobs.list().find(job => ['deploy', 'upgrade'].includes(job.action) && !job.committed && !job.checkpoint.restored
|
|
316
|
+
&& Object.values(job.members).some(member => member.aid === targetAid))?.jobId ?? null };
|
|
317
|
+
}
|
|
318
|
+
async runUpdateCheck(job) {
|
|
319
|
+
job.result = await this.checkUpdate(job.args.targetAid, job.actor);
|
|
320
|
+
job.status = 'succeeded';
|
|
321
|
+
job.phase = 'completed';
|
|
191
322
|
this.jobs.save(job);
|
|
192
|
-
|
|
193
|
-
|
|
323
|
+
}
|
|
324
|
+
async checkUpdate(targetAid, actor) {
|
|
325
|
+
return withFileLock(path.join(this.cache, 'update-checks', templateFingerprint(targetAid) + '.lock'), () => this.checkUpdateResult(targetAid, actor));
|
|
326
|
+
}
|
|
327
|
+
/** Shared repository check; only the scheduled caller may send a notice. */
|
|
328
|
+
async checkUpdateResult(targetAid, actor) {
|
|
329
|
+
const context = await this.updateAuthority(targetAid, actor);
|
|
330
|
+
const resolved = await this.resolveUpgrade(context, 'check:' + randomUUID());
|
|
331
|
+
let summary = null;
|
|
332
|
+
if (resolved.updateAvailable) {
|
|
333
|
+
const detail = await this.deps.updates.catalog(resolved.source, 'detail', { releaseId: resolved.candidate.releaseId,
|
|
334
|
+
fromVersion: context.version }, 'summary:' + randomUUID());
|
|
335
|
+
if (templateFingerprint(this.attestedRelease(resolved.source, detail.release ?? detail)) !== templateFingerprint(resolved.candidate)) {
|
|
336
|
+
throw templateError('SOURCE_CHANGED', 'Target summary differs from the enabled release');
|
|
337
|
+
}
|
|
338
|
+
summary = detail.summary ?? { available: false, reason: 'PREVIOUS_PACKAGE_UNAVAILABLE' };
|
|
339
|
+
}
|
|
340
|
+
const fresh = await this.updateAuthority(targetAid, context.ownerAid);
|
|
341
|
+
if (templateFingerprint([fresh.ownerAid, fresh.key, fresh.registryAid, fresh.version, fresh.mode])
|
|
342
|
+
!== templateFingerprint([context.ownerAid, context.key, context.registryAid, context.version, context.mode]))
|
|
343
|
+
throw templateError('SOURCE_CHANGED', 'Update configuration changed');
|
|
344
|
+
const file = this.updateFile(targetAid);
|
|
345
|
+
const before = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
|
|
346
|
+
const result = { targetAid, ownerAid: context.ownerAid, key: context.key, registryAid: context.registryAid,
|
|
347
|
+
currentVersion: context.version, updateAvailable: resolved.updateAvailable, target: resolved.candidate, summary,
|
|
348
|
+
checkedAt: Date.now(), notified: before.notified ?? null };
|
|
349
|
+
writeTemplateState(file, result);
|
|
350
|
+
return result;
|
|
351
|
+
}
|
|
352
|
+
/** Invoked by the daemon's one built-in script Trigger, never a model or a per-Agent timer. */
|
|
353
|
+
async checkDueUpdates() {
|
|
354
|
+
if (this.updateRun)
|
|
355
|
+
return this.updateRun;
|
|
356
|
+
const run = this.scanDueUpdates();
|
|
357
|
+
this.updateRun = run;
|
|
194
358
|
try {
|
|
195
|
-
|
|
196
|
-
|
|
359
|
+
await run;
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
if (this.updateRun === run)
|
|
363
|
+
this.updateRun = undefined;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
async scanDueUpdates() {
|
|
367
|
+
for (const target of this.deps.updates?.targets() ?? []) {
|
|
368
|
+
if (this.disposed)
|
|
369
|
+
return;
|
|
370
|
+
try {
|
|
371
|
+
const context = await this.updateAuthority(target.aid, undefined, undefined, true);
|
|
372
|
+
if (!context.eligible)
|
|
197
373
|
continue;
|
|
198
|
-
|
|
374
|
+
await withFileLock(path.join(this.cache, 'update-checks', templateFingerprint(target.aid) + '.lock'), async () => {
|
|
375
|
+
const result = await this.checkUpdateResult(target.aid);
|
|
376
|
+
if (!result.updateAvailable)
|
|
377
|
+
return;
|
|
378
|
+
const source = result.target.source;
|
|
379
|
+
const noticeId = 'notice_' + templateFingerprint({ targetAid: target.aid, ownerAid: result.ownerAid,
|
|
380
|
+
...source, version: result.target.version });
|
|
381
|
+
if (result.notified?.noticeId === noticeId)
|
|
382
|
+
return;
|
|
383
|
+
const notice = { noticeId, targetAid: target.aid, ownerAid: result.ownerAid, source,
|
|
384
|
+
candidate: result.target, currentVersion: result.currentVersion, createdAt: Date.now(), unread: true, delivery: 'pending' };
|
|
385
|
+
const receipt = await this.deps.updates.notify(notice);
|
|
386
|
+
if (!receipt.messageId)
|
|
387
|
+
throw templateError('NOTIFICATION_FAILED', 'Notice transport did not accept the message');
|
|
388
|
+
result.notified = { noticeId, version: notice.candidate.version, messageId: receipt.messageId };
|
|
389
|
+
writeTemplateState(this.updateFile(target.aid), result);
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
if (this.disposed)
|
|
394
|
+
return;
|
|
395
|
+
const file = this.updateFile(target.aid);
|
|
396
|
+
const previous = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
|
|
397
|
+
writeTemplateState(file, { ...previous, checkedAt: Date.now(), error: { code: error.code ?? 'CHECK_FAILED', message: error.message } });
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
async acceptUpgrade(actor, requestId, args) {
|
|
402
|
+
return withFileLock(path.join(this.cache, 'update-targets', templateFingerprint(args.targetAid) + '.lock'), async () => {
|
|
403
|
+
const prior = this.jobs.original(actor, requestId);
|
|
404
|
+
if (prior) {
|
|
405
|
+
if (!this.jobs.requestMatches(actor, requestId, 'upgrade', args))
|
|
406
|
+
throw templateError('CONFLICT', 'Request arguments changed');
|
|
407
|
+
return this.view(prior);
|
|
408
|
+
}
|
|
409
|
+
const active = this.jobs.list().find(job => ['upgrade', 'deploy'].includes(job.action) && !job.committed && !['cancelled', 'succeeded'].includes(job.status)
|
|
410
|
+
&& Object.values(job.members).some(member => member.aid === args.targetAid));
|
|
411
|
+
if (active) {
|
|
412
|
+
if (active.actor !== actor)
|
|
413
|
+
throw templateError('NOT_ALLOWED', 'Target has an unfinished job from another Owner');
|
|
414
|
+
this.jobs.bindRequest(actor, requestId, 'upgrade', args, active.jobId);
|
|
415
|
+
return this.view(active);
|
|
416
|
+
}
|
|
417
|
+
const context = await this.updateAuthority(args.targetAid, actor);
|
|
418
|
+
const { job } = this.jobs.accept(actor, requestId, 'upgrade', args, { [context.key]: { aid: args.targetAid, projectPath: context.projectPath, requestId } });
|
|
419
|
+
job.resumable = true;
|
|
420
|
+
this.jobs.save(job);
|
|
421
|
+
this.jobs.associate(job);
|
|
422
|
+
this.launch(job, value => this.runUpgrade(value));
|
|
423
|
+
return this.view(job);
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
readInstalledManifest(targetAid, version) {
|
|
427
|
+
try {
|
|
428
|
+
const installed = this.jobs.installation(targetAid);
|
|
429
|
+
const file = path.join(this.deps.root, 'agents', targetAid, 'template.manifest.json');
|
|
430
|
+
this.jobs.assertStatePath(file);
|
|
431
|
+
const bytes = fs.readFileSync(file);
|
|
432
|
+
if (installed?.release?.version !== version || installed.manifestDigest !== 'sha256:' + createHash('sha256').update(bytes).digest('hex'))
|
|
433
|
+
return null;
|
|
434
|
+
const list = JSON.parse(bytes.toString('utf8'));
|
|
435
|
+
return Array.isArray(list) ? list : null;
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
async runUpgrade(job) {
|
|
442
|
+
const context = await this.step(job, () => this.updateAuthority(job.args.targetAid, job.actor, job.jobId));
|
|
443
|
+
let frozen = job.checkpoint.update;
|
|
444
|
+
if (!frozen) {
|
|
445
|
+
const resolved = await this.step(job, () => this.resolveUpgrade(context, job.jobId + ':target'));
|
|
446
|
+
if (job.args.releaseId && job.args.releaseId !== resolved.candidate?.releaseId)
|
|
447
|
+
throw templateError('UPGRADE_TARGET_CHANGED', 'Displayed target is no longer enabled', { target: resolved.candidate });
|
|
448
|
+
if (!resolved.updateAvailable) {
|
|
449
|
+
job.status = 'succeeded';
|
|
450
|
+
job.phase = 'no_update';
|
|
451
|
+
job.resumable = false;
|
|
452
|
+
job.checkpoint.restored = true;
|
|
453
|
+
job.result = { updateAvailable: false, target: resolved.candidate };
|
|
454
|
+
this.jobs.save(job);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
const detail = await this.step(job, () => this.deps.updates.catalog(resolved.source, 'detail', { releaseId: resolved.candidate.releaseId, fromVersion: context.version }, job.jobId + ':detail'));
|
|
458
|
+
const actual = this.attestedRelease(resolved.source, detail.release ?? detail);
|
|
459
|
+
if (templateFingerprint(actual) !== templateFingerprint(resolved.candidate))
|
|
460
|
+
throw templateError('SOURCE_CHANGED', 'Target detail differs from enabled release');
|
|
461
|
+
frozen = job.checkpoint.update = { release: actual, source: resolved.source, oldVersion: context.version,
|
|
462
|
+
mode: context.mode, oldManifest: this.readInstalledManifest(job.args.targetAid, context.version),
|
|
463
|
+
lock: this.snapshot(this.jobs.installationFile(job.args.targetAid)),
|
|
464
|
+
path: path.join(context.projectPath, '.evolcore', 'template-upgrades', job.jobId + '.ectpl'), downloadGeneration: 1,
|
|
465
|
+
summary: detail.summary ?? { available: false, reason: 'PREVIOUS_PACKAGE_UNAVAILABLE' } };
|
|
466
|
+
this.jobs.save(job);
|
|
467
|
+
}
|
|
468
|
+
let repreview = false;
|
|
469
|
+
let restoreDownload = false;
|
|
470
|
+
if (job.checkpoint.previewId) {
|
|
471
|
+
const previous = this.previewRecord(job.checkpoint.previewId);
|
|
472
|
+
if (previous.planDigest !== null) {
|
|
473
|
+
if (!frozen.path || fs.existsSync(frozen.path) || job.checkpoint.resourcesApplied) {
|
|
474
|
+
await this.runInstallation(job);
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
restoreDownload = true;
|
|
478
|
+
}
|
|
479
|
+
else {
|
|
480
|
+
if (job.committed || job.activating || ['backupDir', 'executionPlanFile', 'executionConfirmedAt', 'resourcesApplied',
|
|
481
|
+
'runtimeStopped', 'runtimeInactive', 'originalProfile', 'installMode', 'restored', 'restoredProfileVersion']
|
|
482
|
+
.some(key => Object.hasOwn(job.checkpoint, key))
|
|
483
|
+
|| Object.values(job.members).some(member => member.profilePublication || member.runtimeReady !== undefined)) {
|
|
484
|
+
throw templateError('RECOVERY_REQUIRED', 'An executed upgrade preview cannot be regenerated');
|
|
485
|
+
}
|
|
486
|
+
if (previous.actor !== job.actor || previous.previewId !== job.args.previewId || previous.installMode !== 'overwrite'
|
|
487
|
+
|| previous.packageId !== frozen.packageId || job.result?.previewId !== previous.previewId
|
|
488
|
+
|| job.result?.planDigest !== null || job.result?.executable !== false
|
|
489
|
+
|| !previous.update || templateFingerprint(previous.update.release) !== templateFingerprint(frozen.release)
|
|
490
|
+
|| templateFingerprint(previous.update.source) !== templateFingerprint(frozen.source)
|
|
491
|
+
|| previous.update.oldVersion !== frozen.oldVersion || previous.update.mode !== frozen.mode
|
|
492
|
+
|| templateFingerprint(previous.update.lock) !== templateFingerprint(frozen.lock)
|
|
493
|
+
|| job.args.releaseId && job.args.releaseId !== frozen.release.releaseId
|
|
494
|
+
|| Object.keys(job.members).length !== 1 || job.members[frozen.source.key]?.aid !== job.args.targetAid
|
|
495
|
+
|| job.members[frozen.source.key]?.projectPath !== context.projectPath) {
|
|
496
|
+
throw templateError('CONFLICT', 'Original unresolved upgrade preview or target changed');
|
|
497
|
+
}
|
|
498
|
+
const cached = frozen.path ? undefined : this.packageRecord(job.actor, frozen.packageId);
|
|
499
|
+
const changed = frozen.path ? previous.sourcePath !== frozen.path
|
|
500
|
+
: cached.data.digest !== frozen.release.digest || cached.provenance?.kind !== 'upgrade'
|
|
501
|
+
|| templateFingerprint(cached.provenance.release) !== templateFingerprint(frozen.release);
|
|
502
|
+
if (changed)
|
|
503
|
+
throw templateError('INTEGRITY_FAILED', 'Original fixed-candidate package changed');
|
|
504
|
+
await this.step(job, () => this.verifyUpdatePreview(job.actor, previous, job.jobId));
|
|
505
|
+
repreview = true;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (context.key !== frozen.source.key || context.registryAid !== frozen.source.registryAid || context.version !== frozen.oldVersion) {
|
|
509
|
+
throw templateError('SOURCE_CHANGED', 'Local source or version changed; resume requires the original target');
|
|
510
|
+
}
|
|
511
|
+
if (!job.checkpoint.previewId || repreview || restoreDownload) {
|
|
512
|
+
const directory = frozen.path ? path.dirname(frozen.path) : path.join(this.cache, 'packages', frozen.packageId);
|
|
513
|
+
const recordFile = path.join(directory, 'record.json');
|
|
514
|
+
const file = frozen.path ?? path.join(directory, 'package.ectpl');
|
|
515
|
+
if (frozen.path ? !fs.existsSync(file) : !fs.existsSync(recordFile)) {
|
|
516
|
+
if (frozen.downloadAuthorization && (frozen.downloadExpiresAt <= Date.now() || frozen.downloadError === 'ACCESS_DENIED')) {
|
|
517
|
+
frozen.downloadGeneration++;
|
|
518
|
+
delete frozen.downloadAuthorization;
|
|
519
|
+
this.jobs.save(job);
|
|
520
|
+
}
|
|
521
|
+
const download = frozen.downloadAuthorization ?? await this.step(job, () => this.deps.updates.catalog(frozen.source, 'download', { purpose: 'upgrade', releaseId: frozen.release.releaseId, targetHostAid: this.deps.hostAid }, job.jobId + ':download:' + frozen.downloadGeneration));
|
|
522
|
+
const errors = templateContract.validateTemplateRequest({ requestId: job.requestId, action: 'pull', args: { source: download.source, path: file } });
|
|
523
|
+
if (errors.length || download.releaseId !== frozen.release.releaseId || download.targetHostAid !== this.deps.hostAid
|
|
524
|
+
|| download.source.digest !== frozen.release.digest)
|
|
525
|
+
throw templateError('INTEGRITY_FAILED', 'Fixed upgrade download differs');
|
|
526
|
+
frozen.downloadAuthorization = download;
|
|
527
|
+
frozen.downloadExpiresAt = Date.now() + (download.expiresInSeconds ?? 300) * 1000;
|
|
199
528
|
this.jobs.save(job);
|
|
529
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
530
|
+
fs.rmSync(file, { force: true });
|
|
531
|
+
this.phase(job, 'downloading');
|
|
200
532
|
try {
|
|
201
|
-
|
|
533
|
+
await this.step(job, () => this.deps.download(download.source.download?.shareId, file, download.source.location));
|
|
202
534
|
}
|
|
203
535
|
catch (error) {
|
|
204
|
-
|
|
536
|
+
frozen.downloadError = error.code;
|
|
537
|
+
this.jobs.save(job);
|
|
538
|
+
throw error;
|
|
539
|
+
}
|
|
540
|
+
const data = await this.executeTool(job, 'read-package', { archivePath: file, digest: frozen.release.digest });
|
|
541
|
+
const member = data.members?.[frozen.source.key];
|
|
542
|
+
if (Object.keys(data.members ?? {}).length !== 1 || !member || member.version !== frozen.release.version
|
|
543
|
+
|| data.metadata.version !== frozen.release.version || data.publisher?.aid !== frozen.release.publisher) {
|
|
544
|
+
throw templateError('INTEGRITY_FAILED', 'Original AID key, publisher and unified author version required');
|
|
205
545
|
}
|
|
546
|
+
if (!frozen.path)
|
|
547
|
+
writeTemplateState(recordFile, { actor: job.actor, packageId: frozen.packageId, createdAt: Date.now(), data: { ...data, file }, provenance: { kind: 'upgrade', release: frozen.release } });
|
|
206
548
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
549
|
+
if (!restoreDownload)
|
|
550
|
+
await this.preview(job, { ...(frozen.path ? { path: frozen.path } : { packageId: frozen.packageId }), installMode: 'overwrite', members: {
|
|
551
|
+
[frozen.source.key]: { target: { aid: job.args.targetAid, project: context.projectPath } }
|
|
552
|
+
} }, frozen);
|
|
553
|
+
}
|
|
554
|
+
this.current(job);
|
|
555
|
+
await this.runInstallation(job);
|
|
556
|
+
}
|
|
557
|
+
async inspect(actor, requestId, args) {
|
|
558
|
+
const members = Object.fromEntries(Object.entries(args.members).map(([key, member]) => [key, { aid: member.source.kind === 'agent' ? member.source.aid : '',
|
|
559
|
+
projectPath: member.source.kind === 'directory' ? member.source.path : '', requestId: randomUUID() }]));
|
|
560
|
+
for (const member of Object.values(members))
|
|
561
|
+
if (member.aid)
|
|
562
|
+
await this.deps.authorize(actor, member.aid);
|
|
563
|
+
const { job, reused } = this.jobs.accept(actor, requestId, 'inspect', args, members);
|
|
564
|
+
if (!reused)
|
|
565
|
+
this.launch(job, async (value) => {
|
|
566
|
+
this.phase(value, 'inventory');
|
|
219
567
|
const sources = {};
|
|
220
|
-
for (const [key, member] of Object.entries(
|
|
568
|
+
for (const [key, member] of Object.entries(args.members)) {
|
|
221
569
|
sources[key] = member.source.kind === 'agent'
|
|
222
|
-
? await this.step(
|
|
223
|
-
: { kind: 'directory', path: member.source.path,
|
|
570
|
+
? await this.step(value, () => this.deps.source(member.source.aid, actor, args.module))
|
|
571
|
+
: { kind: 'directory', path: member.source.path, publisher: { aid: actor } };
|
|
224
572
|
}
|
|
225
|
-
|
|
226
|
-
this.jobs.save(
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
current.phase = 'awaiting_selection';
|
|
232
|
-
current.resumable = false;
|
|
233
|
-
this.jobs.save(current);
|
|
573
|
+
value.checkpoint.sources = sources;
|
|
574
|
+
this.jobs.save(value);
|
|
575
|
+
value.result = await this.executeTool(value, 'inspect-module', { members: sources, module: args.module });
|
|
576
|
+
value.status = 'succeeded';
|
|
577
|
+
value.phase = 'inventoried';
|
|
578
|
+
this.jobs.save(value);
|
|
234
579
|
});
|
|
235
|
-
}
|
|
236
|
-
catch (error) {
|
|
237
|
-
job.error = { code: error.code ?? 'AGENT_BUSY', message: error.message, retryable: false, details: error.details };
|
|
238
|
-
await this.release(job, 'failed');
|
|
239
|
-
job.status = job.freeze.state === 'released' ? 'failed' : 'cancelling';
|
|
240
|
-
this.jobs.save(job);
|
|
241
|
-
}
|
|
242
580
|
return this.view(job);
|
|
243
581
|
}
|
|
244
|
-
async
|
|
582
|
+
async collect(actor, requestId, args, context) {
|
|
245
583
|
const inspection = this.jobs.get(actor, { jobId: args.inspectionJobId });
|
|
246
|
-
if (inspection.action !== 'inspect'
|
|
247
|
-
|
|
248
|
-
if (inspection.freeze?.buildJobId) {
|
|
249
|
-
const built = this.jobs.read(inspection.freeze.buildJobId);
|
|
250
|
-
if (built.fingerprint !== templateFingerprint({ action: 'build', args }))
|
|
251
|
-
throw templateError('CONFLICT', 'Inspection was already used');
|
|
252
|
-
this.jobs.bindRequest(actor, requestId, 'build', args, built.jobId);
|
|
253
|
-
return this.view(built);
|
|
254
|
-
}
|
|
255
|
-
if (inspection.freeze?.state !== 'held' || inspection.freeze.selectionExpiresAt <= Date.now()) {
|
|
256
|
-
throw templateError('EXPIRED', 'Inspection is no longer frozen');
|
|
257
|
-
}
|
|
258
|
-
if (inspection.phase !== 'awaiting_selection' || inspection.result?.inventoryDigest !== args.inventoryDigest
|
|
584
|
+
if (inspection.action !== 'inspect' || inspection.status !== 'succeeded' || inspection.args.module !== args.module
|
|
585
|
+
|| inspection.result?.inventoryDigest !== args.inventoryDigest
|
|
259
586
|
|| Object.keys(inspection.members).sort().join() !== Object.keys(args.members).sort().join()) {
|
|
260
|
-
throw templateError('CONFLICT', '
|
|
587
|
+
throw templateError('CONFLICT', 'Completed matching module inspection required');
|
|
261
588
|
}
|
|
262
|
-
await this.tool('validate-selection', { inventory: inspection.result, metadata: args.metadata, members: args.members });
|
|
263
589
|
for (const aid of templateJobAids(inspection))
|
|
264
590
|
await this.deps.authorize(actor, aid);
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
job.
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
591
|
+
if (args.freeze && Object.values(inspection.members).some(member => !member.aid)) {
|
|
592
|
+
throw templateError('INVALID_ARGUMENT', 'Only live Agent sources support optional freezing');
|
|
593
|
+
}
|
|
594
|
+
const first = Object.values(inspection.checkpoint.sources)[0];
|
|
595
|
+
const workRoot = context.projectPath ?? first?.projectPath ?? (first?.kind === 'directory' ? first.path : undefined)
|
|
596
|
+
?? context.runtimeDir ?? process.env.TMPDIR;
|
|
597
|
+
if (!workRoot || !path.isAbsolute(workRoot))
|
|
598
|
+
throw templateError('TEMP_UNAVAILABLE', 'Absolute module work root required');
|
|
599
|
+
const { job, reused } = this.jobs.accept(actor, requestId, 'collect', args, structuredClone(inspection.members));
|
|
600
|
+
if (reused)
|
|
601
|
+
return this.view(job);
|
|
602
|
+
job.checkpoint.executionContext = context;
|
|
603
|
+
job.checkpoint.inventory = inspection.result;
|
|
604
|
+
job.checkpoint.sources = inspection.checkpoint.sources;
|
|
605
|
+
// The path is chosen by the daemon from its trusted session or registered source project.
|
|
606
|
+
job.checkpoint.workspace = path.join(workRoot, '.template-work', job.jobId);
|
|
278
607
|
this.jobs.save(job);
|
|
279
|
-
this.jobs.save(current);
|
|
280
|
-
held.owner = job.jobId;
|
|
281
|
-
clearTimeout(this.timers.get(current.jobId));
|
|
282
|
-
this.timers.delete(current.jobId);
|
|
283
608
|
this.launch(job, async (value) => {
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
609
|
+
let selectionIndex;
|
|
610
|
+
if (args.module === 'project') {
|
|
611
|
+
this.phase(value, 'loading_selection');
|
|
612
|
+
selectionIndex = await this.downloadIndex(value, args.selectionIndex, path.join(this.cache, 'jobs', value.jobId + '-selection.json'));
|
|
613
|
+
}
|
|
614
|
+
if (args.freeze) {
|
|
615
|
+
this.phase(value, 'acquiring');
|
|
616
|
+
value.checkpoint.collectionKey = value.jobId;
|
|
617
|
+
value.freeze = { state: 'acquiring', generation: 1, frozenAt: null, selectionExpiresAt: null };
|
|
618
|
+
this.collections.set(value.jobId, { owner: value.jobId, releases: [] });
|
|
619
|
+
this.jobs.save(value);
|
|
620
|
+
const held = this.collections.get(value.jobId);
|
|
621
|
+
for (const [key, member] of Object.entries(value.members).sort(([a], [b]) => a.localeCompare(b)))
|
|
622
|
+
if (member.aid) {
|
|
623
|
+
held.releases.push({ key, release: await this.deps.hold(member.aid, value.jobId + ':' + key) });
|
|
624
|
+
}
|
|
625
|
+
value.freeze.state = 'held';
|
|
626
|
+
value.freeze.frozenAt = Date.now();
|
|
627
|
+
this.jobs.save(value);
|
|
628
|
+
}
|
|
288
629
|
const sources = structuredClone(value.checkpoint.sources);
|
|
289
|
-
for (const [key,
|
|
290
|
-
if (
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
const data = await this.executeTool(value, '
|
|
296
|
-
selections:
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
kind: 'build', sourceAids: templateJobAids(value), sources: value.args.inspectionJobId
|
|
301
|
-
} };
|
|
302
|
-
writeTemplateState(path.join(this.cache, 'packages', packageId, 'record.json'), record);
|
|
630
|
+
for (const [key, member] of Object.entries(value.members))
|
|
631
|
+
if (member.aid) {
|
|
632
|
+
await this.deps.authorize(actor, member.aid);
|
|
633
|
+
sources[key] = await this.step(value, () => this.deps.source(member.aid, actor, args.module));
|
|
634
|
+
}
|
|
635
|
+
this.phase(value, args.module === 'project' ? 'validating_selection' : 'collecting');
|
|
636
|
+
const data = await this.executeTool(value, 'collect-module', { module: args.module, members: sources,
|
|
637
|
+
selections: args.members, inventory: value.checkpoint.inventory, inventoryDigest: args.inventoryDigest,
|
|
638
|
+
inspectionJobId: args.inspectionJobId, selectionIndex, out: value.checkpoint.workspace });
|
|
639
|
+
if (value.freeze)
|
|
640
|
+
this.phase(value, 'releasing');
|
|
303
641
|
await this.release(value, 'completed');
|
|
304
|
-
if (value.freeze
|
|
305
|
-
throw templateError('RECOVERY_REQUIRED', '
|
|
306
|
-
|
|
307
|
-
value.result = { ...
|
|
642
|
+
if (value.freeze && value.freeze.state !== 'released')
|
|
643
|
+
throw templateError('RECOVERY_REQUIRED', 'Collection release incomplete');
|
|
644
|
+
value.checkpoint.sources = sources;
|
|
645
|
+
value.result = { ...data, workspaceRef: { aid: context.executionAgentAid ?? first?.agentAid,
|
|
646
|
+
path: '.template-work/' + value.jobId, root: 'project' } };
|
|
308
647
|
value.status = 'succeeded';
|
|
309
|
-
value.phase = '
|
|
648
|
+
value.phase = 'collected';
|
|
310
649
|
this.jobs.save(value);
|
|
311
650
|
});
|
|
312
651
|
return this.view(job);
|
|
313
652
|
}
|
|
653
|
+
async downloadIndex(job, ref, file) {
|
|
654
|
+
const executor = job.checkpoint.executionContext?.executionAgentAid;
|
|
655
|
+
if (ref.location.aid !== job.actor && ref.location.aid !== executor) {
|
|
656
|
+
throw templateError('ACCESS_DENIED', 'Index must belong to the Owner or actual executing Agent');
|
|
657
|
+
}
|
|
658
|
+
if (executor)
|
|
659
|
+
await this.deps.authorize(job.actor, executor);
|
|
660
|
+
await this.step(job, () => this.deps.download(ref.download.shareId, file, ref.location, templateContract.SELECTION_INDEX_LIMITS.bytes));
|
|
661
|
+
this.phase(job, 'validating_selection');
|
|
662
|
+
const bytes = fs.readFileSync(file);
|
|
663
|
+
if (bytes.length !== ref.size || bytes.length > templateContract.SELECTION_INDEX_LIMITS.bytes
|
|
664
|
+
|| 'sha256:' + createHash('sha256').update(bytes).digest('hex') !== ref.digest) {
|
|
665
|
+
throw templateError('INTEGRITY_FAILED', 'Selection index bytes differ from reference');
|
|
666
|
+
}
|
|
667
|
+
if (!Buffer.from(bytes.toString('utf8')).equals(bytes))
|
|
668
|
+
throw templateError('INVALID_ARGUMENT', 'UTF-8 selection index required');
|
|
669
|
+
return JSON.parse(bytes.toString('utf8'));
|
|
670
|
+
}
|
|
671
|
+
async pack(actor, requestId, args, context) {
|
|
672
|
+
const jobs = new Map();
|
|
673
|
+
const members = {};
|
|
674
|
+
const sourceMembers = {};
|
|
675
|
+
const originalKeys = {};
|
|
676
|
+
for (const [key, selection] of Object.entries(args.members)) {
|
|
677
|
+
members[key] = [];
|
|
678
|
+
const sources = new Set();
|
|
679
|
+
for (const ref of selection.collections) {
|
|
680
|
+
const collected = this.jobs.get(actor, { jobId: ref.jobId });
|
|
681
|
+
if (collected.action !== 'collect' || collected.status !== 'succeeded' || !collected.result?.workspace || !collected.members[key]
|
|
682
|
+
|| collected.freeze && collected.freeze.state !== 'released')
|
|
683
|
+
throw templateError('CONFLICT', 'Completed module collection for this member required');
|
|
684
|
+
if (jobs.has(ref.jobId) && members[key].some(value => value.workspace === collected.result.workspace)) {
|
|
685
|
+
throw templateError('CONFLICT', 'Duplicate module reference');
|
|
686
|
+
}
|
|
687
|
+
jobs.set(ref.jobId, collected);
|
|
688
|
+
const source = collected.checkpoint.sources[key];
|
|
689
|
+
sources.add(collected.members[key].aid || source.path);
|
|
690
|
+
sourceMembers[key] = collected.members[key];
|
|
691
|
+
const originalKey = source.originalKey ?? source.effectiveConfig?.update?.key ?? source.agentAid ?? key;
|
|
692
|
+
if (originalKeys[key] && originalKeys[key] !== originalKey)
|
|
693
|
+
throw templateError('CONFLICT', 'Original member key changed between modules');
|
|
694
|
+
originalKeys[key] = originalKey;
|
|
695
|
+
members[key].push({ module: collected.args.module, workspace: collected.result.workspace, memberKey: key,
|
|
696
|
+
platforms: collected.result.platforms });
|
|
697
|
+
}
|
|
698
|
+
if (sources.size !== 1)
|
|
699
|
+
throw templateError('CONFLICT', 'Modules must refer to the same source member');
|
|
700
|
+
}
|
|
701
|
+
for (const member of Object.values(sourceMembers))
|
|
702
|
+
if (member.aid)
|
|
703
|
+
await this.deps.authorize(actor, member.aid);
|
|
704
|
+
const publisherAid = args.publisherIdentity ? await this.publicationIdentity(actor, args.publisherIdentity, context) : actor;
|
|
705
|
+
const { job, reused } = this.jobs.accept(actor, requestId, 'pack', args, sourceMembers);
|
|
706
|
+
if (reused)
|
|
707
|
+
return this.view(job);
|
|
708
|
+
job.checkpoint.executionContext = context;
|
|
709
|
+
job.checkpoint.packageId = 'package_' + randomUUID();
|
|
710
|
+
this.jobs.save(job);
|
|
711
|
+
job.checkpoint.packOptions = { members, originalKeys, metadata: args.metadata,
|
|
712
|
+
memberReferences: args.memberReferences, assistantKey: args.assistantKey, publisher: { aid: publisherAid },
|
|
713
|
+
createdAt: job.createdAt, out: path.join(this.cache, 'packages', job.checkpoint.packageId) };
|
|
714
|
+
job.checkpoint.collectionIds = [...jobs.keys()];
|
|
715
|
+
this.jobs.save(job);
|
|
716
|
+
this.launch(job, value => this.runPack(value));
|
|
717
|
+
return this.view(job);
|
|
718
|
+
}
|
|
719
|
+
async runPack(job) {
|
|
720
|
+
for (const aid of templateJobAids(job))
|
|
721
|
+
await this.deps.authorize(job.actor, aid);
|
|
722
|
+
this.phase(job, 'assembling');
|
|
723
|
+
const data = await this.executeTool(job, 'pack-modules', job.checkpoint.packOptions);
|
|
724
|
+
const packageId = job.checkpoint.packageId;
|
|
725
|
+
writeTemplateState(path.join(this.cache, 'packages', packageId, 'record.json'), {
|
|
726
|
+
actor: job.actor, packageId, createdAt: job.createdAt, data,
|
|
727
|
+
executionAgentAid: job.checkpoint.executionContext?.executionAgentAid,
|
|
728
|
+
provenance: { kind: 'pack', sourceAids: templateJobAids(job), collections: job.checkpoint.collectionIds },
|
|
729
|
+
});
|
|
730
|
+
const { file: _file, members: _members, ...publicData } = data;
|
|
731
|
+
job.result = { ...publicData, packageId, path: data.file, memberKeys: Object.keys(data.members) };
|
|
732
|
+
job.status = 'succeeded';
|
|
733
|
+
job.phase = 'completed';
|
|
734
|
+
job.resumable = false;
|
|
735
|
+
this.jobs.save(job);
|
|
736
|
+
}
|
|
314
737
|
async release(job, reason) {
|
|
315
738
|
if (!job.freeze || ['released', 'transferred'].includes(job.freeze.state))
|
|
316
739
|
return;
|
|
@@ -343,8 +766,16 @@ export class AgentTemplateService {
|
|
|
343
766
|
job.error = { code: 'RECOVERY_REQUIRED', message: 'Some sources still require release', retryable: true };
|
|
344
767
|
this.jobs.save(job);
|
|
345
768
|
}
|
|
346
|
-
async control(actor, requestId, action, jobId) {
|
|
769
|
+
async control(actor, requestId, action, jobId, context = {}) {
|
|
347
770
|
const job = this.jobs.get(actor, { jobId });
|
|
771
|
+
if (['list', 'detail', 'publish', 'download'].includes(job.action)
|
|
772
|
+
&& !(job.action === 'publish' && job.args.publisherIdentity === 'host')
|
|
773
|
+
&& job.checkpoint.executionContext?.executionAgentAid !== context.executionAgentAid) {
|
|
774
|
+
throw templateError('NOT_ALLOWED', 'Resume or cancel the Store job from its original execution identity');
|
|
775
|
+
}
|
|
776
|
+
if (job.action === 'publish' && action === 'cancel' && job.checkpoint.submitIntent) {
|
|
777
|
+
throw templateError('CONFLICT', 'Registry submission cannot be cancelled; query or resume its original job');
|
|
778
|
+
}
|
|
348
779
|
const first = this.jobs.bindRequest(actor, requestId, action, { jobId }, jobId);
|
|
349
780
|
if (!first)
|
|
350
781
|
return this.view(job);
|
|
@@ -352,6 +783,38 @@ export class AgentTemplateService {
|
|
|
352
783
|
await this.cancelInternal(actor, jobId, 'user_cancel');
|
|
353
784
|
}
|
|
354
785
|
else {
|
|
786
|
+
if (['list', 'detail', 'download'].includes(job.action) && job.resumable && ['paused', 'failed'].includes(job.status)) {
|
|
787
|
+
job.attempt++;
|
|
788
|
+
job.status = 'queued';
|
|
789
|
+
delete job.error;
|
|
790
|
+
this.jobs.save(job);
|
|
791
|
+
this.launch(job, value => this.store(value));
|
|
792
|
+
return this.view(job);
|
|
793
|
+
}
|
|
794
|
+
if (job.action === 'publish' && job.resumable && ['paused', 'failed'].includes(job.status)) {
|
|
795
|
+
job.attempt++;
|
|
796
|
+
job.status = 'queued';
|
|
797
|
+
delete job.error;
|
|
798
|
+
this.jobs.save(job);
|
|
799
|
+
this.launch(job, value => this.publish(value));
|
|
800
|
+
return this.view(job);
|
|
801
|
+
}
|
|
802
|
+
if (job.action === 'pack' && job.resumable && ['paused', 'failed'].includes(job.status)) {
|
|
803
|
+
job.attempt++;
|
|
804
|
+
job.status = 'queued';
|
|
805
|
+
delete job.error;
|
|
806
|
+
this.jobs.save(job);
|
|
807
|
+
this.launch(job, value => this.runPack(value));
|
|
808
|
+
return this.view(job);
|
|
809
|
+
}
|
|
810
|
+
if (job.action === 'upgrade' && job.resumable && ['paused', 'failed'].includes(job.status)) {
|
|
811
|
+
job.attempt++;
|
|
812
|
+
job.status = 'queued';
|
|
813
|
+
delete job.error;
|
|
814
|
+
this.jobs.save(job);
|
|
815
|
+
this.launch(job, value => this.runUpgrade(value));
|
|
816
|
+
return this.view(job);
|
|
817
|
+
}
|
|
355
818
|
if (!job.resumable || job.action !== 'deploy' || !['paused', 'failed'].includes(job.status)) {
|
|
356
819
|
throw templateError('CONFLICT', 'This job cannot resume');
|
|
357
820
|
}
|
|
@@ -375,6 +838,9 @@ export class AgentTemplateService {
|
|
|
375
838
|
throw templateError('CONFLICT', 'Committed deployment cannot be cancelled');
|
|
376
839
|
if (['cancelled', 'succeeded'].includes(job.status))
|
|
377
840
|
return;
|
|
841
|
+
if (job.action === 'publish' && job.checkpoint.submitIntent) {
|
|
842
|
+
throw templateError('CONFLICT', 'Registry submission may have completed; query or resume the publication');
|
|
843
|
+
}
|
|
378
844
|
const previous = this.cancellations.get(jobId);
|
|
379
845
|
if (previous)
|
|
380
846
|
return previous;
|
|
@@ -385,7 +851,15 @@ export class AgentTemplateService {
|
|
|
385
851
|
const cancel = (async () => {
|
|
386
852
|
await this.work.get(jobId);
|
|
387
853
|
const current = this.jobs.read(jobId);
|
|
388
|
-
|
|
854
|
+
const beforeUpgradePreview = current.action === 'upgrade' && !current.args.previewId;
|
|
855
|
+
if (beforeUpgradePreview) {
|
|
856
|
+
if (current.activating || ['previewId', 'backupDir', 'executionPlanFile', 'executionConfirmedAt',
|
|
857
|
+
'resourcesApplied', 'runtimeStopped', 'originalProfile'].some(key => Object.hasOwn(current.checkpoint, key))) {
|
|
858
|
+
throw templateError('RECOVERY_REQUIRED', 'Upgrade execution state requires its original preview recovery');
|
|
859
|
+
}
|
|
860
|
+
await this.deps.authorize(current.actor, current.args.targetAid, current.jobId);
|
|
861
|
+
}
|
|
862
|
+
if (['deploy', 'upgrade'].includes(current.action) && current.args.previewId) {
|
|
389
863
|
const overwrite = this.previewRecord(current.args.previewId).installMode === 'overwrite';
|
|
390
864
|
const aid = Object.values(current.members)[0]?.aid;
|
|
391
865
|
const release = overwrite && aid ? await this.deps.hold(aid, current.jobId) : undefined;
|
|
@@ -408,9 +882,13 @@ export class AgentTemplateService {
|
|
|
408
882
|
await this.release(current, reason);
|
|
409
883
|
}
|
|
410
884
|
if (!current.freeze || current.freeze.state === 'released') {
|
|
885
|
+
if (beforeUpgradePreview)
|
|
886
|
+
current.checkpoint.restored = true;
|
|
411
887
|
current.status = 'cancelled';
|
|
412
888
|
current.phase = reason;
|
|
413
889
|
this.jobs.save(current);
|
|
890
|
+
if (beforeUpgradePreview)
|
|
891
|
+
await this.completeRecovery(current.args.targetAid);
|
|
414
892
|
}
|
|
415
893
|
})().finally(() => { this.cancellations.delete(jobId); });
|
|
416
894
|
this.cancellations.set(jobId, cancel);
|
|
@@ -425,19 +903,247 @@ export class AgentTemplateService {
|
|
|
425
903
|
const record = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
426
904
|
if (record.actor !== actor)
|
|
427
905
|
throw templateError('NOT_ALLOWED', 'Package belongs to another principal');
|
|
428
|
-
const pinned = this.jobs.list().some(job => job.args.packageId === packageId && job.action === 'deploy'
|
|
429
|
-
&& !job.committed && !job.checkpoint.restored
|
|
906
|
+
const pinned = this.jobs.list().some(job => job.args.packageId === packageId && (job.action === 'deploy'
|
|
907
|
+
&& !job.committed && !job.checkpoint.restored || job.action === 'publish'
|
|
908
|
+
&& !['succeeded', 'cancelled', 'failed'].includes(job.status)));
|
|
430
909
|
if (!pinned && record.createdAt < Date.now() - 7 * 86400_000)
|
|
431
910
|
throw templateError('EXPIRED', 'Package expired');
|
|
432
911
|
return record;
|
|
433
912
|
}
|
|
913
|
+
async publicationIdentity(actor, kind, context) {
|
|
914
|
+
if (!this.deps.publication)
|
|
915
|
+
throw templateError('NOT_CONFIGURED', 'Template publication runtime unavailable');
|
|
916
|
+
if (kind === 'agent') {
|
|
917
|
+
if (!context.executionAgentAid)
|
|
918
|
+
throw templateError('NOT_ALLOWED', 'Agent publishing requires a managed Agent session');
|
|
919
|
+
await this.deps.authorize(actor, context.executionAgentAid);
|
|
920
|
+
}
|
|
921
|
+
const aid = await this.deps.publication.identity(kind, context.executionAgentAid);
|
|
922
|
+
const expected = kind === 'agent' ? context.executionAgentAid : this.deps.hostAid;
|
|
923
|
+
if (!aid || aid !== expected)
|
|
924
|
+
throw templateError('NOT_ALLOWED', 'Publication connection does not match the selected identity');
|
|
925
|
+
return aid;
|
|
926
|
+
}
|
|
927
|
+
async publish(job) {
|
|
928
|
+
this.phase(job, 'validating');
|
|
929
|
+
const context = job.checkpoint.executionContext ?? {};
|
|
930
|
+
const kind = job.args.publisherIdentity ?? (context.executionAgentAid ? 'agent' : 'host');
|
|
931
|
+
const aid = await this.step(job, () => this.publicationIdentity(job.actor, kind, context));
|
|
932
|
+
if (job.checkpoint.publisherAid && job.checkpoint.publisherAid !== aid) {
|
|
933
|
+
throw templateError('PUBLISHER_MISMATCH', 'Original publication identity changed');
|
|
934
|
+
}
|
|
935
|
+
job.checkpoint.publisherAid = aid;
|
|
936
|
+
this.jobs.save(job);
|
|
937
|
+
const record = this.packageRecord(job.actor, job.args.packageId);
|
|
938
|
+
for (const sourceAid of record.provenance?.sourceAids ?? []) {
|
|
939
|
+
await this.step(job, () => this.deps.authorize(job.actor, sourceAid));
|
|
940
|
+
}
|
|
941
|
+
this.jobs.assertStatePath(record.data.file);
|
|
942
|
+
if (fs.statSync(record.data.file).size > templatePackage.PACKAGE_LIMITS.total) {
|
|
943
|
+
throw templateError('PACKAGE_TOO_LARGE', 'Publication package exceeds the package limit');
|
|
944
|
+
}
|
|
945
|
+
const bytes = fs.readFileSync(record.data.file);
|
|
946
|
+
const checked = templatePackage.inspectTemplatePackage(bytes, { digest: record.data.digest });
|
|
947
|
+
const size = bytes.length;
|
|
948
|
+
const metadata = checked.metadata;
|
|
949
|
+
if (metadata.publisher?.aid !== aid)
|
|
950
|
+
throw templateError('PUBLISHER_MISMATCH', 'Package publisher differs from the real Caller; pack again with publisherIdentity=' + kind);
|
|
951
|
+
const { registryAid } = job.args;
|
|
952
|
+
if (registryAid === aid)
|
|
953
|
+
throw templateError('INVALID_ARGUMENT', 'Publication registry must differ from the publisher');
|
|
954
|
+
const location = { aid, path: '/templates/' + metadata.id + '/' + metadata.id + '-' + metadata.version + '.ectpl' };
|
|
955
|
+
if (job.checkpoint.source && (job.checkpoint.source.digest !== checked.digest
|
|
956
|
+
|| job.checkpoint.source.location.aid !== aid || job.checkpoint.source.location.path !== location.path)) {
|
|
957
|
+
throw templateError('INTEGRITY_FAILED', 'Publication source differs from its saved snapshot');
|
|
958
|
+
}
|
|
959
|
+
job.result = { packageId: job.args.packageId, registryAid, publisher: metadata.publisher,
|
|
960
|
+
templateId: metadata.id, version: metadata.version, digest: checked.digest, size, sourceLocation: location,
|
|
961
|
+
...(job.checkpoint.serviceJobId ? { serviceJobId: job.checkpoint.serviceJobId } : {}) };
|
|
962
|
+
this.jobs.save(job);
|
|
963
|
+
if (!job.checkpoint.uploaded) {
|
|
964
|
+
this.phase(job, 'uploading');
|
|
965
|
+
await this.step(job, () => this.deps.upload(aid, location.path, record.data.file, true, context.executionAgentAid));
|
|
966
|
+
job.checkpoint.uploaded = true;
|
|
967
|
+
this.jobs.save(job);
|
|
968
|
+
}
|
|
969
|
+
if (!job.checkpoint.source) {
|
|
970
|
+
this.phase(job, 'granting');
|
|
971
|
+
const shareId = await this.step(job, () => this.deps.publication.grant(aid, location.path, registryAid, 'template-publish-' + job.jobId));
|
|
972
|
+
if (!/^[A-Za-z0-9]{10}$/.test(shareId))
|
|
973
|
+
throw templateError('SHARE_RESULT_UNKNOWN', 'Confirmed warehouse read authorization required');
|
|
974
|
+
job.checkpoint.source = { kind: 'remote', location, download: { shareId }, digest: checked.digest };
|
|
975
|
+
this.jobs.save(job);
|
|
976
|
+
}
|
|
977
|
+
if (!job.checkpoint.serviceJobId) {
|
|
978
|
+
this.phase(job, 'submitting');
|
|
979
|
+
job.checkpoint.submitIntent = true;
|
|
980
|
+
this.jobs.save(job);
|
|
981
|
+
const accepted = await this.step(job, () => this.deps.publication.call(aid, registryAid, 'publish', {
|
|
982
|
+
operationId: 'core-publish-' + job.jobId, source: job.checkpoint.source,
|
|
983
|
+
}, job.jobId));
|
|
984
|
+
if (!/^[a-f0-9]{64}$/.test(accepted?.jobId ?? '')) {
|
|
985
|
+
throw templateError('PUBLICATION_PENDING', 'Registry submission result is unconfirmed; resume the original job');
|
|
986
|
+
}
|
|
987
|
+
job.checkpoint.serviceJobId = accepted.jobId;
|
|
988
|
+
job.result.serviceJobId = accepted.jobId;
|
|
989
|
+
this.jobs.save(job);
|
|
990
|
+
}
|
|
991
|
+
this.phase(job, 'waiting_registry');
|
|
992
|
+
const deadline = Date.now() + 25_000;
|
|
993
|
+
do {
|
|
994
|
+
const status = await this.step(job, () => this.deps.publication.call(aid, registryAid, 'status', {
|
|
995
|
+
jobId: job.checkpoint.serviceJobId,
|
|
996
|
+
}, job.jobId));
|
|
997
|
+
if (status.jobId !== job.checkpoint.serviceJobId)
|
|
998
|
+
throw templateError('PUBLICATION_PENDING', 'Registry replied with another job');
|
|
999
|
+
if (status.state === 'completed') {
|
|
1000
|
+
if (status.ok !== true)
|
|
1001
|
+
throw templateError(status.error?.code ?? 'PUBLICATION_FAILED', status.error?.message ?? 'Registry publication failed', { remoteFailure: status.error?.code !== 'EXECUTION_UNKNOWN', serviceJobId: status.jobId });
|
|
1002
|
+
const result = status.result;
|
|
1003
|
+
const releaseId = templateFingerprint([aid, metadata.id, metadata.version]);
|
|
1004
|
+
if (!result || result.releaseId !== releaseId || result.publisher !== aid || result.templateId !== metadata.id
|
|
1005
|
+
|| result.version !== metadata.version || result.digest !== checked.digest || result.size !== size
|
|
1006
|
+
|| result.location?.aid !== registryAid || typeof result.location?.path !== 'string'
|
|
1007
|
+
|| !result.location.path.startsWith('/')) {
|
|
1008
|
+
throw templateError('PUBLICATION_PENDING', 'Registry release does not match the submitted package');
|
|
1009
|
+
}
|
|
1010
|
+
job.result = { ...job.result, releaseId, location: result.location, reused: result.reused === true,
|
|
1011
|
+
...(result.reviewStatus !== undefined ? { reviewStatus: result.reviewStatus } : {}),
|
|
1012
|
+
...(result.upgradeStatus !== undefined ? { upgradeStatus: result.upgradeStatus } : {}) };
|
|
1013
|
+
job.status = 'succeeded';
|
|
1014
|
+
job.phase = 'completed';
|
|
1015
|
+
job.resumable = false;
|
|
1016
|
+
this.jobs.save(job);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (!['queued', 'running'].includes(status.state))
|
|
1020
|
+
throw templateError('PUBLICATION_PENDING', 'Unconfirmed registry job state');
|
|
1021
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
1022
|
+
} while (Date.now() < deadline);
|
|
1023
|
+
throw templateError('PUBLICATION_PENDING', 'Registry job remains pending; resume the original publication', { serviceJobId: job.checkpoint.serviceJobId });
|
|
1024
|
+
}
|
|
1025
|
+
async storeRequest(job, aid, action, args, key) {
|
|
1026
|
+
const calls = job.checkpoint.storeCalls ??= {};
|
|
1027
|
+
const call = calls[key] ??= {};
|
|
1028
|
+
if (!call.jobId) {
|
|
1029
|
+
const accepted = await this.step(job, () => this.deps.publication.call(aid, job.args.storeAid, action, { ...args, operationId: 'core-store-' + job.jobId + '-' + key }, job.jobId + ':' + key));
|
|
1030
|
+
if (!/^[a-f0-9]{64}$/.test(accepted?.jobId ?? ''))
|
|
1031
|
+
throw templateError('INVALID_STORE_RESPONSE', 'Store jobId required');
|
|
1032
|
+
call.jobId = accepted.jobId;
|
|
1033
|
+
this.jobs.save(job);
|
|
1034
|
+
}
|
|
1035
|
+
const deadline = Date.now() + 25_000;
|
|
1036
|
+
do {
|
|
1037
|
+
const status = await this.step(job, () => this.deps.publication.call(aid, job.args.storeAid, 'status', { jobId: call.jobId }, job.jobId + ':' + key));
|
|
1038
|
+
if (status.jobId !== call.jobId)
|
|
1039
|
+
throw templateError('INVALID_STORE_RESPONSE', 'Store returned another job');
|
|
1040
|
+
if (status.state === 'completed') {
|
|
1041
|
+
if (status.ok !== true)
|
|
1042
|
+
throw templateError(status.error?.code ?? 'STORE_FAILED', status.error?.message ?? 'Store operation failed', { remoteFailure: status.error?.code !== 'EXECUTION_UNKNOWN', serviceJobId: call.jobId });
|
|
1043
|
+
if (!status.result || typeof status.result !== 'object' || Array.isArray(status.result)) {
|
|
1044
|
+
throw templateError('INVALID_STORE_RESPONSE', 'Store result object required');
|
|
1045
|
+
}
|
|
1046
|
+
return status.result;
|
|
1047
|
+
}
|
|
1048
|
+
if (!['queued', 'running'].includes(status.state))
|
|
1049
|
+
throw templateError('INVALID_STORE_RESPONSE', 'Unknown Store job state');
|
|
1050
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
1051
|
+
} while (Date.now() < deadline);
|
|
1052
|
+
throw templateError('STORE_PENDING', 'Store job remains pending; resume the original job', { serviceJobId: call.jobId });
|
|
1053
|
+
}
|
|
1054
|
+
async store(job) {
|
|
1055
|
+
const context = job.checkpoint.executionContext ?? {};
|
|
1056
|
+
const aid = await this.step(job, () => this.publicationIdentity(job.actor, context.executionAgentAid ? 'agent' : 'host', context));
|
|
1057
|
+
if (job.checkpoint.callerAid && job.checkpoint.callerAid !== aid)
|
|
1058
|
+
throw templateError('NOT_ALLOWED', 'Original Store Caller changed');
|
|
1059
|
+
job.checkpoint.callerAid = aid;
|
|
1060
|
+
this.jobs.save(job);
|
|
1061
|
+
if (job.action !== 'download') {
|
|
1062
|
+
this.phase(job, 'querying');
|
|
1063
|
+
const { storeAid: _storeAid, ...args } = job.args;
|
|
1064
|
+
job.result = await this.storeRequest(job, aid, job.action, args, job.action);
|
|
1065
|
+
}
|
|
1066
|
+
else {
|
|
1067
|
+
if (!job.checkpoint.storeRelease) {
|
|
1068
|
+
this.phase(job, 'resolving');
|
|
1069
|
+
const detail = await this.storeRequest(job, aid, 'detail', { releaseId: job.args.releaseId }, 'detail');
|
|
1070
|
+
const release = detail.release ?? detail;
|
|
1071
|
+
if (release.releaseId !== job.args.releaseId || !isValidAid(release.publisher ?? '')
|
|
1072
|
+
|| !/^sha256:[a-f0-9]{64}$/.test(release.digest ?? '') || !Number.isSafeInteger(release.size)
|
|
1073
|
+
|| release.size <= 0 || release.size > templatePackage.PACKAGE_LIMITS.total
|
|
1074
|
+
|| typeof release.templateId !== 'string' || typeof release.version !== 'string'
|
|
1075
|
+
|| release.releaseId !== templateFingerprint([release.publisher, release.templateId, release.version])) {
|
|
1076
|
+
throw templateError('INVALID_STORE_RESPONSE', 'Store release metadata is invalid');
|
|
1077
|
+
}
|
|
1078
|
+
job.checkpoint.storeRelease = release;
|
|
1079
|
+
job.checkpoint.downloadGeneration = 1;
|
|
1080
|
+
if (!job.args.path)
|
|
1081
|
+
job.checkpoint.packageId = 'package_' + randomUUID();
|
|
1082
|
+
this.jobs.save(job);
|
|
1083
|
+
}
|
|
1084
|
+
const release = job.checkpoint.storeRelease;
|
|
1085
|
+
if (job.checkpoint.downloadAuthorization && (job.checkpoint.downloadExpiresAt <= Date.now()
|
|
1086
|
+
|| job.checkpoint.downloadError === 'ACCESS_DENIED')) {
|
|
1087
|
+
job.checkpoint.downloadGeneration++;
|
|
1088
|
+
delete job.checkpoint.downloadAuthorization;
|
|
1089
|
+
delete job.checkpoint.downloadExpiresAt;
|
|
1090
|
+
delete job.checkpoint.downloadError;
|
|
1091
|
+
this.jobs.save(job);
|
|
1092
|
+
}
|
|
1093
|
+
this.phase(job, 'authorizing');
|
|
1094
|
+
const grant = job.checkpoint.downloadAuthorization ?? await this.storeRequest(job, aid, 'download', { releaseId: release.releaseId, targetHostAid: this.deps.hostAid }, 'download-' + job.checkpoint.downloadGeneration);
|
|
1095
|
+
const errors = templateContract.validateTemplateRequest({ requestId: job.requestId, action: 'pull', args: { source: grant.source,
|
|
1096
|
+
path: job.args.path ?? path.join(this.cache, 'packages', job.checkpoint.packageId, 'package.ectpl') } });
|
|
1097
|
+
if (errors.length || grant.source.kind !== 'remote' || grant.releaseId !== release.releaseId
|
|
1098
|
+
|| grant.targetHostAid !== this.deps.hostAid || grant.source.digest !== release.digest
|
|
1099
|
+
|| grant.source.location.aid !== job.args.storeAid || grant.size !== release.size
|
|
1100
|
+
|| release.location && templateFingerprint(grant.source.location) !== templateFingerprint(release.location)
|
|
1101
|
+
|| !Number.isFinite(grant.expiresInSeconds) || grant.expiresInSeconds <= 0) {
|
|
1102
|
+
throw templateError('INTEGRITY_FAILED', 'Download authorization differs from the fixed release or Host');
|
|
1103
|
+
}
|
|
1104
|
+
job.checkpoint.downloadAuthorization = grant;
|
|
1105
|
+
job.checkpoint.downloadExpiresAt ??= Date.now() + grant.expiresInSeconds * 1000;
|
|
1106
|
+
this.jobs.save(job);
|
|
1107
|
+
if (job.args.path && !path.isAbsolute(job.args.path))
|
|
1108
|
+
throw templateError('INVALID_ARGUMENT', 'Download path must be absolute');
|
|
1109
|
+
const directory = job.args.path ? path.dirname(job.args.path) : path.join(this.cache, 'packages', job.checkpoint.packageId);
|
|
1110
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
1111
|
+
const file = job.args.path ?? path.join(directory, 'package.ectpl');
|
|
1112
|
+
fs.rmSync(file, { force: true });
|
|
1113
|
+
this.phase(job, 'downloading');
|
|
1114
|
+
try {
|
|
1115
|
+
await this.step(job, () => this.deps.download(grant.source.download?.shareId, file, grant.source.location, release.size));
|
|
1116
|
+
}
|
|
1117
|
+
catch (error) {
|
|
1118
|
+
job.checkpoint.downloadError = error.code;
|
|
1119
|
+
this.jobs.save(job);
|
|
1120
|
+
fs.rmSync(file, { force: true });
|
|
1121
|
+
throw error;
|
|
1122
|
+
}
|
|
1123
|
+
this.phase(job, 'verifying');
|
|
1124
|
+
const data = await this.executeTool(job, 'read-package', { archivePath: file, digest: release.digest });
|
|
1125
|
+
if (fs.statSync(file).size !== release.size || data.metadata.id !== release.templateId
|
|
1126
|
+
|| data.metadata.version !== release.version || data.publisher?.aid !== release.publisher) {
|
|
1127
|
+
throw templateError('INTEGRITY_FAILED', 'Downloaded package differs from the fixed Store release');
|
|
1128
|
+
}
|
|
1129
|
+
// Only resumed historical downloads use the old package registry.
|
|
1130
|
+
if (!job.args.path)
|
|
1131
|
+
writeTemplateState(path.join(directory, 'record.json'), { actor: job.actor, packageId: job.checkpoint.packageId,
|
|
1132
|
+
createdAt: Date.now(), data: { ...data, file }, provenance: { kind: 'import', source: grant.source,
|
|
1133
|
+
registryAid: job.args.storeAid, release } });
|
|
1134
|
+
job.result = { ...data, path: file, ...(job.args.path ? {} : { packageId: job.checkpoint.packageId }),
|
|
1135
|
+
storeAid: job.args.storeAid, releaseId: release.releaseId,
|
|
1136
|
+
reviewStatus: release.reviewStatus, upgradeStatus: release.upgradeStatus };
|
|
1137
|
+
}
|
|
1138
|
+
job.status = 'succeeded';
|
|
1139
|
+
job.phase = 'completed';
|
|
1140
|
+
job.resumable = false;
|
|
1141
|
+
this.jobs.save(job);
|
|
1142
|
+
}
|
|
434
1143
|
async push(job) {
|
|
435
1144
|
const record = this.packageRecord(job.actor, job.args.packageId);
|
|
436
1145
|
for (const aid of record.provenance.sourceAids ?? [])
|
|
437
|
-
await this.step(job, () => this.deps.authorize(job.actor, aid));
|
|
438
|
-
if (record.data.scan.findings.some((item) => !job.args.releasedFindings.includes(item.id))) {
|
|
439
|
-
throw templateError('SCAN_BLOCKED', 'Release the package scan findings before upload');
|
|
440
|
-
}
|
|
1146
|
+
await this.step(job, () => this.deps.authorize(job.actor, aid, job.action === 'upgrade' ? job.jobId : undefined));
|
|
441
1147
|
const { aid, path: remote } = job.args.location;
|
|
442
1148
|
const metadata = record.data.metadata;
|
|
443
1149
|
if (remote !== '/templates/' + metadata.id + '/' + metadata.id + '-' + metadata.version + '.ectpl') {
|
|
@@ -446,7 +1152,10 @@ export class AgentTemplateService {
|
|
|
446
1152
|
this.phase(job, 'uploading');
|
|
447
1153
|
job.checkpoint.uploadIntent = true;
|
|
448
1154
|
this.jobs.save(job);
|
|
449
|
-
|
|
1155
|
+
const executor = job.checkpoint.executionContext?.executionAgentAid;
|
|
1156
|
+
if (executor && aid === executor)
|
|
1157
|
+
await this.deps.authorize(job.actor, executor);
|
|
1158
|
+
await this.step(job, () => this.deps.upload(aid, remote, record.data.file, true, executor));
|
|
450
1159
|
job.result = { packageId: record.packageId, location: job.args.location, digest: record.data.digest,
|
|
451
1160
|
size: record.data.size, metadata };
|
|
452
1161
|
job.status = 'succeeded';
|
|
@@ -455,79 +1164,204 @@ export class AgentTemplateService {
|
|
|
455
1164
|
}
|
|
456
1165
|
async pull(job) {
|
|
457
1166
|
const source = job.args.source;
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
1167
|
+
let file = source.kind === 'artifact' ? this.packageRecord(job.actor, source.packageId).data.file
|
|
1168
|
+
: source.kind === 'file' ? source.path : job.args.path;
|
|
1169
|
+
let temporaryDirectory;
|
|
1170
|
+
if (source.kind === 'remote' && file === undefined) {
|
|
1171
|
+
const context = job.checkpoint.executionContext;
|
|
1172
|
+
const tempRoot = context?.executionAgentAid ? context.runtimeDir : process.env.TMPDIR;
|
|
1173
|
+
if (!tempRoot || !path.isAbsolute(tempRoot))
|
|
1174
|
+
throw templateError('TEMP_UNAVAILABLE', 'Template pull requires an absolute managed TMPDIR');
|
|
1175
|
+
fs.mkdirSync(tempRoot, { recursive: true });
|
|
1176
|
+
temporaryDirectory = fs.mkdtempSync(path.join(tempRoot, 'template-pull-'));
|
|
1177
|
+
file = path.join(temporaryDirectory, 'package.ectpl');
|
|
462
1178
|
}
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
1179
|
+
if (typeof file !== 'string' || !path.isAbsolute(file)) {
|
|
1180
|
+
throw templateError('INVALID_ARGUMENT', 'An absolute destination path is required; existing files can be previewed directly');
|
|
1181
|
+
}
|
|
1182
|
+
const destination = file;
|
|
1183
|
+
try {
|
|
1184
|
+
if (source.kind === 'remote') {
|
|
1185
|
+
if (!temporaryDirectory)
|
|
1186
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
1187
|
+
await this.step(job, () => this.deps.download(source.download?.shareId, destination, source.location));
|
|
1188
|
+
}
|
|
1189
|
+
const data = await this.executeTool(job, 'read-package', { archivePath: destination, digest: source.digest });
|
|
1190
|
+
job.result = { ...data, path: destination, ...(job.args.registryAid ? { storeAid: job.args.registryAid } : {}) };
|
|
1191
|
+
job.status = 'succeeded';
|
|
1192
|
+
job.phase = 'completed';
|
|
468
1193
|
this.jobs.save(job);
|
|
469
|
-
const archivePath = path.join(directory, 'package.ectpl');
|
|
470
|
-
if (source.kind === 'remote')
|
|
471
|
-
await this.step(job, () => this.deps.download(source.download?.shareId, archivePath, source.location));
|
|
472
|
-
else
|
|
473
|
-
fs.copyFileSync(source.path, archivePath);
|
|
474
|
-
const data = await this.executeTool(job, 'read-package', { archivePath, digest: source.digest });
|
|
475
|
-
writeTemplateState(path.join(directory, 'record.json'), { actor: job.actor, packageId, createdAt: Date.now(),
|
|
476
|
-
data: { ...data, file: archivePath }, provenance: { kind: 'import', source } });
|
|
477
|
-
job.result = { ...data, packageId };
|
|
478
1194
|
}
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
1195
|
+
catch (error) {
|
|
1196
|
+
if (temporaryDirectory) {
|
|
1197
|
+
try {
|
|
1198
|
+
fs.rmSync(destination, { force: true });
|
|
1199
|
+
fs.rmdirSync(temporaryDirectory);
|
|
1200
|
+
}
|
|
1201
|
+
catch (cleanupError) {
|
|
1202
|
+
logger.warn('[Template] Failed to remove temporary pull output: ' + String(cleanupError));
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
throw error;
|
|
1206
|
+
}
|
|
482
1207
|
}
|
|
483
1208
|
previewRecord(id) {
|
|
484
1209
|
if (!TEMPLATE_PREVIEW_ID.test(id))
|
|
485
1210
|
throw templateError('INVALID_ARGUMENT', 'Invalid previewId');
|
|
486
1211
|
return JSON.parse(fs.readFileSync(path.join(this.cache, 'previews', id, 'record.json'), 'utf8'));
|
|
487
1212
|
}
|
|
488
|
-
async preview(job) {
|
|
489
|
-
const
|
|
490
|
-
|
|
491
|
-
if (
|
|
492
|
-
|
|
1213
|
+
async preview(job, overrideArgs, update) {
|
|
1214
|
+
const args = overrideArgs ?? job.args;
|
|
1215
|
+
let record;
|
|
1216
|
+
if (args.path) {
|
|
1217
|
+
if (!path.isAbsolute(args.path))
|
|
1218
|
+
throw templateError('INVALID_ARGUMENT', 'Template path must be absolute');
|
|
1219
|
+
const data = await this.executeTool(job, 'read-package', { archivePath: args.path, ...(update ? { digest: update.release.digest } : {}) });
|
|
1220
|
+
// Source attribution comes from a successful owned job for these exact bytes, not the file name.
|
|
1221
|
+
const downloaded = this.jobs.list().filter(value => value.actor === job.actor && value.status === 'succeeded'
|
|
1222
|
+
&& ['download', 'pull'].includes(value.action) && value.result?.path === args.path
|
|
1223
|
+
&& value.result?.digest === data.digest && value.result?.storeAid)
|
|
1224
|
+
.sort((left, right) => right.createdAt - left.createdAt)[0];
|
|
1225
|
+
record = { data: { ...data, file: args.path }, provenance: {
|
|
1226
|
+
registryAid: downloaded?.result?.storeAid, release: downloaded?.checkpoint.storeRelease
|
|
1227
|
+
} };
|
|
1228
|
+
}
|
|
1229
|
+
else
|
|
1230
|
+
record = this.packageRecord(job.actor, args.packageId);
|
|
1231
|
+
const keys = update ? [update.source.key] : Object.keys(record.data.members).sort();
|
|
1232
|
+
if (keys.join() !== Object.keys(args.members).sort().join()
|
|
1233
|
+
|| args.installMode === 'overwrite' && keys.length !== 1)
|
|
493
1234
|
throw templateError('INVALID_ARGUMENT', 'Map every member; overwrite allows one');
|
|
494
1235
|
const previewId = 'preview_' + randomUUID();
|
|
495
1236
|
const out = path.join(this.cache, 'previews', previewId);
|
|
496
1237
|
const members = {};
|
|
497
1238
|
const targets = {};
|
|
498
1239
|
const snapshot = this.deps.installation.hostSnapshot();
|
|
1240
|
+
const projectKey = (project) => process.platform === 'win32' ? project.toLowerCase() : project;
|
|
1241
|
+
// Explicit selections reserve their names before automatic allocation, including later members.
|
|
1242
|
+
const selectedProjects = new Set(Object.values(args.members).flatMap((selected) => typeof selected.target.project === 'string' && path.isAbsolute(selected.target.project)
|
|
1243
|
+
? [projectKey(path.resolve(selected.target.project))] : []));
|
|
499
1244
|
for (const key of keys) {
|
|
500
|
-
const selected =
|
|
1245
|
+
const selected = args.members[key];
|
|
501
1246
|
const target = selected.target;
|
|
502
|
-
const aid = target.aid === 'auto' ? 'a' + randomUUID().replace(/-/g, '').slice(0, 14) + '.' +
|
|
503
|
-
|
|
504
|
-
|
|
1247
|
+
const aid = target.aid === 'auto' ? 'a' + randomUUID().replace(/-/g, '').slice(0, 14) + '.' + args.defaultAidDomain : target.aid;
|
|
1248
|
+
let project = target.project;
|
|
1249
|
+
if (args.installMode === 'create') {
|
|
1250
|
+
try {
|
|
1251
|
+
if (project === undefined) {
|
|
1252
|
+
const root = agentProjectRootFromDefaults(snapshot.defaults, this.deps.root);
|
|
1253
|
+
project = deriveAgentProjectPath(root, aid, {
|
|
1254
|
+
existsSync: candidate => fs.existsSync(candidate) || selectedProjects.has(projectKey(candidate)),
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
if (typeof project !== 'string' || !project.trim() || project.includes('\0') || !path.isAbsolute(project)) {
|
|
1258
|
+
throw templateError('INVALID_ARGUMENT', 'Project directory must be an absolute path on the target host');
|
|
1259
|
+
}
|
|
1260
|
+
project = path.resolve(project);
|
|
1261
|
+
this.deps.installation.available(aid, project);
|
|
1262
|
+
selectedProjects.add(projectKey(project));
|
|
1263
|
+
}
|
|
1264
|
+
catch (error) {
|
|
1265
|
+
throw templateError(error.code ?? 'INVALID_ARGUMENT', `Member ${key} project directory: ${error.message}`, { memberKey: key, stage: 'resolve_project', field: `args.members.${key}.target.project`,
|
|
1266
|
+
...(error.details ? { cause: error.details } : {}) });
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
505
1269
|
else {
|
|
506
|
-
await this.step(job, () => this.deps.authorize(job.actor, aid));
|
|
1270
|
+
await this.step(job, () => this.deps.authorize(job.actor, aid, job.action === 'upgrade' ? job.jobId : undefined));
|
|
507
1271
|
targets[key] = await this.step(job, () => this.deps.target(aid, job.actor));
|
|
1272
|
+
if (targets[key].targetConfig?.update?.mode === 'disabled')
|
|
1273
|
+
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before overwrite');
|
|
1274
|
+
if (!update && this.jobs.installation(aid))
|
|
1275
|
+
throw templateError('USE_UPDATE_PREVIEW', 'Bound Agents require the fixed-candidate update preview');
|
|
508
1276
|
if (targets[key].projectPath !== target.project)
|
|
509
1277
|
throw templateError('TARGET_CHANGED', 'Overwrite must use the current default project');
|
|
510
1278
|
}
|
|
511
|
-
members[key] = { aid, projectPath: path.resolve(
|
|
1279
|
+
members[key] = { aid, projectPath: path.resolve(project), requestId: randomUUID() };
|
|
1280
|
+
}
|
|
1281
|
+
if (update) {
|
|
1282
|
+
const targetAid = job.args.targetAid;
|
|
1283
|
+
for (const other of this.deps.updates.targets().filter(value => value.aid !== targetAid)) {
|
|
1284
|
+
const project = members[keys[0]].projectPath;
|
|
1285
|
+
if (other.projectPath === project || other.projectPath.startsWith(project + path.sep) || project.startsWith(other.projectPath + path.sep)) {
|
|
1286
|
+
throw templateError('SHARED_RESOURCE_CONFLICT', 'The target workspace is shared with another Agent', { affectedAids: [other.aid] });
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
512
1289
|
}
|
|
513
1290
|
const values = Object.values(members);
|
|
1291
|
+
const identityAids = new Set([job.actor, this.deps.hostAid, ...values.map(member => member.aid)]);
|
|
1292
|
+
if (record.data.memberReferences?.external?.some((contact) => identityAids.has(contact.aid))) {
|
|
1293
|
+
throw templateError('CONFLICT', 'External AID conflicts with a Team identity');
|
|
1294
|
+
}
|
|
514
1295
|
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
1296
|
|| right.projectPath.startsWith(left.projectPath + path.sep)))))
|
|
516
1297
|
throw templateError('INVALID_ARGUMENT', 'Targets or projects overlap');
|
|
1298
|
+
const selections = structuredClone(args.members);
|
|
1299
|
+
const modelBindings = {};
|
|
1300
|
+
const modelWarnings = [];
|
|
1301
|
+
if (this.deps.resolveModels)
|
|
1302
|
+
for (const key of keys) {
|
|
1303
|
+
const resolved = await this.step(job, () => this.deps.resolveModels({ config: record.data.members[key].config ?? {},
|
|
1304
|
+
selections: selections[key].providers ?? {}, providers: targets[key]?.providers ?? snapshot.providers, defaults: snapshot.defaults,
|
|
1305
|
+
local: targets[key]?.effectiveConfig ?? targets[key]?.targetConfig, preferLocal: !!update }));
|
|
1306
|
+
selections[key].providers = resolved.selections;
|
|
1307
|
+
modelBindings[key] = resolved.binding;
|
|
1308
|
+
modelWarnings.push(...resolved.warnings.map(warning => ({ memberKey: key, ...warning })));
|
|
1309
|
+
}
|
|
1310
|
+
if (update && !this.deps.resolveModels)
|
|
1311
|
+
for (const key of keys) {
|
|
1312
|
+
const declared = record.data.members[key].config ?? {};
|
|
1313
|
+
const local = targets[key].effectiveConfig ?? targets[key].targetConfig;
|
|
1314
|
+
const active = declared.active_baseagent ?? local.active_baseagent;
|
|
1315
|
+
const baseagents = [...new Set([...Object.keys(declared.baseagents ?? {}), active])];
|
|
1316
|
+
selections[key].providers ??= {};
|
|
1317
|
+
for (const name of baseagents) {
|
|
1318
|
+
if (selections[key].providers[name])
|
|
1319
|
+
continue;
|
|
1320
|
+
const provider = local.baseagents?.[name]?.provider;
|
|
1321
|
+
if (!publicTemplate.providerUsable(targets[key].providers ?? {}, provider, name)) {
|
|
1322
|
+
if (name !== active)
|
|
1323
|
+
continue;
|
|
1324
|
+
throw templateError('UNRESOLVED', 'Current local Provider binding is unavailable for ' + name, { memberKey: key, baseagent: name });
|
|
1325
|
+
}
|
|
1326
|
+
selections[key].providers[name] = { provider };
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
517
1329
|
const data = await this.executeTool(job, 'preview', { archivePath: record.data.file, digest: record.data.digest,
|
|
518
|
-
installMode:
|
|
1330
|
+
installMode: args.installMode, members, targets, selections,
|
|
519
1331
|
out, home: this.deps.root, ownerAid: job.actor, hostAid: this.deps.hostAid,
|
|
1332
|
+
...(record.provenance?.registryAid ? { registryAid: record.provenance.registryAid } : {}),
|
|
1333
|
+
...(update ? { sourceMemberKey: keys[0], update: { key: update.source.key, version: update.release.version, digest: update.release.digest,
|
|
1334
|
+
manifest: update.oldManifest,
|
|
1335
|
+
otherAgents: this.deps.updates.targets().filter(target => target.aid !== job.args.targetAid).map(target => target.aid) } } : {}),
|
|
520
1336
|
agentSchemaVersion: snapshot.schemaVersion, providers: snapshot.providers });
|
|
521
1337
|
const plans = {};
|
|
522
|
-
const
|
|
1338
|
+
const modelUnavailable = [];
|
|
1339
|
+
const unresolved = [...(data.update?.unresolved ?? [])];
|
|
1340
|
+
for (const member of data.members)
|
|
1341
|
+
for (const skill of member.preview?.skills ?? []) {
|
|
1342
|
+
if (skill.conflict && !skill.conflict.resolution)
|
|
1343
|
+
unresolved.push({ memberKey: member.key,
|
|
1344
|
+
code: 'SKILL_CONFLICT', message: `技能 ${skill.installAs} 与主机已有内容不同,请选择覆盖或跳过。` });
|
|
1345
|
+
}
|
|
523
1346
|
for (const key of keys) {
|
|
524
1347
|
const config = data.configs[key];
|
|
525
1348
|
const baseagent = config.active_baseagent;
|
|
526
1349
|
const model = config.baseagents?.[baseagent];
|
|
527
1350
|
const profile = data.profiles[key];
|
|
1351
|
+
if (!model?.provider || !model?.model)
|
|
1352
|
+
modelUnavailable.push(key);
|
|
528
1353
|
try {
|
|
529
1354
|
await this.step(job, () => this.deps.validateModels(config, data.members.find((member) => member.key === key).providers));
|
|
530
|
-
|
|
1355
|
+
}
|
|
1356
|
+
catch (error) {
|
|
1357
|
+
this.current(job);
|
|
1358
|
+
if (!modelUnavailable.includes(key))
|
|
1359
|
+
modelUnavailable.push(key);
|
|
1360
|
+
modelWarnings.push({ memberKey: key, code: error.code ?? 'MODEL_UNAVAILABLE',
|
|
1361
|
+
message: `模型配置未就绪,安装后可能需要补充配置:${error.message}` });
|
|
1362
|
+
}
|
|
1363
|
+
try {
|
|
1364
|
+
if (args.installMode === 'create') {
|
|
531
1365
|
const plan = { aid: members[key].aid, project: members[key].projectPath, baseagent,
|
|
532
1366
|
provider: model?.provider, model: model?.model, effort: model?.effort, chatmode: config.chatmode,
|
|
533
1367
|
ownerAid: job.actor, name: profile.name, description: profile.description || 'EvolCore template member.',
|
|
@@ -540,21 +1374,67 @@ export class AgentTemplateService {
|
|
|
540
1374
|
unresolved.push({ memberKey: key, code: error.code ?? 'UNRESOLVED', message: error.message });
|
|
541
1375
|
}
|
|
542
1376
|
}
|
|
1377
|
+
let updateRecord;
|
|
1378
|
+
if (update) {
|
|
1379
|
+
const targetAid = job.args.targetAid;
|
|
1380
|
+
updateRecord = { source: update.source, release: update.release, lock: update.lock, oldVersion: update.oldVersion,
|
|
1381
|
+
oldManifest: update.oldManifest, mode: update.mode, summary: update.summary,
|
|
1382
|
+
nextInstallation: { targetAid, ownerAid: job.actor, hostAid: this.deps.hostAid, projectPath: members[keys[0]].projectPath,
|
|
1383
|
+
source: update.source, release: update.release, baseline: { known: false } } };
|
|
1384
|
+
const plan = JSON.parse(fs.readFileSync(data.planFile, 'utf8'));
|
|
1385
|
+
plan.update = updateRecord;
|
|
1386
|
+
writeTemplateState(data.planFile, plan);
|
|
1387
|
+
}
|
|
543
1388
|
const planDigest = unresolved.length ? null : 'sha256:' + templateFingerprint(JSON.parse(fs.readFileSync(data.planFile, 'utf8')));
|
|
544
1389
|
const preview = { actor: job.actor, previewId, packageId: record.packageId, createdAt: Date.now(),
|
|
545
|
-
|
|
1390
|
+
...(args.path ? { sourcePath: args.path, source: { size: record.data.size, release: record.provenance?.release } } : {}),
|
|
1391
|
+
installMode: args.installMode, snapshot: templateFingerprint(snapshot), members, plans, planDigest, data, modelUnavailable,
|
|
1392
|
+
...(updateRecord ? { update: updateRecord } : {}) };
|
|
546
1393
|
writeTemplateState(path.join(out, 'record.json'), preview);
|
|
547
|
-
job.result = { previewId, planDigest,
|
|
1394
|
+
job.result = { previewId, planDigest, ...(record.packageId ? { packageId: record.packageId } : {}),
|
|
1395
|
+
path: record.data.file, digest: record.data.digest, metadata: record.data.metadata,
|
|
548
1396
|
installMode: preview.installMode, members: Object.fromEntries(keys.map(key => [key, {
|
|
549
|
-
target: { aid: members[key].aid, project: members[key].projectPath }, changes: data.members.find((member) => member.key === key)
|
|
1397
|
+
target: { aid: members[key].aid, project: members[key].projectPath }, changes: data.members.find((member) => member.key === key),
|
|
1398
|
+
...(modelBindings[key] ? { models: modelBindings[key] } : {}),
|
|
1399
|
+
...(keys.length === 1 && isValidAid(key) ? { installation: {
|
|
1400
|
+
version: data.configs[key].version ?? null, update: data.configs[key].update ?? null,
|
|
1401
|
+
recordPlanned: !update && data.configs[key].update?.key === key,
|
|
1402
|
+
} } : {})
|
|
550
1403
|
}])),
|
|
551
1404
|
bindingOwnerAid: job.actor, expiresAt: preview.createdAt + 3600_000, executable: !unresolved.length, unresolved,
|
|
552
|
-
changes: data.changes ?? [], ignored: data.ignored ?? [], warnings: data.warnings ?? [] };
|
|
1405
|
+
changes: data.changes ?? [], ignored: data.ignored ?? [], warnings: [...(data.warnings ?? []), ...modelWarnings] };
|
|
1406
|
+
if (update) {
|
|
1407
|
+
const previousPreviewId = job.checkpoint.previewId;
|
|
1408
|
+
if (previousPreviewId && previousPreviewId !== previewId) {
|
|
1409
|
+
job.checkpoint.previousPreviewIds = [...(job.checkpoint.previousPreviewIds ?? []), previousPreviewId];
|
|
1410
|
+
}
|
|
1411
|
+
job.result = { targetAid: job.args.targetAid, candidate: update.release, summary: update.summary, previewId, planDigest,
|
|
1412
|
+
executable: !unresolved.length, unresolved, members: job.result.members, warnings: job.result.warnings,
|
|
1413
|
+
...(previousPreviewId ? { previousPreviewId } : {}) };
|
|
1414
|
+
job.args.previewId = previewId;
|
|
1415
|
+
job.checkpoint.previewId = previewId;
|
|
1416
|
+
this.jobs.save(job);
|
|
1417
|
+
if (unresolved.length)
|
|
1418
|
+
throw templateError('UNRESOLVED', 'Candidate cannot be installed', { unresolved });
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
553
1421
|
job.status = 'succeeded';
|
|
554
1422
|
job.phase = 'completed';
|
|
555
1423
|
this.jobs.save(job);
|
|
556
1424
|
}
|
|
557
1425
|
async deploy(actor, requestId, args) {
|
|
1426
|
+
const record = this.previewRecord(args.previewId);
|
|
1427
|
+
if (record.installMode === 'overwrite') {
|
|
1428
|
+
const aid = Object.values(record.members)[0];
|
|
1429
|
+
return withFileLock(path.join(this.cache, 'update-targets', templateFingerprint(aid.aid) + '.lock'), () => this.acceptDeployment(actor, requestId, args, record));
|
|
1430
|
+
}
|
|
1431
|
+
return this.acceptDeployment(actor, requestId, args, record);
|
|
1432
|
+
}
|
|
1433
|
+
async acceptDeployment(actor, requestId, args, record) {
|
|
1434
|
+
if (record.actor !== actor)
|
|
1435
|
+
throw templateError('NOT_ALLOWED', 'Preview belongs to another principal');
|
|
1436
|
+
if (!record.planDigest || record.planDigest !== args.planDigest)
|
|
1437
|
+
throw templateError('CONFLICT', 'Executable preview and matching planDigest required');
|
|
558
1438
|
const prior = this.jobs.list().find(job => job.actor === actor && job.action === 'deploy' && job.args.previewId === args.previewId);
|
|
559
1439
|
if (prior) {
|
|
560
1440
|
if (prior.fingerprint !== templateFingerprint({ action: 'deploy', args }))
|
|
@@ -562,15 +1442,27 @@ export class AgentTemplateService {
|
|
|
562
1442
|
this.jobs.bindRequest(actor, requestId, 'deploy', args, prior.jobId);
|
|
563
1443
|
return this.view(prior);
|
|
564
1444
|
}
|
|
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
1445
|
if (record.createdAt + 3600_000 <= Date.now())
|
|
571
1446
|
throw templateError('EXPIRED', 'Preview expired');
|
|
572
1447
|
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
573
1448
|
throw templateError('TARGET_CHANGED', 'Host configuration changed');
|
|
1449
|
+
if (record.installMode === 'overwrite') {
|
|
1450
|
+
const aid = Object.values(record.members)[0].aid;
|
|
1451
|
+
const active = this.jobs.list().find(job => ['deploy', 'upgrade'].includes(job.action) && !job.committed && !job.checkpoint.restored
|
|
1452
|
+
&& Object.values(job.members).some(member => member.aid === aid));
|
|
1453
|
+
if (active)
|
|
1454
|
+
throw templateError('CONFLICT', 'Resume the original target job', { jobId: active.jobId });
|
|
1455
|
+
if (record.update)
|
|
1456
|
+
await this.verifyUpdatePreview(actor, record);
|
|
1457
|
+
else {
|
|
1458
|
+
await this.deps.authorize(actor, aid);
|
|
1459
|
+
const target = await this.deps.target(aid, actor);
|
|
1460
|
+
if (target.targetConfig?.update?.mode === 'disabled')
|
|
1461
|
+
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before overwrite');
|
|
1462
|
+
if (this.jobs.installation(aid))
|
|
1463
|
+
throw templateError('USE_UPDATE_PREVIEW', 'Bound Agents require the fixed-candidate update preview');
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
574
1466
|
const accepted = this.jobs.accept(actor, requestId, 'deploy', args, structuredClone(record.members));
|
|
575
1467
|
accepted.job.resumable = true;
|
|
576
1468
|
this.jobs.save(accepted.job);
|
|
@@ -592,7 +1484,7 @@ export class AgentTemplateService {
|
|
|
592
1484
|
this.mutations = new Promise(resolve => { release = resolve; });
|
|
593
1485
|
await previous.catch(() => undefined);
|
|
594
1486
|
try {
|
|
595
|
-
await this.install(job);
|
|
1487
|
+
await withFileLock(path.join(this.cache, 'jobs', job.jobId + '.execution.lock'), () => this.install(job));
|
|
596
1488
|
}
|
|
597
1489
|
finally {
|
|
598
1490
|
release();
|
|
@@ -601,6 +1493,13 @@ export class AgentTemplateService {
|
|
|
601
1493
|
async install(job) {
|
|
602
1494
|
this.current(job);
|
|
603
1495
|
const record = JSON.parse(fs.readFileSync(path.join(this.cache, 'previews', job.args.previewId, 'record.json'), 'utf8'));
|
|
1496
|
+
if (record.sourcePath && !job.committed && !job.checkpoint.resourcesApplied) {
|
|
1497
|
+
if (!fs.existsSync(record.sourcePath))
|
|
1498
|
+
throw templateError('NOT_FOUND', 'Template file is missing; download it again to the same path');
|
|
1499
|
+
const digest = 'sha256:' + createHash('sha256').update(fs.readFileSync(record.sourcePath)).digest('hex');
|
|
1500
|
+
if (digest !== record.data.digest)
|
|
1501
|
+
throw templateError('SOURCE_CHANGED', 'Template file changed; preview it again before installing');
|
|
1502
|
+
}
|
|
604
1503
|
if (record.installMode === 'overwrite')
|
|
605
1504
|
return this.runOverwrite(job, record);
|
|
606
1505
|
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
@@ -608,9 +1507,8 @@ export class AgentTemplateService {
|
|
|
608
1507
|
const plan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
609
1508
|
if (record.planDigest !== 'sha256:' + templateFingerprint(plan))
|
|
610
1509
|
throw templateError('CONFLICT', 'Frozen team plan changed');
|
|
611
|
-
for (const
|
|
1510
|
+
for (const key of Object.keys(record.data.configs)) {
|
|
612
1511
|
await this.step(job, () => this.deps.installation.validatePlan(record.plans[key]));
|
|
613
|
-
await this.step(job, () => this.deps.validateModels(config, record.data.members.find((member) => member.key === key).providers));
|
|
614
1512
|
}
|
|
615
1513
|
const legacyProfiles = false;
|
|
616
1514
|
if (job.checkpoint.resourcesApplied)
|
|
@@ -677,7 +1575,7 @@ export class AgentTemplateService {
|
|
|
677
1575
|
job.activating = true;
|
|
678
1576
|
job.phase = 'activating';
|
|
679
1577
|
this.jobs.save(job);
|
|
680
|
-
for (const member of Object.
|
|
1578
|
+
for (const [key, member] of Object.entries(job.members)) {
|
|
681
1579
|
await this.step(job, () => this.deps.installation.authorize(job.actor));
|
|
682
1580
|
await this.step(job, () => this.deps.installation.verify(member.aid));
|
|
683
1581
|
member.phase = 'activating';
|
|
@@ -690,8 +1588,10 @@ export class AgentTemplateService {
|
|
|
690
1588
|
return;
|
|
691
1589
|
}
|
|
692
1590
|
member.phase = 'active';
|
|
693
|
-
member.runtimeReady =
|
|
1591
|
+
member.runtimeReady = this.deps.installation.ready(member.aid);
|
|
694
1592
|
this.jobs.save(job);
|
|
1593
|
+
if (!member.runtimeReady && !record.modelUnavailable?.includes(key))
|
|
1594
|
+
throw templateError('TEAM_NOT_READY', 'A prepared member is unavailable');
|
|
695
1595
|
}
|
|
696
1596
|
this.current(job);
|
|
697
1597
|
job.phase = 'verifying';
|
|
@@ -699,17 +1599,15 @@ export class AgentTemplateService {
|
|
|
699
1599
|
await this.step(job, () => this.executeTool(job, 'verify-installation', { planFile: record.data.planFile }));
|
|
700
1600
|
for (const [key, member] of Object.entries(job.members)) {
|
|
701
1601
|
await this.step(job, () => this.deps.installation.verify(member.aid));
|
|
702
|
-
if (!this.deps.installation.ready(member.aid))
|
|
1602
|
+
if (!this.deps.installation.ready(member.aid) && !record.modelUnavailable?.includes(key))
|
|
703
1603
|
throw templateError('TEAM_NOT_READY', 'A prepared member is unavailable');
|
|
704
1604
|
await this.publishProfile(job, key, { ...record.data.profiles[key], description: record.plans[key].description }, false);
|
|
705
1605
|
}
|
|
706
1606
|
await this.step(job, () => this.deps.installation.authorize(job.actor));
|
|
707
1607
|
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
708
1608
|
throw templateError('CONFLICT', 'Host configuration changed before team commit');
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
members: Object.entries(job.members).map(([key, member]) => ({ key, aid: member.aid, project: member.projectPath, profile: record.data.profiles[key] })),
|
|
712
|
-
});
|
|
1609
|
+
await this.prepareInitialInstallation(job, record, path.join(path.dirname(record.data.planFile), 'creation-plan.json'));
|
|
1610
|
+
job.checkpoint.modelUnavailable = record.modelUnavailable ?? [];
|
|
713
1611
|
job.committed = true;
|
|
714
1612
|
job.activating = false;
|
|
715
1613
|
job.status = 'succeeded';
|
|
@@ -719,8 +1617,72 @@ export class AgentTemplateService {
|
|
|
719
1617
|
installMode: record.installMode, committed: true, members: Object.fromEntries(Object.entries(job.members)
|
|
720
1618
|
.map(([key, member]) => [key, { aid: member.aid, project: member.projectPath }])) };
|
|
721
1619
|
this.jobs.save(job);
|
|
722
|
-
|
|
1620
|
+
await this.completeCreation(job);
|
|
1621
|
+
}
|
|
1622
|
+
/** Installation is already committed; welcome failures only affect delivery. */
|
|
1623
|
+
async completeCreation(job) {
|
|
1624
|
+
if (!job.committed || job.action !== 'deploy' || job.result?.installMode !== 'create')
|
|
1625
|
+
return;
|
|
1626
|
+
for (const [key, member] of Object.entries(job.members)) {
|
|
1627
|
+
// Querying an old creation must not welcome an Agent since overwritten or upgraded.
|
|
1628
|
+
const gate = templateInstallationGate(member.aid, undefined, this.deps.root);
|
|
1629
|
+
if (gate.blocked || gate.jobId !== job.jobId)
|
|
1630
|
+
continue;
|
|
1631
|
+
if (job.checkpoint.initialInstallation && !job.checkpoint.installationRecorded)
|
|
1632
|
+
await this.recordInitialInstallation(job);
|
|
723
1633
|
await this.completeRecovery(member.aid);
|
|
1634
|
+
if (!this.deps.completeCreationWelcome || job.checkpoint.welcomeCompleted?.[key])
|
|
1635
|
+
continue;
|
|
1636
|
+
let result;
|
|
1637
|
+
try {
|
|
1638
|
+
result = await this.deps.completeCreationWelcome(member.aid);
|
|
1639
|
+
}
|
|
1640
|
+
catch (error) {
|
|
1641
|
+
result = { ok: false, code: 'WELCOME_FAILED', reloaded: false,
|
|
1642
|
+
error: error instanceof Error ? error.message : String(error) };
|
|
1643
|
+
}
|
|
1644
|
+
(job.result.welcome ??= {})[key] = { ...result, aid: member.aid };
|
|
1645
|
+
// Once persisted, queued messages belong to the existing durable outbox.
|
|
1646
|
+
// Preparation failures remain retryable through the original job's status.
|
|
1647
|
+
if (result.ok)
|
|
1648
|
+
(job.checkpoint.welcomeCompleted ??= {})[key] = true;
|
|
1649
|
+
this.jobs.save(job);
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
async prepareInitialInstallation(job, record, planFile) {
|
|
1653
|
+
const entries = Object.entries(job.members);
|
|
1654
|
+
if (record.update || entries.length !== 1 || !isValidAid(entries[0][0]))
|
|
1655
|
+
return;
|
|
1656
|
+
const [key, member] = entries[0];
|
|
1657
|
+
const config = record.data.configs[key];
|
|
1658
|
+
if (config.update?.key !== key)
|
|
1659
|
+
return;
|
|
1660
|
+
const source = { key, registryAid: config.update.registryAid };
|
|
1661
|
+
const pkg = record.sourcePath ? { data: record.source, provenance: { release: record.source.release } }
|
|
1662
|
+
: this.packageRecord(job.actor, record.packageId);
|
|
1663
|
+
const plan = JSON.parse(fs.readFileSync(planFile, 'utf8'));
|
|
1664
|
+
job.checkpoint.initialInstallation = { operation: 'record-installation', planFile,
|
|
1665
|
+
installation: { targetAid: member.aid, ownerAid: job.actor, hostAid: this.deps.hostAid, projectPath: member.projectPath,
|
|
1666
|
+
source, release: { source, releaseId: pkg.provenance?.release?.releaseId ?? record.data.digest.slice(7),
|
|
1667
|
+
key, publisher: plan.package.publisher?.aid, version: config.version, packageVersion: config.version,
|
|
1668
|
+
digest: record.data.digest, size: pkg.data.size }, committedJobId: job.jobId, baseline: { known: false } } };
|
|
1669
|
+
job.checkpoint.initialInstallation.prepared = await this.executeTool(job, 'overlay', {
|
|
1670
|
+
...job.checkpoint.initialInstallation, operation: 'prepare-installation-record'
|
|
1671
|
+
});
|
|
1672
|
+
this.jobs.save(job);
|
|
1673
|
+
}
|
|
1674
|
+
async recordInitialInstallation(job) {
|
|
1675
|
+
try {
|
|
1676
|
+
await this.tool('overlay', job.checkpoint.initialInstallation);
|
|
1677
|
+
job.checkpoint.installationRecorded = true;
|
|
1678
|
+
delete job.checkpoint.installationRecordError;
|
|
1679
|
+
}
|
|
1680
|
+
catch (error) {
|
|
1681
|
+
job.checkpoint.installationRecordError = { code: error.code ?? 'RECORD_FAILED', message: error.message };
|
|
1682
|
+
}
|
|
1683
|
+
job.result.installationRecord = { recorded: job.checkpoint.installationRecorded === true,
|
|
1684
|
+
...(job.checkpoint.installationRecordError ? { error: job.checkpoint.installationRecordError } : {}) };
|
|
1685
|
+
this.jobs.save(job);
|
|
724
1686
|
}
|
|
725
1687
|
async publishProfile(job, key, profile, legacyRecovery) {
|
|
726
1688
|
const member = job.members[key];
|
|
@@ -756,12 +1718,40 @@ export class AgentTemplateService {
|
|
|
756
1718
|
publication.confirmedVersion = confirmed.profileVersion;
|
|
757
1719
|
this.jobs.save(job);
|
|
758
1720
|
}
|
|
1721
|
+
async verifyUpdatePreview(actor, record, recoveryJobId) {
|
|
1722
|
+
const update = record.update;
|
|
1723
|
+
const aid = update.nextInstallation.targetAid;
|
|
1724
|
+
const context = await this.updateAuthority(aid, actor, recoveryJobId);
|
|
1725
|
+
if (context.key !== update.source.key || context.registryAid !== update.source.registryAid
|
|
1726
|
+
|| context.version !== update.oldVersion || context.mode !== update.mode || context.projectPath !== update.nextInstallation.projectPath
|
|
1727
|
+
|| templateFingerprint(this.snapshot(this.jobs.installationFile(aid))) !== templateFingerprint(update.lock)) {
|
|
1728
|
+
throw templateError('SOURCE_CHANGED', 'Owner, source, policy or installed lock changed since preview');
|
|
1729
|
+
}
|
|
1730
|
+
const plan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
1731
|
+
if (templateFingerprint(plan.update) !== templateFingerprint(update)
|
|
1732
|
+
|| templateFingerprint(Object.fromEntries(plan.members.map((member) => [member.key, member.profile]))) !== templateFingerprint(record.data.profiles)) {
|
|
1733
|
+
throw templateError('CONFLICT', 'Frozen update source, plan or profile differs from its digest');
|
|
1734
|
+
}
|
|
1735
|
+
const profile = await this.deps.readProfile(aid);
|
|
1736
|
+
const recoveredVersion = recoveryJobId ? this.jobs.read(recoveryJobId).checkpoint.restoredProfileVersion : undefined;
|
|
1737
|
+
if (profile.profileVersion !== (recoveredVersion ?? plan.members[0].profileVersion)
|
|
1738
|
+
|| templateFingerprint(profile.profile) !== templateFingerprint(plan.members[0].originalProfile)) {
|
|
1739
|
+
throw templateError('TARGET_CHANGED', 'Target profile changed since the confirmed preview');
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
759
1742
|
async runOverwrite(job, record) {
|
|
760
1743
|
const member = Object.values(job.members)[0];
|
|
761
1744
|
const key = Object.keys(job.members)[0];
|
|
762
1745
|
const release = await this.deps.hold(member.aid, job.jobId);
|
|
763
1746
|
let authorized = false;
|
|
764
1747
|
try {
|
|
1748
|
+
if (!job.checkpoint.executionConfirmedAt && record.createdAt + 3600_000 <= Date.now())
|
|
1749
|
+
throw templateError('EXPIRED', 'Confirmed preview expired before target work began');
|
|
1750
|
+
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
1751
|
+
throw templateError('TARGET_CHANGED', 'Host configuration changed');
|
|
1752
|
+
const frozenPlan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
1753
|
+
if (record.planDigest !== 'sha256:' + templateFingerprint(frozenPlan))
|
|
1754
|
+
throw templateError('CONFLICT', 'Frozen overwrite plan changed');
|
|
765
1755
|
await this.step(job, () => this.deps.authorize(job.actor, member.aid, job.jobId));
|
|
766
1756
|
authorized = true;
|
|
767
1757
|
if (job.checkpoint.backupDir && !job.checkpoint.restored)
|
|
@@ -775,38 +1765,87 @@ export class AgentTemplateService {
|
|
|
775
1765
|
const current = await this.step(job, () => this.deps.target(member.aid, job.actor));
|
|
776
1766
|
if (current.projectPath !== member.projectPath)
|
|
777
1767
|
throw templateError('TARGET_CHANGED', 'Target project changed');
|
|
1768
|
+
if (current.targetConfig?.update?.mode === 'disabled')
|
|
1769
|
+
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before overwrite');
|
|
1770
|
+
if (record.update)
|
|
1771
|
+
await this.step(job, () => this.verifyUpdatePreview(job.actor, record, job.jobId));
|
|
1772
|
+
else if (current.targetConfig?.update?.key)
|
|
1773
|
+
throw templateError('USE_UPGRADE', 'Use the single upgrade action for this Agent');
|
|
778
1774
|
job.checkpoint.runtimeStopped ??= current.runtimeStatus === 'stopped';
|
|
779
1775
|
job.checkpoint.runtimeInactive ??= current.targetConfig?.enabled === false || current.runtimeStatus === 'stopped';
|
|
1776
|
+
job.checkpoint.executionConfirmedAt ??= Date.now();
|
|
1777
|
+
this.jobs.save(job);
|
|
780
1778
|
await this.executeTool(job, 'overlay', { operation: 'verify', planFile: record.data.planFile });
|
|
1779
|
+
let planFile = record.data.planFile;
|
|
1780
|
+
if (record.update) {
|
|
1781
|
+
const plan = JSON.parse(fs.readFileSync(planFile, 'utf8'));
|
|
1782
|
+
plan.commitInstallation = { ...record.update.nextInstallation, committedJobId: job.jobId };
|
|
1783
|
+
planFile = path.join(this.cache, 'previews', record.previewId, 'execution-' + job.jobId + '.json');
|
|
1784
|
+
writeTemplateState(planFile, plan);
|
|
1785
|
+
}
|
|
781
1786
|
const original = await this.step(job, () => this.deps.readProfile(member.aid));
|
|
782
1787
|
job.checkpoint.originalProfile = original;
|
|
783
1788
|
job.checkpoint.backupDir = path.join(this.cache, 'backups', job.jobId + '-' + job.attempt);
|
|
1789
|
+
job.checkpoint.executionPlanFile = planFile;
|
|
784
1790
|
job.checkpoint.installMode = 'overwrite';
|
|
785
1791
|
job.checkpoint.restored = false;
|
|
786
1792
|
this.jobs.save(job);
|
|
787
|
-
await this.executeTool(job, 'overlay', { planFile
|
|
1793
|
+
await this.executeTool(job, 'overlay', { planFile, backupDir: job.checkpoint.backupDir });
|
|
788
1794
|
job.checkpoint.resourcesApplied = true;
|
|
789
1795
|
this.jobs.save(job);
|
|
790
1796
|
await this.step(job, () => this.deps.reload(member.aid, job.jobId, job.checkpoint.runtimeStopped === true));
|
|
791
1797
|
await this.publishProfile(job, key, record.data.profiles[key], false);
|
|
1798
|
+
await this.executeTool(job, 'overlay', { operation: 'verify-applied', planFile });
|
|
1799
|
+
if (record.update) {
|
|
1800
|
+
const context = await this.step(job, () => this.updateAuthority(member.aid, job.actor, job.jobId));
|
|
1801
|
+
if (context.mode !== record.update.mode || context.key !== record.update.source.key
|
|
1802
|
+
|| context.registryAid !== record.update.source.registryAid || context.version !== record.update.oldVersion) {
|
|
1803
|
+
throw templateError('SOURCE_CHANGED', 'Local update configuration changed before commit');
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
792
1806
|
job.activating = true;
|
|
793
1807
|
this.jobs.save(job);
|
|
794
1808
|
member.runtimeReady = this.deps.installation.ready(member.aid);
|
|
795
|
-
if (!member.runtimeReady && !job.checkpoint.runtimeInactive)
|
|
1809
|
+
if (!member.runtimeReady && !job.checkpoint.runtimeInactive && !record.modelUnavailable?.includes(key))
|
|
796
1810
|
throw templateError('RECOVERY_REQUIRED', 'Reloaded target is not ready');
|
|
1811
|
+
if (record.update)
|
|
1812
|
+
await this.executeTool(job, 'overlay', { operation: 'finalize-upgrade', planFile, backupDir: job.checkpoint.backupDir });
|
|
1813
|
+
else
|
|
1814
|
+
await this.prepareInitialInstallation(job, record, planFile);
|
|
1815
|
+
job.checkpoint.modelUnavailable = record.modelUnavailable ?? [];
|
|
797
1816
|
job.committed = true;
|
|
798
1817
|
job.activating = false;
|
|
799
1818
|
job.status = 'succeeded';
|
|
800
1819
|
job.resumable = false;
|
|
801
1820
|
job.phase = 'completed';
|
|
802
1821
|
job.result = { packageId: record.packageId, previewId: record.previewId, planDigest: record.planDigest,
|
|
803
|
-
installMode: 'overwrite', committed: true, members: { [key]: { aid: member.aid, project: member.projectPath } }
|
|
1822
|
+
installMode: 'overwrite', committed: true, members: { [key]: { aid: member.aid, project: member.projectPath } },
|
|
1823
|
+
...(record.update ? { installedRelease: record.update.release, summary: record.update.summary,
|
|
1824
|
+
...(job.checkpoint.previousPreviewIds?.length ? { previousPreviewId: job.checkpoint.previousPreviewIds.at(-1) } : {}),
|
|
1825
|
+
preservedSharedResources: record.data.update.retainedShared ?? [] } : {}) };
|
|
804
1826
|
this.jobs.save(job);
|
|
1827
|
+
if (job.checkpoint.initialInstallation)
|
|
1828
|
+
await this.recordInitialInstallation(job);
|
|
1829
|
+
if (record.update) {
|
|
1830
|
+
try {
|
|
1831
|
+
job.result.backupCleanup = await this.tool('overlay', { operation: 'cleanup-upgrade', planFile, backupDir: job.checkpoint.backupDir });
|
|
1832
|
+
}
|
|
1833
|
+
catch (error) {
|
|
1834
|
+
job.result.backupCleanup = { backupDir: job.checkpoint.backupDir, cleaned: 0, retainedAll: true, reason: 'CLEANUP_FAILED', error: error.message };
|
|
1835
|
+
}
|
|
1836
|
+
this.jobs.save(job);
|
|
1837
|
+
try {
|
|
1838
|
+
await this.deps.reload(member.aid, job.jobId, job.checkpoint.runtimeStopped === true);
|
|
1839
|
+
}
|
|
1840
|
+
catch (error) {
|
|
1841
|
+
logger.warn('[Template] Committed version refresh pending: ' + String(error));
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
805
1844
|
await this.completeRecovery(member.aid);
|
|
806
1845
|
}
|
|
807
1846
|
catch (error) {
|
|
808
1847
|
const current = this.jobs.read(job.jobId);
|
|
809
|
-
if (authorized)
|
|
1848
|
+
if (authorized && !current.committed)
|
|
810
1849
|
await this.compensate(current);
|
|
811
1850
|
throw error;
|
|
812
1851
|
}
|
|
@@ -865,6 +1904,11 @@ export class AgentTemplateService {
|
|
|
865
1904
|
throw templateError('PROFILE_CONFLICT', 'Independent profile edit during rollback');
|
|
866
1905
|
await this.deps.publishProfile(member.aid, original.profile, current.profileVersion);
|
|
867
1906
|
}
|
|
1907
|
+
const confirmed = await this.deps.readProfile(member.aid);
|
|
1908
|
+
if (templateFingerprint(fields(confirmed.profile)) !== templateFingerprint(fields(original.profile))) {
|
|
1909
|
+
throw templateError('PROFILE_NOT_CONFIRMED', 'Original profile restoration is not confirmed');
|
|
1910
|
+
}
|
|
1911
|
+
job.checkpoint.restoredProfileVersion = confirmed.profileVersion;
|
|
868
1912
|
}
|
|
869
1913
|
await this.deps.reload(member.aid, job.jobId, job.checkpoint.runtimeStopped === true);
|
|
870
1914
|
job.checkpoint.restored = true;
|