krnell 3.0.5 → 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.
@@ -10,13 +10,314 @@
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 ANTIGRAVITY_INTEGRATION_IDS = ["antigravity"]
19
+ const WORKBUDDY_INTEGRATION_ID = "workbuddy"
20
+ const BRIDGE_PROVIDER_IDS = ["krnell", "antigravity", "workbuddy", "nyxo", "kimibridge"]
18
21
  const METHOD_ID = "antigravity-oauth"
22
+ const WORKBUDDY_METHOD_ID = "workbuddy-oauth"
19
23
  const DEFAULT_BRIDGE_ORIGIN = "http://127.0.0.1:8765"
24
+ const WORKBUDDY_API_BASE = "https://www.workbuddy.ai"
25
+ const WORKBUDDY_HEADERS: Record<string, string> = {
26
+ accept: "application/json",
27
+ "content-type": "application/json",
28
+ "x-product": "SaaS",
29
+ "user-agent": "WorkBuddy/0.0.0",
30
+ "x-no-authorization": "true",
31
+ "x-no-user-id": "true",
32
+ "x-no-enterprise-id": "true",
33
+ "x-no-department-info": "true",
34
+ }
35
+
36
+ function findKrnellCandidateDirs(): string[] {
37
+ const explicit = [process.env.KRNELL_HOME, process.env.NYXO_HOME].filter(Boolean) as string[]
38
+ if (explicit.length > 0) return explicit
39
+ const home = homedir()
40
+ const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
41
+ const dataHome = process.env.XDG_DATA_HOME || join(home, ".local", "share")
42
+ return [
43
+ process.platform === "win32" ? join(localAppData, "Krnell") : join(dataHome, "krnell"),
44
+ join(home, "bridge-package", "krnell"),
45
+ join(home, "bridge-package", "nyxo"),
46
+ ]
47
+ }
48
+
49
+ function findKrnellRootDir(): string | undefined {
50
+ for (const dir of findKrnellCandidateDirs()) {
51
+ if (existsSync(join(dir, "bridge.py")) || existsSync(join(dir, "painel.py"))) return dir
52
+ }
53
+ return undefined
54
+ }
55
+
56
+ interface BridgeAccountsInfo {
57
+ antigravity: boolean
58
+ antigravityHasPaid: boolean
59
+ antigravityModels: Set<string>
60
+ antigravityAccounts: any[]
61
+ workbuddy: boolean
62
+ workbuddyIsPro: boolean
63
+ }
64
+
65
+ async function detectBridgeAccounts(origin: string): Promise<BridgeAccountsInfo> {
66
+ const info: BridgeAccountsInfo = {
67
+ antigravity: false,
68
+ antigravityHasPaid: false,
69
+ antigravityModels: new Set<string>(),
70
+ antigravityAccounts: [],
71
+ workbuddy: false,
72
+ workbuddyIsPro: false,
73
+ }
74
+ // 1) Checa contas e plano (free vs pago) no Antigravity (sem nunca apagar nenhuma conta)
75
+ try {
76
+ const res = await fetch(`${origin}/antigravity/quota`, {
77
+ headers: { accept: "application/json" },
78
+ signal: AbortSignal.timeout(1500),
79
+ })
80
+ if (res.ok) {
81
+ const data: any = await res.json().catch(() => null)
82
+ const accts = Array.isArray(data?.accounts) ? data.accounts : []
83
+ if (accts.length > 0) {
84
+ info.antigravity = true
85
+ info.antigravityAccounts = accts
86
+ for (const a of accts) {
87
+ const paidTier = String(a?.paidTier || "").toLowerCase()
88
+ const paidName = String(a?.paidTierName || "").toLowerCase()
89
+ if (
90
+ (paidTier && !paidTier.includes("free")) ||
91
+ paidName.includes("pro") ||
92
+ paidName.includes("ultra") ||
93
+ paidName.includes("paid")
94
+ ) {
95
+ info.antigravityHasPaid = true
96
+ }
97
+ const fams = a?.quota?.families
98
+ if (fams && typeof fams === "object") {
99
+ for (const [fid, fval] of Object.entries<any>(fams)) {
100
+ if (fval?.available) info.antigravityModels.add(fid)
101
+ }
102
+ }
103
+ const rawModels = a?.quota?.models
104
+ if (rawModels && typeof rawModels === "object") {
105
+ for (const mid of Object.keys(rawModels)) {
106
+ info.antigravityModels.add(mid)
107
+ }
108
+ }
109
+ }
110
+ }
111
+ }
112
+ } catch {}
113
+
114
+ // 2) Checa contas WorkBuddy salvas no disco e se alguma tem assinatura Pro real.
115
+ // Atenção: no WorkBuddy, conta grátis recebe créditos gratuitos que rodam
116
+ // DeepSeek-V4.1-Flash, MiniMax-M3.1-Flash, Kimi-K3, GLM-5.3/5.3-Flash, Hy4 e
117
+ // Hy4-Flash-Free. Só os modelos marcados como `Pro Only` em /v3/config
118
+ // (modelTiers -> paywall: GPT-6/5.6, Grok-4.7, Gemini-3.8-Flash, GLM-5.4,
119
+ // Kimi-K3.1-Pro) exigem plano Pro pago.
120
+ for (const dir of findKrnellCandidateDirs()) {
121
+ try {
122
+ const wbPath = join(dir, "workbuddy_contas.json")
123
+ if (!existsSync(wbPath)) continue
124
+ const parsed = JSON.parse(readFileSync(wbPath, "utf8"))
125
+ const list = Array.isArray(parsed?.contas) ? parsed.contas : []
126
+ const valid = list.filter((c: any) => typeof c?.access_token === "string" && c.access_token.trim())
127
+ if (valid.length > 0) {
128
+ info.workbuddy = true
129
+ for (const c of valid) {
130
+ const plano = String(c?.plano || "").toLowerCase()
131
+ if (c?.pro === true || plano.includes("pro") || plano.includes("enterprise") || plano.includes("ultra")) {
132
+ info.workbuddyIsPro = true
133
+ }
134
+ }
135
+ break
136
+ }
137
+ } catch {}
138
+ }
139
+
140
+ // Se o bridge local estiver respondendo /_bridge/workbuddy, confirma também o flag `pro` das contas
141
+ if (info.workbuddy) {
142
+ try {
143
+ const res = await fetch(`${origin}/_bridge/workbuddy`, {
144
+ headers: { accept: "application/json" },
145
+ signal: AbortSignal.timeout(1200),
146
+ })
147
+ if (res.ok) {
148
+ const wb: any = await res.json().catch(() => null)
149
+ if (Array.isArray(wb?.contas) && wb.contas.some((c: any) => c?.pro === true)) {
150
+ info.workbuddyIsPro = true
151
+ }
152
+ }
153
+ } catch {}
154
+ }
155
+
156
+ return info
157
+ }
158
+
159
+ function saveWorkBuddyAccountToDisk(auth: any, account: any): { id: string; nome: string; email: string; label: string } {
160
+ const rootDir = findKrnellRootDir()
161
+ const email = String(account?.email || account?.mail || "").trim()
162
+ const apelido = String(account?.nickname || account?.nickName || account?.nick || account?.userName || account?.name || "").trim()
163
+ const uid = String(account?.uid || account?.userId || account?.user_id || "").trim()
164
+ const enterpriseId = String(account?.enterpriseId || account?.enterprise_id || "").trim()
165
+ const id = uid || `wb_${Date.now().toString(36)}`
166
+ const label = email || apelido || id
167
+ let nome = "workbuddy_01"
168
+ if (rootDir) {
169
+ try {
170
+ const wbPath = join(rootDir, "workbuddy_contas.json")
171
+ let contas: any[] = []
172
+ if (existsSync(wbPath)) {
173
+ const parsed = JSON.parse(readFileSync(wbPath, "utf8"))
174
+ if (Array.isArray(parsed?.contas)) contas = parsed.contas
175
+ }
176
+ const used = new Set(contas.map((c: any) => String(c?.nome || "")))
177
+ for (let i = 1; i < 100; i++) {
178
+ const cand = `workbuddy_${String(i).padStart(2, "0")}`
179
+ if (!used.has(cand)) {
180
+ nome = cand
181
+ break
182
+ }
183
+ }
184
+ if (uid) {
185
+ contas = contas.filter((c: any) => !(String(c?.uid || "") === uid && String(c?.enterprise_id || "") === enterpriseId))
186
+ }
187
+ const nowSec = Math.floor(Date.now() / 1000)
188
+ const expiresIn = Number(auth?.expiresIn || auth?.expires_in || 3600)
189
+ const rawExp = Number(auth?.expiresAt || auth?.expires_at || 0)
190
+ const expiresAt = rawExp > 1e12 ? rawExp / 1000 : rawExp > nowSec ? rawExp : nowSec + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600)
191
+ contas.push({
192
+ id: Math.random().toString(16).slice(2, 14),
193
+ nome,
194
+ uid,
195
+ apelido,
196
+ email,
197
+ enterprise_id: enterpriseId,
198
+ empresa: String(account?.enterpriseName || account?.enterprise_name || ""),
199
+ plano: String(account?.editionType || account?.edition_type || account?.plan || ""),
200
+ tipo_conta: String(account?.accountType || account?.account_type || ""),
201
+ access_token: String(auth?.accessToken || auth?.access_token || auth?.token || "").trim(),
202
+ refresh_token: String(auth?.refreshToken || auth?.refresh_token || "").trim(),
203
+ expires_at: expiresAt,
204
+ domain: String(auth?.domain || ""),
205
+ adicionada_em: nowSec,
206
+ ultimo_uso: null,
207
+ precisa_login: false,
208
+ })
209
+ writeFileSync(wbPath, JSON.stringify({ versao: 1, contas }, null, 2), { mode: 0o600 })
210
+ } catch {}
211
+ }
212
+ return { id, nome, email, label }
213
+ }
214
+
215
+ let ensureBridgePromise: Promise<boolean> | null = null
216
+ let lastEnsureAttemptAt = 0
217
+
218
+ function isLocalBridgeOrigin(origin: string): boolean {
219
+ try {
220
+ const u = new URL(origin)
221
+ return u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "::1"
222
+ } catch {
223
+ return false
224
+ }
225
+ }
226
+
227
+ function findNodeBinary(): string {
228
+ const candidates =
229
+ process.platform === "win32"
230
+ ? ["node.exe", "node"]
231
+ : [
232
+ "/usr/local/bin/node",
233
+ "/usr/bin/node",
234
+ process.env.PREFIX ? join(process.env.PREFIX, "bin", "node") : "",
235
+ "node",
236
+ ].filter(Boolean)
237
+ for (const c of candidates) {
238
+ if (c === "node" || c === "node.exe" || existsSync(c)) return c
239
+ }
240
+ return "node"
241
+ }
242
+
243
+ function findKrnellCommand(): { cmd: string; args: string[]; cwd?: string } | null {
244
+ const home = homedir()
245
+ const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
246
+ const dataHome = process.env.XDG_DATA_HOME || join(home, ".local", "share")
247
+ const dirs = [
248
+ process.env.KRNELL_HOME,
249
+ process.env.NYXO_HOME,
250
+ process.platform === "win32" ? join(localAppData, "Krnell") : join(dataHome, "krnell"),
251
+ join(home, "bridge-package", "krnell"),
252
+ join(home, "bridge-package", "nyxo"),
253
+ ].filter(Boolean) as string[]
254
+
255
+ for (const dir of dirs) {
256
+ const bridgePy = join(dir, "bridge.py")
257
+ if (existsSync(bridgePy)) {
258
+ const py = process.platform === "win32" ? "python" : "python3"
259
+ return { cmd: py, args: ["-B", bridgePy, "--config", join(dir, "config.json")], cwd: dir }
260
+ }
261
+ const mjs = join(dir, "bin", "krnell.mjs")
262
+ if (existsSync(mjs)) {
263
+ return { cmd: findNodeBinary(), args: [mjs, "--headless"], cwd: dir }
264
+ }
265
+ }
266
+ return { cmd: process.platform === "win32" ? "krnell.cmd" : "krnell", args: ["--headless"] }
267
+ }
268
+
269
+ async function isBridgeAlive(origin: string, timeoutMs = 900): Promise<boolean> {
270
+ try {
271
+ const r = await fetch(`${origin}/healthz`, { signal: AbortSignal.timeout(timeoutMs) })
272
+ if (r.ok) return true
273
+ } catch {}
274
+ try {
275
+ const r = await fetch(`${origin}/_bridge/status`, { signal: AbortSignal.timeout(timeoutMs) })
276
+ return r.status < 500
277
+ } catch {
278
+ return false
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Inicialização inteligente sob demanda:
284
+ * só sobe o Krnell em background se o alvo for loopback local, o bridge estiver
285
+ * offline e houver uso real (chamada com modelo Krnell/KimiBridge ou /connect).
286
+ */
287
+ async function ensureKrnellRunning(origin: string, reason: string): Promise<boolean> {
288
+ if (!isLocalBridgeOrigin(origin)) return false
289
+ if (await isBridgeAlive(origin, 700)) return true
290
+ if (ensureBridgePromise) return ensureBridgePromise
291
+ const now = Date.now()
292
+ if (now - lastEnsureAttemptAt < 10_000) return false
293
+ lastEnsureAttemptAt = now
294
+
295
+ ensureBridgePromise = (async () => {
296
+ const launch = findKrnellCommand()
297
+ if (!launch) return false
298
+ try {
299
+ const child = spawn(launch.cmd, launch.args, {
300
+ cwd: launch.cwd,
301
+ detached: true,
302
+ stdio: "ignore",
303
+ windowsHide: true,
304
+ env: { ...process.env, KRNELL_STARTED_BY: `opencode-plugin:${reason}` },
305
+ })
306
+ child.unref()
307
+ } catch {
308
+ return false
309
+ }
310
+ const deadline = Date.now() + 12_000
311
+ while (Date.now() < deadline) {
312
+ if (await isBridgeAlive(origin, 600)) return true
313
+ await new Promise((r) => setTimeout(r, 350))
314
+ }
315
+ return false
316
+ })().finally(() => {
317
+ ensureBridgePromise = null
318
+ })
319
+ return ensureBridgePromise
320
+ }
20
321
 
21
322
  let cachedFile = ""
22
323
  let cachedMtimeMs = -1
@@ -66,6 +367,10 @@ function normalizeBridgeOrigin(baseURL?: string): string {
66
367
  }
67
368
 
68
369
  async function resolveBridgeOrigin(ctx: any, preferredId?: string): Promise<string> {
370
+ if (process.env.KRNELL_BRIDGE_URL) {
371
+ const envOrigin = normalizeBridgeOrigin(process.env.KRNELL_BRIDGE_URL)
372
+ if (envOrigin) return envOrigin
373
+ }
69
374
  if (process.env.NYXO_BRIDGE_URL) {
70
375
  const envOrigin = normalizeBridgeOrigin(process.env.NYXO_BRIDGE_URL)
71
376
  if (envOrigin) return envOrigin
@@ -74,7 +379,7 @@ async function resolveBridgeOrigin(ctx: any, preferredId?: string): Promise<stri
74
379
  const envOrigin = normalizeBridgeOrigin(process.env.KIMI_BRIDGE_URL)
75
380
  if (envOrigin) return envOrigin
76
381
  }
77
- const order = preferredId ? [preferredId, ...INTEGRATION_IDS.filter((x) => x !== preferredId)] : INTEGRATION_IDS
382
+ const order = preferredId ? [preferredId, ...BRIDGE_PROVIDER_IDS.filter((x) => x !== preferredId)] : BRIDGE_PROVIDER_IDS
78
383
  for (const id of order) {
79
384
  try {
80
385
  if (ctx?.provider?.get) {
@@ -123,7 +428,15 @@ export default {
123
428
  // -----------------------------------------------------------------
124
429
  // 1. Substituição do system prompt via AGENTS.md
125
430
  // -----------------------------------------------------------------
126
- const makeApply = (hook: string) => (event: any) => {
431
+ const makeApply = (hook: string) => async (event: any) => {
432
+ // Momento inteligente 1: se a chamada atual vai usar krnell/kimibridge/nyxo
433
+ // e o bridge local ainda não está no ar, sobe em background automaticamente.
434
+ const provID = String(event?.model?.providerID || event?.providerID || "").toLowerCase()
435
+ if (BRIDGE_PROVIDER_IDS.includes(provID)) {
436
+ const origin = await resolveBridgeOrigin(ctx, provID)
437
+ await ensureKrnellRunning(origin, `hook:${hook}`)
438
+ }
439
+
127
440
  const text = loadPrompt()
128
441
  if (!text) return
129
442
 
@@ -169,14 +482,207 @@ export default {
169
482
  // -----------------------------------------------------------------
170
483
  const pluginAbort = new AbortController()
171
484
 
485
+ // Detecta contas que JÁ existem no bridge/disco (nunca remove nem apaga
486
+ // contas existentes). Se já houver conta no bridge OU credencial no /connect
487
+ // do OpenCode, o provedor aparece em /model; se não houver nenhuma conta,
488
+ // removemos os modelos dele do /model até a pessoa conectar no /connect.
489
+ const bridgeOrigin = await resolveBridgeOrigin(ctx, "krnell")
490
+ let existingBridgeAccounts = await detectBridgeAccounts(bridgeOrigin)
491
+
492
+ const hasIntegrationCreds = async (integrationID: string): Promise<boolean> => {
493
+ try {
494
+ if (!ctx?.integration?.get) return false
495
+ const info = await ctx.integration.get({ integrationID })
496
+ const conns = Array.isArray(info?.connections) ? info.connections : []
497
+ return conns.length > 0
498
+ } catch {
499
+ return false
500
+ }
501
+ }
502
+
503
+ // Só ativa provedores com auth se houver conta real no bridge OU credencial no OpenCode.
504
+ // Atenção: antes do ctx.integration.transform rodar, `ctx.integration.get` ainda não conhece
505
+ // os métodos customizados, então fazemos a checagem das credenciais DEPOIS de registrar o transform.
506
+ let connectedState = {
507
+ antigravity: existingBridgeAccounts.antigravity,
508
+ workbuddy: existingBridgeAccounts.workbuddy,
509
+ tokenharbor: false,
510
+ }
511
+
512
+ const refreshConnectedState = async () => {
513
+ existingBridgeAccounts = await detectBridgeAccounts(bridgeOrigin)
514
+ const [agCred, wbCred, thCred] = await Promise.all([
515
+ hasIntegrationCreds("antigravity"),
516
+ hasIntegrationCreds("workbuddy"),
517
+ hasIntegrationCreds("tokenharbor"),
518
+ ])
519
+ connectedState = {
520
+ antigravity: existingBridgeAccounts.antigravity || agCred,
521
+ workbuddy: existingBridgeAccounts.workbuddy || wbCred,
522
+ tokenharbor: thCred,
523
+ }
524
+ if (ctx?.provider?.reload) {
525
+ await ctx.provider.reload().catch(() => {})
526
+ }
527
+ if (ctx?.model?.reload) {
528
+ await ctx.model.reload().catch(() => {})
529
+ }
530
+ }
531
+
532
+ if (ctx?.provider?.transform) {
533
+ await ctx.provider.transform((editor: any) => {
534
+ const ref = editor.get?.("openai") || editor.list?.()[0]
535
+ const baseProv = ref?.provider || {}
536
+ const baseModel = ref?.models ? Array.from(ref.models.values())[0] : {}
537
+ const mkModel = (
538
+ providerID: string,
539
+ id: string,
540
+ name: string,
541
+ ctxLimit: number,
542
+ outLimit: number,
543
+ input: string[],
544
+ efforts: string[],
545
+ defaultEffort: string,
546
+ ) => ({
547
+ ...baseModel,
548
+ id,
549
+ modelID: id,
550
+ providerID,
551
+ type: baseModel?.type || "chat",
552
+ name,
553
+ status: "active",
554
+ enabled: true,
555
+ cost: [],
556
+ capabilities: {
557
+ tools: true,
558
+ reasoning: { supported: true, effort: efforts },
559
+ input,
560
+ output: ["text"],
561
+ },
562
+ limit: { context: ctxLimit, output: outLimit },
563
+ compatibility: {
564
+ reasoningField: "reasoning_content",
565
+ maxTokensField: "max_tokens",
566
+ },
567
+ body: { reasoning_effort: defaultEffort },
568
+ variants: efforts.map((e) => ({ id: e, body: { reasoning_effort: e } })),
569
+ })
570
+
571
+ // 1) "antigravity" (Antigravity Google):
572
+ // - aparece sempre no /connect
573
+ // - só entra no /model quando já houver conta no bridge OU credencial no /connect
574
+ // - conta Free-only mostra apenas os modelos realmente liberados pelo plano Starter/Free;
575
+ // conta Pro/Paid libera Claude Opus/Sonnet 5.5 e Gemini 4 Hydrogen/Neon.
576
+ const agConnected = connectedState.antigravity
577
+ const agPaid = existingBridgeAccounts.antigravityHasPaid
578
+ const agInfo = {
579
+ ...baseProv,
580
+ id: "antigravity",
581
+ name: "Antigravity Google",
582
+ activation: agConnected ? "enabled" : "auto",
583
+ integrationID: "antigravity",
584
+ package: "@opencode/ai/providers/openai-compatible",
585
+ settings: agConnected ? { baseURL: `${bridgeOrigin}/v1`, apiKey: "local" } : { baseURL: `${bridgeOrigin}/v1` },
586
+ }
587
+ const agPaidModels = [
588
+ mkModel("antigravity", "claude-opus-5-5", "Claude Opus 5.5", 1000000, 128000, ["text", "image"], ["low", "medium", "high"], "high"),
589
+ mkModel("antigravity", "claude-sonnet-5-5", "Claude Sonnet 5.5", 1000000, 128000, ["text", "image"], ["low", "medium", "high"], "high"),
590
+ mkModel("antigravity", "gemini-4-hydrogen", "Gemini 4 Hydrogen", 1000000, 262144, ["text", "image", "audio", "video", "pdf"], ["low", "medium", "high", "xhigh"], "xhigh"),
591
+ mkModel("antigravity", "gemini-4-neon", "Gemini 4 Neon", 1000000, 262144, ["text", "image", "audio", "video", "pdf"], ["low", "medium", "high", "xhigh"], "xhigh"),
592
+ ]
593
+ const agFreeModels = [
594
+ mkModel("antigravity", "claude-sonnet-4-6", "Claude Sonnet 4.6", 200000, 64000, ["text", "image"], ["low", "medium", "high"], "high"),
595
+ mkModel("antigravity", "claude-opus-4-6-thinking", "Claude Opus 4.6", 200000, 64000, ["text", "image"], ["low", "medium", "high"], "high"),
596
+ mkModel("antigravity", "gemini-3.8-flash-high", "Gemini 3.8 Flash", 1000000, 65536, ["text", "image", "audio", "video", "pdf"], ["low", "medium", "high"], "high"),
597
+ mkModel("antigravity", "gemini-2.5-pro", "Gemini 2.5 Pro", 1000000, 65536, ["text", "image", "audio", "video", "pdf"], ["low", "medium", "high"], "high"),
598
+ ]
599
+ // Se nenhuma conta é paga e já consultamos o bridge, mostra somente os modelos liberados no plano Free.
600
+ const agModels = (!agConnected || agPaid || existingBridgeAccounts.antigravityAccounts.length === 0)
601
+ ? agPaidModels
602
+ : agFreeModels
603
+ if (!editor.get?.("antigravity")) {
604
+ editor.add({ info: agInfo, models: agModels })
605
+ } else {
606
+ editor.update("antigravity", (p: any) => Object.assign(p, agInfo))
607
+ editor.models?.set?.("antigravity", agModels)
608
+ }
609
+
610
+ // 2) "workbuddy" (WorkBuddy):
611
+ // - aparece sempre no /connect
612
+ // - só entra no /model quando já houver conta salva em workbuddy_contas.json OU /connect
613
+ // - conta Free (sem Pro) libera todos os modelos NÃO-paywall (que gastam a
614
+ // cota gratuita sem precisar de Pro: DeepSeek-V4.1-Flash, MiniMax-M3.1-Flash,
615
+ // Kimi-K3, GLM-5.3, GLM-5.3-Flash, Hy4, Hy4-Flash e Hy4-Flash-Free).
616
+ // - conta Pro libera também os modelos `Pro Only` do paywall (Grok-4.7,
617
+ // Gemini-3.8-Flash, GLM-5.4, Kimi-K3.1-Pro, GPT-6.2/6.1/6/5.6).
618
+ const wbConnected = connectedState.workbuddy
619
+ const wbPro = existingBridgeAccounts.workbuddyIsPro
620
+ const wbInfo = {
621
+ ...baseProv,
622
+ id: "workbuddy",
623
+ name: "WorkBuddy",
624
+ activation: wbConnected ? "enabled" : "auto",
625
+ integrationID: "workbuddy",
626
+ package: "@opencode/ai/providers/openai-compatible",
627
+ settings: wbConnected ? { baseURL: `${bridgeOrigin}/v1`, apiKey: "local" } : { baseURL: `${bridgeOrigin}/v1` },
628
+ }
629
+ const wbStandardModels = [
630
+ mkModel("workbuddy", "deepseek-v4.1-flash-sg", "DeepSeek V4.1 Flash", 1000000, 128000, ["text", "image"], ["low", "medium", "high", "max"], "max"),
631
+ mkModel("workbuddy", "minimax-m3.1-flash", "MiniMax M3.1 Flash", 1000000, 128000, ["text", "image"], ["low", "medium", "high", "max"], "max"),
632
+ mkModel("workbuddy", "kimi-k3", "Kimi K3", 1000000, 32000, ["text", "image"], ["low", "medium", "high"], "high"),
633
+ mkModel("workbuddy", "glm-5.3-flash", "GLM 5.3 Flash", 1000000, 32000, ["text", "image"], ["low", "medium", "high"], "high"),
634
+ mkModel("workbuddy", "glm-5.3", "GLM 5.3", 1000000, 32000, ["text", "image"], ["low", "medium", "high"], "high"),
635
+ mkModel("workbuddy", "hy4std", "Hy4", 256000, 64000, ["text", "image"], ["low", "medium", "high"], "high"),
636
+ mkModel("workbuddy", "hy4flash", "Hy4 Flash", 192000, 64000, ["text", "image"], ["low", "medium", "high"], "high"),
637
+ mkModel("workbuddy", "hy4flash-free", "Hy4 Flash Free", 192000, 64000, ["text", "image"], ["low", "medium", "high"], "high"),
638
+ ]
639
+ const wbProOnlyModels = [
640
+ mkModel("workbuddy", "kimi-k3.1-pro", "Kimi K3.1 Pro", 1000000, 65536, ["text", "image"], ["low", "medium", "high", "max"], "max"),
641
+ mkModel("workbuddy", "glm-5.4", "GLM 5.4", 1000000, 32000, ["text", "image"], ["low", "medium", "high"], "high"),
642
+ mkModel("workbuddy", "grok-4.7", "Grok 4.7", 500000, 128000, ["text", "image"], ["low", "medium", "high"], "high"),
643
+ mkModel("workbuddy", "gemini-3.8-flash", "Gemini 3.8 Flash", 1000000, 65536, ["text", "image"], ["low", "medium", "high"], "high"),
644
+ mkModel("workbuddy", "gpt-6.2-sol", "GPT-6.2 Sol", 400000, 128000, ["text", "image"], ["low", "medium", "high"], "high"),
645
+ mkModel("workbuddy", "gpt-6.1-terra", "GPT-6.1 Terra", 400000, 128000, ["text", "image"], ["low", "medium", "high"], "high"),
646
+ ]
647
+ const wbModels = wbPro ? [...wbStandardModels, ...wbProOnlyModels] : wbStandardModels
648
+ if (!editor.get?.("workbuddy")) {
649
+ editor.add({ info: wbInfo, models: wbModels })
650
+ } else {
651
+ editor.update("workbuddy", (p: any) => Object.assign(p, wbInfo))
652
+ editor.models?.set?.("workbuddy", wbModels)
653
+ }
654
+
655
+ // 3) "tokenharbor" (TokenHarbor):
656
+ // - aparece sempre no /connect (método API key)
657
+ // - só entra no /model quando a pessoa conectar uma API key no /connect
658
+ const thInfo = {
659
+ ...baseProv,
660
+ id: "tokenharbor",
661
+ name: "TokenHarbor",
662
+ activation: "auto",
663
+ integrationID: "tokenharbor",
664
+ package: "@opencode/ai/providers/openai-compatible",
665
+ settings: { baseURL: "https://api.tokenharbor.ai/v1" },
666
+ }
667
+ const thModels = [
668
+ mkModel("tokenharbor", "deepseek-v4.1-flash:free", "DeepSeek V4.1 Flash Free", 200000, 32768, ["text"], ["low", "medium", "high", "max"], "max"),
669
+ ]
670
+ if (!editor.get?.("tokenharbor")) {
671
+ editor.add({ info: thInfo, models: thModels })
672
+ } else {
673
+ editor.update("tokenharbor", (p: any) => Object.assign(p, thInfo))
674
+ editor.models?.set?.("tokenharbor", thModels)
675
+ }
676
+ })
677
+ }
678
+
172
679
  if (ctx?.integration?.transform) {
173
680
  await ctx.integration.transform((reg: any) => {
174
- for (const integrationID of INTEGRATION_IDS) {
175
- const pretty = integrationID === "nyxo" ? "Nyxo Bridge (local)" : "Kimi Bridge (local)"
681
+ for (const integrationID of ANTIGRAVITY_INTEGRATION_IDS) {
176
682
  reg.update(integrationID, (ref: any) => {
177
- if (!ref.name || ref.name === integrationID) ref.name = pretty
683
+ ref.name = "Antigravity Google"
178
684
  })
179
- reg.method.remove(integrationID, { type: "key" })
685
+ // Acrescenta o OAuth sem remover nenhum método/integração nativa.
180
686
  reg.method.update({
181
687
  integrationID,
182
688
  method: {
@@ -191,6 +697,7 @@ export default {
191
697
  },
192
698
  authorize: async () => {
193
699
  const base = await resolveBridgeOrigin(ctx, integrationID)
700
+ await ensureKrnellRunning(base, "connect-oauth")
194
701
  let started: any
195
702
  try {
196
703
  const res = await fetch(`${base}/antigravity/login/start`, {
@@ -202,7 +709,7 @@ export default {
202
709
  started = await res.json()
203
710
  } catch (err: any) {
204
711
  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.`,
712
+ `Não foi possível falar com a bridge em ${base} (${err?.message || err}). Inicie o krnell (krnell --headless) e tente /connect novamente.`,
206
713
  )
207
714
  }
208
715
 
@@ -220,6 +727,7 @@ export default {
220
727
  resolveAuth = (cred) => {
221
728
  if (finished) return
222
729
  finished = true
730
+ existingBridgeAccounts.antigravity = true
223
731
  resolve(cred)
224
732
  }
225
733
  rejectAuth = (err) => {
@@ -301,6 +809,196 @@ export default {
301
809
  },
302
810
  })
303
811
  }
812
+
813
+ // WorkBuddy: tenta via bridge local e, se o bridge antigo ainda não tiver a rota
814
+ // /workbuddy/login/start (HTTP 404), fala direto com a API oficial do WorkBuddy
815
+ // e salva a conta em workbuddy_contas.json preservando todas as existentes.
816
+ reg.update(WORKBUDDY_INTEGRATION_ID, (ref: any) => {
817
+ ref.name = "WorkBuddy"
818
+ })
819
+ reg.method.update({
820
+ integrationID: WORKBUDDY_INTEGRATION_ID,
821
+ method: {
822
+ id: WORKBUDDY_METHOD_ID,
823
+ type: "oauth",
824
+ label: "Login WorkBuddy (navegador — multi-conta + cota)",
825
+ },
826
+ label: (cred: any) => {
827
+ const label = cred?.metadata?.label || cred?.metadata?.email || cred?.metadata?.nome
828
+ if (typeof label === "string" && label.trim()) return label.trim()
829
+ return "WorkBuddy"
830
+ },
831
+ authorize: async () => {
832
+ const base = await resolveBridgeOrigin(ctx, WORKBUDDY_INTEGRATION_ID)
833
+ let state = ""
834
+ let url = ""
835
+ let viaDirectApi = false
836
+
837
+ // 1) Tenta pelo bridge local se disponível
838
+ try {
839
+ const res = await fetch(`${base}/workbuddy/login/start`, {
840
+ method: "POST",
841
+ headers: { accept: "application/json" },
842
+ signal: AbortSignal.timeout(5000),
843
+ })
844
+ if (res.ok) {
845
+ const started: any = await res.json().catch(() => null)
846
+ state = String(started?.state || "")
847
+ url = String(started?.url || "")
848
+ }
849
+ } catch {}
850
+
851
+ // 2) Fallback direto para a API oficial do WorkBuddy (funciona mesmo sem reiniciar o bridge)
852
+ if (!state || !url) {
853
+ viaDirectApi = true
854
+ let directResp: any
855
+ try {
856
+ const res = await fetch(`${WORKBUDDY_API_BASE}/v2/plugin/auth/state?platform=workbuddy-ai`, {
857
+ method: "POST",
858
+ headers: WORKBUDDY_HEADERS,
859
+ body: "{}",
860
+ signal: AbortSignal.timeout(12000),
861
+ })
862
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
863
+ directResp = await res.json()
864
+ } catch (err: any) {
865
+ throw new Error(`Não foi possível gerar o link de login do WorkBuddy (${err?.message || err}).`)
866
+ }
867
+ const data = directResp?.data || {}
868
+ state = String(data.state || "").trim()
869
+ url = String(data.authUrl || data.auth_url || "").trim()
870
+ if (state && !url) {
871
+ url = `${WORKBUDDY_API_BASE}/login?platform=workbuddy-ai&state=${encodeURIComponent(state)}`
872
+ }
873
+ }
874
+
875
+ if (!state || !url) {
876
+ throw new Error("WorkBuddy não retornou a URL de login.")
877
+ }
878
+
879
+ let finished = false
880
+ const callback = new Promise<any>((resolve, reject) => {
881
+ const deadline = Date.now() + 10 * 60 * 1000
882
+ const poll = async () => {
883
+ while (!finished && !pluginAbort.signal.aborted) {
884
+ if (Date.now() > deadline) {
885
+ finished = true
886
+ reject(new Error("Tempo esgotado aguardando login no WorkBuddy."))
887
+ return
888
+ }
889
+ try {
890
+ if (!viaDirectApi) {
891
+ const r = await fetch(
892
+ `${base}/workbuddy/login/status?state=${encodeURIComponent(state)}`,
893
+ { signal: AbortSignal.timeout(8000) },
894
+ )
895
+ if (r.ok) {
896
+ const st: any = await r.json()
897
+ if (st.status === "complete" && st.account) {
898
+ finished = true
899
+ existingBridgeAccounts.workbuddy = true
900
+ const acc = st.account
901
+ const label = String(acc.email || acc.apelido || acc.nome || acc.id || "WorkBuddy").trim()
902
+ const id = String(acc.id || acc.nome || label).trim()
903
+ resolve({
904
+ type: "oauth" as const,
905
+ methodID: WORKBUDDY_METHOD_ID,
906
+ access: `wb:${id}`,
907
+ refresh: `wb:${id}`,
908
+ expires: Date.now() + 365 * 24 * 60 * 60 * 1000,
909
+ metadata: { id, nome: String(acc.nome || ""), email: String(acc.email || ""), label },
910
+ })
911
+ return
912
+ }
913
+ if (st.status === "failed") {
914
+ finished = true
915
+ reject(new Error(st.error || "Login no WorkBuddy falhou."))
916
+ return
917
+ }
918
+ if (st.status === "expired") {
919
+ finished = true
920
+ reject(new Error("Link do WorkBuddy expirou. Tente /connect novamente."))
921
+ return
922
+ }
923
+ }
924
+ } else {
925
+ const r = await fetch(
926
+ `${WORKBUDDY_API_BASE}/v2/plugin/auth/token?state=${encodeURIComponent(state)}`,
927
+ { headers: WORKBUDDY_HEADERS, signal: AbortSignal.timeout(10000) },
928
+ )
929
+ if (r.ok) {
930
+ const payload: any = await r.json().catch(() => null)
931
+ const data = payload?.data
932
+ const token = data?.accessToken || data?.access_token || data?.token
933
+ if ((payload?.code === 0 || payload?.code == null) && typeof token === "string" && token.trim()) {
934
+ let accountInfo: any = {}
935
+ try {
936
+ const accRes = await fetch(
937
+ `${WORKBUDDY_API_BASE}/v2/plugin/login/account?state=${encodeURIComponent(state)}`,
938
+ {
939
+ headers: {
940
+ ...WORKBUDDY_HEADERS,
941
+ authorization: `Bearer ${token.trim()}`,
942
+ ...(data?.domain ? { "x-domain": String(data.domain) } : {}),
943
+ },
944
+ signal: AbortSignal.timeout(10000),
945
+ },
946
+ )
947
+ if (accRes.ok) {
948
+ const accJson: any = await accRes.json().catch(() => null)
949
+ if (accJson?.data && typeof accJson.data === "object") accountInfo = accJson.data
950
+ }
951
+ } catch {}
952
+ const saved = saveWorkBuddyAccountToDisk(data, accountInfo)
953
+ finished = true
954
+ existingBridgeAccounts.workbuddy = true
955
+ resolve({
956
+ type: "oauth" as const,
957
+ methodID: WORKBUDDY_METHOD_ID,
958
+ access: `wb:${saved.id}`,
959
+ refresh: `wb:${saved.id}`,
960
+ expires: Date.now() + 365 * 24 * 60 * 60 * 1000,
961
+ metadata: saved,
962
+ })
963
+ return
964
+ }
965
+ }
966
+ }
967
+ } catch {
968
+ // ignora erro pontual de polling
969
+ }
970
+ await new Promise((r) => setTimeout(r, 1500))
971
+ }
972
+ }
973
+ void poll()
974
+ })
975
+
976
+ return {
977
+ mode: "auto" as const,
978
+ url,
979
+ instructions: "Abra o link no navegador e entre na sua conta WorkBuddy. O OpenCode detecta automaticamente.",
980
+ callback,
981
+ }
982
+ },
983
+ refresh: async (cred: any) => ({
984
+ ...cred,
985
+ type: "oauth" as const,
986
+ methodID: WORKBUDDY_METHOD_ID,
987
+ expires: Date.now() + 365 * 24 * 60 * 60 * 1000,
988
+ }),
989
+ })
990
+
991
+ // TokenHarbor (API key — provedor que não vem no catálogo nativo do OpenCode)
992
+ reg.update("tokenharbor", (ref: any) => {
993
+ ref.name = "TokenHarbor"
994
+ })
995
+ reg.method.update({
996
+ integrationID: "tokenharbor",
997
+ method: {
998
+ type: "key",
999
+ label: "API key (TokenHarbor)",
1000
+ },
1001
+ })
304
1002
  })
305
1003
  }
306
1004
 
@@ -312,7 +1010,7 @@ export default {
312
1010
 
313
1011
  const snapshotConnections = async () => {
314
1012
  const next = new Map<string, string>()
315
- for (const integrationID of INTEGRATION_IDS) {
1013
+ for (const integrationID of ANTIGRAVITY_INTEGRATION_IDS) {
316
1014
  try {
317
1015
  const info = await ctx.integration.get({ integrationID })
318
1016
  const conns = Array.isArray(info?.connections) ? info.connections : []
@@ -333,7 +1031,7 @@ export default {
333
1031
  }
334
1032
 
335
1033
  const syncActiveToBridge = async (targetId?: string) => {
336
- const ids = targetId ? [targetId] : INTEGRATION_IDS
1034
+ const ids = targetId ? [targetId] : ANTIGRAVITY_INTEGRATION_IDS
337
1035
  for (const integrationID of ids) {
338
1036
  try {
339
1037
  if (!ctx.integration.connection?.active) continue
@@ -356,6 +1054,7 @@ export default {
356
1054
  }
357
1055
 
358
1056
  const startSync = async () => {
1057
+ await refreshConnectedState()
359
1058
  const init = await snapshotConnections()
360
1059
  for (const [k, v] of init) knownConns.set(k, v)
361
1060
 
@@ -368,7 +1067,10 @@ export default {
368
1067
  if (pluginAbort.signal.aborted) break
369
1068
  const data = ev?.data || ev?.properties || {}
370
1069
  const intId = String(data.integrationID || "")
371
- if (intId && !INTEGRATION_IDS.includes(intId)) continue
1070
+ if (intId && ["antigravity", "workbuddy", "tokenharbor"].includes(intId)) {
1071
+ await refreshConnectedState()
1072
+ }
1073
+ if (intId && !ANTIGRAVITY_INTEGRATION_IDS.includes(intId)) continue
372
1074
 
373
1075
  if (ev?.type === "credential.switched") {
374
1076
  await syncActiveToBridge(intId || undefined)