@phyzess/kitto 0.1.1 → 0.2.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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # Kitto
2
2
 
3
+ ## 0.2.1
4
+
5
+ - Select hosts with arrow keys and Space in the setup wizard, then choose a configuration source and preview or apply the plan. Scripted input remains supported.
6
+ - Use the pinned i-have-adhd skill in the default Codex and DSH configuration alongside the existing Pi extension.
7
+
8
+ ## 0.2.0
9
+
10
+ - Guide users through host selection, configuration sources, dependencies, preview and installation in one interactive setup.
11
+ - Share global and workspace instructions and skills across Pi, Codex and DSH, including workspaces created after setup.
12
+ - Configure an active DSH system service under its own account from the same wizard.
13
+ - Preserve conflicting unowned skills during guided setup and subsequent synchronization.
14
+
3
15
  ## 0.1.1
4
16
 
5
17
  - Document setup, synchronization and tag-pinned configuration for Pi, Codex and DSH.
package/README.md CHANGED
@@ -1,25 +1,33 @@
1
1
  # Kitto
2
2
 
3
- Kitto 把这份仓库里的个人配置带到每台开发机。换一台 Mac 或 Linux 机器后,Pi、Codex 和 DeepSeek Harness(DSH)都能用上你熟悉的工作规则和 skills。
3
+ Kitto 把一套工作规则和 skills 带到 Pi、Codex 和 DeepSeek Harness(DSH)。每台机器设置一次。之后照常从项目目录启动 agent,或在 DSH Web 中选择项目。
4
4
 
5
- ## 新机安装
5
+ ## 换一台新机器
6
6
 
7
- 准备好 Git、Node.js 26 LTS(Kitto 最低要求 Node.js 22),以及你要使用的 agent。在任意目录运行一次:
7
+ 准备好 Node.js 26 和 Git,在终端运行:
8
8
 
9
9
  ```bash
10
- npx --yes github:phyzess/kitto setup
10
+ npx --yes @phyzess/kitto@latest setup
11
11
  ```
12
12
 
13
- 这条命令从 GitHub 取得 Kitto,自动识别本机已安装的 agent,把配置部署到当前用户目录。Pi 还需要 Bash 和 Python 3.10+,DSH 需要 pnpm。如果机器上还没有 agent,见[安装选项](docs/usage.md#选择-agent)。
13
+ 用 ↑↓ 移动、空格勾选宿主、Enter 确认。随后从菜单选择配置来源,指定本地路径或 Git URL 时直接输入。选「使用默认 Kitto 配置」即可部署仓库里的规则、skills 和各宿主的 Kitto 集成。选择 Pi 时还会同步 Pi 包、扩展和 MCP 设置。已有自己的配置仓库时,可以填 Git URL 或本地路径。向导会询问是否补装缺少的 CLI 和辅助依赖,也可以在同一次运行里先预览,再确认安装。已有 Kitto 源码的机器可直接运行 `./setup.sh`。
14
14
 
15
- ## 平时怎么用
15
+ ## 以后才建工作区怎么办?
16
16
 
17
- 照常启动 `pi`、`codex` 或 `dsh web`。需要维护配置时,在会话里直接说:
17
+ 假设你会把项目放在 `~/workspaces/workspace-1/repo-a`。向导问「工作区父目录」时填 `~/workspaces`,即使这个目录还没建。以后在里面新建工作区、clone repo,开启新会话即可,无需再次 setup。
18
18
 
19
- - “用 Kitto 看看,这台机器的配置和仓库有什么不同?”
20
- - “用 Kitto 把仓库里的最新配置同步到这台机器。”
21
- - “以后所有机器上的 Codex 都用中文回复,把这条写进配置仓库。”
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`,可以随代码提交 |
22
24
 
23
- 想把改动带到另一台机器,先把配置提交并推送到 Git,再在另一台机器上同步。只属于本机的设置可以留在本地。
25
+ 全局和工作区的 skills 放在同层的 `.agents/skills/<名称>/SKILL.md`。没有额外约定时,工作区可以保持空白。父目录之外的项目也能使用账号的全局配置。
24
26
 
25
- [配置与同步指南](docs/usage.md) · [Pi 配置参考](docs/pi.md) · [版本记录](CHANGELOG.md) · [发布新版本](docs/usage.md#发布新版本)
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 CHANGED
@@ -3,20 +3,31 @@ import { setup, parseOptions } from '../lib/kitto.mjs';
3
3
 
4
4
  const help = `Kitto — portable personal agent configuration
5
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]
6
11
  kitto setup [--agents pi,codex,dsh] [--source PATH_OR_GIT_URL] [--ref BRANCH_OR_TAG]
