Skip to content

fix(config): allow sessions with invalid user config - #4951

Merged
sailist merged 8 commits into
bug-370-11-15-release-fixesfrom
bug-371-11-15-permission-config-read-failure-release
Nov 15, 2026
Merged

sailist merged 8 commits into
bug-370-11-15-release-fixesfrom
bug-371-11-15-permission-config-read-failure-release

Conversation

@sailist

@sailist sailist commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Users whose user config.toml is unreadable, contains malformed TOML, or has invalid sections can be blocked from creating or resuming sessions. This PR makes implicit and explicit session creation and resume continue with default or last-known-good validated config while keeping the errors visible through diagnostics.

Bug Reproduction Steps

The existing SDK scenario now covers three user-config states end to end: an invalid environment entry, an invalid default environment reference, and malformed TOML.

  1. Start an in-process v2 client with one of those config.toml files.
  2. Call KimiHarness.createSession({ workDir }) without an environmentId, then close and resume that session. Also create an explicit local session through ISessionManager with environmentId: 'local'.
  3. Before this fix, these paths can reject with config.invalid. With this PR, implicit creation, resume, and explicit-local creation all succeed. Malformed TOML retains an error diagnostic; invalid sections retain a warning diagnostic.

Root Cause

Session loading used assertValid in both readUserPermissionRules and resolveWorkspaceEnvironmentDeclarations. The permission reader was added by #4550, and the environment reader rejects implicit creation before it can fall back to the local environment. These calls reject file-level read errors and schema errors instead of using the config service's fallback behavior.

This is a fundamental fix: both readers now use ConfigService.get() directly. Initial failures produce defaults, read or schema failures on reload retain the last valid section values, and invalid sections no longer block session loading. Environment declarations use the previous valid declarations when available; without them, implicit creation falls back to local with a warning rather than failing.

Headless CLI and kap-server previously surfaced only warning diagnostics. They now surface both warning and error through their existing channels, so falling back cannot silently discard configured permission policy.

Code Changes

  • Remove session-blocking assertValid calls from permission-rule and environment-declaration readers; rely on the config service's validated effective values.
  • Preserve the previous valid section value when schema validation fails on reload. Initial failures still use defaults, and valid permission rules are not discarded by a later invalid entry.
  • Preserve project .kimi-code/local.toml semantics and the block on persisting user config while it cannot be read or parsed.
  • Surface both warning and error diagnostics in headless CLI and through kap-server's existing config-warning event, without changing its wire shape.
  • Extend existing config, permission, SDK, CLI, and kap-server tests without increasing the test count. The SDK scenario exercises implicit creation, close, resume, and explicit-local creation for all three config states.
  • Document recovery and the possibility that implicit creation without valid remote declarations falls back to local, in English and Chinese, and add a patch changeset.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
User config cannot be read or parsed on initial load Session creation and resume can reject with config.invalid Implicit and explicit sessions continue with default validated config and retain error diagnostics Users with damaged configs who could not open sessions Repair the file to restore configured values; headless diagnostics remain visible
A previously valid config becomes unreadable or schema-invalid on reload Permission rules or environment declarations can be rejected or dropped The previous valid section value remains active Running clients that externally edit or replace their config Fix and reload the file to adopt new values
Implicit creation has no valid remote declarations Environment validation can reject, or the entire invalid section can disappear without a visible warning Sessions continue with a warning; previous valid declarations are preferred, otherwise the local environment is used Users who expected a configured remote but have no valid declaration Fix the remote declaration; diagnostics and the environment docs explicitly warn that commands may run locally
Headless CLI and kap-server receive config diagnostics Only warning diagnostics are surfaced Both warning and error diagnostics are surfaced through existing channels Headless users whose configured permission policy may be unavailable N/A
Project .kimi-code/local.toml is invalid Existing project-local validation rejects Unchanged Users relying on strict project-local validation N/A
User config is persisted while unreadable or malformed Existing persistence guard rejects Unchanged Users whose config must not be overwritten after a read failure Repair the file before writing

Affected modules and coverage:

  • agent-core-v2: config and permission tests passed, 126/126, including last-valid-section recovery after schema failure.
  • node-sdk: all three config-state scenarios passed for implicit creation, close, resume, and explicit-local creation.
  • Headless CLI: 34/34 tests passed, including warning and error output.
  • kap-server: 76/76 tests passed across config and event broadcasting, including real error-diagnostic publication on reload.
  • agent-core-v2 and kap-server package typecheck passed; scoped type-aware oxlint reported zero errors on the changed source and test files.
  • English and Chinese docs were updated; the VitePress build passed.
  • An earlier full local SDK run passed 104/105 tests. The remaining suggestFiles assertion concerns .gitignore filtering, does not exercise config recovery, and was not changed by this PR.
  • Full CI passed on earlier PR heads; the latest head runs the same workflows.

