-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSetup-CopilotSettings.ps1
More file actions
464 lines (404 loc) · 18.9 KB
/
Copy pathSetup-CopilotSettings.ps1
File metadata and controls
464 lines (404 loc) · 18.9 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
<#
.SYNOPSIS
Configures VS Code settings for Copilot custom agents, instructions, skills, and prompts.
.DESCRIPTION
Derives the folder name from the repository root (e.g. CopilotAtelier),
copies customization files to OneDrive or the user profile, and links the
well-known ~/.copilot directories to that target. Resolves the VS Code user
directory using the conventions for Windows, macOS, and Linux. Idempotent:
removes obsolete location aliases without disturbing user-defined entries,
strips JSONC comments before parsing, and creates a timestamped backup on
every run.
.PARAMETER SkipCopilotCliEnvironment
Skips the user-scoped COPILOT_ALLOW_ALL configuration. Intended for
sandboxed tests that must not mutate the host user profile.
#>
[CmdletBinding()]
param(
[Parameter()]
[switch]$SkipCopilotCliEnvironment
)
$ErrorActionPreference = 'Stop'
# --- Resolve the repo root and derive the folder name used for paths ---
$repoRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
$repoName = Split-Path -Leaf $repoRoot
$isWindowsPlatform = [Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT
$isMacOSPlatform = $false
$isMacOSVariable = Get-Variable -Name IsMacOS -ErrorAction SilentlyContinue
if ($isMacOSVariable) {
$isMacOSPlatform = [bool]$isMacOSVariable.Value
}
if ($isWindowsPlatform -and -not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
$userHome = $env:USERPROFILE
} elseif (-not [string]::IsNullOrWhiteSpace($env:HOME)) {
$userHome = $env:HOME
} else {
$userHome = [Environment]::GetFolderPath([Environment+SpecialFolder]::UserProfile)
}
if ([string]::IsNullOrWhiteSpace($userHome)) {
throw 'Unable to resolve the current user profile directory.'
}
if ($isWindowsPlatform) {
$configRoot = $env:APPDATA
if ([string]::IsNullOrWhiteSpace($configRoot)) {
$configRoot = [Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData)
}
} elseif ($isMacOSPlatform) {
$configRoot = Join-Path $userHome 'Library/Application Support'
} elseif (-not [string]::IsNullOrWhiteSpace($env:XDG_CONFIG_HOME)) {
$configRoot = $env:XDG_CONFIG_HOME
} else {
$configRoot = Join-Path $userHome '.config'
}
if ([string]::IsNullOrWhiteSpace($configRoot)) {
throw 'Unable to resolve the VS Code configuration directory.'
}
$settingsDir = Join-Path (Join-Path $configRoot 'Code') 'User'
$settingsPath = Join-Path $settingsDir 'settings.json'
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
if (-not (Test-Path $settingsDir)) {
New-Item -ItemType Directory -Path $settingsDir -Force | Out-Null
Write-Host "Created VS Code User directory: $settingsDir"
}
if (-not (Test-Path $settingsPath)) {
Write-Host "VS Code settings file not found at $settingsPath - creating a new one."
'{}' | Set-Content -Path $settingsPath -Encoding UTF8
} else {
# Back up the existing settings file with a timestamp
$backupPath = "$settingsPath.$timestamp.bak"
Copy-Item -Path $settingsPath -Destination $backupPath -Force
Write-Host "Backup created: $backupPath"
}
# Helper: merge new keys into an existing location-map property without removing
# any paths the user added manually between runs.
function Merge-LocationSetting {
param(
[psobject]$Settings,
[string]$PropertyName,
[hashtable]$NewEntries
)
$merged = [ordered]@{}
# Preserve every existing key
if ($Settings.PSObject.Properties[$PropertyName]) {
foreach ($prop in $Settings.$PropertyName.PSObject.Properties) {
$merged[$prop.Name] = $prop.Value
}
}
# Add / overwrite only the keys we care about
foreach ($key in $NewEntries.Keys) {
$merged[$key] = $NewEntries[$key]
}
$Settings | Add-Member -NotePropertyName $PropertyName `
-NotePropertyValue ([pscustomobject]$merged) -Force
}
function Remove-LocationSettingEntry {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[psobject]$Settings,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$PropertyName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$Entry
)
$property = $Settings.PSObject.Properties[$PropertyName]
if (-not $property) {
return
}
foreach ($entryName in $Entry) {
if ($PSCmdlet.ShouldProcess($PropertyName, "Remove location entry '$entryName'")) {
$property.Value.PSObject.Properties.Remove($entryName)
}
}
if (@($property.Value.PSObject.Properties).Count -eq 0) {
$Settings.PSObject.Properties.Remove($PropertyName)
}
}
# Read and parse existing settings
$raw = Get-Content $settingsPath -Raw
# Strip JSONC single-line comments (// ...) that sit on their own line,
# block comments (/* ... */), and trailing commas before } or ]
$cleaned = $raw -replace '(?m)^\s*//.*$', ''
$cleaned = $cleaned -replace '/\*[\s\S]*?\*/', ''
$cleaned = $cleaned -replace ',(\s*[}\]])', '$1'
$settings = $cleaned | ConvertFrom-Json
# --- Detect OneDrive availability ---
# When both Consumer and Commercial are present, prompt the user to choose.
# Otherwise pick whichever is available.
$oneDriveCandidates = [ordered]@{}
if ($env:OneDriveConsumer -and (Test-Path $env:OneDriveConsumer)) {
$oneDriveCandidates['Consumer'] = $env:OneDriveConsumer
}
if ($env:OneDriveCommercial -and (Test-Path $env:OneDriveCommercial)) {
$oneDriveCandidates['Commercial'] = $env:OneDriveCommercial
}
if ($oneDriveCandidates.Count -gt 1) {
Write-Host 'Multiple OneDrive accounts detected:'
$index = 1
$choices = @()
foreach ($key in $oneDriveCandidates.Keys) {
$choices += $key
Write-Host " [$index] $key - $($oneDriveCandidates[$key])"
$index++
}
do {
$selection = Read-Host "Select OneDrive account (1-$($choices.Count))"
} while ($selection -notmatch '^\d+$' -or [int]$selection -lt 1 -or [int]$selection -gt $choices.Count)
$selectedKey = $choices[[int]$selection - 1]
$oneDriveRoot = $oneDriveCandidates[$selectedKey]
Write-Host "Using OneDrive ($selectedKey): $oneDriveRoot"
} elseif ($oneDriveCandidates.Count -eq 1) {
$oneDriveRoot = $oneDriveCandidates.Values | Select-Object -First 1
} elseif ($env:OneDrive -and (Test-Path $env:OneDrive)) {
$oneDriveRoot = $env:OneDrive
} else {
$defaultOneDrivePath = Join-Path $userHome 'OneDrive'
if (Test-Path $defaultOneDrivePath) {
$oneDriveRoot = $defaultOneDrivePath
} else {
$oneDriveRoot = $null
}
}
# --- File location strategy ---
# Prefer OneDrive when available so a single synced copy serves every machine.
# Fall back to ~/<repoName> only when OneDrive is not installed. Discovery for
# agents, instructions, and skills is wired up later via NTFS junctions under
# $env:USERPROFILE\.copilot, which the VS Code Copilot chat extension and the
# GitHub Copilot CLI both auto-discover. Prompts are the exception: VS Code
# Copilot Chat reads them from %APPDATA%\Code\User\prompts plus any path in
# `chat.promptFilesLocations`, and does NOT auto-discover ~/.copilot/prompts
# (only the CLI does), so that single setting is still written below.
if ($oneDriveRoot) {
Write-Host "OneDrive detected at: $oneDriveRoot - target tree will live there."
} else {
Write-Host "OneDrive not found - target tree will live under ~/$repoName."
}
# Remove aliases written by setup versions that predate ~/.copilot discovery.
# Unrelated locations remain available to the user.
$legacyLocationMap = [ordered]@{
'chat.agentFilesLocations' = 'Agents'
'chat.instructionsFilesLocations' = 'Instructions'
'chat.agentSkillsLocations' = 'Skills'
'chat.promptFilesLocations' = 'Prompts'
}
foreach ($location in $legacyLocationMap.GetEnumerator()) {
$legacyEntries = @(
"~/$repoName/$($location.Value)"
"~/OneDrive/$repoName/$($location.Value)"
)
$removeLocationSettingEntry = @{
Settings = $settings
PropertyName = $location.Key
Entry = $legacyEntries
}
Remove-LocationSettingEntry @removeLocationSettingEntry
}
# --- Feature flags ---
$settings | Add-Member -NotePropertyName 'chat.includeApplyingInstructions' -NotePropertyValue $true -Force
$settings | Add-Member -NotePropertyName 'chat.includeReferencedInstructions' -NotePropertyValue $true -Force
# --- GitLens AI model ---
# Claude Opus 4.8 is the current Copilot release, superseding Opus 4.7
# (which replaced Opus 4.5 / 4.6; Opus 4.6 Fast was retired April 10, 2026).
$settings | Add-Member -NotePropertyName 'gitlens.ai.vscode.model' -NotePropertyValue 'copilot:claude-opus-4.8' -Force
# --- Copilot completions model ---
$settings | Add-Member -NotePropertyName 'github.copilot.advanced.model' -NotePropertyValue 'claude-opus-4.8' -Force
# --- Copilot chat enhancements ---
$settings | Add-Member -NotePropertyName 'github.copilot.chat.agent.thinkingTool' -NotePropertyValue $true -Force
$settings | Add-Member -NotePropertyName 'github.copilot.chat.search.semanticTextResults' -NotePropertyValue $true -Force
# --- Copilot request limits ---
$settings | Add-Member -NotePropertyName 'github.copilot.chat.agent.maxRequests' -NotePropertyValue 500 -Force
# --- Prompt-file discovery for VS Code Copilot Chat ---
# Unlike agents/instructions/skills, the chat extension does not auto-discover
# ~/.copilot/prompts as a well-known path - it only reads from the per-profile
# %APPDATA%\Code\User\prompts folder plus paths listed in this setting.
# Pointing it at the same junction the CLI uses keeps both surfaces in sync.
# Merge (do not overwrite) so any user-added prompt locations are preserved.
Merge-LocationSetting -Settings $settings -PropertyName 'chat.promptFilesLocations' -NewEntries @{
'~/.copilot/prompts' = $true
}
# Write back
$settings | ConvertTo-Json -Depth 10 | Set-Content $settingsPath -Encoding UTF8
# --- Clear and recreate the chosen target subdirectories, then copy files ---
# Only one location is populated: OneDrive when available, otherwise ~/<repoName>.
# A stale local copy from a previous run is removed when OneDrive is now used.
$subDirs = @('Agents', 'Instructions', 'Skills', 'Prompts')
if ($oneDriveRoot) {
$targetBase = Join-Path $oneDriveRoot $repoName
# Clean up legacy ~/<repoName> tree from earlier dual-copy runs.
$legacyLocalBase = Join-Path $userHome $repoName
if (Test-Path $legacyLocalBase) {
Remove-Item -Path $legacyLocalBase -Recurse -Force
Write-Host "Removed legacy local copy: $legacyLocalBase"
}
} else {
$targetBase = Join-Path $userHome $repoName
}
foreach ($sub in $subDirs) {
$dest = Join-Path $targetBase $sub
if (Test-Path $dest) {
Remove-Item -Path $dest -Recurse -Force
Write-Host "Cleared: $dest"
}
New-Item -ItemType Directory -Path $dest -Force | Out-Null
Write-Host "Created: $dest"
$source = Join-Path $repoRoot $sub
if (Test-Path $source) {
$sourceContents = Join-Path $source '*'
Copy-Item -Path $sourceContents -Destination $dest -Recurse -Force
Write-Host "Copied: $source -> $dest"
} else {
Write-Host "Skipped: $source (not found in repo)"
}
}
# --- Create ~/.copilot/{agents,instructions,skills,prompts} junctions ---
# Both the VS Code Copilot chat extension and the GitHub Copilot CLI discover
# customization files under ~/.copilot. Pointing those well-known
# folders at our single target tree (OneDrive or local fallback) keeps both
# clients in sync without writing chat.*FilesLocations settings.
#
# Behaviour for each link path:
# - Already a junction/symlink -> remove and recreate at the current target.
# - Real directory and empty -> remove silently.
# - Real directory, non-empty -> prompt the user. On consent, copy contents
# into the target (merge, no overwrite of newer files in the target) and
# then remove. On refusal, skip the junction with a warning.
# - Missing -> just create the junction or symbolic link.
$copilotRoot = Join-Path $userHome '.copilot'
if (-not (Test-Path $copilotRoot)) {
New-Item -ItemType Directory -Path $copilotRoot -Force | Out-Null
Write-Host "Created: $copilotRoot"
}
$linkItemType = if ($isWindowsPlatform) { 'Junction' } else { 'SymbolicLink' }
# Map repo subfolder (PascalCase) -> well-known .copilot link name (lowercase).
$junctionMap = [ordered]@{
'Agents' = 'agents'
'Instructions' = 'instructions'
'Skills' = 'skills'
'Prompts' = 'prompts'
}
foreach ($entry in $junctionMap.GetEnumerator()) {
$linkPath = Join-Path $copilotRoot $entry.Value
$targetPath = Join-Path $targetBase $entry.Key
if (-not (Test-Path $targetPath)) {
Write-Host "Skipped junction: target missing - $targetPath"
continue
}
if (Test-Path $linkPath) {
$item = Get-Item -LiteralPath $linkPath -Force
$isLink = $item.Attributes.HasFlag([IO.FileAttributes]::ReparsePoint)
if ($isLink) {
# Stale or correct junction: remove and recreate so it always
# points at the current $targetPath.
try {
[IO.Directory]::Delete($linkPath)
} catch {
Remove-Item -LiteralPath $linkPath -Force -Recurse
}
Write-Host "Removed existing junction: $linkPath"
} else {
# Real directory. Check if it has any content.
$children = Get-ChildItem -LiteralPath $linkPath -Force -ErrorAction SilentlyContinue
if (-not $children) {
Remove-Item -LiteralPath $linkPath -Force
Write-Host "Removed empty directory: $linkPath"
} else {
Write-Host ""
Write-Host "Directory '$linkPath' is not empty ($($children.Count) item(s))."
Write-Host "It must be replaced with a junction to '$targetPath'."
$answer = Read-Host 'Copy its contents into the target and then delete it? [y/N]'
if ($answer -match '^(y|yes)$') {
# Merge into target without clobbering newer files already there.
foreach ($child in $children) {
$destChild = Join-Path $targetPath $child.Name
if (Test-Path -LiteralPath $destChild) {
Write-Host " Skip (already present in target): $($child.Name)"
continue
}
Copy-Item -LiteralPath $child.FullName -Destination $destChild -Recurse -Force
Write-Host " Copied: $($child.Name) -> $targetPath"
}
Remove-Item -LiteralPath $linkPath -Recurse -Force
Write-Host "Removed: $linkPath"
} else {
Write-Host "Skipped junction: user declined to remove '$linkPath'."
continue
}
}
}
}
New-Item -ItemType $linkItemType -Path $linkPath -Target $targetPath | Out-Null
Write-Host "${linkItemType}: $linkPath -> $targetPath"
}
# --- Set environment variable required by the GitHub Copilot CLI ---
# `gh copilot` consults COPILOT_ALLOW_ALL=1 to bypass the per-tool confirmation
# prompts that otherwise block non-interactive use of the custom agents and
# skills shipped from this repo. Persisted at User scope so every new shell
# session picks it up automatically; the current process variable is also set
# so the change is visible without opening a new shell.
$copilotEnvName = 'COPILOT_ALLOW_ALL'
$copilotEnvValue = '1'
if ($SkipCopilotCliEnvironment) {
Write-Verbose "Skipped environment variable: $copilotEnvName (requested)"
} else {
$existingValue = [Environment]::GetEnvironmentVariable($copilotEnvName, 'User')
if ($existingValue -eq $copilotEnvValue) {
Write-Host "Environment variable already set: $copilotEnvName=$copilotEnvValue (User)"
} else {
[Environment]::SetEnvironmentVariable($copilotEnvName, $copilotEnvValue, 'User')
Write-Host "Environment variable set: $copilotEnvName=$copilotEnvValue (User)"
Write-Host " Open a new shell to pick up the change in other sessions."
}
[Environment]::SetEnvironmentVariable($copilotEnvName, $copilotEnvValue, 'Process')
}
# --- Merge keybindings into %APPDATA%\Code\User\keybindings.json ---
# Idempotent: match on (key, command, when) tuple so re-runs do not duplicate
# entries and user-added bindings are preserved. Creates a timestamped backup
# before writing.
$keybindingsSource = Join-Path (Join-Path $repoRoot 'Keybindings') 'keybindings.json'
$keybindingsPath = Join-Path $settingsDir 'keybindings.json'
if (Test-Path $keybindingsSource) {
if (-not (Test-Path $keybindingsPath)) {
Write-Host "VS Code keybindings file not found at $keybindingsPath - creating a new one."
'[]' | Set-Content -Path $keybindingsPath -Encoding UTF8
} else {
$kbBackup = "$keybindingsPath.$timestamp.bak"
Copy-Item -Path $keybindingsPath -Destination $kbBackup -Force
Write-Host "Backup created: $kbBackup"
}
# Parse existing bindings (JSONC-tolerant: strip // and /* */ comments and trailing commas)
$kbRaw = Get-Content $keybindingsPath -Raw
$kbCleaned = $kbRaw -replace '(?m)^\s*//.*$', ''
$kbCleaned = $kbCleaned -replace '/\*[\s\S]*?\*/', ''
$kbCleaned = $kbCleaned -replace ',(\s*[}\]])', '$1'
if ([string]::IsNullOrWhiteSpace($kbCleaned)) { $kbCleaned = '[]' }
$existingBindings = @($kbCleaned | ConvertFrom-Json)
# Parse desired bindings from the repo
$desiredRaw = Get-Content $keybindingsSource -Raw
$desiredCleaned = $desiredRaw -replace '(?m)^\s*//.*$', ''
$desiredCleaned = $desiredCleaned -replace '/\*[\s\S]*?\*/', ''
$desiredCleaned = $desiredCleaned -replace ',(\s*[}\]])', '$1'
$desiredBindings = @($desiredCleaned | ConvertFrom-Json)
# Build a tuple key for deduplication
function Get-BindingKey {
param($Binding)
$k = if ($Binding.PSObject.Properties['key']) { [string]$Binding.key } else { '' }
$c = if ($Binding.PSObject.Properties['command']) { [string]$Binding.command } else { '' }
$w = if ($Binding.PSObject.Properties['when']) { [string]$Binding.when } else { '' }
"$k|$c|$w"
}
$desiredKeys = @{}
foreach ($b in $desiredBindings) { $desiredKeys[(Get-BindingKey $b)] = $true }
# Keep every existing binding that is not one of ours, then append ours.
# This removes stale copies of our bindings (e.g. after we update the "when"
# clause) and avoids duplicates.
$kept = @($existingBindings | Where-Object { -not $desiredKeys.ContainsKey((Get-BindingKey $_)) })
$merged = @($kept) + @($desiredBindings)
$merged | ConvertTo-Json -Depth 10 | Set-Content $keybindingsPath -Encoding UTF8
Write-Host "Keybindings merged: $($desiredBindings.Count) bindings from repo, $($kept.Count) user bindings preserved."
} else {
Write-Host "Skipped keybindings merge: $keybindingsSource not found."
}
Write-Host "`nSettings updated at: $settingsPath"
Write-Host "Restart VS Code to apply changes."