@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
@@ -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" -- "$@"
@@ -134,23 +136,6 @@ if [[ -z "$PROJECT_ROOT" ]]; then
134
136
  PROJECT_ROOT="$(cd "$(dirname "$FEED_FILE")/.." && pwd)"
135
137
  fi
136
138
 
137
- if [[ ! "$CONVERSATION_ID" =~ ^conv_[A-Za-z0-9-]+(_ext)?$ ]]; then
138
- printf 'CONVERSATION_ID is missing or invalid; expected conv_<id> or conv_<id>_ext.\n' >&2
139
- exit 6
140
- fi
141
- if [[ -z "$PROJECT_CONVERSATION_ID" ]]; then
142
- PROJECT_CONVERSATION_ID="$CONVERSATION_ID"
143
- fi
144
- if [[ ! "$PROJECT_CONVERSATION_ID" =~ ^conv_[A-Za-z0-9-]+(_ext)?$ ]]; then
145
- printf 'Project ConversationId is invalid.\n' >&2
146
- exit 6
147
- fi
148
-
149
- if [[ -z "$OUTPUT" ]]; then
150
- OUTPUT="$PROJECT_ROOT/artifacts/feed-card-${CONVERSATION_ID}.png"
151
- fi
152
- mkdir -p "$(dirname "$OUTPUT")"
153
-
154
139
  if [[ -n "$SESSION_NAME" && ! "$SESSION_NAME" =~ ^[A-Za-z0-9._-]+$ ]]; then
155
140
  printf 'Session name may contain only letters, digits, dot, underscore and hyphen.\n' >&2
156
141
  exit 2
