dsh-form-fill-agent 0.2.20 → 0.2.21

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 CHANGED
@@ -5,7 +5,7 @@
5
5
  AI填表智能体:支持自动填表、表格填充、表格补全、Excel填表与 Excel回填;使用企查查 MCP 填写 XLSX 空白字段,预览确认后导出新副本。
6
6
 
7
7
  ```sh
8
- dsh plugin --profile web add dsh-form-fill-agent@0.2.20
8
+ dsh plugin --profile web add dsh-form-fill-agent@0.2.21
9
9
  ```
10
10
 
11
11
  请先满足下文的 DSH、连接器及侧边栏依赖要求;安装后完整停止并重启对应 Profile。
@@ -64,7 +64,7 @@ dsh plugin --profile web add dsh-form-fill-agent@latest
64
64
 
65
65
  ## 使用边界与数据保存
66
66
 
67
- 补充要求为模型可读文本;字段或工作表范围请通过向导/工作台修改,不能仅改文字后假定执行范围已同步。任务 schema 5 可读取 schema 1–5;回退旧版本请使用升级前目录副本或独立任务目录。主包为 0.2.20,共享内核为 0.2.10,Provider 为 0.2.2,共享字段契约为 0.1.0。
67
+ 补充要求为模型可读文本;字段或工作表范围请通过向导/工作台修改,不能仅改文字后假定执行范围已同步。任务 schema 5 可读取 schema 1–5;回退旧版本请使用升级前目录副本或独立任务目录。主包为 0.2.21,共享内核为 0.2.10,Provider 为 0.2.2,共享字段契约为 0.1.0。
68
68
 
69
69
  支持企业完整登记名称或 18 位信用代码;简称、主体不一致或多候选不会自动猜选。仅有信用代码的表格也可作为查询锚点。连接候选检索工具时可检索简称,仍需人工确认;缺少工具时降级人工输入。字段映射采用确定性规则及人工确认,不让模型编造事实。支持普通内部公式、固定区域下拉、基础条件格式和普通表格对象;复杂 Excel 结构和 Word 暂不支持,保真边界见下方安全说明。
70
70
 
@@ -72,7 +72,7 @@ dsh plugin --profile web add dsh-form-fill-agent@latest
72
72
 
73
73
  显式设置 DSH_HOME 时,任务保存至其 form-fill-tasks 目录,默认 24 小时过期;未设置时使用内存。任务保存输入表格和归一化预览,不持久化原始 MCP 响应,可主动删除任务。模型及 MCP 凭据由宿主管理。
74
74
 
75
- 0.2.20 保存任务 schema 5,兼容读取旧 schema 1–4;回退旧版本须使用升级前任务目录副本或新目录,防止丢失已确认的字段/主体设置。
75
+ 0.2.21 保存任务 schema 5,兼容读取旧 schema 1–4;回退旧版本须使用升级前任务目录副本或新目录,防止丢失已确认的字段/主体设置。
76
76
 
77
77
  ## 文档与反馈
78
78
 
package/lib/brand.css CHANGED
@@ -60,3 +60,16 @@
60
60
  .ff-ui #wizard-mapping>.card>h2,.ff-ui #wizard-mapping #mapping-next{display:none}
61
61
  .ff-ui #wizard-mapping fieldset{min-width:0}
62
62
  .ff-ui #wizard-mapping .ff-mapping-row{min-width:0}
63
+ /* Progress measures processed work, independently from result quality. */
64
+ #progress-panel { padding: 12px 16px; }
65
+ #task-progress { width: 100%; height: 12px; accent-color: #087bd8; }
66
+ #task-progress[data-ended="true"] { accent-color: #138263; }
67
+ #task-progress::-webkit-progress-bar { background: #e3e9ef; border-radius: 6px; }
68
+ #task-progress::-webkit-progress-value { background: #087bd8; border-radius: 6px; }
69
+ #task-progress[data-ended="true"]::-webkit-progress-value { background: #138263; }
70
+ #progress-label { color: var(--action); font-weight: 600; }
71
+ #progress-label[data-ended="true"] { color: var(--success); }
72
+ .ff-review-count { color: var(--review); font-weight: 600; }
73
+ .ff-failure-count { color: var(--error); font-weight: 600; }
74
+ #wizard-grid { min-width: 0; margin-bottom: 16px; }
75
+ #task-meta, #task-details { overflow-wrap: anywhere; }
package/lib/http.js CHANGED
@@ -7,6 +7,7 @@ import { createTaskStore } from './task-store.js';
7
7
  import { allCandidates, selectCandidates } from './task-model.js';
8
8
  import { gridPage } from './grid.js';
9
9
  import { diagnostics } from './diagnostics.js';
10
+ import { taskPresentation, isResultExplanation } from './task-presentation.js';
10
11
  import { mappingRecommendations, mappingSearchAliases } from './mapping-recommendations.js';
11
12
  const XLSX_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
12
13
  const FIXTURES = ['客户台账', '供应商准入表', '合同主体信息表'];
