@tulcn/lxz 0.0.0-stage → 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.
Files changed (93) hide show
  1. package/README.md +63 -2
  2. package/dist/application.d.ts +2 -0
  3. package/dist/application.js +17 -0
  4. package/dist/auth/client.d.ts +5 -0
  5. package/dist/auth/client.js +14 -0
  6. package/dist/auth/gateway.d.ts +1 -0
  7. package/dist/auth/gateway.js +10 -0
  8. package/dist/auth/host.d.ts +2 -0
  9. package/dist/auth/host.js +16 -0
  10. package/dist/auth/identity.d.ts +45 -0
  11. package/dist/auth/identity.js +106 -0
  12. package/dist/auth/index.d.ts +9 -0
  13. package/dist/auth/index.js +12 -0
  14. package/dist/auth/inspection.d.ts +14 -0
  15. package/dist/auth/inspection.js +20 -0
  16. package/dist/auth/modules.d.ts +12 -0
  17. package/dist/auth/modules.js +25 -0
  18. package/dist/auth/protocol.d.ts +17 -0
  19. package/dist/auth/protocol.js +1 -0
  20. package/dist/auth/provider.d.ts +36 -0
  21. package/dist/auth/provider.js +166 -0
  22. package/dist/auth/response.d.ts +2 -0
  23. package/dist/auth/response.js +17 -0
  24. package/dist/auth/service.d.ts +5 -0
  25. package/dist/auth/service.js +71 -0
  26. package/dist/auth/store.d.ts +25 -0
  27. package/dist/auth/store.js +170 -0
  28. package/dist/cli/browser.d.ts +1 -0
  29. package/dist/cli/browser.js +11 -0
  30. package/dist/cli/contracts.d.ts +85 -0
  31. package/dist/cli/contracts.js +51 -0
  32. package/dist/cli/deployment.d.ts +5 -0
  33. package/dist/cli/deployment.js +23 -0
  34. package/dist/cli/device-login.d.ts +29 -0
  35. package/dist/cli/device-login.js +87 -0
  36. package/dist/cli/environment.d.ts +9 -0
  37. package/dist/cli/environment.js +19 -0
  38. package/dist/cli/errors.d.ts +30 -0
  39. package/dist/cli/errors.js +22 -0
  40. package/dist/cli/files.d.ts +6 -0
  41. package/dist/cli/files.js +71 -0
  42. package/dist/cli/http.d.ts +6 -0
  43. package/dist/cli/http.js +38 -0
  44. package/dist/cli/identity-commands.d.ts +3 -0
  45. package/dist/cli/identity-commands.js +56 -0
  46. package/dist/cli/index.d.ts +13 -0
  47. package/dist/cli/index.js +13 -0
  48. package/dist/cli/init.d.ts +205 -0
  49. package/dist/cli/init.js +77 -0
  50. package/dist/cli/modules.d.ts +6 -0
  51. package/dist/cli/modules.js +18 -0
  52. package/dist/cli/output.d.ts +2 -0
  53. package/dist/cli/output.js +35 -0
  54. package/dist/cli/prompts.d.ts +34 -0
  55. package/dist/cli/prompts.js +58 -0
  56. package/dist/cli/runtime.d.ts +2 -0
  57. package/dist/cli/runtime.js +137 -0
  58. package/dist/cli/schemas.d.ts +187 -0
  59. package/dist/cli/schemas.js +46 -0
  60. package/dist/doctor.d.ts +2 -0
  61. package/dist/doctor.js +72 -0
  62. package/dist/internal/client.d.ts +6 -0
  63. package/dist/internal/client.js +51 -0
  64. package/dist/internal/host.d.ts +1 -0
  65. package/dist/internal/host.js +50 -0
  66. package/dist/internal/protocol.d.ts +27 -0
  67. package/dist/internal/protocol.js +1 -0
  68. package/dist/main.d.ts +2 -0
  69. package/dist/main.js +12 -0
  70. package/dist/skills/agents.d.ts +7 -0
  71. package/dist/skills/agents.js +11 -0
  72. package/dist/skills/artifacts.d.ts +9 -0
  73. package/dist/skills/artifacts.js +12 -0
  74. package/dist/skills/bundle.d.ts +22 -0
  75. package/dist/skills/bundle.js +77 -0
  76. package/dist/skills/client.d.ts +5 -0
  77. package/dist/skills/client.js +9 -0
  78. package/dist/skills/commands.d.ts +5 -0
  79. package/dist/skills/commands.js +20 -0
  80. package/dist/skills/delivery.d.ts +60 -0
  81. package/dist/skills/delivery.js +89 -0
  82. package/dist/skills/index.d.ts +7 -0
  83. package/dist/skills/index.js +7 -0
  84. package/dist/skills/installer.d.ts +23 -0
  85. package/dist/skills/installer.js +130 -0
  86. package/dist/skills/paths.d.ts +2 -0
  87. package/dist/skills/paths.js +28 -0
  88. package/package.json +36 -3
  89. package/scripts/install.mjs +17 -0
  90. package/skills/SKILL.md +38 -0
  91. package/skills/bundle.json +7 -0
  92. package/skills/commands.md +440 -0
  93. package/skills/features.md +12 -0
