picocode-core 0.9.208 → 0.9.210

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.210",
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,
package/src/mcp.js CHANGED
@@ -79,8 +79,11 @@ async function readJson(file, fallback) {
79
79
  }
80
80
  }
81
81
 
82
- export function readRegistry() {
83
- return readJson(globalMcpFile(), { servers: {} })
82
+ // the global file: every project's servers, and the ones switched off
83
+ // everywhere unless a project switches them back on
84
+ export async function readRegistry() {
85
+ const registry = await readJson(globalMcpFile(), {})
86
+ return { servers: registry.servers || {}, disabled: registry.disabled || {} }
84
87
  }
85
88
 
86
89
  export async function writeRegistry(registry) {
@@ -88,6 +91,8 @@ export async function writeRegistry(registry) {
88
91
  await writeFile(globalMcpFile(), JSON.stringify(registry, null, 2) + '\n')
89
92
  }
90
93
 
94
+ // a project's file: its own servers, and a switch per server where the
95
+ // project differs from the global setting (true off, false on)
91
96
  export async function readProjectConfig(root) {
92
97
  const config = await readJson(projectMcpFile(root), {})
93
98
  return { disabled: config.disabled || {}, servers: config.servers || {} }
@@ -120,21 +125,20 @@ export async function createMcpTransport(command) {
120
125
  }
121
126
 
122
127
  export async function createMcpRuntime({ root, onChange = () => {} }) {
123
- const registry = await readRegistry()
124
- const projectConfig = await readProjectConfig(root)
128
+ let registry = await readRegistry()
129
+ let projectConfig = await readProjectConfig(root)
125
130
  const servers = new Map()
131
+ // switches for this session alone, never written anywhere
132
+ const sessionSettings = new Map()
133
+
134
+ const projectSetting = (name) => (Object.hasOwn(projectConfig.disabled, name) ? !projectConfig.disabled[name] : null)
135
+ const globalEnabled = (name) => !registry.disabled[name]
136
+ // the session's switch wins, then the project's, then the global one
137
+ const effective = (name) => sessionSettings.has(name) ? sessionSettings.get(name) : projectSetting(name) ?? globalEnabled(name)
126
138
 
127
139
  const register = (name, command, scope) => {
128
- servers.set(name, {
129
- name,
130
- command,
131
- scope,
132
- enabled: !projectConfig.disabled[name],
133
- status: projectConfig.disabled[name] ? 'disabled' : 'idle',
134
- error: null,
135
- connection: null,
136
- transport: null,
137
- })
140
+ const enabled = effective(name)
141
+ servers.set(name, { name, command, scope, enabled, status: enabled ? 'idle' : 'disabled', error: null, connection: null, transport: null })
138
142
  }
139
143
  for (const [name, command] of Object.entries(registry.servers)) register(name, command, 'global')
140
144
  for (const [name, command] of Object.entries(projectConfig.servers)) register(name, command, 'project')
@@ -146,13 +150,21 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
146
150
  server.error = null
147
151
  onChange()
148
152
  try {
149
- server.transport = await createMcpTransport(server.command)
150
- server.connection = await connectMCP({
153
+ const transport = await createMcpTransport(server.command)
154
+ server.transport = transport
155
+ const connection = await connectMCP({
151
156
  name,
152
- transport: () => server.transport,
157
+ transport: () => transport,
153
158
  })
159
+ // switched off or replaced while it was connecting
160
+ if (servers.get(name) !== server || !server.enabled || server.transport !== transport) {
161
+ await connection.close().catch(() => {})
162
+ return
163
+ }
164
+ server.connection = connection
154
165
  server.status = 'connected'
155
166
  } catch (err) {
167
+ if (servers.get(name) !== server || !server.enabled) return
156
168
  server.status = 'error'
157
169
  server.error = String(err.message || err).slice(0, 300)
158
170
  server.connection = null
@@ -163,10 +175,28 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
163
175
 
164
176
  async function disconnect(name) {
165
177
  const server = servers.get(name)
166
- if (server?.connection) {
167
- await server.connection.close().catch(() => {})
168
- server.connection = null
178
+ if (!server) return
179
+ const connection = server.connection
180
+ server.connection = null
181
+ server.transport = null
182
+ if (connection) await connection.close().catch(() => {})
183
+ }
184
+
185
+ // brings one server in line with its switches; connecting and closing
186
+ // run in the background, so nothing waits on a slow server
187
+ function apply(name) {
188
+ const server = servers.get(name)
189
+ if (!server) return
190
+ const enabled = effective(name)
191
+ if (enabled === server.enabled && (enabled ? server.status !== 'disabled' : true)) return
192
+ server.enabled = enabled
193
+ if (enabled) connect(name).catch(() => {})
194
+ else {
195
+ server.status = 'disabled'
196
+ server.error = null
197
+ disconnect(name).catch(() => {})
169
198
  }
199
+ onChange()
170
200
  }
171
201
 
172
202
  return {
@@ -177,18 +207,59 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
177
207
  }
178
208
  return Promise.allSettled(pending)
179
209
  },
210
+ // reads both files again and follows them: servers added, removed or
211
+ // changed elsewhere, and switches flipped in another session
212
+ async sync() {
213
+ registry = await readRegistry()
214
+ projectConfig = await readProjectConfig(root)
215
+ const wanted = new Map([
216
+ ...Object.entries(registry.servers).map(([name, command]) => [name, { command, scope: 'global' }]),
217
+ ...Object.entries(projectConfig.servers).map(([name, command]) => [name, { command, scope: 'project' }]),
218
+ ])
219
+ for (const name of [...servers.keys()]) {
220
+ if (wanted.has(name)) continue
221
+ disconnect(name).catch(() => {})
222
+ servers.delete(name)
223
+ }
224
+ for (const [name, { command, scope }] of wanted) {
225
+ const server = servers.get(name)
226
+ if (!server) {
227
+ register(name, command, scope)
228
+ if (servers.get(name).enabled) connect(name).catch(() => {})
229
+ continue
230
+ }
231
+ server.scope = scope
232
+ if (server.command !== command) {
233
+ server.command = command
234
+ disconnect(name).catch(() => {})
235
+ server.status = server.enabled ? 'idle' : 'disabled'
236
+ if (server.enabled) connect(name).catch(() => {})
237
+ }
238
+ apply(name)
239
+ }
240
+ onChange()
241
+ },
242
+ // on or off for this session only; null follows the project and global
243
+ setSessionEnabled(name, enabled) {
244
+ if (enabled === null || enabled === undefined) sessionSettings.delete(name)
245
+ else sessionSettings.set(name, !!enabled)
246
+ apply(name)
247
+ },
180
248
  async add(name, command, scope = 'global') {
181
249
  if (scope === 'project') {
182
250
  const config = await readProjectConfig(root)
183
251
  config.servers[name] = command
184
252
  await writeProjectConfig(root, config)
253
+ projectConfig = config
185
254
  } else {
186
- const registry = await readRegistry()
187
- registry.servers[name] = command
188
- await writeRegistry(registry)
255
+ const next = await readRegistry()
256
+ next.servers[name] = command
257
+ await writeRegistry(next)
258
+ registry = next
189
259
  }
190
- servers.set(name, { name, command, scope, enabled: true, status: 'idle', error: null, connection: null, transport: null })
191
- await connect(name)
260
+ register(name, command, scope)
261
+ if (servers.get(name).enabled) await connect(name)
262
+ else onChange()
192
263
  },
193
264
  async update(name, command) {
194
265
  const server = servers.get(name)
@@ -197,10 +268,12 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
197
268
  const config = await readProjectConfig(root)
198
269
  config.servers[name] = command
199
270
  await writeProjectConfig(root, config)
271
+ projectConfig = config
200
272
  } else {
201
- const registry = await readRegistry()
202
- registry.servers[name] = command
203
- await writeRegistry(registry)
273
+ const next = await readRegistry()
274
+ next.servers[name] = command
275
+ await writeRegistry(next)
276
+ registry = next
204
277
  }
205
278
  await disconnect(name)
206
279
  server.command = command
@@ -215,34 +288,30 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
215
288
  const config = await readProjectConfig(root)
216
289
  delete config.servers[name]
217
290
  await writeProjectConfig(root, config)
291
+ projectConfig = config
218
292
  } else {
219
- const registry = await readRegistry()
220
- delete registry.servers[name]
221
- await writeRegistry(registry)
293
+ const next = await readRegistry()
294
+ delete next.servers[name]
295
+ delete next.disabled[name]
296
+ await writeRegistry(next)
297
+ registry = next
222
298
  }
223
299
  await disconnect(name)
224
300
  servers.delete(name)
225
301
  onChange()
226
302
  },
303
+ // the project's switch: off here, or back to on (overriding a global off)
227
304
  async toggle(name) {
228
305
  const server = servers.get(name)
229
306
  if (!server) return
230
307
  const config = await readProjectConfig(root)
231
- if (server.enabled) {
232
- // flip the visible state first: a slow-closing server (headless
233
- // browsers, heavy processes) must not make disable feel dead
234
- server.enabled = false
235
- server.status = 'disabled'
236
- onChange()
237
- config.disabled[name] = true
238
- await writeProjectConfig(root, config)
239
- disconnect(name).catch(() => {})
240
- } else {
241
- server.enabled = true
242
- delete config.disabled[name]
243
- await writeProjectConfig(root, config)
244
- await connect(name)
245
- }
308
+ if (server.enabled) config.disabled[name] = true
309
+ else if (globalEnabled(name)) delete config.disabled[name]
310
+ else config.disabled[name] = false
311
+ await writeProjectConfig(root, config)
312
+ projectConfig = config
313
+ sessionSettings.delete(name)
314
+ apply(name)
246
315
  },
247
316
  reconnect(name) {
248
317
  return disconnect(name).then(() => connect(name))
@@ -253,6 +322,9 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
253
322
  command: s.command,
254
323
  scope: s.scope,
255
324
  enabled: s.enabled,
325
+ globalEnabled: globalEnabled(s.name),
326
+ projectEnabled: projectSetting(s.name),
327
+ sessionEnabled: sessionSettings.has(s.name) ? sessionSettings.get(s.name) : null,
256
328
  status: s.status,
257
329
  error: s.error,
258
330
  toolCount: s.connection?.tools.length || 0,
@@ -261,7 +333,7 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
261
333
  },
262
334
  tools() {
263
335
  return [...servers.values()]
264
- .filter((s) => s.connection)
336
+ .filter((s) => s.connection && s.enabled)
265
337
  .flatMap((s) => s.connection.tools)
266
338
  },
267
339
  closeAll() {
@@ -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
+ }