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(desktop): preserve Learn across all harnesses

xd-bobo259c9f96ba0c
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index d73c40b075..93ba2d54da 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -295,7 +295,7 @@ describe('maker SEND transaction', () => {
);
});
- it('does not request a Learn grant from a runtime without exact-path dispatch', async () => {
+ it('forwards the exact Learn pin to Claude for provider-boundary expansion', async () => {
const grant = {
version: 1 as const,
sessionInstanceId: 'session-instance-1',
@@ -320,13 +320,16 @@ describe('maker SEND transaction', () => {
},
);
- expect(captureCindyLearnInvocation).not.toHaveBeenCalled();
+ expect(captureCindyLearnInvocation).toHaveBeenCalledTimes(1);
const sendOptions = vi.mocked(claudeSession.send).mock.calls[0]?.[1];
- expect(sendOptions?.[PINNED_SKILL_INVOCATION]).toBeUndefined();
+ expect(sendOptions?.[PINNED_SKILL_INVOCATION]).toEqual({
+ name: 'learn',
+ path: grant.resolvedSkillPath,
+ });
expect(deps.createDbMessage).toHaveBeenCalledWith(
'session-1',
expect.objectContaining({
- agentMeta: expect.not.objectContaining({ cindyLearnInvocation: expect.anything() }),
+ agentMeta: expect.objectContaining({ cindyLearnInvocation: grant }),
}),
undefined,
);
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index ae3e4b63d5..4d0cf17cc5 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -1407,11 +1407,10 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
directPreDispatchHookStarted = true;
}
let cindyLearnInvocation: CindyLearnInvocationGrant | null = null;
- // Only runtimes with an exact-path dispatch contract may mint the paid
- // Learn grant. Claude's SDK resolves slash commands by name and exposes
- // no path-level invocation or provenance, so it must stay fail-closed.
- const supportsPinnedSkillDispatch = sess.agentKind === 'codex' || sess.agentKind === 'pi';
- if (persistUserMessage && supportsPinnedSkillDispatch && deps.captureCindyLearnInvocation) {
+ // Every Cindy harness consumes this exact-path pin at its provider
+ // boundary: Codex sends a structured Skill item, Pi validates the live
+ // command provenance, and Claude expands the attested file directly.
+ if (persistUserMessage && deps.captureCindyLearnInvocation) {
try {
// Capture before Session.send: onAccepted persists this exact snapshot,
// and the provider cannot start until that durable write completes.
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index a2780de290..63e7cfbdf2 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -12272,10 +12272,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
prepareUserMessageForAgent(sessionId, message, 'send'),
materializeDirectSendOssAttachments,
captureCindyLearnInvocation: async (session, persistedContent, dispatchedText) => {
- // Codex accepts an exact Skill path in turn/start. Pi exposes the exact
- // loaded command provenance and validates it again at prompt dispatch.
- // Claude's SDK offers name-only slash dispatch, so it cannot mint this grant.
- if (session.agentKind !== 'codex' && session.agentKind !== 'pi') return null;
const invocationText = visibleMessageTextForConversationSearch(
'user',
typeof persistedContent === 'string' ? persistedContent : JSON.stringify(persistedContent),
@@ -12300,10 +12296,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const learnDescriptor = descriptors.find((descriptor) => descriptor.name === 'learn');
if (!learnDescriptor || !isCindySkillEnabled(learnDescriptor.absolutePath)) return null;
- const result = await maker.listAgentSkills(session.agentKind, {
- workingDir: session.workDir,
- sessionId: session.id,
- });
+ const result = session.agentKind === 'claude-code'
+ ? await maker.listAgentRuntimeSkills(session.agentKind, {
+ workingDir: session.workDir,
+ sessionId: session.id,
+ runtimeConfigDir: process.env.CLAUDE_CONFIG_DIR?.trim() || (
+ process.env.XDT_USER_DATA_DIR && !app.isPackaged
+ ? path.join(app.getPath('userData'), 'claude-home')
+ : path.join(os.homedir(), '.claude')
+ ),
+ })
+ : await maker.listAgentSkills(session.agentKind, {
+ workingDir: session.workDir,
+ sessionId: session.id,
+ });
if (result.errors?.length || maker.getSession(session.id) !== session) return null;
const learnCandidates = activeCindyBuiltInAgentSkills(
result.skills,
@@ -12311,7 +12317,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
isCindySkillEnabled,
).filter((skill) => skill.name.toLowerCase() === 'learn');
if (
- learnCandidates.length === 0
+ learnCandidates.length !== 1
|| learnCandidates.some((skill) => skill.builtIn !== true || !skill.path)
) return null;
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/pinned-skill-invocation.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/pinned-skill-invocation.test.ts
new file mode 100644
index 0000000000..c8006c6ccb
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/__tests__/pinned-skill-invocation.test.ts
@@ -0,0 +1,61 @@
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { preparePinnedClaudeSkillInvocation } from '../pinned-skill-invocation.js';
+
+const tempDirs: string[] = [];
+
+async function writeSkill(name = 'learn'): Promise<string> {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-pinned-skill-'));
+ tempDirs.push(dir);
+ const skillFile = path.join(dir, 'SKILL.md');
+ await fs.writeFile(skillFile, [
+ '---',
+ `name: ${name}`,
+ 'description: Test Skill.',
+ '---',
+ '',
+ '# Exact Skill body',
+ ].join('\n'));
+ return skillFile;
+}
+
+afterEach(async () => {
+ await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
+});
+
+describe('preparePinnedClaudeSkillInvocation', () => {
+ it.each(['/learn release flow', '/skill:learn release flow'])(
+ 'keeps the original %s invocation while loading the attested file',
+ async (input) => {
+ const skillFile = await writeSkill();
+
+ await expect(preparePinnedClaudeSkillInvocation(
+ input,
+ { name: 'learn', path: skillFile },
+ )).resolves.toBe([
+ '<command-name>learn</command-name>',
+ '<command-message>/learn</command-message>',
+ '<command-args>release flow</command-args>',
+ '',
+ '# Exact Skill body',
+ ].join('\n'));
+ },
+ );
+
+ it('fails closed when the command or frontmatter does not match the pin', async () => {
+ const skillFile = await writeSkill('other');
+
+ await expect(preparePinnedClaudeSkillInvocation(
+ '/other release flow',
+ { name: 'learn', path: skillFile },
+ )).rejects.toThrow('does not match the user invocation');
+ await expect(preparePinnedClaudeSkillInvocation(
+ '/learn release flow',
+ { name: 'learn', path: skillFile },
+ )).rejects.toThrow('metadata does not match');
+ });
+});
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
index dfefd14de4..306abd7e45 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
@@ -13,6 +13,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { PINNED_SKILL_INVOCATION } from '../../base-agent.js';
import type { AgentDeps, RemoteClaudeRoute } from '../../base-agent.js';
import type { AuthAdapter, AuthAdapterOptions } from '../../../interfaces/auth-adapter.js';
import type { PermissionMode } from '../../../types/common.js';
@@ -276,6 +277,40 @@ describe('ClaudeCodeAgent plan mode', () => {
await handle.close();
});
+ it('expands the exact Host-pinned Skill before Claude resolves slash commands by name', async () => {
+ const { handle, queryPrompt, workingDir } = await startPlanSession(false);
+ const skillFile = path.join(workingDir, 'system-skills', 'v10', 'learn', 'SKILL.md');
+ await fs.mkdir(path.dirname(skillFile), { recursive: true });
+ await fs.writeFile(skillFile, [
+ '---',
+ 'name: learn',
+ 'description: Start Cindy Learn.',
+ '---',
+ '',
+ '# Trusted Learn instructions',
+ '',
+ 'Call the Cindy Learn host exactly once.',
+ ].join('\n'));
+ const nextInput = queryPrompt[Symbol.asyncIterator]().next();
+
+ await handle.send(
+ { type: 'user', content: '/learn release flow' },
+ { [PINNED_SKILL_INVOCATION]: { name: 'learn', path: skillFile } },
+ );
+
+ const sdkInput = (await nextInput).value;
+ expect(sdkInput?.message?.content).toBe([
+ '<command-name>learn</command-name>',
+ '<command-message>/learn</command-message>',
+ '<command-args>release flow</command-args>',
+ '',
+ '# Trusted Learn instructions',
+ '',
+ 'Call the Cindy Learn host exactly once.',
+ ].join('\n'));
+ await handle.close();
+ });
+
it('starts the SDK query in plan mode while keeping the underlying permission mode', async () => {
const { handle, queryOptions } = await startPlanSession(true);
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index aa26f74d4a..c8765b6f30 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -60,6 +60,7 @@ import {
AgentNotAuthenticatedError,
AgentStartupStoppedError,
TurnPermissionPolicyUnsupportedError,
+ PINNED_SKILL_INVOCATION,
type AgentSessionHandle,
type AgentDeps,
type StartSessionOptions,
@@ -67,6 +68,7 @@ import {
type SendOptions,
type TurnPermissionPolicy,
} from '../base-agent.js';
+import { preparePinnedClaudeSkillInvocation } from './pinned-skill-invocation.js';
import { isBotMcpServerAllowed } from '../shared/bot-runtime-policy.js';
import { SYSTEM_PROMPT_APPEND as MAKER_SYSTEM_PROMPT_APPEND } from './system-prompt-append.js';
import { MAKER_MEMORY_RULES } from '../../memory/system-prompt.js';
@@ -6066,9 +6068,20 @@ export class ClaudeCodeAgent extends BaseAgent {
reviewReadGrants,
);
}
+ const pinnedSkill = sendOpts?.[PINNED_SKILL_INVOCATION];
+ let providerContent = message.content;
+ if (pinnedSkill) {
+ if (typeof providerContent !== 'string') {
+ throw new Error('Pinned Claude Skill invocation must be text-only.');
+ }
+ providerContent = await preparePinnedClaudeSkillInvocation(
+ providerContent,
+ pinnedSkill,
+ );
+ }
// SSH 图片路径属于远端主机,不能在桌面端压缩或读取;保留路径引用交给远端 SDK。
const content = await toClaudeSdkContent(
- withLibraryNativeReadContext(message.content, mutableLibraryRoot, activeQueryReadonlyDirs),
+ withLibraryNativeReadContext(providerContent, mutableLibraryRoot, activeQueryReadonlyDirs),
undefined,
!opts.remoteHostId,
);
diff --git a/packages/maker-core/src/agents/claude-code/pinned-skill-invocation.ts b/packages/maker-core/src/agents/claude-code/pinned-skill-invocation.ts
new file mode 100644
index 0000000000..6a09033055
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/pinned-skill-invocation.ts
@@ -0,0 +1,77 @@
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+import matter from 'gray-matter';
+
+import type { PinnedSkillInvocation } from '../base-agent.js';
+
+const MAX_PINNED_SKILL_BYTES = 512 * 1024;
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+/**
+ * Expand a Host-attested Skill from its exact file before Claude's name-only
+ * slash-command resolver can choose a colliding project or user Skill.
+ *
+ * The command envelope mirrors Claude Code's native prompt-command transcript
+ * shape, so the task still appears and behaves like the user's original
+ * `/name args` invocation. Only the instruction source changes: it comes from
+ * the path that Main attested for this exact turn.
+ */
+export async function preparePinnedClaudeSkillInvocation(
+ input: string,
+ pinned: PinnedSkillInvocation,
+): Promise<string> {
+ if (!/^[a-z0-9][a-z0-9_-]*$/i.test(pinned.name)) {
+ throw new Error('Pinned Claude Skill has an invalid name.');
+ }
+ if (!path.isAbsolute(pinned.path) || path.basename(pinned.path).toLowerCase() !== 'skill.md') {
+ throw new Error('Pinned Claude Skill must reference an absolute SKILL.md path.');
+ }
+
+ const invocation = new RegExp(
+ `^/(?:skill:)?${escapeRegExp(pinned.name)}(?:\\s+([\\s\\S]*))?$`,
+ 'i',
+ ).exec(input.trim());
+ if (!invocation) {
+ throw new Error('Pinned Claude Skill does not match the user invocation.');
+ }
+
+ const handle = await fs.open(pinned.path, 'r');
+ let raw: string;
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_PINNED_SKILL_BYTES) {
+ throw new Error('Pinned Claude Skill file is missing or too large.');
+ }
+ raw = await handle.readFile('utf8');
+ } finally {
+ await handle.close();
+ }
+
+ let parsed: ReturnType<typeof matter>;
+ try {
+ parsed = matter(raw);
+ } catch {
+ throw new Error('Pinned Claude Skill has invalid frontmatter.');
+ }
+ const frontmatterName = parsed.data?.name;
+ if (
+ typeof frontmatterName !== 'string'
+ || frontmatterName.trim().toLowerCase() !== pinned.name.toLowerCase()
+ || !parsed.content.trim()
+ ) {
+ throw new Error('Pinned Claude Skill metadata does not match the attested Skill.');
+ }
+
+ const args = (invocation[1] ?? '').trim();
+ return [
+ `<command-name>${pinned.name}</command-name>`,
+ `<command-message>/${pinned.name}</command-message>`,
+ ...(args ? [`<command-args>${args}</command-args>`] : []),
+ '',
+ parsed.content.trim(),
+ ].join('\n');
+}