forked from gastownhall/gascity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpack.go
More file actions
2784 lines (2568 loc) · 88.8 KB
/
Copy pathpack.go
File metadata and controls
2784 lines (2568 loc) · 88.8 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
package config
import (
"crypto/sha256"
"errors"
"fmt"
iofs "io/fs"
"log"
"path/filepath"
"slices"
"sort"
"strings"
"github.com/BurntSushi/toml"
"github.com/gastownhall/gascity/internal/fsys"
"github.com/gastownhall/gascity/internal/orders"
"github.com/gastownhall/gascity/internal/pricing"
)
// packFile is the expected filename inside a pack directory.
const packFile = "pack.toml"
// currentPackSchema is the supported pack schema version.
const currentPackSchema = 2
// packConfig is the TOML structure of a pack.toml file.
// It has a [pack] metadata header and agent definitions.
type packConfig struct {
Pack PackMeta `toml:"pack"`
Imports map[string]Import `toml:"imports,omitempty"`
AgentDefaults AgentDefaults `toml:"agent_defaults,omitempty"`
AgentsDefaults AgentDefaults `toml:"agents,omitempty" jsonschema:"-"`
Defaults packDefaults `toml:"defaults,omitempty"`
Agents []Agent `toml:"agent"`
NamedSessions []NamedSession `toml:"named_session,omitempty"`
Services []Service `toml:"service,omitempty"`
Providers map[string]ProviderSpec `toml:"providers,omitempty"`
Formulas FormulasConfig `toml:"formulas,omitempty"`
Patches Patches `toml:"patches,omitempty"`
Doctor []PackDoctorEntry `toml:"doctor,omitempty"`
Commands []PackCommandEntry `toml:"commands,omitempty"`
Global PackGlobal `toml:"global,omitempty"`
Pricing []pricing.ModelPricing `toml:"pricing,omitempty"`
}
type packDefaults struct {
Rig packRigDefaults `toml:"rig,omitempty"`
}
type packRigDefaults struct {
Imports map[string]Import `toml:"imports,omitempty"`
}
// ExpandPacks resolves pack references on all rigs. For each rig
// with pack fields set (V1 includes or V2 [rigs.imports.X]), it loads
// the pack directories, stamps agents with dir = rig.Name and
// BindingName from imports, resolves paths relative to the pack
// directory, and appends the agents to the city config.
//
// Overrides from the rig are applied to the stamped agents (after all
// packs for the rig are expanded). All expansion happens before
// validation — downstream sees a flat City struct.
//
// rigFormulaDirs is populated with per-rig pack formula directories
// (Layer 3). cityRoot is the city directory (parent of city.toml), used
// for path resolution.
func ExpandPacks(cfg *City, fs fsys.FS, cityRoot string, rigFormulaDirs map[string][]string) error {
return expandPacks(cfg, fs, cityRoot, rigFormulaDirs, LoadOptions{})
}
func expandPacks(cfg *City, fs fsys.FS, cityRoot string, rigFormulaDirs map[string][]string, opts LoadOptions) error {
var expanded []Agent
for i := range cfg.Rigs {
rig := &cfg.Rigs[i]
cache := &packLoadCache{results: make(map[string]*packLoadResult)}
topoRefs := rig.Includes
if len(topoRefs) == 0 && len(rig.Imports) == 0 {
continue
}
var rigAgents []Agent
var rigNamedSessions []NamedSession
var rigTopoDirs []string
var rigPackGraphOnlyDirs []string
var rigImportPackDirs []string
var rigGlobals []ResolvedPackGlobal
for _, ref := range topoRefs {
topoDir, err := resolvePackRef(ref, cityRoot, cityRoot)
if err != nil {
return fmt.Errorf("rig %q pack %q: %w", rig.Name, ref, err)
}
topoPath := filepath.Join(topoDir, packFile)
// Skip remote packs whose subpath was deleted upstream.
if isRemoteRef(ref) {
if _, sErr := fs.Stat(topoPath); sErr != nil {
log.Printf("rig %q pack %q: not found, skipping: %v", rig.Name, ref, sErr)
continue
}
}
agents, namedSessions, providers, services, topoDirs, reqs, globals, err := loadPackWithCacheOptions(fs, topoPath, topoDir, cityRoot, rig.Name, nil, cache, opts)
if err != nil {
return fmt.Errorf("rig %q pack %q: %w", rig.Name, ref, err)
}
cfg.LoadWarnings = appendUnique(cfg.LoadWarnings, cachedPackWarnings(cache, topoDir)...)
if len(services) > 0 {
return fmt.Errorf("rig %q pack %q: [[service]] is only allowed in city-scoped packs", rig.Name, ref)
}
rigGlobals = append(rigGlobals, globals...)
packName := tcPackName(fs, topoPath)
cfg.PackCommands = appendDiscoveredCommands(
cfg.PackCommands,
stampDefaultBinding(cachedPackCommands(cache, topoDir), packName)...,
)
cfg.PackDoctors = appendDiscoveredDoctors(cfg.PackDoctors, cachedPackDoctors(cache, topoDir)...)
skills := cachedPackSkills(cache, topoDir)
if packName == "" && len(skills) > 0 {
return fmt.Errorf("rig %q pack %q: discovered skills require [pack].name for binding", rig.Name, ref)
}
if cfg.RigPackSkills == nil {
cfg.RigPackSkills = make(map[string][]DiscoveredSkillCatalog)
}
cfg.RigPackSkills[rig.Name] = appendDiscoveredSkills(
cfg.RigPackSkills[rig.Name],
stampSkillBinding(skills, packName)...,
)
// Validate rig-scoped requirements.
for _, req := range reqs {
if req.Scope != "rig" {
continue
}
found := false
for _, a := range agents {
if a.Name == req.Agent {
found = true
break
}
}
if !found {
return fmt.Errorf("rig %q: pack requires rig agent %q — include a pack that provides it", rig.Name, req.Agent)
}
}
// Accumulate pack dirs for this rig.
rigTopoDirs = appendUnique(rigTopoDirs, topoDirs...)
rigPackGraphOnlyDirs = appendUniqueLastWins(rigPackGraphOnlyDirs, topoDirs...)
// Keep only rig-scoped and unscoped agents for rig expansion.
agents = filterAgentsByScope(agents, false)
namedSessions = filterNamedSessionsByScope(namedSessions, false)
// Record rig pack formula dirs (Layer 3) — derive from topoDirs.
if rigFormulaDirs != nil {
for _, td := range topoDirs {
fd := filepath.Join(td, "formulas")
if _, sErr := fs.Stat(fd); sErr == nil {
rigFormulaDirs[rig.Name] = append(rigFormulaDirs[rig.Name], fd)
}
}
}
rigAgents = append(rigAgents, agents...)
rigNamedSessions = append(rigNamedSessions, namedSessions...)
// Merge pack providers into city (additive, no overwrite).
if len(providers) > 0 {
if cfg.Providers == nil {
cfg.Providers = make(map[string]ProviderSpec)
}
for name, spec := range providers {
if _, exists := cfg.Providers[name]; !exists {
cfg.Providers[name] = spec
}
}
}
}
// Process rig-level [imports.X] entries (V2).
if len(rig.Imports) > 0 {
importNames := make([]string, 0, len(rig.Imports))
for name := range rig.Imports {
importNames = append(importNames, name)
}
sort.Strings(importNames)
for _, bindingName := range importNames {
imp := rig.Imports[bindingName]
impDir, err := resolvePackRef(imp.Source, cityRoot, cityRoot)
if err != nil {
return fmt.Errorf("rig %q import %q: %w", rig.Name, bindingName, err)
}
impPath := filepath.Join(impDir, packFile)
agents, namedSessions, providers, services, topoDirs, reqs, globals, err := loadPackWithCacheOptions(
fs, impPath, impDir, cityRoot, rig.Name, nil, cache, opts)
if err != nil {
return fmt.Errorf("rig %q import %q: %w", rig.Name, bindingName, err)
}
warnings := cachedPackWarnings(cache, impDir)
commands := cachedPackCommands(cache, impDir)
doctors := cachedPackDoctors(cache, impDir)
skills := cachedPackSkills(cache, impDir)
if !imp.ImportIsTransitive() {
warnings = cachedPackLocalWarnings(cache, impDir)
absImpDir, _ := filepath.Abs(impDir)
var direct []Agent
for _, a := range agents {
absSrc, _ := filepath.Abs(a.SourceDir)
if absSrc == absImpDir {
direct = append(direct, a)
}
}
agents = direct
namedSessions = filterNamedSessionsBySourceDir(namedSessions, impDir)
services = filterServicesBySourceDir(services, impDir)
commands = filterCommandsByPackDir(commands, impDir)
doctors = filterDoctorsByPackDir(doctors, impDir)
providers = cachedPackLocalProviders(cache, impDir)
topoDirs = cachedPackLocalTopoDirs(cache, impDir)
reqs = cachedPackLocalRequires(cache, impDir)
globals = cachedPackLocalGlobals(cache, impDir)
skills = filterSkillsByPackDir(skills, impDir)
}
cfg.LoadWarnings = appendUnique(cfg.LoadWarnings, warnings...)
if len(services) > 0 {
return fmt.Errorf("rig %q import %q: [[service]] is only allowed in city-scoped packs", rig.Name, bindingName)
}
rigGlobals = append(rigGlobals, globals...)
if cfg.RigPackSkills == nil {
cfg.RigPackSkills = make(map[string][]DiscoveredSkillCatalog)
}
cfg.RigPackSkills[rig.Name] = appendDiscoveredSkills(
cfg.RigPackSkills[rig.Name],
stampImportedSkillBinding(skills, bindingName, imp.Export)...,
)
mcpTopoDirs := topoDirs
if !imp.ImportIsTransitive() {
mcpTopoDirs = filterPackDirsByRoot(topoDirs, impDir)
}
if cfg.RigImportMCPBindings == nil {
cfg.RigImportMCPBindings = make(map[string]map[string]string)
}
cfg.RigImportMCPBindings[rig.Name] = stampMCPDirBindings(cfg.RigImportMCPBindings[rig.Name], mcpTopoDirs, bindingName)
// Stamp binding name on agents and named sessions.
// At the rig level, ALL agents from an import get the rig's
// binding — nested bindings are overridden.
for i := range agents {
agents[i].BindingName = bindingName
}
for i := range namedSessions {
namedSessions[i].BindingName = bindingName
}
for i := range commands {
if commands[i].BindingName == "" {
commands[i].BindingName = bindingName
} else if imp.Export {
commands[i].BindingName = bindingName
}
}
for i := range doctors {
if doctors[i].BindingName == "" {
doctors[i].BindingName = bindingName
} else if imp.Export {
doctors[i].BindingName = bindingName
}
}
// Re-qualify depends_on with binding name now that it's stamped.
for i := range agents {
if agents[i].BindingName == "" || len(agents[i].DependsOn) == 0 {
continue
}
for j, dep := range agents[i].DependsOn {
// If dep was already rewritten with dir prefix but
// doesn't have the binding, inject it.
_, depName := ParseQualifiedName(dep)
if !strings.Contains(depName, ".") {
// Bare name after dir prefix: inject binding.
binding := agents[i].BindingName
if agents[i].Dir != "" {
agents[i].DependsOn[j] = agents[i].Dir + "/" + binding + "." + depName
} else {
agents[i].DependsOn[j] = binding + "." + depName
}
}
}
}
// Read pack name for provenance.
impData, readErr := fs.ReadFile(impPath)
if readErr != nil {
return fmt.Errorf("rig %q import %q: reading %s: %w", rig.Name, bindingName, impPath, readErr)
}
packName, err := decodePackName(impData)
if err != nil {
return fmt.Errorf("rig %q import %q: parsing %s: %w", rig.Name, bindingName, impPath, err)
}
for i := range agents {
if agents[i].PackName == "" {
agents[i].PackName = packName
}
}
for i := range commands {
if commands[i].PackName == "" {
commands[i].PackName = packName
}
}
// Validate rig-scoped requirements.
for _, req := range reqs {
if req.Scope != "rig" {
continue
}
found := false
for _, a := range agents {
if a.Name == req.Agent {
found = true
break
}
}
if !found {
return fmt.Errorf("rig %q: import %q requires rig agent %q — not found", rig.Name, bindingName, req.Agent)
}
}
rigTopoDirs = appendUnique(rigTopoDirs, topoDirs...)
rigImportPackDirs = prependUniqueBlock(rigImportPackDirs, mcpTopoDirs...)
agents = filterAgentsByScope(agents, false)
namedSessions = filterNamedSessionsByScope(namedSessions, false)
if rigFormulaDirs != nil {
for _, td := range topoDirs {
fd := filepath.Join(td, "formulas")
if _, sErr := fs.Stat(fd); sErr == nil {
rigFormulaDirs[rig.Name] = append(rigFormulaDirs[rig.Name], fd)
}
}
}
rigAgents = append(rigAgents, agents...)
rigNamedSessions = append(rigNamedSessions, namedSessions...)
cfg.PackDoctors = appendDiscoveredDoctors(cfg.PackDoctors, doctors...)
if len(providers) > 0 {
if cfg.Providers == nil {
cfg.Providers = make(map[string]ProviderSpec)
}
for name, spec := range providers {
if _, exists := cfg.Providers[name]; !exists {
cfg.Providers[name] = spec
}
}
}
}
}
// Store per-rig pack dirs.
if cfg.RigPackDirs == nil {
cfg.RigPackDirs = make(map[string][]string)
}
if len(rigTopoDirs) > 0 {
cfg.RigPackDirs[rig.Name] = rigTopoDirs
}
if len(rigPackGraphOnlyDirs) > 0 {
if cfg.RigPackGraphOnlyDirs == nil {
cfg.RigPackGraphOnlyDirs = make(map[string][]string)
}
cfg.RigPackGraphOnlyDirs[rig.Name] = rigPackGraphOnlyDirs
}
if len(rigImportPackDirs) > 0 {
if cfg.RigImportPackDirs == nil {
cfg.RigImportPackDirs = make(map[string][]string)
}
cfg.RigImportPackDirs[rig.Name] = rigImportPackDirs
}
// Collect overlay/ dirs from rig pack dirs.
var rigOverlayDirs []string
for _, dir := range rigTopoDirs {
od := filepath.Join(dir, "overlay")
if info, sErr := fs.Stat(od); sErr == nil && info.IsDir() {
rigOverlayDirs = appendUnique(rigOverlayDirs, od)
}
}
if len(rigOverlayDirs) > 0 {
if cfg.RigOverlayDirs == nil {
cfg.RigOverlayDirs = make(map[string][]string)
}
cfg.RigOverlayDirs[rig.Name] = rigOverlayDirs
}
// Resolve fallback agents before collision detection.
rigAgents = resolveFallbackAgents(rigAgents)
// Check for duplicate agent names across packs for this rig.
if err := checkPackAgentCollisions(rigAgents, rig.Name); err != nil {
return err
}
// Apply per-rig overrides/patches after all packs for this rig.
// V2 accepts both "overrides" (V1) and "patches" (V2) TOML keys.
allOverrides := rig.Overrides
allOverrides = append(allOverrides, rig.RigPatches...)
if err := applyOverrides(rigAgents, allOverrides, rig.Name); err != nil {
return fmt.Errorf("rig %q: %w", rig.Name, err)
}
// Store rig-level pack globals.
if len(rigGlobals) > 0 {
if cfg.RigPackGlobals == nil {
cfg.RigPackGlobals = make(map[string][]ResolvedPackGlobal)
}
cfg.RigPackGlobals[rig.Name] = rigGlobals
}
expanded = append(expanded, rigAgents...)
cfg.NamedSessions = append(cfg.NamedSessions, rigNamedSessions...)
}
cfg.Agents = append(cfg.Agents, expanded...)
return nil
}
// ExpandCityPacks loads all city-level packs from workspace.includes (V1)
// and city-level [imports.X] (V2). City pack agents are stamped with
// dir="" (city-scoped) and prepended to the agent list. Returns
// (formulaDirs, packRequirements, shadowWarnings, error). cityRoot is
// the city directory.
func ExpandCityPacks(cfg *City, fs fsys.FS, cityRoot string) ([]string, []PackRequirement, []string, error) {
return expandCityPacks(cfg, fs, cityRoot, LoadOptions{})
}
func expandCityPacks(cfg *City, fs fsys.FS, cityRoot string, opts LoadOptions) ([]string, []PackRequirement, []string, error) {
topos := cfg.Workspace.Includes
hasImports := len(cfg.Imports) > 0
if len(topos) == 0 && !hasImports {
return nil, nil, nil, nil
}
var allAgents []Agent
var allNamedSessions []NamedSession
var formulaDirs []string
var allPackDirs []string
var packGraphOnlyDirs []string
var explicitImportPackDirs []string
var implicitImportPackDirs []string
var bootstrapImportPackDirs []string
var allRequires []PackRequirement
var allGlobals []ResolvedPackGlobal
var packWarnings []string
// Shared cache across all pack loads to deduplicate diamond DAGs.
cache := &packLoadCache{results: make(map[string]*packLoadResult)}
for _, ref := range topos {
topoDir, err := resolvePackRef(ref, cityRoot, cityRoot)
if err != nil {
// Pack directory may have been removed upstream (e.g. renamed/deleted
// in the remote repo). Skip gracefully so the rest of the city loads.
if errors.Is(err, iofs.ErrNotExist) {
log.Printf("city pack %q: not found, skipping: %v", ref, err)
continue
}
return nil, nil, nil, fmt.Errorf("city pack %q: %w", ref, err)
}
topoPath := filepath.Join(topoDir, packFile)
// For remote includes, skip gracefully if the subpath was
// deleted upstream (the git fetch succeeded but the path no
// longer exists in the repo).
if isRemoteRef(ref) {
if _, sErr := fs.Stat(topoPath); sErr != nil {
log.Printf("city pack %q: not found, skipping: %v", ref, sErr)
continue
}
}
agents, namedSessions, providers, services, topoDirs, reqs, globals, err := loadPackWithCacheOptions(fs, topoPath, topoDir, cityRoot, "", nil, cache, opts)
if err != nil {
// pack.toml may be missing if the pack was removed upstream after
// the repo was fetched. Skip gracefully.
if errors.Is(err, iofs.ErrNotExist) {
log.Printf("city pack %q: not found, skipping: %v", ref, err)
continue
}
return nil, nil, nil, fmt.Errorf("city pack %q: %w", ref, err)
}
packWarnings = appendUnique(packWarnings, cachedPackWarnings(cache, topoDir)...)
allRequires = append(allRequires, reqs...)
allGlobals = append(allGlobals, globals...)
cfg.Services = append(cfg.Services, services...)
packName := tcPackName(fs, topoPath)
if packName == "" && len(cachedPackCommands(cache, topoDir)) > 0 {
return nil, nil, nil, fmt.Errorf("city pack %q: discovered commands require [pack].name for CLI binding", ref)
}
cfg.PackCommands = appendDiscoveredCommands(cfg.PackCommands, stampDefaultBinding(cachedPackCommands(cache, topoDir), packName)...)
cfg.PackDoctors = appendDiscoveredDoctors(cfg.PackDoctors, cachedPackDoctors(cache, topoDir)...)
skills := cachedPackSkills(cache, topoDir)
if packName == "" && len(skills) > 0 {
return nil, nil, nil, fmt.Errorf("city pack %q: discovered skills require [pack].name for shared binding", ref)
}
cfg.PackSkills = appendDiscoveredSkills(cfg.PackSkills, stampSkillBinding(skills, packName)...)
// Accumulate pack dirs (deduped).
allPackDirs = appendUnique(allPackDirs, topoDirs...)
packGraphOnlyDirs = appendUniqueLastWins(packGraphOnlyDirs, topoDirs...)
// Keep only city-scoped and unscoped agents for city expansion.
agents = filterAgentsByScope(agents, true)
namedSessions = filterNamedSessionsByScope(namedSessions, true)
allAgents = append(allAgents, agents...)
allNamedSessions = append(allNamedSessions, namedSessions...)
// Derive formula dirs from pack dirs.
for _, td := range topoDirs {
fd := filepath.Join(td, "formulas")
if _, sErr := fs.Stat(fd); sErr == nil {
formulaDirs = append(formulaDirs, fd)
}
}
// Merge pack providers (additive, first wins).
if len(providers) > 0 {
if cfg.Providers == nil {
cfg.Providers = make(map[string]ProviderSpec)
}
for name, spec := range providers {
if _, exists := cfg.Providers[name]; !exists {
cfg.Providers[name] = spec
}
}
}
}
// Process city-level [imports.X] entries (V2). These produce agents
// with qualified names (bindingName.agentName). Processed after V1
// includes so imports can coexist during migration.
if hasImports {
importNames := make([]string, 0, len(cfg.Imports))
for name := range cfg.Imports {
importNames = append(importNames, name)
}
sort.Strings(importNames)
for _, bindingName := range importNames {
imp := cfg.Imports[bindingName]
if cfg.ImplicitImportBindings != nil && cfg.ImplicitImportBindings[bindingName] {
continue
}
// Unlike V1 includes (which skip gracefully for missing remote
// subpaths), V2 imports are always fatal on missing source.
// A typo in [imports.X].source should not be silently ignored.
impDir, err := resolveImportPackRef(imp.Source, cityRoot, cityRoot)
if err != nil {
return nil, nil, nil, fmt.Errorf("city import %q: %w", bindingName, err)
}
impPath := filepath.Join(impDir, packFile)
agents, namedSessions, providers, services, topoDirs, reqs, globals, err := loadPackWithCacheOptions(
fs, impPath, impDir, cityRoot, "", nil, cache, opts)
if err != nil {
return nil, nil, nil, fmt.Errorf("city import %q: %w", bindingName, err)
}
warnings := cachedPackWarnings(cache, impDir)
if !imp.ImportIsTransitive() {
warnings = cachedPackLocalWarnings(cache, impDir)
}
packWarnings = appendUnique(packWarnings, warnings...)
commands := cachedPackCommands(cache, impDir)
doctors := cachedPackDoctors(cache, impDir)
skills := cachedPackSkills(cache, impDir)
mcpTopoDirs := topoDirs
// by this import. Nested pack dependencies reached through
// either [imports] or legacy [pack].includes stay hidden from
// the consumer.
if !imp.ImportIsTransitive() {
absImpDir, _ := filepath.Abs(impDir)
var direct []Agent
for _, a := range agents {
absSrc, _ := filepath.Abs(a.SourceDir)
if absSrc == absImpDir {
direct = append(direct, a)
}
}
agents = direct
namedSessions = filterNamedSessionsBySourceDir(namedSessions, impDir)
services = filterServicesBySourceDir(services, impDir)
commands = filterCommandsByPackDir(commands, impDir)
doctors = filterDoctorsByPackDir(doctors, impDir)
providers = cachedPackLocalProviders(cache, impDir)
topoDirs = cachedPackLocalTopoDirs(cache, impDir)
reqs = cachedPackLocalRequires(cache, impDir)
globals = cachedPackLocalGlobals(cache, impDir)
skills = filterSkillsByPackDir(skills, impDir)
mcpTopoDirs = filterPackDirsByRoot(topoDirs, impDir)
}
// Stamp binding name on all agents and named sessions.
// At the city level, ALL agents from an import get the city's
// binding — any nested bindings are overridden because the city
// is the root of composition and its binding is the user-visible one.
for i := range agents {
agents[i].BindingName = bindingName
}
for i := range namedSessions {
namedSessions[i].BindingName = bindingName
}
// Re-qualify depends_on with binding name.
for i := range agents {
if agents[i].BindingName == "" || len(agents[i].DependsOn) == 0 {
continue
}
for j, dep := range agents[i].DependsOn {
_, depName := ParseQualifiedName(dep)
if !strings.Contains(depName, ".") {
binding := agents[i].BindingName
if agents[i].Dir != "" {
agents[i].DependsOn[j] = agents[i].Dir + "/" + binding + "." + depName
} else {
agents[i].DependsOn[j] = binding + "." + depName
}
}
}
}
for i := range commands {
if commands[i].BindingName == "" {
commands[i].BindingName = bindingName
} else if imp.Export {
commands[i].BindingName = bindingName
}
}
for i := range doctors {
if doctors[i].BindingName == "" {
doctors[i].BindingName = bindingName
} else if imp.Export {
doctors[i].BindingName = bindingName
}
}
// Read imported pack name for provenance.
impData, readErr := fs.ReadFile(impPath)
if readErr != nil {
return nil, nil, nil, fmt.Errorf("city import %q: reading %s: %w", bindingName, impPath, readErr)
}
packName, err := decodePackName(impData)
if err != nil {
return nil, nil, nil, fmt.Errorf("city import %q: parsing %s: %w", bindingName, impPath, err)
}
for i := range agents {
if agents[i].PackName == "" {
agents[i].PackName = packName
}
}
for i := range commands {
if commands[i].PackName == "" {
commands[i].PackName = packName
}
}
for i := range doctors {
if doctors[i].PackName == "" {
doctors[i].PackName = packName
}
}
allRequires = append(allRequires, reqs...)
allGlobals = append(allGlobals, globals...)
cfg.Services = append(cfg.Services, services...)
cfg.PackCommands = appendDiscoveredCommands(cfg.PackCommands, commands...)
cfg.PackDoctors = appendDiscoveredDoctors(cfg.PackDoctors, doctors...)
if !slices.Contains(BootstrapManagedImportNames(), bindingName) {
cfg.PackSkills = appendDiscoveredSkills(cfg.PackSkills, stampImportedSkillBinding(skills, bindingName, imp.Export)...)
}
allPackDirs = appendUnique(allPackDirs, topoDirs...)
switch {
case cfg.BootstrapImportBindings != nil && cfg.BootstrapImportBindings[bindingName]:
bootstrapImportPackDirs = prependUniqueBlock(bootstrapImportPackDirs, mcpTopoDirs...)
cfg.BootstrapImportMCPBindings = stampMCPDirBindings(cfg.BootstrapImportMCPBindings, mcpTopoDirs, bindingName)
case cfg.ImplicitImportBindings != nil && cfg.ImplicitImportBindings[bindingName]:
implicitImportPackDirs = prependUniqueBlock(implicitImportPackDirs, mcpTopoDirs...)
cfg.ImplicitImportMCPBindings = stampMCPDirBindings(cfg.ImplicitImportMCPBindings, mcpTopoDirs, bindingName)
default:
explicitImportPackDirs = prependUniqueBlock(explicitImportPackDirs, mcpTopoDirs...)
cfg.ExplicitImportMCPBindings = stampMCPDirBindings(cfg.ExplicitImportMCPBindings, mcpTopoDirs, bindingName)
}
// Filter by scope for city expansion.
agents = filterAgentsByScope(agents, true)
namedSessions = filterNamedSessionsByScope(namedSessions, true)
allAgents = append(allAgents, agents...)
allNamedSessions = append(allNamedSessions, namedSessions...)
// Derive formula dirs.
for _, td := range topoDirs {
fd := filepath.Join(td, "formulas")
if _, sErr := fs.Stat(fd); sErr == nil {
formulaDirs = append(formulaDirs, fd)
}
}
// Merge providers (additive, first wins).
if len(providers) > 0 {
if cfg.Providers == nil {
cfg.Providers = make(map[string]ProviderSpec)
}
for name, spec := range providers {
if _, exists := cfg.Providers[name]; !exists {
cfg.Providers[name] = spec
}
}
}
}
}
// Store city pack dirs.
cfg.PackDirs = appendUnique(cfg.PackDirs, allPackDirs...)
cfg.PackGraphOnlyDirs = appendUniqueLastWins(cfg.PackGraphOnlyDirs, packGraphOnlyDirs...)
cfg.ExplicitImportPackDirs = appendUniqueLastWins(cfg.ExplicitImportPackDirs, explicitImportPackDirs...)
cfg.ImplicitImportPackDirs = appendUniqueLastWins(cfg.ImplicitImportPackDirs, implicitImportPackDirs...)
cfg.BootstrapImportPackDirs = appendUniqueLastWins(cfg.BootstrapImportPackDirs, bootstrapImportPackDirs...)
// Collect overlay/ dirs from pack dirs.
for _, dir := range allPackDirs {
od := filepath.Join(dir, "overlay")
if info, err := fs.Stat(od); err == nil && info.IsDir() {
cfg.PackOverlayDirs = appendUnique(cfg.PackOverlayDirs, od)
}
}
// Resolve fallback agents before collision detection.
allAgents = resolveFallbackAgents(allAgents)
// Check for duplicate agent names across city packs.
if err := checkPackAgentCollisions(allAgents, ""); err != nil {
return nil, nil, nil, err
}
// City pack agents go at the front (before user-defined agents).
// Run fallback dedup again on the combined set so system pack
// fallback agents yield to inline city-level agents.
cfg.Agents = resolveFallbackAgents(append(allAgents, cfg.Agents...))
cfg.NamedSessions = append(allNamedSessions, cfg.NamedSessions...)
// Detect shadow conflicts: city-local agents masking imported agents.
// A city agent (BindingName == "") with the same bare Name as an
// imported agent (BindingName != "") shadows it. Warn unless the
// import has shadow = "silent".
var shadowWarnings []string
if hasImports {
// Build set of imported agent bare names → binding name.
importedNames := make(map[string]string) // bare name → binding
for _, a := range cfg.Agents {
if a.BindingName != "" && a.Dir == "" {
importedNames[a.Name] = a.BindingName
}
}
// Check city-local agents against imported names.
for _, a := range cfg.Agents {
if a.BindingName == "" && a.Dir == "" && !a.Implicit {
if binding, ok := importedNames[a.Name]; ok {
// Check if this import has shadow = "silent".
if imp, impOk := cfg.Imports[binding]; impOk && imp.Shadow == "silent" {
continue
}
shadowWarnings = append(shadowWarnings,
fmt.Sprintf("city agent %q shadows agent of the same name from import %q (set shadow = \"silent\" on [imports.%s] to suppress)", a.Name, binding, binding))
}
}
}
}
// Store city-level pack globals.
cfg.PackGlobals = append(cfg.PackGlobals, allGlobals...)
shadowWarnings = appendUnique(shadowWarnings, packWarnings...)
return formulaDirs, allRequires, shadowWarnings, nil
}
func resolveImportPackRef(ref, declDir, cityRoot string) (string, error) {
if isGitHubTreeURL(ref) {
_, subpath, _ := parseGitHubTreeURL(ref)
cacheDir, err := resolveInstalledRemoteImport(ref, cityRoot)
if err != nil {
return "", err
}
if subpath != "" {
return filepath.Join(cacheDir, subpath), nil
}
return cacheDir, nil
}
if isRemoteInclude(ref) {
_, subpath, _ := parseRemoteInclude(ref)
cacheDir, err := resolveInstalledRemoteImport(ref, cityRoot)
if err != nil {
return "", err
}
if subpath != "" {
return filepath.Join(cacheDir, subpath), nil
}
return cacheDir, nil
}
return resolvePackRef(ref, declDir, cityRoot)
}
// ComputeFormulaLayers builds the FormulaLayers from the resolved formula
// directories. Each layer slice is ordered lowest→highest priority.
//
// Parameters:
// - cityTopoFormulas: formula dirs from city packs (Layer 1), nil if none
// - cityLocalFormulas: formula dir from city [formulas] section (Layer 2), "" if none
// - rigTopoFormulas: map[rigName][]formulaDirs from rig packs (Layer 3)
// - rigs: rig configs (for rig-local FormulasDir, Layer 4)
// - cityRoot: city directory for resolving relative paths
func ComputeFormulaLayers(cityTopoFormulas []string, cityLocalFormulas string, rigTopoFormulas map[string][]string, rigs []Rig, cityRoot string) FormulaLayers {
fl := FormulaLayers{
Rigs: make(map[string][]string),
}
// City layers (apply to city-scoped agents and as base for all rigs).
var cityLayers []string
cityLayers = append(cityLayers, cityTopoFormulas...)
if cityLocalFormulas != "" {
cityLayers = append(cityLayers, cityLocalFormulas)
}
fl.City = cityLayers
// Per-rig layers: city layers + rig pack + rig local.
for _, r := range rigs {
layers := make([]string, len(cityLayers))
copy(layers, cityLayers)
if fds, ok := rigTopoFormulas[r.Name]; ok {
layers = append(layers, fds...)
}
if r.FormulasDir != "" {
rigLocalDir := resolveConfigPath(r.FormulasDir, cityRoot, cityRoot)
layers = append(layers, rigLocalDir)
}
if len(layers) > 0 {
fl.Rigs[r.Name] = layers
}
}
return fl
}
// resolveFallbackAgents resolves fallback agent collisions. When agents
// from different SourceDirs share a name:
// - One fallback + one non-fallback: non-fallback wins, fallback removed
// - Both fallback: first loaded wins (depth-first include order)
// - Neither fallback: left for checkPackAgentCollisions to error
//
// Agents from the same SourceDir are never in conflict (they're duplicates
// within one pack, handled elsewhere). Order is preserved.
func resolveFallbackAgents(agents []Agent) []Agent {
// Build per-name groups from distinct SourceDirs.
type entry struct {
idx int
fallback bool
srcDir string
}
groups := make(map[string][]entry)
for i, a := range agents {
// Use QualifiedName so agents with different bindings
// (e.g., "gs.mayor" and "maint.mayor") don't collide.
groups[a.QualifiedName()] = append(groups[a.QualifiedName()], entry{i, a.Fallback, a.SourceDir})
}
// Determine which indices to remove.
remove := make(map[int]bool)
for _, entries := range groups {
// Only care about names from multiple sources.
// Empty SourceDir means city-level (inline) — count it as a
// distinct source so system pack fallbacks yield to inline agents.
dirs := make(map[string]bool)
for _, e := range entries {
dirs[e.srcDir] = true // "" is a valid key (city-level)
}
if len(dirs) < 2 {
continue
}
// Separate fallback vs non-fallback entries.
var fb, nonfb []entry
for _, e := range entries {
if e.fallback {
fb = append(fb, e)
} else {
nonfb = append(nonfb, e)
}
}
if len(nonfb) > 0 && len(fb) > 0 {
// Non-fallback wins: remove all fallback entries.
for _, e := range fb {
remove[e.idx] = true
}
} else if len(nonfb) == 0 && len(fb) > 1 {
// All fallback: keep first, remove rest.
for _, e := range fb[1:] {
remove[e.idx] = true
}
}
// Both non-fallback: leave alone for collision detection.
}
if len(remove) == 0 {
return agents
}
result := make([]Agent, 0, len(agents)-len(remove))
for i, a := range agents {
if !remove[i] {
result = append(result, a)
}
}
return result
}
// checkPackAgentCollisions detects duplicate agent names within
// pack-expanded agents and returns an error with provenance (which
// pack directories defined the conflicting agents). rigName is used
// for the error message context; pass "" for city-scoped agents.
func checkPackAgentCollisions(agents []Agent, rigName string) error {
// Map agent qualified name → list of source directories that defined it.
// Uses QualifiedName so agents with different bindings (e.g.,
// "gs.mayor" and "maint.mayor") don't collide.
sources := make(map[string][]string)
for _, a := range agents {
src := a.SourceDir
if src == "" {
continue // inline agents have no SourceDir
}
qn := a.QualifiedName()
existing := sources[qn]
if !slices.Contains(existing, src) {
sources[qn] = append(existing, src)
}
}
for name, dirs := range sources {
if len(dirs) < 2 {
continue
}
scope := "city"
if rigName != "" {
scope = fmt.Sprintf("rig %q", rigName)
}
return fmt.Errorf("%s: packs define duplicate agent %q:\n - %s\nrename one agent in its pack.toml, or use separate rigs",
scope, name, strings.Join(dirs, "\n - "))
}
return nil
}
// loadPack loads a pack.toml, validates metadata, and returns the
// agent list with dir stamped and paths adjusted, and the ordered pack
// directories.
//
// The topoDirs return is the ordered list: included pack dirs first
// (depth-first), then this pack's dir. Consumers derive resource paths
// from these dirs (e.g., formulas/, prompts/shared/).
//
// The seen set tracks visited pack directories for cycle detection.
// Pass nil for the initial call; it will be initialized automatically.
// Includes are processed recursively: included agents come first (base
// layer), then the parent's own agents (override layer).
// packLoadCache caches results from loadPack to avoid loading the same
// pack directory twice in a diamond-shaped DAG (A→B→D, A→C→D). The
// cache is keyed by absolute directory path.
type packLoadCache struct {
results map[string]*packLoadResult
}
type packLoadResult struct {
agents []Agent
namedSessions []NamedSession
providers map[string]ProviderSpec
localProviders map[string]ProviderSpec
services []Service
topoDirs []string
localTopoDirs []string
requires []PackRequirement
localRequires []PackRequirement
globals []ResolvedPackGlobal
localGlobals []ResolvedPackGlobal
commands []DiscoveredCommand
doctors []DiscoveredDoctor
skills []DiscoveredSkillCatalog
localWarnings []string
warnings []string
}
func parsePackConfigWithMeta(data []byte, source string) (packConfig, []string, error) {
cfg, _, warnings, err := parsePackConfigWithMetadata(data, source)