dsh-nova-lewis 0.2.0 → 0.2.2

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/host/index.mjs CHANGED
@@ -11,7 +11,7 @@ import { discoverRoutes, executorFor, plannerFor } from './models.mjs'
11
11
  import {choosePlanner} from '../src/role-routing.mjs'
12
12
  import { createChildren } from './children.mjs'
13
13
  import {sessionSelection} from './selection.mjs'
14
- import {formatConversationPlan} from './plan-view.mjs'
14
+ import {isRollCall,prepareRollCall,executeRollCall,renderRollCall} from './roll-call.mjs'
15
15
 
16
16
  export const name = 'dsh-nova-lewis'
17
17
  export const inject = ['commands','llm','agents','sessions','sessionProjections','connection','storageDomain','webServer']
@@ -63,9 +63,14 @@ function delta(previous, snapshot) {
63
63
  return {runId:snapshot.runId,fields,rows,order}
64
64
  }
65
65
  function delivered(snapshot) {
66
- const outputs = snapshot.nodes.filter(n=>n.artifactId && !snapshot.nodes.some(next=>next.deps.includes(n.id)))
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)))
67
68
  return outputs.map(n=>snapshot.artifacts.find(a=>a.id===n.artifactId)).filter(Boolean)
68
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))
69
74
  const settled = run=>['completed','cancelled','blocked'].includes(run.status)
