@whyshu/argent-engine 0.8.0-rc.9 → 0.13.28

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 (106) hide show
  1. package/MANIFEST.json +102 -40
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +2 -2
  7. package/engine/core/lib/account-token.mjs +37 -0
  8. package/engine/core/lib/redact.mjs +34 -0
  9. package/engine/core/mcp/billing-upload.mjs +77 -0
  10. package/engine/core/mcp/erp-server.mjs +300 -0
  11. package/engine/core/mcp/gateway.mjs +333 -0
  12. package/engine/core/mcp/meter.mjs +101 -0
  13. package/engine/core/mcp/server.mjs +245 -0
  14. package/engine/core/mcp/vault.mjs +78 -0
  15. package/engine/scripts/appointment-worker.mjs +456 -35
  16. package/engine/scripts/appointment_grab.py +1389 -264
  17. package/engine/scripts/appointment_rules.py +118 -0
  18. package/engine/scripts/argent-timers.mjs +227 -0
  19. package/engine/scripts/argent-web-preflight.mjs +123 -0
  20. package/engine/scripts/argent-web-verify.mjs +105 -0
  21. package/engine/scripts/billing-upload.mjs +26 -0
  22. package/engine/scripts/build-engine-package.mjs +7 -1
  23. package/engine/scripts/capability-packs.lock.json +323 -300
  24. package/engine/scripts/check-version-consistency.mjs +14 -1
  25. package/engine/scripts/collect-intel.mjs +108 -0
  26. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  27. package/engine/scripts/daily-report-timers.sh +36 -3
  28. package/engine/scripts/daily-report.mjs +78 -2
  29. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  30. package/engine/scripts/engine-manifest.mjs +90 -0
  31. package/engine/scripts/engine-runtime-install.mjs +92 -0
  32. package/engine/scripts/erp-ui-install.mjs +127 -0
  33. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  34. package/engine/scripts/erp-ui-verify.mjs +135 -0
  35. package/engine/scripts/flow-requirements.json +122 -99
  36. package/engine/scripts/full-exec-worker.mjs +251 -0
  37. package/engine/scripts/gen-preset-rows.mjs +1 -1
  38. package/engine/scripts/invoice_lip_runner.py +1 -0
  39. package/engine/scripts/invoice_runner.py +17 -6
  40. package/engine/scripts/invoice_stageb.py +21 -4
  41. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  42. package/engine/scripts/lib/intel-card.mjs +43 -0
  43. package/engine/scripts/lib/invoice_names.py +23 -0
  44. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  45. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  46. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  47. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  48. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  49. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  50. package/engine/scripts/lib/ml-items.mjs +40 -0
  51. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  52. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  53. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  54. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  55. package/engine/scripts/line_pack.py +196 -0
  56. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  57. package/engine/scripts/migrate-providers.mjs +3 -3
  58. package/engine/scripts/ml-ads-advice.mjs +140 -0
  59. package/engine/scripts/ml-ads.mjs +40 -0
  60. package/engine/scripts/ml-category-baseline.mjs +174 -0
  61. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  62. package/engine/scripts/ml-insight-run.sh +183 -0
  63. package/engine/scripts/ml-insight-timers.sh +224 -0
  64. package/engine/scripts/ml-listing-audit.mjs +170 -0
  65. package/engine/scripts/ml-market-matrix.mjs +84 -0
  66. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  67. package/engine/scripts/ml-messages.mjs +145 -0
  68. package/engine/scripts/npm-publish-argent.mjs +14 -0
  69. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  70. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  71. package/engine/scripts/ops-digest.mjs +98 -0
  72. package/engine/scripts/ops-verify.mjs +67 -0
  73. package/engine/scripts/orchestrator.py +410 -20
  74. package/engine/scripts/orchestrator_br.py +146 -4
  75. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  76. package/engine/scripts/publish-engine.mjs +111 -0
  77. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  78. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  79. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  80. package/engine/scripts/vertical-lint.mjs +12 -1
  81. package/engine/scripts/web-switch.mjs +121 -0
  82. package/engine/scripts/wenyao_fill_template.py +52 -15
  83. package/engine/scripts/wenyao_run.py +2 -1
  84. package/engine/skills/README.md +3 -3
  85. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  86. package/engine/skills/douyin-upload/SKILL.md +74 -0
  87. package/engine/skills/internal.json +28 -0
  88. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  89. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  90. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  91. package/engine/skills/ml-invoice/SKILL.md +2 -2
  92. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  93. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  94. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  95. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  96. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  97. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  98. package/engine/skills/tencent-upload/SKILL.md +60 -0
  99. package/engine/skills/weibo-upload/SKILL.md +106 -0
  100. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  101. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  102. package/engine/version.mjs +1 -1
  103. package/engine/verticals/README.md +7 -0
  104. package/engine/verticals/_engine-words.baseline.txt +27 -59
  105. package/engine/verticals/mercadolibre/manifest.json +132 -6
  106. package/package.json +5 -1
