dsh-taskbridge 1.8.1 → 1.9.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +751 -733
  3. package/antigravity/agents/dsh-taskbridge.md +14 -12
  4. package/antigravity/skills/dsh-taskbridge/SKILL.md +32 -19
  5. package/bin/dsh-delegate-codex-agent.js +9 -4
  6. package/codex/skills/dsh-taskbridge/SKILL.md +131 -0
  7. package/codex/skills/dsh-taskbridge/rules-reference-96027c387cb9b7587efa4aa3836235d86db1108068e007dc08196e807ca25e5d.md +114 -0
  8. package/docs/INTRODUCTION.md +148 -122
  9. package/docs/INTRODUCTION.zh.md +151 -134
  10. package/docs/antigravity-integration.md +47 -42
  11. package/docs/assets/taskbridge-workflow.en.svg +72 -0
  12. package/docs/assets/taskbridge-workflow.zh.png +0 -0
  13. package/docs/claude-code.md +18 -18
  14. package/docs/codex-integration.md +139 -113
  15. package/docs/releases/1.8.0.zh.md +16 -16
  16. package/docs/releases/1.8.1.zh.md +24 -24
  17. package/docs/releases/1.9.0.zh.md +31 -0
  18. package/docs/runtime-compatibility.md +7 -9
  19. package/docs/silent-wait.md +17 -26
  20. package/docs/taskbridge-upgrade.md +4 -4
  21. package/lib/client.d.ts +2 -2
  22. package/lib/client.js +7 -7
  23. package/locale/en.json +7 -7
  24. package/locale/zh.json +7 -7
  25. package/package.json +10 -4
  26. package/src/antigravity/installer.js +1099 -1068
  27. package/src/antigravity/seam.js +142 -142
  28. package/src/client/api.js +135 -13
  29. package/src/client/index.jsx +19 -18
  30. package/src/codex/agent-ownership.js +72 -12
  31. package/src/codex/installer.js +688 -268
  32. package/src/http/execution-plane.js +17 -0
  33. package/src/http/user-plane.js +6 -0
  34. package/src/index.d.ts +9 -1
  35. package/src/index.js +86 -64
  36. package/src/jobs/engine.js +278 -5
  37. package/src/jobs/history.js +17 -1
  38. package/src/jobs/record-cleanup.js +715 -641
  39. package/src/mcp/server.js +241 -12
  40. package/src/runtime/permissions.js +18 -0
  41. package/src/runtime/worker-prompt.js +13 -9
  42. package/codex/dsh-taskbridge.toml +0 -181
