Skip to content

fix(node-sdk): bind --agent/--agent-file profile on interactive session create (v2) - #2832

Open
SnowingFox wants to merge 3 commits into
MoonshotAI:mainfrom
SnowingFox:fix/2765-interactive-agent-tools
Open

SnowingFox wants to merge 3 commits into
MoonshotAI:mainfrom
SnowingFox:fix/2765-interactive-agent-tools

Conversation

@SnowingFox

Copy link
Copy Markdown

Fixes #2765

Problem

Agent profile frontmatter tools (allowlist) and disallowedTools (denylist)
are enforced in -p print mode but completely ignored in interactive TUI
sessions. The interactive session is created through the SDK's agent-core-v2
client, and its createSession never bound the requested startup profile —
the main agent fell back to the default profile, so the model saw the full,
unrestricted tool set regardless of the profile's tool policy.

The profile's system prompt appeared to be applied because profile text can
still influence prompt rendering, but the tool policy (activation fold +
execution guard) is driven by the bound profile's tools / disallowedTools,
which were never applied in interactive mode.

Root cause

SDKRpcClientV2.createSession (the v2 engine client used by the interactive
TUI, run-shell.ts → createKimiHarnessV2) dropped
CreateSessionOptions.agentProfile / agentFiles entirely: it created the
session with no mainAgentBinding and materializeMainAgent always bound
DEFAULT_AGENT_PROFILE_NAME. Print mode (run-v2-print.ts), by contrast,
resolves the profile name and passes it into the session's mainAgentBinding,
so the tool policy is enforced there.

Fix

