@tulcn/lxz 0.3.0 → 0.4.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 CHANGED
@@ -7,7 +7,7 @@
7
7
  准备 Node.js >=22.12 和 pnpm 12。从 npm 官方源直接运行推荐版(`latest`),以下命令适用于 pwsh 和 bash:
8
8
 
9
9
  ```sh
10
- pnpm dlx @tulcn/lxz --version --json
10
+ pnpm dlx @tulcn/lxz --version
11
11
  pnpm dlx @tulcn/lxz --help
12
12
  ```
13
13
 
@@ -20,7 +20,7 @@ lxz --version
20
20
 
21
21
  安装输出提示 `Ignored build scripts`,或使用 `--ignore-scripts` 等不运行安装脚本的方式安装时,按下文“Agent 接入”运行 `install skill` 补装。
22
22
 
23
- 默认输出行数据;Agent 使用 `--non-interactive`,需要程序解析时加 `--json`,先解析 JSON 再读取字段。命令说明、帮助、提示和程序日志使用英文 ASCII;业务数据、用户输入及路径按 UTF-8 保留原文。`--json` 回执为纯 ASCII,中文等字符以 `\uXXXX` 转义,解析后与原文一致,PowerShell 可直接用 `ConvertFrom-Json` 解析。行数据按 UTF-8 解码;PowerShell 捕获行数据时,在当前会话先执行:
23
+ 普通命令、帮助和版本输出文本;Agent 使用 `--non-interactive`,失败时读取 stderr 和退出码。`lxz auth --schema --json` 返回授权分组的 JSON 契约。输出按 UTF-8 解码;PowerShell 捕获输出时,在当前会话先执行:
24
24
 
25
25
  ```powershell
26
26
  [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
@@ -30,14 +30,14 @@ lxz --version
30
30
 
31
31
  命令和分组都支持 `-h`(同 `--help`)。使用上面的调用前缀加 `auth -h`,列出授权子命令;加 `auth login -h`,查看登录参数与示例。通过帮助逐级查看当前版本的命令与参数。
32
32
 
33
- 默认使用正式授权中心 `https://ai-cli.tul.cn/linkwise-api`。先向管理员确认该环境中已登记且获准使用的 CLI 标识,把下面的 `<CLI 标识>` 替换为管理员分配的值。管理员要求连接其他授权环境时,在当前终端把 `LINKWISE_ISSUER` 设为管理员提供的地址;各环境的登记、授权和令牌互不通用。
33
+ 默认使用正式授权中心 `https://ai-cli.tul.cn/linkwise-api`。先向管理员确认该环境中已登记且获准使用的 CLI 标识,把下面的 `<CLI 标识>` 替换为管理员分配的值。管理员要求连接其他授权环境时,在当前终端把 `LINKWISE_ISSUER` 设为管理员提供的地址;各环境的登记、授权和令牌互不通用。授权中心域名连不上时,CLI 自动改用备用地址(正式为 `https://linkwise.tul.cn/cli`),并在命令行提示一行。
34
34
 
35
35
  登录时在浏览器核对验证码并允许授权;退出命令会撤销本次授权并删除本机登录信息。
36
36
 
37
37
  ```sh
38
38
  pnpm dlx @tulcn/lxz auth login --client-id '<CLI 标识>'
39
- pnpm dlx @tulcn/lxz auth status --client-id '<CLI 标识>' --json
40
- pnpm dlx @tulcn/lxz doctor --client-id '<CLI 标识>' --json
39
+ pnpm dlx @tulcn/lxz auth status --client-id '<CLI 标识>'
40
+ pnpm dlx @tulcn/lxz doctor --client-id '<CLI 标识>'
41
41
  pnpm dlx @tulcn/lxz auth logout --client-id '<CLI 标识>'
42
42
  ```
43
43
 
@@ -45,7 +45,7 @@ pnpm dlx @tulcn/lxz auth logout --client-id '<CLI 标识>'
45
45
 
46
46
  Agent 或脚本登录时加 `--device-login --non-interactive`,默认仍打开浏览器。命令拿到授权链接和用户码后立即返回 `status: pending`,由后台进程继续等待;把链接和用户码交给用户,再运行 `auth status --wait-seconds 170`(带同样的 `--client-id`),批准后立即返回。再加 `--no-browser` 时不打开浏览器,可在另一设备打开链接;需要原命令一直等到批准时加 `--wait`,默认最多 660 秒。
47
47
 