@@ -1,1068 +1,1099 @@
1
- // Antigravity integration: install the self-contained DSH TaskBridge plugin bundle
2
- // into `<ANTIGRAVITY_CONFIG_DIR>/plugins/dsh-taskbridge/` (default `~/.gemini/config`).
3
- //
4
- // Everything lives inside that single plugin directory so Antigravity can toggle or
5
- // uninstall it cleanly without touching `~/.gemini/config/mcp_config.json` or
6
- // `~/.gemini/config/config.json`:
7
- //
8
- // plugins/dsh-taskbridge/
9
- // ├── plugin.json
10
- // ├── mcp_config.json
11
- // ├── assets/logo.svg
12
- // ├── skills/dsh-taskbridge/SKILL.md
13
- // └── agents/dsh-taskbridge.md
14
- //
15
- // Safety and ownership mirror `src/codex/installer.js`:
16
- // * `status` is strictly read-only and never creates directories or files;
17
- // * root symlink/junction is resolved and pinned once; links inside the plugin
18
- // tree are refused as `conflict`;
19
- // * ownership is proved by content digest (current template or recorded managed
20
- // digest for this home) rather than by filename alone, so operator-edited
21
- // skills, agents or MCP entries are preserved and never overwritten or deleted;
22
- // * `install` manages both the plugin files and `mcp_config.json`, `repair` fixes
23
- // MCP (plus a missing/outdated `plugin.json` manifest only) without touching
24
- // skills or agents, and `remove` deletes only verified plugin-managed files;
25
- // * startup refresh updates already-installed, unmodified outdated files in place
26
- // and never performs a first install.
27
-
28
- import { createHash } from 'node:crypto';
29
- import { lstat, mkdir, readdir, readFile, realpath, rmdir, unlink } from 'node:fs/promises';
30
- import { homedir } from 'node:os';
31
- import { dirname, isAbsolute, join, resolve } from 'node:path';
32
- import { fileURLToPath } from 'node:url';
33
-
34
- import { writeFileAtomic } from '../config/store.js';
35
- import { digestLf, pluginDataDirectory } from '../codex/agent-ownership.js';
36
- import {
37
- DISCOVERY_ENV_VAR,
38
- MCP_ENTRY_RELATIVE,
39
- digest,
40
- inspectDirectory,
41
- isNodeExecutableName,
42
- isOwnedEntryScript,
43
- resolveNodeExecutable,
44
- useDirectoryClassifier,
45
- } from '../codex/installer.js';
46
- import { resolveDefaultEndpointDiscoveryPath, resolveEndpointDiscoveryPath } from '../runtime/endpoint-discovery.js';
47
-
48
- function sameFsPath(left, right) {
49
- if (typeof left !== 'string' || typeof right !== 'string') return false;
50
- const a = resolve(left);
51
- const b = resolve(right);
52
- return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
53
- }
54
-
55
- export const ANTIGRAVITY_PLUGIN_NAME = 'dsh-taskbridge';
56
- export const ANTIGRAVITY_MCP_SERVER_NAME = 'dsh-taskbridge';
57
- export const ANTIGRAVITY_ACTIONS = Object.freeze(['status', 'install', 'repair', 'remove']);
58
-
59
- export const ANTIGRAVITY_PLUGIN_STATES = Object.freeze({
60
- missing: 'not-installed',
61
- installed: 'installed',
62
- outdated: 'outdated',
63
- modified: 'modified',
64
- conflict: 'conflict',
65
- });
66
-
67
- export const ANTIGRAVITY_MCP_STATES = Object.freeze({
68
- missing: 'not-configured',
69
- configured: 'configured',
70
- outdated: 'outdated',
71
- conflict: 'conflict',
72
- unreadable: 'unreadable',
73
- });
74
-
75
- export const ANTIGRAVITY_ENV_VARS = Object.freeze(['ANTIGRAVITY_CONFIG_DIR', 'GEMINI_CONFIG_DIR']);
76
-
77
- const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
78
- const PACKAGE_MANIFEST_PATH = join(PACKAGE_ROOT, 'package.json');
79
- const SKILL_TEMPLATE_PATH = join(PACKAGE_ROOT, 'antigravity', 'skills', 'dsh-taskbridge', 'SKILL.md');
80
- const AGENT_TEMPLATE_PATH = join(PACKAGE_ROOT, 'antigravity', 'agents', 'dsh-taskbridge.md');
81
- const LOGO_TEMPLATE_PATH = join(PACKAGE_ROOT, 'icon.svg');
82
-
83
- const PLUGIN_FILE_KEYS = Object.freeze([
84
- 'plugin.json',
85
- 'skills/dsh-taskbridge/SKILL.md',
86
- 'agents/dsh-taskbridge.md',
87
- 'assets/logo.svg',
88
- ]);
89
-
90
- const MCP_FILE_KEY = 'mcp_config.json';
91
- const OWNERSHIP_DIR_NAME = 'antigravity-plugin-ownership';
92
- const OWNERSHIP_SCHEMA_VERSION = 1;
93
- const MAX_FILE_BYTES = 1024 * 1024;
94
- const MAX_OWNERSHIP_BYTES = 8192;
95
- const SHA256_RE = /^[0-9a-f]{64}$/u;
96
-
97
- const ALLOWED_MCP_ENTRY_KEYS = new Set(['command', 'args', 'env']);
98
-
99
- export class AntigravityInstallError extends Error {
100
- constructor(code, message, details = {}) {
101
- super(message);
102
- this.name = 'AntigravityInstallError';
103
- this.code = code;
104
- this.details = details;
105
- }
106
- }
107
-
108
- export { useDirectoryClassifier };
109
-
110
- function normalizeLf(text) {
111
- return String(text ?? '').replace(/\r\n/gu, '\n');
112
- }
113
-
114
- function sameTextLf(left, right) {
115
- if (left === right) return true;
116
- const a = normalizeLf(left);
117
- const b = normalizeLf(right);
118
- if (a.includes('\r') || b.includes('\r')) return false;
119
- return a === b;
120
- }
121
-
122
- export function resolveAntigravityHome({ env = process.env, homeDirectory = homedir() } = {}) {
123
- for (const key of ANTIGRAVITY_ENV_VARS) {
124
- const configured = typeof env?.[key] === 'string' ? env[key].trim() : '';
125
- if (configured !== '') {
126
- if (!isAbsolute(configured)) {
127
- throw new AntigravityInstallError('ANTIGRAVITY_HOME_INVALID', `${key} must be an absolute path`);
128
- }
129
- return resolve(configured);
130
- }
131
- }
132
- return resolve(join(homeDirectory, '.gemini', 'config'));
133
- }
134
-
135
- export function requireAntigravityHome(antigravityHome) {
136
- if (typeof antigravityHome !== 'string' || antigravityHome.trim() === '' || !isAbsolute(antigravityHome)) {
137
- throw new AntigravityInstallError('ANTIGRAVITY_HOME_INVALID', 'the Antigravity config directory must be an absolute path');
138
- }
139
- return resolve(antigravityHome);
140
- }
141
-
142
- async function readPackageVersion() {
143
- try {
144
- const manifest = JSON.parse(await readFile(PACKAGE_MANIFEST_PATH, 'utf8'));
145
- return typeof manifest.version === 'string' ? manifest.version : '';
146
- } catch {
147
- return '';
148
- }
149
- }
150
-
151
- export function renderAntigravityManifest(version) {
152
- const manifest = {
153
- name: ANTIGRAVITY_PLUGIN_NAME,
154
- displayName: 'DSH TaskBridge',
155
- version: version || '0.0.0',
156
- description: '通过 DSH TaskBridge MCP 服务向 DeepSeek Harness 派工,支持先定方案后派工、后台静默等待、逐次权限审批与集中审查验收。',
157
- logo: 'assets/logo.svg',
158
- suggestedPrompts: [
159
- '把当前仓库的功能修改交给 DSH TaskBridge 执行并在交付后审查',
160
- '检查 DSH TaskBridge 本机调用状态和当前工作区预检结果',
161
- '把多阶段目标拆成 TaskBridge 任务树并按顺序派给 DSH 执行',
162
- ],
163
- };
164
- return `${JSON.stringify(manifest, null, 2)}\n`;
165
- }
166
-
167
- export async function readAntigravityTemplates(versionOverride = null) {
168
- const version = typeof versionOverride === 'string' && versionOverride.trim() !== ''
169
- ? versionOverride.trim()
170
- : await readPackageVersion();
171
- const [skill, agent, logo] = await Promise.all([
172
- readFile(SKILL_TEMPLATE_PATH, 'utf8'),
173
- readFile(AGENT_TEMPLATE_PATH, 'utf8'),
174
- readFile(LOGO_TEMPLATE_PATH, 'utf8'),
175
- ]);
176
- return {
177
- version,
178
- files: {
179
- 'plugin.json': renderAntigravityManifest(version),
180
- 'skills/dsh-taskbridge/SKILL.md': normalizeLf(skill),
181
- 'agents/dsh-taskbridge.md': normalizeLf(agent),
182
- 'assets/logo.svg': normalizeLf(logo),
183
- },
184
- };
185
- }
186
-
187
- function pluginPathsFor(realHome) {
188
- const pluginsDir = join(realHome, 'plugins');
189
- const pluginDir = join(pluginsDir, ANTIGRAVITY_PLUGIN_NAME);
190
- return {
191
- pluginsDir,
192
- pluginDir,
193
- files: {
194
- 'plugin.json': join(pluginDir, 'plugin.json'),
195
- 'skills/dsh-taskbridge/SKILL.md': join(pluginDir, 'skills', 'dsh-taskbridge', 'SKILL.md'),
196
- 'agents/dsh-taskbridge.md': join(pluginDir, 'agents', 'dsh-taskbridge.md'),
197
- 'assets/logo.svg': join(pluginDir, 'assets', 'logo.svg'),
198
- },
199
- mcpPath: join(pluginDir, MCP_FILE_KEY),
200
- dirs: [
201
- pluginsDir,
202
- pluginDir,
203
- join(pluginDir, 'skills'),
204
- join(pluginDir, 'skills', 'dsh-taskbridge'),
205
- join(pluginDir, 'agents'),
206
- join(pluginDir, 'assets'),
207
- ],
208
- };
209
- }
210
-
211
- function ownershipPathFor(realHome, env = process.env) {
212
- const dataDir = pluginDataDirectory(env);
213
- if (dataDir === null) return null;
214
- const key = createHash('sha256').update(resolve(realHome), 'utf8').digest('hex');
215
- return join(dataDir, OWNERSHIP_DIR_NAME, `${key}.json`);
216
- }
217
-
218
- async function readOwnershipRecord(realHome, env = process.env) {
219
- const path = ownershipPathFor(realHome, env);
220
- if (path === null) return null;
221
- try {
222
- const info = await lstat(path);
223
- if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_OWNERSHIP_BYTES) return null;
224
- const parsed = JSON.parse(await readFile(path, 'utf8'));
225
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
226
- if (parsed.schemaVersion !== OWNERSHIP_SCHEMA_VERSION) return null;
227
- if (typeof parsed.antigravityHome !== 'string' || resolve(parsed.antigravityHome) !== resolve(realHome)) return null;
228
- if (parsed.files === null || typeof parsed.files !== 'object' || Array.isArray(parsed.files)) return null;
229
- const files = {};
230
- for (const [k, v] of Object.entries(parsed.files)) {
231
- if (typeof v === 'string' && SHA256_RE.test(v)) files[k] = v;
232
- }
233
- return { path, files };
234
- } catch {
235
- return null;
236
- }
237
- }
238
-
239
- async function writeOwnershipRecord(realHome, pluginDir, fileDigests, env = process.env) {
240
- const path = ownershipPathFor(realHome, env);
241
- if (path === null) return false;
242
- try {
243
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
244
- const record = {
245
- schemaVersion: OWNERSHIP_SCHEMA_VERSION,
246
- antigravityHome: resolve(realHome),
247
- pluginDir: resolve(pluginDir),
248
- files: fileDigests,
249
- };
250
- await writeFileAtomic(path, `${JSON.stringify(record, null, 2)}\n`);
251
- return true;
252
- } catch {
253
- return false;
254
- }
255
- }
256
-
257
- async function pinAntigravityHome(selected) {
258
- const info = await inspectDirectory(selected).catch(() => ({ kind: 'unknown' }));
259
- if (info.kind === 'missing' || info.kind === 'directory' || info.kind === 'unknown') {
260
- return { selected, real: selected, linked: false, linkTarget: null, error: null };
261
- }
262
- if (info.kind === 'link') {
263
- let resolved;
264
- try {
265
- resolved = await realpath(selected);
266
- } catch {
267
- return {
268
- selected,
269
- real: selected,
270
- linked: true,
271
- linkTarget: info.target ?? null,
272
- error: {
273
- code: 'ANTIGRAVITY_HOME_UNUSABLE',
274
- reason: 'antigravity-home-link-unresolvable',
275
- message: 'the Antigravity config directory link cannot be resolved to a real directory',
276
- },
277
- };
278
- }
279
- const targetInfo = await inspectDirectory(resolved).catch(() => ({ kind: 'unknown' }));
280
- if (targetInfo.kind !== 'directory') {
281
- return {
282
- selected,
283
- real: resolved,
284
- linked: true,
285
- linkTarget: info.target ?? null,
286
- error: {
287
- code: 'ANTIGRAVITY_HOME_UNUSABLE',
288
- reason: 'antigravity-home-target-not-a-directory',
289
- message: 'the Antigravity config directory link does not point at a real directory',
290
- },
291
- };
292
- }
293
- return { selected, real: resolved, linked: true, linkTarget: info.target ?? null, error: null };
294
- }
295
- return {
296
- selected,
297
- real: selected,
298
- linked: false,
299
- linkTarget: null,
300
- error: {
301
- code: 'ANTIGRAVITY_HOME_UNUSABLE',
302
- reason: 'antigravity-home-not-a-directory',
303
- message: 'the Antigravity config path exists but is not a directory',
304
- },
305
- };
306
- }
307
-
308
- async function inspectFileSafe(path) {
309
- let info;
310
- try {
311
- info = await lstat(path);
312
- } catch (error) {
313
- if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return { kind: 'missing' };
314
- throw error;
315
- }
316
- if (info.isSymbolicLink()) return { kind: 'link' };
317
- if (!info.isFile()) return { kind: 'other' };
318
- if (info.size > MAX_FILE_BYTES) return { kind: 'other' };
319
- return { kind: 'file', contents: await readFile(path, 'utf8') };
320
- }
321
-
322
- async function inspectBoundaries(realHome, paths) {
323
- const rootInfo = await inspectDirectory(realHome).catch(() => ({ kind: 'unknown' }));
324
- if (rootInfo.kind !== 'missing' && rootInfo.kind !== 'directory') {
325
- return { ok: false, reason: rootInfo.kind === 'unknown' ? 'boundary-unverified' : 'antigravity-home-invalid', path: realHome };
326
- }
327
- for (const dir of paths.dirs) {
328
- const info = await inspectDirectory(dir).catch(() => ({ kind: 'unknown' }));
329
- if (info.kind === 'missing' || info.kind === 'directory') continue;
330
- return {
331
- ok: false,
332
- reason: info.kind === 'link' ? 'plugin-dir-is-link' : (info.kind === 'unknown' ? 'boundary-unverified' : 'plugin-dir-not-a-directory'),
333
- path: dir,
334
- };
335
- }
336
- return { ok: true, reason: null, path: null };
337
- }
338
-
339
- function desiredMcpConfig(options = {}) {
340
- const env = options.env ?? process.env;
341
- const script = resolve(join(PACKAGE_ROOT, MCP_ENTRY_RELATIVE));
342
- let node = null;
343
- let nodeError = null;
344
- try {
345
- node = typeof options.nodeExecutable === 'string' && options.nodeExecutable.trim() !== ''
346
- ? resolve(options.nodeExecutable)
347
- : resolveNodeExecutable({ env, execPath: options.execPath, resourcesPath: options.resourcesPath, versions: options.versions, platform: options.platform });
348
- } catch (error) {
349
- nodeError = {
350
- code: typeof error?.code === 'string' ? error.code : 'MCP_EXECUTABLE_UNRESOLVED',
351
- message: String(error?.message ?? 'no Node.js executable could be proved'),
352
- };
353
- }
354
- let discoveryFile = null;
355
- if (typeof options.discoveryFile === 'string' && options.discoveryFile.trim() !== '') {
356
- discoveryFile = resolve(options.discoveryFile);
357
- } else {
358
- const resolved = resolveEndpointDiscoveryPath(env);
359
- const defaultPath = resolveDefaultEndpointDiscoveryPath(env);
360
- if (resolved !== undefined && !sameFsPath(resolved, defaultPath)) {
361
- discoveryFile = resolve(resolved);
362
- }
363
- }
364
- const serverEntry = node === null ? null : {
365
- command: node,
366
- args: [script],
367
- ...(discoveryFile === null ? {} : { env: { [DISCOVERY_ENV_VAR]: discoveryFile } }),
368
- };
369
- return { node, nodeError, script, discoveryFile, serverEntry };
370
- }
371
-
372
- function renderMcpDocument(existingDoc, serverEntry) {
373
- const base = existingDoc !== null && typeof existingDoc === 'object' && !Array.isArray(existingDoc)
374
- ? { ...existingDoc }
375
- : {};
376
- const servers = base.mcpServers !== null && typeof base.mcpServers === 'object' && !Array.isArray(base.mcpServers)
377
- ? { ...base.mcpServers }
378
- : {};
379
- servers[ANTIGRAVITY_MCP_SERVER_NAME] = serverEntry;
380
- base.mcpServers = servers;
381
- return `${JSON.stringify(base, null, 2)}\n`;
382
- }
383
-
384
- function sameMcpEnv(actualEnv, desiredEnv) {
385
- const a = actualEnv === undefined ? null : actualEnv;
386
- const b = desiredEnv === undefined ? null : desiredEnv;
387
- if (a === null && b === null) return true;
388
- if (a === null || b === null) return false;
389
- if (typeof a !== 'object' || Array.isArray(a)) return false;
390
- const aKeys = Object.keys(a);
391
- const bKeys = Object.keys(b);
392
- if (aKeys.length !== bKeys.length) return false;
393
- return aKeys.every((key) => typeof a[key] === 'string' && typeof b[key] === 'string' && sameFsPath(a[key], b[key]));
394
- }
395
-
396
- function isManagedMcpShape(entry) {
397
- if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return false;
398
- for (const key of Object.keys(entry)) {
399
- if (!ALLOWED_MCP_ENTRY_KEYS.has(key)) return false;
400
- }
401
- if (typeof entry.command !== 'string' || !isNodeExecutableName(entry.command)) return false;
402
- if (!Array.isArray(entry.args) || entry.args.length !== 1 || typeof entry.args[0] !== 'string') return false;
403
- if (entry.env !== undefined) {
404
- if (entry.env === null || typeof entry.env !== 'object' || Array.isArray(entry.env)) return false;
405
- const keys = Object.keys(entry.env);
406
- if (keys.some((key) => key !== DISCOVERY_ENV_VAR || typeof entry.env[key] !== 'string')) return false;
407
- }
408
- return true;
409
- }
410
-
411
- async function classifyMcpFile({ mcpPath, desired, recordedDigest }) {
412
- const file = await inspectFileSafe(mcpPath);
413
- if (file.kind === 'missing') {
414
- return {
415
- path: mcpPath,
416
- state: ANTIGRAVITY_MCP_STATES.missing,
417
- configured: false,
418
- managed: true,
419
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
420
- script: desired.script,
421
- node: desired.node,
422
- nodeResolved: desired.node !== null,
423
- nodeError: desired.nodeError,
424
- reason: null,
425
- existingDoc: null,
426
- expectDigest: null,
427
- };
428
- }
429
- if (file.kind !== 'file') {
430
- return {
431
- path: mcpPath,
432
- state: ANTIGRAVITY_MCP_STATES.conflict,
433
- configured: false,
434
- managed: false,
435
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
436
- script: desired.script,
437
- node: desired.node,
438
- nodeResolved: desired.node !== null,
439
- nodeError: desired.nodeError,
440
- reason: file.kind === 'link' ? 'mcp-file-is-link' : 'mcp-file-not-regular',
441
- existingDoc: null,
442
- expectDigest: null,
443
- };
444
- }
445
- let parsed;
446
- try {
447
- parsed = JSON.parse(file.contents);
448
- } catch {
449
- return {
450
- path: mcpPath,
451
- state: ANTIGRAVITY_MCP_STATES.unreadable,
452
- configured: false,
453
- managed: false,
454
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
455
- script: desired.script,
456
- node: desired.node,
457
- nodeResolved: desired.node !== null,
458
- nodeError: desired.nodeError,
459
- reason: 'mcp-json-invalid',
460
- existingDoc: null,
461
- expectDigest: digest(file.contents),
462
- };
463
- }
464
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
465
- return {
466
- path: mcpPath,
467
- state: ANTIGRAVITY_MCP_STATES.unreadable,
468
- configured: false,
469
- managed: false,
470
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
471
- script: desired.script,
472
- node: desired.node,
473
- nodeResolved: desired.node !== null,
474
- nodeError: desired.nodeError,
475
- reason: 'mcp-json-not-object',
476
- existingDoc: null,
477
- expectDigest: digest(file.contents),
478
- };
479
- }
480
- const servers = parsed.mcpServers;
481
- if (servers !== undefined && (servers === null || typeof servers !== 'object' || Array.isArray(servers))) {
482
- return {
483
- path: mcpPath,
484
- state: ANTIGRAVITY_MCP_STATES.unreadable,
485
- configured: false,
486
- managed: false,
487
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
488
- script: desired.script,
489
- node: desired.node,
490
- nodeResolved: desired.node !== null,
491
- nodeError: desired.nodeError,
492
- reason: 'mcp-servers-not-object',
493
- existingDoc: null,
494
- expectDigest: digest(file.contents),
495
- };
496
- }
497
- const entry = servers?.[ANTIGRAVITY_MCP_SERVER_NAME];
498
- const fileDigest = digest(file.contents);
499
- if (entry === undefined) {
500
- return {
501
- path: mcpPath,
502
- state: ANTIGRAVITY_MCP_STATES.missing,
503
- configured: false,
504
- managed: true,
505
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
506
- script: desired.script,
507
- node: desired.node,
508
- nodeResolved: desired.node !== null,
509
- nodeError: desired.nodeError,
510
- reason: null,
511
- existingDoc: parsed,
512
- expectDigest: fileDigest,
513
- };
514
- }
515
- if (!isManagedMcpShape(entry)) {
516
- return {
517
- path: mcpPath,
518
- state: ANTIGRAVITY_MCP_STATES.conflict,
519
- configured: false,
520
- managed: false,
521
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
522
- script: desired.script,
523
- node: desired.node,
524
- nodeResolved: desired.node !== null,
525
- nodeError: desired.nodeError,
526
- reason: 'mcp-entry-customized',
527
- existingDoc: parsed,
528
- expectDigest: fileDigest,
529
- };
530
- }
531
- const exactMatch = desired.serverEntry !== null
532
- && sameFsPath(entry.command, desired.serverEntry.command)
533
- && sameFsPath(entry.args[0], desired.serverEntry.args[0])
534
- && sameMcpEnv(entry.env, desired.serverEntry.env);
535
- if (exactMatch) {
536
- return {
537
- path: mcpPath,
538
- state: ANTIGRAVITY_MCP_STATES.configured,
539
- configured: true,
540
- managed: true,
541
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
542
- script: desired.script,
543
- node: desired.node,
544
- nodeResolved: desired.node !== null,
545
- nodeError: desired.nodeError,
546
- reason: null,
547
- existingDoc: parsed,
548
- expectDigest: fileDigest,
549
- };
550
- }
551
- const recordedMatch = typeof recordedDigest === 'string' && digestLf(file.contents) === recordedDigest;
552
- const sameScript = sameFsPath(entry.args[0], desired.script);
553
- const ownedMovedScript = !sameScript && await isOwnedEntryScript(entry.args[0], desired.script);
554
- if (recordedMatch || sameScript || ownedMovedScript) {
555
- const reasons = [];
556
- if (desired.node !== null && !sameFsPath(entry.command, desired.node)) reasons.push('node-path-changed');
557
- if (!sameScript) reasons.push('script-path-changed');
558
- if (desired.serverEntry !== null && !sameMcpEnv(entry.env, desired.serverEntry.env)) reasons.push('discovery-env-changed');
559
- return {
560
- path: mcpPath,
561
- state: ANTIGRAVITY_MCP_STATES.outdated,
562
- configured: false,
563
- managed: true,
564
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
565
- script: desired.script,
566
- node: desired.node,
567
- nodeResolved: desired.node !== null,
568
- nodeError: desired.nodeError,
569
- reason: reasons.join(',') || 'mcp-outdated',
570
- movedScript: ownedMovedScript,
571
- existingDoc: parsed,
572
- expectDigest: fileDigest,
573
- };
574
- }
575
- return {
576
- path: mcpPath,
577
- state: ANTIGRAVITY_MCP_STATES.conflict,
578
- configured: false,
579
- managed: false,
580
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
581
- script: desired.script,
582
- node: desired.node,
583
- nodeResolved: desired.node !== null,
584
- nodeError: desired.nodeError,
585
- reason: 'mcp-script-unowned',
586
- existingDoc: parsed,
587
- expectDigest: fileDigest,
588
- };
589
- }
590
-
591
- /**
592
- * Exact LF SHA-256 digests of prior published Antigravity managed files.
593
- * Allows an untouched published installation (such as 1.8.0) to be recognized as
594
- * `outdated` and upgraded cleanly even if the local ownership sidecar is absent,
595
- * while any operator-edited file still classifies as `modified` and is preserved.
596
- */
597
- const KNOWN_PRIOR_ANTIGRAVITY_FILES = Object.freeze({
598
- 'skills/dsh-taskbridge/SKILL.md': Object.freeze([
599
- // Published 1.8.0 SKILL.md (LF)
600
- '9e83135ece937dbc0b73f5098509daac2fe4b973fe4dcd2ed75186745cf3cfee',
601
- ]),
602
- 'agents/dsh-taskbridge.md': Object.freeze([
603
- // Published 1.8.0 agents/dsh-taskbridge.md (LF)
604
- 'df1418abe2c58c535734ecf6619bd027ca251d2dd6043cec9f41561d8e0a432b',
605
- ]),
606
- });
607
-
608
- function isManagedAntigravityManifest(contents) {
609
- try {
610
- const parsed = JSON.parse(contents);
611
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
612
- if (typeof parsed.version !== 'string' || parsed.version.trim() === '') return false;
613
- return sameTextLf(contents, renderAntigravityManifest(parsed.version));
614
- } catch {
615
- return false;
616
- }
617
- }
618
-
619
- async function classifyPluginFiles({ paths, templates, recordedFiles }) {
620
- const details = {};
621
- for (const key of PLUGIN_FILE_KEYS) {
622
- const targetPath = paths.files[key];
623
- const desiredText = templates.files[key];
624
- const file = await inspectFileSafe(targetPath);
625
- if (file.kind === 'missing') {
626
- details[key] = { path: targetPath, state: 'not-installed', expectDigest: null };
627
- continue;
628
- }
629
- if (file.kind !== 'file') {
630
- details[key] = {
631
- path: targetPath,
632
- state: 'conflict',
633
- reason: file.kind === 'link' ? 'file-is-link' : 'file-not-regular',
634
- expectDigest: null,
635
- };
636
- continue;
637
- }
638
- const rawDigest = digest(file.contents);
639
- if (sameTextLf(file.contents, desiredText)) {
640
- details[key] = { path: targetPath, state: 'installed', expectDigest: rawDigest };
641
- continue;
642
- }
643
- const recorded = recordedFiles?.[key] ?? null;
644
- const lfDigest = digestLf(file.contents);
645
- if (typeof recorded === 'string' && lfDigest === recorded) {
646
- details[key] = { path: targetPath, state: 'outdated', expectDigest: rawDigest };
647
- continue;
648
- }
649
- if (Array.isArray(KNOWN_PRIOR_ANTIGRAVITY_FILES[key]) && KNOWN_PRIOR_ANTIGRAVITY_FILES[key].includes(lfDigest)) {
650
- details[key] = { path: targetPath, state: 'outdated', expectDigest: rawDigest };
651
- continue;
652
- }
653
- if (key === 'plugin.json' && isManagedAntigravityManifest(file.contents)) {
654
- details[key] = { path: targetPath, state: 'outdated', expectDigest: rawDigest };
655
- continue;
656
- }
657
- details[key] = { path: targetPath, state: 'modified', expectDigest: rawDigest };
658
- }
659
- const states = Object.values(details).map((entry) => entry.state);
660
- let state;
661
- if (states.includes('conflict')) state = ANTIGRAVITY_PLUGIN_STATES.conflict;
662
- else if (states.includes('modified')) state = ANTIGRAVITY_PLUGIN_STATES.modified;
663
- else if (states.every((s) => s === 'not-installed')) state = ANTIGRAVITY_PLUGIN_STATES.missing;
664
- else if (states.every((s) => s === 'installed')) state = ANTIGRAVITY_PLUGIN_STATES.installed;
665
- else state = ANTIGRAVITY_PLUGIN_STATES.outdated;
666
- return {
667
- path: paths.pluginDir,
668
- state,
669
- installed: state === ANTIGRAVITY_PLUGIN_STATES.installed,
670
- managed: state !== ANTIGRAVITY_PLUGIN_STATES.modified && state !== ANTIGRAVITY_PLUGIN_STATES.conflict,
671
- files: details,
672
- };
673
- }
674
-
675
- export async function readAntigravityStatus(options = {}) {
676
- const env = options.env ?? process.env;
677
- const selectedHome = typeof options.antigravityHome === 'string' && options.antigravityHome.trim() !== ''
678
- ? requireAntigravityHome(options.antigravityHome)
679
- : resolveAntigravityHome({ env, homeDirectory: options.homeDirectory });
680
-
681
- const pinned = await pinAntigravityHome(selectedHome);
682
- const templates = await readAntigravityTemplates(options.version ?? null);
683
- const paths = pluginPathsFor(pinned.real);
684
- const desiredMcp = desiredMcpConfig(options);
685
- const notes = [];
686
-
687
- if (pinned.error !== null) {
688
- notes.push({ code: pinned.error.reason, text: pinned.error.message });
689
- return {
690
- antigravityHome: pinned.selected,
691
- realAntigravityHome: pinned.real,
692
- pluginDir: paths.pluginDir,
693
- packageVersion: templates.version,
694
- plugin: { path: paths.pluginDir, state: ANTIGRAVITY_PLUGIN_STATES.conflict, installed: false, managed: false, files: {} },
695
- mcp: {
696
- path: paths.mcpPath,
697
- state: ANTIGRAVITY_MCP_STATES.conflict,
698
- configured: false,
699
- managed: false,
700
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
701
- script: desiredMcp.script,
702
- node: desiredMcp.node,
703
- nodeResolved: desiredMcp.node !== null,
704
- nodeError: desiredMcp.nodeError,
705
- reason: pinned.error.reason,
706
- },
707
- ready: false,
708
- notes,
709
- };
710
- }
711
-
712
- const boundary = await inspectBoundaries(pinned.real, paths);
713
- if (!boundary.ok) {
714
- notes.push({
715
- code: boundary.reason,
716
- text: `检测到非普通目录边界(${boundary.path}),插件不会穿过软链接或异常路径写入文件。`,
717
- });
718
- return {
719
- antigravityHome: pinned.selected,
720
- realAntigravityHome: pinned.real,
721
- pluginDir: paths.pluginDir,
722
- packageVersion: templates.version,
723
- plugin: { path: paths.pluginDir, state: ANTIGRAVITY_PLUGIN_STATES.conflict, installed: false, managed: false, files: {} },
724
- mcp: {
725
- path: paths.mcpPath,
726
- state: ANTIGRAVITY_MCP_STATES.conflict,
727
- configured: false,
728
- managed: false,
729
- serverName: ANTIGRAVITY_MCP_SERVER_NAME,
730
- script: desiredMcp.script,
731
- node: desiredMcp.node,
732
- nodeResolved: desiredMcp.node !== null,
733
- nodeError: desiredMcp.nodeError,
734
- reason: boundary.reason,
735
- },
736
- ready: false,
737
- notes,
738
- };
739
- }
740
-
741
- const ownership = await readOwnershipRecord(pinned.real, env);
742
- const plugin = await classifyPluginFiles({
743
- paths,
744
- templates,
745
- recordedFiles: ownership?.files ?? {},
746
- });
747
- const mcp = await classifyMcpFile({
748
- mcpPath: paths.mcpPath,
749
- desired: desiredMcp,
750
- recordedDigest: ownership?.files?.[MCP_FILE_KEY] ?? null,
751
- });
752
-
753
- if (desiredMcp.nodeError !== null) {
754
- notes.push({
755
- code: desiredMcp.nodeError.code,
756
- text: '未找到可用的 Node.js 运行时,无法写入 MCP 配置(不会写入桌面应用自身的 exe)。',
757
- });
758
- }
759
- if (plugin.state === ANTIGRAVITY_PLUGIN_STATES.modified) {
760
- notes.push({
761
- code: 'PLUGIN_USER_MODIFIED',
762
- text: '检测到插件目录内有你自定义修改过的文件,安装与卸载都会保留它们;若仅需恢复连接,可点「仅修复 MCP 配置」。',
763
- });
764
- }
765
- if (mcp.state === ANTIGRAVITY_MCP_STATES.conflict || mcp.state === ANTIGRAVITY_MCP_STATES.unreadable) {
766
- notes.push({
767
- code: 'MCP_CONFLICT',
768
- text: 'plugins/dsh-taskbridge/mcp_config.json 存在自定义内容或格式错误,插件不会覆盖。',
769
- });
770
- }
771
-
772
- return {
773
- antigravityHome: pinned.selected,
774
- realAntigravityHome: pinned.real,
775
- pluginDir: paths.pluginDir,
776
- packageVersion: templates.version,
777
- plugin,
778
- mcp,
779
- ready: plugin.installed && mcp.configured,
780
- notes,
781
- };
782
- }
783
-
784
- async function ensureManagedDirs(paths) {
785
- for (const dir of paths.dirs) {
786
- const info = await inspectDirectory(dir).catch(() => ({ kind: 'unknown' }));
787
- if (info.kind === 'directory') continue;
788
- if (info.kind !== 'missing') {
789
- throw new AntigravityInstallError('ANTIGRAVITY_PATH_CONFLICT', `refused to traverse non-directory ${dir}`);
790
- }
791
- await mkdir(dir, { mode: 0o700 });
792
- const after = await inspectDirectory(dir).catch(() => ({ kind: 'unknown' }));
793
- if (after.kind !== 'directory') {
794
- throw new AntigravityInstallError('ANTIGRAVITY_PATH_CONFLICT', `created directory ${dir} could not be verified`);
795
- }
796
- }
797
- }
798
-
799
- async function ensureRootDir(realHome) {
800
- const info = await inspectDirectory(realHome).catch(() => ({ kind: 'unknown' }));
801
- if (info.kind === 'directory') return;
802
- if (info.kind !== 'missing') {
803
- throw new AntigravityInstallError('ANTIGRAVITY_HOME_UNUSABLE', `refused to use non-directory ${realHome}`);
804
- }
805
- await mkdir(realHome, { recursive: true, mode: 0o700 });
806
- }
807
-
808
- async function verifyUnchanged(filePath, expectDigest) {
809
- const current = await inspectFileSafe(filePath);
810
- if (expectDigest === null) return current.kind === 'missing';
811
- return current.kind === 'file' && digest(current.contents) === expectDigest;
812
- }
813
-
814
- async function removeEmptyDirs(dirs) {
815
- for (const dir of [...dirs].reverse()) {
816
- try {
817
- const entries = await readdir(dir);
818
- if (entries.length === 0) await rmdir(dir);
819
- } catch {
820
- // ignore missing or non-empty dirs
821
- }
822
- }
823
- }
824
-
825
- export async function runAntigravityAction(action, options = {}) {
826
- if (!ANTIGRAVITY_ACTIONS.includes(action)) {
827
- throw new AntigravityInstallError('ANTIGRAVITY_ACTION_INVALID', `unknown action ${String(action)}`);
828
- }
829
- if (action === 'status') {
830
- return { changed: [], refused: [], status: await readAntigravityStatus(options) };
831
- }
832
-
833
- const env = options.env ?? process.env;
834
- const before = await readAntigravityStatus(options);
835
- const templates = await readAntigravityTemplates(options.version ?? null);
836
- const paths = pluginPathsFor(before.realAntigravityHome);
837
- const desiredMcp = desiredMcpConfig(options);
838
- const ownership = await readOwnershipRecord(before.realAntigravityHome, env);
839
- const nextDigests = { ...(ownership?.files ?? {}) };
840
- const changed = [];
841
- const refused = [];
842
-
843
- if (before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.conflict) {
844
- refused.push({ target: 'plugin', code: 'ANTIGRAVITY_PATH_CONFLICT', message: 'plugin directory boundary conflict' });
845
- refused.push({ target: 'mcp', code: 'ANTIGRAVITY_PATH_CONFLICT', message: 'plugin directory boundary conflict' });
846
- return { changed, refused, status: before };
847
- }
848
-
849
- if (action === 'install') {
850
- await ensureRootDir(before.realAntigravityHome);
851
- await ensureManagedDirs(paths);
852
-
853
- // 1. Plugin bundle files (per-file: write missing/outdated managed files, preserve user-modified ones)
854
- let wrotePlugin = false;
855
- let modifiedPlugin = false;
856
- let pluginConflict = false;
857
- for (const key of PLUGIN_FILE_KEYS) {
858
- const entry = before.plugin.files[key];
859
- if (entry?.state === 'installed') {
860
- nextDigests[key] = digestLf(templates.files[key]);
861
- continue;
862
- }
863
- if (entry?.state === 'modified') {
864
- modifiedPlugin = true;
865
- continue;
866
- }
867
- if (entry?.state !== 'not-installed' && entry?.state !== 'outdated') {
868
- pluginConflict = true;
869
- continue;
870
- }
871
- if (!(await verifyUnchanged(paths.files[key], entry?.expectDigest ?? null))) {
872
- pluginConflict = true;
873
- break;
874
- }
875
- await writeFileAtomic(paths.files[key], templates.files[key]);
876
- nextDigests[key] = digestLf(templates.files[key]);
877
- wrotePlugin = true;
878
- }
879
- if (wrotePlugin) changed.push('plugin');
880
- if (pluginConflict) {
881
- refused.push({ target: 'plugin', code: 'PLUGIN_CHANGED_CONCURRENTLY', message: 'plugin file changed during install' });
882
- } else if (modifiedPlugin) {
883
- refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
884
- }
885
-
886
- // 2. MCP config file
887
- await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
888
- await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
889
- } else if (action === 'repair') {
890
- await ensureRootDir(before.realAntigravityHome);
891
- await ensureManagedDirs(paths);
892
-
893
- // Repair touches mcp_config.json (and creates/updates plugin.json only if missing/outdated
894
- // so Antigravity discovers the plugin), never touching SKILL.md or agents/dsh-taskbridge.md.
895
- const manifestEntry = before.plugin.files['plugin.json'];
896
- if (manifestEntry?.state === 'not-installed' || manifestEntry?.state === 'outdated') {
897
- if (await verifyUnchanged(paths.files['plugin.json'], manifestEntry.expectDigest ?? null)) {
898
- await writeFileAtomic(paths.files['plugin.json'], templates.files['plugin.json']);
899
- nextDigests['plugin.json'] = digestLf(templates.files['plugin.json']);
900
- }
901
- }
902
- await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
903
- await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
904
- } else if (action === 'remove') {
905
- // 1. Remove verified managed plugin files only
906
- let removedPlugin = false;
907
- let refusedPlugin = false;
908
- for (const key of PLUGIN_FILE_KEYS) {
909
- const entry = before.plugin.files[key];
910
- if (!entry || entry.state === 'not-installed') {
911
- delete nextDigests[key];
912
- continue;
913
- }
914
- if (entry.state !== 'installed' && entry.state !== 'outdated') {
915
- refusedPlugin = true;
916
- continue;
917
- }
918
- if (!(await verifyUnchanged(paths.files[key], entry.expectDigest))) {
919
- refusedPlugin = true;
920
- continue;
921
- }
922
- await unlink(paths.files[key]);
923
- delete nextDigests[key];
924
- removedPlugin = true;
925
- }
926
- if (removedPlugin) changed.push('plugin');
927
- if (refusedPlugin) {
928
- refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
929
- }
930
-
931
- // 2. Remove managed MCP entry only
932
- if (before.mcp.state === ANTIGRAVITY_MCP_STATES.configured || before.mcp.state === ANTIGRAVITY_MCP_STATES.outdated) {
933
- if (await verifyUnchanged(paths.mcpPath, before.mcp.expectDigest)) {
934
- const doc = { ...(before.mcp.existingDoc ?? {}) };
935
- const servers = { ...(doc.mcpServers ?? {}) };
936
- delete servers[ANTIGRAVITY_MCP_SERVER_NAME];
937
- if (Object.keys(servers).length === 0 && Object.keys(doc).every((k) => k === 'mcpServers')) {
938
- await unlink(paths.mcpPath);
939
- } else {
940
- doc.mcpServers = servers;
941
- await writeFileAtomic(paths.mcpPath, `${JSON.stringify(doc, null, 2)}\n`);
942
- }
943
- delete nextDigests[MCP_FILE_KEY];
944
- changed.push('mcp');
945
- } else {
946
- refused.push({ target: 'mcp', code: 'MCP_CHANGED_CONCURRENTLY', message: 'mcp_config.json changed during remove' });
947
- }
948
- } else if (before.mcp.state === ANTIGRAVITY_MCP_STATES.conflict || before.mcp.state === ANTIGRAVITY_MCP_STATES.unreadable) {
949
- refused.push({ target: 'mcp', code: 'MCP_USER_MODIFIED', message: 'customized mcp_config.json was preserved' });
950
- }
951
-
952
- await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
953
- // Clean empty directories inside plugins/dsh-taskbridge only (never remove plugins/ itself).
954
- await removeEmptyDirs(paths.dirs.slice(1));
955
- }
956
-
957
- return { changed, refused, status: await readAntigravityStatus(options) };
958
- }
959
-
960
- async function applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused }) {
961
- if (desiredMcp.serverEntry === null) {
962
- refused.push({
963
- target: 'mcp',
964
- code: desiredMcp.nodeError?.code ?? 'MCP_EXECUTABLE_UNRESOLVED',
965
- message: desiredMcp.nodeError?.message ?? 'no Node.js executable available',
966
- });
967
- return;
968
- }
969
- if (before.mcp.state === ANTIGRAVITY_MCP_STATES.configured) {
970
- const existing = await inspectFileSafe(paths.mcpPath);
971
- if (existing.kind === 'file') nextDigests[MCP_FILE_KEY] = digestLf(existing.contents);
972
- return;
973
- }
974
- if (before.mcp.state !== ANTIGRAVITY_MCP_STATES.missing && before.mcp.state !== ANTIGRAVITY_MCP_STATES.outdated) {
975
- refused.push({
976
- target: 'mcp',
977
- code: before.mcp.state === ANTIGRAVITY_MCP_STATES.unreadable ? 'MCP_UNREADABLE' : 'MCP_CONFLICT',
978
- message: 'mcp_config.json cannot be overwritten safely',
979
- });
980
- return;
981
- }
982
- if (!(await verifyUnchanged(paths.mcpPath, before.mcp.expectDigest ?? null))) {
983
- refused.push({ target: 'mcp', code: 'MCP_CHANGED_CONCURRENTLY', message: 'mcp_config.json changed during write' });
984
- return;
985
- }
986
- const rendered = renderMcpDocument(before.mcp.existingDoc, desiredMcp.serverEntry);
987
- await writeFileAtomic(paths.mcpPath, rendered);
988
- nextDigests[MCP_FILE_KEY] = digestLf(rendered);
989
- changed.push('mcp');
990
- }
991
-
992
- export async function refreshManagedAntigravityPlugin(options = {}) {
993
- const before = await readAntigravityStatus(options);
994
- const env = options.env ?? process.env;
995
- const templates = await readAntigravityTemplates(options.version ?? null);
996
- const paths = pluginPathsFor(before.realAntigravityHome);
997
- const desiredMcp = desiredMcpConfig(options);
998
- const ownership = await readOwnershipRecord(before.realAntigravityHome, env);
999
- const nextDigests = { ...(ownership?.files ?? {}) };
1000
- const changed = [];
1001
- const refused = [];
1002
-
1003
- // Never create a fresh installation on startup. Upgrade only provably existing
1004
- // managed plugin files (per-file when another file was customized by the user).
1005
- const pluginEntries = Object.values(before.plugin.files ?? {});
1006
- const hasOutdatedPluginFile = before.plugin.state !== ANTIGRAVITY_PLUGIN_STATES.conflict
1007
- && pluginEntries.some((entry) => entry?.state === 'outdated');
1008
- const hasExistingManagedPlugin = before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.outdated || hasOutdatedPluginFile;
1009
- const hasExistingStaleMcp = before.mcp.state === ANTIGRAVITY_MCP_STATES.outdated && before.mcp.movedScript !== true;
1010
- if (!hasExistingManagedPlugin && !hasExistingStaleMcp) {
1011
- return { changed, refused, status: before };
1012
- }
1013
-
1014
- if (hasExistingManagedPlugin) {
1015
- await ensureManagedDirs(paths);
1016
- const fillMissing = before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.outdated;
1017
- let wrotePlugin = false;
1018
- let modifiedPlugin = false;
1019
- let pluginConflict = false;
1020
- for (const key of PLUGIN_FILE_KEYS) {
1021
- const entry = before.plugin.files[key];
1022
- if (entry?.state === 'modified') {
1023
- modifiedPlugin = true;
1024
- continue;
1025
- }
1026
- const shouldWrite = entry?.state === 'outdated' || (fillMissing && entry?.state === 'not-installed');
1027
- if (!shouldWrite) continue;
1028
- if (!(await verifyUnchanged(paths.files[key], entry?.expectDigest ?? null))) {
1029
- pluginConflict = true;
1030
- break;
1031
- }
1032
- await writeFileAtomic(paths.files[key], templates.files[key]);
1033
- nextDigests[key] = digestLf(templates.files[key]);
1034
- wrotePlugin = true;
1035
- }
1036
- if (wrotePlugin) changed.push('plugin');
1037
- if (pluginConflict) {
1038
- refused.push({ target: 'plugin', code: 'PLUGIN_CHANGED_CONCURRENTLY', message: 'plugin file changed during refresh' });
1039
- } else if (modifiedPlugin) {
1040
- refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
1041
- }
1042
- }
1043
-
1044
- if (hasExistingStaleMcp) {
1045
- await ensureManagedDirs(paths);
1046
- await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
1047
- }
1048
-
1049
- if (changed.length > 0) {
1050
- await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
1051
- }
1052
- return { changed, refused, status: await readAntigravityStatus(options) };
1053
- }
1054
-
1055
- export function publicAntigravityStatus(status) {
1056
- if (status === null || typeof status !== 'object') return status;
1057
- const files = {};
1058
- for (const [key, entry] of Object.entries(status.plugin?.files ?? {})) {
1059
- const { expectDigest: _ignored, ...pub } = entry ?? {};
1060
- files[key] = pub;
1061
- }
1062
- const { existingDoc: _doc, expectDigest: _digest, ...mcp } = status.mcp ?? {};
1063
- return {
1064
- ...status,
1065
- plugin: { ...(status.plugin ?? {}), files },
1066
- mcp,
1067
- };
1068
- }
1
+ // Antigravity integration: install the self-contained DSH TaskBridge plugin bundle
2
+ // into `<ANTIGRAVITY_CONFIG_DIR>/plugins/dsh-taskbridge/` (default `~/.gemini/config`).
3
+ //
4
+ // Everything lives inside that single plugin directory so Antigravity can toggle or
5
+ // uninstall it cleanly without touching `~/.gemini/config/mcp_config.json` or
6
+ // `~/.gemini/config/config.json`:
7
+ //
8
+ // plugins/dsh-taskbridge/
9
+ // ├── plugin.json
10
+ // ├── mcp_config.json
11
+ // ├── assets/logo.svg
12
+ // ├── skills/dsh-taskbridge/SKILL.md
13
+ // └── agents/dsh-taskbridge.md
14
+ //
15
+ // Safety and ownership mirror `src/codex/installer.js`:
16
+ // * `status` is strictly read-only and never creates directories or files;
17
+ // * root symlink/junction is resolved and pinned once; links inside the plugin
18
+ // tree are refused as `conflict`;
19
+ // * ownership is proved by content digest (current template or recorded managed
20
+ // digest for this home) rather than by filename alone, so operator-edited
21
+ // skills, agents or MCP entries are preserved and never overwritten or deleted;
22
+ // * `install` manages both the plugin files and `mcp_config.json`, `repair` fixes
23
+ // MCP (plus a missing/outdated `plugin.json` manifest only) without touching
24
+ // skills or agents, and `remove` deletes only verified plugin-managed files;
25
+ // * startup refresh updates already-installed, unmodified outdated files in place
26
+ // and never performs a first install.
27
+
28
+ import { createHash } from 'node:crypto';
29
+ import { lstat, mkdir, readdir, readFile, realpath, rmdir, unlink } from 'node:fs/promises';
30
+ import { homedir } from 'node:os';
31
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
32
+ import { fileURLToPath } from 'node:url';
33
+
34
+ import { writeFileAtomic } from '../config/store.js';
35
+ import { digestLf, pluginDataDirectory } from '../codex/agent-ownership.js';
36
+ import {
37
+ DISCOVERY_ENV_VAR,
38
+ MCP_ENTRY_RELATIVE,
39
+ digest,
40
+ inspectDirectories,
41
+ inspectDirectory,
42
+ isNodeExecutableName,
43
+ isOwnedEntryScript,
44
+ resolveNodeExecutable,
45
+ useDirectoryClassifier,
46
+ } from '../codex/installer.js';
47
+ import { resolveDefaultEndpointDiscoveryPath, resolveEndpointDiscoveryPath } from '../runtime/endpoint-discovery.js';
48
+
49
+ function sameFsPath(left, right) {
50
+ if (typeof left !== 'string' || typeof right !== 'string') return false;
51
+ const a = resolve(left);
52
+ const b = resolve(right);
53
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
54
+ }
55
+
56
+ export const ANTIGRAVITY_PLUGIN_NAME = 'dsh-taskbridge';
57
+ export const ANTIGRAVITY_MCP_SERVER_NAME = 'dsh-taskbridge';
58
+ export const ANTIGRAVITY_ACTIONS = Object.freeze(['status', 'install', 'repair', 'remove']);
59
+
60
+ export const ANTIGRAVITY_PLUGIN_STATES = Object.freeze({
61
+ missing: 'not-installed',
62
+ installed: 'installed',
63
+ outdated: 'outdated',
64
+ modified: 'modified',
65
+ conflict: 'conflict',
66
+ });
67
+
68
+ export const ANTIGRAVITY_MCP_STATES = Object.freeze({
69
+ missing: 'not-configured',
70
+ configured: 'configured',
71
+ outdated: 'outdated',
72
+ conflict: 'conflict',
73
+ unreadable: 'unreadable',
74
+ });
75
+
76
+ export const ANTIGRAVITY_ENV_VARS = Object.freeze(['ANTIGRAVITY_CONFIG_DIR', 'GEMINI_CONFIG_DIR']);
77
+
78
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
79
+ const PACKAGE_MANIFEST_PATH = join(PACKAGE_ROOT, 'package.json');
80
+ const SKILL_TEMPLATE_PATH = join(PACKAGE_ROOT, 'antigravity', 'skills', 'dsh-taskbridge', 'SKILL.md');
81
+ const AGENT_TEMPLATE_PATH = join(PACKAGE_ROOT, 'antigravity', 'agents', 'dsh-taskbridge.md');
82
+ const LOGO_TEMPLATE_PATH = join(PACKAGE_ROOT, 'icon.svg');
83
+
84
+ const PLUGIN_FILE_KEYS = Object.freeze([
85
+ 'plugin.json',
86
+ 'skills/dsh-taskbridge/SKILL.md',
87
+ 'agents/dsh-taskbridge.md',
88
+ 'assets/logo.svg',
89
+ ]);
90
+
91
+ const MCP_FILE_KEY = 'mcp_config.json';
92
+ const OWNERSHIP_DIR_NAME = 'antigravity-plugin-ownership';
93
+ const OWNERSHIP_SCHEMA_VERSION = 1;
94
+ const MAX_FILE_BYTES = 1024 * 1024;
95
+ const MAX_OWNERSHIP_BYTES = 8192;
96
+ const SHA256_RE = /^[0-9a-f]{64}$/u;
97
+
98
+ const ALLOWED_MCP_ENTRY_KEYS = new Set(['command', 'args', 'env']);
99
+
100
+ export class AntigravityInstallError extends Error {
101
+ constructor(code, message, details = {}) {
102
+ super(message);
103
+ this.name = 'AntigravityInstallError';
104
+ this.code = code;
105
+ this.details = details;
106
+ }
107
+ }
108
+
109
+ export { useDirectoryClassifier };
110
+
111
+ function normalizeLf(text) {
112
+ return String(text ?? '').replace(/\r\n/gu, '\n');
113
+ }
114
+
115
+ function sameTextLf(left, right) {
116
+ if (left === right) return true;
117
+ const a = normalizeLf(left);
118
+ const b = normalizeLf(right);
119
+ if (a.includes('\r') || b.includes('\r')) return false;
120
+ return a === b;
121
+ }
122
+
123
+ export function resolveAntigravityHome({ env = process.env, homeDirectory = homedir() } = {}) {
124
+ for (const key of ANTIGRAVITY_ENV_VARS) {
125
+ const configured = typeof env?.[key] === 'string' ? env[key].trim() : '';
126
+ if (configured !== '') {
127
+ if (!isAbsolute(configured)) {
128
+ throw new AntigravityInstallError('ANTIGRAVITY_HOME_INVALID', `${key} must be an absolute path`);
129
+ }
130
+ return resolve(configured);
131
+ }
132
+ }
133
+ return resolve(join(homeDirectory, '.gemini', 'config'));
134
+ }
135
+
136
+ export function requireAntigravityHome(antigravityHome) {
137
+ if (typeof antigravityHome !== 'string' || antigravityHome.trim() === '' || !isAbsolute(antigravityHome)) {
138
+ throw new AntigravityInstallError('ANTIGRAVITY_HOME_INVALID', 'the Antigravity config directory must be an absolute path');
139
+ }
140
+ return resolve(antigravityHome);
141
+ }
142
+
143
+ async function readPackageVersion() {
144
+ try {
145
+ const manifest = JSON.parse(await readFile(PACKAGE_MANIFEST_PATH, 'utf8'));
146
+ return typeof manifest.version === 'string' ? manifest.version : '';
147
+ } catch {
148
+ return '';
149
+ }
150
+ }
151
+
152
+ export function renderAntigravityManifest(version) {
153
+ const manifest = {
154
+ name: ANTIGRAVITY_PLUGIN_NAME,
155
+ displayName: 'DSH TaskBridge',
156
+ version: version || '0.0.0',
157
+ description: '通过 DSH TaskBridge MCP 服务向 DeepSeek Harness 派工,支持先定方案后派工、后台静默等待、逐次权限审批与集中审查验收。',
158
+ logo: 'assets/logo.svg',
159
+ suggestedPrompts: [
160
+ '把当前仓库的功能修改交给 DSH TaskBridge 执行并在交付后审查',
161
+ '检查 DSH TaskBridge 本机调用状态和当前工作区预检结果',
162
+ '把多阶段目标拆成 TaskBridge 任务树并按顺序派给 DSH 执行',
163
+ ],
164
+ };
165
+ return `${JSON.stringify(manifest, null, 2)}\n`;
166
+ }
167
+
168
+ export async function readAntigravityTemplates(versionOverride = null) {
169
+ const version = typeof versionOverride === 'string' && versionOverride.trim() !== ''
170
+ ? versionOverride.trim()
171
+ : await readPackageVersion();
172
+ const [skill, agent, logo] = await Promise.all([
173
+ readFile(SKILL_TEMPLATE_PATH, 'utf8'),
174
+ readFile(AGENT_TEMPLATE_PATH, 'utf8'),
175
+ readFile(LOGO_TEMPLATE_PATH, 'utf8'),
176
+ ]);
177
+ return {
178
+ version,
179
+ files: {
180
+ 'plugin.json': renderAntigravityManifest(version),
181
+ 'skills/dsh-taskbridge/SKILL.md': normalizeLf(skill),
182
+ 'agents/dsh-taskbridge.md': normalizeLf(agent),
183
+ 'assets/logo.svg': normalizeLf(logo),
184
+ },
185
+ };
186
+ }
187
+
188
+ function pluginPathsFor(realHome) {
189
+ const pluginsDir = join(realHome, 'plugins');
190
+ const pluginDir = join(pluginsDir, ANTIGRAVITY_PLUGIN_NAME);
191
+ return {
192
+ pluginsDir,
193
+ pluginDir,
194
+ files: {
195
+ 'plugin.json': join(pluginDir, 'plugin.json'),
196
+ 'skills/dsh-taskbridge/SKILL.md': join(pluginDir, 'skills', 'dsh-taskbridge', 'SKILL.md'),
197
+ 'agents/dsh-taskbridge.md': join(pluginDir, 'agents', 'dsh-taskbridge.md'),
198
+ 'assets/logo.svg': join(pluginDir, 'assets', 'logo.svg'),
199
+ },
200
+ mcpPath: join(pluginDir, MCP_FILE_KEY),
201
+ dirs: [
202
+ pluginsDir,
203
+ pluginDir,
204
+ join(pluginDir, 'skills'),
205
+ join(pluginDir, 'skills', 'dsh-taskbridge'),
206
+ join(pluginDir, 'agents'),
207
+ join(pluginDir, 'assets'),
208
+ ],
209
+ };
210
+ }
211
+
212
+ function ownershipPathFor(realHome, env = process.env) {
213
+ const dataDir = pluginDataDirectory(env);
214
+ if (dataDir === null) return null;
215
+ const key = createHash('sha256').update(resolve(realHome), 'utf8').digest('hex');
216
+ return join(dataDir, OWNERSHIP_DIR_NAME, `${key}.json`);
217
+ }
218
+
219
+ async function readOwnershipRecord(realHome, env = process.env) {
220
+ const path = ownershipPathFor(realHome, env);
221
+ if (path === null) return null;
222
+ try {
223
+ const info = await lstat(path);
224
+ if (info.isSymbolicLink() || !info.isFile() || info.size > MAX_OWNERSHIP_BYTES) return null;
225
+ const parsed = JSON.parse(await readFile(path, 'utf8'));
226
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
227
+ if (parsed.schemaVersion !== OWNERSHIP_SCHEMA_VERSION) return null;
228
+ if (typeof parsed.antigravityHome !== 'string' || resolve(parsed.antigravityHome) !== resolve(realHome)) return null;
229
+ if (parsed.files === null || typeof parsed.files !== 'object' || Array.isArray(parsed.files)) return null;
230
+ const files = {};
231
+ for (const [k, v] of Object.entries(parsed.files)) {
232
+ if (typeof v === 'string' && SHA256_RE.test(v)) files[k] = v;
233
+ }
234
+ return { path, files };
235
+ } catch {
236
+ return null;
237
+ }
238
+ }
239
+
240
+ async function writeOwnershipRecord(realHome, pluginDir, fileDigests, env = process.env) {
241
+ const path = ownershipPathFor(realHome, env);
242
+ if (path === null) return false;
243
+ try {
244
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
245
+ const record = {
246
+ schemaVersion: OWNERSHIP_SCHEMA_VERSION,
247
+ antigravityHome: resolve(realHome),
248
+ pluginDir: resolve(pluginDir),
249
+ files: fileDigests,
250
+ };
251
+ await writeFileAtomic(path, `${JSON.stringify(record, null, 2)}\n`);
252
+ return true;
253
+ } catch {
254
+ return false;
255
+ }
256
+ }
257
+
258
+ async function pinAntigravityHome(selected) {
259
+ const info = await inspectDirectory(selected).catch(() => ({ kind: 'unknown' }));
260
+ if (info.kind === 'missing' || info.kind === 'directory' || info.kind === 'unknown') {
261
+ return { selected, real: selected, linked: false, linkTarget: null, error: null };
262
+ }
263
+ if (info.kind === 'link') {
264
+ let resolved;
265
+ try {
266
+ resolved = await realpath(selected);
267
+ } catch {
268
+ return {
269
+ selected,
270
+ real: selected,
271
+ linked: true,
272
+ linkTarget: info.target ?? null,
273
+ error: {
274
+ code: 'ANTIGRAVITY_HOME_UNUSABLE',
275
+ reason: 'antigravity-home-link-unresolvable',
276
+ message: 'the Antigravity config directory link cannot be resolved to a real directory',
277
+ },
278
+ };
279
+ }
280
+ const targetInfo = await inspectDirectory(resolved).catch(() => ({ kind: 'unknown' }));
281
+ if (targetInfo.kind !== 'directory') {
282
+ return {
283
+ selected,
284
+ real: resolved,
285
+ linked: true,
286
+ linkTarget: info.target ?? null,
287
+ error: {
288
+ code: 'ANTIGRAVITY_HOME_UNUSABLE',
289
+ reason: 'antigravity-home-target-not-a-directory',
290
+ message: 'the Antigravity config directory link does not point at a real directory',
291
+ },
292
+ };
293
+ }
294
+ return { selected, real: resolved, linked: true, linkTarget: info.target ?? null, error: null };
295
+ }
296
+ return {
297
+ selected,
298
+ real: selected,
299
+ linked: false,
300
+ linkTarget: null,
301
+ error: {
302
+ code: 'ANTIGRAVITY_HOME_UNUSABLE',
303
+ reason: 'antigravity-home-not-a-directory',
304
+ message: 'the Antigravity config path exists but is not a directory',
305
+ },
306
+ };
307
+ }
308
+
309
+ async function inspectFileSafe(path) {
310
+ let info;
311
+ try {
312
+ info = await lstat(path);
313
+ } catch (error) {
314
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return { kind: 'missing' };
315
+ throw error;
316
+ }
317
+ if (info.isSymbolicLink()) return { kind: 'link' };
318
+ if (!info.isFile()) return { kind: 'other' };
319
+ if (info.size > MAX_FILE_BYTES) return { kind: 'other' };
320
+ return { kind: 'file', contents: await readFile(path, 'utf8') };
321
+ }
322
+
323
+ async function inspectBoundaries(realHome, paths) {
324
+ let inspected;
325
+ try {
326
+ inspected = await inspectDirectories([realHome, ...paths.dirs]);
327
+ } catch {
328
+ inspected = new Map();
329
+ }
330
+ const rootInfo = inspected.get(realHome) ?? { kind: 'unknown' };
331
+ if (rootInfo.kind !== 'missing' && rootInfo.kind !== 'directory') {
332
+ return { ok: false, reason: rootInfo.kind === 'unknown' ? 'boundary-unverified' : 'antigravity-home-invalid', path: realHome };
333
+ }
334
+ for (const dir of paths.dirs) {
335
+ const info = inspected.get(dir) ?? { kind: 'unknown' };
336
+ if (info.kind === 'missing' || info.kind === 'directory') continue;
337
+ return {
338
+ ok: false,
339
+ reason: info.kind === 'link' ? 'plugin-dir-is-link' : (info.kind === 'unknown' ? 'boundary-unverified' : 'plugin-dir-not-a-directory'),
340
+ path: dir,
341
+ };
342
+ }
343
+ return { ok: true, reason: null, path: null };
344
+ }
345
+
346
+ function desiredMcpConfig(options = {}) {
347
+ const env = options.env ?? process.env;
348
+ const script = resolve(join(PACKAGE_ROOT, MCP_ENTRY_RELATIVE));
349
+ let node = null;
350
+ let nodeError = null;
351
+ try {
352
+ node = typeof options.nodeExecutable === 'string' && options.nodeExecutable.trim() !== ''
353
+ ? resolve(options.nodeExecutable)
354
+ : resolveNodeExecutable({ env, execPath: options.execPath, resourcesPath: options.resourcesPath, versions: options.versions, platform: options.platform });
355
+ } catch (error) {
356
+ nodeError = {
357
+ code: typeof error?.code === 'string' ? error.code : 'MCP_EXECUTABLE_UNRESOLVED',
358
+ message: String(error?.message ?? 'no Node.js executable could be proved'),
359
+ };
360
+ }
361
+ let discoveryFile = null;
362
+ if (typeof options.discoveryFile === 'string' && options.discoveryFile.trim() !== '') {
363
+ discoveryFile = resolve(options.discoveryFile);
364
+ } else {
365
+ const resolved = resolveEndpointDiscoveryPath(env);
366
+ const defaultPath = resolveDefaultEndpointDiscoveryPath(env);
367
+ if (resolved !== undefined && !sameFsPath(resolved, defaultPath)) {
368
+ discoveryFile = resolve(resolved);
369
+ }
370
+ }
371
+ const serverEntry = node === null ? null : {
372
+ command: node,
373
+ args: [script],
374
+ ...(discoveryFile === null ? {} : { env: { [DISCOVERY_ENV_VAR]: discoveryFile } }),
375
+ };
376
+ return { node, nodeError, script, discoveryFile, serverEntry };
377
+ }
378
+
379
+ function renderMcpDocument(existingDoc, serverEntry) {
380
+ const base = existingDoc !== null && typeof existingDoc === 'object' && !Array.isArray(existingDoc)
381
+ ? { ...existingDoc }
382
+ : {};
383
+ const servers = base.mcpServers !== null && typeof base.mcpServers === 'object' && !Array.isArray(base.mcpServers)
384
+ ? { ...base.mcpServers }
385
+ : {};
386
+ servers[ANTIGRAVITY_MCP_SERVER_NAME] = serverEntry;
387
+ base.mcpServers = servers;
388
+ return `${JSON.stringify(base, null, 2)}\n`;
389
+ }
390
+
391
+ function sameMcpEnv(actualEnv, desiredEnv) {
392
+ const a = actualEnv === undefined ? null : actualEnv;
393
+ const b = desiredEnv === undefined ? null : desiredEnv;
394
+ if (a === null && b === null) return true;
395
+ if (a === null || b === null) return false;
396
+ if (typeof a !== 'object' || Array.isArray(a)) return false;
397
+ const aKeys = Object.keys(a);
398
+ const bKeys = Object.keys(b);
399
+ if (aKeys.length !== bKeys.length) return false;
400
+ return aKeys.every((key) => typeof a[key] === 'string' && typeof b[key] === 'string' && sameFsPath(a[key], b[key]));
401
+ }
402
+
403
+ function isManagedMcpShape(entry) {
404
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return false;
405
+ for (const key of Object.keys(entry)) {
406
+ if (!ALLOWED_MCP_ENTRY_KEYS.has(key)) return false;
407
+ }
408
+ if (typeof entry.command !== 'string' || !isNodeExecutableName(entry.command)) return false;
409
+ if (!Array.isArray(entry.args) || entry.args.length !== 1 || typeof entry.args[0] !== 'string') return false;
410
+ if (entry.env !== undefined) {
411
+ if (entry.env === null || typeof entry.env !== 'object' || Array.isArray(entry.env)) return false;
412
+ const keys = Object.keys(entry.env);
413
+ if (keys.some((key) => key !== DISCOVERY_ENV_VAR || typeof entry.env[key] !== 'string')) return false;
414
+ }
415
+ return true;
416
+ }
417
+
418
+ async function classifyMcpFile({ mcpPath, desired, recordedDigest }) {
419
+ const file = await inspectFileSafe(mcpPath);
420
+ if (file.kind === 'missing') {
421
+ return {
422
+ path: mcpPath,
423
+ state: ANTIGRAVITY_MCP_STATES.missing,
424
+ configured: false,
425
+ managed: true,
426
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
427
+ script: desired.script,
428
+ node: desired.node,
429
+ nodeResolved: desired.node !== null,
430
+ nodeError: desired.nodeError,
431
+ reason: null,
432
+ existingDoc: null,
433
+ expectDigest: null,
434
+ };
435
+ }
436
+ if (file.kind !== 'file') {
437
+ return {
438
+ path: mcpPath,
439
+ state: ANTIGRAVITY_MCP_STATES.conflict,
440
+ configured: false,
441
+ managed: false,
442
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
443
+ script: desired.script,
444
+ node: desired.node,
445
+ nodeResolved: desired.node !== null,
446
+ nodeError: desired.nodeError,
447
+ reason: file.kind === 'link' ? 'mcp-file-is-link' : 'mcp-file-not-regular',
448
+ existingDoc: null,
449
+ expectDigest: null,
450
+ };
451
+ }
452
+ let parsed;
453
+ try {
454
+ parsed = JSON.parse(file.contents);
455
+ } catch {
456
+ return {
457
+ path: mcpPath,
458
+ state: ANTIGRAVITY_MCP_STATES.unreadable,
459
+ configured: false,
460
+ managed: false,
461
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
462
+ script: desired.script,
463
+ node: desired.node,
464
+ nodeResolved: desired.node !== null,
465
+ nodeError: desired.nodeError,
466
+ reason: 'mcp-json-invalid',
467
+ existingDoc: null,
468
+ expectDigest: digest(file.contents),
469
+ };
470
+ }
471
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
472
+ return {
473
+ path: mcpPath,
474
+ state: ANTIGRAVITY_MCP_STATES.unreadable,
475
+ configured: false,
476
+ managed: false,
477
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
478
+ script: desired.script,
479
+ node: desired.node,
480
+ nodeResolved: desired.node !== null,
481
+ nodeError: desired.nodeError,
482
+ reason: 'mcp-json-not-object',
483
+ existingDoc: null,
484
+ expectDigest: digest(file.contents),
485
+ };
486
+ }
487
+ const servers = parsed.mcpServers;
488
+ if (servers !== undefined && (servers === null || typeof servers !== 'object' || Array.isArray(servers))) {
489
+ return {
490
+ path: mcpPath,
491
+ state: ANTIGRAVITY_MCP_STATES.unreadable,
492
+ configured: false,
493
+ managed: false,
494
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
495
+ script: desired.script,
496
+ node: desired.node,
497
+ nodeResolved: desired.node !== null,
498
+ nodeError: desired.nodeError,
499
+ reason: 'mcp-servers-not-object',
500
+ existingDoc: null,
501
+ expectDigest: digest(file.contents),
502
+ };
503
+ }
504
+ const entry = servers?.[ANTIGRAVITY_MCP_SERVER_NAME];
505
+ const fileDigest = digest(file.contents);
506
+ if (entry === undefined) {
507
+ return {
508
+ path: mcpPath,
509
+ state: ANTIGRAVITY_MCP_STATES.missing,
510
+ configured: false,
511
+ managed: true,
512
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
513
+ script: desired.script,
514
+ node: desired.node,
515
+ nodeResolved: desired.node !== null,
516
+ nodeError: desired.nodeError,
517
+ reason: null,
518
+ existingDoc: parsed,
519
+ expectDigest: fileDigest,
520
+ };
521
+ }
522
+ if (!isManagedMcpShape(entry)) {
523
+ return {
524
+ path: mcpPath,
525
+ state: ANTIGRAVITY_MCP_STATES.conflict,
526
+ configured: false,
527
+ managed: false,
528
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
529
+ script: desired.script,
530
+ node: desired.node,
531
+ nodeResolved: desired.node !== null,
532
+ nodeError: desired.nodeError,
533
+ reason: 'mcp-entry-customized',
534
+ existingDoc: parsed,
535
+ expectDigest: fileDigest,
536
+ };
537
+ }
538
+ const exactMatch = desired.serverEntry !== null
539
+ && sameFsPath(entry.command, desired.serverEntry.command)
540
+ && sameFsPath(entry.args[0], desired.serverEntry.args[0])
541
+ && sameMcpEnv(entry.env, desired.serverEntry.env);
542
+ if (exactMatch) {
543
+ return {
544
+ path: mcpPath,
545
+ state: ANTIGRAVITY_MCP_STATES.configured,
546
+ configured: true,
547
+ managed: true,
548
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
549
+ script: desired.script,
550
+ node: desired.node,
551
+ nodeResolved: desired.node !== null,
552
+ nodeError: desired.nodeError,
553
+ reason: null,
554
+ existingDoc: parsed,
555
+ expectDigest: fileDigest,
556
+ };
557
+ }
558
+ const recordedMatch = typeof recordedDigest === 'string' && digestLf(file.contents) === recordedDigest;
559
+ const sameScript = sameFsPath(entry.args[0], desired.script);
560
+ const ownedMovedScript = !sameScript && await isOwnedEntryScript(entry.args[0], desired.script);
561
+ if (recordedMatch || sameScript || ownedMovedScript) {
562
+ const reasons = [];
563
+ if (desired.node !== null && !sameFsPath(entry.command, desired.node)) reasons.push('node-path-changed');
564
+ if (!sameScript) reasons.push('script-path-changed');
565
+ if (desired.serverEntry !== null && !sameMcpEnv(entry.env, desired.serverEntry.env)) reasons.push('discovery-env-changed');
566
+ return {
567
+ path: mcpPath,
568
+ state: ANTIGRAVITY_MCP_STATES.outdated,
569
+ configured: false,
570
+ managed: true,
571
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
572
+ script: desired.script,
573
+ node: desired.node,
574
+ nodeResolved: desired.node !== null,
575
+ nodeError: desired.nodeError,
576
+ reason: reasons.join(',') || 'mcp-outdated',
577
+ movedScript: ownedMovedScript,
578
+ existingDoc: parsed,
579
+ expectDigest: fileDigest,
580
+ };
581
+ }
582
+ return {
583
+ path: mcpPath,
584
+ state: ANTIGRAVITY_MCP_STATES.conflict,
585
+ configured: false,
586
+ managed: false,
587
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
588
+ script: desired.script,
589
+ node: desired.node,
590
+ nodeResolved: desired.node !== null,
591
+ nodeError: desired.nodeError,
592
+ reason: 'mcp-script-unowned',
593
+ existingDoc: parsed,
594
+ expectDigest: fileDigest,
595
+ };
596
+ }
597
+
598
+ /**
599
+ * Exact LF SHA-256 digests of prior published Antigravity managed files.
600
+ * Allows an untouched published installation (such as 1.8.0) to be recognized as
601
+ * `outdated` and upgraded cleanly even if the local ownership sidecar is absent,
602
+ * while any operator-edited file still classifies as `modified` and is preserved.
603
+ */
604
+ const KNOWN_PRIOR_ANTIGRAVITY_FILES = Object.freeze({
605
+ 'skills/dsh-taskbridge/SKILL.md': Object.freeze([
606
+ // Published 1.8.0 SKILL.md (LF)
607
+ '9e83135ece937dbc0b73f5098509daac2fe4b973fe4dcd2ed75186745cf3cfee',
608
+ // Published 1.8.1 / 1.9.0-test1 SKILL.md (LF)
609
+ 'cb4b0645dbe0de74dce89c286ab61d91e258f24b85edfe6e6ade9362c9f31c14',
610
+ // Pre-layered 1.9.0 balanced SKILL.md (LF)
611
+ '72cf86f41fee5482bb78379949709ec61069997a738060c0bedfb806175e168a',
612
+ // Layered 1.9.0-test2 .. test4 SKILL.md (LF)
613
+ '0346fd973a7a81ed90e8406b11c39953da4165192ce1dddbb70b714ffa771e9c',
614
+ // Layered 1.9.0-test5 SKILL.md (LF)
615
+ '2d3351c1eccce74715929d9fee47d930d3729876db9807ed32be45caed805b1c',
616
+ // Layered 1.9.0-test6 SKILL.md (LF)
617
+ '731c17aa516059a7fc6180b848d2c830b66a1d7117cae8415eb85318ed067093',
618
+ // Layered 1.9.0-preview SKILL.md (LF)
619
+ 'ce3a02c9b9ba4e45be30f3ba83ec93ee5254da64f643f12bfcc841dd9dbd2e3f',
620
+ // Layered 1.9.0-preview2 / preview3 SKILL.md (LF)
621
+ 'b27118375a6f87fc35ea623c131912ef1545adc84f7c0c5a94790d12b73d4d4d',
622
+ ]),
623
+ 'agents/dsh-taskbridge.md': Object.freeze([
624
+ // Published 1.8.0 agents/dsh-taskbridge.md (LF)
625
+ 'df1418abe2c58c535734ecf6619bd027ca251d2dd6043cec9f41561d8e0a432b',
626
+ // Published 1.8.1 / 1.9.0-test1 agents/dsh-taskbridge.md (LF)
627
+ 'cadb5f5f4de640c89b924a75f53a09d38ee68df22086b5aa4aa516192970055b',
628
+ // Pre-layered 1.9.0 slim agents/dsh-taskbridge.md (LF)
629
+ 'c26f3272c4a164ec4fe5977aeb8033b296329120445f197121d8087052b5e175',
630
+ // Layered 1.9.0-test2 .. test5 agents/dsh-taskbridge.md (LF)
631
+ 'de2c85d753f0eed941c5942d1eba4e2aace921f138cab1b81fe4391f01a02a09',
632
+ // Layered 1.9.0-test6 agents/dsh-taskbridge.md (LF)
633
+ 'fa31106b0c0433941d3d1a92bab5a100b9d25c8af3a87687c2b04032ff5cea3d',
634
+ // Layered 1.9.0-preview .. preview3 agents/dsh-taskbridge.md (LF)
635
+ '52648163cbb532a6d3dbe37b82e0efb27c9a26c207462d6740ec0abfa119ee8a',
636
+ ]),
637
+ });
638
+
639
+ function isManagedAntigravityManifest(contents) {
640
+ try {
641
+ const parsed = JSON.parse(contents);
642
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
643
+ if (typeof parsed.version !== 'string' || parsed.version.trim() === '') return false;
644
+ return sameTextLf(contents, renderAntigravityManifest(parsed.version));
645
+ } catch {
646
+ return false;
647
+ }
648
+ }
649
+
650
+ async function classifyPluginFiles({ paths, templates, recordedFiles }) {
651
+ const details = {};
652
+ for (const key of PLUGIN_FILE_KEYS) {
653
+ const targetPath = paths.files[key];
654
+ const desiredText = templates.files[key];
655
+ const file = await inspectFileSafe(targetPath);
656
+ if (file.kind === 'missing') {
657
+ details[key] = { path: targetPath, state: 'not-installed', expectDigest: null };
658
+ continue;
659
+ }
660
+ if (file.kind !== 'file') {
661
+ details[key] = {
662
+ path: targetPath,
663
+ state: 'conflict',
664
+ reason: file.kind === 'link' ? 'file-is-link' : 'file-not-regular',
665
+ expectDigest: null,
666
+ };
667
+ continue;
668
+ }
669
+ const rawDigest = digest(file.contents);
670
+ if (sameTextLf(file.contents, desiredText)) {
671
+ details[key] = { path: targetPath, state: 'installed', expectDigest: rawDigest };
672
+ continue;
673
+ }
674
+ const recorded = recordedFiles?.[key] ?? null;
675
+ const lfDigest = digestLf(file.contents);
676
+ if (typeof recorded === 'string' && lfDigest === recorded) {
677
+ details[key] = { path: targetPath, state: 'outdated', expectDigest: rawDigest };
678
+ continue;
679
+ }
680
+ if (Array.isArray(KNOWN_PRIOR_ANTIGRAVITY_FILES[key]) && KNOWN_PRIOR_ANTIGRAVITY_FILES[key].includes(lfDigest)) {
681
+ details[key] = { path: targetPath, state: 'outdated', expectDigest: rawDigest };
682
+ continue;
683
+ }
684
+ if (key === 'plugin.json' && isManagedAntigravityManifest(file.contents)) {
685
+ details[key] = { path: targetPath, state: 'outdated', expectDigest: rawDigest };
686
+ continue;
687
+ }
688
+ details[key] = { path: targetPath, state: 'modified', expectDigest: rawDigest };
689
+ }
690
+ const states = Object.values(details).map((entry) => entry.state);
691
+ let state;
692
+ if (states.includes('conflict')) state = ANTIGRAVITY_PLUGIN_STATES.conflict;
693
+ else if (states.includes('modified')) state = ANTIGRAVITY_PLUGIN_STATES.modified;
694
+ else if (states.every((s) => s === 'not-installed')) state = ANTIGRAVITY_PLUGIN_STATES.missing;
695
+ else if (states.every((s) => s === 'installed')) state = ANTIGRAVITY_PLUGIN_STATES.installed;
696
+ else state = ANTIGRAVITY_PLUGIN_STATES.outdated;
697
+ return {
698
+ path: paths.pluginDir,
699
+ state,
700
+ installed: state === ANTIGRAVITY_PLUGIN_STATES.installed,
701
+ managed: state !== ANTIGRAVITY_PLUGIN_STATES.modified && state !== ANTIGRAVITY_PLUGIN_STATES.conflict,
702
+ files: details,
703
+ };
704
+ }
705
+
706
+ export async function readAntigravityStatus(options = {}) {
707
+ const env = options.env ?? process.env;
708
+ const selectedHome = typeof options.antigravityHome === 'string' && options.antigravityHome.trim() !== ''
709
+ ? requireAntigravityHome(options.antigravityHome)
710
+ : resolveAntigravityHome({ env, homeDirectory: options.homeDirectory });
711
+
712
+ const pinned = await pinAntigravityHome(selectedHome);
713
+ const templates = await readAntigravityTemplates(options.version ?? null);
714
+ const paths = pluginPathsFor(pinned.real);
715
+ const desiredMcp = desiredMcpConfig(options);
716
+ const notes = [];
717
+
718
+ if (pinned.error !== null) {
719
+ notes.push({ code: pinned.error.reason, text: pinned.error.message });
720
+ return {
721
+ antigravityHome: pinned.selected,
722
+ realAntigravityHome: pinned.real,
723
+ pluginDir: paths.pluginDir,
724
+ packageVersion: templates.version,
725
+ plugin: { path: paths.pluginDir, state: ANTIGRAVITY_PLUGIN_STATES.conflict, installed: false, managed: false, files: {} },
726
+ mcp: {
727
+ path: paths.mcpPath,
728
+ state: ANTIGRAVITY_MCP_STATES.conflict,
729
+ configured: false,
730
+ managed: false,
731
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
732
+ script: desiredMcp.script,
733
+ node: desiredMcp.node,
734
+ nodeResolved: desiredMcp.node !== null,
735
+ nodeError: desiredMcp.nodeError,
736
+ reason: pinned.error.reason,
737
+ },
738
+ ready: false,
739
+ notes,
740
+ };
741
+ }
742
+
743
+ const boundary = await inspectBoundaries(pinned.real, paths);
744
+ if (!boundary.ok) {
745
+ notes.push({
746
+ code: boundary.reason,
747
+ text: `检测到非普通目录边界(${boundary.path}),插件不会穿过软链接或异常路径写入文件。`,
748
+ });
749
+ return {
750
+ antigravityHome: pinned.selected,
751
+ realAntigravityHome: pinned.real,
752
+ pluginDir: paths.pluginDir,
753
+ packageVersion: templates.version,
754
+ plugin: { path: paths.pluginDir, state: ANTIGRAVITY_PLUGIN_STATES.conflict, installed: false, managed: false, files: {} },
755
+ mcp: {
756
+ path: paths.mcpPath,
757
+ state: ANTIGRAVITY_MCP_STATES.conflict,
758
+ configured: false,
759
+ managed: false,
760
+ serverName: ANTIGRAVITY_MCP_SERVER_NAME,
761
+ script: desiredMcp.script,
762
+ node: desiredMcp.node,
763
+ nodeResolved: desiredMcp.node !== null,
764
+ nodeError: desiredMcp.nodeError,
765
+ reason: boundary.reason,
766
+ },
767
+ ready: false,
768
+ notes,
769
+ };
770
+ }
771
+
772
+ const ownership = await readOwnershipRecord(pinned.real, env);
773
+ const plugin = await classifyPluginFiles({
774
+ paths,
775
+ templates,
776
+ recordedFiles: ownership?.files ?? {},
777
+ });
778
+ const mcp = await classifyMcpFile({
779
+ mcpPath: paths.mcpPath,
780
+ desired: desiredMcp,
781
+ recordedDigest: ownership?.files?.[MCP_FILE_KEY] ?? null,
782
+ });
783
+
784
+ if (desiredMcp.nodeError !== null) {
785
+ notes.push({
786
+ code: desiredMcp.nodeError.code,
787
+ text: '未找到可用的 Node.js 运行时,无法写入 MCP 配置(不会写入桌面应用自身的 exe)。',
788
+ });
789
+ }
790
+ if (plugin.state === ANTIGRAVITY_PLUGIN_STATES.modified) {
791
+ notes.push({
792
+ code: 'PLUGIN_USER_MODIFIED',
793
+ text: '检测到插件目录内有你自定义修改过的文件,安装与卸载都会保留它们;若仅需恢复连接,可点「仅修复 MCP 配置」。',
794
+ });
795
+ }
796
+ if (mcp.state === ANTIGRAVITY_MCP_STATES.conflict || mcp.state === ANTIGRAVITY_MCP_STATES.unreadable) {
797
+ notes.push({
798
+ code: 'MCP_CONFLICT',
799
+ text: 'plugins/dsh-taskbridge/mcp_config.json 存在自定义内容或格式错误,插件不会覆盖。',
800
+ });
801
+ }
802
+
803
+ return {
804
+ antigravityHome: pinned.selected,
805
+ realAntigravityHome: pinned.real,
806
+ pluginDir: paths.pluginDir,
807
+ packageVersion: templates.version,
808
+ plugin,
809
+ mcp,
810
+ ready: plugin.installed && mcp.configured,
811
+ notes,
812
+ };
813
+ }
814
+
815
+ async function ensureManagedDirs(paths) {
816
+ for (const dir of paths.dirs) {
817
+ const info = await inspectDirectory(dir).catch(() => ({ kind: 'unknown' }));
818
+ if (info.kind === 'directory') continue;
819
+ if (info.kind !== 'missing') {
820
+ throw new AntigravityInstallError('ANTIGRAVITY_PATH_CONFLICT', `refused to traverse non-directory ${dir}`);
821
+ }
822
+ await mkdir(dir, { mode: 0o700 });
823
+ const after = await inspectDirectory(dir).catch(() => ({ kind: 'unknown' }));
824
+ if (after.kind !== 'directory') {
825
+ throw new AntigravityInstallError('ANTIGRAVITY_PATH_CONFLICT', `created directory ${dir} could not be verified`);
826
+ }
827
+ }
828
+ }
829
+
830
+ async function ensureRootDir(realHome) {
831
+ const info = await inspectDirectory(realHome).catch(() => ({ kind: 'unknown' }));
832
+ if (info.kind === 'directory') return;
833
+ if (info.kind !== 'missing') {
834
+ throw new AntigravityInstallError('ANTIGRAVITY_HOME_UNUSABLE', `refused to use non-directory ${realHome}`);
835
+ }
836
+ await mkdir(realHome, { recursive: true, mode: 0o700 });
837
+ }
838
+
839
+ async function verifyUnchanged(filePath, expectDigest) {
840
+ const current = await inspectFileSafe(filePath);
841
+ if (expectDigest === null) return current.kind === 'missing';
842
+ return current.kind === 'file' && digest(current.contents) === expectDigest;
843
+ }
844
+
845
+ async function removeEmptyDirs(dirs) {
846
+ for (const dir of [...dirs].reverse()) {
847
+ try {
848
+ const entries = await readdir(dir);
849
+ if (entries.length === 0) await rmdir(dir);
850
+ } catch {
851
+ // ignore missing or non-empty dirs
852
+ }
853
+ }
854
+ }
855
+
856
+ export async function runAntigravityAction(action, options = {}) {
857
+ if (!ANTIGRAVITY_ACTIONS.includes(action)) {
858
+ throw new AntigravityInstallError('ANTIGRAVITY_ACTION_INVALID', `unknown action ${String(action)}`);
859
+ }
860
+ if (action === 'status') {
861
+ return { changed: [], refused: [], status: await readAntigravityStatus(options) };
862
+ }
863
+
864
+ const env = options.env ?? process.env;
865
+ const before = await readAntigravityStatus(options);
866
+ const templates = await readAntigravityTemplates(options.version ?? null);
867
+ const paths = pluginPathsFor(before.realAntigravityHome);
868
+ const desiredMcp = desiredMcpConfig(options);
869
+ const ownership = await readOwnershipRecord(before.realAntigravityHome, env);
870
+ const nextDigests = { ...(ownership?.files ?? {}) };
871
+ const changed = [];
872
+ const refused = [];
873
+
874
+ if (before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.conflict) {
875
+ refused.push({ target: 'plugin', code: 'ANTIGRAVITY_PATH_CONFLICT', message: 'plugin directory boundary conflict' });
876
+ refused.push({ target: 'mcp', code: 'ANTIGRAVITY_PATH_CONFLICT', message: 'plugin directory boundary conflict' });
877
+ return { changed, refused, status: before };
878
+ }
879
+
880
+ if (action === 'install') {
881
+ await ensureRootDir(before.realAntigravityHome);
882
+ await ensureManagedDirs(paths);
883
+
884
+ // 1. Plugin bundle files (per-file: write missing/outdated managed files, preserve user-modified ones)
885
+ let wrotePlugin = false;
886
+ let modifiedPlugin = false;
887
+ let pluginConflict = false;
888
+ for (const key of PLUGIN_FILE_KEYS) {
889
+ const entry = before.plugin.files[key];
890
+ if (entry?.state === 'installed') {
891
+ nextDigests[key] = digestLf(templates.files[key]);
892
+ continue;
893
+ }
894
+ if (entry?.state === 'modified') {
895
+ modifiedPlugin = true;
896
+ continue;
897
+ }
898
+ if (entry?.state !== 'not-installed' && entry?.state !== 'outdated') {
899
+ pluginConflict = true;
900
+ continue;
901
+ }
902
+ if (!(await verifyUnchanged(paths.files[key], entry?.expectDigest ?? null))) {
903
+ pluginConflict = true;
904
+ break;
905
+ }
906
+ await writeFileAtomic(paths.files[key], templates.files[key]);
907
+ nextDigests[key] = digestLf(templates.files[key]);
908
+ wrotePlugin = true;
909
+ }
910
+ if (wrotePlugin) changed.push('plugin');
911
+ if (pluginConflict) {
912
+ refused.push({ target: 'plugin', code: 'PLUGIN_CHANGED_CONCURRENTLY', message: 'plugin file changed during install' });
913
+ } else if (modifiedPlugin) {
914
+ refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
915
+ }
916
+
917
+ // 2. MCP config file
918
+ await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
919
+ await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
920
+ } else if (action === 'repair') {
921
+ await ensureRootDir(before.realAntigravityHome);
922
+ await ensureManagedDirs(paths);
923
+
924
+ // Repair touches mcp_config.json (and creates/updates plugin.json only if missing/outdated
925
+ // so Antigravity discovers the plugin), never touching SKILL.md or agents/dsh-taskbridge.md.
926
+ const manifestEntry = before.plugin.files['plugin.json'];
927
+ if (manifestEntry?.state === 'not-installed' || manifestEntry?.state === 'outdated') {
928
+ if (await verifyUnchanged(paths.files['plugin.json'], manifestEntry.expectDigest ?? null)) {
929
+ await writeFileAtomic(paths.files['plugin.json'], templates.files['plugin.json']);
930
+ nextDigests['plugin.json'] = digestLf(templates.files['plugin.json']);
931
+ }
932
+ }
933
+ await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
934
+ await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
935
+ } else if (action === 'remove') {
936
+ // 1. Remove verified managed plugin files only
937
+ let removedPlugin = false;
938
+ let refusedPlugin = false;
939
+ for (const key of PLUGIN_FILE_KEYS) {
940
+ const entry = before.plugin.files[key];
941
+ if (!entry || entry.state === 'not-installed') {
942
+ delete nextDigests[key];
943
+ continue;
944
+ }
945
+ if (entry.state !== 'installed' && entry.state !== 'outdated') {
946
+ refusedPlugin = true;
947
+ continue;
948
+ }
949
+ if (!(await verifyUnchanged(paths.files[key], entry.expectDigest))) {
950
+ refusedPlugin = true;
951
+ continue;
952
+ }
953
+ await unlink(paths.files[key]);
954
+ delete nextDigests[key];
955
+ removedPlugin = true;
956
+ }
957
+ if (removedPlugin) changed.push('plugin');
958
+ if (refusedPlugin) {
959
+ refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
960
+ }
961
+
962
+ // 2. Remove managed MCP entry only
963
+ if (before.mcp.state === ANTIGRAVITY_MCP_STATES.configured || before.mcp.state === ANTIGRAVITY_MCP_STATES.outdated) {
964
+ if (await verifyUnchanged(paths.mcpPath, before.mcp.expectDigest)) {
965
+ const doc = { ...(before.mcp.existingDoc ?? {}) };
966
+ const servers = { ...(doc.mcpServers ?? {}) };
967
+ delete servers[ANTIGRAVITY_MCP_SERVER_NAME];
968
+ if (Object.keys(servers).length === 0 && Object.keys(doc).every((k) => k === 'mcpServers')) {
969
+ await unlink(paths.mcpPath);
970
+ } else {
971
+ doc.mcpServers = servers;
972
+ await writeFileAtomic(paths.mcpPath, `${JSON.stringify(doc, null, 2)}\n`);
973
+ }
974
+ delete nextDigests[MCP_FILE_KEY];
975
+ changed.push('mcp');
976
+ } else {
977
+ refused.push({ target: 'mcp', code: 'MCP_CHANGED_CONCURRENTLY', message: 'mcp_config.json changed during remove' });
978
+ }
979
+ } else if (before.mcp.state === ANTIGRAVITY_MCP_STATES.conflict || before.mcp.state === ANTIGRAVITY_MCP_STATES.unreadable) {
980
+ refused.push({ target: 'mcp', code: 'MCP_USER_MODIFIED', message: 'customized mcp_config.json was preserved' });
981
+ }
982
+
983
+ await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
984
+ // Clean empty directories inside plugins/dsh-taskbridge only (never remove plugins/ itself).
985
+ await removeEmptyDirs(paths.dirs.slice(1));
986
+ }
987
+
988
+ return { changed, refused, status: await readAntigravityStatus(options) };
989
+ }
990
+
991
+ async function applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused }) {
992
+ if (desiredMcp.serverEntry === null) {
993
+ refused.push({
994
+ target: 'mcp',
995
+ code: desiredMcp.nodeError?.code ?? 'MCP_EXECUTABLE_UNRESOLVED',
996
+ message: desiredMcp.nodeError?.message ?? 'no Node.js executable available',
997
+ });
998
+ return;
999
+ }
1000
+ if (before.mcp.state === ANTIGRAVITY_MCP_STATES.configured) {
1001
+ const existing = await inspectFileSafe(paths.mcpPath);
1002
+ if (existing.kind === 'file') nextDigests[MCP_FILE_KEY] = digestLf(existing.contents);
1003
+ return;
1004
+ }
1005
+ if (before.mcp.state !== ANTIGRAVITY_MCP_STATES.missing && before.mcp.state !== ANTIGRAVITY_MCP_STATES.outdated) {
1006
+ refused.push({
1007
+ target: 'mcp',
1008
+ code: before.mcp.state === ANTIGRAVITY_MCP_STATES.unreadable ? 'MCP_UNREADABLE' : 'MCP_CONFLICT',
1009
+ message: 'mcp_config.json cannot be overwritten safely',
1010
+ });
1011
+ return;
1012
+ }
1013
+ if (!(await verifyUnchanged(paths.mcpPath, before.mcp.expectDigest ?? null))) {
1014
+ refused.push({ target: 'mcp', code: 'MCP_CHANGED_CONCURRENTLY', message: 'mcp_config.json changed during write' });
1015
+ return;
1016
+ }
1017
+ const rendered = renderMcpDocument(before.mcp.existingDoc, desiredMcp.serverEntry);
1018
+ await writeFileAtomic(paths.mcpPath, rendered);
1019
+ nextDigests[MCP_FILE_KEY] = digestLf(rendered);
1020
+ changed.push('mcp');
1021
+ }
1022
+
1023
+ export async function refreshManagedAntigravityPlugin(options = {}) {
1024
+ const before = await readAntigravityStatus(options);
1025
+ const env = options.env ?? process.env;
1026
+ const templates = await readAntigravityTemplates(options.version ?? null);
1027
+ const paths = pluginPathsFor(before.realAntigravityHome);
1028
+ const desiredMcp = desiredMcpConfig(options);
1029
+ const ownership = await readOwnershipRecord(before.realAntigravityHome, env);
1030
+ const nextDigests = { ...(ownership?.files ?? {}) };
1031
+ const changed = [];
1032
+ const refused = [];
1033
+
1034
+ // Never create a fresh installation on startup. Upgrade only provably existing
1035
+ // managed plugin files (per-file when another file was customized by the user).
1036
+ const pluginEntries = Object.values(before.plugin.files ?? {});
1037
+ const hasOutdatedPluginFile = before.plugin.state !== ANTIGRAVITY_PLUGIN_STATES.conflict
1038
+ && pluginEntries.some((entry) => entry?.state === 'outdated');
1039
+ const hasExistingManagedPlugin = before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.outdated || hasOutdatedPluginFile;
1040
+ const hasExistingStaleMcp = before.mcp.state === ANTIGRAVITY_MCP_STATES.outdated && before.mcp.movedScript !== true;
1041
+ if (!hasExistingManagedPlugin && !hasExistingStaleMcp) {
1042
+ return { changed, refused, status: before };
1043
+ }
1044
+
1045
+ if (hasExistingManagedPlugin) {
1046
+ await ensureManagedDirs(paths);
1047
+ const fillMissing = before.plugin.state === ANTIGRAVITY_PLUGIN_STATES.outdated;
1048
+ let wrotePlugin = false;
1049
+ let modifiedPlugin = false;
1050
+ let pluginConflict = false;
1051
+ for (const key of PLUGIN_FILE_KEYS) {
1052
+ const entry = before.plugin.files[key];
1053
+ if (entry?.state === 'modified') {
1054
+ modifiedPlugin = true;
1055
+ continue;
1056
+ }
1057
+ const shouldWrite = entry?.state === 'outdated' || (fillMissing && entry?.state === 'not-installed');
1058
+ if (!shouldWrite) continue;
1059
+ if (!(await verifyUnchanged(paths.files[key], entry?.expectDigest ?? null))) {
1060
+ pluginConflict = true;
1061
+ break;
1062
+ }
1063
+ await writeFileAtomic(paths.files[key], templates.files[key]);
1064
+ nextDigests[key] = digestLf(templates.files[key]);
1065
+ wrotePlugin = true;
1066
+ }
1067
+ if (wrotePlugin) changed.push('plugin');
1068
+ if (pluginConflict) {
1069
+ refused.push({ target: 'plugin', code: 'PLUGIN_CHANGED_CONCURRENTLY', message: 'plugin file changed during refresh' });
1070
+ } else if (modifiedPlugin) {
1071
+ refused.push({ target: 'plugin', code: 'PLUGIN_USER_MODIFIED', message: 'customized plugin files were preserved' });
1072
+ }
1073
+ }
1074
+
1075
+ if (hasExistingStaleMcp) {
1076
+ await ensureManagedDirs(paths);
1077
+ await applyMcpWrite({ before, desiredMcp, paths, nextDigests, changed, refused });
1078
+ }
1079
+
1080
+ if (changed.length > 0) {
1081
+ await writeOwnershipRecord(before.realAntigravityHome, paths.pluginDir, nextDigests, env);
1082
+ }
1083
+ return { changed, refused, status: await readAntigravityStatus(options) };
1084
+ }
1085
+
1086
+ export function publicAntigravityStatus(status) {
1087
+ if (status === null || typeof status !== 'object') return status;
1088
+ const files = {};
1089
+ for (const [key, entry] of Object.entries(status.plugin?.files ?? {})) {
1090
+ const { expectDigest: _ignored, ...pub } = entry ?? {};
1091
+ files[key] = pub;
1092
+ }
1093
+ const { existingDoc: _doc, expectDigest: _digest, ...mcp } = status.mcp ?? {};
1094
+ return {
1095
+ ...status,
1096
+ plugin: { ...(status.plugin ?? {}), files },
1097
+ mcp,
1098
+ };
1099
+ }