@open-dy/interest-card-cli 0.1.0-beta.31 → 0.1.0-beta.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/browser-runtime/scripts/capture-feed-card.sh +42 -19
  2. package/browser-runtime/scripts/cdp-client.mjs +12 -3
  3. package/browser-runtime/scripts/cli.mjs +129 -11
  4. package/browser-runtime/scripts/inspect-preview-state.mjs +16 -2
  5. package/browser-runtime/scripts/preview-frame-action.mjs +26 -3
  6. package/browser-runtime/scripts/preview-session.mjs +27 -1
  7. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-aiuser-profile.md +6 -4
  8. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-aiuser-profile.md +6 -4
  9. package/card-skills/douyin-interest-card-capability/scripts/search-capabilities.mjs +7 -4
  10. package/card-skills/douyin-interest-card-cli/SKILL.md +10 -4
  11. package/card-skills/douyin-interest-card-generate/references/common/post-card-differences.md +29 -3
  12. package/card-skills/douyin-interest-card-generate/references/common/upgrade-to-post.md +28 -5
  13. package/card-skills/douyin-interest-card-generate/scripts/inspect-post-upgrade.mjs +630 -0
  14. package/dist/src/args.js +1 -0
  15. package/dist/src/card/binding.js +15 -7
  16. package/dist/src/card/browser-command.js +44 -0
  17. package/dist/src/card/dev-commands.js +33 -2
  18. package/dist/src/card/handlers.js +2 -1
  19. package/dist/src/card/sandbox-commands.js +12 -2
  20. package/dist/src/card-install.js +4 -0
  21. package/dist/src/cli.js +4 -2
  22. package/dist/src/error-hints.js +71 -0
  23. package/dist/src/help.js +1 -0
  24. package/dist/src/install-channel.js +52 -0
  25. package/dist/src/telemetry.js +25 -1
  26. package/dist/src/upgrade.js +37 -5
  27. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { renameReplacing } from '../platform-process.js';
3
+ import { renameReplacing, retryWhileBusy } from '../platform-process.js';
4
4
  import { CliError } from '../types.js';
5
5
  import { CARD_STATE_DIR } from './constants.js';
6
6
  import { isNotFound } from './snapshot.js';
@@ -59,17 +59,25 @@ export async function writeStateDirGitignore(root) {
59
59
  await fs.mkdir(path.join(root, CARD_STATE_DIR), { recursive: true });
60
60
  await fs.writeFile(path.join(root, CARD_STATE_DIR, '.gitignore'), '*\n');
61
61
  }
