@phyzess/kitto 0.0.0-stage → 0.2.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/CHANGELOG.md +42 -0
- package/README.md +32 -2
- package/bin/kitto.mjs +35 -0
- package/bin/maintain.mjs +9 -0
- package/integration/cordis.patch.yml +3 -0
- package/integration/dsh.mjs +21 -0
- package/integration/pi.mjs +14 -0
- package/integration/plugin.json +6 -0
- package/integration/scoped-codex/session-start.mjs +59 -0
- package/integration/scoped-dsh/index.mjs +124 -0
- package/integration/scoped-dsh/native.mjs +8 -0
- package/integration/scoped-pi/index.mjs +62 -0
- package/integration/skills/kitto/SKILL.md +39 -0
- package/lib/dependencies.mjs +178 -0
- package/lib/environment-setup.mjs +43 -0
- package/lib/host-config.mjs +70 -0
- package/lib/kitto.mjs +616 -0
- package/lib/pi_config.py +330 -0
- package/lib/scope-codex.mjs +76 -0
- package/lib/scope-dsh.mjs +92 -0
- package/lib/scope-pi.mjs +41 -0
- package/lib/scope-service.mjs +261 -0
- package/lib/scope-setup.mjs +140 -0
- package/lib/scopes.mjs +51 -0
- package/lib/setup-wizard.mjs +241 -0
- package/lib/update-notice.mjs +26 -0
- package/lib/versions.mjs +139 -0
- package/package.json +16 -4
- package/sync.sh +480 -0
package/lib/kitto.mjs
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
4
|
+
import { cp, mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile, lstat, readlink, realpath } from 'node:fs/promises';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { applyInstructions, hostSkillRoots, instructionPlan } from './host-config.mjs';
|
|
9
|
+
import { dependencyPlan, installDependencies } from './dependencies.mjs';
|
|
10
|
+
import { versionReport } from './versions.mjs';
|
|
11
|
+
|
|
12
|
+
export const packageRoot = fileURLToPath(new URL('../', import.meta.url));
|
|
13
|
+
export const hosts = {
|
|
14
|
+
pi: { package: '@earendil-works/pi-coding-agent', version: '1.5.2', node: '22.19.0' },
|
|
15
|
+
codex: { package: '@openai/codex', version: '0.170.0' },
|
|
16
|
+
dsh: { package: '@deepseek-ai/dsh', version: '0.2.2-rc.1', node: '24.9.0' },
|
|
17
|
+
};
|
|
18
|
+
export const pnpmVersion = '12.21.0'; // Required by the native DSH plugin manager.
|
|
19
|
+
const defaultSource = 'https://github.com/phyzess/kitto.git';
|
|
20
|
+
export const kittoHome = () => {
|
|
21
|
+
// Native hosts do not need to inherit the shell used during setup.
|
|
22
|
+
const installedHome = dirname(resolve(packageRoot));
|
|
23
|
+
return resolve(process.env.KITTO_HOME || (existsSync(join(installedHome, 'state.json')) && resolve(packageRoot) === join(installedHome, 'runtime')
|
|
24
|
+
? installedHome : join(process.env.XDG_DATA_HOME || join(homedir(), '.local/share'), 'kitto')));
|
|
25
|
+
};
|
|
26
|
+
const json = async path => JSON.parse(await readFile(path, 'utf8'));
|
|
27
|
+
const shellQuote = value => `'${value.replaceAll("'", "'\\''")}'`;
|
|
28
|
+
const present = async path => { try { await lstat(path); return true; } catch (e) { if (e.code === 'ENOENT') return false; throw e; } };
|
|
29
|
+
function sameLocation(a, b) {
|
|
30
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
|
31
|
+
const canonical = path => {
|
|
32
|
+
try { return realpathSync(path); } catch (error) {
|
|
33
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return resolve(path);
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
return canonical(a) === canonical(b);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function run(command, args, { capture = false, ...options } = {}) {
|
|
41
|
+
const result = spawnSync(command, args, { encoding: 'utf8', stdio: capture ? 'pipe' : 'inherit', timeout: 600_000, ...options });
|
|
42
|
+
if (result.error || result.status !== 0) throw new Error(`${command} failed: ${result.error?.message || result.stderr?.trim() || `exit ${result.status}`}`);
|
|
43
|
+
return result.stdout?.trim() || '';
|
|
44
|
+
}
|
|
45
|
+
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;
|
|
47
|
+
|
|
48
|
+
export function parseOptions(args) {
|
|
49
|
+
const options = {};
|
|
50
|
+
for (let i = 0; i < args.length; i++) {
|
|
51
|
+
const arg = args[i];
|
|
52
|
+
if (['--dry-run', '--install-agents', '--recover', '--global'].includes(arg)) options[arg.slice(2)] = true;
|
|
53
|
+
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
|
+
else throw new Error(`Unknown option or missing value: ${arg}`);
|
|
55
|
+
}
|
|
56
|
+
if (options.agents) {
|
|
57
|
+
options.agents = [...new Set(options.agents.split(','))];
|
|
58
|
+
if (options.agents.some(name => !hosts[name])) throw new Error('Agents must be pi,codex,dsh.');
|
|
59
|
+
}
|
|
60
|
+
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
|
+
return options;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function atomicJson(path, value) {
|
|
65
|
+
await mkdir(dirname(path), { recursive: true });
|
|
66
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
67
|
+
try {
|
|
68
|
+
await writeFile(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
|
|
69
|
+
await rename(temporary, path);
|
|
70
|
+
} finally { await rm(temporary, { force: true }); }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function locked(home, callback) {
|
|
74
|
+
await mkdir(home, { recursive: true });
|
|
75
|
+
const lock = join(home, '.lock');
|
|
76
|
+
try { await mkdir(lock); } catch (e) {
|
|
77
|
+
if (e.code === 'EEXIST') throw new Error(`Another Kitto operation holds ${lock}. Remove it only after verifying that process has stopped.`);
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
try { return await callback(); } finally { await rm(lock, { recursive: true }); }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function validateSource({ source, agents }) {
|
|
84
|
+
if (git(source, ['rev-parse', '--show-toplevel']) !== await realpath(source)) throw new Error('Source must be the root of a Git checkout.');
|
|
85
|
+
if (!agents.includes('pi')) return;
|
|
86
|
+
const settings = await json(join(source, 'config/pi/settings.json'));
|
|
87
|
+
if (!Array.isArray(settings.packages)) throw new Error('Source lacks config/pi/settings.json packages.');
|
|
88
|
+
await json(join(source, 'config/pi/mcp.json'));
|
|
89
|
+
await readFile(join(source, 'config/pi/AGENTS.md'));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
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.`);
|
|
100
|
+
}
|
|
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})`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function checkSelectedHosts(agents, installAgents) {
|
|
107
|
+
for (const name of agents) {
|
|
108
|
+
if (!available(name)) {
|
|
109
|
+
if (!installAgents) throw new Error(`${name} is missing. Install it natively or add --install-agents (pins ${hosts[name].version}).`);
|
|
110
|
+
const requiredNode = hosts[name].node;
|
|
111
|
+
if (requiredNode && requiredNode.localeCompare(process.versions.node, 'en', { numeric: true }) > 0) {
|
|
112
|
+
throw new Error(`Installing ${name} through npm requires Node >=${requiredNode}.`);
|
|
113
|
+
}
|
|
114
|
+
console.log(`Install missing CLI: ${hosts[name].package}@${hosts[name].version}${name === 'dsh' ? ' (prerelease)' : ''}`);
|
|
115
|
+
} else checkHost(name);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function installMissingHosts(agents) {
|
|
120
|
+
for (const name of agents) if (!available(name)) {
|
|
121
|
+
run('npm', ['install', '--global', `${hosts[name].package}@${hosts[name].version}`]);
|
|
122
|
+
checkHost(name);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function replaceRuntime(home, next) {
|
|
127
|
+
const runtime = join(home, 'runtime'), replacing = join(home, 'runtime.replacing');
|
|
128
|
+
// Repair a directory switch interrupted before the new runtime was in place.
|
|
129
|
+
if (!await present(runtime) && await present(replacing)) await rename(replacing, runtime);
|
|
130
|
+
await rm(replacing, { recursive: true, force: true });
|
|
131
|
+
if (await present(runtime)) await rename(runtime, replacing);
|
|
132
|
+
try { await rename(next, runtime); } catch (error) {
|
|
133
|
+
if (await present(replacing)) await rename(replacing, runtime);
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
await rm(replacing, { recursive: true, force: true });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function installRuntime(home, old) {
|
|
140
|
+
// A whitelist, shared with npm's files list. Never copy personal configuration.
|
|
141
|
+
const next = join(home, 'runtime.next');
|
|
142
|
+
const runtime = join(home, 'runtime');
|
|
143
|
+
const previous = join(home, 'runtime.previous');
|
|
144
|
+
if (resolve(packageRoot) === runtime) return runtime;
|
|
145
|
+
await rm(next, { recursive: true, force: true });
|
|
146
|
+
await mkdir(next);
|
|
147
|
+
for (const name of ['package.json', 'bin', 'lib', 'integration', 'sync.sh', 'CHANGELOG.md']) {
|
|
148
|
+
await cp(join(packageRoot, name), join(next, name), {
|
|
149
|
+
recursive: true, filter: path => !path.includes('__pycache__') && !path.endsWith('.pyc'),
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
const skillPath = join(next, 'integration/skills/kitto/SKILL.md');
|
|
153
|
+
await writeFile(skillPath, (await readFile(skillPath, 'utf8')).replaceAll('KITTO_RUNNER', shellQuote(join(runtime, 'bin/maintain.mjs'))));
|
|
154
|
+
const hash = await treeHash(next, true);
|
|
155
|
+
if (await present(runtime) && await treeHash(runtime, true) === hash) {
|
|
156
|
+
await rm(next, { recursive: true });
|
|
157
|
+
return runtime;
|
|
158
|
+
}
|
|
159
|
+
// A retry after failure must not replace the last known-good checkpoint.
|
|
160
|
+
const currentIsVerified = await present(runtime) && (old.runtimeHash
|
|
161
|
+
? await treeHash(runtime, true) === old.runtimeHash
|
|
162
|
+
: (await json(join(runtime, 'package.json'))).version === old.version);
|
|
163
|
+
if (old.ready && !old.detached && currentIsVerified) {
|
|
164
|
+
const staging = join(home, 'checkpoint.next');
|
|
165
|
+
await rm(staging, { recursive: true, force: true });
|
|
166
|
+
await cp(runtime, staging, { recursive: true });
|
|
167
|
+
await rm(previous, { recursive: true, force: true });
|
|
168
|
+
await rename(staging, previous);
|
|
169
|
+
await atomicJson(join(home, 'runtime.previous.json'), {
|
|
170
|
+
version: (await json(join(previous, 'package.json'))).version, dshProfile: old.dshProfile || 'web', hash: await treeHash(previous, true),
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
await replaceRuntime(home, next);
|
|
174
|
+
return runtime;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function treeHash(path, ignorePythonCache = false) {
|
|
178
|
+
const hash = createHash('sha256');
|
|
179
|
+
async function walk(directory, relative = '') {
|
|
180
|
+
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
181
|
+
if (ignorePythonCache && (entry.name === '__pycache__' || entry.name.endsWith('.pyc'))) continue;
|
|
182
|
+
const name = join(relative, entry.name), full = join(directory, entry.name);
|
|
183
|
+
if (entry.isDirectory()) { hash.update(`dir:${name}\0`); await walk(full, name); }
|
|
184
|
+
else if (entry.isFile()) { hash.update(`file:${name}\0`); hash.update(await readFile(full)); }
|
|
185
|
+
else throw Object.assign(new Error(`Unsupported symlink or special file in skill: ${full}`), {
|
|
186
|
+
code: 'KITTO_UNSUPPORTED_SKILL_ENTRY',
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
await walk(path);
|
|
191
|
+
return hash.digest('hex');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function existingSkillAction(target, source, nextHash, previous, keepUnowned) {
|
|
195
|
+
const stat = await lstat(target);
|
|
196
|
+
if (stat.isSymbolicLink()) {
|
|
197
|
+
if (sameLocation(resolve(dirname(target), await readlink(target)), source)) return 'linked';
|
|
198
|
+
if (keepUnowned) return 'keep';
|
|
199
|
+
throw new Error(`Skill conflict: ${target} links elsewhere. Preserved.`);
|
|
200
|
+
}
|
|
201
|
+
if (keepUnowned && !stat.isDirectory()) return 'keep';
|
|
202
|
+
const current = await treeHash(target).catch(error => {
|
|
203
|
+
if (keepUnowned && error.code === 'KITTO_UNSUPPORTED_SKILL_ENTRY') return null;
|
|
204
|
+
throw error;
|
|
205
|
+
});
|
|
206
|
+
if (current === nextHash) return 'same';
|
|
207
|
+
if (current === previous) return 'copy';
|
|
208
|
+
if (keepUnowned) return 'keep';
|
|
209
|
+
throw new Error(`Skill conflict: ${target} differs from the source and last deployment. Preserved.`);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function skillPlan(root, destination, owned = {}, keepExisting = false, kept = []) {
|
|
213
|
+
const plans = [];
|
|
214
|
+
const entries = await present(root) ? await readdir(root, { withFileTypes: true }) : [];
|
|
215
|
+
for (const entry of entries) {
|
|
216
|
+
if (!entry.isDirectory() || !existsSync(join(root, entry.name, 'SKILL.md'))) continue;
|
|
217
|
+
const source = join(root, entry.name), target = join(destination, entry.name);
|
|
218
|
+
const nextHash = await treeHash(source);
|
|
219
|
+
let action = 'copy';
|
|
220
|
+
if (await present(target)) {
|
|
221
|
+
const keepUnowned = keepExisting && !Object.hasOwn(owned, entry.name);
|
|
222
|
+
action = keepUnowned && kept.includes(entry.name) ? 'keep'
|
|
223
|
+
: await existingSkillAction(target, source, nextHash, owned[entry.name], keepUnowned);
|
|
224
|
+
}
|
|
225
|
+
plans.push({ name: entry.name, source, target, hash: nextHash, action });
|
|
226
|
+
}
|
|
227
|
+
for (const name of Object.keys(owned)) {
|
|
228
|
+
if (plans.some(plan => plan.name === name)) continue;
|
|
229
|
+
const target = join(destination, name);
|
|
230
|
+
if (await present(target)) {
|
|
231
|
+
if ((await lstat(target)).isSymbolicLink() || await treeHash(target) !== owned[name]) throw new Error(`Removed skill has local changes: ${target}. Preserved.`);
|
|
232
|
+
plans.push({ name, target, action: 'remove' });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
for (const name of kept) {
|
|
236
|
+
if (plans.some(plan => plan.name === name)) continue;
|
|
237
|
+
const target = join(destination, name);
|
|
238
|
+
if (await present(target)) plans.push({ name, target, action: 'keep' });
|
|
239
|
+
}
|
|
240
|
+
return plans;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function checkPiTools() {
|
|
244
|
+
for (const name of ['bash', 'python3']) if (!available(name)) throw new Error(`Pi configuration requires ${name}.`);
|
|
245
|
+
run('python3', ['-c', 'import sys; assert sys.version_info >= (3,10), "Python >=3.10 required for Pi"'], { capture: true });
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function syncCommand(state, command, apply = false, codeRoot = join(kittoHome(), 'runtime')) {
|
|
249
|
+
checkPiTools();
|
|
250
|
+
return run('bash', [join(codeRoot, 'sync.sh'), command, ...(!apply && command !== 'status' ? ['--dry-run'] : [])], {
|
|
251
|
+
env: { ...process.env, KITTO_CONFIG_ROOT: state.source, KITTO_SHARED_SKILLS_MANAGED: '1',
|
|
252
|
+
PI_CODING_AGENT_DIR: state.piHome, PI_AGENTS_DIR: state.agentsHome },
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function connect(state) {
|
|
257
|
+
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.');
|
|
259
|
+
for (const name of state.agents) {
|
|
260
|
+
if (name === 'pi') run('pi', ['install', runtime], { env: { ...process.env, PI_CODING_AGENT_DIR: state.piHome } });
|
|
261
|
+
if (name === 'codex') {
|
|
262
|
+
await mkdir(state.codexHome, { recursive: true });
|
|
263
|
+
const marketplace = join(home, '.agents/plugins/marketplace.json');
|
|
264
|
+
await atomicJson(marketplace, { name: 'phyzess-kitto', plugins: [{ name: 'kitto',
|
|
265
|
+
source: { source: 'local', path: './runtime/integration' },
|
|
266
|
+
policy: { installation: 'AVAILABLE', authentication: 'ON_INSTALL' }, category: 'Productivity' }] });
|
|
267
|
+
const env = { ...process.env, CODEX_HOME: state.codexHome };
|
|
268
|
+
run('codex', ['plugin', 'marketplace', 'add', home], { env });
|
|
269
|
+
run('codex', ['plugin', 'add', 'kitto@phyzess-kitto'], { env });
|
|
270
|
+
}
|
|
271
|
+
if (name === 'dsh') {
|
|
272
|
+
await mkdir(state.dshHome, { recursive: true });
|
|
273
|
+
run('dsh', ['plugin', '--profile', state.dshProfile || 'web', 'add', runtime], {
|
|
274
|
+
env: { ...process.env, DSH_HOME: state.dshHome, DSH_AGENTS_HOME: state.agentsHome },
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function configurationPlan(state) {
|
|
281
|
+
const groups = [{ name: 'shared', source: join(state.source, 'skills'), target: join(state.agentsHome, 'skills') },
|
|
282
|
+
...hostSkillRoots(state)];
|
|
283
|
+
for (const group of groups) {
|
|
284
|
+
const owned = group.name === 'shared' ? state.skills : state.hostSkills?.[group.name];
|
|
285
|
+
group.plans = await skillPlan(group.source, group.target, owned, state.keepExistingSkills, state.keptSkills?.[group.name]);
|
|
286
|
+
for (const plan of group.plans) console.log(`skill ${plan.action}: ${plan.name} (${group.name})`);
|
|
287
|
+
}
|
|
288
|
+
const instructions = await instructionPlan(state);
|
|
289
|
+
for (const plan of instructions) console.log(`instructions ${plan.before === plan.after ? 'same' : 'sync'}: ${plan.target}`);
|
|
290
|
+
return { groups, instructions };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async function deploy(state, apply, plan = undefined, codeRoot = undefined) {
|
|
294
|
+
const { groups, instructions } = plan ?? await configurationPlan(state);
|
|
295
|
+
const deployment = apply ? sourceRevision(state.source) : undefined;
|
|
296
|
+
if (state.agents.includes('pi')) syncCommand(state, 'pull', apply, codeRoot);
|
|
297
|
+
if (!apply) {
|
|
298
|
+
if (!state.ready) console.log(`Connect native Kitto integrations: ${state.agents.join(', ')}`);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
await applyInstructions(state, instructions);
|
|
302
|
+
state.hostSkills ||= {};
|
|
303
|
+
for (const { name, plans } of groups) {
|
|
304
|
+
const owned = {};
|
|
305
|
+
const kept = [];
|
|
306
|
+
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 });
|
|
310
|
+
}
|
|
311
|
+
if (plan.action === 'keep') kept.push(plan.name);
|
|
312
|
+
else if (plan.action !== 'remove') owned[plan.name] = plan.hash;
|
|
313
|
+
}
|
|
314
|
+
if (kept.length) {
|
|
315
|
+
state.keptSkills ||= {};
|
|
316
|
+
state.keptSkills[name] = kept;
|
|
317
|
+
} else if (state.keptSkills) delete state.keptSkills[name];
|
|
318
|
+
if (name === 'shared') state.skills = owned;
|
|
319
|
+
else state.hostSkills[name] = owned;
|
|
320
|
+
}
|
|
321
|
+
// Save deployment ownership before native managers, so retry is recoverable.
|
|
322
|
+
await atomicJson(join(kittoHome(), 'state.json'), state);
|
|
323
|
+
if (!state.ready) {
|
|
324
|
+
await connect(state);
|
|
325
|
+
state.runtimeHash = await treeHash(join(kittoHome(), 'runtime'), true);
|
|
326
|
+
}
|
|
327
|
+
state.deployed = deployment;
|
|
328
|
+
state.ready = true;
|
|
329
|
+
await atomicJson(join(kittoHome(), 'state.json'), state);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function recover(state, apply) {
|
|
333
|
+
if (state.detached || state.removing) throw new Error('Kitto integrations are being removed or already detached. Use setup to reconnect them.');
|
|
334
|
+
const home = kittoHome(), previous = join(home, 'runtime.previous');
|
|
335
|
+
if (!await present(join(home, 'runtime.previous.json'))) throw new Error('No verified runtime checkpoint. Rerun setup with a known working package version.');
|
|
336
|
+
const checkpoint = await json(join(home, 'runtime.previous.json'));
|
|
337
|
+
if (state.agents.includes('dsh') && (state.dshProfile || 'web') !== (checkpoint.dshProfile || 'web')) {
|
|
338
|
+
throw new Error('The runtime checkpoint was verified with a different DSH profile.');
|
|
339
|
+
}
|
|
340
|
+
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.`);
|
|
342
|
+
if (!apply) return;
|
|
343
|
+
state.ready = false;
|
|
344
|
+
await atomicJson(join(home, 'state.json'), state);
|
|
345
|
+
if (!await present(join(home, 'runtime')) || await treeHash(join(home, 'runtime'), true) !== checkpoint.hash) {
|
|
346
|
+
const next = join(home, 'runtime.next');
|
|
347
|
+
await rm(next, { recursive: true, force: true });
|
|
348
|
+
await cp(previous, next, { recursive: true });
|
|
349
|
+
await replaceRuntime(home, next);
|
|
350
|
+
}
|
|
351
|
+
state.version = checkpoint.version;
|
|
352
|
+
await atomicJson(join(home, 'state.json'), state);
|
|
353
|
+
await connect(state);
|
|
354
|
+
state.runtimeHash = checkpoint.hash;
|
|
355
|
+
state.ready = true;
|
|
356
|
+
await atomicJson(join(home, 'state.json'), state);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async function removeIntegration(state, name, apply) {
|
|
360
|
+
const home = kittoHome(), runtime = join(home, 'runtime');
|
|
361
|
+
if (name === 'pi') {
|
|
362
|
+
const settings = join(state.piHome, 'settings.json');
|
|
363
|
+
const data = await present(settings) ? await json(settings) : {};
|
|
364
|
+
const owned = value => typeof value === 'string' && (value.startsWith('.') || value.startsWith('/')) && sameLocation(resolve(state.piHome, value), runtime);
|
|
365
|
+
if ((data.packages || []).some(entry => owned(typeof entry === 'string' ? entry : entry.source))) {
|
|
366
|
+
if (apply) run('pi', ['remove', runtime], { env: { ...process.env, PI_CODING_AGENT_DIR: state.piHome } });
|
|
367
|
+
}
|
|
368
|
+
// The old Pi merge may have remembered this path as a machine-only package.
|
|
369
|
+
const cache = join(state.source, 'config/pi/local/packages.txt');
|
|
370
|
+
if (apply && await present(cache)) {
|
|
371
|
+
const before = await readFile(cache, 'utf8');
|
|
372
|
+
const after = before.split('\n').filter(line => !owned(line.trim())).join('\n');
|
|
373
|
+
if (after !== before) await writeFile(cache, after);
|
|
374
|
+
}
|
|
375
|
+
} else if (name === 'codex') {
|
|
376
|
+
const env = { ...process.env, CODEX_HOME: state.codexHome };
|
|
377
|
+
if (!await present(state.codexHome)) return;
|
|
378
|
+
const markets = JSON.parse(run('codex', ['plugin', 'marketplace', 'list', '--json'], { env, capture: true }));
|
|
379
|
+
const market = markets.marketplaces.find(item => item.name === 'phyzess-kitto');
|
|
380
|
+
if (market && !sameLocation(market.root, home)) throw new Error('The phyzess-kitto marketplace now belongs to another location. Preserved.');
|
|
381
|
+
const plugins = JSON.parse(run('codex', ['plugin', 'list', '--json'], { env, capture: true }));
|
|
382
|
+
if (plugins.installed.some(item => item.marketplaceName === 'phyzess-kitto' && item.pluginId !== 'kitto@phyzess-kitto')) {
|
|
383
|
+
throw new Error('The Kitto marketplace contains other installed plugins. Preserved; detach them or move them to their own marketplace first.');
|
|
384
|
+
}
|
|
385
|
+
const plugin = plugins.installed.find(item => item.pluginId === 'kitto@phyzess-kitto');
|
|
386
|
+
if (plugin && (plugin.source?.source !== 'local' || !sameLocation(plugin.source.path, join(runtime, 'integration')))) {
|
|
387
|
+
throw new Error('The Codex Kitto plugin now comes from another source. Preserved.');
|
|
388
|
+
}
|
|
389
|
+
if (apply && plugin) run('codex', ['plugin', 'remove', 'kitto@phyzess-kitto'], { env });
|
|
390
|
+
if (apply && market) run('codex', ['plugin', 'marketplace', 'remove', 'phyzess-kitto'], { env });
|
|
391
|
+
} else if (name === 'dsh') {
|
|
392
|
+
const manifest = join(state.dshHome, 'profiles', state.dshProfile || 'web', 'package.json');
|
|
393
|
+
if (!await present(manifest)) return;
|
|
394
|
+
const profile = await json(manifest), dependency = profile.dependencies?.['@phyzess/kitto'];
|
|
395
|
+
if (dependency && (!dependency.startsWith('link:') || !sameLocation(resolve(dirname(manifest), dependency.slice(5)), runtime))) throw new Error('DSH Kitto dependency now comes from another source. Preserved.');
|
|
396
|
+
if (dependency || profile.dsh?.profile?.bundles?.includes('@phyzess/kitto')) {
|
|
397
|
+
if (!available('pnpm')) throw new Error('DSH native removal requires pnpm on PATH. Restore pnpm before retrying removal.');
|
|
398
|
+
if (apply) run('dsh', ['plugin', '--profile', state.dshProfile || 'web', 'remove', '@phyzess/kitto'], { env: { ...process.env, DSH_HOME: state.dshHome } });
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async function remove(state, apply) {
|
|
404
|
+
console.log(`Detach Kitto from ${state.agents.join(', ')}. Keep configuration, shared skills, agent CLIs and Kitto files for recovery/reinstallation.`);
|
|
405
|
+
// Inspect every remaining host before making any change.
|
|
406
|
+
const remaining = state.agents.filter(name => !(state.removedAgents || []).includes(name));
|
|
407
|
+
for (const name of remaining) await removeIntegration(state, name, false);
|
|
408
|
+
if (!apply) return;
|
|
409
|
+
const path = join(kittoHome(), 'state.json');
|
|
410
|
+
state.ready = false; state.removing = true;
|
|
411
|
+
await atomicJson(path, state);
|
|
412
|
+
for (const name of remaining) {
|
|
413
|
+
await removeIntegration(state, name, true);
|
|
414
|
+
state.removedAgents = [...(state.removedAgents || []), name];
|
|
415
|
+
await atomicJson(path, state);
|
|
416
|
+
}
|
|
417
|
+
state.removing = false; state.detached = true;
|
|
418
|
+
await atomicJson(path, state);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function sourceRevision(source) {
|
|
422
|
+
const status = git(source, ['status', '--porcelain', '--branch']).split('\n');
|
|
423
|
+
return {
|
|
424
|
+
commit: git(source, ['rev-parse', 'HEAD']),
|
|
425
|
+
dirty: status.length > 1,
|
|
426
|
+
detached: status[0] === '## HEAD (no branch)',
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const bootstrapMarker = source => join(source, '.git', 'kitto-bootstrap.json');
|
|
431
|
+
|
|
432
|
+
async function cloneSource(home, source, url, ref) {
|
|
433
|
+
const staging = await mkdtemp(join(home, 'config.clone-'));
|
|
434
|
+
try {
|
|
435
|
+
run('git', ['clone', ...(ref ? ['--branch', ref] : []), '--', url, staging]);
|
|
436
|
+
await atomicJson(bootstrapMarker(staging), { url, ref: ref ?? null });
|
|
437
|
+
if (await present(source)) throw new Error(`Configuration destination already exists: ${source}`);
|
|
438
|
+
await rename(staging, source);
|
|
439
|
+
} finally {
|
|
440
|
+
await rm(staging, { recursive: true, force: true });
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export async function setup(options = {}) {
|
|
445
|
+
if (options.global || Object.hasOwn(options, 'workspace') || Object.hasOwn(options, 'workspace-parent')) {
|
|
446
|
+
const { setupScope } = await import('./scope-setup.mjs');
|
|
447
|
+
return setupScope(options);
|
|
448
|
+
}
|
|
449
|
+
if (options['dsh-service']) throw new Error('--dsh-service requires --workspace PATH.');
|
|
450
|
+
const home = kittoHome(), statePath = join(home, 'state.json');
|
|
451
|
+
if (options.recover) {
|
|
452
|
+
const work = async () => recover(await json(statePath), !options['dry-run']);
|
|
453
|
+
return options['dry-run'] ? work() : locked(home, work);
|
|
454
|
+
}
|
|
455
|
+
const readState = () => readFile(statePath, 'utf8').catch(error => {
|
|
456
|
+
if (error.code === 'ENOENT') return null;
|
|
457
|
+
throw error;
|
|
458
|
+
});
|
|
459
|
+
const baseline = await readState();
|
|
460
|
+
const old = baseline ? JSON.parse(baseline) : {};
|
|
461
|
+
const agents = options.agents ? [...new Set([...(old.agents || []), ...options.agents])]
|
|
462
|
+
: old.agents || Object.keys(hosts).filter(available);
|
|
463
|
+
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');
|
|
465
|
+
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
|
+
if (installPnpm) console.log(`Install missing DSH prerequisite: pnpm@${pnpmVersion}`);
|
|
467
|
+
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
|
+
if (old.agents?.includes('dsh') && !old.detached && dshProfile !== (old.dshProfile || 'web')) {
|
|
472
|
+
throw new Error('Detach the existing Kitto integration before selecting a different DSH profile.');
|
|
473
|
+
}
|
|
474
|
+
const requested = options.source || old.source || defaultSource;
|
|
475
|
+
const local = existsSync(requested);
|
|
476
|
+
const source = local ? await realpath(requested) : join(await realpath(home).catch(error => {
|
|
477
|
+
if (error.code === 'ENOENT') return home;
|
|
478
|
+
throw error;
|
|
479
|
+
}), 'config');
|
|
480
|
+
if (old.source && source !== old.source) {
|
|
481
|
+
// A new Kitto home may have been recorded before its parent aliases were resolved.
|
|
482
|
+
const sameSource = basename(source) === basename(old.source) && sameLocation(dirname(source), dirname(old.source));
|
|
483
|
+
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
|
+
}
|
|
485
|
+
if (!local && !/^(https:\/\/|ssh:\/\/|git@)/.test(requested)) throw new Error('Source must be an existing checkout or HTTPS/SSH Git URL.');
|
|
486
|
+
let switchTag = false, ownedSource = false;
|
|
487
|
+
const markerPath = bootstrapMarker(source);
|
|
488
|
+
if (options.ref && await present(markerPath)) {
|
|
489
|
+
const marker = await json(markerPath);
|
|
490
|
+
const origin = git(source, ['config', '--local', '--get', 'remote.origin.url']);
|
|
491
|
+
ownedSource = (local || requested === marker.url) && origin === marker.url;
|
|
492
|
+
switchTag = ownedSource && (marker.ref !== options.ref || (Boolean(old.source)
|
|
493
|
+
&& git(source, ['rev-parse', '--abbrev-ref', 'HEAD']) !== options.ref));
|
|
494
|
+
if (switchTag) {
|
|
495
|
+
if (!local && await realpath(source) !== source) throw new Error('Kitto checkout is a symlink. Preserved.');
|
|
496
|
+
git(source, ['check-ref-format', `refs/tags/${options.ref}`]);
|
|
497
|
+
if (sourceRevision(source).dirty) throw new Error('Source has local changes. Commit or resolve them before switching tags.');
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
let resume = false;
|
|
501
|
+
if (!local && await present(source)) {
|
|
502
|
+
if (await present(bootstrapMarker(source)) && await realpath(source) === source) {
|
|
503
|
+
const marker = await json(bootstrapMarker(source));
|
|
504
|
+
resume = marker.url === requested && (switchTag || marker.ref === (options.ref ?? null))
|
|
505
|
+
&& git(source, ['config', '--local', '--get', 'remote.origin.url']) === requested;
|
|
506
|
+
}
|
|
507
|
+
if (!resume) throw new Error(`Unregistered checkout already exists at ${source}. Inspect it and rerun with --source ${shellQuote(source)}.`);
|
|
508
|
+
console.log(`Resume setup from Kitto checkout: ${source}`);
|
|
509
|
+
}
|
|
510
|
+
if (local && options.ref && !ownedSource) throw new Error('Switch tags only in a Kitto-created checkout. For your own checkout, use Git.');
|
|
511
|
+
console.log(`Global setup: ${agents.join(', ')}; source: ${requested}; Kitto home: ${home}`);
|
|
512
|
+
checkSelectedHosts(agents, options['install-agents']);
|
|
513
|
+
const state = { ...old, schema: 1, ready: false, detached: false, removing: false, removedAgents: [], source, agents, dshProfile,
|
|
514
|
+
agentsHome: old.agentsHome || resolve((agents.includes('pi') && process.env.PI_AGENTS_DIR)
|
|
515
|
+
|| (agents.includes('dsh') && process.env.DSH_AGENTS_HOME) || join(homedir(), '.agents')),
|
|
516
|
+
piHome: old.piHome || resolve(process.env.PI_CODING_AGENT_DIR || join(homedir(), '.pi/agent')),
|
|
517
|
+
codexHome: old.codexHome || resolve(process.env.CODEX_HOME || join(homedir(), '.codex')),
|
|
518
|
+
dshHome: old.dshHome || resolve(process.env.DSH_HOME || join(homedir(), '.dsh')),
|
|
519
|
+
version: (await json(join(packageRoot, 'package.json'))).version,
|
|
520
|
+
};
|
|
521
|
+
if (options.keepExistingSkills === true) state.keepExistingSkills = true;
|
|
522
|
+
if (agents.includes('codex') && state.agentsHome !== resolve(homedir(), '.agents')) {
|
|
523
|
+
throw new Error('Codex discovers shared skills in ~/.agents. Use that common root for PI_AGENTS_DIR / DSH_AGENTS_HOME when selecting Codex.');
|
|
524
|
+
}
|
|
525
|
+
if (agents.includes('dsh') && process.env.DSH_AGENTS_HOME && resolve(process.env.DSH_AGENTS_HOME) !== state.agentsHome) {
|
|
526
|
+
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
|
+
}
|
|
528
|
+
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.`);
|
|
532
|
+
}
|
|
533
|
+
console.log(`DSH profile: ${dshProfile}`);
|
|
534
|
+
}
|
|
535
|
+
if (agents.includes('pi') && (!(local || resume) || !options['dry-run'])) checkPiTools();
|
|
536
|
+
if (options['dry-run']) {
|
|
537
|
+
if (switchTag) console.log(`Would switch the Kitto checkout to tag ${options.ref} and deploy it.`);
|
|
538
|
+
else if (local || resume) {
|
|
539
|
+
await validateSource(state);
|
|
540
|
+
await deploy(state, false, undefined, packageRoot);
|
|
541
|
+
}
|
|
542
|
+
console.log('Preview only: clone if needed, persist Kitto runtime, deploy selected configuration and skills, register native integrations. No writes.');
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
await locked(home, async () => {
|
|
546
|
+
if (await readState() !== baseline) throw new Error('Kitto installation changed during setup. Run the same command again.');
|
|
547
|
+
if (installPnpm) {
|
|
548
|
+
run('npm', ['install', '--global', `pnpm@${pnpmVersion}`]);
|
|
549
|
+
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
|
+
}
|
|
551
|
+
installMissingHosts(agents);
|
|
552
|
+
if (!local && !resume) await cloneSource(home, source, requested, options.ref);
|
|
553
|
+
if (switchTag) {
|
|
554
|
+
if (sourceRevision(source).dirty) throw new Error('Source has local changes. Commit or resolve them before switching tags.');
|
|
555
|
+
git(source, ['fetch', '--no-tags', 'origin', `refs/tags/${options.ref}`]);
|
|
556
|
+
const commit = git(source, ['rev-parse', 'FETCH_HEAD^{commit}']);
|
|
557
|
+
git(source, ['checkout', '--no-overwrite-ignore', '--detach', commit]);
|
|
558
|
+
}
|
|
559
|
+
await validateSource(state);
|
|
560
|
+
const plan = await configurationPlan(state);
|
|
561
|
+
await installRuntime(home, old);
|
|
562
|
+
await atomicJson(join(home, 'state.json'), state);
|
|
563
|
+
await deploy(state, true, plan);
|
|
564
|
+
});
|
|
565
|
+
console.log('Kitto setup complete. Start your agent with its native command; ask the Kitto skill to maintain configuration.');
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
export async function maintain(args) {
|
|
569
|
+
const [operation = 'status', ...flags] = args;
|
|
570
|
+
const allowed = { status: [], versions: ['--online'], sync: ['--apply'], update: ['--apply'], export: ['--apply'], deps: ['--apply'], recover: ['--apply'], remove: ['--apply'] };
|
|
571
|
+
if (!allowed[operation] || flags.some(flag => !allowed[operation].includes(flag))) throw new Error('Unsupported maintenance operation or flag. Read the Kitto skill.');
|
|
572
|
+
const home = kittoHome(), state = await json(join(home, 'state.json'));
|
|
573
|
+
const apply = flags.includes('--apply');
|
|
574
|
+
// These operations must also work when the personal checkout is unavailable.
|
|
575
|
+
if (operation === 'recover' || operation === 'remove') {
|
|
576
|
+
const work = () => operation === 'recover' ? recover(state, apply) : remove(state, apply);
|
|
577
|
+
if (apply) await locked(home, work); else await work();
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
if (operation === 'status' && (state.detached || state.removing || !await present(state.source))) {
|
|
581
|
+
console.log(JSON.stringify(state, null, 2));
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
if (state.detached || state.removing) throw new Error('Kitto is detached or removal is incomplete. Use setup to reconnect, or finish remove.');
|
|
585
|
+
await validateSource(state);
|
|
586
|
+
if (operation === 'status') {
|
|
587
|
+
console.log(JSON.stringify({ ...state, checkout: sourceRevision(state.source), git: git(state.source, ['status', '--short', '--branch']) }, null, 2));
|
|
588
|
+
await configurationPlan(state);
|
|
589
|
+
for (const tool of await dependencyPlan(state)) console.log(`dependency ${tool.available ? 'available' : 'missing'}: ${tool.name} (${tool.reason})`);
|
|
590
|
+
if (state.agents.includes('pi')) syncCommand(state, 'status');
|
|
591
|
+
} else if (operation === 'versions') {
|
|
592
|
+
console.log(JSON.stringify(await versionReport(state, hosts, pnpmVersion, flags.includes('--online'), treeHash), null, 2));
|
|
593
|
+
} else {
|
|
594
|
+
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
|
+
if (operation === 'deps') await installDependencies(state, apply);
|
|
609
|
+
else if (operation === 'export') {
|
|
610
|
+
if (!state.agents.includes('pi')) throw new Error('Pi export requires a Pi installation. Edit shared skills in the source checkout.');
|
|
611
|
+
syncCommand(state, 'push', apply);
|
|
612
|
+
} else await deploy(state, apply);
|
|
613
|
+
};
|
|
614
|
+
if (apply) await locked(home, work); else await work();
|
|
615
|
+
}
|
|
616
|
+
}
|