dsh-nova-lewis 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ import {formatEggMessage, formatEggReply} from '../src/easter-egg.mjs'
2
+ import {isRollCall, renderRollCall, rollCallReplies} from './roll-call.mjs'
3
+
4
+ export const RUN_RECORD = 'plugin:collaboration/run'
5
+
6
+ export function delivered(run) {
7
+ const finals = run.nodes.filter(node => node.final && node.artifactId)
8
+ const used = new Set(run.nodes.flatMap(node => node.deps || []))
9
+ const outputs = finals.length ? finals : run.nodes.filter(node => node.artifactId && !used.has(node.id))
10
+ const artifacts = new Map(run.artifacts.map(artifact => [artifact.id, artifact]))
11
+ return outputs.map(node => artifacts.get(node.artifactId)).filter(Boolean)
12
+ }
13
+
14
+ function artifactText(artifact) {
15
+ return artifact.text + (artifact.unresolved?.length ? '\n未决项:' + artifact.unresolved.join('、') : '')
16
+ }
17
+
18
+ export function completedText(run) {
19
+ if (run.settings?.easterEgg) return renderRollCall(run)
20
+ return delivered(run).map(artifactText).join('\n\n') || '本次协作没有可交付的答复。'
21
+ }
22
+
23
+ function matchingRollCall(run, markdown) {
24
+ const replies = rollCallReplies(run)
25
+ const closing = run.settings.easterEgg.closing
26
+ if (renderRollCall(run, replies) !== markdown) {
27
+ // 0.2.2 and 0.2.3 included the account name in saved lines.
28
+ const older = replies.map(({route, text}) => {
29
+ const provider = route.providerId || route.apiId
30
+ const name = route.modelId || route.label || route.id
31
+ return formatEggReply({modelId:provider ? provider + ' / ' + name : name}, text)
32
+ })
33
+ if (formatEggMessage(older, closing) !== markdown) return null
34
+ }
35
+ return {kind:'roll-call', markdown, participants:replies.map(({route, text}) => ({name:route.modelId || route.label || route.id, text})),
36
+ closing:closing.slice(2, -2)}
37
+ }
38
+
39
+ // The transcript slot identifies a persisted assistant event. Only a completed
40
+ // Nova run in that exact DSH step can supply its attribution and deliverables.
41
+ export function transcriptReply(session, {messageId, seq}, getRun) {
42
+ if (!session || typeof messageId !== 'string' || !messageId) return null
43
+ let at
44
+ if (typeof session.eventAt === 'function' && Number.isSafeInteger(seq) && seq >= 0) {
45
+ if (seq >= session.seq) throw Error('消息尚未保存。')
46
+ at = index => session.eventAt(index)
47
+ } else {
48
+ const events = session.ownEvents()
49
+ seq = events.findIndex(event => event.type === 'assistant/message' && event.data.message?.id === messageId)
50
+ at = index => events[index]
51
+ }
52
+ const entry = at(seq)
53
+ const message = entry?.data?.message
54
+ if (entry?.type !== 'assistant/message' || message?.id !== messageId || message.role !== 'assistant' ||
55
+ message.source?.kind !== 'model' || !message.content?.length || message.content.some(b => b.type !== 'text')) return null
56
+ const markdown = message.content.map(block => block.text).join('')
57
+ // Command/workbench delivery appends its own assistant event immediately after
58
+ // persisting completion, outside the agent loop (turn 0, step 0).
59
+ const standalone = entry.data.turn === 0 && entry.data.step === 0
60
+ const candidates = [], inputs = []
61
+ for (let pos = seq - 1; pos >= 0; pos--) {
62
+ const event = at(pos)
63
+ if (!event || event.type === 'step/start' || event.type === 'turn/start') break
64
+ if (event.type === RUN_RECORD && event.ignorable === true && event.data.fields?.status === 'completed')
65
+ candidates.push(event.data.runId)
66
+ if (standalone) break
67
+ if (event.type === 'assistant/message' && event.data.turn !== 0) break
68
+ if (event.type === 'user/message' && event.data.source?.kind === 'user') inputs.push(event.data)
69
+ }
70
+ if (!standalone && !isRollCall(inputs)) return null
71
+ for (const runId of candidates) {
72
+ const run = getRun(runId)
73
+ if (!run) continue
74
+ if (standalone) {
75
+ if (completedText(run) === markdown) return {kind:'answer', markdown}
76
+ } else if (run.settings?.easterEgg && run.settings.nativePromptId === inputs[0].id) {
77
+ const reply = matchingRollCall(run, markdown)
78
+ if (reply) return reply
79
+ }
80
+ }
81
+ return null
82
+ }
@@ -34,6 +34,39 @@ export function prepareRollCall(pref, routes) {
34
34
  return {participants, replies, closing:chooseNovaClosing()}
35
35
  }
