@xiashe/sdk 0.1.41 → 0.1.42

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.
package/alipayWallet.mjs CHANGED
@@ -1,6 +1,8 @@
1
+ import { paymentCustomerError, formatPaymentCustomerError } from './paymentErrors.mjs';
2
+ import { privateDirectory, checkPrivateFile, withPrivateLock, atomicPrivateJson } from './privateState.mjs';
1
3
  import { createHash } from 'node:crypto';
2
4
  import { execFile } from 'node:child_process';
3
- import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { chmod, readFile, rm, stat, writeFile } from 'node:fs/promises';
4
6
  import os from 'node:os';
5
7
  import path from 'node:path';
6
8
 
@@ -8,7 +10,6 @@ const DEFAULT_TIMEOUT_MS = 8 * 60 * 1000;
8
10
  const RESOURCE_FETCH_TIMEOUT_MS = 20 * 1000;
9
11
  const MAX_OUTPUT_BYTES = 32 * 1024;
10
12
  const SENSITIVE_OUTPUT = /payment[-_ ]?proof|payment[-_ ]?needed|seller_signature|runtimeToken|authorization\s*:/i;
11
- const SENSITIVE_USER_OUTPUT = /payment[-_ ]?proof|payment[-_ ]?needed|seller_signature|runtimeToken|authorization\s*:|trade[_ -]?no|交易(?:流水)?号|订单号|查询单号|out[_ -]?shake|client[_ -]?session|payguard|validateclientparent|agentfamily/i;
12
13
  const DEFAULT_STATE_DIR = path.join(os.homedir(), '.xiashe', 'alipay-402');
13
14
  const OFFICIAL_MEDIA_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp']);
14
15
  const MAX_OFFICIAL_MEDIA_BYTES = 8 * 1024 * 1024;
