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.
@@ -15,9 +15,202 @@ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"
15
15
  import { homedir } from "node:os"
16
16
  import { join } from "node:path"
17
17
 
18
- const INTEGRATION_IDS = ["krnell", "nyxo", "kimibridge"]
18
+ const ANTIGRAVITY_INTEGRATION_IDS = ["antigravity"]
19
+ const WORKBUDDY_INTEGRATION_ID = "workbuddy"
20
+ const BRIDGE_PROVIDER_IDS = ["krnell", "antigravity", "workbuddy", "nyxo", "kimibridge"]
19
21
  const METHOD_ID = "antigravity-oauth"
22
+ const WORKBUDDY_METHOD_ID = "workbuddy-oauth"
20
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
+ }
21
214
 
22
215
  let ensureBridgePromise: Promise<boolean> | null = null
23
216
  let lastEnsureAttemptAt = 0
@@ -31,6 +224,22 @@ function isLocalBridgeOrigin(origin: string): boolean {
31
224
  }
32
225
  }
33
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
+
34
243
  function findKrnellCommand(): { cmd: string; args: string[]; cwd?: string } | null {
35
244
  const home = homedir()
36
245
  const localAppData = process.env.LOCALAPPDATA || join(home, "AppData", "Local")
@@ -39,19 +248,20 @@ function findKrnellCommand(): { cmd: string; args: string[]; cwd?: string } | nu
39
248
  process.env.KRNELL_HOME,
40
249
  process.env.NYXO_HOME,
41
250
  process.platform === "win32" ? join(localAppData, "Krnell") : join(dataHome, "krnell"),
251
+ join(home, "bridge-package", "krnell"),
42
252
  join(home, "bridge-package", "nyxo"),
43
253
  ].filter(Boolean) as string[]
44
254
 
45
255
  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
256
  const bridgePy = join(dir, "bridge.py")
51
257
  if (existsSync(bridgePy)) {
52
258
  const py = process.platform === "win32" ? "python" : "python3"
53
259
  return { cmd: py, args: ["-B", bridgePy, "--config", join(dir, "config.json")], cwd: dir }
54
260
  }
261
+ const mjs = join(dir, "bin", "krnell.mjs")
262
+ if (existsSync(mjs)) {
263
+ return { cmd: findNodeBinary(), args: [mjs, "--headless"], cwd: dir }
264
+ }
55
265
  }
56
266
  return { cmd: process.platform === "win32" ? "krnell.cmd" : "krnell", args: ["--headless"] }
57
267
  }
@@ -157,6 +367,10 @@ function normalizeBridgeOrigin(baseURL?: string): string {
157
367
  }
158
368
 
159
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
+ }
160
374
  if (process.env.NYXO_BRIDGE_URL) {
161
375
  const envOrigin = normalizeBridgeOrigin(process.env.NYXO_BRIDGE_URL)
162
376
  if (envOrigin) return envOrigin
@@ -165,7 +379,7 @@ async function resolveBridgeOrigin(ctx: any, preferredId?: string): Promise<stri
165
379
  const envOrigin = normalizeBridgeOrigin(process.env.KIMI_BRIDGE_URL)
166
380
  if (envOrigin) return envOrigin
167
381
  }
