@tinchu0/knitt 0.1.0-beta.4 → 0.1.0-beta.6

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 (33) hide show
  1. package/README.md +24 -15
  2. package/dist/apps/server/src/cloud-picker.js +245 -0
  3. package/dist/apps/server/src/http-gateway.js +1 -1
  4. package/dist/apps/server/src/main.js +6 -2
  5. package/dist/apps/server/src/onboarding.js +266 -0
  6. package/dist/apps/server/src/plugin-bootstrap.js +82 -0
  7. package/dist/apps/server/src/plugin-hook.js +51 -0
  8. package/dist/apps/server/src/plugin-main.js +10 -0
  9. package/dist/apps/server/src/server.js +108 -29
  10. package/dist/packages/adapters/src/cli.js +19 -2
  11. package/dist/packages/adapters/src/handoff.js +10 -6
  12. package/dist/packages/adapters/src/histories.js +221 -0
  13. package/dist/packages/adapters/src/history-time.js +10 -0
  14. package/dist/packages/adapters/src/hooks.js +8 -8
  15. package/dist/packages/adapters/src/picker.js +2 -1
  16. package/dist/packages/adapters/src/question-ui.js +37 -0
  17. package/dist/packages/adapters/src/scope.js +9 -3
  18. package/dist/packages/adapters/src/server-name.js +5 -0
  19. package/dist/packages/adapters/src/transcript.js +2 -0
  20. package/dist/packages/cloud/src/client.js +40 -0
  21. package/dist/packages/cloud/src/local-sync.js +300 -0
  22. package/dist/packages/installer/src/antigravity.js +90 -0
  23. package/dist/packages/installer/src/cli.js +77 -30
  24. package/dist/packages/installer/src/cloud-cli.js +199 -0
  25. package/dist/packages/installer/src/connections.js +37 -9
  26. package/dist/packages/installer/src/runtime.js +2 -2
  27. package/dist/packages/memory/src/store.js +36 -0
  28. package/dist/skills/knit/SKILL.md +27 -5
  29. package/docs/clients/connector-setup.md +1 -1
  30. package/docs/clients/npm-installation.md +28 -12
  31. package/docs/clients/support-matrix.md +12 -0
  32. package/docs/usage.md +28 -29
  33. package/package.json +6 -3
