dsh-nova-lewis 0.2.2 → 0.2.4

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.
@@ -0,0 +1,52 @@
1
+ /* Only hide the original body after its authenticated, same-row presentation mounts.
2
+ The native turn actions and persisted message keep their original contents. */
3
+ [data-chat-flow-kind="assistant-step"]:has(> [data-nova-replies]) > [data-slot="conversation.chat.node"] {
4
+ /* DSH supplies display:contents inline on the slot anchor. */
5
+ display:none !important;
6
+ }
7
+ /* Wallpaper Engine decorates the host's assistant row when its avatar option is on. */
8
+ [data-chat-flow-kind="assistant-step"][data-we-avatar-row]:has(> [data-nova-replies]) > .we-avatar { display:none; }
9
+ [data-nova-replies] {
10
+ min-width:0;
11
+ color:var(--dsw-alias-label-primary,CanvasText);
12
+ font-size:var(--dsh-content-font-size,14px);
13
+ text-align:start;
14
+ }
15
+ [data-nova-replies] > [role="list"], [data-nova-participant], [data-nova-closing] {
16
+ display:flex;
17
+ flex-direction:column;
18
+ align-items:flex-start;
19
+ min-width:0;
20
+ }
21
+ [data-nova-replies] > [role="list"] { gap:12px; }
22
+ [data-nova-participant], [data-nova-closing] { gap:4px; max-width:100%; }
23
+ [data-nova-closing] { margin-block-start:22px; }
24
+ [data-nova-name] {
25
+ max-width:100%;
26
+ overflow-wrap:anywhere;
27
+ font-size:var(--dsh-content-font-size-secondary,13px);
28
+ font-weight:600;
29
+ color:var(--dsw-alias-label-secondary,CanvasText);
30
+ }
31
+ [data-nova-bubble] {
32
+ min-width:0;
33
+ max-width:100%;
34
+ overflow-wrap:anywhere;
35
+ white-space:pre-wrap;
36
+ user-select:text;
37
+ }
38
+ [data-nova-copy] {
39
+ display:inline-flex;
40
+ align-items:center;
41
+ justify-content:center;
42
+ width:28px;
43
+ height:28px;
44
+ margin-top:8px;
45
+ padding:4px;
46
+ border:0;
47
+ border-radius:var(--dsw-radius-sm,6px);
48
+ color:var(--dsw-alias-label-secondary,CanvasText);
49
+ background:transparent;
50
+ cursor:pointer;
51
+ }
52
+ [data-nova-copy]:hover { background:var(--dsw-alias-interactive-bg-hover); }
@@ -0,0 +1,151 @@
1
+ import React, {useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react'
2
+ import {createPortal} from 'react-dom'
3
+ import {IconCheckOutlineRegular, IconCopyOutlineRegular, MarkdownText, UserMessageBubble, useClipboardCopy} from '@deepseek-ai/dsh-client-ui-primitives'
4
+ import {hasRollCallClosing} from '../src/easter-egg.mjs'
5
+ import bubbleCSS from './chat-replies.css'
6
+
7
+ const h = React.createElement
8
+ const labels = {
9
+ code:{copyLabel:'复制', copiedLabel:'已复制', toolbarLabels:{codeLabel:'代码', wrapLabel:'自动换行', unwrapLabel:'取消换行'}},
10
+ footnotes:'脚注',
11
+ }
12
+
13
+ // Historical turns can mount together. Only query nearby visible answers, share in-flight
14
+ // requests between panes, and retain negative identities rather than large answer bodies.
15
+ const pending = new Map(), ordinary = new Set()
16
+ const standaloneKind = 'dsh-nova-standalone-reply'
17
+ const deliveryEvent = 'plugin:collaboration/reply-delivered'
18
+ async function lookup(sessionId, messageId, seq) {
19
+ const key = JSON.stringify([sessionId, messageId, seq])
20
+ if (ordinary.has(key)) return null
21
+ if (pending.has(key)) return pending.get(key)
22
+ const request = (async () => {
23
+ const response = await fetch('/api/collaboration-local/reply', {
24
+ method:'POST', credentials:'same-origin', cache:'no-store', headers:{'Content-Type':'application/json'},
25
+ body:JSON.stringify({sessionId, messageId, seq}),
26
+ })
27
+ if (!response.ok) throw Error('读取协作回复失败')
28
+ const result = await response.json()
29
+ if (!result.ok) throw Error('读取协作回复失败')
30
+ if (result.value === null) {
31
+ ordinary.add(key)
32
+ if (ordinary.size > 512) ordinary.delete(ordinary.values().next().value)
33
+ }
34
+ return result.value
35
+ })().finally(() => pending.delete(key))
36
+ pending.set(key, request)
37
+ return request
38
+ }
39
+
40
+ function Participant({name, text, closing=false}) {
41
+ return h('div', closing ? {'data-nova-closing':''} : {'data-nova-participant':'',role:'listitem'},
42
+ h('div', {'data-nova-name':''}, name),
43
+ h(UserMessageBubble, {'data-message-bubble':'', 'data-nova-bubble':'', 'data-text-interaction-source':''}, text))
44
+ }
45
+
46
+ function Replies({value}) {
47
+ return h('section', {'data-nova-replies':'', 'aria-label':'协作模型回复'},
48
+ h('style', null, bubbleCSS),
49
+ h('div', {role:'list'}, value.participants.map(({name,text}, index) =>
50
+ h(Participant, {key:index, name, text}))),
51
+ h(Participant, {name:'NOVA', text:value.closing.replace(/^NOVA:/u,''), closing:true}))
52
+ }
53
+
54
+ function useReply(target, sessionId, messageId, seq, markdown) {
55
+ const [answer, setAnswer] = useState(null)
56
+ useEffect(() => {
57
+ if (!target || !messageId || markdown === null) return
58
+ let live = true, retry, observer, attempts = 0
59
+ const read = async () => {
60
+ try {
61
+ const value = await lookup(sessionId, messageId, seq)
62
+ if (live && value && (markdown === undefined || value.markdown === markdown))
63
+ setAnswer({target, messageId, value})
64
+ } catch {
65
+ // Keep the normal DSH answer available during a transient host/persistence failure.
66
+ if (live && ++attempts < 3) retry = setTimeout(read, 400 * attempts)
67
+ }
68
+ }
69
+ if (typeof IntersectionObserver === 'function') {
70
+ observer = new IntersectionObserver(entries => {
71
+ if (!entries.some(entry => entry.isIntersecting)) return
72
+ observer.disconnect()
73
+ void read()
74
+ }, {rootMargin:'700px 0px'})
75
+ observer.observe(target)
76
+ } else void read()
77
+ return () => { live = false; observer?.disconnect(); clearTimeout(retry) }
78
+ }, [target, sessionId, messageId, seq, markdown])
79
+ return answer?.target === target && answer?.messageId === messageId &&
80
+ (markdown === undefined || answer?.value.markdown === markdown) ? answer?.value : null
81
+ }
82
+
83
+ // An out-of-turn Workbench delivery has no native chat row or turn tail in rc.5.
84
+ // Only NOVA's own delivery receipt contributes this new node kind to the transcript.
85
+ export function registerStandaloneReplies(ctx) {
86
+ ctx.uiConversation.events.register({
87
+ kind:standaloneKind, target:'chat',
88
+ match:{[deliveryEvent]:event => event.ignorable === true && typeof event.data?.messageId === 'string' &&
89
+ Number.isSafeInteger(event.data.seq) && event.data.seq === event.seq - 1 ? {id:event.data.messageId,role:'start'} : null},
90
+ start:(_context, match) => match.event.data,
91
+ update:context => context.state,
92
+ buildViewNode:context => context.state ? {key:context.key, id:context.id, kind:standaloneKind, target:'chat',
93
+ anchorSeq:context.state.seq, location:{kind:'session'}, visibility:'visible', groupTree:'turn', data:context.state} : null,
94
+ })
95
+ ctx.slots.inject('conversation.chat.node',()=>ctx.slots.register({name:'conversation.chat.node', key:standaloneKind,
96
+ inject:sessionId=>({sessionId, eventSource:ctx.sessions.binding(sessionId)?.eventSource})},StandaloneReply))
97
+ }
98
+
99
+ function savedDeliveryText(entries, {messageId,seq}) {
100
+ // The authorized client's event window can still supply a plain answer while the
101
+ // host is reconnecting. Require the original receipt, answer and completion together.
102
+ const index = entries?.findLastIndex(({event}) => event?.type === deliveryEvent && event.seq === seq + 1 && event.data.messageId === messageId)
103
+ if (!(index >= 2)) return
104
+ const completed = entries[index - 2].event, entry = entries[index - 1].event, message = entry?.data?.message
105
+ if (completed?.type !== 'plugin:collaboration/run' || completed.seq !== seq - 1 || completed.ignorable !== true ||
106
+ completed.data.fields?.status !== 'completed' || entry?.type !== 'assistant/message' || entry.seq !== seq ||
107
+ entry.data.turn !== 0 || entry.data.step !== 0 || message?.id !== messageId || message.role !== 'assistant' ||
108
+ message.source?.kind !== 'model' || !message.content?.length || message.content.some(b=>b.type !== 'text')) return
109
+ return message.content.map(block=>block.text).join('')
110
+ }
111
+
112
+ function StandaloneReply({sessionId, node, eventSource}) {
113
+ const [target, setTarget] = useState(null)
114
+ const original = useMemo(()=>savedDeliveryText(eventSource?.getSnapshot().entries,node.data),[eventSource,node.data])
115
+ const value = useReply(target, sessionId, node.data.messageId, node.data.seq,original)
116
+ const markdown = value?.markdown ?? original
117
+ const {copied, onCopy} = useClipboardCopy(markdown || '')
118
+ return h('div', {ref:setTarget}, h('style',null,bubbleCSS),
119
+ markdown && h(MarkdownText,{text:markdown,labels,streaming:false,textInteractionSource:true}),
120
+ markdown && h('button',{type:'button', 'aria-label':copied ? '已复制' : '复制', 'data-nova-copy':'',onClick:onCopy},
121
+ h(copied ? IconCheckOutlineRegular : IconCopyOutlineRegular, {size:16,'aria-hidden':true})))
122
+ }
123
+
124
+ // rc.5 exposes the durable closing message through its per-turn extension seat. The
125
+ // keyed assistant renderer itself owns DSH chat behaviour for every other plugin.
126
+ export function ChatReplies({sessionId, turn, seq, useChat}) {
127
+ const marker = useRef(null)
128
+ const [target, setTarget] = useState(null)
129
+ const closing = turn.data.get('turn-tail')?.closing
130
+ const blocks = closing?.blocks
131
+ const markdown = blocks?.length === 1 && blocks[0].kind === 'text' && hasRollCallClosing(blocks[0].text) ? blocks[0].text : null
132
+ const messageId = markdown !== null && closing?.finalNode?.seq === seq ? closing.finalNode.messageId : null
133
+ const turnNumber = turn.turn, step = closing?.step
134
+ const selectKey = useCallback(snapshot => {
135
+ if (!messageId) return null
136
+ return snapshot.locations.getStep(turnNumber,step).find(key => {
137
+ const node = snapshot.nodes.get(key)
138
+ return node?.kind === 'assistant-step' && node.data.finalNode?.messageId === messageId
139
+ }) || null
140
+ }, [turnNumber, step, messageId])
141
+ const nodeKey = useChat(selectKey)
142
+ const value = useReply(target, sessionId, messageId, seq, markdown)
143
+
144
+ useLayoutEffect(() => {
145
+ const flow = marker.current?.closest('[data-slot="conversation.chat.flow"]')
146
+ const row = nodeKey && flow?.querySelector(`[data-chat-flow-kind="assistant-step"][data-chat-node-key="${CSS.escape(nodeKey)}"]:not([data-chat-group-part="reasoning"])`)
147
+ setTarget(row || null)
148
+ }, [sessionId, nodeKey])
149
+ return h(React.Fragment, null, h('span',{ref:marker,hidden:true}),
150
+ value?.kind === 'roll-call' && value.participants?.length > 0 && value.closing && createPortal(h(Replies,{value}),target))
151
+ }
package/host/children.mjs CHANGED
@@ -6,6 +6,7 @@ import { mkdtemp, writeFile, rm } from 'node:fs/promises'
6
6
  import { realpathSync, existsSync } from 'node:fs'
7
7
  import { childReceipt, visibleText } from './models.mjs'
8
8
  import {reasoningOptions} from './selection.mjs'
9
+ import {estimateInput,outputLimits} from '../src/context.mjs'
9
10
 
10
11
  const preflightError = message => Object.assign(Error(message), {dispatched:false})
11
12
  const shellName = process.platform === 'win32' ? 'powershell' : 'bash'
@@ -81,7 +82,7 @@ export function createChildren(ctx, config = {}) {
81
82
  child.reports.catch(()=>{})
82
83
  }
83
84
  })
