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): attest Learn dispatch by runtime

xd-bobo4dc87032793b
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 728f14cd97..d73c40b075 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -295,6 +295,43 @@ describe('maker SEND transaction', () => {
);
});
+ it('does not request a Learn grant from a runtime without exact-path dispatch', async () => {
+ const grant = {
+ version: 1 as const,
+ sessionInstanceId: 'session-instance-1',
+ resolvedSkillPath: '/system-skills/v10/learn/SKILL.md',
+ };
+ const captureCindyLearnInvocation = vi.fn(async () => grant);
+ const claudeSession = createSession({ agentKind: 'claude-code' });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => claudeSession),
+ captureCindyLearnInvocation,
+ });
+
+ await createMakerSendTransaction(deps).sendToAgentAccepted(
+ 'session-1',
+ { type: 'user', content: '/learn release flow' },
+ undefined,
+ {
+ persistUserMessage: {
+ clientId: 'claude-learn-1',
+ content: '/learn release flow',
+ },
+ },
+ );
+
+ expect(captureCindyLearnInvocation).not.toHaveBeenCalled();
+ const sendOptions = vi.mocked(claudeSession.send).mock.calls[0]?.[1];
+ expect(sendOptions?.[PINNED_SKILL_INVOCATION]).toBeUndefined();
+ expect(deps.createDbMessage).toHaveBeenCalledWith(
+ 'session-1',
+ expect.objectContaining({
+ agentMeta: expect.not.objectContaining({ cindyLearnInvocation: expect.anything() }),
+ }),
+ undefined,
+ );
+ });
+
it('restamps a trusted local queue edit for the existing Desktop command route', async () => {
const { deps, session } = createDeps();
const transaction = createMakerSendTransaction(deps);
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index eb22df4bcf..ae3e4b63d5 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -1407,7 +1407,11 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
directPreDispatchHookStarted = true;
}
let cindyLearnInvocation: CindyLearnInvocationGrant | null = null;
- if (persistUserMessage && deps.captureCindyLearnInvocation) {
+ // 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) {
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 9705a98ee1..a2780de290 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -12272,6 +12272,10 @@ 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),
@@ -12296,20 +12300,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const learnDescriptor = descriptors.find((descriptor) => descriptor.name === 'learn');
if (!learnDescriptor || !isCindySkillEnabled(learnDescriptor.absolutePath)) return null;
- 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,
- });
+ const result = 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,
diff --git a/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts b/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts
index 594c83c5bf..f15bded05e 100644
--- a/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/runtime-capabilities.test.ts
@@ -5,6 +5,7 @@ import {
capturePiRuntimeCapabilityManifest,
identifyManagedPiPackageCommandNames,
parsePiRuntimeCommands,
+ preparePinnedPiSkillInvocation,
snapshotManagedPiPackageSkills,
} from '../runtime-capabilities.js';
@@ -41,6 +42,58 @@ describe('Pi runtime capability parsing', () => {
});
});
+ it.each(['/learn release flow', '/skill:learn release flow'])(
+ 'pins %s to the sole same-path Pi runtime winner',
+ (input) => {
+ const skillFile = path.resolve('system-skills', 'v10', 'learn', 'SKILL.md');
+ const manifest = {
+ capturedAt: '2026-09-19T00:00:00.000Z',
+ generation: 1,
+ status: 'loaded' as const,
+ source: 'pi:get_commands' as const,
+ commands: [{
+ name: 'skill:learn',
+ source: 'skill',
+ sourceInfo: { path: skillFile, baseDir: path.dirname(skillFile) },
+ }],
+ };
+
+ expect(preparePinnedPiSkillInvocation(
+ input,
+ { name: 'learn', path: skillFile },
+ manifest,
+ )).toBe('/skill:learn release flow');
+ },
+ );
+
+ it('rejects a colliding or ambiguous Pi runtime winner', () => {
+ const pinnedPath = path.resolve('system-skills', 'v10', 'learn', 'SKILL.md');
+ const customPath = path.resolve('project', '.agents', 'skills', 'learn', 'SKILL.md');
+ const command = (skillFile: string) => ({
+ name: 'skill:learn',
+ source: 'skill',
+ sourceInfo: { path: skillFile, baseDir: path.dirname(skillFile) },
+ });
+ const manifest = {
+ capturedAt: '2026-09-19T00:00:00.000Z',
+ generation: 1,
+ status: 'loaded' as const,
+ source: 'pi:get_commands' as const,
+ commands: [command(pinnedPath), command(customPath)],
+ };
+
+ expect(() => preparePinnedPiSkillInvocation(
+ '/learn release flow',
+ { name: 'learn', path: pinnedPath },
+ manifest,
+ )).toThrow('does not match the Pi runtime winner');
+ expect(() => preparePinnedPiSkillInvocation(
+ '/learn release flow',
+ { name: 'learn', path: pinnedPath },
+ { ...manifest, commands: [command(customPath)] },
+ )).toThrow('does not match the Pi runtime winner');
+ });
+
it('marks commands only when Pi provenance is inside an enabled managed package root', () => {
const extensionCommand = {
...command,
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index beae3a1107..6b9cad422e 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -66,6 +66,7 @@ import {
AgentStartupStoppedError,
BaseAgent,
MAIN_OWNED_SEND_CONTEXT,
+ PINNED_SKILL_INVOCATION,
PiManagedPackageMutationCancelledError,
PiManagedPackageMutationFailedError,
projectPiPackageCommandDiagnostic,
@@ -194,6 +195,7 @@ import type { PiRemoteFileOps } from '../base-agent.js';
import {
capturePiRuntimeCapabilityManifest,
identifyManagedPiPackageCommandNames,
+ preparePinnedPiSkillInvocation,
snapshotManagedPiPackageSkills,
} from './runtime-capabilities.js';
import {
@@ -6608,6 +6610,7 @@ export class PiAgent extends BaseAgent {
await assertReviewMessageContentPaths(message.content, opts.workingDir, reviewReadGrants);
}
let { text, images } = await buildPiPrompt(message, { remote });
+ const pinnedSkill = sendOpts?.[PINNED_SKILL_INVOCATION];
rejectIfCancelled(sendOpts, 'send');
assertImageInputSupported(images);
setAutoReviewIntent(appendAutoReviewUserIntent(priorAutoReviewIntent(), message.content, sendOpts), { authority: autoReviewContext() });
@@ -6624,6 +6627,12 @@ export class PiAgent extends BaseAgent {
// erase the user message/receipt while leaving an installed package.
if (!managedPackageRoute.accepted) rejectIfCancelled(sendOpts, 'send');
await awaitRuntimeCapabilitiesForSlashCommand(text);
+ if (pinnedSkill && !runtimeCapabilityManifest) {
+ await runtimeCapabilityRefreshPromise;
+ }
+ if (pinnedSkill) {
+ text = preparePinnedPiSkillInvocation(text, pinnedSkill, runtimeCapabilityManifest);
+ }
if (!managedPackageRoute.accepted) rejectIfCancelled(sendOpts, 'send');
// setExtraDirs 是热更新;Pi 没有独立的 mid-session system-prompt RPC,所以在
// 后续 user turn 前附上短引用目录段(但 /skill: 起始时不前置,见 composePiPromptText)。
diff --git a/packages/maker-core/src/agents/pi/runtime-capabilities.ts b/packages/maker-core/src/agents/pi/runtime-capabilities.ts
index b9b6af8ef4..fb9a295fa1 100644
--- a/packages/maker-core/src/agents/pi/runtime-capabilities.ts
+++ b/packages/maker-core/src/agents/pi/runtime-capabilities.ts
@@ -1,4 +1,5 @@
import type { PiRpcResponse } from './rpc-client.js';
+import fs from 'node:fs';
import path from 'node:path';
import type {
PiRuntimeCapabilityError,
@@ -161,6 +162,60 @@ function managedSkillCommandMatchesSource(command: PiRuntimeCommand, sourcePath:
&& canonicalRuntimePath(commandBaseDir) === canonicalRuntimePath(path.dirname(sourcePath));
}
+function canonicalExistingRuntimePath(value: string): string {
+ let resolved: string;
+ try {
+ resolved = fs.realpathSync.native(value);
+ } catch {
+ resolved = path.resolve(value);
+ }
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+}
+
+function piSkillCommandMatchesPinnedPath(command: PiRuntimeCommand, skillFile: string): boolean {
+ if (command.source !== 'skill' || !path.isAbsolute(skillFile)) return false;
+ const expected = canonicalExistingRuntimePath(skillFile);
+ const candidates = [
+ command.sourceInfo.path,
+ typeof command.sourceInfo.baseDir === 'string'
+ ? path.join(command.sourceInfo.baseDir, 'SKILL.md')
+ : undefined,
+ ];
+ return candidates.some((candidate) => (
+ typeof candidate === 'string'
+ && path.isAbsolute(candidate)
+ && canonicalExistingRuntimePath(candidate) === expected
+ ));
+}
+
+/**
+ * Bind one Host-attested invocation to Pi's frozen runtime catalog. Pi only
+ * executes Skills through /skill:name, so normalize Cindy's /name alias after
+ * proving that the sole runtime winner has the same physical SKILL.md path.
+ */
+export function preparePinnedPiSkillInvocation(
+ text: string,
+ pinnedSkill: { readonly name: string; readonly path: string },
+ manifest: PiRuntimeCapabilityManifest | undefined,
+): string {
+ const invocation = /^\/(?:skill:)?([^\s/]+)([\s\S]*)$/i.exec(text.trim());
+ if (!invocation?.[1] || invocation[1].toLowerCase() !== pinnedSkill.name.toLowerCase()) {
+ throw new Error('The pinned Skill does not match the Pi command');
+ }
+ if (manifest?.status !== 'loaded') {
+ throw new Error('Pi runtime Skill provenance is unavailable');
+ }
+ const runtimeName = `skill:${pinnedSkill.name}`.toLowerCase();
+ const winners = manifest.commands.filter((command) => command.name.toLowerCase() === runtimeName);
+ if (
+ winners.length !== 1
+ || !piSkillCommandMatchesPinnedPath(winners[0]!, pinnedSkill.path)
+ ) {
+ throw new Error('The pinned Skill does not match the Pi runtime winner');
+ }
+ return `/${winners[0]!.name}${invocation[2] ?? ''}`;
+}
+
/**
* Freeze the managed-skill roster passed to one runtime and attach a command
* name only when that runtime's own catalog proves an unambiguous loaded match.