Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/skills/agent-core-dev/edge-exposure.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ Read = `GET`, write = `POST`. `sid` = `session_id`, `aid` = `agent_id`.
| `tasks` | `list` / `get` / `readOutput` | IBackgroundService.* | GET |
| `tasks` | `stop` / `detach` | IBackgroundService.* | POST |
| `usage` | `status` | IUsageService.status | GET |
| `context` | `status` | IAgentContextSizeService.get | GET |
| `context` | `status` | IAgentTokenCountingService.get | GET |
| `swarm` | `isActive` | ISwarmService.isActive | GET |
| `swarm` | `enter` / `exit` | ISwarmService.* | POST |
| `permission` | `getMode` | IPermissionModeService.mode | GET |
Expand Down
5 changes: 5 additions & 0 deletions .changeset/tidy-llamas-attend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---

Fix the context window limit showing as 0 in session status updates when no model is bound yet or the configured model no longer resolves; the limit now falls back to the default model or is omitted when unknown.
5 changes: 5 additions & 0 deletions .changeset/token-counting-reporting-edge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": minor
---

The `[token_counting]` strategy now only selects the reported context size: `estimated` keeps provider-reported usage out of the context-size display, and `measured` no longer gets stuck retrying an oversized compaction request until it fails.
5 changes: 5 additions & 0 deletions .changeset/token-counting-strategy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---

Add a `[token_counting]` config section to choose how context token counts are derived: `measured+estimated` (default), `measured` (provider usage only), or `estimated` (heuristic only, for providers without usage reporting). Set `strategy` under `[token_counting]` in config.toml (or `KIMI_TOKEN_COUNTING_STRATEGY`) to switch.
6 changes: 3 additions & 3 deletions apps/kimi-inspect/src/panels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
*/

import { IAgentActivityView } from '@moonshot-ai/agent-core-v2/agent/activityView/activityView';
import { IAgentContextSizeService } from '@moonshot-ai/agent-core-v2/agent/contextSize/contextSize';
import { IAgentGoalService } from '@moonshot-ai/agent-core-v2/agent/goal/goal';
import { IAgentMcpService } from '@moonshot-ai/agent-core-v2/agent/mcp/mcp';
import { IAgentPermissionModeService } from '@moonshot-ai/agent-core-v2/agent/permissionMode/permissionMode';
Expand All @@ -27,6 +26,7 @@ import { IAgentProfileService } from '@moonshot-ai/agent-core-v2/agent/profile/p
import { IAgentRPCService } from '@moonshot-ai/agent-core-v2/agent/rpc/rpc';
import { IAgentSwarmService } from '@moonshot-ai/agent-core-v2/agent/swarm/swarm';
import { IAgentTaskService } from '@moonshot-ai/agent-core-v2/agent/task/task';
import { IAgentTokenCountingService } from '@moonshot-ai/agent-core-v2/agent/tokenCounting/tokenCounting';
import { IAgentToolRegistryService } from '@moonshot-ai/agent-core-v2/agent/toolRegistry/toolRegistry';
import { IAgentUsageService } from '@moonshot-ai/agent-core-v2/agent/usage/usage';
import { IAuthSummaryService } from '@moonshot-ai/agent-core-v2/app/auth/auth';
Expand Down Expand Up @@ -179,8 +179,8 @@ export const AGENT_PANELS: readonly ServicePanelDef[] = [
fetch: (svc) => call(svc, 'status'),
},
{
id: String(IAgentContextSizeService),
label: 'AgentContextSizeService',
id: String(IAgentTokenCountingService),
label: 'AgentTokenCountingService',
scope: 'agent',
fetch: (svc) => call(svc, 'get'),
},
Expand Down
10 changes: 10 additions & 0 deletions docs/en/configuration/config-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,16 @@ When the experiment is enabled, the configuration is validated as the session st

Retries only apply to transient failures — connection errors, timeouts, HTTP 429 rate limits, and 5xx server errors. A 429 caused by an exhausted quota or insufficient account balance is not retried and fails immediately, since it cannot succeed until the account is recharged.

## `token_counting`

`token_counting` selects which context token count is reported externally — the value behind the context-size display. Internal logic (automatic compaction triggers, budgets, and overflow backoff) always uses both provider-reported usage and estimates, regardless of this setting.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `strategy` | `"measured+estimated" \| "measured" \| "estimated"` | `"measured+estimated"` | `measured+estimated` reports the live size — the provider-reported usage of each exchange plus an estimate of the not-yet-measured tail — floored by the last measured total; `measured` reports provider usage alone, so the display only moves when an exchange completes; `estimated` reports a pure estimate with provider usage ignored — the fallback for providers that do not report usage or report it unreliably |

