@open-dy/interest-card-cli 0.1.0-beta.32 → 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.
@@ -32,6 +32,8 @@ browser_version=""
32
32
  webgl_status="{}"
33
33
  CONTROL_FAILED="false"
34
34
  COMMAND_TIMEOUT_MS="15000"
35
+ WEBGL_RPC_TIMEOUT_MS="15000"
36
+ WEBGL_BUSY_HINT='The card renders WebGL with software rendering (SwiftShader) in this sandbox Chrome, which can keep the page main thread busy past the CDP timeout; this is not a card code error. Retry once; if it keeps timing out, check the card on a real device (interest-card-cli preview), or reduce continuous rendering such as real-time shadows, full-screen particles and pixel ratio.'
35
37
 
36
38
  agent-browser() {
37
39
  node "$SCRIPT_DIR/run-browser-command.mjs" --timeout-ms "$COMMAND_TIMEOUT_MS" -- "$@"
@@ -247,6 +249,10 @@ print_diagnostics() {
247
249
  agent-browser --session "$SESSION_NAME" network requests >&2 || true
248
250
  }
249
251
 
252
+ project_uses_webgl() {
253
+ [[ "$(printf '%s' "$webgl_status" | jq -r '.projectUsesWebgl == true' 2>/dev/null)" == "true" ]]
254
+ }
255
+
250
256
  inspect_current() {
251
257
  local inspection_exit=0
252
258
  local remaining_ms="${1:-10000}"
@@ -264,6 +270,9 @@ inspect_current() {
264
270
  ERROR_SUMMARY="$(printf '%s' "$inspection" | jq -r '.error // "Preview inspection failed"')"
265
271
  printf 'Preview inspection failed: %s\n' "$ERROR_SUMMARY" >&2
266
272
  if [[ "$(printf '%s' "$inspection" | jq -r '.code // ""')" =~ ^CDP_ ]]; then
273
+ if [[ "$(printf '%s' "$inspection" | jq -r '.code // ""')" == "CDP_TIMEOUT" ]] && project_uses_webgl; then
274
+ ERROR_SUMMARY="${ERROR_SUMMARY}. ${WEBGL_BUSY_HINT}"
275
+ fi
267
276
  CONTROL_FAILED="true"
268
277
  preview_state="unknown"
269
278
  exit 13
@@ -349,6 +358,10 @@ browser_version="$(agent-browser --version 2>/dev/null | grep -Eo '[0-9]+\.[0-9]
349
358
  # only reports. A project without WebGL returns at once without touching the browser.
350
359
  webgl_status="$(node "$SCRIPT_DIR/ensure-webgl.mjs" --enable --if-idle --project-root "$PROJECT_ROOT" --timeout-ms 30000 2>/dev/null || true)"
351
360
  printf '%s' "$webgl_status" | jq -e 'type == "object"' >/dev/null 2>&1 || webgl_status="{}"
361
+ # Software-rendered WebGL can hold the page main thread for seconds; give each CDP call a longer window unless set.
362
+ if project_uses_webgl && [[ -z "${ICB_CDP_RPC_TIMEOUT_MS:-}" ]]; then
363
+ export ICB_CDP_RPC_TIMEOUT_MS="$WEBGL_RPC_TIMEOUT_MS"
364
+ fi
352
365
  case "$(printf '%s' "$webgl_status" | jq -r '.status // ""')" in
353
366
  enabled)
354
367
  printf 'WebGL enabled for this sandbox Chrome (one restart while no page was open).\n' >&2 ;;
@@ -458,7 +471,12 @@ if [[ "$preview_state" == 'loading' ]]; then
458
471
  fi
459
472
 
460
473
  if [[ "$preview_state" != 'ready' || "$ready_passes" -lt 2 ]]; then
461
- ERROR_SUMMARY="Could not verify two ready OpenCard inspections before the deadline"
474
+ # Online (TEA): the bare summary did not say whether the card stayed blank or kept changing.
475
+ if [[ "$preview_state" == 'ready' ]]; then
476
+ ERROR_SUMMARY="Could not verify two ready OpenCard inspections before the deadline: the card was ready only once (it kept changing); retry with a longer --timeout"
477
+ else
478
+ ERROR_SUMMARY="Could not verify two ready OpenCard inspections before the deadline: last state=${preview_state:-unknown}${preview_match:+ (${preview_match})}; the card showed no rendered content (blank card, a runtime error, or still starting); check the diagnostic screenshot, read console --level error and the dev logs"
479
+ fi
462
480
  printf 'Could not verify rendered OpenCard content through browser inspection.\n' >&2
463
481
  capture_diagnostic
464
482
  print_diagnostics
@@ -33,6 +33,14 @@ export const matchesExpectedTarget = (actualUrl, expectedUrl) => {
33
33
  };
34
34
 
35
35
  const RPC_TIMEOUT_MS = 5000;
36
+ // Per-call window for one CDP command. A WebGL card rendered by SwiftShader (CPU) can hold the page main thread for
37
+ // several seconds, so capture raises it through this variable; values outside 1000..60000 fall back to the default.
38
+ export const RPC_TIMEOUT_ENV = 'ICB_CDP_RPC_TIMEOUT_MS';
39
+ export const WEBGL_RPC_TIMEOUT_MS = 15000;
40
+ export const resolveRpcTimeoutMs = (value = process.env[RPC_TIMEOUT_ENV]) => {
41
+ const parsed = Number(value);
42
+ return Number.isInteger(parsed) && parsed >= 1000 && parsed <= 60000 ? parsed : RPC_TIMEOUT_MS;
43
+ };
36
44
  const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
37
45
 
38
46
  export class CdpClient {
@@ -47,6 +55,7 @@ export class CdpClient {
47
55
  this.onEvent = onEvent;
48
56
  this.onClose = onClose;
49
57
  this.closed = false;
58
+ this.rpcTimeoutMs = resolveRpcTimeoutMs();
50
59
  this.deadline = timeoutMs === undefined ? Infinity : Date.now() + timeoutMs;
51
60
  this.operationTimer = timeoutMs === undefined ? null : setTimeout(() => {
52
61
  this.close(this.error('CDP operation budget timed out; stop browser retries and retain blocked', 'CDP_TIMEOUT',
@@ -67,9 +76,9 @@ export class CdpClient {
67
76
 
68
77
  timerFor(createError) {
69
78
  const remaining = this.deadline - Date.now();
70
- const budgetExhausted = remaining < RPC_TIMEOUT_MS;
71
- const timeoutError = () => Object.assign(createError(), budgetExhausted ? { budgetExhausted } : {});
72
- return [Math.max(1, Math.min(RPC_TIMEOUT_MS, remaining)), timeoutError];
79
+ const budgetExhausted = remaining < this.rpcTimeoutMs;
80
+ const timeoutError = () => Object.assign(createError(), budgetExhausted ? { budgetExhausted } : { rpcTimeoutMs: this.rpcTimeoutMs });
81
+ return [Math.max(1, Math.min(this.rpcTimeoutMs, remaining)), timeoutError];
73
82
  }
74
83
 
75
84
  async connect() {
@@ -9,6 +9,7 @@ import { spawn } from 'node:child_process';
9
9
  import { randomUUID } from 'node:crypto';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { writeSessionFile } from './cli-input.mjs';
12
+ import { RPC_TIMEOUT_ENV, WEBGL_RPC_TIMEOUT_MS } from './cdp-client.mjs';
12
13
 
13
14
  export const PROTOCOL = 1;
14
15
  export const CLI_VERSION = '1.0.0';
@@ -43,6 +44,21 @@ export const DEFAULT_VIEWPORT = { width: 375, height: 812 };
43
44
  export const ARTIFACT_KEEP = 40;
44
45
  export const ARTIFACT_MAX_AGE_MS = 24 * 3600 * 1000;
45
46
 
47
+ // Names agents reach for that are not verbs or options here (online USAGE failures), and what to run instead.
48
+ export const VERB_HINTS = {
49
+ reload: 'open', refresh: 'open', goto: 'open', navigate: 'open',
50
+ console: 'read console', 'preview-console': 'read console', logs: 'read console', network: 'read network',
51
+ map: 'read map', text: 'read text', layout: 'read layout',
52
+ screenshot: 'shot', capture: 'shot',
53
+ click: 'act click', tap: 'act click', fill: 'act fill', type: 'act fill', scroll: 'act scroll', press: 'act press',
54
+ quit: 'close', exit: 'close', stop: 'close', help: 'describe',
55
+ };
56
+ export const OPTION_HINTS = {
57
+ '--text': '--target text:<visible text>', '--selector': '--target css:<selector>', '--css': '--target css:<selector>',
58
+ '--id': '--target id:<test id>', '--xy': '--target xy:<x>,<y>',
59
+ '--output': '--name <name>', '--out': '--name <name>', '--path': '--name <name>', '--file': '--name <name>',
60
+ '--wait-ms': '--timeout <e.g. 30s>', '--full-page': '--full', '--fullpage': '--full',
61
+ };
46
62
  export class CliError extends Error {
47
63
  constructor(code, message, exit = EXIT.failed, extra = {}) {
48
64
  super(message);
@@ -87,7 +103,7 @@ export const parseArgs = argv => {
87
103
  flags.steps_.push({ kind: name.slice(2), value });
88
104
  continue;
89
105
  }
90
- if (!VALUE_FLAGS.has(name)) throw usage(`Unknown option ${name}; run describe for supported options`);
106
+ if (!VALUE_FLAGS.has(name)) throw usage(`Unknown option ${name}${OPTION_HINTS[name] ? `; use ${OPTION_HINTS[name]}` : ''}; run describe for supported options`);
91
107
  let value = eq > 0 ? arg.slice(eq + 1) : rest[++index];
92
108
  if (value === undefined) throw usage(`${name} requires a value`);
93
109
  if (name === '--target' && value !== (value = rejoinXy(value, rest, index))) index += 1;
@@ -250,17 +266,39 @@ export const startScript = (file, args, { timeoutMs = 120000, onStderrLine } = {
250
266
  const runScript = (file, args, options) => startScript(file, args, options).done;
251
267
 
252
268
  const BLOCKED_CODE = /^(CDP_|AGENT_BROWSER_|BROWSER_)/u;
269
+ export const WEBGL_BUSY_HINT = 'The card renders WebGL with software rendering (SwiftShader) in this sandbox Chrome, which can keep ' +
270
+ 'the page main thread busy past the CDP timeout; this is not a card code error. Retry once; if it keeps timing out, check the ' +
271
+ 'card on a real device (interest-card-cli preview), or reduce continuous rendering such as real-time shadows, full-screen ' +
272
+ 'particles and pixel ratio.';
273
+ /** Set from the open session's WebGL probe; later verbs reuse the longer CDP window and explain timeouts. */
274
+ let webglSession = false;
275
+ // Capture records whether the project draws WebGL; give its follow-up CDP calls the same longer per-call window.
276
+ export const applyWebglSession = (state, env = process.env) => {
277
+ webglSession = state?.webgl?.projectUsesWebgl === true;
278
+ if (webglSession && !env[RPC_TIMEOUT_ENV]) env[RPC_TIMEOUT_ENV] = String(WEBGL_RPC_TIMEOUT_MS);
279
+ return webglSession;
280
+ };
253
281
  // Converts a failed adapter receipt into a CliError: CDP/browser faults are environment blocks, the rest business failures.
282
+ // The adapters speak of --state-file and capture sessions; an agent only has verbs.
283
+ export const SESSION_STALE_HINT = 'The sandbox browser restarted or the preview tab is gone, so the page state of this session is lost: run `open` again and redo the steps from the start; do not assume the last action took effect';
254
284
  const childFailure = (step, result, fallbackCode) => {
255
285
  const json = result.json ?? {};
256
- const code = result.timedOut ? 'TIMEOUT' : json.code || fallbackCode;
286
+ const code = result.timedOut ? 'TIMEOUT' : json.code || (json.reason === 'browser-restarted' ? 'SESSION_STALE' : fallbackCode);
257
287
  const blocked = result.timedOut || BLOCKED_CODE.test(code) || result.code === 4 || result.code === 127;
258
288
  const reasons = [...new Set((json.attempts ?? []).map(item => item?.reason).filter(Boolean))].join(', ');
289
+ // The action adapter answers some failures with a top-level reason (and a hint) instead of an error.
290
+ const restarted = json.reason === 'browser-restarted';
291
+ const top = typeof json.reason === 'string' && json.reason
292
+ ? `${step}: ${json.reason}${!restarted && json.hint ? `; ${json.hint}` : ''}${json.openPages ? `; open pages: ${json.openPages}` : ''}` : '';
293
+ const silent = json.ok === false && !result.stderr.trim()
294
+ ? `${step}: the preview page gave no result (it may be reloading or navigating); run wait stable, then retry` : '';
259
295
  const error = json.error || (result.timedOut ? `${step} did not finish in time` : '')
260
- || (reasons ? `${step}: ${reasons}` : '')
296
+ || top || (reasons ? `${step}: ${reasons}` : '') || silent
261
297
  || result.stderr.trim().split('\n').slice(-3).join(' ').slice(0, 400) || `${step} exited ${result.code}`;
262
- const nextSteps = json.nextSteps ?? (code === 'SESSION_STALE' ? ['open'] : undefined);
263
- return new CliError(code, error, blocked ? EXIT.blocked : EXIT.failed, { data: json, ...(nextSteps ? { nextSteps } : {}) });
298
+ const explained = code === 'CDP_TIMEOUT' && webglSession && !error.includes(WEBGL_BUSY_HINT) ? `${error}. ${WEBGL_BUSY_HINT}`
299
+ : code === 'SESSION_STALE' && !error.includes(SESSION_STALE_HINT) ? `${error}. ${SESSION_STALE_HINT}` : error;
300
+ const nextSteps = json.nextSteps ?? (code === 'SESSION_STALE' || json.reason === 'page-target-not-found' ? ['open'] : undefined);
301
+ return new CliError(code, explained, blocked ? EXIT.blocked : EXIT.failed, { data: json, ...(nextSteps ? { nextSteps } : {}) });
264
302
  };
265
303
 
266
304
  // ---------- session context ----------
@@ -287,6 +325,7 @@ const createContext = flags => {
287
325
  artifacts: [],
288
326
  };
289
327
  ctx.meta = readJson(ctx.metaPath) ?? {};
328
+ applyWebglSession(readJson(ctx.statePath));
290
329
  if (!process.env.CONVERSATION_ID && CONVERSATION.test(ctx.meta.conversationId ?? '')) process.env.CONVERSATION_ID = ctx.meta.conversationId;
291
330
  return ctx;
292
331
  };
@@ -317,10 +356,30 @@ const artifactPath = (ctx, name, extension = 'png') => {
317
356
  const addArtifact = (ctx, kind, file) => {
318
357
  if (file && fs.existsSync(file) && !ctx.artifacts.some(item => item.path === file)) ctx.artifacts.push({ kind, path: file });
319
358
  };
359
+ /** Other sessions that are open right now, so a mistyped or forgotten --session can be spotted. */
360
+ const openSessionNames = ctx => {
361
+ let entries;
362
+ try { entries = fs.readdirSync(workRoot(), { withFileTypes: true }); } catch { return []; }
363
+ return entries.filter(entry => entry.isDirectory() && entry.name !== ctx.session && SESSION_NAME.test(entry.name))
364
+ .filter(entry => {
365
+ const dir = path.join(workRoot(), entry.name);
366
+ return readJson(path.join(dir, 'session.json'))?.sessionOpen === true && Boolean(readJson(path.join(dir, 'cli.json'))?.browserSession);
367
+ }).map(entry => entry.name).sort();
368
+ };
369
+ // Online (TEA): agents call shot/act after snap or a run closed the browser, or with a --session never opened.
370
+ export const sessionNotOpenMessage = ctx => {
371
+ const sessionFlag = ctx.session === 'default' ? '' : ` --session ${ctx.session}`;
372
+ const why = ctx.meta?.closedAt
373
+ ? `it was closed at ${ctx.meta.closedAt} (close, snap, and a run that opened the browser itself, all close it when they finish)`
374
+ : 'nothing has been opened under this name in this sandbox';
375
+ const others = openSessionNames(ctx);
376
+ const elsewhere = others.length ? `; open sessions: ${others.join(', ')} (pass --session <name> to use one)` : '';
377
+ return `Session "${ctx.session}" is not open: ${why}${elsewhere}. Run \`open${sessionFlag}\` first, then this command again; for a single screenshot use \`snap\` instead`;
378
+ };
320
379
  const openState = ctx => {
321
380
  const state = readJson(ctx.statePath);
322
381
  if (!state || state.ok !== true || state.sessionOpen !== true || !ctx.meta.browserSession) {
323
- throw new CliError('SESSION_NOT_OPEN', `Session "${ctx.session}" is not open; run open first`, EXIT.failed, { nextSteps: ['open'] });
382
+ throw new CliError('SESSION_NOT_OPEN', sessionNotOpenMessage(ctx), EXIT.failed, { nextSteps: ['open'] });
324
383
  }
325
384
  return state;
326
385
  };
@@ -330,11 +389,15 @@ const jsonArg = (ctx, label, value) => {
330
389
  writeJson(file, value);
331
390
  return file;
332
391
  };
392
+ // Shown in every --steps error so the next attempt has the exact shape.
393
+ export const STEPS_EXAMPLE = '[["act","click","--target","text:开始"],["shot","--area","face","--name","after"]]';
394
+ const JSON_OPTION_EXAMPLES = { '--steps': STEPS_EXAMPLE, '--selectors': '[".card",".btn"]', '--fields': '{"score":{"type":"number","pattern":"得分:([0-9]+)","group":1}}' };
395
+ const withExample = (label, message) => (JSON_OPTION_EXAMPLES[label] ? `${message}, e.g. ${label} '${JSON_OPTION_EXAMPLES[label]}'` : message);
333
396
  // --fields/--selectors/--steps accept inline JSON or an existing JSON file.
334
397
  const readJsonOption = (value, label) => {
335
398
  if (value === undefined) return undefined;
336
399
  const text = /^\s*[[{]/u.test(value) ? value : (() => {
337
- if (!fs.existsSync(value)) throw usage(`${label} must be inline JSON or an existing JSON file`);
400
+ if (!fs.existsSync(value)) throw usage(withExample(label, `${label} must be inline JSON or an existing JSON file (no file at ${JSON.stringify(String(value).slice(0, 80))})`));
338
401
  return fs.readFileSync(value, 'utf8');
339
402
  })();
340
403
  // PowerShell and cmd strip the double quotes of inline JSON; a file survives every shell.
@@ -534,6 +597,7 @@ async function verbOpen(ctx, flags, timeoutMs) {
534
597
  '--width', String((requestedViewport ?? DEFAULT_VIEWPORT).width), '--height', String((requestedViewport ?? DEFAULT_VIEWPORT).height)],
535
598
  { timeoutMs: timeoutMs + 120000 });
536
599
  state = readJson(ctx.statePath) ?? capture.json;
600
+ applyWebglSession(state);
537
601
  if (!state?.ok) {
538
602
  addArtifact(ctx, 'diagnostic', state?.diagnosticScreenshot);
539
603
  const blocked = state?.status === 'blocked' || capture.code === 4;
@@ -650,6 +714,11 @@ async function verbAct(ctx, flags, positional, timeoutMs) {
650
714
  failure.extra.nextSteps = [`act ${op} --in host --target ${flags.target}`, 'open --page landing', 'read map'];
651
715
  failure.message += '. Not found in the card: Feed shell controls (title, 不感兴趣, the button under the card) need --in host; landing-page elements need open --page landing';
652
716
  }
717
+ const detail = actionFailureDetail(result.json);
718
+ if (detail) {
719
+ failure.message += `. ${detail.message}`;
720
+ failure.extra.nextSteps ??= detail.nextSteps;
721
+ }
653
722
  throw failure;
654
723
  }
655
724
  if (action.capture) addArtifact(ctx, 'screenshot', action.capture.output);
@@ -716,6 +785,51 @@ async function pointClick(ctx, target) {
716
785
  return { ok: true, operation, match: { point, dispatchMethod: 'agent-browser-mouse' } };
717
786
  }
718
787
 
788
+ const quoteList = texts => texts.map(text => `"${text}"`).join(', ');
789
+ const elementLabel = element => `<${String(element.tag ?? '').toLowerCase()}${element.id ? `#${element.id}` : ''}${element.className ? `.${String(element.className).trim().split(/\s+/u).slice(0, 2).join('.')}` : ''}>${element.text ? ` "${element.text}"` : ''}`;
790
+ /**
791
+ * What a failed act adds to its error (online: most ACTION_FAILED are a target that is not there or is
792
+ * covered): the clickable text really on the page, or what sits on top of the target.
793
+ */
794
+ export const actionFailureDetail = json => {
795
+ const attempts = (json?.attempts ?? []).filter(item => item && typeof item === 'object');
796
+ const covered = attempts.find(item => item.reason === 'target-covered-or-outside-viewport' && item.rect && item.viewport);
797
+ if (covered) {
798
+ const { rect, viewport, coveredBy } = covered;
799
+ const x = Math.round(rect.x + rect.width / 2);
800
+ const y = Math.round(rect.y + rect.height / 2);
801
+ const outside = x < 0 || y < 0 || x >= viewport.width || y >= viewport.height;
802
+ return {
803
+ message: outside
804
+ ? `The target's centre (${x},${y}) is outside the ${viewport.width}x${viewport.height} viewport and could not be scrolled into it; scroll its container first (act scroll --target ...) or check the layout`
805
+ : coveredBy
806
+ ? `The target is there but ${elementLabel(coveredBy)} lies on top of it at (${x},${y}): close or click that layer first (a popup, mask or guide), or wait for it to go away`
807
+ : `Nothing can be clicked at the target's centre (${x},${y})`,
808
+ nextSteps: ['shot', 'read map'],
809
+ };
810
+ }
811
+ if (attempts.length && attempts.every(item => item.reason === 'target-document-not-found')) {
812
+ return {
813
+ message: 'The preview shows no rendered page to act on: it may still be loading, be blank, or show an error. Take a shot to see it and read console --level error',
814
+ nextSteps: ['shot', 'read console --level error'],
815
+ };
816
+ }
817
+ const ambiguous = attempts.find(item => item.reason === 'ambiguous-target-document');
818
+ if (ambiguous) {
819
+ const routes = [...new Set((ambiguous.candidates ?? []).map(item => item.renderedRoute).filter(Boolean))];
820
+ return {
821
+ message: `More than one visible page matched${routes.length ? ` (routes: ${routes.join(', ')})` : ''}: a page transition may not have finished. Run wait stable and retry${routes.length > 1 ? ', or pass --route <one of these routes>' : ''}`,
822
+ nextSteps: ['wait stable'],
823
+ };
824
+ }
825
+ const listed = attempts.filter(item => item.reason === 'visible-target-not-found' && Array.isArray(item.visibleTexts));
826
+ if (!listed.length) return undefined;
827
+ const texts = [...new Set(listed.flatMap(item => item.visibleTexts))].slice(0, 12);
828
+ return texts.length
829
+ ? { message: `Clickable text on the page right now: ${quoteList(texts)}`, nextSteps: ['read map'] }
830
+ : { message: 'The page has no clickable text right now: it may still be loading (wait stable), or it is drawn on a canvas (take a shot, then --target xy:x,y)', nextSteps: ['wait stable', 'shot'] };
831
+ };
832
+
719
833
  const notFound = json => json?.code === 'TARGET_NOT_FOUND'
720
834
  || (json?.attempts ?? []).some(item => /not-found/u.test(String(item?.reason ?? '')));
721
835
 
@@ -850,11 +964,15 @@ async function verbClose(ctx, flags = {}) {
850
964
  const sessionIsOpen = ctx => Boolean(ctx.meta?.browserSession) && Boolean(readJson(ctx.statePath)?.sessionOpen);
851
965
 
852
966
  async function verbRun(ctx, flags) {
853
- const steps = typeof flags.steps === 'object' ? flags.steps : readJsonOption(flags.steps, '--steps');
854
- if (!Array.isArray(steps) || !steps.length || steps.length > 30) throw usage('--steps must be a JSON array of 1..30 argv arrays');
967
+ const input = typeof flags.steps === 'object' ? flags.steps : readJsonOption(flags.steps, '--steps');
968
+ // A file written as {"steps":[...]} is the same list: unwrap it rather than fail.
969
+ const steps = Array.isArray(input?.steps) && !Array.isArray(input) ? input.steps : input;
970
+ if (!Array.isArray(steps) || !steps.length || steps.length > 30) {
971
+ throw usage(withExample('--steps', '--steps must be a JSON array of 1..30 argv arrays'));
972
+ }
855
973
  const argvs = steps.map((step, index) => {
856
974
  const argv = Array.isArray(step) ? step.map(String) : typeof step === 'object' && step?.verb ? [step.verb, ...(step.args ?? []).map(String)] : undefined;
857
- if (!argv?.length || ['run', 'describe', 'snap'].includes(argv[0])) throw usage(`steps[${index}] must be an argv array of a verb other than run/snap/describe`);
975
+ if (!argv?.length || ['run', 'describe', 'snap'].includes(argv[0])) throw usage(withExample('--steps', `steps[${index}] must be an argv array of a verb other than run/snap/describe`));
858
976
  return argv;
859
977
  });
860
978
  const wasOpen = sessionIsOpen(ctx);
@@ -942,7 +1060,7 @@ export const execute = async (argv, { nested = false } = {}) => {
942
1060
  return { protocol: PROTOCOL, ok: true, code: 'OK', verb: 'describe', session: null, page: null, outcome: 'described',
943
1061
  expect: [], data: describe(), artifacts: [], exit: EXIT.ok };
944
1062
  }
945
- if (!VERBS[verb]) throw usage(`Unknown verb ${verb}; one of ${Object.keys(VERBS).join(' | ')}`);
1063
+ if (!VERBS[verb]) throw usage(`Unknown verb ${verb}${VERB_HINTS[verb] ? `; use \`${VERB_HINTS[verb]}\`` : ''}; one of ${Object.keys(VERBS).join(' | ')}`);
946
1064
  if (nested && (verb === 'run' || verb === 'snap')) throw usage(`${verb} cannot be nested`);
947
1065
  const timeoutMs = parseTimeout(parsed.flags.timeout, verb === 'open' ? 60000 : 30000);
948
1066
  ctx = createContext(parsed.flags);
@@ -142,9 +142,13 @@ export const classifyPreviewDocuments = (documents, inspectionErrors = [], scope
142
142
  const loadingMatch = findMatch(surfaceDocuments, LOADING_PATTERNS);
143
143
  const contentDocuments = surfaceDocuments.filter(document => normalizeLine(document.text));
144
144
  // A card drawn on canvas or images: its render document has the widget root and visible drawn elements.
145
- const drawnDocuments = scope === 'landing-page' || scope === 'feed-host'
145
+ // A landing page needs more than drawn elements (a logo or placeholder image is not content): one
146
+ // canvas covering much of the viewport, as a full-screen game draws.
147
+ const drawnDocuments = scope === 'feed-host'
146
148
  ? []
147
- : surfaceDocuments.filter(document => document.hasWidgetRoot && document.visualElements > 0);
149
+ : scope === 'landing-page'
150
+ ? surfaceDocuments.filter(document => document.largeCanvas === true)
151
+ : surfaceDocuments.filter(document => document.hasWidgetRoot && document.visualElements > 0);
148
152
 
149
153
  const match = errorMatch ?? loadingMatch;
150
154
  const state = errorMatch
@@ -289,6 +293,15 @@ export const collectPreviewDocument = ({ selectors = [], identity = {} } = {}) =
289
293
  if (tag === 'svg' || tag === 'video') return true;
290
294
  return /url\(/u.test(getComputedStyle(element).backgroundImage);
291
295
  }).length,
296
+ // A game drawn into one canvas (WebGL or 2D) covering at least 40% of the viewport: it has no DOM text.
297
+ // The number is inlined: this function runs in the page from its source text.
298
+ largeCanvas: all('canvas').some(element => {
299
+ if (!isVisible(element) || !(element.width > 0 && element.height > 0)) return false;
300
+ const rect = element.getBoundingClientRect();
301
+ const width = Math.min(rect.right, innerWidth) - Math.max(rect.left, 0);
302
+ const height = Math.min(rect.bottom, innerHeight) - Math.max(rect.top, 0);
303
+ return width > 0 && height > 0 && width * height >= 0.4 * innerWidth * innerHeight;
304
+ }),
292
305
  hasWidgetRoot: all('.widget-root').length > 0,
293
306
  hasLandingRoot: all('.taro_page_show,.taro_page').length > 0,
294
307
  hasLandingFrame: Array.from(document.querySelectorAll('iframe')).some(frame =>
@@ -427,6 +440,7 @@ export const inspectPreviewState = async (cdpUrl, expectedTargetUrl = '', scope
427
440
  visibleTextNodes: document.visibleTextNodes,
428
441
  pendingImages: document.pendingImages ?? 0,
429
442
  visualElements: document.visualElements ?? 0,
443
+ largeCanvas: document.largeCanvas === true,
430
444
  hasWidgetRoot: document.hasWidgetRoot,
431
445
  hasLandingRoot: document.hasLandingRoot,
432
446
  hasLandingFrame: document.hasLandingFrame,
@@ -235,6 +235,23 @@ export const actionExpression = action => `(async () => {
235
235
  }
236
236
  return null;
237
237
  };
238
+ // What a failed click reports back, so the next attempt can name a target that is really there.
239
+ const clickableTexts = () => {
240
+ const texts = [];
241
+ for (const element of all('*')) {
242
+ if (texts.length >= 12) break;
243
+ if (!visible(element) || actionableAncestor(element) !== element) continue;
244
+ const text = normalize(element.innerText || element.textContent || element.value).slice(0, 24);
245
+ if (text && !texts.includes(text)) texts.push(text);
246
+ }
247
+ return texts;
248
+ };
249
+ const describeElement = element => element ? {
250
+ tag: element.tagName,
251
+ id: String(element.id || '').slice(0, 60),
252
+ className: String(element.className?.baseVal ?? element.className ?? '').slice(0, 80),
253
+ text: normalize(element.innerText || element.textContent || '').slice(0, 40),
254
+ } : null;
238
255
  const compareActionCandidates = ${compareActionCandidates.toString()};
239
256
  const candidates = () => {
240
257
  if (action.target.by === 'selector') return all(action.target.value);
@@ -375,18 +392,24 @@ export const actionExpression = action => `(async () => {
375
392
  }
376
393
  const occurrence = Number.isInteger(action.target.occurrence) ? action.target.occurrence : 0;
377
394
  const matchedElement = candidates().filter(visible)[occurrence];
378
- if (!matchedElement) return { ok: false, reason: 'visible-target-not-found' };
395
+ if (!matchedElement) return { ok: false, reason: 'visible-target-not-found', documentUrl, frameElementUrl, visibleTexts: clickableTexts() };
379
396
  const element = action.op === 'click'
380
397
  ? actionableAncestor(matchedElement) || matchedElement
381
398
  : matchedElement;
382
399
  if (action.op === 'click') {
383
- element.scrollIntoView({ block: 'center', inline: 'nearest' });
400
+ // instant: a page with scroll-behavior:smooth would still be moving when the rect is read below.
401
+ element.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
384
402
  }
385
403
  const rect = element.getBoundingClientRect();
386
404
  if (action.op === 'click') {
387
405
  const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);
388
406
  if (!hit || (hit !== element && !element.contains(hit))) {
389
- return { ok: false, reason: 'target-covered-or-outside-viewport', documentUrl, frameElementUrl };
407
+ return {
408
+ ok: false, reason: 'target-covered-or-outside-viewport', documentUrl, frameElementUrl,
409
+ coveredBy: describeElement(hit),
410
+ rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
411
+ viewport: { width: innerWidth, height: innerHeight },
412
+ };
390
413
  }
391
414
  if (action.scope === 'feed-host') {
392
415
  window.__microappAuditFeedActionMessages = [];
@@ -205,6 +205,15 @@ export const reconcileOperation = async (sessionFile, options) => {
205
205
  return { ok: true, operation, replayed: false };
206
206
  };
207
207
 
208
+ // Online (TEA): the bare reason gave an agent nothing to act on. Name the pages that matched.
209
+ export const ambiguousDocumentMessage = (candidates = []) => {
210
+ const routes = [...new Set(candidates.map(item => item.renderedRoute).filter(Boolean))];
211
+ return 'ambiguous-target-document: ' + (candidates.length || 'several') + ' visible pages matched until the deadline' +
212
+ (routes.length ? ' (routes: ' + routes.join(', ') + ')' : '') +
213
+ '; a page transition did not finish or the app shows two pages at once' +
214
+ (routes.length > 1 ? '; pass --route <one of these routes> to pick one' : '; take a shot to see the page, then retry');
215
+ };
216
+
208
217
  export const waitForPreview = async (cdpUrl, expectedUrl, scope, {
209
218
  textPresent = [], textAbsent = [], stablePasses = 2, timeoutMs = 30000, allowError = false, settleImagesMs = 0,
210
219
  expectedRoute: configuredRoute = '',
@@ -226,6 +235,7 @@ export const waitForPreview = async (cdpUrl, expectedUrl, scope, {
226
235
  let currentCdpUrl = cdpUrl;
227
236
  let address = {};
228
237
  let readySince = 0;
238
+ let ambiguous = null;
229
239
  const notReady = cutShort => Object.assign(new Error(
230
240
  `Preview wait timed out: state=${inspection?.state}, documents=${inspection?.documents?.length}, ` +
231
241
  `renderedRoute=${renderedRoute || '<none>'}, expectedRoute=${expectedRoute || '<any>'}; ` +
@@ -259,8 +269,14 @@ export const waitForPreview = async (cdpUrl, expectedUrl, scope, {
259
269
  throw new Error(inspection.diagnostics.blockingReason);
260
270
  }
261
271
  if (inspection.diagnostics?.documentSelection?.reason === 'ambiguous-target-document') {
262
- throw new Error('ambiguous-target-document; bind the visible business page with expectedRoute/frameId/pageTargetId');
272
+ // Two visible pages at once is usually a page transition (the old page has not left yet):
273
+ // keep polling, and fail only when it is still so at the deadline.
274
+ ambiguous = inspection.diagnostics.documentSelection;
275
+ passes = 0; readySince = 0; previous = '';
276
+ await new Promise(resolve => setTimeout(resolve, Math.max(0, Math.min(300, deadline - Date.now()))));
277
+ continue;
263
278
  }
279
+ ambiguous = null;
264
280
  renderedRoute = scope === 'landing-page' ? getRenderedRoute(inspection) : '';
265
281
  const signature = JSON.stringify(inspection.documents.map(document => ({
266
282
  frameId: document.frameId, text: document.text, path: document.frameElementUrl,
@@ -280,6 +296,7 @@ export const waitForPreview = async (cdpUrl, expectedUrl, scope, {
280
296
  previous = signature;
281
297
  await new Promise(resolve => setTimeout(resolve, Math.max(0, Math.min(300, deadline - Date.now()))));
282
298
  }
299
+ if (ambiguous) throw new Error(ambiguousDocumentMessage(ambiguous.candidates));
283
300
  throw notReady(false);
284
301
  };
285
302
 
package/dist/src/args.js CHANGED
@@ -7,6 +7,7 @@ const valueOptions = new Set([
7
7
  'answers',
8
8
  'auth-base-url',
9
9
  'base-url',
10
+ 'channel',
10
11
  'config',
11
12
  'conversation-id',
12
13
  'dir',
@@ -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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-dy/interest-card-cli",
3
- "version": "0.1.0-beta.32",
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",