krnell 0.0.0-stage → 3.0.0

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.
Files changed (50) hide show
  1. package/Iniciar_Linux.sh +129 -0
  2. package/Instalar_Atalho_Windows.cmd +40 -0
  3. package/Instalar_Ubuntu.sh +95 -0
  4. package/Painel.cmd +138 -0
  5. package/README.md +70 -2
  6. package/bin/nyxo.mjs +138 -0
  7. package/bridge.py +5196 -0
  8. package/config.example.json +57 -0
  9. package/contexto.py +184 -0
  10. package/dashboard_web.py +308 -0
  11. package/dns_duck.py +227 -0
  12. package/ferramentas/Liberar_Firewall.ps1 +96 -0
  13. package/ferramentas/firewall_linux.sh +67 -0
  14. package/ferramentas/install_windows.py +482 -0
  15. package/ferramentas/selecionar_provedor.py +70 -0
  16. package/iniciar.sh +255 -0
  17. package/keys.example.env +3 -0
  18. package/kimi.py +482 -0
  19. package/opencode_sync.py +239 -0
  20. package/package.json +69 -4
  21. package/painel.py +5227 -0
  22. package/painel_web.py +367 -0
  23. package/plugins/system-prompt/index.ts +409 -0
  24. package/provedores/kimi/bridge.mjs +4280 -0
  25. package/provedores/kimi/package.json +10 -0
  26. package/provedores_catalogo.py +155 -0
  27. package/tls_proxy.py +205 -0
  28. package/tui_core.py +600 -0
  29. package/web/dist/.vite/manifest.json +84 -0
  30. package/web/dist/assets/LogsPage-DkXN-I7o.js +2 -0
  31. package/web/dist/assets/LogsPage-OsSvuqxQ.js +2 -0
  32. package/web/dist/assets/TerminalPage-CZTPxVyx.js +1 -0
  33. package/web/dist/assets/TerminalPage-D208X99P.js +1 -0
  34. package/web/dist/assets/TerminalPage-DYGPu4ux.css +1 -0
  35. package/web/dist/assets/index-B5rIwous.js +1 -0
  36. package/web/dist/assets/index-CJE_a_Tn.js +27 -0
  37. package/web/dist/assets/index-COlDAcsY.js +1 -0
  38. package/web/dist/assets/index-Dzc8Obwp.css +1 -0
  39. package/web/dist/assets/index-LZadV7rx.js +27 -0
  40. package/web/dist/assets/index-o8xT03ZV.css +1 -0
  41. package/web/dist/assets/press-start-2p-2BZhbCiP.ttf +0 -0
  42. package/web/dist/assets/react-vendor-C475ILlI.js +49 -0
  43. package/web/dist/assets/terminal-vendor-DOrYoP_4.css +32 -0
  44. package/web/dist/assets/terminal-vendor-Dp03d74L.js +38 -0
  45. package/web/dist/assets/terminal-webgl-BRBWwLY7.js +75 -0
  46. package/web/dist/favicon.svg +1 -0
  47. package/web/dist/fonts/OFL.txt +93 -0
  48. package/web/dist/fonts/press-start-2p.ttf +0 -0
  49. package/web/dist/index.html +18 -0
  50. package/workbuddy.py +1965 -0
