-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
255 lines (223 loc) · 9.27 KB
/
Copy pathbot.js
File metadata and controls
255 lines (223 loc) · 9.27 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
process.env.COLORTERM = process.env.COLORTERM || 'truecolor';
process.env.TERM = process.env.TERM || 'xterm-256color';
const fs = require('fs');
const fsp = require('fs/promises');
const path = require('path');
const {
initCli,
setConsoleHandlers,
logChatMessage,
forwardSystemLog,
updateUiStatus,
updateServerInfo
} = require('./cli');
const { loadConfig, watchConfig, saveConfig } = require('./lib/config');
const { createCliHandler } = require('./cli/handler');
const { createStatusPanel } = require('./lib/statusPanel');
const { createCommandRouter } = require('./lib/commandRouter');
const { SessionLogger } = require('./lib/logger');
const { AccessControl } = require('./modules/accessControl');
const { createThemeManager } = require('./lib/themeManager');
const { createInstanceManager } = require('./lib/instanceManager');
const { createMultiBotManager } = require('./lib/multiBotManager');
const updateManager = require('./lib/updateManager');
const UI_REFRESH_MS = 1500;
const originalConsoleLog = console.log;
const originalConsoleError = console.error;
main().catch(err => {
originalConsoleError('v0.nav failed to start:', err);
process.exit(1);
});
async function main() {
const ready = await ensureFirstTimeSetup();
if (!ready) {
return;
}
startFlightBot();
}
function startFlightBot() {
setConsoleHandlers(originalConsoleLog, originalConsoleError);
const instanceManager = createInstanceManager({
filePath: path.join(__dirname, 'config', 'instances.json')
});
instanceManager.loadSync();
const cfgPath = path.join(__dirname, 'config', 'config.json');
let config = loadConfig(cfgPath);
const logger = new SessionLogger({ directory: path.resolve(__dirname, config.logging?.directory || 'logs') });
const accessControl = new AccessControl({
filePath: path.join(__dirname, 'data', 'whitelist.json'),
legacyFile: path.join(__dirname, 'white.list'),
ownerUuid: config.ownerUuid,
logger
});
const themeManager = createThemeManager({ filePath: path.join(__dirname, 'config', 'themes.json') });
let stopConfigWatch = () => {};
const commandRouter = createCommandRouter({
prefix: '.',
commandsDir: path.join(__dirname, 'commands'),
logger
});
const multiBotManager = createMultiBotManager({
rootDir: __dirname,
logger,
accessControl,
themeManager,
commandRouter,
logChatMessage,
forwardSystemLog,
baseConfig: config,
saveConfig: (nextConfig) => saveConfig(cfgPath, nextConfig),
instanceManager
});
const statusPanel = createStatusPanel({
options: config.minecraft,
updateUiStatus,
updateServerInfo
});
function refreshStatus() {
const activeEntry = multiBotManager.getActiveEntry();
const runningInstances = multiBotManager.getStatusInfo();
statusPanel.refresh({
bot: activeEntry?.botManager?.getBot() || null,
elytraFly: activeEntry?.botManager?.getElytraFly() || null,
autoTunnel: activeEntry?.botManager?.getAutoTunnel() || null,
connectedAt: activeEntry?.botManager?.getConnectedAt() || null,
instanceName: activeEntry?.instance?.name || 'None',
runningCount: runningInstances.length,
runningInstances
});
}
stopConfigWatch = watchConfig(cfgPath, next => {
config = next;
accessControl.setOwnerUuid(config.ownerUuid);
forwardSystemLog('Config reloaded.');
});
const refreshInterval = setInterval(refreshStatus, UI_REFRESH_MS);
refreshStatus();
function handleInstanceStart(instance) {
forwardSystemLog(`Starting instance: ${instance.name} (${instance.minecraft?.host})...`, 'cyan');
multiBotManager.startInstance(instance);
}
function handleInstanceStop(instanceId) {
multiBotManager.stopInstance(instanceId);
}
function handleSetActiveInstance(instanceId) {
if (multiBotManager.setActiveInstance(instanceId)) {
const entry = multiBotManager.getActiveEntry();
forwardSystemLog(`Active instance set to: ${entry?.instance?.name || instanceId}`, 'green');
}
}
const cliHandler = createCliHandler({
commandRouter,
forwardSystemLog,
logChatMessage,
getBot: () => multiBotManager.getActiveBot(),
getElytraFly: () => multiBotManager.getActiveBotManager()?.getElytraFly() || null,
getAutoTunnel: () => multiBotManager.getActiveBotManager()?.getAutoTunnel() || null,
getAutoTotem: () => multiBotManager.getActiveBotManager()?.getAutoTotem() || null,
getAutoArmor: () => multiBotManager.getActiveBotManager()?.getAutoArmor() || null,
getAutoEat: () => multiBotManager.getActiveBotManager()?.getAutoEat() || null,
getCommander: () => multiBotManager.getActiveBotManager()?.getCommander() || null,
accessControl,
logger,
refreshStatus,
requestShutdown: (opts) => {
if (opts?.forceExit) {
multiBotManager.stopAll('shutdown');
setTimeout(() => process.exit(0), 500);
} else {
const activeId = multiBotManager.getActiveInstanceId();
if (activeId) {
multiBotManager.stopInstance(activeId, opts?.reason || 'manual quit');
}
}
},
themeManager,
instanceManager,
multiBotManager,
onInstanceStart: handleInstanceStart,
onInstanceStop: handleInstanceStop
});
initCli({
onSubmit: cliHandler.handleUserInput,
onCtrlC: () => {
multiBotManager.stopAll('shutdown');
setTimeout(() => process.exit(0), 500);
},
themeManager,
instanceManager,
multiBotManager,
onInstanceStart: handleInstanceStart,
onInstanceStop: handleInstanceStop,
onSetActiveInstance: handleSetActiveInstance
}).catch(err => {
originalConsoleError('Failed to initialize CLI:', err);
process.exit(1);
});
console.log = (...args) => forwardSystemLog(formatArgs(args), 'cyan');
console.error = (...args) => forwardSystemLog(formatArgs(args), 'red');
forwardSystemLog('v0.nav CLI ready. Press F2 to open Instance Manager.', 'green');
forwardSystemLog('Type .help for commands. Start instances from the Instance Manager.', 'cyan');
(async () => {
try {
const updateInfo = await updateManager.checkForUpdates({ repoPath: __dirname });
if (updateInfo?.hasCustomCode) {
const details = updateInfo.customCodeDetails || {};
const files = [...new Set([...(details.workingTree || []), ...(details.committed || [])])];
const preview = files.length ? `${files.slice(0, 2).join(', ')}${files.length > 2 ? ` (+${files.length - 2} more)` : ''}` : 'custom code changes';
forwardSystemLog(`[Update] Custom code detected (${preview}). You're running a custom v0.nav build and support isn't guaranteed.`, 'magenta');
}
if (updateInfo?.status === 'behind') {
const warn = `[Update] A new version (${updateInfo.remoteHash}) is available. Run .update for the best experience.`;
forwardSystemLog(warn, 'yellow');
}
} catch (err) {
forwardSystemLog(`[Update] Failed to check for updates: ${err.message}`, 'red');
}
const restored = await multiBotManager.restorePreviousSession();
if (!restored) {
const firstInstance = instanceManager.getActiveInstance() || instanceManager.getInstances()[0];
if (firstInstance) {
forwardSystemLog(`Auto-starting instance: ${firstInstance.name}...`, 'cyan');
multiBotManager.startInstance(firstInstance);
}
}
})();
process.once('exit', () => {
clearInterval(refreshInterval);
stopConfigWatch();
themeManager.close();
logger.close('process-exit');
});
}
async function ensureFirstTimeSetup() {
const navPath = path.join(__dirname, 'data', 'v0.nav');
try {
await fsp.access(navPath);
return true;
} catch (err) {
if (!err || err.code !== 'ENOENT') {
throw err;
}
}
const runFirstTimeSetup = require('./core/firstTime');
const result = await runFirstTimeSetup({
configPath: path.join(__dirname, 'config', 'config.json'),
themesPath: path.join(__dirname, 'config', 'themes.json'),
dataDir: path.join(__dirname, 'data')
});
if (!result?.launchBot) {
originalConsoleLog('Setup finished. Re-run FlightBot whenever you are ready.');
return false;
}
return true;
}
function formatArgs(args) {
return args
.map(arg => {
if (typeof arg === 'string') return arg;
try { return JSON.stringify(arg); }
catch { return String(arg); }
})
.join(' ');
}