@tinchu0/knitt 0.1.0-beta.5 → 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 (42) hide show
  1. package/README.md +25 -27
  2. package/dist/apps/server/src/cloud-picker.js +245 -0
  3. package/dist/apps/server/src/onboarding.js +266 -0
  4. package/dist/apps/server/src/plugin-bootstrap.js +82 -0
  5. package/dist/apps/server/src/plugin-hook.js +51 -0
  6. package/dist/apps/server/src/plugin-main.js +10 -0
  7. package/dist/apps/server/src/server.js +126 -258
  8. package/dist/packages/adapters/src/cli.js +59 -190
  9. package/dist/packages/adapters/src/command.js +18 -149
  10. package/dist/packages/adapters/src/handoff.js +2 -3
  11. package/dist/packages/adapters/src/histories.js +2 -3
  12. package/dist/packages/adapters/src/hooks.js +43 -122
  13. package/dist/packages/adapters/src/launch.js +3 -10
  14. package/dist/packages/adapters/src/question-ui.js +4 -4
  15. package/dist/packages/adapters/src/repository.js +5 -32
  16. package/dist/packages/adapters/src/scope.js +1 -1
  17. package/dist/packages/adapters/src/server-name.js +1 -2
  18. package/dist/packages/adapters/src/transcript.js +15 -70
  19. package/dist/packages/cloud/src/client.js +40 -0
  20. package/dist/packages/cloud/src/local-sync.js +300 -0
  21. package/dist/packages/installer/src/antigravity.js +3 -3
  22. package/dist/packages/installer/src/cli.js +79 -194
  23. package/dist/packages/installer/src/cloud-cli.js +199 -0
  24. package/dist/packages/installer/src/connections.js +43 -170
  25. package/dist/packages/installer/src/runtime.js +10 -72
  26. package/dist/packages/memory/src/store.js +58 -200
  27. package/dist/skills/knit/SKILL.md +20 -4
  28. package/docs/clients/npm-installation.md +17 -13
  29. package/docs/usage.md +19 -10
  30. package/package.json +9 -7
  31. package/dist/apps/server/src/conversation-server.js +0 -203
  32. package/dist/memory-schema.json +0 -1
  33. package/dist/packages/adapters/src/discovery.js +0 -128
  34. package/dist/packages/adapters/src/providers/jsonl.js +0 -105
  35. package/dist/packages/adapters/src/status.js +0 -81
  36. package/dist/packages/contracts/src/conversations.js +0 -30
  37. package/dist/packages/memory/src/checkpoints.js +0 -68
  38. package/dist/packages/memory/src/context.js +0 -91
  39. package/dist/packages/memory/src/conversations.js +0 -148
  40. package/dist/packages/memory/src/migrations.js +0 -55
  41. package/dist/skills/continue-chat/SKILL.md +0 -15
  42. package/docs/clients/local-agent-memory.md +0 -50
@@ -1,31 +1,38 @@
1
1
  #!/usr/bin/env node
2
- import { readCaptureStatuses } from '../../adapters/src/status.js';
3
2
  import { parseArgs } from 'node:util';
4
3
  import { createInterface } from 'node:readline/promises';
5
4
  import { fileURLToPath } from 'node:url';
6
- import { join, resolve, dirname, basename } from 'node:path';
7
- import { existsSync, readFileSync, accessSync, constants, } 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';
8
8
  import { execFileSync } from 'node:child_process';
9
- import { planConnection, applyConnectionPlan, planUninstall, clients, atomicWrite, readConnectionState, rollbackConnectionPlan, } from './connections.js';
10
- import { installRuntime, readInstallation, defaultHome, runtimePaths, withInstallLock, activateRuntime, assertRuntimeCompatibility, packageName, } from './runtime.js';
11
- import { planAntigravity, verifyAntigravity, defaultAntigravityConfig, } from './antigravity.js';
9
+ import { planConnection, applyConnectionPlan, planUninstall, clients, atomicWrite, readConnectionState, rollbackConnectionPlan } from './connections.js';
10
+ import { installRuntime, readInstallation, defaultHome, runtimePaths, withInstallLock, activateRuntime, packageName } from './runtime.js';
11
+ import { planAntigravity, verifyAntigravity, defaultAntigravityConfig } from './antigravity.js';
12
12
  import { antigravityServerName } from '../../adapters/src/server-name.js';
