@phyzess/kitto 0.2.1 → 0.3.0

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/lib/kitto.mjs CHANGED
@@ -1,22 +1,31 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { existsSync, realpathSync } from 'node:fs';
3
+ import { existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
4
4
  import { cp, mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile, lstat, readlink, realpath } from 'node:fs/promises';
5
- import { homedir } from 'node:os';
5
+ import { homedir, tmpdir } from 'node:os';
6
6
  import { basename, dirname, join, resolve } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { applyInstructions, hostSkillRoots, instructionPlan } from './host-config.mjs';
9
9
  import { dependencyPlan, installDependencies } from './dependencies.mjs';
10
+ import { reportCodeGraphIndexes } from './codegraph.mjs';
11
+ import { applyCodexMcp, planCodexMcp, removeCodexMcp, sourceServers as codexMcpSource } from './codex-mcp.mjs';
12
+ import { printMcpParity } from './parity.mjs';
13
+ import { removeDshMcp, syncDshMcp } from './mcp-sync.mjs';
14
+ import { desktopProfileNotice, isDesktopProfile, probeDesktopProfile, reportDesktopProbe, validateDshProfile } from './dsh-profile.mjs';
10
15
  import { versionReport } from './versions.mjs';
11
16
 
12
17
  export const packageRoot = fileURLToPath(new URL('../', import.meta.url));
13
18
  export const hosts = {
14
19
  pi: { package: '@earendil-works/pi-coding-agent', version: '1.5.2', node: '22.19.0' },
15
20
  codex: { package: '@openai/codex', version: '0.170.0' },
16
- dsh: { package: '@deepseek-ai/dsh', version: '0.2.2-rc.1', node: '24.9.0' },
21
+ dsh: { package: '@deepseek-ai/dsh', version: '0.2.2-rc.2', node: '24.9.0' },
17
22
  };
18
23
  export const pnpmVersion = '12.21.0'; // Required by the native DSH plugin manager.
19
24
  const defaultSource = 'https://github.com/phyzess/kitto.git';
25
+ // Only clone sources Kitto may persist and replay; credentials in a URL are
26
+ // hidden from every message while the state keeps what it needs to clone.
27
+ const isGitUrl = value => typeof value === 'string' && /^(https:\/\/|ssh:\/\/|git@)/.test(value);
28
+ const redactUrl = value => String(value).replace(/\/\/[^/@\s]+@/g, '//***@');
20
29
  export const kittoHome = () => {
21
30
  // Native hosts do not need to inherit the shell used during setup.
22
31
  const installedHome = dirname(resolve(packageRoot));
@@ -26,6 +35,23 @@ export const kittoHome = () => {
26
35
  const json = async path => JSON.parse(await readFile(path, 'utf8'));
27
36
  const shellQuote = value => `'${value.replaceAll("'", "'\\''")}'`;
28
37
  const present = async path => { try { await lstat(path); return true; } catch (e) { if (e.code === 'ENOENT') return false; throw e; } };
38
+
39
+ /** Replace a skill directory without leaving a half-copied tree behind. */
40
+ export async function replaceDirectory(source, target) {
41
+ const temporary = `${target}.kitto-tmp-${process.pid}`;
42
+ const backup = `${target}.kitto-old-${process.pid}`;
43
+ await rm(temporary, { recursive: true, force: true });
44
+ await cp(source, temporary, { recursive: true });
45
+ const existed = await present(target);
46
+ if (existed) await rename(target, backup);
47
+ try {
48
+ await rename(temporary, target);
49
+ } catch (error) {
50
+ if (existed) await rename(backup, target);
51
+ throw error;
52
+ }
53
+ if (existed) await rm(backup, { recursive: true, force: true });
54
+ }
29
55
  function sameLocation(a, b) {
30
56
  if (typeof a !== 'string' || typeof b !== 'string') return false;
31
57
  const canonical = path => {
@@ -43,13 +69,13 @@ function run(command, args, { capture = false, ...options } = {}) {
43
69
  return result.stdout?.trim() || '';
44
70
  }
45
71
  const git = (source, args) => run('git', ['-C', source, ...args], { capture: true, timeout: 30_000 });
46
- const available = name => spawnSync(name, ['--version'], { stdio: 'ignore', timeout: 8000 }).status === 0;
72
+ const available = (name, env = process.env) => spawnSync(name, ['--version'], { stdio: 'ignore', timeout: 8000, env }).status === 0;
47
73
 
48
74
  export function parseOptions(args) {
49
75
  const options = {};
50
76
  for (let i = 0; i < args.length; i++) {
51
77
  const arg = args[i];
52
- if (['--dry-run', '--install-agents', '--recover', '--global'].includes(arg)) options[arg.slice(2)] = true;
78
+ if (['--dry-run', '--install-agents', '--recover', '--global', '--include-private', '--no-include-private'].includes(arg)) options[arg.slice(2)] = true;
53
79
  else if (['--agents', '--source', '--ref', '--dsh-profile', '--workspace', '--workspace-parent', '--dsh-service'].includes(arg) && args[i + 1] && !args[i + 1].startsWith('-')) options[arg.slice(2)] = args[++i];
54
80
  else throw new Error(`Unknown option or missing value: ${arg}`);
55
81
  }
@@ -57,6 +83,7 @@ export function parseOptions(args) {
57
83
  options.agents = [...new Set(options.agents.split(','))];
58
84
  if (options.agents.some(name => !hosts[name])) throw new Error('Agents must be pi,codex,dsh.');
59
85
  }
86
+ if (options['include-private'] && options['no-include-private']) throw new Error('Choose either --include-private or --no-include-private.');
60
87
  if (options.recover && Object.keys(options).some(key => !['recover', 'dry-run'].includes(key))) throw new Error('--recover only accepts --dry-run; it uses the saved installation.');
61
88
  return options;
62
89
  }
@@ -82,6 +109,13 @@ async function locked(home, callback) {
82
109
 
83
110
  async function validateSource({ source, agents }) {
84
111
  if (git(source, ['rev-parse', '--show-toplevel']) !== await realpath(source)) throw new Error('Source must be the root of a Git checkout.');
112
+ if (agents.includes('codex')) {
113
+ try {
114
+ await codexMcpSource(source);
115
+ } catch (error) {
116
+ throw new Error(`Codex MCP sync requires a readable Pi MCP source: ${error.message}`);
117
+ }
118
+ }
85
119
  if (!agents.includes('pi')) return;
86
120
  const settings = await json(join(source, 'config/pi/settings.json'));
87
121
  if (!Array.isArray(settings.packages)) throw new Error('Source lacks config/pi/settings.json packages.');
@@ -89,23 +123,80 @@ async function validateSource({ source, agents }) {
89
123
  await readFile(join(source, 'config/pi/AGENTS.md'));
90
124
  }
91
125
 
126
+ /**
127
+ * Whether an installed host version reaches a validated baseline. Prerelease
128
+ * identifiers matter here: DSH ships rc builds, and 0.2.2-rc.1 is older than
129
+ * 0.2.2-rc.2 even though the numeric triplet is equal.
130
+ */
131
+ export function meetsBaseline(actual, baseline) {
132
+ const parse = value => {
133
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(value).trim());
134
+ if (!match) return null;
135
+ return {
136
+ numbers: [Number(match[1]), Number(match[2]), Number(match[3])],
137
+ prerelease: match[4] ? match[4].split('.') : [],
138
+ };
139
+ };
140
+ const installed = parse(actual), expected = parse(baseline);
141
+ if (!installed || !expected) return false;
142
+ for (let index = 0; index < 3; index++) {
143
+ if (installed.numbers[index] !== expected.numbers[index]) {
144
+ return installed.numbers[index] > expected.numbers[index];
145
+ }
146
+ }
147
+ // A release outranks any prerelease of the same triplet.
148
+ if (!installed.prerelease.length) return true;
149
+ if (!expected.prerelease.length) return false;
150
+ for (let index = 0; index < Math.max(installed.prerelease.length, expected.prerelease.length); index++) {
151
+ const left = installed.prerelease[index], right = expected.prerelease[index];
152
+ if (left === undefined) return false;
153
+ if (right === undefined) return true;
154
+ const leftNumeric = /^\d+$/.test(left), rightNumeric = /^\d+$/.test(right);
155
+ if (leftNumeric && rightNumeric) {
156
+ if (Number(left) !== Number(right)) return Number(left) > Number(right);
157
+ } else if (leftNumeric !== rightNumeric) {
158
+ return !leftNumeric;
159
+ } else if (left !== right) {
160
+ return left > right;
161
+ }
162
+ }
163
+ return true;
164
+ }
165
+
92
166
  function checkHost(name) {
93
- const version = run(name, ['--version'], { capture: true, timeout: 8000 });
94
- const actual = version.match(/\d+\.\d+\.\d+(?:-[\w.]+)?/)?.[0];
95
- const expected = hosts[name].version;
96
- const numbers = value => value.split(/[.-]/).slice(0, 3).map(Number);
97
- const a = actual && numbers(actual), b = numbers(expected);
98
- if (!a || a[0] < b[0] || (a[0] === b[0] && (a[1] < b[1] || (a[1] === b[1] && a[2] < b[2])))) {
99
- throw new Error(`${name}: found ${version}; validated baseline is ${expected}. Upgrade with its native manager first.`);
167
+ // Codex creates helper files under CODEX_HOME even for --version/--help.
168
+ // Probe with a scratch home so checks never write the user's Codex state.
169
+ const probe = name === 'codex' ? mkdtempSync(join(tmpdir(), 'kitto-codex-check-')) : null;
170
+ const env = probe ? { ...process.env, CODEX_HOME: probe } : process.env;
171
+ try {
172
+ const version = run(name, ['--version'], { capture: true, timeout: 8000, env });
173
+ const actual = version.match(/\d+\.\d+\.\d+(?:-[\w.]+)?/)?.[0];
174
+ const expected = hosts[name].version;
175
+ if (!actual || !meetsBaseline(actual, expected)) {
176
+ throw new Error(`${name}: found ${version}; validated baseline is ${expected}. Upgrade with its native manager first.`);
177
+ }
178
+ if (name === 'codex') {
179
+ run(name, ['plugin', 'add', '--help'], { capture: true, timeout: 8000, env });
180
+ run(name, ['mcp', '--help'], { capture: true, timeout: 8000, env });
181
+ }
182
+ if (name === 'dsh') run(name, ['plugin', '--help'], { capture: true, timeout: 8000 });
183
+ console.log(`${name}: ${actual} (tested baseline ${expected})`);
184
+ } finally {
185
+ if (probe) rmSync(probe, { recursive: true, force: true });
100
186
  }
101
- if (name === 'codex') run(name, ['plugin', 'add', '--help'], { capture: true, timeout: 8000 });
102
- if (name === 'dsh') run(name, ['plugin', '--help'], { capture: true, timeout: 8000 });
103
- console.log(`${name}: ${actual} (tested baseline ${expected})`);
187
+ }
188
+
189
+ function availableHost(name) {
190
+ if (name !== 'codex') return available(name);
191
+ // Codex creates helper files under CODEX_HOME even for --version.
192
+ const probe = mkdtempSync(join(tmpdir(), 'kitto-codex-check-'));
193
+ try { return available(name, { ...process.env, CODEX_HOME: probe }); }
194
+ finally { rmSync(probe, { recursive: true, force: true }); }
104
195
  }
105
196
 
106
197
  export function checkSelectedHosts(agents, installAgents) {
107
198
  for (const name of agents) {
108
- if (!available(name)) {
199
+ if (!availableHost(name)) {
109
200
  if (!installAgents) throw new Error(`${name} is missing. Install it natively or add --install-agents (pins ${hosts[name].version}).`);
110
201
  const requiredNode = hosts[name].node;
111
202
  if (requiredNode && requiredNode.localeCompare(process.versions.node, 'en', { numeric: true }) > 0) {
@@ -117,7 +208,7 @@ export function checkSelectedHosts(agents, installAgents) {
117
208
  }
118
209
 
119
210
  export function installMissingHosts(agents) {
120
- for (const name of agents) if (!available(name)) {
211
+ for (const name of agents) if (!availableHost(name)) {
121
212
  run('npm', ['install', '--global', `${hosts[name].package}@${hosts[name].version}`]);
122
213
  checkHost(name);
123
214
  }
@@ -141,7 +232,7 @@ async function installRuntime(home, old) {
141
232
  const next = join(home, 'runtime.next');
142
233
  const runtime = join(home, 'runtime');
143
234
  const previous = join(home, 'runtime.previous');
144
- if (resolve(packageRoot) === runtime) return runtime;
235
+ if (sameLocation(packageRoot, runtime)) return runtime;
145
236
  await rm(next, { recursive: true, force: true });
146
237
  await mkdir(next);
147
238
  for (const name of ['package.json', 'bin', 'lib', 'integration', 'sync.sh', 'CHANGELOG.md']) {
@@ -255,7 +346,8 @@ function syncCommand(state, command, apply = false, codeRoot = join(kittoHome(),
255
346
 
256
347
  async function connect(state) {
257
348
  const home = kittoHome(), runtime = join(home, 'runtime');
258
- if (state.agents.includes('dsh') && !available('pnpm')) throw new Error('DSH native plugin operations require pnpm on PATH. Run setup --install-agents to install the missing prerequisite.');
349
+ const desktopDsh = state.agents.includes('dsh') && isDesktopProfile(state.dshProfile);
350
+ if (state.agents.includes('dsh') && !desktopDsh && !available('pnpm')) throw new Error('DSH native plugin operations require pnpm on PATH. Run setup --install-agents to install the missing prerequisite.');
259
351
  for (const name of state.agents) {
260
352
  if (name === 'pi') run('pi', ['install', runtime], { env: { ...process.env, PI_CODING_AGENT_DIR: state.piHome } });
261
353
  if (name === 'codex') {
@@ -269,6 +361,10 @@ async function connect(state) {
269
361
  run('codex', ['plugin', 'add', 'kitto@phyzess-kitto'], { env });
270
362
  }
271
363
  if (name === 'dsh') {
364
+ if (isDesktopProfile(state.dshProfile)) {
365
+ console.log('DSH desktop profile: app-managed; skipped Kitto bundle registration (global rules and skills only).');
366
+ continue;
367
+ }
272
368
  await mkdir(state.dshHome, { recursive: true });
273
369
  run('dsh', ['plugin', '--profile', state.dshProfile || 'web', 'add', runtime], {
274
370
  env: { ...process.env, DSH_HOME: state.dshHome, DSH_AGENTS_HOME: state.agentsHome },
@@ -287,15 +383,18 @@ async function configurationPlan(state) {
287
383
  }
288
384
  const instructions = await instructionPlan(state);
289
385
  for (const plan of instructions) console.log(`instructions ${plan.before === plan.after ? 'same' : 'sync'}: ${plan.target}`);
290
- return { groups, instructions };
386
+ const mcp = state.agents.includes('codex') ? await planCodexMcp(state) : undefined;
387
+ return { groups, instructions, mcp };
291
388
  }
292
389
 
293
390
  async function deploy(state, apply, plan = undefined, codeRoot = undefined) {
294
391
  const { groups, instructions } = plan ?? await configurationPlan(state);
295
392
  const deployment = apply ? sourceRevision(state.source) : undefined;
393
+ const connectable = state.agents.filter(name => !(name === 'dsh' && isDesktopProfile(state.dshProfile)));
296
394
  if (state.agents.includes('pi')) syncCommand(state, 'pull', apply, codeRoot);
395
+ if (state.agents.includes('dsh') && !isDesktopProfile(state.dshProfile)) await syncDshMcp(state, { dryRun: !apply });
297
396
  if (!apply) {
298
- if (!state.ready) console.log(`Connect native Kitto integrations: ${state.agents.join(', ')}`);
397
+ if (!state.ready && connectable.length) console.log(`Connect native Kitto integrations: ${connectable.join(', ')}`);
299
398
  return;
300
399
  }
301
400
  await applyInstructions(state, instructions);
@@ -304,9 +403,11 @@ async function deploy(state, apply, plan = undefined, codeRoot = undefined) {
304
403
  const owned = {};
305
404
  const kept = [];
306
405
  for (const plan of plans) {
307
- if (['copy', 'remove'].includes(plan.action)) {
308
- await rm(plan.target, { recursive: true, force: true });
309
- if (plan.action === 'copy') await cp(plan.source, plan.target, { recursive: true });
406
+ if (plan.action === 'copy') await replaceDirectory(plan.source, plan.target);
407
+ else if (plan.action === 'remove') {
408
+ const trash = `${plan.target}.kitto-remove-${process.pid}`;
409
+ await rename(plan.target, trash);
410
+ await rm(trash, { recursive: true, force: true });
310
411
  }
311
412
  if (plan.action === 'keep') kept.push(plan.name);
312
413
  else if (plan.action !== 'remove') owned[plan.name] = plan.hash;
@@ -320,6 +421,9 @@ async function deploy(state, apply, plan = undefined, codeRoot = undefined) {
320
421
  }
321
422
  // Save deployment ownership before native managers, so retry is recoverable.
322
423
  await atomicJson(join(kittoHome(), 'state.json'), state);
424
+ if (state.agents.includes('codex')) {
425
+ await applyCodexMcp(state, { save: () => atomicJson(join(kittoHome(), 'state.json'), state) });
426
+ }
323
427
  if (!state.ready) {
324
428
  await connect(state);
325
429
  state.runtimeHash = await treeHash(join(kittoHome(), 'runtime'), true);
@@ -338,7 +442,7 @@ async function recover(state, apply) {
338
442
  throw new Error('The runtime checkpoint was verified with a different DSH profile.');
339
443
  }
340
444
  if (await treeHash(previous, true) !== checkpoint.hash) throw new Error('The runtime checkpoint was modified. Preserved; use a known working package version instead.');
341
- console.log(`Restore Kitto code ${state.version} -> ${checkpoint.version}; reconnect ${state.agents.join(', ')}. Personal configuration and skills stay as deployed.`);
445
+ console.log(`Restore Kitto code ${state.pendingRuntime?.version || state.version} -> ${checkpoint.version}; reconnect ${state.agents.join(', ')}. Personal configuration and skills stay as deployed.`);
342
446
  if (!apply) return;
343
447
  state.ready = false;
344
448
  await atomicJson(join(home, 'state.json'), state);
@@ -349,6 +453,7 @@ async function recover(state, apply) {
349
453
  await replaceRuntime(home, next);
350
454
  }
351
455
  state.version = checkpoint.version;
456
+ delete state.pendingRuntime;
352
457
  await atomicJson(join(home, 'state.json'), state);
353
458
  await connect(state);
354
459
  state.runtimeHash = checkpoint.hash;
@@ -356,7 +461,7 @@ async function recover(state, apply) {
356
461
  await atomicJson(join(home, 'state.json'), state);
357
462
  }
358
463
 
359
- async function removeIntegration(state, name, apply) {
464
+ async function removeIntegration(state, name, apply, announce = true) {
360
465
  const home = kittoHome(), runtime = join(home, 'runtime');
361
466
  if (name === 'pi') {
362
467
  const settings = join(state.piHome, 'settings.json');
@@ -386,9 +491,19 @@ async function removeIntegration(state, name, apply) {
386
491
  if (plugin && (plugin.source?.source !== 'local' || !sameLocation(plugin.source.path, join(runtime, 'integration')))) {
387
492
  throw new Error('The Codex Kitto plugin now comes from another source. Preserved.');
388
493
  }
494
+ await removeCodexMcp(state, {
495
+ apply, env,
496
+ save: () => atomicJson(join(home, 'state.json'), state),
497
+ ...(announce ? {} : { log: () => {}, warn: () => {} }),
498
+ });
389
499
  if (apply && plugin) run('codex', ['plugin', 'remove', 'kitto@phyzess-kitto'], { env });
390
500
  if (apply && market) run('codex', ['plugin', 'marketplace', 'remove', 'phyzess-kitto'], { env });
391
501
  } else if (name === 'dsh') {
502
+ if (isDesktopProfile(state.dshProfile)) {
503
+ if (announce) console.log('DSH desktop profile is app-managed; Kitto never installed a bundle, patch or MCP home row for it, so no native removal is needed.');
504
+ return;
505
+ }
506
+ await removeDshMcp(state, { dryRun: !apply, ...(announce ? {} : { log: () => {}, warn: () => {} }) });
392
507
  const manifest = join(state.dshHome, 'profiles', state.dshProfile || 'web', 'package.json');
393
508
  if (!await present(manifest)) return;
394
509
  const profile = await json(manifest), dependency = profile.dependencies?.['@phyzess/kitto'];
@@ -404,7 +519,8 @@ async function remove(state, apply) {
404
519
  console.log(`Detach Kitto from ${state.agents.join(', ')}. Keep configuration, shared skills, agent CLIs and Kitto files for recovery/reinstallation.`);
405
520
  // Inspect every remaining host before making any change.
406
521
  const remaining = state.agents.filter(name => !(state.removedAgents || []).includes(name));
407
- for (const name of remaining) await removeIntegration(state, name, false);
522
+ // Keep the preflight quiet when the same removal will report its real work below.
523
+ for (const name of remaining) await removeIntegration(state, name, false, !apply);
408
524
  if (!apply) return;
409
525
  const path = join(kittoHome(), 'state.json');
410
526
  state.ready = false; state.removing = true;
@@ -418,6 +534,231 @@ async function remove(state, apply) {
418
534
  await atomicJson(path, state);
419
535
  }
420
536
 
537
+ // Kitto updates its own code copy, never a host CLI. Print both versions so the
538
+ // user knows what to upgrade with the host's native manager, without failing.
539
+ function hostCliVersions(state) {
540
+ console.log('Host CLIs (Kitto never upgrades them; use each native manager):');
541
+ for (const name of state.agents) {
542
+ const baseline = hosts[name].version;
543
+ if (name === 'dsh' && isDesktopProfile(state.dshProfile)) {
544
+ console.log(` dsh: app-managed (Kitto tested baseline ${baseline}); upgrade through DeepSeek Harness Desktop`);
545
+ continue;
546
+ }
547
+ // Codex creates helper files under CODEX_HOME even for --version.
548
+ const probe = name === 'codex' ? mkdtempSync(join(tmpdir(), 'kitto-codex-check-')) : null;
549
+ try {
550
+ const output = run(name, ['--version'], { capture: true, timeout: 8000, env: probe ? { ...process.env, CODEX_HOME: probe } : process.env });
551
+ const actual = output.match(/\d+\.\d+\.\d+(?:-[\w.]+)?/)?.[0] || output.split('\n')[0];
552
+ console.log(` ${name}: ${actual} (Kitto tested baseline ${baseline}); upgrade with its native manager (${hosts[name].package})`);
553
+ } catch {
554
+ console.log(` ${name}: not found (Kitto tested baseline ${baseline}); install ${hosts[name].package} with its native manager`);
555
+ } finally {
556
+ if (probe) rmSync(probe, { recursive: true, force: true });
557
+ }
558
+ }
559
+ }
560
+
561
+ async function refreshRuntime(state, apply) {
562
+ const home = kittoHome(), runtime = join(home, 'runtime');
563
+ // The bundled maintenance runner is the installed runtime itself: only another
564
+ // Kitto package can replace that copy.
565
+ const fromInstalledRuntime = sameLocation(packageRoot, runtime);
566
+ const current = state.version;
567
+ if (!apply) {
568
+ if (fromInstalledRuntime) console.log(`Runtime: ${current} (this entry runs from the installed copy; run update with the intended Kitto package to replace it).`);
569
+ else {
570
+ const next = (await json(join(packageRoot, 'package.json'))).version;
571
+ console.log(next === current
572
+ ? `Runtime: ${current} (re-synced from the executing package only if its files differ).`
573
+ : `Runtime: ${current} -> ${next} (the previous verified version stays recoverable).`);
574
+ }
575
+ return undefined;
576
+ }
577
+ if (fromInstalledRuntime) {
578
+ console.log(`Runtime: ${current} (the installed maintenance runner cannot replace itself; run update with the intended Kitto package to refresh the code copy).`);
579
+ return undefined;
580
+ }
581
+ const installed = await installRuntime(home, state);
582
+ const pending = { version: (await json(join(installed, 'package.json'))).version, hash: await treeHash(installed, true) };
583
+ // A replaced runtime is not a verified checkpoint yet. Keep the last verified
584
+ // version/hash until the deployment below succeeds, so a retry cannot turn
585
+ // never-deployed code into the recovery target.
586
+ state.pendingRuntime = pending;
587
+ await atomicJson(join(home, 'state.json'), state);
588
+ console.log(pending.version === current
589
+ ? `Runtime: ${pending.version} (re-synced; verified after deployment)`
590
+ : `Runtime: ${current} -> ${pending.version} (verified after deployment; recover keeps ${current} until then)`);
591
+ return pending;
592
+ }
593
+
594
+ async function finalizeRuntime(state, pending) {
595
+ if (!pending) return;
596
+ state.version = pending.version;
597
+ state.runtimeHash = pending.hash;
598
+ delete state.pendingRuntime;
599
+ await atomicJson(join(kittoHome(), 'state.json'), state);
600
+ }
601
+
602
+ function upstreamOf(state, branch) {
603
+ try {
604
+ return git(state.source, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
605
+ } catch {
606
+ throw new Error(`Branch ${branch} has no upstream. Set one with 'git branch --set-upstream-to=<remote>/${branch} ${branch}' or 'git push -u <remote> ${branch}', then retry.`);
607
+ }
608
+ }
609
+
610
+ function restoreHint(state) {
611
+ const steps = [];
612
+ if (state.sourceUrl) steps.push(`git clone ${shellQuote(redactUrl(state.sourceUrl))} ${shellQuote(state.source)}`);
613
+ if (state.sourceRef) steps.push(`git -C ${shellQuote(state.source)} checkout ${shellQuote(state.sourceRef)}`);
614
+ return steps.length ? `Recreate the checkout in place (${steps.join(' && ')})` : `Recreate the checkout in place at ${state.source}`;
615
+ }
616
+
617
+ function restoreError(state, detail) {
618
+ return new Error(`${detail} ${restoreHint(state)} and rerun kitto setup; or use a new KITTO_HOME for a fresh installation.`);
619
+ }
620
+
621
+ /** Preview and apply must agree: inspect the recorded ref before announcing a restore. */
622
+ async function checkRestoreRef(state) {
623
+ const ref = state.sourceRef;
624
+ if (!ref) return;
625
+ let heads, tags;
626
+ try {
627
+ heads = run('git', ['ls-remote', '--heads', state.sourceUrl, `refs/heads/${ref}`], { capture: true, timeout: 30_000 });
628
+ tags = run('git', ['ls-remote', '--tags', state.sourceUrl, `refs/tags/${ref}`], { capture: true, timeout: 30_000 });
629
+ } catch (error) {
630
+ throw restoreError(state, `Cannot inspect ${redactUrl(state.sourceUrl)}: ${error.message}.`);
631
+ }
632
+ if (heads && tags) throw restoreError(state, `The recorded ref ${ref} exists as both a branch and a tag on ${redactUrl(state.sourceUrl)}.`);
633
+ if (tags) throw restoreError(state, `The checkout was pinned to tag ${ref} and Kitto does not guess pinned snapshots.`);
634
+ if (!heads) throw restoreError(state, `Branch ${ref} no longer exists on ${redactUrl(state.sourceUrl)}.`);
635
+ }
636
+
637
+ /** Follow a managed checkout's origin so recovery does not replay a stale URL. */
638
+ async function syncSourceLocation(state, apply) {
639
+ if (!state.sourceUrl) return;
640
+ let origin;
641
+ try { origin = git(state.source, ['config', '--local', '--get', 'remote.origin.url']); } catch { return; }
642
+ if (!origin || origin === state.sourceUrl) return;
643
+ if (!isGitUrl(origin)) {
644
+ console.log(`Configuration origin is not a Git URL; keeping ${redactUrl(state.sourceUrl)} for recovery.`);
645
+ return;
646
+ }
647
+ console.log(`Configuration source URL changed: ${redactUrl(state.sourceUrl)} -> ${redactUrl(origin)}.`);
648
+ if (!apply) return;
649
+ state.sourceUrl = origin;
650
+ const markerPath = bootstrapMarker(state.source);
651
+ if (await present(markerPath)) {
652
+ const marker = await json(markerPath).catch(() => ({}));
653
+ await atomicJson(markerPath, { ...marker, url: origin });
654
+ }
655
+ await atomicJson(join(kittoHome(), 'state.json'), state);
656
+ }
657
+
658
+ /** Backfill sourceUrl/sourceRef for installations whose state predates them. */
659
+ async function backfillSource(state) {
660
+ if (!await present(state.source)) return;
661
+ const markerPath = bootstrapMarker(state.source);
662
+ if (!await present(markerPath)) return;
663
+ const marker = await json(markerPath).catch(() => undefined);
664
+ if (!marker) return;
665
+ let changed = false;
666
+ if (marker.url && !state.sourceUrl) { state.sourceUrl = marker.url; changed = true; }
667
+ if (state.sourceRef === undefined) { state.sourceRef = marker.ref ?? null; changed = true; }
668
+ if (!changed) return;
669
+ console.log(`Recovered the configuration source from the bootstrap marker: ${redactUrl(state.sourceUrl)}${state.sourceRef ? ` (${state.sourceRef})` : ''}.`);
670
+ }
671
+
672
+ async function updateSource(state, apply) {
673
+ if (!await present(state.source)) {
674
+ if (!state.sourceUrl) throw restoreError(state, 'The Kitto configuration checkout is missing and no source URL was recorded.');
675
+ if (state.deployed?.detached) throw restoreError(state, `The configuration checkout was pinned to a detached revision${state.sourceRef ? ` (${state.sourceRef})` : ''} and is missing. Kitto does not guess pinned snapshots.`);
676
+ if (state.sourceRef === undefined) throw restoreError(state, 'The configuration checkout is missing and state.json does not record its branch or tag.');
677
+ if (!isGitUrl(state.sourceUrl)) throw restoreError(state, 'The recorded source URL is not an HTTPS/SSH Git URL.');
678
+ await checkRestoreRef(state);
679
+ console.log(`Restore configuration checkout from ${redactUrl(state.sourceUrl)}${state.sourceRef ? ` (${state.sourceRef})` : ' (remote default branch)'}: ${state.source}`);
680
+ if (!apply) return false;
681
+ await cloneSource(kittoHome(), state.source, state.sourceUrl, state.sourceRef ?? undefined);
682
+ }
683
+ if (sourceRevision(state.source).detached) {
684
+ throw new Error('Configuration is pinned to a detached revision. Run kitto setup --ref TAG to switch a Kitto-created checkout to another snapshot.');
685
+ }
686
+ if (git(state.source, ['status', '--porcelain'])) throw new Error('Source has local changes. Commit or resolve them before update; nothing was stashed or reset.');
687
+ const branch = git(state.source, ['symbolic-ref', '--short', 'HEAD']);
688
+ const upstream = upstreamOf(state, branch);
689
+ const remote = git(state.source, ['config', `branch.${branch}.remote`]);
690
+ const ref = git(state.source, ['config', `branch.${branch}.merge`]);
691
+ if (remote === '.') throw new Error('A remote-tracking branch is required for update.');
692
+ const before = sourceRevision(state.source).commit;
693
+ if (!apply) {
694
+ const head = run('git', ['-C', state.source, 'ls-remote', remote, ref], { capture: true, timeout: 30_000 }).split('\n')[0]?.split(/\s+/)[0];
695
+ console.log(`Configuration ${branch}: local ${before.slice(0, 7)}; remote ${head ? head.slice(0, 7) : '(no matching ref)'} (not fetched).`);
696
+ return false;
697
+ }
698
+ git(state.source, ['fetch', remote]);
699
+ // Only true divergence blocks the update: the local branch may be ahead of
700
+ // (or equal to) its remote, in which case --ff-only already reports up to date.
701
+ const isAncestor = (earlier, later) => spawnSync('git', ['-C', state.source, 'merge-base', '--is-ancestor', earlier, later],
702
+ { stdio: 'ignore', timeout: 30_000 }).status === 0;
703
+ if (!isAncestor(before, upstream) && !isAncestor(upstream, before)) {
704
+ throw new Error(`The remote branch ${upstream} and the local branch ${branch} have diverged (neither is an ancestor of the other). Kitto only fast-forwards; reconcile manually (for example git pull --rebase) and retry. Nothing was changed.`);
705
+ }
706
+ git(state.source, ['pull', '--ff-only']);
707
+ const after = sourceRevision(state.source).commit;
708
+ console.log(after === before
709
+ ? `Configuration ${branch} is already at ${after.slice(0, 7)}.`
710
+ : `Configuration ${branch} fast-forwarded ${before.slice(0, 7)} -> ${after.slice(0, 7)}.`);
711
+ await validateSource(state);
712
+ return true;
713
+ }
714
+
715
+ /** `kitto update [--check|--apply]`: source checkout, runtime copy and deployment. */
716
+ export async function update(args = []) {
717
+ if (args.includes('--check') && args.includes('--apply')) throw new Error('Choose either --check or --apply for update.');
718
+ if (args.includes('--include-private') && args.includes('--no-include-private')) throw new Error('Choose either --include-private or --no-include-private for update.');
719
+ const unknown = args.filter(flag => !['--check', '--apply', '--include-private', '--no-include-private'].includes(flag));
720
+ if (unknown.length) throw new Error(`Unknown update option: ${unknown[0]}. Read the Kitto skill.`);
721
+ const apply = args.includes('--apply');
722
+ const includePrivate = args.includes('--include-private') ? true
723
+ : args.includes('--no-include-private') ? false : undefined;
724
+ const home = kittoHome();
725
+ const state = await json(join(home, 'state.json')).catch(error => {
726
+ if (error.code === 'ENOENT') return null;
727
+ throw error;
728
+ });
729
+ if (!state) throw new Error(`Kitto is not set up in ${home}. Run kitto setup first.`);
730
+ if (state.detached || state.removing) throw new Error('Kitto is detached or removal is incomplete. Use setup to reconnect, or finish remove.');
731
+ console.log(`Kitto ${state.version} update${apply ? '' : ' preview (no writes)'}.`);
732
+ hostCliVersions(state);
733
+ const work = async () => {
734
+ // An explicit toggle applies to the preview and is persisted only after the
735
+ // deployment succeeds, because deploy() writes the state on apply.
736
+ if (includePrivate !== undefined) state.includePrivate = includePrivate;
737
+ await backfillSource(state);
738
+ const updated = await updateSource(state, apply);
739
+ if (!updated) {
740
+ if (await present(state.source)) {
741
+ await syncSourceLocation(state, false);
742
+ const plan = await configurationPlan(state);
743
+ await deploy(state, false, plan, packageRoot);
744
+ }
745
+ await refreshRuntime(state, false);
746
+ console.log('Preview only: restore the checkout if missing, fetch and fast-forward the source branch, refresh the Kitto runtime copy, then deploy configuration, skills and MCP. No writes.');
747
+ return;
748
+ }
749
+ await syncSourceLocation(state, true);
750
+ // Resolve configuration conflicts before replacing working code.
751
+ const plan = await configurationPlan(state);
752
+ const pending = await refreshRuntime(state, true);
753
+ // The process keeps the code it started with for this deployment; the next
754
+ // Kitto call (and each restarted host) uses the replaced runtime.
755
+ await deploy(state, true, plan, packageRoot);
756
+ await finalizeRuntime(state, pending);
757
+ console.log(`Kitto update complete: runtime ${state.version}, configuration ${sourceRevision(state.source).commit.slice(0, 7)}. Restart native hosts to load new plugin code.`);
758
+ };
759
+ if (apply) await locked(home, work); else await work();
760
+ }
761
+
421
762
  function sourceRevision(source) {
422
763
  const status = git(source, ['status', '--porcelain', '--branch']).split('\n');
423
764
  return {
@@ -443,6 +784,9 @@ async function cloneSource(home, source, url, ref) {
443
784
 
444
785
  export async function setup(options = {}) {
445
786
  if (options.global || Object.hasOwn(options, 'workspace') || Object.hasOwn(options, 'workspace-parent')) {
787
+ if (options['include-private'] || options['no-include-private']) {
788
+ throw new Error('--include-private and --no-include-private apply to global setup/update; scoped setup does not sync MCP servers.');
789
+ }
446
790
  const { setupScope } = await import('./scope-setup.mjs');
447
791
  return setupScope(options);
448
792
  }
@@ -459,15 +803,15 @@ export async function setup(options = {}) {
459
803
  const baseline = await readState();
460
804
  const old = baseline ? JSON.parse(baseline) : {};
461
805
  const agents = options.agents ? [...new Set([...(old.agents || []), ...options.agents])]
462
- : old.agents || Object.keys(hosts).filter(available);
806
+ : old.agents || Object.keys(hosts).filter(availableHost);
463
807
  if (!agents.length) throw new Error('No agent detected. Select --agents pi,codex,dsh; add --install-agents to install missing CLIs.');
464
- const installPnpm = agents.includes('dsh') && !available('pnpm');
808
+ const dshProfile = validateDshProfile(options['dsh-profile'] ?? old.dshProfile ?? 'web');
809
+ if (options['dsh-profile'] && !agents.includes('dsh')) throw new Error('--dsh-profile requires DSH.');
810
+ // The app-managed Desktop profile never installs a Kitto bundle, so it needs no pnpm.
811
+ const installPnpm = agents.includes('dsh') && !isDesktopProfile(dshProfile) && !available('pnpm');
465
812
  if (installPnpm && !options['install-agents']) throw new Error('DSH native plugin operations require pnpm on PATH. Add --install-agents to install the missing prerequisite.');
466
813
  if (installPnpm) console.log(`Install missing DSH prerequisite: pnpm@${pnpmVersion}`);
467
814
  if (!available('git')) throw new Error('git is required.');
468
- const dshProfile = options['dsh-profile'] ?? old.dshProfile ?? 'web';
469
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(dshProfile) || dshProfile === 'desktop') throw new Error('Invalid DSH CLI profile name.');
470
- if (options['dsh-profile'] && !agents.includes('dsh')) throw new Error('--dsh-profile requires DSH.');
471
815
  if (old.agents?.includes('dsh') && !old.detached && dshProfile !== (old.dshProfile || 'web')) {
472
816
  throw new Error('Detach the existing Kitto integration before selecting a different DSH profile.');
473
817
  }
@@ -482,7 +826,7 @@ export async function setup(options = {}) {
482
826
  const sameSource = basename(source) === basename(old.source) && sameLocation(dirname(source), dirname(old.source));
483
827
  if (!sameSource) throw new Error('This installation already has a source. Keep it or use a separate KITTO_HOME; source switching is not implicit.');
484
828
  }
485
- if (!local && !/^(https:\/\/|ssh:\/\/|git@)/.test(requested)) throw new Error('Source must be an existing checkout or HTTPS/SSH Git URL.');
829
+ if (!local && !isGitUrl(requested)) throw new Error('Source must be an existing checkout or HTTPS/SSH Git URL.');
486
830
  let switchTag = false, ownedSource = false;
487
831
  const markerPath = bootstrapMarker(source);
488
832
  if (options.ref && await present(markerPath)) {
@@ -508,9 +852,22 @@ export async function setup(options = {}) {
508
852
  console.log(`Resume setup from Kitto checkout: ${source}`);
509
853
  }
510
854
  if (local && options.ref && !ownedSource) throw new Error('Switch tags only in a Kitto-created checkout. For your own checkout, use Git.');
855
+ // Remember how to restore a managed checkout if it disappears: its URL and the
856
+ // branch/tag it was set up with. A local checkout records a URL only when Kitto
857
+ // created it (bootstrap marker); user-owned checkouts keep no implicit source.
858
+ const marker = await present(markerPath) ? await json(markerPath).catch(() => undefined) : undefined;
859
+ const sourceUrl = local ? marker?.url : requested;
860
+ // An explicit --ref always wins; otherwise the recorded marker/state ref is
861
+ // replayed, so a lost checkout is never silently restored from another branch.
862
+ const sourceRef = options.ref ?? marker?.ref ?? old.sourceRef ?? null;
511
863
  console.log(`Global setup: ${agents.join(', ')}; source: ${requested}; Kitto home: ${home}`);
512
- checkSelectedHosts(agents, options['install-agents']);
864
+ // The app-managed Desktop profile has no CLI prerequisite Kitto may install or verify.
865
+ const checkedAgents = agents.filter(name => !(name === 'dsh' && isDesktopProfile(dshProfile)));
866
+ checkSelectedHosts(checkedAgents, options['install-agents']);
867
+ const includePrivate = options['include-private'] === true ? true
868
+ : options['no-include-private'] === true ? false : old.includePrivate === true;
513
869
  const state = { ...old, schema: 1, ready: false, detached: false, removing: false, removedAgents: [], source, agents, dshProfile,
870
+ includePrivate, sourceUrl: sourceUrl || old.sourceUrl, sourceRef, pendingRuntime: undefined,
514
871
  agentsHome: old.agentsHome || resolve((agents.includes('pi') && process.env.PI_AGENTS_DIR)
515
872
  || (agents.includes('dsh') && process.env.DSH_AGENTS_HOME) || join(homedir(), '.agents')),
516
873
  piHome: old.piHome || resolve(process.env.PI_CODING_AGENT_DIR || join(homedir(), '.pi/agent')),
@@ -526,11 +883,18 @@ export async function setup(options = {}) {
526
883
  throw new Error('DSH_AGENTS_HOME and the shared skill root differ. Use the same root so native DSH sessions can discover your skills.');
527
884
  }
528
885
  if (agents.includes('dsh')) {
529
- const builtIn = ['web', 'headless', 'sdk', 'sdk-minimal', 'acp'];
530
- if (!builtIn.includes(dshProfile) && !await present(join(state.dshHome, 'profiles', dshProfile, 'package.json'))) {
531
- throw new Error(`Initialize the native DSH profile ${dshProfile} before setup.`);
886
+ if (isDesktopProfile(dshProfile)) {
887
+ // Global-only: the Desktop app owns profiles/desktop, its manifest and its patch.
888
+ console.log(`DSH profile: ${dshProfile} (global-only; managed by the Desktop app)`);
889
+ reportDesktopProbe(probeDesktopProfile({ dshHome: state.dshHome }));
890
+ console.log(desktopProfileNotice);
891
+ } else {
892
+ const builtIn = ['web', 'headless', 'sdk', 'sdk-minimal', 'acp'];
893
+ if (!builtIn.includes(dshProfile) && !await present(join(state.dshHome, 'profiles', dshProfile, 'package.json'))) {
894
+ throw new Error(`Initialize the native DSH profile ${dshProfile} before setup.`);
895
+ }
896
+ console.log(`DSH profile: ${dshProfile}`);
532
897
  }
533
- console.log(`DSH profile: ${dshProfile}`);
534
898
  }
535
899
  if (agents.includes('pi') && (!(local || resume) || !options['dry-run'])) checkPiTools();
536
900
  if (options['dry-run']) {
@@ -539,7 +903,9 @@ export async function setup(options = {}) {
539
903
  await validateSource(state);
540
904
  await deploy(state, false, undefined, packageRoot);
541
905
  }
542
- console.log('Preview only: clone if needed, persist Kitto runtime, deploy selected configuration and skills, register native integrations. No writes.');
906
+ console.log(isDesktopProfile(dshProfile)
907
+ ? 'Preview only: clone if needed, persist Kitto runtime, deploy global rules and skills; the app-managed DSH desktop bundle and scopes stay untouched. No writes.'
908
+ : 'Preview only: clone if needed, persist Kitto runtime, deploy selected configuration and skills, register native integrations. No writes.');
543
909
  return;
544
910
  }
545
911
  await locked(home, async () => {
@@ -548,13 +914,14 @@ export async function setup(options = {}) {
548
914
  run('npm', ['install', '--global', `pnpm@${pnpmVersion}`]);
549
915
  if (!available('pnpm')) throw new Error('pnpm was installed but cannot run. Check PATH and allow pnpm native-binary install scripts, then rerun setup.');
550
916
  }
551
- installMissingHosts(agents);
917
+ installMissingHosts(checkedAgents);
552
918
  if (!local && !resume) await cloneSource(home, source, requested, options.ref);
553
919
  if (switchTag) {
554
920
  if (sourceRevision(source).dirty) throw new Error('Source has local changes. Commit or resolve them before switching tags.');
555
921
  git(source, ['fetch', '--no-tags', 'origin', `refs/tags/${options.ref}`]);
556
922
  const commit = git(source, ['rev-parse', 'FETCH_HEAD^{commit}']);
557
923
  git(source, ['checkout', '--no-overwrite-ignore', '--detach', commit]);
924
+ await atomicJson(bootstrapMarker(source), { ...(await json(bootstrapMarker(source)).catch(() => ({}))), ref: options.ref });
558
925
  }
559
926
  await validateSource(state);
560
927
  const plan = await configurationPlan(state);
@@ -562,13 +929,22 @@ export async function setup(options = {}) {
562
929
  await atomicJson(join(home, 'state.json'), state);
563
930
  await deploy(state, true, plan);
564
931
  });
565
- console.log('Kitto setup complete. Start your agent with its native command; ask the Kitto skill to maintain configuration.');
932
+ console.log(isDesktopProfile(dshProfile)
933
+ ? 'Kitto setup complete. Fully quit and reopen DeepSeek Harness Desktop to load the deployed global rules and skills; ask the Kitto skill to maintain configuration.'
934
+ : 'Kitto setup complete. Start your agent with its native command; ask the Kitto skill to maintain configuration.');
566
935
  }
567
936
 
568
937
  export async function maintain(args) {
569
938
  const [operation = 'status', ...flags] = args;
570
- const allowed = { status: [], versions: ['--online'], sync: ['--apply'], update: ['--apply'], export: ['--apply'], deps: ['--apply'], recover: ['--apply'], remove: ['--apply'] };
939
+ // Host CLI policy is shared with the public kitto command. Import lazily to
940
+ // avoid a module cycle with lib/hosts.mjs.
941
+ if (operation === 'hosts') {
942
+ const { hostsCommand } = await import('./hosts.mjs');
943
+ return hostsCommand(flags);
944
+ }
945
+ const allowed = { status: [], versions: ['--online'], sync: ['--apply'], update: ['--check', '--apply'], export: ['--apply'], deps: ['--apply'], recover: ['--apply'], remove: ['--apply'] };
571
946
  if (!allowed[operation] || flags.some(flag => !allowed[operation].includes(flag))) throw new Error('Unsupported maintenance operation or flag. Read the Kitto skill.');
947
+ if (operation === 'update') return update(flags);
572
948
  const home = kittoHome(), state = await json(join(home, 'state.json'));
573
949
  const apply = flags.includes('--apply');
574
950
  // These operations must also work when the personal checkout is unavailable.
@@ -587,24 +963,13 @@ export async function maintain(args) {
587
963
  console.log(JSON.stringify({ ...state, checkout: sourceRevision(state.source), git: git(state.source, ['status', '--short', '--branch']) }, null, 2));
588
964
  await configurationPlan(state);
589
965
  for (const tool of await dependencyPlan(state)) console.log(`dependency ${tool.available ? 'available' : 'missing'}: ${tool.name} (${tool.reason})`);
966
+ await reportCodeGraphIndexes(state);
967
+ await printMcpParity(state);
590
968
  if (state.agents.includes('pi')) syncCommand(state, 'status');
591
969
  } else if (operation === 'versions') {
592
970
  console.log(JSON.stringify(await versionReport(state, hosts, pnpmVersion, flags.includes('--online'), treeHash), null, 2));
593
971
  } else {
594
972
  const work = async () => {
595
- if (operation === 'update') {
596
- if (sourceRevision(state.source).detached) {
597
- throw new Error('Configuration is pinned to a detached revision. Run kitto setup --ref TAG to switch a Kitto-created checkout to another snapshot.');
598
- }
599
- if (git(state.source, ['status', '--porcelain'])) throw new Error('Source has local changes. Commit or resolve them before update; nothing was stashed or reset.');
600
- const branch = git(state.source, ['symbolic-ref', '--short', 'HEAD']);
601
- const remote = git(state.source, ['config', `branch.${branch}.remote`]);
602
- const ref = git(state.source, ['config', `branch.${branch}.merge`]);
603
- if (remote === '.') throw new Error('A remote-tracking branch is required for update.');
604
- if (!apply) { console.log(run('git', ['-C', state.source, 'ls-remote', remote, ref], { capture: true, timeout: 30_000 })); return; }
605
- git(state.source, ['pull', '--ff-only']);
606
- await validateSource(state);
607
- }
608
973
  if (operation === 'deps') await installDependencies(state, apply);
609
974
  else if (operation === 'export') {
610
975
  if (!state.agents.includes('pi')) throw new Error('Pi export requires a Pi installation. Edit shared skills in the source checkout.');