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.7.0",
"version": "0.8.0",
"author": {
"name": "context4ai"
},
Expand Down
3 changes: 3 additions & 0 deletions cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,14 @@ A token acts as its owner: it reads what you can read, manages repositories you
| Tags | `tags`, `tags rename <old> <new>` |
| 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 <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`.

Run `sourcegraph <command> --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.
Expand Down
4 changes: 2 additions & 2 deletions cli/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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)\"",
Expand Down
33 changes: 30 additions & 3 deletions cli/src/api.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -13,16 +14,42 @@ 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);
for (const [k, v] of Object.entries(query || {})) if (v !== undefined && v !== '') u.searchParams.set(k, String(v));
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<T = any>(path: string, req: Request = {}): Promise<T> {
try { return await this.send<T>(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<T>(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<T>(path: string, req: Request): Promise<T> {
const headers: Record<string, string> = { 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';
Expand All @@ -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;
Expand Down
16 changes: 15 additions & 1 deletion cli/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>; public_url?: string;
site_notice?: { site: string; recommend: string; cli?: string };
Expand Down Expand Up @@ -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);
Expand Down
34 changes: 27 additions & 7 deletions cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any>;
interface Ctx { client: Client; site: string; json: boolean; yes: boolean }
Expand Down Expand Up @@ -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 ----------
Expand Down Expand Up @@ -510,6 +511,19 @@ const C: Record<string, Command> = {
}
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 <your token: sourcegraph tokens create mcp>' } } : {}) } } };
Expand All @@ -524,6 +538,7 @@ function help(name?: string): string {
}

export async function main(argv: string[]): Promise<number> {
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;
Expand All @@ -537,13 +552,18 @@ export async function main(argv: string[]): Promise<number> {
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 <id> --all-tags --include-public');
if (jsonOutput && e.body) console.log(JSON.stringify(e.body, null, 2));
} else console.error('error: ' + (e?.message || e));
Expand Down
Loading