krnell 3.0.6 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,32 @@
1
- import { spawn } from "node:child_process"
2
- import { existsSync } from "node:fs"
1
+ import { execFileSync, spawn } from "node:child_process"
2
+ import { existsSync, readFileSync } from "node:fs"
3
3
  import { homedir } from "node:os"
4
4
  import { join } from "node:path"
5
- import { createSignal, onCleanup } from "solid-js"
5
+ import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js"
6
+ import { useTerminalDimensions } from "@opentui/solid"
6
7
 
7
8
  const BRIDGE_ORIGIN = (process.env.KRNELL_BRIDGE_URL || process.env.NYXO_BRIDGE_URL || "http://127.0.0.1:8765").replace(/\/+$/, "")
9
+ const MOTOR_ORIGIN = (process.env.KRNELL_MOTOR_URL || "http://127.0.0.1:9098").replace(/\/+$/, "")
10
+ const SPIN = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
11
+ const WAVE = ["▁▂▃▄", "▂▃▄▅", "▃▄▅▆", "▄▅▆▇", "▅▆▇▆", "▆▇▆▅", "▇▆▅▄", "▆▅▄▃", "▅▄▃▂", "▄▃▂▁"]
12
+ const PULSE = ["◈", "◈", "◈", "◇", "◈", "◈"]
13
+ const LOGO = [
14
+ ["█ ▄▀ █▀▀▄ █▀▀▄ ", "█▀▀█ █ █ "],
15
+ ["█▄▀ █▄▄▀ █ █ ", "█▀▀ █ █ "],
16
+ ["█ ▀▄ █ █ █ █ ", "▀▀▀▀ ▀▀▀▀ ▀▀▀▀"],
17
+ ]
8
18
 
