@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 ADDED
@@ -0,0 +1,42 @@
1
+ # Kitto
2
+
3
+ ## 0.2.0
4
+
5
+ - Guide users through host selection, configuration sources, dependencies, preview and installation in one interactive setup.
6
+ - Share global and workspace instructions and skills across Pi, Codex and DSH, including workspaces created after setup.
7
+ - Configure an active DSH system service under its own account from the same wizard.
8
+ - Preserve conflicting unowned skills during guided setup and subsequent synchronization.
9
+
10
+ ## 0.1.1
11
+
12
+ - Document setup, synchronization and tag-pinned configuration for Pi, Codex and DSH.
13
+ - Use Node.js 26 LTS for release checks and CI.
14
+ - Validate, tag and publish release snapshots with `npm run release`.
15
+ - Allow switching configuration tags when the Kitto home path uses a filesystem alias.
16
+
17
+ ## 0.1.0
18
+
19
+ - Pin the Pi extensions and Context7 package used by the configuration snapshot.
20
+ - Record the configured and last deployed revisions, and switch managed checkouts to explicit Git tags.
21
+ - Declare tools in the configuration repository and report shared versus machine-local changes.
22
+
23
+ - Scope configuration validation and prerequisites to the selected agent. Codex and DSH maintenance no longer needs Python or Pi files.
24
+ - Sync user rules and host-specific skills for Codex and DSH. Remember the selected DSH CLI profile.
25
+ - Plan tool dependencies from enabled Pi MCPs and shared skills. Give optional CodeGraph workflows a native-tool fallback.
26
+ - Report selected host versions, native plugins and bundles, and the actual configured MCP launch versions.
27
+
28
+ - Resume a Kitto-owned checkout after a failed first setup.
29
+ - Summarize dependency readiness and report incomplete managed installs.
30
+ - Keep the last working code checkpoint through failed installation retries.
31
+ - Add previewable code recovery and resumable native integration removal.
32
+ - Keep personal configuration, shared skills and installed agent CLIs in place.
33
+ - Provide `setup --recover` when the installed maintenance runner cannot start.
34
+ - Check DSH's pnpm prerequisite before writes; install it when missing with `--install-agents`.
35
+ - Recognize native registration paths through filesystem aliases without weakening foreign-source checks.
36
+
37
+ ## 0.1.0-dev.0
38
+
39
+ - Add global setup and an on-demand maintenance skill for Pi, Codex and DSH.
40
+ - Reuse the Pi configuration merge/export implementation and version inventory.
41
+ - Keep personal configuration outside the distributable npm package.
42
+ - Preserve native launch commands; do not start background services.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # Kitto
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Kitto 把一套工作规则和 skills 带到 Pi、Codex 和 DeepSeek Harness(DSH)。每台机器设置一次。之后照常从项目目录启动 agent,或在 DSH Web 中选择项目。
4
+
5
+ ## 换一台新机器
6
+
7
+ 准备好 Node.js 26 和 Git,在终端运行:
8
+
9
+ ```bash
10
+ npx --yes @phyzess/kitto@latest setup
11
+ ```
12
+
13
+ 向导会让你选择宿主和配置仓库。选「使用默认 Kitto 配置」即可部署仓库里的规则、skills 和各宿主的 Kitto 集成。选择 Pi 时还会同步 Pi 包、扩展和 MCP 设置。已有自己的配置仓库时,可以填 Git URL 或本地路径。向导会询问是否补装缺少的 CLI 和辅助依赖,也可以在同一次运行里先预览,再确认安装。已有 Kitto 源码的机器可直接运行 `./setup.sh`。
14
+
15
+ ## 以后才建工作区怎么办?
16
+
17
+ 假设你会把项目放在 `~/workspaces/workspace-1/repo-a`。向导问「工作区父目录」时填 `~/workspaces`,即使这个目录还没建。以后在里面新建工作区、clone repo,开启新会话即可,无需再次 setup。
18
+
19
+ | 希望谁使用这条规则 | 写在哪里 |
20
+ | --- | --- |
21
+ | 当前账号下的所有项目 | `~/.local/share/kitto/global/AGENTS.md`,向导会打印实际路径 |
22
+ | `workspace-1` 下所有 repo | `~/workspaces/workspace-1/AGENTS.md` |
23
+ | 只有 repo-a | repo-a 自己的 `AGENTS.md`,可以随代码提交 |
24
+
25
+ 全局和工作区的 skills 放在同层的 `.agents/skills/<名称>/SKILL.md`。没有额外约定时,工作区可以保持空白。父目录之外的项目也能使用账号的全局配置。
26
+
27
+ Codex 首次需要在 `/hooks` 中信任 Kitto 的 SessionStart hook。正在运行的 DSH 服务需要重启对应 profile。宿主登录和私有 MCP 凭据由各账号配置。
28
+
29
+ ## 把改动带到下一台机器
30
+
31
+ 把需要跨机器分发的内容改在配置仓库里,提交并推送。另一台机器的完整安装可以在 agent 会话里说「用 Kitto 检查并同步配置」。直接编辑全局或工作区文件会在对应目录生效,想跨机器复用时需将它们纳入自己的版本管理。
32
+
33
+ [配置与同步指南](https://github.com/phyzess/kitto/blob/main/docs/usage.md) · [Pi 配置参考](https://github.com/phyzess/kitto/blob/main/docs/pi.md) · [版本记录](CHANGELOG.md)
package/bin/kitto.mjs ADDED
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import { setup, parseOptions } from '../lib/kitto.mjs';
3
+
4
+ const help = `Kitto — portable personal agent configuration
5
+
6
+ kitto setup Guided setup in an interactive terminal
7
+ kitto setup --interactive Start the setup wizard explicitly
8
+ kitto setup --workspace-parent PATH [--agents pi,codex,dsh] [--dry-run]
9
+ kitto setup --global [--agents pi,codex,dsh] [--dry-run]
10
+ kitto setup --workspace PATH [--agents pi,codex,dsh] [--dsh-service UNIT] [--dry-run]
11
+ kitto setup [--agents pi,codex,dsh] [--source PATH_OR_GIT_URL] [--ref BRANCH_OR_TAG]
12
+ [--dsh-profile PROFILE] [--install-agents] [--dry-run]
13
+ kitto setup --recover [--dry-run] Restore the last working Kitto code
14
+
15
+ Scoped setup shares AGENTS.md and .agents/skills. Plain setup uses the phyzess/kitto configuration repository.
16
+ After scoped setup, edit the shared files and start a new native agent session.
17
+ Plain setup installs the Kitto maintenance skill for configuration synchronization.
18
+ Kitto needs Node >=22 and Git. Pi sync also needs Bash and Python >=3.10.
19
+ DSH needs pnpm and uses the web profile by default. Host CLIs have their own Node requirements.
20
+ `;
21
+ try {
22
+ const [command, ...args] = process.argv.slice(2);
23
+ if (!command || command === '--help' || command === '-h') console.log(help);
24
+ else if (command === 'setup') {
25
+ if ((args.length === 0 && process.stdin.isTTY && process.stdout.isTTY) ||
26
+ (args.length === 1 && args[0] === '--interactive')) {
27
+ const { runWizard } = await import('../lib/setup-wizard.mjs');
28
+ await runWizard();
29
+ } else await setup(parseOptions(args));
30
+ }
31
+ else throw new Error(`Unknown command: ${command}. Use kitto --help.`);
32
+ } catch (error) {
33
+ console.error(`Kitto: ${error.message}`);
34
+ process.exitCode = 1;
35
+ }
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ // Internal entry used by the bundled skill, not a second public CLI.
3
+ import { maintain } from '../lib/kitto.mjs';
4
+ try {
5
+ await maintain(process.argv.slice(2));
6
+ } catch (error) {
7
+ console.error(`Kitto: ${error.message}`);
8
+ process.exitCode = 1;
9
+ }
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: phyzess-kitto
3
+ name: ./dsh.mjs
@@ -0,0 +1,21 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ export const name = 'phyzess-kitto';
5
+ export const inject = ['skills'];
6
+
7
+ // Only one catalog entry at startup; the body is loaded on demand.
8
+ export function apply(ctx) {
9
+ const path = fileURLToPath(new URL('./skills/kitto/SKILL.md', import.meta.url));
10
+ const candidate = {
11
+ name: 'kitto', description: 'Inspect, synchronize and update personal agent configuration with Kitto.',
12
+ invocation: { modelInvocable: true, userInvocable: true },
13
+ source: 'bundled', provider: 'phyzess-kitto', rank: 600, locator: path, path,
14
+ resourceBase: { kind: 'directory', path: fileURLToPath(new URL('./skills/kitto/', import.meta.url)) },
15
+ };
16
+ ctx.skills.registerProvider(() => ({
17
+ name: 'phyzess-kitto',
18
+ list: async () => [candidate],
19
+ get: async () => ({ ...candidate, content: (await readFile(path, 'utf8')).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '') }),
20
+ }));
21
+ }
@@ -0,0 +1,14 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { kittoHome } from '../lib/kitto.mjs';
3
+ import { updateNotice } from '../lib/update-notice.mjs';
4
+
5
+ // Non-blocking self-update notice; Pi remains responsible for its other packages.
6
+ export default function kitto(pi) {
7
+ pi.on('session_start', (_event, ctx) => {
8
+ if (!ctx.hasUI || process.env.KITTO_UPDATE_CHECK === '0') return;
9
+ void readFile(new URL('../package.json', import.meta.url), 'utf8')
10
+ .then(text => updateNotice(kittoHome(), JSON.parse(text).version))
11
+ .then(notice => { if (notice) ctx.ui.notify(notice, 'info'); })
12
+ .catch(() => {});
13
+ });
14
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
+ "name": "kitto",
4
+ "version": "0.2.0",
5
+ "description": "Maintain personal agent configuration on request"
6
+ }
@@ -0,0 +1,59 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { resolveScopes } from '../../lib/scopes.mjs';
4
+
5
+ async function optional(operation, fallback) {
6
+ try {
7
+ return await operation();
8
+ } catch (error) {
9
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return fallback;
10
+ throw error;
11
+ }
12
+ }
13
+
14
+ async function skillCatalog(directory) {
15
+ const entries = await optional(() => readdir(directory, { withFileTypes: true }), []);
16
+ const skills = [];
17
+ for (const entry of entries) {
18
+ if (entry.name.startsWith('.') || (!entry.isDirectory() && !entry.isSymbolicLink())) continue;
19
+ const path = join(directory, entry.name, 'SKILL.md');
20
+ const file = await optional(() => readFile(path, 'utf8'), '');
21
+ const metadata = file.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
22
+ if (!metadata) continue;
23
+ const name = metadata.match(/^name:[ \t]*(.*)$/m)?.[1]?.trim().replace(/^(['"])(.*)\1$/, '$2');
24
+ const field = metadata.match(/^description:[ \t]*([^\r\n]*)((?:\r?\n[ \t]+[^\r\n]*)*)/m);
25
+ const description = field && (/^[>|]/.test(field[1]) ? field[2] : field[1])
26
+ .trim().replace(/\s+/g, ' ').replace(/^(['"])(.*)\1$/, '$2');
27
+ if (name) skills.push({ name, description, path });
28
+ }
29
+ return skills.sort((a, b) => a.path.localeCompare(b.path));
30
+ }
31
+
32
+ process.stdin.setEncoding('utf8');
33
+ let input = '';
34
+ for await (const chunk of process.stdin) input += chunk;
35
+ const { cwd } = JSON.parse(input);
36
+ if (typeof cwd !== 'string' || !isAbsolute(cwd)) throw new Error('Codex SessionStart requires an absolute cwd.');
37
+
38
+ const context = [];
39
+ const skills = new Map();
40
+ for (const scope of await resolveScopes(cwd)) {
41
+ const instructions = await optional(() => readFile(scope.instructions, 'utf8'), '');
42
+ if (instructions.trim()) context.push(`# Shared instructions from ${scope.instructions}\n\n${instructions.trim()}`);
43
+ for (const skill of await skillCatalog(scope.skills)) skills.set(skill.name, skill);
44
+ }
45
+ if (skills.size) {
46
+ const entries = [...skills.values()].map(({ name, description, path }) =>
47
+ `- ${name}${description ? ': ' + description : ''} (${path})`);
48
+ context.push([
49
+ '# Kitto shared skills',
50
+ 'When a listed skill applies, read its SKILL.md and follow it. Resolve its relative resource paths from the directory containing that file.',
51
+ ...entries,
52
+ ].join('\n'));
53
+ }
54
+ if (context.length) {
55
+ context.unshift('Apply the closest workspace’s shared instructions if scopes conflict. Follow repository instructions for any conflicting repository-specific guidance, including repository-local skills.');
56
+ console.log(JSON.stringify({
57
+ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context.join('\n\n') },
58
+ }));
59
+ }
@@ -0,0 +1,124 @@
1
+ import { watch } from 'node:fs';
2
+ import { readFile, realpath, stat } from 'node:fs/promises';
3
+ import { isAbsolute, relative, sep } from 'node:path';
4
+ import { resolveScopes, scopeHome } from '../../lib/scopes.mjs';
5
+ import { importFromDsh } from './native.mjs';
6
+
7
+ export const name = 'phyzess-kitto-scopes';
8
+ export const inject = ['skills', 'workingDirectory', 'systemPrompt', 'profileContext'];
9
+
10
+ async function optionalFile(path, signal) {
11
+ try {
12
+ const info = await stat(path);
13
+ // Match DSH's native ceiling for a single instruction file.
14
+ if (info.isFile() && info.size <= 1_048_576) return (await readFile(path, { encoding: 'utf8', signal })).trim();
15
+ } catch (error) {
16
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error;
17
+ }
18
+ }
19
+
20
+ function covers(parent, child) {
21
+ const path = relative(parent, child);
22
+ return path !== '..' && !path.startsWith('..' + sep) && !isAbsolute(path);
23
+ }
24
+
25
+ function registerScopes(ctx, FileSystemSkillProvider, discoverBaselineInstructionFiles, nativeConfigByPreset) {
26
+ ctx.skills.registerProvider(control => {
27
+ const providers = new Map();
28
+ const watcher = watch(scopeHome(), { persistent: false, signal: control.signal }, (_event, file) => {
29
+ if (file === null || file === 'scopes.json') control.invalidate();
30
+ });
31
+ watcher.on('error', error => ctx.logger.warn(`Kitto scope registry watcher: ${error.message}`));
32
+ return {
33
+ name,
34
+ async list({ cwd, signal }) {
35
+ if (!cwd) return [];
36
+ const directory = await realpath(cwd);
37
+ const scopes = await resolveScopes(directory);
38
+ const candidates = [];
39
+ let complete = true;
40
+ for (const { skills, root } of scopes.toReversed()) {
41
+ if (!skills) continue;
42
+ signal?.throwIfAborted();
43
+ let provider = providers.get(skills);
44
+ if (!provider) {
45
+ provider = new FileSystemSkillProvider(ctx, control, {
46
+ providerName: name,
47
+ includeDefaultRoots: false,
48
+ bundledSkillDir: skills,
49
+ });
50
+ providers.set(skills, provider);
51
+ }
52
+ const result = await provider.list({ cwd, signal });
53
+ complete &&= Array.isArray(result) || result.complete;
54
+ for (const candidate of Array.isArray(result) ? result : result.candidates) {
55
+ candidates.push({
56
+ ...candidate,
57
+ source: 'custom',
58
+ // Native project skills already have priority (ranks 100 and 200).
59
+ rank: covers(root, directory) ? 225 : 525,
60
+ locator: { skills, candidate },
61
+ });
62
+ }
63
+ }
64
+ return { candidates, complete };
65
+ },
66
+ async get({ locator }, { cwd, signal }) {
67
+ if (!cwd || !(await resolveScopes(cwd)).some(scope => scope.skills === locator.skills)) return;
68
+ const skill = await providers.get(locator.skills)?.get(locator.candidate, { cwd, signal });
69
+ if (skill) return { ...skill, source: 'custom' };
70
+ },
71
+ };
72
+ });
73
+
74
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
75
+ const assembly = await next();
76
+ if (!context.agent) return assembly;
77
+ const { signal } = context;
78
+ const cwd = await ctx.workingDirectory.ensure(context.agent, signal);
79
+ const scopes = await resolveScopes(cwd);
80
+ if (!scopes.length) return assembly;
81
+ const preset = ctx.get('agentPresets')?.composedPreset(context.agent.ctx);
82
+ const nativeConfig = nativeConfigByPreset.get(preset) ?? nativeConfigByPreset.get(undefined);
83
+ const nativePaths = new Set(ctx.get('fs') && nativeConfig?.maxBytes > 0
84
+ ? (await discoverBaselineInstructionFiles({ ...nativeConfig, cwd: await realpath(cwd), signal }))
85
+ .map(file => file.absolutePath)
86
+ : []);
87
+ const sections = [];
88
+ for (const { instructions } of scopes) {
89
+ // The built-in loader already supplies files in its baseline chain.
90
+ if (!instructions || nativePaths.has(instructions)) continue;
91
+ const text = await optionalFile(instructions, signal);
92
+ if (text) sections.push(`# Project instructions from ${instructions}\n\n${text}`);
93
+ }
94
+ if (sections.length) assembly.contexts.push({ name, text: sections.join('\n\n'), interpolate: false });
95
+ return assembly;
96
+ });
97
+ }
98
+
99
+ function* activeRows(rows) {
100
+ for (const row of rows) {
101
+ if (row.disabled) continue;
102
+ yield row;
103
+ if (row.group && Array.isArray(row.config)) yield* activeRows(row.config);
104
+ }
105
+ }
106
+
107
+ function nativeInstructionConfig(rows) {
108
+ return Array.from(activeRows(rows)).find(row => row.id === 'agent-instructions')?.config;
109
+ }
110
+
111
+ export async function apply(ctx) {
112
+ const [{ FileSystemSkillProvider }, { discoverBaselineInstructionFiles }, { readProfilePatches, composeEntries }] = await Promise.all([
113
+ importFromDsh(process.argv[1], '@deepseek-ai/dsh-skill-filesystem'),
114
+ importFromDsh(process.argv[1], '@deepseek-ai/dsh-agent-instructions'),
115
+ importFromDsh(process.argv[1], '@deepseek-ai/dsh-app-boot'),
116
+ ]);
117
+ const rows = composeEntries([readProfilePatches('dsh', ctx.profileContext)]);
118
+ const nativeConfigByPreset = new Map([[undefined, nativeInstructionConfig(rows)]]);
119
+ for (const row of activeRows(rows)) {
120
+ if (row.name !== '@deepseek-ai/dsh-agent-preset' || !Array.isArray(row.config?.plugins)) continue;
121
+ nativeConfigByPreset.set(row.config.id, nativeInstructionConfig(row.config.plugins));
122
+ }
123
+ registerScopes(ctx, FileSystemSkillProvider, discoverBaselineInstructionFiles, nativeConfigByPreset);
124
+ }
@@ -0,0 +1,8 @@
1
+ import { createRequire } from 'node:module';
2
+ import { realpath } from 'node:fs/promises';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ export async function importFromDsh(entry, name) {
6
+ const require = createRequire(await realpath(entry));
7
+ return import(pathToFileURL(require.resolve(name)).href);
8
+ }
@@ -0,0 +1,62 @@
1
+ import { readFile, realpath, stat } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, relative, sep } from 'node:path';
3
+ import { resolveScopes } from '../../lib/scopes.mjs';
4
+
5
+ async function ifPresent(callback) {
6
+ try {
7
+ return await callback();
8
+ } catch (error) {
9
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
10
+ }
11
+ }
12
+
13
+ function contains(parent, path) {
14
+ const suffix = relative(parent, path);
15
+ return suffix !== '..' && !suffix.startsWith(`..${sep}`) && !isAbsolute(suffix);
16
+ }
17
+
18
+ export default function kittoScopes(pi) {
19
+ const args = process.argv.slice(2);
20
+ const separator = args.indexOf('--');
21
+ const options = separator === -1 ? args : args.slice(0, separator);
22
+ if (!options.includes('--no-skills') && !options.includes('-ns')) {
23
+ pi.on('resources_discover', async ({ cwd }) => {
24
+ const scopes = await resolveScopes(cwd);
25
+ const skillPaths = [];
26
+ // Pi uses the first skill with a given name, and gives its existing paths priority.
27
+ for (const { skills } of scopes.toReversed()) {
28
+ if (skills && (await ifPresent(() => stat(skills)))?.isDirectory()) skillPaths.push(skills);
29
+ }
30
+ return { skillPaths };
31
+ });
32
+ }
33
+
34
+ if (!options.includes('--no-context-files') && !options.includes('-nc')) {
35
+ pi.on('before_agent_start', async ({ systemPromptOptions }, { cwd }) => {
36
+ const files = systemPromptOptions?.contextFiles;
37
+ if (!files) return;
38
+ const scopes = await resolveScopes(cwd);
39
+ if (!scopes.length) return;
40
+
41
+ // Preserve Pi's native context and skip scope files already loaded through another path.
42
+ const seen = new Set(await Promise.all(files.map(async ({ path }) => await ifPresent(() => realpath(path)) ?? path)));
43
+ const directories = await Promise.all(files.map(async ({ path }) => {
44
+ const directory = dirname(path);
45
+ return await ifPresent(() => realpath(directory)) ?? directory;
46
+ }));
47
+ const canonicalCwd = await realpath(cwd);
48
+ for (const { root, instructions } of scopes) {
49
+ if (!instructions) continue;
50
+ const canonical = await ifPresent(() => realpath(instructions));
51
+ if (!canonical || seen.has(canonical) || !(await ifPresent(() => stat(instructions)))?.isFile()) continue;
52
+ const content = await ifPresent(() => readFile(instructions, 'utf8'));
53
+ if (content === undefined) continue;
54
+ const index = directories.findIndex(directory => contains(root, directory));
55
+ const position = index >= 0 ? index : contains(root, canonicalCwd) ? files.length : 0;
56
+ files.splice(position, 0, { path: instructions, content: content.replace(/^\uFEFF/, '') });
57
+ directories.splice(position, 0, root);
58
+ seen.add(canonical);
59
+ }
60
+ });
61
+ }
62
+ }
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: kitto
3
+ description: Inspect, synchronize and update personal agent configuration across machines with Kitto. Use for Kitto setup, configuration drift, dependency versions or syncing personal skills; not for ordinary project tasks.
4
+ ---
5
+
6
+ Use the installed maintenance runner. Setup replaces `KITTO_RUNNER` below with its absolute, shell-quoted path. If it is still a placeholder, Kitto setup has not completed; do not guess an installation path.
7
+
8
+ ```sh
9
+ node KITTO_RUNNER status
10
+ ```
11
+
12
+ Keep normal work in the current native agent. Do not introduce a launcher or modify project configuration. The runner exposes only these maintenance operations:
13
+
14
+ | Operation | Behavior |
15
+ |---|---|
16
+ | `status` | Read installation state and configuration differences locally |
17
+ | `versions` | Read installed and declared component versions |
18
+ | `versions --online` | Also query registry release channels; no installation |
19
+ | `sync` | Preview repository-to-machine configuration deployment |
20
+ | `sync --apply` | Deploy configuration and reconnect native integrations |
21
+ | `update` | Preview the source branch's remote head without fetching |
22
+ | `update --apply` | Fast-forward a clean tracked source branch, then deploy |
23
+ | `export` | Preview sanitized Pi machine-to-repository export |
24
+ | `export --apply` | Write that export to the local source checkout; never commit or push |
25
+ | `deps` / `deps --apply` | Preview / install CLI dependencies needed by the selected hosts and enabled capabilities, only when requested |
26
+ | `recover` / `recover --apply` | Preview / restore the last verified Kitto code checkpoint and reconnect native integrations |
27
+ | `remove` / `remove --apply` | Preview / detach Kitto's native integrations; retain personal configuration, shared skills, CLIs and recovery files |
28
+
29
+ Begin with `status`. For changes, inspect the corresponding preview, explain concrete conflicts or scope, and apply within the user's authorization. A sync may install the source's declared Pi packages. Existing shared skill directories are preserved when different; report conflicts and resolve them with the user rather than deleting them. Local edits or diverged source history stop an update; never reset or stash them automatically.
30
+
31
+ Use `versions --online` when asked about upgrades. Distinguish installed, declared and upstream versions, including prereleases and engine requirements. Registry metadata is not a compatibility test. Kitto does not bulk-upgrade hosts or plugins: use each native manager for explicitly selected upgrades, test the relevant host, and update the source only after validation. Update Kitto itself by rerunning its npm setup entry with the intended package version.
32
+
33
+ For a change intended for every machine, edit the source checkout. Write host-specific changes under the corresponding `config/<agent>/` and common workflows under `skills/`. Show the Git diff, preview and apply sync, and report whether the changes have reached the remote. For this machine only, use the native host's local override. For Codex and DSH instructions, keep local text outside Kitto's managed block. For Pi, use its existing local settings and MCP overrides. When migrating an existing machine, first identify shared content, local changes and machine-specific tools, then transfer only the selected portable items.
34
+
35
+ The source checkout owns shared skills, host-specific skills, Pi settings, and managed instruction blocks for Codex and DSH. Codex and DSH keep their own authentication, model choices, permissions and MCP configuration. Check the current session for any optional tools a skill needs. Read the source's documentation before changing personal assets. Report what changed, skipped conflicts, failures and any required native reload. Stop on errors; rerun only after resolving the cause.
36
+
37
+ Recovery only changes Kitto code and its native registration, preserving the currently deployed personal configuration. It is not a transaction rollback of all earlier file changes or dependency installs. If the installed runner cannot start, use the same package setup entry with `--recover --dry-run`, then `--recover` within the user's request. This external entry also works when recovering an older Kitto version whose skill lacks recovery commands. With no verified checkpoint, rerun setup from a known working package version.
38
+
39
+ Removal is resumable: repeat it after fixing a native-manager error. It never deletes the source checkout, shared skills, agent CLIs or authentication. Native registrations that point to another source are preserved and reported as conflicts. After detaching, use setup to reinstall; ordinary sync must not reconnect a removed integration implicitly. Complete the requested maintenance without running the agent's task through Kitto.
@@ -0,0 +1,178 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, statSync, accessSync, constants } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { delimiter, join, resolve } from 'node:path';
5
+
6
+ export async function optionalJson(path, fallback = {}) {
7
+ try { return JSON.parse(await readFile(path, 'utf8')); }
8
+ catch (error) { if (error.code === 'ENOENT') return fallback; throw error; }
9
+ }
10
+
11
+ export function executable(name) {
12
+ const paths = name.includes('/') ? [resolve(name)] : (process.env.PATH || '').split(delimiter).map(dir => resolve(dir, name));
13
+ return paths.find(path => {
14
+ try { accessSync(path, constants.X_OK); return statSync(path).isFile(); }
15
+ catch { return false; }
16
+ });
17
+ }
18
+
19
+ export function query(command, args, env = process.env) {
20
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 8000, env });
21
+ return result.status === 0 ? result.stdout.trim() : null;
22
+ }
23
+
24
+ export function npmSpec(source) {
25
+ const spec = source.replace(/^npm:/, '');
26
+ const split = spec.lastIndexOf('@');
27
+ return split > 0 ? [spec.slice(0, split), spec.slice(split + 1)] : [spec, null];
28
+ }
29
+
30
+ export async function piServers(state) {
31
+ const declared = await optionalJson(join(state.source, 'config/pi/mcp.json'));
32
+ // Once installed, respect the actual selected command and local on/off switches.
33
+ const live = await optionalJson(join(state.piHome, 'mcp.json'), declared);
34
+ return Object.fromEntries(Object.entries(live.mcpServers || {}).filter(
35
+ ([name, entry]) => !name.startsWith('_') && entry?.command && entry.enabled !== false,
36
+ ));
37
+ }
38
+
39
+ const legacyRules = [
40
+ { executable: 'codegraph', skill: 'codegraph', piCommand: 'codegraph' },
41
+ { executable: 'serena', piCommand: 'serena' },
42
+ { executable: 'dap-mcp-server', piCommand: 'dap-mcp-server', list: 'mise-tools.txt', manager: 'mise' },
43
+ { package: 'debugpy', piCommand: 'dap-mcp-server', list: 'pip.txt', manager: 'pip' },
44
+ { executable: 'ast-grep', piNpx: 'ast-grep-mcp', list: 'brew.txt', manager: 'brew', platform: 'darwin' },
45
+ { executable: 'ast-grep', package: '@ast-grep/cli', piNpx: 'ast-grep-mcp', list: 'npm.txt', manager: 'mise', platform: 'linux' },
46
+ ];
47
+
48
+ export function npxPackage(entry) {
49
+ if (entry.command !== 'npx') return [];
50
+ const spec = entry.args?.find(value => !value.startsWith('-'));
51
+ return spec ? npmSpec(spec) : [];
52
+ }
53
+
54
+ async function listTarget(state, rule) {
55
+ if (!rule.list) return null;
56
+ const path = join(state.source, 'lists', rule.list);
57
+ if (!existsSync(path)) return undefined;
58
+ const lines = (await readFile(path, 'utf8')).split('\n');
59
+ for (const line of lines) {
60
+ const [name, version] = line.split('#', 1)[0].trim().split(/\s+/);
61
+ if (name === (rule.package || rule.executable)) return version ?? null;
62
+ }
63
+ return undefined;
64
+ }
65
+
66
+ async function dependencyRules(state) {
67
+ const entries = await optionalJson(join(state.source, 'config/dependencies.json'), null);
68
+ if (entries === null) return legacyRules;
69
+ if (!Array.isArray(entries)) throw new Error('config/dependencies.json must contain an array.');
70
+ return entries.map((rule, index) => {
71
+ const invalid = () => new Error(`Invalid dependency declaration at config/dependencies.json entry ${index + 1}.`);
72
+ const fields = ['agent', 'platform', 'skill', 'piCommand', 'piNpx', 'executable', 'install'];
73
+ const name = /^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/;
74
+ const npmName = /^(?:@[a-z0-9_.-]+\/)?[a-z0-9_][a-z0-9_.-]*$/;
75
+ if (!rule || typeof rule !== 'object' || Object.keys(rule).some(key => !fields.includes(key))) throw invalid();
76
+ for (const key of fields.filter(key => key !== 'install')) {
77
+ if (key in rule && (typeof rule[key] !== 'string' || !(key === 'piNpx' ? npmName : name).test(rule[key]))) throw invalid();
78
+ }
79
+ if (!rule.agent && !rule.skill && !rule.piCommand && !rule.piNpx) throw invalid();
80
+ if (rule.agent && !['pi', 'codex', 'dsh'].includes(rule.agent)) throw invalid();
81
+ if (rule.platform && !['darwin', 'linux'].includes(rule.platform)) throw invalid();
82
+ if (!('install' in rule)) {
83
+ if (!rule.executable) throw invalid();
84
+ return rule;
85
+ }
86
+ if (!rule.install || typeof rule.install !== 'object' || Object.keys(rule.install).length !== 1) throw invalid();
87
+ const [[manager, spec]] = Object.entries(rule.install);
88
+ if (!['mise', 'pip', 'brew'].includes(manager) || typeof spec !== 'string') throw invalid();
89
+ const [pkg, target] = manager === 'mise' ? npmSpec(spec) : [spec, null];
90
+ if (manager === 'mise') {
91
+ if (!spec.startsWith('npm:') || !npmName.test(pkg) || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(target || '')) throw invalid();
92
+ } else if (!name.test(pkg)) throw invalid();
93
+ if (manager !== 'pip' && !rule.executable) throw invalid();
94
+ return { ...rule, package: pkg, target, manager };
95
+ });
96
+ }
97
+
98
+ export async function dependencyPlan(state) {
99
+ const servers = state.agents.includes('pi') ? await piServers(state) : {};
100
+ const plans = new Map();
101
+ for (const rule of await dependencyRules(state)) {
102
+ if (rule.agent && !state.agents.includes(rule.agent)) continue;
103
+ if (rule.platform && rule.platform !== process.platform) continue;
104
+ const reasons = [];
105
+ if (rule.skill && existsSync(join(state.source, 'skills', rule.skill, 'SKILL.md'))) reasons.push(`shared skill ${rule.skill}`);
106
+ for (const [name, entry] of Object.entries(servers)) {
107
+ if (rule.piCommand === entry.command || (rule.piNpx && rule.piNpx === npxPackage(entry)[0])) reasons.push(`Pi MCP ${name}`);
108
+ }
109
+ if (!reasons.length && rule.agent && !rule.skill && !rule.piCommand && !rule.piNpx) reasons.push(rule.agent);
110
+ if (!reasons.length) continue;
111
+ const target = rule.list ? await listTarget(state, rule) : rule.target ?? null;
112
+ if (target === undefined) continue;
113
+ const name = rule.package || rule.executable;
114
+ if (rule.manager === 'mise' && !target) throw new Error(`Missing declared version for ${name} in lists/${rule.list}.`);
115
+ let installed = null;
116
+ const path = rule.executable ? executable(rule.executable) : undefined;
117
+ if (rule.manager === 'mise') {
118
+ const active = query('mise', ['current', `npm:${name}`]);
119
+ if (active) installed = active.replace(/^v/, '');
120
+ } else if (rule.manager === 'pip') {
121
+ installed = query('python3', ['-m', 'pip', 'show', name])?.match(/^Version: (.+)$/m)?.[1] || null;
122
+ }
123
+ const key = rule.executable ? `executable:${rule.executable}` : `package:${name}`;
124
+ const previous = plans.get(key);
125
+ if (previous?.manager && rule.manager &&
126
+ (previous.manager !== rule.manager || previous.name !== name || previous.target !== target)) {
127
+ throw new Error(`Conflicting dependency declarations for ${rule.executable || name}.`);
128
+ }
129
+ const plan = { name, path, target, installed, manager: rule.manager,
130
+ note: rule.skill ? 'Binary check only. Verify MCP tools in the active session.' : undefined,
131
+ available: rule.manager === 'pip' ? Boolean(installed) : Boolean(path) && (!target || installed === target),
132
+ reason: reasons.join(', ') };
133
+ const selected = previous?.manager || !rule.manager ? previous || plan : plan;
134
+ if (previous) {
135
+ selected.reason = [...new Set([...previous.reason.split(', '), ...reasons])].join(', ');
136
+ selected.note ||= previous.note || plan.note;
137
+ }
138
+ plans.set(key, selected);
139
+ }
140
+ return [...plans.values()];
141
+ }
142
+
143
+ export async function installDependencies(state, apply) {
144
+ const plans = await dependencyPlan(state);
145
+ if (!plans.length) console.log('No declared dependencies for the enabled hosts and shared skills.');
146
+ const blocked = [], manual = [], attempted = [];
147
+ for (const tool of plans) {
148
+ const { name, target, manager, reason } = tool;
149
+ if (tool.available) { console.log(`Available: ${name} (${reason})`); continue; }
150
+ if (!manager) {
151
+ manual.push(name);
152
+ console.log(`Missing: ${name} (${reason}); install separately if needed.`);
153
+ continue;
154
+ }
155
+ const command = manager === 'pip' ? 'python3' : manager;
156
+ const args = manager === 'mise' ? ['use', '-g', `npm:${name}@${target}`]
157
+ : manager === 'pip' ? ['-m', 'pip', 'install', name] : ['install', name];
158
+ if (!executable(command)) {
159
+ blocked.push(`${name} (missing ${command})`);
160
+ console.log(`Missing installer ${command}: ${name} (${reason})`);
161
+ continue;
162
+ }
163
+ console.log(`${apply ? 'Run' : 'Would run'}: ${[command, ...args].join(' ')} (${reason})`);
164
+ if (apply) {
165
+ const result = spawnSync(command, args, { stdio: 'inherit', timeout: 600_000 });
166
+ if (result.status !== 0) blocked.push(`${name} (${result.error?.message || `exit ${result.status}`})`);
167
+ else attempted.push(name);
168
+ }
169
+ }
170
+ if (!apply) return;
171
+ const current = attempted.length ? await dependencyPlan(state) : plans;
172
+ const ready = current.filter(tool => tool.available).map(tool => tool.name);
173
+ for (const name of attempted) if (!ready.includes(name)) blocked.push(`${name} (still unavailable after install)`);
174
+ console.log(`Ready: ${ready.join(', ') || 'none'}`);
175
+ console.log(`Manual setup: ${manual.join(', ') || 'none'}`);
176
+ console.log(`Unresolved managed dependencies: ${blocked.join(', ') || 'none'}`);
177
+ if (blocked.length) throw new Error('Some managed dependencies are still unavailable.');
178
+ }