dsh-nova-lewis 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.cn.md +5 -5
- package/README.md +8 -8
- package/dist/client.js +90 -27
- package/host/children.mjs +8 -3
- package/host/client.mjs +23 -5
- package/host/composer.css +1 -0
- package/host/exact-composer-text.mjs +31 -0
- package/host/index.mjs +107 -54
- package/host/models.mjs +15 -10
- package/host/plan-view.mjs +0 -17
- package/host/roll-call.mjs +118 -0
- package/package.json +5 -5
- package/src/context.mjs +15 -3
- package/src/easter-egg.mjs +86 -0
- package/src/engine-plan.mjs +37 -3
- package/src/engine.mjs +11 -7
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,7 +12,7 @@ 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 {
|
|
15
|
+
import {isRollCall,prepareRollCall,executeRollCall,renderRollCall} from './roll-call.mjs'
|
|
15
16
|
|
|
16
17
|
export const name = 'dsh-nova-lewis'
|
|
17
18
|
export const inject = ['commands','llm','agents','sessions','sessionProjections','connection','storageDomain','webServer']
|
|
@@ -63,9 +64,14 @@ function delta(previous, snapshot) {
|
|
|
63
64
|
return {runId:snapshot.runId,fields,rows,order}
|
|
64
65
|
}
|
|
65
66
|
function delivered(snapshot) {
|
|
66
|
-
const
|
|
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)))
|
|
67
69
|
return outputs.map(n=>snapshot.artifacts.find(a=>a.id===n.artifactId)).filter(Boolean)
|
|
68
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))
|
|
69
75
|
const settled = run=>['completed','cancelled','blocked'].includes(run.status)
|
|
70
76
|
function waitForRun(engine,ready,signal) {
|
|
71
77
|
return new Promise((resolve,reject)=>{
|
|
@@ -99,48 +105,55 @@ export async function installHost(ctx,config,api) {
|
|
|
99
105
|
ctx.effect(()=>()=>author.dispose(),'collaboration author settings')
|
|
100
106
|
const spawn = createChildren(ctx,config), execute = executorFor(ctx,spawn)
|
|
101
107
|
const engines = new Map(), active = new WeakMap(), observers = new Map()
|
|
102
|
-
const nativeDeliveries = new
|
|
108
|
+
const nativeDeliveries = new Map()
|
|
109
|
+
const pendingRollCalls = new WeakMap()
|
|
103
110
|
const composerSettings=(room,sessionId)=>{
|
|
104
111
|
const saved=room.composer?.sessionId===sessionId && room.composer
|
|
105
112
|
const materialIds=room.materialSelection?.sessionId===sessionId ? room.materialSelection.ids : []
|
|
106
113
|
return {enabled:saved?.enabled===true,routeIds:saved?.routeIds || [],reasoningLevels:saved?.reasoningLevels || {},policy:readProfile().settings.policy,materialIds}
|
|
107
114
|
}
|
|
108
|
-
let epoch = 0, catalogPromise
|
|
115
|
+
let epoch = 0, catalogPromise, lastCatalog
|
|
109
116
|
function updated() { epoch++; for (const wake of [...observers.values()]) wake() }
|
|
110
|
-
function catalog() {
|
|
111
|
-
if (!
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
117
|
+
function catalog(force=false) {
|
|
118
|
+
if (catalogPromise && !force) return catalogPromise
|
|
119
|
+
const pending=Promise.resolve().then(()=>catalogPromise===pending ? discoverRoutes(ctx) : catalog()).then(async result=>{
|
|
120
|
+
if (catalogPromise !== pending) return catalog()
|
|
121
|
+
for (const route of result.routes) route.local ||= (config.localProviders || []).includes(route.providerId)
|
|
122
|
+
const previous=lastCatalog
|
|
123
|
+
lastCatalog=result
|
|
124
|
+
if (previous && !isDeepStrictEqual(previous,result)) {
|
|
125
|
+
if (!isDeepStrictEqual(previous.routes,result.routes)) {
|
|
126
|
+
const running=[...engines.values()].filter(({engine})=>!['completed','cancelled'].includes(engine.snapshot().status))
|
|
127
|
+
await Promise.allSettled(running.map(({engine})=>engine.updateRoutes(result.routes)))
|
|
128
|
+
}
|
|
129
|
+
updated()
|
|
130
|
+
}
|
|
131
|
+
return catalogPromise===pending ? result : catalog()
|
|
132
|
+
})
|
|
133
|
+
catalogPromise=pending
|
|
134
|
+
pending.catch(()=>{if (catalogPromise===pending) catalogPromise=null})
|
|
128
135
|
return pending
|
|
129
136
|
}
|
|
137
|
+
const refresh=()=>catalog(true)
|
|
130
138
|
ctx.on('llm/models-updated',refresh)
|
|
131
139
|
ctx.on('llm/adapters-updated',refresh)
|
|
140
|
+
// DSH can save the profile, its model list and its credential separately.
|
|
141
|
+
// Adapter registration alone does not announce all three changes.
|
|
142
|
+
ctx.on('settings/document-updated',ns=>{
|
|
143
|
+
if (ctx.llm.listConfigurableProviders?.().some(entry=>entry.settingsNs===ns)) return refresh()
|
|
144
|
+
})
|
|
145
|
+
ctx.on('credentials/record-updated',refresh)
|
|
146
|
+
ctx.on('credentials/reference-updated',refresh)
|
|
132
147
|
function bind(session,runId) {
|
|
133
148
|
let last = view.stateOf(session).runs[runId]
|
|
134
|
-
return {execute,persist:async (snapshot,event)=>{
|
|
149
|
+
return {execute:args=>args.settings?.easterEgg ? executeRollCall(ctx,args) : execute(args),persist:async (snapshot,event)=>{
|
|
135
150
|
const data = clean(snapshot)
|
|
136
151
|
api.appendPluginRecord(session,RECORD,delta(last,data))
|
|
137
152
|
if (data.status==='completed' && last?.status!=='completed' && !nativeDeliveries.has(runId)) {
|
|
138
153
|
const outputs = delivered(data)
|
|
139
|
-
const text =
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
].join('\n\n')
|
|
143
|
-
const final = outputs.at(-1), route = data.attempts.find(a=>a.id===final?.attemptId)?.route
|
|
154
|
+
const text = completedText(data)
|
|
155
|
+
const final = outputs.at(-1), route = [...(data.operations || []),...data.attempts].find(a=>a.id===final?.attemptId)?.route ||
|
|
156
|
+
data.routes.find(r=>r.id===(final?.routeId || data.plannerRouteId))
|
|
144
157
|
if (route) session.append('assistant/message',{turn:0,step:0,stream:[],message:{
|
|
145
158
|
role:'assistant',id:randomUUID(),content:[{type:'text',text}],source:{kind:'model',provider:route.providerId,model:route.modelId}
|
|
146
159
|
}},{surfaceOp:'append'})
|
|
@@ -170,7 +183,7 @@ export async function installHost(ctx,config,api) {
|
|
|
170
183
|
if (compact) {
|
|
171
184
|
const snapshot=room.runs[selectedId]
|
|
172
185
|
const run=snapshot && snapshot.sessionId===sessionId?{runId:snapshot.runId,status:snapshot.status,planVersion:snapshot.planVersion,
|
|
173
|
-
createdAt:snapshot.createdAt,native:!!snapshot.settings?.nativePromptId,
|
|
186
|
+
createdAt:snapshot.createdAt,native:!!snapshot.settings?.nativePromptId && !snapshot.settings.easterEgg,
|
|
174
187
|
assignmentsHash:snapshot.assignmentsHash,total:snapshot.nodes.length,done:snapshot.nodes.filter(n=>n.status==='done').length}:null
|
|
175
188
|
const {routes,connections,warnings}=await catalog()
|
|
176
189
|
return {mode:'host',sessionId,composer:composerSettings(room,sessionId),run,revision:epoch,
|
|
@@ -196,7 +209,7 @@ export async function installHost(ctx,config,api) {
|
|
|
196
209
|
const launch = ()=>engine.plan(planner).catch(()=>updated())
|
|
197
210
|
const jobs=ctx.get ? ctx.get('jobs') : ctx.jobs
|
|
198
211
|
if (!jobs) { void launch(); return }
|
|
199
|
-
const {
|
|
212
|
+
const {task} = engine.snapshot()
|
|
200
213
|
try {
|
|
201
214
|
jobs.start({owner:session.id,kind:'collab',label:task.replace(/\s+/g,' ').slice(0,100),
|
|
202
215
|
run:job=>{
|
|
@@ -205,7 +218,8 @@ export async function installHost(ctx,config,api) {
|
|
|
205
218
|
job.updateProgress?.(snapshot.nodes.filter(n=>n.status==='done').length+'/'+snapshot.nodes.length+' · '+snapshot.status)
|
|
206
219
|
if (['completed','cancelled','blocked'].includes(snapshot.status)) {
|
|
207
220
|
off()
|
|
208
|
-
resolve({status:snapshot.status==='completed'?'completed':snapshot.status==='cancelled'?'killed':'failed',
|
|
221
|
+
resolve({status:snapshot.status==='completed'?'completed':snapshot.status==='cancelled'?'killed':'failed',
|
|
222
|
+
result:snapshot.status==='completed'?'协作已完成。':snapshot.status==='cancelled'?'协作已取消。':'请在右侧协作导图查看需要处理的步骤。'})
|
|
209
223
|
}
|
|
210
224
|
})
|
|
211
225
|
void launch()
|
|
@@ -218,6 +232,40 @@ export async function installHost(ctx,config,api) {
|
|
|
218
232
|
}
|
|
219
233
|
}
|
|
220
234
|
const create=(session,p,native)=>presets.run(()=>createRun(session,p,native))
|
|
235
|
+
function rollCall(session,pref,promptId,signal) {
|
|
236
|
+
let pending=pendingRollCalls.get(session)
|
|
237
|
+
if (!pending) { pending=new Map(); pendingRollCalls.set(session,pending) }
|
|
238
|
+
if (pending.has(promptId)) return pending.get(promptId)
|
|
239
|
+
const stored=Object.values(view.stateOf(session).runs).find(run=>run.sessionId===session.id && run.settings?.nativePromptId===promptId)
|
|
240
|
+
if (stored) return Promise.resolve(stored.runId)
|
|
241
|
+
const start=createRollCall(session,pref,promptId,signal).finally(()=>pending.delete(promptId))
|
|
242
|
+
pending.set(promptId,start)
|
|
243
|
+
return start
|
|
244
|
+
}
|
|
245
|
+
async function createRollCall(session,pref,promptId,signal) {
|
|
246
|
+
const {routes}=await catalog()
|
|
247
|
+
await profileQueue
|
|
248
|
+
signal?.throwIfAborted()
|
|
249
|
+
const {participants,replies,closing}=prepareRollCall(pref,routes)
|
|
250
|
+
const {settings}=readProfile()
|
|
251
|
+
const runId=randomUUID(), allowedRouteIds=participants.map(r=>r.id)
|
|
252
|
+
const nodes=participants.map((route,i)=>({id:'roll-call-'+(i+1),routeId:route.id,title:route.label || route.modelId || route.id,
|
|
253
|
+
deliverable:'点名回应 '+(i+1),acceptance:'从该型号的彩蛋选项中选一句。',final:true,optional:true}))
|
|
254
|
+
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},
|
|
256
|
+
...bind(session,runId)})
|
|
257
|
+
engines.set(runId,{session,engine}); active.set(session,runId)
|
|
258
|
+
nativeDeliveries.set(runId,0)
|
|
259
|
+
const abort=()=>{void engine.cancel().catch(()=>{})}
|
|
260
|
+
signal?.addEventListener('abort',abort,{once:true})
|
|
261
|
+
try {
|
|
262
|
+
await engine.publish({nodes,rationale:'每个勾选的型号独立回应本次点名。'})
|
|
263
|
+
return runId
|
|
264
|
+
} catch(error) {
|
|
265
|
+
nativeDeliveries.delete(runId)
|
|
266
|
+
throw error
|
|
267
|
+
} finally { signal?.removeEventListener('abort',abort) }
|
|
268
|
+
}
|
|
221
269
|
async function createRun(session,p,native) {
|
|
222
270
|
void author.launch().catch(()=>{})
|
|
223
271
|
const task = String(p.task || '').trim()
|
|
@@ -247,17 +295,17 @@ export async function installHost(ctx,config,api) {
|
|
|
247
295
|
const selectedMaterials=sources.slice()
|
|
248
296
|
if (native?.history) sources.push(native.history)
|
|
249
297
|
const runId = randomUUID()
|
|
250
|
-
const runSettings={...settings,...(missing.length && {unavailableRouteIds:missing}),reasoningLevels:Object.fromEntries(allowed.filter(route=>route.reasoningLevels?.includes(preference.reasoningLevels[route.id]))
|
|
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]))
|
|
251
299
|
.map(route=>[route.id,preference.reasoningLevels[route.id]])),
|
|
252
300
|
...(native?{nativePromptId:native.promptId}:{}),
|
|
253
301
|
...(native?.materialSelectionId?{nativeMaterialSelectionId:native.materialSelectionId}:{})}
|
|
254
302
|
const engine = new RunEngine({runId,sessionId:session.id,task,routes,settings:runSettings,sources,plannerAssignment,
|
|
255
|
-
allowedRouteIds:allowed.map(r=>r.id),mode:p.policy ?? settings.policy
|
|
303
|
+
allowedRouteIds:allowed.map(r=>r.id),mode:p.policy ?? settings.policy,...bind(session,runId)})
|
|
256
304
|
engines.set(runId,{session,engine});active.set(session,runId)
|
|
257
305
|
const planModel=plannerFor(ctx,{allowedTools,workMode:p.mode,history:native?.history,materials:selectedMaterials})
|
|
258
306
|
const planner=args=>presets.run(()=>planModel(args))
|
|
259
307
|
if (native) {
|
|
260
|
-
nativeDeliveries.
|
|
308
|
+
nativeDeliveries.set(runId,0)
|
|
261
309
|
void engine.plan(planner).catch(()=>updated())
|
|
262
310
|
} else startJob(session,engine,planner)
|
|
263
311
|
updated()
|
|
@@ -301,6 +349,7 @@ export async function installHost(ctx,config,api) {
|
|
|
301
349
|
const runId = p.runId || active.get(session) || Object.keys(view.stateOf(session).runs).at(-1)
|
|
302
350
|
const e = obtain(session,runId)
|
|
303
351
|
if (!e) throw Error('请先在当前会话创建协作运行。')
|
|
352
|
+
if (['assign','editPlan','revise'].includes(type) && view.stateOf(session).runs[runId]?.settings?.easterEgg) throw Error('点名回应由本次勾选的每个型号分别完成,无法改派。')
|
|
304
353
|
switch(type) {
|
|
305
354
|
case 'selectRun': return // Selection belongs to this view. The composer follows the current run.
|
|
306
355
|
case 'confirm': await e.confirm(p.planVersion,p.assignmentsHash);return
|
|
@@ -356,18 +405,19 @@ export async function installHost(ctx,config,api) {
|
|
|
356
405
|
return collaborate({options,session,room,pref,current,next})
|
|
357
406
|
})
|
|
358
407
|
async function* collaborate({options,session,room,pref,current,next}){
|
|
408
|
+
const egg=isRollCall(current)
|
|
359
409
|
// DSH already admitted the draft, attachment receipts and prior history. Preserve the host's multimodal path.
|
|
360
|
-
if (options.messages.some(m=>m.role==='user' && m.content.some(b=>b.type==='file' || b.type==='image')) ||
|
|
361
|
-
current.some(m=>m.content.some(b=>b.type!=='text'))) { yield* next();return }
|
|
410
|
+
if (!egg && (options.messages.some(m=>m.role==='user' && m.content.some(b=>b.type==='file' || b.type==='image')) ||
|
|
411
|
+
current.some(m=>m.content.some(b=>b.type!=='text')))) { yield* next();return }
|
|
362
412
|
const task=current.flatMap(m=>m.content.map(b=>b.text)).join('\n\n').trim()
|
|
363
413
|
if (!task || task.startsWith('/')) { yield* next();return }
|
|
364
414
|
const selected=pref.routeIds
|
|
365
415
|
const snapshotList=Object.values(room.runs).filter(r=>r.sessionId===session.id)
|
|
366
416
|
const promptId=current.map(m=>m.id).join(',')
|
|
367
417
|
let runId=snapshotList.find(r=>r.settings?.nativePromptId===promptId)?.runId, engine
|
|
368
|
-
let
|
|
369
|
-
const graphRead=new Promise(resolve=>{releaseGraph=resolve})
|
|
418
|
+
let blockStarted=false
|
|
370
419
|
try{
|
|
420
|
+
if (!runId && egg) runId=await rollCall(session,pref,promptId,options.signal)
|
|
371
421
|
if (!runId) {
|
|
372
422
|
const currentIds=new Set(current.map(m=>m.id))
|
|
373
423
|
const historyText=options.messages.filter(m=>!currentIds.has(m.id) && (m.role==='assistant'||m.role==='user'&&m.source?.kind==='user'))
|
|
@@ -381,23 +431,23 @@ export async function installHost(ctx,config,api) {
|
|
|
381
431
|
const provider=(await catalog()).routes.find(r=>r.providerId===options.provider && r.modelId===options.model && selected.includes(r.id))
|
|
382
432
|
const materialIds=pref.materialIds
|
|
383
433
|
const created=await create(session,{task,routeIds:selected,preferredPlannerId:provider?.id,materialIds},
|
|
384
|
-
{history,promptId,materialSelectionId:materialIds.length?room.materialSelection.id:null
|
|
385
|
-
beforeAutoStart:()=>graphRead})
|
|
434
|
+
{history,promptId,materialSelectionId:materialIds.length?room.materialSelection.id:null})
|
|
386
435
|
runId=created.runId
|
|
387
436
|
}
|
|
388
437
|
engine=obtain(session,runId)
|
|
438
|
+
nativeDeliveries.set(runId,(nativeDeliveries.get(runId) || 0)+1)
|
|
389
439
|
blockStarted=true
|
|
390
440
|
yield {type:'block-start',index:0,blockType:'text'}
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
graphDelivered=true
|
|
394
|
-
releaseGraph()
|
|
395
|
-
const done=settled(plan)?plan:await waitForRun(engine,settled,options.signal)
|
|
396
|
-
const outputs=delivered(done)
|
|
397
|
-
const body=done.status==='completed' ? outputs.map(a=>a.text+(a.unresolved.length?'\n未决项:'+a.unresolved.join('、'):'')).join('\n\n') :
|
|
441
|
+
const done=await waitForRun(engine,settled,options.signal)
|
|
442
|
+
const body=done.status==='completed' ? completedText(done) :
|
|
398
443
|
done.status==='cancelled'?'协作已取消。':'协作需要处理。'+(done.error || done.nodes.find(n=>n.reason)?.reason || '请打开任务图查看阻塞原因。')
|
|
399
|
-
|
|
400
|
-
|
|
444
|
+
// Limit individual transport frames while preserving one complete assistant message.
|
|
445
|
+
for (let offset=0;offset<body.length;) {
|
|
446
|
+
let end=Math.min(offset+16384,body.length)
|
|
447
|
+
if (end<body.length && body.charCodeAt(end-1)>=0xd800 && body.charCodeAt(end-1)<=0xdbff) end--
|
|
448
|
+
yield {type:'text-delta',index:0,text:body.slice(offset,end)}
|
|
449
|
+
offset=end
|
|
450
|
+
}
|
|
401
451
|
yield {type:'finish',reason:{kind:'stop'}}
|
|
402
452
|
}catch(error){
|
|
403
453
|
if (options.signal?.aborted) throw error
|
|
@@ -405,9 +455,12 @@ export async function installHost(ctx,config,api) {
|
|
|
405
455
|
yield {type:'text-delta',index:0,text:'协作未完成:'+error.message}
|
|
406
456
|
yield {type:'finish',reason:{kind:'stop'}}
|
|
407
457
|
}finally{
|
|
408
|
-
if(engine && (!
|
|
409
|
-
|
|
410
|
-
|
|
458
|
+
if(engine && (!engine.snapshot().planVersion || options.signal?.aborted) && !settled(engine.snapshot()))await engine.cancel().catch(()=>{})
|
|
459
|
+
if (engine) {
|
|
460
|
+
const remaining=(nativeDeliveries.get(runId) || 1)-1
|
|
461
|
+
if (remaining) nativeDeliveries.set(runId,remaining)
|
|
462
|
+
else nativeDeliveries.delete(runId)
|
|
463
|
+
}
|
|
411
464
|
}
|
|
412
465
|
}
|
|
413
466
|
ctx.commands.register({definitionId:name,name:'collab',description:'在当前会话规划并执行多模型协作任务',input:{hint:'<任务>'},
|
|
@@ -420,8 +473,8 @@ export async function installHost(ctx,config,api) {
|
|
|
420
473
|
const pref=composerSettings(room,inv.agent.session.id)
|
|
421
474
|
const allowed=pref.routeIds.length?pref.routeIds:planner?[planner.id]:[]
|
|
422
475
|
if (!allowed.length) throw Error('请先在会话中选择参与模型。')
|
|
423
|
-
|
|
424
|
-
return {kind:'success',text:'
|
|
476
|
+
await create(inv.agent.session,{task:inv.rawInput,routeIds:allowed,preferredPlannerId:planner?.id})
|
|
477
|
+
return {kind:'success',text:'协作已开始,可在右侧协作导图查看进度。'}
|
|
425
478
|
} catch(error) {return {kind:'error',text:error.message}}
|
|
426
479
|
}})
|
|
427
480
|
ctx.on('session/disposed',session=>{
|
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
|
|
124
|
-
const ceiling = args.reserveTokens ? await args.reserveTokens(inputEstimate,
|
|
125
|
-
const maxTokens = Math.floor(Math.min(
|
|
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
|
|
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
|
|
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
|
|
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
|
}
|
package/host/plan-view.mjs
CHANGED
|
@@ -1,20 +1,3 @@
|
|
|
1
|
-
function inline(value) {
|
|
2
|
-
return String(value ?? '').replace(/[\r\n\t]+/g,' ').replace(/([\\`*_\[\]<>])/g,'\\$1')
|
|
3
|
-
}
|
|
4
|
-
export function formatConversationPlan(run) {
|
|
5
|
-
const labels=new Map(run.routes.map(r=>[r.id,inline(r.label || r.modelId || r.id)]))
|
|
6
|
-
const indices=new Map(run.nodes.map((node,i)=>[node.id,i+1]))
|
|
7
|
-
const rows=run.nodes.slice(0,16).map(node=>{
|
|
8
|
-
const predecessors=node.deps.length?node.deps.map(id=>'第 '+indices.get(id)+' 步').join('、'):'统筹计划'
|
|
9
|
-
return indices.get(node.id)+'. **'+inline(node.title)+'** · '+(labels.get(node.routeId) || inline(node.routeId))+' · 承接'+predecessors
|
|
10
|
-
})
|
|
11
|
-
if (run.nodes.length>rows.length) rows.push('其余 '+(run.nodes.length-rows.length)+' 步见右栏完整任务图。')
|
|
12
|
-
return '**协作分工图 · 版本 '+run.planVersion+'**\n\n统筹模型 '+(labels.get(run.plannerRouteId) || inline(run.plannerRouteId))+
|
|
13
|
-
' 已发布计划。开工方式为'+(run.mode==='manual'?'确认后执行。':'直接执行。')+
|
|
14
|
-
(run.settings?.unavailableRouteIds?.length?'\n本次跳过暂不可用的已选型号:'+run.settings.unavailableRouteIds.map(inline).join('、')+'。':'')+
|
|
15
|
-
'\n\n'+rows.join('\n')+'\n\n'
|
|
16
|
-
}
|
|
17
|
-
|
|
18
1
|
export function isNewVisiblePlan(run,mountedAt,currentSessionId,sessionId,lastShown) {
|
|
19
2
|
return !!(run && run.native && run.planVersion>0 && run.runId!==lastShown && currentSessionId===sessionId &&
|
|
20
3
|
Number.isFinite(Date.parse(run.createdAt)) && Date.parse(run.createdAt)>=mountedAt)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import {allocateEggReplies, chooseNovaClosing, formatEggMessage, formatEggReply} from '../src/easter-egg.mjs'
|
|
2
|
+
import {PRESENCE_TRIGGER} from './exact-composer-text.mjs'
|
|
3
|
+
import {streamText} from './models.mjs'
|
|
4
|
+
|
|
5
|
+
export function isRollCall(current) {
|
|
6
|
+
if (current.length !== 1) return false
|
|
7
|
+
const message = current[0]
|
|
8
|
+
return message.source?.kind === 'user' && message.content?.length === 1 &&
|
|
9
|
+
message.content[0].type === 'text' && message.content[0].text === PRESENCE_TRIGGER
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function unavailableRoute(id) {
|
|
13
|
+
const split = id.indexOf('/')
|
|
14
|
+
if (split !== -1) {
|
|
15
|
+
try {
|
|
16
|
+
return {id, providerId:decodeURIComponent(id.slice(0, split)), modelId:decodeURIComponent(id.slice(split + 1)),
|
|
17
|
+
enabled:false, capabilities:[]}
|
|
18
|
+
} catch { /* A previously stored route may use a different key format. */ }
|
|
19
|
+
}
|
|
20
|
+
return {id, modelId:id, enabled:false, capabilities:[]}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function prepareRollCall(pref, routes) {
|
|
24
|
+
const directory = new Map(routes.map(route => [route.id, route]))
|
|
25
|
+
const participants = [...new Set(pref.routeIds)].map(id => directory.get(id) || unavailableRoute(id))
|
|
26
|
+
// Deal to reachable text models first so an old checkbox cannot use up a category.
|
|
27
|
+
const available = [], unavailable = []
|
|
28
|
+
for (const route of participants) {
|
|
29
|
+
if (route.enabled !== false && (route.capabilities ?? ['text']).includes('text')) available.push(route)
|
|
30
|
+
else unavailable.push(route)
|
|
31
|
+
}
|
|
32
|
+
const assigned = new Map(allocateEggReplies([...available, ...unavailable]).map(reply => [reply.routeId, reply]))
|
|
33
|
+
const replies = participants.map(route => assigned.get(route.id))
|
|
34
|
+
return {participants, replies, closing:chooseNovaClosing()}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function unpackAnswer(value) {
|
|
38
|
+
// Some adapters include reasoning in the visible text even when asked for a single option.
|
|
39
|
+
let answer = value.replace(/^\s*(?:<think>[\s\S]*?<\/think>\s*)+/i, '').trim()
|
|
40
|
+
const fence = answer.match(/^```(?:json|text)?\s*\n([\s\S]*?)\n?```$/i)
|
|
41
|
+
if (fence) answer = fence[1].trim()
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(answer)
|
|
44
|
+
if (typeof parsed === 'string' || typeof parsed === 'number') return String(parsed)
|
|
45
|
+
if (parsed && typeof parsed === 'object' && Object.keys(parsed).length === 1 &&
|
|
46
|
+
['string','number'].includes(typeof parsed.choice)) return String(parsed.choice)
|
|
47
|
+
} catch { /* Plain text and unquoted workbook phrases are normal responses. */ }
|
|
48
|
+
return answer
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function unwrap(value) {
|
|
52
|
+
for (const [left, right] of [['"', '"'], ["'", "'"], ['“', '”'], ['「', '」'], ['**', '**'], ['`', '`']]) {
|
|
53
|
+
if (value.startsWith(left) && value.endsWith(right) && value.length >= left.length + right.length) {
|
|
54
|
+
return value.slice(left.length, -right.length).trim()
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return value
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function selectedPhrase(text, choices) {
|
|
61
|
+
const plain = unwrap(unpackAnswer(text))
|
|
62
|
+
const answer = unwrap(plain.replace(/^(?:我(?:选择|选)|选项|编号|(?:I choose|option|choice)\b)\s*[::]?\s*/i, '').trim())
|
|
63
|
+
if (choices.includes(answer)) return answer
|
|
64
|
+
const selection = answer.match(/^([1-91-9][0-90-9]*)(?:\s*([.)::、.)\-])\s*(.*))?$/u)
|
|
65
|
+
if (!selection) return
|
|
66
|
+
const chosen = choices[Number(selection[1].normalize('NFKC')) - 1]
|
|
67
|
+
if (!selection[3] || unwrap(selection[3]) === chosen) return chosen
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function executeRollCall(ctx, args) {
|
|
71
|
+
const reply = args.settings.easterEgg.replies.find(item => item.routeId === args.route.id)
|
|
72
|
+
if (!reply || args.route.id !== args.node.routeId) throw Object.assign(Error('未找到该型号的彩蛋候选。'), {dispatched:false})
|
|
73
|
+
const messages = [
|
|
74
|
+
{role:'system', content:'NOVA 彩蛋点名。用户问“在嘛?”。请从用户消息的 JSON 数组中任选一句作答。只返回从 1 开始的选项编号,或逐字返回所选原句。'},
|
|
75
|
+
{role:'user', content:JSON.stringify(reply.choices)},
|
|
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
|
+
}
|
|
99
|
+
const chosen = selectedPhrase(result.text, reply.choices)
|
|
100
|
+
if (chosen === undefined) throw Object.assign(Error('该型号未返回有效的彩蛋选项。'), {usage:result.usage})
|
|
101
|
+
return {...result, text:chosen}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function renderRollCall(snapshot) {
|
|
105
|
+
const {replies, closing} = snapshot.settings.easterEgg
|
|
106
|
+
const directory = new Map(snapshot.routes.map(route => [route.id, route]))
|
|
107
|
+
const nodes = new Map(snapshot.nodes.map(node => [node.routeId, node]))
|
|
108
|
+
const artifacts = new Map(snapshot.artifacts.map(artifact => [artifact.id, artifact]))
|
|
109
|
+
const lines = replies.map(({routeId, choices}) => {
|
|
110
|
+
const route = directory.get(routeId) || unavailableRoute(routeId)
|
|
111
|
+
const node = nodes.get(routeId)
|
|
112
|
+
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)
|
|
116
|
+
})
|
|
117
|
+
return formatEggMessage(lines, closing)
|
|
118
|
+
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-nova-lewis",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"lewisEnchantRelease": {
|
|
5
|
-
"version": "0.2.
|
|
6
|
-
"notes": "
|
|
5
|
+
"version": "0.2.3",
|
|
6
|
+
"notes": ""
|
|
7
7
|
},
|
|
8
8
|
"lewisEnchantReleaseEn": {
|
|
9
|
-
"version": "0.2.
|
|
10
|
-
"notes": "
|
|
9
|
+
"version": "0.2.3",
|
|
10
|
+
"notes": ""
|
|
11
11
|
},
|
|
12
12
|
"type": "module",
|
|
13
13
|
"publishConfig": {
|
package/src/context.mjs
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
const encoder = new TextEncoder()
|
|
2
2
|
export const defaultSettings = Object.freeze({
|
|
3
|
-
policy: 'manual', concurrency: 2, perApiConcurrency: 2, maxRequests:
|
|
4
|
-
maxTokens:
|
|
3
|
+
policy: 'manual', concurrency: 2, perApiConcurrency: 2, maxRequests: null,
|
|
4
|
+
maxTokens: null, warnAt: 0.75, compressAt: 0.9, targetAt: 0.7
|
|
5
5
|
})
|
|
6
|
+
const legacyDefaults = {...defaultSettings, maxRequests:60, maxTokens:160000}
|
|
6
7
|
|
|
7
8
|
export function validateSettings(settings) {
|
|
8
9
|
const result = {...defaultSettings}
|
|
9
10
|
for (const key of Object.keys(result)) if (Object.hasOwn(settings, key)) result[key] = settings[key]
|
|
10
11
|
if (!['manual', 'auto'].includes(result.policy)) throw new Error('请选择开工方式。')
|
|
11
12
|
for (const key of ['concurrency', 'perApiConcurrency', 'maxRequests', 'maxTokens']) {
|
|
13
|
+
if ((key === 'maxRequests' || key === 'maxTokens') && result[key] === null) continue
|
|
12
14
|
if (!Number.isSafeInteger(result[key]) || result[key] < 1) throw new Error('并发与预算必须为正整数。')
|
|
13
15
|
}
|
|
14
16
|
if (!(0 < result.targetAt && result.targetAt <= result.warnAt && result.warnAt < result.compressAt && result.compressAt <= 1)) throw new Error('压缩目标、提醒阈值和触发阈值须按从小到大设置。')
|
|
@@ -20,7 +22,7 @@ export function settingsProfile(profile = {}) {
|
|
|
20
22
|
if (!overrides) {
|
|
21
23
|
const previous=profile.settings || {}
|
|
22
24
|
overrides=Object.fromEntries(Object.keys(defaultSettings).filter(key=>Object.hasOwn(previous,key) &&
|
|
23
|
-
(key==='policy' || previous[key]!==
|
|
25
|
+
(key==='policy' || previous[key]!==legacyDefaults[key])).map(key=>[key,previous[key]]))
|
|
24
26
|
}
|
|
25
27
|
return patchSettings({policy:'manual'},overrides)
|
|
26
28
|
}
|
|
@@ -57,6 +59,16 @@ const ref = item => (item.id ?? item.nodeId) + '@v' + (item.version ?? 1)
|
|
|
57
59
|
const critical = /[\d%%¥¥$€]|不得|除外|除非|未|禁止|不|无需|例外|必须|仅限|except|unless|\b(?:no|not|never|must|error|failed)\b/i
|
|
58
60
|
const beforeDispatch = message => Object.assign(new Error(message), {dispatched:false})
|
|
59
61
|
|
|
62
|
+
// Input compression reserves a minimum space for generation. Once the input is
|
|
63
|
+
// packed, each model can use its own output allowance and the rest of its window.
|
|
64
|
+
export function outputLimits(route, input, requested, margin) {
|
|
65
|
+
const window = knownPositiveMin(route.window, route.contextWindow, route.deploymentWindow)
|
|
66
|
+
const declared = knownPositiveMin(requested, route.maxOutput, route.outputLimit)
|
|
67
|
+
const room = window == null ? Infinity : window - input - (margin ?? Math.ceil(window * 0.032))
|
|
68
|
+
if (room < 1) throw beforeDispatch('上下文超限:当前请求没有可用于输出的窗口。')
|
|
69
|
+
return {declared, available:Math.min(room, declared ?? Infinity)}
|
|
70
|
+
}
|
|
71
|
+
|
|
60
72
|
export function assembleContext({task, node, route, inputs = [], materials = [], settings = {}, system, tools = []}) {
|
|
61
73
|
const s = {...defaultSettings, ...settings}
|
|
62
74
|
const window = knownPositiveMin(route.window, route.contextWindow, route.deploymentWindow)
|