@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.
@@ -5,6 +5,7 @@ import { join } from 'node:path';
5
5
  import { setTimeout as delay } from 'node:timers/promises';
6
6
  import { openBrowser } from './browser.js';
7
7
  import { CliError } from './errors.js';
8
+ import { backgroundArgument, readBackgroundResult } from './background.js';
8
9
  const urlLabel = 'Authorization URL: ', codeLabel = 'User code: ';
9
10
  export const authorizationPrompt = (url, code) => `${urlLabel}${url}\n${codeLabel}${code}`;
10
11
  const labelled = (text, label) => text.split(/\r?\n/).find(line => line.startsWith(label))?.slice(label.length).trim();
@@ -12,7 +13,7 @@ export const statusWaitLimitSeconds = 170;
12
13
  const linkDeadlineMs = 30000;
13
14
  // An approval that is already done, or an issuer that approves at once, still finishes in the foreground.
14
15
  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 waitParameter = { type: 'boolean', description: 'With --device-login in non-interactive mode, wait for browser approval in the foreground', default: false };
16
17
  export const pendingProperties = {
17
18
  authorizationUrl: { type: 'string' }, userCode: { type: 'string' },
18
19
  browserOpened: { type: 'boolean', description: 'This command opened the authorization page in the system browser' },
@@ -21,31 +22,21 @@ export const pendingProperties = {
21
22
  export function waitsInBackground(input, context) {
22
23
  return Boolean(input['device-login'] && !context.interactive && !input.wait && context.argv);
23
24
  }
24
- export function approvalNext(link, status) {
25
+ export function approvalNext(link, status, json = true) {
25
26
  return (link.browserOpened
26
27
  ? '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
28
  : '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
+ + '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. Keep the link on its own line and write userCode on a separate line. '
29
30
  + '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
+ + `In the same turn, immediately run ${status} --wait-seconds ${statusWaitLimitSeconds}${json ? ' --json' : ''} --non-interactive; it returns once the user approves. Continue the user's original task after approval. Reuse this authorization link while it is valid.`;
31
32
  }
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.');
33
+ function finalResult(result) {
34
+ if (!result)
35
+ throw new CliError('UNAVAILABLE', 'Background authorization stopped without a result.', 'Run the command again.');
36
+ if (result.ok)
37
+ return result.data;
38
+ const { code, message, next, retryable, details } = result.error;
39
+ throw new CliError(code, message, next, retryable, details);
49
40
  }
50
41
  // Agents that show output only after a command exits cannot show the link of a device login that waits.
51
42
  // A detached copy of this command waits instead; this one opens the browser once and returns the link.
@@ -53,8 +44,13 @@ export async function deviceLoginInBackground(input, context, pending, entry = p
53
44
  const log = join(mkdtempSync(join(tmpdir(), 'lxz-authorization-')), 'authorization.log');
54
45
  const output = openSync(log, 'a');
55
46
  let exited = false;
47
+ let result;
48
+ let disconnect = () => { };
56
49
  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] });
50
+ const child = spawn(process.execPath, [...process.execArgv, entry, ...context.argv, '--wait', '--no-browser', '--non-interactive', backgroundArgument], { detached: true, windowsHide: true, stdio: ['ignore', output, output, 'ipc'] });
51
+ child.once('message', message => { result = readBackgroundResult(message); });
52
+ disconnect = () => { if (child.connected)
53
+ child.disconnect(); };
58
54
  child.once('exit', () => { exited = true; });
59
55
  child.once('error', () => { exited = true; });
60
56
  child.unref();
@@ -69,19 +65,24 @@ export async function deviceLoginInBackground(input, context, pending, entry = p
69
65
  return '';
70
66
  } };
71
67
  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 });
68
+ try {
69
+ for (const start = Date.now(); Date.now() - start < linkDeadlineMs;) {
70
+ await delay(200, undefined, { signal: context.signal });
71
+ const text = read();
72
+ if (result || exited)
73
+ return finalResult(result);
74
+ const authorizationUrl = labelled(text, urlLabel), userCode = labelled(text, codeLabel);
75
+ if (!authorizationUrl || !userCode)
76
+ continue;
77
+ seen ||= Date.now();
78
+ browser ??= input.browser === false ? Promise.resolve(false) : openBrowser(authorizationUrl, context.signal);
79
+ if (Date.now() - seen < graceMs)
80
+ continue;
81
+ return pending({ authorizationUrl, userCode, browserOpened: await browser, log });
82
+ }
83
+ }
84
+ finally {
85
+ disconnect();
85
86
  }
