Repository navigation
Expand file tree
/
Copy pathagentshim.go
More file actions
174 lines (166 loc) · 5.03 KB
/
Copy pathagentshim.go
File metadata and controls
174 lines (166 loc) · 5.03 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
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
// agentShimMaxSize bounds how much of a batch file is read when looking for
// the program it launches. npm, pnpm and Yarn shims are a few hundred bytes.
const agentShimMaxSize = 64 << 10
// agentShimArgv returns the program and arguments to start an agent with.
//
// On Windows a .cmd or .bat file can only run through cmd.exe, and cmd.exe
// ends each argument at its first newline, so a multi-line prompt handed to
// an npm shim such as claude.cmd reached the agent as its first line only
// (issue #809). The shim is therefore replaced by the program it launches,
// which receives the prompt intact. A batch file glorp cannot read through is
// still run as is, unless the prompt has a line break it would lose: that is
// refused with an error naming --agent-binary as the way to point glorp at
// the real executable.
func agentShimArgv(binary string, args []string) (string, []string, error) {
if runtime.GOOS != "windows" {
return binary, args, nil
}
path, err := exec.LookPath(binary)
if err != nil || !isBatchFile(path) {
return binary, args, nil
}
if argv := resolveBatchShim(path); len(argv) > 0 {
return argv[0], append(argv[1:], args...), nil
}
for _, arg := range args {
if strings.ContainsAny(arg, "\r\n") {
return binary, args, fmt.Errorf("agent binary %s is a batch file, and cmd.exe would cut its multi-line prompt at the first line break; pass the executable it launches with --agent-binary NAME=PATH", path)
}
}
return binary, args, nil
}
func isBatchFile(path string) bool {
switch strings.ToLower(filepath.Ext(path)) {
case ".cmd", ".bat":
return true
}
return false
}
// resolveBatchShim reads a package-manager shim and returns the command line
// it runs ahead of the arguments it forwards with %*, or nil when the file is
// not a shim it understands or what the shim launches does not exist. npm's
// cmd-shim runs either the package's native executable or node with the
// package's script; pnpm's does the same with %~dp0 in place of %dp0%. Each
// line that forwards %* is tried in turn, so a shim choosing between a
// bundled node.exe and node on PATH resolves to whichever it would run.
func resolveBatchShim(path string) []string {
info, err := os.Stat(path)
if err != nil || info.Size() > agentShimMaxSize {
return nil
}
content, err := os.ReadFile(path)
if err != nil {
return nil
}
dir := filepath.Dir(path)
for _, line := range strings.Split(string(content), "\n") {
if argv := shimLineArgv(line, dir); len(argv) > 0 {
return argv
}
}
return nil
}
// shimLineArgv resolves one shim line of the form `... & "PROGRAM" ARGS %*`.
func shimLineArgv(line, dir string) []string {
before, _, found := strings.Cut(line, "%*")
if !found {
return nil
}
// npm's shim runs the program after `endLocal & goto ... || title ... &`,
// so only what follows the last unquoted & is the command.
command := before
quoted := false
for i, r := range before {
switch {
case r == '"':
quoted = !quoted
case r == '&' && !quoted:
command = before[i+1:]
}
}
tokens, ok := splitShimCommand(command)
if !ok || len(tokens) == 0 {
return nil
}
nodeExe := filepath.Join(dir, "node.exe")
program := "node"
if fileExists(nodeExe) {
program = nodeExe
}
argv := make([]string, 0, len(tokens))
for _, token := range tokens {
token = strings.ReplaceAll(token, "%_prog%", program)
token = strings.ReplaceAll(token, "%dp0%", dir+`\`)
token = strings.ReplaceAll(token, "%~dp0", dir+`\`)
if strings.Contains(token, "%") {
return nil
}
if strings.ContainsAny(token, `\/`) {
token = filepath.Clean(filepath.FromSlash(strings.ReplaceAll(token, `\`, "/")))
if !fileExists(token) {
return nil
}
}
argv = append(argv, token)
}
if !strings.ContainsAny(argv[0], `\/`) {
resolved, err := exec.LookPath(argv[0])
if err != nil {
return nil
}
argv[0] = resolved
}
// A shim that only hands off to another batch file is no better than the
// one it replaced.
if isBatchFile(argv[0]) {
return nil
}
return argv
}
// splitShimCommand splits a batch command into its words, keeping quoted
// words whole. A leading @ (echo off) or ( of an IF block is dropped. It
// reports false for a command using batch syntax it does not model.
func splitShimCommand(command string) ([]string, bool) {
command = strings.TrimLeft(strings.TrimSpace(command), "@(")
var tokens []string
var word strings.Builder
inWord, quoted := false, false
for _, r := range command {
switch {
case r == '"':
quoted = !quoted
inWord = true
case !quoted && (r == ' ' || r == '\t' || r == '\r'):
if inWord {
tokens = append(tokens, word.String())
word.Reset()
inWord = false
}
case !quoted && strings.ContainsRune("|<>^()", r):
return nil, false
default:
word.WriteRune(r)
inWord = true
}
}
if quoted {
return nil, false
}
if inWord {
tokens = append(tokens, word.String())
}
return tokens, true
}
func fileExists(path string) bool {
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}