36
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
+
37
70
  export async function executeRollCall(ctx, args) {
38
71
  const reply = args.settings.easterEgg.replies.find(item => item.routeId === args.route.id)
39
72
  if (!reply || args.route.id !== args.node.routeId) throw Object.assign(Error('未找到该型号的彩蛋候选。'), {dispatched:false})
@@ -41,8 +74,9 @@ export async function executeRollCall(ctx, args) {
41
74
  {role:'system', content:'NOVA 彩蛋点名。用户问“在嘛?”。请从用户消息的 JSON 数组中任选一句作答。只返回从 1 开始的选项编号,或逐字返回所选原句。'},
42
75
  {role:'user', content:JSON.stringify(reply.choices)},
43
76
  ]
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)])
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])
46
80
  signal.throwIfAborted()
47
81
  let onAbort
48
82
  const aborted = new Promise((_, reject) => {
@@ -50,29 +84,38 @@ export async function executeRollCall(ctx, args) {
50
84
  signal.addEventListener('abort', onAbort, {once:true})
51
85
  })
52
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()
53
93
  try {
54
- result = await Promise.race([streamText(ctx, {...args, signal}, messages, args.node.outputReserve), aborted])
94
+ result = await Promise.race([streamText(ctx, {...args, signal, onStreamActivity}, messages), aborted])
55
95
  } finally {
96
+ clearTimeout(timer)
56
97
  signal.removeEventListener('abort', onAbort)
57
98
  }
58
- const answer = result.text
59
- const chosen = /^[1-9]\d*$/.test(answer) ? reply.choices[Number(answer) - 1] : reply.choices.find(text => text === answer)
99
+ const chosen = selectedPhrase(result.text, reply.choices)
60
100
  if (chosen === undefined) throw Object.assign(Error('该型号未返回有效的彩蛋选项。'), {usage:result.usage})
61
101
  return {...result, text:chosen}
62
102
  }
63
103
 
