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): share guide and isolate personal learning

zqchris4df39c26b75a
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 1c8c60dda7..162c085781 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -1366,7 +1366,7 @@ describe('Bot canonical Session lifecycle', () => {
const allowed = resolveBotAllowedBuiltinPluginIds(policy.catalog, policy.configured);
expect(allowed.includes('xdt_helper')).toBe(helperEnabled);
expect(opts.botProfileContextPrompt?.includes('`start_session_task`')).toBe(helperEnabled);
- expect(opts.botProfileContextPrompt?.includes('`find_bot_capabilities`')).toBe(helperEnabled);
+ expect(opts.botProfileContextPrompt?.includes('`find_teammate_capabilities`')).toBe(helperEnabled);
// Remote Claude/Codex mount helper but not the cindy plugin gateway.
expect(opts.botProfileContextPrompt).not.toContain('ghost_list');
expect(opts.botProfileContextPrompt).not.toContain('ghost_call');
@@ -1396,7 +1396,7 @@ describe('Bot canonical Session lifecycle', () => {
}],
});
- expect(opts.botProfileContextPrompt).toContain('`find_bot_capabilities`');
+ expect(opts.botProfileContextPrompt).toContain('`find_teammate_capabilities`');
expect(opts.botProfileContextPrompt).toContain('ghost_list');
expect(opts.botProfileContextPrompt).toContain('ghost_call');
});
@@ -1542,6 +1542,11 @@ describe('Bot canonical Session lifecycle', () => {
await hydrateBotProfileRuntime(opts, {
listSkills: async () => [],
listOwnSkills: async ({ botId }) => ({
+ baseline: { pluginRoot: '/userdata/managed-teammate-skills/v1', skill: {
+ name: 'teammate-guide', description: 'Shared baseline',
+ path: '/userdata/managed-teammate-skills/v1/skills/teammate-guide',
+ filePath: '/userdata/managed-teammate-skills/v1/skills/teammate-guide/SKILL.md',
+ } },
pluginRoot: `/userdata/bot-skills/${botId}`,
skills: [{
name: 'weekly-report',
@@ -1553,6 +1558,9 @@ describe('Bot canonical Session lifecycle', () => {
}, { persistSnapshot: false });
expect(opts.botRuntimeProfile?.skillPolicy.ownSkills).toEqual([
+ { name: 'teammate-guide', description: 'Shared baseline',
+ path: '/userdata/managed-teammate-skills/v1/skills/teammate-guide',
+ filePath: '/userdata/managed-teammate-skills/v1/skills/teammate-guide/SKILL.md' },
{
name: 'weekly-report',
description: 'How I put the weekly report together',
@@ -1562,6 +1570,7 @@ describe('Bot canonical Session lifecycle', () => {
]);
// Claude Code 只会开关它自己发现到的 Skill,所以还要给它一个本地 plugin 根。
expect(opts.botRuntimeProfile?.skillPolicy.ownSkillPluginRoots).toEqual([
+ '/userdata/managed-teammate-skills/v1',
'/userdata/bot-skills/bot-1',
]);
// 用户配的 Skill 那一栏不受影响。
@@ -1651,7 +1660,7 @@ describe('Bot canonical Session lifecycle', () => {
listSkills: async () => [],
listOwnSkills: async () => ({ pluginRoot: '/userdata/bot-skills/bot-1', skills: [] }),
});
- expect(initial.botProfileContextPrompt).toContain('save_bot_skill');
+ expect(initial.botProfileContextPrompt).toContain('save_teammate_skill');
await markBotProfileRuntimeApplied(first!);
const resumed = makeOpts();
diff --git a/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts b/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts
index 35163a19ab..f94e4be3fe 100644
--- a/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts
+++ b/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts
@@ -50,6 +50,11 @@ export interface NewMakerDraftSnapshot {
let cache: NewMakerDraftSnapshot | null = null;
let selectedRouteOwner: string | undefined;
+const defaultListeners = new Set<(confirmedRequestId?: string) => void>();
+export function subscribeNewMakerDefaults(listener: (confirmedRequestId?: string) => void): () => void {
+ defaultListeners.add(listener);
+ return () => { defaultListeners.delete(listener); };
+}
export interface WorkerCreationPrefsSnapshot {
workerPermissionMode: OrcaWorkerPermissionMode;
@@ -74,9 +79,10 @@ export type ProviderModelMemorySnapshot = Record<
let providerMemoryCache: ProviderModelMemorySnapshot | null = null;
/** Renderer push handler 调; 整体替换缓存 (而不是合并), 跟 source of truth 对齐。 */
-export function setNewMakerDraftCache(snapshot: NewMakerDraftSnapshot, ownerScope?: string): void {
+export function setNewMakerDraftCache(snapshot: NewMakerDraftSnapshot, ownerScope?: string, confirmedRequestId?: string): void {
cache = snapshot;
selectedRouteOwner = ownerScope;
+ for (const listener of defaultListeners) listener(confirmedRequestId);
}
/** One owner-fenced mirror for both ordinary task defaults and Bot defaults. */
@@ -87,7 +93,7 @@ export function syncNewMakerDraftCache(
boundaryPending: boolean,
): boolean {
if (boundaryPending || !raw || typeof raw !== 'object' || Array.isArray(raw)) return false;
- const p = raw as Partial<NewMakerDraftSnapshot> & { ownerStamp?: unknown };
+ const p = raw as Partial<NewMakerDraftSnapshot> & { ownerStamp?: unknown; appDefaultModelRequestId?: unknown };
if (!isDataOwnerPushStamp(p.ownerStamp)
|| p.ownerStamp.dataOwnerId !== activeOwner.dataOwnerId
|| p.ownerStamp.ownerGeneration !== activeOwner.ownerGeneration) return false;
@@ -100,7 +106,8 @@ export function syncNewMakerDraftCache(
fastModeByModel: p.fastModeByModel!,
effortByModel: p.effortByModel!,
worktreeEnabled: p.worktreeEnabled === true,
- }, ownerScope);
+ }, ownerScope, typeof p.appDefaultModelRequestId === 'string' && p.appDefaultModelRequestId.length <= 64
+ ? p.appDefaultModelRequestId : undefined);
return true;
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts
new file mode 100644
index 0000000000..506e200e7c
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts
@@ -0,0 +1,71 @@
+import type { ProviderView } from '@cindy/model-providers';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { changeAppDefaultModel, configureAppDefaultModelSelection, inspectAppDefaultModel } from '../appDefaultModelControl';
+import { setNewMakerDraftCache } from '../../maker-host/newMakerDefaultsCache';
+
+const host = vi.hoisted(() => ({ owner: 'owner:1', enabled: true, connected: true, agents: ['codex'],
+ providers: vi.fn() }));
+vi.mock('../../maker-host/index.js', () => ({ getMakerIfReady: () => ({ listAvailableAgents: () => host.agents }) }));
+vi.mock('../../maker-host/createDesktopProviderService.js', () => ({
+ getDesktopProviderService: () => ({ listProviders: host.providers }),
+}));
+vi.mock('../../maker-host/model-visibility-mirror.js', () => ({
+ waitForModelVisibilityMirror: async () => {}, getModelVisibilityOverride: (_a: string, _p: string, model: string) => model === 'luna' && host.enabled,
+}));
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => host.owner, isAppSessionBoundaryPending: () => false,
+ getActiveDataOwnerPushStamp: () => ({ dataOwnerId: 'owner', ownerGeneration: 1 }),
+}));
+const route = { harness: 'codex' as const, providerId: 'openai', model: 'luna', effort: 'medium', fastMode: false };
+const mirror = (selectedRoute = route, requestId?: string) => setNewMakerDraftCache({ selectedRoute,
+ lastByVendor: {}, fastModeByModel: {}, effortByModel: {} }, host.owner, requestId);
+const id = JSON.stringify(['codex', 'openai', 'luna']);
+
+beforeEach(() => {
+ host.owner = 'owner:1'; host.enabled = true; host.connected = true; host.agents = ['codex'];
+ host.providers.mockImplementation(async () => [{ id: 'openai', source: 'builtin', connected: host.connected,
+ models: { codex: ['luna', 'sol'].map(model => ({ id: model, status: 'active', mode: 'chat', defaultEnabled: true,
+ efforts: ['low', 'medium'], defaultEffort: 'medium' })) } }] as ProviderView[]);
+ mirror();
+});
+afterEach(() => { configureAppDefaultModelSelection(null); vi.useRealTimers(); });
+
+describe('Bot control of the real Cindy default', () => {
+ it('only lists the enabled connected model, even if another model is in the catalog', async () => {
+ expect(await inspectAppDefaultModel()).toMatchObject({ current: route, available: [{ id, route }] });
+ expect((await inspectAppDefaultModel()).available).toHaveLength(1);
+ });
+ it.each(['disabled', 'disconnected', 'missing harness'] as const)('rejects a stale selection that is now %s', async failure => {
+ await inspectAppDefaultModel();
+ if (failure === 'disabled') host.enabled = false;
+ if (failure === 'disconnected') host.connected = false;
+ if (failure === 'missing harness') host.agents = [];
+ const dispatch = vi.fn(); configureAppDefaultModelSelection(dispatch);
+ await expect(changeAppDefaultModel(id)).rejects.toThrow();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+ it('waits for the real owner-fenced mirror instead of mutating the cache itself', async () => {
+ const dispatch = vi.fn(selection => mirror(selection.route, selection.requestId));
+ configureAppDefaultModelSelection(dispatch);
+ expect(await changeAppDefaultModel(id, 'low')).toEqual({ current: { ...route, effort: 'low' } });
+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ expectedRoute: route,
+ ownerStamp: { dataOwnerId: 'owner', ownerGeneration: 1 } }));
+ });
+ it('does not claim success when an unrelated mirror matches but the renderer never confirms this write', async () => {
+ vi.useFakeTimers(); configureAppDefaultModelSelection(() => mirror());
+ const result = expect(changeAppDefaultModel(id)).rejects.toThrow('未确认');
+ await vi.advanceTimersByTimeAsync(5001); await result;
+ });
+ it('rejects an owner switch during catalog reading before dispatch', async () => {
+ const providers = await host.providers();
+ host.providers.mockImplementation(async () => { host.owner = 'owner:2'; return providers; });
+ const dispatch = vi.fn(); configureAppDefaultModelSelection(dispatch);
+ await expect(changeAppDefaultModel(id)).rejects.toThrow('账号');
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+ it('rejects an unsupported effort without changing anything', async () => {
+ const dispatch = vi.fn(); configureAppDefaultModelSelection(dispatch);
+ await expect(changeAppDefaultModel(id, 'ultra')).rejects.toThrow('不可用');
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts
index 2f8a9e3ee8..df627bb416 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botInvitation.test.ts
@@ -164,7 +164,7 @@ describe('companion invitation with SQLite and real skill files', () => {
});
it.each(['cindy', 'dash', 'lizi'])(
- 'prepares %s from bundled skills without a model request',
+ 'prepares %s without a model request or role-specific Skill pack',
async (templateId) => {
seed({}, { templateId });
queueBotInvitation('bot-1');
@@ -172,7 +172,7 @@ describe('companion invitation with SQLite and real skill files', () => {
expect(h.generate).not.toHaveBeenCalled();
const folder = await readBotProfileFolder(h.root, 'bot-1');
expect(folder.identitySource).toContain('性格与聊天习惯');
- expect((await fs.readdir(path.join(h.root, 'bots', 'bot-1', 'skills'))).length).toBe(templateId === 'cindy' ? 1 : 3);
+ expect((await fs.readdir(path.join(h.root, 'bots', 'bot-1', 'skills'))).length).toBe(0);
},
);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts
index 5ba9d06ca8..3d944059c2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botProfileRuntime.test.ts
@@ -54,11 +54,11 @@ describe('Bot Profile runtime prompt', () => {
it('uses direct Bot tools and avoids whole-surface discovery loops', () => {
const prompt = buildBotCapabilityContextPrompt();
- expect(prompt).toContain('You are running as a Cindy Bot');
- expect(prompt).toContain('Use direct Bot tools');
- expect(prompt).toContain('`find_bot_capabilities`');
- expect(prompt).toContain('`set_bot_capability`');
- expect(prompt).toContain('`cindy` (`ghost_list`, `ghost_info`, `ghost_call`)');
+ expect(prompt).toContain('You are a teammate with a durable profile');
+ expect(prompt).toContain('Use direct teammate tools');
+ expect(prompt).toContain('`find_teammate_capabilities`');
+ expect(prompt).toContain('`set_teammate_capability`');
+ expect(prompt).toContain('installed-plugin gateway (`ghost_list`, `ghost_info`, `ghost_call`)');
expect(prompt).toContain('New mounts take effect next turn in this same task');
expect(prompt).toContain('`start_session_task`');
expect(prompt).toContain('proactively start independent tasks for coding and medium or large work');
@@ -69,7 +69,7 @@ describe('Bot Profile runtime prompt', () => {
expect(prompt).toContain('do not repeatedly list the whole tool surface');
expect(prompt).toContain('Completion returns automatically');
expect(prompt).toContain('It is not a task and has no progress or cancellation');
- expect(prompt).toContain('does not rewrite another Bot\'s identity');
+ expect(prompt).toContain('does not rewrite another teammate\'s identity');
expect(prompt).toContain('offer either a message or a tracked Session task');
expect(prompt).not.toContain('delegate_to_bot');
expect(prompt).not.toContain('list_bot_delegations');
@@ -77,19 +77,19 @@ describe('Bot Profile runtime prompt', () => {
it('does not advertise helper discovery or delegation when the target cannot mount it', () => {
const prompt = buildBotCapabilityContextPrompt({ helperAvailable: false });
- expect(prompt).toContain('durable Profile');
- expect(prompt).toContain('not a diary of every turn');
+ expect(prompt).toContain('durable profile');
+ expect(prompt).toContain('Respect the user’s memory switch');
expect(prompt).not.toContain('`list_tools`');
expect(prompt).not.toContain('discover other available Bots');
expect(prompt).not.toContain('`start_session_task`');
- expect(prompt).not.toContain('`save_bot_skill`');
+ expect(prompt).not.toContain('`save_teammate_skill`');
expect(prompt).not.toContain('ghost_list');
});
it('keeps helper capability tools when cindy is not on the remote tool surface', () => {
const prompt = buildBotCapabilityContextPrompt({ helperAvailable: true, cindyAvailable: false });
- expect(prompt).toContain('`find_bot_capabilities`');
- expect(prompt).toContain('`set_bot_capability`');
+ expect(prompt).toContain('`find_teammate_capabilities`');
+ expect(prompt).toContain('`set_teammate_capability`');
expect(prompt).toContain('`start_session_task`');
expect(prompt).toContain('do not repeatedly list the whole tool surface');
expect(prompt).not.toContain('ghost_list');
@@ -100,25 +100,25 @@ describe('Bot Profile runtime prompt', () => {
it('keeps learned Skills deliberate instead of writing a diary of every turn', () => {
const prompt = buildBotCapabilityContextPrompt();
expect(prompt).toContain('Use a `learned-` name only for a stable reusable working habit');
- expect(prompt).toContain('not a diary of every turn');
- expect(prompt).toContain('instead of waiting for repetition');
- expect(prompt).toContain('after that first verified success');
- expect(prompt).toContain('Never start a background review worker');
+ expect(prompt).toContain('Respect the user’s memory switch');
+ expect(prompt).toContain('without waiting for a request to remember');
+ expect(prompt).toContain('One verified reusable success is enough');
+ expect(prompt).toContain('not an extra learning model or background review worker');
expect(prompt).toContain('never for a one-off conclusion');
});
/**
- * 批次 ζ:「TA 学会的」列的是**真技能**,来源是伙伴自己调 `save_bot_skill`。
+ * 批次 ζ:「TA 学会的」列的是**真技能**,来源是伙伴自己调 `save_teammate_skill`。
* 这条约定掉了,技能就永远长不出来 —— 判断「这次做法值不值得沉淀」是语言理解
* 问题,代码判不了(maker-core-and-agent-behavior.md §2 的分界)。
*/
it('only saves a verified reusable workflow as a real Skill', () => {
const prompt = buildBotCapabilityContextPrompt();
- expect(prompt).toContain('`save_bot_skill`');
- expect(prompt).toContain('`list_bot_skills`');
+ expect(prompt).toContain('`save_teammate_skill`');
+ expect(prompt).toContain('`list_teammate_skills`');
expect(prompt).toContain('only after the workflow has succeeded');
expect(prompt).toContain('reusable steps are known');
- expect(prompt).toContain('mounted from the next task onward');
+ expect(prompt).toContain('at a safe turn boundary in this same chat');
});
it('keeps the same affirmative delegation guidance beside the default and every preset SOUL', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillService.test.ts
index b92b5a92bb..9210f954d0 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botSkillService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillService.test.ts
@@ -8,7 +8,7 @@
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
collectBotOwnSkillMounts,
@@ -42,6 +42,22 @@ const SAVE = {
};
describe('saveBotSkillForSession', () => {
+ it('queues the canonical chat for safe refresh after a delegated task learns a Skill', async () => {
+ const requestRefresh = vi.fn(() => true);
+ const result = await saveBotSkillForSession(SAVE, { ...depsFor('bot-1'), requestRefresh,
+ resolveBotId: async () => ({ ok: true, botId: 'bot-1', canonicalSessionId: 'main-chat' }),
+ });
+ expect(result).toMatchObject({ ok: true, effective: 'next-turn' });
+ expect(requestRefresh).toHaveBeenCalledExactlyOnceWith('main-chat', 'resource');
+ expect(await readBotSkillForBot('bot-1', 'weekly-report', { userDataDir })).not.toBeNull();
+ });
+
+ it('does not request a runtime refresh when saving fails', async () => {
+ const requestRefresh = vi.fn(() => true);
+ expect(await saveBotSkillForSession({ ...SAVE, name: '无有效名字' }, { ...depsFor('bot-1'), requestRefresh }))
+ .toMatchObject({ ok: false });
+ expect(requestRefresh).not.toHaveBeenCalled();
+ });
it('tells the model the skill only takes effect next session', async () => {
const result = await saveBotSkillForSession(SAVE, depsFor('bot-1'));
@@ -114,6 +130,21 @@ describe('saveBotSkillForSession', () => {
});
describe('设置页与会话挂载读的是同一份磁盘事实', () => {
+ it('mounts exactly the same managed baseline for Cindy and a fresh named Bot, outside learned shelves', async () => {
+ const cindy = await collectBotOwnSkillMounts('bot-cindy', { userDataDir });
+ const fresh = await collectBotOwnSkillMounts('bot-fresh', { userDataDir });
+ expect(cindy.baseline).toEqual(fresh.baseline);
+ expect(cindy.baseline.skill.name).toBe('teammate-guide');
+ expect(cindy.baseline.pluginRoot).not.toContain('bot-cindy');
+ const source = await fs.readFile(fresh.baseline.skill.filePath, 'utf8');
+ for (const tool of ['start_session_task', 'send_to_agent', 'create_teammate', 'get_app_default_model', 'set_app_default_model', 'save_teammate_skill', 'ghost_call'])
+ expect(source).toContain(tool);
+ expect(cindy.skills).toEqual([]);
+ expect(fresh.skills).toEqual([]);
+ await saveBotSkillForSession(SAVE, depsFor('bot-fresh'));
+ expect((await collectBotOwnSkillMounts('bot-cindy', { userDataDir })).skills).toEqual([]);
+ expect((await collectBotOwnSkillMounts('bot-fresh', { userDataDir })).baseline).toEqual(cindy.baseline);
+ });
it('exposes every saved skill as a mountable directory plus a CC plugin root', async () => {
await saveBotSkillForSession(SAVE, depsFor('bot-1'));
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSystemPrompt.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSystemPrompt.test.ts
index 12e3854974..d55027ea21 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botSystemPrompt.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSystemPrompt.test.ts
@@ -100,7 +100,7 @@ describe('稳定层:能力必须写进提示词', () => {
);
expect(all).toContain('你记得住事');
expect(all).toContain('第一次明确说出一条稳定偏好');
- expect(all).toContain('save_bot_skill');
+ expect(all).toContain('save_teammate_skill');
expect(all).toContain('第一次验证完就');
expect(all).toContain('开后台任务,也可以给伙伴发消息');
expect(all).toContain('start_session_task');
@@ -118,7 +118,7 @@ describe('稳定层:能力必须写进提示词', () => {
expect(all).not.toContain('list_tools');
const none = buildBotStableTier(input());
- expect(none).not.toContain('save_bot_skill');
+ expect(none).not.toContain('save_teammate_skill');
expect(none).not.toContain('create_teammate');
expect(none).not.toContain('make_pptx');
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTemplateSkillSeed.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTemplateSkillSeed.test.ts
index 55ce3c64cc..56e68483ab 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botTemplateSkillSeed.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTemplateSkillSeed.test.ts
@@ -17,24 +17,10 @@ afterEach(async () => {
});
describe('seedBotTemplateSkills', () => {
- it.each([
- ['cindy', 'help-with-cindy', '使用 Cindy 完成工作'],
- ['dash', 'make-executive-decisions', '高管决策'],
- ['lizi', 'deliver-engineering-changes', '开发交付'],
- ] as const)(
- 'installs the %s preset as a real Bot-owned Skill',
- async (templateId, slug, name) => {
- const result = await seedBotTemplateSkills(userDataDir, `bot-${templateId}`, templateId);
-
- expect(result.completedNow).toBe(true);
- expect(result.skills).toHaveLength(templateId === 'cindy' ? 1 : 3);
- expect(result.skills[0]?.created).toBe(true);
- expect(await readBotSkill(userDataDir, `bot-${templateId}`, slug)).toMatchObject({
- name,
- description: expect.any(String),
- body: expect.stringContaining(`# ${name}`),
- });
- expect(result.skills.some(({ record }) => record.body.includes(templateId === 'cindy' ? '连接' : '文档工具'))).toBe(true);
+ it.each(['cindy', 'dash', 'lizi'] as const)(
+ 'does not seed a role-specific capability pack for %s', async (templateId) => {
+ expect(await seedBotTemplateSkills(userDataDir, `bot-${templateId}`, templateId))
+ .toEqual({ completedNow: false, skills: [] });
},
);
@@ -47,7 +33,7 @@ describe('seedBotTemplateSkills', () => {
});
const result = await seedBotTemplateSkills(userDataDir, 'bot-lizi', 'lizi');
- expect(result.skills[0]?.created).toBe(false);
+ expect(result.skills).toEqual([]);
expect((await readBotSkill(userDataDir, 'bot-lizi', 'deliver-engineering-changes'))?.body).toBe(
'先读我的团队约定。',
);
@@ -64,17 +50,17 @@ describe('seedBotTemplateSkills', () => {
expect(await readBotSkill(userDataDir, 'bot-dash', 'make-executive-decisions')).toBeNull();
});
- it('adds newly bundled Skills without restoring a legacy Skill the user deleted', async () => {
+ it('preserves legacy deletion markers without moving the shared baseline into personal Skills', async () => {
const root = botSkillRootDir(userDataDir, 'bot-cindy');
await fs.mkdir(root, { recursive: true });
await fs.writeFile(path.join(root, '.template-skills-cindy.seeded'), 'cindy\n');
const result = await seedBotTemplateSkills(userDataDir, 'bot-cindy', 'cindy');
- expect(result.skills).toHaveLength(1);
+ expect(result.skills).toHaveLength(0);
expect(await readBotSkill(userDataDir, 'bot-cindy', 'everyday-work-coordination')).toBeNull();
expect(
await readBotSkill(userDataDir, 'bot-cindy', 'help-with-cindy'),
- ).not.toBeNull();
+ ).toBeNull();
});
});
diff --git a/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts b/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts
new file mode 100644
index 0000000000..6762e9a386
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts
@@ -0,0 +1,93 @@
+import { randomUUID } from 'node:crypto';
+import { isModelVisible, type ProviderView } from '@cindy/model-providers';
+import { defaultBotModelChain } from '../../shared/botDefaultModelChain.js';
+import type { BotModelRoute } from '../../shared/botModelChain.js';
+import { sameModelRoute, type AppDefaultModelSelection } from '../../shared/appDefaultModelSelection.js';
+import { activeOwnerScopeKey, getActiveDataOwnerPushStamp, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
+import { getMakerIfReady } from '../maker-host/index.js';
+import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../maker-host/model-visibility-mirror.js';
+import { getSelectedNewMakerRoute, subscribeNewMakerDefaults } from '../maker-host/newMakerDefaultsCache.js';
+
+/** A narrow bridge to the existing renderer-owned default, never a second settings file. */
+let dispatchSelection: ((selection: AppDefaultModelSelection) => void) | null = null;
+export function configureAppDefaultModelSelection(dispatch: typeof dispatchSelection): void {
+ dispatchSelection = dispatch;
+}
+
+export function availableAppDefaultModels(input: {
+ providers: readonly ProviderView[];
+ availableAgents: ReadonlySet<'cc' | 'codex' | 'pi'>;
+ enabled: NonNullable<Parameters<typeof defaultBotModelChain>[0]['isModelEnabled']>;
+}) {
+ return input.providers.flatMap(provider => (['claude-code', 'codex', 'pi'] as const).flatMap(agent =>
+ (provider.models[agent] ?? []).flatMap(model => {
+ const route: BotModelRoute = { harness: agent === 'claude-code' ? 'claude' : agent,
+ providerId: provider.id, model: model.id,
+ effort: model.defaultEffort && model.efforts.includes(model.defaultEffort) ? model.defaultEffort : '',
+ fastMode: false };
+ const valid = defaultBotModelChain({ providers: input.providers, providersLoading: false,
+ 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 }] : [];
+ }),
+ ));
+}
+
+async function readSelection() {
+ const owner = activeOwnerScopeKey();
+ const assertOwner = () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner) throw new Error('账号已变化,请重新查询');
+ };
+ assertOwner();
+ await waitForModelVisibilityMirror();
+ const providers = await getDesktopProviderService().listProviders({ allowSideEffects: false });
+ assertOwner();
+ const available = availableAppDefaultModels({ providers,
+ availableAgents: new Set((getMakerIfReady()?.listAvailableAgents() ?? []).map(agent => agent === 'claude-code' ? 'cc' : agent)),
+ enabled: (agent, providerId, model) => isModelVisible(getModelVisibilityOverride(agent, providerId, model.id), model.defaultEnabled),
+ });
+ return { owner, assertOwner, current: getSelectedNewMakerRoute(owner) ?? null, available };
+}
+
+export async function inspectAppDefaultModel() {
+ const { current, available } = await readSelection();
+ return { current, available };
+}
+
+/** Wait for a fresh owner-fenced mirror after the real setter persisted the selected route. */
+export async function changeAppDefaultModel(id: string, effort?: string, assertCaller: () => void = () => {}) {
+ assertCaller();
+ const state = await readSelection();
+ assertCaller();
+ const choice = state.available.find(item => item.id === id);
+ if (!choice || (effort !== undefined && effort !== '' && !choice.efforts.some(value => value === effort)))
+ throw new Error('该模型或思考档不可用,请重新查询已启用模型');
+ const route = { ...choice.route, ...(effort !== undefined ? { effort } : {}) };
+ if (!dispatchSelection) throw new Error('客户端默认模型设置入口尚未就绪');
+ state.assertOwner();
+ assertCaller();
+ const dispatch = dispatchSelection;
+ await new Promise<void>((resolve, reject) => {
+ const requestId = randomUUID();
+ const expiresAt = Date.now() + 5000;
+ const timer = setTimeout(() => { off(); reject(new Error('未确认默认模型已保存,请查询当前设置后重试')); }, 5000);
+ const off = subscribeNewMakerDefaults((confirmedRequestId) => {
+ try {
+ state.assertOwner();
+ if (confirmedRequestId !== requestId) return;
+ if (!sameModelRoute(getSelectedNewMakerRoute(state.owner), route)) return;
+ clearTimeout(timer); off(); resolve();
+ } catch (error) { clearTimeout(timer); off(); reject(error); }
+ });
+ try {
+ dispatch({ requestId, route, expectedRoute: state.current, ownerStamp: getActiveDataOwnerPushStamp(), expiresAt });
+ } catch (error) { clearTimeout(timer); off(); reject(error); }
+ });
+ state.assertOwner();
+ assertCaller();
+ const current = getSelectedNewMakerRoute(state.owner);
+ if (!sameModelRoute(current, route)) throw new Error('默认模型已被其他操作改变,请重新查询');
+ return { current: route };
+}
diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
index 78eb5d64cf..3f3677d440 100644
--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts
@@ -1,3 +1,4 @@
+import { inspectAppDefaultModel, changeAppDefaultModel } from './appDefaultModelControl.js';
import type { BotControlState } from '@cindy/mcps';
import { and, eq } from 'drizzle-orm';
import { botProfiles, botProfileVersions, botSessionLinks, sessions } from '../localDb/schema.js';
@@ -229,6 +230,26 @@ async function selectBotCapability(input: Input & { id: string; joined: boolean
/** Host callbacks are bound at initialization, without importing the host singleton. */
export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {
return {
+ async models(input: { callerSessionId: string }) {
+ try {
+ const ctx = await context(input.callerSessionId);
+ const selection = await inspectAppDefaultModel();
+ ctx.assertOwner();
+ return { ok: true as const, ...selection };
+ } catch {
+ return { ok: false as const, errorCode: 'MODEL_SETTINGS_UNAVAILABLE', message: '无法读取当前用户的默认模型和可用型号' };
+ }
+ },
+ async setDefaultModel(input: { callerSessionId: string; id: string; effort?: string }) {
+ try {
+ const ctx = await context(input.callerSessionId);
+ const result = await changeAppDefaultModel(input.id, input.effort, ctx.assertOwner);
+ ctx.assertOwner();
+ return { ok: true as const, ...result };
+ } catch {
+ return { ok: false as const, errorCode: 'MODEL_DEFAULT_NOT_CONFIRMED', message: '默认模型未确认保存;型号可能已停用、账号或选择已变化,请重新查询当前设置。' };
+ }
+ },
async inspect(input: { callerSessionId: string }) {
try {
const ctx = await context(input.callerSessionId);
diff --git a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
index b6a3951c09..ed505abe74 100644
--- a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
+++ b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
@@ -1,4 +1,4 @@
-import { BOT_CONTROL_GUIDANCE } from '@cindy/mcps';
+import { buildTeammateGuide as buildBotCapabilityContextPrompt } from './teammateGuide.js';
import { and, desc, eq, inArray } from 'drizzle-orm';
import { buildBotMemoryScopeKey } from '@cindy/maker-core';
import { createHash, randomUUID } from 'node:crypto';
@@ -125,6 +125,7 @@ export interface BotProfileRuntimeDeps {
*/
listOwnSkills?: (input: { botId: string }) => Promise<{
pluginRoot: string;
+ baseline?: { pluginRoot: string; skill: { name: string; description: string; path: string; filePath: string } };
skills: { name: string; description: string; path: string; filePath?: string }[];
}>;
readSkillSource?: (input: {
@@ -299,35 +300,7 @@ export function buildBotProfileContextPrompt(displayName: string): string {
* 设置页不再为它维护第二套「成长」分类;记忆和技能的实际存储与工具契约才是真相源。
* 文本是常量,不含会话变量,因此 prompt 前缀保持稳定,不影响缓存率。
*/
-export function buildBotCapabilityContextPrompt(
- options: { helperAvailable?: boolean; cindyAvailable?: boolean } = {},
-): string {
- const helperAvailable = options.helperAvailable !== false;
- // cindy / ghost_* live on the local builtin gateway. SSH Claude/Codex only
- // inject collab, memory and helper (REMOTE_ALLOWED_SERVER_NAMES); advertising
- // plugins there would tell the model to call tools it cannot reach. Remote Pi
- // tunnels cindy, so keep plugin guidance there.
- const cindyAvailable = options.cindyAvailable !== false;
- const pluginGuidance = cindyAvailable
- ? ' Installed plugins are a separate discovery surface from Skill/MCP/toolset references. An empty capability search does not mean no plugin can do the work. Before declaring a connected-service task unavailable, inspect the relevant installed plugin. Installed plugins are available on demand through `cindy` (`ghost_list`, `ghost_info`, `ghost_call`) under their existing permissions. When a plugin returns SETUP_REQUIRED with an authorization request id, its login/configuration card is already in this chat and the requested tool has not run. End the turn and wait for the Host authorization-completed notification, then continue the original work through the live plugin tool. Do not poll, ask for credentials in chat, invent login links, or treat login as task execution approval. The phone can display/cancel the card; connection and secret entry happen on the trusted desktop.'
- : '';
- return [
- '## Cindy Bot Runtime',
- 'You are running as a Cindy Bot with a durable Profile. This task is one active runtime of that Bot, not an ordinary standalone task.',
- ...(helperAvailable ? [
- BOT_CONTROL_GUIDANCE,
- `Use direct Bot tools for your own memory, Skills and teammates. When work needs another capability, use \`find_bot_capabilities\` in the helper bots category to search existing Skills, MCP connections or built-in tools, then \`set_bot_capability\` to join it. References reuse Cindy installations and authorization; do not copy credentials or edit shared sources. New mounts take effect next turn in this same task.${pluginGuidance} Discover only what the work needs; do not repeatedly list the whole tool surface.`,
- "A real Cindy background task is a standalone Session in the user's task list. Follow the workload split in the `start_session_task` guidance: handle short simple work yourself and proactively start independent tasks for coding and medium or large work. Do not wait for the user to ask for delegation. Use `check_session_task`, `message_session_task`, and `stop_session_task` to control that same task when needed. Completion returns automatically; you remain responsible for reviewing and presenting the result.",
- 'Use `send_to_agent` only to send one bounded asynchronous message to a named teammate. It is not a task and has no progress or cancellation. Never use a teammate named Cindy as a substitute for `start_session_task`.',
- "A teammate message does not rewrite another Bot's identity or make that Bot obey. If the user asks for obedience or control, explain this boundary and offer either a message or a tracked Session task, whichever matches the work.",
- ] : []),
- 'Long-term memory and your own Skills are deliberate, user-visible records, not a diary of every turn. When the user first states a specific stable preference, correction, or long-lived background fact, remember it immediately instead of waiting for repetition or sending the user to Settings. When one complete workflow succeeds in a real task and is clearly reusable, save it as a Skill after that first verified success. Ask only when long-term value is genuinely unclear. Never start a background review worker just to create memory or Skills.',
- 'Before writing memory, search for an existing record and update it instead of creating a duplicate. Use a `learned-` name only for a stable reusable working habit, never for a one-off conclusion, temporary path, guess, or unverified step.',
- ...(helperAvailable ? [
- 'Before `save_bot_skill`, call `list_bot_skills`. Save or update a Skill only after the workflow has succeeded and the reusable steps are known. A saved Skill is mounted from the next task onward and remains visible, editable, and removable by the user.',
- ] : []),
- ].join('\n');
-}
+export { buildTeammateGuide as buildBotCapabilityContextPrompt } from './teammateGuide.js';
/**
* 把 Bot Home 的 workspace 补进会话可写面。整个 Home 不能直接可写:根部留有
@@ -719,17 +692,20 @@ export async function hydrateBotProfileRuntime(
冻上,等于「一学会就再也 resume 不了」。
*/
let ownSkills: { name: string; description: string; path: string; filePath?: string }[] = [];
- let ownSkillPluginRoot: string | null = null;
+ let ownSkillPluginRoots: string[] = [];
// SSH remote 会话的 harness 跑在远端文件系统上,本机 userData 里的技能目录
// 在那边不存在 —— 与其挂一串打不开的路径,不如这类会话直接不挂。
if (deps.listOwnSkills && !opts.remoteHostId) {
try {
const own = await deps.listOwnSkills({ botId: row.botId });
- ownSkills = own.skills;
- ownSkillPluginRoot = own.skills.length > 0 ? own.pluginRoot : null;
+ ownSkills = [...(own.baseline && row.role === 'canonical' ? [own.baseline.skill] : []), ...own.skills];
+ ownSkillPluginRoots = [
+ ...(own.baseline && row.role === 'canonical' ? [own.baseline.pluginRoot] : []),
+ ...(own.skills.length > 0 ? [own.pluginRoot] : []),
+ ];
} catch {
ownSkills = [];
- ownSkillPluginRoot = null;
+ ownSkillPluginRoots = [];
}
}
let mcpCatalog: BotMcpCatalogItem[] = [];
@@ -923,7 +899,7 @@ export async function hydrateBotProfileRuntime(
})),
}
: {}),
- ...(ownSkillPluginRoot ? { ownSkillPluginRoots: [ownSkillPluginRoot] } : {}),
+ ...(ownSkillPluginRoots.length ? { ownSkillPluginRoots } : {}),
},
mcpPolicy: {
mode: runtimeMcpMode,
diff --git a/apps/desktop/src/main/maker-ipc/botRuntimeEpochRefreshSignal.ts b/apps/desktop/src/main/maker-ipc/botRuntimeEpochRefreshSignal.ts
index d0ee1229d6..b27cdb93d5 100644
--- a/apps/desktop/src/main/maker-ipc/botRuntimeEpochRefreshSignal.ts
+++ b/apps/desktop/src/main/maker-ipc/botRuntimeEpochRefreshSignal.ts
@@ -18,6 +18,8 @@ export function configureBotRuntimeEpochRefreshRequest(
export function requestBotRuntimeEpochRefresh(
sessionId: string,
reason: BotRuntimeEpochRefreshReason,
-): void {
- requestRefresh?.(sessionId, reason);
+): boolean {
+ if (!requestRefresh) return false;
+ requestRefresh(sessionId, reason);
+ return true;
}
diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.ts
index 50c1017d4e..81bccb2886 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts
@@ -8,6 +8,8 @@
*/
import { app } from 'electron';
+import { collectTeammateGuideMount } from './teammateGuideStore.js';
+import { requestBotRuntimeEpochRefresh } from './botRuntimeEpochRefreshSignal.js';
import { and, eq } from 'drizzle-orm';
import { migrateBotSkillsIntoProfileFolder } from './botProfileFolder.js';
@@ -56,8 +58,9 @@ export interface BotSkillServiceDeps {
userDataDir?: string;
ownerScopeKey?: () => string;
ownerBoundaryPending?: () => boolean;
+ requestRefresh?: typeof requestBotRuntimeEpochRefresh;
resolveBotId?: (callerSessionId: string) => Promise<
- | { ok: true; botId: string }
+ | { ok: true; botId: string; canonicalSessionId?: string | null }
| { ok: false; errorCode: string; message: string }
>;
}
@@ -116,12 +119,13 @@ async function skillHomeOf(
}
async function defaultResolveBotId(callerSessionId: string): Promise<
- { ok: true; botId: string } | { ok: false; errorCode: string; message: string }
+ { ok: true; botId: string; canonicalSessionId: string | null } | { ok: false; errorCode: string; message: string }
> {
const db = getDbClient().drizzle;
const [row] = await db
.select({
botId: botSessionLinks.botId,
+ canonicalSessionId: botProfiles.canonicalSessionId,
role: botSessionLinks.role,
sessionStatus: sessions.status,
profileStatus: botProfiles.status,
@@ -141,7 +145,7 @@ async function defaultResolveBotId(callerSessionId: string): Promise<
if (row.role !== 'canonical' && row.role !== 'delegation') {
return { ok: false, errorCode: 'BOT_SESSION_READ_ONLY', message: '当前 Bot 历史任务为只读状态' };
}
- return { ok: true, botId: row.botId };
+ return { ok: true, botId: row.botId, canonicalSessionId: row.canonicalSessionId };
}
function storeError(cause: unknown): { ok: false; errorCode: string; message: string } {
@@ -158,9 +162,8 @@ function storeError(cause: unknown): { ok: false; errorCode: string; message: st
/**
* 伙伴把一次做法沉淀成技能(新建或更新同名技能)。
*
- * 写完**当前会话不会立刻多出一个可调用技能** —— harness 的技能面在 spawn 时冻结。
- * 返回值里的 `effective: 'next-session'` 就是这件事的诚实说明,让模型不要转头去
- * 调一个还没挂上的技能。
+ * 工具面在 spawn 时冻结。保存后请求宿主在安全轮次边界刷新同一个主任务,
+ * 不打断当前轮、授权卡或后台工作;未配置刷新桥的宿主仍诚实返回 next-session。
*/
export async function saveBotSkillForSession(
params: { callerSessionId: string; name: string; description: string; body: string; slug?: string },
@@ -169,7 +172,7 @@ export async function saveBotSkillForSession(
BotSkillResult<{
skill: BotSkillWireSummary;
created: boolean;
- effective: 'next-session';
+ effective: 'next-turn' | 'next-session';
}>
> {
try {
@@ -184,10 +187,13 @@ export async function saveBotSkillForSession(
...(params.slug ? { slug: params.slug } : {}),
});
assertOwnerBoundary(deps, boundary);
+ const refreshQueued = (deps.requestRefresh ?? requestBotRuntimeEpochRefresh)(
+ owner.canonicalSessionId ?? params.callerSessionId, 'resource',
+ );
return {
ok: true,
created,
- effective: 'next-session',
+ effective: refreshQueued ? 'next-turn' : 'next-session',
skill: {
slug: record.slug,
name: record.name,
@@ -272,14 +278,17 @@ export async function collectBotOwnSkillMounts(
deps: BotSkillServiceDeps = {},
): Promise<{
pluginRoot: string;
+ baseline: Awaited<ReturnType<typeof collectTeammateGuideMount>>;
skills: { name: string; description: string; path: string; filePath: string }[];
}> {
const boundary = captureOwnerBoundary(deps);
const userDataDir = await skillHomeOf(deps, botId, boundary);
const skills = await listBotSkills(userDataDir, botId);
+ const baseline = await collectTeammateGuideMount(userDataDir);
assertOwnerBoundary(deps, boundary);
return {
pluginRoot: botSkillRootDir(userDataDir, botId),
+ baseline,
skills: skills.map((item) => ({
name: item.name,
description: item.description,
diff --git a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts b/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
index ffcb38c12d..2ee13818c6 100644
--- a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
+++ b/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
@@ -31,7 +31,7 @@ export interface BotPromptCapabilitySignals {
/** 是否能直接创建新的伙伴;与消息/任务能力独立。 */
botCreationEnabled?: boolean;
routinesEnabled?: boolean;
- /** 伙伴自有技能是否可写入(save_bot_skill 是否在工具面里)。 */
+ /** 伙伴自有技能是否可写入(save_teammate_skill 是否在工具面里)。 */
ownSkillsEnabled: boolean;
/** 是否为 Bot 的 canonical Chat;Bot Mode 协议只在这里生效。 */
botModeEnabled?: boolean;
@@ -120,8 +120,8 @@ const MEMORY_GUIDANCE = [
/** 自有技能:与记忆的分工是「做法」vs「事实」。 */
const OWN_SKILLS_GUIDANCE = [
'## 你能把做法沉淀成本事',
- '技能不是每轮复盘或流水账。用户明确要求时直接沉淀;或者一套完整做法已经在真实任务里验证成功、以后明显还会复用时,第一次验证完就用 `save_bot_skill` 存成自己的技能,不要等用户去设置页手填。单次结论、临时路径、猜测和未经验证的做法都不存。',
- '存之前先用 `list_bot_skills` 查重;有同类就更新原来的,不要另造一份。技能从下一个任务开始生效,并且始终让用户看得见、改得动、删得掉。',
+ '几次相关交流或任务以后,主动检查用户反复需要的做法、格式和成功经验,为他创建或改进自己的技能,不用等用户开口。不要按轮次或固定数量凑技能。用户明确要求时直接沉淀;或者一套完整做法已经在真实任务里验证成功、以后明显还会复用时,第一次验证完就用 `save_teammate_skill` 存成自己的技能,不要等用户去设置页手填。单次结论、临时路径、猜测和未经验证的做法都不存。',
+ '存之前先用 `list_teammate_skills` 查重;有同类就更新原来的,不要另造一份。技能由宿主在当前聊天的安全轮次边界加载,并且始终让用户看得见、改得动、删得掉。',
'不要为了整理记忆或技能启动后台复盘、协同 worker。发现旧技能确实过时,先验证新做法,再更新。',
].join('\n');
@@ -266,7 +266,7 @@ export function buildBotSkillIndex(entries: readonly BotPromptSkillIndexEntry[])
}
/**
- * 易变层:技能索引在最前(它随会话内的 save_bot_skill 变),记忆与用户档案随后。
+ * 易变层:技能索引在最前(它随会话内的 save_teammate_skill 变),记忆与用户档案随后。
* 放在整份提示词末尾,变化时只从这里往后重新计算。
*/
export function buildBotVolatileTier(input: BotSystemPromptInput): string {
diff --git a/apps/desktop/src/main/maker-ipc/botTemplateSkillSeed.ts b/apps/desktop/src/main/maker-ipc/botTemplateSkillSeed.ts
index f3f5064efa..f789459602 100644
--- a/apps/desktop/src/main/maker-ipc/botTemplateSkillSeed.ts
+++ b/apps/desktop/src/main/maker-ipc/botTemplateSkillSeed.ts
@@ -1,223 +1,22 @@
-import { promises as fs } from 'node:fs';
-import path from 'node:path';
-
import type { BotTemplatePresetId } from '../../shared/botTemplatePreset.js';
-import {
- botSkillRootDir,
- listBotSkills,
- seedBotSkillIfMissing,
- type BotSkillRecord,
-} from './botSkillStore.js';
-
-type TemplateSkillSeed = {
- slug: string;
- name: string;
- description: string;
- body: string;
-};
+import { listBotSkills, type BotSkillRecord } from './botSkillStore.js';
export interface BotTemplateSkillSeedResult {
- /** 本次是否刚把整套模板安装推进到“完成”;用于刷新已经存在的运行时。 */
completedNow: boolean;
skills: Array<{ record: BotSkillRecord; created: boolean }>;
}
-const TEMPLATE_SKILLS: Record<BotTemplatePresetId, readonly TemplateSkillSeed[]> = {
- cindy: [
- {
- slug: 'help-with-cindy',
- name: '使用 Cindy 完成工作',
- description: '用户需要调整 Cindy、连接工具、找到合适的伙伴或完成具体工作时使用。',
- body: [
- '# 使用 Cindy 完成工作',
- '',
- '- 从用户眼前想完成的事情开始;先使用实际可用的 Cindy 能力查询入口核对功能与操作,不凭记忆编造菜单。',
- '- 需要插件时发现已安装、已启用的插件,读取对应说明再调用;已有连接直接复用,缺少连接时使用现有连接入口。',
- '- 需要专门方法或工具时,按需发现并加入已有 Skill 或 MCP,不复制整套能力库,不把能力发现当作外部操作授权。',
- '- 简单工作自己完成;编码实施和中大型工作交给独立 Cindy 任务,带上目标、材料、约束和验收要求。',
- '- 需要其他伙伴时按实际阵容与能力选择,不假定任何预设伙伴存在。结果返回后核对成果,再向用户交付。',
- ].join('\n'),
- },
- ],
- dash: [
- {
- slug: 'make-executive-decisions',
- name: '高管决策',
- description: '用户要求定方向、选方案、排优先级或审批重要事项时使用。',
- body: [
- '# 高管决策',
- '',
- '- 用一句话定义真正要决定的问题、截止点和不决定的代价。',
- '- 分开列出事实、假设、约束和信息缺口,只保留真正不同的少量方案。',
- '- 从长期目标、用户价值、投入产出、组织能力和风险承受度比较方案。',
- '- 必须给出一个明确结论:通过、补充信息或暂缓;随后写理由、主要风险、负责人和下一步。',
- '- 重要决定使用文档工具形成一页决策纪要,记录背景、选择、被放弃方案和复盘时间点。',
- ].join('\n'),
- },
- {
- slug: 'review-business-cases',
- name: '经营方案审查',
- description: '用户讨论预算、定价、商业模式、投入产出、招聘或资源配置时使用。',
- body: [
- '# 经营方案审查',
- '',
- '- 先明确目标指标、时间跨度、资源上限和决策门槛。',
- '- 把收入、成本、现金、机会成本和关键依赖分开;没有数据时列出所需数据,不编造精确数字。',
- '- 对关键变量至少做基准、乐观、保守三种情景,并指出结论在哪个假设下会反转。',
- '- 同时检查执行负责人、组织负荷、合规或声誉风险以及退出成本。',
- '- 需要计算或审批时,用文档工具制作可复核的测算表和简短审批建议,公式与假设必须可见。',
- ].join('\n'),
- },
- {
- slug: 'review-product-proposals',
- name: '产品方案审批',
- description: '用户评审产品方向、路线图、体验、品牌表达或上线方案时使用。',
- body: [
- '# 产品方案审批',
- '',
- '- 先说明目标用户、真实问题、使用场景和成功标准,再看具体功能或视觉方案。',
- '- 检查价值是否清楚、范围是否完整、体验是否一致克制、品牌表达是否适合办公场景。',
- '- 区分必须解决的问题与个人偏好;不给只靠形容词的审美结论。',
- '- 涉及技术可行性、安全或交付成本时请 LiZi 给出证据,最终产品取舍仍由 Dash 收口。',
- '- 输出通过、要求修改或暂缓,并列出上线前必须满足的少量条件;需要汇报时用文档工具形成评审纪要或汇报稿。',
- ].join('\n'),
- },
- ],
- lizi: [
- {
- slug: 'deliver-engineering-changes',
- name: '开发交付',
- description: '用户要求开发、修复、重构、补测试或完成工程改动时使用。',
- body: [
- '# 开发交付',
- '',
- '- 先检查真实工作区、规则、现有实现和未提交改动,明确可见结果与边界。',
- '- 选择最小但完整的实现;保护用户已有工作,不顺手扩大需求。',
- '- 修改代码时同步处理必要测试、错误路径、兼容性和用户可见文案。',
- '- 按风险运行定向测试、类型检查和必要的更广验证,并检查真实产物,不把“代码路径跑过”当成交付完成。',
- '- 最终交付实际改动、验证证据、未验证项和剩余风险。涉及提交、发布或不可逆操作时遵守项目规则并取得所需授权。',
- ].join('\n'),
- },
- {
- slug: 'diagnose-technical-incidents',
- name: '技术故障诊断',
- description: '遇到报错、日志异常、崩溃、性能下降或线上事故,需要定位根因时使用。',
- body: [
- '# 技术故障诊断',
- '',
- '- 先保存症状、时间线、影响范围和环境差异;能复现就给出最小复现。',
- '- 用代码、日志、配置和运行状态建立证据链,区分症状、直接原因、根因与尚未验证的假设。',
- '- 先给安全的止血方案,再给根治方案和回归范围;用户只要求诊断时不要擅自实施修复。',
- '- 验证修复既消除原问题,也没有破坏相邻路径;无法验证的部分明确列出。',
- '- 重大事故用文档工具形成复盘:影响、时间线、根因、处理、预防措施、负责人和完成时间。',
- ].join('\n'),
- },
- {
- slug: 'review-architecture-and-release',
- name: '架构与上线评审',
- description: '用户要求评审架构、API、数据迁移、安全边界或发布方案时使用。',
- body: [
- '# 架构与上线评审',
- '',
- '- 先画清组件边界、数据流、状态归属、信任边界和失败路径,再判断方案。',
- '- 检查兼容性、迁移、并发、幂等、权限、隐私、性能、可观测性和恢复能力;只报告有证据的风险。',
- '- Findings 按严重度排序,写清触发条件、影响和建议;不要用风格偏好冒充阻塞问题。',
- '- 发布前必须覆盖迁移顺序、灰度或开关、监控信号、回滚条件、数据恢复和负责人。',
- '- 需要长期使用时,用文档工具形成 ADR 或技术方案,并附上线检查表;结论明确为可上线、有条件上线或不可上线。',
- ].join('\n'),
- },
- ],
-};
-
-const LEGACY_V1_SLUGS: Record<BotTemplatePresetId, readonly string[]> = {
- cindy: ['everyday-work-coordination'],
- dash: ['executive-decision-review'],
- lizi: ['technical-delivery'],
-};
-
-function legacyCompletionMarkerPath(
- userDataDir: string,
- botId: string,
- templateId: BotTemplatePresetId,
-): string {
- return path.join(botSkillRootDir(userDataDir, botId), `.template-skills-${templateId}.seeded`);
-}
-
-function manifestPath(userDataDir: string, botId: string, templateId: BotTemplatePresetId): string {
- return path.join(botSkillRootDir(userDataDir, botId), `.template-skills-${templateId}.json`);
-}
-
-async function fileExists(filePath: string): Promise<boolean> {
- try {
- return (await fs.stat(filePath)).isFile();
- } catch {
- return false;
- }
-}
-
-async function readOfferedSlugs(
- userDataDir: string,
- botId: string,
- templateId: BotTemplatePresetId,
-): Promise<Set<string>> {
- try {
- const parsed = JSON.parse(
- await fs.readFile(manifestPath(userDataDir, botId, templateId), 'utf8'),
- ) as {
- offeredSlugs?: unknown;
- };
- if (Array.isArray(parsed.offeredSlugs)) {
- return new Set(
- parsed.offeredSlugs.filter((item): item is string => typeof item === 'string'),
- );
- }
- } catch {
- // 缺失或损坏的 manifest 走旧标记迁移;绝不因为元数据损坏覆盖现有 Skill。
- }
- return (await fileExists(legacyCompletionMarkerPath(userDataDir, botId, templateId)))
- ? new Set(LEGACY_V1_SLUGS[templateId])
- : new Set();
-}
-
-async function writeOfferedSlugs(
- userDataDir: string,
- botId: string,
- templateId: BotTemplatePresetId,
- offeredSlugs: Set<string>,
-): Promise<void> {
- const target = manifestPath(userDataDir, botId, templateId);
- const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
- await fs.mkdir(path.dirname(target), { recursive: true });
- await fs.writeFile(
- temporary,
- `${JSON.stringify({ version: 2, offeredSlugs: [...offeredSlugs].sort() }, null, 2)}\n`,
- 'utf8',
- );
- await fs.rename(temporary, target);
-}
-
/**
- * 创建预设伙伴时安装真实 Skill;同 slug 已存在则完整保留用户版本。
- *
- * manifest 记录的是“曾经提供过”,而不是“当前存在”。这样模板升级只补新能力,
- * 用户主动删除过的内置 Skill 不会在下次任务中被擅自装回来。
+ * Compatibility entry for old creation/invitation callers. Every new Bot now
+ * receives the shared managed baseline at runtime, never a role capability pack.
+ * Preserve and normalize previously seeded/user-edited files without restoring
+ * deleted Skills or rewriting old completion markers.
*/
export async function seedBotTemplateSkills(
userDataDir: string,
botId: string,
- templateId: BotTemplatePresetId,
+ _templateId: BotTemplatePresetId,
): Promise<BotTemplateSkillSeedResult> {
- // list 同时完成旧 Cindy frontmatter 的无损标准化,确保已经装过的模板 Skill
- // 也能被所有 harness 识别,而不是只修以后新写的文件。
await listBotSkills(userDataDir, botId);
- const offeredSlugs = await readOfferedSlugs(userDataDir, botId, templateId);
- const pending = TEMPLATE_SKILLS[templateId].filter((skill) => !offeredSlugs.has(skill.slug));
- if (pending.length === 0) return { completedNow: false, skills: [] };
-
- const skills = await Promise.all(
- pending.map((skill) => seedBotSkillIfMissing(userDataDir, botId, skill)),
- );
- for (const skill of pending) offeredSlugs.add(skill.slug);
- await writeOfferedSlugs(userDataDir, botId, templateId, offeredSlugs);
- return { completedNow: true, skills };
+ return { completedNow: false, skills: [] };
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 19937cd8cb..933ad59d29 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1,3 +1,4 @@
+import { configureAppDefaultModelSelection } from './appDefaultModelControl.js';
import { setBotInvitationWelcomeDispatch } from './botInvitation.js';
import type { TurnUsageContext } from './turnUsageContext.js';
import { registerPluginListHandler } from './pluginListHandler.js';
@@ -4589,6 +4590,13 @@ let disposePiPackagesChangedBroadcast: (() => void) | null = null;
* soon as the Renderer selects an owner, before the splash-gated Maker IPC bundle is available.
*/
export function registerModelVisibilitySyncIpc(): void {
+ configureAppDefaultModelSelection((appDefaultSelection) => {
+ broadcastToAllWindows(MAKER_PUSH.DRAFT_PREF_APPLY, {
+ agent: appDefaultSelection.route.harness === 'claude' ? 'claude-code' : appDefaultSelection.route.harness,
+ providerId: appDefaultSelection.route.providerId ?? '', modelId: appDefaultSelection.route.model,
+ active: true, appDefaultSelection,
+ });
+ });
// Register with model visibility before the first window; a cold-start preference
// push must not be lost while the larger Maker bundle is still initializing.
ipcMain.on(MAKER_SEND.SYNC_NEW_MAKER_DRAFT, (event, payload: unknown) => {
diff --git a/apps/desktop/src/main/maker-ipc/teammateGuide.ts b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
new file mode 100644
index 0000000000..d162ed9435
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
@@ -0,0 +1,39 @@
+import { TEAMMATE_CONTROL_GUIDANCE } from '@cindy/mcps';
+
+/** Single host-owned baseline: preloaded text and native SKILL.md share this source. */
+export const TEAMMATE_GUIDE_NAME = 'teammate-guide';
+export const TEAMMATE_GUIDE_DESCRIPTION = 'Shared operating procedures for every teammate: manage tasks, contact and create teammates, change model defaults, use tools, and maintain personal Skills and memory.';
+
+export function buildTeammateGuide(
+ options: { helperAvailable?: boolean; cindyAvailable?: boolean } = {},
+): string {
+ const helperAvailable = options.helperAvailable !== false;
+ // cindy / ghost_* live on the local builtin gateway. SSH Claude/Codex only
+ // inject collab, memory and helper (REMOTE_ALLOWED_SERVER_NAMES); advertising
+ // plugins there would tell the model to call tools it cannot reach. Remote Pi
+ // tunnels cindy, so keep plugin guidance there.
+ const cindyAvailable = options.cindyAvailable !== false;
+ const pluginGuidance = cindyAvailable
+ ? ' Installed plugins are a separate discovery surface from Skill/MCP/toolset references. An empty capability search does not mean no plugin can do the work. Before declaring a connected-service task unavailable, inspect the relevant installed plugin. Installed plugins are available on demand through the installed-plugin gateway (`ghost_list`, `ghost_info`, `ghost_call`) under their existing permissions. When a plugin returns SETUP_REQUIRED with an authorization request id, its login/configuration card is already in this chat and the requested tool has not run. End the turn and wait for the Host authorization-completed notification, then continue the original work through the live plugin tool. Do not poll, ask for credentials in chat, invent login links, or treat login as task execution approval. The phone can display/cancel the card; connection and secret entry happen on the trusted desktop.'
+ : '';
+ return [
+ '## teammate-guide — 伙伴使用指南',
+ 'This guide is preloaded for every teammate, regardless of name or personality. It describes the shared operating procedures, not a persona. Your identity, personal Skills and memory are independent of this guide.',
+ 'You are a teammate with a durable profile and a persistent chat. The application manages your runtime; independent tasks have their own execution and lifecycle.',
+ 'The application in this guide is the host providing teammate, task and settings tools, not the model provider or agent CLI. Use the host tools for these operations; provider documentation cannot tell you the application’s current settings or available controls.',
+ ...(helperAvailable ? [
+ TEAMMATE_CONTROL_GUIDANCE,
+ 'When the user wants another teammate, call `create_teammate` with a name and any identity details the user supplied. New teammates receive this same baseline and follow the user’s available default model; do not generate a fixed number of role Skills, prewrite a greeting, or require a profile form. Their personality, personal learning and memory remain independent.',
+ 'When the user asks to change the application’s default model, use `get_app_default_model` to read the actual current selection and enabled options, then `set_app_default_model` with the returned id and a supported effort if requested. Check the confirmed result. This changes the same default used by new tasks and following teammates; it does not overwrite existing task choices or explicit teammate/global teammate chains. Do not use this global setter when asked to change only this teammate, edit configuration files, guess providers, enable hidden models, or call an auxiliary model.',
+ `Use direct teammate tools for your own memory, Skills and teammates. When work needs another capability, use \`find_teammate_capabilities\` through the helper’s teammate tools to search existing Skills, MCP connections or built-in tools, then \`set_teammate_capability\` to join it. References reuse existing installations and authorization; do not copy credentials or edit shared sources. New mounts take effect next turn in this same task.${pluginGuidance} Discover only what the work needs; do not repeatedly list the whole tool surface.`,
+ "A real background task is a standalone Session in the user's task list. Follow the workload split in the `start_session_task` guidance: handle short simple work yourself and proactively start independent tasks for coding and medium or large work. Do not wait for the user to ask for delegation. Use `check_session_task`, `message_session_task`, and `stop_session_task` to control that same task when needed. Completion returns automatically; you remain responsible for reviewing and presenting the result.",
+ 'Use `send_to_agent` only to send one bounded asynchronous message to a named teammate. It is not a task and has no progress or cancellation. Do not substitute a message to a teammate for `start_session_task`.',
+ "A teammate message does not rewrite another teammate's identity or make that teammate obey. If the user asks for obedience or control, explain this boundary and offer either a message or a tracked Session task, whichever matches the work.",
+ ] : []),
+ 'Actively personalize your own memory and Skills as you work. Save a clear stable preference, correction, or long-lived background fact when it first appears, without waiting for a request to remember. After a few related exchanges or completed tasks, look for recurring needs, preferred formats and successful methods, then create or refine a useful personal Skill without waiting for the user to ask. One verified reusable success is enough; there is no minimum number of chats or quota of Skills. Do this within the current turn using your own tools and model, not an extra learning model or background review worker. Respect the user’s memory switch and requests not to retain information.',
+ 'Before writing memory, search for an existing record and update it instead of creating a duplicate. Use a `learned-` name only for a stable reusable working habit, never for a one-off conclusion, temporary path, guess, or unverified step.',
+ ...(helperAvailable ? [
+ 'Before `save_teammate_skill`, call `list_teammate_skills`. Name personal Skills for the concrete action and object, such as `prepare-weekly-report`; avoid vague names like helper, expert, or assistant. Save or update a Skill only after the workflow has succeeded and the reusable steps are known. The Host queues saved Skills for loading at a safe turn boundary in this same chat; do not call a newly saved Skill before it appears in your live skill surface. Your learned Skills remain visible, editable, and removable by the user, isolated from other teammates and the shared baseline.',
+ ] : []),
+ ].join('\n');
+}
diff --git a/apps/desktop/src/main/maker-ipc/teammateGuideStore.ts b/apps/desktop/src/main/maker-ipc/teammateGuideStore.ts
new file mode 100644
index 0000000000..19099ed796
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/teammateGuideStore.ts
@@ -0,0 +1,35 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import {
+ TEAMMATE_GUIDE_DESCRIPTION,
+ TEAMMATE_GUIDE_NAME,
+ buildTeammateGuide,
+} from './teammateGuide.js';
+
+/** Managed, versioned source shared by every local Bot; never lives on a Bot's learned shelf. */
+export async function collectTeammateGuideMount(userDataDir: string) {
+ const source = `---\nname: ${TEAMMATE_GUIDE_NAME}\ndescription: ${JSON.stringify(TEAMMATE_GUIDE_DESCRIPTION)}\n---\n\n${buildTeammateGuide()}\n`;
+ const version = createHash('sha256').update(source).digest('hex');
+ const pluginRoot = path.join(userDataDir, 'managed-teammate-skills', version);
+ const skillPath = path.join(pluginRoot, 'skills', TEAMMATE_GUIDE_NAME);
+ const filePath = path.join(skillPath, 'SKILL.md');
+ const manifestPath = path.join(pluginRoot, '.claude-plugin', 'plugin.json');
+ // Immutable generations avoid rewriting a Skill underneath an active harness.
+ for (const [target, content] of [
+ [filePath, source],
+ [manifestPath, JSON.stringify({ name: 'teammate-guide', version: '1.0.0', description: TEAMMATE_GUIDE_DESCRIPTION })],
+ ]) {
+ if (await fs.readFile(target, 'utf8').catch(() => null) === content) continue;
+ await fs.mkdir(path.dirname(target), { recursive: true });
+ const temporary = `${target}.${randomUUID()}.tmp`;
+ try {
+ await fs.writeFile(temporary, content, 'utf8');
+ await fs.rename(temporary, target);
+ } finally {
+ await fs.rm(temporary, { force: true });
+ }
+ }
+ return { pluginRoot, skill: { name: TEAMMATE_GUIDE_NAME,
+ description: TEAMMATE_GUIDE_DESCRIPTION, path: skillPath, filePath } };
+}
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index 375e98ac2b..e0ef8aba6f 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -50,6 +50,7 @@ import {
import { useResyncAgentIslandSettingsAfterLogin } from '@/hooks/useAgentIslandSettings';
import {
getDraftForOwnerPreferenceSync,
+ applyAppDefaultModelSelection,
subscribeDraft,
setEffortForModel,
setFastModeForModel,
@@ -97,7 +98,7 @@ function LoginHandoffHost({ children }: { children: React.ReactNode }) {
);
}
-function syncNewMakerPrefs() {
+function syncNewMakerPrefs(appDefaultModelRequestId?: string) {
// 多 renderer 的模块内存彼此独立;跨窗口通知必须从共享持久快照同步,避免旧窗口把
// 自己的 model / workingDir 等完整旧草稿覆盖进 main 缓存。
const owner = getDataOwnerGeneration();
@@ -119,6 +120,7 @@ function syncNewMakerPrefs() {
// 不消费这两项,远程草稿镜像才用)。fire-and-forget。
const selected = draft.lastByVendor[draft.vendor];
window.electronAPI.syncNewMakerDraft({
+ ...(appDefaultModelRequestId ? { appDefaultModelRequestId } : {}),
ownerStamp: { dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation },
selectedRoute: {
harness: draft.vendor === 'cc' || draft.vendor === 'orca' ? 'claude' : draft.vendor,
@@ -267,7 +269,16 @@ export function App() {
// 通过 providerModelMemory 同步。写入触发上面的镜像 effect → NEW_MAKER_DRAFT_CHANGED 回流控制端。
useEffect(() => {
const offDraft = window.electronAPI.onMakerDraftPrefApply(
- ({ agent, providerId, modelId, active, effort, fast, thinking, markModelChoice }) => {
+ ({ agent, providerId, modelId, active, effort, fast, thinking, markModelChoice, appDefaultSelection }) => {
+ if (appDefaultSelection) {
+ if (applyAppDefaultModelSelection(appDefaultSelection)) {
+ const route = appDefaultSelection.route;
+ setProviderModelChoice(agent, route.providerId ?? '', route.model, route.effort as Effort);
+ setProviderModelFast(agent, route.providerId ?? '', route.model, route.fastMode);
+ syncNewMakerPrefs(appDefaultSelection.requestId);
+ }
+ return;
+ }
const vendor = agentKindToVendor(agent);
if (active) {
const patch =
diff --git a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts
index 37acfac39c..eab05014ba 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerDraft.test.ts
@@ -1821,3 +1821,37 @@ it('does not stamp a prior owner draft during the synchronous auth handoff', asy
expect(getDraftForOwnerPreferenceSync('B')?.lastByVendor.cc.model).not.toBe('owner-a-model');
expect(getDraftForOwnerPreferenceSync('A')).toBeNull();
});
+
+describe('Bot default model write-through', () => {
+ async function setup() {
+ const store = await loadModule();
+ const owner = await import('@/contexts/dataOwnerGeneration');
+ owner.setDataOwnerGeneration('bot-owner', 8);
+ store.setNewMakerDraftOwner('bot-owner');
+ store.patchVendorPrefs('codex', { model: 'luna', providerId: 'openai', effort: 'medium' });
+ store.switchVendor('codex');
+ const route = { harness: 'codex' as const, providerId: 'openai', model: 'luna', effort: 'medium', fastMode: false };
+ return { store, selection: { requestId: "test-default-selection", route: { ...route, effort: 'low' }, expectedRoute: route,
+ ownerStamp: { dataOwnerId: 'bot-owner', ownerGeneration: 8 }, expiresAt: Date.now() + 5000 } };
+ }
+ it('persists the same default used by new tasks and survives reloading', async () => {
+ const { store, selection } = await setup();
+ expect(store.applyAppDefaultModelSelection(selection)).toBe(true);
+ vi.resetModules();
+ const reloaded = await loadModule();
+ reloaded.setNewMakerDraftOwner('bot-owner');
+ expect(reloaded.getDraft().lastByVendor.codex).toMatchObject({ model: 'luna', effort: 'low', providerId: 'openai' });
+ expect(reloaded.getDraft().vendor).toBe('codex');
+ expect(reloaded.getDraft().defaultTupleSelectionCustomized).toBe(true);
+ });
+ it.each(['owner', 'expiry', 'selection', 'disk'] as const)('refuses %s changes without reporting success', async reason => {
+ const { store, selection } = await setup();
+ if (reason === 'owner') selection.ownerStamp.ownerGeneration = 7;
+ if (reason === 'expiry') selection.expiresAt = Date.now() - 1;
+ if (reason === 'selection') store.patchVendorPrefs('codex', { model: 'a-new-user-choice' });
+ if (reason === 'disk') vi.spyOn(memStorage, 'setItem').mockImplementation(() => { throw new Error('full'); });
+ const before = store.getDraft();
+ expect(store.applyAppDefaultModelSelection(selection)).toBe(false);
+ expect(store.getDraft()).toEqual(before);
+ });
+});
diff --git a/apps/desktop/src/renderer/state/newMakerDraft.ts b/apps/desktop/src/renderer/state/newMakerDraft.ts
index a6fe4f3689..f28e4fe95e 100644
--- a/apps/desktop/src/renderer/state/newMakerDraft.ts
+++ b/apps/desktop/src/renderer/state/newMakerDraft.ts
@@ -19,6 +19,9 @@
*/
import { useSyncExternalStore } from 'react';
+import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';
+import { sameModelRoute, type AppDefaultModelSelection } from '../../shared/appDefaultModelSelection';
+import type { BotModelRoute } from '../../shared/botModelChain';
import type { MakerVendor } from '@/lib/ccAgent.types';
import { isSelectableVendor } from '@/lib/agentVendors';
@@ -904,6 +907,40 @@ export function switchVendor(next: MakerVendor): void {
emit();
}
+/** Explicit Bot-requested default uses the same persisted tuple, with owner/CAS and no partial writes. */
+export function applyAppDefaultModelSelection(selection: AppDefaultModelSelection): boolean {
+ if (!isDataOwnerPushStampCurrent(selection.ownerStamp)
+ || activeDataOwnerId !== selection.ownerStamp.dataOwnerId
+ || Date.now() > selection.expiresAt) return false;
+ const stored = readStoredDraftRecord();
+ const base = stored ? sanitize(stored) : currentDraft;
+ const prefs = base.lastByVendor[base.vendor];
+ const current: BotModelRoute | null = prefs.model ? {
+ harness: base.vendor === 'cc' || base.vendor === 'orca' ? 'claude' : base.vendor,
+ model: prefs.model, providerId: prefs.providerId ?? null, effort: prefs.effort ?? '',
+ fastMode: base.fastModeByModel[prefs.model] === true,
+ } : null;
+ if (!sameModelRoute(current, selection.expectedRoute) && !sameModelRoute(current, selection.route)) return false;
+ const route = selection.route;
+ const vendor = route.harness === 'claude' ? 'cc' : route.harness;
+ const next: NewMakerDraft = { ...base, vendor,
+ defaultTupleCustomized: true, defaultTupleSelectionCustomized: true,
+ modelChosenByVendor: { ...base.modelChosenByVendor, [vendor]: true },
+ lastByVendor: { ...base.lastByVendor, [vendor]: { ...base.lastByVendor[vendor],
+ model: route.model, providerId: route.providerId, effort: route.effort as Effort } },
+ effortByModel: { ...base.effortByModel, [route.model]: route.effort as Effort },
+ fastModeByModel: { ...base.fastModeByModel, [route.model]: route.fastMode },
+ };
+ try {
+ window.localStorage.setItem(storageKey(), JSON.stringify(next));
+ } catch { return false; }
+ currentDraft = { ...currentDraft, ...defaultTuplePreferenceOf(next),
+ effortByModel: next.effortByModel, fastModeByModel: next.fastModeByModel };
+ preferenceSyncFallback = null;
+ emit();
+ return true;
+}
+
/**
* 当前草稿 Harness 不可用时按系统顺序回退。
*
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index d42410eb3d..fdda7a6b64 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2400,6 +2400,7 @@ interface ElectronAPI {
}) => void;
syncNewMakerDraft: (snapshot: {
+ appDefaultModelRequestId?: string;
ownerStamp: import('../shared/dataOwnerPush').DataOwnerPushStamp;
selectedRoute?: import('../shared/botModelChain').BotModelRoute;
lastByVendor: Partial<
@@ -2442,6 +2443,7 @@ interface ElectronAPI {
/** 被控端本地 main → 自身 renderer:控制端写穿的草稿「模型 effort/fast」pref(调本地 setter)。 */
onMakerDraftPrefApply: (
cb: (payload: {
+ appDefaultSelection?: import('../shared/appDefaultModelSelection').AppDefaultModelSelection;
agent: 'claude-code' | 'codex' | 'pi';
providerId: string;
modelId: string;
diff --git a/apps/desktop/src/shared/appDefaultModelSelection.ts b/apps/desktop/src/shared/appDefaultModelSelection.ts
new file mode 100644
index 0000000000..49df32e46e
--- /dev/null
+++ b/apps/desktop/src/shared/appDefaultModelSelection.ts
@@ -0,0 +1,17 @@
+import type { BotModelRoute } from './botModelChain.js';
+import type { DataOwnerPushStamp } from './dataOwnerPush.js';
+
+/** Host-only write-through request; existing remote preference payloads remain unchanged. */
+export interface AppDefaultModelSelection {
+ requestId: string;
+ route: BotModelRoute;
+ expectedRoute: BotModelRoute | null;
+ ownerStamp: DataOwnerPushStamp;
+ expiresAt: number;
+}
+
+export function sameModelRoute(a: BotModelRoute | null | undefined, b: BotModelRoute | null | undefined): boolean {
+ if (!a || !b) return !a && !b;
+ return a.harness === b.harness && a.providerId === b.providerId && a.model === b.model
+ && a.effort === b.effort && a.fastMode === b.fastMode;
+}
diff --git a/docs/product-rules/cindy-bots-completion-matrix.md b/docs/product-rules/cindy-bots-completion-matrix.md
index 7ccbebbb11..9348dd064e 100644
--- a/docs/product-rules/cindy-bots-completion-matrix.md
+++ b/docs/product-rules/cindy-bots-completion-matrix.md
@@ -22,7 +22,7 @@
| 后台任务(start_session_task) | `botDelegationService.ts`、`lizi_xdtHelperMcpServer.ts` | `botCanonicalSession.test.ts` 的 Session 任务用例 | 大活开成普通 Cindy 任务,出现在主任务列表、走自己的权限门;check/message/stop 控制同一任务。 |
| 任务卡与完成信号 | `BotCollaborationCard.tsx`、`botDelegationLive.ts`、`deliverCompletion` | `BotCollaborationCard.test.tsx`、Session 任务完成与重启补投用例 | 父时间线只有一张持久任务卡;完成信号是隐藏指令,带持久送达标记、幂等键、退避重试和重启补投。 |
| 统一通知 | `useSessionRunningStatus.ts`、`sessionEventNotification.ts`、两个任务侧栏 | 侧栏与通知入口测试 | 伙伴页接手统一完成 / 失败 / 待回复观察;沿用全局通道与聚焦去重,通知点击回到伙伴路由。 |
-| 自有技能学习 | `botSkillStore.ts`、`botSkillService.ts`、`save_bot_skill` | `botSkillStore.test.ts`、`botSkillService.test.ts`、`bot-own-skills-mount.test.ts` | 沉淀真技能、下会话挂载、设置页可见可删。 |
+| 自有技能学习 | `botSkillStore.ts`、`botSkillService.ts`、`save_teammate_skill` | `botSkillStore.test.ts`、`botSkillService.test.ts`、`bot-own-skills-mount.test.ts` | 沉淀真技能、同一聊天安全轮次加载、设置页可见可删。 |
| Desktop UI | `renderer/features/bots/**` | renderer store 与视图测试、typecheck | 名册、聊天、最小设置(成长/模型/维护);无工程概念暴露。 |
## 并发与故障矩阵
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 493e509e17..f104260f9f 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -157,9 +157,12 @@ harness + provider + model + effort + fastMode
subagent 面(pi 的 `subagent` 工具、cc 的 `Task`),也不得继承 Cindy 完整 system prompt、
全量 Skill 清单或全量 MCP schema。
- 普通伙伴不能启动 Orca / Team Worker。需要独立执行的工作走 Cindy Session 任务(见 6.1)。
-- 伙伴学习 Skill 或写长期记忆必须满足至少一项:用户明确要求、同一偏好稳定重复出现、或流程
- 已验证且明显可复用。写入前去重,写入后可见、可编辑、可删除。普通一轮对话不得默认生成记忆
- 或 Skill,也不得为了“成长”开后台 review worker。
+- 伙伴主动为用户积累记忆和 Skill,不以用户明确要求为前提。清晰稳定的偏好、纠正与长期背景
+ 第一次出现就记;几次相关交流或任务后,主动整理反复需要的格式与已验证的做法,形成或改进
+ 个性化 Skill。一次已经验证且明显可复用的成功也可立即沉淀,不设轮次数或 Skill 数量配额。
+ 写入前去重,写入后可见、可编辑、可删除;尊重记忆开关和不保存要求,不记流水账或臆造流程。
+ 学习在当前轮用当前可用模型完成,不另选学习模型或启动后台 review worker。
+ 保存 Skill 后请求主任务在安全轮次边界刷新,不打断运行中的工作或授权卡;同一个聊天继续使用新技能。
### 6.1 后台任务与伙伴消息:两条边界,不做混合 action
@@ -281,10 +284,14 @@ Session 任务遵守同一套机制与呈现契约:
- 创建只必填名字,头像可从图库选择或上传;创建后直接进入伙伴自身的对话。身份细节未提供时不编造,
不先调用辅助模型生成资料,也不按固定数量创建 Skill。已有生成草稿和自有 Skill 继续兼容。
- 新建与改名不能产生同名伙伴(NFKC、去首尾空格、不区分大小写)。头像可复用,姓名必须可区分。
-- 所有伙伴共用宿主管理的控制说明与能力发现基准,模板只补充身份和专门方法。
- `get_bot_state` 投影当前 Profile、主任务、模型候选链、记忆开关和能力引用;
- `update_bot_profile` 通过同一个 Profile 写入服务修改用户点名的字段,使用版本校验,下一轮生效。
- 两个入口的说明与运行时基准来自同一份 `BOT_CONTROL_GUIDANCE`,不复制为用户 Skill。
+- 所有伙伴(包括默认 Cindy)启动时拥有完全相同的 `teammate-guide` 基座 Skill 和默认工具能力,
+ 新建时只区别人设资料,不按模板附加或缺省一组角色能力。共同基座由宿主维护,正文预加载,
+ 本地运行时同时挂载真实 SKILL.md;按内容版本放在 owner 根的 `managed-teammate-skills/`,
+ 不混入各 Bot 的 `skills/` 学习目录。远端使用同源、按实际工具面裁剪的预加载正文,不传本机路径。
+ `get_teammate_state` 投影当前 Profile、主任务、模型候选链、记忆开关和能力引用;
+ `update_teammate_profile` 通过同一个 Profile 写入服务修改用户点名的字段,使用版本校验,下一轮生效。
+ 控制工具说明来自同一份 `TEAMMATE_CONTROL_GUIDANCE`;共同基座的预加载正文与 SKILL.md 同源。
+ 任务分工、伙伴消息、创建伙伴、插件连接及学习规则对所有伙伴一致。
- 记忆、Skill、MCP、模型与主任务仍由各自模块保存和校验。模型候选与已选择的能力引用不等于本轮
实际运行的模型和工具。默认模型链遵循用户当前选择与可用模型目录,不写入伙伴 override。
- 伙伴可查询与普通任务相同的 Cindy 功能说明,但产品说明不授予操作权限。插件通过已有的
@@ -299,3 +306,9 @@ Session 任务遵守同一套机制与呈现契约:
当前数据 owner 与代次;切换期间、旧账号或旧代次的迟到快照不得覆盖当前默认。
没有自有 Skill 的新伙伴也具备学习入口;空技能索引只表示尚未沉淀,不关闭技能管理能力。
插件登录/配置使用 [伙伴授权卡](bot-authorization-cards.md),与独立任务的执行授权分别处理。
+
+`get_app_default_model` 读取客户端真实默认与已连接、已启用的可用型号;
+`set_app_default_model` 仅在用户要求调整全局默认时使用,复用 renderer 的现有默认组合存储。
+宿主重新验证可用型号,写入携带 owner/代次、原选择和期限;renderer 原子持久化并经现有镜像读回
+以后才返回成功。旧账号、迟到写入、并发选择、未启用型号或未确认落盘不能声称成功。
+不覆盖已有任务或显式的伙伴/全局伙伴模型链,不以写缓存或新增 Bot override 冒充修改客户端默认。
diff --git a/packages/lizi-mcps/src/__tests__/botCapabilitiesTool.test.ts b/packages/lizi-mcps/src/__tests__/botCapabilitiesTool.test.ts
index d172c941af..11d2cad629 100644
--- a/packages/lizi-mcps/src/__tests__/botCapabilitiesTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botCapabilitiesTool.test.ts
@@ -22,35 +22,35 @@ function fixture(sessionId: string | undefined = 'current-bot') {
describe('Bot capability tools', () => {
it('binds discovery and selection to the host caller and reports next-turn activation', async () => {
const { registry, callbacks } = fixture();
- await registry.call('find_bot_capabilities', { kind: 'mcp', query: 'docs' });
+ await registry.call('find_teammate_capabilities', { kind: 'mcp', query: 'docs' });
expect(callbacks.list).toHaveBeenCalledWith({ callerSessionId: 'current-bot', kind: 'mcp', query: 'docs' });
- const result = await registry.call('set_bot_capability', { kind: 'mcp', id: 'docs', joined: true });
+ const result = await registry.call('set_teammate_capability', { kind: 'mcp', id: 'docs', joined: true });
expect(callbacks.select).toHaveBeenCalledWith({ callerSessionId: 'current-bot', kind: 'mcp', id: 'docs', joined: true });
expect(result.content[0]).toMatchObject({ text: JSON.stringify({ ok: true, effective: 'next-turn', joined: true }) });
});
it('rejects attempts to select capabilities for another caller', async () => {
const { registry, callbacks } = fixture();
- const result = await registry.call('set_bot_capability', { kind: 'skill', id: 'release', joined: true, callerSessionId: 'another-bot' });
+ const result = await registry.call('set_teammate_capability', { kind: 'skill', id: 'release', joined: true, callerSessionId: 'another-bot' });
expect(result.isError).toBe(true);
expect(callbacks.select).not.toHaveBeenCalled();
});
it('does not call the host without a bound session', async () => {
const { registry, callbacks } = fixture('');
- expect((await registry.call('find_bot_capabilities', { kind: 'skill' })).isError).toBe(true);
- expect((await registry.call('set_bot_capability', { kind: 'skill', id: 'release', joined: false })).isError).toBe(true);
+ expect((await registry.call('find_teammate_capabilities', { kind: 'skill' })).isError).toBe(true);
+ expect((await registry.call('set_teammate_capability', { kind: 'skill', id: 'release', joined: false })).isError).toBe(true);
expect(callbacks.list).not.toHaveBeenCalled();
expect(callbacks.select).not.toHaveBeenCalled();
});
- it('keeps plugin discovery in the default find_bot_capabilities description', () => {
+ it('keeps plugin discovery in the default find_teammate_capabilities description', () => {
const description = buildFindBotCapabilitiesDescription();
expect(description).toContain('ghost_list');
expect(description).toContain('ghost_info');
expect(buildFindBotCapabilitiesDescription(true)).toBe(description);
const { registry } = fixture();
- expect(registry.list('bots').find((tool) => tool.name === 'find_bot_capabilities')?.description).toBe(description);
+ expect(registry.list('bots').find((tool) => tool.name === 'find_teammate_capabilities')?.description).toBe(description);
});
it('omits ghost tools when cindy is unavailable', () => {
@@ -66,14 +66,14 @@ describe('Bot capability tools', () => {
},
cindyAvailable: false,
});
- expect(registry.list('bots').find((tool) => tool.name === 'find_bot_capabilities')?.description).toBe(description);
- expect(registry.list('bots').find((tool) => tool.name === 'set_bot_capability')?.description).not.toMatch(/ghost_list|ghost_info|ghost_call/);
+ expect(registry.list('bots').find((tool) => tool.name === 'find_teammate_capabilities')?.description).toBe(description);
+ expect(registry.list('bots').find((tool) => tool.name === 'set_teammate_capability')?.description).not.toMatch(/ghost_list|ghost_info|ghost_call/);
});
- it('rewrites only find_bot_capabilities at list time', () => {
+ it('rewrites only find_teammate_capabilities at list time', () => {
const tools = [
- { name: 'find_bot_capabilities', description: buildFindBotCapabilitiesDescription() },
- { name: 'set_bot_capability', description: 'join or leave' },
+ { name: 'find_teammate_capabilities', description: buildFindBotCapabilitiesDescription() },
+ { name: 'set_teammate_capability', description: 'join or leave' },
];
expect(withCindyGatedBotToolDescriptions(tools, true)).toEqual(tools);
const remote = withCindyGatedBotToolDescriptions(tools, false);
@@ -91,13 +91,36 @@ describe('Bot self control', () => {
getSessionContext: () => ({ sessionId: 'self', agentKind: 'pi', workingDir: '/w' }),
callbacks: { ...fixture().callbacks, updateProfile },
});
- expect((await registry.call('update_bot_profile', { expectedVersion: 2, name: 'New name', botId: 'other' })).isError).toBe(true);
- expect((await registry.call('update_bot_profile', { expectedVersion: 2, model: 'disabled' })).isError).toBe(true);
- expect((await registry.call('update_bot_profile', { expectedVersion: 2 })).isError).toBe(true);
+ expect((await registry.call('update_teammate_profile', { expectedVersion: 2, name: 'New name', botId: 'other' })).isError).toBe(true);
+ expect((await registry.call('update_teammate_profile', { expectedVersion: 2, model: 'disabled' })).isError).toBe(true);
+ expect((await registry.call('update_teammate_profile', { expectedVersion: 2 })).isError).toBe(true);
expect(updateProfile).not.toHaveBeenCalled();
- const result = await registry.call('update_bot_profile', { expectedVersion: 2, description: '' });
+ const result = await registry.call('update_teammate_profile', { expectedVersion: 2, description: '' });
expect(updateProfile).toHaveBeenCalledWith({ callerSessionId: 'self', expectedVersion: 2, description: '' });
expect(result.isError).toBe(true);
expect(result.content[0]).toMatchObject({ text: expect.stringContaining('BOT_PROFILE_UPDATE_FAILED') });
});
});
+
+it('advertises teammate names while accepting saved legacy helper calls', async () => {
+ const { registry, callbacks } = fixture();
+ expect(registry.list('bots').map(item => item.name)).toContain('find_teammate_capabilities');
+ expect(registry.list('bots').map(item => item.name)).not.toContain('find_bot_capabilities');
+ await registry.call('find_bot_capabilities', { kind: 'skill' });
+ expect(callbacks.list).toHaveBeenCalledWith({ callerSessionId: 'current-bot', kind: 'skill' });
+});
+
+it('exposes app default model operations with bound callers and propagates unconfirmed writes', async () => {
+ const registry = new XdtHelperToolRegistry();
+ const models = vi.fn(async () => ({ ok: true as const, current: null, available: [] }));
+ const setDefaultModel = vi.fn(async () => ({ ok: false as const, errorCode: 'MODEL_DEFAULT_NOT_CONFIRMED', message: 'not saved' }));
+ const ordinary = fixture().callbacks;
+ registerBotCapabilityTools(registry, { getSessionContext: () => ({ sessionId: 'current-bot', agentKind: 'codex', workingDir: '/w' }),
+ callbacks: { ...ordinary, models, setDefaultModel } });
+ await registry.call('get_app_default_model', {});
+ expect(models).toHaveBeenCalledWith({ callerSessionId: 'current-bot' });
+ expect((await registry.call('set_app_default_model', { id: 'selected', callerSessionId: 'other' })).isError).toBe(true);
+ expect(setDefaultModel).not.toHaveBeenCalled();
+ 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' });
+});
diff --git a/packages/lizi-mcps/src/__tests__/botSkillsTool.test.ts b/packages/lizi-mcps/src/__tests__/botSkillsTool.test.ts
index ddbaa80c75..cd09c96e05 100644
--- a/packages/lizi-mcps/src/__tests__/botSkillsTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botSkillsTool.test.ts
@@ -46,7 +46,7 @@ describe('Bot skill tools', () => {
callbacks: { save, list: vi.fn() },
});
- const result = await reg.call('save_bot_skill', {
+ const result = await reg.call('save_teammate_skill', {
name: 'weekly-report',
description: 'How I put the weekly report together',
body: '1. Pull merged PRs\n2. Group by author',
@@ -74,7 +74,7 @@ describe('Bot skill tools', () => {
},
});
- const result = await reg.call('save_bot_skill', {
+ const result = await reg.call('save_teammate_skill', {
name: 'weekly-report',
description: 'sharper now',
body: 'step 1',
@@ -83,7 +83,7 @@ describe('Bot skill tools', () => {
});
it('lists what the Bot already learned so it does not learn it twice', async () => {
- const result = await registry().call('list_bot_skills', {});
+ const result = await registry().call('list_teammate_skills', {});
expect(parse(result)).toMatchObject({ ok: true, skills: [SKILL] });
});
@@ -94,10 +94,10 @@ describe('Bot skill tools', () => {
callbacks: { save: vi.fn(), list: vi.fn() },
});
- for (const tool of ['save_bot_skill', 'list_bot_skills']) {
+ for (const tool of ['save_teammate_skill', 'list_teammate_skills']) {
const result = await reg.call(
tool,
- tool === 'save_bot_skill' ? { name: 'a', description: 'b', body: 'c' } : {},
+ tool === 'save_teammate_skill' ? { name: 'a', description: 'b', body: 'c' } : {},
);
expect(result.isError).toBe(true);
expect(parse(result)).toMatchObject({ ok: false, errorCode: 'NOT_A_BOT_SESSION' });
@@ -116,7 +116,7 @@ describe('Bot skill tools', () => {
},
});
- const result = await reg.call('save_bot_skill', {
+ const result = await reg.call('save_teammate_skill', {
name: '周报怎么写',
description: 'b',
body: 'c',
@@ -128,7 +128,7 @@ describe('Bot skill tools', () => {
it('rejects a stray field instead of silently dropping it', async () => {
// registry 用 strictObject 校验:模型把 botId 塞进来必须被打回,不能静默剥掉后
// 当成「写进自己名下」成功返回。
- const result = await registry().call('save_bot_skill', {
+ const result = await registry().call('save_teammate_skill', {
name: 'a',
description: 'b',
body: 'c',
diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
index 28eb7d7309..e8a59f362e 100644
--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
@@ -633,7 +633,7 @@ describe("cindy_helper MCP server", () => {
});
describe("direct Bot MCP tools", () => {
- it.each(["claude-code", "codex"] as const)("omits ghost plugin guidance from find_bot_capabilities on remote %s", async (agentKind) => {
+ it.each(["claude-code", "codex"] as const)("omits ghost plugin guidance from find_teammate_capabilities on remote %s", async (agentKind) => {
let remoteHostId: string | undefined;
const server = createXdtHelperMcpServer({
resolveSurface: async () => "bot",
@@ -655,23 +655,23 @@ describe("direct Bot MCP tools", () => {
const client = new Client({ name: "remote-bot-capability-desc", version: "0.0.0" });
await Promise.all([server.connect(st), client.connect(ct)]);
try {
- const localTool = (await client.listTools()).tools.find((tool) => tool.name === "find_bot_capabilities");
+ const localTool = (await client.listTools()).tools.find((tool) => tool.name === "find_teammate_capabilities");
expect(localTool?.description).toContain("ghost_list");
const localDiscovered = parsePayload(await client.callTool({
name: "list_tools",
arguments: { category: "bots" },
})).tools as Array<{ name: string; description: string }>;
- expect(localDiscovered.find((tool) => tool.name === "find_bot_capabilities")?.description).toContain("ghost_list");
+ expect(localDiscovered.find((tool) => tool.name === "find_teammate_capabilities")?.description).toContain("ghost_list");
remoteHostId = "ssh-host";
- const remoteTool = (await client.listTools()).tools.find((tool) => tool.name === "find_bot_capabilities");
+ const remoteTool = (await client.listTools()).tools.find((tool) => tool.name === "find_teammate_capabilities");
expect(remoteTool?.description).toContain("Skill");
expect(remoteTool?.description).not.toMatch(/ghost_list|ghost_info|ghost_call/);
const remoteDiscovered = parsePayload(await client.callTool({
name: "list_tools",
arguments: { category: "bots" },
})).tools as Array<{ name: string; description: string }>;
- expect(remoteDiscovered.find((tool) => tool.name === "find_bot_capabilities")?.description).not.toMatch(
+ expect(remoteDiscovered.find((tool) => tool.name === "find_teammate_capabilities")?.description).not.toMatch(
/ghost_list|ghost_info|ghost_call/,
);
} finally {
@@ -702,7 +702,7 @@ describe("direct Bot MCP tools", () => {
name: "list_tools",
arguments: { category: "bots" },
})).tools as Array<{ name: string; description: string }>;
- const find = discovered.find((tool) => tool.name === "find_bot_capabilities");
+ const find = discovered.find((tool) => tool.name === "find_teammate_capabilities");
expect(find?.description).toContain("Skill");
expect(find?.description).toContain("ghost_list");
expect(find?.description).toContain("ghost_info");
diff --git a/packages/lizi-mcps/src/index.ts b/packages/lizi-mcps/src/index.ts
index ac9d37330b..707c09f707 100644
--- a/packages/lizi-mcps/src/index.ts
+++ b/packages/lizi-mcps/src/index.ts
@@ -49,4 +49,4 @@ export * from './computer/index.js';
export * from './contacts/approval.js';
-export { BOT_CONTROL_GUIDANCE, type BotControlState } from './xdt-helper/bot_capabilities.js';
+export { TEAMMATE_CONTROL_GUIDANCE, BOT_CONTROL_GUIDANCE, type BotControlState } from './xdt-helper/bot_capabilities.js';
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts b/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts
index 8a679d0306..113fb597ff 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts
@@ -74,6 +74,15 @@ export interface XdtHelperToolSummary {
export class XdtHelperToolRegistry {
private readonly tools = new Map<string, XdtHelperToolDef>();
+ private readonly aliases = new Map<string, string>();
+
+ /** Accept saved legacy calls without advertising a second set of names to the model. */
+ registerAlias(alias: string, name: string): void {
+ if (this.tools.has(alias) || this.aliases.has(alias) || !this.tools.has(name)) {
+ throw new Error(`[cindyHelperToolRegistry] invalid tool alias: ${alias}`);
+ }
+ this.aliases.set(alias, name);
+ }
register<T extends z.ZodRawShape>(def: {
name: string;
@@ -82,18 +91,18 @@ export class XdtHelperToolRegistry {
inputShape: T;
handler: XdtHelperToolHandler<{ [K in keyof T]: z.infer<T[K]> }>;
}): void {
- if (this.tools.has(def.name)) {
+ if (this.tools.has(def.name) || this.aliases.has(def.name)) {
throw new Error(`[cindyHelperToolRegistry] duplicate tool name: ${def.name}`);
}
this.tools.set(def.name, def as unknown as XdtHelperToolDef);
}
has(name: string): boolean {
- return this.tools.has(name);
+ return this.get(name) !== undefined;
}
get(name: string): XdtHelperToolDef | undefined {
- return this.tools.get(name);
+ return this.tools.get(this.aliases.get(name) ?? name);
}
list(category?: XdtHelperToolCategory): XdtHelperToolSummary[] {
@@ -116,7 +125,7 @@ export class XdtHelperToolRegistry {
}
async call(name: string, rawArgs: unknown): Promise<XdtHelperToolResult> {
- const def = this.tools.get(name);
+ const def = this.get(name);
if (!def) {
return {
content: [
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
index b961f54109..c957311022 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
@@ -4,6 +4,13 @@ import type { ControlResult, LiziMcpSessionContext } from "../types.js";
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[] }[];
+ }, string>>;
+ setDefaultModel?(params: { callerSessionId: string; id: string; effort?: string }): Promise<ControlResult<{
+ current: AppDefaultModelRoute;
+ }, string>>;
/** Host resolves the caller; tools never accept another Bot's id or raw config. */
inspect?(params: { callerSessionId: string }): Promise<ControlResult<{ state: BotControlState }, string>>;
updateProfile?(params: {
@@ -41,6 +48,11 @@ export interface BotCapabilityCallbacks {
>;
}
+export interface AppDefaultModelRoute {
+ harness: 'claude' | 'codex' | 'pi'; providerId: string | null;
+ model: string; effort: string; fastMode: boolean;
+}
+
export interface BotControlState {
profile: { id: string; name: string; description: string; identitySource: string; version: number };
session: { id: string; workingDir: string | null; remoteHostId: string | null };
@@ -50,16 +62,19 @@ export interface BotControlState {
}
/** Same instructions in the runtime baseline and tool descriptions. */
-export const BOT_CONTROL_GUIDANCE = [
- 'Use `get_bot_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.',
- 'Use `update_bot_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 `get_capabilities` for Cindy product 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.',
+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.',
+ '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 `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');
+/** @deprecated Internal compatibility export; new teammate guidance uses the product name. */
+export const BOT_CONTROL_GUIDANCE = TEAMMATE_CONTROL_GUIDANCE;
+
const FIND_BOT_CAPABILITIES_CORE =
- "按需查找 Cindy 已有的 Skill、MCP 连接或内置工具集,返回可用性和当前伙伴是否已加入。";
+ "按需查找应用已有的 Skill、MCP 连接或内置工具集,返回可用性和当前伙伴是否已加入。";
const FIND_BOT_CAPABILITIES_PLUGIN_SENTENCE =
- "插件用 cindy 的 ghost_list / ghost_info 发现并直接按现有授权调用。";
+ "插件用已安装插件网关的 ghost_list / ghost_info 发现并直接按现有授权调用。";
/**
* Local Cindy sessions keep the plugin/`ghost_*` sentence byte-identical.
@@ -78,7 +93,7 @@ export function withCindyGatedBotToolDescriptions<T extends { name: string; desc
): T[] {
if (cindyAvailable) return [...tools];
return tools.map((tool) =>
- tool.name === "find_bot_capabilities"
+ tool.name === "find_teammate_capabilities"
? { ...tool, description: buildFindBotCapabilitiesDescription(false) }
: tool,
);
@@ -93,10 +108,32 @@ export function registerBotCapabilityTools(
cindyAvailable?: boolean;
},
): void {
+ if (deps.callbacks.models) registry.register({
+ name: 'get_app_default_model', category: 'bots',
+ description: '读取当前用户在应用中选择的默认模型,以及已连接、已启用且引擎可用的型号。修改默认模型前先读此表;不要猜型号或启用用户关闭的型号。伙伴显式配置的模型链可能与此默认值不同。',
+ inputShape: {},
+ handler: async () => {
+ const callerSessionId = deps.getSessionContext().sessionId;
+ if (!callerSessionId) return errorPayload('NOT_A_BOT_SESSION', '当前调用未绑定伙伴任务');
+ const result = await deps.callbacks.models!({ callerSessionId });
+ return result.ok ? okPayload({ current: result.current, available: result.available }) : errorPayload(result.errorCode, result.message);
+ },
+ });
+ if (deps.callbacks.setDefaultModel) registry.register({
+ name: 'set_app_default_model', category: 'bots',
+ description: '用户明确要求更换应用默认模型时,使用 get_app_default_model 返回的可用型号 id 保存并读回确认。作用于以后新建任务及跟随应用默认的伙伴;不覆盖已有任务、伙伴单独配置的模型或全局伙伴模型链。仅换当前伙伴时不要改这个全局默认值。失败后重新查询,不得声称已修改。',
+ inputShape: { id: z.string().min(1).max(2048), effort: z.string().max(64).optional() },
+ handler: async (input) => {
+ const callerSessionId = deps.getSessionContext().sessionId;
+ if (!callerSessionId) return errorPayload('NOT_A_BOT_SESSION', '当前调用未绑定伙伴任务');
+ const result = await deps.callbacks.setDefaultModel!({ ...input, callerSessionId });
+ return result.ok ? okPayload({ current: result.current, effective: 'new-tasks-and-following-bots', overridesPreserved: true }) : errorPayload(result.errorCode, result.message);
+ },
+ });
if (deps.callbacks.inspect) registry.register({
- name: "get_bot_state",
+ name: "get_teammate_state",
category: "bots",
- description: BOT_CONTROL_GUIDANCE,
+ description: TEAMMATE_CONTROL_GUIDANCE,
inputShape: {},
handler: async () => {
const callerSessionId = deps.getSessionContext().sessionId;
@@ -106,9 +143,9 @@ export function registerBotCapabilityTools(
},
});
if (deps.callbacks.updateProfile) registry.register({
- name: "update_bot_profile",
+ name: "update_teammate_profile",
category: "bots",
- description: BOT_CONTROL_GUIDANCE,
+ description: TEAMMATE_CONTROL_GUIDANCE,
inputShape: {
expectedVersion: z.number().int().positive(),
name: z.string().trim().min(1).max(200).optional(),
@@ -126,7 +163,7 @@ export function registerBotCapabilityTools(
});
const kind = z.enum(["skill", "mcp", "toolset"]);
registry.register({
- name: "find_bot_capabilities",
+ name: "find_teammate_capabilities",
category: "bots",
description: buildFindBotCapabilitiesDescription(deps.cindyAvailable !== false),
inputShape: { kind, query: z.string().max(200).optional() },
@@ -141,10 +178,10 @@ export function registerBotCapabilityTools(
},
});
registry.register({
- name: "set_bot_capability",
+ name: "set_teammate_capability",
category: "bots",
description:
- "把查到的已有能力加入当前伙伴,或从当前伙伴移除。复用 Cindy 已有安装和连接,不修改共享源、凭证或全局开关。新挂载在下一轮生效;当前轮不要声称已有尚未挂载的工具。",
+ "把查到的已有能力加入当前伙伴,或从当前伙伴移除。复用应用已有安装和连接,不修改共享源、凭证或全局开关。新挂载在下一轮生效;当前轮不要声称已有尚未挂载的工具。",
inputShape: { kind, id: z.string().min(1).max(512), joined: z.boolean() },
handler: async (input) => {
const callerSessionId = deps.getSessionContext().sessionId;
@@ -156,4 +193,10 @@ export function registerBotCapabilityTools(
: errorPayload(result.errorCode, result.message);
},
});
+ for (const [legacy, name] of [
+ ['get_bot_state', 'get_teammate_state'],
+ ['update_bot_profile', 'update_teammate_profile'],
+ ['find_bot_capabilities', 'find_teammate_capabilities'],
+ ['set_bot_capability', 'set_teammate_capability'],
+ ]) if (registry.has(name)) registry.registerAlias(legacy, name);
}
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_skills.ts b/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
index 88e9910a01..0701b6a075 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
@@ -31,7 +31,7 @@ export interface BotSkillCallbacks {
slug?: string;
}): Promise<
ControlResult<
- { skill: BotSkillSummaryWire; created: boolean; effective: 'next-session' },
+ { skill: BotSkillSummaryWire; created: boolean; effective: 'next-turn' | 'next-session' },
string
>
>;
@@ -58,13 +58,13 @@ export function registerBotSkillTools(
deps: BotSkillToolDeps,
): void {
registry.register({
- name: 'save_bot_skill',
+ name: 'save_teammate_skill',
category: 'bots',
description:
- '把刚做完的一类任务的可复用做法,存成当前 Bot 自己的一个技能(真技能文件,不是记忆分片)。'
+ '把刚做完的一类任务的可复用做法,存成当前伙伴自己的一个技能(真技能文件,不是记忆分片)。'
+ '同名技能会被原地更新 —— 发现更好的做法就用同一个 name 再存一次。'
+ 'body 写成可照做的步骤,不要写这一次的具体结论。'
- + '技能在**下一次任务**才会被挂载,本次任务里不要指望能立刻调用它。',
+ + '宿主会在当前聊天的安全轮次边界加载技能;以返回的 effective 为准,旧宿主可能需要下一任务。当前轮不要调用尚未挂载的新技能。',
inputShape: {
name: z
.string()
@@ -101,10 +101,10 @@ export function registerBotSkillTools(
});
registry.register({
- name: 'list_bot_skills',
+ name: 'list_teammate_skills',
category: 'bots',
description:
- '列出当前 Bot 已经学会的技能(名称 / 说明 / 更新时间,不含正文)。'
+ '列出当前伙伴已经学会的技能(名称 / 说明 / 更新时间,不含正文)。'
+ '打算沉淀新技能前先看一眼:已经有的就用同名更新,不要重复学一遍。',
inputShape: {},
handler: async () => {
@@ -116,4 +116,6 @@ export function registerBotSkillTools(
: errorPayload(result.errorCode, result.message);
},
});
+ registry.registerAlias('save_bot_skill', 'save_teammate_skill');
+ registry.registerAlias('list_bot_skills', 'list_teammate_skills');
}