evolcore 0.0.50 → 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 +39 -2
- package/bin/ec-build.mjs +60 -0
- package/bin/ecmsg.js +65 -63
- package/dist/ability/caller/command.js +24 -15
- package/dist/ability/caller/contract.js +24 -9
- package/dist/ability/caller/credential-files.js +132 -0
- package/dist/ability/caller/daemon.js +32 -7
- package/dist/ability/caller/schema-view.js +157 -0
- package/dist/ability/caller/service.js +202 -63
- package/dist/ability/interop-v1.js +156 -113
- package/dist/agent-template/jobs.js +14 -110
- package/dist/agent-template/runtime.js +331 -193
- package/dist/agent-template/service.js +1029 -1104
- package/dist/agent-template/share.js +103 -0
- package/dist/agent-template/tool-runner.js +25 -0
- package/dist/agent-template/types.js +10 -3
- 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} +74 -158
- 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} +648 -382
- 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 +55 -10
- package/dist/agents/gemini/{gemini-runner.js → runner.js} +4 -9
- package/dist/aun/ability-device-routing.js +11 -17
- package/dist/aun/aid/agentmd.js +27 -1
- package/dist/aun/aid/managed-operation.js +6 -4
- package/dist/aun/group/invite-service.js +1 -1
- 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/p2p.js +6 -6
- 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 +180 -43
- 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/{agents/claude-gateway → claude-gateway}/agent-registration.js +13 -13
- package/dist/{agents/claude-gateway → claude-gateway}/binding.js +3 -3
- package/dist/{agents/claude-gateway → claude-gateway}/inbox.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/index.js +2 -2
- package/dist/{agents/claude-gateway → claude-gateway}/listing.js +3 -3
- package/dist/{agents/claude-gateway → claude-gateway}/router.js +4 -4
- package/dist/{agents/claude-gateway → claude-gateway}/sessions.js +2 -2
- package/dist/{agents/claude-gateway → claude-gateway}/terminal.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/transcript.js +1 -1
- package/dist/cli/ability-command.js +8 -5
- package/dist/cli/ability-output.js +182 -0
- package/dist/cli/agent-command.js +1 -1
- package/dist/cli/agent-create.js +123 -42
- package/dist/cli/agent-template.js +400 -29
- package/dist/cli/agent.js +14 -11
- package/dist/cli/aun-commands.js +167 -111
- package/dist/cli/daemon-commands.js +38 -8
- 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 +55 -19
- package/dist/cli/fs-command.js +67 -39
- package/dist/cli/index.js +25 -11
- package/dist/cli/init.js +124 -29
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +1 -1
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/services-command.js +24 -1
- 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 +3 -2
- package/dist/cli/trigger-command.js +47 -12
- package/dist/cli/watch-logs.js +2 -1
- package/dist/config/boot-log.js +3 -0
- package/dist/config/builtin-role-templates.js +1 -1
- package/dist/config/config-field-policy.js +10 -6
- package/dist/config/config-manager.js +33 -12
- package/dist/config/gateway-config.js +21 -37
- package/dist/config/invoke-ipc-service.js +1 -1
- package/dist/config/owner-config.js +5 -3
- package/dist/config/peer-book-store.js +2 -3
- package/dist/config/peer-book.js +2 -2
- package/dist/config/peer-role-resolver.js +2 -2
- 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 +39 -15
- package/dist/config/providers-import.js +3 -3
- package/dist/config/providers-management.js +74 -99
- package/dist/config/schema-migration.js +177 -11
- package/dist/config/schema-registry.js +1 -1
- package/dist/config-store.js +38 -50
- package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +9 -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} +102 -25
- package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +61 -1
- package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +53 -27
- package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +12 -12
- package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
- package/dist/core/auth/agent-delegation.js +1 -8
- package/dist/core/auth/delegation-authorization.js +28 -0
- package/dist/core/auth/operation-authorizer.js +7 -4
- package/dist/core/auth/operation-catalog.js +34 -5
- 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} +62 -6
- package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
- package/dist/{agents → core/baseagent}/baseagent-plugin-descriptor.js +107 -24
- 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 +79 -30
- 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} +18 -18
- package/dist/core/command/agent-control.js +60 -15
- package/dist/core/command/agent-template-menu.js +21 -9
- package/dist/core/command/agentmd-menu-request.js +19 -8
- package/dist/core/command/agentmd-menu.js +14 -5
- 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 +80 -20
- package/dist/core/command/menu-handler.js +305 -25
- package/dist/core/command/menu-protocol.js +42 -8
- package/dist/core/command/menu-query-batch.js +9 -5
- 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 +127 -96
- package/dist/core/command/team-workspace-team.js +3 -3
- package/dist/core/command/topic-slash.js +10 -10
- package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -14
- package/dist/core/{daemon-control.js → daemon/daemon-control.js} +46 -20
- package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +15 -15
- package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +3 -3
- package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +98 -38
- 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 +1 -1
- 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 +54 -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 +1 -1
- package/dist/core/memory/consolidation-trigger.js +9 -3
- package/dist/core/memory/consolidation.js +4 -4
- 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 +114 -75
- package/dist/core/message/aun-request-registry.js +13 -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} +4 -4
- 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 +135 -54
- package/dist/core/message/message-queue.js +83 -4
- package/dist/core/message/message-utils.js +1 -1
- package/dist/core/message/peer-mode.js +1 -1
- package/dist/core/message/response-engine.js +347 -163
- package/dist/core/message/send-options.js +9 -6
- package/dist/core/message/send-routing.js +45 -109
- 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 +14 -3
- package/dist/core/model/model-diagnostics.js +4 -4
- package/dist/core/ownership/owner-resolver.js +95 -15
- package/dist/core/{pack-auth.js → pack/pack-auth.js} +30 -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 +70 -34
- package/dist/core/permission/managed-file.js +234 -0
- package/dist/core/permission/protected-paths.js +56 -0
- package/dist/core/permission/sandbox-runtime.js +267 -3
- package/dist/core/permission/session-path-grants.js +1 -1
- package/dist/core/permission/shell-environment.js +15 -1
- package/dist/core/plugin/plugin-lifecycle.js +442 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +2 -246
- package/dist/core/session/adapters/codex-session-file-adapter.js +2 -566
- 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 +29 -2
- 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 +1 -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/ipc-operation.js +2 -2
- package/dist/core/thread/thread-operation.js +2 -1
- package/dist/core/thread/thread-route.js +5 -3
- package/dist/core/thread/thread-service.js +14 -4
- 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 +1 -1
- package/dist/eck/manifest-engine.js +64 -2
- package/dist/eck/message-renderer.js +35 -0
- package/dist/ecweb/basic-settings-service.js +9 -3
- 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 +1 -1
- 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 +71 -42
- package/dist/ipc.js +103 -10
- 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 +12 -0
- package/dist/pay/command.js +1 -1
- package/dist/pay/runtime.js +18 -10
- package/dist/response-system/engines/v1/proactive-flow.js +1 -1
- package/dist/services/dispatcher.js +2 -2
- package/dist/services/host/main.js +10 -1
- package/dist/services/host/protocol.js +9 -2
- package/dist/services/host/resident.js +37 -0
- package/dist/services/host-client.js +12 -0
- package/dist/services/host-recycle.js +8 -3
- package/dist/services/host-runtime.js +54 -15
- package/dist/services/index.js +83 -19
- package/dist/services/ipc-operation.js +303 -38
- package/dist/services/pack-manager.js +2 -2
- package/dist/services/router.js +43 -3
- package/dist/services/script-runner.js +34 -25
- package/dist/services/service-payload.js +28 -1
- package/dist/services/validation.js +28 -2
- 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 +3 -2
- package/dist/trigger/authorization.js +36 -33
- package/dist/trigger/ipc-service.js +4 -4
- package/dist/trigger/local-files.js +8 -176
- package/dist/trigger/manager.js +2 -2
- package/dist/trigger/parser.js +48 -0
- package/dist/trigger/scheduler.js +14 -2
- package/dist/trigger/script-executor.js +21 -0
- package/dist/trigger/script-sandbox.js +57 -243
- package/dist/trigger/system-definitions.js +25 -0
- package/dist/trigger/validation.js +1 -1
- 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 +1 -1
- package/dist/utils/logger.js +3 -1
- package/dist/utils/media-cache.js +99 -4
- package/dist/utils/startup-trace.js +20 -4
- package/dist/utils/welcome.js +64 -20
- 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 +1 -1
- package/kits/docs/channels/feishu.md +1 -1
- package/kits/docs/evolcore/INDEX.md +10 -7
- package/kits/docs/evolcore/agent-create.md +2 -0
- package/kits/docs/evolcore/agent.md +100 -13
- package/kits/docs/evolcore/aid.md +19 -3
- package/kits/docs/evolcore/config.md +94 -0
- 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 +3 -3
- package/kits/docs/evolcore/memory-consolidation.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +24 -2
- package/kits/docs/evolcore/model.md +9 -1
- package/kits/docs/evolcore/msg.md +30 -28
- package/kits/docs/evolcore/pay.md +8 -20
- package/kits/docs/evolcore/plugin.md +74 -0
- package/kits/docs/evolcore/provider.md +8 -2
- package/kits/docs/evolcore/rpc.md +2 -2
- 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 +19 -10
- package/kits/docs/evolcore/tool-authorization.md +4 -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/02-navigation.md +20 -13
- package/kits/rules/06-channel.md +18 -2
- package/kits/schemas/_meta.json +8 -4
- package/kits/schemas/agent-config.schema.23.json +19 -3
- 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.11.json +487 -0
- package/kits/schemas/daemon.schema.12.json +505 -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 +8 -2
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ability/SKILL.md +194 -27
- package/kits/skills/ability/STRUCTURE.md +5 -0
- package/kits/skills/agent-output-cards/SKILL.md +90 -54
- 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 +3 -3
- package/kits/skills/ec-group-collaboration/SKILL.md +4 -4
- package/kits/skills/ec-identity/SKILL.md +9 -6
- package/kits/skills/ec-pay/SKILL.md +163 -41
- package/kits/skills/ec-provider/SKILL.md +5 -5
- package/kits/skills/ec-service-call/SKILL.md +3 -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 +2 -2
- 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/system-fragments/commands.md +1 -1
- package/kits/templates/system-fragments/personal-assistant.md +2 -2
- package/kits/templates/system-fragments/reply.md +14 -9
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +10 -5
- package/package.json +6 -5
- package/scripts/agent-template/index.mjs +7 -1
- package/scripts/agent-template/inspect.mjs +81 -35
- package/scripts/agent-template/overlay.mjs +110 -4
- package/scripts/agent-template/shared/common.mjs +36 -4
- 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 +467 -54
- package/scripts/agent-template/shared/template-contract.mjs +70 -68
- package/scripts/agent-template/shared/template-package.mjs +153 -36
- package/scripts/agent-template/shared/template-runtime.mjs +76 -64
- package/scripts/agent-template/shared/template.mjs +11 -46
- package/scripts/agent-template/team-pack.mjs +451 -35
- package/scripts/agent-template/team-preview.mjs +75 -226
- package/scripts/aid-batch/identity-batch.mjs +1 -1
- package/dist/agents/baseagent-availability.js +0 -176
- package/dist/agents/baseagent-capability-adapter.js +0 -102
- package/dist/agents/baseagent-plugin-loader.js +0 -145
- package/dist/agents/baseagent.js +0 -816
- 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/skills/ec-pay/references/pay-cli.md +0 -110
- /package/dist/agents/gemini/{gemini-capability-provider.js → capability-provider.js} +0 -0
- /package/dist/agents/gemini/{gemini-session-file-adapter.js → session-file-adapter.js} +0 -0
- /package/dist/{agents/claude-gateway → claude-gateway}/types.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,17 +1,20 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
-
import { TemplateJobs, templateFingerprint, writeTemplateState, TEMPLATE_PREVIEW_ID, compareTemplateVersions } from './jobs.js';
|
|
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
9
|
import { isValidAid } from '../aun/aid/validation.js';
|
|
10
10
|
import { withFileLock } from '../utils/atomic-write.js';
|
|
11
11
|
const publicTemplate = await import(new URL('../../scripts/agent-template/shared/template-runtime.mjs', import.meta.url).href);
|
|
12
12
|
const templateContract = await import(new URL('../../scripts/agent-template/shared/template-contract.mjs', import.meta.url).href);
|
|
13
|
-
const
|
|
13
|
+
const templatePackage = await import(new URL('../../scripts/agent-template/shared/template-package.mjs', import.meta.url).href);
|
|
14
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']);
|
|
15
18
|
export class AgentTemplateService {
|
|
16
19
|
deps;
|
|
17
20
|
jobs;
|
|
@@ -25,8 +28,6 @@ export class AgentTemplateService {
|
|
|
25
28
|
tool;
|
|
26
29
|
cleanupTimer;
|
|
27
30
|
disposed = false;
|
|
28
|
-
discoveryRun;
|
|
29
|
-
updateTimer;
|
|
30
31
|
updateRun;
|
|
31
32
|
constructor(deps) {
|
|
32
33
|
this.deps = deps;
|
|
@@ -53,32 +54,27 @@ export class AgentTemplateService {
|
|
|
53
54
|
return;
|
|
54
55
|
this.disposed = true;
|
|
55
56
|
clearInterval(this.cleanupTimer);
|
|
56
|
-
if (this.updateTimer)
|
|
57
|
-
clearInterval(this.updateTimer);
|
|
58
57
|
for (const timer of this.timers.values())
|
|
59
58
|
clearTimeout(timer);
|
|
60
59
|
this.timers.clear();
|
|
61
60
|
for (const job of this.jobs.list())
|
|
62
|
-
if (['inspect', 'build'].includes(job.action)
|
|
61
|
+
if (['inspect', 'collect', 'build'].includes(job.action)
|
|
63
62
|
&& job.freeze && !['released', 'transferred'].includes(job.freeze.state)) {
|
|
64
63
|
await this.cancelInternal(job.actor, job.jobId, 'runtime_disposed');
|
|
65
64
|
}
|
|
66
|
-
|
|
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]);
|
|
67
68
|
}
|
|
68
69
|
view(job) {
|
|
69
70
|
const { actor: _actor, fingerprint: _fingerprint, args: _args, checkpoint: _checkpoint, version: _version, activating: _activating, ...view } = job;
|
|
70
|
-
if (job.checkpoint.
|
|
71
|
-
|
|
72
|
-
const team = this.jobs.readTeam(binding.instanceId);
|
|
73
|
-
const slot = team.members.find(member => member.key === binding.memberKey);
|
|
74
|
-
Object.assign(view, { memberInstallation: { instanceId: team.instanceId, memberKey: slot.key,
|
|
75
|
-
state: slot.state, revision: team.revision, ...(slot.pending ? { pending: slot.pending } : {}) } });
|
|
71
|
+
if (['collect', 'build'].includes(job.action) && job.checkpoint.executionContext?.remote && view.result?.workspace) {
|
|
72
|
+
view.result = { ...view.result, workspace: undefined };
|
|
76
73
|
}
|
|
77
74
|
if (job.action === 'deploy' && job.committed) {
|
|
78
75
|
const runtimeReady = templateJobAids(job).every(aid => this.deps.installation.ready(aid));
|
|
79
76
|
const directoryReady = this.deps.installation.directoryReady(templateJobAids(job));
|
|
80
|
-
return { ...view,
|
|
81
|
-
? { instanceId: 'team_' + templateFingerprint({ teamId: job.jobId, ownerAid: job.actor, hostAid: this.deps.hostAid }) } : {}),
|
|
77
|
+
return { ...view,
|
|
82
78
|
readiness: { runtimeReady, directoryReady, teamReady: runtimeReady && directoryReady,
|
|
83
79
|
health: runtimeReady && directoryReady ? 'ready' : 'degraded' } };
|
|
84
80
|
}
|
|
@@ -104,6 +100,11 @@ export class AgentTemplateService {
|
|
|
104
100
|
async executeTool(job, command, options) {
|
|
105
101
|
return this.step(job, () => this.tool(command, options, {
|
|
106
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
|
+
},
|
|
107
108
|
onSpawn: worker => { this.current(job); job.checkpoint.worker = worker; this.jobs.save(job); },
|
|
108
109
|
onExit: () => {
|
|
109
110
|
const current = this.jobs.read(job.jobId);
|
|
@@ -135,16 +136,26 @@ export class AgentTemplateService {
|
|
|
135
136
|
const current = this.jobs.read(job.jobId);
|
|
136
137
|
if (current.status === 'cancelling' || ['cancelled', 'succeeded'].includes(current.status))
|
|
137
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;
|
|
138
146
|
current.error = { code: error.code ?? 'TEMPLATE_FAILED', message: error.message,
|
|
139
|
-
retryable:
|
|
140
|
-
if (['inspect', 'build'].includes(current.action)) {
|
|
147
|
+
retryable: recoverable, ...(error.details ? { details: error.details } : {}) };
|
|
148
|
+
if (['inspect', 'collect', 'build'].includes(current.action)) {
|
|
141
149
|
await this.release(current, 'failed');
|
|
142
|
-
current.status = current.freeze
|
|
150
|
+
current.status = !current.freeze || current.freeze.state === 'released' ? 'failed' : 'cancelling';
|
|
143
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
|
+
}
|
|
144
155
|
}
|
|
145
156
|
else {
|
|
146
|
-
current.status =
|
|
147
|
-
current.resumable =
|
|
157
|
+
current.status = recoverable ? 'paused' : 'failed';
|
|
158
|
+
current.resumable = recoverable;
|
|
148
159
|
}
|
|
149
160
|
this.jobs.save(current);
|
|
150
161
|
}
|
|
@@ -163,24 +174,47 @@ export class AgentTemplateService {
|
|
|
163
174
|
}
|
|
164
175
|
async query(actor, args) {
|
|
165
176
|
await this.deps.installation.authorize(actor);
|
|
166
|
-
|
|
167
|
-
if (job.committed && job.
|
|
168
|
-
await this.
|
|
169
|
-
|
|
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);
|
|
170
197
|
}
|
|
171
|
-
else if (job.committed && job.result?.installMode === 'create')
|
|
172
|
-
await this.recordCreatedTeam(job, this.previewRecord(job.args.previewId));
|
|
173
198
|
return this.view(job);
|
|
174
199
|
}
|
|
175
|
-
async action(actor, requestId, action, args) {
|
|
200
|
+
async action(actor, requestId, action, args, context = {}) {
|
|
176
201
|
if (this.disposed)
|
|
177
202
|
throw templateError('RECOVERY_REQUIRED', 'Template runtime has been disposed');
|
|
203
|
+
if (!TEMPLATE_ACTIONS.includes(action))
|
|
204
|
+
throw templateError('INVALID_ARGUMENT', 'Unknown template action');
|
|
178
205
|
if (typeof requestId !== 'string' || !requestId.trim() || requestId.length > 200)
|
|
179
206
|
throw templateError('INVALID_ARGUMENT', 'Stable requestId required');
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
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;
|
|
184
218
|
}
|
|
185
219
|
if (action === 'status')
|
|
186
220
|
return this.query(actor, args);
|
|
@@ -188,39 +222,39 @@ export class AgentTemplateService {
|
|
|
188
222
|
return this.tool('capabilities', {});
|
|
189
223
|
if (action === 'update-status')
|
|
190
224
|
return this.updateStatus(actor, args.targetAid);
|
|
191
|
-
if (action === '
|
|
192
|
-
return this.
|
|
193
|
-
if (action === 'confirm-update-source')
|
|
194
|
-
return this.confirmUpdateSource(actor, args);
|
|
195
|
-
if (action === 'read-update-notice')
|
|
196
|
-
return this.readUpdateNotice(actor, args.targetAid, args.noticeId);
|
|
197
|
-
if (action === 'register-team')
|
|
198
|
-
return this.registerTeam(actor, args.manifest, args.deliveryDigest);
|
|
199
|
-
if (action === 'team-members')
|
|
200
|
-
return this.discoveredTeamMembers(actor, args);
|
|
201
|
-
if (action === 'prepare-member-install')
|
|
202
|
-
return this.prepareMemberInstall(actor, requestId, args);
|
|
203
|
-
if (action === 'resume-member-join')
|
|
204
|
-
return this.resumeMemberJoin(actor, args.instanceId, args.memberKey);
|
|
225
|
+
if (action === 'upgrade')
|
|
226
|
+
return this.acceptUpgrade(actor, requestId, args);
|
|
205
227
|
if (action === 'cancel' || action === 'resume')
|
|
206
|
-
return this.control(actor, requestId, action, args.jobId);
|
|
228
|
+
return this.control(actor, requestId, action, args.jobId, context);
|
|
207
229
|
const prior = this.jobs.original(actor, requestId);
|
|
208
230
|
if (prior) {
|
|
209
231
|
if (!this.jobs.requestMatches(actor, requestId, action, args))
|
|
210
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
|
+
}
|
|
211
237
|
if (action === 'deploy')
|
|
212
238
|
return this.deploy(actor, requestId, args);
|
|
213
239
|
return this.view(prior);
|
|
214
240
|
}
|
|
215
241
|
if (action === 'inspect')
|
|
216
242
|
return this.inspect(actor, requestId, args);
|
|
217
|
-
if (action === '
|
|
218
|
-
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);
|
|
219
247
|
if (action === 'deploy')
|
|
220
248
|
return this.deploy(actor, requestId, args);
|
|
249
|
+
if (action === 'publish')
|
|
250
|
+
this.packageRecord(actor, args.packageId);
|
|
221
251
|
const { job } = this.jobs.accept(actor, requestId, action, args);
|
|
252
|
+
job.checkpoint.executionContext = context;
|
|
253
|
+
this.jobs.save(job);
|
|
222
254
|
this.launch(job, value => action === 'push' ? this.push(value) : action === 'pull' ? this.pull(value)
|
|
223
|
-
: action === '
|
|
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));
|
|
224
258
|
return this.view(job);
|
|
225
259
|
}
|
|
226
260
|
updateFile(targetAid) {
|
|
@@ -228,734 +262,297 @@ export class AgentTemplateService {
|
|
|
228
262
|
return path.join(this.cache, 'updates', templateFingerprint(targetAid) + '.json');
|
|
229
263
|
}
|
|
230
264
|
snapshot(file) {
|
|
231
|
-
this.jobs.
|
|
265
|
+
this.jobs.assertStatePath(file);
|
|
232
266
|
if (!fs.existsSync(file))
|
|
233
267
|
return null;
|
|
234
|
-
|
|
235
|
-
if (!stat.isFile() || stat.nlink !== 1)
|
|
236
|
-
throw templateError('CONFLICT', 'Ordinary private managed file required');
|
|
237
|
-
// templateFingerprint is for JSON; file snapshots use the overlay's exact byte digest.
|
|
238
|
-
return { sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), mode: stat.mode & 0o777 };
|
|
268
|
+
return { sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), mode: fs.statSync(file).mode & 0o777 };
|
|
239
269
|
}
|
|
240
270
|
async updateAuthority(targetAid, actor, recoveryJobId, allowDisabled = false) {
|
|
241
271
|
if (!this.deps.updates)
|
|
242
|
-
throw templateError('CATALOG_UNAVAILABLE', 'Template update runtime
|
|
272
|
+
throw templateError('CATALOG_UNAVAILABLE', 'Template update runtime unavailable');
|
|
243
273
|
const current = await this.deps.updates.context(targetAid);
|
|
244
274
|
if (!current.ownerAid || actor && actor !== current.ownerAid)
|
|
245
|
-
throw templateError('NOT_ALLOWED', 'Current direct
|
|
275
|
+
throw templateError('NOT_ALLOWED', 'Current direct Owner required');
|
|
246
276
|
await this.deps.authorize(current.ownerAid, targetAid, recoveryJobId);
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
}
|
|
256
|
-
return installed;
|
|
257
|
-
}
|
|
258
|
-
attestedRelease(source, detail) {
|
|
259
|
-
const member = detail.members?.find((value) => value.key === source.memberKey);
|
|
260
|
-
if (detail.revoked || detail.withdrawn || detail.deleted || detail.state && !['published', 'released'].includes(detail.state)) {
|
|
261
|
-
throw templateError('RELEASE_WITHDRAWN', 'The fixed release is no longer published');
|
|
262
|
-
}
|
|
263
|
-
if (detail.schema !== 1 || detail.templateId !== source.templateId || detail.publisher !== source.publisher
|
|
264
|
-
|| detail.publisherProof !== 'authenticated-AUN-service-submission' || !member?.publisherVerified
|
|
265
|
-
|| member.publisher !== source.publisher || !/^[a-f0-9]{64}$/.test(detail.releaseId ?? '')
|
|
266
|
-
|| !/^sha256:[a-f0-9]{64}$/.test(detail.digest ?? '')) {
|
|
267
|
-
throw templateError('UNVERIFIED_SOURCE', 'Registry did not attest the original author and member source');
|
|
268
|
-
}
|
|
269
|
-
compareTemplateVersions(member.version, member.version);
|
|
270
|
-
compareTemplateVersions(detail.version, detail.version);
|
|
271
|
-
return { source: structuredClone(source), releaseId: detail.releaseId, version: member.version,
|
|
272
|
-
packageVersion: detail.version, digest: detail.digest, ...(member.agentTemplateId ? { agentTemplateId: member.agentTemplateId } : {}) };
|
|
273
|
-
}
|
|
274
|
-
async fixedRelease(source, releaseId, operation) {
|
|
275
|
-
const detail = await this.deps.updates.catalog(source, 'detail', { releaseId }, operation);
|
|
276
|
-
const release = this.attestedRelease(source, detail);
|
|
277
|
-
if (release.releaseId !== releaseId)
|
|
278
|
-
throw templateError('SOURCE_CHANGED', 'Registry returned another release');
|
|
279
|
-
return release;
|
|
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 };
|
|
280
285
|
}
|
|
281
|
-
|
|
282
|
-
if (!/^
|
|
283
|
-
|
|
284
|
-
|
|
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 };
|
|
285
295
|
}
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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 };
|
|
294
307
|
}
|
|
295
308
|
async updateStatus(actor, targetAid) {
|
|
296
309
|
const context = await this.updateAuthority(targetAid, actor, undefined, true);
|
|
297
|
-
const installation = this.installed(targetAid, actor, context.projectPath);
|
|
298
310
|
const file = this.updateFile(targetAid);
|
|
299
311
|
const check = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
baselineKnown: installation?.baseline.known ?? false, check: currentCheck,
|
|
305
|
-
notices: this.notices(targetAid, actor, installation?.source),
|
|
306
|
-
activeJob: this.jobs.list().find(job => job.action === 'deploy' && !job.committed && !job.checkpoint.restored
|
|
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
|
|
307
316
|
&& Object.values(job.members).some(member => member.aid === targetAid))?.jobId ?? null };
|
|
308
317
|
}
|
|
309
|
-
async readUpdateNotice(actor, targetAid, noticeId) {
|
|
310
|
-
const context = await this.updateAuthority(targetAid, actor, undefined, true);
|
|
311
|
-
const installation = this.installed(targetAid, actor, context.projectPath);
|
|
312
|
-
const notice = this.notices(targetAid, actor, installation?.source).find(value => value.noticeId === noticeId);
|
|
313
|
-
if (!notice)
|
|
314
|
-
throw templateError('NOT_FOUND', 'Current Owner notification not found');
|
|
315
|
-
notice.unread = false;
|
|
316
|
-
writeTemplateState(this.noticeFile(noticeId), notice);
|
|
317
|
-
return { noticeId, unread: false };
|
|
318
|
-
}
|
|
319
|
-
async bindUpdateSource(actor, requestId, args) {
|
|
320
|
-
const context = await this.updateAuthority(args.targetAid, actor);
|
|
321
|
-
const sourceErrors = templateContract.validateTemplateRequest({ requestId, action: 'bind-update-source', args });
|
|
322
|
-
if (sourceErrors.length)
|
|
323
|
-
throw templateError('INVALID_ARGUMENT', sourceErrors.join('; '));
|
|
324
|
-
const release = await this.fixedRelease(args.source, args.releaseId, 'binding:' + templateFingerprint({ actor, requestId }));
|
|
325
|
-
const target = await this.deps.target(args.targetAid, actor);
|
|
326
|
-
const bindingId = 'binding_' + randomUUID();
|
|
327
|
-
const installation = { targetAid: args.targetAid, ownerAid: actor, hostAid: this.deps.hostAid,
|
|
328
|
-
projectPath: context.projectPath, source: args.source, bindingId, bindingReleaseId: release.releaseId, baseline: { known: false } };
|
|
329
|
-
const value = { bindingId, actor, installation, release, snapshot: templateFingerprint(target),
|
|
330
|
-
lock: this.snapshot(this.jobs.installationFile(args.targetAid)), expiresAt: Date.now() + SELECTION_MS };
|
|
331
|
-
const planDigest = 'sha256:' + templateFingerprint(value);
|
|
332
|
-
writeTemplateState(path.join(this.cache, 'update-bindings', bindingId + '.json'), { ...value, planDigest });
|
|
333
|
-
return { bindingId, planDigest, expiresAt: value.expiresAt, targetAid: args.targetAid, source: args.source,
|
|
334
|
-
selectedRelease: release, currentVersion: null, baselineKnown: false, requiresOwnerConfirmation: true,
|
|
335
|
-
warning: '来源绑定不会宣称当前内容已安装该版本;本地差异将在升级预览中逐项确认。' };
|
|
336
|
-
}
|
|
337
|
-
async confirmUpdateSource(actor, args) {
|
|
338
|
-
if (!/^binding_[a-f0-9-]{36}$/.test(args.bindingId ?? ''))
|
|
339
|
-
throw templateError('INVALID_ARGUMENT', 'Invalid bindingId');
|
|
340
|
-
const record = JSON.parse(fs.readFileSync(path.join(this.cache, 'update-bindings', args.bindingId + '.json'), 'utf8'));
|
|
341
|
-
const installation = record.installation;
|
|
342
|
-
return withFileLock(path.join(this.cache, 'update-targets', templateFingerprint(installation.targetAid) + '.lock'), async () => {
|
|
343
|
-
await this.updateAuthority(installation.targetAid, actor);
|
|
344
|
-
if (record.actor !== actor || args.planDigest !== record.planDigest)
|
|
345
|
-
throw templateError('NOT_ALLOWED', 'Original Owner confirmation and digest required');
|
|
346
|
-
const { planDigest: _digest, confirmed: _confirmed, ...boundInput } = record;
|
|
347
|
-
if ('sha256:' + templateFingerprint(boundInput) !== record.planDigest)
|
|
348
|
-
throw templateError('CONFLICT', 'Frozen source binding changed');
|
|
349
|
-
const existing = this.jobs.installation(installation.targetAid);
|
|
350
|
-
if (existing?.bindingId === record.bindingId && templateFingerprint(existing) === templateFingerprint(installation)) {
|
|
351
|
-
record.confirmed = true;
|
|
352
|
-
writeTemplateState(path.join(this.cache, 'update-bindings', args.bindingId + '.json'), record);
|
|
353
|
-
return { targetAid: installation.targetAid, sourceState: 'bound', currentVersion: null, bindingId: record.bindingId };
|
|
354
|
-
}
|
|
355
|
-
if (record.confirmed)
|
|
356
|
-
throw templateError('SOURCE_CHANGED', 'A later Owner source binding superseded this confirmation');
|
|
357
|
-
if (record.expiresAt <= Date.now())
|
|
358
|
-
throw templateError('EXPIRED', 'Source binding preview expired');
|
|
359
|
-
const target = await this.deps.target(installation.targetAid, actor);
|
|
360
|
-
if (templateFingerprint(target) !== record.snapshot || templateFingerprint(this.snapshot(this.jobs.installationFile(installation.targetAid))) !== templateFingerprint(record.lock)) {
|
|
361
|
-
throw templateError('TARGET_CHANGED', 'Binding target changed');
|
|
362
|
-
}
|
|
363
|
-
const release = await this.fixedRelease(installation.source, record.release.releaseId, args.bindingId + ':confirm');
|
|
364
|
-
if (templateFingerprint(release) !== templateFingerprint(record.release))
|
|
365
|
-
throw templateError('SOURCE_CHANGED', 'Selected source changed');
|
|
366
|
-
const active = this.jobs.list().find(job => job.action === 'deploy' && !job.committed && !job.checkpoint.restored
|
|
367
|
-
&& Object.values(job.members).some(member => member.aid === installation.targetAid));
|
|
368
|
-
if (active)
|
|
369
|
-
throw templateError('CONFLICT', 'Resume the original target job', { jobId: active.jobId });
|
|
370
|
-
writeTemplateState(this.jobs.installationFile(installation.targetAid), { schemaVersion: 2, installation });
|
|
371
|
-
record.confirmed = true;
|
|
372
|
-
writeTemplateState(path.join(this.cache, 'update-bindings', args.bindingId + '.json'), record);
|
|
373
|
-
return { targetAid: installation.targetAid, sourceState: 'bound', currentVersion: null, bindingId: record.bindingId };
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
318
|
async runUpdateCheck(job) {
|
|
377
319
|
job.result = await this.checkUpdate(job.args.targetAid, job.actor);
|
|
378
320
|
job.status = 'succeeded';
|
|
379
321
|
job.phase = 'completed';
|
|
380
322
|
this.jobs.save(job);
|
|
381
323
|
}
|
|
382
|
-
/** Read-only catalog work: never enters pull, preview, deploy or a model runner. */
|
|
383
324
|
async checkUpdate(targetAid, actor) {
|
|
384
|
-
return withFileLock(path.join(this.cache, 'update-checks', templateFingerprint(targetAid) + '.lock'),
|
|
385
|
-
const context = await this.updateAuthority(targetAid, actor);
|
|
386
|
-
const ownerAid = context.ownerAid;
|
|
387
|
-
const installation = this.installed(targetAid, ownerAid, context.projectPath);
|
|
388
|
-
if (!installation)
|
|
389
|
-
return { targetAid, sourceState: 'unbound', reason: 'SOURCE_UNBOUND', currentVersion: null };
|
|
390
|
-
const source = installation.source;
|
|
391
|
-
const releases = [];
|
|
392
|
-
// Revalidate the original source as well as the selected candidate; do not drift to another publisher.
|
|
393
|
-
const anchor = installation.release?.releaseId ?? installation.bindingReleaseId;
|
|
394
|
-
if (!anchor)
|
|
395
|
-
throw templateError('UNVERIFIED_SOURCE', 'Source attestation is absent');
|
|
396
|
-
const originalRelease = await this.fixedRelease(source, anchor, 'check-anchor:' + randomUUID());
|
|
397
|
-
if (installation.release && templateFingerprint(originalRelease) !== templateFingerprint(installation.release)) {
|
|
398
|
-
throw templateError('SOURCE_CHANGED', 'The original installed release no longer matches its trusted receipt');
|
|
399
|
-
}
|
|
400
|
-
for (let offset = 0;; offset += 50) {
|
|
401
|
-
if (offset >= 5000)
|
|
402
|
-
throw templateError('CATALOG_LIMIT', 'Too many releases; narrow the trusted source');
|
|
403
|
-
const page = await this.deps.updates.catalog(source, 'versions', { entity: 'agent', publisher: source.publisher,
|
|
404
|
-
templateId: source.templateId, memberKey: source.memberKey, offset, limit: 50 }, 'check:' + randomUUID());
|
|
405
|
-
if (!Array.isArray(page.releases) || !Number.isSafeInteger(page.total))
|
|
406
|
-
throw templateError('INVALID_CATALOG', 'Bounded release page required');
|
|
407
|
-
for (const row of page.releases) {
|
|
408
|
-
if (row.templateId !== source.templateId || row.key !== source.memberKey || row.publisher !== source.publisher
|
|
409
|
-
|| row.publisherVerified !== true || row.packagePublisher !== source.publisher)
|
|
410
|
-
throw templateError('UNVERIFIED_SOURCE', 'Author version source mismatch');
|
|
411
|
-
compareTemplateVersions(row.version, row.version);
|
|
412
|
-
const release = await this.fixedRelease(source, row.releaseId, 'check-detail:' + randomUUID());
|
|
413
|
-
if (release.version !== row.version || release.digest !== row.digest || release.packageVersion !== row.packageVersion) {
|
|
414
|
-
throw templateError('SOURCE_CHANGED', 'Catalog version and fixed release disagree');
|
|
415
|
-
}
|
|
416
|
-
releases.push(release);
|
|
417
|
-
}
|
|
418
|
-
if (offset + page.releases.length >= page.total)
|
|
419
|
-
break;
|
|
420
|
-
if (!page.releases.length)
|
|
421
|
-
throw templateError('INVALID_CATALOG', 'Catalog pagination stalled');
|
|
422
|
-
}
|
|
423
|
-
const known = new Map();
|
|
424
|
-
for (const release of [...releases, ...(installation.release ? [installation.release] : [])]) {
|
|
425
|
-
if (known.has(release.version) && known.get(release.version) !== release.digest)
|
|
426
|
-
throw templateError('VERSION_CONTENT_CONFLICT', 'The same author version has different content');
|
|
427
|
-
known.set(release.version, release.digest);
|
|
428
|
-
}
|
|
429
|
-
releases.sort((a, b) => compareTemplateVersions(b.version, a.version));
|
|
430
|
-
const candidate = releases.find(release => !installation.release || compareTemplateVersions(release.version, installation.release.version) > 0);
|
|
431
|
-
const current = await this.updateAuthority(targetAid, ownerAid);
|
|
432
|
-
if (templateFingerprint(this.installed(targetAid, ownerAid, current.projectPath)) !== templateFingerprint(installation)
|
|
433
|
-
|| current.mode !== context.mode)
|
|
434
|
-
throw templateError('SOURCE_CHANGED', 'Owner, source or policy changed during check');
|
|
435
|
-
const result = { targetAid, sourceState: 'bound', currentVersion: installation.release?.version ?? null,
|
|
436
|
-
state: candidate ? installation.release ? 'available' : 'current-version-unknown' : 'current', candidate: candidate ?? null };
|
|
437
|
-
writeTemplateState(this.updateFile(targetAid), { ...result, ownerAid, installation: templateFingerprint(installation),
|
|
438
|
-
mode: context.mode ?? null, checkedAt: Date.now(), nextCheckAt: Date.now() + 86400_000, failures: 0 });
|
|
439
|
-
if (candidate)
|
|
440
|
-
await this.deliverUpdateNotice(installation, candidate);
|
|
441
|
-
return result;
|
|
442
|
-
});
|
|
325
|
+
return withFileLock(path.join(this.cache, 'update-checks', templateFingerprint(targetAid) + '.lock'), () => this.checkUpdateResult(targetAid, actor));
|
|
443
326
|
}
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
const
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
const
|
|
463
|
-
|
|
464
|
-
|
|
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;
|
|
465
351
|
}
|
|
466
|
-
/**
|
|
467
|
-
|
|
468
|
-
if (
|
|
469
|
-
return;
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
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;
|
|
358
|
+
try {
|
|
359
|
+
await run;
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
if (this.updateRun === run)
|
|
363
|
+
this.updateRun = undefined;
|
|
364
|
+
}
|
|
479
365
|
}
|
|
480
|
-
async
|
|
366
|
+
async scanDueUpdates() {
|
|
481
367
|
for (const target of this.deps.updates?.targets() ?? []) {
|
|
482
|
-
if (this.disposed
|
|
483
|
-
|
|
484
|
-
const file = this.updateFile(target.aid);
|
|
485
|
-
let state = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
|
|
486
|
-
if (!state) {
|
|
487
|
-
writeTemplateState(file, { nextCheckAt: now + 60_000 + parseInt(templateFingerprint(target.aid).slice(0, 8), 16) % 600_000 });
|
|
488
|
-
continue;
|
|
489
|
-
}
|
|
490
|
-
if (target.mode === 'disabled') {
|
|
491
|
-
if (state.mode !== 'disabled')
|
|
492
|
-
writeTemplateState(file, { ...state, mode: 'disabled', nextCheckAt: now + 86400_000 });
|
|
493
|
-
continue;
|
|
494
|
-
}
|
|
495
|
-
const changed = state.installation && state.installation !== templateFingerprint(this.jobs.installation(target.aid))
|
|
496
|
-
|| state.mode === 'disabled' && target.mode !== 'disabled';
|
|
497
|
-
if (!changed && state.nextCheckAt > now)
|
|
498
|
-
continue;
|
|
368
|
+
if (this.disposed)
|
|
369
|
+
return;
|
|
499
370
|
try {
|
|
500
|
-
await this.
|
|
371
|
+
const context = await this.updateAuthority(target.aid, undefined, undefined, true);
|
|
372
|
+
if (!context.eligible)
|
|
373
|
+
continue;
|
|
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
|
+
});
|
|
501
391
|
}
|
|
502
392
|
catch (error) {
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
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 } });
|
|
506
398
|
}
|
|
507
399
|
}
|
|
508
400
|
}
|
|
509
|
-
async
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
await this.step(job, () => this.checkUpdate(job.args.targetAid, job.actor));
|
|
517
|
-
const release = await this.step(job, () => this.fixedRelease(installation.source, job.args.releaseId, job.jobId + ':detail'));
|
|
518
|
-
if (installation.release && compareTemplateVersions(release.version, installation.release.version) <= 0) {
|
|
519
|
-
throw templateError(release.version === installation.release.version && release.digest !== installation.release.digest
|
|
520
|
-
? 'VERSION_CONTENT_CONFLICT' : 'VERSION_NOT_NEWER', 'Choose a newer author member version');
|
|
521
|
-
}
|
|
522
|
-
frozen = job.checkpoint.update = { installation, release,
|
|
523
|
-
lock: this.snapshot(this.jobs.installationFile(job.args.targetAid)), packageId: 'package_' + randomUUID(), downloadGeneration: 1 };
|
|
524
|
-
job.resumable = true;
|
|
525
|
-
this.jobs.save(job);
|
|
526
|
-
}
|
|
527
|
-
if (templateFingerprint(installation) !== templateFingerprint(frozen.installation))
|
|
528
|
-
throw templateError('SOURCE_CHANGED', 'Original installed source changed');
|
|
529
|
-
const release = await this.step(job, () => this.fixedRelease(installation.source, frozen.release.releaseId, job.jobId + ':verify:' + job.attempt));
|
|
530
|
-
if (templateFingerprint(release) !== templateFingerprint(frozen.release))
|
|
531
|
-
throw templateError('SOURCE_CHANGED', 'Frozen candidate changed');
|
|
532
|
-
const directory = path.join(this.cache, 'packages', frozen.packageId);
|
|
533
|
-
const file = path.join(directory, 'record.json');
|
|
534
|
-
if (!fs.existsSync(file)) {
|
|
535
|
-
this.phase(job, 'authorizing_download');
|
|
536
|
-
if (frozen.downloadAuthorization && (frozen.downloadExpiresAt <= Date.now() || frozen.downloadError === 'ACCESS_DENIED')) {
|
|
537
|
-
frozen.downloadGeneration++;
|
|
538
|
-
delete frozen.downloadAuthorization;
|
|
539
|
-
delete frozen.downloadError;
|
|
540
|
-
this.jobs.save(job);
|
|
541
|
-
}
|
|
542
|
-
const download = frozen.downloadAuthorization ?? await this.step(job, () => this.deps.updates.catalog(installation.source, 'download', { releaseId: release.releaseId, targetHostAid: this.deps.hostAid }, job.jobId + ':download:' + frozen.downloadGeneration));
|
|
543
|
-
const errors = templateContract.validateTemplateRequest({ requestId: job.requestId, action: 'pull', args: { source: download.source } });
|
|
544
|
-
if (download.releaseId !== release.releaseId || download.targetHostAid !== this.deps.hostAid || errors.length
|
|
545
|
-
|| download.source?.kind !== 'remote' || download.source.digest !== release.digest)
|
|
546
|
-
throw templateError('INTEGRITY_FAILED', 'Fixed Host download authorization differs');
|
|
547
|
-
if (!frozen.downloadAuthorization) {
|
|
548
|
-
frozen.downloadAuthorization = download;
|
|
549
|
-
frozen.downloadExpiresAt = Date.now() + Math.min(download.expiresInSeconds ?? 300, 300) * 1000;
|
|
550
|
-
this.jobs.save(job);
|
|
551
|
-
}
|
|
552
|
-
fs.mkdirSync(directory, { recursive: true });
|
|
553
|
-
const archivePath = path.join(directory, 'package.ectpl');
|
|
554
|
-
// Only this unpublished cache file is replaced when renewing credentials for the same frozen release.
|
|
555
|
-
fs.rmSync(archivePath, { force: true });
|
|
556
|
-
this.phase(job, 'downloading');
|
|
557
|
-
try {
|
|
558
|
-
await this.step(job, () => this.deps.download(download.source.download?.shareId, archivePath, download.source.location));
|
|
559
|
-
}
|
|
560
|
-
catch (error) {
|
|
561
|
-
frozen.downloadError = error.code ?? 'DOWNLOAD_FAILED';
|
|
562
|
-
this.jobs.save(job);
|
|
563
|
-
throw error;
|
|
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);
|
|
564
408
|
}
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
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);
|
|
571
416
|
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
/** Canonical whitelist shared by automatic discovery and manual archive association. */
|
|
580
|
-
definitionManifest(input, strict = false) {
|
|
581
|
-
const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
582
|
-
const fields = (value, allowed) => record(value) && Object.keys(value).every(key => allowed.includes(key));
|
|
583
|
-
if (!record(input) || input.version !== 1 || typeof input.team_id !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(input.team_id)
|
|
584
|
-
|| !isValidAid(input.owner?.aid) || !isValidAid(input.team?.host?.aid) || input.owner.aid === input.team.host.aid || !Array.isArray(input.team?.agents) || !input.team.agents.length
|
|
585
|
-
|| input.team.agents.length > 200 || strict && (!fields(input, ['version', 'team_id', 'owner', 'team', 'member_references'])
|
|
586
|
-
|| !fields(input.owner, ['aid']) || !fields(input.team, ['host', 'assistantKey', 'agents']) || !fields(input.team.host, ['aid']))) {
|
|
587
|
-
throw templateError('INVALID_DEFINITION', 'A lightweight Team identity manifest is required');
|
|
588
|
-
}
|
|
589
|
-
const actual = input.team.agents.map((member) => {
|
|
590
|
-
if (!record(member) || !/^[a-z0-9][a-z0-9_-]{0,31}$/.test(member.key ?? '') || !isValidAid(member.aid)
|
|
591
|
-
|| strict && !fields(member, ['key', 'aid']))
|
|
592
|
-
throw templateError('INVALID_DEFINITION', 'Invalid actual Team member');
|
|
593
|
-
return { key: member.key, aid: member.aid };
|
|
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);
|
|
594
424
|
});
|
|
595
|
-
if (new Set(actual.map((member) => member.key)).size !== actual.length || new Set(actual.map((member) => member.aid)).size !== actual.length
|
|
596
|
-
|| actual.some((member) => [input.owner.aid, input.team.host.aid].includes(member.aid)))
|
|
597
|
-
throw templateError('INVALID_DEFINITION', 'Distinct actual Team identities are required');
|
|
598
|
-
const references = input.member_references ?? { optional: [], external: [] };
|
|
599
|
-
if (!fields(references, ['optional', 'external']) || !Array.isArray(references.optional) || !Array.isArray(references.external)
|
|
600
|
-
|| references.optional.length > 200 || references.external.length > 200)
|
|
601
|
-
throw templateError('INVALID_DEFINITION', 'Invalid member_references');
|
|
602
|
-
if (input.assistantKey !== undefined && input.team.assistantKey !== undefined && input.assistantKey !== input.team.assistantKey) {
|
|
603
|
-
throw templateError('CONFLICT', 'Top-level and Team assistant keys conflict');
|
|
604
|
-
}
|
|
605
|
-
const assistantKey = strict ? input.team.assistantKey : input.assistantKey ?? input.team.assistantKey
|
|
606
|
-
?? actual.find((member) => !references.optional.some((reference) => reference?.key === member.key))?.key;
|
|
607
|
-
if (!actual.some((member) => member.key === assistantKey)
|
|
608
|
-
|| references.optional.some((member) => member?.key === assistantKey)
|
|
609
|
-
|| strict && references.optional.some((member) => actual.some((created) => created.key === member?.key))) {
|
|
610
|
-
throw templateError('INVALID_DEFINITION', 'An explicit actual required assistantKey is required');
|
|
611
|
-
}
|
|
612
|
-
const declarations = [...actual.filter((member) => !references.optional.some((value) => value?.key === member.key))
|
|
613
|
-
.map((member) => ({ key: member.key, profile: { name: member.key } })), ...references.optional];
|
|
614
|
-
const normalized = templateContract.normalizeTeam({ $schema_version: 1, id: 'team-definition', version: '1.0.0', host: { platform: [process.platform] },
|
|
615
|
-
agents: declarations, personal_assistant: declarations.findIndex(member => member.key === assistantKey), external_contacts: references.external });
|
|
616
|
-
if (normalized.errors.length)
|
|
617
|
-
throw templateError('INVALID_DEFINITION', normalized.errors.join('; '));
|
|
618
|
-
const identities = new Set([input.owner.aid, input.team.host.aid, ...actual.map((member) => member.aid)]);
|
|
619
|
-
if (references.external.some((member) => identities.has(member.aid)))
|
|
620
|
-
throw templateError('CONFLICT', 'External AID conflicts with a Team identity');
|
|
621
|
-
return { version: 1, team_id: input.team_id, owner: { aid: input.owner.aid },
|
|
622
|
-
team: { host: { aid: input.team.host.aid }, assistantKey, agents: actual }, member_references: structuredClone(references) };
|
|
623
425
|
}
|
|
624
|
-
|
|
625
|
-
async discoverTeams() {
|
|
626
|
-
if (this.disposed)
|
|
627
|
-
return [];
|
|
628
|
-
if (this.discoveryRun)
|
|
629
|
-
return this.discoveryRun;
|
|
630
|
-
const run = this.scanTeamDefinitions().finally(() => { if (this.discoveryRun === run)
|
|
631
|
-
this.discoveryRun = undefined; });
|
|
632
|
-
this.discoveryRun = run;
|
|
633
|
-
return run;
|
|
634
|
-
}
|
|
635
|
-
async scanTeamDefinitions() {
|
|
636
|
-
const results = [];
|
|
637
|
-
let files;
|
|
426
|
+
readInstalledManifest(targetAid, version) {
|
|
638
427
|
try {
|
|
639
|
-
|
|
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;
|
|
640
439
|
}
|
|
641
|
-
|
|
642
|
-
|
|
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);
|
|
643
467
|
}
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
const
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
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;
|
|
652
476
|
}
|
|
653
|
-
|
|
654
|
-
result.teamId = manifest.team_id;
|
|
655
|
-
result.ownerAid = manifest.owner.aid;
|
|
656
|
-
result.hostAid = manifest.team.host.aid;
|
|
657
|
-
result.assistantAid = manifest.team.agents.find((member) => member.key === manifest.team.assistantKey).aid;
|
|
658
|
-
result.instanceId = 'team_' + templateFingerprint({ teamId: manifest.team_id, ownerAid: result.ownerAid, hostAid: result.hostAid });
|
|
659
|
-
result.definitionDigest = templateContract.contractDigest(manifest);
|
|
660
|
-
if (file !== manifest.team_id + '.json')
|
|
661
|
-
throw templateError('CONFLICT', 'Team definition filename differs from team_id');
|
|
662
|
-
if (envelope.definitionDigest !== templateContract.contractDigest(envelope.manifest))
|
|
663
|
-
throw templateError('INTEGRITY_FAILED', 'Team definition digest mismatch');
|
|
664
|
-
if (manifest.team.host.aid !== this.deps.hostAid)
|
|
665
|
-
throw templateError('NOT_ALLOWED', 'Team definition belongs to another Host');
|
|
666
|
-
if (!this.deps.discovery)
|
|
667
|
-
throw templateError('DISCOVERY_UNAVAILABLE', 'Internal Team ownership verification is unavailable');
|
|
668
|
-
await this.deps.discovery.verifyHost(manifest.owner.aid, manifest.team.host.aid);
|
|
669
|
-
if (this.disposed)
|
|
670
|
-
break;
|
|
671
|
-
await this.registerTeamRecord(manifest.owner.aid, manifest, { definitionDigest: result.definitionDigest, source: 'definition', verifySource: () => {
|
|
672
|
-
if (templateFingerprint(this.jobs.readDefinition(file)) !== templateFingerprint(envelope))
|
|
673
|
-
throw templateError('SOURCE_CHANGED', 'Team definition changed during ownership verification');
|
|
674
|
-
} });
|
|
675
|
-
result.status = 'registered';
|
|
477
|
+
restoreDownload = true;
|
|
676
478
|
}
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
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;
|
|
681
506
|
}
|
|
682
|
-
results.push(result);
|
|
683
507
|
}
|
|
684
|
-
if (
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
}
|
|
697
|
-
const discovery = await this.discoverTeams();
|
|
698
|
-
const failures = discovery.filter(item => item.ownerAid === actor && item.hostAid === this.deps.hostAid
|
|
699
|
-
&& (args.instanceId ? item.instanceId === args.instanceId : item.assistantAid === args.assistantAid) && item.status !== 'registered');
|
|
700
|
-
if (failures.length)
|
|
701
|
-
throw templateError(failures[0].status === 'pending' ? 'TEAM_DISCOVERY_PENDING' : failures[0].code, failures[0].message, { discovery: failures });
|
|
702
|
-
const teams = this.jobs.listTeams().filter(team => team.ownerAid === actor && team.hostAid === this.deps.hostAid
|
|
703
|
-
&& (args.instanceId ? team.instanceId === args.instanceId : team.members.some(member => member.key === team.assistantKey && member.aid === args.assistantAid)));
|
|
704
|
-
const invalidSource = discovery.find(item => item.status !== 'registered' && (item.file === 'team-definitions'
|
|
705
|
-
|| teams.some(team => item.file === team.teamId + '.json')));
|
|
706
|
-
if (invalidSource)
|
|
707
|
-
throw templateError(invalidSource.status === 'pending' ? 'TEAM_DISCOVERY_PENDING' : invalidSource.code, invalidSource.message, { discovery: [{ file: invalidSource.file, status: invalidSource.status, code: invalidSource.code }] });
|
|
708
|
-
if (teams.length > 1)
|
|
709
|
-
throw templateError('CONFLICT', 'Assistant belongs to multiple original Team instances');
|
|
710
|
-
if (!teams.length)
|
|
711
|
-
throw templateError('NOT_FOUND', 'Original Team instance not found', { discoveryPending: discovery.filter(item => item.status === 'pending').length,
|
|
712
|
-
invalidDefinitions: discovery.filter(item => item.status === 'rejected').length });
|
|
713
|
-
return this.teamMembers(actor, teams[0].instanceId);
|
|
714
|
-
}
|
|
715
|
-
async ownedTeam(actor, instanceId) {
|
|
716
|
-
const team = this.jobs.readTeam(instanceId);
|
|
717
|
-
if (team.ownerAid !== actor || team.hostAid !== this.deps.hostAid)
|
|
718
|
-
throw templateError('NOT_ALLOWED', 'Original Team Owner and Host required');
|
|
719
|
-
for (const member of team.members)
|
|
720
|
-
if (member.aid)
|
|
721
|
-
await this.deps.authorize(actor, member.aid);
|
|
722
|
-
return this.jobs.readTeam(instanceId);
|
|
723
|
-
}
|
|
724
|
-
/** Accept only identities already present on this Host; retain references without the source package. */
|
|
725
|
-
async registerTeam(actor, manifest, deliveryDigest) {
|
|
726
|
-
await this.deps.installation.authorize(actor);
|
|
727
|
-
const projected = this.definitionManifest(manifest);
|
|
728
|
-
const instanceId = await this.registerTeamRecord(actor, manifest, { deliveryDigest, definitionDigest: templateContract.contractDigest(projected), source: 'manual' });
|
|
729
|
-
return this.teamMembers(actor, instanceId);
|
|
730
|
-
}
|
|
731
|
-
async registerTeamRecord(actor, manifest, provenance) {
|
|
732
|
-
const projected = this.definitionManifest(manifest, provenance.source === 'definition');
|
|
733
|
-
if (!manifest || manifest.version !== 1 || typeof manifest.team_id !== 'string' || !manifest.team_id
|
|
734
|
-
|| provenance.source === 'manual' && !/^sha256:[a-f0-9]{64}$/.test(provenance.deliveryDigest ?? '') || manifest.owner?.aid !== actor
|
|
735
|
-
|| manifest.team?.host?.aid !== this.deps.hostAid || !Array.isArray(manifest.team?.agents) || !manifest.team.agents.length) {
|
|
736
|
-
throw templateError('INVALID_ARGUMENT', 'A matching Owner/Host delivery manifest and digest are required');
|
|
737
|
-
}
|
|
738
|
-
const refs = manifest.member_references ?? { optional: [], external: [] };
|
|
739
|
-
if (!Array.isArray(refs.optional) || !Array.isArray(refs.external)
|
|
740
|
-
|| Object.keys(refs).some(key => !['optional', 'external'].includes(key)))
|
|
741
|
-
throw templateError('INVALID_ARGUMENT', 'Invalid member_references');
|
|
742
|
-
const actual = [];
|
|
743
|
-
const targets = {};
|
|
744
|
-
for (const declaration of manifest.team.agents) {
|
|
745
|
-
if (!declaration || typeof declaration.key !== 'string' || !isValidAid(declaration.aid)
|
|
746
|
-
|| [actor, this.deps.hostAid].includes(declaration.aid) || actual.some(member => member.aid === declaration.aid || member.key === declaration.key)) {
|
|
747
|
-
throw templateError('INVALID_ARGUMENT', 'Delivery members must have distinct real AIDs and keys');
|
|
748
|
-
}
|
|
749
|
-
if (provenance.source === 'manual')
|
|
750
|
-
await this.deps.authorize(actor, declaration.aid);
|
|
751
|
-
const target = provenance.source === 'definition' ? await this.deps.discovery.member(declaration.aid, actor, this.deps.hostAid)
|
|
752
|
-
: await this.deps.target(declaration.aid, actor);
|
|
753
|
-
if (this.disposed)
|
|
754
|
-
throw templateError('RECOVERY_REQUIRED', 'Template runtime has been disposed');
|
|
755
|
-
if (target.targetAid !== declaration.aid || !path.isAbsolute(target.projectPath ?? ''))
|
|
756
|
-
throw templateError('NOT_FOUND', 'Delivery member is unavailable on this Host');
|
|
757
|
-
targets[declaration.key] = target;
|
|
758
|
-
actual.push({ key: declaration.key, aid: declaration.aid, projectPath: target.projectPath,
|
|
759
|
-
profile: structuredClone(target.profile), state: 'joined',
|
|
760
|
-
...(Object.hasOwn(target.targetConfig ?? {}, 'access') ? { config: { access: publicTemplate.validateAccessDeclaration(target.targetConfig.access) } } : {}) });
|
|
761
|
-
}
|
|
762
|
-
const references = new Map(refs.optional.map((value) => [value?.key, value]));
|
|
763
|
-
if (references.size !== refs.optional.length)
|
|
764
|
-
throw templateError('INVALID_ARGUMENT', 'Duplicate optional reference');
|
|
765
|
-
const required = actual.filter(member => !references.has(member.key));
|
|
766
|
-
const assistantKey = manifest.assistantKey ?? manifest.team.assistantKey ?? required[0]?.key;
|
|
767
|
-
const declarations = [...required, ...refs.optional];
|
|
768
|
-
const normalized = templateContract.normalizeTeam({ $schema_version: 1, id: 'delivered-team', version: '1.0.0',
|
|
769
|
-
host: { platform: [process.platform] }, agents: declarations.map(({ state: _state, aid: _aid, projectPath: _project, ...member }) => member),
|
|
770
|
-
external_contacts: refs.external, personal_assistant: declarations.findIndex(member => member.key === assistantKey) });
|
|
771
|
-
if (normalized.errors.length)
|
|
772
|
-
throw templateError('INVALID_ARGUMENT', normalized.errors.join('; '));
|
|
773
|
-
const partition = publicTemplate.partitionTeamMembers(normalized.team);
|
|
774
|
-
const identityAids = new Set([actor, this.deps.hostAid, ...actual.map(member => member.aid)]);
|
|
775
|
-
if (partition.externalContacts.some((contact) => identityAids.has(contact.aid)))
|
|
776
|
-
throw templateError('CONFLICT', 'External AID conflicts with a Team identity');
|
|
777
|
-
const instanceId = 'team_' + templateFingerprint({ teamId: manifest.team_id, ownerAid: actor, hostAid: this.deps.hostAid });
|
|
778
|
-
await this.jobs.withTeams(async () => {
|
|
779
|
-
if (this.disposed)
|
|
780
|
-
throw templateError('RECOVERY_REQUIRED', 'Template runtime has been disposed');
|
|
781
|
-
provenance.verifySource?.();
|
|
782
|
-
if (fs.existsSync(this.jobs.teamFile(instanceId))) {
|
|
783
|
-
const current = this.jobs.readTeam(instanceId);
|
|
784
|
-
const existing = current.definitionManifest ?? this.definitionManifest({ version: 1, team_id: current.teamId, owner: { aid: current.ownerAid },
|
|
785
|
-
team: { host: { aid: current.hostAid }, assistantKey: current.assistantKey,
|
|
786
|
-
agents: current.members.filter(member => member.aid && !member.installation).map(member => ({ key: member.key, aid: member.aid })) },
|
|
787
|
-
member_references: { optional: current.members.filter(member => member.optional).map(member => member.installation
|
|
788
|
-
? this.jobs.read(member.installation.jobId).checkpoint.memberInstall.declaration
|
|
789
|
-
: { key: member.key, optional: true, agentTemplateId: member.agentTemplateId, profile: member.profile, ...(member.config ? { config: member.config } : {}) }),
|
|
790
|
-
external: current.externalContacts } });
|
|
791
|
-
if (templateContract.contractDigest(existing) !== provenance.definitionDigest
|
|
792
|
-
|| current.definitionDigest && current.definitionDigest !== provenance.definitionDigest
|
|
793
|
-
|| current.deliveryDigest && provenance.deliveryDigest && current.deliveryDigest !== provenance.deliveryDigest) {
|
|
794
|
-
throw templateError('CONFLICT', 'Team already registered from a different definition or archive');
|
|
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);
|
|
795
520
|
}
|
|
796
|
-
const
|
|
797
|
-
const
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
const members = actual.map(member => references.has(member.key)
|
|
808
|
-
? { ...structuredClone(references.get(member.key)), ...member, optional: true } : member);
|
|
809
|
-
for (const reference of partition.optionalReferences)
|
|
810
|
-
if (!actual.some(member => member.key === reference.key))
|
|
811
|
-
members.push({ ...reference, state: 'available' });
|
|
812
|
-
const team = { version: 1, instanceId, teamId: manifest.team_id, ownerAid: actor,
|
|
813
|
-
hostAid: this.deps.hostAid, ...(provenance.deliveryDigest ? { deliveryDigest: provenance.deliveryDigest } : {}),
|
|
814
|
-
definitionDigest: provenance.definitionDigest, definitionManifest: projected, sources: [provenance.source],
|
|
815
|
-
assistantKey, members, externalContacts: partition.externalContacts,
|
|
816
|
-
relationshipTargets: actual.filter(member => (targets[member.key].targetConfig?.team ?? [])
|
|
817
|
-
.some((aid) => actual.some(other => other.aid === aid))).map(member => member.aid),
|
|
818
|
-
revision: '', createdAt: Date.now(), updatedAt: Date.now() };
|
|
819
|
-
this.jobs.saveTeam(team);
|
|
820
|
-
});
|
|
821
|
-
return instanceId;
|
|
822
|
-
}
|
|
823
|
-
async teamMembers(actor, instanceId) {
|
|
824
|
-
let team = await this.ownedTeam(actor, instanceId);
|
|
825
|
-
for (const member of team.members)
|
|
826
|
-
if (member.installation) {
|
|
827
|
-
const job = this.jobs.read(member.installation.jobId);
|
|
828
|
-
if (job.committed)
|
|
829
|
-
await this.attachCommittedMember(job);
|
|
830
|
-
}
|
|
831
|
-
team = this.jobs.readTeam(instanceId);
|
|
832
|
-
return { instanceId, teamId: team.teamId, ownerAid: team.ownerAid, hostAid: team.hostAid,
|
|
833
|
-
...(team.definitionDigest ? { definitionDigest: team.definitionDigest } : {}), ...(team.deliveryDigest ? { deliveryDigest: team.deliveryDigest } : {}),
|
|
834
|
-
sources: team.sources ?? [],
|
|
835
|
-
assistantKey: team.assistantKey, revision: team.revision, members: team.members, externalContacts: team.externalContacts };
|
|
836
|
-
}
|
|
837
|
-
async prepareMemberInstall(actor, requestId, args) {
|
|
838
|
-
await this.ownedTeam(actor, args.instanceId);
|
|
839
|
-
return this.jobs.withTeams(async () => {
|
|
840
|
-
const file = path.join(this.cache, 'member-install-requests', templateFingerprint({ actor, requestId }) + '.json');
|
|
841
|
-
if (fs.existsSync(file)) {
|
|
842
|
-
const prior = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
843
|
-
if (prior.fingerprint !== templateFingerprint(args))
|
|
844
|
-
throw templateError('CONFLICT', 'Request has different slot arguments');
|
|
845
|
-
return this.memberInstallView(this.jobs.readMemberInstall(actor, prior.memberInstallId));
|
|
846
|
-
}
|
|
847
|
-
const team = this.jobs.readTeam(args.instanceId);
|
|
848
|
-
if (team.revision !== args.expectedRevision)
|
|
849
|
-
throw templateError('CONFLICT', 'Team revision changed', { revision: team.revision });
|
|
850
|
-
const member = team.members.find(value => value.key === args.memberKey);
|
|
851
|
-
if (!member?.optional)
|
|
852
|
-
throw templateError('INVALID_ARGUMENT', 'An optional slot in the original Team is required');
|
|
853
|
-
if (member.state !== 'available' || member.aid || member.installation)
|
|
854
|
-
throw templateError('CONFLICT', 'Slot already has an installation', { jobId: member.installation?.jobId, state: member.state });
|
|
855
|
-
const { key, profile, config, agentTemplateId } = member;
|
|
856
|
-
const value = { memberInstallId: 'member_install_' + randomUUID(), actor,
|
|
857
|
-
instanceId: team.instanceId, memberKey: key, ownerAid: team.ownerAid, hostAid: team.hostAid,
|
|
858
|
-
declaration: { key, optional: true, agentTemplateId, profile, ...(config ? { config } : {}) },
|
|
859
|
-
revision: team.revision, createdAt: Date.now() };
|
|
860
|
-
this.jobs.saveMemberInstall(value);
|
|
861
|
-
writeTemplateState(file, { fingerprint: templateFingerprint(args), memberInstallId: value.memberInstallId });
|
|
862
|
-
return this.memberInstallView(value);
|
|
863
|
-
});
|
|
864
|
-
}
|
|
865
|
-
memberInstallView(value) {
|
|
866
|
-
const { actor: _actor, ...view } = value;
|
|
867
|
-
return { ...view, catalogAvailable: !!this.deps.resolveMemberRelease };
|
|
868
|
-
}
|
|
869
|
-
async memberInstall(actor, id) {
|
|
870
|
-
const value = this.jobs.readMemberInstall(actor, id);
|
|
871
|
-
const team = await this.ownedTeam(actor, value.instanceId);
|
|
872
|
-
if (value.ownerAid !== actor || value.hostAid !== this.deps.hostAid || !team.members.some(member => member.key === value.memberKey
|
|
873
|
-
&& member.agentTemplateId === value.declaration.agentTemplateId))
|
|
874
|
-
throw templateError('CONFLICT', 'Original slot binding changed');
|
|
875
|
-
return value;
|
|
876
|
-
}
|
|
877
|
-
async updateTeamMember(instanceId, key, update) {
|
|
878
|
-
await this.jobs.withTeams(async () => {
|
|
879
|
-
const team = this.jobs.readTeam(instanceId);
|
|
880
|
-
const revision = team.revision;
|
|
881
|
-
const member = team.members.find(value => value.key === key);
|
|
882
|
-
if (!member)
|
|
883
|
-
throw templateError('RECOVERY_REQUIRED', 'Original slot is missing');
|
|
884
|
-
const before = templateFingerprint(team);
|
|
885
|
-
update(member, team);
|
|
886
|
-
if (before !== templateFingerprint(team))
|
|
887
|
-
this.jobs.saveTeam(team, revision);
|
|
888
|
-
});
|
|
889
|
-
}
|
|
890
|
-
/** Repair from the committed job, including a crash between commit and instance association. */
|
|
891
|
-
async attachCommittedMember(job) {
|
|
892
|
-
if (!job.committed || !job.checkpoint.memberInstall)
|
|
893
|
-
return;
|
|
894
|
-
const binding = job.checkpoint.memberInstall;
|
|
895
|
-
const record = this.previewRecord(job.args.previewId);
|
|
896
|
-
const sourceKey = binding.release.sourceMemberKey;
|
|
897
|
-
const installed = job.members[sourceKey];
|
|
898
|
-
if (job.actor !== binding.ownerAid || !installed?.aid || !installed.runtimeReady)
|
|
899
|
-
throw templateError('RECOVERY_REQUIRED', 'Committed member binding is invalid');
|
|
900
|
-
await this.updateTeamMember(binding.instanceId, binding.memberKey, (member, team) => {
|
|
901
|
-
if (team.ownerAid !== job.actor || team.hostAid !== binding.hostAid || member.installation?.jobId !== job.jobId
|
|
902
|
-
|| member.aid && member.aid !== installed.aid)
|
|
903
|
-
throw templateError('CONFLICT', 'Slot belongs to a different installation');
|
|
904
|
-
if (member.aid && ['installed', 'joining', 'joined'].includes(member.state))
|
|
905
|
-
return;
|
|
906
|
-
member.aid = installed.aid;
|
|
907
|
-
member.projectPath = installed.projectPath;
|
|
908
|
-
member.profile = structuredClone(record.data.profiles[sourceKey]);
|
|
909
|
-
const access = record.finalDeclaration?.config?.access;
|
|
910
|
-
member.config = access === undefined ? {} : { access: structuredClone(access) };
|
|
911
|
-
member.state = 'installed';
|
|
912
|
-
member.pending = { publicationId: 'publication_' + templateFingerprint({ instanceId: team.instanceId, key: member.key, jobId: job.jobId }),
|
|
913
|
-
aid: installed.aid, ownerAid: team.ownerAid, hostAid: team.hostAid, profile: structuredClone(member.profile),
|
|
914
|
-
ownerDirectoryMutation: { mode: 'add', requiresOwnerAuthorization: true, openPaContextAdd: [installed.aid],
|
|
915
|
-
entries: [{ aid: installed.aid, ...structuredClone(member.profile), type: 'agent', owner_aid: team.ownerAid, ownership_status: 'owned' }] } };
|
|
916
|
-
});
|
|
917
|
-
}
|
|
918
|
-
async resumeMemberJoin(actor, instanceId, memberKey) {
|
|
919
|
-
await this.ownedTeam(actor, instanceId);
|
|
920
|
-
return withFileLock(path.join(this.cache, 'teams', instanceId, templateFingerprint(memberKey) + '.join.lock'), async () => {
|
|
921
|
-
let team = await this.ownedTeam(actor, instanceId);
|
|
922
|
-
let member = team.members.find(value => value.key === memberKey);
|
|
923
|
-
if (!member?.installation)
|
|
924
|
-
throw templateError('INVALID_ARGUMENT', 'No optional installation in this slot');
|
|
925
|
-
const job = this.jobs.get(actor, { jobId: member.installation.jobId });
|
|
926
|
-
if (!job.committed)
|
|
927
|
-
throw templateError('RECOVERY_REQUIRED', 'Resume the original creation job first', { jobId: job.jobId });
|
|
928
|
-
await this.attachCommittedMember(job);
|
|
929
|
-
team = this.jobs.readTeam(instanceId);
|
|
930
|
-
member = team.members.find(value => value.key === memberKey);
|
|
931
|
-
if (member.state !== 'joined') {
|
|
932
|
-
await this.updateTeamMember(instanceId, memberKey, value => { value.state = 'joining'; delete value.pending.error; });
|
|
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;
|
|
528
|
+
this.jobs.save(job);
|
|
529
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
530
|
+
fs.rmSync(file, { force: true });
|
|
531
|
+
this.phase(job, 'downloading');
|
|
933
532
|
try {
|
|
934
|
-
|
|
935
|
-
throw templateError('OWNER_DIRECTORY_PENDING', 'Owner publication and verification dependencies are unavailable');
|
|
936
|
-
const evidence = await this.deps.joining.ownership(member.aid, actor, team.hostAid);
|
|
937
|
-
await this.updateTeamMember(instanceId, memberKey, value => { value.pending.ownershipEvidence = evidence; });
|
|
938
|
-
team = await this.ownedTeam(actor, instanceId);
|
|
939
|
-
member = team.members.find(value => value.key === memberKey);
|
|
940
|
-
const directory = await this.deps.joining.verifyDirectory(team, member);
|
|
941
|
-
if (!directory.revision)
|
|
942
|
-
throw templateError('OWNER_DIRECTORY_PENDING', 'Verified Owner directory revision required');
|
|
943
|
-
await this.updateTeamMember(instanceId, memberKey, value => { value.pending.directory = directory; });
|
|
944
|
-
await this.deps.joining.addRelationships(team, member);
|
|
945
|
-
// Revalidate after side effects. A lost response retries only idempotent membership additions.
|
|
946
|
-
await this.ownedTeam(actor, instanceId);
|
|
947
|
-
await this.deps.joining.ownership(member.aid, actor, team.hostAid);
|
|
948
|
-
await this.deps.joining.verifyDirectory(team, member);
|
|
949
|
-
await this.updateTeamMember(instanceId, memberKey, value => { value.pending.relationshipsApplied = true; value.state = 'joined'; });
|
|
533
|
+
await this.step(job, () => this.deps.download(download.source.download?.shareId, file, download.source.location));
|
|
950
534
|
}
|
|
951
535
|
catch (error) {
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
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');
|
|
955
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 } });
|
|
956
548
|
}
|
|
957
|
-
|
|
958
|
-
|
|
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);
|
|
959
556
|
}
|
|
960
557
|
async inspect(actor, requestId, args) {
|
|
961
558
|
const members = Object.fromEntries(Object.entries(args.members).map(([key, member]) => [key, { aid: member.source.kind === 'agent' ? member.source.aid : '',
|
|
@@ -963,142 +560,180 @@ export class AgentTemplateService {
|
|
|
963
560
|
for (const member of Object.values(members))
|
|
964
561
|
if (member.aid)
|
|
965
562
|
await this.deps.authorize(actor, member.aid);
|
|
966
|
-
const
|
|
967
|
-
if (
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
const generation = 1;
|
|
971
|
-
const collectionKey = job.jobId + ':' + generation;
|
|
972
|
-
job.checkpoint.collectionKey = collectionKey;
|
|
973
|
-
job.freeze = { state: 'acquiring', generation, frozenAt: null, selectionExpiresAt: null };
|
|
974
|
-
job.status = 'running';
|
|
975
|
-
job.phase = 'acquiring';
|
|
976
|
-
this.jobs.save(job);
|
|
977
|
-
const held = { owner: job.jobId, releases: [] };
|
|
978
|
-
this.collections.set(collectionKey, held);
|
|
979
|
-
try {
|
|
980
|
-
for (const [key, member] of Object.entries(members).sort((a, b) => a[1].aid.localeCompare(b[1].aid))) {
|
|
981
|
-
if (!member.aid)
|
|
982
|
-
continue;
|
|
983
|
-
job.checkpoint.tokens = { ...job.checkpoint.tokens, [key]: collectionKey + ':' + key };
|
|
984
|
-
this.jobs.save(job);
|
|
985
|
-
try {
|
|
986
|
-
held.releases.push({ key, release: await this.deps.hold(member.aid, collectionKey + ':' + key) });
|
|
987
|
-
}
|
|
988
|
-
catch (error) {
|
|
989
|
-
throw templateError(error.code ?? 'AGENT_BUSY', error.message, { memberKey: key });
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
job.freeze.state = 'held';
|
|
993
|
-
job.freeze.frozenAt = Date.now();
|
|
994
|
-
job.freeze.selectionExpiresAt = job.freeze.frozenAt + SELECTION_MS;
|
|
995
|
-
this.jobs.save(job);
|
|
996
|
-
const timer = setTimeout(() => {
|
|
997
|
-
void this.cancelInternal(actor, job.jobId, 'selection_expired')
|
|
998
|
-
.catch(error => logger.warn('[Template] Selection cleanup failed: ' + String(error)));
|
|
999
|
-
}, SELECTION_MS);
|
|
1000
|
-
timer.unref?.();
|
|
1001
|
-
this.timers.set(job.jobId, timer);
|
|
1002
|
-
this.launch(job, async (current) => {
|
|
1003
|
-
this.phase(current, 'inventory');
|
|
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');
|
|
1004
567
|
const sources = {};
|
|
1005
|
-
for (const [key, member] of Object.entries(
|
|
568
|
+
for (const [key, member] of Object.entries(args.members)) {
|
|
1006
569
|
sources[key] = member.source.kind === 'agent'
|
|
1007
|
-
? await this.step(
|
|
1008
|
-
: { 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 } };
|
|
1009
572
|
}
|
|
1010
|
-
|
|
1011
|
-
this.jobs.save(
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
current.phase = 'awaiting_selection';
|
|
1017
|
-
current.resumable = false;
|
|
1018
|
-
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);
|
|
1019
579
|
});
|
|
1020
|
-
}
|
|
1021
|
-
catch (error) {
|
|
1022
|
-
job.error = { code: error.code ?? 'AGENT_BUSY', message: error.message, retryable: false, details: error.details };
|
|
1023
|
-
await this.release(job, 'failed');
|
|
1024
|
-
job.status = job.freeze.state === 'released' ? 'failed' : 'cancelling';
|
|
1025
|
-
this.jobs.save(job);
|
|
1026
|
-
}
|
|
1027
580
|
return this.view(job);
|
|
1028
581
|
}
|
|
1029
|
-
async
|
|
582
|
+
async collect(actor, requestId, args, context) {
|
|
1030
583
|
const inspection = this.jobs.get(actor, { jobId: args.inspectionJobId });
|
|
1031
|
-
if (inspection.action !== 'inspect'
|
|
1032
|
-
|
|
1033
|
-
if (inspection.freeze?.buildJobId) {
|
|
1034
|
-
const built = this.jobs.read(inspection.freeze.buildJobId);
|
|
1035
|
-
if (built.fingerprint !== templateFingerprint({ action: 'build', args }))
|
|
1036
|
-
throw templateError('CONFLICT', 'Inspection was already used');
|
|
1037
|
-
this.jobs.bindRequest(actor, requestId, 'build', args, built.jobId);
|
|
1038
|
-
return this.view(built);
|
|
1039
|
-
}
|
|
1040
|
-
if (inspection.freeze?.state !== 'held' || inspection.freeze.selectionExpiresAt <= Date.now()) {
|
|
1041
|
-
throw templateError('EXPIRED', 'Inspection is no longer frozen');
|
|
1042
|
-
}
|
|
1043
|
-
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
|
|
1044
586
|
|| Object.keys(inspection.members).sort().join() !== Object.keys(args.members).sort().join()) {
|
|
1045
|
-
throw templateError('CONFLICT', '
|
|
587
|
+
throw templateError('CONFLICT', 'Completed matching module inspection required');
|
|
1046
588
|
}
|
|
1047
|
-
await this.tool('validate-selection', { inventory: inspection.result, metadata: args.metadata, members: args.members });
|
|
1048
589
|
for (const aid of templateJobAids(inspection))
|
|
1049
590
|
await this.deps.authorize(actor, aid);
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
job.
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
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);
|
|
1064
607
|
this.jobs.save(job);
|
|
1065
|
-
this.jobs.save(current);
|
|
1066
|
-
held.owner = job.jobId;
|
|
1067
|
-
clearTimeout(this.timers.get(current.jobId));
|
|
1068
|
-
this.timers.delete(current.jobId);
|
|
1069
608
|
this.launch(job, async (value) => {
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
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
|
+
}
|
|
1074
629
|
const sources = structuredClone(value.checkpoint.sources);
|
|
1075
|
-
for (const [key,
|
|
1076
|
-
if (
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
throw templateError('SOURCE_CHANGED', 'Source profile or configuration changed', { memberKey: key });
|
|
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));
|
|
1080
634
|
}
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
const record = { actor, packageId, createdAt: Date.now(), data, provenance: {
|
|
1088
|
-
kind: 'build', sourceAids: templateJobAids(value), sources: value.args.inspectionJobId
|
|
1089
|
-
} };
|
|
1090
|
-
writeTemplateState(path.join(this.cache, 'packages', packageId, 'record.json'), record);
|
|
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');
|
|
1091
641
|
await this.release(value, 'completed');
|
|
1092
|
-
if (value.freeze
|
|
1093
|
-
throw templateError('RECOVERY_REQUIRED', '
|
|
1094
|
-
|
|
1095
|
-
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' } };
|
|
1096
647
|
value.status = 'succeeded';
|
|
1097
|
-
value.phase = '
|
|
648
|
+
value.phase = 'collected';
|
|
1098
649
|
this.jobs.save(value);
|
|
1099
650
|
});
|
|
1100
651
|
return this.view(job);
|
|
1101
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
|
+
}
|
|
1102
737
|
async release(job, reason) {
|
|
1103
738
|
if (!job.freeze || ['released', 'transferred'].includes(job.freeze.state))
|
|
1104
739
|
return;
|
|
@@ -1131,25 +766,53 @@ export class AgentTemplateService {
|
|
|
1131
766
|
job.error = { code: 'RECOVERY_REQUIRED', message: 'Some sources still require release', retryable: true };
|
|
1132
767
|
this.jobs.save(job);
|
|
1133
768
|
}
|
|
1134
|
-
async control(actor, requestId, action, jobId) {
|
|
769
|
+
async control(actor, requestId, action, jobId, context = {}) {
|
|
1135
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
|
+
}
|
|
1136
779
|
const first = this.jobs.bindRequest(actor, requestId, action, { jobId }, jobId);
|
|
1137
780
|
if (!first)
|
|
1138
781
|
return this.view(job);
|
|
1139
|
-
if (action === 'resume' && job.committed && job.checkpoint.memberInstall) {
|
|
1140
|
-
await this.resumeMemberJoin(actor, job.checkpoint.memberInstall.instanceId, job.checkpoint.memberInstall.memberKey);
|
|
1141
|
-
return this.view(job);
|
|
1142
|
-
}
|
|
1143
782
|
if (action === 'cancel') {
|
|
1144
783
|
await this.cancelInternal(actor, jobId, 'user_cancel');
|
|
1145
784
|
}
|
|
1146
785
|
else {
|
|
1147
|
-
if (
|
|
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)) {
|
|
1148
803
|
job.attempt++;
|
|
1149
804
|
job.status = 'queued';
|
|
1150
805
|
delete job.error;
|
|
1151
806
|
this.jobs.save(job);
|
|
1152
|
-
this.launch(job, value => this.
|
|
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));
|
|
1153
816
|
return this.view(job);
|
|
1154
817
|
}
|
|
1155
818
|
if (!job.resumable || job.action !== 'deploy' || !['paused', 'failed'].includes(job.status)) {
|
|
@@ -1175,6 +838,9 @@ export class AgentTemplateService {
|
|
|
1175
838
|
throw templateError('CONFLICT', 'Committed deployment cannot be cancelled');
|
|
1176
839
|
if (['cancelled', 'succeeded'].includes(job.status))
|
|
1177
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
|
+
}
|
|
1178
844
|
const previous = this.cancellations.get(jobId);
|
|
1179
845
|
if (previous)
|
|
1180
846
|
return previous;
|
|
@@ -1185,7 +851,15 @@ export class AgentTemplateService {
|
|
|
1185
851
|
const cancel = (async () => {
|
|
1186
852
|
await this.work.get(jobId);
|
|
1187
853
|
const current = this.jobs.read(jobId);
|
|
1188
|
-
|
|
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) {
|
|
1189
863
|
const overwrite = this.previewRecord(current.args.previewId).installMode === 'overwrite';
|
|
1190
864
|
const aid = Object.values(current.members)[0]?.aid;
|
|
1191
865
|
const release = overwrite && aid ? await this.deps.hold(aid, current.jobId) : undefined;
|
|
@@ -1208,9 +882,13 @@ export class AgentTemplateService {
|
|
|
1208
882
|
await this.release(current, reason);
|
|
1209
883
|
}
|
|
1210
884
|
if (!current.freeze || current.freeze.state === 'released') {
|
|
885
|
+
if (beforeUpgradePreview)
|
|
886
|
+
current.checkpoint.restored = true;
|
|
1211
887
|
current.status = 'cancelled';
|
|
1212
888
|
current.phase = reason;
|
|
1213
889
|
this.jobs.save(current);
|
|
890
|
+
if (beforeUpgradePreview)
|
|
891
|
+
await this.completeRecovery(current.args.targetAid);
|
|
1214
892
|
}
|
|
1215
893
|
})().finally(() => { this.cancellations.delete(jobId); });
|
|
1216
894
|
this.cancellations.set(jobId, cancel);
|
|
@@ -1225,19 +903,247 @@ export class AgentTemplateService {
|
|
|
1225
903
|
const record = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1226
904
|
if (record.actor !== actor)
|
|
1227
905
|
throw templateError('NOT_ALLOWED', 'Package belongs to another principal');
|
|
1228
|
-
const pinned = this.jobs.list().some(job => job.args.packageId === packageId && job.action === 'deploy'
|
|
1229
|
-
&& !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)));
|
|
1230
909
|
if (!pinned && record.createdAt < Date.now() - 7 * 86400_000)
|
|
1231
910
|
throw templateError('EXPIRED', 'Package expired');
|
|
1232
911
|
return record;
|
|
1233
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
|
+
}
|
|
1234
1143
|
async push(job) {
|
|
1235
1144
|
const record = this.packageRecord(job.actor, job.args.packageId);
|
|
1236
1145
|
for (const aid of record.provenance.sourceAids ?? [])
|
|
1237
|
-
await this.step(job, () => this.deps.authorize(job.actor, aid));
|
|
1238
|
-
if (record.data.scan.findings.some((item) => !job.args.releasedFindings.includes(item.id))) {
|
|
1239
|
-
throw templateError('SCAN_BLOCKED', 'Release the package scan findings before upload');
|
|
1240
|
-
}
|
|
1146
|
+
await this.step(job, () => this.deps.authorize(job.actor, aid, job.action === 'upgrade' ? job.jobId : undefined));
|
|
1241
1147
|
const { aid, path: remote } = job.args.location;
|
|
1242
1148
|
const metadata = record.data.metadata;
|
|
1243
1149
|
if (remote !== '/templates/' + metadata.id + '/' + metadata.id + '-' + metadata.version + '.ectpl') {
|
|
@@ -1246,7 +1152,10 @@ export class AgentTemplateService {
|
|
|
1246
1152
|
this.phase(job, 'uploading');
|
|
1247
1153
|
job.checkpoint.uploadIntent = true;
|
|
1248
1154
|
this.jobs.save(job);
|
|
1249
|
-
|
|
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));
|
|
1250
1159
|
job.result = { packageId: record.packageId, location: job.args.location, digest: record.data.digest,
|
|
1251
1160
|
size: record.data.size, metadata };
|
|
1252
1161
|
job.status = 'succeeded';
|
|
@@ -1254,64 +1163,47 @@ export class AgentTemplateService {
|
|
|
1254
1163
|
this.jobs.save(job);
|
|
1255
1164
|
}
|
|
1256
1165
|
async pull(job) {
|
|
1257
|
-
|
|
1258
|
-
let
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
}
|
|
1278
|
-
|
|
1279
|
-
});
|
|
1166
|
+
const source = job.args.source;
|
|
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');
|
|
1178
|
+
}
|
|
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));
|
|
1280
1188
|
}
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
const { file: _file, ...data } = record.data;
|
|
1286
|
-
job.result = { ...data, packageId: record.packageId };
|
|
1287
|
-
}
|
|
1288
|
-
else {
|
|
1289
|
-
const packageId = 'package_' + randomUUID();
|
|
1290
|
-
const directory = path.join(this.cache, 'packages', packageId);
|
|
1291
|
-
fs.mkdirSync(directory, { recursive: true });
|
|
1292
|
-
job.checkpoint.packageId = packageId;
|
|
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';
|
|
1293
1193
|
this.jobs.save(job);
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|| data.memberReferences?.optional?.length || data.metadata.version !== release.version) {
|
|
1304
|
-
throw templateError('INTEGRITY_FAILED', 'Downloaded package differs from the attested single-Agent release');
|
|
1194
|
+
}
|
|
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));
|
|
1305
1203
|
}
|
|
1306
1204
|
}
|
|
1307
|
-
|
|
1308
|
-
data: { ...data, file: archivePath }, provenance: { kind: 'import', source,
|
|
1309
|
-
...(binding ? { memberInstallId: binding.memberInstallId, release: binding.release } : {}) } });
|
|
1310
|
-
job.result = { ...data, packageId, ...(binding ? { memberInstallId: binding.memberInstallId, release: binding.release } : {}) };
|
|
1205
|
+
throw error;
|
|
1311
1206
|
}
|
|
1312
|
-
job.status = 'succeeded';
|
|
1313
|
-
job.phase = 'completed';
|
|
1314
|
-
this.jobs.save(job);
|
|
1315
1207
|
}
|
|
1316
1208
|
previewRecord(id) {
|
|
1317
1209
|
if (!TEMPLATE_PREVIEW_ID.test(id))
|
|
@@ -1320,23 +1212,23 @@ export class AgentTemplateService {
|
|
|
1320
1212
|
}
|
|
1321
1213
|
async preview(job, overrideArgs, update) {
|
|
1322
1214
|
const args = overrideArgs ?? job.args;
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
const team = this.jobs.readTeam(binding.instanceId);
|
|
1337
|
-
contextMembers = Object.fromEntries(team.members.filter(member => member.aid).map(member => [member.key,
|
|
1338
|
-
{ aid: member.aid, projectPath: member.projectPath }]));
|
|
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
|
+
} };
|
|
1339
1228
|
}
|
|
1229
|
+
else
|
|
1230
|
+
record = this.packageRecord(job.actor, args.packageId);
|
|
1231
|
+
const keys = update ? [update.source.key] : Object.keys(record.data.members).sort();
|
|
1340
1232
|
if (keys.join() !== Object.keys(args.members).sort().join()
|
|
1341
1233
|
|| args.installMode === 'overwrite' && keys.length !== 1)
|
|
1342
1234
|
throw templateError('INVALID_ARGUMENT', 'Map every member; overwrite allows one');
|
|
@@ -1352,7 +1244,7 @@ export class AgentTemplateService {
|
|
|
1352
1244
|
for (const key of keys) {
|
|
1353
1245
|
const selected = args.members[key];
|
|
1354
1246
|
const target = selected.target;
|
|
1355
|
-
const aid = target.aid === 'auto' ? 'a' + randomUUID().replace(/-/g, '').slice(0, 14) + '.' + args.
|
|
1247
|
+
const aid = target.aid === 'auto' ? 'a' + randomUUID().replace(/-/g, '').slice(0, 14) + '.' + args.defaultAidDomain : target.aid;
|
|
1356
1248
|
let project = target.project;
|
|
1357
1249
|
if (args.installMode === 'create') {
|
|
1358
1250
|
try {
|
|
@@ -1375,7 +1267,7 @@ export class AgentTemplateService {
|
|
|
1375
1267
|
}
|
|
1376
1268
|
}
|
|
1377
1269
|
else {
|
|
1378
|
-
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));
|
|
1379
1271
|
targets[key] = await this.step(job, () => this.deps.target(aid, job.actor));
|
|
1380
1272
|
if (targets[key].targetConfig?.update?.mode === 'disabled')
|
|
1381
1273
|
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before overwrite');
|
|
@@ -1387,43 +1279,88 @@ export class AgentTemplateService {
|
|
|
1387
1279
|
members[key] = { aid, projectPath: path.resolve(project), requestId: randomUUID() };
|
|
1388
1280
|
}
|
|
1389
1281
|
if (update) {
|
|
1390
|
-
const targetAid =
|
|
1391
|
-
const team = this.jobs.listTeams().find(value => value.members.some(member => member.aid === targetAid));
|
|
1392
|
-
contextMembers = Object.fromEntries((team?.members ?? []).filter(member => member.aid && member.aid !== targetAid)
|
|
1393
|
-
.map(member => [member.key, { aid: member.aid, projectPath: member.projectPath }]));
|
|
1282
|
+
const targetAid = job.args.targetAid;
|
|
1394
1283
|
for (const other of this.deps.updates.targets().filter(value => value.aid !== targetAid)) {
|
|
1395
|
-
const project =
|
|
1284
|
+
const project = members[keys[0]].projectPath;
|
|
1396
1285
|
if (other.projectPath === project || other.projectPath.startsWith(project + path.sep) || project.startsWith(other.projectPath + path.sep)) {
|
|
1397
1286
|
throw templateError('SHARED_RESOURCE_CONFLICT', 'The target workspace is shared with another Agent', { affectedAids: [other.aid] });
|
|
1398
1287
|
}
|
|
1399
1288
|
}
|
|
1400
1289
|
}
|
|
1401
1290
|
const values = Object.values(members);
|
|
1402
|
-
const identityAids = new Set([job.actor, this.deps.hostAid, ...values.map(member => member.aid)
|
|
1403
|
-
...Object.values(contextMembers ?? {}).map((member) => member.aid)]);
|
|
1291
|
+
const identityAids = new Set([job.actor, this.deps.hostAid, ...values.map(member => member.aid)]);
|
|
1404
1292
|
if (record.data.memberReferences?.external?.some((contact) => identityAids.has(contact.aid))) {
|
|
1405
1293
|
throw templateError('CONFLICT', 'External AID conflicts with a Team identity');
|
|
1406
1294
|
}
|
|
1407
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)
|
|
1408
1296
|
|| right.projectPath.startsWith(left.projectPath + path.sep)))))
|
|
1409
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
|
+
}
|
|
1410
1329
|
const data = await this.executeTool(job, 'preview', { archivePath: record.data.file, digest: record.data.digest,
|
|
1411
|
-
installMode: args.installMode, members, targets, selections
|
|
1330
|
+
installMode: args.installMode, members, targets, selections,
|
|
1412
1331
|
out, home: this.deps.root, ownerAid: job.actor, hostAid: this.deps.hostAid,
|
|
1413
|
-
...(
|
|
1414
|
-
...(update ? { sourceMemberKey: keys[0],
|
|
1415
|
-
|
|
1416
|
-
otherAgents: this.deps.updates.targets().filter(target => target.aid !==
|
|
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) } } : {}),
|
|
1417
1336
|
agentSchemaVersion: snapshot.schemaVersion, providers: snapshot.providers });
|
|
1418
1337
|
const plans = {};
|
|
1338
|
+
const modelUnavailable = [];
|
|
1419
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
|
+
}
|
|
1420
1346
|
for (const key of keys) {
|
|
1421
1347
|
const config = data.configs[key];
|
|
1422
1348
|
const baseagent = config.active_baseagent;
|
|
1423
1349
|
const model = config.baseagents?.[baseagent];
|
|
1424
1350
|
const profile = data.profiles[key];
|
|
1351
|
+
if (!model?.provider || !model?.model)
|
|
1352
|
+
modelUnavailable.push(key);
|
|
1425
1353
|
try {
|
|
1426
1354
|
await this.step(job, () => this.deps.validateModels(config, data.members.find((member) => member.key === key).providers));
|
|
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 {
|
|
1427
1364
|
if (args.installMode === 'create') {
|
|
1428
1365
|
const plan = { aid: members[key].aid, project: members[key].projectPath, baseagent,
|
|
1429
1366
|
provider: model?.provider, model: model?.model, effort: model?.effort, chatmode: config.chatmode,
|
|
@@ -1437,46 +1374,50 @@ export class AgentTemplateService {
|
|
|
1437
1374
|
unresolved.push({ memberKey: key, code: error.code ?? 'UNRESOLVED', message: error.message });
|
|
1438
1375
|
}
|
|
1439
1376
|
}
|
|
1440
|
-
if (binding) {
|
|
1441
|
-
const plan = JSON.parse(fs.readFileSync(data.planFile, 'utf8'));
|
|
1442
|
-
plan.memberInstall = { memberInstallId: binding.memberInstallId, instanceId: binding.instanceId, memberKey: binding.memberKey,
|
|
1443
|
-
sourceMemberKey: keys[0], ownerAid: binding.ownerAid, hostAid: binding.hostAid,
|
|
1444
|
-
agentTemplateId: binding.release.agentTemplateId, releaseId: binding.release.releaseId, digest: binding.release.digest,
|
|
1445
|
-
finalProfile: data.profiles[keys[0]], finalAccess: data.configs[keys[0]].access ?? null };
|
|
1446
|
-
writeTemplateState(data.planFile, plan);
|
|
1447
|
-
}
|
|
1448
1377
|
let updateRecord;
|
|
1449
1378
|
if (update) {
|
|
1450
|
-
const
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
...(team && teamMember ? { teamBaseline: { instanceId: team.instanceId, memberKey: teamMember.key, diverged: true } } : {}) } };
|
|
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 } } };
|
|
1456
1384
|
const plan = JSON.parse(fs.readFileSync(data.planFile, 'utf8'));
|
|
1457
1385
|
plan.update = updateRecord;
|
|
1458
1386
|
writeTemplateState(data.planFile, plan);
|
|
1459
1387
|
}
|
|
1460
1388
|
const planDigest = unresolved.length ? null : 'sha256:' + templateFingerprint(JSON.parse(fs.readFileSync(data.planFile, 'utf8')));
|
|
1461
1389
|
const preview = { actor: job.actor, previewId, packageId: record.packageId, createdAt: Date.now(),
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
...(
|
|
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 } : {}) };
|
|
1465
1393
|
writeTemplateState(path.join(out, 'record.json'), preview);
|
|
1466
|
-
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,
|
|
1467
1396
|
installMode: preview.installMode, members: Object.fromEntries(keys.map(key => [key, {
|
|
1468
|
-
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
|
+
} } : {})
|
|
1469
1403
|
}])),
|
|
1470
1404
|
bindingOwnerAid: job.actor, expiresAt: preview.createdAt + 3600_000, executable: !unresolved.length, unresolved,
|
|
1471
|
-
changes: data.changes ?? [], ignored: data.ignored ?? [], warnings: data.warnings ?? [] };
|
|
1472
|
-
if (
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
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
|
+
}
|
|
1480
1421
|
job.status = 'succeeded';
|
|
1481
1422
|
job.phase = 'completed';
|
|
1482
1423
|
this.jobs.save(job);
|
|
@@ -1487,10 +1428,6 @@ export class AgentTemplateService {
|
|
|
1487
1428
|
const aid = Object.values(record.members)[0];
|
|
1488
1429
|
return withFileLock(path.join(this.cache, 'update-targets', templateFingerprint(aid.aid) + '.lock'), () => this.acceptDeployment(actor, requestId, args, record));
|
|
1489
1430
|
}
|
|
1490
|
-
if (record.memberInstall) {
|
|
1491
|
-
await this.memberInstall(actor, record.memberInstall.memberInstallId);
|
|
1492
|
-
return this.jobs.withTeams(() => this.acceptDeployment(actor, requestId, args, record));
|
|
1493
|
-
}
|
|
1494
1431
|
return this.acceptDeployment(actor, requestId, args, record);
|
|
1495
1432
|
}
|
|
1496
1433
|
async acceptDeployment(actor, requestId, args, record) {
|
|
@@ -1498,54 +1435,6 @@ export class AgentTemplateService {
|
|
|
1498
1435
|
throw templateError('NOT_ALLOWED', 'Preview belongs to another principal');
|
|
1499
1436
|
if (!record.planDigest || record.planDigest !== args.planDigest)
|
|
1500
1437
|
throw templateError('CONFLICT', 'Executable preview and matching planDigest required');
|
|
1501
|
-
const binding = record.memberInstall;
|
|
1502
|
-
let team;
|
|
1503
|
-
let slot;
|
|
1504
|
-
if (binding) {
|
|
1505
|
-
team = this.jobs.readTeam(binding.instanceId);
|
|
1506
|
-
slot = team.members.find(member => member.key === binding.memberKey);
|
|
1507
|
-
if (team.ownerAid !== actor || team.hostAid !== this.deps.hostAid || !slot?.optional
|
|
1508
|
-
|| slot.agentTemplateId !== binding.declaration.agentTemplateId)
|
|
1509
|
-
throw templateError('CONFLICT', 'Original Team binding changed');
|
|
1510
|
-
// Recover even if the process stopped after the job write but before the slot write.
|
|
1511
|
-
const prior = slot.installation ? this.jobs.read(slot.installation.jobId) : this.jobs.list().find(candidate => {
|
|
1512
|
-
if (candidate.action !== 'deploy' || candidate.actor !== actor)
|
|
1513
|
-
return false;
|
|
1514
|
-
const file = TEMPLATE_PREVIEW_ID.test(candidate.args.previewId ?? '')
|
|
1515
|
-
? path.join(this.cache, 'previews', candidate.args.previewId, 'record.json') : '';
|
|
1516
|
-
if (!file || !fs.existsSync(file))
|
|
1517
|
-
return false;
|
|
1518
|
-
const original = this.previewRecord(candidate.args.previewId).memberInstall;
|
|
1519
|
-
return original?.instanceId === binding.instanceId && original.memberKey === binding.memberKey;
|
|
1520
|
-
});
|
|
1521
|
-
if (prior) {
|
|
1522
|
-
const original = this.previewRecord(prior.args.previewId).memberInstall;
|
|
1523
|
-
if (!slot.installation) {
|
|
1524
|
-
slot.installation = { jobId: prior.jobId, memberInstallId: original.memberInstallId,
|
|
1525
|
-
sourceMemberKey: original.release.sourceMemberKey, release: original.release };
|
|
1526
|
-
slot.state = 'reserved';
|
|
1527
|
-
this.jobs.saveTeam(team, team.revision);
|
|
1528
|
-
}
|
|
1529
|
-
this.jobs.bindRequest(actor, requestId, 'deploy', args, prior.jobId);
|
|
1530
|
-
if (prior.status === 'queued' && !prior.checkpoint.memberInstall) {
|
|
1531
|
-
prior.checkpoint.memberInstall = structuredClone(original);
|
|
1532
|
-
prior.resumable = true;
|
|
1533
|
-
this.jobs.save(prior);
|
|
1534
|
-
try {
|
|
1535
|
-
this.jobs.associate(prior);
|
|
1536
|
-
this.launch(prior, job => this.runInstallation(job));
|
|
1537
|
-
}
|
|
1538
|
-
catch (error) {
|
|
1539
|
-
prior.status = 'paused';
|
|
1540
|
-
prior.error = { code: error.code ?? 'RECOVERY_REQUIRED', message: error.message, retryable: true };
|
|
1541
|
-
this.jobs.save(prior);
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
return this.view(prior);
|
|
1545
|
-
}
|
|
1546
|
-
if (slot.aid || slot.state !== 'available')
|
|
1547
|
-
throw templateError('CONFLICT', 'Optional slot is occupied');
|
|
1548
|
-
}
|
|
1549
1438
|
const prior = this.jobs.list().find(job => job.actor === actor && job.action === 'deploy' && job.args.previewId === args.previewId);
|
|
1550
1439
|
if (prior) {
|
|
1551
1440
|
if (prior.fingerprint !== templateFingerprint({ action: 'deploy', args }))
|
|
@@ -1559,7 +1448,7 @@ export class AgentTemplateService {
|
|
|
1559
1448
|
throw templateError('TARGET_CHANGED', 'Host configuration changed');
|
|
1560
1449
|
if (record.installMode === 'overwrite') {
|
|
1561
1450
|
const aid = Object.values(record.members)[0].aid;
|
|
1562
|
-
const active = this.jobs.list().find(job => job.action
|
|
1451
|
+
const active = this.jobs.list().find(job => ['deploy', 'upgrade'].includes(job.action) && !job.committed && !job.checkpoint.restored
|
|
1563
1452
|
&& Object.values(job.members).some(member => member.aid === aid));
|
|
1564
1453
|
if (active)
|
|
1565
1454
|
throw templateError('CONFLICT', 'Resume the original target job', { jobId: active.jobId });
|
|
@@ -1575,13 +1464,6 @@ export class AgentTemplateService {
|
|
|
1575
1464
|
}
|
|
1576
1465
|
}
|
|
1577
1466
|
const accepted = this.jobs.accept(actor, requestId, 'deploy', args, structuredClone(record.members));
|
|
1578
|
-
if (binding) {
|
|
1579
|
-
accepted.job.checkpoint.memberInstall = structuredClone(binding);
|
|
1580
|
-
slot.installation = { jobId: accepted.job.jobId, memberInstallId: binding.memberInstallId,
|
|
1581
|
-
sourceMemberKey: binding.release.sourceMemberKey, release: structuredClone(binding.release) };
|
|
1582
|
-
slot.state = 'reserved';
|
|
1583
|
-
this.jobs.saveTeam(team, team.revision);
|
|
1584
|
-
}
|
|
1585
1467
|
accepted.job.resumable = true;
|
|
1586
1468
|
this.jobs.save(accepted.job);
|
|
1587
1469
|
try {
|
|
@@ -1611,28 +1493,22 @@ export class AgentTemplateService {
|
|
|
1611
1493
|
async install(job) {
|
|
1612
1494
|
this.current(job);
|
|
1613
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
|
+
}
|
|
1614
1503
|
if (record.installMode === 'overwrite')
|
|
1615
1504
|
return this.runOverwrite(job, record);
|
|
1616
|
-
if (record.memberInstall) {
|
|
1617
|
-
const binding = await this.memberInstall(job.actor, record.memberInstall.memberInstallId);
|
|
1618
|
-
if (templateFingerprint(binding) !== templateFingerprint(record.memberInstall))
|
|
1619
|
-
throw templateError('CONFLICT', 'Frozen member installation changed');
|
|
1620
|
-
job.checkpoint.memberInstall = structuredClone(binding);
|
|
1621
|
-
this.jobs.save(job);
|
|
1622
|
-
await this.updateTeamMember(binding.instanceId, binding.memberKey, member => {
|
|
1623
|
-
if (member.installation?.jobId !== job.jobId)
|
|
1624
|
-
throw templateError('CONFLICT', 'Slot is reserved by another job');
|
|
1625
|
-
member.state = 'creating';
|
|
1626
|
-
});
|
|
1627
|
-
}
|
|
1628
1505
|
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
1629
1506
|
throw templateError('CONFLICT', 'Host configuration changed; team remains paused');
|
|
1630
1507
|
const plan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
1631
1508
|
if (record.planDigest !== 'sha256:' + templateFingerprint(plan))
|
|
1632
1509
|
throw templateError('CONFLICT', 'Frozen team plan changed');
|
|
1633
|
-
for (const
|
|
1510
|
+
for (const key of Object.keys(record.data.configs)) {
|
|
1634
1511
|
await this.step(job, () => this.deps.installation.validatePlan(record.plans[key]));
|
|
1635
|
-
await this.step(job, () => this.deps.validateModels(config, record.data.members.find((member) => member.key === key).providers));
|
|
1636
1512
|
}
|
|
1637
1513
|
const legacyProfiles = false;
|
|
1638
1514
|
if (job.checkpoint.resourcesApplied)
|
|
@@ -1699,7 +1575,7 @@ export class AgentTemplateService {
|
|
|
1699
1575
|
job.activating = true;
|
|
1700
1576
|
job.phase = 'activating';
|
|
1701
1577
|
this.jobs.save(job);
|
|
1702
|
-
for (const member of Object.
|
|
1578
|
+
for (const [key, member] of Object.entries(job.members)) {
|
|
1703
1579
|
await this.step(job, () => this.deps.installation.authorize(job.actor));
|
|
1704
1580
|
await this.step(job, () => this.deps.installation.verify(member.aid));
|
|
1705
1581
|
member.phase = 'activating';
|
|
@@ -1712,8 +1588,10 @@ export class AgentTemplateService {
|
|
|
1712
1588
|
return;
|
|
1713
1589
|
}
|
|
1714
1590
|
member.phase = 'active';
|
|
1715
|
-
member.runtimeReady =
|
|
1591
|
+
member.runtimeReady = this.deps.installation.ready(member.aid);
|
|
1716
1592
|
this.jobs.save(job);
|
|
1593
|
+
if (!member.runtimeReady && !record.modelUnavailable?.includes(key))
|
|
1594
|
+
throw templateError('TEAM_NOT_READY', 'A prepared member is unavailable');
|
|
1717
1595
|
}
|
|
1718
1596
|
this.current(job);
|
|
1719
1597
|
job.phase = 'verifying';
|
|
@@ -1721,18 +1599,15 @@ export class AgentTemplateService {
|
|
|
1721
1599
|
await this.step(job, () => this.executeTool(job, 'verify-installation', { planFile: record.data.planFile }));
|
|
1722
1600
|
for (const [key, member] of Object.entries(job.members)) {
|
|
1723
1601
|
await this.step(job, () => this.deps.installation.verify(member.aid));
|
|
1724
|
-
if (!this.deps.installation.ready(member.aid))
|
|
1602
|
+
if (!this.deps.installation.ready(member.aid) && !record.modelUnavailable?.includes(key))
|
|
1725
1603
|
throw templateError('TEAM_NOT_READY', 'A prepared member is unavailable');
|
|
1726
1604
|
await this.publishProfile(job, key, { ...record.data.profiles[key], description: record.plans[key].description }, false);
|
|
1727
1605
|
}
|
|
1728
1606
|
await this.step(job, () => this.deps.installation.authorize(job.actor));
|
|
1729
1607
|
if (record.snapshot !== templateFingerprint(this.deps.installation.hostSnapshot()))
|
|
1730
1608
|
throw templateError('CONFLICT', 'Host configuration changed before team commit');
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
version: 1, jobId: job.jobId, ownerAid: job.actor, hostAid: this.deps.hostAid,
|
|
1734
|
-
members: Object.entries(job.members).map(([key, member]) => ({ key, aid: member.aid, project: member.projectPath, profile: record.data.profiles[key] })),
|
|
1735
|
-
});
|
|
1609
|
+
await this.prepareInitialInstallation(job, record, path.join(path.dirname(record.data.planFile), 'creation-plan.json'));
|
|
1610
|
+
job.checkpoint.modelUnavailable = record.modelUnavailable ?? [];
|
|
1736
1611
|
job.committed = true;
|
|
1737
1612
|
job.activating = false;
|
|
1738
1613
|
job.status = 'succeeded';
|
|
@@ -1742,37 +1617,72 @@ export class AgentTemplateService {
|
|
|
1742
1617
|
installMode: record.installMode, committed: true, members: Object.fromEntries(Object.entries(job.members)
|
|
1743
1618
|
.map(([key, member]) => [key, { aid: member.aid, project: member.projectPath }])) };
|
|
1744
1619
|
this.jobs.save(job);
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
for (const member of Object.
|
|
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);
|
|
1752
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
|
+
}
|
|
1753
1651
|
}
|
|
1754
|
-
async
|
|
1755
|
-
const
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
this.jobs.saveTeam(team);
|
|
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'
|
|
1774
1671
|
});
|
|
1775
|
-
|
|
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);
|
|
1776
1686
|
}
|
|
1777
1687
|
async publishProfile(job, key, profile, legacyRecovery) {
|
|
1778
1688
|
const member = job.members[key];
|
|
@@ -1810,21 +1720,19 @@ export class AgentTemplateService {
|
|
|
1810
1720
|
}
|
|
1811
1721
|
async verifyUpdatePreview(actor, record, recoveryJobId) {
|
|
1812
1722
|
const update = record.update;
|
|
1813
|
-
const
|
|
1814
|
-
const
|
|
1815
|
-
if (
|
|
1816
|
-
||
|
|
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)) {
|
|
1817
1728
|
throw templateError('SOURCE_CHANGED', 'Owner, source, policy or installed lock changed since preview');
|
|
1818
1729
|
}
|
|
1819
|
-
const release = await this.fixedRelease(installed.source, update.release.releaseId, 'execute:' + randomUUID());
|
|
1820
|
-
if (templateFingerprint(release) !== templateFingerprint(update.release))
|
|
1821
|
-
throw templateError('SOURCE_CHANGED', 'Frozen release changed or was withdrawn');
|
|
1822
1730
|
const plan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
1823
1731
|
if (templateFingerprint(plan.update) !== templateFingerprint(update)
|
|
1824
1732
|
|| templateFingerprint(Object.fromEntries(plan.members.map((member) => [member.key, member.profile]))) !== templateFingerprint(record.data.profiles)) {
|
|
1825
1733
|
throw templateError('CONFLICT', 'Frozen update source, plan or profile differs from its digest');
|
|
1826
1734
|
}
|
|
1827
|
-
const profile = await this.deps.readProfile(
|
|
1735
|
+
const profile = await this.deps.readProfile(aid);
|
|
1828
1736
|
const recoveredVersion = recoveryJobId ? this.jobs.read(recoveryJobId).checkpoint.restoredProfileVersion : undefined;
|
|
1829
1737
|
if (profile.profileVersion !== (recoveredVersion ?? plan.members[0].profileVersion)
|
|
1830
1738
|
|| templateFingerprint(profile.profile) !== templateFingerprint(plan.members[0].originalProfile)) {
|
|
@@ -1844,9 +1752,6 @@ export class AgentTemplateService {
|
|
|
1844
1752
|
const frozenPlan = JSON.parse(fs.readFileSync(record.data.planFile, 'utf8'));
|
|
1845
1753
|
if (record.planDigest !== 'sha256:' + templateFingerprint(frozenPlan))
|
|
1846
1754
|
throw templateError('CONFLICT', 'Frozen overwrite plan changed');
|
|
1847
|
-
for (const [key, config] of Object.entries(record.data.configs)) {
|
|
1848
|
-
await this.step(job, () => this.deps.validateModels(config, record.data.members.find((value) => value.key === key).providers));
|
|
1849
|
-
}
|
|
1850
1755
|
await this.step(job, () => this.deps.authorize(job.actor, member.aid, job.jobId));
|
|
1851
1756
|
authorized = true;
|
|
1852
1757
|
if (job.checkpoint.backupDir && !job.checkpoint.restored)
|
|
@@ -1864,8 +1769,8 @@ export class AgentTemplateService {
|
|
|
1864
1769
|
throw templateError('UPDATE_DISABLED', 'Owner must change update.mode before overwrite');
|
|
1865
1770
|
if (record.update)
|
|
1866
1771
|
await this.step(job, () => this.verifyUpdatePreview(job.actor, record, job.jobId));
|
|
1867
|
-
else if (
|
|
1868
|
-
throw templateError('
|
|
1772
|
+
else if (current.targetConfig?.update?.key)
|
|
1773
|
+
throw templateError('USE_UPGRADE', 'Use the single upgrade action for this Agent');
|
|
1869
1774
|
job.checkpoint.runtimeStopped ??= current.runtimeStatus === 'stopped';
|
|
1870
1775
|
job.checkpoint.runtimeInactive ??= current.targetConfig?.enabled === false || current.runtimeStatus === 'stopped';
|
|
1871
1776
|
job.checkpoint.executionConfirmedAt ??= Date.now();
|
|
@@ -1874,16 +1779,14 @@ export class AgentTemplateService {
|
|
|
1874
1779
|
let planFile = record.data.planFile;
|
|
1875
1780
|
if (record.update) {
|
|
1876
1781
|
const plan = JSON.parse(fs.readFileSync(planFile, 'utf8'));
|
|
1877
|
-
|
|
1878
|
-
const lock = { schemaVersion: 2, installation: record.update.installation, pending: { jobId: job.jobId, installation } };
|
|
1879
|
-
plan.writes.push({ path: this.jobs.installationFile(member.aid), content: Buffer.from(JSON.stringify(lock, null, 2) + '\n').toString('base64'),
|
|
1880
|
-
mode: 0o600, expected: record.update.lock });
|
|
1782
|
+
plan.commitInstallation = { ...record.update.nextInstallation, committedJobId: job.jobId };
|
|
1881
1783
|
planFile = path.join(this.cache, 'previews', record.previewId, 'execution-' + job.jobId + '.json');
|
|
1882
1784
|
writeTemplateState(planFile, plan);
|
|
1883
1785
|
}
|
|
1884
1786
|
const original = await this.step(job, () => this.deps.readProfile(member.aid));
|
|
1885
1787
|
job.checkpoint.originalProfile = original;
|
|
1886
1788
|
job.checkpoint.backupDir = path.join(this.cache, 'backups', job.jobId + '-' + job.attempt);
|
|
1789
|
+
job.checkpoint.executionPlanFile = planFile;
|
|
1887
1790
|
job.checkpoint.installMode = 'overwrite';
|
|
1888
1791
|
job.checkpoint.restored = false;
|
|
1889
1792
|
this.jobs.save(job);
|
|
@@ -1895,17 +1798,21 @@ export class AgentTemplateService {
|
|
|
1895
1798
|
await this.executeTool(job, 'overlay', { operation: 'verify-applied', planFile });
|
|
1896
1799
|
if (record.update) {
|
|
1897
1800
|
const context = await this.step(job, () => this.updateAuthority(member.aid, job.actor, job.jobId));
|
|
1898
|
-
if (
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
throw templateError('SOURCE_CHANGED', 'Frozen release changed before commit');
|
|
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
|
+
}
|
|
1903
1805
|
}
|
|
1904
1806
|
job.activating = true;
|
|
1905
1807
|
this.jobs.save(job);
|
|
1906
1808
|
member.runtimeReady = this.deps.installation.ready(member.aid);
|
|
1907
|
-
if (!member.runtimeReady && !job.checkpoint.runtimeInactive)
|
|
1809
|
+
if (!member.runtimeReady && !job.checkpoint.runtimeInactive && !record.modelUnavailable?.includes(key))
|
|
1908
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 ?? [];
|
|
1909
1816
|
job.committed = true;
|
|
1910
1817
|
job.activating = false;
|
|
1911
1818
|
job.status = 'succeeded';
|
|
@@ -1913,9 +1820,27 @@ export class AgentTemplateService {
|
|
|
1913
1820
|
job.phase = 'completed';
|
|
1914
1821
|
job.result = { packageId: record.packageId, previewId: record.previewId, planDigest: record.planDigest,
|
|
1915
1822
|
installMode: 'overwrite', committed: true, members: { [key]: { aid: member.aid, project: member.projectPath } },
|
|
1916
|
-
...(record.update ? { installedRelease: record.update.release,
|
|
1917
|
-
|
|
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 ?? [] } : {}) };
|
|
1918
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
|
+
}
|
|
1919
1844
|
await this.completeRecovery(member.aid);
|
|
1920
1845
|
}
|
|
1921
1846
|
catch (error) {
|