huaweicloud-devkit 2.0.0-next.3 → 2.0.0-next.4

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 (161) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-plan.js +62 -61
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  24. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  25. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  26. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  27. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  28. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  31. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  32. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  33. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  34. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  35. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  36. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  37. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6506 -912
  39. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  40. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  41. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  42. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  43. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  44. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  45. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  46. package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
  47. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
  55. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  56. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  57. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  58. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  59. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  60. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  61. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  62. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  63. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  64. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  65. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  66. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  67. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  68. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  69. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  72. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  73. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  74. package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
  75. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  76. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  77. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  78. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  79. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  80. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  81. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
  82. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  83. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  84. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
  85. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
  86. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  87. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  88. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  91. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  92. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  93. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  94. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  95. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  97. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  98. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  99. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  100. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  101. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  102. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  103. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  104. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  105. package/plugins/huaweicloud-core/src/hcloud-plan.ts +68 -70
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  107. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  108. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  109. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  110. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  111. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  112. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
  113. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  114. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  115. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  116. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  117. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  118. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  119. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  120. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  122. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  123. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  124. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  125. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  126. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  127. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  128. package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
  129. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  130. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
  131. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  132. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  133. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  134. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
  135. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
  136. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
  137. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  138. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  139. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  140. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  141. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  142. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  143. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  144. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  145. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  146. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  147. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
  148. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  149. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  150. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  151. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  152. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  153. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  154. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  155. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  156. package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
  157. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  158. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  159. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  160. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  161. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -5,15 +5,124 @@
5
5
  import { spawnSync, type SpawnSyncOptionsWithStringEncoding } from 'node:child_process';
6
6
 
7
7
  import { SUPPORTED_AGENT_TARGETS } from './auth/agent-registration.ts';
8
+ import { isCredentialEnvVarName } from './lib/secret-vault/refs.ts';
8
9
  import { determineTarget, semverCompare, type DistTags } from './update-semver.ts';
9
10
  import { readInstalledVersion } from './update-installed.ts';
10
- import { queryDistTags, errorMessage } from './update-registry.ts';
11
+ import { queryDistTags, errorMessage, resolveRegistryOverride, resolveEnvSpelling } from './update-registry.ts';
11
12
  import { invalidateUpdateCache } from './update-cache.ts';
12
13
 
13
14
  const NPX_BIN = process.platform === 'win32' ? 'npx.cmd' : 'npx';
14
15
 