62
- /** Prevents sync, push, and resolve from writing the manifest concurrently. */
63
- export async function acquireLock(root) {
62
+ /**
63
+ * Prevents sync, push, and resolve from writing the manifest concurrently. On Windows a lock file
64
+ * another command just deleted, or one an antivirus scan holds open, briefly fails with EPERM /
65
+ * EBUSY instead of EEXIST, so those are retried rather than failing the command.
66
+ */
67
+ export async function acquireLock(root, ops = {}) {
68
+ const platform = ops.platform ?? process.platform;
69
+ const create = ops.create ?? ((file, content) => fs.writeFile(file, content, { flag: 'wx' }));
70
+ const remove = ops.remove ?? ((file) => fs.rm(file, { force: true }));
64
71
  const lockPath = path.join(root, CARD_STATE_DIR, LOCK_FILE);
72
+ const removeLock = () => retryWhileBusy(() => remove(lockPath), platform);
65
73
  const release = async () => {
66
- await fs.rm(lockPath, { force: true });
74
+ await removeLock();
67
75
  };
68
76
  await fs.mkdir(path.dirname(lockPath), { recursive: true });
69
77
  for (let attempt = 0; attempt < 3; attempt += 1) {
70
78
  try {
71
79
  // 'wx' fails when the file exists, so only one process can create the lock.
72
- await fs.writeFile(lockPath, String(process.pid), { flag: 'wx' });
80
+ await retryWhileBusy(() => create(lockPath, String(process.pid)), platform);
73
81
  return release;
74
82
  }
75
83
  catch (error) {
@@ -89,7 +97,7 @@ export async function acquireLock(root) {
89
97
  await new Promise(resolve => setTimeout(resolve, 100));
90
98
  continue;
91
99
  }
92
- await fs.rm(lockPath, { force: true });
100
+ await removeLock();
93
101
  }
94
102
  throw lockedError();
95
103
  }
@@ -115,6 +123,6 @@ async function readJson(filePath) {
115
123
  async function writeJsonAtomic(filePath, value) {
116
124
  await fs.mkdir(path.dirname(filePath), { recursive: true });
117
125
  const tmpPath = `${filePath}.${process.pid}.tmp`;
118
- await fs.writeFile(tmpPath, `${JSON.stringify(value, null, 2)}\n`);
126
+ await retryWhileBusy(() => fs.writeFile(tmpPath, `${JSON.stringify(value, null, 2)}\n`));
119
127
  await renameReplacing(tmpPath, filePath);
120
128
  }
@@ -5,6 +5,7 @@ import { parseCliArgs } from '../args.js';
5
5
  import { CliError } from '../types.js';
6
6
  import { loadBrowserRuntime } from './browser-runtime.js';
7
7
  import { CARD_STATE_DIR } from './constants.js';
8
+ import { restartDevServices } from './dev-commands.js';
8
9
  import { openAioClient } from './sandbox-commands.js';
9
10
  /**
10
11
  * `interest-card-cli browser <verb> ...` runs the browser entry (scripts/cli.mjs) that ships with
@@ -148,6 +149,20 @@ export function parseBrowserOutput(stdout) {
148
149
  }
149
150
  return { receipt, exitCode: exitMatch ? Number(exitMatch[1]) : undefined, finished: markerAt >= 0 };
150
151
  }
152
+ const DEV_NOT_READY = 'DEV_NOT_READY';
153
+ /** A session that could not be resumed; the reason is in the error text. */
154
+ const RESUME_BLOCKED = 'RESUME_BLOCKED';
155
+ /** True when the receipt fails because the sandbox dev services are not ready. */
156
+ export function devNotReady(receipt) {
157
+ return (receipt?.code === DEV_NOT_READY ||
158
+ (receipt?.code === RESUME_BLOCKED && typeof receipt.error === 'string' && receipt.error.includes('dev service not ready')));
159
+ }
160
+ const DEV_RESTART_TIMEOUT_SEC = 180;
161
+ const DEV_NOT_READY_HINT = 'The sandbox dev server is not ready. Run `interest-card-cli logs --errors --json` to see why, fix the code if it is a code error, push, then `interest-card-cli dev restart --json` and retry the browser command. Do not run pnpm dev yourself.';
162
+ /** dev/status said the dev script is not running at all, as opposed to running but not ready yet. */
163
+ export function devScriptStopped(receipt) {
164
+ return typeof receipt.error === 'string' && receipt.error.includes('scriptRunning=false');
165
+ }
151
166
  export function failureReceipt(verb, code, error, extra = {}) {
152
167
  return { protocol: BROWSER_PROTOCOL, ok: false, code, verb: verb ?? null, session: null, page: null, expect: [], data: {}, artifacts: [], error, ...extra };
153
168
  }
@@ -235,6 +250,35 @@ export async function runBrowserCommand(argv, globalArgv = [], deps = {}) {
235
250
  };
236
251
  }
237
252
  }
253
+ let devRestart;
254
+ if (receipt && devNotReady(receipt) && devScriptStopped(receipt)) {
255
+ // The sandbox dev services are not running (休眠恢复、沙箱重建): start them the way
256
+ // `dev restart` does, then run the verb once more. The browser entry's own advice
257
+ // (`pnpm dev` in the sandbox) is not something a local agent can run.
258
+ try {
259
+ const restart = await (deps.restartDev ?? restartDevServices)(client, { wait: true, timeoutSec: DEV_RESTART_TIMEOUT_SEC });
260
+ devRestart = { ok: true, waitedMs: restart.waitedMs };
261
+ }
262
+ catch (error) {
263
+ const cliError = error instanceof CliError ? error : undefined;
264
+ const details = (cliError?.details ?? {});
265
+ return {
266
+ receipt: failureReceipt(verb, DEV_NOT_READY, error instanceof Error ? error.message : String(error), {
267
+ hint: typeof details.hint === 'string' ? details.hint : DEV_NOT_READY_HINT,
268
+ devRestart: { ok: false, code: cliError?.code ?? 'ERROR', ...(Array.isArray(details.errors) ? { errors: details.errors.slice(-5) } : {}) },
269
+ }),
270
+ exitCode: EXIT.blocked,
271
+ };
272
+ }
273
+ result = await exec();
274
+ ({ receipt, exitCode, finished } = parseBrowserOutput(result.stdout));
275
+ }
276
+ if (receipt && devNotReady(receipt) && !receipt.hint) {
277
+ receipt.hint = DEV_NOT_READY_HINT;
278
+ }
279
+ if (receipt && devRestart) {
280
+ receipt.devRestart = devRestart;
281
+ }
238
282
  if (!receipt) {
239
283
  return {
240
284
  receipt: failureReceipt(verb, 'BROWSER_NO_RECEIPT', 'The sandbox browser command returned no receipt.', {
@@ -15,6 +15,16 @@ const STOPPED_POLLS_BEFORE_FAIL = 2;
15
15
  const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
16
16
  const PACKAGE_VERSION = /^[A-Za-z0-9._^~*+-]+$/;
17
17
  const NOT_READY_HINT = 'Run `interest-card-cli logs --errors --json` to find why the dev server did not come up, fix the code, push, and run `interest-card-cli dev restart --json` again.';
18
+ /** The sandbox database did not start: the platform's side, not the card code. */
19
+ const DATABASE_INIT_FAILED = /database initialization failed/i;
20
+ const DATABASE_INIT_HINT = 'The sandbox database failed to start; this is on the platform side, not in the card code. Run `interest-card-cli dev restart --json` once more; if it fails the same way, open the project page with `interest-card-cli open` so the platform rebuilds the sandbox, or ask the platform Agent with `interest-card-cli reply`, instead of changing code.';
21
+ /** A build that cannot find an imported file or package: the dev server never comes up until the code changes. */
22
+ export const BUILD_RESOLVE_ERROR = /Could not load .*ENOENT|Could not resolve ["'`]|Failed to resolve import|Cannot find module ["'`]|Module not found/i;
23
+ const BUILD_RESOLVE_HINT = 'The build cannot find a file or package that the code imports (see the last error). Restarting will not help: fix that import (a missing file, a wrong path or alias, or a package to add with `interest-card-cli deps add`), push, then run `interest-card-cli dev restart --json`.';
24
+ /** How long a build error must stand while nothing is ready before the wait gives up early. */
25
+ const BUILD_ERROR_GRACE_MS = 30_000;
26
+ /** Polls between two log reads while waiting; a log read is one more sandbox call. */
27
+ const LOG_CHECK_EVERY_POLLS = 5;
18
28
  const SERVER_UNREACHABLE_HINT = 'microapp_server did not answer inside the sandbox. Open the project page with `interest-card-cli open` so the platform wakes the sandbox, then retry.';
19
29
  /**
20
30
  * Fixed microapp_server calls; nothing from the command line reaches the shell.
@@ -79,7 +89,9 @@ export async function restartDevServices(client, options) {
79
89
  const deadline = startedAt + options.timeoutSec * 1000;
80
90
  let dev;
81
91
  let stoppedPolls = 0;
92
+ let polls = 0;
82
93
  while (Date.now() < deadline) {
94
+ polls += 1;
83
95
  await new Promise(resolve => setTimeout(resolve, READY_POLL_MS));
84
96
  dev = await readDevStatus(client).catch(() => undefined);
85
97
  if (isDevReady(dev)) {
@@ -90,19 +102,38 @@ export async function restartDevServices(client, options) {
90
102
  if (stoppedPolls >= STOPPED_POLLS_BEFORE_FAIL) {
91
103
  throw await devNotReadyError(client, dev, 'Sandbox dev services exited before they were ready.');
92
104
  }
105
+ // A build that cannot resolve an import never comes up: say so now instead of after the timeout.
106
+ if (Date.now() - startedAt >= BUILD_ERROR_GRACE_MS && polls % LOG_CHECK_EVERY_POLLS === 0) {
107
+ const errors = await readLastRunErrors(client);
108
+ if (errors.some(line => BUILD_RESOLVE_ERROR.test(line))) {
109
+ throw notReadyError(dev, errors, 'Sandbox dev services cannot build the code.');
110
+ }
111
+ }
93
112
  }
94
113
  throw await devNotReadyError(client, dev, `Sandbox dev services were not ready after ${options.timeoutSec}s.`);
95
114
  }
96
115
  /** Puts the last error lines of the run into the error, so the reason is not one more command away. */
97
116
  async function devNotReadyError(client, dev, message) {
98
- const errors = await readLastRunErrors(client);
117
+ return notReadyError(dev, await readLastRunErrors(client), message);
118
+ }
119
+ function notReadyError(dev, errors, message) {
99
120
  return new CliError(devNotReadyMessage(message, errors), 'CARD_DEV_NOT_READY', {
100
121
  dev: dev ?? null,
101
122
  logFile: SANDBOX_DEV_LOG,
102
123
  errors,
103
- hint: NOT_READY_HINT,
124
+ hint: devNotReadyHint(errors),
104
125
  });
105
126
  }
127
+ /** Points at the platform for a database that would not start and at the import for a build that cannot resolve one. */
128
+ export function devNotReadyHint(errors) {
129
+ if (errors.some(line => DATABASE_INIT_FAILED.test(line))) {
130
+ return DATABASE_INIT_HINT;
131
+ }
132
+ if (errors.some(line => BUILD_RESOLVE_ERROR.test(line))) {
133
+ return BUILD_RESOLVE_HINT;
134
+ }
135
+ return NOT_READY_HINT;
136
+ }
106
137
  export function devNotReadyMessage(message, errors) {
107
138
  const last = errors.at(-1);
108
139
  return last ? `${message} Last error: ${last.length > 300 ? `${last.slice(0, 300)}…` : last}` : message;
@@ -1,3 +1,4 @@
1
+ import { unknownCommandError } from '../error-hints.js';
1
2
  import fs from 'node:fs/promises';
2
3
  import path from 'node:path';
3
4
  import { getString } from '../cli-helpers.js';
@@ -133,7 +134,7 @@ async function dispatchCard(parsed) {
133
134
  printText(help);
134
135
  }
135
136
  if (subcommand) {
136
- return Promise.reject(new CliError(`Unknown card command: ${subcommand}`, 'UNKNOWN_COMMAND'));
137
+ return Promise.reject(unknownCommandError(subcommand, 'card command'));
137
138
  }
138
139
  return { ok: true, command: 'card', data: { help } };
139
140
  }
@@ -43,6 +43,15 @@ export function buildVerifyCommand(full) {
43
43
  `else echo "${VERIFY_ENTRY_MISSING_MARKER}" >&2; exit ${VERIFY_ENTRY_MISSING_EXIT_CODE}; fi`,
44
44
  ].join(' ');
45
45
  }
46
+ /**
47
+ * The end of a failed verify's output: stderr, or stdout when a check printed its reason there only.
48
+ * Reported in place of the shorter stderr detail, so the failing field survives the cut.
49
+ */
50
+ export function verifyFailureOutputTail(stderr, stdout) {
51
+ const output = stderr?.trim() || stdout?.trim();
52
+ return output ? output.slice(-VERIFY_OUTPUT_TAIL_CHARS) : undefined;
53
+ }
54
+ const VERIFY_OUTPUT_TAIL_CHARS = 2000;
46
55
  export function verifyFailureHint(exitCode, stderr) {
47
56
  if (exitCode === VERIFY_ENTRY_MISSING_EXIT_CODE && stderr.includes(VERIFY_ENTRY_MISSING_MARKER)) {
48
57
  return 'The sandbox project has neither node_modules/.bin/vibecoding nor scripts/verify.mjs. A sandbox restored from sleep has no dependencies until its dev server starts: run `interest-card-cli dev restart --json`, which waits until the services are ready, then retry. If dependencies are installed and it still fails, the project template is outdated: ask the platform Agent with `interest-card-cli reply` to migrate to the current template. Do not run pnpm verify yourself.';
@@ -73,9 +82,10 @@ export async function handleCardVerify(parsed) {
73
82
  const data = { conversationId, command, cwd: CARD_APP_DIR, full, ...result };
74
83
  if (result.status !== 'completed' || result.exitCode !== 0) {
75
84
  const hint = verifyFailureHint(result.exitCode, result.stderr);
85
+ const outputTail = verifyFailureOutputTail(result.stderr, result.stdout);
76
86
  throw new CliError(`Sandbox verify ${result.status === 'completed' ? `exited with ${result.exitCode}` : result.status}.`, 'CARD_VERIFY_FAILED', parsed.options.json
77
- ? { ...data, hint }
78
- : { exitCode: result.exitCode, status: result.status, full, hint });
87
+ ? { ...data, hint, outputTail }
88
+ : { exitCode: result.exitCode, status: result.status, full, hint, outputTail });
79
89
  }
80
90
  return { ok: true, command: 'card-verify', data };
81
91
  }
@@ -3,6 +3,7 @@ import { existsSync, readFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { installGlobalSkills } from './card/global-skills.js';
5
5
  import { getString, getStringList } from './cli-helpers.js';
6
+ import { resolveInstallChannel } from './install-channel.js';
6
7
  import { handleLogin } from './login-handlers.js';
7
8
  import { commandInvocation } from './platform-process.js';
8
9
  import { compareVersions } from './semver.js';
@@ -20,6 +21,8 @@ const NEXT_PROMPTS = ['列出我最近改过的兴趣卡(带链接),问我
20
21
  export async function handleCardInstall(parsed) {
21
22
  const json = Boolean(parsed.options.json);
22
23
  const log = (line) => (json ? process.stderr : process.stdout).write(`${line}\n`);
24
+ // Saved first, so an install that fails later is still counted for its channel.
25
+ const channel = resolveInstallChannel(getString(parsed, 'channel'));
23
26
  log('Setting up interest-card-cli for interest cards...');
24
27
  const cli = await ensureGlobalCli(json, log);
25
28
  let skills;
@@ -73,6 +76,7 @@ export async function handleCardInstall(parsed) {
73
76
  login,
74
77
  entrySkill: skills?.entrySkill,
75
78
  nextPrompts: NEXT_PROMPTS,
79
+ channel: channel ?? null,
76
80
  },
77
81
  };
78
82
  }
package/dist/src/cli.js CHANGED
@@ -17,6 +17,7 @@ import { CLI_SOURCE_HEADERS, invalidLaneEnv } from './request-source.js';
17
17
  import { handleWhoami } from './current-user.js';
18
18
  import { printJson, printText } from './output.js';
19
19
  import { trackCommand } from './telemetry.js';
20
+ import { describeNativeError, unknownCommandError } from './error-hints.js';
20
21
  import { CliError, getCliVersion } from './types.js';
21
22
  export async function runCli(argv) {
22
23
  if (isUpdateRefreshProcess(argv)) {
@@ -44,7 +45,8 @@ export async function runCli(argv) {
44
45
  printJson(result);
45
46
  }
46
47
  }
47
- catch (error) {
48
+ catch (raw) {
49
+ const error = describeNativeError(raw);
48
50
  await telemetry.fail(error);
49
51
  handleError(error, Boolean(parsed.options.json));
50
52
  }
@@ -124,7 +126,7 @@ function runCommand(parsed) {
124
126
  case 'install':
125
127
  return handleCardInstall(parsed);
126
128
  default:
127
- throw new CliError(`Unknown command: ${parsed.command}`, 'UNKNOWN_COMMAND');
129
+ throw unknownCommandError(parsed.command);
128
130
  }
129
131
  }
130
132
  function handleVersion(parsed) {
@@ -0,0 +1,71 @@
1
+ import { CliError } from './types.js';
2
+ const COMMAND_HINTS = {
3
+ platform: '`--platform creator` is an option of login: interest-card-cli login --platform creator --json',
4
+ auth: 'Sign in with: interest-card-cli login --platform creator --json. Check the account with: interest-card-cli whoami --json',
5
+ signin: 'Sign in with: interest-card-cli login --platform creator --json',
6
+ info: 'Use `interest-card-cli whoami --json` for the account, or `interest-card-cli status --json` inside a pulled project.',
7
+ me: 'Use: interest-card-cli whoami --json',
8
+ user: 'Use: interest-card-cli whoami --json',
9
+ projects: 'Use: interest-card-cli list --json',
10
+ ls: 'Use: interest-card-cli list --json',
11
+ update: 'Use `interest-card-cli upgrade --json` to update the CLI, or `interest-card-cli push --json` to sync code.',
12
+ sync: 'Use `interest-card-cli push --json` to sync local changes to the sandbox.',
13
+ screenshot: 'Screenshots are browser verbs: interest-card-cli browser snap --area face --name face',
14
+ init: 'Use `interest-card-cli create --blank --json`, then `interest-card-cli pull <projectId> <dir> --json`.',
15
+ new: 'Use `interest-card-cli create --blank --json`, then `interest-card-cli pull <projectId> <dir> --json`.',
16
+ };
17
+ /** Why `name` is not a command, and what to run instead. */
18
+ export function unknownCommandHint(name) {
19
+ const trimmed = name.trim();
20
+ const words = trimmed.split(/\s+/u);
21
+ if (words.length > 1) {
22
+ return `The command and its options were passed as one quoted argument. Pass them separately: interest-card-cli ${words.join(' ')}`;
23
+ }
24
+ if (trimmed.startsWith('@') || trimmed.includes('/')) {
25
+ return `"${trimmed}" is the npm package name, not a command. After \`npx -y ${trimmed.startsWith('@') ? trimmed : '@open-dy/interest-card-cli@beta'}\` put the command, e.g. install --json; once installed, run interest-card-cli <command>.`;
26
+ }
27
+ if (trimmed === 'interest-card-cli') {
28
+ return 'The program name was repeated. Run: interest-card-cli <command>';
29
+ }
30
+ if (/^\d+$/u.test(trimmed)) {
31
+ return `"${trimmed}" looks like a project id. Put a command before it, e.g. interest-card-cli pull ${trimmed} <dir> --json`;
32
+ }
33
+ return COMMAND_HINTS[trimmed.toLowerCase()] ?? 'Run `interest-card-cli help` for the list of commands.';
34
+ }
35
+ export function unknownCommandError(name, kind = 'command') {
36
+ return new CliError(`Unknown ${kind}: ${name}`, 'UNKNOWN_COMMAND', { hint: unknownCommandHint(name) });
37
+ }
38
+ const ACCESS_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
39
+ /**
40
+ * Gives Node's own failures a code and a next step. A dropped connection outside the wrapped API
41
+ * calls, and a file the system refuses to open, would otherwise reach the agent as a bare
42
+ * `fetch failed` or `EPERM` with code `ERROR`.
43
+ */
44
+ export function describeNativeError(error) {
45
+ if (error instanceof CliError || !(error instanceof Error)) {
46
+ return error;
47
+ }
48
+ const cause = error.cause;
49
+ if (error instanceof TypeError && error.message === 'fetch failed') {
50
+ const causeCode = typeof cause?.code === 'string' ? cause.code : undefined;
51
+ const reason = cause instanceof Error ? cause.message.split(' (attempted')[0] : undefined;
52
+ return new CliError(`The network request failed${reason ? `: ${reason}` : ''}.`, 'NETWORK_ERROR', {
53
+ ...(reason ? { cause: reason } : {}),
54
+ ...(causeCode ? { causeCode } : {}),
55
+ hint: 'The connection to the platform dropped or timed out; nothing is wrong with the project. Run the same command again. If it keeps failing, check the network, proxy or VPN.',
56
+ });
57
+ }
58
+ const { code, path: filePath, syscall } = error;
59
+ if (code && ACCESS_CODES.has(code) && typeof filePath === 'string') {
60
+ const inProject = /[\\/]\.dycard[\\/]/u.test(filePath);
61
+ return new CliError(`The system refused access to ${filePath} (${code}${syscall ? ` on ${syscall}` : ''}).`, 'FILE_ACCESS_DENIED', {
62
+ path: filePath,
63
+ causeCode: code,
64
+ ...(syscall ? { syscall } : {}),
65
+ hint: inProject
66
+ ? 'Another process holds this file: a second interest-card-cli command still running in this project, a sync client or antivirus. Run one command at a time in a project and run this one again.'
67
+ : 'The CLI cannot write its own data directory. If commands run inside a sandbox, allow writes to this path; otherwise set DOUYIN_AI_CONFIG to a config file path in a writable directory and run the command again.',
68
+ });
69
+ }
70
+ return error;
71
+ }
package/dist/src/help.js CHANGED
@@ -39,6 +39,7 @@ Options:
39
39
  repeatable
40
40
  --skip-skills Do not install skills
41
41
  --skip-login Do not log in
42
+ --channel <code> Where the install guide link came from (its c= value)
42
43
  --qr Log in by scanning a QR code with Douyin App
43
44
  --browser-headed Log in through a visible browser window
44
45
  -j, --json Print one JSON document; progress goes to stderr
@@ -0,0 +1,52 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { resolveConfigPath } from './config.js';
4
+ import { DEFAULT_CONFIG_DIR } from './types.js';
5
+ const CHANNEL_FILE = 'install-channel';
6
+ const CHANNEL_PATTERN = /^[a-z0-9][a-z0-9_-]{0,31}$/;
7
+ /**
8
+ * The promotion channel an install came from: the `c` query of the guide link the creator was
9
+ * given, passed on as `install --channel`. Lower-cased; `undefined` when it is not a plain code,
10
+ * so a mistyped value never fails an install.
11
+ */
12
+ export function normalizeChannel(value) {
13
+ const channel = typeof value === 'string' ? value.trim().toLowerCase() : '';
14
+ return CHANNEL_PATTERN.test(channel) ? channel : undefined;
15
+ }
16
+ /** The channel saved on this machine, kept beside the CLI config. */
17
+ export function readInstallChannel(dir = resolveConfigPath(DEFAULT_CONFIG_DIR)) {
18
+ try {
19
+ return normalizeChannel(fs.readFileSync(path.join(dir, CHANNEL_FILE), 'utf8'));
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ }
25
+ /**
26
+ * Saves the channel of the first install and returns the one in effect. A later install from
27
+ * another channel keeps the first: reports count where a creator first came from.
28
+ */
29
+ export function rememberInstallChannel(value, dir = resolveConfigPath(DEFAULT_CONFIG_DIR)) {
30
+ const saved = readInstallChannel(dir);
31
+ const channel = normalizeChannel(value);
32
+ if (saved || !channel) {
33
+ return saved;
34
+ }
35
+ try {
36
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
37
+ fs.writeFileSync(path.join(dir, CHANNEL_FILE), `${channel}\n`, { mode: 0o600 });
38
+ }
39
+ catch {
40
+ // An unwritable home still reports this run through the returned value.
41
+ }
42
+ return channel;
43
+ }
44
+ /** Set by a host that ships the CLI preinstalled, where no one runs `install --channel`. */
45
+ export const CHANNEL_ENV = 'INTEREST_CARD_CLI_CHANNEL';
46
+ /**
47
+ * The channel in effect for this run. A channel already saved wins, then `--channel`, then the
48
+ * host's environment variable; whichever is used first is saved for later runs.
49
+ */
50
+ export function resolveInstallChannel(explicit, env = process.env, dir = resolveConfigPath(DEFAULT_CONFIG_DIR)) {
51
+ return rememberInstallChannel(normalizeChannel(explicit) ?? env[CHANNEL_ENV], dir);
52
+ }
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
+ import { isCreatorLoginSession } from './creator-login-session.js';
7
8
  import { DETACHED_WORKER_OPTIONS } from './platform-process.js';
8
9
  import { readBinding, findProjectRoot } from './card/binding.js';
9
10
  import { CARD_PROJECT_PAGE_URL } from './card/constants.js';
@@ -14,6 +15,7 @@ import { isCreatorPlatform, isExternalPlatform } from './platform.js';
14
15
  import { laneHeaders } from './request-source.js';
15
16
  import { notedTelemetryProject } from './telemetry-project.js';
16
17
  import { notedSessionCheckRetries } from './telemetry-session.js';
18
+ import { resolveInstallChannel } from './install-channel.js';
17
19
  import { CliError, DEFAULT_CONFIG_DIR } from './types.js';
18
20
  import { getCliVersion } from './version.js';
19
21
  /**
@@ -63,8 +65,17 @@ export function isTelemetryDisabled(env = process.env) {
63
65
  return Boolean(env.NODE_TEST_CONTEXT) && !resolveSendOptions(env).channelDomain;
64
66
  }
65
67
  /** `card sync` -> `card.sync`; unknown shapes collapse so positionals (prompts, paths) never leak. */
68
+ /**
69
+ * The background process a link or QR login leaves polling for the creator is its own command: it
70
+ * ends with DEVICE_AUTH_EXPIRED whenever the creator does not confirm in time, and counting that
71
+ * as a failed `login` hides the logins that really failed.
72
+ */
73
+ export const LOGIN_WORKER_COMMAND = 'login.worker';
66
74
  export function telemetryCommandName(parsed) {
67
75
  const command = SUBCOMMAND_PATTERN.test(parsed.command) ? parsed.command : 'unknown';
76
+ if (command === 'login' && parsed.options && isCreatorLoginSession(parsed)) {
77
+ return LOGIN_WORKER_COMMAND;
78
+ }
68
79
  if (command !== 'card') {
69
80
  return command;
70
81
  }
@@ -82,6 +93,12 @@ export function telemetryLoginMethod(parsed) {
82
93
  }
83
94
  const ERROR_MESSAGE_MAX_CHARS = 300;
84
95
  const ERROR_DETAIL_MAX_CHARS = 200;
96
+ /**
97
+ * `outputTail` is the end of a failed check's output (verify), which names the failing field after a
98
+ * long error list: it gets more room than other details, and replaces the shorter `stderr` it repeats.
99
+ */
100
+ const OUTPUT_DETAIL_KEYS = new Set(['outputTail']);
101
+ const OUTPUT_DETAIL_MAX_CHARS = 600;
85
102
  const ERROR_TOTAL_MAX_CHARS = 1000;
86
103
  const LOGID_PATTERN = /^[A-Za-z0-9]{8,64}$/;
87
104
  /** Applied in order. What is left is for finding the cause, not for reading someone's machine. */
@@ -132,6 +149,7 @@ const ERROR_DETAIL_KEYS = [
132
149
  'msg',
133
150
  'cause',
134
151
  'stderr',
152
+ 'outputTail',
135
153
  ];
136
154
  /** A failed response's JSON body: only what says why it failed. */
137
155
  const ERROR_BODY_KEYS = ['code', 'error', 'error_code', 'err_no', 'status_code', 'message', 'msg', 'err_msg'];
@@ -221,7 +239,11 @@ export function telemetryErrorMessage(error, home = os.homedir()) {
221
239
  const seen = new Set();
222
240
  const parts = [];
223
241
  for (const [key, raw] of pairs) {
224
- const value = cleanErrorText(raw, home, ERROR_DETAIL_MAX_CHARS, key === 'stderr');
242
+ if (key === 'stderr' && detailText(details.outputTail)) {
243
+ continue;
244
+ }
245
+ const output = OUTPUT_DETAIL_KEYS.has(key);
246
+ const value = cleanErrorText(raw, home, output ? OUTPUT_DETAIL_MAX_CHARS : ERROR_DETAIL_MAX_CHARS, output || key === 'stderr');
225
247
  // The message often repeats a detail (the server's `msg`, an exit code): say it once.
226
248
  if (!value || seen.has(key) || message.includes(value) && value.length > 3) {
227
249
  continue;
@@ -299,6 +321,7 @@ export function buildTelemetryJob(telemetry, identity, options = {}) {
299
321
  session_check_retries: Math.max(0, Math.round(telemetry.sessionCheckRetries || 0)),
300
322
  user_id: identity.userId || '',
301
323
  cli_device_id: identity.deviceId,
324
+ install_channel: identity.channel || '',
302
325
  client: 'interest_card_cli',
303
326
  cli_version: version,
304
327
  node_version: process.versions.node,
@@ -423,6 +446,7 @@ async function resolveIdentity(parsed) {
423
446
  platform: config ? telemetryPlatform(getConfigBaseUrl(config)) : undefined,
424
447
  userId: telemetryUserId(config),
425
448
  deviceId: readDeviceId(),
449
+ channel: resolveInstallChannel(),
426
450
  authType: config ? (config.token_type === 'Bearer' ? 'token' : 'cookie') : undefined,
427
451
  };
428
452
  }
@@ -161,16 +161,38 @@ export async function installGlobalPackage(version, json) {
161
161
  '--registry',
162
162
  registry,
163
163
  scopeRegistryArg(registry),
164
- ], json);
164
+ ], json, true);
165
165
  }
166
166
  catch (error) {
167
167
  const cause = failureCause(error);
168
+ const stderr = capturedStderr(error);
168
169
  throw new CliError(`Could not install ${CLI_PACKAGE_NAME}@${version}.`, 'CARD_UPGRADE_FAILED', {
169
170
  cause,
170
171
  installCommand: installCommand(version, registry),
172
+ ...(stderr ? { stderr } : {}),
173
+ hint: installFailureHint(stderr),
171
174
  });
172
175
  }
173
176
  }
177
+ const NPM_PERMISSION_ERROR = /\b(EACCES|EPERM|EROFS)\b|permission denied|operation not permitted|read-only file system/i;
178
+ const NPM_NETWORK_ERROR = /\b(ENOTFOUND|ETIMEDOUT|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ENETUNREACH|ERR_SOCKET_TIMEOUT)\b|network (request|error|timeout)|socket hang up/i;
179
+ /** What to do next after `npm install -g` failed, judged from what npm printed. */
180
+ export function installFailureHint(stderr) {
181
+ const text = stderr ?? '';
182
+ if (NPM_PERMISSION_ERROR.test(text)) {
183
+ return 'npm could not write to its global directory. Agents in a sandbox: rerun this command with write access outside the sandbox. Otherwise fix the permissions of the npm global prefix, or run installCommand yourself.';
184
+ }
185
+ if (NPM_NETWORK_ERROR.test(text)) {
186
+ return 'npm could not reach the registry. Agents in a sandbox: rerun this command with network access. Otherwise check the network or npm proxy settings.';
187
+ }
188
+ return 'See stderr for what npm reported. Agents in a sandbox: rerun this command with network access and write access outside the sandbox. Otherwise run installCommand yourself.';
189
+ }
190
+ const STDERR_TAIL_CHARS = 2000;
191
+ /** The end of what a failed child printed to stderr, when it was captured. */
192
+ function capturedStderr(error) {
193
+ const stderr = error instanceof CliError ? error.details?.stderr : undefined;
194
+ return typeof stderr === 'string' && stderr.trim() ? stderr.trim() : undefined;
195
+ }
174
196
  async function refreshProjectSkills(parsed, useInstalledCli = false, json = false) {
175
197
  const root = await findProjectRoot(getString(parsed, 'dir') || process.cwd()).catch(() => undefined);
176
198
  if (!root) {
@@ -208,13 +230,23 @@ function runCapture(command, args) {
208
230
  });
209
231
  });
210
232
  }
211
- /** With --json, child output goes to stderr so stdout stays one JSON document. */
212
- function runInherit(command, args, json = false) {
233
+ /**
234
+ * With --json, child output goes to stderr so stdout stays one JSON document.
235
+ * With captureStderr, the child's stderr is still shown as it arrives, and its tail is kept
236
+ * on the error (details.stderr) so a failure can say what the child reported.
237
+ */
238
+ export function runInherit(command, args, json = false, captureStderr = false) {
213
239
  return new Promise((resolve, reject) => {
214
240
  const run = commandInvocation(command, args);
241
+ const stderrTarget = captureStderr ? 'pipe' : json ? 2 : 'inherit';
215
242
  const child = spawn(run.command, run.args, {
216
243
  ...run.options,
217
- stdio: json ? ['ignore', 2, 2] : 'inherit',
244
+ stdio: json ? ['ignore', 2, stderrTarget] : ['inherit', 'inherit', stderrTarget],
245
+ });
246
+ let stderrTail = '';
247
+ child.stderr?.on('data', chunk => {
248
+ process.stderr.write(chunk);
249
+ stderrTail = (stderrTail + String(chunk)).slice(-STDERR_TAIL_CHARS);
218
250
  });
219
251
  child.on('error', error => {
220
252
  reject(new CliError(`Failed to run ${command}.`, 'CARD_UPGRADE_FAILED', {
@@ -226,7 +258,7 @@ function runInherit(command, args, json = false) {
226
258
  resolve();
227
259
  return;
228
260
  }
229
- reject(new CliError(`${command} exited with ${code}.`, 'CARD_UPGRADE_FAILED'));
261
+ reject(new CliError(`${command} exited with ${code}.`, 'CARD_UPGRADE_FAILED', stderrTail.trim() ? { stderr: stderrTail } : undefined));
230
262
  });
231
263
  });
232
264
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-dy/interest-card-cli",
3
- "version": "0.1.0-beta.31",
3
+ "version": "0.1.0-beta.33",
4
4
  "description": "Pull, edit and sync Douyin interest card projects locally with any AI agent",
5
5
  "private": false,
6
6
  "type": "module",