picocode-core 0.9.238 → 0.9.239

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.
Files changed (39) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/acp/README.md +41 -0
  4. package/src/acp/connect.js +108 -0
  5. package/src/acp/engine.js +531 -0
  6. package/src/acp/pico-agent.js +295 -0
  7. package/src/acp/rpc.js +75 -0
  8. package/src/acp/translate.js +163 -0
  9. package/src/antigravity/README.md +42 -0
  10. package/src/antigravity/adapter.js +146 -0
  11. package/src/antigravity/conversations.js +22 -0
  12. package/src/antigravity/engine.js +27 -0
  13. package/src/antigravity/models.js +91 -0
  14. package/src/antigravity/process.js +60 -0
  15. package/src/boot.js +3 -2
  16. package/src/catalog-snapshot.json +1 -1
  17. package/src/claude-code/README.md +14 -20
  18. package/src/claude-code/adapter.js +278 -0
  19. package/src/claude-code/cli.js +6 -2
  20. package/src/claude-code/engine.js +30 -398
  21. package/src/claude-code/models.js +7 -4
  22. package/src/claude-code/token.js +23 -0
  23. package/src/claude-code/translate.js +65 -180
  24. package/src/controller.js +2 -0
  25. package/src/engine-history.js +87 -0
  26. package/src/engines.js +3 -1
  27. package/src/local-session.js +49 -0
  28. package/src/mcp.js +12 -1
  29. package/src/model-runtime.js +94 -0
  30. package/src/openai-auth.js +9 -1
  31. package/src/sign-in/antigravity.js +123 -0
  32. package/src/sign-in/chatgpt.js +32 -0
  33. package/src/sign-in/claude-code.js +73 -0
  34. package/src/sign-in/index.js +32 -0
  35. package/src/sign-in/screen.js +56 -0
  36. package/src/sign-in/supergrok.js +21 -0
  37. package/src/{claude-code/mcp-server.js → tool-bridge-server.js} +3 -3
  38. package/src/{claude-code/bridge.js → tool-bridge.js} +42 -12
  39. package/src/xai-auth.js +6 -1
