@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.
- package/README.md +63 -2
- package/dist/application.d.ts +2 -0
- package/dist/application.js +17 -0
- package/dist/auth/client.d.ts +5 -0
- package/dist/auth/client.js +14 -0
- package/dist/auth/gateway.d.ts +1 -0
- package/dist/auth/gateway.js +10 -0
- package/dist/auth/host.d.ts +2 -0
- package/dist/auth/host.js +16 -0
- package/dist/auth/identity.d.ts +45 -0
- package/dist/auth/identity.js +106 -0
- package/dist/auth/index.d.ts +9 -0
- package/dist/auth/index.js +12 -0
- package/dist/auth/inspection.d.ts +14 -0
- package/dist/auth/inspection.js +20 -0
- package/dist/auth/modules.d.ts +12 -0
- package/dist/auth/modules.js +25 -0
- package/dist/auth/protocol.d.ts +17 -0
- package/dist/auth/protocol.js +1 -0
- package/dist/auth/provider.d.ts +36 -0
- package/dist/auth/provider.js +166 -0
- package/dist/auth/response.d.ts +2 -0
- package/dist/auth/response.js +17 -0
- package/dist/auth/service.d.ts +5 -0
- package/dist/auth/service.js +71 -0
- package/dist/auth/store.d.ts +25 -0
- package/dist/auth/store.js +170 -0
- package/dist/cli/browser.d.ts +1 -0
- package/dist/cli/browser.js +11 -0
- package/dist/cli/contracts.d.ts +85 -0
- package/dist/cli/contracts.js +51 -0
- package/dist/cli/deployment.d.ts +5 -0
- package/dist/cli/deployment.js +23 -0
- package/dist/cli/device-login.d.ts +29 -0
- package/dist/cli/device-login.js +87 -0
- package/dist/cli/environment.d.ts +9 -0
- package/dist/cli/environment.js +19 -0
- package/dist/cli/errors.d.ts +30 -0
- package/dist/cli/errors.js +22 -0
- package/dist/cli/files.d.ts +6 -0
- package/dist/cli/files.js +71 -0
- package/dist/cli/http.d.ts +6 -0
- package/dist/cli/http.js +38 -0
- package/dist/cli/identity-commands.d.ts +3 -0
- package/dist/cli/identity-commands.js +56 -0
- package/dist/cli/index.d.ts +13 -0
- package/dist/cli/index.js +13 -0
- package/dist/cli/init.d.ts +205 -0
- package/dist/cli/init.js +77 -0
- package/dist/cli/modules.d.ts +6 -0
- package/dist/cli/modules.js +18 -0
- package/dist/cli/output.d.ts +2 -0
- package/dist/cli/output.js +35 -0
- package/dist/cli/prompts.d.ts +34 -0
- package/dist/cli/prompts.js +58 -0
- package/dist/cli/runtime.d.ts +2 -0
- package/dist/cli/runtime.js +137 -0
- package/dist/cli/schemas.d.ts +187 -0
- package/dist/cli/schemas.js +46 -0
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.js +72 -0
- package/dist/internal/client.d.ts +6 -0
- package/dist/internal/client.js +51 -0
- package/dist/internal/host.d.ts +1 -0
- package/dist/internal/host.js +50 -0
- package/dist/internal/protocol.d.ts +27 -0
- package/dist/internal/protocol.js +1 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +12 -0
- package/dist/skills/agents.d.ts +7 -0
- package/dist/skills/agents.js +11 -0
- package/dist/skills/artifacts.d.ts +9 -0
- package/dist/skills/artifacts.js +12 -0
- package/dist/skills/bundle.d.ts +22 -0
- package/dist/skills/bundle.js +77 -0
- package/dist/skills/client.d.ts +5 -0
- package/dist/skills/client.js +9 -0
- package/dist/skills/commands.d.ts +5 -0
- package/dist/skills/commands.js +20 -0
- package/dist/skills/delivery.d.ts +60 -0
- package/dist/skills/delivery.js +89 -0
- package/dist/skills/index.d.ts +7 -0
- package/dist/skills/index.js +7 -0
- package/dist/skills/installer.d.ts +23 -0
- package/dist/skills/installer.js +130 -0
- package/dist/skills/paths.d.ts +2 -0
- package/dist/skills/paths.js +28 -0
- package/package.json +36 -3
- package/scripts/install.mjs +17 -0
- package/skills/SKILL.md +38 -0
- package/skills/bundle.json +7 -0
- package/skills/commands.md +440 -0
- package/skills/features.md +12 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { CliError } from '../cli/index.js';
|
|
2
|
+
export function backendError(response, data, secrets = []) {
|
|
3
|
+
const categories = { invalid_client: 'CONFIGURATION', invalid_request: 'INVALID_INPUT', unsupported_grant_type: 'CONFIGURATION', invalid_grant: 'AUTH_EXPIRED', expired_token: 'AUTH_EXPIRED', access_denied: 'ACCESS_DENIED', temporarily_unavailable: 'UNAVAILABLE', server_error: 'UNAVAILABLE' };
|
|
4
|
+
const statuses = { 400: 'INVALID_INPUT', 401: 'AUTH_EXPIRED', 403: 'ACCESS_DENIED', 404: 'INVALID_INPUT', 409: 'CONFLICT', 413: 'INVALID_INPUT', 422: 'INVALID_INPUT' };
|
|
5
|
+
const code = categories[String(data.error)] ?? statuses[response.status] ?? 'UNAVAILABLE';
|
|
6
|
+
const redact = (value) => secrets.filter(Boolean).reduce((result, secret) => result.replaceAll(secret, '[REDACTED]'), value).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
|
7
|
+
const message = typeof data.error_description === 'string' ? data.error_description : typeof data.msg === 'string' ? data.msg : 'Service request failed.';
|
|
8
|
+
const requestId = response.headers.get('x-request-id');
|
|
9
|
+
const recovery = {
|
|
10
|
+
AUTH_EXPIRED: 'Run this CLI init command and approve authorization.',
|
|
11
|
+
ACCESS_DENIED: 'Ask the administrator to grant access to this CLI or business service.',
|
|
12
|
+
CONFIGURATION: 'Check the service URL and client ID; if correct, ask the administrator to enable this CLI.',
|
|
13
|
+
INVALID_INPUT: 'Check the request input and the service message, then retry.',
|
|
14
|
+
CONFLICT: 'Check the current target and resolve the conflict before submitting again.',
|
|
15
|
+
};
|
|
16
|
+
return new CliError(code, redact(message), recovery[code] ?? 'Check the network and service status, then retry.', response.status >= 500 || response.status === 429, requestId ? { requestId: redact(requestId) } : undefined);
|
|
17
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { IdentityPort } from '../cli/index.js';
|
|
2
|
+
export declare function serviceJson(identity: IdentityPort, input: string | URL, signal: AbortSignal): Promise<Record<string, unknown>>;
|
|
3
|
+
export declare function serviceRequest(identity: IdentityPort, send: (token: string) => Promise<Response>, signal: AbortSignal, { replay }?: {
|
|
4
|
+
replay?: boolean | undefined;
|
|
5
|
+
}): Promise<Response>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { CliError, readJson, request, secureUrl } from '../cli/index.js';
|
|
4
|
+
import { backendError } from './response.js';
|
|
5
|
+
export async function serviceJson(identity, input, signal) {
|
|
6
|
+
const url = secureUrl(String(input), 'Business service URL', { allowHttp: true, allowQuery: true });
|
|
7
|
+
return readJson(await serviceRequest(identity, token => request(url, { headers: { authorization: `Bearer ${token}`, 'x-request-id': randomUUID() }, signal }), signal));
|
|
8
|
+
}
|
|
9
|
+
export async function serviceRequest(identity, send, signal, { replay = true } = {}) {
|
|
10
|
+
let credential = await identity.credential(signal);
|
|
11
|
+
const sendWithRetry = async () => {
|
|
12
|
+
for (let attempt = 0;; attempt++) {
|
|
13
|
+
signal.throwIfAborted();
|
|
14
|
+
try {
|
|
15
|
+
const response = await send(credential.token);
|
|
16
|
+
if (!replay || attempt === 2 || (response.status !== 429 && response.status < 500))
|
|
17
|
+
return response;
|
|
18
|
+
await response.body?.cancel();
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
signal.throwIfAborted();
|
|
22
|
+
if (!replay || attempt === 2 || !(error instanceof CliError && ['UNAVAILABLE', 'TIMEOUT'].includes(error.code)))
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
await delay(2000, undefined, { signal });
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
signal.throwIfAborted();
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
let response = await sendWithRetry();
|
|
35
|
+
if (response.status === 401) {
|
|
36
|
+
const requestId = response.headers.get('x-request-id');
|
|
37
|
+
const rejectedByGateway = /^Bearer\s+error="invalid_token"$/i.test(response.headers.get('www-authenticate') ?? '');
|
|
38
|
+
await response.body?.cancel();
|
|
39
|
+
credential = await identity.credential(signal, { forceRefresh: true, rejectedToken: credential.token });
|
|
40
|
+
if (!replay && !rejectedByGateway)
|
|
41
|
+
throw new CliError('UNAVAILABLE', 'Credentials were renewed; this operation was not replayed.', 'Check the actual outcome before deciding whether to submit again.', false, { status: 401, requestId, credentialRenewed: true, executed: 'unknown' });
|
|
42
|
+
response = await sendWithRetry();
|
|
43
|
+
}
|
|
44
|
+
if (response.status === 401) {
|
|
45
|
+
const requestId = response.headers.get('x-request-id');
|
|
46
|
+
await response.body?.cancel();
|
|
47
|
+
await identity.invalidate?.(signal, credential.token);
|
|
48
|
+
throw new CliError('AUTH_EXPIRED', 'The current session cannot access this business service.', 'Run init to authorize again. If access still fails, ask the administrator to check the CLI gateway route and permissions.', false, requestId ? { requestId } : undefined);
|
|
49
|
+
}
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
let data = {};
|
|
52
|
+
try {
|
|
53
|
+
data = await readJson(response);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
signal.throwIfAborted();
|
|
57
|
+
}
|
|
58
|
+
throw typeof data.msg !== 'string' && [502, 503, 504].includes(response.status) ? gatewayFailure(response, replay) : backendError(response, data, [credential.token]);
|
|
59
|
+
}
|
|
60
|
+
return response;
|
|
61
|
+
}
|
|
62
|
+
// Without the backend's msg, these statuses come from the gateway: the backend is down, unreachable or too slow.
|
|
63
|
+
// details.executed records what is known about the outcome; next already tells the caller what to do about it.
|
|
64
|
+
function gatewayFailure(response, replay) {
|
|
65
|
+
const requestId = response.headers.get('x-request-id');
|
|
66
|
+
const details = { status: response.status, ...(requestId ? { requestId } : {}) };
|
|
67
|
+
if (response.status === 504) {
|
|
68
|
+
return new CliError('UNAVAILABLE', 'The business service did not answer in time (HTTP 504); the request may still have completed.', replay ? 'Retry later.' : 'Check the actual outcome first, for example with a query, before submitting again, so the operation is not repeated.', replay, { ...details, executed: 'unknown' });
|
|
69
|
+
}
|
|
70
|
+
return new CliError('UNAVAILABLE', `The business service is not reachable (HTTP ${response.status}). This is a server problem, not a problem with the input.`, 'Nothing was changed. Retry later; if it keeps failing, tell the CLI maintainer that the business backend is down or unreachable.', true, { ...details, executed: false });
|
|
71
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { TokenSet } from './provider.js';
|
|
2
|
+
export interface Session extends TokenSet {
|
|
3
|
+
version: 2;
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
clientId: string;
|
|
6
|
+
}
|
|
7
|
+
export interface SessionStore {
|
|
8
|
+
transaction<T>(signal: AbortSignal, action: (store: SessionAccess) => Promise<T>): Promise<T>;
|
|
9
|
+
}
|
|
10
|
+
export interface SessionAccess {
|
|
11
|
+
read(): Promise<Session | null>;
|
|
12
|
+
/** Completes an atomic commit even if cancellation arrives after token rotation. */
|
|
13
|
+
write(session: Session): Promise<void>;
|
|
14
|
+
clear(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
export declare class FileSessionStore implements SessionStore {
|
|
17
|
+
readonly directory: string;
|
|
18
|
+
readonly file: string;
|
|
19
|
+
constructor(context: string, directory?: string);
|
|
20
|
+
deviceId(signal: AbortSignal): Promise<string>;
|
|
21
|
+
transaction<T>(signal: AbortSignal, action: (store: SessionAccess) => Promise<T>): Promise<T>;
|
|
22
|
+
private recoverLock;
|
|
23
|
+
private read;
|
|
24
|
+
private write;
|
|
25
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile, rename, rm, lstat } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
|
+
import { CliError } from '../cli/index.js';
|
|
8
|
+
function protect(input, decrypt, signal) {
|
|
9
|
+
const operation = decrypt ? 'Unprotect' : 'Protect';
|
|
10
|
+
const script = `Add-Type -AssemblyName System.Security; $data=[Convert]::FromBase64String([Console]::In.ReadToEnd()); $result=[Security.Cryptography.ProtectedData]::${operation}($data,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Out.Write([Convert]::ToBase64String($result))`;
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'], timeout: 15000, signal });
|
|
13
|
+
let output = '';
|
|
14
|
+
child.stdout.setEncoding('utf8').on('data', (chunk) => { output += chunk; });
|
|
15
|
+
child.on('error', () => reject(signal?.aborted ? signal.reason : new CliError('IO_ERROR', 'System credential protection is unavailable.', 'Check Windows PowerShell and DPAPI.')));
|
|
16
|
+
child.on('close', (code) => code === 0 ? resolve(output.trim()) : reject(new CliError('IO_ERROR', 'Cannot protect or read local credentials.', 'Use the original OS account; authorize again if needed.')));
|
|
17
|
+
child.stdin.on('error', () => { });
|
|
18
|
+
child.stdin.end(input);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
export class FileSessionStore {
|
|
22
|
+
directory;
|
|
23
|
+
file;
|
|
24
|
+
constructor(context, directory = process.env.LXZ_STATE_DIR ?? join(homedir(), '.lianxz', 'identity')) {
|
|
25
|
+
this.directory = directory;
|
|
26
|
+
this.file = join(directory, `${createHash('sha256').update(context).digest('hex')}.json`);
|
|
27
|
+
}
|
|
28
|
+
deviceId(signal) {
|
|
29
|
+
return this.transaction(signal, async () => {
|
|
30
|
+
const file = this.file.replace(/\.json$/, '.device-id');
|
|
31
|
+
try {
|
|
32
|
+
return await readFile(file, 'utf8');
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error.code !== 'ENOENT')
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
const id = randomUUID();
|
|
39
|
+
await writeFile(file, id, { mode: 0o600, flag: 'wx' });
|
|
40
|
+
return id;
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
async transaction(signal, action) {
|
|
44
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
45
|
+
const stat = await lstat(this.directory);
|
|
46
|
+
if (stat.isSymbolicLink() || (process.platform !== 'win32' && (stat.mode & 0o077) !== 0))
|
|
47
|
+
throw new CliError('IO_ERROR', 'Session directory permissions are unsafe.', 'Use a private session directory owned by the current user with mode 0700.');
|
|
48
|
+
const lock = `${this.file}.lock`;
|
|
49
|
+
const deadline = Date.now() + 20000;
|
|
50
|
+
while (true) {
|
|
51
|
+
signal.throwIfAborted();
|
|
52
|
+
try {
|
|
53
|
+
await mkdir(lock, { mode: 0o700 });
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (error.code !== 'EEXIST')
|
|
58
|
+
throw new CliError('IO_ERROR', 'Cannot lock the session directory.', 'Check write permissions for the session directory.');
|
|
59
|
+
await this.recoverLock(lock);
|
|
60
|
+
if (Date.now() > deadline)
|
|
61
|
+
throw new CliError('UNAVAILABLE', 'Another process is using this CLI session.', 'Retry later. If the process crashed and the lock has no pid, ensure no CLI is running before removing its .lock directory.', true);
|
|
62
|
+
await delay(50, undefined, { signal });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
await writeFile(join(lock, 'pid'), String(process.pid), { mode: 0o600 });
|
|
67
|
+
signal.throwIfAborted();
|
|
68
|
+
return await action({
|
|
69
|
+
read: async () => { signal.throwIfAborted(); const session = await this.read(signal); signal.throwIfAborted(); return session; },
|
|
70
|
+
write: (session) => this.write(session),
|
|
71
|
+
clear: async () => { await rm(this.file, { force: true }); },
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
await rm(lock, { recursive: true, force: true });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
async recoverLock(lock) {
|
|
79
|
+
const recovery = `${lock}.recovery`;
|
|
80
|
+
try {
|
|
81
|
+
await mkdir(recovery);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
let pid = 0;
|
|
88
|
+
try {
|
|
89
|
+
pid = Number(await readFile(join(lock, 'pid'), 'utf8'));
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error.code === 'ENOENT') {
|
|
93
|
+
try {
|
|
94
|
+
if (Date.now() - (await lstat(lock)).mtimeMs > 30000)
|
|
95
|
+
await rm(lock, { recursive: true, force: true });
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error.code !== 'ENOENT')
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
105
|
+
return;
|
|
106
|
+
try {
|
|
107
|
+
process.kill(pid, 0);
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (error.code === 'ESRCH')
|
|
111
|
+
await rm(lock, { recursive: true, force: true });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
await rm(recovery, { recursive: true, force: true });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async read(signal) {
|
|
119
|
+
let raw;
|
|
120
|
+
try {
|
|
121
|
+
const stat = await lstat(this.file);
|
|
122
|
+
if (stat.isSymbolicLink() || (process.platform !== 'win32' && (stat.mode & 0o077) !== 0))
|
|
123
|
+
throw new CliError('IO_ERROR', 'Session file permissions are unsafe.', 'Set session file permissions to 0600.');
|
|
124
|
+
raw = await readFile(this.file, 'utf8');
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
if (error.code === 'ENOENT')
|
|
128
|
+
return null;
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const record = JSON.parse(raw);
|
|
133
|
+
if (record.version !== 2)
|
|
134
|
+
throw new CliError('INCOMPATIBLE', 'Unsupported local session format.', 'Run this CLI logout command to clear the session, then authorize again.');
|
|
135
|
+
if (record.protection === 'dpapi')
|
|
136
|
+
raw = Buffer.from(await protect(record.data, true, signal), 'base64').toString('utf8');
|
|
137
|
+
else if (record.protection === 'user-file' && process.platform !== 'win32')
|
|
138
|
+
raw = record.data;
|
|
139
|
+
else
|
|
140
|
+
throw new Error('protection');
|
|
141
|
+
const session = JSON.parse(raw);
|
|
142
|
+
session.accessExpiresAt = session.accessTokenExpiresAt;
|
|
143
|
+
session.refreshExpiresAt = session.refreshTokenExpiresAt;
|
|
144
|
+
delete session.accessTokenExpiresAt;
|
|
145
|
+
delete session.refreshTokenExpiresAt;
|
|
146
|
+
if (session.version !== 2 || ['refreshToken', 'accessToken', 'baseUrl', 'clientId'].some((key) => typeof session[key] !== 'string') || (session.account !== undefined && typeof session.account !== 'string') || !Number.isFinite(session.accessExpiresAt) || !Number.isFinite(session.refreshExpiresAt))
|
|
147
|
+
throw new Error('session');
|
|
148
|
+
return session;
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
signal.throwIfAborted();
|
|
152
|
+
if (error instanceof CliError)
|
|
153
|
+
throw error;
|
|
154
|
+
throw new CliError('IO_ERROR', 'Local session is damaged or cannot be decrypted.', 'Run this CLI logout command to clear local tokens, then authorize again.');
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
async write(session) {
|
|
158
|
+
const { accessExpiresAt, refreshExpiresAt, ...rest } = session;
|
|
159
|
+
const plain = JSON.stringify({ ...rest, accessTokenExpiresAt: accessExpiresAt, refreshTokenExpiresAt: refreshExpiresAt });
|
|
160
|
+
const data = process.platform === 'win32' ? await protect(Buffer.from(plain).toString('base64'), false) : plain;
|
|
161
|
+
const temporary = `${this.file}.${randomUUID()}.tmp`;
|
|
162
|
+
try {
|
|
163
|
+
await writeFile(temporary, JSON.stringify({ version: 2, protection: process.platform === 'win32' ? 'dpapi' : 'user-file', data }), { mode: 0o600, flag: 'wx' });
|
|
164
|
+
await rename(temporary, this.file);
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
await rm(temporary, { force: true });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function openBrowser(url: string, signal: AbortSignal): Promise<boolean>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
export async function openBrowser(url, signal) {
|
|
3
|
+
signal.throwIfAborted();
|
|
4
|
+
const [command, args] = process.platform === 'win32' ? ['rundll32.exe', ['url.dll,FileProtocolHandler', url]]
|
|
5
|
+
: process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
|
|
6
|
+
return new Promise((resolve) => {
|
|
7
|
+
const child = spawn(command, args, { windowsHide: true, stdio: 'ignore', timeout: 10000, signal });
|
|
8
|
+
child.on('error', () => resolve(false));
|
|
9
|
+
child.on('close', (code) => resolve(code === 0));
|
|
10
|
+
});
|
|
11
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { ArgDef } from 'citty';
|
|
2
|
+
export declare const contractVersion = "1.0.0";
|
|
3
|
+
export interface Parameter {
|
|
4
|
+
type: 'string' | 'boolean';
|
|
5
|
+
description: string;
|
|
6
|
+
required?: boolean;
|
|
7
|
+
default?: string | boolean;
|
|
8
|
+
choices?: string[];
|
|
9
|
+
pattern?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface Command {
|
|
12
|
+
module?: string;
|
|
13
|
+
description: string;
|
|
14
|
+
parameters?: Record<string, Parameter>;
|
|
15
|
+
result: Record<string, unknown>;
|
|
16
|
+
examples: string[];
|
|
17
|
+
effects: 'none' | 'local' | 'remote';
|
|
18
|
+
preview?: boolean;
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
interactiveTimeout?: 'idle' | 'total';
|
|
21
|
+
format?: (result: unknown) => string;
|
|
22
|
+
run: (input: Record<string, string | boolean>, context: Context) => unknown | Promise<unknown>;
|
|
23
|
+
}
|
|
24
|
+
export interface Context {
|
|
25
|
+
interactive: boolean;
|
|
26
|
+
allowDeviceLogin?: boolean;
|
|
27
|
+
browser?: boolean;
|
|
28
|
+
/** Arguments of this invocation, used to continue it in a background process. */
|
|
29
|
+
argv?: string[];
|
|
30
|
+
signal: AbortSignal;
|
|
31
|
+
log: (message: string) => void;
|
|
32
|
+
}
|
|
33
|
+
export interface Application {
|
|
34
|
+
name: string;
|
|
35
|
+
packageName: string;
|
|
36
|
+
version: string;
|
|
37
|
+
description: string;
|
|
38
|
+
defaultCommand?: string;
|
|
39
|
+
commands: Record<string, Command>;
|
|
40
|
+
}
|
|
41
|
+
export declare const commonParameters: Record<string, Parameter>;
|
|
42
|
+
export declare function commandParameters(command?: Command): {
|
|
43
|
+
'timeout-ms'?: {
|
|
44
|
+
description: string;
|
|
45
|
+
default?: string | boolean;
|
|
46
|
+
type: "string" | "boolean";
|
|
47
|
+
required?: boolean;
|
|
48
|
+
choices?: string[];
|
|
49
|
+
pattern?: string;
|
|
50
|
+
} | undefined;
|
|
51
|
+
};
|
|
52
|
+
export declare function argumentDefinitions(parameters: Record<string, Parameter>): Record<string, ArgDef>;
|
|
53
|
+
export declare function describe(app: Application, scope?: string): {
|
|
54
|
+
contractVersion: string;
|
|
55
|
+
name: string;
|
|
56
|
+
packageName: string;
|
|
57
|
+
version: string;
|
|
58
|
+
description: string;
|
|
59
|
+
commands: {
|
|
60
|
+
[k: string]: {
|
|
61
|
+
description: string;
|
|
62
|
+
effects: "none" | "local" | "remote";
|
|
63
|
+
preview: boolean;
|
|
64
|
+
examples: string[];
|
|
65
|
+
input: {
|
|
66
|
+
type: string;
|
|
67
|
+
additionalProperties: boolean;
|
|
68
|
+
properties: {
|
|
69
|
+
[k: string]: {
|
|
70
|
+
pattern?: string | undefined;
|
|
71
|
+
enum?: string[] | undefined;
|
|
72
|
+
default?: string | boolean | undefined;
|
|
73
|
+
type: "string" | "boolean";
|
|
74
|
+
description: string;
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
required: string[];
|
|
78
|
+
};
|
|
79
|
+
result: Record<string, unknown>;
|
|
80
|
+
module?: string | undefined;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
export declare function commandReference(app: Application): string;
|
|
85
|
+
export declare function shellCommandExamples(pwsh: string, bash?: string): string;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export const contractVersion = '1.0.0';
|
|
2
|
+
export const commonParameters = {
|
|
3
|
+
json: { type: 'boolean', description: 'Return a JSON receipt instead of compact rows; use for programmatic parsing', default: false },
|
|
4
|
+
'non-interactive': { type: 'boolean', description: 'Use command parameters without interactive prompts', default: false },
|
|
5
|
+
'timeout-ms': { type: 'string', description: 'Non-interactive deadline in ms (1-3600000); interactive prompts exit after 60 seconds without input', default: '120000', pattern: '^(?:[1-9][0-9]{0,5}|[12][0-9]{6}|3[0-5][0-9]{5}|3600000)$' },
|
|
6
|
+
help: { type: 'boolean', description: 'Show help for this command or group; same as -h' },
|
|
7
|
+
version: { type: 'boolean', description: 'Show version' },
|
|
8
|
+
schema: { type: 'boolean', description: 'Show command, input and result schemas' },
|
|
9
|
+
};
|
|
10
|
+
export function commandParameters(command) {
|
|
11
|
+
return { ...commonParameters, ...(command?.timeoutMs || command?.interactiveTimeout === 'total' ? { 'timeout-ms': {
|
|
12
|
+
...commonParameters['timeout-ms'],
|
|
13
|
+
...(command.timeoutMs ? { default: String(command.timeoutMs) } : {}),
|
|
14
|
+
...(command.interactiveTimeout === 'total' ? { description: 'Total deadline in ms (1-3600000), including approval waits; keyboard inactivity does not end authorization' } : {}),
|
|
15
|
+
} } : {}), ...command?.parameters };
|
|
16
|
+
}
|
|
17
|
+
export function argumentDefinitions(parameters) {
|
|
18
|
+
return Object.fromEntries(Object.entries(parameters).map(([key, { choices, pattern, ...definition }]) => [key, definition]));
|
|
19
|
+
}
|
|
20
|
+
export function describe(app, scope) {
|
|
21
|
+
return {
|
|
22
|
+
contractVersion, name: app.name, packageName: app.packageName, version: app.version,
|
|
23
|
+
description: app.description,
|
|
24
|
+
commands: Object.fromEntries(Object.entries(app.commands).filter(([name]) => !scope || name === scope || name.startsWith(scope + ' ')).map(([name, command]) => [name, {
|
|
25
|
+
...(command.module ? { module: command.module } : {}),
|
|
26
|
+
description: command.description, effects: command.effects, preview: command.preview ?? false,
|
|
27
|
+
examples: command.examples,
|
|
28
|
+
input: {
|
|
29
|
+
type: 'object', additionalProperties: false,
|
|
30
|
+
properties: Object.fromEntries(Object.entries(commandParameters(command)).map(([name, { description, type, default: value, choices, pattern }]) => [name, {
|
|
31
|
+
type, description, ...(value === undefined ? {} : { default: value }), ...(choices ? { enum: choices } : {}), ...(pattern ? { pattern } : {}),
|
|
32
|
+
}])),
|
|
33
|
+
required: Object.entries(command.parameters ?? {}).filter(([, p]) => p.required).map(([name]) => name),
|
|
34
|
+
},
|
|
35
|
+
result: command.result,
|
|
36
|
+
}])),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export function commandReference(app) {
|
|
40
|
+
return Object.entries(describe(app).commands).map(([name, command]) => [
|
|
41
|
+
`### ${app.name} ${name}`, command.description, `Effects: ${command.effects}; Preview: ${command.preview}.`,
|
|
42
|
+
...Object.entries(command.input.properties).map(([key, value]) => `- --${key} (${value.type}): ${value.description}${'default' in value ? `; default ${JSON.stringify(value.default)}` : ''}${command.input.required.includes(key) ? '; required' : ''}${'enum' in value ? `; choices ${JSON.stringify(value.enum)}` : ''}`),
|
|
43
|
+
`Result schema:\n\n\`\`\`json\n${JSON.stringify(command.result, null, 2)}\n\`\`\``,
|
|
44
|
+
...command.examples.map((example) => shellCommandExamples(example)),
|
|
45
|
+
].join('\n\n')).join('\n\n');
|
|
46
|
+
}
|
|
47
|
+
export function shellCommandExamples(pwsh, bash = pwsh) {
|
|
48
|
+
if (pwsh === bash)
|
|
49
|
+
return `**pwsh / bash**\n\n\`\`\`sh\n${pwsh}\n\`\`\``;
|
|
50
|
+
return `**pwsh**\n\n\`\`\`pwsh\n${pwsh}\n\`\`\`\n\n**bash**\n\n\`\`\`bash\n${bash}\n\`\`\``;
|
|
51
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const deploymentDefaults: {
|
|
2
|
+
LINKWISE_ISSUER: string;
|
|
3
|
+
};
|
|
4
|
+
/** Fixes the authorization server for this process and the lxz processes it starts: environment, then the file a test build ships with, then production. */
|
|
5
|
+
export declare function applyDeployment(packageRoot: URL, env?: NodeJS.ProcessEnv): void;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
export const deploymentDefaults = {
|
|
3
|
+
LINKWISE_ISSUER: 'https://ai-cli.tul.cn/linkwise-api',
|
|
4
|
+
};
|
|
5
|
+
function packagedIssuer(packageRoot) {
|
|
6
|
+
let text;
|
|
7
|
+
try {
|
|
8
|
+
text = readFileSync(new URL('linkwise.env.json', packageRoot), 'utf8');
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
if (error.code === 'ENOENT')
|
|
12
|
+
return undefined;
|
|
13
|
+
throw error;
|
|
14
|
+
}
|
|
15
|
+
const value = JSON.parse(text).LINKWISE_ISSUER;
|
|
16
|
+
if (typeof value !== 'string' || !value)
|
|
17
|
+
throw new Error('linkwise.env.json must set LINKWISE_ISSUER.');
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
/** Fixes the authorization server for this process and the lxz processes it starts: environment, then the file a test build ships with, then production. */
|
|
21
|
+
export function applyDeployment(packageRoot, env = process.env) {
|
|
22
|
+
env.LINKWISE_ISSUER ??= packagedIssuer(packageRoot) ?? deploymentDefaults.LINKWISE_ISSUER;
|
|
23
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Context, Parameter } from './contracts.js';
|
|
2
|
+
export interface AuthorizationLink {
|
|
3
|
+
authorizationUrl: string;
|
|
4
|
+
userCode: string;
|
|
5
|
+
browserOpened: boolean;
|
|
6
|
+
log: string;
|
|
7
|
+
}
|
|
8
|
+
export declare const authorizationPrompt: (url: string, code: string) => string;
|
|
9
|
+
export declare const statusWaitLimitSeconds = 170;
|
|
10
|
+
export declare const waitParameter: Parameter;
|
|
11
|
+
export declare const pendingProperties: {
|
|
12
|
+
authorizationUrl: {
|
|
13
|
+
type: string;
|
|
14
|
+
};
|
|
15
|
+
userCode: {
|
|
16
|
+
type: string;
|
|
17
|
+
};
|
|
18
|
+
browserOpened: {
|
|
19
|
+
type: string;
|
|
20
|
+
description: string;
|
|
21
|
+
};
|
|
22
|
+
log: {
|
|
23
|
+
type: string;
|
|
24
|
+
description: string;
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
export declare function waitsInBackground(input: Record<string, string | boolean>, context: Context): boolean;
|
|
28
|
+
export declare function approvalNext(link: AuthorizationLink, status: string): string;
|
|
29
|
+
export declare function deviceLoginInBackground(input: Record<string, string | boolean>, context: Context, pending: (link: AuthorizationLink) => unknown, entry?: string): Promise<unknown>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { closeSync, mkdtempSync, openSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { openBrowser } from './browser.js';
|
|
7
|
+
import { CliError } from './errors.js';
|
|
8
|
+
const urlLabel = 'Authorization URL: ', codeLabel = 'User code: ';
|
|
9
|
+
export const authorizationPrompt = (url, code) => `${urlLabel}${url}\n${codeLabel}${code}`;
|
|
10
|
+
const labelled = (text, label) => text.split(/\r?\n/).find(line => line.startsWith(label))?.slice(label.length).trim();
|
|
11
|
+
export const statusWaitLimitSeconds = 170;
|
|
12
|
+
const linkDeadlineMs = 30000;
|
|
13
|
+
// An approval that is already done, or an issuer that approves at once, still finishes in the foreground.
|
|
14
|
+
const graceMs = 3000;
|
|
15
|
+
export const waitParameter = { type: 'boolean', description: 'With --device-login in non-interactive mode, wait for approval in the foreground instead of returning the link at once', default: false };
|
|
16
|
+
export const pendingProperties = {
|
|
17
|
+
authorizationUrl: { type: 'string' }, userCode: { type: 'string' },
|
|
18
|
+
browserOpened: { type: 'boolean', description: 'This command opened the authorization page in the system browser' },
|
|
19
|
+
log: { type: 'string', description: 'Log of the background process that waits for approval' },
|
|
20
|
+
};
|
|
21
|
+
export function waitsInBackground(input, context) {
|
|
22
|
+
return Boolean(input['device-login'] && !context.interactive && !input.wait && context.argv);
|
|
23
|
+
}
|
|
24
|
+
export function approvalNext(link, status) {
|
|
25
|
+
return (link.browserOpened
|
|
26
|
+
? 'The authorization page is open in the system browser on this computer. Tell the user to switch to the browser, check that it shows userCode and approve; also give the link and userCode in your reply in case the page did not appear. '
|
|
27
|
+
: 'Give the link and userCode in your reply and ask the user to open the link in the system browser, check userCode and approve. ')
|
|
28
|
+
+ 'Write authorizationUrl unchanged as a Markdown link on a line of its own, for example [Open the authorization page](authorizationUrl) with the label in the user\'s language; never as a bare URL, and with no text or punctuation right after it, because chat clients treat following characters as part of the URL. Write userCode on a line of its own. '
|
|
29
|
+
+ 'In Linkwise a clicked link opens in the built-in browser, so tell the user to right-click it and choose to open it in the system browser. '
|
|
30
|
+
+ `Then, in the same turn and without waiting for the user to reply, run ${status} --wait-seconds ${statusWaitLimitSeconds} --json --non-interactive; it returns once the user approves, and you continue the user's original task. Do not run init or login again while this link is valid.`;
|
|
31
|
+
}
|
|
32
|
+
function finalReceipt(text) {
|
|
33
|
+
for (const line of text.split(/\r?\n/).reverse()) {
|
|
34
|
+
if (!line.startsWith('{'))
|
|
35
|
+
continue;
|
|
36
|
+
let receipt;
|
|
37
|
+
try {
|
|
38
|
+
receipt = JSON.parse(line);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (receipt.ok)
|
|
44
|
+
return receipt.data;
|
|
45
|
+
const { code, message, next, retryable, details } = receipt.error;
|
|
46
|
+
throw new CliError(code, message, next, retryable, details);
|
|
47
|
+
}
|
|
48
|
+
throw new CliError('UNAVAILABLE', 'Background authorization stopped without a result.', 'Run the command again.');
|
|
49
|
+
}
|
|
50
|
+
// Agents that show output only after a command exits cannot show the link of a device login that waits.
|
|
51
|
+
// A detached copy of this command waits instead; this one opens the browser once and returns the link.
|
|
52
|
+
export async function deviceLoginInBackground(input, context, pending, entry = process.argv[1]) {
|
|
53
|
+
const log = join(mkdtempSync(join(tmpdir(), 'lxz-authorization-')), 'authorization.log');
|
|
54
|
+
const output = openSync(log, 'a');
|
|
55
|
+
let exited = false;
|
|
56
|
+
try {
|
|
57
|
+
const child = spawn(process.execPath, [...process.execArgv, entry, ...context.argv, '--wait', '--no-browser', '--non-interactive', '--json'], { detached: true, windowsHide: true, stdio: ['ignore', output, output] });
|
|
58
|
+
child.once('exit', () => { exited = true; });
|
|
59
|
+
child.once('error', () => { exited = true; });
|
|
60
|
+
child.unref();
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
closeSync(output);
|
|
64
|
+
}
|
|
65
|
+
const read = () => { try {
|
|
66
|
+
return readFileSync(log, 'utf8');
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return '';
|
|
70
|
+
} };
|
|
71
|
+
let seen = 0, browser;
|
|
72
|
+
for (const start = Date.now(); Date.now() - start < linkDeadlineMs;) {
|
|
73
|
+
await delay(200, undefined, { signal: context.signal });
|
|
74
|
+
const text = read();
|
|
75
|
+
if (exited)
|
|
76
|
+
return finalReceipt(text);
|
|
77
|
+
const authorizationUrl = labelled(text, urlLabel), userCode = labelled(text, codeLabel);
|
|
78
|
+
if (!authorizationUrl || !userCode)
|
|
79
|
+
continue;
|
|
80
|
+
seen ||= Date.now();
|
|
81
|
+
browser ??= input.browser === false ? Promise.resolve(false) : openBrowser(authorizationUrl, context.signal);
|
|
82
|
+
if (Date.now() - seen < graceMs)
|
|
83
|
+
continue;
|
|
84
|
+
return pending({ authorizationUrl, userCode, browserOpened: await browser, log });
|
|
85
|
+
}
|
|
86
|
+
throw new CliError('UNAVAILABLE', 'Could not get an authorization link in time.', `Check the network and run the command again; the background log is ${log}.`, true);
|
|
87
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { CliError } from './errors.js';
|
|
2
|
+
export const runtimeRequirements = { node: '22.12.0', pnpm: '12.16.1' };
|
|
3
|
+
function supported(version, minimum) {
|
|
4
|
+
const parsed = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(version);
|
|
5
|
+
if (!parsed)
|
|
6
|
+
return false;
|
|
7
|
+
const parts = parsed.slice(1).map(Number);
|
|
8
|
+
const required = minimum.split('.').map(Number);
|
|
9
|
+
for (let index = 0; index < required.length; index++) {
|
|
10
|
+
if (parts[index] !== required[index])
|
|
11
|
+
return parts[index] > required[index];
|
|
12
|
+
}
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
export function checkRuntimeVersions(node, pnpm) {
|
|
16
|
+
if (!supported(node, runtimeRequirements.node) || !supported(pnpm, runtimeRequirements.pnpm))
|
|
17
|
+
throw new CliError('CONFIGURATION', 'Unsupported Node.js or pnpm version.', `Install stable Node.js >=${runtimeRequirements.node} and pnpm >=${runtimeRequirements.pnpm}.`);
|
|
18
|
+
return { node, pnpm, supported: true };
|
|
19
|
+
}
|