7
12
  [--dsh-profile PROFILE] [--install-agents] [--dry-run]
8
13
  kitto setup --recover [--dry-run] Restore the last working Kitto code
9
14
 
10
- Global user setup only. Defaults to installed agents and phyzess/kitto.
11
- After setup, start your agent with its native command and ask the Kitto skill
12
- to inspect, sync or update your configuration. No project initialization.
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.
13
18
  Kitto needs Node >=22 and Git. Pi sync also needs Bash and Python >=3.10.
14
19
  DSH needs pnpm and uses the web profile by default. Host CLIs have their own Node requirements.
15
20
  `;
16
21
  try {
17
22
  const [command, ...args] = process.argv.slice(2);
18
23
  if (!command || command === '--help' || command === '-h') console.log(help);
19
- else if (command === 'setup') await setup(parseOptions(args));
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
+ }
20
31
  else throw new Error(`Unknown command: ${command}. Use kitto --help.`);
21
32
  } catch (error) {
22
33
  console.error(`Kitto: ${error.message}`);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "kitto",
4
- "version": "0.1.1",
4
+ "version": "0.2.1",
5
5
  "description": "Maintain personal agent configuration on request"
6
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,43 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { checkSelectedHosts, installMissingHosts, maintain, setup } from './kitto.mjs';
4
+ import { query } from './dependencies.mjs';
5
+ import { configureServiceEnvironment } from './scope-service.mjs';
6
+
7
+ export async function runEnvironmentSetup(plan) {
8
+ const { unit, deps, installAgents, dryRun, dshProfile } = plan;
9
+ const source = plan.source && existsSync(plan.source) ? resolve(plan.source) : plan.source;
10
+ const workspace = plan.workspace && resolve(plan.workspace);
11
+ const agents = plan.agents.filter(name => name !== 'dsh' || !unit);
12
+ const serviceOptions = { unit, source, deps, workspace, global: true, installAgents: plan.serviceInstallAgents ?? false, dshProfile };
13
+ if (unit) await configureServiceEnvironment({ ...serviceOptions, dryRun: true });
14
+ if (agents.length) {
15
+ const options = { agents, 'dry-run': dryRun };
16
+ if (agents.includes('dsh')) options['dsh-profile'] = dshProfile;
17
+ if (source === false) {
18
+ checkSelectedHosts(agents, installAgents);
19
+ if (!dryRun && installAgents) installMissingHosts(agents);
20
+ } else {
21
+ await setup({ ...options, source, 'install-agents': installAgents, keepExistingSkills: true });
22
+ }
23
+ // The DSH adapter imports modules from its native CLI, which may still be pending in a preview.
24
+ const scopedAgents = agents.filter(name => !(dryRun && installAgents && name === 'dsh' && query('dsh', ['--version']) === null));
25
+ if (scopedAgents.length !== agents.length) console.log('DSH scope registration will run after its CLI is installed.');
26
+ if (scopedAgents.length) {
27
+ const scope = { ...options, agents: scopedAgents };
28
+ if (!scopedAgents.includes('dsh')) delete scope['dsh-profile'];
29
+ await setup({ ...scope, global: true });
30
+ if (workspace) await setup({ ...scope, 'workspace-parent': workspace });
31
+ }
32
+ }
33
+ if (unit && !dryRun) await configureServiceEnvironment({ ...serviceOptions, dryRun: false });
34
+ if (agents.length && deps && source !== false) {
35
+ if (dryRun) console.log('安装时将检查配置仓库声明的辅助工具和依赖。');
36
+ else await maintain(['deps', '--apply']);
37
+ }
38
+ if (dryRun) return;
39
+ console.log('环境配置已完成。以后在项目目录开启新会话即可。');
40
+ if (workspace) console.log('未来新建的工作区也会生效:' + workspace + '/<工作区>/AGENTS.md');
41
+ if (agents.includes('codex')) console.log('首次使用 Codex 时,在 /hooks 中确认信任 Kitto 的 SessionStart hook。');
42
+ if (plan.agents.includes('dsh')) console.log('已运行的 DSH 需要重启对应服务或 profile 以加载配置。');
43
+ }
package/lib/kitto.mjs CHANGED
@@ -49,8 +49,8 @@ export function parseOptions(args) {
49
49
  const options = {};
50
50
  for (let i = 0; i < args.length; i++) {
51
51
  const arg = args[i];
52
- if (['--dry-run', '--install-agents', '--recover'].includes(arg)) options[arg.slice(2)] = true;
53
- else if (['--agents', '--source', '--ref', '--dsh-profile'].includes(arg) && args[i + 1] && !args[i + 1].startsWith('-')) options[arg.slice(2)] = 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
54
  else throw new Error(`Unknown option or missing value: ${arg}`);
55
55
  }
56
56
  if (options.agents) {
@@ -103,6 +103,26 @@ function checkHost(name) {
103
103
  console.log(`${name}: ${actual} (tested baseline ${expected})`);
104
104
  }
105
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
+
106
126
  async function replaceRuntime(home, next) {
107
127
  const runtime = join(home, 'runtime'), replacing = join(home, 'runtime.replacing');
108
128
  // Repair a directory switch interrupted before the new runtime was in place.
@@ -162,14 +182,34 @@ export async function treeHash(path, ignorePythonCache = false) {
162
182
  const name = join(relative, entry.name), full = join(directory, entry.name);
163
183
  if (entry.isDirectory()) { hash.update(`dir:${name}\0`); await walk(full, name); }
164
184
  else if (entry.isFile()) { hash.update(`file:${name}\0`); hash.update(await readFile(full)); }
165
- else throw new Error(`Unsupported symlink or special file in skill: ${full}`);
185
+ else throw Object.assign(new Error(`Unsupported symlink or special file in skill: ${full}`), {
186
+ code: 'KITTO_UNSUPPORTED_SKILL_ENTRY',
187
+ });
166
188
  }
167
189
  }
168
190
  await walk(path);
169
191
  return hash.digest('hex');
170
192
  }
171
193
 
172
- async function skillPlan(root, destination, owned = {}) {
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 = []) {
173
213
  const plans = [];
174
214
  const entries = await present(root) ? await readdir(root, { withFileTypes: true }) : [];
175
215
  for (const entry of entries) {
@@ -178,15 +218,9 @@ async function skillPlan(root, destination, owned = {}) {
178
218
  const nextHash = await treeHash(source);
179
219
  let action = 'copy';
180
220
  if (await present(target)) {
181
- const stat = await lstat(target);
182
- if (stat.isSymbolicLink()) {
183
- if (!sameLocation(resolve(dirname(target), await readlink(target)), source)) throw new Error(`Skill conflict: ${target} links elsewhere. Preserved.`);
184
- action = 'linked';
185
- } else {
186
- const current = await treeHash(target);
187
- if (current === nextHash) action = 'same';
188
- else if (current !== owned[entry.name]) throw new Error(`Skill conflict: ${target} differs from the source and last deployment. Preserved.`);
189
- }
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);
190
224
  }
191
225
  plans.push({ name: entry.name, source, target, hash: nextHash, action });
192
226
  }
@@ -198,6 +232,11 @@ async function skillPlan(root, destination, owned = {}) {
198
232
  plans.push({ name, target, action: 'remove' });
199
233
  }
200
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
+ }
201
240
  return plans;
202
241
  }
203
242
 
@@ -242,7 +281,8 @@ async function configurationPlan(state) {
242
281
  const groups = [{ name: 'shared', source: join(state.source, 'skills'), target: join(state.agentsHome, 'skills') },
243
282
  ...hostSkillRoots(state)];
244
283
  for (const group of groups) {
245
- group.plans = await skillPlan(group.source, group.target, group.name === 'shared' ? state.skills : state.hostSkills?.[group.name]);
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]);
246
286
  for (const plan of group.plans) console.log(`skill ${plan.action}: ${plan.name} (${group.name})`);
247
287
  }
248
288
  const instructions = await instructionPlan(state);
@@ -262,13 +302,19 @@ async function deploy(state, apply, plan = undefined, codeRoot = undefined) {
262
302
  state.hostSkills ||= {};
263
303
  for (const { name, plans } of groups) {
264
304
  const owned = {};
305
+ const kept = [];
265
306
  for (const plan of plans) {
266
307
  if (['copy', 'remove'].includes(plan.action)) {
267
308
  await rm(plan.target, { recursive: true, force: true });
268
309
  if (plan.action === 'copy') await cp(plan.source, plan.target, { recursive: true });
269
310
  }
270
- if (plan.action !== 'remove') owned[plan.name] = plan.hash;
311
+ if (plan.action === 'keep') kept.push(plan.name);
312
+ else if (plan.action !== 'remove') owned[plan.name] = plan.hash;
271
313
  }
314
+ if (kept.length) {
315
+ state.keptSkills ||= {};
316
+ state.keptSkills[name] = kept;
317
+ } else if (state.keptSkills) delete state.keptSkills[name];
272
318
  if (name === 'shared') state.skills = owned;
273
319
  else state.hostSkills[name] = owned;
274
320
  }
@@ -396,6 +442,11 @@ async function cloneSource(home, source, url, ref) {
396
442
  }
397
443
 
398
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.');
399
450
  const home = kittoHome(), statePath = join(home, 'state.json');
400
451
  if (options.recover) {
401
452
  const work = async () => recover(await json(statePath), !options['dry-run']);
@@ -458,16 +509,7 @@ export async function setup(options = {}) {
458
509
  }
459
510
  if (local && options.ref && !ownedSource) throw new Error('Switch tags only in a Kitto-created checkout. For your own checkout, use Git.');
460
511
  console.log(`Global setup: ${agents.join(', ')}; source: ${requested}; Kitto home: ${home}`);
461
- for (const name of agents) {
462
- if (!available(name)) {
463
- if (!options['install-agents']) throw new Error(`${name} is missing. Install it natively or add --install-agents (pins ${hosts[name].version}).`);
464
- const requiredNode = hosts[name].node;
465
- if (requiredNode && requiredNode.localeCompare(process.versions.node, 'en', { numeric: true }) > 0) {
466
- throw new Error(`Installing ${name} through npm requires Node >=${requiredNode}.`);
467
- }
468
- console.log(`Install missing CLI: ${hosts[name].package}@${hosts[name].version}${name === 'dsh' ? ' (prerelease)' : ''}`);
469
- } else checkHost(name);
470
- }
512
+ checkSelectedHosts(agents, options['install-agents']);
471
513
  const state = { ...old, schema: 1, ready: false, detached: false, removing: false, removedAgents: [], source, agents, dshProfile,
472
514
  agentsHome: old.agentsHome || resolve((agents.includes('pi') && process.env.PI_AGENTS_DIR)
473
515
  || (agents.includes('dsh') && process.env.DSH_AGENTS_HOME) || join(homedir(), '.agents')),
@@ -476,6 +518,7 @@ export async function setup(options = {}) {
476
518
  dshHome: old.dshHome || resolve(process.env.DSH_HOME || join(homedir(), '.dsh')),
477
519
  version: (await json(join(packageRoot, 'package.json'))).version,
478
520
  };
521
+ if (options.keepExistingSkills === true) state.keepExistingSkills = true;
479
522
  if (agents.includes('codex') && state.agentsHome !== resolve(homedir(), '.agents')) {
480
523
  throw new Error('Codex discovers shared skills in ~/.agents. Use that common root for PI_AGENTS_DIR / DSH_AGENTS_HOME when selecting Codex.');
481
524
  }
@@ -505,10 +548,7 @@ export async function setup(options = {}) {
505
548
  run('npm', ['install', '--global', `pnpm@${pnpmVersion}`]);
506
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.');
507
550
  }
508
- for (const name of agents) if (!available(name)) {
509
- run('npm', ['install', '--global', `${hosts[name].package}@${hosts[name].version}`]);
510
- checkHost(name);
511
- }
551
+ installMissingHosts(agents);
512
552
  if (!local && !resume) await cloneSource(home, source, requested, options.ref);
513
553
  if (switchTag) {
514
554
  if (sourceRevision(source).dirty) throw new Error('Source has local changes. Commit or resolve them before switching tags.');