Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(teammates): support persistent self model selection and reset

zqchrisa7d963c30a60
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 2acfcb8c32..192b14e540 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -1,4 +1,4 @@
-import { setNewMakerDraftCache } from '../../../maker-host/newMakerDefaultsCache';
+import { getSelectedNewMakerRoute, setNewMakerDraftCache } from '../../../maker-host/newMakerDefaultsCache';
import { setModelVisibilityMirror } from '../../../maker-host/model-visibility-mirror';
import Database from 'better-sqlite3';
import type { ProviderView } from '@cindy/model-providers';
@@ -4343,3 +4343,72 @@ describe('Bot self control uses the same profile authority as settings', () => {
expect((await invoke('local-db:bots:get', 'bot-1')).name).toBe('Renamed');
});
});
+
+
+describe('Teammate model selection shares profile persistence and route reconciliation', () => {
+ async function setupModelControl() {
+ const canonical = await invoke('local-db:bots:create-canonical-session', {
+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,
+ });
+ const model = { ...h.providers[0]!.models.pi![0]!, id: 'enabled-alternate-model' };
+ h.providers[0]!.models.pi!.push(model);
+ model.efforts = ['low', 'high'];
+ model.defaultEnabled = true;
+ return { sessionId: canonical.session.id as string,
+ service: createBotCapabilityService(capabilityDeps),
+ id: JSON.stringify(['pi', 'xd', model.id]), model };
+ }
+
+ it('saves only its own explicit model chain, applies it through the send resolver, and resets to the live default', async () => {
+ const { service, sessionId, id } = await setupModelControl();
+ await invoke('local-db:bots:create', { id: 'bot-2', name: 'Other teammate', avatar: '🐈' });
+ const before = await invoke('local-db:bots:get', 'bot-1');
+ const other = await invoke('local-db:bots:get', 'bot-2');
+ const appDefault = getSelectedNewMakerRoute(h.ownerScopeKey);
+ expect(await service.updateProfile({ callerSessionId: sessionId, expectedVersion: 1,
+ modelChain: [{ id, effort: 'low', fastMode: false }] })).toMatchObject({ ok: true, effective: 'next-turn' });
+ const after = await invoke('local-db:bots:get', 'bot-1');
+ const chain = await modelSettings.readEffectiveBotModelChain(after.capabilities);
+ expect(chain).toEqual([{ harness: 'pi', providerId: 'xd', model: 'enabled-alternate-model', effort: 'low', fastMode: false }]);
+ expect(after.identitySource).toBe(before.identitySource);
+ expect(after.canonicalSessionId).toBe(sessionId);
+ for (const key of ['skills', 'mcpServers', 'toolsets', 'memory', 'permissions'])
+ expect(after.capabilities[key]).toEqual(before.capabilities[key]);
+ expect(await invoke('local-db:bots:get', 'bot-2')).toEqual(other);
+ expect(getSelectedNewMakerRoute(h.ownerScopeKey)).toEqual(appDefault);
+ const apply = vi.fn();
+ // A fresh reconciler models restart; the saved choice, not an ephemeral override, owns the next send.
+ await createBotModelRouteReconciler({ ownerEpoch: () => h.ownerScopeKey,
+ read: async () => ({ chain, current: { agentKind: 'pi', model: 'grok-4.5', providerId: null, effort: 'high', fastMode: false }, hasRuntimeOverride: false }), apply,
+ })(sessionId);
+ expect(apply).toHaveBeenCalledWith(sessionId, expect.objectContaining({ effort: 'low', model: 'enabled-alternate-model' }), expect.anything());
+ expect(await service.updateProfile({ callerSessionId: sessionId, expectedVersion: 1, modelChain: null })).toMatchObject({ ok: false });
+ expect(await service.updateProfile({ callerSessionId: sessionId, expectedVersion: 2, modelChain: null })).toMatchObject({ ok: true });
+ const restored = await invoke('local-db:bots:get', 'bot-1');
+ expect(restored.capabilities.modelChainOverride).toBeNull();
+ expect(await modelSettings.readEffectiveBotModelChain(restored.capabilities)).toEqual([appDefault]);
+ const nextDefault = { ...appDefault!, effort: 'low' };
+ setNewMakerDraftCache({ selectedRoute: nextDefault, lastByVendor: {}, effortByModel: {}, fastModeByModel: {} }, h.ownerScopeKey);
+ expect(await modelSettings.readEffectiveBotModelChain(restored.capabilities)).toEqual([nextDefault]);
+ });
+
+ it.each(['disabled', 'disconnected', 'effort', 'fast', 'duplicate', 'unknown', 'owner', 'foreign'] as const)(
+ 'rejects %s selection without changing profile or app defaults', async (kind) => {
+ const { service, sessionId, id, model } = await setupModelControl();
+ const before = await invoke('local-db:bots:get', 'bot-1');
+ const appDefault = getSelectedNewMakerRoute(h.ownerScopeKey);
+ const choice = { id, effort: 'low', fastMode: false };
+ if (kind === 'disabled') model.defaultEnabled = false;
+ if (kind === 'disconnected') h.providers[0]!.connected = false;
+ if (kind === 'effort') choice.effort = 'ultra';
+ if (kind === 'fast') choice.fastMode = true;
+ if (kind === 'unknown') choice.id = 'not-a-route';
+ if (kind === 'owner') h.ownerBoundaryPending = true;
+ const result = await service.updateProfile({ callerSessionId: kind === 'foreign' ? 'ordinary-session' : sessionId,
+ expectedVersion: 1, modelChain: kind === 'duplicate' ? [choice, choice] : [choice] });
+ expect(result).toMatchObject({ ok: false });
+ h.ownerBoundaryPending = false;
+ expect(await invoke('local-db:bots:get', 'bot-1')).toEqual(before);
+ expect(getSelectedNewMakerRoute(h.ownerScopeKey)).toEqual(appDefault);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts b/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts
index 6762e9a386..d810c6dac3 100644
--- a/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts
+++ b/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts
@@ -30,7 +30,7 @@ export function availableAppDefaultModels(input: {
availableAgents: input.availableAgents, availableAgentsLoaded: true,
preferredRoute: route, isModelEnabled: input.enabled });
return valid.length ? [{ id: JSON.stringify([route.harness, route.providerId, route.model]),
- route, efforts: model.efforts }] : [];
+ route, efforts: model.efforts, supportsFastMode: model.supportsFastMode === true }] : [];
}),
));
}
diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
index 3f3677d440..a2b9458930 100644
--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
@@ -1,5 +1,5 @@
import { inspectAppDefaultModel, changeAppDefaultModel } from './appDefaultModelControl.js';
-import type { BotControlState } from '@cindy/mcps';
+import type { BotCapabilityCallbacks, BotControlState } from '@cindy/mcps';
import { and, eq } from 'drizzle-orm';
import { botProfiles, botProfileVersions, botSessionLinks, sessions } from '../localDb/schema.js';
import { getDbClient } from '../localDb/client/current.js';
@@ -271,22 +271,45 @@ export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {
return { ok: false as const, errorCode: 'BOT_STATE_UNAVAILABLE', message: '无法读取当前伙伴状态,请稍后重试' };
}
},
- async updateProfile(input: { callerSessionId: string; expectedVersion: number;
- name?: string; description?: string; identitySource?: string }) {
+ async updateProfile(input: Parameters<NonNullable<BotCapabilityCallbacks['updateProfile']>>[0]) {
try {
const ctx = await context(input.callerSessionId);
if (ctx.version !== input.expectedVersion) throw new Error('Profile changed');
+ let modelChain: BotModelRoute[] | null | undefined;
+ if (input.modelChain === null) modelChain = null;
+ else if (input.modelChain !== undefined) {
+ const { available } = await inspectAppDefaultModel();
+ ctx.assertOwner();
+ if (!input.modelChain.length || input.modelChain.length > 5) throw new Error('Invalid model chain');
+ const seen = new Set<string>();
+ modelChain = input.modelChain.map(selection => {
+ const choice = available.find(item => item.id === selection.id);
+ if (!choice || seen.has(selection.id)
+ || (selection.effort !== undefined && selection.effort !== '' && !choice.efforts.some(effort => effort === selection.effort))
+ || (selection.fastMode === true && !choice.supportsFastMode)) {
+ throw new Error('Model route or settings are unavailable');
+ }
+ seen.add(selection.id);
+ return { ...choice.route,
+ ...(selection.effort !== undefined ? { effort: selection.effort } : {}),
+ ...(selection.fastMode !== undefined ? { fastMode: selection.fastMode } : {}),
+ };
+ });
+ }
ctx.assertOwner();
await updateBotProfile({ id: ctx.botId,
...(input.name !== undefined ? { name: input.name } : {}),
...(input.description !== undefined ? { description: input.description } : {}),
...(input.identitySource !== undefined ? { identitySource: input.identitySource } : {}),
+ ...(modelChain !== undefined ? { capabilities: {
+ modelChainOverride: modelChain, modelOverride: null,
+ } } : {}),
}, input.expectedVersion);
ctx.assertOwner();
return { ok: true as const, effective: 'next-turn' as const };
} catch {
return { ok: false as const, errorCode: 'BOT_PROFILE_UPDATE_FAILED',
- message: '伙伴状态或资料已变化,请重新读取后重试' };
+ message: '伙伴资料已变化,或所选模型及档位不可用;请重新读取伙伴状态和可用型号后重试' };
}
},
/** Read the same metadata before a profile exists; this never joins or executes a capability. */
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 83be0851c4..35098dd83f 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -278,6 +278,13 @@ Session 任务遵守同一套机制与呈现契约:
## 9. 伙伴创建与共同基准
+**维护入口:这里的共享基座变更对所有新旧 teammate 生效,不按名字或模板分支。**
+`apps/desktop/src/main/maker-ipc/teammateGuide.ts` 生成预加载指南与受管 SKILL.md;
+`packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts` 定义共享控制说明与工具契约,
+`apps/desktop/src/main/maker-ipc/botCapabilityService.ts` 连接实际设置服务。
+新增共同能力须同时核对指南、工具注册、运行期挂载和实际服务;不得只改文案或给默认 Cindy 私装 Skill。
+验收必须包含新伙伴和存量伙伴的原聊天,确认模型实际收到新版基座并调用对应工具;不能以文件存在或新伙伴成功代替旧伙伴升级验收。
+
- 首次使用伙伴时自动提供 Cindy;进入伙伴直接打开她的消息流,不增加介绍页或头像首页。
账号级的一次性记录保留在 Bot Home 之外,删除伙伴不会重新添加。升级时已有阵容和历史保持原样,
不猜测缺少 Cindy 是否代表用户曾删除她。没有 Cindy 时,主入口直接显示创建表单,其他伙伴仍从侧栏打开。
@@ -292,6 +299,9 @@ Session 任务遵守同一套机制与呈现契约:
不混入各 Bot 的 `skills/` 学习目录。远端使用同源、按实际工具面裁剪的预加载正文,不传本机路径。
`get_teammate_state` 投影当前 Profile、主任务、模型候选链、记忆开关和能力引用;
`update_teammate_profile` 通过同一个 Profile 写入服务修改用户点名的字段,使用版本校验,下一轮生效。
+ 自身模型使用该接口的 `modelChain` 字段:1–5 个已启用路由组成完整显式链,`null` 清除覆盖并恢复跟随;
+ 保存前重新核对连接、型号开关与思考 / Fast 支持,复用设置页持久化与发送前协调,不另建临时模型状态。
+ 该接口只作用于调用方伙伴,不能指定其他伙伴,也不修改应用默认。
控制工具说明来自同一份 `TEAMMATE_CONTROL_GUIDANCE`;共同基座的预加载正文与 SKILL.md 同源。
任务分工、伙伴消息、创建伙伴、插件连接及学习规则对所有伙伴一致。
- 记忆、Skill、MCP、模型与主任务仍由各自模块保存和校验。模型候选与已选择的能力引用不等于本轮
diff --git a/packages/lizi-mcps/src/__tests__/botCapabilitiesTool.test.ts b/packages/lizi-mcps/src/__tests__/botCapabilitiesTool.test.ts
index 11d2cad629..c98d06713f 100644
--- a/packages/lizi-mcps/src/__tests__/botCapabilitiesTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botCapabilitiesTool.test.ts
@@ -124,3 +124,23 @@ it('exposes app default model operations with bound callers and propagates uncon
expect((await registry.call('set_app_default_model', { id: 'selected', effort: 'medium' })).isError).toBe(true);
expect(setDefaultModel).toHaveBeenCalledWith({ callerSessionId: 'current-bot', id: 'selected', effort: 'medium' });
});
+
+
+it('accepts scoped model chains and reset through the existing profile tool without accepting foreign targets', async () => {
+ const registry = new XdtHelperToolRegistry();
+ const updateProfile = vi.fn(async () => ({ ok: true as const, effective: 'next-turn' as const }));
+ registerBotCapabilityTools(registry, {
+ getSessionContext: () => ({ sessionId: 'self', agentKind: 'codex', workingDir: '/w' }),
+ callbacks: { ...fixture().callbacks, updateProfile },
+ });
+ const modelChain = [{ id: 'enabled-route', effort: 'low', fastMode: false }];
+ for (const bad of [{ modelChain: [] }, { modelChain, botId: 'other' }, { modelChain, session_id: 'other' },
+ { modelChain: [{ id: 'enabled-route', providerId: 'invented' }] }]) {
+ expect((await registry.call('update_teammate_profile', { expectedVersion: 2, ...bad })).isError).toBe(true);
+ }
+ expect(updateProfile).not.toHaveBeenCalled();
+ expect((await registry.call('update_teammate_profile', { expectedVersion: 2, modelChain })).isError).not.toBe(true);
+ expect(updateProfile).toHaveBeenLastCalledWith({ callerSessionId: 'self', expectedVersion: 2, modelChain });
+ expect((await registry.call('update_teammate_profile', { expectedVersion: 3, modelChain: null })).isError).not.toBe(true);
+ expect(updateProfile).toHaveBeenLastCalledWith({ callerSessionId: 'self', expectedVersion: 3, modelChain: null });
+});
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
index 7f2cc7bfa4..fb321d792f 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
@@ -6,7 +6,7 @@ import { errorPayload, okPayload } from "./_payload.js";
export interface BotCapabilityCallbacks {
models?(params: { callerSessionId: string }): Promise<ControlResult<{
current: AppDefaultModelRoute | null;
- available: { id: string; route: AppDefaultModelRoute; efforts: string[] }[];
+ available: { id: string; route: AppDefaultModelRoute; efforts: string[]; supportsFastMode?: boolean }[];
}, string>>;
setDefaultModel?(params: { callerSessionId: string; id: string; effort?: string }): Promise<ControlResult<{
current: AppDefaultModelRoute;
@@ -19,6 +19,7 @@ export interface BotCapabilityCallbacks {
name?: string;
description?: string;
identitySource?: string;
+ modelChain?: { id: string; effort?: string; fastMode?: boolean }[] | null;
}): Promise<ControlResult<{ effective: "next-turn" }, string>>;
list(params: {
callerSessionId: string;
@@ -65,7 +66,7 @@ export interface BotControlState {
export const TEAMMATE_CONTROL_GUIDANCE = [
'Use `get_teammate_state` to inspect your current profile, stable chat, configured model candidates, memory switch and capability references. Candidates and selected references are not proof of the model or tools running this turn; the live runtime and registered tools are authoritative.',
'The references arrays contain optional external grants, not the shared teammate guide or your personal Skill shelf. Empty references do not mean you have no Skills. Use `list_teammate_skills` to inspect personal Skills; report the preloaded shared guide separately.',
- 'Use `update_teammate_profile` only when the user asks to change your name, introduction or identity; read the current version first and patch only the requested fields. Changes apply next turn without replacing memory, Skills, model settings or chat history.',
+ 'Use `update_teammate_profile` when the user asks to change your name, introduction, identity or your own model selection. Read the current version first and patch only the requested fields. For modelChain, first read `get_app_default_model` for enabled route ids and supported effort/Fast settings; supply the complete ordered chain (1–5 routes), preserving existing candidates unless the user asks to replace them. Set modelChain to null to remove your override and follow the application default again. This saves only your profile through the same settings service, persists across restarts, and applies next turn; it never changes the application default, other teammates, personal Skills, memory or chat history. A next-turn save is not proof of the model running this turn.',
'Use `get_capabilities` for application features and UI guidance. It describes the product, not a permission grant or proof that every feature is available here. Use the matching live tool to act, and verify its result before claiming success.',
].join('\n');
@@ -152,11 +153,16 @@ export function registerBotCapabilityTools(
name: z.string().trim().min(1).max(200).optional(),
description: z.string().max(12000).optional(),
identitySource: z.string().max(12000).optional(),
+ modelChain: z.array(z.strictObject({
+ id: z.string().min(1).max(2048).describe('Enabled route id from get_app_default_model.'),
+ effort: z.string().max(64).optional(),
+ fastMode: z.boolean().optional(),
+ })).min(1).max(5).nullable().optional().describe('Complete model chain for this teammate; null removes its override and follows the application default.'),
},
handler: async (input) => {
const callerSessionId = deps.getSessionContext().sessionId;
if (!callerSessionId) return errorPayload("NOT_A_BOT_SESSION", "当前调用未绑定伙伴任务");
- if (input.name === undefined && input.description === undefined && input.identitySource === undefined)
+ if (input.name === undefined && input.description === undefined && input.identitySource === undefined && input.modelChain === undefined)
return errorPayload("INVALID_PARAMS", "请选择要修改的资料");
const result = await deps.callbacks.updateProfile!({ ...input, callerSessionId });
return result.ok ? okPayload({ effective: result.effective }) : errorPayload(result.errorCode, result.message);