-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmulti-cli.ps1
More file actions
2012 lines (1859 loc) · 90.1 KB
/
Copy pathmulti-cli.ps1
File metadata and controls
2012 lines (1859 loc) · 90.1 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
<#
.SYNOPSIS
multi-cli.ps1 -- Run multiple sandboxed profiles of supported CLIs, IDEs, and GUI apps.
.DESCRIPTION
Adapter-driven launcher: each supported tool ships an adapter.json describing
how to find its binary and how to isolate its state. multi-cli reads the
adapter and applies its isolation strategy: env, userDataDir, redirectHome,
appdata, sandboxUser, or accountOverlay (schema-v2).
USAGE
multi-cli new <tool>/<name> Create a new profile
multi-cli launch <tool>/<name> Launch the profile (binary args after `--`)
multi-cli continue <tool> <src> <dest> Copy a chat session between profiles
multi-cli list List all profiles
multi-cli tools List supported tools and detect installs
multi-cli doctor Diagnose environment
multi-cli help Full command reference
#>
param (
[Parameter(Position = 0, Mandatory = $false)]
[string]$Cmd,
[Parameter(Position = 1, Mandatory = $false)]
[string]$Arg1,
[Parameter(Position = 2, Mandatory = $false)]
[string]$Arg2,
[Alias('i')]
[switch]$WholeRoot,
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]$ForwardArgs
)
$ErrorActionPreference = 'Stop'
$VERSION = '1.0.0'
$UTF8_BOM_BYTES = [byte[]](0xEF, 0xBB, 0xBF)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$MultiCliLauncherPath = $MyInvocation.MyCommand.Definition
$ToolsDir = if ($env:MULTICLI_TOOLS_DIR) { $env:MULTICLI_TOOLS_DIR } else { Join-Path $ScriptDir 'ai-tools' }
$BASE = if ($env:MULTICLI_HOME) { $env:MULTICLI_HOME } else { Join-Path $env:USERPROFILE 'MultiCliProfiles' }
# Locate a lib module next to this launcher, falling back to the tools dir
# parent when MULTICLI_TOOLS_DIR points elsewhere (tests).
function Resolve-MultiCliModulePath {
param([string]$ModuleName)
$modulePath = Join-Path $ScriptDir "lib\$ModuleName"
if (-not (Test-Path -LiteralPath $modulePath)) {
$modulePath = Join-Path (Split-Path -Parent $ToolsDir) "lib\$ModuleName"
}
if (-not (Test-Path -LiteralPath $modulePath)) {
throw "Module '$ModuleName' not found for $ToolsDir. Reinstall multi-cli."
}
return $modulePath
}
# Import the validation/runtime modules once per process; the Get-Command
# guard keeps repeated imports cheap.
function Import-AdapterValidationModule {
if (Get-Command Test-AdapterManifest -ErrorAction SilentlyContinue) { return }
Import-Module (Resolve-MultiCliModulePath 'MultiCli.AdapterValidation.psm1') -Force
}
function Import-RuntimeModule {
if (Get-Command Get-AccountOverlayLaunchPlan -ErrorAction SilentlyContinue) { return }
Import-Module (Resolve-MultiCliModulePath 'MultiCli.Runtime.psm1') -Force
}
# =============================================================================
# Adapter loading
# =============================================================================
# Parse every adapter under the tools dir, warning and skipping invalid ones.
function Get-Adapters {
Import-AdapterValidationModule
if (-not (Test-Path $ToolsDir)) { return @() }
$adapters = @()
foreach ($dir in Get-ChildItem -Directory -Path $ToolsDir) {
$manifest = Join-Path $dir.FullName 'adapter.json'
if (-not (Test-Path $manifest)) { continue }
$validationErrors = @(Test-AdapterManifest -ManifestPath $manifest -ExpectedId $dir.Name)
if ($validationErrors.Count -gt 0) {
Write-Warning "Invalid adapter '$($dir.Name)': $($validationErrors -join '; ')"
continue
}
$adapters += (Get-Content $manifest -Raw | ConvertFrom-Json)
}
return $adapters
}
# Parse one adapter by id; throws for unknown ids and invalid manifests.
# Every command that touches adapter data goes through this first.
function Get-Adapter {
param([string]$ToolId)
Test-ToolId $ToolId
Import-AdapterValidationModule
$manifest = Join-Path (Join-Path $ToolsDir $ToolId) 'adapter.json'
if (-not (Test-Path $manifest)) { throw "Unknown tool '$ToolId'. Run: multi-cli tools" }
$validationErrors = @(Test-AdapterManifest -ManifestPath $manifest -ExpectedId $ToolId)
if ($validationErrors.Count -gt 0) {
throw "Invalid adapter '$ToolId': $($validationErrors -join '; ')"
}
return Get-Content $manifest -Raw | ConvertFrom-Json
}
# Expand the path tokens adapters use for per-OS roots: $HOME and %VARS%.
function Resolve-PathToken {
param([string]$Path)
if (-not $Path) { return $Path }
$expanded = $Path -replace '\$HOME', $env:USERPROFILE.Replace('\', '\\')
return [Environment]::ExpandEnvironmentVariables($expanded)
}
# First binary candidate that exists (path or PATH lookup); $null when none
# resolve. MULTICLI_OVERRIDE_BINARY wins.
function Test-UriProtocol {
param([string]$Scheme)
$key = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey($Scheme)
if ($null -eq $key) { return $false }
try {
if ($null -eq $key.GetValue('URL Protocol', $null)) { return $false }
$command = $key.OpenSubKey('shell\open\command')
if ($null -eq $command) { return $false }
try { return -not [string]::IsNullOrWhiteSpace([string]$command.GetValue('')) } finally { $command.Dispose() }
} finally { $key.Dispose() }
}
function Test-UriBinary {
param([string]$Binary)
return ($Binary -match '(?i)[\\/]explorer\.exe$')
}
function Get-AppxAdapterBinary {
param([string]$PackageTarget)
if ($PackageTarget -notmatch '^([^!]+)!(.+)$') { return $null }
$packageName = $Matches[1]
$applicationId = $Matches[2]
$package = Get-AppxPackage -Name $packageName -PackageTypeFilter Main -ErrorAction SilentlyContinue |
Where-Object { $_.SignatureKind -eq 'Store' } |
Sort-Object Version -Descending |
Select-Object -First 1
if ($null -eq $package) { return $null }
$manifest = Get-AppxPackageManifest -Package $package
$application = @($manifest.Package.Applications.Application) |
Where-Object { $_.Id -eq $applicationId } | Select-Object -First 1
if ($null -eq $application) { return $null }
return "appx:$($package.PackageFamilyName)!$applicationId"
}
function Find-AdapterBinary {
param($Adapter)
if ($env:MULTICLI_OVERRIDE_BINARY) { return $env:MULTICLI_OVERRIDE_BINARY }
$candidates = @()
if ($Adapter.binary.windows) { $candidates += $Adapter.binary.windows }
foreach ($candidate in $candidates) {
if ($candidate -like 'appx:*') {
$appxBinary = Get-AppxAdapterBinary -PackageTarget $candidate.Substring(5)
if ($appxBinary) { return $appxBinary }
continue
}
if ($candidate -like 'uri:*') {
$scheme = $candidate.Substring(4)
if (Test-UriProtocol -Scheme $scheme) { return (Get-Command explorer.exe).Source }
continue
}
$resolved = Resolve-PathToken $candidate
if (Test-Path $resolved -ErrorAction SilentlyContinue) { return $resolved }
$command = Get-Command $resolved -ErrorAction SilentlyContinue
if ($command) { return $command.Source }
}
return $null
}
# =============================================================================
# Session continuation
# =============================================================================
$SESSION_RESERVED_ENDPOINT = 'base'
# Skip automatic session seeding when the base state exceeds this size.
$SEED_MAX_BYTES = 500 * 1024 * 1024
# Null-safe PSObject property getter: adapters arrive from ConvertFrom-Json,
# so an absent section is a missing property rather than a null-valued one.
function Get-ObjectPropertySafe {
param($Object, [string]$Name)
if ($null -eq $Object) { return $null }
$property = $Object.PSObject.Properties[$Name]
if ($property) { return $property.Value }
return $null
}
function Test-AdapterNeedsOsUser {
param($Adapter)
$account = Get-ObjectPropertySafe -Object $Adapter -Name 'account'
return (Get-ObjectPropertySafe -Object $account -Name 'mechanism') -eq 'osUserCredentialStore'
}
function Get-AdapterSystemHome {
param($Adapter)
if ((Get-ObjectPropertySafe -Object $Adapter -Name 'schemaVersion') -eq 2) {
$normalState = Get-ObjectPropertySafe -Object $Adapter -Name 'normalState'
$roots = Get-ObjectPropertySafe -Object $normalState -Name 'root'
$root = Get-ObjectPropertySafe -Object $roots -Name 'windows'
if (-not $root) { return $null }
return [System.IO.Path]::GetFullPath((Resolve-PathToken $root))
}
if ($Adapter.share -and $Adapter.share.systemHome) {
return [System.IO.Path]::GetFullPath((Resolve-PathToken $Adapter.share.systemHome))
}
return $null
}
function Resolve-SessionEndpoint {
param($Adapter, [string]$Tool, [string]$Name)
if ($Name -eq $SESSION_RESERVED_ENDPOINT) {
$sysHome = Get-AdapterSystemHome $Adapter
if (-not $sysHome) { throw "Tool '$Tool' has no system home; 'base' endpoint unavailable" }
return $sysHome
}
Test-ProfileName $Name
return Get-ProfileDir $Tool $Name
}
# Throw if an adapter-declared relative path is unsafe to join under a root:
# absolute, drive-qualified, or containing a '..' component.
function Assert-RelPathSafe {
param([string]$Path, [string]$Kind, [string]$ToolId)
if (-not $Path) { return }
$norm = $Path -replace '\\', '/'
if ($norm -match '^/' -or $norm -match '^[a-zA-Z]:') {
throw "Adapter bug: $Kind '$Path' is absolute/drive-qualified for '$ToolId'."
}
if ("/$norm/" -match '/\.\./') {
throw "Adapter bug: $Kind '$Path' contains '..' for '$ToolId'."
}
}
function Test-SessionAdapterBug {
param($Adapter)
$paths = @($Adapter.session.paths)
$creds = @($Adapter.session.credentials)
foreach ($cred in $creds) {
Assert-RelPathSafe -Path $cred -Kind 'credential' -ToolId $Adapter.id
}
foreach ($path in $paths) {
if (-not $path) { continue }
Assert-RelPathSafe -Path $path -Kind 'session path' -ToolId $Adapter.id
$normPath = ($path -replace '\\', '/').TrimEnd('/')
foreach ($cred in $creds) {
if (-not $cred) { continue }
$normCred = ($cred -replace '\\', '/').TrimEnd('/')
if ($normPath -eq $normCred -or
$normPath -like "$normCred/*" -or
$normCred -like "$normPath/*") {
throw "Adapter bug: session path '$path' overlaps credential '$cred' for '$($Adapter.id)'. Refusing to copy credentials."
}
}
}
}
# True if any component of the dest-relative path matches a credential entry
# name, blocking files nested inside a credential-named directory.
function Test-IsCredentialName {
param([string]$RelativePath, [string[]]$Credentials)
$components = ($RelativePath -replace '\\', '/').Split('/') | Where-Object { $_ }
foreach ($comp in $components) {
foreach ($cred in $Credentials) {
if (-not $cred) { continue }
$credLeaf = Split-Path ($cred -replace '/', '\') -Leaf
if ($comp -eq $credLeaf) { return $true }
}
}
return $false
}
# True when a filesystem item is a symlink/junction/reparse point.
function Test-IsReparsePoint {
param($Item)
if ($Item.LinkType) { return $true }
return (($Item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0)
}
# Return regular files below a session entry without following reparse-point
# directories. An explicit stack is required because Get-ChildItem -Recurse
# traverses nested junctions before their child files can be identified as links.
function Get-SessionFilesNoReparse {
param([string]$Root)
$files = New-Object 'System.Collections.Generic.List[System.IO.FileInfo]'
$stack = New-Object 'System.Collections.Generic.Stack[System.IO.DirectoryInfo]'
$stack.Push((Get-Item -LiteralPath $Root -Force))
while ($stack.Count -gt 0) {
$directory = $stack.Pop()
foreach ($item in (Get-ChildItem -LiteralPath $directory.FullName -Force -ErrorAction SilentlyContinue)) {
if (Test-IsReparsePoint $item) { continue }
if ($item.PSIsContainer) { $stack.Push($item); continue }
$files.Add($item)
}
}
return $files
}
# Copy every adapter-declared session entry (file or directory, merged
# per-file). Reparse points are skipped so credential targets never travel;
# Copied/Skipped are ref counters shared across the whole run.
function Copy-SessionEntry {
param(
[string]$Source,
[string]$Destination,
[bool]$NoMerge,
[bool]$DryRun,
[string[]]$Credentials,
[string]$RelativeRoot,
[ref]$Copied,
[ref]$Skipped
)
$srcItem = Get-Item -LiteralPath $Source -Force -ErrorAction SilentlyContinue
if (-not $srcItem -or (Test-IsReparsePoint $srcItem)) { return }
if (-not $srcItem.PSIsContainer) {
Copy-SessionFile -Source $Source -Destination $Destination -NoMerge $NoMerge -DryRun $DryRun -Copied $Copied -Skipped $Skipped
return
}
$sourceRoot = [System.IO.Path]::GetFullPath($Source).TrimEnd('\', '/')
foreach ($item in (Get-SessionFilesNoReparse -Root $sourceRoot)) {
$relative = $item.FullName.Substring($sourceRoot.Length).TrimStart('\', '/')
if (Test-IsCredentialName -RelativePath "$RelativeRoot/$relative" -Credentials $Credentials) { continue }
$target = Join-Path $Destination $relative
Copy-SessionFile -Source $item.FullName -Destination $target -NoMerge $NoMerge -DryRun $DryRun -Copied $Copied -Skipped $Skipped
}
}
# Copy one file atomically (temp in dest dir, then move over) preserving the
# source mtime. Skips when dest is strictly newer, or equal mtime + equal size;
# repairs a truncated dest whose mtime matches but whose size differs.
function Copy-SessionFile {
param(
[string]$Source,
[string]$Destination,
[bool]$NoMerge,
[bool]$DryRun,
[ref]$Copied,
[ref]$Skipped
)
if ((-not $NoMerge) -and (Test-Path -LiteralPath $Destination -PathType Leaf)) {
$src = Get-Item -LiteralPath $Source
$dst = Get-Item -LiteralPath $Destination
if ($dst.LastWriteTimeUtc -gt $src.LastWriteTimeUtc) { $Skipped.Value++; return }
if ($dst.LastWriteTimeUtc -eq $src.LastWriteTimeUtc -and $dst.Length -eq $src.Length) {
$Skipped.Value++; return
}
}
if ($DryRun) {
Write-Host " would copy $Source -> $Destination"
$Copied.Value++
return
}
$parent = Split-Path -Parent $Destination
if ($parent -and -not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
$tmp = Join-Path $parent (".mcli-copy." + [System.IO.Path]::GetRandomFileName())
Copy-Item -LiteralPath $Source -Destination $tmp -Force
(Get-Item -LiteralPath $tmp).LastWriteTimeUtc = (Get-Item -LiteralPath $Source).LastWriteTimeUtc
Move-Item -LiteralPath $tmp -Destination $Destination -Force
$Copied.Value++
}
# Read one redirected line as UTF-8 bytes so BOM handling never depends on the
# host console code page.
function Read-RedirectedLine {
param([IO.Stream]$InputStream = $([Console]::OpenStandardInput()))
$bytes = New-Object 'System.Collections.Generic.List[byte]'
while ($true) {
$value = $InputStream.ReadByte()
if ($value -lt 0 -or $value -eq 10) { break }
if ($value -ne 13) { $bytes.Add([byte]$value) }
}
if ($value -lt 0 -and $bytes.Count -eq 0) { return $null }
$offset = if ($bytes.Count -ge 3 -and
$bytes[0] -eq $UTF8_BOM_BYTES[0] -and
$bytes[1] -eq $UTF8_BOM_BYTES[1] -and
$bytes[2] -eq $UTF8_BOM_BYTES[2]) { 3 } else { 0 }
return (New-Object Text.UTF8Encoding($false, $true)).GetString($bytes.ToArray(), $offset, $bytes.Count - $offset)
}
# multi-cli auth set|status|clear: manage a process-secret profile's
# credential in the OS store, keyed by the profile's stable profileId.
function Invoke-Auth {
param([string]$Action, [string]$Spec)
$profile = Split-ProfileSpec $Spec
$adapter = Get-Adapter $profile.Tool
if ($adapter.account.mechanism -ne 'processSecret') {
throw "Tool '$($profile.Tool)' does not use a process-secret credential."
}
$profileDir = Get-ProfileDir $profile.Tool $profile.Name
$metadataPath = Join-Path $profileDir '.profile.json'
if (-not (Test-Path -LiteralPath $metadataPath)) { throw "Schema-v2 profile '$Spec' does not exist." }
$metadata = Get-Content -LiteralPath $metadataPath -Raw | ConvertFrom-Json
$environmentVariable = $adapter.account.secret.environmentVariable
$target = "multi-cli/$($adapter.id)/$($metadata.profileId)/$environmentVariable"
Import-Module (Resolve-MultiCliModulePath 'MultiCli.CredentialStore.psm1') -Force
switch ($Action) {
'set' {
$plainSecret = $null
if ([Console]::IsInputRedirected) {
$plainSecret = Read-RedirectedLine
if ([string]::IsNullOrEmpty($plainSecret)) { throw 'Credential input was empty.' }
} else {
$secureSecret = Read-Host "Enter $environmentVariable for $Spec" -AsSecureString
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureSecret)
try {
$plainSecret = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer)
} finally {
if ($pointer -ne [IntPtr]::Zero) { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
}
}
try {
Set-MultiCliCredential -Target $target -Secret $plainSecret
} finally {
$plainSecret = $null
}
Write-Host "Stored credential for $Spec."
}
'status' {
$present = Test-MultiCliCredential -Target $target
Write-Host $(if ($present) { "Credential present for $Spec." } else { "No credential stored for $Spec." })
if (-not $present) { exit 1 }
}
'clear' {
Remove-MultiCliCredential -Target $target | Out-Null
Write-Host "Cleared credential for $Spec."
}
default { throw 'Usage: multi-cli auth <set|status|clear> <tool>/<profile>' }
}
}
# Throw if any schema-v2 session path is unsafe or overlaps a declared
# credential -- the same invariant Test-SessionAdapterBug enforces for
# schema-v1 adapters, read from the v2 field names.
function Test-IsolatedSessionAdapterBug {
param($Adapter)
$normalState = Get-ObjectPropertySafe -Object $Adapter -Name 'normalState'
$paths = @($normalState.sessionPaths)
$creds = @($Adapter.account.credentialFiles)
foreach ($cred in $creds) {
Assert-RelPathSafe -Path $cred -Kind 'credential' -ToolId $Adapter.id
}
foreach ($path in $paths) {
if (-not $path) { continue }
Assert-RelPathSafe -Path $path -Kind 'session path' -ToolId $Adapter.id
$normPath = ($path -replace '\\', '/').TrimEnd('/')
foreach ($cred in $creds) {
if (-not $cred) { continue }
$normCred = ($cred -replace '\\', '/').TrimEnd('/')
if ($normPath -eq $normCred -or
$normPath -like "$normCred/*" -or
$normCred -like "$normPath/*") {
throw "Adapter bug: session path '$path' overlaps credential '$cred' for '$($Adapter.id)'. Refusing to copy credentials."
}
}
}
}
# multi-cli continue <tool> <src> <dest>: copy adapter-declared session state
# between endpoints ('base' = the tool's real home). Merge policy keeps the
# newer file; credential paths never travel. Schema-v2 tools already share
# sessions, so this is a no-op message there.
function Invoke-Continue {
param([string]$Tool, [string]$SrcName, [string]$DestName, [bool]$NoMerge = $false, [bool]$DryRun = $false)
if (-not $Tool -or -not $SrcName -or -not $DestName) {
throw "Usage: multi-cli continue <tool> <src-profile> <dest-profile> [--no-merge] [--dry-run]"
}
$adapter = Get-Adapter $Tool
if ((Get-ObjectPropertySafe -Object $adapter -Name 'schemaVersion') -eq 2) {
# Isolated profiles share nothing, so continuation is a real copy
# between them (and 'base'), exactly like legacy endpoints. Shared
# schema-v2 profiles keep the no-op.
if ($SrcName -eq $DestName) { throw "Source and destination must differ" }
$srcDir = Resolve-SessionEndpoint $adapter $Tool $SrcName
$destDir = Resolve-SessionEndpoint $adapter $Tool $DestName
if (-not (Test-Path $srcDir)) {
throw "Source endpoint '$SrcName' not found at $srcDir. Nothing to continue from."
}
if (-not (Test-Path $destDir)) {
throw "Destination profile '$DestName' does not exist. Create it with: multi-cli new $Tool/$DestName"
}
$srcIsolated = Test-Path -LiteralPath (Join-Path $srcDir '.isolated')
$destIsolated = Test-Path -LiteralPath (Join-Path $destDir '.isolated')
if (-not $srcIsolated -and -not $destIsolated) {
Write-Host "$($adapter.displayName) profiles already share conversations through the shared normal state; nothing to continue."
return
}
$normalState = Get-ObjectPropertySafe -Object $adapter -Name 'normalState'
$sessionPaths = @($normalState.sessionPaths)
if ($sessionPaths.Count -eq 0) {
throw "$($adapter.displayName) declares no session paths; nothing to continue."
}
Test-IsolatedSessionAdapterBug $adapter
$sourceState = $srcDir
$destinationState = $destDir
$runtimeSubdir = Get-ObjectPropertySafe -Object $normalState -Name 'runtimeSubdir'
if ($runtimeSubdir) {
$sourceState = Join-Path $srcDir ($runtimeSubdir -replace '/', '\')
$destinationState = Join-Path $destDir ($runtimeSubdir -replace '/', '\')
}
$credentials = @($adapter.account.credentialFiles)
$copied = 0; $skipped = 0; $found = $false
if ($DryRun) { Write-Host "Dry run -- no files will be written." }
foreach ($entry in $sessionPaths) {
if (-not $entry) { continue }
if (Test-IsCredentialName -RelativePath $entry -Credentials $credentials) { continue }
$src = Join-Path $sourceState ($entry -replace '/', '\')
if (-not (Test-Path $src)) { continue }
$found = $true
$dst = Join-Path $destinationState ($entry -replace '/', '\')
$c = [ref]$copied; $s = [ref]$skipped
Copy-SessionEntry -Source $src -Destination $dst -NoMerge $NoMerge -DryRun $DryRun -Credentials $credentials -RelativeRoot $entry -Copied $c -Skipped $s
$copied = $c.Value; $skipped = $s.Value
}
if (-not $found) {
Write-Host "No session data found at source '$SrcName'. Nothing to continue."
return
}
Write-Host "Continued ${Tool}: $SrcName -> $DestName ($copied copied, $skipped skipped (same-or-newer))"
return
}
if (-not $adapter.session -or -not $adapter.session.portable) {
$reason = if ($adapter.session) { $adapter.session.reason } else { '' }
Write-Host "$($adapter.displayName) sessions are not portable: $reason" -ForegroundColor Yellow
exit 1
}
if ($SrcName -eq $DestName) { throw "Source and destination must differ" }
Test-SessionAdapterBug $adapter
$srcDir = Resolve-SessionEndpoint $adapter $Tool $SrcName
$destDir = Resolve-SessionEndpoint $adapter $Tool $DestName
if (-not (Test-Path $srcDir)) {
throw "Source endpoint '$SrcName' not found at $srcDir. Nothing to continue from."
}
if (-not (Test-Path $destDir)) {
throw "Destination profile '$DestName' does not exist. Create it with: multi-cli new $Tool/$DestName"
}
$credentials = @($adapter.session.credentials)
$copied = 0; $skipped = 0; $found = $false
if ($DryRun) { Write-Host "Dry run -- no files will be written." }
foreach ($entry in @($adapter.session.paths)) {
if (-not $entry) { continue }
if (Test-IsCredentialName -RelativePath $entry -Credentials $credentials) { continue }
$src = Join-Path $srcDir ($entry -replace '/', '\')
if (-not (Test-Path $src)) { continue }
$found = $true
$dst = Join-Path $destDir ($entry -replace '/', '\')
$c = [ref]$copied; $s = [ref]$skipped
Copy-SessionEntry -Source $src -Destination $dst -NoMerge $NoMerge -DryRun $DryRun -Credentials $credentials -RelativeRoot $entry -Copied $c -Skipped $s
$copied = $c.Value; $skipped = $s.Value
}
if (-not $found) {
Write-Host "No session data found at source '$SrcName'. Nothing to continue."
exit 0
}
Write-Host "Continued ${Tool}: $SrcName -> $DestName ($copied copied, $skipped skipped (same-or-newer))"
if ($adapter.session.resumeHint) { Write-Host $adapter.session.resumeHint }
}
# Total size in bytes of the adapter-declared session paths under a root.
function Get-SessionStateSize {
param($Adapter, [string]$Root)
$total = 0
foreach ($entry in @($Adapter.session.paths)) {
if (-not $entry) { continue }
$path = Join-Path $Root ($entry -replace '/', '\')
$item = Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue
if (-not $item -or (Test-IsReparsePoint $item)) { continue }
$files = if ($item.PSIsContainer) { Get-SessionFilesNoReparse -Root $path } else { @($item) }
$sum = ($files | Measure-Object -Property Length -Sum).Sum
if ($sum) { $total += $sum }
}
return $total
}
# Seed session state from base into a new profile, with a size guard above the
# threshold and a progress line for big-but-allowed copies. Returns copied count.
function Initialize-SessionSeed {
param($Adapter, [string]$SysHome, [string]$ProfileDir)
Test-SessionAdapterBug $Adapter
$bytes = Get-SessionStateSize -Adapter $Adapter -Root $SysHome
if ($bytes -gt $SEED_MAX_BYTES) {
$name = Split-Path $ProfileDir -Leaf
Write-Host "base session state is $(Format-Bytes $bytes); skipped automatic copy -- run: multi-cli continue $($Adapter.id) base $name"
return 0
}
$credentials = @($Adapter.session.credentials)
$copied = 0; $skipped = 0
foreach ($entry in @($Adapter.session.paths)) {
if (-not $entry) { continue }
if (Test-IsCredentialName -RelativePath $entry -Credentials $credentials) { continue }
$src = Join-Path $SysHome ($entry -replace '/', '\')
if (-not (Test-Path $src)) { continue }
$dst = Join-Path $ProfileDir ($entry -replace '/', '\')
$c = [ref]$copied; $s = [ref]$skipped
Copy-SessionEntry -Source $src -Destination $dst -NoMerge $false -DryRun $false -Credentials $credentials -RelativeRoot $entry -Copied $c -Skipped $s
$copied = $c.Value; $skipped = $s.Value
}
if ($copied -gt 0) { Write-Host "seeding $copied session file(s) from base" }
return $copied
}
function Initialize-ProfileSeed {
param($Adapter, [string]$ProfileDir, [bool]$Shared)
$sysHome = Get-AdapterSystemHome $Adapter
$seeded = @()
if ($Adapter.session -and $Adapter.session.portable -and $sysHome -and (Test-Path $sysHome)) {
$copied = Initialize-SessionSeed -Adapter $Adapter -SysHome $sysHome -ProfileDir $ProfileDir
if ($copied -gt 0) { $seeded += "$copied session file(s)" }
}
if (-not $Shared -and $Adapter.share -and $sysHome -and (Test-Path $sysHome)) {
$assets = 0
foreach ($entry in @($Adapter.share.linkable)) {
if (-not $entry) { continue }
$src = Join-Path $sysHome $entry
$dst = Join-Path $ProfileDir $entry
if ((Test-Path $src) -and (-not (Test-Path $dst))) {
Copy-Item -Path $src -Destination $dst -Recurse -Force -ErrorAction SilentlyContinue
$assets++
}
}
if ($assets -gt 0) { $seeded += "$assets shared asset(s)" }
}
if ($seeded.Count -gt 0) {
Write-Host "Seeded from base: $($seeded -join ', ')."
}
}
# =============================================================================
# Profile addressing
# =============================================================================
# Parse <tool>/<name> into an object; throws on any other shape. Name
# validation is a separate step (Test-ProfileName).
function Split-ProfileSpec {
param([string]$Spec)
if (-not $Spec) { throw "Profile required: <tool>/<name>" }
if ($Spec -notmatch '/') { throw "Profile must be in form <tool>/<name>. Got: '$Spec'" }
$parts = $Spec.Split('/', 2)
Test-ToolId $parts[0]
return [pscustomobject]@{ Tool = $parts[0]; Name = $parts[1] }
}
# Throw unless $ToolId is a safe adapter id: alnum start, then alnum or
# hyphen. This blocks traversal before adapter/profile paths are joined.
function Test-ToolId {
param([string]$ToolId)
if ([string]::IsNullOrWhiteSpace($ToolId)) { throw 'Tool id required' }
if ($ToolId -notmatch '^[a-zA-Z0-9][a-zA-Z0-9-]*$') {
throw "Tool id '$ToolId' invalid: must start with alphanumeric, contain only letters/numbers/hyphens"
}
}
# Throw unless $Name is a safe profile/template name: alnum start, then alnum
# or hyphen. This is what keeps profile specs inside the storage root.
function Test-ProfileName {
param([string]$Name)
if ([string]::IsNullOrWhiteSpace($Name)) { throw "Profile name required" }
if ($Name -notmatch '^[a-zA-Z0-9][a-zA-Z0-9-]*$') {
throw "Profile name '$Name' invalid: must start with alphanumeric, contain only letters/numbers/hyphens"
}
}
function Get-StorageCanonical {
param([string]$Path)
return ([System.IO.Path]::GetFullPath($Path)).TrimEnd('\', '/')
}
function Test-StoragePathWithin {
param([string]$Child, [string]$Root)
if (-not $Root) { return $false }
$prefix = $Root.TrimEnd('\', '/') + '\'
return ($Child.TrimEnd('\', '/') + '\').StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)
}
function Get-StorageLinkInfo {
param([string]$Path)
$item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
if ($null -eq $item) { return $null }
$linkType = Get-ObjectPropertySafe -Object $item -Name 'LinkType'
if ($linkType -ne 'Junction' -and $linkType -ne 'SymbolicLink' -and $linkType -ne 'HardLink') { return $null }
$target = @((Get-ObjectPropertySafe -Object $item -Name 'Target'))[0]
if (-not $target) { return $null }
return [pscustomobject]@{ Item = $item; LinkType = $linkType; Target = $target }
}
function Get-StorageLinkTarget {
param([string]$Path)
$link = Get-StorageLinkInfo -Path $Path
if ($null -eq $link) { return $null }
$target = $link.Target
if (-not [System.IO.Path]::IsPathRooted($target)) {
$target = Join-Path (Split-Path -Parent $Path) $target
}
return Get-StorageCanonical -Path $target
}
function Assert-StoragePathSafe {
param([string]$Path, [string]$Label)
$baseCanonical = Get-StorageCanonical -Path $BASE
$candidateCanonical = Get-StorageCanonical -Path $Path
if (-not (Test-StoragePathWithin -Child $candidateCanonical -Root $baseCanonical)) {
throw "Refusing to access $Label outside MULTICLI_HOME: '$candidateCanonical'."
}
if ($candidateCanonical.Length -le $baseCanonical.Length) { return }
$relative = $candidateCanonical.Substring($baseCanonical.Length).TrimStart('\', '/')
if (-not $relative) { return }
$current = $baseCanonical
foreach ($segment in ($relative -split '[\\/]')) {
if (-not $segment) { continue }
$current = Join-Path $current $segment
if (-not (Test-Path -LiteralPath $current)) { break }
$target = Get-StorageLinkTarget -Path $current
if ($null -eq $target) { continue }
if (-not (Test-StoragePathWithin -Child $target -Root $baseCanonical)) {
throw "Refusing to access $Label because '$current' resolves outside MULTICLI_HOME."
}
}
}
function Resolve-StoragePath {
param([string]$Label, [string[]]$Segments)
$path = $BASE
foreach ($segment in @($Segments)) {
if ([string]::IsNullOrEmpty($segment)) { continue }
$path = Join-Path $path $segment
}
Assert-StoragePathSafe -Path $path -Label $Label
return $path
}
function Get-ProfileDir {
param([string]$Tool,[string]$Name)
Test-ToolId $Tool
Test-ProfileName $Name
return Resolve-StoragePath -Label "profile '$Tool/$Name'" -Segments @($Tool, $Name)
}
function Get-ToolProfilesDir {
param([string]$Tool)
Test-ToolId $Tool
return Resolve-StoragePath -Label "profile root for '$Tool'" -Segments @($Tool)
}
function Get-AliasDir { Resolve-StoragePath -Label 'alias directory' -Segments @('bin') }
function Get-TemplatesDir { Resolve-StoragePath -Label 'template root' -Segments @('.templates') }
function Throw-LegacyTransferBlocked {
param([string]$Action, [string]$Spec)
throw "Cannot $Action '$Spec': legacy profile transfer is disabled because whole-root copies can leak tokens. Migrate the legacy profile first: multi-cli migrate $Spec"
}
function Throw-LegacyTemplateApplyBlocked {
param([string]$Spec, [string]$TemplateName)
throw "Cannot create '$Spec' from template '$TemplateName': legacy template application is disabled because old on-disk templates can contain credentials. Recreate the template from a migrated schema-v2 profile."
}
function Remove-StorageTreeNoReparse {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) { return }
$item = Get-Item -LiteralPath $Path -Force
$isReparsePoint = ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0
if ($isReparsePoint) {
if ($item.PSIsContainer) {
[System.IO.Directory]::Delete($item.FullName)
} else {
[System.IO.File]::Delete($item.FullName)
}
return
}
if ($item.PSIsContainer) {
foreach ($child in Get-ChildItem -LiteralPath $item.FullName -Force -ErrorAction SilentlyContinue) {
Remove-StorageTreeNoReparse -Path $child.FullName
}
}
Remove-Item -LiteralPath $item.FullName -Force
}
function Copy-StorageTreeNoReparse {
param([string]$Source, [string]$Destination)
if (-not (Test-Path -LiteralPath $Source)) { return }
$item = Get-Item -LiteralPath $Source -Force
if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) {
throw "Cannot clone '$Source': nested reparse points are not supported inside isolated profile state."
}
if ($item.PSIsContainer) {
New-Item -ItemType Directory -Force -Path $Destination | Out-Null
foreach ($child in Get-ChildItem -LiteralPath $item.FullName -Force -ErrorAction SilentlyContinue) {
Copy-StorageTreeNoReparse -Source $child.FullName -Destination (Join-Path $Destination $child.Name)
}
return
}
$parent = Split-Path -Parent $Destination
if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
Copy-Item -LiteralPath $item.FullName -Destination $Destination -Force
}
# =============================================================================
# Profile CRUD
# =============================================================================
# Write .profile.json for any isolated schema-v2 profile atomically. The
# unique profileId keeps lifecycle and optional OS-store credentials distinct.
function Write-IsolatedProfileMetadata {
param($Adapter, [string]$ProfileDir)
$metadata = [ordered]@{
schemaVersion = 2
adapterId = $Adapter.id
profileId = [guid]::NewGuid().ToString()
mode = 'isolated'
}
$temporaryPath = Join-Path $ProfileDir '.profile.json.tmp'
$metadata | ConvertTo-Json | Set-Content -LiteralPath $temporaryPath -Encoding UTF8
Move-Item -LiteralPath $temporaryPath -Destination (Join-Path $ProfileDir '.profile.json') -Force
}
# multi-cli new <tool>/<name>: create the profile dir, seed from base unless
# suppressed, wire schema-v2 runtime metadata when the adapter is
# accountOverlay, then create the alias and (for non-CLI kinds) a shortcut.
function New-Profile {
param([string]$Spec, [bool]$Shared = $false, [bool]$Cli = $false, [string]$FromTemplate = '', [bool]$NoSeed = $false, [bool]$Isolated = $false)
$p = Split-ProfileSpec $Spec
Test-ProfileName $p.Name
$adapter = Get-Adapter $p.Tool
$profileDir = Get-ProfileDir $p.Tool $p.Name
if ($Shared -and $Isolated) { throw '--shared and --isolated are mutually exclusive: choose one profile mode.' }
if ($Isolated -and (Test-AdapterNeedsOsUser -Adapter $adapter)) {
throw "Adapter '$($adapter.id)' cannot use --isolated because folder redirection does not isolate Windows Credential Manager."
}
if ($Isolated -and $adapter.isolation.strategy -ne 'accountOverlay') {
throw "--isolated applies to schema-v2 (accountOverlay) adapters; '$($p.Tool)' uses '$($adapter.isolation.strategy)', which already isolates the whole root per profile."
}
if (Test-Path $profileDir) { throw "Profile '$Spec' already exists" }
New-Item -ItemType Directory -Force -Path (Get-ToolProfilesDir $p.Tool) | Out-Null
if ($FromTemplate) {
$tplDir = Join-Path (Get-TemplatesDir) $FromTemplate
if (-not (Test-Path $tplDir)) { throw "Template '$FromTemplate' not found" }
if ($adapter.isolation.strategy -eq 'accountOverlay') {
Import-Module (Resolve-MultiCliModulePath 'MultiCli.Transfer.psm1') -Force
# Validation runs before creating the profile, then payload files go
# to the state location the selected mode actually launches.
[void](Assert-TransferTemplateCompatible -TemplateDir $tplDir -Adapter $adapter)
New-Item -ItemType Directory -Force -Path $profileDir | Out-Null
Apply-MultiCliTemplate -TemplateDir $tplDir -Adapter $adapter -ProfileDir $profileDir -Isolated:$Isolated
} else {
Throw-LegacyTemplateApplyBlocked -Spec $Spec -TemplateName $FromTemplate
}
} elseif ($Shared) {
New-SharedProfile -Adapter $adapter -ProfileDir $profileDir
} else {
New-Item -ItemType Directory -Force -Path $profileDir | Out-Null
}
if (-not $NoSeed -and -not $FromTemplate -and $adapter.isolation.strategy -ne 'accountOverlay') {
Initialize-ProfileSeed -Adapter $adapter -ProfileDir $profileDir -Shared $Shared
}
if ($Isolated) {
New-Item -ItemType File -Force -Path (Join-Path $profileDir '.isolated') | Out-Null
# Every isolated schema-v2 profile carries a unique profileId. Lifecycle
# operations then stay on the allowlisted transfer path instead of the
# legacy whole-directory clone/export path.
if (-not (Test-Path -LiteralPath (Join-Path $profileDir '.profile.json'))) {
Write-IsolatedProfileMetadata -Adapter $adapter -ProfileDir $profileDir
}
} elseif ($adapter.isolation.strategy -eq 'accountOverlay') {
Import-RuntimeModule
Initialize-RuntimeProfile -Adapter $adapter -ProfileDir $profileDir
}
if ($adapter.isolation.strategy -eq 'redirectHome') {
$homeDir = Join-Path $profileDir '_home'
New-Item -ItemType Directory -Force -Path $homeDir | Out-Null
Set-RedirectHomeDotfileLinks -Adapter $adapter -HomeDir $homeDir
}
if ($Cli) { New-Item -ItemType File -Force -Path (Join-Path $profileDir '.cli') | Out-Null }
New-AliasScript -Tool $p.Tool -Name $p.Name
if (-not $Cli -and $adapter.kind -ne 'cli') {
New-StartMenuShortcut -Tool $p.Tool -Name $p.Name -Adapter $adapter | Out-Null
}
$modeNote = if ($Isolated) { ', isolated' } else { '' }
Write-Host "Created profile $Spec ($($adapter.displayName), strategy=$($adapter.isolation.strategy)$modeNote)"
# Never persist a custom (test/scratch) MULTICLI_HOME into the user's PATH;
# only the default profile root belongs there permanently.
if (-not $env:MULTICLI_HOME -and -not (Test-AliasDirInPath)) {
$aliasDir = Get-AliasDir
$userPath = [Environment]::GetEnvironmentVariable('PATH', 'User')
if ($userPath -notlike "*$aliasDir*") {
[Environment]::SetEnvironmentVariable('PATH', "$aliasDir;$userPath", 'User')
$env:PATH = "$aliasDir;$env:PATH"
Write-Host "Added $aliasDir to user PATH. Restart your terminal to use '$($p.Name)' or '$($p.Tool)-$($p.Name)' as a command."
} else {
Write-Host "$aliasDir is already in PATH."
}
}
}
# A --shared profile links the adapter's share.linkable entries from the
# tool's system home into the profile dir (copy fallback when linking fails).
function New-SharedProfile {
param($Adapter, [string]$ProfileDir)
New-Item -ItemType Directory -Force -Path $ProfileDir | Out-Null
New-Item -ItemType File -Force -Path (Join-Path $ProfileDir '.shared') | Out-Null
if (-not $Adapter.share -or -not $Adapter.share.systemHome) { return }
$sysHome = Resolve-PathToken $Adapter.share.systemHome
if (-not (Test-Path $sysHome)) { return }
foreach ($entry in @($Adapter.share.linkable)) {
if (-not $entry) { continue }
$src = Join-Path $sysHome $entry
$dst = Join-Path $ProfileDir $entry
if ((Test-Path $src) -and (-not (Test-Path $dst))) {
try {
New-Item -ItemType SymbolicLink -Path $dst -Target $src -ErrorAction Stop | Out-Null
} catch {
Write-Warning "Could not symlink $entry (Developer Mode may be required). Falling back to copy."
Copy-Item -Path $src -Destination $dst -Recurse -ErrorAction SilentlyContinue
}
}
}
}
# Link the adapter's shareFromRealHome dotfiles from the real user profile
# into the redirected profile home, leaving existing entries alone.
function Set-RedirectHomeDotfileLinks {
param($Adapter, [string]$HomeDir)
if (-not $Adapter.isolation.shareFromRealHome) { return }
foreach ($entry in @($Adapter.isolation.shareFromRealHome)) {
if (-not $entry) { continue }
$src = Join-Path $env:USERPROFILE $entry
$dst = Join-Path $HomeDir $entry
if ((Test-Path $src) -and (-not (Test-Path $dst))) {
try {
New-Item -ItemType SymbolicLink -Path $dst -Target $src -ErrorAction Stop | Out-Null
} catch {
Write-Warning "Could not symlink shared dotfile $entry."
}
}
}
}
# multi-cli delete: confirm, clear any process-secret credential, then remove
# the profile dir, alias, and shortcut.
function Remove-Profile {
param([string]$Spec)
$p = Split-ProfileSpec $Spec
Test-ProfileName $p.Name
$profileDir = Get-ProfileDir $p.Tool $p.Name
if (-not (Test-Path $profileDir)) { throw "Profile '$Spec' does not exist" }
# Read-Host consults the console on some hosts even when stdin is piped,
# silently returning an empty answer and aborting scripted deletes. Read
# the redirected stream directly so piped confirmations are honored.
if ([Console]::IsInputRedirected) {
Write-Host "Delete profile '$Spec' and all its data? [y/N]"
$confirm = Read-RedirectedLine
} else {
$confirm = Read-Host "Delete profile '$Spec' and all its data? [y/N]"
}
if ($confirm -notmatch '^[Yy]$') { Write-Host "Aborted."; return }
# An OS-user profile owns a sandbox user, optional legacy scheduled tasks,
# and a Credential Manager entry; remove them before deleting the profile dir.
# The helper verifies ownership and is a no-op without a record.
if (Test-Path -LiteralPath (Join-Path $profileDir '.osuser.json')) {
Import-Module (Resolve-MultiCliModulePath 'MultiCli.OsUser.psm1') -Force
Remove-OsUserIsolation -ProfileDir $profileDir
}
# A process-secret profile owns a Credential Manager entry keyed by its
# profileId; delete must not orphan it in the store. A missing adapter
# manifest must not block deleting the profile itself.
$metadataPath = Join-Path $profileDir '.profile.json'
$adapterManifest = Join-Path (Join-Path $ToolsDir $p.Tool) 'adapter.json'
if ((Test-Path -LiteralPath $metadataPath) -and (Test-Path -LiteralPath $adapterManifest)) {
$adapter = Get-Adapter $p.Tool
if ($adapter.account.mechanism -eq 'processSecret') {