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.
@@ -0,0 +1,78 @@
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
+ export async function executeRollCall(ctx, args) {
38
+ const reply = args.settings.easterEgg.replies.find(item => item.routeId === args.route.id)
39
+ if (!reply || args.route.id !== args.node.routeId) throw Object.assign(Error('未找到该型号的彩蛋候选。'), {dispatched:false})
40
+ const messages = [
41
+ {role:'system', content:'NOVA 彩蛋点名。用户问“在嘛?”。请从用户消息的 JSON 数组中任选一句作答。只返回从 1 开始的选项编号,或逐字返回所选原句。'},
42
+ {role:'user', content:JSON.stringify(reply.choices)},
43
+ ]
44
+ // A stalled provider must release its slot so the other selected models can answer.
45
+ const signal = AbortSignal.any([args.signal, AbortSignal.timeout(90_000)])
46
+ signal.throwIfAborted()
47
+ let onAbort
48
+ const aborted = new Promise((_, reject) => {
49
+ onAbort = () => reject(signal.reason)
50
+ signal.addEventListener('abort', onAbort, {once:true})
51
+ })
52
+ let result
53
+ try {
54
+ result = await Promise.race([streamText(ctx, {...args, signal}, messages, args.node.outputReserve), aborted])
55
+ } finally {
56
+ signal.removeEventListener('abort', onAbort)
57
+ }
58
+ const answer = result.text
59
+ const chosen = /^[1-9]\d*$/.test(answer) ? reply.choices[Number(answer) - 1] : reply.choices.find(text => text === answer)
60
+ if (chosen === undefined) throw Object.assign(Error('该型号未返回有效的彩蛋选项。'), {usage:result.usage})
61
+ return {...result, text:chosen}
62
+ }
63
+
64
+ export function renderRollCall(snapshot) {
65
+ const {replies, closing} = snapshot.settings.easterEgg
66
+ const directory = new Map(snapshot.routes.map(route => [route.id, route]))
67
+ const nodes = new Map(snapshot.nodes.map(node => [node.routeId, node]))
68
+ const artifacts = new Map(snapshot.artifacts.map(artifact => [artifact.id, artifact]))
69
+ const lines = replies.map(({routeId, choices}) => {
70
+ const route = directory.get(routeId) || unavailableRoute(routeId)
71
+ const node = nodes.get(routeId)
72
+ const artifact = artifacts.get(node?.artifactId)
73
+ const text = artifact?.routeId === routeId && choices.includes(artifact.text) ? artifact.text :
74
+ route.enabled === false ? '(型号当前不可用)' : '(本次未回应)'
75
+ return formatEggReply(route, text)
76
+ })
77
+ return formatEggMessage(lines, closing)
78
+ }
@@ -1,19 +1,42 @@
1
1
  export function toggleParticipant(preference,routeId,checked) {
2
2
  const routeIds=checked?[...new Set([...preference.routeIds,routeId])]:preference.routeIds.filter(id=>id!==routeId)
3
- return {routeIds,enabled:routeIds.length>0 && preference.enabled===true}
3
+ return {routeIds,enabled:routeIds.length>0 && preference.enabled===true,
4
+ ...(preference.reasoningLevels && {reasoningLevels:preference.reasoningLevels})}
4
5
  }
6
+
7
+ function reasoningSelection(patch, available, previous) {
8
+ const requested = patch.reasoningLevels === undefined ? previous?.reasoningLevels : patch.reasoningLevels
9
+ if (requested === undefined) return {}
10
+ if (requested === null || Array.isArray(requested) || typeof requested !== 'object') throw Error('推理等级设置无效。')
11
+ const routes = new Map(available.map(route => [route.id, route]))
12
+ const supported = []
13
+ for (const [id, level] of Object.entries(requested)) {
14
+ const route = routes.get(id)
15
+ const saved = typeof level === 'string' && previous?.reasoningLevels?.[id] === level
16
+ if (route?.reasoningLevels?.includes(level) || (saved && (!route || route.reasoningUnavailable))) supported.push([id, level])
17
+ else if (!saved) throw Error('所选推理等级不在该型号的 DSH 目录中,请刷新后重选。')
18
+ }
19
+ return {reasoningLevels:Object.fromEntries(supported)}
20
+ }
21
+
22
+ export function reasoningOptions({route, settings}) {
23
+ const level = settings?.reasoningLevels?.[route.id]
24
+ return route.reasoningLevels?.includes(level) ? {reasoningEffort:level} : {}
25
+ }
26
+
5
27
  export function sessionSelection(patch,available,previous) {
6
28
  const requested=[...new Set(patch.routeIds)], availableIds=available.map(route=>route.id)
29
+ const reasoning = reasoningSelection(patch, available, previous)
7
30
  let routeIds=requested
8
31
  if (patch.enabled) {
9
32
  routeIds=requested.filter(id=>availableIds.includes(id))
10
33
  if (requested.length!==routeIds.length) {
11
34
  const stale=requested.filter(id=>!availableIds.includes(id))
12
- if (!previous?.enabled || stale.some(id=>!previous.routeIds.includes(id))) throw Error('所选型号已从 DSH 可用目录移除,请重新选择参与模型。')
13
- return {routeIds:requested,enabled:true}
35
+ if (stale.some(id=>!previous?.routeIds?.includes(id))) throw Error('所选型号已从 DSH 可用目录移除,请重新选择参与模型。')
36
+ return {routeIds:requested,enabled:true,...reasoning}
14
37
  }
15
38
  if (!requested.length) routeIds=availableIds.slice(0,2)
16
39
  if (!routeIds.length) throw Error('当前没有可用模型,请先在 DSH 设置中配置模型。')
17
40
  }
18
- return {routeIds,enabled:patch.enabled===true}
41
+ return {routeIds,enabled:patch.enabled===true,...reasoning}
19
42
  }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "dsh-nova-lewis",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "lewisEnchantRelease": {
5
- "version": "0.2.0",
6
- "notes": "统筹模型根据当前问题和你勾选的型号安排分工。在「模型预设」里可以单独更新型号的分工参考资料。"
5
+ "version": "0.2.2",
6
+ "notes": ""
7
7
  },