@@ -55,75 +56,75 @@ const SAFE_OFFICIAL_ERROR_MESSAGE = /^(?!.*(?:https?:\/\/|payment[-_ ]?needed|pa
55
56
  const OFFICIAL_ERROR_DIAGNOSES = {
56
57
  PAYMENT_NEEDED_REJECTED: {
57
58
  stage: 'alipay_bill_validation',
58
- nextStep: '核对支付宝平台中该 APPID 的应用公钥、service_id、收款方 2088 seller_id 和线上接入状态;修复后必须创建新订单再测试。'
59
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
59
60
  },
60
61
  CLIENT_SESSION_IS_EMPTY: {
61
62
  stage: 'merchant_payment_proof_verification',
62
- nextStep: '买方 CLI 未传回有效 client_session;升级官方支付宝支付组件后,用新订单重新发起付款。'
63
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
63
64
  },
64
65
  PAYMENT_PROOF_AGENT_MISMATCH: {
65
66
  stage: 'merchant_payment_proof_verification',
66
- nextStep: '支付凭证与当前 Agent 商户身份不一致;确认付款与重试使用同一官方钱包运行时后,以新订单重试。'
67
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
67
68
  },
68
69
  PAYMENT_PROOF_BUYER_MISMATCH: {
69
70
  stage: 'merchant_payment_proof_verification',
70
- nextStep: '支付买家与凭证买家不一致;不要复用凭证,请在同一支付宝买家身份下重新发起付款。'
71
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
71
72
  },
72
73
  PAYMENT_PROOF_ID_MISMATCH: {
73
74
  stage: 'merchant_payment_proof_verification',
74
- nextStep: 'Payment-Proof 中的卖家身份与本 Skill 配置不一致;核对 APPID、2088 seller_id 和 service_id。'
75
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
75
76
  },
76
77
  PAYMENT_PROOF_EMPTY: {
77
78
  stage: 'merchant_payment_proof_verification',
78
- nextStep: '官方钱包没有返回支付凭证;请停止,不要手工补造凭证,并用受支持运行时重新发起。'
79
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
79
80
  },
80
81
  PAYMENT_PROOF_INVALID: {
81
82
  stage: 'merchant_payment_proof_verification',
82
- nextStep: '支付宝返回的支付凭证格式无效;请使用最新官方买方组件,并创建新订单重试。'
83
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
83
84
  },
84
85
  PAYMENT_PROOF_NOT_FOUND: {
85
86
  stage: 'merchant_payment_proof_verification',
86
- nextStep: '支付凭证不存在或已过期;不要重复提交旧凭证,创建新订单后重新付款。'
87
+ nextStep: '支付凭证不存在或已过期;保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
87
88
  },
88
89
  PAYMENT_PROOF_STATUS_INVALID: {
89
90
  stage: 'merchant_payment_proof_verification',
90
- nextStep: '支付凭证已失效或已被使用;请创建新订单重新付款。'
91
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
91
92
  },
92
93
  PAYMENT_PROOF_TRADE_NO_MISMATCH: {
93
94
  stage: 'merchant_payment_proof_verification',
94
- nextStep: '支付凭证与交易号不匹配;不要重放该凭证,创建新订单后重新付款。'
95
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
95
96
  },
96
97
  TRADE_NOT_FOUND: {
97
98
  stage: 'merchant_payment_proof_verification',
98
- nextStep: '支付宝找不到该交易;先查询官方钱包本地状态,未创建交易时用新订单重新发起。'
99
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
99
100
  },
100
101
  TRADE_NO_EMPTY: {
101
102
  stage: 'merchant_payment_proof_verification',
102
- nextStep: '官方钱包未返回交易号;当前交易不可继续,请创建新订单重新发起。'
103
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
103
104
  },
104
105
  TRADE_NO_INVALID: {
105
106
  stage: 'merchant_payment_proof_verification',
106
- nextStep: '官方钱包返回的交易号格式无效;升级官方买方组件后以新订单重试。'
107
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
107
108
  },
108
109
  TRADE_STATUS_CLOSED: {
109
110
  stage: 'merchant_payment_proof_verification',
110
- nextStep: '该交易已关闭;不要重试旧订单,请创建新订单重新付款。'
111
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
111
112
  },
112
113
  TRADE_STATUS_UNPAID: {
113
114
  stage: 'merchant_payment_proof_verification',
114
- nextStep: '交易尚未完成付款;如本地有查询凭证则运行 status,否则创建新订单重新发起。'
115
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
115
116
  },
116
117
  SELLER_IDENTITY_MISMATCH: {
117
118
  stage: 'merchant_fulfillment_confirmation',
118
- nextStep: '已交付的 Skill 权益不会撤销;运营方应核对卖家 APPID、2088 seller_id 与交易卖方身份。'
119
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
119
120
  },
120
121
  SELLER_ID_EMPTY: {
121
122
  stage: 'merchant_fulfillment_confirmation',
122
- nextStep: '已交付的 Skill 权益不会撤销;运营方应检查商户应用签名与卖家身份配置。'
123
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
123
124
  },
124
125
  TRADE_STATUS_INVALID: {
125
126
  stage: 'merchant_fulfillment_confirmation',
126
- nextStep: '已交付的 Skill 权益不会撤销;运营方应查询支付宝交易状态后处理履约回执。'
127
+ nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
127
128
  }
128
129
  };
129
130
 
@@ -264,43 +265,42 @@ function statePaths(resourceUrl, options = {}) {
264
265
  }
265
266
 
266
267
  async function ensurePrivateDirectory(directory) {
267
- await mkdir(directory, { recursive: true, mode: 0o700 });
268
- // mkdir does not change permissions of an existing directory.
269
- await chmod(directory, 0o700);
268
+ await privateDirectory(directory);
270
269
  }
271
270
 
272
271
  async function writePrivateFile(filePath, contents) {
273
- await writeFile(filePath, contents, { encoding: 'utf8', mode: 0o600 });
272
+ await checkPrivateFile(filePath);
273
+ await writeFile(filePath, contents, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
274
274
  await chmod(filePath, 0o600);
275
275
  }
276
276
 
277
277
  async function readPaymentState(resourceUrl, options = {}) {
278
278
  const { statePath } = statePaths(resourceUrl, options);
279
279
  try {
280
+ await checkPrivateFile(statePath);
280
281
  const parsed = JSON.parse(await readFile(statePath, 'utf8'));
281
282
  if (!parsed || parsed.version !== 1 || parsed.resourceDigest !== digest(resourceUrl)) {
282
- return null;
283
+ throw Error('PAYMENT_STATE_IDENTITY_MISMATCH');
283
284
  }
284
285
  // Earlier bridge releases accidentally kept the host business session in
285
286
  // the local retry state. It is required only for the initial official
286
287
  // wallet invocation; status queries use their separate query credential.
287
- // Remove it as soon as an old state file is read.
288
+ // Drop it in memory; the next locked atomic save removes it from disk.
288
289
  if (Object.prototype.hasOwnProperty.call(parsed, 'sessionId')) {
289
290
  const { sessionId: _legacySessionId, ...withoutSession } = parsed;
290
- await writePrivateFile(statePath, `${JSON.stringify(withoutSession)}\n`);
291
291
  return withoutSession;
292
292
  }
293
293
  return parsed;
294
294
  } catch (error) {
295
295
  if (error?.code === 'ENOENT') return null;
296
- throw new AlipayWalletError('ALIPAY_PAYMENT_STATE_INVALID', '本地支付宝付款状态无法读取;请重新发起本次付款。');
296
+ throw new AlipayWalletError('ALIPAY_PAYMENT_STATE_INVALID', '本地支付宝付款状态无法读取;请保留原交易并联系支持核对,勿重复付款。');
297
297
  }
298
298
  }
299
299
 
300
300
  async function writePaymentState(state, options = {}) {
301
301
  const { directory, statePath } = statePaths(state.resourceUrl, options);
302
302
  await ensurePrivateDirectory(directory);
303
- await writePrivateFile(statePath, `${JSON.stringify(state)}\n`);
303
+ await atomicPrivateJson(statePath, state);
304
304
  }
305
305
 
306
306
  function defaultRunFile(command, args, options) {
@@ -410,16 +410,6 @@ function paymentStatusFromOutput(stdout, stderr) {
410
410
  };
411
411
  }
412
412
 
413
- function userVisibleWalletOutput(stdout, stderr) {
414
- const lines = `${stdout}\n${stderr}`
415
- .replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, '')
416
- .split(/\r?\n/)
417
- .map((line) => line.trim())
418
- .filter((line) => line && !line.startsWith('MEDIA:') && !SENSITIVE_USER_OUTPUT.test(line))
419
- .slice(0, 12);
420
- return lines.length ? lines.join('\n').slice(0, 1_200) : null;
421
- }
422
-
423
413
  /** Preserve only an image emitted by the official wallet in this invocation. */
424
414
  async function officialWalletMedia(stdout, stderr) {
425
415
  const mediaLine = `${stdout}\n${stderr}`.split(/\r?\n/).find((line) => line.trim().startsWith('MEDIA:'));
@@ -502,14 +492,14 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
502
492
  merchantDiagnostic,
503
493
  nextStep: fulfillment
504
494
  ? 'Skill 权益已交付;运营方应按商家验证诊断处理履约回执,买家无需重复付款。'
505
- : '商家已返回支付宝验凭证诊断;不要手工补造凭证,按诊断修复后创建新订单重新付款。'
495
+ : '商家已返回支付宝验凭证诊断;不要手工补造凭证,按诊断修复后查询原交易,勿重复付款。'
506
496
  };
507
497
  }
508
498
  if (failureCode === 'payment_needed_rejected') {
509
499
  return {
510
500
  ...base,
511
501
  stage: 'alipay_bill_validation',
512
- nextStep: '核对支付宝平台中该 APPID 的应用公钥、service_id、收款方 2088 seller_id 和线上接入状态;修复后必须创建新订单再测试。',
502
+ nextStep: '核对支付宝平台中该 APPID 的应用公钥、service_id、收款方 2088 seller_id 和线上接入状态;修复后先核对原交易,勿重复付款。',
513
503
  ...(officialCode ? { officialCode } : {})
514
504
  };
515
505
  }
@@ -525,7 +515,7 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
525
515
  return {
526
516
  ...base,
527
517
  stage: 'buyer_identity_validation',
528
- nextStep: '支付宝钱包的买家身份未通过校验;完成钱包授权后,用同一受支持运行时创建新订单。',
518
+ nextStep: '支付宝钱包的买家身份未通过校验;通过官方流程处理后,核对原交易,勿重复付款。',
529
519
  ...(officialCode ? { officialCode } : {})
530
520
  };
531
521
  }
