picocode-core 0.9.207 → 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/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'
@@ -10,7 +13,7 @@ import { deriveState, userEntries, rewindStats } from './derive.js'
10
13
  import { appendPrompt } from './history.js'
11
14
  import { runTurn, summarizeText, compactHistory, compactProgress } from './agent.js'
12
15
  import { createAgentManager } from './agents.js'
13
- import { createPeers } from './peers.js'
16
+ import { automaticPeerName, createPeers } from './peers.js'
14
17
  import { runDeliberation, validateDeliberation } from './deliberation.js'
15
18
  import { deliberationsFromEvents } from './deliberation-history.js'
16
19
  import { compactionPrompt, formatCompactSummary, summarySections, compactionKeepFrom } from './compaction.js'
@@ -265,10 +268,25 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
265
268
  set({ peerConnection: null, peerError: null })
266
269
  }
267
270
 
271
+ // every saved session is reachable by peers: under the name the user gave
272
+ // it, or else an automatic one from its folder and id
273
+ async function connectAutomatic() {
274
+ const id = state.session.id
275
+ for (let length = 2; ; length++) {
276
+ try {
277
+ return await peers.connect({ id, name: automaticPeerName(boot.root, id, length), cwd: boot.cwd })
278
+ } catch (error) {
279
+ if (error.code !== 'PEER_NAME_TAKEN' || length >= 32) throw error
280
+ }
281
+ }
282
+ }
283
+
268
284
  async function reconnectPeers() {
269
- if (!state.derived.title || !state.session) return
285
+ if (!state.session || boot.ephemeral) return
270
286
  try {
271
- const identity = await peers.connect({ id: state.session.id, name: state.derived.title, cwd: boot.cwd })
287
+ const identity = state.derived.title
288
+ ? await peers.connect({ id: state.session.id, name: state.derived.title, cwd: boot.cwd })
289
+ : await connectAutomatic()
272
290
  set({ peerConnection: identity, peerError: null })
273
291
  } catch (error) {
274
292
  set({ peerConnection: null, peerError: error.message })
@@ -299,6 +317,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
299
317
  // the file exists from this moment; anyone tracking open sessions
300
318
  // by file needs to hear about it
301
319
  emit('session', state.session)
320
+ if (!boot.ephemeral) reconnectPeers()
302
321
  }
303
322
  if (!state.events.some(event => event.type === 'speed')) {
304
323
  state.events.push(makeEvent('speed', { to: state.speed }))
@@ -315,10 +334,10 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
315
334
  changed()
316
335
  }
317
336
 
318
- async function codexAuth() {
319
- if (state.model.provider !== 'codex') return { auth: null, ok: true }
320
- const auth = await openaiCredentials().catch(() => null)
321
- 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)')
322
341
  return { auth, ok: !!auth }
323
342
  }
324
343
 
@@ -339,7 +358,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
339
358
  run: async (agent, signal, onStream) => {
340
359
  const worker = boot.models.find((m) => m.name === agent.model)
341
360
  if (!worker || worker.available === false) throw new Error(`research model unavailable: ${agent.model}`)
342
- const auth = worker.provider === 'codex' ? await openaiCredentials() : null
361
+ const auth = await modelCredentials(worker)
343
362
  const sessionId = state.session?.id
344
363
  if (!sessionId) throw new Error('worker requires an active session')
345
364
  const scratchpad = ensureDir(agentScratchDir(boot.root, sessionId, agent.id))
@@ -388,7 +407,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
388
407
  const found = boot.models.find((m) => m.name === name)
389
408
  if (!found || found.available === false) throw new Error(`deliberation model unavailable: ${name}`)
390
409
  roleWorkers[part] = found
391
- roleAuths[part] = found.provider === 'codex' ? await openaiCredentials() : null
410
+ roleAuths[part] = await modelCredentials(found)
392
411
  }
393
412
  const sessionId = state.session?.id
394
413
  if (!sessionId) throw new Error('deliberation requires an active session')
@@ -620,7 +639,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
620
639
  abort = controller
621
640
  set({ busy: true, compacting: true, compactStatus: null, compactOutcome: null, startedAt: Date.now() })
622
641
 
