@open-dy/interest-card-cli 0.1.0-beta.30 → 0.1.0-beta.32

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 (210) hide show
  1. package/browser-runtime/scripts/capture-feed-card.sh +23 -18
  2. package/browser-runtime/scripts/cli.mjs +10 -3
  3. package/browser-runtime/scripts/inspect-preview-state.mjs +6 -4
  4. package/browser-runtime/scripts/preview-session.mjs +9 -0
  5. package/card-skills/douyin-interest-card-browser/references/commands.md +1 -1
  6. package/card-skills/douyin-interest-card-capability/SKILL.md +12 -4
  7. package/card-skills/douyin-interest-card-capability/references/common/openapi/external/guide.md +5 -5
  8. package/card-skills/douyin-interest-card-capability/references/microapp/api/capability-index.json +27 -27
  9. package/card-skills/douyin-interest-card-capability/references/microapp/api/connect-socket.md +24 -1
  10. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-bytenn-engine-context.md +11 -1
  11. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-camera-context.md +12 -0
  12. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-canvas-context.md +45 -1
  13. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-effect-camera-stream.md +21 -1
  14. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-inner-audio-context.md +80 -3
  15. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-intersection-observer.md +12 -1
  16. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-interstitial-ad.md +12 -0
  17. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-live-player-context.md +16 -0
  18. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-map-context.md +24 -0
  19. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-media-recorder.md +17 -0
  20. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-offscreen-canvas.md +9 -1
  21. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-rewarded-video-ad.md +16 -0
  22. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-rtc-room-context.md +33 -0
  23. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-scene-activity-context.md +13 -0
  24. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-selector-query.md +13 -1
  25. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-sticker-manager.md +11 -1
  26. package/card-skills/douyin-interest-card-capability/references/microapp/api/create-video-context.md +17 -0
  27. package/card-skills/douyin-interest-card-capability/references/microapp/api/download-file.md +10 -0
  28. package/card-skills/douyin-interest-card-capability/references/microapp/api/get-algorithm-manager.md +9 -1
  29. package/card-skills/douyin-interest-card-capability/references/microapp/api/get-background-audio-manager.md +60 -1
  30. package/card-skills/douyin-interest-card-capability/references/microapp/api/get-file-system-manager.md +37 -0
  31. package/card-skills/douyin-interest-card-capability/references/microapp/api/get-recorder-manager.md +23 -0
  32. package/card-skills/douyin-interest-card-capability/references/microapp/api/get-update-manager.md +11 -0
  33. package/card-skills/douyin-interest-card-capability/references/microapp/api/preload-video.md +8 -0
  34. package/card-skills/douyin-interest-card-capability/references/microapp/api/request.md +8 -0
  35. package/card-skills/douyin-interest-card-capability/references/microapp/api/upload-file.md +10 -0
  36. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/capability-index.json +9 -4
  37. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/censor-image.md +1 -1
  38. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/censor-text.md +1 -1
  39. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/check-fans.md +1 -1
  40. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/create-activity.md +1 -1
  41. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-affiliate-id.md +1 -1
  42. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-aiuser-data-info.md +1 -1
  43. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-aiuser-item-list.md +1 -1
  44. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-aiuser-profile.md +7 -5
  45. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-fans-favourite.md +1 -1
  46. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-fans-profile.md +1 -1
  47. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-fans-source.md +1 -1
  48. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-feed.md +1 -1
  49. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-follow-feed.md +1 -1
  50. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-follow-hot-word.md +1 -1
  51. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-friend-list.md +1 -1
  52. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-hot-list.md +1 -1
  53. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-music-collection-list.md +1 -1
  54. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-recommend.md +1 -1
  55. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-related-id.md +1 -1
  56. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-room-real-time-data.md +1 -1
  57. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-basic-data.md +1 -1
  58. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-cert-labels-info.md +1 -1
  59. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-comment-data.md +1 -1
  60. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-constellation.md +1 -1
  61. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-fans-data.md +1 -1
  62. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-fans-profile.md +1 -1
  63. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-following.md +1 -1
  64. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-hash-mobile.md +1 -1
  65. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-interest.md +1 -1
  66. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-item-data.md +1 -1
  67. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-like-data.md +1 -1
  68. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-profile-data.md +1 -1
  69. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-user-share-data.md +1 -1
  70. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/get-video-pack.md +48 -3
  71. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/modify-activity.md +1 -1
  72. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/query-activity-info.md +1 -1
  73. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/query-activity-user-completion-status.md +1 -1
  74. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/query-room-data.md +1 -1
  75. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/search-experience.md +1 -1
  76. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/search-general.md +1 -1
  77. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/search-live.md +1 -1
  78. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/search-music.md +1 -1
  79. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/search-user.md +1 -1
  80. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/search-video.md +1 -1
  81. package/card-skills/douyin-interest-card-capability/references/microapp/openapi/external/search-vision.md +1 -1
  82. package/card-skills/douyin-interest-card-capability/references/opencard/api/call-container.md +1 -0
  83. package/card-skills/douyin-interest-card-capability/references/opencard/api/capability-index.json +6 -6
  84. package/card-skills/douyin-interest-card-capability/references/opencard/api/create-inner-audio-context.md +60 -1
  85. package/card-skills/douyin-interest-card-capability/references/opencard/api/create-map-context.md +24 -0
  86. package/card-skills/douyin-interest-card-capability/references/opencard/api/create-selector-query.md +13 -1
  87. package/card-skills/douyin-interest-card-capability/references/opencard/api/create-video-context.md +17 -0
  88. package/card-skills/douyin-interest-card-capability/references/opencard/api/download-file.md +1 -3
  89. package/card-skills/douyin-interest-card-capability/references/opencard/api/get-background-audio-manager.md +60 -1
  90. package/card-skills/douyin-interest-card-capability/references/opencard/api/request.md +1 -3
  91. package/card-skills/douyin-interest-card-capability/references/opencard/api/upload-file.md +1 -3
  92. package/card-skills/douyin-interest-card-capability/references/opencard/closed-domain-openapi.md +2 -2
  93. package/card-skills/douyin-interest-card-capability/references/opencard/component/button.md +4 -2
  94. package/card-skills/douyin-interest-card-capability/references/opencard/component/canvas.md +4 -3
  95. package/card-skills/douyin-interest-card-capability/references/opencard/component/capability-index.json +8 -9
  96. package/card-skills/douyin-interest-card-capability/references/opencard/component/checkbox-group.md +2 -0
  97. package/card-skills/douyin-interest-card-capability/references/opencard/component/image.md +3 -2
  98. package/card-skills/douyin-interest-card-capability/references/opencard/component/input.md +3 -2
  99. package/card-skills/douyin-interest-card-capability/references/opencard/component/text.md +3 -3
  100. package/card-skills/douyin-interest-card-capability/references/opencard/component/textarea.md +5 -5
  101. package/card-skills/douyin-interest-card-capability/references/opencard/component/video.md +10 -2
  102. package/card-skills/douyin-interest-card-capability/references/opencard/component-guide.md +5 -3
  103. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/capability-index.json +16 -11
  104. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/censor-image.md +1 -1
  105. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/censor-text.md +1 -1
  106. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/check-fans.md +1 -1
  107. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/create-activity.md +1 -1
  108. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-affiliate-id.md +1 -1
  109. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-aiuser-data-info.md +10 -9
  110. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-aiuser-item-list.md +10 -9
  111. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-aiuser-profile.md +16 -13
  112. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-fans-favourite.md +1 -1
  113. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-fans-profile.md +1 -1
  114. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-fans-source.md +1 -1
  115. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-feed.md +1 -1
  116. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-follow-feed.md +1 -1
  117. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-follow-hot-word.md +1 -1
  118. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-friend-list.md +1 -1
  119. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-hot-list.md +1 -1
  120. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-music-collection-list.md +1 -1
  121. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-recommend.md +1 -1
  122. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-related-id.md +1 -1
  123. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-room-real-time-data.md +1 -1
  124. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-basic-data.md +10 -9
  125. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-cert-labels-info.md +1 -1
  126. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-comment-data.md +1 -1
  127. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-constellation.md +10 -9
  128. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-fans-data.md +1 -1
  129. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-fans-profile.md +1 -1
  130. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-following.md +10 -9
  131. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-hash-mobile.md +1 -1
  132. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-interest.md +10 -9
  133. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-item-data.md +1 -1
  134. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-like-data.md +1 -1
  135. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-profile-data.md +1 -1
  136. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-user-share-data.md +1 -1
  137. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/get-video-pack.md +48 -3
  138. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/modify-activity.md +1 -1
  139. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/query-activity-info.md +1 -1
  140. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/query-activity-user-completion-status.md +1 -1
  141. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/query-room-data.md +1 -1
  142. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/search-experience.md +1 -1
  143. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/search-general.md +1 -1
  144. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/search-live.md +1 -1
  145. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/search-music.md +1 -1
  146. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/search-user.md +1 -1
  147. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/search-video.md +1 -1
  148. package/card-skills/douyin-interest-card-capability/references/opencard/openapi/search-vision.md +1 -1
  149. package/card-skills/douyin-interest-card-capability/scripts/search-capabilities.mjs +7 -4
  150. package/card-skills/douyin-interest-card-cli/SKILL.md +11 -5
  151. package/card-skills/douyin-interest-card-generate/SKILL.md +5 -3
  152. package/card-skills/douyin-interest-card-generate/init.sh +13 -23
  153. package/card-skills/douyin-interest-card-generate/references/common/fullstack.md +6 -10
  154. package/card-skills/douyin-interest-card-generate/references/common/post-card-differences.md +29 -3
  155. package/card-skills/douyin-interest-card-generate/references/common/private-data-intent-routing.md +1 -1
  156. package/card-skills/douyin-interest-card-generate/references/common/upgrade-to-post.md +29 -6
  157. package/card-skills/douyin-interest-card-generate/references/microapp/microapp.md +1 -1
  158. package/card-skills/douyin-interest-card-generate/references/opencard/api.md +8 -0
  159. package/card-skills/douyin-interest-card-generate/references/opencard/closed-domain-card.md +1 -1
  160. package/card-skills/douyin-interest-card-generate/references/opencard/components.md +11 -28
  161. package/card-skills/douyin-interest-card-generate/references/opencard/opencard.md +9 -7
  162. package/card-skills/douyin-interest-card-generate/references/opencard/rendering.md +5 -5
  163. package/card-skills/douyin-interest-card-generate/references/opencard/taro-dsl.md +6 -6
  164. package/card-skills/douyin-interest-card-generate/scripts/inspect-post-upgrade.mjs +630 -0
  165. package/card-skills/douyin-interest-card-generate/templates/fragments/opencard/package.json +2 -2
  166. package/card-skills/douyin-interest-card-generate/templates/fragments/opencard/pnpm-lock.yaml +17 -17
  167. package/card-skills/douyin-interest-card-generate/templates/taro/closed-domain-server/package.json +1 -1
  168. package/card-skills/douyin-interest-card-generate/templates/taro/package.json +5 -4
  169. package/card-skills/douyin-interest-card-generate/templates/taro/pnpm-lock.yaml +27 -26
  170. package/card-skills/douyin-interest-card-generate/templates/taro/server/package.json +1 -1
  171. package/dist/src/args.js +23 -8
  172. package/dist/src/browser.js +3 -1
  173. package/dist/src/card/agent-chat.js +4 -0
  174. package/dist/src/card/binding.js +2 -1
  175. package/dist/src/card/candidate.js +90 -0
  176. package/dist/src/card/card-api.js +2 -2
  177. package/dist/src/card/card-token.js +25 -2
  178. package/dist/src/card/chat-commands.js +26 -11
  179. package/dist/src/card/constants.js +5 -0
  180. package/dist/src/card/create-project-client.js +2 -2
  181. package/dist/src/card/create.js +29 -3
  182. package/dist/src/card/editor-client.js +41 -6
  183. package/dist/src/card/editor-fs.js +4 -4
  184. package/dist/src/card/global-skills.js +6 -1
  185. package/dist/src/card/handlers-misc.js +3 -6
  186. package/dist/src/card/handlers.js +32 -24
  187. package/dist/src/card/help.js +6 -4
  188. package/dist/src/card/ignore.js +22 -0
  189. package/dist/src/card/project.js +13 -4
  190. package/dist/src/card-install.js +8 -9
  191. package/dist/src/cli.js +5 -2
  192. package/dist/src/config.js +26 -3
  193. package/dist/src/creator-device-login.js +2 -1
  194. package/dist/src/creator-login-session.js +6 -6
  195. package/dist/src/creator-passport-login.js +8 -2
  196. package/dist/src/creator-session.js +30 -7
  197. package/dist/src/current-user.js +29 -0
  198. package/dist/src/help-access.js +22 -0
  199. package/dist/src/help.js +6 -2
  200. package/dist/src/http.js +4 -4
  201. package/dist/src/login-handlers.js +2 -1
  202. package/dist/src/platform-process.js +98 -0
  203. package/dist/src/platform.js +1 -1
  204. package/dist/src/request-source.js +4 -0
  205. package/dist/src/telemetry-session.js +17 -0
  206. package/dist/src/telemetry.js +7 -2
  207. package/dist/src/update-check.js +5 -3
  208. package/dist/src/upgrade.js +56 -12
  209. package/package.json +1 -1
  210. package/card-skills/douyin-interest-card-capability/references/opencard/component/svg.md +0 -58