packages/node-sdk/src/sdk-rpc-client-v2.ts:

  • createSession now resolves the startup profile (--agent name, or the
    --agent-file's frontmatter name, mirroring run-v2-print.ts) and passes
    it to main-agent materialization, so the interactive session binds the same
    profile (and its tool policy) as print mode.
  • materializeMainAgent accepts the optional profile and binds it instead
    of unconditionally binding the default profile; an already-bound agent is
    left alone so the explicit binding is never overwritten.

Verification

  • New regression test packages/node-sdk/test/session-agent-profile.test.ts
    creates a v2 session with agentProfile pointing at a restricted profile
    and asserts the interactive main agent binds that profile (profileName +
    activeToolNames). It fails on the previous code (main agent bound the
    default profile) and passes with the fix.
  • Run: pnpm -C packages/node-sdk exec vitest run test/session-agent-profile.test.ts

Note: unrelated to the earlier open PR #2822 (hooks index rebuild), which
touches the hooks domain of agent-core-v2.

@changeset-bot

changeset-bot Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 8aefb5b

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

@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: 7adf7e4aea

ℹ️ 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".

input.permission !== undefined
) {
const agent = await this.materializeMainAgent(handle, {
profile: agentProfileName,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Register --agent-file profiles before binding

When the TUI passes only agentFiles, this binds the parsed profile name, but SDKRpcClientV2 never registers those files with the v2 engine; the explicit profile loader reads only IBootstrapService.args.agentFiles, while this client bootstraps only skillDirs. In that context an arbitrary --agent-file profile is absent from the session catalog, so profile.bind rejects as an unknown profile and interactive --agent-file remains unusable unless the same profile is also discoverable from user/project agent dirs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Rebased onto main (fb58f81). createSession sets the session agentFiles on the bootstrap args and reloads the workspace explicit-profile loader before the bind. main no longer exposes that loader, so this adds a Program.explicitAgentProfiles getter. The test "binds an --agent-file profile that is not discoverable from user/project agent dirs" covers it.

// materialized — the same binding print mode applies via `mainAgentBinding`
// — so a profile's `tools` / `disallowedTools` policy is enforced in
// interactive sessions too, not just `-p`.
const agentProfileName = await this.resolveStartupAgentProfile(input, workDir);

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 Clean up failed startup profile binds

When a newly selected startup profile is invalid or missing, the rejection now happens after ISessionLifecycleService.create() has already returned and indexed the session, because the profile is resolved/bound in the SDK instead of inside the lifecycle create call. In that scenario createSession({ id, agentProfile: 'missing-agent' }) returns an error but leaves a live/persisted session behind, so listSessions shows a failed create and the same id cannot be reused; either validate/bind before indexing via mainAgentBinding or close/remove the handle on failure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in fb58f81. If the startup-profile bind fails, createSession now deletes the session through ISessionManager.delete before rethrowing. The new test creates with agentProfile "missing-agent" and a fixed id, then checks the session is not live or listed and that the id can be reused. The test fails with the delete removed.

…on create (v2)

Fixes MoonshotAI#2765. The v2 SDK createSession never bound the requested startup
profile, so interactive sessions ignored a profile tools/disallowedTools
policy that print mode enforces. Resolve the profile (agent files parsed
before the session exists), register --agent-file profiles with the
workspace explicit loader, bind the profile on the main agent, and delete
the session if that bind fails so a failed create leaves nothing behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: SnowingFox <[email protected]>
@SnowingFox
SnowingFox force-pushed the fix/2765-interactive-agent-tools branch from 1c8e2d1 to fb58f81 Compare October 24, 2026 14:43
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T15:20:32.165480Z 8aefb5b New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: fb58f8138b

ℹ️ 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".

agentFiles?: readonly string[];
};
if (sessionAgentFiles === undefined && hostArgs.agentFiles === undefined) return;
hostArgs.agentFiles = sessionAgentFiles;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep explicit profiles scoped to each session

When one SDKRpcClientV2 owns multiple sessions (or two createSession calls overlap), assigning the per-session list to process-global IBootstrapService.args and reloading the workspace-scoped loader lets one creation replace another live session's explicit catalog; a same-workspace second session without files removes the first session's file-only subagents, while concurrent creates can make one bind against the other's file and fail with an unknown profile. Keep these contributions session-scoped (or otherwise isolate each create) instead of mutating the shared bootstrap arguments.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 0090617. createSession now passes agentFiles to session create, which loads them into that session's own profile catalog instead of rewriting the shared bootstrap args. The new test creates two overlapping sessions with different agent files plus one without, and checks that no session sees another's profile.

@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code-sdk": patch

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 Target the changeset at the CLI package

This behavior is user-visible in apps/kimi-code because the TUI forwards agentProfile and agentFiles into this SDK path, but the changeset versions only the private @moonshot-ai/kimi-code-sdk package. The canonical changeset rule requires CLI-visible internal fixes to target @moonshot-ai/kimi-code; as written, the released CLI's bump and changelog omit this fix, so retarget the entry to the CLI package.

AGENTS.md reference: AGENTS.md:L108-L108

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Retargeted to @moonshot-ai/kimi-code with a user-facing sentence in 8aefb5b.

SnowingFox and others added 2 commits October 24, 2026 23:10
createSession no longer writes the per-session agentFiles into the shared
bootstrap args and reloads the workspace explicit loader. The files are
passed to session create, loaded there, and seeded into that session's
agent profile catalog only, so overlapping creates and other sessions in
the same workspace do not see or lose each other's profiles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: 8aefb5b930

ℹ️ 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 +1419 to +1420
agent = await this.materializeMainAgent(handle, {
profile: agentProfileName,

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 Validate startup profiles before announcing the session

When agentProfileName is unknown (or binding otherwise fails), profile binding happens here only after ISessionManager.create() has already run SessionLifecycleService.announceCreated; configured SessionStart scripts therefore execute, and the catch's normal delete() closes the handle and executes SessionEnd, even though createSession() rejects. The index/live cleanup fixes the leaked session, but hook side effects for a failed creation remain; validate or bind before the lifecycle publishes creation.

AGENTS.md reference: AGENTS.md:L124-L124

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Confirmed: a failed profile bind runs SessionStart and then SessionEnd. The bind sits after ISessionManager.create() for the same reason the existing model/thinking bind does: the SDK can only wire session events once create() returns, so moving the bind into mainAgentBinding would drop bind-time warnings (oversized AGENTS.md, unknown tool patterns). Fixing it means wiring sessions from onWillCreateSession / onDidCreateScope before the main agent exists. That changes create-time wiring for every session, and model/thinking bind failures on main already have the same ordering, so it fits better as a separate change.

sessionId: input.id,
workDir,
additionalDirs: input.additionalDirs,
agentFiles: input.agentFiles,

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 Restore session profile contributions after reopen

When a caller closes and resumes (including /reload) a session created with an agent-file-only catalog, this is the only place the SDK file list enters the lifecycle: the parsed profiles live solely in ISessionAgentProfileCatalogSeed, while doResume materializes without them and neither session metadata nor ResumeSessionOptions carries the paths. The saved main binding restores that agent's prompt/tools, but a second profile from agentFiles (or the selected profile when used as a subagent) disappears from the catalog, so ISessionSubagentService.planSpawn starts returning PROFILE_UNKNOWN after reopen; persist and reload the session contribution on every materialization.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Confirmed for additional agent-file profiles. The main agent itself keeps its profile after reopen: its prompt, active tools and disallowedTools are restored from the persisted binding snapshot. Keeping the other --agent-file profiles in the catalog across resume would mean persisting the file paths (or parsed profiles) in session metadata and loading them in doResume. Before this PR, interactive sessions never loaded agent files into the catalog, so this fits better as a separate change.

This branch has not been deployed

No deployments
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.

[Bug]: Agent profile tools/disallowedTools ignored in interactive mode (works in -p mode with KIMI_CODE_EXPERIMENTAL_FLAG=1)

1 participant