@@ -0,0 +1,342 @@
1
+ import { fetchItemsBatched } from './ml-items.mjs'
2
+
3
+ /**
4
+ * ml-listing-core.mjs —— Listing 体检(只读)取数 + 评分 + 整改项(L1 执行内核,纯逻辑)。
5
+ *
6
+ * ## 为什么用官方 /performance 而不是自己算分
7
+ * 平台官方 `GET /item/{ITEM_ID}/performance`(`/health` 已于 2026-02-07 停用)直接给:
8
+ * · `score`(0–100)+ `level`(按站点本地化)+ `calculated_at`;
9
+ * · `buckets[]`(`CHARACTERISTICS` / `OFFER`),每桶带 `score/status`;
10
+ * · `rules[]`:`status = COMPLETED | PENDING`、`mode = OPPORTUNITY | WARNING`,
11
+ * 带 `progress` 与 `wordings{title,label,link}`(**平台自己说"该做什么"+一键深链**)。
12
+ * ⇒ 我们**不自造评分模型**(客户与平台认官方分),只做:解析 → 分级 → 中文整改项 → 排序。
13
+ *
14
+ * ## 纪律
15
+ * · **纯 L1**:只 import `node:` 内建;HTTP 入口注入 `apiGet`;零写盘;
16
+ * · 容错:官方字段可能缺(不同站点/新旧版本)⇒ 一律软降级,不抛、不猜数;
17
+ * · 只读:本文件不出现在任何写路径上(写回在后续 P3b,需读写权限 + 守卫)。
18
+ */
19
+
20
+ /** 评分分级阈值(可按调优覆盖)。 */
21
+ export const GRADE_THRESHOLDS = { a: 80, b: 60, c: 40 }
22
+
23
+ /** 已知 rule key → 中文动作提示(未知 key 用官方 title 兜底)。 */
24
+ const RULE_HINTS = {
25
+ HAS_GTIN: '补 GTIN/条码(属性完整度最常扣分项)',
26
+ PICTURES_QUANTITY_MIN: '补主图到平台要求张数',
27
+ PICTURES_SIZE: '主图尺寸 ≥ 500×500(建议 1200×1200)',
28
+ TITLE_LENGTH: '标题长度落在类目允许区间',
29
+ TITLE_KEYWORDS: '标题含核心关键词与关键规格',
30
+ FREE_SHIPPING: '评估包邮(影响曝光与转化)',
31
+ WARRANTY: '补保修/售后信息',
32
+ DESCRIPTION: '补描述(移动端首屏要点前置)',
33
+ MEASUREMENTS: '补尺寸/重量(运费与转化都吃这个)',
34
+ VIDEO: '加视频(有视频的链接转化通常更高)',
35
+ CATALOG_LISTING: '进目录/关联 catalog(抢 buy box 的前提)',
36
+ BUY_BOX: '关注 buy box 归属与价格竞争力',
37
+ }
38
+
39
+ const num = (x) => (Number.isFinite(Number(x)) ? Number(x) : 0)
40
+ const str = (x) => String(x == null ? '' : x).trim()
41
+ const round1 = (x) => Math.round(Number(x || 0) * 10) / 10
42
+
43
+ /** 从 rule 对象里取中文标题(兼容多种官方字段名)。 */
44
+ function ruleTitle(rule) {
45
+ const w = (rule && rule.wordings) || {}
46
+ return str(w.title) || str(w.label) || str(rule.title) || str(rule.label) || str(rule.key)
47
+ }
48
+
49
+ function ruleLink(rule) {
50
+ const w = (rule && rule.wordings) || {}
51
+ return str(w.link) || str(rule.link)
52
+ }
53
+
54
+ /**
55
+ * 纯函数:把 `/item/{id}/performance` 的原始响应归一化。
56
+ * @returns {{score:number|null, level:string, levelWording:string, calculatedAt:string,
57
+ * buckets:Array<{key:string,status:string,score:number|null,rules:Array}>,
58
+ * pending:Array<{bucket:string,key:string,title:string,link:string,progress:number,mode:string}>,
59
+ * completed:number, raw:boolean}}
60
+ */
61
+ export function parsePerformance(raw) {
62
+ const doc = (raw && raw.performance) || raw || {}
63
+ const scoreRaw = doc.score
64
+ const score = scoreRaw == null || scoreRaw === '' ? null : Math.max(0, Math.min(100, num(scoreRaw)))
65
+ const bucketsIn = Array.isArray(doc.buckets) ? doc.buckets : []
66
+ const buckets = bucketsIn.map((b) => {
67
+ const rulesIn = Array.isArray(b && b.rules) ? b.rules : []
68
+ return {
69
+ key: str(b && b.key),
70
+ status: str(b && b.status),
71
+ score: b && b.score != null ? num(b.score) : null,
72
+ rules: rulesIn.map((r) => ({
73
+ key: str(r && r.key),
74
+ status: str(r && r.status).toUpperCase(),
75
+ mode: str(r && r.mode).toUpperCase(),
76
+ progress: r && r.progress != null ? num(r.progress) : null,
77
+ title: ruleTitle(r),
78
+ link: ruleLink(r),
79
+ })),
80
+ }
81
+ })
82
+ const pending = []
83
+ let completed = 0
84
+ for (const b of buckets) {
85
+ for (const r of b.rules) {
86
+ if (r.status === 'COMPLETED') completed++
87
+ // 只把显式 PENDING 当待办;状态缺失 ⇒ 不猜(宁少报,不误报)
88
+ else if (r.status === 'PENDING') pending.push({ bucket: b.key, ...r })
89
+ }
90
+ }
91
+ return {
92
+ score,
93
+ level: str(doc.level).toLowerCase(),
94
+ levelWording: str(doc.level_wording) || str(doc.levelWording),
95
+ calculatedAt: str(doc.calculated_at),
96
+ buckets,
97
+ pending,
98
+ completed,
99
+ raw: true,
100
+ }
101
+ }
102
+
103
+ /** 纯函数:分数 → 等级 A/B/C/D + 是否达标(null 分 ⇒ unknown)。 */
104
+ export function gradeOf(score, thresholds = GRADE_THRESHOLDS) {
105
+ if (score == null) return { grade: 'unknown', ok: false }
106
+ if (score >= thresholds.a) return { grade: 'A', ok: true }
107
+ if (score >= thresholds.b) return { grade: 'B', ok: true }
108
+ if (score >= thresholds.c) return { grade: 'C', ok: false }
109
+ return { grade: 'D', ok: false }
110
+ }
111
+
112
+ /**
113
+ * 纯函数:待办 rules → 中文整改项(按 platform 的 mode 排优先级:WARNING 先于 OPPORTUNITY)。
114
+ * @returns {Array<{bucket:string,ruleKey:string,title:string,hint:string,link:string,priority:number,mode:string}>}
115
+ */
116
+ export function buildListingActions(perf) {
117
+ const list = (perf && perf.pending) || []
118
+ return list.map((r) => ({
119
+ bucket: r.bucket,
120
+ ruleKey: r.key,
121
+ title: r.title,
122
+ hint: RULE_HINTS[r.key] || '',
123
+ link: r.link,
124
+ mode: r.mode,
125
+ priority: r.mode === 'WARNING' ? 1 : 2,
126
+ })).sort((a, b) => a.priority - b.priority)
127
+ }
128
+
129
+ /**
130
+ * 纯函数:单商品体检结果(performance + 商品基础信息)→ 可渲染对象。
131
+ * @param {{id:string,title?:string,price?:number,status?:string,availableQuantity?:number,permalink?:string}} item
132
+ * @param {object} perfRaw `/item/{id}/performance` 原始响应(可为空 ⇒ 记为未取到)
133
+ */
134
+ export function auditOne(item, perfRaw) {
135
+ const perf = perfRaw ? parsePerformance(perfRaw) : null
136
+ const grade = gradeOf(perf ? perf.score : null)
137
+ return {
138
+ id: str(item && item.id),
139
+ title: str(item && item.title),
140
+ price: item && item.price != null ? num(item.price) : null,
141
+ status: str(item && item.status),
142
+ availableQuantity: item && item.availableQuantity != null ? num(item.availableQuantity) : null,
143
+ permalink: str(item && item.permalink),
144
+ score: perf ? perf.score : null,
145
+ level: perf ? perf.level : '',
146
+ levelWording: perf ? perf.levelWording : '',
147
+ grade: grade.grade,
148
+ ok: grade.ok,
149
+ pendingCount: perf ? perf.pending.length : 0,
150
+ actions: perf ? buildListingActions(perf) : [],
151
+ error: perf ? '' : '未取到质量分(接口失败或无权限)',
152
+ }
153
+ }
154
+
155
+ /** 纯函数:汇总(平均分只统计拿到分的商品,避免"未取到"把均值拉低成假象)。 */
156
+ export function summarizeAudits(audits = []) {
157
+ const scored = audits.filter((a) => a && a.score != null)
158
+ const grades = { A: 0, B: 0, C: 0, D: 0, unknown: 0 }
159
+ for (const a of audits) grades[a.grade] = (grades[a.grade] || 0) + 1
160
+ const avg = scored.length ? round1(scored.reduce((s, a) => s + a.score, 0) / scored.length) : null
161
+ const byBucket = {}
162
+ for (const a of audits) for (const act of a.actions || []) byBucket[act.bucket] = (byBucket[act.bucket] || 0) + 1
163
+ return {
164
+ count: audits.length,
165
+ scored: scored.length,
166
+ avg,
167
+ grades,
168
+ pendingTotal: audits.reduce((s, a) => s + (a.pendingCount || 0), 0),
169
+ byBucket,
170
+ }
171
+ }
172
+
173
+ /**
174
+ * 只读取数:按店铺在售商品抽样 → 批量取商品信息 → 逐个拉质量分。
175
+ * @param {{apiGet:Function, token:string, site:string, uid:string, limit?:number, batchSize?:number, offset?:number}} p
176
+ */
177
+ export async function runListingAudit({ apiGet, token, site, uid, limit = 20, batchSize = 20, offset = 0 }) {
178
+ if (typeof apiGet !== 'function') throw new Error('runListingAudit 需要注入 apiGet')
179
+ if (!uid) throw new Error('runListingAudit 需要 uid(店铺 user_id)')
180
+ const cap = Math.max(1, Math.min(200, num(limit) || 20))
181
+
182
+ // 1) 在售商品 id 列表(分页,直到凑够 cap)
183
+ const ids = []
184
+ let pageOffset = Math.max(0, num(offset))
185
+ for (let page = 0; page < 20 && ids.length < cap; page++) {
186
+ const r = await apiGet(`/users/${uid}/items/search?status=active&limit=50&offset=${pageOffset}`, token)
187
+ const rows = (r && (r.results || r.item_ids)) || []
188
+ if (!rows.length) break
189
+ for (const id of rows) { if (ids.length < cap) ids.push(String(id)) }
190
+ const total = (r && r.paging && r.paging.total) ?? null
191
+ pageOffset += rows.length
192
+ if (total != null && pageOffset >= total) break
193
+ }
194
+ if (!ids.length) return { site, items: [], summary: summarizeAudits([]), note: '没有在售商品' }
195
+
196
+ // 2) 商品基础信息(批量,最多 batchSize/次)
197
+ const info = {}
198
+ for (let i = 0; i < ids.length; i += batchSize) {
199
+ const chunk = ids.slice(i, i + batchSize)
200
+ // ⚠️ `ids` 逗号必须裸写:URL-encoded 的 `%2C` 会被平台判 ResourceDeprecated(403)——
201
+ // 2026-11-24 本机实测(`/items?ids=MLM1%2CMLM2` ⇒ 403;裸逗号 ⇒ 200)。
202
+ const attrs = 'id,title,price,status,available_quantity,permalink'
203
+ // 2026-12-01:`/items?ids=` 可能被平台弃用(403 ResourceDeprecated)⇒ 批量优先 + 单条兜底
204
+ const rows = await fetchItemsBatched({ apiGet, token, ids: chunk, attrs, batchSize })
205
+ for (const row of rows) {
206
+ const b = row && row.body
207
+ if (b && b.id) info[String(b.id)] = b
208
+ }
209
+ }
210
+
211
+ // 3) 逐个拉质量分(单 item 接口,无批量端点 ⇒ 限上限,防把配额打满)
212
+ const items = []
213
+ for (const id of ids) {
214
+ const b = info[id] || { id }
215
+ let perfRaw = null
216
+ let err = ''
217
+ try {
218
+ perfRaw = await apiGet(`/item/${encodeURIComponent(id)}/performance`, token)
219
+ } catch (e) {
220
+ err = String(e.message || e).slice(0, 160)
221
+ }
222
+ const a = auditOne({
223
+ id,
224
+ title: b.title,
225
+ price: b.price,
226
+ status: b.status,
227
+ availableQuantity: b.available_quantity,
228
+ permalink: b.permalink,
229
+ }, perfRaw)
230
+ if (err) a.error = `质量分取数失败:${err}`
231
+ items.push(a)
232
+ }
233
+ return { site, items, summary: summarizeAudits(items) }
234
+ }
235
+
236
+ /**
237
+ * 纯函数:把一次体检渲染成中文卡片行(日报分区 / 角色回复 / CLI 共用)。
238
+ * @param {{site?:string, store?:string, items?:Array, summary?:object}} audit
239
+ * @param {{currency?:string, topN?:number}} opts
240
+ */
241
+ export function listingCardLines(audit, opts = {}) {
242
+ const s = (audit && audit.summary) || summarizeAudits((audit && audit.items) || [])
243
+ const out = []
244
+ const head = [audit && audit.store ? audit.store : '', audit && audit.site ? `(${audit.site})` : ''].join('')
245
+ out.push(`**🩺 Listing 体检**${head ? ':' + head : ''}(抽查 ${s.count} 个在售)`)
246
+ if (!s.count) { out.push('未取到在售商品(或在售为 0)'); return out }
247
+ const gradeLine = `A ${s.grades.A} · B ${s.grades.B} · C ${s.grades.C} · D ${s.grades.D}` + (s.grades.unknown ? ` · 未评分 ${s.grades.unknown}` : '')
248
+ out.push(`平均分 ${s.avg == null ? '—' : s.avg}(已评分 ${s.scored} 个)· ${gradeLine} · 待办 ${s.pendingTotal} 项`)
249
+ const worst = [...(audit.items || [])]
250
+ .filter((x) => x.score != null)
251
+ .sort((a, b) => a.score - b.score)
252
+ .slice(0, Math.max(1, num(opts.topN) || 3))
253
+ for (const it of worst) {
254
+ const g = { A: '🟢', B: '🟡', C: '🟠', D: '🔴', unknown: '⚪' }[it.grade] || '⚪'
255
+ const top = (it.actions || []).slice(0, 2).map((a) => a.hint || a.title).filter(Boolean)
256
+ out.push(`${g} ${it.id}${it.title ? '「' + it.title.slice(0, 28) + '」' : ''} ${it.score} 分 · 待办 ${it.pendingCount}${top.length ? ' → ' + top.join(';') : ''}`)
257
+ }
258
+ const errCount = (audit.items || []).filter((x) => x.error).length
259
+ if (errCount) out.push(`⚠️ ${errCount} 个商品未取到质量分(接口失败或无权限),已跳过不计入均分`)
260
+ return out
261
+ }
262
+
263
+ /**
264
+ * 纯函数:一次体检结果 → ERP 上报 body(字段名是与 whyshu-svr 端点的**契约**,⛔ 不要改名)。
265
+ * 端点:POST /api/argent/v1/tenants/:appId/reports/listing/bridge(header `x-appointment-secret`)。
266
+ * @param {{store?:string, site?:string, items?:Array, summary?:object}} row
267
+ * @param {{limit?:number, offset?:number, capturedAt?:string}} opts
268
+ */
269
+ export function buildListingBridgePayload(row, opts = {}) {
270
+ const items = (row && row.items) || []
271
+ return {
272
+ store: str(row && row.store),
273
+ site: str(row && row.site),
274
+ capturedAt: str(opts.capturedAt) || new Date().toISOString(),
275
+ limit: opts.limit == null ? null : num(opts.limit),
276
+ offset: opts.offset == null ? null : num(opts.offset),
277
+ summary: (row && row.summary) || summarizeAudits(items),
278
+ items: items.map((it) => ({
279
+ id: str(it && it.id),
280
+ title: str(it && it.title),
281
+ price: it && it.price != null ? num(it.price) : null,
282
+ status: str(it && it.status),
283
+ availableQuantity: it && it.availableQuantity != null ? num(it.availableQuantity) : null,
284
+ permalink: str(it && it.permalink),
285
+ score: it && it.score != null ? num(it.score) : null,
286
+ level: str(it && it.level),
287
+ levelWording: str(it && it.levelWording),
288
+ grade: str(it && it.grade),
289
+ ok: Boolean(it && it.ok),
290
+ pendingCount: num(it && it.pendingCount),
291
+ actions: ((it && it.actions) || []).map((a) => ({
292
+ bucket: str(a && a.bucket),
293
+ ruleKey: str(a && a.ruleKey),
294
+ title: str(a && a.title),
295
+ hint: str(a && a.hint),
296
+ link: str(a && a.link),
297
+ mode: str(a && a.mode),
298
+ priority: num(a && a.priority),
299
+ })),
300
+ error: str(it && it.error),
301
+ })),
302
+ }
303
+ }
304
+
305
+ /**
306
+ * POST 一次上报。注入 `fetchImpl` 便于离线测试;网络/HTTP 失败一律返回 `{ok:false,error}`,不抛。
307
+ * @param {object} payload buildListingBridgePayload 的产物
308
+ * @param {{base?:string, tenant?:string, secret?:string, fetchImpl?:Function, timeoutMs?:number}} opts
309
+ */
310
+ export async function pushListingReport(payload, opts = {}) {
311
+ const base = str(opts.base)
312
+ const tenant = str(opts.tenant)
313
+ const secret = str(opts.secret)
314
+ const fetchImpl = opts.fetchImpl || globalThis.fetch
315
+ const machineToken = String(opts.machineToken || '')
316
+ if (!base) throw new Error('push 需要 ERP 地址:--api 或 ARGENT_API_BASE')
317
+ if (!tenant) throw new Error('push 需要租户 appId:--tenant 或 ARGENT_TENANT')
318
+ if (!machineToken && !secret) throw new Error('push 需要机器令牌(agent-report.json#machineToken)或上报密钥 DAILY_REPORT_BRIDGE_SECRET')
319
+ if (typeof fetchImpl !== 'function') throw new Error('push 需要 fetch 实现')
320
+ const url = `${base.replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(tenant)}/reports/listing/bridge`
321
+ const ctl = typeof AbortController === 'function' ? new AbortController() : null
322
+ const timer = ctl ? setTimeout(() => ctl.abort(), Math.max(1000, num(opts.timeoutMs) || 15000)) : null
323
+ try {
324
+ const res = await fetchImpl(url, {
325
+ method: 'POST',
326
+ headers: {
327
+ 'content-type': 'application/json',
328
+ ...(machineToken ? { authorization: `Bearer ${machineToken}` } : {}),
329
+ ...(secret ? { 'x-appointment-secret': secret } : {}),
330
+ },
331
+ body: JSON.stringify(payload),
332
+ signal: ctl ? ctl.signal : undefined,
333
+ })
334
+ const body = await res.json().catch(() => ({}))
335
+ if (!res.ok) return { ok: false, status: res.status, error: `HTTP ${res.status} ${JSON.stringify(body).slice(0, 200)}` }
336
+ return { ok: true, status: res.status, data: body }
337
+ } catch (e) {
338
+ return { ok: false, status: 0, error: String((e && e.message) || e) }
339
+ } finally {
340
+ if (timer) clearTimeout(timer)
341
+ }
342
+ }