| 44 | |
| 45 | func (p *PromptProcessor) substituteArguments(content, args string, namedArgs []string, argumentHint *string) string { |
| 46 | rawArgs := strings.TrimSpace(args) |
| 47 | var argv []string |
| 48 | var err error |
| 49 | if rawArgs != "" { |
| 50 | argv, err = shellquote.Split(rawArgs) |
| 51 | if err != nil { |
| 52 | argv = []string{rawArgs} |
| 53 | } |
| 54 | } |
| 55 | replacementsApplied := false |
| 56 | indexRe := regexp.MustCompile(`\$ARGUMENTS\[(\d+)\]`) |
| 57 | content = indexRe.ReplaceAllStringFunc(content, func(match string) string { |
| 58 | groups := indexRe.FindStringSubmatch(match) |
| 59 | idx, _ := strconv.Atoi(groups[1]) |
| 60 | replacementsApplied = true |
| 61 | if idx < len(argv) { |
| 62 | return argv[idx] |
| 63 | } |
| 64 | return "" |
| 65 | }) |
| 66 | allArgsRe := regexp.MustCompile(`\$ARGUMENTS([^\[]|$)`) |
| 67 | allCount := 0 |
| 68 | content = allArgsRe.ReplaceAllStringFunc(content, func(match string) string { |
| 69 | allCount++ |
| 70 | return rawArgs + strings.TrimPrefix(match, "$ARGUMENTS") |
| 71 | }) |
| 72 | replacementsApplied = replacementsApplied || allCount > 0 |
| 73 | posRe := regexp.MustCompile(`\$(\d+)`) |
| 74 | seen := map[int]struct{}{} |
| 75 | for _, match := range posRe.FindAllStringSubmatch(content, -1) { |
| 76 | idx, _ := strconv.Atoi(match[1]) |
| 77 | seen[idx] = struct{}{} |
| 78 | } |
| 79 | var indices []int |
| 80 | for idx := range seen { |
| 81 | indices = append(indices, idx) |
| 82 | } |
| 83 | for i := 0; i < len(indices); i++ { |
| 84 | for j := i + 1; j < len(indices); j++ { |
| 85 | if indices[j] > indices[i] { |
| 86 | indices[i], indices[j] = indices[j], indices[i] |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | for _, idx := range indices { |
| 91 | value := "" |
| 92 | if idx < len(argv) { |
| 93 | value = argv[idx] |
| 94 | } |
| 95 | content = strings.ReplaceAll(content, fmt.Sprintf("$%d", idx), value) |
| 96 | replacementsApplied = true |
| 97 | } |
| 98 | if len(namedArgs) > 0 { |
| 99 | valueMap := map[string]string{} |
| 100 | for idx, name := range namedArgs { |
| 101 | if idx < len(argv) { |
| 102 | valueMap[name] = argv[idx] |
| 103 | } else { |