Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
grok-build-switch/main.go at main · 1parado/grok-build-switch · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
1parado
grok-build-switch
Repository navigation
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
More
items
Files
Expand file tree
main
Breadcrumbs
grok-build-switch
/
main.go
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
240 lines (222 loc) · 7.45 KB
main
Breadcrumbs
grok-build-switch
/
main.go
Copy path
Top
File metadata and controls
Code
Blame
240 lines (222 loc) · 7.45 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
//go:build !wailsgui
package
main
import
(
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"grok_switch/internal/agentbridge"
"grok_switch/internal/autostart"
grokconfig
"grok_switch/internal/config"
"grok_switch/internal/cpamint"
"grok_switch/internal/crash"
"grok_switch/internal/grokauth"
"grok_switch/internal/grokpool"
"grok_switch/internal/mcpserver"
"grok_switch/internal/paths"
"grok_switch/internal/profiles"
"grok_switch/internal/registrar"
"grok_switch/internal/remoteaccess"
"grok_switch/internal/server"
"grok_switch/internal/settings"
"grok_switch/internal/singleinstance"
"grok_switch/internal/switcher"
"grok_switch/internal/tray"
"grok_switch/internal/updatecheck"
"grok_switch/internal/webpool"
)
func
main
() {
// MCP 子进程:由 Grok Agent 以 `grok_switch mcp` 拉起,暴露生图工具。
if
len
(
os
.
Args
)
>
1
&&
os
.
Args
[
1
]
==
"mcp"
{
os
.
Exit
(
mcpserver
.
Run
(
os
.
Args
[
2
:]))
}
defer
crash
.
RecoverMainThread
()
silent
:=
flag
.
Bool
(
"silent"
,
false
,
"start without opening browser"
)
noTray
:=
flag
.
Bool
(
"no-tray"
,
false
,
"run http server without tray"
)
flag
.
Parse
()
resolved
,
err
:=
paths
.
Resolve
()
if
err
!=
nil
{
fatal
(
err
)
}
// Initialize diagnostics before any directory setup so permission failures
// still produce a native error dialog and use the log whenever possible.
crash
.
Setup
(
resolved
.
LogFile
)
if
err
:=
resolved
.
Ensure
();
err
!=
nil
{
fatal
(
err
)
}
settingsStore
:=
settings
.
NewStore
(
resolved
.
SettingsFile
)
instanceLock
,
alreadyRunning
,
err
:=
singleinstance
.
Acquire
(
resolved
.
DataDir
)
if
err
!=
nil
{
fatal
(
fmt
.
Errorf
(
"创建单实例锁失败: %w"
,
err
))
}
if
alreadyRunning
{
url
,
findErr
:=
waitForExistingInstanceURL
(
settingsStore
,
resolved
.
DataDir
,
3
*
time
.
Second
)
if
findErr
==
nil
{
if
openErr
:=
tray
.
OpenBrowser
(
url
);
openErr
==
nil
{
return
}
else
{
crash
.
Logf
(
"open existing instance failed: %v"
,
openErr
)
}
}
else
{
crash
.
Logf
(
"find existing instance failed: %v"
,
findErr
)
}
crash
.
ShowInfo
(
"grok_switch"
,
"grok_switch 已经在运行,但未能自动打开管理页面。请使用系统托盘图标打开。"
)
return
}
defer
instanceLock
.
Close
()
exePath
,
err
:=
os
.
Executable
()
if
err
!=
nil
{
fatal
(
err
)
}
exePath
,
_
=
filepath
.
Abs
(
exePath
)
profileStore
:=
profiles
.
NewStore
(
resolved
.
ProfilesFile
)
grokAuthStore
:=
grokauth
.
NewStore
(
resolved
.
GrokAuthFile
)
grokPool
,
err
:=
grokpool
.
NewManager
(
resolved
.
GrokPoolDir
)
if
err
!=
nil
{
fatal
(
err
)
}
if
err
:=
grokAuthStore
.
SetProxyURL
(
grokPool
.
Status
().
Settings
.
ProxyURL
);
err
!=
nil
{
fatal
(
err
)
}
if
singleStatus
,
statusErr
:=
grokAuthStore
.
Status
();
statusErr
==
nil
&&
singleStatus
.
Configured
{
if
raw
,
readErr
:=
os
.
ReadFile
(
resolved
.
GrokAuthFile
);
readErr
==
nil
{
if
_
,
migrateErr
:=
grokPool
.
Ensure
([]grokpool.
ImportFile
{{
Name
:
"legacy-grok-auth.json"
,
Content
:
string
(
raw
)}});
migrateErr
!=
nil
{
crash
.
Logf
(
"migrate legacy Grok auth into pool: %v"
,
migrateErr
)
}
}
}
grokPool
.
Start
()
defer
grokPool
.
Close
()
registrarService
,
err
:=
registrar
.
NewService
(
resolved
.
DataDir
)
if
err
!=
nil
{
fatal
(
err
)
}
defer
registrarService
.
Close
()
// Web 通道号池(grok2api 式):SSO cookie → grok.com 网页 API。
// 与 CLI OAuth 号池并列;思考以 reasoning_content 返回。
webPool
,
err
:=
webpool
.
NewManager
(
resolved
.
WebPoolDir
)
if
err
!=
nil
{
fatal
(
err
)
}
sw
:=
&
switcher.
Switcher
{
ConfigPath
:
resolved
.
GrokConfig
,
BackupsDir
:
resolved
.
BackupsDir
,
Profiles
:
profileStore
,
}
if
err
:=
sw
.
EnsureDefaultProfile
();
err
!=
nil
{
crash
.
Logf
(
"default profile import skipped: %v"
,
err
)
}
currentSettings
,
err
:=
settingsStore
.
Get
()
if
err
!=
nil
{
fatal
(
err
)
}
if
err
:=
autostart
.
Sync
(
currentSettings
.
Autostart
,
exePath
,
currentSettings
.
SilentAutostart
);
err
!=
nil
{
crash
.
Logf
(
"autostart sync failed: %v"
,
err
)
}
agent
:=
agentbridge
.
New
(
resolved
.
GrokHome
,
filepath
.
Join
(
resolved
.
DataDir
,
"agent.log"
))
agent
.
SetDefaultCwd
(
currentSettings
.
AgentDefaultCwd
)
defer
agent
.
Stop
()
updateState
:=
updatecheck
.
NewPreferenceStore
(
resolved
.
UpdateStateFile
)
appServer
:=
&
server.
Server
{
Paths
:
resolved
,
Profiles
:
profileStore
,
Settings
:
settingsStore
,
RemoteAccess
:
remoteaccess
.
NewStore
(
resolved
.
RemoteAccessFile
),
GrokAuth
:
grokAuthStore
,
GrokPool
:
grokPool
,
WebPool
:
webPool
,
CpaMint
:
cpamint
.
NewService
(),
Registrar
:
registrarService
,
Switcher
:
sw
,
Assets
:
assets
,
ExePath
:
exePath
,
Version
:
version
,
UpdateChecker
:
updatecheck
.
New
(
version
,
"grok_switch.exe"
),
UpdateState
:
updateState
,
}
// 引擎选择器(设计文档 D6):native = 进程内自研引擎,无需 grok CLI;
// acp = 旧桥(spawn Grok CLI,默认)。构造失败自动降级 acp 并写日志。
// 必须在 Listen 之前赋值:Handler 在 goroutine 里开始服务后读 s.Agent。
if
currentSettings
.
AgentEngine
==
settings
.
AgentEngineNative
{
if
nativeSvc
,
nativeErr
:=
appServer
.
NewNativeAgentService
();
nativeErr
==
nil
{
appServer
.
Agent
=
nativeSvc
crash
.
Logf
(
"agent engine: native"
)
}
else
{
appServer
.
Agent
=
agent
crash
.
Logf
(
"native agent engine unavailable, fallback to acp: %v"
,
nativeErr
)
}
}
else
{
appServer
.
Agent
=
agent
}
httpServer
,
port
,
err
:=
appServer
.
Listen
(
currentSettings
.
Port
)
if
err
!=
nil
{
fatal
(
err
)
}
startUpdateNotification
(
appServer
.
UpdateChecker
,
updateState
,
"grok_switch"
)
// Route net/http's internal panic/error reports into the crash log too.
if
crashFile
:=
resolved
.
LogFile
;
crashFile
!=
""
{
if
f
,
ferr
:=
os
.
OpenFile
(
crashFile
,
os
.
O_CREATE
|
os
.
O_APPEND
|
os
.
O_WRONLY
,
0o644
);
ferr
==
nil
{
httpServer
.
ErrorLog
=
log
.
New
(
f
,
"http: "
,
log
.
LstdFlags
)
}
}
url
:=
fmt
.
Sprintf
(
"http://127.0.0.1:%d"
,
port
)
// 生图能力全局开关:开启时通过 Grok CLI 原生 [mcp_servers] 注册生图
// MCP 服务器(Grok CLI 自己 spawn `grok_switch mcp` 并把 generate_image
// 暴露给模型,TUI 与 Agent 会话都生效);关闭时移除注册,模型回到无
// 生图工具的原始状态。每次启动同步一次,保证可执行路径始终正确。
if
currentSettings
.
ImageGenEnabled
{
if
err
:=
grokconfig
.
EnsureMcpServerToFile
(
resolved
.
GrokConfig
, grokconfig.
McpServerConfig
{
Name
:
"image_generator"
,
Command
:
exePath
,
Args
: []
string
{
"mcp"
},
Env
:
map
[
string
]
string
{
"GROK_SWITCH_BASE_URL"
:
url
},
});
err
!=
nil
{
crash
.
Logf
(
"register mcp server failed: %v"
,
err
)
}
}
else
if
err
:=
grokconfig
.
RemoveMcpServerToFile
(
resolved
.
GrokConfig
,
"image_generator"
);
err
!=
nil
{
crash
.
Logf
(
"remove mcp server failed: %v"
,
err
)
}
trayApp
:=
&
tray.
Tray
{
Profiles
:
profileStore
,
Settings
:
settingsStore
,
Switcher
:
sw
,
URL
:
url
,
ExePath
:
exePath
,
DataDir
:
resolved
.
DataDir
,
LogFile
:
resolved
.
LogFile
,
AuthFile
:
filepath
.
Join
(
resolved
.
GrokHome
,
"auth.json"
),
Assets
:
assets
,
}
if
!
*
noTray
{
appServer
.
SetOnChanged
(
trayApp
.
Refresh
)
}
if
!
*
silent
&&
currentSettings
.
AutoOpenBrowser
{
_
=
tray
.
OpenBrowser
(
url
)
}
if
*
noTray
{
waitForSignal
()
shutdown
(
httpServer
)
return
}
trayApp
.
Run
()
shutdown
(
httpServer
)
}
func
waitForSignal
() {
ch
:=
make
(
chan
os.
Signal
,
1
)
signal
.
Notify
(
ch
,
os
.
Interrupt
,
syscall
.
SIGTERM
)
<-
ch
}
func
shutdown
(
srv
interface
{
Shutdown
(context.
Context
)
error
}) {
ctx
,
cancel
:=
context
.
WithTimeout
(
context
.
Background
(),
3
*
time
.
Second
)
defer
cancel
()
_
=
srv
.
Shutdown
(
ctx
)
}
func
fatal
(
err
error
) {
crash
.
ReportFatal
(
err
)
os
.
Exit
(
1
)
}
You can’t perform that action at this time.