feat(subagent): 实验功能设置新增子代理模型配置
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s

- 子代理设置页支持选择次主力模型,仅保存模型引用(不再写补丁字段),
  子代理直接继承所选模型的上下文长度与思考模式
- 界面只读展示继承的上下文长度与思考模式,移除补丁编辑项
- 仪表盘统计识别子代理请求(__secondary__):归为「子代理模型(估算)」
  并缓存次主力模型定价;自定义网关模型价格按官方同名模型跨 provider 匹配
- bump v0.7.1
This commit is contained in:
KimiSwitch Dev committed 2026-08-05 23:38:05 +08:00
1 parent 8b0daabd95
commit 8aed04898c
22 files changed
+16648 -8882

No files matched your search

+21 -2
View File
@@ -5,6 +5,7 @@ import { useConfig } from "./hooks/useConfig";
import { useUpdateCheck } from "./hooks/useUpdateCheck";
import { ProviderList } from "./components/ProviderList";
import { ProviderEdit } from "./components/ProviderEdit";
import { SubagentSettingsPage } from "./components/SubagentSettingsPage";
import { DashboardPage } from "./components/dashboard/DashboardPage";
import { SessionsPage } from "./components/sessions/SessionsPage";
import { SettingsModal } from "./components/SettingsModal";
@@ -70,7 +71,7 @@ export default function App() {
updateConfig,
} = useConfig(agent);
const [view, setView] = useState<"list" | "edit" | "dashboard" | "sessions">("list");
const [view, setView] = useState<"list" | "edit" | "subagent" | "dashboard" | "sessions">("list");
const [editingProvider, setEditingProvider] = useState<string>("");
const [loadTimeout, setLoadTimeout] = useState(false);
const [switchMessage, setSwitchMessage] = useState<string | null>(null);
@@ -573,7 +574,7 @@ export default function App() {
type="button"
onClick={() => setView("list")}
className={`px-3 py-1 text-sm rounded transition-colors ${
view === "list" || view === "edit"
view === "list" || view === "edit" || view === "subagent"
? "bg-blue-600 text-white"
: "text-content-muted hover:text-content-primary"
}`}
@@ -649,6 +650,15 @@ export default function App() {
<DashboardPage />
) : view === "sessions" ? (
<SessionsPage />
) : view === "subagent" ? (
<SubagentSettingsPage
rawOther={config.raw_other}
models={config.models}
onChange={(nextRawOther) =>
updateConfig((cfg) => ({ ...cfg, raw_other: nextRawOther }))
}
onBack={() => setView("list")}
/>
) : view === "list" ? (
<ProviderList
providers={providers}
@@ -813,6 +823,15 @@ export default function App() {
>
{t("openConfigDir")}
</button>
{view === "list" && (
<button
type="button"
onClick={() => setView("subagent")}
className="px-3 py-1.5 text-sm border border-border rounded hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("subagentSettings")}
</button>
)}
</div>
</footer>
)}
+1 -100
View File
@@ -1,8 +1,8 @@
import type { ReactNode } from "react";
import { useTranslation } from "../i18n";
import type { TranslationKey } from "../i18n/zh";
import { getAgentSettings, setAgentSettings } from "../lib/agent-settings";
import type { AgentSettings, Hook, PermissionRule } from "../types";
import { Card, Checkbox, NumberField, Segmented } from "./ui/controls";
interface AgentSettingsPanelProps {
rawOther: unknown;
@@ -275,102 +275,3 @@ export function AgentSettingsPanel({ rawOther, onChange }: AgentSettingsPanelPro
</div>
);
}
function Card({ title, children }: { title: string; children: ReactNode }) {
return (
<div className="bg-panel border border-border rounded-xl p-4 space-y-3">
<h4 className="text-content-muted text-sm font-medium">{title}</h4>
{children}
</div>
);
}
function Checkbox({
label,
checked,
disabled,
onChange,
}: {
label: string;
checked: boolean;
disabled?: boolean;
onChange: (checked: boolean) => void;
}) {
return (
<label
className={`flex items-center gap-2 text-sm ${
disabled ? "text-content-muted" : "text-content-primary"
}`}
>
<input
type="checkbox"
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
className="rounded border-border bg-input text-blue-600 focus:ring-blue-500"
/>
{label}
</label>
);
}
function NumberField({
label,
value,
onChange,
}: {
label: string;
value?: number;
onChange: (value: number | undefined) => void;
}) {
return (
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="text-content-muted">{label}</span>
<input
type="number"
value={value ?? ""}
onChange={(e) => {
const raw = e.target.value;
onChange(raw === "" ? undefined : Number(raw));
}}
className="w-32 bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</label>
);
}
function Segmented({
options,
value,
onChange,
disabled,
}: {
options: { key: string; label: string }[];
value: string;
onChange: (value: string) => void;
disabled?: boolean;
}) {
return (
<div
className={`flex items-center rounded overflow-hidden border border-border ${
disabled ? "opacity-50" : ""
}`}
>
{options.map((opt) => (
<button
key={opt.key}
type="button"
disabled={disabled}
onClick={() => onChange(opt.key)}
className={`px-3 py-1 text-sm ${
value === opt.key
? "bg-blue-600 text-white"
: "bg-input text-content-muted hover:bg-hover-2"
}`}
>
{opt.label}
</button>
))}
</div>
);
}
+239
View File
@@ -0,0 +1,239 @@
import { useEffect, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { useTranslation } from "../i18n";
import type { TranslationKey } from "../i18n/zh";
import type { ExperimentalEnvStatus, Model } from "../types";
import {
EXPERIMENTAL_FLAGS,
clearSecondaryModel,
forcedEnvValue,
getExperimentalFlags,
getSecondaryModel,
isFlagLockedByEnv,
isMasterEnvOn,
setExperimentalFlag,
setSecondaryModelOnly,
type ExperimentalFlagDef,
} from "../lib/subagent-settings";
import { Card, Checkbox } from "./ui/controls";
interface SubagentSettingsPageProps {
/** config.raw_other — hosts the `[experimental]` and `[secondary_model]` sections. */
rawOther: unknown;
/** All configured models (alias → entry) for the secondary-model picker. */
models: Record<string, Model>;
onChange: (nextRawOther: unknown) => void;
onBack: () => void;
}
const EFFORTS = ["low", "medium", "high", "max"] as const;
const EFFORT_LABELS: Record<(typeof EFFORTS)[number], TranslationKey> = {
low: "thinkingLow",
medium: "thinkingMedium",
high: "thinkingHigh",
max: "thinkingMax",
};
const FLAG_LABELS: Record<string, { name: TranslationKey; desc: TranslationKey }> = {
"secondary-model": { name: "flagSecondaryModel", desc: "flagSecondaryModelDesc" },
"tool-select": { name: "flagToolSelect", desc: "flagToolSelectDesc" },
"acp-v2": { name: "flagAcpV2", desc: "flagAcpV2Desc" },
persistence_minidb_readmodel: {
name: "flagMinidbReadmodel",
desc: "flagMinidbReadmodelDesc",
},
};
export function SubagentSettingsPage({
rawOther,
models,
onChange,
onBack,
}: SubagentSettingsPageProps) {
const { t } = useTranslation();
const [env, setEnv] = useState<ExperimentalEnvStatus | null>(null);
useEffect(() => {
invoke<ExperimentalEnvStatus>("get_experimental_env_status")
.then(setEnv)
.catch(() => setEnv({}));
}, []);
const flags = getExperimentalFlags(rawOther);
const secondary = getSecondaryModel(rawOther);
const masterOn = isMasterEnvOn(env);
const secondaryFlag = EXPERIMENTAL_FLAGS[0]; // "secondary-model"
const otherFlags = EXPERIMENTAL_FLAGS.slice(1);
/** Effective state of the secondary-model flag (env overrides config). */
const secondaryEnabled = masterOn
? true
: isFlagLockedByEnv(env, secondaryFlag)
? forcedEnvValue(env, secondaryFlag)
: flags["secondary-model"] === true;
const aliasList = Object.keys(models).sort();
// Inherited settings shown for the picked model: subagents bind the pointed
// entry directly (no patch fields), so context size and effort come from the
// model entry / global [thinking], not from a `[secondary_model]` patch.
const selectedEntry = secondary.model ? models[secondary.model] : undefined;
const inheritedContext = selectedEntry?.max_context_size;
const modelEffort =
selectedEntry &&
typeof (selectedEntry.raw_other as Record<string, unknown> | undefined)
?.default_effort === "string"
? ((selectedEntry.raw_other as Record<string, unknown>).default_effort as string)
: undefined;
const thinkingEffort = (() => {
const ro = rawOther as Record<string, unknown> | undefined;
const thinking = ro?.thinking as Record<string, unknown> | undefined;
return thinking && typeof thinking.effort === "string" && thinking.effort
? thinking.effort
: undefined;
})();
const inheritedEffort = modelEffort ?? thinkingEffort;
const fmtContext = (n: number): string =>
n >= 1_000_000
? `${(n / 1_000_000).toFixed(1)}M`
: n >= 1000
? `${Math.round(n / 1000)}K`
: String(n);
const effortLabel = (e: string): string => {
const key = EFFORT_LABELS[e as (typeof EFFORTS)[number]];
return key ? t(key) : e;
};
const renderFlagRow = (flag: ExperimentalFlagDef) => {
const labels = FLAG_LABELS[flag.id];
const locked = masterOn || isFlagLockedByEnv(env, flag);
const on = masterOn
? true
: isFlagLockedByEnv(env, flag)
? forcedEnvValue(env, flag)
: flags[flag.id] === true;
return (
<div key={flag.id} className="flex items-center gap-3">
<div className="flex-1 min-w-0">
<div className="text-sm text-content-primary">{t(labels.name)}</div>
<div className="text-xs text-content-muted">
{t(labels.desc)}
<code className="ml-2">{flag.envVar}</code>
</div>
</div>
{locked && (
<span className="text-xs text-content-muted shrink-0">
🔒 {t("lockedByEnv")}
</span>
)}
<Checkbox
label=""
checked={on}
disabled={locked}
onChange={(checked) =>
onChange(setExperimentalFlag(rawOther, flag.id, checked))
}
/>
</div>
);
};
return (
<div className="h-full flex flex-col bg-app">
{/* Header */}
<div className="flex items-center gap-3 px-4 py-3 border-b border-border bg-panel">
<button
type="button"
onClick={onBack}
className="p-2 rounded-lg hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
← {t("back")}
</button>
<h2 className="font-semibold text-lg">{t("subagentSettings")}</h2>
</div>
<div className="flex-1 overflow-auto p-6 space-y-4">
{masterOn && (
<div className="bg-green-100 dark:bg-green-900/20 border border-green-300 dark:border-green-500/30 rounded-lg px-4 py-2 text-sm text-green-700 dark:text-green-400">
{t("masterEnvOnHint")}
</div>
)}
{/* Subagent: experimental flag + secondary model in one card */}
<Card title={t("secondaryModelSection")}>
{renderFlagRow(secondaryFlag)}
<div className="border-t border-border" />
{!secondaryEnabled && (
<div className="bg-amber-100 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-500/30 rounded-lg px-3 py-2 text-sm text-amber-800 dark:text-amber-400">
{t("secondaryModelDisabledHint")}
</div>
)}
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="text-content-muted">{t("secondaryModelLabel")}</span>
<select
className="flex-1 max-w-md bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
value={secondary.model ?? ""}
onChange={(e) => {
const alias = e.target.value;
if (alias === "") {
onChange(clearSecondaryModel(rawOther));
} else {
// Only the model reference is persisted — no patch fields.
// Subagents bind the pointed entry directly and inherit its
// settings; usage records stay keyed on the real alias
// instead of Kimi Code's synthesized `__secondary__` entry.
onChange(setSecondaryModelOnly(rawOther, alias));
}
}}
>
<option value="">{t("secondaryModelUnset")}</option>
{aliasList.map((alias) => (
<option key={alias} value={alias}>
{models[alias]?.display_name
? `${alias}(${models[alias].display_name})`
: alias}
</option>
))}
</select>
</label>
{secondary.model !== undefined && (
<div className="rounded-lg border border-border bg-input/40 px-3 py-2 space-y-1.5">
<div className="flex items-center gap-3 text-sm">
<span className="text-content-muted w-24 shrink-0">
{t("secondaryModelInheritedContext")}
</span>
<span className="text-content-primary">
{inheritedContext ? fmtContext(inheritedContext) : "—"}
</span>
</div>
<div className="flex items-center gap-3 text-sm">
<span className="text-content-muted w-24 shrink-0">
{t("secondaryModelInheritedEffort")}
</span>
<span className="text-content-primary">
{inheritedEffort ? effortLabel(inheritedEffort) : "—"}
</span>
</div>
<p className="text-xs text-content-muted">
{t("secondaryModelInheritedHint")}
</p>
</div>
)}
<p className="text-xs text-content-muted">{t("secondaryModelHint")}</p>
<p className="text-xs text-content-muted">{t("secondaryModelPriorityHint")}</p>
</Card>
{/* Other experimental features (not subagent-related) */}
<Card title={t("otherExperimentalFlags")}>
{otherFlags.map(renderFlagRow)}
<p className="text-xs text-content-muted">{t("experimentalFlagsHint")}</p>
</Card>
</div>
</div>
);
}
+4
View File
@@ -59,6 +59,10 @@ export function DailyBars({ daily, dimension, names, unknownProviderLabel }: Dai
if (dimension === "provider") {
return key === "unknown" ? unknownProviderLabel : key;
}
// Subagent records (Kimi Code `__secondary__` marker) show their own label.
if (key === "__secondary__") {
return t("subagentModel");
}
return shortModel(key);
};
@@ -25,6 +25,10 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
const { t } = useTranslation();
const { money } = useCurrency();
/** Subagent records (Kimi Code `__secondary__` marker) show their own label. */
const modelName = (model: string) =>
model === "__secondary__" ? t("subagentModel") : shortModel(model);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
@@ -143,7 +147,7 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
<div className="mt-1 ml-5 space-y-0.5">
{p.models.map((m) => (
<div key={m.model} className="flex items-baseline justify-between gap-2 text-xs">
<span className="truncate text-content-muted" title={m.model}>{shortModel(m.model)}</span>
<span className="truncate text-content-muted" title={m.model}>{modelName(m.model)}</span>
<span className="shrink-0 text-content-muted tabular-nums">{fmtTokens(m.tokens)}</span>
</div>
))}
@@ -167,7 +171,7 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
<span className="inline-block h-2.5 w-2.5 rounded-sm shrink-0" style={{ backgroundColor: modelColor(i) }} />
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-2">
<span className="truncate text-content-primary" title={s.model}>{shortModel(s.model)}</span>
<span className="truncate text-content-primary" title={s.model}>{modelName(s.model)}</span>
<span className="shrink-0 text-xs text-content-muted tabular-nums">
{fmtTokens(s.tokens)} <span className="text-content-muted">· {s.pct.toFixed(1)}%</span>
</span>
+10 -2
View File
@@ -310,7 +310,9 @@ export function DashboardPage() {
}}
/>
<div className="flex items-center gap-1.5 min-w-0">
<span className="text-content-primary whitespace-nowrap truncate">{m.modelDisplay || m.model}</span>
<span className="text-content-primary whitespace-nowrap truncate">
{m.isSecondary ? t("subagentModel") : m.modelDisplay || m.model}
</span>
{m.costEstimated && (
<span className="text-[10px] text-yellow-600 shrink-0">({t("estimate")})</span>
)}
@@ -371,7 +373,13 @@ export function DashboardPage() {
<td className="py-1.5 pr-4 text-content-muted whitespace-nowrap">
{fmtTime(r.time)}
</td>
<td className="py-1.5 pr-4 text-content-primary">{r.modelDisplay || r.model}</td>
<td className="py-1.5 pr-4 text-content-primary">
<span className="flex items-center gap-1.5 min-w-0">
<span className="truncate">
{r.isSecondary ? t("subagentModel") : r.modelDisplay || r.model}
</span>
</span>
</td>
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtTokens(r.inputOther)}</td>
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtTokens(r.output)}</td>
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtTokens(r.inputCacheRead)}</td>
+104
View File
@@ -0,0 +1,104 @@
import type { ReactNode } from "react";
/** Shared small form controls used by settings panels (Agent settings,
* Subagent settings, ...). Extracted from AgentSettingsPanel.tsx so new
* panels can reuse the same look without duplicating code. */
export function Card({ title, children }: { title: string; children: ReactNode }) {
return (
<div className="bg-panel border border-border rounded-xl p-4 space-y-3">
<h4 className="text-content-muted text-sm font-medium">{title}</h4>
{children}
</div>
);
}
export function Checkbox({
label,
checked,
disabled,
onChange,
}: {
label: string;
checked: boolean;
disabled?: boolean;
onChange: (checked: boolean) => void;
}) {
return (
<label
className={`flex items-center gap-2 text-sm ${
disabled ? "text-content-muted" : "text-content-primary"
}`}
>
<input
type="checkbox"
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
className="rounded border-border bg-input text-blue-600 focus:ring-blue-500"
/>
{label}
</label>
);
}
export function NumberField({
label,
value,
onChange,
}: {
label: string;
value?: number;
onChange: (value: number | undefined) => void;
}) {
return (
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="text-content-muted">{label}</span>
<input
type="number"
value={value ?? ""}
onChange={(e) => {
const raw = e.target.value;
onChange(raw === "" ? undefined : Number(raw));
}}
className="w-32 bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</label>
);
}
export function Segmented({
options,
value,
onChange,
disabled,
}: {
options: { key: string; label: string }[];
value: string;
onChange: (value: string) => void;
disabled?: boolean;
}) {
return (
<div
className={`flex items-center rounded overflow-hidden border border-border ${
disabled ? "opacity-50" : ""
}`}
>
{options.map((opt) => (
<button
key={opt.key}
type="button"
disabled={disabled}
onClick={() => onChange(opt.key)}
className={`px-3 py-1 text-sm ${
value === opt.key
? "bg-blue-600 text-white"
: "bg-input text-content-muted hover:bg-hover-2"
}`}
>
{opt.label}
</button>
))}
</div>
);
}
+31
View File
@@ -320,6 +320,7 @@ export const enTranslations: Record<TranslationKey, string> = {
colCacheRead: "Cache read",
unitTimes: "requests",
estimate: "est.",
subagentModel: "Subagent model",
collapse: "Collapse",
expandAll: "Expand all ({n})",
@@ -447,4 +448,34 @@ export const enTranslations: Record<TranslationKey, string> = {
trendLineShowRequests: "Show requests",
trendLineTooltip: "{date}\nTokens: {tokens}\nCache hit: {cache}\nRequests: {req}",
trendLineNoData: "No data",
// Subagent settings page (experimental flags + secondary model)
subagentSettings: "Subagent Settings",
experimentalFlags: "Experimental Features",
otherExperimentalFlags: "Other Experimental Features",
experimentalFlagsHint:
"Toggles are written to the [experimental] section of config.toml; env vars take precedence and locked toggles cannot be changed here",
flagSecondaryModel: "Subagent Secondary Model",
flagSecondaryModelDesc: "Newly spawned subagents bind a second (usually cheaper) model config",
flagToolSelect: "Tool Select",
flagToolSelectDesc: "Enable the experimental tool selection feature",
flagAcpV2: "ACP v2 Protocol",
flagAcpV2Desc: "Enable Agent Communication Protocol v2",
flagMinidbReadmodel: "MiniDB Read Model",
flagMinidbReadmodelDesc: "Enable the v2 engine MiniDB read-model backend",
lockedByEnv: "Locked by env var",
masterEnvOnHint: "KIMI_CODE_EXPERIMENTAL_FLAG is set: all experimental features are forced on by the env var",
secondaryModelSection: "Subagent Model (Secondary Model)",
secondaryModelDisabledHint:
"The experimental flag \"Subagent Secondary Model\" is off and this config will not take effect — enable the toggle above first",
secondaryModelLabel: "Secondary model",
secondaryModelUnset: "Not configured",
secondaryModelInheritedContext: "Inherited context",
secondaryModelInheritedEffort: "Inherited effort",
secondaryModelInheritedHint:
"Subagents bind the selected model directly and inherit its context size and effort — no patch needed",
secondaryModelHint:
"Second model config bound to subagents by default; when unset, subagents inherit the primary model. Only the model reference is stored; subagents inherit all of that model's settings",
secondaryModelPriorityHint:
"Priority: explicit tool model param > profile model_preference > this config > inherit primary model",
};
+31
View File
@@ -315,6 +315,7 @@ export const zhTranslations = {
colCacheRead: "缓存读",
unitTimes: "次",
estimate: "估算",
subagentModel: "子代理模型",
collapse: "收起",
expandAll: "展开全部 ({n})",
@@ -442,6 +443,36 @@ export const zhTranslations = {
trendLineShowRequests: "显示请求数",
trendLineTooltip: "{date}\nToken: {tokens}\n命中率: {cache}\n请求: {req}",
trendLineNoData: "暂无数据",
// Subagent settings page (experimental flags + secondary model)
subagentSettings: "子代理设置",
experimentalFlags: "实验功能开关",
otherExperimentalFlags: "其他实验功能",
experimentalFlagsHint:
"开关写入 config.toml 的 [experimental] 节;环境变量优先级更高,被锁定的开关无法在此修改",
flagSecondaryModel: "子代理次主力模型",
flagSecondaryModelDesc: "子代理派发时绑定第二份(通常更便宜的)模型配置",
flagToolSelect: "工具选择",
flagToolSelectDesc: "启用实验性工具选择功能",
flagAcpV2: "ACP v2 协议",
flagAcpV2Desc: "启用 Agent Communication Protocol v2",
flagMinidbReadmodel: "MiniDB 读模型",
flagMinidbReadmodelDesc: "启用 v2 引擎 MiniDB 读模型后端",
lockedByEnv: "被环境变量锁定",
masterEnvOnHint: "KIMI_CODE_EXPERIMENTAL_FLAG 已设置:全部实验功能被环境变量强制开启",
secondaryModelSection: "子代理模型(次主力模型)",
secondaryModelDisabledHint:
"实验开关「子代理次主力模型」未启用,本配置不会生效——请先在上方打开对应开关",
secondaryModelLabel: "次主力模型",
secondaryModelUnset: "未配置",
secondaryModelInheritedContext: "继承上下文长度",
secondaryModelInheritedEffort: "继承思考模式",
secondaryModelInheritedHint:
"子代理直接绑定所选模型,继承其上下文长度与思考设置,无需单独配置补丁",
secondaryModelHint:
"子代理默认绑定的第二份模型配置;未配置时子代理继承主模型;仅保存模型引用,子代理继承该模型的全部设置",
secondaryModelPriorityHint:
"优先级:工具显式 model 参数 > 子代理 profile 的 model_preference > 本配置 > 继承主模型",
} as const;
export type TranslationKey = keyof typeof zhTranslations;
+8635 -4926
View File
File diff suppressed because it is too large. Load diff
+7152 -3842
View File
File diff suppressed because it is too large. Load diff
+155
View File
@@ -0,0 +1,155 @@
import type { ExperimentalEnvStatus, SecondaryModelConfig } from "../types";
/**
* Helpers for the `[experimental]` and `[secondary_model]` sections of the
* Kimi Code config.toml. Both live in `config.raw_other` (the pass-through
* bucket for unknown top-level TOML sections), so these helpers read/write
* that JSON object directly.
*/
function asRecord(value: unknown): Record<string, unknown> {
if (value && typeof value === "object" && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
function isTruthyEnv(value: string | undefined): boolean {
if (!value) return false;
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
// ---------------------------------------------------------------------------
// [experimental] — experimental feature flags
// ---------------------------------------------------------------------------
export interface ExperimentalFlagDef {
/** Flag id as stored in config.toml `[experimental]` (e.g. "secondary-model"). */
id: string;
/** Single-feature env var that can force the flag (locks the UI toggle). */
envVar: string;
}
/** Known experimental flags (Kimi Code v1 + v2 registries, merged). */
export const EXPERIMENTAL_FLAGS: ExperimentalFlagDef[] = [
{ id: "secondary-model", envVar: "KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL" },
{ id: "tool-select", envVar: "KIMI_CODE_EXPERIMENTAL_TOOL_SELECT" },
{ id: "acp-v2", envVar: "KIMI_CODE_EXPERIMENTAL_ACP_V2" },
{
id: "persistence_minidb_readmodel",
envVar: "KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL",
},
];
export const EXPERIMENTAL_MASTER_ENV = "KIMI_CODE_EXPERIMENTAL_FLAG";
/** Whether the master env var is set to a truthy value (locks every flag on). */
export function isMasterEnvOn(env: ExperimentalEnvStatus | null): boolean {
return isTruthyEnv(env?.[EXPERIMENTAL_MASTER_ENV]);
}
/** Whether a flag's value is overridden by its env var (set & non-empty),
* locking the config toggle. Kimi Code lets the env var force the flag on
* *or* off, so a set env var locks regardless of its truthiness. */
export function isFlagLockedByEnv(
env: ExperimentalEnvStatus | null,
flag: ExperimentalFlagDef
): boolean {
return env !== null && flag.envVar in env;
}
/** The value a locked flag is forced to by its env var. */
export function forcedEnvValue(
env: ExperimentalEnvStatus | null,
flag: ExperimentalFlagDef
): boolean {
return isTruthyEnv(env?.[flag.envVar]);
}
/** Read `[experimental]` from raw_other: `{ flagId: boolean }`. */
export function getExperimentalFlags(rawOther: unknown): Record<string, boolean> {
const section = asRecord(rawOther)["experimental"];
const flags = asRecord(section);
const out: Record<string, boolean> = {};
for (const [k, v] of Object.entries(flags)) {
out[k] = v === true;
}
return out;
}
/** Set one flag in `[experimental]`. Removing all flags drops the section. */
export function setExperimentalFlag(
rawOther: unknown,
id: string,
enabled: boolean
): unknown {
const root = { ...asRecord(rawOther) };
const flags = { ...getExperimentalFlags(rawOther) };
if (enabled) {
flags[id] = true;
} else {
delete flags[id];
}
if (Object.keys(flags).length > 0) {
root.experimental = flags;
} else {
delete root.experimental;
}
return root;
}
// ---------------------------------------------------------------------------
// [secondary_model] — subagent secondary model
// ---------------------------------------------------------------------------
/** Read `[secondary_model]` from raw_other; `{}` when absent. */
export function getSecondaryModel(rawOther: unknown): SecondaryModelConfig {
const section = asRecord(rawOther)["secondary_model"];
const cfg = asRecord(section);
const out: SecondaryModelConfig = {};
if (typeof cfg.model === "string" && cfg.model !== "") out.model = cfg.model;
if (typeof cfg.default_effort === "string" && cfg.default_effort !== "")
out.default_effort = cfg.default_effort;
if (typeof cfg.max_output_size === "number" && cfg.max_output_size > 0)
out.max_output_size = cfg.max_output_size;
if (typeof cfg.max_context_size === "number" && cfg.max_context_size > 0)
out.max_context_size = cfg.max_context_size;
return out;
}
/**
* Write `[secondary_model]` with only the `model` field — no patch fields.
* Subagents then bind the pointed model entry directly and inherit its
* settings (context size, capabilities, effort fallback), which also keeps
* usage records keyed on the real model alias instead of the synthesized
* `__secondary__` derived entry. Unknown fields already present in the
* section are preserved; the known patch fields (`default_effort`,
* `max_output_size`, `max_context_size`) are dropped so stale patches are
* cleaned up when the model is re-picked.
*/
export function setSecondaryModelOnly(
rawOther: unknown,
alias: string
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = { model: alias };
const knownFields: ReadonlySet<string> = new Set([
"model",
"default_effort",
"max_output_size",
"max_context_size",
]);
for (const [k, v] of Object.entries(section)) {
if (!knownFields.has(k)) next[k] = v;
}
root.secondary_model = next;
return root;
}
/** Remove `[secondary_model]` entirely (the "not configured" option). */
export function clearSecondaryModel(rawOther: unknown): unknown {
const root = { ...asRecord(rawOther) };
delete root.secondary_model;
return root;
}
+4
View File
@@ -24,6 +24,8 @@ export interface ModelRow extends TotalsRow {
modelResolved: string;
priceId: string;
costEstimated: boolean;
/** True when any record in this row came from a subagent (secondary-model) request. */
isSecondary: boolean;
}
export interface RecentRow {
@@ -40,6 +42,8 @@ export interface RecentRow {
costEstimated: boolean;
priceId: string;
fromEnv: boolean;
/** True when this request came from a subagent (secondary-model) call. */
isSecondary: boolean;
}
export interface RangeStats {
+16
View File
@@ -127,3 +127,19 @@ export interface AgentSettings {
permission?: { rules?: PermissionRule[] };
hooks?: Hook[];
}
/**
* Kimi Code `[secondary_model]` section of config.toml: the secondary model
* bound to newly spawned subagents (experimental feature).
* `model` points at an alias defined in `[models]`; the remaining fields are
* a patch applied on top of the referenced entry (subagents only).
*/
export interface SecondaryModelConfig {
model?: string;
default_effort?: string;
max_output_size?: number;
max_context_size?: number;
}
/** Values of experimental env vars that are currently set (non-empty). */
export type ExperimentalEnvStatus = Record<string, string>;