minicode-ai 0.9.26
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/CHANGELOG.md +935 -0
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/cli/args.ts +195 -0
- package/cli/auto-update.ts +108 -0
- package/cli/commands/auth.ts +166 -0
- package/cli/commands/config.ts +382 -0
- package/cli/commands/doctor.ts +128 -0
- package/cli/commands/exec.ts +179 -0
- package/cli/commands/mcp.ts +35 -0
- package/cli/commands/memory.ts +107 -0
- package/cli/commands/pricing.ts +100 -0
- package/cli/commands/providers.ts +162 -0
- package/cli/commands/sessions.ts +128 -0
- package/cli/commands/skills.ts +61 -0
- package/cli/commands/stats.ts +82 -0
- package/cli/commands.ts +317 -0
- package/cli/index.ts +539 -0
- package/cli/model-manager.ts +112 -0
- package/cli/provider-manager.ts +111 -0
- package/cli/repl.ts +734 -0
- package/cli/router.ts +124 -0
- package/cli/setup.ts +780 -0
- package/cli/wizard.ts +21 -0
- package/docs/ARCHITECTURE.html +1222 -0
- package/docs/README.md +109 -0
- package/docs/architecture.md +44 -0
- package/docs/changelog.md +3 -0
- package/package.json +91 -0
- package/src/agents/pool.ts +43 -0
- package/src/app/mentions.ts +50 -0
- package/src/app/provider-layer.ts +118 -0
- package/src/app/rag-layer.ts +105 -0
- package/src/app/session.ts +154 -0
- package/src/app/tool-layer.ts +56 -0
- package/src/config.ts +372 -0
- package/src/constants.ts +119 -0
- package/src/hooks/run.ts +89 -0
- package/src/lib/atomic-write.ts +88 -0
- package/src/lib/db-path.ts +36 -0
- package/src/lib/git-hardening.ts +91 -0
- package/src/lib/ignore.ts +58 -0
- package/src/lib/keystore.ts +202 -0
- package/src/lib/net.ts +70 -0
- package/src/lib/safe-open.ts +138 -0
- package/src/lib/session-id.ts +23 -0
- package/src/lib/trash.ts +38 -0
- package/src/lib/trusted-exec.ts +81 -0
- package/src/lsp/client.ts +395 -0
- package/src/mcp/client.ts +400 -0
- package/src/mcp/http-transport.ts +344 -0
- package/src/mcp/server.ts +538 -0
- package/src/mcp/transport.ts +150 -0
- package/src/memory/files.ts +159 -0
- package/src/memory/vector.ts +775 -0
- package/src/policy/allowlist.ts +67 -0
- package/src/policy/bash-guard.ts +465 -0
- package/src/policy/compaction.ts +271 -0
- package/src/policy/context.ts +161 -0
- package/src/policy/executor.ts +199 -0
- package/src/policy/jail.ts +127 -0
- package/src/policy/permission.ts +517 -0
- package/src/policy/pricing.ts +336 -0
- package/src/policy/ratelimit.ts +54 -0
- package/src/policy/sandbox-policy.ts +157 -0
- package/src/policy/scrub.ts +138 -0
- package/src/policy/update-check.ts +200 -0
- package/src/policy/usage.ts +292 -0
- package/src/policy/verifier.ts +181 -0
- package/src/providers/anthropic.ts +401 -0
- package/src/providers/auth-store.ts +139 -0
- package/src/providers/build.ts +136 -0
- package/src/providers/detect.ts +126 -0
- package/src/providers/effort.ts +165 -0
- package/src/providers/guards.ts +107 -0
- package/src/providers/oauth.ts +326 -0
- package/src/providers/presets.ts +122 -0
- package/src/providers/provision.ts +298 -0
- package/src/providers/responses.ts +371 -0
- package/src/providers/router.ts +247 -0
- package/src/repo/repomap.ts +470 -0
- package/src/sandbox/docker.ts +129 -0
- package/src/sandbox/os.ts +193 -0
- package/src/session/checkpoint.ts +543 -0
- package/src/session/journal.ts +1347 -0
- package/src/session/persistence.ts +446 -0
- package/src/session/shadow-git.ts +351 -0
- package/src/session/turn-marker.ts +118 -0
- package/src/skills/loader.ts +117 -0
- package/src/telemetry/trace.ts +283 -0
- package/src/tools/ask_user.ts +54 -0
- package/src/tools/bash.ts +400 -0
- package/src/tools/code_run.ts +96 -0
- package/src/tools/delete_file.ts +31 -0
- package/src/tools/edit.ts +204 -0
- package/src/tools/git.ts +301 -0
- package/src/tools/glob.ts +90 -0
- package/src/tools/grep.ts +281 -0
- package/src/tools/hashline.ts +66 -0
- package/src/tools/index.ts +103 -0
- package/src/tools/lsp.ts +346 -0
- package/src/tools/mcp_call.ts +163 -0
- package/src/tools/memory.ts +144 -0
- package/src/tools/move_file.ts +47 -0
- package/src/tools/patch.ts +86 -0
- package/src/tools/read_file.ts +130 -0
- package/src/tools/read_image.ts +80 -0
- package/src/tools/submit_result.ts +49 -0
- package/src/tools/task.ts +346 -0
- package/src/tools/todo.ts +201 -0
- package/src/tools/web_fetch.ts +161 -0
- package/src/tools/web_search.ts +156 -0
- package/src/tools/write_file.ts +42 -0
- package/src/ui/approval/prompt.ts +76 -0
- package/src/ui/assistant/simple.ts +568 -0
- package/src/ui/assistant/turn-status.ts +303 -0
- package/src/ui/contract.ts +55 -0
- package/src/ui/footer.ts +105 -0
- package/src/ui/input/input.ts +805 -0
- package/src/ui/input/prompt-engine.ts +606 -0
- package/src/ui/render/collapse.ts +84 -0
- package/src/ui/render/detail.ts +24 -0
- package/src/ui/render/diff.ts +181 -0
- package/src/ui/render/errors.ts +239 -0
- package/src/ui/render/format.ts +54 -0
- package/src/ui/render/highlight.ts +294 -0
- package/src/ui/render/markdown.ts +120 -0
- package/src/ui/render/money.ts +12 -0
- package/src/ui/render/reasoning.ts +20 -0
- package/src/ui/render/sanitize.ts +80 -0
- package/src/ui/render/table.ts +88 -0
- package/src/ui/render/theme.ts +339 -0
- package/src/ui/render/width.ts +256 -0
- package/src/ui/render/wrap.ts +120 -0
- package/src/ui/runtime/bus-debug.ts +83 -0
- package/src/ui/runtime/chrome.ts +301 -0
- package/src/ui/runtime/spinner.ts +77 -0
- package/src/ui/runtime/statusline.ts +227 -0
- package/src/ui/screens/model-manager.ts +434 -0
- package/src/ui/screens/overlay.ts +61 -0
- package/src/ui/screens/picker.ts +307 -0
- package/src/ui/screens/provider-manager.ts +450 -0
- package/src/ui/screens/wizard.ts +132 -0
- package/vendor/minicore/VENDOR.md +29 -0
- package/vendor/minicore/package.json +21 -0
- package/vendor/minicore/src/core/budget.ts +26 -0
- package/vendor/minicore/src/core/compact.ts +76 -0
- package/vendor/minicore/src/core/errors.ts +60 -0
- package/vendor/minicore/src/core/events.ts +74 -0
- package/vendor/minicore/src/core/executor.ts +139 -0
- package/vendor/minicore/src/core/history.ts +32 -0
- package/vendor/minicore/src/core/index.ts +42 -0
- package/vendor/minicore/src/core/loop.ts +344 -0
- package/vendor/minicore/src/core/permission.ts +24 -0
- package/vendor/minicore/src/core/provider.ts +39 -0
- package/vendor/minicore/src/core/recovery.ts +34 -0
- package/vendor/minicore/src/core/session.ts +327 -0
- package/vendor/minicore/src/core/snapshot.ts +142 -0
- package/vendor/minicore/src/core/tokens.ts +111 -0
- package/vendor/minicore/src/core/tool.ts +118 -0
- package/vendor/minicore/src/core/types.ts +50 -0
- package/vendor/minicore/src/providers/openai-compat.ts +366 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// OAuth 2.0 Device Authorization Grant (RFC 8628) untuk CLI.
|
|
2
|
+
//
|
|
3
|
+
// Kenapa device-code dan bukan authorization-code + PKCE? Device flow tidak
|
|
4
|
+
// butuh redirect URI, tidak butuh membuka port lokal, dan bekerja saat CLI
|
|
5
|
+
// dijalankan lewat SSH — tiga hal yang semuanya relevan untuk agent terminal.
|
|
6
|
+
// Tradeoff-nya user harus menyalin kode ke browser; itu wajar untuk login sekali.
|
|
7
|
+
//
|
|
8
|
+
// Alur:
|
|
9
|
+
// 1. POST device_authorization_endpoint → { device_code, user_code,
|
|
10
|
+
// verification_uri, interval, expires_in }
|
|
11
|
+
// 2. Tampilkan user_code + URI ke user.
|
|
12
|
+
// 3. Poll token_endpoint dengan grant_type=device_code sampai:
|
|
13
|
+
// - success → simpan token
|
|
14
|
+
// - authorization_pending → tunggu `interval`
|
|
15
|
+
// - slow_down → naikkan interval (RFC 8628 §3.5)
|
|
16
|
+
// - access_denied / expired_token → berhenti dengan pesan jelas
|
|
17
|
+
//
|
|
18
|
+
// Provider dideklarasikan sebagai data (OAUTH_PROVIDERS) bukan kode, supaya
|
|
19
|
+
// menambah provider = menambah satu entri, bukan menulis alur baru.
|
|
20
|
+
|
|
21
|
+
import { LIMITS } from "../constants.ts"
|
|
22
|
+
import { type AuthCredentials, getAuth, saveAuth } from "./auth-store.ts"
|
|
23
|
+
|
|
24
|
+
export interface OAuthProviderSpec {
|
|
25
|
+
id: string
|
|
26
|
+
label: string
|
|
27
|
+
/** Endpoint device authorization (RFC 8628 §3.1). */
|
|
28
|
+
deviceUrl: string
|
|
29
|
+
/** Endpoint token (dipakai untuk poll dan refresh). */
|
|
30
|
+
tokenUrl: string
|
|
31
|
+
clientId: string
|
|
32
|
+
scope?: string
|
|
33
|
+
/** baseUrl API setelah login berhasil — dipakai untuk mendaftarkan provider. */
|
|
34
|
+
apiBaseUrl: string
|
|
35
|
+
/** Model default bila detect gagal. */
|
|
36
|
+
fallbackModels: string[]
|
|
37
|
+
/** Catatan yang ditampilkan ke user sebelum login. */
|
|
38
|
+
note?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Qwen Code memakai device flow publik dengan free tier — kandidat paling masuk
|
|
42
|
+
// akal untuk "coba tanpa kartu kredit". clientId di bawah adalah client publik
|
|
43
|
+
// (RFC 8628 mengizinkan client publik tanpa secret).
|
|
44
|
+
//
|
|
45
|
+
// CATATAN JUJUR: nilai endpoint/clientId di sini belum bisa saya verifikasi
|
|
46
|
+
// dengan login sungguhan dari lingkungan ini (butuh interaksi browser).
|
|
47
|
+
// Mekanismenya diuji end-to-end terhadap server device-flow lokal; identitas
|
|
48
|
+
// provider-nya perlu dikonfirmasi saat pertama dipakai. `minicode auth login`
|
|
49
|
+
// akan melaporkan error server apa adanya bila nilainya salah, bukan gagal senyap.
|
|
50
|
+
export const OAUTH_PROVIDERS: OAuthProviderSpec[] = [
|
|
51
|
+
{
|
|
52
|
+
id: "qwen",
|
|
53
|
+
label: "Qwen Code (free tier, device login)",
|
|
54
|
+
deviceUrl: "https://chat.qwen.ai/api/v1/oauth2/device/code",
|
|
55
|
+
tokenUrl: "https://chat.qwen.ai/api/v1/oauth2/token",
|
|
56
|
+
clientId: "f0304373b74a44d2b584a3fb70ca9e56",
|
|
57
|
+
scope: "openid profile email model.completion",
|
|
58
|
+
apiBaseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
59
|
+
fallbackModels: ["qwen3-coder-plus", "qwen2.5-coder-32b-instruct"],
|
|
60
|
+
note: "Free tier harian. Verifikasi endpoint saat login pertama.",
|
|
61
|
+
},
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
export function findOAuthProvider(id: string): OAuthProviderSpec | undefined {
|
|
65
|
+
return OAUTH_PROVIDERS.find((p) => p.id === id.toLowerCase())
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface DeviceCodeStart {
|
|
69
|
+
deviceCode: string
|
|
70
|
+
userCode: string
|
|
71
|
+
verificationUri: string
|
|
72
|
+
/** URI lengkap dengan kode ter-embed, bila server menyediakannya. */
|
|
73
|
+
verificationUriComplete?: string
|
|
74
|
+
/** Detik antar-poll yang diminta server. */
|
|
75
|
+
interval: number
|
|
76
|
+
/** Epoch ms saat device_code kedaluwarsa. */
|
|
77
|
+
expiresAt: number
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface TokenResponse {
|
|
81
|
+
access_token?: string
|
|
82
|
+
refresh_token?: string
|
|
83
|
+
expires_in?: number
|
|
84
|
+
scope?: string
|
|
85
|
+
token_type?: string
|
|
86
|
+
error?: string
|
|
87
|
+
error_description?: string
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function postForm(url: string, body: Record<string, string>, timeoutMs: number) {
|
|
91
|
+
const res = await fetch(url, {
|
|
92
|
+
method: "POST",
|
|
93
|
+
headers: {
|
|
94
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
95
|
+
accept: "application/json",
|
|
96
|
+
},
|
|
97
|
+
body: new URLSearchParams(body).toString(),
|
|
98
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
99
|
+
redirect: "manual",
|
|
100
|
+
})
|
|
101
|
+
const text = await res.text()
|
|
102
|
+
let json: TokenResponse = {}
|
|
103
|
+
if (text.trim()) {
|
|
104
|
+
try {
|
|
105
|
+
json = JSON.parse(text) as TokenResponse
|
|
106
|
+
} catch {
|
|
107
|
+
// Server yang membalas HTML (proxy, captive portal) tidak boleh muncul
|
|
108
|
+
// sebagai "undefined is not an object" di layar user.
|
|
109
|
+
throw new Error(`response is not JSON (HTTP ${res.status}): ${text.slice(0, 200)}`)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { status: res.status, json }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Langkah 1: minta device code. Diekspor untuk test. */
|
|
116
|
+
export async function startDeviceFlow(spec: OAuthProviderSpec): Promise<DeviceCodeStart> {
|
|
117
|
+
const { status, json } = await postForm(
|
|
118
|
+
spec.deviceUrl,
|
|
119
|
+
{
|
|
120
|
+
client_id: spec.clientId,
|
|
121
|
+
...(spec.scope ? { scope: spec.scope } : {}),
|
|
122
|
+
},
|
|
123
|
+
LIMITS.OAUTH_REQUEST_TIMEOUT_MS,
|
|
124
|
+
)
|
|
125
|
+
const raw = json as TokenResponse & {
|
|
126
|
+
device_code?: string
|
|
127
|
+
user_code?: string
|
|
128
|
+
verification_uri?: string
|
|
129
|
+
verification_url?: string
|
|
130
|
+
verification_uri_complete?: string
|
|
131
|
+
interval?: number
|
|
132
|
+
expires_in?: number
|
|
133
|
+
}
|
|
134
|
+
if (raw.error) {
|
|
135
|
+
throw new Error(`device authorization rejected: ${raw.error_description ?? raw.error}`)
|
|
136
|
+
}
|
|
137
|
+
if (status >= 400) throw new Error(`device authorization failed (HTTP ${status})`)
|
|
138
|
+
if (!raw.device_code || !raw.user_code) {
|
|
139
|
+
throw new Error("server did not return device_code/user_code")
|
|
140
|
+
}
|
|
141
|
+
// Beberapa server memakai `verification_url` (non-standar, mis. Google lama).
|
|
142
|
+
const uri = raw.verification_uri ?? raw.verification_url
|
|
143
|
+
if (!uri) throw new Error("server did not return verification_uri")
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
deviceCode: raw.device_code,
|
|
147
|
+
userCode: raw.user_code,
|
|
148
|
+
verificationUri: uri,
|
|
149
|
+
...(raw.verification_uri_complete
|
|
150
|
+
? { verificationUriComplete: raw.verification_uri_complete }
|
|
151
|
+
: {}),
|
|
152
|
+
// RFC 8628: default 5 detik bila server tak menyebut interval.
|
|
153
|
+
interval: Math.max(1, Math.min(raw.interval ?? 5, 60)),
|
|
154
|
+
expiresAt: Date.now() + (raw.expires_in ?? 600) * 1000,
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export type PollOutcome =
|
|
159
|
+
| { state: "success"; creds: AuthCredentials }
|
|
160
|
+
| { state: "pending"; nextIntervalSec: number }
|
|
161
|
+
| { state: "denied"; message: string }
|
|
162
|
+
| { state: "expired"; message: string }
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Satu iterasi poll. Dipisah dari loop agar bisa diuji tanpa menunggu.
|
|
166
|
+
* Diekspor untuk test.
|
|
167
|
+
*/
|
|
168
|
+
export async function pollDeviceTokenOnce(
|
|
169
|
+
spec: OAuthProviderSpec,
|
|
170
|
+
deviceCode: string,
|
|
171
|
+
currentIntervalSec: number,
|
|
172
|
+
): Promise<PollOutcome> {
|
|
173
|
+
const { status, json } = await postForm(
|
|
174
|
+
spec.tokenUrl,
|
|
175
|
+
{
|
|
176
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
177
|
+
device_code: deviceCode,
|
|
178
|
+
client_id: spec.clientId,
|
|
179
|
+
},
|
|
180
|
+
LIMITS.OAUTH_REQUEST_TIMEOUT_MS,
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
if (json.access_token) {
|
|
184
|
+
return {
|
|
185
|
+
state: "success",
|
|
186
|
+
creds: {
|
|
187
|
+
type: "oauth",
|
|
188
|
+
accessToken: json.access_token,
|
|
189
|
+
...(json.refresh_token ? { refreshToken: json.refresh_token } : {}),
|
|
190
|
+
...(json.expires_in ? { expiresAt: Date.now() + json.expires_in * 1000 } : {}),
|
|
191
|
+
...(json.scope ? { scope: json.scope } : {}),
|
|
192
|
+
tokenUrl: spec.tokenUrl,
|
|
193
|
+
clientId: spec.clientId,
|
|
194
|
+
},
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
switch (json.error) {
|
|
199
|
+
case "authorization_pending":
|
|
200
|
+
return { state: "pending", nextIntervalSec: currentIntervalSec }
|
|
201
|
+
case "slow_down":
|
|
202
|
+
// RFC 8628 §3.5: klien WAJIB menaikkan interval, minimal +5 detik.
|
|
203
|
+
return { state: "pending", nextIntervalSec: Math.min(currentIntervalSec + 5, 60) }
|
|
204
|
+
case "access_denied":
|
|
205
|
+
return { state: "denied", message: json.error_description ?? "user denied the request" }
|
|
206
|
+
case "expired_token":
|
|
207
|
+
return { state: "expired", message: json.error_description ?? "device code expired" }
|
|
208
|
+
default:
|
|
209
|
+
// Error tak dikenal: jangan diam-diam terus polling sampai timeout.
|
|
210
|
+
return {
|
|
211
|
+
state: "denied",
|
|
212
|
+
message: json.error
|
|
213
|
+
? `${json.error}: ${json.error_description ?? ""}`.trim()
|
|
214
|
+
: `HTTP ${status} without a token`,
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export interface LoginCallbacks {
|
|
220
|
+
/** Dipanggil sekali dengan instruksi untuk user. */
|
|
221
|
+
onPrompt(info: DeviceCodeStart): void
|
|
222
|
+
/** Progres opsional tiap poll. */
|
|
223
|
+
onPoll?(elapsedSec: number): void
|
|
224
|
+
/** Batalkan login. */
|
|
225
|
+
signal?: AbortSignal
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Alur lengkap: mulai device flow, tampilkan kode, poll sampai selesai. */
|
|
229
|
+
export async function loginWithDeviceFlow(
|
|
230
|
+
spec: OAuthProviderSpec,
|
|
231
|
+
cb: LoginCallbacks,
|
|
232
|
+
sleep: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
233
|
+
): Promise<AuthCredentials> {
|
|
234
|
+
const start = await startDeviceFlow(spec)
|
|
235
|
+
cb.onPrompt(start)
|
|
236
|
+
|
|
237
|
+
let interval = start.interval
|
|
238
|
+
const t0 = Date.now()
|
|
239
|
+
while (true) {
|
|
240
|
+
if (cb.signal?.aborted) throw new Error("login canceled")
|
|
241
|
+
if (Date.now() >= start.expiresAt) {
|
|
242
|
+
throw new Error("device code expired — run `minicode auth login` again")
|
|
243
|
+
}
|
|
244
|
+
await sleep(interval * 1000)
|
|
245
|
+
if (cb.signal?.aborted) throw new Error("login canceled")
|
|
246
|
+
|
|
247
|
+
const res = await pollDeviceTokenOnce(spec, start.deviceCode, interval)
|
|
248
|
+
if (res.state === "success") {
|
|
249
|
+
await saveAuth(spec.id, res.creds)
|
|
250
|
+
return res.creds
|
|
251
|
+
}
|
|
252
|
+
if (res.state === "denied") throw new Error(`login rejected: ${res.message}`)
|
|
253
|
+
if (res.state === "expired") throw new Error(`login expired: ${res.message}`)
|
|
254
|
+
interval = res.nextIntervalSec
|
|
255
|
+
cb.onPoll?.(Math.round((Date.now() - t0) / 1000))
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Tukar refresh token dengan access token baru.
|
|
261
|
+
*
|
|
262
|
+
* Return null bila tidak ada refresh token atau server menolak — pemanggil
|
|
263
|
+
* memutuskan apakah itu berarti "minta login ulang".
|
|
264
|
+
*/
|
|
265
|
+
export async function refreshAccessToken(
|
|
266
|
+
providerId: string,
|
|
267
|
+
creds: AuthCredentials,
|
|
268
|
+
): Promise<AuthCredentials | null> {
|
|
269
|
+
if (!creds.refreshToken || !creds.tokenUrl || !creds.clientId) return null
|
|
270
|
+
let res: { status: number; json: TokenResponse }
|
|
271
|
+
try {
|
|
272
|
+
res = await postForm(
|
|
273
|
+
creds.tokenUrl,
|
|
274
|
+
{
|
|
275
|
+
grant_type: "refresh_token",
|
|
276
|
+
refresh_token: creds.refreshToken,
|
|
277
|
+
client_id: creds.clientId,
|
|
278
|
+
},
|
|
279
|
+
LIMITS.OAUTH_REQUEST_TIMEOUT_MS,
|
|
280
|
+
)
|
|
281
|
+
} catch {
|
|
282
|
+
return null
|
|
283
|
+
}
|
|
284
|
+
if (!res.json.access_token) return null
|
|
285
|
+
const next: AuthCredentials = {
|
|
286
|
+
type: "oauth",
|
|
287
|
+
accessToken: res.json.access_token,
|
|
288
|
+
// Server boleh merotasi refresh token; bila tidak, pakai yang lama.
|
|
289
|
+
refreshToken: res.json.refresh_token ?? creds.refreshToken,
|
|
290
|
+
...(res.json.expires_in ? { expiresAt: Date.now() + res.json.expires_in * 1000 } : {}),
|
|
291
|
+
...(res.json.scope ? { scope: res.json.scope } : creds.scope ? { scope: creds.scope } : {}),
|
|
292
|
+
tokenUrl: creds.tokenUrl,
|
|
293
|
+
clientId: creds.clientId,
|
|
294
|
+
}
|
|
295
|
+
await saveAuth(providerId, next)
|
|
296
|
+
return next
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Access token yang pasti valid: refresh otomatis bila hampir kedaluwarsa.
|
|
301
|
+
* Return null bila belum login atau refresh gagal.
|
|
302
|
+
*/
|
|
303
|
+
const refreshInflight = new Map<string, Promise<string | null>>()
|
|
304
|
+
|
|
305
|
+
export async function getValidAccessToken(providerId: string): Promise<string | null> {
|
|
306
|
+
const creds = await getAuth(providerId)
|
|
307
|
+
if (!creds) return null
|
|
308
|
+
const { isExpired } = await import("./auth-store.ts")
|
|
309
|
+
if (!isExpired(creds)) return creds.accessToken
|
|
310
|
+
// Dedup refresh konkuren (temuan audit #03): dua pemanggil paralel
|
|
311
|
+
// (sesi utama + sub-agen) tanpa ini memicu dua token POST dan last-wins
|
|
312
|
+
// saveAuth — rotasi bisa menginvalidasi token pertama.
|
|
313
|
+
const ongoing = refreshInflight.get(providerId)
|
|
314
|
+
if (ongoing) return ongoing
|
|
315
|
+
let run!: Promise<string | null>
|
|
316
|
+
run = (async () => {
|
|
317
|
+
try {
|
|
318
|
+
const refreshed = await refreshAccessToken(providerId, creds)
|
|
319
|
+
return refreshed?.accessToken ?? null
|
|
320
|
+
} finally {
|
|
321
|
+
if (refreshInflight.get(providerId) === run) refreshInflight.delete(providerId)
|
|
322
|
+
}
|
|
323
|
+
})()
|
|
324
|
+
refreshInflight.set(providerId, run)
|
|
325
|
+
return run
|
|
326
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Gateway presets — satu sumber kebenaran untuk baseUrl umum.
|
|
2
|
+
// Dipakai /provider-add (REPL) & wizard setup (cli/wizard.ts).
|
|
3
|
+
|
|
4
|
+
export interface GatewayPreset {
|
|
5
|
+
id: string
|
|
6
|
+
label: string
|
|
7
|
+
baseUrl: string
|
|
8
|
+
fallbackModels: string[]
|
|
9
|
+
hint?: string
|
|
10
|
+
// beberapa gateway butuh header tambahan (x-api-key vs Bearer) —
|
|
11
|
+
// deteksi hybrid sudah coba keduanya, preset cukup id+baseUrl.
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const GATEWAY_PRESETS: GatewayPreset[] = [
|
|
15
|
+
{
|
|
16
|
+
id: "openai",
|
|
17
|
+
label: "OpenAI (gpt, o-series)",
|
|
18
|
+
baseUrl: "https://api.openai.com/v1",
|
|
19
|
+
fallbackModels: ["gpt-4o-mini", "gpt-4o", "o3-mini"],
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
id: "anthropic",
|
|
23
|
+
label: "Anthropic (Claude)",
|
|
24
|
+
baseUrl: "https://api.anthropic.com",
|
|
25
|
+
fallbackModels: ["claude-sonnet-4", "claude-opus-4", "claude-haiku-3.5"],
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
id: "openrouter",
|
|
29
|
+
label: "OpenRouter (gateway 75+ model)",
|
|
30
|
+
baseUrl: "https://openrouter.ai/api/v1",
|
|
31
|
+
fallbackModels: [
|
|
32
|
+
// ID gratis pertama terverifikasi live 2026-09-14 (pengganti
|
|
33
|
+
// llama-3.1-8b-instruct:free yang sudah tak ada di katalog).
|
|
34
|
+
// Free-tier OpenRouter berputar — bila wizard gagal, cek katalog.
|
|
35
|
+
"nvidia/nemotron-3.5-lightning:free",
|
|
36
|
+
"anthropic/claude-3.5-sonnet",
|
|
37
|
+
"openai/gpt-4o-mini",
|
|
38
|
+
],
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
id: "deepseek",
|
|
42
|
+
label: "DeepSeek (deepseek-chat/reasoner)",
|
|
43
|
+
baseUrl: "https://api.deepseek.com/v1",
|
|
44
|
+
fallbackModels: ["deepseek-chat", "deepseek-reasoner"],
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
id: "opencode-zen",
|
|
48
|
+
label: "OpenCode Zen (opencode.ai gateway)",
|
|
49
|
+
baseUrl: "https://opencode.ai/zen/v1",
|
|
50
|
+
fallbackModels: [
|
|
51
|
+
"muse-spark-1.2-contributor-free",
|
|
52
|
+
"muse-spark-1.3-contributor-free",
|
|
53
|
+
"nemotron-3.5-lightning:free",
|
|
54
|
+
"nemotron-3-nano-30b-a3b:free",
|
|
55
|
+
"gemini-2.0-flash:free",
|
|
56
|
+
"deepseek-v4-flash:free",
|
|
57
|
+
"claude-sonnet-4",
|
|
58
|
+
],
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
id: "google",
|
|
62
|
+
label: "Google Gemini (konteks 1M)",
|
|
63
|
+
baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
64
|
+
fallbackModels: ["gemini-2.0-flash", "gemini-2.5-pro"],
|
|
65
|
+
},
|
|
66
|
+
// Local & open-weight — OpenCode-style BYOK $0
|
|
67
|
+
{
|
|
68
|
+
id: "ollama",
|
|
69
|
+
label: "Ollama (local, free - no API key)",
|
|
70
|
+
baseUrl: "http://localhost:11434/v1",
|
|
71
|
+
fallbackModels: ["llama3.1", "qwen2.5-coder", "deepseek-coder"],
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
id: "qwen",
|
|
75
|
+
label: "Qwen (Alibaba Cloud, Qwen3-Coder)",
|
|
76
|
+
baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
77
|
+
fallbackModels: ["qwen3-coder-plus", "qwen2.5-coder-32b-instruct"],
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
id: "groq",
|
|
81
|
+
label: "Groq (inferensi sangat cepat)",
|
|
82
|
+
baseUrl: "https://api.groq.com/openai/v1",
|
|
83
|
+
fallbackModels: ["llama-3.1-70b-versatile", "mixtral-8x7b-32768"],
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
id: "together",
|
|
87
|
+
label: "Together AI (model terbuka)",
|
|
88
|
+
baseUrl: "https://api.together.xyz/v1",
|
|
89
|
+
fallbackModels: ["meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"],
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
id: "fireworks",
|
|
93
|
+
label: "Fireworks AI",
|
|
94
|
+
baseUrl: "https://api.fireworks.ai/inference/v1",
|
|
95
|
+
fallbackModels: ["accounts/fireworks/models/llama-v3p1-405b-instruct"],
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
id: "mistral",
|
|
99
|
+
label: "Mistral AI",
|
|
100
|
+
baseUrl: "https://api.mistral.ai/v1",
|
|
101
|
+
fallbackModels: ["mistral-large-latest", "codestral-latest"],
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
id: "cohere",
|
|
105
|
+
label: "Cohere",
|
|
106
|
+
baseUrl: "https://api.cohere.ai/compatibility/v1",
|
|
107
|
+
fallbackModels: ["command-r-plus"],
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
id: "generic",
|
|
111
|
+
label: "OpenAI-compatible umum (vLLM/LM Studio/lain)",
|
|
112
|
+
baseUrl: "http://localhost:11434/v1",
|
|
113
|
+
fallbackModels: ["llama3"],
|
|
114
|
+
},
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
// id preset → opsi "custom" di ujung daftar
|
|
118
|
+
export const CUSTOM_PRESET_ID = "custom"
|
|
119
|
+
|
|
120
|
+
export function findPreset(id: string): GatewayPreset | undefined {
|
|
121
|
+
return GATEWAY_PRESETS.find((p) => p.id === id)
|
|
122
|
+
}
|