@@ -8,6 +8,8 @@ import { sleep } from './cli-helpers.js';
8
8
  import { resolveConfigPath } from './config.js';
9
9
  import { formatCreatorQrExpiry } from './external-login/passport-utils.js';
10
10
  import { printText } from './output.js';
11
+ import { LINK_LOGIN_FALLBACK } from './browser.js';
12
+ import { DETACHED_WORKER_OPTIONS, writeFileReplacing } from './platform-process.js';
11
13
  import { renderQrCode } from './qr.js';
12
14
  import { CliError } from './types.js';
13
15
  /** Private argv flag for the background process that keeps the QR session alive. */
@@ -83,15 +85,13 @@ function isInside(child, parent) {
83
85
  }
84
86
  export async function publishCreatorLoginStatus(configPath, status) {
85
87
  const target = creatorLoginStatusPath(configPath);
86
- const temporary = `${target}.${process.pid}.tmp`;
87
88
  await fs.mkdir(path.dirname(target), { recursive: true });
88
89
  // The status may hold a link authorization's device_code: owner-only, like the config file.
89
- await fs.writeFile(temporary, JSON.stringify({
90
+ await writeFileReplacing(target, JSON.stringify({
90
91
  ...status,
91
92
  pid: status.pid ?? process.pid,
92
93
  configPath: resolveConfigPath(configPath),
93
- }), { mode: 0o600 });
94
- await fs.rename(temporary, target);
94
+ }), 0o600);
95
95
  await fs.chmod(target, 0o600).catch(() => undefined);
96
96
  }