86
87
  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
88
  }
package/dist/cli/http.js CHANGED
@@ -22,7 +22,7 @@ export async function request(url, init = {}) {
22
22
  throw init.signal.reason;
23
23
  if (timeout.aborted)
24
24
  throw new CliError('TIMEOUT', 'The service did not respond within 60 seconds.', 'Check the network and service status, then retry.', true);
25
- throw new CliError('UNAVAILABLE', 'Cannot reach the service.', 'Check the network and service URL, then retry.', true);
25
+ throw new CliError('UNAVAILABLE', 'Cannot reach the service.', 'Check the network and service URL, then retry.', true, undefined, error);
26
26
  }
27
27
  }
28
28
  export async function readJson(response) {
@@ -1,3 +1,3 @@
1
- import type { Command } from './contracts.js';
1
+ import type { Application, Command } from './contracts.js';
2
2
  import type { IdentityPort } from './init.js';
3
- export declare function identityCommands(identity: (input: Record<string, string | boolean>) => IdentityPort, invoke: string): Record<string, Command>;
3
+ export declare function identityCommands(identity: (input: Record<string, string | boolean>) => IdentityPort, invoke: string, options?: Pick<Application, 'jsonOutput'>): Record<string, Command>;
@@ -2,14 +2,16 @@ import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { errorSchema } from './schemas.js';
3
3
  import { approvalNext, deviceLoginInBackground, pendingProperties, statusWaitLimitSeconds, waitParameter, waitsInBackground } from './device-login.js';
4
4
  const pollMs = 2000;
5
- export function identityCommands(identity, invoke) {
5
+ export function identityCommands(identity, invoke, options = {}) {
6
+ const json = options.jsonOutput !== false && options.jsonOutput !== 'schema';
7
+ const outputFlag = json ? ' --json' : '';
6
8
  const status = {
7
9
  description: 'Show this CLI authorization status and current account', effects: 'none', timeoutMs: (statusWaitLimitSeconds + 5) * 1000,
8
10
  parameters: {
9
11
  'wait-seconds': { type: 'string', default: '0', pattern: `^(?:0|[1-9][0-9]?|1[0-6][0-9]|${statusWaitLimitSeconds})$`, description: `Wait up to this many seconds (0-${statusWaitLimitSeconds}) for a pending browser approval; returns as soon as it is approved` },
10
12
  },
11
13
  result: { type: 'object', properties: { authorized: { type: 'boolean', description: 'Local session exists within its refresh lifetime; server status has not been checked' }, account: { type: 'string', description: 'Backend account ID; defaults to token sub, which may differ from the login name' }, loginName: { type: 'string', description: 'Backend login name from token name; omitted when unavailable' }, clientId: { type: 'string', description: 'CLI client ID, separate from account identity' }, displayName: { type: 'string', description: 'Backend display name; omitted when unavailable' }, accessExpiresAt: { type: 'number' }, refreshExpiresAt: { type: 'number' }, next: { type: 'string', description: 'What to do when the approval did not arrive in time' } }, required: ['authorized'] },
12
- examples: [invoke + ' status --json --non-interactive', `${invoke} status --wait-seconds ${statusWaitLimitSeconds} --json --non-interactive`],
14
+ examples: [invoke + ` status${outputFlag} --non-interactive`, `${invoke} status --wait-seconds ${statusWaitLimitSeconds}${outputFlag} --non-interactive`],
13
15
  async run(input, context) {
14
16
  const seconds = Number(input['wait-seconds'] ?? 0);
15
17
  const deadline = Date.now() + seconds * 1000;
@@ -20,7 +22,7 @@ export function identityCommands(identity, invoke) {
20
22
  if (Date.now() >= deadline)
21
23
  return seconds ? {
22
24
  authorized: false,
23
- next: `Not approved within ${seconds} seconds. Ask the user whether they approved in the browser. If the link is still valid, run ${statusCommand(input)} --wait-seconds ${statusWaitLimitSeconds} --json --non-interactive again; if it expired or was refused, run the init or login command again with --device-login --non-interactive --json for a new link.`,
25
+ next: `Not approved within ${seconds} seconds. Ask the user whether they approved in the browser. If the link is still valid, run ${statusCommand(input)} --wait-seconds ${statusWaitLimitSeconds}${outputFlag} --non-interactive again; if it expired or was refused, run the init or login command again with --device-login --non-interactive${outputFlag} for a new link.`,
24
26
  } : { authorized: false };
25
27
  await delay(Math.min(pollMs, deadline - Date.now()), undefined, { signal: context.signal });
26
28
  }
@@ -37,10 +39,10 @@ export function identityCommands(identity, invoke) {
37
39
  browser: { type: 'boolean', description: 'Open the authorization page in the default browser; use --no-browser to open the URL on another device', default: true },
38
40
  },
39
41
  result: { type: 'object', properties: { account: { type: 'string' }, status: { const: 'pending' }, ...pendingProperties, next: { type: 'string', description: 'What to do next while authorization is pending' } } },
40
- examples: [invoke + ' login', invoke + ' login --device-login --json --non-interactive'],
42
+ examples: [invoke + ' login', invoke + ` login --device-login${outputFlag} --non-interactive`],
41
43
  async run(input, context) {
42
44
  if (waitsInBackground(input, context) && !await identity(input).status(context.signal).then(Boolean, () => true)) {
43
- return deviceLoginInBackground(input, context, link => ({ status: 'pending', ...link, next: approvalNext(link, statusCommand(input)) }));
45
+ return deviceLoginInBackground(input, context, link => ({ status: 'pending', ...link, next: approvalNext(link, statusCommand(input), json) }));
44
46
  }
45
47
  return identity(input).login({ ...context, allowDeviceLogin: Boolean(input['device-login']), browser: input.browser !== false });
46
48
  },
@@ -49,7 +51,7 @@ export function identityCommands(identity, invoke) {
49
51
  logout: {
50
52
  description: 'Revoke this CLI grant and delete local tokens; other devices and CLIs are unaffected', effects: 'remote',
51
53
  result: { type: 'object', properties: { loggedOut: { const: true }, clientId: { type: 'string' }, impact: { type: 'string' }, revocation: { enum: ['revoked', 'failed', 'not-needed'] }, warning: { type: 'string' }, revocationError: errorSchema }, required: ['loggedOut', 'clientId', 'impact'] },
52
- examples: [invoke + ' logout --json --non-interactive'],
54
+ examples: [invoke + ` logout${outputFlag} --non-interactive`],
53
55
  run: (input, context) => identity(input).logout(context.signal),
54
56
  },
55
57
  };
package/dist/cli/init.js CHANGED
@@ -21,7 +21,7 @@ export function initCommand(identity, skill, clientId, example) {
21
21
  'device-login': { type: 'boolean', description: 'Allow device authorization in non-interactive mode; returns the link at once and waits for approval in the background', default: false },
22
22
  wait: waitParameter,
23
23
  browser: { type: 'boolean', description: 'Open the authorization page in the default browser; use --no-browser to open the URL on another device', default: true },
24
- 'skills-dir': { type: 'string', description: 'Skills root; overrides LXZ_SKILLS_DIR. Default: registered roots, or ~/.agents/skills and ~/.linkwise/skills (Linkwise)' },
24
+ 'skills-dir': { type: 'string', description: 'Skills root; overrides LXZ_SKILLS_DIR. Defaults to registered roots or ~/.linkwise/skills on first install' },
25
25
  'skill-conflict': { type: 'string', description: 'Local Skill changes: error keeps them; replace overwrites managed files', choices: ['error', 'replace'], default: 'error' },
26
26
  },
27
27
  result: initializationSchema, examples: [example],
@@ -1,2 +1,3 @@
1
+ import type { CharacterEscaping } from './contracts.js';
1
2
  export declare function jsonText(value: unknown, space?: number): string;
2
- export declare function rowText(value: unknown): string;
3
+ export declare function rowText(value: unknown, characters?: CharacterEscaping): string;
@@ -1,14 +1,16 @@
1
- // Console decoders such as PowerShell on Chinese Windows read stdout with the local code page; ASCII JSON parses the same everywhere.
2
1
  export function jsonText(value, space) {
3
- return JSON.stringify(value, null, space).replace(/[^\x00-\x7e]/g, character => '\\u' + character.charCodeAt(0).toString(16).padStart(4, '0'));
2
+ return JSON.stringify(value, null, space);
4
3
  }
5
- function cell(value) {
4
+ function escapedCell(value) {
6
5
  return typeof value === 'string' ? JSON.stringify(value).slice(1, -1) : value === undefined ? '' : String(value);
7
6
  }
7
+ function literalCell(value) {
8
+ return value === undefined ? '' : String(value);
9
+ }
8
10
  function scalar(value) {
9
11
  return value === null || typeof value !== 'object';
10
12
  }
11
- function rows(value) {
13
+ function rows(value, cell) {
12
14
  if (scalar(value))
13
15
  return [cell(value)];
14
16
  if (Array.isArray(value)) {
@@ -21,15 +23,15 @@ function rows(value) {
21
23
  if (columns.length)
22
24
  return [columns.map(key => cell(key)).join('\t'), ...value.map(item => columns.map(key => Object.hasOwn(item, key) ? cell(item[key]) : '').join('\t'))];
23
25
  }
24
- return value.flatMap((item, index) => [`[${index}]:`, ...rows(item).map(line => ' ' + line)]);
26
+ return value.flatMap((item, index) => [`[${index}]:`, ...rows(item, cell).map(line => ' ' + line)]);
25
27
  }
26
28
  const entries = Object.entries(value).filter(([, item]) => item !== undefined);
27
29
  if (!entries.length)
28
30
  return ['{}'];
29
31
  return entries.flatMap(([key, item]) => scalar(item)
30
32
  ? [`${cell(key)}\t${cell(item)}`]
31
- : [`${cell(key)}:`, ...rows(item).map(line => ' ' + line)]);
33
+ : [`${cell(key)}:`, ...rows(item, cell).map(line => ' ' + line)]);
32
34
  }
33
- export function rowText(value) {
34
- return typeof value === 'string' ? value : rows(value).join('\n');
35
+ export function rowText(value, characters = 'escaped') {
36
+ return typeof value === 'string' ? value : rows(value, characters === 'literal' ? literalCell : escapedCell).join('\n');
35
37
  }
@@ -1,6 +1,7 @@
1
1
  import { defineCommand, renderUsage } from 'citty';
2
2
  import { parseArgs } from 'node:util';
3
- import { argumentDefinitions, commonParameters, commandParameters, contractVersion, describe } from './contracts.js';
3
+ import { argumentDefinitions, commandParameters, commonParameters, contractVersion, describe } from './contracts.js';
4
+ import { backgroundInvocation } from './background.js';
4
5
  import { CliError, exitCodes, failure } from './errors.js';
5
6
  import { jsonText, rowText } from './output.js';
6
7
  function jsonLine(value) {
@@ -16,15 +17,15 @@ function validate(input, parameters, required) {
16
17
  }
17
18
  }
18
19
  }
19
- function jsonMode(raw, parameters) {
20
- let enabled = false;
20
+ function booleanMode(raw, parameters, name) {
21
+ let enabled;
21
22
  for (let index = 0; index < raw.length; index++) {
22
23
  const flag = raw[index];
23
24
  if (flag === '--')
24
25
  break;
25
- if (flag === '--json' || flag === '--json=true')
26
+ if (flag === `--${name}` || flag === `--${name}=true`)
26
27
  enabled = true;
27
- else if (flag === '--no-json' || flag === '--json=false')
28
+ else if (flag === `--no-${name}` || flag === `--${name}=false`)
28
29
  enabled = false;
29
30
  else if (!flag.includes('=') && parameters[flag.slice(2)]?.type === 'string' && !raw[index + 1]?.startsWith('-'))
30
31
  index++;
@@ -32,10 +33,16 @@ function jsonMode(raw, parameters) {
32
33
  return enabled;
33
34
  }
34
35
  export async function runApplication(app, argv = process.argv.slice(2)) {
36
+ const background = backgroundInvocation(argv);
37
+ argv = background.argv;
35
38
  argv = argv.map((value) => value === '-h' ? '--help' : value === '-v' ? '--version' : value);
36
39
  let json = false;
40
+ const characters = app.characterEscaping ?? 'escaped';
37
41
  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');
42
+ const write = async (data, format) => {
43
+ process.stdout.write(json ? jsonLine({ ok: true, data, meta }) : (format ? format(data) : rowText(data, characters)) + '\n');
44
+ await background.complete({ ok: true, data });
45
+ };
39
46
  let dispose = () => { };
40
47
  try {
41
48
  const names = [...new Set(Object.keys(app.commands).flatMap((name) => {
@@ -43,14 +50,15 @@ export async function runApplication(app, argv = process.argv.slice(2)) {
43
50
  return words.map((_, index) => words.slice(0, index + 1).join(' '));
44
51
  }))].sort((a, b) => b.length - a.length);
45
52
  const leading = [];
53
+ const globals = commandParameters();
46
54
  let offset = 0;
47
55
  while (argv[offset]?.startsWith('--')) {
48
56
  const name = argv[offset].slice(2).split('=')[0].replace(/^no-/, '');
49
- if (!commonParameters[name])
57
+ if (!globals[name])
50
58
  break;
51
59
  const flag = argv[offset++];
52
60
  leading.push(flag);
53
- if (commonParameters[name].type === 'string' && !flag.includes('=') && argv[offset] !== undefined)
61
+ if (globals[name].type === 'string' && !flag.includes('=') && argv[offset] !== undefined)
54
62
  leading.push(argv[offset++]);
55
63
  }
56
64
  const remaining = argv.slice(offset);
@@ -58,9 +66,16 @@ export async function runApplication(app, argv = process.argv.slice(2)) {
58
66
  const explicitRoute = names.find((name) => name.split(' ').every((word, i) => remaining[i] === word));
59
67
  const route = explicitRoute ?? app.defaultCommand;
60
68
  const command = route ? app.commands[route] : undefined;
61
- const parameters = commandParameters(command);
69
+ const parameters = commandParameters(command, app);
62
70
  const raw = [...leading, ...(explicitRoute ? remaining.slice(explicitRoute.split(' ').length) : remaining)];
63
- json = jsonMode(raw, parameters);
71
+ if (app.jsonOutput === 'schema' && booleanMode(raw, parameters, 'schema') && !booleanMode(raw, parameters, 'version'))
72
+ parameters.json = commonParameters.json;
73
+ const requestedJson = booleanMode(raw, parameters, 'json');
74
+ if (app.jsonOutput === 'schema' && !parameters.json && requestedJson !== undefined) {
75
+ const commandPath = app.name + (explicitRoute ? ' ' + explicitRoute : '');
76
+ throw new CliError('INVALID_INPUT', 'JSON output is available only with --schema.', `Run ${commandPath} --help for command options, or ${commandPath} --schema --json for the contract.`);
77
+ }
78
+ json = Boolean(parameters.json && requestedJson);
64
79
  let input;
65
80
  try {
66
81
  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 });
@@ -70,11 +85,11 @@ export async function runApplication(app, argv = process.argv.slice(2)) {
70
85
  throw new CliError('INVALID_INPUT', 'Unknown command, option or invalid option type.', `Use ${app.name} --help to view commands and options.`);
71
86
  }
72
87
  if (input.version) {
73
- write({ version: app.version, contractVersion });
88
+ await write({ version: app.version, contractVersion });
74
89
  return;
75
90
  }
76
91
  if (input.schema) {
77
- write(describe(app, explicitRoute));
92
+ await write(describe(app, explicitRoute));
78
93
  return;
79
94
  }
80
95
  if (input.help || (!argv.length && !app.defaultCommand)) {
@@ -82,7 +97,7 @@ export async function runApplication(app, argv = process.argv.slice(2)) {
82
97
  const usage = await renderUsage(definition);
83
98
  const children = Object.entries(app.commands).filter(([name]) => !route || name.startsWith(route + ' '));
84
99
  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}`);
100
+ await write(`${usage}${command ? `\nExamples:\n${command.examples.join('\n')}` : ''}${commands}`);
86
101
  return;
87
102
  }
88
103
  if (!command)
@@ -121,15 +136,16 @@ export async function runApplication(app, argv = process.argv.slice(2)) {
121
136
  interactive, argv,
122
137
  signal: controller.signal, log: (message) => process.stderr.write(`${message}\n`),
123
138
  }), aborted]);
124
- write(!json && command.format ? command.format(result) : result);
139
+ await write(result, command.format);
125
140
  }
126
141
  catch (error) {
127
142
  const detail = failure(error);
128
143
  if (json)
129
144
  process.stdout.write(jsonLine({ ok: false, error: detail, meta }));
130
145
  else
131
- process.stderr.write(`${detail.code}: ${detail.message}\nNext: ${detail.next}\n${detail.details ? rowText(detail.details) + '\n' : ''}`);
146
+ process.stderr.write(`${detail.code}: ${detail.message}\nNext: ${detail.next}\n${detail.details ? rowText(detail.details, characters) + '\n' : ''}`);
132
147
  process.exitCode = exitCodes[detail.code];
148
+ await background.complete({ ok: false, error: detail });
133
149
  }
134
150
  finally {
135
151
  dispose();
@@ -1,6 +1,5 @@
1
1
  import { contractVersion, describe } from './contracts.js';
2
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
3
  const dialect = { $schema: 'https://json-schema.org/draft/2020-12/schema' };
5
4
  export const schemaDialect = dialect.$schema;
6
5
  export const errorSchema = {
package/dist/doctor.js CHANGED
@@ -24,7 +24,7 @@ async function packageRegistry(signal) {
24
24
  export const doctor = {
25
25
  description: 'Check runtime, package registry, authorization service and local session without logging in', effects: 'none',
26
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'] },
27
+ examples: ['pnpm dlx @tulcn/lxz doctor --non-interactive', 'pnpm dlx @tulcn/lxz doctor --client-id crm-demo1 --non-interactive'], result: { type: 'object', required: ['checks', 'healthy'] },
28
28
  async run(input, context) {
29
29
  const clientId = typeof input['client-id'] === 'string' ? input['client-id'] : undefined;
30
30
  const checks = {};
@@ -7,5 +7,5 @@ export const agentSkillDirectories = {
7
7
  linkwise: '.linkwise/skills',
8
8
  };
9
9
  export function defaultSkillDirectories() {
10
- return [agentSkillDirectories.shared, agentSkillDirectories.linkwise].map(path => join(homedir(), path));
10
+ return [join(homedir(), agentSkillDirectories.linkwise)];
11
11
  }
@@ -1,5 +1,5 @@
1
- import type { Command } from '../cli/index.js';
1
+ import type { Application, Command } from '../cli/index.js';
2
2
  export interface SkillSyncPort {
3
3
  sync(directory: string | undefined, conflict: 'error' | 'replace', signal: AbortSignal): Promise<unknown>;
4
4
  }
5
- export declare function skillCommands(skill: SkillSyncPort, invoke: string): Record<string, Command>;
5
+ export declare function skillCommands(skill: SkillSyncPort, invoke: string, options?: Pick<Application, 'jsonOutput'>): Record<string, Command>;
@@ -1,14 +1,14 @@
1
- export function skillCommands(skill, invoke) {
1
+ export function skillCommands(skill, invoke, options = {}) {
2
2
  return {
3
3
  'install skill': {
4
4
  description: 'Install the bundled Skill for this version; synchronize registered directories on upgrade or rollback',
5
5
  effects: 'local',
6
6
  parameters: {
7
- 'skills-dir': { type: 'string', description: 'Skills root; overrides LXZ_SKILLS_DIR. First install targets ~/.agents/skills and ~/.linkwise/skills (Linkwise)' },
7
+ 'skills-dir': { type: 'string', description: 'Skills root; overrides LXZ_SKILLS_DIR. Defaults to registered roots or ~/.linkwise/skills on first install' },
8
8
  'skill-conflict': { type: 'string', description: 'Local changes: error keeps them; replace overwrites files managed by this CLI', choices: ['error', 'replace'], default: 'error' },
9
9
  },
10
10
  result: { type: 'object', required: ['installed'], properties: { installed: { type: 'array', items: { type: 'object', required: ['directory', 'version', 'action'], properties: { directory: { type: 'string' }, version: { type: 'string' }, action: { enum: ['installed', 'updated', 'unchanged'] } } } } } },
11
- examples: [invoke + ' install skill', invoke + ' install skill --skills-dir ./ceshi123/skills --json --non-interactive'],
11
+ examples: [invoke + ' install skill', invoke + ` install skill --skills-dir ./ceshi123/skills${options.jsonOutput === false || options.jsonOutput === 'schema' ? '' : ' --json'} --non-interactive`],
12
12
  format(result) {
13
13
  return result.installed.map((item) => `Agent Skill: ${item.directory}\nVersion: ${item.version}; ${{ installed: 'installed', updated: 'updated', unchanged: 'already current' }[item.action]}`).join('\n\n');
14
14
  },
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url';
6
6
  import { CliError, failure } from '../cli/index.js';
7
7
  import { loadSkill } from './bundle.js';
8
8
  import { SkillInstaller, legacyPackageName } from './installer.js';
9
- import { defaultSkillDirectories } from './agents.js';
9
+ import { agentSkillDirectories, defaultSkillDirectories } from './agents.js';
10
10
  export class BundledSkill {
11
11
  name;
12
12
  env;
@@ -25,7 +25,7 @@ export class BundledSkill {
25
25
  return { installer: new SkillInstaller(bundle), registry: registryOf(pkg.name), legacyRegistry: legacy && registryOf(legacy) };
26
26
  }
27
27
  directory(input) {
28
- const value = input ?? (this.env.LXZ_SKILLS_DIR || join(homedir(), '.agents', 'skills'));
28
+ const value = input ?? (this.env.LXZ_SKILLS_DIR || join(homedir(), agentSkillDirectories.linkwise));
29
29
  if (!value.trim())
30
30
  throw new CliError('INVALID_INPUT', 'The Skill installation directory must not be empty.', 'Pass --skills-dir <agent-skills-root>.');
31
31
  return resolve(value.replace(/^~(?=$|[\\/])/, () => homedir()));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tulcn/lxz",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "联小助 CLI 主程序与命令、授权、Skill 模块",
6
6
  "license": "UNLICENSED",
package/skills/SKILL.md CHANGED
@@ -5,21 +5,21 @@ description: 管理指定 CLI 的登录授权并检查运行环境
5
5
 
6
6
  # lxz
7
7
 
8
- 此说明对应 @tulcn/lxz@0.3.0。优先使用已安装且版本匹配的 lxz;未安装时,可用 `pnpm dlx @tulcn/lxz@<版本>`(`<版本>` 取上面的版本号)作为调用前缀。以下命令适用于 pwsh 和 bash,选择 dlx 时替换调用前缀。
8
+ 此说明对应 @tulcn/lxz@0.4.0。优先使用已安装且版本匹配的 lxz;未安装时,可用 `pnpm dlx @tulcn/lxz@<版本>`(`<版本>` 取上面的版本号)作为调用前缀。以下命令适用于 pwsh 和 bash,选择 dlx 时替换调用前缀。
9
9
 
10
10
  功能定位可按需读取同目录 [features.md](features.md);它由当前命令注册自动生成,再沿子命令帮助查询参数。
11
11
 
12
12
  ## 按任务查帮助
13
13
 
14
- 先核对版本,再从 `lxz -h` 查找所需功能,沿分组逐层查询。例如授权任务先看 `lxz auth -h`,再看选定子命令的 `-h`,读取其参数、选项与示例。帮助不发起登录、不执行操作;不要凭记忆补写参数。
14
+ 先核对版本,再从 `lxz -h` 查找所需功能,沿分组逐层查询。例如授权任务先看 `lxz auth -h`,再看选定子命令的 `-h`,按当前帮助提供参数。
15
15
 
16
16
  需要结构化的输入和结果约束时,在选定命令或分组后加 `--schema --json`,只获取该范围的契约;根入口 `lxz --schema --json` 返回全量,仅在需要总览时使用。完整命令参考 [commands.md](commands.md),按需定位相关命令。本说明只保留流程和判断规则,子功能细节以当前帮助为准。
17
17
 
18
- Agent 使用 `--non-interactive` 读取默认行数据,失败时读取 stderr。行数据使用 UTF-8,业务数据保留原文;需要程序解析时加 `--json`,先解析再读取字段,JSON 回执中的非 ASCII 字符以 `\uXXXX` 转义,解析后即为原文。
18
+ Agent 使用 `--non-interactive` 读取文本结果,查询契约时使用 `--schema --json`。输出按 UTF-8 解码,失败时读取 stderr 和退出码。
19
19
 
20
20
  ## 和用户沟通
21
21
 
22
- 用户关心业务结果,不关心命令怎么运行。回复只用业务说法,不提预览开关(如 dry-run)、命令名、参数、字段名、JSON、退出码或执行步骤;例如说“已经检查过,可以提交”,而不是“预览通过,返回 ok”。只有出错且需要用户处理时,才用业务说法说明原因和用户要做的事。授权链接和用户码例外,要原样写给用户。
22
+ 用业务语言说明任务结果、实际影响和下一步,例如“已经检查过,可以提交”。遇到需要用户处理的问题,说明原因及恢复方式。授权时原样提供链接和用户码。
23
23
 
24
24
  ## 授权与诊断
25
25
 
@@ -27,7 +27,7 @@ Agent 使用 `--non-interactive` 读取默认行数据,失败时读取 stderr
27
27
 
28
28
  默认连接正式授权中心;切换测试环境前确认目标地址、该环境的 CLI 登记和人员使用权,授权与令牌不跨环境复用。未知配置联系维护者,不猜测权限。状态查询和普通诊断不应自行触发登录。
29
29
 
30
- 仅在用户要求登录时发起授权,先查登录帮助。`lxz auth login --client-id <CLI 标识> --device-login --non-interactive --json` 几秒内返回 `status: pending`,批准在后台等待:把 `authorizationUrl` 和 `userCode` 原样写给用户。链接写成单独一行的 Markdown 链接,例如 `[打开授权页面](authorizationUrl)`,不要写成裸 URL,链接后面也不要紧跟文字或标点(聊天窗口会把它们当成链接的一部分,点开就打不开);用户码另起一行原样写出。`browserOpened` 为 true 时请用户切到已打开的浏览器核对用户码,为 false 时请用户在系统浏览器打开链接(联小助里请右键选择用系统浏览器打开)。然后在同一轮、不等用户回话,运行结果 `next` 中带同一 `--client-id` 的 `auth status --wait-seconds 170` 命令,批准后立即返回并继续用户原来的任务。仍未批准时按 `next` 询问用户;链接有效期间不重复登录,拒绝或到期后停止,不自动重复登录。只有能实时看到输出的终端才用 `--wait` 前台等待;需要在另一设备确认时加 `--no-browser`。
30
+ 仅在用户要求登录时发起授权,先查登录帮助。`lxz auth login --client-id <CLI 标识> --device-login --non-interactive` 几秒内以行数据返回待批准状态、授权链接和用户码,后台继续等待:把 `authorizationUrl` 和 `userCode` 原样写给用户。链接写成单独一行的 Markdown 链接,例如 `[打开授权页面](authorizationUrl)`;用户码另起一行原样写出。`browserOpened` 为 true 时请用户切到已打开的浏览器核对用户码,为 false 时请用户在系统浏览器打开链接(联小助里请右键选择用系统浏览器打开)。随即在同一轮运行结果 `next` 中带同一 `--client-id` 的 `auth status --wait-seconds 170` 命令,批准后立即返回并继续用户原来的任务。仍未批准时按 `next` 询问用户;链接有效期间不重复登录,拒绝或到期后停止,不自动重复登录。只有能实时看到输出的终端才用 `--wait` 前台等待;需要在另一设备确认时加 `--no-browser`。
31
31
 
32
32
  将后端失败原因与恢复提示如实告知用户。不得展示设备码、读取或复制令牌缓存,不在日志、结果或业务文档中记录访问令牌和刷新令牌。
33
33
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "lxz",
3
3
  "packageName": "@tulcn/lxz",
4
- "version": "0.3.0",
5
- "cliVersion": "0.3.0",
4
+ "version": "0.4.0",
5
+ "cliVersion": "0.4.0",
6
6
  "contractVersion": "1.0.0"
7
7
  }