48
- `pnpm dlx @tulcn/lxz auth whoami --client-id '<CLI 标识>' --json` 显示本机保存的人员编号 `account`、登录名 `loginName`、显示名 `displayName` 及授权有效期。`clientId` 是 CLI 标识;后端未提供的身份字段不会补齐。本机有登录记录不代表已实时确认服务端权限。
48
+ `pnpm dlx @tulcn/lxz auth whoami --client-id '<CLI 标识>'` 显示本机保存的人员编号 `account`、登录名 `loginName`、显示名 `displayName` 及授权有效期。`clientId` 是 CLI 标识;身份字段按后端实际提供的内容显示。服务端在执行业务请求时校验权限。
49
49
 
50
50
  `doctor` 检查 Node.js 与 pnpm 版本、pnpm 为 `@tulcn` 包配置的源(未单独配置时为默认源)能否取到 `@tulcn/lxz`、授权服务和本机登录状态,不发起登录。
51
51
 
@@ -57,7 +57,7 @@ Agent 或脚本登录时加 `--device-login --non-interactive`,默认仍打开
57
57
  pnpm dlx @tulcn/lxz install skill --skills-dir '<Agent 的 Skills 根目录>'
58
58
  ```
59
59
 
60
- Skill 写入该目录下的 `lxz/`。安装目录优先使用 `--skills-dir`,其次为 `LXZ_SKILLS_DIR`,首次默认同时安装到 `~/.agents/skills` 和 `~/.linkwise/skills`。安装位置会登记,后续未指定目录时同步已登记的位置;`LXZ_SKILLS_STATE_DIR` 可指定登记记录的目录。
60
+ Skill 写入该目录下的 `lxz/`。安装目录优先使用 `--skills-dir`,其次为 `LXZ_SKILLS_DIR`,首次默认安装到 `~/.linkwise/skills`。安装位置会登记,后续未指定目录时同步已登记的位置;`LXZ_SKILLS_STATE_DIR` 可指定登记记录的目录。
61
61
 
62
62
  全局安装时,postinstall 在获准运行后自动安装 Skill;pnpm 默认会跳过它,其他包管理器或公司策略也可能跳过,请显式运行上述命令确认安装(已安装同一版本时不会重复写入)。本地修改引起冲突时先备份,再使用 `--skill-conflict replace` 替换。
63
63
 
@@ -4,14 +4,16 @@ import { identityCommands, registerCommandModules } from './cli/index.js';
4
4
  import { BundledSkill, skillCommands } from './skills/index.js';
5
5
  import { doctor } from './doctor.js';
6
6
  const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
7
- const commands = identityCommands((input) => defaultIdentity(typeof input['client-id'] === 'string' ? input['client-id'] : undefined), 'pnpm dlx @tulcn/lxz auth');
7
+ const output = { jsonOutput: 'schema' };
8
+ const commands = identityCommands((input) => defaultIdentity(typeof input['client-id'] === 'string' ? input['client-id'] : undefined), 'pnpm dlx @tulcn/lxz auth', output);
8
9
  for (const command of Object.values(commands))
9
10
  command.parameters = { ...command.parameters, 'client-id': { type: 'string', description: 'Client ID to manage; defaults to LXZ_AUTH_CLIENT_ID' } };
10
11
  export const application = {
11
12
  name: 'lxz', packageName: pkg.name, version: pkg.version, description: 'Linkwise CLI authorization and diagnostics',
13
+ ...output,
12
14
  commands: registerCommandModules([
13
15
  { id: 'authorization', commands: { ...Object.fromEntries(Object.entries(commands).map(([name, command]) => ['auth ' + name, command])), 'auth whoami': { ...commands.status, description: 'Show the local account authorized for this CLI' } } },
14
16
  { id: 'diagnostics', commands: { doctor } },
15
- { id: 'skill', commands: skillCommands(new BundledSkill(new URL('../', import.meta.url), 'lxz'), 'pnpm dlx @tulcn/lxz') },
17
+ { id: 'skill', commands: skillCommands(new BundledSkill(new URL('../', import.meta.url), 'lxz'), 'pnpm dlx @tulcn/lxz', output) },
16
18
  ]),
17
19
  };
@@ -3,6 +3,7 @@ export * from './store.js';
3
3
  export * from './identity.js';
4
4
  export * from './service.js';
5
5
  export * from './gateway.js';
6
+ export * from './platform.js';
6
7
  export * from './modules.js';
7
8
  export * from './inspection.js';
8
9
  export * from './client.js';
@@ -4,6 +4,7 @@ export * from './store.js';
4
4
  export * from './identity.js';
5
5
  export * from './service.js';
6
6
  export * from './gateway.js';
7
+ export * from './platform.js';
7
8
  export * from './modules.js';
8
9
  export * from './inspection.js';
9
10
  export * from './client.js';
@@ -1,8 +1,10 @@
1
1
  import { CliError, readJson, request } from '../cli/index.js';
2
2
  import { gatewayAddress } from './gateway.js';
3
+ import { platformExchange } from './platform.js';
3
4
  export async function inspectAuthorization(config, signal) {
4
- const business = gatewayAddress(config.clientId, { LINKWISE_ISSUER: config.baseUrl });
5
- const response = await request(business + '/', { signal });
5
+ const primary = gatewayAddress(config.clientId, { LINKWISE_ISSUER: config.baseUrl }) + '/';
6
+ const { response, url } = config.site ? await platformExchange(primary, { signal }, { site: config.site }) : { response: await request(primary, { signal }), url: primary };
7
+ const business = url.replace(/\/$/, '');
6
8
  const requestId = response.headers.get('x-request-id');
7
9
  const details = { status: response.status, ...(requestId ? { requestId } : {}) };
8
10
  let data = {};
@@ -0,0 +1,26 @@
1
+ /** Where the platform is reachable: the issuer origin first, then a fallback root serving the same paths. */
2
+ export interface PlatformSite {
3
+ roots: readonly string[];
4
+ stateDirectory?: string;
5
+ }
6
+ export declare function platformSite(env?: NodeJS.ProcessEnv): PlatformSite;
7
+ /** The path of target under the root that reference was sent to. */
8
+ export declare function atRootOf(target: string, reference: string, site: PlatformSite): string;
9
+ /**
10
+ * Sends a request to the platform. When a root cannot be reached (no connection, or HTTP 502/504 from a proxy) the request is sent
11
+ * at the other root; a request that may already have been delivered (lost connection, 504) only when replay is allowed.
12
+ * Once the fallback answers for an unreachable primary, it goes first for 10 minutes and log is told. URLs outside the platform are sent as they are.
13
+ */
14
+ export declare function platformExchange(url: string | URL, init: RequestInit, { site, replay, log }: {
15
+ site: PlatformSite;
16
+ replay?: boolean;
17
+ log?: (message: string) => void;
18
+ }): Promise<{
19
+ response: Response;
20
+ url: string;
21
+ }>;
22
+ /** Sends a request to the platform of env (LINKWISE_ISSUER), using the fallback address while the primary cannot be reached. */
23
+ export declare function platformRequest(url: string | URL, init?: RequestInit, { env, replay }?: {
24
+ env?: NodeJS.ProcessEnv;
25
+ replay?: boolean;
26
+ }): Promise<Response>;
@@ -0,0 +1,102 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { CliError, request, secureUrl } from '../cli/index.js';
5
+ import { deploymentDefaults, deploymentFallbacks } from '../cli/deployment.js';
6
+ import { stateDirectory } from './store.js';
7
+ const FALLBACK_FIRST_MS = 10 * 60 * 1000;
8
+ /** Failures before anything is sent: name resolution, refused or timed-out connections, TLS. */
9
+ const NOT_CONNECTED = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'UND_ERR_CONNECT_TIMEOUT',
10
+ 'CERT_HAS_EXPIRED', 'ERR_TLS_CERT_ALTNAME_INVALID', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY']);
11
+ /** Connections lost after the request may have been delivered. */
12
+ const DISCONNECTED = new Set(['ECONNRESET', 'EPIPE', 'UND_ERR_SOCKET']);
13
+ export function platformSite(env = process.env) {
14
+ const issuer = env.LINKWISE_ISSUER ?? deploymentDefaults.LINKWISE_ISSUER;
15
+ const allowHttp = /^http:/i.test(issuer.trim());
16
+ const origin = secureUrl(issuer, 'Authorization service URL', { allowHttp }).origin;
17
+ const fallback = env.LINKWISE_FALLBACK_URL ?? deploymentFallbacks[origin];
18
+ const roots = fallback ? [origin, secureUrl(fallback, 'Fallback service URL', { allowHttp }).href.replace(/\/+$/, '')] : [origin];
19
+ return { roots, stateDirectory: env.LXZ_STATE_DIR };
20
+ }
21
+ /** The path of target under the root that reference was sent to. */
22
+ export function atRootOf(target, reference, site) {
23
+ const from = rootOf(target, site);
24
+ const to = rootOf(reference, site);
25
+ return from === undefined || to === undefined ? target : to + target.slice(from.length);
26
+ }
27
+ /**
28
+ * Sends a request to the platform. When a root cannot be reached (no connection, or HTTP 502/504 from a proxy) the request is sent
29
+ * at the other root; a request that may already have been delivered (lost connection, 504) only when replay is allowed.
30
+ * Once the fallback answers for an unreachable primary, it goes first for 10 minutes and log is told. URLs outside the platform are sent as they are.
31
+ */
32
+ export async function platformExchange(url, init, { site, replay = true, log = notice }) {
33
+ const target = String(url);
34
+ const root = rootOf(target, site);
35
+ if (root === undefined || site.roots.length < 2)
36
+ return { response: await request(target, init), url: target };
37
+ const [primary, fallback] = site.roots;
38
+ const marker = join(stateDirectory(site.stateDirectory), `platform-${createHash('sha256').update(primary).digest('hex').slice(0, 16)}.json`);
39
+ const order = await fallbackFirst(marker) ? [fallback, primary] : [primary, fallback];
40
+ for (const [index, base] of order.entries()) {
41
+ const attempt = base + target.slice(root.length);
42
+ const last = index === order.length - 1;
43
+ let response;
44
+ try {
45
+ response = await request(attempt, init);
46
+ }
47
+ catch (error) {
48
+ init.signal?.throwIfAborted();
49
+ if (last || !unreachable(error, replay))
50
+ throw error;
51
+ continue;
52
+ }
53
+ if (!last && unreachable(response.status, replay)) {
54
+ await response.body?.cancel();
55
+ continue;
56
+ }
57
+ if (index > 0 && !unreachable(response.status, replay)) {
58
+ await setFallbackFirst(marker, base === fallback ? Date.now() + FALLBACK_FIRST_MS : 0);
59
+ if (base === fallback)
60
+ log(`The primary platform address is unreachable; using the fallback address ${fallback} for the next 10 minutes.`);
61
+ }
62
+ return { response, url: attempt };
63
+ }
64
+ throw new CliError('INTERNAL', 'No platform address was tried.', 'Contact the lxz maintainer.');
65
+ }
66
+ /** Sends a request to the platform of env (LINKWISE_ISSUER), using the fallback address while the primary cannot be reached. */
67
+ export async function platformRequest(url, init = {}, { env, replay } = {}) {
68
+ return (await platformExchange(url, init, { site: platformSite(env), replay })).response;
69
+ }
70
+ function rootOf(url, site) {
71
+ return [...site.roots].sort((a, b) => b.length - a.length).find(root => url === root || url.startsWith(root + '/') || url.startsWith(root + '?'));
72
+ }
73
+ function unreachable(outcome, replay) {
74
+ if (typeof outcome === 'number')
75
+ return outcome === 502 || (replay && outcome === 504);
76
+ if (!(outcome instanceof CliError) || outcome.code !== 'UNAVAILABLE')
77
+ return false;
78
+ let cause = outcome.cause;
79
+ while (cause && typeof cause.code !== 'string')
80
+ cause = cause.cause;
81
+ const code = cause?.code;
82
+ return code !== undefined && (NOT_CONNECTED.has(code) || (replay && DISCONNECTED.has(code)));
83
+ }
84
+ async function fallbackFirst(marker) {
85
+ try {
86
+ return Number(JSON.parse(await readFile(marker, 'utf8')).until) > Date.now();
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ async function setFallbackFirst(marker, until) {
93
+ // The marker only saves waiting for an unreachable primary; when it cannot be written, the next request tries the primary again.
94
+ try {
95
+ await mkdir(dirname(marker), { recursive: true, mode: 0o700 });
96
+ await writeFile(marker, JSON.stringify({ until }), { mode: 0o600 });
97
+ }
98
+ catch { /* ignored */ }
99
+ }
100
+ function notice(message) {
101
+ process.stderr.write(message + '\n');
102
+ }
@@ -1,5 +1,6 @@
1
1
  import type { Context } from '../cli/index.js';
2
2
  import { openBrowser } from '../cli/browser.js';
3
+ import type { PlatformSite } from './platform.js';
3
4
  export interface AuthConfig {
4
5
  baseUrl: string;
5
6
  clientId: string;
@@ -8,6 +9,8 @@ export interface AuthConfig {
8
9
  revokeEndpoint: string;
9
10
  allowHttp: boolean;
10
11
  stateDirectory?: string;
12
+ /** Addresses the endpoints are also served at; without it requests go only to baseUrl. */
13
+ site?: PlatformSite;
11
14
  }
12
15
  export interface TokenSet {
13
16
  account?: string;
@@ -28,6 +31,7 @@ export declare class OAuthProvider implements AuthProvider {
28
31
  readonly config: AuthConfig;
29
32
  private readonly browser;
30
33
  constructor(config: AuthConfig, browser?: typeof openBrowser);
34
+ private exchange;
31
35
  private send;
32
36
  private post;
33
37
  login(context: Context): Promise<TokenSet>;
@@ -7,6 +7,7 @@ import { authorizationPrompt } from '../cli/device-login.js';
7
7
  import { backendError } from './response.js';
8
8
  import { FileSessionStore } from './store.js';
9
9
  import { deploymentDefaults } from '../cli/deployment.js';
10
+ import { atRootOf, platformExchange, platformSite } from './platform.js';
10
11
  function text(data, name) {
11
12
  if (typeof data[name] === 'string' && data[name])
12
13
  return data[name];
@@ -46,7 +47,7 @@ export function authConfig(env = process.env, clientId = env.LXZ_AUTH_CLIENT_ID)
46
47
  throw new CliError('CONFIGURATION', 'Authorization service URL or client ID is missing.', 'Set LINKWISE_ISSUER and, if no default client ID is configured, LXZ_AUTH_CLIENT_ID. Obtain these values from the administrator.');
47
48
  const allowHttp = /^http:/i.test(issuer.trim());
48
49
  const baseUrl = secureUrl(issuer, 'Authorization service URL', { allowHttp }).href.replace(/\/$/, '');
49
- return { baseUrl, clientId, allowHttp, stateDirectory: env.LXZ_STATE_DIR, deviceEndpoint: `${baseUrl}/oauth2/device_authorization`, tokenEndpoint: `${baseUrl}/oauth2/token`, revokeEndpoint: `${baseUrl}/oauth2/revoke` };
50
+ return { baseUrl, clientId, allowHttp, stateDirectory: env.LXZ_STATE_DIR, site: platformSite(env), deviceEndpoint: `${baseUrl}/oauth2/device_authorization`, tokenEndpoint: `${baseUrl}/oauth2/token`, revokeEndpoint: `${baseUrl}/oauth2/revoke` };
50
51
  }
51
52
  export class OAuthProvider {
52
53
  config;
@@ -55,22 +56,28 @@ export class OAuthProvider {
55
56
  this.config = config;
56
57
  this.browser = browser;
57
58
  }
58
- send(endpoint, values, signal) {
59
- return request(endpoint, { method: 'POST', headers: { 'x-request-id': randomUUID() }, body: new URLSearchParams({ client_id: this.config.clientId, ...values }), signal });
59
+ exchange(endpoint, values, signal, { replay = true, log } = {}) {
60
+ const init = { method: 'POST', headers: { 'x-request-id': randomUUID() }, body: new URLSearchParams({ client_id: this.config.clientId, ...values }), signal };
61
+ return this.config.site ? platformExchange(endpoint, init, { site: this.config.site, replay, log }) : request(endpoint, init).then(response => ({ response, url: endpoint }));
60
62
  }
61
- async post(endpoint, values, signal) {
62
- const response = await this.send(endpoint, values, signal);
63
+ async send(endpoint, values, signal, options) {
64
+ return (await this.exchange(endpoint, values, signal, options)).response;
65
+ }
66
+ async post(endpoint, values, signal, options) {
67
+ const { response, url } = await this.exchange(endpoint, values, signal, options);
63
68
  const data = await readJson(response);
64
- return { response, data };
69
+ return { response, data, url };
65
70
  }
66
71
  async login(context) {
67
72
  if (!context.interactive && !context.allowDeviceLogin)
68
73
  throw new CliError('AUTH_REQUIRED', 'Authorize this CLI before continuing.', 'Run init in a terminal; for scripts, use init --device-login --timeout-ms 660000 and ask the user to approve in a browser.');
69
74
  const os = { win32: 'Windows', darwin: 'macOS', linux: 'Linux' }[platform()] ?? platform();
70
75
  const deviceId = await new FileSessionStore(`${this.config.baseUrl}\n${this.config.clientId}`, this.config.stateDirectory).deviceId(context.signal);
71
- const device = await this.post(this.config.deviceEndpoint, { client_os: os, device_id: deviceId }, context.signal);
76
+ const device = await this.post(this.config.deviceEndpoint, { client_os: os, device_id: deviceId }, context.signal, { log: context.log });
72
77
  if (!device.response.ok)
73
78
  throw backendError(device.response, device.data);
79
+ // The whole device login stays at the address that issued the device code.
80
+ const tokenEndpoint = this.config.site ? atRootOf(this.config.tokenEndpoint, device.url, this.config.site) : this.config.tokenEndpoint;
74
81
  const verification = text(device.data, 'verification_uri_complete');
75
82
  secureUrl(verification, 'Authorization approval URL', { allowHttp: this.config.allowHttp, allowQuery: true });
76
83
  const code = text(device.data, 'user_code');
@@ -97,7 +104,7 @@ export class OAuthProvider {
97
104
  const remaining = AbortSignal.timeout(Math.max(1, deadline - Date.now()));
98
105
  let response;
99
106
  try {
100
- response = await this.send(this.config.tokenEndpoint, { device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' }, AbortSignal.any([context.signal, remaining]));
107
+ response = await request(tokenEndpoint, { method: 'POST', headers: { 'x-request-id': randomUUID() }, body: new URLSearchParams({ client_id: this.config.clientId, device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' }), signal: AbortSignal.any([context.signal, remaining]) });
101
108
  }
102
109
  catch (error) {
103
110
  context.signal.throwIfAborted();
@@ -144,7 +151,8 @@ export class OAuthProvider {
144
151
  throw new CliError('AUTH_EXPIRED', 'The user code has expired.', 'Run init or login again to request a new user code.');
145
152
  }
146
153
  async refresh(refreshToken, signal) {
147
- const { response, data } = await this.post(this.config.tokenEndpoint, { grant_type: 'refresh_token', refresh_token: refreshToken }, signal);
154
+ // A delivered refresh rotates the token, and sending the old one again is treated as replay; move only when nothing was sent.
155
+ const { response, data } = await this.post(this.config.tokenEndpoint, { grant_type: 'refresh_token', refresh_token: refreshToken }, signal, { replay: false });
148
156
  if (!response.ok)
149
157
  throw backendError(response, data, [refreshToken]);
150
158
  return tokens(data);
@@ -1,10 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { setTimeout as delay } from 'node:timers/promises';
3
- import { CliError, readJson, request, secureUrl } from '../cli/index.js';
3
+ import { CliError, readJson, secureUrl } from '../cli/index.js';
4
4
  import { backendError } from './response.js';
5
+ import { platformRequest } from './platform.js';
5
6
  export async function serviceJson(identity, input, signal) {
6
7
  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
+ return readJson(await serviceRequest(identity, token => platformRequest(url, { headers: { authorization: `Bearer ${token}`, 'x-request-id': randomUUID() }, signal }), signal));
8
9
  }
9
10
  export async function serviceRequest(identity, send, signal, { replay = true } = {}) {
10
11
  let credential = await identity.credential(signal);
@@ -13,6 +13,7 @@ export interface SessionAccess {
13
13
  write(session: Session): Promise<void>;
14
14
  clear(): Promise<void>;
15
15
  }
16
+ export declare const stateDirectory: (directory?: string | undefined) => string;
16
17
  export declare class FileSessionStore implements SessionStore {
17
18
  readonly directory: string;
18
19
  readonly file: string;
@@ -18,10 +18,11 @@ function protect(input, decrypt, signal) {
18
18
  child.stdin.end(input);
19
19
  });
20
20
  }
21
+ export const stateDirectory = (directory = process.env.LXZ_STATE_DIR) => directory ?? join(homedir(), '.lianxz', 'identity');
21
22
  export class FileSessionStore {
22
23
  directory;
23
24
  file;
24
- constructor(context, directory = process.env.LXZ_STATE_DIR ?? join(homedir(), '.lianxz', 'identity')) {
25
+ constructor(context, directory = stateDirectory()) {
25
26
  this.directory = directory;
26
27
  this.file = join(directory, `${createHash('sha256').update(context).digest('hex')}.json`);
27
28
  }
@@ -0,0 +1,14 @@
1
+ import type { failure } from './errors.js';
2
+ export declare const backgroundArgument = "--lxz-background";
3
+ export type BackgroundResult = {
4
+ ok: true;
5
+ data: unknown;
6
+ } | {
7
+ ok: false;
8
+ error: ReturnType<typeof failure>;
9
+ };
10
+ export declare function readBackgroundResult(value: unknown): BackgroundResult | undefined;
11
+ export declare function backgroundInvocation(argv: string[]): {
12
+ argv: string[];
13
+ complete(result: BackgroundResult): Promise<void> | undefined;
14
+ };
@@ -0,0 +1,35 @@
1
+ import { exitCodes } from './errors.js';
2
+ export const backgroundArgument = '--lxz-background';
3
+ function errorCode(value) {
4
+ return typeof value === 'string' && Object.hasOwn(exitCodes, value);
5
+ }
6
+ export function readBackgroundResult(value) {
7
+ if (typeof value !== 'object' || value === null || !('type' in value) || value.type !== 'lxz:result' || !('ok' in value))
8
+ return;
9
+ if (value.ok === true && 'data' in value)
10
+ return { ok: true, data: value.data };
11
+ if (value.ok !== false || !('error' in value) || typeof value.error !== 'object' || value.error === null)
12
+ return;
13
+ const error = value.error;
14
+ if ('code' in error && errorCode(error.code) && 'message' in error && typeof error.message === 'string'
15
+ && 'next' in error && typeof error.next === 'string' && 'retryable' in error && typeof error.retryable === 'boolean') {
16
+ return { ok: false, error: { code: error.code, message: error.message, next: error.next, retryable: error.retryable, ...('details' in error ? { details: error.details } : {}) } };
17
+ }
18
+ }
19
+ export function backgroundInvocation(argv) {
20
+ const enabled = process.connected && argv.at(-1) === backgroundArgument;
21
+ return {
22
+ argv: enabled ? argv.slice(0, -1) : argv,
23
+ complete(result) {
24
+ if (!enabled || !process.connected)
25
+ return;
26
+ return new Promise(resolve => {
27
+ process.send({ type: 'lxz:result', ...result }, () => {
28
+ if (process.connected)
29
+ process.disconnect();
30
+ resolve();
31
+ });
32
+ });
33
+ },
34
+ };
35
+ }
@@ -1,5 +1,6 @@
1
1
  import type { ArgDef } from 'citty';
2
2
  export declare const contractVersion = "1.0.0";
3
+ export type CharacterEscaping = 'escaped' | 'literal';
3
4
  export interface Parameter {
4
5
  type: 'string' | 'boolean';
5
6
  description: string;
@@ -36,19 +37,12 @@ export interface Application {
36
37
  version: string;
37
38
  description: string;
38
39
  defaultCommand?: string;
40
+ characterEscaping?: CharacterEscaping;
41
+ jsonOutput?: boolean | 'schema';
39
42
  commands: Record<string, Command>;
40
43
  }
41
44
  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
- };
45
+ export declare function commandParameters(command?: Command, options?: Pick<Application, 'jsonOutput'>): Record<string, Parameter>;
52
46
  export declare function argumentDefinitions(parameters: Record<string, Parameter>): Record<string, ArgDef>;
53
47
  export declare function describe(app: Application, scope?: string): {
54
48
  contractVersion: string;
@@ -1,18 +1,23 @@
1
1
  export const contractVersion = '1.0.0';
2
2
  export const commonParameters = {
3
- json: { type: 'boolean', description: 'Return a JSON receipt instead of compact rows; use for programmatic parsing', default: false },
3
+ json: { type: 'boolean', description: 'Return a JSON receipt for programmatic parsing', default: false },
4
4
  'non-interactive': { type: 'boolean', description: 'Use command parameters without interactive prompts', default: false },
5
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
6
  help: { type: 'boolean', description: 'Show help for this command or group; same as -h' },
7
7
  version: { type: 'boolean', description: 'Show version' },
8
8
  schema: { type: 'boolean', description: 'Show command, input and result schemas' },
9
9
  };
10
- export function commandParameters(command) {
11
- return { ...commonParameters, ...(command?.timeoutMs || command?.interactiveTimeout === 'total' ? { 'timeout-ms': {
10
+ export function commandParameters(command, options = {}) {
11
+ const parameters = { ...commonParameters, ...(command?.timeoutMs || command?.interactiveTimeout === 'total' ? { 'timeout-ms': {
12
12
  ...commonParameters['timeout-ms'],
13
13
  ...(command.timeoutMs ? { default: String(command.timeoutMs) } : {}),
14
14
  ...(command.interactiveTimeout === 'total' ? { description: 'Total deadline in ms (1-3600000), including approval waits; keyboard inactivity does not end authorization' } : {}),
15
15
  } } : {}), ...command?.parameters };
16
+ if (options.jsonOutput === false || options.jsonOutput === 'schema')
17
+ delete parameters.json;
18
+ if (options.jsonOutput === 'schema')
19
+ parameters.schema = { ...parameters.schema, description: 'Show command, input and result schemas; add --json for a JSON receipt' };
20
+ return parameters;
16
21
  }
17
22
  export function argumentDefinitions(parameters) {
18
23
  return Object.fromEntries(Object.entries(parameters).map(([key, { choices, pattern, ...definition }]) => [key, definition]));
@@ -27,7 +32,7 @@ export function describe(app, scope) {
27
32
  examples: command.examples,
28
33
  input: {
29
34
  type: 'object', additionalProperties: false,
30
- properties: Object.fromEntries(Object.entries(commandParameters(command)).map(([name, { description, type, default: value, choices, pattern }]) => [name, {
35
+ properties: Object.fromEntries(Object.entries(commandParameters(command, app)).map(([name, { description, type, default: value, choices, pattern }]) => [name, {
31
36
  type, description, ...(value === undefined ? {} : { default: value }), ...(choices ? { enum: choices } : {}), ...(pattern ? { pattern } : {}),
32
37
  }])),
33
38
  required: Object.entries(command.parameters ?? {}).filter(([, p]) => p.required).map(([name]) => name),
@@ -1,5 +1,13 @@
1
1
  export declare const deploymentDefaults: {
2
2
  LINKWISE_ISSUER: string;
3
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. */
4
+ /**
5
+ * Roots serving the same paths as an issuer origin, used while that origin cannot be reached.
6
+ * LINKWISE_FALLBACK_URL overrides (an empty value disables); a test build ships its own in linkwise.env.json.
7
+ */
8
+ export declare const deploymentFallbacks: Readonly<Record<string, string>>;
9
+ /**
10
+ * Fixes the authorization server for this process and the lxz processes it starts: environment, then the file a test build ships with, then production.
11
+ * The packaged fallback address goes with the packaged issuer only.
12
+ */
5
13
  export declare function applyDeployment(packageRoot: URL, env?: NodeJS.ProcessEnv): void;
@@ -2,7 +2,14 @@ import { readFileSync } from 'node:fs';
2
2
  export const deploymentDefaults = {
3
3
  LINKWISE_ISSUER: 'https://ai-cli.tul.cn/linkwise-api',
4
4
  };
5
- function packagedIssuer(packageRoot) {
5
+ /**
6
+ * Roots serving the same paths as an issuer origin, used while that origin cannot be reached.
7
+ * LINKWISE_FALLBACK_URL overrides (an empty value disables); a test build ships its own in linkwise.env.json.
8
+ */
9
+ export const deploymentFallbacks = {
10
+ 'https://ai-cli.tul.cn': 'https://linkwise.tul.cn/cli',
11
+ };
12
+ function packagedDeployment(packageRoot) {
6
13
  let text;
7
14
  try {
8
15
  text = readFileSync(new URL('linkwise.env.json', packageRoot), 'utf8');
@@ -12,12 +19,17 @@ function packagedIssuer(packageRoot) {
12
19
  return undefined;
13
20
  throw error;
14
21
  }
15
- const value = JSON.parse(text).LINKWISE_ISSUER;
16
- if (typeof value !== 'string' || !value)
22
+ const { LINKWISE_ISSUER: issuer, LINKWISE_FALLBACK_URL: fallback } = JSON.parse(text);
23
+ if (typeof issuer !== 'string' || !issuer)
17
24
  throw new Error('linkwise.env.json must set LINKWISE_ISSUER.');
18
- return value;
25
+ return { LINKWISE_ISSUER: issuer, ...(typeof fallback === 'string' ? { LINKWISE_FALLBACK_URL: fallback } : {}) };
19
26
  }
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. */
27
+ /**
28
+ * Fixes the authorization server for this process and the lxz processes it starts: environment, then the file a test build ships with, then production.
29
+ * The packaged fallback address goes with the packaged issuer only.
30
+ */
21
31
  export function applyDeployment(packageRoot, env = process.env) {
22
- env.LINKWISE_ISSUER ??= packagedIssuer(packageRoot) ?? deploymentDefaults.LINKWISE_ISSUER;
32
+ if (env.LINKWISE_ISSUER !== undefined)
33
+ return;
34
+ Object.assign(env, packagedDeployment(packageRoot) ?? deploymentDefaults);
23
35
  }
@@ -25,5 +25,5 @@ export declare const pendingProperties: {
25
25
  };
26
26
  };
27
27
  export declare function waitsInBackground(input: Record<string, string | boolean>, context: Context): boolean;
28
- export declare function approvalNext(link: AuthorizationLink, status: string): string;
28
+ export declare function approvalNext(link: AuthorizationLink, status: string, json?: boolean): string;
29
29
  export declare function deviceLoginInBackground(input: Record<string, string | boolean>, context: Context, pending: (link: AuthorizationLink) => unknown, entry?: string): Promise<unknown>;