84
- return async (args,messages)=>{
85
+ return async (args,messages,context)=>{
85
86
  const tools = [...new Set(args.node.tools)].sort()
86
87
  if (tools.some(t=>!['read','edit','write','search','bash'].includes(t))) throw preflightError('节点请求了未适配的工具。')
87
88
  if (!get('subagents') || !get('agentPresets') || !get('tools')) throw preflightError('此 DSH profile 尚未启用原生子代理与工具。')
@@ -115,12 +116,16 @@ export function createChildren(ctx, config = {}) {
115
116
  }
116
117
  const child = {cwd,args,calls:0,spent:0,receipts:[],reports:Promise.resolve()}
117
118
  children.set(childId,child)
118
- const maxTokens = Math.min(1024,args.route.maxOutput || 1024,args.maxAttemptTokens == null ? Infinity : Math.max(64,Math.floor(args.maxAttemptTokens/4)))
119
+ const prompt = messages.map(m=>m.content).join('\n\n')+sourceIndex
120
+ const {declared, available} = outputLimits(args.route, (context?.estimated ?? estimateInput(prompt)) +
121
+ (context ? estimateInput(sourceIndex) : 0), args.node.outputReserve || args.settings?.outputReserve, context?.margin)
122
+ const maxTokens = args.maxAttemptTokens == null ? (declared == null ? undefined : available) :
123
+ Math.min(available, Math.max(1, Math.floor(args.maxAttemptTokens / 4)))
119
124
  activation = await get('subagents').startActivation({provider:'spawn',agentPreset:presetId,label:args.node.title,parent,childId,cwd,
120
125
  signal:args.signal,delivery:'caller',agentOptions:{provider:args.route.providerId,model:args.route.modelId,maxTokens,
121
126
  // DSH merges same-route parent options into children. Clear any inherited effort when using the model default.
122
127
  reasoningEffort:reasoningOptions(args).reasoningEffort},
123
- prompt:[{type:'text',text:messages.map(m=>m.content).join('\n\n')+sourceIndex}]})
128
+ prompt:[{type:'text',text:prompt}]})
124
129
  cancel = ()=>{activation.dispose().catch(()=>{})}