Checklist

  • I have read the CONTRIBUTING document.
  • No issue is linked; this internal PR describes the regression and reproduction above.
  • I have added test coverage that proves the fix works.
  • The behavior-change table above is complete, and the recovery and diagnostic behavior are named in the changeset.
  • Added a patch changeset.
  • Updated the English and Chinese configuration docs and verified the docs build.

@changeset-bot

changeset-bot Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c660a12

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 commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T06:36:58.096667Z c660a12 Manual request
ℹ️ 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 15, 2026 •

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

commit: c660a12

@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: 2f956d2f36

ℹ️ 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 thread docs/en/configuration/config-files.md Outdated

User rules are loaded from the user `config.toml` at session startup. For compatibility, legacy `turn-override` and `session-runtime` rules in the user config are silently ignored without a warning.

If the user `config.toml` cannot be read or parsed, sessions continue with no user rules on initial load or the last-known-good rules after a reload, and the error remains visible in config diagnostics. Invalid permission rules still block session startup, and config writes remain blocked until the file is readable again.

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 Qualify which sessions survive an unreadable config

This promise is broader than the implemented behavior: when callers omit environmentId—including the normal KimiHarness.createSession({ workDir }) path—the environment declaration reader still calls assertValid(ENVIRONMENTS_SECTION) without the new tolerance and rejects with config.invalid. The changed SDK test explicitly preserves that rejection at packages/node-sdk/test/sdk-rpc-client-v2.test.ts:342-360; only an explicit environmentId: 'local' session and resume are demonstrated to continue. Please either extend the recovery to ordinary implicit-local creation or document the explicit-local limitation here and in the changeset.

Useful? React with 👍 / 👎.

@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: 3df2c7dda0

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


