@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
package/README.md CHANGED
@@ -1,24 +1,32 @@
1
1
  # Knitt
2
2
 
3
- Carry selected repository conversation context between coding agents. Choose the chat you want to continue, retrieve its checkpoint through MCP, and capture new progress using supported coding hooks.
3
+ Continue coding conversations across agents. Keep local memory, optionally sync supported project history privately to Knitt Cloud, and explicitly publish reviewed handoffs for another person.
4
4
 
5
5
  Start with the **[Knitt usage guide](docs/usage.md)** for setup, choosing a conversation, continuing work across agents, saving checkpoints, and troubleshooting.
6
6
 
7
- ## npm installation (release candidate)
7
+ ## npm installation
8
8
 
9
- The npm CLI is being prepared for publication. **It is not published yet:** the selected package is `@tinchu0/knitt`, and terminal login as `tinchu0` is verified. Until then, test the same distribution artifact locally:
9
+ Open your Git project in a coding agent and paste this into the chat:
10
+
11
+ > Run `npx @tinchu0/knitt@latest plugin` from this Git project to connect my coding agents.
12
+
13
+ Knitt detects Codex, Claude Code, and Antigravity from their local settings or executables on PATH. Add `--client` to choose specific agents. In an interactive terminal you can review the detected list before applying setup.
14
+
15
+ After setup, restart the connected agents and review their trust prompts. Ask “Set up Knitt for this project” to pair your account and approve project sync, then use `/knit` to resume a conversation. The coding agent needs local shell access, Node.js 24+, and Git.
16
+
17
+ For interactive setup from your own terminal, run:
10
18
 
11
19
  ```bash
12
- npm ci
13
- npm run build
14
- npm pack
15
- npx --yes --package ./tinchu0-knitt-0.1.0-beta.1.tgz knitt setup \
16
- --package /absolute/path/to/tinchu0-knitt-0.1.0-beta.1.tgz
20
+ npx @tinchu0/knitt setup
17
21
  ```
18
22
 
19
- Setup asks for a Git project folder and agents. It shows configuration changes before applying them, installs a persistent runtime in your user data directory, and leaves client login/trust prompts to the client. Node.js 24+ and Git are required. The npm installation path does not require Python or a source checkout once the tarball exists.
23
+ Setup asks for a Git project folder and agents. It shows configuration changes before applying them, installs a persistent runtime in your user data directory, and leaves client login/trust prompts to the client. Node.js 24+ and Git are required. No source checkout or Python is needed.
24
+
25
+ For Antigravity only:
20
26
 
21
- Once a registry package has actually been published, the intended entry point is `npx @tinchu0/knitt@next setup`. That placeholder is not a current install command.
27
+ ```bash
28
+ npx @tinchu0/knitt setup --workspace /path/to/project --client antigravity
29
+ ```
22
30
 
23
31
  The installer includes native Linux, macOS and Windows paths. Windows uses built-in Windows PowerShell for hooks; macOS and Linux use POSIX hooks. CI is configured to run the full suite and packaged lifecycle checks on all three operating systems. Linux checks passed locally; native Windows/macOS runs and live client handoffs still need confirmation. Claude Desktop currently receives a configuration fragment requiring a manual merge into Desktop settings. No universal client compatibility is claimed.
24
32
 