@@ -0,0 +1,123 @@
1
+ // Signing this machine's agy in to a Google account, and out again. agy
2
+ // runs the whole sign-in itself, as it does in a terminal: it opens
3
+ // Google's page and listens on this machine for the page's answer. pico
4
+ // only catches the page's address, so a host can show it wherever the
5
+ // person is, and hands back the address the page ended on when the
6
+ // person signed in from another device. The login agy keeps stays agy's.
7
+
8
+ import { execFile } from 'node:child_process'
9
+ import { mkdtempSync, rmSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+ import { initialize, spawnAgent } from '../acp/connect.js'
14
+ import { modelsOffered } from '../acp/translate.js'
15
+ import { agyEnv, pageCatcher } from '../antigravity/process.js'
16
+ import { agyCommand, antigravityStatus, writeCatalog } from '../antigravity/models.js'
17
+ import { forgetConversation } from '../antigravity/conversations.js'
18
+
19
+ const SUBSCRIPTION_REQUIRED = /SUBSCRIPTION_REQUIRED|eligib/i
20
+
21
+ function signInError(error) {
22
+ const text = String(error?.message ?? error)
23
+ if (SUBSCRIPTION_REQUIRED.test(text)) return new Error('This Google account has no Antigravity plan that allows sign-in here')
24
+ if (/cancel/i.test(text)) return new Error('cancelled')
25
+ if (/access_denied|denied access/i.test(text)) return new Error('Google sign-in was not approved')
26
+ return new Error(text)
27
+ }
28
+
29
+ export const status = async () => {
30
+ const s = await antigravityStatus()
31
+ return { installed: s.installed, signedIn: s.connected, identity: null, ...(s.error ? { error: s.error } : {}) }
32
+ }
33
+
34
+ // begins a sign-in. `page` is Google's page to open; `done` settles when
35
+ // agy has signed in and opened a session with it, which is the only proof
36
+ // the sign-in works, and lists the models it may use
37
+ export async function start({ command = agyCommand() } = {}) {
38
+ if (!command) throw new Error('The Antigravity CLI is not installed')
39
+ const catcher = pageCatcher()
40
+ const cwd = mkdtempSync(join(tmpdir(), 'pico-agy-signin-'))
41
+ let exit = null
42
+ const agy = spawnAgent({ command, args: ['acp'], cwd, env: agyEnv(catcher.env(process.env)), onExit: (e) => { exit = e } })
43
+ const cleanup = () => { agy.close(); catcher.close(); rmSync(cwd, { recursive: true, force: true }) }
44
+ // where Google's page sends the browser back to, and the sign-in it belongs to
45
+ let redirect = null
46
+ let state = null
47
+
48
+ const page = (async () => {
49
+ await initialize(agy)
50
+ const url = await catcher.next()
51
+ const params = new URL(url).searchParams
52
+ redirect = new URL(params.get('redirect_uri'))
53
+ state = params.get('state')
54
+ return { url }
55
+ })()
56
+
57
+ const done = (async () => {
58
+ await initialize(agy)
59
+ try {
60
+ await agy.request('authenticate', { methodId: 'oauth-personal' })
61
+ } catch (error) {
62
+ throw signInError(exit?.error ?? error)
63
+ }
64
+ try {
65
+ const session = await agy.request('session/new', { cwd, mcpServers: [] })
66
+ const models = modelsOffered(session?.configOptions)
67
+ if (models.length) writeCatalog(models)
68
+ await agy.request('session/close', { sessionId: session.sessionId }).catch(() => {})
69
+ forgetConversation(session.sessionId)
70
+ return { identity: null, models }
71
+ } catch (error) {
72
+ throw signInError(error)
73
+ }
74
+ })()
75
+ done.then(cleanup, cleanup)
76
+ page.catch(() => {})
77
+
78
+ return {
79
+ page,
80
+ input: 'redirect',
81
+ done,
82
+ // the address Google's page ended on, from a browser on another
83
+ // device, passed on to the listener agy keeps on this machine
84
+ async finish(address) {
85
+ await page
86
+ let back
87
+ try { back = new URL(String(address).trim()) } catch { throw new Error('That is not the address the page ended on') }
88
+ const sameListener = ['localhost', '127.0.0.1', '[::1]'].includes(back.hostname) && back.port === redirect.port && back.pathname === redirect.pathname
89
+ if (!sameListener) throw new Error('That is not the address the page ended on')
90
+ if (back.searchParams.get('state') !== state) throw new Error('That address is from another sign-in; sign in again')
91
+ if (!back.searchParams.has('code') && !back.searchParams.has('error')) throw new Error('That address has no answer from Google in it')
92
+ const response = await fetch(`http://${redirect.host}${back.pathname}${back.search}`, { signal: AbortSignal.timeout(10000) }).catch(() => null)
93
+ if (!response) throw new Error('The sign-in on this machine has already ended; sign in again')
94
+ },
95
+ cancel: cleanup,
96
+ }
97
+ }
98
+
99
+ // signs agy out of its Google account on this machine
100
+ export async function signOut({ command = agyCommand() } = {}) {
101
+ if (!command) return
102
+ const cwd = mkdtempSync(join(tmpdir(), 'pico-agy-signout-'))
103
+ const agy = spawnAgent({ command, args: ['acp'], cwd, env: agyEnv() })
104
+ try {
105
+ await initialize(agy)
106
+ await agy.request('logout', {})
107
+ } finally {
108
+ agy.close()
109
+ rmSync(cwd, { recursive: true, force: true })
110
+ }
111
+ writeCatalog([])
112
+ }
113
+
114
+ // Google's own installer for the Antigravity CLI, run as Google says to run it
115
+ const INSTALLER = 'https://antigravity.google/cli/install.sh'
116
+ export function install() {
117
+ return new Promise((resolve, reject) => {
118
+ execFile('sh', ['-c', `curl -fsSL '${INSTALLER}' | bash`], { cwd: homedir(), timeout: 600000, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
119
+ if (error) reject(new Error(`The Antigravity installer failed: ${String(stderr || stdout || error.message).trim().split('\n').at(-1)}`))
120
+ else resolve()
121
+ })
122
+ })
123
+ }
@@ -0,0 +1,32 @@
1
+ // ChatGPT's sign-in, for Codex models: pico's own (openai-auth.js). The
2
+ // page sends the browser back to a listener on this machine; from a
3
+ // browser elsewhere, the address the page ended on is handed to it.
4
+
5
+ import { connectOpenAI, disconnectOpenAI, openaiStatus } from '../openai-auth.js'
6
+
7
+ export const status = async () => {
8
+ const s = await openaiStatus().catch(() => ({ connected: false, email: null }))
9
+ return { installed: true, signedIn: !!s.connected, identity: s.email ?? null }
10
+ }
11
+
12
+ export async function start() {
13
+ const controller = new AbortController()
14
+ let shown
15
+ const page = new Promise((resolve) => { shown = resolve })
16
+ const done = connectOpenAI({ openBrowser: false, onUrl: (url) => shown({ url }), signal: controller.signal }).then((r) => ({ identity: r.email ?? null }))
17
+ done.catch(() => {})
18
+ return {
19
+ page,
20
+ input: 'redirect',
21
+ done,
22
+ async finish(address) {
23
+ let back
24
+ try { back = new URL(String(address).trim()) } catch { throw new Error('That is not the address the page ended on') }
25
+ if (!['localhost', '127.0.0.1'].includes(back.hostname) || back.pathname !== '/auth/callback') throw new Error('That is not the address the page ended on')
26
+ await fetch(`http://127.0.0.1:1455${back.pathname}${back.search}`, { signal: AbortSignal.timeout(10000) }).catch(() => {})
27
+ },
28
+ cancel: () => controller.abort(),
29
+ }
30
+ }
31
+
32
+ export const signOut = () => disconnectOpenAI()
@@ -0,0 +1,73 @@
1
+ // Claude Code's sign-in, as pico keeps it: the long-lived token
2
+ // `claude setup-token` makes (../claude-code/token.js), so pico does not
3
+ // depend on, or disturb, the login `claude` keeps itself. The token is
4
+ // also handed back, for a host that keeps it elsewhere.
5
+
6
+ import { homedir } from 'node:os'
7
+ import { claudeCodeStatus, claudeCommand } from '../claude-code/models.js'
8
+ import { forgetClaudeToken, keepClaudeToken } from '../claude-code/token.js'
9
+ import { flat, lastSaid, runOnScreen } from './screen.js'
10
+
11
+ const TOKEN = /sk-ant-oat[0-9]+-[A-Za-z0-9_-]{20,}/
12
+ const LINK = /https:\/\/\S+\/oauth\/authorize\?\S*state=\S+/
13
+
14
+ export const status = async () => {
15
+ const claude = await claudeCodeStatus()
16
+ return { installed: claude.installed, signedIn: claude.connected, identity: claude.email }
17
+ }
18
+
19
+ // `keep: false` hands the token back without keeping it, for a host that keeps it itself
20
+ export async function start({ keep = true } = {}) {
21
+ const command = claudeCommand()
22
+ if (!command) throw new Error('Claude Code is not installed')
23
+ const env = { ...process.env }
24
+ delete env.CLAUDE_CODE_OAUTH_TOKEN
25
+ const run = runOnScreen(command, ['setup-token'], { env, cwd: homedir() })
26
+ let settled = false
27
+ let cancelled = false
28
+ const found = (screen) => flat(screen).match(TOKEN)?.[0] ?? null
29
+ const page = new Promise((resolve) => {
30
+ const check = (screen) => { const url = flat(screen).match(LINK)?.[0]; if (url) { off(); resolve({ url }) } }
31
+ const off = run.onScreen(check)
32
+ })
33
+ const done = new Promise((resolve, reject) => {
34
+ const off = run.onScreen((screen) => {
35
+ const token = found(screen)
36
+ if (!token || settled) return
37
+ settled = true
38
+ off()
39
+ if (keep) keepClaudeToken(token)
40
+ resolve({ identity: null, token })
41
+ setTimeout(() => run.kill(), 500)
42
+ })
43
+ run.exited.then(() => {
44
+ if (settled) return
45
+ settled = true
46
+ // a token printed just before it stopped is still taken
47
+ const token = found(run.screen)
48
+ if (token) { if (keep) keepClaudeToken(token); resolve({ identity: null, token }) }
49
+ else if (cancelled) reject(new Error('cancelled'))
50
+ else reject(new Error(`Claude Code stopped without a token. It last said: ${lastSaid(run.screen)}`))
51
+ })
52
+ })
53
+ done.catch(() => {})
54
+ return {
55
+ page,
56
+ input: 'code',
57
+ done,
58
+ // the code from Claude's page goes in, and the answer is waited for:
59
+ // a token, or Claude refusing the code
60
+ finish: (code) => new Promise((resolve, reject) => {
61
+ const from = run.screen.length
62
+ const check = setInterval(() => {
63
+ if (settled) { clearInterval(check); resolve(); return }
64
+ if (/retry|invalid|expired|error|failed/i.test(flat(run.screen.slice(from)))) { clearInterval(check); reject(new Error('Claude did not accept that code. Copy the whole code from the page and try again.')) }
65
+ }, 250)
66
+ setTimeout(() => { clearInterval(check); if (!settled) reject(new Error(`Claude did not answer. It last said: ${lastSaid(run.screen)}`)) }, 45000)
67
+ run.type(String(code).trim())
68
+ }),
69
+ cancel() { cancelled = true; run.kill() },
70
+ }
71
+ }
72
+
73
+ export const signOut = async () => forgetClaudeToken()
@@ -0,0 +1,32 @@
1
+ // Every sign-in pico makes to use a subscription, one per provider, each
2
+ // the same five calls:
3
+ //
4
+ // - status(): { installed, signedIn, identity, error? }
5
+ // - start(): a sign-in under way, { page, input, finish, done, cancel }:
6
+ // `page` resolves to { url, code? }, the page to open (and a code to
7
+ // enter there); `input` says what the person brings back from it by
8
+ // hand, 'code', 'redirect' (the address the page ended on, from a
9
+ // browser on another device) or null; `finish(text)` hands that in;
10
+ // `done` resolves to { identity, token? } once signed in
11
+ // - signOut()
12
+ // - install(), where pico can install the agent a sign-in is for
13
+ //
14
+ // Keyed by the provider whose models the sign-in opens up.
15
+
16
+ import * as claudeCode from './claude-code.js'
17
+ import * as chatgpt from './chatgpt.js'
18
+ import * as supergrok from './supergrok.js'
19
+ import * as antigravity from './antigravity.js'
20
+
21
+ export const SIGN_INS = {
22
+ 'claude-code': { label: 'Claude Code', ...claudeCode },
23
+ codex: { label: 'ChatGPT', ...chatgpt },
24
+ grok: { label: 'SuperGrok', ...supergrok },
25
+ antigravity: { label: 'Antigravity', ...antigravity },
26
+ }
27
+
28
+ export function signInFor(provider) {
29
+ const found = SIGN_INS[provider]
30
+ if (!found) throw new Error(`no sign-in for ${provider}`)
31
+ return found
32
+ }
@@ -0,0 +1,56 @@
1
+ // A terminal program's screen, read as text: what a sign-in that only
2
+ // runs in a terminal shows, through the system's `script` command, which
3
+ // gives it a terminal of its own without a native library. Wide enough
4
+ // that a long link is never wrapped, and so never read cut short.
5
+
6
+ import { spawn } from 'node:child_process'
7
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { tmpdir } from 'node:os'
9
+ import { join } from 'node:path'
10
+
11
+ const quote = (text) => `'${String(text).replace(/'/g, `'\\''`)}'`
12
+
13
+ // everything a terminal program wrote, as plain characters: every escape
14
+ // sequence gone, and no line redrawn away
15
+ export const flat = (raw) => String(raw)
16
+ .replace(/\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[()][0-9A-Za-z]|[@-Z\\-_78=>])/g, '')
17
+ .replace(/\r/g, '\n')
18
+ .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '')
19
+
20
+ // the last line a person would read there, anything token-like hidden
21
+ export const lastSaid = (raw) => flat(raw).split('\n').map((l) => l.trim()).filter((l) => l.length > 3 && !/^[╭╰│─]+$/.test(l)).at(-1)?.replace(/[A-Za-z0-9_#-]{24,}/g, '…') ?? ''
22
+
23
+ // the programs a sign-in may open a web page with, stood in for by ones
24
+ // that do nothing: the page is shown where the person is, not here
25
+ const OPENERS = ['xdg-open', 'open', 'sensible-browser', 'x-www-browser', 'gnome-open', 'kde-open', 'wslview']
26
+
27
+ export function runOnScreen(command, args, { env = process.env, cwd } = {}) {
28
+ const quiet = mkdtempSync(join(tmpdir(), 'pico-no-browser-'))
29
+ for (const opener of OPENERS) writeFileSync(join(quiet, opener), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
30
+ const line = `stty cols 4000 rows 40; exec ${[command, ...args].map(quote).join(' ')}`
31
+ const scriptArgs = process.platform === 'darwin' ? ['-q', '/dev/null', 'sh', '-c', line] : ['-qfec', line, '/dev/null']
32
+ const child = spawn('script', scriptArgs, { cwd, env: { ...env, PATH: `${quiet}:${env.PATH ?? ''}`, BROWSER: join(quiet, 'xdg-open') }, stdio: ['pipe', 'pipe', 'pipe'] })
33
+ let screen = ''
34
+ const listeners = new Set()
35
+ const take = (chunk) => { screen += chunk; for (const listener of listeners) listener(screen) }
36
+ child.stdout.setEncoding('utf8')
37
+ child.stdout.on('data', take)
38
+ child.stderr.setEncoding('utf8')
39
+ child.stderr.on('data', take)
40
+ child.stdin.on('error', () => {})
41
+ const exited = new Promise((resolve) => {
42
+ child.on('error', (error) => resolve({ error }))
43
+ child.on('exit', (code) => resolve({ code }))
44
+ }).finally(() => rmSync(quiet, { recursive: true, force: true }))
45
+ return {
46
+ get screen() { return screen },
47
+ onScreen(listener) { listeners.add(listener); return () => listeners.delete(listener) },
48
+ // typed, then submitted a moment later: Enter in the same burst would count as part of a paste
49
+ type(text) {
50
+ child.stdin.write(String(text))
51
+ setTimeout(() => child.stdin.write('\r'), 400)
52
+ },
53
+ exited,
54
+ kill() { try { child.kill('SIGTERM') } catch {} },
55
+ }
56
+ }
@@ -0,0 +1,21 @@
1
+ // SuperGrok's sign-in, for Grok models: pico's own (xai-auth.js), a device
2
+ // code shown with its page, entered there; nothing comes back by hand.
3
+
4
+ import { connectXAI, disconnectXAI, xaiConnected } from '../xai-auth.js'
5
+
6
+ export const status = async () => {
7
+ const s = await xaiConnected().catch(() => ({ connected: false, email: null }))
8
+ return { installed: true, signedIn: !!s.connected, identity: s.email ?? null }
9
+ }
10
+
11
+ export async function start() {
12
+ const controller = new AbortController()
13
+ let shown
14
+ const page = new Promise((resolve) => { shown = resolve })
15
+ const done = connectXAI({ openBrowser: false, onUrl: (url, code) => shown({ url, code }), signal: controller.signal })
16
+ .then((r) => ({ identity: r?.email ?? null }), (error) => { throw controller.signal.aborted ? new Error('cancelled') : error })
17
+ done.catch(() => {})
18
+ return { page, input: null, done, finish: async () => {}, cancel: () => controller.abort() }
19
+ }
20
+
21
+ export const signOut = () => disconnectXAI()
@@ -1,6 +1,6 @@
1
- // The stdio MCP server Claude Code starts for pico's tools. It holds no
2
- // tools itself: every list and call goes over the socket named in its
3
- // environment to the bridge in the pico process (see bridge.js).
1
+ // The stdio MCP server a program an engine runs starts for pico's tools.
2
+ // It holds no tools itself: every list and call goes over the socket named
3
+ // in its environment to the bridge in the pico process (see tool-bridge.js).
4
4
 
5
5
  import { createConnection } from 'node:net'
6
6
  import { Server } from '@modelcontextprotocol/sdk/server/index.js'
@@ -1,9 +1,10 @@
1
1
  // pico's own tools (peers, questions, wake-ups, and whatever the host adds,
2
- // like kagent's terminals and browser) offered to Claude Code over MCP.
3
- // Claude Code starts mcp-server.js as a stdio MCP server; that process
4
- // relays each list and call over a private Unix socket back to this one,
5
- // where the tool runs with the live turn's toolset and recorder. The tool
6
- // set changes turn to turn, so the bridge holds whichever turn is current.
2
+ // like kagent's terminals and browser) offered over MCP to a program an
3
+ // engine runs, such as Claude Code or Antigravity. The program starts
4
+ // tool-bridge-server.js as a stdio MCP server; that process relays each
5
+ // list and call over a private Unix socket back to this one, where the
6
+ // tool runs with the live turn's toolset and recorder. The tool set
7
+ // changes turn to turn, so the bridge holds whichever turn is current.
7
8
 
8
9
  import { createServer } from 'node:net'
9
10
  import { mkdtemp, rm, chmod } from 'node:fs/promises'
@@ -11,12 +12,41 @@ import { tmpdir } from 'node:os'
11
12
  import { join } from 'node:path'
12
13
  import { randomBytes } from 'node:crypto'
13
14
  import { fileURLToPath } from 'node:url'
14
- import { BRIDGE_SERVER, inputSchema } from './translate.js'
15
15
 
16
- const SHIM = fileURLToPath(new URL('./mcp-server.js', import.meta.url))
16
+ const SHIM = fileURLToPath(new URL('./tool-bridge-server.js', import.meta.url))
17
+
18
+ // the MCP server's name, so the program sees pico's tools under it, as
19
+ // Claude Code's mcp__pico__<name>
20
+ export const BRIDGE_SERVER = 'pico'
21
+
22
+ // ---- pico tool schemas to JSON Schema ----
23
+
24
+ function jsonProperty(prop) {
25
+ const out = { type: prop.type }
26
+ if (prop.description) out.description = prop.description
27
+ if (prop.enum) out.enum = prop.enum
28
+ if (prop.items) out.items = jsonProperty(prop.items)
29
+ if (prop.properties) {
30
+ out.properties = Object.fromEntries(Object.entries(prop.properties).map(([key, child]) => [key, jsonProperty(child)]))
31
+ if (prop.required) out.required = prop.required
32
+ }
33
+ return out
34
+ }
35
+
36
+ export function inputSchema(schema = {}) {
37
+ // a whole JSON Schema (an MCP server's) goes as it is
38
+ if (typeof schema.type === 'string') return schema
39
+ const properties = {}
40
+ const required = []
41
+ for (const [key, prop] of Object.entries(schema)) {
42
+ properties[key] = jsonProperty(prop)
43
+ if (!prop.optional) required.push(key)
44
+ }
45
+ return { type: 'object', properties, ...(required.length ? { required } : {}) }
46
+ }
17
47
 
18
48
  export async function createBridge() {
19
- const dir = await mkdtemp(join(tmpdir(), 'pico-claude-'))
49
+ const dir = await mkdtemp(join(tmpdir(), 'pico-bridge-'))
20
50
  await chmod(dir, 0o700)
21
51
  const path = join(dir, 'bridge.sock')
22
52
  const token = randomBytes(24).toString('hex')
@@ -80,12 +110,12 @@ export async function createBridge() {
80
110
  }
81
111
 
82
112
  return {
83
- // the MCP server entry Claude Code is started with
84
- mcpConfig() {
85
- return { mcpServers: { [BRIDGE_SERVER]: { type: 'stdio', command: process.execPath, args: [SHIM], env: { PICO_BRIDGE_SOCKET: path, PICO_BRIDGE_TOKEN: token } } } }
113
+ // the stdio MCP server the program is started with
114
+ server() {
115
+ return { name: BRIDGE_SERVER, command: process.execPath, args: [SHIM], env: { PICO_BRIDGE_SOCKET: path, PICO_BRIDGE_TOKEN: token } }
86
116
  },
87
117
  // the tools a turn offers; `onClaim` ties an incoming call to the
88
- // tool_use Claude announced for it
118
+ // tool call the program announced for it
89
119
  setTurn(next, onClaim) {
90
120
  tools = next
91
121
  claim = onClaim
package/src/xai-auth.js CHANGED
@@ -116,11 +116,15 @@ function openInBrowser(url) {
116
116
  execFile(command, [url], () => {})
117
117
  }
118
118
 
119
- export async function connectXAI({ onUrl = () => {}, openBrowser = true, timeoutMs = 300000 } = {}) {
119
+ // `signal` cancels a sign-in under way
120
+ export async function connectXAI({ onUrl = () => {}, openBrowser = true, timeoutMs = 300000, signal } = {}) {
120
121
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('Invalid xAI sign-in timeout')
121
122
  const deadline = Date.now() + timeoutMs
122
123
  const controller = new AbortController()
123
124
  const timer = setTimeout(() => controller.abort(new Error('xAI sign-in timed out')), timeoutMs)
125
+ const cancel = () => controller.abort(new Error('cancelled'))
126
+ if (signal?.aborted) cancel()
127
+ signal?.addEventListener('abort', cancel, { once: true })
124
128
  try {
125
129
  return await locked(async (file, assertLock) => {
126
130
  controller.signal.throwIfAborted()
@@ -154,6 +158,7 @@ export async function connectXAI({ onUrl = () => {}, openBrowser = true, timeout
154
158
  })
155
159
  } finally {
156
160
  clearTimeout(timer)
161
+ signal?.removeEventListener('abort', cancel)
157
162
  }
158
163
  }
159
164