From c9381a2debf53f2cca2ba2f081ceb80a5eb6b9f4 Mon Sep 17 00:00:00 2001 From: qiansc Date: Tue, 1 Dec 2026 07:14:14 +0000 Subject: [PATCH] cli 0.8.0: doctor, IPv4/IPv6 fallback, switch to another entry of the same service - sourcegraph doctor: DNS, a connection to each IPv4/IPv6 address, HTTPS and the sign-in, with advice. - Turn on IPv4/IPv6 family fallback on Node 18 as Node 20+ does; NETWORK_ERROR lists the addresses tried. Node 18.18+. - A deployment whose site has a production entry (same service, another network path) uses that entry when the site cannot be reached at all and the request never left this machine. - Skill and README: troubleshooting for NETWORK_ERROR and MCP timeouts. Co-Authored-By: Claude Opus 5.5 --- .claude-plugin/plugin.json | 2 +- cli/README.md | 3 + cli/package.json | 4 +- cli/src/api.ts | 33 ++++++++- cli/src/config.ts | 16 ++++- cli/src/main.ts | 34 +++++++-- cli/src/network.test.ts | 115 +++++++++++++++++++++++++++++ cli/src/network.ts | 120 +++++++++++++++++++++++++++++++ cli/src/version.ts | 2 +- scripts/deployment/cli-readme.md | 3 + scripts/deployment/skill.md | 3 +- skills/sourcegraph/SKILL.md | 3 +- 12 files changed, 321 insertions(+), 17 deletions(-) create mode 100644 cli/src/network.test.ts create mode 100644 cli/src/network.ts diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 0961755..4d1e757 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "sourcegraph", "description": "Search and read code in a Sourcegraph service at pinned commits, and register or maintain its repositories, through MCP or the sourcegraph CLI.", - "version": "0.7.0", + "version": "0.8.0", "author": { "name": "context4ai" }, diff --git a/cli/README.md b/cli/README.md index 9af7ce0..9b7cdf7 100644 --- a/cli/README.md +++ b/cli/README.md @@ -36,11 +36,14 @@ A token acts as its owner: it reads what you can read, manages repositories you | Tags | `tags`, `tags rename ` | | Site administration | `admin settings/users/role/credentials/query-errors/clear-jobs/cluster/instances/statistics/logs` | | MCP | `mcp` prints a client configuration | +| Connection | `doctor` checks DNS, each IPv4/IPv6 address, HTTPS and the sign-in, and says what to do | `sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` shows service logs of all instances (default: warnings and errors, last 24 hours). `sourcegraph read ` prints lines 1–200 by default; `--start N` alone reads 200 lines from line N, and `--start/--end` reads a range of up to 2000 lines per call. `--all` reads the whole file page by page at the commit of the first page, with continuous line numbers. It stops after 20000 lines and still exits 0: the command that continues is printed on stderr, and `--json` output keeps `HasMore: true` and `NextStartLine`. +Some networks reach a site over only IPv4 or only IPv6. When an address does not answer within 250 ms the CLI tries the next one, including the other family (on Node 18 too; the Node option `--no-network-family-autoselection` turns this off). If a command reports `NETWORK_ERROR`, `sourcegraph doctor` shows which addresses answer from this machine. MCP clients connect on their own: Node 20+ switches the same way; on Node 18 set `NODE_OPTIONS=--network-family-autoselection`. + Run `sourcegraph --help` for flags. `--json` prints the API's raw output; `--yes` skips confirmations. Repository settings use `key=value` (`sourcegraph repo set org/repo sync_interval_minutes=60 public_read=false`). Intervals under 30 minutes are for site administrators; others are raised to 30 minutes with a warning. `manual_updates=true` turns off automatic updates (scheduled checks); `tags=a,b` replaces the tags and `tags=` clears them. diff --git a/cli/package.json b/cli/package.json index 795d970..c797bb9 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@c4a/sourcegraph", - "version": "0.7.0", + "version": "0.8.0", "description": "Command-line client for Sourcegraph: search and read code at pinned commits, register and manage repositories, personal and site settings.", "license": "MIT", "type": "module", @@ -14,7 +14,7 @@ "directory": "cli" }, "engines": { - "node": ">=18.3" + "node": ">=18.18" }, "scripts": { "build": "node ../scripts/sync-deployment.mjs && bun build src/main.ts --target node --outfile dist/sourcegraph.js && node -e \"const f='dist/sourcegraph.js',fs=require('fs');const s=fs.readFileSync(f,'utf8');fs.writeFileSync(f,(s.startsWith('#!')?'':'#!/usr/bin/env node\\n')+s);fs.chmodSync(f,0o755)\"", diff --git a/cli/src/api.ts b/cli/src/api.ts index a538ea5..834ec73 100644 --- a/cli/src/api.ts +++ b/cli/src/api.ts @@ -1,8 +1,9 @@ import { randomBytes } from 'node:crypto'; +import { networkDetail, unsent } from './network.js'; // One HTTP API request; errors carry the server's code and message. export class ApiError extends Error { - constructor(public status: number, public code: string, message: string, public body: any) { super(message); } + constructor(public status: number, public code: string, message: string, public body: any, public unsent = false) { super(message); } } export interface Request { @@ -13,8 +14,11 @@ export interface Request { anonymous?: boolean; } +// Another entry of the same service, used when the site cannot be reached. +export interface Alternate { site: string; token?: string; onSwitch?: (site: string, why: string) => void } + export class Client { - constructor(public site: string, public token?: string) {} + constructor(public site: string, public token?: string, private alternate?: Alternate) {} url(path: string, query?: Request['query']): string { const u = new URL(this.site + path); @@ -22,7 +26,30 @@ export class Client { return u.toString(); } + // call sends a request. When the site cannot be reached at all (the request + // never left this machine) and the service has another entry, the client + // switches to that entry for this request and the rest of the command. async call(path: string, req: Request = {}): Promise { + try { return await this.send(path, req); } catch (e) { + const alt = this.alternate; + if (!alt || !(e instanceof ApiError) || !e.unsent) throw e; + this.alternate = undefined; + const from = this.site, token = this.token; + this.site = alt.site; + this.token = token ?? alt.token; + try { + const r = await this.send(path, req); + alt.onSwitch?.(alt.site, e.message.replace(/^Cannot reach \S+: /, '')); + return r; + } catch (e2) { + this.site = from; this.token = token; + if (e2 instanceof ApiError && e2.unsent) throw new ApiError(0, 'NETWORK_ERROR', `${e.message}; the same service at ${alt.site} cannot be reached either: ${e2.message.replace(/^Cannot reach \S+: /, '')}`, null, true); + throw e2; + } + } + } + + private async send(path: string, req: Request): Promise { const headers: Record = { Accept: 'application/json', 'User-Agent': 'sourcegraph-cli', ...(req.headers || {}) }; if (this.token && !req.anonymous) headers.Authorization = 'Bearer ' + this.token; if (req.body !== undefined) headers['Content-Type'] = 'application/json'; @@ -32,7 +59,7 @@ export class Client { try { res = await fetch(this.url(path, req.query), { method: req.method || (req.body !== undefined ? 'POST' : 'GET'), headers, body: req.body === undefined ? undefined : JSON.stringify(req.body), signal: ctl.signal, redirect: 'manual' }); } catch (e: any) { - throw new ApiError(0, 'NETWORK_ERROR', `Cannot reach ${this.site}: ${e?.cause?.code || e?.message || e}`, null); + throw new ApiError(0, 'NETWORK_ERROR', `Cannot reach ${this.site}: ${ctl.signal.aborted ? 'no response within 60 s' : networkDetail(e)}`, null, !ctl.signal.aborted && unsent(e)); } finally { clearTimeout(timer); } const text = await res.text(); let body: any = text; diff --git a/cli/src/config.ts b/cli/src/config.ts index e696391..b741b3a 100644 --- a/cli/src/config.ts +++ b/cli/src/config.ts @@ -7,7 +7,7 @@ import deployment from '../../config/deployment.json' with { type: 'json' }; // The sites come from the deployment profile (config/deployment.json), bundled // at build time: a private deployment builds a CLI that knows its own sites. -export interface Site { id: string; label: string; url: string; aliases?: string[]; cli?: string } +export interface Site { id: string; label: string; url: string; aliases?: string[]; cli?: string; production_entry?: { site: string } } export const DEPLOYMENT = deployment as unknown as { sites: Site[]; default_site: string; site_aliases?: Record; public_url?: string; site_notice?: { site: string; recommend: string; cli?: string }; @@ -55,6 +55,20 @@ export function siteName(url: string): string { return url; } +// alternateSite is the other entry of the same service (a site and its +// production entry): same data and same tokens, reached over another network +// path. Undefined for a site without one. +export function alternateSite(url: string): string | undefined { + const id = siteName(url); + for (const s of DEPLOYMENT.sites) { + const other = s.production_entry?.site; + if (!other || !SITES[other]) continue; + if (s.id === id) return SITES[other]; + if (other === id) return SITES[s.id]; + } + return undefined; +} + // --site/--url, then SOURCEGRAPH_URL, then the saved site, then the default site. export function resolveSite(flag: string | undefined): string { if (flag) return normalizeSite(flag); diff --git a/cli/src/main.ts b/cli/src/main.ts index 12e4ee4..f500b6c 100644 --- a/cli/src/main.ts +++ b/cli/src/main.ts @@ -5,9 +5,10 @@ import { hostname } from 'node:os'; import { spawn } from 'node:child_process'; import { createInterface } from 'node:readline/promises'; import { Client, ApiError, idempotencyKey } from './api.js'; -import { SITES, DEFAULT_SITE, DEPLOYMENT, loadConfig, saveConfig, resolveSite, resolveToken, normalizeSite, siteName, configPath } from './config.js'; +import { SITES, DEFAULT_SITE, DEPLOYMENT, loadConfig, saveConfig, resolveSite, resolveToken, normalizeSite, siteName, configPath, alternateSite } from './config.js'; import { settingsUpdate, parseAssignments, SETTING_KEYS } from './settings.js'; import { VERSION } from './version.js'; +import { enableFamilyFallback, diagnose, diagnosisText, advise } from './network.js'; type Opts = Record; interface Ctx { client: Client; site: string; json: boolean; yes: boolean } @@ -155,18 +156,18 @@ async function login(ctx: Ctx, _a: string[], o: Opts) { return jsonOutput ? me : `Signed in to ${ctx.site} as ${me.user.name} (${me.user.role}). Token saved in ${configPath()}.`; } async function logout(ctx: Ctx) { - const config = loadConfig(); - const token = config.tokens?.[ctx.site]; - if (!token) return `Not signed in to ${ctx.site}.`; + const config = loadConfig(), site = ctx.site; + const token = config.tokens?.[site]; + if (!token) return `Not signed in to ${site}.`; let revoked = false; try { const keys = await ctx.client.call('/auth/api-keys', { query: { limit: 100 } }); const mine = (keys.items || []).find((k: any) => k.key_prefix && token.startsWith(k.key_prefix)); if (mine) revoked = (await ctx.client.call('/auth/api-keys/' + encodeURIComponent(mine.id), { method: 'DELETE' })).deleted === true; } catch (e) { if (!(e instanceof ApiError) || e.status !== 401) throw e; } - delete config.tokens![ctx.site]; + delete config.tokens![site]; saveConfig(config); - return revoked ? `Signed out of ${ctx.site}; the token was revoked.` : `Signed out of ${ctx.site}. The token could not be revoked here (already invalid, or not found); check User settings → API Tokens.`; + return revoked ? `Signed out of ${site}; the token was revoked.` : `Signed out of ${site}. The token could not be revoked here (already invalid, or not found); check User settings → API Tokens.`; } // ---------- read ---------- @@ -510,6 +511,19 @@ const C: Record = { } throw new Error('Unknown admin command. See: sourcegraph admin --help'); } }, + doctor: { usage: 'doctor', summary: 'Check the connection to the site: DNS, IPv4/IPv6 addresses, HTTPS and sign-in', run: async ctx => { + const others = Object.keys(SITES).filter(id => id !== siteName(ctx.site)); + const d = await diagnose(ctx.site, ctx.client.token ? () => ctx.client.call('/auth/me') : undefined, others); + const alt = alternateSite(ctx.site); + if (alt && !d.https.ok) { + const a = (await diagnose(alt)).https; + d.alternate = { site: siteName(alt), ok: a.ok, status: a.status, error: a.error }; + d.advice = advise(d, others); + } + if (d.https.ok && d.sign_in?.ok !== false) return jsonOutput ? d : diagnosisText(d); + print(jsonOutput ? d : diagnosisText(d)); + throw new Error(!d.https.status ? 'the site cannot be reached from here' : !d.https.ok ? 'the site is not ready' : 'the sign-in failed'); + } }, mcp: { usage: 'mcp', summary: 'Print an MCP client configuration for this site and token', run: async ctx => { const token = resolveToken(ctx.site); return { mcpServers: { [DEPLOYMENT.mcp_server_name || 'sourcegraph']: { type: 'http', url: ctx.site + '/mcp?plugins=auto', ...(token ? { headers: { Authorization: 'Bearer ' } } : {}) } } }; @@ -524,6 +538,7 @@ function help(name?: string): string { } export async function main(argv: string[]): Promise { + enableFamilyFallback(); // The command is the first positional once the global flags (and their values) are set aside. const name = parseArgs({ args: argv, options: { site: { type: 'string' }, url: { type: 'string' } }, allowPositionals: true, strict: false }).positionals[0]; const cmd = name ? C[name] : undefined; @@ -537,13 +552,18 @@ export async function main(argv: string[]): Promise { jsonOutput = !!o.json; try { const site = resolveSite(o.url || o.site); - const ctx: Ctx = { site, client: new Client(site, resolveToken(site)), json: jsonOutput, yes: !!o.yes }; + const alt = alternateSite(site); + const ctx: Ctx = { site, client: new Client(site, resolveToken(site), alt ? { site: alt, token: resolveToken(alt), onSwitch: (to, why) => { + ctx.site = to; + console.error(`note: ${site} cannot be reached from here (${why}); used ${to}, the same service with the same data. To use it by default: sourcegraph config set site ${siteName(to)}`); + } } : undefined), json: jsonOutput, yes: !!o.yes }; print(await cmd.run(ctx, parsed.positionals.slice(1), o)); return 0; } catch (e: any) { if (e instanceof ApiError) { console.error(`error: ${e.message === e.code ? e.code : `${e.message} (${e.code})`}${e.status ? ` [HTTP ${e.status}]` : ''}`); if (e.status === 401) console.error('Sign in with: sourcegraph login'); + if (e.code === 'NETWORK_ERROR') console.error('Check the connection with: sourcegraph doctor'); if (e.code === 'REPOSITORY_OUTSIDE_TOKEN_SCOPE') console.error('See the scope with: sourcegraph tokens; change it with: sourcegraph tokens scope --all-tags --include-public'); if (jsonOutput && e.body) console.log(JSON.stringify(e.body, null, 2)); } else console.error('error: ' + (e?.message || e)); diff --git a/cli/src/network.test.ts b/cli/src/network.test.ts new file mode 100644 index 0000000..fcbb54e --- /dev/null +++ b/cli/src/network.test.ts @@ -0,0 +1,115 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { spawn, spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { advise, diagnose, networkDetail, type Diagnosis } from './network.js'; + +const base = (addresses: Diagnosis['addresses'], https: Diagnosis['https'] = { ok: true, status: 200, ms: 1 }): Diagnosis => + ({ site: 'https://example.test', node: 'v20', family_fallback: true, addresses, https, advice: [] }); + +test('advise names the family that does not answer and what MCP clients need', () => { + const d = base([{ address: '10.0.0.1', family: 4, ok: false, error: 'ETIMEDOUT' }, { address: 'fd00::1', family: 6, ok: true, ms: 5 }]); + const out = advise(d); + assert.match(out[0], /IPv4 addresses do not answer here; IPv6 does\. The CLI switches to IPv6 automatically/); + assert.match(out[1], /NODE_OPTIONS=--network-family-autoselection/); + assert.match(advise({ ...d, family_fallback: false })[0], /Remove --no-network-family-autoselection/); +}); + +test('advise suggests other sites when nothing answers, and reports a site that is not ready', () => { + const down = base([{ address: 'fd00::1', family: 6, ok: false, error: 'ENETUNREACH' }], { ok: false, ms: 1, error: 'ENETUNREACH' }); + assert.match(advise(down, ['sg-prod'])[0], /No address .* sourcegraph doctor --site sg-prod/); + assert.match(advise({ ...base([]), dns_error: 'ENOTFOUND' })[0], /does not resolve/); + const busy = base([{ address: '127.0.0.1', family: 4, ok: true, ms: 1 }], { ok: false, status: 503, ms: 1 }); + assert.match(advise(busy)[0], /HTTP 503/); + assert.deepEqual(advise(base([{ address: '127.0.0.1', family: 4, ok: true, ms: 1 }])), ['The site is reachable from here.']); +}); + +test('networkDetail lists every address that was tried', () => { + const cause = Object.assign(new AggregateError([Object.assign(new Error('a'), { address: '10.0.0.1', code: 'ETIMEDOUT' }), Object.assign(new Error('b'), { address: 'fd00::1', code: 'ENETUNREACH' })]), { code: 'ETIMEDOUT' }); + assert.equal(networkDetail(Object.assign(new TypeError('fetch failed'), { cause })), 'ETIMEDOUT (tried 10.0.0.1 ETIMEDOUT, fd00::1 ENETUNREACH)'); + assert.equal(networkDetail(Object.assign(new TypeError('fetch failed'), { cause: { code: 'UND_ERR_CONNECT_TIMEOUT' } })), 'UND_ERR_CONNECT_TIMEOUT'); +}); + +test('diagnose checks a live site end to end and the sign-in', async () => { + const server = createServer((req, res) => { res.statusCode = req.url === '/readyz' ? 200 : 404; res.end('ok'); }); + await new Promise(r => server.listen(0, '127.0.0.1', r)); + const url = `http://127.0.0.1:${(server.address() as any).port}`; + try { + const d = await diagnose(url, async () => ({ user: { name: 'u', role: 'user' } })); + assert.equal(d.addresses.length, 1); + assert.ok(d.addresses[0].ok); + assert.equal(d.https.status, 200); + assert.equal(d.sign_in?.user, 'u (user)'); + const bad = await diagnose(url, async () => { throw Object.assign(new Error('x'), { status: 401 }); }); + assert.match(bad.advice.join('\n'), /sourcegraph login/); + } finally { server.close(); } +}); + +// The client under Node (its fetch and errors differ from Bun's): bundle +// api.ts and run a scenario in a node process; it prints JSON. +async function underNode(scenario: string, env: Record): Promise { + const dir = mkdtempSync(join(tmpdir(), 'sg-net-')); + const built = spawnSync(process.execPath, ['build', fileURLToPath(new URL('api.ts', import.meta.url)), '--target', 'node', '--outdir', dir]); + assert.equal(built.status, 0, String(built.stderr)); + const script = `import { Client, ApiError } from ${JSON.stringify(join(dir, 'api.js'))};\nconst out = {};\ntry { ${scenario} } catch (e) { out.error = { code: e.code, unsent: e.unsent, message: e.message }; }\nconsole.log(JSON.stringify(out));`; + const file = join(dir, 'run.mjs'); + writeFileSync(file, script); + return new Promise((resolve, reject) => { + const p = spawn('node', [file], { env: { ...process.env, ...env } }); + let out = ''; + p.stdout.on('data', d => { out += d; }); + p.stderr.on('data', d => { out += d; }); + p.on('close', () => { try { resolve(JSON.parse(out.trim().split('\n').pop()!)); } catch { reject(new Error(out)); } }); + }); +} + +async function listen(handler: (req: any, res: any) => void) { + const server = createServer(handler); + await new Promise(r => server.listen(0, '127.0.0.1', r)); + return { url: `http://127.0.0.1:${(server.address() as any).port}`, close: () => server.close() }; +} + +async function deadUrl() { + const s = await listen(() => {}); + s.close(); // nobody listens there any more: connection refused + return s.url; +} + +test('a site that cannot be reached is switched to the other entry of the same service', async () => { + const seen: string[] = []; + const live = await listen((req, res) => { seen.push(`${req.method} ${req.url} ${req.headers.authorization || ''}`); res.setHeader('Content-Type', 'application/json'); res.end('{"ok":true}'); }); + const dead = await deadUrl(), dead2 = await deadUrl(); + try { + const r = await underNode(` + const switched = []; + const c = new Client(process.env.DEAD, undefined, { site: process.env.LIVE, token: 'sgk_alt', onSwitch: (to, why) => switched.push(to + ' ' + why) }); + out.first = await c.call('/v1/x', { body: { a: 1 } }); + await c.call('/v1/y'); + out.site = c.site; out.switched = switched; + const both = new Client(process.env.DEAD, undefined, { site: process.env.DEAD2 }); + try { await both.call('/v1/x'); } catch (e) { out.both = { code: e.code, message: e.message }; }`, { DEAD: dead, DEAD2: dead2, LIVE: live.url }); + assert.deepEqual(r.first, { ok: true }); + assert.equal(r.site, live.url); + assert.equal(r.switched.length, 1); + assert.match(r.switched[0], /ECONNREFUSED/); + assert.deepEqual(seen, ['POST /v1/x Bearer sgk_alt', 'GET /v1/y Bearer sgk_alt']); + assert.equal(r.both.code, 'NETWORK_ERROR'); + assert.match(r.both.message, /cannot be reached either/); + } finally { live.close(); } +}); + +test('a request the server may have received is never sent to the other entry', async () => { + let other = 0; + const drop = await listen(req => { req.socket.destroy(); }); + const live = await listen((_req, res) => { other++; res.end('{}'); }); + try { + const r = await underNode(`const c = new Client(process.env.DROP, undefined, { site: process.env.LIVE }); await c.call('/v1/x', { body: {} });`, { DROP: drop.url, LIVE: live.url }); + assert.equal(r.error.code, 'NETWORK_ERROR'); + assert.equal(r.error.unsent, false); + assert.equal(other, 0); + } finally { drop.close(); live.close(); } +}); diff --git a/cli/src/network.ts b/cli/src/network.ts new file mode 100644 index 0000000..01004f3 --- /dev/null +++ b/cli/src/network.ts @@ -0,0 +1,120 @@ +// Reaching a site over IPv4 or IPv6, and explaining why it cannot be reached. +import net from 'node:net'; +import { lookup } from 'node:dns/promises'; + +// Some networks reach a site over only one address family: private IPv4 +// addresses of another region are often not routed while IPv6 is. Node 20+ +// tries the next address (and family) when one does not answer within 250 ms; +// Node 18 waits on the first address until the connection times out. Turn the +// Node 20 behaviour on for Node 18 too, unless the user switched it off. +export function enableFamilyFallback(): void { + const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS || '').split(/\s+/)]; + if (flags.includes('--no-network-family-autoselection')) return; + if (typeof net.setDefaultAutoSelectFamily === 'function') net.setDefaultAutoSelectFamily(true); +} + +export function familyFallback(): boolean { + return typeof net.getDefaultAutoSelectFamily === 'function' ? net.getDefaultAutoSelectFamily() : false; +} + +// networkDetail names why a request failed: the error code and, when several +// addresses were tried, each address with its own error. +export function networkDetail(e: any): string { + if (e?.name === 'TimeoutError' || e?.name === 'AbortError') return 'no response in time'; + const c = e?.cause ?? e; + const tried = (c?.errors || []).filter((x: any) => x?.address).map((x: any) => `${x.address} ${x.code || x.message}`); + const code = c?.code || c?.message || e?.message || String(e); + return tried.length ? `${code} (tried ${tried.join(', ')})` : code; +} + +// unsent tells whether a failed request never reached the server: the name did +// not resolve or no connection could be opened. Only then is it safe to send +// the same request to another entry of the service. +export function unsent(e: any): boolean { + const c = e?.cause ?? e; + if (c?.code === 'UND_ERR_CONNECT_TIMEOUT') return true; + if (c instanceof AggregateError && Array.isArray(c.errors) && c.errors.every((x: any) => x?.syscall === 'connect' || x?.address)) return true; + return ['connect', 'getaddrinfo'].includes(c?.syscall) && ['ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(c?.code); +} + +export interface Probe { address: string; family: 4 | 6; ok: boolean; ms?: number; error?: string } +export interface Diagnosis { + site: string; node: string; family_fallback: boolean; + dns_error?: string; addresses: Probe[]; + https: { ok: boolean; status?: number; ms: number; error?: string }; + sign_in?: { ok: boolean; user?: string; error?: string; skipped?: boolean }; + alternate?: { site: string; ok: boolean; status?: number; error?: string }; + advice: string[]; +} + +// probe opens one TCP connection to one address, without falling back. +function probe(address: string, family: 4 | 6, port: number, timeout: number): Promise { + const started = Date.now(); + return new Promise(resolve => { + const s = net.connect({ host: address, port, autoSelectFamily: false } as net.NetConnectOpts); + const done = (p: Partial) => { s.destroy(); resolve({ address, family, ok: false, ...p }); }; + s.setTimeout(timeout, () => done({ error: 'ETIMEDOUT' })); + s.once('connect', () => done({ ok: true, ms: Date.now() - started })); + s.once('error', (e: any) => done({ error: e.code || e.message })); + }); +} + +// diagnose checks a site the way a request reaches it: name resolution, a TCP +// connection to each address, an HTTPS request and, with a token, the sign-in. +export async function diagnose(site: string, whoami?: () => Promise, otherSites: string[] = []): Promise { + const u = new URL(site), port = Number(u.port || (u.protocol === 'http:' ? 80 : 443)); + const d: Diagnosis = { site, node: process.version, family_fallback: familyFallback(), addresses: [], https: { ok: false, ms: 0 }, advice: [] }; + let found: { address: string; family: number }[] = []; + try { found = await lookup(u.hostname.replace(/^\[|\]$/g, ''), { all: true, verbatim: true }); } catch (e: any) { d.dns_error = e.code || e.message; } + d.addresses = await Promise.all(found.map(a => probe(a.address, a.family === 6 ? 6 : 4, port, 3000))); + const started = Date.now(); + try { + const r = await fetch(site + '/readyz', { signal: AbortSignal.timeout(15_000), redirect: 'manual', headers: { 'User-Agent': 'sourcegraph-cli' } }); + await r.arrayBuffer(); + d.https = { ok: r.ok, status: r.status, ms: Date.now() - started }; + } catch (e) { d.https = { ok: false, ms: Date.now() - started, error: networkDetail(e) }; } + if (whoami && !d.https.status) d.sign_in = { ok: false, skipped: true }; + else if (whoami) { + try { const me = await whoami(); d.sign_in = { ok: true, user: `${me.user.name} (${me.user.role})` }; } + catch (e: any) { d.sign_in = { ok: false, error: e.status === 401 ? 'the token is invalid or expired' : e.message }; } + } + d.advice = advise(d, otherSites); + return d; +} + +// advise turns a diagnosis into what to do next. +export function advise(d: Diagnosis, otherSites: string[] = []): string[] { + const out: string[] = []; + const by = (f: 4 | 6) => d.addresses.filter(a => a.family === f); + const up = (f: 4 | 6) => by(f).some(a => a.ok), down = (f: 4 | 6) => by(f).length > 0 && !up(f); + const others = otherSites.length ? ` Or try another site: ${otherSites.map(s => `sourcegraph doctor --site ${s}`).join(', ')}.` : ''; + if (d.dns_error) out.push(`The site name does not resolve on this network (${d.dns_error}). Check DNS, VPN or the office network.${others}`); + else if (!d.addresses.some(a => a.ok)) out.push(`No address of the site accepts connections from here. Check VPN, the office network or a firewall.${others}`); + else for (const [bad, good] of [[4, 6], [6, 4]] as const) { + if (!down(bad) || !up(good)) continue; + out.push(d.family_fallback + ? `IPv${bad} addresses do not answer here; IPv${good} does. The CLI switches to IPv${good} automatically.` + : `IPv${bad} addresses do not answer here; IPv${good} does. Remove --no-network-family-autoselection so the CLI can switch to IPv${good}.`); + out.push(`MCP clients and other programs connect on their own: on Node 20+ they switch the same way; on Node 18 set NODE_OPTIONS=--network-family-autoselection.`); + } + if (d.addresses.some(a => a.ok) && !d.https.ok) out.push(d.https.status + ? `The site answered HTTP ${d.https.status}: it is reachable but not ready; try again later or use another site.` + : `Connections open but the HTTPS request failed (${d.https.error}): a proxy or TLS inspection may be in the way.`); + if (d.alternate?.ok) out.unshift(`${d.alternate.site} answers from here: it is another entry of the same service, with the same data and tokens. Other commands switch to it automatically; to use it by default: sourcegraph config set site ${d.alternate.site}`); + if (d.sign_in && !d.sign_in.ok && !d.sign_in.skipped) out.push(`Sign-in: ${d.sign_in.error}. Sign in again with: sourcegraph login`); + if (!out.length) out.push('The site is reachable from here.'); + return out; +} + +export function diagnosisText(d: Diagnosis): string { + const lines = [`site ${d.site}`, `node ${d.node} · switch between IPv4 and IPv6: ${d.family_fallback ? 'on' : 'off'}`]; + if (d.dns_error) lines.push(`dns failed: ${d.dns_error}`); + else { + lines.push(`dns ${d.addresses.length} address${d.addresses.length === 1 ? '' : 'es'}`); + for (const a of d.addresses) lines.push(` IPv${a.family} ${a.address.padEnd(40)} ${a.ok ? `connects in ${a.ms} ms` : `fails: ${a.error}`}`); + } + lines.push(`https ${d.https.status ? `/readyz answered ${d.https.status}` : `failed: ${d.https.error}`} in ${d.https.ms} ms`); + if (d.alternate) lines.push(`same service ${d.alternate.site}: ${d.alternate.ok ? 'answers' : d.alternate.status ? `answered ${d.alternate.status}` : 'failed: ' + d.alternate.error}`); + lines.push(`sign-in ${!d.sign_in ? 'not signed in (public repositories only)' : d.sign_in.ok ? d.sign_in.user : d.sign_in.skipped ? 'not checked (the site cannot be reached)' : 'failed: ' + d.sign_in.error}`); + return [...lines, '', ...d.advice].join('\n'); +} diff --git a/cli/src/version.ts b/cli/src/version.ts index b6d55fa..ca24a8e 100644 --- a/cli/src/version.ts +++ b/cli/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.7.0'; +export const VERSION = '0.8.0'; diff --git a/scripts/deployment/cli-readme.md b/scripts/deployment/cli-readme.md index 846b2c0..4a35939 100644 --- a/scripts/deployment/cli-readme.md +++ b/scripts/deployment/cli-readme.md @@ -36,11 +36,14 @@ A token acts as its owner: it reads what you can read, manages repositories you | Tags | `tags`, `tags rename ` | | Site administration | `admin settings/users/role/credentials/query-errors/clear-jobs/cluster/instances/statistics/logs` | | MCP | `mcp` prints a client configuration | +| Connection | `doctor` checks DNS, each IPv4/IPv6 address, HTTPS and the sign-in, and says what to do | `sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` shows service logs of all instances (default: warnings and errors, last 24 hours). `sourcegraph read ` prints lines 1–200 by default; `--start N` alone reads 200 lines from line N, and `--start/--end` reads a range of up to 2000 lines per call. `--all` reads the whole file page by page at the commit of the first page, with continuous line numbers. It stops after 20000 lines and still exits 0: the command that continues is printed on stderr, and `--json` output keeps `HasMore: true` and `NextStartLine`. +Some networks reach a site over only IPv4 or only IPv6. When an address does not answer within 250 ms the CLI tries the next one, including the other family (on Node 18 too; the Node option `--no-network-family-autoselection` turns this off). If a command reports `NETWORK_ERROR`, `sourcegraph doctor` shows which addresses answer from this machine. MCP clients connect on their own: Node 20+ switches the same way; on Node 18 set `NODE_OPTIONS=--network-family-autoselection`. + Run `sourcegraph --help` for flags. `--json` prints the API's raw output; `--yes` skips confirmations. Repository settings use `key=value` (`sourcegraph repo set org/repo sync_interval_minutes=60 public_read=false`). Intervals under 30 minutes are for site administrators; others are raised to 30 minutes with a warning. `manual_updates=true` turns off automatic updates (scheduled checks); `tags=a,b` replaces the tags and `tags=` clears them. diff --git a/scripts/deployment/skill.md b/scripts/deployment/skill.md index caa9e56..1ca4c17 100644 --- a/scripts/deployment/skill.md +++ b/scripts/deployment/skill.md @@ -18,7 +18,7 @@ Sourcegraph indexes registered Git repositories so agents can search and read th ## Choose MCP or CLI 1. If `tools/list` shows `search`, `read` and friends from `{{mcp_server_name}}`, use MCP. With a token in the MCP configuration the server also offers `whoami`, `repository_register`, `repository_settings`, `repository_jobs`, `personal_settings`, `site_settings` and `site_admin`; without a token (or with `?tools=read`) only query tools exist. Never ask the user for a token inside the conversation: it belongs in the client configuration. -2. Otherwise use the CLI (Node 18+): `{{cli_install}}`. `sourcegraph --help` and `sourcegraph --help` list everything. Pick the site with `--site {{site_ids}}` or `--url
`; {{default_site_label}} is the default. +2. Otherwise use the CLI (Node 18.18+): `{{cli_install}}`. `sourcegraph --help` and `sourcegraph --help` list everything. Pick the site with `--site {{site_ids}}` or `--url
`; {{default_site_label}} is the default. 3. Sign-in: `sourcegraph login` prints a link and a code; the user approves it in the browser and the CLI stores a 90-day personal token for that site. In non-interactive environments use `SOURCEGRAPH_API_TOKEN`. Public repositories need no sign-in for queries. A token acts as its owner: it reads what the owner can read, manages repositories the owner manages, and administers the site only while the owner is a site administrator. A token can be narrowed to repositories with given tags and/or to non-public repositories (its visibility scope); repositories outside it answer `REPOSITORY_OUTSIDE_TOKEN_SCOPE`. Without a token, a registered repository that is not public answers `REPOSITORY_SIGN_IN_REQUIRED` and names managers who can make it public: tell the user to sign in (`sourcegraph login`) or configure a token, not that the repository is unregistered. Never print or log tokens. @@ -81,3 +81,4 @@ All changes go through the site API with the caller's permissions, exactly as on - `REVISION_NOT_SEARCHABLE` (search): the commit has no index and its files are not on the service. Search one of the commits the message lists, or the branch; do not retry the same commit. `SEARCH_BUSY` (search): scans are busy on that instance; retry once after Retry-After. - `INDEX_NOT_READY`, `SCOPE_NOT_READY`, `CONTENT_NOT_READY` (reads and other tools): the version is not prepared; prepare it if authorized, otherwise report it. To read, list or compare only, prepare its contents without an index (MCP `prepare` with `content_only: true`, or `sourcegraph jobs retry --kind content --commit SHA`), which is faster; search then scans its files. For indexed search use MCP `prepare` or `--kind index`. A reader who does not manage the repository may prepare contents only, of a full 40-character SHA (never a branch), when the site allows it (capabilities list `prepare-content-reader`): an already readable commit answers `stage: ready` with no job; `RATE_LIMITED` (`detail.scope` user or repository), `READER_PREPARE_FULL` and `REPOSITORY_STORAGE_BUSY` carry a retry time — wait for it once or report, do not loop. Without a token, MCP `prepare` answers `LOGIN_REQUIRED`: tell the user to sign in on the website, create a personal token and send it as `Authorization: Bearer `. - `SITE_FROZEN`: the site is read-only for maintenance; retry later. +- `NETWORK_ERROR` from the CLI, or MCP requests that time out: run `sourcegraph doctor` (with the same `--url`) and follow its advice; it checks DNS, a connection to each IPv4 and IPv6 address, HTTPS and the sign-in. Some networks reach a site over only IPv4 or only IPv6: the CLI switches family automatically; an MCP client on Node 18 needs `NODE_OPTIONS=--network-family-autoselection` (Node 20+ switches by itself). Do not edit the installed CLI or add Node flags to its launcher. If no address answers, report the doctor output. diff --git a/skills/sourcegraph/SKILL.md b/skills/sourcegraph/SKILL.md index a379ebf..b2a3c3e 100644 --- a/skills/sourcegraph/SKILL.md +++ b/skills/sourcegraph/SKILL.md @@ -18,7 +18,7 @@ Self-hosted deployments work the same way: use their address with --url or in th ## Choose MCP or CLI 1. If `tools/list` shows `search`, `read` and friends from `sourcegraph`, use MCP. With a token in the MCP configuration the server also offers `whoami`, `repository_register`, `repository_settings`, `repository_jobs`, `personal_settings`, `site_settings` and `site_admin`; without a token (or with `?tools=read`) only query tools exist. Never ask the user for a token inside the conversation: it belongs in the client configuration. -2. Otherwise use the CLI (Node 18+): `npm i -g @c4a/sourcegraph`. `sourcegraph --help` and `sourcegraph --help` list everything. Pick the site with `--site default` or `--url
`; Context4AI is the default. +2. Otherwise use the CLI (Node 18.18+): `npm i -g @c4a/sourcegraph`. `sourcegraph --help` and `sourcegraph --help` list everything. Pick the site with `--site default` or `--url
`; Context4AI is the default. 3. Sign-in: `sourcegraph login` prints a link and a code; the user approves it in the browser and the CLI stores a 90-day personal token for that site. In non-interactive environments use `SOURCEGRAPH_API_TOKEN`. Public repositories need no sign-in for queries. A token acts as its owner: it reads what the owner can read, manages repositories the owner manages, and administers the site only while the owner is a site administrator. A token can be narrowed to repositories with given tags and/or to non-public repositories (its visibility scope); repositories outside it answer `REPOSITORY_OUTSIDE_TOKEN_SCOPE`. Without a token, a registered repository that is not public answers `REPOSITORY_SIGN_IN_REQUIRED` and names managers who can make it public: tell the user to sign in (`sourcegraph login`) or configure a token, not that the repository is unregistered. Never print or log tokens. @@ -81,3 +81,4 @@ All changes go through the site API with the caller's permissions, exactly as on - `REVISION_NOT_SEARCHABLE` (search): the commit has no index and its files are not on the service. Search one of the commits the message lists, or the branch; do not retry the same commit. `SEARCH_BUSY` (search): scans are busy on that instance; retry once after Retry-After. - `INDEX_NOT_READY`, `SCOPE_NOT_READY`, `CONTENT_NOT_READY` (reads and other tools): the version is not prepared; prepare it if authorized, otherwise report it. To read, list or compare only, prepare its contents without an index (MCP `prepare` with `content_only: true`, or `sourcegraph jobs retry --kind content --commit SHA`), which is faster; search then scans its files. For indexed search use MCP `prepare` or `--kind index`. A reader who does not manage the repository may prepare contents only, of a full 40-character SHA (never a branch), when the site allows it (capabilities list `prepare-content-reader`): an already readable commit answers `stage: ready` with no job; `RATE_LIMITED` (`detail.scope` user or repository), `READER_PREPARE_FULL` and `REPOSITORY_STORAGE_BUSY` carry a retry time — wait for it once or report, do not loop. Without a token, MCP `prepare` answers `LOGIN_REQUIRED`: tell the user to sign in on the website, create a personal token and send it as `Authorization: Bearer `. - `SITE_FROZEN`: the site is read-only for maintenance; retry later. +- `NETWORK_ERROR` from the CLI, or MCP requests that time out: run `sourcegraph doctor` (with the same `--url`) and follow its advice; it checks DNS, a connection to each IPv4 and IPv6 address, HTTPS and the sign-in. Some networks reach a site over only IPv4 or only IPv6: the CLI switches family automatically; an MCP client on Node 18 needs `NODE_OPTIONS=--network-family-autoselection` (Node 20+ switches by itself). Do not edit the installed CLI or add Node flags to its launcher. If no address answers, report the doctor output.