13
13
  import { resolveRepository } from '../../adapters/src/repository.js';
14
14
  const appRoot = fileURLToPath(new URL('../../../', import.meta.url));
15
- const packageRoot = existsSync(join(appRoot, 'package.json'))
16
- ? appRoot
17
- : dirname(appRoot);
15
+ const packageRoot = existsSync(join(appRoot, 'package.json')) ? appRoot : dirname(appRoot);
18
16
  const metadata = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'));
19
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
+ }
20
30
  async function confirm(text, yes = false) {
21
31
  if (yes)
22
32
  return true;
23
33
  if (!process.stdin.isTTY)
24
34
  throw new Error('Use --yes for noninteractive apply, or --preview to inspect without changes');
25
- const reader = createInterface({
26
- input: process.stdin,
27
- output: process.stdout,
28
- });
35
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
29
36
  try {
30
37
  return /^y(es)?$/i.test((await reader.question(text + ' [y/N] ')).trim());
31
38
  }
@@ -36,10 +43,7 @@ async function confirm(text, yes = false) {
36
43
  async function ask(prompt) {
37
44
  if (!process.stdin.isTTY)
38
45
  throw new Error('Pass --workspace and --client for noninteractive setup');
39
- const reader = createInterface({
40
- input: process.stdin,
41
- output: process.stdout,
42
- });
46
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
43
47
  try {
44
48
  return (await reader.question(prompt)).trim();
45
49
  }
@@ -72,79 +76,33 @@ async function applyAll(plans, commit, verify = async () => { }) {
72
76
  throw error;
73
77
  }
74
78
  }
75
- function plansFor(runtime, projects) {
76
- return projects.map((project) => planConnection({
77
- ...project,
78
- appRoot: runtime.appRoot,
79
- node: runtime.node,
80
- }));
81
- }
79
+ function plansFor(runtime, projects, installationHome) { return projects.map(project => planConnection({ ...project, appRoot: runtime.appRoot, node: runtime.node, installationHome })); }
82
80
  async function main() {
83
- const { values, positionals } = parseArgs({
84
- allowPositionals: true,
85
- options: {
86
- session: { type: 'string' },
87
- workspace: { type: 'string' },
88
- client: { type: 'string', multiple: true },
89
- home: { type: 'string' },
90
- package: { type: 'string' },
91
- yes: { type: 'boolean' },
92
- preview: { type: 'boolean' },
93
- 'capture-new-sessions': { type: 'boolean' },
94
- 'antigravity-config': { type: 'string' },
95
- version: { type: 'boolean' },
96
- help: { type: 'boolean' },
97
- },
98
- });
81
+ if (process.argv[2] === 'cloud') {
82
+ const { runCloud } = await import('./cloud-cli.js');
83
+ return runCloud(process.argv.slice(3));
84
+ }
85
+ const { values, positionals } = parseArgs({ allowPositionals: true, options: {
86
+ workspace: { type: 'string' }, client: { type: 'string', multiple: true }, home: { type: 'string' },
87
+ package: { type: 'string' }, yes: { type: 'boolean' }, preview: { type: 'boolean' },
88
+ 'antigravity-config': { type: 'string' }, version: { type: 'boolean' }, help: { type: 'boolean' },
89
+ } });
99
90
  if (values.version) {
100
91
  console.log(version);
101
92
  return;
102
93
  }
103
- const action = positionals[0];
94
+ const plugin = positionals[0] === 'plugin';
95
+ const action = plugin ? 'setup' : positionals[0];
104
96
  if (!action || values.help) {
105
- console.log('Knitt ' +
106
- version +
107
- '\nCommands: setup, doctor, update, rollback, uninstall, serve, continue\nOptions: --workspace PATH --client codex|claude-code|antigravity|claude-desktop (repeatable)\n --antigravity-config PATH --capture-new-sessions --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.');
108
98
  return;
109
99
  }
110
100
  const home = resolve(values.home ?? defaultHome()), paths = runtimePaths(home);
111
- if (action === 'continue') {
112
- if (!values.workspace)
113
- throw new Error('Pass --workspace for the connected project');
114
- const common = (cwd) => execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
115
- const expected = common(resolve(values.workspace));
116
- const state = readInstallation(home);
117
- const project = state?.projects.find((p) => {
118
- try {
119
- return common(p.workspace) === expected;
120
- }
121
- catch {
122
- return false;
123
- }
124
- });
125
- if (!project?.captureNewSessions)
126
- throw new Error('This project has not opted into local conversation mode; run setup --capture-new-sessions first');
127
- process.env.MEMORY_DB = project.database;
128
- process.env.MEMORY_REPO = project.repoId;
129
- process.env.MEMORY_CONVERSATION_MODE = '1';
130
- await import('../../adapters/src/command.js');
131
- return;
132
- }
133
101
  const initialState = readInstallation(home);
134
- const configPath = resolve(values['antigravity-config'] ??
135
- initialState?.antigravityConfig ??
136
- defaultAntigravityConfig());
137
- const globalOptions = (runtime, projects) => ({
138
- configPath,
139
- installationHome: home,
140
- appRoot: runtime.appRoot,
141
- node: runtime.node,
142
- projects,
143
- });
144
- if (initialState?.antigravityConfig &&
145
- configPath !== resolve(initialState.antigravityConfig))
146
- throw new Error('This installation already manages another Antigravity config. Use its existing path: ' +
147
- initialState.antigravityConfig);
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);
148
106
  if (action === 'serve') {
149
107
  process.env.MEMORY_DB ??= join(paths.data, 'events.sqlite');
150
108
  await import('../../../apps/server/src/main.js');
@@ -163,10 +121,7 @@ async function main() {
163
121
  if (!state)
164
122
  problems.push('No persistent runtime installed. Run setup.');
165
123
  else {
166
- for (const file of [
167
- state.current.node,
168
- join(state.current.appRoot, 'apps/server/src/main.js'),
169
- ])
124
+ for (const file of [state.current.node, join(state.current.appRoot, 'apps/server/src/main.js')])
170
125
  if (!existsSync(file))
171
126
  problems.push('Missing runtime path: ' + file + '. Run setup again.');
172
127
  try {
@@ -178,8 +133,8 @@ async function main() {
178
133
  try {
179
134
  const globalPlan = planAntigravity(globalOptions(state.current, state.projects));
180
135
  const before = globalPlan.expected[basename(configPath)];
181
- const servers = before ? (JSON.parse(before).mcpServers ?? {}) : {};
182
- for (const project of state.projects.filter((p) => p.clients.includes('antigravity'))) {
136
+ const servers = before ? JSON.parse(before).mcpServers ?? {} : {};
137
+ for (const project of state.projects.filter(p => p.clients.includes('antigravity'))) {
183
138
  if (!servers[antigravityServerName(project.workspace)])
184
139
  problems.push('Missing Antigravity server: ' + project.workspace);
185
140
  }
@@ -195,8 +150,7 @@ async function main() {
195
150
  for (const [path, snapshot] of Object.entries(managed.files)) {
196
151
  const current = readFileSync(join(project.workspace, path), 'utf8');
197
152
  if (current !== snapshot.after)
198
- problems.push('Configuration changed; review before setup: ' +
199
- join(project.workspace, path));
153
+ problems.push('Configuration changed; review before setup: ' + join(project.workspace, path));
200
154
  }
201
155
  }
202
156
  catch {
@@ -204,26 +158,7 @@ async function main() {
204
158
  }
205
159
  }
206
160
  }
207
- const capture = (state?.projects ?? [])
208
- .filter((p) => p.captureNewSessions)
209
- .map((project) => {
210
- const observations = project.clients
211
- .flatMap((client) => readCaptureStatuses(join(dirname(project.database), 'queue', client === 'claude-code' ? 'claude' : client)))
212
- .filter((s) => s.session.repoId === project.repoId);
213
- return {
214
- workspace: project.workspace,
215
- captureObserved: observations.some((s) => s.lastCaptureAt !== null),
216
- startupObserved: observations.length > 0,
217
- sessions: observations,
218
- };
219
- });
220
- console.log(JSON.stringify({
221
- capture,
222
- status: problems.length ? 'attention_required' : 'configured',
223
- runtime: state?.current.version,
224
- problems,
225
- note: 'Configuration check only; agent login/trust and live handoff are not verified.',
226
- }, null, 2));
161
+ console.log(JSON.stringify({ status: problems.length ? 'attention_required' : 'configured', runtime: state?.current.version, problems, note: 'Configuration check only; agent login/trust and live handoff are not verified.' }, null, 2));
227
162
  if (problems.length)
228
163
  process.exitCode = 1;
229
164
  return;
@@ -232,37 +167,26 @@ async function main() {
232
167
  throw new Error('Unknown command: ' + action);
233
168
  let project;
234
169
  if (action === 'setup') {
235
- const directory = values.workspace ?? (await ask('Project folder: '));
236
- const selected = values.client ??
237
- (await ask('Agents (comma separated: ' + clients.join(', ') + '): '))
238
- .split(',')
239
- .map((v) => v.trim());
170
+ const directory = values.workspace ?? (plugin ? process.cwd() : await ask('Project folder: '));
240
171
  const { workspace, repoId } = resolveRepository(resolve(directory));
241
- project = {
242
- workspace,
243
- repoId,
244
- clients: selected,
245
- database: join(paths.data, 'events.sqlite'),
246
- ...(values['capture-new-sessions'] ? { captureNewSessions: true } : {}),
247
- };
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());
185
+ project = { workspace, repoId, clients: selected, database: join(paths.data, 'events.sqlite') };
248
186
  // Validate and show changes before installing dependencies or writing settings.
249
- const previousProject = readInstallation(home)?.projects.find((p) => p.workspace === workspace);
250
- if (previousProject)
251
- project.repoId = previousProject.repoId;
252
- const plan = planConnection({ ...project, appRoot });
187
+ const plan = planConnection({ ...project, appRoot, installationHome: home });
253
188
  preview(plan);
254
- const projects = [
255
- ...(initialState?.projects ?? []).filter((p) => p.workspace !== project.workspace),
256
- {
257
- ...project,
258
- clients: [
259
- ...new Set([
260
- ...(initialState?.projects.find((p) => p.workspace === project.workspace)?.clients ?? []),
261
- ...project.clients,
262
- ]),
263
- ],
264
- },
265
- ];
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])] }];
266
190
  preview(planAntigravity(globalOptions({ version, appRoot, node: process.execPath }, projects)), false);
267
191
  if (values.preview) {
268
192
  console.log('Preview only. No runtime or configuration installed.');
@@ -274,28 +198,20 @@ async function main() {
274
198
  if (!state)
275
199
  throw new Error('No installation found. Run setup first.');
276
200
  if (action === 'uninstall') {
277
- const target = values.workspace
278
- ? resolveRepository(resolve(values.workspace)).workspace
279
- : null;
201
+ const target = values.workspace ? resolveRepository(resolve(values.workspace)).workspace : null;
280
202
  if (!target)
281
203
  throw new Error('Pass --workspace to uninstall one project; memory data is always retained');
282
- if (!state.projects.some((p) => p.workspace === target))
204
+ if (!state.projects.some(p => p.workspace === target))
283
205
  throw new Error('Project is not managed by this installation');
284
206
  preview(planUninstall(target));
285
- preview(planAntigravity({
286
- ...globalOptions(state.current, state.projects.filter((p) => p.workspace !== target)),
287
- removeOnly: true,
288
- }), false);
207
+ preview(planAntigravity({ ...globalOptions(state.current, state.projects.filter(p => p.workspace !== target)), removeOnly: true }), false);
289
208
  }
290
209
  else
291
- console.log(action +
292
- ' runtime for ' +
293
- state.projects.length +
294
- ' project(s); user memory is retained.');
210
+ console.log(action + ' runtime for ' + state.projects.length + ' project(s); user memory is retained.');
295
211
  if (values.preview)
296
212
  return;
297
213
  }
298
- if (!(await confirm('Apply ' + action + '?', values.yes))) {
214
+ if (!await confirm('Apply ' + action + '?', values.yes || (plugin && !process.stdin.isTTY))) {
299
215
  console.log('Cancelled. No changes applied.');
300
216
  return;
301
217
  }
@@ -304,62 +220,31 @@ async function main() {
304
220
  if (action === 'uninstall') {
305
221
  const target = resolveRepository(resolve(values.workspace)).workspace;
306
222
  const plan = planUninstall(target);
307
- const remaining = state.projects.filter((p) => p.workspace !== target);
308
- await applyAll([
309
- plan,
310
- planAntigravity({
311
- ...globalOptions(state.current, remaining),
312
- removeOnly: true,
313
- }),
314
- ], () => atomicWrite(paths.state, JSON.stringify({ ...state, projects: remaining }, 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)));
315
225
  console.log('Project connectors removed where unchanged. User-edited settings and all memory retained. Runtime retained for other projects.');
316
226
  return;
317
227
  }
318
228
  if (project) {
319
- const existing = state?.projects.find((p) => p.workspace === project.workspace);
320
- if (existing) {
321
- project.repoId = existing.repoId;
322
- project.clients = [
323
- ...new Set([...existing.clients, ...project.clients]),
324
- ];
325
- if (existing.captureNewSessions)
326
- project.captureNewSessions = true;
327
- }
229
+ const existing = state?.projects.find(p => p.workspace === project.workspace);
230
+ if (existing)
231
+ project.clients = [...new Set([...existing.clients, ...project.clients])];
328
232
  }
329
- const projects = project
330
- ? [
331
- ...(state?.projects ?? []).filter((p) => p.workspace !== project.workspace),
332
- project,
333
- ]
334
- : state.projects;
233
+ const projects = project ? [...(state?.projects ?? []).filter(p => p.workspace !== project.workspace), project] : state.projects;
335
234
  if (action !== 'rollback' && metadata.private && !values.package)
336
235
  throw new Error('This package is unpublished. Pass --package /absolute/path/to/the-built.tgz; registry installation is disabled until release.');
337
- const runtime = action === 'rollback'
338
- ? state?.previous
339
- : installRuntime(home, values.package ??
340
- packageName +
341
- '@' +
342
- (action === 'update'
343
- ? version.includes('-')
344
- ? 'next'
345
- : 'latest'
346
- : version));
236
+ const runtime = action === 'rollback' ? state?.previous : installRuntime(home, values.package ?? packageName + '@' + (action === 'update' ? (metadata.publishConfig?.tag ?? 'latest') : version));
347
237
  if (!runtime)
348
238
  throw new Error('No previous runtime available');
349
- assertRuntimeCompatibility(runtime, projects);
350
- const plans = plansFor(runtime, projects);
239
+ const plans = plansFor(runtime, projects, home);
351
240
  plans.push(planAntigravity(globalOptions(runtime, projects)));
352
- await applyAll(plans, () => activateRuntime(home, runtime, projects, projects.some((p) => p.clients.includes('antigravity'))
353
- ? configPath
354
- : state?.antigravityConfig), () => verifyAntigravity(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)));
355
242
  console.log('Installed runtime ' + runtime.version + '. Data: ' + paths.data);
356
- console.log('Restart connected agents and review MCP/hook trust prompts. ' +
357
- (existsSync(join(runtime.appRoot, 'skills/knit/SKILL.md')) ? 'Use /continue-chat for projects with --capture-new-sessions; use /knit for other projects.' : 'Use /continue-chat with this runtime.'));
358
- if (projects.some((p) => p.clients.includes('antigravity')))
359
- console.log('Antigravity: project memory servers registered in ' +
360
- configPath +
361
- ' and tool connections verified. Restart Antigravity and open a fresh project chat.');
362
- if (projects.some((p) => p.clients.includes('claude-desktop')))
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.');
247
+ if (projects.some(p => p.clients.includes('claude-desktop')))
363
248
  console.log('Claude Desktop: merge the generated project .memory/connectors/claude-desktop.json fragment into Desktop MCP settings, then restart.');
364
249
  });
365
250
  }
@@ -0,0 +1,199 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { hostname, tmpdir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs';
5
+ import { spawn } from 'node:child_process';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { createInterface } from 'node:readline/promises';
8
+ import { setTimeout as sleep } from 'node:timers/promises';
9
+ import { z } from 'zod';
10
+ import { api, CloudError, credentials, credentialsPath, defaultServer, request, serverOrigin } from '../../cloud/src/client.js';
11
+ import { defaultHome, runtimePaths, withInstallLock } from './runtime.js';
12
+ import { atomicWrite } from './connections.js';
13
+ import { defaultHistoryRoots, discoverHistories } from '../../adapters/src/histories.js';
14
+ import { importConversation } from '../../adapters/src/handoff.js';
15
+ import { MemoryStore } from '../../memory/src/store.js';
16
+ const print = (value) => console.log(JSON.stringify(value, null, 2));
17
+ async function prompt(question) {
18
+ if (!process.stdin.isTTY)
19
+ throw new Error('Use the cloud publish subcommands and explicit flags for noninteractive review. See knitt cloud --help.');
20
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
21
+ try {
22
+ return (await reader.question(question + ' ')).trim();
23
+ }
24
+ finally {
25
+ reader.close();
26
+ }
27
+ }
28
+ async function login(home, origin, name, open) {
29
+ if (credentials(home))
30
+ throw new Error('This installation is paired. Run knitt cloud logout before pairing again.');
31
+ const pairing = await request(origin, '/api/device-pairings', { body: { name } });
32
+ const verification = new URL(pairing.verificationUri, origin);
33
+ if (verification.origin !== origin)
34
+ throw new Error('Pairing approval must use the selected Knitt Cloud origin');
35
+ console.log(`Approve installation ${name} with code ${pairing.userCode} at ${verification.href}`);
36
+ if (open) {
37
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32.exe' : 'xdg-open';
38
+ const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', verification.href] : [verification.href];
39
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
40
+ child.on('error', () => console.error('Open the approval link above in your browser.'));
41
+ child.unref();
42
+ }
43
+ while (Date.now() < Date.parse(pairing.expiresAt)) {
44
+ const result = await request(origin, '/api/device-pairings/exchange', { body: { pairingId: pairing.pairingId, deviceCode: pairing.deviceCode } });
45
+ if (result.status !== 'pending') {
46
+ if (!result.token || !result.account?.id || !result.device?.id)
47
+ throw new Error('Incomplete pairing response');
48
+ atomicWrite(credentialsPath(home), JSON.stringify({ origin, token: result.token, account: result.account, device: result.device }));
49
+ console.log(`Paired ${result.device.name} with ${result.account.email}.`);
50
+ return;
51
+ }
52
+ await sleep(Math.max(1, pairing.interval) * 1000);
53
+ }
54
+ throw new Error('Pairing expired. Run knitt cloud login again.');
55
+ }
56
+ const draftSchema = z.object({
57
+ title: z.string().trim().min(1), creationKey: z.string().min(1), publicationKey: z.string().min(1), contextId: z.string().min(1).optional(),
58
+ sourceVersionId: z.string().min(1).optional(), accountId: z.string().optional(), origin: z.string().optional(),
59
+ checkpoint: z.string().trim().min(1), source: z.object({ agent: z.enum(['codex', 'claude', 'antigravity']), conversationId: z.string().min(1), repository: z.string().optional(), branch: z.string().optional(), commit: z.string().optional() }).strict(),
60
+ excerpts: z.array(z.object({ text: z.string().min(1) }).strict()),
61
+ }).strict();
62
+ function userPreview(draft) {
63
+ const { title, contextId, sourceVersionId, checkpoint, source, excerpts } = draft;
64
+ return { title, contextId, sourceVersionId, checkpoint, source, excerpts, ...(sourceVersionId ? { originalWork: true } : {}) };
65
+ }
66
+ function transcriptExcerpts(conversation) {
67
+ const scratch = mkdtempSync(join(tmpdir(), 'knitt-review-'));
68
+ const store = new MemoryStore(':memory:');
69
+ try {
70
+ const repoId = 'review';
71
+ const { featureId } = importConversation({ conversation, repoId, directory: scratch, store });
72
+ const excerpts = [];
73
+ let before;
74
+ do {
75
+ const page = store.search({ repoId, featureId, before, limit: 20 });
76
+ for (const match of page.matches)
77
+ excerpts.push({ id: match.eventId, text: store.evidence(repoId, match.eventId).content });
78
+ before = page.nextCursor ?? undefined;
79
+ } while (before);
80
+ return excerpts.reverse();
81
+ }
82
+ finally {
83
+ store.close();
84
+ rmSync(scratch, { recursive: true, force: true });
85
+ }
86
+ }
87
+ async function submit(home, path, yes) {
88
+ const draft = draftSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
89
+ const device = credentials(home);
90
+ if (!device)
91
+ throw new Error('Pair this installation with knitt cloud login before submitting.');
92
+ if ((draft.accountId && draft.accountId !== device.account.id) || (draft.origin && draft.origin !== device.origin))
93
+ throw new Error('This draft belongs to another account or server');
94
+ print(userPreview(draft));
95
+ if (draft.sourceVersionId)
96
+ console.log('Only your original work may be published. Confirm that the checkpoint and excerpts contain your own material.');
97
+ if (!yes && (await prompt('Publish this exact material to ' + device.account.email + '? Type publish to confirm.')) !== 'publish') {
98
+ console.log('Cancelled.');
99
+ return;
100
+ }
101
+ draft.accountId = device.account.id;
102
+ draft.origin = device.origin;
103
+ atomicWrite(path, JSON.stringify(draft, null, 2));
104
+ if (!draft.contextId) {
105
+ const { context } = await api(device, '/api/contexts', { title: draft.title, creationKey: draft.creationKey, sourceVersionId: draft.sourceVersionId });
106
+ draft.contextId = context.id;
107
+ atomicWrite(path, JSON.stringify(draft, null, 2));
108
+ }
109
+ const { version } = await api(device, `/api/contexts/${encodeURIComponent(draft.contextId)}/versions`, { publicationKey: draft.publicationKey, checkpoint: draft.checkpoint, source: draft.source, excerpts: draft.excerpts, ...(draft.sourceVersionId ? { originalWork: true } : {}) });
110
+ console.log(`Published v${version.number} (${version.id}) in context ${draft.contextId}.`);
111
+ }
112
+ const help = `knitt cloud login [--server ORIGIN] [--name DEVICE] [--no-browser]\nknitt cloud logout\nknitt cloud publish [--workspace PATH] Interactive review\nknitt cloud publish list [--workspace PATH] Available local conversations\nknitt cloud publish excerpts --source AGENT:ID Local excerpt IDs and text\nknitt cloud publish prepare --source AGENT:ID --checkpoint TEXT --draft FILE [--excerpt ID ...]\nknitt cloud publish show --draft FILE Review edited JSON locally\nknitt cloud publish submit --draft FILE [--yes] Publish exactly the reviewed material\nOptional publication flags: --title TITLE --context ID --repository REPO --branch BRANCH --commit HASH\nUse --home PATH to select the Knitt installation. --yes confirms publication of only your original work.`;
113
+ export async function runCloud(args) {
114
+ const { positionals, values: v } = parseArgs({ args, allowPositionals: true, options: {
115
+ home: { type: 'string' }, server: { type: 'string' }, name: { type: 'string' }, 'no-browser': { type: 'boolean' }, workspace: { type: 'string' }, source: { type: 'string' }, checkpoint: { type: 'string' }, excerpt: { type: 'string', multiple: true }, draft: { type: 'string' }, title: { type: 'string' }, context: { type: 'string' }, repository: { type: 'string' }, branch: { type: 'string' }, commit: { type: 'string' }, yes: { type: 'boolean' }, help: { type: 'boolean' },
116
+ } });
117
+ const [action, step] = positionals;
118
+ const home = resolve(v.home ?? defaultHome());
119
+ if (!action || v.help) {
120
+ console.log(help);
121
+ return;
122
+ }
123
+ if (action === 'login')
124
+ return withInstallLock(home, () => login(home, serverOrigin(v.server ?? defaultServer), v.name ?? hostname(), !v['no-browser']));
125
+ if (action === 'logout')
126
+ return withInstallLock(home, async () => {
127
+ const device = credentials(home);
128
+ if (!device) {
129
+ console.log('Signed out.');
130
+ return;
131
+ }
132
+ try {
133
+ await request(device.origin, '/api/devices/current', { method: 'DELETE', token: device.token });
134
+ }
135
+ catch (err) {
136
+ if (!(err instanceof CloudError && err.status === 401))
137
+ throw err;
138
+ }
139
+ rmSync(credentialsPath(home));
140
+ console.log('Signed out.');
141
+ });
142
+ if (action !== 'publish' || (step && !['list', 'excerpts', 'prepare', 'show', 'submit'].includes(step)))
143
+ throw new Error(help);
144
+ if (step === 'show' || step === 'submit') {
145
+ if (!v.draft)
146
+ throw new Error('Pass --draft FILE');
147
+ if (step === 'show')
148
+ return print(userPreview(draftSchema.parse(JSON.parse(readFileSync(v.draft, 'utf8')))));
149
+ return submit(home, resolve(v.draft), !!v.yes);
150
+ }
151
+ const workspace = resolve(v.workspace ?? process.cwd());
152
+ const chats = discoverHistories({ roots: defaultHistoryRoots(), workspace });
153
+ const choices = chats.map(c => ({ source: (c.client ?? 'antigravity') + ':' + c.id, title: c.title, modified: c.modified }));
154
+ if (step === 'list')
155
+ return print(choices);
156
+ if (!choices.length)
157
+ throw new Error('No local conversations were found for this workspace.');
158
+ if (!v.source) {
159
+ if (step)
160
+ throw new Error('Choose --source AGENT:ID from knitt cloud publish list');
161
+ choices.forEach((c, i) => console.log(`${i + 1}. ${c.title} (${c.source})`));
162
+ v.source = choices[Number(await prompt('Choose a conversation number.')) - 1]?.source;
163
+ }
164
+ const index = choices.findIndex(c => c.source === v.source);
165
+ if (index < 0)
166
+ throw new Error('Choose a conversation listed for this workspace.');
167
+ const chat = chats[index];
168
+ const db = process.env.MEMORY_DB ?? join(runtimePaths(home).data, 'events.sqlite');
169
+ const store = existsSync(db) ? new MemoryStore(db) : null;
170
+ let provenance;
171
+ try {
172
+ provenance = store?.lastCloudSource(chat.id, chat.client ?? 'antigravity');
173
+ }
174
+ finally {
175
+ store?.close();
176
+ }
177
+ // Recipient transcripts can contain previously loaded source text. Only
178
+ // individually saved new-work events can be selected for an onward handoff.
179
+ const excerpts = provenance ? provenance.work : transcriptExcerpts(chat);
180
+ if (step === 'excerpts')
181
+ return print(excerpts);
182
+ if (!step && !v.excerpt) {
183
+ excerpts.forEach((e, i) => console.log(`${i + 1}. ${JSON.stringify(e.text)}`));
184
+ const selected = await prompt('Include excerpts by number, separated by commas (Enter for none).');
185
+ v.excerpt = selected ? selected.split(',').map(n => excerpts[Number(n.trim()) - 1]?.id ?? 'unknown') : [];
186
+ }
187
+ const selected = [...new Set(v.excerpt ?? [])].map(id => { const e = excerpts.find(e => e.id === id); if (!e)
188
+ throw new Error('Unknown excerpt ID'); return { text: e.text }; });
189
+ const checkpoint = v.checkpoint ?? await prompt('Write your checkpoint (goal, decisions, progress, verification, blockers and next steps).');
190
+ const draft = draftSchema.parse({ title: v.title ?? chat.title, creationKey: randomUUID(), publicationKey: randomUUID(), contextId: v.context,
191
+ checkpoint, source: { agent: chat.client ?? 'antigravity', conversationId: chat.id, repository: v.repository, branch: v.branch, commit: v.commit }, excerpts: selected,
192
+ ...(provenance ? { sourceVersionId: provenance.versionId, origin: provenance.origin, accountId: provenance.accountId } : {}) });
193
+ const path = resolve(v.draft ?? join(home, 'cloud', 'drafts', draft.publicationKey + '.json'));
194
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
195
+ writeFileSync(path, JSON.stringify(draft, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
196
+ console.log('Saved local draft ' + path + '. Edit it and use knitt cloud publish show or submit --draft FILE.');
197
+ if (!step)
198
+ await submit(home, path, !!v.yes);
199
+ }