-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathinstall.ps1
More file actions
5034 lines (4644 loc) · 224 KB
/
Copy pathinstall.ps1
File metadata and controls
5034 lines (4644 loc) · 224 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
#Requires -Version 5.1
<#
.SYNOPSIS
1c-rules installer (PowerShell channel)
.DESCRIPTION
Implements the same installation protocol as AGENT-INSTALL.md but
deterministically through a CLI. Reads content/ and adapters/*.yaml,
writes per-tool files and a shared .ai-rules.json manifest.
Commands:
init First install (no manifest yet, or force re-init).
update Update installed rules to the current repo version.
add Add rules for an additional tool.
remove Remove rules (optionally only for one tool).
doctor Read-only diagnostic.
eject Delete manifest; leave files in place.
.PARAMETER Command
Command to run. One of: init, update, add, remove, doctor, eject.
.PARAMETER Tool
For `add` / `remove`: the tool id to operate on.
.PARAMETER Tools
For `init` / `update`: explicit list of active tool ids. If omitted,
the script auto-detects and prompts the user.
.PARAMETER Source
Source repository URL or local path. Defaults to the directory where
install.ps1 lives (supports running from a cloned repo directly).
A URL value (https://..., git@host:..., or path ending with .git) is
shallow-cloned into a deterministic cache directory under $env:TEMP
(key derived from the URL hash) and reused on subsequent runs. Requires
'git' on PATH when a URL is supplied.
.PARAMETER NonInteractive
Do not prompt. Use defaults: accept detected tools, skip collisions,
keep user-modified files on conflict.
.PARAMETER AssumeYes
Answer "yes" to confirmation prompts (but still pause on destructive
conflicts — those require -NonInteractive to auto-resolve).
.PARAMETER Force
For `update`: overwrite user-modified files with the current shipped
version ("take theirs") instead of keeping the user's edits. Without
-ForcePaths this applies to every drifted file; combine with -ForcePaths
to force only specific files. Applies uniformly to artefact files, the
MCP config, the `entry` file (CLAUDE.md), and skill files.
.PARAMETER ForcePaths
For `update`: restrict -Force to the listed project-relative paths
(exact match or `*` wildcard, e.g. `.claude/rules-1c/tooling-playbooks.md`
or `.claude/skills/*`). Implies -Force for the matching paths only; all
other drifted files keep the user's edits. Multiple paths are passed
COMMA-separated (PowerShell array syntax):
`-ForcePaths .claude/skills/*,.claude/rules-1c/forms.md` — a space-separated
list would bind only the first path.
.PARAMETER McpMode
How to handle the MCP phase. `auto` (default) — detect an external MCP
installation (INSTALL.md mode 3 of the MCP distribution) via the
BASESAI_MCP_GLOBAL_ROOT user environment variable (fallback:
MCP_GLOBAL_ROOT in the project .dev.env) plus `install.manifest.json`
in that folder; when found, the installer does NOT touch any tool MCP
config and instead syncs the `mcp:install_forme` section of
USER-RULES.md from the actual install artifacts. `managed` — always
render MCP configs from `content/mcp-servers.json` (legacy behaviour),
even when an external installation is detected. `external` — require
the external installation (fail if the env signal or manifest is
missing) and skip MCP config rendering.
.PARAMETER ProjectRoot
Project root directory to install into. Defaults to the current working
directory. Use this when invoking install.ps1 from a different location
(e.g. running a cached copy from $env:TEMP) and you want the rules
written into a specific project folder.
.EXAMPLE
.\install.ps1 init -Tools cursor,claude-code -NonInteractive
.EXAMPLE
.\install.ps1 update -AssumeYes
.EXAMPLE
& "$env:TEMP\install.ps1" init -ProjectRoot "C:\Work\MyProject" -Source "$env:TEMP\1c-rules" -AssumeYes
.EXAMPLE
.\install.ps1 init -Source https://github.com/comol/ai_rules_1c -AssumeYes
.NOTES
Target: Windows PowerShell 5.1+ (compatible with PowerShell 7+).
Protocol version: 1.0. See AGENT-INSTALL.md for the specification.
#>
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[ValidateSet('init', 'update', 'add', 'remove', 'doctor', 'eject')]
[string]$Command = 'init',
[Parameter(Position = 1)]
[string]$Tool,
[string[]]$Tools,
[string]$Source,
[string]$ProjectRoot,
[switch]$NonInteractive,
[switch]$AssumeYes,
[switch]$Force,
[string[]]$ForcePaths,
[ValidateSet('auto', 'managed', 'external')]
[string]$McpMode = 'auto'
)
# ============================================================================
# CONSTANTS
# ============================================================================
$script:ProtocolVersion = '1.1'
$script:ManifestFileName = '.ai-rules.json'
$script:AgentsMdFileName = 'AGENTS.md'
$script:UserRulesFileName = 'USER-RULES.md'
$script:MemoryFileName = 'memory.md'
$script:LlmRulesFileName = 'LLM-RULES.md'
$script:DevEnvFileName = '.dev.env'
$script:DevEnvExampleName = '.dev.env.example'
$script:SupportedTools = @('cursor', 'claude-code', 'codex', 'opencode', 'kilocode', 'kimi', 'qwen', 'command-code', 'cline', 'pi', 'other')
$script:ManagedBlocks = @('core', 'user-defined', 'openspec')
$script:LastChannel = 'powershell'
$script:Utf8NoBom = New-Object System.Text.UTF8Encoding $false
# Set by Invoke-Update (empty during init): the full set of project-relative
# paths the manifest tracked before the per-update prune. Used by skill
# pruning to tell "a file we shipped and later dropped" (safe to delete) from
# "a file the user dropped into the skill dir themselves" (must be kept).
$script:PreviousFiles = @{}
$script:ForcedThisRun = @()
$script:KeptThisRun = @()
# ============================================================================
# SECTION 1: LOGGING AND USER INPUT
# ============================================================================
function Write-Info {
param([string]$Message)
Write-Host $Message
}
function Write-Warn {
param([string]$Message)
Write-Host "WARN: $Message" -ForegroundColor Yellow
}
function Write-Err {
param([string]$Message)
Write-Host "ERROR: $Message" -ForegroundColor Red
}
function Write-Section {
param([string]$Title)
Write-Host ''
Write-Host "== $Title ==" -ForegroundColor Cyan
}
function Read-YesNo {
param(
[string]$Prompt,
[bool]$Default = $true
)
if ($NonInteractive -or $AssumeYes) { return $true }
$suffix = if ($Default) { '[Y/n]' } else { '[y/N]' }
$ans = Read-Host "$Prompt $suffix"
if ([string]::IsNullOrWhiteSpace($ans)) { return $Default }
return ($ans -match '^[Yy]')
}
function Read-Choice {
param(
[string]$Prompt,
[string[]]$Options,
[string]$Default
)
if ($NonInteractive) { return $Default }
$optsText = ($Options | ForEach-Object { if ($_ -eq $Default) { "[$_]" } else { $_ } }) -join '/'
$ans = Read-Host "$Prompt ($optsText)"
if ([string]::IsNullOrWhiteSpace($ans)) { return $Default }
$match = $Options | Where-Object { $_ -like "${ans}*" } | Select-Object -First 1
if ($match) { return $match }
return $Default
}
# ============================================================================
# SECTION 2: FILE IO WITH ENCODING CONTROL
# ============================================================================
function Read-TextFile {
param([string]$Path)
return [System.IO.File]::ReadAllText((Resolve-Path $Path).Path)
}
function Write-TextFile {
param(
[string]$Path,
[string]$Content
)
$full = [System.IO.Path]::GetFullPath($Path)
$dir = [System.IO.Path]::GetDirectoryName($full)
if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
[System.IO.File]::WriteAllText($full, $Content, $script:Utf8NoBom)
}
function Get-FileSha256 {
param([string]$Path)
return (Get-FileHash -Path $Path -Algorithm SHA256).Hash.ToLower()
}
function Get-StringSha256 {
param([string]$Text)
$sha = [System.Security.Cryptography.SHA256]::Create()
$bytes = [System.Text.Encoding]::UTF8.GetBytes($Text)
$hash = $sha.ComputeHash($bytes)
$sha.Dispose()
return (($hash | ForEach-Object { $_.ToString('x2') }) -join '')
}
# ============================================================================
# SECTION 3: YAML PARSING (frontmatter + adapter subset)
# ============================================================================
# Parse a flat YAML frontmatter block. Supports scalars, quoted strings,
# booleans, flow arrays [a, b]. No nesting.
function ConvertFrom-FrontmatterYaml {
param([string]$Text)
$result = [ordered]@{}
foreach ($rawLine in ($Text -split "`r?`n")) {
$line = $rawLine -replace '\s+$', ''
if ([string]::IsNullOrWhiteSpace($line)) { continue }
if ($line -match '^\s*#') { continue }
if ($line -notmatch '^([\w-]+)\s*:\s*(.*)$') { continue }
$key = $Matches[1]
$val = $Matches[2]
$result[$key] = ConvertFrom-ScalarOrArray $val
}
return $result
}
function ConvertFrom-ScalarOrArray {
param([string]$Raw)
$trim = $Raw.Trim()
if ($trim -eq '') { return '' }
if ($trim -match '^\[(.*)\]$') {
$inside = $Matches[1]
if ($inside.Trim() -eq '') { return @() }
$items = $inside -split ','
return @($items | ForEach-Object { ConvertFrom-Scalar ($_.Trim()) })
}
return (ConvertFrom-Scalar $trim)
}
function ConvertFrom-Scalar {
param([string]$Raw)
if ($Raw.Length -eq 0) { return '' }
$c = $Raw[0]
if ($c -eq '"' -and $Raw.EndsWith('"')) {
$inner = $Raw.Substring(1, $Raw.Length - 2)
return $inner -replace '\\"', '"'
}
if ($c -eq "'" -and $Raw.EndsWith("'")) {
return $Raw.Substring(1, $Raw.Length - 2)
}
if ($Raw -eq 'true') { return $true }
if ($Raw -eq 'false') { return $false }
if ($Raw -eq 'null' -or $Raw -eq '~') { return $null }
if ($Raw -match '^-?\d+$') { return [int]$Raw }
return $Raw
}
# Parse an adapter YAML file. Supports:
# - Scalars (string, int, bool)
# - Flow arrays [a, b]
# - Flow dicts { k: v, k2: v2 }
# - Block-style nested dicts via indentation
# - Block literal (|) for multi-line strings
# - Comments (# to end of line, but not inside quoted strings)
function ConvertFrom-AdapterYaml {
param([string]$Path)
$text = Read-TextFile $Path
$allLines = $text -split "`r?`n"
# Strip end-of-line comments but preserve content lines.
$lines = @()
foreach ($ln in $allLines) {
$stripped = $ln
# Remove comments only if the # is not inside quotes
$inS = $false; $inD = $false; $cutAt = -1
for ($i = 0; $i -lt $stripped.Length; $i++) {
$ch = $stripped[$i]
if (-not $inD -and $ch -eq "'") { $inS = -not $inS }
elseif (-not $inS -and $ch -eq '"') { $inD = -not $inD }
elseif (-not $inS -and -not $inD -and $ch -eq '#') { $cutAt = $i; break }
}
if ($cutAt -ge 0) { $stripped = $stripped.Substring(0, $cutAt) }
$lines += $stripped.TrimEnd()
}
$parser = [PSCustomObject]@{ Lines = $lines; Index = 0 }
return Invoke-YamlBlock -Parser $parser -BaseIndent 0
}
function Get-YamlIndent {
param([string]$Line)
if ($Line -match '^(\s*)') { return $Matches[1].Length }
return 0
}
function Test-YamlBlank {
param([string]$Line)
return [string]::IsNullOrWhiteSpace($Line)
}
# Parse a YAML block (dict) starting at Parser.Index with BaseIndent.
# Returns an ordered hashtable.
function Invoke-YamlBlock {
param(
[Parameter(Mandatory)][PSCustomObject]$Parser,
[Parameter(Mandatory)][int]$BaseIndent
)
$result = [ordered]@{}
while ($Parser.Index -lt $Parser.Lines.Count) {
$line = $Parser.Lines[$Parser.Index]
if (Test-YamlBlank $line) { $Parser.Index++; continue }
$indent = Get-YamlIndent $line
if ($indent -lt $BaseIndent) { break }
if ($indent -gt $BaseIndent) {
throw "YAML parse error at line $($Parser.Index + 1): unexpected indent (expected $BaseIndent, got $indent)"
}
$trim = $line.Trim()
# Dict entries look like "key:" or "key: value"
if ($trim -notmatch '^("([^"]+)"|[\w!-][\w-]*)\s*:\s*(.*)$') {
throw "YAML parse error at line $($Parser.Index + 1): expected key-value, got '$trim'"
}
$rawKey = $Matches[1]
$quotedKey = $Matches[2]
$rawVal = $Matches[3]
$key = if ($quotedKey) { $quotedKey } else { $rawKey }
$Parser.Index++
if ($rawVal -eq '|') {
# Block literal: collect indented lines
$blockLines = @()
$blockIndent = -1
while ($Parser.Index -lt $Parser.Lines.Count) {
$l = $Parser.Lines[$Parser.Index]
if (Test-YamlBlank $l) { $blockLines += ''; $Parser.Index++; continue }
$li = Get-YamlIndent $l
if ($li -le $BaseIndent) { break }
if ($blockIndent -lt 0) { $blockIndent = $li }
if ($li -lt $blockIndent) { break }
$blockLines += $l.Substring($blockIndent)
$Parser.Index++
}
# Trim trailing empty lines
while ($blockLines.Count -gt 0 -and $blockLines[-1] -eq '') {
$blockLines = $blockLines[0..($blockLines.Count - 2)]
}
$result[$key] = ($blockLines -join "`n") + "`n"
}
elseif ($rawVal -eq '') {
# Nested block — could be dict or array. Skip blank lines first
# (comment-only lines are blanked by the comment stripper above);
# otherwise a comment between `key:` and its first child would be
# mistaken for an empty value and break the nesting detection.
while ($Parser.Index -lt $Parser.Lines.Count -and (Test-YamlBlank $Parser.Lines[$Parser.Index])) {
$Parser.Index++
}
if ($Parser.Index -lt $Parser.Lines.Count) {
$next = $Parser.Lines[$Parser.Index]
$nextIndent = Get-YamlIndent $next
$nextTrim = $next.Trim()
if ($nextTrim.StartsWith('- ') -or $nextTrim -eq '-') {
$result[$key] = Invoke-YamlBlockArray -Parser $Parser -BaseIndent $nextIndent
}
elseif ($nextIndent -gt $BaseIndent) {
$result[$key] = Invoke-YamlBlock -Parser $Parser -BaseIndent $nextIndent
}
else {
$result[$key] = $null
}
}
else {
$result[$key] = $null
}
}
else {
$result[$key] = ConvertFrom-YamlInlineValue $rawVal
}
}
return $result
}
# Parse a block-style array at BaseIndent (each line starts with "- ").
function Invoke-YamlBlockArray {
param(
[Parameter(Mandatory)][PSCustomObject]$Parser,
[Parameter(Mandatory)][int]$BaseIndent
)
$items = @()
while ($Parser.Index -lt $Parser.Lines.Count) {
$line = $Parser.Lines[$Parser.Index]
if (Test-YamlBlank $line) { $Parser.Index++; continue }
$indent = Get-YamlIndent $line
if ($indent -lt $BaseIndent) { break }
if ($indent -gt $BaseIndent) {
throw "YAML parse error at line $($Parser.Index + 1): unexpected indent in array"
}
$trim = $line.Trim()
if ($trim -notmatch '^-\s*(.*)$') { break }
$rest = $Matches[1]
$Parser.Index++
if ([string]::IsNullOrWhiteSpace($rest)) {
# Nested dict item
if ($Parser.Index -lt $Parser.Lines.Count) {
$next = $Parser.Lines[$Parser.Index]
$nextIndent = Get-YamlIndent $next
$items += (Invoke-YamlBlock -Parser $Parser -BaseIndent $nextIndent)
}
}
elseif ($rest -match '^([\w-]+)\s*:\s*(.*)$') {
# Inline dict with single key on the - line; possibly followed by more keys
# We support single-line flow for simplicity:
# - exists: ".cursor/"
$dict = [ordered]@{}
$dict[$Matches[1]] = ConvertFrom-YamlInlineValue $Matches[2]
$items += $dict
}
else {
$items += (ConvertFrom-YamlInlineValue $rest)
}
}
return , $items
}
# Parse an inline YAML value: scalar, flow array, flow dict.
function ConvertFrom-YamlInlineValue {
param([string]$Raw)
$trim = $Raw.Trim()
if ($trim -eq '') { return '' }
if ($trim -match '^\{(.*)\}$') {
$inside = $Matches[1].Trim()
if ($inside -eq '') { return [ordered]@{} }
$dict = [ordered]@{}
$parts = Split-YamlFlow $inside
foreach ($p in $parts) {
if ($p -match '^("([^"]+)"|[\w!-][\w-]*)\s*:\s*(.*)$') {
$k = if ($Matches[2]) { $Matches[2] } else { $Matches[1] }
$dict[$k] = ConvertFrom-YamlInlineValue $Matches[3]
}
}
return $dict
}
if ($trim -match '^\[(.*)\]$') {
$inside = $Matches[1].Trim()
if ($inside -eq '') { return , @() }
$items = Split-YamlFlow $inside
return , ($items | ForEach-Object { ConvertFrom-YamlInlineValue $_ })
}
return (ConvertFrom-Scalar $trim)
}
# Split a flow-style inner (e.g. "a, b, { k: v }, [x, y]") on commas that
# are not inside brackets, braces, or quotes.
function Split-YamlFlow {
param([string]$Raw)
$parts = @()
$buf = ''
$depthB = 0; $depthC = 0; $inD = $false; $inS = $false
for ($i = 0; $i -lt $Raw.Length; $i++) {
$ch = $Raw[$i]
if (-not $inD -and $ch -eq "'") { $inS = -not $inS; $buf += $ch; continue }
if (-not $inS -and $ch -eq '"') { $inD = -not $inD; $buf += $ch; continue }
if ($inS -or $inD) { $buf += $ch; continue }
switch ($ch) {
'[' { $depthB++; $buf += $ch; continue }
']' { $depthB--; $buf += $ch; continue }
'{' { $depthC++; $buf += $ch; continue }
'}' { $depthC--; $buf += $ch; continue }
',' {
if ($depthB -eq 0 -and $depthC -eq 0) {
$parts += $buf.Trim(); $buf = ''; continue
}
else { $buf += $ch; continue }
}
default { $buf += $ch }
}
}
if ($buf.Trim() -ne '') { $parts += $buf.Trim() }
return $parts
}
# ============================================================================
# SECTION 4: FRONTMATTER EXTRACTION AND SERIALIZATION
# ============================================================================
function Split-FrontmatterAndBody {
param([string]$Text)
$lines = $Text -split "`r?`n"
if ($lines.Count -lt 2 -or $lines[0] -ne '---') {
return @{ Frontmatter = $null; Body = $Text }
}
$closer = -1
for ($i = 1; $i -lt $lines.Count; $i++) {
if ($lines[$i] -eq '---') { $closer = $i; break }
}
if ($closer -lt 0) {
return @{ Frontmatter = $null; Body = $Text }
}
$fmText = ($lines[1..($closer - 1)] -join "`n")
$bodyText = ($lines[($closer + 1)..($lines.Count - 1)] -join "`n")
$fm = ConvertFrom-FrontmatterYaml $fmText
return @{ Frontmatter = $fm; Body = $bodyText }
}
function Format-Frontmatter {
param([System.Collections.IDictionary]$Fm)
if ($null -eq $Fm -or $Fm.Keys.Count -eq 0) { return '' }
$lines = @('---')
foreach ($k in $Fm.Keys) {
$v = $Fm[$k]
$lines += (Format-FrontmatterEntry $k $v)
}
$lines += '---'
return ($lines -join "`n")
}
function Format-FrontmatterEntry {
param(
[string]$Key,
$Value
)
if ($null -eq $Value) { return "${Key}:" }
if ($Value -is [bool]) {
$s = if ($Value) { 'true' } else { 'false' }
return "${Key}: $s"
}
if ($Value -is [int]) { return "${Key}: $Value" }
if ($Value -is [System.Collections.IDictionary]) {
# Nested block-style dict (e.g. OpenCode `permission:` object).
$lines = @("${Key}:")
foreach ($subKey in $Value.Keys) {
$subVal = $Value[$subKey]
$rendered =
if ($null -eq $subVal) { '' }
elseif ($subVal -is [bool]) { if ($subVal) { 'true' } else { 'false' } }
elseif ($subVal -is [int]) { "$subVal" }
elseif ($subVal -is [string]) { Format-FrontmatterStringValue $subVal }
else { [string]$subVal }
$lines += " ${subKey}: $rendered"
}
return ($lines -join "`n")
}
if ($Value -is [array]) {
$items = @($Value | ForEach-Object { Format-FrontmatterInlineString $_ })
return "${Key}: [$(($items -join ', '))]"
}
if ($Value -is [string]) {
return "${Key}: " + (Format-FrontmatterStringValue $Value)
}
return "${Key}: " + $Value.ToString()
}
function Format-FrontmatterInlineString {
param([string]$S)
if ($S -match '[,\[\]"'':]') {
return '"' + ($S -replace '"', '\"') + '"'
}
return '"' + $S + '"'
}
function Format-FrontmatterStringValue {
param([string]$S)
if ($S -match '^[\w./\-]+$' -and -not ($S -match '^(true|false|null|~)$')) {
return $S
}
return '"' + ($S -replace '"', '\"') + '"'
}
# ============================================================================
# SECTION 5: FRONTMATTER OPERATIONS
# ============================================================================
function Invoke-FrontmatterOps {
param(
[System.Collections.IDictionary]$Source,
$Ops
)
$src = [ordered]@{}
if ($Source) { foreach ($k in $Source.Keys) { $src[$k] = $Source[$k] } }
if ($null -eq $Ops) { return $src }
$keep = if ($Ops.keep) { @($Ops.keep) } else { @() }
$drop = if ($Ops.drop) { @($Ops.drop) } else { @() }
$rename = if ($Ops.rename) { $Ops.rename } else { @{} }
$addIf = if ($Ops.addIf) { $Ops.addIf } else { @{} }
$toolsToPermission = if ($Ops.toolsToPermission) { $Ops.toolsToPermission } else { $null }
# Phase 0: tools array -> permission object (OpenCode).
# Runs BEFORE keep/drop so it can still read the source `tools` list.
# Each mapped source tool present in the list -> `grant` (allow);
# every mapped permission key NOT granted -> `deny`, so a read-only agent
# (no Write/Edit/Shell in its `tools`) is actually denied edit/bash instead
# of falling back to OpenCode's permissive default tool set.
if ($toolsToPermission) {
$srcKey = if ($toolsToPermission.source) { $toolsToPermission.source } else { 'tools' }
$grantVal = if ($toolsToPermission.grant) { $toolsToPermission.grant } else { 'allow' }
$denyVal = if ($toolsToPermission.deny) { $toolsToPermission.deny } else { 'deny' }
$map = $toolsToPermission.map
if ($map -and $src.Contains($srcKey)) {
$granted = @($src[$srcKey])
$permission = [ordered]@{}
foreach ($srcTool in $map.Keys) {
$permKey = $map[$srcTool]
if ([string]::IsNullOrEmpty([string]$permKey)) { continue }
$isGranted = $granted -contains $srcTool
if (-not $permission.Contains($permKey)) {
$permission[$permKey] = if ($isGranted) { $grantVal } else { $denyVal }
}
elseif ($isGranted) {
# Multiple source tools can map to one key (Write/Edit -> edit):
# any granting tool wins.
$permission[$permKey] = $grantVal
}
}
if ($permission.Keys.Count -gt 0) { $src['permission'] = $permission }
}
}
# Phase 1: keep/drop filtering
if ($keep.Count -gt 0) {
$filtered = [ordered]@{}
foreach ($k in $src.Keys) {
if ($keep -contains $k) { $filtered[$k] = $src[$k] }
}
$src = $filtered
}
elseif ($drop.Count -gt 0) {
$filtered = [ordered]@{}
foreach ($k in $src.Keys) {
if (-not ($drop -contains $k)) { $filtered[$k] = $src[$k] }
}
$src = $filtered
}
# Phase 2: rename
if ($rename -and $rename.Keys.Count -gt 0) {
$renamed = [ordered]@{}
foreach ($k in $src.Keys) {
$newName = if ($rename.Contains($k)) { $rename[$k] } else { $k }
$renamed[$newName] = $src[$k]
}
$src = $renamed
}
# Phase 3: addIf — add fields conditionally
if ($addIf -and $addIf.Keys.Count -gt 0) {
foreach ($cond in $addIf.Keys) {
$negated = $cond.StartsWith('!')
$field = if ($negated) { $cond.Substring(1) } else { $cond }
$hasField = $Source.Contains($field)
$truthy = $hasField -and $Source[$field]
$shouldAdd = if ($negated) { -not $truthy } else { $truthy }
if ($shouldAdd) {
$toAdd = $addIf[$cond]
if ($toAdd -is [System.Collections.IDictionary]) {
foreach ($k in $toAdd.Keys) { $src[$k] = $toAdd[$k] }
}
}
}
}
return $src
}
# ============================================================================
# SECTION 6: TOML RENDERING (for Codex rebuild-toml and MCP config)
# ============================================================================
function Format-TomlString {
param([string]$Value)
# Simple TOML string escape: quotes and backslashes
$s = $Value -replace '\\', '\\\\' -replace '"', '\"'
return '"' + $s + '"'
}
function Format-TomlArray {
param([array]$Values)
$items = @($Values | ForEach-Object { Format-TomlString $_ })
return '[' + ($items -join ', ') + ']'
}
function Invoke-CodexAgentTemplate {
param(
[string]$Template,
[System.Collections.IDictionary]$Fm,
[string]$Body
)
$outLines = @()
foreach ($line in ($Template -split "`n")) {
# Find placeholders {field}
$placeholders = [regex]::Matches($line, '\{([\w-]+)\}')
$hasMissing = $false
$rendered = $line
$placeholderKeys = @()
foreach ($m in $placeholders) {
$k = $m.Groups[1].Value
if ($k -eq 'body') { continue }
$placeholderKeys += $k
if (-not $Fm.Contains($k) -or [string]::IsNullOrEmpty([string]$Fm[$k])) {
$hasMissing = $true
break
}
}
if ($hasMissing) { continue }
foreach ($k in $placeholderKeys) {
$v = $Fm[$k]
$rendered = $rendered -replace ('\{' + [regex]::Escape($k) + '\}'), ($v -replace '\$', '$$$$')
}
if ($rendered -match '\{body\}') {
$rendered = $rendered -replace '\{body\}', ($Body -replace '\$', '$$$$')
}
$outLines += $rendered
}
return ($outLines -join "`n")
}
# ============================================================================
# SECTION 7: MCP CONFIG RENDERERS
# ============================================================================
function Read-McpServers {
param([string]$Root)
$path = Join-Path $Root 'content/mcp-servers.json'
if (-not (Test-Path $path)) {
throw "MCP servers list not found: $path"
}
$json = Read-TextFile $path
$obj = $json | ConvertFrom-Json
return $obj.servers
}
# Known UI locale codes that may appear as the trailing path segment of
# INFOBASE_PUBLISH_URL (the web-publication URL is typically
# `http://host/<infobase>/<locale>/`). The HTTP-service endpoint is served
# under `<host>/<infobase>/hs/<service>` — without the locale subpath — so the
# locale must be stripped before substituting into MCP server URL templates.
$script:KnownInfobaseLocales = @(
'ru', 'en', 'uk', 'kk', 'be', 'de', 'fr', 'es', 'it', 'pl', 'tr',
'vi', 'zh', 'ja', 'ka', 'lt', 'lv', 'hu', 'bg', 'ro', 'sk', 'cs',
'sl', 'hr', 'sr', 'et', 'fi', 'sv', 'no', 'da', 'nl', 'pt', 'el',
'az', 'hy', 'mn', 'mk', 'th', 'ko', 'ar', 'he'
)
function Get-InfobasePublishUrlBase {
# Reads INFOBASE_PUBLISH_URL from `.dev.env` in the project root and
# normalizes it for use as the base URL of HTTP services published on the
# infobase:
# 1) trim whitespace, strip the trailing slash;
# 2) strip the trailing `/<locale>` segment when it matches a known
# 1C UI locale code from $script:KnownInfobaseLocales — HTTP services
# live at `<base>/hs/<service>`, not under the locale subpath.
# Returns an empty string when `.dev.env` is missing, the key is absent,
# or the value is empty.
param([string]$Root)
$envPath = Join-Path $Root $script:DevEnvFileName
if (-not (Test-Path $envPath)) { return '' }
$keys = Read-DevEnvKeys -Path $envPath
if (-not $keys.Contains('INFOBASE_PUBLISH_URL')) { return '' }
$raw = [string]$keys['INFOBASE_PUBLISH_URL']
if ([string]::IsNullOrWhiteSpace($raw)) { return '' }
$url = $raw.Trim().TrimEnd('/')
if ($url -match '/([a-z]{2,3})$') {
if ($script:KnownInfobaseLocales -contains $Matches[1]) {
$url = $url.Substring(0, $url.LastIndexOf('/'))
}
}
return $url
}
function Resolve-McpServerPlaceholders {
# Substitutes {INFOBASE_PUBLISH_URL} in the `url` field of every server
# entry that contains it. Mutates the input collection. Returns the list
# of server ids whose placeholder could not be resolved because
# INFOBASE_PUBLISH_URL was empty / `.dev.env` was missing — the caller
# uses this to warn the user.
param(
[array]$Servers,
[string]$InfobaseBase
)
$unresolved = @()
foreach ($s in $Servers) {
if (-not $s.url) { continue }
if ($s.url -notmatch '\{INFOBASE_PUBLISH_URL\}') { continue }
if ($InfobaseBase) {
$s.url = $s.url.Replace('{INFOBASE_PUBLISH_URL}', $InfobaseBase)
}
else {
$unresolved += $s.id
}
}
return , $unresolved
}
function Test-McpHttpEndpoint {
# Probes an HTTP endpoint with a short timeout. Used to detect whether a
# 1C HTTP-service-based MCP server (`1c-data-mcp`) is reachable AND
# whether the publication allows anonymous access (no Basic auth) — the
# MCP client does not pass credentials, so HTTP 401 / 403 means the user
# must reconfigure the publication.
#
# Returns a hashtable:
# Code — HTTP status code (int) when the server responded with one,
# or the string 'down' when the connection was refused /
# timed out, or 'error' on any other client-side failure.
# Reachable — $true if any HTTP response was received (even 4xx / 5xx).
param(
[string]$Url,
[int]$TimeoutSec = 3
)
try {
$r = Invoke-WebRequest -Uri $Url -Method Get -TimeoutSec $TimeoutSec -UseBasicParsing -ErrorAction Stop
return @{ Code = [int]$r.StatusCode; Reachable = $true }
}
catch {
if ($_.Exception -and $_.Exception.Response) {
try { return @{ Code = [int]$_.Exception.Response.StatusCode; Reachable = $true } } catch { }
}
# No HTTP response was received — the server is not listening, the
# name does not resolve, or the request timed out. From the
# installer's point of view all three are equivalent ("endpoint not
# reachable, not blocking install"), so report a single 'down' code.
return @{ Code = 'down'; Reachable = $false }
}
}
function ConvertTo-McpServersJsonDict {
param([array]$Servers)
$dict = [ordered]@{}
foreach ($s in $Servers) {
$entry = [ordered]@{}
if ($s.url) { $entry['url'] = $s.url }
if ($s.connectionId) { $entry['connection_id'] = $s.connectionId }
if ($s.description) { $entry['description'] = $s.description }
if ($s.command) { $entry['command'] = $s.command }
if ($s.args) { $entry['args'] = $s.args }
if ($s.env) { $entry['env'] = $s.env }
$dict[$s.id] = $entry
}
return $dict
}
function New-McpConfig-Cursor {
param([array]$Servers)
$root = [ordered]@{ mcpServers = (ConvertTo-McpServersJsonDict $Servers) }
return (ConvertTo-Json $root -Depth 10)
}
function New-McpConfig-ClaudeCode {
# Claude Code `.mcp.json` schema (https://code.claude.com/docs/en/mcp).
# Remote servers MUST carry an explicit `"type": "http"` — without it the
# current Claude Code (VS Code extension and CLI) does not load the server
# and it silently never appears in the tool list. The documented keys for
# an HTTP entry are `type`, `url`, `headers`; for a local (stdio) entry
# `command`, `args`, `env`. The Cursor-only `connection_id` / `description`
# keys are NOT part of the Claude Code schema, so they are omitted here.
param([array]$Servers)
$dict = [ordered]@{}
foreach ($s in $Servers) {
$entry = [ordered]@{}
if ($s.url) {
$entry['type'] = 'http'
$entry['url'] = $s.url
if ($s.headers) { $entry['headers'] = $s.headers }
}
elseif ($s.command) {
$entry['command'] = $s.command
if ($s.args) { $entry['args'] = $s.args }
if ($s.env) { $entry['env'] = $s.env }
}
$dict[$s.id] = $entry
}
$root = [ordered]@{ mcpServers = $dict }
return (ConvertTo-Json $root -Depth 10)
}
function New-McpConfig-Kilocode {
# Current Kilo CLI / Kilo Code extension MCP schema (v7.x+, see
# https://kilo.ai/docs/automate/mcp/using-in-cli):
#
# {
# "mcp": {
# "<server-id>": {
# "type": "remote" | "local",
# "url": "...", # remote only
# "command": ["..."], # local only
# "environment": {...}, # local, optional
# "headers": {...}, # remote, optional
# "enabled": true,
# "timeout": 5000 # optional
# }
# }
# }
#
# The legacy `.kilocode/mcp.json` with the `mcpServers` dictionary is no
# longer read by the current Kilo CLI nor by the current Kilo Code VS
# Code extension — both look up MCP under the top-level `mcp` key of
# `kilo.json` / `kilo.jsonc` / `.kilo/kilo.json` / `.kilo/kilo.jsonc`
# (see `adapters/kilocode.yaml > mcp.target`). Writing the legacy
# `mcpServers` shape into `.kilocode/mcp.json` results in silently empty
# MCP listings in `/mcps` and during agent tool discovery.
param([array]$Servers)
$mcp = [ordered]@{}
foreach ($s in $Servers) {
$entry = [ordered]@{}
if ($s.url) {
$entry['type'] = 'remote'
$entry['url'] = $s.url
}
elseif ($s.command) {
$entry['type'] = 'local'
$cmd = @($s.command) + @($s.args)
$entry['command'] = $cmd
if ($s.env) { $entry['environment'] = $s.env }
}
$entry['enabled'] = $true
$mcp[$s.id] = $entry
}
$root = [ordered]@{ mcp = $mcp }
return (ConvertTo-Json $root -Depth 10)
}
function New-McpConfig-Other {
# Universal fallback adapter — uses the standard `mcpServers` JSON
# dictionary schema (same shape as Cursor / Claude Code / Kilo Code), so
# reuse the same renderer. The output is written to `.ai-agent/mcp.json`
# per `adapters/other.yaml` and is consumable by any AI client that
# supports the de-facto `mcpServers` JSON convention.
param([array]$Servers)
return New-McpConfig-Cursor $Servers
}
function New-McpConfig-Qwen {
# Qwen Code project MCP lives in `.qwen/settings.json` under `mcpServers`
# (https://qwenlm.github.io/qwen-code-docs/en/users/features/mcp/).
# HTTP (streamable) servers MUST use `httpUrl`; `url` is SSE-only.
# Stdio servers use `command` / `args` / `env`. The installer deep-merges
# only the `mcpServers` key (see adapter `mcp.mergeKey`) so other
# settings survive `update`.
param([array]$Servers)
$dict = [ordered]@{}
foreach ($s in $Servers) {
$entry = [ordered]@{}
if ($s.url) {
$entry['httpUrl'] = $s.url
if ($s.headers) { $entry['headers'] = $s.headers }
}
elseif ($s.command) {
$entry['command'] = $s.command
if ($s.args) { $entry['args'] = $s.args }
if ($s.env) { $entry['env'] = $s.env }
}
$dict[$s.id] = $entry
}
$root = [ordered]@{ mcpServers = $dict }
return (ConvertTo-Json $root -Depth 10)
}
function ConvertTo-OpenCodeMcpKey {
# OpenCode exposes MCP tools to the model as `<server-key>_<tool>`, taking
# the key verbatim from the `mcp` object (it only replaces characters
# outside [a-zA-Z0-9_-] with `_`, it does NOT force a leading letter). Some
# providers — Moonshot/Kimi in particular — reject any function name that
# does not start with a letter (`^[a-zA-Z_][a-zA-Z0-9-_]{2,63}$`), so a key
# like `1c-syntax-checker-mcp` produces `1c-syntax-checker-mcp_syntaxcheck`
# and the whole request fails with "function name is invalid, must start
# with a letter". Normalize the well-known `1c`/`1C` prefix to the readable
# `onec`; guarantee any other non-letter-leading id also starts with a
# letter. Canonical ids in content/mcp-servers.json stay `1c-...`; only the
# OpenCode-rendered key changes (tool detection in /checkmcp keys off the
# bare tool names, not the server prefix, so it is unaffected).
param([string]$Id)
$key = $Id
if ($key -match '^1c(.*)$') { $key = 'onec' + $Matches[1] }
if ($key -notmatch '^[A-Za-z]') { $key = 'mcp-' + $key }