@phyzess/kitto 0.2.1 → 0.3.1
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/CHANGELOG.md +31 -0
- package/README.md +36 -4
- package/bin/kitto.mjs +176 -2
- package/integration/dsh-archive-review.mjs +55 -0
- package/integration/dsh.mjs +3 -1
- package/integration/plugin.json +1 -1
- package/integration/scoped-dsh/native.mjs +33 -1
- package/integration/skills/kitto/SKILL.md +5 -4
- package/lib/codegraph.mjs +135 -0
- package/lib/codex-mcp.mjs +738 -0
- package/lib/dsh-profile.mjs +111 -0
- package/lib/environment-setup.mjs +19 -3
- package/lib/host-config.mjs +29 -4
- package/lib/hosts.mjs +288 -0
- package/lib/kitto.mjs +475 -59
- package/lib/mcp-credentials.mjs +289 -0
- package/lib/mcp-sync.mjs +500 -0
- package/lib/parity.mjs +64 -0
- package/lib/pi_config.py +218 -9
- package/lib/scope-dsh.mjs +10 -31
- package/lib/scope-setup.mjs +35 -13
- package/lib/scopes.mjs +45 -10
- package/lib/setup-wizard.mjs +38 -13
- package/lib/versions.mjs +8 -2
- package/lib/worktree-audit.mjs +189 -0
- package/lib/worktree-lifecycle.mjs +451 -0
- package/package.json +3 -3
- package/sync.sh +94 -25
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.
|
|
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', '--require-baseline', '--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,37 +123,131 @@ async function validateSource({ source, agents }) {
|
|
|
89
123
|
await readFile(join(source, 'config/pi/AGENTS.md'));
|
|
90
124
|
}
|
|
91
125
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
+
|
|
166
|
+
// Host CLI versions are observations, not gates. An older CLI is reported and
|
|
167
|
+
// the steps it cannot support are skipped, so one stale host never blocks the
|
|
168
|
+
// others; a missing binary stays fatal because no integration can run.
|
|
169
|
+
function hostCapabilities(name, env) {
|
|
170
|
+
const supports = args => spawnSync(name, args, { stdio: 'ignore', timeout: 8000, env }).status === 0;
|
|
171
|
+
if (name === 'codex') return { plugin: supports(['plugin', 'add', '--help']), mcp: supports(['mcp', '--help']) };
|
|
172
|
+
if (name === 'dsh') return { plugin: supports(['plugin', '--help']) };
|
|
173
|
+
return {};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function inspectHost(name) {
|
|
177
|
+
// Codex creates helper files under CODEX_HOME even for --version/--help.
|
|
178
|
+
// Probe with a scratch home so checks never write the user's Codex state.
|
|
179
|
+
const probe = name === 'codex' ? mkdtempSync(join(tmpdir(), 'kitto-codex-check-')) : null;
|
|
180
|
+
const env = probe ? { ...process.env, CODEX_HOME: probe } : process.env;
|
|
181
|
+
try {
|
|
182
|
+
const result = spawnSync(name, ['--version'], { encoding: 'utf8', timeout: 8000, env });
|
|
183
|
+
const stdout = (result.stdout ?? '').trim();
|
|
184
|
+
const actual = stdout.match(/\d+\.\d+\.\d+(?:-[\w.-]+)?/)?.[0] ?? null;
|
|
185
|
+
const baseline = hosts[name].version;
|
|
186
|
+
const missing = result.error?.code === 'ENOENT';
|
|
187
|
+
const detail = (stdout.split('\n')[0] || (result.stderr ?? '').trim().split('\n')[0] || `exit ${result.status}`);
|
|
188
|
+
return {
|
|
189
|
+
name, baseline, actual, status: missing ? 'missing' : actual ? 'found' : 'unreadable', detail,
|
|
190
|
+
meetsBaseline: Boolean(actual) && meetsBaseline(actual, baseline),
|
|
191
|
+
capabilities: missing ? {} : hostCapabilities(name, env),
|
|
192
|
+
};
|
|
193
|
+
} finally {
|
|
194
|
+
if (probe) rmSync(probe, { recursive: true, force: true });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// A host below the tested baseline is a warning, never a write barrier: every
|
|
199
|
+
// other selected host is still deployed. --require-baseline restores the old
|
|
200
|
+
// fatal behaviour for release verification.
|
|
201
|
+
function reportHost(report, requireBaseline) {
|
|
202
|
+
const { name, baseline } = report;
|
|
203
|
+
if (report.status === 'unreadable') {
|
|
204
|
+
console.warn(`kitto: ${name}: could not read its version (${report.detail}); continuing, but its native integration is unverified.`);
|
|
205
|
+
} else if (report.meetsBaseline) {
|
|
206
|
+
console.log(`${name}: ${report.actual} (tested baseline ${baseline})`);
|
|
207
|
+
} else {
|
|
208
|
+
const detail = `${name}: ${report.actual} is older than the tested baseline ${baseline}`;
|
|
209
|
+
if (requireBaseline) throw new Error(`${detail}. Upgrade it with \`kitto hosts --apply\`, or drop --require-baseline.`);
|
|
210
|
+
console.warn(`kitto: ${detail}; continuing and skipping the steps this CLI cannot support. Run \`kitto hosts --apply\` when you want the tested baseline.`);
|
|
100
211
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
212
|
+
}
|
|
213
|
+
function availableHost(name) {
|
|
214
|
+
if (name !== 'codex') return available(name);
|
|
215
|
+
// Codex creates helper files under CODEX_HOME even for --version.
|
|
216
|
+
const probe = mkdtempSync(join(tmpdir(), 'kitto-codex-check-'));
|
|
217
|
+
try { return available(name, { ...process.env, CODEX_HOME: probe }); }
|
|
218
|
+
finally { rmSync(probe, { recursive: true, force: true }); }
|
|
104
219
|
}
|
|
105
220
|
|
|
106
|
-
export function checkSelectedHosts(agents, installAgents) {
|
|
221
|
+
export function checkSelectedHosts(agents, installAgents, options = {}) {
|
|
222
|
+
const reports = [];
|
|
107
223
|
for (const name of agents) {
|
|
108
|
-
if (!
|
|
224
|
+
if (!availableHost(name)) {
|
|
109
225
|
if (!installAgents) throw new Error(`${name} is missing. Install it natively or add --install-agents (pins ${hosts[name].version}).`);
|
|
110
226
|
const requiredNode = hosts[name].node;
|
|
111
227
|
if (requiredNode && requiredNode.localeCompare(process.versions.node, 'en', { numeric: true }) > 0) {
|
|
112
228
|
throw new Error(`Installing ${name} through npm requires Node >=${requiredNode}.`);
|
|
113
229
|
}
|
|
114
230
|
console.log(`Install missing CLI: ${hosts[name].package}@${hosts[name].version}${name === 'dsh' ? ' (prerelease)' : ''}`);
|
|
115
|
-
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const report = inspectHost(name);
|
|
234
|
+
reports.push(report);
|
|
235
|
+
reportHost(report, options.requireBaseline === true);
|
|
116
236
|
}
|
|
237
|
+
return reports;
|
|
117
238
|
}
|
|
118
239
|
|
|
119
240
|
export function installMissingHosts(agents) {
|
|
120
|
-
for (const name of agents) if (!
|
|
241
|
+
for (const name of agents) if (!availableHost(name)) {
|
|
121
242
|
run('npm', ['install', '--global', `${hosts[name].package}@${hosts[name].version}`]);
|
|
122
|
-
|
|
243
|
+
// Unlike the pre-flight check, a fresh install is verified strictly: Kitto
|
|
244
|
+
// chose the version, so a different one means PATH or the prefix is wrong.
|
|
245
|
+
const report = inspectHost(name);
|
|
246
|
+
if (report.status !== 'found' || report.actual !== hosts[name].version) {
|
|
247
|
+
throw new Error(`${name}: npm installed ${hosts[name].version} but the CLI reports ${report.actual ?? report.status}. `
|
|
248
|
+
+ 'Check PATH and the npm global prefix; Kitto wrote no state.');
|
|
249
|
+
}
|
|
250
|
+
console.log(`${name}: ${report.actual} (installed pinned baseline)`);
|
|
123
251
|
}
|
|
124
252
|
}
|
|
125
253
|
|
|
@@ -141,7 +269,7 @@ async function installRuntime(home, old) {
|
|
|
141
269
|
const next = join(home, 'runtime.next');
|
|
142
270
|
const runtime = join(home, 'runtime');
|
|
143
271
|
const previous = join(home, 'runtime.previous');
|
|
144
|
-
if (
|
|
272
|
+
if (sameLocation(packageRoot, runtime)) return runtime;
|
|
145
273
|
await rm(next, { recursive: true, force: true });
|
|
146
274
|
await mkdir(next);
|
|
147
275
|
for (const name of ['package.json', 'bin', 'lib', 'integration', 'sync.sh', 'CHANGELOG.md']) {
|
|
@@ -255,10 +383,17 @@ function syncCommand(state, command, apply = false, codeRoot = join(kittoHome(),
|
|
|
255
383
|
|
|
256
384
|
async function connect(state) {
|
|
257
385
|
const home = kittoHome(), runtime = join(home, 'runtime');
|
|
258
|
-
|
|
386
|
+
const desktopDsh = state.agents.includes('dsh') && isDesktopProfile(state.dshProfile);
|
|
387
|
+
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
388
|
for (const name of state.agents) {
|
|
260
389
|
if (name === 'pi') run('pi', ['install', runtime], { env: { ...process.env, PI_CODING_AGENT_DIR: state.piHome } });
|
|
261
390
|
if (name === 'codex') {
|
|
391
|
+
const codex = inspectHost('codex');
|
|
392
|
+
if (!codex.capabilities.plugin) {
|
|
393
|
+
console.warn('kitto: this codex CLI has no plugin subcommand; skipped the Kitto plugin registration. '
|
|
394
|
+
+ 'Rules, skills and MCP were still deployed.');
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
262
397
|
await mkdir(state.codexHome, { recursive: true });
|
|
263
398
|
const marketplace = join(home, '.agents/plugins/marketplace.json');
|
|
264
399
|
await atomicJson(marketplace, { name: 'phyzess-kitto', plugins: [{ name: 'kitto',
|
|
@@ -269,6 +404,16 @@ async function connect(state) {
|
|
|
269
404
|
run('codex', ['plugin', 'add', 'kitto@phyzess-kitto'], { env });
|
|
270
405
|
}
|
|
271
406
|
if (name === 'dsh') {
|
|
407
|
+
if (isDesktopProfile(state.dshProfile)) {
|
|
408
|
+
console.log('DSH desktop profile: app-managed; skipped Kitto bundle registration (global rules and skills only).');
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
const dsh = inspectHost('dsh');
|
|
412
|
+
if (!dsh.capabilities.plugin) {
|
|
413
|
+
console.warn(`kitto: this dsh CLI${dsh.actual ? ` (${dsh.actual})` : ''} has no plugin subcommand; `
|
|
414
|
+
+ 'skipped the Kitto bundle registration. Rules and skills were still deployed.');
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
272
417
|
await mkdir(state.dshHome, { recursive: true });
|
|
273
418
|
run('dsh', ['plugin', '--profile', state.dshProfile || 'web', 'add', runtime], {
|
|
274
419
|
env: { ...process.env, DSH_HOME: state.dshHome, DSH_AGENTS_HOME: state.agentsHome },
|
|
@@ -287,15 +432,18 @@ async function configurationPlan(state) {
|
|
|
287
432
|
}
|
|
288
433
|
const instructions = await instructionPlan(state);
|
|
289
434
|
for (const plan of instructions) console.log(`instructions ${plan.before === plan.after ? 'same' : 'sync'}: ${plan.target}`);
|
|
290
|
-
|
|
435
|
+
const mcp = state.agents.includes('codex') ? await planCodexMcp(state) : undefined;
|
|
436
|
+
return { groups, instructions, mcp };
|
|
291
437
|
}
|
|
292
438
|
|
|
293
439
|
async function deploy(state, apply, plan = undefined, codeRoot = undefined) {
|
|
294
440
|
const { groups, instructions } = plan ?? await configurationPlan(state);
|
|
295
441
|
const deployment = apply ? sourceRevision(state.source) : undefined;
|
|
442
|
+
const connectable = state.agents.filter(name => !(name === 'dsh' && isDesktopProfile(state.dshProfile)));
|
|
296
443
|
if (state.agents.includes('pi')) syncCommand(state, 'pull', apply, codeRoot);
|
|
444
|
+
if (state.agents.includes('dsh') && !isDesktopProfile(state.dshProfile)) await syncDshMcp(state, { dryRun: !apply });
|
|
297
445
|
if (!apply) {
|
|
298
|
-
if (!state.ready) console.log(`Connect native Kitto integrations: ${
|
|
446
|
+
if (!state.ready && connectable.length) console.log(`Connect native Kitto integrations: ${connectable.join(', ')}`);
|
|
299
447
|
return;
|
|
300
448
|
}
|
|
301
449
|
await applyInstructions(state, instructions);
|
|
@@ -304,9 +452,11 @@ async function deploy(state, apply, plan = undefined, codeRoot = undefined) {
|
|
|
304
452
|
const owned = {};
|
|
305
453
|
const kept = [];
|
|
306
454
|
for (const plan of plans) {
|
|
307
|
-
if (
|
|
308
|
-
|
|
309
|
-
|
|
455
|
+
if (plan.action === 'copy') await replaceDirectory(plan.source, plan.target);
|
|
456
|
+
else if (plan.action === 'remove') {
|
|
457
|
+
const trash = `${plan.target}.kitto-remove-${process.pid}`;
|
|
458
|
+
await rename(plan.target, trash);
|
|
459
|
+
await rm(trash, { recursive: true, force: true });
|
|
310
460
|
}
|
|
311
461
|
if (plan.action === 'keep') kept.push(plan.name);
|
|
312
462
|
else if (plan.action !== 'remove') owned[plan.name] = plan.hash;
|
|
@@ -320,6 +470,9 @@ async function deploy(state, apply, plan = undefined, codeRoot = undefined) {
|
|
|
320
470
|
}
|
|
321
471
|
// Save deployment ownership before native managers, so retry is recoverable.
|
|
322
472
|
await atomicJson(join(kittoHome(), 'state.json'), state);
|
|
473
|
+
if (state.agents.includes('codex')) {
|
|
474
|
+
await applyCodexMcp(state, { save: () => atomicJson(join(kittoHome(), 'state.json'), state) });
|
|
475
|
+
}
|
|
323
476
|
if (!state.ready) {
|
|
324
477
|
await connect(state);
|
|
325
478
|
state.runtimeHash = await treeHash(join(kittoHome(), 'runtime'), true);
|
|
@@ -338,7 +491,7 @@ async function recover(state, apply) {
|
|
|
338
491
|
throw new Error('The runtime checkpoint was verified with a different DSH profile.');
|
|
339
492
|
}
|
|
340
493
|
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.`);
|
|
494
|
+
console.log(`Restore Kitto code ${state.pendingRuntime?.version || state.version} -> ${checkpoint.version}; reconnect ${state.agents.join(', ')}. Personal configuration and skills stay as deployed.`);
|
|
342
495
|
if (!apply) return;
|
|
343
496
|
state.ready = false;
|
|
344
497
|
await atomicJson(join(home, 'state.json'), state);
|
|
@@ -349,6 +502,7 @@ async function recover(state, apply) {
|
|
|
349
502
|
await replaceRuntime(home, next);
|
|
350
503
|
}
|
|
351
504
|
state.version = checkpoint.version;
|
|
505
|
+
delete state.pendingRuntime;
|
|
352
506
|
await atomicJson(join(home, 'state.json'), state);
|
|
353
507
|
await connect(state);
|
|
354
508
|
state.runtimeHash = checkpoint.hash;
|
|
@@ -356,7 +510,7 @@ async function recover(state, apply) {
|
|
|
356
510
|
await atomicJson(join(home, 'state.json'), state);
|
|
357
511
|
}
|
|
358
512
|
|
|
359
|
-
async function removeIntegration(state, name, apply) {
|
|
513
|
+
async function removeIntegration(state, name, apply, announce = true) {
|
|
360
514
|
const home = kittoHome(), runtime = join(home, 'runtime');
|
|
361
515
|
if (name === 'pi') {
|
|
362
516
|
const settings = join(state.piHome, 'settings.json');
|
|
@@ -386,9 +540,19 @@ async function removeIntegration(state, name, apply) {
|
|
|
386
540
|
if (plugin && (plugin.source?.source !== 'local' || !sameLocation(plugin.source.path, join(runtime, 'integration')))) {
|
|
387
541
|
throw new Error('The Codex Kitto plugin now comes from another source. Preserved.');
|
|
388
542
|
}
|
|
543
|
+
await removeCodexMcp(state, {
|
|
544
|
+
apply, env,
|
|
545
|
+
save: () => atomicJson(join(home, 'state.json'), state),
|
|
546
|
+
...(announce ? {} : { log: () => {}, warn: () => {} }),
|
|
547
|
+
});
|
|
389
548
|
if (apply && plugin) run('codex', ['plugin', 'remove', 'kitto@phyzess-kitto'], { env });
|
|
390
549
|
if (apply && market) run('codex', ['plugin', 'marketplace', 'remove', 'phyzess-kitto'], { env });
|
|
391
550
|
} else if (name === 'dsh') {
|
|
551
|
+
if (isDesktopProfile(state.dshProfile)) {
|
|
552
|
+
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.');
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
await removeDshMcp(state, { dryRun: !apply, ...(announce ? {} : { log: () => {}, warn: () => {} }) });
|
|
392
556
|
const manifest = join(state.dshHome, 'profiles', state.dshProfile || 'web', 'package.json');
|
|
393
557
|
if (!await present(manifest)) return;
|
|
394
558
|
const profile = await json(manifest), dependency = profile.dependencies?.['@phyzess/kitto'];
|
|
@@ -404,7 +568,8 @@ async function remove(state, apply) {
|
|
|
404
568
|
console.log(`Detach Kitto from ${state.agents.join(', ')}. Keep configuration, shared skills, agent CLIs and Kitto files for recovery/reinstallation.`);
|
|
405
569
|
// Inspect every remaining host before making any change.
|
|
406
570
|
const remaining = state.agents.filter(name => !(state.removedAgents || []).includes(name));
|
|
407
|
-
|
|
571
|
+
// Keep the preflight quiet when the same removal will report its real work below.
|
|
572
|
+
for (const name of remaining) await removeIntegration(state, name, false, !apply);
|
|
408
573
|
if (!apply) return;
|
|
409
574
|
const path = join(kittoHome(), 'state.json');
|
|
410
575
|
state.ready = false; state.removing = true;
|
|
@@ -418,6 +583,231 @@ async function remove(state, apply) {
|
|
|
418
583
|
await atomicJson(path, state);
|
|
419
584
|
}
|
|
420
585
|
|
|
586
|
+
// Kitto updates its own code copy, never a host CLI. Print both versions so the
|
|
587
|
+
// user knows what to upgrade with the host's native manager, without failing.
|
|
588
|
+
function hostCliVersions(state) {
|
|
589
|
+
console.log('Host CLIs (Kitto never upgrades them; use each native manager):');
|
|
590
|
+
for (const name of state.agents) {
|
|
591
|
+
const baseline = hosts[name].version;
|
|
592
|
+
if (name === 'dsh' && isDesktopProfile(state.dshProfile)) {
|
|
593
|
+
console.log(` dsh: app-managed (Kitto tested baseline ${baseline}); upgrade through DeepSeek Harness Desktop`);
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
// Codex creates helper files under CODEX_HOME even for --version.
|
|
597
|
+
const probe = name === 'codex' ? mkdtempSync(join(tmpdir(), 'kitto-codex-check-')) : null;
|
|
598
|
+
try {
|
|
599
|
+
const output = run(name, ['--version'], { capture: true, timeout: 8000, env: probe ? { ...process.env, CODEX_HOME: probe } : process.env });
|
|
600
|
+
const actual = output.match(/\d+\.\d+\.\d+(?:-[\w.]+)?/)?.[0] || output.split('\n')[0];
|
|
601
|
+
console.log(` ${name}: ${actual} (Kitto tested baseline ${baseline}); upgrade with its native manager (${hosts[name].package})`);
|
|
602
|
+
} catch {
|
|
603
|
+
console.log(` ${name}: not found (Kitto tested baseline ${baseline}); install ${hosts[name].package} with its native manager`);
|
|
604
|
+
} finally {
|
|
605
|
+
if (probe) rmSync(probe, { recursive: true, force: true });
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
async function refreshRuntime(state, apply) {
|
|
611
|
+
const home = kittoHome(), runtime = join(home, 'runtime');
|
|
612
|
+
// The bundled maintenance runner is the installed runtime itself: only another
|
|
613
|
+
// Kitto package can replace that copy.
|
|
614
|
+
const fromInstalledRuntime = sameLocation(packageRoot, runtime);
|
|
615
|
+
const current = state.version;
|
|
616
|
+
if (!apply) {
|
|
617
|
+
if (fromInstalledRuntime) console.log(`Runtime: ${current} (this entry runs from the installed copy; run update with the intended Kitto package to replace it).`);
|
|
618
|
+
else {
|
|
619
|
+
const next = (await json(join(packageRoot, 'package.json'))).version;
|
|
620
|
+
console.log(next === current
|
|
621
|
+
? `Runtime: ${current} (re-synced from the executing package only if its files differ).`
|
|
622
|
+
: `Runtime: ${current} -> ${next} (the previous verified version stays recoverable).`);
|
|
623
|
+
}
|
|
624
|
+
return undefined;
|
|
625
|
+
}
|
|
626
|
+
if (fromInstalledRuntime) {
|
|
627
|
+
console.log(`Runtime: ${current} (the installed maintenance runner cannot replace itself; run update with the intended Kitto package to refresh the code copy).`);
|
|
628
|
+
return undefined;
|
|
629
|
+
}
|
|
630
|
+
const installed = await installRuntime(home, state);
|
|
631
|
+
const pending = { version: (await json(join(installed, 'package.json'))).version, hash: await treeHash(installed, true) };
|
|
632
|
+
// A replaced runtime is not a verified checkpoint yet. Keep the last verified
|
|
633
|
+
// version/hash until the deployment below succeeds, so a retry cannot turn
|
|
634
|
+
// never-deployed code into the recovery target.
|
|
635
|
+
state.pendingRuntime = pending;
|
|
636
|
+
await atomicJson(join(home, 'state.json'), state);
|
|
637
|
+
console.log(pending.version === current
|
|
638
|
+
? `Runtime: ${pending.version} (re-synced; verified after deployment)`
|
|
639
|
+
: `Runtime: ${current} -> ${pending.version} (verified after deployment; recover keeps ${current} until then)`);
|
|
640
|
+
return pending;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
async function finalizeRuntime(state, pending) {
|
|
644
|
+
if (!pending) return;
|
|
645
|
+
state.version = pending.version;
|
|
646
|
+
state.runtimeHash = pending.hash;
|
|
647
|
+
delete state.pendingRuntime;
|
|
648
|
+
await atomicJson(join(kittoHome(), 'state.json'), state);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
function upstreamOf(state, branch) {
|
|
652
|
+
try {
|
|
653
|
+
return git(state.source, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
|
654
|
+
} catch {
|
|
655
|
+
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.`);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function restoreHint(state) {
|
|
660
|
+
const steps = [];
|
|
661
|
+
if (state.sourceUrl) steps.push(`git clone ${shellQuote(redactUrl(state.sourceUrl))} ${shellQuote(state.source)}`);
|
|
662
|
+
if (state.sourceRef) steps.push(`git -C ${shellQuote(state.source)} checkout ${shellQuote(state.sourceRef)}`);
|
|
663
|
+
return steps.length ? `Recreate the checkout in place (${steps.join(' && ')})` : `Recreate the checkout in place at ${state.source}`;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function restoreError(state, detail) {
|
|
667
|
+
return new Error(`${detail} ${restoreHint(state)} and rerun kitto setup; or use a new KITTO_HOME for a fresh installation.`);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** Preview and apply must agree: inspect the recorded ref before announcing a restore. */
|
|
671
|
+
async function checkRestoreRef(state) {
|
|
672
|
+
const ref = state.sourceRef;
|
|
673
|
+
if (!ref) return;
|
|
674
|
+
let heads, tags;
|
|
675
|
+
try {
|
|
676
|
+
heads = run('git', ['ls-remote', '--heads', state.sourceUrl, `refs/heads/${ref}`], { capture: true, timeout: 30_000 });
|
|
677
|
+
tags = run('git', ['ls-remote', '--tags', state.sourceUrl, `refs/tags/${ref}`], { capture: true, timeout: 30_000 });
|
|
678
|
+
} catch (error) {
|
|
679
|
+
throw restoreError(state, `Cannot inspect ${redactUrl(state.sourceUrl)}: ${error.message}.`);
|
|
680
|
+
}
|
|
681
|
+
if (heads && tags) throw restoreError(state, `The recorded ref ${ref} exists as both a branch and a tag on ${redactUrl(state.sourceUrl)}.`);
|
|
682
|
+
if (tags) throw restoreError(state, `The checkout was pinned to tag ${ref} and Kitto does not guess pinned snapshots.`);
|
|
683
|
+
if (!heads) throw restoreError(state, `Branch ${ref} no longer exists on ${redactUrl(state.sourceUrl)}.`);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** Follow a managed checkout's origin so recovery does not replay a stale URL. */
|
|
687
|
+
async function syncSourceLocation(state, apply) {
|
|
688
|
+
if (!state.sourceUrl) return;
|
|
689
|
+
let origin;
|
|
690
|
+
try { origin = git(state.source, ['config', '--local', '--get', 'remote.origin.url']); } catch { return; }
|
|
691
|
+
if (!origin || origin === state.sourceUrl) return;
|
|
692
|
+
if (!isGitUrl(origin)) {
|
|
693
|
+
console.log(`Configuration origin is not a Git URL; keeping ${redactUrl(state.sourceUrl)} for recovery.`);
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
console.log(`Configuration source URL changed: ${redactUrl(state.sourceUrl)} -> ${redactUrl(origin)}.`);
|
|
697
|
+
if (!apply) return;
|
|
698
|
+
state.sourceUrl = origin;
|
|
699
|
+
const markerPath = bootstrapMarker(state.source);
|
|
700
|
+
if (await present(markerPath)) {
|
|
701
|
+
const marker = await json(markerPath).catch(() => ({}));
|
|
702
|
+
await atomicJson(markerPath, { ...marker, url: origin });
|
|
703
|
+
}
|
|
704
|
+
await atomicJson(join(kittoHome(), 'state.json'), state);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/** Backfill sourceUrl/sourceRef for installations whose state predates them. */
|
|
708
|
+
async function backfillSource(state) {
|
|
709
|
+
if (!await present(state.source)) return;
|
|
710
|
+
const markerPath = bootstrapMarker(state.source);
|
|
711
|
+
if (!await present(markerPath)) return;
|
|
712
|
+
const marker = await json(markerPath).catch(() => undefined);
|
|
713
|
+
if (!marker) return;
|
|
714
|
+
let changed = false;
|
|
715
|
+
if (marker.url && !state.sourceUrl) { state.sourceUrl = marker.url; changed = true; }
|
|
716
|
+
if (state.sourceRef === undefined) { state.sourceRef = marker.ref ?? null; changed = true; }
|
|
717
|
+
if (!changed) return;
|
|
718
|
+
console.log(`Recovered the configuration source from the bootstrap marker: ${redactUrl(state.sourceUrl)}${state.sourceRef ? ` (${state.sourceRef})` : ''}.`);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
async function updateSource(state, apply) {
|
|
722
|
+
if (!await present(state.source)) {
|
|
723
|
+
if (!state.sourceUrl) throw restoreError(state, 'The Kitto configuration checkout is missing and no source URL was recorded.');
|
|
724
|
+
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.`);
|
|
725
|
+
if (state.sourceRef === undefined) throw restoreError(state, 'The configuration checkout is missing and state.json does not record its branch or tag.');
|
|
726
|
+
if (!isGitUrl(state.sourceUrl)) throw restoreError(state, 'The recorded source URL is not an HTTPS/SSH Git URL.');
|
|
727
|
+
await checkRestoreRef(state);
|
|
728
|
+
console.log(`Restore configuration checkout from ${redactUrl(state.sourceUrl)}${state.sourceRef ? ` (${state.sourceRef})` : ' (remote default branch)'}: ${state.source}`);
|
|
729
|
+
if (!apply) return false;
|
|
730
|
+
await cloneSource(kittoHome(), state.source, state.sourceUrl, state.sourceRef ?? undefined);
|
|
731
|
+
}
|
|
732
|
+
if (sourceRevision(state.source).detached) {
|
|
733
|
+
throw new Error('Configuration is pinned to a detached revision. Run kitto setup --ref TAG to switch a Kitto-created checkout to another snapshot.');
|
|
734
|
+
}
|
|
735
|
+
if (git(state.source, ['status', '--porcelain'])) throw new Error('Source has local changes. Commit or resolve them before update; nothing was stashed or reset.');
|
|
736
|
+
const branch = git(state.source, ['symbolic-ref', '--short', 'HEAD']);
|
|
737
|
+
const upstream = upstreamOf(state, branch);
|
|
738
|
+
const remote = git(state.source, ['config', `branch.${branch}.remote`]);
|
|
739
|
+
const ref = git(state.source, ['config', `branch.${branch}.merge`]);
|
|
740
|
+
if (remote === '.') throw new Error('A remote-tracking branch is required for update.');
|
|
741
|
+
const before = sourceRevision(state.source).commit;
|
|
742
|
+
if (!apply) {
|
|
743
|
+
const head = run('git', ['-C', state.source, 'ls-remote', remote, ref], { capture: true, timeout: 30_000 }).split('\n')[0]?.split(/\s+/)[0];
|
|
744
|
+
console.log(`Configuration ${branch}: local ${before.slice(0, 7)}; remote ${head ? head.slice(0, 7) : '(no matching ref)'} (not fetched).`);
|
|
745
|
+
return false;
|
|
746
|
+
}
|
|
747
|
+
git(state.source, ['fetch', remote]);
|
|
748
|
+
// Only true divergence blocks the update: the local branch may be ahead of
|
|
749
|
+
// (or equal to) its remote, in which case --ff-only already reports up to date.
|
|
750
|
+
const isAncestor = (earlier, later) => spawnSync('git', ['-C', state.source, 'merge-base', '--is-ancestor', earlier, later],
|
|
751
|
+
{ stdio: 'ignore', timeout: 30_000 }).status === 0;
|
|
752
|
+
if (!isAncestor(before, upstream) && !isAncestor(upstream, before)) {
|
|
753
|
+
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.`);
|
|
754
|
+
}
|
|
755
|
+
git(state.source, ['pull', '--ff-only']);
|
|
756
|
+
const after = sourceRevision(state.source).commit;
|
|
757
|
+
console.log(after === before
|
|
758
|
+
? `Configuration ${branch} is already at ${after.slice(0, 7)}.`
|
|
759
|
+
: `Configuration ${branch} fast-forwarded ${before.slice(0, 7)} -> ${after.slice(0, 7)}.`);
|
|
760
|
+
await validateSource(state);
|
|
761
|
+
return true;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/** `kitto update [--check|--apply]`: source checkout, runtime copy and deployment. */
|
|
765
|
+
export async function update(args = []) {
|
|
766
|
+
if (args.includes('--check') && args.includes('--apply')) throw new Error('Choose either --check or --apply for update.');
|
|
767
|
+
if (args.includes('--include-private') && args.includes('--no-include-private')) throw new Error('Choose either --include-private or --no-include-private for update.');
|
|
768
|
+
const unknown = args.filter(flag => !['--check', '--apply', '--include-private', '--no-include-private'].includes(flag));
|
|
769
|
+
if (unknown.length) throw new Error(`Unknown update option: ${unknown[0]}. Read the Kitto skill.`);
|
|
770
|
+
const apply = args.includes('--apply');
|
|
771
|
+
const includePrivate = args.includes('--include-private') ? true
|
|
772
|
+
: args.includes('--no-include-private') ? false : undefined;
|
|
773
|
+
const home = kittoHome();
|
|
774
|
+
const state = await json(join(home, 'state.json')).catch(error => {
|
|
775
|
+
if (error.code === 'ENOENT') return null;
|
|
776
|
+
throw error;
|
|
777
|
+
});
|
|
778
|
+
if (!state) throw new Error(`Kitto is not set up in ${home}. Run kitto setup first.`);
|
|
779
|
+
if (state.detached || state.removing) throw new Error('Kitto is detached or removal is incomplete. Use setup to reconnect, or finish remove.');
|
|
780
|
+
console.log(`Kitto ${state.version} update${apply ? '' : ' preview (no writes)'}.`);
|
|
781
|
+
hostCliVersions(state);
|
|
782
|
+
const work = async () => {
|
|
783
|
+
// An explicit toggle applies to the preview and is persisted only after the
|
|
784
|
+
// deployment succeeds, because deploy() writes the state on apply.
|
|
785
|
+
if (includePrivate !== undefined) state.includePrivate = includePrivate;
|
|
786
|
+
await backfillSource(state);
|
|
787
|
+
const updated = await updateSource(state, apply);
|
|
788
|
+
if (!updated) {
|
|
789
|
+
if (await present(state.source)) {
|
|
790
|
+
await syncSourceLocation(state, false);
|
|
791
|
+
const plan = await configurationPlan(state);
|
|
792
|
+
await deploy(state, false, plan, packageRoot);
|
|
793
|
+
}
|
|
794
|
+
await refreshRuntime(state, false);
|
|
795
|
+
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.');
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
await syncSourceLocation(state, true);
|
|
799
|
+
// Resolve configuration conflicts before replacing working code.
|
|
800
|
+
const plan = await configurationPlan(state);
|
|
801
|
+
const pending = await refreshRuntime(state, true);
|
|
802
|
+
// The process keeps the code it started with for this deployment; the next
|
|
803
|
+
// Kitto call (and each restarted host) uses the replaced runtime.
|
|
804
|
+
await deploy(state, true, plan, packageRoot);
|
|
805
|
+
await finalizeRuntime(state, pending);
|
|
806
|
+
console.log(`Kitto update complete: runtime ${state.version}, configuration ${sourceRevision(state.source).commit.slice(0, 7)}. Restart native hosts to load new plugin code.`);
|
|
807
|
+
};
|
|
808
|
+
if (apply) await locked(home, work); else await work();
|
|
809
|
+
}
|
|
810
|
+
|
|
421
811
|
function sourceRevision(source) {
|
|
422
812
|
const status = git(source, ['status', '--porcelain', '--branch']).split('\n');
|
|
423
813
|
return {
|
|
@@ -443,6 +833,9 @@ async function cloneSource(home, source, url, ref) {
|
|
|
443
833
|
|
|
444
834
|
export async function setup(options = {}) {
|
|
445
835
|
if (options.global || Object.hasOwn(options, 'workspace') || Object.hasOwn(options, 'workspace-parent')) {
|
|
836
|
+
if (options['include-private'] || options['no-include-private']) {
|
|
837
|
+
throw new Error('--include-private and --no-include-private apply to global setup/update; scoped setup does not sync MCP servers.');
|
|
838
|
+
}
|
|
446
839
|
const { setupScope } = await import('./scope-setup.mjs');
|
|
447
840
|
return setupScope(options);
|
|
448
841
|
}
|
|
@@ -459,15 +852,15 @@ export async function setup(options = {}) {
|
|
|
459
852
|
const baseline = await readState();
|
|
460
853
|
const old = baseline ? JSON.parse(baseline) : {};
|
|
461
854
|
const agents = options.agents ? [...new Set([...(old.agents || []), ...options.agents])]
|
|
462
|
-
: old.agents || Object.keys(hosts).filter(
|
|
855
|
+
: old.agents || Object.keys(hosts).filter(availableHost);
|
|
463
856
|
if (!agents.length) throw new Error('No agent detected. Select --agents pi,codex,dsh; add --install-agents to install missing CLIs.');
|
|
464
|
-
const
|
|
857
|
+
const dshProfile = validateDshProfile(options['dsh-profile'] ?? old.dshProfile ?? 'web');
|
|
858
|
+
if (options['dsh-profile'] && !agents.includes('dsh')) throw new Error('--dsh-profile requires DSH.');
|
|
859
|
+
// The app-managed Desktop profile never installs a Kitto bundle, so it needs no pnpm.
|
|
860
|
+
const installPnpm = agents.includes('dsh') && !isDesktopProfile(dshProfile) && !available('pnpm');
|
|
465
861
|
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
862
|
if (installPnpm) console.log(`Install missing DSH prerequisite: pnpm@${pnpmVersion}`);
|
|
467
863
|
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
864
|
if (old.agents?.includes('dsh') && !old.detached && dshProfile !== (old.dshProfile || 'web')) {
|
|
472
865
|
throw new Error('Detach the existing Kitto integration before selecting a different DSH profile.');
|
|
473
866
|
}
|
|
@@ -482,7 +875,7 @@ export async function setup(options = {}) {
|
|
|
482
875
|
const sameSource = basename(source) === basename(old.source) && sameLocation(dirname(source), dirname(old.source));
|
|
483
876
|
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
877
|
}
|
|
485
|
-
if (!local &&
|
|
878
|
+
if (!local && !isGitUrl(requested)) throw new Error('Source must be an existing checkout or HTTPS/SSH Git URL.');
|
|
486
879
|
let switchTag = false, ownedSource = false;
|
|
487
880
|
const markerPath = bootstrapMarker(source);
|
|
488
881
|
if (options.ref && await present(markerPath)) {
|
|
@@ -508,9 +901,24 @@ export async function setup(options = {}) {
|
|
|
508
901
|
console.log(`Resume setup from Kitto checkout: ${source}`);
|
|
509
902
|
}
|
|
510
903
|
if (local && options.ref && !ownedSource) throw new Error('Switch tags only in a Kitto-created checkout. For your own checkout, use Git.');
|
|
904
|
+
// Remember how to restore a managed checkout if it disappears: its URL and the
|
|
905
|
+
// branch/tag it was set up with. A local checkout records a URL only when Kitto
|
|
906
|
+
// created it (bootstrap marker); user-owned checkouts keep no implicit source.
|
|
907
|
+
const marker = await present(markerPath) ? await json(markerPath).catch(() => undefined) : undefined;
|
|
908
|
+
const sourceUrl = local ? marker?.url : requested;
|
|
909
|
+
// An explicit --ref always wins; otherwise the recorded marker/state ref is
|
|
910
|
+
// replayed, so a lost checkout is never silently restored from another branch.
|
|
911
|
+
const sourceRef = options.ref ?? marker?.ref ?? old.sourceRef ?? null;
|
|
511
912
|
console.log(`Global setup: ${agents.join(', ')}; source: ${requested}; Kitto home: ${home}`);
|
|
512
|
-
|
|
913
|
+
// The app-managed Desktop profile has no CLI prerequisite Kitto may install or verify.
|
|
914
|
+
const checkedAgents = agents.filter(name => !(name === 'dsh' && isDesktopProfile(dshProfile)));
|
|
915
|
+
// A stale host is reported and downgraded, never fatal: --require-baseline
|
|
916
|
+
// restores the strict gate for release verification.
|
|
917
|
+
checkSelectedHosts(checkedAgents, options['install-agents'], { requireBaseline: options['require-baseline'] === true });
|
|
918
|
+
const includePrivate = options['include-private'] === true ? true
|
|
919
|
+
: options['no-include-private'] === true ? false : old.includePrivate === true;
|
|
513
920
|
const state = { ...old, schema: 1, ready: false, detached: false, removing: false, removedAgents: [], source, agents, dshProfile,
|
|
921
|
+
includePrivate, sourceUrl: sourceUrl || old.sourceUrl, sourceRef, pendingRuntime: undefined,
|
|
514
922
|
agentsHome: old.agentsHome || resolve((agents.includes('pi') && process.env.PI_AGENTS_DIR)
|
|
515
923
|
|| (agents.includes('dsh') && process.env.DSH_AGENTS_HOME) || join(homedir(), '.agents')),
|
|
516
924
|
piHome: old.piHome || resolve(process.env.PI_CODING_AGENT_DIR || join(homedir(), '.pi/agent')),
|
|
@@ -526,11 +934,18 @@ export async function setup(options = {}) {
|
|
|
526
934
|
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
935
|
}
|
|
528
936
|
if (agents.includes('dsh')) {
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
937
|
+
if (isDesktopProfile(dshProfile)) {
|
|
938
|
+
// Global-only: the Desktop app owns profiles/desktop, its manifest and its patch.
|
|
939
|
+
console.log(`DSH profile: ${dshProfile} (global-only; managed by the Desktop app)`);
|
|
940
|
+
reportDesktopProbe(probeDesktopProfile({ dshHome: state.dshHome }));
|
|
941
|
+
console.log(desktopProfileNotice);
|
|
942
|
+
} else {
|
|
943
|
+
const builtIn = ['web', 'headless', 'sdk', 'sdk-minimal', 'acp'];
|
|
944
|
+
if (!builtIn.includes(dshProfile) && !await present(join(state.dshHome, 'profiles', dshProfile, 'package.json'))) {
|
|
945
|
+
throw new Error(`Initialize the native DSH profile ${dshProfile} before setup.`);
|
|
946
|
+
}
|
|
947
|
+
console.log(`DSH profile: ${dshProfile}`);
|
|
532
948
|
}
|
|
533
|
-
console.log(`DSH profile: ${dshProfile}`);
|
|
534
949
|
}
|
|
535
950
|
if (agents.includes('pi') && (!(local || resume) || !options['dry-run'])) checkPiTools();
|
|
536
951
|
if (options['dry-run']) {
|
|
@@ -539,7 +954,9 @@ export async function setup(options = {}) {
|
|
|
539
954
|
await validateSource(state);
|
|
540
955
|
await deploy(state, false, undefined, packageRoot);
|
|
541
956
|
}
|
|
542
|
-
console.log(
|
|
957
|
+
console.log(isDesktopProfile(dshProfile)
|
|
958
|
+
? '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.'
|
|
959
|
+
: 'Preview only: clone if needed, persist Kitto runtime, deploy selected configuration and skills, register native integrations. No writes.');
|
|
543
960
|
return;
|
|
544
961
|
}
|
|
545
962
|
await locked(home, async () => {
|
|
@@ -548,13 +965,14 @@ export async function setup(options = {}) {
|
|
|
548
965
|
run('npm', ['install', '--global', `pnpm@${pnpmVersion}`]);
|
|
549
966
|
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
967
|
}
|
|
551
|
-
installMissingHosts(
|
|
968
|
+
installMissingHosts(checkedAgents);
|
|
552
969
|
if (!local && !resume) await cloneSource(home, source, requested, options.ref);
|
|
553
970
|
if (switchTag) {
|
|
554
971
|
if (sourceRevision(source).dirty) throw new Error('Source has local changes. Commit or resolve them before switching tags.');
|
|
555
972
|
git(source, ['fetch', '--no-tags', 'origin', `refs/tags/${options.ref}`]);
|
|
556
973
|
const commit = git(source, ['rev-parse', 'FETCH_HEAD^{commit}']);
|
|
557
974
|
git(source, ['checkout', '--no-overwrite-ignore', '--detach', commit]);
|
|
975
|
+
await atomicJson(bootstrapMarker(source), { ...(await json(bootstrapMarker(source)).catch(() => ({}))), ref: options.ref });
|
|
558
976
|
}
|
|
559
977
|
await validateSource(state);
|
|
560
978
|
const plan = await configurationPlan(state);
|
|
@@ -562,13 +980,22 @@ export async function setup(options = {}) {
|
|
|
562
980
|
await atomicJson(join(home, 'state.json'), state);
|
|
563
981
|
await deploy(state, true, plan);
|
|
564
982
|
});
|
|
565
|
-
console.log(
|
|
983
|
+
console.log(isDesktopProfile(dshProfile)
|
|
984
|
+
? '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.'
|
|
985
|
+
: 'Kitto setup complete. Start your agent with its native command; ask the Kitto skill to maintain configuration.');
|
|
566
986
|
}
|
|
567
987
|
|
|
568
988
|
export async function maintain(args) {
|
|
569
989
|
const [operation = 'status', ...flags] = args;
|
|
570
|
-
|
|
990
|
+
// Host CLI policy is shared with the public kitto command. Import lazily to
|
|
991
|
+
// avoid a module cycle with lib/hosts.mjs.
|
|
992
|
+
if (operation === 'hosts') {
|
|
993
|
+
const { hostsCommand } = await import('./hosts.mjs');
|
|
994
|
+
return hostsCommand(flags);
|
|
995
|
+
}
|
|
996
|
+
const allowed = { status: [], versions: ['--online'], sync: ['--apply'], update: ['--check', '--apply'], export: ['--apply'], deps: ['--apply'], recover: ['--apply'], remove: ['--apply'] };
|
|
571
997
|
if (!allowed[operation] || flags.some(flag => !allowed[operation].includes(flag))) throw new Error('Unsupported maintenance operation or flag. Read the Kitto skill.');
|
|
998
|
+
if (operation === 'update') return update(flags);
|
|
572
999
|
const home = kittoHome(), state = await json(join(home, 'state.json'));
|
|
573
1000
|
const apply = flags.includes('--apply');
|
|
574
1001
|
// These operations must also work when the personal checkout is unavailable.
|
|
@@ -587,24 +1014,13 @@ export async function maintain(args) {
|
|
|
587
1014
|
console.log(JSON.stringify({ ...state, checkout: sourceRevision(state.source), git: git(state.source, ['status', '--short', '--branch']) }, null, 2));
|
|
588
1015
|
await configurationPlan(state);
|
|
589
1016
|
for (const tool of await dependencyPlan(state)) console.log(`dependency ${tool.available ? 'available' : 'missing'}: ${tool.name} (${tool.reason})`);
|
|
1017
|
+
await reportCodeGraphIndexes(state);
|
|
1018
|
+
await printMcpParity(state);
|
|
590
1019
|
if (state.agents.includes('pi')) syncCommand(state, 'status');
|
|
591
1020
|
} else if (operation === 'versions') {
|
|
592
1021
|
console.log(JSON.stringify(await versionReport(state, hosts, pnpmVersion, flags.includes('--online'), treeHash), null, 2));
|
|
593
1022
|
} else {
|
|
594
1023
|
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
1024
|
if (operation === 'deps') await installDependencies(state, apply);
|
|
609
1025
|
else if (operation === 'export') {
|
|
610
1026
|
if (!state.agents.includes('pi')) throw new Error('Pi export requires a Pi installation. Edit shared skills in the source checkout.');
|