8
8
  "lewisEnchantReleaseEn": {
9
- "version": "0.2.0",
10
- "notes": "The coordinator assigns work for each question to the models you select. Update the model reference cards separately in Model Presets."
9
+ "version": "0.2.2",
10
+ "notes": ""
11
11
  },
12
12
  "type": "module",
13
13
  "publishConfig": {
package/src/context.mjs CHANGED
@@ -127,7 +127,11 @@ export function assembleContext({task, node, route, inputs = [], materials = [],
127
127
  }
128
128
  }
129
129
  const estimated = countInput()
130
- if (budget !== null && estimated > budget) throw beforeDispatch('上下文超限:保留硬约束、数字和例外条款后约 ' + estimated + ' Token,输入预算 ' + budget + '。请按原文位置拆分资料或改派到更大窗口。')
130
+ if (budget !== null && estimated > budget) {
131
+ const error=beforeDispatch('上下文超限:保留硬约束、数字和例外条款后约 ' + estimated + ' Token,输入预算 ' + budget + '。请按原文位置拆分资料或改派到更大窗口。')
132
+ error.code='CONTEXT_OVERFLOW'
133
+ throw error
134
+ }
131
135
  const evidence = entries.map(e => ({id: e.item.id, ref: ref(e.item), title: e.item.title, version: e.item.version ?? 1,
132
136
  hash: e.item.hash ?? null, kind: e.item.kind, lines: e.selected ? [...e.selected].sort((a,b) => a-b).map(i => i+1) : null,
133
137
  excerpt: e.excerpt && !e.selected?.has(e.excerpt.index) ? {line:e.excerpt.index+1,start:1,end:e.excerpt.length} : null,
@@ -0,0 +1,86 @@
1
+ // 彩蛋.xlsx, Sheet1!B2:I8. Column C labels the languages of the replies in D.
2
+ export const eggPhrases = Object.freeze({
3
+ 古怪: Object.freeze(['にゃ〜 ฅ^•ﻌ•^ฅ', 'Ciallo~(∠・ω< )⌒★']),
4
+ 各国语言: Object.freeze(['Coucou!', 'Holaaa~', 'Hallöchen!', 'Привет!', '안뇽!', 'はーい!( ´ ▽ ` )ノ', 'やっほー!(≧▽≦)']),
5
+ 正常人类: Object.freeze(['怎么啦?', '嗨', '一直在啊']),
6
+ 不正常: Object.freeze(['你猜?', '可以不在吗?', '阿巴阿巴', '又有活了']),
7
+ 程序员: Object.freeze(['Let me cook', 'Noodling…']),
8
+ 颜文字: Object.freeze(['👀', '( ̄▽ ̄)', '(・∀・)', '(`・ω・´)', '(=^・ω・^=)']),
9
+ nova系列: Object.freeze(['Still shining ✩', 'Ad astra ✧', '(∩^o^)⊃━☆゚.*', '星星收到啦 ✦']),
10
+ })
11
+
12
+ const closings = [
13
+ "**NOVA:See? We're all here. ✦**",
14
+ '**NOVA:Here we are, together. ♡**',
15
+ '**NOVA:Present and shining! ✧**',
16
+ ]
17
+
18
+ // Draw every item once before refilling. At a cycle boundary avoid repeating the last draw.
19
+ function drawFrom(items, random) {
20
+ let pool = [], previous
21
+ return () => {
22
+ let available = pool.length
23
+ if (!available) {
24
+ pool = items.filter(item=>item!==previous)
25
+ available = pool.length
26
+ if (previous!==undefined) pool.push(previous)
27
+ }
28
+ const index = Math.floor(random() * (available || pool.length))
29
+ previous = pool.splice(index,1)[0]
30
+ return previous
31
+ }
32
+ }
33
+
34
+ const modelName = route => route.modelId || route.label || route.id
35
+ const oneLine = text => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/gu,' ')
36
+ .replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu,'').trim()
37
+ const renderPhrase = (phrase, route) => phrase.replaceAll('【模型】',()=>oneLine(modelName(route)))
38
+
39
+ export function allocateEggReplies(routes, random = Math.random) {
40
+ const categories = Object.keys(eggPhrases)
41
+ const nextCategory = drawFrom(categories, random)
42
+ const members = new Map(categories.map(category=>[category,[]]))
43
+ const replies = routes.map(route=>{
44
+ const category = nextCategory()
45
+ const reply = {routeId:route.id, category, text:'', choices:[]}
46
+ members.get(category).push({route, reply})
47
+ return reply
48
+ })
49
+ for (const [category, team] of members) {
50
+ if (!team.length) continue
51
+ const phrases = eggPhrases[category]
52
+ const nextPhrase = drawFrom(phrases,random), unused = new Set(phrases)
53
+ for (const {route, reply} of team) {
54
+ const phrase = nextPhrase()
55
+ unused.delete(phrase)
56
+ reply.text = renderPhrase(phrase,route)
57
+ reply.choices.push(reply.text)
58
+ }
59
+ // Disjoint menus let each live model choose freely without duplicating another model's choices.
60
+ const extraPhrase = drawFrom([...unused],random), recipient = drawFrom(team,random)
61
+ for (let i = 0; i < unused.size; i++) {
62
+ const {route, reply} = recipient()
63
+ reply.choices.push(renderPhrase(extraPhrase(),route))
64
+ }
65
+ }
66
+ return replies
67
+ }
68
+
69
+ function markdownText(value) {
70
+ return oneLine(value).replace(/[\\`*_\[\]<>~&|]/g,'\\$&')
71
+ }
72
+
73
+ export function formatEggReply(route, text) {
74
+ const provider = route.providerId || route.apiId
75
+ const name = provider ? provider+' / '+modelName(route) : modelName(route)
76
+ return '**'+markdownText(name)+'**:'+markdownText(text)
77
+ }
78
+
79
+ export function chooseNovaClosing(random = Math.random) {
80
+ return closings[Math.floor(random() * closings.length)]
81
+ }
82
+
83
+ export function formatEggMessage(lines, closing = chooseNovaClosing()) {
84
+ if (!closings.includes(closing)) throw Error('未知的 NOVA 彩蛋结语。')
85
+ return lines.length ? lines.join(' \n')+'\n\n'+closing : closing
86
+ }
@@ -17,9 +17,9 @@ export function routeCatalog(routes) {
17
17
  return copy(routes)
18
18
  }
19
19
 
20
- export function normalizeNodes(plan) {
21
- if (!Array.isArray(plan?.nodes) || !plan.nodes.length || plan.nodes.length > 100) {
22
- throw Error('计划需包含 1 至 100 个节点')
20
+ export function normalizeNodes(plan, maxNodes = 100) {
21
+ if (!Array.isArray(plan?.nodes) || !plan.nodes.length || plan.nodes.length > maxNodes) {
22
+ throw Error('计划需包含 1 至 '+maxNodes+' 个节点')
23
23
  }
24
24
  const ids = new Set()
25
25
  const deliverables = new Set()
package/src/engine.mjs CHANGED
@@ -24,9 +24,27 @@ const safeLimit = (value, name) => {
24
24
  return value
25
25
  }
26
26
 
27
+ const needsFinalReserve = (state,node) => !node.final && (state.status === 'planning' || state.nodes.some(n => n.final && ['pending','blocked'].includes(n.status)))
28
+ const plannedOutput = (state,node) => positiveNumber(node.outputReserve) || positiveNumber(state.settings.outputReserve) || (node.id === 'plan' ? 4096 : 2048)
29
+
30
+ function remainingTokens(state, node, replacingId) {
31
+ let consumed = state.attempts.reduce((sum, attempt) => {
32
+ if (attempt.id === replacingId) return sum
33
+ const actual = attempt.usage?.total
34
+ return sum + (attempt.status === 'running' || !Number.isFinite(actual) ? attempt.reservedTokens : actual)
35
+ }, 0)
36
+ for (const op of state.operations || []) {
37
+ if (op.id === replacingId) continue
38
+ const children = state.attempts.filter(a => a.parentId === op.id)
39
+ if (op.status !== 'running' && !children.some(child => !Number.isFinite(child.usage?.total))) continue
40
+ const observed = children.reduce((sum,a) => sum + (a.usage?.total ?? 0), 0)
41
+ consumed += Math.max(0, op.reservedTokens - observed)
42
+ }
43
+ return state.maxTokens - consumed - (needsFinalReserve(state,node) ? state.reserveFinalTokens : 0)
44
+ }
45
+
27
46
  function limitReason(state, node) {
28
- const reserveFinal = !node.final && (state.status === 'planning' || state.nodes.some(n => n.final && ['pending','blocked'].includes(n.status)))
29
- const reservedRequests = reserveFinal ? state.reserveFinalRequests : 0
47
+ const reservedRequests = needsFinalReserve(state,node) ? state.reserveFinalRequests : 0
30
48
  let committed = state.attempts.length
31
49
  for (const op of ownedCalls(state).filter(a => a.status === 'running')) {
32
50
  const physical = state.operations.some(a => a.id === op.id) ? state.attempts.filter(a => a.parentId === op.id).length : 1
@@ -38,17 +56,7 @@ function limitReason(state, node) {
38
56
  }
39
57
  const requestSlots = node.tools?.length ? Math.min(positiveNumber(state.settings.maxToolSteps) || 4, remainingRequests ?? Infinity) : 1
40
58
  if (state.maxTokens == null) return { reserved: node.tokenBudget || 0, requestSlots }
41
- let consumed = state.attempts.reduce((sum, attempt) => {
42
- const actual = attempt.usage?.total
43
- return sum + (attempt.status === 'running' || !Number.isFinite(actual) ? attempt.reservedTokens : actual)
44
- }, 0)
45
- for (const op of state.operations || []) {
46
- const children = state.attempts.filter(a => a.parentId === op.id)
47
- if (op.status !== 'running' && !children.some(child => !Number.isFinite(child.usage?.total))) continue
48
- const observed = children.reduce((sum,a) => sum + (a.usage?.total ?? 0), 0)
49
- consumed += Math.max(0, op.reservedTokens - observed)
50
- }
51
- const remaining = state.maxTokens - consumed - (reserveFinal ? state.reserveFinalTokens : 0)
59
+ const remaining = remainingTokens(state,node)
52
60
  // A fixed small reservation would reject a valid long-document job even with sufficient remaining budget.
53
61
  const route = state.routes.find(r => r.id === (node.nextRouteId || node.routeId))
54
62
  const sourceText = state.sources.filter(s => node.sourceIds?.includes(s.id)).map(s => s.text || '')
@@ -57,8 +65,7 @@ function limitReason(state, node) {
57
65
  ? JSON.stringify([state.allowedRouteIds, state.sources.map(s => [s.id, s.title || s.name])])
58
66
  : JSON.stringify([node.title, node.goal, node.acceptance, node.constraints, node.tools])
59
67
  const inputEstimate = [state.task, brief, ...new Set([...sourceText, ...upstream])].reduce((sum, content) => sum + estimateInput(content), 64)
60
- const outputReserve = Math.min(positiveNumber(route?.maxOutput) || Infinity,
61
- positiveNumber(node.outputReserve) || positiveNumber(state.settings.outputReserve) || (node.id === 'plan' ? 4096 : 2048))
68
+ const outputReserve = Math.min(positiveNumber(route?.maxOutput) || Infinity, plannedOutput(state,node))
62
69
  const suggested = Math.max(positiveNumber(state.settings.defaultAttemptTokens) || 4096, inputEstimate + outputReserve)
63
70
  const reserved = node.tokenBudget || Math.min(suggested, remaining)
64
71
  return reserved > 0 && reserved <= remaining ? { reserved, requestSlots } : { reason: 'Token 预算不足(含活动请求与终稿预留)' }
@@ -80,7 +87,7 @@ function beginAttempt(state, node, route, kind, reserved) {
80
87
 
81
88
  function publish(state, plan, fromPlanner = false) {
82
89
  if (plan?.validationError) throw Error(String(plan.validationError))
83
- const nodes = normalizeNodes(plan)
90
+ const nodes = normalizeNodes(plan, !fromPlanner && state.settings.easterEgg ? state.allowedRouteIds.length : undefined)
84
91
  if (fromPlanner && nodes.length > 1) {
85
92
  const byId = new Map(nodes.map(n => [n.id, n])), prerequisites = new Set()
86
93
  const include = id => {
@@ -127,8 +134,30 @@ function missingInputs(state, node) {
127
134
  }
128
135
 
129
136
  function availableFallback(state, node, exclude) {
130
- const previous = new Set(ownedCalls(state).filter(a => a.nodeId === node.id && a.revision === node.revision).map(a => a.routeId))
131
- return node.fallbackRouteIds.find(id => id !== exclude && !previous.has(id) && state.allowedRouteIds.includes(id) && !incompatibility(state,node,id))
137
+ const attempts = ownedCalls(state).filter(a => a.nodeId === node.id && a.revision === node.revision)
138
+ const previous = new Set(attempts.map(a=>a.routeId))
139
+ const candidates = node.fallbackRouteIds.filter(id => id !== exclude && !previous.has(id) && state.allowedRouteIds.includes(id) && !incompatibility(state,node,id))
140
+ return nextAvailable(state,candidates,attempts)
141
+ }
142
+
143
+ function nextAvailable(state, candidates, attempts) {
144
+ const cooldowns = new Map()
145
+ for (const attempt of attempts) if (attempt.retryAfter) {
146
+ cooldowns.set(attempt.apiId, Math.max(cooldowns.get(attempt.apiId) || 0, Date.parse(attempt.retryAfter)))
147
+ }
148
+ let delayed
149
+ for (const id of candidates) {
150
+ const apiId = api(state.routes.find(r=>r.id===id))
151
+ const retryAt = cooldowns.get(apiId) || 0
152
+ if (retryAt <= Date.now()) return {id,retryAfter:null}
153
+ if (!delayed || retryAt < Date.parse(delayed.retryAfter)) delayed = {id,retryAfter:new Date(retryAt).toISOString()}
154
+ }
155
+ return delayed
156
+ }
157
+
158
+ function retryAfter(error) {
159
+ const delay = Number(error?.retryAfterMs)
160
+ return Number.isFinite(delay) && delay > 0 && delay < 8.64e15 - Date.now() ? new Date(Date.now() + delay).toISOString() : null
132
161
  }
133
162
 
134
163
  async function contentHash(text) {
@@ -189,6 +218,25 @@ function setReceipt(state, attempt, result) {
189
218
  }
190
219
  }
191
220
 
221
+ function recordUnsent(state, attempt, error) {
222
+ if (error?.dispatched === false && !state.operations.some(op => op.id === attempt.id)) {
223
+ state.operations.push(attempt)
224
+ state.attempts = state.attempts.filter(record => record.id !== attempt.id)
225
+ }
226
+ }
227
+
228
+ function largerPlanningOutput(state, attempt, error) {
229
+ if (error.finishKind !== 'max-tokens' || !positiveNumber(error.maxTokens) || !Number.isSafeInteger(error.inputEstimate)) return 0
230
+ const route = state.routes.find(r => r.id === attempt.routeId && r.enabled !== false)
231
+ const node = {id:'plan', routeId:attempt.routeId}
232
+ if (!route || limitReason(state,node).reason) return 0
233
+ const window = Math.min(...[route.contextWindow,route.window,route.deploymentWindow].filter(positiveNumber))
234
+ const available = state.maxTokens == null ? Infinity : remainingTokens(state,node) - error.inputEstimate
235
+ const limit = Math.min(8192, route.maxOutput || Infinity, route.outputLimit || Infinity, Math.floor(window / 2),
236
+ window - (attempt.context?.margin || 0) - error.inputEstimate, available)
237
+ return limit > error.maxTokens ? Math.floor(limit) : 0
238
+ }
239
+
192
240
  function resetNode(state, node) {
193
241
  const attempt = byAttempt(state, node.attemptId)
194
242
  if (attempt?.status === 'running') {
@@ -208,6 +256,7 @@ export class RunEngine {
208
256
  #listeners = new Set()
209
257
  #live = new Map()
210
258
  #pumpTask = null
259
+ #planning = false
211
260
  #wakeAgain = false
212
261
  #wakeTimer
213
262
  #fault = null
@@ -218,8 +267,9 @@ export class RunEngine {
218
267
  this.#beforeAutoStart = options.beforeAutoStart
219
268
  const settings = copy(options.settings || {})
220
269
  const allowedRouteIds = strings(options.allowedRouteIds ?? routes.filter(route => route.enabled !== false).map(route => route.id), '允许的路由')
221
- const plannerAssignment = options.plannerAssignment || choosePlanner(routes.filter(r=>allowedRouteIds.includes(r.id)), options.task || '',
222
- {lockedId:options.plannerRouteId,preferredId:options.preferredPlannerId})
270
+ const plannerAssignment = settings.easterEgg || !allowedRouteIds.length ? null : options.plannerAssignment ||
271
+ choosePlanner(routes.filter(r=>allowedRouteIds.includes(r.id)), options.task || '',
272
+ {lockedId:options.plannerRouteId,preferredId:options.preferredPlannerId})
223
273
  const configured = key => options[key] ?? settings[key]
224
274
  const maxTokens = safeLimit(configured('maxTokens'), 'Token 预算')
225
275
  const defaultFinalTokens = maxTokens == null ? 0 : Math.min(2048, Math.floor(maxTokens / 8))
@@ -328,9 +378,16 @@ export class RunEngine {
328
378
  publish(state, plan)
329
379
  for(const node of state.nodes) {
330
380
  const old=previous.get(node.id)
331
- if (old?.routeId===node.routeId && old.assignment && old.role===node.role && old.title===node.title) node.assignment=old.assignment
381
+ const sameOwner=old?.routeId===node.routeId && old.assignment && old.role===node.role && old.title===node.title
382
+ if (sameOwner) node.assignment={...old.assignment}
332
383
  else node.assignment={role:nodeRole(node,state.task),routeId:node.routeId,source:'manual',reasons:['用户编辑并指定了本步骤及负责人。'],evidence:[]}
384
+ if (old?.assignment?.automaticFallbacks) {
385
+ const kept=JSON.stringify(node.fallbackRouteIds)===JSON.stringify(old.fallbackRouteIds)
386
+ if (kept && (!sameOwner || node.tools.length || node.writePaths.length)) node.fallbackRouteIds=[]
387
+ if (!kept || !node.fallbackRouteIds.length) delete node.assignment.automaticFallbacks
388
+ }
333
389
  }
390
+ state.assignmentsHash=assignmentsHash(state)
334
391
  return {planVersion: state.planVersion}
335
392
  })
336
393
  return this.snapshot()
@@ -338,16 +395,47 @@ export class RunEngine {
338
395
 
339
396
  async plan(planner) {
340
397
  if (typeof planner !== 'function') throw Error('缺少统筹执行器')
341
- let correction = ''
342
- for (let round = 0; round < 2; round++) {
398
+ if (this.#planning) throw Error('规划已被领取或结束')
399
+ this.#planning = true
400
+ try { return await this.#runPlanner(planner) }
401
+ finally { this.#planning = false }
402
+ }
403
+
404
+ async #runPlanner(planner) {
405
+ const initial = this.#state.plannerAssignment
406
+ const initialPlannerId = this.#state.plannerRouteId
407
+ const plannerIds = [...new Set([initialPlannerId, ...(initial?.fallbackRouteIds || [])])]
408
+ let index = 0, correction = '', revising = false, planningOutputTokens = 4096, expanded = false
409
+ while (index < plannerIds.length) {
343
410
  const event = await this.#change('planning.claimed', state => {
344
411
  if (state.status !== 'planning' || state.attempts.some(a => a.status === 'running')) throw Error('规划已被领取或结束')
345
- const route = state.routes.find(r => r.id === state.plannerRouteId && r.enabled !== false)
346
- if (!route || !(route.capabilities || ['text']).includes('text') || !state.allowedRouteIds.includes(route.id)) throw Error('没有获准的文本统筹路由')
347
- const node = {id: 'plan', revision: 1, routeId: route.id}
412
+ const allowed = new Set(state.allowedRouteIds)
413
+ const history = state.sources.find(s=>s.id===initial?.historySourceId)
414
+ const eligible = new Map(state.routes.filter(r=>r.enabled !== false && allowed.has(r.id) &&
415
+ (r.capabilities || ['text']).includes('text') && (!initial?.historySourceId || mayRead(history,r))).map(r=>[r.id,r]))
416
+ const candidates = plannerIds.slice(index).filter(id=>eligible.has(id))
417
+ const selected = nextAvailable(state,candidates,ownedCalls(state).filter(a=>a.nodeId==='plan'))
418
+ if (!selected) throw Error('没有获准的文本统筹路由')
419
+ if (plannerIds[index] !== selected.id) {
420
+ const next = plannerIds.indexOf(selected.id,index)
421
+ plannerIds[next] = plannerIds[index]
422
+ plannerIds[index] = selected.id
423
+ revising = false; correction = ''; expanded = false; planningOutputTokens = 4096
424
+ }
425
+ const route = eligible.get(selected.id)
426
+ const node = {id:'plan', revision:1, routeId:route.id, outputReserve:planningOutputTokens}
348
427
  const budget = limitReason(state, node)
349
428
  if (budget.reason) throw Error(budget.reason)
350
- const attempt = beginAttempt(state, node, route, round ? 'plan_revision' : 'planning', budget.reserved)
429
+ if (selected.retryAfter) return {type:'planning.waiting_for_provider',retryAfter:selected.retryAfter}
430
+ if (state.plannerRouteId !== route.id) {
431
+ state.plannerRouteId = route.id
432
+ state.plannerAssignment = {...initial, routeId:route.id, source:'fallback', evidence:[],
433
+ reasons:['前一统筹未完成规划,已切换至本次允许的候补型号。']}
434
+ }
435
+ const kind = revising || expanded ? 'plan_revision' : route.id === initialPlannerId ? 'planning' : 'fallback'
436
+ const attempt = beginAttempt(state,node,route,kind,budget.reserved)
437
+ attempt.plannedRouteId = initialPlannerId
438
+ attempt.planningOutputTokens = planningOutputTokens
351
439
  return {attemptId: attempt.id}
352
440
  }).catch(async error => {
353
441
  if (!this.#fault) await this.#change('planning.blocked', state => {
@@ -358,6 +446,15 @@ export class RunEngine {
358
446
  })
359
447
  throw error
360
448
  })
449
+ if (event.retryAfter) {
450
+ await new Promise(resolve=>{
451
+ const timer = setTimeout(finish, Math.min(0x7fffffff, Math.max(1, Date.parse(event.retryAfter) - Date.now())))
452
+ const off = this.subscribe((state,update)=>{ if (state.status !== 'planning' || update.type === 'catalog.updated') finish() })
453
+ function finish() { clearTimeout(timer); off(); resolve() }
454
+ if (this.#state.status !== 'planning') finish()
455
+ })
456
+ continue
457
+ }
361
458
  const id = event.attemptId
362
459
  const controller = new AbortController()
363
460
  this.#live.set(id, controller)
@@ -372,7 +469,9 @@ export class RunEngine {
372
469
  }))
373
470
  result = await planner({task: state.task, node: {id: 'plan', role: 'planner', title: '规划任务', sourceIds: [], deps: []},
374
471
  route, routes: state.routes.filter(r => r.enabled !== false && state.allowedRouteIds.includes(r.id)), sources, settings: state.settings,
375
- inputs: [], correction, signal: controller.signal, attemptId: id, report: patch => this.#report(id, patch),
472
+ inputs: [], correction, planningOutputTokens, signal: controller.signal, attemptId: id, report: patch => this.#report(id, patch),
473
+ planningTokenBudget:state.maxTokens == null ? null : remainingTokens(state,{id:'plan'},id),
474
+ reserveTokens: (input, output) => this.#reserveTokens(id, input, output),
376
475
  maxAttemptTokens: state.maxTokens == null ? null : attempt.reservedTokens,
377
476
  runId: state.runId, sessionId: state.sessionId})
378
477
  await this.#change('plan.published', draft => {
@@ -385,16 +484,25 @@ export class RunEngine {
385
484
  })
386
485
  return await this.#afterPublish()
387
486
  } catch (error) {
388
- const invalidPlan = !!result && round === 0 && this.#state.status === 'planning' && !this.#fault
389
- correction = message(error)
390
- await this.#change('planning.failed', draft => {
487
+ const reason = message(error)
488
+ const recoverable = this.#state.status === 'planning' && !this.#fault && !controller.signal.aborted && error?.retryable !== false
489
+ const revise = recoverable && !!result && !revising
490
+ const switchPlanner = recoverable && !revise && index + 1 < plannerIds.length
491
+ const failure = await this.#change('planning.failed', draft => {
391
492
  const a = byAttempt(draft, id)
392
493
  setReceipt(draft, a, result || error)
393
- if (a.status === 'running') Object.assign(a, {status: 'failed', error: correction, endedAt: now()})
394
- if (draft.status === 'planning' && !invalidPlan) { draft.status = 'blocked'; draft.error = correction }
395
- return {attemptId: id, reason: correction}
494
+ if (a.status === 'running') Object.assign(a, {status:'failed', error:reason, endedAt:now()})
495
+ if (error?.retryAfterMs) a.retryAfter = retryAfter(error)
496
+ recordUnsent(draft, a, error)
497
+ const nextOutput = recoverable && !expanded && draft.status === 'planning' ? largerPlanningOutput(draft,a,error) : 0
498
+ if (draft.status === 'planning' && !nextOutput && !revise && !switchPlanner) { draft.status = 'blocked'; draft.error = reason }
499
+ return {attemptId:id, reason, ...(nextOutput && {nextOutput})}
396
500
  })
397
- if (!invalidPlan) throw error
501
+ if (failure.nextOutput) { expanded = true; planningOutputTokens = failure.nextOutput; continue }
502
+ if (!revise && !switchPlanner) throw error
503
+ if (switchPlanner) { index++; expanded = false; planningOutputTokens = 4096 }
504
+ revising = revise
505
+ correction = revise ? reason : ''
398
506
  } finally { this.#live.delete(id) }
399
507
  }
400
508
  }
@@ -464,6 +572,27 @@ export class RunEngine {
464
572
  })
465
573
  }
466
574
 
575
+ async #reserveTokens(id, input, output) {
576
+ const current = this.#state
577
+ const active = byAttempt(current,id)
578
+ if (active?.status !== 'running') throw Object.assign(Error('此请求已结束'), {dispatched:false})
579
+ if (current.maxTokens == null) {
580
+ return current.nodes.find(node => node.id === active.nodeId)?.tokenBudget || null
581
+ }
582
+ const event = await this.#change('attempt.budget_reserved', state => {
583
+ const attempt = byAttempt(state,id)
584
+ if (attempt?.status !== 'running') throw Object.assign(Error('此请求已结束'), {dispatched:false})
585
+ const node = attempt.nodeId === 'plan' ? {id:'plan',outputReserve:attempt.planningOutputTokens} : byNode(state,attempt.nodeId)
586
+ // The host now has the actual assembled request, including the selected catalog and conversation history.
587
+ const desired = Math.max(attempt.reservedTokens, input + plannedOutput(state,node))
588
+ const ceiling = Math.min(input + output, desired, node.tokenBudget || Infinity, remainingTokens(state,node,id))
589
+ if (ceiling <= input) throw Object.assign(Error('输入约 '+input+' Token,当前请求可用 '+Math.max(0,ceiling)+' Token,无法预留输出。'), {dispatched:false})
590
+ attempt.reservedTokens = ceiling
591
+ return {attemptId:id, reservedTokens:ceiling}
592
+ })
593
+ return event.reservedTokens
594
+ }
595
+
467
596
  #wake() {
468
597
  if (this.#fault || this.#state.status !== 'running') return
469
598
  if (this.#pumpTask) { this.#wakeAgain = true; return }
@@ -496,8 +625,8 @@ export class RunEngine {
496
625
  if (!reason && unsuitable && state.allowedRouteIds.includes(routeId)) {
497
626
  const fallback = availableFallback(state,node,routeId)
498
627
  if (fallback) {
499
- node.nextRouteId = fallback; node.switchReason = unsuitable
500
- routeId = fallback; unsuitable = null
628
+ node.nextRouteId = fallback.id; node.switchReason = unsuitable; node.retryAfter = fallback.retryAfter
629
+ routeId = fallback.id; unsuitable = null
501
630
  }
502
631
  }
503
632
  reason ||= unsuitable
@@ -567,6 +696,7 @@ export class RunEngine {
567
696
  signal: controller.signal, attemptId: id, runId: snapshot.runId, sessionId: snapshot.sessionId,
568
697
  maxAttemptTokens: snapshot.maxTokens == null && !node.tokenBudget ? null : attempt.reservedTokens,
569
698
  remainingRequests: snapshot.maxRequests == null ? null : attempt.reservedRequests,
699
+ reserveTokens: (input, output) => this.#reserveTokens(id, input, output),
570
700
  report: patch => this.#report(id, patch)})
571
701
  checkpoint(result)
572
702
  hash = await contentHash(result.text)
@@ -583,19 +713,15 @@ export class RunEngine {
583
713
  if (problem) {
584
714
  a.status = 'failed'
585
715
  a.error = message(problem)
586
- if (problem.dispatched === false && !state.operations.some(op => op.id === a.id)) {
587
- state.operations.push(a)
588
- state.attempts = state.attempts.filter(record => record.id !== a.id)
589
- }
716
+ recordUnsent(state, a, problem)
590
717
  current.status = 'failed'
591
718
  current.phase = 'failed'
592
719
  current.reason = a.error
593
720
  current.finishedAt = a.endedAt
594
- const delay = Number(problem.retryAfterMs)
595
- if (Number.isFinite(delay) && delay > 0 && delay < 8.64e15 - Date.now()) current.retryAfter = new Date(Date.now() + delay).toISOString()
721
+ if (problem.retryAfterMs) current.retryAfter = a.retryAfter = retryAfter(problem)
596
722
  const candidate = availableFallback(state,current,a.routeId)
597
723
  if (candidate && problem.retryable !== false && !controller.signal.aborted) {
598
- Object.assign(current, {nextRouteId: candidate, switchReason: a.error, status: 'pending', phase: 'queued', reason: null})
724
+ Object.assign(current, {nextRouteId:candidate.id, retryAfter:candidate.retryAfter, switchReason:a.error, status:'pending', phase:'queued', reason:null})
599
725
  }
600
726
  } else {
601
727
  a.status = 'completed'
@@ -670,6 +796,7 @@ export class RunEngine {
670
796
  const previousRouteId = node.routeId, previousAttempt = node.attemptId
671
797
  resetNode(state, node)
672
798
  node.routeId = routeId
799
+ if (node.assignment?.automaticFallbacks) node.fallbackRouteIds = []
673
800
  node.assignment = {role:node.assignment?.role || nodeRole(node,state.task),routeId,source:'manual',reasons:['用户改派了本节点。'],evidence:[]}
674
801
  state.planVersion++
675
802
  state.assignmentsHash = assignmentsHash(state)
@@ -116,9 +116,16 @@ export function choosePlanner(routes, task, {lockedId,preferredId,history} = {})
116
116
  lockedId ||= owner
117
117
  if (lockedId) {
118
118
  if (!candidates.some(r=>r.id===lockedId)) throw Error('显式指定的统筹路由未获准、不可读取所需前文或缺少文本能力。')
119
- return {role:'planning',routeId:lockedId,difficulty,source:'manual',reasons:['用户指定了本次统筹模型。'],evidence:[]}
119
+ return {role:'planning',routeId:lockedId,difficulty,source:'manual',reasons:['用户指定了本次统筹模型。'],evidence:[],
120
+ ...(history?.id && {historySourceId:history.id})}
120
121
  }
121
- return choose(candidates.filter(r=>!denied.has(r.id)),'planning',content,preferredId,difficulty)
122
+ const eligible=candidates.filter(r=>!denied.has(r.id))
123
+ const pick=choose(eligible,'planning',content,preferredId,difficulty)
124
+ if (pick) {
125
+ pick.fallbackRouteIds=eligible.filter(r=>r.id!==pick.routeId).map(r=>r.id)
126
+ if (history?.id) pick.historySourceId=history.id
127
+ }
128
+ return pick
122
129
  }
123
130
 
124
131
  export function planningCards(routes,task) {
@@ -232,7 +239,15 @@ export function assignGeneratedPlan(nodes, routes, task, sources, options={}) {
232
239
  }
233
240
  nodes[i].routeId=pick.routeId
234
241
  nodes[i].difficulty=difficulty
235
- if (nodes[i].fallbackRouteIds) nodes[i].fallbackRouteIds=nodes[i].fallbackRouteIds.filter(id=>!denied.has(id) && (!lock || id===lock) && id!==pick.routeId)
242
+ if (nodes[i].fallbackRouteIds) {
243
+ nodes[i].fallbackRouteIds=nodes[i].fallbackRouteIds.filter(id=>!denied.has(id) && (!lock || id===lock) && id!==pick.routeId)
244
+ } else if (!options.offline && !options.single && !lock && !n.tools.length && !n.writePaths?.length) {
245
+ const compatible=routes.filter(r=>r.id!==pick.routeId && !denied.has(r.id) && !incompatibility(state,n,r.id))
246
+ if (compatible.length) {
247
+ nodes[i].fallbackRouteIds=compatible.map(r=>r.id)
248
+ pick.automaticFallbacks=true
249
+ }
250
+ }
236
251
  nodes[i].assignment=pick
237
252
  const promptInputs=n.deps.filter(id=>normalized.some(other=>other.id===id && promptNode(other)))
238
253
  nodes[i].instructions=[typeof n.instructions==='string'?n.instructions:'',