@whyshu/argent-engine 0.8.0-rc.3 → 0.8.0-rc.5
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/MANIFEST.json +36 -20
- package/engine/VERSION +1 -1
- package/engine/core/contracts/argent.contracts.json +1 -1
- package/engine/scripts/argent-doctor.mjs +34 -1
- package/engine/scripts/argent-schedule.mjs +6 -0
- package/engine/scripts/build-engine-package.mjs +1 -1
- package/engine/scripts/capability-packs.lock.json +36 -36
- package/engine/scripts/check-argent-desktop.mjs +91 -0
- package/engine/scripts/daily-report-run.sh +68 -0
- package/engine/scripts/daily-report-status.mjs +130 -0
- package/engine/scripts/daily-report-timer-plist.sh +89 -0
- package/engine/scripts/daily-report-timers.sh +162 -0
- package/engine/scripts/daily-report.mjs +79 -4
- package/engine/scripts/erp_invoice_shadow.py +62 -0
- package/engine/scripts/erp_invoice_writeback.py +93 -0
- package/engine/scripts/flow-requirements.json +3 -3
- package/engine/scripts/flow-timers.sh +11 -0
- package/engine/scripts/flow_config.py +14 -0
- package/engine/scripts/flow_source.py +10 -1
- package/engine/scripts/flow_sources/__init__.py +1 -0
- package/engine/scripts/flow_sources/erp.py +54 -0
- package/engine/scripts/huangwei-preflight.sh +42 -0
- package/engine/scripts/invoice_lip_runner.py +43 -0
- package/engine/scripts/lib/daily-report-status.mjs +227 -0
- package/engine/scripts/lib/plugin-packages.mjs +3 -0
- package/engine/scripts/orchestrator.py +173 -5
- package/engine/scripts/orchestrator_br.py +89 -1
- package/engine/scripts/publish-release-0.8.0-rc.4.sh +18 -0
- package/engine/scripts/query_runner.py +2 -3
- package/engine/scripts/release-gate-0.8.mjs +1 -0
- package/engine/scripts/skuflow_invoice_runner.py +145 -0
- package/engine/scripts/verify-release-0.8.0-rc.4.sh +16 -0
- package/engine/scripts/vertical-lint.mjs +19 -0
- package/engine/tools/agentic/README.md +95 -0
- package/engine/tools/agentic/mcp_server.py +212 -0
- package/engine/tools/agentic/ml_agent_tools.py +602 -0
- package/engine/version.mjs +1 -1
- package/engine/verticals/mercadolibre/flows.json +3 -1
- package/package.json +1 -1
|
@@ -45,6 +45,11 @@ import {
|
|
|
45
45
|
// 广告(Product Ads)只读取数/聚合/告警:与 `scripts/ml-ads.mjs` 共用同一份实现
|
|
46
46
|
// (⛔ 不在两处各写一份口径;2026-10-17 新增,默认关,客户开广告权限后再启用 `ads.summary`)
|
|
47
47
|
import { fetchAdsReport, adsCardLines } from './lib/ml-ads-core.mjs'
|
|
48
|
+
// 定时器状态(2026-10-30):日报改成 launchd 直跑确定性脚本后没有会话/台账可看 ⇒
|
|
49
|
+
// 每轮把「推了哪几家 / 下次几点 / 上次错误」落一份状态文件(桌宠 / doctor / CLI 读同一份)。
|
|
50
|
+
import {
|
|
51
|
+
computeStoreStates, mergeStatus, readStatus, summarizeStates, writeStatus,
|
|
52
|
+
} from './lib/daily-report-status.mjs'
|
|
48
53
|
|
|
49
54
|
// 逐字转出(既有调用方/单测 import 路径不变;同一绑定 ⇒ `M.aggregateOrders === core.aggregateOrders`)
|
|
50
55
|
export { aggregateOrders, localDateStr, tzOffsetMs, startOfLocalDayUTC, localHour, loadEnvFile }
|
|
@@ -1393,6 +1398,55 @@ export function collectMock(fixture) {
|
|
|
1393
1398
|
})
|
|
1394
1399
|
}
|
|
1395
1400
|
|
|
1401
|
+
// ── 定时器状态(2026-10-30)──────────────────────────────────
|
|
1402
|
+
// 只记**事实**:本轮推了哪些店、失败原因、下次该推时点(由标记文件推算)。
|
|
1403
|
+
// 状态写入**永不影响**推送结果(try/catch 兜住);--dry-run / --json / --mock / 列表模式不写。
|
|
1404
|
+
const STATUS_ACC = { pushed: [], failed: [], summary: '' }
|
|
1405
|
+
const STATUS_CTX = { stores: [], reportTime: '' }
|
|
1406
|
+
|
|
1407
|
+
function statusEnabled() {
|
|
1408
|
+
return !FLAG_DRY && !FLAG_JSON && !MOCK_FILE && !FLAG_LIST_SECTIONS && !FLAG_LIST_STORES
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
function finalizeStatus({ code = 0, startedAt = '', error = '' } = {}) {
|
|
1412
|
+
if (!statusEnabled()) return
|
|
1413
|
+
try {
|
|
1414
|
+
const now = new Date()
|
|
1415
|
+
const prev = readStatus(DATA_HOME)
|
|
1416
|
+
const patch = {
|
|
1417
|
+
updatedAt: now.toISOString(),
|
|
1418
|
+
lastRunAt: startedAt || prev.lastRunAt || now.toISOString(),
|
|
1419
|
+
lastFinishAt: now.toISOString(),
|
|
1420
|
+
lastExit: code,
|
|
1421
|
+
reportTime: STATUS_CTX.reportTime || prev.reportTime || '00:05',
|
|
1422
|
+
lastPushed: STATUS_ACC.pushed,
|
|
1423
|
+
failed: STATUS_ACC.failed,
|
|
1424
|
+
lastSummary: STATUS_ACC.summary || '',
|
|
1425
|
+
lastError: code === 0 ? '' : (error || STATUS_ACC.summary
|
|
1426
|
+
|| (STATUS_ACC.failed.length ? `${STATUS_ACC.failed.length} 家取数失败:${STATUS_ACC.failed[0].store}(${STATUS_ACC.failed[0].error})` : '')
|
|
1427
|
+
|| `exit ${code}`),
|
|
1428
|
+
}
|
|
1429
|
+
if (code === 0) patch.lastOkAt = now.toISOString()
|
|
1430
|
+
const pushedAt = STATUS_ACC.pushed.reduce((max, p) => (p.at > max ? p.at : max), '')
|
|
1431
|
+
if (pushedAt) patch.lastPushAt = pushedAt
|
|
1432
|
+
// 用 --store / --date 过滤的运行只记"推了什么",不重算全店派生面(否则会把其它店的状态写成空)
|
|
1433
|
+
if (STATUS_CTX.stores.length && !ARG_STORE.length) {
|
|
1434
|
+
const states = computeStoreStates({
|
|
1435
|
+
stores: STATUS_CTX.stores,
|
|
1436
|
+
cacheDir: cacheDir(),
|
|
1437
|
+
now,
|
|
1438
|
+
reportTime: patch.reportTime,
|
|
1439
|
+
})
|
|
1440
|
+
Object.assign(patch, summarizeStates(states))
|
|
1441
|
+
if (!patch.lastPushAt) patch.lastPushAt = prev.lastPushAt || ''
|
|
1442
|
+
if (!patch.pending) patch.pending = prev.pending || []
|
|
1443
|
+
}
|
|
1444
|
+
writeStatus(DATA_HOME, mergeStatus(prev, patch))
|
|
1445
|
+
} catch (e) {
|
|
1446
|
+
console.error(`⚠️ 定时器状态写入失败(不影响推送):${e.message}`)
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1396
1450
|
// ── 主流程 ─────────────────────────────────────────────────
|
|
1397
1451
|
async function main() {
|
|
1398
1452
|
// 进程 env 覆盖 env 文件(文件仍是部署基线;命令行临时覆盖用 process.env)
|
|
@@ -1417,6 +1471,7 @@ async function main() {
|
|
|
1417
1471
|
const now = ARG_ASOF ? new Date(ARG_ASOF) : new Date()
|
|
1418
1472
|
if (ARG_ASOF && Number.isNaN(now.getTime())) { console.error(`✗ --as-of 解析失败:${ARG_ASOF}`); return 1 }
|
|
1419
1473
|
const reportTime = pick(cfg, env, 'mlDailyTime', 'REPORT_TIME', '08:00')
|
|
1474
|
+
STATUS_CTX.reportTime = String(reportTime)
|
|
1420
1475
|
|
|
1421
1476
|
if (MOCK_FILE) {
|
|
1422
1477
|
const fixture = JSON.parse(readFileSync(MOCK_FILE, 'utf8'))
|
|
@@ -1437,6 +1492,8 @@ async function main() {
|
|
|
1437
1492
|
}
|
|
1438
1493
|
stores = stores.stores || []
|
|
1439
1494
|
STORE_LIST = stores // 供 token 轮换后原子写回(persistStores)
|
|
1495
|
+
// 定时器状态的派生面永远按**全量**店铺算(--store 过滤只影响本轮抓取,不影响"哪几家还没推")
|
|
1496
|
+
STATUS_CTX.stores = stores.slice()
|
|
1440
1497
|
if (FLAG_LIST_STORES) {
|
|
1441
1498
|
console.log(JSON.stringify({ stores: stores.map((x) => ({ name: x.name, site: x.site, user_id: String(x.user_id) })) }, null, 1))
|
|
1442
1499
|
return 0
|
|
@@ -1487,10 +1544,15 @@ async function main() {
|
|
|
1487
1544
|
})
|
|
1488
1545
|
}
|
|
1489
1546
|
}
|
|
1547
|
+
// 定时器状态:把本轮每店事实记下来(成功也记 —— "这轮跑了、某店取数失败"同样是状态)
|
|
1548
|
+
STATUS_ACC.failed = reports.filter((x) => !x.r.summary).map((x) => ({
|
|
1549
|
+
store: x.store.name, site: x.store.site, error: String(x.r.error || '采集失败').slice(0, 200),
|
|
1550
|
+
}))
|
|
1490
1551
|
|
|
1491
1552
|
const okReports = reports.filter((x) => x.r.summary)
|
|
1492
1553
|
if (!okReports.length) {
|
|
1493
1554
|
console.error('✗ 全部店铺采集失败,不推送')
|
|
1555
|
+
STATUS_ACC.summary = `全部店铺采集失败(${reports.length} 家)`
|
|
1494
1556
|
return 1
|
|
1495
1557
|
}
|
|
1496
1558
|
|
|
@@ -1593,10 +1655,16 @@ async function main() {
|
|
|
1593
1655
|
if (!FLAG_NO_MARK) {
|
|
1594
1656
|
for (const { store, r } of due) markPushed(r.date, store)
|
|
1595
1657
|
}
|
|
1658
|
+
const at = new Date().toISOString()
|
|
1659
|
+
STATUS_ACC.pushed = due.map(({ store, r }) => ({
|
|
1660
|
+
store: store.name, site: store.site, date: r.date, at,
|
|
1661
|
+
}))
|
|
1662
|
+
STATUS_ACC.summary = `已推送 ${due.length} 家(${channel})· ${dateLabel}`
|
|
1596
1663
|
console.log(`[daily-report] ✅ 日报已推送(${channel}):${title}(${due.length} 家店铺)${FLAG_NO_MARK ? '(--no-mark 未写幂等标记)' : ''}`)
|
|
1597
1664
|
return 0
|
|
1598
1665
|
} catch (err) {
|
|
1599
1666
|
console.error(`✗ 推送失败:${err.message}`)
|
|
1667
|
+
STATUS_ACC.summary = `推送失败:${String(err.message).slice(0, 160)}`
|
|
1600
1668
|
// KB-090:推送失败 → 飞书告警(webhook 优先/lark-bot 兜底/alert.log 落盘)
|
|
1601
1669
|
await notifyPushFailure(env, err).catch(() => {})
|
|
1602
1670
|
return 1
|
|
@@ -1606,8 +1674,15 @@ async function main() {
|
|
|
1606
1674
|
// 仅直接执行时跑主流程(import 单测时不触发)
|
|
1607
1675
|
const isMain = isDirectRun(import.meta.url)
|
|
1608
1676
|
if (isMain) {
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1677
|
+
const startedAt = new Date().toISOString()
|
|
1678
|
+
main()
|
|
1679
|
+
.then((code) => {
|
|
1680
|
+
finalizeStatus({ code: code === 0 ? 0 : 1, startedAt })
|
|
1681
|
+
process.exit(code)
|
|
1682
|
+
})
|
|
1683
|
+
.catch((err) => {
|
|
1684
|
+
console.error(`✗ 异常:${err.message}`)
|
|
1685
|
+
finalizeStatus({ code: 1, startedAt, error: `未捕获异常:${err.message}` })
|
|
1686
|
+
process.exit(1)
|
|
1687
|
+
})
|
|
1613
1688
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""发票写回 shadow:把「准备写到 lip 的字段/附件」映射成 ERP 契约并落 JSONL。
|
|
2
|
+
|
|
3
|
+
⛔ 本模块**不调用 ERP 写接口**、**不改客户状态**;只供 invoice_lip_runner 在
|
|
4
|
+
ARGENT_WRITEBACK=shadow 时记录“如果切 ERP 会写什么”,用于和 lip 结果比对。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
FIELD_MAP = {
|
|
14
|
+
'发票状态': 'invoiceStatus',
|
|
15
|
+
'发票错误信息': 'invoiceError',
|
|
16
|
+
'发票就绪': 'invoiceReady',
|
|
17
|
+
}
|
|
18
|
+
ATTACHMENT_MAP = {
|
|
19
|
+
'发票文件': 'invoiceFile',
|
|
20
|
+
'大货标签': 'bulkLabel',
|
|
21
|
+
'产品图': 'productImage',
|
|
22
|
+
'FULL标签文件': 'fullLabelFile',
|
|
23
|
+
'FULL箱唛文件': 'fullCartonFile',
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def to_erp_fields(patch: dict) -> tuple[dict, list]:
|
|
28
|
+
"""lip 中文 patch → ERP 字段;返回 (erp_fields, skipped)。"""
|
|
29
|
+
fields: dict = {}
|
|
30
|
+
skipped: list = []
|
|
31
|
+
for key, value in (patch or {}).items():
|
|
32
|
+
target = FIELD_MAP.get(key)
|
|
33
|
+
if target:
|
|
34
|
+
fields[target] = value
|
|
35
|
+
else:
|
|
36
|
+
skipped.append(key)
|
|
37
|
+
return fields, skipped
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def shadow_record(rids, patch=None, source: str = 'lip_update', attachments=None) -> dict:
|
|
41
|
+
fields, skipped = to_erp_fields(patch or {})
|
|
42
|
+
return {
|
|
43
|
+
'ts': time.strftime('%Y-%m-%dT%H:%M:%S'),
|
|
44
|
+
'mode': 'shadow',
|
|
45
|
+
'source': source,
|
|
46
|
+
'records': [str(x) for x in (rids or [])],
|
|
47
|
+
'erpFields': fields,
|
|
48
|
+
'skippedFields': skipped,
|
|
49
|
+
'attachments': [
|
|
50
|
+
{'field': ATTACHMENT_MAP.get(a.get('field'), a.get('field')), 'filename': a.get('filename', '')}
|
|
51
|
+
for a in (attachments or [])
|
|
52
|
+
],
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def append_shadow(record: dict, data_dir=None) -> Path:
|
|
57
|
+
base = Path(data_dir) if data_dir else Path(os.environ.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
|
|
58
|
+
path = base / 'invoice-lip-writes' / 'erp-shadow.jsonl'
|
|
59
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
with path.open('a', encoding='utf-8') as fh:
|
|
61
|
+
fh.write(json.dumps(record, ensure_ascii=False) + '\n')
|
|
62
|
+
return path
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""发票写回 ERP(ARGENT_WRITEBACK=erp):字段 + 附件引用。
|
|
2
|
+
|
|
3
|
+
⛔ 不打印 token;附件走 machine 上传端点(≤2MB),再把 attachment `_id` 同时作为
|
|
4
|
+
fileToken/attachmentId 传给 /agent-tasks/invoice-finalize(attachInvoiceFile 幂等)。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import json
|
|
10
|
+
import mimetypes
|
|
11
|
+
import os
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from erp_invoice_shadow import ATTACHMENT_MAP, to_erp_fields
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _config() -> dict:
|
|
20
|
+
env = os.environ
|
|
21
|
+
candidates = []
|
|
22
|
+
if env.get('ARGENT_AGENT_REPORT'):
|
|
23
|
+
candidates.append(Path(env['ARGENT_AGENT_REPORT']))
|
|
24
|
+
data_dir = Path(env.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
|
|
25
|
+
candidates += [data_dir / 'agent-report.json', Path.home() / '.dsh-argent' / 'argent' / 'agent-report.json']
|
|
26
|
+
for f in candidates:
|
|
27
|
+
try:
|
|
28
|
+
d = json.loads(f.read_text())
|
|
29
|
+
if d.get('serverUrl') and d.get('tenantAppId') and d.get('machineId') and d.get('machineToken'):
|
|
30
|
+
return d
|
|
31
|
+
except Exception:
|
|
32
|
+
continue
|
|
33
|
+
raise RuntimeError('ERP 写回:找不到 agent-report.json(serverUrl/tenantAppId/machineId/machineToken)')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _post(path: str, body: dict) -> tuple[int, dict]:
|
|
37
|
+
cfg = _config()
|
|
38
|
+
url = f"{str(cfg['serverUrl']).rstrip('/')}{path}"
|
|
39
|
+
req = urllib.request.Request(url, data=json.dumps(body, ensure_ascii=False).encode('utf-8'), method='POST',
|
|
40
|
+
headers={'content-type': 'application/json', 'authorization': f"Bearer {cfg['machineToken']}"})
|
|
41
|
+
try:
|
|
42
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
43
|
+
raw = resp.read().decode('utf-8', errors='replace')
|
|
44
|
+
return resp.status, (json.loads(raw) if raw else {})
|
|
45
|
+
except urllib.error.HTTPError as e:
|
|
46
|
+
raw = e.read().decode('utf-8', errors='replace')
|
|
47
|
+
try:
|
|
48
|
+
return e.code, json.loads(raw)
|
|
49
|
+
except Exception:
|
|
50
|
+
return e.code, {'ok': False, 'error': {'code': 'http_error', 'message': raw[:500]}}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def upload_attachment(path) -> dict:
|
|
54
|
+
p = Path(path)
|
|
55
|
+
data = base64.b64encode(p.read_bytes()).decode('ascii')
|
|
56
|
+
mime = mimetypes.guess_type(p.name)[0] or 'application/octet-stream'
|
|
57
|
+
cfg = _config()
|
|
58
|
+
status, doc = _post(f"/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/attachments", {
|
|
59
|
+
'filename': p.name, 'mime': mime, 'dataBase64': data, 'kind': 'invoice-file',
|
|
60
|
+
})
|
|
61
|
+
att = (doc.get('data') or {}).get('attachment') or {}
|
|
62
|
+
if not doc.get('ok') or not att.get('_id'):
|
|
63
|
+
raise RuntimeError(f"ERP 附件上传失败(HTTP {status}):{(doc.get('error') or {}).get('message') or doc}")
|
|
64
|
+
return {
|
|
65
|
+
'attachmentId': str(att['_id']), 'fileToken': str(att['_id']),
|
|
66
|
+
'filename': att.get('filename') or p.name, 'mime': att.get('mime') or mime,
|
|
67
|
+
'size': att.get('size') if isinstance(att.get('size'), int) else p.stat().st_size,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def finalize(record_id: str, fields: dict, attachments: list) -> bool:
|
|
72
|
+
cfg = _config()
|
|
73
|
+
body = {'sourceRecordId': str(record_id), 'fields': fields or {}, 'attachments': attachments or []}
|
|
74
|
+
status, doc = _post(f"/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/agent-tasks/invoice-finalize", body)
|
|
75
|
+
return bool(doc.get('ok')), status, doc
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def write_fields(rids, patch) -> bool:
|
|
79
|
+
fields, _skipped = to_erp_fields(patch or {})
|
|
80
|
+
if not fields:
|
|
81
|
+
return True
|
|
82
|
+
for rid in rids or []:
|
|
83
|
+
ok, _status, _doc = finalize(rid, fields, [])
|
|
84
|
+
if not ok:
|
|
85
|
+
return False
|
|
86
|
+
return True
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def upload_and_finalize(rid, field, path) -> bool:
|
|
90
|
+
att = upload_attachment(path)
|
|
91
|
+
erp_field = ATTACHMENT_MAP.get(field, field)
|
|
92
|
+
ok, _status, _doc = finalize(rid, {}, [{**att, 'field': erp_field}])
|
|
93
|
+
return ok
|
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
},
|
|
158
158
|
"minPlan": "enterprise",
|
|
159
159
|
"pack": {
|
|
160
|
-
"version": "1.2.
|
|
160
|
+
"version": "1.2.190",
|
|
161
161
|
"scripts": [
|
|
162
162
|
"scripts/wenyao-invoice-writeback.mjs",
|
|
163
163
|
"scripts/invoice_lip_runner.py",
|
|
@@ -260,7 +260,7 @@
|
|
|
260
260
|
],
|
|
261
261
|
"minPlan": "enterprise",
|
|
262
262
|
"pack": {
|
|
263
|
-
"version": "1.3.
|
|
263
|
+
"version": "1.3.196",
|
|
264
264
|
"scripts": [
|
|
265
265
|
"scripts/poll-fulfillment.sh",
|
|
266
266
|
"scripts/orchestrator.py",
|
|
@@ -340,7 +340,7 @@
|
|
|
340
340
|
"minPlan": "pro",
|
|
341
341
|
"_minPlanNote": "**2026-10-09(变现分层落地)**:`enterprise` → **`pro`**。判据 = 用户已确认的产品模型「分界线 = **价值更高 / 风险更高 ⇒ 企业版**」:日报是**只读**能力(官方 API 只读查询 + 生成推送,⛔ 不写客户任何系统、⛔ 不动浏览器),与 `full`(箱唛/写操作)、`invoice`(发票/门户写操作)不同档 ⇒ 归 **Pro**。⛔ 只改**档位下限**,⛔ 不改流程行为、⛔ 不改价格口径;`daily-report` 的能力包版本随引擎前进(见 pack.version)。已装机器**不因本改动被卸载/停用**(缩权只影响后续下发,见 entitlements.plans._why 与 docs 策划案 §4.4)。",
|
|
342
342
|
"pack": {
|
|
343
|
-
"version": "1.1.
|
|
343
|
+
"version": "1.1.187",
|
|
344
344
|
"scripts": [
|
|
345
345
|
"scripts/daily-report.mjs",
|
|
346
346
|
"scripts/daily-report.sh",
|
|
@@ -84,6 +84,11 @@ usage() { sed -n '2,26p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; }
|
|
|
84
84
|
|
|
85
85
|
cfg() { "$PY" "$REPO/scripts/flow_config.py" --flow "$1" --get "$2"; }
|
|
86
86
|
|
|
87
|
+
# 交付方式(2026-10-30):`launchd-script` 的流程由确定性脚本定时器接管(日报),
|
|
88
|
+
# 本安装器**不装**它的唤醒触发器(单一调度者纪律)—— 声明面仍是注册表 trigger.delivery。
|
|
89
|
+
delivery_of() { cfg "$1" trigger.delivery 2>/dev/null || true; }
|
|
90
|
+
is_script_delivered() { [ "$(delivery_of "$1")" = "launchd-script" ]; }
|
|
91
|
+
|
|
87
92
|
flows_arg() { # 解析 --flow/--all
|
|
88
93
|
local out=() all=0
|
|
89
94
|
while [ $# -gt 0 ]; do
|
|
@@ -135,6 +140,7 @@ cmd_status() {
|
|
|
135
140
|
while IFS= read -r f; do
|
|
136
141
|
[ -n "$f" ] || continue
|
|
137
142
|
local p; p="$(cfg "$f" paths.pauseSwitch 2>/dev/null || echo '?')"
|
|
143
|
+
if is_script_delivered "$f"; then echo " 🕒 ${f}:由确定性脚本定时器调度(launchd-script;不看本安装器的 plist)"; continue; fi
|
|
138
144
|
if [ -f "$p" ]; then echo " ⏸ ${f}:已暂停(${p})"; else echo " ▶️ ${f}:未暂停"; fi
|
|
139
145
|
done < <(flows_arg --all)
|
|
140
146
|
}
|
|
@@ -145,6 +151,11 @@ cmd_install() {
|
|
|
145
151
|
while IFS= read -r f; do
|
|
146
152
|
[ -n "$f" ] || continue
|
|
147
153
|
local label plist ins
|
|
154
|
+
if is_script_delivered "$f"; then
|
|
155
|
+
echo " ⏭ ${f}:交付方式=launchd-script(确定性脚本定时器),flow-timers 不装它的唤醒触发器" >&2
|
|
156
|
+
echo " 装法:bash $REPO/scripts/daily-report-timers.sh install(⛔ 与唤醒触发器二选一)" >&2
|
|
157
|
+
continue
|
|
158
|
+
fi
|
|
148
159
|
label="$LABEL_PREFIX-$f"; plist="$AGENTS/$label.plist"
|
|
149
160
|
if ! ins="$(gen_plist "$f")"; then
|
|
150
161
|
echo "❌ ${f}:生成 plist 失败(见上面那句)⇒ 本轮跳过这一条(⛔ 不写半成品 plist)" >&2
|
|
@@ -81,6 +81,12 @@ DEFAULTS = {
|
|
|
81
81
|
'autoRetry': {'enabled': True, 'max': 2, 'cooldownMin': 20, 'perCycle': 2},
|
|
82
82
|
}
|
|
83
83
|
WAKE_MODES = ('session', 'off')
|
|
84
|
+
# 交付方式(2026-10-30):这条流程的定时**谁在跑**。
|
|
85
|
+
# · session(缺省)= 激活垫片唤醒角色会话(flow-trigger.sh);
|
|
86
|
+
# · launchd-script = launchd 直跑确定性脚本(日报;`scripts/daily-report-timers.sh`),
|
|
87
|
+
# ⛔ 不进 flow-timers 安装面、⛔ 不许同时启用宿主排程(单一调度者)。
|
|
88
|
+
# 声明面唯一:`verticals/<id>/flows.json#trigger.delivery`;本文件是运行期唯一读取点。
|
|
89
|
+
DELIVERY_MODES = ('session', 'launchd-script')
|
|
84
90
|
# 本轮语义:real=真实写入生产;shadow=只读/零副作用(缺省 shadow —— 不宣称真实写入)
|
|
85
91
|
WRITE_MODES = ('real', 'shadow')
|
|
86
92
|
|
|
@@ -850,6 +856,12 @@ def load_config(flow_id: str, registry=None, registry_path=None, strict: bool =
|
|
|
850
856
|
if wake not in WAKE_MODES:
|
|
851
857
|
die(f'流程 {flow_id} 的 trigger.wake 非法: {wake}(可选: {", ".join(WAKE_MODES)})')
|
|
852
858
|
|
|
859
|
+
# 交付方式:只声明了才出现(未迁移的流程 cfg 形状逐字不变)
|
|
860
|
+
if raw_t.get('delivery') is not None:
|
|
861
|
+
delivery = str(raw_t.get('delivery'))
|
|
862
|
+
if delivery not in DELIVERY_MODES:
|
|
863
|
+
die(f'流程 {flow_id} 的 trigger.delivery 非法: {delivery}(可选: {", ".join(DELIVERY_MODES)})')
|
|
864
|
+
|
|
853
865
|
# 2026-09-18:本轮**是否真实写入**必须来自注册表 —— 此前 flow-trigger.sh / flow-trigger-wake.mjs
|
|
854
866
|
# 把「影子模式」写死在日志里,FULL 已转真实运行后日志仍在说"影子模式"(误导操作者)。
|
|
855
867
|
# 保守默认 shadow:注册表没写 mode 的流程,日志一律按影子播报,绝不宣称真实写入。
|
|
@@ -871,6 +883,8 @@ def load_config(flow_id: str, registry=None, registry_path=None, strict: bool =
|
|
|
871
883
|
# (首版就踩了:paths 里读不到 pauseSwitchLegacy ⇒ 兜底形同虚设)
|
|
872
884
|
if raw_t.get('pauseSwitchLegacy'):
|
|
873
885
|
trigger['pauseSwitchLegacy'] = str(raw_t['pauseSwitchLegacy'])
|
|
886
|
+
if raw_t.get('delivery') is not None:
|
|
887
|
+
trigger['delivery'] = str(raw_t['delivery'])
|
|
874
888
|
# P1-A(2026-10-12):宿主排程声明(只声明了才出现这个键 —— 未迁移的流程 cfg 形状**逐字不变**)
|
|
875
889
|
schedule = resolve_schedule(canonical, spec, strict)
|
|
876
890
|
if schedule:
|
|
@@ -62,6 +62,8 @@ SOURCES: dict = {
|
|
|
62
62
|
'cases-json': {'needs_args': ('--from-json 或 source.file',), 'registry_driven': True,
|
|
63
63
|
'module': 'flow_sources.cases_json',
|
|
64
64
|
'note': '批量清单文件(生成器产出的待处理单元;日报走这条)'},
|
|
65
|
+
'erp': {'needs_args': (), 'registry_driven': True, 'module': 'flow_sources.erp',
|
|
66
|
+
'note': 'ERP Shipment/Invoice 只读数据面(0.8 去 lip Phase 2;machine token 只读)'},
|
|
65
67
|
'cli-json': {'needs_args': ('--ticket', '--fields-from-json'), 'registry_driven': False, 'inline': True,
|
|
66
68
|
'note': '手工/外部喂字段(会话与排障用)'},
|
|
67
69
|
'conversation': {'needs_args': ('--ticket', '--fields-from-json'), 'registry_driven': False, 'inline': True,
|
|
@@ -100,7 +102,14 @@ def _assert_kinds_aligned() -> None:
|
|
|
100
102
|
|
|
101
103
|
|
|
102
104
|
def declared_kind(spec: dict) -> str:
|
|
103
|
-
"""该流程在注册表里声明的数据面(`source.kind`),缺省 feishu-base(历史行为)。
|
|
105
|
+
"""该流程在注册表里声明的数据面(`source.kind`),缺省 feishu-base(历史行为)。
|
|
106
|
+
|
|
107
|
+
0.8 去 lip 过渡开关:ARGENT_FLOW_SOURCE=erp 时,所有流程统一改走 ERP source
|
|
108
|
+
(字段名由适配器保持 lip 兼容),用于先灰度、再删除 lip 源。
|
|
109
|
+
"""
|
|
110
|
+
override = os.environ.get('ARGENT_FLOW_SOURCE', '').strip()
|
|
111
|
+
if override:
|
|
112
|
+
return override
|
|
104
113
|
return str((spec.get('source') or {}).get('kind') or 'feishu-base')
|
|
105
114
|
|
|
106
115
|
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""ERP 数据面(0.8 去 lip,Phase 2)。
|
|
2
|
+
|
|
3
|
+
从 ERP 机器只读接口拉取 Shipment/Invoice 并映射成旧流程认识的字段;
|
|
4
|
+
不再读 lip 表。身份 = 本机 agent-report.json 的 machine token。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import urllib.request
|
|
11
|
+
import urllib.error
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
KIND = 'erp'
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _config() -> dict:
|
|
18
|
+
env = os.environ
|
|
19
|
+
candidates = []
|
|
20
|
+
if env.get('ARGENT_AGENT_REPORT'):
|
|
21
|
+
candidates.append(Path(env['ARGENT_AGENT_REPORT']))
|
|
22
|
+
data_dir = Path(env.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
|
|
23
|
+
candidates += [data_dir / 'agent-report.json', Path.home() / '.dsh-argent' / 'argent' / 'agent-report.json']
|
|
24
|
+
for f in candidates:
|
|
25
|
+
try:
|
|
26
|
+
d = json.loads(f.read_text())
|
|
27
|
+
if d.get('serverUrl') and d.get('tenantAppId') and d.get('machineId') and d.get('machineToken'):
|
|
28
|
+
return d
|
|
29
|
+
except Exception:
|
|
30
|
+
continue
|
|
31
|
+
return {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def pull(spec, args):
|
|
35
|
+
cfg = _config()
|
|
36
|
+
if not cfg:
|
|
37
|
+
raise SystemExit('ERP source:找不到 agent-report.json(serverUrl/tenantAppId/machineId/machineToken)')
|
|
38
|
+
base = str(cfg['serverUrl']).rstrip('/')
|
|
39
|
+
url = f"{base}/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/erp-source?limit=5000"
|
|
40
|
+
req = urllib.request.Request(url, headers={'authorization': f"Bearer {cfg['machineToken']}"})
|
|
41
|
+
try:
|
|
42
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
43
|
+
doc = json.loads(resp.read().decode('utf-8', errors='replace') or '{}')
|
|
44
|
+
except urllib.error.HTTPError as e:
|
|
45
|
+
raise SystemExit(f'ERP source HTTP {e.code}: {e.read().decode("utf-8", errors="replace")[:500]}')
|
|
46
|
+
except Exception as e:
|
|
47
|
+
raise SystemExit(f'ERP source 不可达:{e}')
|
|
48
|
+
items = (doc.get('data') or {}).get('items') or []
|
|
49
|
+
out = []
|
|
50
|
+
for it in items:
|
|
51
|
+
rid = str(it.get('recordId') or (it.get('fields') or {}).get('recordId') or '')
|
|
52
|
+
if rid:
|
|
53
|
+
out.append((rid, it.get('fields') or {}))
|
|
54
|
+
return out
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Huangwei Mac 迁移前只读体检(不修改/不停止/不安装任何东西)
|
|
3
|
+
set -u
|
|
4
|
+
echo "=== Huangwei preflight $(date -Is) ==="
|
|
5
|
+
echo "host: $(hostname) / $(uname -m) / $(sw_vers -productVersion 2>/dev/null || true)"
|
|
6
|
+
echo
|
|
7
|
+
echo "--- DSH Desktop / web ---"
|
|
8
|
+
ls -ld "/Applications/DeepSeek Harness.app" 2>/dev/null || echo "no /Applications/DeepSeek Harness.app"
|
|
9
|
+
pgrep -fl "DeepSeek Harness|dsh web|dsh-web" 2>/dev/null | head -20 || true
|
|
10
|
+
echo "--- launch agents ---"
|
|
11
|
+
launchctl list 2>/dev/null | grep -iE 'dsh|argent|whyshu' | head -30 || true
|
|
12
|
+
echo
|
|
13
|
+
echo "--- dsh version ---"
|
|
14
|
+
command -v dsh >/dev/null && dsh --version 2>&1 | head -3 || echo "dsh not in PATH"
|
|
15
|
+
echo
|
|
16
|
+
echo "--- argent data identity (no token) ---"
|
|
17
|
+
python3 - <<'PY' 2>/dev/null || true
|
|
18
|
+
import json, os
|
|
19
|
+
p=os.path.expanduser('~/.dsh/argent/agent-report.json')
|
|
20
|
+
try:
|
|
21
|
+
d=json.load(open(p))
|
|
22
|
+
print('agent-report:', {k:d.get(k) for k in ('enabled','serverUrl','tenantAppId','machineId','machineName','chatEnabled')})
|
|
23
|
+
except Exception as e:
|
|
24
|
+
print('agent-report: missing/invalid', type(e).__name__)
|
|
25
|
+
PY
|
|
26
|
+
echo
|
|
27
|
+
echo "--- desktop profile packages ---"
|
|
28
|
+
python3 - <<'PY' 2>/dev/null || true
|
|
29
|
+
import json, os
|
|
30
|
+
p=os.path.expanduser('~/.dsh/profiles/desktop/package.json')
|
|
31
|
+
try:
|
|
32
|
+
d=json.load(open(p)); print('profile:', {k:d.get(k) for k in ('name','version')}); print('deps:', d.get('dependencies') or {})
|
|
33
|
+
except Exception as e:
|
|
34
|
+
print('profile: missing/invalid', type(e).__name__)
|
|
35
|
+
PY
|
|
36
|
+
echo
|
|
37
|
+
echo "--- global argent packages ---"
|
|
38
|
+
npm ls -g --depth=0 @whyshu 2>/dev/null | head -20 || true
|
|
39
|
+
echo
|
|
40
|
+
echo "--- installed engine/runtime ---"
|
|
41
|
+
ls -ld ~/.dsh/argent/engines/* 2>/dev/null | tail -10 || true
|
|
42
|
+
echo "READ-ONLY: nothing was changed."
|
|
@@ -74,6 +74,14 @@ def _load_env():
|
|
|
74
74
|
|
|
75
75
|
_load_env()
|
|
76
76
|
# lark-cli shebang「/usr/bin/env node」需 node 在 PATH(launchd/ssh 最小 PATH 兼容)
|
|
77
|
+
try:
|
|
78
|
+
from erp_invoice_shadow import shadow_record, append_shadow # noqa: E402
|
|
79
|
+
except Exception: # 半坏机器/旧包没有该模块时只关闭 shadow,不影响 lip
|
|
80
|
+
shadow_record = append_shadow = None
|
|
81
|
+
try:
|
|
82
|
+
from erp_invoice_writeback import write_fields as erp_write_fields, upload_and_finalize as erp_upload_and_finalize # noqa: E402
|
|
83
|
+
except Exception: # ERP 写回模块缺失时只在 erp 模式报错
|
|
84
|
+
erp_write_fields = erp_upload_and_finalize = None
|
|
77
85
|
_EXTRA_PATH = [p for p in (f"{HOME}/.local/bin", f"{HOME}/node/bin",
|
|
78
86
|
"/opt/homebrew/bin", "/usr/local/bin")
|
|
79
87
|
if p not in (os.environ.get("PATH") or "").split(":")]
|
|
@@ -97,6 +105,9 @@ F_HS = "HS编码"
|
|
|
97
105
|
F_MAT = "材质"
|
|
98
106
|
F_FILE = "发票文件"
|
|
99
107
|
F_LABEL = "大货标签"
|
|
108
|
+
|
|
109
|
+
def _writeback_mode() -> str:
|
|
110
|
+
return (os.environ.get("ARGENT_WRITEBACK") or "lip").strip().lower()
|
|
100
111
|
F_ERR = "发票错误信息"
|
|
101
112
|
F_FULL_ST = "FULL状态"
|
|
102
113
|
F_SKU = "SKU"
|
|
@@ -351,6 +362,22 @@ def lip_update(rids, patch):
|
|
|
351
362
|
_audit_write(rids, patch, False, f"越界字段: {bad}")
|
|
352
363
|
raise SystemExit(f"❌ 拒绝写回:{bad} 不在发票字段白名单 {sorted(WRITE_FIELDS)} 内"
|
|
353
364
|
f"(只允许改发票相关字段,其余字段由运营/其他流程负责)")
|
|
365
|
+
mode = _writeback_mode()
|
|
366
|
+
if mode == "erp":
|
|
367
|
+
if erp_write_fields is None:
|
|
368
|
+
raise SystemExit("❌ ARGENT_WRITEBACK=erp:ERP 写回模块不可用(缺 erp_invoice_writeback.py)")
|
|
369
|
+
try:
|
|
370
|
+
ok = erp_write_fields(rids, patch)
|
|
371
|
+
except Exception as e:
|
|
372
|
+
_audit_write(rids, patch, False, str(e)[:200])
|
|
373
|
+
raise SystemExit(f"❌ ERP 发票写回失败:{e}")
|
|
374
|
+
_audit_write(rids, patch, ok, "" if ok else "ERP invoice-finalize 失败")
|
|
375
|
+
return ok
|
|
376
|
+
if mode == "shadow" and shadow_record is not None:
|
|
377
|
+
try:
|
|
378
|
+
append_shadow(shadow_record(rids, patch, source="lip_update"), DATA)
|
|
379
|
+
except Exception as e:
|
|
380
|
+
log(f"ERP shadow 记录失败(不影响 lip 写回): {e}")
|
|
354
381
|
d = _cli("base", "+record-batch-update", "--base-token", BASE_TOKEN,
|
|
355
382
|
"--table-id", TABLE_ID,
|
|
356
383
|
"--json", json.dumps({"record_id_list": rids, "patch": patch}, ensure_ascii=False))
|
|
@@ -460,6 +487,22 @@ def lip_upload_attachment(rid, field, path, row=None):
|
|
|
460
487
|
上传标签时查不到自己那条 ⇒ 归一失效、附件越挂越多)。
|
|
461
488
|
"""
|
|
462
489
|
path = Path(path)
|
|
490
|
+
if _writeback_mode() == "erp":
|
|
491
|
+
if erp_upload_and_finalize is None:
|
|
492
|
+
raise SystemExit("❌ ARGENT_WRITEBACK=erp:ERP 附件写回模块不可用")
|
|
493
|
+
try:
|
|
494
|
+
ok = erp_upload_and_finalize(rid, field, path)
|
|
495
|
+
except Exception as e:
|
|
496
|
+
_audit_write([rid], {field: path.name}, False, str(e)[:200])
|
|
497
|
+
raise SystemExit(f"❌ ERP 附件写回失败:{e}")
|
|
498
|
+
_audit_write([rid], {field: path.name}, ok, "" if ok else "ERP 附件写回失败")
|
|
499
|
+
return ok
|
|
500
|
+
if _writeback_mode() == "shadow" and shadow_record is not None:
|
|
501
|
+
try:
|
|
502
|
+
append_shadow(shadow_record([rid], {}, source="lip_upload_attachment",
|
|
503
|
+
attachments=[{"field": field, "filename": path.name}]), DATA)
|
|
504
|
+
except Exception as e:
|
|
505
|
+
log(f"ERP shadow 附件记录失败(不影响 lip 上传): {e}")
|
|
463
506
|
same = _same_name_attachments(row, field, path.name)
|
|
464
507
|
if row is not None and same and not _needs_refresh(same, path):
|
|
465
508
|
if len(same) > 1:
|