16
+ // The upgrade child is arbitrary registry code and the published package needs
17
+ // no account, so it gets an environment without the credential family the
18
+ // vault predicate owns (case-normalized, so a Windows spelling cannot survive),
19
+ // plus dev 4890d78c's AWS keys and KooCLI's `HUAWEI_*` alias spellings, which the
20
+ // predicate does not claim.
21
+ const UPGRADE_EXTRA_CREDENTIAL_ENV_KEYS = new Set([
22
+ 'AWS_ACCESS_KEY_ID',
23
+ 'AWS_SECRET_ACCESS_KEY',
24
+ 'AWS_SESSION_TOKEN',
25
+ 'HUAWEI_ACCESS_KEY',
26
+ 'HUAWEI_SECRET_KEY',
27
+ 'GITHUB_ENTERPRISE_TOKEN',
28
+ 'GH_ENTERPRISE_TOKEN',
29
+ 'GITHUB_TOKEN',
30
+ 'GH_TOKEN',
31
+ 'DOCKER_PASSWORD',
32
+ 'DOCKER_AUTH_CONFIG',
33
+ 'GITLAB_TOKEN',
34
+ 'GITLAB_CI_JOB_TOKEN',
35
+ 'BITBUCKET_TOKEN',
36
+ 'AZURE_DEVOPS_EXT_PAT',
37
+ 'NPM_AUTH_TOKEN',
38
+ 'YARN_NPM_AUTH_TOKEN',
39
+ 'NUGET_API_KEY',
40
+ 'GOOGLE_APPLICATION_CREDENTIALS',
41
+ 'VAULT_TOKEN',
42
+ 'TERRAFORM_CLOUD_TOKEN',
43
+ 'HEROKU_API_KEY',
44
+ 'SLACK_TOKEN',
45
+ 'PYPI_TOKEN',
46
+ 'TWINE_PASSWORD',
47
+ 'HUAWEI_DOMAIN_TOKEN',
48
+ 'HUAWEI_SECURITY_TOKEN',
49
+ ]);
50
+
51
+ // The predicate's prefixes also cover the devkit's own configuration. These
52
+ // names are read by the child's update graph (registry, proxy, state root,
53
+ // binary resolution, install skips), so they pass through unchanged.
54
+ const UPGRADE_PRESERVE_ENV_KEYS = new Set([
55
+ 'HCLOUD_BIN',
56
+ 'HCLOUD_BIN_ARGS_JSON',
57
+ 'HCLOUD_CONFIG_PATH',
58
+ 'HCLOUD_META_DIR',
59
+ 'HCLOUD_OBS_CONFIG_PATH',
60
+ 'HUAWEICLOUD_DEVKIT_DEBUG',
61
+ 'HUAWEICLOUD_DEVKIT_HOME',
62
+ 'HUAWEICLOUD_DEVKIT_SKIP_DSH_PLUGIN_INSTALL',
63
+ 'HUAWEICLOUD_DEVKIT_SKIP_OFFICEACE_DETECT',
64
+ 'HUAWEICLOUD_DEVKIT_SKIP_UPDATE',
65
+ 'HUAWEICLOUD_DEVKIT_TELEMETRY',
66
+ 'HUAWEICLOUD_DEVKIT_TELEMETRY_ENDPOINT',
67
+ 'HUAWEICLOUD_HOME',
68
+ 'HUAWEICLOUD_ICONS_OFFLINE',
69
+ 'HUAWEICLOUD_INJECT_STS_CMD',
70
+ 'HUAWEICLOUD_MCP_POLICY_FILE',
71
+ 'HUAWEICLOUD_NPM_REGISTRY',
72
+ 'HUAWEICLOUD_OPENCODE_PERMISSION_SEAM',
73
+ 'HUAWEICLOUD_REGION',
74
+ 'HUAWEICLOUD_VENDOR_CHALLENGE',
75
+ 'HW_IAM_ENDPOINT',
76
+ 'HW_POOL_TEMPLATE_EPHEMERAL',
77
+ 'HW_POOL_TEMPLATE_PERSISTENT',
78
+ 'HW_REGION',
79
+ 'HW_SANDBOX_POOL_CACHE_PATH',
80
+ 'HW_STS_EXPIRES_AT',
81
+ 'HW_WORKSPACE_ID',
82
+ ]);
83
+
84
+ function upgradeEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
85
+ const next: NodeJS.ProcessEnv = {};
86
+ const registrySpellings: string[] = [];
87
+ for (const [key, value] of Object.entries(env)) {
88
+ // The vault predicate trims its spelling; the strip and preserve lists must
89
+ // agree, so a padded vendor key strips and a padded preserve key survives.
90
+ const upper = key.trim().toUpperCase();
91
+ if (upper === 'HUAWEICLOUD_NPM_REGISTRY') continue;
92
+ if (upper === 'NPM_CONFIG_REGISTRY') registrySpellings.push(key);
93
+ // npm's own auth channels are resolved after the loop through the shared
94
+ // spelling rule, matching the pre-flight query's bearer exactly.
95
+ if (upper === 'NPM_TOKEN' || upper === 'NODE_AUTH_TOKEN') continue;
96
+ if (UPGRADE_PRESERVE_ENV_KEYS.has(upper)) {
97
+ // A padded spelling cannot reach the child's exact-name lookup: forward
98
+ // the trimmed name, letting an existing exact spelling win.
99
+ const canonical = key.trim();
100
+ if (key === canonical || next[canonical] === undefined) next[canonical] = value;
101
+ continue;
102
+ }
103
+ if (isCredentialEnvVarName(key) || UPGRADE_EXTRA_CREDENTIAL_ENV_KEYS.has(upper)) continue;
104
+ next[key] = value;
105
+ }
106
+ // One canonical channel through the shared resolver, so the child's own
107
+ // devkit lookup, npm's pin, and the pre-flight query cannot disagree; empty
108
+ // and whitespace count as unset everywhere, and an unset override never pins.
109
+ const authKeys = ['NPM_TOKEN', 'NODE_AUTH_TOKEN'] as const;
110
+ for (const name of authKeys) {
111
+ const token = resolveEnvSpelling(env, name);
112
+ if (token) next[name] = token;
113
+ }
114
+ const registry = resolveRegistryOverride(env);
115
+ if (registry) {
116
+ next.HUAWEICLOUD_NPM_REGISTRY = registry;
117
+ for (const key of registrySpellings) delete next[key];
118
+ next.npm_config_registry = registry;
119
+ }
120
+ return next;
121
+ }
122
+
15
123
  interface SpawnResultLike {
16
124
  status?: number | null;
125
+ signal?: string | null;
17
126
  stdout?: string;
18
127
  stderr?: string;
19
128
  error?: { message?: string } | null;
@@ -40,6 +149,1012 @@ function defaultSpawn(
40
149
  return spawnSync([command, ...args].join(' '), options);
41
150
  }
42
151
 
152
+ // npm reports failures as `npm error ...` lines (npm 7+) or `npm ERR! ...`
153
+ // (legacy), with ANSI color, pty spinners, warnings, notices, and log pointers
154
+ // around them. The tail is boilerplate, so the reason keeps the identifying
155
+ // code line plus the human diagnostic when the npm block wins; a strong
156
+ // code-less line wins alone, and a weak one inherits the code line (#1117).
157
+ const ESCAPE = String.fromCharCode(27);
158
+ const ANSI_ESCAPE = new RegExp(`${ESCAPE}\\[[0-9;?]*[A-Za-z]`, 'g');
159
+ const SINGLE_FRAME_BEFORE_ESCAPE = new RegExp(`^[|\\\\/-](?=${ESCAPE})`);
160
+ const LOG_POINTER_SUFFIX =
161
+ /\s*(?:npm error\s+)?(?:A complete log of this run can be found in:|For a full report see:|(?:完整的运行日志|本次运行的完整日志)可在以下位置(?:找到|查看)[::]|Please include the following file with any support request:).*$/;
162
+ const DIAGNOSTIC_HINT =
163
+ /\b[A-Za-z]*Error\b|\b(?:failed|failure|fatal|unknown|unsupported|stopped|cannot|unable)\b|permission denied|错误|失败|不支持|未知/i;
164
+ // Error-name starts: Error, TypeError, RangeError, ReferenceError, SyntaxError,
165
+ // and the bracketed dump header `[TypeError: ...] {`.
166
+ const ERROR_NAME = /^(?:\[?[A-Za-z]*Error\b|fatal\b|FATAL\b)/;
167
+ // Errno names are a closed vocabulary (POSIX plus npm's own codes), so
168
+ // membership is the shape test real errno tokens have. An English progress
169
+ // word cannot masquerade no matter how the vocabulary of prose grows
170
+ // (EVICTED, ENQUEUED, EVALUATING, ERRORS, and every future sibling).
171
+ const ERRNO_SHAPE = /^E[A-Z0-9][A-Z0-9_]+$/;
172
+ const ERRNO_CODES = new Set([
173
+ 'E2BIG',
174
+ 'EACCES',
175
+ 'EADDRINUSE',
176
+ 'EADDRNOTAVAIL',
177
+ 'EAFNOSUPPORT',
178
+ 'EAGAIN',
179
+ 'EALREADY',
180
+ 'EBADF',
181
+ 'EBADMSG',
182
+ 'EBUSY',
183
+ 'ECANCELED',
184
+ 'ECHILD',
185
+ 'ECONNABORTED',
186
+ 'ECONNREFUSED',
187
+ 'ECONNRESET',
188
+ 'EDEADLK',
189
+ 'EDESTADDRREQ',
190
+ 'EDOM',
191
+ 'EDQUOT',
192
+ 'EEXIST',
193
+ 'EFAULT',
194
+ 'EFBIG',
195
+ 'EHOSTDOWN',
196
+ 'EHOSTUNREACH',
197
+ 'EIDRM',
198
+ 'EILSEQ',
199
+ 'EINPROGRESS',
200
+ 'EINTR',
201
+ 'EINVAL',
202
+ 'EIO',
203
+ 'EISCONN',
204
+ 'EISDIR',
205
+ 'ELOOP',
206
+ 'EMFILE',
207
+ 'EMLINK',
208
+ 'EMSGSIZE',
209
+ 'EMULTIHOP',
210
+ 'ENAMETOOLONG',
211
+ 'ENETDOWN',
212
+ 'ENETRESET',
213
+ 'ENETUNREACH',
214
+ 'ENFILE',
215
+ 'ENOBUFS',
216
+ 'ENODATA',
217
+ 'ENODEV',
218
+ 'ENOENT',
219
+ 'ENOEXEC',
220
+ 'ENOLCK',
221
+ 'ENOLINK',
222
+ 'ENOMEM',
223
+ 'ENOMSG',
224
+ 'ENOPROTOOPT',
225
+ 'ENOSPC',
226
+ 'ENOSR',
227
+ 'ENOSTR',
228
+ 'ENOSYS',
229
+ 'ENOTCONN',
230
+ 'ENOTDIR',
231
+ 'ENOTEMPTY',
232
+ 'ENOTRECOVERABLE',
233
+ 'ENOTSOCK',
234
+ 'ENOTSUP',
235
+ 'ENOTTY',
236
+ 'ENXIO',
237
+ 'EOPNOTSUPP',
238
+ 'EOVERFLOW',
239
+ 'EOWNERDEAD',
240
+ 'EPERM',
241
+ 'EPIPE',
242
+ 'EPROTO',
243
+ 'EPROTONOSUPPORT',
244
+ 'EPROTOTYPE',
245
+ 'ERANGE',
246
+ 'EROFS',
247
+ 'ESPIPE',
248
+ 'ESRCH',
249
+ 'ESTALE',
250
+ 'ETIME',
251
+ 'ETIMEDOUT',
252
+ 'ETXTBSY',
253
+ 'EWOULDBLOCK',
254
+ 'EXDEV',
255
+ 'EAI_AGAIN',
256
+ 'EUSAGE',
257
+ 'ENOGIT',
258
+ 'EMISSINGROOT',
259
+ 'ELOCKVERIFY',
260
+ 'EINTEGRITY',
261
+ 'EINVALIDPACKAGENAME',
262
+ 'ECOMPROMISED',
263
+ 'EAI_SYSTEM',
264
+ 'EAI_SOCKTYPE',
265
+ 'EAI_SERVICE',
266
+ 'EAI_OVERFLOW',
267
+ 'EAI_NONAME',
268
+ 'EAI_MEMORY',
269
+ 'EAI_FAIL',
270
+ 'EAI_NODATA',
271
+ 'E404',
272
+ 'E401',
273
+ 'E403',
274
+ 'E426',
275
+ 'E429',
276
+ 'E500',
277
+ 'EBADENGINE',
278
+ 'EBADPLATFORM',
279
+ 'EJSONPARSE',
280
+ 'ELIFECYCLE',
281
+ 'EMAXREDIRECT',
282
+ 'EMAXREDIRECTS',
283
+ 'ENOAUDIT',
284
+ 'ENOLOCAL',
285
+ 'ENOLOCK',
286
+ 'ENOSELF',
287
+ 'ENOVERSIONS',
288
+ 'ENOTCACHED',
289
+ 'ENOTFOUND',
290
+ 'EOTP',
291
+ 'EREGISTRY',
292
+ 'ERESOLVE',
293
+ 'ETARGET',
294
+ 'EUNKNOWNCOMMAND',
295
+ 'EUNSUPPORTEDPROTOCOL',
296
+ ]);
297
+
298
+ function isErrnoToken(token: string | undefined): boolean {
299
+ return Boolean(token && ERRNO_SHAPE.test(token) && ERRNO_CODES.has(token));
300
+ }
301
+
302
+ function stripLogPointerSuffix(line: string): string {
303
+ return line.replace(LOG_POINTER_SUFFIX, '').trim();
304
+ }
305
+
306
+ function shiftNpmErrorToken(line: string): string {
307
+ const errorAt = line.search(/npm error\b/);
308
+ if (errorAt === 0) return line;
309
+ if (errorAt > 0 && /^[^\x21-\x7e]*$/.test(line.slice(0, errorAt))) return line.slice(errorAt);
310
+ // npm 9 under a pty glues progress text before the legacy token; nothing
311
+ // printable there is a diagnostic of its own, so the token still moves.
312
+ const legacyAt = line.search(/npm ERR!/);
313
+ return legacyAt > 0 ? line.slice(legacyAt) : line;
314
+ }
315
+
316
+ function normalizeNpmLine(line: string): string {
317
+ const withoutSpinner = line
318
+ .trim()
319
+ .replace(SINGLE_FRAME_BEFORE_ESCAPE, '')
320
+ .replace(ANSI_ESCAPE, '')
321
+ .replace(/^[\u2800-\u28ff\s]+/, '')
322
+ .replace(/^[|\\/-]{2,}/, '');
323
+ const shifted = shiftNpmErrorToken(withoutSpinner);
324
+ return stripLogPointerSuffix(shifted.replace(/^npm ERR!\s?/, 'npm error '));
325
+ }
326
+
327
+ function npmPayload(line: string): string {
328
+ return line.replace(/^npm error\s*/, '');
329
+ }
330
+
331
+ function isNpmErrorLine(line: string): boolean {
332
+ return /^npm error\b/.test(line);
333
+ }
334
+
335
+ // A pointer line carries nothing but the npm log path (optionally behind a
336
+ // label); a sentence that mentions the path keeps its content.
337
+ function isPointerOnlyLine(line: string): boolean {
338
+ const payload = npmPayload(line)
339
+ .trim()
340
+ .replace(/^(?:[A-Za-z][\w .-]*|[\u4e00-\u9fa5][\u4e00-\u9fa5\w .-]*)\s*[::]\s*/, '');
341
+ if (!/(?:-debug(?:-\d+)?\.log|-eresolve-report\.txt)$/.test(payload)) return false;
342
+ if (/^(?:[A-Za-z]:[\\/]|~[\\/]|\.{0,2}[\\/])/.test(payload)) return true;
343
+ // A bare relative log name ("npm-debug.log", "logs/npm-debug-0.log").
344
+ return !/\s/.test(payload) && !payload.includes(':');
345
+ }
346
+
347
+ // V8 frames: `at`, optional async/new, a token (optionally aliased `[as x]`),
348
+ // then a location in parentheses, a `file:`/`node:`/`<anonymous>` target, a
349
+ // `wasm` frame, or a bare `:<line>:<col>` tail. A sentence that opens with
350
+ // "at least" or "at startup (retry 1)" carries prose, not a location.
351
+ function isStackFrame(payload: string): boolean {
352
+ const match = /^\s*at\s+(?:async\s+|new\s+)?(.+)$/.exec(payload);
353
+ if (!match) return false;
354
+ const rest = match[1]!.trim();
355
+ if (rest === '<anonymous>') return true;
356
+ if (/^wasm[-:]/.test(rest) || /\bwasm-function\b/.test(rest)) return true;
357
+ const call = /^\S+(?:\s+\[as [^\]]+\])?\s*\(([^)]*)\)\s*{?\s*$/.exec(rest);
358
+ if (call) {
359
+ const location = call[1]!.trim();
360
+ return location === '<anonymous>' || /^index \d+$/.test(location) || /^\S+:\d+(?::\d+)?$/.test(location);
361
+ }
362
+ // Nested eval frames close more than one paren (eval at <anonymous> (...)),
363
+ // so the flat paren match above cannot span them; a frame ends with a paren
364
+ // and carries a location token.
365
+ if (/\)\s*$/.test(rest) && /(?:file:|node:|\[eval\]|eval at |<anonymous>|:\d+(?::\d+)?)/.test(rest)) {
366
+ return true;
367
+ }
368
+ return /^(?:file:|node:)\S*:\d+:\d+\b/.test(rest) || /^\S+:\d+:\d+\b/.test(rest);
369
+ }
370
+
371
+ function isNpmNoiseLine(line: string): boolean {
372
+ if (/^Node\.js v\d/.test(line) || /^\s*\^\s*$/.test(line)) return true;
373
+ if (/^Require stack:/.test(line) || /^\s*-\s+[/~]\S*$/.test(line)) return true;
374
+ if (/^\s*throw err;\s*$/.test(line)) return true;
375
+ if (!/[\p{L}\p{N}]/u.test(line)) return true;
376
+ if (/^(?:npm warn\b|npm notice\b|\(node:\d+\))/i.test(line)) return true;
377
+ // Node's non-deprecation warning footer: the `(node:…)` header is dropped
378
+ // above, but its continuation lines are boilerplate too (the
379
+ // MODULE_TYPELESS_PACKAGE_JSON / ExperimentalWarning family). Anchor on the
380
+ // emission shapes, not the word "warning", which can ride a real diagnostic.
381
+ if (/^\(Use `node --trace-warnings\b[^`]*` to show where the warning was created\)$/.test(line)) return true;
382
+ if (/^\(Use `node --trace-uncaught\b[^`]*` to show where the exception was thrown\)$/.test(line)) return true;
383
+ if (/^Reparsing as ES module because module syntax was detected\b/.test(line)) return true;
384
+ if (/^To eliminate this warning, add "type": "module" to\b/.test(line)) return true;
385
+ // npm's log channels are not diagnostics: every `npm <channel>` prefix is
386
+ // noise except the error channel and the `info run` echo of a script.
387
+ if (
388
+ /^npm\s+(?:notice|warn|info|verbose|verb(?:ose)?|http|silly|sill|timing)\b/i.test(line) &&
389
+ !/^npm info run\b/i.test(line)
390
+ ) {
391
+ return true;
392
+ }
393
+ if (/DeprecationWarning|trace-deprecation/i.test(line)) return true;
394
+ if (/^gyp info\b/i.test(line)) return true;
395
+ if (/^added \d+ packages? in\b/i.test(line)) return true;
396
+ const payload = npmPayload(line);
397
+ return (
398
+ /^A complete log of this run can be found in:/.test(payload) ||
399
+ /^For a full report see:/.test(payload) ||
400
+ /^Log files were not written due to an error writing to the directory:/.test(payload) ||
401
+ /^You can rerun the command with `--loglevel=verbose`/.test(payload) ||
402
+ isPointerOnlyLine(line) ||
403
+ isStackFrame(payload)
404
+ );
405
+ }
406
+
407
+ // Tiers: a strong failure marker, then failure words, then the plain position
408
+ // tier, and metadata last. The strongest tier takes its later line (a fatal
409
+ // line lands after a retry marker), the hint tier its earlier one (the real
410
+ // failure precedes cleanup chatter), and the position tier the later line in
411
+ // the codeless branch.
412
+ function isNpmScriptResult(line: string): boolean {
413
+ return /\{\s*code:\s*(?:-?\d+|null)\s*,?\s*signal:/.test(line);
414
+ }
415
+
416
+ function isFailingScriptResult(line: string): boolean {
417
+ const match = /\{\s*code:\s*(-?\d+|null)\s*,?\s*signal:\s*(null|'[^']*'|"[^"]*")/.exec(line);
418
+ if (!match) return false;
419
+ return !(match[1] === '0' && match[2] === 'null');
420
+ }
421
+
422
+ // npm's echo of a failing script: the block's `command <shell> -c <script>`
423
+ // line (sh, bash, or cmd.exe) and the npm-prefixed `info run` echo. A child
424
+ // line that merely starts with "command:" or a shell word is not an echo.
425
+ function isEchoLine(line: string, payload: string): boolean {
426
+ if (isNpmScriptResult(line) || isNpmScriptResult(payload)) return false;
427
+ if (/^npm info run\b/.test(line)) return true;
428
+ // npm's block echo, whichever shell it named; `command failed` is metadata.
429
+ if (/^npm error\s+command\s+/i.test(line) && !/^command failed$/i.test(payload)) return true;
430
+ // A bare shell lead counts only when the -c payload is one command (quoted
431
+ // or a single token), not a child sentence that merely starts with one.
432
+ const commandEnd = /^(?:"[^"]*"|'[^']*'|\S+)\s*$/;
433
+ const shell = /^(?:\S*\/)?(?:ba|z|k|da)?sh\s+-c\s+(.*)$/.exec(payload)?.[1];
434
+ if (shell && commandEnd.test(shell)) return true;
435
+ const cmd = /^cmd(?:\.exe)?\b[^]*?\/c\s+(.*)$/i.exec(payload)?.[1];
436
+ if (cmd && commandEnd.test(cmd)) return true;
437
+ return false;
438
+ }
439
+
440
+ function lineRank(line: string): number {
441
+ const payload = npmPayload(line);
442
+ // Dump punctuation demotes before any token scan: a `[cause]:` line carrying
443
+ // an errno code is still dump metadata, not a diagnosis.
444
+ if (/^\[cause\]:/.test(payload)) return 4;
445
+ // The echo test runs before the strong-marker scans: an echo that quotes the
446
+ // child's own errno token must not tie with the child's line.
447
+ if (isEchoLine(line, payload)) return 3;
448
+ if (ERROR_NAME.test(payload)) return 0;
449
+ const token = /^([A-Z0-9_]+)(?=:|\s|$)/.exec(payload)?.[1];
450
+ if (isErrnoToken(token)) return 0;
451
+ for (const match of payload.matchAll(/(?<=:\s)(E[A-Z0-9][A-Z0-9_]+)\b/g)) {
452
+ if (isErrnoToken(match[1])) return 0;
453
+ }
454
+ if (!payload || /^(?:errno|syscall|path|code|command failed)\b/.test(payload)) return 4;
455
+ if (/^\s*[A-Za-z_]\w*:\s*(?:'[^']*'|"[^"]*"|-?\d+|\[[^\]]*\])\s*,?\s*$/.test(payload)) return 4;
456
+ if (/^\s*[A-Za-z_]\w*:\s*\[[^\]]*\]\s*,?\s*$/.test(payload)) return 4;
457
+ if (/^\s*requireStack:\s*\[.*$/.test(payload) || /^\s*'[^']*',?\s*$/.test(payload)) return 4;
458
+ if (isNpmScriptResult(payload)) return 4;
459
+ // npm's echo of the failing script carries the child's words in quotes, so it
460
+ // must not tie with the child's own line; it is the honest fallback only when
461
+ // the child printed nothing.
462
+ if (DIAGNOSTIC_HINT.test(payload)) return 1;
463
+ return 2;
464
+ }
465
+
466
+ type LineEntry = { line: string; index: number };
467
+
468
+ function lastFailingResult(entries: LineEntry[]): LineEntry | undefined {
469
+ return entries.filter((entry) => isNpmScriptResult(entry.line) && isFailingScriptResult(entry.line)).at(-1);
470
+ }
471
+
472
+ // INVARIANT (gyp preference): the preference is PAIRED, never tier-wide. A gyp
473
+ // banner (`gyp ERR! build/configure error`) is demoted only in favor of a gyp
474
+ // `stack Error:` line in the same rank-1 tier; a non-gyp rank-1 line (a
475
+ // compiler diagnostic, a make line, any child text) is NEVER displaced by a
476
+ // gyp line. The selector's usual earlier-wins order stands everywhere else.
477
+ // Every site that selects from the rank-1 tier routes through this helper.
478
+ const GYP_BANNER = /^gyp ERR! (?:build|configure) error\b/;
479
+ const GYP_STACK_CAUSE = /^gyp ERR! stack Error\b/;
480
+ function pickRankOneLine(hits: LineEntry[]): LineEntry {
481
+ const first = hits[0]!;
482
+ if (!GYP_BANNER.test(npmPayload(first.line))) return first;
483
+ return hits.find((entry) => GYP_STACK_CAUSE.test(npmPayload(entry.line))) ?? first;
484
+ }
485
+
486
+ // The promoted-dying-words sites see a rank-<=2 window, not a single tier;
487
+ // they follow the selector's tier order (rank 0 later, rank 1 through the
488
+ // paired helper, otherwise the last line).
489
+ function pickPromotedLine(entries: LineEntry[]): LineEntry | undefined {
490
+ const rankZero = entries.filter((entry) => lineRank(entry.line) === 0);
491
+ if (rankZero.length) return rankZero.at(-1);
492
+ const rankOne = entries.filter((entry) => lineRank(entry.line) === 1);
493
+ if (rankOne.length) return pickRankOneLine(rankOne);
494
+ return entries.at(-1);
495
+ }
496
+
497
+ function lastEchoBefore(entries: LineEntry[], index: number): LineEntry | undefined {
498
+ return entries.filter((entry) => entry.index < index && lineRank(entry.line) === 3).at(-1);
499
+ }
500
+
501
+ function selectFailureLine(
502
+ rawEntries: LineEntry[],
503
+ { positionLast, echoAllowed = () => true }: { positionLast: boolean; echoAllowed?: (index: number) => boolean },
504
+ ): { line: string; rank: number; index: number } | undefined {
505
+ // A recovery announcement (in a block body or in the plain stderr) is never a
506
+ // candidate; skipping it lets the next truthful tier of the same capture win.
507
+ const entries = rawEntries.filter((entry) => !isRecoveryAnnouncement(entry.line));
508
+ for (const rank of [0, 1, 2, 3, 4]) {
509
+ const hits = entries.filter((entry) => lineRank(entry.line) === rank);
510
+ if (!hits.length) continue;
511
+ if (rank === 3) {
512
+ // The echo tier names the failing script: the last echo that carries the
513
+ // failing result's own package/script identity wins, so a nesting script's
514
+ // nearer echo cannot stand in; an echo that belongs to a recovered window
515
+ // never qualifies; else the last allowed echo.
516
+ const allowed = hits.filter((entry) => echoAllowed(entry.index));
517
+ if (!allowed.length) continue;
518
+ const failing = lastFailingResult(entries);
519
+ const identity = failing ? npmRunIdentity(failing.line) : undefined;
520
+ const identityPaired = identity
521
+ ? allowed
522
+ .filter(
523
+ (entry) =>
524
+ entry.index < failing!.index && lineRank(entry.line) === 3 && npmRunIdentity(entry.line) === identity,
525
+ )
526
+ .at(-1)
527
+ : undefined;
528
+ const paired =
529
+ identityPaired ?? (failing ? allowed.filter((entry) => entry.index < failing.index).at(-1) : undefined);
530
+ const chosen = paired ?? allowed.at(-1)!;
531
+ return { line: chosen.line, rank, index: chosen.index };
532
+ }
533
+ const later = rank === 0 || (rank === 2 && positionLast);
534
+ const chosen = later ? hits.at(-1)! : rank === 1 ? pickRankOneLine(hits) : hits[0]!;
535
+ return { line: chosen.line, rank, index: chosen.index };
536
+ }
537
+ return undefined;
538
+ }
539
+
540
+ // Error blocks are npm's `code` lines plus the metadata and diagnostic lines
541
+ // that follow each one, bounded by the next code line. An `npm error` block and
542
+ // its code line are one unit: an errno-code block that a later block supersedes
543
+ // is a nested or recovered step, not the failure.
544
+ type ErrorBlock = { code: LineEntry; entries: LineEntry[] };
545
+
546
+ function errorBlocks(
547
+ codeEntries: LineEntry[],
548
+ otherEntries: LineEntry[],
549
+ codelessEntries: LineEntry[] = [],
550
+ ): ErrorBlock[] {
551
+ return codeEntries.map((code, position) => {
552
+ const next = codeEntries[position + 1]?.index ?? Number.POSITIVE_INFINITY;
553
+ // A lifecycle line (an info-run echo or a result) starts the next step:
554
+ // the block body (npm's error metadata) cannot own a later step's echo.
555
+ const bare =
556
+ codelessEntries.find(
557
+ (entry) =>
558
+ entry.index > code.index &&
559
+ entry.index < next &&
560
+ (/^npm info run\b/.test(entry.line) || isNpmScriptResult(entry.line)),
561
+ )?.index ?? next;
562
+ const boundary = Math.min(next, bare);
563
+ return {
564
+ code,
565
+ entries: otherEntries.filter((entry) => entry.index > code.index && entry.index < boundary),
566
+ };
567
+ });
568
+ }
569
+
570
+ function pickInBlock(block: ErrorBlock): { line: string; rank: number; index: number } | undefined {
571
+ const entries = block.entries.filter((entry) => !isRecoveryAnnouncement(entry.line));
572
+ for (const rank of [0, 1, 2, 3, 4]) {
573
+ const hits = entries.filter((entry) => lineRank(entry.line) === rank);
574
+ if (!hits.length) continue;
575
+ // The in-block pick mirrors the selector it overrides: the strongest tier
576
+ // takes its later line (a fatal line follows a retry marker).
577
+ const hit = rank === 0 ? hits.at(-1)! : rank === 1 ? pickRankOneLine(hits) : hits[0]!;
578
+ return { line: hit.line, rank, index: hit.index };
579
+ }
580
+ return undefined;
581
+ }
582
+
583
+ function npmRunIdentity(line: string): string | undefined {
584
+ return /^npm info run (\S+ \S+)\b/.exec(npmPayload(line))?.[1];
585
+ }
586
+
587
+ // A line that *announces* a recovery is evidence the step succeeded, not a
588
+ // dying word. A token at the sentence end is the canonical announcement
589
+ // ("... failed once, recovered"); the sentence's final clause wins over an
590
+ // earlier failure mention ("first attempt failed, recovered, fine"), while a
591
+ // governing verb/negation ("failed to recover", "could not yet recover")
592
+ // keeps the line a diagnostic.
593
+ const RECOVER_TOKEN = /\brecover(?:ed|ing|s|y|ies)?\b/i;
594
+ const RECOVER_CONTINUATION =
595
+ /^\s*(?:[.!?]?\s*$|,\s*(?:continuing\b|anyway\b|complete\b|succeeded\b|ok\b|fine\b).*|\s+(?:complete|completely|fully|succeeded|ok|fine)\b.*)$/i;
596
+ // The governing verb/negation before the token turns a sentence into a failure
597
+ // statement ("failed to recover", "not yet recovered", "no recovery"), even
598
+ // when the recover token is the sentence's last word. Adverbs may sit before or
599
+ // after `to` ("failed to fully recover", "unable to completely recover").
600
+ const RECOVER_GOVERNING =
601
+ /(?:failed|failure|refused|rejected|unable|could not|cannot|can't|not|never|no)\s+(?:(?:yet|still|even|ever|really|quite|fully|actually|entirely|completely|eventually)\s+)*(?:to\s+(?:(?:yet|still|even|ever|really|quite|fully|actually|entirely|completely|eventually)\s+)*)?$/i;
602
+ // A recovered step's continuation notices ("falling back to the bundled
603
+ // toolchain", "retrying from snapshot", "using cached copy of previous build",
604
+ // "best-effort rebuild only", "degraded mode active"): "falling back" and
605
+ // "retrying" are announcements only in their full forms, so a failing step's
606
+ // bare dying words surface, while the cached/best-effort/degraded idiom tokens
607
+ // mark an announcement wherever they appear. A dying line that merely contains
608
+ // one of those fallback tokens is therefore treated as a recovered-step notice
609
+ // (a ledgered trade).
610
+ const CONTINUATION_ANNOUNCEMENT = /\b(?:falling back to|retrying from|using cached|best-effort|degraded)\b/i;
611
+ function isRecoveryAnnouncement(line: string): boolean {
612
+ const payload = npmPayload(line);
613
+ // A command/echo line names a script, not prose: "sh -c node recover" is not
614
+ // a recovery announcement.
615
+ if (
616
+ /^command\b/i.test(payload) ||
617
+ /^(?:\S*\/)?(?:ba|z|k|da)?sh\s+-c\b/i.test(payload) ||
618
+ /^cmd(?:\.exe)?\s/i.test(payload)
619
+ ) {
620
+ return false;
621
+ }
622
+ const match = RECOVER_TOKEN.exec(payload);
623
+ if (match) {
624
+ const prefix = payload.slice(0, match.index);
625
+ const suffix = payload.slice(match.index + match[0].length);
626
+ // Governing negation/verb first: the sentence-final shortcut must not eat it.
627
+ if (RECOVER_GOVERNING.test(prefix)) return false;
628
+ // The recovery is the sentence's final clause: a failure mention earlier in
629
+ // the sentence ("first attempt failed, recovered, fine") does not veto it.
630
+ return RECOVER_CONTINUATION.test(suffix);
631
+ }
632
+ const continuation = CONTINUATION_ANNOUNCEMENT.exec(payload);
633
+ if (!continuation) return false;
634
+ return !RECOVER_GOVERNING.test(payload.slice(0, continuation.index));
635
+ }
636
+
637
+ function isCauseLine(line: string): boolean {
638
+ const payload = npmPayload(line);
639
+ if (!/^\[cause\]:/.test(payload)) return false;
640
+ const rest = payload.replace(/^\[cause\]:\s*/, '');
641
+ if (ERROR_NAME.test(rest)) return true;
642
+ const token = /^([A-Z0-9_]+)(?=:|\s|$)/.exec(rest)?.[1];
643
+ return isErrnoToken(token);
644
+ }
645
+
646
+ function extractNpmFailureReason(execResult: SpawnResultLike): string {
647
+ // Keep the untrimmed source beside the normalized lines: the blank-line and
648
+ // stack-frame shapes the warning scan needs survive only in the raw text.
649
+ const sourceLines = String(execResult.stderr || '').split(/\r?\n/);
650
+ const rawLines = sourceLines.map((line) => normalizeNpmLine(line));
651
+ // A Node crash preamble carries three lines the per-line rules cannot judge:
652
+ // the `file:line` header, the source snippet, and the caret under it.
653
+ const crashPreamble = new Set<number>();
654
+ rawLines.forEach((line, index) => {
655
+ const header = /^\S+:\d+$/.test(line);
656
+ const snippet = Boolean(rawLines[index + 1] && /[;=()]/.test(rawLines[index + 1]!));
657
+ const caret = /^\s*\^+\s*$/.test(rawLines[index + 2] ?? '');
658
+ if (header && snippet && caret) {
659
+ crashPreamble
660
+ .add(index)
661
+ .add(index + 1)
662
+ .add(index + 2);
663
+ }
664
+ });
665
+ // Node's warning continuation lines are boilerplate whatever their wording.
666
+ // The region ends at the FIRST structural closer met scanning forward from
667
+ // the header — a traced stack-frame run (its last frame), an `npm error`
668
+ // block start (the last line before it is kept as the child's possible
669
+ // diagnostic), a blank line, the `(Use …)` footer, or a crash/diagnostic
670
+ // header (the lines before it are excluded, the header itself is kept). A
671
+ // later closer never re-extends a region an earlier one already closed: the
672
+ // outer loop re-scans from every warning header, which covers adjacent
673
+ // warnings without a separate header clause.
674
+ const WARNING_FOOTER =
675
+ /^\(Use `node --trace-(?:warnings|deprecation)\b[^`]*` to show where the warning was created\)$/;
676
+ const WARNING_HEADER = /^\(node:\d+\)/;
677
+ const frameLine = (raw: string) => /^\s+at\s/.test(raw);
678
+ const crashHeader = (line: string) => /^\S+:\d+$/.test(line);
679
+ const diagnosticHeader = (line: string) => /^(?:\[?[A-Za-z]*Error\b|[Ff][Aa][Tt][Aa][Ll]\b|Uncaught\b)/.test(line);
680
+ const warningContinuation = new Set<number>();
681
+ for (let index = 0; index < rawLines.length; index += 1) {
682
+ if (!WARNING_HEADER.test(rawLines[index]!)) continue;
683
+ let end = -1;
684
+ let frameSeen = false;
685
+ for (let cursor = index + 1; cursor < rawLines.length; cursor += 1) {
686
+ const raw = sourceLines[cursor] ?? '';
687
+ const line = rawLines[cursor]!;
688
+ if (frameLine(raw)) {
689
+ frameSeen = true;
690
+ end = cursor;
691
+ continue;
692
+ }
693
+ if (frameSeen) break;
694
+ if (!raw.trim()) {
695
+ end = cursor - 1;
696
+ break;
697
+ }
698
+ if (isNpmErrorLine(line)) {
699
+ end = cursor - 2;
700
+ break;
701
+ }
702
+ if (WARNING_FOOTER.test(line)) {
703
+ end = cursor;
704
+ break;
705
+ }
706
+ if (crashHeader(line) || diagnosticHeader(line)) {
707
+ end = cursor - 1;
708
+ break;
709
+ }
710
+ }
711
+ for (let cursor = index + 1; cursor <= end; cursor += 1) warningContinuation.add(cursor);
712
+ }
713
+ // Every entry keeps its raw position: the code candidate, the block and the
714
+ // echo are compared against the success window in one index space, so a
715
+ // duplicate text line can never be re-resolved to its first occurrence.
716
+ const entries: LineEntry[] = rawLines
717
+ .map((line, index) => ({ line, index }))
718
+ .filter(
719
+ (entry) =>
720
+ Boolean(entry.line) &&
721
+ !crashPreamble.has(entry.index) &&
722
+ !warningContinuation.has(entry.index) &&
723
+ !isNpmNoiseLine(entry.line),
724
+ );
725
+ const codeEntries = entries.filter((entry) => isNpmErrorLine(entry.line) && /^code \S+/.test(npmPayload(entry.line)));
726
+ const otherEntries = entries.filter(
727
+ (entry) => isNpmErrorLine(entry.line) && !codeEntries.some((code) => code.index === entry.index),
728
+ );
729
+ const codelessEntries = entries.filter((entry) => !isNpmErrorLine(entry.line));
730
+ const codeFor = (target: { index: number } | undefined) =>
731
+ (target ? codeEntries.filter((entry) => entry.index <= target.index).at(-1) : undefined)?.line ??
732
+ codeEntries.at(-1)?.line;
733
+
734
+ const isSuccessAssertion = (line: string) =>
735
+ /^gyp info ok\b/i.test(line) ||
736
+ /^prebuilt binary installed\b/i.test(line) ||
737
+ (isNpmScriptResult(line) && !isFailingScriptResult(line));
738
+ const lastSuccessIndex = (before: number): number => {
739
+ let found = -1;
740
+ rawLines.forEach((line, index) => {
741
+ if (index < before && isSuccessAssertion(line)) found = index;
742
+ });
743
+ return found;
744
+ };
745
+
746
+ // The gate is a failing pair: a failure result line with its own echo. A
747
+ // successful script's echo pair, or a lone echo, proves nothing about the
748
+ // failing step.
749
+ const failing = lastFailingResult(codelessEntries);
750
+ // npm's echo of the failing script may be a bare shell line or the block's own
751
+ // `npm error command` line; the pair is the result line plus the echo that
752
+ // names the same package and lifecycle script. A nesting script's nearer echo
753
+ // must not stand in for the failing step, and a result line whose echo landed
754
+ // after it (a dying step that printed `gyp info ok` then its result) is not a
755
+ // pair.
756
+ const failingIdentity = failing ? npmRunIdentity(failing.line) : undefined;
757
+ // A code-0 result owns the lines between its echo and its result, whether or
758
+ // not it shares the failing step's identity: a recovered run of the same
759
+ // package is a different step. Each result claims its nearest preceding echo
760
+ // of the same identity that no earlier result claimed, so interleaved
761
+ // same-identity siblings get one window each instead of both anchoring at the
762
+ // later echo.
763
+ // Under concurrency a later successful run of the same package must not claim
764
+ // the echo the failing pair needs: the pair's anchoring wins.
765
+ const reservedPairEchoes = new Set<number>();
766
+ if (failing && failingIdentity) {
767
+ const identityEchoes = entries.filter(
768
+ (entry) =>
769
+ entry.index < failing.index && lineRank(entry.line) === 3 && npmRunIdentity(entry.line) === failingIdentity,
770
+ );
771
+ // The pair's own echo is the one followed by its failure-shaped rank-0
772
+ // dying words (a FATAL/Error header). An errno diagnostic follower (for
773
+ // example "EACCES: permission denied, using user cache instead") can be a
774
+ // successful sibling's recovered evidence, so it never reserves an echo;
775
+ // under concurrency the other same-identity echo belongs to the sibling's
776
+ // run.
777
+ const strongWordEcho = identityEchoes
778
+ .filter((echo) => {
779
+ const next = codelessEntries.find((entry) => entry.index > echo.index && entry.index < failing.index);
780
+ return Boolean(
781
+ next &&
782
+ lineRank(next.line) === 0 &&
783
+ ERROR_NAME.test(npmPayload(next.line)) &&
784
+ !isNpmScriptResult(next.line) &&
785
+ !isRecoveryAnnouncement(next.line),
786
+ );
787
+ })
788
+ .at(-1);
789
+ // A lone echo cannot be split between two runs; reserving it would leave
790
+ // the pair with nothing, so the sequential claim handles that shape.
791
+ if (strongWordEcho && identityEchoes.length >= 2) reservedPairEchoes.add(strongWordEcho.index);
792
+ }
793
+ const recoveredWindows: Array<{ start: number; end: number }> = [];
794
+ const claimedEchoes = new Set<number>();
795
+ for (const result of codelessEntries) {
796
+ if (!isNpmScriptResult(result.line) || isFailingScriptResult(result.line)) continue;
797
+ const identity = npmRunIdentity(result.line);
798
+ if (!identity) continue;
799
+ const echo = entries
800
+ .filter(
801
+ (entry) =>
802
+ entry.index < result.index &&
803
+ lineRank(entry.line) === 3 &&
804
+ npmRunIdentity(entry.line) === identity &&
805
+ !claimedEchoes.has(entry.index) &&
806
+ !reservedPairEchoes.has(entry.index),
807
+ )
808
+ .at(-1);
809
+ if (echo) {
810
+ claimedEchoes.add(echo.index);
811
+ recoveredWindows.push({ start: echo.index, end: result.index });
812
+ }
813
+ // A result with no claimable echo is unattributable: it registers no window.
814
+ }
815
+ const startsRecoveredWindow = (index: number) => recoveredWindows.some((window) => window.start === index);
816
+ // The failing pair's echo is the step's own: the nearest identity echo that
817
+ // does not belong to a recovered window; a fallback echo that does belong to
818
+ // one leaves the pair unattributable.
819
+ const ownEcho = failing
820
+ ? entries
821
+ .filter(
822
+ (entry) =>
823
+ entry.index < failing.index &&
824
+ lineRank(entry.line) === 3 &&
825
+ npmRunIdentity(entry.line) === failingIdentity &&
826
+ !startsRecoveredWindow(entry.index),
827
+ )
828
+ .at(-1)
829
+ : undefined;
830
+ const fallbackEcho = failing ? lastEchoBefore(entries, failing.index) : undefined;
831
+ const failingPairEcho =
832
+ ownEcho ?? (fallbackEcho && !startsRecoveredWindow(fallbackEcho.index) ? fallbackEcho : undefined);
833
+ const hasFailingPair = Boolean(failing && failingPairEcho);
834
+ // A nested window whose own echo starts after the failing pair's echo belongs
835
+ // to a nested step and is excluded even when it sits inside the pair's span;
836
+ // only the failing step's own words between its echo and result are in-pair
837
+ // survivors. Boundaries are inclusive: a window's own echo is not a reason.
838
+ const insideFailingPair = (index: number) =>
839
+ Boolean(failing && failingPairEcho && index > failingPairEcho.index && index < failing.index);
840
+ // A candidate line is excluded when it is a recovery notice or sits in a
841
+ // nested window (one opening after the failing echo). A window opening before
842
+ // the failing echo can interleave with the failing step, so it blocks only its
843
+ // recovery notices; with no failing pair every window blocks its whole span.
844
+ const inNestedWindow = (index: number) =>
845
+ recoveredWindows.some(
846
+ (window) => index >= window.start && index <= window.end && window.start > (failingPairEcho?.index ?? -1),
847
+ );
848
+ const lineExcluded = (index: number) => {
849
+ const line = entries.find((entry) => entry.index === index)?.line ?? '';
850
+ // With no failing pair every window start is past the sentinel, so
851
+ // inNestedWindow already covers the whole span.
852
+ return isRecoveryAnnouncement(line) || inNestedWindow(index);
853
+ };
854
+ // A success assertion is recovery evidence only when it precedes the last
855
+ // failing pair: the failing step's own `gyp info ok`, printed after its dying
856
+ // words and before its own result line, is not a recovery.
857
+ const recoverySuccess = failingPairEcho ? lastSuccessIndex(failingPairEcho.index) : -1;
858
+
859
+ const echoAllowed = (index: number) => !startsRecoveredWindow(index);
860
+ let block = selectFailureLine(otherEntries, { positionLast: false, echoAllowed });
861
+ let bare = selectFailureLine(codelessEntries, { positionLast: true, echoAllowed });
862
+ let codeLine = codeFor(block);
863
+ let recoveredSwap = false;
864
+ let bodylessTwin = false;
865
+ const blocks = codeEntries.length ? errorBlocks(codeEntries, otherEntries, codelessEntries) : [];
866
+ const blockBodyEnd = (target: ErrorBlock) =>
867
+ target.entries.reduce((max, entry) => Math.max(max, entry.index), target.code.index);
868
+ const firstBlockCode = blocks[0]?.code.index ?? -1;
869
+ const lastBlockBodyEnd = blocks.length ? blockBodyEnd(blocks.at(-1)!) : -1;
870
+ const inBlockRange = (index: number) =>
871
+ blocks.some((target) => index >= target.code.index && index <= blockBodyEnd(target));
872
+
873
+ // At npm's default loglevel lifecycle result lines do not exist, so a nested
874
+ // step's recovered block is the only visible error text while the failing
875
+ // step said nothing. With no failing pair, the last error block is the only
876
+ // attributable one; a sole nested block whose errno code cannot be tied to
877
+ // the exit falls to the honest exit status, and a child line outside it is
878
+ // the child's dying words.
879
+ if (!hasFailingPair && codeEntries.length) {
880
+ const lastBlock = blocks.at(-1)!;
881
+ // A duplicate `code N` line with no body of its own (a harness prepend) is
882
+ // one logical block; two populated blocks are distinct steps even when
883
+ // their code text matches, so both shapes keep the last-block rule.
884
+ const previous = blocks.at(-2);
885
+ const distinctLastCode =
886
+ Boolean(previous) &&
887
+ npmPayload(previous!.code.line).replace(/^code\s+/, '') !==
888
+ npmPayload(lastBlock.code.line).replace(/^code\s+/, '');
889
+ // A harness-prepended `code N` line has no block body of its own: it is the
890
+ // same logical block as the one that follows the child diagnostic. A real
891
+ // nested block always carries its own path/echo lines, so shared code text
892
+ // between two populated blocks must not disable the last-block rule.
893
+ const previousHasBody = Boolean(previous && previous.entries.length);
894
+ const overrides = blocks.length > 1 && (distinctLastCode || previousHasBody);
895
+ const picked = pickInBlock(lastBlock);
896
+ const lastHasEcho = lastBlock.entries.some((entry) => lineRank(entry.line) === 3);
897
+ const codeToken = npmPayload(lastBlock.code.line).replace(/^code\s+/, '');
898
+ const numericLast = /^-?\d+$/.test(codeToken);
899
+ const codeTiesExit =
900
+ numericLast && typeof execResult.status === 'number' && Number(codeToken) === execResult.status;
901
+ // Two populated blocks are a recovered step plus npm's summary of the
902
+ // failing one; a shared code text is the round-25 shape. From three blocks
903
+ // on, a numeric block whose code does not tie to the exit is another nested
904
+ // step even when it carries npm's inner script echo.
905
+ const attributableNumeric =
906
+ numericLast && (codeTiesExit || blocks.length <= 2 || typeof execResult.status !== 'number');
907
+ const unattributableNested = numericLast
908
+ ? typeof execResult.status === 'number' && execResult.status > 1 && !attributableNumeric
909
+ : !lastHasEcho && typeof execResult.status === 'number' && execResult.status > 1;
910
+ const blockEnd = blockBodyEnd(lastBlock);
911
+ if (overrides) {
912
+ // A body-less trailing duplicate of a tying populated block is npm's
913
+ // summary of the same step: the populated twin's line and echo ride.
914
+ const tiedBodyless = !picked && Boolean(previous?.entries.length) && !distinctLastCode;
915
+ bodylessTwin = tiedBodyless;
916
+ const owner = tiedBodyless ? previous! : lastBlock;
917
+ block = (tiedBodyless ? pickInBlock(previous!) : picked) ?? {
918
+ line: lastBlock.code.line,
919
+ rank: 4,
920
+ index: lastBlock.code.index,
921
+ };
922
+ codeLine = owner.code.line;
923
+ // The child's earlier chatter belongs to a recovered step; the last
924
+ // block's own echo names the failing script.
925
+ if (bare && bare.index < lastBlock.code.index) bare = undefined;
926
+ }
927
+ // An errno-coded block with no echo is a nested/recovered block, not this
928
+ // exit's failure at an exit above 1: plural nested blocks and the
929
+ // metadata-only lone block are the same shape. A child line after the block
930
+ // is the dying words; otherwise the exit status is honest. A top-level errno
931
+ // failure exits 1 and keeps its code line, as do the numeric blocks above.
932
+ if (unattributableNested) {
933
+ const dying = pickPromotedLine(
934
+ codelessEntries
935
+ .filter((entry) => entry.index > blockEnd && lineRank(entry.line) <= 2)
936
+ .filter(
937
+ (entry) =>
938
+ !isRecoveryAnnouncement(entry.line) &&
939
+ !rawLines.some((line, index) => index > entry.index && isSuccessAssertion(line)),
940
+ ),
941
+ );
942
+ if (dying) return dying.line;
943
+ block = undefined;
944
+ codeLine = undefined;
945
+ }
946
+ }
947
+
948
+ // A block that trails the last failing result is npm's own summary of that
949
+ // step, and it owns the failure even when an earlier, recovered block carries
950
+ // a higher-ranked diagnostic (the verbose/default asymmetry). Its code line
951
+ // is the failing step's, so no recovered block's code can be the reason.
952
+ let trailingSwap = false;
953
+ if (hasFailingPair) {
954
+ const tiesExit = (candidate: ErrorBlock) => {
955
+ const token = npmPayload(candidate.code.line).replace(/^code\s+/, '');
956
+ return /^-?\d+$/.test(token) && typeof execResult.status === 'number' && Number(token) === execResult.status;
957
+ };
958
+ const trailing = blocks.filter((candidate) => candidate.code.index > failing!.index).at(-1);
959
+ const firstFailing = codelessEntries.find(
960
+ (entry) => isNpmScriptResult(entry.line) && isFailingScriptResult(entry.line),
961
+ );
962
+ const tyingTrailing =
963
+ firstFailing && !(trailing && tiesExit(trailing))
964
+ ? blocks.filter((candidate) => candidate.code.index > firstFailing.index && tiesExit(candidate)).at(-1)
965
+ : undefined;
966
+ const chosen = trailing && tiesExit(trailing) ? trailing : (tyingTrailing ?? trailing);
967
+ const chosenIndex = chosen ? blocks.indexOf(chosen) : -1;
968
+ const previousBlock = chosenIndex > 0 ? blocks[chosenIndex - 1] : undefined;
969
+ const tiedBodyless =
970
+ chosen &&
971
+ !chosen.entries.length &&
972
+ Boolean(previousBlock?.entries.length) &&
973
+ npmPayload(previousBlock!.code.line).replace(/^code\s+/, '') ===
974
+ npmPayload(chosen.code.line).replace(/^code\s+/, '');
975
+ const owner = tiedBodyless ? previousBlock! : chosen;
976
+ if (owner) {
977
+ block = pickInBlock(owner) ?? { line: owner.code.line, rank: 4, index: owner.code.index };
978
+ codeLine = owner.code.line;
979
+ // The child's earlier chatter belongs to the step that recovered.
980
+ if (bare && bare.index < owner.code.index) bare = undefined;
981
+ trailingSwap = true;
982
+ recoveredSwap = true;
983
+ }
984
+ }
985
+ // A loud successful script (or a gyp error it survived) is not the cause when
986
+ // npm emitted a failing echo pair later: the echo names the failing script.
987
+ if (bare && failing && failingPairEcho && recoverySuccess > -1 && bare.index < recoverySuccess) {
988
+ bare = { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index };
989
+ }
990
+ // The failing step's own dying words sit between its echo and its result;
991
+ // earlier chatter belongs to a step that recovered (or another step). This is
992
+ // the in-pair window: a code-0 success between the echo and the result does
993
+ // not restore the earlier line.
994
+ let promotedInPair = false;
995
+ if (failing && failingPairEcho) {
996
+ const inside = pickPromotedLine(
997
+ codelessEntries
998
+ .filter((entry) => entry.index > failingPairEcho.index && entry.index < failing.index)
999
+ .filter((entry) => lineRank(entry.line) <= 2)
1000
+ .filter((entry) => !lineExcluded(entry.index)),
1001
+ );
1002
+ if (inside) {
1003
+ bare = { line: inside.line, rank: lineRank(inside.line), index: inside.index };
1004
+ promotedInPair = true;
1005
+ } else if (!bare || !insideFailingPair(bare.index)) {
1006
+ bare = { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index };
1007
+ }
1008
+ }
1009
+ // Lines belonging to a step whose own result says it recovered are not this
1010
+ // failure's words: the failing pair's echo is the honest fallback, and with no
1011
+ // attributable pair echo the floor is the exit status. The in-pair promotion
1012
+ // already filtered its own candidates.
1013
+ if (bare && lineExcluded(bare.index)) {
1014
+ bare = failingPairEcho ? { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index } : undefined;
1015
+ }
1016
+ // The outer shell names a signal death "Terminated" or "Killed"; when npm
1017
+ // emitted the failing echo pair, the named script is the better reason.
1018
+ if (bare?.rank === 2 && /^(?:Terminated|Killed)\b/i.test(bare.line) && hasFailingPair) {
1019
+ bare = { line: failingPairEcho!.line, rank: 3, index: failingPairEcho!.index };
1020
+ }
1021
+ // A spawn kill (timeout, buffer ceiling) or a plain nonzero status with no
1022
+ // failing pair and no error block leaves no line attributable to the failing
1023
+ // script: the spawn artifact or the exit status is the honest reason.
1024
+ const unattributableStatus =
1025
+ (typeof execResult.status === 'number' && execResult.status !== 0) ||
1026
+ (execResult.status === null && Boolean(execResult.signal || execResult.error));
1027
+ if (
1028
+ !block &&
1029
+ !codeLine &&
1030
+ !hasFailingPair &&
1031
+ bare &&
1032
+ !/^(?:Terminated|Killed)\b/i.test(bare.line) &&
1033
+ unattributableStatus
1034
+ ) {
1035
+ bare = undefined;
1036
+ }
1037
+ // A sole surviving diagnostic line is the child's dying words and is kept
1038
+ // after the floor, even when noise filtering discarded its companions (a
1039
+ // pointer, a stack frame, spinner residue). Only a failure-marked line
1040
+ // qualifies: plain progress chatter does not distinguish itself, and a
1041
+ // filtered success assertion (a code-0 result, gyp's info channel) means the
1042
+ // survivor belongs to a script that did not fail.
1043
+ const survivorEligible = (entry: LineEntry) =>
1044
+ !inBlockRange(entry.index) &&
1045
+ !lineExcluded(entry.index) &&
1046
+ !(
1047
+ hasFailingPair &&
1048
+ failing &&
1049
+ failingPairEcho &&
1050
+ entry.index < failingPairEcho.index &&
1051
+ rawLines.some((line, index) => index > entry.index && index < failing.index && isSuccessAssertion(line))
1052
+ ) &&
1053
+ (entry.index > lastBlockBodyEnd || (blocks.length <= 1 && entry.index < firstBlockCode));
1054
+ const strongSurvivors = codelessEntries.filter((entry) => lineRank(entry.line) <= 1 && survivorEligible(entry));
1055
+ // A demoted `[cause]:` line still rides when it is the only substantive text:
1056
+ // the rank-4 demotion exists to keep it from outranking a header, not to
1057
+ // silence a dump that has nothing else.
1058
+ const attributableSurvivors = strongSurvivors.length
1059
+ ? strongSurvivors
1060
+ : codelessEntries.filter((entry) => isCauseLine(entry.line) && survivorEligible(entry));
1061
+ if (
1062
+ !block &&
1063
+ !codeLine &&
1064
+ typeof execResult.status === 'number' &&
1065
+ execResult.status !== 0 &&
1066
+ attributableSurvivors.length === 1
1067
+ ) {
1068
+ const survivor = attributableSurvivors[0]!;
1069
+ // The entry's own raw position: a crash snippet that repeats the text must
1070
+ // not move the survivor past the success assertion that vetoes it.
1071
+ const survivorIndex = survivor.index;
1072
+ const echoIndex = failingPairEcho ? failingPairEcho.index : -1;
1073
+ const successAfter = rawLines.some((line, index) => index >= survivorIndex && isSuccessAssertion(line));
1074
+ const laterFailingPair =
1075
+ hasFailingPair &&
1076
+ echoIndex > survivorIndex &&
1077
+ rawLines.some((line, index) => index > survivorIndex && index < echoIndex && isSuccessAssertion(line));
1078
+ if (!laterFailingPair && (!successAfter || hasFailingPair)) return survivor.line;
1079
+ }
1080
+ // A recovered block's echo must name the failing step: the block line moved
1081
+ // to a later echo only when the success that recovered it precedes the last
1082
+ // failing pair, and the code line is re-derived from the failing step's own
1083
+ // block (never re-resolved by duplicate text).
1084
+ if (block && block.rank <= 2 && recoverySuccess > block.index) {
1085
+ const echo = entries
1086
+ .filter((entry) => lineRank(entry.line) === 3 && entry.index > block!.index && entry.index > recoverySuccess)
1087
+ .at(-1);
1088
+ if (echo) {
1089
+ block = { line: echo.line, rank: 3, index: echo.index };
1090
+ codeLine = codeEntries.filter((entry) => entry.index > recoverySuccess).at(-1)?.line;
1091
+ recoveredSwap = true;
1092
+ }
1093
+ }
1094
+ // A success assertion after a rank-0/1 code-less line means that line came
1095
+ // from a step that recovered and a later block names a different step; the
1096
+ // block's code line and echo are the honest reason instead.
1097
+ if (!hasFailingPair && bare && block && bare.rank <= 1) {
1098
+ const laterCode = codeEntries.find((entry) => entry.index > bare!.index);
1099
+ const boundary = laterCode?.index ?? block.index;
1100
+ const recovered = rawLines.some(
1101
+ (line, index) => index > bare!.index && index < boundary && isSuccessAssertion(line),
1102
+ );
1103
+ if (recovered) return [codeLine, block.line].filter((line): line is string => Boolean(line)).join(' ');
1104
+ }
1105
+ // A failing pair after an earlier dying-words line, with a success assertion
1106
+ // between them, names a later failing step; prefer it. Without that gap the
1107
+ // pair belongs to the same script as the cause, and the cause stays.
1108
+ const bareRawIndex = bare ? bare.index : -1;
1109
+ if (
1110
+ hasFailingPair &&
1111
+ failingPairEcho &&
1112
+ bare &&
1113
+ bareRawIndex >= 0 &&
1114
+ bareRawIndex < failingPairEcho.index &&
1115
+ bare.rank <= 1 &&
1116
+ rawLines.some((line, index) => index > bareRawIndex && index < failingPairEcho.index && isSuccessAssertion(line))
1117
+ ) {
1118
+ bare = { line: failingPairEcho.line, rank: 3, index: failingPairEcho.index };
1119
+ }
1120
+ // An echo that precedes the chosen block belongs to an earlier step; a
1121
+ // metadata-only block must not inherit it.
1122
+ if (bare && lineRank(bare.line) === 3 && block && bare.index < block.index) bare = undefined;
1123
+ // A success assertion is never the reason: it names a step that recovered.
1124
+ if (bare && isSuccessAssertion(bare.line)) bare = undefined;
1125
+ // The same holds when the echo itself won the tier: npm's block echo follows
1126
+ // its code line, so an echo above the last code line is an earlier step's.
1127
+ if (
1128
+ !bodylessTwin &&
1129
+ !trailingSwap &&
1130
+ block &&
1131
+ lineRank(block.line) === 3 &&
1132
+ codeEntries.length &&
1133
+ block.index < codeEntries.at(-1)!.index
1134
+ ) {
1135
+ block = undefined;
1136
+ }
1137
+ // Both branches compete: an unprefixed crash line outranks a block echo, and
1138
+ // the block keeps its code prefix when the block wins or when only a weak
1139
+ // code-less line survives, because the code still identifies the failure.
1140
+ if (bare && (!block || bare.rank < block.rank)) {
1141
+ if (trailingSwap && promotedInPair) return bare.line;
1142
+ if (recoveredSwap && block && bare.rank >= 2) {
1143
+ return [codeLine, block.line].filter((line): line is string => Boolean(line)).join(' ');
1144
+ }
1145
+ return codeLine && bare.rank >= 2 ? `${codeLine} ${bare.line}` : bare.line;
1146
+ }
1147
+ if (block && block.rank < 4) return [codeLine, block.line].filter((line): line is string => Boolean(line)).join(' ');
1148
+ if (codeLine) return codeLine;
1149
+ if (bare) return bare.line;
1150
+ // A spawn artifact (timeout, ENOBUFS) names the kill for unattributable
1151
+ // stderr; a block or a failing pair has already won above.
1152
+ if (execResult.error?.message) return execResult.error.message;
1153
+ if (execResult.signal) return `signal ${execResult.signal}`;
1154
+ if (typeof execResult.status === 'number') return `exit ${execResult.status}`;
1155
+ return 'unknown failure';
1156
+ }
1157
+
43
1158
  function restartMessage(target: string): string {
44
1159
  if (target === 'officeace') {
45
1160
  return '升级完成,请打开连接器 → 我的连接器 → huaweicloud-devkit → 重新连接后使用新版本。';
@@ -78,7 +1193,7 @@ export async function upgradePackage(
78
1193
  return {
79
1194
  success: false,
80
1195
  error: errorMessage(error) || '无法确认最新版本(registry 查询失败)。',
81
- manual: `npx --yes huaweicloud-devkit@latest update --target ${target}`,
1196
+ manual: `npx --yes --foreground-scripts huaweicloud-devkit@latest update --target ${target}`,
82
1197
  };
83
1198
  }
84
1199
  const targetVersion = determineTarget(previousVersion, distTags ?? {});
@@ -86,7 +1201,7 @@ export async function upgradePackage(
86
1201
  return {
87
1202
  success: false,
88
1203
  error: '无法确认最新版本(registry 查询失败)。',
89
- manual: `npx --yes huaweicloud-devkit@latest update --target ${target}`,
1204
+ manual: `npx --yes --foreground-scripts huaweicloud-devkit@latest update --target ${target}`,
90
1205
  };
91
1206
  }
92
1207
  if (!targetVersion) {
@@ -94,15 +1209,22 @@ export async function upgradePackage(
94
1209
  }
95
1210
  const isNextTarget = Boolean(distTags.next && semverCompare(targetVersion, distTags.next) === 0);
96
1211
  const tag = isNextTarget ? 'next' : 'latest';
97
- const command = ['--yes', `huaweicloud-devkit@${tag}`, 'update', '--target', String(target)];
1212
+ const command = ['--yes', '--foreground-scripts', `huaweicloud-devkit@${tag}`, 'update', '--target', String(target)];
98
1213
  let execResult: SpawnResultLike;
99
1214
  try {
100
- execResult = spawnFn(NPX_BIN, command, { encoding: 'utf8', timeout: 300000, windowsHide: true, shell: true });
1215
+ execResult = spawnFn(NPX_BIN, command, {
1216
+ encoding: 'utf8',
1217
+ timeout: 300000,
1218
+ windowsHide: true,
1219
+ shell: true,
1220
+ env: upgradeEnv(),
1221
+ maxBuffer: 16 * 1024 * 1024,
1222
+ });
101
1223
  } catch (error) {
102
1224
  return {
103
1225
  success: false,
104
1226
  error: errorMessage(error) || '升级命令执行失败。',
105
- manual: `npx --yes huaweicloud-devkit@${tag} update --target ${target}`,
1227
+ manual: `npx --yes --foreground-scripts huaweicloud-devkit@${tag} update --target ${target}`,
106
1228
  };
107
1229
  }
108
1230
  if (execResult.status === 0) {
@@ -115,16 +1237,10 @@ export async function upgradePackage(
115
1237
  message: restartMessage(target),
116
1238
  };
117
1239
  }
118
- const errObj = execResult.error;
119
- const stderr = String(execResult.stderr || '').trim();
120
- const reason = errObj?.message
121
- ? errObj.message
122
- : stderr
123
- ? stderr.split(/\r?\n/).filter(Boolean).slice(-2).join(' ')
124
- : `exit ${execResult.status}`;
1240
+ const reason = extractNpmFailureReason(execResult);
125
1241
  return {
126
1242
  success: false,
127
1243
  error: reason,
128
- manual: `npx --yes huaweicloud-devkit@${tag} update --target ${target}`,
1244
+ manual: `npx --yes --foreground-scripts huaweicloud-devkit@${tag} update --target ${target}`,
129
1245
  };
130
1246
  }