@@ -533,7 +523,7 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
533
523
  return {
534
524
  ...base,
535
525
  stage: 'wallet_authorization',
536
- nextStep: '支付宝钱包未完成授权或未启用;先完成官方钱包授权,再创建新订单。',
526
+ nextStep: '支付宝钱包未完成授权或未启用;按官方流程处理并核对原交易,勿重复付款。',
537
527
  ...(officialCode ? { officialCode } : {})
538
528
  };
539
529
  }
@@ -541,7 +531,7 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
541
531
  return {
542
532
  ...base,
543
533
  stage: 'wallet_network',
544
- nextStep: '钱包或网络请求没有完成;先检查网络,再创建新订单。',
534
+ nextStep: '钱包或网络请求没有完成;先检查网络并查询原交易,勿重复付款。',
545
535
  ...(officialCode ? { officialCode } : {})
546
536
  };
547
537
  }
@@ -559,50 +549,11 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
559
549
  };
560
550
  }
561
551
 
562
- function paymentFailureUserVisible(diagnosis) {
563
- const lines = [
564
- diagnosis.stage === 'merchant_payment_proof_verification'
565
- ? '商家未能验证本次支付宝付款凭证,尚未授予付费 Skill 权益。'
566
- : diagnosis.code === 'wallet_query_credential_missing'
567
- ? '支付宝钱包未返回可继续查询的交易凭据,当前付款状态无法确认。'
568
- : '支付宝付款未创建可确认交易。',
569
- `诊断代码:${diagnosis.code}`,
570
- `失败阶段:${diagnosis.stage}`,
571
- ...(diagnosis.officialCode ? [`官方返回代码:${diagnosis.officialCode}`] : []),
572
- ...(diagnosis.officialSubCode ? [`官方子码:${diagnosis.officialSubCode}`] : []),
573
- ...(diagnosis.officialMessage ? [`官方消息:${diagnosis.officialMessage}`] : []),
574
- ...(diagnosis.officialRequestId ? [`官方请求标识:${diagnosis.officialRequestId}`] : []),
575
- ...(diagnosis.officialTraceId ? [`官方追踪标识:${diagnosis.officialTraceId}`] : []),
576
- ...(diagnosis.merchantDiagnostic ? [`商家验证诊断:${diagnosis.merchantDiagnostic}`] : []),
577
- `下一步:${diagnosis.nextStep}`
578
- ];
579
- return lines.join('\n');
580
- }
581
-
582
552
  function paymentMessage(status) {
583
553
  if (status === 'completed') return '支付宝钱包显示本次付款已完成;正在由服务端确认权益。';
584
554
  if (status === 'pending_confirmation') return '支付宝已发起本次付款确认;请打开支付宝 App 完成确认,然后运行 status。';
585
555
  if (status === 'failed') return '支付宝钱包显示本次付款未完成;未授予付费 Skill 权益。';
586
- return '支付宝官方钱包已被调用,但尚未返回可确认的付款状态;请运行 status 查询,或重新发起付款。';
587
- }
588
-
589
- function paymentFailureMessage(failureCode) {
590
- if (failureCode === 'merchant_payment_proof_verification_failed') {
591
- return '商家未能验证支付宝付款凭证,未授予付费 Skill 权益;请勿重放旧凭证或重复付款。';
592
- }
593
- if (failureCode === 'wallet_query_credential_missing') {
594
- return '支付宝钱包返回待确认,但未返回可继续查询的交易凭据。无法确认是否已付款,因此不会授予付费 Skill 权益;请勿再次付款。';
595
- }
596
- if (failureCode === 'wallet_trade_progress_failed') {
597
- return '支付宝钱包未能创建可确认的交易;未授予付费 Skill 权益。官方钱包没有给出可归因的原因,不能据此判断为 Agent 不受支持、账单签名错误或已扣款;请勿重复付款。';
598
- }
599
- if (failureCode === 'wallet_runtime_not_supported') {
600
- return '当前 Agent 运行环境不支持支付宝 AI付;未授予付费 Skill 权益。';
601
- }
602
- if (failureCode === 'payment_needed_rejected') {
603
- return '支付宝端拒绝了本次付款账单,未创建交易、未扣款。请确认该 APPID 已在支付宝完成 AI按量付费的服务注册、密钥配置、技术集成确认与线上验证前置步骤;若这些均已完成,请提交支付宝问题反馈并附上本次发生时间。';
604
- }
605
- return '支付宝官方钱包没有生成可确认的付款状态;未授予付费 Skill 权益。';
556
+ return '支付宝官方钱包已被调用,但尚未返回可确认的付款状态;请查询原交易或联系支持,勿重复付款。';
606
557
  }
