forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschemas.ts
More file actions
1681 lines (1617 loc) · 57.5 KB
/
Copy pathschemas.ts
File metadata and controls
1681 lines (1617 loc) · 57.5 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 { z } from 'zod/v4'
import { HooksSchema } from '../../schemas/hooks.js'
import { McpServerConfigSchema } from '../../services/mcp/types.js'
import { lazySchema } from '../lazySchema.js'
/**
* First-layer defense against official marketplace impersonation.
*
* This validation blocks direct impersonation attempts like "anthropic-official",
* "claude-marketplace", etc. Indirect variations (e.g., "my-claude-marketplace")
* are not blocked intentionally to avoid false positives on legitimate names.
* Source org verification provides additional protection at registration/install time.
*/
/**
* Official marketplace names that are reserved for Anthropic/Claude official use.
* These names are allowed ONLY for official marketplaces and blocked for third parties.
*/
export const ALLOWED_OFFICIAL_MARKETPLACE_NAMES = new Set([
'claude-code-marketplace',
'claude-code-plugins',
'claude-plugins-official',
'anthropic-marketplace',
'anthropic-plugins',
'agent-skills',
'life-sciences',
'knowledge-work-plugins',
])
/**
* Official marketplaces that should NOT auto-update by default.
* These are still reserved/allowed names, but opt out of the auto-update
* default that other official marketplaces receive.
*/
const NO_AUTO_UPDATE_OFFICIAL_MARKETPLACES = new Set(['knowledge-work-plugins'])
/**
* Check if auto-update is enabled for a marketplace.
* Uses the stored value if set, otherwise defaults based on whether
* it's an official Anthropic marketplace (true) or not (false).
* Official marketplaces in NO_AUTO_UPDATE_OFFICIAL_MARKETPLACES are excluded
* from the auto-update default.
*
* @param marketplaceName - The name of the marketplace
* @param entry - The marketplace entry (may have autoUpdate set)
* @returns Whether auto-update is enabled for this marketplace
*/
export function isMarketplaceAutoUpdate(
marketplaceName: string,
entry: { autoUpdate?: boolean },
): boolean {
const normalizedName = marketplaceName.toLowerCase()
return (
entry.autoUpdate ??
(ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(normalizedName) &&
!NO_AUTO_UPDATE_OFFICIAL_MARKETPLACES.has(normalizedName))
)
}
/**
* Pattern to detect names that impersonate official Anthropic/Claude marketplaces.
*
* Matches names containing variations like:
* - "official" combined with "anthropic" or "claude" (e.g., "official-claude-plugins")
* - "anthropic" or "claude" combined with "official" (e.g., "claude-official")
* - Names starting with "anthropic" or "claude" followed by official-sounding terms
* like "marketplace", "plugins" (e.g., "anthropic-marketplace-new", "claude-plugins-v2")
*
* The pattern is case-insensitive.
*/
export const BLOCKED_OFFICIAL_NAME_PATTERN =
/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i
/**
* Pattern to detect non-ASCII characters that could be used for homograph attacks.
* Marketplace names should only contain ASCII characters to prevent impersonation
* via lookalike Unicode characters (e.g., Cyrillic 'а' instead of Latin 'a').
*/
const NON_ASCII_PATTERN = /[^\u0020-\u007E]/
/**
* Check if a marketplace name impersonates an official Anthropic/Claude marketplace.
*
* @param name - The marketplace name to check
* @returns true if the name is blocked (impersonates official), false if allowed
*/
export function isBlockedOfficialName(name: string): boolean {
// If it's in the allowed list, it's not blocked
if (ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(name.toLowerCase())) {
return false
}
// Block names with non-ASCII characters to prevent homograph attacks
// (e.g., using Cyrillic 'а' to impersonate 'anthropic')
if (NON_ASCII_PATTERN.test(name)) {
return true
}
// Check if it matches the blocked pattern
return BLOCKED_OFFICIAL_NAME_PATTERN.test(name)
}
/**
* The official GitHub organization for Anthropic marketplaces.
* Reserved names must come from this org.
*/
export const OFFICIAL_GITHUB_ORG = 'anthropics'
/**
* Validate that a marketplace with a reserved name comes from the official source.
*
* Reserved names (in ALLOWED_OFFICIAL_MARKETPLACE_NAMES) can only be used by
* marketplaces from the official Anthropic GitHub organization.
*
* @param name - The marketplace name
* @param source - The marketplace source configuration
* @returns An error message if validation fails, or null if valid
*/
export function validateOfficialNameSource(
name: string,
source: { source: string; repo?: string; url?: string },
): string | null {
const normalizedName = name.toLowerCase()
// Only validate reserved names
if (!ALLOWED_OFFICIAL_MARKETPLACE_NAMES.has(normalizedName)) {
return null // Not a reserved name, no source validation needed
}
// Check for GitHub source type
if (source.source === 'github') {
// Verify the repo is from the official org
const repo = source.repo || ''
if (!repo.toLowerCase().startsWith(`${OFFICIAL_GITHUB_ORG}/`)) {
return `The name '${name}' is reserved for official Anthropic marketplaces. Only repositories from 'github.com/${OFFICIAL_GITHUB_ORG}/' can use this name.`
}
return null // Valid: reserved name from official GitHub source
}
// Check for git URL source type
if (source.source === 'git' && source.url) {
const url = source.url.toLowerCase()
// Check for HTTPS URL format: https://github.com/anthropics/...
// or SSH format: git@github.com:anthropics/...
const isHttpsAnthropics = url.includes('github.com/anthropics/')
const isSshAnthropics = url.includes('git@github.com:anthropics/')
if (isHttpsAnthropics || isSshAnthropics) {
return null // Valid: reserved name from official git URL
}
return `The name '${name}' is reserved for official Anthropic marketplaces. Only repositories from 'github.com/${OFFICIAL_GITHUB_ORG}/' can use this name.`
}
// Reserved names must come from GitHub (either 'github' or 'git' source)
return `The name '${name}' is reserved for official Anthropic marketplaces and can only be used with GitHub sources from the '${OFFICIAL_GITHUB_ORG}' organization.`
}
/**
* Schema for relative file paths that must start with './'
*/
const RelativePath = lazySchema(() => z.string().startsWith('./'))
/**
* Schema for relative paths to JSON files
*/
const RelativeJSONPath = lazySchema(() => RelativePath().endsWith('.json'))
/**
* Schema for MCPB (MCP Bundle) file paths
* Supports both local relative paths and remote URLs
*/
const McpbPath = lazySchema(() =>
z.union([
RelativePath()
.refine(path => path.endsWith('.mcpb') || path.endsWith('.dxt'), {
message: 'MCPB file path must end with .mcpb or .dxt',
})
.describe('Path to MCPB file relative to plugin root'),
z
.string()
.url()
.refine(url => url.endsWith('.mcpb') || url.endsWith('.dxt'), {
message: 'MCPB URL must end with .mcpb or .dxt',
})
.describe('URL to MCPB file'),
]),
)
/**
* Schema for relative paths to Markdown files
*/
const RelativeMarkdownPath = lazySchema(() => RelativePath().endsWith('.md'))
/**
* Schema for relative paths to command sources (markdown files or directories containing SKILL.md)
*/
const RelativeCommandPath = lazySchema(() =>
z.union([
RelativeMarkdownPath(),
RelativePath(), // Allow any relative path, including directories
]),
)
/**
* Shared marketplace-name validation. Used by both PluginMarketplaceSchema
* (validates fetched marketplace.json) and the settings arm of
* MarketplaceSourceSchema (validates inline names in settings.json).
*
* The two must stay in sync: loadAndCacheMarketplace's case 'settings' writes
* to join(cacheDir, source.name) BEFORE the post-write PluginMarketplaceSchema
* validation runs. Any name that passes the settings arm but fails
* PluginMarketplaceSchema leaves orphaned files in the cache (cleanupNeeded=false).
* A single shared schema makes drift impossible.
*/
const MarketplaceNameSchema = lazySchema(() =>
z
.string()
.min(1, 'Marketplace must have a name')
.refine(name => !name.includes(' '), {
message:
'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")',
})
.refine(
name =>
!name.includes('/') &&
!name.includes('\\') &&
!name.includes('..') &&
name !== '.',
{
message:
'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."',
},
)
.refine(name => !isBlockedOfficialName(name), {
message:
'Marketplace name impersonates an official Anthropic/Claude marketplace',
})
.refine(name => name.toLowerCase() !== 'inline', {
message:
'Marketplace name "inline" is reserved for --plugin-dir session plugins',
})
.refine(name => name.toLowerCase() !== 'builtin', {
message: 'Marketplace name "builtin" is reserved for built-in plugins',
}),
)
/**
* Schema for plugin author information
*/
export const PluginAuthorSchema = lazySchema(() =>
z.object({
name: z
.string()
.min(1, 'Author name cannot be empty')
.describe('Display name of the plugin author or organization'),
email: z
.string()
.optional()
.describe('Contact email for support or feedback'),
url: z
.string()
.optional()
.describe('Website, GitHub profile, or organization URL'),
}),
)
/**
* Metadata part of the plugin manifest file (plugin.json)
*
* This schema validates the structure of plugin manifests and provides
* runtime type checking when loading plugins from disk.
*/
const PluginManifestMetadataSchema = lazySchema(() =>
z.object({
name: z
.string()
.min(1, 'Plugin name cannot be empty')
.refine(name => !name.includes(' '), {
message:
'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")',
})
.describe(
'Unique identifier for the plugin, used for namespacing (prefer kebab-case)',
),
version: z
.string()
.optional()
.describe(
'Semantic version (e.g., 1.2.3) following semver.org specification',
),
description: z
.string()
.optional()
.describe('Brief, user-facing explanation of what the plugin provides'),
author: PluginAuthorSchema()
.optional()
.describe('Information about the plugin creator or maintainer'),
homepage: z
.string()
.url()
.optional()
.describe('Plugin homepage or documentation URL'),
repository: z.string().optional().describe('Source code repository URL'),
license: z
.string()
.optional()
.describe('SPDX license identifier (e.g., MIT, Apache-2.0)'),
keywords: z
.array(z.string())
.optional()
.describe('Tags for plugin discovery and categorization'),
dependencies: z
.array(DependencyRefSchema())
.optional()
.describe(
'Plugins that must be enabled for this plugin to function. Bare names (no "@marketplace") are resolved against the declaring plugin\'s own marketplace.',
),
}),
)
/**
* Schema for plugin hooks configuration (hooks.json)
*
* Defines the hooks that a plugin can provide to intercept and modify
* Claude Code behavior at various lifecycle events.
*/
export const PluginHooksSchema = lazySchema(() =>
z.object({
description: z
.string()
.optional()
.describe('Brief, user-facing explanation of what these hooks provide'),
hooks: z
.lazy(() => HooksSchema())
.describe(
'The hooks provided by the plugin, in the same format as the one used for settings',
),
}),
)
/**
* Schema for additional hooks configuration in plugin manifest
*
* Allows plugins to specify hooks either inline or via external files,
* supplementing any hooks defined in the standard hooks/hooks.json location.
*/
const PluginManifestHooksSchema = lazySchema(() =>
z.object({
hooks: z.union([
RelativeJSONPath().describe(
'Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root',
),
z
.lazy(() => HooksSchema())
.describe(
'Additional hooks (in addition to those in hooks/hooks.json, if it exists)',
),
z.array(
z.union([
RelativeJSONPath().describe(
'Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root',
),
z
.lazy(() => HooksSchema())
.describe(
'Additional hooks (in addition to those in hooks/hooks.json, if it exists)',
),
]),
),
]),
}),
)
/**
* Schema for command metadata when using object-mapping format
*
* Allows marketplace entries to provide rich metadata for commands including
* custom descriptions and frontmatter overrides.
*
* Commands can be defined with either:
* - source: Path to a markdown file
* - content: Inline markdown content
*/
export const CommandMetadataSchema = lazySchema(() =>
z
.object({
source: RelativeCommandPath()
.optional()
.describe('Path to command markdown file, relative to plugin root'),
content: z
.string()
.optional()
.describe('Inline markdown content for the command'),
description: z
.string()
.optional()
.describe('Command description override'),
argumentHint: z
.string()
.optional()
.describe('Hint for command arguments (e.g., "[file]")'),
model: z.string().optional().describe('Default model for this command'),
allowedTools: z
.array(z.string())
.optional()
.describe('Tools allowed when command runs'),
})
.refine(
data => (data.source && !data.content) || (!data.source && data.content),
{
message:
'Command must have either "source" (file path) or "content" (inline markdown), but not both',
},
),
)
/**
* Schema for additional command definitions in plugin manifest
*
* Allows plugins to specify extra command files or skill directories beyond those
* in the standard commands/ directory.
*
* Supports three formats:
* 1. Single path: "./README.md"
* 2. Array of paths: ["./README.md", "./docs/guide.md"]
* 3. Object mapping: { "about": { "source": "./README.md", "description": "..." } }
*/
const PluginManifestCommandsSchema = lazySchema(() =>
z.object({
commands: z.union([
// TODO (future work): allow globs?
RelativeCommandPath().describe(
'Path to additional command file or skill directory (in addition to those in the commands/ directory, if it exists), relative to the plugin root',
),
z
.array(
RelativeCommandPath().describe(
'Path to additional command file or skill directory (in addition to those in the commands/ directory, if it exists), relative to the plugin root',
),
)
.describe(
'List of paths to additional command files or skill directories',
),
z
.record(z.string(), CommandMetadataSchema())
.describe(
'Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" → "/plugin:about")',
),
]),
}),
)
/**
* Schema for additional agent definitions in plugin manifest
*
* Allows plugins to specify extra agent files beyond those in the
* standard agents/ directory.
*/
const PluginManifestAgentsSchema = lazySchema(() =>
z.object({
agents: z.union([
// TODO (future work): allow globs?
RelativeMarkdownPath().describe(
'Path to additional agent file (in addition to those in the agents/ directory, if it exists), relative to the plugin root',
),
z
.array(
RelativeMarkdownPath().describe(
'Path to additional agent file (in addition to those in the agents/ directory, if it exists), relative to the plugin root',
),
)
.describe('List of paths to additional agent files'),
]),
}),
)
/**
* Schema for additional skill definitions in plugin manifest
*
* Allows plugins to specify extra skill directories beyond those in the
* standard skills/ directory.
*/
const PluginManifestSkillsSchema = lazySchema(() =>
z.object({
skills: z.union([
RelativePath().describe(
'Path to additional skill directory (in addition to those in the skills/ directory, if it exists), relative to the plugin root',
),
z
.array(
RelativePath().describe(
'Path to additional skill directory (in addition to those in the skills/ directory, if it exists), relative to the plugin root',
),
)
.describe('List of paths to additional skill directories'),
]),
}),
)
/**
* Schema for additional output style definitions in plugin manifest
*
* Allows plugins to specify extra output style files or directories beyond those in the
* standard output-styles/ directory.
*/
const PluginManifestOutputStylesSchema = lazySchema(() =>
z.object({
outputStyles: z.union([
RelativePath().describe(
'Path to additional output styles directory or file (in addition to those in the output-styles/ directory, if it exists), relative to the plugin root',
),
z
.array(
RelativePath().describe(
'Path to additional output styles directory or file (in addition to those in the output-styles/ directory, if it exists), relative to the plugin root',
),
)
.describe(
'List of paths to additional output styles directories or files',
),
]),
}),
)
// Helper validators for LSP config
const nonEmptyString = lazySchema(() => z.string().min(1))
const fileExtension = lazySchema(() =>
z
.string()
.min(2)
.refine(ext => ext.startsWith('.'), {
message: 'File extensions must start with dot (e.g., ".ts", not "ts")',
}),
)
/**
* Schema for MCP server configurations in plugin manifest
*
* Allows plugins to provide MCP servers either inline or via external
* configuration files, supplementing any servers in .mcp.json.
*/
const PluginManifestMcpServerSchema = lazySchema(() =>
z.object({
mcpServers: z.union([
RelativeJSONPath().describe(
'MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)',
),
McpbPath().describe(
'Path or URL to MCPB file containing MCP server configuration',
),
z
.record(z.string(), McpServerConfigSchema())
.describe('MCP server configurations keyed by server name'),
z
.array(
z.union([
RelativeJSONPath().describe(
'Path to MCP servers configuration file',
),
McpbPath().describe('Path or URL to MCPB file'),
z
.record(z.string(), McpServerConfigSchema())
.describe('Inline MCP server configurations'),
]),
)
.describe(
'Array of MCP server configurations (paths, MCPB files, or inline definitions)',
),
]),
}),
)
/**
* Schema for a single user-configurable option in plugin manifest userConfig.
*
* Shape intentionally matches `McpbUserConfigurationOption` from
* `@anthropic-ai/mcpb` so the parsed result is structurally assignable to
* `UserConfigSchema` in mcpbHandler.ts — this lets us reuse
* `validateUserConfig` and the config dialog without modification.
* `title` and `description` are required (not optional) because the upstream
* type requires them and the config dialog renders them.
*
* Used by both the top-level manifest.userConfig and the per-channel
* channels[].userConfig (assistant-mode channels).
*/
const PluginUserConfigOptionSchema = lazySchema(() =>
z
.object({
type: z
.enum(['string', 'number', 'boolean', 'directory', 'file'])
.describe('Type of the configuration value'),
title: z
.string()
.describe('Human-readable label shown in the config dialog'),
description: z
.string()
.describe('Help text shown beneath the field in the config dialog'),
required: z
.boolean()
.optional()
.describe('If true, validation fails when this field is empty'),
default: z
.union([z.string(), z.number(), z.boolean(), z.array(z.string())])
.optional()
.describe('Default value used when the user provides nothing'),
multiple: z
.boolean()
.optional()
.describe('For string type: allow an array of strings'),
sensitive: z
.boolean()
.optional()
.describe(
'If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json',
),
min: z.number().optional().describe('Minimum value (number type only)'),
max: z.number().optional().describe('Maximum value (number type only)'),
})
.strict(),
)
/**
* Schema for the top-level userConfig field in plugin manifest.
*
* Declares user-configurable values the plugin needs. Users are prompted at
* enable time. Non-sensitive values go to settings.json
* pluginConfigs[pluginId].options; sensitive values go to secure storage.
* Values are available as ${user_config.KEY} in MCP/LSP server config, hook
* commands, and (non-sensitive only) skill/agent content.
*/
const PluginManifestUserConfigSchema = lazySchema(() =>
z.object({
userConfig: z
.record(
z
.string()
.regex(
/^[A-Za-z_]\w*$/,
'Option keys must be valid identifiers (letters, digits, underscore; no leading digit) — they become CLAUDE_PLUGIN_OPTION_<KEY> env vars in hooks',
),
PluginUserConfigOptionSchema(),
)
.optional()
.describe(
'User-configurable values this plugin needs. Prompted at enable time. ' +
'Non-sensitive values saved to settings.json; sensitive values to secure storage ' +
'(macOS keychain or .credentials.json). Available as ${user_config.KEY} in ' +
'MCP/LSP server config, hook commands, and (non-sensitive only) skill/agent content. ' +
'Note: sensitive values share a single keychain entry with OAuth tokens — keep ' +
'secret counts small to stay under the ~2KB stdin-safe limit (see INC-3028).',
),
}),
)
/**
* Schema for channel declarations in plugin manifest.
*
* A channel is an MCP server that emits `notifications/claude/channel` to
* inject messages into the conversation (Telegram, Slack, Discord, etc.).
* Declaring it here lets the plugin prompt for user config (bot tokens,
* owner IDs) at install time via the PluginOptionsFlow prompt,
* rather than requiring users to hand-edit settings.json.
*
* The `server` field must match a key in the plugin's `mcpServers` — this is
* not cross-validated at schema parse time (the mcpServers field can be a
* path to a JSON file we haven't read yet), so the check happens at load
* time in mcpPluginIntegration.ts instead.
*/
const PluginManifestChannelsSchema = lazySchema(() =>
z.object({
channels: z
.array(
z
.object({
server: z
.string()
.min(1)
.describe(
"Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers.",
),
displayName: z
.string()
.optional()
.describe(
'Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.',
),
userConfig: z
.record(z.string(), PluginUserConfigOptionSchema())
.optional()
.describe(
'Fields to prompt the user for when enabling this plugin in assistant mode. ' +
'Saved values are substituted into ${user_config.KEY} references in the mcpServers env.',
),
})
.strict(),
)
.describe(
'Channels this plugin provides. Each entry declares an MCP server as a message channel ' +
'and optionally specifies user configuration to prompt for at enable time.',
),
}),
)
/**
* Schema for individual LSP server configuration.
*/
export const LspServerConfigSchema = lazySchema(() =>
z.strictObject({
command: z
.string()
.min(1)
.refine(
cmd => {
// Commands with spaces should use args array instead
if (cmd.includes(' ') && !cmd.startsWith('/')) {
return false
}
return true
},
{
message:
'Command should not contain spaces. Use args array for arguments.',
},
)
.describe(
'Command to execute the LSP server (e.g., "typescript-language-server")',
),
args: z
.array(nonEmptyString())
.optional()
.describe('Command-line arguments to pass to the server'),
extensionToLanguage: z
.record(fileExtension(), nonEmptyString())
.refine(record => Object.keys(record).length > 0, {
message: 'extensionToLanguage must have at least one mapping',
})
.describe(
'Mapping from file extension to LSP language ID. File extensions and languages are derived from this mapping.',
),
transport: z
.enum(['stdio', 'socket'])
.default('stdio')
.describe('Communication transport mechanism'),
env: z
.record(z.string(), z.string())
.optional()
.describe('Environment variables to set when starting the server'),
initializationOptions: z
.unknown()
.optional()
.describe(
'Initialization options passed to the server during initialization',
),
settings: z
.unknown()
.optional()
.describe(
'Settings passed to the server via workspace/didChangeConfiguration',
),
workspaceFolder: z
.string()
.optional()
.describe('Workspace folder path to use for the server'),
startupTimeout: z
.number()
.int()
.positive()
.optional()
.describe('Maximum time to wait for server startup (milliseconds)'),
shutdownTimeout: z
.number()
.int()
.positive()
.optional()
.describe('Maximum time to wait for graceful shutdown (milliseconds)'),
restartOnCrash: z
.boolean()
.optional()
.describe('Whether to restart the server if it crashes'),
maxRestarts: z
.number()
.int()
.nonnegative()
.optional()
.describe('Maximum number of restart attempts before giving up'),
}),
)
/**
* Schema for LSP server declarations in plugin manifest.
* Supports multiple formats:
* - String: path to .lsp.json file
* - Object: inline server configs { "serverName": {...} }
* - Array: mix of strings and objects
*/
const PluginManifestLspServerSchema = lazySchema(() =>
z.object({
lspServers: z.union([
RelativeJSONPath().describe(
'Path to .lsp.json configuration file relative to plugin root',
),
z
.record(z.string(), LspServerConfigSchema())
.describe('LSP server configurations keyed by server name'),
z
.array(
z.union([
RelativeJSONPath().describe('Path to LSP configuration file'),
z
.record(z.string(), LspServerConfigSchema())
.describe('Inline LSP server configurations'),
]),
)
.describe(
'Array of LSP server configurations (paths or inline definitions)',
),
]),
}),
)
/**
* Schema for npm package names
*
* Validates npm package names including scoped packages.
* Prevents path traversal attacks by disallowing '..' and '//'.
*
* Valid examples:
* - "express"
* - "@babel/core"
* - "lodash.debounce"
*
* Invalid examples:
* - "../../../etc/passwd"
* - "package//name"
*/
const NpmPackageNameSchema = lazySchema(() =>
z
.string()
.refine(
name => !name.includes('..') && !name.includes('//'),
'Package name cannot contain path traversal patterns',
)
.refine(name => {
// Allow scoped packages (@org/package) and regular packages
const scopedPackageRegex = /^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/
const regularPackageRegex = /^[a-z0-9][a-z0-9-._]*$/
return scopedPackageRegex.test(name) || regularPackageRegex.test(name)
}, 'Invalid npm package name format'),
)
/**
* Schema for plugin settings that get merged into the settings cascade.
* Accepts any record here; filtering to allowlisted keys happens at load time
* in pluginLoader.ts via PluginSettingsSchema (derived from SettingsSchema).
*/
const PluginManifestSettingsSchema = lazySchema(() =>
z.object({
settings: z
.record(z.string(), z.unknown())
.optional()
.describe(
'Settings to merge when plugin is enabled. ' +
'Only allowlisted keys are kept (currently: agent)',
),
}),
)
/**
* Plugin manifest file (plugin.json)
*
* This schema validates the structure of plugin manifests and provides
* runtime type checking when loading plugins from disk.
*
* Unknown top-level fields are silently stripped (zod default) rather than
* rejected. This keeps plugin loading resilient to custom/future top-level
* fields that plugin authors may add. Nested config objects (userConfig
* options, channels, lspServers) remain strict — unknown keys inside those
* still fail, since a typo there is more likely to be an author mistake
* than a vendor extension. Type mismatches and other validation errors
* still fail at all levels. For developer feedback on unknown top-level
* fields, use `claude plugin validate`.
*/
export const PluginManifestSchema = lazySchema(() =>
z.object({
...PluginManifestMetadataSchema().shape,
...PluginManifestHooksSchema().partial().shape,
...PluginManifestCommandsSchema().partial().shape,
...PluginManifestAgentsSchema().partial().shape,
...PluginManifestSkillsSchema().partial().shape,
...PluginManifestOutputStylesSchema().partial().shape,
...PluginManifestChannelsSchema().partial().shape,
...PluginManifestMcpServerSchema().partial().shape,
...PluginManifestLspServerSchema().partial().shape,
...PluginManifestSettingsSchema().partial().shape,
...PluginManifestUserConfigSchema().partial().shape,
}),
)
/**
* Schema for marketplace source locations
*
* Defines various ways to reference marketplace manifests including
* direct URLs, GitHub repos, git URLs, npm packages, and local paths.
*/
export const MarketplaceSourceSchema = lazySchema(() =>
z.discriminatedUnion('source', [
z.object({
source: z.literal('url'),
url: z.string().url().describe('Direct URL to marketplace.json file'),
headers: z
.record(z.string(), z.string())
.optional()
.describe('Custom HTTP headers (e.g., for authentication)'),
}),
z.object({
source: z.literal('github'),
repo: z.string().describe('GitHub repository in owner/repo format'),
ref: z
.string()
.optional()
.describe(
'Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.',
),
path: z
.string()
.optional()
.describe(
'Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)',
),
sparsePaths: z
.array(z.string())
.optional()
.describe(
'Directories to include via git sparse-checkout (cone mode). ' +
'Use for monorepos where the marketplace lives in a subdirectory. ' +
'Example: [".claude-plugin", "plugins"]. ' +
'If omitted, the full repository is cloned.',
),
}),
z.object({
source: z.literal('git'),
// No .endsWith('.git') here — that's a GitHub/GitLab/Bitbucket
// convention, not a git requirement. Azure DevOps uses
// https://dev.azure.com/{org}/{proj}/_git/{repo} with no suffix, and
// appending .git makes ADO look for a repo literally named {repo}.git
// (TF401019). AWS CodeCommit also omits the suffix. If the user
// explicitly wrote source:'git', they know it's a git repo; a typo'd
// URL fails at `git clone` with a clearer error anyway. (gh-31256)
url: z.string().describe('Full git repository URL'),
ref: z
.string()
.optional()
.describe(
'Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.',
),
path: z
.string()
.optional()
.describe(
'Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)',
),
sparsePaths: z
.array(z.string())
.optional()
.describe(
'Directories to include via git sparse-checkout (cone mode). ' +
'Use for monorepos where the marketplace lives in a subdirectory. ' +
'Example: [".claude-plugin", "plugins"]. ' +
'If omitted, the full repository is cloned.',
),
}),
z.object({
source: z.literal('npm'),
package: NpmPackageNameSchema().describe(
'NPM package containing marketplace.json',
),
}),
z.object({
source: z.literal('file'),
path: z.string().describe('Local file path to marketplace.json'),
}),
z.object({
source: z.literal('directory'),
path: z
.string()
.describe('Local directory containing .claude-plugin/marketplace.json'),
}),
z.object({
source: z.literal('hostPattern'),
hostPattern: z
.string()
.describe(
'Regex pattern to match the host/domain extracted from any marketplace source type. ' +
'For github sources, matches against "github.com". For git sources (SSH or HTTPS), ' +
'extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all ' +
'marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").',
),
}),
z.object({