@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.
@@ -0,0 +1,241 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { homedir } from 'node:os';
3
+ import { resolve } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { promisify } from 'node:util';
6
+
7
+ const agents = ['pi', 'codex', 'dsh'];
8
+ const names = { pi: 'Pi', codex: 'Codex', dsh: 'DeepSeek Harness (DSH)' };
9
+ const serviceUnit = 'dsh.service';
10
+ const exec = promisify(execFile);
11
+
12
+ async function detectEnvironment() {
13
+ async function works(command, args) {
14
+ try {
15
+ await exec(command, args, { timeout: 3000 });
16
+ return true;
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
21
+ const [detected, pnpmAvailable, serviceActive] = await Promise.all([
22
+ Promise.all(agents.map(name => works(name, ['--version']))),
23
+ works('pnpm', ['--version']),
24
+ process.platform === 'linux' && works('/usr/bin/systemctl', ['--system', 'is-active', '--quiet', serviceUnit]),
25
+ ]);
26
+ return {
27
+ available: agents.filter((_, index) => detected[index]),
28
+ pnpmAvailable,
29
+ serviceActive,
30
+ canConfigureService: process.getuid?.() === 0 && process.geteuid?.() === 0,
31
+ };
32
+ }
33
+
34
+ function expandHome(path) {
35
+ if (path === '~') return homedir();
36
+ return path.startsWith('~/') ? resolve(homedir(), path.slice(2)) : path;
37
+ }
38
+
39
+ async function configure({ input, output, environment, execute, probeServicePnpm }) {
40
+ const terminal = Boolean(input.isTTY && output.isTTY);
41
+ const rl = createInterface({ input, output, terminal });
42
+ const lines = rl[Symbol.asyncIterator]();
43
+ let interrupted = false;
44
+ rl.on('SIGINT', () => {
45
+ interrupted = true;
46
+ rl.close();
47
+ });
48
+ const print = line => output.write(line + '\n');
49
+
50
+ async function ask(prompt) {
51
+ if (interrupted) return undefined;
52
+ if (terminal) {
53
+ rl.setPrompt(prompt + ' ');
54
+ rl.prompt();
55
+ } else {
56
+ output.write(prompt + ' ');
57
+ }
58
+ const reply = await lines.next();
59
+ return interrupted || reply.done ? undefined : reply.value.trim();
60
+ }
61
+
62
+ async function choose(prompt, parse) {
63
+ while (true) {
64
+ const answer = await ask(prompt);
65
+ if (answer === undefined) return undefined;
66
+ const choice = parse(answer);
67
+ if (choice !== undefined) return choice;
68
+ print('输入无效,请重试。');
69
+ }
70
+ }
71
+
72
+ async function yesNo(prompt, defaultValue) {
73
+ return choose(prompt + (defaultValue ? ' [Y/n]' : ' [y/N]'), answer => {
74
+ if (!answer) return defaultValue;
75
+ if (/^(y|yes|是)$/i.test(answer)) return true;
76
+ if (/^(n|no|否)$/i.test(answer)) return false;
77
+ });
78
+ }
79
+
80
+ try {
81
+ const { available, pnpmAvailable, serviceActive, canConfigureService } = environment;
82
+ const serviceAvailable = serviceActive && canConfigureService;
83
+ const defaults = agents.filter(agent => available.includes(agent) || (agent === 'dsh' && serviceAvailable));
84
+ print('Kitto 环境安装向导');
85
+ print('为选中的宿主配置当前账号的共享规则与 skills。按 Ctrl+C 可取消。');
86
+ for (const [index, agent] of agents.entries()) {
87
+ print(` ${index + 1}. ${names[agent]}(${available.includes(agent) ? '已安装 CLI' : '未检测到 CLI'})`);
88
+ }
89
+ if (serviceActive) {
90
+ print('检测到正在运行的系统服务 dsh.service。' +
91
+ (canConfigureService ? '可以配置服务账号。' : '需要 root 权限才能配置服务账号。'));
92
+ }
93
+
94
+ let selected;
95
+ let unit;
96
+ let installAgents;
97
+ while (true) {
98
+ selected = await choose(
99
+ `选择宿主,可用逗号分隔编号或名称${defaults.length ? ` [${defaults.join(',')}]` : ''},输入 0 取消。`,
100
+ answer => {
101
+ if (answer === '0') return [];
102
+ if (!answer && defaults.length) return defaults;
103
+ const items = answer.toLowerCase().split(/[,,\s]+/).filter(Boolean);
104
+ const chosen = items.map(item => /^[1-3]$/.test(item) ? agents[Number(item) - 1] : item);
105
+ if (chosen.length && chosen.every(item => agents.includes(item))) return [...new Set(chosen)];
106
+ },
107
+ );
108
+ if (!selected?.length) return undefined;
109
+
110
+ unit = undefined;
111
+ if (selected.includes('dsh') && serviceAvailable) {
112
+ const useService = await yesNo('配置 dsh.service 使用的 DSH 账号?', true);
113
+ if (useService === undefined) return undefined;
114
+ if (useService) unit = serviceUnit;
115
+ }
116
+
117
+ const missing = selected.filter(agent => !available.includes(agent) && !(agent === 'dsh' && unit));
118
+ installAgents = false;
119
+ if (missing.length) {
120
+ installAgents = await yesNo(`补装 ${missing.map(agent => names[agent]).join('、')}?`, true);
121
+ if (installAgents === undefined) return undefined;
122
+ if (!installAgents) continue;
123
+ }
124
+ break;
125
+ }
126
+
127
+ print('配置来源');
128
+ print('完整配置包含仓库的 AGENTS.md、skills 和所选宿主的 Kitto 集成。选择 Pi 时还会同步 Pi 包、扩展和 MCP 设置。');
129
+ print(' 1. 使用默认 Kitto 配置,优先复用已有安装');
130
+ print(' 2. 指定配置仓库路径或 Git URL');
131
+ print(' 3. 仅配置共享规则与 skills');
132
+ let source;
133
+ let serviceInstallAgents;
134
+ let servicePnpmAvailable;
135
+ while (true) {
136
+ const sourceChoice = await choose('选择配置来源 [1],输入 0 取消。', answer => {
137
+ if (!answer) return '1';
138
+ if (['0', '1', '2', '3'].includes(answer)) return answer;
139
+ });
140
+ if (sourceChoice === undefined || sourceChoice === '0') return;
141
+
142
+ const needsPnpm = sourceChoice !== '3' && selected.includes('dsh') && !unit && pnpmAvailable === false;
143
+ if (needsPnpm) {
144
+ const installPnpm = await yesNo('本机 DSH 的完整配置需要 pnpm。允许补装 pnpm?', true);
145
+ if (installPnpm === undefined) return;
146
+ if (!installPnpm) {
147
+ print('可选择仅配置共享规则与 skills。');
148
+ continue;
149
+ }
150
+ installAgents = true;
151
+ }
152
+
153
+ if (unit && sourceChoice !== '3') {
154
+ servicePnpmAvailable ??= await probeServicePnpm(unit);
155
+ if (servicePnpmAvailable === false) {
156
+ const installPnpm = await yesNo(`服务 ${unit} 的完整配置需要 pnpm。允许在服务账号中补装 pnpm?`, true);
157
+ if (installPnpm === undefined) return;
158
+ if (!installPnpm) {
159
+ print('可选择仅配置共享规则与 skills。');
160
+ continue;
161
+ }
162
+ serviceInstallAgents = true;
163
+ }
164
+ }
165
+
166
+ if (sourceChoice === '2') {
167
+ const path = await choose('输入配置仓库路径或 Git URL。', answer => answer || undefined);
168
+ if (path === undefined) return;
169
+ source = expandHome(path);
170
+ } else if (sourceChoice === '3') {
171
+ source = false;
172
+ }
173
+ break;
174
+ }
175
+
176
+ const deps = source === false ? false : await yesNo('安装配置中声明的辅助工具和依赖?', false);
177
+ if (deps === undefined) return undefined;
178
+ const workspace = await ask('工作区父目录(可选)。例如未来项目会放在 ~/workspaces/workspace-1 下,就填 ~/workspaces。留空使用全局配置。');
179
+ if (workspace === undefined) return undefined;
180
+
181
+ let dshProfile = 'web';
182
+ if (selected.includes('dsh')) {
183
+ dshProfile = await choose('DSH 配置档名称 [web]。', answer => {
184
+ if (!answer) return 'web';
185
+ if (/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(answer) && answer !== 'desktop') return answer;
186
+ });
187
+ if (dshProfile === undefined) return undefined;
188
+ }
189
+
190
+ const plan = {
191
+ agents: selected, source, installAgents, deps, workspace: workspace ? expandHome(workspace) : undefined,
192
+ unit, dshProfile,
193
+ };
194
+ if (serviceInstallAgents) plan.serviceInstallAgents = true;
195
+ print('安装计划');
196
+ print(` 宿主 ${selected.map(agent => names[agent]).join('、')}`);
197
+ print(` 配置来源 ${source === false ? '仅配置共享规则与 skills' : source ?? '默认 Kitto 配置'}`);
198
+ print(' 共享范围 全局' + (plan.workspace ? `,以及工作区 ${plan.workspace}` : ''));
199
+ if (selected.includes('dsh')) print(` DSH ${unit ?? '当前账号'},配置档 ${dshProfile}`);
200
+ print(` 补装缺少的宿主和必需工具 ${installAgents ? '是' : '否'}`);
201
+ if (serviceInstallAgents) print(` 为 ${unit} 的账号补装 pnpm 是`);
202
+ if (source !== false) print(` 安装配置声明的辅助依赖 ${deps ? '是' : '否'}`);
203
+
204
+ let action = await choose('下一步 [1]。1 预览,2 安装,0 取消。', answer => {
205
+ if (!answer) return '1';
206
+ if (['0', '1', '2'].includes(answer)) return answer;
207
+ });
208
+ if (action === '1') {
209
+ await execute({ ...plan, dryRun: true });
210
+ action = await choose('预览完成 [0]。2 按此计划安装,0 退出。', answer => {
211
+ if (!answer || answer === '0') return '0';
212
+ if (answer === '2') return answer;
213
+ });
214
+ if (action !== '2') {
215
+ print('已退出,未执行安装。');
216
+ return true;
217
+ }
218
+ }
219
+ if (action !== '2') return;
220
+ rl.close();
221
+ await execute({ ...plan, dryRun: false });
222
+ return true;
223
+ } finally {
224
+ rl.close();
225
+ }
226
+ }
227
+
228
+ export async function runWizard({
229
+ input = process.stdin, output = process.stdout, detect = detectEnvironment, execute,
230
+ probeServicePnpm = async unit => {
231
+ const { servicePnpmAvailable } = await import('./scope-service.mjs');
232
+ return servicePnpmAvailable(unit);
233
+ },
234
+ } = {}) {
235
+ const runSetup = execute ?? (async plan => {
236
+ const { runEnvironmentSetup } = await import('./environment-setup.mjs');
237
+ await runEnvironmentSetup(plan);
238
+ });
239
+ const handled = await configure({ input, output, environment: await detect(), execute: runSetup, probeServicePnpm });
240
+ if (!handled) output.write('已取消安装。\n');
241
+ }
@@ -0,0 +1,26 @@
1
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ export function newerStable(candidate, current) {
5
+ if (!/^\d+\.\d+\.\d+$/.test(candidate) || !/^\d+\.\d+\.\d+(?:-[\w.]+)?$/.test(current)) return false;
6
+ const a = candidate.split('.').map(Number), b = current.split(/[.-]/).slice(0, 3).map(Number);
7
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
8
+ return current.includes('-');
9
+ }
10
+
11
+ // One bounded registry request per day, only for Kitto itself. No host/plugin scan.
12
+ // Errors (including unpublished packages, offline or unwritable cache) are silent.
13
+ export async function updateNotice(home, current, { fetcher = fetch, now = Date.now() } = {}) {
14
+ try {
15
+ const path = join(home, 'update-check.json');
16
+ let cache = {};
17
+ try { cache = JSON.parse(await readFile(path, 'utf8')); } catch {}
18
+ if (Number.isFinite(cache.checkedAt) && now - cache.checkedAt < 86_400_000 && now >= cache.checkedAt) return;
19
+ await mkdir(home, { recursive: true });
20
+ await writeFile(path, JSON.stringify({ checkedAt: now }), { mode: 0o600 });
21
+ const result = await fetcher('https://registry.npmjs.org/@phyzess%2fkitto/latest', { signal: AbortSignal.timeout(2000) });
22
+ if (!result.ok) return;
23
+ const metadata = await result.json();
24
+ if (newerStable(metadata.version, current)) return `Kitto ${metadata.version} is available. Ask the Kitto skill to review the update.`;
25
+ } catch { /* Maintenance must never prevent an agent session from starting. */ }
26
+ }
@@ -0,0 +1,139 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, readdir } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { dependencyPlan, executable, npmSpec, npxPackage, optionalJson, piServers, query } from './dependencies.mjs';
5
+ import { hostSkillRoots } from './host-config.mjs';
6
+
7
+ const version = output => output?.match(/\d+\.\d+\.\d+(?:-[\w.-]+)?/)?.[0] || null;
8
+
9
+ async function entries(path) {
10
+ try { return await readdir(path, { withFileTypes: true }); }
11
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
12
+ }
13
+
14
+ async function resources(root, revision, hashTree) {
15
+ const rows = [];
16
+ for (const entry of await entries(root)) {
17
+ const path = join(root, entry.name);
18
+ if (!entry.isDirectory() || !(await entries(path)).some(file => file.name === 'SKILL.md' && file.isFile())) continue;
19
+ rows.push({ kind: 'skill', name: entry.name, revision, contentSha256: await hashTree(path, true) });
20
+ }
21
+ return rows;
22
+ }
23
+
24
+ async function piVersions(state, revision) {
25
+ const rows = [];
26
+ const settings = await optionalJson(join(state.source, 'config/pi/settings.json'));
27
+ const machine = await optionalJson(join(state.piHome, 'settings.json'), settings);
28
+ const specs = new Map();
29
+ for (const list of [settings.packages || [], machine.packages || []]) {
30
+ for (const entry of list) {
31
+ const source = typeof entry === 'string' ? entry : entry.source;
32
+ if (source?.startsWith('npm:')) {
33
+ const [name, target] = npmSpec(source);
34
+ specs.set(name, target);
35
+ } else if (source) {
36
+ if (!rows.some(row => row.name === source)) rows.push({ name: source, kind: 'source', installed: null });
37
+ }
38
+ }
39
+ }
40
+ for (const [name, target] of specs) {
41
+ const manifest = await optionalJson(join(state.piHome, 'npm/node_modules', name, 'package.json'));
42
+ rows.push({ kind: 'npm', name, target, installed: manifest.version || null });
43
+ }
44
+ for (const [id, server] of Object.entries(await piServers(state))) {
45
+ const [name, target] = npxPackage(server);
46
+ if (name) rows.push({ kind: 'npm', name, target, installed: null, mcp: id, note: 'Version resolved by npx at launch.' });
47
+ else rows.push({ kind: 'external', name: server.command, mcp: id, path: executable(server.command) || null });
48
+ }
49
+ const extensions = join(state.source, 'config/pi/extensions');
50
+ for (const file of await entries(extensions)) {
51
+ if (!file.isFile() || !file.name.endsWith('.ts')) continue;
52
+ rows.push({ kind: 'extension', name: file.name, revision, contentSha256: createHash('sha256').update(await readFile(join(extensions, file.name))).digest('hex') });
53
+ }
54
+ return rows.map(row => ({ ...row, owner: 'pi' }));
55
+ }
56
+
57
+ async function codexVersions(state) {
58
+ const output = query('codex', ['plugin', 'list', '--json'], { ...process.env, CODEX_HOME: state.codexHome });
59
+ if (!output) return [{ kind: 'inventory', owner: 'codex', note: 'Native plugin inventory unavailable.' }];
60
+ try {
61
+ return JSON.parse(output).installed.map(plugin => ({
62
+ kind: 'plugin', owner: 'codex', name: plugin.pluginId, installed: plugin.version || null, enabled: plugin.enabled,
63
+ }));
64
+ } catch {
65
+ return [{ kind: 'inventory', owner: 'codex', note: 'Unrecognized native plugin inventory.' }];
66
+ }
67
+ }
68
+
69
+ async function dshVersions(state) {
70
+ const profile = state.dshProfile || 'web';
71
+ const root = join(state.dshHome, 'profiles', profile);
72
+ const manifest = await optionalJson(join(root, 'package.json'));
73
+ const rows = [];
74
+ for (const name of manifest.dsh?.profile?.bundles || []) {
75
+ const target = manifest.dependencies?.[name];
76
+ const bundled = !target;
77
+ const installed = bundled ? {} : await optionalJson(join(root, 'node_modules', name, 'package.json'));
78
+ rows.push({ kind: bundled ? 'bundle' : 'npm', owner: 'dsh', profile,
79
+ name, target: target || null, installed: installed.version || (name === '@phyzess/kitto' ? state.version : null),
80
+ note: bundled ? 'Bundled with DSH.' : undefined });
81
+ }
82
+ return rows;
83
+ }
84
+
85
+ async function upstream(kind, name) {
86
+ const encoded = encodeURIComponent(name);
87
+ const url = kind === 'npm' ? `https://registry.npmjs.org/${encoded}` : `https://pypi.org/pypi/${encoded}/json`;
88
+ try {
89
+ const response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
90
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
91
+ const data = await response.json();
92
+ if (kind === 'pypi') return { source: url, version: data.info.version, requiresPython: data.info.requires_python };
93
+ const channels = Object.fromEntries(Object.entries(data['dist-tags'] || {}).filter(
94
+ ([tag]) => ['latest', 'next', 'alpha', 'beta', 'canary'].includes(tag),
95
+ ));
96
+ const requirements = Object.fromEntries(Object.entries(channels).map(([tag, value]) => {
97
+ const release = data.versions?.[value];
98
+ return [tag, { engines: release?.engines, peers: release?.peerDependencies, deprecated: release?.deprecated }];
99
+ }));
100
+ return { source: url, channels, requirements };
101
+ } catch (error) {
102
+ return { source: url, error: error.message };
103
+ }
104
+ }
105
+
106
+ export async function versionReport(state, hosts, pnpmVersion, online, hashTree) {
107
+ const rows = [{ kind: 'npm', owner: 'kitto', name: '@phyzess/kitto', installed: state.version }];
108
+ for (const name of state.agents) {
109
+ rows.push({ kind: 'npm', owner: name, name: hosts[name].package, installed: version(query(name, ['--version'])), tested: hosts[name].version });
110
+ }
111
+ if (state.agents.includes('dsh')) rows.push({ kind: 'npm', owner: 'dsh', name: 'pnpm', installed: version(query('pnpm', ['--version'])), tested: pnpmVersion });
112
+ const revision = query('git', ['-C', state.source, 'rev-parse', 'HEAD']);
113
+ if (state.agents.includes('pi')) rows.push(...await piVersions(state, revision));
114
+ if (state.agents.includes('codex')) rows.push(...await codexVersions(state));
115
+ if (state.agents.includes('dsh')) rows.push(...await dshVersions(state));
116
+ for (const { name, source } of [{ name: 'shared', source: join(state.source, 'skills') }, ...hostSkillRoots(state)]) {
117
+ rows.push(...(await resources(source, revision, hashTree)).map(row => ({ ...row, owner: name })));
118
+ }
119
+ for (const tool of await dependencyPlan(state)) {
120
+ const kind = { mise: 'npm', pip: 'pypi', brew: 'brew' }[tool.manager] || 'external';
121
+ rows.push({ ...tool, kind });
122
+ }
123
+ if (online) {
124
+ const groups = new Map();
125
+ for (const row of rows.filter(row => ['npm', 'pypi'].includes(row.kind))) {
126
+ const key = `${row.kind}:${row.name}`;
127
+ if (!groups.has(key)) groups.set(key, []);
128
+ groups.get(key).push(row);
129
+ }
130
+ const batches = [...groups.values()];
131
+ for (let i = 0; i < batches.length; i += 6) {
132
+ await Promise.all(batches.slice(i, i + 6).map(async group => {
133
+ const result = await upstream(group[0].kind, group[0].name);
134
+ for (const row of group) row.upstream = result;
135
+ }));
136
+ }
137
+ }
138
+ return { checkedAt: new Date().toISOString(), online, components: rows };
139
+ }
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "@phyzess/kitto",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Portable personal configuration for Pi, Codex and DeepSeek Harness",
5
+ "type": "module",
6
+ "bin": { "kitto": "bin/kitto.mjs" },
7
+ "engines": { "node": ">=22.0.0", "dsh": ">=0.2.2-rc.1 <0.3.0" },
8
+ "publishConfig": { "access": "public" },
9
+ "repository": { "type": "git", "url": "git+https://github.com/phyzess/kitto.git" },
10
+ "files": ["bin/*.mjs", "lib/*.mjs", "lib/*.py", "integration/", "sync.sh", "CHANGELOG.md"],
11
+ "scripts": {
12
+ "test": "node --test tests/kitto.test.mjs tests/scope*.test.mjs tests/setup-wizard.test.mjs",
13
+ "prepublishOnly": "npm test && python3 -m unittest discover -s tests -v",
14
+ "release": "node scripts/release.mjs"
15
+ },
16
+ "pi": { "extensions": ["./integration/pi.mjs"], "skills": ["./integration/skills"] },
17
+ "dsh": { "manifestVersion": 1, "bundle": { "patch": "./integration/cordis.patch.yml" } }
18
+ }