125
130
  args.signal.addEventListener('abort',cancel,{once:true})
126
131
  if (args.signal.aborted) cancel()
package/host/client.mjs CHANGED
@@ -14,6 +14,7 @@ import {isNewVisiblePlan} from './plan-view.mjs'
14
14
  import {mountChoice,POLICY_OPTIONS} from '../ui/choices.mjs'
15
15
  import {composerPlacement} from './composer-layout.mjs'
16
16
  import {preserveExactComposerText} from './exact-composer-text.mjs'
17
+ import {ChatReplies,registerStandaloneReplies} from './chat-replies.mjs'
17
18
  import composerCSS from './composer.css'
18
19
 
19
20
  // Keep DSH's persisted sidebar tabs, series shortcuts and settings target valid across the package rename.
@@ -189,7 +190,7 @@ function TabBody({ctx,sessionId,defaultView,useTabInfo}) {
189
190
  }
190
191
  function Composer({ctx,sessionId}){
191
192
  const [state,setState]=useState(null),[opened,setOpened]=useState(false),[reason,error]=useState(''),[busy,pending]=useState(false)
192
- const bridge=useRef(null),button=useRef(null),menu=useRef(null),anchor=useRef(null)
193
+ const bridge=useRef(null),refreshState=useRef(null),button=useRef(null),menu=useRef(null),anchor=useRef(null)
193
194
  const [position,setPosition]=useState(null)
194
195
  const appearance=useEnchantAppearance()
195
196
  useEffect(()=>{
@@ -207,10 +208,11 @@ function Composer({ctx,sessionId}){
207
208
  ctx.sidebarRight.openTab(id,{params:{view:'graph',runId:value.run.runId}})
208
209
  shownPlans.set(sessionId,value.run.runId)
209
210
  }
210
- }catch(e){if(live)error(e.message)}
211
+ }catch(e){if(live && n===seq)error(e.message)}
211
212
  }
213
+ refreshState.current=refresh
212
214
  const off=b.subscribe(refresh);void refresh()
213
- return ()=>{live=false;off();b.dispose()}
215
+ return ()=>{live=false;off();b.dispose();bridge.current=null;refreshState.current=null}
214
216
  },[ctx,sessionId])
215
217
  useEffect(()=>{
216
218
  if(!opened)return
@@ -238,6 +240,9 @@ function Composer({ctx,sessionId}){
238
240
  visual?.removeEventListener('resize',measure);visual?.removeEventListener('scroll',measure)}
239
241
  },[opened])
240
242
  const pref=state?.composer || {enabled:false,routeIds:[]}, run=state?.run
243
+ const selectedIds=new Set(pref.routeIds)
244
+ const availableIds=(state?.routes || []).map(route=>route.id)
245
+ const availableSelected=availableIds.filter(routeId=>selectedIds.has(routeId)).length
241
246
  const materialIds=pref.materialIds || []
242
247
  const active=pref.enabled && pref.routeIds.length>0
243
248
  function openView(view){openSidebar(ctx,{view});setOpened(false)}
@@ -245,7 +250,7 @@ function Composer({ctx,sessionId}){
245
250
  async function change(type,p){
246
251
  const connection=bridge.current
247
252
  pending(true)
248
- try{await connection.action(type,p);const value=await connection.getState();if(connection===bridge.current){setState(value);error('')}}
253
+ try{await connection.action(type,p);if(connection===bridge.current)await refreshState.current()}
249
254
  catch(e){if(connection===bridge.current)error(e.message)}finally{if(connection===bridge.current)pending(false)}
250
255
  }
251
256
  const hint=run?.status==='awaiting_confirmation'?'待确认':run?.status==='planning'?'规划中':
@@ -266,6 +271,10 @@ function Composer({ctx,sessionId}){
266
271
  h('label',{className:'bs-field bs-toggle-row'},h('span',null,'在本会话启用协作'),h('input',{type:'checkbox',checked:pref.enabled,disabled:busy,
267
272
  onChange:e=>change('composer',{enabled:e.target.checked,routeIds:pref.routeIds})}),h('span',{className:'bs-switch','aria-hidden':true})),
268
273
  h(ComposerChoice,{label:'开工方式',options:POLICY_OPTIONS,value:pref.policy || 'manual',disabled:busy||!state,onChange:policy=>change('settings',{policy})}),
274
+ availableIds.length>0 && h('div',{className:'bs-clip-actions composer-roster'},
275
+ h('span',null,'已选 '+availableSelected+' / '+availableIds.length+' 个可用型号'),
276
+ h('button',{type:'button',disabled:busy || availableSelected===availableIds.length,
277
+ onClick:()=>change('composer',{enabled:pref.enabled,routeIds:[...new Set([...pref.routeIds,...availableIds])]})},'全选当前可用型号')),
269
278
  ...(state?.connections || []).map(group=>h('fieldset',{key:group.providerId},
270
279
  h('legend',{title:group.providerId},group.label+(group.label!==group.providerId && state.connections.filter(g=>g.label===group.label).length>1?' · '+group.providerId:'')),
271
280
  ...group.models.map(model=>h(Participant,{key:model.id,model,providerId:group.providerId,pref,busy,change})))),
@@ -289,9 +298,15 @@ function Composer({ctx,sessionId}){
289
298
  h('button',{type:'button',onClick:()=>manage('settings')},'协作设置')))),document.body)
290
299
  return h('span',{ref:anchor,style:{display:'inline-flex'},onClick:e=>e.stopPropagation()},h(SeriesSurface,null,
291
300
  h('button',{ref:button,type:'button',className:'bs-primary',style:{padding:'3px 8px'},
292
- title:reason || '本会话的协作开关、模型与进度','aria-expanded':opened,'aria-haspopup':'dialog',onClick:()=>setOpened(!opened)},'协作'+(hint?' · '+hint:''))),pop)
301
+ title:reason || '本会话的协作开关、模型与进度','aria-expanded':opened,'aria-haspopup':'dialog',onClick:()=>{
302
+ setOpened(!opened)
303
+ if (!opened && bridge.current) void change('refreshRoutes')
304
+ }},'协作'+(hint?' · '+hint:''))),pop)
293
305
  }
294
306
  export function apply(ctx){
307
+ ctx.inject?.(['uiConversation','sessions'],registerStandaloneReplies)
308
+ ctx.slots.inject('conversation.chat.turnTail',()=>ctx.slots.register({name:'conversation.chat.turnTail',id:id+'-replies',
309
+ inject:sessionId=>({sessionId})},ChatReplies))
295
310
  ctx.inject?.(['conversation','sessions'],ready=>ready.effect(()=>preserveExactComposerText(ready.conversation,ready.sessions,async sessionId=>{
296
311
  const bridge=hostBridge(ctx,sessionId,true)
297
312
  try{return (await bridge.getState()).composer?.enabled===true}
package/host/composer.css CHANGED
@@ -44,6 +44,7 @@
44
44
  .composer-menu .bs-field .model-id { font-family:var(--dsw-font-mono,monospace); }
45
45
  .composer-menu .composer-reasoning { padding:0 4px 10px 12px; }
46
46
  .composer-menu .composer-reasoning > span:first-child { color:var(--bs-muted); }
47
+ .composer-menu .composer-roster { justify-content:space-between; align-items:center; flex-wrap:wrap; padding:4px; }
47
48
  .composer-menu .composer-materials { border-top:1px solid var(--bs-border); margin-top:6px; padding:7px 0; }
48
49
  .composer-menu .composer-materials summary { cursor:pointer; display:list-item; list-style-position:inside; padding:8px 4px; }
49
50
  .composer-menu .composer-materials .bs-clip-actions { padding:4px 4px 7px; }
package/host/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto'
2
+ import {isDeepStrictEqual} from 'node:util'
2
3
  import { RunEngine } from '../src/engine.mjs'
3
4
  import { mayRead } from '../src/engine-plan.mjs'
4
5
  import { makeMaterial, patchSettings,settingsProfile } from '../src/context.mjs'
@@ -11,12 +12,12 @@ import { discoverRoutes, executorFor, plannerFor } from './models.mjs'
11
12
  import {choosePlanner} from '../src/role-routing.mjs'
12
13
  import { createChildren } from './children.mjs'
13
14
  import {sessionSelection} from './selection.mjs'
14
- import {isRollCall,prepareRollCall,executeRollCall,renderRollCall} from './roll-call.mjs'
15
+ import {isRollCall,prepareRollCall,executeRollCall} from './roll-call.mjs'
16
+ import {RUN_RECORD as RECORD, completedText, delivered, transcriptReply} from './reply-view.mjs'
15
17
 
16
18
  export const name = 'dsh-nova-lewis'
17
19
  export const inject = ['commands','llm','agents','sessions','sessionProjections','connection','storageDomain','webServer']
18
20
  export const CHANNEL = '/api/collaboration-local'
19
- const RECORD = 'plugin:collaboration/run'
20
21
  const MATERIAL = 'plugin:collaboration/material'
21
22
  const MATERIAL_SELECTION = 'plugin:collaboration/material-selection'
22
23
  const COMPOSER = 'plugin:collaboration/composer'
@@ -62,15 +63,6 @@ function delta(previous, snapshot) {
62
63
  }
63
64
  return {runId:snapshot.runId,fields,rows,order}
64
65
  }
65
- function delivered(snapshot) {
66
- const finals = snapshot.nodes.filter(n=>n.final && n.artifactId)
67
- const outputs = finals.length ? finals : snapshot.nodes.filter(n=>n.artifactId && !snapshot.nodes.some(next=>next.deps.includes(n.id)))
68
- return outputs.map(n=>snapshot.artifacts.find(a=>a.id===n.artifactId)).filter(Boolean)
69
- }
70
- function answerText(outputs) {
71
- return outputs.map(a=>a.text+(a.unresolved?.length ? '\n未决项:'+a.unresolved.join('、') : '')).join('\n\n') || '本次协作没有可交付的答复。'
72
- }
73
- const completedText = snapshot => snapshot.settings?.easterEgg ? renderRollCall(snapshot) : answerText(delivered(snapshot))
74
66
  const settled = run=>['completed','cancelled','blocked'].includes(run.status)
75
67
  function waitForRun(engine,ready,signal) {
76
68
  return new Promise((resolve,reject)=>{
@@ -111,30 +103,38 @@ export async function installHost(ctx,config,api) {
111
103
  const materialIds=room.materialSelection?.sessionId===sessionId ? room.materialSelection.ids : []
112
104
  return {enabled:saved?.enabled===true,routeIds:saved?.routeIds || [],reasoningLevels:saved?.reasoningLevels || {},policy:readProfile().settings.policy,materialIds}
113
105
  }
114
- let epoch = 0, catalogPromise
106
+ let epoch = 0, catalogPromise, lastCatalog
115
107
  function updated() { epoch++; for (const wake of [...observers.values()]) wake() }
116
- function catalog() {
117
- if (!catalogPromise) {
118
- catalogPromise = discoverRoutes(ctx).then(result=>{
119
- for (const r of result.routes) r.local ||= (config.localProviders || []).includes(r.providerId)
120
- return result
121
- }).catch(error=>{catalogPromise=null;throw error})
122
- }
123
- return catalogPromise
124
- }
125
- function refresh() {
126
- catalogPromise = null
127
- const pending = catalogPromise = catalog()
128
- pending.then(async({routes})=>{
129
- if (catalogPromise !== pending) return
130
- for (const record of engines.values()) if (!['completed','cancelled'].includes(record.engine.snapshot().status))
131
- await record.engine.updateRoutes(routes)
132
- updated()
133
- }).catch(()=>{})
108
+ function catalog(force=false) {
109
+ if (catalogPromise && !force) return catalogPromise
110
+ const pending=Promise.resolve().then(()=>catalogPromise===pending ? discoverRoutes(ctx) : catalog()).then(async result=>{
111
+ if (catalogPromise !== pending) return catalog()
112
+ for (const route of result.routes) route.local ||= (config.localProviders || []).includes(route.providerId)
113
+ const previous=lastCatalog
114
+ lastCatalog=result
115
+ if (previous && !isDeepStrictEqual(previous,result)) {
116
+ if (!isDeepStrictEqual(previous.routes,result.routes)) {
117
+ const running=[...engines.values()].filter(({engine})=>!['completed','cancelled'].includes(engine.snapshot().status))
118
+ await Promise.allSettled(running.map(({engine})=>engine.updateRoutes(result.routes)))
119
+ }
120
+ updated()
121
+ }
122
+ return catalogPromise===pending ? result : catalog()
123
+ })
124
+ catalogPromise=pending
125
+ pending.catch(()=>{if (catalogPromise===pending) catalogPromise=null})
134
126
  return pending
135
127
  }
128
+ const refresh=()=>catalog(true)
136
129
  ctx.on('llm/models-updated',refresh)
137
130
  ctx.on('llm/adapters-updated',refresh)
131
+ // DSH can save the profile, its model list and its credential separately.
132
+ // Adapter registration alone does not announce all three changes.
133
+ ctx.on('settings/document-updated',ns=>{
134
+ if (ctx.llm.listConfigurableProviders?.().some(entry=>entry.settingsNs===ns)) return refresh()
135
+ })
136
+ ctx.on('credentials/record-updated',refresh)
137
+ ctx.on('credentials/reference-updated',refresh)
138
138
  function bind(session,runId) {
139
139
  let last = view.stateOf(session).runs[runId]
140
140
  return {execute:args=>args.settings?.easterEgg ? executeRollCall(ctx,args) : execute(args),persist:async (snapshot,event)=>{
@@ -145,9 +145,15 @@ export async function installHost(ctx,config,api) {
145
145
  const text = completedText(data)
146
146
  const final = outputs.at(-1), route = [...(data.operations || []),...data.attempts].find(a=>a.id===final?.attemptId)?.route ||
147
147
  data.routes.find(r=>r.id===(final?.routeId || data.plannerRouteId))
148
- if (route) session.append('assistant/message',{turn:0,step:0,stream:[],message:{
149
- role:'assistant',id:randomUUID(),content:[{type:'text',text}],source:{kind:'model',provider:route.providerId,model:route.modelId}
150
- }},{surfaceOp:'append'})
148
+ if (route) {
149
+ const messageId=randomUUID()
150
+ const delivery=session.append('assistant/message',{turn:0,step:0,stream:[],message:{
151
+ role:'assistant',id:messageId,content:[{type:'text',text}],source:{kind:'model',provider:route.providerId,model:route.modelId}
152
+ }},{surfaceOp:'append'})
153
+ // Background deliveries have no native turn/end slot. Refer to the same
154
+ // persisted answer so the chat view can show it without a second message.
155
+ api.appendPluginRecord(session,'plugin:collaboration/reply-delivered',{messageId,...(delivery && {seq:delivery.seq})})
156
+ }
151
157
  }
152
158
  await ctx.sessions.flush(session)
153
159
  last = data
@@ -174,7 +180,7 @@ export async function installHost(ctx,config,api) {
174
180
  if (compact) {
175
181
  const snapshot=room.runs[selectedId]
176
182
  const run=snapshot && snapshot.sessionId===sessionId?{runId:snapshot.runId,status:snapshot.status,planVersion:snapshot.planVersion,
177
- createdAt:snapshot.createdAt,native:!!snapshot.settings?.nativePromptId && !snapshot.settings.easterEgg,
183
+ createdAt:snapshot.createdAt,native:!!snapshot.settings?.nativePromptId,
178
184
  assignmentsHash:snapshot.assignmentsHash,total:snapshot.nodes.length,done:snapshot.nodes.filter(n=>n.status==='done').length}:null
179
185
  const {routes,connections,warnings}=await catalog()
180
186
  return {mode:'host',sessionId,composer:composerSettings(room,sessionId),run,revision:epoch,
@@ -238,13 +244,12 @@ export async function installHost(ctx,config,api) {
238
244
  await profileQueue
239
245
  signal?.throwIfAborted()
240
246
  const {participants,replies,closing}=prepareRollCall(pref,routes)
241
- const {settings,settingsOverrides}=readProfile()
247
+ const {settings}=readProfile()
242
248
  const runId=randomUUID(), allowedRouteIds=participants.map(r=>r.id)
243
249
  const nodes=participants.map((route,i)=>({id:'roll-call-'+(i+1),routeId:route.id,title:route.label || route.modelId || route.id,
244
- deliverable:'点名回应 '+(i+1),acceptance:'从该型号的彩蛋选项中选一句。',outputReserve:1024,final:true,optional:true}))
250
+ deliverable:'点名回应 '+(i+1),acceptance:'从该型号的彩蛋选项中选一句。',final:true,optional:true}))
245
251
  const engine=new RunEngine({runId,sessionId:session.id,task:'在嘛?',mode:'auto',routes:participants,allowedRouteIds,
246
- settings:{...settings,...(!Object.hasOwn(settingsOverrides,'maxRequests') && {maxRequests:Math.max(settings.maxRequests,nodes.length)}),
247
- nativePromptId:promptId,easterEgg:{replies,closing},reasoningLevels:pref.reasoningLevels},
252
+ settings:{...settings,nativePromptId:promptId,easterEgg:{replies,closing},reasoningLevels:pref.reasoningLevels},
248
253
  ...bind(session,runId)})
249
254
  engines.set(runId,{session,engine}); active.set(session,runId)
250
255
  nativeDeliveries.set(runId,0)
@@ -287,7 +292,7 @@ export async function installHost(ctx,config,api) {
287
292
  const selectedMaterials=sources.slice()
288
293
  if (native?.history) sources.push(native.history)
289
294
  const runId = randomUUID()
290
- const runSettings={...settings,...(missing.length && {unavailableRouteIds:missing}),reasoningLevels:Object.fromEntries(allowed.filter(route=>route.reasoningLevels?.includes(preference.reasoningLevels[route.id]))
295
+ const runSettings={...settings,includeAllParticipants:p.mode!=='single',...(missing.length && {unavailableRouteIds:missing}),reasoningLevels:Object.fromEntries(allowed.filter(route=>route.reasoningLevels?.includes(preference.reasoningLevels[route.id]))
291
296
  .map(route=>[route.id,preference.reasoningLevels[route.id]])),
292
297
  ...(native?{nativePromptId:native.promptId}:{}),
293
298
  ...(native?.materialSelectionId?{nativeMaterialSelectionId:native.materialSelectionId}:{})}
@@ -373,12 +378,17 @@ export async function installHost(ctx,config,api) {
373
378
  })
374
379
  }
375
380
  if (endpoint==='wait') return {ok:true,value:{revision:epoch}}
381
+ if (endpoint==='reply') {
382
+ const session=ctx.sessions.get(p.sessionId)
383
+ if (!session) throw Error('当前会话尚未激活。')
384
+ return {ok:true,value:transcriptReply(session,p,runId=>view.stateOf(session).runs[runId])}
385
+ }
376
386
  if (endpoint==='state') return {ok:true,value:await state(p.sessionId,p.runId,p.compact===true)}
377
387
  if (endpoint==='action') return {ok:true,value:await action(p.sessionId,p.type,p.payload) ?? null}
378
388
  throw Error('未知协作接口。')
379
389
  } catch(error){return {ok:false,error:{code:'collaboration/error',message:error.message,details:{}}}}
380
390
  }
381
- for (const endpoint of ['state','wait','action']) {
391
+ for (const endpoint of ['state','wait','action','reply']) {
382
392
  ctx.connection.fetch.register({path:CHANNEL+'/'+endpoint,methods:['POST'],requestBody:'buffered',async fetch(req){
383
393
  try{
384
394
  const result=await listener(endpoint,await req.json(),req.signal,{principal:{kind:'owner'}})
@@ -433,7 +443,13 @@ export async function installHost(ctx,config,api) {
433
443
  const done=await waitForRun(engine,settled,options.signal)
434
444
  const body=done.status==='completed' ? completedText(done) :
435
445
  done.status==='cancelled'?'协作已取消。':'协作需要处理。'+(done.error || done.nodes.find(n=>n.reason)?.reason || '请打开任务图查看阻塞原因。')
436
- yield {type:'text-delta',index:0,text:body}
446
+ // Limit individual transport frames while preserving one complete assistant message.
447
+ for (let offset=0;offset<body.length;) {
448
+ let end=Math.min(offset+16384,body.length)
449
+ if (end<body.length && body.charCodeAt(end-1)>=0xd800 && body.charCodeAt(end-1)<=0xdbff) end--
450
+ yield {type:'text-delta',index:0,text:body.slice(offset,end)}
451
+ offset=end
452
+ }
437
453
  yield {type:'finish',reason:{kind:'stop'}}
438
454
  }catch(error){
439
455
  if (options.signal?.aborted) throw error
package/host/models.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { assembleContext, estimateInput } from '../src/context.mjs'
1
+ import { assembleContext, estimateInput, outputLimits } from '../src/context.mjs'
2
2
  import { normalizeUsage } from '../src/ledger.mjs'
3
3
  import { mayRead } from '../src/engine-plan.mjs'
4
4
  import { reviewInstruction,decodeReview } from '../src/engine-review.mjs'
@@ -114,22 +114,23 @@ export async function discoverRoutes(ctx) {
114
114
  const receipt = raw => raw ? normalizeUsage(raw, 'dsh', {uncertainZeros:true}) : null
115
115
  const visibleText = blocks => (blocks || []).filter(b => b.type === 'text').map(b => b.text).join('')
116
116
 
117
- export async function streamText(ctx, args, messages, desiredOutput) {
117
+ export async function streamText(ctx, args, messages, desiredOutput, margin) {
118
118
  const system = messages.filter(m => m.role === 'system').map(m => m.content).join('\n')
119
119
  const user = messages.filter(m => m.role !== 'system').map(m => ({
120
120
  role:'user', content:[{type:'text', text:m.content}]
121
121
  }))
122
122
  const inputEstimate = messages.reduce((s,m) => s + 4 + estimateInput(m.content), 2)
123
- const outputLimit = Math.min(desiredOutput || 3072, args.route.maxOutput || Infinity)
124
- const ceiling = args.reserveTokens ? await args.reserveTokens(inputEstimate,outputLimit) : args.maxAttemptTokens
125
- const maxTokens = Math.floor(Math.min(outputLimit, ceiling == null ? Infinity : ceiling - inputEstimate))
123
+ const {declared, available} = outputLimits(args.route, inputEstimate, desiredOutput, margin)
124
+ const ceiling = args.reserveTokens ? await args.reserveTokens(inputEstimate,available) : args.maxAttemptTokens
125
+ const maxTokens = Math.floor(Math.min(available, ceiling == null ? Infinity : ceiling - inputEstimate))
126
126
  if (maxTokens < 1) throw Object.assign(Error('该请求的输入估算已超出此次预算,请调整预算或缩短输入。'),{dispatched:false})
127
127
  const blocks = new Map()
128
128
  let usage = null, finish, observedOutput = false
129
129
  const chunks = ctx.llm.stream({provider:args.route.providerId, model:args.route.modelId, system,
130
- messages:user, maxTokens, signal:args.signal, sessionId:args.sessionId,
130
+ messages:user, ...(declared != null || Number.isFinite(ceiling) ? {maxTokens} : {}), signal:args.signal, sessionId:args.sessionId,
131
131
  ...reasoningOptions(args)})
132
132
  for await (const chunk of chunks) {
133
+ args.onStreamActivity?.()
133
134
  if (chunk.type === 'usage') {
134
135
  usage = receipt(chunk.usage)
135
136
  await args.report({usage})
@@ -188,16 +189,18 @@ export function plannerFor(ctx, options = {}) {
188
189
  const catalog = planningCards(args.routes,args.task)
189
190
  const windows=[args.route.window,args.route.contextWindow,args.route.deploymentWindow].filter(n=>n>0)
190
191
  const window=Math.min(...windows)
191
- const outputReserve=Math.max(1,Math.min(args.planningOutputTokens || 4096,Math.floor(window/2),
192
+ const requestedOutput=args.planningOutputTokens || 4096
193
+ const outputReserve=Math.max(1,Math.min(requestedOutput,4096,Math.floor(window/2),
192
194
  args.route.maxOutput || Infinity,args.route.outputLimit || Infinity))
193
195
  const instruction = [
194
196
  '你是 DSH 任务规划者。只输出 JSON 对象 {"rationale":"一句分工理由","nodes":[...]}。不要执行任务。',
195
197
  '每个节点包含 id,title,role,routeId,assignmentReason,difficulty,deps,sourceIds,requiredCapabilities,tools,deliverable,acceptance。由你为此步骤选择具体负责人,在 assignmentReason 中用一句话说明选择依据。使用目录中的实际路由 ID、唯一交付物、有效前置依赖。',
196
198
  '逐节点评定 difficulty。routine 是边界明确、可按固定规则验收的工作,standard 是常规专业工作,complex 是需要多步判断、权衡约束或处理依赖风险的工作。同一计划可包含不同难度。为执行节点给出具体的 instructions。',
197
- '在本次勾选的具体型号中,结合步骤本身、验收方式、实际能力与工具、型号卡的岗位依据和可选 workload 定位安排负责人。同一个 API 下的各型号各自独立,同一个型号也可承担多个步骤。资料未知的自定义型号仍可安排。不要按名称猜测能力、费用或速度,也不要为轮流使用型号而拆分任务。',
199
+ '在本次勾选的具体型号中,结合步骤本身、验收方式、实际能力与工具、型号卡的岗位依据和可选 workload 定位安排负责人。同一个 API 下的各型号各自独立,同一个型号也可承担多个步骤。资料未知的自定义型号仍可安排。不要按名称猜测能力、费用或速度。',
198
200
  '需要起草提示词再交给其他模型时,用 role=prompting 的节点独立交付提示词;在 promptFor 数组写接收节点 ID,接收步骤把它列入 deps。若用户只索要提示词,直接以提示词作为交付。普通问答无需增加起草轮次。',
199
201
  '根据本条任务、资料索引与本次参与型号,即席分析目标和依赖后设计分工。目录使用 profile 数字时,从 catalogProfiles 对应下标读取该型号的能力与工具。',
200
202
  '简单问答也由后续执行节点回答。统筹节点只画计划,不输出用户问题的答案。简单任务只用一个执行节点。多节点最后有 final 汇合所有必要成果;独立复核使用原文并声明 reviewOf。',
203
+ ...(args.settings?.includeAllParticipants ? ['只列出完成任务所需的分工。其余已选型号由系统安排独立建议,并交给你的最终负责人。'] : []),
201
204
  '资料索引仅供分配,切勿编造资料。每组资料至少有一个执行步骤负责;其后依赖该步骤的路由也须在同组可读范围。仅使用授权工具。请以用户的语言作答。'
202
205
  ].join('\n')
203
206
  const request = {task:args.task,workMode:options.workMode || 'recommended',catalog,
@@ -242,7 +245,8 @@ export function plannerFor(ctx, options = {}) {
242
245
  } catch (error) { if (!packed || !isContextOverflow(error)) throw error }
243
246
  }
244
247
  await args.report({context:packed.context,phase:'waiting'})
245
- const result = await streamText(ctx,args,packed.messages,packed.context.outputReserve)
248
+ const generationLimit = requestedOutput > 4096 ? requestedOutput : packed.context.outputReserve
249
+ const result = await streamText(ctx,args,packed.messages,generationLimit,packed.context.margin)
246
250
  let plan
247
251
  let invalid
248
252
  try { plan = JSON.parse(result.text.replace(/^\s*```(?:json)?\s*|\s*```\s*$/gi,'')) } catch {plan={};invalid='规划回执不是有效 JSON'}
@@ -292,7 +296,8 @@ export function executorFor(ctx, spawn) {
292
296
  const {messages,context,evidence} = assembleContext({task:args.task,node,route:args.route,inputs:args.inputs,
293
297
  materials:args.sources,settings:args.settings,tools:args.node.tools})
294
298
  await args.report({context,phase:'waiting'})
295
- const result = args.node.tools?.length ? await spawn(args,messages) : await streamText(ctx,args,messages,context.outputReserve)
299
+ const requestedOutput = node.outputReserve || args.settings?.outputReserve
300
+ const result = args.node.tools?.length ? await spawn(args,messages,context) : await streamText(ctx,args,messages,requestedOutput,context.margin)
296
301
  return {...result,...decodeReview(result.text,node),context,evidence}
297
302
  }
298
303
  }