Repository navigation
fix(node-sdk): bind --agent/--agent-file profile on interactive session create (v2) - #2832
SnowingFox wants to merge 3 commits into
Conversation
🦋 Changeset detectedLatest commit: 8aefb5b The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
There was a problem hiding this comment.
💡 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, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]>
1c8e2d1 to
fb58f81
Compare
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Retargeted to @moonshot-ai/kimi-code with a user-facing sentence in 8aefb5b.
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 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".
| agent = await this.materializeMainAgent(handle, { | ||
| profile: agentProfileName, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
Fixes #2765
Problem
Agent profile frontmatter
tools(allowlist) anddisallowedTools(denylist)are enforced in
-pprint mode but completely ignored in interactive TUIsessions. The interactive session is created through the SDK's agent-core-v2
client, and its
createSessionnever 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 interactiveTUI,
run-shell.ts→createKimiHarnessV2) droppedCreateSessionOptions.agentProfile/agentFilesentirely: it created thesession with no
mainAgentBindingandmaterializeMainAgentalways boundDEFAULT_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:createSessionnow resolves the startup profile (--agentname, or the--agent-file's frontmattername, mirroringrun-v2-print.ts) and passesit to main-agent materialization, so the interactive session binds the same
profile (and its tool policy) as print mode.
materializeMainAgentaccepts the optionalprofileand binds it insteadof unconditionally binding the default profile; an already-bound agent is
left alone so the explicit binding is never overwritten.
Verification
packages/node-sdk/test/session-agent-profile.test.tscreates a v2 session with
agentProfilepointing at a restricted profileand asserts the interactive main agent binds that profile (
profileName+activeToolNames). It fails on the previous code (main agent bound thedefault profile) and passes with the fix.
pnpm -C packages/node-sdk exec vitest run test/session-agent-profile.test.tsNote: unrelated to the earlier open PR #2822 (hooks index rebuild), which
touches the hooks domain of agent-core-v2.