Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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.8.0",
"version": "0.8.1",
"author": {
"name": "context4ai"
},
Expand Down
2 changes: 1 addition & 1 deletion cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ A token acts as its owner: it reads what you can read, manages repositories you

`sourcegraph read <repo> <path>` 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`.
Some networks reach a site over only IPv4 or only IPv6. An address is used only once its TLS handshake completes (certificate and host name verified): when one does not connect, or connects but never completes TLS, the CLI tries the next address after a second, alternating IPv4 and IPv6, and remembers the family that worked for that host in its configuration file. With a proxy that Node's fetch is told to use (`NODE_USE_ENV_PROXY=1`), requests go through the proxy instead. If a command reports `NETWORK_ERROR`, `sourcegraph doctor` shows which addresses answer from this machine. MCP clients connect on their own and keep the first address that connects: when doctor shows one family without TLS, start them with `NODE_OPTIONS=--dns-result-order=ipv6first` (or `ipv4first`).

Run `sourcegraph <command> --help` for flags. `--json` prints the API's raw output; `--yes` skips confirmations.

Expand Down
2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@c4a/sourcegraph",
"version": "0.8.0",
"version": "0.8.1",
"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",
Expand Down
5 changes: 3 additions & 2 deletions cli/src/api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { randomBytes } from 'node:crypto';
import { networkDetail, unsent } from './network.js';
import { request, Response, TransportOptions } from './transport.js';

// One HTTP API request; errors carry the server's code and message.
export class ApiError extends Error {
Expand All @@ -18,7 +19,7 @@ export interface Request {
export interface Alternate { site: string; token?: string; onSwitch?: (site: string, why: string) => void }

export class Client {
constructor(public site: string, public token?: string, private alternate?: Alternate) {}
constructor(public site: string, public token?: string, private alternate?: Alternate, private transport: TransportOptions = {}) {}

url(path: string, query?: Request['query']): string {
const u = new URL(this.site + path);
Expand Down Expand Up @@ -57,7 +58,7 @@ export class Client {
const timer = setTimeout(() => ctl.abort(), 60_000);
let res: Response;
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' });
res = await request(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 }, this.transport);
} catch (e: any) {
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); }
Expand Down
17 changes: 16 additions & 1 deletion cli/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,22 @@ const ALIASES: Record<string, string> = DEPLOYMENT.site_aliases || {};
export const DEFAULT_SITE = SITES[DEPLOYMENT.default_site] || trim(DEPLOYMENT.sites[0].url);
const SITE_IDS = DEPLOYMENT.sites.map(s => s.id);

export interface Config { site?: string; tokens?: Record<string, string> }
export interface Config { site?: string; tokens?: Record<string, string>; routes?: Record<string, { family: number; at: string }> }

// The address family (4 or 6) whose TLS handshake last completed for a host,
// so later commands try it first. Kept for a week; refreshed at most daily.
const ROUTE_TTL = 7 * 24 * 3600_000, ROUTE_REFRESH = 24 * 3600_000;
export const preferredFamily = {
get(host: string): number | undefined {
const r = loadConfig().routes?.[host];
return r && Date.now() - Date.parse(r.at) < ROUTE_TTL ? r.family : undefined;
},
set(host: string, family: number): void {
const c = loadConfig(), r = c.routes?.[host];
if (r && r.family === family && Date.now() - Date.parse(r.at) < ROUTE_REFRESH) return;
try { saveConfig({ ...c, routes: { ...(c.routes || {}), [host]: { family, at: new Date().toISOString() } } }); } catch { /* read-only home: just do not remember */ }
},
};

export function configPath(): string {
const base = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
Expand Down
6 changes: 3 additions & 3 deletions cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ 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, alternateSite } from './config.js';
import { SITES, DEFAULT_SITE, DEPLOYMENT, loadConfig, saveConfig, resolveSite, resolveToken, normalizeSite, siteName, configPath, alternateSite, preferredFamily } from './config.js';
import { settingsUpdate, parseAssignments, SETTING_KEYS } from './settings.js';
import { VERSION } from './version.js';
import { enableFamilyFallback, diagnose, diagnosisText, advise } from './network.js';
Expand Down Expand Up @@ -513,7 +513,7 @@ const C: Record<string, Command> = {
} },
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 d = await diagnose(ctx.site, ctx.client.token ? () => ctx.client.call('/auth/me') : undefined, others, { preferred: preferredFamily });
const alt = alternateSite(ctx.site);
if (alt && !d.https.ok) {
const a = (await diagnose(alt)).https;
Expand Down Expand Up @@ -556,7 +556,7 @@ export async function main(argv: string[]): Promise<number> {
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 };
} } : undefined, { preferred: preferredFamily }), json: jsonOutput, yes: !!o.yes };
print(await cmd.run(ctx, parsed.positionals.slice(1), o));
return 0;
} catch (e: any) {
Expand Down
12 changes: 12 additions & 0 deletions cli/src/network.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,15 @@ test('a request the server may have received is never sent to the other entry',
assert.equal(other, 0);
} finally { drop.close(); live.close(); }
});

test('advise names a family that connects but does not complete TLS', () => {
const d = base([
{ address: '10.0.0.1', family: 4, ok: true, ms: 5, tls: { ok: false, error: 'TLS_HANDSHAKE_TIMEOUT' } },
{ address: 'fd00::1', family: 6, ok: true, ms: 5, tls: { ok: true, ms: 20 } },
]);
const out = advise(d);
assert.match(out[0], /IPv4 addresses accept connections here but do not complete TLS; IPv6 does/);
assert.match(out[1], /--dns-result-order=ipv6first/);
const none = base([{ address: '10.0.0.1', family: 4, ok: true, ms: 5, tls: { ok: false, error: 'TLS_HANDSHAKE_TIMEOUT' } }], { ok: false, ms: 1, error: 'x' });
assert.match(advise(none, ['cn'])[0], /no address completes TLS.*sourcegraph doctor --site cn/);
});
52 changes: 43 additions & 9 deletions cli/src/network.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Reaching a site over IPv4 or IPv6, and explaining why it cannot be reached.
import net from 'node:net';
import tls from 'node:tls';
import { lookup } from 'node:dns/promises';
import { request, TransportOptions } from './transport.js';

// 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+
Expand Down Expand Up @@ -32,12 +34,12 @@ export function networkDetail(e: any): string {
// 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?.unsent === true || 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 Probe { address: string; family: 4 | 6; ok: boolean; ms?: number; error?: string; tls?: { ok: boolean; ms?: number; error?: string } }
export interface Diagnosis {
site: string; node: string; family_fallback: boolean;
dns_error?: string; addresses: Probe[];
Expand All @@ -47,6 +49,23 @@ export interface Diagnosis {
advice: string[];
}

// usable: the address completes what a request needs (TLS for https sites).
const usable = (a: Probe) => (a.tls ? a.tls.ok : a.ok);

// probeTLS completes a TLS handshake with one address for host name servername.
function probeTLS(address: string, port: number, servername: string, timeout: number, ca?: string | Buffer): Promise<NonNullable<Probe['tls']>> {
const started = Date.now();
return new Promise(resolve => {
const s = tls.connect({ host: address, port, servername, ca: ca ? [...tls.rootCertificates, String(ca)] : undefined, ALPNProtocols: ['http/1.1'] });
let tcp = false;
const done = (r: NonNullable<Probe['tls']>) => { s.destroy(); resolve(r); };
s.once('connect', () => { tcp = true; });
s.setTimeout(timeout, () => done({ ok: false, error: tcp ? 'TLS_HANDSHAKE_TIMEOUT' : 'ETIMEDOUT' }));
s.once('secureConnect', () => done({ ok: true, ms: Date.now() - started }));
s.once('error', (e: any) => done({ ok: false, error: e.code || e.message }));
});
}

// probe opens one TCP connection to one address, without falling back.
function probe(address: string, family: 4 | 6, port: number, timeout: number): Promise<Probe> {
const started = Date.now();
Expand All @@ -61,16 +80,21 @@ function probe(address: string, family: 4 | 6, port: number, timeout: number): P

// 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<any>, otherSites: string[] = []): Promise<Diagnosis> {
export async function diagnose(site: string, whoami?: () => Promise<any>, otherSites: string[] = [], transport: TransportOptions = {}): Promise<Diagnosis> {
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 host = u.hostname.replace(/^\[|\]$/g, '');
d.addresses = await Promise.all(found.map(async a => {
const p = await probe(a.address, a.family === 6 ? 6 : 4, port, 3000);
if (p.ok && u.protocol === 'https:') p.tls = await probeTLS(a.address, port, host, 5000, transport.ca);
return p;
}));
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();
const r = await request(site + '/readyz', { signal: AbortSignal.timeout(15_000), headers: { 'User-Agent': 'sourcegraph-cli' } }, transport);
await r.text();
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 };
Expand All @@ -86,18 +110,25 @@ export async function diagnose(site: string, whoami?: () => Promise<any>, otherS
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 up = (f: 4 | 6) => by(f).some(usable), down = (f: 4 | 6) => by(f).length > 0 && !up(f);
const tlsOnly = (f: 4 | 6) => by(f).some(a => a.ok && a.tls && !a.tls.ok);
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 if (!d.addresses.some(usable)) out.push(`Connections open but no address completes TLS: a proxy, firewall or TLS inspection is in the way.${others}`);
else for (const [bad, good] of [[4, 6], [6, 4]] as const) {
if (!down(bad) || !up(good)) continue;
if (tlsOnly(bad)) {
out.push(`IPv${bad} addresses accept connections here but do not complete TLS; IPv${good} does. The CLI uses IPv${good} automatically and remembers it.`);
out.push(`MCP clients and other programs keep the first address that connects: start them with NODE_OPTIONS=--dns-result-order=ipv${good}first (Node), or point them at another site that answers.`);
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
if (d.addresses.some(usable) && !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}`);
Expand All @@ -111,7 +142,10 @@ export function diagnosisText(d: Diagnosis): string {
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}`}`);
for (const a of d.addresses) {
const tlsText = !a.tls ? '' : a.tls.ok ? `, TLS in ${a.tls.ms} ms` : `, TLS fails: ${a.tls.error}`;
lines.push(` IPv${a.family} ${a.address.padEnd(40)} ${a.ok ? `connects in ${a.ms} ms${tlsText}` : `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}`);
Expand Down
Loading