@@ -170,7 +155,8 @@ cleanup() {
170
155
  fi
171
156
  [[ -z "$DATA_PREFLIGHT_FILE" ]] || rm -f "$DATA_PREFLIGHT_FILE"
172
157
  COMMAND_TIMEOUT_MS="1500"
173
- if [[ "$CONTROL_FAILED" != "true" && ( "$KEEP_OPEN" != "true" || "$CAPTURE_SUCCEEDED" != "true" ) ]]; then
158
+ if [[ "$STAGE" != "readiness" && "$CONTROL_FAILED" != "true" &&
159
+ ( "$KEEP_OPEN" != "true" || "$CAPTURE_SUCCEEDED" != "true" ) ]]; then
174
160
  if [[ -n "$owned_tab_id" ]]; then
175
161
  agent-browser --session "$SESSION_NAME" tab close "$owned_tab_id" >/dev/null 2>&1 || true
176
162
  fi
@@ -263,6 +249,10 @@ print_diagnostics() {
263
249
  agent-browser --session "$SESSION_NAME" network requests >&2 || true
264
250
  }
265
251
 
252
+ project_uses_webgl() {
253
+ [[ "$(printf '%s' "$webgl_status" | jq -r '.projectUsesWebgl == true' 2>/dev/null)" == "true" ]]
254
+ }
255
+
266
256
  inspect_current() {
267
257
  local inspection_exit=0
268
258
  local remaining_ms="${1:-10000}"
@@ -280,6 +270,9 @@ inspect_current() {
280
270
  ERROR_SUMMARY="$(printf '%s' "$inspection" | jq -r '.error // "Preview inspection failed"')"
281
271
  printf 'Preview inspection failed: %s\n' "$ERROR_SUMMARY" >&2
282
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
283
276
  CONTROL_FAILED="true"
284
277
  preview_state="unknown"
285
278
  exit 13
@@ -290,11 +283,32 @@ inspect_current() {
290
283
 
291
284
  STAGE="readiness"
292
285
  dev_status="$(cd "$PROJECT_ROOT" && node "$SCRIPT_DIR/wait-dev-status.mjs")"
286
+ initial_conversation_id="$CONVERSATION_ID"
293
287
  runtime_conversation_id="$(printf '%s' "$dev_status" | jq -r '.runtimeConversationId // ""')"
294
288
  if [[ "$CONVERSATION_ID_SOURCE" == "environment" && -n "$runtime_conversation_id" ]]; then
295
289
  CONVERSATION_ID="$runtime_conversation_id"
296
290
  CONVERSATION_ID_SOURCE="dev/status or runtime meta"
297
291
  fi
292
+
293
+ conversation_id_pattern='^conv_[A-Za-z0-9-]+(_ext)?$'
294
+ if [[ ! "$CONVERSATION_ID" =~ $conversation_id_pattern ]]; then
295
+ ERROR_SUMMARY='CONVERSATION_ID is missing or invalid; expected conv_<id> or conv_<id>_ext.'
296
+ printf '%s\n' "$ERROR_SUMMARY" >&2
297
+ exit 6
298
+ fi
299
+ # Keep a valid caller CID for audit metadata and the default output name.
300
+ if [[ ! "$initial_conversation_id" =~ $conversation_id_pattern ]]; then
301
+ initial_conversation_id="$CONVERSATION_ID"
302
+ fi
303
+ PROJECT_CONVERSATION_ID="${PROJECT_CONVERSATION_ID:-$initial_conversation_id}"
304
+ if [[ ! "$PROJECT_CONVERSATION_ID" =~ $conversation_id_pattern ]]; then
305
+ ERROR_SUMMARY='Project ConversationId is invalid.'
306
+ printf '%s\n' "$ERROR_SUMMARY" >&2
307
+ exit 6
308
+ fi
309
+ OUTPUT="${OUTPUT:-$PROJECT_ROOT/artifacts/feed-card-${initial_conversation_id}.png}"
310
+ mkdir -p "$(dirname "$OUTPUT")"
311
+
298
312
  if [[ "$CONVERSATION_ID" == *_ext ]]; then
299
313
  PREVIEW_HOST="aihub.douyin.com"
300
314
  else
@@ -344,6 +358,10 @@ browser_version="$(agent-browser --version 2>/dev/null | grep -Eo '[0-9]+\.[0-9]
344
358
  # only reports. A project without WebGL returns at once without touching the browser.
345
359
  webgl_status="$(node "$SCRIPT_DIR/ensure-webgl.mjs" --enable --if-idle --project-root "$PROJECT_ROOT" --timeout-ms 30000 2>/dev/null || true)"
346
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
347
365
  case "$(printf '%s' "$webgl_status" | jq -r '.status // ""')" in
348
366
  enabled)
349
367
  printf 'WebGL enabled for this sandbox Chrome (one restart while no page was open).\n' >&2 ;;
@@ -453,7 +471,12 @@ if [[ "$preview_state" == 'loading' ]]; then
453
471
  fi
454
472
 
455
473
  if [[ "$preview_state" != 'ready' || "$ready_passes" -lt 2 ]]; then
456
- 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
457
480
  printf 'Could not verify rendered OpenCard content through browser inspection.\n' >&2
458
481
  capture_diagnostic
459
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 = [];
@@ -14,6 +14,7 @@ import { SESSION_FLAGS, readJsonInput, readSessionFile, requireCdpUrl, resolveBr
14
14
  export const SESSION_HELP = `Usage: preview-session.mjs <command> [arguments]
15
15
  landing-url <preview-url> <registered-pages-route-with-optional-query>
16
16
  inject <cdp-url> <feed-url> <feed.json> [--reload]
17
+ inject --session-file state.json [<feed.json>] [--reload]
17
18
  wait <cdp-url> <url> <interest-card|landing-page> [readiness-json-or-file]
18
19
  observe <cdp-url> <url> <interest-card|landing-page> <absolute-output.json> <fields-json-or-file>
19
20
  capture <cdp-url> <url> <output.png> [options-json-or-file]
@@ -22,6 +23,7 @@ Preferred: replace <cdp-url> <url> with --session-file <capture state.json> [--s
22
23
  wait --session-file state.json landing-page readiness.json
23
24
  capture --session-file state.json --scope landing-page out.png options.json
24
25
  The session file supplies cdpUrl and previewUrl (landingPreviewUrl for landing-page); --url overrides the URL.
26
+ inject uses the session's feedFile when no Feed JSON path is supplied.
25
27
 
26
28
  readiness: {"expectedRoute":"pages/detail/index","textPresent":["TA 的主页"],"stablePasses":2,"timeoutMs":10000}
27
29
  fields: {"quantity":{"type":"number","pattern":"数量:[ ]*([0-9]+)","group":1}}
@@ -203,6 +205,15 @@ export const reconcileOperation = async (sessionFile, options) => {
203
205
  return { ok: true, operation, replayed: false };
204
206
  };
205
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
+
206
217
  export const waitForPreview = async (cdpUrl, expectedUrl, scope, {
207
218
  textPresent = [], textAbsent = [], stablePasses = 2, timeoutMs = 30000, allowError = false, settleImagesMs = 0,
208
219
  expectedRoute: configuredRoute = '',
@@ -224,6 +235,7 @@ export const waitForPreview = async (cdpUrl, expectedUrl, scope, {
224
235
  let currentCdpUrl = cdpUrl;
225
236
  let address = {};
226
237
  let readySince = 0;
238
+ let ambiguous = null;
227
239
  const notReady = cutShort => Object.assign(new Error(
228
240
  `Preview wait timed out: state=${inspection?.state}, documents=${inspection?.documents?.length}, ` +
229
241
  `renderedRoute=${renderedRoute || '<none>'}, expectedRoute=${expectedRoute || '<any>'}; ` +
@@ -257,8 +269,14 @@ export const waitForPreview = async (cdpUrl, expectedUrl, scope, {
257
269
  throw new Error(inspection.diagnostics.blockingReason);
258
270
  }
259
271
  if (inspection.diagnostics?.documentSelection?.reason === 'ambiguous-target-document') {
260
- 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;
261
278
  }
279
+ ambiguous = null;
262
280
  renderedRoute = scope === 'landing-page' ? getRenderedRoute(inspection) : '';
263
281
  const signature = JSON.stringify(inspection.documents.map(document => ({
264
282
  frameId: document.frameId, text: document.text, path: document.frameElementUrl,
@@ -278,6 +296,7 @@ export const waitForPreview = async (cdpUrl, expectedUrl, scope, {
278
296
  previous = signature;
279
297
  await new Promise(resolve => setTimeout(resolve, Math.max(0, Math.min(300, deadline - Date.now()))));
280
298
  }
299
+ if (ambiguous) throw new Error(ambiguousDocumentMessage(ambiguous.candidates));
281
300
  throw notReady(false);
282
301
  };
283
302
 
@@ -413,6 +432,13 @@ if (isMain) {
413
432
  const scoped = ['wait', 'observe'].includes(operation);
414
433
  const target = named ? resolveBrowserTarget(flags, positional, { defaultScope: scoped ? '' : 'interest-card' })
415
434
  : { cdpUrl: positional[0], expectedUrl: positional[1], rest: positional.slice(2) };
435
+ if (operation === 'inject') {
436
+ const feedFile = target.rest[0] ?? target.browserSession?.feedFile;
437
+ if (typeof feedFile !== 'string' || !feedFile.trim()) {
438
+ throw new Error('inject requires a Feed JSON path or a --session-file containing feedFile');
439
+ }
440
+ target.rest[0] = feedFile;
441
+ }
416
442
  if (named && scoped) target.rest.unshift(target.scope);
417
443
  args = { ...target, named, cdpUrl: requireCdpUrl(target.cdpUrl), reload: Boolean(flags['--reload']),
418
444
  sessionFile: flags['--session-file'] };
@@ -37,7 +37,8 @@ getAIUserProfile(params: AIUserProfileParams, options?: CallOptions): Promise<Op
37
37
 
38
38
  ## 能力使用规则
39
39
 
40
- - 当前访问者的账号性别从 `data.UserInfo.gender` 读取,未知值不归为男性或女性;年龄在 `birthday` 返回有效完整出生日期时按生日是否已过计算周岁,不把账号注册天数当作年龄。
40
+ - `const response = await getAIUserProfile(params, options)` 得到 SDK 已规范化的 `{ err_no, err_msg, data: { UserInfo } }`。直接从 `response.data.UserInfo` 取资料,业务状态码在 `response.err_no`。`response.data` 的下一层是 `UserInfo`。
41
+ - 保留 SDK 推断的返回类型。性别读 `response.data.UserInfo.gender`,未知值不归为男性或女性。生日读 `response.data.UserInfo.birthday`,有效完整出生日期按生日是否已过计算周岁,不把账号注册天数当作年龄。
41
42
  - 生日缺失、不完整或无效时,不能推测年龄或填入固定画像;明确展示资料不可用,并保留不依赖该字段的业务内容。不得因一次检索为空就要求用户改为手填年龄或性别。
42
43
  - 账号资料及其派生年龄在封闭域服务中处理,遵守数据流限制;不得记录原始生日、身份或凭证。
43
44
 
@@ -61,8 +62,9 @@ export async function callGetAIUserProfile(input: {
61
62
  params,
62
63
  { ...options, delegateToken },
63
64
  );
64
- console.log('getAIUserProfile success', result);
65
- return result;
65
+ const profile = result.data.UserInfo;
66
+ console.log('getAIUserProfile success', { errNo: result.err_no });
67
+ return profile;
66
68
  } catch (error) {
67
69
  console.error('getAIUserProfile fail', error);
68
70
  throw error;
@@ -72,4 +74,4 @@ export async function callGetAIUserProfile(input: {
72
74
 
73
75
  ## 验证
74
76
 
75
- 调用成功时使用 `console.log` 输出 SDK 返回结果;调用失败时使用 `console.error` 输出完整错误。根据实际返回数据确认业务字段,并保留错误处理。
77
+ 核对 `result.err_no` 和 `result.data.UserInfo`。仅记录业务状态码,不输出资料内容;SDK 调用失败时保留错误处理。
@@ -40,7 +40,8 @@ getAIUserProfile(params: AIUserProfileParams, options?: CallOptions): Promise<Op
40
40
 
41
41
  ## 能力使用规则
42
42
 
43
- - 当前访问者的账号性别从 `data.UserInfo.gender` 读取,未知值不归为男性或女性;年龄在 `birthday` 返回有效完整出生日期时按生日是否已过计算周岁,不把账号注册天数当作年龄。
43
+ - `const response = await getAIUserProfile(params, options)` 得到 SDK 已规范化的 `{ err_no, err_msg, data: { UserInfo } }`。直接从 `response.data.UserInfo` 取资料,业务状态码在 `response.err_no`。`response.data` 的下一层是 `UserInfo`。
44
+ - 保留 SDK 推断的返回类型。性别读 `response.data.UserInfo.gender`,未知值不归为男性或女性。生日读 `response.data.UserInfo.birthday`,有效完整出生日期按生日是否已过计算周岁,不把账号注册天数当作年龄。
44
45
  - 生日缺失、不完整或无效时,不能推测年龄或填入固定画像;明确展示资料不可用,并保留不依赖该字段的业务内容。不得因一次检索为空就要求用户改为手填年龄或性别。
45
46
  - 账号资料及其派生年龄在封闭域服务中处理,遵守数据流限制;不得记录原始生日、身份或凭证。
46
47
 
@@ -64,8 +65,9 @@ export async function callGetAIUserProfile(input: {
64
65
  params,
65
66
  { ...options, delegateToken },
66
67
  );
67
- console.log('getAIUserProfile success', result);
68
- return result;
68
+ const profile = result.data.UserInfo;
69
+ console.log('getAIUserProfile success', { errNo: result.err_no });
70
+ return profile;
69
71
  } catch (error) {
70
72
  console.error('getAIUserProfile fail', error);
71
73
  throw error;
@@ -75,4 +77,4 @@ export async function callGetAIUserProfile(input: {
75
77
 
76
78
  ## 验证
77
79
 
78
- 调用成功时使用 `console.log` 输出 SDK 返回结果;调用失败时使用 `console.error` 输出完整错误。根据实际返回数据确认业务字段,并保留错误处理。
80
+ 核对 `result.err_no` 和 `result.data.UserInfo`。仅记录业务状态码,不输出资料内容;SDK 调用失败时保留错误处理。