@@ -0,0 +1,409 @@
1
+ // System prompt definitivo + Login Antigravity multi-conta no /connect do OpenCode.
2
+ //
3
+ // 1) System prompt (AGENTS.md):
4
+ // Os hooks "context", "compaction" e "generate" rodam imediatamente antes de
5
+ // cada chamada ao modelo (turno normal, compactação de contexto e geração
6
+ // auxiliar) e substituem o array `system` pelo conteúdo do AGENTS.md
7
+ // (recarregado por mtime sem reiniciar o OpenCode).
8
+ //
9
+ // 2) /connect -> Kimi Bridge (local):
10
+ // Remove o prompt manual de API key do provider "kimibridge" e coloca no
11
+ // lugar o login OAuth do Google Antigravity via bridge local, suportando
12
+ // múltiplas contas com troca automática quando uma conta esgota a quota.
13
+ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"
14
+ import { homedir } from "node:os"
15
+ import { join } from "node:path"
16
+
17
+ const INTEGRATION_IDS = ["nyxo", "kimibridge"]
18
+ const METHOD_ID = "antigravity-oauth"
19
+ const DEFAULT_BRIDGE_ORIGIN = "http://127.0.0.1:8765"
20
+
21
+ let cachedFile = ""
22
+ let cachedMtimeMs = -1
23
+ let cachedText = ""
24
+
25
+ function defaultPromptFile(): string {
26
+ const primary = join(homedir(), ".config", "opencode", "AGENTS.md")
27
+ if (existsSync(primary)) return primary
28
+ if (process.platform === "win32" && process.env.APPDATA) {
29
+ const winCfg = join(process.env.APPDATA, "opencode", "AGENTS.md")
30
+ if (existsSync(winCfg)) return winCfg
31
+ }
32
+ return primary
33
+ }
34
+
35
+ function promptFile(): string {
36
+ return process.env.ENI_SYSTEM_PROMPT || defaultPromptFile()
37
+ }
38
+
39
+ function loadPrompt(): string | undefined {
40
+ try {
41
+ const file = promptFile()
42
+ const mtimeMs = statSync(file).mtimeMs
43
+ if (file !== cachedFile || mtimeMs !== cachedMtimeMs) {
44
+ const text = readFileSync(file, "utf8")
45
+ if (!text.trim()) return undefined
46
+ cachedFile = file
47
+ cachedText = text
48
+ cachedMtimeMs = mtimeMs
49
+ }
50
+ return cachedText
51
+ } catch {
52
+ // Arquivo ausente ou ilegível: não destrói o prompt que o OpenCode montou.
53
+ return undefined
54
+ }
55
+ }
56
+
57
+ function normalizeBridgeOrigin(baseURL?: string): string {
58
+ const raw = String(baseURL || "").trim()
59
+ if (!raw) return ""
60
+ try {
61
+ const u = new URL(raw)
62
+ return `${u.protocol}//${u.host}`
63
+ } catch {
64
+ return raw.replace(/\/v1\/?$/i, "").replace(/\/+$/, "")
65
+ }
66
+ }
67
+
68
+ async function resolveBridgeOrigin(ctx: any, preferredId?: string): Promise<string> {
69
+ if (process.env.NYXO_BRIDGE_URL) {
70
+ const envOrigin = normalizeBridgeOrigin(process.env.NYXO_BRIDGE_URL)
71
+ if (envOrigin) return envOrigin
72
+ }
73
+ if (process.env.KIMI_BRIDGE_URL) {
74
+ const envOrigin = normalizeBridgeOrigin(process.env.KIMI_BRIDGE_URL)
75
+ if (envOrigin) return envOrigin
76
+ }
77
+ const order = preferredId ? [preferredId, ...INTEGRATION_IDS.filter((x) => x !== preferredId)] : INTEGRATION_IDS
78
+ for (const id of order) {
79
+ try {
80
+ if (ctx?.provider?.get) {
81
+ const prov = await ctx.provider.get({ providerID: id })
82
+ const baseURL = prov?.settings?.baseURL || prov?.provider?.settings?.baseURL
83
+ const origin = normalizeBridgeOrigin(baseURL)
84
+ if (origin) return origin
85
+ }
86
+ } catch {
87
+ // tenta proximo provider
88
+ }
89
+ }
90
+ return DEFAULT_BRIDGE_ORIGIN
91
+ }
92
+
93
+ function makeOAuthCredential(account: any) {
94
+ const email = String(account?.email || account?.id || "antigravity").trim()
95
+ const accountId = email.toLowerCase()
96
+ return {
97
+ type: "oauth" as const,
98
+ methodID: METHOD_ID,
99
+ access: `ag:${accountId}`,
100
+ refresh: `ag:${accountId}`,
101
+ expires: Date.now() + 365 * 24 * 60 * 60 * 1000,
102
+ metadata: {
103
+ email,
104
+ projectId: String(account?.projectId || ""),
105
+ paidTier: String(account?.paidTierName || account?.paidTier || ""),
106
+ },
107
+ }
108
+ }
109
+
110
+ function extractEmailFromCredOrConn(cred: any, conn?: any): string {
111
+ const metaEmail = cred?.metadata?.email
112
+ if (typeof metaEmail === "string" && metaEmail.trim()) return metaEmail.trim()
113
+ const access = typeof cred?.access === "string" ? cred.access.trim() : ""
114
+ if (access.toLowerCase().startsWith("ag:")) return access.slice(3).trim()
115
+ const label = typeof conn?.label === "string" ? conn.label.trim() : ""
116
+ if (label.includes("@")) return label
117
+ return ""
118
+ }
119
+
120
+ export default {
121
+ id: "eni.system-prompt",
122
+ async setup(ctx: any) {
123
+ // -----------------------------------------------------------------
124
+ // 1. Substituição do system prompt via AGENTS.md
125
+ // -----------------------------------------------------------------
126
+ const makeApply = (hook: string) => (event: any) => {
127
+ const text = loadPrompt()
128
+ if (!text) return
129
+
130
+ // Remove tudo o que o OpenCode montou e deixa só o arquivo.
131
+ event.system.splice(0, event.system.length, { type: "text", text })
132
+
133
+ try {
134
+ const dump =
135
+ process.env.ENI_SYSTEM_DUMP ||
136
+ (existsSync("/tmp/opencode/dump-enabled") ? "/tmp/opencode/system-last.json" : undefined)
137
+ if (dump) {
138
+ writeFileSync(
139
+ dump,
140
+ JSON.stringify(
141
+ {
142
+ hook,
143
+ agent: event.agent,
144
+ sessionID: event.sessionID,
145
+ file: promptFile(),
146
+ bytes: Buffer.byteLength(text),
147
+ parts: event.system.length,
148
+ system: event.system,
149
+ },
150
+ null,
151
+ 2,
152
+ ),
153
+ )
154
+ }
155
+ } catch {
156
+ // Dump opcional: ignora erros de escrita.
157
+ }
158
+ }
159
+
160
+ if (ctx?.session?.hook) {
161
+ await ctx.session.hook("context", makeApply("context"))
162
+ await ctx.session.hook("compaction", makeApply("compaction"))
163
+ await ctx.session.hook("generate", makeApply("generate"))
164
+ }
165
+
166
+ // -----------------------------------------------------------------
167
+ // 2. /connect -> Kimi Bridge: Login Google (Antigravity multi-conta)
168
+ // Substitui o "Manually enter API Key" pelo fluxo OAuth da bridge.
169
+ // -----------------------------------------------------------------
170
+ const pluginAbort = new AbortController()
171
+
172
+ if (ctx?.integration?.transform) {
173
+ await ctx.integration.transform((reg: any) => {
174
+ for (const integrationID of INTEGRATION_IDS) {
175
+ const pretty = integrationID === "nyxo" ? "Nyxo Bridge (local)" : "Kimi Bridge (local)"
176
+ reg.update(integrationID, (ref: any) => {
177
+ if (!ref.name || ref.name === integrationID) ref.name = pretty
178
+ })
179
+ reg.method.remove(integrationID, { type: "key" })
180
+ reg.method.update({
181
+ integrationID,
182
+ method: {
183
+ id: METHOD_ID,
184
+ type: "oauth",
185
+ label: "Login com Google (Antigravity — multi-conta + troca automática)",
186
+ },
187
+ label: (cred: any) => {
188
+ const email = cred?.metadata?.email
189
+ if (typeof email === "string" && email.trim()) return email.trim()
190
+ return "Antigravity"
191
+ },
192
+ authorize: async () => {
193
+ const base = await resolveBridgeOrigin(ctx, integrationID)
194
+ let started: any
195
+ try {
196
+ const res = await fetch(`${base}/antigravity/login/start`, {
197
+ method: "POST",
198
+ headers: { accept: "application/json" },
199
+ signal: AbortSignal.timeout(8000),
200
+ })
201
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
202
+ started = await res.json()
203
+ } catch (err: any) {
204
+ throw new Error(
205
+ `Não foi possível falar com a bridge em ${base} (${err?.message || err}). Inicie o nyxo (bash iniciar.sh) e tente /connect novamente.`,
206
+ )
207
+ }
208
+
209
+ const state = String(started?.state || "")
210
+ const url = String(started?.shortUrl || started?.url || "")
211
+ if (!state || !url) {
212
+ throw new Error("A bridge não retornou a URL de login OAuth. Reinicie a bridge para a versão atualizada.")
213
+ }
214
+
215
+ let finished = false
216
+ let resolveAuth: ((cred: any) => void) | null = null
217
+ let rejectAuth: ((err: Error) => void) | null = null
218
+
219
+ const callback = new Promise<any>((resolve, reject) => {
220
+ resolveAuth = (cred) => {
221
+ if (finished) return
222
+ finished = true
223
+ resolve(cred)
224
+ }
225
+ rejectAuth = (err) => {
226
+ if (finished) return
227
+ finished = true
228
+ reject(err)
229
+ }
230
+
231
+ const deadline = Date.now() + 10 * 60 * 1000
232
+ const poll = async () => {
233
+ while (!finished && !pluginAbort.signal.aborted) {
234
+ if (Date.now() > deadline) {
235
+ rejectAuth?.(new Error("Tempo esgotado aguardando o login no Google."))
236
+ return
237
+ }
238
+ try {
239
+ const r = await fetch(
240
+ `${base}/antigravity/login/status?state=${encodeURIComponent(state)}`,
241
+ { signal: AbortSignal.timeout(5000) },
242
+ )
243
+ if (r.ok) {
244
+ const st: any = await r.json()
245
+ if (st.status === "complete" && st.account) {
246
+ resolveAuth?.(makeOAuthCredential(st.account))
247
+ return
248
+ }
249
+ if (st.status === "failed") {
250
+ rejectAuth?.(new Error(st.error || "Login no Antigravity falhou."))
251
+ return
252
+ }
253
+ if (st.status === "expired") {
254
+ rejectAuth?.(new Error("Link de login expirado. Tente /connect novamente."))
255
+ return
256
+ }
257
+ }
258
+ } catch {
259
+ // ignora falha pontual de polling
260
+ }
261
+ await new Promise((r) => setTimeout(r, 1200))
262
+ }
263
+ }
264
+ void poll()
265
+ })
266
+
267
+ const submit = async (input: string) => {
268
+ const raw = String(input || "").trim()
269
+ if (!raw) throw new Error("Cole a URL completa de retorno (com ?state=...&code=...).")
270
+ const res = await fetch(`${base}/antigravity/login/complete`, {
271
+ method: "POST",
272
+ headers: { "content-type": "application/json", accept: "application/json" },
273
+ body: JSON.stringify({ state, input: raw }),
274
+ signal: AbortSignal.timeout(20000),
275
+ })
276
+ const data: any = await res.json().catch(() => ({}))
277
+ if (!res.ok || !data.ok) {
278
+ throw new Error(data.error || `Falha ao validar callback (HTTP ${res.status}).`)
279
+ }
280
+ if (data.account) {
281
+ resolveAuth?.(makeOAuthCredential(data.account))
282
+ }
283
+ }
284
+
285
+ return {
286
+ mode: "auto" as const,
287
+ url,
288
+ instructions:
289
+ 'Aperte TAB ou clique em "copy link" abaixo para copiar e abra no navegador. Repita /connect para adicionar mais contas.',
290
+ callback,
291
+ submit,
292
+ }
293
+ },
294
+ refresh: async (cred: any) => {
295
+ return {
296
+ ...cred,
297
+ type: "oauth" as const,
298
+ methodID: METHOD_ID,
299
+ expires: Date.now() + 365 * 24 * 60 * 60 * 1000,
300
+ }
301
+ },
302
+ })
303
+ }
304
+ })
305
+ }
306
+
307
+ // -----------------------------------------------------------------
308
+ // 3. Sincroniza troca manual / remoção de conta do /connect -> bridge
309
+ // -----------------------------------------------------------------
310
+ if (ctx?.event?.subscribe && ctx?.integration?.get) {
311
+ const knownConns = new Map<string, string>() // "integrationID:connectionID" -> email
312
+
313
+ const snapshotConnections = async () => {
314
+ const next = new Map<string, string>()
315
+ for (const integrationID of INTEGRATION_IDS) {
316
+ try {
317
+ const info = await ctx.integration.get({ integrationID })
318
+ const conns = Array.isArray(info?.connections) ? info.connections : []
319
+ for (const c of conns) {
320
+ if (!c || c.type !== "credential" || !c.id) continue
321
+ let email = typeof c.label === "string" && c.label.includes("@") ? c.label.trim() : ""
322
+ if (!email && ctx.integration.connection?.resolve) {
323
+ try {
324
+ const resolved = await ctx.integration.connection.resolve(c)
325
+ email = extractEmailFromCredOrConn(resolved, c)
326
+ } catch {}
327
+ }
328
+ if (email) next.set(`${integrationID}:${c.id}`, email)
329
+ }
330
+ } catch {}
331
+ }
332
+ return next
333
+ }
334
+
335
+ const syncActiveToBridge = async (targetId?: string) => {
336
+ const ids = targetId ? [targetId] : INTEGRATION_IDS
337
+ for (const integrationID of ids) {
338
+ try {
339
+ if (!ctx.integration.connection?.active) continue
340
+ const active = await ctx.integration.connection.active(integrationID)
341
+ if (!active || active.type !== "credential") continue
342
+ const resolved = ctx.integration.connection.resolve
343
+ ? await ctx.integration.connection.resolve(active).catch(() => undefined)
344
+ : undefined
345
+ const email = extractEmailFromCredOrConn(resolved, active)
346
+ if (!email) continue
347
+ const base = await resolveBridgeOrigin(ctx, integrationID)
348
+ await fetch(`${base}/antigravity/accounts/active`, {
349
+ method: "POST",
350
+ headers: { "content-type": "application/json" },
351
+ body: JSON.stringify({ email }),
352
+ signal: AbortSignal.timeout(5000),
353
+ }).catch(() => {})
354
+ } catch {}
355
+ }
356
+ }
357
+
358
+ const startSync = async () => {
359
+ const init = await snapshotConnections()
360
+ for (const [k, v] of init) knownConns.set(k, v)
361
+
362
+ try {
363
+ const stream = ctx.event.subscribe({
364
+ types: ["credential.switched", "credential.updated"],
365
+ signal: pluginAbort.signal,
366
+ })
367
+ for await (const ev of stream) {
368
+ if (pluginAbort.signal.aborted) break
369
+ const data = ev?.data || ev?.properties || {}
370
+ const intId = String(data.integrationID || "")
371
+ if (intId && !INTEGRATION_IDS.includes(intId)) continue
372
+
373
+ if (ev?.type === "credential.switched") {
374
+ await syncActiveToBridge(intId || undefined)
375
+ continue
376
+ }
377
+
378
+ if (ev?.type === "credential.updated") {
379
+ const current = await snapshotConnections()
380
+ const remainingEmails = new Set(Array.from(current.values()).map((e) => e.toLowerCase()))
381
+ const base = await resolveBridgeOrigin(ctx, intId || undefined)
382
+ for (const [oldKey, oldEmail] of knownConns.entries()) {
383
+ if (!current.has(oldKey) && !remainingEmails.has(oldEmail.toLowerCase())) {
384
+ await fetch(`${base}/antigravity/logout`, {
385
+ method: "POST",
386
+ headers: { "content-type": "application/json" },
387
+ body: JSON.stringify({ email: oldEmail }),
388
+ signal: AbortSignal.timeout(5000),
389
+ }).catch(() => {})
390
+ }
391
+ }
392
+ knownConns.clear()
393
+ for (const [k, v] of current) knownConns.set(k, v)
394
+ await syncActiveToBridge(intId || undefined)
395
+ }
396
+ }
397
+ } catch {
398
+ // encerrado ou sem suporte a stream de eventos
399
+ }
400
+ }
401
+
402
+ void startSync()
403
+ }
404
+
405
+ return () => {
406
+ pluginAbort.abort()
407
+ }
408
+ },
409
+ }