`strategy` can be overridden by the `KIMI_TOKEN_COUNTING_STRATEGY` environment variable, which takes higher priority than `config.toml`.

## `background`

`background` controls the concurrency behavior of background tasks (launched via the `Bash` tool or the `Agent` tool's `run_in_background=true` parameter).
Expand Down
1 change: 1 addition & 0 deletions docs/en/configuration/env-vars.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ Switches that control the behavior of subsystems such as telemetry, background t
| `KIMI_MCP_TOOL_TIMEOUT_MS` | Global default single tool-call timeout (ms) for all MCP servers; takes higher priority than `[mcp] tool_timeout_ms` in `config.toml`, but a per-server `toolTimeoutMs` in `mcp.json` still wins (default `60000`) | Integer from `1` to `2147483647`; invalid values are ignored |
| `KIMI_LOOP_MAX_STEPS_PER_TURN` | Maximum Agent steps per turn; takes higher priority than `[loop_control] max_steps_per_turn` in `config.toml` (unset or `0` means unlimited) | Non-negative integer; invalid values are ignored |
| `KIMI_LOOP_MAX_ATTEMPTS_PER_STEP` | Maximum total attempts for a failing step (including the initial attempt); takes higher priority than `[loop_control] max_attempts_per_step` in `config.toml` (default `10`). The deprecated `KIMI_LOOP_MAX_RETRIES_PER_STEP` is still honored with a warning when this variable is unset | Non-negative integer; invalid values are ignored |
| `KIMI_TOKEN_COUNTING_STRATEGY` | Which context token count is reported externally (the context-size display); takes higher priority than `[token_counting] strategy` in `config.toml` (default `measured+estimated`) | `measured+estimated`, `measured`, `estimated` (case-insensitive); invalid values are ignored |
| `KIMI_WEB_SEARCH_BASE_URL` | API URL of the web search (`WebSearch`) service; takes higher priority than `[services.moonshot_search] base_url` in `config.toml`, and enables the service without that config section. Persisted credentials and custom headers are not forwarded to an env-selected endpoint | Non-blank string; blank values are ignored |
| `KIMI_WEB_SEARCH_API_KEY` | API key of the web search (`WebSearch`) service; replaces both the configured API key and OAuth credential when set | Non-blank string; blank values are ignored |
| `KIMI_WEB_FETCH_BASE_URL` | API URL of the web fetch (`FetchURL`) service; takes higher priority than `[services.moonshot_fetch] base_url`. Persisted credentials and custom headers are not forwarded to an env-selected endpoint. Without an env or config endpoint, signed-in users try the managed Kimi OAuth fetch service before direct local requests | Non-blank string; blank values are ignored |
Expand Down
10 changes: 10 additions & 0 deletions docs/zh/configuration/config-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,16 @@ max_output_size = 8192

重试仅针对瞬时故障——连接错误、超时、HTTP 429 限流和 5xx 服务端错误。账户额度耗尽或余额不足导致的 429 不会重试,会立即失败:在充值之前重试不可能成功。

## `token_counting`

`token_counting` 决定对外上报的上下文 token 计数——即上下文大小显示所基于的值。内部逻辑(自动压缩触发、预算、超限退避)始终同时使用供应商实测与估算,不受本配置影响。

| 字段 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `strategy` | `"measured+estimated" \| "measured" \| "estimated"` | `"measured+estimated"` | `measured+estimated` 上报实时大小——每次请求的供应商实测用量加上未实测尾部的估算——并以最近一次实测总量兜底;`measured` 只上报供应商实测,显示仅在每次请求完成后变化;`estimated` 忽略供应商实测、上报纯估算——适用于不上报用量或用量不可信的供应商 |

`strategy` 可被环境变量 `KIMI_TOKEN_COUNTING_STRATEGY` 覆盖,优先级高于 `config.toml`。

## `background`

`background` 控制后台任务(通过 `Bash` 工具或 `Agent` 工具的 `run_in_background=true` 参数启动)的并发数。
Expand Down
1 change: 1 addition & 0 deletions docs/zh/configuration/env-vars.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ kimi
| `KIMI_MCP_TOOL_TIMEOUT_MS` | 所有 MCP server 的全局默认单次工具调用超时(毫秒);优先级高于 `config.toml` 的 `[mcp] tool_timeout_ms`,但低于 `mcp.json` 中单个 server 的 `toolTimeoutMs`(默认 `60000`) | `1` 到 `2147483647` 的整数;非法值被忽略 |
| `KIMI_LOOP_MAX_STEPS_PER_TURN` | Agent 单轮最大步数;优先级高于 `config.toml` 的 `[loop_control] max_steps_per_turn`(不设或 `0` 表示无上限) | 非负整数;非法值被忽略 |
| `KIMI_LOOP_MAX_ATTEMPTS_PER_STEP` | 单步失败后的最大总尝试次数(含首次尝试);优先级高于 `config.toml` 的 `[loop_control] max_attempts_per_step`(默认 `10`)。旧的 `KIMI_LOOP_MAX_RETRIES_PER_STEP` 已废弃,但在本变量未设置时仍生效并给出警告 | 非负整数;非法值被忽略 |
| `KIMI_TOKEN_COUNTING_STRATEGY` | 对外上报的上下文 token 计数(上下文大小显示);优先级高于 `config.toml` 的 `[token_counting] strategy`(默认 `measured+estimated`) | `measured+estimated`、`measured`、`estimated`(不区分大小写);非法值被忽略 |
| `KIMI_WEB_SEARCH_BASE_URL` | 网页搜索(`WebSearch`)服务的 API URL;优先级高于 `config.toml` 的 `[services.moonshot_search] base_url`,未写配置段时也可启用服务。文件中持久化的凭据和自定义 header 不会发送到环境变量指定的端点 | 非空字符串;空白值被忽略 |
| `KIMI_WEB_SEARCH_API_KEY` | 网页搜索(`WebSearch`)服务的 API 密钥;设置后同时替换配置中的 API 密钥和 OAuth 凭据 | 非空字符串;空白值被忽略 |
| `KIMI_WEB_FETCH_BASE_URL` | 网页抓取(`FetchURL`)服务的 API URL;优先级高于 `[services.moonshot_fetch] base_url`。文件中持久化的凭据和自定义 header 不会发送到环境变量指定的端点。环境变量和配置都没有指定端点时,已登录用户会先尝试 Kimi OAuth 托管抓取服务,再回退到本地直接请求 | 非空字符串;空白值被忽略 |
Expand Down
15 changes: 14 additions & 1 deletion packages/agent-core-v2/docs/config-manifest.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# commented "# field: type" lines describe the remaining schema fields.
# Values resolve as: default -> config.toml -> env overlay -> memory.

# Index (22 sections · 3 overlay(s))
# Index (23 sections · 3 overlay(s))
# background src/agent/task/configSection.ts
# cron src/app/cron/configSection.ts
# defaultPermissionMode src/agent/permissionMode/configSection.ts
Expand All @@ -30,6 +30,7 @@
# subagent src/session/subagent/configSection.ts
# task src/agent/task/configSection.ts
# thinking src/app/kosongConfig/configSection.ts
# tokenCounting src/agent/tokenCounting/configSection.ts
# tools src/agent/toolPolicy/configSection.ts
# (overlay) servicesCredentialEnvOverlay src/app/auth/configSection.ts
# (overlay) kimiModelEnvOverlay src/app/kosongConfig/envOverlay.ts
Expand Down Expand Up @@ -390,6 +391,18 @@ timeout_ms = 7200000
# forced_effort: string
# keep: string

# ##########################################################################
# tokenCounting (config.toml: token_counting)
# owner: src/agent/tokenCounting/configSection.ts
# scope: core
# hooks: stripEnv
# env:
# strategy <- KIMI_TOKEN_COUNTING_STRATEGY (custom parse)
# ##########################################################################

[token_counting]
strategy = "measured+estimated"

# ##########################################################################
# tools
# owner: src/agent/toolPolicy/configSection.ts
Expand Down
5 changes: 1 addition & 4 deletions packages/agent-core-v2/docs/state-manifest.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
// references become '(circular)', and class instances collapse to a '(ClassName)'
// marker — the wire shape of an entry is the JSON projection of the type here.
//
// Index (App: 0 keys · Workspace: 6 keys · Session: 18 keys · Agent: 70 keys)
// Index (App: 0 keys · Workspace: 6 keys · Session: 18 keys · Agent: 69 keys)
// App
// Workspace
// workspaceDirs.ephemeralDirs src/workspace/workspaceDirs/workspaceDirsService.ts
Expand Down Expand Up @@ -62,7 +62,6 @@
// agentsMdReminder.seeded src/agent/agentsMdReminder/agentsMdReminderService.ts
// contextInjector.isNewTurn src/agent/contextInjector/contextInjectorService.ts
// contextProjector.lastRepairSignature src/agent/contextProjector/contextProjectorService.ts
// contextSize.lastEmittedTokens src/agent/contextSize/contextSizeService.ts
// externalHooks.stopHookContinuationUsed src/agent/externalHooks/externalHooksService.ts
// fullCompaction.activeTurnId src/agent/fullCompaction/fullCompactionService.ts
// fullCompaction.compactionCountInTurn src/agent/fullCompaction/fullCompactionService.ts
Expand Down Expand Up @@ -981,8 +980,6 @@ export interface AgentStateSnapshot {
'contextInjector.isNewTurn': boolean;
// src/agent/contextProjector/contextProjectorService.ts
'contextProjector.lastRepairSignature': string | null;
// src/agent/contextSize/contextSizeService.ts
'contextSize.lastEmittedTokens': number;
// src/agent/externalHooks/externalHooksService.ts
'externalHooks.stopHookContinuationUsed': boolean;
// src/agent/fullCompaction/fullCompactionService.ts
Expand Down
51 changes: 38 additions & 13 deletions packages/agent-core-v2/docs/wire-manifest.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@
// owning model offloads inline media to blob storage), cross-reducers
// (foreign models that also reduce this record on dispatch and replay).

// Index (46 record types)
// Index (48 record types)
// config.update profile persisted src/agent/profile/profileOps.ts
// context_size.measured contextSize transient src/agent/contextSize/contextSizeOps.ts
// context.append_loop_event contextMemory persisted src/agent/contextMemory/contextOps.ts
// context.append_message contextMemory persisted src/agent/contextMemory/contextOps.ts
// context.apply_compaction contextMemory persisted src/agent/contextMemory/contextOps.ts
Expand Down Expand Up @@ -58,6 +57,9 @@
// swarm_mode.exit swarm persisted src/agent/swarm/swarmOps.ts
// task.started task persisted src/agent/task/taskOps.ts
// task.terminated task persisted src/agent/task/taskOps.ts
// token_counting.measured tokenCounting transient src/agent/tokenCounting/tokenCountingOps.ts
// token_counting.rebased tokenCounting transient src/agent/tokenCounting/tokenCountingOps.ts
// token_counting.truncated tokenCounting transient src/agent/tokenCounting/tokenCountingOps.ts
// tools.register_user_tool userTool persisted src/agent/userTool/userToolOps.ts
// tools.reset_active_tools profile.activeTools persisted src/agent/profile/profileOps.ts
// tools.set_active_tools profile.activeTools persisted src/agent/profile/profileOps.ts
Expand Down Expand Up @@ -86,16 +88,6 @@ interface ConfigUpdatePayload {
disallowedTools?: string[];
}

/**
* model: contextSize · toEvent
* owner: src/agent/contextSize/contextSizeOps.ts
*/
interface ContextSizeMeasuredPayload {
_name: 'context_size.measured';
length: number;
tokens: number;
}

/**
* model: contextMemory · persisted · blobs · cross-reducers: turn
* owner: src/agent/contextMemory/contextOps.ts
Expand Down Expand Up @@ -525,6 +517,37 @@ interface TaskTerminatedPayload {
outputTail?: string;
}

/**
* model: tokenCounting · toEvent
* owner: src/agent/tokenCounting/tokenCountingOps.ts
*/
interface TokenCountingMeasuredPayload {
_name: 'token_counting.measured';
length: number;
tokens: number;
}

/**
* model: tokenCounting · toEvent
* owner: src/agent/tokenCounting/tokenCountingOps.ts
*/
interface TokenCountingRebasedPayload {
_name: 'token_counting.rebased';
length: number;
tokens: number;
measured: boolean;
}

/**
* model: tokenCounting · toEvent
* owner: src/agent/tokenCounting/tokenCountingOps.ts
*/
interface TokenCountingTruncatedPayload {
_name: 'token_counting.truncated';
length: number;
tokens: number;
}

/**
* model: userTool · persisted
* owner: src/agent/userTool/userToolOps.ts
Expand Down Expand Up @@ -683,7 +706,6 @@ interface UsageRecordPayload {
/** Record type → payload sketch. */
interface WirePayloadMap {
"config.update": ConfigUpdatePayload;
"context_size.measured": ContextSizeMeasuredPayload;
"context.append_loop_event": ContextAppendLoopEventPayload;
"context.append_message": ContextAppendMessagePayload;
"context.apply_compaction": ContextApplyCompactionPayload;
Expand Down Expand Up @@ -718,6 +740,9 @@ interface WirePayloadMap {
"swarm_mode.exit": SwarmModeExitPayload;
"task.started": TaskStartedPayload;
"task.terminated": TaskTerminatedPayload;
"token_counting.measured": TokenCountingMeasuredPayload;
"token_counting.rebased": TokenCountingRebasedPayload;
"token_counting.truncated": TokenCountingTruncatedPayload;
"tools.register_user_tool": ToolsRegisterUserToolPayload;
"tools.reset_active_tools": ToolsResetActiveToolsPayload;
"tools.set_active_tools": ToolsSetActiveToolsPayload;
Expand Down
Loading
Loading