Repository navigation
Expand file tree
/
Copy pathplugin.ts
More file actions
435 lines (398 loc) · 15.4 KB
/
Copy pathplugin.ts
File metadata and controls
435 lines (398 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// The opencode-deveco plugin entry (hybrid architecture).
//
// The published opencode binary does NOT load external plugins' auth hooks, so
// this plugin cannot inject the DevEco Bearer token directly. Instead it uses a
// HYBRID approach:
//
// 1. On load, it starts a LOCAL PROXY server (DevEcoProxy) that holds the
// DevEco credentials and forwards requests to the real DevEco backend.
// 2. The config hook injects a `deveco` provider whose baseURL points at the
// local proxy. opencode then sends normal OpenAI-style requests to the
// proxy; the proxy adds auth + applies DevEco URL quirks + forwards.
//
// The `auth` hook (loader + methods) is still returned for forward-compat: on
// opencode versions that DO load external plugin auth, the auth.loader's custom
// fetch takes over (bypassing the proxy). On versions that don't, the proxy is
// the live path.
import type { Hooks, Plugin, PluginInput } from "@opencode-ai/plugin"
import {
ACCESS_TOKEN_EXPIRES_MS,
DEVECO_DEFAULTS,
DEVECO_EXIT_QUEUE_URL,
OAUTH_DUMMY_KEY,
PROVIDER_ID,
type ModelInfo,
type ProviderInfo,
log,
} from "./config.js"
import { createLoginService } from "./auth-login.js"
import { JsonTokenStore } from "./token-store.js"
import { getDevecoProviderConfig, loadPersistedModels, resetModelCache } from "./models.js"
import { DevEcoProxy, conversationKey } from "./proxy.js"
import { applyVisionRouting } from "./vision-routing.js"
import { normalizeOpenAIChatBody } from "./openai-normalize.js"
// Default local proxy port. Kept in sync with README and the standalone CLI.
const PROXY_PORT = Number(process.env.DEVECO_PROXY_PORT) || 17128
const PROXY_HOST = "127.0.0.1"
const PROXY_BASE_URL = `http://${PROXY_HOST}:${PROXY_PORT}/v2`
// Shared singletons (used by the auth-hook fallback path).
const tokenStore = new JsonTokenStore()
const loginService = createLoginService(tokenStore)
// Per-session Chat-Id map for the auth-loader fallback path.
const sessionChatIdMap = new Map<string, string>()
/** Release the upstream queue slot, matching proxy.ts semantics (one retry). */
function exitQueue(key: string, chatId: string, model: string, token: string): void {
const url = `${DEVECO_EXIT_QUEUE_URL}?modelId=${encodeURIComponent(model)}`
const attempt = (retriesLeft: number): void => {
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Session-Id": key,
"Chat-Id": chatId,
Authorization: `Bearer ${token}`,
},
signal: AbortSignal.timeout(5_000),
})
.then((r) => {
if (r.ok) log.debug(`exitSessionQueue -> ${r.status}`)
else if (retriesLeft > 0) {
log.warn(`exitSessionQueue -> HTTP ${r.status}, retrying`)
setTimeout(() => attempt(retriesLeft - 1), 500)
} else log.warn(`exitSessionQueue -> HTTP ${r.status}`)
})
.catch((err) => {
if (retriesLeft > 0) {
log.warn("exitSessionQueue failed, retrying", { error: String(err) })
setTimeout(() => attempt(retriesLeft - 1), 500)
} else log.warn("exitSessionQueue failed", { error: String(err) })
})
}
attempt(1)
}
/** True when the auth loader is still talking to our own local proxy. */
function isProxyUrl(input: RequestInfo | URL): boolean {
try {
const u =
input instanceof URL
? input
: new URL(typeof input === "string" ? input : (input as Request).url)
return u.hostname === PROXY_HOST || u.hostname === "localhost"
} catch {
return false
}
}
// Proxy lifecycle — started once on plugin load.
let proxyStarted: Promise<DevEcoProxy> | null = null
function startProxy(): Promise<DevEcoProxy> {
if (!proxyStarted) {
proxyStarted = (async () => {
const proxy = new DevEcoProxy({ port: PROXY_PORT, hostname: PROXY_HOST })
await proxy.start()
return proxy
})().catch((err) => {
proxyStarted = null // allow retry
log.error("failed to start DevEco proxy", { error: String(err) })
throw err
})
}
return proxyStarted
}
// ---------------------------------------------------------------------------
// config hook — inject a `deveco` provider that points at our local proxy.
// The model list comes from the catalog snapshot the last successful fetch
// persisted, so cloud-side model changes reach the picker on the next start;
// the static defaults cover a cold start. A user-owned entry keeps its own
// fields and per-model settings.
// ---------------------------------------------------------------------------
/**
* Merge the cloud catalog with whatever the user configured: the cloud supplies
* the metadata (context limits, effort tiers, modalities), an explicit user
* entry still wins field by field.
*/
export function mergeModels(
catalog: Record<string, ModelInfo>,
userModels: unknown,
): Record<string, ModelInfo> {
const merged: Record<string, ModelInfo> = { ...catalog }
if (!userModels || typeof userModels !== "object") return merged
for (const [id, userModel] of Object.entries(userModels as Record<string, unknown>)) {
const fromCatalog = merged[id]
merged[id] =
fromCatalog && userModel && typeof userModel === "object"
? { ...fromCatalog, ...(userModel as ModelInfo) }
: (userModel as ModelInfo)
}
return merged
}
export function applyConfigHook(cfg: {
provider?: Record<string, unknown>
small_model?: string
}): void {
try {
if (!cfg || typeof cfg !== "object") return
cfg.provider ??= {}
const persisted = loadPersistedModels()
const persistedModels = persisted?.config.models
const catalog =
persistedModels && Object.keys(persistedModels).length > 0
? persistedModels
: DEVECO_DEFAULTS.provider.models
const existing = cfg.provider[PROVIDER_ID]
if (!existing) {
const provider: ProviderInfo = {
name: "DevEco Code",
npm: "@ai-sdk/openai-compatible",
api: PROXY_BASE_URL,
env: [],
options: { apiKey: OAUTH_DUMMY_KEY, baseURL: PROXY_BASE_URL },
models: { ...catalog },
}
cfg.provider[PROVIDER_ID] = provider
} else if (typeof existing === "object") {
// A user-owned entry keeps its own fields (baseURL, options, …); only the
// model list is merged into it.
const entry = existing as Record<string, unknown>
entry.models = mergeModels({ ...catalog }, entry.models)
}
// opencode resolves the small model from this top-level field (the DevEco
// fork reads task_default_model_map directly), so pointing it at the
// cloud's declared model keeps title generation and similar side-tasks on
// the model DevEco intends. A user-set small_model wins.
const small = persisted?.taskMap?.small_model
if (small && typeof small === "string" && !cfg.small_model) {
cfg.small_model = `${PROVIDER_ID}/${small}`
}
} catch (err) {
log.error("config hook failed", { error: String(err) })
}
}
// ---------------------------------------------------------------------------
// auth.loader (forward-compat fallback) — injects the Bearer token directly
// when opencode loads plugin auth. Used by opencode versions that support
// external plugin auth; otherwise unused (the proxy is the live path).
// ---------------------------------------------------------------------------
function isOAuthLike(v: unknown): v is {
type: "oauth"
access?: string
refresh?: string
expires?: number
} {
return !!v && typeof v === "object" && (v as Record<string, unknown>).type === "oauth"
}
function buildAuthedFetch(
getAuth: () => Promise<unknown>,
persistAuth: (a: string, r: string, e: number) => Promise<void>,
) {
return async function devEcoFetch(
requestInput: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
if (init?.headers) {
if (init.headers instanceof Headers) {
init.headers.delete("authorization")
init.headers.delete("Authorization")
} else if (Array.isArray(init.headers)) {
init.headers = init.headers.filter(([k]) => k.toLowerCase() !== "authorization")
} else {
const h = { ...init.headers }
delete h["authorization"]
delete h["Authorization"]
init.headers = h as Record<string, string>
}
}
const current = await getAuth()
if (!isOAuthLike(current)) return fetch(requestInput as RequestInfo, init)
if (!current.access || (current.expires ?? 0) < Date.now()) {
const jwtToken = await tokenStore.load()
if (jwtToken) {
const refreshed = await loginService.refreshToken(jwtToken)
if (refreshed?.accessToken) {
const exp = Date.now() + ACCESS_TOKEN_EXPIRES_MS
await persistAuth(refreshed.accessToken, refreshed.refreshToken, exp)
current.access = refreshed.accessToken
if (current.refresh !== undefined) current.refresh = refreshed.refreshToken
current.expires = exp
} else {
return new Response(
JSON.stringify({ error: "Token refresh failed. Please re-login." }),
{ status: 401, headers: { "Content-Type": "application/json" } },
)
}
} else {
return new Response(
JSON.stringify({ error: "DevEco login expired. Please re-login." }),
{ status: 401, headers: { "Content-Type": "application/json" } },
)
}
}
const headers = new Headers()
if (init?.headers) {
if (init.headers instanceof Headers) {
init.headers.forEach((v, k) => headers.set(k, v))
} else if (Array.isArray(init.headers)) {
for (const [k, v] of init.headers) if (v !== undefined) headers.set(k, String(v))
} else {
for (const [k, v] of Object.entries(init.headers))
if (v !== undefined) headers.set(k, String(v))
}
}
if (current.access) headers.set("authorization", `Bearer ${current.access}`)
headers.set("lang", "en")
let finalInput: RequestInfo | URL = requestInput
let convKey = crypto.randomUUID().replace(/-/g, "")
let upstreamModel = ""
let streamBody = false
let bodyForFetch: string | undefined
if (typeof init?.body === "string") {
try {
const parsed = JSON.parse(init.body) as Record<string, unknown>
if (typeof parsed.model === "string") upstreamModel = parsed.model
if (parsed.stream === true) streamBody = true
const explicit =
headers.get("x-deveco-session") ||
headers.get("x-session-affinity") ||
headers.get("x-session-id")
convKey = explicit || conversationKey(parsed)
// Same DevEco quirks as the proxy: role/token-cap/tool_choice rewrites
// and the transparent vision fallback.
const normalized = normalizeOpenAIChatBody(parsed)
const routing = applyVisionRouting(normalized.body)
if (routing) {
upstreamModel = routing.upstreamModel
if (routing.rerouted || routing.imagesStripped || normalized.changed) {
bodyForFetch = JSON.stringify(routing.body)
}
}
if (!streamBody) {
const url =
requestInput instanceof URL
? new URL(requestInput.toString())
: new URL(
typeof requestInput === "string"
? requestInput
: (requestInput as Request).url,
)
url.pathname = url.pathname
.replace(/\/$/, "")
.replace(/\/chat\/completions$/, "/no-stream/chat/completions")
finalInput = url
}
} catch {
/* ignore */
}
}
let chatId = sessionChatIdMap.get(convKey)
if (!chatId) {
// Bound the map like the proxy's chatIdFor: a long-lived process would
// otherwise accumulate one entry per conversation forever.
if (sessionChatIdMap.size >= 500) {
sessionChatIdMap.delete(sessionChatIdMap.keys().next().value!)
}
chatId = crypto.randomUUID().replace(/-/g, "")
sessionChatIdMap.set(convKey, chatId)
}
headers.set("Chat-Id", chatId)
headers.set("Session-Id", convKey)
const initForFetch: RequestInit = { ...init, headers }
if (bodyForFetch !== undefined) initForFetch.body = bodyForFetch
void getDevecoProviderConfig(current.access ?? "").catch(() => {})
const directToUpstream = !isProxyUrl(requestInput)
const token = current.access ?? ""
const release = () => exitQueue(convKey, chatId, upstreamModel, token)
let response: Response
try {
response = await fetch(finalInput as RequestInfo, initForFetch)
} catch (err) {
if (directToUpstream && upstreamModel) release()
throw err
}
if (!directToUpstream || !upstreamModel) return response
// For streams, release the queue slot only when the body has been fully
// consumed (or the client disconnects), matching the proxy's lifecycle.
if (streamBody && response.body) {
const wrapped = response.body.pipeThrough(
new TransformStream({
flush() {
release()
},
}),
)
return new Response(wrapped, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
})
}
release()
return response
}
}
// ---------------------------------------------------------------------------
// Plugin export
// ---------------------------------------------------------------------------
export const DevEcoPlugin: Plugin = async (input: PluginInput): Promise<Hooks> => {
log.info("opencode-deveco plugin LOADED; starting local proxy")
// Start the proxy (fire-and-forget; failures are logged).
void startProxy().catch(() => {
/* logged in startProxy */
})
const persistAuth = async (a: string, r: string, e: number): Promise<void> => {
try {
await input.client.auth.set({
path: { id: PROVIDER_ID },
body: { type: "oauth", access: a, refresh: r, expires: e },
})
} catch (err) {
log.error("failed to persist refreshed auth via client.auth.set", {
error: String(err),
})
}
}
return {
config: async (cfg) => applyConfigHook(cfg),
auth: {
provider: PROVIDER_ID,
async loader(getAuth: () => Promise<unknown>, _provider: unknown) {
const info = await getAuth()
if (!info) return {}
return {
apiKey: OAUTH_DUMMY_KEY,
fetch: buildAuthedFetch(getAuth as () => Promise<unknown>, persistAuth),
}
},
methods: [
{
type: "oauth",
label: "Login with Huawei DevEco Account",
async authorize() {
return {
url: "",
instructions: "Opening browser for login...",
method: "auto" as const,
async callback() {
resetModelCache()
const result = await loginService.login()
if (!result.success) {
return {
type: "failed" as const,
error: result.unsupportedRegion
? "Sorry, only China site accounts are currently supported"
: result.error || "Login failed",
}
}
return {
type: "success" as const,
provider: PROVIDER_ID,
access: result.userInfo?.accessToken || "",
refresh: result.userInfo?.refreshToken || "",
expires: Date.now() + ACCESS_TOKEN_EXPIRES_MS,
}
},
}
},
},
],
},
}
}