97
97
  /** The detached login finished: the status file must stop saying it waits for a scan. */
@@ -127,7 +127,7 @@ export async function detachCreatorLogin(parsed, options, deps = {}) {
127
127
  // Link authorization is the default login, so the QR worker is told to stay on the QR flow.
128
128
  ...sessionWorkerArgs(argv.slice(2).filter(arg => arg !== '--qr')),
129
129
  '--qr',
130
- ], { detached: true, stdio: 'ignore', cwd: process.cwd(), env: process.env });
130
+ ], { ...DETACHED_WORKER_OPTIONS, stdio: 'ignore', cwd: process.cwd(), env: process.env });
131
131
  child.on('error', () => undefined);
132
132
  child.unref();
133
133
  let status;
@@ -195,7 +195,7 @@ async function waitForHandoff(statusPath, pid, deps) {
195
195
  }
196
196
  await pause(200);
197
197
  }
198
- throw new CliError('Creator center QR login did not produce a QR code. Run `interest-card-cli login --platform creator --json` again.', 'PASSPORT_QR_INIT_TIMEOUT');
198
+ throw new CliError(`Creator center QR login did not produce a QR code. ${LINK_LOGIN_FALLBACK}`, 'PASSPORT_QR_INIT_TIMEOUT');
199
199
  }
