From cd47ef4aff096efc3597ef47dc7df1f2a32c213f Mon Sep 17 00:00:00 2001 From: "haozhe.yang" Date: Wed, 1 Jul 2026 00:59:45 +0800 Subject: [PATCH] refactor(agent-core-v2): rename scoped services to encode scope - rename service interfaces and implementations to carry the Session/Agent scope prefix and Service suffix (e.g. IApprovalService -> ISessionApprovalService, ApprovalService -> SessionApprovalService) - rename LifecycleScope.Core to App in the DI base - update DI createDecorator keys to match the new identifiers - propagate the renames through server-v2 routes/transport, examples, docs, and the agent-core-dev skill --- .agents/skills/agent-core-dev/align.md | 2 +- .agents/skills/agent-core-dev/config.md | 2 +- .agents/skills/agent-core-dev/design.md | 46 +-- .../agent-core-dev/domain-boundaries.md | 2 +- .agents/skills/agent-core-dev/flags.md | 10 +- .agents/skills/agent-core-dev/implement.md | 6 +- .agents/skills/agent-core-dev/orient.md | 38 +- .agents/skills/agent-core-dev/permission.md | 2 +- .../agent-core-dev/service-authoring.md | 54 ++- .agents/skills/agent-core-dev/telemetry.md | 4 +- packages/agent-core-v2/AGENTS.md | 4 +- packages/agent-core-v2/docs/Permission.md | 10 +- .../agent-core-v2/docs/di-scope-domains.puml | 118 +++--- .../agent-core-v2/docs/di-scope-domains.svg | 2 +- packages/agent-core-v2/docs/di.md | 20 +- packages/agent-core-v2/docs/flag.md | 14 +- packages/agent-core-v2/docs/service-design.md | 42 +- .../agent-core-v2/examples/config.example.ts | 146 +++---- .../examples/interaction.example.ts | 32 +- .../agent-core-v2/examples/oauth.example.ts | 30 +- .../examples/observability.example.ts | 2 +- .../examples/persistence.example.ts | 18 +- .../agent-core-v2/examples/scope.example.ts | 22 +- .../examples/session-index.example.ts | 12 +- .../agent-core-v2/examples/session.example.ts | 14 +- .../examples/wire-record.example.ts | 12 +- packages/agent-core-v2/src/_base/di/scope.ts | 12 +- packages/agent-core-v2/src/_base/di/test.ts | 14 +- .../agent-lifecycle/agentLifecycleService.ts | 4 +- packages/agent-core-v2/src/agentFs/agentFs.ts | 12 +- .../src/agentFs/agentFsService.ts | 14 +- packages/agent-core-v2/src/agentFs/fs.ts | 12 +- .../agent-core-v2/src/agentFs/fsProcess.ts | 8 +- .../agent-core-v2/src/agentFs/fsService.ts | 28 +- packages/agent-core-v2/src/agentFs/index.ts | 2 +- .../agent-core-v2/src/approval/approval.ts | 8 +- .../src/approval/approvalService.ts | 12 +- packages/agent-core-v2/src/approval/index.ts | 2 +- packages/agent-core-v2/src/auth/auth.ts | 4 +- .../agent-core-v2/src/auth/authService.ts | 8 +- .../src/authLegacy/authLegacy.ts | 2 +- .../src/authLegacy/authLegacyService.ts | 4 +- .../src/background/background.ts | 6 +- .../src/background/backgroundService.ts | 36 +- .../src/background/configSection.ts | 2 +- .../agent-core-v2/src/background/index.ts | 2 +- .../agent-core-v2/src/background/persist.ts | 4 +- .../src/background/tools/task-list.ts | 4 +- .../src/background/tools/task-output.ts | 4 +- .../src/background/tools/task-stop.ts | 4 +- .../agent-core-v2/src/blobStore/blobStore.ts | 4 +- .../src/blobStore/blobStoreService.ts | 8 +- .../agent-core-v2/src/bootstrap/bootstrap.ts | 10 +- .../src/bootstrap/bootstrapService.ts | 4 +- .../src/chatProvider/chatProvider.ts | 2 +- .../src/chatProvider/chatProviderService.ts | 4 +- packages/agent-core-v2/src/config/config.ts | 2 +- .../agent-core-v2/src/config/configService.ts | 6 +- .../src/contextInjector/contextInjector.ts | 6 +- .../contextInjector/contextInjectorService.ts | 20 +- .../src/contextMemory/contextMemory.ts | 4 +- .../src/contextMemory/contextMemoryService.ts | 16 +- .../src/contextMemory/messageId.ts | 2 +- .../src/contextProjector/contextProjector.ts | 4 +- .../contextProjectorService.ts | 14 +- .../src/contextSize/contextSize.ts | 6 +- .../src/contextSize/contextSizeService.ts | 22 +- packages/agent-core-v2/src/cron/cron.ts | 4 +- .../agent-core-v2/src/cron/cronService.ts | 32 +- packages/agent-core-v2/src/cron/index.ts | 2 +- .../src/cron/tools/session-store.ts | 4 +- packages/agent-core-v2/src/event/event.ts | 2 +- .../agent-core-v2/src/event/eventService.ts | 4 +- .../agent-core-v2/src/eventSink/eventSink.ts | 4 +- .../src/eventSink/eventSinkService.ts | 12 +- .../src/externalHooks/configSection.ts | 2 +- .../src/externalHooks/externalHooks.ts | 6 +- .../src/externalHooks/externalHooksService.ts | 26 +- .../agent-core-v2/src/fileTools/fileTools.ts | 10 +- .../src/fileTools/fileToolsService.ts | 28 +- packages/agent-core-v2/src/fileTools/index.ts | 4 +- .../agent-core-v2/src/fileTools/tools/edit.ts | 6 +- .../agent-core-v2/src/fileTools/tools/glob.ts | 8 +- .../agent-core-v2/src/fileTools/tools/grep.ts | 14 +- .../agent-core-v2/src/fileTools/tools/read.ts | 8 +- .../src/fileTools/tools/write.ts | 6 +- .../src/filestore/fileStoreService.ts | 4 +- .../agent-core-v2/src/filestore/filestore.ts | 2 +- packages/agent-core-v2/src/filestore/index.ts | 2 +- packages/agent-core-v2/src/flag/flag.ts | 2 +- .../agent-core-v2/src/flag/flagRegistry.ts | 2 +- .../src/flag/flagRegistryService.ts | 4 +- .../agent-core-v2/src/flag/flagService.ts | 4 +- .../src/fullCompaction/fullCompaction.ts | 4 +- .../fullCompaction/fullCompactionService.ts | 56 +-- packages/agent-core-v2/src/gateway/gateway.ts | 2 +- .../src/gateway/gatewayService.ts | 26 +- packages/agent-core-v2/src/goal/goal.ts | 4 +- .../agent-core-v2/src/goal/goalService.ts | 36 +- packages/agent-core-v2/src/goal/index.ts | 2 +- .../src/goal/injection/goalInjection.ts | 4 +- .../src/goal/tools/create-goal.ts | 8 +- .../agent-core-v2/src/goal/tools/get-goal.ts | 4 +- .../src/goal/tools/set-goal-budget.ts | 4 +- .../src/goal/tools/update-goal.ts | 8 +- .../hostFolderBrowser/hostFolderBrowser.ts | 2 +- .../hostFolderBrowserService.ts | 4 +- packages/agent-core-v2/src/hostFs/hostFs.ts | 2 +- .../agent-core-v2/src/hostFs/hostFsService.ts | 4 +- packages/agent-core-v2/src/index.ts | 6 +- .../agent-core-v2/src/interaction/index.ts | 2 +- .../src/interaction/interaction.ts | 12 +- .../src/interaction/interactionService.ts | 10 +- packages/agent-core-v2/src/kaos/kaos.ts | 8 +- .../src/kaos/kaosFactoryService.ts | 4 +- .../src/llmRequestLog/llmRequestLog.ts | 6 +- .../src/llmRequestLog/llmRequestLogService.ts | 8 +- .../src/llmRequester/llmRequester.ts | 4 +- .../src/llmRequester/llmRequesterService.ts | 40 +- packages/agent-core-v2/src/log/index.ts | 2 +- packages/agent-core-v2/src/log/log.ts | 2 +- packages/agent-core-v2/src/log/logConfig.ts | 2 +- packages/agent-core-v2/src/log/logService.ts | 6 +- .../agent-core-v2/src/loop/configSection.ts | 4 +- packages/agent-core-v2/src/loop/loop.ts | 4 +- .../agent-core-v2/src/loop/loopService.ts | 48 +-- packages/agent-core-v2/src/loop/run-turn.ts | 4 +- packages/agent-core-v2/src/loop/turn-step.ts | 4 +- packages/agent-core-v2/src/loop/types.ts | 2 +- .../src/mcp/connection-manager.ts | 2 +- packages/agent-core-v2/src/mcp/mcp.ts | 4 +- packages/agent-core-v2/src/mcp/mcpService.ts | 22 +- .../src/media/registerMediaTools.ts | 8 +- .../src/media/tools/read-media.ts | 4 +- .../src/messageLegacy/messageLegacy.ts | 6 +- .../src/messageLegacy/messageLegacyService.ts | 26 +- .../src/microCompaction/configSection.ts | 2 +- .../src/microCompaction/microCompaction.ts | 8 +- .../microCompaction/microCompactionService.ts | 32 +- packages/agent-core-v2/src/model/model.ts | 2 +- .../agent-core-v2/src/model/modelService.ts | 4 +- .../src/modelCatalog/modelCatalog.ts | 2 +- .../src/modelCatalog/modelCatalogService.ts | 4 +- .../agent-core-v2/src/modelRuntime/index.ts | 2 +- .../src/modelRuntime/modelResolverService.ts | 16 +- .../src/modelRuntime/modelRuntime.ts | 10 +- .../src/permissionGate/permissionGate.ts | 6 +- .../permissionGate/permissionGateService.ts | 34 +- .../injection/permissionModeInjection.ts | 8 +- .../src/permissionMode/permissionMode.ts | 6 +- .../permissionMode/permissionModeService.ts | 24 +- .../src/permissionPolicy/permissionPolicy.ts | 6 +- .../permissionPolicyService.ts | 10 +- .../policies/auto-mode-approve.ts | 4 +- .../auto-mode-ask-user-question-deny.ts | 4 +- .../policies/exit-plan-mode-review-ask.ts | 10 +- .../policies/git-control-path-access-ask.ts | 6 +- .../policies/git-cwd-write-approve.ts | 6 +- .../policies/goal-start-review-ask.ts | 4 +- .../policies/plan-mode-guard-deny.ts | 6 +- .../policies/plan-mode-tool-approve.ts | 6 +- .../policies/session-approval-history.ts | 4 +- .../swarm-mode-agent-swarm-approve.ts | 6 +- .../policies/user-configured-allow.ts | 4 +- .../policies/user-configured-ask.ts | 4 +- .../policies/user-configured-deny.ts | 4 +- .../policies/user-configured-rule.ts | 6 +- .../policies/yolo-mode-approve.ts | 4 +- .../src/permissionRules/configSection.ts | 2 +- .../src/permissionRules/permissionRules.ts | 6 +- .../permissionRules/permissionRulesService.ts | 16 +- packages/agent-core-v2/src/plan/index.ts | 2 +- packages/agent-core-v2/src/plan/plan.ts | 6 +- .../agent-core-v2/src/plan/planService.ts | 42 +- .../src/plan/tools/enter-plan-mode.ts | 4 +- .../src/plan/tools/exit-plan-mode.ts | 4 +- packages/agent-core-v2/src/process/index.ts | 2 +- packages/agent-core-v2/src/process/process.ts | 10 +- .../src/process/processRunnerService.ts | 10 +- packages/agent-core-v2/src/profile/profile.ts | 4 +- .../src/profile/profileService.ts | 28 +- packages/agent-core-v2/src/prompt/prompt.ts | 4 +- .../agent-core-v2/src/prompt/promptService.ts | 24 +- .../src/promptLegacy/promptLegacy.ts | 8 +- .../src/promptLegacy/promptLegacyService.ts | 28 +- .../agent-core-v2/src/provider/provider.ts | 2 +- .../src/provider/providerService.ts | 4 +- packages/agent-core-v2/src/question/index.ts | 2 +- .../agent-core-v2/src/question/question.ts | 8 +- .../src/question/questionService.ts | 12 +- .../src/question/questionTools.ts | 14 +- .../src/question/questionToolsService.ts | 28 +- .../src/question/tools/ask-user.ts | 8 +- .../src/replayBuilder/replayBuilder.ts | 4 +- .../src/replayBuilder/replayBuilderService.ts | 12 +- packages/agent-core-v2/src/rpc/rpcService.ts | 80 ++-- .../sessionActivityService.ts | 10 +- .../src/session-index/sessionIndexService.ts | 4 +- .../src/session-lifecycle/sessionLifecycle.ts | 2 +- .../sessionLifecycleService.ts | 16 +- .../src/sessionLegacy/sessionLegacy.ts | 4 +- .../src/sessionLegacy/sessionLegacyService.ts | 36 +- .../agent-core-v2/src/shellTools/index.ts | 4 +- .../src/shellTools/shellTools.ts | 10 +- .../src/shellTools/shellToolsService.ts | 28 +- .../src/shellTools/tools/bash.ts | 22 +- .../src/skill/fileSkillCatalogStore.ts | 2 +- .../src/skill/globalSkillCatalog.ts | 2 +- .../src/skill/globalSkillCatalogService.ts | 4 +- .../src/skill/inMemorySkillCatalogStore.ts | 6 +- packages/agent-core-v2/src/skill/index.ts | 2 +- packages/agent-core-v2/src/skill/registry.ts | 4 +- .../agent-core-v2/src/skill/skillCatalog.ts | 6 +- .../src/skill/skillCatalogService.ts | 14 +- .../src/skill/skillCatalogStore.ts | 2 +- .../agent-core-v2/src/skill/skillService.ts | 20 +- .../src/storage/appendLogStore.ts | 2 +- .../src/storage/atomicDocumentStore.ts | 6 +- .../src/storage/inMemoryStorageService.ts | 12 +- .../src/subagentHost/agentTool.ts | 10 +- .../src/subagentHost/subagentHost.ts | 4 +- .../src/subagentHost/subagentHostService.ts | 20 +- packages/agent-core-v2/src/swarm/index.ts | 2 +- packages/agent-core-v2/src/swarm/swarm.ts | 4 +- .../agent-core-v2/src/swarm/swarmService.ts | 32 +- .../agent-core-v2/src/systemReminder/index.ts | 2 +- .../src/systemReminder/systemReminder.ts | 4 +- .../systemReminder/systemReminderService.ts | 12 +- .../src/telemetry/cloudAppender.ts | 2 +- .../src/telemetry/cloudTransport.ts | 2 +- .../src/telemetry/consoleAppender.ts | 2 +- .../agent-core-v2/src/telemetry/telemetry.ts | 2 +- .../src/telemetry/telemetryService.ts | 4 +- packages/agent-core-v2/src/terminal/index.ts | 2 +- .../agent-core-v2/src/terminal/terminal.ts | 18 +- .../src/terminal/terminalBackend.ts | 12 +- .../src/terminal/terminalService.ts | 20 +- .../agent-core-v2/src/todoList/todoList.ts | 4 +- .../src/todoList/todoListService.ts | 28 +- packages/agent-core-v2/src/tool/toolHooks.ts | 2 +- .../src/toolExecutor/toolExecutor.ts | 4 +- .../src/toolExecutor/toolExecutorService.ts | 14 +- .../agent-core-v2/src/toolRegistry/index.ts | 2 +- .../src/toolRegistry/toolRegistry.ts | 6 +- .../src/toolRegistry/toolRegistryService.ts | 8 +- .../agent-core-v2/src/toolStore/toolStore.ts | 4 +- .../src/toolStore/toolStoreService.ts | 12 +- packages/agent-core-v2/src/tooldedup/index.ts | 2 +- .../agent-core-v2/src/tooldedup/toolDedupe.ts | 8 +- .../src/tooldedup/toolDedupeService.ts | 18 +- packages/agent-core-v2/src/turn/turn.ts | 4 +- .../agent-core-v2/src/turn/turnService.ts | 28 +- packages/agent-core-v2/src/usage/index.ts | 2 +- packages/agent-core-v2/src/usage/usage.ts | 4 +- .../agent-core-v2/src/usage/usageService.ts | 16 +- .../agent-core-v2/src/userTool/userTool.ts | 4 +- .../src/userTool/userToolService.ts | 20 +- packages/agent-core-v2/src/web/index.ts | 2 +- packages/agent-core-v2/src/web/web.ts | 10 +- packages/agent-core-v2/src/web/webService.ts | 16 +- .../src/wireRecord/wireRecord.ts | 4 +- .../src/wireRecord/wireRecordService.ts | 12 +- .../src/workspaceContext/index.ts | 2 +- .../src/workspaceContext/workspaceContext.ts | 8 +- .../workspaceContextService.ts | 10 +- .../workspaceRegistry/fileWorkspaceStore.ts | 4 +- .../workspaceRegistry/workspaceRegistry.ts | 2 +- .../workspaceRegistryService.ts | 4 +- .../test/agentFs/agentFsService.test.ts | 16 +- .../test/agentFs/fsProcess.test.ts | 6 +- .../test/agentFs/fsService.test.ts | 54 +-- .../test/approval/approval.test.ts | 20 +- packages/agent-core-v2/test/approval/stubs.ts | 6 +- .../test/background/agent-timeout.test.ts | 8 +- .../test/background/background.test.ts | 34 +- .../bg-idle-notification-repro.test.ts | 36 +- .../background/foreground-persistence.test.ts | 8 +- .../test/background/heartbeat-stale.test.ts | 8 +- .../agent-core-v2/test/background/ids.test.ts | 8 +- .../test/background/manager.test.ts | 10 +- .../test/background/output-access.test.ts | 8 +- .../test/background/persist.test.ts | 2 +- .../background/persistence-compat.test.ts | 4 +- .../test/background/reconcile.test.ts | 10 +- .../test/background/rpc-events.test.ts | 22 +- .../agent-core-v2/test/background/stubs.ts | 4 +- .../test/blobStore/blobStoreService.test.ts | 12 +- .../test/blobStore/blobref.test.ts | 18 +- .../test/bootstrap/bootstrapService.test.ts | 20 +- .../chatProvider/chatProviderFactory.test.ts | 8 +- .../agent-core-v2/test/config/config.test.ts | 6 +- .../test/contextInjector/manager.test.ts | 58 +-- .../test/contextMemory/context.test.ts | 14 +- .../agent-core-v2/test/contextMemory/stubs.ts | 40 +- .../test/cron/agent-integration.test.ts | 26 +- .../agent-core-v2/test/cron/cron.e2e.test.ts | 12 +- packages/agent-core-v2/test/cron/cron.test.ts | 46 +-- .../agent-core-v2/test/cron/manager.test.ts | 52 +-- .../test/cron/manual-tick.test.ts | 36 +- .../agent-core-v2/test/cron/resume.test.ts | 48 +-- .../test/cron/subagent-skip.test.ts | 22 +- .../agent-core-v2/test/di/scope-tree.test.ts | 108 ++--- .../test/di/scoped-register.test.ts | 24 +- .../agent-core-v2/test/fileTools/edit.test.ts | 6 +- .../test/fileTools/fileToolsService.test.ts | 24 +- .../agent-core-v2/test/fileTools/glob.test.ts | 12 +- .../agent-core-v2/test/fileTools/grep.test.ts | 8 +- .../agent-core-v2/test/fileTools/read.test.ts | 12 +- .../test/fileTools/write.test.ts | 8 +- .../test/fullCompaction/full.test.ts | 26 +- .../test/gateway/gateway.test.ts | 12 +- packages/agent-core-v2/test/goal/goal.test.ts | 38 +- .../agent-core-v2/test/goal/injection.test.ts | 38 +- packages/agent-core-v2/test/harness/agent.ts | 368 +++++++++--------- packages/agent-core-v2/test/harness/index.ts | 4 +- .../test/interaction/interaction.test.ts | 26 +- .../test/kaos/kaosFactory.test.ts | 8 +- .../test/lint/domain-layers.test.ts | 2 +- .../test/llmRequester/kosong-llm.test.ts | 20 +- .../agent-core-v2/test/log/logConfig.test.ts | 4 +- .../agent-core-v2/test/log/logService.test.ts | 10 +- .../agent-core-v2/test/loop/basic.test.ts | 16 +- packages/agent-core-v2/test/mcp/mcp.test.ts | 70 ++-- .../test/media/read-media.test.ts | 16 +- .../test/message/message.test.ts | 26 +- .../test/microCompaction/micro.test.ts | 58 +-- .../test/modelRuntime/modelResolver.test.ts | 16 +- .../agent-core-v2/test/modelRuntime/stubs.ts | 6 +- .../test/permission/permissionGate.test.ts | 72 ++-- .../test/permissionMode/stubs.ts | 6 +- ...xit-plan-mode-review-ask-telemetry.test.ts | 12 +- .../goal-start-review-ask.test.ts | 6 +- .../permission-policy-service.test.ts | 74 ++-- .../test/permissionPolicy/stubs.ts | 6 +- .../test/permissionRules/stubs.ts | 6 +- .../agent-core-v2/test/plan/injection.test.ts | 34 +- .../test/plan/plan-tools-telemetry.test.ts | 16 +- packages/agent-core-v2/test/plan/plan.test.ts | 28 +- .../test/process/processRunnerService.test.ts | 16 +- .../test/profile/config-state.test.ts | 24 +- .../promptLegacy/promptLegacyService.test.ts | 36 +- .../test/question/question.test.ts | 24 +- .../session-activity/sessionActivity.test.ts | 22 +- .../test/session-index/sessionIndex.test.ts | 4 +- .../sessionLifecycle.test.ts | 10 +- .../test/shellTools/bash.test.ts | 24 +- .../test/shellTools/shellToolsService.test.ts | 22 +- .../test/skill/plugin-session-start.test.ts | 4 +- .../test/skill/skill-tool-manager.test.ts | 68 ++-- .../agent-core-v2/test/skill/skill.test.ts | 26 +- .../test/skill/skillCatalog.test.ts | 20 +- .../test/subagentHost/agent-tool.test.ts | 24 +- .../agent-core-v2/test/swarm/swarm.test.ts | 40 +- .../test/telemetry/telemetryService.test.ts | 6 +- .../test/terminal/terminalService.test.ts | 42 +- packages/agent-core-v2/test/tool/tool.test.ts | 32 +- .../test/toolDedup/tool-dedup.test.ts | 24 +- .../test/toolExecutor/tool-executor.test.ts | 18 +- packages/agent-core-v2/test/turn/stubs.ts | 30 +- packages/agent-core-v2/test/turn/turn.test.ts | 50 +-- .../agent-core-v2/test/usage/usage.test.ts | 20 +- .../test/wireRecord/index.test.ts | 32 +- .../test/wireRecord/persistence.test.ts | 30 +- .../test/wireRecord/resume.test.ts | 30 +- .../workspaceRegistryService.test.ts | 6 +- packages/server-v2/src/routes/approvals.ts | 14 +- packages/server-v2/src/routes/fs.ts | 14 +- packages/server-v2/src/routes/questions.ts | 14 +- packages/server-v2/src/routes/skills.ts | 10 +- packages/server-v2/src/routes/snapshot.ts | 4 +- packages/server-v2/src/routes/terminals.ts | 14 +- packages/server-v2/src/start.ts | 6 +- .../src/terminal/nodePtyTerminalBackend.ts | 10 +- packages/server-v2/src/transport/actionMap.ts | 58 +-- .../server-v2/src/transport/ws/eventMap.ts | 10 +- packages/server-v2/test/approvals.test.ts | 4 +- packages/server-v2/test/eventMap.test.ts | 6 +- packages/server-v2/test/messages.test.ts | 2 +- packages/server-v2/test/questions.test.ts | 6 +- packages/server-v2/test/skills.test.ts | 2 +- packages/server-v2/test/tasks.test.ts | 2 +- packages/server-v2/test/terminals.test.ts | 6 +- 382 files changed, 2852 insertions(+), 2814 deletions(-) diff --git a/.agents/skills/agent-core-dev/align.md b/.agents/skills/agent-core-dev/align.md index faa9126ec..e4ea6ade7 100644 --- a/.agents/skills/agent-core-dev/align.md +++ b/.agents/skills/agent-core-dev/align.md @@ -20,7 +20,7 @@ v1 is a **VSCode-style singleton container**: services self-register with `regis | Resolve SUT in tests | `ix.createInstance(Impl)` (common) | `ix.get(IX)` by interface — see test.md | | Scope tests | none | `createScopedTestHost` — see test.md | | Errors | `from '../../errors'` (central `KimiError`, `ErrorCodes`) | `from '#/_base/errors'` + domain co-located `XxxError` — see errors.md | -| Flags | `flags/` (process-global `FlagResolver`) | `flag/` (Core-scope `IFlagService`) — see flags.md | +| Flags | `flags/` (process-global `FlagResolver`) | `flag/` (App-scope `IFlagService`) — see flags.md | | Permission | `agent/permission/` (hardcoded chain) | `permission*` (registry + composer) — see permission.md | ## The align workflow diff --git a/.agents/skills/agent-core-dev/config.md b/.agents/skills/agent-core-dev/config.md index 36b8164c0..d96f8c72b 100644 --- a/.agents/skills/agent-core-dev/config.md +++ b/.agents/skills/agent-core-dev/config.md @@ -87,7 +87,7 @@ pass `ConfigTarget.Memory` for a per-run override that is never written to disk. ## Layout - `src/config/config.ts` — `IConfigRegistry` / `IConfigService` tokens, `ConfigSection`, `ConfigEffectiveOverlay`, event types. -- `src/config/configService.ts` — `ConfigRegistry` + `ConfigService` impl; self-registers at Core scope. +- `src/config/configService.ts` — `ConfigRegistry` + `ConfigService` impl; self-registers at App scope. - `src/config/toml.ts` — generic snake_case ↔ camelCase machinery plus the registry-aware `transformTomlData` / `applySectionToToml` entry points. Per-domain normalization lives in the section owner's `configSection.ts` (registered as `fromToml` / `toToml`); this module stays free of any other domain's semantics. - `src/config/thinking.ts` — `resolveThinkingEffort` / `resolveThinkingLevel` helpers (own a local `ThinkingConfigDefaults` structural type; do not import `profile`). - `src/config/configPure.ts` — `isPlainObject`, `deepMerge`, `omitUndefined`, `describeUnknownError`. diff --git a/.agents/skills/agent-core-dev/design.md b/.agents/skills/agent-core-dev/design.md index 997d0b33e..c85f56380 100644 --- a/.agents/skills/agent-core-dev/design.md +++ b/.agents/skills/agent-core-dev/design.md @@ -19,7 +19,7 @@ A Service = a bundle of **state** + a set of **behaviors**, bound to a **lifetim | Scope | State identity (keyed by) | Lifetime | |---|---|---| -| `Core` | none (single global instance) | the process | +| `App` | none (single global instance) | the process | | `Session` | `sessionId` | one session | | `Agent` | `agentId` | one agent | | `Turn` | `turnId` | one turn | @@ -33,7 +33,7 @@ A Service = a bundle of **state** + a set of **behaviors**, bound to a **lifetim **Q2. What is the identity of that state?** -- one global instance → **`Core`** +- one global instance → **`App`** - one per session → **`Session`** - one per agent → **`Agent`** - one per turn → **`Turn`** @@ -41,13 +41,13 @@ A Service = a bundle of **state** + a set of **behaviors**, bound to a **lifetim **Q3 (stateless). What is the shortest-lived dependency it must inject?** -A stateless Service is pulled *down* by its shortest-lived dependency: if it injects an `Agent`-scoped Service, it cannot be `Core`. Among the scopes that still satisfy every dependency, **default to the longest-lived one** (usually `Core`) to maximize reuse. Push it down only when it must inject a shorter-lived Service, or when you want to limit its visibility. +A stateless Service is pulled *down* by its shortest-lived dependency: if it injects an `Agent`-scoped Service, it cannot be `App`. Among the scopes that still satisfy every dependency, **default to the longest-lived one** (usually `App`) to maximize reuse. Push it down only when it must inject a shorter-lived Service, or when you want to limit its visibility. ### The core anti-pattern (a litmus test) -> **Do not store per-session state in a `Map` inside a `Core` Service.** +> **Do not store per-session state in a `Map` inside a `App` Service.** -This is the tell-tale sign of "should have been `Session`-scoped but was parked at `Core`". Consequences: nobody cleans the entry up when the session ends (leak); every consumer threads `sessionId` around (loss of type safety); it cannot inject `Session`/`Agent`-scoped collaborators. +This is the tell-tale sign of "should have been `Session`-scoped but was parked at `App`". Consequences: nobody cleans the entry up when the session ends (leak); every consumer threads `sessionId` around (loss of type safety); it cannot inject `Session`/`Agent`-scoped collaborators. ### One-sentence self-check @@ -71,19 +71,19 @@ The standard split is "global registry / factory" + "per-instance": | Tier | Role | Naming tends to | |---|---|---| -| `Core` | global registry / catalog / factory — knows "all of them" and how to create one | `XxxStore` / `XxxRegistry` / `XxxCatalog` | +| `App` | global registry / catalog / factory — knows "all of them" and how to create one | `XxxStore` / `XxxRegistry` / `XxxCatalog` | | `Session` / `Agent` | one instance — only the state of "this one" | `XxxService` / `ISessionXxx` / `IAgentXxx` | Canonical splits in the codebase: -- **`records`** — `ISessionStore` (`Core`) + `ISessionMetaStore` (`Session`) + `IAgentRecords` (`Agent`). -- **`config`** — `IConfigRegistry` / `IConfigService` (`Core`). -- **`kosong`** — `IProtocolHandlerRegistry` (`Core`) + `IProviderManager` (`Session`). Generation is driven by `ILLMRequester` (`Agent`) in the `llmRequester` domain. -- **`tool`** — `IToolDefinitionRegistry` (`Core`) + `IToolService` (`Agent`). +- **`records`** — `ISessionStore` (`App`) + `ISessionMetaStore` (`Session`) + `IAgentRecords` (`Agent`). +- **`config`** — `IConfigRegistry` / `IConfigService` (`App`). +- **`kosong`** — `IProtocolHandlerRegistry` (`App`) + `IProviderManager` (`Session`). Generation is driven by `ILLMRequester` (`Agent`) in the `llmRequester` domain. +- **`tool`** — `IToolDefinitionRegistry` (`App`) + `IToolService` (`Agent`). -Split when the domain genuinely has both a global view and per-instance state. Do **not** split when state lives at only one lifetime (e.g. purely `Core` like `log`; purely `Agent` like `prompt`). Do not pre-split for symmetry. +Split when the domain genuinely has both a global view and per-instance state. Do **not** split when state lives at only one lifetime (e.g. purely `App` like `log`; purely `Agent` like `prompt`). Do not pre-split for symmetry. -After the split, the `Core` Service usually plays the **factory**; most consumers inject the **per-instance** Service. Inject the `Core` factory only when you genuinely need cross-instance management. +After the split, the `App` Service usually plays the **factory**; most consumers inject the **per-instance** Service. Inject the `App` factory only when you genuinely need cross-instance management. ## 4. Choosing a calling style @@ -125,10 +125,10 @@ The three mechanisms above are also where a domain accepts new behavior without | Need | Extension point | Typical scope | |---|---|---| -| Register a new implementation / definition | a **registry / catalog** the domain queries | `Core` | +| Register a new implementation / definition | a **registry / catalog** the domain queries | `App` | | React to a fact the domain announces | an **event** on the bus | the announcing scope | | Step into an operation in order / veto | a **hook** (`onWill`/`onDid`, `OrderedHookSlot`) | the owning scope | -| Swap a backend (File ↔ DB ↔ S3) | a **Store / Storage token** at the byte layer (see persistence.md) | `Core` (composition root) | +| Swap a backend (File ↔ DB ↔ S3) | a **Store / Storage token** at the byte layer (see persistence.md) | `App` (composition root) | Closed-for-modification means: the domain's own file is not where new scenarios branch. If a new scenario forces an edit here, an extension point is missing or misplaced. @@ -185,7 +185,7 @@ domain: `` (owning scope: ) │ ├─ (inject) @ │ └─ (accessor) @ ├─ exposes (interfaces I provide, by scope) -│ ├─ Core : +│ ├─ App : │ ├─ Session : │ ├─ Agent : │ └─ Turn : — — (none) @@ -208,7 +208,7 @@ Conventions: When a domain has `accessor` consumers, draw the reverse-direction borrow next to the tree so it is never mistaken for injection: ```text -Core scope +App scope ──holds──► IScopeHandle() │ │ accessor.get() @@ -230,10 +230,10 @@ domain: `session` (owning scope: Session) ├─ serves (who uses me) │ ├─ (inject) — (none yet) │ └─ (accessor) -│ ├─ session-lifecycle @Core — archive() before disposing the child scope -│ └─ gateway / rpc @Core(edge) — session-level commands (archive, rename…) +│ ├─ session-lifecycle @App — archive() before disposing the child scope +│ └─ gateway / rpc @App(edge) — session-level commands (archive, rename…) ├─ exposes (interfaces I provide, by scope) -│ ├─ Core : — — (no global session state here) +│ ├─ App : — — (no global session state here) │ ├─ Session : ISessionService — this session's operations + child-agent set │ ├─ Agent : — — (per-agent state lives in agent-lifecycle) │ └─ Turn : — — (no per-turn session state) @@ -242,13 +242,13 @@ domain: `session` (owning scope: Session) ├─ agent-lifecycle @Session direct — drives child-agent lifecycle ├─ sessionMetaStore @Session direct — persists session metadata ├─ session-activity @Session direct — records activity - └─ event @Core direct — broadcasts session-level facts + └─ event @App direct — broadcasts session-level facts ``` Cross-scope borrow for `session`: ```text -Core scope +App scope SessionLifecycleService ──holds──┐ GatewayService ───────────holds──┼──► IScopeHandle(sessionId) │ @@ -271,8 +271,8 @@ For a multi-scope split, the `exposes` block fills more than one scope — see t - Scope is not a domain; ownership follows write authority and invariants, not read consumption. - Do not create `I{Scope}EntityService` bundles (`IAgentEntityService`, `ISessionEntityService`, `ITurnEntityService`) that re-merge multiple domains. -- No `Map` at `Core` to fake per-session state. -- Scope follows state identity; stateless Services are pulled down by their shortest-lived dependency, otherwise default to `Core`. +- No `Map` at `App` to fake per-session state. +- Scope follows state identity; stateless Services are pulled down by their shortest-lived dependency, otherwise default to `App`. - Do not pre-split a domain that has state at only one lifetime. - Need a result / I orchestrate → direct call; stating a fact → event; ordered participation / may veto → hook. - Foundational layers never know upstream ones; business code never depends on the edge layer. diff --git a/.agents/skills/agent-core-dev/domain-boundaries.md b/.agents/skills/agent-core-dev/domain-boundaries.md index bf5f05050..24b8ed9a1 100644 --- a/.agents/skills/agent-core-dev/domain-boundaries.md +++ b/.agents/skills/agent-core-dev/domain-boundaries.md @@ -84,7 +84,7 @@ The `session` domain owns only Session-level identity, metadata, lifecycle comma |---|---|---| | `sessionId`, `workspaceId`, `sessionDir`, `metaScope` | `session-context` | Seeded facts; no IO | | `SessionMeta` | `session-metadata` | Durable atomic document; entity-like | -| Open session scope registry | `session-lifecycle` | Core-scope live handles; not the persisted entity table | +| Open session scope registry | `session-lifecycle` | App-scope live handles; not the persisted entity table | | Session commands such as `archive()` | `session` | Orchestrates metadata, agent teardown, and events | | Persisted session list / get / count | `session-index` | Backend-neutral read model | | Running / idle / awaiting status | `session-activity` | Derived from interactions and active turns; owns no state | diff --git a/.agents/skills/agent-core-dev/flags.md b/.agents/skills/agent-core-dev/flags.md index 45e74b98b..5f57c3074 100644 --- a/.agents/skills/agent-core-dev/flags.md +++ b/.agents/skills/agent-core-dev/flags.md @@ -1,22 +1,22 @@ # Topic — Flags -Experimental feature-flag gating for agent-core-v2 — a Core-scope `IFlagService` resolver plus a writable `IFlagRegistry` catalog that domains contribute their flags to, backed by the `[experimental]` config section. +Experimental feature-flag gating for agent-core-v2 — a App-scope `IFlagService` resolver plus a writable `IFlagRegistry` catalog that domains contribute their flags to, backed by the `[experimental]` config section. Gate not-yet-public features behind `IFlagService.enabled(id)`, per the repository hard rule that unreleased behavior must be flag-gated. v1 was a process-global `FlagResolver` singleton over a central `FLAG_DEFINITIONS` array; v2 is a scoped DI service whose flag definitions are registered **decentrally** by each owning domain — there is no central catalog to edit. ## Layout - `src/flag/flagRegistry.ts` — `IFlagRegistry` token + `FlagDefinitionInput` / `FlagId` / `FlagSurface` types + `registerFlagDefinition` / `getContributedFlags` (import-time contribution queue). -- `src/flag/flagRegistryService.ts` — `FlagRegistryService` impl; in-memory catalog seeded from import-time contributions; Core scope. +- `src/flag/flagRegistryService.ts` — `FlagRegistryService` impl; in-memory catalog seeded from import-time contributions; App scope. - `src/flag/flag.ts` — `IFlagService` token + resolver types (`ExperimentalFlagMap`, `ExperimentalFlagConfig`, `ExperimentalFlagSource`, `ExperimentalFeatureState`) + `ExperimentalConfigSchema` / `ExperimentalConfig` (zod). -- `src/flag/flagService.ts` — `FlagService` impl + `MASTER_ENV` (`KIMI_CODE_EXPERIMENTAL_FLAG`) + `EXPERIMENTAL_SECTION` (`experimental`); reads definitions from `IFlagRegistry`; self-registers at Core scope. +- `src/flag/flagService.ts` — `FlagService` impl + `MASTER_ENV` (`KIMI_CODE_EXPERIMENTAL_FLAG`) + `EXPERIMENTAL_SECTION` (`experimental`); reads definitions from `IFlagRegistry`; self-registers at App scope. - `src/flag/index.ts` — barrel; re-exported by `src/index.ts` at the L3 block. - `src//flag.ts` — each domain that owns a flag declares it here and calls `registerFlagDefinition` at the module top level (e.g. `src/microCompaction/flag.ts`). The directory already names the domain, so the file is just `flag.ts`. ## Public surface -- `IFlagService` (DI token, Core scope): `enabled(id)`, `explain(id)`, `snapshot()`, `enabledIds()`, `explainAll()`, `setConfigOverrides(overrides)`, `registry`. -- `IFlagRegistry` (DI token, Core scope): `register(definition)`, `get(id)`, `list()` — writable catalog. `register` is the **runtime** path (tests, dynamic registration); `IFlagService.registry` exposes the same instance for hosts/UI to enumerate flags without resolving them. +- `IFlagService` (DI token, App scope): `enabled(id)`, `explain(id)`, `snapshot()`, `enabledIds()`, `explainAll()`, `setConfigOverrides(overrides)`, `registry`. +- `IFlagRegistry` (DI token, App scope): `register(definition)`, `get(id)`, `list()` — writable catalog. `register` is the **runtime** path (tests, dynamic registration); `IFlagService.registry` exposes the same instance for hosts/UI to enumerate flags without resolving them. - `registerFlagDefinition(definition)` — the **import-time** path. Domains call this from their `flag.ts` top level; contributions are queued and drained by `FlagRegistryService` when it is instantiated. - `FlagService` / `FlagRegistryService`: exported for tests and hosts that construct them directly. diff --git a/.agents/skills/agent-core-dev/implement.md b/.agents/skills/agent-core-dev/implement.md index 9c1f8d060..1462bd939 100644 --- a/.agents/skills/agent-core-dev/implement.md +++ b/.agents/skills/agent-core-dev/implement.md @@ -42,7 +42,7 @@ export class Greeter implements IGreeter { } registerScopedService( - LifecycleScope.Core, // lifetime: process-wide + LifecycleScope.App, // lifetime: process-wide IGreeter, // identity Greeter, // implementation InstantiationType.Eager, // when to construct: immediately @@ -130,10 +130,10 @@ export class WSBroadcastService extends Disposable implements IWSBroadcastServic ```ts // Eager: constructed when the scope is created -registerScopedService(LifecycleScope.Core, ILogService, LogService, InstantiationType.Eager, 'log'); +registerScopedService(LifecycleScope.App, ILogService, LogService, InstantiationType.Eager, 'log'); // Delayed: constructed on first get -registerScopedService(LifecycleScope.Core, IScopeRegistry, ScopeRegistry, InstantiationType.Delayed, 'gateway'); +registerScopedService(LifecycleScope.App, IScopeRegistry, ScopeRegistry, InstantiationType.Delayed, 'gateway'); ``` A `Delayed` service returns a **Proxy** that constructs the real instance on first property access. Listeners registered on its `onDid…` / `onWill…` events before construction are not lost — the container records them and replays the subscriptions once the instance exists. diff --git a/.agents/skills/agent-core-dev/orient.md b/.agents/skills/agent-core-dev/orient.md index 6b1235c45..d4c15c0e3 100644 --- a/.agents/skills/agent-core-dev/orient.md +++ b/.agents/skills/agent-core-dev/orient.md @@ -17,7 +17,7 @@ Classes talk only to interfaces and never care how an implementation is construc Lifetimes form a tree, from longest to shortest: ```text -Core (0) process-wide, single global instance +App (0) process-wide, single global instance └── Session (1) one session └── Agent (2) one agent └── Turn (3) one turn of conversation @@ -25,7 +25,7 @@ Core (0) process-wide, single global instance ```ts export enum LifecycleScope { - Core = 0, + App = 0, Session = 1, Agent = 2, Turn = 3, @@ -40,8 +40,8 @@ export enum LifecycleScope { A child scope sees its ancestors; a parent never sees its children. Resolution walks *up* the tree: -- ✅ A `Turn` service injects a `Session` or `Core` service (found upward). -- ❌ A `Core` service injects a `Session` service (the parent does not look down, and the child may not exist yet). +- ✅ A `Turn` service injects a `Session` or `App` service (found upward). +- ❌ An `App` service injects a `Session` service (the parent does not look down, and the child may not exist yet). > **Short-lived may inject long-lived; never the reverse.** The tree structure enforces this — it is not a matter of discipline. @@ -55,19 +55,33 @@ Deterministic: **child scopes die first; within one scope, instances dispose in - **Header only.** Comments live solely in the top-of-file `/** */` block — never beside functions, methods, or statements. The code is the source of truth for *how*; the header states *what the module exposes and the responsibility it owns*. - **Identity line first.** Start with `` `` domain (Ln) — . `` Keep an existing `(cross-cutting)` label as-is; barrels omit the layer (`` `` domain barrel — … ``). Write the role as a responsibility ("drives the turn lifecycle"), not a symbol list. -- **Impl files** add collaborators + scope: list every imported cross-domain collaborator as a role ("persists records through `records`"); read scope from `registerScopedService(LifecycleScope.X, …)`. -- **Contract files** add the public contract + scope. +- **Scope is in the filename.** `session*.ts` = Session, `agent*.ts` = Agent, no prefix = App (see service-authoring.md). State the same scope in the header so the two never drift. +- **Interface files** (`.ts`) state the public contract + scope: which `IXxx` they define and what it is for. +- **Impl files** (`Service.ts`) add collaborators + scope: list every imported cross-domain collaborator as a role ("persists records through `records`"); read scope from `registerScopedService(LifecycleScope.X, …)`. +- **Contribution files** (`.ts` / `.contrib.ts`) state what they register into the target domain (e.g. "registers the `log` config section into `config`"). +- **Pure-function / `.types` / `.errors` files** state the responsibility only — they own no scoped state, so no scope line. -Impl example: +Impl file example (`sessionService.ts`): ```ts /** * `session` domain (L6) — `ISessionService` implementation. * * Owns the session's child-agent set and session-level operations; drives - * agent lifecycle through `agent-lifecycle`, broadcasts through `event`, + * agent lifecycle through `agentLifecycle`, broadcasts through `event`, * persists session metadata through `records`, and records activity through - * `session-activity`. Bound at Session scope. + * `sessionActivity`. Bound at Session scope. + */ +``` + +Contribution file example (`config.ts` inside `log/`): + +```ts +/** + * `log` domain — registers the `log` config section into `config`. + * + * Owns the `log` section schema and its env overlay; imported for the + * registration side effect. Bound at App scope. */ ``` @@ -75,9 +89,9 @@ Barrel example: ```ts /** - * `session` domain barrel — re-exports the session facade contract - * (`session`) and its scoped service (`sessionService`). Importing this - * barrel registers the `ISessionService` binding into the scope registry. + * `session` domain barrel — re-exports the session contract (`session`), + * its scoped service (`sessionService`), and its contribution files. Importing + * this barrel registers the `ISessionService` binding into the scope registry. */ ``` diff --git a/.agents/skills/agent-core-dev/permission.md b/.agents/skills/agent-core-dev/permission.md index 3e420699e..6d7abb725 100644 --- a/.agents/skills/agent-core-dev/permission.md +++ b/.agents/skills/agent-core-dev/permission.md @@ -74,7 +74,7 @@ interface PermissionPolicyEntry { factory: (accessor: ServicesAccessor) => PermissionPolicy; } -// Core scope — collects every domain's registration +// App scope — collects every domain's registration interface IPermissionPolicyRegistry { register(entry: PermissionPolicyEntry): IDisposable; list(): readonly PermissionPolicyEntry[]; diff --git a/.agents/skills/agent-core-dev/service-authoring.md b/.agents/skills/agent-core-dev/service-authoring.md index d3dde0d10..8451e6036 100644 --- a/.agents/skills/agent-core-dev/service-authoring.md +++ b/.agents/skills/agent-core-dev/service-authoring.md @@ -4,33 +4,57 @@ How to write a Service in `packages/agent-core-v2`: file layout, naming, what go ## File layout -One folder per domain, **kebab-case**: `session/`, `session-activity/`, `contextMemory/`. Inside: +One folder per domain, **camelCase**: `session/`, `sessionActivity/`, `contextMemory/`, `toolDedup/`. Inside, six kinds of files, all flat (no subdirectories): ```text / -├── .ts ← contract: model types + interface(s) + decorator(s) + helpers -├── Service.ts ← impl: class(es) + top-level registerScopedService(...) -└── index.ts ← barrel: re-exports contract + impl (+ helpers) +├── .ts ← interface file: exactly one IXxx + its createDecorator + the types it owns +├── Service.ts ← impl file: exactly one class + exactly one registerScopedService(...) +├── .ts ← pure function(s): no Service suffix, no class, no registration +├── .ts ← contribution file (common): registers into another domain's extension point +├── .contrib.ts ← contribution file (uncommon / ad-hoc) +├── .types.ts ← shared types that no single interface owns +└── index.ts ← barrel: re-exports everything; importing it runs the domain's registrations ``` -A domain may have more than one impl file when its Services live at different scopes or carry independent responsibilities (e.g. `logService.ts` for the Core `ILogService`, `sessionLogService.ts` for the Session `ISessionLogService`). See [Multi-Service domains](#multi-service-domains). +- **One service per file.** An interface file holds exactly one injectable interface; an impl file holds exactly one class and exactly one `registerScopedService(...)`. A multi-service domain splits into one interface-file + one impl-file per service. +- **Scope is in the filename.** `session*.ts` = Session, `agent*.ts` = Agent, no scope prefix = App (see [Naming](#naming)). The header comment restates the same scope. +- A domain therefore has as many impl files as it has services (e.g. `logService.ts` for the App `ILogService`, `sessionLogService.ts` for the Session `ISessionLogService`). See [Multi-Service domains](#multi-service-domains). The package entry `src/index.ts` re-exports each domain barrel so that importing the package runs every registration side effect. ## Naming +### Interfaces and classes + | Artifact | Rule | Example | |---|---|---| -| Interface | `I` + PascalCase + `Service` suffix | `ISessionService`, `ILogService` | -| Class | PascalCase + `Service` suffix, `implements` the interface | `SessionService implements ISessionService` | -| Decorator string | lowerCamelCase of the interface name minus the leading `I`; **globally unique and stable** (it surfaces in `CyclicDependencyError.path` and "no service registered" errors) | `createDecorator('sessionService')` | -| Contract file | `.ts` (kebab domain, no `Service` suffix) | `session.ts`, `session-activity.ts` | -| Impl file | `Service.ts` (with `Service` suffix) | `sessionService.ts` | +| Interface | `I` + scope prefix + PascalCase domain + role suffix. Scope prefix: `Session` / `Agent` / none (= App). Role suffix is usually `Service`. | `ISessionLogService`, `IAgentLoopService`, `ILogService` (App) | +| Class | the interface name minus the leading `I`, plus `Service` if it does not already end in `Service`; `implements` the interface | `SessionLogService implements ISessionLogService`, `AppendLogStoreService implements IAppendLogStore` | +| Decorator string | lowerCamelCase of the interface name minus the leading `I`; **globally unique and stable** (it surfaces in `CyclicDependencyError.path` and "no service registered" errors) | `createDecorator('sessionLogService')` | | Model / non-service types | PascalCase, no `I` prefix | `SessionMeta`, `LogEntry`, `ConfigSection` | -> The `Service` suffix is the norm for injectables. Roles (facade / bus / broker / adapter) are conveyed by the interface shape and the file-header comment, not by inventing new suffixes. +The scope prefix makes a service's lifetime readable from its name. App services carry **no** prefix (App is the default, longest-lived tier); Session and Agent services always carry `Session` / `Agent`. The prefix applies to the interface, the class, and therefore the file names. -Do not name a Service after a scope or a god-object-shaped data bag. `IAgentEntityService`, `IAgentDataService`, `ISessionEntityService`, and `ITurnEntityService` re-merge domains by lifetime; name Services after the real owning domain (`IBackgroundTaskEntityService`, `ISessionMetadata`, `IPermissionRulesService`). See [domain-boundaries.md](domain-boundaries.md). +> Do **not** use the scope prefix to re-merge domains by lifetime. `IAgentEntityService`, `IAgentDataService`, `ISessionEntityService`, and `ITurnEntityService` are still banned — the prefix marks lifetime, the rest of the name must still be the real owning domain (`IBackgroundTaskEntityService`, `ISessionMetadata`, `IPermissionRulesService`). See [domain-boundaries.md](domain-boundaries.md). + +### File names + +File names derive from the interface / class names so that scope and role are visible in the tree: + +| File kind | Rule | Example (interface → file) | +|---|---|---| +| Interface file | interface name minus leading `I`, minus trailing `Service` if present; acronym-aware lowerCamelCase | `ISessionLogService` → `sessionLog.ts`; `IAppendLogStore` → `appendLogStore.ts`; `ILogService` → `log.ts` | +| Impl file | the class name; acronym-aware lowerCamelCase | `SessionLogService` → `sessionLogService.ts`; `AppendLogStoreService` → `appendLogStoreService.ts` | +| Pure-function file | the function / concern name; no `Service` suffix | `formatLogEntry.ts`, `levelEnabled.ts` | +| Contribution file (common) | the **target** domain name | `config.ts` (registers a config section), `tool.ts`, `flag.ts` | +| Contribution file (uncommon) | `.contrib.ts` | `slackWebhook.contrib.ts` | +| Shared-types file | `.types.ts` | `log.types.ts` | +| Errors file | `.errors.ts` | `appendLogStore.errors.ts` | + +Acronym-aware lowerCamelCase lowercases a leading acronym as a group: `ILLMRequester` → `llmRequester.ts`, `IWSGateway` → `wsGateway.ts`, `IOAuthToolkit` → `oauthToolkit.ts`, `IAgentRPCService` → `agentRpcService.ts`. + +Because the impl class always ends in `Service` and the interface file never does, the two files of one service never collide — even for `Store` / `Registry` / `Resolver` interfaces (`IAppendLogStore` → `appendLogStore.ts` + `appendLogStoreService.ts`). ## The contract file (`.ts`) @@ -111,7 +135,7 @@ Holds the concrete class(es) and the top-level registration. A typical impl: /** * `greet` domain (Ln) — `IGreeter` implementation. * - * … collaborators as roles ("logs through `log`") … Bound at Core scope. + * … collaborators as roles ("logs through `log`") … Bound at App scope. */ import { InstantiationType } from '#/_base/di/extensions'; @@ -131,7 +155,7 @@ export class Greeter implements IGreeter { } } -registerScopedService(LifecycleScope.Core, IGreeter, Greeter, InstantiationType.Eager, 'greet'); +registerScopedService(LifecycleScope.App, IGreeter, Greeter, InstantiationType.Eager, 'greet'); ``` What belongs here: @@ -290,7 +314,7 @@ export class Greeter implements IGreeter { hello(): Greeting { return { message: 'hi' }; } } -registerScopedService(LifecycleScope.Core, IGreeter, Greeter, InstantiationType.Eager, 'greet'); +registerScopedService(LifecycleScope.App, IGreeter, Greeter, InstantiationType.Eager, 'greet'); ``` ```ts diff --git a/.agents/skills/agent-core-dev/telemetry.md b/.agents/skills/agent-core-dev/telemetry.md index ba7ce5db7..71c579a2c 100644 --- a/.agents/skills/agent-core-dev/telemetry.md +++ b/.agents/skills/agent-core-dev/telemetry.md @@ -7,7 +7,7 @@ Telemetry is a **layer-1 root** domain (alongside `log`): pure `Core` scope, sta ## Where things live - `src/telemetry/telemetry.ts`: contract — `ITelemetryService` (facade), `ITelemetryAppender` (destination), `TelemetryProperties`, `nullTelemetryAppender`, and `TelemetryServiceOptions`. -- `src/telemetry/telemetryService.ts`: `TelemetryService` impl + `registerScopedService(LifecycleScope.Core, …)`. +- `src/telemetry/telemetryService.ts`: `TelemetryService` impl + `registerScopedService(LifecycleScope.App, …)`. - `src/telemetry/consoleAppender.ts`: `ConsoleAppender` — echoes events to a log function (dev / debug). - `src/telemetry/cloudAppender.ts`: `CloudAppender` — batches + enriches + posts to the telemetry endpoint. - `src/telemetry/cloudTransport.ts`: `CloudTransport` — HTTP transport behind `CloudAppender`. @@ -59,7 +59,7 @@ Built-in appenders: ### Registering appenders (bootstrap) -Appenders are added after the Core scope exists, by resolving the service and calling `addAppender`: +Appenders are added after the App scope exists, by resolving the service and calling `addAppender`: ```ts const core = createCoreScope(); diff --git a/packages/agent-core-v2/AGENTS.md b/packages/agent-core-v2/AGENTS.md index f09300956..b2e73cee0 100644 --- a/packages/agent-core-v2/AGENTS.md +++ b/packages/agent-core-v2/AGENTS.md @@ -4,7 +4,7 @@ ## Examples -`examples/` holds runnable **domain-slice scenarios**: each `examples/.example.ts` is a vitest test that exercises one subset of domains end-to-end, so a single file teaches a single capability. Each example builds its **own** container (the `createServices` flat harness for Core-scope slices, or `bootstrap` + child scopes for tree-spanning slices), runs its slice's services for real, and stubs the collaborators outside the slice — so examples never need the full engine, and different examples stub different subsets. Tree-spanning examples redirect `KIMI_CODE_HOME` to a single `.vitest-results/kimi-code-{timestamp}/` per run (set once in `examples/_globalSetup.ts` and shared across every file in the invocation) and seed a file-backed `IAtomicDocumentStorage`, so persisted state is written to disk for inspection. +`examples/` holds runnable **domain-slice scenarios**: each `examples/.example.ts` is a vitest test that exercises one subset of domains end-to-end, so a single file teaches a single capability. Each example builds its **own** container (the `createServices` flat harness for App-scope slices, or `bootstrap` + child scopes for tree-spanning slices), runs its slice's services for real, and stubs the collaborators outside the slice — so examples never need the full engine, and different examples stub different subsets. Tree-spanning examples redirect `KIMI_CODE_HOME` to a single `.vitest-results/kimi-code-{timestamp}/` per run (set once in `examples/_globalSetup.ts` and shared across every file in the invocation) and seed a file-backed `IAtomicDocumentStorage`, so persisted state is written to disk for inspection. Run one from the repo root with `pnpm dev:core-example ` (a filename filter; omit `` to run them all). Examples use their own vitest project (`agent-core-v2-examples`, via `vitest.examples.config.ts`), so they are separate from the real `test/` suite and their console output is shown per scenario. Add a new example by adding an `examples/.example.ts` that imports only its slice's domains. @@ -55,7 +55,7 @@ Per-domain references live in `docs/`. - [`docs/di.md`](docs/di.md) — Read **before adding any business capability**: a scenario-driven walkthrough of the DI × Scope black box, from "add a global service" through dependency injection, scope selection, disposal, delayed/eager instantiation, `invokeFunction`, `createInstance`, child scopes, and cycles — introducing each concept only as the scenario needs it. - [`docs/service-design.md`](docs/service-design.md) — Read **before designing a new Service**: first-principles rules for choosing a scope, splitting a domain Multi-Scope, picking a calling style (direct call vs event vs hook), and directing dependencies — the design companion to `docs/di.md`. -- [`docs/flag.md`](docs/flag.md) — Read **before gating behavior behind a feature flag**: declaring a flag in its owning domain and registering it at import time via `registerFlagDefinition`, checking `IFlagService.enabled(id)`, wiring the `[experimental]` config section, or deciding whether a flag is Core-scope vs. per-session. +- [`docs/flag.md`](docs/flag.md) — Read **before gating behavior behind a feature flag**: declaring a flag in its owning domain and registering it at import time via `registerFlagDefinition`, checking `IFlagService.enabled(id)`, wiring the `[experimental]` config section, or deciding whether a flag is App-scope vs. per-session. - [`docs/errors.md`](docs/errors.md) — Read **before raising errors from a domain**: defining a co-located `XxxError`, registering a code in `ErrorCodes`/`ERROR_INFO`, translating external errors (provider/HTTP, fs, MCP) at the boundary, or (de)serializing errors across RPC/SDK with `toErrorPayload`/`fromErrorPayload`. - [`docs/di-testing.md`](docs/di-testing.md) — Read **before writing or touching any DI/Scope test**: picking the right harness (`InstantiationService` vs `TestInstantiationService` vs `createScopedTestHost`), declaring deps with `@IService`, stubbing collaborators, and teardown via `DisposableStore`. - [`docs/di-scope-domains.puml`](docs/di-scope-domains.puml) — DI Scope × Domain dependency map (node color = `LifecycleScope`; solid edges = constructor DI injection, dashed edges = `wireRecord` / event-driven). **When adding a Service or changing the dependency relationships between Services, update this puml and regenerate `docs/di-scope-domains.svg`**. diff --git a/packages/agent-core-v2/docs/Permission.md b/packages/agent-core-v2/docs/Permission.md index 8424b1df1..6cd420d6a 100644 --- a/packages/agent-core-v2/docs/Permission.md +++ b/packages/agent-core-v2/docs/Permission.md @@ -172,7 +172,7 @@ interface PermissionPolicyEntry { factory: (accessor: ServicesAccessor) => PermissionPolicy; } -// Core scope —— 收集所有 domain 的注册 +// App scope —— 收集所有 domain 的注册 interface IPermissionPolicyRegistry { register(entry: PermissionPolicyEntry): IDisposable; list(): readonly PermissionPolicyEntry[]; @@ -192,7 +192,7 @@ this.policies = registry.list() 要点: - `modes`/`agentTypes` 是**声明**,把现在 `YoloModeApprove` 里的 `if (mode !== 'yolo') return` 提到元数据。 -- `factory` 而非 `instance`:节点可能依赖 agent-scoped 服务(mode、rules),需在 Agent scope 实例化——对称 `IToolDefinitionRegistry`(Core) 存 factory、`IToolService`(Agent) 实例化工具。 +- `factory` 而非 `instance`:节点可能依赖 agent-scoped 服务(mode、rules),需在 Agent scope 实例化——对称 `IToolDefinitionRegistry`(App) 存 factory、`IToolService`(Agent) 实例化工具。 - **不同 (agent, mode) 产出形状不同的链**:yolo 下 ask/fallback 阶段被物理过滤掉。 ### 5.3 两条贡献路径 @@ -212,11 +212,11 @@ this.policies = registry.list() // src/plan/planService.ts constructor(@IPermissionPolicyRegistry registry: IPermissionPolicyRegistry) { registry.register({ name: 'plan-mode-guard-deny', phase: 'guard', - factory: a => new PlanModeGuardDenyPolicy(a.get(IPlanService)) }); + factory: a => new PlanModeGuardDenyPolicy(a.get(IAgentPlanService)) }); registry.register({ name: 'plan-mode-tool-approve', phase: 'mode', - factory: a => new PlanModeToolApprovePolicy(a.get(IPlanService)) }); + factory: a => new PlanModeToolApprovePolicy(a.get(IAgentPlanService)) }); registry.register({ name: 'exit-plan-mode-review-ask', phase: 'user-ask', - factory: a => new ExitPlanModeReviewAskPolicy(a.get(IPlanService), a.get(IPermissionModeService)) }); + factory: a => new ExitPlanModeReviewAskPolicy(a.get(IAgentPlanService), a.get(IAgentPermissionModeService)) }); } ``` diff --git a/packages/agent-core-v2/docs/di-scope-domains.puml b/packages/agent-core-v2/docs/di-scope-domains.puml index 9773e07c9..d125081ae 100644 --- a/packages/agent-core-v2/docs/di-scope-domains.puml +++ b/packages/agent-core-v2/docs/di-scope-domains.puml @@ -6,7 +6,7 @@ skinparam ranksep 55 legend right Scope = node color - Core (process-wide) + App (process-wide) Session (per session) Agent (per agent) == Edges == @@ -18,27 +18,27 @@ legend right `_base` / seed / options deps are omitted. endlegend -package "Core scope (process-wide)" #EAF3FB { - rectangle "bootstrap\nCore\n IBootstrapService" as bootstrap #D6EAF8 - rectangle "log\nCore\n ILogService\n ILogWriterService" as log #D6EAF8 - rectangle "telemetry\nCore\n ITelemetryService" as telemetry #D6EAF8 - rectangle "event\nCore\n IEventService" as event #D6EAF8 - rectangle "storage\nCore\n IStorageService\n IAppendLogStore\n IAtomicDocumentStore\n IAtomicTomlDocumentStore" as storage #D6EAF8 - rectangle "filestore\nCore\n IFileStore" as filestore #D6EAF8 - rectangle "gateway\nCore\n IRestGateway\n IWSGateway\n IWSBroadcastService" as gateway #D6EAF8 - rectangle "session-lifecycle\nCore\n ISessionLifecycleService" as session_lifecycle #D6EAF8 - rectangle "session-index\nCore\n ISessionIndex" as sessionIndex #D6EAF8 - rectangle "hostFs\nCore\n IHostFileSystem" as hostFs #D6EAF8 - rectangle "workspaceRegistry\nCore\n IWorkspaceRegistry" as workspaceRegistry #D6EAF8 - rectangle "hostFolderBrowser\nCore\n IHostFolderBrowser" as hostFolderBrowser #D6EAF8 - rectangle "kaos\nCore\n IKaosFactory" as kaos_core #D6EAF8 - rectangle "auth\nCore\n IOAuthService\n IAuthSummaryService" as auth #D6EAF8 - rectangle "provider\nCore\n IProviderService" as provider #D6EAF8 - rectangle "flag\nCore\n IFlagService\n IFlagRegistry" as flag #D6EAF8 - rectangle "config\nCore\n IConfigRegistry\n IConfigService" as config #D6EAF8 - rectangle "chatProvider\nCore\n IChatProviderFactory" as chatProvider #D6EAF8 - rectangle "model\nCore\n IModelService" as model #D6EAF8 - rectangle "modelCatalog\nCore\n IModelCatalogService" as modelCatalog #D6EAF8 +package "App scope (process-wide)" #EAF3FB { + rectangle "bootstrap\nApp\n IBootstrapService" as bootstrap #D6EAF8 + rectangle "log\nApp\n ILogService\n ILogWriterService" as log #D6EAF8 + rectangle "telemetry\nApp\n ITelemetryService" as telemetry #D6EAF8 + rectangle "event\nApp\n IEventService" as event #D6EAF8 + rectangle "storage\nApp\n IStorageService\n IAppendLogStore\n IAtomicDocumentStore\n IAtomicTomlDocumentStore" as storage #D6EAF8 + rectangle "filestore\nApp\n IFileStore" as filestore #D6EAF8 + rectangle "gateway\nApp\n IRestGateway\n IWSGateway\n IWSBroadcastService" as gateway #D6EAF8 + rectangle "session-lifecycle\nApp\n ISessionLifecycleService" as session_lifecycle #D6EAF8 + rectangle "session-index\nApp\n ISessionIndex" as sessionIndex #D6EAF8 + rectangle "hostFs\nApp\n IHostFileSystem" as hostFs #D6EAF8 + rectangle "workspaceRegistry\nApp\n IWorkspaceRegistry" as workspaceRegistry #D6EAF8 + rectangle "hostFolderBrowser\nApp\n IHostFolderBrowser" as hostFolderBrowser #D6EAF8 + rectangle "kaos\nApp\n IKaosFactory" as kaos_core #D6EAF8 + rectangle "auth\nApp\n IOAuthService\n IAuthSummaryService" as auth #D6EAF8 + rectangle "provider\nApp\n IProviderService" as provider #D6EAF8 + rectangle "flag\nApp\n IFlagService\n IFlagRegistry" as flag #D6EAF8 + rectangle "config\nApp\n IConfigRegistry\n IConfigService" as config #D6EAF8 + rectangle "chatProvider\nApp\n IChatProviderFactory" as chatProvider #D6EAF8 + rectangle "model\nApp\n IModelService" as model #D6EAF8 + rectangle "modelCatalog\nApp\n IModelCatalogService" as modelCatalog #D6EAF8 } package "Session scope (per session)" #EAFAF1 { @@ -61,45 +61,45 @@ package "Session scope (per session)" #EAFAF1 { } package "Agent scope (per agent)" #FDF5E6 { - rectangle "wireRecord\nAgent\n IWireRecord (event hub)" as wireRecord #FDEBD0 - rectangle "eventSink\nAgent\n IEventSink" as eventSink #FDEBD0 - rectangle "blobStore\nAgent\n IBlobStoreService" as blobStore #FDEBD0 - rectangle "contextMemory\nAgent\n IContextMemory" as contextMemory #FDEBD0 - rectangle "contextProjector\nAgent\n IContextProjector" as contextProjector #FDEBD0 - rectangle "contextInjector\nAgent\n IContextInjector" as contextInjector #FDEBD0 - rectangle "contextSize\nAgent\n IContextSizeService" as contextSize #FDEBD0 - rectangle "systemReminder\nAgent\n ISystemReminderService" as systemReminder #FDEBD0 - rectangle "replayBuilder\nAgent\n IReplayBuilderService" as replayBuilder #FDEBD0 - rectangle "profile\nAgent\n IProfileService" as profile #FDEBD0 - rectangle "prompt\nAgent\n IPromptService" as prompt #FDEBD0 - rectangle "turn\nAgent\n ITurnService" as turn #FDEBD0 - rectangle "loop\nAgent\n ILoopService" as loop #FDEBD0 - rectangle "llmRequester\nAgent\n ILLMRequester" as llmRequester #FDEBD0 - rectangle "llmRequestLog\nAgent\n ILLMRequestLogService" as llmRequestLog #FDEBD0 - rectangle "toolRegistry\nAgent\n IToolRegistry" as toolRegistry #FDEBD0 - rectangle "toolExecutor\nAgent\n IToolExecutor" as toolExecutor #FDEBD0 - rectangle "toolStore\nAgent\n IToolStoreService" as toolStore #FDEBD0 - rectangle "toolDedup\nAgent\n IToolDedupe" as toolDedup #FDEBD0 - rectangle "permissionGate\nAgent\n IPermissionGate" as permissionGate #FDEBD0 - rectangle "permissionMode\nAgent\n IPermissionModeService" as permissionMode #FDEBD0 - rectangle "permissionPolicy\nAgent\n IPermissionPolicyService" as permissionPolicy #FDEBD0 - rectangle "permissionRules\nAgent\n IPermissionRulesService" as permissionRules #FDEBD0 - rectangle "plan\nAgent\n IPlanService" as plan #FDEBD0 - rectangle "goal\nAgent\n IGoalService" as goal #FDEBD0 + rectangle "wireRecord\nAgent\n IAgentWireRecordService (event hub)" as wireRecord #FDEBD0 + rectangle "eventSink\nAgent\n IAgentEventSinkService" as eventSink #FDEBD0 + rectangle "blobStore\nAgent\n IAgentBlobStoreService" as blobStore #FDEBD0 + rectangle "contextMemory\nAgent\n IAgentContextMemoryService" as contextMemory #FDEBD0 + rectangle "contextProjector\nAgent\n IAgentContextProjectorService" as contextProjector #FDEBD0 + rectangle "contextInjector\nAgent\n IAgentContextInjectorService" as contextInjector #FDEBD0 + rectangle "contextSize\nAgent\n IAgentContextSizeService" as contextSize #FDEBD0 + rectangle "systemReminder\nAgent\n IAgentSystemReminderService" as systemReminder #FDEBD0 + rectangle "replayBuilder\nAgent\n IAgentReplayBuilderService" as replayBuilder #FDEBD0 + rectangle "profile\nAgent\n IAgentProfileService" as profile #FDEBD0 + rectangle "prompt\nAgent\n IAgentPromptService" as prompt #FDEBD0 + rectangle "turn\nAgent\n IAgentTurnService" as turn #FDEBD0 + rectangle "loop\nAgent\n IAgentLoopService" as loop #FDEBD0 + rectangle "llmRequester\nAgent\n IAgentLLMRequesterService" as llmRequester #FDEBD0 + rectangle "llmRequestLog\nAgent\n IAgentLLMRequestLogService" as llmRequestLog #FDEBD0 + rectangle "toolRegistry\nAgent\n IAgentToolRegistryService" as toolRegistry #FDEBD0 + rectangle "toolExecutor\nAgent\n IAgentToolExecutorService" as toolExecutor #FDEBD0 + rectangle "toolStore\nAgent\n IAgentToolStoreService" as toolStore #FDEBD0 + rectangle "toolDedup\nAgent\n IAgentToolDedupeService" as toolDedup #FDEBD0 + rectangle "permissionGate\nAgent\n IAgentPermissionGate" as permissionGate #FDEBD0 + rectangle "permissionMode\nAgent\n IAgentPermissionModeService" as permissionMode #FDEBD0 + rectangle "permissionPolicy\nAgent\n IAgentPermissionPolicyService" as permissionPolicy #FDEBD0 + rectangle "permissionRules\nAgent\n IAgentPermissionRulesService" as permissionRules #FDEBD0 + rectangle "plan\nAgent\n IAgentPlanService" as plan #FDEBD0 + rectangle "goal\nAgent\n IAgentGoalService" as goal #FDEBD0 rectangle "skill\nAgent\n IAgentSkillService" as skill #FDEBD0 - rectangle "userTool\nAgent\n IUserToolService" as userTool #FDEBD0 - rectangle "background\nAgent\n IBackgroundService" as background #FDEBD0 - rectangle "cron\nAgent\n ICronService" as cron #FDEBD0 - rectangle "swarm\nAgent\n ISwarmService" as swarm #FDEBD0 - rectangle "mcp\nAgent\n IMcpService" as mcp #FDEBD0 - rectangle "fullCompaction\nAgent\n IFullCompaction" as fullCompaction #FDEBD0 - rectangle "microCompaction\nAgent\n IMicroCompactionService" as microCompaction #FDEBD0 - rectangle "externalHooks\nAgent\n IExternalHooksService" as externalHooks #FDEBD0 - rectangle "todoList\nAgent\n ITodoListService" as todoList #FDEBD0 - rectangle "usage\nAgent\n IUsageService" as usage #FDEBD0 + rectangle "userTool\nAgent\n IAgentUserToolService" as userTool #FDEBD0 + rectangle "background\nAgent\n IAgentBackgroundService" as background #FDEBD0 + rectangle "cron\nAgent\n IAgentCronService" as cron #FDEBD0 + rectangle "swarm\nAgent\n IAgentSwarmService" as swarm #FDEBD0 + rectangle "mcp\nAgent\n IAgentMcpService" as mcp #FDEBD0 + rectangle "fullCompaction\nAgent\n IAgentFullCompactionService" as fullCompaction #FDEBD0 + rectangle "microCompaction\nAgent\n IAgentMicroCompactionService" as microCompaction #FDEBD0 + rectangle "externalHooks\nAgent\n IAgentExternalHooksService" as externalHooks #FDEBD0 + rectangle "todoList\nAgent\n IAgentTodoListService" as todoList #FDEBD0 + rectangle "usage\nAgent\n IAgentUsageService" as usage #FDEBD0 rectangle "rpc\nAgent\n IAgentRPCService" as rpc #FDEBD0 - rectangle "fileTools\nAgent\n IFileToolsService" as fileTools #FDEBD0 - rectangle "shellTools\nAgent\n IShellToolsService" as shellTools #FDEBD0 + rectangle "fileTools\nAgent\n IAgentFileToolsService" as fileTools #FDEBD0 + rectangle "shellTools\nAgent\n IAgentShellToolsService" as shellTools #FDEBD0 } ' ---- DI injection (solid) ---- diff --git a/packages/agent-core-v2/docs/di-scope-domains.svg b/packages/agent-core-v2/docs/di-scope-domains.svg index cf7ce5c49..35d6e9c84 100644 --- a/packages/agent-core-v2/docs/di-scope-domains.svg +++ b/packages/agent-core-v2/docs/di-scope-domains.svg @@ -1 +1 @@ -Core scope (process-wide)Session scope (per session)Agent scope (per agent)bootstrapCoreIBootstrapServicelogCoreILogServiceILogWriterServicetelemetryCoreITelemetryServiceeventCoreIEventServicestorageCoreIStorageServiceIAppendLogStoreIAtomicDocumentStoreIAtomicTomlDocumentStorefilestoreCoreIFileStoregatewayCoreIRestGatewayIWSGatewayIWSBroadcastServicesession-lifecycleCoreISessionLifecycleServicesession-indexCoreISessionIndexhostFsCoreIHostFileSystemworkspaceRegistryCoreIWorkspaceRegistryhostFolderBrowserCoreIHostFolderBrowserkaosCoreIKaosFactoryauthCoreIOAuthServiceIAuthSummaryServiceproviderCoreIProviderServiceflagCoreIFlagServiceIFlagRegistryconfigCoreIConfigRegistryIConfigServicechatProviderCoreIChatProviderFactorymodelCoreIModelServicemodelCatalogCoreIModelCatalogServicesessionSessionISessionServicesession-contextSessionISessionContext (seed)session-metadataSessionISessionMetadatasession-activitySessionISessionActivityagent-lifecycleSessionIAgentLifecycleServiceinteractionSessionIInteractionServiceworkspaceContextSessionIWorkspaceContextsessionLogSessionISessionLogServiceILogWriterServicekaosSessionIKaos (seed)agentFsSessionIAgentFileSystemIFsServiceapprovalSessionIApprovalServicequestionSessionIQuestionServicesubagentHostSessionISubagentHostprocessSessionIProcessRunnerIProcessterminalSessionITerminalServiceITerminalBackendmodelProviderSessionIModelProvider (seed)wireRecordAgentIWireRecord (event hub)eventSinkAgentIEventSinkblobStoreAgentIBlobStoreServicecontextMemoryAgentIContextMemorycontextProjectorAgentIContextProjectorcontextInjectorAgentIContextInjectorcontextSizeAgentIContextSizeServicesystemReminderAgentISystemReminderServicereplayBuilderAgentIReplayBuilderServiceprofileAgentIProfileServicepromptAgentIPromptServiceturnAgentITurnServiceloopAgentILoopServicellmRequesterAgentILLMRequesterllmRequestLogAgentILLMRequestLogServicetoolRegistryAgentIToolRegistrytoolExecutorAgentIToolExecutortoolStoreAgentIToolStoreServicetoolDedupAgentIToolDedupepermissionAgentIPermissionGatepermissionModeAgentIPermissionModeServicepermissionPolicyAgentIPermissionPolicyServicepermissionRulesAgentIPermissionRulesServiceplanAgentIPlanServicegoalAgentIGoalServiceskillAgentIAgentSkillServiceuserToolAgentIUserToolServicebackgroundAgentIBackgroundServicecronAgentICronServiceswarmAgentISwarmServicemcpAgentIMcpServicefullCompactionAgentIFullCompactionmicroCompactionAgentIMicroCompactionServiceexternalHooksAgentIExternalHooksServicetodoListAgentITodoListServiceusageAgentIUsageServicerpcAgentIAgentRPCServicefileToolsAgentIFileToolsServiceshellToolsAgentIShellToolsServiceonDidChangecontext.splicehooks.onSplicedcontext_size.measuredconfig.update / tools.set_active_toolshooks.onSplicedhooks.onResumeEndedtools.update_storepermission.set_modepermission.rules.add / record_approval_resultplan_mode.enter/cancel/exitgoal.create/update/clearskill.activatetools.register_/unregister_user_toolbackground.task.started/terminatedhooks.onSplicedcron.add / delete / cursorswarm_mode.enter/exitfull_compaction.begin/cancel/completehooks.onContextOverflowmicro_compaction.apply / full_compaction.completeusage.recordsubscribehooks.onEndedScope = node color      Core (process-wide)      Session (per session)      Agent (per agent)Edgessolid: DI injection (ctor @IX)dashed: event-driven (subscribe/emit)direction: consumer ---> providerNotesGenerated from `node scripts/dep-graph.mjs` output;`_base` / seed / options deps are omitted. \ No newline at end of file +App scope (process-wide)Session scope (per session)Agent scope (per agent)bootstrapAppIBootstrapServicelogAppILogServiceILogWriterServicetelemetryAppITelemetryServiceeventAppIEventServicestorageAppIStorageServiceIAppendLogStoreIAtomicDocumentStoreIAtomicTomlDocumentStorefilestoreAppIFileStoregatewayAppIRestGatewayIWSGatewayIWSBroadcastServicesession-lifecycleAppISessionLifecycleServicesession-indexAppISessionIndexhostFsAppIHostFileSystemworkspaceRegistryAppIWorkspaceRegistryhostFolderBrowserAppIHostFolderBrowserkaosAppIKaosFactoryauthAppIOAuthServiceIAuthSummaryServiceproviderAppIProviderServiceflagAppIFlagServiceIFlagRegistryconfigAppIConfigRegistryIConfigServicechatProviderAppIChatProviderFactorymodelAppIModelServicemodelCatalogAppIModelCatalogServicesessionSessionISessionServicesession-contextSessionISessionContext (seed)session-metadataSessionISessionMetadatasession-activitySessionISessionActivityagent-lifecycleSessionIAgentLifecycleServiceinteractionSessionIInteractionServiceworkspaceContextSessionIWorkspaceContextsessionLogSessionISessionLogServiceILogWriterServicekaosSessionIKaos (seed)agentFsSessionIAgentFileSystemIFsServiceapprovalSessionIApprovalServicequestionSessionIQuestionServicesubagentHostSessionISubagentHostprocessSessionIProcessRunnerIProcessterminalSessionITerminalServiceITerminalBackendmodelProviderSessionIModelProvider (seed)wireRecordAgentIWireRecord (event hub)eventSinkAgentIEventSinkblobStoreAgentIBlobStoreServicecontextMemoryAgentIContextMemorycontextProjectorAgentIContextProjectorcontextInjectorAgentIContextInjectorcontextSizeAgentIContextSizeServicesystemReminderAgentISystemReminderServicereplayBuilderAgentIReplayBuilderServiceprofileAgentIProfileServicepromptAgentIPromptServiceturnAgentITurnServiceloopAgentILoopServicellmRequesterAgentILLMRequesterllmRequestLogAgentILLMRequestLogServicetoolRegistryAgentIToolRegistrytoolExecutorAgentIToolExecutortoolStoreAgentIToolStoreServicetoolDedupAgentIToolDedupepermissionAgentIPermissionGatepermissionModeAgentIPermissionModeServicepermissionPolicyAgentIPermissionPolicyServicepermissionRulesAgentIPermissionRulesServiceplanAgentIPlanServicegoalAgentIGoalServiceskillAgentIAgentSkillServiceuserToolAgentIUserToolServicebackgroundAgentIBackgroundServicecronAgentICronServiceswarmAgentISwarmServicemcpAgentIMcpServicefullCompactionAgentIFullCompactionmicroCompactionAgentIMicroCompactionServiceexternalHooksAgentIExternalHooksServicetodoListAgentITodoListServiceusageAgentIUsageServicerpcAgentIAgentRPCServicefileToolsAgentIFileToolsServiceshellToolsAgentIShellToolsServiceonDidChangecontext.splicehooks.onSplicedcontext_size.measuredconfig.update / tools.set_active_toolshooks.onSplicedhooks.onResumeEndedtools.update_storepermission.set_modepermission.rules.add / record_approval_resultplan_mode.enter/cancel/exitgoal.create/update/clearskill.activatetools.register_/unregister_user_toolbackground.task.started/terminatedhooks.onSplicedcron.add / delete / cursorswarm_mode.enter/exitfull_compaction.begin/cancel/completehooks.onContextOverflowmicro_compaction.apply / full_compaction.completeusage.recordsubscribehooks.onEndedScope = node color      App (process-wide)      Session (per session)      Agent (per agent)Edgessolid: DI injection (ctor @IX)dashed: event-driven (subscribe/emit)direction: consumer ---> providerNotesGenerated from `node scripts/dep-graph.mjs` output;`_base` / seed / options deps are omitted. \ No newline at end of file diff --git a/packages/agent-core-v2/docs/di.md b/packages/agent-core-v2/docs/di.md index d6912f0cc..abe33a749 100644 --- a/packages/agent-core-v2/docs/di.md +++ b/packages/agent-core-v2/docs/di.md @@ -64,7 +64,7 @@ export class Greeter implements IGreeter { ```ts // greet/greetService.ts(文件顶层,import 时执行) registerScopedService( - LifecycleScope.Core, // 活多久:进程级 + LifecycleScope.App, // 活多久:进程级 IGreeter, // 身份 Greeter, // 实现 InstantiationType.Eager, // 创建时机:立刻 @@ -143,7 +143,7 @@ const session = accessor.get(ISessionService); // 类型是 ISessionService ```ts export enum LifecycleScope { - Core = 0, // 进程级,全局一份 + App = 0, // 进程级,全局一份 Session = 1, // 一次会话 Agent = 2, // 一个 agent } @@ -155,14 +155,14 @@ export enum LifecycleScope { registerScopedService(LifecycleScope.Session, ISessionService, SessionService, InstantiationType.Delayed, 'session'); ``` -「单例」的粒度是**每个 scope 一份**:Core 的 `ILogService` 全局只有一份;每个 Session scope 各有自己的 `ISessionService`。 +「单例」的粒度是**每个 scope 一份**:App 的 `ILogService` 全局只有一份;每个 Session scope 各有自己的 `ISessionService`。 ### 3.2 子 scope 看得见父 scope,反之不行 Scope 是一棵树,`kind` 必须沿父子方向**严格递增**: ``` -Core (0) +App (0) └── Session (1) └── Agent (2) ``` @@ -171,8 +171,8 @@ Core (0) > **短寿命的服务可以注入长寿命的服务,反过来不行。** -- ✅ Agent 服务注入 Session / Core 服务(往上找,找得到)。 -- ❌ Core 服务注入 Session 服务(Core 创建时 Session 还不存在,且父不会往下找)。 +- ✅ Agent 服务注入 Session / App 服务(往上找,找得到)。 +- ❌ App 服务注入 Session 服务(App 创建时 Session 还不存在,且父不会往下找)。 这条规则由树的结构强制保证,不靠纪律维持。 @@ -212,10 +212,10 @@ export class WSBroadcastService extends Disposable implements IWSBroadcastServic ```ts // Eager:scope 创建时立刻 new -registerScopedService(LifecycleScope.Core, ILogService, LogService, InstantiationType.Eager, 'log'); +registerScopedService(LifecycleScope.App, ILogService, LogService, InstantiationType.Eager, 'log'); // Delayed:第一次被 get 时才 new -registerScopedService(LifecycleScope.Core, IScopeRegistry, ScopeRegistry, InstantiationType.Delayed, 'gateway'); +registerScopedService(LifecycleScope.App, IScopeRegistry, ScopeRegistry, InstantiationType.Delayed, 'gateway'); ``` Delayed 服务返回的是一个 **Proxy**:在首次访问任意属性时才真正构造。即便还没构造好,别人提前订阅它的 `onDid…` / `onWill…` 事件也不会丢——容器会先记下监听器,实例真正出来后再回放订阅。 @@ -300,7 +300,7 @@ export class ScopeRegistry implements IScopeRegistry { 关键点: - `getScopedServiceDescriptors(scope)` 能拿回注册在某一层的所有描述符,装进一个 `ServiceCollection`。 -- `instantiation.createChild(collection)` 造一个子容器,它的父指针指向当前容器——于是子容器能向上解析到 Core 的服务(场景 3 的可见性规则)。 +- `instantiation.createChild(collection)` 造一个子容器,它的父指针指向当前容器——于是子容器能向上解析到 App 的服务(场景 3 的可见性规则)。 - 给外部暴露时,用 `invokeFunction` 把子容器包成 `ServicesAccessor`(场景 6)。 > 更高层通常直接用 [`Scope.createChild(kind, id)`](../src/_base/di/scope.ts)(它帮你做了「筛描述符 + 建子容器」);只有需要手动控制 `ServiceCollection` 时才像上面这样写。 @@ -317,7 +317,7 @@ A 创建中要 B,B 创建中又要 A——容器会抛 `CyclicDependencyError` ### 9.2 为什么不允许 -- scope 分层让正常依赖天然是 DAG(Agent → Session → Core 向上找),一个环几乎总是设计味道。 +- scope 分层让正常依赖天然是 DAG(Agent → Session → App 向上找),一个环几乎总是设计味道。 - 靠「让环刚好能跑」会把构造顺序变成隐式约定,难调试、难排错。 所以 v2 的立场是:**依赖图必须是无环的。** diff --git a/packages/agent-core-v2/docs/flag.md b/packages/agent-core-v2/docs/flag.md index 1523a4c4f..24341e6c3 100644 --- a/packages/agent-core-v2/docs/flag.md +++ b/packages/agent-core-v2/docs/flag.md @@ -1,22 +1,22 @@ # flag -> Experimental feature-flag gating for agent-core-v2 — a Core-scope `IFlagService` resolver plus a writable `IFlagRegistry` catalog that domains contribute their flags to, backed by the `[experimental]` config section. +> Experimental feature-flag gating for agent-core-v2 — a App-scope `IFlagService` resolver plus a writable `IFlagRegistry` catalog that domains contribute their flags to, backed by the `[experimental]` config section. Gates not-yet-public features behind `IFlagService.enabled(id)`, per the repository hard rule that unreleased behavior must be flag-gated. Ported from `packages/agent-core/src/flags/**`; v1 was a process-global `FlagResolver` singleton over a central `FLAG_DEFINITIONS` array, v2 is a scoped DI service whose flag definitions are registered **decentrally** by each owning domain — there is no central catalog to edit. ## Layout - `src/flag/flagRegistry.ts` — `IFlagRegistry` token + `FlagDefinitionInput` / `FlagId` / `FlagSurface` types + `registerFlagDefinition` / `getContributedFlags` (import-time contribution queue). -- `src/flag/flagRegistryService.ts` — `FlagRegistryService` impl; in-memory catalog seeded from import-time contributions; Core scope. +- `src/flag/flagRegistryService.ts` — `FlagRegistryService` impl; in-memory catalog seeded from import-time contributions; App scope. - `src/flag/flag.ts` — `IFlagService` token + resolver types (`ExperimentalFlagMap`, `ExperimentalFlagConfig`, `ExperimentalFlagSource`, `ExperimentalFeatureState`) + `ExperimentalConfigSchema` / `ExperimentalConfig` (zod). -- `src/flag/flagService.ts` — `FlagService` impl + `MASTER_ENV` (`KIMI_CODE_EXPERIMENTAL_FLAG`) + `EXPERIMENTAL_SECTION` (`experimental`); reads definitions from `IFlagRegistry`; self-registers at Core scope. +- `src/flag/flagService.ts` — `FlagService` impl + `MASTER_ENV` (`KIMI_CODE_EXPERIMENTAL_FLAG`) + `EXPERIMENTAL_SECTION` (`experimental`); reads definitions from `IFlagRegistry`; self-registers at App scope. - `src/flag/index.ts` — barrel; re-exported by `src/index.ts` at the L3 block. - `src//flag.ts` — each domain that owns a flag declares it here and calls `registerFlagDefinition` at the module top level (e.g. `src/microCompaction/flag.ts`). The directory already names the domain, so the file is just `flag.ts`. ## Public surface -- `IFlagService` (DI token, Core scope): `enabled(id)`, `explain(id)`, `snapshot()`, `enabledIds()`, `explainAll()`, `setConfigOverrides(overrides)`, `registry`. -- `IFlagRegistry` (DI token, Core scope): `register(definition)`, `get(id)`, `list()` — writable catalog. `register` is the **runtime** path (tests, dynamic registration); `IFlagService.registry` exposes the same instance for hosts/UI to enumerate flags without resolving them. +- `IFlagService` (DI token, App scope): `enabled(id)`, `explain(id)`, `snapshot()`, `enabledIds()`, `explainAll()`, `setConfigOverrides(overrides)`, `registry`. +- `IFlagRegistry` (DI token, App scope): `register(definition)`, `get(id)`, `list()` — writable catalog. `register` is the **runtime** path (tests, dynamic registration); `IFlagService.registry` exposes the same instance for hosts/UI to enumerate flags without resolving them. - `registerFlagDefinition(definition)` — the **import-time** path. Domains call this from their `flag.ts` top level; contributions are queued and drained by `FlagRegistryService` when it is instantiated. - `FlagService` / `FlagRegistryService`: exported for tests and hosts that construct them directly. @@ -85,7 +85,7 @@ export * from './flag'; ## Consume a flag -Inject `IFlagService` and gate on it. It is resolvable from any scope (Core ancestor): +Inject `IFlagService` and gate on it. It is resolvable from any scope (App ancestor): ```ts constructor(@IFlagService private readonly flags: IFlagService) {} @@ -99,7 +99,7 @@ Current consumer: `microCompaction` (Agent scope) gates `micro_compaction`. - Domain `flag` is registered at **L3** (`scripts/check-domain-layers.mjs` → `['flag', 3]`). It imports only `config` (L2) downward. - It cannot live in `_base` (L0): registering/reading the config section requires importing `config`, and L0 must not import L2. -- Scope: `IFlagRegistry` and `IFlagService` are both `Core`. Env + config are process-global inputs, so there is no per-session/agent state. Flag definitions are contributed at **import time** (top-level `registerFlagDefinition` calls), so they are queued before any scope is created and drained when `FlagRegistryService` is first instantiated — before `IFlagService` is first resolved. +- Scope: `IFlagRegistry` and `IFlagService` are both `App`. Env + config are process-global inputs, so there is no per-session/agent state. Flag definitions are contributed at **import time** (top-level `registerFlagDefinition` calls), so they are queued before any scope is created and drained when `FlagRegistryService` is first instantiated — before `IFlagService` is first resolved. - Tests build `FlagService` + `FlagRegistryService` directly with a real `ConfigRegistry`/`ConfigService` and an injected env map, then `register` the flags they exercise (`test/flag/flag.test.ts`). ## References diff --git a/packages/agent-core-v2/docs/service-design.md b/packages/agent-core-v2/docs/service-design.md index c181a8d4f..7e918c7a3 100644 --- a/packages/agent-core-v2/docs/service-design.md +++ b/packages/agent-core-v2/docs/service-design.md @@ -37,11 +37,11 @@ Every principle below derives from two root questions: **First principle: Scope = the identity + lifetime of the owned state.** -`Core` / `Session` / `Agent` are three tiers of identity + lifetime: +`App` / `Session` / `Agent` are three tiers of identity + lifetime: | Scope | State identity (keyed by) | Lifetime | |---|---|---| -| `Core` | none (single global instance) | the process | +| `App` | none (single global instance) | the process | | `Session` | `sessionId` | one session | | `Agent` | `agentId` | one agent | @@ -54,7 +54,7 @@ Every principle below derives from two root questions: **Q2. What is the identity of that state?** -- one global instance → **`Core`** +- one global instance → **`App`** - one per session → **`Session`** - one per agent → **`Agent`** - a mix (a global registry *and* per-instance state) → **do not put it in one Service; @@ -63,8 +63,8 @@ Every principle below derives from two root questions: **Q3 (stateless). What is the shortest-lived dependency it must inject?** A stateless Service is pulled *down* by its shortest-lived dependency: if it injects an -`Agent`-scoped Service, it cannot be `Core`. Among the scopes that still satisfy every -dependency, **default to the longest-lived one** (usually `Core`) to maximize reuse and +`Agent`-scoped Service, it cannot be `App`. Among the scopes that still satisfy every +dependency, **default to the longest-lived one** (usually `App`) to maximize reuse and singleton sharing. Push it down only when: 1. it must inject a shorter-lived Service (enforced by the container); or @@ -73,10 +73,10 @@ singleton sharing. Push it down only when: ### The core anti-pattern (a litmus test) -> **Do not store per-session state in a `Map` inside a `Core` Service.** +> **Do not store per-session state in a `Map` inside a `App` Service.** This is the tell-tale sign of "this should have been `Session`-scoped but was lazily parked -at `Core`". Consequences: +at `App`". Consequences: - nobody cleans the entry up when the session ends → **leak**; - every consumer threads `sessionId` around → **loss of type safety**; @@ -107,36 +107,36 @@ job well. | Tier | Role | Naming tends to | |---|---|---| -| `Core` | **global registry / catalog / factory** — knows "all of them" and how to create one | `XxxStore` / `XxxRegistry` / `XxxCatalog` | +| `App` | **global registry / catalog / factory** — knows "all of them" and how to create one | `XxxStore` / `XxxRegistry` / `XxxCatalog` | | `Session` / `Agent` | **one instance** — only the state of "this one" | `XxxService` / `ISessionXxx` / `IAgentXxx` | This pattern recurs throughout the codebase and confirms the rule: -- **`records`** — `ISessionIndex` (`Core`, read model of all persisted sessions) + - `ISessionMetadata` (`Session`, this session's metadata) + `IWireRecord` (`Agent`, this +- **`records`** — `ISessionIndex` (`App`, read model of all persisted sessions) + + `ISessionMetadata` (`Session`, this session's metadata) + `IAgentWireRecordService` (`Agent`, this agent's record stream). -- **`config`** — `IConfigRegistry` / `IConfigService` (`Core`, global config). -- **`chatProvider` / `model` / `modelRuntime`** — `IChatProviderFactory` (`Core`, - protocol adapters keyed by provider type), `IModelService` (`Core`, model-alias +- **`config`** — `IConfigRegistry` / `IConfigService` (`App`, global config). +- **`chatProvider` / `model` / `modelRuntime`** — `IChatProviderFactory` (`App`, + protocol adapters keyed by provider type), `IModelService` (`App`, model-alias configuration), and `IModelResolver` (`Session`, resolves the active model into a runtime provider config plus request authorization). Provider connection - configuration lives in the sibling `provider` domain (`IProviderService`, `Core`). - Generation itself is driven by `ILLMRequester` (`Agent`) in the `llmRequester` + configuration lives in the sibling `provider` domain (`IProviderService`, `App`). + Generation itself is driven by `IAgentLLMRequesterService` (`Agent`) in the `llmRequester` domain. -- **`tool`** — `IToolDefinitionRegistry` (`Core`, tool-definition registry) + `IToolService` +- **`tool`** — `IToolDefinitionRegistry` (`App`, tool-definition registry) + `IToolService` (`Agent`, this agent's execution). ### When to split and when not to - **Split** when the domain genuinely has both a global view and per-instance state. -- **Do not split** when the domain has state at only one lifetime (e.g. purely `Core` like +- **Do not split** when the domain has state at only one lifetime (e.g. purely `App` like `log` / `telemetry`; purely `Agent` like `prompt`). **Do not pre-split for symmetry.** ### Dependency direction after the split -The `Core` Service usually plays the **factory**: it knows how to create or locate the +The `App` Service usually plays the **factory**: it knows how to create or locate the per-instance one. Most consumers inject the **per-instance** Service, because it serves the -current session/agent directly without threading an id. Inject the `Core` factory only when +current session/agent directly without threading an id. Inject the `App` factory only when you genuinely need cross-instance management. --- @@ -277,8 +277,8 @@ The complete checklist for a new `IXxxService`: ## 7. Summary - **Scope**: the **identity** of the state fixes the scope; do not fake per-instance state - at `Core` with a `Map`. -- **Multi-Scope**: a domain with state at several lifetimes → split into "a `Core` registry + at `App` with a `Map`. +- **Multi-Scope**: a domain with state at several lifetimes → split into "a `App` registry + per-instance Services". - **Calling style**: need a result / I orchestrate → direct call; stating a fact / react if you care → event; ordered participation / may veto → hook. diff --git a/packages/agent-core-v2/examples/config.example.ts b/packages/agent-core-v2/examples/config.example.ts index 2883d025e..e94645e52 100644 --- a/packages/agent-core-v2/examples/config.example.ts +++ b/packages/agent-core-v2/examples/config.example.ts @@ -7,24 +7,24 @@ * resolves **every** current section owner so its `registerSection` runs, then * reads the single `IConfigRegistry` / `IConfigService` they all populated: * - * Core-scope owners (resolved from the production `bootstrap` Core scope): + * App-scope owners (resolved from the production `bootstrap` App scope): * - `IModelService` → `models` (+ the `KIMI_MODEL_*` overlay) * - `IProviderService` → `providers` * - `IFlagService` → `experimental` * * Agent-scope owners (constructed here against the same registry): - * - `IBackgroundService` → `background` - * - `ICronService` → `cron` - * - `IPermissionRulesService`→ `permission` - * - `IProfileService` → `thinking`, `defaultThinking` - * - `ILoopService` → `loopControl` - * - `IExternalHooksService` → `hooks` + * - `IAgentBackgroundService` → `background` + * - `IAgentCronService` → `cron` + * - `IAgentPermissionRulesService`→ `permission` + * - `IAgentProfileService` → `thinking`, `defaultThinking` + * - `IAgentLoopService` → `loopControl` + * - `IAgentExternalHooksService` → `hooks` * * The Agent owners are constructed through `createServices` with their * non-config collaborators stubbed, mirroring how the slice tests isolate a * domain (see `feature-flags.example.ts`). Only the `registerSection` call and * the config reads are real — which is exactly what this example is about. The - * Core owners are *not* re-constructed: they are resolved from the real Core + * App owners are *not* re-constructed: they are resolved from the real App * scope, so no section is registered twice. * * Two scenarios are shown: @@ -48,39 +48,39 @@ import { afterEach, beforeEach, describe, expect, test } from 'vitest'; import { DisposableStore, toDisposable } from '#/_base/di/lifecycle'; import type { Scope } from '#/_base/di/scope'; import { createServices, type TestInstantiationService } from '#/_base/di/test'; -import { BackgroundService, IBackgroundService } from '#/background'; +import { AgentBackgroundService, IAgentBackgroundService } from '#/background'; import { bootstrap } from '#/bootstrap/bootstrap'; import { type ConfigInspectValue, IConfigRegistry, IConfigService } from '#/config/config'; import '#/config/index'; -import { IContextMemory } from '#/contextMemory'; -import { IContextProjector } from '#/contextProjector'; -import { IContextSizeService } from '#/contextSize'; -import { CronService } from '#/cron'; -import { IEventSink } from '#/eventSink'; -import { ExternalHooksService, IExternalHooksService } from '#/externalHooks'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentContextProjectorService } from '#/contextProjector'; +import { IAgentContextSizeService } from '#/contextSize'; +import { AgentCronService } from '#/cron'; +import { IAgentEventSinkService } from '#/eventSink'; +import { AgentExternalHooksService, IAgentExternalHooksService } from '#/externalHooks'; import { IFlagService } from '#/flag'; -import { ILLMRequester } from '#/llmRequester'; +import { IAgentLLMRequesterService } from '#/llmRequester'; import { logSeed, resolveLoggingConfig } from '#/log/logConfig'; -import { LoopService, ILoopService } from '#/loop'; +import { AgentLoopService, IAgentLoopService } from '#/loop'; import { IChatProviderFactory } from '#/chatProvider'; import { IModelService } from '#/model'; import '#/model/index'; -import { IModelResolver } from '#/modelRuntime'; -import { IPermissionRulesService, PermissionRulesService } from '#/permissionRules'; -import { IProfileService, ProfileService } from '#/profile'; -import { IPromptService } from '#/prompt'; +import { ISessionModelResolver } from '#/modelRuntime'; +import { IAgentPermissionRulesService, AgentPermissionRulesService } from '#/permissionRules'; +import { IAgentProfileService, AgentProfileService } from '#/profile'; +import { IAgentPromptService } from '#/prompt'; import { IProviderService } from '#/provider'; import '#/provider/index'; import '#/flag/index'; -import { IReplayBuilderService } from '#/replayBuilder'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; import { ISessionContext } from '#/session-context'; import { IAtomicDocumentStore, IStorageService } from '#/storage'; import '#/storage/index'; import { ITelemetryService } from '#/telemetry'; -import { IToolExecutor } from '#/toolExecutor'; -import { IToolRegistry } from '#/toolRegistry'; -import { ITurnService } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentToolExecutorService } from '#/toolExecutor'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { IAgentTurnService } from '#/turn'; +import { IAgentWireRecordService } from '#/wireRecord'; /** * One schema-valid sample value per **persistable** section, written through @@ -131,7 +131,7 @@ function hookSlot() { describe('config slice (every section owner against one shared registry)', () => { let homeDir: string; - let core: Scope; + let app: Scope; let configPath: string; let disposables: DisposableStore; let ix: TestInstantiationService; @@ -145,12 +145,12 @@ describe('config slice (every section owner against one shared registry)', () => mkdirSync(homeDir, { recursive: true }); configPath = join(homeDir, 'config.toml'); - // Real, file-backed config. Constructing the Core scope eager-loads + // Real, file-backed config. Constructing the App scope eager-loads // `IModelService`, which registers the `models` section + overlay. - core = bootstrap({ homeDir }, logSeed(resolveLoggingConfig({ homeDir, env: process.env }))).core; + app = bootstrap({ homeDir }, logSeed(resolveLoggingConfig({ homeDir, env: process.env }))).app; - const registry = core.accessor.get(IConfigRegistry); - const config = core.accessor.get(IConfigService); + const registry = app.accessor.get(IConfigRegistry); + const config = app.accessor.get(IConfigService); // Construct the Agent-scope owners against the SAME registry/service. Their // non-config collaborators are stubbed: this example isolates the config @@ -163,79 +163,79 @@ describe('config slice (every section owner against one shared registry)', () => reg.defineInstance(IConfigService, config); // Collaborators touched during owner construction, with real shape. - reg.definePartialInstance(IWireRecord, { + reg.definePartialInstance(IAgentWireRecordService, { register: () => toDisposable(() => {}), append: () => {}, hooks: { onRestoredRecord: hookSlot(), onResumeEnded: hookSlot() }, }); - reg.definePartialInstance(IContextMemory, { hooks: { onSpliced: hookSlot() } }); - reg.definePartialInstance(IToolExecutor, { + reg.definePartialInstance(IAgentContextMemoryService, { hooks: { onSpliced: hookSlot() } }); + reg.definePartialInstance(IAgentToolExecutorService, { // `OrderedHookSlot` is a class with private members, so the stub is // shaped as a `HookSlot` and cast to the declared slot type. hooks: { onWillExecuteTool: hookSlot(), onDidExecuteTool: hookSlot(), - } as unknown as IToolExecutor['hooks'], + } as unknown as IAgentToolExecutorService['hooks'], }); - reg.definePartialInstance(IModelResolver, { defaultModel: 'mock-model' }); + reg.definePartialInstance(ISessionModelResolver, { defaultModel: 'mock-model' }); reg.definePartialInstance(ISessionContext, { metaScope: 'sessions/demo/demo/session-meta', sessionDir: homeDir, }); - reg.definePartialInstance(ITurnService, { getActiveTurn: () => undefined }); + reg.definePartialInstance(IAgentTurnService, { getActiveTurn: () => undefined }); // Collaborators declared but not touched during construction — empty // stubs keep the container strict-clean (no "unknown service" warnings). - reg.definePartialInstance(IEventSink, {}); + reg.definePartialInstance(IAgentEventSinkService, {}); reg.definePartialInstance(ITelemetryService, { track: () => {} }); - reg.definePartialInstance(IPromptService, {}); + reg.definePartialInstance(IAgentPromptService, {}); reg.definePartialInstance(IAtomicDocumentStore, {}); reg.definePartialInstance(IStorageService, {}); - reg.definePartialInstance(IToolRegistry, {}); - reg.definePartialInstance(IReplayBuilderService, {}); + reg.definePartialInstance(IAgentToolRegistryService, {}); + reg.definePartialInstance(IAgentReplayBuilderService, {}); reg.definePartialInstance(IChatProviderFactory, {}); - reg.definePartialInstance(IContextProjector, {}); - reg.definePartialInstance(IContextSizeService, {}); - reg.definePartialInstance(ILLMRequester, {}); + reg.definePartialInstance(IAgentContextProjectorService, {}); + reg.definePartialInstance(IAgentContextSizeService, {}); + reg.definePartialInstance(IAgentLLMRequesterService, {}); - // Real Agent-scope section owners. `ICronService` is constructed via + // Real Agent-scope section owners. `IAgentCronService` is constructed via // `createInstance` below (not here) so we can pass `{ isSubagent: true }` // and keep its runtime scheduler/tool registration from starting. - reg.define(IExternalHooksService, ExternalHooksService); - reg.define(IPermissionRulesService, PermissionRulesService); - reg.define(IProfileService, ProfileService); - reg.define(IBackgroundService, BackgroundService); - reg.define(ILoopService, LoopService); + reg.define(IAgentExternalHooksService, AgentExternalHooksService); + reg.define(IAgentPermissionRulesService, AgentPermissionRulesService); + reg.define(IAgentProfileService, AgentProfileService); + reg.define(IAgentBackgroundService, AgentBackgroundService); + reg.define(IAgentLoopService, AgentLoopService); }, }); }); afterEach(() => { disposables.dispose(); - core.dispose(); + app.dispose(); }); test('every section owner registers its section into the shared registry', async () => { - const registry = core.accessor.get(IConfigRegistry); - const config = core.accessor.get(IConfigService); + const registry = app.accessor.get(IConfigRegistry); + const config = app.accessor.get(IConfigService); await config.ready; - // Resolve the Core owners and touch each one: delayed Core services return + // Resolve the App owners and touch each one: delayed App services return // a lazy proxy, so reading a method forces construction (and thus the // `registerSection` call). `IModelService` is eager but still needs a `get`. - core.accessor.get(IModelService).list(); - core.accessor.get(IProviderService).list(); - core.accessor.get(IFlagService).snapshot(); + app.accessor.get(IModelService).list(); + app.accessor.get(IProviderService).list(); + app.accessor.get(IFlagService).snapshot(); // Construct the Agent owners — each registers its section(s). - ix.get(IBackgroundService); - ix.get(IPermissionRulesService); - ix.get(IProfileService); - ix.get(IExternalHooksService); - ix.get(ILoopService); + ix.get(IAgentBackgroundService); + ix.get(IAgentPermissionRulesService); + ix.get(IAgentProfileService); + ix.get(IAgentExternalHooksService); + ix.get(IAgentLoopService); // `isSubagent: true` keeps the cron scheduler/tool registration from // starting — only the `cron` config-section registration is relevant here. - ix.createInstance(CronService, { isSubagent: true }); + ix.createInstance(AgentCronService, { isSubagent: true }); const registered = registry .listSections() @@ -253,19 +253,19 @@ describe('config slice (every section owner against one shared registry)', () => }); test('writes every persistable section through config and round-trips the file', async () => { - const config = core.accessor.get(IConfigService); + const config = app.accessor.get(IConfigService); await config.ready; // Resolve every owner so its section is registered before writing. - core.accessor.get(IModelService).list(); - core.accessor.get(IProviderService).list(); - core.accessor.get(IFlagService).snapshot(); - ix.get(IBackgroundService); - ix.get(IPermissionRulesService); - ix.get(IProfileService); - ix.get(IExternalHooksService); - ix.get(ILoopService); - ix.createInstance(CronService, { isSubagent: true }); + app.accessor.get(IModelService).list(); + app.accessor.get(IProviderService).list(); + app.accessor.get(IFlagService).snapshot(); + ix.get(IAgentBackgroundService); + ix.get(IAgentPermissionRulesService); + ix.get(IAgentProfileService); + ix.get(IAgentExternalHooksService); + ix.get(IAgentLoopService); + ix.createInstance(AgentCronService, { isSubagent: true }); // Write each persistable section through IConfigService — every owner's // value is validated, env-stripped, and persisted to config.toml. diff --git a/packages/agent-core-v2/examples/interaction.example.ts b/packages/agent-core-v2/examples/interaction.example.ts index 0b2385ec6..d7941f10f 100644 --- a/packages/agent-core-v2/examples/interaction.example.ts +++ b/packages/agent-core-v2/examples/interaction.example.ts @@ -8,9 +8,9 @@ * scoped registry is cleared and re-populated explicitly in `beforeEach` rather * than relying on import-order side effects. * - * `IInteractionService` is the only Service that owns state — a pending set + * `ISessionInteractionService` is the only Service that owns state — a pending set * plus a recently-resolved ledger — and it is domain-agnostic. - * `IApprovalService` and `IQuestionService` are zero-state typed facades over + * `ISessionApprovalService` and `ISessionQuestionService` are zero-state typed facades over * it: they tag each request with `kind: 'approval'` / `kind: 'question'`, * rename the resolve verb (`decide` / `answer` → `respond`), and cast the * stored payload back to the typed request on `listPending`. @@ -41,9 +41,9 @@ import { type Scope, } from '#/_base/di/scope'; import { createScopedTestHost, type ScopedTestHost } from '#/_base/di/test'; -import { type ApprovalRequest, ApprovalService, IApprovalService } from '#/approval'; -import { IInteractionService, InteractionService } from '#/interaction'; -import { type QuestionRequest, IQuestionService, QuestionService } from '#/question'; +import { type ApprovalRequest, SessionApprovalService, ISessionApprovalService } from '#/approval'; +import { ISessionInteractionService, SessionInteractionService } from '#/interaction'; +import { type QuestionRequest, ISessionQuestionService, SessionQuestionService } from '#/question'; const display: ToolInputDisplay = { kind: 'command', command: 'rm -rf /tmp/demo' }; @@ -70,9 +70,9 @@ describe('interaction kernel + approval/question facades (Session scope)', () => beforeEach(() => { _clearScopedRegistryForTests(); - registerScopedService(LifecycleScope.Session, IInteractionService, InteractionService, InstantiationType.Delayed, 'interaction'); - registerScopedService(LifecycleScope.Session, IApprovalService, ApprovalService, InstantiationType.Delayed, 'approval'); - registerScopedService(LifecycleScope.Session, IQuestionService, QuestionService, InstantiationType.Delayed, 'question'); + registerScopedService(LifecycleScope.Session, ISessionInteractionService, SessionInteractionService, InstantiationType.Delayed, 'interaction'); + registerScopedService(LifecycleScope.Session, ISessionApprovalService, SessionApprovalService, InstantiationType.Delayed, 'approval'); + registerScopedService(LifecycleScope.Session, ISessionQuestionService, SessionQuestionService, InstantiationType.Delayed, 'question'); disposables = new DisposableStore(); host = createScopedTestHost(); @@ -84,7 +84,7 @@ describe('interaction kernel + approval/question facades (Session scope)', () => }); test('blocking: approval.request parks until decide resolves the Promise', async () => { - const approvals = session.accessor.get(IApprovalService); + const approvals = session.accessor.get(ISessionApprovalService); // The caller (e.g. a tool) awaits the decision. Nothing resolves yet. const decision = approvals.request(approval('bash-1')); @@ -97,8 +97,8 @@ describe('interaction kernel + approval/question facades (Session scope)', () => }); test('non-blocking: question.enqueue returns immediately; the answer streams over onDidResolve', () => { - const interaction = session.accessor.get(IInteractionService); - const questions = session.accessor.get(IQuestionService); + const interaction = session.accessor.get(ISessionInteractionService); + const questions = session.accessor.get(ISessionQuestionService); // Edge callers observe outcomes through the stream instead of awaiting. const resolved: { id: string; response: unknown }[] = []; @@ -116,9 +116,9 @@ describe('interaction kernel + approval/question facades (Session scope)', () => }); test('one kernel backs both facades; onDidChange announces every mutation', () => { - const interaction = session.accessor.get(IInteractionService); - const approvals = session.accessor.get(IApprovalService); - const questions = session.accessor.get(IQuestionService); + const interaction = session.accessor.get(ISessionInteractionService); + const approvals = session.accessor.get(ISessionApprovalService); + const questions = session.accessor.get(ISessionQuestionService); let changes = 0; disposables.add(interaction.onDidChange(() => changes++)); @@ -139,8 +139,8 @@ describe('interaction kernel + approval/question facades (Session scope)', () => test('Session scope isolates brokers: a request parked in A is invisible to B', async () => { const sessionB = host.child(LifecycleScope.Session, 'session-b'); - const approvalsA = session.accessor.get(IApprovalService); - const approvalsB = sessionB.accessor.get(IApprovalService); + const approvalsA = session.accessor.get(ISessionApprovalService); + const approvalsB = sessionB.accessor.get(ISessionApprovalService); console.log('1) distinct broker instances per session:', approvalsA !== approvalsB); const decisionA = approvalsA.request(approval('bash-1')); diff --git a/packages/agent-core-v2/examples/oauth.example.ts b/packages/agent-core-v2/examples/oauth.example.ts index d6ecf5ff7..c4700dd6b 100644 --- a/packages/agent-core-v2/examples/oauth.example.ts +++ b/packages/agent-core-v2/examples/oauth.example.ts @@ -23,7 +23,7 @@ * *triggers* the refresh explicitly (it is not auto-chained inside login), * then observes the new aliases arrive through config. * - * Everything runs against the real Core-scope Services **and** the real OAuth + * Everything runs against the real App-scope Services **and** the real OAuth * clients — `KimiOAuthToolkit` (device-code protocol + token persistence) and * `fetchManagedKimiCodeModels` (the `/models` request) are not stubbed. The * only thing faked is the wire itself: `globalThis.fetch` is replaced with a @@ -138,7 +138,7 @@ async function waitUntil(predicate: () => boolean, timeoutMs = 2000): Promise { let homeDir: string; let caseDir: string; - let core: Scope | undefined; + let app: Scope | undefined; beforeEach(() => { const resolved = process.env['KIMI_CODE_HOME']; @@ -155,23 +155,23 @@ describe('oauth → modelCatalog slice (request-layer fetch mock, real clients)' }); afterEach(() => { - core?.dispose(); - core = undefined; + app?.dispose(); + app = undefined; vi.unstubAllGlobals(); }); - function buildCore(): Scope { + function buildApp(): Scope { return bootstrap( { homeDir: caseDir }, logSeed(resolveLoggingConfig({ homeDir: caseDir, env: process.env })), - ).core; + ).app; } test('device-code login provisions the provider credential through config.onDidChange', async () => { - core = buildCore(); - const config = core.accessor.get(IConfigService); - const oauth = core.accessor.get(IOAuthService); - const providers = core.accessor.get(IProviderService); + app = buildApp(); + const config = app.accessor.get(IConfigService); + const oauth = app.accessor.get(IOAuthService); + const providers = app.accessor.get(IProviderService); await config.ready; providers.list(); @@ -199,11 +199,11 @@ describe('oauth → modelCatalog slice (request-layer fetch mock, real clients)' }); test('refreshOAuthProviderModels fetches /models internally and lands aliases through config.onDidChange', async () => { - core = buildCore(); - const config = core.accessor.get(IConfigService); - const oauth = core.accessor.get(IOAuthService); - const providers = core.accessor.get(IProviderService); - const models = core.accessor.get(IModelService); + app = buildApp(); + const config = app.accessor.get(IConfigService); + const oauth = app.accessor.get(IOAuthService); + const providers = app.accessor.get(IProviderService); + const models = app.accessor.get(IModelService); await config.ready; providers.list(); diff --git a/packages/agent-core-v2/examples/observability.example.ts b/packages/agent-core-v2/examples/observability.example.ts index c29d4bc0a..408f9efc6 100644 --- a/packages/agent-core-v2/examples/observability.example.ts +++ b/packages/agent-core-v2/examples/observability.example.ts @@ -3,7 +3,7 @@ * * Builds a flat container that runs both services for real (neither has * cross-domain collaborators, so nothing is stubbed). `ILogService` writes - * through the Core console writer; `ITelemetryService` fans events out to a + * through the App console writer; `ITelemetryService` fans events out to a * console appender while merging bound context. The two compose: a child * logger and a context-scoped telemetry both carry their bound fields into * the output. diff --git a/packages/agent-core-v2/examples/persistence.example.ts b/packages/agent-core-v2/examples/persistence.example.ts index 4083d3cf9..1fa7402fd 100644 --- a/packages/agent-core-v2/examples/persistence.example.ts +++ b/packages/agent-core-v2/examples/persistence.example.ts @@ -55,7 +55,7 @@ const WIRE_KEY = 'example'; describe('persistence module (Store → Storage → backend, real ~/.kimi-code files)', () => { let homeDir: string; - let core: Scope; + let app: Scope; beforeEach(() => { const resolved = process.env['KIMI_CODE_HOME']; @@ -64,17 +64,17 @@ describe('persistence module (Store → Storage → backend, real ~/.kimi-code f } homeDir = resolved; mkdirSync(homeDir, { recursive: true }); - core = bootstrap({ homeDir }).core; + app = bootstrap({ homeDir }).app; }); afterEach(() => { - core.dispose(); + app.dispose(); }); test('typed Store → raw Storage bytes → real file path', async () => { // 1) Atomic document, TOML codec → config.toml - const tomlDocs = core.accessor.get(IAtomicTomlDocumentStore); - const configBytes = core.accessor.get(IStorageService); + const tomlDocs = app.accessor.get(IAtomicTomlDocumentStore); + const configBytes = app.accessor.get(IStorageService); const configValue = { theme: 'dark', telemetry: { enabled: true } }; await tomlDocs.set('', 'config.toml', configValue); console.log('1) config.toml (atomic doc, TOML):'); @@ -86,8 +86,8 @@ describe('persistence module (Store → Storage → backend, real ~/.kimi-code f console.log(' path :', join(homeDir, 'config.toml')); // 2) Atomic document, JSON codec → sessions/.../session-meta/state.json - const docs = core.accessor.get(IAtomicDocumentStore); - const docBytes = core.accessor.get(IAtomicDocumentStorage); + const docs = app.accessor.get(IAtomicDocumentStore); + const docBytes = app.accessor.get(IAtomicDocumentStorage); const metaScope = 'sessions/example/s-example/session-meta'; const meta = { id: 's-example', @@ -103,8 +103,8 @@ describe('persistence module (Store → Storage → backend, real ~/.kimi-code f console.log(' path :', join(homeDir, metaScope, 'state.json')); // 3) Append log, JSONL framing → wire/.jsonl - const logs = core.accessor.get(IAppendLogStore); - const logBytes = core.accessor.get(IAppendLogStorage); + const logs = app.accessor.get(IAppendLogStore); + const logBytes = app.accessor.get(IAppendLogStorage); const key = WIRE_KEY; logs.append('wire', key, { type: 'metadata', protocol_version: '1.5' }); logs.append('wire', key, { type: 'swarm_mode.enter', trigger: 'manual' }); diff --git a/packages/agent-core-v2/examples/scope.example.ts b/packages/agent-core-v2/examples/scope.example.ts index 823e45b98..cfe2a8cd7 100644 --- a/packages/agent-core-v2/examples/scope.example.ts +++ b/packages/agent-core-v2/examples/scope.example.ts @@ -2,8 +2,8 @@ * Scenario: the **DI Scope** foundation — how resolution follows the tree. * * Not a business slice but the model every other slice rests on. Two rules, - * shown with real services: a Core-scoped service (`ILogService`) resolves to - * the same instance whether you ask the Core scope or a child Session scope + * shown with real services: a App-scoped service (`ILogService`) resolves to + * the same instance whether you ask the App scope or a child Session scope * (it is found by walking up), while a Session-scoped service * (`ISessionMetadata`) is one distinct instance per session, so two sessions * hold independent state. Loads only `log` and `session-metadata`. @@ -31,9 +31,9 @@ function diskStorageSeed(homeDir: string): ScopeSeed { return [[IAtomicDocumentStorage as ServiceIdentifier, new FileStorageService(homeDir)]]; } -describe('di scope foundation (Core singletons vs. per-Session instances)', () => { +describe('di scope foundation (App singletons vs. per-Session instances)', () => { let homeDir: string; - let core: Scope; + let app: Scope; beforeEach(() => { const resolved = process.env['KIMI_CODE_HOME']; @@ -42,18 +42,18 @@ describe('di scope foundation (Core singletons vs. per-Session instances)', () = } homeDir = resolved; mkdirSync(homeDir, { recursive: true }); - core = bootstrap({}, [ + app = bootstrap({}, [ ...logSeed(resolveLoggingConfig({ homeDir, env: process.env })), ...diskStorageSeed(homeDir), - ]).core; + ]).app; }); afterEach(() => { - core.dispose(); + app.dispose(); }); function createSession(sessionId: string): Scope { const sessionDir = join(homeDir, 'sessions', 'example', sessionId); - return core.createChild(LifecycleScope.Session, sessionId, { + return app.createChild(LifecycleScope.Session, sessionId, { extra: [ ...sessionContextSeed({ _serviceBrand: undefined, @@ -67,14 +67,14 @@ describe('di scope foundation (Core singletons vs. per-Session instances)', () = }); } - test('Core services are shared; Session services are per-session', async () => { + test('App services are shared; Session services are per-session', async () => { console.log('KIMI_CODE_HOME =', homeDir); const sessionA = createSession('scope-a'); const sessionB = createSession('scope-b'); - const logFromCore = core.accessor.get(ILogService); + const logFromCore = app.accessor.get(ILogService); const logFromSession = sessionA.accessor.get(ILogService); - console.log('Core ILogService shared across scopes:', logFromCore === logFromSession); + console.log('App ILogService shared across scopes:', logFromCore === logFromSession); const metaA = sessionA.accessor.get(ISessionMetadata); const metaB = sessionB.accessor.get(ISessionMetadata); diff --git a/packages/agent-core-v2/examples/session-index.example.ts b/packages/agent-core-v2/examples/session-index.example.ts index ac230aa7f..6d93c2739 100644 --- a/packages/agent-core-v2/examples/session-index.example.ts +++ b/packages/agent-core-v2/examples/session-index.example.ts @@ -45,7 +45,7 @@ interface SeedMeta { describe('session-index module (business Store over storage Stores)', () => { let homeDir: string; - let core: Scope; + let app: Scope; let sessionsScope: string; let docs: IAtomicDocumentStore; let index: ISessionIndex; @@ -58,11 +58,11 @@ describe('session-index module (business Store over storage Stores)', () => { homeDir = resolved; mkdirSync(homeDir, { recursive: true }); - core = bootstrap({ homeDir }).core; - const layout = core.accessor.get(IBootstrapService); + app = bootstrap({ homeDir }).app; + const layout = app.accessor.get(IBootstrapService); sessionsScope = relative(layout.homeDir, layout.sessionsDir); - docs = core.accessor.get(IAtomicDocumentStore); - index = core.accessor.get(ISessionIndex); + docs = app.accessor.get(IAtomicDocumentStore); + index = app.accessor.get(ISessionIndex); await seed('ws-a', 's1', { title: 'first session', @@ -91,7 +91,7 @@ describe('session-index module (business Store over storage Stores)', () => { }); afterEach(() => { - core.dispose(); + app.dispose(); }); async function seed(workspaceId: string, sessionId: string, meta: SeedMeta): Promise { diff --git a/packages/agent-core-v2/examples/session.example.ts b/packages/agent-core-v2/examples/session.example.ts index 59db7dc8c..6d290f1ed 100644 --- a/packages/agent-core-v2/examples/session.example.ts +++ b/packages/agent-core-v2/examples/session.example.ts @@ -2,10 +2,10 @@ * Scenario: the **session** slice — `session-lifecycle` + `session-metadata`. * * Shows the session as a durable, tracked entity and how the slice's domains - * compose: `ISessionLifecycleService` (Core) creates Session child scopes — + * compose: `ISessionLifecycleService` (App) creates Session child scopes — * seeding each with its identity and storage and materializing its metadata — * and tracks the live set, while each session's `ISessionMetadata` (Session) - * reads and updates the persisted document through the Core `storage` service. + * reads and updates the persisted document through the App `storage` service. * The host is the production `bootstrap` composition root (real file-backed * storage rooted under `.vitest-results/kimi-code-{timestamp}/`); only the * slice's barrels are imported, so nothing outside it is loaded. @@ -33,7 +33,7 @@ function diskStorageSeed(homeDir: string): ScopeSeed { describe('session slice (session-lifecycle + session-metadata)', () => { let homeDir: string; - let core: Scope; + let app: Scope; beforeEach(() => { const resolved = process.env['KIMI_CODE_HOME']; @@ -42,18 +42,18 @@ describe('session slice (session-lifecycle + session-metadata)', () => { } homeDir = resolved; mkdirSync(homeDir, { recursive: true }); - core = bootstrap({}, [ + app = bootstrap({}, [ ...logSeed(resolveLoggingConfig({ homeDir, env: process.env })), ...diskStorageSeed(homeDir), - ]).core; + ]).app; }); afterEach(() => { - core.dispose(); + app.dispose(); }); test('creates, tracks, persists, and closes sessions', async () => { console.log('KIMI_CODE_HOME =', homeDir); - const lifecycle = core.accessor.get(ISessionLifecycleService); + const lifecycle = app.accessor.get(ISessionLifecycleService); const first = await lifecycle.create({ sessionId: 's1', workDir: homeDir }); await lifecycle.create({ sessionId: 's2', workDir: homeDir }); diff --git a/packages/agent-core-v2/examples/wire-record.example.ts b/packages/agent-core-v2/examples/wire-record.example.ts index 87cb23c7e..4d61a7d27 100644 --- a/packages/agent-core-v2/examples/wire-record.example.ts +++ b/packages/agent-core-v2/examples/wire-record.example.ts @@ -2,7 +2,7 @@ * Scenario: the **wire-record** module — a durable-record + replay chain built * on the append-log Store. * - * Shows how a real Domain Service (`IWireRecord` / `WireRecordService`) + * Shows how a real Domain Service (`IAgentWireRecordService` / `AgentWireRecordService`) * aggregates the `IAppendLogStore` access pattern into a complete engine call * chain: `append` stamps and persists records (writing a `metadata` header * first), and `restore` reads the log back and replays each record through the @@ -11,8 +11,8 @@ * `swarm` domain's `WireRecordMap` declaration merge. * * Persistence is gated on the `homedir` option: the scoped-registered - * `IWireRecord` passes no options and is therefore in-memory only, so this - * scenario constructs the real `WireRecordService` with `createInstance(..., + * `IAgentWireRecordService` passes no options and is therefore in-memory only, so this + * scenario constructs the real `AgentWireRecordService` with `createInstance(..., * { homedir })` — the same way production wires a persisting wire record — * resolving its `IAppendLogStore` dependency from the container. The resumers * are small side callbacks (not Services). All resolved Services come from @@ -26,7 +26,7 @@ import { afterEach, beforeEach, describe, test } from 'vitest'; import { DisposableStore } from '#/_base/di/lifecycle'; import { createServices, type TestInstantiationService } from '#/_base/di/test'; import { FileStorageService, IAppendLogStorage, IAppendLogStore, AppendLogStore } from '#/storage'; -import { WireRecordService, type IWireRecord } from '#/wireRecord'; +import { AgentWireRecordService, type IAgentWireRecordService } from '#/wireRecord'; import '#/swarm/swarm'; const textDecoder = new TextDecoder(); @@ -61,7 +61,7 @@ describe('wire-record module (durable record + replay over IAppendLogStore)', () const logBytes = ix.get(IAppendLogStorage); // --- writer side: append records, which persist to wire/.jsonl --- - const writer: IWireRecord = ix.createInstance(WireRecordService, { homedir: homeDir }); + const writer: IAgentWireRecordService = ix.createInstance(AgentWireRecordService, { homedir: homeDir }); writer.append({ type: 'swarm_mode.enter', trigger: 'manual' }); writer.append({ type: 'swarm_mode.exit' }); @@ -77,7 +77,7 @@ describe('wire-record module (durable record + replay over IAppendLogStore)', () // --- reader side: a fresh instance on the same log replays the records --- const replayed: string[] = []; - const reader: IWireRecord = ix.createInstance(WireRecordService, { homedir: homeDir }); + const reader: IAgentWireRecordService = ix.createInstance(AgentWireRecordService, { homedir: homeDir }); reader.register('swarm_mode.enter', (rec) => { replayed.push(`enter(trigger=${rec.trigger})`); }); diff --git a/packages/agent-core-v2/src/_base/di/scope.ts b/packages/agent-core-v2/src/_base/di/scope.ts index 2de9f88c9..bbffe90d3 100644 --- a/packages/agent-core-v2/src/_base/di/scope.ts +++ b/packages/agent-core-v2/src/_base/di/scope.ts @@ -10,7 +10,7 @@ import { DisposableStore, type IDisposable } from './lifecycle'; import { ServiceCollection } from './serviceCollection'; export enum LifecycleScope { - Core = 0, + App = 0, Session = 1, Agent = 2, } @@ -119,11 +119,11 @@ export class Scope implements IDisposable { }; } - static createCore(options: ScopeOptions = {}): Scope { - const kind = LifecycleScope.Core; + static createApp(options: ScopeOptions = {}): Scope { + const kind = LifecycleScope.App; const collection = buildCollection(kind, options.extra); const instantiation = new InstantiationService(collection, true); - return new Scope(options.id ?? 'core', kind, instantiation); + return new Scope(options.id ?? 'app', kind, instantiation); } private _assertNotDisposed(): void { @@ -174,6 +174,6 @@ export class Scope implements IDisposable { } } -export function createCoreScope(options: ScopeOptions = {}): Scope { - return Scope.createCore(options); +export function createAppScope(options: ScopeOptions = {}): Scope { + return Scope.createApp(options); } diff --git a/packages/agent-core-v2/src/_base/di/test.ts b/packages/agent-core-v2/src/_base/di/test.ts index 86cadc305..f67d07e89 100644 --- a/packages/agent-core-v2/src/_base/di/test.ts +++ b/packages/agent-core-v2/src/_base/di/test.ts @@ -13,27 +13,27 @@ export type { } from './testInstantiationService'; import { type ServiceIdentifier } from './instantiation'; -import { createCoreScope, LifecycleScope, Scope, type ScopeSeed } from './scope'; +import { createAppScope, LifecycleScope, Scope, type ScopeSeed } from './scope'; export interface ScopedTestHost { - readonly core: Scope; + readonly app: Scope; child(kind: LifecycleScope, id: string, stubs?: ScopeSeed): Scope; childOf(parent: Scope, kind: LifecycleScope, id: string, stubs?: ScopeSeed): Scope; dispose(): void; } -export function createScopedTestHost(coreStubs: ScopeSeed = []): ScopedTestHost { - const core = createCoreScope({ extra: coreStubs }); +export function createScopedTestHost(appStubs: ScopeSeed = []): ScopedTestHost { + const app = createAppScope({ extra: appStubs }); return { - core, + app, child(kind, id, stubs = []) { - return core.createChild(kind, id, { extra: stubs }); + return app.createChild(kind, id, { extra: stubs }); }, childOf(parent, kind, id, stubs = []) { return parent.createChild(kind, id, { extra: stubs }); }, dispose() { - core.dispose(); + app.dispose(); }, }; } diff --git a/packages/agent-core-v2/src/agent-lifecycle/agentLifecycleService.ts b/packages/agent-core-v2/src/agent-lifecycle/agentLifecycleService.ts index 64b59251b..60dcdb580 100644 --- a/packages/agent-core-v2/src/agent-lifecycle/agentLifecycleService.ts +++ b/packages/agent-core-v2/src/agent-lifecycle/agentLifecycleService.ts @@ -21,7 +21,7 @@ import { } from '#/_base/di/scope'; import { ISessionContext } from '#/session-context'; import { ISessionMetadata } from '#/session-metadata'; -import { IWireRecord, WireRecordService } from '#/wireRecord'; +import { IAgentWireRecordService, AgentWireRecordService } from '#/wireRecord'; import { type CreateAgentOptions, IAgentLifecycleService } from './agentLifecycle'; @@ -58,7 +58,7 @@ export class AgentLifecycleService extends Disposable implements IAgentLifecycle LifecycleScope.Agent, agentId, { - extra: [[IWireRecord, new SyncDescriptor(WireRecordService, [{ homedir: agentHomedir }])]], + extra: [[IAgentWireRecordService, new SyncDescriptor(AgentWireRecordService, [{ homedir: agentHomedir }])]], }, ); this.handles.set(agentId, handle); diff --git a/packages/agent-core-v2/src/agentFs/agentFs.ts b/packages/agent-core-v2/src/agentFs/agentFs.ts index ac376cbb6..8cc357323 100644 --- a/packages/agent-core-v2/src/agentFs/agentFs.ts +++ b/packages/agent-core-v2/src/agentFs/agentFs.ts @@ -1,9 +1,9 @@ /** * `agentFs` domain (L1) — the Agent's filesystem. * - * Defines the `IAgentFileSystem` that business code injects to read and write + * Defines the `ISessionAgentFileSystem` that business code injects to read and write * files inside the Agent's execution environment. Session-scoped and backed by - * the session `IKaos`; business code depends on `IAgentFileSystem` only. + * the session `IKaos`; business code depends on `ISessionAgentFileSystem` only. */ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; @@ -18,7 +18,7 @@ export interface AgentFileStat { readonly ino?: number; } -export interface IAgentFileSystem { +export interface ISessionAgentFileSystem { readonly _serviceBrand: undefined; readonly cwd: string; @@ -38,8 +38,8 @@ export interface IAgentFileSystem { path: string, options?: { readonly parents?: boolean; readonly existOk?: boolean }, ): Promise; - withCwd(cwd: string): IAgentFileSystem; + withCwd(cwd: string): ISessionAgentFileSystem; } -export const IAgentFileSystem: ServiceIdentifier = - createDecorator('agentFileSystem'); +export const ISessionAgentFileSystem: ServiceIdentifier = + createDecorator('sessionAgentFileSystem'); diff --git a/packages/agent-core-v2/src/agentFs/agentFsService.ts b/packages/agent-core-v2/src/agentFs/agentFsService.ts index 46441eb9d..cbf2c4167 100644 --- a/packages/agent-core-v2/src/agentFs/agentFsService.ts +++ b/packages/agent-core-v2/src/agentFs/agentFsService.ts @@ -1,5 +1,5 @@ /** - * `agentFs` domain (L1) — `IAgentFileSystem` implementation. + * `agentFs` domain (L1) — `ISessionAgentFileSystem` implementation. * * Focused file-IO surface over the session execution environment (`IKaos.backend`). * Relative-path resolution (in the target path style) and symlink-safe glob are @@ -12,7 +12,7 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { IKaos, type StatResult } from '#/kaos'; -import { type AgentFileStat, IAgentFileSystem } from './agentFs'; +import { type AgentFileStat, ISessionAgentFileSystem } from './agentFs'; const S_IFMT = 0o170000; const S_IFREG = 0o100000; @@ -28,7 +28,7 @@ function basename(p: string): string { return parts[parts.length - 1] ?? p; } -export class AgentFileSystem implements IAgentFileSystem { +export class SessionAgentFileSystem implements ISessionAgentFileSystem { declare readonly _serviceBrand: undefined; constructor(@IKaos private readonly kaos: IKaos) {} @@ -96,15 +96,15 @@ export class AgentFileSystem implements IAgentFileSystem { }); } - withCwd(cwd: string): IAgentFileSystem { - return new AgentFileSystem(this.kaos.withCwd(cwd)); + withCwd(cwd: string): ISessionAgentFileSystem { + return new SessionAgentFileSystem(this.kaos.withCwd(cwd)); } } registerScopedService( LifecycleScope.Session, - IAgentFileSystem, - AgentFileSystem, + ISessionAgentFileSystem, + SessionAgentFileSystem, InstantiationType.Delayed, 'agentFs', ); diff --git a/packages/agent-core-v2/src/agentFs/fs.ts b/packages/agent-core-v2/src/agentFs/fs.ts index 4914dff1f..c6a1ce281 100644 --- a/packages/agent-core-v2/src/agentFs/fs.ts +++ b/packages/agent-core-v2/src/agentFs/fs.ts @@ -1,10 +1,10 @@ /** * `agentFs` domain (L2) — wire-shaped filesystem operations. * - * Defines the `IFsService` that backs the fs REST surface: content search, + * Defines the `ISessionFsService` that backs the fs REST surface: content search, * content grep, and git status/diff. It is the higher-level counterpart to - * `IAgentFileSystem` (the thin IO primitive): it orchestrates the IO primitive - * plus `IProcessRunner` (for `rg` / `git` / `gh`) and returns protocol-shaped + * `ISessionAgentFileSystem` (the thin IO primitive): it orchestrates the IO primitive + * plus `ISessionProcessRunner` (for `rg` / `git` / `gh`) and returns protocol-shaped * responses. Session-scoped — the scope itself is the session, so no * `sessionId` is threaded through. */ @@ -50,7 +50,7 @@ export interface FsDownloadResolved { readonly modifiedAt: Date; } -export interface IFsService { +export interface ISessionFsService { readonly _serviceBrand: undefined; list(req: FsListRequest): Promise; @@ -67,5 +67,5 @@ export interface IFsService { resolveDownload(relPath: string): Promise; } -export const IFsService: ServiceIdentifier = - createDecorator('fsService'); +export const ISessionFsService: ServiceIdentifier = + createDecorator('sessionFsService'); diff --git a/packages/agent-core-v2/src/agentFs/fsProcess.ts b/packages/agent-core-v2/src/agentFs/fsProcess.ts index 05d098412..188e241b8 100644 --- a/packages/agent-core-v2/src/agentFs/fsProcess.ts +++ b/packages/agent-core-v2/src/agentFs/fsProcess.ts @@ -1,8 +1,8 @@ /** - * `agentFs` domain (L2) — `runCommand` helper over `IProcessRunner`. + * `agentFs` domain (L2) — `runCommand` helper over `ISessionProcessRunner`. * * Collects a child process's full stdout/stderr and exit code through the - * Agent's backend-pluggable `IProcessRunner`, with optional `AbortSignal` + * Agent's backend-pluggable `ISessionProcessRunner`, with optional `AbortSignal` * support (the caller decides timeout semantics — git has none, `gh pr view` * uses 5s, `rg` grep uses 30s). Kept separate from `fsService` so it can be * unit-tested with a fake runner. @@ -10,7 +10,7 @@ import { type Readable } from 'node:stream'; -import { type IProcess, type IProcessRunner } from '#/process'; +import { type IProcess, type ISessionProcessRunner } from '#/process'; export interface RunResult { readonly exitCode: number; @@ -26,7 +26,7 @@ export interface RunCommandOptions { } export async function runCommand( - runner: IProcessRunner, + runner: ISessionProcessRunner, args: readonly string[], options: RunCommandOptions = {}, ): Promise { diff --git a/packages/agent-core-v2/src/agentFs/fsService.ts b/packages/agent-core-v2/src/agentFs/fsService.ts index 93ca6b079..d70b584c9 100644 --- a/packages/agent-core-v2/src/agentFs/fsService.ts +++ b/packages/agent-core-v2/src/agentFs/fsService.ts @@ -1,12 +1,12 @@ /** - * `agentFs` domain (L2) — `IFsService` implementation. + * `agentFs` domain (L2) — `ISessionFsService` implementation. * * Backs the fs REST surface (search / grep / git status / git diff) by - * orchestrating `IAgentFileSystem` (file IO) and `IProcessRunner` (`rg` / + * orchestrating `ISessionAgentFileSystem` (file IO) and `ISessionProcessRunner` (`rg` / * `git` / `gh`). Bound at Session scope — the workspace root and execution * environment come from the scope, so no `sessionId` is threaded through. * - * Path confinement is lexical (`IWorkspaceContext.isWithin`); it does not + * Path confinement is lexical (`ISessionWorkspaceContext.isWithin`); it does not * follow symlinks, matching the rest of v2 (`_base/tools/policies/path-access.ts`). */ @@ -45,11 +45,11 @@ import ignore, { type Ignore } from 'ignore'; import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { ErrorCodes, KimiError } from '#/errors'; -import { IProcessRunner } from '#/process'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { ISessionProcessRunner } from '#/process'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; -import { type AgentFileStat, IAgentFileSystem } from './agentFs'; -import { type FsDownloadResolved, type FsPathResolved, IFsService } from './fs'; +import { type AgentFileStat, ISessionAgentFileSystem } from './agentFs'; +import { type FsDownloadResolved, type FsPathResolved, ISessionFsService } from './fs'; import { parseNumstat, parsePorcelain, parsePullRequest } from './fsGit'; import { runCommand } from './fsProcess'; import { @@ -80,7 +80,7 @@ const FS_BINARY_NONPRINTABLE_FRACTION = 0.3; const HIDDEN_NAME_RE = /^\./; const MACOS_NOISE = new Set(['.DS_Store', '.AppleDouble', '.LSOverride']); -export class FsService implements IFsService { +export class SessionFsService implements ISessionFsService { declare readonly _serviceBrand: undefined; private readonly gitignoreCache = new Map(); @@ -91,9 +91,9 @@ export class FsService implements IFsService { private rgAvailable: boolean | undefined = undefined; constructor( - @IWorkspaceContext private readonly workspace: IWorkspaceContext, - @IAgentFileSystem private readonly fs: IAgentFileSystem, - @IProcessRunner private readonly runner: IProcessRunner, + @ISessionWorkspaceContext private readonly workspace: ISessionWorkspaceContext, + @ISessionAgentFileSystem private readonly fs: ISessionAgentFileSystem, + @ISessionProcessRunner private readonly runner: ISessionProcessRunner, ) {} async list(req: FsListRequest): Promise { @@ -895,7 +895,7 @@ function parseRgJsonOutput( // --------------------------------------------------------------------------- // Helpers shared by the list/read/stat/mkdir methods. Ported from the v1 -// `FsService` so the `/api/v1` mirror stays byte-compatible. +// `SessionFsService` so the `/api/v1` mirror stays byte-compatible. // --------------------------------------------------------------------------- function isHidden(name: string): boolean { @@ -1074,8 +1074,8 @@ function guessLanguageId(relPath: string): string | undefined { registerScopedService( LifecycleScope.Session, - IFsService, - FsService, + ISessionFsService, + SessionFsService, InstantiationType.Delayed, 'agentFs', ); diff --git a/packages/agent-core-v2/src/agentFs/index.ts b/packages/agent-core-v2/src/agentFs/index.ts index 0e41b8b65..e27330036 100644 --- a/packages/agent-core-v2/src/agentFs/index.ts +++ b/packages/agent-core-v2/src/agentFs/index.ts @@ -2,7 +2,7 @@ * `agentFs` domain barrel — re-exports the agent-filesystem contract * (`agentFs`) and its scoped service (`agentFsService`), the wire-shaped fs * service (`fs`, `fsService`), and the fs error codes (`errors`). Importing - * this barrel registers the `IAgentFileSystem` and `IFsService` bindings into + * this barrel registers the `ISessionAgentFileSystem` and `ISessionFsService` bindings into * the scope registry. */ diff --git a/packages/agent-core-v2/src/approval/approval.ts b/packages/agent-core-v2/src/approval/approval.ts index 6c942e49b..d1377e586 100644 --- a/packages/agent-core-v2/src/approval/approval.ts +++ b/packages/agent-core-v2/src/approval/approval.ts @@ -2,7 +2,7 @@ * `approval` domain (L7) — session-scope approval broker. * * Defines the public contract of approval brokering: the `ApprovalRequest` / - * `ApprovalDecision` models and the `IApprovalService` used to request a + * `ApprovalDecision` models and the `ISessionApprovalService` used to request a * decision, resolve it, and list pending approvals. Session-scoped — one * broker per session. */ @@ -30,7 +30,7 @@ export interface ApprovalResponse { readonly selectedLabel?: string; } -export interface IApprovalService { +export interface ISessionApprovalService { readonly _serviceBrand: undefined; request(req: ApprovalRequest): Promise; /** @@ -43,5 +43,5 @@ export interface IApprovalService { listPending(): readonly ApprovalRequest[]; } -export const IApprovalService: ServiceIdentifier = - createDecorator('approvalService'); +export const ISessionApprovalService: ServiceIdentifier = + createDecorator('sessionApprovalService'); diff --git a/packages/agent-core-v2/src/approval/approvalService.ts b/packages/agent-core-v2/src/approval/approvalService.ts index d6d039a77..199b8a1da 100644 --- a/packages/agent-core-v2/src/approval/approvalService.ts +++ b/packages/agent-core-v2/src/approval/approvalService.ts @@ -1,5 +1,5 @@ /** - * `approval` domain (L7) — `IApprovalService` implementation. + * `approval` domain (L7) — `ISessionApprovalService` implementation. * * Typed facade over the `interaction` kernel for approval requests; owns no * pending state of its own (the kernel holds it). Bound at Session scope. @@ -7,18 +7,18 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IInteractionService } from '#/interaction'; +import { ISessionInteractionService } from '#/interaction'; import { type ApprovalRequest, type ApprovalResponse, - IApprovalService, + ISessionApprovalService, } from './approval'; -export class ApprovalService implements IApprovalService { +export class SessionApprovalService implements ISessionApprovalService { declare readonly _serviceBrand: undefined; - constructor(@IInteractionService private readonly interaction: IInteractionService) {} + constructor(@ISessionInteractionService private readonly interaction: ISessionInteractionService) {} request(req: ApprovalRequest): Promise { return this.interaction.request({ @@ -55,4 +55,4 @@ function requestId(req: ApprovalRequest): string { return req.id ?? req.toolCallId ?? `${req.toolName}:${String(Date.now())}`; } -registerScopedService(LifecycleScope.Session, IApprovalService, ApprovalService, InstantiationType.Delayed, 'approval'); +registerScopedService(LifecycleScope.Session, ISessionApprovalService, SessionApprovalService, InstantiationType.Delayed, 'approval'); diff --git a/packages/agent-core-v2/src/approval/index.ts b/packages/agent-core-v2/src/approval/index.ts index f85c1d5dc..2e8562eb9 100644 --- a/packages/agent-core-v2/src/approval/index.ts +++ b/packages/agent-core-v2/src/approval/index.ts @@ -1,7 +1,7 @@ /** * `approval` domain barrel — re-exports the approval contract (`approval`) and * its scoped service (`approvalService`). Importing this barrel registers the - * `IApprovalService` binding into the scope registry. + * `ISessionApprovalService` binding into the scope registry. */ export * from './approval'; diff --git a/packages/agent-core-v2/src/auth/auth.ts b/packages/agent-core-v2/src/auth/auth.ts index 1ca4a36ed..071c05268 100644 --- a/packages/agent-core-v2/src/auth/auth.ts +++ b/packages/agent-core-v2/src/auth/auth.ts @@ -1,5 +1,5 @@ /** - * `auth` domain (cross-cutting) — core-scope OAuth + auth summary contracts. + * `auth` domain (cross-cutting) — app-scope OAuth + auth summary contracts. * * Defines the public contracts of authentication: the `AuthStatus` model, the * `IOAuthService` used to drive device-code login / logout / flow inspection, @@ -7,7 +7,7 @@ * OAuth provider's server-side model configuration, the `IOAuthToolkit` * device-code client that `IOAuthService` delegates the OAuth protocol to, and * the `IAuthSummaryService` used to summarize auth state and assert readiness. - * Core-scoped — shared across the application. + * App-scoped — shared across the application. */ import type { diff --git a/packages/agent-core-v2/src/auth/authService.ts b/packages/agent-core-v2/src/auth/authService.ts index 66964d9ae..771e88baf 100644 --- a/packages/agent-core-v2/src/auth/authService.ts +++ b/packages/agent-core-v2/src/auth/authService.ts @@ -8,7 +8,7 @@ * through `telemetry`, logs through `log`, and delegates the device-code * protocol, token storage, and token refresh to `IOAuthToolkit` (provided by * `OAuthToolkitService` over `@moonshot-ai/kimi-code-oauth`, which locates - * token storage through `bootstrap`). Bound at Core scope. + * token storage through `bootstrap`). Bound at App scope. */ import { randomUUID } from 'node:crypto'; @@ -616,6 +616,6 @@ class OAuthToolkitService extends KimiOAuthToolkit implements IOAuthToolkit { } } -registerScopedService(LifecycleScope.Core, IOAuthService, OAuthService, InstantiationType.Delayed, 'auth'); -registerScopedService(LifecycleScope.Core, IOAuthToolkit, OAuthToolkitService, InstantiationType.Delayed, 'auth'); -registerScopedService(LifecycleScope.Core, IAuthSummaryService, AuthSummaryService, InstantiationType.Delayed, 'auth'); +registerScopedService(LifecycleScope.App, IOAuthService, OAuthService, InstantiationType.Delayed, 'auth'); +registerScopedService(LifecycleScope.App, IOAuthToolkit, OAuthToolkitService, InstantiationType.Delayed, 'auth'); +registerScopedService(LifecycleScope.App, IAuthSummaryService, AuthSummaryService, InstantiationType.Delayed, 'auth'); diff --git a/packages/agent-core-v2/src/authLegacy/authLegacy.ts b/packages/agent-core-v2/src/authLegacy/authLegacy.ts index fb74562e2..b14b10968 100644 --- a/packages/agent-core-v2/src/authLegacy/authLegacy.ts +++ b/packages/agent-core-v2/src/authLegacy/authLegacy.ts @@ -5,7 +5,7 @@ * native v2 services (`IProviderService`, `IConfigService`, `IOAuthService`). * The native `IAuthSummaryService` keeps serving `/api/v2` (`auth:summarize` / * `auth:ensureReady`) and is left untouched; this adapter exists only so v1 - * clients keep working against server-v2. Bound at Core scope — it is a + * clients keep working against server-v2. Bound at App scope — it is a * stateless projector over the global provider / model / credential state. */ diff --git a/packages/agent-core-v2/src/authLegacy/authLegacyService.ts b/packages/agent-core-v2/src/authLegacy/authLegacyService.ts index c1ace2b2d..8faaffd26 100644 --- a/packages/agent-core-v2/src/authLegacy/authLegacyService.ts +++ b/packages/agent-core-v2/src/authLegacy/authLegacyService.ts @@ -1,7 +1,7 @@ /** * `authLegacy` domain — `IAuthLegacyService` implementation. * - * Stateless Core-scope projector: reads the configured providers through + * Stateless App-scope projector: reads the configured providers through * `provider`, the global default-model selection through `config`, and the * managed OAuth provider's cached-token state through `auth`, then assembles * the v1 `AuthSummary`. The computation mirrors v1's `AuthSummaryService.get()` @@ -77,7 +77,7 @@ function nonEmpty(value: string | undefined): string | null { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IAuthLegacyService, AuthLegacyService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/background/background.ts b/packages/agent-core-v2/src/background/background.ts index 59d28f498..0a4bda9a5 100644 --- a/packages/agent-core-v2/src/background/background.ts +++ b/packages/agent-core-v2/src/background/background.ts @@ -45,7 +45,7 @@ export interface RegisterBackgroundTaskOptions { export type ForegroundTaskReleaseReason = 'detached' | 'terminal'; -export interface IBackgroundService { +export interface IAgentBackgroundService { readonly _serviceBrand: undefined; registerTask(task: BackgroundTask, options?: RegisterBackgroundTaskOptions): string; getTask(taskId: string): BackgroundTaskInfo | undefined; @@ -66,5 +66,5 @@ export interface IBackgroundService { ): Promise; } -export const IBackgroundService = - createDecorator('agentBackgroundService'); +export const IAgentBackgroundService = + createDecorator('agentBackgroundService'); diff --git a/packages/agent-core-v2/src/background/backgroundService.ts b/packages/agent-core-v2/src/background/backgroundService.ts index 6f3b01886..9c4fcbaef 100644 --- a/packages/agent-core-v2/src/background/backgroundService.ts +++ b/packages/agent-core-v2/src/background/backgroundService.ts @@ -1,5 +1,5 @@ /** - * `background` domain (L5) — `BackgroundService` implementation. + * `background` domain (L5) — `AgentBackgroundService` implementation. * * Owns the agent's registry of running and restored background tasks: * registers and drives tasks to completion, retains a bounded output ring, @@ -25,19 +25,19 @@ import { type BackgroundTaskSettlement, } from './task'; -import { IContextMemory } from '#/contextMemory'; +import { IAgentContextMemoryService } from '#/contextMemory'; import { IConfigRegistry, IConfigService } from '#/config'; -import { IEventSink } from '../eventSink'; -import { IExternalHooksService } from '#/externalHooks'; -import { IPromptService } from '#/prompt'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentExternalHooksService } from '#/externalHooks'; +import { IAgentPromptService } from '#/prompt'; import { ISessionContext } from '#/session-context'; import { IAtomicDocumentStore, IStorageService } from '#/storage'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { WireRecord } from '#/wireRecord'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { - IBackgroundService, + IAgentBackgroundService, type BackgroundLoadOptions, type BackgroundTask, type BackgroundTaskInfo, @@ -123,7 +123,7 @@ export function isBackgroundTaskTerminal(status: BackgroundTaskStatus): boolean return TERMINAL_STATUSES.has(status); } -export class BackgroundService extends Disposable implements IBackgroundService { +export class AgentBackgroundService extends Disposable implements IAgentBackgroundService { declare readonly _serviceBrand: undefined; private readonly tasks = new Map(); @@ -133,13 +133,13 @@ export class BackgroundService extends Disposable implements IBackgroundService private readonly persistence: BackgroundTaskPersistence; constructor( - @IEventSink private readonly events: IEventSink, - @IWireRecord private readonly wireRecord: IWireRecord, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, @ITelemetryService private readonly telemetry: ITelemetryService, - @IPromptService private readonly prompt: IPromptService, - @IExternalHooksService private readonly externalHooks: IExternalHooksService, - @IContextMemory private readonly context: IContextMemory, - @IToolRegistry toolRegistry: IToolRegistry, + @IAgentPromptService private readonly prompt: IAgentPromptService, + @IAgentExternalHooksService private readonly externalHooks: IAgentExternalHooksService, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, @IConfigRegistry configRegistry: IConfigRegistry, @IConfigService private readonly config: IConfigService, @IAtomicDocumentStore atomicDocs: IAtomicDocumentStore, @@ -944,12 +944,12 @@ function errorMessage(error: unknown): string { return String(error); } -export { BackgroundService as Background }; +export { AgentBackgroundService as Background }; registerScopedService( LifecycleScope.Agent, - IBackgroundService, - BackgroundService, + IAgentBackgroundService, + AgentBackgroundService, InstantiationType.Delayed, 'background', ); diff --git a/packages/agent-core-v2/src/background/configSection.ts b/packages/agent-core-v2/src/background/configSection.ts index 40cf7d024..3a6dea763 100644 --- a/packages/agent-core-v2/src/background/configSection.ts +++ b/packages/agent-core-v2/src/background/configSection.ts @@ -2,7 +2,7 @@ * `background` domain (L5) — `background` config-section schema. * * Owns the `[background]` configuration section (background-task limits and - * lifecycle tuning). Registered into `IConfigRegistry` by `BackgroundService` + * lifecycle tuning). Registered into `IConfigRegistry` by `AgentBackgroundService` * on construction, so the `config` domain never imports this domain's types. */ diff --git a/packages/agent-core-v2/src/background/index.ts b/packages/agent-core-v2/src/background/index.ts index bfcd9431c..b319c20d2 100644 --- a/packages/agent-core-v2/src/background/index.ts +++ b/packages/agent-core-v2/src/background/index.ts @@ -1,7 +1,7 @@ /** * `background` domain barrel — re-exports the background contract * (`background`) and its scoped service (`backgroundService`). Importing this - * barrel registers the `IBackgroundService` binding into the scope registry. + * barrel registers the `IAgentBackgroundService` binding into the scope registry. */ export * from './background'; diff --git a/packages/agent-core-v2/src/background/persist.ts b/packages/agent-core-v2/src/background/persist.ts index a8854285d..8c2b994b2 100644 --- a/packages/agent-core-v2/src/background/persist.ts +++ b/packages/agent-core-v2/src/background/persist.ts @@ -1,6 +1,6 @@ /** * `background` domain (L5) — `BackgroundTaskPersistence`, the per-session - * persistence helper behind `BackgroundService`. + * persistence helper behind `AgentBackgroundService`. * * Persists task state (`.json`) and raw task output (`output.log`) * through the `storage` access-pattern stores (`IAtomicDocumentStore` for @@ -10,7 +10,7 @@ * `{prefix}-{8 hex}` shape before use as path segments (path-traversal and * legacy `bg_` guard), and legacy snake_case records are normalized to * the current shape on read. Not scope-bound; constructed by - * `BackgroundService`. + * `AgentBackgroundService`. */ import { join } from 'pathe'; diff --git a/packages/agent-core-v2/src/background/tools/task-list.ts b/packages/agent-core-v2/src/background/tools/task-list.ts index a0a160a83..e2de4df36 100644 --- a/packages/agent-core-v2/src/background/tools/task-list.ts +++ b/packages/agent-core-v2/src/background/tools/task-list.ts @@ -8,7 +8,7 @@ import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import { matchesGlobRuleSubject } from '#/_base/tools/support/rule-match'; import type { BuiltinTool, ToolExecution } from '#/tool'; -import type { BackgroundTaskInfo, IBackgroundService } from '../background'; +import type { BackgroundTaskInfo, IAgentBackgroundService } from '../background'; import { formatPlainObject } from './format'; import TASK_LIST_DESCRIPTION from './task-list.md?raw'; @@ -48,7 +48,7 @@ export class TaskListTool implements BuiltinTool { readonly description = TASK_LIST_DESCRIPTION; readonly parameters: Record = toInputJsonSchema(TaskListInputSchema); - constructor(private readonly background: IBackgroundService) {} + constructor(private readonly background: IAgentBackgroundService) {} resolveExecution(args: TaskListInput): ToolExecution { const listScope = (args.active_only ?? true) ? 'active' : 'all'; diff --git a/packages/agent-core-v2/src/background/tools/task-output.ts b/packages/agent-core-v2/src/background/tools/task-output.ts index c54518dff..dcada1d32 100644 --- a/packages/agent-core-v2/src/background/tools/task-output.ts +++ b/packages/agent-core-v2/src/background/tools/task-output.ts @@ -21,7 +21,7 @@ import type { BuiltinTool, ExecutableToolResult, ToolExecution } from '#/tool'; import type { BackgroundTaskInfo, BackgroundTaskOutputSnapshot, - IBackgroundService, + IAgentBackgroundService, } from '../background'; import { type BackgroundTaskStatus, TERMINAL_STATUSES } from '../task'; import { formatPlainObject } from './format'; @@ -98,7 +98,7 @@ export class TaskOutputTool implements BuiltinTool { readonly description: string = TASK_OUTPUT_DESCRIPTION; readonly parameters: Record = toInputJsonSchema(TaskOutputInputSchema); - constructor(private readonly background: IBackgroundService) {} + constructor(private readonly background: IAgentBackgroundService) {} resolveExecution(args: TaskOutputInput): ToolExecution { return { diff --git a/packages/agent-core-v2/src/background/tools/task-stop.ts b/packages/agent-core-v2/src/background/tools/task-stop.ts index 36f13b59a..0baa748a2 100644 --- a/packages/agent-core-v2/src/background/tools/task-stop.ts +++ b/packages/agent-core-v2/src/background/tools/task-stop.ts @@ -8,7 +8,7 @@ import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import { matchesGlobRuleSubject } from '#/_base/tools/support/rule-match'; import type { BuiltinTool, ToolExecution } from '#/tool'; -import type { IBackgroundService } from '../background'; +import type { IAgentBackgroundService } from '../background'; import { TERMINAL_STATUSES } from '../task'; import TASK_STOP_DESCRIPTION from './task-stop.md?raw'; @@ -32,7 +32,7 @@ export class TaskStopTool implements BuiltinTool { readonly description = TASK_STOP_DESCRIPTION; readonly parameters: Record = toInputJsonSchema(TaskStopInputSchema); - constructor(private readonly background: IBackgroundService) {} + constructor(private readonly background: IAgentBackgroundService) {} resolveExecution(args: TaskStopInput): ToolExecution { return { diff --git a/packages/agent-core-v2/src/blobStore/blobStore.ts b/packages/agent-core-v2/src/blobStore/blobStore.ts index 9b71cbebb..6784e4232 100644 --- a/packages/agent-core-v2/src/blobStore/blobStore.ts +++ b/packages/agent-core-v2/src/blobStore/blobStore.ts @@ -5,13 +5,13 @@ import { createDecorator } from "#/_base/di"; export const BLOBREF_PROTOCOL = 'blobref:'; export const MISSING_MEDIA_PLACEHOLDER = '[media missing]'; -export interface IBlobStoreService { +export interface IAgentBlobStoreService { readonly _serviceBrand: undefined; offloadParts(parts: readonly ContentPart[]): Promise; rehydrateParts(parts: readonly ContentPart[]): Promise; isBlobRef(url: string): boolean; } -export const IBlobStoreService = createDecorator( +export const IAgentBlobStoreService = createDecorator( 'agentBlobStoreService', ); diff --git a/packages/agent-core-v2/src/blobStore/blobStoreService.ts b/packages/agent-core-v2/src/blobStore/blobStoreService.ts index bd1e6a850..2d922b25e 100644 --- a/packages/agent-core-v2/src/blobStore/blobStoreService.ts +++ b/packages/agent-core-v2/src/blobStore/blobStoreService.ts @@ -6,7 +6,7 @@ import { IBlobStorage, type IStorageService } from '#/storage'; import { BLOBREF_PROTOCOL, - IBlobStoreService, + IAgentBlobStoreService, MISSING_MEDIA_PLACEHOLDER, } from './blobStore'; @@ -15,7 +15,7 @@ const DEFAULT_MAX_CACHE_SIZE = 50 * 1024 * 1024; const DEFAULT_STORAGE_SCOPE = 'blobs'; const DATA_URI_HEADER_RE = /^data:([^;]+);base64,/; -export class BlobStoreService implements IBlobStoreService { +export class AgentBlobStoreService implements IAgentBlobStoreService { declare readonly _serviceBrand: undefined; private readonly storageScope = DEFAULT_STORAGE_SCOPE; @@ -184,8 +184,8 @@ function asMediaContainer(value: unknown): { url: unknown } | undefined { registerScopedService( LifecycleScope.Agent, - IBlobStoreService, - BlobStoreService, + IAgentBlobStoreService, + AgentBlobStoreService, InstantiationType.Delayed, 'blobStore', ); diff --git a/packages/agent-core-v2/src/bootstrap/bootstrap.ts b/packages/agent-core-v2/src/bootstrap/bootstrap.ts index 61d2d3a45..c585cf7a3 100644 --- a/packages/agent-core-v2/src/bootstrap/bootstrap.ts +++ b/packages/agent-core-v2/src/bootstrap/bootstrap.ts @@ -7,7 +7,7 @@ * layout (`homeDir`, `configPath`, …). `resolveBootstrapOptions` is the single * place that reads `process.env` / `os.homedir()` / invocation input to resolve * the snapshot; everything downstream reads from `IBootstrapService` instead of - * touching `process` directly. Bound at Core scope. Also seeds the Core storage + * touching `process` directly. Bound at App scope. Also seeds the App storage * roles (`IStorageService`, `IAppendLogStorage`, `IAtomicDocumentStorage`, * `IBlobStorage`) each with its own `FileStorageService` rooted at `homeDir` * (via per-token `SyncDescriptor`s), so the byte layer (and every Store above @@ -23,7 +23,7 @@ import type { Environment } from '#/kaos'; import { SyncDescriptor } from '#/_base/di/descriptors'; import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; -import { createCoreScope, type Scope, type ScopeSeed } from '#/_base/di/scope'; +import { createAppScope, type Scope, type ScopeSeed } from '#/_base/di/scope'; import { FileStorageService, IAppendLogStorage, @@ -101,15 +101,15 @@ export function bootstrapSeed(input: BootstrapInput = {}): ScopeSeed { } export interface BootstrapResult { - readonly core: Scope; + readonly app: Scope; } export function bootstrap(input: BootstrapInput = {}, extraSeeds: ScopeSeed = []): BootstrapResult { const options = resolveBootstrapOptions(input); - const core = createCoreScope({ + const app = createAppScope({ extra: [...bootstrapSeed(input), ...storageSeed(options), ...skillSeed(), ...extraSeeds], }); - return { core }; + return { app }; } function storageSeed(options: IBootstrapOptions): ScopeSeed { diff --git a/packages/agent-core-v2/src/bootstrap/bootstrapService.ts b/packages/agent-core-v2/src/bootstrap/bootstrapService.ts index 3c3198d60..0b37242aa 100644 --- a/packages/agent-core-v2/src/bootstrap/bootstrapService.ts +++ b/packages/agent-core-v2/src/bootstrap/bootstrapService.ts @@ -3,7 +3,7 @@ * * Holds the resolved startup snapshot from the seeded `IBootstrapOptions` and * exposes the host facts and app path layout; `detect()` probes the host through - * `kaos` on demand. Bound at Core scope. + * `kaos` on demand. Bound at App scope. */ import { join } from 'pathe'; @@ -57,4 +57,4 @@ export class BootstrapService implements IBootstrapService { } } -registerScopedService(LifecycleScope.Core, IBootstrapService, BootstrapService, InstantiationType.Eager, 'bootstrap'); +registerScopedService(LifecycleScope.App, IBootstrapService, BootstrapService, InstantiationType.Eager, 'bootstrap'); diff --git a/packages/agent-core-v2/src/chatProvider/chatProvider.ts b/packages/agent-core-v2/src/chatProvider/chatProvider.ts index 008a3f476..6ac609eb5 100644 --- a/packages/agent-core-v2/src/chatProvider/chatProvider.ts +++ b/packages/agent-core-v2/src/chatProvider/chatProvider.ts @@ -4,7 +4,7 @@ * Builds the protocol adapter (`ChatProvider`) that speaks a given provider * `type`. A provider is a configured endpoint (baseUrl / apiKey / model); the * factory is the adapter that speaks its wire protocol — different providers - * may share one adapter. Bound at Core scope. + * may share one adapter. Bound at App scope. */ import type { ChatProvider, ProviderConfig, ProviderType } from '@moonshot-ai/kosong'; diff --git a/packages/agent-core-v2/src/chatProvider/chatProviderService.ts b/packages/agent-core-v2/src/chatProvider/chatProviderService.ts index 27fd8dfca..781fe810e 100644 --- a/packages/agent-core-v2/src/chatProvider/chatProviderService.ts +++ b/packages/agent-core-v2/src/chatProvider/chatProviderService.ts @@ -4,7 +4,7 @@ * Dispatches to the adapter registered for a provider `type`, falling back to * the built-in adapters from the `@moonshot-ai/kosong` package's * `createProvider`. Owns no configuration and no business dependencies. Bound - * at Core scope. + * at App scope. */ import type { ChatProvider, ProviderConfig, ProviderType } from '@moonshot-ai/kosong'; @@ -30,7 +30,7 @@ export class ChatProviderFactory implements IChatProviderFactory { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IChatProviderFactory, ChatProviderFactory, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/config/config.ts b/packages/agent-core-v2/src/config/config.ts index 3fabf23f3..9d9355b4b 100644 --- a/packages/agent-core-v2/src/config/config.ts +++ b/packages/agent-core-v2/src/config/config.ts @@ -2,7 +2,7 @@ * `config` domain (L2) — configuration registry and layered global config service. * * Defines the config service identifiers and section models: the - * `IConfigRegistry` for section schemas, and the Core-scoped `IConfigService` + * `IConfigRegistry` for section schemas, and the App-scoped `IConfigService` * that resolves a value by precedence across layers (defaults → user config → * per-run memory overrides) and writes through a `ConfigTarget`. Owners react * to edits through two change events — `onDidChange` (a domain was touched) and diff --git a/packages/agent-core-v2/src/config/configService.ts b/packages/agent-core-v2/src/config/configService.ts index 9a0d5a78d..8c05e8d1b 100644 --- a/packages/agent-core-v2/src/config/configService.ts +++ b/packages/agent-core-v2/src/config/configService.ts @@ -12,7 +12,7 @@ * `bootstrap`, persists the TOML document through the `storage` TOML * atomic-document store (reloading when the document changes on disk), and logs * through `log`. Late section / overlay registration re-validates the - * already-loaded raw value and re-runs overlays. Bound at Core scope. + * already-loaded raw value and re-runs overlays. Bound at App scope. */ import { basename } from 'pathe'; @@ -480,14 +480,14 @@ export class ConfigService extends Disposable implements IConfigService { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IConfigRegistry, ConfigRegistry, InstantiationType.Delayed, 'config', ); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IConfigService, ConfigService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/contextInjector/contextInjector.ts b/packages/agent-core-v2/src/contextInjector/contextInjector.ts index e35e8b783..23deffe5e 100644 --- a/packages/agent-core-v2/src/contextInjector/contextInjector.ts +++ b/packages/agent-core-v2/src/contextInjector/contextInjector.ts @@ -13,7 +13,7 @@ export type ContextInjectionProvider = ( context: ContextInjectionContext, ) => string | undefined | Promise; -export interface IContextInjector { +export interface IAgentContextInjectorService { readonly _serviceBrand: undefined; register( variant: string, @@ -22,6 +22,6 @@ export interface IContextInjector { ): IDisposable; } -export const IContextInjector = createDecorator( - 'contextInjectorService', +export const IAgentContextInjectorService = createDecorator( + 'agentContextInjectorService', ); diff --git a/packages/agent-core-v2/src/contextInjector/contextInjectorService.ts b/packages/agent-core-v2/src/contextInjector/contextInjectorService.ts index 0b276aa02..d39e55c54 100644 --- a/packages/agent-core-v2/src/contextInjector/contextInjectorService.ts +++ b/packages/agent-core-v2/src/contextInjector/contextInjectorService.ts @@ -5,12 +5,12 @@ import { import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IContextMemory } from '../contextMemory'; -import { ISystemReminderService } from '../systemReminder'; -import { ITurnService } from '../turn'; +import { IAgentContextMemoryService } from '../contextMemory'; +import { IAgentSystemReminderService } from '../systemReminder'; +import { IAgentTurnService } from '../turn'; import type { ContextMessage } from '#/contextMemory'; import { - IContextInjector, + IAgentContextInjectorService, type ContextInjectionOptions, type ContextInjectionProvider, } from './contextInjector'; @@ -24,15 +24,15 @@ interface ContextInjectionEntry { turnConsumed: boolean; } -export class ContextInjectorService extends Disposable implements IContextInjector { +export class AgentContextInjectorService extends Disposable implements IAgentContextInjectorService { declare readonly _serviceBrand: undefined; private readonly entries = new Set(); private readonly selfInsertedMessages = new WeakMap(); constructor( - @IContextMemory private readonly context: IContextMemory, - @ITurnService turnService: ITurnService, - @ISystemReminderService private readonly reminders: ISystemReminderService, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentTurnService turnService: IAgentTurnService, + @IAgentSystemReminderService private readonly reminders: IAgentSystemReminderService, ) { super(); this._register( @@ -186,8 +186,8 @@ function findLastInjection( registerScopedService( LifecycleScope.Agent, - IContextInjector, - ContextInjectorService, + IAgentContextInjectorService, + AgentContextInjectorService, InstantiationType.Delayed, 'contextInjector', ); diff --git a/packages/agent-core-v2/src/contextMemory/contextMemory.ts b/packages/agent-core-v2/src/contextMemory/contextMemory.ts index f5406ef03..56432d637 100644 --- a/packages/agent-core-v2/src/contextMemory/contextMemory.ts +++ b/packages/agent-core-v2/src/contextMemory/contextMemory.ts @@ -3,7 +3,7 @@ import { createDecorator } from "#/_base/di"; import type { Hooks } from '#/hooks'; import type { ContextMessage } from './types'; -export interface IContextMemory { +export interface IAgentContextMemoryService { readonly _serviceBrand: undefined; get(): readonly ContextMessage[]; splice( @@ -23,4 +23,4 @@ export interface IContextMemory { }>; } -export const IContextMemory = createDecorator('agentContextMemoryService'); +export const IAgentContextMemoryService = createDecorator('agentContextMemoryService'); diff --git a/packages/agent-core-v2/src/contextMemory/contextMemoryService.ts b/packages/agent-core-v2/src/contextMemory/contextMemoryService.ts index c0853def8..cf5659f0e 100644 --- a/packages/agent-core-v2/src/contextMemory/contextMemoryService.ts +++ b/packages/agent-core-v2/src/contextMemory/contextMemoryService.ts @@ -2,9 +2,9 @@ import { Disposable, } from "#/_base/di"; import { OrderedHookSlot } from '#/hooks'; -import { IReplayBuilderService } from '#/replayBuilder'; -import { IWireRecord, type WireRecord } from '#/wireRecord'; -import { IContextMemory } from './contextMemory'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; +import { IAgentWireRecordService, type WireRecord } from '#/wireRecord'; +import { IAgentContextMemoryService } from './contextMemory'; import { ensureMessageId } from './messageId'; import type { ContextMessage } from './types'; import { InstantiationType } from '#/_base/di/extensions'; @@ -21,7 +21,7 @@ declare module '#/wireRecord' { } } -export class ContextMemoryService extends Disposable implements IContextMemory { +export class AgentContextMemoryService extends Disposable implements IAgentContextMemoryService { declare readonly _serviceBrand: undefined; private readonly history: ContextMessage[] = []; @@ -35,8 +35,8 @@ export class ContextMemoryService extends Disposable implements IContextMemory { }; constructor( - @IWireRecord private readonly wireRecord: IWireRecord, - @IReplayBuilderService private readonly replayBuilder: IReplayBuilderService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentReplayBuilderService private readonly replayBuilder: IAgentReplayBuilderService, ) { super(); this._register( @@ -104,8 +104,8 @@ export class ContextMemoryService extends Disposable implements IContextMemory { registerScopedService( LifecycleScope.Agent, - IContextMemory, - ContextMemoryService, + IAgentContextMemoryService, + AgentContextMemoryService, InstantiationType.Delayed, 'contextMemory', ); diff --git a/packages/agent-core-v2/src/contextMemory/messageId.ts b/packages/agent-core-v2/src/contextMemory/messageId.ts index ff9e3a9b1..3dc083554 100644 --- a/packages/agent-core-v2/src/contextMemory/messageId.ts +++ b/packages/agent-core-v2/src/contextMemory/messageId.ts @@ -2,7 +2,7 @@ * `contextMemory` message id helpers. * * Every `ContextMessage` gets a stable local id (`msg_`) when it enters - * `IContextMemory` — see `ContextMemoryService.splice`. The id is persisted in + * `IAgentContextMemoryService` — see `AgentContextMemoryService.splice`. The id is persisted in * the `context.splice` wire record, so it is stable across restarts. It is the * identity used by `Turn.promptMessageId`, snapshot `current_prompt_id`, and * message lookup. Provider-assigned ids live on the separate diff --git a/packages/agent-core-v2/src/contextProjector/contextProjector.ts b/packages/agent-core-v2/src/contextProjector/contextProjector.ts index d678a2810..b475b679f 100644 --- a/packages/agent-core-v2/src/contextProjector/contextProjector.ts +++ b/packages/agent-core-v2/src/contextProjector/contextProjector.ts @@ -3,11 +3,11 @@ import type { Message } from '@moonshot-ai/kosong'; import type { ContextMessage } from '#/contextMemory'; -export interface IContextProjector { +export interface IAgentContextProjectorService { readonly _serviceBrand: undefined; project(messages: readonly ContextMessage[]): readonly Message[]; } -export const IContextProjector = createDecorator( +export const IAgentContextProjectorService = createDecorator( 'agentContextProjectorService', ); diff --git a/packages/agent-core-v2/src/contextProjector/contextProjectorService.ts b/packages/agent-core-v2/src/contextProjector/contextProjectorService.ts index cc00ba74c..f0deedc9a 100644 --- a/packages/agent-core-v2/src/contextProjector/contextProjectorService.ts +++ b/packages/agent-core-v2/src/contextProjector/contextProjectorService.ts @@ -5,11 +5,11 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import type { ContextMessage } from '#/contextMemory/types'; import { ErrorCodes, KimiError } from '#/errors'; -import { IMicroCompactionService } from '#/microCompaction'; +import { IAgentMicroCompactionService } from '#/microCompaction'; import type { ContentPart, Message, TextPart } from '@moonshot-ai/kosong'; -import { IContextProjector } from './contextProjector'; +import { IAgentContextProjectorService } from './contextProjector'; -export class ContextProjectorService implements IContextProjector { +export class AgentContextProjectorService implements IAgentContextProjectorService { declare readonly _serviceBrand: undefined; constructor( @IInstantiationService private readonly instantiation: IInstantiationService, @@ -19,9 +19,9 @@ export class ContextProjectorService implements IContextProjector { return project(this.microCompaction().compact(messages)); } - private microCompaction(): IMicroCompactionService { + private microCompaction(): IAgentMicroCompactionService { return this.instantiation.invokeFunction((accessor) => - accessor.get(IMicroCompactionService), + accessor.get(IAgentMicroCompactionService), ); } } @@ -226,8 +226,8 @@ function isInterruptedToolResult(message: Message): boolean { registerScopedService( LifecycleScope.Agent, - IContextProjector, - ContextProjectorService, + IAgentContextProjectorService, + AgentContextProjectorService, InstantiationType.Delayed, 'contextProjector', ); diff --git a/packages/agent-core-v2/src/contextSize/contextSize.ts b/packages/agent-core-v2/src/contextSize/contextSize.ts index c7d16b835..67a18711c 100644 --- a/packages/agent-core-v2/src/contextSize/contextSize.ts +++ b/packages/agent-core-v2/src/contextSize/contextSize.ts @@ -5,12 +5,12 @@ export interface ContextSizeStatus { readonly contextTokensWithPending: number; } -export interface IContextSizeService { +export interface IAgentContextSizeService { readonly _serviceBrand: undefined; getStatus(): ContextSizeStatus; measured(length: number, tokens: number): void; } -export const IContextSizeService = - createDecorator('agentContextSizeService'); +export const IAgentContextSizeService = + createDecorator('agentContextSizeService'); diff --git a/packages/agent-core-v2/src/contextSize/contextSizeService.ts b/packages/agent-core-v2/src/contextSize/contextSizeService.ts index fb071f44d..8387456ce 100644 --- a/packages/agent-core-v2/src/contextSize/contextSizeService.ts +++ b/packages/agent-core-v2/src/contextSize/contextSizeService.ts @@ -5,11 +5,11 @@ import { estimateTokensForMessage, } from "#/_base/utils/tokens"; import type { ContextMessage } from '#/contextMemory'; -import { IContextMemory } from '#/contextMemory'; -import { IEventSink } from '../eventSink'; -import { IWireRecord, type WireRecord } from '#/wireRecord'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentWireRecordService, type WireRecord } from '#/wireRecord'; import { - IContextSizeService, + IAgentContextSizeService, type ContextSizeStatus, } from './contextSize'; import { InstantiationType } from '#/_base/di/extensions'; @@ -24,9 +24,9 @@ declare module '#/wireRecord' { } } -export class ContextSizeService +export class AgentContextSizeService extends Disposable - implements IContextSizeService + implements IAgentContextSizeService { declare readonly _serviceBrand: undefined; @@ -38,9 +38,9 @@ export class ContextSizeService }; constructor( - @IContextMemory private readonly context: IContextMemory, - @IEventSink private readonly events: IEventSink, - @IWireRecord private readonly wireRecord: IWireRecord, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, ) { super(); this._register( @@ -157,8 +157,8 @@ function sum(values: readonly number[]): number { registerScopedService( LifecycleScope.Agent, - IContextSizeService, - ContextSizeService, + IAgentContextSizeService, + AgentContextSizeService, InstantiationType.Delayed, 'contextSize', ); diff --git a/packages/agent-core-v2/src/cron/cron.ts b/packages/agent-core-v2/src/cron/cron.ts index f3d3e2742..85a8546d9 100644 --- a/packages/agent-core-v2/src/cron/cron.ts +++ b/packages/agent-core-v2/src/cron/cron.ts @@ -26,7 +26,7 @@ export interface CronFireOptions { readonly firedAt?: number; } -export interface ICronService extends CronToolManager { +export interface IAgentCronService extends CronToolManager { readonly _serviceBrand: undefined; readonly isEnabled: boolean; getTask(id: string): CronTask | undefined; @@ -46,4 +46,4 @@ export interface ICronService extends CronToolManager { flushPersist(): Promise; } -export const ICronService = createDecorator('agentCronService'); +export const IAgentCronService = createDecorator('agentCronService'); diff --git a/packages/agent-core-v2/src/cron/cronService.ts b/packages/agent-core-v2/src/cron/cronService.ts index 338a61fb2..c813d6369 100644 --- a/packages/agent-core-v2/src/cron/cronService.ts +++ b/packages/agent-core-v2/src/cron/cronService.ts @@ -1,5 +1,5 @@ /** - * `cron` domain (L5) — `CronService` implementation. + * `cron` domain (L5) — `AgentCronService` implementation. * * Owns the agent's cron task set: schedules and fires due tasks (steering * the agent through `prompt`), persists task records through the `cron` @@ -17,17 +17,17 @@ import { toDisposable, } from "#/_base/di"; import type { ContextMessage } from '#/contextMemory'; -import { IEventSink } from '../eventSink'; +import { IAgentEventSinkService } from '../eventSink'; import { IConfigRegistry, IConfigService } from '#/config'; -import { IPromptService } from '#/prompt'; +import { IAgentPromptService } from '#/prompt'; import { IAtomicDocumentStore } from '#/storage'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { Turn } from '#/turn'; -import { ITurnService } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentTurnService } from '#/turn'; +import { IAgentWireRecordService } from '#/wireRecord'; import { - ICronService, + IAgentCronService, type CronFireOptions, type CronLoadOptions, type CronOptions, @@ -82,9 +82,9 @@ declare module '#/wireRecord' { const STALE_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000; -export class CronService +export class AgentCronService extends Disposable - implements ICronService, CronToolManager { + implements IAgentCronService, CronToolManager { declare readonly _serviceBrand: undefined; readonly store = new SessionCronStore(); @@ -100,12 +100,12 @@ export class CronService constructor( options: CronOptions = {}, - @IPromptService private readonly prompt: IPromptService, - @IEventSink private readonly events: IEventSink, - @IWireRecord private readonly wireRecord: IWireRecord, - @ITurnService private readonly turnService: ITurnService, + @IAgentPromptService private readonly prompt: IAgentPromptService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentTurnService private readonly turnService: IAgentTurnService, @ITelemetryService private readonly telemetry: ITelemetryService, - @IToolRegistry private readonly toolRegistry: IToolRegistry, + @IAgentToolRegistryService private readonly toolRegistry: IAgentToolRegistryService, @IConfigRegistry configRegistry: IConfigRegistry, @IConfigService private readonly config: IConfigService, @IAtomicDocumentStore private readonly atomicDocs: IAtomicDocumentStore, @@ -442,8 +442,8 @@ export class CronService registerScopedService( LifecycleScope.Agent, - ICronService, - CronService, + IAgentCronService, + AgentCronService, InstantiationType.Delayed, 'cron', ); diff --git a/packages/agent-core-v2/src/cron/index.ts b/packages/agent-core-v2/src/cron/index.ts index 63221b878..c0f0e5ba4 100644 --- a/packages/agent-core-v2/src/cron/index.ts +++ b/packages/agent-core-v2/src/cron/index.ts @@ -1,6 +1,6 @@ /** * `cron` domain barrel — re-exports the cron contract (`cron`) and its scoped - * service (`cronService`). Importing this barrel registers the `ICronService` + * service (`cronService`). Importing this barrel registers the `IAgentCronService` * and `ICronFireCoordinator` bindings into the scope registry. */ diff --git a/packages/agent-core-v2/src/cron/tools/session-store.ts b/packages/agent-core-v2/src/cron/tools/session-store.ts index d4abc3305..38560d03f 100644 --- a/packages/agent-core-v2/src/cron/tools/session-store.ts +++ b/packages/agent-core-v2/src/cron/tools/session-store.ts @@ -2,7 +2,7 @@ * SessionCronStore — in-memory cron task store for a single CLI session. * * The store itself is purely in-memory; cross-restart persistence is - * layered on top by `CronService.addTask` / `removeTasks`, which + * layered on top by `AgentCronService.addTask` / `removeTasks`, which * mirror every mutation to `/cron/.json`. On resume * the service calls {@link adopt} to put each persisted task back into * the store with its original id and `createdAt` preserved. @@ -68,7 +68,7 @@ export class SessionCronStore { /** * Insert a previously-persisted task verbatim — id and createdAt - * stay as they are on disk. Used by `CronService.loadFromDisk()` to + * stay as they are on disk. Used by `AgentCronService.loadFromDisk()` to * rehydrate the store on resume. Unlike {@link add}, this does NOT * generate a new id; the caller is responsible for ensuring the id * matches the expected shape (the persistence layer's regex / diff --git a/packages/agent-core-v2/src/event/event.ts b/packages/agent-core-v2/src/event/event.ts index 02fb24c27..05d0c1a03 100644 --- a/packages/agent-core-v2/src/event/event.ts +++ b/packages/agent-core-v2/src/event/event.ts @@ -3,7 +3,7 @@ * * Defines `IEventService`, a minimal type-tagged event bus used by business * domains to broadcast facts (for example session lifecycle changes) to an - * unknown set of consumers. Bound at Core scope; a single global instance. + * unknown set of consumers. Bound at App scope; a single global instance. */ import { createDecorator, type IDisposable, type ServiceIdentifier } from '#/_base/di'; diff --git a/packages/agent-core-v2/src/event/eventService.ts b/packages/agent-core-v2/src/event/eventService.ts index b6e1f9da9..a9b12c491 100644 --- a/packages/agent-core-v2/src/event/eventService.ts +++ b/packages/agent-core-v2/src/event/eventService.ts @@ -2,7 +2,7 @@ * `event` domain (L0) — `IEventService` implementation. * * Delivers published events to subscribers through the `_base/event` `Emitter` - * primitive. Bound at Core scope. + * primitive. Bound at App scope. */ import { Disposable, type IDisposable } from '#/_base/di'; @@ -27,7 +27,7 @@ export class EventService extends Disposable implements IEventService { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IEventService, EventService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/eventSink/eventSink.ts b/packages/agent-core-v2/src/eventSink/eventSink.ts index 2ff525432..f1e72c0e2 100644 --- a/packages/agent-core-v2/src/eventSink/eventSink.ts +++ b/packages/agent-core-v2/src/eventSink/eventSink.ts @@ -2,10 +2,10 @@ import type { IDisposable } from "#/_base/di"; import { createDecorator } from "#/_base/di"; import type { AgentEvent } from '@moonshot-ai/protocol'; -export interface IEventSink { +export interface IAgentEventSinkService { readonly _serviceBrand: undefined; emit(event: AgentEvent): void; on(handler: (event: AgentEvent) => void): IDisposable; } -export const IEventSink = createDecorator('agentEventSink'); +export const IAgentEventSinkService = createDecorator('agentEventSinkService'); diff --git a/packages/agent-core-v2/src/eventSink/eventSinkService.ts b/packages/agent-core-v2/src/eventSink/eventSinkService.ts index dba894383..441721f5f 100644 --- a/packages/agent-core-v2/src/eventSink/eventSinkService.ts +++ b/packages/agent-core-v2/src/eventSink/eventSinkService.ts @@ -6,15 +6,15 @@ import { } from "#/_base/di"; import { Emitter } from "#/_base/event"; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import type { AgentEvent } from '@moonshot-ai/protocol'; -import { IEventSink } from './eventSink'; +import { IAgentEventSinkService } from './eventSink'; -export class EventSinkService extends Disposable implements IEventSink { +export class AgentEventSinkService extends Disposable implements IAgentEventSinkService { declare readonly _serviceBrand: undefined; private readonly onDidEmitEmitter = this._register(new Emitter()); - constructor(@IWireRecord private readonly wireRecord: IWireRecord) { + constructor(@IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService) { super(); } @@ -30,8 +30,8 @@ export class EventSinkService extends Disposable implements IEventSink { registerScopedService( LifecycleScope.Agent, - IEventSink, - EventSinkService, + IAgentEventSinkService, + AgentEventSinkService, InstantiationType.Delayed, 'eventSink', ); diff --git a/packages/agent-core-v2/src/externalHooks/configSection.ts b/packages/agent-core-v2/src/externalHooks/configSection.ts index e8b239ca0..fcab683fa 100644 --- a/packages/agent-core-v2/src/externalHooks/configSection.ts +++ b/packages/agent-core-v2/src/externalHooks/configSection.ts @@ -4,7 +4,7 @@ * * Owns the `[[hooks]]` configuration section (external hook definitions), * including the snake_case ↔ camelCase TOML transforms for each hook entry. - * Registered into `IConfigRegistry` by `ExternalHooksService` on construction, + * Registered into `IConfigRegistry` by `AgentExternalHooksService` on construction, * so the `config` domain never imports this domain's types. */ diff --git a/packages/agent-core-v2/src/externalHooks/externalHooks.ts b/packages/agent-core-v2/src/externalHooks/externalHooks.ts index 179e09ae2..e4de133b5 100644 --- a/packages/agent-core-v2/src/externalHooks/externalHooks.ts +++ b/packages/agent-core-v2/src/externalHooks/externalHooks.ts @@ -59,7 +59,7 @@ export type PermissionResultHookPayload = readonly error: string; }; -export interface IExternalHooksService { +export interface IAgentExternalHooksService { readonly _serviceBrand: undefined; triggerPreToolUse( payload: { @@ -98,5 +98,5 @@ export interface IExternalHooksService { }): void; } -export const IExternalHooksService = - createDecorator('agentExternalHooksService'); +export const IAgentExternalHooksService = + createDecorator('agentExternalHooksService'); diff --git a/packages/agent-core-v2/src/externalHooks/externalHooksService.ts b/packages/agent-core-v2/src/externalHooks/externalHooksService.ts index a739d6929..972ec2e36 100644 --- a/packages/agent-core-v2/src/externalHooks/externalHooksService.ts +++ b/packages/agent-core-v2/src/externalHooks/externalHooksService.ts @@ -1,7 +1,7 @@ import { toKimiErrorPayload } from "#/errors"; import { IConfigRegistry } from '#/config'; import { - IExternalHooksService, + IAgentExternalHooksService, type ExternalHooksServiceOptions, type NotificationHookPayload, type PermissionRequestHookPayload, @@ -16,7 +16,7 @@ import { import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { isPlainRecord } from '#/_base/utils/canonical-args'; -import { IToolExecutor } from '#/toolExecutor'; +import { IAgentToolExecutorService } from '#/toolExecutor'; function fireAndForget( engine: ExternalHooksServiceOptions['hookEngine'], @@ -32,12 +32,12 @@ function fireAndForget( void engine?.fireAndForgetTrigger(event, { matcherValue, signal, inputData }); } -export class ExternalHooksService implements IExternalHooksService { +export class AgentExternalHooksService implements IAgentExternalHooksService { declare readonly _serviceBrand: undefined; constructor( private readonly options: ExternalHooksServiceOptions = {}, - @IToolExecutor toolExecutor: IToolExecutor, + @IAgentToolExecutorService toolExecutor: IAgentToolExecutorService, @IConfigRegistry configRegistry: IConfigRegistry, ) { configRegistry.registerSection(HOOKS_SECTION, HooksConfigSchema, { @@ -74,7 +74,7 @@ export class ExternalHooksService implements IExternalHooksService { } async triggerPreToolUse( - payload: Parameters[0], + payload: Parameters[0], signal: AbortSignal, ): Promise { signal.throwIfAborted(); @@ -92,7 +92,7 @@ export class ExternalHooksService implements IExternalHooksService { } async triggerUserPromptSubmit( - input: Parameters[0], + input: Parameters[0], signal: AbortSignal, ): Promise { signal.throwIfAborted(); @@ -121,7 +121,7 @@ export class ExternalHooksService implements IExternalHooksService { } async triggerPostToolUse( - payload: Parameters[0], + payload: Parameters[0], signal: AbortSignal, ): Promise { const output = toolOutputText(payload.result.output); @@ -176,14 +176,14 @@ export class ExternalHooksService implements IExternalHooksService { ); } - triggerInterrupt(payload: Parameters[0]): void { + triggerInterrupt(payload: Parameters[0]): void { void this.options.hookEngine?.fireAndForgetTrigger('Interrupt', { inputData: payload, }); } async triggerPreCompact( - payload: Parameters[0], + payload: Parameters[0], signal: AbortSignal, ): Promise { signal.throwIfAborted(); @@ -198,7 +198,7 @@ export class ExternalHooksService implements IExternalHooksService { signal.throwIfAborted(); } - triggerPostCompact(payload: Parameters[0]): void { + triggerPostCompact(payload: Parameters[0]): void { void this.options.hookEngine?.fireAndForgetTrigger('PostCompact', { matcherValue: payload.trigger, inputData: { @@ -221,7 +221,7 @@ export class ExternalHooksService implements IExternalHooksService { } function toolOutputText( - output: Parameters[0]['result']['output'], + output: Parameters[0]['result']['output'], ): string { if (typeof output === 'string') return output; return output @@ -257,8 +257,8 @@ function permissionResultInputData(payload: PermissionResultHookPayload): Record registerScopedService( LifecycleScope.Agent, - IExternalHooksService, - ExternalHooksService, + IAgentExternalHooksService, + AgentExternalHooksService, InstantiationType.Delayed, 'externalHooks', ); diff --git a/packages/agent-core-v2/src/fileTools/fileTools.ts b/packages/agent-core-v2/src/fileTools/fileTools.ts index 0d5474ea7..4c4e68a96 100644 --- a/packages/agent-core-v2/src/fileTools/fileTools.ts +++ b/packages/agent-core-v2/src/fileTools/fileTools.ts @@ -1,16 +1,16 @@ /** * `fileTools` domain (L4) — built-in file tool registration contract. * - * `IFileToolsService` is a marker: its implementation registers the built-in - * file tools (Read / Write / Edit / Grep / Glob) into the agent `IToolRegistry` + * `IAgentFileToolsService` is a marker: its implementation registers the built-in + * file tools (Read / Write / Edit / Grep / Glob) into the agent `IAgentToolRegistryService` * on construction. Bound at Agent scope. */ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; -export interface IFileToolsService { +export interface IAgentFileToolsService { readonly _serviceBrand: undefined; } -export const IFileToolsService: ServiceIdentifier = - createDecorator('fileToolsService'); +export const IAgentFileToolsService: ServiceIdentifier = + createDecorator('agentFileToolsService'); diff --git a/packages/agent-core-v2/src/fileTools/fileToolsService.ts b/packages/agent-core-v2/src/fileTools/fileToolsService.ts index d092fd94d..654f5bbc0 100644 --- a/packages/agent-core-v2/src/fileTools/fileToolsService.ts +++ b/packages/agent-core-v2/src/fileTools/fileToolsService.ts @@ -1,36 +1,36 @@ /** - * `fileTools` domain (L4) — `IFileToolsService` implementation. + * `fileTools` domain (L4) — `IAgentFileToolsService` implementation. * * Registers the built-in file tools (Read / Write / Edit / Grep / Glob) into - * the agent `IToolRegistry` on construction, wiring each to the session - * `IAgentFileSystem` (file IO), `IFsService` (workspace search/grep), `IKaos` + * the agent `IAgentToolRegistryService` on construction, wiring each to the session + * `ISessionAgentFileSystem` (file IO), `ISessionFsService` (workspace search/grep), `IKaos` * (path semantics) and the session workspace. Bound at Agent scope. */ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import type { WorkspaceConfig } from '#/_base/tools/support/workspace'; -import { IAgentFileSystem, IFsService } from '#/agentFs'; +import { ISessionAgentFileSystem, ISessionFsService } from '#/agentFs'; import { IKaos } from '#/kaos'; -import { IToolRegistry } from '#/toolRegistry'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; -import { IFileToolsService } from './fileTools'; +import { IAgentFileToolsService } from './fileTools'; import { EditTool } from './tools/edit'; import { GlobTool } from './tools/glob'; import { GrepTool } from './tools/grep'; import { ReadTool } from './tools/read'; import { WriteTool } from './tools/write'; -export class FileToolsService implements IFileToolsService { +export class AgentFileToolsService implements IAgentFileToolsService { declare readonly _serviceBrand: undefined; constructor( - @IToolRegistry toolRegistry: IToolRegistry, - @IAgentFileSystem fs: IAgentFileSystem, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, + @ISessionAgentFileSystem fs: ISessionAgentFileSystem, @IKaos kaos: IKaos, - @IWorkspaceContext workspace: IWorkspaceContext, - @IFsService fsService: IFsService, + @ISessionWorkspaceContext workspace: ISessionWorkspaceContext, + @ISessionFsService fsService: ISessionFsService, ) { const workspaceConfig: WorkspaceConfig = { workspaceDir: workspace.workDir, @@ -46,8 +46,8 @@ export class FileToolsService implements IFileToolsService { registerScopedService( LifecycleScope.Agent, - IFileToolsService, - FileToolsService, + IAgentFileToolsService, + AgentFileToolsService, InstantiationType.Delayed, 'fileTools', ); diff --git a/packages/agent-core-v2/src/fileTools/index.ts b/packages/agent-core-v2/src/fileTools/index.ts index 0aa126e83..f696e06f8 100644 --- a/packages/agent-core-v2/src/fileTools/index.ts +++ b/packages/agent-core-v2/src/fileTools/index.ts @@ -1,8 +1,8 @@ /** * `fileTools` domain barrel — re-exports the built-in file tools (Read / Write * / Edit / Grep / Glob), the shared line-ending helpers, and the - * `IFileToolsService` registration contract + service. Importing this barrel - * registers the `IFileToolsService` binding into the scope registry. + * `IAgentFileToolsService` registration contract + service. Importing this barrel + * registers the `IAgentFileToolsService` binding into the scope registry. */ export * from './fileTools'; diff --git a/packages/agent-core-v2/src/fileTools/tools/edit.ts b/packages/agent-core-v2/src/fileTools/tools/edit.ts index 8a56907a5..35f729180 100644 --- a/packages/agent-core-v2/src/fileTools/tools/edit.ts +++ b/packages/agent-core-v2/src/fileTools/tools/edit.ts @@ -16,7 +16,7 @@ * * Ported from v1 (`packages/agent-core/src/tools/builtin/file/edit.ts`): the * `kaos.readText` / `kaos.writeText` calls become `fs.readText` / - * `fs.writeText` against `IAgentFileSystem`, and `kaos.pathClass()` / + * `fs.writeText` against `ISessionAgentFileSystem`, and `kaos.pathClass()` / * `kaos.gethome()` come from `IKaos`. */ @@ -27,7 +27,7 @@ import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import { literalRulePattern, matchesPathRuleSubject } from '#/_base/tools/support/rule-match'; import type { WorkspaceConfig } from '#/_base/tools/support/workspace'; import { renderPrompt } from '#/_base/utils/render-prompt'; -import { IAgentFileSystem } from '#/agentFs'; +import { ISessionAgentFileSystem } from '#/agentFs'; import { IKaos } from '#/kaos'; import { ToolAccesses } from '#/tool'; import type { BuiltinTool, ExecutableToolResult, ToolExecution } from '#/tool'; @@ -77,7 +77,7 @@ export class EditTool implements BuiltinTool { readonly parameters: Record = toInputJsonSchema(EditInputSchema); constructor( - private readonly fs: IAgentFileSystem, + private readonly fs: ISessionAgentFileSystem, private readonly kaos: IKaos, private readonly workspace: WorkspaceConfig, ) {} diff --git a/packages/agent-core-v2/src/fileTools/tools/glob.ts b/packages/agent-core-v2/src/fileTools/tools/glob.ts index 27c5ff905..7666374b8 100644 --- a/packages/agent-core-v2/src/fileTools/tools/glob.ts +++ b/packages/agent-core-v2/src/fileTools/tools/glob.ts @@ -10,7 +10,7 @@ * Ported from v1 (`packages/agent-core/src/tools/builtin/file/glob.ts`) onto * the v2 domains: * - Search root: v1 `kaos.glob(root, pattern)` (async generator) maps to - * `fs.withCwd(root).glob(pattern)`, since v2 `IAgentFileSystem.glob` + * `fs.withCwd(root).glob(pattern)`, since v2 `ISessionAgentFileSystem.glob` * searches from `fs.cwd` and returns a collected `Promise`. kaos yields absolute paths, so no further joining is needed. * - Path safety / home expansion / path class: `resolvePathAccessPath` over @@ -21,7 +21,7 @@ * instead of a misleading "No matches found". * * Documented deviation from v1: results are no longer sorted by modification - * time. v2 `IAgentFileSystem.stat` exposes `{ isFile, isDirectory, size }` + * time. v2 `ISessionAgentFileSystem.stat` exposes `{ isFile, isDirectory, size }` * only — it carries no mtime — so matches are returned in walk order (the * order `fs.glob` yields them, grouped by expanded sub-pattern). The cap, * dedup, truncation markers, and `include_dirs` filtering are unchanged. @@ -34,7 +34,7 @@ import { normalize } from 'pathe'; import { z } from 'zod'; -import { IAgentFileSystem } from '#/agentFs'; +import { ISessionAgentFileSystem } from '#/agentFs'; import { IKaos } from '#/kaos'; import { ToolAccesses } from '#/tool'; import type { BuiltinTool, ExecutableToolResult, ToolExecution } from '#/tool'; @@ -107,7 +107,7 @@ export class GlobTool implements BuiltinTool { readonly description: string; readonly parameters: Record = toInputJsonSchema(GlobInputSchema); constructor( - private readonly fs: IAgentFileSystem, + private readonly fs: ISessionAgentFileSystem, private readonly kaos: IKaos, private readonly workspace: WorkspaceConfig, ) { diff --git a/packages/agent-core-v2/src/fileTools/tools/grep.ts b/packages/agent-core-v2/src/fileTools/tools/grep.ts index 320013182..dccabfa22 100644 --- a/packages/agent-core-v2/src/fileTools/tools/grep.ts +++ b/packages/agent-core-v2/src/fileTools/tools/grep.ts @@ -2,7 +2,7 @@ * `fileTools` domain — GrepTool, the model's content search tool. * * Searches file contents with ripgrep-style regular expressions, delegating - * the actual scan to the `agentFs` domain's `IFsService.grep` (which is + * the actual scan to the `agentFs` domain's `ISessionFsService.grep` (which is * workspace-confined, `rg`-backed when available, and falls back to a Node * walker otherwise, honoring gitignore and glob filters). The tool maps the * model-facing input args onto an `FsGrepRequest`, then renders the @@ -14,12 +14,12 @@ * Read/Write/Edit/Grep: an explicit absolute path outside the workspace is * allowed for the access declaration, while a relative path that escapes the * workspace is rejected. The search itself is confined to the workspace by - * `IFsService`. + * `ISessionFsService`. * * Ported from v1 (`packages/agent-core/src/tools/builtin/file/grep.ts`). The * v1 tool shelled out to `rg` directly through Kaos and parsed its output; - * that work now lives in `IFsService.grep`, so this tool only maps arguments - * and renders results. A few v1 behaviors that `IFsService.grep` does not + * that work now lives in `ISessionFsService.grep`, so this tool only maps arguments + * and renders results. A few v1 behaviors that `ISessionFsService.grep` does not * expose (mtime ordering of `files_with_matches`, multiline matching, and * searching a path outside the workspace) are intentionally not replicated. */ @@ -27,7 +27,7 @@ import type { FsGrepMatch, FsGrepRequest, FsGrepResponse } from '@moonshot-ai/protocol'; import { z } from 'zod'; -import { IFsService } from '#/agentFs'; +import { ISessionFsService } from '#/agentFs'; import { ErrorCodes, isKimiError } from '#/errors'; import { IKaos } from '#/kaos'; import { ToolAccesses } from '#/tool'; @@ -147,7 +147,7 @@ export class GrepTool implements BuiltinTool { readonly description = GREP_DESCRIPTION; readonly parameters: Record = toInputJsonSchema(GrepInputSchema); constructor( - private readonly fs: IFsService, + private readonly fs: ISessionFsService, private readonly kaos: IKaos, private readonly workspace: WorkspaceConfig, ) {} @@ -265,7 +265,7 @@ function renderGrepResponse(args: GrepInput, response: FsGrepResponse): Executab const mode: GrepMode = args.output_mode ?? 'files_with_matches'; // Post-filter sensitive files, mirroring v1's post-rg sensitive filter. - // `IFsService.grep` searches the whole workspace and does not exclude + // `ISessionFsService.grep` searches the whole workspace and does not exclude // sensitive paths, so the tool drops them before rendering. const filteredSensitive: string[] = []; const keptFiles = response.files.filter((file) => { diff --git a/packages/agent-core-v2/src/fileTools/tools/read.ts b/packages/agent-core-v2/src/fileTools/tools/read.ts index 772ea418e..c9e59f150 100644 --- a/packages/agent-core-v2/src/fileTools/tools/read.ts +++ b/packages/agent-core-v2/src/fileTools/tools/read.ts @@ -18,12 +18,12 @@ * * Ported from v1 (`packages/agent-core/src/tools/builtin/file/read.ts`). The * optional `scanTextFile` / `readLineRange` / `readTailLines` fast-paths are - * intentionally dropped: `IAgentFileSystem` streams through `readLines` only. + * intentionally dropped: `ISessionAgentFileSystem` streams through `readLines` only. */ import { z } from 'zod'; -import { IAgentFileSystem } from '#/agentFs'; +import { ISessionAgentFileSystem } from '#/agentFs'; import { IKaos } from '#/kaos'; import { ToolAccesses } from '#/tool'; import type { BuiltinTool, ExecutableToolResult, ToolExecution } from '#/tool'; @@ -223,7 +223,7 @@ export class ReadTool implements BuiltinTool { readonly description = READ_DESCRIPTION; readonly parameters: Record = toInputJsonSchema(ReadInputSchema); constructor( - private readonly fs: IAgentFileSystem, + private readonly fs: ISessionAgentFileSystem, private readonly kaos: IKaos, private readonly workspace: WorkspaceConfig, ) {} @@ -251,7 +251,7 @@ export class ReadTool implements BuiltinTool { private async execution(args: ReadInput, safePath: string): Promise { try { - let stat: Awaited>; + let stat: Awaited>; try { stat = await this.fs.stat(safePath); } catch (error) { diff --git a/packages/agent-core-v2/src/fileTools/tools/write.ts b/packages/agent-core-v2/src/fileTools/tools/write.ts index c101acda6..10d1b5e91 100644 --- a/packages/agent-core-v2/src/fileTools/tools/write.ts +++ b/packages/agent-core-v2/src/fileTools/tools/write.ts @@ -6,7 +6,7 @@ * (mirroring `mkdir(parents=True, exist_ok=True)`). Path access policy is * resolved before any filesystem I/O. * - * v2's `IAgentFileSystem.writeText` has no mode flag: overwrite maps to a + * v2's `ISessionAgentFileSystem.writeText` has no mode flag: overwrite maps to a * direct write, while append reads the existing content first (treating a * missing file as empty) and writes the concatenation back. * @@ -19,7 +19,7 @@ import { dirname } from 'pathe'; import { z } from 'zod'; -import type { AgentFileStat, IAgentFileSystem } from '#/agentFs'; +import type { AgentFileStat, ISessionAgentFileSystem } from '#/agentFs'; import { IKaos } from '#/kaos'; import { ToolAccesses } from '#/tool'; import type { BuiltinTool, ExecutableToolResult, ToolExecution } from '#/tool'; @@ -62,7 +62,7 @@ export class WriteTool implements BuiltinTool { readonly parameters: Record = toInputJsonSchema(WriteInputSchema); constructor( - private readonly fs: IAgentFileSystem, + private readonly fs: ISessionAgentFileSystem, private readonly kaos: IKaos, private readonly workspace: WorkspaceConfig, ) {} diff --git a/packages/agent-core-v2/src/filestore/fileStoreService.ts b/packages/agent-core-v2/src/filestore/fileStoreService.ts index f3f86c651..31e793519 100644 --- a/packages/agent-core-v2/src/filestore/fileStoreService.ts +++ b/packages/agent-core-v2/src/filestore/fileStoreService.ts @@ -5,7 +5,7 @@ * keeps a JSON `FileMeta` index in the same backend under the `filestore` * scope. Enforces the 50 MiB upload cap while collecting the stream, prunes the * index when a referenced blob is missing, and hands downloads back as a lazy - * `Readable` over `readStream`. Bound at Core scope. + * `Readable` over `readStream`. Bound at App scope. */ import { randomUUID } from 'node:crypto'; @@ -165,7 +165,7 @@ export class FileStoreService implements IFileStore { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IFileStore, FileStoreService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/filestore/filestore.ts b/packages/agent-core-v2/src/filestore/filestore.ts index da62f1895..66997cb8b 100644 --- a/packages/agent-core-v2/src/filestore/filestore.ts +++ b/packages/agent-core-v2/src/filestore/filestore.ts @@ -5,7 +5,7 @@ * uploaded bytes in the `IBlobStorage` backend and their `FileMeta` index in the * same byte store, then hands callers a stream back on download. The v1 * `IFileStore` returned a filesystem `blobPath`; here the byte-store substrate - * is stream-oriented, so `get` yields a `Readable` instead. Bound at Core scope. + * is stream-oriented, so `get` yields a `Readable` instead. Bound at App scope. */ import type { Readable } from 'node:stream'; diff --git a/packages/agent-core-v2/src/filestore/index.ts b/packages/agent-core-v2/src/filestore/index.ts index 568764f29..af0138693 100644 --- a/packages/agent-core-v2/src/filestore/index.ts +++ b/packages/agent-core-v2/src/filestore/index.ts @@ -1,6 +1,6 @@ /** * `filestore` domain barrel — re-exports the file-store contract, its errors, - * and the Core-scoped implementation. Importing this barrel registers the + * and the App-scoped implementation. Importing this barrel registers the * `IFileStore` binding and the file error codes into the scope/error registries. */ diff --git a/packages/agent-core-v2/src/flag/flag.ts b/packages/agent-core-v2/src/flag/flag.ts index a04a38acf..cc6a26a4f 100644 --- a/packages/agent-core-v2/src/flag/flag.ts +++ b/packages/agent-core-v2/src/flag/flag.ts @@ -6,7 +6,7 @@ * flag-resolution types (`ExperimentalFeatureState`, `ExperimentalFlagConfig`, * `ExperimentalFlagSource`). Owns the `[experimental]` config section, whose * keys are flag ids and are preserved verbatim (no snake ↔ camel conversion) by - * its TOML read/write transforms. Core-scoped — one instance shared across the + * its TOML read/write transforms. App-scoped — one instance shared across the * process. */ diff --git a/packages/agent-core-v2/src/flag/flagRegistry.ts b/packages/agent-core-v2/src/flag/flagRegistry.ts index 8b706c35e..5991184ed 100644 --- a/packages/agent-core-v2/src/flag/flagRegistry.ts +++ b/packages/agent-core-v2/src/flag/flagRegistry.ts @@ -5,7 +5,7 @@ * definitions from. Definitions are contributed **decentrally**: each domain * calls `registerFlagDefinition` from its own `Flag.ts` top level, and * `FlagRegistryService` drains those contributions when it is instantiated. - * There is no central catalog to edit by hand. Core-scoped. + * There is no central catalog to edit by hand. App-scoped. */ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; diff --git a/packages/agent-core-v2/src/flag/flagRegistryService.ts b/packages/agent-core-v2/src/flag/flagRegistryService.ts index eca7d8613..923ed87b6 100644 --- a/packages/agent-core-v2/src/flag/flagRegistryService.ts +++ b/packages/agent-core-v2/src/flag/flagRegistryService.ts @@ -3,7 +3,7 @@ * * In-memory catalog of flag definitions. Seeds itself from the import-time * contributions (`getContributedFlags`) on construction, and also accepts - * runtime `register` calls (used by tests). Bound at Core scope. + * runtime `register` calls (used by tests). Bound at App scope. */ import { InstantiationType } from '#/_base/di/extensions'; @@ -54,7 +54,7 @@ export class FlagRegistryService extends Disposable implements IFlagRegistry { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IFlagRegistry, FlagRegistryService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/flag/flagService.ts b/packages/agent-core-v2/src/flag/flagService.ts index bd1ce61d1..6fe997acb 100644 --- a/packages/agent-core-v2/src/flag/flagService.ts +++ b/packages/agent-core-v2/src/flag/flagService.ts @@ -3,7 +3,7 @@ * * Resolves experimental flags from the environment (read through `bootstrap`), * the `[experimental]` config section, and defaults; reads flag definitions - * from `flagRegistry`, and reads/watches config through `config`. Bound at Core + * from `flagRegistry`, and reads/watches config through `config`. Bound at App * scope. */ @@ -122,7 +122,7 @@ export class FlagService extends Disposable implements IFlagService { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IFlagService, FlagService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/fullCompaction/fullCompaction.ts b/packages/agent-core-v2/src/fullCompaction/fullCompaction.ts index bd5f8e396..d958ce0d9 100644 --- a/packages/agent-core-v2/src/fullCompaction/fullCompaction.ts +++ b/packages/agent-core-v2/src/fullCompaction/fullCompaction.ts @@ -13,7 +13,7 @@ export interface CompactInput { readonly signal?: AbortSignal; } -export interface IFullCompaction { +export interface IAgentFullCompactionService { readonly _serviceBrand: undefined; readonly isCompacting: boolean; @@ -21,4 +21,4 @@ export interface IFullCompaction { cancel(): void; } -export const IFullCompaction = createDecorator('agentFullCompactionService'); +export const IAgentFullCompactionService = createDecorator('agentFullCompactionService'); diff --git a/packages/agent-core-v2/src/fullCompaction/fullCompactionService.ts b/packages/agent-core-v2/src/fullCompaction/fullCompactionService.ts index e177b933b..89e26a12d 100644 --- a/packages/agent-core-v2/src/fullCompaction/fullCompactionService.ts +++ b/packages/agent-core-v2/src/fullCompaction/fullCompactionService.ts @@ -15,21 +15,21 @@ import { import { ErrorCodes, KimiError, isKimiError, toKimiErrorPayload } from "#/errors"; import { renderPrompt } from "#/_base/utils/render-prompt"; import { estimateTokens, estimateTokensForMessages } from "#/_base/utils/tokens"; -import { IContextMemory } from '#/contextMemory'; -import { IContextProjector } from '#/contextProjector'; -import { IContextSizeService } from '#/contextSize'; -import { IEventSink } from '../eventSink'; -import { IExternalHooksService } from '#/externalHooks'; -import { ILLMRequester, type LLMEvent } from '#/llmRequester'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentContextProjectorService } from '#/contextProjector'; +import { IAgentContextSizeService } from '#/contextSize'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentExternalHooksService } from '#/externalHooks'; +import { IAgentLLMRequesterService, type LLMEvent } from '#/llmRequester'; import { isAbortError } from '#/loop/errors'; import { retryBackoffDelays, sleepForRetry } from '#/loop/retry'; -import { IProfileService } from '#/profile'; -import { IReplayBuilderService } from '#/replayBuilder'; +import { IAgentProfileService } from '#/profile'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; import { ITelemetryService } from '#/telemetry'; -import { IToolStoreService } from '#/toolStore'; -import { ITurnService, type TurnContextOverflowContext } from '#/turn'; +import { IAgentToolStoreService } from '#/toolStore'; +import { IAgentTurnService, type TurnContextOverflowContext } from '#/turn'; import type { ContextMessage } from '#/contextMemory'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { TODO_STORE_KEY, renderTodoList, @@ -37,7 +37,7 @@ import { } from '#/todoList/tools/todo-list'; import compactionInstructionTemplate from './compaction-instruction.md?raw'; import { - IFullCompaction, + IAgentFullCompactionService, type CompactInput, type FullCompactionCompleteData, } from './fullCompaction'; @@ -88,7 +88,7 @@ class CompactionTruncatedError extends Error { } } -export class FullCompactionService extends Disposable implements IFullCompaction { +export class AgentFullCompactionService extends Disposable implements IAgentFullCompactionService { declare readonly _serviceBrand: undefined; private readonly strategy: CompactionStrategy; private compactionCountInTurn = 0; @@ -96,18 +96,18 @@ export class FullCompactionService extends Disposable implements IFullCompaction constructor( private readonly options: FullCompactionServiceOptions = {}, - @IContextMemory private readonly context: IContextMemory, - @IContextProjector private readonly projector: IContextProjector, - @IContextSizeService private readonly contextSize: IContextSizeService, - @ILLMRequester private readonly llmRequester: ILLMRequester, - @IProfileService private readonly profile: IProfileService, - @IToolStoreService private readonly toolStore: IToolStoreService, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentContextProjectorService private readonly projector: IAgentContextProjectorService, + @IAgentContextSizeService private readonly contextSize: IAgentContextSizeService, + @IAgentLLMRequesterService private readonly llmRequester: IAgentLLMRequesterService, + @IAgentProfileService private readonly profile: IAgentProfileService, + @IAgentToolStoreService private readonly toolStore: IAgentToolStoreService, @ITelemetryService private readonly telemetry: ITelemetryService, - @IWireRecord private readonly wireRecord: IWireRecord, - @IEventSink private readonly events: IEventSink, - @IReplayBuilderService private readonly replayBuilder: IReplayBuilderService, - @IExternalHooksService private readonly externalHooks: IExternalHooksService, - @ITurnService turnService: ITurnService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentReplayBuilderService private readonly replayBuilder: IAgentReplayBuilderService, + @IAgentExternalHooksService private readonly externalHooks: IAgentExternalHooksService, + @IAgentTurnService turnService: IAgentTurnService, ) { super(); this.strategy = @@ -579,17 +579,17 @@ function isTodoItem(value: unknown): value is TodoItem { ); } -export { FullCompactionService as FullCompaction }; +export { AgentFullCompactionService as FullCompaction }; // Construct eagerly (not delayed): the service registers turn-lifecycle hooks // (onLaunched / beforeStep / afterStep) in its constructor that drive auto -// compaction. With delayed instantiation the eager `accessor.get(IFullCompaction)` +// compaction. With delayed instantiation the eager `accessor.get(IAgentFullCompactionService)` // only realizes a proxy, so the hooks would not register until the first RPC — // after turns have already run without the auto-compaction gate. registerScopedService( LifecycleScope.Agent, - IFullCompaction, - FullCompactionService, + IAgentFullCompactionService, + AgentFullCompactionService, InstantiationType.Eager, 'fullCompaction', ); diff --git a/packages/agent-core-v2/src/gateway/gateway.ts b/packages/agent-core-v2/src/gateway/gateway.ts index d540c0275..9cd90eb81 100644 --- a/packages/agent-core-v2/src/gateway/gateway.ts +++ b/packages/agent-core-v2/src/gateway/gateway.ts @@ -4,7 +4,7 @@ * Defines the public contracts of the gateway layer: the `IRestGateway` / * `IWSGateway` / `IWSBroadcastService` entry points. Session scope creation is * owned by `session-lifecycle`; the gateway resolves sessions through it. - * Core-scoped — shared across the application. + * App-scoped — shared across the application. */ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; diff --git a/packages/agent-core-v2/src/gateway/gatewayService.ts b/packages/agent-core-v2/src/gateway/gatewayService.ts index 3446c6d0a..b9ccb2437 100644 --- a/packages/agent-core-v2/src/gateway/gatewayService.ts +++ b/packages/agent-core-v2/src/gateway/gatewayService.ts @@ -4,7 +4,7 @@ * * Owns the REST/WS entry points; resolves sessions through `session-lifecycle`, * agents through `agent-lifecycle`, drives turns through `turn`, flushes logs - * through `log`, and subscribes to broadcasts through `event`. Bound at Core + * through `log`, and subscribes to broadcasts through `event`. Bound at App * scope. */ @@ -12,11 +12,11 @@ import { InstantiationType } from '#/_base/di/extensions'; import { type IScopeHandle, LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { Disposable } from '#/_base/di/lifecycle'; import { IAgentLifecycleService } from '#/agent-lifecycle/agentLifecycle'; -import { IEventSink } from '#/eventSink'; +import { IAgentEventSinkService } from '#/eventSink'; import { ILogService, ISessionLogService } from '#/log'; -import { IPromptService } from '#/prompt'; +import { IAgentPromptService } from '#/prompt'; import { ISessionLifecycleService } from '#/session-lifecycle'; -import { ITurnService } from '#/turn'; +import { IAgentTurnService } from '#/turn'; import { IRestGateway, IWSBroadcastService, IWSGateway } from './gateway'; @@ -42,7 +42,7 @@ export class RestGateway implements IRestGateway { agentId: string, input: string, ): Promise<{ readonly turn_id: number } | undefined> { - const turn = this.agent(sessionId, agentId).accessor.get(IPromptService).prompt({ + const turn = this.agent(sessionId, agentId).accessor.get(IAgentPromptService).prompt({ role: 'user', content: [{ type: 'text', text: input }], toolCalls: [], @@ -56,17 +56,17 @@ export class RestGateway implements IRestGateway { content: string, ): Promise<{ readonly turn_id: number } | undefined> { const agent = this.agent(sessionId, agentId); - const turn = agent.accessor.get(IPromptService).steer({ + const turn = agent.accessor.get(IAgentPromptService).steer({ role: 'user', content: [{ type: 'text', text: content }], toolCalls: [], origin: { kind: 'user' }, }); - const id = turn?.id ?? agent.accessor.get(ITurnService).getActiveTurn()?.id; + const id = turn?.id ?? agent.accessor.get(IAgentTurnService).getActiveTurn()?.id; return Promise.resolve(id === undefined ? undefined : { turn_id: id }); } cancel(sessionId: string, agentId: string, reason?: string): Promise { - const activeTurn = this.agent(sessionId, agentId).accessor.get(ITurnService).getActiveTurn(); + const activeTurn = this.agent(sessionId, agentId).accessor.get(IAgentTurnService).getActiveTurn(); activeTurn?.abortController.abort(reason); return Promise.resolve(); } @@ -91,7 +91,7 @@ export class WSGateway implements IWSGateway { constructor( @ISessionLifecycleService _sessions: ISessionLifecycleService, - @IEventSink _event: IEventSink, + @IAgentEventSinkService _event: IAgentEventSinkService, ) {} connect(connectionId: string): void { @@ -104,7 +104,7 @@ export class WSGateway implements IWSGateway { export class WSBroadcastService extends Disposable implements IWSBroadcastService { declare readonly _serviceBrand: undefined; - constructor(@IEventSink event: IEventSink) { + constructor(@IAgentEventSinkService event: IAgentEventSinkService) { super(); this._register( event.on(() => { @@ -113,6 +113,6 @@ export class WSBroadcastService extends Disposable implements IWSBroadcastServic } } -registerScopedService(LifecycleScope.Core, IRestGateway, RestGateway, InstantiationType.Delayed, 'gateway'); -registerScopedService(LifecycleScope.Core, IWSGateway, WSGateway, InstantiationType.Delayed, 'gateway'); -registerScopedService(LifecycleScope.Core, IWSBroadcastService, WSBroadcastService, InstantiationType.Delayed, 'gateway'); +registerScopedService(LifecycleScope.App, IRestGateway, RestGateway, InstantiationType.Delayed, 'gateway'); +registerScopedService(LifecycleScope.App, IWSGateway, WSGateway, InstantiationType.Delayed, 'gateway'); +registerScopedService(LifecycleScope.App, IWSBroadcastService, WSBroadcastService, InstantiationType.Delayed, 'gateway'); diff --git a/packages/agent-core-v2/src/goal/goal.ts b/packages/agent-core-v2/src/goal/goal.ts index e28fcd8ec..7fe24a13e 100644 --- a/packages/agent-core-v2/src/goal/goal.ts +++ b/packages/agent-core-v2/src/goal/goal.ts @@ -11,7 +11,7 @@ export interface GoalReasonInput { readonly reason?: string; } -export interface IGoalService { +export interface IAgentGoalService { readonly _serviceBrand: undefined; getGoal(): GoalToolResult; createGoal(input: CreateGoalInput, actor?: GoalActor): Promise; @@ -26,4 +26,4 @@ export interface IGoalService { markBlocked(input?: GoalReasonInput, actor?: GoalActor): Promise; } -export const IGoalService = createDecorator('agentGoalService'); +export const IAgentGoalService = createDecorator('agentGoalService'); diff --git a/packages/agent-core-v2/src/goal/goalService.ts b/packages/agent-core-v2/src/goal/goalService.ts index b55ee5f48..29abdb482 100644 --- a/packages/agent-core-v2/src/goal/goalService.ts +++ b/packages/agent-core-v2/src/goal/goalService.ts @@ -7,18 +7,18 @@ import { Disposable, } from "#/_base/di"; import { ErrorCodes, KimiError } from "#/errors"; -import { IContextInjector } from '../contextInjector'; -import { IEventSink } from '../eventSink'; -import { IPermissionModeService } from '#/permissionMode'; -import { IReplayBuilderService } from '#/replayBuilder'; -import { ISystemReminderService } from '#/systemReminder'; +import { IAgentContextInjectorService } from '../contextInjector'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentPermissionModeService } from '#/permissionMode'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; +import { IAgentSystemReminderService } from '#/systemReminder'; import type { TelemetryProperties } from '#/telemetry'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { WireRecord } from '#/wireRecord'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { - IGoalService, + IAgentGoalService, type GoalReasonInput, } from './goal'; import { @@ -94,21 +94,21 @@ interface GoalState { terminalReason?: string; } -export class GoalService extends Disposable implements IGoalService { +export class AgentGoalService extends Disposable implements IAgentGoalService { declare readonly _serviceBrand: undefined; private state: GoalState | undefined; constructor( private readonly options: GoalServiceOptions = {}, - @IWireRecord private readonly wireRecord: IWireRecord, - @IEventSink private readonly events: IEventSink, - @ISystemReminderService private readonly reminders: ISystemReminderService, - @IReplayBuilderService private readonly replayBuilder: IReplayBuilderService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentSystemReminderService private readonly reminders: IAgentSystemReminderService, + @IAgentReplayBuilderService private readonly replayBuilder: IAgentReplayBuilderService, @ITelemetryService private readonly telemetry: ITelemetryService, - @IContextInjector private readonly dynamicInjector: IContextInjector, - @IToolRegistry toolRegistry: IToolRegistry, - @IPermissionModeService private readonly permissionMode: IPermissionModeService, + @IAgentContextInjectorService private readonly dynamicInjector: IAgentContextInjectorService, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, + @IAgentPermissionModeService private readonly permissionMode: IAgentPermissionModeService, ) { super(); this._register( @@ -595,8 +595,8 @@ function normalizeCompletionCriterion(value: string | undefined): string | undef registerScopedService( LifecycleScope.Agent, - IGoalService, - GoalService, + IAgentGoalService, + AgentGoalService, InstantiationType.Delayed, 'goal', ); diff --git a/packages/agent-core-v2/src/goal/index.ts b/packages/agent-core-v2/src/goal/index.ts index a616a1e87..5ce944034 100644 --- a/packages/agent-core-v2/src/goal/index.ts +++ b/packages/agent-core-v2/src/goal/index.ts @@ -1,6 +1,6 @@ /** * `goal` domain barrel — re-exports the goal contract (`goal`) and its scoped - * service (`goalService`). Importing this barrel registers the `IGoalService` + * service (`goalService`). Importing this barrel registers the `IAgentGoalService` * binding into the scope registry. */ diff --git a/packages/agent-core-v2/src/goal/injection/goalInjection.ts b/packages/agent-core-v2/src/goal/injection/goalInjection.ts index 3bb28ff2b..5f5e9aba9 100644 --- a/packages/agent-core-v2/src/goal/injection/goalInjection.ts +++ b/packages/agent-core-v2/src/goal/injection/goalInjection.ts @@ -1,7 +1,7 @@ import type { GoalSnapshot } from '#/goal'; import { Disposable } from "#/_base/di"; import { renderPrompt } from "#/_base/utils/render-prompt"; -import { IContextInjector } from '../../contextInjector/contextInjector'; +import { IAgentContextInjectorService } from '../../contextInjector/contextInjector'; import GOAL_ACTIVE_REMINDER from './goal-active-reminder.md?raw'; import GOAL_BLOCKED_REMINDER from './goal-blocked-reminder.md?raw'; import GOAL_PAUSED_REMINDER from './goal-paused-reminder.md?raw'; @@ -14,7 +14,7 @@ export interface GoalInjectionOptions { export class GoalInjection extends Disposable { constructor( private readonly options: GoalInjectionOptions, - @IContextInjector dynamicInjector: IContextInjector, + @IAgentContextInjectorService dynamicInjector: IAgentContextInjectorService, ) { super(); this._register(dynamicInjector.register('goal', () => this.reminder(), { cadence: 'turn' })); diff --git a/packages/agent-core-v2/src/goal/tools/create-goal.ts b/packages/agent-core-v2/src/goal/tools/create-goal.ts index 5e352c19f..b4107a724 100644 --- a/packages/agent-core-v2/src/goal/tools/create-goal.ts +++ b/packages/agent-core-v2/src/goal/tools/create-goal.ts @@ -9,10 +9,10 @@ import { z } from 'zod'; import type { ToolInputDisplay } from '@moonshot-ai/protocol'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; -import type { IPermissionModeService } from '#/permissionMode'; +import type { IAgentPermissionModeService } from '#/permissionMode'; import type { BuiltinTool, ToolExecution } from '#/tool'; -import type { IGoalService } from '../goal'; +import type { IAgentGoalService } from '../goal'; import DESCRIPTION from './create-goal.md?raw'; import { goalForModel } from './serialize'; @@ -38,8 +38,8 @@ export class CreateGoalTool implements BuiltinTool { readonly parameters: Record = toInputJsonSchema(CreateGoalToolInputSchema); constructor( - private readonly goal: IGoalService, - private readonly permissionMode: IPermissionModeService, + private readonly goal: IAgentGoalService, + private readonly permissionMode: IAgentPermissionModeService, ) {} resolveExecution(args: CreateGoalToolInput): ToolExecution { diff --git a/packages/agent-core-v2/src/goal/tools/get-goal.ts b/packages/agent-core-v2/src/goal/tools/get-goal.ts index 0d58f6ba4..e4519f0d9 100644 --- a/packages/agent-core-v2/src/goal/tools/get-goal.ts +++ b/packages/agent-core-v2/src/goal/tools/get-goal.ts @@ -9,7 +9,7 @@ import { z } from 'zod'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import type { BuiltinTool, ToolExecution } from '#/tool'; -import type { IGoalService } from '../goal'; +import type { IAgentGoalService } from '../goal'; import DESCRIPTION from './get-goal.md?raw'; import { goalResultForModel } from './serialize'; @@ -21,7 +21,7 @@ export class GetGoalTool implements BuiltinTool { readonly description: string = DESCRIPTION; readonly parameters: Record = toInputJsonSchema(GetGoalToolInputSchema); - constructor(private readonly goal: IGoalService) {} + constructor(private readonly goal: IAgentGoalService) {} resolveExecution(_args: GetGoalToolInput): ToolExecution { return { diff --git a/packages/agent-core-v2/src/goal/tools/set-goal-budget.ts b/packages/agent-core-v2/src/goal/tools/set-goal-budget.ts index ebd85b2e4..e6f004c27 100644 --- a/packages/agent-core-v2/src/goal/tools/set-goal-budget.ts +++ b/packages/agent-core-v2/src/goal/tools/set-goal-budget.ts @@ -9,7 +9,7 @@ import { z } from 'zod'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import type { BuiltinTool, ToolExecution } from '#/tool'; -import type { IGoalService } from '../goal'; +import type { IAgentGoalService } from '../goal'; import type { GoalBudgetLimits } from '../types'; import DESCRIPTION from './set-goal-budget.md?raw'; @@ -33,7 +33,7 @@ export class SetGoalBudgetTool implements BuiltinTool { readonly description: string = DESCRIPTION; readonly parameters: Record = toInputJsonSchema(SetGoalBudgetToolInputSchema); - constructor(private readonly goal: IGoalService) {} + constructor(private readonly goal: IAgentGoalService) {} resolveExecution(args: SetGoalBudgetToolInput): ToolExecution { const normalizedArgs = normalizeBudgetInput(args); diff --git a/packages/agent-core-v2/src/goal/tools/update-goal.ts b/packages/agent-core-v2/src/goal/tools/update-goal.ts index 81bf4c9cf..201971211 100644 --- a/packages/agent-core-v2/src/goal/tools/update-goal.ts +++ b/packages/agent-core-v2/src/goal/tools/update-goal.ts @@ -12,10 +12,10 @@ import { z } from 'zod'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; -import type { ISystemReminderService } from '#/systemReminder'; +import type { IAgentSystemReminderService } from '#/systemReminder'; import type { BuiltinTool, ToolExecution } from '#/tool'; -import type { IGoalService } from '../goal'; +import type { IAgentGoalService } from '../goal'; import { buildGoalBlockedReasonPrompt, buildGoalCompletionSummaryPrompt, @@ -41,8 +41,8 @@ export class UpdateGoalTool implements BuiltinTool { readonly parameters: Record = toInputJsonSchema(UpdateGoalToolInputSchema); constructor( - private readonly goal: IGoalService, - private readonly reminders: ISystemReminderService, + private readonly goal: IAgentGoalService, + private readonly reminders: IAgentSystemReminderService, ) {} resolveExecution(args: UpdateGoalToolInput): ToolExecution { diff --git a/packages/agent-core-v2/src/hostFolderBrowser/hostFolderBrowser.ts b/packages/agent-core-v2/src/hostFolderBrowser/hostFolderBrowser.ts index 11725361c..db2177d9b 100644 --- a/packages/agent-core-v2/src/hostFolderBrowser/hostFolderBrowser.ts +++ b/packages/agent-core-v2/src/hostFolderBrowser/hostFolderBrowser.ts @@ -4,7 +4,7 @@ * Defines the `IHostFolderBrowser` used by the program side (TUI / server) to * let the user browse the real local filesystem when choosing a workspace * folder. Distinct from the Agent-side `agentFs`, which is sandboxed and may - * be remote. Core-scoped. + * be remote. App-scoped. * * The wire shapes (`FsBrowseResponse` / `FsHomeResponse`) are sourced from * `@moonshot-ai/protocol` so the `/api/v1` and `/api/v2` transports share one diff --git a/packages/agent-core-v2/src/hostFolderBrowser/hostFolderBrowserService.ts b/packages/agent-core-v2/src/hostFolderBrowser/hostFolderBrowserService.ts index 0c4e2e5f2..dd1cf471c 100644 --- a/packages/agent-core-v2/src/hostFolderBrowser/hostFolderBrowserService.ts +++ b/packages/agent-core-v2/src/hostFolderBrowser/hostFolderBrowserService.ts @@ -2,7 +2,7 @@ * `hostFolderBrowser` domain (L2) — `IHostFolderBrowser` implementation. * * Browses the real local filesystem through `node:fs/promises` and derives - * `recent_roots` from the process-wide `IWorkspaceRegistry`. Bound at Core + * `recent_roots` from the process-wide `IWorkspaceRegistry`. Bound at App * scope. Mirrors the v1 `WorkspaceFsService` behaviour so the `/api/v1` * transport stays wire-compatible: realpath resolution, directory-only * entries, git metadata, dot-last sorting, and `parent` resolution. @@ -148,7 +148,7 @@ async function detectGit(root: string): Promise { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IHostFolderBrowser, HostFolderBrowser, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/hostFs/hostFs.ts b/packages/agent-core-v2/src/hostFs/hostFs.ts index fd1de31d8..8360926be 100644 --- a/packages/agent-core-v2/src/hostFs/hostFs.ts +++ b/packages/agent-core-v2/src/hostFs/hostFs.ts @@ -3,7 +3,7 @@ * * Defines the `IHostFileSystem` used by the program side (persistence, skill * loading, workspace registry) to read and write the app's own files on the - * real local disk, plus the stat/entry models. Core-scoped — one shared + * real local disk, plus the stat/entry models. App-scoped — one shared * instance. The Agent side never injects this directly; its local backend * reuses it internally. */ diff --git a/packages/agent-core-v2/src/hostFs/hostFsService.ts b/packages/agent-core-v2/src/hostFs/hostFsService.ts index 87d89c8a5..689ed8a17 100644 --- a/packages/agent-core-v2/src/hostFs/hostFsService.ts +++ b/packages/agent-core-v2/src/hostFs/hostFsService.ts @@ -2,7 +2,7 @@ * `hostFs` domain (L1) — `IHostFileSystem` implementation. * * Reads and writes the app's own files on the real local disk through - * `node:fs/promises`. Bound at Core scope. + * `node:fs/promises`. Bound at App scope. */ import { open, readFile, readdir, stat, mkdir, rm, writeFile } from 'node:fs/promises'; @@ -72,7 +72,7 @@ export class HostFileSystem implements IHostFileSystem { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IHostFileSystem, HostFileSystem, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/index.ts b/packages/agent-core-v2/src/index.ts index 5b4899277..82fde87eb 100644 --- a/packages/agent-core-v2/src/index.ts +++ b/packages/agent-core-v2/src/index.ts @@ -22,7 +22,7 @@ export * from './modelCatalog/index'; export * from './modelRuntime/index'; import './skill/index'; -export { IAgentSkillService, ISkillCatalog } from './skill/index'; +export { IAgentSkillService, ISessionSkillCatalog } from './skill/index'; export * from './permissionGate/index'; import './flag/index'; export * from './flag/index'; @@ -47,7 +47,7 @@ export * from './session/index'; export * from './eventSink/index'; import './approval/index'; -export { IApprovalService } from './approval/index'; +export { ISessionApprovalService } from './approval/index'; export * from './question/index'; export * from './gateway/index'; @@ -92,7 +92,7 @@ export * from './todoList/index'; export * from './tool/index'; export * from './toolExecutor/index'; import './toolRegistry/index'; -export { IToolRegistry } from './toolRegistry/index'; +export { IAgentToolRegistryService } from './toolRegistry/index'; export * from './toolStore/index'; export * from './userTool/index'; export * from './wireRecord/index'; diff --git a/packages/agent-core-v2/src/interaction/index.ts b/packages/agent-core-v2/src/interaction/index.ts index fd38329d3..60d64a2ac 100644 --- a/packages/agent-core-v2/src/interaction/index.ts +++ b/packages/agent-core-v2/src/interaction/index.ts @@ -1,7 +1,7 @@ /** * `interaction` domain barrel — re-exports the interaction contract * (`interaction`) and its scoped service (`interactionService`). Importing this - * barrel registers the `IInteractionService` binding into the scope registry. + * barrel registers the `ISessionInteractionService` binding into the scope registry. */ export * from './interaction'; diff --git a/packages/agent-core-v2/src/interaction/interaction.ts b/packages/agent-core-v2/src/interaction/interaction.ts index 5f403cffd..83f52a780 100644 --- a/packages/agent-core-v2/src/interaction/interaction.ts +++ b/packages/agent-core-v2/src/interaction/interaction.ts @@ -1,7 +1,7 @@ /** * `interaction` domain (L6) — blocking human-in-the-loop request kernel. * - * Defines the `Interaction` model and the `IInteractionService` kernel that + * Defines the `Interaction` model and the `ISessionInteractionService` kernel that * owns the session's pending interaction set: a unified, blocking request / * response primitive (`request` → `respond`) with change notification * (`onDidChange`), a non-blocking enqueue (`enqueue`) for callers that observe @@ -37,13 +37,13 @@ export interface Interaction { readonly createdAt: number; } -/** Emitted by {@link IInteractionService.onDidResolve} when a request is responded to. */ +/** Emitted by {@link ISessionInteractionService.onDidResolve} when a request is responded to. */ export interface InteractionResolution { readonly id: string; readonly response: unknown; } -export interface IInteractionService { +export interface ISessionInteractionService { readonly _serviceBrand: undefined; request(req: InteractionRequest): Promise; /** @@ -58,7 +58,7 @@ export interface IInteractionService { /** * Whether `id` was responded to within the recent-resolution window. Lets * edge callers distinguish a duplicate resolve (idempotent conflict) from an - * unknown id. The window is bounded (see {@link InteractionService}) and + * unknown id. The window is bounded (see {@link SessionInteractionService}) and * exists purely for idempotency signaling. */ isRecentlyResolved(id: string): boolean; @@ -67,5 +67,5 @@ export interface IInteractionService { readonly onDidResolve: Event; } -export const IInteractionService: ServiceIdentifier = - createDecorator('interactionService'); +export const ISessionInteractionService: ServiceIdentifier = + createDecorator('sessionInteractionService'); diff --git a/packages/agent-core-v2/src/interaction/interactionService.ts b/packages/agent-core-v2/src/interaction/interactionService.ts index 24e33ebd6..84073fb84 100644 --- a/packages/agent-core-v2/src/interaction/interactionService.ts +++ b/packages/agent-core-v2/src/interaction/interactionService.ts @@ -1,5 +1,5 @@ /** - * `interaction` domain (L6) — `IInteractionService` implementation. + * `interaction` domain (L6) — `ISessionInteractionService` implementation. * * Owns the pending interaction set and resolves requests when a response * arrives; announces add/remove through a typed `onDidChange`. Bound at @@ -17,7 +17,7 @@ import { type InteractionOrigin, type InteractionRequest, type InteractionResolution, - IInteractionService, + ISessionInteractionService, } from './interaction'; interface Pending { @@ -30,7 +30,7 @@ const RECENTLY_RESOLVED_TTL_MS = 60_000; /** Upper bound on the resolved-ledger size; oldest entries are swept first. */ const RECENTLY_RESOLVED_MAX = 256; -export class InteractionService extends Disposable implements IInteractionService { +export class SessionInteractionService extends Disposable implements ISessionInteractionService { declare readonly _serviceBrand: undefined; private readonly pending = new Map(); @@ -116,8 +116,8 @@ export class InteractionService extends Disposable implements IInteractionServic registerScopedService( LifecycleScope.Session, - IInteractionService, - InteractionService, + ISessionInteractionService, + SessionInteractionService, InstantiationType.Delayed, 'interaction', ); diff --git a/packages/agent-core-v2/src/kaos/kaos.ts b/packages/agent-core-v2/src/kaos/kaos.ts index 5820ab99a..d81aa6d83 100644 --- a/packages/agent-core-v2/src/kaos/kaos.ts +++ b/packages/agent-core-v2/src/kaos/kaos.ts @@ -3,13 +3,13 @@ * * Defines `IKaos`, the Agent's execution environment (cwd, env layers, the * OS/shell probe, and the backend handle the fs/process domains delegate to), - * plus `IKaosFactory`, the Core factory that builds an `IKaos` for a session + * plus `IKaosFactory`, the App factory that builds an `IKaos` for a session * (local today; ssh/container behind the same factory later). * * Temporary: this domain wraps the `@moonshot-ai/kaos` package and re-exports * a few of its data types so business code imports them from `#/kaos` instead * of the package. `IKaos` is seeded into each Session scope by the composition - * root; `IKaosFactory` is bound at Core scope. + * root; `IKaosFactory` is bound at App scope. */ import type { Environment, Kaos } from '@moonshot-ai/kaos'; @@ -32,8 +32,8 @@ export interface IKaos { readonly osEnv: Environment; /** * The backend fs/process domains delegate to. Temporary — owned by this - * environment; business code should reach for `IAgentFileSystem` / - * `IProcessRunner` instead of touching this directly. + * environment; business code should reach for `ISessionAgentFileSystem` / + * `ISessionProcessRunner` instead of touching this directly. */ readonly backend: Kaos; diff --git a/packages/agent-core-v2/src/kaos/kaosFactoryService.ts b/packages/agent-core-v2/src/kaos/kaosFactoryService.ts index 257fe7aab..e0d70cb16 100644 --- a/packages/agent-core-v2/src/kaos/kaosFactoryService.ts +++ b/packages/agent-core-v2/src/kaos/kaosFactoryService.ts @@ -2,7 +2,7 @@ * `kaos` domain (L1) — `IKaosFactory` implementation. * * Builds an `IKaos` for a session. Today only local (`LocalKaos`); ssh/container - * are added behind the same factory later. Bound at Core scope. + * are added behind the same factory later. Bound at App scope. */ import { LocalKaos } from '@moonshot-ai/kaos'; @@ -23,7 +23,7 @@ export class KaosFactory implements IKaosFactory { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IKaosFactory, KaosFactory, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/llmRequestLog/llmRequestLog.ts b/packages/agent-core-v2/src/llmRequestLog/llmRequestLog.ts index 085178d52..f64477e96 100644 --- a/packages/agent-core-v2/src/llmRequestLog/llmRequestLog.ts +++ b/packages/agent-core-v2/src/llmRequestLog/llmRequestLog.ts @@ -12,11 +12,11 @@ export interface LLMRequestLogInput { readonly fields?: LLMRequestLogFields; } -export interface ILLMRequestLogService { +export interface IAgentLLMRequestLogService { readonly _serviceBrand: undefined; logRequest(input: LLMRequestLogInput): void; } -export const ILLMRequestLogService = - createDecorator('agentLLMRequestLogService'); +export const IAgentLLMRequestLogService = + createDecorator('agentLLMRequestLogService'); diff --git a/packages/agent-core-v2/src/llmRequestLog/llmRequestLogService.ts b/packages/agent-core-v2/src/llmRequestLog/llmRequestLogService.ts index 7285acb2d..d47099226 100644 --- a/packages/agent-core-v2/src/llmRequestLog/llmRequestLogService.ts +++ b/packages/agent-core-v2/src/llmRequestLog/llmRequestLogService.ts @@ -7,11 +7,11 @@ import type { Tool } from '@moonshot-ai/kosong'; import { ILogService } from "#/log/log"; import { - ILLMRequestLogService, + IAgentLLMRequestLogService, type LLMRequestLogInput, } from './llmRequestLog'; -export class LLMRequestLogService implements ILLMRequestLogService { +export class AgentLLMRequestLogService implements IAgentLLMRequestLogService { readonly _serviceBrand: undefined; private lastConfigLogSignature: string | undefined; @@ -61,8 +61,8 @@ function fingerprint(content: string): string { registerScopedService( LifecycleScope.Agent, - ILLMRequestLogService, - LLMRequestLogService, + IAgentLLMRequestLogService, + AgentLLMRequestLogService, InstantiationType.Delayed, 'llmRequestLog', ); diff --git a/packages/agent-core-v2/src/llmRequester/llmRequester.ts b/packages/agent-core-v2/src/llmRequester/llmRequester.ts index deaaba42a..17c1813f1 100644 --- a/packages/agent-core-v2/src/llmRequester/llmRequester.ts +++ b/packages/agent-core-v2/src/llmRequester/llmRequester.ts @@ -27,9 +27,9 @@ export type LLMEvent = readonly streamDurationMs: number; }; -export interface ILLMRequester { +export interface IAgentLLMRequesterService { readonly _serviceBrand: undefined; request(overrides?: LLMRequestOverrides, signal?: AbortSignal): AsyncIterable; } -export const ILLMRequester = createDecorator('agentLLMRequesterService'); +export const IAgentLLMRequesterService = createDecorator('agentLLMRequesterService'); diff --git a/packages/agent-core-v2/src/llmRequester/llmRequesterService.ts b/packages/agent-core-v2/src/llmRequester/llmRequesterService.ts index 893bfe49b..a496eff27 100644 --- a/packages/agent-core-v2/src/llmRequester/llmRequesterService.ts +++ b/packages/agent-core-v2/src/llmRequester/llmRequesterService.ts @@ -1,9 +1,9 @@ /** - * `llmRequester` domain (L3) — `ILLMRequester` implementation. + * `llmRequester` domain (L3) — `IAgentLLMRequesterService` implementation. * * Assembles one LLM request from `profile` (provider / system prompt), * `contextMemory` + `contextProjector` (history), and `toolRegistry` (tools), - * resolves request authorization through `modelRuntime` `IModelResolver`, drives + * resolves request authorization through `modelRuntime` `ISessionModelResolver`, drives * `@moonshot-ai/kosong` `generate()`, and logs each request through * `llmRequestLog`. Bound at Agent scope. */ @@ -20,39 +20,39 @@ import { import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IModelResolver } from '#/modelRuntime'; +import { ISessionModelResolver } from '#/modelRuntime'; import { applyCompletionBudget, resolveCompletionBudget, } from "#/_base/utils/completion-budget"; import { IConfigService } from '#/config'; import type { KimiModelOverrides } from '#/chatProvider'; -import { IProfileService } from '#/profile'; -import { IContextMemory } from '#/contextMemory'; -import { IContextProjector } from '#/contextProjector'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentProfileService } from '#/profile'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentContextProjectorService } from '#/contextProjector'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { LLMEvent, LLMRequestOverrides } from '.'; -import { ILLMRequestLogService } from '#/llmRequestLog'; -import { IUsageService } from '#/usage'; +import { IAgentLLMRequestLogService } from '#/llmRequestLog'; +import { IAgentUsageService } from '#/usage'; import { AsyncEventQueue } from './asyncEventQueue'; -import { ILLMRequester } from './llmRequester'; +import { IAgentLLMRequesterService } from './llmRequester'; const EMPTY_TOOL_PARAMETERS: Record = { type: 'object', properties: {}, }; -export class LLMRequesterService implements ILLMRequester { +export class AgentLLMRequesterService implements IAgentLLMRequesterService { declare readonly _serviceBrand: undefined; constructor( - @IContextMemory private readonly context: IContextMemory, - @IContextProjector private readonly projector: IContextProjector, - @IToolRegistry private readonly tools: IToolRegistry, - @IProfileService private readonly profile: IProfileService, - @ILLMRequestLogService private readonly requestLog: ILLMRequestLogService, - @IUsageService private readonly usage: IUsageService, - @IModelResolver private readonly modelResolver: IModelResolver, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentContextProjectorService private readonly projector: IAgentContextProjectorService, + @IAgentToolRegistryService private readonly tools: IAgentToolRegistryService, + @IAgentProfileService private readonly profile: IAgentProfileService, + @IAgentLLMRequestLogService private readonly requestLog: IAgentLLMRequestLogService, + @IAgentUsageService private readonly usage: IAgentUsageService, + @ISessionModelResolver private readonly modelResolver: ISessionModelResolver, @IConfigService private readonly config: IConfigService, ) {} @@ -219,8 +219,8 @@ interface ResolvedLLMRequest { registerScopedService( LifecycleScope.Agent, - ILLMRequester, - LLMRequesterService, + IAgentLLMRequesterService, + AgentLLMRequesterService, InstantiationType.Delayed, 'llmRequester', ); diff --git a/packages/agent-core-v2/src/log/index.ts b/packages/agent-core-v2/src/log/index.ts index a9e5b8ac1..b423fed04 100644 --- a/packages/agent-core-v2/src/log/index.ts +++ b/packages/agent-core-v2/src/log/index.ts @@ -1,7 +1,7 @@ /** * `log` domain barrel — re-exports the logging contract and its scoped * services. Importing this barrel registers the `ILogService` / `ILogWriterService` - * (Core) and `ISessionLogService` (Session) bindings into the scope registry. + * (App) and `ISessionLogService` (Session) bindings into the scope registry. */ export * from './log'; diff --git a/packages/agent-core-v2/src/log/log.ts b/packages/agent-core-v2/src/log/log.ts index bdb11f94c..9a6dd2fb4 100644 --- a/packages/agent-core-v2/src/log/log.ts +++ b/packages/agent-core-v2/src/log/log.ts @@ -4,7 +4,7 @@ * Defines the public contract of logging: the `LogEntry` / `LogLevel` model, * the `ILogger` / `ILogService` used by other domains to emit leveled entries, * the `ILogWriterService` they are written to, and the per-session `ISessionLogService` - * that owns a session-scoped sink. `ILogService` is Core-scoped; + * that owns a session-scoped sink. `ILogService` is App-scoped; * `ISessionLogService` is Session-scoped. */ diff --git a/packages/agent-core-v2/src/log/logConfig.ts b/packages/agent-core-v2/src/log/logConfig.ts index 0b5d51397..8f7f11744 100644 --- a/packages/agent-core-v2/src/log/logConfig.ts +++ b/packages/agent-core-v2/src/log/logConfig.ts @@ -3,7 +3,7 @@ * * Builds the `LoggingConfig` from `KIMI_LOG_*` environment variables plus * defaults, resolves the global and per-session log paths, and exposes the - * `ILogOptions` seed used to inject the resolved config into a Core scope. + * `ILogOptions` seed used to inject the resolved config into a App scope. */ import { join } from 'pathe'; diff --git a/packages/agent-core-v2/src/log/logService.ts b/packages/agent-core-v2/src/log/logService.ts index 9d450b54b..41f286a85 100644 --- a/packages/agent-core-v2/src/log/logService.ts +++ b/packages/agent-core-v2/src/log/logService.ts @@ -3,7 +3,7 @@ * * Filters entries by the configured `LogLevel` and writes them to the bound * `ILogWriterService`; provides the console and in-memory `ILogWriterService` implementations. - * Bound at Core scope. + * Bound at App scope. */ import { InstantiationType } from '#/_base/di/extensions'; @@ -178,14 +178,14 @@ export class LogService extends BoundLogger implements ILogService { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ILogWriterService, ConsoleLogWriterService, InstantiationType.Eager, 'log', ); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ILogService, LogService, InstantiationType.Eager, diff --git a/packages/agent-core-v2/src/loop/configSection.ts b/packages/agent-core-v2/src/loop/configSection.ts index 64b9a5303..d7f76f681 100644 --- a/packages/agent-core-v2/src/loop/configSection.ts +++ b/packages/agent-core-v2/src/loop/configSection.ts @@ -2,10 +2,10 @@ * `loop` domain (L4) — `loopControl` config-section schema and TOML transforms. * * Owns the `[loop_control]` configuration section (step / retry / context-size - * limits) consumed by `LoopService` (step + retry budgets) and `ProfileService` + * limits) consumed by `AgentLoopService` (step + retry budgets) and `AgentProfileService` * (context sizing), plus the snake_case ↔ camelCase TOML transforms (including * the legacy `max_steps_per_run` → `maxStepsPerTurn` rename). Registered into - * `IConfigRegistry` by `LoopService` on construction. + * `IConfigRegistry` by `AgentLoopService` on construction. */ import { z } from 'zod'; diff --git a/packages/agent-core-v2/src/loop/loop.ts b/packages/agent-core-v2/src/loop/loop.ts index b330c6961..584b4bd53 100644 --- a/packages/agent-core-v2/src/loop/loop.ts +++ b/packages/agent-core-v2/src/loop/loop.ts @@ -8,9 +8,9 @@ export interface LoopRunHooks { readonly onContextOverflow: HookSlot; } -export interface ILoopService { +export interface IAgentLoopService { readonly _serviceBrand: undefined; runTurn(turn: Turn, hooks?: LoopRunHooks): Promise; } -export const ILoopService = createDecorator('agentLoopService'); +export const IAgentLoopService = createDecorator('agentLoopService'); diff --git a/packages/agent-core-v2/src/loop/loopService.ts b/packages/agent-core-v2/src/loop/loopService.ts index b3b603f6b..67790868d 100644 --- a/packages/agent-core-v2/src/loop/loopService.ts +++ b/packages/agent-core-v2/src/loop/loopService.ts @@ -37,26 +37,26 @@ import { type KimiErrorPayload, } from "#/errors"; import { canonicalTelemetryArgs } from '#/_base/utils/canonical-args'; -import { IContextMemory, newMessageId, type ContextMessage } from '#/contextMemory'; -import { IContextProjector } from '#/contextProjector'; -import { IContextSizeService } from '#/contextSize'; -import { IEventSink } from '../eventSink'; -import { IExternalHooksService } from '#/externalHooks'; -import { ILLMRequester } from '#/llmRequester'; -import { IProfileService } from '#/profile'; +import { IAgentContextMemoryService, newMessageId, type ContextMessage } from '#/contextMemory'; +import { IAgentContextProjectorService } from '#/contextProjector'; +import { IAgentContextSizeService } from '#/contextSize'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentExternalHooksService } from '#/externalHooks'; +import { IAgentLLMRequesterService } from '#/llmRequester'; +import { IAgentProfileService } from '#/profile'; import { IConfigRegistry, IConfigService } from '#/config'; import { ITelemetryService } from '#/telemetry'; -import { IToolExecutor } from '#/toolExecutor'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolExecutorService } from '#/toolExecutor'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { Turn, TurnResult } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import type { LoopEvent, LoopEventDispatcher, LoopRecordedEvent, } from './events'; import type { LLM, LLMChatParams, LLMChatResponse } from './llm'; -import { ILoopService, type LoopRunHooks } from './loop'; +import { IAgentLoopService, type LoopRunHooks } from './loop'; import { LOOP_CONTROL_SECTION, LoopControlSchema, @@ -79,7 +79,7 @@ const TOOL_OUTPUT_EMPTY_TEXT = 'Tool output is empty.'; type ToolTelemetryEvent = 'tool_call' | 'tool_call_dedup_detected' | 'tool_call_repeat'; type TelemetryProperties = Record; -export class LoopService extends Disposable implements ILoopService { +export class AgentLoopService extends Disposable implements IAgentLoopService { declare readonly _serviceBrand: undefined; private readonly openSteps = new Map(); private readonly toolCallStartedAt = new Map(); @@ -91,17 +91,17 @@ export class LoopService extends Disposable implements ILoopService { private protocolTurnId: number | undefined; constructor( - @IContextMemory private readonly context: IContextMemory, - @IContextProjector private readonly projector: IContextProjector, - @IContextSizeService private readonly contextSize: IContextSizeService, - @ILLMRequester private readonly llmRequester: ILLMRequester, - @IEventSink private readonly events: IEventSink, - @IToolRegistry private readonly toolRegistry: IToolRegistry, - @IToolExecutor private readonly toolExecutor: IToolExecutor, - @IProfileService private readonly profile: IProfileService, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentContextProjectorService private readonly projector: IAgentContextProjectorService, + @IAgentContextSizeService private readonly contextSize: IAgentContextSizeService, + @IAgentLLMRequesterService private readonly llmRequester: IAgentLLMRequesterService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentToolRegistryService private readonly toolRegistry: IAgentToolRegistryService, + @IAgentToolExecutorService private readonly toolExecutor: IAgentToolExecutorService, + @IAgentProfileService private readonly profile: IAgentProfileService, @ITelemetryService private readonly telemetry: ITelemetryService, - @IWireRecord private readonly wireRecord: IWireRecord, - @IExternalHooksService private readonly externalHooks: IExternalHooksService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentExternalHooksService private readonly externalHooks: IAgentExternalHooksService, @IConfigRegistry configRegistry: IConfigRegistry, @IConfigService private readonly config: IConfigService, ) { @@ -1059,8 +1059,8 @@ interface ToolCallDelta { registerScopedService( LifecycleScope.Agent, - ILoopService, - LoopService, + IAgentLoopService, + AgentLoopService, InstantiationType.Delayed, 'loop', ); diff --git a/packages/agent-core-v2/src/loop/run-turn.ts b/packages/agent-core-v2/src/loop/run-turn.ts index 08b452815..cd43c76b9 100644 --- a/packages/agent-core-v2/src/loop/run-turn.ts +++ b/packages/agent-core-v2/src/loop/run-turn.ts @@ -17,7 +17,7 @@ import { isMaxStepsExceededError, } from './errors'; import type { LoopInterruptReason, LoopEventDispatcher, LoopTurnInterruptedEvent } from './events'; -import type { IToolExecutor } from '#/toolExecutor'; +import type { IAgentToolExecutorService } from '#/toolExecutor'; import type { LLM } from './llm'; import { executeLoopStep } from './turn-step'; import type { ExecutableTool } from '#/tool'; @@ -42,7 +42,7 @@ export interface RunTurnInput { readonly log?: Logger | undefined; readonly maxSteps?: number | undefined; readonly maxRetryAttempts?: number; - readonly toolExecutor: IToolExecutor; + readonly toolExecutor: IAgentToolExecutorService; readonly recordStepUsage?: | (( usage: TokenUsage, diff --git a/packages/agent-core-v2/src/loop/turn-step.ts b/packages/agent-core-v2/src/loop/turn-step.ts index 5e45e34c5..6446fa1b5 100644 --- a/packages/agent-core-v2/src/loop/turn-step.ts +++ b/packages/agent-core-v2/src/loop/turn-step.ts @@ -12,7 +12,7 @@ import { randomUUID } from 'node:crypto'; import type { TokenUsage } from '@moonshot-ai/kosong'; import type { ILogger as Logger } from '#/log'; -import type { IToolExecutor } from '#/toolExecutor'; +import type { IAgentToolExecutorService } from '#/toolExecutor'; import type { LoopEventDispatcher } from './events'; import type { LLM, LLMChatParams, LLMChatResponse } from './llm'; import { chatWithRetry } from './retry'; @@ -41,7 +41,7 @@ export interface ExecuteLoopStepDeps { readonly log?: Logger | undefined; readonly currentStep: number; readonly maxRetryAttempts?: number; - readonly toolExecutor: IToolExecutor; + readonly toolExecutor: IAgentToolExecutorService; readonly recordUsage: ( usage: TokenUsage, context: RecordStepUsageContext, diff --git a/packages/agent-core-v2/src/loop/types.ts b/packages/agent-core-v2/src/loop/types.ts index 655a7eabe..fba81a2ae 100644 --- a/packages/agent-core-v2/src/loop/types.ts +++ b/packages/agent-core-v2/src/loop/types.ts @@ -117,7 +117,7 @@ export type ShouldContinueAfterStopHook = ( * Groups every awaited phase hook forwarded from the turn layer. * * Tool-execution gates (`onWillExecuteTool` / `onDidExecuteTool`) are owned by - * `IToolExecutor` and run by it at the right transcript points. + * `IAgentToolExecutorService` and run by it at the right transcript points. * `shouldContinueAfterStop` is loop-local convergence control. */ export interface LoopHooks { diff --git a/packages/agent-core-v2/src/mcp/connection-manager.ts b/packages/agent-core-v2/src/mcp/connection-manager.ts index 8aee8cb64..eab07c5e9 100644 --- a/packages/agent-core-v2/src/mcp/connection-manager.ts +++ b/packages/agent-core-v2/src/mcp/connection-manager.ts @@ -6,7 +6,7 @@ * (stdio / SSE / HTTP), discovers and registers tools, attaches the OAuth * provider through `mcp/oauth` when tokens are present, flips failing * servers into `needs-auth` on 401, and reconnects after authentication. - * Emits server status changes to subscribers. Constructed by `McpService`. + * Emits server status changes to subscribers. Constructed by `AgentMcpService`. */ import { ErrorCodes, KimiError } from '#/errors'; diff --git a/packages/agent-core-v2/src/mcp/mcp.ts b/packages/agent-core-v2/src/mcp/mcp.ts index ec3733d5e..23ea6fccc 100644 --- a/packages/agent-core-v2/src/mcp/mcp.ts +++ b/packages/agent-core-v2/src/mcp/mcp.ts @@ -14,7 +14,7 @@ export interface McpResolvedServer { readonly enabledNames: ReadonlySet; } -export interface IMcpService { +export interface IAgentMcpService { readonly _serviceBrand: undefined; readonly oauthService: McpOAuthService | undefined; @@ -31,4 +31,4 @@ export interface McpServiceOptions { readonly manager?: McpConnectionManager; } -export const IMcpService = createDecorator('agentMcpService'); +export const IAgentMcpService = createDecorator('agentMcpService'); diff --git a/packages/agent-core-v2/src/mcp/mcpService.ts b/packages/agent-core-v2/src/mcp/mcpService.ts index 7cdd10201..b0a464a93 100644 --- a/packages/agent-core-v2/src/mcp/mcpService.ts +++ b/packages/agent-core-v2/src/mcp/mcpService.ts @@ -7,13 +7,13 @@ import { type IDisposable, } from "#/_base/di"; import { ErrorCodes, makeErrorPayload } from "#/errors"; -import { IEventSink } from '../eventSink'; -import { IToolExecutor } from '#/toolExecutor'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentToolExecutorService } from '#/toolExecutor'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { createMcpAuthTool } from './tools/auth'; import { createMcpTool } from './tools/mcp'; import type { McpServerEntry } from './connection-manager'; -import { IMcpService, type McpServiceOptions } from './mcp'; +import { IAgentMcpService, type McpServiceOptions } from './mcp'; import { qualifyMcpToolName } from './tool-naming'; import type { MCPClient } from './types'; @@ -30,16 +30,16 @@ interface McpToolCollision { | { readonly kind: 'other_server'; readonly serverName: string }; } -export class McpService extends Disposable implements IMcpService { +export class AgentMcpService extends Disposable implements IAgentMcpService { declare readonly _serviceBrand: undefined; private readonly mcpTools = new Map(); private readonly mcpToolsByServer = new Map(); constructor( private readonly options: McpServiceOptions = {}, - @IToolRegistry private readonly registry: IToolRegistry, - @IEventSink private readonly events: IEventSink, - @IToolExecutor toolExecutor: IToolExecutor, + @IAgentToolRegistryService private readonly registry: IAgentToolRegistryService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentToolExecutorService toolExecutor: IAgentToolExecutorService, ) { super(); this.attachMcpTools(); @@ -84,7 +84,7 @@ export class McpService extends Disposable implements IMcpService { signal?.throwIfAborted(); } - onStatusChange(listener: Parameters[0]) { + onStatusChange(listener: Parameters[0]) { const unsubscribe = this.options.manager?.onStatusChange(listener); return { dispose: unsubscribe ?? (() => undefined), @@ -266,8 +266,8 @@ export class McpService extends Disposable implements IMcpService { registerScopedService( LifecycleScope.Agent, - IMcpService, - McpService, + IAgentMcpService, + AgentMcpService, InstantiationType.Delayed, 'mcp', ); diff --git a/packages/agent-core-v2/src/media/registerMediaTools.ts b/packages/agent-core-v2/src/media/registerMediaTools.ts index 1c227e41e..a14401931 100644 --- a/packages/agent-core-v2/src/media/registerMediaTools.ts +++ b/packages/agent-core-v2/src/media/registerMediaTools.ts @@ -17,13 +17,13 @@ import type { ChatProvider, ModelCapability } from '@moonshot-ai/kosong'; import { toDisposable, type IDisposable } from '#/_base/di'; import type { WorkspaceConfig } from '#/_base/tools/support/workspace'; -import type { IAgentFileSystem } from '#/agentFs'; +import type { ISessionAgentFileSystem } from '#/agentFs'; import type { IKaos } from '#/kaos'; -import type { IToolRegistry } from '#/toolRegistry'; +import type { IAgentToolRegistryService } from '#/toolRegistry'; import { ReadMediaFileTool, type VideoUploader } from './tools/read-media'; export interface RegisterMediaToolsDeps { - readonly fs: IAgentFileSystem; + readonly fs: ISessionAgentFileSystem; readonly kaos: IKaos; readonly workspace: WorkspaceConfig; readonly capabilities: ModelCapability; @@ -39,7 +39,7 @@ export interface RegisterMediaToolsDeps { * lifecycle and re-run registration cleanly on capability changes. */ export function registerMediaTools( - toolRegistry: IToolRegistry, + toolRegistry: IAgentToolRegistryService, deps: RegisterMediaToolsDeps, ): IDisposable { if (!deps.capabilities.image_in && !deps.capabilities.video_in) { diff --git a/packages/agent-core-v2/src/media/tools/read-media.ts b/packages/agent-core-v2/src/media/tools/read-media.ts index 148840cf4..6719ebcad 100644 --- a/packages/agent-core-v2/src/media/tools/read-media.ts +++ b/packages/agent-core-v2/src/media/tools/read-media.ts @@ -27,7 +27,7 @@ import type { } from '@moonshot-ai/kosong'; import { z } from 'zod'; -import { IAgentFileSystem } from '#/agentFs'; +import { ISessionAgentFileSystem } from '#/agentFs'; import { IKaos } from '#/kaos'; import { ToolAccesses } from '#/tool'; import type { BuiltinTool, ExecutableToolResult, ToolExecution } from '#/tool'; @@ -136,7 +136,7 @@ export class ReadMediaFileTool implements BuiltinTool { readonly description: string; readonly parameters: Record = toInputJsonSchema(ReadMediaFileInputSchema); constructor( - private readonly fs: IAgentFileSystem, + private readonly fs: ISessionAgentFileSystem, private readonly kaos: IKaos, private readonly workspace: WorkspaceConfig, private readonly capabilities: ModelCapability, diff --git a/packages/agent-core-v2/src/messageLegacy/messageLegacy.ts b/packages/agent-core-v2/src/messageLegacy/messageLegacy.ts index 6694800af..b2121c141 100644 --- a/packages/agent-core-v2/src/messageLegacy/messageLegacy.ts +++ b/packages/agent-core-v2/src/messageLegacy/messageLegacy.ts @@ -4,14 +4,14 @@ * Implements the legacy `GET /api/v1/sessions/{sid}/messages[/{mid}]` contract * (`packages/server/src/routes/messages.ts`) on top of the native v2 services. * - * The native `IContextMemory` (Agent scope, serving `/api/v2` `messages:*`) + * The native `IAgentContextMemoryService` (Agent scope, serving `/api/v2` `messages:*`) * holds the model's CURRENT, folded context and is left untouched. For a live * session this adapter reads that folded history (its transcript is in memory * by definition); for a cold session it loads the session, restores the main - * agent's wire log, and reads the FULL transcript from `IReplayBuilderService` + * agent's wire log, and reads the FULL transcript from `IAgentReplayBuilderService` * (pre-compaction messages preserved, matching v1's `wire.jsonl` rebuild). The * `ContextMessage → Message` projection is shared with the `snapshot` and - * `:undo` edges via `contextMemory/messageProjection`. Bound at Core scope — a + * `:undo` edges via `contextMemory/messageProjection`. Bound at App scope — a * stateless dispatcher that resolves the target session/agent per call. * * Error contract (mapped at the route layer): diff --git a/packages/agent-core-v2/src/messageLegacy/messageLegacyService.ts b/packages/agent-core-v2/src/messageLegacy/messageLegacyService.ts index c413597a8..76426d342 100644 --- a/packages/agent-core-v2/src/messageLegacy/messageLegacyService.ts +++ b/packages/agent-core-v2/src/messageLegacy/messageLegacyService.ts @@ -1,12 +1,12 @@ /** * `messageLegacy` domain — `IMessageLegacyService` implementation. * - * Stateless Core-scope dispatcher: each call resolves the target session (and + * Stateless App-scope dispatcher: each call resolves the target session (and * its main agent), sources the transcript, and projects it into the v1 wire - * shape. Live sessions are read from the main agent's `IContextMemory` (the + * shape. Live sessions are read from the main agent's `IAgentContextMemoryService` (the * folded history already in memory); cold sessions are loaded, their main agent * is restored from the persisted wire log, and the FULL transcript is read from - * `IReplayBuilderService` — v2's own replay reducer, so no reduction logic is + * `IAgentReplayBuilderService` — v2's own replay reducer, so no reduction logic is * duplicated here. Pagination, id derivation, and the role filter mirror v1's * `MessageService` (`packages/agent-core/src/services/message/messageService.ts`). */ @@ -17,15 +17,15 @@ import { InstantiationType } from '#/_base/di/extensions'; import { type IScopeHandle, LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { IAgentLifecycleService } from '#/agent-lifecycle'; import { - IContextMemory, + IAgentContextMemoryService, toProtocolMessage, type ContextMessage, } from '#/contextMemory'; import { ErrorCodes, KimiError } from '#/errors'; -import { IReplayBuilderService } from '#/replayBuilder'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; import { ISessionIndex, type SessionSummary } from '#/session-index'; import { ISessionLifecycleService } from '#/session-lifecycle'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { IWorkspaceRegistry } from '#/workspaceRegistry'; import { IMessageLegacyService, type MessageListQuery } from './messageLegacy'; @@ -112,12 +112,12 @@ export class MessageLegacyService implements IMessageLegacyService { // agent was restored and the replay holds the full pre-compaction history. // Otherwise the agent is fresh (never restored) and the folded context // memory IS the transcript. - const replay = agent.accessor.get(IReplayBuilderService).buildResult(); + const replay = agent.accessor.get(IAgentReplayBuilderService).buildResult(); const restored: ContextMessage[] = []; for (const record of replay) { if (record.type === 'message') restored.push(record.message); } - const source = restored.length > 0 ? restored : agent.accessor.get(IContextMemory).get(); + const source = restored.length > 0 ? restored : agent.accessor.get(IAgentContextMemoryService).get(); return source.map((msg, index) => toProtocolMessage(sessionId, index, msg, summary.createdAt)); } @@ -148,11 +148,11 @@ export class MessageLegacyService implements IMessageLegacyService { // Restore only the agent we just materialized from a cold session; an // already-live agent must not be re-restored (it would re-apply splices). if (loaded) { - // `IContextMemory` registers the `context.splice` resumer and pulls in - // `IReplayBuilderService`; both are Delayed, so resolve them before + // `IAgentContextMemoryService` registers the `context.splice` resumer and pulls in + // `IAgentReplayBuilderService`; both are Delayed, so resolve them before // replaying the wire or the restore would replay into a void. - agent.accessor.get(IContextMemory); - await agent.accessor.get(IWireRecord).restore(); + agent.accessor.get(IAgentContextMemoryService); + await agent.accessor.get(IAgentWireRecordService).restore(); } } return agent; @@ -160,7 +160,7 @@ export class MessageLegacyService implements IMessageLegacyService { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IMessageLegacyService, MessageLegacyService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/microCompaction/configSection.ts b/packages/agent-core-v2/src/microCompaction/configSection.ts index bfff61cf7..5fed7d77b 100644 --- a/packages/agent-core-v2/src/microCompaction/configSection.ts +++ b/packages/agent-core-v2/src/microCompaction/configSection.ts @@ -2,7 +2,7 @@ * `microCompaction` domain (L4) - micro-compaction config-section schema. * * Owns the `[micro_compaction]` tuning section consumed by - * `MicroCompactionService`. Registered into `IConfigRegistry` by the + * `AgentMicroCompactionService`. Registered into `IConfigRegistry` by the * micro-compaction service on construction. */ diff --git a/packages/agent-core-v2/src/microCompaction/microCompaction.ts b/packages/agent-core-v2/src/microCompaction/microCompaction.ts index 3548a0c28..827150011 100644 --- a/packages/agent-core-v2/src/microCompaction/microCompaction.ts +++ b/packages/agent-core-v2/src/microCompaction/microCompaction.ts @@ -2,7 +2,7 @@ * `microCompaction` domain (L4) - micro-compaction service contract. * * Defines the truncation tuning model and the Agent-scoped - * `IMicroCompactionService` used by context projection. Bound at Agent scope. + * `IAgentMicroCompactionService` used by context projection. Bound at Agent scope. */ import { createDecorator } from "#/_base/di"; @@ -22,10 +22,10 @@ export interface MicroCompactionEffect { readonly truncatedToolResultTokensAfter: number; } -export interface IMicroCompactionService { +export interface IAgentMicroCompactionService { readonly _serviceBrand: undefined; compact(messages: readonly ContextMessage[]): readonly ContextMessage[]; } -export const IMicroCompactionService = - createDecorator('agentMicroCompactionService'); +export const IAgentMicroCompactionService = + createDecorator('agentMicroCompactionService'); diff --git a/packages/agent-core-v2/src/microCompaction/microCompactionService.ts b/packages/agent-core-v2/src/microCompaction/microCompactionService.ts index b9cb0a1e8..c235bedda 100644 --- a/packages/agent-core-v2/src/microCompaction/microCompactionService.ts +++ b/packages/agent-core-v2/src/microCompaction/microCompactionService.ts @@ -1,5 +1,5 @@ /** - * `microCompaction` domain (L4) - `IMicroCompactionService` implementation. + * `microCompaction` domain (L4) - `IAgentMicroCompactionService` implementation. * * Tracks cache-miss compaction cutoffs over `contextMemory`, sizes context via * `contextSize`, resolves model capacity through `profile`, persists cutoffs @@ -20,16 +20,16 @@ import { } from "#/_base/utils/tokens"; import type { TelemetryProperties } from '#/telemetry'; import { IConfigRegistry, IConfigService } from '#/config'; -import { IContextMemory } from '#/contextMemory'; -import { IContextSizeService } from '#/contextSize'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentContextSizeService } from '#/contextSize'; import { IFlagService } from '#/flag'; -import { IProfileService } from '#/profile'; +import { IAgentProfileService } from '#/profile'; import { ITelemetryService } from '#/telemetry'; -import { ITurnService } from '#/turn'; +import { IAgentTurnService } from '#/turn'; import type { ContextMessage } from '../contextMemory'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { - IMicroCompactionService, + IAgentMicroCompactionService, type MicroCompactionConfig, type MicroCompactionEffect, } from './microCompaction'; @@ -55,9 +55,9 @@ const DEFAULT_CONFIG: MicroCompactionConfig = { minContextUsageRatio: 0.5, }; -export class MicroCompactionService +export class AgentMicroCompactionService extends Disposable - implements IMicroCompactionService + implements IAgentMicroCompactionService { declare readonly _serviceBrand: undefined; private cutoff = 0; @@ -65,13 +65,13 @@ export class MicroCompactionService private _lastAssistantAt: number | null = null; constructor( - @IContextMemory private readonly context: IContextMemory, - @IContextSizeService private readonly contextSize: IContextSizeService, - @IWireRecord private readonly wireRecord: IWireRecord, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentContextSizeService private readonly contextSize: IAgentContextSizeService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, @IFlagService private readonly flags: IFlagService, - @IProfileService private readonly profile: IProfileService, + @IAgentProfileService private readonly profile: IAgentProfileService, @ITelemetryService private readonly telemetry: ITelemetryService, - @ITurnService turn: ITurnService, + @IAgentTurnService turn: IAgentTurnService, @IConfigRegistry configRegistry: IConfigRegistry, @IConfigService private readonly config: IConfigService, ) { @@ -273,8 +273,8 @@ function isAssistantCacheAnchor(message: ContextMessage): boolean { registerScopedService( LifecycleScope.Agent, - IMicroCompactionService, - MicroCompactionService, + IAgentMicroCompactionService, + AgentMicroCompactionService, InstantiationType.Eager, 'microCompaction', ); diff --git a/packages/agent-core-v2/src/model/model.ts b/packages/agent-core-v2/src/model/model.ts index 2713a5d40..8ff5f2fcd 100644 --- a/packages/agent-core-v2/src/model/model.ts +++ b/packages/agent-core-v2/src/model/model.ts @@ -3,7 +3,7 @@ * * Owns the `ModelAlias` model and the `models` config section (alias → provider * + model + context/capabilities); exposes CRUD over model aliases and persists - * them through `config`. Core-scoped — model aliases are global and shared + * them through `config`. App-scoped — model aliases are global and shared * across sessions. */ diff --git a/packages/agent-core-v2/src/model/modelService.ts b/packages/agent-core-v2/src/model/modelService.ts index 1ed8d898b..b3f3be57d 100644 --- a/packages/agent-core-v2/src/model/modelService.ts +++ b/packages/agent-core-v2/src/model/modelService.ts @@ -4,7 +4,7 @@ * Owns the in-memory view of the `models` config section, persists changes * through `config`, registers the section schema plus the `KIMI_MODEL_*` * effective overlay on construction, and forwards section changes as - * `onDidChange`. Bound at Core scope, eager — registering the `models` section + * `onDidChange`. Bound at App scope, eager — registering the `models` section * is an early side effect that config reads depend on. */ @@ -69,4 +69,4 @@ export class ModelService extends Disposable implements IModelService { } } -registerScopedService(LifecycleScope.Core, IModelService, ModelService, InstantiationType.Eager, 'model'); +registerScopedService(LifecycleScope.App, IModelService, ModelService, InstantiationType.Eager, 'model'); diff --git a/packages/agent-core-v2/src/modelCatalog/modelCatalog.ts b/packages/agent-core-v2/src/modelCatalog/modelCatalog.ts index 39ef9dca1..355ec8058 100644 --- a/packages/agent-core-v2/src/modelCatalog/modelCatalog.ts +++ b/packages/agent-core-v2/src/modelCatalog/modelCatalog.ts @@ -4,7 +4,7 @@ * * Projects the `provider` / `model` configuration registries into the * protocol `ProviderCatalogItem` / `ModelCatalogItem` wire shapes that the - * edge (`server-v2` `/api/v1` routes) serves. Core-scoped — provider and + * edge (`server-v2` `/api/v1` routes) serves. App-scoped — provider and * model configuration is global and shared across sessions. This domain is a * thin facade over `provider`, `model`, `config`, and `auth`; it owns no * persistence of its own. The OAuth-provider model refresh lives in diff --git a/packages/agent-core-v2/src/modelCatalog/modelCatalogService.ts b/packages/agent-core-v2/src/modelCatalog/modelCatalogService.ts index 2375d5510..52d4464f9 100644 --- a/packages/agent-core-v2/src/modelCatalog/modelCatalogService.ts +++ b/packages/agent-core-v2/src/modelCatalog/modelCatalogService.ts @@ -3,7 +3,7 @@ * * Projects the `provider` / `model` registries into protocol catalog items, * resolves credential state through `config` and `auth`, and persists the - * global default-model selection through `config`. Bound at Core scope. The + * global default-model selection through `config`. Bound at App scope. The * The managed OAuth-provider refresh lives in `auth` (`IOAuthService`), not here. */ @@ -139,7 +139,7 @@ function nonEmpty(value: string | undefined): string | undefined { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IModelCatalogService, ModelCatalogService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/modelRuntime/index.ts b/packages/agent-core-v2/src/modelRuntime/index.ts index 4383f58e2..6f0434c50 100644 --- a/packages/agent-core-v2/src/modelRuntime/index.ts +++ b/packages/agent-core-v2/src/modelRuntime/index.ts @@ -1,7 +1,7 @@ /** * `modelRuntime` domain barrel — re-exports the model-runtime contract * (`modelRuntime`) and its runtime implementation (`modelResolverService`). - * `IModelResolver` is registered as a Session-scoped service (built from + * `ISessionModelResolver` is registered as a Session-scoped service (built from * `IConfigService` + `IOAuthService`); `modelResolverSeed` remains available * as a host/test override seam. */ diff --git a/packages/agent-core-v2/src/modelRuntime/modelResolverService.ts b/packages/agent-core-v2/src/modelRuntime/modelResolverService.ts index ea373893a..1fbfeb173 100644 --- a/packages/agent-core-v2/src/modelRuntime/modelResolverService.ts +++ b/packages/agent-core-v2/src/modelRuntime/modelResolverService.ts @@ -1,5 +1,5 @@ /** - * `modelRuntime` domain (L3) — `IModelResolver` runtime implementation. + * `modelRuntime` domain (L3) — `ISessionModelResolver` runtime implementation. * * Resolves a model alias into a runtime provider configuration plus optional * OAuth request authorization, reading provider / model configuration through @@ -29,16 +29,16 @@ import type { ProviderConfig } from '#/provider'; import { type AuthorizedRequest, - IModelResolver, + ISessionModelResolver, type RequestLogger, type ResolvedModel, } from './modelRuntime'; -export function modelResolverSeed(modelResolver: IModelResolver): ScopeSeed { - return [[IModelResolver as ServiceIdentifier, modelResolver]]; +export function modelResolverSeed(modelResolver: ISessionModelResolver): ScopeSeed { + return [[ISessionModelResolver as ServiceIdentifier, modelResolver]]; } -export class SingleModelResolver implements IModelResolver { +export class SingleModelResolver implements ISessionModelResolver { declare readonly _serviceBrand: undefined; constructor( private readonly providerConfig: RuntimeProviderConfig, @@ -64,7 +64,7 @@ export class SingleModelResolver implements IModelResolver { } } -export class ModelResolver implements IModelResolver { +export class SessionModelResolver implements ISessionModelResolver { declare readonly _serviceBrand: undefined; constructor( @IConfigService private readonly config: IConfigService, @@ -376,8 +376,8 @@ function locationFromVertexAIBaseUrl(baseUrl: string | undefined): string | unde registerScopedService( LifecycleScope.Session, - IModelResolver, - ModelResolver, + ISessionModelResolver, + SessionModelResolver, InstantiationType.Delayed, 'modelRuntime', ); diff --git a/packages/agent-core-v2/src/modelRuntime/modelRuntime.ts b/packages/agent-core-v2/src/modelRuntime/modelRuntime.ts index 5854890c5..e6badd916 100644 --- a/packages/agent-core-v2/src/modelRuntime/modelRuntime.ts +++ b/packages/agent-core-v2/src/modelRuntime/modelRuntime.ts @@ -1,10 +1,10 @@ /** - * `modelRuntime` domain (L3) — `IModelResolver` contract. + * `modelRuntime` domain (L3) — `ISessionModelResolver` contract. * * Resolves a model alias into a runnable runtime provider configuration plus * optional OAuth request authorization, reading provider / model configuration * through `IConfigService` and OAuth tokens through `IOAuthService`. Registered - * as a Session-scoped service; `IProfileService` / `ILLMRequester` consume it + * as a Session-scoped service; `IAgentProfileService` / `IAgentLLMRequesterService` consume it * through DI. Bound at Session scope. */ @@ -50,7 +50,7 @@ export type AuthorizedRequest = ( request: (auth: ProviderRequestAuth) => Promise, ) => Promise; -export interface IModelResolver { +export interface ISessionModelResolver { readonly _serviceBrand: undefined; readonly defaultModel?: string; resolve(model: string): ResolvedModel; @@ -60,5 +60,5 @@ export interface IModelResolver { ): AuthorizedRequest | undefined; } -export const IModelResolver: ServiceIdentifier = - createDecorator('modelResolver'); +export const ISessionModelResolver: ServiceIdentifier = + createDecorator('sessionModelResolver'); diff --git a/packages/agent-core-v2/src/permissionGate/permissionGate.ts b/packages/agent-core-v2/src/permissionGate/permissionGate.ts index 86004af3c..3254854a0 100644 --- a/packages/agent-core-v2/src/permissionGate/permissionGate.ts +++ b/packages/agent-core-v2/src/permissionGate/permissionGate.ts @@ -12,7 +12,7 @@ export interface PermissionGateOptions { readonly agentType?: 'main' | 'sub'; } -export interface IPermissionGate { +export interface IAgentPermissionGate { readonly _serviceBrand: undefined; data(): PermissionData; authorize( @@ -20,5 +20,5 @@ export interface IPermissionGate { ): Promise; } -export const IPermissionGate = - createDecorator('agentPermissionGate'); +export const IAgentPermissionGate = + createDecorator('agentPermissionGate'); diff --git a/packages/agent-core-v2/src/permissionGate/permissionGateService.ts b/packages/agent-core-v2/src/permissionGate/permissionGateService.ts index 0f58f6da2..c135c3b7c 100644 --- a/packages/agent-core-v2/src/permissionGate/permissionGateService.ts +++ b/packages/agent-core-v2/src/permissionGate/permissionGateService.ts @@ -12,37 +12,37 @@ import type { ResolvedToolExecutionHookContext, } from '#/tool'; import type { ToolInputDisplay } from '@moonshot-ai/protocol'; -import { IApprovalService } from "#/approval/approval"; -import { IExternalHooksService } from '#/externalHooks'; -import { IPermissionModeService } from '#/permissionMode'; +import { ISessionApprovalService } from "#/approval/approval"; +import { IAgentExternalHooksService } from '#/externalHooks'; +import { IAgentPermissionModeService } from '#/permissionMode'; import { - IPermissionPolicyService, + IAgentPermissionPolicyService, type PermissionPolicyResolution, type PermissionPolicyResult, } from '#/permissionPolicy'; -import { IPermissionRulesService } from '#/permissionRules'; +import { IAgentPermissionRulesService } from '#/permissionRules'; import { ISessionContext } from '#/session-context'; import { ITelemetryService } from '#/telemetry'; -import { IToolExecutor } from '#/toolExecutor'; +import { IAgentToolExecutorService } from '#/toolExecutor'; import { - IPermissionGate, + IAgentPermissionGate, type PermissionGateOptions, } from './permissionGate'; import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -export class PermissionGate extends Disposable implements IPermissionGate { +export class AgentPermissionGate extends Disposable implements IAgentPermissionGate { declare readonly _serviceBrand: undefined; constructor( private readonly options: PermissionGateOptions = {}, - @IPermissionModeService private readonly modeService: IPermissionModeService, - @IPermissionRulesService private readonly rulesService: IPermissionRulesService, - @IPermissionPolicyService private readonly policyService: IPermissionPolicyService, - @IExternalHooksService private readonly externalHooks: IExternalHooksService, + @IAgentPermissionModeService private readonly modeService: IAgentPermissionModeService, + @IAgentPermissionRulesService private readonly rulesService: IAgentPermissionRulesService, + @IAgentPermissionPolicyService private readonly policyService: IAgentPermissionPolicyService, + @IAgentExternalHooksService private readonly externalHooks: IAgentExternalHooksService, @ISessionContext private readonly session: ISessionContext, @IInstantiationService private readonly instantiation: IInstantiationService, @ITelemetryService private readonly telemetry: ITelemetryService, - @IToolExecutor toolExecutor: IToolExecutor, + @IAgentToolExecutorService toolExecutor: IAgentToolExecutorService, ) { super(); toolExecutor.hooks.onWillExecuteTool.register('permission', async (ctx, next) => { @@ -230,10 +230,10 @@ export class PermissionGate extends Disposable implements IPermissionGate { }; } - private tryApprovalService(): IApprovalService | undefined { + private tryApprovalService(): ISessionApprovalService | undefined { try { return this.instantiation.invokeFunction( - (accessor) => accessor.get(IApprovalService) as IApprovalService | undefined, + (accessor) => accessor.get(ISessionApprovalService) as ISessionApprovalService | undefined, ); } catch { return undefined; @@ -277,8 +277,8 @@ function numericTurnId(turnId: string): number { registerScopedService( LifecycleScope.Agent, - IPermissionGate, - PermissionGate, + IAgentPermissionGate, + AgentPermissionGate, InstantiationType.Delayed, 'permissionGate', ); diff --git a/packages/agent-core-v2/src/permissionMode/injection/permissionModeInjection.ts b/packages/agent-core-v2/src/permissionMode/injection/permissionModeInjection.ts index f402d7eeb..0a1e72915 100644 --- a/packages/agent-core-v2/src/permissionMode/injection/permissionModeInjection.ts +++ b/packages/agent-core-v2/src/permissionMode/injection/permissionModeInjection.ts @@ -1,15 +1,15 @@ import type { PermissionMode } from '#/permissionPolicy'; import type { IDisposable } from "#/_base/di"; -import type { IContextInjector } from '../../contextInjector/contextInjector'; -import type { IPermissionModeService } from '../permissionMode'; +import type { IAgentContextInjectorService } from '../../contextInjector/contextInjector'; +import type { IAgentPermissionModeService } from '../permissionMode'; import AUTO_MODE_ENTER_REMINDER from './permission-mode-auto-enter-reminder.md?raw'; import AUTO_MODE_EXIT_REMINDER from './permission-mode-auto-exit-reminder.md?raw'; const PERMISSION_MODE_INJECTION_VARIANT = 'permission_mode'; export function registerPermissionModeInjection( - dynamicInjector: IContextInjector, - permissionMode: Pick, + dynamicInjector: IAgentContextInjectorService, + permissionMode: Pick, ): IDisposable { let lastMode: PermissionMode | undefined; return dynamicInjector.register(PERMISSION_MODE_INJECTION_VARIANT, () => { diff --git a/packages/agent-core-v2/src/permissionMode/permissionMode.ts b/packages/agent-core-v2/src/permissionMode/permissionMode.ts index 4553a306f..196214adc 100644 --- a/packages/agent-core-v2/src/permissionMode/permissionMode.ts +++ b/packages/agent-core-v2/src/permissionMode/permissionMode.ts @@ -8,7 +8,7 @@ export interface PermissionModeChangedContext { readonly previousMode: PermissionMode; } -export interface IPermissionModeService { +export interface IAgentPermissionModeService { readonly _serviceBrand: undefined; readonly mode: PermissionMode; setMode(mode: PermissionMode): void; @@ -18,5 +18,5 @@ export interface IPermissionModeService { }>; } -export const IPermissionModeService = - createDecorator('agentPermissionModeService'); +export const IAgentPermissionModeService = + createDecorator('agentPermissionModeService'); diff --git a/packages/agent-core-v2/src/permissionMode/permissionModeService.ts b/packages/agent-core-v2/src/permissionMode/permissionModeService.ts index b45daa895..8a4728a42 100644 --- a/packages/agent-core-v2/src/permissionMode/permissionModeService.ts +++ b/packages/agent-core-v2/src/permissionMode/permissionModeService.ts @@ -5,14 +5,14 @@ import { import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IContextInjector } from '../contextInjector'; -import { IEventSink } from '../eventSink'; +import { IAgentContextInjectorService } from '../contextInjector'; +import { IAgentEventSinkService } from '../eventSink'; import { OrderedHookSlot } from '../hooks'; -import { IReplayBuilderService } from '#/replayBuilder'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; import type { WireRecord } from '#/wireRecord'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { registerPermissionModeInjection } from './injection/permissionModeInjection'; -import { IPermissionModeService } from './permissionMode'; +import { IAgentPermissionModeService } from './permissionMode'; declare module '#/wireRecord' { interface WireRecordMap { @@ -22,7 +22,7 @@ declare module '#/wireRecord' { } } -export class PermissionModeService extends Disposable implements IPermissionModeService { +export class AgentPermissionModeService extends Disposable implements IAgentPermissionModeService { declare readonly _serviceBrand: undefined; private currentMode: PermissionMode = 'manual'; @@ -35,10 +35,10 @@ export class PermissionModeService extends Disposable implements IPermissionMode }; constructor( - @IWireRecord private readonly wireRecord: IWireRecord, - @IEventSink private readonly events: IEventSink, - @IReplayBuilderService private readonly replayBuilder: IReplayBuilderService, - @IContextInjector dynamicInjector: IContextInjector, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentReplayBuilderService private readonly replayBuilder: IAgentReplayBuilderService, + @IAgentContextInjectorService dynamicInjector: IAgentContextInjectorService, ) { super(); this._register( @@ -74,8 +74,8 @@ export class PermissionModeService extends Disposable implements IPermissionMode registerScopedService( LifecycleScope.Agent, - IPermissionModeService, - PermissionModeService, + IAgentPermissionModeService, + AgentPermissionModeService, InstantiationType.Delayed, 'permissionMode', ); diff --git a/packages/agent-core-v2/src/permissionPolicy/permissionPolicy.ts b/packages/agent-core-v2/src/permissionPolicy/permissionPolicy.ts index 3d50cd829..96f2d334e 100644 --- a/packages/agent-core-v2/src/permissionPolicy/permissionPolicy.ts +++ b/packages/agent-core-v2/src/permissionPolicy/permissionPolicy.ts @@ -10,12 +10,12 @@ export interface PermissionPolicyEvaluation { readonly result: PermissionPolicyResult; } -export interface IPermissionPolicyService { +export interface IAgentPermissionPolicyService { readonly _serviceBrand: undefined; evaluate( context: ResolvedToolExecutionHookContext, ): Promise; } -export const IPermissionPolicyService = - createDecorator('agentPermissionPolicyService'); +export const IAgentPermissionPolicyService = + createDecorator('agentPermissionPolicyService'); diff --git a/packages/agent-core-v2/src/permissionPolicy/permissionPolicyService.ts b/packages/agent-core-v2/src/permissionPolicy/permissionPolicyService.ts index ecf3d6a15..3478d07d2 100644 --- a/packages/agent-core-v2/src/permissionPolicy/permissionPolicyService.ts +++ b/packages/agent-core-v2/src/permissionPolicy/permissionPolicyService.ts @@ -22,16 +22,16 @@ import { UserConfiguredAskPermissionPolicyService } from './policies/user-config import { UserConfiguredDenyPermissionPolicyService } from './policies/user-configured-deny'; import { YoloModeApprovePermissionPolicyService } from './policies/yolo-mode-approve'; import { - IPermissionPolicyService, + IAgentPermissionPolicyService, type PermissionPolicyEvaluation, } from './permissionPolicy'; import type { PermissionPolicy } from "./types"; import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -export class PermissionPolicyService +export class AgentPermissionPolicyService extends Disposable - implements IPermissionPolicyService + implements IAgentPermissionPolicyService { declare readonly _serviceBrand: undefined; @@ -76,8 +76,8 @@ export class PermissionPolicyService registerScopedService( LifecycleScope.Agent, - IPermissionPolicyService, - PermissionPolicyService, + IAgentPermissionPolicyService, + AgentPermissionPolicyService, InstantiationType.Delayed, 'permissionPolicy', ); diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/auto-mode-approve.ts b/packages/agent-core-v2/src/permissionPolicy/policies/auto-mode-approve.ts index c9941da5d..dfdd29597 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/auto-mode-approve.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/auto-mode-approve.ts @@ -1,4 +1,4 @@ -import { IPermissionModeService } from '../../permissionMode/permissionMode'; +import { IAgentPermissionModeService } from '../../permissionMode/permissionMode'; import type { PermissionPolicy, PermissionPolicyResult, @@ -8,7 +8,7 @@ export class AutoModeApprovePermissionPolicyService implements PermissionPolicy readonly name = 'auto-mode-approve'; constructor( - @IPermissionModeService private readonly modeService: IPermissionModeService, + @IAgentPermissionModeService private readonly modeService: IAgentPermissionModeService, ) {} evaluate(): PermissionPolicyResult | undefined { diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/auto-mode-ask-user-question-deny.ts b/packages/agent-core-v2/src/permissionPolicy/policies/auto-mode-ask-user-question-deny.ts index eb689d5e7..9757c3afd 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/auto-mode-ask-user-question-deny.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/auto-mode-ask-user-question-deny.ts @@ -1,5 +1,5 @@ import type { ResolvedToolExecutionHookContext } from '#/tool'; -import { IPermissionModeService } from '../../permissionMode/permissionMode'; +import { IAgentPermissionModeService } from '../../permissionMode/permissionMode'; import type { PermissionPolicy, PermissionPolicyResult, @@ -9,7 +9,7 @@ export class AutoModeAskUserQuestionDenyPermissionPolicyService implements Permi readonly name = 'auto-mode-ask-user-question-deny'; constructor( - @IPermissionModeService private readonly modeService: IPermissionModeService, + @IAgentPermissionModeService private readonly modeService: IAgentPermissionModeService, ) {} evaluate(context: ResolvedToolExecutionHookContext): PermissionPolicyResult | undefined { diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/exit-plan-mode-review-ask.ts b/packages/agent-core-v2/src/permissionPolicy/policies/exit-plan-mode-review-ask.ts index a54b3ad67..74146bd6e 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/exit-plan-mode-review-ask.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/exit-plan-mode-review-ask.ts @@ -1,7 +1,7 @@ -import { IPlanService } from '#/plan'; -import type { IPlanService as PlanService } from '#/plan'; +import { IAgentPlanService } from '#/plan'; +import type { IAgentPlanService as AgentPlanService } from '#/plan'; import type { ResolvedToolExecutionHookContext } from '#/tool'; -import { IPermissionModeService } from '../../permissionMode/permissionMode'; +import { IAgentPermissionModeService } from '../../permissionMode/permissionMode'; import { ITelemetryService } from '../../telemetry/telemetry'; import type { PermissionPolicy, @@ -25,8 +25,8 @@ export class ExitPlanModeReviewAskPermissionPolicyService implements PermissionP readonly name = 'exit-plan-mode-review-ask'; constructor( - @IPlanService private readonly plan: PlanService, - @IPermissionModeService private readonly modeService: IPermissionModeService, + @IAgentPlanService private readonly plan: AgentPlanService, + @IAgentPermissionModeService private readonly modeService: IAgentPermissionModeService, @ITelemetryService private readonly telemetry: ITelemetryService, ) {} diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/git-control-path-access-ask.ts b/packages/agent-core-v2/src/permissionPolicy/policies/git-control-path-access-ask.ts index 3d7777b1c..54a80fdc1 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/git-control-path-access-ask.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/git-control-path-access-ask.ts @@ -1,8 +1,8 @@ import type { ResolvedToolExecutionHookContext } from '#/tool'; import { IKaos } from '#/kaos'; import type { IKaos as KaosService } from '#/kaos'; -import { IWorkspaceContext } from '#/workspaceContext'; -import type { IWorkspaceContext as WorkspaceContext } from '#/workspaceContext'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; +import type { ISessionWorkspaceContext as WorkspaceContext } from '#/workspaceContext'; import type { PermissionPolicy, PermissionPolicyResult, @@ -19,7 +19,7 @@ export class GitControlPathAccessAskPermissionPolicyService implements Permissio constructor( @IKaos private readonly kaos: KaosService, - @IWorkspaceContext private readonly workspace: WorkspaceContext, + @ISessionWorkspaceContext private readonly workspace: WorkspaceContext, ) {} async evaluate( diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/git-cwd-write-approve.ts b/packages/agent-core-v2/src/permissionPolicy/policies/git-cwd-write-approve.ts index 058002596..ce7389ede 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/git-cwd-write-approve.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/git-cwd-write-approve.ts @@ -2,8 +2,8 @@ import type { ResolvedToolExecutionHookContext } from '#/tool'; import { isWithinWorkspace } from '#/_base/tools/policies/path-access'; import { IKaos } from '#/kaos'; import type { IKaos as KaosService } from '#/kaos'; -import { IWorkspaceContext } from '#/workspaceContext'; -import type { IWorkspaceContext as WorkspaceContext } from '#/workspaceContext'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; +import type { ISessionWorkspaceContext as WorkspaceContext } from '#/workspaceContext'; import type { PermissionPolicy, PermissionPolicyResult, @@ -18,7 +18,7 @@ export class GitCwdWriteApprovePermissionPolicyService implements PermissionPoli constructor( @IKaos private readonly kaos: KaosService, - @IWorkspaceContext private readonly workspace: WorkspaceContext, + @ISessionWorkspaceContext private readonly workspace: WorkspaceContext, ) {} async evaluate( diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/goal-start-review-ask.ts b/packages/agent-core-v2/src/permissionPolicy/policies/goal-start-review-ask.ts index 8de621567..808041e46 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/goal-start-review-ask.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/goal-start-review-ask.ts @@ -1,5 +1,5 @@ import type { ResolvedToolExecutionHookContext } from '#/tool'; -import { IPermissionModeService } from '../../permissionMode/permissionMode'; +import { IAgentPermissionModeService } from '../../permissionMode/permissionMode'; import type { PermissionPolicy, PermissionMode, @@ -10,7 +10,7 @@ export class GoalStartReviewAskPermissionPolicyService implements PermissionPoli readonly name = 'goal-start-review-ask'; constructor( - @IPermissionModeService private readonly modeService: IPermissionModeService, + @IAgentPermissionModeService private readonly modeService: IAgentPermissionModeService, ) {} evaluate(context: ResolvedToolExecutionHookContext): PermissionPolicyResult | undefined { diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/plan-mode-guard-deny.ts b/packages/agent-core-v2/src/permissionPolicy/policies/plan-mode-guard-deny.ts index af94a5f41..1d33541c8 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/plan-mode-guard-deny.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/plan-mode-guard-deny.ts @@ -1,5 +1,5 @@ -import { IPlanService } from '#/plan'; -import type { IPlanService as PlanService } from '#/plan'; +import { IAgentPlanService } from '#/plan'; +import type { IAgentPlanService as AgentPlanService } from '#/plan'; import type { ResolvedToolExecutionHookContext } from '#/tool'; import type { PermissionPolicy, @@ -12,7 +12,7 @@ import { export class PlanModeGuardDenyPermissionPolicyService implements PermissionPolicy { readonly name = 'plan-mode-guard-deny'; - constructor(@IPlanService private readonly plan: PlanService) {} + constructor(@IAgentPlanService private readonly plan: AgentPlanService) {} async evaluate( context: ResolvedToolExecutionHookContext, diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/plan-mode-tool-approve.ts b/packages/agent-core-v2/src/permissionPolicy/policies/plan-mode-tool-approve.ts index c0aa34499..b3fe84a00 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/plan-mode-tool-approve.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/plan-mode-tool-approve.ts @@ -1,5 +1,5 @@ -import { IPlanService } from '#/plan'; -import type { IPlanService as PlanService } from '#/plan'; +import { IAgentPlanService } from '#/plan'; +import type { IAgentPlanService as AgentPlanService } from '#/plan'; import type { ResolvedToolExecutionHookContext } from '#/tool'; import type { PermissionPolicy, @@ -10,7 +10,7 @@ import { writesOnlyPlanFile } from './path-utils'; export class PlanModeToolApprovePermissionPolicyService implements PermissionPolicy { readonly name = 'plan-mode-tool-approve'; - constructor(@IPlanService private readonly plan: PlanService) {} + constructor(@IAgentPlanService private readonly plan: AgentPlanService) {} async evaluate( context: ResolvedToolExecutionHookContext, diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/session-approval-history.ts b/packages/agent-core-v2/src/permissionPolicy/policies/session-approval-history.ts index 5911bd56f..4b7bb8044 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/session-approval-history.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/session-approval-history.ts @@ -1,6 +1,6 @@ import type { ResolvedToolExecutionHookContext } from '#/tool'; import { matchPermissionRule } from '#/permissionRules'; -import { IPermissionRulesService } from '../../permissionRules/permissionRules'; +import { IAgentPermissionRulesService } from '../../permissionRules/permissionRules'; import type { PermissionPolicy, PermissionPolicyResult, @@ -10,7 +10,7 @@ export class SessionApprovalHistoryPermissionPolicyService implements Permission readonly name = 'session-approval-history'; constructor( - @IPermissionRulesService private readonly rulesService: IPermissionRulesService, + @IAgentPermissionRulesService private readonly rulesService: IAgentPermissionRulesService, ) {} evaluate(context: ResolvedToolExecutionHookContext): PermissionPolicyResult | undefined { diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/swarm-mode-agent-swarm-approve.ts b/packages/agent-core-v2/src/permissionPolicy/policies/swarm-mode-agent-swarm-approve.ts index 897a76a94..5211b9e4b 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/swarm-mode-agent-swarm-approve.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/swarm-mode-agent-swarm-approve.ts @@ -1,5 +1,5 @@ -import { ISwarmService } from '#/swarm'; -import type { ISwarmService as SwarmService } from '#/swarm'; +import { IAgentSwarmService } from '#/swarm'; +import type { IAgentSwarmService as AgentSwarmService } from '#/swarm'; import type { ResolvedToolExecutionHookContext } from '#/tool'; import type { PermissionPolicy, @@ -9,7 +9,7 @@ import type { export class SwarmModeAgentSwarmApprovePermissionPolicyService implements PermissionPolicy { readonly name = 'swarm-mode-agent-swarm-approve'; - constructor(@ISwarmService private readonly swarm: SwarmService) {} + constructor(@IAgentSwarmService private readonly swarm: AgentSwarmService) {} evaluate(context: ResolvedToolExecutionHookContext): PermissionPolicyResult | undefined { if (context.toolCall.name !== 'AgentSwarm') return undefined; diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-allow.ts b/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-allow.ts index dd8119317..332497221 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-allow.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-allow.ts @@ -1,5 +1,5 @@ import type { ResolvedToolExecutionHookContext } from '#/tool'; -import { IPermissionRulesService } from '../../permissionRules/permissionRules'; +import { IAgentPermissionRulesService } from '../../permissionRules/permissionRules'; import type { PermissionPolicy, PermissionPolicyResult, @@ -9,7 +9,7 @@ import { evaluateUserConfiguredRule } from './user-configured-rule'; export class UserConfiguredAllowPermissionPolicyService implements PermissionPolicy { readonly name = 'user-configured-allow'; - constructor(@IPermissionRulesService private readonly rulesService: IPermissionRulesService) {} + constructor(@IAgentPermissionRulesService private readonly rulesService: IAgentPermissionRulesService) {} evaluate(context: ResolvedToolExecutionHookContext): PermissionPolicyResult | undefined { return evaluateUserConfiguredRule(context, 'allow', this.rulesService); diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-ask.ts b/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-ask.ts index 980b6ed4c..03bef2f9b 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-ask.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-ask.ts @@ -1,5 +1,5 @@ import type { ResolvedToolExecutionHookContext } from '#/tool'; -import { IPermissionRulesService } from '../../permissionRules/permissionRules'; +import { IAgentPermissionRulesService } from '../../permissionRules/permissionRules'; import type { PermissionPolicy, PermissionPolicyResult, @@ -9,7 +9,7 @@ import { evaluateUserConfiguredRule } from './user-configured-rule'; export class UserConfiguredAskPermissionPolicyService implements PermissionPolicy { readonly name = 'user-configured-ask'; - constructor(@IPermissionRulesService private readonly rulesService: IPermissionRulesService) {} + constructor(@IAgentPermissionRulesService private readonly rulesService: IAgentPermissionRulesService) {} evaluate(context: ResolvedToolExecutionHookContext): PermissionPolicyResult | undefined { return evaluateUserConfiguredRule(context, 'ask', this.rulesService); diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-deny.ts b/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-deny.ts index bb052a985..679d58cac 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-deny.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-deny.ts @@ -1,5 +1,5 @@ import type { ResolvedToolExecutionHookContext } from '#/tool'; -import { IPermissionRulesService } from '../../permissionRules/permissionRules'; +import { IAgentPermissionRulesService } from '../../permissionRules/permissionRules'; import type { PermissionPolicy, PermissionPolicyResult, @@ -9,7 +9,7 @@ import { evaluateUserConfiguredRule } from './user-configured-rule'; export class UserConfiguredDenyPermissionPolicyService implements PermissionPolicy { readonly name = 'user-configured-deny'; - constructor(@IPermissionRulesService private readonly rulesService: IPermissionRulesService) {} + constructor(@IAgentPermissionRulesService private readonly rulesService: IAgentPermissionRulesService) {} evaluate(context: ResolvedToolExecutionHookContext): PermissionPolicyResult | undefined { return evaluateUserConfiguredRule(context, 'deny', this.rulesService); diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-rule.ts b/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-rule.ts index 2ab19f16c..90225e48b 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-rule.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/user-configured-rule.ts @@ -8,7 +8,7 @@ import { type PermissionRuleMatch, } from '#/permissionRules'; import type { ResolvedToolExecutionHookContext } from '#/tool'; -import type { IPermissionRulesService } from '../../permissionRules/permissionRules'; +import type { IAgentPermissionRulesService } from '../../permissionRules/permissionRules'; import type { PermissionPolicyResult } from '../types'; const USER_CONFIGURED_SCOPES = new Set([ @@ -20,7 +20,7 @@ const USER_CONFIGURED_SCOPES = new Set([ export function evaluateUserConfiguredRule( context: ResolvedToolExecutionHookContext, decision: PermissionRuleDecision, - rulesService: IPermissionRulesService, + rulesService: IAgentPermissionRulesService, ): PermissionPolicyResult | undefined { const match = firstMatchingRule(context, decision, rulesService, USER_CONFIGURED_SCOPES); if (match === undefined) return undefined; @@ -42,7 +42,7 @@ function defaultPermissionRuleDenyMessage(tool: string, reason: string | undefin function firstMatchingRule( context: ResolvedToolExecutionHookContext, decision: PermissionRuleDecision, - rulesService: IPermissionRulesService, + rulesService: IAgentPermissionRulesService, scopes: ReadonlySet, ): PermissionRuleMatch | undefined { const rules = rulesService.rules.filter((rule): rule is PermissionRule => diff --git a/packages/agent-core-v2/src/permissionPolicy/policies/yolo-mode-approve.ts b/packages/agent-core-v2/src/permissionPolicy/policies/yolo-mode-approve.ts index 5ab68ef1b..998bf1f54 100644 --- a/packages/agent-core-v2/src/permissionPolicy/policies/yolo-mode-approve.ts +++ b/packages/agent-core-v2/src/permissionPolicy/policies/yolo-mode-approve.ts @@ -1,4 +1,4 @@ -import { IPermissionModeService } from '../../permissionMode/permissionMode'; +import { IAgentPermissionModeService } from '../../permissionMode/permissionMode'; import type { PermissionPolicy, PermissionPolicyResult, @@ -8,7 +8,7 @@ export class YoloModeApprovePermissionPolicyService implements PermissionPolicy readonly name = 'yolo-mode-approve'; constructor( - @IPermissionModeService private readonly modeService: IPermissionModeService, + @IAgentPermissionModeService private readonly modeService: IAgentPermissionModeService, ) {} evaluate(): PermissionPolicyResult | undefined { diff --git a/packages/agent-core-v2/src/permissionRules/configSection.ts b/packages/agent-core-v2/src/permissionRules/configSection.ts index d7880da63..c00011b0d 100644 --- a/packages/agent-core-v2/src/permissionRules/configSection.ts +++ b/packages/agent-core-v2/src/permissionRules/configSection.ts @@ -6,7 +6,7 @@ * rules), including the snake_case ↔ camelCase TOML transforms that reshape the * on-disk `deny` / `allow` / `ask` lists and the `tool`/`match` shorthand into * the in-memory `rules` array. Registered into `IConfigRegistry` by - * `PermissionRulesService` on construction, so the `config` domain never + * `AgentPermissionRulesService` on construction, so the `config` domain never * imports this domain's types. */ diff --git a/packages/agent-core-v2/src/permissionRules/permissionRules.ts b/packages/agent-core-v2/src/permissionRules/permissionRules.ts index 80e48ee1b..90c0fe5ae 100644 --- a/packages/agent-core-v2/src/permissionRules/permissionRules.ts +++ b/packages/agent-core-v2/src/permissionRules/permissionRules.ts @@ -41,7 +41,7 @@ export interface PermissionRule { readonly reason?: string; } -export interface IPermissionRulesService { +export interface IAgentPermissionRulesService { readonly _serviceBrand: undefined; readonly rules: readonly PermissionRule[]; readonly sessionApprovalRulePatterns: readonly string[]; @@ -55,5 +55,5 @@ export interface IPermissionRulesService { }>; } -export const IPermissionRulesService = - createDecorator('agentPermissionRulesService'); +export const IAgentPermissionRulesService = + createDecorator('agentPermissionRulesService'); diff --git a/packages/agent-core-v2/src/permissionRules/permissionRulesService.ts b/packages/agent-core-v2/src/permissionRules/permissionRulesService.ts index 428e6b4f5..ce1e27c6e 100644 --- a/packages/agent-core-v2/src/permissionRules/permissionRulesService.ts +++ b/packages/agent-core-v2/src/permissionRules/permissionRulesService.ts @@ -7,10 +7,10 @@ import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { OrderedHookSlot } from '../hooks'; import { IConfigRegistry } from '#/config'; -import { IReplayBuilderService } from '#/replayBuilder'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; +import { IAgentWireRecordService } from '#/wireRecord'; import { - IPermissionRulesService, + IAgentPermissionRulesService, type PermissionApprovalResultRecord, type PermissionRule, } from './permissionRules'; @@ -31,7 +31,7 @@ declare module '#/wireRecord' { } -export class PermissionRulesService extends Disposable implements IPermissionRulesService { +export class AgentPermissionRulesService extends Disposable implements IAgentPermissionRulesService { declare readonly _serviceBrand: undefined; private readonly localRules: PermissionRule[] = []; @@ -43,8 +43,8 @@ export class PermissionRulesService extends Disposable implements IPermissionRul }; constructor( - @IWireRecord private readonly wireRecord: IWireRecord, - @IReplayBuilderService private readonly replayBuilder: IReplayBuilderService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentReplayBuilderService private readonly replayBuilder: IAgentReplayBuilderService, @IConfigRegistry configRegistry: IConfigRegistry, ) { super(); @@ -109,8 +109,8 @@ export class PermissionRulesService extends Disposable implements IPermissionRul registerScopedService( LifecycleScope.Agent, - IPermissionRulesService, - PermissionRulesService, + IAgentPermissionRulesService, + AgentPermissionRulesService, InstantiationType.Delayed, 'permissionRules', ); diff --git a/packages/agent-core-v2/src/plan/index.ts b/packages/agent-core-v2/src/plan/index.ts index 8d5c97a0b..f138f333f 100644 --- a/packages/agent-core-v2/src/plan/index.ts +++ b/packages/agent-core-v2/src/plan/index.ts @@ -1,6 +1,6 @@ /** * `plan` domain barrel — re-exports the plan contract (`plan`) and its scoped - * service (`planService`). Importing this barrel registers the `IPlanService` + * service (`planService`). Importing this barrel registers the `IAgentPlanService` * binding into the scope registry. */ diff --git a/packages/agent-core-v2/src/plan/plan.ts b/packages/agent-core-v2/src/plan/plan.ts index 68d2b9f1d..23128c833 100644 --- a/packages/agent-core-v2/src/plan/plan.ts +++ b/packages/agent-core-v2/src/plan/plan.ts @@ -8,7 +8,7 @@ export type PlanData = null | { export type PlanFilePath = string | null; -export interface IPlanService { +export interface IAgentPlanService { readonly _serviceBrand: undefined; enter(id?: string, createFile?: boolean): Promise; cancel(id?: string): void; @@ -17,5 +17,5 @@ export interface IPlanService { status(): Promise; } -export const IPlanService = - createDecorator('agentPlanService'); +export const IAgentPlanService = + createDecorator('agentPlanService'); diff --git a/packages/agent-core-v2/src/plan/planService.ts b/packages/agent-core-v2/src/plan/planService.ts index 170f4f611..4161b64cc 100644 --- a/packages/agent-core-v2/src/plan/planService.ts +++ b/packages/agent-core-v2/src/plan/planService.ts @@ -13,15 +13,15 @@ import { } from "#/_base/di"; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import { generateHeroSlug } from "#/_base/utils/hero-slug"; -import { IContextMemory, type ContextMessage } from '#/contextMemory'; -import { IContextInjector } from '../contextInjector'; -import { IEventSink } from '../eventSink'; -import { IAgentFileSystem } from '#/agentFs'; -import { IProfileService } from '#/profile'; -import { IReplayBuilderService } from '#/replayBuilder'; +import { IAgentContextMemoryService, type ContextMessage } from '#/contextMemory'; +import { IAgentContextInjectorService } from '../contextInjector'; +import { IAgentEventSinkService } from '../eventSink'; +import { ISessionAgentFileSystem } from '#/agentFs'; +import { IAgentProfileService } from '#/profile'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { IAgentWireRecordService } from '#/wireRecord'; import type { ToolInputDisplay } from '@moonshot-ai/protocol'; import type { ExecutableToolResult } from '#/tool'; import { EnterPlanModeInputSchema } from './tools/enter-plan-mode'; @@ -32,7 +32,7 @@ import { } from './tools/exit-plan-mode'; import EXIT_PLAN_MODE_DESCRIPTION from './tools/exit-plan-mode.md?raw'; import { - IPlanService, + IAgentPlanService, type PlanData, type PlanFilePath, } from './plan'; @@ -56,7 +56,7 @@ const PLAN_MODE_DEDUP_MIN_TURNS = 2; const PLAN_MODE_FULL_REFRESH_TURNS = 5; const PLAN_MODE_INJECTION_VARIANT = 'plan_mode'; -export class PlanService extends Disposable implements IPlanService { +export class AgentPlanService extends Disposable implements IAgentPlanService { declare readonly _serviceBrand: undefined; private _active = false; @@ -64,14 +64,14 @@ export class PlanService extends Disposable implements IPlanService { private _planFilePath: PlanFilePath = null; constructor( - @IContextMemory private readonly context: IContextMemory, - @IWireRecord private readonly wireRecord: IWireRecord, - @IEventSink private readonly events: IEventSink, - @IAgentFileSystem private readonly agentFs: IAgentFileSystem, - @IProfileService private readonly profile: IProfileService, - @IReplayBuilderService private readonly replayBuilder: IReplayBuilderService, - @IToolRegistry toolRegistry: IToolRegistry, - @IContextInjector dynamicInjector: IContextInjector, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @ISessionAgentFileSystem private readonly agentFs: ISessionAgentFileSystem, + @IAgentProfileService private readonly profile: IAgentProfileService, + @IAgentReplayBuilderService private readonly replayBuilder: IAgentReplayBuilderService, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, + @IAgentContextInjectorService dynamicInjector: IAgentContextInjectorService, @ITelemetryService private readonly telemetry: ITelemetryService, ) { super(); @@ -555,12 +555,12 @@ function isMissingFileError(error: unknown): boolean { return code === 'ENOENT'; } -export { PlanService as Plan }; +export { AgentPlanService as Plan }; registerScopedService( LifecycleScope.Agent, - IPlanService, - PlanService, + IAgentPlanService, + AgentPlanService, InstantiationType.Delayed, 'plan', ); diff --git a/packages/agent-core-v2/src/plan/tools/enter-plan-mode.ts b/packages/agent-core-v2/src/plan/tools/enter-plan-mode.ts index 0db53adfd..39f7f09f5 100644 --- a/packages/agent-core-v2/src/plan/tools/enter-plan-mode.ts +++ b/packages/agent-core-v2/src/plan/tools/enter-plan-mode.ts @@ -11,7 +11,7 @@ import type { BuiltinTool } from '#/tool'; import type { ToolExecution } from '#/tool'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import type { ITelemetryService } from '#/telemetry'; -import type { IPlanService } from '../plan'; +import type { IAgentPlanService } from '../plan'; import DESCRIPTION from './enter-plan-mode.md?raw'; // ── Input schema ───────────────────────────────────────────────────── @@ -25,7 +25,7 @@ export class EnterPlanModeTool implements BuiltinTool { readonly parameters: Record = toInputJsonSchema(EnterPlanModeInputSchema); constructor( - private readonly planMode: IPlanService, + private readonly planMode: IAgentPlanService, private readonly telemetry: ITelemetryService, ) {} diff --git a/packages/agent-core-v2/src/plan/tools/exit-plan-mode.ts b/packages/agent-core-v2/src/plan/tools/exit-plan-mode.ts index 10108c0b3..d2f32ffe0 100644 --- a/packages/agent-core-v2/src/plan/tools/exit-plan-mode.ts +++ b/packages/agent-core-v2/src/plan/tools/exit-plan-mode.ts @@ -13,7 +13,7 @@ import type { BuiltinTool } from '#/tool'; import type { ExecutableToolResult, ToolExecution } from '#/tool'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import type { ITelemetryService } from '#/telemetry'; -import type { IPlanService, PlanData } from '../plan'; +import type { IAgentPlanService, PlanData } from '../plan'; import DESCRIPTION from './exit-plan-mode.md?raw'; // ── Input schema ───────────────────────────────────────────────────── @@ -85,7 +85,7 @@ export class ExitPlanModeTool implements BuiltinTool { readonly parameters: Record = toInputJsonSchema(ExitPlanModeInputSchema); constructor( - private readonly planMode: IPlanService, + private readonly planMode: IAgentPlanService, private readonly telemetry: ITelemetryService, ) {} diff --git a/packages/agent-core-v2/src/process/index.ts b/packages/agent-core-v2/src/process/index.ts index 408a6742f..a8cd96f76 100644 --- a/packages/agent-core-v2/src/process/index.ts +++ b/packages/agent-core-v2/src/process/index.ts @@ -1,7 +1,7 @@ /** * `process` domain barrel — re-exports the process contract (`process`) and * its scoped service (`processRunnerService`). Importing this barrel registers - * the `IProcessRunner` binding into the scope registry. + * the `ISessionProcessRunner` binding into the scope registry. */ export * from './process'; diff --git a/packages/agent-core-v2/src/process/process.ts b/packages/agent-core-v2/src/process/process.ts index 4a8486b76..ecfa149fa 100644 --- a/packages/agent-core-v2/src/process/process.ts +++ b/packages/agent-core-v2/src/process/process.ts @@ -1,10 +1,10 @@ /** * `process` domain (L1) — the Agent's process runner. * - * Defines the `IProcessRunner` that business code injects to spawn processes + * Defines the `ISessionProcessRunner` that business code injects to spawn processes * inside the Agent's execution environment, plus the `IProcess` handle it * returns. Session-scoped and backed by the session `IKaos`; business code - * depends on `IProcessRunner` only. + * depends on `ISessionProcessRunner` only. */ import type { Readable, Writable } from 'node:stream'; @@ -27,11 +27,11 @@ export interface ProcessExecOptions { readonly env?: Record; } -export interface IProcessRunner { +export interface ISessionProcessRunner { readonly _serviceBrand: undefined; exec(args: readonly string[], options?: ProcessExecOptions): Promise; } -export const IProcessRunner: ServiceIdentifier = - createDecorator('processRunner'); +export const ISessionProcessRunner: ServiceIdentifier = + createDecorator('sessionProcessRunner'); diff --git a/packages/agent-core-v2/src/process/processRunnerService.ts b/packages/agent-core-v2/src/process/processRunnerService.ts index 1d146620b..c03531306 100644 --- a/packages/agent-core-v2/src/process/processRunnerService.ts +++ b/packages/agent-core-v2/src/process/processRunnerService.ts @@ -1,5 +1,5 @@ /** - * `process` domain (L1) — `IProcessRunner` implementation. + * `process` domain (L1) — `ISessionProcessRunner` implementation. * * Spawns processes through the session execution environment (`IKaos.backend`), * defaulting cwd/env to the execution environment and honoring per-call @@ -10,9 +10,9 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { IKaos } from '#/kaos'; -import { type IProcess, IProcessRunner, type ProcessExecOptions } from './process'; +import { type IProcess, ISessionProcessRunner, type ProcessExecOptions } from './process'; -export class ProcessRunner implements IProcessRunner { +export class SessionProcessRunner implements ISessionProcessRunner { declare readonly _serviceBrand: undefined; constructor(@IKaos private readonly kaos: IKaos) {} @@ -29,8 +29,8 @@ export class ProcessRunner implements IProcessRunner { registerScopedService( LifecycleScope.Session, - IProcessRunner, - ProcessRunner, + ISessionProcessRunner, + SessionProcessRunner, InstantiationType.Delayed, 'process', ); diff --git a/packages/agent-core-v2/src/profile/profile.ts b/packages/agent-core-v2/src/profile/profile.ts index 4ef3bcc79..6c18510d4 100644 --- a/packages/agent-core-v2/src/profile/profile.ts +++ b/packages/agent-core-v2/src/profile/profile.ts @@ -78,7 +78,7 @@ export interface ProfileSetModelResult { readonly providerName?: string | undefined; } -export interface IProfileService { +export interface IAgentProfileService { readonly _serviceBrand: undefined; configure(options: ProfileServiceOptions): void; update(changed: ProfileUpdateData): void; @@ -106,4 +106,4 @@ export interface IProfileService { removeActiveTool(name: string): void; } -export const IProfileService = createDecorator('profileService.agent'); +export const IAgentProfileService = createDecorator('agentProfileService'); diff --git a/packages/agent-core-v2/src/profile/profileService.ts b/packages/agent-core-v2/src/profile/profileService.ts index 7df9dee45..c43fc968b 100644 --- a/packages/agent-core-v2/src/profile/profileService.ts +++ b/packages/agent-core-v2/src/profile/profileService.ts @@ -1,9 +1,9 @@ /** - * `profile` domain (L3) — `IProfileService` implementation. + * `profile` domain (L3) — `IAgentProfileService` implementation. * * Owns the active agent's model alias, thinking level, system prompt, and * active-tool set; resolves the runtime provider through `modelRuntime` - * `IModelResolver`, builds the protocol adapter through `chatProvider` + * `ISessionModelResolver`, builds the protocol adapter through `chatProvider` * `IChatProviderFactory`, applies completion budget through * `completion-budget`, persists profile changes through `wireRecord`, and * emits status through `eventBus`. Bound at Agent scope. @@ -25,14 +25,14 @@ import { resolveThinkingEffort, type ThinkingEffort } from '#/config/thinking'; import { applyKimiModelOverrides, IChatProviderFactory, type KimiModelOverrides } from '#/chatProvider'; import type { LoopControl } from '#/loop/configSection'; import { isMcpToolName } from '#/tool'; -import { IModelResolver, type ResolvedModel } from '#/modelRuntime'; +import { ISessionModelResolver, type ResolvedModel } from '#/modelRuntime'; import type { ResolvedAgentProfile, SystemPromptContext } from '#/profile'; -import { IEventSink } from '../eventSink'; -import { IReplayBuilderService } from '#/replayBuilder'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; import { ITelemetryService } from '#/telemetry'; import type { ToolSource } from '#/tool'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import type { ProfileData, ProfileModelContext, @@ -40,7 +40,7 @@ import type { ProfileSetModelResult, ProfileUpdateData, } from './profile'; -import { IProfileService } from './profile'; +import { IAgentProfileService } from './profile'; import { DEFAULT_THINKING_SECTION, defaultThinkingEnvBindings, @@ -59,7 +59,7 @@ declare module '#/wireRecord' { } } -export class ProfileService implements IProfileService { +export class AgentProfileService implements IAgentProfileService { declare readonly _serviceBrand: undefined; private optionsValue: ProfileServiceOptions = {}; @@ -71,13 +71,13 @@ export class ProfileService implements IProfileService { private activeToolNames: readonly string[] | undefined; constructor( - @IWireRecord private readonly wireRecord: IWireRecord, - @IEventSink private readonly events: IEventSink, - @IReplayBuilderService private readonly replayBuilder: IReplayBuilderService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentReplayBuilderService private readonly replayBuilder: IAgentReplayBuilderService, @ITelemetryService private readonly telemetry: ITelemetryService, @IConfigRegistry configRegistry: IConfigRegistry, @IConfigService private readonly config: IConfigService, - @IModelResolver private readonly modelResolver: IModelResolver, + @ISessionModelResolver private readonly modelResolver: ISessionModelResolver, @IChatProviderFactory private readonly chatProviders: IChatProviderFactory, ) { configRegistry.registerSection(THINKING_SECTION, ThinkingConfigSchema, { @@ -355,8 +355,8 @@ export class ProfileService implements IProfileService { registerScopedService( LifecycleScope.Agent, - IProfileService, - ProfileService, + IAgentProfileService, + AgentProfileService, InstantiationType.Delayed, 'profile', ); diff --git a/packages/agent-core-v2/src/prompt/prompt.ts b/packages/agent-core-v2/src/prompt/prompt.ts index a28e3bcb9..856cbb749 100644 --- a/packages/agent-core-v2/src/prompt/prompt.ts +++ b/packages/agent-core-v2/src/prompt/prompt.ts @@ -3,7 +3,7 @@ import type { ContextMessage } from "#/contextMemory"; import type { Turn } from "#/turn"; -export interface IPromptService { +export interface IAgentPromptService { readonly _serviceBrand: undefined; prompt(message: ContextMessage): Turn | undefined; steer(message: ContextMessage): Turn | undefined; @@ -12,4 +12,4 @@ export interface IPromptService { clear(): void; } -export const IPromptService = createDecorator('promptService.agent'); +export const IAgentPromptService = createDecorator('agentPromptService'); diff --git a/packages/agent-core-v2/src/prompt/promptService.ts b/packages/agent-core-v2/src/prompt/promptService.ts index 09386437c..510159797 100644 --- a/packages/agent-core-v2/src/prompt/promptService.ts +++ b/packages/agent-core-v2/src/prompt/promptService.ts @@ -4,25 +4,25 @@ import { ErrorCodes, KimiError, makeErrorPayload } from "#/errors"; import { ensureMessageId, - IContextMemory, + IAgentContextMemoryService, USER_PROMPT_ORIGIN, type ContextMessage, } from '#/contextMemory'; -import { IEventSink } from '../eventSink'; -import { ITurnService, type Turn } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; -import { IPromptService } from './prompt'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentTurnService, type Turn } from '#/turn'; +import { IAgentWireRecordService } from '#/wireRecord'; +import { IAgentPromptService } from './prompt'; -export class PromptService implements IPromptService { +export class AgentPromptService implements IAgentPromptService { declare readonly _serviceBrand: undefined; private readonly steerQueue: ContextMessage[] = []; private observedTurn: Turn | undefined; constructor( - @IContextMemory private readonly context: IContextMemory, - @ITurnService private readonly turnService: ITurnService, - @IWireRecord private readonly wireRecord: IWireRecord, - @IEventSink private readonly events: IEventSink, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentTurnService private readonly turnService: IAgentTurnService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, ) { turnService.hooks.beforeStep.register('prompt-service-steer-before-step', async (_ctx, next) => { this.flushSteerQueue(); @@ -179,8 +179,8 @@ function formatPromptCount(count: number): string { registerScopedService( LifecycleScope.Agent, - IPromptService, - PromptService, + IAgentPromptService, + AgentPromptService, InstantiationType.Delayed, 'prompt', ); diff --git a/packages/agent-core-v2/src/promptLegacy/promptLegacy.ts b/packages/agent-core-v2/src/promptLegacy/promptLegacy.ts index 3c64f8589..5ca4a7b76 100644 --- a/packages/agent-core-v2/src/promptLegacy/promptLegacy.ts +++ b/packages/agent-core-v2/src/promptLegacy/promptLegacy.ts @@ -3,7 +3,7 @@ * * Implements the legacy `/api/v1` prompt contract (`submit` / `list` / `steer` * / `abort` with `prompt_id`, a FIFO queue, and `prompt.*` lifecycle events) on - * top of the v2 turn-driver (`IPromptService`). v2's native `IPromptService` + * top of the v2 turn-driver (`IAgentPromptService`). v2's native `IAgentPromptService` * (turn-is-the-submission, no queue) is untouched and continues to serve * `/api/v2`. This service exists purely so clients of the v1 server keep * working against server-v2. Bound at Agent scope — the queue and the active @@ -20,7 +20,7 @@ import type { import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; -export interface IPromptLegacyService { +export interface IAgentPromptLegacyService { readonly _serviceBrand: undefined; list(): PromptListResponse; submit(body: PromptSubmission): Promise; @@ -28,5 +28,5 @@ export interface IPromptLegacyService { abort(promptId: string): Promise; } -export const IPromptLegacyService: ServiceIdentifier = - createDecorator('promptLegacyService.agent'); +export const IAgentPromptLegacyService: ServiceIdentifier = + createDecorator('agentPromptLegacyService'); diff --git a/packages/agent-core-v2/src/promptLegacy/promptLegacyService.ts b/packages/agent-core-v2/src/promptLegacy/promptLegacyService.ts index 4059428c8..b9d3dc1b7 100644 --- a/packages/agent-core-v2/src/promptLegacy/promptLegacyService.ts +++ b/packages/agent-core-v2/src/promptLegacy/promptLegacyService.ts @@ -1,8 +1,8 @@ /** - * `promptLegacy` domain — `IPromptLegacyService` implementation. + * `promptLegacy` domain — `IAgentPromptLegacyService` implementation. * * Per-agent v1-compatible scheduler. Owns the active submission and a FIFO - * queue; launches turns through `IPromptService` and observes them to + * queue; launches turns through `IAgentPromptService` and observes them to * auto-start the next queued prompt. Legacy `prompt.*` lifecycle events are * not emitted (they are not part of the v2 `AgentEvent` union); the HTTP * responses carry the same information. @@ -12,10 +12,10 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { newMessageId } from '#/contextMemory'; import { ErrorCodes, KimiError } from '#/errors'; -import { IPermissionModeService } from '#/permissionMode/permissionMode'; -import { IProfileService } from '#/profile/profile'; -import { IPromptService } from '#/prompt/prompt'; -import { ITurnService, type Turn, type TurnResult } from '#/turn/turn'; +import { IAgentPermissionModeService } from '#/permissionMode/permissionMode'; +import { IAgentProfileService } from '#/profile/profile'; +import { IAgentPromptService } from '#/prompt/prompt'; +import { IAgentTurnService, type Turn, type TurnResult } from '#/turn/turn'; import type { ContentPart } from '@moonshot-ai/kosong'; import type { PromptAbortResponse, @@ -26,7 +26,7 @@ import type { PromptSubmitResult, } from '@moonshot-ai/protocol'; -import { IPromptLegacyService } from './promptLegacy'; +import { IAgentPromptLegacyService } from './promptLegacy'; interface PromptRecord { readonly promptId: string; @@ -39,7 +39,7 @@ interface ActivePrompt extends PromptRecord { readonly turn: Turn; } -export class PromptLegacyService implements IPromptLegacyService { +export class AgentPromptLegacyService implements IAgentPromptLegacyService { declare readonly _serviceBrand: undefined; private active: ActivePrompt | undefined; @@ -48,10 +48,10 @@ export class PromptLegacyService implements IPromptLegacyService { private readonly abortedPromptIds = new Set(); constructor( - @IPromptService private readonly prompt: IPromptService, - @ITurnService private readonly turnService: ITurnService, - @IProfileService private readonly profile: IProfileService, - @IPermissionModeService private readonly permissionMode: IPermissionModeService, + @IAgentPromptService private readonly prompt: IAgentPromptService, + @IAgentTurnService private readonly turnService: IAgentTurnService, + @IAgentProfileService private readonly profile: IAgentProfileService, + @IAgentPermissionModeService private readonly permissionMode: IAgentPermissionModeService, ) {} list(): PromptListResponse { @@ -234,8 +234,8 @@ function contentToCoreParts(content: PromptSubmission['content']): ContentPart[] registerScopedService( LifecycleScope.Agent, - IPromptLegacyService, - PromptLegacyService, + IAgentPromptLegacyService, + AgentPromptLegacyService, InstantiationType.Delayed, 'promptLegacy', ); diff --git a/packages/agent-core-v2/src/provider/provider.ts b/packages/agent-core-v2/src/provider/provider.ts index 5a7154e64..77e4dff3b 100644 --- a/packages/agent-core-v2/src/provider/provider.ts +++ b/packages/agent-core-v2/src/provider/provider.ts @@ -3,7 +3,7 @@ * * Owns the `ProviderConfig` / `OAuthRef` models and the `providers` config * section; exposes CRUD over provider configurations and persists them through - * `config`. Core-scoped — provider configuration is global and shared across + * `config`. App-scoped — provider configuration is global and shared across * sessions. Higher-level services (OAuth, CLI, UI, modelRuntime) mutate providers * through this domain instead of writing config directly. */ diff --git a/packages/agent-core-v2/src/provider/providerService.ts b/packages/agent-core-v2/src/provider/providerService.ts index 9c0ed98bf..c66f8f5af 100644 --- a/packages/agent-core-v2/src/provider/providerService.ts +++ b/packages/agent-core-v2/src/provider/providerService.ts @@ -3,7 +3,7 @@ * * Owns the in-memory view of the `providers` config section, persists changes * through `config`, registers the section schema on construction, and forwards - * section changes as `onDidChange`. Bound at Core scope. + * section changes as `onDidChange`. Bound at App scope. */ import { InstantiationType } from '#/_base/di/extensions'; @@ -72,4 +72,4 @@ export class ProviderService extends Disposable implements IProviderService { } } -registerScopedService(LifecycleScope.Core, IProviderService, ProviderService, InstantiationType.Delayed, 'provider'); +registerScopedService(LifecycleScope.App, IProviderService, ProviderService, InstantiationType.Delayed, 'provider'); diff --git a/packages/agent-core-v2/src/question/index.ts b/packages/agent-core-v2/src/question/index.ts index f30ce2f13..a572b58f6 100644 --- a/packages/agent-core-v2/src/question/index.ts +++ b/packages/agent-core-v2/src/question/index.ts @@ -1,7 +1,7 @@ /** * `question` domain barrel — re-exports the question contract (`question`) and * its scoped service (`questionService`). Importing this barrel registers the - * `IQuestionService` binding into the scope registry. + * `ISessionQuestionService` binding into the scope registry. */ export * from './question'; diff --git a/packages/agent-core-v2/src/question/question.ts b/packages/agent-core-v2/src/question/question.ts index 8f4abac6c..28afd040f 100644 --- a/packages/agent-core-v2/src/question/question.ts +++ b/packages/agent-core-v2/src/question/question.ts @@ -3,7 +3,7 @@ * * Defines the public contract of asking the user: the rich in-process * `QuestionRequest` model (mirrors the `agent-core` SDK shape — a batch of - * `QuestionItem`s, each with its own options) and the `IQuestionService` used + * `QuestionItem`s, each with its own options) and the `ISessionQuestionService` used * to post a request, supply its answer, dismiss it, and list pending requests. * * The model is the **in-process** representation (camelCase, options carry no @@ -51,7 +51,7 @@ export interface QuestionRequest { readonly questions: readonly QuestionItem[]; } -export interface IQuestionService { +export interface ISessionQuestionService { readonly _serviceBrand: undefined; request(req: QuestionRequest): Promise; /** @@ -67,5 +67,5 @@ export interface IQuestionService { listPending(): readonly QuestionRequest[]; } -export const IQuestionService: ServiceIdentifier = - createDecorator('questionService'); +export const ISessionQuestionService: ServiceIdentifier = + createDecorator('sessionQuestionService'); diff --git a/packages/agent-core-v2/src/question/questionService.ts b/packages/agent-core-v2/src/question/questionService.ts index 29d172fe4..c12f0aa1f 100644 --- a/packages/agent-core-v2/src/question/questionService.ts +++ b/packages/agent-core-v2/src/question/questionService.ts @@ -1,5 +1,5 @@ /** - * `question` domain (L7) — `IQuestionService` implementation. + * `question` domain (L7) — `ISessionQuestionService` implementation. * * Typed facade over the `interaction` kernel for ask-user requests; owns no * pending state of its own (the kernel holds it). Bound at Session scope. @@ -7,18 +7,18 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IInteractionService } from '#/interaction'; +import { ISessionInteractionService } from '#/interaction'; import { type QuestionRequest, type QuestionResult, - IQuestionService, + ISessionQuestionService, } from './question'; -export class QuestionService implements IQuestionService { +export class SessionQuestionService implements ISessionQuestionService { declare readonly _serviceBrand: undefined; - constructor(@IInteractionService private readonly interaction: IInteractionService) {} + constructor(@ISessionInteractionService private readonly interaction: ISessionInteractionService) {} request(req: QuestionRequest): Promise { return this.interaction.request({ @@ -59,4 +59,4 @@ function requestId(req: QuestionRequest): string { return req.id ?? req.toolCallId ?? `question:${String(Date.now())}`; } -registerScopedService(LifecycleScope.Session, IQuestionService, QuestionService, InstantiationType.Delayed, 'question'); +registerScopedService(LifecycleScope.Session, ISessionQuestionService, SessionQuestionService, InstantiationType.Delayed, 'question'); diff --git a/packages/agent-core-v2/src/question/questionTools.ts b/packages/agent-core-v2/src/question/questionTools.ts index fa8f8861f..b445fe339 100644 --- a/packages/agent-core-v2/src/question/questionTools.ts +++ b/packages/agent-core-v2/src/question/questionTools.ts @@ -1,18 +1,18 @@ /** * `question` domain (L7) — ask-user tool registration contract. * - * `IQuestionToolsService` is a marker: its implementation registers the - * built-in `AskUserQuestion` tool into the agent `IToolRegistry` on + * `IAgentQuestionToolsService` is a marker: its implementation registers the + * built-in `AskUserQuestion` tool into the agent `IAgentToolRegistryService` on * construction. Bound at Agent scope (the tool needs the agent-scoped - * `IToolRegistry` and `IBackgroundService`, plus the session-scoped - * `IQuestionService`). + * `IAgentToolRegistryService` and `IAgentBackgroundService`, plus the session-scoped + * `ISessionQuestionService`). */ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; -export interface IQuestionToolsService { +export interface IAgentQuestionToolsService { readonly _serviceBrand: undefined; } -export const IQuestionToolsService: ServiceIdentifier = - createDecorator('questionToolsService'); +export const IAgentQuestionToolsService: ServiceIdentifier = + createDecorator('agentQuestionToolsService'); diff --git a/packages/agent-core-v2/src/question/questionToolsService.ts b/packages/agent-core-v2/src/question/questionToolsService.ts index e751d8348..546aee469 100644 --- a/packages/agent-core-v2/src/question/questionToolsService.ts +++ b/packages/agent-core-v2/src/question/questionToolsService.ts @@ -1,29 +1,29 @@ /** - * `question` domain (L7) — `IQuestionToolsService` implementation. + * `question` domain (L7) — `IAgentQuestionToolsService` implementation. * - * Registers the built-in `AskUserQuestion` tool into the agent `IToolRegistry` - * on construction, wiring it to the session `IQuestionService` (ask-user - * broker), the agent `IBackgroundService` (background-question lifecycle) and + * Registers the built-in `AskUserQuestion` tool into the agent `IAgentToolRegistryService` + * on construction, wiring it to the session `ISessionQuestionService` (ask-user + * broker), the agent `IAgentBackgroundService` (background-question lifecycle) and * `ITelemetryService`. Bound at Agent scope. */ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IBackgroundService } from '#/background'; +import { IAgentBackgroundService } from '#/background'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; -import { IQuestionService } from './question'; -import { IQuestionToolsService } from './questionTools'; +import { ISessionQuestionService } from './question'; +import { IAgentQuestionToolsService } from './questionTools'; import { AskUserQuestionTool } from './tools/ask-user'; -export class QuestionToolsService implements IQuestionToolsService { +export class AgentQuestionToolsService implements IAgentQuestionToolsService { declare readonly _serviceBrand: undefined; constructor( - @IToolRegistry toolRegistry: IToolRegistry, - @IQuestionService question: IQuestionService, - @IBackgroundService background: IBackgroundService, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, + @ISessionQuestionService question: ISessionQuestionService, + @IAgentBackgroundService background: IAgentBackgroundService, @ITelemetryService telemetry: ITelemetryService, ) { toolRegistry.register(new AskUserQuestionTool(question, background, telemetry)); @@ -32,8 +32,8 @@ export class QuestionToolsService implements IQuestionToolsService { registerScopedService( LifecycleScope.Agent, - IQuestionToolsService, - QuestionToolsService, + IAgentQuestionToolsService, + AgentQuestionToolsService, InstantiationType.Delayed, 'questionTools', ); diff --git a/packages/agent-core-v2/src/question/tools/ask-user.ts b/packages/agent-core-v2/src/question/tools/ask-user.ts index 1f32d1632..c4dbcbb9e 100644 --- a/packages/agent-core-v2/src/question/tools/ask-user.ts +++ b/packages/agent-core-v2/src/question/tools/ask-user.ts @@ -11,7 +11,7 @@ import { z } from 'zod'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; -import { QuestionBackgroundTask, type IBackgroundService } from '#/background'; +import { QuestionBackgroundTask, type IAgentBackgroundService } from '#/background'; import type { ITelemetryService, TelemetryProperties } from '#/telemetry'; import type { BuiltinTool, @@ -21,7 +21,7 @@ import type { } from '#/tool'; import type { - IQuestionService, + ISessionQuestionService, QuestionAnswers, QuestionAnswerMethod, QuestionResponse, @@ -99,8 +99,8 @@ export class AskUserQuestionTool implements BuiltinTool { ); constructor( - private readonly question: IQuestionService, - private readonly background: IBackgroundService, + private readonly question: ISessionQuestionService, + private readonly background: IAgentBackgroundService, private readonly telemetry: ITelemetryService, ) {} diff --git a/packages/agent-core-v2/src/replayBuilder/replayBuilder.ts b/packages/agent-core-v2/src/replayBuilder/replayBuilder.ts index 44f6d3acc..fdb4c7dc8 100644 --- a/packages/agent-core-v2/src/replayBuilder/replayBuilder.ts +++ b/packages/agent-core-v2/src/replayBuilder/replayBuilder.ts @@ -12,7 +12,7 @@ export interface ReplayBuilderServiceOptions { readonly range?: ReplayRangeOptions; } -export interface IReplayBuilderService { +export interface IAgentReplayBuilderService { readonly _serviceBrand: undefined; postRestoring: boolean; @@ -28,6 +28,6 @@ export interface IReplayBuilderService { buildResult(): readonly AgentReplayRecord[]; } -export const IReplayBuilderService = createDecorator( +export const IAgentReplayBuilderService = createDecorator( 'agentReplayBuilderService', ); diff --git a/packages/agent-core-v2/src/replayBuilder/replayBuilderService.ts b/packages/agent-core-v2/src/replayBuilder/replayBuilderService.ts index 3b642a5c9..059e76ae0 100644 --- a/packages/agent-core-v2/src/replayBuilder/replayBuilderService.ts +++ b/packages/agent-core-v2/src/replayBuilder/replayBuilderService.ts @@ -7,9 +7,9 @@ import type { AgentReplayRecord, AgentReplayRecordPayload } from './types'; import type { ContextMessage } from "#/contextMemory"; import type { WireRecord } from "#/wireRecord"; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { - IReplayBuilderService, + IAgentReplayBuilderService, type ReplayBuilderServiceOptions, } from './replayBuilder'; @@ -24,7 +24,7 @@ function isUndoBoundaryRecord(record: WireRecord): boolean { return record.type === 'context.splice' && record.start === 0 && record.deleteCount > 0; } -export class ReplayBuilderService extends Disposable implements IReplayBuilderService { +export class AgentReplayBuilderService extends Disposable implements IAgentReplayBuilderService { declare readonly _serviceBrand: undefined; captureLiveRecords = false; @@ -36,7 +36,7 @@ export class ReplayBuilderService extends Disposable implements IReplayBuilderSe constructor( private readonly options: ReplayBuilderServiceOptions = {}, - @IWireRecord private readonly wireRecord: IWireRecord, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, ) { super(); this._register( @@ -142,8 +142,8 @@ export class ReplayBuilderService extends Disposable implements IReplayBuilderSe registerScopedService( LifecycleScope.Agent, - IReplayBuilderService, - ReplayBuilderService, + IAgentReplayBuilderService, + AgentReplayBuilderService, InstantiationType.Delayed, 'replayBuilder', ); diff --git a/packages/agent-core-v2/src/rpc/rpcService.ts b/packages/agent-core-v2/src/rpc/rpcService.ts index ad57791a0..7216b9fa9 100644 --- a/packages/agent-core-v2/src/rpc/rpcService.ts +++ b/packages/agent-core-v2/src/rpc/rpcService.ts @@ -1,28 +1,28 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IBackgroundService } from '#/background'; -import { IContextMemory } from '#/contextMemory'; -import { IContextSizeService } from '#/contextSize'; -import { IFileToolsService } from '#/fileTools'; -import { IFullCompaction } from '#/fullCompaction'; -import { IGoalService } from '#/goal'; +import { IAgentBackgroundService } from '#/background'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentContextSizeService } from '#/contextSize'; +import { IAgentFileToolsService } from '#/fileTools'; +import { IAgentFullCompactionService } from '#/fullCompaction'; +import { IAgentGoalService } from '#/goal'; import { userCancellationReason } from '#/_base/utils/abort'; -import { IPermissionGate } from '#/permissionGate'; -import { IPermissionModeService } from '#/permissionMode/permissionMode'; -import { IPlanService } from '../plan'; -import { IProfileService } from '#/profile'; -import { IPromptService } from '#/prompt'; -import { IQuestionToolsService } from '#/question'; -import { IShellToolsService } from '#/shellTools'; +import { IAgentPermissionGate } from '#/permissionGate'; +import { IAgentPermissionModeService } from '#/permissionMode/permissionMode'; +import { IAgentPlanService } from '../plan'; +import { IAgentProfileService } from '#/profile'; +import { IAgentPromptService } from '#/prompt'; +import { IAgentQuestionToolsService } from '#/question'; +import { IAgentShellToolsService } from '#/shellTools'; import { IAgentSkillService } from '#/skill'; -import { ISubagentHost } from '#/subagentHost'; -import { ISwarmService } from '../swarm'; +import { ISessionSubagentHost } from '#/subagentHost'; +import { IAgentSwarmService } from '../swarm'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; -import { ITurnService } from '../turn'; -import { IUsageService } from '#/usage'; -import { IUserToolService } from '#/userTool'; -import { IWebService } from '#/web'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { IAgentTurnService } from '../turn'; +import { IAgentUsageService } from '#/usage'; +import { IAgentUserToolService } from '#/userTool'; +import { IAgentWebService } from '#/web'; import type { ActivateSkillPayload, BeginCompactionPayload, @@ -51,28 +51,28 @@ import { IAgentRPCService } from './rpc'; export class AgentRPCService implements IAgentRPCService { declare readonly _serviceBrand: undefined; constructor( - @IPromptService private readonly promptService: IPromptService, - @ITurnService private readonly turnService: ITurnService, - @IProfileService private readonly profile: IProfileService, - @IPermissionModeService private readonly permissionMode: IPermissionModeService, - @IPermissionGate private readonly permission: IPermissionGate, - @IPlanService private readonly planMode: IPlanService, - @ISwarmService private readonly swarmMode: ISwarmService, - @IFullCompaction private readonly fullCompaction: IFullCompaction, - @IUserToolService private readonly userTools: IUserToolService, - @IToolRegistry private readonly toolRegistry: IToolRegistry, - @IFileToolsService private readonly fileTools: IFileToolsService, - @IShellToolsService private readonly shellTools: IShellToolsService, - @IBackgroundService private readonly background: IBackgroundService, - @IContextMemory private readonly context: IContextMemory, - @IContextSizeService private readonly contextSize: IContextSizeService, + @IAgentPromptService private readonly promptService: IAgentPromptService, + @IAgentTurnService private readonly turnService: IAgentTurnService, + @IAgentProfileService private readonly profile: IAgentProfileService, + @IAgentPermissionModeService private readonly permissionMode: IAgentPermissionModeService, + @IAgentPermissionGate private readonly permission: IAgentPermissionGate, + @IAgentPlanService private readonly planMode: IAgentPlanService, + @IAgentSwarmService private readonly swarmMode: IAgentSwarmService, + @IAgentFullCompactionService private readonly fullCompaction: IAgentFullCompactionService, + @IAgentUserToolService private readonly userTools: IAgentUserToolService, + @IAgentToolRegistryService private readonly toolRegistry: IAgentToolRegistryService, + @IAgentFileToolsService private readonly fileTools: IAgentFileToolsService, + @IAgentShellToolsService private readonly shellTools: IAgentShellToolsService, + @IAgentBackgroundService private readonly background: IAgentBackgroundService, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentContextSizeService private readonly contextSize: IAgentContextSizeService, @IAgentSkillService private readonly skills: IAgentSkillService, - @ISubagentHost private readonly subagentHost: ISubagentHost, - @IUsageService private readonly usage: IUsageService, + @ISessionSubagentHost private readonly subagentHost: ISessionSubagentHost, + @IAgentUsageService private readonly usage: IAgentUsageService, @ITelemetryService private readonly telemetry: ITelemetryService, - @IGoalService private readonly goal: IGoalService, - @IQuestionToolsService private readonly questionTools: IQuestionToolsService, - @IWebService private readonly web: IWebService, + @IAgentGoalService private readonly goal: IAgentGoalService, + @IAgentQuestionToolsService private readonly questionTools: IAgentQuestionToolsService, + @IAgentWebService private readonly web: IAgentWebService, ) { } prompt(payload: PromptPayload): PromptLaunchResult | undefined { diff --git a/packages/agent-core-v2/src/session-activity/sessionActivityService.ts b/packages/agent-core-v2/src/session-activity/sessionActivityService.ts index 10bab97f2..de4aaa60b 100644 --- a/packages/agent-core-v2/src/session-activity/sessionActivityService.ts +++ b/packages/agent-core-v2/src/session-activity/sessionActivityService.ts @@ -10,8 +10,8 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { IAgentLifecycleService } from '#/agent-lifecycle/agentLifecycle'; -import { IInteractionService } from '#/interaction'; -import { ITurnService } from '#/turn'; +import { ISessionInteractionService } from '#/interaction'; +import { IAgentTurnService } from '#/turn'; import { ISessionActivity, type SessionStatus } from './sessionActivity'; @@ -20,7 +20,7 @@ export class SessionActivity implements ISessionActivity { constructor( @IAgentLifecycleService private readonly agents: IAgentLifecycleService, - @IInteractionService private readonly interaction: IInteractionService, + @ISessionInteractionService private readonly interaction: ISessionInteractionService, ) {} status(): SessionStatus { @@ -37,7 +37,7 @@ export class SessionActivity implements ISessionActivity { private hasActiveTurn(): boolean { for (const handle of this.agents.list()) { - const turn = handle.accessor.get(ITurnService); + const turn = handle.accessor.get(IAgentTurnService); if (turn.getActiveTurn() !== undefined) return true; } return false; @@ -45,7 +45,7 @@ export class SessionActivity implements ISessionActivity { private hasAbortedTurn(): boolean { for (const handle of this.agents.list()) { - const reason = handle.accessor.get(ITurnService).lastEndedReason(); + const reason = handle.accessor.get(IAgentTurnService).lastEndedReason(); if (reason === 'cancelled' || reason === 'failed' || reason === 'filtered') { return true; } diff --git a/packages/agent-core-v2/src/session-index/sessionIndexService.ts b/packages/agent-core-v2/src/session-index/sessionIndexService.ts index 8a58f3a9e..2d1a6eded 100644 --- a/packages/agent-core-v2/src/session-index/sessionIndexService.ts +++ b/packages/agent-core-v2/src/session-index/sessionIndexService.ts @@ -15,7 +15,7 @@ * representations are normalized to epoch ms. * * This is the local-deployment backend of `ISessionIndex`; a server deployment - * would substitute a database-backed `DbSessionIndex`. Bound at Core scope. + * would substitute a database-backed `DbSessionIndex`. Bound at App scope. */ import { relative } from 'pathe'; @@ -147,7 +147,7 @@ export class FileSessionIndex implements ISessionIndex { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ISessionIndex, FileSessionIndex, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/session-lifecycle/sessionLifecycle.ts b/packages/agent-core-v2/src/session-lifecycle/sessionLifecycle.ts index ef0615548..6bf97e7ac 100644 --- a/packages/agent-core-v2/src/session-lifecycle/sessionLifecycle.ts +++ b/packages/agent-core-v2/src/session-lifecycle/sessionLifecycle.ts @@ -4,7 +4,7 @@ * Defines the public contract of session lifecycle: the `CreateSessionOptions`, * `ForkSessionOptions`, and the `ISessionLifecycleService` used to create * sessions (`create`), look up the live ones (`get` / `list`), close them - * (`close`), archive them (`archive`), and fork them (`fork`). Core-scoped — a + * (`close`), archive them (`archive`), and fork them (`fork`). App-scoped — a * single process-wide instance owns the live session scope tree. Persisted * sessions (open or closed) are the `session-index` read model; per-session * behaviour lives in the Session-scoped domains. diff --git a/packages/agent-core-v2/src/session-lifecycle/sessionLifecycleService.ts b/packages/agent-core-v2/src/session-lifecycle/sessionLifecycleService.ts index 08fc04cb9..8153ef884 100644 --- a/packages/agent-core-v2/src/session-lifecycle/sessionLifecycleService.ts +++ b/packages/agent-core-v2/src/session-lifecycle/sessionLifecycleService.ts @@ -4,7 +4,7 @@ * Owns the process-wide registry of open Session child scopes, creating them * through the DI scope tree and seeding each with its identity and storage * addressing. Materializes the session's initial metadata on creation by - * resolving `session-metadata`. Bound at Core scope. Persisted sessions are + * resolving `session-metadata`. Bound at App scope. Persisted sessions are * the `session-index` read model. */ @@ -31,10 +31,10 @@ import { IWorkspaceRegistry } from '#/workspaceRegistry'; import { ISessionService } from '#/session'; import { ISessionContext, sessionContextSeed } from '#/session-context'; import { ISessionMetadata, type SessionMeta } from '#/session-metadata'; -import { ISkillCatalog } from '#/skill'; +import { ISessionSkillCatalog } from '#/skill'; import { AGENT_WIRE_PROTOCOL_VERSION, - IWireRecord, + IAgentWireRecordService, wireRecordPersistKey, type PersistedWireRecord, } from '#/wireRecord'; @@ -87,7 +87,7 @@ export class SessionLifecycleService implements ISessionLifecycleService { ); this.sessions.set(opts.sessionId, handle); await handle.accessor.get(ISessionMetadata).ready; - void handle.accessor.get(ISkillCatalog).load(); + void handle.accessor.get(ISessionSkillCatalog).load(); return handle; } @@ -168,7 +168,7 @@ export class SessionLifecycleService implements ISessionLifecycleService { // 7. Copy every source agent's wire log into the target's per-agent log // (BEFORE the target agents are created, so the logs are in place when - // their WireRecordService restores them in step 9). + // their AgentWireRecordService restores them in step 9). const sourceAgents = sourceMeta?.agents ?? {}; const agentIds = Object.keys(sourceAgents); for (const agentId of agentIds) { @@ -195,7 +195,7 @@ export class SessionLifecycleService implements ISessionLifecycleService { // log. Creating them registers fresh agent entries with TARGET homedirs. for (const agentId of agentIds) { const agentHandle = await target.accessor.get(IAgentLifecycleService).create({ agentId }); - await agentHandle.accessor.get(IWireRecord).restore(); + await agentHandle.accessor.get(IAgentWireRecordService).restore(); } return target; @@ -218,7 +218,7 @@ export class SessionLifecycleService implements ISessionLifecycleService { .accessor.get(IAgentLifecycleService) .getHandle(args.agentId); if (agentHandle !== undefined) { - await agentHandle.accessor.get(IWireRecord).flush(); + await agentHandle.accessor.get(IAgentWireRecordService).flush(); } } @@ -248,7 +248,7 @@ export class SessionLifecycleService implements ISessionLifecycleService { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ISessionLifecycleService, SessionLifecycleService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/sessionLegacy/sessionLegacy.ts b/packages/agent-core-v2/src/sessionLegacy/sessionLegacy.ts index 0919fea2f..b0d8e7f33 100644 --- a/packages/agent-core-v2/src/sessionLegacy/sessionLegacy.ts +++ b/packages/agent-core-v2/src/sessionLegacy/sessionLegacy.ts @@ -5,9 +5,9 @@ * `compact` / `undo` / `abort` / `btw`) and the `/sessions/{id}/children` * endpoints (`createChild` / `listChildren`) on top of the native v2 services * (`ISessionLifecycleService`, `ISessionIndex`, `IAgentRPCService`, - * `IFullCompaction`, `IPromptService`, …). The native services keep serving + * `IAgentFullCompactionService`, `IAgentPromptService`, …). The native services keep serving * `/api/v2` and are left untouched; this adapter exists only so clients of the - * v1 server keep working against server-v2. Bound at Core scope — it is a + * v1 server keep working against server-v2. Bound at App scope — it is a * stateless dispatcher that resolves the target session/agent per call. */ diff --git a/packages/agent-core-v2/src/sessionLegacy/sessionLegacyService.ts b/packages/agent-core-v2/src/sessionLegacy/sessionLegacyService.ts index 5f6330c42..d1ecf933f 100644 --- a/packages/agent-core-v2/src/sessionLegacy/sessionLegacyService.ts +++ b/packages/agent-core-v2/src/sessionLegacy/sessionLegacyService.ts @@ -1,7 +1,7 @@ /** * `sessionLegacy` domain — `ISessionLegacyService` implementation. * - * Stateless Core-scope dispatcher: each method resolves the target session (and + * Stateless App-scope dispatcher: each method resolves the target session (and * its main agent) per call, delegates to the native v2 services, and projects * the result into the v1 wire shape. Child sessions are implemented as forks * tagged in `custom` (`parent_session_id` + `child_session_kind`); listing reads @@ -13,21 +13,21 @@ import { InstantiationType } from '#/_base/di/extensions'; import { type IScopeHandle, LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { IAgentLifecycleService } from '#/agent-lifecycle'; import { IAuthSummaryService } from '#/auth'; -import { IContextMemory, toProtocolMessage, type ContextMessage } from '#/contextMemory'; -import { IContextSizeService } from '#/contextSize'; +import { IAgentContextMemoryService, toProtocolMessage, type ContextMessage } from '#/contextMemory'; +import { IAgentContextSizeService } from '#/contextSize'; import { ErrorCodes, isKimiError, KimiError } from '#/errors'; -import { IFullCompaction } from '#/fullCompaction'; -import { IPermissionModeService } from '#/permissionMode'; -import { IPlanService } from '#/plan'; -import { IProfileService } from '#/profile'; -import { IPromptService } from '#/prompt'; +import { IAgentFullCompactionService } from '#/fullCompaction'; +import { IAgentPermissionModeService } from '#/permissionMode'; +import { IAgentPlanService } from '#/plan'; +import { IAgentProfileService } from '#/profile'; +import { IAgentPromptService } from '#/prompt'; import { IAgentRPCService } from '#/rpc'; import { ISessionActivity } from '#/session-activity'; import { ISessionContext } from '#/session-context'; import { ISessionIndex, type SessionSummary } from '#/session-index'; import { ISessionLifecycleService } from '#/session-lifecycle'; import { ISessionMetadata } from '#/session-metadata'; -import { ISwarmService } from '#/swarm'; +import { IAgentSwarmService } from '#/swarm'; import { IWorkspaceRegistry } from '#/workspaceRegistry'; import type { ArchiveSessionResponse, @@ -177,13 +177,13 @@ export class SessionLegacyService implements ISessionLegacyService { // `begin` returns false when busy / over the per-turn limit — v1 treats // that as a silent success. It throws `compaction.unable` when there is no // compactable prefix, which we let propagate. - agent.accessor.get(IFullCompaction).begin({ source: 'manual', instruction }); + agent.accessor.get(IAgentFullCompactionService).begin({ source: 'manual', instruction }); return {}; } async undo(sessionId: string, body: UndoSessionRequest): Promise { const agent = await this.resolveMainAgent(sessionId); - const context = agent.accessor.get(IContextMemory); + const context = agent.accessor.get(IAgentContextMemoryService); const before = context.get(); const { count } = body; if (!canUndoHistory(before, count)) { @@ -193,7 +193,7 @@ export class SessionLegacyService implements ISessionLegacyService { ); } try { - agent.accessor.get(IPromptService).undo(count); + agent.accessor.get(IAgentPromptService).undo(count); } catch (error) { if (isKimiError(error) && error.code === ErrorCodes.REQUEST_INVALID) { throw new KimiError(ErrorCodes.SESSION_UNDO_UNAVAILABLE, error.message); @@ -291,11 +291,11 @@ export class SessionLegacyService implements ISessionLegacyService { private async assembleStatus(sessionId: string, agent: IScopeHandle): Promise { const session = this.lifecycle.get(sessionId); - const profile = agent.accessor.get(IProfileService); - const contextSize = agent.accessor.get(IContextSizeService); - const permission = agent.accessor.get(IPermissionModeService); - const plan = agent.accessor.get(IPlanService); - const swarm = agent.accessor.get(ISwarmService); + const profile = agent.accessor.get(IAgentProfileService); + const contextSize = agent.accessor.get(IAgentContextSizeService); + const permission = agent.accessor.get(IAgentPermissionModeService); + const plan = agent.accessor.get(IAgentPlanService); + const swarm = agent.accessor.get(IAgentSwarmService); const profileData = profile.data(); const model = profile.getModel(); @@ -381,7 +381,7 @@ function isRealUserPrompt(message: ContextMessage): boolean { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ISessionLegacyService, SessionLegacyService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/shellTools/index.ts b/packages/agent-core-v2/src/shellTools/index.ts index b795bacbc..a21592906 100644 --- a/packages/agent-core-v2/src/shellTools/index.ts +++ b/packages/agent-core-v2/src/shellTools/index.ts @@ -1,7 +1,7 @@ /** * `shellTools` domain barrel — re-exports the built-in Bash tool, the shared - * output `ToolResultBuilder`, and the `IShellToolsService` registration - * contract + service. Importing this barrel registers the `IShellToolsService` + * output `ToolResultBuilder`, and the `IAgentShellToolsService` registration + * contract + service. Importing this barrel registers the `IAgentShellToolsService` * binding into the scope registry. */ diff --git a/packages/agent-core-v2/src/shellTools/shellTools.ts b/packages/agent-core-v2/src/shellTools/shellTools.ts index c0f306661..a2edb3dfb 100644 --- a/packages/agent-core-v2/src/shellTools/shellTools.ts +++ b/packages/agent-core-v2/src/shellTools/shellTools.ts @@ -1,16 +1,16 @@ /** * `shellTools` domain (L4) — built-in shell tool registration contract. * - * `IShellToolsService` is a marker: its implementation registers the built-in - * Bash tool into the agent `IToolRegistry` on construction. Bound at Agent + * `IAgentShellToolsService` is a marker: its implementation registers the built-in + * Bash tool into the agent `IAgentToolRegistryService` on construction. Bound at Agent * scope. */ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; -export interface IShellToolsService { +export interface IAgentShellToolsService { readonly _serviceBrand: undefined; } -export const IShellToolsService: ServiceIdentifier = - createDecorator('shellToolsService'); +export const IAgentShellToolsService: ServiceIdentifier = + createDecorator('agentShellToolsService'); diff --git a/packages/agent-core-v2/src/shellTools/shellToolsService.ts b/packages/agent-core-v2/src/shellTools/shellToolsService.ts index 45135520c..7a9831ee6 100644 --- a/packages/agent-core-v2/src/shellTools/shellToolsService.ts +++ b/packages/agent-core-v2/src/shellTools/shellToolsService.ts @@ -1,30 +1,30 @@ /** - * `shellTools` domain (L4) — `IShellToolsService` implementation. + * `shellTools` domain (L4) — `IAgentShellToolsService` implementation. * - * Registers the built-in Bash tool into the agent `IToolRegistry` on - * construction, wiring it to the session `IProcessRunner` (process spawn), - * `IKaos` (cwd + OS/shell probe) and `IBackgroundService` (background-task + * Registers the built-in Bash tool into the agent `IAgentToolRegistryService` on + * construction, wiring it to the session `ISessionProcessRunner` (process spawn), + * `IKaos` (cwd + OS/shell probe) and `IAgentBackgroundService` (background-task * lifecycle). Bound at Agent scope. */ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IBackgroundService } from '#/background'; +import { IAgentBackgroundService } from '#/background'; import { IKaos } from '#/kaos'; -import { IProcessRunner } from '#/process'; -import { IToolRegistry } from '#/toolRegistry'; +import { ISessionProcessRunner } from '#/process'; +import { IAgentToolRegistryService } from '#/toolRegistry'; -import { IShellToolsService } from './shellTools'; +import { IAgentShellToolsService } from './shellTools'; import { BashTool } from './tools/bash'; -export class ShellToolsService implements IShellToolsService { +export class AgentShellToolsService implements IAgentShellToolsService { declare readonly _serviceBrand: undefined; constructor( - @IToolRegistry toolRegistry: IToolRegistry, - @IProcessRunner runner: IProcessRunner, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, + @ISessionProcessRunner runner: ISessionProcessRunner, @IKaos kaos: IKaos, - @IBackgroundService background: IBackgroundService, + @IAgentBackgroundService background: IAgentBackgroundService, ) { toolRegistry.register(new BashTool(runner, kaos, background)); } @@ -32,8 +32,8 @@ export class ShellToolsService implements IShellToolsService { registerScopedService( LifecycleScope.Agent, - IShellToolsService, - ShellToolsService, + IAgentShellToolsService, + AgentShellToolsService, InstantiationType.Delayed, 'shellTools', ); diff --git a/packages/agent-core-v2/src/shellTools/tools/bash.ts b/packages/agent-core-v2/src/shellTools/tools/bash.ts index 746425adf..bc266445c 100644 --- a/packages/agent-core-v2/src/shellTools/tools/bash.ts +++ b/packages/agent-core-v2/src/shellTools/tools/bash.ts @@ -2,16 +2,16 @@ * `shellTools` domain — BashTool, the model's shell command runner. * * Invokes the execution-environment shell (POSIX bash; Git Bash on Windows) - * through the injected `IProcessRunner`. The command runs as + * through the injected `ISessionProcessRunner`. The command runs as * `cd && ` inside the environment's working directory. * * Dependencies injected via constructor: - * - `runner` — `IProcessRunner`, spawns the shell process + * - `runner` — `ISessionProcessRunner`, spawns the shell process * - `kaos` — `IKaos`, the execution environment (cwd / osEnv / shellPath) - * - `background` — `IBackgroundService`, owns foreground/background task + * - `background` — `IAgentBackgroundService`, owns foreground/background task * lifecycle (timeouts, detach, user interrupt) * - * Execution goes through `IProcessRunner`, never directly via + * Execution goes through `ISessionProcessRunner`, never directly via * `node:child_process`. * * Hardening: @@ -19,12 +19,12 @@ * manager-owned process task on either edge. * - stdin is closed immediately so interactive commands (`cat`, `read`, * `python -c 'input()'`) receive EOF instead of hanging. - * - Two-phase kill is owned by `IBackgroundService`: SIGTERM → grace → SIGKILL. + * - Two-phase kill is owned by `IAgentBackgroundService`: SIGTERM → grace → SIGKILL. * - stdout/stderr are captured by `ProcessBackgroundTask` for task output; * foreground runs pass a callback to collect chunks for this call. * * Ported from v1 (`packages/agent-core/src/tools/builtin/shell/bash.ts`). The - * v1 `process.env` spread is intentionally dropped: v2's `IProcessRunner.exec` + * v1 `process.env` spread is intentionally dropped: v2's `ISessionProcessRunner.exec` * already overlays the per-call `env` on `process.env`, so only the * noninteractive knobs are passed here. */ @@ -32,9 +32,9 @@ import { z } from 'zod'; import { ProcessBackgroundTask } from '#/background'; -import type { IBackgroundService } from '#/background'; +import type { IAgentBackgroundService } from '#/background'; import type { IKaos } from '#/kaos'; -import type { IProcess, IProcessRunner } from '#/process'; +import type { IProcess, ISessionProcessRunner } from '#/process'; import type { BuiltinTool, ExecutableToolResult, ToolExecution, ToolUpdate } from '#/tool'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import { literalRulePattern, matchesGlobRuleSubject } from '#/_base/tools/support/rule-match'; @@ -165,9 +165,9 @@ export class BashTool implements BuiltinTool { private readonly allowBackground: boolean; constructor( - private readonly runner: IProcessRunner, + private readonly runner: ISessionProcessRunner, private readonly kaos: IKaos, - private readonly background: IBackgroundService, + private readonly background: IAgentBackgroundService, options?: { allowBackground?: boolean; }, @@ -215,7 +215,7 @@ export class BashTool implements BuiltinTool { SHELL: this.kaos.osEnv.shellPath, }; - // v2's IProcessRunner.exec overlays this env on process.env, so we pass + // v2's ISessionProcessRunner.exec overlays this env on process.env, so we pass // only the noninteractive knobs (the v1 spread of process.env is handled // by the runner). return this.runner.exec(shellArgs, { env: noninteractiveEnv }); diff --git a/packages/agent-core-v2/src/skill/fileSkillCatalogStore.ts b/packages/agent-core-v2/src/skill/fileSkillCatalogStore.ts index de8d8f012..035a73b6d 100644 --- a/packages/agent-core-v2/src/skill/fileSkillCatalogStore.ts +++ b/packages/agent-core-v2/src/skill/fileSkillCatalogStore.ts @@ -4,7 +4,7 @@ * Discovers skill bundles by walking skill roots on the local filesystem and * parsing each SKILL.md through `parser`. This is the only file in the skill * domain that imports `node:fs`; the rest of the domain depends on the - * `ISkillCatalogStore` interface and stays filesystem-agnostic. Bound at Core + * `ISkillCatalogStore` interface and stays filesystem-agnostic. Bound at App * scope by the composition root (tests register the in-memory backend instead). */ diff --git a/packages/agent-core-v2/src/skill/globalSkillCatalog.ts b/packages/agent-core-v2/src/skill/globalSkillCatalog.ts index 7d925c83f..d3ef2574a 100644 --- a/packages/agent-core-v2/src/skill/globalSkillCatalog.ts +++ b/packages/agent-core-v2/src/skill/globalSkillCatalog.ts @@ -3,7 +3,7 @@ * * `IGlobalSkillCatalog` holds the process-wide skill set: code-defined builtin * skills plus user / brand skills discovered from the user's home directories. - * It is loaded once and shared by every Session catalog. Core-scoped. + * It is loaded once and shared by every Session catalog. App-scoped. */ import { createDecorator } from '#/_base/di/instantiation'; diff --git a/packages/agent-core-v2/src/skill/globalSkillCatalogService.ts b/packages/agent-core-v2/src/skill/globalSkillCatalogService.ts index 049988c4a..ded206c96 100644 --- a/packages/agent-core-v2/src/skill/globalSkillCatalogService.ts +++ b/packages/agent-core-v2/src/skill/globalSkillCatalogService.ts @@ -3,7 +3,7 @@ * * Registers the builtin skills and discovers user / brand skills through the * `ISkillCatalogStore`, using the user home directories from `bootstrap`. The - * result is cached after the first `load()`. Bound at Core scope. + * result is cached after the first `load()`. Bound at App scope. */ import { InstantiationType } from '#/_base/di/extensions'; @@ -46,7 +46,7 @@ export class GlobalSkillCatalogService implements IGlobalSkillCatalog { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IGlobalSkillCatalog, GlobalSkillCatalogService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/skill/inMemorySkillCatalogStore.ts b/packages/agent-core-v2/src/skill/inMemorySkillCatalogStore.ts index 1275f6635..54e368033 100644 --- a/packages/agent-core-v2/src/skill/inMemorySkillCatalogStore.ts +++ b/packages/agent-core-v2/src/skill/inMemorySkillCatalogStore.ts @@ -2,9 +2,9 @@ * `skill` domain (L5) — in-memory `ISkillCatalogStore` backend. * * Returns preset skill lists for project / user discovery without any IO. - * Registered as the Core-scope default so tests and scopes work without a + * Registered as the App-scope default so tests and scopes work without a * filesystem; the production composition root overrides it with the filesystem - * backend. Core-scoped. + * backend. App-scoped. */ import { InstantiationType } from '#/_base/di/extensions'; @@ -38,7 +38,7 @@ export class InMemorySkillCatalogStore implements ISkillCatalogStore { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ISkillCatalogStore, InMemorySkillCatalogStore, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/skill/index.ts b/packages/agent-core-v2/src/skill/index.ts index f71e9edbd..82dade7d8 100644 --- a/packages/agent-core-v2/src/skill/index.ts +++ b/packages/agent-core-v2/src/skill/index.ts @@ -1,7 +1,7 @@ /** * `skill` domain barrel — re-exports the skill contracts and their scoped * services plus the in-memory catalog Store backend. Importing this barrel - * registers the `IAgentSkillService`, `IGlobalSkillCatalog`, `ISkillCatalog`, + * registers the `IAgentSkillService`, `IGlobalSkillCatalog`, `ISessionSkillCatalog`, * and the default in-memory `ISkillCatalogStore` bindings into the scope * registry. */ diff --git a/packages/agent-core-v2/src/skill/registry.ts b/packages/agent-core-v2/src/skill/registry.ts index 8d9f13619..7246749c4 100644 --- a/packages/agent-core-v2/src/skill/registry.ts +++ b/packages/agent-core-v2/src/skill/registry.ts @@ -2,8 +2,8 @@ * `skill` domain (L5) — concrete in-memory skill catalog. * * Owns registered skill lookup, plugin-scoped skill lookup, prompt rendering, - * and model-facing skill listings for `skill`. Held internally by the Core - * `IGlobalSkillCatalog` and Session `ISkillCatalog`; it is not a scoped service. + * and model-facing skill listings for `skill`. Held internally by the App + * `IGlobalSkillCatalog` and Session `ISessionSkillCatalog`; it is not a scoped service. */ import { escapeXmlAttr, escapeXmlTags } from '#/_base/utils/xml-escape'; diff --git a/packages/agent-core-v2/src/skill/skillCatalog.ts b/packages/agent-core-v2/src/skill/skillCatalog.ts index 0787ea751..213ede8b6 100644 --- a/packages/agent-core-v2/src/skill/skillCatalog.ts +++ b/packages/agent-core-v2/src/skill/skillCatalog.ts @@ -1,7 +1,7 @@ /** * `skill` domain (L5) — session skill catalog contract. * - * `ISkillCatalog` holds the active skill set for one session: the global + * `ISessionSkillCatalog` holds the active skill set for one session: the global * catalog (builtin + user/brand) merged with the project skills discovered * from the session's current `workDir`. It reloads when the workDir changes. * Session-scoped. @@ -11,7 +11,7 @@ import { createDecorator } from '#/_base/di/instantiation'; import type { SkillCatalog } from './types'; -export interface ISkillCatalog { +export interface ISessionSkillCatalog { readonly _serviceBrand: undefined; readonly catalog: SkillCatalog; @@ -23,4 +23,4 @@ export interface ISkillCatalog { reload(): Promise; } -export const ISkillCatalog = createDecorator('skillCatalog'); +export const ISessionSkillCatalog = createDecorator('sessionSkillCatalog'); diff --git a/packages/agent-core-v2/src/skill/skillCatalogService.ts b/packages/agent-core-v2/src/skill/skillCatalogService.ts index 06de97109..668f0db6b 100644 --- a/packages/agent-core-v2/src/skill/skillCatalogService.ts +++ b/packages/agent-core-v2/src/skill/skillCatalogService.ts @@ -1,5 +1,5 @@ /** - * `skill` domain (L5) — `ISkillCatalog` implementation. + * `skill` domain (L5) — `ISessionSkillCatalog` implementation. * * Merges the global catalog (`IGlobalSkillCatalog`) with the project skills * discovered through `ISkillCatalogStore` for the session's current workDir @@ -11,15 +11,15 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; import { IGlobalSkillCatalog } from './globalSkillCatalog'; import { InMemorySkillCatalog } from './registry'; -import { ISkillCatalog } from './skillCatalog'; +import { ISessionSkillCatalog } from './skillCatalog'; import { ISkillCatalogStore } from './skillCatalogStore'; import type { SkillCatalog } from './types'; -export class SkillCatalogService implements ISkillCatalog { +export class SessionSkillCatalogService implements ISessionSkillCatalog { declare readonly _serviceBrand: undefined; private inner = new InMemorySkillCatalog(); @@ -29,7 +29,7 @@ export class SkillCatalogService implements ISkillCatalog { constructor( @IGlobalSkillCatalog private readonly global: IGlobalSkillCatalog, @ISkillCatalogStore private readonly store: ISkillCatalogStore, - @IWorkspaceContext private readonly workspace: IWorkspaceContext, + @ISessionWorkspaceContext private readonly workspace: ISessionWorkspaceContext, ) {} get catalog(): SkillCatalog { @@ -69,8 +69,8 @@ export class SkillCatalogService implements ISkillCatalog { registerScopedService( LifecycleScope.Session, - ISkillCatalog, - SkillCatalogService, + ISessionSkillCatalog, + SessionSkillCatalogService, InstantiationType.Delayed, 'skill', ); diff --git a/packages/agent-core-v2/src/skill/skillCatalogStore.ts b/packages/agent-core-v2/src/skill/skillCatalogStore.ts index e57633e7b..48c1e3003 100644 --- a/packages/agent-core-v2/src/skill/skillCatalogStore.ts +++ b/packages/agent-core-v2/src/skill/skillCatalogStore.ts @@ -6,7 +6,7 @@ * and parses it into `SkillDefinition`s. The skill domain depends on this * interface only and never touches `node:fs` / `hostFs`; the backend is chosen * at the composition root (file locally, in-memory for tests, object storage or - * a DB on a server). Core-scoped. + * a DB on a server). App-scoped. */ import { createDecorator } from '#/_base/di/instantiation'; diff --git a/packages/agent-core-v2/src/skill/skillService.ts b/packages/agent-core-v2/src/skill/skillService.ts index c2aba611c..5068efe34 100644 --- a/packages/agent-core-v2/src/skill/skillService.ts +++ b/packages/agent-core-v2/src/skill/skillService.ts @@ -19,18 +19,18 @@ import { isUserActivatableSkillType, type SkillDefinition, } from './types'; -import { IEventSink } from '../eventSink'; -import { IPromptService } from '#/prompt'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentPromptService } from '#/prompt'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { Turn } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { IAgentSkillService, type ModelSkillActivationInput, type SkillActivationInput, } from './skill'; -import { ISkillCatalog } from './skillCatalog'; +import { ISessionSkillCatalog } from './skillCatalog'; import { SkillTool } from './tools/skill'; declare module '#/wireRecord' { @@ -45,12 +45,12 @@ export class AgentSkillService extends Disposable implements IAgentSkillService declare readonly _serviceBrand: undefined; constructor( - @ISkillCatalog private readonly skillCatalog: ISkillCatalog, - @IPromptService private readonly prompt: IPromptService, - @IEventSink private readonly events: IEventSink, - @IWireRecord private readonly wireRecord: IWireRecord, + @ISessionSkillCatalog private readonly skillCatalog: ISessionSkillCatalog, + @IAgentPromptService private readonly prompt: IAgentPromptService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, @ITelemetryService private readonly telemetry: ITelemetryService, - @IToolRegistry toolRegistry: IToolRegistry, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, ) { super(); this._register( diff --git a/packages/agent-core-v2/src/storage/appendLogStore.ts b/packages/agent-core-v2/src/storage/appendLogStore.ts index 5ab2647e4..9fd2f4028 100644 --- a/packages/agent-core-v2/src/storage/appendLogStore.ts +++ b/packages/agent-core-v2/src/storage/appendLogStore.ts @@ -207,7 +207,7 @@ function encodeBatch(records: readonly unknown[]): Uint8Array { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IAppendLogStore, AppendLogStore, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/storage/atomicDocumentStore.ts b/packages/agent-core-v2/src/storage/atomicDocumentStore.ts index 41a08a433..dc2992e22 100644 --- a/packages/agent-core-v2/src/storage/atomicDocumentStore.ts +++ b/packages/agent-core-v2/src/storage/atomicDocumentStore.ts @@ -9,7 +9,7 @@ * session metadata) and `tomlDocumentCodec` backs `TomlAtomicDocumentStore` * (the `config` document). Reads and writes bytes through `IStorageService` * (the config document) or `IAtomicDocumentStorage` (everyone else). Bound at - * Core scope. + * App scope. */ import { parse as parseToml, stringify as stringifyToml } from 'smol-toml'; @@ -119,7 +119,7 @@ export class TomlAtomicDocumentStore extends AtomicDocumentStoreBase { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IAtomicDocumentStore, AtomicDocumentStore, InstantiationType.Delayed, @@ -127,7 +127,7 @@ registerScopedService( ); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IAtomicTomlDocumentStore, TomlAtomicDocumentStore, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/storage/inMemoryStorageService.ts b/packages/agent-core-v2/src/storage/inMemoryStorageService.ts index 1f8e1f652..2c3c304e9 100644 --- a/packages/agent-core-v2/src/storage/inMemoryStorageService.ts +++ b/packages/agent-core-v2/src/storage/inMemoryStorageService.ts @@ -1,10 +1,10 @@ /** * `InMemoryStorageService` — `IStorageService` backed by in-memory maps. * - * Registered as the default `IStorageService` at Core scope so scopes and + * Registered as the default `IStorageService` at App scope so scopes and * tests work out of the box. For durable production storage, the composition * root seeds a per-token `FileStorageService` descriptor (rooted at - * `bootstrap.homeDir`) into the Core scope via `ScopeOptions.extra`, + * `bootstrap.homeDir`) into the App scope via `ScopeOptions.extra`, * overriding this default — the same pattern `blobStoreService` uses. * * `append` concatenates into the same key slot `write` replaces, mirroring the @@ -146,7 +146,7 @@ export class InMemoryStorageService implements IStorageService { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IStorageService, InMemoryStorageService, InstantiationType.Delayed, @@ -154,7 +154,7 @@ registerScopedService( ); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IAppendLogStorage, InMemoryStorageService, InstantiationType.Delayed, @@ -162,7 +162,7 @@ registerScopedService( ); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IAtomicDocumentStorage, InMemoryStorageService, InstantiationType.Delayed, @@ -170,7 +170,7 @@ registerScopedService( ); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IBlobStorage, InMemoryStorageService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/subagentHost/agentTool.ts b/packages/agent-core-v2/src/subagentHost/agentTool.ts index 8edc630fd..7f81c26cc 100644 --- a/packages/agent-core-v2/src/subagentHost/agentTool.ts +++ b/packages/agent-core-v2/src/subagentHost/agentTool.ts @@ -2,7 +2,7 @@ * AgentTool — collaboration tool for spawning task subagents. * * Unlike the built-in tools (Read/Write/Edit/Bash/Grep/Glob), this is a - * "collaboration tool". It uses `ISubagentHost` (injected via the constructor + * "collaboration tool". It uses `ISessionSubagentHost` (injected via the constructor * rather than through the runtime) to create in-process subagent loop instances. * * Foreground and background subagents both run through the background service. @@ -29,10 +29,10 @@ import { DEFAULT_SUBAGENT_TIMEOUT_DESCRIPTION, DEFAULT_SUBAGENT_TIMEOUT_MS, type SubagentHandle, - type ISubagentHost, + type ISessionSubagentHost, } from './subagentHost'; import { isUserCancellation } from '#/_base/utils/abort'; -import { AgentBackgroundTask, type IBackgroundService, type RegisterBackgroundTaskOptions } from '#/background'; +import { AgentBackgroundTask, type IAgentBackgroundService, type RegisterBackgroundTaskOptions } from '#/background'; import { toInputJsonSchema } from '#/_base/tools/support/input-schema'; import { matchesGlobRuleSubject } from '#/_base/tools/support/rule-match'; import AGENT_BACKGROUND_DISABLED_DESCRIPTION from './agent-background-disabled.md?raw'; @@ -119,8 +119,8 @@ export class AgentTool implements BuiltinTool { readonly parameters: Record = toInputJsonSchema(AgentToolInputSchema); constructor( - private readonly subagentHost: ISubagentHost, - private readonly background: IBackgroundService, + private readonly subagentHost: ISessionSubagentHost, + private readonly background: IAgentBackgroundService, subagents?: AgentToolSubagentMap | undefined, options?: { log?: ILogger; diff --git a/packages/agent-core-v2/src/subagentHost/subagentHost.ts b/packages/agent-core-v2/src/subagentHost/subagentHost.ts index 5c9dca745..2d05b9e91 100644 --- a/packages/agent-core-v2/src/subagentHost/subagentHost.ts +++ b/packages/agent-core-v2/src/subagentHost/subagentHost.ts @@ -46,7 +46,7 @@ export interface SessionSubagentHost { export type QueuedSubagentRunResult = SubagentResult; export type { QueuedSubagentTask }; -export interface ISubagentHost { +export interface ISessionSubagentHost { readonly _serviceBrand: undefined; getSwarmItem(agentId: string): string | undefined; startBtw(): Promise; @@ -59,4 +59,4 @@ export interface ISubagentHost { } -export const ISubagentHost = createDecorator('agentSubagentHostService'); +export const ISessionSubagentHost = createDecorator('sessionSubagentHost'); diff --git a/packages/agent-core-v2/src/subagentHost/subagentHostService.ts b/packages/agent-core-v2/src/subagentHost/subagentHostService.ts index 2cf0c5045..cc72355b9 100644 --- a/packages/agent-core-v2/src/subagentHost/subagentHostService.ts +++ b/packages/agent-core-v2/src/subagentHost/subagentHostService.ts @@ -7,25 +7,25 @@ import type { SubagentHandle, } from './subagentHost'; import { - ISubagentHost, + ISessionSubagentHost, } from './subagentHost'; import { Disposable } from '#/_base/di'; import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IBackgroundService } from '#/background'; +import { IAgentBackgroundService } from '#/background'; import { ILogService } from '#/log'; -import { IProfileService } from '#/profile'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentProfileService } from '#/profile'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { AgentTool } from './agentTool'; -export class SubagentHostService extends Disposable implements ISubagentHost { +export class SessionSubagentHostService extends Disposable implements ISessionSubagentHost { declare readonly _serviceBrand: undefined; constructor( private readonly subagentHost: SessionSubagentHost, - @IToolRegistry toolRegistry: IToolRegistry, - @IBackgroundService background: IBackgroundService, - @IProfileService profile: IProfileService, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, + @IAgentBackgroundService background: IAgentBackgroundService, + @IAgentProfileService profile: IAgentProfileService, @ILogService log?: ILogService, ) { super(); @@ -93,8 +93,8 @@ export class SubagentHostService extends Disposable implements ISubagentHost { registerScopedService( LifecycleScope.Session, - ISubagentHost, - SubagentHostService, + ISessionSubagentHost, + SessionSubagentHostService, InstantiationType.Delayed, 'subagentHost', ); diff --git a/packages/agent-core-v2/src/swarm/index.ts b/packages/agent-core-v2/src/swarm/index.ts index c517f724c..831d46c42 100644 --- a/packages/agent-core-v2/src/swarm/index.ts +++ b/packages/agent-core-v2/src/swarm/index.ts @@ -1,7 +1,7 @@ /** * `swarm` domain barrel — re-exports the swarm contract (`swarm`) and its * scoped service (`swarmService`). Importing this barrel registers the - * `ISwarmService` binding into the scope registry. + * `IAgentSwarmService` binding into the scope registry. */ export * from './swarm'; diff --git a/packages/agent-core-v2/src/swarm/swarm.ts b/packages/agent-core-v2/src/swarm/swarm.ts index 4e9b4b0f5..313d3857c 100644 --- a/packages/agent-core-v2/src/swarm/swarm.ts +++ b/packages/agent-core-v2/src/swarm/swarm.ts @@ -2,11 +2,11 @@ import { createDecorator } from "#/_base/di"; export type SwarmModeTrigger = 'manual' | 'task' | 'tool'; -export interface ISwarmService { +export interface IAgentSwarmService { readonly _serviceBrand: undefined; readonly isActive: boolean; enter(trigger: SwarmModeTrigger): void; exit(): void; } -export const ISwarmService = createDecorator('agentSwarmService'); +export const IAgentSwarmService = createDecorator('agentSwarmService'); diff --git a/packages/agent-core-v2/src/swarm/swarmService.ts b/packages/agent-core-v2/src/swarm/swarmService.ts index 3c76eadfb..b31617d5b 100644 --- a/packages/agent-core-v2/src/swarm/swarmService.ts +++ b/packages/agent-core-v2/src/swarm/swarmService.ts @@ -3,17 +3,17 @@ import { } from "#/_base/di"; import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IEventSink } from '../eventSink'; -import { ISubagentHost } from '#/subagentHost'; -import { ISystemReminderService } from '#/systemReminder'; -import { IToolRegistry } from '#/toolRegistry'; -import { ITurnService } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentEventSinkService } from '../eventSink'; +import { ISessionSubagentHost } from '#/subagentHost'; +import { IAgentSystemReminderService } from '#/systemReminder'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { IAgentTurnService } from '#/turn'; +import { IAgentWireRecordService } from '#/wireRecord'; import SWARM_MODE_ENTER_REMINDER from './enter-reminder.md?raw'; import SWARM_MODE_EXIT_REMINDER from './exit-reminder.md?raw'; import { AgentSwarmTool } from './tools/agent-swarm'; import { - ISwarmService, + IAgentSwarmService, type SwarmModeTrigger, } from './swarm'; @@ -26,18 +26,18 @@ declare module '#/wireRecord' { } } -export class SwarmService extends Disposable implements ISwarmService { +export class AgentSwarmService extends Disposable implements IAgentSwarmService { declare readonly _serviceBrand: undefined; private _active: SwarmModeTrigger | null = null; constructor( - @IWireRecord private readonly wireRecord: IWireRecord, - @IEventSink private readonly events: IEventSink, - @ISystemReminderService private readonly reminders: ISystemReminderService, - @ITurnService turnService: ITurnService, - @IToolRegistry toolRegistry: IToolRegistry, - @ISubagentHost subagentHost: ISubagentHost, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentSystemReminderService private readonly reminders: IAgentSystemReminderService, + @IAgentTurnService turnService: IAgentTurnService, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, + @ISessionSubagentHost subagentHost: ISessionSubagentHost, ) { super(); this._register( @@ -115,8 +115,8 @@ export class SwarmService extends Disposable implements ISwarmService { registerScopedService( LifecycleScope.Agent, - ISwarmService, - SwarmService, + IAgentSwarmService, + AgentSwarmService, InstantiationType.Delayed, 'swarm', ); diff --git a/packages/agent-core-v2/src/systemReminder/index.ts b/packages/agent-core-v2/src/systemReminder/index.ts index 1716869fb..e7f22472d 100644 --- a/packages/agent-core-v2/src/systemReminder/index.ts +++ b/packages/agent-core-v2/src/systemReminder/index.ts @@ -1,6 +1,6 @@ /** * `systemReminder` domain barrel — re-exports the reminder contract and its - * scoped service. Importing this barrel registers the `ISystemReminderService` + * scoped service. Importing this barrel registers the `IAgentSystemReminderService` * binding into the scope registry. */ diff --git a/packages/agent-core-v2/src/systemReminder/systemReminder.ts b/packages/agent-core-v2/src/systemReminder/systemReminder.ts index d23b8c84f..59b79eb85 100644 --- a/packages/agent-core-v2/src/systemReminder/systemReminder.ts +++ b/packages/agent-core-v2/src/systemReminder/systemReminder.ts @@ -2,7 +2,7 @@ import { createDecorator } from "#/_base/di"; import type { ContextMessage, PromptOrigin } from '#/contextMemory'; -export interface ISystemReminderService { +export interface IAgentSystemReminderService { readonly _serviceBrand: undefined; /** @@ -18,4 +18,4 @@ export interface ISystemReminderService { removeLastReminder(filter: (message: ContextMessage) => boolean): boolean; } -export const ISystemReminderService = createDecorator('agentSystemReminderService'); +export const IAgentSystemReminderService = createDecorator('agentSystemReminderService'); diff --git a/packages/agent-core-v2/src/systemReminder/systemReminderService.ts b/packages/agent-core-v2/src/systemReminder/systemReminderService.ts index a0f73f582..f6ec764a1 100644 --- a/packages/agent-core-v2/src/systemReminder/systemReminderService.ts +++ b/packages/agent-core-v2/src/systemReminder/systemReminderService.ts @@ -3,16 +3,16 @@ import { } from "#/_base/di"; import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IContextMemory } from '#/contextMemory'; +import { IAgentContextMemoryService } from '#/contextMemory'; import type { ContextMessage, PromptOrigin } from '#/contextMemory'; -import { ISystemReminderService } from './systemReminder'; +import { IAgentSystemReminderService } from './systemReminder'; -export class SystemReminderService extends Disposable implements ISystemReminderService { +export class AgentSystemReminderService extends Disposable implements IAgentSystemReminderService { declare readonly _serviceBrand: undefined; constructor( - @IContextMemory private readonly context: IContextMemory, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, ) { super(); } @@ -47,8 +47,8 @@ export class SystemReminderService extends Disposable implements ISystemReminder registerScopedService( LifecycleScope.Agent, - ISystemReminderService, - SystemReminderService, + IAgentSystemReminderService, + AgentSystemReminderService, InstantiationType.Delayed, 'systemReminder', ); diff --git a/packages/agent-core-v2/src/telemetry/cloudAppender.ts b/packages/agent-core-v2/src/telemetry/cloudAppender.ts index 05ba2442c..bbb8ff9c5 100644 --- a/packages/agent-core-v2/src/telemetry/cloudAppender.ts +++ b/packages/agent-core-v2/src/telemetry/cloudAppender.ts @@ -2,7 +2,7 @@ * `telemetry` domain (L1) — `CloudAppender`, an `ITelemetryAppender` that * batches events, enriches them with common context, and posts them to the * telemetry endpoint through `CloudTransport`, which persists failed events - * through the `storage` byte layer. Core-scoped; independent of + * through the `storage` byte layer. App-scoped; independent of * `@moonshot-ai/kimi-telemetry`. */ diff --git a/packages/agent-core-v2/src/telemetry/cloudTransport.ts b/packages/agent-core-v2/src/telemetry/cloudTransport.ts index 443832433..fdce50a59 100644 --- a/packages/agent-core-v2/src/telemetry/cloudTransport.ts +++ b/packages/agent-core-v2/src/telemetry/cloudTransport.ts @@ -3,7 +3,7 @@ * `CloudAppender`. Posts enriched events to the telemetry endpoint with Bearer * auth, retry, and a byte-store fallback for failed events, persisted through * the `storage` byte layer (`IStorageService`) under the `telemetry` scope. - * Core-scoped; independent of `@moonshot-ai/kimi-telemetry`. + * App-scoped; independent of `@moonshot-ai/kimi-telemetry`. */ import { randomBytes } from 'node:crypto'; diff --git a/packages/agent-core-v2/src/telemetry/consoleAppender.ts b/packages/agent-core-v2/src/telemetry/consoleAppender.ts index cad044f98..28254cead 100644 --- a/packages/agent-core-v2/src/telemetry/consoleAppender.ts +++ b/packages/agent-core-v2/src/telemetry/consoleAppender.ts @@ -1,6 +1,6 @@ /** * `telemetry` domain (L1) — `ConsoleAppender`, an `ITelemetryAppender` that - * echoes events to a log function for development and debugging. Core-scoped; + * echoes events to a log function for development and debugging. App-scoped; * has no cross-domain collaborators. */ diff --git a/packages/agent-core-v2/src/telemetry/telemetry.ts b/packages/agent-core-v2/src/telemetry/telemetry.ts index b5ceb7361..120b746bf 100644 --- a/packages/agent-core-v2/src/telemetry/telemetry.ts +++ b/packages/agent-core-v2/src/telemetry/telemetry.ts @@ -2,7 +2,7 @@ * `telemetry` domain (L1) — `ITelemetryService` contract and appender types. * * Layer-1 root service: merges bound context into tracked events and fans - * them out to one or more `ITelemetryAppender` destinations. Core-scoped — + * them out to one or more `ITelemetryAppender` destinations. App-scoped — * stateless beyond its appender set and bound context; enrichment, batching, * and transport are owned by the appenders, not by this layer. Defines the * `ITelemetryAppender` contract, the `ITelemetryService` facade, the service diff --git a/packages/agent-core-v2/src/telemetry/telemetryService.ts b/packages/agent-core-v2/src/telemetry/telemetryService.ts index d26dc5b60..ee2bd215b 100644 --- a/packages/agent-core-v2/src/telemetry/telemetryService.ts +++ b/packages/agent-core-v2/src/telemetry/telemetryService.ts @@ -4,7 +4,7 @@ * Merges bound context into each tracked event and fans it out to the * registered `ITelemetryAppender` destinations; owns the appender set, the * enabled flag, and the bound context, but no enrichment or transport of its - * own. Bound at Core scope; has no cross-domain collaborators. + * own. Bound at App scope; has no cross-domain collaborators. */ import { InstantiationType } from '#/_base/di/extensions'; @@ -91,7 +91,7 @@ export class TelemetryService implements ITelemetryService { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ITelemetryService, TelemetryService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/terminal/index.ts b/packages/agent-core-v2/src/terminal/index.ts index 03d721b4b..d26dfeae2 100644 --- a/packages/agent-core-v2/src/terminal/index.ts +++ b/packages/agent-core-v2/src/terminal/index.ts @@ -2,7 +2,7 @@ * `terminal` domain barrel — re-exports the terminal contract (`terminal`), * its scoped service (`terminalService`), the default backend stub * (`terminalBackend`), and the domain error codes (`errors`). Importing this - * barrel registers the `ITerminalService` and default `ITerminalBackend` + * barrel registers the `ISessionTerminalService` and default `ISessionTerminalBackend` * bindings into the scope registry. */ diff --git a/packages/agent-core-v2/src/terminal/terminal.ts b/packages/agent-core-v2/src/terminal/terminal.ts index 992328e23..8afca6652 100644 --- a/packages/agent-core-v2/src/terminal/terminal.ts +++ b/packages/agent-core-v2/src/terminal/terminal.ts @@ -1,12 +1,12 @@ /** * `terminal` domain (L6) — interactive terminal (PTY) contract. * - * Defines the `ITerminalService` that business code (and the edge, via an + * Defines the `ISessionTerminalService` that business code (and the edge, via an * accessor borrow) uses to manage a session's interactive terminals, the - * `ITerminalBackend` provider that hides the local/ssh/container split, and + * `ISessionTerminalBackend` provider that hides the local/ssh/container split, and * the attach/stream types (`TerminalProcess`, `TerminalAttachSink`, * `TerminalFrame`) used to wire terminal I/O to a transport. Session-scoped: - * one `ITerminalService` owns only its own session's terminals. Wire types + * one `ISessionTerminalService` owns only its own session's terminals. Wire types * (`Terminal`, `CreateTerminalRequest`, frame messages) are sourced from * `@moonshot-ai/protocol`. */ @@ -49,7 +49,7 @@ export interface TerminalProcess { kill(): void; } -export interface ITerminalService { +export interface ISessionTerminalService { readonly _serviceBrand: undefined; create(input: CreateTerminalRequest): Promise; @@ -75,14 +75,14 @@ export interface ITerminalService { close(terminalId: string): Promise<{ closed: true }>; } -export const ITerminalService: ServiceIdentifier = - createDecorator('terminalService'); +export const ISessionTerminalService: ServiceIdentifier = + createDecorator('sessionTerminalService'); -export interface ITerminalBackend { +export interface ISessionTerminalBackend { readonly _serviceBrand: undefined; spawn(options: TerminalSpawnOptions): Promise; } -export const ITerminalBackend: ServiceIdentifier = - createDecorator('terminalBackend'); +export const ISessionTerminalBackend: ServiceIdentifier = + createDecorator('sessionTerminalBackend'); diff --git a/packages/agent-core-v2/src/terminal/terminalBackend.ts b/packages/agent-core-v2/src/terminal/terminalBackend.ts index 83d641e00..2fc803670 100644 --- a/packages/agent-core-v2/src/terminal/terminalBackend.ts +++ b/packages/agent-core-v2/src/terminal/terminalBackend.ts @@ -1,8 +1,8 @@ /** - * `terminal` domain (L6) — default `ITerminalBackend` stub. + * `terminal` domain (L6) — default `ISessionTerminalBackend` stub. * * Placeholder backend registered so the binding graph is complete and - * `ITerminalService` resolves out of the box. It cannot spawn a real PTY; a + * `ISessionTerminalService` resolves out of the box. It cannot spawn a real PTY; a * composition root that needs interactive terminals (for example the server * or the desktop app, both of which already depend on `node-pty`) supplies a * real backend through the scope registry to override this one. @@ -12,9 +12,9 @@ import { InstantiationType } from '#/_base/di/extensions'; import { NotImplementedError } from '#/_base/errors'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { type TerminalProcess, type TerminalSpawnOptions, ITerminalBackend } from './terminal'; +import { type TerminalProcess, type TerminalSpawnOptions, ISessionTerminalBackend } from './terminal'; -export class NotImplementedTerminalBackend implements ITerminalBackend { +export class SessionNotImplementedTerminalBackend implements ISessionTerminalBackend { declare readonly _serviceBrand: undefined; spawn(_options: TerminalSpawnOptions): Promise { @@ -24,8 +24,8 @@ export class NotImplementedTerminalBackend implements ITerminalBackend { registerScopedService( LifecycleScope.Session, - ITerminalBackend, - NotImplementedTerminalBackend, + ISessionTerminalBackend, + SessionNotImplementedTerminalBackend, InstantiationType.Delayed, 'terminal', ); diff --git a/packages/agent-core-v2/src/terminal/terminalService.ts b/packages/agent-core-v2/src/terminal/terminalService.ts index 0b38cbfeb..c13f09c93 100644 --- a/packages/agent-core-v2/src/terminal/terminalService.ts +++ b/packages/agent-core-v2/src/terminal/terminalService.ts @@ -1,8 +1,8 @@ /** - * `terminal` domain (L6) — `ITerminalService` implementation. + * `terminal` domain (L6) — `ISessionTerminalService` implementation. * * Owns this session's terminal set and its per-terminal output buffers and - * attached sinks; spawns PTYs through the injected `ITerminalBackend`, + * attached sinks; spawns PTYs through the injected `ISessionTerminalBackend`, * resolves the working directory through `workspaceContext`, and reads the * session id through `session-context` to tag frames. Bound at Session scope. */ @@ -14,7 +14,7 @@ import { Disposable, type IDisposable } from '#/_base/di/lifecycle'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { ErrorCodes, KimiError } from '#/errors'; import { ISessionContext } from '#/session-context'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; import { type CreateTerminalRequest, @@ -25,8 +25,8 @@ import { type TerminalFrame, type TerminalOutputMessage, type TerminalProcess, - ITerminalBackend, - ITerminalService, + ISessionTerminalBackend, + ISessionTerminalService, } from './terminal'; const DEFAULT_COLS = 80; @@ -43,14 +43,14 @@ interface TerminalRecord { closed: boolean; } -export class TerminalService extends Disposable implements ITerminalService { +export class SessionTerminalService extends Disposable implements ISessionTerminalService { declare readonly _serviceBrand: undefined; private readonly records = new Map(); constructor( - @ITerminalBackend private readonly backend: ITerminalBackend, - @IWorkspaceContext private readonly workspace: IWorkspaceContext, + @ISessionTerminalBackend private readonly backend: ISessionTerminalBackend, + @ISessionWorkspaceContext private readonly workspace: ISessionWorkspaceContext, @ISessionContext private readonly sessionContext: ISessionContext, ) { super(); @@ -239,8 +239,8 @@ function defaultShell(): string { registerScopedService( LifecycleScope.Session, - ITerminalService, - TerminalService, + ISessionTerminalService, + SessionTerminalService, InstantiationType.Delayed, 'terminal', ); diff --git a/packages/agent-core-v2/src/todoList/todoList.ts b/packages/agent-core-v2/src/todoList/todoList.ts index 093ae86d9..eac458f94 100644 --- a/packages/agent-core-v2/src/todoList/todoList.ts +++ b/packages/agent-core-v2/src/todoList/todoList.ts @@ -1,7 +1,7 @@ import { createDecorator } from "#/_base/di"; -export interface ITodoListService { +export interface IAgentTodoListService { readonly _serviceBrand: undefined; } -export const ITodoListService = createDecorator('agentTodoListService'); +export const IAgentTodoListService = createDecorator('agentTodoListService'); diff --git a/packages/agent-core-v2/src/todoList/todoListService.ts b/packages/agent-core-v2/src/todoList/todoListService.ts index a878861c4..e0e383b24 100644 --- a/packages/agent-core-v2/src/todoList/todoListService.ts +++ b/packages/agent-core-v2/src/todoList/todoListService.ts @@ -12,24 +12,24 @@ import { TODO_LIST_REMINDER_VARIANT, todoListStaleReminder, } from './todoListReminder'; -import { IContextMemory } from '#/contextMemory'; -import { IContextInjector } from '../contextInjector'; -import { IProfileService } from '#/profile'; -import { IToolRegistry } from '#/toolRegistry'; -import { IToolStoreService } from '#/toolStore'; -import { ITodoListService } from './todoList'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentContextInjectorService } from '../contextInjector'; +import { IAgentProfileService } from '#/profile'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { IAgentToolStoreService } from '#/toolStore'; +import { IAgentTodoListService } from './todoList'; import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -export class TodoListService extends Disposable implements ITodoListService { +export class AgentTodoListService extends Disposable implements IAgentTodoListService { declare readonly _serviceBrand: undefined; constructor( - @IContextMemory private readonly context: IContextMemory, - @IProfileService private readonly profile: IProfileService, - @IToolStoreService private readonly toolStore: IToolStoreService, - @IToolRegistry toolRegistry: IToolRegistry, - @IContextInjector dynamicInjector: IContextInjector, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentProfileService private readonly profile: IAgentProfileService, + @IAgentToolStoreService private readonly toolStore: IAgentToolStoreService, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, + @IAgentContextInjectorService dynamicInjector: IAgentContextInjectorService, ) { super(); this._register(toolRegistry.register(new TodoListTool(toolStore))); @@ -53,8 +53,8 @@ export class TodoListService extends Disposable implements ITodoListService { registerScopedService( LifecycleScope.Agent, - ITodoListService, - TodoListService, + IAgentTodoListService, + AgentTodoListService, InstantiationType.Eager, 'todoList', ); diff --git a/packages/agent-core-v2/src/tool/toolHooks.ts b/packages/agent-core-v2/src/tool/toolHooks.ts index 83c307c68..6a05b4e3a 100644 --- a/packages/agent-core-v2/src/tool/toolHooks.ts +++ b/packages/agent-core-v2/src/tool/toolHooks.ts @@ -1,7 +1,7 @@ /** * `tool` domain (L3) — tool-execution hook contexts. * - * Defines the context objects passed through `IToolExecutor`'s + * Defines the context objects passed through `IAgentToolExecutorService`'s * `onWillExecuteTool` / `onDidExecuteTool` hooks and the decision results * handlers may return. Owned by `tool` because they describe tool execution, * not the turn lifecycle or the loop: participants such as `permission`, diff --git a/packages/agent-core-v2/src/toolExecutor/toolExecutor.ts b/packages/agent-core-v2/src/toolExecutor/toolExecutor.ts index 1e89c6a45..5508c932c 100644 --- a/packages/agent-core-v2/src/toolExecutor/toolExecutor.ts +++ b/packages/agent-core-v2/src/toolExecutor/toolExecutor.ts @@ -18,7 +18,7 @@ export interface ToolExecutorExecuteOptions { readonly onProgress?: ((toolCallId: string, update: ToolUpdate) => void) | undefined; } -export interface IToolExecutor { +export interface IAgentToolExecutorService { readonly _serviceBrand: undefined; execute(calls: ToolCall[], options?: ToolExecutorExecuteOptions): Promise; @@ -29,4 +29,4 @@ export interface IToolExecutor { }; } -export const IToolExecutor = createDecorator('toolExecutorService'); +export const IAgentToolExecutorService = createDecorator('agentToolExecutorService'); diff --git a/packages/agent-core-v2/src/toolExecutor/toolExecutorService.ts b/packages/agent-core-v2/src/toolExecutor/toolExecutorService.ts index d2bbcbe2c..807c59bd6 100644 --- a/packages/agent-core-v2/src/toolExecutor/toolExecutorService.ts +++ b/packages/agent-core-v2/src/toolExecutor/toolExecutorService.ts @@ -22,11 +22,11 @@ import type { } from '#/tool'; import type { ToolCall } from '@moonshot-ai/kosong'; import { isAbortError } from '#/loop/errors'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { ToolAccesses } from '#/tool'; import { OrderedHookSlot } from '#/hooks'; import { - IToolExecutor, + IAgentToolExecutorService, type ToolExecutorExecuteOptions, } from './toolExecutor'; import { ToolScheduler } from './toolScheduler'; @@ -43,14 +43,14 @@ export interface ToolExecutionTask { readonly execute: (signal: AbortSignal) => Promise; } -export class ToolExecutorService implements IToolExecutor { +export class AgentToolExecutorService implements IAgentToolExecutorService { declare readonly _serviceBrand: undefined; readonly hooks = { onWillExecuteTool: new OrderedHookSlot(), onDidExecuteTool: new OrderedHookSlot(), }; - constructor(@IToolRegistry private readonly toolRegistry: IToolRegistry) {} + constructor(@IAgentToolRegistryService private readonly toolRegistry: IAgentToolRegistryService) {} async execute( calls: ToolCall[], @@ -384,7 +384,7 @@ function buildWillExecuteContext( } function preflightToolCall( - toolRegistry: IToolRegistry, + toolRegistry: IAgentToolRegistryService, toolCall: ToolCall, ): PreflightedToolCall { const toolName = toolCall.name; @@ -625,8 +625,8 @@ function errorMessage(error: unknown): string { registerScopedService( LifecycleScope.Agent, - IToolExecutor, - ToolExecutorService, + IAgentToolExecutorService, + AgentToolExecutorService, InstantiationType.Delayed, 'toolExecutor', ); diff --git a/packages/agent-core-v2/src/toolRegistry/index.ts b/packages/agent-core-v2/src/toolRegistry/index.ts index 704520bb3..b86a8da1a 100644 --- a/packages/agent-core-v2/src/toolRegistry/index.ts +++ b/packages/agent-core-v2/src/toolRegistry/index.ts @@ -1,7 +1,7 @@ /** * `toolRegistry` domain barrel — re-exports the per-agent tool registry * contract (`toolRegistry`) and its scoped service (`toolRegistryService`). - * Importing this barrel registers the `IToolRegistry` binding into the scope + * Importing this barrel registers the `IAgentToolRegistryService` binding into the scope * registry. */ diff --git a/packages/agent-core-v2/src/toolRegistry/toolRegistry.ts b/packages/agent-core-v2/src/toolRegistry/toolRegistry.ts index ff9df40a7..f51a211ed 100644 --- a/packages/agent-core-v2/src/toolRegistry/toolRegistry.ts +++ b/packages/agent-core-v2/src/toolRegistry/toolRegistry.ts @@ -1,5 +1,5 @@ /** - * `toolRegistry` domain (L3) — `IToolRegistry` contract. + * `toolRegistry` domain (L3) — `IAgentToolRegistryService` contract. * * Per-agent registry of the tools an agent can resolve and run: `register` / * `unregister` / `list` / `resolve`, plus `onRegistered` / `onUnregistered` @@ -16,7 +16,7 @@ export interface ToolRegistrationOptions { readonly source?: ToolSource; } -export interface IToolRegistry { +export interface IAgentToolRegistryService { readonly _serviceBrand: undefined; register(tool: ExecutableTool, options?: ToolRegistrationOptions): IDisposable; list(): readonly ToolInfo[]; @@ -28,4 +28,4 @@ export interface IToolRegistry { }>; } -export const IToolRegistry = createDecorator('agentToolRegistryService'); +export const IAgentToolRegistryService = createDecorator('agentToolRegistryService'); diff --git a/packages/agent-core-v2/src/toolRegistry/toolRegistryService.ts b/packages/agent-core-v2/src/toolRegistry/toolRegistryService.ts index 2e1f6548c..5a46a121c 100644 --- a/packages/agent-core-v2/src/toolRegistry/toolRegistryService.ts +++ b/packages/agent-core-v2/src/toolRegistry/toolRegistryService.ts @@ -7,14 +7,14 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import type { ExecutableTool, ToolInfo, ToolSource } from '#/tool'; import { OrderedHookSlot } from '../hooks'; -import { IToolRegistry, type ToolRegistrationOptions } from './toolRegistry'; +import { IAgentToolRegistryService, type ToolRegistrationOptions } from './toolRegistry'; interface ToolEntry { readonly tool: ExecutableTool; readonly source: ToolSource; } -export class ToolRegistryService extends Disposable implements IToolRegistry { +export class AgentToolRegistryService extends Disposable implements IAgentToolRegistryService { declare readonly _serviceBrand: undefined; private readonly tools = new Map(); @@ -68,8 +68,8 @@ export class ToolRegistryService extends Disposable implements IToolRegistry { registerScopedService( LifecycleScope.Agent, - IToolRegistry, - ToolRegistryService, + IAgentToolRegistryService, + AgentToolRegistryService, InstantiationType.Delayed, 'toolRegistry', ); diff --git a/packages/agent-core-v2/src/toolStore/toolStore.ts b/packages/agent-core-v2/src/toolStore/toolStore.ts index 3eb3ac323..e7ed9e1bf 100644 --- a/packages/agent-core-v2/src/toolStore/toolStore.ts +++ b/packages/agent-core-v2/src/toolStore/toolStore.ts @@ -15,7 +15,7 @@ export interface ToolStoreUpdate { readonly value: ToolStoreData[K]; } -export interface IToolStoreService extends ToolStore { +export interface IAgentToolStoreService extends ToolStore { readonly _serviceBrand: undefined; data(): Readonly>; @@ -24,4 +24,4 @@ export interface IToolStoreService extends ToolStore { }>; } -export const IToolStoreService = createDecorator('agentToolStoreService'); +export const IAgentToolStoreService = createDecorator('agentToolStoreService'); diff --git a/packages/agent-core-v2/src/toolStore/toolStoreService.ts b/packages/agent-core-v2/src/toolStore/toolStoreService.ts index 323b9a98e..65a8e8250 100644 --- a/packages/agent-core-v2/src/toolStore/toolStoreService.ts +++ b/packages/agent-core-v2/src/toolStore/toolStoreService.ts @@ -4,8 +4,8 @@ import { import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { OrderedHookSlot } from '../hooks'; -import { IToolStoreService, type ToolStoreData, type ToolStoreKey } from './toolStore'; -import { IWireRecord, type WireRecord } from '#/wireRecord'; +import { IAgentToolStoreService, type ToolStoreData, type ToolStoreKey } from './toolStore'; +import { IAgentWireRecordService, type WireRecord } from '#/wireRecord'; declare module '#/wireRecord' { interface WireRecordMap { @@ -16,7 +16,7 @@ declare module '#/wireRecord' { } } -export class ToolStoreService extends Disposable implements IToolStoreService { +export class AgentToolStoreService extends Disposable implements IAgentToolStoreService { declare readonly _serviceBrand: undefined; private readonly store: Partial = {}; @@ -28,7 +28,7 @@ export class ToolStoreService extends Disposable implements IToolStoreService { }; constructor( - @IWireRecord private readonly wireRecord: IWireRecord, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, ) { super(); this._register( @@ -66,8 +66,8 @@ export class ToolStoreService extends Disposable implements IToolStoreService { registerScopedService( LifecycleScope.Agent, - IToolStoreService, - ToolStoreService, + IAgentToolStoreService, + AgentToolStoreService, InstantiationType.Delayed, 'toolStore', ); diff --git a/packages/agent-core-v2/src/tooldedup/index.ts b/packages/agent-core-v2/src/tooldedup/index.ts index d195511b3..980c49b95 100644 --- a/packages/agent-core-v2/src/tooldedup/index.ts +++ b/packages/agent-core-v2/src/tooldedup/index.ts @@ -1,7 +1,7 @@ /** * `toolDedup` domain barrel — re-exports the tool-call deduplication * contract (`toolDedupe`) and its scoped service (`toolDedupeService`). Importing - * this barrel registers the `IToolDedupe` binding into the scope registry. + * this barrel registers the `IAgentToolDedupeService` binding into the scope registry. */ export * from './toolDedupe'; diff --git a/packages/agent-core-v2/src/tooldedup/toolDedupe.ts b/packages/agent-core-v2/src/tooldedup/toolDedupe.ts index a2a087376..8287a3c88 100644 --- a/packages/agent-core-v2/src/tooldedup/toolDedupe.ts +++ b/packages/agent-core-v2/src/tooldedup/toolDedupe.ts @@ -2,7 +2,7 @@ * `toolDedup` domain (L4) — per-turn tool-call deduplication. * * A self-wiring plugin: it participates in `turn` step boundaries and - * `IToolExecutor`'s will/did hooks to suppress same-step duplicates and inject + * `IAgentToolExecutorService`'s will/did hooks to suppress same-step duplicates and inject * cross-step repeat reminders. No other service injects it — the container * constructs it eagerly at Agent scope so its constructor registers the hooks. * The only public surface is the read-only `currentStreak` observation; the @@ -34,10 +34,10 @@ export interface ToolDedupErrorResult { export type ToolDedupResult = ToolDedupSuccessResult | ToolDedupErrorResult; -export interface IToolDedupe { +export interface IAgentToolDedupeService { readonly _serviceBrand: undefined; readonly currentStreak: number; } -export const IToolDedupe: ServiceIdentifier = - createDecorator('toolDedupe'); +export const IAgentToolDedupeService: ServiceIdentifier = + createDecorator('agentToolDedupeService'); diff --git a/packages/agent-core-v2/src/tooldedup/toolDedupeService.ts b/packages/agent-core-v2/src/tooldedup/toolDedupeService.ts index 203b8c376..2163d635a 100644 --- a/packages/agent-core-v2/src/tooldedup/toolDedupeService.ts +++ b/packages/agent-core-v2/src/tooldedup/toolDedupeService.ts @@ -1,5 +1,5 @@ /** - * `toolDedup` domain (L4) — `IToolDedupe` implementation. + * `toolDedup` domain (L4) — `IAgentToolDedupeService` implementation. * * Self-wiring plugin: its constructor registers `turn` beforeStep/afterStep * hooks and `toolExecutor` onWillExecuteTool/onDidExecuteTool hooks to drive @@ -13,10 +13,10 @@ import { Disposable } from '#/_base/di/lifecycle'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { canonicalTelemetryArgs } from '#/_base/utils/canonical-args'; import { ITelemetryService } from '#/telemetry/telemetry'; -import { IToolExecutor } from '#/toolExecutor'; -import { ITurnService } from '#/turn'; +import { IAgentToolExecutorService } from '#/toolExecutor'; +import { IAgentTurnService } from '#/turn'; import type { ContentPart } from '@moonshot-ai/kosong'; -import { IToolDedupe, type ToolDedupResult } from './toolDedupe'; +import { IAgentToolDedupeService, type ToolDedupResult } from './toolDedupe'; const REMINDER_TEXT_1 = '\n\n\n' + @@ -97,7 +97,7 @@ function forceStopResult(result: ToolDedupResult, reminderText: string): ToolDed const DEDUP_PLACEHOLDER_RESULT: ToolDedupResult = { output: '' }; -export class ToolDedupeService extends Disposable implements IToolDedupe { +export class AgentToolDedupeService extends Disposable implements IAgentToolDedupeService { declare readonly _serviceBrand: undefined; private readonly stepDeferreds = new Map>(); private stepCalls: string[] = []; @@ -109,8 +109,8 @@ export class ToolDedupeService extends Disposable implements IToolDedupe { constructor( @ITelemetryService private readonly telemetry: ITelemetryService, - @ITurnService turn: ITurnService, - @IToolExecutor toolExecutor: IToolExecutor, + @IAgentTurnService turn: IAgentTurnService, + @IAgentToolExecutorService toolExecutor: IAgentToolExecutorService, ) { super(); turn.hooks.beforeStep.register('toolDedup', async (_ctx, next) => { @@ -260,8 +260,8 @@ export const __testing = { registerScopedService( LifecycleScope.Agent, - IToolDedupe, - ToolDedupeService, + IAgentToolDedupeService, + AgentToolDedupeService, InstantiationType.Eager, 'toolDedup', ); diff --git a/packages/agent-core-v2/src/turn/turn.ts b/packages/agent-core-v2/src/turn/turn.ts index b81dc6cd1..a2e4d0d53 100644 --- a/packages/agent-core-v2/src/turn/turn.ts +++ b/packages/agent-core-v2/src/turn/turn.ts @@ -39,7 +39,7 @@ export interface TurnEndedContext { readonly result: TurnResult; } -export interface ITurnService { +export interface IAgentTurnService { readonly _serviceBrand: undefined; launch(origin: PromptOrigin, promptMessageId?: string): Turn; getActiveTurn(): Turn | undefined; @@ -59,4 +59,4 @@ export interface ITurnService { }>; } -export const ITurnService = createDecorator('turnService'); +export const IAgentTurnService = createDecorator('agentTurnService'); diff --git a/packages/agent-core-v2/src/turn/turnService.ts b/packages/agent-core-v2/src/turn/turnService.ts index 6c33a652b..a3de626b2 100644 --- a/packages/agent-core-v2/src/turn/turnService.ts +++ b/packages/agent-core-v2/src/turn/turnService.ts @@ -3,13 +3,13 @@ import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { toKimiErrorPayload, type KimiErrorPayload } from "#/errors"; import { isUserCancellation } from "#/_base/utils/abort"; import type { ContextMessage, PromptOrigin } from '#/contextMemory'; -import { IContextMemory, USER_PROMPT_ORIGIN } from '#/contextMemory'; -import { IEventSink } from '../eventSink'; -import { IExternalHooksService } from '#/externalHooks'; +import { IAgentContextMemoryService, USER_PROMPT_ORIGIN } from '#/contextMemory'; +import { IAgentEventSinkService } from '../eventSink'; +import { IAgentExternalHooksService } from '#/externalHooks'; import { OrderedHookSlot } from '#/hooks'; -import { ILoopService } from '#/loop'; +import { IAgentLoopService } from '#/loop'; import { ITelemetryService } from '#/telemetry'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import type { Turn, TurnContextOverflowContext, @@ -17,7 +17,7 @@ import type { TurnResult, TurnStepContext, } from './turn'; -import { ITurnService } from './turn'; +import { IAgentTurnService } from './turn'; declare module '#/wireRecord' { interface WireRecordMap { @@ -29,7 +29,7 @@ declare module '#/wireRecord' { } } -export class TurnService implements ITurnService { +export class AgentTurnService implements IAgentTurnService { declare readonly _serviceBrand: undefined; private nextTurnId = 0; private activeTurn: Turn | undefined; @@ -49,11 +49,11 @@ export class TurnService implements ITurnService { }; constructor( - @ILoopService private readonly loop: ILoopService, - @IEventSink private readonly events: IEventSink, - @IWireRecord private readonly wireRecord: IWireRecord, - @IContextMemory private readonly context: IContextMemory, - @IExternalHooksService private readonly externalHooks: IExternalHooksService, + @IAgentLoopService private readonly loop: IAgentLoopService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentContextMemoryService private readonly context: IAgentContextMemoryService, + @IAgentExternalHooksService private readonly externalHooks: IAgentExternalHooksService, @ITelemetryService private readonly telemetry: ITelemetryService, ) { wireRecord.register('turn.launch', (record) => { @@ -325,8 +325,8 @@ function createControlledPromise(): ControlledPromise { registerScopedService( LifecycleScope.Agent, - ITurnService, - TurnService, + IAgentTurnService, + AgentTurnService, InstantiationType.Delayed, 'turn', ); diff --git a/packages/agent-core-v2/src/usage/index.ts b/packages/agent-core-v2/src/usage/index.ts index a59c03184..6fb92ac34 100644 --- a/packages/agent-core-v2/src/usage/index.ts +++ b/packages/agent-core-v2/src/usage/index.ts @@ -1,7 +1,7 @@ /** * `usage` domain barrel — re-exports the usage contract (`usage`) and its * scoped service (`usageService`). Importing this barrel registers the - * `IUsageService` binding into the scope registry. + * `IAgentUsageService` binding into the scope registry. */ export * from './usage'; diff --git a/packages/agent-core-v2/src/usage/usage.ts b/packages/agent-core-v2/src/usage/usage.ts index ff144a745..7bf141b7c 100644 --- a/packages/agent-core-v2/src/usage/usage.ts +++ b/packages/agent-core-v2/src/usage/usage.ts @@ -13,10 +13,10 @@ export interface UsageStatus { readonly currentTurn?: TokenUsage; } -export interface IUsageService { +export interface IAgentUsageService { readonly _serviceBrand: undefined; record(model: string, usage: TokenUsage, context?: UsageRecordContext): void; status(): UsageStatus; } -export const IUsageService = createDecorator('usageService.agent'); +export const IAgentUsageService = createDecorator('agentUsageService'); diff --git a/packages/agent-core-v2/src/usage/usageService.ts b/packages/agent-core-v2/src/usage/usageService.ts index fcdab6b7c..0f84c9abc 100644 --- a/packages/agent-core-v2/src/usage/usageService.ts +++ b/packages/agent-core-v2/src/usage/usageService.ts @@ -5,10 +5,10 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { Disposable } from '#/_base/di/lifecycle'; -import { IEventSink } from '../eventSink'; +import { IAgentEventSinkService } from '../eventSink'; import type { UsageRecordContext, UsageStatus } from './usage'; -import { IUsageService } from './usage'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentUsageService } from './usage'; +import { IAgentWireRecordService } from '#/wireRecord'; declare module '#/wireRecord' { interface WireRecordMap { @@ -20,15 +20,15 @@ declare module '#/wireRecord' { } } -export class UsageService extends Disposable implements IUsageService { +export class AgentUsageService extends Disposable implements IAgentUsageService { declare readonly _serviceBrand: undefined; private readonly byModel: Record = {}; private currentTurnId: number | undefined; private currentTurn: TokenUsage | undefined; constructor( - @IWireRecord private readonly wireRecord: IWireRecord, - @IEventSink private readonly events: IEventSink, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, + @IAgentEventSinkService private readonly events: IAgentEventSinkService, ) { super(); this._register( @@ -102,8 +102,8 @@ function totalUsage(byModel: Record): TokenUsage | undefined registerScopedService( LifecycleScope.Agent, - IUsageService, - UsageService, + IAgentUsageService, + AgentUsageService, InstantiationType.Delayed, 'usage', ); diff --git a/packages/agent-core-v2/src/userTool/userTool.ts b/packages/agent-core-v2/src/userTool/userTool.ts index e9204ac23..802499fae 100644 --- a/packages/agent-core-v2/src/userTool/userTool.ts +++ b/packages/agent-core-v2/src/userTool/userTool.ts @@ -6,11 +6,11 @@ export interface UserToolRegistration { readonly parameters: Record; } -export interface IUserToolService { +export interface IAgentUserToolService { readonly _serviceBrand: undefined; register(input: UserToolRegistration): void; unregister(name: string): void; } -export const IUserToolService = createDecorator('agentUserToolService'); +export const IAgentUserToolService = createDecorator('agentUserToolService'); diff --git a/packages/agent-core-v2/src/userTool/userToolService.ts b/packages/agent-core-v2/src/userTool/userToolService.ts index b464e8916..146ca5cdd 100644 --- a/packages/agent-core-v2/src/userTool/userToolService.ts +++ b/packages/agent-core-v2/src/userTool/userToolService.ts @@ -7,12 +7,12 @@ import type { ExecutableToolContext, ExecutableToolResult, } from '#/tool'; -import { IProfileService } from '#/profile'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentProfileService } from '#/profile'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { ToolResult } from '#/tool'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { - IUserToolService, + IAgentUserToolService, type UserToolRegistration, } from './userTool'; import { InstantiationType } from '#/_base/di/extensions'; @@ -27,15 +27,15 @@ declare module '#/wireRecord' { } } -export class UserToolService extends Disposable implements IUserToolService { +export class AgentUserToolService extends Disposable implements IAgentUserToolService { declare readonly _serviceBrand: undefined; private readonly registrations = new Map(); constructor( - @IToolRegistry private readonly registry: IToolRegistry, - @IProfileService private readonly profile: IProfileService, - @IWireRecord private readonly wireRecord: IWireRecord, + @IAgentToolRegistryService private readonly registry: IAgentToolRegistryService, + @IAgentProfileService private readonly profile: IAgentProfileService, + @IAgentWireRecordService private readonly wireRecord: IAgentWireRecordService, ) { super(); this._register( @@ -112,8 +112,8 @@ function toExecutableToolResult(result: ToolResult): ExecutableToolResult { registerScopedService( LifecycleScope.Agent, - IUserToolService, - UserToolService, + IAgentUserToolService, + AgentUserToolService, InstantiationType.Eager, 'userTool', ); diff --git a/packages/agent-core-v2/src/web/index.ts b/packages/agent-core-v2/src/web/index.ts index 593a7f6f0..6678aad5e 100644 --- a/packages/agent-core-v2/src/web/index.ts +++ b/packages/agent-core-v2/src/web/index.ts @@ -1,6 +1,6 @@ /** * `web` domain barrel — re-exports the web contract (`web`) and its scoped - * service (`webService`). Importing this barrel registers the `IWebService` + * service (`webService`). Importing this barrel registers the `IAgentWebService` * binding into the scope registry. */ diff --git a/packages/agent-core-v2/src/web/web.ts b/packages/agent-core-v2/src/web/web.ts index 492fd5f8f..002852bcc 100644 --- a/packages/agent-core-v2/src/web/web.ts +++ b/packages/agent-core-v2/src/web/web.ts @@ -1,10 +1,10 @@ /** * `web` domain (L4) — web tool registration contract and provider options. * - * `IWebService` is a marker: its implementation registers the built-in + * `IAgentWebService` is a marker: its implementation registers the built-in * `FetchURL` tool (always, falling back to `LocalFetchURLProvider`) and the * `WebSearch` tool (only when a `WebSearchProvider` is supplied) into the - * agent `IToolRegistry` on construction. Bound at Agent scope. + * agent `IAgentToolRegistryService` on construction. Bound at Agent scope. * * The actual fetch/search backends are host-injected through * `WebServiceOptions` so this domain stays independent of config and OAuth. @@ -22,9 +22,9 @@ export interface WebServiceOptions { readonly webSearcher?: WebSearchProvider; } -export interface IWebService { +export interface IAgentWebService { readonly _serviceBrand: undefined; } -export const IWebService: ServiceIdentifier = - createDecorator('webService'); +export const IAgentWebService: ServiceIdentifier = + createDecorator('agentWebService'); diff --git a/packages/agent-core-v2/src/web/webService.ts b/packages/agent-core-v2/src/web/webService.ts index d0008abb2..fc2084989 100644 --- a/packages/agent-core-v2/src/web/webService.ts +++ b/packages/agent-core-v2/src/web/webService.ts @@ -1,7 +1,7 @@ /** - * `web` domain (L4) — `IWebService` implementation. + * `web` domain (L4) — `IAgentWebService` implementation. * - * Registers the built-in web tools into the agent `IToolRegistry` on + * Registers the built-in web tools into the agent `IAgentToolRegistryService` on * construction: `FetchURL` is always registered (using the injected * `UrlFetcher` or the built-in `LocalFetchURLProvider` fallback); `WebSearch` * is registered only when a `WebSearchProvider` is supplied via options, since @@ -10,19 +10,19 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { LocalFetchURLProvider } from './providers/local-fetch-url'; import { FetchURLTool } from './tools/fetch-url'; import { WebSearchTool } from './tools/web-search'; -import { IWebService, type WebServiceOptions } from './web'; +import { IAgentWebService, type WebServiceOptions } from './web'; -export class WebService implements IWebService { +export class AgentWebService implements IAgentWebService { declare readonly _serviceBrand: undefined; constructor( private readonly options: WebServiceOptions = {}, - @IToolRegistry toolRegistry: IToolRegistry, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, ) { const fetcher = options.urlFetcher ?? new LocalFetchURLProvider(); toolRegistry.register(new FetchURLTool(fetcher)); @@ -34,8 +34,8 @@ export class WebService implements IWebService { registerScopedService( LifecycleScope.Agent, - IWebService, - WebService, + IAgentWebService, + AgentWebService, InstantiationType.Delayed, 'web', ); diff --git a/packages/agent-core-v2/src/wireRecord/wireRecord.ts b/packages/agent-core-v2/src/wireRecord/wireRecord.ts index 8f1306336..999302c34 100644 --- a/packages/agent-core-v2/src/wireRecord/wireRecord.ts +++ b/packages/agent-core-v2/src/wireRecord/wireRecord.ts @@ -48,7 +48,7 @@ export interface WireRecordRegisterOptions { readonly blobs?: WireRecordBlobSelector>; } -export interface IWireRecord { +export interface IAgentWireRecordService { readonly _serviceBrand: undefined; readonly restoring: WireRecordRestoringContext | null; readonly postRestoring: boolean; @@ -79,4 +79,4 @@ export interface IWireRecord { }>; } -export const IWireRecord = createDecorator('agentWireRecordService'); +export const IAgentWireRecordService = createDecorator('agentWireRecordService'); diff --git a/packages/agent-core-v2/src/wireRecord/wireRecordService.ts b/packages/agent-core-v2/src/wireRecord/wireRecordService.ts index 08c378a97..9f7102d1c 100644 --- a/packages/agent-core-v2/src/wireRecord/wireRecordService.ts +++ b/packages/agent-core-v2/src/wireRecord/wireRecordService.ts @@ -6,7 +6,7 @@ import { Disposable, toDisposable, } from "#/_base/di"; -import { IBlobStoreService } from '#/blobStore'; +import { IAgentBlobStoreService } from '#/blobStore'; import { IBootstrapService } from '#/bootstrap'; import { onUnexpectedError } from '#/_base/errors/unexpectedError'; import { IAppendLogStore } from '#/storage'; @@ -21,7 +21,7 @@ import { type WireMigrationRecord, } from './migration'; import { - IWireRecord, + IAgentWireRecordService, type PersistedWireRecord, type WireRecordBlobSelector, type WireRecordMetadata, @@ -34,7 +34,7 @@ import { type Resumer = (data: WireRecord) => void | Promise; type BlobSelector = WireRecordBlobSelector>; -export class WireRecordService extends Disposable implements IWireRecord { +export class AgentWireRecordService extends Disposable implements IAgentWireRecordService { declare readonly _serviceBrand: undefined; private readonly records: WireRecord[] = []; private readonly resumers = new Map>>(); @@ -54,7 +54,7 @@ export class WireRecordService extends Disposable implements IWireRecord { constructor( @IBootstrapService bootstrap: IBootstrapService, - @IBlobStoreService private readonly blobStore?: IBlobStoreService, + @IAgentBlobStoreService private readonly blobStore?: IAgentBlobStoreService, @IAppendLogStore private readonly log?: IAppendLogStore, ) { super(); @@ -341,8 +341,8 @@ async function* toAsyncIterable( registerScopedService( LifecycleScope.Agent, - IWireRecord, - WireRecordService, + IAgentWireRecordService, + AgentWireRecordService, InstantiationType.Delayed, 'wireRecord', ); diff --git a/packages/agent-core-v2/src/workspaceContext/index.ts b/packages/agent-core-v2/src/workspaceContext/index.ts index 63c36545e..35d7e30ea 100644 --- a/packages/agent-core-v2/src/workspaceContext/index.ts +++ b/packages/agent-core-v2/src/workspaceContext/index.ts @@ -2,7 +2,7 @@ * `workspaceContext` domain barrel — re-exports the workspace-context * contract (`workspaceContext`) and its scoped service * (`workspaceContextService`). Importing this barrel registers the - * `IWorkspaceContext` binding into the scope registry. + * `ISessionWorkspaceContext` binding into the scope registry. */ export * from './workspaceContext'; diff --git a/packages/agent-core-v2/src/workspaceContext/workspaceContext.ts b/packages/agent-core-v2/src/workspaceContext/workspaceContext.ts index 29041e954..1a172c714 100644 --- a/packages/agent-core-v2/src/workspaceContext/workspaceContext.ts +++ b/packages/agent-core-v2/src/workspaceContext/workspaceContext.ts @@ -1,7 +1,7 @@ /** * `workspaceContext` domain (L1) — session workspace root and path access. * - * Defines the `IWorkspaceContext` used by the Agent side to resolve relative + * Defines the `ISessionWorkspaceContext` used by the Agent side to resolve relative * paths against the session work directory and to enforce that file/process * operations stay within the workspace (plus any additional dirs). Pure * configuration + boundary — it performs no IO. Session-scoped. @@ -11,7 +11,7 @@ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiatio export type PathAccessOperation = 'read' | 'write' | 'execute'; -export interface IWorkspaceContext { +export interface ISessionWorkspaceContext { readonly _serviceBrand: undefined; readonly workDir: string; @@ -25,5 +25,5 @@ export interface IWorkspaceContext { removeAdditionalDir(dir: string): void; } -export const IWorkspaceContext: ServiceIdentifier = - createDecorator('workspaceContext'); +export const ISessionWorkspaceContext: ServiceIdentifier = + createDecorator('sessionWorkspaceContext'); diff --git a/packages/agent-core-v2/src/workspaceContext/workspaceContextService.ts b/packages/agent-core-v2/src/workspaceContext/workspaceContextService.ts index 0ea73a28d..34307d662 100644 --- a/packages/agent-core-v2/src/workspaceContext/workspaceContextService.ts +++ b/packages/agent-core-v2/src/workspaceContext/workspaceContextService.ts @@ -1,5 +1,5 @@ /** - * `workspaceContext` domain (L1) — `IWorkspaceContext` implementation. + * `workspaceContext` domain (L1) — `ISessionWorkspaceContext` implementation. * * Holds the session work directory and additional dirs, resolves relative * paths, and checks whether a path falls within the workspace. Bound at @@ -12,9 +12,9 @@ import { InstantiationType } from '#/_base/di/extensions'; import { LifecycleScope, registerScopedService } from '#/_base/di/scope'; import { IKaos } from '#/kaos'; -import { IWorkspaceContext, type PathAccessOperation } from './workspaceContext'; +import { ISessionWorkspaceContext, type PathAccessOperation } from './workspaceContext'; -export class WorkspaceContextService implements IWorkspaceContext { +export class SessionWorkspaceContextService implements ISessionWorkspaceContext { declare readonly _serviceBrand: undefined; private _workDir: string; private _additionalDirs: string[] = []; @@ -71,8 +71,8 @@ export class WorkspaceContextService implements IWorkspaceContext { registerScopedService( LifecycleScope.Session, - IWorkspaceContext, - WorkspaceContextService, + ISessionWorkspaceContext, + SessionWorkspaceContextService, InstantiationType.Delayed, 'workspaceContext', ); diff --git a/packages/agent-core-v2/src/workspaceRegistry/fileWorkspaceStore.ts b/packages/agent-core-v2/src/workspaceRegistry/fileWorkspaceStore.ts index e63b5945e..7093f6131 100644 --- a/packages/agent-core-v2/src/workspaceRegistry/fileWorkspaceStore.ts +++ b/packages/agent-core-v2/src/workspaceRegistry/fileWorkspaceStore.ts @@ -4,7 +4,7 @@ * File backend of `IWorkspaceStore`. Persists the catalog as a single * v1-compatible `workspaces.json` document at the storage root * (`/workspaces.json`, via `scope = ''`) through the - * `IAtomicDocumentStore` access-pattern Store. Bound at Core scope. + * `IAtomicDocumentStore` access-pattern Store. Bound at App scope. */ import { InstantiationType } from '#/_base/di/extensions'; @@ -104,7 +104,7 @@ function parseTime(value: string, fallback: number): number { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IWorkspaceStore, FileWorkspaceStore, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/src/workspaceRegistry/workspaceRegistry.ts b/packages/agent-core-v2/src/workspaceRegistry/workspaceRegistry.ts index b4ffd7b47..db3e11f9b 100644 --- a/packages/agent-core-v2/src/workspaceRegistry/workspaceRegistry.ts +++ b/packages/agent-core-v2/src/workspaceRegistry/workspaceRegistry.ts @@ -4,7 +4,7 @@ * Defines the `IWorkspaceRegistry` used by the program side to remember the * folders the user has opened (backed by the app's own persistence). This is * a host-side catalog, distinct from the session-scoped `workspaceContext` - * that describes one Agent's active work directory. Core-scoped. + * that describes one Agent's active work directory. App-scoped. */ import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; diff --git a/packages/agent-core-v2/src/workspaceRegistry/workspaceRegistryService.ts b/packages/agent-core-v2/src/workspaceRegistry/workspaceRegistryService.ts index 394d69a94..98be45014 100644 --- a/packages/agent-core-v2/src/workspaceRegistry/workspaceRegistryService.ts +++ b/packages/agent-core-v2/src/workspaceRegistry/workspaceRegistryService.ts @@ -7,7 +7,7 @@ * absent or malformed, it is rebuilt once from the legacy * `/session_index.jsonl` (one workspace per distinct absolute * `workDir`) and then persisted. All access is serialized through a - * promise-chain mutex so load/rebuild/mutations never race. Bound at Core + * promise-chain mutex so load/rebuild/mutations never race. Bound at App * scope. */ @@ -175,7 +175,7 @@ function parseSessionIndexLine(line: string): SessionIndexLine | undefined { } registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IWorkspaceRegistry, WorkspaceRegistryService, InstantiationType.Delayed, diff --git a/packages/agent-core-v2/test/agentFs/agentFsService.test.ts b/packages/agent-core-v2/test/agentFs/agentFsService.test.ts index adf5459da..5968c2ced 100644 --- a/packages/agent-core-v2/test/agentFs/agentFsService.test.ts +++ b/packages/agent-core-v2/test/agentFs/agentFsService.test.ts @@ -11,16 +11,16 @@ import { registerScopedService, } from '#/_base/di/scope'; import { createScopedTestHost, stubPair } from '#/_base/di/test'; -import { AgentFileSystem, IAgentFileSystem } from '#/agentFs'; +import { SessionAgentFileSystem, ISessionAgentFileSystem } from '#/agentFs'; import { IKaos, IKaosFactory, KaosFactory } from '#/kaos'; -describe('AgentFileSystem (backed by IKaos)', () => { +describe('SessionAgentFileSystem (backed by IKaos)', () => { let dir: string; beforeEach(async () => { _clearScopedRegistryForTests(); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IKaosFactory, KaosFactory, InstantiationType.Delayed, @@ -28,8 +28,8 @@ describe('AgentFileSystem (backed by IKaos)', () => { ); registerScopedService( LifecycleScope.Session, - IAgentFileSystem, - AgentFileSystem, + ISessionAgentFileSystem, + SessionAgentFileSystem, InstantiationType.Delayed, 'agentFs', ); @@ -40,12 +40,12 @@ describe('AgentFileSystem (backed by IKaos)', () => { await rm(dir, { recursive: true, force: true }); }); - async function makeFs(): Promise { + async function makeFs(): Promise { const host = createScopedTestHost(); - const factory = host.core.accessor.get(IKaosFactory); + const factory = host.app.accessor.get(IKaosFactory); const kaos = await factory.createLocal(dir); const session = host.child(LifecycleScope.Session, 's', [stubPair(IKaos, kaos)]); - return session.accessor.get(IAgentFileSystem); + return session.accessor.get(ISessionAgentFileSystem); } it('writes and reads text relative to cwd', async () => { diff --git a/packages/agent-core-v2/test/agentFs/fsProcess.test.ts b/packages/agent-core-v2/test/agentFs/fsProcess.test.ts index ee9326dc9..7ddba9adc 100644 --- a/packages/agent-core-v2/test/agentFs/fsProcess.test.ts +++ b/packages/agent-core-v2/test/agentFs/fsProcess.test.ts @@ -2,7 +2,7 @@ import { Readable, Writable } from 'node:stream'; import { describe, expect, it } from 'vitest'; -import { type IProcess, type IProcessRunner } from '#/process'; +import { type IProcess, type ISessionProcessRunner } from '#/process'; import { runCommand, type RunCommandOptions } from '#/agentFs/fsProcess'; @@ -29,7 +29,7 @@ function fakeProcess(opts: FakeProcessOptions = {}): IProcess { }; } -function fakeRunner(proc: IProcess): IProcessRunner { +function fakeRunner(proc: IProcess): ISessionProcessRunner { return { _serviceBrand: undefined, exec: () => Promise.resolve(proc), @@ -45,7 +45,7 @@ describe('runCommand', () => { it('passes cwd and env to the runner', async () => { let received: { args: readonly string[]; cwd?: string; env?: Record } | undefined; - const runner: IProcessRunner = { + const runner: ISessionProcessRunner = { _serviceBrand: undefined, exec: (args, options) => { received = { args, cwd: options?.cwd, env: options?.env }; diff --git a/packages/agent-core-v2/test/agentFs/fsService.test.ts b/packages/agent-core-v2/test/agentFs/fsService.test.ts index f98b282ac..16ae0b5a4 100644 --- a/packages/agent-core-v2/test/agentFs/fsService.test.ts +++ b/packages/agent-core-v2/test/agentFs/fsService.test.ts @@ -10,15 +10,15 @@ import { registerScopedService, } from '#/_base/di/scope'; import { createScopedTestHost, stubPair } from '#/_base/di/test'; -import { IAgentFileSystem } from '#/agentFs'; -import { IFsService } from '#/agentFs/fs'; -import { FsService } from '#/agentFs/fsService'; -import { IProcessRunner, type IProcess } from '#/process'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { ISessionAgentFileSystem } from '#/agentFs'; +import { ISessionFsService } from '#/agentFs/fs'; +import { SessionFsService } from '#/agentFs/fsService'; +import { ISessionProcessRunner, type IProcess } from '#/process'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; const WORK_DIR = '/repo'; -function stubWorkspace(): IWorkspaceContext { +function stubWorkspace(): ISessionWorkspaceContext { return { _serviceBrand: undefined, workDir: WORK_DIR, @@ -35,7 +35,7 @@ function stubWorkspace(): IWorkspaceContext { }; } -function fakeFs(files: Record): IAgentFileSystem { +function fakeFs(files: Record): ISessionAgentFileSystem { const fileMap = new Map(Object.entries(files)); const dirSet = new Set(['']); for (const p of fileMap.keys()) { @@ -142,7 +142,7 @@ type RunHandler = (args: readonly string[]) => { exitCode: number; }; -function fakeRunner(handler: RunHandler): IProcessRunner { +function fakeRunner(handler: RunHandler): ISessionProcessRunner { return { _serviceBrand: undefined, exec: async (args) => { @@ -156,8 +156,8 @@ beforeEach(() => { _clearScopedRegistryForTests(); registerScopedService( LifecycleScope.Session, - IFsService, - FsService, + ISessionFsService, + SessionFsService, InstantiationType.Delayed, 'agentFs', ); @@ -170,19 +170,19 @@ afterEach(() => { host = undefined; }); -function makeSession(files: Record, handler: RunHandler): IFsService { +function makeSession(files: Record, handler: RunHandler): ISessionFsService { host = createScopedTestHost(); const session = host.child(LifecycleScope.Session, 's1', [ - stubPair(IWorkspaceContext, stubWorkspace()), - stubPair(IAgentFileSystem, fakeFs(files)), - stubPair(IProcessRunner, fakeRunner(handler)), + stubPair(ISessionWorkspaceContext, stubWorkspace()), + stubPair(ISessionAgentFileSystem, fakeFs(files)), + stubPair(ISessionProcessRunner, fakeRunner(handler)), ]); - return session.accessor.get(IFsService); + return session.accessor.get(ISessionFsService); } const emptyHandler: RunHandler = () => ({ stdout: '', exitCode: 0 }); -describe('FsService.gitStatus', () => { +describe('SessionFsService.gitStatus', () => { it('returns branch, entries, numstat, and null pull request', async () => { const fs = makeSession({}, (args) => { const cmd = args.join(' '); @@ -213,7 +213,7 @@ describe('FsService.gitStatus', () => { }); }); -describe('FsService.diff', () => { +describe('SessionFsService.diff', () => { it('returns the unified diff for a tracked file', async () => { const fs = makeSession({ 'src/a.ts': 'content' }, (args) => { const cmd = args.join(' '); @@ -239,7 +239,7 @@ describe('FsService.diff', () => { }); }); -describe('FsService.search', () => { +describe('SessionFsService.search', () => { it('finds files by fuzzy query and respects the result cap', async () => { const fs = makeSession( { 'src/foo.ts': '', 'src/bar.ts': '', 'README.md': '' }, @@ -252,7 +252,7 @@ describe('FsService.search', () => { }); }); -describe('FsService.grep', () => { +describe('SessionFsService.grep', () => { it('falls back to the node implementation when rg is unavailable', async () => { const fs = makeSession( { 'src/a.ts': 'hello world\nfoo bar\nhello again\n' }, @@ -312,7 +312,7 @@ describe('FsService.grep', () => { }); }); -describe('FsService.list', () => { +describe('SessionFsService.list', () => { it('lists files and directories with kinds', async () => { const fs = makeSession( { 'src/a.ts': '', 'src/sub/b.ts': '', 'README.md': '' }, @@ -365,7 +365,7 @@ describe('FsService.list', () => { }); }); -describe('FsService.read', () => { +describe('SessionFsService.read', () => { it('reads utf-8 content with metadata', async () => { const fs = makeSession({ 'src/a.ts': 'hello\nworld\n' }, emptyHandler); const result = await fs.read({ @@ -413,7 +413,7 @@ describe('FsService.read', () => { }); }); -describe('FsService.stat', () => { +describe('SessionFsService.stat', () => { it('returns a file entry with mime', async () => { const fs = makeSession({ 'src/a.ts': 'content' }, emptyHandler); const entry = await fs.stat({ path: 'src/a.ts' }); @@ -429,7 +429,7 @@ describe('FsService.stat', () => { }); }); -describe('FsService.statMany', () => { +describe('SessionFsService.statMany', () => { it('returns null per missing path and entries for present ones', async () => { const fs = makeSession({ 'a.txt': 'hi' }, emptyHandler); const result = await fs.statMany({ paths: ['a.txt', 'missing.txt'] }); @@ -438,7 +438,7 @@ describe('FsService.statMany', () => { }); }); -describe('FsService.listMany', () => { +describe('SessionFsService.listMany', () => { it('returns results per path and partial_errors for failures', async () => { const fs = makeSession({ 'a.txt': '' }, emptyHandler); const result = await fs.listMany({ @@ -455,7 +455,7 @@ describe('FsService.listMany', () => { }); }); -describe('FsService.mkdir', () => { +describe('SessionFsService.mkdir', () => { it('creates a directory and returns its entry', async () => { const fs = makeSession({}, emptyHandler); const entry = await fs.mkdir({ path: 'newdir', recursive: false }); @@ -471,7 +471,7 @@ describe('FsService.mkdir', () => { }); }); -describe('FsService.resolvePath', () => { +describe('SessionFsService.resolvePath', () => { it('returns absolute, relative, and isDirectory', async () => { const fs = makeSession({ 'src/a.ts': '' }, emptyHandler); const res = await fs.resolvePath('src/a.ts'); @@ -481,7 +481,7 @@ describe('FsService.resolvePath', () => { }); }); -describe('FsService.resolveDownload', () => { +describe('SessionFsService.resolveDownload', () => { it('returns size, etag, mime, modifiedAt', async () => { const fs = makeSession({ 'a.txt': 'hello' }, emptyHandler); const res = await fs.resolveDownload('a.txt'); diff --git a/packages/agent-core-v2/test/approval/approval.test.ts b/packages/agent-core-v2/test/approval/approval.test.ts index c80f70b22..f80f56aba 100644 --- a/packages/agent-core-v2/test/approval/approval.test.ts +++ b/packages/agent-core-v2/test/approval/approval.test.ts @@ -5,10 +5,10 @@ import { SyncDescriptor } from '#/_base/di/descriptors'; import { DisposableStore } from '#/_base/di/lifecycle'; import { TestInstantiationService } from '#/_base/di/test'; import type { ApprovalRequest } from '#/approval'; -import { IApprovalService } from '#/approval'; -import { ApprovalService } from '#/approval/approvalService'; -import { IInteractionService } from '#/interaction'; -import { InteractionService } from '#/interaction/interactionService'; +import { ISessionApprovalService } from '#/approval'; +import { SessionApprovalService } from '#/approval/approvalService'; +import { ISessionInteractionService } from '#/interaction'; +import { SessionInteractionService } from '#/interaction/interactionService'; const display: ToolInputDisplay = { kind: 'command', command: 'bash' }; @@ -16,20 +16,20 @@ function makeRequest(id: string): ApprovalRequest { return { id, toolName: 'bash', action: 'run', display }; } -describe('ApprovalService', () => { +describe('SessionApprovalService', () => { let disposables: DisposableStore; let ix: TestInstantiationService; beforeEach(() => { disposables = new DisposableStore(); ix = disposables.add(new TestInstantiationService()); - ix.set(IInteractionService, new SyncDescriptor(InteractionService)); - ix.set(IApprovalService, new SyncDescriptor(ApprovalService)); + ix.set(ISessionInteractionService, new SyncDescriptor(SessionInteractionService)); + ix.set(ISessionApprovalService, new SyncDescriptor(SessionApprovalService)); }); afterEach(() => disposables.dispose()); it('request parks until decide resolves it', async () => { - const svc = ix.get(IApprovalService); + const svc = ix.get(ISessionApprovalService); const req = makeRequest('r1'); const p = svc.request(req); expect(svc.listPending()).toEqual([req]); @@ -39,12 +39,12 @@ describe('ApprovalService', () => { }); it('decide on unknown id is a no-op', () => { - const svc = ix.get(IApprovalService); + const svc = ix.get(ISessionApprovalService); expect(() => svc.decide('missing', { decision: 'rejected' })).not.toThrow(); }); it('enqueue parks a request and returns it with its id without blocking', () => { - const svc = ix.get(IApprovalService); + const svc = ix.get(ISessionApprovalService); const enqueued = svc.enqueue(makeRequest('r1')); expect(enqueued).toEqual({ ...makeRequest('r1'), id: 'r1' }); expect(svc.listPending()).toEqual([makeRequest('r1')]); diff --git a/packages/agent-core-v2/test/approval/stubs.ts b/packages/agent-core-v2/test/approval/stubs.ts index 07afdfac7..894b374fa 100644 --- a/packages/agent-core-v2/test/approval/stubs.ts +++ b/packages/agent-core-v2/test/approval/stubs.ts @@ -1,14 +1,14 @@ /** - * `approval` test stubs — shared doubles for `IApprovalService`. + * `approval` test stubs — shared doubles for `ISessionApprovalService`. * * Lives under `test/` (not `src/`) so test-support code stays out of the * production tree. Import from a relative path (`./stubs` or * `../approval/stubs`). */ -import type { ApprovalResponse, IApprovalService } from '#/approval/approval'; +import type { ApprovalResponse, ISessionApprovalService } from '#/approval/approval'; -export function stubApprovalService(respond: () => ApprovalResponse): IApprovalService { +export function stubApprovalService(respond: () => ApprovalResponse): ISessionApprovalService { return { _serviceBrand: undefined, request: async () => respond(), diff --git a/packages/agent-core-v2/test/background/agent-timeout.test.ts b/packages/agent-core-v2/test/background/agent-timeout.test.ts index 3a580a2b5..89d683db7 100644 --- a/packages/agent-core-v2/test/background/agent-timeout.test.ts +++ b/packages/agent-core-v2/test/background/agent-timeout.test.ts @@ -1,5 +1,5 @@ /** - * BackgroundService task timeout for AgentBackgroundTask registrations. + * AgentBackgroundService task timeout for AgentBackgroundTask registrations. * * Semantics: * - manager-owned deadline fires → status=`timed_out` @@ -11,7 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { AgentBackgroundTask, IBackgroundService } from '#/background'; +import { AgentBackgroundTask, IAgentBackgroundService } from '#/background'; import { createTestAgent, type TestAgentContext } from '../harness'; function agentTask( @@ -28,11 +28,11 @@ function agentTask( describe('AgentBackgroundTask — timeoutMs', () => { let ctx: TestAgentContext; - let background: IBackgroundService; + let background: IAgentBackgroundService; beforeEach(() => { ctx = createTestAgent(); - background = ctx.get(IBackgroundService); + background = ctx.get(IAgentBackgroundService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/background/background.test.ts b/packages/agent-core-v2/test/background/background.test.ts index cc5920958..de1dedb56 100644 --- a/packages/agent-core-v2/test/background/background.test.ts +++ b/packages/agent-core-v2/test/background/background.test.ts @@ -3,18 +3,18 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { SyncDescriptor } from '#/_base/di/descriptors'; import { DisposableStore, toDisposable } from '#/_base/di/lifecycle'; import { TestInstantiationService } from '#/_base/di/test'; -import { IBackgroundService, type BackgroundTask } from '#/background'; -import { BackgroundService } from '#/background/backgroundService'; +import { IAgentBackgroundService, type BackgroundTask } from '#/background'; +import { AgentBackgroundService } from '#/background/backgroundService'; import { IConfigRegistry, IConfigService } from '#/config'; -import { IContextMemory } from '#/contextMemory'; -import { IEventSink } from '#/eventSink'; -import { IExternalHooksService } from '#/externalHooks'; -import { IPromptService } from '#/prompt'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentEventSinkService } from '#/eventSink'; +import { IAgentExternalHooksService } from '#/externalHooks'; +import { IAgentPromptService } from '#/prompt'; import { ISessionContext } from '#/session-context'; import { IAtomicDocumentStore, IStorageService } from '#/storage'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { IAgentWireRecordService } from '#/wireRecord'; import { stubContextMemory, stubWireRecord } from '../contextMemory/stubs'; @@ -28,22 +28,22 @@ function fakeProcessTask(): BackgroundTask { }; } -describe('BackgroundService', () => { +describe('AgentBackgroundService', () => { let disposables: DisposableStore; let ix: TestInstantiationService; beforeEach(() => { disposables = new DisposableStore(); ix = disposables.add(new TestInstantiationService()); - ix.stub(IWireRecord, stubWireRecord()); - ix.stub(IContextMemory, stubContextMemory()); - ix.stub(IEventSink, { emit: () => {}, on: () => toDisposable(() => {}) }); + ix.stub(IAgentWireRecordService, stubWireRecord()); + ix.stub(IAgentContextMemoryService, stubContextMemory()); + ix.stub(IAgentEventSinkService, { emit: () => {}, on: () => toDisposable(() => {}) }); ix.stub(ITelemetryService, { track: () => {} }); - ix.stub(IToolRegistry, { + ix.stub(IAgentToolRegistryService, { register: () => toDisposable(() => {}), }); - ix.stub(IPromptService, { steer: () => undefined }); - ix.stub(IExternalHooksService, { triggerNotification: () => {} }); + ix.stub(IAgentPromptService, { steer: () => undefined }); + ix.stub(IAgentExternalHooksService, { triggerNotification: () => {} }); ix.stub(IConfigRegistry, { registerSection: () => {} }); ix.stub(IConfigService, { get: (() => undefined) as IConfigService['get'], @@ -70,12 +70,12 @@ describe('BackgroundService', () => { flush: async () => {}, close: async () => {}, }); - ix.set(IBackgroundService, new SyncDescriptor(BackgroundService)); + ix.set(IAgentBackgroundService, new SyncDescriptor(AgentBackgroundService)); }); afterEach(() => disposables.dispose()); it('registerTask / list / readOutput / stop', async () => { - const svc = ix.get(IBackgroundService); + const svc = ix.get(IAgentBackgroundService); const id = svc.registerTask(fakeProcessTask()); const listed = svc.list(); expect(listed).toHaveLength(1); diff --git a/packages/agent-core-v2/test/background/bg-idle-notification-repro.test.ts b/packages/agent-core-v2/test/background/bg-idle-notification-repro.test.ts index 9b0e74cf9..a6a480ca2 100644 --- a/packages/agent-core-v2/test/background/bg-idle-notification-repro.test.ts +++ b/packages/agent-core-v2/test/background/bg-idle-notification-repro.test.ts @@ -24,11 +24,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { AgentBackgroundTask, - IBackgroundService, + IAgentBackgroundService, } from '#/background'; -import { IPromptService } from '#/prompt'; -import { IProfileService } from '#/profile'; -import { ITurnService } from '#/turn'; +import { IAgentPromptService } from '#/prompt'; +import { IAgentProfileService } from '#/profile'; +import { IAgentTurnService } from '#/turn'; import { backgroundServices, createTestAgent, @@ -55,17 +55,17 @@ function agentTask( describe('background notification → main agent (real Agent instance)', () => { describe('live notification delivery', () => { let ctx: TestAgentContext; - let background: IBackgroundService; - let prompt: IPromptService; - let turn: ITurnService; - let profile: IProfileService; + let background: IAgentBackgroundService; + let prompt: IAgentPromptService; + let turn: IAgentTurnService; + let profile: IAgentProfileService; beforeEach(() => { ctx = createTestAgent(); - background = ctx.get(IBackgroundService); - prompt = ctx.get(IPromptService); - turn = ctx.get(ITurnService); - profile = ctx.get(IProfileService); + background = ctx.get(IAgentBackgroundService); + prompt = ctx.get(IAgentPromptService); + turn = ctx.get(IAgentTurnService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: [] }); }); @@ -275,8 +275,8 @@ describe('background notification → main agent (real Agent instance)', () => { let sessionDir: string; let ctx: TestAgentContext; let background: BackgroundServiceTestManager; - let prompt: IPromptService; - let turn: ITurnService; + let prompt: IAgentPromptService; + let turn: IAgentTurnService; beforeEach(async () => { sessionDir = await mkdtemp(join(tmpdir(), 'kimi-bg-resume-repro-')); @@ -306,10 +306,10 @@ describe('background notification → main agent (real Agent instance)', () => { }); ctx = createTestAgent(homeDirServices(sessionDir), backgroundServices()); - background = ctx.get(IBackgroundService) as BackgroundServiceTestManager; - prompt = ctx.get(IPromptService); - turn = ctx.get(ITurnService); - const profile = ctx.get(IProfileService); + background = ctx.get(IAgentBackgroundService) as BackgroundServiceTestManager; + prompt = ctx.get(IAgentPromptService); + turn = ctx.get(IAgentTurnService); + const profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: [] }); }); diff --git a/packages/agent-core-v2/test/background/foreground-persistence.test.ts b/packages/agent-core-v2/test/background/foreground-persistence.test.ts index f4a9ddc4a..3094822db 100644 --- a/packages/agent-core-v2/test/background/foreground-persistence.test.ts +++ b/packages/agent-core-v2/test/background/foreground-persistence.test.ts @@ -15,7 +15,7 @@ import type { KaosProcess } from '@moonshot-ai/kaos'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { - IBackgroundService, + IAgentBackgroundService, ProcessBackgroundTask, } from '#/background'; import { @@ -79,7 +79,7 @@ function controllableProcess(): { } function registerForeground( - background: IBackgroundService, + background: IAgentBackgroundService, proc: KaosProcess, command: string, description: string, @@ -93,13 +93,13 @@ describe('BackgroundManager — foreground persistence', () => { let sessionDir: string; let persistence: ReturnType; let ctx: TestAgentContext; - let background: IBackgroundService; + let background: IAgentBackgroundService; beforeEach(() => { sessionDir = mkdtempSync(join(tmpdir(), 'bpm-fg-')); persistence = createBackgroundTaskPersistence(sessionDir); ctx = createTestAgent(homeDirServices(sessionDir), backgroundServices()); - background = ctx.get(IBackgroundService); + background = ctx.get(IAgentBackgroundService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/background/heartbeat-stale.test.ts b/packages/agent-core-v2/test/background/heartbeat-stale.test.ts index e69d2784f..976105ffc 100644 --- a/packages/agent-core-v2/test/background/heartbeat-stale.test.ts +++ b/packages/agent-core-v2/test/background/heartbeat-stale.test.ts @@ -9,10 +9,10 @@ import { join } from 'pathe'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { - IBackgroundService, + IAgentBackgroundService, type BackgroundTaskInfo, } from '#/background'; -import { IEventSink } from '#/eventSink'; +import { IAgentEventSinkService } from '#/eventSink'; import { backgroundServices, createTestAgent, @@ -61,9 +61,9 @@ describe('Background reconcile — stale ghost detection', () => { beforeEach(() => { ctx = createTestAgent(homeDirServices(sessionDir), backgroundServices()); - background = ctx.get(IBackgroundService) as BackgroundServiceTestManager; + background = ctx.get(IAgentBackgroundService) as BackgroundServiceTestManager; emittedEvents = []; - const events = ctx.get(IEventSink); + const events = ctx.get(IAgentEventSinkService); events.on((event) => { emittedEvents.push(event); }); diff --git a/packages/agent-core-v2/test/background/ids.test.ts b/packages/agent-core-v2/test/background/ids.test.ts index 5f24f006f..c7995c04f 100644 --- a/packages/agent-core-v2/test/background/ids.test.ts +++ b/packages/agent-core-v2/test/background/ids.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { AgentBackgroundTask, - IBackgroundService, + IAgentBackgroundService, ProcessBackgroundTask, } from '#/background'; import type { SessionSubagentHost, SubagentHandle } from '#/subagentHost'; @@ -14,7 +14,7 @@ import { createTestAgent, type TestAgentContext } from '../harness'; import { createBackgroundTaskPersistence } from './stubs'; function registerProcess( - manager: IBackgroundService, + manager: IAgentBackgroundService, proc: KaosProcess, command: string, description: string, @@ -69,11 +69,11 @@ function pendingProcess(): KaosProcess & { resolve(code: number): void } { describe('background task id format', () => { let ctx: TestAgentContext; - let background: IBackgroundService; + let background: IAgentBackgroundService; beforeEach(() => { ctx = createTestAgent(); - background = ctx.get(IBackgroundService); + background = ctx.get(IAgentBackgroundService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/background/manager.test.ts b/packages/agent-core-v2/test/background/manager.test.ts index e2eb95f91..71e569944 100644 --- a/packages/agent-core-v2/test/background/manager.test.ts +++ b/packages/agent-core-v2/test/background/manager.test.ts @@ -13,7 +13,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { AgentBackgroundTask, - IBackgroundService, + IAgentBackgroundService, ProcessBackgroundTask, type BackgroundTaskInfo, } from '#/background'; @@ -59,13 +59,13 @@ function createBackgroundManager(options: { const ctx = createTestAgent(...overrides); return { ctx, - manager: ctx.get(IBackgroundService) as BackgroundServiceTestManager, + manager: ctx.get(IAgentBackgroundService) as BackgroundServiceTestManager, persistence, }; } function registerProcess( - manager: IBackgroundService, + manager: IAgentBackgroundService, proc: KaosProcess, command: string, description: string, @@ -106,7 +106,7 @@ function agentTask( } async function waitForTerminal( - manager: IBackgroundService, + manager: IAgentBackgroundService, taskId: string, timeoutMs = 30_000, ): Promise { @@ -128,7 +128,7 @@ async function waitForTerminal( } async function waitForOutput( - manager: IBackgroundService, + manager: IAgentBackgroundService, taskId: string, expected: string, ): Promise { diff --git a/packages/agent-core-v2/test/background/output-access.test.ts b/packages/agent-core-v2/test/background/output-access.test.ts index f2d50e12d..15e01e6a0 100644 --- a/packages/agent-core-v2/test/background/output-access.test.ts +++ b/packages/agent-core-v2/test/background/output-access.test.ts @@ -5,7 +5,7 @@ import type { Writable } from 'node:stream'; import { join } from 'pathe'; import type { KaosProcess } from '@moonshot-ai/kaos'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { IBackgroundService, ProcessBackgroundTask } from '#/background'; +import { IAgentBackgroundService, ProcessBackgroundTask } from '#/background'; import { createBackgroundTaskPersistence, type BackgroundServiceTestManager } from './stubs'; import { backgroundServices, createTestAgent, homeDirServices, type TestAgentContext } from '../harness'; @@ -18,7 +18,7 @@ interface BackgroundServiceFixture { function createBackgroundService(homedir: string): BackgroundServiceFixture { const persistence = createBackgroundTaskPersistence(homedir); const ctx = createTestAgent(homeDirServices(homedir), backgroundServices()); - const manager = ctx.get(IBackgroundService) as BackgroundServiceTestManager; + const manager = ctx.get(IAgentBackgroundService) as BackgroundServiceTestManager; return { ctx, manager, @@ -27,7 +27,7 @@ function createBackgroundService(homedir: string): BackgroundServiceFixture { } function registerProcess( - manager: IBackgroundService, + manager: IAgentBackgroundService, proc: KaosProcess, command: string, description: string, @@ -36,7 +36,7 @@ function registerProcess( } async function waitForOutput( - manager: IBackgroundService, + manager: IAgentBackgroundService, taskId: string, expected: string, ): Promise { diff --git a/packages/agent-core-v2/test/background/persist.test.ts b/packages/agent-core-v2/test/background/persist.test.ts index 3b61c1e2f..3d5cdf9dd 100644 --- a/packages/agent-core-v2/test/background/persist.test.ts +++ b/packages/agent-core-v2/test/background/persist.test.ts @@ -53,7 +53,7 @@ beforeEach(async () => { await mkdir(sessionDir, { recursive: true }); // `BackgroundTaskPersistence` is a plain (non-DI) helper constructed by - // `BackgroundService`, so the test builds it directly. Its `docs` + // `AgentBackgroundService`, so the test builds it directly. Its `docs` // collaborator (`IAtomicDocumentStore`) carries an `@IService` dependency, so // it is resolved by interface through the container rather than `new`ed. disposables = new DisposableStore(); diff --git a/packages/agent-core-v2/test/background/persistence-compat.test.ts b/packages/agent-core-v2/test/background/persistence-compat.test.ts index 4bf2b8617..5a3aea767 100644 --- a/packages/agent-core-v2/test/background/persistence-compat.test.ts +++ b/packages/agent-core-v2/test/background/persistence-compat.test.ts @@ -4,7 +4,7 @@ import { join } from 'pathe'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { IBackgroundService } from '#/background'; +import { IAgentBackgroundService } from '#/background'; import { backgroundServices, createTestAgent, @@ -102,7 +102,7 @@ describe('BackgroundTaskPersistence legacy compatibility', () => { it('migrates legacy records through load/reconcile writeback', async () => { const ctx: TestAgentContext = createTestAgent(homeDirServices(sessionDir), backgroundServices()); - const background = ctx.get(IBackgroundService) as BackgroundServiceTestManager; + const background = ctx.get(IAgentBackgroundService) as BackgroundServiceTestManager; await writeLegacyTask('bash-orphan01', { task_id: 'bash-orphan01', command: 'sleep 60', diff --git a/packages/agent-core-v2/test/background/reconcile.test.ts b/packages/agent-core-v2/test/background/reconcile.test.ts index 13ea2f7fc..e1c45605a 100644 --- a/packages/agent-core-v2/test/background/reconcile.test.ts +++ b/packages/agent-core-v2/test/background/reconcile.test.ts @@ -9,10 +9,10 @@ import { join } from 'pathe'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { - IBackgroundService, + IAgentBackgroundService, type BackgroundTaskInfo, } from '#/background'; -import { IEventSink } from '#/eventSink'; +import { IAgentEventSinkService } from '#/eventSink'; import { backgroundServices, createTestAgent, @@ -64,7 +64,7 @@ describe('BackgroundManager — loadFromDisk + reconcile', () => { beforeEach(() => { ctx = createTestAgent(backgroundServices()); - background = ctx.get(IBackgroundService) as BackgroundServiceTestManager; + background = ctx.get(IAgentBackgroundService) as BackgroundServiceTestManager; }); afterEach(async () => { @@ -89,9 +89,9 @@ describe('BackgroundManager — loadFromDisk + reconcile', () => { beforeEach(() => { ctx = createTestAgent(homeDirServices(sessionDir), backgroundServices()); - background = ctx.get(IBackgroundService) as BackgroundServiceTestManager; + background = ctx.get(IAgentBackgroundService) as BackgroundServiceTestManager; emittedEvents = []; - const events = ctx.get(IEventSink); + const events = ctx.get(IAgentEventSinkService); events.on((event) => { emittedEvents.push(event); }); diff --git a/packages/agent-core-v2/test/background/rpc-events.test.ts b/packages/agent-core-v2/test/background/rpc-events.test.ts index cd0bebdf2..463ab88b5 100644 --- a/packages/agent-core-v2/test/background/rpc-events.test.ts +++ b/packages/agent-core-v2/test/background/rpc-events.test.ts @@ -1,5 +1,5 @@ /** - * Covers BackgroundService event emission and notification delivery. + * Covers AgentBackgroundService event emission and notification delivery. */ import { mkdtemp, rm } from 'node:fs/promises'; @@ -14,13 +14,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { AgentBackgroundTask, type BackgroundTaskInfo, - IBackgroundService, + IAgentBackgroundService, ProcessBackgroundTask, } from '#/background'; -import { IContextMemory } from '#/contextMemory'; -import { IEventSink } from '#/eventSink'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentEventSinkService } from '#/eventSink'; import type { HookEngine } from '#/externalHooks/engine'; -import { IPromptService } from '#/prompt'; +import { IAgentPromptService } from '#/prompt'; import type { SessionSubagentHost, SubagentHandle } from '#/subagentHost'; import { configServices, @@ -200,13 +200,13 @@ function createBackgroundManager(options: { const ctx = createTestAgent(...overrides); const emittedEvents: Array<{ type: string; info?: unknown }> = []; - const events = ctx.get(IEventSink); + const events = ctx.get(IAgentEventSinkService); const disposable = events.on((event) => { emittedEvents.push(event as { type: string; info?: unknown }); }); - const steerSpy = vi.spyOn(ctx.get(IPromptService), 'steer').mockReturnValue(undefined); - const context = ctx.get(IContextMemory); + const steerSpy = vi.spyOn(ctx.get(IAgentPromptService), 'steer').mockReturnValue(undefined); + const context = ctx.get(IAgentContextMemoryService); const spliceHistorySpy = vi.spyOn(context, 'splice'); const agent: FakeBackgroundAgent = { @@ -232,7 +232,7 @@ function createBackgroundManager(options: { return { ctx, agent, - manager: ctx.get(IBackgroundService) as BackgroundServiceTestManager, + manager: ctx.get(IAgentBackgroundService) as BackgroundServiceTestManager, persistence, }; } @@ -249,7 +249,7 @@ function firstAppendedContextMessage(agent: FakeBackgroundAgent): TestContextMes } function registerProcess( - manager: IBackgroundService, + manager: IAgentBackgroundService, proc: KaosProcess, command: string, description: string, @@ -578,7 +578,7 @@ describe('BackgroundManager — notification delivery', () => { await persistence.writeTask(persistedAgent({ taskId: 'agent-seen0000' })); await persistence.appendTaskOutput('agent-seen0000', 'already delivered summary'); const { agent, ctx, manager } = createBackgroundManager({ sessionDir }); - const context = ctx.get(IContextMemory); + const context = ctx.get(IAgentContextMemoryService); context.splice(context.get().length, 0, [ { role: 'user', diff --git a/packages/agent-core-v2/test/background/stubs.ts b/packages/agent-core-v2/test/background/stubs.ts index 356de1442..da4f40d60 100644 --- a/packages/agent-core-v2/test/background/stubs.ts +++ b/packages/agent-core-v2/test/background/stubs.ts @@ -3,11 +3,11 @@ import { join } from 'pathe'; import { BackgroundTaskPersistence, type BackgroundTaskInfo, - type IBackgroundService, + type IAgentBackgroundService, } from '#/background'; import { AtomicDocumentStore, FileStorageService } from '#/storage'; -export type BackgroundServiceTestManager = IBackgroundService & { +export type BackgroundServiceTestManager = IAgentBackgroundService & { loadFromDisk(): Promise; reconcile(): Promise; }; diff --git a/packages/agent-core-v2/test/blobStore/blobStoreService.test.ts b/packages/agent-core-v2/test/blobStore/blobStoreService.test.ts index 389a66911..4221bf95b 100644 --- a/packages/agent-core-v2/test/blobStore/blobStoreService.test.ts +++ b/packages/agent-core-v2/test/blobStore/blobStoreService.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import type { ContentPart } from '@moonshot-ai/kosong'; import { LifecycleScope } from '#/_base/di/scope'; import { createScopedTestHost, stubPair } from '#/_base/di/test'; -import { IBlobStoreService } from '#/blobStore'; +import { IAgentBlobStoreService } from '#/blobStore'; import { IBlobStorage, InMemoryStorageService } from '#/storage'; function makeLargeDataUri(mimeType = 'image/png'): { uri: string; payload: string } { @@ -17,7 +17,7 @@ function makeSmallDataUri(mimeType = 'image/png'): { uri: string; payload: strin return { uri: `data:${mimeType};base64,${payload}`, payload }; } -describe('BlobStoreService', () => { +describe('AgentBlobStoreService', () => { let host: ReturnType; beforeEach(() => { @@ -28,9 +28,9 @@ describe('BlobStoreService', () => { host.dispose(); }); - function getBlobStore(): IBlobStoreService { - const agent = host.core.createChild(LifecycleScope.Agent, 'test-agent'); - return agent.accessor.get(IBlobStoreService); + function getBlobStore(): IAgentBlobStoreService { + const agent = host.app.createChild(LifecycleScope.Agent, 'test-agent'); + return agent.accessor.get(IAgentBlobStoreService); } it('leaves small data URIs unchanged', async () => { @@ -56,7 +56,7 @@ describe('BlobStoreService', () => { expect(store.isBlobRef(newUrl)).toBe(true); expect(newUrl.startsWith('blobref:image/png;')).toBe(true); - const backend = host.core.accessor.get(IBlobStorage); + const backend = host.app.accessor.get(IBlobStorage); const keys = await backend.list('blobs'); expect(keys).toHaveLength(1); expect(Buffer.from((await backend.read('blobs', keys[0]!))!).toString('base64')).toBe(payload); diff --git a/packages/agent-core-v2/test/blobStore/blobref.test.ts b/packages/agent-core-v2/test/blobStore/blobref.test.ts index ebcc48c77..37a887dd0 100644 --- a/packages/agent-core-v2/test/blobStore/blobref.test.ts +++ b/packages/agent-core-v2/test/blobStore/blobref.test.ts @@ -11,10 +11,10 @@ import { DisposableStore } from '#/_base/di/lifecycle'; import { TestInstantiationService } from '#/_base/di/test'; import { BLOBREF_PROTOCOL, - IBlobStoreService, + IAgentBlobStoreService, MISSING_MEDIA_PLACEHOLDER, } from '#/blobStore'; -import { BlobStoreService } from '#/blobStore/blobStoreService'; +import { AgentBlobStoreService } from '#/blobStore/blobStoreService'; import { FileStorageService, IBlobStorage } from '#/storage'; const cleanups: string[] = []; @@ -58,18 +58,18 @@ async function makeHomeDir(): Promise<{ homeDir: string; blobsDir: string }> { function createStore( homeDir: string, - ctor: typeof BlobStoreService = BlobStoreService, -): IBlobStoreService { + ctor: typeof AgentBlobStoreService = AgentBlobStoreService, +): IAgentBlobStoreService { const disposable = new DisposableStore(); disposables.push(disposable); const ix = disposable.add(new TestInstantiationService()); ix.set(IBlobStorage, new FileStorageService(homeDir)); - ix.set(IBlobStoreService, new SyncDescriptor(ctor)); - return ix.get(IBlobStoreService); + ix.set(IAgentBlobStoreService, new SyncDescriptor(ctor)); + return ix.get(IAgentBlobStoreService); } -async function makeStore(): Promise<{ store: IBlobStoreService; blobsDir: string }> { +async function makeStore(): Promise<{ store: IAgentBlobStoreService; blobsDir: string }> { const { homeDir, blobsDir } = await makeHomeDir(); return { store: createStore(homeDir), @@ -77,13 +77,13 @@ async function makeStore(): Promise<{ store: IBlobStoreService; blobsDir: string }; } -class TwoBlobCacheStoreService extends BlobStoreService { +class TwoBlobCacheStoreService extends AgentBlobStoreService { protected override get maxCacheSize(): number { return 8_000; } } -class OneBlobCacheStoreService extends BlobStoreService { +class OneBlobCacheStoreService extends AgentBlobStoreService { protected override get maxCacheSize(): number { return 4_000; } diff --git a/packages/agent-core-v2/test/bootstrap/bootstrapService.test.ts b/packages/agent-core-v2/test/bootstrap/bootstrapService.test.ts index 62070cafc..df1c9ca58 100644 --- a/packages/agent-core-v2/test/bootstrap/bootstrapService.test.ts +++ b/packages/agent-core-v2/test/bootstrap/bootstrapService.test.ts @@ -18,7 +18,7 @@ describe('BootstrapService (scoped)', () => { beforeEach(() => { _clearScopedRegistryForTests(); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IBootstrapService, BootstrapService, InstantiationType.Eager, @@ -28,7 +28,7 @@ describe('BootstrapService (scoped)', () => { it('resolves homeDir/configPath from the seeded context token', () => { const host = createScopedTestHost(bootstrapSeed({ homeDir: '/tmp/kimi-home' })); - const svc = host.core.accessor.get(IBootstrapService); + const svc = host.app.accessor.get(IBootstrapService); expect(svc.homeDir).toBe('/tmp/kimi-home'); expect(svc.configPath).toBe('/tmp/kimi-home/config.toml'); expect(svc.sessionsDir).toBe('/tmp/kimi-home/sessions'); @@ -37,7 +37,7 @@ describe('BootstrapService (scoped)', () => { it('getEnv reads from the seeded env bag', () => { const host = createScopedTestHost(bootstrapSeed({ env: { FOO: 'bar' } })); - const svc = host.core.accessor.get(IBootstrapService); + const svc = host.app.accessor.get(IBootstrapService); expect(svc.getEnv('FOO')).toBe('bar'); expect(svc.getEnv('MISSING')).toBeUndefined(); host.dispose(); @@ -45,7 +45,7 @@ describe('BootstrapService (scoped)', () => { it('detect() returns a cached OS/shell probe', async () => { const host = createScopedTestHost(bootstrapSeed({ homeDir: '/tmp/kimi-home' })); - const svc = host.core.accessor.get(IBootstrapService); + const svc = host.app.accessor.get(IBootstrapService); const a = await svc.detect(); const b = await svc.detect(); expect(a).toBe(b); @@ -65,12 +65,12 @@ describe('resolveBootstrapOptions', () => { describe('bootstrap() storage seeding', () => { it('routes each storage role token to its own FileStorageService instance', () => { - const { core } = bootstrap({ homeDir: '/tmp/kimi-home' }); + const { app } = bootstrap({ homeDir: '/tmp/kimi-home' }); try { - const storage = core.accessor.get(IStorageService); - const appendLog = core.accessor.get(IAppendLogStorage); - const atomicDoc = core.accessor.get(IAtomicDocumentStorage); - const blob = core.accessor.get(IBlobStorage); + const storage = app.accessor.get(IStorageService); + const appendLog = app.accessor.get(IAppendLogStorage); + const atomicDoc = app.accessor.get(IAtomicDocumentStorage); + const blob = app.accessor.get(IBlobStorage); for (const instance of [storage, appendLog, atomicDoc, blob]) { expect(instance).toBeInstanceOf(FileStorageService); @@ -80,7 +80,7 @@ describe('bootstrap() storage seeding', () => { // shared backend instance by default. expect(new Set([storage, appendLog, atomicDoc, blob]).size).toBe(4); } finally { - core.dispose(); + app.dispose(); } }); }); diff --git a/packages/agent-core-v2/test/chatProvider/chatProviderFactory.test.ts b/packages/agent-core-v2/test/chatProvider/chatProviderFactory.test.ts index aa6355e48..d2ea7298f 100644 --- a/packages/agent-core-v2/test/chatProvider/chatProviderFactory.test.ts +++ b/packages/agent-core-v2/test/chatProvider/chatProviderFactory.test.ts @@ -31,8 +31,8 @@ function stubProvider(): ChatProvider { describe('ChatProviderFactory', () => { it('creates a built-in adapter by type', () => { const host = createScopedTestHost(); - afterEach(() => host.core.dispose()); - const factory = host.core.accessor.get(IChatProviderFactory); + afterEach(() => host.app.dispose()); + const factory = host.app.accessor.get(IChatProviderFactory); const provider = factory.create({ type: 'kimi', model: 'kimi-model', apiKey: 'sk-test' }); expect(provider.name).toBe('kimi'); expect(provider.modelName).toBe('kimi-model'); @@ -40,8 +40,8 @@ describe('ChatProviderFactory', () => { it('lets a registered factory override a built-in type', () => { const host = createScopedTestHost(); - afterEach(() => host.core.dispose()); - const factory = host.core.accessor.get(IChatProviderFactory); + afterEach(() => host.app.dispose()); + const factory = host.app.accessor.get(IChatProviderFactory); const stub = stubProvider(); factory.register('kimi', () => stub); expect(factory.create({ type: 'kimi', model: 'x' })).toBe(stub); diff --git a/packages/agent-core-v2/test/config/config.test.ts b/packages/agent-core-v2/test/config/config.test.ts index 7c8c40f58..c738cbfe5 100644 --- a/packages/agent-core-v2/test/config/config.test.ts +++ b/packages/agent-core-v2/test/config/config.test.ts @@ -2,7 +2,7 @@ import type { Environment } from '@moonshot-ai/kaos'; import type { ModelCapability, ProviderConfig, ToolCall } from '@moonshot-ai/kosong'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { IProfileService, type ResolvedAgentProfile } from '#/profile'; +import { IAgentProfileService, type ResolvedAgentProfile } from '#/profile'; import { AGENT_WIRE_PROTOCOL_VERSION } from '#/wireRecord'; import { createTestAgent, type TestAgentContext } from '../harness'; import { DEFAULT_TEST_SYSTEM_PROMPT } from '../harness/snapshots'; @@ -17,11 +17,11 @@ const TEST_OS_ENV: Environment = { describe('Agent config', () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; beforeEach(() => { ctx = createTestAgent(); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/contextInjector/manager.test.ts b/packages/agent-core-v2/test/contextInjector/manager.test.ts index 305d810f7..ebf5fe958 100644 --- a/packages/agent-core-v2/test/contextInjector/manager.test.ts +++ b/packages/agent-core-v2/test/contextInjector/manager.test.ts @@ -5,21 +5,21 @@ import { createServices, type TestInstantiationService, } from '#/_base/di/test'; -import { IContextInjector } from '#/contextInjector'; -import { ContextInjectorService } from '#/contextInjector/contextInjectorService'; -import { IContextMemory, type ContextMessage } from '#/contextMemory'; -import { IProfileService } from '#/profile'; -import { ISystemReminderService } from '#/systemReminder'; -import { SystemReminderService } from '#/systemReminder/systemReminderService'; -import { ITodoListService, TODO_LIST_REMINDER_VARIANT } from '#/todoList'; -import { TodoListService } from '#/todoList/todoListService'; -import { IToolRegistry } from '#/toolRegistry'; -import { IToolStoreService } from '#/toolStore'; -import { ITurnService } from '#/turn'; +import { IAgentContextInjectorService } from '#/contextInjector'; +import { AgentContextInjectorService } from '#/contextInjector/contextInjectorService'; +import { IAgentContextMemoryService, type ContextMessage } from '#/contextMemory'; +import { IAgentProfileService } from '#/profile'; +import { IAgentSystemReminderService } from '#/systemReminder'; +import { AgentSystemReminderService } from '#/systemReminder/systemReminderService'; +import { IAgentTodoListService, TODO_LIST_REMINDER_VARIANT } from '#/todoList'; +import { AgentTodoListService } from '#/todoList/todoListService'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { IAgentToolStoreService } from '#/toolStore'; +import { IAgentTurnService } from '#/turn'; import { registerContextMemoryServices } from '../contextMemory/stubs'; import { stubTurnWithHooks } from '../turn/stubs'; -type InjectableContextInjector = IContextInjector & { +type InjectableContextInjector = IAgentContextInjectorService & { inject(): Promise; }; @@ -28,7 +28,7 @@ type ContextInjectorInternals = { }; function injector(ix: TestInstantiationService): InjectableContextInjector { - return ix.get(IContextInjector) as InjectableContextInjector; + return ix.get(IAgentContextInjectorService) as InjectableContextInjector; } function userMessage(text: string): ContextMessage { @@ -49,16 +49,16 @@ function compactionSummary(text: string): ContextMessage { }; } -function lastText(context: IContextMemory): string | undefined { +function lastText(context: IAgentContextMemoryService): string | undefined { const message = context.get().at(-1); const part = message?.content[0]; return part?.type === 'text' ? part.text : undefined; } -describe('ContextInjectorService', () => { +describe('AgentContextInjectorService', () => { let disposables: DisposableStore; let ix: TestInstantiationService; - let context: IContextMemory; + let context: IAgentContextMemoryService; beforeEach(() => { disposables = new DisposableStore(); @@ -66,12 +66,12 @@ describe('ContextInjectorService', () => { base: [registerContextMemoryServices], strict: true, additionalServices: (reg) => { - reg.defineInstance(ITurnService, stubTurnWithHooks()); - reg.define(ISystemReminderService, SystemReminderService); - reg.define(IContextInjector, ContextInjectorService); + reg.defineInstance(IAgentTurnService, stubTurnWithHooks()); + reg.define(IAgentSystemReminderService, AgentSystemReminderService); + reg.define(IAgentContextInjectorService, AgentContextInjectorService); }, }); - context = ix.get(IContextMemory); + context = ix.get(IAgentContextMemoryService); }); afterEach(() => disposables.dispose()); @@ -208,7 +208,7 @@ describe('ContextInjectorService', () => { }); }); -describe('ContextInjectorService registration', () => { +describe('AgentContextInjectorService registration', () => { let disposables: DisposableStore; let ix: TestInstantiationService; @@ -218,19 +218,19 @@ describe('ContextInjectorService registration', () => { base: [registerContextMemoryServices], strict: true, additionalServices: (reg) => { - reg.defineInstance(ITurnService, stubTurnWithHooks()); - reg.define(ISystemReminderService, SystemReminderService); - reg.define(IContextInjector, ContextInjectorService); - reg.definePartialInstance(IProfileService, { + reg.defineInstance(IAgentTurnService, stubTurnWithHooks()); + reg.define(IAgentSystemReminderService, AgentSystemReminderService); + reg.define(IAgentContextInjectorService, AgentContextInjectorService); + reg.definePartialInstance(IAgentProfileService, { isToolActive: () => false, }); - reg.definePartialInstance(IToolStoreService, { + reg.definePartialInstance(IAgentToolStoreService, { data: () => ({}), }); - reg.definePartialInstance(IToolRegistry, { + reg.definePartialInstance(IAgentToolRegistryService, { register: () => toDisposable(() => {}), }); - reg.define(ITodoListService, TodoListService); + reg.define(IAgentTodoListService, AgentTodoListService); }, }); }); @@ -238,7 +238,7 @@ describe('ContextInjectorService registration', () => { afterEach(() => disposables.dispose()); it('registers the todo-list reminder when the todo-list service is resolved', () => { - ix.get(ITodoListService); + ix.get(IAgentTodoListService); const entries = [ ...(injector(ix) as unknown as ContextInjectorInternals).entries, diff --git a/packages/agent-core-v2/test/contextMemory/context.test.ts b/packages/agent-core-v2/test/contextMemory/context.test.ts index a388bca68..6b617f16b 100644 --- a/packages/agent-core-v2/test/contextMemory/context.test.ts +++ b/packages/agent-core-v2/test/contextMemory/context.test.ts @@ -1,7 +1,7 @@ import type { Message } from '@moonshot-ai/kosong'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { estimateTokensForMessages } from '#/_base/utils/tokens'; -import { IContextMemory, IContextSizeService, IProfileService } from '#/index'; +import { IAgentContextMemoryService, IAgentContextSizeService, IAgentProfileService } from '#/index'; import { project } from '#/contextProjector'; import type { ContextMessage } from '#/contextMemory'; import { renderNotificationXml } from '#/contextMemory/notification-xml'; @@ -9,15 +9,15 @@ import { createTestAgent, type TestAgentContext } from '../harness'; describe('Agent context', () => { let ctx: TestAgentContext; - let context: IContextMemory; - let contextSize: IContextSizeService; - let profile: IProfileService; + let context: IAgentContextMemoryService; + let contextSize: IAgentContextSizeService; + let profile: IAgentProfileService; beforeEach(() => { ctx = createTestAgent(); - context = ctx.get(IContextMemory); - contextSize = ctx.get(IContextSizeService); - profile = ctx.get(IProfileService); + context = ctx.get(IAgentContextMemoryService); + contextSize = ctx.get(IAgentContextSizeService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/contextMemory/stubs.ts b/packages/agent-core-v2/test/contextMemory/stubs.ts index 87f657a99..b0d4308d5 100644 --- a/packages/agent-core-v2/test/contextMemory/stubs.ts +++ b/packages/agent-core-v2/test/contextMemory/stubs.ts @@ -1,6 +1,6 @@ /** - * `contextMemory` test stubs — shared doubles for `IContextMemory` and its - * collaborators (`IWireRecord`, `IReplayBuilderService`). + * `contextMemory` test stubs — shared doubles for `IAgentContextMemoryService` and its + * collaborators (`IAgentWireRecordService`, `IAgentReplayBuilderService`). * * Lives under `test/` (not `src/`) so test-support code stays out of the * production tree. Import from a relative path (`./stubs` or @@ -11,17 +11,17 @@ import { toDisposable } from '#/_base/di'; import type { ServiceRegistration } from '#/_base/di/test'; import { createHooks } from '#/hooks'; import type { Hooks } from '#/hooks'; -import { ensureMessageId, IContextMemory, type ContextMessage } from '#/contextMemory'; -import { IReplayBuilderService } from '#/replayBuilder'; -import { IWireRecord } from '#/wireRecord'; +import { ensureMessageId, IAgentContextMemoryService, type ContextMessage } from '#/contextMemory'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; +import { IAgentWireRecordService } from '#/wireRecord'; /** - * A no-op `IWireRecord`. `register` returns a disposable so services that + * A no-op `IAgentWireRecordService`. `register` returns a disposable so services that * `_register(wireRecord.register(...))` in their constructor can be disposed * cleanly; `append` is a no-op (in-memory history is driven by `applySplice`). */ -export function stubWireRecord(): IWireRecord { - const hooks = createHooks(['onRestoredRecord', 'onResumeEnded']) as IWireRecord['hooks']; +export function stubWireRecord(): IAgentWireRecordService { + const hooks = createHooks(['onRestoredRecord', 'onResumeEnded']) as IAgentWireRecordService['hooks']; return { _serviceBrand: undefined, restoring: null, @@ -35,8 +35,8 @@ export function stubWireRecord(): IWireRecord { }; } -/** A no-op `IReplayBuilderService` — every mutator is a no-op. */ -export function stubReplayBuilder(): IReplayBuilderService { +/** A no-op `IAgentReplayBuilderService` — every mutator is a no-op. */ +export function stubReplayBuilder(): IAgentReplayBuilderService { return { _serviceBrand: undefined, postRestoring: false, @@ -49,14 +49,14 @@ export function stubReplayBuilder(): IReplayBuilderService { }; } -export interface StubContextMemory extends IContextMemory { +export interface StubContextMemory extends IAgentContextMemoryService { /** The live backing history, exposed so tests can inspect splices. */ readonly messages: readonly ContextMessage[]; } /** - * An in-memory `IContextMemory`. `spliceHistory` mutates the backing history - * and fires `onSpliced`, mirroring `ContextMemoryService.applySplice` enough + * An in-memory `IAgentContextMemoryService`. `spliceHistory` mutates the backing history + * and fires `onSpliced`, mirroring `AgentContextMemoryService.applySplice` enough * for collaborators (e.g. `DynamicInjectorService`) to react to splices. */ export function stubContextMemory(): StubContextMemory { @@ -92,13 +92,13 @@ export function stubContextMemory(): StubContextMemory { } /** - * Register the default collaborators consumed by `ContextMemoryService` - * (`IWireRecord`, `IReplayBuilderService`) and an in-memory `IContextMemory`. - * Tests that exercise the real `ContextMemoryService` should override - * `IContextMemory` via `additionalServices`. + * Register the default collaborators consumed by `AgentContextMemoryService` + * (`IAgentWireRecordService`, `IAgentReplayBuilderService`) and an in-memory `IAgentContextMemoryService`. + * Tests that exercise the real `AgentContextMemoryService` should override + * `IAgentContextMemoryService` via `additionalServices`. */ export function registerContextMemoryServices(reg: ServiceRegistration): void { - reg.defineInstance(IWireRecord, stubWireRecord()); - reg.defineInstance(IReplayBuilderService, stubReplayBuilder()); - reg.defineInstance(IContextMemory, stubContextMemory()); + reg.defineInstance(IAgentWireRecordService, stubWireRecord()); + reg.defineInstance(IAgentReplayBuilderService, stubReplayBuilder()); + reg.defineInstance(IAgentContextMemoryService, stubContextMemory()); } diff --git a/packages/agent-core-v2/test/cron/agent-integration.test.ts b/packages/agent-core-v2/test/cron/agent-integration.test.ts index 253ffe692..620a9733f 100644 --- a/packages/agent-core-v2/test/cron/agent-integration.test.ts +++ b/packages/agent-core-v2/test/cron/agent-integration.test.ts @@ -9,21 +9,21 @@ import { CronCreateTool, type CronCreateInput, } from '#/cron/tools/cron-create'; -import { ICronService } from '#/cron'; -import { IProfileService } from '#/profile'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentCronService } from '#/cron'; +import { IAgentProfileService } from '#/profile'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { createTestAgent, type TestAgentContext } from '../harness'; describe('Agent + Cron integration (P1.7)', () => { describe('default cron wiring', () => { let ctx: TestAgentContext; - let cron: ICronService; - let profile: IProfileService; + let cron: IAgentCronService; + let profile: IAgentProfileService; beforeEach(() => { ctx = createTestAgent(); - cron = ctx.get(ICronService); - profile = ctx.get(IProfileService); + cron = ctx.get(IAgentCronService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['CronCreate', 'CronList', 'CronDelete'] }); }); @@ -59,16 +59,16 @@ describe('Agent + Cron integration (P1.7)', () => { describe('disabled cron config', () => { let ctx: TestAgentContext; - let cron: ICronService; - let profile: IProfileService; - let tools: IToolRegistry; + let cron: IAgentCronService; + let profile: IAgentProfileService; + let tools: IAgentToolRegistryService; beforeEach(() => { vi.stubEnv('KIMI_DISABLE_CRON', '1'); ctx = createTestAgent(); - cron = ctx.get(ICronService); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + cron = ctx.get(IAgentCronService); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); profile.update({ activeToolNames: ['CronCreate'] }); }); diff --git a/packages/agent-core-v2/test/cron/cron.e2e.test.ts b/packages/agent-core-v2/test/cron/cron.e2e.test.ts index 7e5957877..7c4de7e27 100644 --- a/packages/agent-core-v2/test/cron/cron.e2e.test.ts +++ b/packages/agent-core-v2/test/cron/cron.e2e.test.ts @@ -13,8 +13,8 @@ import { CronDeleteTool } from '#/cron/tools/cron-delete'; import { CronListTool } from '#/cron/tools/cron-list'; import type { ExecutableToolOutput } from '#/tool'; import type { ContextMessage } from '#/contextMemory'; -import { ICronService } from '#/cron'; -import { IPromptService } from '#/prompt'; +import { IAgentCronService } from '#/cron'; +import { IAgentPromptService } from '#/prompt'; import { createTestAgent, cronServices, type TestAgentContext } from '../harness'; // Local-time anchor (cron-expr matches on local fields, so a UTC anchor @@ -44,8 +44,8 @@ function outputText(out: ExecutableToolOutput): string { describe('Cron — session E2E (P1.9)', () => { let ctx: TestAgentContext; - let cron: ICronService; - let prompt: IPromptService; + let cron: IAgentCronService; + let prompt: IAgentPromptService; let harness: ReturnType; beforeEach(() => { @@ -59,8 +59,8 @@ describe('Cron — session E2E (P1.9)', () => { vi.stubEnv('KIMI_CRON_POLL_INTERVAL_MS', '0'); harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); cron.start(); }); diff --git a/packages/agent-core-v2/test/cron/cron.test.ts b/packages/agent-core-v2/test/cron/cron.test.ts index f32166a12..1aeaa62c8 100644 --- a/packages/agent-core-v2/test/cron/cron.test.ts +++ b/packages/agent-core-v2/test/cron/cron.test.ts @@ -7,10 +7,10 @@ import { IBootstrapService } from '#/bootstrap'; import { IConfigRegistry, IConfigService } from '#/config'; import { ConfigRegistry, ConfigService } from '#/config/configService'; import type { ContextMessage } from '#/contextMemory'; -import { ICronService } from '#/cron'; -import { CronService } from '#/cron/cronService'; +import { IAgentCronService } from '#/cron'; +import { AgentCronService } from '#/cron/cronService'; import { ILogService } from '#/log'; -import { IPromptService } from '#/prompt'; +import { IAgentPromptService } from '#/prompt'; import { InMemoryStorageService, IStorageService, @@ -19,11 +19,11 @@ import { TomlAtomicDocumentStore, } from '#/storage'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; -import { ITurnService, type Turn } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { IAgentTurnService, type Turn } from '#/turn'; +import { IAgentWireRecordService } from '#/wireRecord'; -import { IEventSink } from '../../src/eventSink'; +import { IAgentEventSinkService } from '../../src/eventSink'; import { stubBootstrap } from '../bootstrap/stubs'; import { stubWireRecord } from '../contextMemory/stubs'; import { stubLog } from '../log/stubs'; @@ -45,12 +45,12 @@ function textOf(message: ContextMessage): string { } // NOTE: the legacy `CronFireCoordinator` (which steered the main agent on fire -// through `ITurnService.steer`) no longer exists in HEAD. Fire delivery now -// lives inside `CronService` itself: a due, idle task is delivered via -// `IPromptService.steer`. The cases below cover that path directly, so there is +// through `IAgentTurnService.steer`) no longer exists in HEAD. Fire delivery now +// lives inside `AgentCronService` itself: a due, idle task is delivered via +// `IAgentPromptService.steer`. The cases below cover that path directly, so there is // no separate coordinator suite to migrate. -describe('CronService', () => { +describe('AgentCronService', () => { let disposables: DisposableStore; let ix: TestInstantiationService; let now: number; @@ -66,12 +66,12 @@ describe('CronService', () => { steered = []; vi.spyOn(Date, 'now').mockImplementation(() => now); - const turnService: ITurnService = { + const turnService: IAgentTurnService = { ...stubTurn(), getActiveTurn: () => activeTurn, }; - ix.stub(IPromptService, { + ix.stub(IAgentPromptService, { prompt: () => undefined, steer: (message) => { steered.push(message); @@ -81,11 +81,11 @@ describe('CronService', () => { undo: () => 0, clear: () => {}, }); - ix.stub(IEventSink, { emit: () => {}, on: () => ({ dispose: () => {} }) }); - ix.stub(IWireRecord, stubWireRecord()); - ix.stub(ITurnService, turnService); + ix.stub(IAgentEventSinkService, { emit: () => {}, on: () => ({ dispose: () => {} }) }); + ix.stub(IAgentWireRecordService, stubWireRecord()); + ix.stub(IAgentTurnService, turnService); ix.stub(ITelemetryService, { track: () => {} }); - ix.stub(IToolRegistry, { register: () => ({ dispose: () => {} }) }); + ix.stub(IAgentToolRegistryService, { register: () => ({ dispose: () => {} }) }); ix.stub(IBootstrapService, stubBootstrap()); ix.stub(ILogService, stubLog()); ix.stub(IStorageService, new InMemoryStorageService()); @@ -99,8 +99,8 @@ describe('CronService', () => { ix.set(IConfigRegistry, new SyncDescriptor(ConfigRegistry)); ix.set(IConfigService, new SyncDescriptor(ConfigService)); ix.set( - ICronService, - new SyncDescriptor(CronService, [{}]), + IAgentCronService, + new SyncDescriptor(AgentCronService, [{}]), ); }); afterEach(() => { @@ -110,7 +110,7 @@ describe('CronService', () => { }); it('addTask / list / removeTasks', () => { - const svc = ix.get(ICronService); + const svc = ix.get(IAgentCronService); const task = svc.addTask({ cron: '* * * * *', prompt: 'hi', recurring: false }); expect(svc.list()).toHaveLength(1); @@ -119,7 +119,7 @@ describe('CronService', () => { }); it('does not fire while a turn is active', () => { - const svc = ix.get(ICronService); + const svc = ix.get(IAgentCronService); svc.addTask({ cron: '* * * * *', prompt: 'fire-me', recurring: false }); activeTurn = fakeTurn(); @@ -130,7 +130,7 @@ describe('CronService', () => { }); it('fires a due task when idle', () => { - const svc = ix.get(ICronService); + const svc = ix.get(IAgentCronService); svc.addTask({ cron: '* * * * *', prompt: 'fire-me', recurring: false }); now = FAR_FUTURE_MS; @@ -142,7 +142,7 @@ describe('CronService', () => { }); it('removes one-shot tasks after firing', () => { - const svc = ix.get(ICronService); + const svc = ix.get(IAgentCronService); svc.addTask({ cron: '* * * * *', prompt: 'x', recurring: false }); now = FAR_FUTURE_MS; diff --git a/packages/agent-core-v2/test/cron/manager.test.ts b/packages/agent-core-v2/test/cron/manager.test.ts index 5be10cb65..5e361e8e8 100644 --- a/packages/agent-core-v2/test/cron/manager.test.ts +++ b/packages/agent-core-v2/test/cron/manager.test.ts @@ -12,11 +12,11 @@ import { CRON_MISSED, } from '#/cron/tools/telemetry-events'; import type { CronTask } from '#/cron/tools/types'; -import { ICronService } from '#/cron'; -import { IPromptService } from '#/prompt'; +import { IAgentCronService } from '#/cron'; +import { IAgentPromptService } from '#/prompt'; import type { ContextMessage, PromptOrigin } from '#/contextMemory'; import { ITelemetryService } from '#/telemetry'; -import { ITurnService, type Turn } from '#/turn'; +import { IAgentTurnService, type Turn } from '#/turn'; import { createTestAgent, cronServices, type TestAgentContext } from '../harness'; import type { TelemetryRecord } from '../telemetry/stubs'; @@ -47,7 +47,7 @@ function createClocks(initial = WALL_ANCHOR) { } function createSteerSpy( - prompt: IPromptService, + prompt: IAgentPromptService, ...args: [ returnValue?: Turn | undefined, ] @@ -77,11 +77,11 @@ function captureTelemetry(telemetry: ITelemetryService): TelemetryRecord[] { } describe('CronManager', () => { - let cron: ICronService; + let cron: IAgentCronService; let ctx: TestAgentContext; - let prompt: IPromptService; + let prompt: IAgentPromptService; let telemetry: ITelemetryService; - let turn: ITurnService; + let turn: IAgentTurnService; beforeEach(() => { // Pin jitter off so fire-count assertions are deterministic. Each @@ -108,7 +108,7 @@ describe('CronManager', () => { describe('construction', () => { beforeEach(() => { ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); it('does not throw with default clocks and supports start/stop', async () => { @@ -141,8 +141,8 @@ describe('CronManager', () => { beforeEach(() => { harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); telemetry = ctx.get(ITelemetryService); telemetryRecords = captureTelemetry(telemetry); steerCalls = createSteerSpy(prompt, { @@ -213,8 +213,8 @@ describe('CronManager', () => { beforeEach(() => { harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); telemetry = ctx.get(ITelemetryService); telemetryRecords = captureTelemetry(telemetry); steerCalls = createSteerSpy(prompt); @@ -258,7 +258,7 @@ describe('CronManager', () => { beforeEach(() => { harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); it('flags recurring tasks older than 7 days as stale', () => { @@ -313,7 +313,7 @@ describe('CronManager', () => { vi.stubEnv('KIMI_CRON_NO_STALE', '1'); harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); it('KIMI_CRON_NO_STALE=1 disables stale judgment for recurring', () => { @@ -334,7 +334,7 @@ describe('CronManager', () => { ctx = createTestAgent( cronServices({}), ); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); it('non-finite age is treated as not stale', () => { @@ -357,8 +357,8 @@ describe('CronManager', () => { beforeEach(() => { harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); telemetry = ctx.get(ITelemetryService); telemetryRecords = captureTelemetry(telemetry); steerCalls = createSteerSpy(prompt); @@ -425,8 +425,8 @@ describe('CronManager', () => { beforeEach(() => { harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); telemetry = ctx.get(ITelemetryService); telemetryRecords = captureTelemetry(telemetry); createSteerSpy(prompt, undefined); @@ -452,10 +452,10 @@ describe('CronManager', () => { beforeEach(() => { harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); telemetry = ctx.get(ITelemetryService); - turn = ctx.get(ITurnService); + turn = ctx.get(IAgentTurnService); telemetryRecords = captureTelemetry(telemetry); steerCalls = createSteerSpy(prompt); hasActiveTurn = true; @@ -495,8 +495,8 @@ describe('CronManager', () => { beforeEach(() => { harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); steerCalls = createSteerSpy(prompt); }); @@ -519,8 +519,8 @@ describe('CronManager', () => { beforeEach(() => { ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); telemetry = ctx.get(ITelemetryService); telemetryRecords = captureTelemetry(telemetry); steerCalls = createSteerSpy(prompt); diff --git a/packages/agent-core-v2/test/cron/manual-tick.test.ts b/packages/agent-core-v2/test/cron/manual-tick.test.ts index bc815cde7..d32d1830a 100644 --- a/packages/agent-core-v2/test/cron/manual-tick.test.ts +++ b/packages/agent-core-v2/test/cron/manual-tick.test.ts @@ -6,8 +6,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { ContextMessage } from '#/contextMemory'; -import { ICronService } from '#/cron'; -import { IPromptService } from '#/prompt'; +import { IAgentCronService } from '#/cron'; +import { IAgentPromptService } from '#/prompt'; import { createTestAgent, cronServices, type TestAgentContext } from '../harness'; const WALL_ANCHOR = 1_700_000_000_000; @@ -30,7 +30,7 @@ function createClocks(initial: number = WALL_ANCHOR): ClockHarness { }; } -function spySteer(prompt: IPromptService) { +function spySteer(prompt: IAgentPromptService) { return vi.spyOn(prompt, 'steer').mockImplementation((_message: ContextMessage) => ({ id: 1, abortController: new AbortController(), @@ -39,7 +39,7 @@ function spySteer(prompt: IPromptService) { })); } -describe('CronService — P1.8 manual tick + SIGUSR1', () => { +describe('AgentCronService — P1.8 manual tick + SIGUSR1', () => { beforeEach(() => { // Disable jitter so fire-count assertions are deterministic. vi.stubEnv('KIMI_CRON_NO_JITTER', '1'); @@ -53,16 +53,16 @@ describe('CronService — P1.8 manual tick + SIGUSR1', () => { describe('KIMI_CRON_MANUAL_TICK=1', () => { let ctx: TestAgentContext; - let cron: ICronService; - let prompt: IPromptService; + let cron: IAgentCronService; + let prompt: IAgentPromptService; let harness: ClockHarness; beforeEach(() => { vi.stubEnv('KIMI_CRON_MANUAL_TICK', '1'); harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); }); afterEach(async () => { @@ -90,8 +90,8 @@ describe('CronService — P1.8 manual tick + SIGUSR1', () => { describe('without KIMI_CRON_MANUAL_TICK', () => { let ctx: TestAgentContext; - let cron: ICronService; - let prompt: IPromptService; + let cron: IAgentCronService; + let prompt: IAgentPromptService; let harness: ClockHarness; beforeEach(() => { @@ -101,8 +101,8 @@ describe('CronService — P1.8 manual tick + SIGUSR1', () => { vi.stubEnv('KIMI_CRON_POLL_INTERVAL_MS', '50'); harness = createClocks(); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); }); afterEach(async () => { @@ -129,14 +129,14 @@ describe('CronService — P1.8 manual tick + SIGUSR1', () => { // and trip Node's MaxListenersExceededWarning cap. describe('manual tick enabled', () => { let ctx: TestAgentContext; - let cron: ICronService; + let cron: IAgentCronService; let listenerCountBeforeCreate: number; beforeEach(() => { vi.stubEnv('KIMI_CRON_MANUAL_TICK', '1'); listenerCountBeforeCreate = process.listenerCount('SIGUSR1'); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); afterEach(async () => { @@ -203,13 +203,13 @@ describe('CronService — P1.8 manual tick + SIGUSR1', () => { describe('manual tick debug logging', () => { let ctx: TestAgentContext; - let cron: ICronService; + let cron: IAgentCronService; beforeEach(() => { vi.stubEnv('KIMI_CRON_MANUAL_TICK', '1'); vi.stubEnv('KIMI_CRON_DEBUG', '1'); ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); afterEach(async () => { @@ -241,11 +241,11 @@ describe('CronService — P1.8 manual tick + SIGUSR1', () => { describe('manual tick disabled', () => { let ctx: TestAgentContext; - let cron: ICronService; + let cron: IAgentCronService; beforeEach(() => { ctx = createTestAgent(cronServices({})); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/cron/resume.test.ts b/packages/agent-core-v2/test/cron/resume.test.ts index c45801e6a..82276deac 100644 --- a/packages/agent-core-v2/test/cron/resume.test.ts +++ b/packages/agent-core-v2/test/cron/resume.test.ts @@ -17,8 +17,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { ContentPart } from '@moonshot-ai/kosong'; import type { ContextMessage, PromptOrigin } from '#/contextMemory'; -import { IPromptService } from '#/prompt'; -import { ICronService } from '#/cron'; +import { IAgentPromptService } from '#/prompt'; +import { IAgentCronService } from '#/cron'; import { createCronPersistStore } from '#/cron/tools/persist'; import type { CronTask } from '#/cron/tools/types'; import { IAtomicDocumentStore } from '#/storage'; @@ -59,7 +59,7 @@ interface SteerCall { readonly origin: PromptOrigin; } -function captureSteer(prompt: IPromptService): SteerCall[] { +function captureSteer(prompt: IAgentPromptService): SteerCall[] { const calls: SteerCall[] = []; prompt.steer = (message: ContextMessage) => { calls.push({ content: message.content, origin: message.origin as PromptOrigin }); @@ -101,11 +101,11 @@ async function readPersistedTask( describe('CronManager — persistence and resume', () => { let sessionDir: string; let ctx: TestAgentContext; - let cron: ICronService; - let prompt: IPromptService; + let cron: IAgentCronService; + let prompt: IAgentPromptService; let resumedCtx: TestAgentContext | undefined; - let resumedCron: ICronService | undefined; - let resumedPrompt: IPromptService | undefined; + let resumedCron: IAgentCronService | undefined; + let resumedPrompt: IAgentPromptService | undefined; beforeEach(async () => { vi.stubEnv('KIMI_CRON_NO_JITTER', '1'); @@ -140,7 +140,7 @@ describe('CronManager — persistence and resume', () => { sessionDir, cronServices({}), ); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); it('addTask writes a JSON record to /cron/.json', async () => { @@ -184,13 +184,13 @@ describe('CronManager — persistence and resume', () => { sessionDir, cronServices({}), ); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); clockB.install(); resumedCtx = createCronAgent( sessionDir, cronServices({}), ); - resumedCron = resumedCtx.get(ICronService); + resumedCron = resumedCtx.get(IAgentCronService); }); it('re-adopts tasks with original id and createdAt', async () => { @@ -232,14 +232,14 @@ describe('CronManager — persistence and resume', () => { sessionDir, cronServices({}), ); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); clockB.install(); resumedCtx = createCronAgent( sessionDir, cronServices({}), ); - resumedCron = resumedCtx.get(ICronService); - resumedPrompt = resumedCtx.get(IPromptService); + resumedCron = resumedCtx.get(IAgentCronService); + resumedPrompt = resumedCtx.get(IAgentPromptService); }); it('recurring task missed during downtime fires once with coalescedCount > 1', async () => { @@ -273,14 +273,14 @@ describe('CronManager — persistence and resume', () => { sessionDir, cronServices({}), ); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); clockB.install(); resumedCtx = createCronAgent( sessionDir, cronServices({}), ); - resumedCron = resumedCtx.get(ICronService); - resumedPrompt = resumedCtx.get(IPromptService); + resumedCron = resumedCtx.get(IAgentCronService); + resumedPrompt = resumedCtx.get(IAgentPromptService); }); it('one-shot scheduled in the past fires once on resume and the file is removed', async () => { @@ -322,15 +322,15 @@ describe('CronManager — persistence and resume', () => { sessionDir, cronServices({}), ); - cron = ctx.get(ICronService); - prompt = ctx.get(IPromptService); + cron = ctx.get(IAgentCronService); + prompt = ctx.get(IAgentPromptService); clockB.install(); resumedCtx = createCronAgent( sessionDir, cronServices({}), ); - resumedCron = resumedCtx.get(ICronService); - resumedPrompt = resumedCtx.get(IPromptService); + resumedCron = resumedCtx.get(IAgentCronService); + resumedPrompt = resumedCtx.get(IAgentPromptService); }); it('does NOT replay on resume', async () => { @@ -375,14 +375,14 @@ describe('CronManager — persistence and resume', () => { sessionDir, cronServices({}), ); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); clockB.install(); resumedCtx = createCronAgent( sessionDir, cronServices({}), ); - resumedCron = resumedCtx.get(ICronService); - resumedPrompt = resumedCtx.get(IPromptService); + resumedCron = resumedCtx.get(IAgentCronService); + resumedPrompt = resumedCtx.get(IAgentPromptService); }); it('treats a future lastFiredAt as corrupt and falls back to createdAt', async () => { @@ -418,7 +418,7 @@ describe('CronManager — persistence and resume', () => { ctx = createTestAgent( cronServices({}), ); - cron = ctx.get(ICronService); + cron = ctx.get(IAgentCronService); }); it('no sessionDir = pure in-memory: no FS side effects, loadFromDisk is a no-op', async () => { diff --git a/packages/agent-core-v2/test/cron/subagent-skip.test.ts b/packages/agent-core-v2/test/cron/subagent-skip.test.ts index 223fd16db..ad7b67b78 100644 --- a/packages/agent-core-v2/test/cron/subagent-skip.test.ts +++ b/packages/agent-core-v2/test/cron/subagent-skip.test.ts @@ -16,8 +16,8 @@ */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { ICronService } from '#/cron'; -import { IProfileService } from '#/profile'; +import { IAgentCronService } from '#/cron'; +import { IAgentProfileService } from '#/profile'; import { createTestAgent, cronServices, type TestAgentContext } from '../harness'; const CRON_TOOL_NAMES = ['CronCreate', 'CronList', 'CronDelete'] as const; @@ -37,15 +37,15 @@ describe('Agent + Cron — subagent suppression', () => { describe("type='sub'", () => { let ctx: TestAgentContext; - let cron: ICronService; - let profile: IProfileService; + let cron: IAgentCronService; + let profile: IAgentProfileService; let listenerCountBeforeCreate: number; beforeEach(() => { listenerCountBeforeCreate = process.listenerCount('SIGUSR1'); ctx = createTestAgent(cronServices({ isSubagent: true })); - cron = ctx.get(ICronService); - profile = ctx.get(IProfileService); + cron = ctx.get(IAgentCronService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { @@ -59,7 +59,7 @@ describe('Agent + Cron — subagent suppression', () => { it('cron exists, start() is skipped, tools not registered', () => { if (process.platform === 'win32') return; - // Subagents get a disabled CronService: no scheduler, no timers, + // Subagents get a disabled AgentCronService: no scheduler, no timers, // no SIGUSR1 listener and no tools — the service-DI equivalent of // the old `agent.cron === null`. expect(cron.isEnabled).toBe(false); @@ -80,13 +80,13 @@ describe('Agent + Cron — subagent suppression', () => { describe("type='main'", () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; let listenerCountBeforeCreate: number; beforeEach(() => { listenerCountBeforeCreate = process.listenerCount('SIGUSR1'); ctx = createTestAgent(); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { @@ -112,13 +112,13 @@ describe('Agent + Cron — subagent suppression', () => { describe("type='independent'", () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; let listenerCountBeforeCreate: number; beforeEach(() => { listenerCountBeforeCreate = process.listenerCount('SIGUSR1'); ctx = createTestAgent(); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/di/scope-tree.test.ts b/packages/agent-core-v2/test/di/scope-tree.test.ts index d91367dda..9f0bbb221 100644 --- a/packages/agent-core-v2/test/di/scope-tree.test.ts +++ b/packages/agent-core-v2/test/di/scope-tree.test.ts @@ -7,103 +7,103 @@ import { LifecycleScope, Scope, _clearScopedRegistryForTests, - createCoreScope, + createAppScope, registerScopedService, } from '#/_base/di/scope'; -interface ICoreSvc { - tag: 'core'; +interface IAppSvc { + tag: 'app'; } interface ISessionSvc { - core: ICoreSvc; + app: IAppSvc; tag: 'session'; } interface IAgentSvc { session: ISessionSvc; - core: ICoreSvc; + app: IAppSvc; tag: 'agent'; } -const ICoreSvc = createDecorator('tree-core'); +const IAppSvc = createDecorator('tree-app'); const ISessionSvc = createDecorator('tree-session'); const IAgentSvc = createDecorator('tree-agent'); -class CoreSvc implements ICoreSvc { - tag = 'core' as const; +class AppSvc implements IAppSvc { + tag = 'app' as const; } class SessionSvc implements ISessionSvc { tag = 'session' as const; - constructor(@ICoreSvc public readonly core: ICoreSvc) {} + constructor(@IAppSvc public readonly app: IAppSvc) {} } class AgentSvc implements IAgentSvc { tag = 'agent' as const; constructor( @ISessionSvc public readonly session: ISessionSvc, - @ICoreSvc public readonly core: ICoreSvc, + @IAppSvc public readonly app: IAppSvc, ) {} } describe('Scope tree', () => { beforeEach(() => { _clearScopedRegistryForTests(); - registerScopedService(LifecycleScope.Core, ICoreSvc, CoreSvc); + registerScopedService(LifecycleScope.App, IAppSvc, AppSvc); registerScopedService(LifecycleScope.Session, ISessionSvc, SessionSvc); registerScopedService(LifecycleScope.Agent, IAgentSvc, AgentSvc); }); - function buildTree(): { core: Scope; session: Scope; agent: Scope } { - const core = createCoreScope(); - const session = core.createChild(LifecycleScope.Session, 's1'); + function buildTree(): { app: Scope; session: Scope; agent: Scope } { + const app = createAppScope(); + const session = app.createChild(LifecycleScope.Session, 's1'); const agent = session.createChild(LifecycleScope.Agent, 'main'); - return { core, session, agent }; + return { app, session, agent }; } it('each scope resolves its own layer service', () => { - const { core, session, agent } = buildTree(); - expect(core.accessor.get(ICoreSvc).tag).toBe('core'); + const { app, session, agent } = buildTree(); + expect(app.accessor.get(IAppSvc).tag).toBe('app'); expect(session.accessor.get(ISessionSvc).tag).toBe('session'); expect(agent.accessor.get(IAgentSvc).tag).toBe('agent'); - core.dispose(); + app.dispose(); }); it('child resolves ancestor services via createChild fallback', () => { - const { core, session, agent } = buildTree(); + const { app, session, agent } = buildTree(); const sessionSvc = session.accessor.get(ISessionSvc); const agentSvc = agent.accessor.get(IAgentSvc); - expect(sessionSvc.core.tag).toBe('core'); + expect(sessionSvc.app.tag).toBe('app'); expect(agentSvc.session.tag).toBe('session'); - expect(agentSvc.core.tag).toBe('core'); - expect(agentSvc.core).toBe(core.accessor.get(ICoreSvc)); - core.dispose(); + expect(agentSvc.app.tag).toBe('app'); + expect(agentSvc.app).toBe(app.accessor.get(IAppSvc)); + app.dispose(); }); it('parent cannot resolve a child-layer service', () => { - const { core, session } = buildTree(); - expect(() => core.accessor.get(ISessionSvc)).toThrow(); + const { app, session } = buildTree(); + expect(() => app.accessor.get(ISessionSvc)).toThrow(); expect(() => session.accessor.get(IAgentSvc)).toThrow(); - core.dispose(); + app.dispose(); }); it('children map tracks created child scopes', () => { - const { core, session, agent } = buildTree(); - expect(core.children.get('s1')).toBe(session); + const { app, session, agent } = buildTree(); + expect(app.children.get('s1')).toBe(session); expect(session.children.get('main')).toBe(agent); - core.dispose(); + app.dispose(); }); it('rejects a child whose kind is not strictly greater', () => { - const core = createCoreScope(); - const session = core.createChild(LifecycleScope.Session, 's1'); + const app = createAppScope(); + const session = app.createChild(LifecycleScope.Session, 's1'); expect(() => session.createChild(LifecycleScope.Session, 's2')).toThrow(/greater/); - expect(() => session.createChild(LifecycleScope.Core, 'c2')).toThrow(/greater/); - core.dispose(); + expect(() => session.createChild(LifecycleScope.App, 'c2')).toThrow(/greater/); + app.dispose(); }); it('rejects duplicate child ids within a parent', () => { - const core = createCoreScope(); - core.createChild(LifecycleScope.Session, 's1'); - expect(() => core.createChild(LifecycleScope.Session, 's1')).toThrow(/already has a child/); - core.dispose(); + const app = createAppScope(); + app.createChild(LifecycleScope.Session, 's1'); + expect(() => app.createChild(LifecycleScope.Session, 's1')).toThrow(/already has a child/); + app.dispose(); }); it('dispose tears down children before the parent (C→B→A)', () => { @@ -127,36 +127,36 @@ describe('Scope tree', () => { tag = 'C'; dispose(): void { events.push('C'); } } - registerScopedService(LifecycleScope.Core, IA, A, InstantiationType.Eager); + registerScopedService(LifecycleScope.App, IA, A, InstantiationType.Eager); registerScopedService(LifecycleScope.Session, IB, B, InstantiationType.Eager); registerScopedService(LifecycleScope.Agent, IC, C, InstantiationType.Eager); - const core = createCoreScope(); - const session = core.createChild(LifecycleScope.Session, 's1'); + const app = createAppScope(); + const session = app.createChild(LifecycleScope.Session, 's1'); const agent = session.createChild(LifecycleScope.Agent, 'main'); - core.accessor.get(IA); + app.accessor.get(IA); session.accessor.get(IB); agent.accessor.get(IC); - core.dispose(); + app.dispose(); expect(events).toEqual(['C', 'B', 'A']); }); it('disposing a child removes it from the parent children map', () => { - const { core, session, agent } = buildTree(); + const { app, session, agent } = buildTree(); agent.dispose(); expect(session.children.has('main')).toBe(false); session.dispose(); - expect(core.children.has('s1')).toBe(false); - core.dispose(); + expect(app.children.has('s1')).toBe(false); + app.dispose(); }); it('toHandle exposes id/kind/accessor for parent-domain reach-in', () => { - const { core, session } = buildTree(); + const { app, session } = buildTree(); const handle = session.toHandle(); expect(handle.id).toBe('s1'); expect(handle.kind).toBe(LifecycleScope.Session); expect(handle.accessor.get(ISessionSvc).tag).toBe('session'); - core.dispose(); + app.dispose(); }); it('extra seed injects a context token resolvable from that scope', () => { @@ -166,20 +166,20 @@ describe('Scope tree', () => { const ISessionContext = createDecorator('tree-session-ctx'); _clearScopedRegistryForTests(); - const core = createCoreScope(); - const session = core.createChild(LifecycleScope.Session, 's1', { + const app = createAppScope(); + const session = app.createChild(LifecycleScope.Session, 's1', { extra: [[ISessionContext as ServiceIdentifier, { sessionId: 's1' }]], }); expect(session.accessor.get(ISessionContext).sessionId).toBe('s1'); - expect(() => core.accessor.get(ISessionContext)).toThrow(); - core.dispose(); + expect(() => app.accessor.get(ISessionContext)).toThrow(); + app.dispose(); }); it('use-after-dispose throws on createChild', () => { - const core = createCoreScope(); - const session = core.createChild(LifecycleScope.Session, 's1'); + const app = createAppScope(); + const session = app.createChild(LifecycleScope.Session, 's1'); session.dispose(); expect(() => session.createChild(LifecycleScope.Agent, 'a1')).toThrow(/disposed/); - core.dispose(); + app.dispose(); }); }); diff --git a/packages/agent-core-v2/test/di/scoped-register.test.ts b/packages/agent-core-v2/test/di/scoped-register.test.ts index 0ca8a092b..b389cdb1d 100644 --- a/packages/agent-core-v2/test/di/scoped-register.test.ts +++ b/packages/agent-core-v2/test/di/scoped-register.test.ts @@ -9,8 +9,8 @@ import { registerScopedService, } from '#/_base/di/scope'; -interface ICore { - tag: 'core'; +interface IApp { + tag: 'app'; } interface ISession { tag: 'session'; @@ -19,12 +19,12 @@ interface IAgent { tag: 'agent'; } -const ICore = createDecorator('scoped-core'); +const IApp = createDecorator('scoped-app'); const ISession = createDecorator('scoped-session'); const IAgent = createDecorator('scoped-agent'); -class CoreSvc implements ICore { - tag = 'core' as const; +class AppSvc implements IApp { + tag = 'app' as const; } class SessionSvc implements ISession { tag = 'session' as const; @@ -39,11 +39,11 @@ describe('registerScopedService / getScopedServiceDescriptors', () => { }); it('filters registrations by scope layer', () => { - registerScopedService(LifecycleScope.Core, ICore, CoreSvc, InstantiationType.Delayed, 'core-domain'); + registerScopedService(LifecycleScope.App, IApp, AppSvc, InstantiationType.Delayed, 'app-domain'); registerScopedService(LifecycleScope.Session, ISession, SessionSvc, InstantiationType.Delayed, 'session-domain'); registerScopedService(LifecycleScope.Agent, IAgent, AgentSvc, InstantiationType.Eager, 'agent-domain'); - expect(getScopedServiceDescriptors(LifecycleScope.Core).map((e) => e.id)).toEqual([ICore]); + expect(getScopedServiceDescriptors(LifecycleScope.App).map((e) => e.id)).toEqual([IApp]); expect(getScopedServiceDescriptors(LifecycleScope.Session).map((e) => e.id)).toEqual([ISession]); expect(getScopedServiceDescriptors(LifecycleScope.Agent).map((e) => e.id)).toEqual([IAgent]); }); @@ -66,18 +66,18 @@ describe('registerScopedService / getScopedServiceDescriptors', () => { tag: string; } const IDual = createDecorator('scoped-dual'); - class CoreDual implements IDual { - tag = 'core'; + class AppDual implements IDual { + tag = 'app'; } class SessionDual implements IDual { tag = 'session'; } - registerScopedService(LifecycleScope.Core, IDual, CoreDual); + registerScopedService(LifecycleScope.App, IDual, AppDual); registerScopedService(LifecycleScope.Session, IDual, SessionDual); - expect(getScopedServiceDescriptors(LifecycleScope.Core)).toHaveLength(1); + expect(getScopedServiceDescriptors(LifecycleScope.App)).toHaveLength(1); expect(getScopedServiceDescriptors(LifecycleScope.Session)).toHaveLength(1); - expect(getScopedServiceDescriptors(LifecycleScope.Core)[0]?.id).toBe(IDual); + expect(getScopedServiceDescriptors(LifecycleScope.App)[0]?.id).toBe(IDual); expect(getScopedServiceDescriptors(LifecycleScope.Session)[0]?.id).toBe(IDual); }); }); diff --git a/packages/agent-core-v2/test/fileTools/edit.test.ts b/packages/agent-core-v2/test/fileTools/edit.test.ts index d7b2385db..ba8ef45ef 100644 --- a/packages/agent-core-v2/test/fileTools/edit.test.ts +++ b/packages/agent-core-v2/test/fileTools/edit.test.ts @@ -3,7 +3,7 @@ * * Ported from v1 (`packages/agent-core/test/tools/edit.test.ts`) and adapted * to the v2 constructor `(fs, kaos, workspace)`. Self-contained: builds minimal - * fake `IAgentFileSystem` (spied readText/writeText) and `IKaos` inline so the + * fake `ISessionAgentFileSystem` (spied readText/writeText) and `IKaos` inline so the * tool can be exercised without the composition root, mirroring * `test/fileTools/read.test.ts`. */ @@ -12,7 +12,7 @@ import { describe, expect, it, vi } from 'vitest'; import { PathSecurityError } from '../../src/_base/tools/policies/path-access'; import type { WorkspaceConfig } from '../../src/_base/tools/support/workspace'; -import type { IAgentFileSystem } from '../../src/agentFs'; +import type { ISessionAgentFileSystem } from '../../src/agentFs'; import { type EditInput, EditInputSchema, EditTool } from '../../src/fileTools/tools/edit'; import type { IKaos } from '../../src/kaos'; import type { ExecutableToolContext, ExecutableToolResult, ToolExecution } from '../../src/tool'; @@ -41,7 +41,7 @@ function createSpiedEditFs( const readText = options.readText ?? vi.fn(async () => ''); const writeText = options.writeText ?? vi.fn(async () => undefined); const stat = vi.fn(async () => ({ isFile: true, isDirectory: false, size: 0 })); - const fs = { cwd: '/', readText, writeText, stat } as unknown as IAgentFileSystem; + const fs = { cwd: '/', readText, writeText, stat } as unknown as ISessionAgentFileSystem; return { fs, readText, writeText }; } diff --git a/packages/agent-core-v2/test/fileTools/fileToolsService.test.ts b/packages/agent-core-v2/test/fileTools/fileToolsService.test.ts index b9f5d4562..4c6d68470 100644 --- a/packages/agent-core-v2/test/fileTools/fileToolsService.test.ts +++ b/packages/agent-core-v2/test/fileTools/fileToolsService.test.ts @@ -1,27 +1,27 @@ import { describe, expect, it, vi } from 'vitest'; -import type { IAgentFileSystem, IFsService } from '#/agentFs'; -import { FileToolsService } from '#/fileTools'; +import type { ISessionAgentFileSystem, ISessionFsService } from '#/agentFs'; +import { AgentFileToolsService } from '#/fileTools'; import type { IKaos } from '#/kaos'; import type { IDisposable } from '#/_base/di'; -import type { IToolRegistry } from '#/toolRegistry'; -import type { IWorkspaceContext } from '#/workspaceContext'; +import type { IAgentToolRegistryService } from '#/toolRegistry'; +import type { ISessionWorkspaceContext } from '#/workspaceContext'; -function fakeToolRegistry(): { registry: IToolRegistry; names: () => string[] } { +function fakeToolRegistry(): { registry: IAgentToolRegistryService; names: () => string[] } { const tools = new Map(); - const registry: IToolRegistry = { + const registry: IAgentToolRegistryService = { _serviceBrand: undefined, register: vi.fn((tool: { name: string }): IDisposable => { tools.set(tool.name, tool); return { dispose: () => tools.delete(tool.name) }; }), list: () => [...tools.values()] as never, - } as unknown as IToolRegistry; + } as unknown as IAgentToolRegistryService; return { registry, names: () => [...tools.keys()].sort() }; } -const fakeFs = { cwd: '/workspace' } as unknown as IAgentFileSystem; -const fakeFsService = {} as unknown as IFsService; +const fakeFs = { cwd: '/workspace' } as unknown as ISessionAgentFileSystem; +const fakeFsService = {} as unknown as ISessionFsService; const fakeKaos = { cwd: '/workspace', pathClass: () => 'posix', @@ -30,12 +30,12 @@ const fakeKaos = { const fakeWorkspace = { workDir: '/workspace', additionalDirs: [], -} as unknown as IWorkspaceContext; +} as unknown as ISessionWorkspaceContext; -describe('FileToolsService', () => { +describe('AgentFileToolsService', () => { it('registers Read/Write/Edit/Grep/Glob into the tool registry', () => { const { registry, names } = fakeToolRegistry(); - new FileToolsService(registry, fakeFs, fakeKaos, fakeWorkspace, fakeFsService); + new AgentFileToolsService(registry, fakeFs, fakeKaos, fakeWorkspace, fakeFsService); expect(names()).toEqual(['Edit', 'Glob', 'Grep', 'Read', 'Write']); }); }); diff --git a/packages/agent-core-v2/test/fileTools/glob.test.ts b/packages/agent-core-v2/test/fileTools/glob.test.ts index a1d25ba25..325ffc36a 100644 --- a/packages/agent-core-v2/test/fileTools/glob.test.ts +++ b/packages/agent-core-v2/test/fileTools/glob.test.ts @@ -3,10 +3,10 @@ * * Ported from v1 (`packages/agent-core/test/tools/glob.test.ts`) and adapted * to the v2 constructor `(fs, kaos, workspace)`. Self-contained: builds minimal - * fake `IAgentFileSystem` (map/spied `glob` + `stat` + `readdir` + `withCwd`) + * fake `ISessionAgentFileSystem` (map/spied `glob` + `stat` + `readdir` + `withCwd`) * and `IKaos` inline so the tool can be exercised without the composition root. * - * v2 `IAgentFileSystem.glob(pattern)` searches from `fs.cwd` and returns a + * v2 `ISessionAgentFileSystem.glob(pattern)` searches from `fs.cwd` and returns a * collected array (no per-root async generator), so the v1 `(root, pattern)` * call assertions become `withCwd(root)` + `glob(pattern)` pairs. v2 * `AgentFileStat` carries no mtime, so the mtime-sort test is adapted to @@ -17,7 +17,7 @@ import { describe, expect, it, vi } from 'vitest'; import { PathSecurityError, type PathClass } from '../../src/_base/tools/policies/path-access'; import type { WorkspaceConfig } from '../../src/_base/tools/support/workspace'; -import type { AgentFileStat, IAgentFileSystem } from '../../src/agentFs'; +import type { AgentFileStat, ISessionAgentFileSystem } from '../../src/agentFs'; import { expandBraces, type GlobInput, @@ -49,7 +49,7 @@ function createTestKaos(opts: { home?: string; pathClass?: PathClass } = {}): IK /** * Fake fs with spied `glob` / `stat` / `readdir` / `withCwd`. `withCwd` returns * a derived fs that shares the same spied IO mocks but carries the new `cwd`, - * mirroring the real `AgentFileSystem.withCwd` semantics. The base fs's + * mirroring the real `SessionAgentFileSystem.withCwd` semantics. The base fs's * `withCwd` is exposed so tests can assert the resolved search root. */ function createSpiedGlobFs(opts: { @@ -62,9 +62,9 @@ function createSpiedGlobFs(opts: { const stat = opts.stat ?? vi.fn(async (): Promise => fileStat()); const readdir = opts.readdir ?? vi.fn(async (): Promise => []); - function build(cwd: string): { fs: IAgentFileSystem; withCwd: ReturnType } { + function build(cwd: string): { fs: ISessionAgentFileSystem; withCwd: ReturnType } { const withCwd = vi.fn((nextCwd: string) => build(nextCwd).fs); - const fs = { cwd, glob, stat, readdir, withCwd } as unknown as IAgentFileSystem; + const fs = { cwd, glob, stat, readdir, withCwd } as unknown as ISessionAgentFileSystem; return { fs, withCwd }; } diff --git a/packages/agent-core-v2/test/fileTools/grep.test.ts b/packages/agent-core-v2/test/fileTools/grep.test.ts index 68b6315c7..18f4a4af3 100644 --- a/packages/agent-core-v2/test/fileTools/grep.test.ts +++ b/packages/agent-core-v2/test/fileTools/grep.test.ts @@ -3,10 +3,10 @@ * * Ported from v1 (`packages/agent-core/test/tools/grep.test.ts`) and adapted * to the v2 constructor `(fs, kaos, workspace)`. Self-contained: builds a - * minimal fake `IFsService` returning canned `FsGrepResponse`s so the tool's + * minimal fake `ISessionFsService` returning canned `FsGrepResponse`s so the tool's * argument mapping and result rendering can be exercised without the * composition root or a real ripgrep. The v1 tests that asserted on the exact - * `rg` argv (which the tool no longer builds — `IFsService.grep` owns the + * `rg` argv (which the tool no longer builds — `ISessionFsService.grep` owns the * subprocess) are intentionally dropped here. */ @@ -14,7 +14,7 @@ import type { FsGrepFileHit, FsGrepRequest, FsGrepResponse } from '@moonshot-ai/ import { describe, expect, it, vi } from 'vitest'; import type { WorkspaceConfig } from '../../src/_base/tools/support/workspace'; -import type { IFsService } from '../../src/agentFs'; +import type { ISessionFsService } from '../../src/agentFs'; import { type GrepInput, GrepInputSchema, @@ -43,7 +43,7 @@ function createFakeFs( const grep = vi.fn(async (req: FsGrepRequest) => typeof response === 'function' ? response(req) : response, ); - const fs = { grep } as unknown as IFsService; + const fs = { grep } as unknown as ISessionFsService; return { fs, grep }; } diff --git a/packages/agent-core-v2/test/fileTools/read.test.ts b/packages/agent-core-v2/test/fileTools/read.test.ts index d7d46062e..f080c0102 100644 --- a/packages/agent-core-v2/test/fileTools/read.test.ts +++ b/packages/agent-core-v2/test/fileTools/read.test.ts @@ -3,11 +3,11 @@ * * Ported from v1 (`packages/agent-core/test/tools/read.test.ts`) and adapted * to the v2 constructor `(fs, kaos, workspace)`. Self-contained: builds minimal - * fake `IAgentFileSystem` and `IKaos` inline so the tool can be exercised + * fake `ISessionAgentFileSystem` and `IKaos` inline so the tool can be exercised * without the composition root. * * The v1 fast-path tests (`scanTextFile` / `readLineRange` / `readTailLines` / - * `readTextPreview`) are intentionally dropped: `IAgentFileSystem` streams + * `readTextPreview`) are intentionally dropped: `ISessionAgentFileSystem` streams * through `readLines` only, so `readForward` / `readTail` always take the * line-iteration path. */ @@ -17,7 +17,7 @@ import { describe, expect, it, vi } from 'vitest'; import { PathSecurityError } from '../../src/_base/tools/policies/path-access'; import { MEDIA_SNIFF_BYTES } from '../../src/_base/tools/support/file-type'; import type { WorkspaceConfig } from '../../src/_base/tools/support/workspace'; -import type { IAgentFileSystem } from '../../src/agentFs'; +import type { ISessionAgentFileSystem } from '../../src/agentFs'; import { MAX_BYTES, MAX_LINE_LENGTH, @@ -79,7 +79,7 @@ function createSpiedFs(content: string) { const readLines = vi.fn().mockImplementation(() => generateLines(content)); const readText = vi.fn(async () => content); const stat = vi.fn(async () => ({ isFile: true, isDirectory: false, size: bytes.length })); - const fs = { cwd: '/', readBytes, readLines, readText, stat } as unknown as IAgentFileSystem; + const fs = { cwd: '/', readBytes, readLines, readText, stat } as unknown as ISessionAgentFileSystem; return { fs, readBytes, readLines, readText, stat }; } @@ -125,7 +125,7 @@ function createSpiedMapFs(files: Record) { size: file.size ?? file.bytes.length, }; }); - const fs = { cwd: '/', readBytes, readLines, readText, stat } as unknown as IAgentFileSystem; + const fs = { cwd: '/', readBytes, readLines, readText, stat } as unknown as ISessionAgentFileSystem; return { fs, readBytes, readLines, readText, stat }; } @@ -587,7 +587,7 @@ describe('ReadTool', () => { n === undefined ? bytes : bytes.subarray(0, n), ); const stat = vi.fn(async () => ({ isFile: true, isDirectory: false, size: bytes.length })); - const fs = { cwd: '/', readBytes, readLines, readText, stat } as unknown as IAgentFileSystem; + const fs = { cwd: '/', readBytes, readLines, readText, stat } as unknown as ISessionAgentFileSystem; const tool = new ReadTool(fs, createTestKaos(), PERMISSIVE_WORKSPACE); const result = await execute(tool, { path: '/tmp/large.txt' }); diff --git a/packages/agent-core-v2/test/fileTools/write.test.ts b/packages/agent-core-v2/test/fileTools/write.test.ts index 73db913e2..705ae59dd 100644 --- a/packages/agent-core-v2/test/fileTools/write.test.ts +++ b/packages/agent-core-v2/test/fileTools/write.test.ts @@ -3,11 +3,11 @@ * * Ported from v1 (`packages/agent-core/test/tools/write.test.ts`) and adapted * to the v2 constructor `(fs, kaos, workspace)`. Self-contained: builds minimal - * fake `IAgentFileSystem` and `IKaos` inline so the tool can be exercised + * fake `ISessionAgentFileSystem` and `IKaos` inline so the tool can be exercised * without the composition root. * * The v1 append path used `kaos.writeText(path, data, { mode: 'a' })`. v2's - * `IAgentFileSystem.writeText` has no mode flag, so append is implemented as + * `ISessionAgentFileSystem.writeText` has no mode flag, so append is implemented as * `readText` (treating a missing file as empty) followed by `writeText` of the * concatenation. The append-call assertions below reflect that mechanic. */ @@ -15,7 +15,7 @@ import { describe, expect, it, vi } from 'vitest'; import { PathSecurityError } from '../../src/_base/tools/policies/path-access'; -import type { AgentFileStat, IAgentFileSystem } from '../../src/agentFs'; +import type { AgentFileStat, ISessionAgentFileSystem } from '../../src/agentFs'; import type { WorkspaceConfig } from '../../src/_base/tools/support/workspace'; import { type WriteInput, WriteInputSchema, WriteTool } from '../../src/fileTools/tools/write'; import type { IKaos } from '../../src/kaos'; @@ -69,7 +69,7 @@ function createWriteFs(options: WriteFsOptions = {}) { options.stat ?? (async () => ({ isFile: false, isDirectory: true, size: 0 })), ); const mkdir = vi.fn(options.mkdir ?? (async () => {})); - const fs = { cwd: '/', readText, writeText, stat, mkdir } as unknown as IAgentFileSystem; + const fs = { cwd: '/', readText, writeText, stat, mkdir } as unknown as ISessionAgentFileSystem; return { fs, readText, writeText, stat, mkdir }; } diff --git a/packages/agent-core-v2/test/fullCompaction/full.test.ts b/packages/agent-core-v2/test/fullCompaction/full.test.ts index 5fc7f1530..24d7e4ae8 100644 --- a/packages/agent-core-v2/test/fullCompaction/full.test.ts +++ b/packages/agent-core-v2/test/fullCompaction/full.test.ts @@ -27,13 +27,13 @@ import { microCompactionFlag } from '#/microCompaction/flag'; import { estimateTokensForMessages } from '#/_base/utils/tokens'; import { recordingTelemetry, type TelemetryRecord } from '../telemetry/stubs'; import type { TestAgentContext, TestAgentOptions, TestAgentServiceOverride } from '../harness'; -import { coreServices, testAgent } from '../harness'; +import { appServices, testAgent } from '../harness'; import { - IFullCompaction, - IMicroCompactionService, + IAgentFullCompactionService, + IAgentMicroCompactionService, IOAuthService, - IProfileService, - IToolStoreService, + IAgentProfileService, + IAgentToolStoreService, } from '#/index'; import { TODO_STORE_KEY } from '#/todoList/tools/todo-list'; @@ -352,7 +352,7 @@ describe('FullCompaction', () => { // onSpliced observer before the tool exchanges are appended (otherwise the // lazily-instantiated service never records the assistant cache anchor that // `detect()` needs). - (ctx.get(IMicroCompactionService) as any).compact([]); + (ctx.get(IAgentMicroCompactionService) as any).compact([]); vi.setSystemTime(0); ctx.appendToolExchange(); @@ -360,7 +360,7 @@ describe('FullCompaction', () => { vi.setSystemTime(61 * 60 * 1000); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); const compacted = ctx.once('full_compaction.complete'); ctx.mockNextResponse({ type: 'text', text: 'Compacted summary.' }); await ctx.rpc.beginCompaction({ instruction: 'Summarize tool exchanges.' }); @@ -466,7 +466,7 @@ describe('FullCompaction', () => { const compacted = ctx.once('full_compaction.complete'); ctx.mockNextResponse({ type: 'text', text: 'Compacted summary.' }); - ctx.get(IFullCompaction).begin({ source: 'auto', instruction: undefined }); + ctx.get(IAgentFullCompactionService).begin({ source: 'auto', instruction: undefined }); await compacted; await vi.waitFor(() => { expect(readHookPayloads(hookLog).map((payload) => payload['hook_event_name'])).toEqual([ @@ -1132,7 +1132,7 @@ describe('FullCompaction', () => { ctx.mockNextResponse({ type: 'text', text: `Auto summary ${String(i)}.` }); } - ctx.get(IFullCompaction).begin({ source: 'auto', instruction: undefined }); + ctx.get(IAgentFullCompactionService).begin({ source: 'auto', instruction: undefined }); await completed; const events = ctx.newEvents(); @@ -1726,7 +1726,7 @@ describe('FullCompaction', () => { provider: CATALOGUED_PROVIDER, modelCapabilities: CATALOGUED_MODEL_CAPABILITIES, }); - ctx.get(IProfileService).update({ thinkingLevel: 'high' }); + ctx.get(IAgentProfileService).update({ thinkingLevel: 'high' }); ctx.appendExchange(1, 'old user one', 'old assistant one', 20); ctx.newEvents(); @@ -1777,7 +1777,7 @@ describe('FullCompaction', () => { ...resolve(model), modelCapabilities: UNKNOWN_CAPABILITY, }); - expect(ctx.get(IProfileService).data().modelCapabilities.max_context_tokens).toBe(0); + expect(ctx.get(IAgentProfileService).data().modelCapabilities.max_context_tokens).toBe(0); ctx.appendExchange(1, 'old user one', 'old assistant one', 20); ctx.newEvents(); @@ -1998,7 +1998,7 @@ describe('FullCompaction', () => { ctx.appendExchange(1, 'old user one', 'old assistant one', 20); ctx.appendExchange(2, 'recent user two', 'recent assistant two', 80); - ctx.get(IToolStoreService).set(TODO_STORE_KEY, [ + ctx.get(IAgentToolStoreService).set(TODO_STORE_KEY, [ { title: 'Fix the auth bug', status: 'in_progress' }, { title: 'Add tests', status: 'pending' }, ]); @@ -2087,7 +2087,7 @@ function oauthTestAgentOptions( }, }, }, - services: coreServices((reg) => { + services: appServices((reg) => { reg.definePartialInstance(IOAuthService, { resolveTokenProvider: () => ({ getAccessToken }), }); diff --git a/packages/agent-core-v2/test/gateway/gateway.test.ts b/packages/agent-core-v2/test/gateway/gateway.test.ts index c4d8b8c04..1762bd8a7 100644 --- a/packages/agent-core-v2/test/gateway/gateway.test.ts +++ b/packages/agent-core-v2/test/gateway/gateway.test.ts @@ -10,9 +10,9 @@ import type { ContextMessage } from '#/contextMemory'; import { IRestGateway } from '#/gateway'; import { RestGateway } from '#/gateway/gatewayService'; import { ILogService } from '#/log'; -import { IPromptService } from '#/prompt'; +import { IAgentPromptService } from '#/prompt'; import { ISessionLifecycleService } from '#/session-lifecycle'; -import { ITurnService } from '#/turn'; +import { IAgentTurnService } from '#/turn'; import { stubLog } from '../log/stubs'; import { stubTurn } from '../turn/stubs'; @@ -39,7 +39,7 @@ describe('RestGateway', () => { let disposables: DisposableStore; let ix: TestInstantiationService; let promptCalls: ContextMessage[]; - let turnService: ITurnService; + let turnService: IAgentTurnService; beforeEach(() => { disposables = new DisposableStore(); @@ -47,7 +47,7 @@ describe('RestGateway', () => { promptCalls = []; turnService = stubTurn({ hasActiveTurn: true }); - const promptService: IPromptService = { + const promptService: IAgentPromptService = { _serviceBrand: undefined, prompt: (message) => { promptCalls.push(message); @@ -63,8 +63,8 @@ describe('RestGateway', () => { id: 'main', kind: LifecycleScope.Agent, accessor: makeAccessor([ - [IPromptService, promptService], - [ITurnService, turnService], + [IAgentPromptService, promptService], + [IAgentTurnService, turnService], ]), dispose: () => {}, }; diff --git a/packages/agent-core-v2/test/goal/goal.test.ts b/packages/agent-core-v2/test/goal/goal.test.ts index 3943f9134..242c6b3fa 100644 --- a/packages/agent-core-v2/test/goal/goal.test.ts +++ b/packages/agent-core-v2/test/goal/goal.test.ts @@ -1,10 +1,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { ErrorCodes } from '#/errors'; -import { IContextMemory } from '#/contextMemory'; -import { IEventSink } from '#/eventSink'; -import { IGoalService, type GoalService } from '#/goal'; -import { IReplayBuilderService } from '#/replayBuilder'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentEventSinkService } from '#/eventSink'; +import { IAgentGoalService, type AgentGoalService } from '#/goal'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; import type { PersistedWireRecord, WireRecord } from '#/wireRecord'; import { recordingTelemetry, type TelemetryRecord } from '../telemetry/stubs'; import { @@ -15,11 +15,11 @@ import { type TestAgentContext, } from '../harness'; -type GoalServiceTestManager = IGoalService & GoalService; +type GoalServiceTestManager = IAgentGoalService & AgentGoalService; type GoalRecord = Extract; -type AgentEvent = Parameters[0]; +type AgentEvent = Parameters[0]; type GoalUpdatedEvent = Extract; -type GoalSnapshot = NonNullable['goal']>; +type GoalSnapshot = NonNullable['goal']>; type GoalChange = GoalUpdatedEvent['change']; function goalRecords(records: readonly PersistedWireRecord[]): readonly GoalRecord[] { @@ -28,19 +28,19 @@ function goalRecords(records: readonly PersistedWireRecord[]): readonly GoalReco async function restoreGoalRecords( ctx: TestAgentContext, - goals: IGoalService, + goals: IAgentGoalService, records: readonly WireRecord[], ): Promise { goals.getGoal(); await ctx.restore(records as readonly PersistedWireRecord[]); } -describe('GoalService', () => { +describe('AgentGoalService', () => { let ctx: TestAgentContext; - let context: IContextMemory; + let context: IAgentContextMemoryService; let goals: GoalServiceTestManager; let records: PersistedWireRecord[]; - let replayBuilder: IReplayBuilderService; + let replayBuilder: IAgentReplayBuilderService; let events: Array<{ readonly type: string; readonly snapshot?: GoalSnapshot | null; readonly change?: GoalChange }>; let telemetry: TelemetryRecord[]; @@ -52,11 +52,11 @@ describe('GoalService', () => { wireRecordPersistenceServices(persistence), telemetryServices(recordingTelemetry(telemetry)), ); - context = ctx.get(IContextMemory); - goals = ctx.get(IGoalService) as GoalServiceTestManager; + context = ctx.get(IAgentContextMemoryService); + goals = ctx.get(IAgentGoalService) as GoalServiceTestManager; records = persistence.records; - replayBuilder = ctx.get(IReplayBuilderService); - const eventSink = ctx.get(IEventSink); + replayBuilder = ctx.get(IAgentReplayBuilderService); + const eventSink = ctx.get(IAgentEventSinkService); eventSink.on((event) => { if (event.type === 'goal.updated') events.push(event); }); @@ -70,7 +70,7 @@ describe('GoalService', () => { } }); -describe('GoalService creation', () => { +describe('AgentGoalService creation', () => { it('creates a goal and exposes it through getGoal', async () => { const snapshot = await goals.createGoal({ objective: 'Ship feature X' }); @@ -137,7 +137,7 @@ describe('GoalService creation', () => { }); }); -describe('GoalService lifecycle', () => { +describe('AgentGoalService lifecycle', () => { it('emits typed lifecycle and completion changes', async () => { await goals.createGoal({ objective: 'work', completionCriterion: 'tests pass' }); expect(events.at(-1)?.change).toBeUndefined(); @@ -188,7 +188,7 @@ describe('GoalService lifecycle', () => { }); }); -describe('GoalService accounting and budgets', () => { +describe('AgentGoalService accounting and budgets', () => { it('counts tokens and turns only while active', async () => { await goals.createGoal({ objective: 'work' }); await goals.recordTokenUsage(30); @@ -238,7 +238,7 @@ describe('GoalService accounting and budgets', () => { }); }); -describe('GoalService records', () => { +describe('AgentGoalService records', () => { it('records only replay-relevant create/update/clear fields', async () => { await goals.createGoal({ objective: 'work', completionCriterion: 'tests pass' }); await goals.recordTokenUsage(5); diff --git a/packages/agent-core-v2/test/goal/injection.test.ts b/packages/agent-core-v2/test/goal/injection.test.ts index 46b417962..93be26ba0 100644 --- a/packages/agent-core-v2/test/goal/injection.test.ts +++ b/packages/agent-core-v2/test/goal/injection.test.ts @@ -1,13 +1,13 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import type { ToolCall } from '@moonshot-ai/kosong'; -import { IContextInjector } from '#/contextInjector'; -import { IContextMemory } from '#/contextMemory'; +import { IAgentContextInjectorService } from '#/contextInjector'; +import { IAgentContextMemoryService } from '#/contextMemory'; import { - IGoalService, - type GoalService, + IAgentGoalService, + type AgentGoalService, } from '#/goal'; -import { IProfileService } from '#/profile'; +import { IAgentProfileService } from '#/profile'; import { InMemoryWireRecordPersistence, createTestAgent, @@ -16,8 +16,8 @@ import { type TestAgentContext, } from '../harness'; -type GoalServiceTestManager = IGoalService & GoalService; -type InjectableContextInjector = IContextInjector & { inject(): Promise }; +type GoalServiceTestManager = IAgentGoalService & AgentGoalService; +type InjectableContextInjector = IAgentContextInjectorService & { inject(): Promise }; async function injectDynamic(injector: InjectableContextInjector): Promise { await injector.inject(); @@ -25,7 +25,7 @@ async function injectDynamic(injector: InjectableContextInjector): Promise async function registerLookupTool( ctx: TestAgentContext, - profile: IProfileService, + profile: IAgentProfileService, ): Promise { profile.update({ activeToolNames: ['Lookup'] }); await ctx.rpc.registerTool({ @@ -54,14 +54,14 @@ function lookupCall(): ToolCall { describe('GoalInjection content', () => { let ctx: TestAgentContext; let goals: GoalServiceTestManager; - let context: IContextMemory; + let context: IAgentContextMemoryService; let injector: InjectableContextInjector; beforeEach(() => { ctx = createTestAgent(); - goals = ctx.get(IGoalService) as GoalServiceTestManager; - context = ctx.get(IContextMemory); - injector = ctx.get(IContextInjector) as InjectableContextInjector; + goals = ctx.get(IAgentGoalService) as GoalServiceTestManager; + context = ctx.get(IAgentContextMemoryService); + injector = ctx.get(IAgentContextInjectorService) as InjectableContextInjector; }); afterEach(async () => { @@ -233,7 +233,7 @@ function goalReminderRecords(persistence: InMemoryWireRecordPersistence) { ); } -function lastGoalReminder(context: IContextMemory): string | undefined { +function lastGoalReminder(context: IAgentContextMemoryService): string | undefined { const message = context.get().findLast((item) => { return item.origin?.kind === 'injection' && item.origin.variant === 'goal'; }); @@ -245,16 +245,16 @@ describe('GoalInjection integration', () => { describe('enabled goal injection', () => { let ctx: TestAgentContext; let goals: GoalServiceTestManager; - let profile: IProfileService; + let profile: IAgentProfileService; let injector: InjectableContextInjector; let persistence: InMemoryWireRecordPersistence; beforeEach(() => { persistence = new InMemoryWireRecordPersistence(); ctx = createTestAgent(wireRecordPersistenceServices(persistence)); - goals = ctx.get(IGoalService) as GoalServiceTestManager; - profile = ctx.get(IProfileService); - injector = ctx.get(IContextInjector) as InjectableContextInjector; + goals = ctx.get(IAgentGoalService) as GoalServiceTestManager; + profile = ctx.get(IAgentProfileService); + injector = ctx.get(IAgentContextInjectorService) as InjectableContextInjector; }); afterEach(async () => { @@ -328,8 +328,8 @@ describe('GoalInjection integration', () => { wireRecordPersistenceServices(persistence), goalServices({ enabled: false }), ); - goals = ctx.get(IGoalService) as GoalServiceTestManager; - injector = ctx.get(IContextInjector) as InjectableContextInjector; + goals = ctx.get(IAgentGoalService) as GoalServiceTestManager; + injector = ctx.get(IAgentContextInjectorService) as InjectableContextInjector; }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/harness/agent.ts b/packages/agent-core-v2/test/harness/agent.ts index 94cfd44fe..b0492e317 100644 --- a/packages/agent-core-v2/test/harness/agent.ts +++ b/packages/agent-core-v2/test/harness/agent.ts @@ -23,61 +23,61 @@ import { expect, vi } from 'vitest'; import { AGENT_WIRE_PROTOCOL_VERSION, - BackgroundService, - ExternalHooksService, + AgentBackgroundService, + AgentExternalHooksService, FileStorageService, - FullCompactionService, + AgentFullCompactionService, IAgentRPCService, IAppendLogStore, IAppendLogStorage, - IApprovalService, + ISessionApprovalService, IAtomicDocumentStorage, - IBackgroundService, + IAgentBackgroundService, IBlobStorage, IBootstrapOptions, IBootstrapService, IConfigService, - IContextMemory, - IContextProjector, - IContextSizeService, - IEventSink, - IExternalHooksService, - IFileToolsService, - IFullCompaction, + IAgentContextMemoryService, + IAgentContextProjectorService, + IAgentContextSizeService, + IAgentEventSinkService, + IAgentExternalHooksService, + IAgentFileToolsService, + IAgentFullCompactionService, IKaos, - ILLMRequester, + IAgentLLMRequesterService, ILogService, - IMcpService, - IMicroCompactionService, - IPermissionGate, - IPermissionModeService, - IPermissionRulesService, + IAgentMcpService, + IAgentMicroCompactionService, + IAgentPermissionGate, + IAgentPermissionModeService, + IAgentPermissionRulesService, ISessionContext, - IShellToolsService, + IAgentShellToolsService, IStorageService, - ISubagentHost, - ISwarmService, + ISessionSubagentHost, + IAgentSwarmService, ITelemetryService, - ITerminalBackend, - IToolRegistry, - IToolStoreService, - IUserToolService, - IUsageService, - IWireRecord, - IWorkspaceContext, - LLMRequesterService, + ISessionTerminalBackend, + IAgentToolRegistryService, + IAgentToolStoreService, + IAgentUserToolService, + IAgentUsageService, + IAgentWireRecordService, + ISessionWorkspaceContext, + AgentLLMRequesterService, LifecycleScope, - McpService, - MicroCompactionService, - PermissionGate, - PermissionRulesService, - ProfileService, + AgentMcpService, + AgentMicroCompactionService, + AgentPermissionGate, + AgentPermissionRulesService, + AgentProfileService, SyncDescriptor, - UserToolService, - WireRecordService, - WorkspaceContextService, + AgentUserToolService, + AgentWireRecordService, + SessionWorkspaceContextService, bootstrapSeed, - createCoreScope, + createAppScope, resolveBootstrapOptions, type IDisposable, type Scope, @@ -89,38 +89,38 @@ import { toDisposable } from '#/_base/di'; import type { PromisifyMethods } from '#/_base/utils/types'; import type { ApprovalResponse } from '#/approval'; import type { BackgroundTaskInfo } from '#/background'; -import { IBlobStoreService, type IBlobStoreService as BlobStoreService } from '#/blobStore'; +import { IAgentBlobStoreService, type IAgentBlobStoreService as AgentBlobStoreService } from '#/blobStore'; import { IOAuthService } from '#/auth/auth'; import { IChatProviderFactory } from '#/chatProvider'; import type { ContextMessage } from '#/contextMemory'; -import { ICronService } from '#/cron/cron'; -import { CronService } from '#/cron/cronService'; +import { IAgentCronService } from '#/cron/cron'; +import { AgentCronService } from '#/cron/cronService'; import type { HookEngine } from '#/externalHooks/engine'; import type { FullCompactionServiceOptions } from '#/fullCompaction'; import type { ILogger, LogContext, LogLevel } from '#/log'; import type { McpServiceOptions } from '#/mcp'; import { MICRO_COMPACTION_SECTION, type MicroCompactionConfig } from '#/microCompaction'; -import { IModelResolver, ModelResolver, type ResolvedModel } from '#/modelRuntime'; +import { ISessionModelResolver, SessionModelResolver, type ResolvedModel } from '#/modelRuntime'; import type { PermissionGateOptions } from '#/permissionGate'; import type { PermissionMode } from '#/permissionPolicy'; import type { PermissionRule } from '#/permissionRules'; -import { IProfileService } from '#/profile/profile'; -import { IPromptService } from '#/prompt/prompt'; -import { GoalService, IGoalService, type GoalServiceOptions } from '#/goal'; -import { IPlanService } from '#/plan'; -import { IQuestionService, type QuestionResult } from '#/question/question'; +import { IAgentProfileService } from '#/profile/profile'; +import { IAgentPromptService } from '#/prompt/prompt'; +import { AgentGoalService, IAgentGoalService, type GoalServiceOptions } from '#/goal'; +import { IAgentPlanService } from '#/plan'; +import { ISessionQuestionService, type QuestionResult } from '#/question/question'; import { - IReplayBuilderService, - ReplayBuilderService, + IAgentReplayBuilderService, + AgentReplayBuilderService, type ReplayBuilderServiceOptions, } from '#/replayBuilder'; import type { AgentAPI } from '#/rpc/core-api'; import { IAgentSkillService } from '#/skill/skill'; -import { ISkillCatalog } from '#/skill/skillCatalog'; +import { ISessionSkillCatalog } from '#/skill/skillCatalog'; import { AgentSkillService } from '#/skill/skillService'; import { ModelSkillTool } from '#/skill/tools/modelSkill'; import type { SkillCatalog } from '#/skill/types'; -import { SubagentHostService, type SessionSubagentHost } from '#/subagentHost'; +import { SessionSubagentHostService, type SessionSubagentHost } from '#/subagentHost'; import type { ExecutableToolOutput as ToolOutput, ToolResult } from '#/tool'; import type { UserToolExecutionHandler } from '#/userTool'; import type { @@ -198,12 +198,12 @@ interface Logger { class TestAgentSkillService extends AgentSkillService { constructor( - @ISkillCatalog skillCatalog: ISkillCatalog, - @IPromptService prompt: IPromptService, - @IEventSink events: IEventSink, - @IWireRecord wireRecord: IWireRecord, + @ISessionSkillCatalog skillCatalog: ISessionSkillCatalog, + @IAgentPromptService prompt: IAgentPromptService, + @IAgentEventSinkService events: IAgentEventSinkService, + @IAgentWireRecordService wireRecord: IAgentWireRecordService, @ITelemetryService telemetry: ITelemetryService, - @IToolRegistry toolRegistry: IToolRegistry, + @IAgentToolRegistryService toolRegistry: IAgentToolRegistryService, ) { super(skillCatalog, prompt, events, wireRecord, telemetry); if (skillCatalog.catalog.listInvocableSkills().length > 0) { @@ -264,7 +264,7 @@ type TestToolResult = ToolResult & { }; interface ResumeStateSnapshot { - readonly background: ReturnType; + readonly background: ReturnType; readonly config: { readonly cwd: string; readonly activeToolNames: readonly string[] | undefined; @@ -277,9 +277,9 @@ interface ResumeStateSnapshot { readonly history: readonly ContextMessage[]; readonly tokenCount: number; }; - readonly permission: ReturnType; - readonly toolStore: ReturnType; - readonly usage: ReturnType; + readonly permission: ReturnType; + readonly toolStore: ReturnType; + readonly usage: ReturnType; } interface ConfigureOptions { @@ -308,7 +308,7 @@ type MutableScopeSeed = Array, unknown]>; // eslint-disable-next-line @typescript-eslint/no-explicit-any type AnyCtor = new (...args: any[]) => T; -type TestAgentServiceScope = 'core' | 'session' | 'agent'; +type TestAgentServiceScope = 'app' | 'session' | 'agent'; export interface TestAgentServiceRegistration { define(id: ServiceIdentifier, ctor: AnyCtor): void; @@ -330,8 +330,8 @@ export type TestAgentServiceOverride = type TestAgentInput = TestAgentServiceOverride | TestAgentOptions; -export function coreServices(group: TestAgentServiceGroup): TestAgentServiceOverride { - return scopedServices('core', group); +export function appServices(group: TestAgentServiceGroup): TestAgentServiceOverride { + return scopedServices('app', group); } export function sessionServices(group: TestAgentServiceGroup): TestAgentServiceOverride { @@ -342,11 +342,11 @@ export function agentServices(group: TestAgentServiceGroup): TestAgentServiceOve return scopedServices('agent', group); } -export function coreService( +export function appService( id: ServiceIdentifier, value: T | SyncDescriptor, ): TestAgentServiceOverride { - return coreServices((reg) => defineServiceValue(reg, id, value)); + return appServices((reg) => defineServiceValue(reg, id, value)); } export function sessionService( @@ -385,12 +385,12 @@ function defineServiceValue( export function kaosServices(kaos: Kaos): TestAgentServiceOverride { return sessionServices((reg) => { reg.defineInstance(IKaos, createIKaos(kaos)); - reg.defineDescriptor(IWorkspaceContext, new SyncDescriptor(WorkspaceContextService)); + reg.defineDescriptor(ISessionWorkspaceContext, new SyncDescriptor(SessionWorkspaceContextService)); }); } export function homeDirServices(homeDir: string | undefined): TestAgentServiceOverride { - return coreServices((reg) => { + return appServices((reg) => { if (homeDir !== undefined) { reg.defineInstance( IBootstrapOptions, @@ -408,56 +408,56 @@ export function homeDirServices(homeDir: string | undefined): TestAgentServiceOv export function additionalDirServices(additionalDirs: readonly string[]): TestAgentServiceOverride { return sessionServices((reg) => { - reg.defineInstance(IWorkspaceContext, createWorkspaceContextStub(process.cwd(), additionalDirs)); + reg.defineInstance(ISessionWorkspaceContext, createWorkspaceContextStub(process.cwd(), additionalDirs)); }); } -export function modelProviderServices(modelResolver: IModelResolver): TestAgentServiceOverride { - return sessionService(IModelResolver, modelResolver); +export function modelProviderServices(modelResolver: ISessionModelResolver): TestAgentServiceOverride { + return sessionService(ISessionModelResolver, modelResolver); } export function modelProviderOptionServices( options: TestModelProviderOptions, ): TestAgentServiceOverride { - return sessionService(IModelResolver, new SyncDescriptor(ConfigBackedModelResolver, [options])); + return sessionService(ISessionModelResolver, new SyncDescriptor(ConfigBackedModelResolver, [options])); } export function configServices(readConfig: () => KimiConfig): TestAgentServiceOverride { - return coreService(IConfigService, configService(readConfig)); + return appService(IConfigService, configService(readConfig)); } export function wireRecordPersistenceServices( persistence: WireRecordPersistence, onRead: (event: PersistedWireRecord) => void = () => {}, ): TestAgentServiceOverride { - return coreService( + return appService( IAppendLogStore, new PersistenceAppendLogStore(persistence, () => {}, onRead), ); } export function logServices(logger: Logger): TestAgentServiceOverride { - return coreService(ILogService, createLogService(logger)); + return appService(ILogService, createLogService(logger)); } export function llmGenerateServices(generate: GenerateFn): TestAgentServiceOverride { - return coreService(IChatProviderFactory, createGenerateBackedChatProviderFactory(generate)); + return appService(IChatProviderFactory, createGenerateBackedChatProviderFactory(generate)); } export function telemetryServices(telemetry: ITelemetryService): TestAgentServiceOverride { - return coreService(ITelemetryService, telemetry); + return appService(ITelemetryService, telemetry); } -export function questionServices(service: IQuestionService): TestAgentServiceOverride { - return sessionService(IQuestionService, service); +export function questionServices(service: ISessionQuestionService): TestAgentServiceOverride { + return sessionService(ISessionQuestionService, service); } export function externalHookServices( hookEngine: Pick | undefined, ): TestAgentServiceOverride { return agentService( - IExternalHooksService, - new SyncDescriptor(ExternalHooksService, [hookEngine === undefined ? {} : { hookEngine }]), + IAgentExternalHooksService, + new SyncDescriptor(AgentExternalHooksService, [hookEngine === undefined ? {} : { hookEngine }]), ); } @@ -473,49 +473,49 @@ export function microCompactionServices( export function fullCompactionServices( options: FullCompactionServiceOptions, ): TestAgentServiceOverride { - return agentService(IFullCompaction, new SyncDescriptor(FullCompactionService, [options])); + return agentService(IAgentFullCompactionService, new SyncDescriptor(AgentFullCompactionService, [options])); } export function permissionModeServices(mode: PermissionMode): TestAgentServiceOverride { return agentService( - IPermissionModeService, + IAgentPermissionModeService, createPermissionModeService(mode), ); } export function permissionRulesServices(rules: readonly PermissionRule[]): TestAgentServiceOverride { - return agentService(IPermissionRulesService, createPermissionRulesStub(rules)); + return agentService(IAgentPermissionRulesService, createPermissionRulesStub(rules)); } export function backgroundServices(): TestAgentServiceOverride { - return agentService(IBackgroundService, new SyncDescriptor(BackgroundService)); + return agentService(IAgentBackgroundService, new SyncDescriptor(AgentBackgroundService)); } export function cronServices( - options: ConstructorParameters[0], + options: ConstructorParameters[0], ): TestAgentServiceOverride { - return agentService(ICronService, new SyncDescriptor(CronService, [options])); + return agentService(IAgentCronService, new SyncDescriptor(AgentCronService, [options])); } export function mcpServices(options: McpServiceOptions): TestAgentServiceOverride { - return agentService(IMcpService, new SyncDescriptor(McpService, [options])); + return agentService(IAgentMcpService, new SyncDescriptor(AgentMcpService, [options])); } -export function skillServices(input: ISkillCatalog | SkillCatalog): TestAgentServiceOverride { +export function skillServices(input: ISessionSkillCatalog | SkillCatalog): TestAgentServiceOverride { const catalogService = isSessionSkillCatalog(input) ? input : createSessionSkillCatalog(input); return [ - sessionService(ISkillCatalog, catalogService), + sessionService(ISessionSkillCatalog, catalogService), agentService(IAgentSkillService, new SyncDescriptor(TestAgentSkillService)), ]; } -function isSessionSkillCatalog(input: ISkillCatalog | SkillCatalog): input is ISkillCatalog { +function isSessionSkillCatalog(input: ISessionSkillCatalog | SkillCatalog): input is ISessionSkillCatalog { return 'catalog' in input; } -function createSessionSkillCatalog(catalog: SkillCatalog): ISkillCatalog { +function createSessionSkillCatalog(catalog: SkillCatalog): ISessionSkillCatalog { return { _serviceBrand: undefined, catalog, @@ -526,15 +526,15 @@ function createSessionSkillCatalog(catalog: SkillCatalog): ISkillCatalog { } export function subagentHostServices(host: SessionSubagentHost): TestAgentServiceOverride { - return agentService(ISubagentHost, new SyncDescriptor(SubagentHostService, [host])); + return agentService(ISessionSubagentHost, new SyncDescriptor(SessionSubagentHostService, [host])); } export function goalServices(options: GoalServiceOptions): TestAgentServiceOverride { - return agentService(IGoalService, new SyncDescriptor(GoalService, [options])); + return agentService(IAgentGoalService, new SyncDescriptor(AgentGoalService, [options])); } export function replayServices(options: ReplayBuilderServiceOptions = {}): TestAgentServiceOverride { - return agentService(IReplayBuilderService, new SyncDescriptor(ReplayBuilderService, [options])); + return agentService(IAgentReplayBuilderService, new SyncDescriptor(AgentReplayBuilderService, [options])); } export function createCommandKaos(stdout: string): Kaos { @@ -716,7 +716,7 @@ class PersistenceAppendLogStore implements IAppendLogStore { } } -class ConfigBackedModelResolver extends ModelResolver { +class ConfigBackedModelResolver extends SessionModelResolver { constructor( private readonly options: TestModelProviderOptions = {}, @IConfigService config: IConfigService, @@ -745,11 +745,11 @@ class ConfigBackedModelResolver extends ModelResolver { } } -class RecordingWireRecordService extends WireRecordService { +class RecordingWireRecordService extends AgentWireRecordService { constructor( private readonly onAppend: (record: PersistedWireRecord) => void, @IBootstrapService bootstrap: IBootstrapService, - @IBlobStoreService blobStore?: BlobStoreService, + @IAgentBlobStoreService blobStore?: AgentBlobStoreService, @IAppendLogStore log?: IAppendLogStore, ) { super(bootstrap, blobStore, log); @@ -801,10 +801,10 @@ export class AgentTestContext { const agentId = 'main'; const persistence = options.persistence ?? new InMemoryWireRecordPersistence(); - const coreSeeds = collectScopeSeed([ + const appSeeds = collectScopeSeed([ (reg) => { for (const [id, value] of bootstrapSeed({ - homeDir: '/tmp/kimi-code-agent-core-v2-test', + homeDir: '/tmp/kimi-code-agent-app-v2-test', cwd: this.cwd, osHomeDir: kaos.gethome(), env: process.env, @@ -833,8 +833,8 @@ export class AgentTestContext { reg.defineInstance(ITelemetryService, options.telemetry); } }, - ], this.serviceOverrides, 'core'); - this.root = createCoreScope({ extra: coreSeeds }); + ], this.serviceOverrides, 'app'); + this.root = createAppScope({ extra: appSeeds }); const bootstrap = this.root.accessor.get(IBootstrapService); this.session = this.root.createChild(LifecycleScope.Session, sessionId, { @@ -847,69 +847,69 @@ export class AgentTestContext { sessionDir: `${bootstrap.sessionsDir}/test-workspace/${sessionId}`, metaScope: `sessions/test-workspace/${sessionId}/session-meta`, }); - reg.defineInstance(IApprovalService, this.createApprovalService()); - reg.defineInstance(IQuestionService, this.createQuestionService()); + reg.defineInstance(ISessionApprovalService, this.createApprovalService()); + reg.defineInstance(ISessionQuestionService, this.createQuestionService()); reg.defineInstance(IKaos, createIKaos(kaos)); - reg.defineInstance(ITerminalBackend, createTerminalBackend()); - reg.defineDescriptor(IWorkspaceContext, new SyncDescriptor(WorkspaceContextService)); - reg.defineDescriptor(IModelResolver, new SyncDescriptor(ConfigBackedModelResolver, [{}])); + reg.defineInstance(ISessionTerminalBackend, createTerminalBackend()); + reg.defineDescriptor(ISessionWorkspaceContext, new SyncDescriptor(SessionWorkspaceContextService)); + reg.defineDescriptor(ISessionModelResolver, new SyncDescriptor(ConfigBackedModelResolver, [{}])); }, ], this.serviceOverrides, 'session'), }); - const workspace = this.session.accessor.get(IWorkspaceContext); + const workspace = this.session.accessor.get(ISessionWorkspaceContext); this.agent = this.session.createChild(LifecycleScope.Agent, agentId, { extra: collectScopeSeed([ (reg) => { - reg.defineDescriptor(IWireRecord, new SyncDescriptor(RecordingWireRecordService, [ + reg.defineDescriptor(IAgentWireRecordService, new SyncDescriptor(RecordingWireRecordService, [ (event: PersistedWireRecord) => this.captureRecord(event), ])); - reg.defineDescriptor(IProfileService, new SyncDescriptor(ProfileService)); - reg.defineDescriptor(ILLMRequester, new SyncDescriptor(LLMRequesterService)); + reg.defineDescriptor(IAgentProfileService, new SyncDescriptor(AgentProfileService)); + reg.defineDescriptor(IAgentLLMRequesterService, new SyncDescriptor(AgentLLMRequesterService)); reg.defineDescriptor( - IExternalHooksService, - new SyncDescriptor(ExternalHooksService, [ + IAgentExternalHooksService, + new SyncDescriptor(AgentExternalHooksService, [ options.hookEngine === undefined ? {} : { hookEngine: options.hookEngine }, ]), ); - reg.defineDescriptor(IMicroCompactionService, new SyncDescriptor(MicroCompactionService)); + reg.defineDescriptor(IAgentMicroCompactionService, new SyncDescriptor(AgentMicroCompactionService)); reg.defineDescriptor( - IFullCompaction, - new SyncDescriptor(FullCompactionService, [options.fullCompaction ?? {}]), + IAgentFullCompactionService, + new SyncDescriptor(AgentFullCompactionService, [options.fullCompaction ?? {}]), ); reg.defineDescriptor( - IPermissionRulesService, - new SyncDescriptor(PermissionRulesService), + IAgentPermissionRulesService, + new SyncDescriptor(AgentPermissionRulesService), ); reg.defineDescriptor( - IPermissionGate, - new SyncDescriptor(PermissionGate, [{ + IAgentPermissionGate, + new SyncDescriptor(AgentPermissionGate, [{ agentId, agentType: 'main', } satisfies PermissionGateOptions]), ); - reg.defineDescriptor(ICronService, new SyncDescriptor(CronService, [{}])); - reg.defineDescriptor(IBackgroundService, new SyncDescriptor(BackgroundService)); - reg.defineDescriptor(IMcpService, new SyncDescriptor(McpService, [{}])); - reg.defineDescriptor(IReplayBuilderService, new SyncDescriptor(ReplayBuilderService, [{}])); - reg.defineDescriptor(IGoalService, new SyncDescriptor(GoalService, [{}])); + reg.defineDescriptor(IAgentCronService, new SyncDescriptor(AgentCronService, [{}])); + reg.defineDescriptor(IAgentBackgroundService, new SyncDescriptor(AgentBackgroundService)); + reg.defineDescriptor(IAgentMcpService, new SyncDescriptor(AgentMcpService, [{}])); + reg.defineDescriptor(IAgentReplayBuilderService, new SyncDescriptor(AgentReplayBuilderService, [{}])); + reg.defineDescriptor(IAgentGoalService, new SyncDescriptor(AgentGoalService, [{}])); reg.defineDescriptor(IAgentSkillService, new SyncDescriptor(AgentSkillService)); reg.defineDescriptor( - IUserToolService, - new SyncDescriptor(UserToolService, [{ + IAgentUserToolService, + new SyncDescriptor(AgentUserToolService, [{ execute: (request: Parameters[0]) => this.executeUserTool(request), }]), ); reg.defineDescriptor( - ISubagentHost, - new SyncDescriptor(SubagentHostService, [unavailableSubagentHost()]), + ISessionSubagentHost, + new SyncDescriptor(SessionSubagentHostService, [unavailableSubagentHost()]), ); }, ], this.serviceOverrides, 'agent'), }); - this.get(IProfileService).configure({ + this.get(IAgentProfileService).configure({ cwd: () => this.cwd, chdir: async (nextCwd: string) => { this.cwd = nextCwd; @@ -919,7 +919,7 @@ export class AgentTestContext { this.initializeRestorableServices(); - const events = this.get(IEventSink); + const events = this.get(IAgentEventSinkService); this.disposables.push( events.on((event) => { const { type, ...args } = event; @@ -942,20 +942,20 @@ export class AgentTestContext { return this.agent.accessor.get(id); } - get modelResolver(): IModelResolver { - return this.session.accessor.get(IModelResolver); + get modelResolver(): ISessionModelResolver { + return this.session.accessor.get(ISessionModelResolver); } - get context(): IContextMemory { - return this.get(IContextMemory); + get context(): IAgentContextMemoryService { + return this.get(IAgentContextMemoryService); } - get contextSize(): IContextSizeService { - return this.get(IContextSizeService); + get contextSize(): IAgentContextSizeService { + return this.get(IAgentContextSizeService); } - get wireRecord(): IWireRecord { - return this.get(IWireRecord); + get wireRecord(): IAgentWireRecordService { + return this.get(IAgentWireRecordService); } async restorePersisted( @@ -974,22 +974,22 @@ export class AgentTestContext { } private initializeRestorableServices(): void { - const context = this.get(IContextMemory); - const contextSize = this.get(IContextSizeService); - const usage = this.get(IUsageService); - const toolStore = this.get(IToolStoreService); - const background = this.get(IBackgroundService); - const permission = this.get(IPermissionGate); - const permissionMode = this.get(IPermissionModeService); - const permissionRules = this.get(IPermissionRulesService); - const cron = this.get(ICronService); - const plan = this.get(IPlanService); - const fileTools = this.get(IFileToolsService); - const shellTools = this.get(IShellToolsService); - const swarm = this.get(ISwarmService); + const context = this.get(IAgentContextMemoryService); + const contextSize = this.get(IAgentContextSizeService); + const usage = this.get(IAgentUsageService); + const toolStore = this.get(IAgentToolStoreService); + const background = this.get(IAgentBackgroundService); + const permission = this.get(IAgentPermissionGate); + const permissionMode = this.get(IAgentPermissionModeService); + const permissionRules = this.get(IAgentPermissionRulesService); + const cron = this.get(IAgentCronService); + const plan = this.get(IAgentPlanService); + const fileTools = this.get(IAgentFileToolsService); + const shellTools = this.get(IAgentShellToolsService); + const swarm = this.get(IAgentSwarmService); context.get(); - const microCompaction = this.get(IMicroCompactionService); + const microCompaction = this.get(IAgentMicroCompactionService); void microCompaction; void fileTools._serviceBrand; void shellTools._serviceBrand; @@ -1011,7 +1011,7 @@ export class AgentTestContext { modelCapabilities, }: ConfigureOptions = {}): void { this.configureRuntimeModel(provider, modelCapabilities); - const profile = this.get(IProfileService); + const profile = this.get(IAgentProfileService); profile.update({ cwd: process.cwd(), modelAlias: provider.model, @@ -1031,13 +1031,13 @@ export class AgentTestContext { modelCapabilities?: ModelCapability | undefined, ): void { this.kimiConfig = configWithProvider(this.kimiConfig, provider, modelCapabilities); - const profile = this.get(IProfileService); + const profile = this.get(IAgentProfileService); profile.update({ modelAlias: provider.model }); } contextData(): { readonly history: readonly ContextMessage[]; readonly tokenCount: number; } { - const context = this.get(IContextMemory); - const contextSize = this.get(IContextSizeService); + const context = this.get(IAgentContextMemoryService); + const contextSize = this.get(IAgentContextSizeService); return { history: context.get(), tokenCount: contextSize.getStatus().contextTokens, @@ -1045,22 +1045,22 @@ export class AgentTestContext { } project(messages?: readonly ContextMessage[]) { - const context = this.get(IContextMemory); - const projector = this.get(IContextProjector); + const context = this.get(IAgentContextMemoryService); + const projector = this.get(IAgentContextProjectorService); return projector.project(messages ?? context.get()); } - toolsData(): Array[number] & { readonly active: boolean; }> { - const profile = this.get(IProfileService); - const toolRegistry = this.get(IToolRegistry); + toolsData(): Array[number] & { readonly active: boolean; }> { + const profile = this.get(IAgentProfileService); + const toolRegistry = this.get(IAgentToolRegistryService); return toolRegistry.list().map((tool) => ({ ...tool, active: profile.isToolActive(tool.name, tool.source), })); } - toolStoreData(): ReturnType { - const toolStore = this.get(IToolStoreService); + toolStoreData(): ReturnType { + const toolStore = this.get(IAgentToolStoreService); return toolStore.data(); } @@ -1296,7 +1296,7 @@ export class AgentTestContext { } compactHistory(): Array<{ readonly role: string; readonly text: string; }> { - const context = this.get(IContextMemory); + const context = this.get(IAgentContextMemoryService); return context.get().map((message) => ({ role: message.role, text: message.content.map((part) => (part.type === 'text' ? part.text : '')).join(''), @@ -1305,7 +1305,7 @@ export class AgentTestContext { async expectResumeMatches(): Promise { await this.drainWirePersistence(); - const profile = this.get(IProfileService); + const profile = this.get(IAgentProfileService); const configSnapshot = structuredClone(this.get(IConfigService).getAll() as KimiConfig); const resumed = createTestAgent( { autoConfigure: false }, @@ -1332,7 +1332,7 @@ export class AgentTestContext { for (let i = 0; i < 5; i += 1) { await Promise.resolve(); } - const wireRecord = this.get(IWireRecord); + const wireRecord = this.get(IAgentWireRecordService); await wireRecord.flush(); } @@ -1398,7 +1398,7 @@ export class AgentTestContext { this.snapshots.respondPending(method, id, result); } - private createApprovalService(): IApprovalService { + private createApprovalService(): ISessionApprovalService { return { _serviceBrand: undefined, request: (request) => { @@ -1420,7 +1420,7 @@ export class AgentTestContext { }; } - private createQuestionService(): IQuestionService { + private createQuestionService(): ISessionQuestionService { return { _serviceBrand: undefined, request: (request) => { @@ -1508,7 +1508,7 @@ export class AgentTestContext { private appendMessage(...messages: ContextMessage[]): void { if (messages.length === 0) return; - const context = this.get(IContextMemory); + const context = this.get(IAgentContextMemoryService); context.splice(context.get().length, 0, messages); } @@ -1522,11 +1522,11 @@ export class AgentTestContext { }; // Persist both the context-size measurement and turn-scoped usage so resume // rebuilds size and usage the same way the real loop does. - const context = this.get(IContextMemory); - const contextSize = this.get(IContextSizeService); + const context = this.get(IAgentContextMemoryService); + const contextSize = this.get(IAgentContextSizeService); contextSize.measured(context.get().length, tokenTotal); - const profile = this.get(IProfileService); - const usageService = this.get(IUsageService); + const profile = this.get(IAgentProfileService); + const usageService = this.get(IAgentUsageService); usageService.record(profile.data().modelAlias ?? 'mock-model', usage, { type: 'turn', turnId: context.get().length, @@ -1559,7 +1559,7 @@ function createIKaos(kaos: Kaos): IKaos { function createWorkspaceContextStub( initialWorkDir: string, initialAdditionalDirs: readonly string[], -): IWorkspaceContext { +): ISessionWorkspaceContext { let workDir = resolve(initialWorkDir); let additionalDirs = initialAdditionalDirs.map((dir) => resolve(dir)); const isWithin = (absPath: string): boolean => { @@ -1603,7 +1603,7 @@ function createWorkspaceContextStub( }; } -function createPermissionModeService(initialMode: PermissionMode): IPermissionModeService { +function createPermissionModeService(initialMode: PermissionMode): IAgentPermissionModeService { let mode = initialMode; const emptyHook = { register: () => toDisposable(() => {}), @@ -1619,13 +1619,13 @@ function createPermissionModeService(initialMode: PermissionMode): IPermissionMo }, hooks: { onChanged: emptyHook, - } as unknown as IPermissionModeService['hooks'], + } as unknown as IAgentPermissionModeService['hooks'], }; } function createPermissionRulesStub( initialRules: readonly PermissionRule[], -): IPermissionRulesService { +): IAgentPermissionRulesService { let rules = [...initialRules]; const emptyHook = { register: () => ({ dispose: () => {} }), @@ -1646,11 +1646,11 @@ function createPermissionRulesStub( hooks: { onChanged: emptyHook, onApprovalRecorded: emptyHook, - } as unknown as IPermissionRulesService['hooks'], + } as unknown as IAgentPermissionRulesService['hooks'], }; } -function createTerminalBackend(): ITerminalBackend { +function createTerminalBackend(): ISessionTerminalBackend { return { _serviceBrand: undefined, spawn: async () => ({ @@ -1716,10 +1716,10 @@ function createResumeNoSideEffectKaos(initialCwd: string): Kaos { } function resumeStateSnapshot(ctx: AgentTestContext): ResumeStateSnapshot { - const background = ctx.get(IBackgroundService); - const usage = ctx.get(IUsageService); - const toolStore = ctx.get(IToolStoreService); - const permission = ctx.get(IPermissionGate); + const background = ctx.get(IAgentBackgroundService); + const usage = ctx.get(IAgentUsageService); + const toolStore = ctx.get(IAgentToolStoreService); + const permission = ctx.get(IAgentPermissionGate); return { background: normalizeBackgroundSnapshot(background.list(false)), config: configStateSnapshot(ctx), @@ -1756,7 +1756,7 @@ function isSystemReminderMessage(message: ContextMessage): boolean { } function configStateSnapshot(ctx: AgentTestContext): ResumeStateSnapshot['config'] { - const profile = ctx.get(IProfileService); + const profile = ctx.get(IAgentProfileService); const data = profile.data(); return { cwd: data.cwd, diff --git a/packages/agent-core-v2/test/harness/index.ts b/packages/agent-core-v2/test/harness/index.ts index 41bb45b5d..1804605e0 100644 --- a/packages/agent-core-v2/test/harness/index.ts +++ b/packages/agent-core-v2/test/harness/index.ts @@ -6,8 +6,8 @@ export { configServices, createCommandKaos, createTestAgent, - coreService, - coreServices, + appService, + appServices, cronServices, externalHookServices, fullCompactionServices, diff --git a/packages/agent-core-v2/test/interaction/interaction.test.ts b/packages/agent-core-v2/test/interaction/interaction.test.ts index 34d48efb8..a13f4bbab 100644 --- a/packages/agent-core-v2/test/interaction/interaction.test.ts +++ b/packages/agent-core-v2/test/interaction/interaction.test.ts @@ -3,22 +3,22 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { SyncDescriptor } from '#/_base/di/descriptors'; import { DisposableStore } from '#/_base/di/lifecycle'; import { TestInstantiationService } from '#/_base/di/test'; -import { IInteractionService } from '#/interaction/interaction'; -import { InteractionService } from '#/interaction/interactionService'; +import { ISessionInteractionService } from '#/interaction/interaction'; +import { SessionInteractionService } from '#/interaction/interactionService'; -describe('InteractionService', () => { +describe('SessionInteractionService', () => { let disposables: DisposableStore; let ix: TestInstantiationService; beforeEach(() => { disposables = new DisposableStore(); ix = disposables.add(new TestInstantiationService()); - ix.set(IInteractionService, new SyncDescriptor(InteractionService)); + ix.set(ISessionInteractionService, new SyncDescriptor(SessionInteractionService)); }); afterEach(() => disposables.dispose()); it('request blocks until respond resolves it', async () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); const pending = svc.request<{ n: number }, string>({ kind: 'question', payload: { n: 1 }, @@ -31,7 +31,7 @@ describe('InteractionService', () => { }); it('uses the caller-provided id for correlation', async () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); const pending = svc.request({ id: 'tool-1', kind: 'approval', payload: {} }); expect(svc.listPending()[0]!.id).toBe('tool-1'); svc.respond('tool-1', { decision: 'approved' }); @@ -39,7 +39,7 @@ describe('InteractionService', () => { }); it('listPending filters by kind', () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); void svc.request({ kind: 'approval', payload: {} }); void svc.request({ kind: 'question', payload: {} }); expect(svc.listPending('approval')).toHaveLength(1); @@ -48,7 +48,7 @@ describe('InteractionService', () => { }); it('onDidChange fires on request and on respond', async () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); let count = 0; disposables.add(svc.onDidChange(() => count++)); const pending = svc.request({ kind: 'question', payload: {} }); @@ -59,12 +59,12 @@ describe('InteractionService', () => { }); it('respond to an unknown id is a no-op', () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); expect(() => svc.respond('nope', 'x')).not.toThrow(); }); it('enqueue parks a request and returns it without blocking', () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); const interaction = svc.enqueue({ id: 'e1', kind: 'approval', payload: { tool: 'bash' } }); expect(interaction).toMatchObject({ id: 'e1', @@ -75,14 +75,14 @@ describe('InteractionService', () => { }); it('enqueue generates an id when none is provided', () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); const interaction = svc.enqueue({ kind: 'question', payload: {} }); expect(interaction.id).toMatch(/^interaction-/); expect(svc.listPending()[0]!.id).toBe(interaction.id); }); it('onDidResolve fires with the id and response when responded to', () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); const seen: { id: string; response: unknown }[] = []; disposables.add(svc.onDidResolve((r) => seen.push(r))); @@ -94,7 +94,7 @@ describe('InteractionService', () => { }); it('onDidResolve does not fire for an unknown id', () => { - const svc = ix.get(IInteractionService); + const svc = ix.get(ISessionInteractionService); let count = 0; disposables.add(svc.onDidResolve(() => count++)); svc.respond('nope', 'x'); diff --git a/packages/agent-core-v2/test/kaos/kaosFactory.test.ts b/packages/agent-core-v2/test/kaos/kaosFactory.test.ts index ec8f38629..427e4d585 100644 --- a/packages/agent-core-v2/test/kaos/kaosFactory.test.ts +++ b/packages/agent-core-v2/test/kaos/kaosFactory.test.ts @@ -13,7 +13,7 @@ describe('KaosFactory', () => { beforeEach(() => { _clearScopedRegistryForTests(); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IKaosFactory, KaosFactory, InstantiationType.Delayed, @@ -23,7 +23,7 @@ describe('KaosFactory', () => { it('createLocal builds an IKaos rooted at the given cwd', async () => { const host = createScopedTestHost(); - const factory = host.core.accessor.get(IKaosFactory); + const factory = host.app.accessor.get(IKaosFactory); const k = await factory.createLocal(process.cwd()); expect(k.name).toBe('local'); @@ -38,7 +38,7 @@ describe('KaosFactory', () => { it('withCwd derives an independent env without mutating the parent', async () => { const host = createScopedTestHost(); - const factory = host.core.accessor.get(IKaosFactory); + const factory = host.app.accessor.get(IKaosFactory); const k = await factory.createLocal('/tmp'); const child = k.withCwd('/var'); @@ -50,7 +50,7 @@ describe('KaosFactory', () => { it('backend delegates fs operations to the kaos backend', async () => { const host = createScopedTestHost(); - const factory = host.core.accessor.get(IKaosFactory); + const factory = host.app.accessor.get(IKaosFactory); const k = await factory.createLocal(process.cwd()); const st = await k.backend.stat(process.cwd()); diff --git a/packages/agent-core-v2/test/lint/domain-layers.test.ts b/packages/agent-core-v2/test/lint/domain-layers.test.ts index db3adbbf4..7d8f3cc94 100644 --- a/packages/agent-core-v2/test/lint/domain-layers.test.ts +++ b/packages/agent-core-v2/test/lint/domain-layers.test.ts @@ -35,7 +35,7 @@ describe('check-domain-layers', () => { it('flags a lower layer importing a higher layer', () => { const violations = checkSource( - `import { ITurnService } from '#/turn';`, + `import { IAgentTurnService } from '#/turn';`, at('log', 'log.ts'), ); expect(violations).toHaveLength(1); diff --git a/packages/agent-core-v2/test/llmRequester/kosong-llm.test.ts b/packages/agent-core-v2/test/llmRequester/kosong-llm.test.ts index e32ae48c9..9b1ad22d9 100644 --- a/packages/agent-core-v2/test/llmRequester/kosong-llm.test.ts +++ b/packages/agent-core-v2/test/llmRequester/kosong-llm.test.ts @@ -2,8 +2,8 @@ import { emptyUsage } from '@moonshot-ai/kosong'; import type { StreamedMessagePart } from '@moonshot-ai/kosong'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { ILLMRequester } from '#/llmRequester'; -import { IProfileService } from '#/profile'; +import { IAgentLLMRequesterService } from '#/llmRequester'; +import { IAgentProfileService } from '#/profile'; import { configServices, createTestAgent, @@ -14,11 +14,11 @@ import { describe('LLMRequester service migration coverage', () => { describe('tool-call deltas', () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; beforeEach(() => { ctx = createTestAgent(); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Lookup'] }); }); @@ -30,7 +30,7 @@ describe('LLMRequester service migration coverage', () => { } }); - it('preserves indexed tool-call deltas through LoopService protocol events', async () => { + it('preserves indexed tool-call deltas through AgentLoopService protocol events', async () => { await ctx.rpc.setPermission({ mode: 'auto' }); await ctx.rpc.registerTool({ name: 'Lookup', @@ -84,8 +84,8 @@ describe('LLMRequester service migration coverage', () => { describe('request timing and budget', () => { let ctx: TestAgentContext; - let llmRequester: ILLMRequester; - let profile: IProfileService; + let llmRequester: IAgentLLMRequesterService; + let profile: IAgentProfileService; let requestMaxTokens: unknown; beforeEach(() => { @@ -130,8 +130,8 @@ describe('LLMRequester service migration coverage', () => { }, })), ); - llmRequester = ctx.get(ILLMRequester); - profile = ctx.get(IProfileService); + llmRequester = ctx.get(IAgentLLMRequesterService); + profile = ctx.get(IAgentProfileService); profile.update({ modelAlias: 'deepseek/deepseek-v4-flash', systemPrompt: 'system', @@ -147,7 +147,7 @@ describe('LLMRequester service migration coverage', () => { } }); - it('emits stream timing and applies the model output budget through ILLMRequester', async () => { + it('emits stream timing and applies the model output budget through IAgentLLMRequesterService', async () => { const events = await collectLLMEvents(llmRequester.request()); expect(requestMaxTokens).toBe(384_000); diff --git a/packages/agent-core-v2/test/log/logConfig.test.ts b/packages/agent-core-v2/test/log/logConfig.test.ts index 7d6abec53..0b78369f8 100644 --- a/packages/agent-core-v2/test/log/logConfig.test.ts +++ b/packages/agent-core-v2/test/log/logConfig.test.ts @@ -74,10 +74,10 @@ describe('path resolution', () => { }); describe('logSeed', () => { - it('seeds ILogOptions into a Core scope', () => { + it('seeds ILogOptions into a App scope', () => { const cfg = resolveLoggingConfig({ homeDir: '/h', env: { KIMI_LOG_LEVEL: 'warn' } }); const host = createScopedTestHost(logSeed(cfg)); - const opts = host.core.accessor.get(ILogOptions); + const opts = host.app.accessor.get(ILogOptions); expect(opts.level).toBe('warn'); expect(opts.globalLogPath).toBe('/h/logs/kimi-code.log'); host.dispose(); diff --git a/packages/agent-core-v2/test/log/logService.test.ts b/packages/agent-core-v2/test/log/logService.test.ts index c9f965954..5a1f1f413 100644 --- a/packages/agent-core-v2/test/log/logService.test.ts +++ b/packages/agent-core-v2/test/log/logService.test.ts @@ -171,14 +171,14 @@ describe('ILogService (scoped)', () => { beforeEach(() => { _clearScopedRegistryForTests(); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ILogWriterService, ConsoleLogWriterService, InstantiationType.Eager, 'log', ); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ILogService, LogService, InstantiationType.Eager, @@ -186,10 +186,10 @@ describe('ILogService (scoped)', () => { ); }); - it('resolves ILogService from the Core scope with its sink injected', () => { + it('resolves ILogService from the App scope with its sink injected', () => { const sink = new MemoryLogWriterService(); const host = createScopedTestHost([stubPair(ILogWriterService, sink)]); - const log = host.core.accessor.get(ILogService); + const log = host.app.accessor.get(ILogService); log.info('scoped-hello'); expect(sink.entries.map((e) => e.msg)).toEqual(['scoped-hello']); host.dispose(); @@ -198,7 +198,7 @@ describe('ILogService (scoped)', () => { it('a scoped child logger bound to sessionId is resolvable downstream', () => { const sink = new MemoryLogWriterService(); const host = createScopedTestHost([stubPair(ILogWriterService, sink)]); - const root = host.core.accessor.get(ILogService); + const root = host.app.accessor.get(ILogService); const sessionLog = root.child({ sessionId: 's1' }); sessionLog.warn('bound'); expect(sink.entries[0]?.ctx).toEqual({ sessionId: 's1' }); diff --git a/packages/agent-core-v2/test/loop/basic.test.ts b/packages/agent-core-v2/test/loop/basic.test.ts index aaf3bbdb1..5e43ed0e1 100644 --- a/packages/agent-core-v2/test/loop/basic.test.ts +++ b/packages/agent-core-v2/test/loop/basic.test.ts @@ -1,22 +1,22 @@ import type { ToolCall } from '@moonshot-ai/kosong'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { IProfileService } from '#/index'; -import { ILoopService } from '#/loop'; +import { IAgentProfileService } from '#/index'; +import { IAgentLoopService } from '#/loop'; import type { ExecutableTool } from '#/tool'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { createTestAgent, type TestAgentContext } from '../harness'; describe('Agent loop', () => { let ctx: TestAgentContext; - let loop: ILoopService; - let profile: IProfileService; + let loop: IAgentLoopService; + let profile: IAgentProfileService; beforeEach(() => { ctx = createTestAgent(); - loop = ctx.get(ILoopService); - profile = ctx.get(IProfileService); + loop = ctx.get(IAgentLoopService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { @@ -121,7 +121,7 @@ describe('Agent loop', () => { }; profile.update({ activeToolNames: ['Lookup'] }); - ctx.get(IToolRegistry).register(lookupTool); + ctx.get(IAgentToolRegistryService).register(lookupTool); ctx.mockNextResponse({ type: 'text', text: 'I will look it up.' }, lookupCall); await ctx.rpc.prompt({ diff --git a/packages/agent-core-v2/test/mcp/mcp.test.ts b/packages/agent-core-v2/test/mcp/mcp.test.ts index a76f150ac..8f411f7f0 100644 --- a/packages/agent-core-v2/test/mcp/mcp.test.ts +++ b/packages/agent-core-v2/test/mcp/mcp.test.ts @@ -5,17 +5,17 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { SyncDescriptor } from '#/_base/di/descriptors'; import { DisposableStore, toDisposable } from '#/_base/di/lifecycle'; import { TestInstantiationService } from '#/_base/di/test'; -import { IEventSink } from '#/eventSink'; +import { IAgentEventSinkService } from '#/eventSink'; import type { McpConnectionManager, McpServerEntry } from '#/mcp/connection-manager'; -import { IMcpService, McpService } from '#/mcp'; +import { IAgentMcpService, AgentMcpService } from '#/mcp'; import type { McpOAuthService } from '#/mcp/oauth'; import type { MCPClient } from '#/mcp/types'; -import { ToolExecutorService } from '#/toolExecutor/toolExecutorService'; -import { IToolExecutor } from '#/toolExecutor'; -import { IToolRegistry } from '#/toolRegistry'; -import { ToolRegistryService } from '#/toolRegistry/toolRegistryService'; -import { ITurnService } from '#/turn'; -import { IProfileService } from '#/profile'; +import { AgentToolExecutorService } from '#/toolExecutor/toolExecutorService'; +import { IAgentToolExecutorService } from '#/toolExecutor'; +import { IAgentToolRegistryService } from '#/toolRegistry'; +import { AgentToolRegistryService } from '#/toolRegistry/toolRegistryService'; +import { IAgentTurnService } from '#/turn'; +import { IAgentProfileService } from '#/profile'; import { createTestAgent, mcpServices, type TestAgentContext } from '../harness'; import { stubTurnWithHooks } from '../turn/stubs'; @@ -123,7 +123,7 @@ class FakeMcpManager { } } -describe('McpService', () => { +describe('AgentMcpService', () => { let disposables: DisposableStore; let ix: TestInstantiationService; let events: AgentEvent[]; @@ -132,23 +132,23 @@ describe('McpService', () => { disposables = new DisposableStore(); ix = disposables.add(new TestInstantiationService()); events = []; - ix.stub(IEventSink, { + ix.stub(IAgentEventSinkService, { emit: (event) => { events.push(event); }, on: () => toDisposable(() => {}), }); - ix.set(IToolRegistry, new SyncDescriptor(ToolRegistryService)); - ix.set(IToolExecutor, new SyncDescriptor(ToolExecutorService)); - ix.stub(ITurnService, stubTurnWithHooks()); + ix.set(IAgentToolRegistryService, new SyncDescriptor(AgentToolRegistryService)); + ix.set(IAgentToolExecutorService, new SyncDescriptor(AgentToolExecutorService)); + ix.stub(IAgentTurnService, stubTurnWithHooks()); }); afterEach(() => { disposables.dispose(); }); - function createService(manager: FakeMcpManager): McpService { + function createService(manager: FakeMcpManager): AgentMcpService { const svc = ix.createInstance( - McpService, + AgentMcpService, { manager: manager as unknown as McpConnectionManager }, ); disposables.add(svc); @@ -173,9 +173,9 @@ describe('McpService', () => { expect(statuses).toEqual(['s1:connected', 's2:connected', 's1:disabled']); }); - it('resolves through the IMcpService binding with no manager', () => { - ix.set(IMcpService, new SyncDescriptor(McpService, [{}])); - const svc = ix.get(IMcpService); + it('resolves through the IAgentMcpService binding with no manager', () => { + ix.set(IAgentMcpService, new SyncDescriptor(AgentMcpService, [{}])); + const svc = ix.get(IAgentMcpService); expect(svc.list()).toEqual([]); }); @@ -187,7 +187,7 @@ describe('McpService', () => { manager.connect('local server'); - const infos = ix.get(IToolRegistry).list().filter((tool) => tool.source === 'mcp'); + const infos = ix.get(IAgentToolRegistryService).list().filter((tool) => tool.source === 'mcp'); expect(infos.map((info) => info.name).toSorted()).toEqual([ 'mcp__local_server__echo', 'mcp__local_server__noop', @@ -209,7 +209,7 @@ describe('McpService', () => { manager.connect('s'); - const names = ix.get(IToolRegistry).list().filter((tool) => tool.source === 'mcp').map((tool) => tool.name); + const names = ix.get(IAgentToolRegistryService).list().filter((tool) => tool.source === 'mcp').map((tool) => tool.name); expect(names).toEqual(['mcp__s__echo']); }); @@ -220,11 +220,11 @@ describe('McpService', () => { createService(manager); manager.connect('s'); - expect(ix.get(IToolRegistry).list().filter((tool) => tool.source === 'mcp')).toHaveLength(2); + expect(ix.get(IAgentToolRegistryService).list().filter((tool) => tool.source === 'mcp')).toHaveLength(2); manager.disconnect('s'); - expect(ix.get(IToolRegistry).list().filter((tool) => tool.source === 'mcp')).toEqual([]); + expect(ix.get(IAgentToolRegistryService).list().filter((tool) => tool.source === 'mcp')).toEqual([]); expect(events).toContainEqual( expect.objectContaining({ type: 'tool.list.updated', @@ -249,7 +249,7 @@ describe('McpService', () => { manager.connect('srv'); - const names = ix.get(IToolRegistry).list().filter((tool) => tool.source === 'mcp').map((tool) => tool.name); + const names = ix.get(IAgentToolRegistryService).list().filter((tool) => tool.source === 'mcp').map((tool) => tool.name); expect(names).toEqual(['mcp__srv__a_b']); expect(events).toContainEqual( expect.objectContaining({ @@ -274,7 +274,7 @@ describe('McpService', () => { manager.connect('srv a'); manager.connect('srv__a'); - expect(ix.get(IToolRegistry).list().filter((tool) => tool.source === 'mcp').map((tool) => tool.name)).toEqual([ + expect(ix.get(IAgentToolRegistryService).list().filter((tool) => tool.source === 'mcp').map((tool) => tool.name)).toEqual([ 'mcp__srv_a__shared', ]); expect(events.filter((event) => event.type === 'error')).toHaveLength(1); @@ -293,7 +293,7 @@ describe('McpService', () => { manager.setResolved('s', secondClient, await discoverTools(secondClient)); manager.connect('s'); - const names = ix.get(IToolRegistry).list().filter((tool) => tool.source === 'mcp').map((tool) => tool.name); + const names = ix.get(IAgentToolRegistryService).list().filter((tool) => tool.source === 'mcp').map((tool) => tool.name); expect(names).toEqual(['mcp__s__only']); }); @@ -304,7 +304,7 @@ describe('McpService', () => { createService(manager); manager.connect('s'); - const echo = ix.get(IToolRegistry).resolve('mcp__s__echo'); + const echo = ix.get(IAgentToolRegistryService).resolve('mcp__s__echo'); expect(echo).toBeDefined(); const result = await executeTool(echo!, { turnId: '1', @@ -339,7 +339,7 @@ describe('McpService', () => { createService(manager); manager.connect('s'); - const big = ix.get(IToolRegistry).resolve('mcp__s__big'); + const big = ix.get(IAgentToolRegistryService).resolve('mcp__s__big'); const result = await executeTool(big!, { turnId: '1', toolCallId: 'tc-big-text', @@ -374,7 +374,7 @@ describe('McpService', () => { createService(manager); manager.connect('s'); - const snap = ix.get(IToolRegistry).resolve('mcp__s__snap'); + const snap = ix.get(IAgentToolRegistryService).resolve('mcp__s__snap'); const result = await executeTool(snap!, { turnId: '1', toolCallId: 'tc-small-image', @@ -417,7 +417,7 @@ describe('McpService', () => { manager.connect('s'); const controller = new AbortController(); - const echo = ix.get(IToolRegistry).resolve('mcp__s__echo'); + const echo = ix.get(IAgentToolRegistryService).resolve('mcp__s__echo'); await executeTool(echo!, { turnId: '1', toolCallId: 'tc-signal', @@ -441,7 +441,7 @@ describe('McpService', () => { manager.needsAuth(); - const tools = ix.get(IToolRegistry).list(); + const tools = ix.get(IAgentToolRegistryService).list(); expect(tools).toEqual([ expect.objectContaining({ name: 'mcp__needs-auth__authenticate', @@ -459,7 +459,7 @@ describe('McpService', () => { manager.connect('s'); manager.fail('s'); - expect(ix.get(IToolRegistry).list().filter((tool) => tool.source === 'mcp')).toEqual([]); + expect(ix.get(IAgentToolRegistryService).list().filter((tool) => tool.source === 'mcp')).toEqual([]); expect(events).toContainEqual( expect.objectContaining({ type: 'tool.list.updated', @@ -470,17 +470,17 @@ describe('McpService', () => { }); }); -describe('McpService + ProfileService', () => { +describe('AgentMcpService + AgentProfileService', () => { let ctx: TestAgentContext; let manager: FakeMcpManager; - let profile: IProfileService; + let profile: IAgentProfileService; beforeEach(() => { manager = new FakeMcpManager(); ctx = createTestAgent(mcpServices({ manager: manager as unknown as McpConnectionManager })); - const mcp = ctx.get(IMcpService); + const mcp = ctx.get(IAgentMcpService); mcp.list(); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/media/read-media.test.ts b/packages/agent-core-v2/test/media/read-media.test.ts index be8660774..f1178e905 100644 --- a/packages/agent-core-v2/test/media/read-media.test.ts +++ b/packages/agent-core-v2/test/media/read-media.test.ts @@ -1,14 +1,14 @@ /** * ReadMediaFileTool tests for the v2 output/capability contract. * - * Self-contained: builds minimal fake `IAgentFileSystem` and `IKaos` inline + * Self-contained: builds minimal fake `ISessionAgentFileSystem` and `IKaos` inline * so the tool can be exercised without the missing composition root. */ import type { ContentPart, ModelCapability } from '@moonshot-ai/kosong'; import { describe, expect, it, vi } from 'vitest'; -import type { IAgentFileSystem } from '../../src/agentFs'; +import type { ISessionAgentFileSystem } from '../../src/agentFs'; import type { IKaos } from '../../src/kaos'; import { ReadMediaFileInputSchema, @@ -16,7 +16,7 @@ import { type VideoUploader, } from '../../src/media/tools/read-media'; import { registerMediaTools } from '../../src/media/registerMediaTools'; -import { ToolRegistryService } from '../../src/toolRegistry'; +import { AgentToolRegistryService } from '../../src/toolRegistry'; import { ToolAccesses } from '../../src/tool'; import type { WorkspaceConfig } from '../../src/_base/tools/support/workspace'; import type { ExecutableToolContext, ExecutableToolResult, ToolExecution } from '../../src/tool'; @@ -65,7 +65,7 @@ interface FakeFile { readonly size?: number; } -function createTestFs(files: Record): IAgentFileSystem { +function createTestFs(files: Record): ISessionAgentFileSystem { const lookup = (path: string): FakeFile | undefined => files[path]; return { cwd: '/workspace', @@ -78,7 +78,7 @@ function createTestFs(files: Record): IAgentFileSystem { size: file?.size ?? file?.data.length ?? 0, }; }), - } as unknown as IAgentFileSystem; + } as unknown as ISessionAgentFileSystem; } function createTestKaos(): IKaos { @@ -264,7 +264,7 @@ describe('registerMediaTools', () => { const kaos = createTestKaos(); it('registers ReadMediaFile when the model supports image input', () => { - const registry = new ToolRegistryService(); + const registry = new AgentToolRegistryService(); const disposable = registerMediaTools(registry, { fs, kaos, @@ -277,7 +277,7 @@ describe('registerMediaTools', () => { }); it('registers ReadMediaFile when the model supports video input', () => { - const registry = new ToolRegistryService(); + const registry = new AgentToolRegistryService(); registerMediaTools(registry, { fs, kaos, @@ -288,7 +288,7 @@ describe('registerMediaTools', () => { }); it('does not register anything when the model lacks media capability', () => { - const registry = new ToolRegistryService(); + const registry = new AgentToolRegistryService(); const disposable = registerMediaTools(registry, { fs, kaos, diff --git a/packages/agent-core-v2/test/message/message.test.ts b/packages/agent-core-v2/test/message/message.test.ts index 8ec3d83c3..f0e6fafa7 100644 --- a/packages/agent-core-v2/test/message/message.test.ts +++ b/packages/agent-core-v2/test/message/message.test.ts @@ -3,10 +3,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { SyncDescriptor } from '#/_base/di/descriptors'; import { DisposableStore } from '#/_base/di/lifecycle'; import { TestInstantiationService } from '#/_base/di/test'; -import { IContextMemory, type ContextMessage } from '#/contextMemory'; -import { ContextMemoryService } from '#/contextMemory/contextMemoryService'; -import { IReplayBuilderService } from '#/replayBuilder'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentContextMemoryService, type ContextMessage } from '#/contextMemory'; +import { AgentContextMemoryService } from '#/contextMemory/contextMemoryService'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; +import { IAgentWireRecordService } from '#/wireRecord'; import { stubReplayBuilder, stubWireRecord } from '../contextMemory/stubs'; function textMessage(role: ContextMessage['role'], text: string): ContextMessage { @@ -26,24 +26,24 @@ function textOf(message: ContextMessage): string { // NOTE: the legacy `IMessageService` (which projected context history into // `ProtocolMessage`s with derived `msg-N` ids) was removed // (see commit `chore: remove IMessageService`). Message history now lives on -// `IContextMemory`, so these cases exercise that history directly instead of +// `IAgentContextMemoryService`, so these cases exercise that history directly instead of // the deleted derived-id projection. -describe('message history (IContextMemory)', () => { +describe('message history (IAgentContextMemoryService)', () => { let disposables: DisposableStore; let ix: TestInstantiationService; beforeEach(() => { disposables = new DisposableStore(); ix = disposables.add(new TestInstantiationService()); - ix.stub(IWireRecord, stubWireRecord()); - ix.stub(IReplayBuilderService, stubReplayBuilder()); - ix.set(IContextMemory, new SyncDescriptor(ContextMemoryService)); + ix.stub(IAgentWireRecordService, stubWireRecord()); + ix.stub(IAgentReplayBuilderService, stubReplayBuilder()); + ix.set(IAgentContextMemoryService, new SyncDescriptor(AgentContextMemoryService)); }); afterEach(() => disposables.dispose()); it('round-trips user/assistant messages with their text content', () => { - const ctx = ix.get(IContextMemory); + const ctx = ix.get(IAgentContextMemoryService); ctx.splice(0, 0, [textMessage('user', 'a')]); ctx.splice(1, 0, [textMessage('assistant', 'b')]); @@ -53,7 +53,7 @@ describe('message history (IContextMemory)', () => { }); it('returns a defensive copy from getHistory', () => { - const ctx = ix.get(IContextMemory); + const ctx = ix.get(IAgentContextMemoryService); ctx.splice(0, 0, [textMessage('user', 'keep')]); const view = ctx.get(); @@ -63,7 +63,7 @@ describe('message history (IContextMemory)', () => { }); it('stamps a msg_ id on messages that lack one', () => { - const ctx = ix.get(IContextMemory); + const ctx = ix.get(IAgentContextMemoryService); ctx.splice(0, 0, [textMessage('user', 'hello')]); const [message] = ctx.get(); @@ -71,7 +71,7 @@ describe('message history (IContextMemory)', () => { }); it('preserves an existing message id (idempotent)', () => { - const ctx = ix.get(IContextMemory); + const ctx = ix.get(IAgentContextMemoryService); const existing: ContextMessage = { ...textMessage('user', 'keep'), id: 'msg_01HXQM8K7Z3V9N2P5R6T8W0Y1B', diff --git a/packages/agent-core-v2/test/microCompaction/micro.test.ts b/packages/agent-core-v2/test/microCompaction/micro.test.ts index 984924d17..d34f00093 100644 --- a/packages/agent-core-v2/test/microCompaction/micro.test.ts +++ b/packages/agent-core-v2/test/microCompaction/micro.test.ts @@ -13,7 +13,7 @@ import { } from '../harness'; import { AGENT_WIRE_PROTOCOL_VERSION, - IMicroCompactionService, + IAgentMicroCompactionService, type PersistedWireRecord, } from '#/index'; @@ -73,7 +73,7 @@ describe('MicroCompaction', () => { vi.setSystemTime(61 * 60 * 1000); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); const messages = ctx.project(); expect(messages[2]).toMatchObject({ role: 'tool', @@ -133,7 +133,7 @@ describe('MicroCompaction', () => { vi.setSystemTime(61 * 60 * 1000); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); const first = ctx.project(); expect(first[2]).toMatchObject({ role: 'tool', @@ -142,7 +142,7 @@ describe('MicroCompaction', () => { vi.setSystemTime(62 * 60 * 1000); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); const second = ctx.project(); expect(second[2]).toMatchObject({ role: 'tool', @@ -169,7 +169,7 @@ describe('MicroCompaction', () => { vi.setSystemTime(61 * 60 * 1000); - (ctx.get(IMicroCompactionService) as any).reset(); + (ctx.get(IAgentMicroCompactionService) as any).reset(); const messages = ctx.project(); expect(hasMarker(messages)).toBe(false); @@ -245,7 +245,7 @@ describe('MicroCompaction', () => { ctx.clearContext(); expect(ctx.project()).toHaveLength(0); - expect((ctx.get(IMicroCompactionService) as any).lastAssistantAt).toBeNull(); + expect((ctx.get(IAgentMicroCompactionService) as any).lastAssistantAt).toBeNull(); }); it('sends truncated old tool results to the next model request without mutating history', async () => { @@ -309,13 +309,13 @@ describe('MicroCompaction', () => { vi.setSystemTime(999_999); await ctx.restorePersisted(); - expect((ctx.get(IMicroCompactionService) as any).lastAssistantAt).toBe(assistantRecordTime); + expect((ctx.get(IAgentMicroCompactionService) as any).lastAssistantAt).toBe(assistantRecordTime); vi.setSystemTime(assistantRecordTime + 30 * MINUTE); expect(hasMarker(ctx.project())).toBe(false); vi.setSystemTime(assistantRecordTime + 61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([DEFAULT_MARKER]); }); @@ -338,7 +338,7 @@ describe('MicroCompaction', () => { appendMicroToolExchange(ctx, 2, { output: 'result two' }); vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([DEFAULT_MARKER, 'result two']); await ctx.wireRecord.flush(); expect(lastMicroCompactionCutoff(persistence.records)).toBe(4); @@ -355,7 +355,7 @@ describe('MicroCompaction', () => { vi.setSystemTime(63 * MINUTE); await resumed.restorePersisted(); - expect((resumed.get(IMicroCompactionService) as any).lastAssistantAt).toBe(62 * MINUTE); + expect((resumed.get(IAgentMicroCompactionService) as any).lastAssistantAt).toBe(62 * MINUTE); expect(toolTexts(resumed.project())).toEqual([ DEFAULT_MARKER, 'result two', @@ -382,7 +382,7 @@ describe('MicroCompaction', () => { appendMicroToolExchange(ctx, 2, { output: 'result two' }); vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([DEFAULT_MARKER, 'result two']); await ctx.wireRecord.flush(); expect(lastMicroCompactionCutoff(persistence.records)).toBe(4); @@ -402,8 +402,8 @@ describe('MicroCompaction', () => { vi.setSystemTime(123 * MINUTE); await resumed.restorePersisted(); - expect((resumed.get(IMicroCompactionService) as any).lastAssistantAt).toBe(62 * MINUTE); - (resumed.get(IMicroCompactionService) as any).detect(); + expect((resumed.get(IAgentMicroCompactionService) as any).lastAssistantAt).toBe(62 * MINUTE); + (resumed.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(resumed.project())).toEqual([ DEFAULT_MARKER, DEFAULT_MARKER, @@ -432,14 +432,14 @@ describe('MicroCompaction', () => { appendMicroToolExchange(ctx, 2, { output: 'result two' }); vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([DEFAULT_MARKER, 'result two']); vi.setSystemTime(62 * MINUTE); appendMicroToolExchange(ctx, 3, { output: 'result three' }); vi.setSystemTime(63 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([ DEFAULT_MARKER, 'result two', @@ -447,7 +447,7 @@ describe('MicroCompaction', () => { ]); vi.setSystemTime(123 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([ DEFAULT_MARKER, DEFAULT_MARKER, @@ -475,7 +475,7 @@ describe('MicroCompaction', () => { appendMicroToolExchange(ctx, 3, { output: 'result three' }); vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([ DEFAULT_MARKER, DEFAULT_MARKER, @@ -511,7 +511,7 @@ describe('MicroCompaction', () => { appendMicroToolExchange(ctx, 3, { output: 'result three' }); vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([ DEFAULT_MARKER, DEFAULT_MARKER, @@ -563,7 +563,7 @@ describe('MicroCompaction', () => { appendMicroToolExchange(ctx, 2, { output: 'result two '.repeat(20) }); vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([ DEFAULT_MARKER, 'result two '.repeat(20), @@ -574,7 +574,7 @@ describe('MicroCompaction', () => { const expectedContextTokensBefore = estimateTokensForMessages(ctx.project()); vi.setSystemTime(123 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); const events = records.filter((record) => record.event === 'micro_compaction_finished'); expect(events).toHaveLength(2); @@ -609,7 +609,7 @@ describe('MicroCompaction', () => { appendMicroToolExchange(ctx, 1, { output: 'result one' }); vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual(['result one']); expect(lastMicroCompactionCutoff(persistence.records)).toBeUndefined(); @@ -636,7 +636,7 @@ describe('MicroCompaction', () => { vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); expect(toolTexts(ctx.project())).toEqual([marker]); expect(textOf(ctx.context.get()[2])).toBe('abcd'); }); @@ -664,9 +664,9 @@ describe('MicroCompaction', () => { vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); const rawPending = ctx.context.get().slice(-1); - const projectedPending = (ctx.get(IMicroCompactionService) as any).compact(rawPending); + const projectedPending = (ctx.get(IAgentMicroCompactionService) as any).compact(rawPending); expect(textOf(projectedPending[0])).toBe(DEFAULT_MARKER); expect(ctx.contextSize.getStatus().contextTokensWithPending).toBe( ctx.contextSize.getStatus().contextTokens + estimateTokensForMessages(rawPending), @@ -701,8 +701,8 @@ describe('MicroCompaction', () => { vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); - const compacted = (ctx.get(IMicroCompactionService) as any).compact(ctx.context.get()); + (ctx.get(IAgentMicroCompactionService) as any).detect(); + const compacted = (ctx.get(IAgentMicroCompactionService) as any).compact(ctx.context.get()); const tool = compacted.find((message: any) => message.role === 'tool'); expect(tool).toMatchObject({ role: 'tool', @@ -744,8 +744,8 @@ describe('MicroCompaction', () => { }, ]); - (ctx.get(IMicroCompactionService) as any).detect(); - const compacted = (ctx.get(IMicroCompactionService) as any).compact(ctx.context.get()); + (ctx.get(IAgentMicroCompactionService) as any).detect(); + const compacted = (ctx.get(IAgentMicroCompactionService) as any).compact(ctx.context.get()); expect(toolTexts(compacted)).toEqual(['orphan tool-like output']); }); @@ -841,7 +841,7 @@ describe('MicroCompaction', () => { vi.setSystemTime(61 * MINUTE); - (ctx.get(IMicroCompactionService) as any).detect(); + (ctx.get(IAgentMicroCompactionService) as any).detect(); const messages = ctx.project(); expect(hasMarker(messages)).toBe(true); }); diff --git a/packages/agent-core-v2/test/modelRuntime/modelResolver.test.ts b/packages/agent-core-v2/test/modelRuntime/modelResolver.test.ts index 1f6863d77..29ec1de7d 100644 --- a/packages/agent-core-v2/test/modelRuntime/modelResolver.test.ts +++ b/packages/agent-core-v2/test/modelRuntime/modelResolver.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'; import type { IOAuthService } from '#/auth'; import type { IConfigService } from '#/config'; import { ErrorCodes, KimiError } from '#/errors'; -import { ModelResolver } from '#/modelRuntime'; +import { SessionModelResolver } from '#/modelRuntime'; function stubConfig(sections: Record): IConfigService { return { @@ -48,9 +48,9 @@ function baseSections(overrides: Record = {}): Record { +describe('SessionModelResolver', () => { it('resolves a configured model to its provider', () => { - const resolver = new ModelResolver(stubConfig(baseSections()), stubOAuth()); + const resolver = new SessionModelResolver(stubConfig(baseSections()), stubOAuth()); const resolved = resolver.resolve('k1'); expect(resolved.providerName).toBe('kimi'); expect(resolved.provider).toMatchObject({ model: 'kimi-model' }); @@ -58,19 +58,19 @@ describe('ModelResolver', () => { }); it('exposes defaultModel from config', () => { - const resolver = new ModelResolver(stubConfig(baseSections()), stubOAuth()); + const resolver = new SessionModelResolver(stubConfig(baseSections()), stubOAuth()); expect(resolver.defaultModel).toBe('k1'); }); it('reads providers and models from the config service', () => { const config = stubConfig(baseSections()); - const resolver = new ModelResolver(config, stubOAuth()); + const resolver = new SessionModelResolver(config, stubOAuth()); expect(resolver.defaultModel).toBe('k1'); expect(resolver.resolve('k1').providerName).toBe('kimi'); }); it('throws CONFIG_INVALID for an unknown model', () => { - const resolver = new ModelResolver(stubConfig(baseSections()), stubOAuth()); + const resolver = new SessionModelResolver(stubConfig(baseSections()), stubOAuth()); expect(() => resolver.resolve('does-not-exist')).toThrowError( expect.objectContaining({ code: ErrorCodes.CONFIG_INVALID } as Partial), ); @@ -86,7 +86,7 @@ describe('ModelResolver', () => { }, }), ); - const resolver = new ModelResolver(config, stubOAuth()); + const resolver = new SessionModelResolver(config, stubOAuth()); expect(() => resolver.resolve('orphan')).toThrowError( expect.objectContaining({ code: ErrorCodes.CONFIG_INVALID } as Partial), ); @@ -101,7 +101,7 @@ describe('ModelResolver', () => { }, }), ); - const resolver = new ModelResolver(config, stubOAuth()); + const resolver = new SessionModelResolver(config, stubOAuth()); expect(() => resolver.resolve('ghost')).toThrowError( expect.objectContaining({ code: ErrorCodes.CONFIG_INVALID } as Partial), ); diff --git a/packages/agent-core-v2/test/modelRuntime/stubs.ts b/packages/agent-core-v2/test/modelRuntime/stubs.ts index 8e45cf5d0..372f78edb 100644 --- a/packages/agent-core-v2/test/modelRuntime/stubs.ts +++ b/packages/agent-core-v2/test/modelRuntime/stubs.ts @@ -1,6 +1,6 @@ import type { IOAuthService } from '#/auth'; import type { IConfigService } from '#/config'; -import { ModelResolver, type IModelResolver } from '#/modelRuntime'; +import { SessionModelResolver, type ISessionModelResolver } from '#/modelRuntime'; import type { ProviderConfig } from '#/provider'; export type TestOAuthAccessTokenProvider = ( @@ -44,9 +44,9 @@ export function stubOAuth(getAccessToken?: TestOAuthAccessTokenProvider): IOAuth export function oauthAgentOptions( getAccessToken: TestOAuthAccessTokenProvider, capabilities: readonly string[] = ['image_in', 'video_in', 'tool_use'], -): { readonly modelResolver: IModelResolver } { +): { readonly modelResolver: ISessionModelResolver } { return { - modelResolver: new ModelResolver( + modelResolver: new SessionModelResolver( stubConfig({ defaultModel: 'kimi-code', providers: { diff --git a/packages/agent-core-v2/test/permission/permissionGate.test.ts b/packages/agent-core-v2/test/permission/permissionGate.test.ts index 35dd1aca3..33e12dd92 100644 --- a/packages/agent-core-v2/test/permission/permissionGate.test.ts +++ b/packages/agent-core-v2/test/permission/permissionGate.test.ts @@ -8,31 +8,31 @@ import { createHooks } from '#/hooks'; import type { Hooks } from '#/hooks'; import type { ApprovalResponse } from '#/approval/approval'; import type { ApprovalRequest } from '#/approval/approval'; -import { IApprovalService } from '#/approval/approval'; -import { IExternalHooksService } from '#/externalHooks'; +import { ISessionApprovalService } from '#/approval/approval'; +import { IAgentExternalHooksService } from '#/externalHooks'; import { IKaos } from '#/kaos'; import type { LLM } from '#/loop/llm'; import type { ResolvedToolExecutionHookContext } from '#/tool'; -import { IPermissionGate, PermissionGate } from '#/permissionGate'; +import { IAgentPermissionGate, AgentPermissionGate } from '#/permissionGate'; import type { PermissionGateOptions } from '#/permissionGate'; -import { IPermissionModeService } from '#/permissionMode'; +import { IAgentPermissionModeService } from '#/permissionMode'; import type { PermissionMode, PermissionPolicyEvaluation } from '#/permissionPolicy'; -import { IPermissionPolicyService } from '#/permissionPolicy'; -import { PermissionPolicyService } from '#/permissionPolicy/permissionPolicyService'; +import { IAgentPermissionPolicyService } from '#/permissionPolicy'; +import { AgentPermissionPolicyService } from '#/permissionPolicy/permissionPolicyService'; import type { - IPermissionRulesService as PermissionRulesServiceContract, + IAgentPermissionRulesService as PermissionRulesServiceContract, PermissionApprovalResultRecord, } from '#/permissionRules'; import type { PermissionRule } from '#/permissionRules'; -import { IPermissionRulesService } from '#/permissionRules'; -import { IPlanService } from '#/plan'; -import { IProfileService, type ProfileData } from '#/profile'; +import { IAgentPermissionRulesService } from '#/permissionRules'; +import { IAgentPlanService } from '#/plan'; +import { IAgentProfileService, type ProfileData } from '#/profile'; import { ISessionContext } from '#/session-context'; -import { ISwarmService } from '#/swarm'; +import { IAgentSwarmService } from '#/swarm'; import { ITelemetryService } from '#/telemetry/telemetry'; -import { IToolExecutor } from '#/toolExecutor'; -import { ITurnService } from '#/turn'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { IAgentToolExecutorService } from '#/toolExecutor'; +import { IAgentTurnService } from '#/turn'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; import type { ToolCall } from '@moonshot-ai/kosong'; import type { ToolInputDisplay } from '@moonshot-ai/protocol'; @@ -77,7 +77,7 @@ function planReviewDisplay(): ToolInputDisplay { }; } -describe('PermissionGate', () => { +describe('AgentPermissionGate', () => { let disposables: DisposableStore; let ix: TestInstantiationService; let mode: PermissionMode; @@ -93,18 +93,18 @@ describe('PermissionGate', () => { approvalResponse = { decision: 'approved' }; ix = createServices(disposables, { additionalServices: (reg) => { - reg.defineInstance(IPermissionModeService, stubPermissionModeService(() => mode)); - reg.defineInstance(IPermissionRulesService, stubPermissionRulesService(() => rules)); + reg.defineInstance(IAgentPermissionModeService, stubPermissionModeService(() => mode)); + reg.defineInstance(IAgentPermissionRulesService, stubPermissionRulesService(() => rules)); reg.defineInstance( - IPermissionPolicyService, + IAgentPermissionPolicyService, stubPermissionPolicyService(() => policyResult), ); - reg.definePartialInstance(IExternalHooksService, { + reg.definePartialInstance(IAgentExternalHooksService, { triggerPermissionRequest: () => {}, triggerPermissionResult: () => {}, }); reg.definePartialInstance(ITelemetryService, { track: () => {} }); - reg.defineInstance(IApprovalService, stubApprovalService(() => approvalResponse)); + reg.defineInstance(ISessionApprovalService, stubApprovalService(() => approvalResponse)); reg.defineInstance(ISessionContext, { _serviceBrand: undefined, sessionId: 'test-session', @@ -112,23 +112,23 @@ describe('PermissionGate', () => { sessionDir: '/tmp/test-session', metaScope: 'sessions/test-workspace/test-session/session-meta', }); - reg.definePartialInstance(IPlanService, { + reg.definePartialInstance(IAgentPlanService, { status: async () => null, exit: () => {}, }); - reg.definePartialInstance(ISwarmService, { + reg.definePartialInstance(IAgentSwarmService, { isActive: false, }); reg.definePartialInstance(IKaos, { pathClass: () => 'posix', }); - reg.definePartialInstance(IWorkspaceContext, { + reg.definePartialInstance(ISessionWorkspaceContext, { workDir: '/workspace', additionalDirs: [], }); - reg.defineInstance(ITurnService, stubTurnWithHooks()); - reg.defineInstance(IToolExecutor, stubToolExecutor()); - reg.definePartialInstance(IProfileService, { + reg.defineInstance(IAgentTurnService, stubTurnWithHooks()); + reg.defineInstance(IAgentToolExecutorService, stubToolExecutor()); + reg.definePartialInstance(IAgentProfileService, { data: () => ({ cwd: '/workspace' }) as ProfileData, }); }, @@ -138,20 +138,20 @@ describe('PermissionGate', () => { disposables.dispose(); }); - function make(options: PermissionGateOptions = {}): IPermissionGate { - ix.set(IPermissionGate, new SyncDescriptor(PermissionGate, [options])); - return ix.get(IPermissionGate); + function make(options: PermissionGateOptions = {}): IAgentPermissionGate { + ix.set(IAgentPermissionGate, new SyncDescriptor(AgentPermissionGate, [options])); + return ix.get(IAgentPermissionGate); } function useRealPolicyService(): void { - ix.set(IPermissionPolicyService, new SyncDescriptor(PermissionPolicyService)); + ix.set(IAgentPermissionPolicyService, new SyncDescriptor(AgentPermissionPolicyService)); } function setApprovalRequest( request: (approval: ApprovalRequest) => Promise, ): ReturnType Promise>> { const requestSpy = vi.fn(request); - ix.set(IApprovalService, { + ix.set(ISessionApprovalService, { _serviceBrand: undefined, request: requestSpy, enqueue: (approval) => ({ ...approval, id: approval.id ?? 'approval-1' }), @@ -319,7 +319,7 @@ describe('PermissionGate', () => { mode = 'manual'; const sessionApprovalRulePatterns: string[] = []; const recorded: PermissionApprovalResultRecord[] = []; - ix.set(IPermissionRulesService, mutablePermissionRulesService({ + ix.set(IAgentPermissionRulesService, mutablePermissionRulesService({ rules: () => [], sessionApprovalRulePatterns: () => sessionApprovalRulePatterns, record: (record) => { @@ -363,7 +363,7 @@ describe('PermissionGate', () => { it('keeps approved-once responses one-shot', async () => { mode = 'manual'; const recorded: PermissionApprovalResultRecord[] = []; - ix.set(IPermissionRulesService, mutablePermissionRulesService({ + ix.set(IAgentPermissionRulesService, mutablePermissionRulesService({ rules: () => [], sessionApprovalRulePatterns: () => [], record: (record) => recorded.push(record), @@ -385,10 +385,10 @@ describe('PermissionGate', () => { it('fires observer hooks while waiting for user approval', async () => { const permissionRequest = vi.fn(); const permissionResult = vi.fn(); - ix.set(IExternalHooksService, { + ix.set(IAgentExternalHooksService, { triggerPermissionRequest: permissionRequest, triggerPermissionResult: permissionResult, - } as Partial as IExternalHooksService); + } as Partial as IAgentExternalHooksService); policyResult = { policyName: 'p', result: { kind: 'ask' } }; approvalResponse = { decision: 'approved', selectedLabel: 'Approve once' }; const request = setApprovalRequest(async () => approvalResponse); @@ -493,7 +493,7 @@ describe('PermissionGate', () => { it('tracks approval transport errors before rethrowing', async () => { policyResult = { policyName: 'exit-plan-mode-review-ask', result: { kind: 'ask' } }; const error = new Error('approval transport closed'); - ix.set(IApprovalService, { + ix.set(ISessionApprovalService, { _serviceBrand: undefined, request: vi.fn(async () => { throw error; diff --git a/packages/agent-core-v2/test/permissionMode/stubs.ts b/packages/agent-core-v2/test/permissionMode/stubs.ts index ec5d5b126..7966115d1 100644 --- a/packages/agent-core-v2/test/permissionMode/stubs.ts +++ b/packages/agent-core-v2/test/permissionMode/stubs.ts @@ -1,6 +1,6 @@ /** * `permissionMode` test stubs — shared doubles for - * `IPermissionModeService`. + * `IAgentPermissionModeService`. * * Lives under `test/` (not `src/`) so test-support code stays out of the * production tree. Import from a relative path (`./stubs` or @@ -9,12 +9,12 @@ import { createHooks } from '#/hooks'; import type { Hooks } from '#/hooks'; -import type { IPermissionModeService } from '#/permissionMode'; +import type { IAgentPermissionModeService } from '#/permissionMode'; import type { PermissionMode } from '#/permissionPolicy'; export function stubPermissionModeService( mode: () => PermissionMode, -): IPermissionModeService { +): IAgentPermissionModeService { return { _serviceBrand: undefined, get mode() { diff --git a/packages/agent-core-v2/test/permissionPolicy/exit-plan-mode-review-ask-telemetry.test.ts b/packages/agent-core-v2/test/permissionPolicy/exit-plan-mode-review-ask-telemetry.test.ts index 747fe340c..b01da004c 100644 --- a/packages/agent-core-v2/test/permissionPolicy/exit-plan-mode-review-ask-telemetry.test.ts +++ b/packages/agent-core-v2/test/permissionPolicy/exit-plan-mode-review-ask-telemetry.test.ts @@ -5,10 +5,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { DisposableStore } from '#/_base/di/lifecycle'; import { createServices, type TestInstantiationService } from '#/_base/di/test'; import type { ResolvedToolExecutionHookContext } from '#/tool'; -import { IPermissionModeService } from '#/permissionMode'; +import { IAgentPermissionModeService } from '#/permissionMode'; import type { PermissionMode } from '#/permissionPolicy'; import { ExitPlanModeReviewAskPermissionPolicyService } from '#/permissionPolicy/policies/exit-plan-mode-review-ask'; -import { IPlanService, type IPlanService as PlanService } from '#/plan'; +import { IAgentPlanService, type IAgentPlanService as AgentPlanService } from '#/plan'; import { ITelemetryService } from '#/telemetry'; import { ToolAccesses } from '#/tool'; @@ -20,7 +20,7 @@ const options = [ { label: 'Approach B', description: 'Larger change.' }, ] as const; -type ExitPlanModeFn = PlanService['exit']; +type ExitPlanModeFn = AgentPlanService['exit']; interface RuntimeApprovalResponse { readonly decision: ApprovalResponse['decision']; @@ -71,7 +71,7 @@ function policyContext(display: ToolInputDisplay): ResolvedToolExecutionHookCont }; } -function planService(exitPlanMode: ExitPlanModeFn = vi.fn()): PlanService { +function planService(exitPlanMode: ExitPlanModeFn = vi.fn()): AgentPlanService { return { _serviceBrand: undefined, enter: async () => {}, @@ -98,7 +98,7 @@ describe('ExitPlanModeReviewAskPermissionPolicyService telemetry', () => { mode = 'manual'; ix = createServices(disposables, { additionalServices: (reg) => { - reg.defineInstance(IPermissionModeService, stubPermissionModeService(() => mode)); + reg.defineInstance(IAgentPermissionModeService, stubPermissionModeService(() => mode)); reg.defineInstance(ITelemetryService, recordingTelemetry(records)); }, }); @@ -111,7 +111,7 @@ describe('ExitPlanModeReviewAskPermissionPolicyService telemetry', () => { function makePolicy( exitPlanMode?: ExitPlanModeFn, ): ExitPlanModeReviewAskPermissionPolicyService { - ix.set(IPlanService, planService(exitPlanMode)); + ix.set(IAgentPlanService, planService(exitPlanMode)); return ix.createInstance(ExitPlanModeReviewAskPermissionPolicyService); } diff --git a/packages/agent-core-v2/test/permissionPolicy/goal-start-review-ask.test.ts b/packages/agent-core-v2/test/permissionPolicy/goal-start-review-ask.test.ts index cb15b663b..0c27e0d65 100644 --- a/packages/agent-core-v2/test/permissionPolicy/goal-start-review-ask.test.ts +++ b/packages/agent-core-v2/test/permissionPolicy/goal-start-review-ask.test.ts @@ -3,12 +3,12 @@ import type { ToolInputDisplay } from '@moonshot-ai/protocol'; import { describe, expect, it } from 'vitest'; import type { ResolvedToolExecutionHookContext } from '#/tool'; -import type { IPermissionModeService } from '#/permissionMode'; +import type { IAgentPermissionModeService } from '#/permissionMode'; import { GoalStartReviewAskPermissionPolicyService } from '#/permissionPolicy/policies/goal-start-review-ask'; import { ToolAccesses } from '#/tool'; const signal = new AbortController().signal; -type PermissionMode = IPermissionModeService['mode']; +type PermissionMode = IAgentPermissionModeService['mode']; function fakeModeService(initialMode: PermissionMode) { let currentMode = initialMode; @@ -19,7 +19,7 @@ function fakeModeService(initialMode: PermissionMode) { setMode(mode: PermissionMode) { currentMode = mode; }, - } as IPermissionModeService; + } as IAgentPermissionModeService; } function policyContext( diff --git a/packages/agent-core-v2/test/permissionPolicy/permission-policy-service.test.ts b/packages/agent-core-v2/test/permissionPolicy/permission-policy-service.test.ts index e1197b422..736d3e882 100644 --- a/packages/agent-core-v2/test/permissionPolicy/permission-policy-service.test.ts +++ b/packages/agent-core-v2/test/permissionPolicy/permission-policy-service.test.ts @@ -17,31 +17,31 @@ import { } from '#/_base/tools/support/rule-match'; import type { ResolvedToolExecutionHookContext } from '#/tool'; import { IKaos, type IKaos as KaosService } from '#/kaos'; -import { IPermissionModeService } from '#/permissionMode'; +import { IAgentPermissionModeService } from '#/permissionMode'; import { - IPermissionPolicyService, + IAgentPermissionPolicyService, type PermissionMode, type PermissionPolicyEvaluation, } from '#/permissionPolicy'; -import { PermissionPolicyService } from '#/permissionPolicy/permissionPolicyService'; +import { AgentPermissionPolicyService } from '#/permissionPolicy/permissionPolicyService'; import { - IPermissionRulesService, - type IPermissionRulesService as PermissionRulesServiceContract, + IAgentPermissionRulesService, + type IAgentPermissionRulesService as PermissionRulesServiceContract, type PermissionApprovalResultRecord, type PermissionRule, } from '#/permissionRules'; -import { IPlanService, type PlanData } from '#/plan'; -import { ISwarmService } from '#/swarm'; +import { IAgentPlanService, type PlanData } from '#/plan'; +import { IAgentSwarmService } from '#/swarm'; import { ITelemetryService } from '#/telemetry'; import { ToolAccesses, type ToolAccesses as ToolAccessList } from '#/tool'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; import { stubPermissionModeService } from '../permissionMode/stubs'; import { recordingTelemetry } from '../telemetry/stubs'; const signal = new AbortController().signal; -describe('PermissionPolicyService chain', () => { +describe('AgentPermissionPolicyService chain', () => { let disposables: DisposableStore; let ix: TestInstantiationService; let mode: PermissionMode; @@ -61,19 +61,19 @@ describe('PermissionPolicyService chain', () => { workspace = workspaceStub('/workspace'); ix = createServices(disposables, { additionalServices: (reg) => { - reg.defineInstance(IPermissionModeService, stubPermissionModeService(() => mode)); - reg.definePartialInstance(IPermissionRulesService, permissionRulesStub({ + reg.defineInstance(IAgentPermissionModeService, stubPermissionModeService(() => mode)); + reg.definePartialInstance(IAgentPermissionRulesService, permissionRulesStub({ rules: () => rules, sessionApprovalRulePatterns: () => sessionApprovalRulePatterns, })); - reg.defineInstance(IWorkspaceContext, workspace); + reg.defineInstance(ISessionWorkspaceContext, workspace); reg.defineInstance(IKaos, kaosStub()); - reg.definePartialInstance(IPlanService, planServiceStub(() => plan, () => { + reg.definePartialInstance(IAgentPlanService, planServiceStub(() => plan, () => { plan = null; })); - reg.definePartialInstance(ISwarmService, swarmServiceStub(() => swarmActive)); + reg.definePartialInstance(IAgentSwarmService, swarmServiceStub(() => swarmActive)); reg.defineInstance(ITelemetryService, recordingTelemetry([])); - reg.define(IPermissionPolicyService, PermissionPolicyService); + reg.define(IAgentPermissionPolicyService, AgentPermissionPolicyService); }, strict: true, }); @@ -83,8 +83,8 @@ describe('PermissionPolicyService chain', () => { disposables.dispose(); }); - function service(): IPermissionPolicyService { - return ix.get(IPermissionPolicyService); + function service(): IAgentPermissionPolicyService { + return ix.get(IAgentPermissionPolicyService); } async function evaluate( @@ -201,7 +201,7 @@ describe('PermissionPolicyService chain', () => { }); }); -describe('PermissionPolicyService plan-mode policies', () => { +describe('AgentPermissionPolicyService plan-mode policies', () => { let disposables: DisposableStore; let ix: TestInstantiationService; let mode: PermissionMode; @@ -215,18 +215,18 @@ describe('PermissionPolicyService plan-mode policies', () => { plan = null; ix = createServices(disposables, { additionalServices: (reg) => { - reg.defineInstance(IPermissionModeService, stubPermissionModeService(() => mode)); - reg.definePartialInstance(IPermissionRulesService, permissionRulesStub({ + reg.defineInstance(IAgentPermissionModeService, stubPermissionModeService(() => mode)); + reg.definePartialInstance(IAgentPermissionRulesService, permissionRulesStub({ sessionApprovalRulePatterns: () => sessionApprovalRulePatterns, })); - reg.defineInstance(IWorkspaceContext, workspaceStub('/workspace')); + reg.defineInstance(ISessionWorkspaceContext, workspaceStub('/workspace')); reg.defineInstance(IKaos, kaosStub()); - reg.definePartialInstance(IPlanService, planServiceStub(() => plan, () => { + reg.definePartialInstance(IAgentPlanService, planServiceStub(() => plan, () => { plan = null; })); - reg.definePartialInstance(ISwarmService, swarmServiceStub(() => false)); + reg.definePartialInstance(IAgentSwarmService, swarmServiceStub(() => false)); reg.defineInstance(ITelemetryService, recordingTelemetry([])); - reg.define(IPermissionPolicyService, PermissionPolicyService); + reg.define(IAgentPermissionPolicyService, AgentPermissionPolicyService); }, strict: true, }); @@ -239,7 +239,7 @@ describe('PermissionPolicyService plan-mode policies', () => { async function evaluate( input: PolicyContextInput, ): Promise { - const svc = ix.get(IPermissionPolicyService); + const svc = ix.get(IAgentPermissionPolicyService); return svc.evaluate(policyContext(input)); } @@ -392,7 +392,7 @@ describe('PermissionPolicyService plan-mode policies', () => { ); }); -describe('PermissionPolicyService git cwd write approval', () => { +describe('AgentPermissionPolicyService git cwd write approval', () => { let disposables: DisposableStore; let ix: TestInstantiationService; let mode: PermissionMode; @@ -409,14 +409,14 @@ describe('PermissionPolicyService git cwd write approval', () => { workspace = workspaceStub(workspaceDir); ix = createServices(disposables, { additionalServices: (reg) => { - reg.defineInstance(IPermissionModeService, stubPermissionModeService(() => mode)); - reg.definePartialInstance(IPermissionRulesService, permissionRulesStub()); - reg.defineInstance(IWorkspaceContext, workspace); + reg.defineInstance(IAgentPermissionModeService, stubPermissionModeService(() => mode)); + reg.definePartialInstance(IAgentPermissionRulesService, permissionRulesStub()); + reg.defineInstance(ISessionWorkspaceContext, workspace); reg.defineInstance(IKaos, kaosStub()); - reg.definePartialInstance(IPlanService, planServiceStub(() => null)); - reg.definePartialInstance(ISwarmService, swarmServiceStub(() => false)); + reg.definePartialInstance(IAgentPlanService, planServiceStub(() => null)); + reg.definePartialInstance(IAgentSwarmService, swarmServiceStub(() => false)); reg.defineInstance(ITelemetryService, recordingTelemetry([])); - reg.define(IPermissionPolicyService, PermissionPolicyService); + reg.define(IAgentPermissionPolicyService, AgentPermissionPolicyService); }, strict: true, }); @@ -430,7 +430,7 @@ describe('PermissionPolicyService git cwd write approval', () => { async function evaluate( input: PolicyContextInput, ): Promise { - const svc = ix.get(IPermissionPolicyService); + const svc = ix.get(IAgentPermissionPolicyService); return svc.evaluate(policyContext(input)); } @@ -707,7 +707,7 @@ function stringArg( return typeof value === 'string' ? value : fallback; } -function workspaceStub(initialWorkDir: string): IWorkspaceContext { +function workspaceStub(initialWorkDir: string): ISessionWorkspaceContext { let workDir = initialWorkDir; let additionalDirs: string[] = []; return { @@ -753,15 +753,15 @@ function kaosStub(pathClass: ReturnType = 'posix'): Ka function planServiceStub( status: () => PlanData | Promise, - exit: IPlanService['exit'] = () => {}, -): Partial { + exit: IAgentPlanService['exit'] = () => {}, +): Partial { return { status: async () => status(), exit, }; } -function swarmServiceStub(isActive: () => boolean): Partial { +function swarmServiceStub(isActive: () => boolean): Partial { return { get isActive() { return isActive(); diff --git a/packages/agent-core-v2/test/permissionPolicy/stubs.ts b/packages/agent-core-v2/test/permissionPolicy/stubs.ts index 2cbf5f862..cb3ffd3ab 100644 --- a/packages/agent-core-v2/test/permissionPolicy/stubs.ts +++ b/packages/agent-core-v2/test/permissionPolicy/stubs.ts @@ -1,6 +1,6 @@ /** * `permissionPolicy` test stubs — shared doubles for - * `IPermissionPolicyService`. + * `IAgentPermissionPolicyService`. * * Lives under `test/` (not `src/`) so test-support code stays out of the * production tree. Import from a relative path (`./stubs` or @@ -8,13 +8,13 @@ */ import type { - IPermissionPolicyService, + IAgentPermissionPolicyService, PermissionPolicyEvaluation, } from '#/permissionPolicy'; export function stubPermissionPolicyService( next: () => PermissionPolicyEvaluation | undefined, -): IPermissionPolicyService { +): IAgentPermissionPolicyService { return { _serviceBrand: undefined, evaluate: () => Promise.resolve(next()), diff --git a/packages/agent-core-v2/test/permissionRules/stubs.ts b/packages/agent-core-v2/test/permissionRules/stubs.ts index c1e083717..9bf28f810 100644 --- a/packages/agent-core-v2/test/permissionRules/stubs.ts +++ b/packages/agent-core-v2/test/permissionRules/stubs.ts @@ -1,6 +1,6 @@ /** * `permissionRules` test stubs — shared doubles for - * `IPermissionRulesService`. + * `IAgentPermissionRulesService`. * * Lives under `test/` (not `src/`) so test-support code stays out of the * production tree. Import from a relative path (`./stubs` or @@ -10,13 +10,13 @@ import { createHooks } from '#/hooks'; import type { Hooks } from '#/hooks'; import type { - IPermissionRulesService, + IAgentPermissionRulesService, PermissionRule, } from '#/permissionRules'; export function stubPermissionRulesService( rules: () => readonly PermissionRule[], -): IPermissionRulesService { +): IAgentPermissionRulesService { return { _serviceBrand: undefined, get rules() { diff --git a/packages/agent-core-v2/test/plan/injection.test.ts b/packages/agent-core-v2/test/plan/injection.test.ts index 7202811d9..bd0633594 100644 --- a/packages/agent-core-v2/test/plan/injection.test.ts +++ b/packages/agent-core-v2/test/plan/injection.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createFakeKaos } from '../tools/fixtures/fake-kaos'; -import { IContextInjector } from '#/contextInjector'; -import { IContextMemory, type ContextMessage } from '#/contextMemory'; -import { IPlanService } from '#/plan'; +import { IAgentContextInjectorService } from '#/contextInjector'; +import { IAgentContextMemoryService, type ContextMessage } from '#/contextMemory'; +import { IAgentPlanService } from '#/plan'; import { createTestAgent, kaosServices, @@ -15,7 +15,7 @@ type InjectableDynamicInjector = { }; async function enterPlan( - plan: IPlanService, + plan: IAgentPlanService, id = 'test-plan', ): Promise { await plan.enter(id, false); @@ -32,19 +32,19 @@ async function injectDynamic(injector: InjectableDynamicInjector): Promise function appendAssistantTurn( ctx: TestAgentContext, - context: IContextMemory, + context: IAgentContextMemoryService, text: string, ): void { ctx.appendAssistantTurn(context.get().length, text); } -function planReminderMessages(context: IContextMemory): readonly ContextMessage[] { +function planReminderMessages(context: IAgentContextMemoryService): readonly ContextMessage[] { return context.get().filter((message) => { return message.origin?.kind === 'injection' && message.origin.variant === 'plan_mode'; }); } -function lastPlanReminder(context: IContextMemory): string { +function lastPlanReminder(context: IAgentContextMemoryService): string { const message = planReminderMessages(context).at(-1); if (message === undefined) return ''; return message.content @@ -54,9 +54,9 @@ function lastPlanReminder(context: IContextMemory): string { describe('PlanModeService dynamic injection content', () => { let ctx: TestAgentContext; - let context: IContextMemory; + let context: IAgentContextMemoryService; let injector: InjectableDynamicInjector; - let plan: IPlanService; + let plan: IAgentPlanService; let readText: (path: string) => Promise; beforeEach(() => { @@ -66,9 +66,9 @@ describe('PlanModeService dynamic injection content', () => { readText: (path: string) => readText(path), writeText: vi.fn(async (_path: string, content: string) => content.length), }))); - context = ctx.get(IContextMemory); - injector = ctx.get(IContextInjector) as unknown as InjectableDynamicInjector; - plan = ctx.get(IPlanService); + context = ctx.get(IAgentContextMemoryService); + injector = ctx.get(IAgentContextInjectorService) as unknown as InjectableDynamicInjector; + plan = ctx.get(IAgentPlanService); }); afterEach(async () => { @@ -136,9 +136,9 @@ describe('PlanModeService dynamic injection content', () => { describe('PlanModeService dynamic injection cadence', () => { let ctx: TestAgentContext; - let context: IContextMemory; + let context: IAgentContextMemoryService; let injector: InjectableDynamicInjector; - let plan: IPlanService; + let plan: IAgentPlanService; beforeEach(() => { ctx = createTestAgent(kaosServices(createFakeKaos({ @@ -146,9 +146,9 @@ describe('PlanModeService dynamic injection cadence', () => { readText: async () => '', writeText: vi.fn(async (_path: string, content: string) => content.length), }))); - context = ctx.get(IContextMemory); - injector = ctx.get(IContextInjector) as unknown as InjectableDynamicInjector; - plan = ctx.get(IPlanService); + context = ctx.get(IAgentContextMemoryService); + injector = ctx.get(IAgentContextInjectorService) as unknown as InjectableDynamicInjector; + plan = ctx.get(IAgentPlanService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/plan/plan-tools-telemetry.test.ts b/packages/agent-core-v2/test/plan/plan-tools-telemetry.test.ts index 6ea262161..bd1d44ab7 100644 --- a/packages/agent-core-v2/test/plan/plan-tools-telemetry.test.ts +++ b/packages/agent-core-v2/test/plan/plan-tools-telemetry.test.ts @@ -1,14 +1,14 @@ import type { ToolCall } from '@moonshot-ai/kosong'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { IPlanService, PlanData } from '#/plan'; +import type { IAgentPlanService, PlanData } from '#/plan'; import { EnterPlanModeTool } from '#/plan/tools/enter-plan-mode'; import { ExitPlanModeTool, type ExitPlanModeInput, } from '#/plan/tools/exit-plan-mode'; import type { ITelemetryService } from '#/telemetry'; -import { IToolExecutor } from '#/toolExecutor'; +import { IAgentToolExecutorService } from '#/toolExecutor'; import { executeTool } from '../tools/fixtures/execute-tool'; import { createFakeKaos } from '../tools/fixtures/fake-kaos'; @@ -63,9 +63,9 @@ function planService({ exit, }: { readonly status?: PlanData; - readonly enter?: IPlanService['enter']; - readonly exit?: IPlanService['exit']; -} = {}): IPlanService { + readonly enter?: IAgentPlanService['enter']; + readonly exit?: IAgentPlanService['exit']; +} = {}): IAgentPlanService { return { _serviceBrand: undefined, enter: enter ?? vi.fn(async () => {}), @@ -102,11 +102,11 @@ describe('EnterPlanModeTool telemetry', () => { }); }); -describe('PlanService EnterPlanMode telemetry', () => { +describe('AgentPlanService EnterPlanMode telemetry', () => { for (const mode of ['manual', 'auto', 'yolo'] as const) { describe(`${mode} mode`, () => { let ctx: TestAgentContext; - let toolExecutor: IToolExecutor; + let toolExecutor: IAgentToolExecutorService; const records: TelemetryRecord[] = []; beforeEach(() => { @@ -118,7 +118,7 @@ describe('PlanService EnterPlanMode telemetry', () => { permissionModeServices(mode), telemetryServices(captureTelemetry(records)), ); - toolExecutor = ctx.get(IToolExecutor); + toolExecutor = ctx.get(IAgentToolExecutorService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/plan/plan.test.ts b/packages/agent-core-v2/test/plan/plan.test.ts index d7a20f668..6cc038971 100644 --- a/packages/agent-core-v2/test/plan/plan.test.ts +++ b/packages/agent-core-v2/test/plan/plan.test.ts @@ -6,11 +6,11 @@ import type { ToolCall } from '@moonshot-ai/kosong'; import { join } from 'pathe'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { IContextInjector } from '#/contextInjector'; -import { IContextMemory } from '#/contextMemory'; -import { IPlanService, type PlanData } from '#/plan'; -import { IPermissionRulesService } from '#/permissionRules'; -import { IProfileService } from '#/profile'; +import { IAgentContextInjectorService } from '#/contextInjector'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentPlanService, type PlanData } from '#/plan'; +import { IAgentPermissionRulesService } from '#/permissionRules'; +import { IAgentProfileService } from '#/profile'; import { createFakeKaos } from '../tools/fixtures/fake-kaos'; import { createCommandKaos, @@ -59,23 +59,23 @@ type InjectableDynamicInjector = { describe('Plan service', () => { let activeKaos: Kaos; - let context: IContextMemory; + let context: IAgentContextMemoryService; let ctx: TestAgentContext; let injector: InjectableDynamicInjector; - let permissionRules: IPermissionRulesService; - let plan: IPlanService; - let profile: IProfileService; + let permissionRules: IAgentPermissionRulesService; + let plan: IAgentPlanService; + let profile: IAgentProfileService; let tempDirs: string[]; beforeEach(() => { activeKaos = createPlanKaos(); tempDirs = []; ctx = createTestAgent(kaosServices(delegatingKaos())); - context = ctx.get(IContextMemory); - injector = ctx.get(IContextInjector) as unknown as InjectableDynamicInjector; - permissionRules = ctx.get(IPermissionRulesService); - plan = ctx.get(IPlanService); - profile = ctx.get(IProfileService); + context = ctx.get(IAgentContextMemoryService); + injector = ctx.get(IAgentContextInjectorService) as unknown as InjectableDynamicInjector; + permissionRules = ctx.get(IAgentPermissionRulesService); + plan = ctx.get(IAgentPlanService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/process/processRunnerService.test.ts b/packages/agent-core-v2/test/process/processRunnerService.test.ts index b22ebc01a..aeb4c33b0 100644 --- a/packages/agent-core-v2/test/process/processRunnerService.test.ts +++ b/packages/agent-core-v2/test/process/processRunnerService.test.ts @@ -13,7 +13,7 @@ import { } from '#/_base/di/scope'; import { createScopedTestHost, stubPair } from '#/_base/di/test'; import { IKaos, IKaosFactory, KaosFactory } from '#/kaos'; -import { IProcessRunner, ProcessRunner } from '#/process'; +import { ISessionProcessRunner, SessionProcessRunner } from '#/process'; async function collect(stream: Readable): Promise { const chunks: Buffer[] = []; @@ -23,13 +23,13 @@ async function collect(stream: Readable): Promise { return Buffer.concat(chunks).toString('utf8'); } -describe('ProcessRunner (backed by IKaos)', () => { +describe('SessionProcessRunner (backed by IKaos)', () => { let dir: string; beforeEach(async () => { _clearScopedRegistryForTests(); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, IKaosFactory, KaosFactory, InstantiationType.Delayed, @@ -37,8 +37,8 @@ describe('ProcessRunner (backed by IKaos)', () => { ); registerScopedService( LifecycleScope.Session, - IProcessRunner, - ProcessRunner, + ISessionProcessRunner, + SessionProcessRunner, InstantiationType.Delayed, 'process', ); @@ -49,12 +49,12 @@ describe('ProcessRunner (backed by IKaos)', () => { await rm(dir, { recursive: true, force: true }); }); - async function makeRunner(): Promise { + async function makeRunner(): Promise { const host = createScopedTestHost(); - const factory = host.core.accessor.get(IKaosFactory); + const factory = host.app.accessor.get(IKaosFactory); const kaos = await factory.createLocal(dir); const session = host.child(LifecycleScope.Session, 's', [stubPair(IKaos, kaos)]); - return session.accessor.get(IProcessRunner); + return session.accessor.get(ISessionProcessRunner); } it('exec runs a command and captures stdout + exit code', async () => { diff --git a/packages/agent-core-v2/test/profile/config-state.test.ts b/packages/agent-core-v2/test/profile/config-state.test.ts index 12493510f..163f10459 100644 --- a/packages/agent-core-v2/test/profile/config-state.test.ts +++ b/packages/agent-core-v2/test/profile/config-state.test.ts @@ -1,8 +1,8 @@ import { emptyUsage } from '@moonshot-ai/kosong'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { ILLMRequester } from '#/llmRequester'; -import { IProfileService } from '#/profile'; +import { IAgentLLMRequesterService } from '#/llmRequester'; +import { IAgentProfileService } from '#/profile'; import { configServices, createTestAgent, @@ -20,8 +20,8 @@ function defaultGenerate(): ReturnType { describe('ConfigState model capabilities', () => { let ctx: TestAgentContext; - let profile: IProfileService; - let requester: ILLMRequester; + let profile: IAgentProfileService; + let requester: IAgentLLMRequesterService; let kimiConfig: TestKimiConfig; let generate: GenerateFn; @@ -34,8 +34,8 @@ describe('ConfigState model capabilities', () => { configServices(() => kimiConfig), llmGenerateServices((...args) => generate(...args)), ); - profile = ctx.get(IProfileService); - requester = ctx.get(ILLMRequester); + profile = ctx.get(IAgentProfileService); + requester = ctx.get(IAgentLLMRequesterService); }); afterEach(async () => { @@ -152,7 +152,7 @@ describe('ConfigState model capabilities', () => { describe('ConfigState prompt cache hint', () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; let kimiConfig: TestKimiConfig; beforeEach(() => { @@ -175,7 +175,7 @@ describe('ConfigState prompt cache hint', () => { configServices(() => kimiConfig), modelProviderOptionServices({ promptCacheKey: 'session-test' }), ); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { @@ -201,7 +201,7 @@ describe('ConfigState prompt cache hint', () => { describe('ConfigState thinking clamp for always-thinking models', () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; let kimiConfig: TestKimiConfig; beforeEach(() => { @@ -223,7 +223,7 @@ describe('ConfigState thinking clamp for always-thinking models', () => { }, }; ctx = createTestAgent(configServices(() => kimiConfig)); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { @@ -267,7 +267,7 @@ describe('ConfigState thinking clamp for always-thinking models', () => { describe('ConfigState.provider applies global KIMI_MODEL_* request config', () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; let kimiConfig: TestKimiConfig; beforeEach(() => { @@ -278,7 +278,7 @@ describe('ConfigState.provider applies global KIMI_MODEL_* request config', () = }, }; ctx = createTestAgent(configServices(() => kimiConfig)); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); }); afterEach(async () => { diff --git a/packages/agent-core-v2/test/promptLegacy/promptLegacyService.test.ts b/packages/agent-core-v2/test/promptLegacy/promptLegacyService.test.ts index 173fa7e38..b1891e934 100644 --- a/packages/agent-core-v2/test/promptLegacy/promptLegacyService.test.ts +++ b/packages/agent-core-v2/test/promptLegacy/promptLegacyService.test.ts @@ -2,13 +2,13 @@ import { describe, expect, it, onTestFinished } from 'vitest'; import { DisposableStore } from '#/_base/di/lifecycle'; import { createServices } from '#/_base/di/test'; -import { IPermissionModeService } from '#/permissionMode/permissionMode'; -import { IProfileService } from '#/profile/profile'; -import { IPromptService } from '#/prompt/prompt'; -import { ITurnService, type Turn, type TurnResult } from '#/turn/turn'; +import { IAgentPermissionModeService } from '#/permissionMode/permissionMode'; +import { IAgentProfileService } from '#/profile/profile'; +import { IAgentPromptService } from '#/prompt/prompt'; +import { IAgentTurnService, type Turn, type TurnResult } from '#/turn/turn'; import type { PromptSubmission } from '@moonshot-ai/protocol'; -import { IPromptLegacyService, PromptLegacyService } from '#/promptLegacy'; +import { IAgentPromptLegacyService, AgentPromptLegacyService } from '#/promptLegacy'; interface ControlledTurn { readonly turn: Turn; @@ -34,7 +34,7 @@ function textBody(text: string): PromptSubmission { } interface Harness { - readonly service: IPromptLegacyService; + readonly service: IAgentPromptLegacyService; readonly turns: Turn[]; readonly settleActive: (result: TurnResult) => void; readonly steered: string[]; @@ -50,7 +50,7 @@ function createHarness(): Harness { const turns: Turn[] = []; const steered: string[] = []; - const prompt: IPromptService = { + const prompt: IAgentPromptService = { _serviceBrand: undefined, prompt: () => { if (activeTurn !== undefined) return undefined; @@ -77,7 +77,7 @@ function createHarness(): Harness { clear: () => {}, }; - const turnService: ITurnService = { + const turnService: IAgentTurnService = { launch: () => { throw new Error('not used'); }, @@ -88,27 +88,27 @@ function createHarness(): Harness { beforeStep: { run: async () => {} }, afterStep: { run: async () => {} }, }, - } as unknown as ITurnService; + } as unknown as IAgentTurnService; const profile = { setModel: () => Promise.resolve({ model: '' }), setThinking: () => {}, - } as unknown as IProfileService; + } as unknown as IAgentProfileService; const permissionMode = { setMode: () => {}, - } as unknown as IPermissionModeService; + } as unknown as IAgentPermissionModeService; const ix = createServices(disposables, { additionalServices: (reg) => { - reg.defineInstance(IPromptService, prompt); - reg.defineInstance(ITurnService, turnService); - reg.defineInstance(IProfileService, profile); - reg.defineInstance(IPermissionModeService, permissionMode); - reg.define(IPromptLegacyService, PromptLegacyService); + reg.defineInstance(IAgentPromptService, prompt); + reg.defineInstance(IAgentTurnService, turnService); + reg.defineInstance(IAgentProfileService, profile); + reg.defineInstance(IAgentPermissionModeService, permissionMode); + reg.define(IAgentPromptLegacyService, AgentPromptLegacyService); }, }); - const service = ix.get(IPromptLegacyService); + const service = ix.get(IAgentPromptLegacyService); return { service, turns, @@ -117,7 +117,7 @@ function createHarness(): Harness { }; } -describe('PromptLegacyService', () => { +describe('AgentPromptLegacyService', () => { it('launches a turn on submit and reports running', async () => { const { service, turns } = createHarness(); const result = await service.submit(textBody('hi')); diff --git a/packages/agent-core-v2/test/question/question.test.ts b/packages/agent-core-v2/test/question/question.test.ts index 0f9310979..bcfbf7101 100644 --- a/packages/agent-core-v2/test/question/question.test.ts +++ b/packages/agent-core-v2/test/question/question.test.ts @@ -9,8 +9,8 @@ import { type Scope, } from '#/_base/di/scope'; import { createScopedTestHost, type ScopedTestHost } from '#/_base/di/test'; -import { IInteractionService, InteractionService } from '#/interaction'; -import { type QuestionRequest, IQuestionService, QuestionService } from '#/question'; +import { ISessionInteractionService, SessionInteractionService } from '#/interaction'; +import { type QuestionRequest, ISessionQuestionService, SessionQuestionService } from '#/question'; function makeRequest(id: string): QuestionRequest { return { @@ -25,15 +25,15 @@ function makeRequest(id: string): QuestionRequest { }; } -describe('IQuestionService (Session scope facade over the interaction kernel)', () => { +describe('ISessionQuestionService (Session scope facade over the interaction kernel)', () => { let disposables: DisposableStore; let host: ScopedTestHost; let session: Scope; beforeEach(() => { _clearScopedRegistryForTests(); - registerScopedService(LifecycleScope.Session, IInteractionService, InteractionService, InstantiationType.Delayed, 'interaction'); - registerScopedService(LifecycleScope.Session, IQuestionService, QuestionService, InstantiationType.Delayed, 'question'); + registerScopedService(LifecycleScope.Session, ISessionInteractionService, SessionInteractionService, InstantiationType.Delayed, 'interaction'); + registerScopedService(LifecycleScope.Session, ISessionQuestionService, SessionQuestionService, InstantiationType.Delayed, 'question'); disposables = new DisposableStore(); host = createScopedTestHost(); @@ -46,7 +46,7 @@ describe('IQuestionService (Session scope facade over the interaction kernel)', }); it('request parks until answer resolves it with the rich result', async () => { - const questions = session.accessor.get(IQuestionService); + const questions = session.accessor.get(ISessionQuestionService); const pending = questions.request(makeRequest('q1')); expect(questions.listPending().map((r) => r.id)).toEqual(['q1']); @@ -57,8 +57,8 @@ describe('IQuestionService (Session scope facade over the interaction kernel)', }); it('enqueue returns immediately and the answer streams over onDidResolve', () => { - const interaction = session.accessor.get(IInteractionService); - const questions = session.accessor.get(IQuestionService); + const interaction = session.accessor.get(ISessionInteractionService); + const questions = session.accessor.get(ISessionQuestionService); const resolved: { id: string; response: unknown }[] = []; disposables.add(interaction.onDidResolve((r) => resolved.push(r))); @@ -73,7 +73,7 @@ describe('IQuestionService (Session scope facade over the interaction kernel)', }); it('dismiss resolves a pending request with null', async () => { - const questions = session.accessor.get(IQuestionService); + const questions = session.accessor.get(ISessionQuestionService); const pending = questions.request(makeRequest('q1')); questions.dismiss('q1'); @@ -83,7 +83,7 @@ describe('IQuestionService (Session scope facade over the interaction kernel)', }); it('listPending returns the stored in-process payload', () => { - const questions = session.accessor.get(IQuestionService); + const questions = session.accessor.get(ISessionQuestionService); questions.enqueue(makeRequest('q1')); const pending = questions.listPending(); @@ -97,8 +97,8 @@ describe('IQuestionService (Session scope facade over the interaction kernel)', it('Session scope isolates brokers: a question parked in A is invisible to B', () => { const sessionB = host.child(LifecycleScope.Session, 'session-b'); - const questionsA = session.accessor.get(IQuestionService); - const questionsB = sessionB.accessor.get(IQuestionService); + const questionsA = session.accessor.get(ISessionQuestionService); + const questionsB = sessionB.accessor.get(ISessionQuestionService); questionsA.enqueue(makeRequest('q1')); expect(questionsA.listPending().map((r) => r.id)).toEqual(['q1']); diff --git a/packages/agent-core-v2/test/session-activity/sessionActivity.test.ts b/packages/agent-core-v2/test/session-activity/sessionActivity.test.ts index ef2b8d773..47d68a775 100644 --- a/packages/agent-core-v2/test/session-activity/sessionActivity.test.ts +++ b/packages/agent-core-v2/test/session-activity/sessionActivity.test.ts @@ -6,10 +6,10 @@ import { DisposableStore } from '#/_base/di/lifecycle'; import { type IScopeHandle, LifecycleScope } from '#/_base/di/scope'; import { TestInstantiationService } from '#/_base/di/test'; import { IAgentLifecycleService } from '#/agent-lifecycle/agentLifecycle'; -import { IInteractionService, type Interaction, type InteractionKind } from '#/interaction'; +import { ISessionInteractionService, type Interaction, type InteractionKind } from '#/interaction'; import { ISessionActivity } from '#/session-activity/sessionActivity'; import { SessionActivity } from '#/session-activity/sessionActivityService'; -import { ITurnService, type Turn } from '#/turn'; +import { IAgentTurnService, type Turn } from '#/turn'; import { stubTurn } from '../turn/stubs'; function makeTurn(id: number): Turn { @@ -21,7 +21,7 @@ function makeTurn(id: number): Turn { }; } -function makeTurnService(active: boolean): ITurnService { +function makeTurnService(active: boolean): IAgentTurnService { const base = stubTurn(); const activeTurn = active ? makeTurn(1) : undefined; return { @@ -30,10 +30,10 @@ function makeTurnService(active: boolean): ITurnService { }; } -function makeAccessor(turn: ITurnService): ServicesAccessor { +function makeAccessor(turn: IAgentTurnService): ServicesAccessor { return { get(id: ServiceIdentifier): T { - if (id === (ITurnService as unknown as ServiceIdentifier)) { + if (id === (IAgentTurnService as unknown as ServiceIdentifier)) { return turn as unknown as T; } throw new Error(`unexpected service request: ${String(id)}`); @@ -66,7 +66,7 @@ function lifecycle(handles: readonly IScopeHandle[]): IAgentLifecycleService { function interactions( pending: { approval?: number; question?: number }, -): Partial { +): Partial { const items: Interaction[] = []; for (let i = 0; i < (pending.approval ?? 0); i++) { items.push({ id: `a${i}`, kind: 'approval', payload: {}, origin: {}, createdAt: 0 }); @@ -88,7 +88,7 @@ describe('SessionActivity', () => { disposables = new DisposableStore(); ix = disposables.add(new TestInstantiationService()); ix.set(ISessionActivity, new SyncDescriptor(SessionActivity)); - ix.stub(IInteractionService, interactions({})); + ix.stub(ISessionInteractionService, interactions({})); }); afterEach(() => disposables.dispose()); @@ -123,25 +123,25 @@ describe('SessionActivity', () => { it('awaiting_approval when an approval interaction is pending', () => { ix.stub(IAgentLifecycleService, lifecycle([handle('a', false)])); - ix.stub(IInteractionService, interactions({ approval: 1 })); + ix.stub(ISessionInteractionService, interactions({ approval: 1 })); expect(ix.get(ISessionActivity).status()).toBe('awaiting_approval'); }); it('awaiting_question when a question interaction is pending', () => { ix.stub(IAgentLifecycleService, lifecycle([handle('a', false)])); - ix.stub(IInteractionService, interactions({ question: 1 })); + ix.stub(ISessionInteractionService, interactions({ question: 1 })); expect(ix.get(ISessionActivity).status()).toBe('awaiting_question'); }); it('approval takes priority over question', () => { ix.stub(IAgentLifecycleService, lifecycle([handle('a', false)])); - ix.stub(IInteractionService, interactions({ approval: 1, question: 1 })); + ix.stub(ISessionInteractionService, interactions({ approval: 1, question: 1 })); expect(ix.get(ISessionActivity).status()).toBe('awaiting_approval'); }); it('question takes priority over running', () => { ix.stub(IAgentLifecycleService, lifecycle([handle('a', true)])); - ix.stub(IInteractionService, interactions({ question: 1 })); + ix.stub(ISessionInteractionService, interactions({ question: 1 })); expect(ix.get(ISessionActivity).status()).toBe('awaiting_question'); }); }); diff --git a/packages/agent-core-v2/test/session-index/sessionIndex.test.ts b/packages/agent-core-v2/test/session-index/sessionIndex.test.ts index ea468c5e0..401ade7a6 100644 --- a/packages/agent-core-v2/test/session-index/sessionIndex.test.ts +++ b/packages/agent-core-v2/test/session-index/sessionIndex.test.ts @@ -28,7 +28,7 @@ describe('FileSessionIndex', () => { beforeEach(async () => { _clearScopedRegistryForTests(); - registerScopedService(LifecycleScope.Core, ISessionIndex, FileSessionIndex, InstantiationType.Delayed, 'session-index'); + registerScopedService(LifecycleScope.App, ISessionIndex, FileSessionIndex, InstantiationType.Delayed, 'session-index'); homeDir = await fsp.mkdtemp(join(os.tmpdir(), 'ws-sessions-')); sessionsDir = join(homeDir, 'sessions'); workspaceId = encodeWorkDirKey(WORK_DIR); @@ -48,7 +48,7 @@ describe('FileSessionIndex', () => { stubPair(IBootstrapService, { homeDir, sessionsDir } as IBootstrapService), ]); disposeHost = () => host.dispose(); - return host.core.accessor.get(ISessionIndex); + return host.app.accessor.get(ISessionIndex); } async function seedSession( diff --git a/packages/agent-core-v2/test/session-lifecycle/sessionLifecycle.test.ts b/packages/agent-core-v2/test/session-lifecycle/sessionLifecycle.test.ts index 6bb8aba7c..18c3405b8 100644 --- a/packages/agent-core-v2/test/session-lifecycle/sessionLifecycle.test.ts +++ b/packages/agent-core-v2/test/session-lifecycle/sessionLifecycle.test.ts @@ -13,7 +13,7 @@ import { ISessionService } from '#/session'; import { ISessionLifecycleService } from '#/session-lifecycle/sessionLifecycle'; import { SessionLifecycleService } from '#/session-lifecycle/sessionLifecycleService'; import { ISessionMetadata } from '#/session-metadata'; -import { ISkillCatalog } from '#/skill'; +import { ISessionSkillCatalog } from '#/skill'; function bootstrapStub(): IBootstrapService { return { @@ -54,7 +54,7 @@ function kaosFactoryStub(): IKaosFactory { }; } -function skillCatalogStub(): ISkillCatalog { +function skillCatalogStub(): ISessionSkillCatalog { return { _serviceBrand: undefined, catalog: { @@ -78,7 +78,7 @@ describe('SessionLifecycleService', () => { beforeEach(() => { _clearScopedRegistryForTests(); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ISessionLifecycleService, SessionLifecycleService, InstantiationType.Delayed, @@ -96,10 +96,10 @@ describe('SessionLifecycleService', () => { stubPair(IBootstrapService, bootstrapStub()), stubPair(ISessionMetadata, metadataStub()), stubPair(IKaosFactory, kaosFactoryStub()), - stubPair(ISkillCatalog, skillCatalogStub()), + stubPair(ISessionSkillCatalog, skillCatalogStub()), ...extra, ]); - return host.core.accessor.get(ISessionLifecycleService); + return host.app.accessor.get(ISessionLifecycleService); } it('create / get / list / close', async () => { diff --git a/packages/agent-core-v2/test/shellTools/bash.test.ts b/packages/agent-core-v2/test/shellTools/bash.test.ts index 3035da0e0..2c2fdafb2 100644 --- a/packages/agent-core-v2/test/shellTools/bash.test.ts +++ b/packages/agent-core-v2/test/shellTools/bash.test.ts @@ -3,9 +3,9 @@ * * Ported from v1 (`packages/agent-core/test/tools/bash.test.ts`) and adapted * to the v2 constructor `(runner, kaos, background, options)`. Self-contained: - * builds minimal fake `IProcessRunner` / `IProcess`, `IKaos`, and - * `IBackgroundService` inline so the tool can be exercised without the - * composition root. The fake `IBackgroundService` drives the real + * builds minimal fake `ISessionProcessRunner` / `IProcess`, `IKaos`, and + * `IAgentBackgroundService` inline so the tool can be exercised without the + * composition root. The fake `IAgentBackgroundService` drives the real * `ProcessBackgroundTask` so stream observation, timeout and user-interrupt * semantics match production. * @@ -22,7 +22,7 @@ import { PassThrough, Readable, type Writable } from 'node:stream'; import { describe, expect, it, vi } from 'vitest'; import { - IBackgroundService, + IAgentBackgroundService, ProcessBackgroundTask, type BackgroundTask, type BackgroundTaskInfo, @@ -33,7 +33,7 @@ import { } from '../../src/background'; import type { BackgroundTaskSettlement } from '../../src/background/task'; import type { Environment, IKaos } from '../../src/kaos'; -import type { IProcess, IProcessRunner } from '../../src/process'; +import type { IProcess, ISessionProcessRunner } from '../../src/process'; import { type BashInput, BashInputSchema, BashTool } from '../../src/shellTools/tools/bash'; import type { ExecutableToolContext, ExecutableToolResult, ToolExecution } from '../../src/tool'; @@ -287,15 +287,15 @@ function createTestKaos(osEnv: Environment = posixEnv, cwd = '/workspace'): IKao } as unknown as IKaos; } -// ── Fake IProcessRunner ────────────────────────────────────────────── +// ── Fake ISessionProcessRunner ────────────────────────────────────────────── function createTestRunner(proc: IProcess | ReturnType) { const exec = typeof proc === 'function' ? proc : vi.fn().mockResolvedValue(proc); - const runner = { exec } as unknown as IProcessRunner; + const runner = { exec } as unknown as ISessionProcessRunner; return { runner, exec }; } -// ── Fake IBackgroundService ────────────────────────────────────────── +// ── Fake IAgentBackgroundService ────────────────────────────────────────── const TERMINAL_STATUSES: ReadonlySet = new Set([ 'completed', @@ -347,7 +347,7 @@ function errorMessage(error: unknown): string { } function createFakeBackgroundService(options: { maxRunningTasks?: number } = {}): { - readonly service: IBackgroundService; + readonly service: IAgentBackgroundService; readonly tasks: Map; } { const tasks = new Map(); @@ -433,7 +433,7 @@ function createFakeBackgroundService(options: { maxRunningTasks?: number } = {}) return count; }; - const service: IBackgroundService = { + const service: IAgentBackgroundService = { _serviceBrand: undefined, registerTask(task: BackgroundTask, registerOptions: RegisterBackgroundTaskOptions = {}): string { @@ -647,9 +647,9 @@ async function executeTool( } function bashTool( - runner: IProcessRunner, + runner: ISessionProcessRunner, kaos: IKaos = createTestKaos(), - background: IBackgroundService = createFakeBackgroundService().service, + background: IAgentBackgroundService = createFakeBackgroundService().service, options?: ConstructorParameters[3], ): BashTool { return new BashTool(runner, kaos, background, options); diff --git a/packages/agent-core-v2/test/shellTools/shellToolsService.test.ts b/packages/agent-core-v2/test/shellTools/shellToolsService.test.ts index 151c63f62..0864cc8ba 100644 --- a/packages/agent-core-v2/test/shellTools/shellToolsService.test.ts +++ b/packages/agent-core-v2/test/shellTools/shellToolsService.test.ts @@ -1,37 +1,37 @@ import { describe, expect, it, vi } from 'vitest'; -import type { IBackgroundService } from '#/background'; +import type { IAgentBackgroundService } from '#/background'; import type { IDisposable } from '#/_base/di'; import type { IKaos } from '#/kaos'; -import type { IProcessRunner } from '#/process'; -import { ShellToolsService } from '#/shellTools'; -import type { IToolRegistry } from '#/toolRegistry'; +import type { ISessionProcessRunner } from '#/process'; +import { AgentShellToolsService } from '#/shellTools'; +import type { IAgentToolRegistryService } from '#/toolRegistry'; -function fakeToolRegistry(): { registry: IToolRegistry; names: () => string[] } { +function fakeToolRegistry(): { registry: IAgentToolRegistryService; names: () => string[] } { const tools = new Map(); - const registry: IToolRegistry = { + const registry: IAgentToolRegistryService = { _serviceBrand: undefined, register: vi.fn((tool: { name: string }): IDisposable => { tools.set(tool.name, tool); return { dispose: () => tools.delete(tool.name) }; }), list: () => [...tools.values()] as never, - } as unknown as IToolRegistry; + } as unknown as IAgentToolRegistryService; return { registry, names: () => [...tools.keys()].sort() }; } -const fakeRunner = {} as unknown as IProcessRunner; +const fakeRunner = {} as unknown as ISessionProcessRunner; const fakeKaos = { cwd: '/workspace', osEnv: { osKind: 'Linux', osArch: 'x64', osVersion: '', shellName: 'bash', shellPath: '/bin/bash' }, pathClass: () => 'posix', } as unknown as IKaos; -const fakeBackground = {} as unknown as IBackgroundService; +const fakeBackground = {} as unknown as IAgentBackgroundService; -describe('ShellToolsService', () => { +describe('AgentShellToolsService', () => { it('registers Bash into the tool registry', () => { const { registry, names } = fakeToolRegistry(); - new ShellToolsService(registry, fakeRunner, fakeKaos, fakeBackground); + new AgentShellToolsService(registry, fakeRunner, fakeKaos, fakeBackground); expect(names()).toEqual(['Bash']); }); }); diff --git a/packages/agent-core-v2/test/skill/plugin-session-start.test.ts b/packages/agent-core-v2/test/skill/plugin-session-start.test.ts index 1827aeb25..e8c2c09fb 100644 --- a/packages/agent-core-v2/test/skill/plugin-session-start.test.ts +++ b/packages/agent-core-v2/test/skill/plugin-session-start.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { IContextInjector } from '#/contextInjector'; +import { IAgentContextInjectorService } from '#/contextInjector'; import type { ContextMessage } from '#/contextMemory'; import type { LogContext, LogPayload } from '#/log'; import type { EnabledPluginSessionStart } from '#/plugin/types'; @@ -80,7 +80,7 @@ function sessionStartRuntime(input: { } async function injectDynamic(ctx: ReturnType): Promise { - await (ctx.get(IContextInjector) as unknown as InjectableDynamicInjector).inject(); + await (ctx.get(IAgentContextInjectorService) as unknown as InjectableDynamicInjector).inject(); } function lastReminder(ctx: ReturnType): string { diff --git a/packages/agent-core-v2/test/skill/skill-tool-manager.test.ts b/packages/agent-core-v2/test/skill/skill-tool-manager.test.ts index 406616368..b930c3125 100644 --- a/packages/agent-core-v2/test/skill/skill-tool-manager.test.ts +++ b/packages/agent-core-v2/test/skill/skill-tool-manager.test.ts @@ -5,12 +5,12 @@ import { join } from 'pathe'; import type { ToolCall } from '@moonshot-ai/kosong'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { IContextMemory } from '#/contextMemory'; -import { IEventSink } from '#/eventSink'; -import { IProfileService } from '#/profile'; -import { IReplayBuilderService } from '#/replayBuilder'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentEventSinkService } from '#/eventSink'; +import { IAgentProfileService } from '#/profile'; +import { IAgentReplayBuilderService } from '#/replayBuilder'; import { InMemorySkillCatalog, type SkillCatalog, type SkillDefinition } from '#/skill'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { InMemoryWireRecordPersistence, createTestAgent, @@ -56,13 +56,13 @@ function isRecordWithMessages( describe('ToolManager SkillTool registration', () => { let ctx: TestAgentContext; - let profile: IProfileService; - let tools: IToolRegistry; + let profile: IAgentProfileService; + let tools: IAgentToolRegistryService; beforeEach(() => { ctx = createTestAgent(); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); }); afterEach(async () => { @@ -83,16 +83,16 @@ describe('ToolManager SkillTool registration', () => { describe('ToolManager SkillTool registration with an empty model skill catalog', () => { let ctx: TestAgentContext; - let profile: IProfileService; - let tools: IToolRegistry; + let profile: IAgentProfileService; + let tools: IAgentToolRegistryService; let skills: InMemorySkillCatalog; beforeEach(() => { skills = new InMemorySkillCatalog(); skills.register(makeSkill('private', { disableModelInvocation: true })); ctx = createTestAgent(skillServices(skills)); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); }); afterEach(async () => { @@ -113,8 +113,8 @@ describe('ToolManager SkillTool registration with an empty model skill catalog', describe('ToolManager SkillTool registration with inline skills', () => { let ctx: TestAgentContext; - let profile: IProfileService; - let tools: IToolRegistry; + let profile: IAgentProfileService; + let tools: IAgentToolRegistryService; let skills: InMemorySkillCatalog; beforeEach(() => { @@ -122,8 +122,8 @@ describe('ToolManager SkillTool registration with inline skills', () => { skills.register(makeSkill('review')); skills.register(makeSkill('flow-only', { type: 'flow' })); ctx = createTestAgent(skillServices(skills)); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); }); afterEach(async () => { @@ -150,8 +150,8 @@ describe('ToolManager SkillTool registration with inline skills', () => { describe('ToolManager SkillTool registration with a structural catalog', () => { let ctx: TestAgentContext; - let profile: IProfileService; - let tools: IToolRegistry; + let profile: IAgentProfileService; + let tools: IAgentToolRegistryService; let skills: SkillCatalog; beforeEach(() => { @@ -166,8 +166,8 @@ describe('ToolManager SkillTool registration with a structural catalog', () => { getModelSkillListing: () => '- review: desc for review', }; ctx = createTestAgent(skillServices(skills)); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); }); afterEach(async () => { @@ -188,8 +188,8 @@ describe('ToolManager SkillTool registration with a structural catalog', () => { describe('ToolManager SkillTool wire behavior', () => { let ctx: TestAgentContext; - let context: IContextMemory; - let profile: IProfileService; + let context: IAgentContextMemoryService; + let profile: IAgentProfileService; let persistence: InMemoryWireRecordPersistence; let skills: InMemorySkillCatalog; @@ -201,8 +201,8 @@ describe('ToolManager SkillTool wire behavior', () => { skillServices(skills), wireRecordPersistenceServices(persistence), ); - context = ctx.get(IContextMemory); - profile = ctx.get(IProfileService); + context = ctx.get(IAgentContextMemoryService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Skill'] }); }); @@ -278,8 +278,8 @@ describe('ToolManager SkillTool wire behavior', () => { describe('ToolManager SkillTool restore behavior', () => { let ctx: TestAgentContext; - let context: IContextMemory; - let replay: IReplayBuilderService; + let context: IAgentContextMemoryService; + let replay: IAgentReplayBuilderService; let skills: InMemorySkillCatalog; let emit: ReturnType; let track: ReturnType; @@ -293,9 +293,9 @@ describe('ToolManager SkillTool restore behavior', () => { skillServices(skills), telemetryServices(telemetry), ); - context = ctx.get(IContextMemory); - const events = ctx.get(IEventSink); - replay = ctx.get(IReplayBuilderService); + context = ctx.get(IAgentContextMemoryService); + const events = ctx.get(IAgentEventSinkService); + replay = ctx.get(IAgentReplayBuilderService); emit = vi.spyOn(events, 'emit'); }); @@ -366,9 +366,9 @@ describe('ToolManager SkillTool restore behavior', () => { describe('ToolManager SkillTool workspace refresh', () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; let tmp: string; - let tools: IToolRegistry; + let tools: IAgentToolRegistryService; beforeEach(async () => { tmp = await mkdtemp(join(tmpdir(), 'kimi-core-skill-tool-refresh-')); @@ -394,8 +394,8 @@ describe('ToolManager SkillTool workspace refresh', () => { kaosServices(createFakeKaos().withCwd(workDir)), skillServices(skills), ); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); profile.update({ activeToolNames: ['Skill'] }); }); diff --git a/packages/agent-core-v2/test/skill/skill.test.ts b/packages/agent-core-v2/test/skill/skill.test.ts index 219064a66..25cbf62fa 100644 --- a/packages/agent-core-v2/test/skill/skill.test.ts +++ b/packages/agent-core-v2/test/skill/skill.test.ts @@ -4,14 +4,14 @@ import { SyncDescriptor } from '#/_base/di/descriptors'; import { DisposableStore } from '#/_base/di/lifecycle'; import { createServices, type TestInstantiationService } from '#/_base/di/test'; import type { ContextMessage } from '#/contextMemory'; -import { IEventSink } from '#/eventSink'; -import { IPromptService } from '#/prompt'; -import { IAgentSkillService, InMemorySkillCatalog, ISkillCatalog } from '#/skill'; +import { IAgentEventSinkService } from '#/eventSink'; +import { IAgentPromptService } from '#/prompt'; +import { IAgentSkillService, InMemorySkillCatalog, ISessionSkillCatalog } from '#/skill'; import { AgentSkillService } from '#/skill/skillService'; import { ITelemetryService } from '#/telemetry'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { Turn } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentWireRecordService } from '#/wireRecord'; import { stubWireRecord } from '../contextMemory/stubs'; import { stubSkill } from './stubs'; @@ -43,7 +43,7 @@ describe('AgentSkillService', () => { prompted = []; ix = createServices(disposables, { additionalServices: (reg) => { - reg.definePartialInstance(IPromptService, { + reg.definePartialInstance(IAgentPromptService, { prompt: (message) => { prompted.push(message); return fakeTurn(); @@ -53,27 +53,27 @@ describe('AgentSkillService', () => { undo: () => 0, clear: () => {}, }); - reg.definePartialInstance(IEventSink, { + reg.definePartialInstance(IAgentEventSinkService, { emit: () => {}, on: () => ({ dispose: () => {} }), }); - reg.defineInstance(IWireRecord, stubWireRecord()); + reg.defineInstance(IAgentWireRecordService, stubWireRecord()); reg.definePartialInstance(ITelemetryService, { track: () => {} }); - reg.definePartialInstance(IToolRegistry, { + reg.definePartialInstance(IAgentToolRegistryService, { register: () => ({ dispose: () => {} }), }); }, }); const skills = new InMemorySkillCatalog(); skills.register(COMMIT_SKILL); - const skillCatalog: ISkillCatalog = { + const skillCatalog: ISessionSkillCatalog = { _serviceBrand: undefined, catalog: skills, ready: Promise.resolve(), load: async () => {}, reload: async () => {}, }; - ix.set(ISkillCatalog, skillCatalog); + ix.set(ISessionSkillCatalog, skillCatalog); ix.set(IAgentSkillService, new SyncDescriptor(AgentSkillService)); }); afterEach(() => disposables.dispose()); @@ -103,13 +103,13 @@ describe('AgentSkillService', () => { }); const skills = new InMemorySkillCatalog(); skills.register(COMMIT_SKILL); - ix.set(ISkillCatalog, { + ix.set(ISessionSkillCatalog, { _serviceBrand: undefined, catalog: skills, ready, load: async () => {}, reload: async () => {}, - } satisfies ISkillCatalog); + } satisfies ISessionSkillCatalog); ix.set(IAgentSkillService, new SyncDescriptor(AgentSkillService)); const svc = ix.get(IAgentSkillService); diff --git a/packages/agent-core-v2/test/skill/skillCatalog.test.ts b/packages/agent-core-v2/test/skill/skillCatalog.test.ts index 6d1078d47..b9c694115 100644 --- a/packages/agent-core-v2/test/skill/skillCatalog.test.ts +++ b/packages/agent-core-v2/test/skill/skillCatalog.test.ts @@ -3,10 +3,10 @@ import { describe, expect, it } from 'vitest'; import { createScopedTestHost, stubPair } from '#/_base/di/test'; import { LifecycleScope } from '#/_base/di/scope'; import { IBootstrapService } from '#/bootstrap'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; import '#/skill'; import { InMemorySkillCatalogStore } from '#/skill/inMemorySkillCatalogStore'; -import { ISkillCatalog } from '#/skill/skillCatalog'; +import { ISessionSkillCatalog } from '#/skill/skillCatalog'; import { ISkillCatalogStore } from '#/skill/skillCatalogStore'; import { stubSkill } from './stubs'; @@ -18,7 +18,7 @@ const bootstrapStub = { } as unknown as IBootstrapService; function workspaceStub(workDir: string): { - readonly stub: IWorkspaceContext; + readonly stub: ISessionWorkspaceContext; setWorkDir(dir: string): void; } { let current = workDir; @@ -36,20 +36,20 @@ function workspaceStub(workDir: string): { assertAllowed: (p: string) => p, addAdditionalDir: () => {}, removeAdditionalDir: () => {}, - } satisfies IWorkspaceContext; + } satisfies ISessionWorkspaceContext; return { stub, setWorkDir: (dir) => { current = dir; } }; } -function makeHost(store: InMemorySkillCatalogStore, ws: IWorkspaceContext) { +function makeHost(store: InMemorySkillCatalogStore, ws: ISessionWorkspaceContext) { const host = createScopedTestHost([ stubPair(ISkillCatalogStore, store), stubPair(IBootstrapService, bootstrapStub), ]); - const session = host.child(LifecycleScope.Session, 's1', [stubPair(IWorkspaceContext, ws)]); + const session = host.child(LifecycleScope.Session, 's1', [stubPair(ISessionWorkspaceContext, ws)]); return { host, session }; } -describe('SkillCatalogService', () => { +describe('SessionSkillCatalogService', () => { it('merges global and project skills; project wins on name collision', async () => { const store = new InMemorySkillCatalogStore(); store.setUserSkills([ @@ -63,7 +63,7 @@ describe('SkillCatalogService', () => { const { stub: ws } = workspaceStub('/work'); const { host, session } = makeHost(store, ws); - const catalog = session.accessor.get(ISkillCatalog); + const catalog = session.accessor.get(ISessionSkillCatalog); await catalog.load(); const names = catalog.catalog.listSkills().map((s) => s.name); @@ -81,7 +81,7 @@ describe('SkillCatalogService', () => { const { stub: ws, setWorkDir } = workspaceStub('/work1'); const { host, session } = makeHost(store, ws); - const catalog = session.accessor.get(ISkillCatalog); + const catalog = session.accessor.get(ISessionSkillCatalog); await catalog.load(); expect(catalog.catalog.getSkill('first')).toBeDefined(); @@ -101,7 +101,7 @@ describe('SkillCatalogService', () => { const { stub: ws } = workspaceStub('/work'); const { host, session } = makeHost(store, ws); - const catalog = session.accessor.get(ISkillCatalog); + const catalog = session.accessor.get(ISessionSkillCatalog); await catalog.load(); store.setProjectSkills([stubSkill('second')]); diff --git a/packages/agent-core-v2/test/subagentHost/agent-tool.test.ts b/packages/agent-core-v2/test/subagentHost/agent-tool.test.ts index e21981c4b..6110241c6 100644 --- a/packages/agent-core-v2/test/subagentHost/agent-tool.test.ts +++ b/packages/agent-core-v2/test/subagentHost/agent-tool.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { IProfileService } from '#/profile'; +import { IAgentProfileService } from '#/profile'; import type { SessionSubagentHost } from '#/subagentHost'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { executeTool } from '../tools/fixtures/execute-tool'; import { createTestAgent, @@ -15,12 +15,12 @@ const signal = new AbortController().signal; describe('Agent tool service runtime', () => { describe('with a default subagent host', () => { let ctx: TestAgentContext; - let profile: IProfileService; + let profile: IAgentProfileService; beforeEach(() => { const subagentHost = createSubagentHost(); ctx = createTestAgent(subagentHostServices(subagentHost)); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Agent'] }); }); @@ -46,8 +46,8 @@ describe('Agent tool service runtime', () => { describe('with a resolving subagent host', () => { let ctx: TestAgentContext; let subagentHost: SessionSubagentHost; - let profile: IProfileService; - let tools: IToolRegistry; + let profile: IAgentProfileService; + let tools: IAgentToolRegistryService; beforeEach(() => { subagentHost = createSubagentHost({ @@ -59,8 +59,8 @@ describe('Agent tool service runtime', () => { }), }); ctx = createTestAgent(subagentHostServices(subagentHost)); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); profile.update({ activeToolNames: ['Agent'] }); }); @@ -164,14 +164,14 @@ describe('Agent tool service runtime', () => { describe('with a non-resuming subagent host', () => { let ctx: TestAgentContext; let subagentHost: SessionSubagentHost; - let profile: IProfileService; - let tools: IToolRegistry; + let profile: IAgentProfileService; + let tools: IAgentToolRegistryService; beforeEach(() => { subagentHost = createSubagentHost(); ctx = createTestAgent(subagentHostServices(subagentHost)); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); profile.update({ activeToolNames: ['Agent'] }); }); diff --git a/packages/agent-core-v2/test/swarm/swarm.test.ts b/packages/agent-core-v2/test/swarm/swarm.test.ts index 0a0c9d069..af84adb52 100644 --- a/packages/agent-core-v2/test/swarm/swarm.test.ts +++ b/packages/agent-core-v2/test/swarm/swarm.test.ts @@ -3,40 +3,40 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { SyncDescriptor } from '#/_base/di/descriptors'; import { DisposableStore, toDisposable } from '#/_base/di/lifecycle'; import { TestInstantiationService } from '#/_base/di/test'; -import { IContextMemory } from '#/contextMemory'; -import { IEventSink } from '../../src/eventSink'; -import { ISubagentHost } from '#/subagentHost'; -import { ISystemReminderService } from '#/systemReminder'; -import { SystemReminderService } from '#/systemReminder/systemReminderService'; -import { ISwarmService } from '#/swarm'; -import { SwarmService } from '#/swarm/swarmService'; -import { IToolRegistry, ToolRegistryService } from '#/toolRegistry'; -import { ITurnService } from '#/turn'; -import { IWireRecord } from '#/wireRecord'; +import { IAgentContextMemoryService } from '#/contextMemory'; +import { IAgentEventSinkService } from '../../src/eventSink'; +import { ISessionSubagentHost } from '#/subagentHost'; +import { IAgentSystemReminderService } from '#/systemReminder'; +import { AgentSystemReminderService } from '#/systemReminder/systemReminderService'; +import { IAgentSwarmService } from '#/swarm'; +import { AgentSwarmService } from '#/swarm/swarmService'; +import { IAgentToolRegistryService, AgentToolRegistryService } from '#/toolRegistry'; +import { IAgentTurnService } from '#/turn'; +import { IAgentWireRecordService } from '#/wireRecord'; import { stubContextMemory, stubWireRecord } from '../contextMemory/stubs'; import { stubTurnWithHooks } from '../turn/stubs'; -describe('SwarmService', () => { +describe('AgentSwarmService', () => { let disposables: DisposableStore; let ix: TestInstantiationService; beforeEach(() => { disposables = new DisposableStore(); ix = disposables.add(new TestInstantiationService()); - ix.stub(IContextMemory, stubContextMemory()); - ix.stub(IWireRecord, stubWireRecord()); - ix.stub(IEventSink, { emit: () => {}, on: () => toDisposable(() => {}) }); - ix.stub(ITurnService, stubTurnWithHooks()); - ix.set(IToolRegistry, new SyncDescriptor(ToolRegistryService)); - ix.stub(ISubagentHost, {}); - ix.set(ISystemReminderService, new SyncDescriptor(SystemReminderService)); - ix.set(ISwarmService, new SyncDescriptor(SwarmService)); + ix.stub(IAgentContextMemoryService, stubContextMemory()); + ix.stub(IAgentWireRecordService, stubWireRecord()); + ix.stub(IAgentEventSinkService, { emit: () => {}, on: () => toDisposable(() => {}) }); + ix.stub(IAgentTurnService, stubTurnWithHooks()); + ix.set(IAgentToolRegistryService, new SyncDescriptor(AgentToolRegistryService)); + ix.stub(ISessionSubagentHost, {}); + ix.set(IAgentSystemReminderService, new SyncDescriptor(AgentSystemReminderService)); + ix.set(IAgentSwarmService, new SyncDescriptor(AgentSwarmService)); }); afterEach(() => disposables.dispose()); it('enter / exit toggle isActive', async () => { - const swarm = ix.get(ISwarmService); + const swarm = ix.get(IAgentSwarmService); expect(swarm.isActive).toBe(false); swarm.enter('manual'); expect(swarm.isActive).toBe(true); diff --git a/packages/agent-core-v2/test/telemetry/telemetryService.test.ts b/packages/agent-core-v2/test/telemetry/telemetryService.test.ts index 57b7a4bd0..3c0db462e 100644 --- a/packages/agent-core-v2/test/telemetry/telemetryService.test.ts +++ b/packages/agent-core-v2/test/telemetry/telemetryService.test.ts @@ -209,7 +209,7 @@ describe('ITelemetryService (scoped)', () => { beforeEach(() => { _clearScopedRegistryForTests(); registerScopedService( - LifecycleScope.Core, + LifecycleScope.App, ITelemetryService, TelemetryService, InstantiationType.Eager, @@ -217,9 +217,9 @@ describe('ITelemetryService (scoped)', () => { ); }); - it('resolves from the Core scope', () => { + it('resolves from the App scope', () => { const host = createScopedTestHost(); - const svc = host.core.accessor.get(ITelemetryService); + const svc = host.app.accessor.get(ITelemetryService); expect(() => svc.track('scoped')).not.toThrow(); host.dispose(); }); diff --git a/packages/agent-core-v2/test/terminal/terminalService.test.ts b/packages/agent-core-v2/test/terminal/terminalService.test.ts index f1a560fb4..267bcb7ed 100644 --- a/packages/agent-core-v2/test/terminal/terminalService.test.ts +++ b/packages/agent-core-v2/test/terminal/terminalService.test.ts @@ -12,11 +12,11 @@ import { type TerminalFrame, type TerminalProcess, type TerminalSpawnOptions, - ITerminalBackend, - ITerminalService, + ISessionTerminalBackend, + ISessionTerminalService, } from '#/terminal'; -import { TerminalService } from '#/terminal/terminalService'; -import { IWorkspaceContext } from '#/workspaceContext'; +import { SessionTerminalService } from '#/terminal/terminalService'; +import { ISessionWorkspaceContext } from '#/workspaceContext'; class FakeTerminalProcess implements TerminalProcess { private readonly dataEmitter = new Emitter(); @@ -48,7 +48,7 @@ class FakeTerminalProcess implements TerminalProcess { } } -class FakeTerminalBackend implements ITerminalBackend { +class FakeTerminalBackend implements ISessionTerminalBackend { declare readonly _serviceBrand: undefined; readonly processes: FakeTerminalProcess[] = []; readonly lastOptions: TerminalSpawnOptions[] = []; @@ -61,7 +61,7 @@ class FakeTerminalBackend implements ITerminalBackend { } } -function stubWorkspace(workDir = '/ws'): IWorkspaceContext { +function stubWorkspace(workDir = '/ws'): ISessionWorkspaceContext { return { _serviceBrand: undefined, workDir, @@ -90,7 +90,7 @@ function collectSink(id = 'sink-1'): { sink: TerminalAttachSink; frames: Termina return { sink: { id, send: (frame) => frames.push(frame) }, frames }; } -describe('TerminalService', () => { +describe('SessionTerminalService', () => { let disposables: DisposableStore; let ix: TestInstantiationService; let backend: FakeTerminalBackend; @@ -100,9 +100,9 @@ describe('TerminalService', () => { backend = new FakeTerminalBackend(); ix = createServices(disposables, { additionalServices: (reg) => { - reg.define(ITerminalService, TerminalService); - reg.defineInstance(ITerminalBackend, backend); - reg.defineInstance(IWorkspaceContext, stubWorkspace()); + reg.define(ISessionTerminalService, SessionTerminalService); + reg.defineInstance(ISessionTerminalBackend, backend); + reg.defineInstance(ISessionWorkspaceContext, stubWorkspace()); reg.defineInstance(ISessionContext, stubSessionContext()); }, }); @@ -110,7 +110,7 @@ describe('TerminalService', () => { afterEach(() => disposables.dispose()); it('creates a terminal and resolves cwd through the workspace', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const terminal = await svc.create({ cwd: 'sub', cols: 100, rows: 40 }); expect(terminal.status).toBe('running'); @@ -123,7 +123,7 @@ describe('TerminalService', () => { }); it('uses the workspace workDir when cwd is omitted', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const terminal = await svc.create({}); expect(terminal.cwd).toBe('/ws'); expect(terminal.cols).toBe(80); @@ -131,7 +131,7 @@ describe('TerminalService', () => { }); it('lists and gets terminals', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const created = await svc.create({}); const listed = await svc.list(); expect(listed).toHaveLength(1); @@ -142,14 +142,14 @@ describe('TerminalService', () => { }); it('throws TERMINAL_NOT_FOUND for an unknown terminal', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); await expect(svc.get('nope')).rejects.toMatchObject({ code: ErrorCodes.TERMINAL_NOT_FOUND, }); }); it('attaches a sink, replays buffered frames, then streams live output', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const terminal = await svc.create({}); const proc = backend.processes[0]!; @@ -172,7 +172,7 @@ describe('TerminalService', () => { }); it('replays only frames after sinceSeq', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const terminal = await svc.create({}); const proc = backend.processes[0]!; proc.emitData('a'); @@ -186,7 +186,7 @@ describe('TerminalService', () => { }); it('emits an exit frame and marks the terminal exited on process exit', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const terminal = await svc.create({}); const proc = backend.processes[0]!; const { sink, frames } = collectSink(); @@ -206,7 +206,7 @@ describe('TerminalService', () => { }); it('delegates write and resize to the process', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const terminal = await svc.create({}); const proc = backend.processes[0]!; @@ -219,7 +219,7 @@ describe('TerminalService', () => { }); it('closes a terminal by killing the process and marking it exited', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const terminal = await svc.create({}); const proc = backend.processes[0]!; @@ -230,7 +230,7 @@ describe('TerminalService', () => { }); it('detaches a sink so it stops receiving frames', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); const terminal = await svc.create({}); const proc = backend.processes[0]!; const { sink, frames } = collectSink(); @@ -242,7 +242,7 @@ describe('TerminalService', () => { }); it('kills every live process when the service is disposed', async () => { - const svc = ix.get(ITerminalService); + const svc = ix.get(ISessionTerminalService); await svc.create({}); const proc = backend.processes[0]!; diff --git a/packages/agent-core-v2/test/tool/tool.test.ts b/packages/agent-core-v2/test/tool/tool.test.ts index 930034844..495443b75 100644 --- a/packages/agent-core-v2/test/tool/tool.test.ts +++ b/packages/agent-core-v2/test/tool/tool.test.ts @@ -4,11 +4,11 @@ import type { Kaos, KaosProcess } from '@moonshot-ai/kaos'; import type { ToolCall } from '@moonshot-ai/kosong'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { IContextMemory } from '#/contextMemory'; +import { IAgentContextMemoryService } from '#/contextMemory'; import { HookEngine } from '#/externalHooks/engine'; -import { IProfileService } from '#/profile'; +import { IAgentProfileService } from '#/profile'; import type { SessionSubagentHost } from '#/subagentHost'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import { createFakeKaos } from '../tools/fixtures/fake-kaos'; import { createCommandKaos, @@ -23,10 +23,10 @@ import { executeTool } from '../tools/fixtures/execute-tool'; const signal = new AbortController().signal; describe('Agent tools', () => { - let context: IContextMemory; + let context: IAgentContextMemoryService; let ctx: TestAgentContext; - let profile: IProfileService; - let tools: IToolRegistry; + let profile: IAgentProfileService; + let tools: IAgentToolRegistryService; afterEach(async () => { try { @@ -68,8 +68,8 @@ describe('Agent tools', () => { kaosServices(createFakeKaos({ execWithEnv })), externalHookServices(hookEngine), ); - context = ctx.get(IContextMemory); - profile = ctx.get(IProfileService); + context = ctx.get(IAgentContextMemoryService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Bash'] }); }); @@ -128,7 +128,7 @@ describe('Agent tools', () => { kaosServices(createCommandKaos('hook-output')), externalHookServices(hookEngine), ); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Bash'] }); await ctx.rpc.setPermission({ mode: 'auto' }); }); @@ -178,7 +178,7 @@ describe('Agent tools', () => { kaosServices(createFailingCommandKaos('hook-output')), externalHookServices(hookEngine), ); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Bash'] }); await ctx.rpc.setPermission({ mode: 'auto' }); }); @@ -199,7 +199,7 @@ describe('Agent tools', () => { describe('Bash tool call start event', () => { beforeEach(async () => { ctx = createTestAgent(kaosServices(createCommandKaos('ok'))); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Bash'] }); await ctx.rpc.setPermission({ mode: 'yolo' }); }); @@ -237,7 +237,7 @@ describe('Agent tools', () => { resume: vi.fn(), } as unknown as SessionSubagentHost; ctx = createTestAgent(subagentHostServices(subagentHost)); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Agent'] }); }); @@ -336,7 +336,7 @@ describe('Agent tools', () => { describe('active builtin tool set', () => { beforeEach(() => { ctx = createTestAgent(); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['Write', 'Bash'] }); }); @@ -357,8 +357,8 @@ describe('Agent tools', () => { describe('Bash background mode', () => { beforeEach(() => { ctx = createTestAgent(); - profile = ctx.get(IProfileService); - tools = ctx.get(IToolRegistry); + profile = ctx.get(IAgentProfileService); + tools = ctx.get(IAgentToolRegistryService); profile.update({ activeToolNames: ['Bash'] }); }); @@ -393,7 +393,7 @@ describe('Agent tools', () => { describe('AgentSwarm visibility', () => { beforeEach(() => { ctx = createTestAgent(); - profile = ctx.get(IProfileService); + profile = ctx.get(IAgentProfileService); profile.update({ activeToolNames: ['AgentSwarm'] }); }); diff --git a/packages/agent-core-v2/test/toolDedup/tool-dedup.test.ts b/packages/agent-core-v2/test/toolDedup/tool-dedup.test.ts index 48d7a69dc..8ef9fa619 100644 --- a/packages/agent-core-v2/test/toolDedup/tool-dedup.test.ts +++ b/packages/agent-core-v2/test/toolDedup/tool-dedup.test.ts @@ -4,13 +4,13 @@ import { DisposableStore } from '#/_base/di/lifecycle'; import { createServices } from '#/_base/di/test'; import { ITelemetryService } from '#/telemetry'; import { - IToolDedupe, - ToolDedupeService, + IAgentToolDedupeService, + AgentToolDedupeService, __testing as toolDedupTesting, } from '#/tooldedup'; import type { ToolDedupResult } from '#/tooldedup'; -import { IToolExecutor } from '#/toolExecutor'; -import { ITurnService } from '#/turn'; +import { IAgentToolExecutorService } from '#/toolExecutor'; +import { IAgentTurnService } from '#/turn'; import { recordingTelemetry, type TelemetryRecord } from '../telemetry/stubs'; import { stubToolExecutor, stubTurnWithHooks } from '../turn/stubs'; @@ -26,17 +26,17 @@ beforeEach(() => { afterEach(() => disposables.dispose()); -function createDeduper(telemetry = recordingTelemetry(telemetryEvents)): IToolDedupe { +function createDeduper(telemetry = recordingTelemetry(telemetryEvents)): IAgentToolDedupeService { const ix = createServices(disposables, { additionalServices: (reg) => { reg.defineInstance(ITelemetryService, telemetry); - reg.defineInstance(ITurnService, stubTurnWithHooks()); - reg.defineInstance(IToolExecutor, stubToolExecutor()); - reg.define(IToolDedupe, ToolDedupeService); + reg.defineInstance(IAgentTurnService, stubTurnWithHooks()); + reg.defineInstance(IAgentToolExecutorService, stubToolExecutor()); + reg.define(IAgentToolDedupeService, AgentToolDedupeService); }, strict: true, }); - return ix.get(IToolDedupe); + return ix.get(IAgentToolDedupeService); } function okResult(text: string): ToolDedupResult { @@ -53,7 +53,7 @@ function errResult(text: string): ToolDedupResult { * + finalizeResult for the original (first-occurrence) call. */ async function runOriginal( - deduper: IToolDedupe, + deduper: IAgentToolDedupeService, callId: string, tool: string, args: unknown, @@ -64,7 +64,7 @@ async function runOriginal( return deduper.finalizeResult(callId, tool, args, result); } -describe('ToolDedupeService', () => { +describe('AgentToolDedupeService', () => { describe('same-step dedup', () => { it('returns a placeholder synchronously and resolves to the real result on finalize', async () => { const dedup = createDeduper(); @@ -404,7 +404,7 @@ describe('ToolDedupeService', () => { } async function runStreak( - dedup: IToolDedupe, + dedup: IAgentToolDedupeService, count: number, ): Promise { let last: ToolDedupResult | undefined; diff --git a/packages/agent-core-v2/test/toolExecutor/tool-executor.test.ts b/packages/agent-core-v2/test/toolExecutor/tool-executor.test.ts index 6f3edf924..75227657a 100644 --- a/packages/agent-core-v2/test/toolExecutor/tool-executor.test.ts +++ b/packages/agent-core-v2/test/toolExecutor/tool-executor.test.ts @@ -6,13 +6,13 @@ import { DisposableStore } from '#/_base/di/lifecycle'; import { createServices, type TestInstantiationService } from '#/_base/di/test'; import type { LoopEvent } from '#/loop'; import { ToolAccesses, type ExecutableTool, type ExecutableToolContext, type ExecutableToolResult, type ToolExecution, type ToolResult, type ToolUpdate } from '#/tool'; -import { IToolExecutor, ToolExecutorService } from '#/toolExecutor'; -import { IToolRegistry, ToolRegistryService } from '#/toolRegistry'; +import { IAgentToolExecutorService, AgentToolExecutorService } from '#/toolExecutor'; +import { IAgentToolRegistryService, AgentToolRegistryService } from '#/toolRegistry'; let disposables: DisposableStore; let ix: TestInstantiationService; -let executor: IToolExecutor; -let registry: IToolRegistry; +let executor: IAgentToolExecutorService; +let registry: IAgentToolRegistryService; let events: LoopEvent[]; beforeEach(() => { @@ -20,20 +20,20 @@ beforeEach(() => { events = []; ix = createServices(disposables, { additionalServices: (reg) => { - reg.define(IToolRegistry, ToolRegistryService); - reg.define(IToolExecutor, ToolExecutorService); + reg.define(IAgentToolRegistryService, AgentToolRegistryService); + reg.define(IAgentToolExecutorService, AgentToolExecutorService); }, strict: true, }); - executor = ix.get(IToolExecutor); - registry = ix.get(IToolRegistry); + executor = ix.get(IAgentToolExecutorService); + registry = ix.get(IAgentToolRegistryService); }); afterEach(() => { disposables.dispose(); }); -describe('ToolExecutorService', () => { +describe('AgentToolExecutorService', () => { it('resolves by interface and routes a successful tool call through execute', async () => { const tool = new TestTool('echo'); registry.register(tool); diff --git a/packages/agent-core-v2/test/turn/stubs.ts b/packages/agent-core-v2/test/turn/stubs.ts index 39762c867..b1f888485 100644 --- a/packages/agent-core-v2/test/turn/stubs.ts +++ b/packages/agent-core-v2/test/turn/stubs.ts @@ -1,5 +1,5 @@ /** - * `turn` test stubs — shared `ITurnService` stubs for unit tests. + * `turn` test stubs — shared `IAgentTurnService` stubs for unit tests. * * Lives under `test/` (not `src/`) so test-support code stays out of the * production tree. Import from a relative path (`./stubs` or `../turn/stubs`). @@ -7,8 +7,8 @@ import { createHooks } from '#/hooks'; import type { PromptOrigin } from '#/contextMemory'; -import type { ITurnService, Turn } from '#/turn'; -import type { IToolExecutor } from '#/toolExecutor'; +import type { IAgentTurnService, Turn } from '#/turn'; +import type { IAgentToolExecutorService } from '#/toolExecutor'; export interface StubTurnOptions { /** When set, `getActiveTurn()` returns a synthetic active turn. */ @@ -19,12 +19,12 @@ export interface StubTurnOptions { } /** - * An `ITurnService` stub that also records `launch` origins and exposes the + * An `IAgentTurnService` stub that also records `launch` origins and exposes the * active turn. `prompts` / `steered` are retained as empty arrays for legacy - * assertions — the HEAD `ITurnService` has no `prompt` / `steer` methods, so + * assertions — the HEAD `IAgentTurnService` has no `prompt` / `steer` methods, so * tests that used to drive them should be rewritten against `launch` + hooks. */ -export type StubTurn = ITurnService & { +export type StubTurn = IAgentTurnService & { readonly prompts: readonly string[]; readonly steered: readonly string[]; readonly launches: readonly PromptOrigin[]; @@ -39,17 +39,17 @@ function makeTurn(id: number): Turn { }; } -function makeHooks(): ITurnService['hooks'] { +function makeHooks(): IAgentTurnService['hooks'] { return createHooks([ 'onLaunched', 'onEnded', 'beforeStep', 'afterStep', 'onContextOverflow', - ]) as ITurnService['hooks']; + ]) as IAgentTurnService['hooks']; } -/** A configurable `ITurnService` stub backed by real `OrderedHookSlot`s. */ +/** A configurable `IAgentTurnService` stub backed by real `OrderedHookSlot`s. */ export function stubTurn(options: StubTurnOptions = {}): StubTurn { const launches: PromptOrigin[] = []; let activeTurn: Turn | undefined; @@ -72,12 +72,12 @@ export function stubTurn(options: StubTurnOptions = {}): StubTurn { } /** - * An `ITurnService` stub backed by real `OrderedHookSlot`s. Use when the system + * An `IAgentTurnService` stub backed by real `OrderedHookSlot`s. Use when the system * under test registers turn-lifecycle hooks (`onLaunched` / `beforeStep` / * `afterStep`) in its constructor, or when a test needs to drive those hooks * directly. `launch` returns a minimal {@link Turn}; `getActiveTurn` is a no-op. */ -export function stubTurnWithHooks(): ITurnService { +export function stubTurnWithHooks(): IAgentTurnService { const turn = makeTurn(0); return { _serviceBrand: undefined, @@ -88,18 +88,18 @@ export function stubTurnWithHooks(): ITurnService { } /** - * An `IToolExecutor` stub whose tool-execution hooks (`onWillExecuteTool` / + * An `IAgentToolExecutorService` stub whose tool-execution hooks (`onWillExecuteTool` / * `onDidExecuteTool`) are real `OrderedHookSlot`s, so services that register - * gate hooks in their constructor (PermissionGate, McpService, …) can be built + * gate hooks in their constructor (AgentPermissionGate, AgentMcpService, …) can be built * in tests. `execute` resolves to an empty batch by default. */ -export function stubToolExecutor(): IToolExecutor { +export function stubToolExecutor(): IAgentToolExecutorService { return { _serviceBrand: undefined, execute: async () => [], hooks: createHooks([ 'onWillExecuteTool', 'onDidExecuteTool', - ]) as IToolExecutor['hooks'], + ]) as IAgentToolExecutorService['hooks'], }; } diff --git a/packages/agent-core-v2/test/turn/turn.test.ts b/packages/agent-core-v2/test/turn/turn.test.ts index 65c771f47..3b3d7c83d 100644 --- a/packages/agent-core-v2/test/turn/turn.test.ts +++ b/packages/agent-core-v2/test/turn/turn.test.ts @@ -17,21 +17,21 @@ import { import { describe, expect, it, vi } from 'vitest'; import { abortError, abortable } from '#/_base/utils/abort'; -import { IAgentFileSystem } from '#/agentFs'; +import { ISessionAgentFileSystem } from '#/agentFs'; import type { ContextMessage } from '#/contextMemory'; import { IOAuthService } from '#/auth'; import { ErrorCodes, KimiError } from '#/errors'; import { HookEngine } from '#/externalHooks/engine'; import { IKaos } from '#/kaos'; import type { ILogger as Logger, LogPayload } from '#/log'; -import { IMcpService } from '#/mcp'; +import { IAgentMcpService } from '#/mcp'; import { McpConnectionManager } from '#/mcp/connection-manager'; import { registerMediaTools, type VideoUploader } from '#/media'; -import { IPermissionGate } from '#/permissionGate'; -import { IProfileService } from '#/profile'; -import { ISwarmService } from '#/swarm'; -import { ITurnService } from '#/turn'; -import { IToolRegistry } from '#/toolRegistry'; +import { IAgentPermissionGate } from '#/permissionGate'; +import { IAgentProfileService } from '#/profile'; +import { IAgentSwarmService } from '#/swarm'; +import { IAgentTurnService } from '#/turn'; +import { IAgentToolRegistryService } from '#/toolRegistry'; import type { QueuedSubagentRunResult, QueuedSubagentTask, @@ -41,7 +41,7 @@ import { recordingTelemetry, type TelemetryRecord } from '../telemetry/stubs'; import { createFakeKaos } from '../tools/fixtures/fake-kaos'; import { configServices, - coreServices, + appServices, createCommandKaos, kaosServices, logServices, @@ -91,7 +91,7 @@ describe('Agent turn flow', () => { ); const { kaos, execWithEnv } = createExecKaos('mcp-ready'); const ctx = testAgent(mcpServices({ manager: mcp }), kaosServices(kaos)); - ctx.get(IMcpService); + ctx.get(IAgentMcpService); ctx.configure({ tools: ['Bash'] }); await ctx.rpc.setPermission({ mode: 'yolo' }); ctx.mockNextResponse( @@ -123,7 +123,7 @@ describe('Agent turn flow', () => { ); const { kaos, execWithEnv } = createExecKaos('should-not-run'); const ctx = testAgent(mcpServices({ manager: mcp }), kaosServices(kaos)); - ctx.get(IMcpService); + ctx.get(IAgentMcpService); ctx.configure({ tools: ['Bash'] }); await ctx.rpc.setPermission({ mode: 'yolo' }); ctx.mockNextResponse( @@ -365,7 +365,7 @@ describe('Agent turn flow', () => { { type: 'swarm_mode.exit' }, ]); - expect(ctx.get(ISwarmService).isActive).toBe(false); + expect(ctx.get(IAgentSwarmService).isActive).toBe(false); expect(ctx.contextData().history).toEqual([]); expect(ctx.newEvents()).toMatchInlineSnapshot(`[wire] context.splice { "start": 0, "deleteCount": 1, "messages": [], "time": "