forked from vava-nessa/free-coding-models
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp_tail.js
More file actions
224 lines (185 loc) Β· 7.31 KB
/
temp_tail.js
File metadata and controls
224 lines (185 loc) Β· 7.31 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
if (key.name === 'up') {
if (state.cursor > 0) {
state.cursor--
}
return
}
if (key.name === 'down') {
if (state.cursor < results.length - 1) {
state.cursor++
}
return
}
if (key.name === 'c' && key.ctrl) { // Ctrl+C
exit(0)
return
}
if (key.name === 'return') { // Enter
// π Use the same sorting as the table display
const sorted = sortResults(results, state.sortColumn, state.sortDirection)
const selected = sorted[state.cursor]
// π Allow selecting ANY model (even timeout/down) - user knows what they're doing
if (true) {
userSelected = { modelId: selected.modelId, label: selected.label, tier: selected.tier }
// π Stop everything and launch OpenCode immediately
clearInterval(ticker)
clearTimeout(state.pingIntervalObj)
readline.emitKeypressEvents(process.stdin)
process.stdin.setRawMode(true)
process.stdin.pause()
process.stdin.removeListener('keypress', onKeyPress)
process.stdout.write(ALT_LEAVE)
// π Show selection with status
if (selected.status === 'timeout') {
console.log(chalk.yellow(` β Selected: ${selected.label} (currently timing out)`))
} else if (selected.status === 'down') {
console.log(chalk.red(` β Selected: ${selected.label} (currently down)`))
} else {
console.log(chalk.cyan(` β Selected: ${selected.label}`))
}
console.log()
// π Wait for OpenCode to finish before exiting
await startOpenCode(userSelected)
process.exit(0)
}
}
}
// π Enable keypress events on stdin
readline.emitKeypressEvents(process.stdin)
if (process.stdin.isTTY) {
process.stdin.setRawMode(true)
}
process.stdin.on('keypress', onKeyPress)
// π Animation loop: clear alt screen + redraw table at FPS with cursor
const ticker = setInterval(() => {
state.frame++
process.stdout.write(ALT_CLEAR + renderTable(state.results, state.pendingPings, state.frame, state.cursor, state.sortColumn, state.sortDirection, state.pingInterval, state.lastPingTime))
}, Math.round(1000 / FPS))
process.stdout.write(ALT_CLEAR + renderTable(state.results, state.pendingPings, state.frame, state.cursor, state.sortColumn, state.sortDirection, state.pingInterval, state.lastPingTime))
// ββ Continuous ping loop β ping all models every 10 seconds forever ββββββββββ
// π Single ping function that updates result
const pingModel = async (r) => {
const { code, ms } = await ping(apiKey, r.modelId)
// π Store ping result as object with ms and code
// π ms = actual response time (even for errors like 429)
// π code = HTTP status code ('200', '429', '500', '000' for timeout)
r.pings.push({ ms, code })
// π Update status based on latest ping
if (code === '200') {
r.status = 'up'
} else if (code === '000') {
r.status = 'timeout'
} else {
r.status = 'down'
r.httpCode = code
}
}
// π Initial ping of all models
const initialPing = Promise.all(results.map(r => pingModel(r)))
// π Continuous ping loop with dynamic interval (adjustable with W/X keys)
const schedulePing = () => {
state.pingIntervalObj = setTimeout(async () => {
state.lastPingTime = Date.now()
results.forEach(r => {
pingModel(r).catch(() => {
// Individual ping failures don't crash the loop
})
})
// π Schedule next ping with current interval
schedulePing()
}, state.pingInterval)
}
// π Start the ping loop
state.pingIntervalObj = null
schedulePing()
await initialPing
// π Keep interface running forever - user can select anytime or Ctrl+C to exit
// π The pings continue running in background with dynamic interval
// π User can press W to decrease interval (faster pings) or X to increase (slower)
// π Current interval shown in header: "next ping Xs"
}
// π Helper function to find best model after analysis
function findBestModel(results) {
// π Sort by avg ping (fastest first), then by uptime percentage (most reliable)
const sorted = [...results].sort((a, b) => {
const avgA = getAvg(a)
const avgB = getAvg(b)
const uptimeA = getUptime(a)
const uptimeB = getUptime(b)
// π Priority 1: Models that are up (status === 'up')
if (a.status === 'up' && b.status !== 'up') return -1
if (a.status !== 'up' && b.status === 'up') return 1
// π Priority 2: Fastest average ping
if (avgA !== avgB) return avgA - avgB
// π Priority 3: Highest uptime percentage
return uptimeB - uptimeA
})
return sorted.length > 0 ? sorted[0] : null
}
// π Function to run in fiable mode (10-second analysis then output best model)
async function runFiableMode(apiKey) {
console.log(chalk.cyan(' β‘ Analyzing models for reliability (10 seconds)...'))
console.log()
let results = MODELS.map(([modelId, label, tier], i) => ({
idx: i + 1, modelId, label, tier,
status: 'pending',
pings: [],
httpCode: null,
}))
const startTime = Date.now()
const analysisDuration = 10000 // 10 seconds
// π Run initial pings
const pingPromises = results.map(r => ping(apiKey, r.modelId).then(({ code, ms }) => {
r.pings.push({ ms, code })
if (code === '200') {
r.status = 'up'
} else if (code === '000') {
r.status = 'timeout'
} else {
r.status = 'down'
r.httpCode = code
}
}))
await Promise.allSettled(pingPromises)
// π Continue pinging for the remaining time
const remainingTime = Math.max(0, analysisDuration - (Date.now() - startTime))
if (remainingTime > 0) {
await new Promise(resolve => setTimeout(resolve, remainingTime))
}
// π Find best model
const best = findBestModel(results)
if (!best) {
console.log(chalk.red(' β No reliable model found'))
process.exit(1)
}
// π Output in format: provider/name
const provider = 'nvidia' // Always NVIDIA NIM for now
console.log(chalk.green(` β Most reliable model:`))
console.log(chalk.bold(` ${provider}/${best.modelId}`))
console.log()
console.log(chalk.dim(` π Stats:`))
console.log(chalk.dim(` Avg ping: ${getAvg(best)}ms`))
console.log(chalk.dim(` Uptime: ${getUptime(best)}%`))
console.log(chalk.dim(` Status: ${best.status === 'up' ? 'β
UP' : 'β DOWN'}`))
process.exit(0)
}
async function main() {
// π Priority: CLI arg > env var > saved config > wizard
let apiKey = process.argv[2] || process.env.NVIDIA_API_KEY || loadApiKey()
// π Check for CLI flags
const bestMode = process.argv.includes('--BEST') || process.argv.includes('--best')
const fiableMode = process.argv.includes('--FABLE') || process.argv.includes('--fiable')
if (!apiKey) {
apiKey = await promptApiKey()
if (!apiKey) {
console.log()
console.log(chalk.red(' β No API key provided.'))
console.log(chalk.dim(' Run `free-coding-models` again or set NVIDIA_API_KEY env var.'))
console.log()
process.exit(1)
}
}
// π Handle fiable mode first (it exits after analysis)
if (fiableMode) {
await runFiableMode(apiKey)
}