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): close remaining built-in skill review gaps

xd-bobof35eed153c34
diff --git a/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py b/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
index 5086f6ee88..9f2353b2bb 100644
--- a/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
+++ b/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
@@ -13,7 +13,14 @@ FRONTMATTER_RE = re.compile(
re.DOTALL,
)
TOP_LEVEL_FIELD_RE = re.compile(r"^([A-Za-z0-9_-]+)[ \t]*:[ \t]*(.*)$")
-BLOCK_SCALAR_RE = re.compile(r"^([|>])(?:[+-])?(?:[1-9])?[ \t]*(?:#.*)?$")
+BLOCK_SCALAR_RE = re.compile(
+ r"^([|>])(?:(?:[+-]([1-9])?)|(?:([1-9])[+-]?))?(?:[ \t]+#.*|[ \t]*)$"
+)
+
+
+def _block_indent_indicator(match):
+ value = match.group(2) or match.group(3)
+ return int(value) if value is not None else None
def split_frontmatter(content):
@@ -214,7 +221,7 @@ def _parse_scalar(raw):
return value
-def _block_value(lines, start, style):
+def _block_value(lines, start, style, indent_indicator=None):
cursor = start
captured = []
minimum_indent = None
@@ -226,10 +233,14 @@ def _block_value(lines, start, style):
indent = len(line) - len(line.lstrip(" "))
if indent == 0 or line.startswith("\t"):
raise FrontmatterError("Block scalars must use space indentation")
+ if indent_indicator is not None and indent < indent_indicator:
+ raise FrontmatterError(
+ f"Block scalar content must be indented at least {indent_indicator} spaces"
+ )
minimum_indent = indent if minimum_indent is None else min(minimum_indent, indent)
captured.append(line)
cursor += 1
- indent = minimum_indent or 0
+ indent = indent_indicator if indent_indicator is not None else minimum_indent or 0
values = [line[indent:] if line.strip() else "" for line in captured]
if style == "|":
return "\n".join(values).rstrip("\n"), cursor
@@ -288,7 +299,10 @@ def _split_mapping_entry(value):
def _validate_nested_entry(text, line_number):
sequence_entry = text == "-" or text.startswith("- ") or text.startswith("-\t")
- value = text[1:].lstrip() if sequence_entry else text
+ sequence_content_indent = (
+ 1 + len(text[1:]) - len(text[1:].lstrip()) if sequence_entry else 0
+ )
+ value = text[sequence_content_indent:] if sequence_entry else text
if not value or value.startswith("#"):
return True, False, "sequence" if sequence_entry else "scalar"
@@ -305,7 +319,11 @@ def _validate_nested_entry(text, line_number):
return True, False, "sequence" if sequence_entry else "mapping"
block_match = BLOCK_SCALAR_RE.match(scalar_value)
if block_match:
- return True, True, "sequence" if sequence_entry else "mapping"
+ return (
+ True,
+ sequence_content_indent + (_block_indent_indicator(block_match) or 1),
+ "sequence" if sequence_entry else "mapping",
+ )
_parse_scalar(scalar_value)
# A sequence item may start a mapping whose sibling keys are indented
# beneath the dash even when this first key already has a value.
@@ -313,7 +331,11 @@ def _validate_nested_entry(text, line_number):
block_match = BLOCK_SCALAR_RE.match(value)
if block_match:
- return True, True, "sequence" if sequence_entry else "scalar"
+ return (
+ True,
+ sequence_content_indent + (_block_indent_indicator(block_match) or 1),
+ "sequence" if sequence_entry else "scalar",
+ )
_parse_scalar(value)
return False, False, "sequence" if sequence_entry else "scalar"
@@ -329,7 +351,8 @@ def _parse_nested_block(lines, start):
cursor = start
indent_levels = []
previous_allows_child = True
- block_scalar_indent = None
+ block_scalar_parent_indent = None
+ block_scalar_required_indent = None
collection = None
while cursor < len(lines):
@@ -347,11 +370,16 @@ def _parse_nested_block(lines, start):
cursor += 1
continue
- if block_scalar_indent is not None:
- if indent > block_scalar_indent:
+ if block_scalar_parent_indent is not None:
+ if indent >= block_scalar_required_indent:
cursor += 1
continue
- block_scalar_indent = None
+ if indent > block_scalar_parent_indent:
+ raise FrontmatterError(
+ f"Block scalar content is under-indented on line {cursor + 1}"
+ )
+ block_scalar_parent_indent = None
+ block_scalar_required_indent = None
if not indent_levels:
indent_levels.append([indent, None])
@@ -366,7 +394,7 @@ def _parse_nested_block(lines, start):
if not indent_levels or indent != indent_levels[-1][0]:
raise FrontmatterError(f"Inconsistent indentation on line {cursor + 1}")
- previous_allows_child, is_block_scalar, entry_kind = _validate_nested_entry(
+ previous_allows_child, block_indent, entry_kind = _validate_nested_entry(
stripped,
cursor + 1,
)
@@ -374,8 +402,9 @@ def _parse_nested_block(lines, start):
indent_levels[-1][1] = entry_kind
elif indent_levels[-1][1] != entry_kind:
raise FrontmatterError(f"Mixed collection types on line {cursor + 1}")
- if is_block_scalar:
- block_scalar_indent = indent
+ if block_indent is not False:
+ block_scalar_parent_indent = indent
+ block_scalar_required_indent = indent + block_indent
cursor += 1
return collection, cursor
@@ -406,7 +435,12 @@ def parse_frontmatter(frontmatter_text):
block_match = BLOCK_SCALAR_RE.match(raw_value)
if block_match:
- value, index = _block_value(lines, index + 1, block_match.group(1))
+ value, index = _block_value(
+ lines,
+ index + 1,
+ block_match.group(1),
+ _block_indent_indicator(block_match),
+ )
result[key] = value
continue
diff --git a/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts b/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts
new file mode 100644
index 0000000000..1bc8d53d42
--- /dev/null
+++ b/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createLearnInvocationGrantConsumer,
+ parseDirectLearnInvocation,
+} from '../invocationGrant.js';
+
+describe('Learn invocation grant', () => {
+ it.each([
+ ['/learn', { input: '', sourceKind: 'session' }],
+ ['/learn release flow', { input: 'release flow', sourceKind: 'freetext' }],
+ [
+ '/skill:learn hub:team:release-notes keep checks',
+ {
+ input: 'keep checks',
+ sourceKind: 'hub',
+ hubSlug: 'release-notes',
+ hubCatalogScope: 'team',
+ },
+ ],
+ ])('parses direct Learn invocation %s', (text, expected) => {
+ expect(parseDirectLearnInvocation(text)).toEqual(expected);
+ });
+
+ it('rejects ordinary messages and mismatched tool arguments without consuming the grant', async () => {
+ const readLatest = vi.fn(async () => ({
+ messageId: 'message-1',
+ text: '/learn hub:market:release-notes keep checks',
+ }));
+ const consume = createLearnInvocationGrantConsumer(readLatest);
+
+ await expect(consume({
+ callerSessionId: 'session-1',
+ input: 'different request',
+ sourceKind: 'freetext',
+ })).resolves.toMatchObject({ ok: false, errorCode: 'USER_REQUEST_REQUIRED' });
+ await expect(consume({
+ callerSessionId: 'session-1',
+ input: 'keep checks',
+ sourceKind: 'hub',
+ hubSlug: 'release-notes',
+ hubCatalogScope: 'market',
+ })).resolves.toEqual({ ok: true });
+
+ readLatest.mockResolvedValue({ messageId: 'message-2', text: 'please inspect /learn docs' });
+ await expect(consume({
+ callerSessionId: 'session-1',
+ input: '',
+ sourceKind: 'session',
+ })).resolves.toMatchObject({ ok: false, errorCode: 'USER_REQUEST_REQUIRED' });
+ });
+
+ it('consumes each persisted user invocation only once', async () => {
+ const consume = createLearnInvocationGrantConsumer(async () => ({
+ messageId: 'message-1',
+ text: '/learn release flow',
+ }));
+ const request = {
+ callerSessionId: 'session-1',
+ input: 'release flow',
+ sourceKind: 'freetext' as const,
+ };
+
+ await expect(consume(request)).resolves.toEqual({ ok: true });
+ await expect(consume(request)).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'USER_REQUEST_REQUIRED',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/learn-host/invocationGrant.ts b/apps/desktop/src/main/learn-host/invocationGrant.ts
new file mode 100644
index 0000000000..7d5977243a
--- /dev/null
+++ b/apps/desktop/src/main/learn-host/invocationGrant.ts
@@ -0,0 +1,144 @@
+import type { StartSkillLearningParams } from '@cindy/mcps';
+import { and, desc, eq, gt, isNull, or, sql } from 'drizzle-orm';
+
+import { visibleMessageTextForConversationSearch } from '../localDb/conversationSearch.pure.js';
+import {
+ isDbClientNotReadyError,
+ tryGetDbClient,
+} from '../localDb/client/current.js';
+import { messages, sessions } from '../localDb/schema.js';
+
+export type LearnInvocationGrantResult =
+ | { ok: true }
+ | {
+ ok: false;
+ errorCode: 'HOST_NOT_READY' | 'INTERNAL' | 'USER_REQUEST_REQUIRED';
+ message: string;
+ };
+
+interface LatestUserInvocation {
+ messageId: string;
+ text: string;
+}
+
+type ReadLatestUserInvocation = (
+ sessionId: string,
+) => Promise<LatestUserInvocation | null>;
+
+const messageRowid = sql<number>`"messages"."rowid"`;
+const MAX_CONSUMED_INVOCATIONS = 2_048;
+
+function normalizeInput(value: string): string {
+ return value.trim().replace(/\s+/g, ' ');
+}
+
+export function parseDirectLearnInvocation(
+ text: string,
+): Omit<StartSkillLearningParams, 'callerSessionId'> | null {
+ const command = /^\/(?:skill:)?learn(?:\s+([\s\S]*))?$/.exec(text.trim());
+ if (!command) return null;
+
+ const arg = (command[1] ?? '').trim();
+ const hubMatch = /^hub:(?:(market|team):)?([a-z0-9][a-z0-9-]*)\s*/.exec(arg);
+ if (hubMatch) {
+ return {
+ input: arg.slice(hubMatch[0].length).trim(),
+ sourceKind: 'hub',
+ hubSlug: hubMatch[2],
+ hubCatalogScope: (hubMatch[1] as 'market' | 'team' | undefined) ?? 'market',
+ };
+ }
+ return {
+ input: arg,
+ sourceKind: arg ? 'freetext' : 'session',
+ };
+}
+
+function matchesInvocation(
+ invocation: Omit<StartSkillLearningParams, 'callerSessionId'>,
+ request: StartSkillLearningParams,
+): boolean {
+ if (invocation.sourceKind !== request.sourceKind) return false;
+ if (normalizeInput(invocation.input) !== normalizeInput(request.input)) return false;
+ if (invocation.sourceKind !== 'hub') {
+ return request.hubSlug === undefined && request.hubCatalogScope === undefined;
+ }
+ return invocation.hubSlug === request.hubSlug
+ && invocation.hubCatalogScope === (request.hubCatalogScope ?? 'market');
+}
+
+export function createLearnInvocationGrantConsumer(
+ readLatestUserInvocation: ReadLatestUserInvocation,
+): (request: StartSkillLearningParams) => Promise<LearnInvocationGrantResult> {
+ const consumed = new Set<string>();
+ const consumptionOrder: string[] = [];
+
+ return async (request) => {
+ let latest: LatestUserInvocation | null;
+ try {
+ latest = await readLatestUserInvocation(request.callerSessionId);
+ } catch (error) {
+ return {
+ ok: false,
+ errorCode: isDbClientNotReadyError(error) ? 'HOST_NOT_READY' : 'INTERNAL',
+ message: 'Cindy could not verify the current /learn request.',
+ };
+ }
+ const invocation = latest ? parseDirectLearnInvocation(latest.text) : null;
+ if (!latest || !invocation || !matchesInvocation(invocation, request)) {
+ return {
+ ok: false,
+ errorCode: 'USER_REQUEST_REQUIRED',
+ message: 'Start Learn by invoking /learn directly in the current task.',
+ };
+ }
+ const consumptionKey = `${request.callerSessionId}\0${latest.messageId}`;
+ if (consumed.has(consumptionKey)) {
+ return {
+ ok: false,
+ errorCode: 'USER_REQUEST_REQUIRED',
+ message: 'This /learn request has already been used.',
+ };
+ }
+
+ consumed.add(consumptionKey);
+ consumptionOrder.push(consumptionKey);
+ if (consumptionOrder.length > MAX_CONSUMED_INVOCATIONS) {
+ consumed.delete(consumptionOrder.shift()!);
+ }
+ return { ok: true };
+ };
+}
+
+async function readLatestUserInvocation(
+ sessionId: string,
+): Promise<LatestUserInvocation | null> {
+ const dbClient = tryGetDbClient();
+ if (!dbClient) {
+ throw Object.assign(new Error('DbClient not ready'), { code: 'HOST_NOT_READY' });
+ }
+ const [row] = await dbClient.drizzle
+ .select({ id: messages.id, content: messages.content })
+ .from(messages)
+ .innerJoin(sessions, eq(messages.sessionId, sessions.id))
+ .where(
+ and(
+ eq(messages.sessionId, sessionId),
+ eq(messages.role, 'user'),
+ isNull(messages.rewindAt),
+ sql`(${messages.agentMeta} IS NULL OR CASE WHEN json_valid(${messages.agentMeta}) THEN json_extract(${messages.agentMeta}, '$.autoResume') END IS NOT 1)`,
+ or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt)),
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(1);
+ if (!row) return null;
+ return {
+ messageId: row.id,
+ text: visibleMessageTextForConversationSearch('user', row.content),
+ };
+}
+
+export const consumeLearnInvocationGrant = createLearnInvocationGrantConsumer(
+ readLatestUserInvocation,
+);
diff --git a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
index 249a75e89a..570bd64337 100644
--- a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
@@ -4,9 +4,11 @@ import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import {
+ activeCindyBuiltInAgentSkills,
builtInSkillDescriptors,
markCindyBuiltInAgentSkills,
prepareBuiltInSkills,
+ refreshBuiltInClaudeSkillLinks,
resolveBundledSystemSkillsRoot,
} from '../built-in-skills';
@@ -239,7 +241,7 @@ describe('built-in Skills', () => {
expect(result.warnings.join('\n')).toContain('already owned by the user');
});
- it('keeps the isolated Claude runtime aligned with the user-owned palette winner', async () => {
+ it('refreshes the isolated Claude runtime when the palette winner changes', async () => {
const input = fixture();
const first = await prepareBuiltInSkills(input);
const descriptor = first.descriptors.find((item) => item.name === 'learn')!;
@@ -250,13 +252,25 @@ describe('built-in Skills', () => {
fs.mkdirSync(claudePaletteSkill, { recursive: true });
fs.writeFileSync(path.join(claudePaletteSkill, 'SKILL.md'), '# User Claude Learn\n');
- const updated = await prepareBuiltInSkills(input);
+ const updated = await refreshBuiltInClaudeSkillLinks({
+ ...input,
+ descriptors: first.descriptors,
+ });
expect(updated.warnings).toEqual([]);
expect(fs.realpathSync(sharedSkill)).toBe(fs.realpathSync(descriptor.absolutePath));
expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(
fs.realpathSync(claudePaletteSkill),
);
+
+ fs.rmSync(claudePaletteSkill, { recursive: true, force: true });
+ const restored = await refreshBuiltInClaudeSkillLinks({
+ ...input,
+ descriptors: first.descriptors,
+ });
+
+ expect(restored.warnings).toEqual([]);
+ expect(fs.realpathSync(descriptor.nativeClaudePath)).toBe(fs.realpathSync(sharedSkill));
});
it('attests only commands backed by the materialized Cindy copy', async () => {
@@ -289,6 +303,30 @@ describe('built-in Skills', () => {
expect(spoofed?.builtIn).toBeUndefined();
});
+ it('removes disabled Cindy built-ins from the Agent roster without hiding user collisions', async () => {
+ const input = fixture();
+ const { descriptors } = await prepareBuiltInSkills(input);
+ const descriptor = descriptors[0]!;
+ const userCopy = path.join(input.homeDir, 'user-copy', 'SKILL.md');
+ fs.mkdirSync(path.dirname(userCopy), { recursive: true });
+ fs.writeFileSync(userCopy, '# User copy\n');
+
+ const skills = activeCindyBuiltInAgentSkills([
+ {
+ kind: 'agent-skill', name: descriptor.name, source: 'skill',
+ path: path.join(descriptor.absolutePath, 'SKILL.md'), scope: 'user', enabled: true,
+ },
+ {
+ kind: 'agent-skill', name: descriptor.name, source: 'skill',
+ path: userCopy, scope: 'user', enabled: true,
+ },
+ ], descriptors, (source) => source !== descriptor.absolutePath);
+
+ expect(skills).toHaveLength(1);
+ expect(skills[0]?.path).toBe(userCopy);
+ expect(skills[0]?.builtIn).toBeUndefined();
+ });
+
it('resolves source and packaged resource roots', () => {
expect(
resolveBundledSystemSkillsRoot({
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts
index f8b8f04f3e..7d1caed5e7 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts
@@ -109,6 +109,10 @@ vi.mock('../shared-global-skills.js', () => ({
prepareSharedProjectSkillLinks: async () => ({ warnings: [] }),
}));
+vi.mock('../built-in-skills.js', () => ({
+ refreshBuiltInClaudeSkillLinks: async () => ({ warnings: [] }),
+}));
+
vi.mock('../anthropic-compat-proxy-host.js', () => ({
isAnthropicCompatProxyHandleReady: () => h.proxyReady,
}));
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index 202f95b92a..10e4569724 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -39,6 +39,7 @@ import { prepareCodexGlobalRulesCopy } from './codex-global-rules.js';
import { prepareCodexGlobalPluginsBridge } from './codex-global-plugins.js';
import { DESKTOP_CAPABILITY_ROUTING_POLICY } from './capability-routing.js';
import { prepareSharedGlobalSkillLinks } from './shared-global-skills.js';
+import { refreshBuiltInClaudeSkillLinks } from './built-in-skills.js';
import {
copyCodexAuthSnapshot,
inspectCodexAuthLink,
@@ -599,11 +600,21 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
private async runEnsureSharedGlobalSkills(): Promise<void> {
try {
const ownerId = getActiveAppSession().dataOwnerId;
- const result = await withSharedGlobalSkillProjectionMutation(ownerId, () =>
- prepareSharedGlobalSkillLinks({
+ const result = await withSharedGlobalSkillProjectionMutation(ownerId, async () => {
+ const sharedProjection = await prepareSharedGlobalSkillLinks({
assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
- }),
- );
+ });
+ const isolatedClaudeProjection = await refreshBuiltInClaudeSkillLinks({
+ userDataDir: app.getPath('userData'),
+ appDataDir: app.getPath('appData'),
+ });
+ return {
+ warnings: [
+ ...sharedProjection.warnings,
+ ...isolatedClaudeProjection.warnings,
+ ],
+ };
+ });
for (const warning of result.warnings) {
assetPrepLog.warn('shared global skill warning', { warning });
}
diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.ts
index b7d892f0c2..8e05ad67cf 100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@ -41,6 +41,19 @@ export interface PrepareBuiltInSkillsResult {
warnings: string[];
}
+export interface RefreshBuiltInClaudeSkillLinksOptions {
+ userDataDir: string;
+ appDataDir?: string;
+ homeDir?: string;
+ descriptors?: readonly BuiltInSkillDescriptor[];
+ withSharedMutation?: typeof withSkillMutation;
+}
+
+export interface RefreshBuiltInClaudeSkillLinksResult {
+ changed: boolean;
+ warnings: string[];
+}
+
interface MaterializationManifest {
schemaVersion: 2;
bundleVersion: number;
@@ -330,6 +343,81 @@ export function markCindyBuiltInAgentSkills(
});
}
+/** Mark trusted Cindy entries, then apply the live activation override to those entries only. */
+export function activeCindyBuiltInAgentSkills(
+ skills: readonly AgentSkillCommand[],
+ descriptors: readonly BuiltInSkillDescriptor[],
+ isEnabled: (source: string) => boolean,
+): AgentSkillCommand[] {
+ const descriptorsByName = new Map(descriptors.map((descriptor) => [descriptor.name, descriptor]));
+ return markCindyBuiltInAgentSkills(skills, descriptors).filter((skill) => {
+ if (skill.builtIn !== true) return true;
+ const descriptor = descriptorsByName.get(skill.name);
+ return descriptor ? isEnabled(descriptor.absolutePath) : false;
+ });
+}
+
+async function refreshBuiltInClaudeSkillLinksUnlocked(
+ options: Omit<RefreshBuiltInClaudeSkillLinksOptions, 'withSharedMutation'>,
+): Promise<RefreshBuiltInClaudeSkillLinksResult> {
+ const descriptors = options.descriptors
+ ?? builtInSkillDescriptors(options.userDataDir, options.appDataDir);
+ const homeDir = options.homeDir ?? os.homedir();
+ const warnings: string[] = [];
+ let changed = false;
+
+ for (const descriptor of descriptors) {
+ const sharedPath = path.join(homeDir, '.agents', 'skills', descriptor.name);
+ const claudePalettePath = path.join(homeDir, '.claude', 'skills', descriptor.name);
+ const claudeRuntimeTarget = await hasSkillFile(claudePalettePath)
+ ? claudePalettePath
+ : sharedPath;
+ if (!(await hasSkillFile(claudeRuntimeTarget))) {
+ warnings.push(
+ `could not expose built-in Skill ${descriptor.name} to Claude because its palette winner is unavailable`,
+ );
+ continue;
+ }
+ try {
+ const linked = await ensureSkillEntry(
+ descriptor,
+ descriptor.nativeClaudePath,
+ true,
+ options.userDataDir,
+ options.appDataDir,
+ claudeRuntimeTarget,
+ [sharedPath, claudePalettePath],
+ );
+ changed = linked.changed || changed;
+ if (linked.warning) warnings.push(linked.warning);
+ } catch (error) {
+ warnings.push(
+ `could not expose built-in Skill ${descriptor.name} to Claude: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+
+ return { changed, warnings };
+}
+
+/** Keep Cindy's isolated Claude runtime pointed at the latest shared/palette winner. */
+export async function refreshBuiltInClaudeSkillLinks(
+ options: RefreshBuiltInClaudeSkillLinksOptions,
+): Promise<RefreshBuiltInClaudeSkillLinksResult> {
+ const descriptors = options.descriptors
+ ?? builtInSkillDescriptors(options.userDataDir, options.appDataDir);
+ const mutate = options.withSharedMutation ?? withSkillMutation;
+ const refreshed = await mutate(
+ descriptors.map((descriptor) => descriptor.name),
+ () => refreshBuiltInClaudeSkillLinksUnlocked({ ...options, descriptors }),
+ { waitMs: BUILT_IN_SKILL_MUTATION_WAIT_MS },
+ );
+ return refreshed ?? {
+ changed: false,
+ warnings: ['could not refresh built-in Claude Skills because another Skill mutation is in progress'],
+ };
+}
+
/**
* Materialize Cindy-owned Skill bytes under a profile-independent appData path, then expose
* them through the shared ~/.agents discovery root and Cindy's isolated Claude
@@ -391,13 +479,6 @@ export async function prepareBuiltInSkills(
continue;
}
- const sharedPath = path.join(
- options.homeDir ?? os.homedir(),
- '.agents',
- 'skills',
- descriptor.name,
- );
- let sharedTarget: string | undefined;
try {
const linked = await ensureSharedEntry(
descriptor,
@@ -406,50 +487,23 @@ export async function prepareBuiltInSkills(
options.appDataDir,
);
changed = linked.changed || changed;
- sharedTarget = linked.targetPath ?? await fsp.realpath(sharedPath).catch(() => undefined);
if (linked.warning) warnings.push(linked.warning);
} catch (error) {
warnings.push(
`could not expose built-in Skill ${descriptor.name}: ${error instanceof Error ? error.message : String(error)}`,
);
}
-
- if (!sharedTarget) {
- warnings.push(`could not expose built-in Skill ${descriptor.name} to Claude because the shared entry is unavailable`);
- continue;
- }
- try {
- // Claude's palette scans ~/.claude while its isolated runtime reads
- // <userData>/claude-home. Mirror the palette winner so a user-owned
- // Claude Skill keeps precedence even when ~/.agents has Cindy's copy.
- const homeDir = options.homeDir ?? os.homedir();
- const claudePalettePath = path.join(
- homeDir,
- '.claude',
- 'skills',
- descriptor.name,
- );
- const claudeRuntimeTarget = await hasSkillFile(claudePalettePath)
- ? claudePalettePath
- : sharedPath;
- const linked = await ensureSkillEntry(
- descriptor,
- descriptor.nativeClaudePath,
- true,
- options.userDataDir,
- options.appDataDir,
- claudeRuntimeTarget,
- [sharedPath],
- );
- changed = linked.changed || changed;
- if (linked.warning) warnings.push(linked.warning);
- } catch (error) {
- warnings.push(
- `could not expose built-in Skill ${descriptor.name} to Claude: ${error instanceof Error ? error.message : String(error)}`,
- );
- }
}
+ const claudeProjection = await refreshBuiltInClaudeSkillLinksUnlocked({
+ userDataDir: options.userDataDir,
+ appDataDir: options.appDataDir,
+ homeDir: options.homeDir,
+ descriptors,
+ });
+ changed = claudeProjection.changed || changed;
+ warnings.push(...claudeProjection.warnings);
+
if (!newerBundleIsInstalled) {
if (bundleReady) manifest.bundleVersion = bundleVersion;
try {
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 0a174d9fd2..a42df9f7ab 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -76,6 +76,10 @@ import {
type BotProfileRuntimeSnapshot,
} from '../maker-ipc/botProfileRuntime.js';
import { collectBotOwnSkillMounts } from '../maker-ipc/botSkillService.js';
+import {
+ builtInSkillDescriptors,
+ markCindyBuiltInAgentSkills,
+} from './built-in-skills.js';
import { buildBotMcpCatalog } from './botMcpCatalog.js';
import { createBotCapabilityService, type BotCapabilityServiceDeps, type BotCapabilityUpdate } from '../maker-ipc/botCapabilityService.js';
import {
@@ -930,6 +934,31 @@ export function getMaker(): Maker {
pluginRegistry,
resolveIOSSimulatorAccess,
invokeRemote: remoteInvoke,
+ attestCindyLearnSkillForSession: async (
+ sessionId: string,
+ sessionInstanceId: string | undefined,
+ ) => {
+ const session = _maker?.getSession(sessionId);
+ if (
+ !sessionInstanceId
+ || !session
+ || session.instanceId !== sessionInstanceId
+ || session.remoteHostId
+ ) {
+ return false;
+ }
+ const result = await _maker!.listAgentSkills(session.agentKind, {
+ workingDir: session.workDir,
+ sessionId,
+ });
+ const skills = markCindyBuiltInAgentSkills(
+ result.skills,
+ builtInSkillDescriptors(app.getPath('userData'), app.getPath('appData')),
+ );
+ const learnCandidates = skills.filter((skill) => skill.name.toLowerCase() === 'learn');
+ return learnCandidates.length > 0
+ && learnCandidates.every((skill) => skill.builtIn === true);
+ },
// 只读活跃 Session 的运行时真相。权限切换是 runtime-first、DB-second,
// 因此插件过户自动放行不得回退 sessions.permission_mode;会话不再 active
// 时同样 fail closed。闭包在 MCP tool-call 时执行,此时 _maker 已装配完成。
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 73707cf308..94b014c76a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -392,9 +392,10 @@ import {
} from '../maker-host/auth-adapters.js';
import { prepareSharedProjectSkillLinks } from '../maker-host/shared-global-skills.js';
import {
+ activeCindyBuiltInAgentSkills,
builtInSkillDescriptors,
- markCindyBuiltInAgentSkills,
} from '../maker-host/built-in-skills.js';
+import { isCindySkillEnabled } from '../skillhub/activationPreferences.js';
import { ensurePiManagerInstalled } from '../maker-host/pi-manager-client.js';
import {
setRemoteCodexLiveTurnChecker,
@@ -6023,9 +6024,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return {
success: true,
...result,
- skills: markCindyBuiltInAgentSkills(
+ skills: activeCindyBuiltInAgentSkills(
result.skills,
builtInSkillDescriptors(app.getPath('userData'), app.getPath('appData')),
+ isCindySkillEnabled,
),
};
} catch (err) {
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
index 0dbf8a3e73..65768b6738 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
@@ -15,6 +15,8 @@ const mockState = vi.hoisted(() => ({
[key: string]: ReturnType<typeof vi.fn>;
},
learnEnabled: true,
+ learnController: {} as object | null,
+ consumeLearnInvocationGrant: vi.fn(async (_request: unknown) => ({ ok: true as const })),
capturedProvidersConfig: null as null | Record<string, unknown>,
}));
@@ -94,6 +96,15 @@ vi.mock('../../skillhub/activationPreferences.js', () => ({
isCindyLearnSkillEnabled: () => mockState.learnEnabled,
}));
+vi.mock('../../learn-host/index.js', () => ({
+ getLearnController: () => mockState.learnController,
+}));
+
+vi.mock('../../learn-host/invocationGrant.js', () => ({
+ consumeLearnInvocationGrant: (request: unknown) =>
+ mockState.consumeLearnInvocationGrant(request),
+}));
+
vi.mock('../../localDb/chatHistoryReader.js', () => ({
listWorkdirsForHistory: vi.fn(),
listSessionsForHistory: vi.fn(),
@@ -170,6 +181,9 @@ describe('collab send outcome semantics', () => {
mockState.logger.fatal.mockClear();
mockState.collabService = null;
mockState.learnEnabled = true;
+ mockState.learnController = {};
+ mockState.consumeLearnInvocationGrant.mockReset();
+ mockState.consumeLearnInvocationGrant.mockResolvedValue({ ok: true });
mockState.capturedProvidersConfig = null;
vi.clearAllMocks();
});
@@ -233,6 +247,46 @@ describe('collab send outcome semantics', () => {
});
});
+ it('authorizes Learn only when the active slash-command winner is Cindy built-in Learn', async () => {
+ const attestCindyLearnSkillForSession = vi.fn(async () => false);
+ createDesktopMcpProviders({
+ botCapabilities,
+ getMakerMemoryManager: vi.fn(),
+ lspPool: {} as never,
+ pluginRegistry: { isEnabled: () => true } as never,
+ resolveIOSSimulatorAccess: () => ({ allowed: true }),
+ invokeRemote: vi.fn(),
+ attestCindyLearnSkillForSession,
+ });
+ const xdtHelper = mockState.capturedProvidersConfig?.xdtHelper as {
+ authorizeSkillLearning: (input: {
+ callerSessionId: string;
+ input: string;
+ sourceKind: 'freetext';
+ }, context: { sessionInstanceId: string }) => Promise<Record<string, unknown>>;
+ };
+ const request = {
+ callerSessionId: 'session-1',
+ input: 'release flow',
+ sourceKind: 'freetext' as const,
+ };
+
+ const context = { sessionInstanceId: 'instance-1' };
+ await expect(xdtHelper.authorizeSkillLearning(request, context)).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'USER_REQUEST_REQUIRED',
+ });
+ expect(attestCindyLearnSkillForSession).toHaveBeenLastCalledWith(
+ 'session-1',
+ 'instance-1',
+ );
+ expect(mockState.consumeLearnInvocationGrant).not.toHaveBeenCalled();
+
+ attestCindyLearnSkillForSession.mockResolvedValue(true);
+ await expect(xdtHelper.authorizeSkillLearning(request, context)).resolves.toEqual({ ok: true });
+ expect(mockState.consumeLearnInvocationGrant).toHaveBeenCalledWith(request);
+ });
+
it('reports enable_collab_mode delegate_task created-and-dispatched distinctly', async () => {
const result = await resolveCollabDispatchResult(
() => Promise.resolve({ accepted: true } satisfies SessionSendResult),
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 53b027bc38..ea7d9cd65e 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -88,6 +88,7 @@ import {
import { botSessionLinks, sessions } from '../localDb/schema.js';
import { isCindyLearnSkillEnabled } from '../skillhub/activationPreferences.js';
import { getLearnController } from '../learn-host/index.js';
+import { consumeLearnInvocationGrant } from '../learn-host/invocationGrant.js';
export interface DesktopMcpProvidersDeps {
botCapabilities: Pick<ReturnType<typeof createBotCapabilityService>, 'list' | 'select'>;
@@ -109,6 +110,11 @@ export interface DesktopMcpProvidersDeps {
sessionId: string,
sessionInstanceId: string,
) => GhostGrantLiveSessionState | null;
+ /** Confirms that this Session's actual slash-command winner is Cindy's built-in Learn Skill. */
+ attestCindyLearnSkillForSession?: (
+ sessionId: string,
+ sessionInstanceId: string | undefined,
+ ) => Promise<boolean>;
/** 把工具结果图片转成文字描述(视觉桥,最佳努力)。缺失 = 不处理。
* 返回结构区分「有意跳过」(skipped:true, 视觉桥未开/模型不命中, 不告警)与
* 「真正尝试但失败」(skipped:false + null, 计入 attemptedCount 供告警)。 */
@@ -377,6 +383,33 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
createProject,
moveSession: createMoveSession(isSessionInTurn),
projectManagement: { list: listProjects, rename: renameProject, remove: removeProject },
+ authorizeSkillLearning: async (request, context) => {
+ if (!isCindyLearnSkillEnabled()) {
+ return {
+ ok: false,
+ errorCode: 'SKILL_DISABLED',
+ message: 'Cindy Learn is disabled in Local Skills.',
+ };
+ }
+ if (!getLearnController()) {
+ return {
+ ok: false,
+ errorCode: 'HOST_NOT_READY',
+ message: 'Cindy Learn is not ready yet.',
+ };
+ }
+ if (!await deps.attestCindyLearnSkillForSession?.(
+ request.callerSessionId,
+ context.sessionInstanceId,
+ )) {
+ return {
+ ok: false,
+ errorCode: 'USER_REQUEST_REQUIRED',
+ message: 'Cindy Learn is not the active /learn Skill for this task.',
+ };
+ }
+ return consumeLearnInvocationGrant(request);
+ },
skillLearning: async ({
callerSessionId,
input,
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 7027d78a71..83fc6231f6 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -400,7 +400,10 @@ describe('registerSkillhubIpc usage handlers', () => {
fs.mkdirSync(builtInRoot, { recursive: true });
fs.writeFileSync(builtInFile, '# Learn\n');
fs.writeFileSync(builtInNotes, 'notes\n');
- const attestedRoot = fs.realpathSync.native(builtInRoot);
+ const physicalBuiltInRoot = fs.realpathSync.native(builtInRoot);
+ const attestedRoot = process.platform === 'win32'
+ ? physicalBuiltInRoot.toLowerCase()
+ : physicalBuiltInRoot;
const sender = { id: 18, on: vi.fn(), once: vi.fn() };
resolveExistingSkillPathForGrant.mockReturnValue(null);
isExistingSkillPathGranted.mockReturnValue(false);
diff --git a/packages/lizi-mcps/src/__tests__/startSkillLearning.test.ts b/packages/lizi-mcps/src/__tests__/startSkillLearning.test.ts
index 0d24fcd1b0..66c358c973 100644
--- a/packages/lizi-mcps/src/__tests__/startSkillLearning.test.ts
+++ b/packages/lizi-mcps/src/__tests__/startSkillLearning.test.ts
@@ -12,6 +12,7 @@ function payload(result: { content: Array<{ type: string; text?: string }> }): R
describe('start_skill_learning', () => {
it('binds the current task and starts a session Learn run', async () => {
const registry = new XdtHelperToolRegistry();
+ const authorizeSkillLearning = vi.fn(async () => ({ ok: true as const }));
const startSkillLearning = vi.fn(async () => ({ ok: true as const, runId: 'run-1' }));
registerStartSkillLearningTool(registry, {
getSessionContext: () => ({
@@ -19,6 +20,7 @@ describe('start_skill_learning', () => {
workingDir: '/repo',
sessionId: 'session-1',
}),
+ authorizeSkillLearning,
startSkillLearning,
});
@@ -27,16 +29,22 @@ describe('start_skill_learning', () => {
input: '',
});
- expect(startSkillLearning).toHaveBeenCalledWith({
+ const request = {
callerSessionId: 'session-1',
input: '',
sourceKind: 'session',
- });
+ } as const;
+ expect(authorizeSkillLearning).toHaveBeenCalledWith(request, expect.objectContaining({
+ sessionId: 'session-1',
+ agentKind: 'codex',
+ }));
+ expect(startSkillLearning).toHaveBeenCalledWith(request);
expect(payload(result)).toMatchObject({ ok: true, run_id: 'run-1', status: 'collecting' });
});
it('normalizes SkillHub input and defaults its catalog scope', async () => {
const registry = new XdtHelperToolRegistry();
+ const authorizeSkillLearning = vi.fn(async () => ({ ok: true as const }));
const startSkillLearning = vi.fn(async () => ({ ok: true as const, runId: 'run-2' }));
registerStartSkillLearningTool(registry, {
getSessionContext: () => ({
@@ -44,6 +52,7 @@ describe('start_skill_learning', () => {
workingDir: '/repo',
sessionId: 'session-2',
}),
+ authorizeSkillLearning,
startSkillLearning,
});
@@ -68,6 +77,7 @@ describe('start_skill_learning', () => {
[{ source_kind: 'session', input: '', hub_slug: 'extra' }, 'INVALID_ARGS'],
])('rejects inconsistent arguments %#', async (args, expectedErrorCode) => {
const registry = new XdtHelperToolRegistry();
+ const authorizeSkillLearning = vi.fn(async () => ({ ok: true as const }));
const startSkillLearning = vi.fn();
registerStartSkillLearningTool(registry, {
getSessionContext: () => ({
@@ -75,20 +85,52 @@ describe('start_skill_learning', () => {
workingDir: '/repo',
sessionId: 'session-3',
}),
+ authorizeSkillLearning,
startSkillLearning,
});
const result = await registry.call('start_skill_learning', args);
expect(payload(result)).toMatchObject({ ok: false, errorCode: expectedErrorCode });
+ expect(authorizeSkillLearning).not.toHaveBeenCalled();
+ expect(startSkillLearning).not.toHaveBeenCalled();
+ });
+
+ it('requires a host-attested one-shot Learn invocation before starting', async () => {
+ const registry = new XdtHelperToolRegistry();
+ const authorizeSkillLearning = vi.fn(async () => ({
+ ok: false as const,
+ errorCode: 'USER_REQUEST_REQUIRED',
+ message: 'The latest user message is not a matching /learn invocation.',
+ }));
+ const startSkillLearning = vi.fn();
+ registerStartSkillLearningTool(registry, {
+ getSessionContext: () => ({
+ agentKind: 'codex',
+ workingDir: '/repo',
+ sessionId: 'session-4',
+ }),
+ authorizeSkillLearning,
+ startSkillLearning,
+ });
+
+ const result = await registry.call('start_skill_learning', {
+ source_kind: 'freetext',
+ input: 'create release notes',
+ });
+
+ expect(payload(result)).toMatchObject({ ok: false, errorCode: 'USER_REQUEST_REQUIRED' });
+ expect(authorizeSkillLearning).toHaveBeenCalledOnce();
expect(startSkillLearning).not.toHaveBeenCalled();
});
it('fails closed without a bound Cindy task', async () => {
const registry = new XdtHelperToolRegistry();
+ const authorizeSkillLearning = vi.fn(async () => ({ ok: true as const }));
const startSkillLearning = vi.fn();
registerStartSkillLearningTool(registry, {
getSessionContext: () => ({ agentKind: 'codex', workingDir: '/repo' }),
+ authorizeSkillLearning,
startSkillLearning,
});
@@ -98,6 +140,7 @@ describe('start_skill_learning', () => {
});
expect(payload(result)).toMatchObject({ ok: false, errorCode: 'NO_SESSION_CONTEXT' });
+ expect(authorizeSkillLearning).not.toHaveBeenCalled();
expect(startSkillLearning).not.toHaveBeenCalled();
});
});
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index 78ab63194b..79ad4349ad 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -64,7 +64,10 @@ import type { SetCurrentSessionTitleDeps } from './xdt-helper/set_current_sessio
import type { RenameSessionsDeps } from './xdt-helper/rename_sessions.js';
import type { ArchiveSessionsDeps } from './xdt-helper/archive_sessions.js';
import type { SendToSessionCallback } from './xdt-helper/send_to_session.js';
-import type { StartSkillLearningCallback } from './xdt-helper/start_skill_learning.js';
+import type {
+ AuthorizeSkillLearningCallback,
+ StartSkillLearningCallback,
+} from './xdt-helper/start_skill_learning.js';
import {
registerBotSkillTools,
type BotSkillCallbacks,
@@ -639,6 +642,8 @@ export interface XdtHelperMcpDeps {
sendToSession?: SendToSessionCallback;
/** Cindy-managed Learn flow; registered in the skills category when supplied by the host. */
skillLearning?: StartSkillLearningCallback;
+ /** Host-owned, one-shot authorization for the current direct Learn invocation. */
+ authorizeSkillLearning?: AuthorizeSkillLearningCallback;
/** Register an existing local directory as a Cindy project without starting a task. */
createProject?: CreateProjectCallback;
moveSession?: MoveSessionCallback;
@@ -806,9 +811,10 @@ export function createXdtHelperMcpServer(
sendToSession: deps.sendToSession,
});
}
- if (deps.skillLearning) {
+ if (deps.skillLearning && deps.authorizeSkillLearning) {
registerStartSkillLearningTool(registry, {
getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
+ authorizeSkillLearning: deps.authorizeSkillLearning,
startSkillLearning: deps.skillLearning,
});
}
diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.ts
index d00cbb5a40..e0c31735c8 100644
--- a/packages/lizi-mcps/src/xdt-helper/index.ts
+++ b/packages/lizi-mcps/src/xdt-helper/index.ts
@@ -158,7 +158,9 @@ export {
} from './submit_github_issue.js';
export {
registerStartSkillLearningTool,
+ type AuthorizeSkillLearningCallback,
type StartSkillLearningCallback,
+ type StartSkillLearningParams,
} from './start_skill_learning.js';
export type {
XdtHelperHistoryDeps,
diff --git a/packages/lizi-mcps/src/xdt-helper/start_skill_learning.ts b/packages/lizi-mcps/src/xdt-helper/start_skill_learning.ts
index c5247408ae..6356d4d37b 100644
--- a/packages/lizi-mcps/src/xdt-helper/start_skill_learning.ts
+++ b/packages/lizi-mcps/src/xdt-helper/start_skill_learning.ts
@@ -4,18 +4,28 @@ import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
import type { ControlResult, LiziMcpSessionContext } from '../types.js';
import { errorPayload, okPayload } from './_payload.js';
-export type StartSkillLearningCallback = (params: {
+export interface StartSkillLearningParams {
callerSessionId: string;
input: string;
sourceKind: 'session' | 'freetext' | 'hub';
hubSlug?: string;
hubCatalogScope?: 'market' | 'team';
-}) => Promise<ControlResult<{ runId: string }, string>>;
+}
+
+export type AuthorizeSkillLearningCallback = (
+ params: StartSkillLearningParams,
+ context: LiziMcpSessionContext,
+) => Promise<ControlResult<object, string>>;
+
+export type StartSkillLearningCallback = (
+ params: StartSkillLearningParams,
+) => Promise<ControlResult<{ runId: string }, string>>;
export function registerStartSkillLearningTool(
registry: XdtHelperToolRegistry,
deps: {
getSessionContext: () => LiziMcpSessionContext;
+ authorizeSkillLearning: AuthorizeSkillLearningCallback;
startSkillLearning: StartSkillLearningCallback;
},
): void {
@@ -50,7 +60,7 @@ export function registerStartSkillLearningTool(
);
}
- const result = await deps.startSkillLearning({
+ const request: StartSkillLearningParams = {
callerSessionId: context.sessionId,
input: normalizedInput,
sourceKind: source_kind,
@@ -58,7 +68,13 @@ export function registerStartSkillLearningTool(
...(source_kind === 'hub'
? { hubCatalogScope: hub_catalog_scope ?? 'market' }
: {}),
- });
+ };
+ const authorization = await deps.authorizeSkillLearning(request, context);
+ if (!authorization.ok) {
+ return errorPayload(authorization.errorCode, authorization.message);
+ }
+
+ const result = await deps.startSkillLearning(request);
return result.ok
? okPayload({
run_id: result.runId,