forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSkillTool.ts
More file actions
1108 lines (1024 loc) · 37.3 KB
/
Copy pathSkillTool.ts
File metadata and controls
1108 lines (1024 loc) · 37.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { feature } from 'bun:bundle'
import type { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs'
import uniqBy from 'lodash-es/uniqBy.js'
import { dirname } from 'path'
import { getProjectRoot } from 'src/bootstrap/state.js'
import {
builtInCommandNames,
findCommand,
getCommands,
type PromptCommand,
} from 'src/commands.js'
import type {
Tool,
ToolCallProgress,
ToolResult,
ToolUseContext,
ValidationResult,
} from 'src/Tool.js'
import { buildTool, type ToolDef } from 'src/Tool.js'
import type { Command } from 'src/types/command.js'
import type {
AssistantMessage,
AttachmentMessage,
Message,
SystemMessage,
UserMessage,
} from 'src/types/message.js'
import { logForDebugging } from 'src/utils/debug.js'
import type { PermissionDecision } from 'src/utils/permissions/PermissionResult.js'
import { getRuleByContentsForTool } from 'src/utils/permissions/permissions.js'
import {
isOfficialMarketplaceName,
parsePluginIdentifier,
} from 'src/utils/plugins/pluginIdentifier.js'
import { buildPluginCommandTelemetryFields } from 'src/utils/telemetry/pluginTelemetry.js'
import { z } from 'zod/v4'
import {
addInvokedSkill,
clearInvokedSkillsForAgent,
getSessionId,
} from '../../bootstrap/state.js'
import { COMMAND_MESSAGE_TAG } from '../../constants/xml.js'
import type { CanUseToolFn } from '../../hooks/useCanUseTool.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
type AnalyticsMetadata_I_VERIFIED_THIS_IS_PII_TAGGED,
logEvent,
} from '../../services/analytics/index.js'
import { getAgentContext } from '../../utils/agentContext.js'
import { errorMessage } from '../../utils/errors.js'
import {
extractResultText,
prepareForkedCommandContext,
} from '../../utils/forkedAgent.js'
import { parseFrontmatter } from '../../utils/frontmatterParser.js'
import { lazySchema } from '../../utils/lazySchema.js'
import { createUserMessage, normalizeMessages } from '../../utils/messages.js'
import type { ModelAlias } from '../../utils/model/aliases.js'
import { resolveSkillModelOverride } from '../../utils/model/model.js'
import { recordSkillUsage } from '../../utils/suggestions/skillUsageTracking.js'
import { createAgentId } from '../../utils/uuid.js'
import { runAgent } from '../AgentTool/runAgent.js'
import {
getToolUseIDFromParentMessage,
tagMessagesWithToolUseID,
} from '../utils.js'
import { SKILL_TOOL_NAME } from './constants.js'
import { getPrompt } from './prompt.js'
import {
renderToolResultMessage,
renderToolUseErrorMessage,
renderToolUseMessage,
renderToolUseProgressMessage,
renderToolUseRejectedMessage,
} from './UI.js'
/**
* Gets all commands including MCP skills/prompts from AppState.
* SkillTool needs this because getCommands() only returns local/bundled skills.
*/
async function getAllCommands(context: ToolUseContext): Promise<Command[]> {
// Only include MCP skills (loadedFrom === 'mcp'), not plain MCP prompts.
// Before this filter, the model could invoke MCP prompts via SkillTool
// if it guessed the mcp__server__prompt name — they weren't discoverable
// but were technically reachable.
const mcpSkills = context
.getAppState()
.mcp.commands.filter(
cmd => cmd.type === 'prompt' && cmd.loadedFrom === 'mcp',
)
if (mcpSkills.length === 0) return getCommands(getProjectRoot())
const localCommands = await getCommands(getProjectRoot())
return uniqBy([...localCommands, ...mcpSkills], 'name')
}
// Re-export Progress from centralized types to break import cycles
export type { SkillToolProgress as Progress } from '../../types/tools.js'
import type { SkillToolProgress as Progress } from '../../types/tools.js'
// Conditional require for remote skill modules — static imports here would
// pull in akiBackend.ts (via remoteSkillLoader → akiBackend), which has
// module-level memoize()/lazySchema() consts that survive tree-shaking as
// side-effecting initializers. All usages are inside
// feature('EXPERIMENTAL_SKILL_SEARCH') guards, so remoteSkillModules is
// non-null at every call site.
/* eslint-disable @typescript-eslint/no-require-imports */
const remoteSkillModules = feature('EXPERIMENTAL_SKILL_SEARCH')
? {
...(require('../../services/skillSearch/remoteSkillState.js') as typeof import('../../services/skillSearch/remoteSkillState.js')),
...(require('../../services/skillSearch/remoteSkillLoader.js') as typeof import('../../services/skillSearch/remoteSkillLoader.js')),
...(require('../../services/skillSearch/telemetry.js') as typeof import('../../services/skillSearch/telemetry.js')),
...(require('../../services/skillSearch/featureCheck.js') as typeof import('../../services/skillSearch/featureCheck.js')),
}
: null
/* eslint-enable @typescript-eslint/no-require-imports */
/**
* Executes a skill in a forked sub-agent context.
* This runs the skill prompt in an isolated agent with its own token budget.
*/
async function executeForkedSkill(
command: Command & { type: 'prompt' },
commandName: string,
args: string | undefined,
context: ToolUseContext,
canUseTool: CanUseToolFn,
parentMessage: AssistantMessage,
onProgress?: ToolCallProgress<Progress>,
): Promise<ToolResult<Output>> {
const startTime = Date.now()
const agentId = createAgentId()
const isBuiltIn = builtInCommandNames().has(commandName)
const isOfficialSkill = isOfficialMarketplaceSkill(command)
const isBundled = command.source === 'bundled'
const forkedSanitizedName =
isBuiltIn || isBundled || isOfficialSkill ? commandName : 'custom'
const wasDiscoveredField =
feature('EXPERIMENTAL_SKILL_SEARCH') &&
remoteSkillModules!.isSkillSearchEnabled()
? {
was_discovered:
context.discoveredSkillNames?.has(commandName) ?? false,
}
: {}
const pluginMarketplace = command.pluginInfo
? parsePluginIdentifier(command.pluginInfo.repository).marketplace
: undefined
const queryDepth = context.queryTracking?.depth ?? 0
const parentAgentId = getAgentContext()?.agentId
logEvent('tengu_skill_tool_invocation', {
command_name:
forkedSanitizedName as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
// _PROTO_skill_name routes to the privileged skill_name BQ column
// (unredacted, all users); command_name stays in additional_metadata as
// the redacted variant for general-access dashboards.
_PROTO_skill_name:
commandName as AnalyticsMetadata_I_VERIFIED_THIS_IS_PII_TAGGED,
execution_context:
'fork' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
invocation_trigger: (queryDepth > 0
? 'nested-skill'
: 'claude-proactive') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
query_depth: queryDepth,
...(parentAgentId && {
parent_agent_id:
parentAgentId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...wasDiscoveredField,
...(process.env.USER_TYPE === 'ant' && {
skill_name:
commandName as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
skill_source:
command.source as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
...(command.loadedFrom && {
skill_loaded_from:
command.loadedFrom as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(command.kind && {
skill_kind:
command.kind as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
}),
...(command.pluginInfo && {
// _PROTO_* routes to PII-tagged plugin_name/marketplace_name BQ columns
// (unredacted, all users); plugin_name/plugin_repository stay in
// additional_metadata as redacted variants.
_PROTO_plugin_name: command.pluginInfo.pluginManifest
.name as AnalyticsMetadata_I_VERIFIED_THIS_IS_PII_TAGGED,
...(pluginMarketplace && {
_PROTO_marketplace_name:
pluginMarketplace as AnalyticsMetadata_I_VERIFIED_THIS_IS_PII_TAGGED,
}),
plugin_name: (isOfficialSkill
? command.pluginInfo.pluginManifest.name
: 'third-party') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
plugin_repository: (isOfficialSkill
? command.pluginInfo.repository
: 'third-party') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
...buildPluginCommandTelemetryFields(command.pluginInfo),
}),
})
const { modifiedGetAppState, baseAgent, promptMessages, skillContent } =
await prepareForkedCommandContext(command, args || '', context)
// Merge skill's effort into the agent definition so runAgent applies it
const agentDefinition =
command.effort !== undefined
? { ...baseAgent, effort: command.effort }
: baseAgent
// Collect messages from the forked agent
const agentMessages: Message[] = []
logForDebugging(
`SkillTool executing forked skill ${commandName} with agent ${agentDefinition.agentType}`,
)
try {
// Run the sub-agent
for await (const message of runAgent({
agentDefinition,
promptMessages,
toolUseContext: {
...context,
getAppState: modifiedGetAppState,
},
canUseTool,
isAsync: false,
querySource: 'agent:custom',
model: command.model as ModelAlias | undefined,
availableTools: context.options.tools,
override: { agentId },
})) {
agentMessages.push(message)
// Report progress for tool uses (like AgentTool does)
if (
(message.type === 'assistant' || message.type === 'user') &&
onProgress
) {
const normalizedNew = normalizeMessages([message])
for (const m of normalizedNew) {
const hasToolContent = m.message.content.some(
c => c.type === 'tool_use' || c.type === 'tool_result',
)
if (hasToolContent) {
onProgress({
toolUseID: `skill_${parentMessage.message.id}`,
data: {
message: m,
type: 'skill_progress',
prompt: skillContent,
agentId,
},
})
}
}
}
}
const resultText = extractResultText(
agentMessages,
'Skill execution completed',
)
// Release message memory after extracting result
agentMessages.length = 0
const durationMs = Date.now() - startTime
logForDebugging(
`SkillTool forked skill ${commandName} completed in ${durationMs}ms`,
)
return {
data: {
success: true,
commandName,
status: 'forked',
agentId,
result: resultText,
},
}
} finally {
// Release skill content from invokedSkills state
clearInvokedSkillsForAgent(agentId)
}
}
export const inputSchema = lazySchema(() =>
z.object({
skill: z
.string()
.describe('The skill name. E.g., "commit", "review-pr", or "pdf"'),
args: z.string().optional().describe('Optional arguments for the skill'),
}),
)
type InputSchema = ReturnType<typeof inputSchema>
export const outputSchema = lazySchema(() => {
// Output schema for inline skills (default)
const inlineOutputSchema = z.object({
success: z.boolean().describe('Whether the skill is valid'),
commandName: z.string().describe('The name of the skill'),
allowedTools: z
.array(z.string())
.optional()
.describe('Tools allowed by this skill'),
model: z.string().optional().describe('Model override if specified'),
status: z.literal('inline').optional().describe('Execution status'),
})
// Output schema for forked skills
const forkedOutputSchema = z.object({
success: z.boolean().describe('Whether the skill completed successfully'),
commandName: z.string().describe('The name of the skill'),
status: z.literal('forked').describe('Execution status'),
agentId: z
.string()
.describe('The ID of the sub-agent that executed the skill'),
result: z.string().describe('The result from the forked skill execution'),
})
return z.union([inlineOutputSchema, forkedOutputSchema])
})
type OutputSchema = ReturnType<typeof outputSchema>
export type Output = z.input<OutputSchema>
export const SkillTool: Tool<InputSchema, Output, Progress> = buildTool({
name: SKILL_TOOL_NAME,
searchHint: 'invoke a slash-command skill',
maxResultSizeChars: 100_000,
get inputSchema(): InputSchema {
return inputSchema()
},
get outputSchema(): OutputSchema {
return outputSchema()
},
description: async ({ skill }) => `Execute skill: ${skill}`,
prompt: async () => getPrompt(getProjectRoot()),
// Only one skill/command should run at a time, since the tool expands the
// command into a full prompt that Claude must process before continuing.
// Skill-coach needs the skill name to avoid false-positive "you could have
// used skill X" suggestions when X was actually invoked. Backseat classifies
// downstream tool calls from the expanded prompt, not this wrapper, so the
// name alone is sufficient — it just records that the skill fired.
toAutoClassifierInput: ({ skill }) => skill ?? '',
async validateInput({ skill }, context): Promise<ValidationResult> {
// Skills are just skill names, no arguments
const trimmed = skill.trim()
if (!trimmed) {
return {
result: false,
message: `Invalid skill format: ${skill}`,
errorCode: 1,
}
}
// Remove leading slash if present (for compatibility)
const hasLeadingSlash = trimmed.startsWith('/')
if (hasLeadingSlash) {
logEvent('tengu_skill_tool_slash_prefix', {})
}
const normalizedCommandName = hasLeadingSlash
? trimmed.substring(1)
: trimmed
// Remote canonical skill handling (ant-only experimental). Intercept
// `_canonical_<slug>` names before local command lookup since remote
// skills are not in the local command registry.
if (
feature('EXPERIMENTAL_SKILL_SEARCH') &&
process.env.USER_TYPE === 'ant'
) {
const slug = remoteSkillModules!.stripCanonicalPrefix(
normalizedCommandName,
)
if (slug !== null) {
const meta = remoteSkillModules!.getDiscoveredRemoteSkill(slug)
if (!meta) {
return {
result: false,
message: `Remote skill ${slug} was not discovered in this session. Use DiscoverSkills to find remote skills first.`,
errorCode: 6,
}
}
// Discovered remote skill — valid. Loading happens in call().
return { result: true }
}
}
// Get available commands (including MCP skills)
const commands = await getAllCommands(context)
// Check if command exists
const foundCommand = findCommand(normalizedCommandName, commands)
if (!foundCommand) {
return {
result: false,
message: `Unknown skill: ${normalizedCommandName}`,
errorCode: 2,
}
}
// Check if command has model invocation disabled
if (foundCommand.disableModelInvocation) {
return {
result: false,
message: `Skill ${normalizedCommandName} cannot be used with ${SKILL_TOOL_NAME} tool due to disable-model-invocation`,
errorCode: 4,
}
}
// Check if command is a prompt-based command
if (foundCommand.type !== 'prompt') {
return {
result: false,
message: `Skill ${normalizedCommandName} is not a prompt-based skill`,
errorCode: 5,
}
}
return { result: true }
},
async checkPermissions(
{ skill, args },
context,
): Promise<PermissionDecision> {
// Skills are just skill names, no arguments
const trimmed = skill.trim()
// Remove leading slash if present (for compatibility)
const commandName = trimmed.startsWith('/') ? trimmed.substring(1) : trimmed
const appState = context.getAppState()
const permissionContext = appState.toolPermissionContext
// Look up the command object to pass as metadata
const commands = await getAllCommands(context)
const commandObj = findCommand(commandName, commands)
// Helper function to check if a rule matches the skill
// Normalizes both inputs by stripping leading slashes for consistent matching
const ruleMatches = (ruleContent: string): boolean => {
// Normalize rule content by stripping leading slash
const normalizedRule = ruleContent.startsWith('/')
? ruleContent.substring(1)
: ruleContent
// Check exact match (using normalized commandName)
if (normalizedRule === commandName) {
return true
}
// Check prefix match (e.g., "review:*" matches "review-pr 123")
if (normalizedRule.endsWith(':*')) {
const prefix = normalizedRule.slice(0, -2) // Remove ':*'
return commandName.startsWith(prefix)
}
return false
}
// Check for deny rules
const denyRules = getRuleByContentsForTool(
permissionContext,
SkillTool as Tool,
'deny',
)
for (const [ruleContent, rule] of denyRules.entries()) {
if (ruleMatches(ruleContent)) {
return {
behavior: 'deny',
message: `Skill execution blocked by permission rules`,
decisionReason: {
type: 'rule',
rule,
},
}
}
}
// Remote canonical skills are ant-only experimental — auto-grant.
// Placed AFTER the deny loop so a user-configured Skill(_canonical_:*)
// deny rule is honored (same pattern as safe-properties auto-allow below).
// The skill content itself is canonical/curated, not user-authored.
if (
feature('EXPERIMENTAL_SKILL_SEARCH') &&
process.env.USER_TYPE === 'ant'
) {
const slug = remoteSkillModules!.stripCanonicalPrefix(commandName)
if (slug !== null) {
return {
behavior: 'allow',
updatedInput: { skill, args },
decisionReason: undefined,
}
}
}
// Check for allow rules
const allowRules = getRuleByContentsForTool(
permissionContext,
SkillTool as Tool,
'allow',
)
for (const [ruleContent, rule] of allowRules.entries()) {
if (ruleMatches(ruleContent)) {
return {
behavior: 'allow',
updatedInput: { skill, args },
decisionReason: {
type: 'rule',
rule,
},
}
}
}
// Auto-allow skills that only use safe properties.
// This is an allowlist: if a skill has any property NOT in this set with a
// meaningful value, it requires permission. This ensures new properties added
// in the future default to requiring permission.
if (
commandObj?.type === 'prompt' &&
skillHasOnlySafeProperties(commandObj)
) {
return {
behavior: 'allow',
updatedInput: { skill, args },
decisionReason: undefined,
}
}
// Prepare suggestions for exact skill and prefix
// Use normalized commandName (without leading slash) for consistent rules
const suggestions = [
// Exact skill suggestion
{
type: 'addRules' as const,
rules: [
{
toolName: SKILL_TOOL_NAME,
ruleContent: commandName,
},
],
behavior: 'allow' as const,
destination: 'localSettings' as const,
},
// Prefix suggestion to allow any args
{
type: 'addRules' as const,
rules: [
{
toolName: SKILL_TOOL_NAME,
ruleContent: `${commandName}:*`,
},
],
behavior: 'allow' as const,
destination: 'localSettings' as const,
},
]
// Default behavior: ask user for permission
return {
behavior: 'ask',
message: `Execute skill: ${commandName}`,
decisionReason: undefined,
suggestions,
updatedInput: { skill, args },
metadata: commandObj ? { command: commandObj } : undefined,
}
},
async call(
{ skill, args },
context,
canUseTool,
parentMessage,
onProgress?,
): Promise<ToolResult<Output>> {
// At this point, validateInput has already confirmed:
// - Skill format is valid
// - Skill exists
// - Skill can be loaded
// - Skill doesn't have disableModelInvocation
// - Skill is a prompt-based skill
// Skills are just names, with optional arguments
const trimmed = skill.trim()
// Remove leading slash if present (for compatibility)
const commandName = trimmed.startsWith('/') ? trimmed.substring(1) : trimmed
// Remote canonical skill execution (ant-only experimental). Intercepts
// `_canonical_<slug>` before local command lookup — loads SKILL.md from
// AKI/GCS (with local cache), injects content directly as a user message.
// Remote skills are declarative markdown so no slash-command expansion
// (no !command substitution, no $ARGUMENTS interpolation) is needed.
if (
feature('EXPERIMENTAL_SKILL_SEARCH') &&
process.env.USER_TYPE === 'ant'
) {
const slug = remoteSkillModules!.stripCanonicalPrefix(commandName)
if (slug !== null) {
return executeRemoteSkill(slug, commandName, parentMessage, context)
}
}
const commands = await getAllCommands(context)
const command = findCommand(commandName, commands)
// Track skill usage for ranking
recordSkillUsage(commandName)
// Check if skill should run as a forked sub-agent
if (command?.type === 'prompt' && command.context === 'fork') {
return executeForkedSkill(
command,
commandName,
args,
context,
canUseTool,
parentMessage,
onProgress,
)
}
// Process the skill with optional args
const { processPromptSlashCommand } = await import(
'src/utils/processUserInput/processSlashCommand.js'
)
const processedCommand = await processPromptSlashCommand(
commandName,
args || '', // Pass args if provided
commands,
context,
)
if (!processedCommand.shouldQuery) {
throw new Error('Command processing failed')
}
// Extract metadata from the command
const allowedTools = processedCommand.allowedTools || []
const model = processedCommand.model
const effort = command?.type === 'prompt' ? command.effort : undefined
const isBuiltIn = builtInCommandNames().has(commandName)
const isBundled = command?.type === 'prompt' && command.source === 'bundled'
const isOfficialSkill =
command?.type === 'prompt' && isOfficialMarketplaceSkill(command)
const sanitizedCommandName =
isBuiltIn || isBundled || isOfficialSkill ? commandName : 'custom'
const wasDiscoveredField =
feature('EXPERIMENTAL_SKILL_SEARCH') &&
remoteSkillModules!.isSkillSearchEnabled()
? {
was_discovered:
context.discoveredSkillNames?.has(commandName) ?? false,
}
: {}
const pluginMarketplace =
command?.type === 'prompt' && command.pluginInfo
? parsePluginIdentifier(command.pluginInfo.repository).marketplace
: undefined
const queryDepth = context.queryTracking?.depth ?? 0
const parentAgentId = getAgentContext()?.agentId
logEvent('tengu_skill_tool_invocation', {
command_name:
sanitizedCommandName as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
// _PROTO_skill_name routes to the privileged skill_name BQ column
// (unredacted, all users); command_name stays in additional_metadata as
// the redacted variant for general-access dashboards.
_PROTO_skill_name:
commandName as AnalyticsMetadata_I_VERIFIED_THIS_IS_PII_TAGGED,
execution_context:
'inline' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
invocation_trigger: (queryDepth > 0
? 'nested-skill'
: 'claude-proactive') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
query_depth: queryDepth,
...(parentAgentId && {
parent_agent_id:
parentAgentId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...wasDiscoveredField,
...(process.env.USER_TYPE === 'ant' && {
skill_name:
commandName as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
...(command?.type === 'prompt' && {
skill_source:
command.source as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(command?.loadedFrom && {
skill_loaded_from:
command.loadedFrom as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(command?.kind && {
skill_kind:
command.kind as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
}),
...(command?.type === 'prompt' &&
command.pluginInfo && {
_PROTO_plugin_name: command.pluginInfo.pluginManifest
.name as AnalyticsMetadata_I_VERIFIED_THIS_IS_PII_TAGGED,
...(pluginMarketplace && {
_PROTO_marketplace_name:
pluginMarketplace as AnalyticsMetadata_I_VERIFIED_THIS_IS_PII_TAGGED,
}),
plugin_name: (isOfficialSkill
? command.pluginInfo.pluginManifest.name
: 'third-party') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
plugin_repository: (isOfficialSkill
? command.pluginInfo.repository
: 'third-party') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
...buildPluginCommandTelemetryFields(command.pluginInfo),
}),
})
// Get the tool use ID from the parent message for linking newMessages
const toolUseID = getToolUseIDFromParentMessage(
parentMessage,
SKILL_TOOL_NAME,
)
// Tag user messages with sourceToolUseID so they stay transient until this tool resolves
const newMessages = tagMessagesWithToolUseID(
processedCommand.messages.filter(
(m): m is UserMessage | AttachmentMessage | SystemMessage => {
if (m.type === 'progress') {
return false
}
// Filter out command-message since SkillTool handles display
if (m.type === 'user' && 'message' in m) {
const content = m.message.content
if (
typeof content === 'string' &&
content.includes(`<${COMMAND_MESSAGE_TAG}>`)
) {
return false
}
}
return true
},
),
toolUseID,
)
logForDebugging(
`SkillTool returning ${newMessages.length} newMessages for skill ${commandName}`,
)
// Note: addInvokedSkill and registerSkillHooks are called inside
// processPromptSlashCommand (via getMessagesForPromptSlashCommand), so
// calling them again here would double-register hooks and rebuild
// skillContent redundantly.
// Return success with newMessages and contextModifier
return {
data: {
success: true,
commandName,
allowedTools: allowedTools.length > 0 ? allowedTools : undefined,
model,
},
newMessages,
contextModifier(ctx) {
let modifiedContext = ctx
// Update allowed tools if specified
if (allowedTools.length > 0) {
// Capture the current getAppState to chain modifications properly
const previousGetAppState = modifiedContext.getAppState
modifiedContext = {
...modifiedContext,
getAppState() {
// Use the previous getAppState, not the closure's context.getAppState,
// to properly chain context modifications
const appState = previousGetAppState()
return {
...appState,
toolPermissionContext: {
...appState.toolPermissionContext,
alwaysAllowRules: {
...appState.toolPermissionContext.alwaysAllowRules,
command: [
...new Set([
...(appState.toolPermissionContext.alwaysAllowRules
.command || []),
...allowedTools,
]),
],
},
},
}
},
}
}
// Carry [1m] suffix over — otherwise a skill with `model: opus` on an
// opus[1m] session drops the effective window to 200K and trips autocompact.
if (model) {
modifiedContext = {
...modifiedContext,
options: {
...modifiedContext.options,
mainLoopModel: resolveSkillModelOverride(
model,
ctx.options.mainLoopModel,
),
},
}
}
// Override effort level if skill specifies one
if (effort !== undefined) {
const previousGetAppState = modifiedContext.getAppState
modifiedContext = {
...modifiedContext,
getAppState() {
const appState = previousGetAppState()
return {
...appState,
effortValue: effort,
}
},
}
}
return modifiedContext
},
}
},
mapToolResultToToolResultBlockParam(
result: Output,
toolUseID: string,
): ToolResultBlockParam {
// Handle forked skill result
if ('status' in result && result.status === 'forked') {
return {
type: 'tool_result' as const,
tool_use_id: toolUseID,
content: `Skill "${result.commandName}" completed (forked execution).\n\nResult:\n${result.result}`,
}
}
// Inline skill result (default)
return {
type: 'tool_result' as const,
tool_use_id: toolUseID,
content: `Launching skill: ${result.commandName}`,
}
},
renderToolResultMessage,
renderToolUseMessage,
renderToolUseProgressMessage,
renderToolUseRejectedMessage,
renderToolUseErrorMessage,
} satisfies ToolDef<InputSchema, Output, Progress>)
// Allowlist of PromptCommand property keys that are safe and don't require permission.
// If a skill has any property NOT in this set with a meaningful value, it requires
// permission. This ensures new properties added to PromptCommand in the future
// default to requiring permission until explicitly reviewed and added here.
const SAFE_SKILL_PROPERTIES = new Set([
// PromptCommand properties
'type',
'progressMessage',
'contentLength',
'argNames',
'model',
'effort',
'source',
'pluginInfo',
'disableNonInteractive',
'skillRoot',
'context',
'agent',
'getPromptForCommand',
'frontmatterKeys',
// CommandBase properties
'name',
'description',
'hasUserSpecifiedDescription',
'isEnabled',
'isHidden',
'aliases',
'isMcp',
'argumentHint',
'whenToUse',
'paths',
'version',
'disableModelInvocation',
'userInvocable',
'loadedFrom',
'immediate',
'userFacingName',
])
function skillHasOnlySafeProperties(command: Command): boolean {
for (const key of Object.keys(command)) {
if (SAFE_SKILL_PROPERTIES.has(key)) {
continue
}
// Property not in safe allowlist - check if it has a meaningful value
const value = (command as Record<string, unknown>)[key]
if (value === undefined || value === null) {
continue
}
if (Array.isArray(value) && value.length === 0) {
continue
}
if (
typeof value === 'object' &&
!Array.isArray(value) &&
Object.keys(value).length === 0
) {
continue
}
return false
}
return true
}
function isOfficialMarketplaceSkill(command: PromptCommand): boolean {
if (command.source !== 'plugin' || !command.pluginInfo?.repository) {
return false
}
return isOfficialMarketplaceName(
parsePluginIdentifier(command.pluginInfo.repository).marketplace,
)
}
/**
* Extract URL scheme for telemetry. Defaults to 'gs' for unrecognized schemes
* since the AKI backend is the only production path and the loader throws on
* unknown schemes before we reach telemetry anyway.
*/
function extractUrlScheme(url: string): 'gs' | 'http' | 'https' | 's3' {
if (url.startsWith('gs://')) return 'gs'
if (url.startsWith('https://')) return 'https'
if (url.startsWith('http://')) return 'http'
if (url.startsWith('s3://')) return 's3'
return 'gs'
}
/**
* Load a remote canonical skill and inject its SKILL.md content into the
* conversation. Unlike local skills (which go through processPromptSlashCommand
* for !command / $ARGUMENTS expansion), remote skills are declarative markdown
* — we wrap the content directly in a user message.
*
* The skill is also registered with addInvokedSkill so it survives compaction
* (same as local skills).
*
* Only called from within a feature('EXPERIMENTAL_SKILL_SEARCH') guard in
* call() — remoteSkillModules is non-null here.
*/
async function executeRemoteSkill(
slug: string,
commandName: string,
parentMessage: AssistantMessage,
context: ToolUseContext,
): Promise<ToolResult<Output>> {
const { getDiscoveredRemoteSkill, loadRemoteSkill, logRemoteSkillLoaded } =
remoteSkillModules!
// validateInput already confirmed this slug is in session state, but we
// re-fetch here to get the URL. If it's somehow gone (e.g., state cleared
// mid-session), fail with a clear error rather than crashing.
const meta = getDiscoveredRemoteSkill(slug)
if (!meta) {
throw new Error(
`Remote skill ${slug} was not discovered in this session. Use DiscoverSkills to find remote skills first.`,
)
}
const urlScheme = extractUrlScheme(meta.url)
let loadResult
try {
loadResult = await loadRemoteSkill(slug, meta.url)
} catch (e) {
const msg = errorMessage(e)
logRemoteSkillLoaded({
slug,
cacheHit: false,
latencyMs: 0,
urlScheme,
error: msg,
})