64
- export function renderRollCall(snapshot) {
65
- const {replies, closing} = snapshot.settings.easterEgg
104
+ export function rollCallReplies(snapshot) {
105
+ const {replies} = snapshot.settings.easterEgg
66
106
  const directory = new Map(snapshot.routes.map(route => [route.id, route]))
67
107
  const nodes = new Map(snapshot.nodes.map(node => [node.routeId, node]))
68
108
  const artifacts = new Map(snapshot.artifacts.map(artifact => [artifact.id, artifact]))
69
- const lines = replies.map(({routeId, choices}) => {
109
+ return replies.map(({routeId, choices}) => {
70
110
  const route = directory.get(routeId) || unavailableRoute(routeId)
71
111
  const node = nodes.get(routeId)
72
112
  const artifact = artifacts.get(node?.artifactId)
73
113
  const text = artifact?.routeId === routeId && choices.includes(artifact.text) ? artifact.text :
74
114
  route.enabled === false ? '(型号当前不可用)' : '(本次未回应)'
75
- return formatEggReply(route, text)
115
+ return {route, text}
76
116
  })
77
- return formatEggMessage(lines, closing)
117
+ }
118
+
119
+ export function renderRollCall(snapshot, replies = rollCallReplies(snapshot)) {
120
+ return formatEggMessage(replies.map(({route, text}) => formatEggReply(route, text)), snapshot.settings.easterEgg.closing)
78
121
  }
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "dsh-nova-lewis",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "lewisEnchantRelease": {
5
- "version": "0.2.2",
5
+ "version": "0.2.4",
6
6
  "notes": ""
7
7
  },
8
8
  "lewisEnchantReleaseEn": {
9
- "version": "0.2.2",
9
+ "version": "0.2.4",
10
10
  "notes": ""
11
11
  },
12
12
  "type": "module",
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: 60,
4
- maxTokens: 160000, warnAt: 0.75, compressAt: 0.9, targetAt: 0.7
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]!==defaultSettings[key])).map(key=>[key,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)
@@ -15,6 +15,10 @@ const closings = [
15
15
  '**NOVA:Present and shining! ✧**',
16
16
  ]
17
17
 
18
+ export function hasRollCallClosing(markdown) {
19
+ return typeof markdown === 'string' && closings.some(line => markdown === line || markdown.endsWith('\n\n' + line))
20
+ }
21
+
18
22
  // Draw every item once before refilling. At a cycle boundary avoid repeating the last draw.
19
23
  function drawFrom(items, random) {
20
24
  let pool = [], previous
@@ -71,9 +75,7 @@ function markdownText(value) {
71
75
  }
72
76
 
73
77
  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)
78
+ return '**'+markdownText(modelName(route))+'**:'+markdownText(text)
77
79
  }
78
80
 