623
- const { auth, ok } = await codexAuth()
642
+ const { auth, ok } = await subscriptionAuth()
624
643
  if (!ok) {
625
644
  abort = null
626
645
  set({ compacting: false, busy: false })
@@ -811,7 +830,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
811
830
  emit('turn', 'start')
812
831
  set({ busy: true, turnPhase: 'responding', startedAt: Date.now(), liveUsage: null })
813
832
 
814
- const { auth, ok } = await codexAuth()
833
+ const { auth, ok } = await subscriptionAuth()
815
834
  if (!ok) {
816
835
  set({ turnPhase: 'idle', busy: false, peerPaused: true })
817
836
  flushSystemNotes()
@@ -1049,6 +1068,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1049
1068
  agents.restore(forked.events)
1050
1069
  reDerive()
1051
1070
  emit('session', state.session)
1071
+ await reconnectPeers()
1052
1072
  flash('session forked')
1053
1073
  }
1054
1074
 
@@ -1064,10 +1084,10 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1064
1084
  await state.session.append(event, { strict: true })
1065
1085
  state.events.push(event)
1066
1086
  state.persisted = state.events.length
1067
- if (!name) await disconnectPeers()
1087
+ if (!name && !boot.ephemeral) await connectAutomatic()
1068
1088
  set({ peerConnection: peers.identity, peerError: null })
1069
1089
  reDerive()
1070
- flash(name ? `session renamed to "${name}"` : 'session name reset')
1090
+ flash(name ? `session renamed to "${name}"` : `session name reset to "${peers.identity?.name}"`)
1071
1091
  return true
1072
1092
  } catch (error) {
1073
1093
  try {
@@ -1535,7 +1555,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1535
1555
  const tail = current.transcript.slice(target.index)
1536
1556
  const text = tail.filter((m) => m.text).map((m) => `${m.kind}: ${m.text}`).join('\n')
1537
1557
  flash('summarizing...')
1538
- const { auth } = await codexAuth()
1558
+ const { auth } = await subscriptionAuth()
1539
1559
  summaryText = await summarizeText({ text, modelName: state.model.name, auth }).catch(() => {
1540
1560
  flash('summary model call failed · kept a crude digest of the rewound turns')
1541
1561
  return tail.filter((m) => m.text).slice(0, 3).map((m) => m.text.split(/\s+/).slice(0, 6).join(' ')).join(' · ')
@@ -1674,8 +1694,11 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1674
1694
  return { model: state.model.name, limit, rows, measured, segments }
1675
1695
  }
1676
1696
 
1677
- async function connectProvider() {
1678
- 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() }
1679
1702
  boot.providers = [...new Set([...boot.providers, 'codex'])]
1680
1703
  const creds = await openaiCredentials().catch(() => null)
1681
1704
  const codex = (await loadCodexModels(creds)).map((m) => ({ ...m, available: true, keyHint: '/connect' }))
@@ -1684,7 +1707,26 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1684
1707
  return { email, count: codex.length }
1685
1708
  }
1686
1709
 
1687
- 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
+ }
1688
1730
  await disconnectOpenAI().catch(() => {})
1689
1731
  boot.providers = boot.providers.filter((p) => p !== 'codex')
1690
1732
  boot.models = boot.models.map((m) => (m.provider === 'codex' ? { ...m, available: false } : m))
@@ -1760,7 +1802,10 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1760
1802
  return {
1761
1803
  state,
1762
1804
  boot,
1805
+ // what peers call this session: the user's name for it, or the automatic one
1806
+ sessionName: () => state.derived.title || state.peerConnection?.name || null,
1763
1807
  isWorking: () => state.busy || preparingTurn,
1808
+ ensureSession,
1764
1809
  on,
1765
1810
  agents,
1766
1811
  send,
@@ -1829,6 +1874,9 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1829
1874
  contextBreakdown,
1830
1875
  connectProvider,
1831
1876
  disconnectProvider,
1877
+ refreshXAIConnection,
1878
+ connectXAI: (options) => connectProvider('xai', options),
1879
+ disconnectXAI: () => disconnectProvider('xai'),
1832
1880
  activity,
1833
1881
  cancelAgent,
1834
1882
  dismissAgent,
package/src/derive.js CHANGED
@@ -216,10 +216,13 @@ export function deriveState(events) {
216
216
  }
217
217
 
218
218
  const references = toolResultArchive(events).references
219
- const historyTokens = () => Math.ceil(JSON.stringify(applyToolTrims(
220
- elideStaleToolResults(state.providerHistory), state.trimmedToolIds,
221
- state.toolTrimVersions, state.toolItems, references,
219
+ const historyTokens = (history = state.providerHistory, trimmed = state.trimmedToolIds, versions = state.toolTrimVersions) => Math.ceil(JSON.stringify(applyToolTrims(
220
+ elideStaleToolResults(history), trimmed, versions, state.toolItems, references,
222
221
  )).length / 4)
222
+ // where the history stood at the last measured request; its size is only
223
+ // computed when a later trim makes the estimate need it, so deriving a
224
+ // long session stays linear in its events
225
+ const historyMark = () => ({ history: state.providerHistory, length: state.providerHistory.length, trimmed: new Set(state.trimmedToolIds), versions: new Map(state.toolTrimVersions) })
223
226
  let measuredBaseline = null
224
227
  let contextEdited = false
225
228
 
@@ -234,7 +237,7 @@ export function deriveState(events) {
234
237
  if (event.data.lastPrompt !== undefined) {
235
238
  state.lastPromptTokens = event.data.lastPrompt
236
239
  state.lastPromptModel = event.data.model
237
- measuredBaseline = { tokens: event.data.lastPrompt, history: historyTokens() }
240
+ measuredBaseline = { tokens: event.data.lastPrompt, mark: historyMark() }
238
241
  contextEdited = false
239
242
  }
240
243
  }
@@ -412,7 +415,7 @@ export function deriveState(events) {
412
415
  const unreadItems = new Set(unread)
413
416
  state.transcript = [...state.transcript.filter(item => !unreadItems.has(item)), ...unread]
414
417
  state.estimatedPromptTokens = contextEdited && measuredBaseline
415
- ? Math.max(0, measuredBaseline.tokens + historyTokens() - measuredBaseline.history)
418
+ ? Math.max(0, measuredBaseline.tokens + historyTokens() - historyTokens(measuredBaseline.mark.history.slice(0, measuredBaseline.mark.length), measuredBaseline.mark.trimmed, measuredBaseline.mark.versions))
416
419
  : null
417
420
  const effectiveHistory = elideStaleToolResults(state.providerHistory)
418
421
  state.providerHistory = applyToolTrims(effectiveHistory, state.trimmedToolIds, state.toolTrimVersions, state.toolItems, toolResultArchive(events).references)
@@ -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
+ }
package/src/peers.js CHANGED
@@ -68,6 +68,14 @@ function exchange(path, request) {
68
68
  })
69
69
  }
70
70
 
71
+ // the name a session goes by until someone names it: its folder and the
72
+ // start of its id, like "gibs-6a", longer only when that is taken
73
+ export function automaticPeerName(root, id, length = 2) {
74
+ const folder = String(root ?? '').split(/[\\/]/).filter(Boolean).pop() ?? ''
75
+ const base = folder.toLowerCase().replace(/[^a-z0-9._]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 40) || 'session'
76
+ return `${base}-${String(id).replace(/[^0-9a-f]/gi, '').slice(0, length).toLowerCase()}`
77
+ }
78
+
71
79
  export function createPeers({ directory = defaultDirectory(), onMessage, onSend, onDelivery } = {}) {
72
80
  if (typeof onMessage !== 'function') throw new TypeError('onMessage must be a function')
73
81
  let identity = null
@@ -199,7 +207,7 @@ export function createPeers({ directory = defaultDirectory(), onMessage, onSend,
199
207
  try {
200
208
  await updateRegistry(records => {
201
209
  if (records.some(peer => peer.id === next.id && peer.instance !== instance)) throw fail(`session ${next.id} is already connected`)
202
- if (records.some(peer => peer.name === next.name && peer.instance !== instance)) throw fail(`peer name "${next.name}" is already connected`)
210
+ if (records.some(peer => peer.name === next.name && peer.instance !== instance)) throw fail(`peer name "${next.name}" is already connected`, 'PEER_NAME_TAKEN')
203
211
  const index = records.findIndex(peer => peer.instance === instance)
204
212
  if (index < 0) records.push(record)
205
213
  else records[index] = record
@@ -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
+ }