@@ -26,17 +34,18 @@ See [npm installation and lifecycle](docs/clients/npm-installation.md) and [remo
26
34
 
27
35
  ## What gets connected
28
36
 
29
- - **Codex, Claude Code, Antigravity:** repository MCP settings and startup/stop hooks. Restart clients and approve MCP/hook trust normally.
37
+ - **Codex, Claude Code:** repository MCP settings and startup/stop hooks. Restart clients and approve MCP/hook trust normally.
38
+ - **Antigravity:** project startup/stop hooks plus automatic registration in `~/.gemini/config/mcp_config.json`. Each project gets its own server name. Setup verifies its memory tools before activating the runtime. Restart Antigravity and use `/knit` in a fresh chat. Choose a conversation inside the same coding interface. Antigravity uses its selectable question UI; clients with native MCP forms can use those.
30
39
  - **Claude Desktop:** a generated local MCP fragment; chat checkpoints use tool calls rather than coding hooks.
31
40
  - **ChatGPT / Claude web:** authenticated HTTP MCP is implemented, but requires your own public HTTPS endpoint and compatible OAuth provider. Local CLI setup does not provision a shared server.
32
41
 
33
- The knit skill calls the user picker. New sessions begin unselected. The current history importer discovers local Antigravity conversations in the connected repository, including linked worktrees. It does not access arbitrary Claude or ChatGPT account histories. Ordinary chat MCP clients must explicitly call memory tools to save checkpoints; MCP alone cannot passively capture every chat turn.
42
+ The knit skill calls the user picker. New sessions begin unselected. The history importer discovers local Claude Code project transcripts, Codex sessions and Antigravity conversations in the connected repository, including linked worktrees. It excludes the current coding agent and sorts the other agents’ histories newest first. It does not access remote Claude or ChatGPT account histories. Ordinary chat MCP clients must explicitly call memory tools to save checkpoints; MCP alone cannot passively capture every chat turn.
34
43
 
35
- Local memory is local to one machine. Team sharing requires a shared authenticated service; identical repository names do not synchronize databases.
44
+ Local installation alone uploads nothing. After browser account pairing, review the project and discovered histories inside the agent and approve private automatic sync. Select an existing cloud project explicitly when connecting another installation. Sharing with another person requires a reviewed publication, an invitation and acceptance. Manage access at https://knit.deeeznuts.me; identical repository names never join projects automatically.
36
45
 
37
46
  ## Memory behavior
38
47
 
39
- The tools are `choose_conversation`, `get_context`, `search_memory`, `get_evidence` and `save_memory`; ordinary chat profiles also expose `start_session`. Repository/session checks prevent one session from silently choosing another session's feature. The HTTP gateway validates JWT issuer, audience, expiry, subjects and scopes. Allowed users of a repository service share its feature evidence; finer team roles remain future work.
48
+ Local memory tools include `choose_conversation`, `get_context`, `search_memory`, `get_evidence` and `save_memory`; ordinary chat profiles also expose `start_session`. Repository/session checks prevent one session from silently choosing another session's feature. The HTTP gateway validates JWT issuer, audience, expiry, subjects and scopes. Allowed users of a repository service share its feature evidence; finer team roles remain future work.
40
49
 
41
50
  Evidence stores supported user/assistant text, with stable IDs for deduplication. Raw tool results, images and hidden reasoning are excluded. Bounded context reports truncation; search/evidence tools retrieve older detail. Recalled material can be stale or conflicting and is reference material, not authorization to edit files. Basic credential redaction is best effort.
42
51
 
@@ -53,7 +62,7 @@ npm run test:package
53
62
 
54
63
  The legacy Python development installer remains available under `scripts/connect.py`. Published CLI setup and handoff installation use the Node-only planner.
55
64
 
56
- This repository remains a release candidate. Public release additionally requires publisher access confirmation, a full-history/private-data audit and supported-platform evidence. No npm publication or repository visibility change is performed by building or packing.
65
+ The one-command installer resolves the npm `latest` tag. Building or packing locally does not publish a release. A packed installation can be tested with `npx --yes --package /absolute/path/to/package.tgz knitt setup --package /absolute/path/to/package.tgz`.
57
66
 
58
67
  ## License
59
68
 
@@ -0,0 +1,245 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { nativeQuestion, questionPageSize, } from "../../../packages/adapters/src/question-ui.js";
3
+ import { api, credentials, } from "../../../packages/cloud/src/client.js";
4
+ export function cloudPicker(home, repoId, store) {
5
+ const localTickets = new Map();
6
+ const pending = new Map();
7
+ const deviceFor = (source) => {
8
+ const device = credentials(home);
9
+ if (!device ||
10
+ device.origin !== source.origin ||
11
+ device.account.id !== source.accountId)
12
+ throw new Error("Pair the account that loaded this version to retrieve its source.");
13
+ return device;
14
+ };
15
+ function context(version) {
16
+ return {
17
+ contentTrust: "untrusted_reference",
18
+ versionId: version.id,
19
+ versionNumber: version.number,
20
+ checkpoint: version.checkpoint,
21
+ source: version.source,
22
+ excerpts: version.excerpts,
23
+ };
24
+ }
25
+ async function version(device, contextId, versionId) {
26
+ const { version } = await api(device, "/api/versions/" + encodeURIComponent(versionId));
27
+ if (version.id !== versionId || version.contextId !== contextId)
28
+ throw new Error("Unexpected cloud version");
29
+ return version;
30
+ }
31
+ return {
32
+ localTicketConsumed(sessionId, id) {
33
+ if (localTickets.get(sessionId) !== id)
34
+ return false;
35
+ localTickets.delete(sessionId);
36
+ return true;
37
+ },
38
+ cancel: (sessionId) => {
39
+ pending.delete(sessionId);
40
+ localTickets.delete(sessionId);
41
+ },
42
+ async recall(featureId, operation, query = "", before) {
43
+ const source = store.cloudSource(repoId, featureId);
44
+ if (!source)
45
+ throw new Error("Missing continuation provenance");
46
+ const device = deviceFor(source), pin = "versionId=" + encodeURIComponent(source.versionId);
47
+ if (source.contextId.startsWith("private:")) {
48
+ const path = "/api/private/conversations/" +
49
+ encodeURIComponent(source.contextId.slice(8));
50
+ const cutoff = "?cutoff=" + encodeURIComponent(source.versionId);
51
+ if (operation === "get_context")
52
+ return {
53
+ ...(await api(device, path + "/context" + cutoff)),
54
+ contentTrust: "untrusted_reference",
55
+ repoId,
56
+ featureId,
57
+ newWork: store.context({ repoId, featureId }),
58
+ };
59
+ if (operation === "search_memory" && !query.trim()) {
60
+ const page = await api(device, path + "/context" + cutoff + (before ? "&before=" + before : ""));
61
+ return {
62
+ ...page,
63
+ nextCursor: page.nextBefore,
64
+ contentTrust: "untrusted_reference",
65
+ };
66
+ }
67
+ if (operation === "search_memory")
68
+ return api(device, path + "/search" + cutoff + "&q=" + encodeURIComponent(query));
69
+ return api(device, path + "/evidence" + cutoff + "&eventId=" + encodeURIComponent(query));
70
+ }
71
+ if (operation === "get_context")
72
+ return {
73
+ ...context(await version(device, source.contextId, source.versionId)),
74
+ repoId,
75
+ featureId,
76
+ newWork: store.context({ repoId, featureId }),
77
+ };
78
+ if (operation === "search_memory")
79
+ return api(device, "/api/search?" + pin + "&q=" + encodeURIComponent(query));
80
+ return api(device, "/api/evidence/" + encodeURIComponent(query) + "?" + pin);
81
+ },
82
+ async choose(client, workspace, sessionId, query, choiceId) {
83
+ for (const [id, state] of pending)
84
+ if (state.expires <= Date.now())
85
+ pending.delete(id);
86
+ const state = pending.get(sessionId);
87
+ const action = choiceId ? state?.choices.get(choiceId) : undefined;
88
+ if (choiceId && !action)
89
+ return null; // Existing local picker validates its own tickets.
90
+ pending.delete(sessionId);
91
+ const device = action && state ? deviceFor(state) : credentials(home);
92
+ if (!device)
93
+ return null;
94
+ if (state && choiceId && state.workspace !== workspace)
95
+ throw new Error("Picker workspace changed");
96
+ if (action?.kind === "local" && choiceId) {
97
+ localTickets.set(sessionId, choiceId);
98
+ return null;
99
+ }
100
+ const list = (title, choices, page = 0, next) => {
101
+ if (!choices.length)
102
+ return {
103
+ selectionRequired: true,
104
+ message: "No authorized matches. Open /knit again to select another source.",
105
+ };
106
+ const size = questionPageSize(client) + (next ? 0 : 1), displayed = choices.slice(page * size, (page + 1) * size);
107
+ if (next && (page + 1) * size < choices.length)
108
+ displayed.push({
109
+ title: "More",
110
+ action: { ...next, page: page + 1 },
111
+ });
112
+ const ids = new Map();
113
+ const options = displayed.map((c) => {
114
+ const choiceId = randomUUID();
115
+ ids.set(choiceId, c.action);
116
+ return { title: c.title, label: c.title, modified: "", choiceId };
117
+ });
118
+ if (pending.size >= 1000)
119
+ throw new Error("Too many pending selections");
120
+ pending.set(sessionId, {
121
+ workspace,
122
+ origin: device.origin,
123
+ accountId: device.account.id,
124
+ choices: ids,
125
+ expires: Date.now() + 600_000,
126
+ });
127
+ return {
128
+ sessionId,
129
+ workspace,
130
+ repoId,
131
+ selectionRequired: true,
132
+ presentation: "native_question",
133
+ nativeQuestion: nativeQuestion(client, workspace, options, 0, 1, title),
134
+ options,
135
+ };
136
+ };
137
+ if (!action)
138
+ return list("Where would you like to continue from?", [
139
+ { title: "My synced conversations", action: { kind: "personal" } },
140
+ { title: "Local conversations", action: { kind: "local" } },
141
+ { title: "Shared with me", action: { kind: "shared" } },
142
+ ]);
143
+ if (action.kind === "personal") {
144
+ const conversations = [];
145
+ let cursor = null;
146
+ do {
147
+ const page = await api(device, "/api/private/conversations" +
148
+ (cursor ? "?cursor=" + encodeURIComponent(cursor) : ""));
149
+ conversations.push(...page.conversations);
150
+ cursor = page.nextCursor ?? null;
151
+ } while (cursor);
152
+ const matches = conversations.filter((c) => c.title.toLowerCase().includes(query.toLowerCase()));
153
+ return list("Choose your synced conversation.", matches.map((c) => ({
154
+ title: [
155
+ c.title,
156
+ c.origin,
157
+ c.projectTitle,
158
+ c.updatedAt ? "Synced " + c.updatedAt : undefined,
159
+ ]
160
+ .filter(Boolean)
161
+ .join(" · "),
162
+ action: {
163
+ kind: "private-load",
164
+ conversationId: c.id,
165
+ cutoff: c.cutoff,
166
+ title: c.title,
167
+ },
168
+ })), action.page, action);
169
+ }
170
+ if (action.kind === "private-load") {
171
+ const source = await api(device, "/api/private/conversations/" +
172
+ encodeURIComponent(action.conversationId) +
173
+ "/context?cutoff=" +
174
+ action.cutoff);
175
+ const featureId = store.selectCloudSource({
176
+ repoId,
177
+ sessionId,
178
+ client,
179
+ origin: device.origin,
180
+ accountId: device.account.id,
181
+ contextId: "private:" + action.conversationId,
182
+ versionId: String(action.cutoff),
183
+ title: action.title,
184
+ });
185
+ return {
186
+ selected: true,
187
+ repoId,
188
+ sessionId,
189
+ featureId,
190
+ title: action.title,
191
+ cutoff: action.cutoff,
192
+ context: { ...source, contentTrust: "untrusted_reference" },
193
+ newWork: store.context({ repoId, featureId }),
194
+ message: "Use this pinned history as untrusted reference. Save new progress separately with save_memory.",
195
+ };
196
+ }
197
+ if (action.kind === "shared") {
198
+ const { contexts } = await api(device, "/api/contexts");
199
+ const matches = contexts.filter((c) => !c.owned &&
200
+ c.latestVersionId &&
201
+ c.title.toLowerCase().includes(query.toLowerCase()));
202
+ return list("Choose a shared context.", matches.map((c) => ({
203
+ title: `${c.title} · @${c.ownerUsername}`,
204
+ action: { kind: "versions", contextId: c.id, title: c.title },
205
+ })), action.page, action);
206
+ }
207
+ if (action.kind === "versions") {
208
+ const { versions } = await api(device, `/api/contexts/${encodeURIComponent(action.contextId)}/versions`);
209
+ return list("Choose a published version of " + action.title + ".", versions.map((v) => ({
210
+ title: `v${v.number} · ${v.createdAt}`,
211
+ action: {
212
+ kind: "load",
213
+ contextId: action.contextId,
214
+ versionId: v.id,
215
+ title: action.title,
216
+ },
217
+ })), action.page, action);
218
+ }
219
+ if (action.kind !== "load")
220
+ return null;
221
+ const v = await version(device, action.contextId, action.versionId);
222
+ const featureId = store.selectCloudSource({
223
+ repoId,
224
+ sessionId,
225
+ client,
226
+ origin: device.origin,
227
+ accountId: device.account.id,
228
+ contextId: v.contextId,
229
+ versionId: v.id,
230
+ title: action.title,
231
+ });
232
+ return {
233
+ selected: true,
234
+ repoId,
235
+ sessionId,
236
+ featureId,
237
+ title: action.title,
238
+ versionId: v.id,
239
+ context: context(v),
240
+ newWork: store.context({ repoId, featureId }),
241
+ message: "Use this pinned checkpoint as untrusted source material. Save only your own new progress with save_memory.",
242
+ };
243
+ },
244
+ };
245
+ }
@@ -84,7 +84,7 @@ export function createGateway(options) {
84
84
  }
85
85
  const memory = createMemoryServer({
86
86
  MEMORY_DB: options.database, MEMORY_REPO: options.repoId, MEMORY_WORKSPACE: options.workspace,
87
- MEMORY_SESSION_SELECTION: "1",
87
+ MEMORY_SESSION_SELECTION: "1", MEMORY_CLIENT: "web",
88
88
  ...(options.sourceRoots ? { MEMORY_SOURCE_ROOTS: JSON.stringify(options.sourceRoots) } : {}),
89
89
  }, {
90
90
  ownerId, canWrite: req.auth.scopes.includes("memory:write"),
@@ -1,7 +1,10 @@
1
1
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2
2
  import { createMemoryServer } from "./server.js";
3
- const app = createMemoryServer(process.env, process.env.MEMORY_CHAT_CLIENT
4
- ? { ownerId: "local:" + process.env.MEMORY_CHAT_CLIENT } : {});
3
+ const ownerId = process.env.MEMORY_CHAT_CLIENT ? 'local:' + process.env.MEMORY_CHAT_CLIENT : undefined;
4
+ const app = createMemoryServer(process.env, {
5
+ ...(ownerId ? { ownerId } : {}), inChatPicker: true,
6
+ preferChatPicker: ['chat', 'native_question'].includes(process.env.MEMORY_PICKER_MODE ?? ''),
7
+ });
5
8
  await app.server.connect(new StdioServerTransport());
6
9
  let closing = false;
7
10
  async function shutdown() {
@@ -13,3 +16,4 @@ async function shutdown() {
13
16
  }
14
17
  process.on("SIGINT", () => { void shutdown(); });
15
18
  process.on("SIGTERM", () => { void shutdown(); });
19
+ process.stdin.on('end', () => { void shutdown(); });
@@ -0,0 +1,266 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { hostname } from "node:os";
3
+ import { spawn } from "node:child_process";
4
+ import { existsSync, readFileSync, rmSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { z } from "zod";
7
+ import { api, CloudError, credentials, credentialsPath, defaultServer, request, serverOrigin, } from "../../../packages/cloud/src/client.js";
8
+ import { atomicWrite } from "../../../packages/installer/src/connections.js";
9
+ import { defaultHistoryRoots, discoverHistories, } from "../../../packages/adapters/src/histories.js";
10
+ import { bindWorkspace, canonicalWorkspace, controlSync, digest, syncStatus, syncWorkspace, syncDatabase, } from "../../../packages/cloud/src/local-sync.js";
11
+ export function registerOnboarding(server, home, env, workspace) {
12
+ const output = (data) => ({
13
+ content: [{ type: "text", text: JSON.stringify(data) }],
14
+ structuredContent: data,
15
+ });
16
+ const account = () => {
17
+ const device = credentials(home);
18
+ if (!device)
19
+ throw new Error("Connect this installation first with knitt_connect.");
20
+ return device;
21
+ };
22
+ const pairPath = join(home, "cloud", "pairing.json");
23
+ const previews = new Map();
24
+ server.registerTool("knitt_invitations", {
25
+ description: "List friend invitations independently of personal sync setup. Show sender, title and starting version. Accept or decline only after the user explicitly chooses that invitation and action.",
26
+ inputSchema: {
27
+ action: z.enum(["list", "accept", "decline"]),
28
+ invitationId: z.string().uuid().optional(),
29
+ userApproved: z.boolean().optional(),
30
+ },
31
+ }, async ({ action, invitationId, userApproved }) => {
32
+ const device = account();
33
+ if (action === "list")
34
+ return output(await api(device, "/api/inbox"));
35
+ if (!invitationId || userApproved !== true)
36
+ throw new Error("Show the invitation and obtain explicit user approval for this action.");
37
+ const response = await api(device, "/api/invitations/" + encodeURIComponent(invitationId) + "/" + action, {});
38
+ return output({
39
+ ...response,
40
+ next: action === "accept"
41
+ ? "Call choose_conversation and let the user select Shared with me, then this context and its published version. Personal autosync remains disabled until separate approval."
42
+ : "Invitation declined.",
43
+ });
44
+ });
45
+ server.registerTool("knitt_status", {
46
+ description: "Show the connected account, this canonical workspace mapping, consent, pending uploads and errors.",
47
+ inputSchema: {},
48
+ }, async () => output(syncStatus(home, workspace)));
49
+ server.registerTool("knitt_connect", {
50
+ description: "Begin browser account approval or poll an existing pairing. This does not upload history. Show the approval code and URL to the user.",
51
+ inputSchema: {
52
+ action: z.enum(["begin", "poll", "reconnect"]),
53
+ userApproved: z.boolean().optional(),
54
+ server: z.string().optional(),
55
+ openBrowser: z.boolean().default(true),
56
+ },
57
+ }, async (input) => {
58
+ const existing = credentials(home);
59
+ if (existing && input.action !== "reconnect") {
60
+ try {
61
+ await api(existing, "/api/me");
62
+ return output(syncStatus(home, workspace));
63
+ }
64
+ catch (error) {
65
+ if (!(error instanceof CloudError) ||
66
+ ![401, 403].includes(error.status))
67
+ throw error;
68
+ return output({
69
+ ...syncStatus(home, workspace),
70
+ connectionInvalid: true,
71
+ next: "This device authorization was revoked. Ask the user to reconnect, then call knitt_connect with action reconnect and userApproved true. Existing sync mappings stay suspended until separate approval.",
72
+ });
73
+ }
74
+ }
75
+ if (input.action === "reconnect") {
76
+ if (input.userApproved !== true)
77
+ throw new Error("Get explicit user approval before disconnecting this account and reconnecting.");
78
+ if (existing) {
79
+ const db = syncDatabase(home);
80
+ try {
81
+ db.prepare("UPDATE bindings SET enabled=0 WHERE account=? AND origin=?").run(existing.account.id, existing.origin);
82
+ }
83
+ finally {
84
+ db.close();
85
+ }
86
+ await request(existing.origin, "/api/devices/current", {
87
+ method: "DELETE",
88
+ token: existing.token,
89
+ }).catch(() => { });
90
+ rmSync(credentialsPath(home), { force: true });
91
+ }
92
+ }
93
+ if (input.action === "begin" || input.action === "reconnect") {
94
+ const origin = serverOrigin(input.server ?? env.KNITT_CLOUD_ORIGIN ?? defaultServer);
95
+ const pairing = {
96
+ ...(await request(origin, "/api/device-pairings", { body: { name: hostname() } })),
97
+ origin,
98
+ };
99
+ const url = new URL(pairing.verificationUri, origin);
100
+ if (url.origin !== origin)
101
+ throw new Error("Approval URL belongs to another server.");
102
+ atomicWrite(pairPath, JSON.stringify(pairing));
103
+ if (input.openBrowser) {
104
+ const command = process.platform === "darwin"
105
+ ? "open"
106
+ : process.platform === "win32"
107
+ ? "rundll32.exe"
108
+ : "xdg-open";
109
+ const child = spawn(command, process.platform === "win32"
110
+ ? ["url.dll,FileProtocolHandler", url.href]
111
+ : [url.href], { stdio: "ignore", detached: true });
112
+ child.on("error", () => { });
113
+ child.unref();
114
+ }
115
+ return output({
116
+ status: "approval_required",
117
+ verificationUri: url.href,
118
+ userCode: pairing.userCode,
119
+ expiresAt: pairing.expiresAt,
120
+ interval: pairing.interval,
121
+ next: "Ask the user to approve in the browser, then poll. No histories are uploaded until separate workspace consent.",
122
+ });
123
+ }
124
+ if (!existsSync(pairPath))
125
+ throw new Error("Begin account connection first.");
126
+ const pairing = JSON.parse(readFileSync(pairPath, "utf8"));
127
+ if (Date.parse(pairing.expiresAt) < Date.now())
128
+ throw new Error("Pairing expired; begin again.");
129
+ const response = await request(pairing.origin, "/api/device-pairings/exchange", {
130
+ body: { pairingId: pairing.pairingId, deviceCode: pairing.deviceCode },
131
+ });
132
+ if (response.status === "pending")
133
+ return output({ status: "pending", interval: pairing.interval });
134
+ if (!response.token || !response.account?.id || !response.device?.id)
135
+ throw new Error("Incomplete pairing response.");
136
+ atomicWrite(credentialsPath(home), JSON.stringify({
137
+ origin: pairing.origin,
138
+ token: response.token,
139
+ account: response.account,
140
+ device: response.device,
141
+ }));
142
+ rmSync(pairPath);
143
+ return output({
144
+ ...syncStatus(home, workspace),
145
+ next: "Call knitt_preview_sync, show the discovered histories and privacy scope, and ask the user to select or create a project and approve sync.",
146
+ });
147
+ });
148
+ server.registerTool("knitt_preview_sync", {
149
+ description: "Discover supported local histories for this workspace and list explicit cloud projects. Does not upload text. Show this preview and obtain user approval before enable_sync.",
150
+ inputSchema: {},
151
+ }, async () => {
152
+ const device = account(), roots = defaultHistoryRoots(env), canonical = canonicalWorkspace(workspace);
153
+ const histories = discoverHistories({ roots, workspace: canonical });
154
+ const previewId = randomUUID();
155
+ previews.set(previewId, {
156
+ accountId: device.account.id,
157
+ deviceId: device.device.id,
158
+ origin: device.origin,
159
+ workspace: canonical,
160
+ roots,
161
+ fingerprint: digest(histories.map((c) => [c.client, c.id, c.root, c.workspace])),
162
+ expires: Date.now() + 600_000,
163
+ });
164
+ const projects = await api(device, "/api/private/projects");
165
+ return output({
166
+ previewId,
167
+ account: device.account,
168
+ workspace: canonical,
169
+ historyRoots: roots,
170
+ histories: histories.map((c) => ({
171
+ agent: c.client ?? "antigravity",
172
+ id: c.id,
173
+ title: c.title,
174
+ workspace: c.workspace,
175
+ modified: c.modified,
176
+ })),
177
+ projects: projects.projects,
178
+ scope: "All supported user and assistant text in these workspace histories, including future sessions, is uploaded privately to this account after approval. Secrets are redacted by the existing importer. Tool outputs and unsupported message shapes are excluded. Select an existing project ID or explicitly create a new project; names never autojoin projects.",
179
+ });
180
+ });
181
+ server.registerTool("knitt_enable_sync", {
182
+ description: "Enable private full-history autosync ONLY after the user approves the preview and explicitly selects a project or asks to create one.",
183
+ inputSchema: {
184
+ previewId: z.string(),
185
+ projectId: z.string().uuid().optional(),
186
+ createTitle: z.string().trim().min(1).max(160).optional(),
187
+ userApproved: z.literal(true),
188
+ },
189
+ }, async (input) => {
190
+ const device = account(), preview = previews.get(input.previewId);
191
+ if (!preview ||
192
+ preview.expires < Date.now() ||
193
+ preview.accountId !== device.account.id ||
194
+ preview.deviceId !== device.device.id ||
195
+ preview.origin !== device.origin)
196
+ throw new Error("Preview expired or account changed; preview again.");
197
+ if (!!input.projectId === !!input.createTitle)
198
+ throw new Error("Choose one existing project ID or explicitly create a new project.");
199
+ const current = discoverHistories({
200
+ roots: preview.roots,
201
+ workspace: preview.workspace,
202
+ });
203
+ if (digest(current.map((c) => [c.client, c.id, c.root, c.workspace])) !==
204
+ preview.fingerprint)
205
+ throw new Error("History discovery changed; show a fresh preview before approval.");
206
+ let projectId = input.projectId;
207
+ if (!projectId) {
208
+ const response = await api(device, "/api/private/projects", { id: randomUUID(), title: input.createTitle });
209
+ projectId = response.project.id;
210
+ }
211
+ else {
212
+ const { projects } = await api(device, "/api/private/projects");
213
+ if (!projects.some((p) => p.id === projectId))
214
+ throw new Error("Select a project belonging to this account.");
215
+ }
216
+ await api(device, `/api/private/projects/${encodeURIComponent(projectId)}/consent`, { enabled: true });
217
+ bindWorkspace(home, device, preview.workspace, projectId, preview.roots);
218
+ previews.delete(input.previewId);
219
+ return output({
220
+ enabled: true,
221
+ projectId,
222
+ ...(await syncWorkspace(home, env, workspace)),
223
+ });
224
+ });
225
+ server.registerTool("knitt_disconnect_account", {
226
+ description: "Disconnect this device from its account, stop all local cloud uploads, and preserve native history and local memory. Requires the user's explicit request.",
227
+ inputSchema: { userApproved: z.literal(true) },
228
+ }, async () => {
229
+ const device = account();
230
+ const db = syncDatabase(home);
231
+ try {
232
+ db.prepare("UPDATE bindings SET enabled=0 WHERE account=? AND origin=?").run(device.account.id, device.origin);
233
+ }
234
+ finally {
235
+ db.close();
236
+ }
237
+ let remoteRevoked = false;
238
+ let remoteError;
239
+ try {
240
+ await request(device.origin, "/api/devices/current", {
241
+ method: "DELETE",
242
+ token: device.token,
243
+ });
244
+ remoteRevoked = true;
245
+ }
246
+ catch (error) {
247
+ remoteError = String(error);
248
+ }
249
+ finally {
250
+ rmSync(credentialsPath(home), { force: true });
251
+ }
252
+ return output({
253
+ connected: false,
254
+ remoteRevoked,
255
+ ...(remoteError ? { remoteError } : {}),
256
+ });
257
+ });
258
+ server.registerTool("knitt_sync", {
259
+ description: "Retry durable pending uploads and sync complete histories for this approved workspace.",
260
+ inputSchema: {},
261
+ }, async () => output((await syncWorkspace(home, env, workspace))));
262
+ server.registerTool("knitt_sync_control", {
263
+ description: "Pause, resume or disconnect this workspace sync. Disconnect removes its local mapping and pending uploads; retained server data stays in the account.",
264
+ inputSchema: { action: z.enum(["pause", "resume", "disconnect"]) },
265
+ }, async ({ action }) => output(await controlSync(home, workspace, action)));
266
+ }