feat(dsh): add durable supervision, scheduling and operations dock
This commit is contained in:
1 parent
f861a3d386
commit
736b582bc1
46 files changed
+4122
-93
No files matched your search
@@ -1,7 +1,7 @@
|
||||
window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
|
||||
const React=require('react'),h=React.createElement;
|
||||
const {IconSettingsOutlineMedium}=require('@deepseek-ai/dsh-client-ui-primitives');
|
||||
const names={observe:'待命',draft:'待配置',configuring:'待配置',running:'执行中',paused:'已暂停',completed:'已完成',blocked:'已阻断',uncertain:'待核验',failed:'失败'};
|
||||
const names={observe:'待命',draft:'待配置',ready:'待执行',deleted:'已归档',configuring:'待配置',running:'执行中',paused:'已暂停',completed:'已完成',blocked:'已阻断',uncertain:'待核验',failed:'失败'};
|
||||
const stages={collecting:'收集异常证据',analyzing:'AI 自动诊断中',retrying:'按规则重试中',verifying:'核验实际执行结果',
|
||||
reflecting:'AI 复盘与补充诊断中',resolved:'处理结果已通过核验',pending_issue:'证据已保存,工单待完整提交',escalated:'证据已保存并提交 Git 工单'};
|
||||
function ToolSettings(){
|
||||
@@ -11,7 +11,7 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
|
||||
h('h3',null,'工作方式'),
|
||||
h('p',null,'在顶部切换任务中心和 DSH助手。会话、任务选择和未发送草稿会保留。'),
|
||||
h('h3',null,'任务能力'),
|
||||
h('ul',null,...['在对话中创建任务、查找和切换任务、复制配置到新工程','修改名称、备注、Value 策略与已有规则,预览同批影响后确认;归档保留证据','执行前预检所选任务,显示阻断原因;确认工程范围后启动或继续现有队列','对话请求安全暂停,返回实际保存、失败与未命中计数','异常后自动创建诊断会话,收集证据','已授权执行遇到明确失败时,按规则最多重试一次并核验','无法解决时复盘,保存诊断和完整证据链,尝试提交 Git 工单'].map(text=>h('li',{key:text},text))),
|
||||
h('ul',null,...['在对话中创建和修改任务;具体工程与执行范围由原生窗口确认','实时监管当前执行、阶段、耗时与保存/失败/未命中计数','保存执行回执,重启后核对原队列并手动确认恢复','预览精确位号影响;仅有料号映射时明确标记未知匹配数量','检索历史异常经验,仅将持久化核验通过的记录标为已验证','只读同步已有 Git 工单状态与评论,查看本地证据','查看会话 Token、耗时与超时状态,配置响应时限并停止模型生成','设置任务优先级、执行时间与依赖,通过原生窗口确认排期'].map(text=>h('li',{key:text},text))),
|
||||
h('h3',null,'模型与数据'),
|
||||
h('p',null,'使用主工具配置的模型,在输入框下方选择。会话保存在本机任务中心数据目录。'),
|
||||
h('h3',null,'异常工单'),
|
||||
@@ -24,23 +24,10 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
|
||||
border:0,borderRadius:10,background:'transparent',color:'var(--dsw-alias-label-primary)',cursor:'pointer',font:'inherit'}},
|
||||
h(IconSettingsOutlineMedium,{size:18}),wide&&'工具设置');
|
||||
}
|
||||
function TaskPanel(){
|
||||
const[data,setData]=React.useState(null),[notice,setNotice]=React.useState('');
|
||||
React.useEffect(()=>{
|
||||
let live=true;
|
||||
const read=()=>fetch('/dx/context').then(r=>{if(!r.ok)throw Error();return r.json();}).then(v=>{if(live)setData(v);}).catch(()=>{if(live)setNotice('任务上下文暂不可用');});
|
||||
read();const timer=setInterval(read,1500);return()=>{live=false;clearInterval(timer);};
|
||||
},[]);
|
||||
async function request(action){
|
||||
setNotice('等待任务中心确认…');
|
||||
try{
|
||||
const response=await fetch('/dx/action',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action,task_id:data.task_id,revision:data.revision})});
|
||||
setNotice(response.ok?'请求已交给任务中心,请在工具中确认。':'任务状态已改变,请刷新后重试。');
|
||||
}catch{setNotice('任务服务暂不可用,请稍后重试。');}
|
||||
}
|
||||
function OverviewPanel({data,notice,request}){
|
||||
const section=(title,text)=>h('section',{style:{marginBottom:24}},h('h3',{style:{fontSize:14,fontWeight:500,marginBottom:10}},title),
|
||||
h('div',{style:{whiteSpace:'pre-wrap',color:'var(--dsw-alias-label-secondary)',lineHeight:1.8}},text));
|
||||
return h('div',{'data-testid':'dx-task-panel',style:{padding:20,overflow:'auto',height:'100%',boxSizing:'border-box'}},
|
||||
return h('div',{'data-testid':'dx-task-overview'},
|
||||
section('当前任务',data?(data.task_name||data.task_id||'尚未选择任务'):'读取中…'),
|
||||
data?.lifecycle?.request_id&&h('section',{'data-testid':'dx-task-lifecycle',style:{marginBottom:24}},
|
||||
h('h3',{style:{fontSize:14,fontWeight:500}},data.lifecycle.title||'对话任务操作'),
|
||||
@@ -82,6 +69,180 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
|
||||
section('能力边界','任务修改与执行展示具体范围后由原生窗口确认;预检核对保存的配置,不代表 CAD 已连通。\n自动诊断只读事件快照,处理沿用既有执行规则;不确定状态保留现场,转人工与工单。'),
|
||||
section('监管记录',(data?.events||[]).join('\n')||'等待任务事件'));
|
||||
}
|
||||
const secondary='var(--dsw-alias-label-secondary)';
|
||||
const border='1px solid var(--dsw-alias-border-l2)';
|
||||
const buttonStyle={border,background:'var(--dsw-alias-bg-base)',color:'var(--dsw-alias-label-primary)',borderRadius:8,padding:'7px 10px',font:'inherit',fontSize:12,cursor:'pointer'};
|
||||
const stateNames={...names,pending:'待执行',claimed:'已领取',interrupted:'执行中断',cancelled:'已取消',synced:'已同步',not_synced:'尚未同步',unavailable:'暂不可用',open:'处理中',closed:'已关闭',idle:'待命',generating:'生成中',timeout:'响应超时',error:'出错',finished:'已结束'};
|
||||
const blockers={queue_missing:'原队列检查点不存在',queue_invalid:'原队列证据无效',interrupted:'存在待核验步骤',failed_items:'仍有失败项',plan_changed:'保存计划已变化',task_unavailable:'任务不可用',task_paused:'任务已手动暂停,请先核对并接续原执行',not_due:'尚未到执行时间',worker_busy:'执行器忙碌',already_claimed:'排期已被领取',finished:'排期已结束',preflight_blocked:'执行预检未通过',preflight_unavailable:'执行预检不可用',dependency_incomplete:'依赖任务尚未完成并通过核验'};
|
||||
const display=value=>value===null||value===undefined||value===''?'未报告':String(value);
|
||||
const status=value=>stateNames[value]||display(value);
|
||||
const count=value=>Number.isFinite(value)?value.toLocaleString():'未报告';
|
||||
const time=value=>{if(!value)return '未设置';const stamp=new Date(value);return Number.isNaN(stamp.getTime())?String(value):stamp.toLocaleString();};
|
||||
const elapsed=value=>Number.isFinite(value)?`${Math.max(0,Math.floor(value))} 秒`:'未报告';
|
||||
const detail=(label,value)=>h('p',{style:{fontSize:12,lineHeight:1.7,margin:'5px 0',overflowWrap:'anywhere'}},h('span',{style:{color:secondary}},label+':'),value);
|
||||
const empty=text=>h('p',{style:{fontSize:12,lineHeight:1.8,color:secondary}},text);
|
||||
const card=(key,title,...children)=>h('section',{key,style:{border,borderRadius:10,padding:12,marginBottom:12,overflowWrap:'anywhere'}},h('h3',{style:{fontSize:13,margin:'0 0 8px',fontWeight:500}},title),...children);
|
||||
const button=(testid,title,onClick,disabled=false)=>h('button',{'data-testid':testid,type:'button',disabled,onClick,style:{...buttonStyle,opacity:disabled?0.5:1}},title);
|
||||
const actions=(...children)=>h('div',{style:{display:'flex',flexWrap:'wrap',gap:8,margin:'10px 0'}},...children);
|
||||
const counterLine=value=>`已保存 ${count(value?.saved_items)} · 失败 ${count(value?.failed_items)} · 未命中 ${count(value?.no_match_items)}`;
|
||||
const blockerList=values=>values?.length?detail('阻断原因',values.map(value=>blockers[value]||value).join(';')):null;
|
||||
function ImpactPanel({report,scope,perform,pending}){
|
||||
const rows=report?.rows||[];
|
||||
const policy=row=>row.value_policy==='preserve'?'保留原 Value':row.value_policy==='custom'?'自定义 Value':'复制元件库标签(实际值待执行读取)';
|
||||
const columns=['范围','工程 / 图页','位号 / UID','旧料号 → 新料号','旧 Value → 拟议 Value','Cell / NC'];
|
||||
return h('div',{'data-testid':'dx-operations-impact'},
|
||||
actions(button('dx-impact-refresh','查看当前任务影响',()=>perform({operation:'impact',task_ids:scope}),pending||!scope.length)),
|
||||
!report?empty('选择任务后查看保存计划中的影响范围。'):h(React.Fragment,null,
|
||||
detail('范围',report.coverage==='exact'?'已保存的精确位号计划':report.coverage==='mapping_only'?'仅料号映射':'精确位号与料号映射'),
|
||||
detail('元件数量',report.component_count===null?'未知:映射尚未收集匹配元件':count(report.component_count)),
|
||||
report.component_count===null&&detail('已知位号范围',count(report.known_component_count)),
|
||||
detail('已启用范围',`${count(report.enabled_scope)} 条位号 / 映射`),
|
||||
empty('按已保存计划展示。仅有料号映射时,匹配元件的数量、位号和 UID 尚未知。'),
|
||||
h('div',{style:{overflowX:'auto'}},h('table',{'data-testid':'dx-impact-table',style:{borderCollapse:'collapse',width:'100%',fontSize:11,textAlign:'left'}},
|
||||
h('thead',null,h('tr',null,...columns.map(title=>h('th',{key:title,style:{borderBottom:border,padding:8,whiteSpace:'nowrap',fontWeight:500}},title)))),
|
||||
h('tbody',null,...rows.map((row,index)=>h('tr',{key:row.task_id+':'+(row.uid||index),'data-testid':'dx-impact-row',style:{opacity:row.enabled?1:.6}},
|
||||
h('td',{style:{padding:8,borderBottom:border}},row.enabled?'已启用':'已禁用',h('br'),row.coverage==='mapping_only'?'映射 · 数量未知':`${row.component_count} 个元件`),
|
||||
h('td',{style:{padding:8,borderBottom:border,overflowWrap:'anywhere'}},row.project||'工程范围未知',h('br'),row.coverage==='mapping_only'?'图页未知':`${row.schematic_name} / ${row.sheet}`),
|
||||
h('td',{style:{padding:8,borderBottom:border}},row.refdes||'位号未知',h('br'),row.uid||'UID 未知'),
|
||||
h('td',{style:{padding:8,borderBottom:border}},row.old_part_number+' → '+row.new_part_number),
|
||||
h('td',{style:{padding:8,borderBottom:border}},(row.old_value===null?'未知':display(row.old_value))+' → '+(row.proposed_value===null?'待执行读取':display(row.proposed_value)),h('br'),policy(row)),
|
||||
h('td',{style:{padding:8,borderBottom:border}},row.target_cell||'按保存的默认 Cell 策略',h('br'),row.sync_nc?'同步 NC':'保留 NC')))))),
|
||||
!rows.length&&empty('保存范围内没有位号或映射行。'),
|
||||
detail('显示范围',`${count(report.returned_rows)} / ${count(report.total_rows)} 行${report.truncated?`,省略 ${count(report.omitted_row_count)} 行`:''}`),
|
||||
report.truncated&&empty('完整计划哈希包含省略的行。'),
|
||||
h('details',null,h('summary',{style:{fontSize:12,cursor:'pointer'}},'范围与计划凭据'),
|
||||
detail('完整范围指纹',report.full_fingerprint||report.fingerprint),
|
||||
...Object.entries(report.plan_hashes||{}).map(([id,hash])=>h('p',{key:id,style:{fontSize:10,overflowWrap:'anywhere'}},id+':'+hash)))));
|
||||
}
|
||||
function RunningPanel({operations,perform,pending,request}){
|
||||
const run=operations.live_run||{},last=operations.last_execution;
|
||||
return h('div',{'data-testid':'dx-operations-running'},
|
||||
card('live','当前执行',detail('状态',run.active?'执行中':'当前无执行中的队列'),
|
||||
detail('任务',run.name||run.task_id||'—'),detail('执行编号',run.run_id||'—'),
|
||||
detail('阶段',run.stage||'—'),run.message&&detail('进度说明',run.message),detail('耗时',elapsed(run.elapsed_seconds)),
|
||||
detail('实际结果',counterLine(run)),detail('步骤',`${count(run.completed_items)} / ${count(run.total_items)}`),
|
||||
run.pause_requested&&empty('已请求安全暂停,当前步骤结束后停止。'),
|
||||
run.active&&button('dx-running-pause',run.pause_requested?'已请求安全暂停':'安全暂停',()=>perform({operation:'pause',task_ids:run.task_ids||[]}),run.pause_requested||!run.task_ids?.length)),
|
||||
last&&card('last','最近一次执行回执',detail('状态',status(last.status)),
|
||||
...(last.tasks||[]).map(task=>h('div',{key:task.task_id,style:{marginTop:8}},detail('任务',task.name||task.task_id),detail('实际结果',counterLine(task)),blockerList(task.blockers))),
|
||||
!last.tasks?.length&&detail('实际结果',counterLine(last))),
|
||||
actions(button('dx-history-refresh','刷新执行历史',()=>perform({operation:'history'}),pending)),
|
||||
...(operations.runs||[]).map(row=>card(row.run_id,'执行 '+row.run_id,
|
||||
detail('状态',status(row.status)),detail('开始时间',time(row.started_utc)),detail('原任务顺序',(row.task_ids||[]).join(' → ')),
|
||||
detail('实际结果',counterLine(row.counters)),
|
||||
...(row.tasks||[]).map(task=>h('p',{key:task.task_id,style:{fontSize:11}},(task.name||task.task_id)+' · '+counterLine(task))),
|
||||
blockerList(row.blockers),row.resume_ready===true?button('dx-resume-'+row.run_id,'核对并恢复原队列',()=>perform({operation:'resume',run_id:row.run_id}),pending):empty('当前没有可直接恢复的原队列。'))),
|
||||
!operations.runs?.length&&empty('暂无保存的执行历史。'));
|
||||
}
|
||||
function SchedulesPanel({operations,scope,perform,pending}){
|
||||
const priorities={low:'低',normal:'普通',high:'高',urgent:'紧急'};
|
||||
return h('div',{'data-testid':'dx-operations-schedules'},
|
||||
actions(button('dx-schedule-new','为当前任务设置排期',()=>perform({operation:'schedule_dialog',task_ids:scope}),pending||!scope.length),
|
||||
button('dx-schedules-refresh','刷新排期',()=>perform({operation:'refresh'}),pending)),
|
||||
empty('时间按本机时区显示。排期在工具打开期间检查,执行前仍需核对保存范围与实际预检。'),
|
||||
...(operations.schedules||[]).map(row=>card(row.schedule_id,row.title||'任务排期',
|
||||
detail('状态',status(row.status)),detail('优先级',priorities[row.priority]||display(row.priority)),detail('不早于',time(row.not_before)),
|
||||
detail('截止时间',time(row.due_at)),detail('任务',(row.task_ids||[]).join(' → ')),detail('依赖',(row.dependencies||[]).join('、')||'无'),
|
||||
detail('执行方式',row.auto_start?'已保存自动启动意图,依原生授权与预检执行':'等待手动确认'),
|
||||
blockerList(row.blockers),actions(
|
||||
button('dx-schedule-run-'+row.schedule_id,'核对并执行',()=>perform({operation:'run_schedule',schedule_id:row.schedule_id}),pending||row.ready!==true),
|
||||
button('dx-schedule-cancel-'+row.schedule_id,'取消排期',()=>perform({operation:'cancel_schedule',schedule_id:row.schedule_id}),pending||row.status!=='pending')))),
|
||||
!operations.schedules?.length&&empty('暂无排期。'));
|
||||
}
|
||||
function ExperiencesPanel({operations,perform,pending}){
|
||||
const[query,setQuery]=React.useState('');
|
||||
return h('div',{'data-testid':'dx-operations-experiences'},
|
||||
h('label',{style:{fontSize:12}},'异常代码或关键词',h('input',{'data-testid':'dx-experience-query',value:query,onChange:event=>setQuery(event.target.value),maxLength:160,placeholder:'留空查看已有经验',style:{...buttonStyle,width:'100%',boxSizing:'border-box',marginTop:8,cursor:'text'}})),
|
||||
actions(button('dx-experience-search','检索本地经验',()=>perform({operation:'experience',issue_code:query}),pending)),
|
||||
...(operations.experiences||[]).map(row=>card(row.incident_id,row.issue_code||'异常经验',
|
||||
h('span',{'data-testid':'dx-experience-verification',style:{fontSize:11,padding:'3px 7px',border,borderRadius:6}},row.verified===true?'已验证':'未验证'),
|
||||
detail('任务',row.task_name||row.task_id),detail('异常',row.message||'—'),
|
||||
...(row.analyses||[]).map((analysis,index)=>h('p',{key:index,style:{fontSize:12,whiteSpace:'pre-wrap'}},analysis.phase+':'+analysis.reply)),
|
||||
row.retry_skipped&&detail('处理限制',row.retry_skipped),
|
||||
row.verification&&detail('核验结果',counterLine(row.verification)),
|
||||
detail('证据',(row.evidence_refs||[]).join('\n')||'暂无持久化证据'),
|
||||
button('dx-experience-open-'+row.incident_id,'打开事件证据',()=>perform({operation:'open_incident',incident_id:row.incident_id}),pending))),
|
||||
!operations.experiences?.length&&empty('暂无匹配的本地经验。经验建议不代表已授权执行。'));
|
||||
}
|
||||
function TicketsPanel({operations,perform,pending}){
|
||||
return h('div',{'data-testid':'dx-operations-tickets'},
|
||||
actions(button('dx-tickets-refresh','读取工单列表',()=>perform({operation:'tickets'}),pending)),
|
||||
empty('仅同步已有事件绑定的工单。工单关闭是反馈,本地修复结果以实际核验为准。'),
|
||||
...(operations.tickets||[]).map(row=>card(row.incident_id,row.title||('工单 '+(row.number||'')),
|
||||
detail('工单状态',status(row.state)),detail('同步状态',status(row.status)),detail('上次同步',time(row.last_sync_at)),
|
||||
detail('工单地址',row.url||'尚未获取'),row.error&&detail('同步问题',row.error),
|
||||
...(row.comments||[]).map((comment,index)=>h('blockquote',{key:comment.id||index,style:{margin:'10px 0',paddingLeft:10,borderLeft:border,fontSize:12}},
|
||||
h('p',{style:{color:secondary}},display(comment.user?.login)+' · '+time(comment.updated_at||comment.created_at)),
|
||||
h('p',{style:{whiteSpace:'pre-wrap'}},comment.body))),
|
||||
actions(button('dx-ticket-sync-'+row.incident_id,'同步状态与评论',()=>perform({operation:'refresh_ticket',incident_id:row.incident_id}),pending),
|
||||
button('dx-ticket-evidence-'+row.incident_id,'打开事件证据',()=>perform({operation:'open_incident',incident_id:row.incident_id}),pending)))),
|
||||
!operations.tickets?.length&&empty('暂无已缓存的工单。'));
|
||||
}
|
||||
function UsagePanel({runtime,control,pending}){
|
||||
const[timeout,setTimeoutValue]=React.useState('90'),[contextLimit,setContextLimit]=React.useState('16000');
|
||||
React.useEffect(()=>{if(runtime?.settings){setTimeoutValue(String(runtime.settings.response_timeout_seconds));setContextLimit(String(runtime.settings.model_context_limit));}},[runtime?.settings?.response_timeout_seconds,runtime?.settings?.model_context_limit]);
|
||||
const inputStyle={...buttonStyle,width:'100%',boxSizing:'border-box',cursor:'text',marginTop:6};
|
||||
return h('div',{'data-testid':'dx-operations-usage'},
|
||||
empty('Token 取自会话运行事件;供应商未报告的数据保持未知。停止生成仅停止模型响应,已确认的工程执行仍由任务中心管理。'),
|
||||
...((runtime?.sessions)||[]).map(row=>card(row.session_id,'会话 '+row.session_id,
|
||||
detail('状态',status(row.status)),detail('耗时',elapsed(row.elapsed_seconds)),
|
||||
detail('输入 Token',count(row.input_tokens)),detail('输出 Token',count(row.output_tokens)),detail('缓存 Token',count(row.cached_tokens)),detail('总 Token',count(row.total_tokens)),
|
||||
detail('费用',row.price===null||row.price===undefined?'未提供':String(row.price)),
|
||||
button('dx-generation-cancel-'+row.session_id,'停止生成',()=>control({action:'cancel',session_id:row.session_id}),pending||!['running','generating'].includes(row.status)))),
|
||||
!runtime?.sessions?.length&&empty('暂无已报告的会话用量。'),
|
||||
card('settings','响应设置',h('label',{style:{display:'block',fontSize:12,marginBottom:12}},'响应超时(秒)',h('input',{'data-testid':'dx-response-timeout',type:'number',min:15,max:600,step:1,value:timeout,onChange:event=>setTimeoutValue(event.target.value),style:inputStyle})),
|
||||
h('label',{style:{display:'block',fontSize:12,marginBottom:12}},'原生上下文压缩阈值(Token)',h('input',{'data-testid':'dx-context-limit',type:'number',min:2000,max:128000,step:1000,value:contextLimit,onChange:event=>setContextLimit(event.target.value),style:inputStyle})),
|
||||
button('dx-usage-configure','保存响应设置',()=>control({action:'configure',response_timeout_seconds:Number(timeout),model_context_limit:Number(contextLimit)}),
|
||||
pending||!Number.isInteger(Number(timeout))||Number(timeout)<15||Number(timeout)>600||!Number.isInteger(Number(contextLimit))||Number(contextLimit)<2000||Number(contextLimit)>128000)));
|
||||
}
|
||||
function TaskPanel(){
|
||||
const[data,setData]=React.useState(null),[notice,setNotice]=React.useState(''),[tab,setTab]=React.useState('overview'),[pending,setPending]=React.useState(false),[runtime,setRuntime]=React.useState(null);
|
||||
React.useEffect(()=>{
|
||||
let live=true;
|
||||
const read=()=>fetch('/dx/context',{credentials:'same-origin'}).then(response=>{if(!response.ok)throw Error();return response.json();}).then(value=>{if(live)setData(value);}).catch(()=>{if(live)setNotice('任务上下文暂不可用');});
|
||||
read();const timer=setInterval(read,1500);return()=>{live=false;clearInterval(timer);};
|
||||
},[]);
|
||||
React.useEffect(()=>{
|
||||
if(tab!=='usage')return;
|
||||
let live=true;
|
||||
const read=()=>fetch('/dx/runtime',{credentials:'same-origin'}).then(response=>{if(!response.ok)throw Error();return response.json();}).then(value=>{if(live)setRuntime(value);}).catch(()=>{if(live)setNotice('会话用量暂不可用');});
|
||||
read();const timer=setInterval(read,2000);return()=>{live=false;clearInterval(timer);};
|
||||
},[tab]);
|
||||
async function post(path,payload){
|
||||
if(pending)return;
|
||||
setPending(true);setNotice('正在交给任务中心…');
|
||||
try{
|
||||
const response=await fetch(path,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
|
||||
setNotice(response.ok?'请求已交给任务中心;如需确认,请核对原生窗口。':response.status===409?'状态已变化或另一个操作正在进行,请核对最新记录后重试。':'请求未完成,请核对任务中心记录。');
|
||||
}catch{setNotice('任务服务暂不可用,请稍后重试。');}
|
||||
finally{setPending(false);}
|
||||
}
|
||||
const perform=async spec=>{
|
||||
if(!data||pending)return;
|
||||
try{
|
||||
// Live progress is published faster than this dock polls. Refresh the
|
||||
// admission revision at the click without changing the clicked scope.
|
||||
const fresh=await fetch('/dx/context',{credentials:'same-origin'}).then(r=>r.json());
|
||||
if(fresh.task_id!==data.task_id){setData(fresh);setNotice('任务选择已变化,请核对后重新点击。');return;}
|
||||
setData(fresh);await post('/dx/operations',{revision:fresh.revision,spec});
|
||||
}catch{setNotice('任务上下文暂不可用,请稍后重试。');}
|
||||
};
|
||||
const request=action=>data&&post('/dx/action',{action,task_id:data.task_id,revision:data.revision});
|
||||
const control=spec=>post('/dx/runtime/control',spec);
|
||||
const operations=data?.operations||{},scope=data?.task_id?[data.task_id]:[];
|
||||
const tabs=[['overview','概览'],['running','运行'],['impact','影响'],['schedules','排期'],['experiences','经验'],['tickets','工单'],['usage','用量']];
|
||||
return h('div',{'data-testid':'dx-task-panel','data-task-id':data?.task_id||'',style:{padding:20,overflow:'auto',height:'100%',boxSizing:'border-box'}},
|
||||
h('div',{role:'tablist','aria-label':'任务监管',style:{display:'flex',flexWrap:'wrap',gap:4,marginBottom:18,paddingBottom:10,borderBottom:border}},
|
||||
...tabs.map(([id,title])=>h('button',{key:id,id:'dx-tab-'+id,role:'tab',type:'button','data-testid':'dx-operations-tab-'+id,'aria-selected':tab===id,'aria-controls':'dx-pane-'+id,onClick:()=>setTab(id),style:{...buttonStyle,border:tab===id?border:'1px solid transparent',fontWeight:tab===id?600:400,color:tab===id?'var(--dsw-alias-label-primary)':secondary}},title))),
|
||||
h('div',{role:'tabpanel',id:'dx-pane-'+tab,'aria-labelledby':'dx-tab-'+tab},
|
||||
tab==='overview'?h(OverviewPanel,{data,notice,request}):
|
||||
tab==='running'?h(RunningPanel,{operations,perform,pending:pending||operations.busy,request}):
|
||||
tab==='impact'?h(ImpactPanel,{report:operations.impact,scope,perform,pending:pending||operations.busy}):
|
||||
tab==='schedules'?h(SchedulesPanel,{operations,scope,perform,pending:pending||operations.busy}):
|
||||
tab==='experiences'?h(ExperiencesPanel,{operations,perform,pending:pending||operations.busy}):
|
||||
tab==='tickets'?h(TicketsPanel,{operations,perform,pending:pending||operations.busy}):h(UsagePanel,{runtime,control,pending})),
|
||||
tab!=='overview'&&h('p',{'data-testid':'dx-operations-notice',role:'status',style:{fontSize:12,color:secondary,lineHeight:1.8,whiteSpace:'pre-wrap'}},operations.activity?.message||notice||''));
|
||||
}
|
||||
return{inject:['slots','sidebarRightTabs','sidebarRight','uiSession','uiWorkspace'],apply(ctx){
|
||||
ctx.effect(()=>{
|
||||
let live=true,opened='';
|
||||
@@ -100,13 +261,25 @@ window.__ModuleLoader__.load({id:'@dx/dsh-task',factory:require=>{
|
||||
ctx.slots.inject('sidebar.brand.name',()=>ctx.slots.register({name:'sidebar.brand.name',priority:-10},()=>h('span',null,'DSH助手')));
|
||||
const current=ctx.sidebarRight.mounted;
|
||||
ctx.effect(()=>{
|
||||
let frame=0,attempts=0;
|
||||
let timer=0,live=true,connecting=false,adopted=false,openedSession;
|
||||
const open=()=>{
|
||||
if(current.getSnapshot())try{ctx.sidebarRight.openTab('dx-task');if(ctx.sidebarRight.isExpanded())return;}catch{}
|
||||
if(++attempts<120)frame=requestAnimationFrame(open);
|
||||
if(!live)return;
|
||||
const sessionId=current.getSnapshot();
|
||||
if(sessionId){
|
||||
if(openedSession===sessionId)return;
|
||||
try{ctx.sidebarRight.openTab('dx-task');if(ctx.sidebarRight.isExpanded()){openedSession=sessionId;return;}}catch{}
|
||||
}else if(!connecting&&!adopted){
|
||||
connecting=true;
|
||||
fetch('/dx/workspace').then(r=>{if(!r.ok&&r.ok!==undefined)throw Error();return r.json();}).then(value=>{
|
||||
if(live&&!current.getSnapshot()&&typeof value.workspace_id==='string'){
|
||||
adopted=true;return ctx.uiWorkspace.openWorkspace(value.workspace_id);
|
||||
}
|
||||
}).catch(()=>{adopted=false;}).finally(()=>{connecting=false;if(live)queue();});
|
||||
}
|
||||
timer=setTimeout(open,100);
|
||||
};
|
||||
const queue=()=>{cancelAnimationFrame(frame);attempts=0;frame=requestAnimationFrame(()=>{frame=requestAnimationFrame(open);});};
|
||||
const stop=current.subscribe(queue);queue();return()=>{stop();cancelAnimationFrame(frame);};
|
||||
const queue=()=>{clearTimeout(timer);timer=setTimeout(open,0);};
|
||||
const stop=current.subscribe(queue);queue();return()=>{live=false;stop();clearTimeout(timer);};
|
||||
},'dx-task: active session');
|
||||
}};
|
||||
}});
|
||||
@@ -3,8 +3,10 @@ import path from 'node:path';
|
||||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {defineTool} from '@deepseek-ai/dsh-tools';
|
||||
import {registerLifecycle,lifecycleNames} from './lifecycle.mjs';
|
||||
import {registerRuntimeUsage} from './runtime_usage.mjs';
|
||||
import {modelSnapshot} from './model_results.mjs';
|
||||
|
||||
export const inject=['webServer','connection','tools','workspaceRegistry','sessionController','agents'];
|
||||
export const inject=['webServer','connection','tools','workspaceRegistry','sessionController','agents','llm'];
|
||||
const actions=new Set(['retry_failed','pause_task','refresh_snapshot','retry_issue','open_evidence']);
|
||||
export async function readContext(){
|
||||
const value=JSON.parse(await readFile(process.env.DX_DSH_CONTEXT_FILE,'utf8'));
|
||||
@@ -30,6 +32,22 @@ export async function apply(ctx){
|
||||
if('rejection' in admission){res.writeHead(admission.rejection);res.end();return false;}
|
||||
return true;
|
||||
}
|
||||
const usage=await registerRuntimeUsage(ctx,{admit});
|
||||
ctx.effect(()=>()=>usage.dispose(),'dx-task: model observation cleanup');
|
||||
ctx.webServer.register({kind:'exact',path:'/dx/operations',handler:async(req,res)=>{
|
||||
if(!admit(req,res))return;
|
||||
if(req.method!=='POST'){res.writeHead(405);res.end();return;}
|
||||
let body='';for await(const chunk of req){body+=chunk;if(body.length>18000){res.writeHead(413);res.end();return;}}
|
||||
let value;try{value=JSON.parse(body);}catch{res.writeHead(400);res.end();return;}
|
||||
const current=await readContext();
|
||||
if(!value||typeof value!=='object'||value.revision!==current.revision||Object.keys(value).some(k=>!['revision','spec'].includes(k))||
|
||||
!value.spec||typeof value.spec!=='object'||Array.isArray(value.spec)){
|
||||
res.writeHead(409);res.end();return;
|
||||
}
|
||||
const request_id=randomUUID().replaceAll('-','');
|
||||
process.stdout.write('DX_DSH_LIFECYCLE_REQUEST '+JSON.stringify({request_id,capability:'operations',spec:value.spec})+'\n');
|
||||
res.setHeader('Content-Type','application/json');res.end(JSON.stringify({status:'awaiting_task_center',request_id}));
|
||||
}});
|
||||
ctx.webServer.register({kind:'exact',path:'/dx/context',handler:async(req,res)=>{
|
||||
if(!admit(req,res))return;
|
||||
if(req.method!=='GET'){res.writeHead(405);res.end();return;}
|
||||
@@ -55,7 +73,7 @@ export async function apply(ctx){
|
||||
ctx.tools.register(defineTool({name:'dx_task_snapshot',
|
||||
description:'Read the current DxDesigner task status, failure code and diagnostic summary. No files or CAD are accessed.',
|
||||
parameters:{},output:{schema:{type:'object',additionalProperties:true},render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]},
|
||||
execute:async(_args,exec)=>incidentSnapshots.get(exec.agent?.id) || readContext()}));
|
||||
execute:async(_args,exec)=>incidentSnapshots.get(exec.agent?.id) || modelSnapshot(await readContext())}));
|
||||
ctx.on('dx/task-creation-result',result=>creations.get(result.request_id)?.resolve(result));
|
||||
ctx.effect(()=>()=>{
|
||||
for(const request of creations.values())request.reject(Error('Task center disconnected'));
|
||||
@@ -97,6 +115,12 @@ export async function apply(ctx){
|
||||
ctx.tools.guard(exec=>exec.name==='dx_task_snapshot'||(['dx_task_create',...lifecycleNames].includes(exec.name)&&!incidentSnapshots.has(exec.agent?.id))?
|
||||
undefined:'This tool is not enabled for this session. Automatic incident sessions may only read their snapshot.');
|
||||
const workspace=await ctx.workspaceRegistry.create(process.env.DX_DSH_WORKSPACE,'DxDesigner 任务中心');
|
||||
ctx.webServer.register({kind:'exact',path:'/dx/workspace',handler:async(req,res)=>{
|
||||
if(!admit(req,res))return;
|
||||
if(req.method!=='GET'){res.writeHead(405);res.end();return;}
|
||||
res.setHeader('Cache-Control','no-store');res.setHeader('Content-Type','application/json');
|
||||
res.end(JSON.stringify({workspace_id:workspace.id}));
|
||||
}});
|
||||
ctx.on('dx/diagnose-request',request=>{
|
||||
const emit=value=>process.stdout.write('DX_DSH_DIAGNOSIS '+JSON.stringify({request_id:request.request_id,...value})+'\n');
|
||||
if(!/^[a-f0-9]{24}$/.test(request.incident_id)||!['diagnose','reflect'].includes(request.phase)||
|
||||
@@ -125,7 +149,7 @@ export async function apply(ctx){
|
||||
{kind:'user',rpcId:randomUUID()});
|
||||
await Promise.race([agent.whenIdle(),new Promise((_,reject)=>{timer=setTimeout(()=>{
|
||||
void ctx.sessionController.cancel({sessionId});reject(Error('diagnosis_timeout'));
|
||||
},120000);})]);
|
||||
},Math.max(120000,usage.snapshot().settings.response_timeout_seconds*3000));})]);
|
||||
}finally{clearTimeout(timer);}
|
||||
const events=agent.session.snapshotEvents();
|
||||
const transcript=events.filter(e=>['user/message','assistant/message','tool/result','turn/start','turn/end'].includes(e.type)).map(e=>({
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import {createHash} from 'node:crypto';
|
||||
import {defineTool} from '@deepseek-ai/dsh-tools';
|
||||
import {compactResult} from './model_results.mjs';
|
||||
|
||||
export const lifecycleNames=['dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute'];
|
||||
export const lifecycleNames=['dx_task_catalog','dx_task_preflight','dx_task_manage','dx_task_execute','dx_task_operations'];
|
||||
|
||||
export function registerLifecycle(ctx){
|
||||
const pending=new Map();
|
||||
@@ -15,8 +16,8 @@ export function registerLifecycle(ctx){
|
||||
let resolve,reject,timer;
|
||||
const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});
|
||||
const cancel=()=>{
|
||||
process.stdout.write('DX_DSH_LIFECYCLE_CANCEL '+JSON.stringify({request_id})+'\n');
|
||||
reject(Error('Conversation wait cancelled. Confirmed configuration writes may still finish. If execution started, a safe pause was requested; inspect actual task receipts.'));
|
||||
process.stdout.write('DX_DSH_LIFECYCLE_CANCEL '+JSON.stringify({request_id,reason:'conversation_cancelled'})+'\n');
|
||||
reject(Error('Conversation wait cancelled. Confirmed configuration writes and executions retain their own lifetime. Inspect actual task receipts; request task pause explicitly when needed.'));
|
||||
};
|
||||
pending.set(request_id,{promise,resolve,reject});
|
||||
try{
|
||||
@@ -26,7 +27,7 @@ export function registerLifecycle(ctx){
|
||||
return await promise;
|
||||
}finally{clearTimeout(timer);exec.signal.removeEventListener('abort',cancel);pending.delete(request_id);}
|
||||
}
|
||||
const output={schema:{type:'object',additionalProperties:true},render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]};
|
||||
const output={schema:{type:'object',additionalProperties:true},render:(_args,value)=>[{type:'text',text:JSON.stringify(compactResult(value))}]};
|
||||
const ids={type:'array',required:true,items:{type:'string'},description:'1 to 20 distinct real task IDs obtained from current records, in execution order. Never infer IDs.'};
|
||||
const definitions=[
|
||||
{name:'dx_task_catalog',capability:'catalog',parameters:{task_id:{type:'string',description:'Optional real task ID to also read its saved rule mappings, Value policy and execution phase.'}},
|
||||
@@ -40,8 +41,16 @@ export function registerLifecycle(ctx){
|
||||
rules:{type:'array',items:{type:'object',additionalProperties:false,properties:{old_part_number:{type:'string',required:true},
|
||||
new_part_number:{type:'string'},target_cell:{type:'string'},custom_value:{type:'string'},custom_value_enabled:{type:'boolean'},sync_nc:{type:'boolean'},enabled:{type:'boolean'}}}}}}},
|
||||
description:'Manage an existing real task. select changes the task-center selection. update previews explicit metadata and existing rule changes, then waits for native user confirmation. archive moves only that task to the recycle bin, preserving evidence. copy copies mapping configuration and opens the native selector for NEW engineering scope; never duplicates execution evidence or executes CAD. Returns committed IDs/results or cancellation. Native user confirmation cannot be supplied by model arguments. Interactive conversations only.'},
|
||||
{name:'dx_task_execute',capability:'execute',parameters:{operation:{type:'string',required:true,enum:['start','pause']},task_ids:ids},
|
||||
{name:'dx_task_execute',capability:'execute',parameters:{operation:{type:'string',required:true,enum:['start','pause','resume']},task_ids:{type:'array',items:{type:'string'},description:ids.description},run_id:{type:'string',description:'For resume only, use the real saved run ID from execution history. Original frozen scope/order and existing checkpoint are inspected, then natively confirmed.'}},
|
||||
description:'Start or continue the existing serial execution queue for an explicit ordered list of real task IDs. Prechecks and native confirmation are required; actual execution can replace and save engineering files using existing backup, interruption and verification gates. Waits for real results including saved, failed and no-match counts. For pause, provide exactly the active run scope; requests safe stopping after the current item and returns pause_requested, not a claim that stopping has completed. No force-stop, no new CAD scripting or hidden retry. Interactive conversations only.'},
|
||||
{name:'dx_task_operations',capability:'operations',parameters:{
|
||||
operation:{type:'string',required:true,enum:['refresh','history','impact','experience','tickets','refresh_ticket','schedule','schedule_dialog','cancel_schedule','run_schedule','resume']},
|
||||
task_ids:{type:'array',items:{type:'string'},description:ids.description},run_id:{type:'string'},schedule_id:{type:'string'},incident_id:{type:'string'},issue_code:{type:'string'},
|
||||
title:{type:'string'},priority:{type:'string',enum:['low','normal','high','urgent']},
|
||||
not_before:{type:'string',description:'For schedule: earliest run time as ISO 8601 with explicit timezone offset, e.g. 2026-10-30T18:00:00+08:00. Ask when ambiguous; never guess a date.'},
|
||||
due_at:{type:'string',description:'Optional deadline with timezone offset'},dependencies:{type:'array',items:{type:'string'},description:'Actual preceding task IDs that must complete without unresolved evidence'},
|
||||
auto_start:{type:'boolean',description:'Future idle execution intent only. Native confirmation explicitly authorizes the frozen scope; never a bypass. Default false.'}},
|
||||
description:'Read execution history/recoverable runs, exact saved impact or unknown mapping counts, evidence-backed local experiences, and existing Git issue status/replies. Refresh one bound ticket by real incident ID; cannot write comments. Plan tasks with priority/time/dependencies and optional idle execution using a native confirmation. App must remain open; changed plans, pause, uncertainty and blockers prevent scheduled execution. Use only fields relevant to the selected operation. history/refresh return real saved run and schedule IDs. resume reconfirms an original frozen queue. Interactive conversations only.'},
|
||||
];
|
||||
for(const {capability,...definition} of definitions){
|
||||
ctx.tools.register(defineTool({...definition,output,execute:(spec,exec)=>request(capability,spec,exec)}));
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/** Bounded model views. Full task records/evidence remain owned by the desktop. */
|
||||
const short=(text,limit=600)=>typeof text==='string'?text.slice(0,limit):text;
|
||||
const fields=(value,keys)=>Object.fromEntries(keys.filter(k=>value?.[k]!==undefined).map(k=>[k,value[k]]));
|
||||
const run=row=>({...fields(row,['run_id','queue_id','status','task_ids','remaining_task_ids','counters','blockers','resume_ready','started_utc']),
|
||||
result:row.result?fields(row.result,['status','tasks','message']):undefined});
|
||||
const schedule=row=>fields(row,['schedule_id','title','task_ids','priority','not_before','due_at','dependencies','auto_start','status','ready','blockers','run_id']);
|
||||
const experience=row=>({...fields(row,['incident_id','issue_code','verified','verification','evidence','evidence_refs','evidence_references','status']),
|
||||
attempts:row.attempts,analyses:row.analyses?.slice(0,2),outcome:row.outcome,
|
||||
summary:short(row.summary,1200),message:short(row.message)});
|
||||
const ticket=row=>({...fields(row,['incident_id','number','url','state','status','last_sync_at','last_attempt_at','error','reason']),
|
||||
comments:row.comments?.slice(-3).map(c=>({...fields(c,['id','created_at','updated_at','author']),body:short(c.body)}))});
|
||||
function impact(report){
|
||||
if(!report||typeof report!=='object')return report;
|
||||
const rows=report.rows||[];
|
||||
return {...fields(report,['coverage','task_ids','component_count','known_component_count','enabled_scope','total_rows','omitted_row_count','truncated','tasks']),
|
||||
rows:rows.slice(0,20),model_omitted_rows:Math.max(0,rows.length-20)};
|
||||
}
|
||||
export function compactResult(value){
|
||||
if(!value||typeof value!=='object')return value;
|
||||
const result={...value};
|
||||
delete result.plan_hashes;delete result.fingerprint;delete result.full_fingerprint;
|
||||
if(result.rows)Object.assign(result,impact(result));
|
||||
if(result.impact)result.impact=impact(result.impact);
|
||||
if(result.tasks?.length>50){result.model_omitted_tasks=result.tasks.length-50;result.tasks=result.tasks.slice(0,50);}
|
||||
if(result.tasks)result.tasks=result.tasks.map(t=>({...t,...t.note?{note:short(t.note,300)}:{}}));
|
||||
if(result.runs)result.runs=result.runs.slice(0,5).map(run);
|
||||
if(result.schedules)result.schedules=result.schedules.slice(0,10).map(schedule);
|
||||
if(result.schedule)result.schedule=schedule(result.schedule);
|
||||
if(result.experiences)result.experiences=result.experiences.slice(0,5).map(experience);
|
||||
if(result.tickets)result.tickets=result.tickets.slice(0,5).map(ticket);
|
||||
if(result.ticket)result.ticket=ticket(result.ticket);
|
||||
return JSON.parse(JSON.stringify(result));
|
||||
}
|
||||
export function modelSnapshot(value){
|
||||
const result=fields(value,['task_id','revision','task_name','status','progress','rules_count','issue','issue_code','events','action_result']);
|
||||
const ops=value.operations||{};
|
||||
result.operations=compactResult({busy:ops.busy===true,live_run:ops.live_run,last_execution:ops.last_execution,
|
||||
runs:ops.runs||[],schedules:ops.schedules||[],experiences:ops.experiences||[],tickets:ops.tickets||[]});
|
||||
if(value.automation?.incident_id)result.automation=fields(value.automation,['incident_id','task_id','issue_code','status','attempts','verification']);
|
||||
if(value.lifecycle?.status)result.lifecycle=fields(value.lifecycle,['request_id','status','task_ids','run_id']);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
/** Application-owned, bounded observations around the official model stream. */
|
||||
import {mkdir,readFile,writeFile,rename,unlink} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
|
||||
const DEFAULTS=Object.freeze({response_timeout_seconds:90,model_context_limit:16000});
|
||||
const MAX_SESSIONS=50;
|
||||
const count=value=>Number.isSafeInteger(value)&&value>=0?value:null;
|
||||
const SAFE_ERRORS=new Set(['AUTH','RATE_LIMIT','QUOTA_EXCEEDED','ACCOUNT_QUOTA_EXCEEDED','INVALID_CREDENTIAL',
|
||||
'NETWORK','NO_ADAPTER','CONTEXT_WINDOW_EXCEEDED','EMPTY_RESPONSE','TIMEOUT','ABORTED']);
|
||||
const code=value=>SAFE_ERRORS.has(value)?value:'MODEL_ERROR';
|
||||
|
||||
function settingsValue(raw,previous=DEFAULTS){
|
||||
if(!raw||typeof raw!=='object'||Array.isArray(raw)||Object.keys(raw).some(key=>!Object.hasOwn(DEFAULTS,key)))throw Error('invalid_settings');
|
||||
const next={...previous,...raw};
|
||||
if(!Number.isInteger(next.response_timeout_seconds)||next.response_timeout_seconds<15||next.response_timeout_seconds>600||
|
||||
!Number.isInteger(next.model_context_limit)||next.model_context_limit<2000||next.model_context_limit>128000)throw Error('invalid_settings');
|
||||
return next;
|
||||
}
|
||||
|
||||
function addUsage(row,usage){
|
||||
if(!usage){row.usage_complete=false;return;}
|
||||
const mapping={input_tokens:'inputTokens',output_tokens:'outputTokens',cache_read_tokens:'cacheReadTokens',
|
||||
cache_write_tokens:'cacheWriteTokens',total_tokens:'totalTokens'};
|
||||
for(const [field,source]of Object.entries(mapping)){
|
||||
const value=count(usage[source]);
|
||||
if(value!==null)row[field]=(row[field]??0)+value;
|
||||
}
|
||||
const read=count(usage.cacheReadTokens),write=count(usage.cacheWriteTokens);
|
||||
if(read!==null||write!==null)row.cached_tokens=(row.cached_tokens??0)+(read??0)+(write??0);
|
||||
if(count(usage.inputTokens)===null||count(usage.outputTokens)===null||count(usage.totalTokens)===null)row.usage_complete=false;
|
||||
}
|
||||
|
||||
function restoreUsage(row,agent){
|
||||
const events=agent?.session?.snapshotEvents?.();
|
||||
if(!Array.isArray(events))return;
|
||||
for(const event of events){
|
||||
const data=event.data;
|
||||
if(!data||!['assistant/message','assistant/attempt','compaction/summary'].includes(event.type))continue;
|
||||
if(event.type==='compaction/summary'&&data.llmStreamCall!==true)continue;
|
||||
let usage=data.usage;
|
||||
if(!usage&&Array.isArray(data.stream)){
|
||||
// Native attempt streams retain raw usage chunks; repeated chunks are
|
||||
// cumulative for that call, so only the last one is authoritative.
|
||||
usage=data.stream.findLast(record=>record.type==='chunk'&&record.chunk?.type==='usage')?.chunk.usage;
|
||||
}
|
||||
addUsage(row,usage);row.response_count++;
|
||||
if(event.type==='compaction/summary')row.context_compactions++;
|
||||
}
|
||||
if(row.response_count){
|
||||
row.elapsed_seconds=null;row.duration_complete=false;
|
||||
row.usage_source='native_session_history';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Required services: llm, agents, sessionController, webServer. Optional native
|
||||
* compaction/tokenMeter are resolved dynamically. No task execution API is used.
|
||||
*/
|
||||
export async function registerRuntimeUsage(ctx,{admit}){
|
||||
if(typeof admit!=='function'||!process.env.DX_DSH_HOME)throw Error('runtime_usage_configuration');
|
||||
const settingsPath=path.join(path.dirname(process.env.DX_DSH_HOME),'assistant-settings.json');
|
||||
let settings={...DEFAULTS};
|
||||
try{settings=settingsValue(JSON.parse(await readFile(settingsPath,'utf8')));}catch{}
|
||||
const rows=new Map(),active=new Set(),timers=new Map(),releases=[];
|
||||
let writeTail=Promise.resolve();
|
||||
const service=name=>typeof ctx.get==='function'?ctx.get(name):ctx[name];
|
||||
const nativeCompaction=agent=>(agent&&service('agentPresets')?.serviceFor?.(agent,'compaction'))??agent?.ctx?.get?.('compaction')??service('compaction');
|
||||
const tokenMeter=()=>service('tokenMeter');
|
||||
const on=(name,fn)=>{const release=ctx.on(name,fn);if(typeof release==='function')releases.push(release);};
|
||||
const known=id=>typeof id==='string'&&id.length>0&&id.length<=256&&ctx.agents.get(id);
|
||||
const entry=id=>{
|
||||
let row=rows.get(id);
|
||||
if(row)return row;
|
||||
if(rows.size>=MAX_SESSIONS){
|
||||
const oldest=[...rows.keys()].find(key=>!active.has(key));
|
||||
if(oldest===undefined)return null;
|
||||
rows.delete(oldest);
|
||||
}
|
||||
row={session_id:id,status:'idle',elapsed_seconds:0,input_tokens:null,output_tokens:null,
|
||||
cached_tokens:null,cache_read_tokens:null,cache_write_tokens:null,total_tokens:null,
|
||||
price:null,usage_complete:true,response_count:0,last_started_at:null,last_finished_at:null,
|
||||
duration_complete:true,usage_source:'native_model_stream',context_compactions:0,context_limit_state:'not_measured'};
|
||||
restoreUsage(row,known(id));
|
||||
rows.set(id,row);return row;
|
||||
};
|
||||
const snapshot=()=>({sessions:[...rows.values()].map(row=>{
|
||||
const value={...row};
|
||||
if(row._started!==undefined&&value.elapsed_seconds!==null)value.elapsed_seconds+=Math.max(0,(Date.now()-row._started)/1000);
|
||||
delete value._started;return value;
|
||||
}).reverse().slice(0,MAX_SESSIONS),settings:{...settings},
|
||||
context_limit_mode:tokenMeter()&&(nativeCompaction()||ctx.agents.list().some(agent=>nativeCompaction(agent)))?'native_compaction_threshold':'unavailable',
|
||||
pricing_status:'unavailable'});
|
||||
const configure=raw=>{
|
||||
settingsValue(raw,settings);
|
||||
const fields={...raw};
|
||||
const operation=writeTail.then(async()=>{
|
||||
const next=settingsValue(fields,settings);
|
||||
const temporary=path.join(path.dirname(settingsPath),'settings-'+randomUUID()+'.tmp');
|
||||
await mkdir(path.dirname(settingsPath),{recursive:true});
|
||||
try{await writeFile(temporary,JSON.stringify(next,null,2),'utf8');await rename(temporary,settingsPath);settings=next;}
|
||||
finally{await unlink(temporary).catch(()=>{});}
|
||||
return {...settings};
|
||||
});
|
||||
writeTail=operation.catch(()=>{});return operation;
|
||||
};
|
||||
const cancel=async id=>{
|
||||
if(!known(id))throw Error('unknown_session');
|
||||
const row=entry(id);
|
||||
// This cancels the native conversation turn. It never calls task-stop, CAD,
|
||||
// or the task-center lifecycle bridge; an admitted task has its own lifetime.
|
||||
const result=await ctx.sessionController.cancel({sessionId:id});
|
||||
if(row&&row.status!=='timeout')row.status='cancelled';
|
||||
return {status:'cancellation_requested',session_id:id,accepted:result?.accepted===true};
|
||||
};
|
||||
|
||||
for(const agent of ctx.agents.list())entry(agent.id);
|
||||
on('agent/created',({agent})=>{entry(agent.id);});
|
||||
|
||||
on('llm/stream',async function*(options,next){
|
||||
const id=options.sessionId;
|
||||
if(!known(id)){yield* next();return;}
|
||||
const row=entry(id);
|
||||
if(!row||active.has(id)){yield* next();return;}
|
||||
active.add(id);
|
||||
const started=Date.now();
|
||||
row._started=started;row.last_started_at=new Date(started).toISOString();
|
||||
row.status='generating';row.response_count++;delete row.error;
|
||||
let timer,latestUsage=null,finish=null,timedOut=false,completed=false;
|
||||
let timeoutResolve;
|
||||
const timeout=new Promise(resolve=>{timeoutResolve=resolve;});
|
||||
timer=setTimeout(()=>{
|
||||
timedOut=true;row.status='timeout';row.error='RESPONSE_TIMEOUT';
|
||||
// Called only while a provider stream is pending, never during a tool wait.
|
||||
Promise.resolve().then(()=>ctx.sessionController.cancel({sessionId:id})).catch(()=>{});
|
||||
timeoutResolve({done:false,value:{type:'finish',reason:{kind:'aborted',failure:{
|
||||
code:'RESPONSE_TIMEOUT',message:'Model response timeout'}}}});
|
||||
},settings.response_timeout_seconds*1000);
|
||||
timers.set(id,timer);
|
||||
timer.unref?.();
|
||||
let iterator;
|
||||
try{
|
||||
iterator=next()[Symbol.asyncIterator]();
|
||||
while(true){
|
||||
const result=await Promise.race([iterator.next(),timeout]);
|
||||
if(result.done){completed=true;break;}
|
||||
const chunk=result.value;
|
||||
if(chunk.type==='usage')latestUsage=chunk.usage;
|
||||
if(chunk.type==='finish'){
|
||||
finish=chunk.reason;
|
||||
// Provider completion ends its response timer before any tool starts.
|
||||
clearTimeout(timer);
|
||||
}
|
||||
yield chunk;
|
||||
if(timedOut)break;
|
||||
}
|
||||
if(!timedOut){
|
||||
row.status=finish?.kind==='error'?'error':finish?.kind==='aborted'||options.signal?.aborted?'cancelled':
|
||||
finish?.kind==='tool-calls'?'waiting_for_tool':finish?'completed':'error';
|
||||
if(row.status==='error')row.error=code(finish?.failure?.code);
|
||||
}
|
||||
}catch(error){
|
||||
if(!timedOut){row.status=options.signal?.aborted?'cancelled':'error';row.error=options.signal?.aborted?'ABORTED':code(error?.code);}
|
||||
throw error;
|
||||
}finally{
|
||||
clearTimeout(timer);timers.delete(id);active.delete(id);
|
||||
if(!completed){try{Promise.resolve(iterator?.return?.()).catch(()=>{});}catch{}}
|
||||
if(row.elapsed_seconds!==null)row.elapsed_seconds+=Math.max(0,(Date.now()-started)/1000);delete row._started;
|
||||
row.last_finished_at=new Date().toISOString();
|
||||
addUsage(row,latestUsage);
|
||||
}
|
||||
});
|
||||
on('agent/status',({agent,status})=>{
|
||||
const row=rows.get(agent.id);
|
||||
if(row&&status==='idle'&&row.status==='waiting_for_tool')row.status='completed';
|
||||
});
|
||||
on('agent/pre-step',async({agent,signal},next)=>{
|
||||
const compaction=nativeCompaction(agent),meter=tokenMeter();
|
||||
if(compaction&&meter&&!signal.aborted){
|
||||
const row=entry(agent.id);
|
||||
try{
|
||||
const measured=count(meter.measure(agent.session)?.totalTokens);
|
||||
if(row)row.context_limit_state=measured===null?'unavailable':measured<settings.model_context_limit?'within_limit':'threshold_reached';
|
||||
if(measured!==null&&measured>=settings.model_context_limit){
|
||||
// Native selection preserves balanced tool pairs and reconstructable
|
||||
// system/identity records. Never truncate the frozen request envelope.
|
||||
const result=await compaction.compactIfNeeded(agent,'context-overflow',signal);
|
||||
if(row){row.context_compactions+=result?1:0;row.context_limit_state=result?'compacted':'no_safe_range';}
|
||||
}
|
||||
}catch(error){
|
||||
if(signal.aborted)throw error;
|
||||
if(row)row.context_limit_state='compaction_unavailable';
|
||||
}
|
||||
}
|
||||
return next();
|
||||
});
|
||||
|
||||
const respond=(res,status,value)=>{res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'});res.end(JSON.stringify(value));};
|
||||
const register=route=>{const release=ctx.webServer.register(route);if(typeof release==='function')releases.push(release);};
|
||||
register({kind:'exact',path:'/dx/runtime',handler:async(req,res)=>{
|
||||
if(!admit(req,res))return;
|
||||
if(req.method!=='GET'){respond(res,405,{error:'method_not_allowed'});return;}
|
||||
respond(res,200,snapshot());
|
||||
}});
|
||||
register({kind:'exact',path:'/dx/runtime/control',handler:async(req,res)=>{
|
||||
if(!admit(req,res))return;
|
||||
if(req.method!=='POST'){respond(res,405,{error:'method_not_allowed'});return;}
|
||||
let raw='',size=0;
|
||||
for await(const chunk of req){size+=Buffer.byteLength(chunk);if(size>2048){respond(res,413,{error:'request_too_large'});return;}raw+=chunk;}
|
||||
try{
|
||||
const value=JSON.parse(raw);
|
||||
if(!value||typeof value!=='object'||Array.isArray(value))throw Error('invalid_control');
|
||||
if(value.action==='configure'){
|
||||
const {action,...fields}=value;
|
||||
respond(res,200,{status:'configured',settings:await configure(fields)});return;
|
||||
}
|
||||
if(value.action==='cancel'&&Object.keys(value).every(key=>['action','session_id'].includes(key))){
|
||||
respond(res,200,await cancel(value.session_id));return;
|
||||
}
|
||||
throw Error('invalid_control');
|
||||
}catch(error){respond(res,error.message==='unknown_session'?409:400,{error:error.message==='unknown_session'?'unknown_session':'invalid_control'});}
|
||||
}});
|
||||
const dispose=()=>{for(const timer of timers.values())clearTimeout(timer);timers.clear();for(const release of releases.splice(0).reverse())release();};
|
||||
return {snapshot,configure,cancel,dispose};
|
||||
}
|
||||
Reference in new issue
Block a user