@tinchu0/knitt 0.0.0-stage → 0.1.0-beta.2
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/LICENSE +202 -0
- package/README.md +64 -2
- package/dist/apps/server/src/conversation-server.js +203 -0
- package/dist/apps/server/src/http-gateway.js +118 -0
- package/dist/apps/server/src/http-main.js +46 -0
- package/dist/apps/server/src/main.js +15 -0
- package/dist/apps/server/src/server.js +253 -0
- package/dist/apps/server/src/web-auth.js +30 -0
- package/dist/apps/server/src/web-picker.js +119 -0
- package/dist/memory-schema.json +1 -0
- package/dist/packages/adapters/src/cli.js +259 -0
- package/dist/packages/adapters/src/command.js +227 -0
- package/dist/packages/adapters/src/discovery.js +128 -0
- package/dist/packages/adapters/src/handoff.js +146 -0
- package/dist/packages/adapters/src/hooks.js +159 -0
- package/dist/packages/adapters/src/launch.js +21 -0
- package/dist/packages/adapters/src/picker.js +40 -0
- package/dist/packages/adapters/src/providers/jsonl.js +105 -0
- package/dist/packages/adapters/src/repository.js +36 -0
- package/dist/packages/adapters/src/scope.js +32 -0
- package/dist/packages/adapters/src/status.js +81 -0
- package/dist/packages/adapters/src/transcript.js +193 -0
- package/dist/packages/contracts/src/capabilities.js +1 -0
- package/dist/packages/contracts/src/conversations.js +30 -0
- package/dist/packages/contracts/src/events.js +27 -0
- package/dist/packages/installer/src/cli.js +325 -0
- package/dist/packages/installer/src/connections.js +352 -0
- package/dist/packages/installer/src/runtime.js +133 -0
- 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 +269 -0
- package/dist/scripts/connector-setup.js +77 -0
- package/dist/skills/continue-chat/SKILL.md +13 -0
- package/docs/clients/connector-setup.md +63 -0
- package/docs/clients/local-agent-memory.md +50 -0
- package/docs/clients/npm-installation.md +67 -0
- package/package.json +50 -4
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readCaptureStatuses } from "../../adapters/src/status.js";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { join, resolve, dirname } from "node:path";
|
|
7
|
+
import { existsSync, readFileSync, accessSync, constants, rmSync, } from "node:fs";
|
|
8
|
+
import { execFileSync } from "node:child_process";
|
|
9
|
+
import { planConnection, applyConnectionPlan, planUninstall, clients, atomicWrite, readConnectionState, } from "./connections.js";
|
|
10
|
+
import { installRuntime, readInstallation, defaultHome, runtimePaths, withInstallLock, activateRuntime, assertRuntimeCompatibility, packageName, } from "./runtime.js";
|
|
11
|
+
import { resolveRepository } from "../../adapters/src/repository.js";
|
|
12
|
+
const appRoot = fileURLToPath(new URL("../../../", import.meta.url));
|
|
13
|
+
const packageRoot = existsSync(join(appRoot, "package.json"))
|
|
14
|
+
? appRoot
|
|
15
|
+
: dirname(appRoot);
|
|
16
|
+
const metadata = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
|
|
17
|
+
const version = metadata.version;
|
|
18
|
+
async function confirm(text, yes = false) {
|
|
19
|
+
if (yes)
|
|
20
|
+
return true;
|
|
21
|
+
if (!process.stdin.isTTY)
|
|
22
|
+
throw new Error("Use --yes for noninteractive apply, or --preview to inspect without changes");
|
|
23
|
+
const reader = createInterface({
|
|
24
|
+
input: process.stdin,
|
|
25
|
+
output: process.stdout,
|
|
26
|
+
});
|
|
27
|
+
try {
|
|
28
|
+
return /^y(es)?$/i.test((await reader.question(text + " [y/N] ")).trim());
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
reader.close();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function ask(prompt) {
|
|
35
|
+
if (!process.stdin.isTTY)
|
|
36
|
+
throw new Error("Pass --workspace and --client for noninteractive setup");
|
|
37
|
+
const reader = createInterface({
|
|
38
|
+
input: process.stdin,
|
|
39
|
+
output: process.stdout,
|
|
40
|
+
});
|
|
41
|
+
try {
|
|
42
|
+
return (await reader.question(prompt)).trim();
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
reader.close();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function preview(plan) {
|
|
49
|
+
for (const [path, content] of Object.entries(plan.changes)) {
|
|
50
|
+
if (path.includes("npm-connection"))
|
|
51
|
+
continue;
|
|
52
|
+
console.log((content === null ? "remove " : "merge ") + join(plan.workspace, path));
|
|
53
|
+
if (content !== null && content !== plan.expected[path])
|
|
54
|
+
console.log(content);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function applyAll(plans, commit) {
|
|
58
|
+
const done = [];
|
|
59
|
+
try {
|
|
60
|
+
for (const plan of plans) {
|
|
61
|
+
applyConnectionPlan(plan);
|
|
62
|
+
done.push(plan);
|
|
63
|
+
}
|
|
64
|
+
commit();
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
for (const plan of done.reverse())
|
|
68
|
+
for (const [path, content] of Object.entries(plan.expected)) {
|
|
69
|
+
// Already-written files are restored as one transaction; unrelated concurrent
|
|
70
|
+
// edits are protected by each plan's optimistic concurrency check.
|
|
71
|
+
const target = join(plan.workspace, path);
|
|
72
|
+
const current = existsSync(target)
|
|
73
|
+
? readFileSync(target, "utf8")
|
|
74
|
+
: null;
|
|
75
|
+
if (current !== plan.changes[path])
|
|
76
|
+
continue;
|
|
77
|
+
if (content !== null)
|
|
78
|
+
atomicWrite(join(plan.workspace, path), content);
|
|
79
|
+
else
|
|
80
|
+
rmSync(join(plan.workspace, path), { force: true });
|
|
81
|
+
}
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function plansFor(runtime, projects) {
|
|
86
|
+
return projects.map((project) => planConnection({
|
|
87
|
+
...project,
|
|
88
|
+
appRoot: runtime.appRoot,
|
|
89
|
+
node: runtime.node,
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
async function main() {
|
|
93
|
+
const { values, positionals } = parseArgs({
|
|
94
|
+
allowPositionals: true,
|
|
95
|
+
options: {
|
|
96
|
+
session: { type: "string" },
|
|
97
|
+
workspace: { type: "string" },
|
|
98
|
+
client: { type: "string", multiple: true },
|
|
99
|
+
home: { type: "string" },
|
|
100
|
+
package: { type: "string" },
|
|
101
|
+
yes: { type: "boolean" },
|
|
102
|
+
preview: { type: "boolean" },
|
|
103
|
+
"capture-new-sessions": { type: "boolean" },
|
|
104
|
+
version: { type: "boolean" },
|
|
105
|
+
help: { type: "boolean" },
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
if (values.version) {
|
|
109
|
+
console.log(version);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const action = positionals[0];
|
|
113
|
+
if (!action || values.help) {
|
|
114
|
+
console.log("Knitt " +
|
|
115
|
+
version +
|
|
116
|
+
"\nCommands: setup, doctor, update, rollback, uninstall, serve, continue\nOptions: --workspace PATH --client codex|claude-code|antigravity|claude-desktop (repeatable)\n --capture-new-sessions --preview --yes --home PATH --package TARBALL_OR_VERSION_SPEC\nSetup configures a persistent local runtime; remote/team service is configured separately.");
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const home = resolve(values.home ?? defaultHome()), paths = runtimePaths(home);
|
|
120
|
+
if (action === "continue") {
|
|
121
|
+
if (!values.workspace)
|
|
122
|
+
throw new Error("Pass --workspace for the connected project");
|
|
123
|
+
const common = (cwd) => execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
124
|
+
const expected = common(resolve(values.workspace));
|
|
125
|
+
const state = readInstallation(home);
|
|
126
|
+
const project = state?.projects.find((p) => {
|
|
127
|
+
try {
|
|
128
|
+
return common(p.workspace) === expected;
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
if (!project?.captureNewSessions)
|
|
135
|
+
throw new Error("This project has not opted into local conversation mode; run setup --capture-new-sessions first");
|
|
136
|
+
process.env.MEMORY_DB = project.database;
|
|
137
|
+
process.env.MEMORY_REPO = project.repoId;
|
|
138
|
+
process.env.MEMORY_CONVERSATION_MODE = "1";
|
|
139
|
+
await import("../../adapters/src/command.js");
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (action === "serve") {
|
|
143
|
+
process.env.MEMORY_DB ??= join(paths.data, "events.sqlite");
|
|
144
|
+
await import("../../../apps/server/src/main.js");
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (action === "doctor") {
|
|
148
|
+
const state = readInstallation(home), problems = [];
|
|
149
|
+
if (Number(process.versions.node.split(".")[0]) < 24)
|
|
150
|
+
problems.push("Install Node.js 24+");
|
|
151
|
+
try {
|
|
152
|
+
execFileSync("git", ["--version"], { stdio: "ignore" });
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
problems.push("Install Git and add it to PATH");
|
|
156
|
+
}
|
|
157
|
+
if (!state)
|
|
158
|
+
problems.push("No persistent runtime installed. Run setup.");
|
|
159
|
+
else {
|
|
160
|
+
for (const file of [
|
|
161
|
+
state.current.node,
|
|
162
|
+
join(state.current.appRoot, "apps/server/src/main.js"),
|
|
163
|
+
])
|
|
164
|
+
if (!existsSync(file))
|
|
165
|
+
problems.push("Missing runtime path: " + file + ". Run setup again.");
|
|
166
|
+
try {
|
|
167
|
+
accessSync(paths.data, constants.W_OK);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
problems.push("Data directory is not writable: " + paths.data);
|
|
171
|
+
}
|
|
172
|
+
for (const project of state.projects) {
|
|
173
|
+
try {
|
|
174
|
+
const managed = readConnectionState(project.workspace);
|
|
175
|
+
if (!Object.keys(managed.files).length)
|
|
176
|
+
problems.push("Missing connector state: " + project.workspace);
|
|
177
|
+
for (const [path, snapshot] of Object.entries(managed.files)) {
|
|
178
|
+
const current = readFileSync(join(project.workspace, path), "utf8");
|
|
179
|
+
if (current !== snapshot.after)
|
|
180
|
+
problems.push("Configuration changed; review before setup: " +
|
|
181
|
+
join(project.workspace, path));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
problems.push("Missing or invalid project configuration: " + project.workspace);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const capture = (state?.projects ?? [])
|
|
190
|
+
.filter((p) => p.captureNewSessions)
|
|
191
|
+
.map((project) => {
|
|
192
|
+
const observations = project.clients
|
|
193
|
+
.flatMap((client) => readCaptureStatuses(join(dirname(project.database), "queue", client === "claude-code" ? "claude" : client)))
|
|
194
|
+
.filter((s) => s.session.repoId === project.repoId);
|
|
195
|
+
return {
|
|
196
|
+
workspace: project.workspace,
|
|
197
|
+
captureObserved: observations.some((s) => s.lastCaptureAt !== null),
|
|
198
|
+
startupObserved: observations.length > 0,
|
|
199
|
+
sessions: observations,
|
|
200
|
+
};
|
|
201
|
+
});
|
|
202
|
+
console.log(JSON.stringify({
|
|
203
|
+
capture,
|
|
204
|
+
status: problems.length ? "attention_required" : "configured",
|
|
205
|
+
runtime: state?.current.version,
|
|
206
|
+
problems,
|
|
207
|
+
note: "Configuration check only; agent login/trust and live handoff are not verified.",
|
|
208
|
+
}, null, 2));
|
|
209
|
+
if (problems.length)
|
|
210
|
+
process.exitCode = 1;
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (!["setup", "update", "rollback", "uninstall"].includes(action))
|
|
214
|
+
throw new Error("Unknown command: " + action);
|
|
215
|
+
let project;
|
|
216
|
+
if (action === "setup") {
|
|
217
|
+
const directory = values.workspace ?? (await ask("Project folder: "));
|
|
218
|
+
const selected = values.client ??
|
|
219
|
+
(await ask("Agents (comma separated: " + clients.join(", ") + "): "))
|
|
220
|
+
.split(",")
|
|
221
|
+
.map((v) => v.trim());
|
|
222
|
+
const { workspace, repoId } = resolveRepository(resolve(directory));
|
|
223
|
+
project = {
|
|
224
|
+
workspace,
|
|
225
|
+
repoId,
|
|
226
|
+
clients: selected,
|
|
227
|
+
database: join(paths.data, "events.sqlite"),
|
|
228
|
+
...(values["capture-new-sessions"] ? { captureNewSessions: true } : {}),
|
|
229
|
+
};
|
|
230
|
+
// Validate and show changes before installing dependencies or writing settings.
|
|
231
|
+
const previousProject = readInstallation(home)?.projects.find((p) => p.workspace === workspace);
|
|
232
|
+
if (previousProject)
|
|
233
|
+
project.repoId = previousProject.repoId;
|
|
234
|
+
const plan = planConnection({ ...project, appRoot });
|
|
235
|
+
preview(plan);
|
|
236
|
+
if (values.preview) {
|
|
237
|
+
console.log("Preview only. No runtime or configuration installed.");
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
const state = readInstallation(home);
|
|
243
|
+
if (!state)
|
|
244
|
+
throw new Error("No installation found. Run setup first.");
|
|
245
|
+
if (action === "uninstall") {
|
|
246
|
+
const target = values.workspace
|
|
247
|
+
? resolveRepository(resolve(values.workspace)).workspace
|
|
248
|
+
: null;
|
|
249
|
+
if (!target)
|
|
250
|
+
throw new Error("Pass --workspace to uninstall one project; memory data is always retained");
|
|
251
|
+
if (!state.projects.some((p) => p.workspace === target))
|
|
252
|
+
throw new Error("Project is not managed by this installation");
|
|
253
|
+
preview(planUninstall(target));
|
|
254
|
+
}
|
|
255
|
+
else
|
|
256
|
+
console.log(action +
|
|
257
|
+
" runtime for " +
|
|
258
|
+
state.projects.length +
|
|
259
|
+
" project(s); user memory is retained.");
|
|
260
|
+
if (values.preview)
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (!(await confirm("Apply " + action + "?", values.yes))) {
|
|
264
|
+
console.log("Cancelled. No changes applied.");
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
await withInstallLock(home, async () => {
|
|
268
|
+
const state = readInstallation(home);
|
|
269
|
+
if (action === "uninstall") {
|
|
270
|
+
const target = resolveRepository(resolve(values.workspace)).workspace;
|
|
271
|
+
const plan = planUninstall(target);
|
|
272
|
+
applyAll([plan], () => atomicWrite(paths.state, JSON.stringify({
|
|
273
|
+
...state,
|
|
274
|
+
projects: state.projects.filter((p) => p.workspace !== target),
|
|
275
|
+
}, null, 2)));
|
|
276
|
+
console.log("Project connectors removed where unchanged. User-edited settings and all memory retained. Runtime retained for other projects.");
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (project) {
|
|
280
|
+
const existing = state?.projects.find((p) => p.workspace === project.workspace);
|
|
281
|
+
if (existing) {
|
|
282
|
+
project.repoId = existing.repoId;
|
|
283
|
+
project.clients = [
|
|
284
|
+
...new Set([...existing.clients, ...project.clients]),
|
|
285
|
+
];
|
|
286
|
+
if (existing.captureNewSessions)
|
|
287
|
+
project.captureNewSessions = true;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const projects = project
|
|
291
|
+
? [
|
|
292
|
+
...(state?.projects ?? []).filter((p) => p.workspace !== project.workspace),
|
|
293
|
+
project,
|
|
294
|
+
]
|
|
295
|
+
: state.projects;
|
|
296
|
+
if (action !== "rollback" && metadata.private && !values.package)
|
|
297
|
+
throw new Error("This package is unpublished. Pass --package /absolute/path/to/the-built.tgz; registry installation is disabled until release.");
|
|
298
|
+
const runtime = action === "rollback"
|
|
299
|
+
? state?.previous
|
|
300
|
+
: installRuntime(home, values.package ??
|
|
301
|
+
packageName +
|
|
302
|
+
"@" +
|
|
303
|
+
(action === "update"
|
|
304
|
+
? version.includes("-")
|
|
305
|
+
? "next"
|
|
306
|
+
: "latest"
|
|
307
|
+
: version));
|
|
308
|
+
if (!runtime)
|
|
309
|
+
throw new Error("No previous runtime available");
|
|
310
|
+
assertRuntimeCompatibility(runtime, projects);
|
|
311
|
+
const plans = plansFor(runtime, projects);
|
|
312
|
+
applyAll(plans, () => activateRuntime(home, runtime, projects));
|
|
313
|
+
console.log("Installed runtime " + runtime.version + ". Data: " + paths.data);
|
|
314
|
+
console.log("Restart connected agents and review MCP/hook trust prompts. Use /continue-chat to select your conversation.");
|
|
315
|
+
if (projects.some((p) => p.clients.includes("claude-desktop")))
|
|
316
|
+
console.log("Claude Desktop: merge the generated project .memory/connectors/claude-desktop.json fragment into Desktop MCP settings, then restart.");
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
try {
|
|
320
|
+
await main();
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
324
|
+
process.exitCode = 1;
|
|
325
|
+
}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync, realpathSync, } from "node:fs";
|
|
2
|
+
import { join, dirname, resolve } from "node:path";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { parse as parseToml } from "smol-toml";
|
|
6
|
+
export const clients = [
|
|
7
|
+
"codex",
|
|
8
|
+
"claude-code",
|
|
9
|
+
"antigravity",
|
|
10
|
+
"claude-desktop",
|
|
11
|
+
];
|
|
12
|
+
const begin = "# BEGIN shared-agent-memory", end = "# END shared-agent-memory";
|
|
13
|
+
const statePath = ".memory/npm-connection.json";
|
|
14
|
+
const read = (path) => existsSync(path) ? readFileSync(path, "utf8") : null;
|
|
15
|
+
const dump = (v) => JSON.stringify(v, null, 2) + "\n";
|
|
16
|
+
const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
17
|
+
const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
18
|
+
export function atomicWrite(path, content) {
|
|
19
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
20
|
+
const temporary = path + "." + randomUUID() + ".tmp";
|
|
21
|
+
try {
|
|
22
|
+
writeFileSync(temporary, content, { mode: 0o600, flag: "wx" });
|
|
23
|
+
renameSync(temporary, path);
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
rmSync(temporary, { force: true });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
// Revert just our changes; later independent additions remain. Modified scalar
|
|
30
|
+
// values stay user-owned rather than being overwritten by an uninstall.
|
|
31
|
+
function restore(before, after, current) {
|
|
32
|
+
if (equal(current, after))
|
|
33
|
+
return before;
|
|
34
|
+
if (object(after) &&
|
|
35
|
+
object(current) &&
|
|
36
|
+
typeof after.command === "string" &&
|
|
37
|
+
Array.isArray(after.args))
|
|
38
|
+
return current;
|
|
39
|
+
if (object(after) &&
|
|
40
|
+
object(current) &&
|
|
41
|
+
(before === undefined || object(before))) {
|
|
42
|
+
const result = { ...current };
|
|
43
|
+
for (const key of new Set([
|
|
44
|
+
...Object.keys(before ?? {}),
|
|
45
|
+
...Object.keys(after),
|
|
46
|
+
])) {
|
|
47
|
+
if (equal(before?.[key], after[key]))
|
|
48
|
+
continue;
|
|
49
|
+
const value = restore(before?.[key], after[key], current[key]);
|
|
50
|
+
if (value === undefined)
|
|
51
|
+
delete result[key];
|
|
52
|
+
else
|
|
53
|
+
result[key] = value;
|
|
54
|
+
}
|
|
55
|
+
return Object.keys(result).length === 0 && before === undefined
|
|
56
|
+
? undefined
|
|
57
|
+
: result;
|
|
58
|
+
}
|
|
59
|
+
if (Array.isArray(after) &&
|
|
60
|
+
Array.isArray(current) &&
|
|
61
|
+
(before === undefined || Array.isArray(before))) {
|
|
62
|
+
const previous = before ?? [];
|
|
63
|
+
const added = after.filter((v) => !previous.some((p) => equal(p, v)));
|
|
64
|
+
const result = current.filter((v) => !added.some((a) => equal(a, v)));
|
|
65
|
+
for (const v of previous)
|
|
66
|
+
if (!after.some((a) => equal(a, v)) && !result.some((a) => equal(a, v)))
|
|
67
|
+
result.push(v);
|
|
68
|
+
return result.length === 0 && before === undefined ? undefined : result;
|
|
69
|
+
}
|
|
70
|
+
return current;
|
|
71
|
+
}
|
|
72
|
+
export function readConnectionState(workspace) {
|
|
73
|
+
const text = read(join(workspace, statePath));
|
|
74
|
+
if (!text)
|
|
75
|
+
return { schema: 1, files: {} };
|
|
76
|
+
const value = JSON.parse(text);
|
|
77
|
+
if (value.schema !== 1 || !object(value.files))
|
|
78
|
+
throw new Error("Unsupported connector state");
|
|
79
|
+
for (const [file, snapshot] of Object.entries(value.files)) {
|
|
80
|
+
if (![
|
|
81
|
+
".mcp.json",
|
|
82
|
+
".codex/config.toml",
|
|
83
|
+
".codex/hooks.json",
|
|
84
|
+
".agents/hooks.json",
|
|
85
|
+
".agents/mcp_config.json",
|
|
86
|
+
".agents/skills/continue-chat/SKILL.md",
|
|
87
|
+
".claude/settings.local.json",
|
|
88
|
+
".claude/skills/continue-chat/SKILL.md",
|
|
89
|
+
".memory/connectors/claude-desktop.json",
|
|
90
|
+
].includes(file) ||
|
|
91
|
+
!object(snapshot) ||
|
|
92
|
+
typeof snapshot.after !== "string" ||
|
|
93
|
+
!(snapshot.before === null || typeof snapshot.before === "string"))
|
|
94
|
+
throw new Error("Invalid connector state");
|
|
95
|
+
}
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
export function planConnection(opts) {
|
|
99
|
+
if (process.platform === "win32")
|
|
100
|
+
throw new Error("Windows hook installation is not yet validated. Use WSL for this preview.");
|
|
101
|
+
const workspace = realpathSync(opts.workspace), app = resolve(opts.appRoot), node = opts.node ?? process.execPath;
|
|
102
|
+
if (!opts.clients.length ||
|
|
103
|
+
opts.clients.some((c) => !clients.includes(c)))
|
|
104
|
+
throw new Error("Choose a supported client");
|
|
105
|
+
const extension = existsSync(join(app, "apps/server/src/main.js"))
|
|
106
|
+
? "js"
|
|
107
|
+
: "ts";
|
|
108
|
+
const server = join(app, "apps/server/src/main." + extension), runner = join(app, "packages/adapters/src/cli." + extension);
|
|
109
|
+
if (!existsSync(server) || !existsSync(runner))
|
|
110
|
+
throw new Error("Runtime files missing");
|
|
111
|
+
const state = readConnectionState(workspace), changes = {}, expected = {};
|
|
112
|
+
const get = (path) => {
|
|
113
|
+
const content = read(join(workspace, path));
|
|
114
|
+
expected[path] = content;
|
|
115
|
+
return content;
|
|
116
|
+
};
|
|
117
|
+
const json = (path) => {
|
|
118
|
+
const v = JSON.parse(get(path) ?? "{}");
|
|
119
|
+
if (!object(v))
|
|
120
|
+
throw new Error(path + " must be an object");
|
|
121
|
+
return v;
|
|
122
|
+
};
|
|
123
|
+
const env = {
|
|
124
|
+
MEMORY_DB: resolve(opts.database),
|
|
125
|
+
MEMORY_REPO: opts.repoId,
|
|
126
|
+
MEMORY_WORKSPACE: workspace,
|
|
127
|
+
MEMORY_SESSION_SELECTION: "1",
|
|
128
|
+
...(opts.captureNewSessions
|
|
129
|
+
? { MEMORY_CONVERSATION_MODE: "1", MEMORY_CAPTURE_NEW_SESSIONS: "1" }
|
|
130
|
+
: {}),
|
|
131
|
+
};
|
|
132
|
+
const quote = (s) => "'" + s.replaceAll("'", "'\\''") + "'";
|
|
133
|
+
const handler = (client, action) => ({
|
|
134
|
+
type: "command",
|
|
135
|
+
timeout: 10,
|
|
136
|
+
command: [
|
|
137
|
+
"env",
|
|
138
|
+
...Object.entries({
|
|
139
|
+
...env,
|
|
140
|
+
MEMORY_QUEUE: join(dirname(opts.database), "queue", client),
|
|
141
|
+
MEMORY_MANAGED: "shared-agent-memory",
|
|
142
|
+
}).map(([k, v]) => k + "=" + v),
|
|
143
|
+
node,
|
|
144
|
+
runner,
|
|
145
|
+
action,
|
|
146
|
+
client,
|
|
147
|
+
]
|
|
148
|
+
.map(quote)
|
|
149
|
+
.join(" "),
|
|
150
|
+
});
|
|
151
|
+
const connection = (desktop = false, client = "claude") => {
|
|
152
|
+
const clientEnv = {
|
|
153
|
+
...env,
|
|
154
|
+
...(desktop ? { MEMORY_CHAT_CLIENT: "claude-desktop" } : {}),
|
|
155
|
+
...(!desktop && opts.captureNewSessions ? { MEMORY_CLIENT: client } : {}),
|
|
156
|
+
};
|
|
157
|
+
if (desktop) {
|
|
158
|
+
delete clientEnv.MEMORY_CONVERSATION_MODE;
|
|
159
|
+
delete clientEnv.MEMORY_CAPTURE_NEW_SESSIONS;
|
|
160
|
+
}
|
|
161
|
+
return { command: node, args: [server], env: clientEnv };
|
|
162
|
+
};
|
|
163
|
+
function owned(path, location, current) {
|
|
164
|
+
if (current === undefined)
|
|
165
|
+
return;
|
|
166
|
+
const prior = state.files[path];
|
|
167
|
+
const previous = prior
|
|
168
|
+
? location.reduce((v, key) => v?.[key], JSON.parse(prior.after))
|
|
169
|
+
: undefined;
|
|
170
|
+
if (!equal(current, previous))
|
|
171
|
+
throw new Error("Unmanaged or modified connector conflict in " + path);
|
|
172
|
+
}
|
|
173
|
+
function mcp(path, desktop = false, client = "claude") {
|
|
174
|
+
const value = json(path);
|
|
175
|
+
value.mcpServers ??= {};
|
|
176
|
+
owned(path, ["mcpServers", "shared-memory"], value.mcpServers["shared-memory"]);
|
|
177
|
+
value.mcpServers["shared-memory"] = connection(desktop, client);
|
|
178
|
+
changes[path] = dump(value);
|
|
179
|
+
}
|
|
180
|
+
function hooks(path, client) {
|
|
181
|
+
const value = json(path);
|
|
182
|
+
value.hooks ??= {};
|
|
183
|
+
const prior = state.files[path]
|
|
184
|
+
? JSON.parse(state.files[path].after).hooks
|
|
185
|
+
: {};
|
|
186
|
+
for (const [event, action] of [
|
|
187
|
+
["SessionStart", "recall"],
|
|
188
|
+
["Stop", "capture"],
|
|
189
|
+
]) {
|
|
190
|
+
const old = prior?.[event] ?? [];
|
|
191
|
+
const groups = value.hooks[event] ?? [];
|
|
192
|
+
if (!Array.isArray(groups))
|
|
193
|
+
throw new Error("Invalid hooks in " + path);
|
|
194
|
+
// Only remove exact previously generated handlers. Edited handlers remain;
|
|
195
|
+
// reject if they mention our runner to avoid duplicate capture.
|
|
196
|
+
const oldOwned = old.filter((g) => g.hooks?.some((h) => h.command?.includes("MEMORY_MANAGED=shared-agent-memory")));
|
|
197
|
+
const kept = groups.filter((g) => !oldOwned.some((p) => equal(p, g)));
|
|
198
|
+
if (kept.some((g) => g.hooks?.some((h) => h.command?.includes("MEMORY_MANAGED=shared-agent-memory"))))
|
|
199
|
+
throw new Error("Modified hook conflict in " + path);
|
|
200
|
+
value.hooks[event] = [...kept, { hooks: [handler(client, action)] }];
|
|
201
|
+
}
|
|
202
|
+
changes[path] = dump(value);
|
|
203
|
+
}
|
|
204
|
+
function skill(path) {
|
|
205
|
+
const current = get(path);
|
|
206
|
+
if (current && current !== state.files[path]?.after)
|
|
207
|
+
throw new Error("Unmanaged or modified skill conflict");
|
|
208
|
+
changes[path] = readFileSync(join(app, "skills/continue-chat/SKILL.md"), "utf8");
|
|
209
|
+
}
|
|
210
|
+
for (const client of opts.clients) {
|
|
211
|
+
if (client === "claude-code") {
|
|
212
|
+
mcp(".mcp.json");
|
|
213
|
+
hooks(".claude/settings.local.json", "claude");
|
|
214
|
+
skill(".claude/skills/continue-chat/SKILL.md");
|
|
215
|
+
}
|
|
216
|
+
if (client === "claude-desktop")
|
|
217
|
+
mcp(".memory/connectors/claude-desktop.json", true);
|
|
218
|
+
if (client === "antigravity") {
|
|
219
|
+
mcp(".agents/mcp_config.json", false, "antigravity");
|
|
220
|
+
const path = ".agents/hooks.json", value = json(path);
|
|
221
|
+
owned(path, ["shared-memory"], value["shared-memory"]);
|
|
222
|
+
value["shared-memory"] = {
|
|
223
|
+
SessionStart: [handler("antigravity", "recall")],
|
|
224
|
+
Stop: [handler("antigravity", "capture")],
|
|
225
|
+
};
|
|
226
|
+
changes[path] = dump(value);
|
|
227
|
+
}
|
|
228
|
+
if (client === "codex") {
|
|
229
|
+
skill(".agents/skills/continue-chat/SKILL.md");
|
|
230
|
+
hooks(".codex/hooks.json", "codex");
|
|
231
|
+
const path = ".codex/config.toml", current = get(path) ?? "";
|
|
232
|
+
const parsed = parseToml(current);
|
|
233
|
+
let base = current;
|
|
234
|
+
if (current.includes(begin)) {
|
|
235
|
+
const previous = state.files[path];
|
|
236
|
+
const block = current.slice(current.indexOf(begin), current.indexOf(end) + end.length);
|
|
237
|
+
if (!previous || !previous.after.includes(block))
|
|
238
|
+
throw new Error("Modified or unmanaged Codex config conflict");
|
|
239
|
+
base = current.replace(block, "");
|
|
240
|
+
}
|
|
241
|
+
else if (parsed.mcp_servers?.["shared-memory"])
|
|
242
|
+
throw new Error("Unmanaged Codex server conflict");
|
|
243
|
+
changes[path] =
|
|
244
|
+
base.trimEnd() +
|
|
245
|
+
"\n\n" +
|
|
246
|
+
begin +
|
|
247
|
+
'\n[mcp_servers.shared-memory]\ndefault_tools_approval_mode = "writes"\ncommand = ' +
|
|
248
|
+
JSON.stringify(node) +
|
|
249
|
+
"\nargs = " +
|
|
250
|
+
JSON.stringify([server]) +
|
|
251
|
+
"\ncwd = " +
|
|
252
|
+
JSON.stringify(workspace) +
|
|
253
|
+
"\nenv = { " +
|
|
254
|
+
Object.entries({
|
|
255
|
+
...env,
|
|
256
|
+
...(opts.captureNewSessions ? { MEMORY_CLIENT: "codex" } : {}),
|
|
257
|
+
})
|
|
258
|
+
.map(([k, v]) => k + " = " + JSON.stringify(v))
|
|
259
|
+
.join(", ") +
|
|
260
|
+
' }\ntools.choose_conversation.approval_mode = "approve"\n' +
|
|
261
|
+
end +
|
|
262
|
+
"\n";
|
|
263
|
+
parseToml(changes[path]);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
for (const [path, after] of Object.entries(changes))
|
|
267
|
+
state.files[path] = {
|
|
268
|
+
before: state.files[path]
|
|
269
|
+
? unapply(path, state.files[path], expected[path] ?? null)
|
|
270
|
+
: (expected[path] ?? null),
|
|
271
|
+
after,
|
|
272
|
+
};
|
|
273
|
+
expected[statePath] = read(join(workspace, statePath));
|
|
274
|
+
changes[statePath] = dump(state);
|
|
275
|
+
return { workspace, changes, expected };
|
|
276
|
+
}
|
|
277
|
+
export function applyConnectionPlan(plan) {
|
|
278
|
+
// Optimistic concurrency prevents applying a preview over later user edits.
|
|
279
|
+
for (const [path, expected] of Object.entries(plan.expected))
|
|
280
|
+
if (read(join(plan.workspace, path)) !== expected)
|
|
281
|
+
throw new Error("Configuration changed since preview: " + path);
|
|
282
|
+
const written = [];
|
|
283
|
+
try {
|
|
284
|
+
for (const [path, content] of Object.entries(plan.changes)) {
|
|
285
|
+
if (content === null)
|
|
286
|
+
rmSync(join(plan.workspace, path), { force: true });
|
|
287
|
+
else
|
|
288
|
+
atomicWrite(join(plan.workspace, path), content);
|
|
289
|
+
written.push(path);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
for (const path of written.reverse()) {
|
|
294
|
+
const old = plan.expected[path];
|
|
295
|
+
if (old === null || old === undefined)
|
|
296
|
+
rmSync(join(plan.workspace, path), { force: true });
|
|
297
|
+
else
|
|
298
|
+
atomicWrite(join(plan.workspace, path), old);
|
|
299
|
+
}
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
const git = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
|
|
304
|
+
cwd: plan.workspace,
|
|
305
|
+
encoding: "utf8",
|
|
306
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
307
|
+
}).trim();
|
|
308
|
+
const path = join(git, "info/exclude"), current = read(path) ?? "";
|
|
309
|
+
const entries = [
|
|
310
|
+
"/.memory/",
|
|
311
|
+
...Object.keys(plan.changes)
|
|
312
|
+
.filter((p) => !p.startsWith(".memory/"))
|
|
313
|
+
.map((p) => "/" + p),
|
|
314
|
+
];
|
|
315
|
+
atomicWrite(path, current +
|
|
316
|
+
"\n" +
|
|
317
|
+
entries.filter((p) => !current.split("\n").includes(p)).join("\n") +
|
|
318
|
+
"\n");
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
/* Non-Git projects can use the planner; CLI validates Git separately. */
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function unapply(path, snapshot, current) {
|
|
325
|
+
const { before, after } = snapshot;
|
|
326
|
+
if (current === null || current === after)
|
|
327
|
+
return current === null ? null : before;
|
|
328
|
+
if (path.endsWith(".json")) {
|
|
329
|
+
const restored = restore(before === null ? undefined : JSON.parse(before), JSON.parse(after), JSON.parse(current));
|
|
330
|
+
return restored === undefined ? null : dump(restored);
|
|
331
|
+
}
|
|
332
|
+
if (path.endsWith(".toml")) {
|
|
333
|
+
const block = after.slice(after.indexOf(begin), after.indexOf(end) + end.length);
|
|
334
|
+
if (current.includes(block))
|
|
335
|
+
return current.replace(block, "").trim() || before;
|
|
336
|
+
}
|
|
337
|
+
return current;
|
|
338
|
+
}
|
|
339
|
+
export function planUninstall(workspace) {
|
|
340
|
+
const state = readConnectionState(workspace), changes = {}, expected = {};
|
|
341
|
+
for (const [path, snapshot] of Object.entries(state.files)) {
|
|
342
|
+
const current = read(join(workspace, path));
|
|
343
|
+
expected[path] = current;
|
|
344
|
+
changes[path] = unapply(path, snapshot, current);
|
|
345
|
+
}
|
|
346
|
+
expected[statePath] = read(join(workspace, statePath));
|
|
347
|
+
changes[statePath] = null;
|
|
348
|
+
return { workspace, changes, expected };
|
|
349
|
+
}
|
|
350
|
+
export function uninstallConnections(workspace) {
|
|
351
|
+
applyConnectionPlan(planUninstall(workspace));
|
|
352
|
+
}
|