@@ -0,0 +1,300 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { chmodSync, mkdirSync, realpathSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import { credentials, api, CloudError } from "./client.js";
6
+ import { discoverHistories, } from "../../adapters/src/histories.js";
7
+ import { importConversation } from "../../adapters/src/handoff.js";
8
+ import { MemoryStore } from "../../memory/src/store.js";
9
+ export const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
10
+ export function canonicalWorkspace(workspace) {
11
+ return realpathSync(resolve(workspace));
12
+ }
13
+ export function syncDatabase(home) {
14
+ const directory = join(home, "cloud");
15
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
16
+ const path = join(directory, "sync.sqlite");
17
+ const db = new DatabaseSync(path);
18
+ chmodSync(path, 0o600);
19
+ db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
20
+ CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY,value TEXT NOT NULL);
21
+ CREATE TABLE IF NOT EXISTS bindings(key TEXT PRIMARY KEY,origin TEXT NOT NULL,account TEXT NOT NULL,workspace TEXT NOT NULL,project TEXT NOT NULL,enabled INTEGER NOT NULL,roots TEXT NOT NULL);
22
+ CREATE TABLE IF NOT EXISTS uploads(id TEXT PRIMARY KEY,binding TEXT NOT NULL,payload TEXT NOT NULL,delivered INTEGER NOT NULL DEFAULT 0);
23
+ CREATE TABLE IF NOT EXISTS sync_errors(binding TEXT PRIMARY KEY,message TEXT NOT NULL,at TEXT NOT NULL);`);
24
+ db.prepare("INSERT OR IGNORE INTO settings VALUES(?,?)").run("installationId", randomUUID());
25
+ return db;
26
+ }
27
+ export function bindingKey(device, workspace) {
28
+ return digest([
29
+ device.origin,
30
+ device.account.id,
31
+ device.device.id,
32
+ canonicalWorkspace(workspace),
33
+ ]);
34
+ }
35
+ export function syncStatus(home, workspace) {
36
+ const device = credentials(home), db = syncDatabase(home);
37
+ try {
38
+ const binding = device
39
+ ? db
40
+ .prepare("SELECT project,enabled,roots FROM bindings WHERE key=?")
41
+ .get(bindingKey(device, workspace))
42
+ : undefined;
43
+ const key = device ? bindingKey(device, workspace) : "";
44
+ const pending = db
45
+ .prepare("SELECT COUNT(*) AS count FROM uploads WHERE binding=? AND delivered=0")
46
+ .get(key);
47
+ const error = db
48
+ .prepare("SELECT message,at FROM sync_errors WHERE binding=?")
49
+ .get(key);
50
+ return {
51
+ connected: !!device,
52
+ account: device?.account,
53
+ device: device?.device,
54
+ workspace: canonicalWorkspace(workspace),
55
+ binding: binding
56
+ ? {
57
+ projectId: String(binding.project),
58
+ enabled: !!binding.enabled,
59
+ historyRoots: JSON.parse(String(binding.roots)),
60
+ }
61
+ : null,
62
+ pending: Number(pending?.count ?? 0),
63
+ error: error ?? null,
64
+ lastSuccessfulSync: db
65
+ .prepare("SELECT value FROM settings WHERE key=?")
66
+ .get("lastSync:" + key)?.value ?? null,
67
+ };
68
+ }
69
+ finally {
70
+ db.close();
71
+ }
72
+ }
73
+ export function bindWorkspace(home, device, workspace, projectId, roots) {
74
+ const db = syncDatabase(home);
75
+ try {
76
+ const key = bindingKey(device, workspace);
77
+ const previous = db
78
+ .prepare("SELECT project, roots FROM bindings WHERE key=?")
79
+ .get(key);
80
+ if (previous &&
81
+ (previous.project !== projectId ||
82
+ previous.roots !== JSON.stringify(roots))) {
83
+ db.prepare("DELETE FROM uploads WHERE binding=?").run(key);
84
+ }
85
+ db.prepare("INSERT INTO bindings VALUES(?,?,?,?,?,?,?) ON CONFLICT(key) DO UPDATE SET project=excluded.project,enabled=1,roots=excluded.roots").run(bindingKey(device, workspace), device.origin, device.account.id, canonicalWorkspace(workspace), projectId, 1, JSON.stringify(roots));
86
+ }
87
+ finally {
88
+ db.close();
89
+ }
90
+ }
91
+ export async function controlSync(home, workspace, action) {
92
+ const device = credentials(home);
93
+ if (!device)
94
+ throw new Error("Connect an account first.");
95
+ const db = syncDatabase(home);
96
+ try {
97
+ const key = bindingKey(device, workspace), binding = db.prepare("SELECT * FROM bindings WHERE key=?").get(key);
98
+ if (!binding)
99
+ throw new Error("This workspace has no approved sync mapping.");
100
+ // Disable locally first, including when the server is offline.
101
+ if (action !== "resume")
102
+ db.prepare("UPDATE bindings SET enabled=0 WHERE key=?").run(key);
103
+ await api(device, `/api/private/projects/${encodeURIComponent(String(binding.project))}/control`, { action });
104
+ if (action === "resume")
105
+ db.prepare("UPDATE bindings SET enabled=1 WHERE key=?").run(key);
106
+ if (action === "disconnect") {
107
+ db.prepare("DELETE FROM uploads WHERE binding=?").run(key);
108
+ db.prepare("DELETE FROM bindings WHERE key=?").run(key);
109
+ }
110
+ return { action, enabled: action === "resume" };
111
+ }
112
+ finally {
113
+ db.close();
114
+ }
115
+ }
116
+ const running = new Map();
117
+ export function syncWorkspace(home, env, workspace) {
118
+ const key = resolve(home) + ":" + canonicalWorkspace(workspace);
119
+ const active = running.get(key);
120
+ if (active)
121
+ return active;
122
+ const promise = performSync(home, env, workspace).finally(() => running.delete(key));
123
+ running.set(key, promise);
124
+ return promise;
125
+ }
126
+ async function performSync(home, _env, workspace) {
127
+ const device = credentials(home);
128
+ if (!device)
129
+ return { skipped: "disconnected" };
130
+ const db = syncDatabase(home), key = bindingKey(device, workspace);
131
+ try {
132
+ const binding = db
133
+ .prepare("SELECT * FROM bindings WHERE key=? AND enabled=1")
134
+ .get(key);
135
+ if (!binding)
136
+ return { skipped: "consent_required_or_paused" };
137
+ await api(device, `/api/private/projects/${encodeURIComponent(String(binding.project))}/status`, {
138
+ status: "syncing",
139
+ pendingCount: Number(db
140
+ .prepare("SELECT COUNT(*) AS count FROM uploads WHERE binding=? AND delivered=0")
141
+ .get(key).count),
142
+ }).catch(() => { });
143
+ const installationId = String(db
144
+ .prepare("SELECT value FROM settings WHERE key=?")
145
+ .get("installationId").value);
146
+ const roots = JSON.parse(String(binding.roots));
147
+ const conversations = discoverHistories({
148
+ roots,
149
+ workspace: canonicalWorkspace(workspace),
150
+ });
151
+ let imported = 0;
152
+ let importErrors = 0;
153
+ for (const conversation of conversations) {
154
+ try {
155
+ const root = realpathSync(conversation.root), agent = conversation.client ?? "antigravity";
156
+ const id = digest([binding.project, agent, conversation.id]);
157
+ const directory = join(home, "cloud", "imports", id);
158
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
159
+ const store = new MemoryStore(join(directory, "events.sqlite"));
160
+ const events = [];
161
+ try {
162
+ const report = importConversation({
163
+ conversation: { ...conversation, branch: undefined },
164
+ repoId: id,
165
+ directory: join(directory, "queue"),
166
+ store,
167
+ });
168
+ let before;
169
+ const ordered = [];
170
+ do {
171
+ const page = store.search({
172
+ repoId: id,
173
+ featureId: report.featureId,
174
+ before,
175
+ limit: 20,
176
+ });
177
+ for (const event of page.matches)
178
+ ordered.push({
179
+ id: event.eventId,
180
+ text: store.evidence(id, event.eventId).content,
181
+ });
182
+ before = page.nextCursor ?? undefined;
183
+ } while (before);
184
+ let role = "assistant";
185
+ ordered.reverse().forEach((event, index) => {
186
+ if (event.text.startsWith("user: "))
187
+ role = "user";
188
+ else if (event.text.startsWith("assistant: ") ||
189
+ event.text.startsWith("model: "))
190
+ role = "assistant";
191
+ events.push({ ...event, sequence: index + 1, role });
192
+ });
193
+ }
194
+ finally {
195
+ store.close();
196
+ }
197
+ for (let offset = 0; offset < events.length; offset += 40) {
198
+ const chunk = events.slice(offset, offset + 40), batchId = digest([key, id, chunk]);
199
+ const payload = {
200
+ projectId: String(binding.project),
201
+ batchId,
202
+ conversations: [
203
+ {
204
+ id,
205
+ origin: agent,
206
+ sessionId: conversation.id,
207
+ title: conversation.title,
208
+ provenance: {
209
+ installationId,
210
+ ...(conversation.branch
211
+ ? { branch: conversation.branch }
212
+ : {}),
213
+ },
214
+ events: chunk,
215
+ },
216
+ ],
217
+ };
218
+ db.prepare("INSERT OR IGNORE INTO uploads(id,binding,payload) VALUES(?,?,?)").run(batchId, key, JSON.stringify(payload));
219
+ }
220
+ imported++;
221
+ }
222
+ catch (error) {
223
+ importErrors++;
224
+ db.prepare("INSERT OR REPLACE INTO sync_errors VALUES(?,?,?)").run(key, String(error), new Date().toISOString());
225
+ }
226
+ }
227
+ let delivered = 0;
228
+ // Each persisted batch is replayed exactly after network failures or restart.
229
+ for (const row of db
230
+ .prepare("SELECT id,payload FROM uploads WHERE binding=? AND delivered=0 ORDER BY rowid")
231
+ .all(key)) {
232
+ const current = credentials(home);
233
+ if (!current ||
234
+ current.account.id !== device.account.id ||
235
+ current.device.id !== device.device.id ||
236
+ current.origin !== device.origin)
237
+ break;
238
+ if (!db
239
+ .prepare("SELECT 1 FROM bindings WHERE key=? AND enabled=1 AND project=? AND roots=?")
240
+ .get(key, binding.project, binding.roots))
241
+ break;
242
+ await api(current, "/api/private/sync", JSON.parse(String(row.payload)));
243
+ db.prepare("UPDATE uploads SET delivered=1 WHERE id=?").run(row.id);
244
+ delivered++;
245
+ }
246
+ const pending = Number(db
247
+ .prepare("SELECT COUNT(*) AS count FROM uploads WHERE binding=? AND delivered=0")
248
+ .get(key).count);
249
+ if (!importErrors && pending === 0 && conversations.length > 0) {
250
+ db.prepare("DELETE FROM sync_errors WHERE binding=?").run(key);
251
+ db.prepare("INSERT OR REPLACE INTO settings VALUES(?,?)").run("lastSync:" + key, new Date().toISOString());
252
+ }
253
+ await api(device, `/api/private/projects/${encodeURIComponent(String(binding.project))}/status`, {
254
+ status: importErrors || pending
255
+ ? "offline"
256
+ : conversations.length
257
+ ? "up_to_date"
258
+ : "waiting",
259
+ pendingCount: Number(db
260
+ .prepare("SELECT COUNT(*) AS count FROM uploads WHERE binding=? AND delivered=0")
261
+ .get(key).count),
262
+ }).catch(() => { });
263
+ return {
264
+ imported,
265
+ delivered,
266
+ importErrors,
267
+ pending: Number(db
268
+ .prepare("SELECT COUNT(*) AS count FROM uploads WHERE binding=? AND delivered=0")
269
+ .get(key).count),
270
+ };
271
+ }
272
+ catch (error) {
273
+ db.prepare("INSERT OR REPLACE INTO sync_errors VALUES(?,?,?)").run(key, String(error), new Date().toISOString());
274
+ const binding = db
275
+ .prepare("SELECT project FROM bindings WHERE key=?")
276
+ .get(key);
277
+ if (binding)
278
+ await api(device, `/api/private/projects/${encodeURIComponent(String(binding.project))}/status`, {
279
+ status: error instanceof CloudError && [401, 403].includes(error.status)
280
+ ? "reconnect"
281
+ : "offline",
282
+ pendingCount: Number(db
283
+ .prepare("SELECT COUNT(*) AS count FROM uploads WHERE binding=? AND delivered=0")
284
+ .get(key).count),
285
+ }).catch(() => { });
286
+ throw error;
287
+ }
288
+ finally {
289
+ db.close();
290
+ }
291
+ }
292
+ export function startAutosync(home, env, workspace) {
293
+ const run = () => {
294
+ void syncWorkspace(home, env, workspace).catch(() => { });
295
+ };
296
+ run();
297
+ const timer = setInterval(run, 30_000);
298
+ timer.unref();
299
+ return () => clearInterval(timer);
300
+ }
@@ -0,0 +1,90 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, basename, join, resolve } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { createHash } from 'node:crypto';
5
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
6
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
7
+ import { antigravityServerName } from '../../adapters/src/server-name.js';
8
+ const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
9
+ const read = (path) => existsSync(path) ? readFileSync(path, 'utf8') : null;
10
+ const dump = (value) => JSON.stringify(value, null, 2) + '\n';
11
+ const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
12
+ export function defaultAntigravityConfig() {
13
+ return resolve(process.env.KNITT_ANTIGRAVITY_CONFIG ?? join(homedir(), '.gemini/config/mcp_config.json'));
14
+ }
15
+ function entries(opts) {
16
+ const extension = existsSync(join(opts.appRoot, 'apps/server/src/main.js')) ? 'js' : 'ts';
17
+ return Object.fromEntries(opts.projects.filter(p => p.clients.includes('antigravity')).map(p => {
18
+ const name = antigravityServerName(p.workspace);
19
+ return [name, { command: opts.node ?? process.execPath, args: [join(opts.appRoot, 'apps/server/src/main.' + extension)], env: {
20
+ MEMORY_CLIENT: 'antigravity', MEMORY_DB: resolve(p.database), MEMORY_REPO: p.repoId, MEMORY_WORKSPACE: p.workspace,
21
+ SHARED_MEMORY_HOME: resolve(opts.installationHome), KNITT_HOME: resolve(opts.installationHome),
22
+ MEMORY_SESSION_SELECTION: '1', MEMORY_MCP_SERVER: name, MEMORY_PICKER_MODE: 'native_question',
23
+ } }];
24
+ }));
25
+ }
26
+ // State is separate per installation, so another installation cannot claim these
27
+ // names or remove our entries. No path from the snapshot is used as a write target.
28
+ export function planAntigravity(opts) {
29
+ const workspace = dirname(resolve(opts.configPath)), configFile = basename(opts.configPath);
30
+ const owner = createHash('sha256').update(resolve(opts.installationHome)).digest('hex').slice(0, 12);
31
+ const stateFile = '.knitt-' + owner + '.json';
32
+ const current = read(join(workspace, configFile)), stateText = read(join(workspace, stateFile));
33
+ const state = stateText ? JSON.parse(stateText) : { schema: 1, servers: {} };
34
+ if (state.schema !== 1 || !object(state.servers) || Object.keys(state.servers).some(k => !/^shared-memory-[a-f0-9]{12}$/.test(k)))
35
+ throw new Error('Invalid Antigravity ownership state');
36
+ const desired = entries(opts);
37
+ // Non-Antigravity installations must not touch the global config directory.
38
+ if (!Object.keys(desired).length && !stateText)
39
+ return { workspace, expected: {}, changes: {} };
40
+ const value = current ? JSON.parse(current) : {};
41
+ if (!object(value) || (value.mcpServers !== undefined && !object(value.mcpServers)))
42
+ throw new Error('Antigravity mcp_config.json must contain an object with an mcpServers object');
43
+ value.mcpServers ??= {};
44
+ for (const [name, old] of Object.entries(state.servers)) {
45
+ if (!(name in desired) && equal(value.mcpServers[name], old))
46
+ delete value.mcpServers[name];
47
+ }
48
+ const nextServers = {};
49
+ for (const [name, entry] of Object.entries(desired)) {
50
+ if (opts.removeOnly) {
51
+ if (state.servers[name])
52
+ nextServers[name] = state.servers[name];
53
+ continue;
54
+ }
55
+ const existing = value.mcpServers[name];
56
+ if (existing !== undefined && (!state.servers[name] || !equal(existing, state.servers[name])))
57
+ throw new Error('Unmanaged or modified Antigravity server conflict: ' + name);
58
+ value.mcpServers[name] = entry;
59
+ nextServers[name] = entry;
60
+ }
61
+ return { workspace, expected: { [configFile]: current, [stateFile]: stateText }, changes: {
62
+ [configFile]: dump(value), [stateFile]: Object.keys(nextServers).length ? dump({ schema: 1, servers: nextServers }) : null,
63
+ } };
64
+ }
65
+ export async function verifyAntigravity(opts) {
66
+ const desired = entries(opts);
67
+ if (!Object.keys(desired).length)
68
+ return;
69
+ const config = JSON.parse(readFileSync(opts.configPath, 'utf8'));
70
+ for (const name of Object.keys(desired)) {
71
+ const entry = config.mcpServers?.[name];
72
+ const client = new Client({ name: 'knitt-setup-check', version: '1' });
73
+ try {
74
+ if (!entry || !equal(entry, desired[name]))
75
+ throw new Error('Missing or modified server registration');
76
+ await client.connect(new StdioClientTransport({ ...entry, env: { ...process.env, ...entry.env }, stderr: 'pipe' }), { timeout: 10_000 });
77
+ const tools = (await client.listTools(undefined, { timeout: 10_000 })).tools;
78
+ for (const tool of ['choose_conversation', 'get_context', 'get_evidence', 'search_memory', 'save_memory']) {
79
+ if (!tools.some(t => t.name === tool))
80
+ throw new Error('Missing tool ' + tool);
81
+ }
82
+ }
83
+ catch (error) {
84
+ throw new Error('Antigravity server connection/tools check failed for ' + name + ': ' + (error instanceof Error ? error.message : String(error)));
85
+ }
86
+ finally {
87
+ await client.close();
88
+ }
89
+ }
90
+ }
@@ -2,16 +2,31 @@
2
2
  import { parseArgs } from 'node:util';
3
3
  import { createInterface } from 'node:readline/promises';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { join, resolve, dirname } from 'node:path';
6
- import { existsSync, readFileSync, accessSync, constants, rmSync } from 'node:fs';
5
+ import { join, resolve, dirname, basename, delimiter } from 'node:path';
6
+ import { homedir } from 'node:os';
7
+ import { existsSync, readFileSync, accessSync, constants } from 'node:fs';
7
8
  import { execFileSync } from 'node:child_process';
8
- import { planConnection, applyConnectionPlan, planUninstall, clients, atomicWrite, readConnectionState } from './connections.js';
9
+ import { planConnection, applyConnectionPlan, planUninstall, clients, atomicWrite, readConnectionState, rollbackConnectionPlan } from './connections.js';
9
10
  import { installRuntime, readInstallation, defaultHome, runtimePaths, withInstallLock, activateRuntime, packageName } from './runtime.js';
11
+ import { planAntigravity, verifyAntigravity, defaultAntigravityConfig } from './antigravity.js';
12
+ import { antigravityServerName } from '../../adapters/src/server-name.js';
10
13
  import { resolveRepository } from '../../adapters/src/repository.js';
11
14
  const appRoot = fileURLToPath(new URL('../../../', import.meta.url));
12
15
  const packageRoot = existsSync(join(appRoot, 'package.json')) ? appRoot : dirname(appRoot);
13
16
  const metadata = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'));
14
17
  const version = metadata.version;
18
+ function detectCodingAgents() {
19
+ const home = homedir();
20
+ const path = (process.env.PATH ?? '').split(delimiter).filter(Boolean);
21
+ const suffixes = process.platform === 'win32' ? ['.exe', '.cmd', '.bat'] : [''];
22
+ const candidates = [
23
+ { client: 'codex', executable: 'codex', directories: [process.env.CODEX_HOME ?? join(home, '.codex')] },
24
+ { client: 'claude-code', executable: 'claude', directories: [process.env.CLAUDE_CONFIG_DIR ?? join(home, '.claude')] },
25
+ { client: 'antigravity', executable: 'antigravity', directories: ['antigravity', 'antigravity-cli', 'antigravity-ide'].map(name => join(home, '.gemini', name)) },
26
+ ];
27
+ return candidates.filter(({ executable, directories }) => directories.some(existsSync) ||
28
+ path.some(directory => suffixes.some(suffix => existsSync(join(directory, executable + suffix))))).map(({ client }) => client);
29
+ }
15
30
  async function confirm(text, yes = false) {
16
31
  if (yes)
17
32
  return true;
@@ -36,58 +51,58 @@ async function ask(prompt) {
36
51
  reader.close();
37
52
  }
38
53
  }
39
- function preview(plan) {
54
+ function preview(plan, contents = true) {
40
55
  for (const [path, content] of Object.entries(plan.changes)) {
41
56
  if (path.includes('npm-connection'))
42
57
  continue;
43
58
  console.log((content === null ? 'remove ' : 'merge ') + join(plan.workspace, path));
44
- if (content !== null && content !== plan.expected[path])
59
+ if (contents && content !== null && content !== plan.expected[path])
45
60
  console.log(content);
46
61
  }
47
62
  }
48
- function applyAll(plans, commit) {
63
+ async function applyAll(plans, commit, verify = async () => { }) {
49
64
  const done = [];
50
65
  try {
51
66
  for (const plan of plans) {
52
67
  applyConnectionPlan(plan);
53
68
  done.push(plan);
54
69
  }
70
+ await verify();
55
71
  commit();
56
72
  }
57
73
  catch (error) {
58
74
  for (const plan of done.reverse())
59
- for (const [path, content] of Object.entries(plan.expected)) {
60
- // Already-written files are restored as one transaction; unrelated concurrent
61
- // edits are protected by each plan's optimistic concurrency check.
62
- const target = join(plan.workspace, path);
63
- const current = existsSync(target) ? readFileSync(target, 'utf8') : null;
64
- if (current !== plan.changes[path])
65
- continue;
66
- if (content !== null)
67
- atomicWrite(join(plan.workspace, path), content);
68
- else
69
- rmSync(join(plan.workspace, path), { force: true });
70
- }
75
+ rollbackConnectionPlan(plan);
71
76
  throw error;
72
77
  }
73
78
  }
74
- function plansFor(runtime, projects) { return projects.map(project => planConnection({ ...project, appRoot: runtime.appRoot, node: runtime.node })); }
79
+ function plansFor(runtime, projects, installationHome) { return projects.map(project => planConnection({ ...project, appRoot: runtime.appRoot, node: runtime.node, installationHome })); }
75
80
  async function main() {
81
+ if (process.argv[2] === 'cloud') {
82
+ const { runCloud } = await import('./cloud-cli.js');
83
+ return runCloud(process.argv.slice(3));
84
+ }
76
85
  const { values, positionals } = parseArgs({ allowPositionals: true, options: {
77
86
  workspace: { type: 'string' }, client: { type: 'string', multiple: true }, home: { type: 'string' },
78
87
  package: { type: 'string' }, yes: { type: 'boolean' }, preview: { type: 'boolean' },
79
- version: { type: 'boolean' }, help: { type: 'boolean' },
88
+ 'antigravity-config': { type: 'string' }, version: { type: 'boolean' }, help: { type: 'boolean' },
80
89
  } });
81
90
  if (values.version) {
82
91
  console.log(version);
83
92
  return;
84
93
  }
85
- const action = positionals[0];
94
+ const plugin = positionals[0] === 'plugin';
95
+ const action = plugin ? 'setup' : positionals[0];
86
96
  if (!action || values.help) {
87
- console.log('Knitt ' + version + '\nCommands: setup, doctor, update, rollback, uninstall, serve\nOptions: --workspace PATH --client codex|claude-code|antigravity|claude-desktop (repeatable)\n --preview --yes --home PATH --package TARBALL_OR_VERSION_SPEC\nSetup configures a persistent local runtime; remote/team service is configured separately.');
97
+ console.log('Knitt ' + version + '\nCommands: plugin, setup, doctor, update, rollback, uninstall, serve, cloud\nRun knitt plugin in a Git project to connect detected coding agents.\nUse knitt cloud --help for pairing and publication.\nOptions: --workspace PATH --client codex|claude-code|antigravity|claude-desktop (repeatable)\n --preview --yes --home PATH --package TARBALL_OR_VERSION_SPEC\n --antigravity-config PATH (optional global MCP config override)\nSetup configures a persistent local runtime; remote/team service is configured separately.');
88
98
  return;
89
99
  }
90
100
  const home = resolve(values.home ?? defaultHome()), paths = runtimePaths(home);
101
+ const initialState = readInstallation(home);
102
+ const configPath = resolve(values['antigravity-config'] ?? initialState?.antigravityConfig ?? defaultAntigravityConfig());
103
+ const globalOptions = (runtime, projects) => ({ configPath, installationHome: home, appRoot: runtime.appRoot, node: runtime.node, projects });
104
+ if (initialState?.antigravityConfig && configPath !== resolve(initialState.antigravityConfig))
105
+ throw new Error('This installation already manages another Antigravity config. Use its existing path: ' + initialState.antigravityConfig);
91
106
  if (action === 'serve') {
92
107
  process.env.MEMORY_DB ??= join(paths.data, 'events.sqlite');
93
108
  await import('../../../apps/server/src/main.js');
@@ -115,6 +130,18 @@ async function main() {
115
130
  catch {
116
131
  problems.push('Data directory is not writable: ' + paths.data);
117
132
  }
133
+ try {
134
+ const globalPlan = planAntigravity(globalOptions(state.current, state.projects));
135
+ const before = globalPlan.expected[basename(configPath)];
136
+ const servers = before ? JSON.parse(before).mcpServers ?? {} : {};
137
+ for (const project of state.projects.filter(p => p.clients.includes('antigravity'))) {
138
+ if (!servers[antigravityServerName(project.workspace)])
139
+ problems.push('Missing Antigravity server: ' + project.workspace);
140
+ }
141
+ }
142
+ catch (error) {
143
+ problems.push(error instanceof Error ? error.message : String(error));
144
+ }
118
145
  for (const project of state.projects) {
119
146
  try {
120
147
  const managed = readConnectionState(project.workspace);
@@ -140,13 +167,27 @@ async function main() {
140
167
  throw new Error('Unknown command: ' + action);
141
168
  let project;
142
169
  if (action === 'setup') {
143
- const directory = values.workspace ?? await ask('Project folder: ');
144
- const selected = values.client ?? (await ask('Agents (comma separated: ' + clients.join(', ') + '): ')).split(',').map(v => v.trim());
170
+ const directory = values.workspace ?? (plugin ? process.cwd() : await ask('Project folder: '));
145
171
  const { workspace, repoId } = resolveRepository(resolve(directory));
172
+ let selected = values.client;
173
+ if (!selected && plugin) {
174
+ selected = detectCodingAgents();
175
+ if (!selected.length)
176
+ throw new Error('No coding agents detected. Run knitt plugin with --client codex, --client claude-code, or --client antigravity to choose one explicitly.');
177
+ if (process.stdin.isTTY && !values.yes && !values.preview) {
178
+ const answer = await ask('Agents to connect [' + selected.join(', ') + '] (Enter to accept, or type a comma-separated list): ');
179
+ if (answer)
180
+ selected = answer.split(',').map(value => value.trim());
181
+ }
182
+ console.log('Connecting ' + selected.join(', ') + ' for ' + workspace);
183
+ }
184
+ selected ??= (await ask('Agents (comma separated: ' + clients.join(', ') + '): ')).split(',').map(v => v.trim());
146
185
  project = { workspace, repoId, clients: selected, database: join(paths.data, 'events.sqlite') };
147
186
  // Validate and show changes before installing dependencies or writing settings.
148
- const plan = planConnection({ ...project, appRoot });
187
+ const plan = planConnection({ ...project, appRoot, installationHome: home });
149
188
  preview(plan);
189
+ const projects = [...(initialState?.projects ?? []).filter(p => p.workspace !== project.workspace), { ...project, clients: [...new Set([...(initialState?.projects.find(p => p.workspace === project.workspace)?.clients ?? []), ...project.clients])] }];
190
+ preview(planAntigravity(globalOptions({ version, appRoot, node: process.execPath }, projects)), false);
150
191
  if (values.preview) {
151
192
  console.log('Preview only. No runtime or configuration installed.');
152
193
  return;
@@ -163,13 +204,14 @@ async function main() {
163
204
  if (!state.projects.some(p => p.workspace === target))
164
205
  throw new Error('Project is not managed by this installation');
165
206
  preview(planUninstall(target));
207
+ preview(planAntigravity({ ...globalOptions(state.current, state.projects.filter(p => p.workspace !== target)), removeOnly: true }), false);
166
208
  }
167
209
  else
168
210
  console.log(action + ' runtime for ' + state.projects.length + ' project(s); user memory is retained.');
169
211
  if (values.preview)
170
212
  return;
171
213
  }
172
- if (!await confirm('Apply ' + action + '?', values.yes)) {
214
+ if (!await confirm('Apply ' + action + '?', values.yes || (plugin && !process.stdin.isTTY))) {
173
215
  console.log('Cancelled. No changes applied.');
174
216
  return;
175
217
  }
@@ -178,7 +220,8 @@ async function main() {
178
220
  if (action === 'uninstall') {
179
221
  const target = resolveRepository(resolve(values.workspace)).workspace;
180
222
  const plan = planUninstall(target);
181
- applyAll([plan], () => atomicWrite(paths.state, JSON.stringify({ ...state, projects: state.projects.filter(p => p.workspace !== target) }, null, 2)));
223
+ const remaining = state.projects.filter(p => p.workspace !== target);
224
+ await applyAll([plan, planAntigravity({ ...globalOptions(state.current, remaining), removeOnly: true })], () => atomicWrite(paths.state, JSON.stringify({ ...state, projects: remaining }, null, 2)));
182
225
  console.log('Project connectors removed where unchanged. User-edited settings and all memory retained. Runtime retained for other projects.');
183
226
  return;
184
227
  }
@@ -190,13 +233,17 @@ async function main() {
190
233
  const projects = project ? [...(state?.projects ?? []).filter(p => p.workspace !== project.workspace), project] : state.projects;
191
234
  if (action !== 'rollback' && metadata.private && !values.package)
192
235
  throw new Error('This package is unpublished. Pass --package /absolute/path/to/the-built.tgz; registry installation is disabled until release.');
193
- const runtime = action === 'rollback' ? state?.previous : installRuntime(home, values.package ?? packageName + '@' + (action === 'update' ? (version.includes('-') ? 'next' : 'latest') : version));
236
+ const runtime = action === 'rollback' ? state?.previous : installRuntime(home, values.package ?? packageName + '@' + (action === 'update' ? (metadata.publishConfig?.tag ?? 'latest') : version));
194
237
  if (!runtime)
195
238
  throw new Error('No previous runtime available');
196
- const plans = plansFor(runtime, projects);
197
- applyAll(plans, () => activateRuntime(home, runtime, projects));
239
+ const plans = plansFor(runtime, projects, home);
240
+ plans.push(planAntigravity(globalOptions(runtime, projects)));
241
+ await applyAll(plans, () => activateRuntime(home, runtime, projects, projects.some(p => p.clients.includes('antigravity')) ? configPath : state?.antigravityConfig), () => verifyAntigravity(globalOptions(runtime, projects)));
198
242
  console.log('Installed runtime ' + runtime.version + '. Data: ' + paths.data);
199
243
  console.log('Restart connected agents and review MCP/hook trust prompts. Use /knit to select your conversation.');
244
+ console.log('For cloud sync, ask your agent to set up Knitt for this project. Account pairing and project-history consent are separate approvals.');
245
+ if (projects.some(p => p.clients.includes('antigravity')))
246
+ console.log('Antigravity: project memory servers registered in ' + configPath + ' and tool connections verified. Restart Antigravity, open the project and use /knit in a new chat.');
200
247
  if (projects.some(p => p.clients.includes('claude-desktop')))
201
248
  console.log('Claude Desktop: merge the generated project .memory/connectors/claude-desktop.json fragment into Desktop MCP settings, then restart.');
202
249
  });