200
200
  function sessionWorkerArgs(args) {
201
201
  return [
@@ -1,4 +1,4 @@
1
- import { launchLoginBrowser } from './browser.js';
1
+ import { LINK_LOGIN_FALLBACK, launchLoginBrowser } from './browser.js';
2
2
  import { getNumber, sleep } from './cli-helpers.js';
3
3
  import { createCookieCredentialConfig, getConfigBaseUrl, sanitizeConfig, saveConfig, } from './config.js';
4
4
  import { tokenLoginConfig } from './card/card-token.js';
@@ -46,7 +46,13 @@ export async function handleCreatorPassportLogin(parsed, options) {
46
46
  watchPassportResponses(page, parsed, qrState, notify, publishScan);
47
47
  notify('Starting creator center QR login...');
48
48
  await openCreatorLogin(page, options.baseUrl);
49
- await qrState.waitForQr(Math.min(30, timeoutSeconds));
49
+ await qrState.waitForQr(Math.min(30, timeoutSeconds)).catch((error) => {
50
+ // The login page never showed a QR code here; link authorization does not need the page.
51
+ if (error instanceof CliError && error.code === 'PASSPORT_QR_INIT_TIMEOUT') {
52
+ throw new CliError(`${error.message} ${LINK_LOGIN_FALLBACK}`, error.code);
53
+ }
54
+ throw error;
55
+ });
50
56
  await waitUntilConfirmed(qrState, page, options.baseUrl, {
51
57
  timeoutSeconds,
52
58
  intervalSeconds,
@@ -2,6 +2,7 @@ import { cardApi } from './card/card-api.js';
2
2
  import { isCardGateError } from './card/card-token.js';
3
3
  import { CARD_API_ROUTES } from './card/constants.js';
4
4
  import { requestJson } from './http.js';
5
+ import { noteSessionCheckRetry } from './telemetry-session.js';
5
6
  import { CliError } from './types.js';
6
7
  /** Douyin passport app id of the creator center (see apps/creator-application creator-logout). */
7
8
  export const CREATOR_PASSPORT_AID = 2906;
@@ -13,12 +14,25 @@ export const CREATOR_PASSPORT_AID = 2906;
13
14
  * and a service that is down or unreachable are reported as what they are: scanning again does
14
15
  * not fix any of them.
15
16
  */
16
- export async function verifyCreatorSession(config) {
17
- try {
18
- await cardApi(config, CARD_API_ROUTES.tenantList, {});
19
- }
20
- catch (error) {
21
- throw sessionCheckError(error);
17
+ /** How long the login waits for a card service that answers 5xx, and how often it asks again. */
18
+ export const SESSION_CHECK_RETRY_WINDOW_MS = 30_000;
19
+ const SESSION_CHECK_RETRY_INTERVAL_MS = 3_000;
20
+ export async function verifyCreatorSession(config, options = {}) {
21
+ const now = options.now ?? Date.now;
22
+ const pause = options.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
23
+ const deadline = now() + (options.retryServerErrorMs ?? 0);
24
+ for (;;) {
25
+ try {
26
+ await cardApi(config, CARD_API_ROUTES.tenantList, {});
27
+ break;
28
+ }
29
+ catch (error) {
30
+ if (!isServerError(error) || now() + SESSION_CHECK_RETRY_INTERVAL_MS > deadline) {
31
+ throw sessionCheckError(error);
32
+ }
33
+ noteSessionCheckRetry();
34
+ await pause(SESSION_CHECK_RETRY_INTERVAL_MS);
35
+ }
22
36
  }
23
37
  const account = await requestJson(config, {
24
38
  path: '/passport/web/account/info/',
@@ -26,7 +40,9 @@ export async function verifyCreatorSession(config) {
26
40
  assertBusinessSuccess: false,
27
41
  }).catch(() => undefined);
28
42
  const data = account?.data || {};
29
- const userId = String(data.user_id_str || data.user_id || '').trim();
43
+ const rawId = data.user_id_str || data.user_id;
44
+ const userId = typeof rawId === 'number' && !Number.isSafeInteger(rawId)
45
+ ? '' : String(rawId || '').trim();
30
46
  return {
31
47
  id: userId,
32
48
  email: userId || 'creator',
@@ -35,6 +51,13 @@ export async function verifyCreatorSession(config) {
35
51
  avatar: data.avatar_url || '',
36
52
  };
37
53
  }
54
+ function isServerError(error) {
55
+ if (isCardGateError(error) || !(error instanceof CliError)) {
56
+ return false;
57
+ }
58
+ const status = error.details?.status;
59
+ return typeof status === 'number' && status >= 500;
60
+ }
38
61
  function sessionCheckError(error) {
39
62
  if (isCardGateError(error)) {
40
63
  return error;
@@ -0,0 +1,29 @@
1
+ import { printText } from './output.js';
2
+ import { CliError } from './types.js';
3
+ import { cardApi } from './card/card-api.js';
4
+ import { saveCandidateCapability } from './config.js';
5
+ import { cliSourceHeaders } from './request-source.js';
6
+ import { CARD_API_ROUTES, getCardApiBaseUrl } from './card/constants.js';
7
+ import { getCardPpeHeaders, loadCardConfig } from './card/project.js';
8
+ export function candidateCapabilityRoute(parsed) {
9
+ return JSON.stringify([getCardApiBaseUrl(), cliSourceHeaders(getCardPpeHeaders(parsed)['x-tt-env'])['x-tt-env'] ?? '']);
10
+ }
11
+ /** Resolve the current account from the authenticated server, never a project owner or cached email. */
12
+ export async function handleWhoami(parsed) {
13
+ const { config } = await loadCardConfig(parsed);
14
+ const response = await cardApi(config, CARD_API_ROUTES.authMe, {}, { headers: getCardPpeHeaders(parsed) });
15
+ const uid = response.data?.uid;
16
+ if (typeof uid !== 'string' || !/^[1-9][0-9]*$/.test(uid)) {
17
+ throw new CliError('The identity endpoint did not return a valid UID string.', 'CURRENT_USER_ID_UNAVAILABLE');
18
+ }
19
+ const capabilities = { candidate_testing: response.data?.capabilities?.candidate_testing === true };
20
+ if (config.token_type === 'Bearer') {
21
+ await saveCandidateCapability(config, candidateCapabilityRoute(parsed), capabilities.candidate_testing)
22
+ .catch(() => undefined);
23
+ }
24
+ const result = { ok: true, command: 'whoami', baseUrl: config.base_url,
25
+ data: { uid, source: 'cli_auth_me', capabilities } };
26
+ if (!parsed.options.json)
27
+ printText(uid);
28
+ return result;
29
+ }
@@ -0,0 +1,22 @@
1
+ import { hasExplicitPlatform, resolveCommandConfigPath } from './command-context.js';
2
+ import { readCandidateCapability, tryLoadConfig } from './config.js';
3
+ import { helpText } from './help.js';
4
+ import { candidateCapabilityRoute } from './current-user.js';
5
+ /** Help reads cached display preferences. Candidate authorization is enforced by the service. */
6
+ async function canShowTestingHelp(parsed) {
7
+ try {
8
+ const scoped = hasExplicitPlatform(parsed) ? parsed
9
+ : { ...parsed, options: { ...parsed.options, platform: 'creator' } };
10
+ const config = await tryLoadConfig(resolveCommandConfigPath(scoped));
11
+ if (config?.token_type !== 'Bearer' || !(Date.parse(config.expires_at) > Date.now()))
12
+ return false;
13
+ return await readCandidateCapability(config, candidateCapabilityRoute(parsed));
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ export async function resolvedHelpText(parsed, command) {
20
+ const needsAccess = !['install', 'card-install', 'login', 'logout', 'upgrade', 'version', 'browser'].includes(command ?? '');
21
+ return helpText(command, needsAccess && await canShowTestingHelp(parsed));
22
+ }
package/dist/src/help.js CHANGED
@@ -1,7 +1,11 @@
1
1
  import { cardHelp } from './card/help.js';
2
2
  import { DEFAULT_CREATOR_CONFIG_PATH, getCliVersion } from './types.js';
3
- export function helpText(command) {
3
+ export function helpText(command, testingAllowed = false) {
4
4
  switch (command) {
5
+ case 'whoami':
6
+ return testingAllowed
7
+ ? 'interest-card-cli whoami [--platform creator] [--config <path>] [--ppe <lane>] [--json]'
8
+ : cardHelp(false);
5
9
  case 'install':
6
10
  case 'card-install':
7
11
  return installHelp();
@@ -15,7 +19,7 @@ export function helpText(command) {
15
19
  case 'browser':
16
20
  return browserHelp();
17
21
  default:
18
- return cardHelp();
22
+ return cardHelp(testingAllowed);
19
23
  }
20
24
  }
21
25
  function installHelp() {
package/dist/src/http.js CHANGED
@@ -126,12 +126,12 @@ export function getAgentTraceDetail(config, params) {
126
126
  },
127
127
  });
128
128
  }
129
- export async function verifyAuth(config) {
130
- await verifyUserSession(config);
129
+ export async function verifyAuth(config, options = {}) {
130
+ await verifyUserSession(config, options);
131
131
  }
132
- export async function verifyUserSession(config) {
132
+ export async function verifyUserSession(config, options = {}) {
133
133
  if (isCreatorPlatform(getConfigBaseUrl(config))) {
134
- return verifyCreatorSession(config);
134
+ return verifyCreatorSession(config, options);
135
135
  }
136
136
  const response = await requestJson(config, {
137
137
  path: '/api/getUserInfo',
@@ -4,6 +4,7 @@ import { getNumber } from './cli-helpers.js';
4
4
  import { handleCreatorDeviceLogin, LINK_SENT_FLAG, requireLinkSentBeforeWait, waitForPendingLinkLogin, } from './creator-device-login.js';
5
5
  import { handleCreatorBrowserLogin } from './creator-login.js';
6
6
  import { isCreatorLoginSession } from './creator-login-session.js';
7
+ import { SESSION_CHECK_RETRY_WINDOW_MS } from './creator-session.js';
7
8
  import { handleCreatorPassportLogin } from './creator-passport-login.js';
8
9
  import { isCreatorPlatform } from './platform.js';
9
10
  import { verifyAuth } from './http.js';
@@ -79,7 +80,7 @@ async function reuseExistingLogin(parsed, previous, targetConfigPath, targetBase
79
80
  const runtimePrevious = applyRuntimeConfigOverrides(previous, parsed);
80
81
  try {
81
82
  if (!parsed.options['skip-verify']) {
82
- await verifyAuth(runtimePrevious);
83
+ await verifyAuth(runtimePrevious, { retryServerErrorMs: SESSION_CHECK_RETRY_WINDOW_MS });
83
84
  }
84
85
  const resolvedPath = resolveConfigPath(targetConfigPath);
85
86
  if (!parsed.options.json) {
@@ -0,0 +1,98 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ /** Tools that Windows ships as `.cmd` shims rather than executables. */
4
+ const WINDOWS_SHIMS = new Set(['npm', 'npx']);
5
+ /**
6
+ * How to start `command` on this platform. Node cannot start a Windows `.cmd` shim directly
7
+ * (`spawn npm ENOENT`), so npm and npx go through cmd.exe there, with every argument quoted here
8
+ * because Node joins shell arguments without quoting them.
9
+ */
10
+ export function commandInvocation(command, args, platform = process.platform) {
11
+ if (platform !== 'win32' || !WINDOWS_SHIMS.has(command)) {
12
+ return { command, args, options: { windowsHide: true } };
13
+ }
14
+ // One command line and no argument list: Node warns (DEP0190) about arguments passed to a shell.
15
+ return {
16
+ command: [command, ...args.map(quoteForCmd)].join(' '),
17
+ args: [],
18
+ options: { shell: true, windowsHide: true },
19
+ };
20
+ }
21
+ /** Quotes one argument for cmd.exe: spaces and `&|<>^()` are literal inside double quotes. */
22
+ export function quoteForCmd(arg) {
23
+ if (/^[A-Za-z0-9_\-.:/=@\\,+]+$/.test(arg)) {
24
+ return arg;
25
+ }
26
+ // Backslashes before a quote, or before the closing quote, must be doubled for the program
27
+ // that parses the command line after cmd.exe.
28
+ const escaped = arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1');
29
+ return `"${escaped}"`;
30
+ }
31
+ /** A detached child gets its own console window on Windows unless it is hidden. */
32
+ export const DETACHED_WORKER_OPTIONS = { detached: true, windowsHide: true };
33
+ /** What to run so the system opens `url` in the default browser. */
34
+ export function browserOpenCommand(url, platform = process.platform) {
35
+ if (platform === 'darwin') {
36
+ return ['open', [url]];
37
+ }
38
+ if (platform === 'win32') {
39
+ // Not `cmd /c start`: cmd.exe would cut the URL at the first `&`.
40
+ return ['rundll32', ['url.dll,FileProtocolHandler', url]];
41
+ }
42
+ return ['xdg-open', [url]];
43
+ }
44
+ /** Why a child process could not start, in words a user can act on. */
45
+ export function spawnFailureCause(command, error) {
46
+ const message = error instanceof Error ? error.message : String(error);
47
+ if (error?.code === 'ENOENT') {
48
+ return `${command} was not found on PATH (${message}). Install Node.js with npm, then reopen the terminal.`;
49
+ }
50
+ return message;
51
+ }
52
+ const BUSY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
53
+ const BUSY_RETRY_DELAYS_MS = [10, 25, 50, 100, 200, 400];
54
+ /**
55
+ * Runs a file operation, retrying on Windows while another process (a second CLI command, an
56
+ * antivirus scan, the search indexer) briefly holds the file.
57
+ */
58
+ export async function retryWhileBusy(operation, platform = process.platform) {
59
+ for (const delay of platform === 'win32' ? BUSY_RETRY_DELAYS_MS : []) {
60
+ try {
61
+ return await operation();
62
+ }
63
+ catch (error) {
64
+ if (!BUSY_CODES.has(error.code ?? '')) {
65
+ throw error;
66
+ }
67
+ await new Promise(resolve => setTimeout(resolve, delay));
68
+ }
69
+ }
70
+ return operation();
71
+ }
72
+ /** `fs.rename` over an existing file, which Windows refuses while the target is open. */
73
+ export async function renameReplacing(from, to, platform = process.platform, rename = fs.rename) {
74
+ await retryWhileBusy(() => rename(from, to), platform);
75
+ }
76
+ /**
77
+ * Replaces `target` with `content` through a temporary file. The temporary name is unique per
78
+ * write: two writes from one process must not share a file, or Windows fails the second open.
79
+ */
80
+ export async function writeFileReplacing(target, content, mode) {
81
+ const temporary = `${target}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
82
+ try {
83
+ await retryWhileBusy(() => fs.writeFile(temporary, content, { mode }));
84
+ await renameReplacing(temporary, target);
85
+ }
86
+ catch (error) {
87
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
88
+ throw error;
89
+ }
90
+ }
91
+ /** Whether two absolute paths are the same directory or `target` is inside `base`. */
92
+ export function isSameOrInside(base, target, platform = process.platform) {
93
+ const sep = platform === 'win32' ? '\\' : '/';
94
+ // Windows paths are case-insensitive, and the drive letter's case varies between tools.
95
+ const fold = (value) => (platform === 'win32' ? value.toLowerCase() : value);
96
+ const [a, b] = [fold(base), fold(target)];
97
+ return a === b || b.startsWith(a.endsWith(sep) ? a : `${a}${sep}`);
98
+ }
@@ -95,7 +95,7 @@ function resolveConfigPathValue(configPath, homeDir = os.homedir()) {
95
95
  if (configPath === '~') {
96
96
  return homeDir;
97
97
  }
98
- if (configPath.startsWith('~/')) {
98
+ if (configPath.startsWith('~/') || configPath.startsWith('~\\')) {
99
99
  return path.join(homeDir, configPath.slice(2));
100
100
  }
101
101
  return path.resolve(configPath);
@@ -33,3 +33,7 @@ export const CLI_SOURCE_HEADERS = {
33
33
  [CLI_SOURCE_HEADER_NAME]: CLI_SOURCE_HEADER_VALUE,
34
34
  ...laneHeaders(),
35
35
  };
36
+ /** An explicit PPE flag takes precedence over the environment lane. */
37
+ export function cliSourceHeaders(ppe) {
38
+ return ppe ? { [CLI_SOURCE_HEADER_NAME]: CLI_SOURCE_HEADER_VALUE, 'x-tt-env': ppe, 'x-use-ppe': '1' } : CLI_SOURCE_HEADERS;
39
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * How many times the login check (tenant/list) was retried after a 5xx in this run, for the
3
+ * command's telemetry event. Only `login` retries: right after the server binds the shared
4
+ * invitation code for a new creator, the platform may still answer from a stale cache.
5
+ */
6
+ let retries = 0;
7
+ /** Never throws. */
8
+ export function noteSessionCheckRetry() {
9
+ retries += 1;
10
+ }
11
+ export function notedSessionCheckRetries() {
12
+ return retries;
13
+ }
14
+ /** For tests: one process there runs many commands. */
15
+ export function resetSessionCheckRetries() {
16
+ retries = 0;
17
+ }
@@ -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 { DETACHED_WORKER_OPTIONS } from './platform-process.js';
7
8
  import { readBinding, findProjectRoot } from './card/binding.js';
8
9
  import { CARD_PROJECT_PAGE_URL } from './card/constants.js';
9
10
  import { getString } from './cli-helpers.js';
@@ -12,6 +13,7 @@ import { getConfigBaseUrl, resolveConfigPath, tryLoadConfig } from './config.js'
12
13
  import { isCreatorPlatform, isExternalPlatform } from './platform.js';
13
14
  import { laneHeaders } from './request-source.js';
14
15
  import { notedTelemetryProject } from './telemetry-project.js';
16
+ import { notedSessionCheckRetries } from './telemetry-session.js';
15
17
  import { CliError, DEFAULT_CONFIG_DIR } from './types.js';
16
18
  import { getCliVersion } from './version.js';
17
19
  /**
@@ -93,7 +95,8 @@ const ERROR_MESSAGE_REDACTIONS = [
93
95
  '$1<redacted>',
94
96
  ],
95
97
  [/[A-Za-z0-9+/_-]{40,}={0,2}/g, '<redacted>'],
96
- [/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, '<email>'],
98
+ // Not `@scope/name@1.2.3`: a package spec looks like an address but says which install failed.
99
+ [/(?<!@[\w.-]+\/[\w.+-]*)[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, '<email>'],
97
100
  // A query string can carry anything; the path is enough to tell which request failed.
98
101
  [/(https?:\/\/[^\s?#"']+)[?#][^\s"']*/g, '$1'],
99
102
  ];
@@ -293,6 +296,7 @@ export function buildTelemetryJob(telemetry, identity, options = {}) {
293
296
  login: identity.userId ? '1' : '0',
294
297
  auth_type: identity.authType || 'none',
295
298
  login_method: telemetry.loginMethod || '',
299
+ session_check_retries: Math.max(0, Math.round(telemetry.sessionCheckRetries || 0)),
296
300
  user_id: identity.userId || '',
297
301
  cli_device_id: identity.deviceId,
298
302
  client: 'interest_card_cli',
@@ -337,6 +341,7 @@ export async function reportCommand(parsed, outcome) {
337
341
  projectId: project.projectId,
338
342
  attemptId: outcome.attemptId,
339
343
  loginMethod: telemetryLoginMethod(parsed),
344
+ sessionCheckRetries: notedSessionCheckRetries(),
340
345
  }, identity);
341
346
  spawnSender(job);
342
347
  }
@@ -519,7 +524,7 @@ function spawnSender(job) {
519
524
  const file = path.join(dir, 'job.json');
520
525
  fs.writeFileSync(file, JSON.stringify(job), { mode: 0o600 });
521
526
  const child = spawn(process.execPath, [sender, file], {
522
- detached: true,
527
+ ...DETACHED_WORKER_OPTIONS,
523
528
  stdio: 'ignore',
524
529
  });
525
530
  child.on('error', () => fs.rmSync(dir, { recursive: true, force: true }));
@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { resolveConfigPath } from './config.js';
6
+ import { commandInvocation, DETACHED_WORKER_OPTIONS, renameReplacing } from './platform-process.js';
6
7
  import { compareVersions, isPublishedVersion, releaseChannel, STABLE_CHANNEL } from './semver.js';
7
8
  import { DEFAULT_CONFIG_DIR } from './types.js';
8
9
  import { getCliVersion } from './version.js';
@@ -95,7 +96,7 @@ export async function rememberDistTags(distTags, homeDir = os.homedir(), checked
95
96
  try {
96
97
  await fs.mkdir(path.dirname(filePath), { recursive: true });
97
98
  await fs.writeFile(tempPath, `${JSON.stringify(body, null, 2)}\n`);
98
- await fs.rename(tempPath, filePath);
99
+ await renameReplacing(tempPath, filePath);
99
100
  }
100
101
  catch {
101
102
  await fs.rm(tempPath, { force: true }).catch(() => undefined);
@@ -134,7 +135,7 @@ export function scheduleUpdateCacheRefresh() {
134
135
  }
135
136
  const execArgv = process.execArgv.filter(arg => !arg.includes('inspect'));
136
137
  const child = spawn(process.execPath, [...execArgv, entry, REFRESH_ARG], {
137
- detached: true,
138
+ ...DETACHED_WORKER_OPTIONS,
138
139
  stdio: 'ignore',
139
140
  });
140
141
  child.on('error', () => undefined);
@@ -231,7 +232,8 @@ function safeCliVersion() {
231
232
  }
232
233
  function runCapture(command, args, timeoutMs) {
233
234
  return new Promise((resolve, reject) => {
234
- const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
235
+ const run = commandInvocation(command, args);
236
+ const child = spawn(run.command, run.args, { ...run.options, stdio: ['ignore', 'pipe', 'pipe'] });
235
237
  let stdout = '';
236
238
  let stderr = '';
237
239
  const timer = setTimeout(() => {
@@ -5,6 +5,7 @@ import { printText } from './output.js';
5
5
  import { findProjectRoot } from './card/binding.js';
6
6
  import { installGlobalSkills, readGlobalStamp } from './card/global-skills.js';
7
7
  import { upgradeCardSkills } from './card/skills.js';
8
+ import { commandInvocation, isSameOrInside, spawnFailureCause } from './platform-process.js';
8
9
  import { CliError } from './types.js';
9
10
  import { CLI_PACKAGE_NAME, CLI_INTERNAL_REGISTRY, CLI_REGISTRY, CLI_SCOPE_REGISTRY_ARG, installCommand, queryRegistryDistTags, rememberDistTags, scopeRegistryArg, upgradeTarget, } from './update-check.js';
10
11
  import { getCliPackageDir, getCliVersion } from './version.js';
@@ -130,9 +131,7 @@ export async function isGlobalInstall() {
130
131
  if (!root) {
131
132
  return false;
132
133
  }
133
- const packageDir = path.resolve(getCliPackageDir());
134
- const globalRoot = path.resolve(root);
135
- return packageDir === globalRoot || packageDir.startsWith(`${globalRoot}${path.sep}`);
134
+ return isSameOrInside(path.resolve(root), path.resolve(getCliPackageDir()));
136
135
  }
137
136
  /** The registry that answered the last dist-tag query; the upgrade installs from it. */
138
137
  let answeredRegistry;
@@ -162,16 +161,38 @@ export async function installGlobalPackage(version, json) {
162
161
  '--registry',
163
162
  registry,
164
163
  scopeRegistryArg(registry),
165
- ], json);
164
+ ], json, true);
166
165
  }
167
166
  catch (error) {
168
- const cause = error instanceof Error ? error.message : String(error);
167
+ const cause = failureCause(error);
168
+ const stderr = capturedStderr(error);
169
169
  throw new CliError(`Could not install ${CLI_PACKAGE_NAME}@${version}.`, 'CARD_UPGRADE_FAILED', {
170
170
  cause,
171
171
  installCommand: installCommand(version, registry),
172
+ ...(stderr ? { stderr } : {}),
173
+ hint: installFailureHint(stderr),
172
174
  });
173
175
  }
174
176
  }
177
+ const NPM_PERMISSION_ERROR = /\b(EACCES|EPERM|EROFS)\b|permission denied|operation not permitted|read-only file system/i;
178
+ const NPM_NETWORK_ERROR = /\b(ENOTFOUND|ETIMEDOUT|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ENETUNREACH|ERR_SOCKET_TIMEOUT)\b|network (request|error|timeout)|socket hang up/i;
179
+ /** What to do next after `npm install -g` failed, judged from what npm printed. */
180
+ export function installFailureHint(stderr) {
181
+ const text = stderr ?? '';
182
+ if (NPM_PERMISSION_ERROR.test(text)) {
183
+ return 'npm could not write to its global directory. Agents in a sandbox: rerun this command with write access outside the sandbox. Otherwise fix the permissions of the npm global prefix, or run installCommand yourself.';
184
+ }
185
+ if (NPM_NETWORK_ERROR.test(text)) {
186
+ return 'npm could not reach the registry. Agents in a sandbox: rerun this command with network access. Otherwise check the network or npm proxy settings.';
187
+ }
188
+ return 'See stderr for what npm reported. Agents in a sandbox: rerun this command with network access and write access outside the sandbox. Otherwise run installCommand yourself.';
189
+ }
190
+ const STDERR_TAIL_CHARS = 2000;
191
+ /** The end of what a failed child printed to stderr, when it was captured. */
192
+ function capturedStderr(error) {
193
+ const stderr = error instanceof CliError ? error.details?.stderr : undefined;
194
+ return typeof stderr === 'string' && stderr.trim() ? stderr.trim() : undefined;
195
+ }
175
196
  async function refreshProjectSkills(parsed, useInstalledCli = false, json = false) {
176
197
  const root = await findProjectRoot(getString(parsed, 'dir') || process.cwd()).catch(() => undefined);
177
198
  if (!root) {
@@ -183,9 +204,16 @@ async function refreshProjectSkills(parsed, useInstalledCli = false, json = fals
183
204
  }
184
205
  return upgradeCardSkills(root);
185
206
  }
207
+ /** The message of a failed child process, with the reason it could not start when there is one. */
208
+ function failureCause(error) {
209
+ const message = error instanceof Error ? error.message : String(error);
210
+ const cause = error instanceof CliError ? error.details?.cause : undefined;
211
+ return typeof cause === 'string' && cause ? `${message} ${cause}` : message;
212
+ }
186
213
  function runCapture(command, args) {
187
214
  return new Promise((resolve, reject) => {
188
- const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
215
+ const run = commandInvocation(command, args);
216
+ const child = spawn(run.command, run.args, { ...run.options, stdio: ['ignore', 'pipe', 'pipe'] });
189
217
  let stdout = '';
190
218
  let stderr = '';
191
219
  child.stdout.on('data', chunk => {
@@ -198,23 +226,39 @@ function runCapture(command, args) {
198
226
  child.on('close', code => resolve({ code: code ?? 1, stdout, stderr }));
199
227
  }).catch((error) => {
200
228
  throw new CliError(`Failed to run ${command}.`, 'CARD_UPGRADE_FAILED', {
201
- cause: error instanceof Error ? error.message : String(error),
229
+ cause: spawnFailureCause(command, error),
202
230
  });
203
231
  });
204
232
  }
205
- /** With --json, child output goes to stderr so stdout stays one JSON document. */
206
- function runInherit(command, args, json = false) {
233
+ /**
234
+ * With --json, child output goes to stderr so stdout stays one JSON document.
235
+ * With captureStderr, the child's stderr is still shown as it arrives, and its tail is kept
236
+ * on the error (details.stderr) so a failure can say what the child reported.
237
+ */
238
+ export function runInherit(command, args, json = false, captureStderr = false) {
207
239
  return new Promise((resolve, reject) => {
208
- const child = spawn(command, args, { stdio: json ? ['ignore', 2, 2] : 'inherit' });
240
+ const run = commandInvocation(command, args);
241
+ const stderrTarget = captureStderr ? 'pipe' : json ? 2 : 'inherit';
242
+ const child = spawn(run.command, run.args, {
243
+ ...run.options,
244
+ stdio: json ? ['ignore', 2, stderrTarget] : ['inherit', 'inherit', stderrTarget],
245
+ });
246
+ let stderrTail = '';
247
+ child.stderr?.on('data', chunk => {
248
+ process.stderr.write(chunk);
249
+ stderrTail = (stderrTail + String(chunk)).slice(-STDERR_TAIL_CHARS);
250
+ });
209
251
  child.on('error', error => {
210
- reject(new CliError(`Failed to run ${command}.`, 'CARD_UPGRADE_FAILED', { cause: error.message }));
252
+ reject(new CliError(`Failed to run ${command}.`, 'CARD_UPGRADE_FAILED', {
253
+ cause: spawnFailureCause(command, error),
254
+ }));
211
255
  });
212
256
  child.on('close', code => {
213
257
  if (code === 0) {
214
258
  resolve();
215
259
  return;
216
260
  }
217
- reject(new CliError(`${command} exited with ${code}.`, 'CARD_UPGRADE_FAILED'));
261
+ reject(new CliError(`${command} exited with ${code}.`, 'CARD_UPGRADE_FAILED', stderrTail.trim() ? { stderr: stderrTail } : undefined));
218
262
  });
219
263
  });
220
264
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-dy/interest-card-cli",
3
- "version": "0.1.0-beta.30",
3
+ "version": "0.1.0-beta.32",
4
4
  "description": "Pull, edit and sync Douyin interest card projects locally with any AI agent",
5
5
  "private": false,
6
6
  "type": "module",