krnell 3.0.4 → 3.0.6
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.
- package/atualizador.py +11 -2
- package/bin/krnell.mjs +63 -15
- package/bridge.py +8 -3
- package/iniciar.sh +1 -1
- package/kimi.py +18 -0
- package/opencode_sync.py +59 -8
- package/package.json +1 -1
- package/painel.py +1008 -219
- package/plugins/system-prompt/index.ts +104 -3
- package/plugins/system-prompt/package.json +10 -0
- package/plugins/system-prompt/tui.tsx +128 -0
- package/provedores/kimi/bridge.mjs +5 -81
- package/tui_core.py +135 -16
|
@@ -10,14 +10,105 @@
|
|
|
10
10
|
// Remove o prompt manual de API key do provider "kimibridge" e coloca no
|
|
11
11
|
// lugar o login OAuth do Google Antigravity via bridge local, suportando
|
|
12
12
|
// múltiplas contas com troca automática quando uma conta esgota a quota.
|
|
13
|
+
import { spawn } from "node:child_process"
|
|
13
14
|
import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
|
14
15
|
import { homedir } from "node:os"
|
|
15
16
|
import { join } from "node:path"
|
|
16
17
|
|
|
17
|
-
const INTEGRATION_IDS = ["nyxo", "kimibridge"]
|
|
18
|
+
const INTEGRATION_IDS = ["krnell", "nyxo", "kimibridge"]
|
|
18
19
|
const METHOD_ID = "antigravity-oauth"
|
|
19
20
|
const DEFAULT_BRIDGE_ORIGIN = "http://127.0.0.1:8765"
|
|
20
21
|
|
|
22
|
+
let ensureBridgePromise: Promise<boolean> | null = null
|
|
23
|
+
let lastEnsureAttemptAt = 0
|
|
24
|
+
|
|
25
|
+
function isLocalBridgeOrigin(origin: string): boolean {
|
|
26
|
+
try {
|
|
27
|
+
const u = new URL(origin)
|
|
28
|
+
return u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "::1"
|
|
29
|
+
} catch {
|
|
30
|
+
return false
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function findKrnellCommand(): { cmd: string; args: string[]; cwd?: string } | null {
|
|
35
|
+
const home = homedir()
|
|
36
|
+
const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
|
|
37
|
+
const dataHome = process.env.XDG_DATA_HOME || join(home, ".local", "share")
|
|
38
|
+
const dirs = [
|
|
39
|
+
process.env.KRNELL_HOME,
|
|
40
|
+
process.env.NYXO_HOME,
|
|
41
|
+
process.platform === "win32" ? join(localAppData, "Krnell") : join(dataHome, "krnell"),
|
|
42
|
+
join(home, "bridge-package", "nyxo"),
|
|
43
|
+
].filter(Boolean) as string[]
|
|
44
|
+
|
|
45
|
+
for (const dir of dirs) {
|
|
46
|
+
const mjs = join(dir, "bin", "krnell.mjs")
|
|
47
|
+
if (existsSync(mjs)) {
|
|
48
|
+
return { cmd: process.execPath, args: [mjs, "--headless"], cwd: dir }
|
|
49
|
+
}
|
|
50
|
+
const bridgePy = join(dir, "bridge.py")
|
|
51
|
+
if (existsSync(bridgePy)) {
|
|
52
|
+
const py = process.platform === "win32" ? "python" : "python3"
|
|
53
|
+
return { cmd: py, args: ["-B", bridgePy, "--config", join(dir, "config.json")], cwd: dir }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { cmd: process.platform === "win32" ? "krnell.cmd" : "krnell", args: ["--headless"] }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function isBridgeAlive(origin: string, timeoutMs = 900): Promise<boolean> {
|
|
60
|
+
try {
|
|
61
|
+
const r = await fetch(`${origin}/healthz`, { signal: AbortSignal.timeout(timeoutMs) })
|
|
62
|
+
if (r.ok) return true
|
|
63
|
+
} catch {}
|
|
64
|
+
try {
|
|
65
|
+
const r = await fetch(`${origin}/_bridge/status`, { signal: AbortSignal.timeout(timeoutMs) })
|
|
66
|
+
return r.status < 500
|
|
67
|
+
} catch {
|
|
68
|
+
return false
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Inicialização inteligente sob demanda:
|
|
74
|
+
* só sobe o Krnell em background se o alvo for loopback local, o bridge estiver
|
|
75
|
+
* offline e houver uso real (chamada com modelo Krnell/KimiBridge ou /connect).
|
|
76
|
+
*/
|
|
77
|
+
async function ensureKrnellRunning(origin: string, reason: string): Promise<boolean> {
|
|
78
|
+
if (!isLocalBridgeOrigin(origin)) return false
|
|
79
|
+
if (await isBridgeAlive(origin, 700)) return true
|
|
80
|
+
if (ensureBridgePromise) return ensureBridgePromise
|
|
81
|
+
const now = Date.now()
|
|
82
|
+
if (now - lastEnsureAttemptAt < 10_000) return false
|
|
83
|
+
lastEnsureAttemptAt = now
|
|
84
|
+
|
|
85
|
+
ensureBridgePromise = (async () => {
|
|
86
|
+
const launch = findKrnellCommand()
|
|
87
|
+
if (!launch) return false
|
|
88
|
+
try {
|
|
89
|
+
const child = spawn(launch.cmd, launch.args, {
|
|
90
|
+
cwd: launch.cwd,
|
|
91
|
+
detached: true,
|
|
92
|
+
stdio: "ignore",
|
|
93
|
+
windowsHide: true,
|
|
94
|
+
env: { ...process.env, KRNELL_STARTED_BY: `opencode-plugin:${reason}` },
|
|
95
|
+
})
|
|
96
|
+
child.unref()
|
|
97
|
+
} catch {
|
|
98
|
+
return false
|
|
99
|
+
}
|
|
100
|
+
const deadline = Date.now() + 12_000
|
|
101
|
+
while (Date.now() < deadline) {
|
|
102
|
+
if (await isBridgeAlive(origin, 600)) return true
|
|
103
|
+
await new Promise((r) => setTimeout(r, 350))
|
|
104
|
+
}
|
|
105
|
+
return false
|
|
106
|
+
})().finally(() => {
|
|
107
|
+
ensureBridgePromise = null
|
|
108
|
+
})
|
|
109
|
+
return ensureBridgePromise
|
|
110
|
+
}
|
|
111
|
+
|
|
21
112
|
let cachedFile = ""
|
|
22
113
|
let cachedMtimeMs = -1
|
|
23
114
|
let cachedText = ""
|
|
@@ -123,7 +214,15 @@ export default {
|
|
|
123
214
|
// -----------------------------------------------------------------
|
|
124
215
|
// 1. Substituição do system prompt via AGENTS.md
|
|
125
216
|
// -----------------------------------------------------------------
|
|
126
|
-
const makeApply = (hook: string) => (event: any) => {
|
|
217
|
+
const makeApply = (hook: string) => async (event: any) => {
|
|
218
|
+
// Momento inteligente 1: se a chamada atual vai usar krnell/kimibridge/nyxo
|
|
219
|
+
// e o bridge local ainda não está no ar, sobe em background automaticamente.
|
|
220
|
+
const provID = String(event?.model?.providerID || event?.providerID || "").toLowerCase()
|
|
221
|
+
if (INTEGRATION_IDS.includes(provID)) {
|
|
222
|
+
const origin = await resolveBridgeOrigin(ctx, provID)
|
|
223
|
+
await ensureKrnellRunning(origin, `hook:${hook}`)
|
|
224
|
+
}
|
|
225
|
+
|
|
127
226
|
const text = loadPrompt()
|
|
128
227
|
if (!text) return
|
|
129
228
|
|
|
@@ -172,7 +271,7 @@ export default {
|
|
|
172
271
|
if (ctx?.integration?.transform) {
|
|
173
272
|
await ctx.integration.transform((reg: any) => {
|
|
174
273
|
for (const integrationID of INTEGRATION_IDS) {
|
|
175
|
-
const pretty = integrationID === "nyxo" ? "Nyxo Bridge (local)" : "Kimi Bridge (local)"
|
|
274
|
+
const pretty = integrationID === "krnell" ? "Krnell (local)" : integrationID === "nyxo" ? "Nyxo Bridge (local)" : "Kimi Bridge (local)"
|
|
176
275
|
reg.update(integrationID, (ref: any) => {
|
|
177
276
|
if (!ref.name || ref.name === integrationID) ref.name = pretty
|
|
178
277
|
})
|
|
@@ -191,6 +290,8 @@ export default {
|
|
|
191
290
|
},
|
|
192
291
|
authorize: async () => {
|
|
193
292
|
const base = await resolveBridgeOrigin(ctx, integrationID)
|
|
293
|
+
// Momento inteligente 2: ao abrir /connect para Antigravity, garante o Krnell no ar.
|
|
294
|
+
await ensureKrnellRunning(base, "connect-oauth")
|
|
194
295
|
let started: any
|
|
195
296
|
try {
|
|
196
297
|
const res = await fetch(`${base}/antigravity/login/start`, {
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { spawn } from "node:child_process"
|
|
2
|
+
import { existsSync } from "node:fs"
|
|
3
|
+
import { homedir } from "node:os"
|
|
4
|
+
import { join } from "node:path"
|
|
5
|
+
import { createSignal, onCleanup } from "solid-js"
|
|
6
|
+
|
|
7
|
+
const BRIDGE_ORIGIN = (process.env.KRNELL_BRIDGE_URL || process.env.NYXO_BRIDGE_URL || "http://127.0.0.1:8765").replace(/\/+$/, "")
|
|
8
|
+
|
|
9
|
+
function findKrnellTuiCommand(): { cmd: string; args: string[]; cwd?: string } {
|
|
10
|
+
const home = homedir()
|
|
11
|
+
const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
|
|
12
|
+
const dataHome = process.env.XDG_DATA_HOME || join(home, ".local", "share")
|
|
13
|
+
const dirs = [
|
|
14
|
+
process.env.KRNELL_HOME,
|
|
15
|
+
process.env.NYXO_HOME,
|
|
16
|
+
process.platform === "win32" ? join(localAppData, "Krnell") : join(dataHome, "krnell"),
|
|
17
|
+
join(home, "bridge-package", "nyxo"),
|
|
18
|
+
].filter(Boolean) as string[]
|
|
19
|
+
|
|
20
|
+
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)) {
|
|
25
|
+
const py = process.platform === "win32" ? "python" : "python3"
|
|
26
|
+
return { cmd: py, args: ["-B", painelPy], cwd: dir }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return { cmd: process.platform === "win32" ? "krnell.cmd" : "krnell", args: [] }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function pingKrnell(): Promise<boolean> {
|
|
33
|
+
try {
|
|
34
|
+
const r = await fetch(`${BRIDGE_ORIGIN}/healthz`, { signal: AbortSignal.timeout(700) })
|
|
35
|
+
if (r.ok) return true
|
|
36
|
+
} catch {}
|
|
37
|
+
try {
|
|
38
|
+
const r = await fetch(`${BRIDGE_ORIGIN}/_bridge/status`, { signal: AbortSignal.timeout(700) })
|
|
39
|
+
return r.status < 500
|
|
40
|
+
} catch {
|
|
41
|
+
return false
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export default {
|
|
46
|
+
id: "krnell.tui",
|
|
47
|
+
setup(t: any) {
|
|
48
|
+
const [online, setOnline] = createSignal(false)
|
|
49
|
+
const [opening, setOpening] = createSignal(false)
|
|
50
|
+
|
|
51
|
+
const refresh = async () => {
|
|
52
|
+
setOnline(await pingKrnell())
|
|
53
|
+
}
|
|
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)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Comando `/krnell` na paleta e slash do OpenCode
|
|
90
|
+
t.keymap?.layer?.(() => ({
|
|
91
|
+
mode: "global",
|
|
92
|
+
commands: [
|
|
93
|
+
{
|
|
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)",
|
|
97
|
+
group: "Krnell",
|
|
98
|
+
palette: true,
|
|
99
|
+
slash: { name: "krnell" },
|
|
100
|
+
run: () => void openKrnell(),
|
|
101
|
+
},
|
|
102
|
+
],
|
|
103
|
+
}))
|
|
104
|
+
|
|
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
|
+
})
|
|
127
|
+
},
|
|
128
|
+
}
|
|
@@ -812,88 +812,12 @@ ${opencodeModelsBlock(' ')}
|
|
|
812
812
|
}
|
|
813
813
|
|
|
814
814
|
// ---------- autostart ----------
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
815
|
+
// Autostart no boot removido por segurança/controle: o Krnell agora sobe sob
|
|
816
|
+
// demanda (pelo `krnell` ou inteligentemente pelo plugin do OpenCode somente
|
|
817
|
+
// quando o usuário usa um modelo Krnell/KimiBridge ou clica no botão do footer).
|
|
819
818
|
async function installAutostart() {
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
const script = path.join(APP_DIR, 'bridge.mjs');
|
|
823
|
-
const winNode = path.join(APP_DIR, 'node', 'node.exe');
|
|
824
|
-
const nodePath = IS_WIN && fs.existsSync(winNode) ? winNode : process.execPath;
|
|
825
|
-
try {
|
|
826
|
-
if (IS_WIN) {
|
|
827
|
-
const dir = startupDir();
|
|
828
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
829
|
-
const vbs = path.join(dir, 'KimiBridge.vbs');
|
|
830
|
-
if (!fs.existsSync(vbs)) {
|
|
831
|
-
const bootBat = path.join(APP_DIR, 'iniciar_oculto.bat');
|
|
832
|
-
fs.writeFileSync(bootBat, `@echo off\r\ncd /d "${APP_DIR}"\r\n"${nodePath}" "${script}" >> "${path.join(LOG_DIR, 'boot.log')}" 2>&1\r\n`);
|
|
833
|
-
fs.writeFileSync(vbs, `Set sh = CreateObject("WScript.Shell")\r\nsh.Run """${bootBat}""", 0, False\r\n`);
|
|
834
|
-
log('autostart: Windows (atalho oculto na inicializacao)');
|
|
835
|
-
}
|
|
836
|
-
} else {
|
|
837
|
-
let done = false;
|
|
838
|
-
if (!IS_TERMUX) {
|
|
839
|
-
try {
|
|
840
|
-
const r = await run('systemctl', ['--user', 'is-system-running']);
|
|
841
|
-
if (/running|degraded/.test(r.stdout)) {
|
|
842
|
-
const svcDir = path.join(HOME, '.config', 'systemd', 'user');
|
|
843
|
-
fs.mkdirSync(svcDir, { recursive: true });
|
|
844
|
-
const unit = path.join(svcDir, 'kimi-bridge.service');
|
|
845
|
-
if (!fs.existsSync(unit)) {
|
|
846
|
-
fs.writeFileSync(unit, `[Unit]
|
|
847
|
-
Description=Kimi Bridge
|
|
848
|
-
After=network-online.target
|
|
849
|
-
|
|
850
|
-
[Service]
|
|
851
|
-
Type=simple
|
|
852
|
-
WorkingDirectory=${APP_DIR}
|
|
853
|
-
ExecStart=${nodePath} ${script}
|
|
854
|
-
Restart=on-failure
|
|
855
|
-
RestartSec=10
|
|
856
|
-
|
|
857
|
-
[Install]
|
|
858
|
-
WantedBy=default.target
|
|
859
|
-
`);
|
|
860
|
-
await run('systemctl', ['--user', 'daemon-reload']);
|
|
861
|
-
await run('systemctl', ['--user', 'enable', 'kimi-bridge.service']);
|
|
862
|
-
log('autostart: servico systemd de usuario');
|
|
863
|
-
}
|
|
864
|
-
done = true;
|
|
865
|
-
}
|
|
866
|
-
} catch {}
|
|
867
|
-
}
|
|
868
|
-
if (!done && !IS_TERMUX && (await commandExists('crontab'))) {
|
|
869
|
-
const current = (await run('crontab', ['-l'])).stdout || '';
|
|
870
|
-
if (!current.includes(APP_DIR)) {
|
|
871
|
-
const line = `@reboot cd ${APP_DIR} && ${nodePath} ${script} >> ${path.join(LOG_DIR, 'boot.log')} 2>&1`;
|
|
872
|
-
await run('sh', ['-c', `(crontab -l 2>/dev/null; echo "${line}") | crontab -`]);
|
|
873
|
-
log('autostart: cron @reboot');
|
|
874
|
-
}
|
|
875
|
-
done = true;
|
|
876
|
-
}
|
|
877
|
-
if (!done) {
|
|
878
|
-
const prof = path.join(HOME, '.profile');
|
|
879
|
-
const txt = fs.existsSync(prof) ? fs.readFileSync(prof, 'utf8') : '';
|
|
880
|
-
if (!txt.includes('# kimi-bridge autostart')) {
|
|
881
|
-
const sh = path.join(APP_DIR, 'iniciar.sh');
|
|
882
|
-
const agFile = path.join(APP_DIR, 'antigravity.json');
|
|
883
|
-
const bootLog = path.join(LOG_DIR, 'boot.log');
|
|
884
|
-
fs.appendFileSync(
|
|
885
|
-
prof,
|
|
886
|
-
`\n# kimi-bridge autostart\nif ! curl -sf http://${CFG.host}:${CFG.port}/healthz >/dev/null 2>&1; then\n if [ -t 0 ] && [ ! -s "${agFile}" ]; then\n bash "${sh}"\n else\n nohup bash "${sh}" --background >> "${bootLog}" 2>&1 &\n fi\nfi\n`
|
|
887
|
-
);
|
|
888
|
-
log('autostart: login do shell (~/.profile)');
|
|
889
|
-
}
|
|
890
|
-
done = true;
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
} catch (e) {
|
|
894
|
-
log('autostart nao instalado:', e.message);
|
|
895
|
-
}
|
|
896
|
-
try { fs.writeFileSync(marker, new Date().toISOString()); } catch {}
|
|
819
|
+
// Não grava nada em Startup, systemd, crontab ou ~/.profile.
|
|
820
|
+
return;
|
|
897
821
|
}
|
|
898
822
|
|
|
899
823
|
// ---------- estado do browser/captcha (pool paralelo + auto-hibernacao) ----------
|
package/tui_core.py
CHANGED
|
@@ -113,13 +113,13 @@ def pad_vis(s: str, largura: int) -> str:
|
|
|
113
113
|
return s + (' ' * faltam)
|
|
114
114
|
|
|
115
115
|
|
|
116
|
-
def barra_progresso(fracao: float | None, largura: int =
|
|
117
|
-
"""Barrinha
|
|
116
|
+
def barra_progresso(fracao: float | None, largura: int = 8) -> str:
|
|
117
|
+
"""Barrinha fina e limpa estilo OpenCode (sem bloco sólido estourando)."""
|
|
118
118
|
if fracao is None:
|
|
119
|
-
return '
|
|
119
|
+
return '─' * largura
|
|
120
120
|
f = max(0.0, min(1.0, float(fracao)))
|
|
121
121
|
cheios = int(round(f * largura))
|
|
122
|
-
return '
|
|
122
|
+
return '━' * cheios + '─' * max(0, largura - cheios)
|
|
123
123
|
|
|
124
124
|
|
|
125
125
|
class TerminalPosix:
|
|
@@ -133,6 +133,8 @@ class TerminalPosix:
|
|
|
133
133
|
self._prev_winch = None
|
|
134
134
|
self._in_paste = False
|
|
135
135
|
self._paste_chars: list[str] = []
|
|
136
|
+
self._drag_y: int | None = None
|
|
137
|
+
self._drag_moved = False
|
|
136
138
|
|
|
137
139
|
def entrar(self) -> bool:
|
|
138
140
|
if os.name == 'nt' or termios is None or tty is None:
|
|
@@ -157,9 +159,10 @@ class TerminalPosix:
|
|
|
157
159
|
modo[6][termios.VMIN] = 1
|
|
158
160
|
modo[6][termios.VTIME] = 0
|
|
159
161
|
termios.tcsetattr(self._fd, termios.TCSAFLUSH, modo)
|
|
160
|
-
# Mouse SGR (1000=clique/roda,
|
|
161
|
-
#
|
|
162
|
-
|
|
162
|
+
# Mouse SGR (1000=clique/roda, 1002=arrastar com dedo/botão, 1006=SGR)
|
|
163
|
+
# + bracketed paste (2004). 1002 permite scroll arrastando o dedo no Termux
|
|
164
|
+
# sem inundar com eventos de hover sem toque (1003 fica desligado).
|
|
165
|
+
sys.stdout.write('\x1b[?1000h\x1b[?1002h\x1b[?1006h\x1b[?2004h')
|
|
163
166
|
sys.stdout.flush()
|
|
164
167
|
if hasattr(signal, 'SIGWINCH'):
|
|
165
168
|
self._prev_winch = signal.getsignal(signal.SIGWINCH)
|
|
@@ -180,7 +183,7 @@ class TerminalPosix:
|
|
|
180
183
|
|
|
181
184
|
def sair(self) -> None:
|
|
182
185
|
try:
|
|
183
|
-
sys.stdout.write('\x1b[?2004l\x1b[?1006l\x1b[?1000l')
|
|
186
|
+
sys.stdout.write('\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1000l')
|
|
184
187
|
sys.stdout.flush()
|
|
185
188
|
except Exception:
|
|
186
189
|
pass
|
|
@@ -356,15 +359,54 @@ class TerminalPosix:
|
|
|
356
359
|
if not m:
|
|
357
360
|
return None
|
|
358
361
|
btn, x, y, kind = int(m.group(1)), int(m.group(2)) - 1, int(m.group(3)) - 1, m.group(4)
|
|
359
|
-
|
|
362
|
+
# Roda do mouse e scroll por swipe no Termux (ignora modificadores Shift/Ctrl/Alt)
|
|
363
|
+
base_btn = btn & ~28
|
|
364
|
+
if base_btn == 64:
|
|
365
|
+
self._drag_y = None
|
|
366
|
+
self._drag_moved = False
|
|
360
367
|
return ('mouse_roda', -1)
|
|
361
|
-
if
|
|
368
|
+
if base_btn == 65:
|
|
369
|
+
self._drag_y = None
|
|
370
|
+
self._drag_moved = False
|
|
362
371
|
return ('mouse_roda', 1)
|
|
372
|
+
# Arrastar verticalmente com o dedo/botão pressionado (modo 1002: bit 32 + botão 0)
|
|
373
|
+
if kind == 'M' and (btn & 32) and (btn & 3) == 0:
|
|
374
|
+
if self._drag_y is not None and y != self._drag_y:
|
|
375
|
+
dy = y - self._drag_y
|
|
376
|
+
self._drag_y = y
|
|
377
|
+
self._drag_moved = True
|
|
378
|
+
# Arrastar dedo para cima (dy < 0) rola lista para baixo (+1), natural mobile
|
|
379
|
+
return ('mouse_roda', 1 if dy < 0 else -1)
|
|
380
|
+
self._drag_y = y
|
|
381
|
+
return None
|
|
382
|
+
# Toque/clique pressionado: registra início; se soltar sem arrastar dispara clique
|
|
363
383
|
if kind == 'M' and (btn & 3) == 0 and not (btn & 32):
|
|
364
|
-
|
|
384
|
+
self._drag_y = y
|
|
385
|
+
self._drag_moved = False
|
|
386
|
+
return None
|
|
387
|
+
if kind == 'm' and (btn & 3) == 0:
|
|
388
|
+
arrastou = self._drag_moved
|
|
389
|
+
self._drag_y = None
|
|
390
|
+
self._drag_moved = False
|
|
391
|
+
return None if arrastou else ('mouse_clique', x, y)
|
|
365
392
|
if btn & 32:
|
|
366
393
|
return ('mouse_move', x, y)
|
|
367
394
|
return None
|
|
395
|
+
# Mouse X10 legado (CSI M cb cx cy): fallback de alguns terminais Android/Termux
|
|
396
|
+
if seq == 'M':
|
|
397
|
+
while len(self._buf) < 3 and self._ler_disponivel(0.02):
|
|
398
|
+
pass
|
|
399
|
+
if len(self._buf) >= 3:
|
|
400
|
+
cb, cx, cy = self._buf[0] - 32, self._buf[1] - 33, self._buf[2] - 33
|
|
401
|
+
del self._buf[:3]
|
|
402
|
+
base_cb = cb & ~28
|
|
403
|
+
if base_cb == 64:
|
|
404
|
+
return ('mouse_roda', -1)
|
|
405
|
+
if base_cb == 65:
|
|
406
|
+
return ('mouse_roda', 1)
|
|
407
|
+
if (cb & 3) == 0 and not (cb & 32):
|
|
408
|
+
return ('mouse_clique', max(0, cx), max(0, cy))
|
|
409
|
+
return None
|
|
368
410
|
mapa = {
|
|
369
411
|
'A': 'cima', 'B': 'baixo', 'C': 'direita', 'D': 'esquerda',
|
|
370
412
|
'H': 'home', 'F': 'end', 'Z': 'shift_tab',
|
|
@@ -513,16 +555,93 @@ def construir_dialogo_opencode(
|
|
|
513
555
|
# Extrai índices selecionáveis e janela visível
|
|
514
556
|
selecionaveis = [i for i, it in enumerate(itens) if it.get('tipo', 'item') == 'item']
|
|
515
557
|
total_sel = len(selecionaveis)
|
|
558
|
+
tem_textos = any(it.get('tipo') == 'texto' for it in itens)
|
|
559
|
+
|
|
560
|
+
def _add_texto_item(it: dict) -> None:
|
|
561
|
+
rich_obj = it.get('rich')
|
|
562
|
+
if isinstance(rich_obj, Text):
|
|
563
|
+
t = Text()
|
|
564
|
+
t.append(' ', style=bg.strip())
|
|
565
|
+
# Preserva cores de cada span sobre o fundo do diálogo, truncando para caber
|
|
566
|
+
usado = 0
|
|
567
|
+
max_w = max(4, inner - 4)
|
|
568
|
+
for span_txt in rich_obj.split('\n')[:1]:
|
|
569
|
+
# Copia texto com corte por cell_len
|
|
570
|
+
if cell_len(span_txt.plain) <= max_w:
|
|
571
|
+
for seg in span_txt.spans:
|
|
572
|
+
pass
|
|
573
|
+
copia = span_txt.copy()
|
|
574
|
+
copia.stylize(bg.strip())
|
|
575
|
+
t.append_text(copia)
|
|
576
|
+
usado = cell_len(span_txt.plain)
|
|
577
|
+
else:
|
|
578
|
+
cortado = truncate_vis(span_txt.plain, max_w)
|
|
579
|
+
t.append(cortado, style=f'{it.get("cor") or texto}{bg}')
|
|
580
|
+
usado = cell_len(cortado)
|
|
581
|
+
linhas.append(frame_line(t, max(0, inner - 2 - usado)))
|
|
582
|
+
return
|
|
583
|
+
txt = truncate_vis(str(it.get('rotulo') or ''), max(4, inner - 4))
|
|
584
|
+
cor = it.get('cor') or fraco
|
|
585
|
+
t = Text()
|
|
586
|
+
t.append(' ' + txt, style=f'{cor}{bg}')
|
|
587
|
+
linhas.append(frame_line(t, max(0, inner - 2 - cell_len(txt))))
|
|
516
588
|
|
|
517
589
|
if total_sel == 0:
|
|
518
590
|
# Só texto informativo ou lista vazia (respeita `limite` em telas baixas)
|
|
519
591
|
vis_txt = itens[:max(1, limite)] if limite else itens
|
|
520
592
|
for it in vis_txt:
|
|
521
|
-
|
|
522
|
-
|
|
593
|
+
_add_texto_item(it)
|
|
594
|
+
elif tem_textos:
|
|
595
|
+
# Diálogo misto (ex.: tela de login com instruções + botões clicáveis [Copiar link] / [Abrir navegador])
|
|
596
|
+
pos_sel = {idx_raw: pos for pos, idx_raw in enumerate(selecionaveis)}
|
|
597
|
+
vis_misto = itens[:max(1, limite)] if limite else itens
|
|
598
|
+
for idx_raw, it in enumerate(vis_misto):
|
|
599
|
+
tipo_it = it.get('tipo', 'item')
|
|
600
|
+
if tipo_it == 'texto':
|
|
601
|
+
_add_texto_item(it)
|
|
602
|
+
continue
|
|
603
|
+
if tipo_it == 'secao':
|
|
604
|
+
sec_vis = truncate_vis(str(it.get('rotulo') or '').upper(), max(4, inner - 4))
|
|
605
|
+
st = Text()
|
|
606
|
+
st.append(' ' + sec_vis, style=f'bold {acento2}{bg}')
|
|
607
|
+
linhas.append(frame_line(st, max(0, inner - 2 - cell_len(sec_vis))))
|
|
608
|
+
continue
|
|
609
|
+
pos = pos_sel[idx_raw]
|
|
610
|
+
focado = (pos == foco)
|
|
611
|
+
badge = str(it.get('badge') or ('●' if it.get('ativo') else ' '))
|
|
612
|
+
badge_cor = it.get('badge_cor') or (ok if it.get('ativo') else acento2)
|
|
613
|
+
rotulo = str(it.get('rotulo') or '')
|
|
614
|
+
detalhe = str(it.get('detalhe') or '')
|
|
615
|
+
prefix_w = 2 + cell_len(badge) + 1
|
|
616
|
+
max_det = max(0, (inner - prefix_w - 6) // 2) if detalhe else 0
|
|
617
|
+
det_vis = truncate_vis(detalhe, max_det) if (detalhe and max_det >= 6) else ''
|
|
618
|
+
max_rot = max(4, inner - prefix_w - 2 - (cell_len(det_vis) + 2 if det_vis else 0))
|
|
619
|
+
rot_vis = truncate_vis(rotulo, max_rot)
|
|
620
|
+
gap = max(1, inner - prefix_w - cell_len(rot_vis) - cell_len(det_vis) - 2) if det_vis else max(0, inner - prefix_w - cell_len(rot_vis))
|
|
523
621
|
t = Text()
|
|
524
|
-
|
|
525
|
-
|
|
622
|
+
if focado:
|
|
623
|
+
hi = f'bold {texto_acento} on {acento}'
|
|
624
|
+
hi_dim = f'{texto_acento} on {acento}'
|
|
625
|
+
t.append(f' {badge} ', style=hi)
|
|
626
|
+
t.append(rot_vis, style=hi)
|
|
627
|
+
if det_vis:
|
|
628
|
+
t.append(' ' * gap, style=hi)
|
|
629
|
+
t.append(det_vis, style=hi_dim)
|
|
630
|
+
t.append(' ', style=hi)
|
|
631
|
+
else:
|
|
632
|
+
t.append(' ' * gap, style=hi)
|
|
633
|
+
else:
|
|
634
|
+
t.append(' ', style=bg.strip())
|
|
635
|
+
t.append(badge + ' ', style=f'{badge_cor}{bg}')
|
|
636
|
+
t.append(rot_vis, style=f'bold {acento if it.get("ativo") else texto}{bg}')
|
|
637
|
+
if det_vis:
|
|
638
|
+
t.append(' ' * gap, style=bg.strip())
|
|
639
|
+
t.append(det_vis, style=f'{fraco}{bg}')
|
|
640
|
+
t.append(' ', style=bg.strip())
|
|
641
|
+
else:
|
|
642
|
+
t.append(' ' * gap, style=bg.strip())
|
|
643
|
+
mapa_clique[len(linhas)] = pos
|
|
644
|
+
linhas.append(frame_line(t))
|
|
526
645
|
else:
|
|
527
646
|
# Janela baseada nos selecionáveis, mantendo cabeçalho de seção acima do primeiro item dela
|
|
528
647
|
vis_sel_indices = selecionaveis[topo:topo + limite]
|
|
@@ -607,7 +726,7 @@ def construir_dialogo_opencode(
|
|
|
607
726
|
|
|
608
727
|
# Rodapé de atalhos
|
|
609
728
|
linhas.append(frame_line(Text(' ' * inner, style=bg.strip())))
|
|
610
|
-
rod_vis = truncate_vis(rodape, inner - 4)
|
|
729
|
+
rod_vis = truncate_vis(rodape, max(4, inner - 4))
|
|
611
730
|
rt = Text()
|
|
612
731
|
rt.append(' ' + rod_vis, style=f'{fraco}{bg}')
|
|
613
732
|
linhas.append(frame_line(rt, max(0, inner - 2 - cell_len(rod_vis))))
|