Repository navigation
Expand file tree
/
Copy pathtool.go
More file actions
2636 lines (2363 loc) · 78.7 KB
/
Copy pathtool.go
File metadata and controls
2636 lines (2363 loc) · 78.7 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package cmd
import (
"context"
"errors"
"fmt"
"io"
"maps"
"slices"
"strings"
"text/tabwriter"
"time"
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/internal"
"github.com/azure/azure-dev/cli/azd/internal/tracing"
"github.com/azure/azure-dev/cli/azd/internal/tracing/fields"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/output/ux"
"github.com/azure/azure-dev/cli/azd/pkg/tool"
uxlib "github.com/azure/azure-dev/cli/azd/pkg/ux"
"github.com/spf13/cobra"
"go.opentelemetry.io/otel/attribute"
)
// singleResultCommonAttrs returns the usage attributes shared by single-target
// `azd tool install` and `azd tool update`: success, tool.id, and the
// installation strategy. Callers append update-specific version attrs
// (tool.update.{from,to}_version) on top.
//
// Returns nil if r is nil so callers can safely pass through results without
// pre-validating the slice element.
func singleResultCommonAttrs(r *tool.InstallResult) []attribute.KeyValue {
if r == nil {
return nil
}
attrs := []attribute.KeyValue{
fields.ToolInstallSuccessKey.Bool(r.Success),
}
if r.Tool != nil {
attrs = append(attrs, fields.ToolIdKey.String(r.Tool.Id))
}
if r.Strategy != "" {
attrs = append(attrs, fields.ToolInstallStrategyKey.String(r.Strategy))
}
return attrs
}
// emitToolInstallTelemetry emits aggregate telemetry attributes for a batch
// install or upgrade operation. When the batch contains exactly one tool the
// caller is responsible for also emitting tool.id, tool.install.strategy, and
// tool.install.success (and, for updates, tool.update.{from,to}_version).
//
// When the batch infrastructure itself fails (opErr != nil and results is
// empty) every requested tool is counted as a failure and its ID is added to
// failed_ids. This preserves the invariant
// success_count + failure_count == len(requested) and prevents a hard
// operation error from being indistinguishable from a no-op.
func emitToolInstallTelemetry(
results []*tool.InstallResult,
elapsed time.Duration,
opErr error,
requested []*tool.ToolDefinition,
) {
requestedIDs := make([]string, 0, len(requested))
for _, t := range requested {
if t != nil {
requestedIDs = append(requestedIDs, t.Id)
}
}
successCount, failureCount, sortedFailedIDs := tool.AggregateInstallResults(results, opErr, requestedIDs)
attrs := []attribute.KeyValue{
fields.ToolInstallSuccessCountKey.Int(successCount),
fields.ToolInstallFailureCountKey.Int(failureCount),
fields.ToolInstallDurationMsKey.Int64(elapsed.Milliseconds()),
}
if len(sortedFailedIDs) > 0 {
attrs = append(attrs,
fields.ToolInstallFailedIdsKey.String(strings.Join(sortedFailedIDs, ",")),
)
}
tracing.SetUsageAttributes(attrs...)
}
// toolActions registers the "azd tool" command group and all of its subcommands.
func toolActions(root *actions.ActionDescriptor) *actions.ActionDescriptor {
toolCmd := &cobra.Command{
Use: "tool",
Short: "Manage Azure development tools.",
Long: "Discover, install, update, and check status of Azure development tools.",
}
group := root.Add("tool", &actions.ActionDescriptorOptions{
Command: toolCmd,
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupManage,
},
ActionResolver: newToolAction,
})
// azd tool list
group.Add("list", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "list",
Short: "List all tools with status.",
},
OutputFormats: []output.Format{output.JsonFormat, output.TableFormat},
DefaultFormat: output.TableFormat,
ActionResolver: newToolListAction,
})
// azd tool install [tool-name...]
group.Add("install", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "install [tool-name...]",
Short: "Install specified tools.",
},
OutputFormats: []output.Format{output.JsonFormat, output.NoneFormat},
DefaultFormat: output.NoneFormat,
ActionResolver: newToolInstallAction,
FlagsResolver: newToolInstallFlags,
})
// azd tool update [tool-name...]
group.Add("update", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "update [tool-name...]",
Aliases: []string{"upgrade"},
Short: "Update installed tools.",
},
OutputFormats: []output.Format{output.JsonFormat, output.NoneFormat},
DefaultFormat: output.NoneFormat,
ActionResolver: newToolUpgradeAction,
FlagsResolver: newToolUpgradeFlags,
})
// azd tool uninstall [tool-name...]
group.Add("uninstall", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "uninstall [tool-name...]",
Short: "Uninstall installed tools.",
},
OutputFormats: []output.Format{output.JsonFormat, output.NoneFormat},
DefaultFormat: output.NoneFormat,
ActionResolver: newToolUninstallAction,
FlagsResolver: newToolUninstallFlags,
})
// azd tool check
group.Add("check", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "check",
Short: "Check for tool updates.",
},
OutputFormats: []output.Format{output.JsonFormat, output.TableFormat},
DefaultFormat: output.TableFormat,
ActionResolver: newToolCheckAction,
})
// azd tool show <tool-name>
group.Add("show", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "show <tool-name>",
Short: "Show details for a specific tool.",
},
OutputFormats: []output.Format{output.JsonFormat, output.NoneFormat},
DefaultFormat: output.NoneFormat,
ActionResolver: newToolShowAction,
})
return group
}
// ---------------------------------------------------------------------------
// azd tool (bare command) — interactive flow
// ---------------------------------------------------------------------------
type toolAction struct {
manager *tool.Manager
console input.Console
writer io.Writer
}
func newToolAction(
manager *tool.Manager,
console input.Console,
writer io.Writer,
) actions.Action {
return &toolAction{
manager: manager,
console: console,
writer: writer,
}
}
func (a *toolAction) Run(ctx context.Context) (*actions.ActionResult, error) {
a.console.MessageUxItem(ctx, &ux.MessageTitle{
Title: "Azure Development Tools (azd tool)",
TitleNote: "Discover and install tools for Azure development",
})
// 1. Detect all tools.
var statuses []*tool.ToolStatus
spinner := uxlib.NewSpinner(&uxlib.SpinnerOptions{
Text: "Detecting tools...",
ClearOnStop: true,
Writer: a.writer,
})
if err := spinner.Run(ctx, func(ctx context.Context) error {
var detectErr error
statuses, detectErr = a.manager.DetectAll(ctx)
return detectErr
}); err != nil {
return nil, fmt.Errorf("detecting tools: %w", err)
}
// 2. Display current status.
a.console.Message(ctx, "")
for _, s := range statuses {
if s.Installed {
version := s.InstalledVersion
if version == "" {
version = "unknown"
}
a.console.Message(ctx, fmt.Sprintf(
" %s %s %s",
output.WithSuccessFormat("(✔)"),
s.Tool.Name,
output.WithGrayFormat("(%s)", version),
))
} else if s.Tool.Priority == tool.ToolPriorityRecommended {
a.console.Message(ctx, fmt.Sprintf(
" %s %s %s",
output.WithWarningFormat("(○)"),
s.Tool.Name,
output.WithWarningFormat("[recommended]"),
))
} else {
a.console.Message(ctx, fmt.Sprintf(
" %s %s %s",
output.WithGrayFormat("(○)"),
s.Tool.Name,
output.WithGrayFormat("[optional]"),
))
}
}
a.console.Message(ctx, "")
// 3. Collect uninstalled tools for interactive selection.
var uninstalled []*tool.ToolStatus
for _, s := range statuses {
if !s.Installed {
uninstalled = append(uninstalled, s)
}
}
if len(uninstalled) == 0 {
a.console.Message(ctx, output.WithSuccessFormat("All tools are installed!"))
return &actions.ActionResult{
Message: &actions.ResultMessage{
Header: "All tools are already installed",
},
}, nil
}
// 4. MultiSelect uninstalled tools.
choices := make([]*uxlib.MultiSelectChoice, len(uninstalled))
for i, s := range uninstalled {
choices[i] = &uxlib.MultiSelectChoice{
Value: s.Tool.Id,
Label: s.Tool.Name,
Selected: s.Tool.Priority == tool.ToolPriorityRecommended,
}
}
multiSelect := uxlib.NewMultiSelect(&uxlib.MultiSelectOptions{
Writer: a.console.Handles().Stdout,
Reader: a.console.Handles().Stdin,
Message: "Select tools to install",
Choices: choices,
})
selected, err := multiSelect.Ask(ctx)
if err != nil {
return nil, fmt.Errorf("selecting tools: %w", err)
}
// 5. Install selected tools using TaskList.
var ids []string
for _, choice := range selected {
if choice.Selected {
ids = append(ids, choice.Value)
}
}
if len(ids) == 0 {
return nil, nil
}
tools := make([]*tool.ToolDefinition, 0, len(ids))
for _, id := range ids {
toolDef, findErr := a.manager.FindTool(id)
if findErr != nil {
return nil, findErr
}
tools = append(tools, toolDef)
}
operationFn := func(ctx context.Context, allIDs []string) ([]*tool.InstallResult, error) {
return a.manager.InstallTools(ctx, allIDs)
}
_ = runToolOperation(ctx, tools, operationFn, "Installing", "install", a.console, false)
// runToolOperation already displayed warnings; we intentionally
// discard the outcome here — child tasks have surfaced what the user
// needs to see, and this caller does not propagate the task error.
header := "Your tool is installed."
if len(tools) > 1 {
header = "Your tools are installed."
}
return &actions.ActionResult{
Message: &actions.ResultMessage{
Header: header,
},
}, nil
}
// ---------------------------------------------------------------------------
// azd tool list
// ---------------------------------------------------------------------------
type toolListItem struct {
Id string `json:"id"`
Name string `json:"name"`
// Agent is the agent CLI a skill row is installed through (e.g.
// "copilot"), empty for non-skill tools.
Agent string `json:"agent,omitempty"`
Category string `json:"category"`
Priority string `json:"priority"`
Status string `json:"status"`
Version string `json:"version"`
// DisplayName is the NAME cell shown in the table: a skill row is
// prefixed with its agent label (e.g. "[Copilot] Azure Skills"), other
// rows use the plain name. Excluded from JSON, which carries Name + Agent.
DisplayName string `json:"-"`
}
type toolListAction struct {
manager *tool.Manager
console input.Console
formatter output.Formatter
writer io.Writer
}
func newToolListAction(
manager *tool.Manager,
console input.Console,
formatter output.Formatter,
writer io.Writer,
) actions.Action {
return &toolListAction{
manager: manager,
console: console,
formatter: formatter,
writer: writer,
}
}
func (a *toolListAction) Run(ctx context.Context) (*actions.ActionResult, error) {
var statuses []*tool.ToolStatus
if a.formatter.Kind() != output.JsonFormat {
spinner := uxlib.NewSpinner(&uxlib.SpinnerOptions{
Text: "Checking tool status...",
ClearOnStop: true,
Writer: a.writer,
})
if err := spinner.Run(ctx, func(ctx context.Context) error {
var detectErr error
statuses, detectErr = a.manager.DetectAll(ctx)
return detectErr
}); err != nil {
return nil, fmt.Errorf("detecting tools: %w", err)
}
} else {
var err error
statuses, err = a.manager.DetectAll(ctx)
if err != nil {
return nil, fmt.Errorf("detecting tools: %w", err)
}
}
rows := make([]toolListItem, 0, len(statuses))
for _, s := range statuses {
// A skill installed on one or more agents expands into one row per
// agent, each prefixed with the agent label (e.g. "[Copilot] ...").
if s.Tool.Category == tool.ToolCategorySkill && len(s.SkillAgents) > 0 {
for _, h := range s.SkillAgents {
rows = append(rows, toolListItem{
Id: s.Tool.Id,
Name: s.Tool.Name,
Agent: h.Agent,
DisplayName: fmt.Sprintf("[%s] %s",
skillAgentDisplayName(s.Tool, h.Agent), s.Tool.Name),
Category: string(s.Tool.Category),
Priority: string(s.Tool.Priority),
Status: "Installed",
Version: h.Version,
})
}
continue
}
status := "Not installed"
version := ""
if s.Installed {
status = "Installed"
version = s.InstalledVersion
}
rows = append(rows, toolListItem{
Id: s.Tool.Id,
Name: s.Tool.Name,
DisplayName: s.Tool.Name,
Category: string(s.Tool.Category),
Priority: string(s.Tool.Priority),
Status: status,
Version: version,
})
}
if len(rows) == 0 {
a.console.Message(ctx, output.WithWarningFormat("No tools found in the registry."))
return nil, nil
}
var formatErr error
if a.formatter.Kind() == output.TableFormat {
prettyFormatter := &output.PrettyTableFormatter{}
columns := []output.PrettyColumn{
{
Column: output.Column{Heading: "ID", ValueTemplate: "{{.Id}}"},
Priority: 1,
},
{
Column: output.Column{Heading: "NAME", ValueTemplate: "{{.DisplayName}}"},
Priority: 2,
CardTitle: true,
Wrappable: true,
Truncatable: true,
ColorFunc: colorAgentPrefix,
},
{
Column: output.Column{Heading: "STATUS", ValueTemplate: "{{.Status}}"},
Priority: 1,
Truncatable: true,
ColorFunc: toolStatusColor,
},
{
Column: output.Column{
Heading: "INSTALLED",
ValueTemplate: `{{if .Version}}{{.Version}}{{else}}-{{end}}`,
},
CardValueTemplate: `{{if .Version}}{{.Version}}{{end}}`,
Priority: 1,
},
{
Column: output.Column{Heading: "CATEGORY", ValueTemplate: "{{.Category}}"},
Priority: 3,
Truncatable: true,
},
}
formatErr = prettyFormatter.Format(rows, a.writer, output.PrettyTableFormatterOptions{
Columns: columns,
CardGroupColumn: "CATEGORY",
ResponsiveColumnHint: true,
})
} else {
formatErr = a.formatter.Format(rows, a.writer, nil)
}
return nil, formatErr
}
// ---------------------------------------------------------------------------
// azd tool install [tool-name...]
// ---------------------------------------------------------------------------
type toolInstallFlags struct {
all bool
agents []string
dryRun bool
}
func newToolInstallFlags(cmd *cobra.Command) *toolInstallFlags {
flags := &toolInstallFlags{}
cmd.Flags().BoolVar(
&flags.all, "all", false, "Install all recommended tools",
)
cmd.Flags().StringSliceVar(
&flags.agents, "agent", nil,
"Install the skill for the specified agent(s): copilot, claude. "+
"Use --agent all for every detected agent (skill tools only)",
)
cmd.Flags().BoolVar(
&flags.dryRun, "dry-run", false,
"Preview what would be installed without making changes",
)
return flags
}
type toolInstallAction struct {
args []string
flags *toolInstallFlags
manager *tool.Manager
console input.Console
formatter output.Formatter
writer io.Writer
}
func newToolInstallAction(
args []string,
flags *toolInstallFlags,
manager *tool.Manager,
console input.Console,
formatter output.Formatter,
writer io.Writer,
) actions.Action {
return &toolInstallAction{
args: args,
flags: flags,
manager: manager,
console: console,
formatter: formatter,
writer: writer,
}
}
func (a *toolInstallAction) Run(ctx context.Context) (*actions.ActionResult, error) {
ids, err := a.resolveToolIds(ctx)
if err != nil {
return nil, err
}
if len(ids) == 0 {
if a.formatter.Kind() == output.JsonFormat {
// Keep a stable array schema for automation instead of a
// consoleMessage object.
return nil, a.formatter.Format([]*toolInstallResultItem{}, a.writer, nil)
}
a.console.Message(ctx, output.WithSuccessFormat("Nothing to install."))
return nil, nil
}
// --dry-run: detect tool status and display what would happen
// without actually installing anything.
if a.flags.dryRun {
return a.dryRun(ctx, ids)
}
if a.formatter.Kind() != output.JsonFormat {
a.console.MessageUxItem(ctx, &ux.MessageTitle{
Title: "Install Azure development tools (azd tool install)",
TitleNote: "Installs specified tools onto the local machine",
})
}
tools := make([]*tool.ToolDefinition, 0, len(ids))
resolvedIDs := make([]string, 0, len(ids))
for _, id := range ids {
toolDef, findErr := a.manager.FindTool(id)
if findErr != nil {
return nil, wrapToolNotFoundIfErr(findErr)
}
tools = append(tools, toolDef)
resolvedIDs = append(resolvedIDs, toolDef.Id)
}
// Emit tool.id (single) or tool.ids (batch) — never both. See
// toolIDUsageAttrs and the rationale in tracing-in-azd.md.
idAttrs := toolIDUsageAttrs(a.flags.dryRun, resolvedIDs)
tracing.SetUsageAttributes(idAttrs...)
// Resolve which agents to install skills for, based on the
// --agent flag. When no agent is given and several are detected, the
// user is asked to choose explicitly.
agentOpts, agentErr := a.resolveAgentOptions(ctx, tools)
if agentErr != nil {
return nil, agentErr
}
// In JSON mode, capture skill agent CLI output so it never leaks onto
// stdout ahead of the structured result.
if a.formatter.Kind() == output.JsonFormat {
agentOpts = append(agentOpts, tool.WithQuiet())
}
start := time.Now()
var (
installResults []*toolInstallResultItem
rawResults []*tool.InstallResult
opErr error
)
if useStepSpinner(a.console, a.formatter, tools) {
// Tools render live per-step progress with the step spinner (like
// azd provision). JSON output is gated out of this path and
// handled below via the per-tool results.
rawResults, opErr = runStepSpinner(
ctx, a.console, tools,
func(ctx context.Context, ids []string, progress ...tool.InstallOption) ([]*tool.InstallResult, error) {
return a.manager.InstallTools(ctx, ids, append(slices.Clone(agentOpts), progress...)...)
},
)
} else {
operationFn := func(ctx context.Context, allIDs []string) ([]*tool.InstallResult, error) {
return a.manager.InstallTools(ctx, allIDs, agentOpts...)
}
outcome := runToolOperation(ctx, tools, operationFn, "Installing", "install", a.console,
a.formatter.Kind() == output.JsonFormat)
installResults = outcome.Items
rawResults = outcome.Results
opErr = outcome.Err
}
emitToolInstallTelemetry(rawResults, time.Since(start), opErr, tools)
if len(rawResults) == 1 {
tracing.SetUsageAttributes(singleResultCommonAttrs(rawResults[0])...)
}
if a.formatter.Kind() == output.JsonFormat {
return nil, a.formatter.Format(installResults, a.writer, nil)
}
// When one or more tools failed, surface the error so the command
// exits non-zero and the success header is NOT printed. The per-tool
// failures were already shown inline.
if opErr != nil {
return nil, opErr
}
header := "Your tool is installed."
if len(tools) > 1 {
header = "Your tools are installed."
}
// Surface any per-tool follow-up guidance (e.g. how to start using a skill)
// after the success header.
var notes []string
for _, t := range tools {
if t.SpinnerNote != "" {
notes = append(notes, t.SpinnerNote)
}
}
return &actions.ActionResult{
Message: &actions.ResultMessage{
Header: header,
FollowUp: strings.Join(notes, "\n"),
},
}, nil
}
// allAgentsKeyword is the reserved --agent value that selects every
// detected agent.
const allAgentsKeyword = "all"
// firstSkillTool returns the first skill tool among tools, or nil when
// none are present.
func firstSkillTool(tools []*tool.ToolDefinition) *tool.ToolDefinition {
for _, t := range tools {
if t.Category == tool.ToolCategorySkill {
return t
}
}
return nil
}
// resolveExplicitSkillAgents maps an explicit --agent flag value to install
// options. The reserved value "all" installs through every available
// agent (resolved at install time); otherwise the named agents are passed
// through for the installer to validate. Shared by the install and
// upgrade actions.
func resolveExplicitSkillAgents(agents []string) ([]tool.InstallOption, error) {
// --agent all selects every detected agent. It cannot be mixed with
// specific agent names.
if slices.Contains(agents, allAgentsKeyword) {
if len(agents) > 1 {
return nil, fmt.Errorf(
"--agent all cannot be combined with specific agents",
)
}
return []tool.InstallOption{tool.WithAllAvailableAgents()}, nil
}
// The installer validates that each named agent is configured and on
// PATH, surfacing a descriptive error otherwise.
return []tool.InstallOption{tool.WithAgents(agents...)}, nil
}
// resolveAgentOptions determines which agent CLI(s) a skill should
// be installed for. With --agent it targets the named agent(s); --agent all
// targets every detected agent. Without --agent, a skill pulled in by a
// batch (--all or the interactive picker) installs through every
// available agent, while an explicitly-named skill with several detected
// agents returns guidance asking the user to choose. It returns the
// install options to pass to the installer (nil selects the single
// preferred agent).
//
// When an explicitly-named skill has several agents on PATH, an
// interactive terminal is prompted to choose which agents to install
// for (we still print a --agent hint); in non-interactive mode it falls
// back to a guidance error telling the user to re-run with --agent.
func (a *toolInstallAction) resolveAgentOptions(
ctx context.Context,
tools []*tool.ToolDefinition,
) ([]tool.InstallOption, error) {
explicit := len(a.flags.agents) > 0
skill := firstSkillTool(tools)
if explicit && skill == nil {
return nil, fmt.Errorf("--agent only applies to skill tools")
}
if skill == nil {
return nil, nil
}
if explicit {
// "all" expands to every detected agent and is validated at
// install time. Specific agent names are checked here so an
// unusable agent (unknown name or not on PATH) can fall back to
// an interactive picker instead of hard-failing.
if !slices.Contains(a.flags.agents, allAgentsKeyword) {
if opts, handled, err := a.resolveUnavailableAgentPrompt(ctx, skill); handled || err != nil {
return opts, err
}
}
return resolveExplicitSkillAgents(a.flags.agents)
}
// No --agent. A skill the user did not name explicitly (batch --all or
// interactive selection) installs through every available agent,
// resolved at install time so agent CLIs installed earlier in the same
// batch are picked up. This is also why --all does not abort when
// several agents are present.
if !slices.Contains(a.args, skill.Id) {
return []tool.InstallOption{tool.WithAllAvailableAgents()}, nil
}
// Explicitly-named skill: when multiple agents are detected we cannot
// safely guess which the user wants.
present, presentName := a.manager.AvailableSkillAgents(ctx, skill)
if len(present) > 1 {
// Interactive terminal: prompt the user to pick the agent(s),
// after surfacing the --agent hint so they learn the shortcut too.
if promptAllowed(a.console, a.formatter) {
a.console.Message(ctx, "Multiple AI agents detected.\n"+
output.WithGrayFormat("Tip: Use `")+
output.WithHighLightFormat("--agent <agent>")+
output.WithGrayFormat("` or `")+
output.WithHighLightFormat("--agent all")+
output.WithGrayFormat("` to select a specific agent or all agents.\n"))
opts, err := a.promptForSkillAgents(ctx, skill, present, presentName)
if err != nil {
return nil, err
}
if opts != nil {
return opts, nil
}
// Nothing selected — fall through to the guidance error.
}
return nil, &internal.ErrorWithSuggestion{
Err: fmt.Errorf("multiple AI agents detected for %s", skill.Name),
Message: fmt.Sprintf(
"Detected multiple agents: %s", strings.Join(presentName, ", "),
),
Suggestion: fmt.Sprintf(
"Specify which agents to install for:\n\n"+
" azd tool install %s --agent <agent>\n\n"+
" azd tool install %s --agent all",
skill.Id, skill.Id,
),
}
}
// Zero or one agent detected: keep the single preferred-agent default.
return nil, nil
}
// resolveUnavailableAgentPrompt handles an explicit --agent whose named
// agents are not usable (unknown name or not on PATH). In an
// interactive terminal it tells the user the requested agent is
// unavailable and prompts them to pick from the agents detected on PATH;
// the chosen agents are returned with handled=true. When no supported
// agent is on PATH at all it defers to the installer's install guidance
// (handled=true via WithAllAvailableAgents). In non-interactive mode, or
// when every requested agent is already available, it returns
// handled=false so the caller validates the request as usual.
func (a *toolInstallAction) resolveUnavailableAgentPrompt(
ctx context.Context,
skill *tool.ToolDefinition,
) (opts []tool.InstallOption, handled bool, err error) {
if !promptAllowed(a.console, a.formatter) {
return nil, false, nil
}
available, availableNames := a.manager.AvailableSkillAgents(ctx, skill)
var unavailable []string
for _, agent := range a.flags.agents {
// Match case-insensitively, mirroring findSkillAgent and the --agent
// contract, so e.g. "--agent Copilot" is not falsely reported
// unavailable (and does not open another prompt) when the installer
// would accept it.
if !slices.ContainsFunc(available, func(cmd string) bool {
return strings.EqualFold(cmd, agent)
}) {
unavailable = append(unavailable, fmt.Sprintf("%q", agent))
}
}
if len(unavailable) == 0 {
return nil, false, nil
}
// No usable agent on PATH — defer to the installer's install guidance
// (recommends installing a CLI agent first) by targeting every
// available agent.
if len(available) == 0 {
return []tool.InstallOption{tool.WithAllAvailableAgents()}, true, nil
}
a.console.Message(ctx, fmt.Sprintf(
"Agent %s is not available for %s. Choose from the agents detected "+
"on your PATH:",
strings.Join(unavailable, ", "), skill.Name,
))
picked, err := a.promptForSkillAgents(ctx, skill, available, availableNames)
if err != nil {
return nil, false, err
}
// Nothing selected — let the caller surface the installer's
// validation error for the originally requested agent.
if picked == nil {
return nil, false, nil
}
return picked, true, nil
}
// promptForSkillAgents shows an interactive multi-select over the given
// available agents and returns the matching install option, or (nil, nil)
// when the user selects nothing so callers can fall back to their own
// guidance. commands and names are index-aligned (from AvailableSkillAgents):
// the picker displays the friendly name for each agent and maps the selection
// back to its command so the installer resolves it by command.
func (a *toolInstallAction) promptForSkillAgents(
ctx context.Context,
skill *tool.ToolDefinition,
commands []string,
names []string,
) ([]tool.InstallOption, error) {
toCommand := make(map[string]string, len(names))
for i, name := range names {
toCommand[name] = commands[i]
}
selected, err := a.console.MultiSelect(ctx, input.ConsoleOptions{
Message: fmt.Sprintf(
"Select the agents to install %s for", skill.Name,
),
Options: names,
DefaultValue: []string{names[0]},
})
if err != nil {
return nil, fmt.Errorf("selecting agents: %w", err)
}
if len(selected) == 0 {
return nil, nil
}
picked := make([]string, len(selected))
for i, name := range selected {
picked[i] = toCommand[name]
}
return []tool.InstallOption{tool.WithAgents(picked...)}, nil
}
// detectAllTools runs manager.DetectAll to get the status of every tool,
// showing a detection spinner with the given text. The spinner is skipped when
// the output format is JSON: it writes control bytes to stdout and would
// corrupt the machine-readable stream (matching tool list/check, which also
// bypass the spinner in JSON mode).
func detectAllTools(
ctx context.Context,
manager *tool.Manager,
formatter output.Formatter,
writer io.Writer,
spinnerText string,
) ([]*tool.ToolStatus, error) {
if formatter != nil && formatter.Kind() == output.JsonFormat {
return manager.DetectAll(ctx)
}
var statuses []*tool.ToolStatus
spinner := uxlib.NewSpinner(&uxlib.SpinnerOptions{
Text: spinnerText,
ClearOnStop: true,
Writer: writer,
})
if err := spinner.Run(ctx, func(ctx context.Context) error {
var detectErr error
statuses, detectErr = manager.DetectAll(ctx)
return detectErr
}); err != nil {
return nil, err
}
return statuses, nil
}
// promptAllowed reports whether azd may show an interactive prompt for a tool
// operation. Prompting requires an interactive terminal, that --no-prompt is
// not set, and that output is not JSON: a JSON-mode prompt writes control bytes
// to the same stdout the result array is serialized to, so the output would no
// longer be a single valid JSON document. When prompting is not allowed, callers
// must require an explicit target (tool IDs / --agent / --all) instead.
func promptAllowed(console input.Console, formatter output.Formatter) bool {
return console.IsSpinnerInteractive() &&
!console.IsNoPromptMode() &&
(formatter == nil || formatter.Kind() != output.JsonFormat)
}
// useStepSpinner reports whether a tool operation should render live
// per-step progress with the step spinner (like azd provision) instead of
// the batch task list. It applies to any interactive, non-JSON operation.
func useStepSpinner(
console input.Console,
formatter output.Formatter,
tools []*tool.ToolDefinition,
) bool {
return len(tools) > 0 &&
formatter.Kind() != output.JsonFormat &&
console.IsSpinnerInteractive()
}
// runStepSpinner runs a tool install/upgrade/uninstall with a live per-step
// step spinner (like azd provision): the installer renders each step via the
// console (each targeted agent for a skill tool, or the tool itself
// otherwise). run performs the manager call with the step-progress option
// appended to its own options. It returns the per-tool results (for
// telemetry) and an aggregate error when any step failed.
func runStepSpinner(
ctx context.Context,
console input.Console,
tools []*tool.ToolDefinition,
run func(context.Context, []string, ...tool.InstallOption) ([]*tool.InstallResult, error),
) ([]*tool.InstallResult, error) {
ids := make([]string, len(tools))
for i, t := range tools {
ids[i] = t.Id
}
results, err := run(ctx, ids, tool.WithStepProgress(console), tool.WithInput(console.Handles().Stdin))
if err != nil {
return results, err
}
// Per-step failures were shown inline by the installer; surface an
// aggregate error so the command still exits non-zero.
var failed []error
for _, r := range results {
if r.Error != nil {
failed = append(failed, r.Error)
}
}
if len(failed) > 0 {
return results, errors.Join(failed...)
}
return results, nil
}
// dryRun detects the current status of the requested tools and
// displays what the install command would do without making changes.
func (a *toolInstallAction) dryRun(
ctx context.Context,
ids []string,
) (*actions.ActionResult, error) {
rows := make([]toolDryRunItem, 0, len(ids))
resolvedIDs := make([]string, 0, len(ids))
for _, id := range ids {
toolDef, findErr := a.manager.FindTool(id)