70
75
  function waitForRun(engine,ready,signal) {
71
76
  return new Promise((resolve,reject)=>{
@@ -99,11 +104,12 @@ export async function installHost(ctx,config,api) {
99
104
  ctx.effect(()=>()=>author.dispose(),'collaboration author settings')
100
105
  const spawn = createChildren(ctx,config), execute = executorFor(ctx,spawn)
101
106
  const engines = new Map(), active = new WeakMap(), observers = new Map()
102
- const nativeDeliveries = new Set()
107
+ const nativeDeliveries = new Map()
108
+ const pendingRollCalls = new WeakMap()
103
109
  const composerSettings=(room,sessionId)=>{
104
110
  const saved=room.composer?.sessionId===sessionId && room.composer
105
111
  const materialIds=room.materialSelection?.sessionId===sessionId ? room.materialSelection.ids : []
106
- return {enabled:saved?.enabled===true,routeIds:saved?.routeIds || [],policy:readProfile().settings.policy,materialIds}
112
+ return {enabled:saved?.enabled===true,routeIds:saved?.routeIds || [],reasoningLevels:saved?.reasoningLevels || {},policy:readProfile().settings.policy,materialIds}
107
113
  }
108
114
  let epoch = 0, catalogPromise
109
115
  function updated() { epoch++; for (const wake of [...observers.values()]) wake() }
@@ -131,16 +137,14 @@ export async function installHost(ctx,config,api) {
131
137
  ctx.on('llm/adapters-updated',refresh)
132
138
  function bind(session,runId) {
133
139
  let last = view.stateOf(session).runs[runId]
134
- return {execute,persist:async (snapshot,event)=>{
140
+ return {execute:args=>args.settings?.easterEgg ? executeRollCall(ctx,args) : execute(args),persist:async (snapshot,event)=>{
135
141
  const data = clean(snapshot)
136
142
  api.appendPluginRecord(session,RECORD,delta(last,data))
137
143
  if (data.status==='completed' && last?.status!=='completed' && !nativeDeliveries.has(runId)) {
138
144
  const outputs = delivered(data)
139
- const text = ['协作交付 · '+data.task,'运行 '+runId,...outputs.map(a=>a.title+'\n'+a.text+
140
- (a.unresolved.length ? '\n未决项:'+a.unresolved.join(';') : '')),
141
- '步骤索引\n'+data.nodes.map((n,i)=>'第 '+(i+1)+' 步 '+n.title+' ['+n.id+']\n'+(data.artifacts.find(a=>a.id===n.artifactId)?.summary || n.status)).join('\n')
142
- ].join('\n\n')
143
- const final = outputs.at(-1), route = data.attempts.find(a=>a.id===final?.attemptId)?.route
145
+ const text = completedText(data)
146
+ const final = outputs.at(-1), route = [...(data.operations || []),...data.attempts].find(a=>a.id===final?.attemptId)?.route ||
147
+ data.routes.find(r=>r.id===(final?.routeId || data.plannerRouteId))
144
148
  if (route) session.append('assistant/message',{turn:0,step:0,stream:[],message:{
145
149
  role:'assistant',id:randomUUID(),content:[{type:'text',text}],source:{kind:'model',provider:route.providerId,model:route.modelId}
146
150
  }},{surfaceOp:'append'})
@@ -170,12 +174,13 @@ export async function installHost(ctx,config,api) {
170
174
  if (compact) {
171
175
  const snapshot=room.runs[selectedId]
172
176
  const run=snapshot && snapshot.sessionId===sessionId?{runId:snapshot.runId,status:snapshot.status,planVersion:snapshot.planVersion,
173
- createdAt:snapshot.createdAt,native:!!snapshot.settings?.nativePromptId,
177
+ createdAt:snapshot.createdAt,native:!!snapshot.settings?.nativePromptId && !snapshot.settings.easterEgg,
174
178
  assignmentsHash:snapshot.assignmentsHash,total:snapshot.nodes.length,done:snapshot.nodes.filter(n=>n.status==='done').length}:null
175
179
  const {routes,connections,warnings}=await catalog()
176
180
  return {mode:'host',sessionId,composer:composerSettings(room,sessionId),run,revision:epoch,
177
181
  materials:room.materials.map(({id,title,localOnly})=>({id,title,localOnly})),
178
- connections,warnings,routes:routes.map(({id,label,modelId,apiLabel,providerId})=>({id,label,modelId,apiLabel,providerId}))}
182
+ connections,warnings,routes:routes.map(({id,label,modelId,apiLabel,providerId,reasoningLevels})=>
183
+ ({id,label,modelId,apiLabel,providerId,...(reasoningLevels && {reasoningLevels})}))}
179
184
  }
180
185
  const run = session && selectedId ? obtain(session,selectedId)?.snapshot() : null
181
186
  const {routes,connections,warnings} = await catalog()
@@ -195,7 +200,7 @@ export async function installHost(ctx,config,api) {
195
200
  const launch = ()=>engine.plan(planner).catch(()=>updated())
196
201
  const jobs=ctx.get ? ctx.get('jobs') : ctx.jobs
197
202
  if (!jobs) { void launch(); return }
198
- const {runId,task} = engine.snapshot()
203
+ const {task} = engine.snapshot()
199
204
  try {
200
205
  jobs.start({owner:session.id,kind:'collab',label:task.replace(/\s+/g,' ').slice(0,100),
201
206
  run:job=>{
@@ -204,7 +209,8 @@ export async function installHost(ctx,config,api) {
204
209
  job.updateProgress?.(snapshot.nodes.filter(n=>n.status==='done').length+'/'+snapshot.nodes.length+' · '+snapshot.status)
205
210
  if (['completed','cancelled','blocked'].includes(snapshot.status)) {
206
211
  off()
207
- resolve({status:snapshot.status==='completed'?'completed':snapshot.status==='cancelled'?'killed':'failed',result:'协作运行 '+runId+' · '+snapshot.status})
212
+ resolve({status:snapshot.status==='completed'?'completed':snapshot.status==='cancelled'?'killed':'failed',
213
+ result:snapshot.status==='completed'?'协作已完成。':snapshot.status==='cancelled'?'协作已取消。':'请在右侧协作导图查看需要处理的步骤。'})
208
214
  }
209
215
  })
210
216
  void launch()
@@ -217,6 +223,41 @@ export async function installHost(ctx,config,api) {
217
223
  }
218
224
  }
219
225
  const create=(session,p,native)=>presets.run(()=>createRun(session,p,native))
226
+ function rollCall(session,pref,promptId,signal) {
227
+ let pending=pendingRollCalls.get(session)
228
+ if (!pending) { pending=new Map(); pendingRollCalls.set(session,pending) }
229
+ if (pending.has(promptId)) return pending.get(promptId)
230
+ const stored=Object.values(view.stateOf(session).runs).find(run=>run.sessionId===session.id && run.settings?.nativePromptId===promptId)
231
+ if (stored) return Promise.resolve(stored.runId)
232
+ const start=createRollCall(session,pref,promptId,signal).finally(()=>pending.delete(promptId))
233
+ pending.set(promptId,start)
234
+ return start
235
+ }
236
+ async function createRollCall(session,pref,promptId,signal) {
237
+ const {routes}=await catalog()
238
+ await profileQueue
239
+ signal?.throwIfAborted()
240
+ const {participants,replies,closing}=prepareRollCall(pref,routes)
241
+ const {settings,settingsOverrides}=readProfile()
242
+ const runId=randomUUID(), allowedRouteIds=participants.map(r=>r.id)
243
+ 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}))
245
+ 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},
248
+ ...bind(session,runId)})
249
+ engines.set(runId,{session,engine}); active.set(session,runId)
250
+ nativeDeliveries.set(runId,0)
251
+ const abort=()=>{void engine.cancel().catch(()=>{})}
252
+ signal?.addEventListener('abort',abort,{once:true})
253
+ try {
254
+ await engine.publish({nodes,rationale:'每个勾选的型号独立回应本次点名。'})
255
+ return runId
256
+ } catch(error) {
257
+ nativeDeliveries.delete(runId)
258
+ throw error
259
+ } finally { signal?.removeEventListener('abort',abort) }
260
+ }
220
261
  async function createRun(session,p,native) {
221
262
  void author.launch().catch(()=>{})
222
263
  const task = String(p.task || '').trim()
@@ -224,10 +265,15 @@ export async function installHost(ctx,config,api) {
224
265
  const {routes} = await catalog()
225
266
  await profileQueue
226
267
  const settings = readProfile().settings
227
- const remembered=composerSettings(view.stateOf(session),session.id).routeIds
268
+ const preference=composerSettings(view.stateOf(session),session.id)
269
+ const remembered=preference.routeIds
228
270
  const requested=p.routeIds ?? (remembered.length ? remembered : p.plannerRouteId?[p.plannerRouteId]:[])
229
271
  const allowed = routes.filter(r=>r.enabled!==false && requested.includes(r.id))
230
- if (requested.some(id=>!allowed.some(r=>r.id===id))) throw Error('本次选择含已失效的 DSH 型号,请先重新选择参与模型。')
272
+ const availableIds=new Set(allowed.map(route=>route.id))
273
+ const missing=requested.filter(id=>!availableIds.has(id))
274
+ if (missing.length && (!allowed.length || missing.some(id=>!remembered.includes(id)))) {
275
+ throw Error('所选 DSH 型号已失效,请刷新模型目录或重新选择参与模型。')
276
+ }
231
277
  if (!allowed.length) throw Error('没有可用路由。可打开离线示例,或在 DSH「设置 → 模型」添加 API。')
232
278
  const plannerAssignment=choosePlanner(allowed,task,{lockedId:p.plannerRouteId,preferredId:p.preferredPlannerId,history:native?.history})
233
279
  if (!plannerAssignment) throw Error('本次勾选的路由中没有可以读取所需前文的文本统筹模型。')
@@ -241,16 +287,17 @@ export async function installHost(ctx,config,api) {
241
287
  const selectedMaterials=sources.slice()
242
288
  if (native?.history) sources.push(native.history)
243
289
  const runId = randomUUID()
244
- const runSettings={...settings,
290
+ const runSettings={...settings,...(missing.length && {unavailableRouteIds:missing}),reasoningLevels:Object.fromEntries(allowed.filter(route=>route.reasoningLevels?.includes(preference.reasoningLevels[route.id]))
291
+ .map(route=>[route.id,preference.reasoningLevels[route.id]])),
245
292
  ...(native?{nativePromptId:native.promptId}:{}),
246
293
  ...(native?.materialSelectionId?{nativeMaterialSelectionId:native.materialSelectionId}:{})}
247
294
  const engine = new RunEngine({runId,sessionId:session.id,task,routes,settings:runSettings,sources,plannerAssignment,
248
- allowedRouteIds:allowed.map(r=>r.id),mode:p.policy ?? settings.policy,beforeAutoStart:native?.beforeAutoStart,...bind(session,runId)})
295
+ allowedRouteIds:allowed.map(r=>r.id),mode:p.policy ?? settings.policy,...bind(session,runId)})
249
296
  engines.set(runId,{session,engine});active.set(session,runId)
250
297
  const planModel=plannerFor(ctx,{allowedTools,workMode:p.mode,history:native?.history,materials:selectedMaterials})
251
298
  const planner=args=>presets.run(()=>planModel(args))
252
299
  if (native) {
253
- nativeDeliveries.add(runId)
300
+ nativeDeliveries.set(runId,0)
254
301
  void engine.plan(planner).catch(()=>updated())
255
302
  } else startJob(session,engine,planner)
256
303
  updated()
@@ -294,6 +341,7 @@ export async function installHost(ctx,config,api) {
294
341
  const runId = p.runId || active.get(session) || Object.keys(view.stateOf(session).runs).at(-1)
295
342
  const e = obtain(session,runId)
296
343
  if (!e) throw Error('请先在当前会话创建协作运行。')
344
+ if (['assign','editPlan','revise'].includes(type) && view.stateOf(session).runs[runId]?.settings?.easterEgg) throw Error('点名回应由本次勾选的每个型号分别完成,无法改派。')
297
345
  switch(type) {
298
346
  case 'selectRun': return // Selection belongs to this view. The composer follows the current run.
299
347
  case 'confirm': await e.confirm(p.planVersion,p.assignmentsHash);return
@@ -349,18 +397,19 @@ export async function installHost(ctx,config,api) {
349
397
  return collaborate({options,session,room,pref,current,next})
350
398
  })
351
399
  async function* collaborate({options,session,room,pref,current,next}){
400
+ const egg=isRollCall(current)
352
401
  // DSH already admitted the draft, attachment receipts and prior history. Preserve the host's multimodal path.
353
- if (options.messages.some(m=>m.role==='user' && m.content.some(b=>b.type==='file' || b.type==='image')) ||
354
- current.some(m=>m.content.some(b=>b.type!=='text'))) { yield* next();return }
402
+ if (!egg && (options.messages.some(m=>m.role==='user' && m.content.some(b=>b.type==='file' || b.type==='image')) ||
403
+ current.some(m=>m.content.some(b=>b.type!=='text')))) { yield* next();return }
355
404
  const task=current.flatMap(m=>m.content.map(b=>b.text)).join('\n\n').trim()
356
405
  if (!task || task.startsWith('/')) { yield* next();return }
357
406
  const selected=pref.routeIds
358
407
  const snapshotList=Object.values(room.runs).filter(r=>r.sessionId===session.id)
359
408
  const promptId=current.map(m=>m.id).join(',')
360
409
  let runId=snapshotList.find(r=>r.settings?.nativePromptId===promptId)?.runId, engine
361
- let releaseGraph,graphDelivered=false,blockStarted=false
362
- const graphRead=new Promise(resolve=>{releaseGraph=resolve})
410
+ let blockStarted=false
363
411
  try{
412
+ if (!runId && egg) runId=await rollCall(session,pref,promptId,options.signal)
364
413
  if (!runId) {
365
414
  const currentIds=new Set(current.map(m=>m.id))
366
415
  const historyText=options.messages.filter(m=>!currentIds.has(m.id) && (m.role==='assistant'||m.role==='user'&&m.source?.kind==='user'))
@@ -374,23 +423,17 @@ export async function installHost(ctx,config,api) {
374
423
  const provider=(await catalog()).routes.find(r=>r.providerId===options.provider && r.modelId===options.model && selected.includes(r.id))
375
424
  const materialIds=pref.materialIds
376
425
  const created=await create(session,{task,routeIds:selected,preferredPlannerId:provider?.id,materialIds},
377
- {history,promptId,materialSelectionId:materialIds.length?room.materialSelection.id:null,
378
- beforeAutoStart:()=>graphRead})
426
+ {history,promptId,materialSelectionId:materialIds.length?room.materialSelection.id:null})
379
427
  runId=created.runId
380
428
  }
381
429
  engine=obtain(session,runId)
430
+ nativeDeliveries.set(runId,(nativeDeliveries.get(runId) || 0)+1)
382
431
  blockStarted=true
383
432
  yield {type:'block-start',index:0,blockType:'text'}
384
- const plan=await waitForRun(engine,s=>s.planVersion>0 || settled(s),options.signal)
385
- if(plan.planVersion>0)yield {type:'text-delta',index:0,text:formatConversationPlan(plan)}
386
- graphDelivered=true
387
- releaseGraph()
388
- const done=settled(plan)?plan:await waitForRun(engine,settled,options.signal)
389
- const outputs=delivered(done)
390
- const body=done.status==='completed' ? outputs.map(a=>a.text+(a.unresolved.length?'\n未决项:'+a.unresolved.join('、'):'')).join('\n\n') :
433
+ const done=await waitForRun(engine,settled,options.signal)
434
+ const body=done.status==='completed' ? completedText(done) :
391
435
  done.status==='cancelled'?'协作已取消。':'协作需要处理。'+(done.error || done.nodes.find(n=>n.reason)?.reason || '请打开任务图查看阻塞原因。')
392
- const footer='\n\n协作运行 '+runId+(outputs.length?' · '+outputs.map(a=>done.routes.find(r=>r.id===a.routeId)?.label || a.routeId).join('、'):'')
393
- yield {type:'text-delta',index:0,text:(done.status==='completed'?'**执行结果**\n\n':'')+body+footer}
436
+ yield {type:'text-delta',index:0,text:body}
394
437
  yield {type:'finish',reason:{kind:'stop'}}
395
438
  }catch(error){
396
439
  if (options.signal?.aborted) throw error
@@ -398,9 +441,12 @@ export async function installHost(ctx,config,api) {
398
441
  yield {type:'text-delta',index:0,text:'协作未完成:'+error.message}
399
442
  yield {type:'finish',reason:{kind:'stop'}}
400
443
  }finally{
401
- if(engine && (!graphDelivered || options.signal?.aborted) && !settled(engine.snapshot()))await engine.cancel().catch(()=>{})
402
- releaseGraph()
403
- if(runId)nativeDeliveries.delete(runId)
444
+ if(engine && (!engine.snapshot().planVersion || options.signal?.aborted) && !settled(engine.snapshot()))await engine.cancel().catch(()=>{})
445
+ if (engine) {
446
+ const remaining=(nativeDeliveries.get(runId) || 1)-1
447
+ if (remaining) nativeDeliveries.set(runId,remaining)
448
+ else nativeDeliveries.delete(runId)
449
+ }
404
450
  }
405
451
  }
406
452
  ctx.commands.register({definitionId:name,name:'collab',description:'在当前会话规划并执行多模型协作任务',input:{hint:'<任务>'},
@@ -413,8 +459,8 @@ export async function installHost(ctx,config,api) {
413
459
  const pref=composerSettings(room,inv.agent.session.id)
414
460
  const allowed=pref.routeIds.length?pref.routeIds:planner?[planner.id]:[]
415
461
  if (!allowed.length) throw Error('请先在会话中选择参与模型。')
416
- const {runId}=await create(inv.agent.session,{task:inv.rawInput,routeIds:allowed,preferredPlannerId:planner?.id})
417
- return {kind:'success',text:'协作规划已开始。打开输入框的「协作」查看分工和用量。\n运行 '+runId}
462
+ await create(inv.agent.session,{task:inv.rawInput,routeIds:allowed,preferredPlannerId:planner?.id})
463
+ return {kind:'success',text:'协作已开始,可在右侧协作导图查看进度。'}
418
464
  } catch(error) {return {kind:'error',text:error.message}}
419
465
  }})
420
466
  ctx.on('session/disposed',session=>{
package/host/models.mjs CHANGED
@@ -3,34 +3,56 @@ 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'
5
5
  import {assignGeneratedPlan, planningCards} from '../src/role-routing.mjs'
6
+ import {reasoningOptions} from './selection.mjs'
7
+ import {isContextOverflow, packIndexedDirectory, profiledCatalog} from './planning-directory.mjs'
6
8
 
7
9
  export function routeKey(provider, model) {
8
10
  return encodeURIComponent(provider) + '/' + encodeURIComponent(model)
9
11
  }
10
12
 
13
+ const validId = id => typeof id === 'string' && id.trim().length > 0 && id.isWellFormed()
14
+ const displayName = row => typeof row.name === 'string' && row.name.trim() ? row.name : row.id
15
+ const positiveLimit = value => Number.isSafeInteger(value) && value > 0 ? value : null
16
+
17
+ function identifiedRows(rows) {
18
+ const seen = new Set()
19
+ return rows.filter(row => {
20
+ if (!validId(row?.id) || seen.has(row.id)) return false
21
+ seen.add(row.id)
22
+ return true
23
+ })
24
+ }
25
+
11
26
  function configuredConnections(ctx) {
12
27
  const directory=ctx.llm.listConfigurableProviders?.() || []
13
- if (!directory.length) return new Map()
14
- const settings=ctx.get ? ctx.get('settings') : ctx.settings
15
- if (directory.some(d=>d.settingsNs==='llm-pi-ai' && d.declared!==false) && typeof settings?.describe!=='function') throw Error('无法读取连接目录')
16
- // rc.5's pi-ai catalog applies the explicit profile baseURL to every materialized model.
17
- // A provider default alone can be overridden by individual catalog entries.
18
- const values=new Map((settings?.describe({redactSecrets:true}) || []).map(ns=>[ns.ns,ns.value]))
19
28
  const configured=new Map()
20
- for (const d of directory) {
21
- if (d.settingsNs!=='llm-pi-ai' || !Array.isArray(d.settingsPath) || d.settingsPath[0]!=='providers') continue
22
- const profile=d.settingsPath.reduce((value,key)=>value?.[key],values.get(d.settingsNs))
23
- if (!profile) {
24
- if (d.declared===true) throw Error('无法核对已配置的连接')
25
- continue
26
- }
27
- const models=(Array.isArray(profile.models)?profile.models:[]).filter(m=>typeof m?.id==='string').map(m=>({modelId:m.id,label:m.name || m.id}))
28
- const connection={models,local:false}
29
- configured.set(d.provider,connection)
29
+ const piProviders=directory.filter(d=>d?.settingsNs==='llm-pi-ai' && validId(d.provider))
30
+ if (!piProviders.length) return configured
31
+ let namespace
32
+ try {
33
+ const settings=ctx.get ? ctx.get('settings') : ctx.settings
34
+ namespace=settings?.describe({redactSecrets:true}).find(ns=>ns.ns==='llm-pi-ai')?.value
35
+ } catch { /* Only routes governed by these settings need to be withheld. */ }
36
+ for (const d of piProviders) {
30
37
  try {
31
- const url=new URL(profile.baseURL)
32
- connection.local=['https:','http:'].includes(url.protocol) && /^(?:127(?:\.\d{1,3}){3}|localhost|\[::1\])$/i.test(url.hostname)
33
- } catch { /* An opaque deployment remains unclassified. */ }
38
+ if (!namespace || !Array.isArray(d.settingsPath) || d.settingsPath[0]!=='providers') throw Error()
39
+ const profile=d.settingsPath.reduce((value,key)=>value?.[key],namespace)
40
+ if (profile==null && d.declared!==true) continue
41
+ if (!profile || typeof profile!=='object' || Array.isArray(profile)) throw Error()
42
+ if (profile.models!=null && !Array.isArray(profile.models)) throw Error()
43
+ const models=identifiedRows(profile.models || []).map(m=>({modelId:m.id,label:displayName(m)}))
44
+ if (profile.models?.length && !models.length) throw Error()
45
+ const connection={models,local:false}
46
+ configured.set(d.provider,connection)
47
+ // rc.5 applies an explicit pi-ai profile endpoint to every model on that route.
48
+ try {
49
+ const url=new URL(profile.baseURL)
50
+ connection.local=['https:','http:'].includes(url.protocol) && /^(?:127(?:\.\d{1,3}){3}|localhost|\[::1\])$/i.test(url.hostname)
51
+ } catch { /* An opaque deployment remains unclassified. */ }
52
+ } catch {
53
+ // A broken declared profile must not expose the adapter's unrestricted catalog.
54
+ configured.set(d.provider,{unavailable:true,models:[],local:false})
55
+ }
34
56
  }
35
57
  return configured
36
58
  }
@@ -41,36 +63,46 @@ export async function discoverRoutes(ctx) {
41
63
  try { configured=configuredConnections(ctx) }
42
64
  catch { return {routes:[],connections:[],warnings:[{message:'暂时无法核对 DSH 连接配置,请刷新模型目录。'}]} }
43
65
  let providers
44
- try { providers=ctx.llm.listProviders() } catch { return {routes:[],connections:[],warnings:[{message:'DSH 模型目录暂时不可用。'}]} }
66
+ try { providers=identifiedRows(ctx.llm.listProviders()) } catch { return {routes:[],connections:[],warnings:[{message:'DSH 模型目录暂时不可用。'}]} }
45
67
  const get = key => ctx.get ? ctx.get(key) : ctx[key]
46
68
  const catalogs = await Promise.all(providers.map(async provider => {
69
+ if (configured.get(provider.id)?.unavailable) {
70
+ warnings.push({provider:provider.id,message:'暂时无法核对该连接的 DSH 模型配置,请刷新模型目录。'})
71
+ return []
72
+ }
47
73
  let models
48
- try { models = await ctx.llm.listModels(provider.id) }
74
+ try { models = identifiedRows(await ctx.llm.listModels(provider.id)) }
49
75
  catch { warnings.push({provider: provider.id, message: '模型目录暂时不可用'}); return [] }
50
- const specified=configured.get(provider.id)?.models || []
51
- const permitted=specified.length ? models.filter(m=>specified.some(row=>row.modelId===m.id)) : models
76
+ const specified=new Set(configured.get(provider.id)?.models.map(row=>row.modelId))
77
+ const permitted=specified.size ? models.filter(m=>specified.has(m.id)) : models
52
78
  return Promise.all(permitted.map(async model => {
53
- let info = {}
54
- try { info = await ctx.llm.resolveModelInfo(provider.id, model.id) || {} } catch { /* Some catalogs supply only an ID. */ }
79
+ let info = {}, reasoningUnavailable = false
80
+ try { info = await ctx.llm.resolveModelInfo(provider.id, model.id) || {} } catch { reasoningUnavailable=true }
55
81
  const modalities = info.inputModalities ?? model.inputModalities
56
- const capabilities = [...(modalities || ['text'])]
82
+ const capabilities = modalities == null ? ['text'] :
83
+ Array.isArray(modalities) ? [...new Set(modalities.filter(value=>value==='text' || value==='image'))] : []
57
84
  if (get('subagents') && get('tools') && get('agentPresets') && capabilities.includes('text')) capabilities.push('tools')
58
- const window=info.context?.contextWindow ?? model.contextWindow ?? null
85
+ const window=positiveLimit(info.context?.contextWindow) ?? positiveLimit(model.contextWindow)
86
+ const efforts=info.reasoning?.efforts
87
+ const reasoningLevels=Array.isArray(efforts) ? identifiedRows(efforts).map(effort=>effort.id) : []
88
+ if (info.reasoning!=null && !reasoningLevels.length) reasoningUnavailable=true
59
89
  return {
60
- id: routeKey(provider.id, model.id), providerId: provider.id, apiId: provider.id, apiLabel: provider.name || provider.id,
61
- modelId: model.id, label: model.name || model.id, enabled: true, capabilities, capabilitySource: modalities ? 'catalog' : 'text-assumed',
90
+ id: routeKey(provider.id, model.id), providerId: provider.id, apiId: provider.id, apiLabel: displayName(provider),
91
+ modelId: model.id, label: displayName(model), enabled: true, capabilities, capabilitySource: modalities == null ? 'text-assumed' : 'catalog',
62
92
  contextWindow: window,window,
63
- maxOutput: info.defaultMaxTokens ?? model.maxTokens ?? null, local: configured.get(provider.id)?.local===true, upstream: null,
93
+ ...(reasoningLevels.length && {reasoningLevels}),
94
+ ...(reasoningUnavailable && {reasoningUnavailable:true}),
95
+ maxOutput: positiveLimit(info.defaultMaxTokens) ?? positiveLimit(model.maxTokens), local: configured.get(provider.id)?.local===true, upstream: null,
64
96
  }
65
97
  }))
66
98
  }))
67
99
  const routes=catalogs.flat()
68
- const providerNames=new Map(providers.map(p=>[p.id,p.name || p.id]))
100
+ const providerNames=new Map(providers.map(p=>[p.id,displayName(p)]))
69
101
  const connections=[]
70
102
  for (const providerId of new Set([...providerNames.keys(),...configured.keys()])) {
71
103
  const available=routes.filter(r=>r.providerId===providerId)
72
104
  const ids=new Set(available.map(r=>r.modelId))
73
- const models=available.map(r=>({id:r.id,modelId:r.modelId,label:r.label,available:true}))
105
+ const models=available.map(({id,modelId,label,reasoningLevels})=>({id,modelId,label,available:true,...(reasoningLevels && {reasoningLevels})}))
74
106
  for(const m of configured.get(providerId)?.models || []) if(!ids.has(m.modelId)) {
75
107
  models.push({id:routeKey(providerId,m.modelId),...m,available:false})
76
108
  }
@@ -88,13 +120,15 @@ export async function streamText(ctx, args, messages, desiredOutput) {
88
120
  role:'user', content:[{type:'text', text:m.content}]
89
121
  }))
90
122
  const inputEstimate = messages.reduce((s,m) => s + 4 + estimateInput(m.content), 2)
91
- const maxTokens = Math.floor(Math.min(desiredOutput || 3072, args.route.maxOutput || Infinity,
92
- args.maxAttemptTokens == null ? Infinity : args.maxAttemptTokens - inputEstimate))
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))
93
126
  if (maxTokens < 1) throw Object.assign(Error('该请求的输入估算已超出此次预算,请调整预算或缩短输入。'),{dispatched:false})
94
127
  const blocks = new Map()
95
128
  let usage = null, finish, observedOutput = false
96
129
  const chunks = ctx.llm.stream({provider:args.route.providerId, model:args.route.modelId, system,
97
- messages:user, maxTokens, signal:args.signal, sessionId:args.sessionId})
130
+ messages:user, maxTokens, signal:args.signal, sessionId:args.sessionId,
131
+ ...reasoningOptions(args)})
98
132
  for await (const chunk of chunks) {
99
133
  if (chunk.type === 'usage') {
100
134
  usage = receipt(chunk.usage)
@@ -106,6 +140,7 @@ export async function streamText(ctx, args, messages, desiredOutput) {
106
140
  }
107
141
  if (args.signal.aborted || finish?.kind !== 'stop') {
108
142
  const error = Error(args.signal.aborted ? '运行已取消' : finish?.failure?.message || '模型响应未完整结束(' + (finish?.kind || '连接中断') + ')')
143
+ if (!args.signal.aborted && finish?.kind === 'max-tokens') Object.assign(error,{finishKind:'max-tokens',maxTokens,inputEstimate})
109
144
  error.usage = usage
110
145
  error.retryAfterMs = finish?.failure?.providerRetryAfterMs
111
146
  throw error
@@ -151,32 +186,74 @@ function includeReviewSources(nodes) {
151
186
  export function plannerFor(ctx, options = {}) {
152
187
  return async args => {
153
188
  const catalog = planningCards(args.routes,args.task)
189
+ const windows=[args.route.window,args.route.contextWindow,args.route.deploymentWindow].filter(n=>n>0)
190
+ const window=Math.min(...windows)
191
+ const outputReserve=Math.max(1,Math.min(args.planningOutputTokens || 4096,Math.floor(window/2),
192
+ args.route.maxOutput || Infinity,args.route.outputLimit || Infinity))
154
193
  const instruction = [
155
194
  '你是 DSH 任务规划者。只输出 JSON 对象 {"rationale":"一句分工理由","nodes":[...]}。不要执行任务。',
156
195
  '每个节点包含 id,title,role,routeId,assignmentReason,difficulty,deps,sourceIds,requiredCapabilities,tools,deliverable,acceptance。由你为此步骤选择具体负责人,在 assignmentReason 中用一句话说明选择依据。使用目录中的实际路由 ID、唯一交付物、有效前置依赖。',
157
196
  '逐节点评定 difficulty。routine 是边界明确、可按固定规则验收的工作,standard 是常规专业工作,complex 是需要多步判断、权衡约束或处理依赖风险的工作。同一计划可包含不同难度。为执行节点给出具体的 instructions。',
158
197
  '在本次勾选的具体型号中,结合步骤本身、验收方式、实际能力与工具、型号卡的岗位依据和可选 workload 定位安排负责人。同一个 API 下的各型号各自独立,同一个型号也可承担多个步骤。资料未知的自定义型号仍可安排。不要按名称猜测能力、费用或速度,也不要为轮流使用型号而拆分任务。',
159
198
  '需要起草提示词再交给其他模型时,用 role=prompting 的节点独立交付提示词;在 promptFor 数组写接收节点 ID,接收步骤把它列入 deps。若用户只索要提示词,直接以提示词作为交付。普通问答无需增加起草轮次。',
160
- '根据本条任务、资料索引与本次参与型号,即席分析目标和依赖后设计分工。',
199
+ '根据本条任务、资料索引与本次参与型号,即席分析目标和依赖后设计分工。目录使用 profile 数字时,从 catalogProfiles 对应下标读取该型号的能力与工具。',
161
200
  '简单问答也由后续执行节点回答。统筹节点只画计划,不输出用户问题的答案。简单任务只用一个执行节点。多节点最后有 final 汇合所有必要成果;独立复核使用原文并声明 reviewOf。',
162
201
  '资料索引仅供分配,切勿编造资料。每组资料至少有一个执行步骤负责;其后依赖该步骤的路由也须在同组可读范围。仅使用授权工具。请以用户的语言作答。'
163
202
  ].join('\n')
164
- const request = JSON.stringify({task:args.task,workMode:options.workMode || 'recommended',catalog,
203
+ const request = {task:args.task,workMode:options.workMode || 'recommended',catalog,
165
204
  materials:args.sources,materialRouteGroups:(options.materials || []).map(source=>({
166
205
  ...(args.sources.some(s=>s.id===source.id)?{id:source.id}:{}),routeIds:args.routes.filter(r=>mayRead(source,r)).map(r=>r.id)
167
206
  })), allowedTools:options.allowedTools || [],
168
- ...(args.correction ? {validationError:args.correction} : {})})
207
+ ...(args.correction ? {validationError:args.correction} : {})}
208
+ // Keep all selected route IDs. In a small context, spend space on the task and source text
209
+ // before repeating full reference cards and documentation links for every deployment.
210
+ const totalBudget=args.planningTokenBudget ?? Infinity
211
+ const catalogBudget=Math.min(window,args.route.maxInput || Infinity,args.settings?.maxTokens || Infinity,totalBudget)/4
212
+ if (estimateInput(JSON.stringify(catalog))>catalogBudget) {
213
+ request.catalog=catalog.map(({id,label,modelId,capabilities,tools,workload,roles})=>({
214
+ id,...(label && label!==modelId && {label}),capabilities,...(tools && {tools}),
215
+ ...(workload && {workload}),...(roles && {roles})
216
+ }))
217
+ if (estimateInput(JSON.stringify(request.catalog))>catalogBudget) {
218
+ Object.assign(request,profiledCatalog(catalog))
219
+ }
220
+ }
169
221
  const history=options.history && args.sources.some(s=>s.id===options.history.id)?[options.history]:[]
170
- const packed=assembleContext({task:request,system:instruction,node:{...args.node,deliverable:'计划 JSON',sourceIds:history.map(s=>s.id)},
171
- route:args.route,materials:history,settings:{...args.settings,outputReserve:4096}})
222
+ const pack=(query,extraInstruction)=>assembleContext({task:JSON.stringify(query),system:extraInstruction?instruction+'\n'+extraInstruction:instruction,
223
+ node:{...args.node,deliverable:'计划 JSON',sourceIds:history.map(s=>s.id)},route:args.route,materials:history,settings:{...args.settings,outputReserve}})
224
+ function packIfFits(query) {
225
+ try { return pack(query) }
226
+ catch (error) { if (!isContextOverflow(error)) throw error }
227
+ }
228
+ const inputLimit=totalBudget-outputReserve
229
+ let packed=packIfFits(request), indexedIds
230
+ if ((!packed || packed.context.estimated>inputLimit) && !request.catalogProfiles) {
231
+ const profiled={...request,...profiledCatalog(catalog)}
232
+ const compact=packIfFits(profiled)
233
+ if (compact && (!packed || compact.context.estimated<packed.context.estimated)) packed=compact
234
+ }
235
+ if (!packed || packed.context.estimated>inputLimit) {
236
+ try {
237
+ const indexed=packIndexedDirectory(request,catalog,args.routes,pack,inputLimit)
238
+ if (!packed || indexed.packed.context.estimated<packed.context.estimated) {
239
+ packed=indexed.packed
240
+ indexedIds=indexed.routeIds
241
+ }
242
+ } catch (error) { if (!packed || !isContextOverflow(error)) throw error }
243
+ }
172
244
  await args.report({context:packed.context,phase:'waiting'})
173
- const result = await streamText(ctx,args,packed.messages,4096)
245
+ const result = await streamText(ctx,args,packed.messages,packed.context.outputReserve)
174
246
  let plan
175
247
  let invalid
176
248
  try { plan = JSON.parse(result.text.replace(/^\s*```(?:json)?\s*|\s*```\s*$/gi,'')) } catch {plan={};invalid='规划回执不是有效 JSON'}
177
249
  if (Array.isArray(plan?.nodes)) {
178
250
  const ids=new Set(catalog.map(r=>r.id))
179
251
  for (const n of plan.nodes) {
252
+ if (indexedIds && n && typeof n==='object') {
253
+ const resolve=id=>Number.isSafeInteger(id)?indexedIds[id-1]:id
254
+ n.routeId=resolve(n.routeId)
255
+ if (Array.isArray(n.fallbackRouteIds)) n.fallbackRouteIds=n.fallbackRouteIds.map(resolve)
256
+ }
180
257
  if (!n || !ids.has(n.routeId) || !Array.isArray(n.fallbackRouteIds ?? []) || (n.fallbackRouteIds || []).some(id=>!ids.has(id))) {
181
258
  invalid='节点或备选路由超出本次勾选范围';break
182
259
  }
@@ -1,18 +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'?'确认后执行。':'直接执行。')+'\n\n'+rows.join('\n')+'\n\n'
14
- }
15
-
16
1
  export function isNewVisiblePlan(run,mountedAt,currentSessionId,sessionId,lastShown) {
17
2
  return !!(run && run.native && run.planVersion>0 && run.runId!==lastShown && currentSessionId===sessionId &&
18
3
  Number.isFinite(Date.parse(run.createdAt)) && Date.parse(run.createdAt)>=mountedAt)
@@ -0,0 +1,84 @@
1
+ // Only used when even the list of exact route IDs cannot fit alongside this task and its history.
2
+ // Numbering is local to this planner call; only resolved, authorized route IDs reach a saved plan.
3
+ const instructions = '本次目录中每个已选型号有唯一整数编号,从 1 到 catalogIndex.count。routeId 和 fallbackRouteIds 可填写整数编号或完整路由 ID。catalog 中 ref 对应一个具体型号,first 至 last 是同类成员的连续编号范围。reads 是可读资料组在 materialRouteGroups 的下标(从 0 开始),其中 exampleRef 是有读取权限的示例成员。'
4
+
5
+ export function profiledCatalog(cards) {
6
+ const traits = new Map(), catalogProfiles = []
7
+ const catalog = cards.map(({id,capabilities,tools})=>{
8
+ const profile = {capabilities,...(tools && {tools})}
9
+ const key = JSON.stringify(profile)
10
+ if (!traits.has(key)) {
11
+ traits.set(key,catalogProfiles.length)
12
+ catalogProfiles.push(profile)
13
+ }
14
+ return {id,profile:traits.get(key)}
15
+ })
16
+ return {catalog,catalogProfiles}
17
+ }
18
+
19
+ export function packIndexedDirectory(request, cards, routes, pack, inputLimit) {
20
+ const access = request.materialRouteGroups.map(row=>new Set(row.routeIds))
21
+ const groups = new Map()
22
+ for (const [index, card] of cards.entries()) {
23
+ const reads = []
24
+ for (const [group, allowed] of access.entries()) if (allowed.has(card.id)) reads.push(group)
25
+ const traits = {
26
+ capabilities:card.capabilities, ...(card.tools && {tools:card.tools}), ...(routes[index].local && {local:true}),
27
+ ...(card.roles && {roles:card.roles}), ...(card.workload && {workload:card.workload}), ...(reads.length && {reads})
28
+ }
29
+ const key = JSON.stringify(traits)
30
+ if (!groups.has(key)) groups.set(key, {traits, members:[]})
31
+ groups.get(key).members.push(card)
32
+ }
33
+ const routeIds = []
34
+ const named = [], summaries = [], examples = new Map()
35
+ const task = request.task.toLowerCase()
36
+ const aliases = new Map()
37
+ for (const card of cards) {
38
+ for (const alias of new Set([card.modelId,card.label])) {
39
+ if (typeof alias==='string') aliases.set(alias,(aliases.get(alias) || 0)+1)
40
+ }
41
+ }
42
+ const materialRouteGroups = request.materialRouteGroups.map(row=>row.id ? {id:row.id} : {})
43
+ for (const {traits, members} of groups.values()) {
44
+ const first = routeIds.length + 1
45
+ for (const card of members) {
46
+ const ref = routeIds.push(card.id)
47
+ const names = [card.id,...[card.modelId,card.label].filter(name=>aliases.get(name)===1)]
48
+ const match = Math.max(0,...names.filter(name=>task.includes(name.toLowerCase())).map(name=>name.length))
49
+ if (match) named.push({match, entry:{ref,id:card.id,...(card.label && card.label!==card.modelId && {label:card.label})}})
50
+ if (ref===first || ref===cards.length) examples.set(ref,{ref,id:card.id})
51
+ }
52
+ summaries.push({first,last:routeIds.length,...traits})
53
+ for (const index of traits.reads || []) {
54
+ if (traits.capabilities.includes('text')) materialRouteGroups[index].exampleRef ??= first
55
+ }
56
+ }
57
+ named.sort((a,b)=>b.match-a.match)
58
+ const entries = [...named.map(({entry})=>entry),...summaries]
59
+ for (const {entry} of named) examples.delete(entry.ref)
60
+ entries.push(...examples.values())
61
+ const indexed = {...request, materialRouteGroups, catalogIndex:{count:routeIds.length}}
62
+ delete indexed.catalogProfiles
63
+ const attempt = count=>pack({...indexed,catalog:entries.slice(0,count)},instructions)
64
+ // Determine fit using the same output reserve, system text, actual history and margin as dispatch.
65
+ // If the bare task or protected source lines exceed the window, the original context error is required.
66
+ let low = 0, high = entries.length, packed = attempt(low)
67
+ while (low < high) {
68
+ const count = Math.ceil((low+high)/2)
69
+ try {
70
+ const candidate = attempt(count)
71
+ if (candidate.context.estimated > inputLimit) { high = count-1; continue }
72
+ low = count
73
+ packed = candidate
74
+ } catch (error) {
75
+ if (!isContextOverflow(error)) throw error
76
+ high = count-1
77
+ }
78
+ }
79
+ return {packed, routeIds}
80
+ }
81
+
82
+ export function isContextOverflow(error) {
83
+ return error?.code === 'CONTEXT_OVERFLOW'
84
+ }