79
81
  export function chooseNovaClosing(random = Math.random) {
@@ -79,6 +79,40 @@ export function normalizeNodes(plan, maxNodes = 100) {
79
79
  return nodes
80
80
  }
81
81
 
82
+ // A coordinator can describe the work without enumerating a large roster in its JSON.
83
+ // Give each remaining selected text route its own artifact and wire it into the existing final.
84
+ export function includeSelectedContributors(state, nodes) {
85
+ const final = nodes.find(node => node.final && !node.optional)
86
+ if (!final) return
87
+ const assigned = new Set(nodes.map(node => node.routeId))
88
+ const allowed = new Set(state.allowedRouteIds)
89
+ const ids = new Set(nodes.map(node => node.id))
90
+ const deliverables = new Set(nodes.map(node => node.deliverable.trim().normalize('NFKC').toLowerCase()))
91
+ const finalSources = state.sources.filter(source => final.sourceIds.includes(source.id))
92
+ const extra = []
93
+ let ordinal = 0
94
+ for (const route of state.routes) {
95
+ if (!allowed.has(route.id) || assigned.has(route.id) || route.enabled === false || !(route.capabilities ?? ['text']).includes('text')) continue
96
+ let id, deliverable
97
+ do {
98
+ ordinal++
99
+ id = 'contributor-' + ordinal
100
+ deliverable = '独立建议 ' + ordinal
101
+ } while (ids.has(id) || deliverables.has(deliverable))
102
+ extra.push({id, title:'独立建议 · '+(route.label || route.modelId || route.id), role:'contributor', routeId:route.id,
103
+ deliverable, acceptance:'就当前任务给出具体、可核查的建议。', optional:true,
104
+ instructions:'独立提出对当前任务有帮助的结论、依据或需要核实的问题,交给最终负责人参考。',
105
+ sourceIds:finalSources.filter(source => mayRead(source, route)).map(source => source.id),
106
+ assignment:{routeId:route.id, role:'contributor', source:'selection', reasons:['此型号已勾选参与,本次独立提供建议。'], evidence:[]}})
107
+ }
108
+ if (!extra.length) return
109
+ for (const contributor of normalizeNodes({nodes:extra}, extra.length)) {
110
+ nodes.push(contributor)
111
+ final.deps.push(contributor.id)
112
+ }
113
+ final.instructions = [final.instructions, '结合直接上游各型号的独立建议,核实后给出最终答复。'].filter(Boolean).join('\n')
114
+ }
115
+
82
116
  export function positiveNumber(value) {
83
117
  return Number.isSafeInteger(value) && value > 0 ? value : 0
84
118
  }
package/src/engine.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { assignmentsHash, copy, descendants, incompatibility, inheritedSources, mayRead,
1
+ import { assignmentsHash, copy, descendants, incompatibility, inheritedSources, mayRead, includeSelectedContributors,
2
2
  normalizeNodes, positiveNumber, routeCatalog, strings, uid, writeConflict } from './engine-plan.mjs'
3
3
  import { estimateInput } from './context.mjs'
4
4
  import { assessReview, reviewDecisions } from './engine-review.mjs'
@@ -87,7 +87,9 @@ function beginAttempt(state, node, route, kind, reserved) {
87
87
 
88
88
  function publish(state, plan, fromPlanner = false) {
89
89
  if (plan?.validationError) throw Error(String(plan.validationError))
90
- const nodes = normalizeNodes(plan, !fromPlanner && state.settings.easterEgg ? state.allowedRouteIds.length : undefined)
90
+ const limit = state.settings.easterEgg ? state.allowedRouteIds.length :
91
+ state.settings.includeAllParticipants ? 100 + state.allowedRouteIds.length : undefined
92
+ const nodes = normalizeNodes(plan, limit)
91
93
  if (fromPlanner && nodes.length > 1) {
92
94
  const byId = new Map(nodes.map(n => [n.id, n])), prerequisites = new Set()
93
95
  const include = id => {
@@ -110,6 +112,7 @@ function publish(state, plan, fromPlanner = false) {
110
112
  if (!state.sources.some(source => source.id === id)) throw Error(node.id + ' 引用了不存在的资料:' + id)
111
113
  }
112
114
  }
115
+ if (fromPlanner && state.settings.includeAllParticipants) includeSelectedContributors(state, nodes)
113
116
  state.nodes = nodes
114
117
  state.planVersion += 1
115
118
  state.assignmentsHash = assignmentsHash(state)
@@ -232,7 +235,8 @@ function largerPlanningOutput(state, attempt, error) {
232
235
  if (!route || limitReason(state,node).reason) return 0
233
236
  const window = Math.min(...[route.contextWindow,route.window,route.deploymentWindow].filter(positiveNumber))
234
237
  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),
238
+ const modelLimit = Math.min(route.maxOutput || Infinity, route.outputLimit || Infinity)
239
+ const limit = Math.min(Number.isFinite(modelLimit) ? modelLimit : error.maxTokens * 2,
236
240
  window - (attempt.context?.margin || 0) - error.inputEstimate, available)
237
241
  return limit > error.maxTokens ? Math.floor(limit) : 0
238
242
  }
@@ -584,8 +588,7 @@ export class RunEngine {
584
588
  if (attempt?.status !== 'running') throw Object.assign(Error('此请求已结束'), {dispatched:false})
585
589
  const node = attempt.nodeId === 'plan' ? {id:'plan',outputReserve:attempt.planningOutputTokens} : byNode(state,attempt.nodeId)
586
590
  // 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))
591
+ const ceiling = Math.min(input + output, node.tokenBudget || Infinity, remainingTokens(state,node,id))
589
592
  if (ceiling <= input) throw Object.assign(Error('输入约 '+input+' Token,当前请求可用 '+Math.max(0,ceiling)+' Token,无法预留输出。'), {dispatched:false})
590
593
  attempt.reservedTokens = ceiling
591
594
  return {attemptId:id, reservedTokens:ceiling}