agy-git-graph 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,167 @@
1
+ import {
2
+ copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync,
3
+ } from 'node:fs';
4
+ import { homedir, tmpdir } from 'node:os';
5
+ import { basename, join } from 'node:path';
6
+ import { DatabaseSync } from 'node:sqlite';
7
+ import { normalizeDirectory, validateRepo } from './git.mjs';
8
+
9
+ const AGY_DIR = join(homedir(), '.gemini', 'antigravity');
10
+ const SUMMARY_DB = join(AGY_DIR, 'conversation_summaries.db');
11
+ export const DATA_DIR = process.env.ANTIGRAVITY_EXECUTABLE_DATA_DIR ||
12
+ join(AGY_DIR, 'sidecar_data', 'agy-git-graph', 'git_graph');
13
+ const REPOS_FILE = join(DATA_DIR, 'repos.json');
14
+
15
+ function pathKey(path) {
16
+ return process.platform === 'win32' ? path.toLowerCase() : path;
17
+ }
18
+
19
+ function workspaceUris(raw) {
20
+ if (Array.isArray(raw)) return raw;
21
+ if (typeof raw !== 'string' || !raw) return [];
22
+ try {
23
+ const parsed = JSON.parse(raw);
24
+ if (Array.isArray(parsed)) return parsed;
25
+ if (typeof parsed === 'string') return [parsed];
26
+ } catch {
27
+ return [raw];
28
+ }
29
+ return [];
30
+ }
31
+
32
+ async function conversationDirectories() {
33
+ const address = process.env.ANTIGRAVITY_LS_ADDRESS;
34
+ if (!address) return [];
35
+ try {
36
+ const response = await fetch('http://' + address + '/product.v1.ConversationService/ListConversations', {
37
+ method: 'POST',
38
+ redirect: 'error',
39
+ signal: AbortSignal.timeout(5000),
40
+ headers: {
41
+ 'Content-Type': 'application/json',
42
+ 'Connect-Protocol-Version': '1',
43
+ 'x-antigravity-csrf-token': process.env.ANTIGRAVITY_CSRF_TOKEN || '',
44
+ },
45
+ body: JSON.stringify({ pageSize: 100, includeArchived: false }),
46
+ });
47
+ if (!response.ok) return [];
48
+ const { conversations = [] } = await response.json();
49
+ const time = (entry) => Date.parse(entry?.state?.lastModifiedTime || '') || 0;
50
+ return conversations.sort((left, right) => time(right) - time(left))
51
+ .flatMap((entry) => workspaceUris(entry?.metadata?.workspaceUris));
52
+ } catch {
53
+ return [];
54
+ }
55
+ }
56
+
57
+ function summaryDirectories() {
58
+ if (!existsSync(SUMMARY_DB)) return [];
59
+ let temp;
60
+ let db;
61
+ try {
62
+ temp = mkdtempSync(join(tmpdir(), 'agy-git-graph-db-'));
63
+ const snapshot = join(temp, basename(SUMMARY_DB));
64
+ for (const suffix of ['', '-wal', '-shm']) {
65
+ try {
66
+ copyFileSync(SUMMARY_DB + suffix, snapshot + suffix);
67
+ } catch (error) {
68
+ if (!suffix || error.code !== 'ENOENT') throw error;
69
+ }
70
+ }
71
+ db = new DatabaseSync(snapshot, { readOnly: true });
72
+ const rows = db.prepare(
73
+ 'SELECT workspace_uris, last_modified_time FROM conversation_summaries ' +
74
+ 'ORDER BY last_modified_time DESC LIMIT 200',
75
+ ).all();
76
+ return rows.flatMap((row) => workspaceUris(row.workspace_uris));
77
+ } catch {
78
+ return [];
79
+ } finally {
80
+ try {
81
+ db?.close();
82
+ } finally {
83
+ if (temp) rmSync(temp, { recursive: true, force: true, maxRetries: 3 });
84
+ }
85
+ }
86
+ }
87
+
88
+ function readCustomRepos() {
89
+ try {
90
+ const repos = JSON.parse(readFileSync(REPOS_FILE, 'utf8'));
91
+ if (!Array.isArray(repos)) throw new Error('repos.json must contain a list of repositories.');
92
+ return repos.map(normalizeDirectory).filter(Boolean);
93
+ } catch (error) {
94
+ if (error.code === 'ENOENT') return [];
95
+ throw error;
96
+ }
97
+ }
98
+
99
+ function saveCustomRepos(repos) {
100
+ mkdirSync(DATA_DIR, { recursive: true });
101
+ const temp = REPOS_FILE + '.' + process.pid + '.tmp';
102
+ try {
103
+ writeFileSync(temp, JSON.stringify(repos, null, 2) + '\n');
104
+ renameSync(temp, REPOS_FILE);
105
+ } finally {
106
+ rmSync(temp, { force: true });
107
+ }
108
+ }
109
+
110
+ function repoInfo(path, source, isCustom = source === 'custom') {
111
+ return { path, name: basename(path) || path, source, isCustom };
112
+ }
113
+
114
+ export async function discoverWorkspaces() {
115
+ const fromService = conversationDirectories();
116
+ const fromDatabase = summaryDirectories();
117
+ let custom = [];
118
+ try {
119
+ custom = readCustomRepos();
120
+ } catch {
121
+ // A damaged custom list should not hide the discovered workspaces.
122
+ }
123
+
124
+ const candidates = new Map();
125
+ for (const [dirs, source] of [[await fromService, 'conversation'], [fromDatabase, 'database'], [custom, 'custom']]) {
126
+ for (const raw of dirs) {
127
+ const path = normalizeDirectory(raw);
128
+ if (!path) continue;
129
+ const key = pathKey(path);
130
+ const prior = candidates.get(key);
131
+ if (!prior) candidates.set(key, repoInfo(path, source));
132
+ else if (source === 'custom') prior.isCustom = true;
133
+ }
134
+ }
135
+
136
+ const repos = new Map();
137
+ const ordered = [...candidates.values()];
138
+ // Bound simultaneous Git processes when the database contains many workspaces.
139
+ for (let offset = 0; offset < ordered.length; offset += 8) {
140
+ const batch = ordered.slice(offset, offset + 8);
141
+ const roots = await Promise.all(batch.map(({ path }) => validateRepo(path).catch(() => '')));
142
+ for (const [index, root] of roots.entries()) {
143
+ if (!root) continue;
144
+ const candidate = batch[index];
145
+ const key = pathKey(root);
146
+ const prior = repos.get(key);
147
+ if (!prior) repos.set(key, repoInfo(root, candidate.source, candidate.isCustom));
148
+ else if (candidate.isCustom) prior.isCustom = true;
149
+ }
150
+ }
151
+ return { repos: [...repos.values()] };
152
+ }
153
+
154
+ export async function addCustomRepo(dirPath) {
155
+ const root = await validateRepo(dirPath);
156
+ const custom = readCustomRepos();
157
+ if (!custom.some((path) => pathKey(path) === pathKey(root))) saveCustomRepos([...custom, root]);
158
+ return { repo: repoInfo(root, 'custom') };
159
+ }
160
+
161
+ export async function removeCustomRepo(repoPath) {
162
+ const root = await validateRepo(repoPath);
163
+ const custom = readCustomRepos();
164
+ const remaining = custom.filter((path) => pathKey(path) !== pathKey(root));
165
+ if (remaining.length !== custom.length) saveCustomRepos(remaining);
166
+ return { path: root, removed: remaining.length !== custom.length };
167
+ }
@@ -0,0 +1,131 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { createServer } from 'node:http';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { InputError } from './lib/git.mjs';
6
+ import { createHandlers } from './lib/handlers.mjs';
7
+
8
+ for (const stream of [process.stdout, process.stderr]) {
9
+ stream.on('error', (error) => {
10
+ if (error.code !== 'EPIPE') throw error;
11
+ });
12
+ }
13
+
14
+ const FONT_SETTINGS = join(homedir(), '.gemini', 'antigravity', 'sidecar_data',
15
+ 'agy-powertools', 'inspector', 'settings.json');
16
+ const BODY_LIMIT = 1024 * 1024;
17
+
18
+ function powertoolsFontCss() {
19
+ try {
20
+ const settings = JSON.parse(readFileSync(FONT_SETTINGS, 'utf8'));
21
+ const font = typeof settings.fontFamily === 'string' ? settings.fontFamily.replace(/["\\]/g, '').trim() : '';
22
+ const weight = Number(settings.fontWeight);
23
+ const rules = [];
24
+ if (font && font.length <= 128 && !/[;{}<>\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(font)) {
25
+ rules.push('--ui-font: "' + font + '", var(--ui-font-default);');
26
+ }
27
+ if (Number.isInteger(weight) && weight >= 1 && weight <= 1000) {
28
+ rules.push('--ui-font-weight: ' + weight + ';');
29
+ }
30
+ return rules.length ? ':root { ' + rules.join(' ') + ' }' : '';
31
+ } catch {
32
+ return '';
33
+ }
34
+ }
35
+
36
+ function renderHtml() {
37
+ return readFileSync(new URL('./index.html', import.meta.url), 'utf8')
38
+ .replace('/*__POWERTOOLS_FONT_CSS__*/', () => powertoolsFontCss());
39
+ }
40
+
41
+ function sendJson(response, code, data) {
42
+ response.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
43
+ response.end(JSON.stringify(data));
44
+ }
45
+
46
+ function readJson(request) {
47
+ return new Promise((resolve, reject) => {
48
+ const chunks = [];
49
+ let size = 0;
50
+ request.on('data', (chunk) => {
51
+ size += chunk.length;
52
+ if (size > BODY_LIMIT) {
53
+ chunks.length = 0;
54
+ reject(new InputError('JSON body exceeds 1 MB.'));
55
+ } else {
56
+ chunks.push(chunk);
57
+ }
58
+ });
59
+ request.on('error', reject);
60
+ request.on('end', () => {
61
+ if (size > BODY_LIMIT) return;
62
+ try {
63
+ const data = size ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {};
64
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error();
65
+ resolve(data);
66
+ } catch {
67
+ reject(new InputError('Expected a JSON object.'));
68
+ }
69
+ });
70
+ });
71
+ }
72
+
73
+ function runStandalone(handlers) {
74
+ const portOption = process.argv.indexOf('--port');
75
+ const portValue = portOption === -1 ? '0' : process.argv[portOption + 1] || '';
76
+ const port = Number(portValue);
77
+ if (!/^\d+$/.test(portValue) || !Number.isInteger(port) || port < 0 || port > 65535) {
78
+ throw new Error('Use --port with a port number from 0 to 65535.');
79
+ }
80
+
81
+ const server = createServer(async (request, response) => {
82
+ try {
83
+ const expectedHost = '127.0.0.1:' + server.address().port;
84
+ if (request.headers.host !== expectedHost ||
85
+ (request.headers.origin && request.headers.origin !== 'http://' + expectedHost)) {
86
+ throw new InputError('Expected a local request.');
87
+ }
88
+ const route = new URL(request.url, 'http://' + expectedHost).pathname;
89
+ if (request.method === 'GET' && route === '/') {
90
+ const html = renderHtml();
91
+ response.writeHead(200, {
92
+ 'Content-Type': 'text/html; charset=utf-8',
93
+ 'Cache-Control': 'no-store',
94
+ 'X-Frame-Options': 'DENY',
95
+ });
96
+ response.end(html);
97
+ } else if (route.startsWith('/api/') && request.method === 'POST' && Object.hasOwn(handlers, route)) {
98
+ const type = (request.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
99
+ if (type !== 'application/json') throw new InputError('Use Content-Type: application/json.');
100
+ if (Number(request.headers['content-length']) > BODY_LIMIT) {
101
+ request.resume();
102
+ throw new InputError('JSON body exceeds 1 MB.');
103
+ }
104
+ const data = await readJson(request);
105
+ sendJson(response, 200, await handlers[route](data));
106
+ } else {
107
+ sendJson(response, 400, { ok: false, error: 'Unknown route or HTTP method.' });
108
+ }
109
+ } catch (error) {
110
+ sendJson(response, error instanceof InputError ? 400 : 500, { ok: false, error: error.message });
111
+ }
112
+ });
113
+
114
+ const shutdown = () => server.close();
115
+ process.once('SIGINT', shutdown);
116
+ process.once('SIGTERM', shutdown);
117
+ server.listen(port, '127.0.0.1', () => {
118
+ process.stdout.write('READY http://127.0.0.1:' + server.address().port + '\n');
119
+ });
120
+ }
121
+
122
+ const handlers = createHandlers();
123
+ if (process.argv.includes('--standalone')) {
124
+ runStandalone(handlers);
125
+ } else {
126
+ const { SidecarApp } = await import('sidecar_sdk');
127
+ const app = new SidecarApp();
128
+ app.page('/', () => renderHtml());
129
+ for (const [route, handler] of Object.entries(handlers)) app.api(route, handler);
130
+ app.run();
131
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "command": "node",
3
+ "args": ["server.mjs"],
4
+ "restart_policy": "always",
5
+ "display_name": "Git Graph",
6
+ "description": "Inspect Git working-tree changes, commit changes, view diffs, and browse a multi-branch SVG commit graph in the right side pane.",
7
+ "has_web_ui": true,
8
+ "agent_permissions": {
9
+ "allows_user_interactions": false
10
+ },
11
+ "ui_config": {
12
+ "display_name": "Git Graph",
13
+ "views": [
14
+ {
15
+ "path": "/",
16
+ "entrypoint": "SIDECAR_UI_ENTRYPOINT_AUX_PANE",
17
+ "title": "Git"
18
+ }
19
+ ]
20
+ }
21
+ }
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: agy-git-graph
3
+ description: Open the Git Graph side panel in Antigravity to inspect working-tree changes, stage/commit files, filter branches, and browse an interactive multi-branch SVG commit graph and commit diffs. Use when the user asks to view the git graph, git commit tree, git lines, or open the Git Graph panel.
4
+ ---
5
+
6
+ # Git Graph (提交图)
7
+
8
+ When the user wants to view the Git commit graph, branch lines, working-tree changes, or diffs in the Antigravity side panel, surface the one-click pill:
9
+
10
+ `[Git Graph](sidecar://agy-git-graph/git_graph/)`