@phyzess/kitto 0.2.1 → 0.3.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,111 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
3
+ import { homedir, tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+
6
+ // The Desktop app manages this reserved profile; the name is case-insensitive.
7
+ export const desktopProfile = 'desktop';
8
+ const profileName = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
9
+
10
+ export function normalizeDshProfile(value = 'web') {
11
+ const profile = String(value);
12
+ return profile.toLowerCase() === desktopProfile ? desktopProfile : profile;
13
+ }
14
+
15
+ export function isDesktopProfile(value) {
16
+ return typeof value === 'string' && value.toLowerCase() === desktopProfile;
17
+ }
18
+
19
+ /** Validate a profile name and normalize the reserved Desktop name. */
20
+ export function validateDshProfile(value, message = 'Invalid DSH CLI profile name.') {
21
+ if (!profileName.test(value)) throw new Error(message);
22
+ return normalizeDshProfile(value);
23
+ }
24
+
25
+ export const desktopProfileNotice = 'DSH desktop profile: managed by the DeepSeek Harness Desktop app. ' +
26
+ 'Kitto v1 deploys only global AGENTS.md and skills for it; it does not install a Kitto bundle, write ' +
27
+ 'profiles/desktop/cordis.patch.yml, register a scope adapter or sync the MCP home patch. ' +
28
+ 'For a Kitto bundle, scoped configuration or MCP sync, use --dsh-profile web instead.';
29
+
30
+ export const desktopScopeError = 'The DSH desktop profile is managed by the DeepSeek Harness Desktop app; ' +
31
+ 'Kitto v1 does not write scoped profile patches or adapters for it. Use global setup ' +
32
+ '(kitto setup --agents dsh --dsh-profile desktop) or select the web profile for scoped configuration.';
33
+
34
+ const desktopProbeWarnings = {
35
+ 'npm-cli': 'The dsh on PATH is the npm CLI and cannot manage the desktop profile. Kitto does not use it for this ' +
36
+ 'profile and still deploys only global rules and skills; use --dsh-profile web for Kitto bundle or scope support.',
37
+ uninitialized: 'The DSH desktop profile has not been initialized. Start DeepSeek Harness Desktop once so it can ' +
38
+ 'create its profile, then fully quit it; Kitto still deploys only global rules and skills.',
39
+ unavailable: 'No dsh CLI was found on PATH, so the Desktop profile check was skipped. Kitto still deploys only ' +
40
+ 'global rules and skills, and the Desktop app remains the owner of its profile.',
41
+ timeout: 'The Desktop profile check timed out. Kitto left the app-managed profile untouched and still deploys only ' +
42
+ 'global rules and skills; fully quit DeepSeek Harness Desktop and rerun if you want the check repeated.',
43
+ };
44
+
45
+ /**
46
+ * Best-effort desktop probe that never touches the app-managed profile.
47
+ *
48
+ * A missing manifest is reported without running any CLI. Otherwise the
49
+ * manifest (and compatibility.json when present) is copied to a scratch
50
+ * DSH_HOME and the carrier is asked there, so its profile lock and any
51
+ * lock file land in the scratch directory. A timeout or unreadable profile
52
+ * is reported as such, not treated as an uninitialized profile.
53
+ */
54
+ export function probeDesktopProfile({ dshHome, env = process.env, timeoutMs = 60_000 } = {}) {
55
+ const home = dshHome || env.DSH_HOME || join(homedir(), '.dsh');
56
+ const profileDir = join(home, 'profiles', desktopProfile);
57
+ const manifest = join(profileDir, 'package.json');
58
+ try { lstatSync(manifest); } catch (error) {
59
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return { kind: 'uninitialized', detail: manifest };
60
+ return { kind: 'unknown', detail: `cannot inspect ${manifest}: ${error.code || error.message}` };
61
+ }
62
+
63
+ let scratch;
64
+ try {
65
+ scratch = mkdtempSync(join(tmpdir(), 'kitto-dsh-desktop-'));
66
+ const scratchProfile = join(scratch, 'profiles', desktopProfile);
67
+ mkdirSync(scratchProfile, { recursive: true });
68
+ copyFileSync(manifest, join(scratchProfile, 'package.json'));
69
+ const compatibility = join(profileDir, 'compatibility.json');
70
+ if (existsSync(compatibility)) copyFileSync(compatibility, join(scratchProfile, 'compatibility.json'));
71
+ const result = spawnSync('dsh', ['plugin', '--profile', desktopProfile, 'version-exemptions'], {
72
+ encoding: 'utf8', timeout: timeoutMs, stdio: ['ignore', 'pipe', 'pipe'],
73
+ env: { ...env, DSH_HOME: scratch },
74
+ });
75
+ if (result.error?.code === 'ETIMEDOUT' || result.signal === 'SIGTERM' || result.signal === 'SIGKILL') {
76
+ return { kind: 'timeout', detail: `probe timed out after ${timeoutMs}ms` };
77
+ }
78
+ if (result.error?.code === 'ENOENT') return { kind: 'unavailable', detail: 'dsh was not found on PATH' };
79
+ if (result.error) return { kind: 'unavailable', detail: result.error.message };
80
+ const detail = `${result.stdout ?? ''}\n${result.stderr ?? ''}`.trim();
81
+ if (/managed exclusively by the Electron application/i.test(detail)) return { kind: 'npm-cli', detail };
82
+ if (/Open DeepSeek Harness Desktop once to initialize its profile/i.test(detail)) return { kind: 'uninitialized', detail };
83
+ if (result.status === 0) {
84
+ try {
85
+ JSON.parse(result.stdout ?? '');
86
+ return { kind: 'desktop-cli', detail };
87
+ } catch { /* Not a DSH exemption report. */ }
88
+ }
89
+ return { kind: 'unknown', detail: detail || `exit ${result.status}` };
90
+ } catch (error) {
91
+ return { kind: 'unknown', detail: error.message };
92
+ } finally {
93
+ if (scratch) rmSync(scratch, { recursive: true, force: true });
94
+ }
95
+ }
96
+
97
+ /** Print one actionable line for a Desktop probe result. */
98
+ export function reportDesktopProbe(probe, { log = console.log, warn = console.warn } = {}) {
99
+ if (probe.kind === 'desktop-cli') {
100
+ log('DSH desktop CLI: initialized profile detected (probe ran against a temporary copy).');
101
+ return;
102
+ }
103
+ if (Object.hasOwn(desktopProbeWarnings, probe.kind)) {
104
+ warn(`Kitto: ${desktopProbeWarnings[probe.kind]}`);
105
+ return;
106
+ }
107
+ const detail = probe.detail?.split('\n').slice(0, 2).join(' ').slice(0, 300);
108
+ warn(`Kitto: could not verify the DSH desktop profile${detail ? ` (${detail})` : ''}. ` +
109
+ 'Kitto still deploys only global rules and skills; check that DeepSeek Harness Desktop has been started once ' +
110
+ 'and fully quit.');
111
+ }
@@ -2,11 +2,17 @@ import { existsSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { checkSelectedHosts, installMissingHosts, maintain, setup } from './kitto.mjs';
4
4
  import { query } from './dependencies.mjs';
5
+ import { isDesktopProfile } from './dsh-profile.mjs';
5
6
  import { configureServiceEnvironment } from './scope-service.mjs';
6
7
 
7
8
  export async function runEnvironmentSetup(plan) {
8
9
  const { unit, deps, installAgents, dryRun, dshProfile } = plan;
10
+ const desktopDsh = isDesktopProfile(dshProfile);
9
11
  const source = plan.source && existsSync(plan.source) ? resolve(plan.source) : plan.source;
12
+ if (source === false && desktopDsh && plan.agents.includes('dsh')) {
13
+ throw new Error('The DSH desktop profile requires a configuration source: the "shared rules and skills only" ' +
14
+ 'mode would deploy no global rules. Choose a source or use --dsh-profile web.');
15
+ }
10
16
  const workspace = plan.workspace && resolve(plan.workspace);
11
17
  const agents = plan.agents.filter(name => name !== 'dsh' || !unit);
12
18
  const serviceOptions = { unit, source, deps, workspace, global: true, installAgents: plan.serviceInstallAgents ?? false, dshProfile };
@@ -21,8 +27,14 @@ export async function runEnvironmentSetup(plan) {
21
27
  await setup({ ...options, source, 'install-agents': installAgents, keepExistingSkills: true });
22
28
  }
23
29
  // 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.');
30
+ const pendingDsh = !desktopDsh && dryRun && installAgents && agents.includes('dsh') && query('dsh', ['--version']) === null;
31
+ const scopedAgents = agents.filter(name => !(pendingDsh && name === 'dsh'))
32
+ // The app-managed Desktop profile has no Kitto scope adapter in v1.
33
+ .filter(name => !(name === 'dsh' && desktopDsh));
34
+ if (desktopDsh && agents.includes('dsh')) {
35
+ console.log('DSH Desktop:由 App 管理,跳过 scoped 适配器;本次只处理全局规则和 skills。');
36
+ }
37
+ if (pendingDsh) console.log('DSH scope registration will run after its CLI is installed.');
26
38
  if (scopedAgents.length) {
27
39
  const scope = { ...options, agents: scopedAgents };
28
40
  if (!scopedAgents.includes('dsh')) delete scope['dsh-profile'];
@@ -39,5 +51,9 @@ export async function runEnvironmentSetup(plan) {
39
51
  console.log('环境配置已完成。以后在项目目录开启新会话即可。');
40
52
  if (workspace) console.log('未来新建的工作区也会生效:' + workspace + '/<工作区>/AGENTS.md');
41
53
  if (agents.includes('codex')) console.log('首次使用 Codex 时,在 /hooks 中确认信任 Kitto 的 SessionStart hook。');
42
- if (plan.agents.includes('dsh')) console.log('已运行的 DSH 需要重启对应服务或 profile 以加载配置。');
54
+ if (desktopDsh && plan.agents.includes('dsh')) {
55
+ console.log('完全退出并重新打开 DeepSeek Harness Desktop,以加载部署的全局 AGENTS.md 和 skills。');
56
+ } else if (plan.agents.includes('dsh')) {
57
+ console.log('已运行的 DSH 需要重启对应服务或 profile 以加载配置。');
58
+ }
43
59
  }
@@ -8,6 +8,27 @@ const optionalText = async path => {
8
8
  catch (error) { if (error.code === 'ENOENT') return null; throw error; }
9
9
  };
10
10
 
11
+ // Explicit boundary between the shared layer and the host addendum. Without it,
12
+ // a truncated common.md can look like an addendum prefix of an older deployed
13
+ // file, so the split would be ambiguous. Keep in sync with lib/pi_config.py.
14
+ const hostAddendumBoundary = '<!-- kitto:host-addendum -->';
15
+
16
+ // One canonical form for shared-layer files: no BOM, LF line endings.
17
+ export function normalizeInstructions(text) {
18
+ return String(text).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
19
+ }
20
+
21
+ // Shared rules first, a boundary line, then the host addendum. Keep this
22
+ // byte-identical to compose_agents() in lib/pi_config.py, which the Pi adapter
23
+ // uses. A single section (legacy sources without the shared layer) keeps the
24
+ // historical output without a boundary.
25
+ export function composeInstructions(...sections) {
26
+ const parts = sections
27
+ .map(section => (typeof section === 'string' ? normalizeInstructions(section).trim() : ''))
28
+ .filter(Boolean);
29
+ return parts.length ? `${parts.join(`\n\n${hostAddendumBoundary}\n\n`)}\n` : '';
30
+ }
31
+
11
32
  export function hostSkillRoots(state) {
12
33
  return state.agents.map(name => ({
13
34
  name,
@@ -18,12 +39,15 @@ export function hostSkillRoots(state) {
18
39
 
19
40
  export async function instructionPlan(state) {
20
41
  const plans = [];
42
+ const common = await optionalText(join(state.source, 'config/instructions/common.md'));
43
+ const reserved = [begin, end, hostAddendumBoundary];
44
+ if (reserved.some(marker => common?.includes(marker))) throw new Error('Reserved Kitto markers in shared instructions.');
21
45
  for (const name of state.agents.filter(name => name !== 'pi')) {
22
- const source = await optionalText(join(state.source, 'config', name, 'AGENTS.md'));
46
+ const addendum = await optionalText(join(state.source, 'config', name, 'AGENTS.md'));
23
47
  const home = state[name + 'Home'];
24
48
  const target = join(home, 'AGENTS.md');
25
- if (source === null && !state.instructions?.[name]) continue;
26
- if (source?.includes(begin) || source?.includes(end)) throw new Error(`Reserved Kitto markers in ${name} instructions.`);
49
+ if (common === null && addendum === null && !state.instructions?.[name]) continue;
50
+ if (reserved.some(marker => addendum?.includes(marker))) throw new Error(`Reserved Kitto markers in ${name} instructions.`);
27
51
  const stat = await lstat(target).catch(error => {
28
52
  if (error.code === 'ENOENT') return null;
29
53
  throw error;
@@ -32,7 +56,8 @@ export async function instructionPlan(state) {
32
56
  const before = (await optionalText(target)) || '';
33
57
  const start = before.indexOf(begin), finish = before.indexOf(end);
34
58
  const previous = state.instructions?.[name];
35
- const block = source?.trim() ? `${begin}\n${source.trim()}\n${end}\n` : '';
59
+ const body = composeInstructions(common, addendum);
60
+ const block = body ? `${begin}\n${body}${end}\n` : '';
36
61
  let after;
37
62
  if (start < 0 && finish < 0) {
38
63
  after = block ? before + (before && !before.endsWith('\n') ? '\n' : '') + block : before;
package/lib/hosts.mjs ADDED
@@ -0,0 +1,288 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { mkdtempSync, rmSync } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { hosts, kittoHome } from './kitto.mjs';
7
+ import { isDesktopProfile } from './dsh-profile.mjs';
8
+
9
+ // `kitto hosts` is deliberately not an updater daemon: it inspects or installs
10
+ // one pinned version per selected host, and never follows a dist-tag.
11
+ const versionPattern = /\d+\.\d+\.\d+(?:-[\w.-]+)?/;
12
+ const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
13
+ const policy = 'Policy: default to the pinned Kitto-validated baseline, never the latest release; '
14
+ + 'an explicit --version overrides it only when you ask. Kitto never upgrades or checks host CLIs automatically.';
15
+
16
+ export function parseHostsArgs(args = []) {
17
+ const options = {};
18
+ for (let i = 0; i < args.length; i++) {
19
+ const arg = args[i];
20
+ if (arg === '--check') options.check = true;
21
+ else if (arg === '--apply') options.apply = true;
22
+ else if (arg === '--host' || arg === '--version') {
23
+ const value = args[i + 1];
24
+ if (!value || value.startsWith('-')) throw new Error(`Missing value for ${arg}.`);
25
+ options[arg.slice(2)] = value;
26
+ i++;
27
+ } else throw new Error(`Unknown hosts option: ${arg}. Read the Kitto skill or run kitto --help.`);
28
+ }
29
+ if (options.check && options.apply) throw new Error('Choose either --check or --apply for hosts.');
30
+ if (options.host && !hosts[options.host]) throw new Error('--host must be pi, codex or dsh.');
31
+ if (options.version && !exactVersion.test(options.version)) {
32
+ throw new Error(`--version must be one exact semantic version (got ${options.version}); dist-tags and ranges are refused.`);
33
+ }
34
+ delete options.check;
35
+ return options;
36
+ }
37
+
38
+ async function readState() {
39
+ const home = kittoHome();
40
+ let state;
41
+ try { state = JSON.parse(await readFile(join(home, 'state.json'), 'utf8')); }
42
+ catch (error) {
43
+ if (error.code === 'ENOENT') throw new Error(`Kitto is not set up in ${home}. Run kitto setup first.`);
44
+ throw error;
45
+ }
46
+ if (state.detached || state.removing) throw new Error('Kitto is detached or removal is incomplete. Use setup to reconnect, or finish remove.');
47
+ if (!Array.isArray(state.agents) || !state.agents.length) throw new Error('Kitto state records no selected hosts. Run kitto setup again.');
48
+ return { home, state };
49
+ }
50
+
51
+ const appManaged = (state, name) => name === 'dsh' && isDesktopProfile(state.dshProfile);
52
+
53
+ // Codex creates helper files under CODEX_HOME even for --version. Probe with a
54
+ // scratch home so check and apply never write the user's Codex state.
55
+ function probeHost(name) {
56
+ const probe = name === 'codex' ? mkdtempSync(join(tmpdir(), 'kitto-codex-hosts-')) : null;
57
+ try {
58
+ const result = spawnSync(name, ['--version'], {
59
+ encoding: 'utf8', timeout: 8000,
60
+ env: probe ? { ...process.env, CODEX_HOME: probe } : process.env,
61
+ });
62
+ if (result.error?.code === 'ENOENT') return { status: 'missing' };
63
+ if (result.error) return { status: 'unreadable', detail: result.error.message };
64
+ if (result.status !== 0) {
65
+ const detail = `${result.stderr ?? ''}\n${result.stdout ?? ''}`.trim().split('\n')[0];
66
+ return { status: 'unreadable', detail: detail || `exit ${result.status}` };
67
+ }
68
+ const output = (result.stdout ?? '').trim();
69
+ const current = output.match(versionPattern)?.[0] || null;
70
+ return current ? { status: 'found', current }
71
+ : { status: 'unreadable', detail: output.split('\n')[0] || 'empty version output' };
72
+ } finally {
73
+ if (probe) rmSync(probe, { recursive: true, force: true });
74
+ }
75
+ }
76
+
77
+ // Keep dependency-free prerelease ordering for the upgrade direction check. The
78
+ // exact target is still verified as a string after npm installs it. Split at the
79
+ // first core/prerelease hyphen only: a prerelease may itself contain hyphens.
80
+ export function compareVersions(a, b) {
81
+ const parse = value => {
82
+ const dash = value.indexOf('-');
83
+ return {
84
+ core: (dash === -1 ? value : value.slice(0, dash)).split('.').map(Number),
85
+ prerelease: dash === -1 ? [] : value.slice(dash + 1).split('.'),
86
+ };
87
+ };
88
+ const left = parse(a), right = parse(b);
89
+ for (let i = 0; i < 3; i++) {
90
+ if (left.core[i] !== right.core[i]) return left.core[i] < right.core[i] ? -1 : 1;
91
+ }
92
+ if (!left.prerelease.length || !right.prerelease.length) {
93
+ return left.prerelease.length === right.prerelease.length ? 0 : left.prerelease.length ? -1 : 1;
94
+ }
95
+ for (let i = 0; i < Math.max(left.prerelease.length, right.prerelease.length); i++) {
96
+ if (left.prerelease[i] === undefined) return -1;
97
+ if (right.prerelease[i] === undefined) return 1;
98
+ const aNumber = /^\d+$/.test(left.prerelease[i]), bNumber = /^\d+$/.test(right.prerelease[i]);
99
+ if (aNumber && bNumber) {
100
+ if (Number(left.prerelease[i]) !== Number(right.prerelease[i])) {
101
+ return Number(left.prerelease[i]) < Number(right.prerelease[i]) ? -1 : 1;
102
+ }
103
+ } else if (aNumber !== bNumber) return aNumber ? -1 : 1;
104
+ else if (left.prerelease[i] !== right.prerelease[i]) return left.prerelease[i] < right.prerelease[i] ? -1 : 1;
105
+ }
106
+ return 0;
107
+ }
108
+
109
+ function selectHosts(state, options) {
110
+ const selected = options.host ? state.agents.filter(name => name === options.host) : [...state.agents];
111
+ if (!selected.length) {
112
+ throw new Error(`${options.host} is not a selected host (${state.agents.join(', ')}). Run kitto setup --agents ${options.host} first.`);
113
+ }
114
+ if (options.version && selected.length > 1) {
115
+ throw new Error(`--version pins one host. Add --host <${selected.join('|')}> or omit --version to use each baseline.`);
116
+ }
117
+ return selected;
118
+ }
119
+
120
+ function buildRows(state, options) {
121
+ const selected = selectHosts(state, options);
122
+ const pin = options.version;
123
+ const rows = selected.map(name => {
124
+ const baseline = hosts[name].version;
125
+ if (appManaged(state, name)) {
126
+ if (pin) throw new Error('The DSH desktop profile is app-managed; Kitto never installs or pins its CLI. Upgrade it in DeepSeek Harness Desktop.');
127
+ return { name, appManaged: true, package: hosts[name].package, baseline };
128
+ }
129
+ const target = pin || baseline;
130
+ const command = ['npm', 'install', '--global', `${hosts[name].package}@${target}`];
131
+ const row = { name, package: hosts[name].package, baseline, target, command, ...probeHost(name) };
132
+ if (row.status !== 'found') row.action = row.status === 'missing' ? 'install' : 'unreadable';
133
+ else if (row.current === target) row.action = 'none';
134
+ else {
135
+ const order = exactVersion.test(row.current) ? compareVersions(row.current, target) : 1;
136
+ row.action = order < 0 ? 'upgrade' : pin ? 'pin' : 'newer';
137
+ }
138
+ return row;
139
+ });
140
+ return rows;
141
+ }
142
+
143
+ function currentLabel(row) {
144
+ if (row.status === 'found') return row.current;
145
+ if (row.status === 'missing') return 'not found';
146
+ return `unreadable (${row.detail})`;
147
+ }
148
+
149
+ function actionLabel(row) {
150
+ switch (row.action) {
151
+ case 'none': return 'already at the target version';
152
+ case 'upgrade': return 'upgrade needed';
153
+ case 'install': return 'not installed; --apply installs the pinned baseline';
154
+ case 'pin': return 'explicit pin differs from the installed version';
155
+ case 'newer': return 'newer than the baseline; Kitto does not downgrade (use --version to pin explicitly)';
156
+ default: return 'cannot read its version; --apply stops before changing anything';
157
+ }
158
+ }
159
+
160
+ const actionable = row => !row.appManaged && ['upgrade', 'install', 'pin'].includes(row.action);
161
+
162
+ function pinWarning(row) {
163
+ if (row.appManaged || row.target === row.baseline) return null;
164
+ return ` WARNING: ${row.target} is an explicit --version pin, not the Kitto-validated baseline ${row.baseline}; only the baseline is validated.`;
165
+ }
166
+
167
+ function printRow(row) {
168
+ if (row.appManaged) {
169
+ console.log(` ${row.name}: app-managed by DeepSeek Harness Desktop; Kitto baseline ${row.baseline}; Kitto never upgrades its CLI`);
170
+ console.log(' upgrade through DeepSeek Harness Desktop');
171
+ return;
172
+ }
173
+ const target = row.target === row.baseline ? row.target : `${row.target} (explicit pin; Kitto baseline ${row.baseline})`;
174
+ console.log(` ${row.name}: current ${currentLabel(row)}; Kitto baseline ${row.baseline}; target ${target}; ${actionLabel(row)}`);
175
+ console.log(` native manager: ${row.command.join(' ')}`);
176
+ const warning = pinWarning(row);
177
+ if (warning) console.log(warning);
178
+ }
179
+
180
+ function printCheck(state, rows) {
181
+ console.log(`Kitto ${state.version} host CLIs (check only; no writes).`);
182
+ console.log(policy);
183
+ for (const row of rows) printRow(row);
184
+ if (rows.some(actionable)) {
185
+ console.log('Preview only: run `kitto hosts --apply` to install the targets above. No writes.');
186
+ } else if (rows.some(row => !row.appManaged)) {
187
+ console.log('Nothing for Kitto to change: selected host CLIs are at or above the pinned targets. No writes.');
188
+ } else {
189
+ console.log('Nothing for Kitto to manage for the selected hosts. No writes.');
190
+ }
191
+ }
192
+
193
+ function npmAvailable() {
194
+ return spawnSync('npm', ['--version'], { stdio: 'ignore', timeout: 8000 }).status === 0;
195
+ }
196
+
197
+ const permissionHint = 'npm could not write to its global prefix. Retry with a writable npm prefix '
198
+ + '(for example `npm config set prefix ~/.npm-global`) or use an administrator/sudo shell.';
199
+
200
+ function runCommand(command) {
201
+ const [name, ...args] = command;
202
+ // Keep npm's progress visible but capture stderr so a permission failure can
203
+ // explain the global prefix instead of only surfacing an exit code.
204
+ const result = spawnSync(name, args, { stdio: ['inherit', 'inherit', 'pipe'], encoding: 'utf8', timeout: 600_000 });
205
+ const stderr = (result.stderr ?? '').trim();
206
+ if (result.error) throw new Error(`${name} ${args.join(' ')} failed: ${result.error.message}`);
207
+ if (result.status !== 0) {
208
+ const detail = stderr.split('\n').filter(Boolean).slice(0, 3).join(' ');
209
+ const permission = /EACCES|EPERM|permission denied|access is denied/i.test(stderr);
210
+ throw new Error(`${name} ${args.join(' ')} failed with exit ${result.status}${detail ? `: ${detail}` : ''}.`
211
+ + (permission ? ` ${permissionHint}` : ''));
212
+ }
213
+ }
214
+
215
+ function applyRows(state, rows) {
216
+ console.log(`Kitto ${state.version} host CLIs (apply: pinned versions only).`);
217
+ console.log(policy);
218
+ const managed = rows.filter(row => !row.appManaged);
219
+ for (const row of rows.filter(row => row.appManaged)) {
220
+ console.log(` ${row.name}: app-managed by DeepSeek Harness Desktop; skipped (upgrade through the App).`);
221
+ }
222
+ const broken = managed.filter(row => row.action === 'unreadable');
223
+ if (broken.length) {
224
+ throw new Error(`Cannot read the current version of ${broken.map(row => `${row.name} (${row.detail})`).join(', ')}. `
225
+ + 'Fix the CLI or reinstall it with its native manager first; nothing was changed.');
226
+ }
227
+ const changes = managed.filter(row => ['upgrade', 'install', 'pin'].includes(row.action));
228
+ const unchanged = managed.filter(row => !changes.includes(row));
229
+ for (const row of unchanged) {
230
+ console.log(` ${row.name}: current ${currentLabel(row)}; ${actionLabel(row)}; no change.`);
231
+ // check and apply must both warn when --version is not the tested baseline,
232
+ // including the no-change path where apply returns before installing.
233
+ const warning = pinWarning(row);
234
+ if (warning) console.log(warning);
235
+ }
236
+ if (!changes.length) {
237
+ console.log(`Summary: updated none; unchanged ${unchanged.map(row => row.name).join(', ') || 'none'}. `
238
+ + 'Nothing to change: the selected host CLIs already satisfy the pinned targets. No writes.');
239
+ return;
240
+ }
241
+ if (!npmAvailable()) {
242
+ throw new Error('npm was not found on PATH. Host CLIs are upgraded only through the native npm global manager; '
243
+ + 'install Node.js/npm or use the host\'s native manager. Nothing was changed.');
244
+ }
245
+ const overridden = changes.filter(row => row.target !== row.baseline);
246
+ if (overridden.length) {
247
+ console.log(`Explicit pin overrides the Kitto-validated baseline for ${overridden.map(row => `${row.name} (${row.baseline} -> ${row.target})`).join(', ')}; only the baseline is validated.`);
248
+ }
249
+ console.log('Installing pinned versions with the native npm global manager (no npx, no dist-tags):');
250
+ const changed = [];
251
+ const notChanged = [];
252
+ let failure;
253
+ for (let index = 0; index < changes.length; index++) {
254
+ const row = changes[index];
255
+ console.log(` ${row.name}: current ${currentLabel(row)} -> ${row.target}`);
256
+ console.log(` ${row.command.join(' ')}`);
257
+ try {
258
+ runCommand(row.command);
259
+ const verified = probeHost(row.name);
260
+ if (verified.status !== 'found' || verified.current !== row.target) {
261
+ throw new Error(`npm finished, but the CLI reports ${verified.status === 'found'
262
+ ? verified.current : verified.status === 'missing' ? 'not found' : `unreadable (${verified.detail})`} `
263
+ + `instead of ${row.target}. Check PATH and the npm global prefix; Kitto wrote no state.`);
264
+ }
265
+ changed.push(row.name);
266
+ console.log(` verified ${row.name} ${verified.current}`);
267
+ } catch (error) {
268
+ failure = { row, error };
269
+ notChanged.push(row.name, ...changes.slice(index + 1).map(other => other.name));
270
+ break;
271
+ }
272
+ }
273
+ if (failure) {
274
+ console.log(`Summary: updated ${changed.join(', ') || 'none'}; not updated ${notChanged.join(', ')}. Kitto wrote no state.`);
275
+ throw new Error(`${failure.row.name}: ${failure.error.message}`);
276
+ }
277
+ console.log(`Summary: updated ${changed.join(', ')}; unchanged ${unchanged.map(row => row.name).join(', ') || 'none'}. `
278
+ + 'Restart each updated host to load the new CLI.');
279
+ }
280
+
281
+ /** `kitto hosts [--check|--apply] [--host NAME] [--version VERSION]`. */
282
+ export async function hostsCommand(args = []) {
283
+ const options = parseHostsArgs(args);
284
+ const { state } = await readState();
285
+ const rows = buildRows(state, options);
286
+ if (options.apply) return applyRows(state, rows);
287
+ return printCheck(state, rows);
288
+ }