ai-profile-switch 0.0.0-stage → 2.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,235 @@
1
+ import { spawn, execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, mkdtempSync, cpSync, renameSync, rmSync, lstatSync, readdirSync, realpathSync, statSync } from 'node:fs';
4
+ import { dirname, join, delimiter, resolve } from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { PROFILES_DIR, SELF_PKG } from './constants.mjs';
8
+ import { computeUpdatePlan, compareSemver, parseSemver } from './updater.mjs';
9
+
10
+ const execute = promisify(execFile);
11
+ const stateFile = join(PROFILES_DIR, '_update-state.json');
12
+ const pointerFile = join(PROFILES_DIR, '_runtime-current.json');
13
+ const versionsDir = join(PROFILES_DIR, '_runtime-updates');
14
+ const lockDir = join(PROFILES_DIR, '_update-lock');
15
+ const interval = 24 * 60 * 60 * 1000;
16
+
17
+ function readState() {
18
+ if (!existsSync(stateFile)) return {};
19
+ if (lstatSync(stateFile).isSymbolicLink()) throw new Error('Update state must not be a symlink');
20
+ try {
21
+ const state = JSON.parse(readFileSync(stateFile, 'utf8'));
22
+ return state && typeof state === 'object' ? state : {};
23
+ } catch (error) {
24
+ if (error instanceof SyntaxError) return {};
25
+ throw error;
26
+ }
27
+ }
28
+
29
+ function atomicJson(file, value) {
30
+ if (existsSync(file) && lstatSync(file).isSymbolicLink()) throw new Error('Update file must not be a symlink');
31
+ const temporary = file + '.' + randomUUID();
32
+ try {
33
+ writeFileSync(temporary, JSON.stringify(value) + '\n', { flag: 'wx', mode: 0o600 });
34
+ renameSync(temporary, file);
35
+ } finally {
36
+ rmSync(temporary, { force: true });
37
+ }
38
+ }
39
+
40
+ export function installedRuntimeDirectory() {
41
+ const base = join(PROFILES_DIR, '_runtime');
42
+ if (!existsSync(base)) return null;
43
+ if (lstatSync(base).isSymbolicLink()) throw new Error('Runtime must not be a symlink');
44
+ if (!existsSync(pointerFile)) return base;
45
+ if (lstatSync(pointerFile).isSymbolicLink()) throw new Error('Runtime pointer must not be a symlink');
46
+ const { directory } = JSON.parse(readFileSync(pointerFile, 'utf8'));
47
+ if (typeof directory !== 'string' || !/^v[\w.-]+$/.test(directory)) throw new Error('Invalid runtime pointer');
48
+ const runtime = join(versionsDir, directory);
49
+ if (lstatSync(versionsDir).isSymbolicLink() || lstatSync(runtime).isSymbolicLink()) throw new Error('Runtime must not be a symlink');
50
+ return runtime;
51
+ }
52
+
53
+ export function shouldCheckSelfUpdate(state, now = Date.now()) {
54
+ const last = Date.parse(state.lastCheck ?? '');
55
+ const retry = state.failed ? 60 * 60 * 1000 : interval;
56
+ return !Number.isFinite(last) || now < last || now - last >= retry;
57
+ }
58
+
59
+ function acquireLock() {
60
+ try {
61
+ mkdirSync(lockDir);
62
+ } catch (error) {
63
+ if (error.code !== 'EEXIST') throw error;
64
+ if (lstatSync(lockDir).isSymbolicLink()) throw new Error('Update lock must not be a symlink');
65
+ const entries = readdirSync(lockDir);
66
+ const ownerFile = join(lockDir, 'owner.json');
67
+ let owner;
68
+ let modified = statSync(lockDir).mtimeMs;
69
+ if (entries.includes('owner.json')) {
70
+ const entry = lstatSync(ownerFile);
71
+ if (!entry.isFile()) return null;
72
+ modified = Math.max(modified, entry.mtimeMs);
73
+ try { owner = JSON.parse(readFileSync(ownerFile, 'utf8')); } catch {}
74
+ }
75
+ if (owner && Number.isInteger(owner.pid) && owner.pid > 0) {
76
+ try { process.kill(owner.pid, 0); return null; } catch (probe) {
77
+ if (probe.code !== 'ESRCH') return null;
78
+ }
79
+ } else if (entries.some(name => name !== 'owner.json') || Date.now() - modified < 300000) {
80
+ // Allow an interrupted owner write to settle before reclaiming its lock.
81
+ return null;
82
+ }
83
+ const stale = lockDir + '-stale-' + randomUUID();
84
+ try { renameSync(lockDir, stale); } catch { return null; }
85
+ rmSync(stale, { recursive: true, force: true });
86
+ return acquireLock();
87
+ }
88
+ writeFileSync(join(lockDir, 'owner.json'), JSON.stringify({ pid: process.pid }), { flag: 'wx', mode: 0o600 });
89
+ return () => rmSync(lockDir, { recursive: true, force: true });
90
+ }
91
+
92
+ function npmCli(env) {
93
+ const candidates = [
94
+ join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),
95
+ join(dirname(process.execPath), '../lib/node_modules/npm/bin/npm-cli.js'),
96
+ ];
97
+ for (const directory of (env.PATH || '').split(delimiter).filter(Boolean)) {
98
+ candidates.push(join(directory, 'node_modules/npm/bin/npm-cli.js'));
99
+ for (const name of ['npm', 'npm.cmd']) {
100
+ try {
101
+ const file = realpathSync(join(directory, name));
102
+ if (file.endsWith('npm-cli.js')) candidates.push(file);
103
+ } catch {}
104
+ }
105
+ }
106
+ return candidates.find(file => existsSync(file) && lstatSync(file).isFile()) ?? null;
107
+ }
108
+
109
+ function assertRegularTree(directory) {
110
+ for (const name of readdirSync(directory)) {
111
+ const file = join(directory, name);
112
+ const stat = lstatSync(file);
113
+ if (stat.isDirectory()) assertRegularTree(file);
114
+ else if (!stat.isFile()) throw new Error(`Unsupported package entry: ${name}`);
115
+ }
116
+ }
117
+
118
+ async function downloadPackage(version, workspace, env) {
119
+ const npm = npmCli(env);
120
+ if (!npm) throw new Error('npm executable unavailable');
121
+ const home = join(workspace, 'home');
122
+ mkdirSync(home);
123
+ const config = join(workspace, 'npmrc');
124
+ writeFileSync(config, '');
125
+ const globalConfig = join(workspace, 'npmrc-global');
126
+ writeFileSync(globalConfig, '');
127
+ const isolatedEnv = {};
128
+ for (const key of ['PATH', 'SystemRoot', 'SYSTEMROOT', 'WINDIR', 'ComSpec', 'COMSPEC', 'PATHEXT', 'TMPDIR', 'TMP', 'TEMP', 'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'https_proxy', 'http_proxy', 'no_proxy', 'NODE_EXTRA_CA_CERTS']) {
129
+ if (env[key]) isolatedEnv[key] = env[key];
130
+ }
131
+ Object.assign(isolatedEnv, {
132
+ HOME: home, USERPROFILE: home, APPDATA: home, LOCALAPPDATA: home,
133
+ npm_config_userconfig: config, npm_config_globalconfig: globalConfig,
134
+ npm_config_cache: join(workspace, 'cache'), npm_config_engine_strict: 'true',
135
+ });
136
+ await execute(process.execPath, [npm, 'install', `${SELF_PKG}@${version}`,
137
+ '--prefix', workspace, '--ignore-scripts', '--no-audit', '--no-fund', '--no-save', '--package-lock=false', '--omit=dev',
138
+ '--fetch-retries=0', '--fetch-timeout=30000', '--registry', env.CAS_TEST_REGISTRY_URL || 'https://registry.npmjs.org'], {
139
+ cwd: workspace, env: isolatedEnv, timeout: 120000, maxBuffer: 1024 * 1024, windowsHide: true,
140
+ });
141
+ return join(workspace, 'node_modules', SELF_PKG);
142
+ }
143
+
144
+ async function activatePackage(source, version) {
145
+ assertRegularTree(source);
146
+ const pkg = JSON.parse(readFileSync(join(source, 'package.json'), 'utf8'));
147
+ if (pkg.name !== SELF_PKG || pkg.version !== version || pkg.claudeAccountSwitch?.runtimeProtocol !== 1) {
148
+ throw new Error('Incompatible runtime package');
149
+ }
150
+ if (Object.keys(pkg.dependencies || {}).length || Object.keys(pkg.optionalDependencies || {}).length) {
151
+ throw new Error('Runtime package must be self-contained');
152
+ }
153
+ for (const file of ['bin/cli.mjs', 'src/index.mjs', 'src/commands/shell.mjs', 'src/lib/self-update.mjs']) {
154
+ if (!existsSync(join(source, file))) throw new Error(`Missing runtime file: ${file}`);
155
+ }
156
+ const validationHome = join(dirname(source), 'validation-home');
157
+ mkdirSync(validationHome);
158
+ const validation = await execute(process.execPath, [join(source, 'bin/cli.mjs'), '--version'], {
159
+ cwd: validationHome, env: { HOME: validationHome, USERPROFILE: validationHome, CLAUDE_SWITCH_DISABLE_AUTO_UPDATE: '1', NO_COLOR: '1' },
160
+ timeout: 10000, windowsHide: true,
161
+ });
162
+ if (validation.stdout.trim() !== version) throw new Error('Runtime version verification failed');
163
+ await execute(process.execPath, ['--input-type=module', '-e', `await import(${JSON.stringify(pathToFileURL(join(source, 'src/commands/shell.mjs')).href)})`], {
164
+ cwd: validationHome, env: { HOME: validationHome, USERPROFILE: validationHome, CLAUDE_SWITCH_DISABLE_AUTO_UPDATE: '1', NO_COLOR: '1' },
165
+ timeout: 10000, windowsHide: true,
166
+ });
167
+ if (existsSync(versionsDir) && lstatSync(versionsDir).isSymbolicLink()) throw new Error('Runtime updates must not be a symlink');
168
+ mkdirSync(versionsDir, { recursive: true });
169
+ const directory = `v${version.replace(/\+/g, '-')}-${randomUUID()}`;
170
+ const destination = join(versionsDir, directory);
171
+ mkdirSync(destination);
172
+ let activated = false;
173
+ try {
174
+ for (const file of ['package.json', 'bin', 'src']) cpSync(join(source, file), join(destination, file), { recursive: true });
175
+ atomicJson(pointerFile, { directory, version });
176
+ activated = true;
177
+ } finally {
178
+ if (!activated) rmSync(destination, { recursive: true, force: true });
179
+ }
180
+ }
181
+
182
+ export async function runSelfUpdate({ force = false, env = process.env, now = Date.now(), computePlan = computeUpdatePlan, download = downloadPackage } = {}) {
183
+ const runtime = installedRuntimeDirectory();
184
+ if (!runtime) return { action: 'skipped', reason: 'not-installed' };
185
+ const release = acquireLock();
186
+ if (!release) return { action: 'skipped', reason: 'busy' };
187
+ let workspace;
188
+ try {
189
+ const state = readState();
190
+ if (!force && !shouldCheckSelfUpdate(state, now)) return { action: 'skipped', reason: 'recent' };
191
+ const installed = JSON.parse(readFileSync(join(installedRuntimeDirectory(), 'package.json'), 'utf8')).version;
192
+ const { self } = await computePlan();
193
+ parseSemver(self.latest);
194
+ if (compareSemver(installed, self.latest) >= 0) {
195
+ atomicJson(stateFile, { lastCheck: new Date(now).toISOString(), failed: false });
196
+ return { action: 'skipped', reason: 'up-to-date' };
197
+ }
198
+ workspace = mkdtempSync(join(PROFILES_DIR, '_update-stage-'));
199
+ const source = await download(self.latest, workspace, env);
200
+ atomicJson(stateFile, { lastCheck: new Date(now).toISOString(), failed: false, version: self.latest });
201
+ await activatePackage(source, self.latest);
202
+ return { action: 'updated', version: self.latest };
203
+ } catch (error) {
204
+ try { atomicJson(stateFile, { lastCheck: new Date(now).toISOString(), failed: true }); } catch {}
205
+ const npmError = error.stderr?.match(/npm (?:ERR!|error) code (\S+)/i)?.[1];
206
+ let message = error.message;
207
+ if (npmError) message = `npm ${npmError}`;
208
+ else if (error.killed) message = 'Update timed out';
209
+ return { action: 'failed', error: message };
210
+ } finally {
211
+ try { if (workspace) rmSync(workspace, { recursive: true, force: true }); } finally { release(); }
212
+ }
213
+ }
214
+
215
+ export function scheduleSelfUpdate({ env = process.env, stdin = process.stdin, stdout = process.stderr, spawnWorker = spawn } = {}) {
216
+ if (env.CLAUDE_SWITCH_DISABLE_AUTO_UPDATE === '1') return { action: 'skipped', reason: 'disabled' };
217
+ if (!stdin.isTTY || !stdout.isTTY) return { action: 'skipped', reason: 'non-tty' };
218
+ try {
219
+ if (!installedRuntimeDirectory()) return { action: 'skipped', reason: 'not-installed' };
220
+ if (!shouldCheckSelfUpdate(readState())) return { action: 'skipped', reason: 'recent' };
221
+ const child = spawnWorker(process.execPath, [fileURLToPath(import.meta.url), '--worker'], {
222
+ cwd: PROFILES_DIR, env, detached: true, stdio: 'ignore', windowsHide: true,
223
+ });
224
+ child.on('error', () => {});
225
+ child.unref();
226
+ return { action: 'scheduled' };
227
+ } catch {
228
+ return { action: 'skipped', reason: 'unavailable' };
229
+ }
230
+ }
231
+
232
+ if (process.argv[2] === '--worker' && process.argv[1]
233
+ && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
234
+ runSelfUpdate().catch(() => {});
235
+ }
@@ -0,0 +1,156 @@
1
+ // Opt-in sharing of profile entries (CLAUDE.md, skills, agents, …) through ~/.claude-profiles/_shared.
2
+ // Each profile gets a link to the shared copy; a profile file that differs is never replaced.
3
+ import { mkdirSync, readdirSync, readlinkSync, rmSync, writeFileSync, lstatSync } from 'node:fs';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import {
6
+ SHARED_DIR, SHAREABLE_ENTRIES, SHAREABLE_FILES, ACCOUNT_SKILL_ENTRIES,
7
+ } from './constants.mjs';
8
+ import { readMeta, getActiveProfile, getSharedEntries, setSharedEntries } from './config.mjs';
9
+ import {
10
+ pathExists, createLink, copyEntry, identicalEntries, emptyEntry, linkTarget, canonicalPath,
11
+ profileDir, listProfiles,
12
+ } from './profile.mjs';
13
+
14
+ function pointsTo(link, target) {
15
+ return lstatSync(link).isSymbolicLink() && canonicalPath(linkTarget(link)) === canonicalPath(target);
16
+ }
17
+
18
+ // 'ok' already linked, 'linked' newly linked (or would be, in a dry run), 'conflict' own content kept.
19
+ function placeLink(link, relativeTarget, sharedPath, isDir, dryRun) {
20
+ if (!pathExists(link)) {
21
+ if (!dryRun) createLink(relativeTarget, link, isDir);
22
+ return 'linked';
23
+ }
24
+ if (pointsTo(link, sharedPath)) return 'ok';
25
+ if (!identicalEntries(link, sharedPath) && !emptyEntry(link)) return 'conflict';
26
+ if (!dryRun) {
27
+ rmSync(link, { recursive: true, force: true });
28
+ createLink(relativeTarget, link, isDir);
29
+ }
30
+ return 'linked';
31
+ }
32
+
33
+ function sharedSkillNames() {
34
+ const dir = join(SHARED_DIR, 'skills');
35
+ if (!pathExists(dir)) return [];
36
+ return readdirSync(dir).filter(name => !name.startsWith('.') && !ACCOUNT_SKILL_ENTRIES.includes(name)).sort();
37
+ }
38
+
39
+ function linksIntoSharedSkills(path) {
40
+ return lstatSync(path).isSymbolicLink()
41
+ && canonicalPath(dirname(resolve(dirname(path), readlinkSync(path)))) === canonicalPath(join(SHARED_DIR, 'skills'));
42
+ }
43
+
44
+ function syncSkills(name, result, dryRun) {
45
+ const skills = join(profileDir(name), 'skills');
46
+ if (pathExists(skills) && (lstatSync(skills).isSymbolicLink() || !lstatSync(skills).isDirectory())) {
47
+ result.conflicts.push('skills');
48
+ return;
49
+ }
50
+ if (!dryRun) mkdirSync(skills, { recursive: true });
51
+ const names = sharedSkillNames();
52
+ for (const skill of names) {
53
+ const state = placeLink(join(skills, skill), join('..', '..', '_shared', 'skills', skill),
54
+ join(SHARED_DIR, 'skills', skill), true, dryRun);
55
+ if (state === 'linked') result.linked.push(`skills/${skill}`);
56
+ else if (state === 'conflict') result.conflicts.push(`skills/${skill}`);
57
+ }
58
+ if (!pathExists(skills)) return;
59
+ // A skill removed from _shared leaves a dangling link behind.
60
+ for (const skill of readdirSync(skills)) {
61
+ const path = join(skills, skill);
62
+ if (names.includes(skill) || !linksIntoSharedSkills(path)) continue;
63
+ if (!dryRun) rmSync(path, { force: true });
64
+ result.unlinked.push(`skills/${skill}`);
65
+ }
66
+ }
67
+
68
+ export function syncProfile(name, entries = getSharedEntries(), { dryRun = false } = {}) {
69
+ const result = { name, linked: [], unlinked: [], conflicts: [], missing: [] };
70
+ for (const entry of entries) {
71
+ const sharedPath = join(SHARED_DIR, entry);
72
+ if (!pathExists(sharedPath)) {
73
+ result.missing.push(entry);
74
+ continue;
75
+ }
76
+ if (entry === 'skills') {
77
+ syncSkills(name, result, dryRun);
78
+ continue;
79
+ }
80
+ const state = placeLink(join(profileDir(name), entry), join('..', '_shared', entry),
81
+ sharedPath, !SHAREABLE_FILES.includes(entry), dryRun);
82
+ if (state === 'linked') result.linked.push(entry);
83
+ else if (state === 'conflict') result.conflicts.push(entry);
84
+ }
85
+ return result;
86
+ }
87
+
88
+ export function syncShared(names = listProfiles(), options) {
89
+ const meta = readMeta();
90
+ if (!meta.shareSettings || !meta.shared?.length) return [];
91
+ return names.map(name => syncProfile(name, meta.shared, options));
92
+ }
93
+
94
+ function validateEntry(entry) {
95
+ if (!SHAREABLE_ENTRIES.includes(entry)) {
96
+ throw new Error(`"${entry}" cannot be shared. Choose one of: ${SHAREABLE_ENTRIES.join(', ')}`);
97
+ }
98
+ }
99
+
100
+ function seedShared(entry, from) {
101
+ const sharedPath = join(SHARED_DIR, entry);
102
+ const source = from ? join(profileDir(from), entry) : null;
103
+ const hasSource = source && pathExists(source) && !emptyEntry(source);
104
+ if (entry === 'skills') {
105
+ mkdirSync(sharedPath, { recursive: true });
106
+ if (!hasSource) return;
107
+ for (const skill of readdirSync(source)) {
108
+ if (skill.startsWith('.') || ACCOUNT_SKILL_ENTRIES.includes(skill)) continue;
109
+ copyEntry(join(source, skill), join(sharedPath, skill));
110
+ }
111
+ } else if (hasSource) {
112
+ copyEntry(source, sharedPath);
113
+ } else if (SHAREABLE_FILES.includes(entry)) {
114
+ writeFileSync(sharedPath, '');
115
+ } else {
116
+ mkdirSync(sharedPath, { recursive: true });
117
+ }
118
+ }
119
+
120
+ export function shareEntry(entry, from = getActiveProfile()) {
121
+ validateEntry(entry);
122
+ const meta = readMeta();
123
+ if (!meta.shareSettings) throw new Error('Sharing needs shared settings. This setup keeps each profile separate.');
124
+ const entries = meta.shared ?? [];
125
+ if (entries.includes(entry)) throw new Error(`"${entry}" is already shared`);
126
+ mkdirSync(SHARED_DIR, { recursive: true });
127
+ if (!pathExists(join(SHARED_DIR, entry))) seedShared(entry, from);
128
+ setSharedEntries([...entries, entry]);
129
+ return syncShared();
130
+ }
131
+
132
+ // Each profile keeps a copy of the shared content, so nothing disappears.
133
+ export function unshareEntry(entry) {
134
+ validateEntry(entry);
135
+ const entries = getSharedEntries();
136
+ if (!entries.includes(entry)) throw new Error(`"${entry}" is not shared`);
137
+ const sharedPath = join(SHARED_DIR, entry);
138
+ for (const name of listProfiles()) {
139
+ if (entry === 'skills') {
140
+ const skills = join(profileDir(name), 'skills');
141
+ if (!pathExists(skills) || lstatSync(skills).isSymbolicLink()) continue;
142
+ for (const skill of readdirSync(skills)) {
143
+ const path = join(skills, skill);
144
+ if (!linksIntoSharedSkills(path)) continue;
145
+ rmSync(path, { force: true });
146
+ if (pathExists(join(sharedPath, skill))) copyEntry(join(sharedPath, skill), path);
147
+ }
148
+ continue;
149
+ }
150
+ const link = join(profileDir(name), entry);
151
+ if (!pathExists(link) || !pointsTo(link, sharedPath)) continue;
152
+ rmSync(link, { force: true });
153
+ if (pathExists(sharedPath)) copyEntry(sharedPath, link);
154
+ }
155
+ setSharedEntries(entries.filter(item => item !== entry));
156
+ }
@@ -0,0 +1,228 @@
1
+ import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync, mkdtempSync, cpSync, copyFileSync, renameSync, rmSync, lstatSync, unlinkSync } from 'node:fs';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { join, dirname, resolve, isAbsolute } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { HOME, PROFILES_DIR, IS_WINDOWS } from './constants.mjs';
6
+
7
+ // Unix file permissions are silently ignored on Windows
8
+ const EXEC_MODE = IS_WINDOWS ? undefined : { mode: 0o755 };
9
+
10
+ const SH_FILE = join(PROFILES_DIR, '.shell-integration.sh');
11
+ const PS1_FILE = join(PROFILES_DIR, '.shell-integration.ps1');
12
+ const FISH_FILE = join(PROFILES_DIR, '.shell-integration.fish');
13
+
14
+ const HERE = dirname(fileURLToPath(import.meta.url));
15
+ const TEMPLATES_DIR = join(HERE, '..', 'shell-templates');
16
+ const PACKAGE_DIR = join(HERE, '..', '..');
17
+ const RUNTIME_DIR = join(PROFILES_DIR, '_runtime');
18
+
19
+ export function installShellIntegration(shell) {
20
+ if (!['bash', 'zsh', 'fish', 'powershell'].includes(shell)) throw new Error(`Unknown shell: ${shell}`);
21
+ installRuntime();
22
+ mkdirSync(PROFILES_DIR, { recursive: true });
23
+ if (shell === 'powershell') {
24
+ writeTemplate('integration.ps1', PS1_FILE);
25
+ installPowerShellProfile();
26
+ } else if (shell === 'fish') {
27
+ writeTemplate('integration.fish', FISH_FILE);
28
+ installFishConfig();
29
+ } else {
30
+ writeTemplate('integration.sh', SH_FILE);
31
+ installUnixRc(shell);
32
+ }
33
+ }
34
+
35
+ export function installAllShells() {
36
+ if (!existsSync(PROFILES_DIR)) return { newlyInstalled: [], alreadyInstalled: [] };
37
+
38
+ installRuntime();
39
+ const newlyInstalled = [];
40
+ const alreadyInstalled = [];
41
+ const track = (name, isNew) => (isNew ? newlyInstalled : alreadyInstalled).push(name);
42
+
43
+ // Generate all scripts upfront (idempotent — keeps them up-to-date)
44
+ writeTemplate('integration.sh', SH_FILE);
45
+ writeTemplate('integration.ps1', PS1_FILE);
46
+ writeTemplate('integration.fish', FISH_FILE);
47
+
48
+ const currentShell = (process.env.SHELL || '').split('/').pop();
49
+ const nativePowerShell = join(process.env.XDG_CONFIG_HOME || join(HOME, '.config'), 'powershell');
50
+ const legacyPowerShell = ['WindowsPowerShell', 'PowerShell'].some(edition =>
51
+ existsSync(join(HOME, 'Documents', edition, 'Microsoft.PowerShell_profile.ps1')));
52
+ if (IS_WINDOWS || currentShell === 'pwsh' || existsSync(nativePowerShell) || legacyPowerShell) {
53
+ track('PowerShell', installPowerShellProfile());
54
+ }
55
+
56
+ if (existsSync(join(HOME, '.bashrc')) || currentShell === 'bash') {
57
+ track('bash', installUnixRc('bash'));
58
+ }
59
+ if (existsSync(join(process.env.ZDOTDIR || HOME, '.zshrc')) || currentShell === 'zsh' || process.platform === 'darwin') {
60
+ track('zsh', installUnixRc('zsh'));
61
+ }
62
+ if (existsSync(join(process.env.XDG_CONFIG_HOME || join(HOME, '.config'), 'fish')) || currentShell === 'fish') {
63
+ track('fish', installFishConfig());
64
+ }
65
+
66
+ return { newlyInstalled, alreadyInstalled };
67
+ }
68
+
69
+
70
+ function installRuntime() {
71
+ mkdirSync(PROFILES_DIR, { recursive: true });
72
+ if (existsSync(RUNTIME_DIR) && lstatSync(RUNTIME_DIR).isSymbolicLink()) {
73
+ throw new Error(`Runtime must be a directory: ${RUNTIME_DIR}`);
74
+ }
75
+ const stage = mkdtempSync(join(PROFILES_DIR, '_runtime-stage-'));
76
+ const backup = stage + '-previous';
77
+ let moved = false;
78
+ try {
79
+ copyFileSync(join(PACKAGE_DIR, 'package.json'), join(stage, 'package.json'));
80
+ cpSync(join(PACKAGE_DIR, 'bin'), join(stage, 'bin'), { recursive: true });
81
+ cpSync(join(PACKAGE_DIR, 'src'), join(stage, 'src'), { recursive: true });
82
+ JSON.parse(readFileSync(join(stage, 'package.json'), 'utf8'));
83
+ for (const relative of ['bin/cli.mjs', 'src/index.mjs', 'src/commands/shell.mjs']) {
84
+ if (!existsSync(join(stage, relative))) throw new Error(`Missing runtime file: ${relative}`);
85
+ }
86
+ if (existsSync(RUNTIME_DIR)) {
87
+ renameSync(RUNTIME_DIR, backup);
88
+ moved = true;
89
+ }
90
+ try {
91
+ renameSync(stage, RUNTIME_DIR);
92
+ } catch (err) {
93
+ if (moved) renameSync(backup, RUNTIME_DIR);
94
+ throw err;
95
+ }
96
+ const pointer = join(PROFILES_DIR, '_runtime-current.json');
97
+ if (existsSync(pointer)) unlinkSync(pointer);
98
+ if (moved) rmSync(backup, { recursive: true, force: true });
99
+ } finally {
100
+ rmSync(stage, { recursive: true, force: true });
101
+ }
102
+ }
103
+
104
+ function writeTemplate(templateName, targetFile) {
105
+ const content = readFileSync(join(TEMPLATES_DIR, templateName), 'utf8').replace(/\r\n/g, '\n');
106
+ writeFileSync(targetFile, content, EXEC_MODE);
107
+ }
108
+
109
+
110
+ function installUnixRc(shell) {
111
+ const rcFile = shell === 'zsh' ? join(process.env.ZDOTDIR || HOME, '.zshrc') : join(HOME, '.bashrc');
112
+ mkdirSync(dirname(rcFile), { recursive: true });
113
+ const sourceLine = '[ -f ~/.claude-profiles/.shell-integration.sh ] && . ~/.claude-profiles/.shell-integration.sh';
114
+ return addSourceLine(rcFile, sourceLine, '.shell-integration.sh');
115
+ }
116
+
117
+ function installFishConfig() {
118
+ const configDir = join(process.env.XDG_CONFIG_HOME || join(HOME, '.config'), 'fish');
119
+ const configFile = join(configDir, 'config.fish');
120
+ const sourceLine = 'test -f ~/.claude-profiles/.shell-integration.fish && source ~/.claude-profiles/.shell-integration.fish';
121
+ mkdirSync(configDir, { recursive: true });
122
+ return addSourceLine(configFile, sourceLine, '.shell-integration.fish');
123
+ }
124
+
125
+ function installPowerShellProfile() {
126
+ const documents = IS_WINDOWS ? windowsDocuments() : join(HOME, 'Documents');
127
+ const legacy = ['WindowsPowerShell', 'PowerShell'].map(edition =>
128
+ join(documents, edition, 'Microsoft.PowerShell_profile.ps1'));
129
+ const native = join(process.env.XDG_CONFIG_HOME || join(HOME, '.config'), 'powershell', 'Microsoft.PowerShell_profile.ps1');
130
+ const profiles = IS_WINDOWS ? legacy : [native, ...legacy.filter(existsSync)];
131
+ const sourceLine = IS_WINDOWS
132
+ ? `. "$env:USERPROFILE\\.claude-profiles\\.shell-integration.ps1"`
133
+ : `. "$HOME/.claude-profiles/.shell-integration.ps1"`;
134
+ let installed = false;
135
+ for (const profile of profiles) {
136
+ mkdirSync(dirname(profile), { recursive: true });
137
+ const changed = addSourceLine(profile, sourceLine, '.shell-integration.ps1');
138
+ installed = changed || installed;
139
+ }
140
+ return installed;
141
+ }
142
+
143
+ function windowsDocuments() {
144
+ const fallback = join(HOME, 'Documents');
145
+ const system = process.env.SystemRoot || process.env.SYSTEMROOT;
146
+ const powershell = system ? join(system, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') : 'powershell.exe';
147
+ const command = `[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding
148
+ @{
149
+ userProfile = [Environment]::GetFolderPath("UserProfile")
150
+ documents = [Environment]::GetFolderPath("MyDocuments", "DoNotVerify")
151
+ } | ConvertTo-Json -Compress`;
152
+ try {
153
+ const output = execFileSync(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command], {
154
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000,
155
+ });
156
+ const { userProfile, documents } = JSON.parse(output.trim().replace(/^\uFEFF/, ''));
157
+ // Known folders belong to the Windows SID, even when HOME is overridden for a fixture.
158
+ if (typeof userProfile === 'string' && isAbsolute(userProfile)
159
+ && resolve(userProfile).toLowerCase() === resolve(HOME).toLowerCase()
160
+ && typeof documents === 'string' && isAbsolute(documents)) return documents;
161
+ } catch {}
162
+ return fallback;
163
+ }
164
+
165
+ function hasActiveSource(text, marker) {
166
+ // Match source commands, not comments or mentions of a template filename.
167
+ if (marker.endsWith('.ps1')) text = text.replace(/<#[\s\S]*?#>/g, '');
168
+ const command = /(?:^\s*|[;&|]\s*|\bthen\s+)(?:source|\.)[ \t]+("[^"]*"|'[^']*'|[^\s;&|#]+)/g;
169
+ return text.replace(/^\uFEFF/, '').split(/\r?\n/).some(line => {
170
+ for (const match of line.matchAll(command)) {
171
+ let quote = null;
172
+ let escaped = false;
173
+ for (const char of line.slice(0, match.index)) {
174
+ if (escaped) { escaped = false; continue; }
175
+ if (char === (marker.endsWith('.ps1') ? '`' : '\\') && quote !== "'") { escaped = true; continue; }
176
+ if (quote) { if (char === quote) quote = null; }
177
+ else if (char === '"' || char === "'") quote = char;
178
+ else if (char === '#') return false;
179
+ }
180
+ const target = match[1].replace(/^["']|["']$/g, '');
181
+ if (!quote && (target === marker || target.endsWith('/' + marker) || target.endsWith('\\' + marker))) return true;
182
+ }
183
+ return false;
184
+ });
185
+ }
186
+
187
+ /** @returns {boolean} true if newly installed, false if already present */
188
+ function addSourceLine(rcFile, sourceLine, marker) {
189
+ const content = existsSync(rcFile) ? readFileSync(rcFile) : Buffer.alloc(0);
190
+ let width = 1;
191
+ let bigEndian = false;
192
+ if (content.subarray(0, 4).equals(Buffer.from([0xff, 0xfe, 0, 0]))) width = 4;
193
+ else if (content.subarray(0, 4).equals(Buffer.from([0, 0, 0xfe, 0xff]))) {
194
+ width = 4;
195
+ bigEndian = true;
196
+ } else if (content.subarray(0, 2).equals(Buffer.from([0xff, 0xfe]))) width = 2;
197
+ else if (content.subarray(0, 2).equals(Buffer.from([0xfe, 0xff]))) {
198
+ width = 2;
199
+ bigEndian = true;
200
+ }
201
+ if (content.length % width !== 0) throw new Error(`Incomplete UTF-${width * 8} encoding in shell profile: ${rcFile}`);
202
+ const encode = text => {
203
+ if (width === 1) return Buffer.from(text, 'utf8');
204
+ if (width === 2) {
205
+ const bytes = Buffer.from(text, 'utf16le');
206
+ return bigEndian ? bytes.swap16() : bytes;
207
+ }
208
+ const bytes = Buffer.alloc(text.length * 4);
209
+ for (let index = 0; index < text.length; index++) bytes.writeUInt32LE(text.charCodeAt(index), index * 4);
210
+ return bigEndian ? bytes.swap32() : bytes;
211
+ };
212
+ let text;
213
+ if (width === 1) text = content.toString('utf8');
214
+ else if (width === 2) text = (bigEndian ? Buffer.from(content).swap16() : content).toString('utf16le');
215
+ else {
216
+ text = '';
217
+ for (let index = 0; index < content.length; index += 4) {
218
+ const point = bigEndian ? content.readUInt32BE(index) : content.readUInt32LE(index);
219
+ text += String.fromCodePoint(point <= 0x10ffff ? point : 0xfffd);
220
+ }
221
+ }
222
+ if (hasActiveSource(text, marker)) return false;
223
+ const newline = content.includes(encode('\r\n')) ? '\r\n' : '\n';
224
+ const lf = encode('\n');
225
+ const separator = content.length > 0 && !content.subarray(-lf.length).equals(lf) ? newline : '';
226
+ appendFileSync(rcFile, encode(`${separator}${newline}# Claude Switch - multi-account manager${newline}${sourceLine}${newline}`));
227
+ return true;
228
+ }