picocode-core 0.9.208 → 0.9.209

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "picocode-core",
3
- "version": "0.9.208",
3
+ "version": "0.9.209",
4
4
  "description": "The agent runtime behind pico: sessions, tools, subagents, MCP, memory, and model access",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/agent.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { modelRequest } from './model-auth.js'
1
2
  import { prepareImages } from './images.js'
2
3
  import { execFile } from 'node:child_process'
3
4
  import { promisify } from 'node:util'
@@ -61,10 +62,8 @@ export function compactionHistory(history, prompt) {
61
62
  export async function compactHistory({ history, modelName, speed, auth, prompt, signal, onStream }) {
62
63
  const out = await compose(
63
64
  model({
64
- model: modelName,
65
+ ...modelRequest(modelName, auth),
65
66
  ...(speed && { speed }),
66
- ...(auth?.apiKey && { apiKey: auth.apiKey }),
67
- ...(auth?.headers && { headers: auth.headers }),
68
67
  }),
69
68
  )({
70
69
  history: await compactionHistory(history, prompt),
@@ -90,10 +89,8 @@ export function compactProgress(streamed) {
90
89
  export async function summarizeText({ text, modelName, auth }) {
91
90
  const out = await compose(
92
91
  model({
93
- model: modelName,
92
+ ...modelRequest(modelName, auth),
94
93
  system: 'Summarize the following conversation excerpt in 2-4 dense sentences. Capture decisions, changes made, and open questions. Output only the summary.',
95
- ...(auth?.apiKey && { apiKey: auth.apiKey }),
96
- ...(auth?.headers && { headers: auth.headers }),
97
94
  }),
98
95
  )(text.slice(0, 30000))
99
96
  return getText(out.lastResponse?.content || '').trim()
@@ -190,7 +187,7 @@ export async function runTurn({ history, tools, recorder, modelName, effort, spe
190
187
  estimatedPromptTokens = estimateTokens({ system, history: hydratedHistory, tools })
191
188
  onStream?.({ type: 'usage_estimate', usage: estimatedUsage() })
192
189
  const out = await model({
193
- model: modelName,
190
+ ...modelRequest(modelName, auth),
194
191
  beforeRequest: async (request) => {
195
192
  if (internal.signal.aborted) return request
196
193
  const messages = await beforeRequest?.() || []
@@ -203,8 +200,6 @@ export async function runTurn({ history, tools, recorder, modelName, effort, spe
203
200
  },
204
201
  ...(effort && { effort }),
205
202
  ...(speed && { speed }),
206
- ...(auth?.apiKey && { apiKey: auth.apiKey }),
207
- ...(auth?.headers && { headers: auth.headers }),
208
203
  })({ ...ctx, history: hydratedHistory, abortSignal: internal.signal })
209
204
  // Prepared bytes and omission notices belong only to the request, not
210
205
  // the conversation returned by the provider or subsequent tool rounds.
package/src/controller.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { modelCredentials, subscriptionProvider } from './model-auth.js'
2
+ import { connectXAI, disconnectXAI } from './xai-auth.js'
3
+ import { loadXAIModels } from './xai-models.js'
1
4
  import { existsSync } from 'node:fs'
2
5
  import { writeFile } from 'node:fs/promises'
3
6
  import { join } from 'node:path'
@@ -331,10 +334,10 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
331
334
  changed()
332
335
  }
333
336
 
334
- async function codexAuth() {
335
- if (state.model.provider !== 'codex') return { auth: null, ok: true }
336
- const auth = await openaiCredentials().catch(() => null)
337
- if (!auth) flash('error: codex models need a ChatGPT sign-in')
337
+ async function subscriptionAuth() {
338
+ if (!subscriptionProvider(state.model.provider)) return { auth: null, ok: true }
339
+ const auth = await modelCredentials(state.model).catch(() => null)
340
+ if (!auth) flash('error: subscription models need a sign-in (/connect)')
338
341
  return { auth, ok: !!auth }
339
342
  }
340
343
 
@@ -355,7 +358,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
355
358
  run: async (agent, signal, onStream) => {
356
359
  const worker = boot.models.find((m) => m.name === agent.model)
357
360
  if (!worker || worker.available === false) throw new Error(`research model unavailable: ${agent.model}`)
358
- const auth = worker.provider === 'codex' ? await openaiCredentials() : null
361
+ const auth = await modelCredentials(worker)
359
362
  const sessionId = state.session?.id
360
363
  if (!sessionId) throw new Error('worker requires an active session')
361
364
  const scratchpad = ensureDir(agentScratchDir(boot.root, sessionId, agent.id))
@@ -404,7 +407,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
404
407
  const found = boot.models.find((m) => m.name === name)
405
408
  if (!found || found.available === false) throw new Error(`deliberation model unavailable: ${name}`)
406
409
  roleWorkers[part] = found
407
- roleAuths[part] = found.provider === 'codex' ? await openaiCredentials() : null
410
+ roleAuths[part] = await modelCredentials(found)
408
411
  }
409
412
  const sessionId = state.session?.id
410
413
  if (!sessionId) throw new Error('deliberation requires an active session')
@@ -636,7 +639,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
636
639
  abort = controller
637
640
  set({ busy: true, compacting: true, compactStatus: null, compactOutcome: null, startedAt: Date.now() })
638
641
 
639
- const { auth, ok } = await codexAuth()
642
+ const { auth, ok } = await subscriptionAuth()
640
643
  if (!ok) {
641
644
  abort = null
642
645
  set({ compacting: false, busy: false })
@@ -827,7 +830,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
827
830
  emit('turn', 'start')
828
831
  set({ busy: true, turnPhase: 'responding', startedAt: Date.now(), liveUsage: null })
829
832
 
830
- const { auth, ok } = await codexAuth()
833
+ const { auth, ok } = await subscriptionAuth()
831
834
  if (!ok) {
832
835
  set({ turnPhase: 'idle', busy: false, peerPaused: true })
833
836
  flushSystemNotes()
@@ -1552,7 +1555,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1552
1555
  const tail = current.transcript.slice(target.index)
1553
1556
  const text = tail.filter((m) => m.text).map((m) => `${m.kind}: ${m.text}`).join('\n')
1554
1557
  flash('summarizing...')
1555
- const { auth } = await codexAuth()
1558
+ const { auth } = await subscriptionAuth()
1556
1559
  summaryText = await summarizeText({ text, modelName: state.model.name, auth }).catch(() => {
1557
1560
  flash('summary model call failed · kept a crude digest of the rewound turns')
1558
1561
  return tail.filter((m) => m.text).slice(0, 3).map((m) => m.text.split(/\s+/).slice(0, 6).join(' ')).join(' · ')
@@ -1691,8 +1694,11 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1691
1694
  return { model: state.model.name, limit, rows, measured, segments }
1692
1695
  }
1693
1696
 
1694
- async function connectProvider() {
1695
- const { email } = await connectOpenAI()
1697
+ async function connectProvider(provider = 'openai', options = {}) {
1698
+ if (provider !== 'openai' && provider !== 'xai') throw new Error(`unknown subscription provider: ${provider}`)
1699
+ const grok = provider === 'xai'
1700
+ const { email } = grok ? await connectXAI(options) : await connectOpenAI()
1701
+ if (grok) return { email, ...await refreshXAIConnection() }
1696
1702
  boot.providers = [...new Set([...boot.providers, 'codex'])]
1697
1703
  const creds = await openaiCredentials().catch(() => null)
1698
1704
  const codex = (await loadCodexModels(creds)).map((m) => ({ ...m, available: true, keyHint: '/connect' }))
@@ -1701,7 +1707,26 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1701
1707
  return { email, count: codex.length }
1702
1708
  }
1703
1709
 
1704
- async function disconnectProvider() {
1710
+ async function refreshXAIConnection() {
1711
+ const credentials = await modelCredentials({ provider: 'grok' })
1712
+ if (!credentials) throw new Error('SuperGrok sign-in required')
1713
+ const models = await loadXAIModels(credentials, { force: true })
1714
+ boot.providers = [...new Set([...boot.providers, 'grok'])]
1715
+ boot.models = [...boot.models.filter((m) => m.provider !== 'grok'), ...models.map((m) => ({ ...m, available: true, keyHint: '/connect' }))]
1716
+ reDerive()
1717
+ return { count: models.length }
1718
+ }
1719
+
1720
+ async function disconnectProvider(provider = 'openai') {
1721
+ if (provider !== 'openai' && provider !== 'xai') throw new Error(`unknown subscription provider: ${provider}`)
1722
+ if (provider === 'xai') {
1723
+ await disconnectXAI()
1724
+ boot.providers = boot.providers.filter((p) => p !== 'grok')
1725
+ boot.models = boot.models.map((m) => m.provider === 'grok' ? { ...m, available: false } : m)
1726
+ if (state.model.provider === 'grok') state.model = boot.models.find((m) => m.available !== false && m.name === state.defaultModel.name) || boot.models.find((m) => m.available !== false) || state.defaultModel
1727
+ changed()
1728
+ return
1729
+ }
1705
1730
  await disconnectOpenAI().catch(() => {})
1706
1731
  boot.providers = boot.providers.filter((p) => p !== 'codex')
1707
1732
  boot.models = boot.models.map((m) => (m.provider === 'codex' ? { ...m, available: false } : m))
@@ -1849,6 +1874,9 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1849
1874
  contextBreakdown,
1850
1875
  connectProvider,
1851
1876
  disconnectProvider,
1877
+ refreshXAIConnection,
1878
+ connectXAI: (options) => connectProvider('xai', options),
1879
+ disconnectXAI: () => disconnectProvider('xai'),
1852
1880
  activity,
1853
1881
  cancelAgent,
1854
1882
  dismissAgent,
@@ -0,0 +1,32 @@
1
+ import { openaiCredentials } from './openai-auth.js'
2
+ import { xaiCredentials } from './xai-auth.js'
3
+ import { XAI_SUBSCRIPTION_URL } from './xai-models.js'
4
+
5
+ export function subscriptionProvider(provider) {
6
+ return provider === 'codex' || provider === 'grok'
7
+ }
8
+
9
+ export async function modelCredentials(model) {
10
+ if (model.provider === 'codex') return openaiCredentials()
11
+ if (model.provider === 'grok') return xaiCredentials()
12
+ return null
13
+ }
14
+
15
+ export function modelRequest(modelName, auth) {
16
+ if (!modelName.startsWith('grok/')) {
17
+ return {
18
+ model: modelName,
19
+ ...(auth?.apiKey && { apiKey: auth.apiKey }),
20
+ ...(auth?.headers && { headers: auth.headers }),
21
+ }
22
+ }
23
+ const token = auth?.accessToken
24
+ if (!token) throw new Error('Grok subscription models need a SuperGrok sign-in (/connect)')
25
+ // The Codex adapter implements the subscription Responses wire protocol.
26
+ return {
27
+ model: `codex/${modelName.slice('grok/'.length)}`,
28
+ baseUrl: XAI_SUBSCRIPTION_URL,
29
+ apiKey: token,
30
+ headers: { originator: 'pico', 'OpenAI-Beta': '', 'x-grok-client-mode': 'cli', 'x-grok-client-version': '1.0.13' },
31
+ }
32
+ }
@@ -1,3 +1,4 @@
1
+ import { connectXAI } from './xai-auth.js'
1
2
  import { applyPatches } from './daemon-patch.js'
2
3
 
3
4
  export async function createRemoteController(connection, { id, options = {}, localBoot = {} } = {}) {
@@ -89,6 +90,10 @@ export async function createRemoteController(connection, { id, options = {}, loc
89
90
  emit('session', state.session)
90
91
  emit('change', state)
91
92
  }
93
+ controller.connectXAI = async options => {
94
+ const { email } = await connectXAI(options)
95
+ return { email, ...await call('controller', 'refreshXAIConnection') }
96
+ }
92
97
  controller.previewSteer = changes => call('controller', 'previewSteer', changes)
93
98
  controller.loadHistory = async limit => {
94
99
  const target = displayedId()
@@ -0,0 +1,228 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { mkdir, open, readFile, rename, rm } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import lockfile from 'proper-lockfile'
6
+ import { setTimeout as sleep } from 'node:timers/promises'
7
+ import { picoHome } from './paths.js'
8
+
9
+ // Shared public client verified in OpenClaw extensions/xai/xai-oauth.ts and
10
+ // Hermes hermes_cli/auth_constants.py. xAI may display Grok Build at consent.
11
+ const CLIENT_ID = 'b1a00492-073a-47ea-816f-4c329264a828'
12
+ const DISCOVERY = 'https://auth.x.ai/.well-known/openid-configuration'
13
+ const SCOPE = 'openid profile email offline_access grok-cli:access api:access'
14
+
15
+ function trustedEndpoint(value) {
16
+ const url = new URL(value)
17
+ if (url.protocol !== 'https:' || url.username || url.password || url.port ||
18
+ !(url.hostname === 'x.ai' || url.hostname.endsWith('.x.ai'))) {
19
+ throw new Error('Untrusted xAI OAuth endpoint')
20
+ }
21
+ return url.href
22
+ }
23
+
24
+ async function locked(task) {
25
+ const home = picoHome()
26
+ await mkdir(home, { recursive: true })
27
+ const file = join(home, 'xai-auth.json')
28
+ let compromised
29
+ const release = await lockfile.lock(file, {
30
+ realpath: false,
31
+ stale: 30000,
32
+ update: 10000,
33
+ retries: { retries: 3600, minTimeout: 100, maxTimeout: 100 },
34
+ onCompromised: error => { compromised = error },
35
+ })
36
+ const assertLock = () => { if (compromised) throw compromised }
37
+ try {
38
+ return await task(file, assertLock)
39
+ } finally {
40
+ if (!compromised) await release()
41
+ }
42
+ }
43
+
44
+ async function readAuth(file) {
45
+ try {
46
+ const value = JSON.parse(await readFile(file, 'utf8'))
47
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid xAI auth file')
48
+ return value
49
+ } catch (error) {
50
+ if (error.code === 'ENOENT') return {}
51
+ throw error
52
+ }
53
+ }
54
+
55
+ async function writeAuth(file, auth, assertLock) {
56
+ const temporary = `${file}.${randomUUID()}.tmp`
57
+ try {
58
+ const handle = await open(temporary, 'wx', 0o600)
59
+ try {
60
+ await handle.writeFile(JSON.stringify(auth, null, 2) + '\n')
61
+ await handle.sync()
62
+ } finally {
63
+ await handle.close()
64
+ }
65
+ assertLock()
66
+ await rename(temporary, file)
67
+ } finally {
68
+ await rm(temporary, { force: true })
69
+ }
70
+ }
71
+
72
+ async function request(url, params, signal = AbortSignal.timeout(30000)) {
73
+ const response = await fetch(trustedEndpoint(url), {
74
+ method: params ? 'POST' : 'GET',
75
+ redirect: 'error',
76
+ signal,
77
+ headers: { Accept: 'application/json', ...(params ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}) },
78
+ ...(params ? { body: new URLSearchParams(params).toString() } : {}),
79
+ })
80
+ let data
81
+ try { data = await response.json() } catch { throw new Error(`xAI returned invalid JSON (${response.status})`) }
82
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid xAI response')
83
+ if (!response.ok || data.error) {
84
+ const error = new Error(`xAI OAuth failed (${response.status}): ${typeof data.error === 'string' ? data.error : 'request rejected'}`)
85
+ error.oauthCode = data.error
86
+ throw error
87
+ }
88
+ return data
89
+ }
90
+
91
+ function claims(token) {
92
+ try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()) } catch { return {} }
93
+ }
94
+
95
+ function tokensInto(auth, tokens, endpoint, requireRefresh = false) {
96
+ if (typeof tokens.access_token !== 'string' || !tokens.access_token.trim()) throw new Error('xAI response missing access_token')
97
+ if (requireRefresh && (typeof tokens.refresh_token !== 'string' || !tokens.refresh_token.trim())) throw new Error('xAI response missing refresh_token')
98
+ const previous = auth.xai || {}
99
+ const expires = Number(tokens.expires_in)
100
+ const jwtExpiry = Number(claims(tokens.access_token).exp) * 1000
101
+ const expiresAt = Number.isFinite(expires) && expires > 0 ? Date.now() + expires * 1000 : jwtExpiry
102
+ if (!Number.isFinite(expiresAt) || expiresAt <= 0) throw new Error('xAI response missing access token expiry')
103
+ const identity = claims(tokens.id_token || tokens.access_token)
104
+ auth.xai = {
105
+ access_token: tokens.access_token,
106
+ refresh_token: typeof tokens.refresh_token === 'string' && tokens.refresh_token.trim() ? tokens.refresh_token : previous.refresh_token,
107
+ email: typeof identity.email === 'string' ? identity.email : previous.email || null,
108
+ expires_at: expiresAt,
109
+ token_endpoint: endpoint,
110
+ }
111
+ return auth
112
+ }
113
+
114
+ function openInBrowser(url) {
115
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer.exe' : 'xdg-open'
116
+ execFile(command, [url], () => {})
117
+ }
118
+
119
+ export async function connectXAI({ onUrl = () => {}, openBrowser = true, timeoutMs = 300000 } = {}) {
120
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('Invalid xAI sign-in timeout')
121
+ const deadline = Date.now() + timeoutMs
122
+ const controller = new AbortController()
123
+ const timer = setTimeout(() => controller.abort(new Error('xAI sign-in timed out')), timeoutMs)
124
+ try {
125
+ return await locked(async (file, assertLock) => {
126
+ controller.signal.throwIfAborted()
127
+ const discovery = await request(DISCOVERY, null, controller.signal)
128
+ const endpoint = trustedEndpoint(discovery.token_endpoint)
129
+ const device = await request(trustedEndpoint(discovery.device_authorization_endpoint), { client_id: CLIENT_ID, scope: SCOPE }, controller.signal)
130
+ if (!device.device_code || !device.user_code || !device.verification_uri || !(Number(device.expires_in) > 0)) throw new Error('Invalid xAI device code response')
131
+ const url = trustedEndpoint(device.verification_uri_complete || device.verification_uri)
132
+ await onUrl(url, device.user_code)
133
+ if (openBrowser) openInBrowser(url)
134
+ const expiresAt = Math.min(deadline, Date.now() + Number(device.expires_in) * 1000)
135
+ let interval = Math.max(1000, Number(device.interval) * 1000 || 5000)
136
+ while (Date.now() < expiresAt) {
137
+ await sleep(Math.min(interval, expiresAt - Date.now()), undefined, { signal: controller.signal })
138
+ if (Date.now() >= expiresAt) break
139
+ assertLock()
140
+ try {
141
+ const tokens = await request(endpoint, {
142
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code', client_id: CLIENT_ID, device_code: device.device_code,
143
+ }, AbortSignal.any([controller.signal, AbortSignal.timeout(Math.max(1, expiresAt - Date.now()))]))
144
+ controller.signal.throwIfAborted()
145
+ const auth = tokensInto(await readAuth(file), tokens, endpoint, true)
146
+ await writeAuth(file, auth, assertLock)
147
+ return { email: auth.xai.email }
148
+ } catch (error) {
149
+ if (error.oauthCode === 'slow_down') interval += 5000
150
+ else if (error.oauthCode !== 'authorization_pending') throw error
151
+ }
152
+ }
153
+ throw new Error('xAI device code expired')
154
+ })
155
+ } finally {
156
+ clearTimeout(timer)
157
+ }
158
+ }
159
+
160
+ export async function xaiConnected() {
161
+ return locked(async file => {
162
+ const { xai } = await readAuth(file)
163
+ return { connected: !!(xai?.access_token && (xai.refresh_token || xai.expires_at > Date.now())), email: xai?.email || null }
164
+ })
165
+ }
166
+
167
+ export async function xaiCredentials() {
168
+ return locked(async (file, assertLock) => {
169
+ const auth = await readAuth(file)
170
+ const stored = auth.xai
171
+ if (!stored?.access_token) return null
172
+ if (!(stored.expires_at > Date.now() + 120000)) {
173
+ if (!stored.refresh_token) return null
174
+ const endpoint = stored.token_endpoint && stored.token_endpoint !== 'https://auth.x.ai/oauth/token'
175
+ ? trustedEndpoint(stored.token_endpoint)
176
+ : trustedEndpoint((await request(DISCOVERY)).token_endpoint)
177
+ const tokens = await request(endpoint, { grant_type: 'refresh_token', client_id: CLIENT_ID, refresh_token: stored.refresh_token })
178
+ tokensInto(auth, tokens, endpoint)
179
+ await writeAuth(file, auth, assertLock)
180
+ }
181
+ return { accessToken: auth.xai.access_token }
182
+ })
183
+ }
184
+
185
+ export async function disconnectXAI() {
186
+ return locked(async (file, assertLock) => {
187
+ const auth = await readAuth(file)
188
+ delete auth.xai
189
+ await writeAuth(file, auth, assertLock)
190
+ })
191
+ }
192
+
193
+ // Billing protocol: OpenClaw extensions/xai/usage.ts. Included subscription
194
+ // quota is separate from on-demand spending and prepaid balance.
195
+ export async function xaiUsage() {
196
+ const credentials = await xaiCredentials()
197
+ if (!credentials) return null
198
+ const response = await fetch('https://cli-chat-proxy.grok.com/v1/billing?format=credits', {
199
+ redirect: 'error', signal: AbortSignal.timeout(30000),
200
+ headers: { Authorization: `Bearer ${credentials.accessToken}`, Accept: 'application/json', 'x-grok-client-mode': 'cli', 'x-grok-client-version': '1.0.13' },
201
+ })
202
+ if (!response.ok) throw new Error(`xAI usage request failed (${response.status})`)
203
+ const data = await response.json()
204
+ const config = data?.config
205
+ if (!config || typeof config !== 'object') throw new Error('Malformed xAI billing response')
206
+ const cents = value => {
207
+ const raw = value?.val
208
+ if (raw === undefined || raw === null) return null
209
+ if (!(typeof raw === 'number' || typeof raw === 'string' && /^\d+$/.test(raw))) return null
210
+ const number = Number(raw)
211
+ return Number.isSafeInteger(number) && number >= 0 ? number : null
212
+ }
213
+ const used = cents(config.used)
214
+ const limit = cents(config.monthlyLimit ?? config.monthly_limit)
215
+ const explicit = config.creditUsagePercent ?? config.credit_usage_percent
216
+ const percent = typeof explicit === 'number' && Number.isFinite(explicit) && explicit >= 0
217
+ ? explicit : used !== null && limit > 0 ? used / limit * 100 : null
218
+ const period = config.currentPeriod ?? config.current_period
219
+ const end = period?.end ?? config.billingPeriodEnd ?? config.billing_period_end
220
+ const reset = typeof end === 'string' ? Date.parse(end) : NaN
221
+ return {
222
+ plan: data.subscription_tier ?? data.subscriptionTier ?? 'SuperGrok',
223
+ windows: percent === null ? [] : [{
224
+ label: period?.type?.endsWith('WEEKLY') ? 'Weekly' : period?.type?.endsWith('MONTHLY') || limit !== null ? 'Monthly' : 'Usage',
225
+ usedPercent: Math.min(100, percent), resetAt: Number.isFinite(reset) ? reset : null,
226
+ }],
227
+ }
228
+ }
@@ -0,0 +1,47 @@
1
+ import { readFile, writeFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { picoHome, ensureDir } from './paths.js'
4
+
5
+ export const XAI_SUBSCRIPTION_URL = 'https://cli-chat-proxy.grok.com/v1'
6
+ const TTL = 24 * 60 * 60 * 1000
7
+
8
+ export function mapXAIModels(entries) {
9
+ return entries.filter(m => typeof m.id === 'string' && m.id.startsWith('grok-') && !/image|video|audio|voice/.test(m.id)).map(m => ({
10
+ name: `grok/${m.id}`,
11
+ provider: 'grok',
12
+ desc: m.description || m.display_name || m.id,
13
+ price: null,
14
+ effort: false,
15
+ context: m.context_window || m.max_context_window || null,
16
+ }))
17
+ }
18
+
19
+ export async function loadXAIModels(credentials, { force = false, fetcher = fetch } = {}) {
20
+ const file = join(picoHome(), 'xai-models-cache.json')
21
+ let cached = null
22
+ try {
23
+ cached = JSON.parse(await readFile(file, 'utf-8'))
24
+ if (!Array.isArray(cached.models)) cached = null
25
+ } catch {}
26
+ if (!credentials?.accessToken || (!force && cached && Date.now() - cached.at < TTL)) return mapXAIModels(cached?.models || [])
27
+ const headers = { Authorization: `Bearer ${credentials.accessToken}` }
28
+ let models
29
+ try {
30
+ const response = await fetcher(`${XAI_SUBSCRIPTION_URL}/models`, {
31
+ headers, redirect: 'error', signal: AbortSignal.timeout(15000),
32
+ })
33
+ if (!response.ok) throw new Error(`Grok subscription model discovery failed (${response.status})`)
34
+ const data = await response.json()
35
+ if (!Array.isArray(data.data)) throw new Error('invalid subscription model list')
36
+ models = [...new Map(data.data.filter(m => typeof m?.id === 'string').map(m => [m.id, m])).values()]
37
+ } catch (error) {
38
+ if (cached) return mapXAIModels(cached.models)
39
+ throw error
40
+ }
41
+ if (!mapXAIModels(models).length) return mapXAIModels(cached?.models || [])
42
+ try {
43
+ ensureDir(picoHome())
44
+ await writeFile(file, JSON.stringify({ at: Date.now(), models }))
45
+ } catch {}
46
+ return mapXAIModels(models)
47
+ }