607
558
 
608
559
  async function fetchPaymentNeeded(resourceUrl, options = {}) {
@@ -733,21 +684,18 @@ export async function preflightAlipay402Resource(input, options = {}) {
733
684
  }
734
685
 
735
686
  function publicPaymentResult(state, status, diagnostic, options = {}) {
736
- const commandFailed = options.commandFailed === true;
737
687
  const failureCode = options.failureCode || 'official_cli_nonzero_exit';
738
688
  const failed = status === 'failed' || status === 'wallet_command_failed';
739
- const diagnosis = failed ? options.diagnosis : null;
689
+ const customerError = failed || status === 'unknown' ? paymentCustomerError(failureCode, { stage: 'payment', reference: `alipay-402:${state.resourceDigest.slice(0, 16)}` }) : null;
740
690
  return {
741
691
  ok: !failed,
742
692
  status,
743
693
  provider: 'alipay-agent-payment',
744
694
  attemptId: `alipay-402:${state.resourceDigest.slice(0, 16)}`,
745
695
  walletInvoked: true,
746
- message: failed ? paymentFailureMessage(failureCode) : paymentMessage(status),
747
- diagnostic,
748
- ...(options.merchantResource ? { merchantResource: options.merchantResource } : {}),
749
- ...(failed && diagnosis ? { userVisible: paymentFailureUserVisible(diagnosis), diagnosis } : {}),
750
- ...(!failed && options.userVisible ? { userVisible: options.userVisible } : {}),
696
+ message: customerError ? customerError.message : paymentMessage(status),
697
+ userVisible: customerError ? formatPaymentCustomerError(customerError) : paymentMessage(status),
698
+ ...(customerError ? { customerError } : {}),
751
699
  ...(options.officialMedia ? { officialMedia: options.officialMedia } : {}),
752
700
  ...(options.queryCredentialSource ? { queryCredentialSource: options.queryCredentialSource } : {}),
753
701
  ...(status === 'pending_confirmation'
@@ -804,6 +752,27 @@ export async function getAlipayWalletBridgeInfo(options = {}) {
804
752
  * a stable session id. No protocol data leaves this module.
805
753
  */
806
754
  export async function payAlipay402Resource(input, options = {}) {
755
+ if (input?.confirm !== true) throw new AlipayWalletError('ALIPAY_CONFIRMATION_REQUIRED', '付款操作必须由用户明确确认。');
756
+ const resourceUrl = normalizeResourceUrl(input?.resourceUrl);
757
+ const paths = statePaths(resourceUrl, options);
758
+ await ensurePrivateDirectory(paths.directory);
759
+ return withPrivateLock(paths.statePath, async () => {
760
+ const previous = await readPaymentState(resourceUrl, options);
761
+ if (previous) {
762
+ if (previous.status === 'completed') {
763
+ const resource = await fetchPaymentNeeded(resourceUrl, options);
764
+ if (resource.alreadyPaid) return publicPaymentResult(previous, 'completed', 'resource_already_available');
765
+ }
766
+ if (previous.queryCredential?.value) return queryAlipay402ResourceUnlocked(input, options);
767
+ return { ok: false, status: 'payment_result_unconfirmed', provider: 'alipay-agent-payment', walletInvoked: false, retryPayment: false,
768
+ customerError: paymentCustomerError('PAYMENT_RESULT_UNCONFIRMED', { stage: 'local_state', reference: `alipay-402:${previous.resourceDigest.slice(0, 16)}` }),
769
+ message: '原付款尝试尚未核实,已阻止再次付款。请查询原交易或联系支持,勿删除本地记录后重付。' };
770
+ }
771
+ return payAlipay402ResourceUnlocked(input, options);
772
+ });
773
+ }
774
+
775
+ async function payAlipay402ResourceUnlocked(input, options = {}) {
807
776
  if (input?.confirm !== true) {
808
777
  throw new AlipayWalletError('ALIPAY_CONFIRMATION_REQUIRED', '付款操作必须由用户明确确认。请在展示付款用途后使用 --confirm。');
809
778
  }
@@ -888,12 +857,7 @@ export async function payAlipay402Resource(input, options = {}) {
888
857
  return publicPaymentResult(state, status, result.diagnostic, {
889
858
  commandFailed: failed,
890
859
  failureCode,
891
- diagnosis: failed ? paymentFailureDiagnosis(failureCode, walletInvocation.stdout, walletInvocation.stderr) : undefined,
892
- userVisible: ['pending_confirmation', 'completed'].includes(status)
893
- ? userVisibleWalletOutput(walletInvocation.stdout, walletInvocation.stderr)
894
- : null,
895
- officialMedia,
896
- merchantResource: state.merchantResource
860
+ officialMedia
897
861
  });
898
862
  }
899
863
 
@@ -904,6 +868,13 @@ export async function payAlipay402Resource(input, options = {}) {
904
868
  * local state, initiate a payment, or acknowledge fulfillment.
905
869
  */
906
870
  export async function queryAlipay402Resource(input, options = {}) {
871
+ const resourceUrl = normalizeResourceUrl(input?.resourceUrl);
872
+ const paths = statePaths(resourceUrl, options);
873
+ await ensurePrivateDirectory(paths.directory);
874
+ return withPrivateLock(paths.statePath, () => queryAlipay402ResourceUnlocked(input, options));
875
+ }
876
+
877
+ async function queryAlipay402ResourceUnlocked(input, options = {}) {
907
878
  const resourceUrl = normalizeResourceUrl(input?.resourceUrl);
908
879
  const suppliedOutShakeNo = input?.outShakeNo || input?.businessNo
909
880
  ? normalizeOutShakeNo(input?.outShakeNo || input?.businessNo)
@@ -922,7 +893,7 @@ export async function queryAlipay402Resource(input, options = {}) {
922
893
  provider: 'alipay-agent-payment',
923
894
  walletInvoked: false,
924
895
  confirmation: { source: 'official_alipay_wallet', required: false },
925
- message: '没有可查询的本地支付宝付款记录;请重新发起付款,不要把付款凭证粘贴到对话中。',
896
+ message: '没有可查询的本地交易凭据;请联系支持核对原交易,勿重复付款或把付款凭证粘贴到对话中。',
926
897
  diagnostic: 'payment_state_not_found'
927
898
  };
928
899
  }
@@ -972,10 +943,6 @@ export async function queryAlipay402Resource(input, options = {}) {
972
943
  return publicPaymentResult(state, status, result.diagnostic, {
973
944
  commandFailed: failed,
974
945
  failureCode,
975
- diagnosis: failed ? paymentFailureDiagnosis(failureCode, walletInvocation.stdout, walletInvocation.stderr) : undefined,
976
- userVisible: ['pending_confirmation', 'completed'].includes(status)
977
- ? userVisibleWalletOutput(walletInvocation.stdout, walletInvocation.stderr)
978
- : null,
979
946
  officialMedia,
980
947
  ...(suppliedOutShakeNo ? { queryCredentialSource: 'supplied_out_shake_no' } : {})
981
948
  });
@@ -997,40 +964,21 @@ export async function diagnoseAlipay402Resource(input, options = {}) {
997
964
  message: '没有找到本地付款尝试;请不要因此重复付款。'
998
965
  };
999
966
  }
1000
- const result = {
1001
- ok: state.status !== 'failed' && state.status !== 'wallet_command_failed',
1002
- status: state.status || 'unknown',
1003
- provider: 'alipay-agent-payment',
967
+ // Build from fixed fields only. Historical local snapshots are private data,
968
+ // not a public response schema; never spread or echo them.
969
+ const statuses = new Set(['started', 'unknown', 'failed', 'wallet_command_failed', 'pending_confirmation', 'completed']);
970
+ const status = statuses.has(state.status) ? state.status : 'unknown';
971
+ const customerError = status === 'completed' || status === 'pending_confirmation' ? null
972
+ : paymentCustomerError(state.lastFailureCode, { reference: `alipay-402:${state.resourceDigest.slice(0, 16)}` });
973
+ return {
974
+ ok: status === 'completed' || status === 'pending_confirmation',
975
+ status, provider: 'alipay-agent-payment', walletInvoked: false,
1004
976
  attemptId: `alipay-402:${state.resourceDigest.slice(0, 16)}`,
1005
- walletInvoked: state.status !== 'started',
1006
977
  queryAvailable: Boolean(state.queryCredential?.value),
1007
- diagnostic: state.lastWalletDiagnostic || 'payment_state_recorded',
1008
- merchantResource: state.merchantResource || null,
1009
- ...(state.lastFailureCode ? { failureCode: state.lastFailureCode } : {}),
1010
- ...(state.lastDiagnosis ? {
1011
- diagnosis: state.lastDiagnosis,
1012
- userVisible: paymentFailureUserVisible(state.lastDiagnosis)
1013
- } : {}),
1014
- updatedAt: state.updatedAt || null
978
+ message: customerError ? customerError.message : paymentMessage(status),
979
+ userVisible: customerError ? formatPaymentCustomerError(customerError) : paymentMessage(status),
980
+ ...(customerError ? { customerError, retryPayment: false } : {})
1015
981
  };
1016
- // TRADE_PROGRESS_FAILED is deliberately generic in the official wallet
1017
- // output. Attach a redacted report to the one diagnose command an Agent is
1018
- // already required to run, rather than relying on it to remember a second
1019
- // optional command after a failed payment.
1020
- if (state.lastFailureCode === 'wallet_trade_progress_failed') {
1021
- const support = await createAlipay402SupportReport({ resourceUrl }, options);
1022
- if (support.ok && support.report) {
1023
- result.supportReport = support.report;
1024
- // Some Agents intentionally present only `userVisible` from a bridge
1025
- // result. Put the already-redacted support text there as well so the
1026
- // only useful evidence from this generic upstream error is not silently
1027
- // dropped by a client-side response mapper.
1028
- result.userVisible = [result.userVisible, '', '支付宝支持诊断:', support.report.text]
1029
- .filter((line) => typeof line === 'string' && line.length > 0)
1030
- .join('\n');
1031
- }
1032
- }
1033
- return result;
1034
982
  }
1035
983
 
1036
984
  /**
@@ -1054,40 +1002,14 @@ export async function createAlipay402SupportReport(input, options = {}) {
1054
1002
  };
1055
1003
  }
1056
1004
 
1057
- const failureCode = state.lastFailureCode || null;
1058
- const diagnosis = state.lastDiagnosis || null;
1059
- const failedBeforeConfirmation = !state.queryCredential?.value &&
1060
- ['failed', 'wallet_command_failed'].includes(state.status);
1061
- const { stdout, stderr } = await runOfficialCli(['--version'], options);
1062
- const runtimeVersion = safeRuntimeVersion(stdout, stderr) || null;
1063
- const lines = [
1064
- '[环节]:402 支付 / 官方钱包创建交易',
1065
- `[结果]:${failedBeforeConfirmation ? '未创建可确认交易,未获得 Payment-Proof' : '请以本地诊断状态为准'}`,
1066
- `[桥接诊断]:${diagnosis?.code || failureCode || 'unknown'}`,
1067
- `[官方代码]:${diagnosis?.officialCode || '未返回'}`,
1068
- `[官方运行时]:${runtimeVersion || '未知'}`,
1069
- `[发生时间]:${state.updatedAt || state.createdAt || '未知'}`,
1070
- '[已确认]:卖方资源返回字段结构有效的 402 账单;本次未生成可查询交易凭证。',
1071
- '[请协助]:返回本次 TRADE_PROGRESS_FAILED 的子码、requestId/traceId,以及交易创建被拒绝的具体校验项。'
1072
- ];
1005
+ const customerError = paymentCustomerError(state.lastFailureCode, { reference: `alipay-402:${state.resourceDigest.slice(0, 16)}` });
1073
1006
  return {
1074
- ok: true,
1075
- status: 'support_report_ready',
1076
- provider: 'alipay-agent-payment',
1077
- walletInvoked: false,
1007
+ ok: true, status: 'support_report_ready', provider: 'alipay-agent-payment', walletInvoked: false,
1078
1008
  report: {
1079
- category: 'ALIPAY_402_TRADE_CREATION_FAILED',
1080
- attemptId: `alipay-402:${state.resourceDigest.slice(0, 16)}`,
1081
- occurredAt: state.updatedAt || state.createdAt || null,
1082
- officialRuntimeVersion: runtimeVersion,
1083
- failureCode,
1084
- ...(diagnosis?.officialCode ? { officialCode: diagnosis.officialCode } : {}),
1085
- ...(diagnosis?.officialSubCode ? { officialSubCode: diagnosis.officialSubCode } : {}),
1086
- billShapeValidated: state.merchantResource?.billShapeValidated === true,
1087
- paymentNeededReceived: state.merchantResource?.paymentNeededReceived === true,
1088
- queryCredentialCreated: Boolean(state.queryCredential?.value),
1089
- text: lines.join('\n')
1009
+ code: state.status === 'completed' ? 'PAYMENT_COMPLETED' : state.status === 'pending_confirmation' ? 'PAYMENT_CONFIRMATION_PENDING' : customerError.code,
1010
+ supportReference: customerError.supportReference,
1011
+ text: state.status === 'completed' || state.status === 'pending_confirmation' ? paymentMessage(state.status) : formatPaymentCustomerError(customerError)
1090
1012
  },
1091
- message: '已生成脱敏的问题反馈材料;其中不包含订单号、资源 URL、账单、Payment-Proof 或钱包凭证。'
1013
+ message: '请向支持提供此摘要;无需提供密码或付款凭据。'
1092
1014
  };
1093
1015
  }
package/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ export { paymentCustomerError, formatPaymentCustomerError } from './paymentErrors.mjs';
1
2
  import { privateDirectory, checkPrivateFile, withPrivateLock, atomicPrivateJson } from './privateState.mjs';
2
3
  import { boundedJsonRequest } from './http.mjs';
3
4
  import { createHash, randomUUID } from 'node:crypto';
@@ -18,7 +19,7 @@ export { serveRuntimeMcp } from './runtimeMcp.mjs';
18
19
 
19
20
  export { safeOutput as redactCredentials } from './outputSafety.mjs';
20
21
 
21
- export const VERSION = '0.1.41';
22
+ export const VERSION = '0.1.42';
22
23
  export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
23
24
 
24
25
  export const DEFAULTS = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiashe/sdk",
3
- "version": "0.1.41",
3
+ "version": "0.1.42",
4
4
  "type": "module",
5
5
  "main": "index.mjs",
6
6
  "exports": {
@@ -0,0 +1,46 @@
1
+ // Pure, portable presentation shared by the server and CLI. Never serialize an
2
+ // arbitrary exception, provider message, request, or credential into this object.
3
+ const support = '保留原会话,联系支持并提供错误代码及参考号(如有);不要提供密码、密钥或付款凭据。';
4
+ const original = '回到原 Agent 会话,查询原支付宝交易。若已扣款,请勿再次付款;查询仍异常时联系支持。';
5
+ const cases = [
6
+ { match: ['RUNTIME_SESSION_REQUIRED'], code: 'SKILL_DELIVERY_SESSION_REQUIRED', title: '需要恢复原交付会话', message: '当前环境找不到可用的原交付授权。', stage: 'delivery', nextAction: 'resume_original_delivery', nextStep: '回到原购买账号与 Agent 会话恢复交付;不要删除状态、重复首次接入或再次购买。' },
7
+ { match: ['ALIPAY_CONFIRMATION_REQUIRED'], code: 'PAYMENT_CONFIRMATION_REQUIRED', title: '需要确认付款用途', message: '当前操作缺少明确的付款确认。', stage: 'payment', nextAction: 'confirm_original_intent', nextStep: '先向用户展示原订单的付款用途并获得确认;已有付款尝试时先查询原交易,不要重复付款。' },
8
+ { match: ['ALIPAY_RESOURCE_URL_INVALID', 'ALIPAY_RESOURCE_URL_UNSAFE', 'ALIPAY_OUT_SHAKE_NO_INVALID', 'ALIPAY_OUT_SHAKE_NO_CONFLICT', 'ALIPAY_SESSION_ID_INVALID', 'ALIPAY_INTENT_SUMMARY_REQUIRED'], code: 'PAYMENT_INPUT_INVALID', title: '付款参数需要检查', message: '付款入口、查询参数或用途摘要未通过检查。', stage: 'local_state', nextAction: 'restore_original_agent', nextStep: '回原 Agent 会话恢复原订单和查询参数;不要自行拼接链接或查询凭据。' },
9
+ { match: ['SKILL_PAYMENT_EXPIRED_REQUIRES_RECONCILIATION'], code: 'PAYMENT_WINDOW_EXPIRED', title: '付款窗口已结束', message: '此订单不能继续付款,原交易结果仍需核对。', stage: 'verification', nextAction: 'check_original_payment', nextStep: original },
10
+ { match: ['SKILL_PAYMENT_MULTIPLE_UNRESOLVED_ORDERS'], code: 'PAYMENT_MULTIPLE_ATTEMPTS_PENDING', title: '发现多笔未决购买', message: '系统已暂停新的付款,避免重复收费。', stage: 'verification', nextAction: 'contact_support', nextStep: support },
11
+ { match: ['SKILL_PAYMENT_HISTORY_REVIEW_REQUIRED'], code: 'PAYMENT_HISTORY_SYNCING', title: '历史购买记录正在核对', message: '历史记录核对完成前,暂不开放新的付款。', stage: 'verification', nextAction: 'wait_and_resume', nextStep: '稍后在原会话恢复获取;持续未恢复时联系支持,不要换会话重复购买。' },
12
+ { match: ['PRIVATE_STATE_BUSY', 'ACCESS_STATE_BUSY'], code: 'PAYMENT_OPERATION_IN_PROGRESS', title: '原操作仍在处理', message: '另一个进程正在处理同一授权或交易,当前请求已停止。', stage: 'local_state', nextAction: 'wait_existing_operation', nextStep: '等待原窗口的操作结束。若曾异常退出,请联系支持检查恢复状态,不要删除交易记录后重付。' },
13
+ { match: ['ALIPAY_PAYMENT_STATE_INVALID', 'PRIVATE_STATE_UNSAFE_FILE', 'PRIVATE_STATE_UNSAFE_DIRECTORY'], code: 'PAYMENT_LOCAL_STATE_UNREADABLE', title: '交易恢复记录无法读取', message: '无法安全读取本地交易状态,已阻止再次付款。', stage: 'local_state', nextAction: 'contact_support', nextStep: support },
14
+ { match: ['ALIPAY_BOT_NOT_INSTALLED', 'ALIPAY_SESSION_ID_REQUIRED', 'HOST_BUSINESS_SESSION_UNAVAILABLE', 'wallet_runtime_not_supported'], code: 'PAYMENT_AGENT_SETUP_REQUIRED', title: '当前 Agent 暂不能完成付款', message: '当前 Agent 缺少受支持的支付宝付款能力或原任务会话。', stage: 'payment', nextAction: 'restore_original_agent', nextStep: '在原 Agent 中安装或更新官方支付宝支付能力后恢复原交易;不要手工填写会话标识。' },
15
+ { match: ['wallet_not_ready', 'WALLET_NOT_READY'], code: 'PAYMENT_AUTHORIZATION_REQUIRED', title: '支付宝授权尚未完成', message: '需要按官方付款流程完成授权确认。', stage: 'payment', nextAction: 'complete_official_authorization', nextStep: '回原会话按支付宝官方提示处理授权,然后查询原交易,不要新建付款。' },
16
+ { match: ['buyer_identity_rejected', 'BUYER_IDENTITY_REJECTED'], code: 'PAYMENT_IDENTITY_CHECK_REQUIRED', title: '买家身份未通过核验', message: '当前支付宝身份与原交易的核验结果不一致。', stage: 'payment', nextAction: 'check_original_identity', nextStep: '确认使用原付款账号和原 Agent 会话;仍失败时联系支持,不要发送身份凭据。' },
17
+ { match: ['insufficient_balance'], code: 'PAYMENT_BALANCE_INSUFFICIENT', title: '付款余额不足', message: '支付宝报告可用余额不足,原订单仍需核对。', stage: 'payment', nextAction: 'check_original_payment', nextStep: '先在支付宝中查看原交易及余额,再按官方提示处理;不要另建订单。' },
18
+ { match: ['DELIVERY_RECOVERY_REQUIRED', 'DELIVERY_DOWNLOAD_FAILED', 'DELIVERY_NOT_READY'], code: 'SKILL_DELIVERY_INTERRUPTED', title: 'Skill 尚未完成交付', message: '完整包暂未就绪或下载未完成,不需要重新购买。', stage: 'delivery', nextAction: 'resume_original_delivery', nextStep: '使用同一账号和原 Agent 会话恢复交付;若已自动恢复仍失败,请联系支持。' },
19
+ { match: ['PAYMENT_ORDER_NOT_FOUND'], code: 'PAYMENT_ORDER_UNAVAILABLE', title: '当前入口找不到订单', message: '可能使用了过期入口或不同环境的链接,不能据此判断未付款。', stage: 'verification', nextAction: 'restore_original_agent', nextStep: '回到原购买会话确认账号和入口;不要在另一个环境重新付款。' },
20
+ ];
21
+ const configuration = new Set(['payment_needed_rejected', 'ALIPAY_AI_COLLECT_SERVICE_NOT_READY', 'ALIPAY_AI_COLLECT_SERVICE_ID_REQUIRED', 'ALIPAY_AI_COLLECT_SERVICE_ID_CONFLICT', 'ALIPAY_AI_COLLECT_SERVICE_BINDING_DUPLICATED', 'ALIPAY_AI_COLLECT_SERVICE_BINDING_INVALID', 'ALIPAY_AI_COLLECT_REREGISTRATION_REQUIRED', 'CREATOR_ALIPAY_APP_REQUIRED', 'CREATOR_ALIPAY_APP_KEYS_NOT_VERIFIED', 'ALIPAY_PUBLIC_KEY_REQUIRED', 'ALIPAY_RESPONSE_SIGN_INVALID', 'ALIPAY_BILL_SIGNATURE_SELF_CHECK_FAILED', 'ALIPAY_APP_ID_INVALID', 'ALIPAY_AI_COLLECT_DISABLED', 'PAID_SKILL_PLAN_REQUIRED']);
22
+
23
+ /** @param {unknown} input @param {{stage?: string, reference?: string}} [options] */
24
+ export function paymentCustomerError(input, options = {}) {
25
+ const value = input && typeof input === 'object' ? /** @type {Record<string, unknown>} */ (input) : {};
26
+ const raw = typeof input === 'string' ? input : typeof value.code === 'string' ? value.code : typeof value.message === 'string' ? value.message : '';
27
+ // Only read the first normalized error token. No prose/JSON/body is forwarded.
28
+ const token = /^([A-Za-z][A-Za-z0-9_]{2,180})(?=[:\s]|$)/.exec(raw)?.[1] ?? '';
29
+ const selected = cases.find(item => item.match.includes(token));
30
+ const seller = configuration.has(token);
31
+ const reference = typeof options.reference === 'string' && /^(?:pay_[0-9a-f-]{36}|alipay-402:[0-9a-f]{16})$/.test(options.reference) ? options.reference : undefined;
32
+ return {
33
+ code: selected?.code ?? (seller ? 'PAYMENT_SELLER_CONFIGURATION_REQUIRED' : 'PAYMENT_RESULT_UNCONFIRMED'),
34
+ title: selected?.title ?? (seller ? '收款配置需要处理' : '付款结果尚未确认'),
35
+ message: selected?.message ?? (seller ? '创作者的收款配置或支付签名未通过检查,当前不能继续付款。' : '尚未取得可信的付款结果,系统不会因此认定未扣款。'),
36
+ nextAction: selected?.nextAction ?? (seller ? 'contact_creator' : 'check_original_payment'),
37
+ nextStep: selected?.nextStep ?? (seller ? '请联系创作者检查服务登记、应用配置和签名。买家无需修改密钥;保留原交易,勿重复付款。' : original),
38
+ retryPayment: false,
39
+ ...(reference ? { supportReference: reference } : {})
40
+ };
41
+ }
42
+
43
+ /** @param {ReturnType<typeof paymentCustomerError>} error */
44
+ export function formatPaymentCustomerError(error) {
45
+ return [error.title, error.message, `下一步:${error.nextStep}`, ...(error.supportReference ? [`支持参考号:${error.supportReference}`] : [])].join('\n');
46
+ }