Skip to content

refactor(agent-core-v2): split agent lifecycle into existence, subagent, and session MCP domains - #1624

Merged
kermanx merged 6 commits into
mainfrom
refactor/v2-agent-lifecycle-split
Jul 14, 2026
Merged

refactor(agent-core-v2): split agent lifecycle into existence, subagent, and session MCP domains#1624
kermanx merged 6 commits into
mainfrom
refactor/v2-agent-lifecycle-split

Conversation

@kermanx

@kermanx kermanx commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

Related Issue

No linked issue — internal refactor plus a crash fix; the problem is explained below.

Problem

  • Sending /goal <text> on the web's new-conversation page crashed the v2 backend process. A fire-and-forget GET /status started main-agent creation, and the subsequent POST /profile / POST /prompts calls received the not-yet-ready agent handle (registered before markReady()). Enqueueing the prompt then hit activity.begin while the lane was still initializing, and the coded error escaped the fire-and-forget prompt scheduler as an unhandled rejection that killed the process.
  • IAgentLifecycleService had become a 500-line grab bag: registry, creation pipeline, agent runs, the session MCP subsystem, and main-only events all lived in one service.

What changed

  • create() is now create-or-get for explicit ids: a concurrent in-flight creation is joined (never a duplicate scope) and an already-created agent is returned as-is, so the main-agent bootstrap can no longer race the first prompt. This removes the crash at its root.
  • The interface is converged to agent existence only: create / fork / get / list / remove + onDidCreate / onDidDispose.
  • New subagent domain (ISessionSubagentService): run() plus the SubagentStart/SubagentStop hook surface, with runAgentTurn / mirrorAgentRun / the Agent tool moved under session/subagent/.
  • New session/mcp domain (ISessionMcpService): the session-wide shared MCP connection manager, initial connect, and telemetry.
  • Removed onDidCreateMain / notifyMainCreated: subscribers filter onDidCreate by id and AgentPluginService self-gates on main; ensureMainAgent stays as a thin helper over create({ agentId: MAIN_AGENT_ID }).
  • Slimmed the agent scope seed to only IAgentScopeContext: a new AgentWireService adapter derives its log addressing, and AgentMcpService resolves the session manager and originals dir itself. The default permission mode is now applied in bindBootstrap.
  • Removed a dead MCP-startup-failure event bridge: it could only fire before the main agent existed, so nothing ever consumed it (no behavior change; the failure is still logged).

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue, or explained the problem above.
  • I have added tests that prove my feature works: create-or-get concurrency/idempotence tests plus migration of every affected test; agent-core-v2 suite (3185 tests) and kap-server suite (552 tests) pass, and typecheck / domain-layer lint are green.
  • Ran gen-changesets skill (@moonshot-ai/kimi-code: patch).
  • This PR needs no doc update (experimental v2 engine internals plus a crash fix).

kermanx added 2 commits July 13, 2026 21:36
…nt, and session MCP domains

Converge IAgentLifecycleService to agent existence only (create / fork /
get / list / remove + onDidCreate / onDidDispose):

- create() is create-or-get for explicit ids: concurrent in-flight
  creations join and an existing agent is returned as-is, so the main
  agent bootstrap can no longer race the first prompt (the web /goal
  crash: a prompt enqueued while the agent lane was still initializing
  killed the process as an unhandled rejection).
- Extract the subagent domain (ISessionSubagentService): run() plus the
  SubagentStart/SubagentStop hook surface, with runAgentTurn /
  mirrorAgentRun / the Agent tool moved under session/subagent/.
- Extract the session MCP domain (ISessionMcpService): the session-wide
  connection manager, initial connect, and telemetry.
- Delete onDidCreateMain / notifyMainCreated: subscribers filter
  onDidCreate by id, and AgentPluginService self-gates on main. The
  ensureMainAgent helper stays as a thin wrapper over
  create({ agentId: MAIN_AGENT_ID }).
- Slim the agent scope seed to IAgentScopeContext: add the AgentWireService
  adapter (derives its log addressing) and let AgentMcpService resolve the
  session manager and originals dir itself. The default permission mode is
  applied in bindBootstrap.
- Migrate callers in kap-server / kimi-code and all affected tests.
@changeset-bot