@@ -17,10 +18,12 @@ export function createFormFillHandler({ basePath = '', getPort, now = Date.now,
17
18
  const controllers=new Map();
18
19
  const validOwner = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
19
20
  const visible = (task, owner) => task && (!task.owner || task.owner === owner);
20
- const metadata = (id, task) => ({ id, filename: task.filename ?? '未命名表格.xlsx', revision: task.revision ?? 1, state: task.state ?? (task.result ? 'completed' : 'preview_ready'), created: task.created, updatedAt: task.updatedAt ?? task.created, expiresAt: task.created + ttlMs, sessionId: task.sessionId, confirmed: !!task.result });
21
+ const metadata = (id, task) => ({ id, presentation:taskPresentation(task), filename: task.filename ?? '未命名表格.xlsx', revision: task.revision ?? 1, state: task.state ?? (task.result ? 'completed' : 'preview_ready'), created: task.created, updatedAt: task.updatedAt ?? task.created, expiresAt: task.created + ttlMs, sessionId: task.sessionId, confirmed: !!task.result });
21
22
  const settings = task => ({
22
23
  mappingProtocol: 2,
23
24
  diagnostics: diagnostics(task.preview),
25
+ resultExplanations: task.preview.changeSet.incomplete.filter(isResultExplanation),
26
+ exceptions: task.preview.changeSet.incomplete.filter(i=>!isResultExplanation(i)),
24
27
  configuration: task.configuration ?? {},
25
28
  selectedFields: task.selectedFields,
26
29
  progress: task.progress,
@@ -134,7 +137,7 @@ export function createFormFillHandler({ basePath = '', getPort, now = Date.now,
134
137
  }
135
138
  const preview = await previewBytes(task.bytes, { configuration, selectedFields, ...(task.analyzeOnly !== false ? { provider: { mode: 'mock', version: '0.1.0-alpha.5', capabilities: [], lookup: async () => ({ status: 'not-found' }) } } : {}) });
136
139
  if (disposed || tasks.get(body.id) !== task || running.has(body.id)) return send(409, { message: '任务已更新,请刷新后重试' });
137
- const updated = { ...task, configuration, selectedFields, preview, baseChangeSet:undefined, revision: (task.revision ?? 1)+1, updatedAt: now(), state: 'preview_ready' };
140
+ const updated = { ...task, configuration, selectedFields, preview, progress:undefined, baseChangeSet:undefined, revision: (task.revision ?? 1)+1, updatedAt: now(), state: 'preview_ready' };
138
141
  tasks.set(body.id,updated);
139
142
  return send(200, { ...preview, ...metadata(body.id,updated), ...settings(updated) });
140
143
  }
@@ -0,0 +1,31 @@
1
+ import { parseWorkbook } from 'form-fill-core';
2
+
3
+ const retained = new Set(['no-data','user-excluded','formula-preserved','hidden-or-merged','hidden-row','hidden-sheet','sheet-excluded','protected-source-range','placeholder-needs-confirmation']);
4
+ export function taskPresentation(task) {
5
+ const items=task.preview.changeSet.incomplete;
6
+ const failures=Math.max(task.state==='failed'?1:0,items.filter(i=>i.reason==='provider-error').length);
7
+ const review=items.filter(i=>i.reason!=='provider-error'&&!retained.has(i.reason)).length;
8
+ const noData=items.filter(i=>i.reason==='no-data').length;
9
+ const running=task.state==='enriching';
10
+ const ended=!running&&(!!task.progress||!!task.result||task.state==='failed');
11
+ const interrupted=['cancelled','interrupted'].includes(task.state);
12
+ const status=running?'处理中':!ended?'待确认字段':task.state==='failed'?'执行失败':review||failures||interrupted?'处理结束(需核验)':noData?'已完成(部分字段无数据)':'已完成';
13
+ const total=task.progress?.total||0,completed=task.progress?.completed||0;
14
+ // A stopped/cancelled run must not imply that all planned items ran.
15
+ const percent=ended&&!interrupted&&task.state!=='failed'?100:total?Math.min(99,Math.floor(completed/total*100)):0;
16
+ const subjects=new Set();
17
+ const document=parseWorkbook(task.bytes);
18
+ for(const table of task.preview.analysis.tables){
19
+ const sheet=document.sheets.find(s=>s.name===table.sheet);
20
+ const cells=new Map(Object.values(sheet?.cells||{}).map(c=>[c.row+':'+c.column,c]));
21
+ const inputs=table.mappings.filter(m=>table.anchorColumns?table.anchorColumns.includes(m.column):table.anchors.includes(m.field));
22
+ for(const row of sheet?.rows||[]){
23
+ if(row.hidden||row.number<=table.headerRow)continue;
24
+ const values=inputs.map(m=>{const c=cells.get(row.number+':'+m.column);return c&&!c.formula&&!c.hidden?c.value.trim():''});
25
+ if(values.some(Boolean))subjects.add(JSON.stringify(values));
26
+ }
27
+ }
28
+ const date=new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hour12:false}).format(new Date(task.created)).replace('/', '-');
29
+ return {title:(task.filename||'未命名表格').replace(/\.xlsx$/i,'')+'|'+subjects.size+' 家企业|'+date,status,running,ended,percent,completed,total,failures,review,noData};
30
+ }
31
+ export const isResultExplanation = item => retained.has(item.reason);
package/lib/ui.html CHANGED
@@ -9,6 +9,8 @@
9
9
  <main id="current">
10
10
  <nav class="ff-stages" aria-label="工作流程"><button data-step="import"><span class="ff-stage-icon" data-icon="upload"></span><span class="ff-stage-label">导入表格</span></button><button data-step="rules"><span class="ff-stage-icon" data-icon="settings"></span><span class="ff-stage-label">字段设置</span></button><button data-step="identity"><span class="ff-stage-icon" data-icon="identity"></span><span class="ff-stage-label">主体核验</span></button><button data-step="preview"><span class="ff-stage-icon" data-icon="table"></span><span class="ff-stage-label">填写预览</span></button><button data-step="download"><span class="ff-stage-icon" data-icon="download"></span><span class="ff-stage-label">确认下载</span></button></nav>
11
11
  <p id="task-meta" class="badge"></p>
12
+ <details><summary>任务详情</summary><p id="task-details"></p></details>
13
+ <div id="progress-panel" hidden><progress id="task-progress" max="100" aria-label="处理进度"></progress><p id="progress-label" role="status"></p><span id="review-count" class="ff-review-count"></span> <span id="failure-count" class="ff-failure-count"></span><p class="muted">100% 只代表处理结束,填写内容需在预览中核验并确认生成副本。</p></div>
12
14
  <div class="toolbar ff-execution-toolbar"><span id="execution-progress" role="status"></span><button id="cancel-run" disabled>取消查询</button><button id="retry-run" disabled>仅重试失败 / 未完成查询</button></div>
13
15
  <details id="grid" hidden><summary>查看完整原表 / 结果表格</summary><p class="muted">全量行列按页查看,隐藏行列只读标注。结果视图展示当前已选填写;下载不受分页或搜索影响。</p><div class="toolbar"><label>工作表 <select id="grid-sheet"></select></label><label>视图 <select id="grid-view"><option value="original">原表</option><option value="result">结果预览</option></select></label><label>搜索全部行 <input id="grid-query" type="search" maxlength="200"></label><button id="grid-search">搜索</button></div><p id="grid-status" role="status"></p><div class="scroll"><table><thead id="grid-head"></thead><tbody id="grid-body"></tbody></table></div><div class="toolbar"><button id="grid-prev">上一页</button><button id="grid-next">下一页</button><button id="grid-left">前 16 列</button><button id="grid-right">后 16 列</button></div></details>
14
16
  <div class="card" data-pane="import"><h2>导入表格</h2><p class="muted">支持 XLSX,最大 8 MiB。支持普通内部公式、固定文本或区域下拉、基础条件格式及普通表格对象;宏、图片、图表及复杂扩展结构暂不支持。上传仅做本地分析,不查询企查查。</p>
@@ -17,10 +19,10 @@
17
19
  <section id="preview" hidden>
18
20
  <div class="card" data-pane="rules"><h2>字段与规则</h2><p id="structure"></p><p id="anchor-alert" role="status"></p><p>默认只填空白。可选择工作表、修正表头行及字段;应用设置会清除旧预览和主体确认,请重新核验。</p><label>搜索字段 <input id="mapping-search" type="search" placeholder="按原表字段名称筛选"></label><p class="muted">未识别字段可手动选择;没有数据来源的字段选择“不填写”。绿色仅表示字段映射已确认,不代表企业已核验或已查询。多个输出位置可分别确认同一字段;定位企业的输入列需明确。规则只保存表头与映射,不含记录。</p><button id="mapping-save">保存字段规则</button><button id="mapping-load">复用字段规则</button><div id="mapping"></div><button id="configure" class="primary">应用字段设置</button><div id="mapping-next" hidden role="status"><p>设置已保存。下一步核验企业主体,确认填写范围后生成指令并发送,查询结果会进入填写预览。</p><button id="mapping-continue" class="primary">下一步:主体核验</button></div></div>
19
21
  <div class="card" data-pane="identity"><h2>主体核验与查询</h2><p id="connection"></p><p>候选不自动选择。查询返回歧义后,可选择返回候选或填写已核验的完整登记名称/信用代码;原表主体文字不覆盖,选择仅用于后续查询。</p><div id="entities"></div><div id="direct-scope" role="status"></div><details id="scope-omissions" hidden><summary>查看未纳入字段</summary><p id="scope-omissions-list"></p></details><label id="direct-ack-label" hidden><input id="direct-ack" type="checkbox">确认仅填写已纳入的原表字段</label><textarea id="direct-command" aria-label="填写指令" readonly hidden></textarea><button id="wizard-open" class="primary">生成填写指令</button><p class="muted">查询不会自动发送;回填后可在原生对话框修改并发送。</p></div>
20
- <div class="card" data-pane="preview"><h2>填写预览</h2><p id="summary"></p><details><summary>逐列填写结果</summary><p class="muted">按单元格统计;整行缺少主体标识的情况另见下方原因分类。</p><div class="scroll"><table><thead><tr><th>原表字段</th><th>映射字段</th><th>预览可填写格数</th><th>未完成项</th></tr></thead><tbody id="field-results"></tbody></table></div></details><p class="muted">每格显示原值、准备填写值和来源。取消勾选后点击“应用选择”,再确认新的预览。</p>
22
+ <div class="card" data-pane="preview"><h2>填写预览</h2><p id="summary"></p><details><summary>结果说明(未披露及保留位置)</summary><p id="result-explanations"></p></details><details><summary>逐列填写结果</summary><p class="muted">按单元格统计;整行缺少主体标识的情况另见下方原因分类。</p><div class="scroll"><table><thead><tr><th>原表字段</th><th>映射字段</th><th>预览可填写格数</th><th>未完成项</th></tr></thead><tbody id="field-results"></tbody></table></div></details><p class="muted">每格显示原值、准备填写值和来源。取消勾选后点击“应用选择”,再确认新的预览。</p>
21
23
  <div class="toolbar"><label>筛选单元格 <input id="result-search" type="search" placeholder="位置、字段或值"></label><span id="result-count" class="muted"></span></div>
22
24
  <div class="scroll"><table><thead><tr><th>位置</th><th>字段</th><th>原值</th><th>准备填写</th><th>依据与来源</th><th>填写</th></tr></thead><tbody id="changes"></tbody></table></div><button id="selection">应用选择</button></div>
23
- <div class="card" data-pane="preview"><h2>未完成项</h2><p id="reason-summary"></p><div class="scroll"><table><thead><tr><th>位置</th><th>字段</th><th>原因</th></tr></thead><tbody id="incomplete"></tbody></table></div></div>
25
+ <div class="card" data-pane="preview"><h2>待核验与失败项</h2><p id="reason-summary"></p><div class="scroll"><table><thead><tr><th>位置</th><th>字段</th><th>原因</th></tr></thead><tbody id="incomplete"></tbody></table></div></div>
24
26
  <div class="card" data-pane="download"><h2>确认并下载</h2><p>原文件不会被覆盖。下载包含全部已确认填写及完整清单,不受当前筛选影响。</p><button id="confirm" class="primary">确认这些填写,生成新副本</button><div id="downloads"></div></div>
25
27
  <details class="ff-task-more"><summary>更多任务操作</summary><div class="controls"><button id="refresh" class="secondary">刷新任务</button><button id="discard" class="secondary">删除任务</button></div></details><div class="ff-next-action" data-pane="preview" hidden><span>核验填充值后继续,下一步生成副本。</span><button id="preview-continue" class="primary">下一步:确认下载</button></div>
26
28
  </section></main>
@@ -28,7 +30,7 @@
28
30
  <nav class="ff-wizard-nav" aria-label="提示词向导步骤"><button data-wizard-step="0"><span class="ff-step-number">1</span> 数据来源</button><button data-wizard-step="1"><span class="ff-step-number">2</span> 填写规则</button><button data-wizard-step="2"><span class="ff-step-number">3</span> 填写字段</button><button data-wizard-step="3"><span class="ff-step-number">4</span> 确认描述</button></nav>
29
31
  <div class="dialog-body">
30
32
  <section class="ff-wizard-step" data-wizard-pane="0"><h3>选择需要填写的原表</h3><p class="muted">识别表头与空白字段,再由企查查 MCP 查询对应的企业信息,填写到原表位置。</p><div class="ff-upload-zone"><label>上传 Excel 表格 <input id="wizard-file" type="file" accept=".xlsx"></label><p class="muted">支持 XLSX,最大 8 MiB。保留已有内容,确认结果后生成新副本。</p></div><p id="wizard-source" class="ff-summary"></p><p class="ff-service-note">完成向导后,将任务描述回填到对话框;发送后使用已连接的企查查 MCP 执行核验与填写。</p></section>
31
- <section class="ff-wizard-step" data-wizard-pane="1"><h3>确认原表字段映射</h3><p id="wizard-rules" hidden></p><div id="wizard-mapping"></div></section>
33
+ <section class="ff-wizard-step" data-wizard-pane="1"><h3>确认原表字段映射</h3><div id="wizard-grid"></div><p id="wizard-rules" hidden></p><div id="wizard-mapping"></div></section>
32
34
  <section class="ff-wizard-step" data-wizard-pane="2"><h3>确认填写范围</h3><p>已确认映射已自动纳入,无需重复选择;下方可按需减少填写范围。</p><div class="toolbar"><label>搜索 <input id="field-search" type="search" placeholder="字段名称"></label><span id="field-count"></span><button id="fields-all">选择可用字段</button><button id="fields-clear">清空可选字段</button></div><p class="muted">主体锚点固定保留;只有原表已映射的字段可选。修改映射请返回第二步。</p><div id="wizard-fields" class="ff-field-grid"></div></section>
33
35
  <section class="ff-wizard-step" data-wizard-pane="3"><h3>确认任务描述</h3><p id="business-summary" class="ff-summary"></p><p id="scope-review" class="ff-summary"></p><details><summary>查看待补空位置与保留列</summary><pre id="wizard-positions" style="white-space:pre-wrap;max-height:240px;overflow:auto"></pre></details><label id="scope-ack-label" hidden><input id="scope-ack" type="checkbox">确认本次不填写以上列</label><label>补充要求<textarea id="requirements" rows="4" maxlength="1000" placeholder="补充核验说明;字段或范围变更请返回前面步骤设置。"></textarea></label><details><summary>兼容执行信息</summary><p id="qcc-command" class="ff-tech"></p></details></section>
34
36
  </div><p id="wizard-message" role="status"></p><footer class="dialog-footer"><button id="wizard-prev">上一步</button><button id="wizard-next" class="primary">下一步</button><button id="draft" class="primary" hidden>回填到对话框</button><button id="copy-command" hidden>复制指令</button></footer></dialog>
@@ -65,7 +67,9 @@ const reasons={'unknown-field':'暂无可用字段映射','no-capability':'尚
65
67
  function controls(value){busy=value;document.querySelectorAll('button').forEach(b=>b.disabled=value);if($('wizard').open)renderWizard();syncActions();if(!value)loadGrid()}
66
68
  function row(target,values,labels){const tr=document.createElement('tr');values.forEach((v,i)=>{const td=document.createElement('td');td.textContent=v;td.dataset.label=labels[i];tr.append(td)});$(target).append(tr);return tr}
67
69
  function syncActions(){
68
- const running=current?.state==='enriching';$('cancel-run').hidden=!running;$('cancel-run').disabled=busy||!running;
70
+ const running=current?.state==='enriching';
71
+ const p=current?.presentation;$('progress-panel').hidden=!p||(!p.running&&!p.ended);if(p){$('task-progress').value=p.percent;$('task-progress').dataset.ended=String(p.ended);$('progress-label').textContent=(p.running?'处理中':p.ended?'处理结束':'待处理')+' · '+p.percent+'% · '+p.completed+' / '+p.total+' 查询计划项';$('progress-label').dataset.ended=String(p.ended);$('review-count').textContent='待核验 '+p.review+' 项';$('failure-count').textContent='失败 '+p.failures+' 项';}
72
+ $('cancel-run').hidden=!running;$('cancel-run').disabled=busy||!running;
69
73
  $('retry-run').hidden=!current||current.confirmed||!current.changeSet.incomplete.some(i=>['provider-error','cancelled','not-started'].includes(i.reason));
70
74
  $('retry-run').disabled=busy||!current||current.confirmed||running||!current.changeSet.incomplete.some(i=>['provider-error','cancelled','not-started'].includes(i.reason));
71
75
  $('execution-progress').textContent=running?(current.progress?.total?'已处理查询计划项 '+(current.progress?.completed||0)+' / '+current.progress.total+'(含失败,不代表填写成功)':'正在准备查询…'):current?.state==='cancelled'?'已取消,成功结果保留。':current?.state==='interrupted'?'上次查询中断,已保存进度,可重试剩余部分。':'';
@@ -99,9 +103,10 @@ function scopeReview(){
99
103
  return {omitted,missing,blocked:!!problem,problem};
100
104
  }
101
105
  let wizardMappingApplied=false;
106
+ const gridHome=document.createComment('grid home');$('grid').before(gridHome);
102
107
  const sharedMapping=document.querySelector('[data-pane="rules"]'),mappingHome=document.createComment('shared mapping home');sharedMapping.before(mappingHome);
103
108
  function renderWizard(){
104
- if($('wizard').open){$('wizard-mapping').append(sharedMapping);sharedMapping.hidden=false}
109
+ if($('wizard').open){$('wizard-mapping').append(sharedMapping);sharedMapping.hidden=false;$('wizard-grid').append($('grid'));if(wizardStep===1){$('grid').open=true;loadGrid()}}
105
110
  initWizard();
106
111
  document.querySelectorAll('[data-wizard-pane]').forEach(p=>p.setAttribute('aria-current',String(Number(p.dataset.wizardPane)===wizardStep)));
107
112
  document.querySelectorAll('[data-wizard-step]').forEach(p=>p.setAttribute('aria-current',String(Number(p.dataset.wizardStep)===wizardStep)));
@@ -128,7 +133,7 @@ function renderWizard(){
128
133
  $('draft').hidden=wizardStep!==3;$('copy-command').hidden=wizardStep!==3;$('draft').disabled=!current||!wizardFields.size||busy||review.blocked;$('copy-command').disabled=$('draft').disabled;
129
134
  }
130
135
  function openWizard(retry=false){retryIntent=retry===true;initWizard();renderWizard();if(!$('wizard').open)$('wizard').showModal();renderWizard();if(parent!==window){document.body.classList.add('ff-modal-host');parent.postMessage({type:'ff-wizard-state',open:true},location.origin)}}
131
- function closeWizard(focusComposer=false){saveWizard();$('draft-conflict').close();$('wizard').close();mappingHome.after(sharedMapping);sharedMapping.hidden=step!=='rules';document.body.classList.remove('ff-modal-host');if(parent!==window)parent.postMessage({type:'ff-wizard-state',open:false,focusComposer},location.origin);if(!focusComposer)$('wizard-open').focus()}
136
+ function closeWizard(focusComposer=false){saveWizard();$('draft-conflict').close();$('wizard').close();mappingHome.after(sharedMapping);gridHome.after($('grid'));sharedMapping.hidden=step!=='rules';document.body.classList.remove('ff-modal-host');if(parent!==window)parent.postMessage({type:'ff-wizard-state',open:false,focusComposer},location.origin);if(!focusComposer)$('wizard-open').focus()}
132
137
  async function applyScope(){
133
138
  if(!current||!wizardFields.size)throw Error('请至少选择一个已映射的填写字段');
134
139
  const review=scopeReview();if(review.blocked)throw Error('没有可用主体标识,请先到字段设置映射企业名称列。');
@@ -165,7 +170,7 @@ function highlightMappingConflicts(){
165
170
  for(const section of $('mapping').querySelectorAll('fieldset')){
166
171
  const fields=[...section.querySelectorAll('select[data-column]')];
167
172
  for(const field of fields)field.closest('.ff-mapping-row').updateMappingStatus?.();
168
- for(const field of fields){const peers=fields.filter(other=>other.value===field.value);const conflict=!!field.value&&peers.length>1&&(peers.some(other=>other.dataset.manual!=='true')||(field.dataset.primary==='true'&&peers.filter(other=>other.closest('.ff-mapping-row').querySelector('.ff-mapping-role').value!=='output').length>1));field.setAttribute('aria-invalid',String(conflict));const row=field.closest('.ff-mapping-row');row.classList.toggle('ff-mapping-conflict',conflict);if(conflict){const message=row.querySelector('.ff-mapping-status');message.dataset.state='pending';message.textContent='待人工确认:重复位置需逐一确认;企业标识需保留唯一定位列。';}}
173
+ for(const field of fields){const peers=fields.filter(other=>other.value===field.value);const conflict=!!field.value&&peers.length>1&&(field.dataset.primary==='true'&&peers.filter(other=>other.closest('.ff-mapping-row').querySelector('.ff-mapping-role').value!=='output').length>1);field.setAttribute('aria-invalid',String(conflict));const row=field.closest('.ff-mapping-row');row.classList.toggle('ff-mapping-conflict',conflict);if(conflict){const message=row.querySelector('.ff-mapping-status');message.dataset.state='pending';message.textContent='待人工确认:重复位置需逐一确认;企业标识需保留唯一定位列。';}}
169
174
  }
170
175
  }
171
176
  function filterResults(){const query=$('result-search').value.trim().toLowerCase(),rows=[...$('changes').rows];let shown=0;for(const tr of rows){tr.hidden=!!query&&!tr.textContent.toLowerCase().includes(query);if(!tr.hidden)shown++}const selected=rows.filter(tr=>tr.querySelector('input')?.checked).length;$('result-count').textContent=rows.length?'显示 '+shown+' / '+rows.length+' 格 · 已选 '+selected+' 格'+(!shown?' · 无匹配结果':''):'暂无可填写单元格'}
@@ -268,19 +273,20 @@ function render(data){
268
273
  current=data;directScope();$('direct-command').hidden=true;filename=(data.filename||'已填表格.xlsx').replace(/\.xlsx$/i,'');location.hash='task='+data.id;
269
274
  if(gridTask!==data.id){gridTask=data.id;gridPageNumber=1;gridColumn=1;$('grid-sheet').replaceChildren();$('grid-query').value=''}$('grid').hidden=false;loadGrid();
270
275
  if(parent!==window)parent.postMessage({type:'ff-task',taskId:data.id},location.origin);
271
- $('incomplete').closest('.card').style.display=data.changeSet.incomplete.length?'':'none';$('changes').replaceChildren();$('incomplete').replaceChildren();$('downloads').replaceChildren();
276
+ $('incomplete').closest('.card').style.display=(data.exceptions||data.changeSet.incomplete).length?'':'none';$('changes').replaceChildren();$('incomplete').replaceChildren();$('downloads').replaceChildren();
272
277
  $('task-meta').dataset.state=data.state;
273
- $('task-meta').textContent=(data.filename||'表格')+' · '+({'enriching':'查询中','completed':'已生成副本'+(data.changeSet.incomplete.length?',仍有 '+data.changeSet.incomplete.length+' 项未完成':''),'interrupted':'查询中断,请重新核验','partial':'部分完成','preview_ready':'可核验'}[data.state]||data.state)+' · 有效期至 '+new Date(data.expiresAt).toLocaleString();
278
+ $('task-meta').textContent=(data.presentation?.title||data.filename)+' · '+(data.presentation?.status||data.state);$('task-details').textContent='任务 ID:'+data.id+' · 有效期至 '+new Date(data.expiresAt).toLocaleString();
274
279
  $('summary').textContent='可填写 '+data.changeSet.changes.length+' 格 · '+(data.plan.paidCalls?'企查查来源':'本地分析 / 合成示例 · 费用 0')+' · 未完成 '+data.changeSet.incomplete.length+' 项';
280
+ $('result-explanations').textContent=(data.resultExplanations||[]).map(i=>(i.sheet||'')+' '+(i.cell||'')+':'+(data.diagnostics?.reasons.find(r=>r.code===i.reason)?.label||i.reason)).join(';')||'暂无。';
275
281
  $('structure').textContent=data.analysis.tables.map(t=>t.sheet+':表头第 '+t.headerRow+' 行').join(';');
276
282
  renderSettings(data);
277
283
  for(const c of data.candidates||data.changeSet.changes){const tr=row('changes',[c.sheet+' ! '+c.cell,c.label,c.oldValue||'(空白)',c.newValue,(c.source.startsWith('qcc://')?'企查查 · '+c.source.slice(6):'合成示例')+' · 获取于 '+c.acquiredAt.slice(0,10)+' · 明确字段映射'],['位置','字段','原值','准备填写','来源']);const td=document.createElement('td'),check=document.createElement('input');check.type='checkbox';check.checked=(data.selectedIds||data.changeSet.changes.map(x=>x.id)).includes(c.id);check.value=c.id;check.disabled=data.confirmed;check.setAttribute('aria-label','填写 '+c.cell);td.append(check);tr.append(td)}
278
- for(const i of data.changeSet.incomplete)row('incomplete',[i.sheet+' '+(i.cell||('第 '+i.row+' 行')),i.label||'—',i.detail||data.diagnostics?.reasons.find(r=>r.code===i.reason)?.label||reasons[i.reason]||'此项需要人工处理'],['位置','字段','原因']);
284
+ for(const i of data.exceptions||data.changeSet.incomplete)row('incomplete',[i.sheet+' '+(i.cell||('第 '+i.row+' 行')),i.label||'—',i.detail||data.diagnostics?.reasons.find(r=>r.code===i.reason)?.label||reasons[i.reason]||'此项需要人工处理'],['位置','字段','原因']);
279
285
  $('field-results').replaceChildren();
280
286
  for(const column of data.diagnostics?.columns||[])row('field-results',[column.label,(data.catalog.find(f=>f.key===column.field)?.label||'未映射 / 不填写'),column.ready,column.incomplete],['原表字段','映射字段','预览可填写格数','未完成项']);
281
287
  $('preview').hidden=false;if(data.confirmed)downloads();$('qcc-command').textContent=command();
282
288
  initWizard();filterResults();syncActions();if($('wizard').open)renderWizard();
283
- $('reason-summary').textContent=(data.diagnostics?.reasons||[]).map(r=>r.label+':'+r.count+r.unit).join(';')||'暂无未完成项。';
289
+ $('reason-summary').textContent=(data.diagnostics?.reasons||[]).filter(r=>(data.exceptions||data.changeSet.incomplete).some(i=>i.reason===r.code)).map(r=>r.label+':'+r.count+r.unit).join(';')||'暂无待核验或失败项。';
284
290
  const missing=data.analysis.incomplete.filter(i=>i.reason==='missing-anchor');
285
291
  $('anchor-alert').textContent=missing.length?'有 '+missing.length+' 行缺少可用主体标识。请把实际包含名称的列映射为“企业名称”,或提供非空信用代码;当前不会查询这些行。':'';
286
292
  }
@@ -288,7 +294,7 @@ async function restore(silent=false){if(busy||!current&& !location.hash)return;c
288
294
  async function preview(buffer,name,demo=false){controls(true);try{const bytes=new Uint8Array(buffer);if(bytes.length>8388608)throw Error('文件超过 8 MiB');let binary='';for(let i=0;i<bytes.length;i+=32768)binary+=String.fromCharCode(...bytes.subarray(i,i+32768));$('grid').open=true;render(await api('/preview',{base64:btoa(binary),filename:name,sessionId,analyzeOnly:!demo}));navigate(demo?'preview':'rules');$('status').textContent='预览已准备好,请检查后确认。'}catch(e){$('status').textContent=e.message;$('wizard-message').textContent=e.message}finally{controls(false)}}
289
295
  document.querySelectorAll('[data-step]').forEach(b=>b.onclick=()=>navigate(b.dataset.step));
290
296
  $('file').onchange=async()=>{const input=$('file'),f=input.files[0];if(!f||busy)return;input.disabled=true;controls(true);$('status').textContent='正在自动解析表格…';try{await preview(await f.arrayBuffer(),f.name)}catch(e){$('status').textContent=e.message}finally{input.disabled=false;input.value='';controls(false)}};
291
- function readMapping(){const configuration={sheets:[],headers:[],mappings:[]};for(const section of $('mapping').querySelectorAll('fieldset')){if(!section.querySelector('.sheet-enabled').checked)continue;const sheet=section.dataset.sheet;configuration.sheets.push(sheet);configuration.headers.push({sheet,row:Number(section.querySelector('.header-row').value)});for(const field of section.querySelectorAll('[data-column]'))if(field.dataset.manual==='true')configuration.mappings.push({sheet,column:Number(field.dataset.column),field:field.value||null,...(field.dataset.primary==='true'?{role:field.closest('.ff-mapping-row').querySelector('.ff-mapping-role').value}:{})})}return configuration}
297
+ function readMapping(){const configuration={sheets:[],headers:[],mappings:[]};for(const section of $('mapping').querySelectorAll('fieldset')){if(!section.querySelector('.sheet-enabled').checked)continue;const sheet=section.dataset.sheet;configuration.sheets.push(sheet);configuration.headers.push({sheet,row:Number(section.querySelector('.header-row').value)});for(const field of section.querySelectorAll('[data-column]'))if(field.value||field.dataset.manual==='true')configuration.mappings.push({sheet,column:Number(field.dataset.column),field:field.value||null,...(field.dataset.primary==='true'?{role:field.closest('.ff-mapping-row').querySelector('.ff-mapping-role').value}:{})})}return configuration}
292
298
  function mappingSignature(configuration){return JSON.stringify(configuration.headers.map(h=>({sheet:h.sheet,row:h.row,cells:current.structure.find(s=>s.name===h.sheet)?.rows.find(r=>r.number===h.row)?.cells}))) }
293
299
  $('mapping-save').onclick=()=>{try{if(!current||busy)return;const configuration=readMapping();localStorage.setItem('ff-mapping:'+owner,JSON.stringify({schema:1,signature:mappingSignature(configuration),configuration}));$('status').textContent='字段规则已保存在本浏览器。'}catch{$('status').textContent='浏览器无法保存字段规则。'}};
294
300
  $('mapping-load').onclick=async()=>{if(!current||busy)return;controls(true);try{const saved=JSON.parse(localStorage.getItem('ff-mapping:'+owner)||'null');if(saved?.schema!==1||saved.signature!==mappingSignature(saved.configuration))throw Error('没有与当前工作表及表头一致的规则,请手动设置。');render(await api('/configure',{id:current.id,configuration:saved.configuration}));$('status').textContent='字段规则已复用,请检查后重新核验。'}catch(e){$('status').textContent=e.message}finally{controls(false)}};
@@ -298,7 +304,7 @@ $('confirm').onclick=async()=>{if(!current||busy)return;controls(true);try{await
298
304
  $('selection').onclick=async()=>{if(!current||busy)return;controls(true);try{render(await api('/select',{id:current.id,selectedIds:[...$('changes').querySelectorAll('input:checked')].map(x=>x.value)}));$('status').textContent='选择已应用,请核对新的预览。'}catch(e){$('status').textContent=e.message}finally{controls(false)}};
299
305
  $('refresh').onclick=()=>restore();
300
306
  $('discard').onclick=async()=>{if(!current||busy)return;controls(true);try{await api('/discard',{id:current.id});current=null;history.replaceState(null,'',location.pathname+location.search);$('preview').hidden=true;$('grid').hidden=true;gridTask=null;navigate('import');$('status').textContent='任务及保存的表格已删除。'}catch(e){$('status').textContent=e.message}finally{controls(false)}};
301
- $('history-tab').onclick=async()=>{try{const list=await api('/tasks');$('history-list').replaceChildren();for(const item of list){const div=document.createElement('div');div.className='history-item';const button=document.createElement('button');button.textContent=item.filename+' · '+item.state;button.onclick=()=>{location.hash='task='+item.id;restore()};div.append(button);$('history-list').append(div)}$('history').hidden=false;$('current').hidden=true;$('current-tab').setAttribute('aria-pressed','false');$('history-tab').setAttribute('aria-pressed','true');if(!list.length)$('history-list').textContent='暂无可恢复的任务。'}catch(e){$('status').textContent=e.message}};
307
+ $('history-tab').onclick=async()=>{try{const list=await api('/tasks');$('history-list').replaceChildren();for(const item of list){const div=document.createElement('div');div.className='history-item';const button=document.createElement('button');button.textContent=(item.presentation?.title||item.filename)+' · '+(item.presentation?.status||item.state);button.onclick=()=>{location.hash='task='+item.id;restore()};const details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='任务详情';details.append(summary,document.createTextNode('任务 ID:'+item.id));div.append(button,details);$('history-list').append(div)}$('history').hidden=false;$('current').hidden=true;$('current-tab').setAttribute('aria-pressed','false');$('history-tab').setAttribute('aria-pressed','true');if(!list.length)$('history-list').textContent='暂无可恢复的任务。'}catch(e){$('status').textContent=e.message}};
302
308
  $('current-tab').onclick=()=>navigate(step);
303
309
  $('wizard-open').onclick=()=>directDraft();$('wizard-close').onclick=()=>closeWizard();$('wizard').addEventListener('cancel',e=>{e.preventDefault();closeWizard()});
304
310
  document.querySelectorAll('[data-wizard-step]').forEach(b=>b.onclick=()=>{const next=Number(b.dataset.wizardStep);wizardStep=next>1&&wizardMappingApplied!==JSON.stringify([current?.id,readMapping()])?1:next;saveWizard();renderWizard()});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-form-fill-agent",
3
- "version": "0.2.20",
3
+ "version": "0.2.21",
4
4
  "private": false,
5
5
  "description": "AI form filling and spreadsheet autofill for XLSX in DeepSeek Harness, using authorized Qichacha MCP facts with cell previews, user confirmation and export to a new copy.",
6
6
  "repository": {