@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
@@ -0,0 +1,58 @@
1
+ import { ConfirmPrompt, MultiSelectPrompt, SelectPrompt, TextPrompt, isCancel } from '@clack/core';
2
+ import { CliError } from './errors.js';
3
+ function frame(message, state, error, body) {
4
+ const marker = state === 'cancel' ? 'x' : state === 'submit' ? '+' : '?';
5
+ return `${marker} ${message}\n${state === 'error' ? `! ${error}\n` : ''}${body}`;
6
+ }
7
+ async function runPrompt(options, create) {
8
+ const controller = new AbortController();
9
+ const abort = () => controller.abort(options.signal?.reason);
10
+ if (options.signal?.aborted)
11
+ abort();
12
+ else
13
+ options.signal?.addEventListener('abort', abort, { once: true });
14
+ try {
15
+ return await create(controller.signal).prompt();
16
+ }
17
+ finally {
18
+ options.signal?.removeEventListener('abort', abort);
19
+ }
20
+ }
21
+ export const prompts = {
22
+ isCancel: (value) => isCancel(value),
23
+ text(options) {
24
+ return runPrompt(options, signal => new TextPrompt({ ...options, signal, output: options.output ?? process.stderr, initialUserInput: options.initialValue,
25
+ render() { return frame(options.message, this.state, this.error, this.userInputWithCursor); },
26
+ }));
27
+ },
28
+ select(options) {
29
+ return runPrompt(options, signal => new SelectPrompt({ ...options, signal, output: options.output ?? process.stderr,
30
+ render() {
31
+ const choices = this.state === 'submit' ? options.options.filter(item => item.value === this.value) : options.options;
32
+ return frame(options.message, this.state, this.error, choices.map(item => `${options.options[this.cursor] === item ? '>' : ' '} ${item.label}${item.hint ? ` (${item.hint})` : ''}`).join('\n'));
33
+ },
34
+ }));
35
+ },
36
+ multiselect(options) {
37
+ return runPrompt(options, signal => new MultiSelectPrompt({ ...options, signal, output: options.output ?? process.stderr,
38
+ render() {
39
+ const selected = this.value ?? [];
40
+ const choices = this.state === 'submit' ? options.options.filter(item => selected.includes(item.value)) : options.options;
41
+ return frame(options.message, this.state, this.error, choices.map(item => `${options.options[this.cursor] === item ? '>' : ' '} [${selected.includes(item.value) ? 'x' : ' '}] ${item.label}${item.hint ? ` (${item.hint})` : ''}`).join('\n') || '(none)');
42
+ },
43
+ }));
44
+ },
45
+ confirm(options) {
46
+ return runPrompt(options, signal => new ConfirmPrompt({ ...options, signal, output: options.output ?? process.stderr, active: 'Yes', inactive: 'No',
47
+ render() { return frame(options.message, this.state, this.error, this.value ? '> Yes / No' : 'Yes / > No'); },
48
+ }));
49
+ },
50
+ };
51
+ export function answer(value) {
52
+ if (isCancel(value))
53
+ throw new CliError('CANCELLED', 'Operation cancelled.', 'Run the command again when needed.');
54
+ return value;
55
+ }
56
+ export async function ask(message, initialValue, signal, validate) {
57
+ return answer(await prompts.text({ message, initialValue, signal, validate: value => value?.trim() ? validate?.(value.trim()) : 'Enter a value' }));
58
+ }
@@ -0,0 +1,2 @@
1
+ import type { Application } from './contracts.js';
2
+ export declare function runApplication(app: Application, argv?: string[]): Promise<void>;
@@ -0,0 +1,137 @@
1
+ import { defineCommand, renderUsage } from 'citty';
2
+ import { parseArgs } from 'node:util';
3
+ import { argumentDefinitions, commonParameters, commandParameters, contractVersion, describe } from './contracts.js';
4
+ import { CliError, exitCodes, failure } from './errors.js';
5
+ import { jsonText, rowText } from './output.js';
6
+ function jsonLine(value) {
7
+ return jsonText(value) + '\n';
8
+ }
9
+ function validate(input, parameters, required) {
10
+ for (const [name, p] of Object.entries(parameters)) {
11
+ const value = input[name];
12
+ if (required && p.required && (value === undefined || value === ''))
13
+ throw new CliError('INVALID_INPUT', `Provide --${name}.`, `See --help and provide ${p.description}.`);
14
+ if (value !== undefined && ((p.choices && !p.choices.includes(String(value))) || (p.pattern && !new RegExp(p.pattern).test(String(value))))) {
15
+ throw new CliError('INVALID_INPUT', `--${name} has an invalid value.`, `${p.description}${p.choices ? `; choices: ${p.choices.join(', ')}` : ''}. See --help for usage.`);
16
+ }
17
+ }
18
+ }
19
+ function jsonMode(raw, parameters) {
20
+ let enabled = false;
21
+ for (let index = 0; index < raw.length; index++) {
22
+ const flag = raw[index];
23
+ if (flag === '--')
24
+ break;
25
+ if (flag === '--json' || flag === '--json=true')
26
+ enabled = true;
27
+ else if (flag === '--no-json' || flag === '--json=false')
28
+ enabled = false;
29
+ else if (!flag.includes('=') && parameters[flag.slice(2)]?.type === 'string' && !raw[index + 1]?.startsWith('-'))
30
+ index++;
31
+ }
32
+ return enabled;
33
+ }
34
+ export async function runApplication(app, argv = process.argv.slice(2)) {
35
+ argv = argv.map((value) => value === '-h' ? '--help' : value === '-v' ? '--version' : value);
36
+ let json = false;
37
+ const meta = { contractVersion, cli: app.packageName, version: app.version };
38
+ const write = (data) => process.stdout.write(json ? jsonLine({ ok: true, data, meta }) : rowText(data) + '\n');
39
+ let dispose = () => { };
40
+ try {
41
+ const names = [...new Set(Object.keys(app.commands).flatMap((name) => {
42
+ const words = name.split(' ');
43
+ return words.map((_, index) => words.slice(0, index + 1).join(' '));
44
+ }))].sort((a, b) => b.length - a.length);
45
+ const leading = [];
46
+ let offset = 0;
47
+ while (argv[offset]?.startsWith('--')) {
48
+ const name = argv[offset].slice(2).split('=')[0].replace(/^no-/, '');
49
+ if (!commonParameters[name])
50
+ break;
51
+ const flag = argv[offset++];
52
+ leading.push(flag);
53
+ if (commonParameters[name].type === 'string' && !flag.includes('=') && argv[offset] !== undefined)
54
+ leading.push(argv[offset++]);
55
+ }
56
+ const remaining = argv.slice(offset);
57
+ // Route only positional command words; option values never become commands.
58
+ const explicitRoute = names.find((name) => name.split(' ').every((word, i) => remaining[i] === word));
59
+ const route = explicitRoute ?? app.defaultCommand;
60
+ const command = route ? app.commands[route] : undefined;
61
+ const parameters = commandParameters(command);
62
+ const raw = [...leading, ...(explicitRoute ? remaining.slice(explicitRoute.split(' ').length) : remaining)];
63
+ json = jsonMode(raw, parameters);
64
+ let input;
65
+ try {
66
+ const parsed = parseArgs({ args: raw, options: Object.fromEntries(Object.entries(parameters).map(([key, p]) => [key, { type: p.type, default: p.default }])), allowNegative: true, strict: true, allowPositionals: false });
67
+ input = parsed.values;
68
+ }
69
+ catch {
70
+ throw new CliError('INVALID_INPUT', 'Unknown command, option or invalid option type.', `Use ${app.name} --help to view commands and options.`);
71
+ }
72
+ if (input.version) {
73
+ write({ version: app.version, contractVersion });
74
+ return;
75
+ }
76
+ if (input.schema) {
77
+ write(describe(app, explicitRoute));
78
+ return;
79
+ }
80
+ if (input.help || (!argv.length && !app.defaultCommand)) {
81
+ const definition = defineCommand({ meta: { name: route ? `${app.name} ${route}` : app.name, version: app.version, description: command?.description ?? app.description }, args: argumentDefinitions(parameters) });
82
+ const usage = await renderUsage(definition);
83
+ const children = Object.entries(app.commands).filter(([name]) => !route || name.startsWith(route + ' '));
84
+ const commands = children.length ? `\nCommands:\n${children.map(([name, c]) => ` ${route ? name.slice(route.length + 1) : name} ${c.description}`).join('\n')}\n\nUse ${route ? `${app.name} ${route}` : app.name} <command> -h for options and examples.` : '';
85
+ write(`${usage}${command ? `\nExamples:\n${command.examples.join('\n')}` : ''}${commands}`);
86
+ return;
87
+ }
88
+ if (!command)
89
+ throw new CliError('INVALID_INPUT', 'Choose a command.', `Run ${app.name} --help.`);
90
+ validate(input, parameters, true);
91
+ const interactive = Boolean(process.stdin.isTTY && process.stderr.isTTY && !input['non-interactive']);
92
+ const idle = interactive && command.interactiveTimeout !== 'total';
93
+ const timeout = Number(input['timeout-ms']);
94
+ const controller = new AbortController();
95
+ let timer;
96
+ const resetTimer = () => {
97
+ clearTimeout(timer);
98
+ timer = setTimeout(() => controller.abort(idle
99
+ ? new CliError('TIMEOUT', 'No input for 60 seconds; operation ended.', 'Run the command again to continue.', true)
100
+ : new CliError('TIMEOUT', 'Operation timed out.', 'Check network and service status, or increase --timeout-ms and retry.', true)), idle ? 60000 : timeout);
101
+ };
102
+ const stdinPaused = process.stdin.isPaused();
103
+ resetTimer();
104
+ if (idle)
105
+ process.stdin.on('data', resetTimer);
106
+ const cancel = () => controller.abort(new CliError('CANCELLED', 'Operation cancelled.', 'Run again when needed.'));
107
+ process.once('SIGINT', cancel);
108
+ process.once('SIGTERM', cancel);
109
+ dispose = () => {
110
+ clearTimeout(timer);
111
+ if (idle) {
112
+ process.stdin.off('data', resetTimer);
113
+ if (stdinPaused)
114
+ process.stdin.pause();
115
+ }
116
+ process.off('SIGINT', cancel);
117
+ process.off('SIGTERM', cancel);
118
+ };
119
+ const aborted = new Promise((_, reject) => controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true }));
120
+ const result = await Promise.race([command.run(input, {
121
+ interactive, argv,
122
+ signal: controller.signal, log: (message) => process.stderr.write(`${message}\n`),
123
+ }), aborted]);
124
+ write(!json && command.format ? command.format(result) : result);
125
+ }
126
+ catch (error) {
127
+ const detail = failure(error);
128
+ if (json)
129
+ process.stdout.write(jsonLine({ ok: false, error: detail, meta }));
130
+ else
131
+ process.stderr.write(`${detail.code}: ${detail.message}\nNext: ${detail.next}\n${detail.details ? rowText(detail.details) + '\n' : ''}`);
132
+ process.exitCode = exitCodes[detail.code];
133
+ }
134
+ finally {
135
+ dispose();
136
+ }
137
+ }
@@ -0,0 +1,187 @@
1
+ import type { Application } from './contracts.js';
2
+ export declare const schemaDialect: "https://json-schema.org/draft/2020-12/schema";
3
+ export declare const errorSchema: {
4
+ type: string;
5
+ required: string[];
6
+ properties: {
7
+ code: {
8
+ enum: string[];
9
+ };
10
+ message: {
11
+ type: string;
12
+ };
13
+ retryable: {
14
+ type: string;
15
+ };
16
+ next: {
17
+ type: string;
18
+ };
19
+ details: {};
20
+ };
21
+ };
22
+ export declare function resultSchema(app?: Application, command?: string): {
23
+ $schema: "https://json-schema.org/draft/2020-12/schema";
24
+ oneOf: ({
25
+ type: string;
26
+ required: string[];
27
+ properties: {
28
+ ok: {
29
+ const: boolean;
30
+ };
31
+ data: Record<string, unknown>;
32
+ meta: {
33
+ type: string;
34
+ required: string[];
35
+ properties: {
36
+ contractVersion: {
37
+ const: string;
38
+ };
39
+ cli: {
40
+ const: string;
41
+ type?: undefined;
42
+ } | {
43
+ type: string;
44
+ const?: undefined;
45
+ };
46
+ version: {
47
+ const: string;
48
+ type?: undefined;
49
+ } | {
50
+ type: string;
51
+ const?: undefined;
52
+ };
53
+ };
54
+ };
55
+ error?: undefined;
56
+ };
57
+ } | {
58
+ type: string;
59
+ required: string[];
60
+ properties: {
61
+ ok: {
62
+ const: boolean;
63
+ };
64
+ error: {
65
+ type: string;
66
+ required: string[];
67
+ properties: {
68
+ code: {
69
+ enum: string[];
70
+ };
71
+ message: {
72
+ type: string;
73
+ };
74
+ retryable: {
75
+ type: string;
76
+ };
77
+ next: {
78
+ type: string;
79
+ };
80
+ details: {};
81
+ };
82
+ };
83
+ meta: {
84
+ type: string;
85
+ required: string[];
86
+ properties: {
87
+ contractVersion: {
88
+ const: string;
89
+ };
90
+ cli: {
91
+ const: string;
92
+ type?: undefined;
93
+ } | {
94
+ type: string;
95
+ const?: undefined;
96
+ };
97
+ version: {
98
+ const: string;
99
+ type?: undefined;
100
+ } | {
101
+ type: string;
102
+ const?: undefined;
103
+ };
104
+ };
105
+ };
106
+ data?: undefined;
107
+ };
108
+ })[];
109
+ };
110
+ export declare function schemaTemplates(app?: Application): Record<string, string>;
111
+ export declare function schemaArtifacts(app: Application): Record<string, string>;
112
+ export declare const commandDocumentSchema: {
113
+ $schema: "https://json-schema.org/draft/2020-12/schema";
114
+ $id: string;
115
+ type: string;
116
+ required: string[];
117
+ properties: {
118
+ contractVersion: {
119
+ const: string;
120
+ };
121
+ name: {
122
+ type: string;
123
+ };
124
+ packageName: {
125
+ type: string;
126
+ pattern: string;
127
+ };
128
+ version: {
129
+ type: string;
130
+ };
131
+ description: {
132
+ type: string;
133
+ };
134
+ commands: {
135
+ type: string;
136
+ additionalProperties: {
137
+ type: string;
138
+ required: string[];
139
+ properties: {
140
+ module: {
141
+ type: string;
142
+ };
143
+ description: {
144
+ type: string;
145
+ };
146
+ effects: {
147
+ enum: string[];
148
+ };
149
+ preview: {
150
+ type: string;
151
+ };
152
+ examples: {
153
+ type: string;
154
+ items: {
155
+ type: string;
156
+ };
157
+ };
158
+ input: {
159
+ type: string;
160
+ required: string[];
161
+ properties: {
162
+ type: {
163
+ const: string;
164
+ };
165
+ properties: {
166
+ type: string;
167
+ };
168
+ required: {
169
+ type: string;
170
+ items: {
171
+ type: string;
172
+ };
173
+ };
174
+ additionalProperties: {
175
+ const: boolean;
176
+ };
177
+ };
178
+ };
179
+ result: {
180
+ type: string;
181
+ required: string[];
182
+ };
183
+ };
184
+ };
185
+ };
186
+ };
187
+ };
@@ -0,0 +1,46 @@
1
+ import { contractVersion, describe } from './contracts.js';
2
+ import { exitCodes } from './errors.js';
3
+ // Kept as a $schema member: the dialect is a schema identifier, not an address the CLI contacts, and code checks read it so
4
+ const dialect = { $schema: 'https://json-schema.org/draft/2020-12/schema' };
5
+ export const schemaDialect = dialect.$schema;
6
+ export const errorSchema = {
7
+ type: 'object', required: ['code', 'message', 'retryable', 'next'],
8
+ properties: { code: { enum: Object.keys(exitCodes) }, message: { type: 'string' }, retryable: { type: 'boolean' }, next: { type: 'string' }, details: {} },
9
+ };
10
+ export function resultSchema(app, command) {
11
+ const meta = { type: 'object', required: ['contractVersion', 'cli', 'version'], properties: { contractVersion: { const: contractVersion }, cli: app ? { const: app.packageName } : { type: 'string' }, version: app ? { const: app.version } : { type: 'string' } } };
12
+ return {
13
+ $schema: schemaDialect,
14
+ oneOf: [
15
+ { type: 'object', required: ['ok', 'data', 'meta'], properties: { ok: { const: true }, data: app && command ? app.commands[command].result : {}, meta } },
16
+ { type: 'object', required: ['ok', 'error', 'meta'], properties: { ok: { const: false }, error: errorSchema, meta } },
17
+ ],
18
+ };
19
+ }
20
+ export function schemaTemplates(app) {
21
+ const json = (value) => JSON.stringify(value, null, 2) + '\n';
22
+ return {
23
+ 'commands.schema.json': json(commandDocumentSchema),
24
+ 'result.schema.json': json(resultSchema(app)),
25
+ };
26
+ }
27
+ export function schemaArtifacts(app) {
28
+ const facts = describe(app);
29
+ const json = (value) => JSON.stringify(value, null, 2) + '\n';
30
+ return {
31
+ ...schemaTemplates(app),
32
+ 'commands.json': json(facts),
33
+ ...Object.fromEntries(Object.entries(facts.commands).flatMap(([name, command]) => {
34
+ const path = name.replaceAll(' ', '.');
35
+ return [[path + '.input.schema.json', json({ $schema: schemaDialect, ...command.input })], [path + '.result.schema.json', json(resultSchema(app, name))]];
36
+ })),
37
+ };
38
+ }
39
+ export const commandDocumentSchema = {
40
+ $schema: schemaDialect, $id: 'urn:lianxz:commands:1', type: 'object',
41
+ required: ['contractVersion', 'name', 'packageName', 'version', 'description', 'commands'],
42
+ properties: {
43
+ contractVersion: { const: contractVersion }, name: { type: 'string' }, packageName: { type: 'string', pattern: '^@tulcn/' }, version: { type: 'string' }, description: { type: 'string' },
44
+ commands: { type: 'object', additionalProperties: { type: 'object', required: ['description', 'effects', 'preview', 'examples', 'input', 'result'], properties: { module: { type: 'string' }, description: { type: 'string' }, effects: { enum: ['none', 'local', 'remote'] }, preview: { type: 'boolean' }, examples: { type: 'array', items: { type: 'string' } }, input: { type: 'object', required: ['type', 'properties', 'required'], properties: { type: { const: 'object' }, properties: { type: 'object' }, required: { type: 'array', items: { type: 'string' } }, additionalProperties: { const: false } } }, result: { type: 'object', required: ['type'] } } } },
45
+ },
46
+ };
@@ -0,0 +1,2 @@
1
+ import type { Command } from './cli/index.js';
2
+ export declare const doctor: Command;
package/dist/doctor.js ADDED
@@ -0,0 +1,72 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { defaultIdentity } from './auth/index.js';
3
+ import { CliError, failure, request, checkRuntimeVersions } from './cli/index.js';
4
+ async function pnpm(args, signal) {
5
+ return new Promise((resolve, reject) => {
6
+ const child = process.platform === 'win32'
7
+ ? spawn('cmd.exe', ['/d', '/s', '/c', ['pnpm', ...args].join(' ')], { windowsHide: true, signal, timeout: 15000 })
8
+ : spawn('pnpm', args, { signal, timeout: 15000 });
9
+ let output = '';
10
+ child.stdout.on('data', (chunk) => { output += chunk; });
11
+ child.stderr.resume();
12
+ child.on('error', () => reject(new CliError('CONFIGURATION', 'pnpm is unavailable.', 'Install a supported pnpm version and add it to PATH.')));
13
+ child.on('close', (code) => code === 0 ? resolve(output.trim()) : reject(new CliError('CONFIGURATION', 'pnpm failed.', 'Repair the pnpm installation.')));
14
+ });
15
+ }
16
+ // The registry pnpm resolves @tulcn packages from: the scope setting when there is one, otherwise the default registry
17
+ async function packageRegistry(signal) {
18
+ const web = (value) => /^https?:\/\//i.test(value) ? value : '';
19
+ const value = web(await pnpm(['config', 'get', '@tulcn:registry'], signal)) || web(await pnpm(['config', 'get', 'registry'], signal));
20
+ if (!value)
21
+ throw new CliError('CONFIGURATION', 'pnpm has no package registry configured.', 'Run pnpm config get registry and repair the registry setting.');
22
+ return new URL(value.endsWith('/') ? value : value + '/');
23
+ }
24
+ export const doctor = {
25
+ description: 'Check runtime, package registry, authorization service and local session without logging in', effects: 'none',
26
+ parameters: { 'client-id': { type: 'string', description: 'Client ID to check; defaults to LXZ_AUTH_CLIENT_ID' } },
27
+ examples: ['pnpm dlx @tulcn/lxz doctor --json --non-interactive', 'pnpm dlx @tulcn/lxz doctor --client-id crm-demo1 --json --non-interactive'], result: { type: 'object', required: ['checks', 'healthy'] },
28
+ async run(input, context) {
29
+ const clientId = typeof input['client-id'] === 'string' ? input['client-id'] : undefined;
30
+ const checks = {};
31
+ let healthy = true;
32
+ const check = async (name, fn) => {
33
+ try {
34
+ checks[name] = { status: 'ready', data: await fn() };
35
+ }
36
+ catch (error) {
37
+ healthy = false;
38
+ checks[name] = { status: 'failed', error: failure(error) };
39
+ }
40
+ };
41
+ await Promise.all([
42
+ check('runtime', async () => checkRuntimeVersions(process.versions.node, await pnpm(['--version'], context.signal))),
43
+ check('registry', async () => {
44
+ const registry = await packageRegistry(context.signal);
45
+ const response = await request(new URL('@tulcn%2flxz', registry), { headers: { accept: 'application/vnd.npm.install-v1+json' }, signal: context.signal });
46
+ await response.body?.cancel();
47
+ if (response.status === 401 || response.status === 403)
48
+ return { registry: registry.href, reachable: true, packageAccessVerified: false, next: `Configure credentials for ${registry.href}, or point @tulcn:registry at a registry that serves @tulcn packages.` };
49
+ if (response.status === 404)
50
+ throw new CliError('CONFIGURATION', `${registry.href} does not serve @tulcn/lxz.`, 'Point @tulcn:registry at a registry that serves @tulcn packages, or remove the setting to use the default registry.');
51
+ if (!response.ok)
52
+ throw new CliError('CONFIGURATION', 'Package registry check failed.', 'Check the network, the @tulcn:registry setting and registry credentials; packages are fetched before the CLI starts.');
53
+ return { registry: registry.href, reachable: true, packageAccessVerified: true };
54
+ }),
55
+ check('authorization', async () => {
56
+ const identity = defaultIdentity(clientId);
57
+ if (!identity.inspect)
58
+ throw new CliError('CONFIGURATION', 'The selected authorization module has no service diagnostics.', 'Ask the CLI maintainer to add diagnostics for the enabled authorization module.');
59
+ return identity.inspect(context.signal);
60
+ }),
61
+ check('identity', async () => {
62
+ const state = await defaultIdentity(clientId).status(context.signal);
63
+ if (!state)
64
+ throw new CliError('AUTH_REQUIRED', 'The selected CLI has no local authorization.', 'Run the CLI init command, or pnpm dlx @tulcn/lxz auth login --client-id <client-id>.');
65
+ return { ...state, validity: 'local-only', next: 'Run the business CLI init or a business command; the gateway checks the token and connects the business service.' };
66
+ }),
67
+ ]);
68
+ if (!healthy)
69
+ throw new CliError('CONFIGURATION', 'Some environment checks failed.', 'Follow the recovery instructions for each failed check.', false, { healthy, checks });
70
+ return { healthy, checks };
71
+ },
72
+ };
@@ -0,0 +1,6 @@
1
+ import type { MainRequest } from './protocol.js';
2
+ export declare function callMain<T>(request: MainRequest, { signal, env, log }: {
3
+ signal: AbortSignal;
4
+ env?: NodeJS.ProcessEnv;
5
+ log?: (message: string) => void;
6
+ }): Promise<T>;
@@ -0,0 +1,51 @@
1
+ import { fork } from 'node:child_process';
2
+ import { CliError, failure } from '../cli/errors.js';
3
+ export function callMain(request, { signal, env = process.env, log }) {
4
+ signal.throwIfAborted();
5
+ return new Promise((resolve, reject) => {
6
+ const child = fork(new URL('../main.js', import.meta.url), ['--lxz-ipc'], {
7
+ env, execArgv: [], windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
8
+ });
9
+ let ready = false;
10
+ let result;
11
+ let killTimer;
12
+ const cancel = () => {
13
+ if (!ready) {
14
+ child.kill('SIGKILL');
15
+ return;
16
+ }
17
+ child.send({ operation: 'cancel', error: failure(signal.reason) }, () => { });
18
+ killTimer = setTimeout(() => child.kill('SIGKILL'), 30000);
19
+ };
20
+ signal.addEventListener('abort', cancel, { once: true });
21
+ child.on('message', (message) => {
22
+ if (message.type === 'ready') {
23
+ ready = true;
24
+ if (signal.aborted)
25
+ child.kill('SIGKILL');
26
+ else
27
+ child.send(request, (error) => { if (error)
28
+ child.kill('SIGKILL'); });
29
+ }
30
+ else if (message.type === 'log')
31
+ log?.(message.message);
32
+ else
33
+ result = message;
34
+ });
35
+ child.once('error', () => { });
36
+ child.once('close', () => {
37
+ signal.removeEventListener('abort', cancel);
38
+ clearTimeout(killTimer);
39
+ if (signal.aborted && !(request.operation === 'logout' && result?.ok))
40
+ reject(signal.reason);
41
+ else if (result?.ok)
42
+ resolve(result.data);
43
+ else if (result) {
44
+ const { code, message, next, retryable, details } = result.error;
45
+ reject(new CliError(code, message, next, retryable, details));
46
+ }
47
+ else
48
+ reject(new CliError('UNAVAILABLE', 'The lxz host could not complete the operation.', 'Reinstall the CLI dependencies and retry; if it still fails, ask the maintainer to check the lxz installation.'));
49
+ });
50
+ });
51
+ }
@@ -0,0 +1 @@
1
+ export declare function runMainHost(): void;
@@ -0,0 +1,50 @@
1
+ import { CliError, failure } from '../cli/errors.js';
2
+ import { executeAuthorization } from '../auth/host.js';
3
+ import { BundledSkill } from '../skills/delivery.js';
4
+ export function runMainHost() {
5
+ const controller = new AbortController();
6
+ const { signal } = controller;
7
+ const send = (message) => {
8
+ if (process.connected)
9
+ process.send(message, () => { });
10
+ };
11
+ const disconnected = () => controller.abort(new CliError('CANCELLED', 'The host call has ended.', 'Run the required command again.'));
12
+ const cancel = () => controller.abort(new CliError('CANCELLED', 'The host operation was cancelled.', 'Run the command again when needed.'));
13
+ process.once('disconnect', disconnected);
14
+ process.once('SIGINT', cancel);
15
+ process.once('SIGTERM', cancel);
16
+ let started = false;
17
+ process.on('message', async (request) => {
18
+ if (request.operation === 'cancel') {
19
+ const { code, message, next, retryable, details } = request.error;
20
+ controller.abort(new CliError(code, message, next, retryable, details));
21
+ }
22
+ else if (!started) {
23
+ started = true;
24
+ try {
25
+ const data = await execute(request);
26
+ send({ type: 'result', ok: true, data });
27
+ }
28
+ catch (error) {
29
+ send({ type: 'result', ok: false, error: failure(error) });
30
+ }
31
+ finally {
32
+ process.removeListener('disconnect', disconnected);
33
+ process.removeListener('SIGINT', cancel);
34
+ process.removeListener('SIGTERM', cancel);
35
+ if (process.connected)
36
+ process.disconnect();
37
+ }
38
+ }
39
+ });
40
+ send({ type: 'ready' });
41
+ async function execute(request) {
42
+ if ('root' in request) {
43
+ const skill = new BundledSkill(request.root, request.name);
44
+ return request.operation === 'skill.install'
45
+ ? skill.install(request.directory, request.conflict, signal)
46
+ : skill.sync(request.directory, request.conflict, signal);
47
+ }
48
+ return executeAuthorization(request, signal, (message) => send({ type: 'log', message }));
49
+ }
50
+ }
@@ -0,0 +1,27 @@
1
+ import type { AuthorizationRequest } from '../auth/protocol.js';
2
+ import type { failure } from '../cli/errors.js';
3
+ export type MainRequest = AuthorizationRequest | {
4
+ operation: 'skill.install' | 'skill.sync';
5
+ root: string;
6
+ name: string;
7
+ directory?: string;
8
+ conflict: 'error' | 'replace';
9
+ };
10
+ export type MainMessage = {
11
+ type: 'ready';
12
+ } | {
13
+ type: 'log';
14
+ message: string;
15
+ } | {
16
+ type: 'result';
17
+ ok: true;
18
+ data: unknown;
19
+ } | {
20
+ type: 'result';
21
+ ok: false;
22
+ error: ReturnType<typeof failure>;
23
+ };
24
+ export type MainCall = MainRequest | {
25
+ operation: 'cancel';
26
+ error: ReturnType<typeof failure>;
27
+ };
@@ -0,0 +1 @@
1
+ export {};
package/dist/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};