weaver-work-cli 0.1.50 → 0.1.52
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/README.md +1 -1
- package/dist/chunks/{attachment-content-EJYIOJPH.js → attachment-content-MBYYSQIX.js} +3 -3
- package/dist/chunks/{chunk-RYFRGTUV.js → chunk-7UOXOGFL.js} +4 -4
- package/dist/chunks/{chunk-BFKLQLBK.js → chunk-D3TDNRFE.js} +7 -7
- package/dist/chunks/{chunk-3NCFFHB2.js → chunk-DZOC77ZD.js} +1 -1
- package/dist/chunks/{chunk-K67FODVC.js → chunk-IRMA3GVP.js} +1 -1
- package/dist/chunks/{chunk-WNJUGI2F.js → chunk-KLZ3ULQQ.js} +1 -1
- package/dist/chunks/{chunk-6T53BSWZ.js → chunk-LALWNK6M.js} +9 -0
- package/dist/chunks/{chunk-HARQF5IP.js → chunk-LM2H7SZI.js} +25 -25
- package/dist/chunks/{chunk-YB3AJYPY.js → chunk-LTRLF6MM.js} +4 -4
- package/dist/chunks/{chunk-7ECB22G3.js → chunk-RPRFIG6I.js} +23 -23
- package/dist/chunks/{chunk-MCZG6HPM.js → chunk-RWFRZSIP.js} +2 -2
- package/dist/chunks/{chunk-7AYQJSFY.js → chunk-ZRHKGQRQ.js} +2 -2
- package/dist/chunks/{conflict-C4UDHCWV.js → conflict-D2HYKBMH.js} +2 -2
- package/dist/chunks/{contract-VUC6JOPG.js → contract-MFOFMM2J.js} +3837 -262
- package/dist/chunks/{create-flow-6OG2LYBD.js → create-flow-7ZATJVTM.js} +6 -6
- package/dist/chunks/{data-QO7QWOIV.js → data-WK5CQXNF.js} +17 -32
- package/dist/chunks/{env-WP57TF2S.js → env-5DO4YENS.js} +2 -2
- package/dist/chunks/{factory-VUXI7N5C.js → factory-3M7D7WJC.js} +1 -1
- package/dist/chunks/{group-chat-UQRGXILK.js → group-chat-B2HT5NEO.js} +3 -3
- package/dist/chunks/{invoice-E7GOITEU.js → invoice-V7ZTITUO.js} +725 -205
- package/dist/chunks/{meeting-4BBLVAWM.js → meeting-HZOX3CBB.js} +10 -10
- package/dist/chunks/{recruit-stage-FKWS5UQF.js → recruit-stage-XCMVEQA2.js} +718 -131
- package/dist/chunks/{registry-V4CHRQDI.js → registry-KYPFFQIH.js} +1 -1
- package/dist/chunks/{registry-5CRCN2TV.js → registry-SJHSBO5G.js} +10 -10
- package/dist/chunks/{room-recommend-AYR3UG7R.js → room-recommend-5AHR4YQV.js} +4 -4
- package/dist/chunks/{schedule-JZEFIXUS.js → schedule-KZPJUPC2.js} +4 -4
- package/dist/chunks/smart-extract-IXHCZE4R.js +2846 -0
- package/dist/chunks/{workflow-3ZAF2J5E.js → workflow-UHKCZJMY.js} +1 -1
- package/dist/index.js +11 -6
- package/dist/shortcuts/contract/manifest.js +151 -0
- package/dist/shortcuts/contract/operations/card-action.js +585 -0
- package/dist/shortcuts/contract/operations/card-ebdf-list.js +315 -0
- package/dist/shortcuts/contract/operations/card-plan.js +327 -0
- package/dist/shortcuts/contract/operations/card-risk-report.js +565 -0
- package/dist/shortcuts/contract/operations/elements-build.js +714 -0
- package/dist/shortcuts/contract/operations/elements-spec.js +216 -0
- package/dist/shortcuts/contract/operations/first-screen.js +563 -0
- package/dist/shortcuts/contract/operations/flow.js +81 -25
- package/dist/shortcuts/contract/operations/modeltext.js +132 -0
- package/dist/shortcuts/contract/operations/op-resolver.js +22 -0
- package/dist/shortcuts/contract/operations/quote.js +131 -25
- package/dist/shortcuts/contract/operations/registry.js +20 -0
- package/dist/shortcuts/contract/operations/review.js +73 -58
- package/dist/shortcuts/contract/operations/summary-validate.js +293 -0
- package/dist/shortcuts/contract/operations/summary.js +4 -2
- package/dist/shortcuts/contract/operations/upload.js +48 -7
- package/dist/shortcuts/contract/prewarm-cache.js +90 -0
- package/dist/shortcuts/contract/prewarm.js +88 -0
- package/dist/shortcuts/contract/upload-cache.js +49 -4
- package/dist/shortcuts/data/index.js +1 -6
- package/dist/shortcuts/data/manifest.js +2 -2
- package/dist/shortcuts/data/operations/index.js +1 -1
- package/dist/shortcuts/data/operations/query.js +23 -46
- package/dist/shortcuts/index.js +5 -0
- package/dist/shortcuts/invoice/index.js +0 -12
- package/dist/shortcuts/invoice/manifest.js +200 -49
- package/dist/shortcuts/invoice/operations/registry.js +4 -2
- package/dist/shortcuts/invoice/operations/reim-relation.js +438 -0
- package/dist/shortcuts/invoice/operations/shared.js +3 -19
- package/dist/shortcuts/invoice/operations/upload-and-validate.js +109 -73
- package/dist/shortcuts/recruit-stage/operations/interview-arrange.js +4 -2
- package/dist/shortcuts/recruit-stage/operations/jd-create.js +6 -2
- package/dist/shortcuts/recruit-stage/operations/list.js +217 -1
- package/dist/shortcuts/recruit-stage/operations/resume-import.js +144 -158
- package/dist/shortcuts/recruit-stage/operations/search.js +348 -0
- package/dist/shortcuts/recruit-stage/shared.js +5 -0
- package/dist/shortcuts/recruit-stage/tag-lookup.js +136 -0
- package/dist/shortcuts/smart-extract/constants.js +79 -0
- package/dist/shortcuts/smart-extract/continuation.js +71 -0
- package/dist/shortcuts/smart-extract/errors.js +68 -0
- package/dist/shortcuts/smart-extract/host.js +191 -0
- package/dist/shortcuts/smart-extract/index.js +105 -0
- package/dist/shortcuts/smart-extract/ledger.js +70 -0
- package/dist/shortcuts/smart-extract/manifest.js +35 -0
- package/dist/shortcuts/smart-extract/operations/attachment.js +212 -0
- package/dist/shortcuts/smart-extract/operations/batch.js +67 -0
- package/dist/shortcuts/smart-extract/operations/config.js +118 -0
- package/dist/shortcuts/smart-extract/operations/fill.js +489 -0
- package/dist/shortcuts/smart-extract/operations/preview.js +174 -0
- package/dist/shortcuts/smart-extract/operations/registry.js +34 -0
- package/dist/shortcuts/smart-extract/operations/save.js +355 -0
- package/dist/shortcuts/smart-extract/operations/shared.js +191 -0
- package/dist/shortcuts/smart-extract/operations/structure.js +401 -0
- package/dist/shortcuts/smart-extract/operations/target.js +167 -0
- package/dist/shortcuts/smart-extract/operations/types.js +22 -0
- package/dist/shortcuts/smart-extract/operations/validate.js +408 -0
- package/dist/shortcuts/workflow/operations/read.js +19 -1
- package/docs/SKILL.md +1 -1
- package/docs/_catalog.md +3 -0
- package/docs/agent-invoice.md +5 -7
- package/docs/data.md +5 -1
- package/docs/fna.md +14 -1
- package/docs/invoice.md +7 -5
- package/docs/smart-extract.md +156 -0
- package/package.json +1 -1
- package/skill-template/business-info.json +16 -1
- package/skill-template/domains/qiyecheng.md +2 -0
- package/skill-template/domains/smart-extract.md +16 -0
- package/skill-template/domains/yepiaotong.md +2 -2
- package/skills/weaver-e10-data/references/scene-and-misc.md +4 -3
- package/skills/weaver-e10-jinchengda/SKILL.md +159 -11
- package/skills/weaver-e10-jinchengda/references/contract-action-card.md +8 -3
- package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +4 -3
- package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +8 -7
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +21 -6
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +3 -1
- package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +1 -1
- package/skills/weaver-e10-jinchengda/references/contract-modeltext-library.md +128 -0
- package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +90 -0
- package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +124 -5
- package/skills/weaver-e10-jinchengda/scripts/contract_first_screen.py +200 -0
- package/skills/weaver-e10-jinchengda/scripts/fill_contract_from_quote.py +572 -0
- package/skills/weaver-e10-jinchengda/scripts/quote_screen.py +560 -0
- package/skills/weaver-e10-jinchengda/scripts/triage_contract.py +894 -0
- package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +10 -0
- package/skills/weaver-e10-qiyecheng/SKILL.md +37 -0
- package/skills/weaver-e10-qiyecheng/references/ai-check-audit.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/budget.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/catalog.md +25 -0
- package/skills/weaver-e10-qiyecheng/references/expense-center.md +8 -0
- package/skills/weaver-e10-qiyecheng/references/expense-chart.md +9 -0
- package/skills/weaver-e10-qiyecheng/references/invoice-writeoff.md +13 -0
- package/skills/weaver-e10-qiyecheng/references/loan-management.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/self-hosted-mode.md +239 -0
- package/skills/weaver-e10-qiyecheng/references/source-manifest.json +34 -27
- package/skills/weaver-e10-recruit-stage/SKILL.md +62 -4
- package/skills/weaver-e10-recruit-stage/agents/openai.yaml +42 -8
- package/skills/weaver-e10-recruit-stage/references/env-ziyong.md +79 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +11 -3
- package/skills/weaver-e10-recruit-stage/references/recruit-edit-interview-feedback.md +3 -2
- package/skills/weaver-e10-recruit-stage/references/recruit-interview-not-attended.md +153 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-jd-create.md +7 -4
- package/skills/weaver-e10-recruit-stage/references/recruit-match-candidates.md +1 -1
- package/skills/weaver-e10-recruit-stage/references/recruit-my-positions.md +66 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +156 -42
- package/skills/weaver-e10-recruit-stage/references/recruit-resume-import-batch.md +122 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +36 -8
- package/skills/weaver-e10-recruit-stage/references/recruit-search-by-tag.md +157 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-utterance-glossary.md +35 -0
- package/skills/weaver-e10-smart-extract/SKILL.md +169 -0
- package/skills/weaver-e10-smart-extract/references/api-contract.md +71 -0
- package/skills/weaver-e10-smart-extract/references/result-format.md +102 -0
- package/skills/weaver-e10-smart-extract/references/troubleshooting.md +105 -0
- package/skills/weaver-e10-workflow/references/workflow-query.md +1 -1
- package/skills/weaver-e10-workflow/references/workflow-view.md +1 -1
- package/skills/weaver-e10-yepiaotong/SKILL.md +46 -33
- package/skills/weaver-e10-yepiaotong/references/invoice-add.md +2 -0
- package/skills/weaver-e10-yepiaotong/references/invoice-file-upload.md +1 -1
- package/skills/weaver-e10-yepiaotong/references/invoice-import.md +19 -2
- package/skills/weaver-e10-yepiaotong/references/invoice-ocr-preview.md +8 -2
- package/skills/weaver-e10-yepiaotong/references/invoice-reim-relation.md +407 -0
- package/skills/weaver-e10-yepiaotong/references/invoice-reim.md +12 -8
- package/skills/weaver-e10-yepiaotong/references/invoice-upload-and-validate.md +97 -39
- package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +91 -2
- package/skills/weaver-e10-yepiaotong/references/reim-examples.md +1 -1
- package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +12 -12
- package/skills/weaver-e10-yepiaotong/references/reim-matching-rules.md +8 -4
- package/skills/weaver-e10-yepiaotong/references/reim-phone-subsidy-rules.md +136 -91
- package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +109 -23
- package/skills/weaver-e10-yepiaotong/references/source-manifest.json +110 -43
- package/dist/shortcuts/invoice/operations/validate-preview.js +0 -40
- package/skills/weaver-e10-jinchengda/scripts/plan_actions.py +0 -279
- package/skills/weaver-e10-jinchengda/scripts/render_action_card.py +0 -450
- package/skills/weaver-e10-jinchengda/scripts/render_ebdf_list_card.py +0 -265
- package/skills/weaver-e10-jinchengda/scripts/render_risk_report.py +0 -358
- package/skills/weaver-e10-yepiaotong/references/invoice-validation-preview.md +0 -40
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { CliError, ExitCode } from '../../core/errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* 智能抽取的结构化错误。
|
|
4
|
+
*
|
|
5
|
+
* 与其它业务模块保持一致:`type/subtype` 是调用方(模型)分流的唯一依据,
|
|
6
|
+
* message 给人看,details 放可诊断的上下文(不要塞凭据)。
|
|
7
|
+
*/
|
|
8
|
+
export class SmartExtractCliError extends CliError {
|
|
9
|
+
type;
|
|
10
|
+
subtype;
|
|
11
|
+
code;
|
|
12
|
+
retryable;
|
|
13
|
+
stage;
|
|
14
|
+
details;
|
|
15
|
+
constructor(type, subtype, message, options = {}) {
|
|
16
|
+
super(message, options.exitCode ?? ExitCode.InternalError);
|
|
17
|
+
this.name = 'SmartExtractCliError';
|
|
18
|
+
this.type = type;
|
|
19
|
+
this.subtype = subtype;
|
|
20
|
+
this.code = options.code;
|
|
21
|
+
this.retryable = options.retryable ?? false;
|
|
22
|
+
this.stage = options.stage;
|
|
23
|
+
this.details = options.details;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export function smartExtractValidationError(subtype, message, details) {
|
|
27
|
+
return new SmartExtractCliError('validation', subtype, message, {
|
|
28
|
+
details,
|
|
29
|
+
exitCode: ExitCode.UsageError,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
export function smartExtractAuthError(subtype, message, details) {
|
|
33
|
+
return new SmartExtractCliError('authentication', subtype, message, {
|
|
34
|
+
details,
|
|
35
|
+
exitCode: ExitCode.AuthError,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export function smartExtractBusinessError(subtype, message, options = {}) {
|
|
39
|
+
return new SmartExtractCliError('business', subtype, message, {
|
|
40
|
+
...options,
|
|
41
|
+
exitCode: ExitCode.GeneralError,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
export function smartExtractNetworkError(subtype, message, options = {}) {
|
|
45
|
+
return new SmartExtractCliError('network', subtype, message, {
|
|
46
|
+
...options,
|
|
47
|
+
retryable: options.retryable ?? true,
|
|
48
|
+
exitCode: ExitCode.NetworkError,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
export function smartExtractConfirmationError(action, details) {
|
|
52
|
+
return new SmartExtractCliError('confirmation', 'required', '该操作需要用户明确确认后才能执行', {
|
|
53
|
+
details: { action, ...details },
|
|
54
|
+
exitCode: ExitCode.ConfirmationRequired,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 写入结果未知(超时/断网/响应不可解析)。
|
|
59
|
+
*
|
|
60
|
+
* 调用方**禁止重试**,只能用 `smart-extract.batch.get` 只读回查:
|
|
61
|
+
* 服务端可能已经落库,重试会产生第二条记录。
|
|
62
|
+
*/
|
|
63
|
+
export function smartExtractPartialError(message, details) {
|
|
64
|
+
return new SmartExtractCliError('partial', 'write_uncertain', message, {
|
|
65
|
+
details,
|
|
66
|
+
exitCode: ExitCode.Partial,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { requireE10Session } from '../../internal/e10/context.js';
|
|
2
|
+
import { getActiveProfile } from '../../internal/e10/auth/session.js';
|
|
3
|
+
import { isE10SessionExpiredResponse } from '../../internal/e10/auth-recovery.js';
|
|
4
|
+
import { createE10RequestRuntime, E10ApiError, } from '../../internal/e10/request-runtime.js';
|
|
5
|
+
import { smartExtractAuthError, smartExtractBusinessError, smartExtractNetworkError, smartExtractValidationError, } from './errors.js';
|
|
6
|
+
import { DEFAULT_TIMEOUT_MS, DOWNLOAD_TIMEOUT_MS } from './constants.js';
|
|
7
|
+
const ALLOWED_PREFIXES = ['/api/ai/application/', '/api/government/', '/api/file/', '/api/ebuilder/'];
|
|
8
|
+
function assertApiPath(path) {
|
|
9
|
+
if (!path.startsWith('/api/') || path.startsWith('//') || path.includes('/../') || /^https?:/iu.test(path)) {
|
|
10
|
+
throw smartExtractValidationError('path_invalid', 'E10 API 只能调用 /api/ 同源相对路径');
|
|
11
|
+
}
|
|
12
|
+
if (!ALLOWED_PREFIXES.some((prefix) => path.startsWith(prefix))) {
|
|
13
|
+
throw smartExtractValidationError('path_forbidden', `smart-extract 不允许调用该接口:${path}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function createSmartExtractHost(ctx) {
|
|
17
|
+
let cached = null;
|
|
18
|
+
async function resolve() {
|
|
19
|
+
if (cached)
|
|
20
|
+
return cached;
|
|
21
|
+
const e10 = await requireE10Session(ctx).catch(() => null);
|
|
22
|
+
if (!e10) {
|
|
23
|
+
cached = {
|
|
24
|
+
e10: null,
|
|
25
|
+
info: {
|
|
26
|
+
available: false,
|
|
27
|
+
baseUrl: '',
|
|
28
|
+
userId: '',
|
|
29
|
+
profile: getActiveProfile(),
|
|
30
|
+
reason: '未取得 E10 会话,请先执行 weaver-work-cli auth login',
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
return cached;
|
|
34
|
+
}
|
|
35
|
+
cached = {
|
|
36
|
+
e10,
|
|
37
|
+
info: {
|
|
38
|
+
available: true,
|
|
39
|
+
baseUrl: e10.getBaseUrl(),
|
|
40
|
+
userId: e10.userId,
|
|
41
|
+
profile: ctx.getGlobalOptions().profile || getActiveProfile(),
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
return cached;
|
|
45
|
+
}
|
|
46
|
+
async function getSession() {
|
|
47
|
+
return (await resolve()).info;
|
|
48
|
+
}
|
|
49
|
+
async function runtime() {
|
|
50
|
+
const { e10, info } = await resolve();
|
|
51
|
+
if (!e10)
|
|
52
|
+
throw smartExtractAuthError('no_session', info.reason || '未取得 E10 会话', { available: false });
|
|
53
|
+
return { runtime: createE10RequestRuntime(ctx, e10), info };
|
|
54
|
+
}
|
|
55
|
+
async function request(options) {
|
|
56
|
+
assertApiPath(options.path);
|
|
57
|
+
const { runtime: rt } = await runtime();
|
|
58
|
+
let response;
|
|
59
|
+
try {
|
|
60
|
+
response = await rt.requestJson({
|
|
61
|
+
module: 'smart-extract',
|
|
62
|
+
operation: options.operation,
|
|
63
|
+
method: options.method || 'POST',
|
|
64
|
+
path: options.path,
|
|
65
|
+
query: options.query,
|
|
66
|
+
body: options.body,
|
|
67
|
+
headers: { langtype: 'zh_CN' },
|
|
68
|
+
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error instanceof E10ApiError) {
|
|
73
|
+
throw smartExtractNetworkError('request_failed', `请求失败:${error.message}`, {
|
|
74
|
+
retryable: error.retryable,
|
|
75
|
+
stage: options.operation,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
throw smartExtractNetworkError('request_failed', `请求异常:${error.message}`, {
|
|
79
|
+
stage: options.operation,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (isE10SessionExpiredResponse(response)) {
|
|
83
|
+
throw smartExtractAuthError('session_expired', 'E10 登录态已失效,请重新登录', {
|
|
84
|
+
httpStatus: response.status,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
if (response.parseError) {
|
|
88
|
+
throw smartExtractNetworkError('protocol', `接口返回不是合法 JSON(HTTP ${response.status})`, {
|
|
89
|
+
retryable: false,
|
|
90
|
+
stage: options.operation,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
if (response.status < 200 || response.status >= 300) {
|
|
94
|
+
throw smartExtractBusinessError('http_error', `接口 HTTP ${response.status}`, {
|
|
95
|
+
code: response.status,
|
|
96
|
+
stage: options.operation,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return response.value;
|
|
100
|
+
}
|
|
101
|
+
async function requestData(options) {
|
|
102
|
+
return unwrapWeaResult(await request(options), options.operation);
|
|
103
|
+
}
|
|
104
|
+
async function download(path, operation, timeoutMs = DOWNLOAD_TIMEOUT_MS) {
|
|
105
|
+
assertApiPath(path);
|
|
106
|
+
const { runtime: rt } = await runtime();
|
|
107
|
+
let response;
|
|
108
|
+
try {
|
|
109
|
+
response = await rt.requestBinary({
|
|
110
|
+
module: 'smart-extract',
|
|
111
|
+
operation,
|
|
112
|
+
method: 'GET',
|
|
113
|
+
path,
|
|
114
|
+
headers: { accept: '*/*' },
|
|
115
|
+
timeoutMs,
|
|
116
|
+
followRedirects: true,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (error instanceof E10ApiError) {
|
|
121
|
+
throw smartExtractNetworkError('download_failed', `下载失败:${error.message}`, {
|
|
122
|
+
retryable: error.retryable,
|
|
123
|
+
stage: operation,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
throw smartExtractNetworkError('download_failed', `下载异常:${error.message}`, {
|
|
127
|
+
stage: operation,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (isE10SessionExpiredResponse(response)) {
|
|
131
|
+
throw smartExtractAuthError('session_expired', '下载时登录态已失效,请重新登录', {
|
|
132
|
+
httpStatus: response.status,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
if (response.status !== 200) {
|
|
136
|
+
throw smartExtractBusinessError('download_failed', `下载失败 HTTP ${response.status}`, {
|
|
137
|
+
code: response.status,
|
|
138
|
+
stage: operation,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
buffer: response.content,
|
|
143
|
+
contentType: response.contentType || '',
|
|
144
|
+
contentDisposition: response.headers.get('content-disposition') || '',
|
|
145
|
+
httpStatus: response.status,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
return { getSession, request, requestData, download };
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* WeaResult 解包。
|
|
152
|
+
*
|
|
153
|
+
* E10 的 `WeaResult` 有两种失败表达:`status=false` / `fail=true` / 非 200 的 `code`。
|
|
154
|
+
* 任何一个命中都抛业务错误,并把服务端 `msg` 原样带出来(英文原文,便于定位)。
|
|
155
|
+
*/
|
|
156
|
+
export function unwrapWeaResult(payload, operation) {
|
|
157
|
+
const root = record(payload);
|
|
158
|
+
if (Object.keys(root).length === 0) {
|
|
159
|
+
throw smartExtractBusinessError('response_invalid', `${operation} 返回为空`, { stage: operation });
|
|
160
|
+
}
|
|
161
|
+
const code = root.code;
|
|
162
|
+
const failed = root.status === false
|
|
163
|
+
|| root.fail === true
|
|
164
|
+
|| (code !== undefined && code !== null && String(code) !== '200' && String(code) !== '0');
|
|
165
|
+
if (failed) {
|
|
166
|
+
throw smartExtractBusinessError('business_error', responseMessage(payload) || `${operation} 业务失败`, {
|
|
167
|
+
code: code === undefined || code === null ? undefined : String(code),
|
|
168
|
+
details: { result: payload },
|
|
169
|
+
stage: operation,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
if (!('data' in root)) {
|
|
173
|
+
throw smartExtractBusinessError('response_invalid', `${operation} 响应缺少 data`, {
|
|
174
|
+
details: { result: payload },
|
|
175
|
+
stage: operation,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
return root.data;
|
|
179
|
+
}
|
|
180
|
+
export function record(value) {
|
|
181
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
182
|
+
}
|
|
183
|
+
export function responseMessage(payload) {
|
|
184
|
+
const root = record(payload);
|
|
185
|
+
const message = record(root.message);
|
|
186
|
+
for (const value of [root.msg, root.message, message.msg, message.message, root.errmsg]) {
|
|
187
|
+
if (typeof value === 'string' && value.trim())
|
|
188
|
+
return value.trim().slice(0, 500);
|
|
189
|
+
}
|
|
190
|
+
return '';
|
|
191
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { ExitCode, isCliError, toErrorEnvelope } from '../../core/errors.js';
|
|
4
|
+
import { stateRoot } from '../../core/state.js';
|
|
5
|
+
import { STATE_SUBDIR } from './constants.js';
|
|
6
|
+
import { createSmartExtractContinuationSigner } from './continuation.js';
|
|
7
|
+
import { smartExtractValidationError } from './errors.js';
|
|
8
|
+
import { createSmartExtractHost } from './host.js';
|
|
9
|
+
import { assertManifestMatchesRegistry, smartExtractManifest } from './manifest.js';
|
|
10
|
+
import { getSmartExtractOperation } from './operations/registry.js';
|
|
11
|
+
import { parseJsonObject, stripBom } from './operations/shared.js';
|
|
12
|
+
/**
|
|
13
|
+
* 命令面:`schema` + `run`。
|
|
14
|
+
*
|
|
15
|
+
* 调用方是模型:读 `schema` 拿 operation 名与入参契约,用 `run` 执行。
|
|
16
|
+
*/
|
|
17
|
+
function asOptions(value) {
|
|
18
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
19
|
+
? value
|
|
20
|
+
: {};
|
|
21
|
+
}
|
|
22
|
+
async function readStdin() {
|
|
23
|
+
const chunks = [];
|
|
24
|
+
for await (const chunk of process.stdin) {
|
|
25
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
26
|
+
}
|
|
27
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
28
|
+
}
|
|
29
|
+
async function inputFrom(options) {
|
|
30
|
+
const inline = typeof options.inputJson === 'string' ? options.inputJson.trim() : '';
|
|
31
|
+
const file = typeof options.input === 'string' ? options.input.trim() : '';
|
|
32
|
+
if (inline && file) {
|
|
33
|
+
throw smartExtractValidationError('input_conflict', '不能同时传 --input 和 --input-json');
|
|
34
|
+
}
|
|
35
|
+
if (inline)
|
|
36
|
+
return parseJsonObject(stripBom(inline), '--input-json');
|
|
37
|
+
if (file) {
|
|
38
|
+
let raw;
|
|
39
|
+
try {
|
|
40
|
+
raw = file === '-' ? await readStdin() : await readFile(file, 'utf8');
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw smartExtractValidationError('input_unreadable', `无法读取 --input:${file}`);
|
|
44
|
+
}
|
|
45
|
+
return parseJsonObject(stripBom(raw), '--input');
|
|
46
|
+
}
|
|
47
|
+
return {};
|
|
48
|
+
}
|
|
49
|
+
function contextOf(ctx) {
|
|
50
|
+
const stateDir = join(stateRoot(ctx), STATE_SUBDIR);
|
|
51
|
+
return {
|
|
52
|
+
ctx,
|
|
53
|
+
host: createSmartExtractHost(ctx),
|
|
54
|
+
continuation: createSmartExtractContinuationSigner(ctx),
|
|
55
|
+
stateDir,
|
|
56
|
+
outDir: join(stateDir, 'attachments'),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
async function executeAndPrint(ctx, operation, input) {
|
|
60
|
+
try {
|
|
61
|
+
const definition = getSmartExtractOperation(operation);
|
|
62
|
+
const result = await definition.handler(input, contextOf(ctx));
|
|
63
|
+
ctx.output.write({
|
|
64
|
+
schemaVersion: 1,
|
|
65
|
+
ok: true,
|
|
66
|
+
operation,
|
|
67
|
+
risk: definition.risk,
|
|
68
|
+
data: result.data === undefined ? null : result.data,
|
|
69
|
+
...(result.meta ? { meta: result.meta } : {}),
|
|
70
|
+
warnings: result.warnings ?? [],
|
|
71
|
+
}, { json: true });
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
/*
|
|
75
|
+
* 错误信封走 stdout:本模块的调用方是模型,它只解析 stdout。
|
|
76
|
+
* 走 stderr 会被多数宿主丢掉,表现为「命令失败了但不知道为什么」。
|
|
77
|
+
*/
|
|
78
|
+
ctx.output.write({ schemaVersion: 1, ok: false, operation, error: toErrorEnvelope(error) }, { json: true });
|
|
79
|
+
process.exitCode = isCliError(error) ? error.exitCode : ExitCode.GeneralError;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export const smartExtractShortcut = {
|
|
83
|
+
name: 'smart-extract',
|
|
84
|
+
description: 'E10 智能抽取 CLI(fill 一次取齐入参 → fill.save 校验+落库+回查,返回 aiExtraId)',
|
|
85
|
+
category: 'shortcut',
|
|
86
|
+
register({ program, action }) {
|
|
87
|
+
assertManifestMatchesRegistry();
|
|
88
|
+
const command = program.command('smart-extract')
|
|
89
|
+
.description('E10 智能抽取:fill 一次取齐结构与附件正文,fill.save 校验+落库+回查;其余为排障命令');
|
|
90
|
+
command.command('schema')
|
|
91
|
+
.description('输出 operation 合约(Agent 自查入口)')
|
|
92
|
+
.action(action((ctx) => {
|
|
93
|
+
ctx.output.write(smartExtractManifest, { json: true });
|
|
94
|
+
}));
|
|
95
|
+
command.command('run')
|
|
96
|
+
.description('按 operation 名执行,例如 smart-extract.form.structure')
|
|
97
|
+
.argument('<operation>', 'operation 名,见 schema 输出')
|
|
98
|
+
.option('--input <path>', 'JSON 入参文件,- 表示 stdin')
|
|
99
|
+
.option('--input-json <json>', '内联 JSON 入参')
|
|
100
|
+
.action(action(async (ctx, operation, options) => {
|
|
101
|
+
const opts = asOptions(options);
|
|
102
|
+
await executeAndPrint(ctx, String(operation), await inputFrom(opts));
|
|
103
|
+
}));
|
|
104
|
+
},
|
|
105
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
const MAX_ENTRIES = 300;
|
|
4
|
+
const LEDGER_FILE = 'saved-ledger.json';
|
|
5
|
+
function ledgerPath(stateDir) {
|
|
6
|
+
return join(stateDir, LEDGER_FILE);
|
|
7
|
+
}
|
|
8
|
+
export async function readLedger(stateDir) {
|
|
9
|
+
try {
|
|
10
|
+
const raw = await readFile(ledgerPath(stateDir), 'utf8');
|
|
11
|
+
const parsed = JSON.parse(raw);
|
|
12
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
13
|
+
return {};
|
|
14
|
+
const ledger = parsed;
|
|
15
|
+
// 兼容旧台账:老条目字段叫 batchId,统一迁移为 aiExtraId
|
|
16
|
+
for (const entry of Object.values(ledger)) {
|
|
17
|
+
if (!entry.aiExtraId && typeof entry.batchId === 'string') {
|
|
18
|
+
entry.aiExtraId = entry.batchId;
|
|
19
|
+
}
|
|
20
|
+
delete entry.batchId;
|
|
21
|
+
}
|
|
22
|
+
return ledger;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export async function findSavedByFingerprint(stateDir, fingerprint) {
|
|
29
|
+
const ledger = await readLedger(stateDir);
|
|
30
|
+
return ledger[fingerprint];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* L2:按「流程 + 节点 + 附件」找已有保存记录。
|
|
34
|
+
* 三个条件都要一致才算同一次业务保存;attachmentIds 完全相等(逗号分隔串比较)。
|
|
35
|
+
*/
|
|
36
|
+
export async function findSavedByTargetAttachment(stateDir, workflowId, nodeId, attachmentIds) {
|
|
37
|
+
const ledger = await readLedger(stateDir);
|
|
38
|
+
for (const entry of Object.values(ledger)) {
|
|
39
|
+
if (entry.workflowId !== workflowId)
|
|
40
|
+
continue;
|
|
41
|
+
if ((entry.nodeId ?? '') !== (nodeId ?? ''))
|
|
42
|
+
continue;
|
|
43
|
+
if (!entry.attachmentIds)
|
|
44
|
+
continue;
|
|
45
|
+
if (entry.attachmentIds !== attachmentIds)
|
|
46
|
+
continue;
|
|
47
|
+
return entry;
|
|
48
|
+
}
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
export async function rememberSaved(stateDir, fingerprint, entry) {
|
|
52
|
+
const ledger = await readLedger(stateDir);
|
|
53
|
+
ledger[fingerprint] = entry;
|
|
54
|
+
const keys = Object.keys(ledger);
|
|
55
|
+
if (keys.length > MAX_ENTRIES) {
|
|
56
|
+
// 只保留最近的若干条:按 savedAt 倒序裁剪,避免台账无限增长。
|
|
57
|
+
const kept = keys
|
|
58
|
+
.sort((left, right) => String(ledger[right]?.savedAt ?? '').localeCompare(String(ledger[left]?.savedAt ?? '')))
|
|
59
|
+
.slice(0, MAX_ENTRIES);
|
|
60
|
+
for (const key of keys) {
|
|
61
|
+
if (!kept.includes(key))
|
|
62
|
+
delete ledger[key];
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
await mkdir(stateDir, { recursive: true });
|
|
66
|
+
const target = ledgerPath(stateDir);
|
|
67
|
+
const temp = `${target}.${process.pid}.tmp`;
|
|
68
|
+
await writeFile(temp, JSON.stringify(ledger, null, 2), 'utf8');
|
|
69
|
+
await rename(temp, target);
|
|
70
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { smartExtractOperationDefinitions, smartExtractOperationNames, } from './operations/registry.js';
|
|
2
|
+
export const smartExtractOperations = smartExtractOperationDefinitions.map((definition) => ({
|
|
3
|
+
name: definition.name,
|
|
4
|
+
risk: definition.risk,
|
|
5
|
+
summary: definition.summary,
|
|
6
|
+
inputSchema: definition.inputSchema,
|
|
7
|
+
}));
|
|
8
|
+
export const smartExtractManifest = {
|
|
9
|
+
schemaVersion: 1,
|
|
10
|
+
module: 'smart-extract',
|
|
11
|
+
name: 'smart-extract',
|
|
12
|
+
title: 'E10 智能抽取(表单结构化数据抽取)',
|
|
13
|
+
version: 1,
|
|
14
|
+
host: 'e10-smart-extract',
|
|
15
|
+
status: 'builtin',
|
|
16
|
+
sourceSkill: 'weaver-e10-smart-extract',
|
|
17
|
+
capabilities: ['smart-extract'],
|
|
18
|
+
/** 主链路两步:fill 只读、fill.save 校验通过即写(不再要人工确认)。 */
|
|
19
|
+
writePolicy: 'auto-after-validate',
|
|
20
|
+
/** 推荐调用顺序,给模型当路标,不参与校验。 */
|
|
21
|
+
flow: [
|
|
22
|
+
'smart-extract.fill',
|
|
23
|
+
'smart-extract.fill.save',
|
|
24
|
+
],
|
|
25
|
+
operations: smartExtractOperations,
|
|
26
|
+
operationNames: smartExtractOperationNames,
|
|
27
|
+
};
|
|
28
|
+
/** 命令面自检:manifest 与 registry 必须一致,避免文档与实现脱节。 */
|
|
29
|
+
export function assertManifestMatchesRegistry() {
|
|
30
|
+
const declared = smartExtractOperations.map((operation) => operation.name).sort();
|
|
31
|
+
const registered = [...smartExtractOperationNames].sort();
|
|
32
|
+
if (declared.join(',') !== registered.join(',')) {
|
|
33
|
+
throw new Error(`manifest 与 registry 不一致:\nmanifest=${declared.join(',')}\nregistry=${registered.join(',')}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { extname, join, resolve } from 'node:path';
|
|
3
|
+
import { FILE_DOWNLOAD_PATH, MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES, PATHS } from '../constants.js';
|
|
4
|
+
import { smartExtractValidationError } from '../errors.js';
|
|
5
|
+
import { record } from '../host.js';
|
|
6
|
+
import { smartExtractSuccess, schemaOf } from './types.js';
|
|
7
|
+
import { optionalString, parseIdList } from './shared.js';
|
|
8
|
+
const KIND_BY_EXT = {
|
|
9
|
+
'.pdf': 'pdf',
|
|
10
|
+
'.doc': 'word',
|
|
11
|
+
'.docx': 'word',
|
|
12
|
+
'.xls': 'excel',
|
|
13
|
+
'.xlsx': 'excel',
|
|
14
|
+
'.csv': 'excel',
|
|
15
|
+
'.ppt': 'ppt',
|
|
16
|
+
'.pptx': 'ppt',
|
|
17
|
+
'.txt': 'text',
|
|
18
|
+
'.md': 'text',
|
|
19
|
+
'.json': 'text',
|
|
20
|
+
'.xml': 'text',
|
|
21
|
+
'.html': 'text',
|
|
22
|
+
'.htm': 'text',
|
|
23
|
+
'.png': 'image',
|
|
24
|
+
'.jpg': 'image',
|
|
25
|
+
'.jpeg': 'image',
|
|
26
|
+
'.webp': 'image',
|
|
27
|
+
'.gif': 'image',
|
|
28
|
+
'.bmp': 'image',
|
|
29
|
+
'.zip': 'archive',
|
|
30
|
+
'.rar': 'archive',
|
|
31
|
+
'.7z': 'archive',
|
|
32
|
+
};
|
|
33
|
+
function kindOf(name, contentType) {
|
|
34
|
+
const ext = extname(name).toLowerCase();
|
|
35
|
+
if (KIND_BY_EXT[ext])
|
|
36
|
+
return KIND_BY_EXT[ext];
|
|
37
|
+
if (contentType.includes('pdf'))
|
|
38
|
+
return 'pdf';
|
|
39
|
+
if (contentType.includes('word'))
|
|
40
|
+
return 'word';
|
|
41
|
+
if (contentType.includes('sheet') || contentType.includes('excel'))
|
|
42
|
+
return 'excel';
|
|
43
|
+
if (contentType.startsWith('image/'))
|
|
44
|
+
return 'image';
|
|
45
|
+
if (contentType.startsWith('text/'))
|
|
46
|
+
return 'text';
|
|
47
|
+
return 'other';
|
|
48
|
+
}
|
|
49
|
+
function safeFileName(name, fileId) {
|
|
50
|
+
const base = name.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').trim();
|
|
51
|
+
return base || fileId;
|
|
52
|
+
}
|
|
53
|
+
function extFromContentType(contentType) {
|
|
54
|
+
const text = contentType.toLowerCase();
|
|
55
|
+
if (text.includes('wordprocessingml'))
|
|
56
|
+
return '.docx';
|
|
57
|
+
if (text.includes('spreadsheetml'))
|
|
58
|
+
return '.xlsx';
|
|
59
|
+
if (text.includes('presentationml'))
|
|
60
|
+
return '.pptx';
|
|
61
|
+
if (text.includes('pdf'))
|
|
62
|
+
return '.pdf';
|
|
63
|
+
if (text.includes('png'))
|
|
64
|
+
return '.png';
|
|
65
|
+
if (text.includes('jpeg') || text.includes('jpg'))
|
|
66
|
+
return '.jpg';
|
|
67
|
+
if (text.includes('plain'))
|
|
68
|
+
return '.txt';
|
|
69
|
+
return '';
|
|
70
|
+
}
|
|
71
|
+
function fileNameFromDisposition(disposition) {
|
|
72
|
+
const encoded = /filename\*=UTF-8''([^;]+)/iu.exec(disposition);
|
|
73
|
+
if (encoded) {
|
|
74
|
+
try {
|
|
75
|
+
return decodeURIComponent(encoded[1]).trim();
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// 落到下一个分支
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const plain = /filename="?([^";]+)"?/iu.exec(disposition);
|
|
82
|
+
return plain ? plain[1].trim() : '';
|
|
83
|
+
}
|
|
84
|
+
async function loadMeta(env, ids) {
|
|
85
|
+
const metas = new Map();
|
|
86
|
+
const warnings = [];
|
|
87
|
+
try {
|
|
88
|
+
const data = await env.host.requestData({
|
|
89
|
+
operation: 'smart-extract.attachment.fetch',
|
|
90
|
+
method: 'GET',
|
|
91
|
+
path: PATHS.attachmentInfo,
|
|
92
|
+
query: { attachmentIds: ids.join(',') },
|
|
93
|
+
});
|
|
94
|
+
const list = Array.isArray(data) ? data : [];
|
|
95
|
+
for (const item of list) {
|
|
96
|
+
const entry = record(item);
|
|
97
|
+
const fileId = String(entry.fileid ?? entry.fileId ?? entry.id ?? '').trim();
|
|
98
|
+
if (!fileId)
|
|
99
|
+
continue;
|
|
100
|
+
metas.set(fileId, {
|
|
101
|
+
fileId,
|
|
102
|
+
...(entry.name ? { name: String(entry.name) } : {}),
|
|
103
|
+
...(entry.extName ? { extName: String(entry.extName) } : {}),
|
|
104
|
+
...(entry.size === undefined || entry.size === null ? {} : { size: Number(entry.size) }),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
warnings.push(`附件元数据查询失败(继续按 ID 下载):${error.message.slice(0, 120)}`);
|
|
110
|
+
}
|
|
111
|
+
return { metas, warnings };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* 附件落地(downloadAttachments)。
|
|
115
|
+
*
|
|
116
|
+
* 链路:`queryAttachmentInfo`(拿文件名/扩展名/大小)→ `remotedownload`(拿原始字节)→ 落本地。
|
|
117
|
+
* 由 `attachment.fetch` 与 `fill` 共用,避免两条链路各写一份下载逻辑。
|
|
118
|
+
*/
|
|
119
|
+
export async function downloadAttachments(env, ids, outDir, maxBytes) {
|
|
120
|
+
const { metas, warnings } = await loadMeta(env, ids);
|
|
121
|
+
const session = await env.host.getSession();
|
|
122
|
+
const items = [];
|
|
123
|
+
for (const fileId of ids) {
|
|
124
|
+
const meta = metas.get(fileId);
|
|
125
|
+
try {
|
|
126
|
+
const response = await env.host.download(FILE_DOWNLOAD_PATH(fileId), 'smart-extract.attachment.fetch');
|
|
127
|
+
if (response.buffer.length > maxBytes) {
|
|
128
|
+
warnings.push(`附件 ${fileId} 大小 ${response.buffer.length} 超过上限 ${maxBytes},已跳过落地`);
|
|
129
|
+
items.push({ fileId, name: meta?.name ?? null, bytes: response.buffer.length, downloaded: false, reason: 'too_large' });
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
const dispositionName = fileNameFromDisposition(response.contentDisposition);
|
|
133
|
+
const ext = meta?.extName ? `.${meta.extName.replace(/^\./u, '')}` : '';
|
|
134
|
+
const metaName = meta?.name
|
|
135
|
+
? (ext && !meta.name.toLowerCase().endsWith(ext.toLowerCase()) ? `${meta.name}${ext}` : meta.name)
|
|
136
|
+
: '';
|
|
137
|
+
const fallbackExt = extFromContentType(response.contentType);
|
|
138
|
+
const name = safeFileName(metaName || dispositionName || `${fileId}${fallbackExt}`, `${fileId}${fallbackExt}`);
|
|
139
|
+
const target = join(outDir, name);
|
|
140
|
+
await writeFile(target, response.buffer);
|
|
141
|
+
const resolvedName = name || `${fileId}${fallbackExt}`;
|
|
142
|
+
items.push({
|
|
143
|
+
fileId,
|
|
144
|
+
name: resolvedName,
|
|
145
|
+
path: target,
|
|
146
|
+
bytes: response.buffer.length,
|
|
147
|
+
contentType: response.contentType,
|
|
148
|
+
kind: kindOf(resolvedName, response.contentType),
|
|
149
|
+
downloaded: true,
|
|
150
|
+
...(session.baseUrl
|
|
151
|
+
? { previewUrl: `${session.baseUrl.replace(/\/+$/u, '')}/sp/file/filePreview/${fileId}` }
|
|
152
|
+
: {}),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
warnings.push(`附件 ${fileId} 下载失败:${error.message.slice(0, 160)}`);
|
|
157
|
+
items.push({
|
|
158
|
+
fileId,
|
|
159
|
+
name: meta?.name ?? null,
|
|
160
|
+
downloaded: false,
|
|
161
|
+
reason: 'download_failed',
|
|
162
|
+
error: error.message.slice(0, 300),
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return { items, warnings };
|
|
167
|
+
}
|
|
168
|
+
const attachmentFetch = {
|
|
169
|
+
name: 'smart-extract.attachment.fetch',
|
|
170
|
+
risk: 'read',
|
|
171
|
+
summary: '把 E10 附件(fileId/attachmentId)下载到本地临时目录,返回绝对路径与文件类型。只落地不解解析:拿到 path 后由宿主模型自己读(PDF/Word/Excel/图片都行)。',
|
|
172
|
+
inputSchema: schemaOf({
|
|
173
|
+
attachmentIds: {
|
|
174
|
+
oneOf: [
|
|
175
|
+
{ type: 'string', description: '附件 ID,多个用逗号分隔' },
|
|
176
|
+
{ type: 'array', items: { type: 'string' }, description: '附件 ID 数组' },
|
|
177
|
+
],
|
|
178
|
+
description: '要下载的附件 ID(E10 文件服务 fileId)',
|
|
179
|
+
},
|
|
180
|
+
outDir: { type: 'string', description: '落地目录;默认 <state>/smart-extract/attachments' },
|
|
181
|
+
maxBytes: { type: 'integer', description: '单文件大小上限(字节),默认 200MB' },
|
|
182
|
+
}, { required: ['attachmentIds'] }),
|
|
183
|
+
handler: async (args, env) => {
|
|
184
|
+
const ids = parseIdList(args.attachmentIds, 'attachmentIds');
|
|
185
|
+
if (ids.length === 0) {
|
|
186
|
+
throw smartExtractValidationError('attachment_ids_required', 'attachmentIds 不能为空');
|
|
187
|
+
}
|
|
188
|
+
if (ids.length > MAX_ATTACHMENTS) {
|
|
189
|
+
throw smartExtractValidationError('too_many_attachments', `一次最多下载 ${MAX_ATTACHMENTS} 个附件,当前 ${ids.length} 个`);
|
|
190
|
+
}
|
|
191
|
+
const maxBytes = Number(args.maxBytes ?? MAX_ATTACHMENT_BYTES) || MAX_ATTACHMENT_BYTES;
|
|
192
|
+
const outDirArg = optionalString(args.outDir, 'outDir');
|
|
193
|
+
const outDir = outDirArg ? resolve(outDirArg) : join(env.stateDir, 'attachments');
|
|
194
|
+
await mkdir(outDir, { recursive: true });
|
|
195
|
+
const { items, warnings } = await downloadAttachments(env, ids, outDir, maxBytes);
|
|
196
|
+
const downloaded = items.filter((item) => item.downloaded === true);
|
|
197
|
+
if (downloaded.length === 0) {
|
|
198
|
+
warnings.push('没有任何附件落地成功;如果确认附件 ID 正确,检查登录态与该附件的访问权限');
|
|
199
|
+
}
|
|
200
|
+
return smartExtractSuccess('smart-extract.attachment.fetch', {
|
|
201
|
+
outDir,
|
|
202
|
+
count: downloaded.length,
|
|
203
|
+
requested: ids.length,
|
|
204
|
+
items,
|
|
205
|
+
/** 给模型的下一步:直接读 path,不要再去服务端要「解析文本」。 */
|
|
206
|
+
next: downloaded.length > 0
|
|
207
|
+
? '用宿主文件读取能力打开 items[].path;图片/PDF 走原生视觉或 pdf 技能,不要假设 CLI 已抽文本'
|
|
208
|
+
: null,
|
|
209
|
+
}, { warnings });
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
export const attachmentOperations = [attachmentFetch];
|