@tinchu0/knitt 0.1.0-beta.4 → 0.1.0-beta.5
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.
- package/README.md +26 -15
- package/dist/apps/server/src/conversation-server.js +203 -0
- package/dist/apps/server/src/http-gateway.js +1 -1
- package/dist/apps/server/src/main.js +6 -2
- package/dist/apps/server/src/server.js +292 -81
- package/dist/memory-schema.json +1 -0
- package/dist/packages/adapters/src/cli.js +193 -45
- package/dist/packages/adapters/src/command.js +149 -18
- package/dist/packages/adapters/src/discovery.js +128 -0
- package/dist/packages/adapters/src/handoff.js +13 -8
- package/dist/packages/adapters/src/histories.js +222 -0
- package/dist/packages/adapters/src/history-time.js +10 -0
- package/dist/packages/adapters/src/hooks.js +123 -44
- package/dist/packages/adapters/src/launch.js +10 -3
- package/dist/packages/adapters/src/picker.js +2 -1
- package/dist/packages/adapters/src/providers/jsonl.js +105 -0
- package/dist/packages/adapters/src/question-ui.js +37 -0
- package/dist/packages/adapters/src/repository.js +32 -5
- package/dist/packages/adapters/src/scope.js +9 -3
- package/dist/packages/adapters/src/server-name.js +6 -0
- package/dist/packages/adapters/src/status.js +81 -0
- package/dist/packages/adapters/src/transcript.js +72 -15
- package/dist/packages/contracts/src/conversations.js +30 -0
- package/dist/packages/installer/src/antigravity.js +90 -0
- package/dist/packages/installer/src/cli.js +210 -48
- package/dist/packages/installer/src/connections.js +193 -38
- package/dist/packages/installer/src/runtime.js +73 -11
- package/dist/packages/memory/src/checkpoints.js +68 -0
- package/dist/packages/memory/src/context.js +91 -0
- package/dist/packages/memory/src/conversations.js +148 -0
- package/dist/packages/memory/src/migrations.js +55 -0
- package/dist/packages/memory/src/store.js +201 -23
- package/dist/skills/continue-chat/SKILL.md +15 -0
- package/dist/skills/knit/SKILL.md +11 -5
- package/docs/clients/connector-setup.md +1 -1
- package/docs/clients/local-agent-memory.md +50 -0
- package/docs/clients/npm-installation.md +23 -11
- package/docs/clients/support-matrix.md +12 -0
- package/docs/usage.md +19 -29
- package/package.json +5 -4
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { basename } from 'node:path';
|
|
2
|
+
export function questionPageSize(client) {
|
|
3
|
+
// Claude supports at most four options; reserve one for navigation. Codex's
|
|
4
|
+
// synchronous question tool supports three. Antigravity supports full lists.
|
|
5
|
+
return client === 'antigravity' ? 50 : client === 'claude' ? 3 : 2;
|
|
6
|
+
}
|
|
7
|
+
const clean = (text) => text.replace(/[\x00-\x1f\x7f]/g, ' ').replace(/\s+/g, ' ').trim();
|
|
8
|
+
export function nativeQuestion(client, workspace, choices, page, pages) {
|
|
9
|
+
const question = 'Which previous conversation would you like to continue in ' + basename(workspace) + '? Project: ' + workspace;
|
|
10
|
+
const choiceMap = {};
|
|
11
|
+
const labels = choices.map((choice, index) => {
|
|
12
|
+
const source = choice.client ? { codex: 'Codex', claude: 'Claude', antigravity: 'Antigravity' }[choice.client] : '';
|
|
13
|
+
const prefix = String(page * questionPageSize(client) + index + 1) + '. [' + source + '] ';
|
|
14
|
+
const title = clean(choice.title) || 'Untitled chat';
|
|
15
|
+
const label = client === 'claude' ? (prefix + title).slice(0, 32) : (prefix + choice.modified + ' · ' + title).slice(0, 180);
|
|
16
|
+
choiceMap[label] = choice.choiceId;
|
|
17
|
+
return { label, description: clean(choice.modified + ' · ' + title).slice(0, 300) };
|
|
18
|
+
});
|
|
19
|
+
const navigation = pages > 1 ? { label: page + 1 < pages ? 'More chats' : 'Newest chats', page: (page + 1) % pages } : undefined;
|
|
20
|
+
const cancelLabel = labels.length === 1 && !navigation ? 'Cancel' : undefined;
|
|
21
|
+
const strings = [...labels.map(choice => choice.label), ...(navigation ? [navigation.label] : []), ...(cancelLabel ? [cancelLabel] : [])];
|
|
22
|
+
let tool;
|
|
23
|
+
let args;
|
|
24
|
+
if (client === 'antigravity') {
|
|
25
|
+
tool = 'ask_question';
|
|
26
|
+
args = { questions: [{ question, options: strings, is_multi_select: false }], toolAction: 'Selecting a previous conversation', toolSummary: 'Choose a project conversation' };
|
|
27
|
+
}
|
|
28
|
+
else if (client === 'claude') {
|
|
29
|
+
tool = 'AskUserQuestion';
|
|
30
|
+
args = { questions: [{ question, header: 'Pick chat', multiSelect: false, options: [...labels, ...(navigation ? [{ label: navigation.label, description: 'Show another page of this project’s chats' }] : []), ...(cancelLabel ? [{ label: cancelLabel, description: 'Stop without selecting a conversation' }] : [])] }] };
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
tool = 'request_user_input_async';
|
|
34
|
+
args = { questions: [{ title: question, options: strings }] };
|
|
35
|
+
}
|
|
36
|
+
return { tool, arguments: args, choiceMap, ...(navigation ? { navigation } : {}), ...(cancelLabel ? { cancelLabel } : {}) };
|
|
37
|
+
}
|
|
@@ -1,20 +1,47 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
1
3
|
import { execFileSync } from "node:child_process";
|
|
2
4
|
import { createHash } from "node:crypto";
|
|
3
5
|
export function resolveRepository(directory) {
|
|
4
6
|
const workspace = execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
5
|
-
cwd: directory,
|
|
7
|
+
cwd: directory,
|
|
8
|
+
encoding: "utf8",
|
|
9
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
6
10
|
}).trim();
|
|
7
11
|
let repoId;
|
|
8
12
|
try {
|
|
9
13
|
const remote = execFileSync("git", ["remote", "get-url", "origin"], {
|
|
10
|
-
cwd: workspace,
|
|
14
|
+
cwd: workspace,
|
|
15
|
+
encoding: "utf8",
|
|
16
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
11
17
|
}).trim();
|
|
12
18
|
const ssh = remote.match(/^[^@]+@([^:]+):(.+)$/);
|
|
13
|
-
const url = ssh
|
|
14
|
-
|
|
19
|
+
const url = ssh
|
|
20
|
+
? new URL("https://" + ssh[1] + "/" + ssh[2])
|
|
21
|
+
: new URL(remote);
|
|
22
|
+
repoId = (url.hostname + url.pathname)
|
|
23
|
+
.replace(/\.git$/, "")
|
|
24
|
+
.replace(/\/$/, "");
|
|
15
25
|
}
|
|
16
26
|
catch {
|
|
17
|
-
repoId =
|
|
27
|
+
repoId =
|
|
28
|
+
"local:" +
|
|
29
|
+
createHash("sha256")
|
|
30
|
+
.update(execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
|
|
31
|
+
cwd: workspace,
|
|
32
|
+
encoding: "utf8",
|
|
33
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
34
|
+
}).trim())
|
|
35
|
+
.digest("hex");
|
|
18
36
|
}
|
|
19
37
|
return { workspace, repoId };
|
|
20
38
|
}
|
|
39
|
+
/** Compare the physical folder across symlinks and native path spellings. */
|
|
40
|
+
export function canonicalWorkspace(directory) {
|
|
41
|
+
try {
|
|
42
|
+
return realpathSync.native(directory);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return resolve(directory);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
1
2
|
import { execFileSync } from "node:child_process";
|
|
2
3
|
export function resolveConnection(payload, env = process.env) {
|
|
3
4
|
const repoId = env.MEMORY_REPO;
|
|
@@ -7,12 +8,17 @@ export function resolveConnection(payload, env = process.env) {
|
|
|
7
8
|
const workspace = typeof payload.cwd === "string" ? payload.cwd :
|
|
8
9
|
Array.isArray(workspacePaths) && workspacePaths.length === 1 && typeof workspacePaths[0] === "string"
|
|
9
10
|
? workspacePaths[0] : process.cwd();
|
|
10
|
-
if (env.MEMORY_WORKSPACE) {
|
|
11
|
+
if (env.MEMORY_WORKSPACE && realpathSync.native(workspace) !== realpathSync.native(env.MEMORY_WORKSPACE)) {
|
|
11
12
|
const commonGitDir = (cwd) => execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
|
|
12
13
|
cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"],
|
|
13
14
|
}).trim();
|
|
14
|
-
|
|
15
|
-
|
|
15
|
+
let matches = false;
|
|
16
|
+
try {
|
|
17
|
+
matches = commonGitDir(workspace) === commonGitDir(env.MEMORY_WORKSPACE);
|
|
18
|
+
}
|
|
19
|
+
catch { /* Non-Git folders can only match by their canonical path. */ }
|
|
20
|
+
if (!matches) {
|
|
21
|
+
throw new Error("Wrong workspace. This memory connection belongs to " + env.MEMORY_WORKSPACE + ". Use the connection for the current project " + workspace + ". No memory was recalled or captured.");
|
|
16
22
|
}
|
|
17
23
|
}
|
|
18
24
|
return { repoId, workspace };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { canonicalWorkspace } from './repository.js';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
// Antigravity's MCP registry is global; each project needs an independent name.
|
|
4
|
+
export function antigravityServerName(workspace) {
|
|
5
|
+
return 'shared-memory-' + createHash('sha256').update(canonicalWorkspace(workspace)).digest('hex').slice(0, 12);
|
|
6
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { sessionKeySchema } from "../../contracts/src/conversations.js";
|
|
6
|
+
import { openQueue } from "./hooks.js";
|
|
7
|
+
export const captureStatusSchema = z.object({
|
|
8
|
+
session: sessionKeySchema,
|
|
9
|
+
lastAttemptAt: z.string().nullable().default(null),
|
|
10
|
+
captureState: z
|
|
11
|
+
.enum([
|
|
12
|
+
"unobserved",
|
|
13
|
+
"captured",
|
|
14
|
+
"partial",
|
|
15
|
+
"no_supported_text",
|
|
16
|
+
"no_new_text",
|
|
17
|
+
"error",
|
|
18
|
+
])
|
|
19
|
+
.default("unobserved"),
|
|
20
|
+
lastCaptureAt: z.string().nullable(),
|
|
21
|
+
lastDeliveryAt: z.string().nullable(),
|
|
22
|
+
pending: z.number().int().nonnegative(),
|
|
23
|
+
lastErrorCode: z.enum(["CAPTURE_FAILED", "DELIVERY_PENDING"]).nullable(),
|
|
24
|
+
});
|
|
25
|
+
export function recordCaptureStatus(directory, input) {
|
|
26
|
+
const status = captureStatusSchema.parse(input), queue = openQueue(directory), id = JSON.stringify(status.session);
|
|
27
|
+
try {
|
|
28
|
+
queue.exec("CREATE TABLE IF NOT EXISTS capture_status(id TEXT PRIMARY KEY,payload TEXT NOT NULL)");
|
|
29
|
+
const row = queue
|
|
30
|
+
.prepare("SELECT payload FROM capture_status WHERE id=?")
|
|
31
|
+
.get(id);
|
|
32
|
+
const old = row
|
|
33
|
+
? captureStatusSchema.parse(JSON.parse(String(row.payload)))
|
|
34
|
+
: null;
|
|
35
|
+
const value = {
|
|
36
|
+
...status,
|
|
37
|
+
lastAttemptAt: status.lastAttemptAt ?? old?.lastAttemptAt ?? null,
|
|
38
|
+
lastCaptureAt: status.lastCaptureAt ?? old?.lastCaptureAt ?? null,
|
|
39
|
+
lastDeliveryAt: status.lastDeliveryAt ?? old?.lastDeliveryAt ?? null,
|
|
40
|
+
};
|
|
41
|
+
queue
|
|
42
|
+
.prepare("INSERT INTO capture_status VALUES(?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload")
|
|
43
|
+
.run(id, JSON.stringify(value));
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
queue.close();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function readCaptureStatuses(directory) {
|
|
50
|
+
const path = join(directory, "queue.sqlite");
|
|
51
|
+
if (!existsSync(path))
|
|
52
|
+
return [];
|
|
53
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
54
|
+
try {
|
|
55
|
+
if (!db
|
|
56
|
+
.prepare("SELECT name FROM sqlite_master WHERE name='capture_status'")
|
|
57
|
+
.get())
|
|
58
|
+
return [];
|
|
59
|
+
return db
|
|
60
|
+
.prepare("SELECT payload FROM capture_status ORDER BY id")
|
|
61
|
+
.all()
|
|
62
|
+
.map((row) => captureStatusSchema.parse(JSON.parse(String(row.payload))));
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
db.close();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function pendingForSession(directory, session) {
|
|
69
|
+
const path = join(directory, "queue.sqlite");
|
|
70
|
+
if (!existsSync(path))
|
|
71
|
+
return 0;
|
|
72
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
73
|
+
try {
|
|
74
|
+
return Number(db
|
|
75
|
+
.prepare("SELECT COUNT(*) AS n FROM pending WHERE json_extract(payload,'$.repoId')=? AND json_extract(payload,'$.sessionId')=? AND json_extract(payload,'$.source') LIKE ?")
|
|
76
|
+
.get(session.repoId, session.nativeSessionId, session.client + ":%").n);
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
db.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { sessionKeySchema } from "../../contracts/src/conversations.js";
|
|
1
2
|
import { openSync, closeSync, fstatSync, readSync } from "node:fs";
|
|
2
3
|
import { resolve } from "node:path";
|
|
3
4
|
import { createHash } from "node:crypto";
|
|
@@ -11,30 +12,48 @@ function textBlocks(value) {
|
|
|
11
12
|
return value;
|
|
12
13
|
if (!Array.isArray(value))
|
|
13
14
|
return "";
|
|
14
|
-
return value
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
return value
|
|
16
|
+
.flatMap((block) => {
|
|
17
|
+
if (block &&
|
|
18
|
+
typeof block === "object" &&
|
|
19
|
+
typeof block.text === "string" &&
|
|
20
|
+
(!block.type ||
|
|
21
|
+
["text", "input_text", "output_text"].includes(block.type)))
|
|
17
22
|
return [block.text];
|
|
18
23
|
return [];
|
|
19
|
-
})
|
|
24
|
+
})
|
|
25
|
+
.join("\n");
|
|
20
26
|
}
|
|
21
27
|
function messageText(row) {
|
|
28
|
+
if (row.isSidechain === true)
|
|
29
|
+
return null;
|
|
22
30
|
if (row.type === "USER_INPUT" && typeof row.content === "string") {
|
|
23
31
|
const request = row.content.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/);
|
|
24
32
|
return "user: " + (request ? request[1].trim() : row.content);
|
|
25
33
|
}
|
|
26
|
-
if (["PLANNER_RESPONSE", "ASSISTANT_MESSAGE"].includes(row.type) &&
|
|
34
|
+
if (["PLANNER_RESPONSE", "ASSISTANT_MESSAGE"].includes(row.type) &&
|
|
35
|
+
typeof row.content === "string") {
|
|
27
36
|
return "assistant: " + row.content;
|
|
28
37
|
}
|
|
29
38
|
const message = row.type === "response_item" ? row.payload : (row.message ?? row);
|
|
30
39
|
if (!message || typeof message !== "object")
|
|
31
40
|
return null;
|
|
32
|
-
const role = message.role ??
|
|
41
|
+
const role = message.role ??
|
|
42
|
+
(["user", "assistant"].includes(row.type) ? row.type : undefined);
|
|
33
43
|
if (!["user", "assistant", "model"].includes(role))
|
|
34
44
|
return null;
|
|
35
45
|
const text = textBlocks(message.content ?? message.parts);
|
|
36
46
|
const blocks = message.content ?? message.parts;
|
|
37
|
-
const onlyNonText = Array.isArray(blocks) &&
|
|
47
|
+
const onlyNonText = Array.isArray(blocks) &&
|
|
48
|
+
blocks.every((block) => block &&
|
|
49
|
+
typeof block === "object" &&
|
|
50
|
+
[
|
|
51
|
+
"tool_use",
|
|
52
|
+
"tool_result",
|
|
53
|
+
"thinking",
|
|
54
|
+
"redacted_thinking",
|
|
55
|
+
"image",
|
|
56
|
+
].includes(block.type));
|
|
38
57
|
if (!text && !onlyNonText)
|
|
39
58
|
throw new Error("Unsupported transcript message shape for role " + role);
|
|
40
59
|
return text ? role + ": " + text : null;
|
|
@@ -70,8 +89,20 @@ export function captureTranscript(options) {
|
|
|
70
89
|
queue.exec("CREATE TABLE IF NOT EXISTS cursors(id TEXT PRIMARY KEY, offset INTEGER NOT NULL, prefix TEXT NOT NULL)");
|
|
71
90
|
queue.exec("BEGIN IMMEDIATE");
|
|
72
91
|
transaction = true;
|
|
73
|
-
|
|
74
|
-
|
|
92
|
+
if (options.session) {
|
|
93
|
+
sessionKeySchema.parse(options.session);
|
|
94
|
+
if (options.session.repoId !== scope.repoId ||
|
|
95
|
+
options.session.client !== client ||
|
|
96
|
+
options.session.nativeSessionId !== sessionId)
|
|
97
|
+
throw new Error("Queued session identity mismatch");
|
|
98
|
+
}
|
|
99
|
+
const identityScope = options.session
|
|
100
|
+
? { repoId: scope.repoId, featureId: scope.featureId }
|
|
101
|
+
: scope;
|
|
102
|
+
const key = hash(JSON.stringify({ client, scope: identityScope, sessionId, path }));
|
|
103
|
+
const previous = queue
|
|
104
|
+
.prepare("SELECT offset,prefix FROM cursors WHERE id=?")
|
|
105
|
+
.get(key);
|
|
75
106
|
const size = fstatSync(fd).size;
|
|
76
107
|
let offset = previous ? Number(previous.offset) : 0;
|
|
77
108
|
const prefix = (length) => {
|
|
@@ -108,11 +139,31 @@ export function captureTranscript(options) {
|
|
|
108
139
|
const contentParts = splitText(redact(text));
|
|
109
140
|
for (const [index, content] of contentParts.entries()) {
|
|
110
141
|
const event = eventSchema.parse({
|
|
111
|
-
...scope,
|
|
112
|
-
|
|
113
|
-
|
|
142
|
+
...scope,
|
|
143
|
+
sessionId,
|
|
144
|
+
kind: "progress",
|
|
145
|
+
content,
|
|
146
|
+
eventId: hash(JSON.stringify({
|
|
147
|
+
client,
|
|
148
|
+
scope: identityScope,
|
|
149
|
+
sessionId,
|
|
150
|
+
byte: offset + start,
|
|
151
|
+
index,
|
|
152
|
+
content,
|
|
153
|
+
})),
|
|
154
|
+
source: client +
|
|
155
|
+
":transcript:line-byte=" +
|
|
156
|
+
(offset + start) +
|
|
157
|
+
":part=" +
|
|
158
|
+
index,
|
|
114
159
|
});
|
|
115
|
-
queue
|
|
160
|
+
queue
|
|
161
|
+
.prepare("INSERT OR IGNORE INTO pending VALUES(?,?)")
|
|
162
|
+
.run(event.eventId, JSON.stringify(event));
|
|
163
|
+
if (options.session)
|
|
164
|
+
queue
|
|
165
|
+
.prepare("INSERT OR IGNORE INTO pending_sessions VALUES(?,?)")
|
|
166
|
+
.run(event.eventId, JSON.stringify(options.session));
|
|
116
167
|
events++;
|
|
117
168
|
}
|
|
118
169
|
}
|
|
@@ -123,11 +174,17 @@ export function captureTranscript(options) {
|
|
|
123
174
|
if (read - start > maxLineBytes && records < 500)
|
|
124
175
|
throw new Error("Transcript line exceeds 1 MiB");
|
|
125
176
|
const nextOffset = offset + start;
|
|
126
|
-
queue
|
|
177
|
+
queue
|
|
178
|
+
.prepare("INSERT INTO cursors VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET offset=excluded.offset,prefix=excluded.prefix")
|
|
127
179
|
.run(key, nextOffset, prefix(nextOffset));
|
|
128
180
|
queue.exec("COMMIT");
|
|
129
181
|
transaction = false;
|
|
130
|
-
return {
|
|
182
|
+
return {
|
|
183
|
+
events,
|
|
184
|
+
records,
|
|
185
|
+
offset: nextOffset,
|
|
186
|
+
remainingBytes: size - nextOffset,
|
|
187
|
+
};
|
|
131
188
|
}
|
|
132
189
|
finally {
|
|
133
190
|
if (transaction)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const id = z.string().trim().min(1).max(256);
|
|
3
|
+
export const sessionKeySchema = z
|
|
4
|
+
.object({ repoId: id, client: id, nativeSessionId: id })
|
|
5
|
+
.strict();
|
|
6
|
+
export const locationSchema = z
|
|
7
|
+
.object({
|
|
8
|
+
workspace: z.string().min(1).max(4096),
|
|
9
|
+
branch: id.optional(),
|
|
10
|
+
commit: id.optional(),
|
|
11
|
+
})
|
|
12
|
+
.strict();
|
|
13
|
+
export const checkpointEntrySchema = z
|
|
14
|
+
.object({
|
|
15
|
+
id,
|
|
16
|
+
category: z.enum([
|
|
17
|
+
"goal",
|
|
18
|
+
"decision",
|
|
19
|
+
"attempt",
|
|
20
|
+
"progress",
|
|
21
|
+
"test_result",
|
|
22
|
+
"blocker",
|
|
23
|
+
"next_step",
|
|
24
|
+
]),
|
|
25
|
+
content: z.string().trim().min(1).max(32768),
|
|
26
|
+
evidenceIds: z.array(id).min(1).max(100),
|
|
27
|
+
status: z.enum(["reported", "verified"]),
|
|
28
|
+
supersedes: id.optional(),
|
|
29
|
+
})
|
|
30
|
+
.strict();
|
|
@@ -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
|
+
MEMORY_SESSION_SELECTION: '1', MEMORY_MCP_SERVER: name,
|
|
22
|
+
...(p.captureNewSessions ? { MEMORY_CONVERSATION_MODE: '1', MEMORY_CAPTURE_NEW_SESSIONS: '1' } : { 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', entry.env.MEMORY_CONVERSATION_MODE === '1' ? 'save_checkpoint' : '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
|
+
}
|