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): guard remote skills and retain committed invitations

zqchris039075d44c91
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 3bf8ea831f..05c7832849 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -4,7 +4,7 @@ import Database from 'better-sqlite3';
import type { ProviderView } from '@cindy/model-providers';
import { createHash } from 'node:crypto';
import { join, resolve } from 'node:path';
-import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -73,6 +73,7 @@ const h = await vi.hoisted(async () => {
customMcpConfigs: [] as CustomMcpConfig[],
mcpProviders: [] as McpProvider[],
providers: [] as ProviderView[],
+ listProviders: vi.fn(async (): Promise<ProviderView[]> => h.providers),
ownerScopeKey: 'owner-a:1',
ownerBoundaryPending: false,
});
@@ -129,7 +130,7 @@ vi.mock('../../../maker-host/custom-mcp-store.js', async (importOriginal) => ({
listCustomMcpServers: async () => h.customMcpConfigs,
}));
vi.mock('../../../maker-host/createDesktopProviderService.js', () => ({
- getDesktopProviderService: () => ({ listProviders: async () => h.providers }),
+ getDesktopProviderService: () => ({ listProviders: h.listProviders }),
}));
vi.mock('../../../maker-host/index.js', () => ({
validateBotCapabilityAdditions: h.validateCapabilityAdditions,
@@ -459,6 +460,7 @@ beforeEach(async () => {
resetCustomMcpRegistry();
registerCustomMcpArrays(h.mcpProviders);
vi.clearAllMocks();
+ h.listProviders.mockReset().mockImplementation(async () => h.providers);
vi.mocked(provisionDefaultBot).mockReset();
h.remove.mockImplementation(async (...args) => {
const fs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
@@ -853,6 +855,44 @@ describe('Bot canonical Session lifecycle', () => {
await expect(invoke('local-db:bots:list', undefined)).resolves.toEqual([]);
});
+ it.each(['legacy IPC', 'resource registry'])('queues committed Cindy before a failed projection on first %s entry', async (entry) => {
+ const real = await vi.importActual<typeof import('../../../maker-ipc/botDefaultProvisioning')>(
+ '../../../maker-ipc/botDefaultProvisioning');
+ vi.mocked(provisionDefaultBot).mockImplementation(real.provisionDefaultBot);
+ h.sqlite!.prepare('DELETE FROM bot_profiles').run();
+ h.ownerScopeKey = `mobile-projection-failure-${entry}:1`;
+ const invitation = await import('../../../maker-ipc/botInvitation');
+ const queued = vi.spyOn(invitation, 'queueBotInvitation').mockImplementation(() => {});
+ let projectionFailed = false;
+ h.listProviders.mockImplementation(async () => {
+ if (!projectionFailed && h.sqlite!.prepare("SELECT id FROM bot_profiles WHERE id = 'cindy-default'").get()) {
+ // A provider read after the create transaction, before the presentation
+ // can complete. The invitation must already be queued at this point.
+ expect(queued).toHaveBeenCalledWith('cindy-default', expect.any(Object), false);
+ projectionFailed = true;
+ throw new Error('Temporary provider projection failure');
+ }
+ return h.providers;
+ });
+ try {
+ const list: () => Promise<{ id: string }[]> = entry === 'legacy IPC' ? () => runDeviceLinkInvokeContext(
+ { controllerDeviceId: 'mobile-first', channel: 'local-db:bots:list' },
+ () => invoke('local-db:bots:list', undefined),
+ ) : listBotRemoteResourceSources;
+ expect((await list()).map(row => row.id)).toEqual(['cindy-default']);
+ expect(projectionFailed).toBe(true);
+ expect(queued).toHaveBeenCalledTimes(1);
+ const stored = h.sqlite!.prepare("SELECT capabilities_json AS config FROM bot_profile_versions WHERE bot_id = 'cindy-default'").get() as { config: string };
+ expect(JSON.parse(stored.config).invitation).toMatchObject({ stage: 'skills' });
+ // A second remote read only sees durable history. It must not be needed
+ // to repair the lost queue entry, or create a second default teammate.
+ expect((await list()).map(row => row.id)).toEqual(['cindy-default']);
+ expect(queued).toHaveBeenCalledTimes(1);
+ } finally {
+ queued.mockRestore();
+ }
+ });
+
it('rejects a remote list when its owner changes during provisioning', async () => {
vi.mocked(provisionDefaultBot).mockImplementationOnce(async () => { h.ownerScopeKey = 'other:2'; });
await expect(runDeviceLinkInvokeContext(
@@ -1629,7 +1669,7 @@ describe('Bot canonical Session lifecycle', () => {
expect(opts.botRuntimeProfile?.skillPolicy.catalog).toEqual([]);
});
- it('does not mount local learned Skills into a remote Bot task', async () => {
+ it.each(['pi', 'claude-code', 'codex'] as const)('does not advertise or mount local personal Skills on remote %s', async (agentKind) => {
const created = await invoke('local-db:bots:create-canonical-session', {
botId: 'bot-1',
expectedCanonicalSessionId: null,
@@ -1637,7 +1677,7 @@ describe('Bot canonical Session lifecycle', () => {
});
const opts: MakerSessionCreateOpts = {
id: created.session.id,
- agentKind: 'pi',
+ agentKind,
workingDir: created.session.workingDir,
workspaceKind: 'dialogue',
model: 'grok-4.5',
@@ -1647,6 +1687,7 @@ describe('Bot canonical Session lifecycle', () => {
await hydrateBotProfileRuntime(opts, {
listSkills: async () => [],
+ listToolsets: async () => [{ id: 'xdt_helper', name: 'Helper', available: true }],
listOwnSkills: async () => ({
pluginRoot: '/userdata/bot-skills/bot-1',
skills: [{ name: 'weekly-report', description: '', path: '/userdata/bot-skills/bot-1/skills/weekly-report' }],
@@ -1656,6 +1697,41 @@ describe('Bot canonical Session lifecycle', () => {
// 路径是本机的,远端 harness 打不开 —— 挂一串死路径比不挂更糟。
expect(opts.botRuntimeProfile?.skillPolicy.ownSkills).toBeUndefined();
expect(opts.botRuntimeProfile?.skillPolicy.ownSkillPluginRoots).toBeUndefined();
+ expect(opts.botProfileContextPrompt).not.toContain('`save_teammate_skill`');
+ expect(opts.botProfileContextPrompt).not.toContain('`list_teammate_skills`');
+ expect(opts.botProfileContextPrompt).not.toContain('then create or refine a useful personal Skill');
+ expect(opts.botProfileContextPrompt).toContain('Personal Skill storage and learning are unavailable');
+ expect(opts.botProfileContextPrompt).toContain('`create_teammate`');
+ expect(opts.botProfileContextPrompt).toContain('`start_session_task`');
+ expect(opts.botProfileContextPrompt).toContain('Respect the user’s memory switch');
+ if (agentKind === 'pi') expect(opts.botProfileContextPrompt).toContain('`ghost_list`, `ghost_info`, `ghost_call`');
+ });
+
+ it.each(['canonical', 'delegation'] as const)('rejects remote %s personal Skill access before local storage or refresh', async (role) => {
+ const created = await invoke('local-db:bots:create-canonical-session', {
+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,
+ });
+ const sessionId = created.session.id;
+ h.sqlite!.prepare('UPDATE sessions SET remote_host_id = ? WHERE id = ?').run('ssh-host', sessionId);
+ h.sqlite!.prepare('UPDATE bot_session_links SET role = ? WHERE session_id = ?').run(role, sessionId);
+ const userDataDir = join(h.userDataDir, `remote-skill-guard-${role}`);
+ const requestRefresh = vi.fn(async () => true);
+ const deps = { userDataDir, requestRefresh };
+ const input = { callerSessionId: sessionId, name: 'Verified workflow', description: 'A reusable method', body: 'A verified sequence of steps.' };
+ const rejected = { ok: false, errorCode: 'REMOTE_SKILLS_UNAVAILABLE' };
+ expect(await listBotSkillsForSession({ callerSessionId: sessionId }, deps)).toMatchObject(rejected);
+ expect(await saveBotSkillForSession(input, deps)).toMatchObject(rejected);
+ expect(existsSync(userDataDir)).toBe(false);
+ expect(requestRefresh).not.toHaveBeenCalled();
+
+ // Device-link control of a desktop runtime is still local: the execution
+ // target, not the caller's phone/transport, determines shelf availability.
+ h.sqlite!.prepare('UPDATE sessions SET remote_host_id = NULL WHERE id = ?').run(sessionId);
+ expect(await saveBotSkillForSession(input, deps)).toMatchObject({ ok: true, effective: 'next-turn' });
+ expect(await listBotSkillsForSession({ callerSessionId: sessionId }, deps)).toMatchObject({
+ ok: true, skills: [expect.objectContaining({ name: input.name })],
+ });
+ expect(requestRefresh).toHaveBeenCalledTimes(1);
});
it('does not promise or mount a local Bot Home into a remote task', async () => {
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 530345401e..39a03b2821 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -1023,9 +1023,11 @@ export async function createBotProfile(raw: unknown) {
}
assertCreationOwnerStillCurrent();
if (prepareInvitation) {
+ // Creation is already committed. A fallible presentation read must not
+ // strand that durable invitation before it reaches the runtime queue.
+ queueBotInvitation(id);
const profile = await readProfile(client, id);
broadcastBotProfileChanged({ botId: id, change: 'created' });
- queueBotInvitation(id);
return profile;
}
await syncBotProfileFolder(
diff --git a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
index ed505abe74..26a2132dcf 100644
--- a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
+++ b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts
@@ -863,7 +863,7 @@ export async function hydrateBotProfileRuntime(
// Delegation children keep Cindy's normal Session prompt plus their
// narrow task context.
...(row.role === 'canonical'
- ? [buildBotCapabilityContextPrompt({ helperAvailable, cindyAvailable })]
+ ? [buildBotCapabilityContextPrompt({ helperAvailable, cindyAvailable, ownSkillsEnabled: promptCapabilities.ownSkillsEnabled })]
: []),
],
};
diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.ts
index 73ea41fd40..f8bd4c1e21 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts
@@ -128,6 +128,7 @@ async function defaultResolveBotId(callerSessionId: string): Promise<
canonicalSessionId: botProfiles.canonicalSessionId,
role: botSessionLinks.role,
sessionStatus: sessions.status,
+ remoteHostId: sessions.remoteHostId,
profileStatus: botProfiles.status,
linkArchivedAt: botSessionLinks.archivedAt,
})
@@ -145,6 +146,12 @@ async function defaultResolveBotId(callerSessionId: string): Promise<
if (row.role !== 'canonical' && row.role !== 'delegation') {
return { ok: false, errorCode: 'BOT_SESSION_READ_ONLY', message: '当前 Bot 历史任务为只读状态' };
}
+ // Runtime hydration cannot mount the local personal shelf on an SSH host.
+ // Reject before migration/read/write and before refreshing the local canonical.
+ // Device-link callers executing on this desktop still have no remoteHostId.
+ if (row.remoteHostId) {
+ return { ok: false, errorCode: 'REMOTE_SKILLS_UNAVAILABLE', message: '当前远端任务尚未挂载伙伴自有 Skill 存储,不能读取或保存本机 Skill,也不能承诺远端生效' };
+ }
return { ok: true, botId: row.botId, canonicalSessionId: row.canonicalSessionId };
}
diff --git a/apps/desktop/src/main/maker-ipc/teammateGuide.ts b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
index 8fb35343bb..5e28a17b16 100644
--- a/apps/desktop/src/main/maker-ipc/teammateGuide.ts
+++ b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
@@ -5,9 +5,11 @@ 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 } = {},
+ options: { helperAvailable?: boolean; cindyAvailable?: boolean; ownSkillsEnabled?: boolean } = {},
): string {
const helperAvailable = options.helperAvailable !== false;
+ // Use the same capability signal as runtime Skill mounting and learning.
+ const ownSkillsEnabled = helperAvailable && options.ownSkillsEnabled !== 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
@@ -23,18 +25,21 @@ export function buildTeammateGuide(
'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,
- 'The preloaded teammate-guide is itself your shared baseline Skill. When asked which Skills or capabilities you have, identify this shared Skill, query `list_teammate_skills` for personal Skills, and distinguish those from optional external references returned by `get_teammate_state`. Empty references or an empty personal shelf never mean that you lack the shared teammate Skill or its operating procedures.',
+ 'The preloaded teammate-guide is itself your shared baseline Skill. When asked which Skills or capabilities you have, identify this shared Skill and distinguish it from optional external references returned by `get_teammate_state`. Empty references or an empty personal shelf never mean that you lack the shared teammate Skill or its operating procedures.',
'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.`,
+ `Use direct teammate tools for your own memory 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.',
+ 'Actively personalize your own memory 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. 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 ? [
+ ...(ownSkillsEnabled ? [
+ 'Use `list_teammate_skills` to inspect your personal Skills. 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. Use your own tools and model within the current turn, not an extra learning model or background review worker.',
'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.',
- ] : []),
+ ] : [
+ 'Personal Skill storage and learning are unavailable in this runtime. Do not read or write the local personal shelf, or claim a saved personal Skill will load on this host. This does not remove the shared teammate-guide, memory under its own switch, or capabilities actually available through the live tools.',
+ ]),
].join('\n');
}
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 32974110cd..13c4606bc5 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -107,7 +107,9 @@ Cindy 应用,也不取消伙伴已委派的独立任务。操作中禁用重
(见第 6.1 节)。
- 上下文压缩、模型 fallback、失败补偿和删除临时任务不得移动或删除 Home 内容。
- 远端运行必须使用远端实际存在且归属于该 Bot 的 Home;在远端 Home 尚未完成供给前,不得把
- 本机路径写进提示词或伪装成可访问目录。
+ 本机路径写进提示词或伪装成可访问目录。远端自有 Skill 未装配时,共享指南不引导本机 Skill
+ 读写和学习,工具入口在存储及刷新之前明确返回不可用,不能承诺下一轮或新任务生效;
+ 这不影响远端已支持的共同基座、记忆、协作及能力发现。手机控制本机运行时仍使用本机自有 Skill。
## 5. 模型候选链
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
index fb321d792f..8af9dda933 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts
@@ -65,7 +65,7 @@ export interface BotControlState {
/** Same instructions in the runtime baseline and tool descriptions. */
export const TEAMMATE_CONTROL_GUIDANCE = [
'Use `get_teammate_state` to inspect your current profile, stable chat, configured model candidates, memory switch and capability references. Candidates and selected references are not proof of the model or tools running this turn; the live runtime and registered tools are authoritative.',
- 'The references arrays contain optional external grants, not the shared teammate guide or your personal Skill shelf. Empty references do not mean you have no Skills. Use `list_teammate_skills` to inspect personal Skills; report the preloaded shared guide separately.',
+ 'The references arrays contain optional external grants, not the shared teammate guide or your personal Skill shelf. Empty references do not mean you have no Skills. Report the preloaded shared guide separately; personal Skill storage and learning depend on the current runtime mounting your own shelf, as described in the teammate guide.',
'Use `update_teammate_profile` when the user asks to change your name, introduction, identity or your own model selection. Read the current version first and patch only the requested fields. For modelChain, first read `get_app_default_model` for enabled route ids and supported effort/Fast settings; supply the complete ordered chain (1–5 routes), preserving existing candidates unless the user asks to replace them. Set modelChain to null to remove your override and follow the application default again. This saves only your profile through the same settings service, persists across restarts, and applies next turn; it never changes the application default, other teammates, personal Skills, memory or chat history. A next-turn save is not proof of the model running this turn.',
'Use `get_capabilities` for application features and UI guidance. It describes the product, not a permission grant or proof that every feature is available here. Use the matching live tool to act, and verify its result before claiming success.',
].join('\n');
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_skills.ts b/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
index 0701b6a075..7164b3159b 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_skills.ts
@@ -64,6 +64,7 @@ export function registerBotSkillTools(
'把刚做完的一类任务的可复用做法,存成当前伙伴自己的一个技能(真技能文件,不是记忆分片)。'
+ '同名技能会被原地更新 —— 发现更好的做法就用同一个 name 再存一次。'
+ 'body 写成可照做的步骤,不要写这一次的具体结论。'
+ + '需要当前运行位置支持伙伴自有 Skill 存储;远端未挂载时返回不可用,不会代写本机,也不能声称已保存或生效。'
+ '宿主会在当前聊天的安全轮次边界加载技能;以返回的 effective 为准,旧宿主可能需要下一任务。当前轮不要调用尚未挂载的新技能。',
inputShape: {
name: z
@@ -105,6 +106,7 @@ export function registerBotSkillTools(
category: 'bots',
description:
'列出当前伙伴已经学会的技能(名称 / 说明 / 更新时间,不含正文)。'
+ + '需要当前运行位置支持伙伴自有 Skill 存储;远端未挂载时返回不可用,不把本机技能表冒充远端可用技能。'
+ '打算沉淀新技能前先看一眼:已经有的就用同名更新,不要重复学一遍。',
inputShape: {},
handler: async () => {