changeset-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 067ad42

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Jul 13, 2026

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@067ad42
npx https://pkg.pr.new/@moonshot-ai/kimi-code@067ad42

commit: 067ad42

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b7428b5e2a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +134 to +136
// Create-or-get for explicit ids: join a concurrent in-flight creation or
// return the existing agent, so callers never see a duplicate scope or a
// not-yet-ready handle. Auto-minted ids always create fresh.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Move inline comments to module headers

packages/agent-core-v2/AGENTS.md requires: "Comments live solely in the top-of-file /** */ block — never beside functions, methods, or statements." This added method-body explanation, along with similar new inline comments in this file, leaves the v2 package out of conformance; please move the durable rationale into the file header or remove the inline narration.

Useful? React with 👍 / 👎.

kermanx added 4 commits July 13, 2026 21:57
…eation

Subagent dispatchers (the Agent tool, AgentSwarm, and /init) now set the
inherited permission mode on the child themselves after creation,
keeping the dispatch posture out of the creation primitive. Fresh
agents still start from the configured defaultPermissionMode.
…ecycle-split

# Conflicts:
#	packages/agent-core-v2/src/session/agentLifecycle/agentLifecycle.ts
#	packages/agent-core-v2/src/session/agentLifecycle/agentLifecycleService.ts
#	packages/agent-core-v2/src/session/agentLifecycle/mainAgent.ts
#	packages/agent-core-v2/test/app/gateway/gateway.test.ts
#	packages/agent-core-v2/test/app/messageLegacy/messageLegacy.test.ts
#	packages/agent-core-v2/test/app/sessionExport/sessionExport.test.ts
#	packages/agent-core-v2/test/app/sessionLifecycle/sessionLifecycle.test.ts
#	packages/agent-core-v2/test/session/agentLifecycle/agentLifecycle.test.ts
#	packages/agent-core-v2/test/session/sessionActivity/sessionActivity.test.ts
#	packages/agent-core-v2/test/session/swarm/sessionSwarm.test.ts
#	packages/agent-core-v2/test/session/todo/sessionTodo.test.ts
#	packages/agent-core-v2/test/session/workspaceCommand/workspaceCommand.test.ts
#	packages/agent-core-v2/test/tool/tool.test.ts
…drain idle constructions before scope ready

- wireRecordService.restore() synthesizes and prepends a current-version
  metadata envelope when the log lacks one, replacing the lifecycle-layer
  ensureWireMetadata; metadataRecord() in metadataOps is the single shared
  factory (restore healing + fork-time log copies).
- InstantiationService tracks pending GlobalIdleValue constructions on the
  root container and exposes drainIdle(); doCreate drains them before
  markReady() so delayed services' constructor side effects (event
  subscriptions, journal registration) are live before the agent admits
  turns, with no reliance on incidental macrotask windows.
…ecycle-split

# Conflicts:
#	packages/agent-core-v2/scripts/dep-graph/analyzer/analyze.ts
#	packages/agent-core-v2/src/agent/wireRecord/wireRecordService.ts
#	packages/agent-core-v2/src/app/sessionLifecycle/sessionLifecycleService.ts
#	packages/agent-core-v2/src/persistence/backends/node-fs/appendLogStore.ts
#	packages/agent-core-v2/src/session/agentLifecycle/agentLifecycle.ts
#	packages/agent-core-v2/src/session/agentLifecycle/agentLifecycleService.ts
#	packages/agent-core-v2/src/session/agentLifecycle/mainAgent.ts
#	packages/agent-core-v2/src/session/subagent/tools/agent.ts
#	packages/agent-core-v2/src/session/todo/sessionTodoService.ts
#	packages/agent-core-v2/test/persistence/backends/node-fs/appendLogStore.test.ts
#	packages/agent-core-v2/test/session/agentLifecycle/agentLifecycle.test.ts
@kermanx

kermanx commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

@codex

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 067ad42faf

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@kermanx
kermanx merged commit 3215129 into main Jul 14, 2026
14 checks passed
@kermanx
kermanx deleted the refactor/v2-agent-lifecycle-split branch July 14, 2026 06:13
@github-actions github-actions Bot mentioned this pull request Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant