dsh-nova-lewis 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.closing && createPortal(h(Replies,{value}),target))
151
+ }
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.
@@ -303,6 +304,9 @@ function Composer({ctx,sessionId}){
303
304
  }},'协作'+(hint?' · '+hint:''))),pop)
304
305
  }
305
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))
306
310
  ctx.inject?.(['conversation','sessions'],ready=>ready.effect(()=>preserveExactComposerText(ready.conversation,ready.sessions,async sessionId=>{
307
311
  const bridge=hostBridge(ctx,sessionId,true)
308
312
  try{return (await bridge.getState()).composer?.enabled===true}
package/host/index.mjs CHANGED
@@ -11,13 +11,13 @@ import { recommendationHistory } from '../src/recommendation.mjs'
11
11
  import { discoverRoutes, executorFor, plannerFor } from './models.mjs'
12
12
  import {choosePlanner} from '../src/role-routing.mjs'
13
13
  import { createChildren } from './children.mjs'
14
- import {sessionSelection} from './selection.mjs'
15
- import {isRollCall,prepareRollCall,executeRollCall,renderRollCall} from './roll-call.mjs'
14
+ import {runReasoningLevels,sessionSelection} from './selection.mjs'
15
+ import {isRollCall,prepareRollCall,executeRollCall} from './roll-call.mjs'
16
+ import {RUN_RECORD as RECORD, completedText, delivered, transcriptReply} from './reply-view.mjs'
16
17
 
17
18
  export const name = 'dsh-nova-lewis'
18
19
  export const inject = ['commands','llm','agents','sessions','sessionProjections','connection','storageDomain','webServer']
19
20
  export const CHANNEL = '/api/collaboration-local'
20
- const RECORD = 'plugin:collaboration/run'
21
21
  const MATERIAL = 'plugin:collaboration/material'
22
22
  const MATERIAL_SELECTION = 'plugin:collaboration/material-selection'
23
23
  const COMPOSER = 'plugin:collaboration/composer'
@@ -63,15 +63,6 @@ function delta(previous, snapshot) {
63
63
  }
64
64
  return {runId:snapshot.runId,fields,rows,order}
65
65
  }
66
- function delivered(snapshot) {
67
- const finals = snapshot.nodes.filter(n=>n.final && n.artifactId)
68
- const outputs = finals.length ? finals : snapshot.nodes.filter(n=>n.artifactId && !snapshot.nodes.some(next=>next.deps.includes(n.id)))
69
- return outputs.map(n=>snapshot.artifacts.find(a=>a.id===n.artifactId)).filter(Boolean)
70
- }
71
- function answerText(outputs) {
72
- return outputs.map(a=>a.text+(a.unresolved?.length ? '\n未决项:'+a.unresolved.join('、') : '')).join('\n\n') || '本次协作没有可交付的答复。'
73
- }
74
- const completedText = snapshot => snapshot.settings?.easterEgg ? renderRollCall(snapshot) : answerText(delivered(snapshot))
75
66
  const settled = run=>['completed','cancelled','blocked'].includes(run.status)
76
67
  function waitForRun(engine,ready,signal) {
77
68
  return new Promise((resolve,reject)=>{
@@ -154,9 +145,15 @@ export async function installHost(ctx,config,api) {
154
145
  const text = completedText(data)
155
146
  const final = outputs.at(-1), route = [...(data.operations || []),...data.attempts].find(a=>a.id===final?.attemptId)?.route ||
156
147
  data.routes.find(r=>r.id===(final?.routeId || data.plannerRouteId))
157
- if (route) session.append('assistant/message',{turn:0,step:0,stream:[],message:{
158
- role:'assistant',id:randomUUID(),content:[{type:'text',text}],source:{kind:'model',provider:route.providerId,model:route.modelId}
159
- }},{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
+ }
160
157
  }
161
158
  await ctx.sessions.flush(session)
162
159
  last = data
@@ -183,7 +180,7 @@ export async function installHost(ctx,config,api) {
183
180
  if (compact) {
184
181
  const snapshot=room.runs[selectedId]
185
182
  const run=snapshot && snapshot.sessionId===sessionId?{runId:snapshot.runId,status:snapshot.status,planVersion:snapshot.planVersion,
186
- createdAt:snapshot.createdAt,native:!!snapshot.settings?.nativePromptId && !snapshot.settings.easterEgg,
183
+ createdAt:snapshot.createdAt,native:!!snapshot.settings?.nativePromptId,
187
184
  assignmentsHash:snapshot.assignmentsHash,total:snapshot.nodes.length,done:snapshot.nodes.filter(n=>n.status==='done').length}:null
188
185
  const {routes,connections,warnings}=await catalog()
189
186
  return {mode:'host',sessionId,composer:composerSettings(room,sessionId),run,revision:epoch,
@@ -232,17 +229,18 @@ export async function installHost(ctx,config,api) {
232
229
  }
233
230
  }
234
231
  const create=(session,p,native)=>presets.run(()=>createRun(session,p,native))
235
- function rollCall(session,pref,promptId,signal) {
232
+ function rollCall(session,pref,promptId,options) {
236
233
  let pending=pendingRollCalls.get(session)
237
234
  if (!pending) { pending=new Map(); pendingRollCalls.set(session,pending) }
238
235
  if (pending.has(promptId)) return pending.get(promptId)
239
236
  const stored=Object.values(view.stateOf(session).runs).find(run=>run.sessionId===session.id && run.settings?.nativePromptId===promptId)
240
237
  if (stored) return Promise.resolve(stored.runId)
241
- const start=createRollCall(session,pref,promptId,signal).finally(()=>pending.delete(promptId))
238
+ const start=createRollCall(session,pref,promptId,options).finally(()=>pending.delete(promptId))
242
239
  pending.set(promptId,start)
243
240
  return start
244
241
  }
245
- async function createRollCall(session,pref,promptId,signal) {
242
+ async function createRollCall(session,pref,promptId,options) {
243
+ const {signal}=options
246
244
  const {routes}=await catalog()
247
245
  await profileQueue
248
246
  signal?.throwIfAborted()
@@ -252,7 +250,7 @@ export async function installHost(ctx,config,api) {
252
250
  const nodes=participants.map((route,i)=>({id:'roll-call-'+(i+1),routeId:route.id,title:route.label || route.modelId || route.id,
253
251
  deliverable:'点名回应 '+(i+1),acceptance:'从该型号的彩蛋选项中选一句。',final:true,optional:true}))
254
252
  const engine=new RunEngine({runId,sessionId:session.id,task:'在嘛?',mode:'auto',routes:participants,allowedRouteIds,
255
- settings:{...settings,nativePromptId:promptId,easterEgg:{replies,closing},reasoningLevels:pref.reasoningLevels},
253
+ settings:{...settings,nativePromptId:promptId,easterEgg:{replies,closing},reasoningLevels:runReasoningLevels(participants,pref,options)},
256
254
  ...bind(session,runId)})
257
255
  engines.set(runId,{session,engine}); active.set(session,runId)
258
256
  nativeDeliveries.set(runId,0)
@@ -295,8 +293,7 @@ export async function installHost(ctx,config,api) {
295
293
  const selectedMaterials=sources.slice()
296
294
  if (native?.history) sources.push(native.history)
297
295
  const runId = randomUUID()
298
- const runSettings={...settings,includeAllParticipants:p.mode!=='single',...(missing.length && {unavailableRouteIds:missing}),reasoningLevels:Object.fromEntries(allowed.filter(route=>route.reasoningLevels?.includes(preference.reasoningLevels[route.id]))
299
- .map(route=>[route.id,preference.reasoningLevels[route.id]])),
296
+ const runSettings={...settings,...(missing.length && {unavailableRouteIds:missing}),reasoningLevels:runReasoningLevels(allowed,preference,native?.selection),
300
297
  ...(native?{nativePromptId:native.promptId}:{}),
301
298
  ...(native?.materialSelectionId?{nativeMaterialSelectionId:native.materialSelectionId}:{})}
302
299
  const engine = new RunEngine({runId,sessionId:session.id,task,routes,settings:runSettings,sources,plannerAssignment,
@@ -381,12 +378,17 @@ export async function installHost(ctx,config,api) {
381
378
  })
382
379
  }
383
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
+ }
384
386
  if (endpoint==='state') return {ok:true,value:await state(p.sessionId,p.runId,p.compact===true)}
385
387
  if (endpoint==='action') return {ok:true,value:await action(p.sessionId,p.type,p.payload) ?? null}
386
388
  throw Error('未知协作接口。')
387
389
  } catch(error){return {ok:false,error:{code:'collaboration/error',message:error.message,details:{}}}}
388
390
  }
389
- for (const endpoint of ['state','wait','action']) {
391
+ for (const endpoint of ['state','wait','action','reply']) {
390
392
  ctx.connection.fetch.register({path:CHANNEL+'/'+endpoint,methods:['POST'],requestBody:'buffered',async fetch(req){
391
393
  try{
392
394
  const result=await listener(endpoint,await req.json(),req.signal,{principal:{kind:'owner'}})
@@ -417,7 +419,7 @@ export async function installHost(ctx,config,api) {
417
419
  let runId=snapshotList.find(r=>r.settings?.nativePromptId===promptId)?.runId, engine
418
420
  let blockStarted=false
419
421
  try{
420
- if (!runId && egg) runId=await rollCall(session,pref,promptId,options.signal)
422
+ if (!runId && egg) runId=await rollCall(session,pref,promptId,options)
421
423
  if (!runId) {
422
424
  const currentIds=new Set(current.map(m=>m.id))
423
425
  const historyText=options.messages.filter(m=>!currentIds.has(m.id) && (m.role==='assistant'||m.role==='user'&&m.source?.kind==='user'))
@@ -431,7 +433,8 @@ export async function installHost(ctx,config,api) {
431
433
  const provider=(await catalog()).routes.find(r=>r.providerId===options.provider && r.modelId===options.model && selected.includes(r.id))
432
434
  const materialIds=pref.materialIds
433
435
  const created=await create(session,{task,routeIds:selected,preferredPlannerId:provider?.id,materialIds},
434
- {history,promptId,materialSelectionId:materialIds.length?room.materialSelection.id:null})
436
+ {history,promptId,selection:{provider:options.provider,model:options.model,reasoningEffort:options.reasoningEffort},
437
+ materialSelectionId:materialIds.length?room.materialSelection.id:null})
435
438
  runId=created.runId
436
439
  }
437
440
  engine=obtain(session,runId)
package/host/models.mjs CHANGED
@@ -86,11 +86,16 @@ export async function discoverRoutes(ctx) {
86
86
  const efforts=info.reasoning?.efforts
87
87
  const reasoningLevels=Array.isArray(efforts) ? identifiedRows(efforts).map(effort=>effort.id) : []
88
88
  if (info.reasoning!=null && !reasoningLevels.length) reasoningUnavailable=true
89
+ // pi-ai can send disabled thinking on omission even when the profile only offers active levels.
90
+ // DSH orders the exact model's levels from least to greatest and owns any configured default.
91
+ const requiredEffort = configured.has(provider.id) && info.reasoning?.defaultEffort == null &&
92
+ !reasoningLevels.includes('off') ? reasoningLevels[0] : undefined
89
93
  return {
90
94
  id: routeKey(provider.id, model.id), providerId: provider.id, apiId: provider.id, apiLabel: displayName(provider),
91
95
  modelId: model.id, label: displayName(model), enabled: true, capabilities, capabilitySource: modalities == null ? 'text-assumed' : 'catalog',
92
96
  contextWindow: window,window,
93
97
  ...(reasoningLevels.length && {reasoningLevels}),
98
+ ...(requiredEffort && {requiredReasoningEffort:requiredEffort}),
94
99
  ...(reasoningUnavailable && {reasoningUnavailable:true}),
95
100
  maxOutput: positiveLimit(info.defaultMaxTokens) ?? positiveLimit(model.maxTokens), local: configured.get(provider.id)?.local===true, upstream: null,
96
101
  }
@@ -124,24 +129,49 @@ export async function streamText(ctx, args, messages, desiredOutput, margin) {
124
129
  const ceiling = args.reserveTokens ? await args.reserveTokens(inputEstimate,available) : args.maxAttemptTokens
125
130
  const maxTokens = Math.floor(Math.min(available, ceiling == null ? Infinity : ceiling - inputEstimate))
126
131
  if (maxTokens < 1) throw Object.assign(Error('该请求的输入估算已超出此次预算,请调整预算或缩短输入。'),{dispatched:false})
132
+ const idle = new AbortController()
133
+ const signal = AbortSignal.any([args.signal, idle.signal])
134
+ signal.throwIfAborted()
135
+ let onAbort, timer
136
+ const aborted = new Promise((_, reject) => {
137
+ onAbort = () => reject(signal.reason)
138
+ signal.addEventListener('abort', onAbort, {once:true})
139
+ })
140
+ const activity = () => {
141
+ clearTimeout(timer)
142
+ timer = setTimeout(() => idle.abort(Error('模型连接长时间未返回数据。')), 5 * 60_000).unref()
143
+ }
144
+ activity()
145
+ try {
146
+ const chunks = ctx.llm.stream({provider:args.route.providerId, model:args.route.modelId, system,
147
+ messages:user, ...(declared != null || Number.isFinite(ceiling) ? {maxTokens} : {}), signal, sessionId:args.sessionId,
148
+ ...reasoningOptions(args)})
149
+ // Some adapters ignore abort and never settle their iterator. Free the slot independently.
150
+ return await Promise.race([collectText(chunks, signal, activity, args.report, maxTokens, inputEstimate), aborted])
151
+ } finally {
152
+ clearTimeout(timer)
153
+ signal.removeEventListener('abort', onAbort)
154
+ }
155
+ }
156
+
157
+ async function collectText(chunks, signal, activity, report, maxTokens, inputEstimate) {
127
158
  const blocks = new Map()
128
159
  let usage = null, finish, observedOutput = false
129
- const chunks = ctx.llm.stream({provider:args.route.providerId, model:args.route.modelId, system,
130
- messages:user, ...(declared != null || Number.isFinite(ceiling) ? {maxTokens} : {}), signal:args.signal, sessionId:args.sessionId,
131
- ...reasoningOptions(args)})
132
160
  for await (const chunk of chunks) {
133
- args.onStreamActivity?.()
161
+ signal.throwIfAborted()
162
+ activity()
134
163
  if (chunk.type === 'usage') {
135
164
  usage = receipt(chunk.usage)
136
- await args.report({usage})
165
+ await report({usage})
137
166
  } else if (chunk.type === 'text-delta' || (chunk.type === 'block-end' && chunk.block.type === 'text')) {
138
- if (!observedOutput) { observedOutput = true; await args.report({phase:'streaming'}) }
167
+ if (!observedOutput) { observedOutput = true; await report({phase:'streaming'}) }
139
168
  blocks.set(chunk.index, chunk.type === 'text-delta' ? (blocks.get(chunk.index) || '') + chunk.text : chunk.block.text)
140
169
  } else if (chunk.type === 'finish') finish = chunk.reason
141
170
  }
142
- if (args.signal.aborted || finish?.kind !== 'stop') {
143
- const error = Error(args.signal.aborted ? '运行已取消' : finish?.failure?.message || '模型响应未完整结束(' + (finish?.kind || '连接中断') + ')')
144
- if (!args.signal.aborted && finish?.kind === 'max-tokens') Object.assign(error,{finishKind:'max-tokens',maxTokens,inputEstimate})
171
+ signal.throwIfAborted()
172
+ if (finish?.kind !== 'stop') {
173
+ const error = Error(finish?.failure?.message || '模型响应未完整结束(' + (finish?.kind || '连接中断') + ')')
174
+ if (finish?.kind === 'max-tokens') Object.assign(error,{finishKind:'max-tokens',maxTokens,inputEstimate})
145
175
  error.usage = usage
146
176
  error.retryAfterMs = finish?.failure?.providerRetryAfterMs
147
177
  throw error
@@ -192,18 +222,22 @@ export function plannerFor(ctx, options = {}) {
192
222
  const requestedOutput=args.planningOutputTokens || 4096
193
223
  const outputReserve=Math.max(1,Math.min(requestedOutput,4096,Math.floor(window/2),
194
224
  args.route.maxOutput || Infinity,args.route.outputLimit || Infinity))
225
+ const allowDirectAnswer = args.allowDirectAnswer === true && !options.materials?.length
195
226
  const instruction = [
196
- '你是 DSH 任务规划者。只输出 JSON 对象 {"rationale":"一句分工理由","nodes":[...]}。不要执行任务。',
227
+ '你是 DSH 任务规划者。先判断完成用户任务所需的最少步骤和型号,只输出 JSON 对象。',
228
+ allowDirectAnswer
229
+ ? '若你能直接用已给文本完成问答,无需工具、指定的其他负责人或独立复核,直接输出 {"answer":"完整答复"}。否则输出 {"rationale":"分工理由","nodes":[...]}。'
230
+ : '输出 {"rationale":"一句分工理由","nodes":[...]},等计划发布、确认后由执行节点工作。',
197
231
  '每个节点包含 id,title,role,routeId,assignmentReason,difficulty,deps,sourceIds,requiredCapabilities,tools,deliverable,acceptance。由你为此步骤选择具体负责人,在 assignmentReason 中用一句话说明选择依据。使用目录中的实际路由 ID、唯一交付物、有效前置依赖。',
198
232
  '逐节点评定 difficulty。routine 是边界明确、可按固定规则验收的工作,standard 是常规专业工作,complex 是需要多步判断、权衡约束或处理依赖风险的工作。同一计划可包含不同难度。为执行节点给出具体的 instructions。',
199
233
  '在本次勾选的具体型号中,结合步骤本身、验收方式、实际能力与工具、型号卡的岗位依据和可选 workload 定位安排负责人。同一个 API 下的各型号各自独立,同一个型号也可承担多个步骤。资料未知的自定义型号仍可安排。不要按名称猜测能力、费用或速度。',
200
234
  '需要起草提示词再交给其他模型时,用 role=prompting 的节点独立交付提示词;在 promptFor 数组写接收节点 ID,接收步骤把它列入 deps。若用户只索要提示词,直接以提示词作为交付。普通问答无需增加起草轮次。',
201
235
  '根据本条任务、资料索引与本次参与型号,即席分析目标和依赖后设计分工。目录使用 profile 数字时,从 catalogProfiles 对应下标读取该型号的能力与工具。',
202
- '简单问答也由后续执行节点回答。统筹节点只画计划,不输出用户问题的答案。简单任务只用一个执行节点。多节点最后有 final 汇合所有必要成果;独立复核使用原文并声明 reviewOf。',
203
- ...(args.settings?.includeAllParticipants ? ['只列出完成任务所需的分工。其余已选型号由系统安排独立建议,并交给你的最终负责人。'] : []),
236
+ '勾选型号是可调用范围。简单任务至多安排一个工作节点;复杂任务可全程由最合适的一个型号完成。仅在分工对交付有帮助时调用其他型号。可在多个节点重复使用同一型号,用 deps 传递上一步成果。',
237
+ '统一交付由最后一个工作节点完成,仅在确需整合时安排合稿。用户要求分别交付时,把各独立终点标为 final:true。独立复核使用原文并声明 reviewOf。平替只列入 fallbackRouteIds,主选无法交付才调用。',
204
238
  '资料索引仅供分配,切勿编造资料。每组资料至少有一个执行步骤负责;其后依赖该步骤的路由也须在同组可读范围。仅使用授权工具。请以用户的语言作答。'
205
239
  ].join('\n')
206
- const request = {task:args.task,workMode:options.workMode || 'recommended',catalog,
240
+ const request = {task:args.task,workMode:options.workMode || 'recommended',allowDirectAnswer,catalog,
207
241
  materials:args.sources,materialRouteGroups:(options.materials || []).map(source=>({
208
242
  ...(args.sources.some(s=>s.id===source.id)?{id:source.id}:{}),routeIds:args.routes.filter(r=>mayRead(source,r)).map(r=>r.id)
209
243
  })), allowedTools:options.allowedTools || [],
@@ -250,6 +284,12 @@ export function plannerFor(ctx, options = {}) {
250
284
  let plan
251
285
  let invalid
252
286
  try { plan = JSON.parse(result.text.replace(/^\s*```(?:json)?\s*|\s*```\s*$/gi,'')) } catch {plan={};invalid='规划回执不是有效 JSON'}
287
+ if (Object.hasOwn(plan ?? {}, 'answer')) {
288
+ if (allowDirectAnswer && plan.nodes === undefined && typeof plan.answer === 'string' && plan.answer.trim()) {
289
+ return {answer:plan.answer.trim(),usage:result.usage,context:packed.context}
290
+ }
291
+ invalid = '请使用本次允许的答复格式;分工计划须包含执行节点,不能同时给出 answer。'
292
+ }
253
293
  if (Array.isArray(plan?.nodes)) {
254
294
  const ids=new Set(catalog.map(r=>r.id))
255
295
  for (const n of plan.nodes) {
@@ -0,0 +1,85 @@
1
+ import {formatEggMessage, formatEggReply} from '../src/easter-egg.mjs'
2
+ import {isRollCall, renderRollCall, rollCallReplies} from './roll-call.mjs'
3
+
4
+ export const RUN_RECORD = 'plugin:collaboration/run'
5
+
6
+ export function delivered(run) {
7
+ const finals = run.nodes.filter(node => node.final && node.artifactId)
8
+ const used = new Set(run.nodes.flatMap(node => node.deps || []))
9
+ const outputs = finals.length ? finals : run.nodes.filter(node => node.artifactId && !used.has(node.id))
10
+ const artifacts = new Map(run.artifacts.map(artifact => [artifact.id, artifact]))
11
+ return outputs.map(node => artifacts.get(node.artifactId)).filter(Boolean)
12
+ }
13
+
14
+ function artifactText(artifact) {
15
+ return artifact.text + (artifact.unresolved?.length ? '\n未决项:' + artifact.unresolved.join('、') : '')
16
+ }
17
+
18
+ export function completedText(run) {
19
+ if (run.settings?.easterEgg) return renderRollCall(run)
20
+ return delivered(run).map(artifactText).join('\n\n') || '本次协作没有可交付的答复。'
21
+ }
22
+
23
+ function matchingRollCall(run, markdown) {
24
+ const replies = rollCallReplies(run)
25
+ const closing = run.settings.easterEgg.closing
26
+ if (renderRollCall(run, replies) !== markdown) {
27
+ const legacy = rollCallReplies(run, true)
28
+ if (renderRollCall(run, legacy) !== markdown) {
29
+ // 0.2.2 and 0.2.3 included the account name in saved lines.
30
+ const older = legacy.map(({route, text}) => {
31
+ const provider = route.providerId || route.apiId
32
+ const name = route.modelId || route.label || route.id
33
+ return formatEggReply({modelId:provider ? provider + ' / ' + name : name}, text)
34
+ })
35
+ if (formatEggMessage(older, closing) !== markdown) return null
36
+ }
37
+ }
38
+ return {kind:'roll-call', markdown, participants:replies.map(({route, text}) => ({name:route.modelId || route.label || route.id, text})),
39
+ closing:closing.slice(2, -2)}
40
+ }
41
+
42
+ // The transcript slot identifies a persisted assistant event. Only a completed
43
+ // Nova run in that exact DSH step can supply its attribution and deliverables.
44
+ export function transcriptReply(session, {messageId, seq}, getRun) {
45
+ if (!session || typeof messageId !== 'string' || !messageId) return null
46
+ let at
47
+ if (typeof session.eventAt === 'function' && Number.isSafeInteger(seq) && seq >= 0) {
48
+ if (seq >= session.seq) throw Error('消息尚未保存。')
49
+ at = index => session.eventAt(index)
50
+ } else {
51
+ const events = session.ownEvents()
52
+ seq = events.findIndex(event => event.type === 'assistant/message' && event.data.message?.id === messageId)
53
+ at = index => events[index]
54
+ }
55
+ const entry = at(seq)
56
+ const message = entry?.data?.message
57
+ if (entry?.type !== 'assistant/message' || message?.id !== messageId || message.role !== 'assistant' ||
58
+ message.source?.kind !== 'model' || !message.content?.length || message.content.some(b => b.type !== 'text')) return null
59
+ const markdown = message.content.map(block => block.text).join('')
60
+ // Command/workbench delivery appends its own assistant event immediately after
61
+ // persisting completion, outside the agent loop (turn 0, step 0).
62
+ const standalone = entry.data.turn === 0 && entry.data.step === 0
63
+ const candidates = [], inputs = []
64
+ for (let pos = seq - 1; pos >= 0; pos--) {
65
+ const event = at(pos)
66
+ if (!event || event.type === 'step/start' || event.type === 'turn/start') break
67
+ if (event.type === RUN_RECORD && event.ignorable === true && event.data.fields?.status === 'completed')
68
+ candidates.push(event.data.runId)
69
+ if (standalone) break
70
+ if (event.type === 'assistant/message' && event.data.turn !== 0) break
71
+ if (event.type === 'user/message' && event.data.source?.kind === 'user') inputs.push(event.data)
72
+ }
73
+ if (!standalone && !isRollCall(inputs)) return null
74
+ for (const runId of candidates) {
75
+ const run = getRun(runId)
76
+ if (!run) continue
77
+ if (standalone) {
78
+ if (completedText(run) === markdown) return {kind:'answer', markdown}
79
+ } else if (run.settings?.easterEgg && run.settings.nativePromptId === inputs[0].id) {
80
+ const reply = matchingRollCall(run, markdown)
81
+ if (reply) return reply
82
+ }
83
+ }
84
+ return null
85
+ }
@@ -74,45 +74,28 @@ export async function executeRollCall(ctx, args) {
74
74
  {role:'system', content:'NOVA 彩蛋点名。用户问“在嘛?”。请从用户消息的 JSON 数组中任选一句作答。只返回从 1 开始的选项编号,或逐字返回所选原句。'},
75
75
  {role:'user', content:JSON.stringify(reply.choices)},
76
76
  ]
77
- // Reasoning and output both count as activity; only a silent provider should lose its slot.
78
- const idle = new AbortController()
79
- const signal = AbortSignal.any([args.signal, idle.signal])
80
- signal.throwIfAborted()
81
- let onAbort
82
- const aborted = new Promise((_, reject) => {
83
- onAbort = () => reject(signal.reason)
84
- signal.addEventListener('abort', onAbort, {once:true})
85
- })
86
- let result
87
- let timer
88
- const onStreamActivity = () => {
89
- clearTimeout(timer)
90
- if (!signal.aborted) timer = setTimeout(() => idle.abort(Error('点名连接长时间未返回数据。')), 5 * 60_000).unref()
91
- }
92
- onStreamActivity()
93
- try {
94
- result = await Promise.race([streamText(ctx, {...args, signal, onStreamActivity}, messages), aborted])
95
- } finally {
96
- clearTimeout(timer)
97
- signal.removeEventListener('abort', onAbort)
98
- }
77
+ const result = await streamText(ctx, args, messages)
99
78
  const chosen = selectedPhrase(result.text, reply.choices)
100
79
  if (chosen === undefined) throw Object.assign(Error('该型号未返回有效的彩蛋选项。'), {usage:result.usage})
101
80
  return {...result, text:chosen}
102
81
  }
103
82
 
104
- export function renderRollCall(snapshot) {
105
- const {replies, closing} = snapshot.settings.easterEgg
83
+ export function rollCallReplies(snapshot, legacyPlaceholders=false) {
84
+ const {replies} = snapshot.settings.easterEgg
106
85
  const directory = new Map(snapshot.routes.map(route => [route.id, route]))
107
86
  const nodes = new Map(snapshot.nodes.map(node => [node.routeId, node]))
108
87
  const artifacts = new Map(snapshot.artifacts.map(artifact => [artifact.id, artifact]))
109
- const lines = replies.map(({routeId, choices}) => {
88
+ return replies.flatMap(({routeId, choices}) => {
110
89
  const route = directory.get(routeId) || unavailableRoute(routeId)
111
90
  const node = nodes.get(routeId)
112
91
  const artifact = artifacts.get(node?.artifactId)
113
- const text = artifact?.routeId === routeId && choices.includes(artifact.text) ? artifact.text :
114
- route.enabled === false ? '(型号当前不可用)' : '(本次未回应)'
115
- return formatEggReply(route, text)
92
+ if (artifact?.routeId === routeId && choices.includes(artifact.text)) return [{route, text:artifact.text}]
93
+ // Earlier releases wrote a row for every checkbox into the durable assistant message.
94
+ if (legacyPlaceholders) return [{route, text:route.enabled === false ? '(型号当前不可用)' : '(本次未回应)'}]
95
+ return []
116
96
  })
117
- return formatEggMessage(lines, closing)
97
+ }
98
+
99
+ export function renderRollCall(snapshot, replies = rollCallReplies(snapshot)) {
100
+ return formatEggMessage(replies.map(({route, text}) => formatEggReply(route, text)), snapshot.settings.easterEgg.closing)
118
101
  }
@@ -21,7 +21,19 @@ function reasoningSelection(patch, available, previous) {
21
21
 
22
22
  export function reasoningOptions({route, settings}) {
23
23
  const level = settings?.reasoningLevels?.[route.id]
24
- return route.reasoningLevels?.includes(level) ? {reasoningEffort:level} : {}
24
+ const effort = route.reasoningLevels?.includes(level) ? level : route.requiredReasoningEffort
25
+ return effort && route.reasoningLevels?.includes(effort) ? {reasoningEffort:effort} : {}
26
+ }
27
+
28
+ export function runReasoningLevels(routes, preference, native) {
29
+ const result = {}
30
+ for (const route of routes) {
31
+ const selected = preference.reasoningLevels?.[route.id]
32
+ if (route.reasoningLevels?.includes(selected)) result[route.id] = selected
33
+ else if (route.providerId === native?.provider && route.modelId === native?.model &&
34
+ route.reasoningLevels?.includes(native?.reasoningEffort)) result[route.id] = native.reasoningEffort
35
+ }
36
+ return result
25
37
  }
26
38
 
27
39
  export function sessionSelection(patch,available,previous) {