export function readUserPermissionRules(config: IConfigService): readonly PermissionRule[] {
config.assertValid(PERMISSION_SECTION);
config.assertValid(PERMISSION_SECTION, { tolerateReadError: true });

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 Surface config errors before ignoring permission rules

When config.toml is unreadable or malformed, this tolerance lets explicit-local sessions continue without the configured user permission rules. For kimi --print --environment local, only warning diagnostics are written (apps/kimi-code/src/cli/v2/run-v2-print.ts:188-192), and kap-server likewise publishes only warnings (packages/kap-server/src/start.ts:416-424); because the read failure is an error, neither headless path signals that custom deny/ask policy was discarded, potentially allowing actions under a weaker policy. Surface the tolerated error before these paths continue.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

@sailist sailist changed the title fix(agent-core-v2): tolerate config read failures for permission rules fix(config): allow sessions with invalid user config Nov 15, 2026

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

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

): Promise<EnvironmentDeclarationSet> {
await config.ready;
config.assertValid(ENVIRONMENTS_SECTION);
const user = config.get<EnvironmentsSection | undefined>(ENVIRONMENTS_SECTION);

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 rejecting invalid implicit environment configs

When an implicit SDK session is created with an invalid [environments] section—such as default = "missing" or one incomplete declaration—ConfigService omits the entire invalid section, so this lookup returns no declarations and SessionManagerService.openCreation silently selects the local host. The changed test at packages/node-sdk/test/sdk-rpc-client-v2.test.ts:326-363 now explicitly accepts this path, whereas the parent returned config.invalid; callers expecting the configured remote can therefore execute commands locally, and createSession does not surface the diagnostic unless the SDK consumer separately requests it. Preserve validation for implicit resolution and limit recovery to explicitly local sessions or another fail-safe path.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.


export function readUserPermissionRules(config: IConfigService): readonly PermissionRule[] {
config.assertValid(PERMISSION_SECTION);
const rules = config.get<PermissionConfig | undefined>(PERMISSION_SECTION)?.rules ?? [];

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 Retain valid permission rules when one entry is invalid

If a valid permission configuration containing deny rules is reloaded with one schema-invalid entry, ConfigService.buildValidated drops the whole section and this getter now returns an empty rule set instead of failing closed. Because running agents evaluate this getter dynamically, their previously active user restrictions disappear immediately and an action can proceed under the weaker defaults; this also contradicts the new documentation's promise to use the last-known-good validated configuration. Retain the last valid permission section on validation failure, or continue rejecting permission-rule use until it is repaired.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +441 to 442
if (configService.diagnostics().length > 0) {
publishConfigWarnings(configService.diagnostics());

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 Replay startup config errors to kap-server clients

When kap-server starts with an unreadable or malformed config.toml, this callback publishes the diagnostic before listenWithPortRetry makes the WebSocket endpoint available, so SessionEventBroadcaster.sendGlobal has no targets and discards the event; it neither stores nor replays global config warnings when a target is later added. Consequently desktop/web clients never receive the advertised error while sessions continue without the configured permission policy. Fresh evidence beyond the prior comment is the current broadcaster behavior at sessionEventBroadcaster.ts:189-191,685-712, together with the new test covering only a reload after the server and subscriber are already active. Cache the current diagnostics for new connections or publish them as part of connection setup.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

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

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

): void {
const previous = this.effective;
this.validated = this.buildValidated(this.raw);
this.validated = this.buildValidated(this.raw, this.validated);

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 Preserve the seeded config after an initial read failure

When seedInitialLoad() successfully reads a valid file but the subsequent asynchronous load('load') fails—for example, because the file is replaced or becomes malformed between the two reads—fileData remains {} and this rebuild discards every seeded section. Passing this.validated does not help because buildValidated() only retains previous values for domains present in raw; with an empty raw, sessions now continue using defaults, potentially losing configured permission rules or a remote default despite having already obtained a valid snapshot. Preserve the seeded raw/effective values on this initial-error path just as reload errors do.

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

Useful? React with 👍 / 👎.

@sailist

sailist commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: c660a12655

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

@sailist
sailist merged commit 813608e into bug-370-11-15-release-fixes Nov 15, 2026
15 checks passed
@sailist
sailist deleted the bug-371-11-15-permission-config-read-failure-release branch November 15, 2026 06:39
sailist added a commit that referenced this pull request Nov 16, 2026
* fix(agent-core-v2): tolerate config read failures for permission rules

* chore: add changeset for permission config recovery

* docs: document permission config recovery

* docs: qualify permission config recovery scope

* fix(config): surface read error diagnostics

* fix(config): allow sessions with invalid user config

* fix(config): preserve valid values and replay diagnostics

* fix(config): remove startup diagnostic replay
wbxl2000 pushed a commit that referenced this pull request Nov 17, 2026
* fix: resume sessions with removed default models (#4982)

* fix(node-sdk): resume sessions with missing default model

* fix(cli): check auth for the resumed session model

* chore: add changeset for unavailable model recovery

* fix(agent-core-v2): stop rebuilding mismatched session indexes (#4980)

* fix(agent-core-v2): reject repeated model responses (#4977)

* fix(agent-core-v2): reject repeated model responses

* chore: add changeset for repeated model responses

---------

Co-authored-by: 7Sageer <[email protected]>

* fix(agent-core-v2): inline deferred tools without dynamic loading (#4971)

* fix(agent-core-v2): record restored task notifications without model requests (#4949) (#4989)

* fix(agent-core-v2): record restored task notifications without model requests

- queue restored task notifications as prompt-only turns after loop initialization
- preserve interrupted and queued turns during resume and fork
- complete reconciliation before initialization and reset return to keep Wire reads ordered
- run loop and container cleanup when reconciliation fails
- surface restored notification persistence failures

* chore: add changeset for restored task notifications

* fix(agent-core-v2): restore overflow recovery after LLM retries (#4950) (#4990)

* fix(agent-core-v2): restore step state after LLM retries

* test(agent-core-v2): scope retry event to overflow regression

* fix(config): allow sessions with invalid user config (#4951) (#4991)

* fix(agent-core-v2): tolerate config read failures for permission rules

* chore: add changeset for permission config recovery

* docs: document permission config recovery

* docs: qualify permission config recovery scope

* fix(config): surface read error diagnostics

* fix(config): allow sessions with invalid user config

* fix(config): preserve valid values and replay diagnostics

* fix(config): remove startup diagnostic replay

* fix(agent-core-v2): ignore non-user prompts during Tower wake (#4952) (#4992)

* fix(agent-core-v2): ignore non-user prompts during Tower wake

* chore: add Tower notification fix changeset

* fix(agent-core-v2): preserve slash prompts during Tower wake

* fix(agent-core-v2): route foreground shell events by origin (#4954) (#4994)

* fix(agent-core-v2): route foreground shell events by origin

* test(agent-core-v2): expect tool event origins in snapshots

* fix(klient): accept tool events from pre-origin hosts

* fix(agent-core-v2): run external Stop hooks after turn completion (#4956) (#4995)

* fix(agent-core-v2): run external Stop hooks after turn completion

* chore: add changeset for external Stop hooks

* docs: clarify post-turn Stop hook timing

* fix(agent-core-v2): wait for subagent quiescence (#4953) (#4993)

* fix(agent-core-v2): reject incomplete model streams (#5006)

* fix(agent-core-v2): preserve choice-level OpenAI token usage (#5017)

* fix(capability): confirm stopping WebBridge before Windows updates (#4999)

* fix(capability): confirm stopping WebBridge before Windows updates

* fix(capability): harden WebBridge update recovery

* fix(capability): restore WebBridge after startup failure

* fix(capability): wait for WebBridge process exit

* fix(capability): handle WebBridge confirmation edge cases

---------

Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>

* chore: sync release 2.6.3 back to main

* chore: finish release 2.6.3 backsync

* chore: sync node-sdk lockfile importer

* fix(sdk): preserve main core type dependencies

* fix: complete release 2.6.3 backsync

---------

Co-authored-by: Haozhe <[email protected]>
Co-authored-by: 7Sageer <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
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