168
- 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
169
383
  for (const id of order) {
170
384
  try {
171
385
  if (ctx?.provider?.get) {
@@ -218,7 +432,7 @@ export default {
218
432
  // Momento inteligente 1: se a chamada atual vai usar krnell/kimibridge/nyxo
219
433
  // e o bridge local ainda não está no ar, sobe em background automaticamente.
220
434
  const provID = String(event?.model?.providerID || event?.providerID || "").toLowerCase()
221
- if (INTEGRATION_IDS.includes(provID)) {
435
+ if (BRIDGE_PROVIDER_IDS.includes(provID)) {
222
436
  const origin = await resolveBridgeOrigin(ctx, provID)
223
437
  await ensureKrnellRunning(origin, `hook:${hook}`)
224
438
  }
@@ -268,14 +482,207 @@ export default {
268
482
  // -----------------------------------------------------------------
269
483
  const pluginAbort = new AbortController()
270
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
+
271
679
  if (ctx?.integration?.transform) {
272
680
  await ctx.integration.transform((reg: any) => {
273
- for (const integrationID of INTEGRATION_IDS) {
274
- const pretty = integrationID === "krnell" ? "Krnell (local)" : integrationID === "nyxo" ? "Nyxo Bridge (local)" : "Kimi Bridge (local)"
681
+ for (const integrationID of ANTIGRAVITY_INTEGRATION_IDS) {
275
682
  reg.update(integrationID, (ref: any) => {
276
- if (!ref.name || ref.name === integrationID) ref.name = pretty
683
+ ref.name = "Antigravity Google"
277
684
  })
278
- reg.method.remove(integrationID, { type: "key" })
685
+ // Acrescenta o OAuth sem remover nenhum método/integração nativa.
279
686
  reg.method.update({
280
687
  integrationID,
281
688
  method: {
@@ -290,7 +697,6 @@ export default {
290
697
  },
291
698
  authorize: async () => {
292
699
  const base = await resolveBridgeOrigin(ctx, integrationID)
293
- // Momento inteligente 2: ao abrir /connect para Antigravity, garante o Krnell no ar.
294
700
  await ensureKrnellRunning(base, "connect-oauth")
295
701
  let started: any
296
702
  try {
@@ -303,7 +709,7 @@ export default {
303
709
  started = await res.json()
304
710
  } catch (err: any) {
305
711
  throw new Error(
306
- `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.`,
307
713
  )
308
714
  }
309
715
 
@@ -321,6 +727,7 @@ export default {
321
727
  resolveAuth = (cred) => {
322
728
  if (finished) return
323
729
  finished = true
730
+ existingBridgeAccounts.antigravity = true
324
731
  resolve(cred)
325
732
  }
326
733
  rejectAuth = (err) => {
@@ -402,6 +809,196 @@ export default {
402
809
  },
403
810
  })
404
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
+ })
405
1002
  })
406
1003
  }
407
1004
 
@@ -413,7 +1010,7 @@ export default {
413
1010
 
414
1011
  const snapshotConnections = async () => {
415
1012
  const next = new Map<string, string>()
416
- for (const integrationID of INTEGRATION_IDS) {
1013
+ for (const integrationID of ANTIGRAVITY_INTEGRATION_IDS) {
417
1014
  try {
418
1015
  const info = await ctx.integration.get({ integrationID })
419
1016
  const conns = Array.isArray(info?.connections) ? info.connections : []
@@ -434,7 +1031,7 @@ export default {
434
1031
  }
435
1032
 
436
1033
  const syncActiveToBridge = async (targetId?: string) => {
437
- const ids = targetId ? [targetId] : INTEGRATION_IDS
1034
+ const ids = targetId ? [targetId] : ANTIGRAVITY_INTEGRATION_IDS
438
1035
  for (const integrationID of ids) {
439
1036
  try {
440
1037
  if (!ctx.integration.connection?.active) continue
@@ -457,6 +1054,7 @@ export default {
457
1054
  }
458
1055
 
459
1056
  const startSync = async () => {
1057
+ await refreshConnectedState()
460
1058
  const init = await snapshotConnections()
461
1059
  for (const [k, v] of init) knownConns.set(k, v)
462
1060
 
@@ -469,7 +1067,10 @@ export default {
469
1067
  if (pluginAbort.signal.aborted) break
470
1068
  const data = ev?.data || ev?.properties || {}
471
1069
  const intId = String(data.integrationID || "")
472
- 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
473
1074
 
474
1075
  if (ev?.type === "credential.switched") {
475
1076
  await syncActiveToBridge(intId || undefined)