9
- function findKrnellTuiCommand(): { cmd: string; args: string[]; cwd?: string } {
19
+ function findNodeBinary(): string {
20
+ const candidates = process.platform === "win32"
21
+ ? ["node.exe", "node"]
22
+ : ["/usr/local/bin/node", "/usr/bin/node", process.env.PREFIX ? join(process.env.PREFIX, "bin", "node") : "", "node"].filter(Boolean)
23
+ for (const candidate of candidates) {
24
+ if (candidate === "node" || candidate === "node.exe" || existsSync(candidate)) return candidate
25
+ }
26
+ return "node"
27
+ }
28
+
29
+ function findKrnellDir(): string | undefined {
10
30
  const home = homedir()
11
31
  const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
12
32
  const dataHome = process.env.XDG_DATA_HOME || join(home, ".local", "share")
@@ -14,115 +34,608 @@ function findKrnellTuiCommand(): { cmd: string; args: string[]; cwd?: string } {
14
34
  process.env.KRNELL_HOME,
15
35
  process.env.NYXO_HOME,
16
36
  process.platform === "win32" ? join(localAppData, "Krnell") : join(dataHome, "krnell"),
37
+ join(home, "bridge-package", "krnell"),
17
38
  join(home, "bridge-package", "nyxo"),
18
39
  ].filter(Boolean) as string[]
19
-
20
40
  for (const dir of dirs) {
21
- const mjs = join(dir, "bin", "krnell.mjs")
22
- if (existsSync(mjs)) return { cmd: process.execPath, args: [mjs], cwd: dir }
23
- const painelPy = join(dir, "painel.py")
24
- if (existsSync(painelPy)) {
41
+ if (existsSync(join(dir, "painel.py")) || existsSync(join(dir, "bridge.py"))) return dir
42
+ }
43
+ return undefined
44
+ }
45
+
46
+ function findKrnellHeadlessCommand(): { cmd: string; args: string[]; cwd?: string } {
47
+ const dir = findKrnellDir()
48
+ if (dir) {
49
+ const bridgePy = join(dir, "bridge.py")
50
+ if (existsSync(bridgePy)) {
25
51
  const py = process.platform === "win32" ? "python" : "python3"
26
- return { cmd: py, args: ["-B", painelPy], cwd: dir }
52
+ return { cmd: py, args: ["-B", bridgePy, "--config", join(dir, "config.json")], cwd: dir }
27
53
  }
54
+ const mjs = join(dir, "bin", "krnell.mjs")
55
+ if (existsSync(mjs)) return { cmd: findNodeBinary(), args: [mjs, "--headless"], cwd: dir }
56
+ }
57
+ return { cmd: process.platform === "win32" ? "krnell.cmd" : "krnell", args: ["--headless"] }
58
+ }
59
+
60
+ let cachedApiKey: string | undefined
61
+ function bridgeApiKey(): string {
62
+ if (cachedApiKey !== undefined) return cachedApiKey
63
+ cachedApiKey = String(process.env.BRIDGE_API_KEY || process.env.KRNELL_API_KEY || "").trim()
64
+ if (cachedApiKey) return cachedApiKey
65
+ const dir = findKrnellDir()
66
+ if (dir) {
67
+ try {
68
+ const text = readFileSync(join(dir, "keys.env"), "utf8")
69
+ const match = text.match(/^BRIDGE_API_KEY=(.*)$/m)
70
+ if (match) cachedApiKey = match[1].trim().replace(/^(['"])(.*)\1$/, "$2")
71
+ } catch {}
28
72
  }
29
- return { cmd: process.platform === "win32" ? "krnell.cmd" : "krnell", args: [] }
73
+ return cachedApiKey
30
74
  }
31
75
 
32
- async function pingKrnell(): Promise<boolean> {
76
+ async function fetchJson(url: string, timeoutMs = 1400, authenticated = true): Promise<any> {
77
+ const headers: Record<string, string> = { accept: "application/json" }
78
+ const key = authenticated ? bridgeApiKey() : ""
79
+ if (key) {
80
+ headers.authorization = `Bearer ${key}`
81
+ headers["x-api-key"] = key
82
+ }
83
+ const response = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) })
84
+ if (!response.ok) return null
85
+ return await response.json().catch(() => null)
86
+ }
87
+
88
+ function isLocalOrigin(origin: string): boolean {
33
89
  try {
34
- const r = await fetch(`${BRIDGE_ORIGIN}/healthz`, { signal: AbortSignal.timeout(700) })
35
- if (r.ok) return true
90
+ const host = new URL(origin).hostname
91
+ return host === "127.0.0.1" || host === "localhost" || host === "::1"
92
+ } catch {
93
+ return false
94
+ }
95
+ }
96
+
97
+ function palette(t: any) {
98
+ return {
99
+ accent: t.theme.text.accent || "#c084fc",
100
+ info: t.theme.text.feedback?.info?.base || "#5c9cf5",
101
+ success: t.theme.text.feedback?.success?.base || "#7fd88f",
102
+ warning: t.theme.text.feedback?.warning?.base || "#f5a742",
103
+ error: t.theme.text.feedback?.error?.base || "#e06c75",
104
+ base: t.theme.text.base,
105
+ muted: t.theme.text.muted,
106
+ surface: t.theme.background?.raised?.base || t.theme.background.base,
107
+ }
108
+ }
109
+
110
+ function fit(value: unknown, width: number, align: "left" | "right" = "left"): string {
111
+ const text = String(value ?? "—")
112
+ if (width <= 0) return ""
113
+ const clipped = text.length > width ? text.slice(0, Math.max(1, width - 1)) + "…" : text
114
+ return align === "right" ? clipped.padStart(width) : clipped.padEnd(width)
115
+ }
116
+
117
+ function numberShort(value: unknown): string {
118
+ const number = Number(value)
119
+ if (!Number.isFinite(number)) return "0"
120
+ const absolute = Math.abs(number)
121
+ if (absolute >= 1_000_000) return `${(number / 1_000_000).toFixed(1)}M`
122
+ if (absolute >= 1_000) return `${(number / 1_000).toFixed(1)}k`
123
+ return String(Math.round(number))
124
+ }
125
+
126
+ function duration(msValue: unknown): string {
127
+ const ms = Math.max(0, Number(msValue) || 0)
128
+ if (ms < 1000) return `${Math.round(ms)}ms`
129
+ const seconds = ms / 1000
130
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
131
+ const minutes = Math.floor(seconds / 60)
132
+ return `${minutes}m${String(Math.round(seconds % 60)).padStart(2, "0")}s`
133
+ }
134
+
135
+ let cachedTimeZone: string | null | undefined
136
+ function detectDeviceTimeZone(): string | undefined {
137
+ if (cachedTimeZone !== undefined) return cachedTimeZone || undefined
138
+ const envTz = String(process.env.TZ || "").trim()
139
+ if (envTz) {
140
+ cachedTimeZone = envTz
141
+ return envTz
142
+ }
143
+ try {
144
+ const prop = execFileSync("getprop", ["persist.sys.timezone"], {
145
+ encoding: "utf8",
146
+ timeout: 800,
147
+ stdio: ["ignore", "pipe", "ignore"],
148
+ }).trim()
149
+ if (prop) {
150
+ cachedTimeZone = prop
151
+ return prop
152
+ }
36
153
  } catch {}
154
+ cachedTimeZone = null
155
+ return undefined
156
+ }
157
+
158
+ function hour(ts: unknown): string {
159
+ const date = new Date(Number(ts) * 1000)
160
+ if (!Number.isFinite(date.getTime())) return "--:--:--"
161
+ const tz = detectDeviceTimeZone()
37
162
  try {
38
- const r = await fetch(`${BRIDGE_ORIGIN}/_bridge/status`, { signal: AbortSignal.timeout(700) })
39
- return r.status < 500
163
+ return date.toLocaleTimeString("en-GB", tz ? { hour12: false, timeZone: tz } : { hour12: false })
40
164
  } catch {
41
- return false
165
+ return date.toLocaleTimeString("en-GB", { hour12: false })
166
+ }
167
+ }
168
+
169
+ function resetUnit(secondsValue: number): string {
170
+ const sec = Math.max(0, Math.floor(secondsValue))
171
+ if (sec >= 86400) return `${Math.floor(sec / 86400)}d`
172
+ if (sec >= 3600) return `${Math.floor(sec / 3600)}h`
173
+ if (sec >= 60) return `${Math.floor(sec / 60)}m`
174
+ return `${sec}s`
175
+ }
176
+
177
+ function bucketReset(item: any, nowMs: number): string {
178
+ if (!item || typeof item !== "object") return ""
179
+ if (typeof item.resetTime === "string" && item.resetTime.trim()) {
180
+ const target = Date.parse(item.resetTime)
181
+ if (Number.isFinite(target)) {
182
+ return resetUnit((target - nowMs) / 1000)
183
+ }
184
+ }
185
+ if (Number.isFinite(Number(item.resetInSeconds))) {
186
+ return resetUnit(Number(item.resetInSeconds))
187
+ }
188
+ const human = String(item.resetHuman || "").trim()
189
+ const match = human.match(/(\d+\s*[dhms])/i)
190
+ return match ? match[1].replace(/\s+/g, "") : ""
191
+ }
192
+
193
+ function bucketPercent(item: any): string {
194
+ const fraction = Number(item?.remainingFraction)
195
+ const value = Number.isFinite(Number(item?.remainingPercent)) ? Number(item.remainingPercent) : fraction * 100
196
+ if (!Number.isFinite(value)) return "—"
197
+ return value >= 100 ? "100%" : `${value.toFixed(1)}%`
198
+ }
199
+
200
+ function tokenPair(tokens: any): string {
201
+ if (!tokens || typeof tokens !== "object") return "—"
202
+ return `${numberShort(tokens.in)}/${numberShort(tokens.out)}`
203
+ }
204
+
205
+ function quotaColor(frac: unknown, colors: any): string {
206
+ const value = Number(frac)
207
+ if (!Number.isFinite(value)) return colors.muted
208
+ if (value >= 0.45) return colors.success
209
+ if (value >= 0.15) return colors.warning
210
+ return colors.error
211
+ }
212
+
213
+ function bucket(group: any, weekly: boolean): any {
214
+ return (group?.buckets || []).find((item: any) => {
215
+ const window = String(item?.window || "").toLowerCase()
216
+ const id = String(item?.bucketId || "").toLowerCase()
217
+ return weekly ? window === "weekly" || id.includes("weekly") : window === "5h" || id.includes("5h")
218
+ })
219
+ }
220
+
221
+ function miniBar(frac: unknown, width = 8): string {
222
+ const f = Math.max(0, Math.min(1, Number(frac) || 0))
223
+ const on = Math.round(f * width)
224
+ return "━".repeat(on) + "─".repeat(Math.max(0, width - on))
225
+ }
226
+
227
+ function ActivityRow(props: { item: any; live?: boolean; tick: number; width: number; colors: any }) {
228
+ const item = props.item || {}
229
+ const statusCode = Number(item.status)
230
+ const status = () => props.live ? `${SPIN[props.tick % SPIN.length]} live` : item.status == null ? "—" : `●${item.status}`
231
+ const statusColor = props.live
232
+ ? props.colors.info
233
+ : !Number.isFinite(statusCode) || statusCode < 400
234
+ ? props.colors.success
235
+ : statusCode < 500
236
+ ? props.colors.warning
237
+ : props.colors.error
238
+ const model = props.live ? item.modelo || item.model || item.conta || item.rota : item.model || item.account || item.rota
239
+ const elapsed = props.live ? duration(Number(item.segundos || 0) * 1000) : duration(item.ms)
240
+ const tokens = props.live
241
+ ? item.tokens_out
242
+ ? `${item.exato === false ? "~" : ""}${numberShort(item.tokens_out)}`
243
+ : "—"
244
+ : tokenPair(item.tokens)
245
+ const observation = () => props.live
246
+ ? item.tok_s
247
+ ? `${WAVE[props.tick % WAVE.length]} ${Number(item.tok_s).toFixed(1)} t/s`
248
+ : `${SPIN[props.tick % SPIN.length]} working`
249
+ : item.error || (item.stream ? "stream" : "")
250
+
251
+ // Colunas progressivas com folga garantida para o nome do modelo nunca ser esmagado
252
+ const showTime = props.width >= 44
253
+ const fullTime = props.width >= 56
254
+ const showTokens = props.width >= 74
255
+ const showObservation = props.width >= 92
256
+ const timeWidth = showTime ? (fullTime ? 8 : 5) : 0
257
+ const elapsedWidth = props.width < 44 ? 6 : 7
258
+
259
+ return (
260
+ <box flexDirection="row" gap={1} width="100%" height={1} flexShrink={0}>
261
+ <Show when={showTime}>
262
+ <text fg={props.colors.muted} flexShrink={0}>{fit(props.live ? "now" : hour(item.ts).slice(0, timeWidth), timeWidth)}</text>
263
+ </Show>
264
+ <text fg={statusColor} flexShrink={0}>{fit(status(), 6)}</text>
265
+ <box flexGrow={1} minWidth={8} height={1} flexShrink={1}>
266
+ <text fg={props.colors.base} truncate>{String(model || "—")}</text>
267
+ </box>
268
+ <text fg={props.colors.base} flexShrink={0}>{fit(elapsed, elapsedWidth, "right")}</text>
269
+ <Show when={showTokens}>
270
+ <text fg={props.colors.muted} flexShrink={0}>{fit(tokens, 10, "right")}</text>
271
+ </Show>
272
+ <Show when={showObservation}>
273
+ <text fg={item.error ? props.colors.error : props.live ? props.colors.info : props.colors.muted} flexShrink={0}>
274
+ {fit(observation(), 14)}
275
+ </text>
276
+ </Show>
277
+ </box>
278
+ )
279
+ }
280
+
281
+ function KrnellDashboard(props: { context: any; onClose: () => void }) {
282
+ const t = props.context
283
+ const colors = palette(t)
284
+ const dimensions = useTerminalDimensions()
285
+ const [tick, setTick] = createSignal(0)
286
+ const [nowMs, setNowMs] = createSignal(Date.now())
287
+ // Animação de abertura em 4 etapas (splash rápido do wordmark + barra de progresso)
288
+ const [introStep, setIntroStep] = createSignal(1)
289
+ const [snapshot, setSnapshot] = createSignal<any>(null)
290
+ const [quota, setQuota] = createSignal<any>(null)
291
+ const [starting, setStarting] = createSignal(false)
292
+ let disposed = false
293
+ let refreshing = false
294
+
295
+ const refresh = async () => {
296
+ if (disposed || refreshing) return snapshot()
297
+ refreshing = true
298
+ try {
299
+ const [dashboard, quotas] = await Promise.all([
300
+ fetchJson(`${BRIDGE_ORIGIN}/_bridge/dashboard`, 1200).catch(() => null),
301
+ fetchJson(`${MOTOR_ORIGIN}/antigravity/quota`, 1000, false).catch(() => null),
302
+ ])
303
+ if (disposed) return dashboard
304
+ setSnapshot(dashboard)
305
+ setQuota(quotas)
306
+ return dashboard
307
+ } finally {
308
+ refreshing = false
309
+ }
42
310
  }
311
+
312
+ const startBridge = async () => {
313
+ if (starting() || disposed || !isLocalOrigin(BRIDGE_ORIGIN)) return
314
+ setStarting(true)
315
+ try {
316
+ const launch = findKrnellHeadlessCommand()
317
+ const child = spawn(launch.cmd, launch.args, {
318
+ cwd: launch.cwd,
319
+ detached: true,
320
+ stdio: "ignore",
321
+ windowsHide: true,
322
+ env: { ...process.env, KRNELL_STARTED_BY: "opencode-plugin:dashboard" },
323
+ })
324
+ child.unref()
325
+ for (let index = 0; index < 20 && !disposed; index++) {
326
+ await new Promise((resolve) => setTimeout(resolve, 350))
327
+ if (await refresh()) break
328
+ }
329
+ } catch {
330
+ // Próximo poll tenta novamente sem derrubar o diálogo
331
+ } finally {
332
+ if (!disposed) setStarting(false)
333
+ }
334
+ }
335
+
336
+ onMount(() => {
337
+ void refresh().then((data) => {
338
+ if (!data && !disposed) void startBridge()
339
+ })
340
+ // Sequência de abertura suave: linha 1 -> 2 -> 3 do wordmark -> revela painel (~260ms)
341
+ const introTimers = [
342
+ setTimeout(() => !disposed && setIntroStep(2), 70),
343
+ setTimeout(() => !disposed && setIntroStep(3), 140),
344
+ setTimeout(() => !disposed && setIntroStep(4), 230),
345
+ ]
346
+ const animation = setInterval(() => {
347
+ setTick((value) => (value + 1) % 10000)
348
+ }, 120)
349
+ const clock = setInterval(() => setNowMs(Date.now()), 1000)
350
+ const polling = setInterval(() => void refresh(), 1200)
351
+ onCleanup(() => {
352
+ disposed = true
353
+ for (const timer of introTimers) clearTimeout(timer)
354
+ clearInterval(animation)
355
+ clearInterval(clock)
356
+ clearInterval(polling)
357
+ })
358
+ })
359
+
360
+ const bridge = () => snapshot()?.bridge || snapshot() || {}
361
+ const online = () => bridge().status === "ok"
362
+ const active = () => (online() ? bridge().live?.ativas || [] : [])
363
+ const requests = () => (Array.isArray(snapshot()?.requests) ? snapshot().requests : [])
364
+ const groups = () => {
365
+ const list = quota()?.quota?.groups || quota()?.groups || []
366
+ return Array.isArray(list)
367
+ ? list.filter((group: any) => !String(group?.displayName || "").toLowerCase().includes("argon"))
368
+ : []
369
+ }
370
+ const currentModel = () => {
371
+ const liveModel = active()[0]?.modelo || active()[0]?.model
372
+ const recentModel = requests()[0]?.model
373
+ const motorModel = String(bridge().motor_local?.modelo || "").split("/").pop()
374
+ return liveModel || recentModel || motorModel || snapshot()?.selected_model || bridge().model || "—"
375
+ }
376
+
377
+ // Tamanho determinístico por breakpoint de largura/altura (PC, tablet, celular perto/longe)
378
+ const dialogSize = createMemo<"medium" | "large" | "xlarge">(() => {
379
+ const w = dimensions().width
380
+ if (w >= 124) return "xlarge"
381
+ if (w >= 72) return "large"
382
+ return "medium"
383
+ })
384
+ createEffect(() => {
385
+ t.ui?.dialog?.set?.({ size: dialogSize(), centered: true })
386
+ })
387
+ const boxWidth = createMemo(() => {
388
+ const cap = dialogSize() === "xlarge" ? 116 : dialogSize() === "large" ? 88 : 60
389
+ return Math.min(cap, Math.max(24, dimensions().width - 2))
390
+ })
391
+ const padX = createMemo(() => (boxWidth() < 46 ? 1 : 2))
392
+ const contentWidth = createMemo(() => Math.max(20, boxWidth() - padX() * 2))
393
+ const height = createMemo(() => {
394
+ const h = dimensions().height
395
+ if (h <= 18) return Math.max(9, h - 4)
396
+ if (h <= 30) return Math.max(14, Math.min(20, Math.floor(h * 0.58)))
397
+ return Math.max(18, Math.min(28, Math.floor(h * 0.62)))
398
+ })
399
+ const showLogo = createMemo(() => contentWidth() >= 32 && height() >= 13)
400
+ const variant = () => t.ui?.model?.current?.()?.variant || "default"
401
+ const introDone = () => introStep() >= 4
402
+
403
+ // Linha de reset resumida e limpa (sem parênteses cortados):
404
+ // ex.: "reseta diário 4h · semanal 6d" (ou só "reseta semanal 6d" em conta Free)
405
+ const resetSummary = createMemo(() => {
406
+ const list = groups()
407
+ if (!list.length) return ""
408
+ const primary = list[0]
409
+ const five = bucket(primary, false)
410
+ const seven = bucket(primary, true)
411
+ const r5 = five ? bucketReset(five, nowMs()) : ""
412
+ const r7 = seven ? bucketReset(seven, nowMs()) : ""
413
+ const parts: string[] = []
414
+ if (r5) parts.push(`diário ${r5}`)
415
+ if (r7) parts.push(`semanal ${r7}`)
416
+ return parts.length ? `reseta ${parts.join(" · ")}` : ""
417
+ })
418
+
419
+ return (
420
+ <box
421
+ width="100%"
422
+ height={height()}
423
+ minHeight={0}
424
+ flexShrink={0}
425
+ flexDirection="column"
426
+ backgroundColor={t.theme.background.base}
427
+ paddingLeft={padX()}
428
+ paddingRight={padX()}
429
+ paddingBottom={1}
430
+ >
431
+ {/* Cabeçalho fixo: marca + estado vivo + esc */}
432
+ <box flexDirection="row" justifyContent="space-between" width="100%" height={1} flexShrink={0}>
433
+ <box flexDirection="row" gap={1}>
434
+ <text fg={online() ? colors.accent : colors.muted}>{online() ? PULSE[tick() % PULSE.length] : "◇"}</text>
435
+ <text fg={colors.base}>krnell</text>
436
+ <Show when={bridge().version}>
437
+ <text fg={colors.muted}>{`v${bridge().version}`}</text>
438
+ </Show>
439
+ </box>
440
+ <box flexDirection="row" gap={2}>
441
+ <text fg={online() ? (active().length ? colors.info : colors.success) : colors.error}>
442
+ {starting()
443
+ ? `${SPIN[tick() % SPIN.length]} starting`
444
+ : active().length
445
+ ? `${SPIN[tick() % SPIN.length]} working`
446
+ : online()
447
+ ? "● online"
448
+ : "○ offline"}
449
+ </text>
450
+ <text fg={colors.muted} onMouseUp={props.onClose}>esc</text>
451
+ </box>
452
+ </box>
453
+
454
+ {/* Splash de abertura animado (3 passos rápidos antes de revelar o corpo) */}
455
+ <Show when={!introDone()}>
456
+ <box flexGrow={1} flexDirection="column" justifyContent="center" alignItems="center" width="100%" gap={1}>
457
+ <Show when={contentWidth() >= 32}>
458
+ <box flexDirection="column" alignItems="center">
459
+ <For each={LOGO.slice(0, introStep())}>
460
+ {(row) => (
461
+ <box flexDirection="row" height={1}>
462
+ <text fg={colors.base}>{row[0]}</text>
463
+ <text fg={colors.accent}>{row[1]}</text>
464
+ </box>
465
+ )}
466
+ </For>
467
+ </box>
468
+ </Show>
469
+ <text fg={colors.info}>{miniBar(introStep() / 3, Math.min(20, contentWidth() - 6))}</text>
470
+ </box>
471
+ </Show>
472
+
473
+ {/* Corpo principal após a animação de abertura */}
474
+ <Show when={introDone()}>
475
+ <Show when={showLogo()}>
476
+ <box height={1} flexShrink={0} />
477
+ <box flexDirection="column" alignItems="center" width="100%" flexShrink={0}>
478
+ <For each={LOGO}>
479
+ {(row) => (
480
+ <box flexDirection="row" height={1} flexShrink={0}>
481
+ <text fg={colors.base}>{row[0]}</text>
482
+ <text fg={colors.accent}>{row[1]}</text>
483
+ </box>
484
+ )}
485
+ </For>
486
+ </box>
487
+ <box height={1} flexShrink={0} />
488
+ </Show>
489
+
490
+ {/* Linha 1: provedor · modelo · variante */}
491
+ <box flexDirection="row" justifyContent="space-between" width="100%" height={1} flexShrink={0}>
492
+ <box flexDirection="row" gap={1} flexShrink={1} minWidth={0}>
493
+ <text fg={colors.accent} flexShrink={0}>{String(bridge().provider || "offline")}</text>
494
+ <text fg={colors.muted} flexShrink={0}>·</text>
495
+ <text fg={colors.base} truncate>{String(currentModel())}</text>
496
+ </box>
497
+ <Show when={contentWidth() >= 48}>
498
+ <text fg={colors.muted} flexShrink={0}>{variant()}</text>
499
+ </Show>
500
+ </box>
501
+
502
+ {/* Linha 2: cotas limpas ao vivo (G 7d 92.4% · 5h 72.8% | C 7d 100% · 5h 100%) */}
503
+ <Show when={groups().length > 0}>
504
+ <box flexDirection="row" gap={1} width="100%" height={1} flexShrink={0}>
505
+ <For each={groups().slice(0, contentWidth() >= 54 ? 2 : 1)}>
506
+ {(group: any, index) => {
507
+ const name = String(group?.displayName || "").toLowerCase().includes("claude") ? "C" : "G"
508
+ const seven = bucket(group, true)
509
+ const five = bucket(group, false)
510
+ return (
511
+ <>
512
+ <Show when={index() > 0}><text fg={colors.muted}>│</text></Show>
513
+ <text fg={colors.accent}>{name}</text>
514
+ <Show when={seven}>
515
+ <text fg={quotaColor(seven?.remainingFraction, colors)}>{`7d ${bucketPercent(seven)}`}</text>
516
+ </Show>
517
+ <Show when={five}>
518
+ <text fg={quotaColor(five?.remainingFraction, colors)}>{`5h ${bucketPercent(five)}`}</text>
519
+ </Show>
520
+ </>
521
+ )
522
+ }}
523
+ </For>
524
+ </box>
525
+ {/* Linha 3: reset separado e legível ("reseta diário 4h · semanal 6d") */}
526
+ <Show when={resetSummary()}>
527
+ <box flexDirection="row" justifyContent="space-between" width="100%" height={1} flexShrink={0}>
528
+ <text fg={colors.muted} truncate>{resetSummary()}</text>
529
+ <Show when={contentWidth() >= 56 && snapshot()?.month?.total}>
530
+ <text fg={colors.info} flexShrink={0}>{`${numberShort(snapshot().month.total)} tok/mês`}</text>
531
+ </Show>
532
+ </box>
533
+ </Show>
534
+ </Show>
535
+
536
+ <Show when={groups().length === 0 && snapshot()?.month?.total}>
537
+ <box flexDirection="row" gap={1} width="100%" height={1} flexShrink={0}>
538
+ <text fg={colors.info}>{`${numberShort(snapshot().month.total)} tok`}</text>
539
+ <text fg={colors.muted}>this month</text>
540
+ </box>
541
+ </Show>
542
+
543
+ {/* Separador sutil + título Activity */}
544
+ <box height={1} width="100%" flexShrink={0}>
545
+ <text fg={colors.muted}>{"─".repeat(Math.max(10, contentWidth()))}</text>
546
+ </box>
547
+ <box flexDirection="row" justifyContent="space-between" width="100%" height={1} flexShrink={0}>
548
+ <box flexDirection="row" gap={1}>
549
+ <text fg={colors.base}>Activity</text>
550
+ <Show when={requests().length}><text fg={colors.muted}>{String(requests().length)}</text></Show>
551
+ <Show when={active().length}>
552
+ <text fg={colors.info}>{`· ${SPIN[tick() % SPIN.length]} ${active().length} live`}</text>
553
+ </Show>
554
+ </box>
555
+ <Show when={active()[0]?.tok_s && contentWidth() >= 48}>
556
+ <text fg={colors.info}>{`${WAVE[tick() % WAVE.length]} ${Number(active()[0].tok_s).toFixed(1)} t/s`}</text>
557
+ </Show>
558
+ </box>
559
+
560
+ {/* Lista rolável com linhas ao vivo no topo + histórico completo */}
561
+ <scrollbox flexGrow={1} minHeight={0}>
562
+ <For each={active()}>
563
+ {(item: any) => <ActivityRow item={item} live tick={tick()} width={contentWidth()} colors={colors} />}
564
+ </For>
565
+ <For each={requests()}>
566
+ {(item: any) => <ActivityRow item={item} tick={tick()} width={contentWidth()} colors={colors} />}
567
+ </For>
568
+ <Show when={requests().length === 0 && active().length === 0}>
569
+ <text fg={colors.muted}>{online() ? "No requests yet · /connect to begin" : "Bridge offline · starting on demand…"}</text>
570
+ </Show>
571
+ </scrollbox>
572
+ </Show>
573
+ </box>
574
+ )
43
575
  }
44
576
 
45
577
  export default {
46
578
  id: "krnell.tui",
47
579
  setup(t: any) {
580
+ const [open, setOpen] = createSignal(false)
48
581
  const [online, setOnline] = createSignal(false)
49
- const [opening, setOpening] = createSignal(false)
50
582
 
51
- const refresh = async () => {
52
- setOnline(await pingKrnell())
583
+ const refreshBadge = async () => {
584
+ const status = await fetchJson(`${BRIDGE_ORIGIN}/_bridge/status`, 800).catch(() => null)
585
+ setOnline(status?.status === "ok")
586
+ }
587
+ void refreshBadge()
588
+ const polling = setInterval(() => void refreshBadge(), 5000)
589
+
590
+ const close = () => {
591
+ setOpen(false)
592
+ t.ui?.dialog?.clear?.()
53
593
  }
54
- void refresh()
55
- const timer = setInterval(() => void refresh(), 5000)
56
- onCleanup(() => clearInterval(timer))
57
-
58
- const openKrnell = async () => {
59
- if (opening()) return
60
- setOpening(true)
61
- try {
62
- const launch = findKrnellTuiCommand()
63
- await t.renderer.suspend()
64
- try {
65
- await new Promise<void>((resolve, reject) => {
66
- const child = spawn(launch.cmd, launch.args, {
67
- cwd: launch.cwd,
68
- stdio: "inherit",
69
- shell: false,
70
- })
71
- child.on("error", reject)
72
- child.on("exit", () => resolve())
73
- })
74
- } finally {
75
- await t.renderer.resume()
76
- }
77
- await refresh()
78
- } catch (err: any) {
79
- t.ui?.toast?.show?.({
80
- title: "Krnell",
81
- message: `Não foi possível abrir o painel (${err?.message || err})`,
82
- variant: "error",
83
- })
84
- } finally {
85
- setOpening(false)
594
+ const toggle = () => {
595
+ if (open()) {
596
+ close()
597
+ return
86
598
  }
599
+ setOpen(true)
600
+ // Janela flutuante modal nativa: funciona na home e em qualquer sessão,
601
+ // redimensiona conforme tela/zoom e captura Esc sem interromper o modelo.
602
+ t.ui?.dialog?.show?.(
603
+ () => <KrnellDashboard context={t} onClose={close} />,
604
+ () => setOpen(false),
605
+ )
606
+ t.ui?.dialog?.set?.({ size: "large", centered: true })
87
607
  }
88
608
 
89
- // Comando `/krnell` na paleta e slash do OpenCode
90
609
  t.keymap?.layer?.(() => ({
91
610
  mode: "global",
92
611
  commands: [
93
612
  {
94
- id: "krnell.panel.open",
95
- title: "Open Krnell panel",
96
- description: "Abre o painel do Krnell (Ctrl+C volta pro OpenCode mantendo em background)",
613
+ id: "krnell.panel.toggle",
614
+ title: "Toggle Krnell",
615
+ description: "Abre a janela flutuante do Krnell sem sair da sessão",
97
616
  group: "Krnell",
98
617
  palette: true,
99
618
  slash: { name: "krnell" },
100
- run: () => void openKrnell(),
619
+ run: () => toggle(),
101
620
  },
102
621
  ],
103
622
  }))
104
623
 
105
- // Botão clicável/tocável no footer da home do OpenCode (ao lado de "1 MCP /mcps")
106
- t.ui.slot({
107
- append: "home.footer.status",
108
- render: () => (
109
- <box
110
- flexDirection="row"
111
- flexShrink={0}
112
- gap={1}
113
- onMouseUp={() => void openKrnell()}
114
- >
115
- <text fg={online() ? t.theme.text.feedback.success.base : t.theme.text.muted}>
116
- ◈
117
- </text>
118
- <text fg={t.theme.text.base}>
119
- {opening() ? "krnell…" : "krnell"}
120
- </text>
121
- <text fg={t.theme.text.muted}>
122
- /krnell
123
- </text>
124
- </box>
125
- ),
126
- })
624
+ const badge = () => (
625
+ <box flexDirection="row" flexShrink={0} gap={0} onMouseUp={() => toggle()}>
626
+ <text fg={online() ? palette(t).success : palette(t).muted}>{online() ? "◈ " : "◇ "}</text>
627
+ <text fg={open() ? palette(t).accent : palette(t).base}>krnell</text>
628
+ </box>
629
+ )
630
+
631
+ const disposeHome = t.ui?.slot?.({ append: "home.footer.status", render: () => badge() })
632
+ const disposePrompt = t.ui?.slot?.({ append: "prompt.footer.status", render: () => badge() })
633
+
634
+ return () => {
635
+ clearInterval(polling)
636
+ disposeHome?.()
637
+ disposePrompt?.()
638
+ if (open()) t.ui?.dialog?.clear?.()
639
+ }
127
640
  },
128
641
  }