-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost.js
More file actions
268 lines (248 loc) · 9.38 KB
/
Copy pathhost.js
File metadata and controls
268 lines (248 loc) · 9.38 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
// OpenCode usage + plan-models helper — Host half.
// Fetches OpenCode Zen usage windows (5h/1w/1m) and the current plan's
// available models for every opencode-family provider configured in DSH
// (settings → llm-pi-ai.providers with an OPENCODE* apiKeyEnv or an
// opencode.ai baseURL), polls every 30s, and serves the snapshot to the
// Client half over the package-private RPC method "ocu/state".
//
// Usage endpoint (OpenAI-compatible auth): GET https://opencode.ai/zen/go/v1/usage
// → { usage: { rolling, weekly, monthly: { status, percent, resetsAt } } }
// Models endpoints (per family):
// zen family → GET https://opencode.ai/zen/v1/models
// go family → GET https://opencode.ai/zen/go/v1/models
return {
inject: ['timer'],
apply(ctx) {
const settingsSvc = ctx.get('settings')
const credentialsSvc = ctx.get('credentials')
const subprocessSvc = ctx.get('subprocess')
const agentDefault = ctx.get('agentDefaultModel')
const USAGE_URL = 'https://opencode.ai/zen/go/v1/usage'
const MODELS_GO = 'https://opencode.ai/zen/go/v1/models'
const MODELS_ZEN = 'https://opencode.ai/zen/v1/models'
const FAMILY_IDS = ['opencode', 'opencode-go']
const FALLBACK_ENVS = ['OPENCODE_GO_API_KEY', 'OPENCODE_API_KEY']
let curlPath = null
let polling = false
let snapshot = { providers: [], active: null, fetchedAt: 0 }
function defaultName(id) {
if (id === 'opencode') return 'OpenCode Zen'
if (id === 'opencode-go') return 'OpenCode Zen Go'
return id
}
function isFamily(id, entry) {
if (FAMILY_IDS.indexOf(id) !== -1) return true
const env = entry && entry.apiKeyEnv
if (typeof env === 'string' && /^OPENCODE/i.test(env)) return true
const url = entry && entry.baseURL
return typeof url === 'string' && url.indexOf('opencode.ai') !== -1
}
function familyOf(id, entry) {
const url = entry && entry.baseURL
if (typeof url === 'string' && url.indexOf('/zen/go') !== -1) return 'go'
if (typeof url === 'string' && url.indexOf('/zen') !== -1) return 'zen'
return id === 'opencode' ? 'zen' : 'go'
}
// The RPC bridge requires lossless JSON: no undefined anywhere.
function sanitize(value) {
if (value === undefined) return null
if (Array.isArray(value)) return value.map(sanitize)
if (value !== null && typeof value === 'object') {
const out = {}
for (const k of Object.keys(value)) out[k] = sanitize(value[k])
return out
}
return value
}
// One-shot authenticated HTTP GET through curl (the web seam cannot send
// Authorization headers). Uses collected stdout, offset readers work after
// exit, so a failure yields `{ error }` and success yields `{ status, body }`.
async function runCurl(args) {
if (!subprocessSvc) return { error: 'subprocess service unavailable' }
let exe = curlPath
if (!exe) {
try {
exe = await subprocessSvc.resolveExecutable('curl.exe')
} catch (e) {
exe = 'C:\\Windows\\System32\\curl.exe'
}
curlPath = exe
}
let handle
try {
handle = subprocessSvc.spawn({
argv: [exe, '--silent', '--show-error', '--location', '--max-time', '20'].concat(args),
cwd: 'C:\\',
stdio: { stdin: 'ignore', stdout: { maxBytes: 262144 }, stderr: { maxBytes: 16384 } },
graceMs: 3000
})
} catch (err) {
return { error: String((err && err.message) || err) }
}
const outcome = await handle.done
const out = handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
const errText = handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
if (outcome.exitCode !== 0) {
return { error: (errText && errText.trim()) || ('curl exit ' + String(outcome.exitCode)) }
}
const m = out.match(/\n__HTTP__(\d+)\s*$/)
const status = m ? Number(m[1]) : 200
const body = m ? out.slice(0, m.index) : out
return { status, body }
}
async function fetchJson(url, key, onError) {
const r = await runCurl(
['--header', 'Authorization: Bearer ' + key, '--write-out', '\n__HTTP__%{http_code}', url],
)
if (r.error) {
if (onError) onError(r.error)
return null
}
if (r.status !== 200) {
const msg = 'HTTP ' + r.status + (r.body && r.body.trim() ? ' — ' + r.body.slice(0, 220) : '')
if (onError) onError(msg)
return null
}
try {
return JSON.parse(r.body)
} catch (e) {
if (onError) onError('invalid JSON response')
return null
}
}
// Resolve which providers are opencode-family and their API keys,
// grouped by the resolved key value so identical keys fetch once.
async function collectTargets() {
const raw = []
const push = (id, entry, env) => {
raw.push({
id,
displayName: (entry && entry.displayName) || defaultName(id),
apiKeyEnv: env,
family: familyOf(id, entry),
})
}
const pi = settingsSvc ? settingsSvc.get('llm-pi-ai') : undefined
const providers = pi && pi.providers
if (providers && typeof providers === 'object') {
for (const id of Object.keys(providers)) {
const entry = providers[id]
if (!isFamily(id, entry)) continue
const env = entry && entry.apiKeyEnv
if (typeof env !== 'string' || env === '') continue
push(id, entry, env)
}
}
if (raw.length === 0) {
for (const env of FALLBACK_ENVS) {
push(env.toLowerCase().replace(/_/g, '-').replace('-api-key', ''), undefined, env)
}
}
const grouped = new Map()
const targets = []
for (const t of raw) {
let keyValue = null
if (credentialsSvc && t.apiKeyEnv) {
try {
const cred = await credentialsSvc.resolve(t.apiKeyEnv)
if (cred && cred.value) keyValue = cred.value
} catch (e) { /* unconfigured → null */ }
}
let bucket = keyValue === null ? null : grouped.get(keyValue)
if (keyValue !== null && !bucket) {
bucket = {
keyValue,
usage: null,
usageError: undefined,
modelsByFamily: new Map(),
famErrors: new Map(),
}
grouped.set(keyValue, bucket)
}
targets.push({
id: t.id,
displayName: t.displayName,
apiKeyEnv: t.apiKeyEnv,
family: t.family,
keyValue,
bucket,
})
}
return targets
}
async function refresh() {
if (polling) return
polling = true
try {
const targets = await collectTargets()
const buckets = new Set()
for (const t of targets) if (t.bucket) buckets.add(t.bucket)
const usageTasks = []
for (const b of buckets) {
usageTasks.push((async () => {
const data = await fetchJson(USAGE_URL, b.keyValue, (e) => { b.usageError = e })
if (data && data.usage) {
b.usage = {
rolling: data.usage.rolling || null,
weekly: data.usage.weekly || null,
monthly: data.usage.monthly || null,
}
}
})())
}
const seenFam = new Set()
const modelTasks = []
for (const t of targets) {
if (!t.keyValue || !t.bucket) continue
const famKey = t.family + '|' + t.keyValue
if (seenFam.has(famKey)) continue
seenFam.add(famKey)
const b = t.bucket
const fam = t.family
modelTasks.push((async () => {
const url = fam === 'zen' ? MODELS_ZEN : MODELS_GO
const data = await fetchJson(url, b.keyValue, (e) => { b.famErrors.set(fam, e) })
if (data && Array.isArray(data.data)) {
const ids = data.data.map((m) => (m && m.id) ? String(m.id) : '').filter(Boolean)
b.modelsByFamily.set(fam, ids)
b.famErrors.delete(fam)
}
})())
}
await Promise.all(usageTasks.concat(modelTasks))
const providers = targets.map((t) => {
const b = t.bucket
return {
id: t.id,
displayName: t.displayName,
family: t.family,
apiKeyEnv: t.apiKeyEnv || null,
keyConfigured: t.keyValue !== null,
usage: b ? b.usage : null,
usageError: b ? b.usageError : undefined,
models: b ? (b.modelsByFamily.get(t.family) || []) : [],
modelsError: b ? b.famErrors.get(t.family) : undefined,
}
})
let active = null
if (agentDefault) {
try {
const sel = agentDefault.currentSelection()
if (sel) active = { provider: sel.provider, model: sel.model }
} catch (e) { /* ignore */ }
}
snapshot = { active, providers, fetchedAt: Date.now() }
} finally {
polling = false
}
}
refresh()
ctx.interval(() => { refresh() }, 30000)
ctx.on('credentials/updated', () => { refresh() })
ctx.on('settings/updated', (ns) => { if (ns === 'llm-pi-ai') refresh() })
harness.handle('ocu/state', async (args) => {
if (args && args.refresh === true) await refresh()
return sanitize(snapshot)
})
},
}