package/dist/main.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { applyDeployment } from './cli/deployment.js';
3
+ applyDeployment(new URL('../', import.meta.url));
4
+ if (process.send && process.argv.length === 3 && process.argv[2] === '--lxz-ipc') {
5
+ const { runMainHost } = await import('./internal/host.js');
6
+ runMainHost();
7
+ }
8
+ else {
9
+ const { runApplication } = await import('./cli/index.js');
10
+ const { application } = await import('./application.js');
11
+ await runApplication(application);
12
+ }
@@ -0,0 +1,7 @@
1
+ export declare const agentSkillDirectories: {
2
+ readonly shared: ".agents/skills";
3
+ readonly codex: ".codex/skills";
4
+ readonly claude: ".claude/skills";
5
+ readonly linkwise: ".linkwise/skills";
6
+ };
7
+ export declare function defaultSkillDirectories(): string[];
@@ -0,0 +1,11 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ export const agentSkillDirectories = {
4
+ shared: '.agents/skills',
5
+ codex: '.codex/skills',
6
+ claude: '.claude/skills',
7
+ linkwise: '.linkwise/skills',
8
+ };
9
+ export function defaultSkillDirectories() {
10
+ return [agentSkillDirectories.shared, agentSkillDirectories.linkwise].map(path => join(homedir(), path));
11
+ }
@@ -0,0 +1,9 @@
1
+ import type { Application } from '../cli/index.js';
2
+ export declare function skillManifest(app: Pick<Application, 'name' | 'packageName' | 'version'>): {
3
+ name: string;
4
+ packageName: string;
5
+ version: string;
6
+ cliVersion: string;
7
+ contractVersion: string;
8
+ };
9
+ export declare function skillArtifacts(app: Application): Record<string, string>;
@@ -0,0 +1,12 @@
1
+ import { commandReference, contractVersion, describe } from '../cli/index.js';
2
+ export function skillManifest(app) {
3
+ return { name: app.name, packageName: app.packageName, version: app.version, cliVersion: app.version, contractVersion };
4
+ }
5
+ export function skillArtifacts(app) {
6
+ const features = Object.entries(describe(app).commands).map(([name, command]) => `| ${command.module ?? 'application'} | ${command.description.replaceAll('|', '\\|')} | \`${app.name} ${name} -h\` | ${command.effects} |`);
7
+ return {
8
+ 'features.md': `# ${app.name} feature map\n\nGenerated from registered commands. Use this map to locate a task, then read that command help.\n\n| Module | Task | Help entry | Effects |\n| --- | --- | --- | --- |\n${features.join('\n')}\n`,
9
+ 'commands.md': commandReference(app) + '\n',
10
+ 'bundle.json': JSON.stringify(skillManifest(app), null, 2) + '\n',
11
+ };
12
+ }
@@ -0,0 +1,22 @@
1
+ export interface SkillBundle {
2
+ name: string;
3
+ packageName: string;
4
+ version: string;
5
+ cliVersion: string;
6
+ contractVersion: string;
7
+ files: Record<string, string>;
8
+ }
9
+ export interface SkillIdentity {
10
+ name: string;
11
+ packageName: string;
12
+ cliVersion: string;
13
+ }
14
+ export interface Manifest extends Omit<SkillBundle, 'files'> {
15
+ format: 1;
16
+ hashes: Record<string, string>;
17
+ }
18
+ export declare const manifestFile = ".lianxz-skill.json";
19
+ export declare function validPaths(paths: string[]): boolean;
20
+ export declare function validateBundle(value: unknown, expected?: SkillIdentity): asserts value is SkillBundle;
21
+ export declare function isManifest(value: unknown): value is Manifest;
22
+ export declare function loadSkill(directory: string, expected?: SkillIdentity): Promise<SkillBundle>;
@@ -0,0 +1,77 @@
1
+ import { lstat, readFile, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { CliError, contractVersion } from '../cli/index.js';
4
+ export const manifestFile = '.lianxz-skill.json';
5
+ function validSegment(segment) {
6
+ return Boolean(segment) && segment !== '.' && segment !== '..'
7
+ && !/[\\<>:"|?*\x00-\x1f]/.test(segment) && !/[. ]$/.test(segment)
8
+ && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(segment);
9
+ }
10
+ export function validPaths(paths) {
11
+ const known = new Set();
12
+ for (const path of paths) {
13
+ const segments = path.split('/');
14
+ if (!segments.every(validSegment) || segments[0]?.toLowerCase() === manifestFile || path.toLowerCase() === 'bundle.json')
15
+ return false;
16
+ const canonical = path.toLowerCase();
17
+ if (known.has(canonical))
18
+ return false;
19
+ known.add(canonical);
20
+ }
21
+ return paths.every((path) => path.split('/').slice(0, -1).every((_, index, parts) => !known.has(parts.slice(0, index + 1).join('/').toLowerCase())));
22
+ }
23
+ function record(value) {
24
+ return Boolean(value && typeof value === 'object' && !Array.isArray(value));
25
+ }
26
+ function metadata(value) {
27
+ return record(value) && ['name', 'packageName', 'version', 'cliVersion', 'contractVersion'].every((key) => typeof value[key] === 'string' && value[key].length > 0) && /^[a-z][a-z0-9-]*$/.test(value.name);
28
+ }
29
+ export function validateBundle(value, expected) {
30
+ if (!metadata(value) || !record(value.files))
31
+ throw new CliError('CONFIGURATION', 'The bundled Skill manifest or file set is invalid.', 'Reinstall this exact CLI version; if it still fails, ask the maintainer to check its bundled Skill.');
32
+ const files = value.files;
33
+ if (!files['SKILL.md'] || !validPaths(Object.keys(files)) || Object.values(files).some((content) => typeof content !== 'string'))
34
+ throw new CliError('CONFIGURATION', 'The bundled Skill is missing SKILL.md or contains invalid resource paths.', 'Reinstall this CLI; if it still fails, ask the maintainer to check its Skill files and directories.');
35
+ if (value.contractVersion !== contractVersion)
36
+ throw new CliError('INCOMPATIBLE', 'The Skill contract does not match this CLI.', 'Reinstall this exact CLI version; if it still fails, ask the maintainer to check bundled resources and shared component versions.');
37
+ if (expected && (value.name !== expected.name || value.packageName !== expected.packageName || value.cliVersion !== expected.cliVersion))
38
+ throw new CliError('INCOMPATIBLE', 'The bundled Skill does not match the running CLI.', 'Reinstall this exact CLI version; if it still fails, ask the maintainer to check the Skill name and version.', false, { expected, bundled: { name: value.name, packageName: value.packageName, cliVersion: value.cliVersion } });
39
+ }
40
+ export function isManifest(value) {
41
+ if (!metadata(value) || !record(value.hashes) || value.format !== 1)
42
+ return false;
43
+ const hashes = value.hashes;
44
+ return validPaths(Object.keys(hashes)) && Object.values(hashes).every((hash) => typeof hash === 'string' && /^[a-f0-9]{64}$/.test(hash));
45
+ }
46
+ export async function loadSkill(directory, expected) {
47
+ try {
48
+ const bundlePath = join(directory, 'bundle.json');
49
+ if (!(await lstat(bundlePath)).isFile())
50
+ throw new Error('invalid manifest');
51
+ const bundle = JSON.parse(await readFile(bundlePath, 'utf8'));
52
+ const files = {};
53
+ async function collect(relative = '') {
54
+ const entries = await readdir(join(directory, relative), { withFileTypes: true });
55
+ for (const entry of entries) {
56
+ const name = relative ? `${relative}/${entry.name}` : entry.name;
57
+ if (!relative && entry.name === 'bundle.json')
58
+ continue;
59
+ if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory()))
60
+ throw new CliError('CONFIGURATION', 'Skill resources contain symbolic links or special files.', 'Store bundled resources as regular files and directories.');
61
+ if (entry.isDirectory())
62
+ await collect(name);
63
+ else
64
+ files[name] = await readFile(join(directory, name), 'utf8');
65
+ }
66
+ }
67
+ await collect();
68
+ const result = { ...(record(bundle) ? bundle : {}), files };
69
+ validateBundle(result, expected);
70
+ return result;
71
+ }
72
+ catch (error) {
73
+ if (error instanceof CliError)
74
+ throw error;
75
+ throw new CliError('CONFIGURATION', 'Cannot read the bundled Skill.', 'Reinstall this exact CLI version; if it still fails, ask the maintainer to check the bundled Skill files.');
76
+ }
77
+ }
@@ -0,0 +1,5 @@
1
+ import type { SkillPort } from '../cli/init.js';
2
+ import type { SkillSyncPort } from './commands.js';
3
+ export declare function createLxzSkill(root: string | URL, name: string, { env }?: {
4
+ env?: NodeJS.ProcessEnv;
5
+ }): SkillPort & SkillSyncPort;
@@ -0,0 +1,9 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { callMain } from '../internal/client.js';
3
+ export function createLxzSkill(root, name, { env = process.env } = {}) {
4
+ const source = { root: root instanceof URL ? fileURLToPath(root) : root, name };
5
+ return {
6
+ install: (directory, conflict, signal) => callMain({ ...source, operation: 'skill.install', directory, conflict }, { env, signal }),
7
+ sync: (directory, conflict, signal) => callMain({ ...source, operation: 'skill.sync', directory, conflict }, { env, signal }),
8
+ };
9
+ }
@@ -0,0 +1,5 @@
1
+ import type { Command } from '../cli/index.js';
2
+ export interface SkillSyncPort {
3
+ sync(directory: string | undefined, conflict: 'error' | 'replace', signal: AbortSignal): Promise<unknown>;
4
+ }
5
+ export declare function skillCommands(skill: SkillSyncPort, invoke: string): Record<string, Command>;
@@ -0,0 +1,20 @@
1
+ export function skillCommands(skill, invoke) {
2
+ return {
3
+ 'install skill': {
4
+ description: 'Install the bundled Skill for this version; synchronize registered directories on upgrade or rollback',
5
+ effects: 'local',
6
+ parameters: {
7
+ 'skills-dir': { type: 'string', description: 'Skills root; overrides LXZ_SKILLS_DIR. First install targets ~/.agents/skills and ~/.linkwise/skills (Linkwise)' },
8
+ 'skill-conflict': { type: 'string', description: 'Local changes: error keeps them; replace overwrites files managed by this CLI', choices: ['error', 'replace'], default: 'error' },
9
+ },
10
+ result: { type: 'object', required: ['installed'], properties: { installed: { type: 'array', items: { type: 'object', required: ['directory', 'version', 'action'], properties: { directory: { type: 'string' }, version: { type: 'string' }, action: { enum: ['installed', 'updated', 'unchanged'] } } } } } },
11
+ examples: [invoke + ' install skill', invoke + ' install skill --skills-dir ./ceshi123/skills --json --non-interactive'],
12
+ format(result) {
13
+ return result.installed.map((item) => `Agent Skill: ${item.directory}\nVersion: ${item.version}; ${{ installed: 'installed', updated: 'updated', unchanged: 'already current' }[item.action]}`).join('\n\n');
14
+ },
15
+ run(input, context) {
16
+ return skill.sync(typeof input['skills-dir'] === 'string' ? input['skills-dir'] : undefined, input['skill-conflict'], context.signal);
17
+ },
18
+ },
19
+ };
20
+ }
@@ -0,0 +1,60 @@
1
+ export declare class BundledSkill {
2
+ readonly name: string;
3
+ readonly env: NodeJS.ProcessEnv;
4
+ readonly root: string;
5
+ constructor(root: string | URL, name: string, env?: NodeJS.ProcessEnv);
6
+ private source;
7
+ directory(input?: string): string;
8
+ private remember;
9
+ install(directory: string | undefined, conflict: 'error' | 'replace', signal: AbortSignal): Promise<{
10
+ directory: string;
11
+ version: string;
12
+ action: string;
13
+ changes: never[];
14
+ incompatible?: undefined;
15
+ } | {
16
+ directory: string;
17
+ version: string;
18
+ action: string;
19
+ incompatible: boolean;
20
+ changes: {
21
+ file: string;
22
+ change: string;
23
+ }[];
24
+ } | {
25
+ installed: ({
26
+ directory: string;
27
+ version: string;
28
+ action: string;
29
+ changes: never[];
30
+ incompatible?: undefined;
31
+ } | {
32
+ directory: string;
33
+ version: string;
34
+ action: string;
35
+ incompatible: boolean;
36
+ changes: {
37
+ file: string;
38
+ change: string;
39
+ }[];
40
+ })[];
41
+ }>;
42
+ sync(directory: string | undefined, conflict: 'error' | 'replace', signal: AbortSignal): Promise<{
43
+ installed: ({
44
+ directory: string;
45
+ version: string;
46
+ action: string;
47
+ changes: never[];
48
+ incompatible?: undefined;
49
+ } | {
50
+ directory: string;
51
+ version: string;
52
+ action: string;
53
+ incompatible: boolean;
54
+ changes: {
55
+ file: string;
56
+ change: string;
57
+ }[];
58
+ })[];
59
+ }>;
60
+ }
@@ -0,0 +1,89 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFile, readdir, mkdir, writeFile, rename, rm } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { CliError, failure } from '../cli/index.js';
7
+ import { loadSkill } from './bundle.js';
8
+ import { SkillInstaller, legacyPackageName } from './installer.js';
9
+ import { defaultSkillDirectories } from './agents.js';
10
+ export class BundledSkill {
11
+ name;
12
+ env;
13
+ root;
14
+ constructor(root, name, env = process.env) {
15
+ this.name = name;
16
+ this.env = env;
17
+ this.root = root instanceof URL ? fileURLToPath(root) : root;
18
+ }
19
+ async source() {
20
+ const pkg = JSON.parse(await readFile(join(this.root, 'package.json'), 'utf8'));
21
+ const bundle = await loadSkill(join(this.root, 'skills'), { name: this.name, packageName: pkg.name, cliVersion: pkg.version });
22
+ const state = this.env.LXZ_SKILLS_STATE_DIR ?? join(homedir(), '.lianxz', 'skills');
23
+ const registryOf = (name) => join(state, createHash('sha256').update(name).digest('hex'));
24
+ const legacy = legacyPackageName(pkg.name);
25
+ return { installer: new SkillInstaller(bundle), registry: registryOf(pkg.name), legacyRegistry: legacy && registryOf(legacy) };
26
+ }
27
+ directory(input) {
28
+ const value = input ?? (this.env.LXZ_SKILLS_DIR || join(homedir(), '.agents', 'skills'));
29
+ if (!value.trim())
30
+ throw new CliError('INVALID_INPUT', 'The Skill installation directory must not be empty.', 'Pass --skills-dir <agent-skills-root>.');
31
+ return resolve(value.replace(/^~(?=$|[\\/])/, () => homedir()));
32
+ }
33
+ async remember(registry, directory) {
34
+ await mkdir(registry, { recursive: true, mode: 0o700 });
35
+ const key = process.platform === 'win32' ? directory.toLowerCase() : directory;
36
+ const file = join(registry, createHash('sha256').update(key).digest('hex') + '.json');
37
+ const temporary = `${file}.${randomUUID()}.tmp`;
38
+ try {
39
+ await writeFile(temporary, JSON.stringify({ directory }) + '\n', { mode: 0o600, flag: 'wx' });
40
+ await rename(temporary, file);
41
+ }
42
+ finally {
43
+ await rm(temporary, { force: true });
44
+ }
45
+ }
46
+ async install(directory, conflict, signal) {
47
+ const result = await this.sync(directory, conflict, signal);
48
+ return directory !== undefined || this.env.LXZ_SKILLS_DIR ? result.installed[0] : result;
49
+ }
50
+ async sync(directory, conflict, signal) {
51
+ const { installer, registry, legacyRegistry } = await this.source();
52
+ let targets = directory !== undefined || this.env.LXZ_SKILLS_DIR
53
+ ? [this.directory(directory)]
54
+ : defaultSkillDirectories();
55
+ if (directory === undefined && !this.env.LXZ_SKILLS_DIR) {
56
+ try {
57
+ // Until the new package has installed anywhere, keep updating where the old @lianxz package installed
58
+ for (const source of [registry, legacyRegistry]) {
59
+ const files = source ? (await readdir(source).catch((error) => { if (error.code === 'ENOENT')
60
+ return []; throw error; })).filter((name) => name.endsWith('.json')) : [];
61
+ if (files.length) {
62
+ targets = await Promise.all(files.map(async (file) => JSON.parse(await readFile(join(source, file), 'utf8')).directory));
63
+ break;
64
+ }
65
+ }
66
+ }
67
+ catch (error) {
68
+ if (error.code !== 'ENOENT')
69
+ throw error;
70
+ }
71
+ }
72
+ const installed = [];
73
+ const failed = [];
74
+ for (const target of new Set(targets)) {
75
+ signal.throwIfAborted();
76
+ try {
77
+ await this.remember(registry, target);
78
+ installed.push(await installer.install(target, conflict, signal));
79
+ }
80
+ catch (error) {
81
+ signal.throwIfAborted();
82
+ failed.push({ directory: target, error: failure(error) });
83
+ }
84
+ }
85
+ if (failed.length)
86
+ throw new CliError('IO_ERROR', 'Some Skill directories could not be updated; successful updates were kept.', 'Resolve each directory error and run install skill again; back up local changes before using --skill-conflict replace.', false, { installed, failed });
87
+ return { installed };
88
+ }
89
+ }
@@ -0,0 +1,7 @@
1
+ export * from './bundle.js';
2
+ export * from './installer.js';
3
+ export * from './delivery.js';
4
+ export * from './commands.js';
5
+ export * from './artifacts.js';
6
+ export * from './client.js';
7
+ export * from './agents.js';
@@ -0,0 +1,7 @@
1
+ export * from './bundle.js';
2
+ export * from './installer.js';
3
+ export * from './delivery.js';
4
+ export * from './commands.js';
5
+ export * from './artifacts.js';
6
+ export * from './client.js';
7
+ export * from './agents.js';
@@ -0,0 +1,23 @@
1
+ import type { SkillBundle } from './bundle.js';
2
+ export declare const legacyPackageName: (name: string) => string | undefined;
3
+ export declare class SkillInstaller {
4
+ readonly bundle: SkillBundle;
5
+ constructor(bundle: SkillBundle);
6
+ install(directory: string, conflict?: 'error' | 'replace', signal?: AbortSignal): Promise<{
7
+ directory: string;
8
+ version: string;
9
+ action: string;
10
+ changes: never[];
11
+ incompatible?: undefined;
12
+ } | {
13
+ directory: string;
14
+ version: string;
15
+ action: string;
16
+ incompatible: boolean;
17
+ changes: {
18
+ file: string;
19
+ change: string;
20
+ }[];
21
+ }>;
22
+ private installFiles;
23
+ }
@@ -0,0 +1,130 @@
1
+ import { mkdir, readFile, writeFile, lstat, cp, rename, rm } from 'node:fs/promises';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { resolve, join, dirname } from 'node:path';
4
+ import { CliError } from '../cli/index.js';
5
+ import { validateBundle, isManifest, manifestFile } from './bundle.js';
6
+ import { exists, managedFile } from './paths.js';
7
+ // Packages moved from @lianxz/<name> to @tulcn/<name>: a Skill installed by the old package belongs to the new one.
8
+ export const legacyPackageName = (name) => name.startsWith('@tulcn/') ? '@lianxz/' + name.slice('@tulcn/'.length) : undefined;
9
+ const hash = (text) => createHash('sha256').update(text).digest('hex');
10
+ export class SkillInstaller {
11
+ bundle;
12
+ constructor(bundle) {
13
+ this.bundle = bundle;
14
+ validateBundle(bundle);
15
+ }
16
+ async install(directory, conflict = 'error', signal = new AbortController().signal) {
17
+ try {
18
+ return await this.installFiles(directory, conflict, signal);
19
+ }
20
+ catch (error) {
21
+ signal.throwIfAborted();
22
+ if (error instanceof CliError)
23
+ throw error;
24
+ throw new CliError('IO_ERROR', 'Skill installation failed.', 'Check directory permissions and free disk space, then retry.');
25
+ }
26
+ }
27
+ async installFiles(directory, conflict, signal) {
28
+ signal.throwIfAborted();
29
+ const root = resolve(directory);
30
+ const target = join(root, this.bundle.name);
31
+ await mkdir(root, { recursive: true });
32
+ if ((await lstat(root)).isSymbolicLink())
33
+ throw new CliError('CONFLICT', 'The Skills root directory must not be a symbolic link.', 'Provide a real directory.');
34
+ const lock = join(root, `.${this.bundle.name}.install-lock`);
35
+ try {
36
+ await mkdir(lock);
37
+ }
38
+ catch (error) {
39
+ if (error.code === 'EEXIST')
40
+ throw new CliError('CONFLICT', 'This Skill is being installed or a previous installation was interrupted.', 'Retry later; remove this Skill .install-lock directory only after confirming no installer is running.', true);
41
+ throw new CliError('IO_ERROR', 'The Skills directory is not writable.', 'Check permissions for --skills-dir.');
42
+ }
43
+ const stage = join(root, `.${this.bundle.name}.${randomUUID()}.stage`);
44
+ const backup = join(root, `.${this.bundle.name}.${randomUUID()}.backup`);
45
+ let moved = false;
46
+ let committed = false;
47
+ try {
48
+ const stat = await exists(target);
49
+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink()))
50
+ throw new CliError('CONFLICT', 'The Skill target is not a regular directory.', 'Choose another Skills directory.');
51
+ let previous;
52
+ if (stat) {
53
+ const manifestStat = await exists(join(target, manifestFile));
54
+ if (manifestStat && (!manifestStat.isFile() || manifestStat.isSymbolicLink()))
55
+ throw new CliError('CONFLICT', 'The Skill manifest is not a regular file.', 'Keep the conflicting directory and inspect its manifest.');
56
+ try {
57
+ previous = JSON.parse(await readFile(join(target, manifestFile), 'utf8'));
58
+ }
59
+ catch { /* Unmanaged directories cannot be overwritten. */ }
60
+ if (!isManifest(previous) || ![this.bundle.packageName, legacyPackageName(this.bundle.packageName)].includes(previous.packageName) || previous.name !== this.bundle.name) {
61
+ throw new CliError('CONFLICT', 'The directory belongs to another Skill or is unmanaged.', 'Keep the directory and choose another --skills-dir.');
62
+ }
63
+ }
64
+ const hashes = Object.fromEntries(Object.entries(this.bundle.files).map(([name, value]) => [name, hash(value)]));
65
+ const changes = [];
66
+ let modified = false;
67
+ for (const name of new Set([...Object.keys(previous?.hashes ?? {}), ...Object.keys(hashes)])) {
68
+ const file = join(target, name);
69
+ const fileStat = await managedFile(target, name);
70
+ let current;
71
+ if (fileStat) {
72
+ current = hash(await readFile(file, 'utf8'));
73
+ }
74
+ if (previous && current !== previous.hashes[name])
75
+ modified = true;
76
+ if (current !== hashes[name])
77
+ changes.push({ file: name, change: !hashes[name] ? 'remove' : !current ? 'add' : 'update' });
78
+ }
79
+ const incompatible = previous && (previous.cliVersion !== this.bundle.cliVersion || previous.contractVersion !== this.bundle.contractVersion);
80
+ if (modified && conflict !== 'replace')
81
+ throw new CliError('CONFLICT', 'The Skill has local changes or conflicting new files.', 'Review and back up local changes; retry with --skill-conflict replace to overwrite managed files.', false, { installedVersion: previous?.version, desiredVersion: this.bundle.version, incompatible, changes });
82
+ if (!changes.length && previous?.version === this.bundle.version && !incompatible)
83
+ return { directory: target, version: this.bundle.version, action: 'unchanged', changes: [] };
84
+ signal.throwIfAborted();
85
+ if (stat)
86
+ await cp(target, stage, { recursive: true, dereference: false });
87
+ else
88
+ await mkdir(stage);
89
+ for (const { file, change } of changes) {
90
+ signal.throwIfAborted();
91
+ if (change === 'remove')
92
+ await rm(join(stage, file));
93
+ else {
94
+ await mkdir(dirname(join(stage, file)), { recursive: true });
95
+ await writeFile(join(stage, file), this.bundle.files[file], { flag: 'w', signal });
96
+ }
97
+ }
98
+ const manifest = { format: 1, name: this.bundle.name, packageName: this.bundle.packageName, version: this.bundle.version, cliVersion: this.bundle.cliVersion, contractVersion: this.bundle.contractVersion, hashes };
99
+ await writeFile(join(stage, manifestFile), JSON.stringify(manifest, null, 2) + '\n');
100
+ signal.throwIfAborted();
101
+ if (stat) {
102
+ await rename(target, backup);
103
+ moved = true;
104
+ }
105
+ try {
106
+ await rename(stage, target);
107
+ committed = true;
108
+ }
109
+ catch (error) {
110
+ if (moved) {
111
+ try {
112
+ await rename(backup, target);
113
+ moved = false;
114
+ }
115
+ catch {
116
+ throw new CliError('IO_ERROR', 'Skill installation failed; old content remains in the backup directory.', `Check and restore ${backup} before retrying.`);
117
+ }
118
+ }
119
+ throw error;
120
+ }
121
+ return { directory: target, version: this.bundle.version, action: previous ? 'updated' : 'installed', incompatible: Boolean(incompatible), changes };
122
+ }
123
+ finally {
124
+ await rm(stage, { recursive: true, force: true });
125
+ if (moved && committed)
126
+ await rm(backup, { recursive: true, force: true });
127
+ await rm(lock, { recursive: true, force: true });
128
+ }
129
+ }
130
+ }
@@ -0,0 +1,2 @@
1
+ export declare function exists(path: string): Promise<import("fs").Stats | null>;
2
+ export declare function managedFile(root: string, relative: string): Promise<import("fs").Stats | null>;
@@ -0,0 +1,28 @@
1
+ import { lstat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { CliError } from '../cli/index.js';
4
+ export async function exists(path) {
5
+ try {
6
+ return await lstat(path);
7
+ }
8
+ catch (error) {
9
+ if (error.code === 'ENOENT')
10
+ return null;
11
+ throw error;
12
+ }
13
+ }
14
+ export async function managedFile(root, relative) {
15
+ const parts = relative.split('/');
16
+ let current = root;
17
+ for (const [index, part] of parts.entries()) {
18
+ current = join(current, part);
19
+ const stat = await exists(current);
20
+ if (!stat)
21
+ return null;
22
+ if (stat.isSymbolicLink() || (index === parts.length - 1 ? !stat.isFile() : !stat.isDirectory()))
23
+ throw new CliError('CONFLICT', 'A managed Skill path is a link or has a file/directory conflict.', 'Keep a backup and move the conflicting content before retrying.', false, { file: relative });
24
+ if (index === parts.length - 1)
25
+ return stat;
26
+ }
27
+ return null;
28
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@tulcn/lxz",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "type": "module",
5
+ "description": "联小助 CLI 主程序与命令、授权、Skill 模块",
6
+ "license": "UNLICENSED",
7
+ "bin": {
8
+ "lxz": "dist/main.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "skills",
13
+ "scripts"
14
+ ],
15
+ "engines": {
16
+ "node": ">=22.12.0"
17
+ },
18
+ "dependencies": {
19
+ "citty": "^0.2.2",
20
+ "@clack/core": "^1.5.1"
21
+ },
22
+ "exports": {
23
+ "./cli": {
24
+ "types": "./dist/cli/index.d.ts",
25
+ "import": "./dist/cli/index.js"
26
+ },
27
+ "./auth": {
28
+ "types": "./dist/auth/index.d.ts",
29
+ "import": "./dist/auth/index.js"
30
+ },
31
+ "./skills": {
32
+ "types": "./dist/skills/index.d.ts",
33
+ "import": "./dist/skills/index.js"
34
+ }
35
+ },
36
+ "scripts": {
37
+ "postinstall": "node scripts/install.mjs"
38
+ }
6
39
  }
@@ -0,0 +1,17 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ if (process.env.LXZ_SKIP_SKILLS !== '1') {
6
+ const root = new URL('../', import.meta.url);
7
+ const pkg = JSON.parse(readFileSync(new URL('package.json', root), 'utf8'));
8
+ const [name, entry] = Object.entries(pkg.bin)[0];
9
+ const result = spawnSync(process.execPath, [fileURLToPath(new URL(entry, root)), 'install', 'skill', '--non-interactive'], {
10
+ stdio: 'inherit', windowsHide: true, timeout: 120000,
11
+ });
12
+ if (result.error || result.status !== 0) {
13
+ console.error(`${name} Agent Skill installation is incomplete.`);
14
+ console.error(`Resolve the error above, then run ${name} install skill --skills-dir <writable-directory>. Set LXZ_SKIP_SKILLS=1 to skip the package install hook.`);
15
+ process.exitCode = result.status || 1;
16
+ }
17
+ }