dsh-progress-union 0.1.2 → 0.1.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.
package/client.js CHANGED
@@ -18,6 +18,24 @@ window.__ModuleLoader__.load({
18
18
  window.dispatchEvent(new CustomEvent(PROGRESS_EVENT, { detail: { sessionId, snapshot } }))
19
19
  }
20
20
 
21
+ // 辅助 LLM 可编辑设置:settingsScope.bind({namespace})(0.1.7+)或 configForms.get(ns)(旧)。
22
+ // 通过 ctx.inject 软注入,拿不到时 scopeOf 恒 undefined,面板退化为只读提示。
23
+ let scopeOf = undefined
24
+ function installSettingsScope(ctx) {
25
+ const tryInject = (deps, pick) => {
26
+ try {
27
+ ctx.inject(deps, (scope) => {
28
+ const src = scope && pick(scope)
29
+ if (src === undefined) return
30
+ if (typeof src.bind === 'function') scopeOf = (ns) => src.bind({ namespace: ns })
31
+ else if (typeof src.get === 'function') scopeOf = (ns) => src.get(ns)
32
+ })
33
+ } catch (_err) {}
34
+ }
35
+ tryInject(['settingsScope'], (s) => s.settingsScope)
36
+ tryInject(['configForms'], (s) => s.configForms)
37
+ }
38
+
21
39
  /*
22
40
  * DeepSeek list prices in CNY per 1M tokens (api-docs.deepseek.com,
23
41
  * 2026-11). Peak hours are Beijing time Mon–Fri 09:00–12:00 and
@@ -206,11 +224,29 @@ window.__ModuleLoader__.load({
206
224
  dockEdit: '编辑',
207
225
  dockOpenFull: '打开完整进度板',
208
226
  dockAllDone: '全部完成',
209
- llmTitle: '进度辅助 LLM(审查/监视)',
227
+ llmTitle: '进度辅助 LLM(审查/槽位/轮次)',
210
228
  llmOn: '已启用',
211
- llmOff: '未启用:观察者为规则版(零 LLM 费用)。启用后由辅助模型按最近输出/动作校准 current/next/percent。',
229
+ llmOff: '未启用:观察者为规则版(零 LLM 费用)。启用后由辅助模型管理任务槽位、产出续轮建议。',
212
230
  llmAuto: ',自动落地',
213
- llmHint: '建议直连本地/局域网 OpenAI 兼容端点(Ollama、LM Studio、自建 llama.cpp、vLLM、SGLang、Strata、Ninfer 等):profile 里配 assistant.mode: direct + baseUrl + model。仅滞后时触发,每回合至多一次,只改 current/next/percent。',
231
+ llmHint: '选「已注册」复用 Settings→模型里的 provider/model(走宿主,免密钥);或「直连」自建 OpenAI 兼容端点。仅滞后时触发,每回合至多一次。助手可增删改槽位并产出轮次草案(仅供参考),判断权归主模型。',
232
+ llmMode: '模式',
233
+ llmModeOff: '关闭',
234
+ llmModeRegistered: '已注册 provider',
235
+ llmModeDirect: '直连端点',
236
+ llmProvider: '提供方',
237
+ llmModel: '模型',
238
+ llmBaseUrl: '端点地址',
239
+ llmApiKey: 'API 密钥',
240
+ llmAuthority: '权限',
241
+ llmAuthoritySlots: '管理槽位',
242
+ llmAuthorityRounds: '轮次草案',
243
+ llmAuthorityBoth: '两者',
244
+ llmPickModel: '选择模型…',
245
+ llmNoProviders: 'Settings→模型 里没有已配置的 provider/model',
246
+ llmSave: '保存',
247
+ llmSaved: '已保存',
248
+ llmSaveFail: '保存失败',
249
+ llmResult: '结果',
214
250
  etaLeft: '预计剩',
215
251
  etaOver: '已超预估',
216
252
  staleTag: '中断',
@@ -316,11 +352,29 @@ window.__ModuleLoader__.load({
316
352
  dockEdit: 'Edit',
317
353
  dockOpenFull: 'Open full board',
318
354
  dockAllDone: 'All done',
319
- llmTitle: 'Progress assistant LLM (audit/watch)',
355
+ llmTitle: 'Progress assistant LLM (audit/slots/rounds)',
320
356
  llmOn: 'Enabled',
321
- llmOff: 'Disabled: the observer is rule-based (zero LLM cost). When enabled, an auxiliary model recalibrates current/next/percent from recent output/actions.',
357
+ llmOff: 'Disabled: the observer is rule-based (zero LLM cost). When enabled, the assistant manages task slots and produces round suggestions.',
322
358
  llmAuto: ', auto-applied',
323
- llmHint: 'Prefer a local/LAN self-hosted OpenAI-compatible endpoint (Ollama, LM Studio, self-hosted llama.cpp, vLLM, SGLang, Strata, Ninfer, …): set assistant.mode: direct + baseUrl + model in the profile. Triggered only while overdue, at most once per turn, and only current/next/percent are changed.',
359
+ llmHint: 'Use "Registered" to reuse a provider/model from Settings → Models (via host, no API key needed), or "Direct" for a self-hosted OpenAI-compatible endpoint. Triggered only while overdue, at most once per turn. The assistant may add/edit/remove slots and emit round suggestions (advice only); the main model decides.',
360
+ llmMode: 'Mode',
361
+ llmModeOff: 'Off',
362
+ llmModeRegistered: 'Registered provider',
363
+ llmModeDirect: 'Direct endpoint',
364
+ llmProvider: 'Provider',
365
+ llmModel: 'Model',
366
+ llmBaseUrl: 'Endpoint URL',
367
+ llmApiKey: 'API key',
368
+ llmAuthority: 'Authority',
369
+ llmAuthoritySlots: 'Manage slots',
370
+ llmAuthorityRounds: 'Round draft',
371
+ llmAuthorityBoth: 'Both',
372
+ llmPickModel: 'Pick a model…',
373
+ llmNoProviders: 'No configured provider/model under Settings → Models',
374
+ llmSave: 'Save',
375
+ llmSaved: 'Saved',
376
+ llmSaveFail: 'Save failed',
377
+ llmResult: 'Result',
324
378
  etaLeft: '~',
325
379
  etaOver: 'over by',
326
380
  staleTag: 'idle',
@@ -510,6 +564,10 @@ window.__ModuleLoader__.load({
510
564
  .pb-llm-title { font-size: 12px; font-weight: 650; }
511
565
  .pb-llm-line { margin-top: 4px; font-size: 12px; line-height: 1.5; }
512
566
  .pb-llm-hint { margin-top: 4px; font-size: 11px; line-height: 1.5; opacity: .75; }
567
+ .pb-llm-editor { margin-top: 8px; padding-top: 8px; border-top: 1px solid rgba(217,119,6,.25); display: grid; gap: 6px; }
568
+ .pb-llm-field { display: flex; align-items: center; gap: 8px; font-size: 11px; }
569
+ .pb-llm-field > span { flex: 0 0 72px; opacity: .8; }
570
+ .pb-llm-field select, .pb-llm-field input { flex: 1; min-width: 0; padding: 3px 6px; font-size: 11px; border: 1px solid rgba(128,128,128,.4); border-radius: 4px; background: transparent; color: inherit; }
513
571
  .pb-header-btn {
514
572
  display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px;
515
573
  border: 1px solid transparent; border-radius: 6px; background: transparent;
@@ -1433,20 +1491,102 @@ window.__ModuleLoader__.load({
1433
1491
  function LlmAssistNotice(props) {
1434
1492
  const t = makeT(props)
1435
1493
  const a = props.assistant
1494
+ const cfg = props.assistantCfg
1495
+ const [open, setOpen] = useState(false)
1496
+ const [mode, setMode] = useState((a && a.mode) || '')
1497
+ const [provider, setProvider] = useState((a && a.provider) || '')
1498
+ const [model, setModel] = useState((a && a.model) || '')
1499
+ const [baseUrl, setBaseUrl] = useState((a && a.baseUrl) || '')
1500
+ const [apiKey, setApiKey] = useState('')
1501
+ const [authority, setAuthority] = useState((a && a.authority) || 'both')
1502
+ const [status, setStatus] = useState('')
1436
1503
  if (!a) return null
1437
1504
  const on = a.enabled === true
1505
+ const providers = cfg && cfg.available ? cfg.providers() : []
1506
+ const selectedProvider = providers.find((p) => p.name === provider)
1507
+ const models = selectedProvider ? selectedProvider.models : []
1508
+
1509
+ const save = async () => {
1510
+ if (!cfg || !cfg.available) { setStatus(t('llmSaveFail')); return }
1511
+ const patch = { mode, provider, model, baseUrl, authority, apiKey }
1512
+ try {
1513
+ await cfg.save(patch)
1514
+ setStatus(t('llmSaved'))
1515
+ if (apiKey) setApiKey('')
1516
+ } catch (_err) {
1517
+ setStatus(t('llmSaveFail'))
1518
+ }
1519
+ }
1520
+
1521
+ const select = (label, value, onChange, options) =>
1522
+ h(
1523
+ 'label',
1524
+ { className: 'pb-llm-field' },
1525
+ h('span', null, label),
1526
+ h(
1527
+ 'select',
1528
+ { value, onChange: (e) => onChange(e.target.value) },
1529
+ options.map((opt) => h('option', { key: opt.value, value: opt.value }, opt.label)),
1530
+ ),
1531
+ )
1532
+
1533
+ const line = on
1534
+ ? (a.mode === 'registered'
1535
+ ? `${t('llmOn')}:${a.provider} · ${a.model}(≤${Math.max(1, Math.round((a.minIntervalMs || 0) / 60000))} min/次${a.autoApply ? t('llmAuto') : ''})`
1536
+ : `${t('llmOn')}:${a.baseUrl} · ${a.model}(≤${Math.max(1, Math.round((a.minIntervalMs || 0) / 60000))} min/次${a.autoApply ? t('llmAuto') : ''})`)
1537
+ : t('llmOff')
1538
+
1438
1539
  return h(
1439
1540
  'div',
1440
1541
  { className: on ? 'pb-llm' : 'pb-llm pb-llm-off' },
1441
1542
  h('div', { className: 'pb-llm-title' }, t('llmTitle')),
1442
- h(
1443
- 'div',
1444
- { className: 'pb-llm-line' },
1445
- on
1446
- ? `${t('llmOn')}:${a.baseUrl} · ${a.model}(≤${Math.max(1, Math.round((a.minIntervalMs || 0) / 60000))} min/次${a.autoApply ? t('llmAuto') : ''})`
1447
- : t('llmOff'),
1448
- ),
1543
+ h('div', { className: 'pb-llm-line' }, line),
1449
1544
  h('div', { className: 'pb-llm-hint' }, t('llmHint')),
1545
+ h('button', { type: 'button', className: 'pb-side-link', style: { marginTop: '4px' }, onClick: () => setOpen((v) => !v) }, open ? '▾' : '▸'),
1546
+ open
1547
+ ? h(
1548
+ 'div',
1549
+ { className: 'pb-llm-editor' },
1550
+ select(t('llmMode'), mode, setMode, [
1551
+ { value: '', label: t('llmModeOff') },
1552
+ { value: 'registered', label: t('llmModeRegistered') },
1553
+ { value: 'direct', label: t('llmModeDirect') },
1554
+ ]),
1555
+ mode === 'registered'
1556
+ ? h(
1557
+ 'div',
1558
+ null,
1559
+ providers.length === 0
1560
+ ? h('div', { className: 'pb-llm-hint' }, t('llmNoProviders'))
1561
+ : select(t('llmProvider'), provider, (v) => { setProvider(v); setModel('') }, [
1562
+ { value: '', label: t('llmPickModel') },
1563
+ ...providers.map((p) => ({ value: p.name, label: p.name })),
1564
+ ]),
1565
+ models.length > 0
1566
+ ? select(t('llmModel'), model, setModel, [
1567
+ { value: '', label: t('llmPickModel') },
1568
+ ...models.map((m) => ({ value: m, label: m })),
1569
+ ])
1570
+ : null,
1571
+ )
1572
+ : mode === 'direct'
1573
+ ? h(
1574
+ 'div',
1575
+ null,
1576
+ h('label', { className: 'pb-llm-field' }, h('span', null, t('llmBaseUrl')), h('input', { type: 'text', value: baseUrl, onChange: (e) => setBaseUrl(e.target.value) })),
1577
+ h('label', { className: 'pb-llm-field' }, h('span', null, t('llmModel')), h('input', { type: 'text', value: model, onChange: (e) => setModel(e.target.value) })),
1578
+ h('label', { className: 'pb-llm-field' }, h('span', null, t('llmApiKey')), h('input', { type: 'password', value: apiKey, placeholder: a.hasApiKey ? '••••••' : '', onChange: (e) => setApiKey(e.target.value) })),
1579
+ )
1580
+ : null,
1581
+ select(t('llmAuthority'), authority, setAuthority, [
1582
+ { value: 'both', label: t('llmAuthorityBoth') },
1583
+ { value: 'slots', label: t('llmAuthoritySlots') },
1584
+ { value: 'rounds', label: t('llmAuthorityRounds') },
1585
+ ]),
1586
+ h('button', { type: 'button', className: 'pb-btn pb-btn-primary', style: { marginTop: '6px' }, onClick: () => void save() }, t('llmSave')),
1587
+ status ? h('span', { className: 'pb-llm-hint', style: { marginLeft: '8px' } }, status) : null,
1588
+ )
1589
+ : null,
1450
1590
  )
1451
1591
  }
1452
1592
 
@@ -1603,7 +1743,7 @@ window.__ModuleLoader__.load({
1603
1743
  ),
1604
1744
  ),
1605
1745
  readError ? h('div', { className: 'pb-side-error' }, `${t('readError')}${readError}`) : null,
1606
- h(LlmAssistNotice, { assistant: snapshot?.assistant, t: props.t }),
1746
+ h(LlmAssistNotice, { assistant: snapshot?.assistant, t: props.t, assistantCfg: props.assistantCfg }),
1607
1747
  actionError ? h('div', { className: 'pb-side-error' }, `${t('saveError')}${actionError}`) : null,
1608
1748
  usageView
1609
1749
  ? h(
@@ -2023,7 +2163,7 @@ window.__ModuleLoader__.load({
2023
2163
  ),
2024
2164
  ),
2025
2165
  ),
2026
- h(LlmAssistNotice, { assistant: snapshot?.assistant, t: props.t }),
2166
+ h(LlmAssistNotice, { assistant: snapshot?.assistant, t: props.t, assistantCfg: props.assistantCfg }),
2027
2167
  snapshot?.enabled === false
2028
2168
  ? h(
2029
2169
  'div',
@@ -2161,6 +2301,7 @@ window.__ModuleLoader__.load({
2161
2301
  return {
2162
2302
  inject: ['slots', 'locale', 'layout', 'sidebarRight', 'sidebarRightTabs', 'sessions'],
2163
2303
  apply(ctx) {
2304
+ installSettingsScope(ctx)
2164
2305
  ctx.effect(
2165
2306
  () =>
2166
2307
  ctx.locale.register(NS, {
@@ -2171,6 +2312,46 @@ window.__ModuleLoader__.load({
2171
2312
  )
2172
2313
 
2173
2314
  const t = ctx.locale.bind(NS)
2315
+ // 辅助 LLM 配置读写面:面板用它在 settings 里改 assistant(运行时生效,无需重启)。
2316
+ const assistantCfg = {
2317
+ available: () => Boolean(scopeOf),
2318
+ // llm-pi-ai 里的 provider/model 列表(供下拉)
2319
+ providers() {
2320
+ if (!scopeOf) return []
2321
+ try {
2322
+ const scope = scopeOf('llm-pi-ai')
2323
+ const snap = scope && typeof scope.getSnapshot === 'function' ? scope.getSnapshot() : null
2324
+ const value = snap && (snap.value !== undefined ? snap.value : snap)
2325
+ const providers = value && Array.isArray(value.providers) ? value.providers : []
2326
+ return providers.map((p) => ({
2327
+ name: String(p && (p.name || p.id || p.provider) || ''),
2328
+ models: Array.isArray(p && p.models)
2329
+ ? p.models.map((m) => String((m && (m.id || m.name)) || '')).filter(Boolean)
2330
+ : [],
2331
+ })).filter((p) => p.name)
2332
+ } catch (_err) {
2333
+ return []
2334
+ }
2335
+ },
2336
+ // progress-union settings 里当前的 assistant 配置
2337
+ current() {
2338
+ if (!scopeOf) return null
2339
+ try {
2340
+ const scope = scopeOf('progress-union')
2341
+ const snap = scope && typeof scope.getSnapshot === 'function' ? scope.getSnapshot() : null
2342
+ const value = snap && (snap.value !== undefined ? snap.value : snap)
2343
+ return value && typeof value === 'object' && value.assistant ? value.assistant : null
2344
+ } catch (_err) {
2345
+ return null
2346
+ }
2347
+ },
2348
+ async save(patch) {
2349
+ if (!scopeOf) throw new Error('settings unavailable')
2350
+ const scope = scopeOf('progress-union')
2351
+ if (!scope || typeof scope.set !== 'function') throw new Error('scope.set unavailable')
2352
+ await scope.set('assistant', patch)
2353
+ },
2354
+ }
2174
2355
  const wakeAgent = (sessionId, text) => {
2175
2356
  try {
2176
2357
  const binding = ctx.sessions.binding(sessionId)
@@ -2267,6 +2448,7 @@ window.__ModuleLoader__.load({
2267
2448
  openFullPanel,
2268
2449
  wakeAgent,
2269
2450
  usage: usageApi,
2451
+ assistantCfg,
2270
2452
  }),
2271
2453
  },
2272
2454
  ProgressSidePanel,
@@ -2283,7 +2465,7 @@ window.__ModuleLoader__.load({
2283
2465
  name: 'main',
2284
2466
  key: PANEL_ID,
2285
2467
  locale: NS,
2286
- inject: () => ({ wakeAgent, usage: usageApi }),
2468
+ inject: () => ({ wakeAgent, usage: usageApi, assistantCfg }),
2287
2469
  },
2288
2470
  ProgressPanel,
2289
2471
  ),
package/dsh.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-progress-union",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "main": "./index.js",
5
5
  "description": "进度结合原型:board 槽位真相源(用户可编辑、diff+ack 增量同步、staleness nudge)× 鲸程时间引擎(step 计数、ETA 三档 board>todo>local>prior、悬浮迷你条),并向压缩插件暴露只读三层进度锚点 progressAnchor(board 语义锚 + time 时间锚 + userEdits 未确认改动,service 与 HTTP 双平面)。",
6
6
  "engines": {
package/index.js CHANGED
@@ -94,12 +94,21 @@ progress_update 维护用户可见的实时进度板。每项含 title/status/pe
94
94
  其余采用可逆默认并标注假设;只有答案会显著改变路径、且至少两个维度各有三种合理解读时才问。
95
95
  输入/约束澄清最晚约 50%,任何澄清不拖到中后段。每任务最多 2 轮、每轮最多 3 问;选项化、给推荐默认、先复述理解。问前把相关任务标 blocked 并写清等什么。`
96
96
 
97
- // 辅助 LLM(审查/监视)的 system prompt:只允许"描述现状 + 校准百分比",禁止增删/改状态。
98
- const ASSISTANT_SYSTEM = 'You are a progress auditor for a task board. Given the board checklist and the recent assistant output / tool activity / file changes, ' +
99
- 'update ONLY per-item current/next/percent so the board matches reality. ' +
100
- 'Never add, remove, retitle, or change the status of an item. ' +
101
- 'Output strictly one JSON object: {"changes":[{"id":"<existing id>","current"?:"...","next"?:"...","percent"?:0-100}],"note":"<one line audit verdict>"}. ' +
102
- 'If nothing needs updating, output {"changes":[],"note":"<why>"}.'
97
+ // 辅助 LLM(审查/监视 + 槽位管理 + 轮次草案)的 system prompt。
98
+ // 事实进输入、判断不进输入:助手可改槽位/产轮次草案,但判断权归主模型。
99
+ const ASSISTANT_SYSTEM = 'You are a progress assistant for a task board in a long-running goal session. ' +
100
+ 'Given the board checklist and recent assistant output / tool activity / file changes, produce two things: ' +
101
+ '(1) board slot changes that make the board match reality (you MAY add, edit, or remove items); ' +
102
+ '(2) a ROUND suggestion stating whether work should continue, is complete, or is blocked, with evidence. ' +
103
+ 'Your round suggestion is ADVICE only — the main model decides; never claim the goal is done yourself. ' +
104
+ 'Output strictly ONE JSON object with this shape: ' +
105
+ '{"board":{"changes":[{"id":"<existing id for edit/remove, omit for add>","kind":"add|edit|remove","title"?:string,"status"?:"todo|doing|done|blocked","percent"?:0-100,"current"?:string,"next"?:string,"note"?:string}]},' +
106
+ '"round":{"status":"continue|complete|blocked","summary":string,"evidence":string[],"nextSteps":string[],"blocker":string},"note":"<one line verdict>"}. ' +
107
+ 'Use "add" with a title to create items; "edit" with an id to update; "remove" with an id to delete. ' +
108
+ 'For "complete" you MUST list concrete evidence and the board should already be all done. ' +
109
+ 'For "blocked" you MUST give a concrete blocker string. ' +
110
+ 'Emit at most 8 changes. If nothing needs changing, use {"board":{"changes":[]},"round":{...},"note":"..."}. ' +
111
+ 'Respond with the JSON object only — no prose, no code fences.'
103
112
 
104
113
  // ============================================================================
105
114
  // 通用工具(board fork)
@@ -1071,6 +1080,134 @@ export async function apply(ctx, config) {
1071
1080
  return parts.join('\n')
1072
1081
  }
1073
1082
 
1083
+ // —— 续轮驱动器(重试):idle → followup 带自有 source 的 <progress_goal_round> ——
1084
+ // 每 agent 一个 attempt 状态:queued/claimed/cancelled + 串行 FIFO;官方 driver 的轻量版。
1085
+ const goalDrives = new WeakMap() // agent -> {attempt, requested, run, stopping}
1086
+
1087
+ function driveStateFor(agent) {
1088
+ let s = goalDrives.get(agent)
1089
+ if (!s) {
1090
+ s = { attempt: undefined, requested: false, run: undefined, stopping: false }
1091
+ goalDrives.set(agent, s)
1092
+ }
1093
+ return s
1094
+ }
1095
+
1096
+ function sameGoalSource(message, attempt) {
1097
+ if (!attempt || !message || !message.source) return false
1098
+ const src = message.source
1099
+ return src.kind === GOAL_SOURCE_KIND && src.goalId === attempt.goalId && src.revision === attempt.revision && src.round === attempt.round
1100
+ }
1101
+
1102
+ function isGoalRoundMessage(message) {
1103
+ return Boolean(message && message.source && message.source.kind === GOAL_SOURCE_KIND && message.source.round > 0)
1104
+ }
1105
+
1106
+ // 构造 followup 消息的 content,把板清单与助手轮次草案(若有)拼进去。
1107
+ function renderGoalRoundContent(sessionId, round, view) {
1108
+ const state = states.get(sessionId)
1109
+ const checklist = state ? renderChecklist(state, cfg.observer.maxItems).join('\n') : '(空板)'
1110
+ const parts = [
1111
+ `${GOAL_TAG}`,
1112
+ `Objective: ${JSON.stringify(view.objective)}`,
1113
+ `Round: ${round}/${view.maxRounds}`,
1114
+ '',
1115
+ '<progress-board-snapshot>',
1116
+ checklist,
1117
+ '</progress-board-snapshot>',
1118
+ ]
1119
+ if (oRoundDraftOf(sessionId)) parts.push('', `助手建议:${oRoundDraftOf(sessionId)}`)
1120
+ parts.push(
1121
+ '',
1122
+ '继续在**同一会话**朝目标推进:以当前工作区、工具结果与持久化状态为准,先核对进度板再行动;做出实质进展并验证。',
1123
+ '若要收尾,先确保进度板全部完成,再调用 progress_goal_report 报 status=complete 并给出 evidence。若受阻,报 status=blocked 并写清 blocker。否则报 status=continue,本目标会自动进入下一轮。',
1124
+ '每轮至少用 progress_update 同步一次进度板(无变化传 changes=[])。',
1125
+ `${GOAL_TAG}`,
1126
+ )
1127
+ return [{ type: 'text', text: parts.join('\n') }]
1128
+ }
1129
+
1130
+ // 助手轮次草案:存在 observers 上,由 Phase3 的辅助 LLM 写入;这里只读。
1131
+ function oRoundDraftOf(sid) {
1132
+ const o = observers.get(sid)
1133
+ return o && typeof o.roundDraft === 'string' && o.roundDraft ? o.roundDraft.slice(0, 400) : ''
1134
+ }
1135
+
1136
+ async function driveGoal(state) {
1137
+ const { agent } = state
1138
+ const sessionId = String(agent.session?.id ?? agent.id)
1139
+ const current = ensureState(sessionId)
1140
+ const g = current.goal
1141
+ // 让路:官方目标 active 时不排队
1142
+ try {
1143
+ const official = ctx.get('goals')?.get?.(agent)
1144
+ if (official && official.phase === 'active' && official.activation === 'armed') return
1145
+ } catch (_err) {}
1146
+ if (g.phase !== 'active' || g.activation !== 'armed') return
1147
+ if (g.roundsStarted >= g.maxRounds) {
1148
+ g.phase = 'blocked'
1149
+ g.activation = 'disarmed'
1150
+ g.blockedReason = `达到预算上限 ${g.maxRounds} 轮`
1151
+ g.blockedStreak = 1
1152
+ g.currentRound = 0
1153
+ await saveGoal(sessionId)
1154
+ return
1155
+ }
1156
+ const round = g.roundsStarted + 1
1157
+ const revision = current.revision
1158
+ const content = renderGoalRoundContent(sessionId, round, goalView(sessionId))
1159
+ const message = {
1160
+ id: `pg-${now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
1161
+ role: 'user',
1162
+ content,
1163
+ source: { kind: GOAL_SOURCE_KIND, goalId: g.id, revision, round },
1164
+ }
1165
+ // 声称本轮:写 currentRound + roundsStarted,避免重复派发
1166
+ g.currentRound = round
1167
+ g.roundsStarted = round
1168
+ await saveGoal(sessionId)
1169
+ state.attempt = { goalId: g.id, revision, round, messageId: message.id, phase: 'queued', stale: false }
1170
+ try {
1171
+ if (typeof agent.followup !== 'function') throw new Error('agent.followup unavailable')
1172
+ agent.followup(message)
1173
+ } catch (err) {
1174
+ state.attempt = undefined
1175
+ g.phase = 'blocked'
1176
+ g.activation = 'disarmed'
1177
+ g.blockedReason = `续轮派发失败:${err instanceof Error ? err.message : String(err)}`
1178
+ await saveGoal(sessionId)
1179
+ }
1180
+ }
1181
+
1182
+ function requestGoalDrive(agent) {
1183
+ const state = driveStateFor(agent)
1184
+ if (state.stopping) return
1185
+ state.requested = true
1186
+ if (state.run !== undefined) return
1187
+ let run
1188
+ try {
1189
+ run = (async () => {
1190
+ while (state.requested && !state.stopping) {
1191
+ state.requested = false
1192
+ try {
1193
+ await driveGoal(state)
1194
+ } catch (_err) {
1195
+ // 单轮失败静默,不阻断后续
1196
+ }
1197
+ }
1198
+ })()
1199
+ } catch (_err) {
1200
+ state.run = undefined
1201
+ return
1202
+ }
1203
+ state.run = run
1204
+ const retire = () => {
1205
+ state.run = undefined
1206
+ if (state.requested && !state.stopping) requestGoalDrive(agent)
1207
+ }
1208
+ run.then(retire, retire)
1209
+ }
1210
+
1074
1211
  // ==========================================================================
1075
1212
  // B. 注入面(board 三块照板 + 鲸程文件上报协议收敛)
1076
1213
  // ==========================================================================
@@ -1231,11 +1368,18 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1231
1368
  void applyChanges({ sessionId: sid, changes: [{ id: doing.id, current: line }], origin: 'observer' }).catch(() => {})
1232
1369
  }
1233
1370
 
1234
- // —— 辅助 LLM(审查/监视):命题 → 校验 → 落地(只动 current/next/percent)——
1371
+ // —— 辅助 LLM:registered(宿主 llm.stream) / direct(自建端点),默认关 ——
1235
1372
  function assistantReady() {
1236
- return cfg.assistant.mode === 'direct'
1237
- && String(cfg.assistant.baseUrl || '').trim() !== ''
1238
- && String(cfg.assistant.model || '').trim() !== ''
1373
+ const a = liveAssistant()
1374
+ if (a.mode === 'registered') {
1375
+ return Boolean(llm && typeof llm.stream === 'function')
1376
+ && String(a.provider || '').trim() !== ''
1377
+ && String(a.model || '').trim() !== ''
1378
+ }
1379
+ if (a.mode === 'direct') {
1380
+ return String(a.baseUrl || '').trim() !== '' && String(a.model || '').trim() !== ''
1381
+ }
1382
+ return false
1239
1383
  }
1240
1384
 
1241
1385
  // 从模型回复里抠出唯一 JSON 对象(容忍 ```json 围栏与前后废话)。
@@ -1256,12 +1400,66 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1256
1400
  * 板滞后(或模型久未同步)时问一次辅助模型。失败静默(记 assistantError),
1257
1401
  * 绝不阻断主流程;每回合至多 maxCallsPerTurn 次、两次至少间隔 minIntervalMs。
1258
1402
  */
1403
+ // 把助手 proposal 的 board.changes 校验+落地。护栏:≤maxSlotChanges、用户改动优先(先 ack)。
1404
+ function applyAssistantSlotChanges(state, sid, proposal, a) {
1405
+ const board = isObject(proposal.board) ? proposal.board : {}
1406
+ const rawChanges = Array.isArray(board.changes) ? board.changes : []
1407
+ if (rawChanges.length === 0) return { count: 0, ackUserRevision: undefined }
1408
+ const byId = new Map(state.items.map((item) => [item.id, item]))
1409
+ const changes = []
1410
+ // 用户未确认的改动优先:本次先 ack,助手不得覆盖它们。
1411
+ const ackUserRevision = state.userRevision > state.agentSeenRevision ? state.userRevision : undefined
1412
+ for (const candidate of rawChanges.slice(0, Math.max(1, Number(a.maxSlotChanges) || 8))) {
1413
+ if (!isObject(candidate)) continue
1414
+ const kind = String(candidate.kind || (candidate.id ? 'edit' : 'add'))
1415
+ if (kind === 'add') {
1416
+ const title = text(candidate.title, MAX_TITLE)
1417
+ if (!title) continue
1418
+ const patch = { title }
1419
+ if (STATUSES.has(candidate.status)) patch.status = candidate.status
1420
+ if (typeof candidate.percent === 'number' && Number.isFinite(candidate.percent)) patch.percent = Math.max(0, Math.min(100, Math.round(candidate.percent)))
1421
+ if (typeof candidate.current === 'string') patch.current = text(candidate.current, MAX_TEXT) || ''
1422
+ if (typeof candidate.next === 'string') patch.next = text(candidate.next, MAX_TEXT) || ''
1423
+ if (typeof candidate.note === 'string') patch.note = text(candidate.note, MAX_NOTE) || ''
1424
+ changes.push(patch)
1425
+ } else if (kind === 'remove') {
1426
+ const target = byId.get(String(candidate.id || ''))
1427
+ if (target) changes.push({ id: target.id, remove: true })
1428
+ } else if (kind === 'edit') {
1429
+ const target = byId.get(String(candidate.id || ''))
1430
+ if (!target) continue
1431
+ const patch = { id: target.id }
1432
+ if (STATUSES.has(candidate.status)) patch.status = candidate.status
1433
+ if (typeof candidate.percent === 'number' && Number.isFinite(candidate.percent)) patch.percent = Math.max(0, Math.min(100, Math.round(candidate.percent)))
1434
+ for (const field of ['current', 'next', 'note']) {
1435
+ if (typeof candidate[field] === 'string') patch[field] = text(candidate[field], field === 'note' ? MAX_NOTE : MAX_TEXT) || ''
1436
+ }
1437
+ if (Object.keys(patch).length > 1) changes.push(patch)
1438
+ }
1439
+ }
1440
+ return { count: changes.length, changes, ackUserRevision }
1441
+ }
1442
+
1443
+ function applyAssistantRoundDraft(sid, proposal, a) {
1444
+ if (a.authority !== 'rounds' && a.authority !== 'both') return
1445
+ const round = isObject(proposal.round) ? proposal.round : {}
1446
+ const status = ['continue', 'complete', 'blocked'].includes(String(round.status)) ? String(round.status) : 'continue'
1447
+ const bits = [`建议状态:${status}`]
1448
+ if (typeof round.summary === 'string' && round.summary.trim()) bits.push(`摘要:${text(round.summary, 240)}`)
1449
+ if (Array.isArray(round.evidence) && round.evidence.length) bits.push(`证据:${round.evidence.slice(0, 4).map((e) => String(e).slice(0, 120)).join(';')}`)
1450
+ if (Array.isArray(round.nextSteps) && round.nextSteps.length) bits.push(`下一步:${round.nextSteps.slice(0, 4).map((e) => String(e).slice(0, 120)).join(';')}`)
1451
+ if (status === 'blocked' && typeof round.blocker === 'string' && round.blocker.trim()) bits.push(`阻塞:${text(round.blocker, 240)}`)
1452
+ const o = obsOf(sid)
1453
+ o.roundDraft = bits.join(' · ').slice(0, 400)
1454
+ }
1455
+
1259
1456
  async function maybeAskAssistant(sid, at) {
1457
+ const a = liveAssistant()
1260
1458
  if (!assistantReady() || !boardHasWork(sid)) return
1261
1459
  const o = obsOf(sid)
1262
1460
  if (!modelIsLate(sid, at) && o.stepsSinceBoard < cfg.observer.maxIdleSteps) return
1263
- if (at - o.lastAssistantAt < cfg.assistant.minIntervalMs) return
1264
- if (o.assistantCalls >= cfg.assistant.maxCallsPerTurn) return
1461
+ if (at - o.lastAssistantAt < Number(a.minIntervalMs || 0)) return
1462
+ if (o.assistantCalls >= Number(a.maxCallsPerTurn || 1)) return
1265
1463
  const state = states.get(sid)
1266
1464
  if (!state) return
1267
1465
  o.assistantCalls += 1
@@ -1269,56 +1467,59 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1269
1467
  const lastOutput = o.outputs[o.outputs.length - 1]
1270
1468
  const files = Array.isArray(o.files) ? o.files.slice(-4).map((f) => f.path) : []
1271
1469
  const lines = [
1470
+ `目标:${state.goal && state.goal.phase === 'active' ? JSON.stringify(state.goal.objective) : '(无)'}`,
1272
1471
  ...renderChecklist(state, cfg.observer.maxItems),
1273
1472
  lastOutput ? `最近输出:${lastOutput.text}` : '最近输出:—',
1274
1473
  o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
1275
1474
  files.length ? `最近改动:${files.join(' · ')}` : '最近改动:—',
1276
1475
  ]
1277
1476
  const controller = new AbortController()
1278
- const timer = setTimeout(() => controller.abort(), Math.max(2000, Number(cfg.assistant.timeoutMs) || 20000))
1477
+ const timer = setTimeout(() => controller.abort(), Math.max(2000, Number(a.timeoutMs) || 20000))
1279
1478
  try {
1280
- const base = String(cfg.assistant.baseUrl || '').replace(/\/+$/, '')
1281
- const response = await fetch(`${base}/chat/completions`, {
1282
- method: 'POST',
1283
- headers: {
1284
- 'content-type': 'application/json',
1285
- ...(String(cfg.assistant.apiKey || '') !== '' ? { authorization: `Bearer ${cfg.assistant.apiKey}` } : {}),
1286
- },
1287
- body: JSON.stringify({
1288
- model: cfg.assistant.model,
1289
- temperature: 0,
1290
- max_tokens: 300,
1291
- messages: [
1292
- { role: 'system', content: ASSISTANT_SYSTEM },
1293
- { role: 'user', content: lines.join('\n') },
1294
- ],
1295
- }),
1296
- signal: controller.signal,
1297
- })
1298
- if (!response.ok) throw new Error(`HTTP ${response.status}`)
1299
- const body = await response.json()
1300
- const proposal = parseProposal(body?.choices?.[0]?.message?.content ?? '')
1479
+ let raw = ''
1480
+ if (a.mode === 'registered') {
1481
+ // 宿主 llm.stream:把 chunk 拼成正文(兼容 content/text 字段与 delta 形态)。
1482
+ const stream = llm.stream({
1483
+ provider: String(a.provider),
1484
+ model: String(a.model),
1485
+ messages: [{ role: 'system', content: ASSISTANT_SYSTEM }, { role: 'user', content: lines.join('\n') }],
1486
+ })
1487
+ for await (const chunk of stream) {
1488
+ if (chunk && typeof chunk.content === 'string') raw += chunk.content
1489
+ else if (chunk && typeof chunk.text === 'string') raw += chunk.text
1490
+ else if (chunk && chunk.delta && typeof chunk.delta === 'string') raw += chunk.delta
1491
+ if (controller.signal.aborted) break
1492
+ }
1493
+ } else {
1494
+ const base = String(a.baseUrl || '').replace(/\/+$/, '')
1495
+ const response = await fetch(`${base}/chat/completions`, {
1496
+ method: 'POST',
1497
+ headers: {
1498
+ 'content-type': 'application/json',
1499
+ ...(String(a.apiKey || '') !== '' ? { authorization: `Bearer ${a.apiKey}` } : {}),
1500
+ },
1501
+ body: JSON.stringify({
1502
+ model: a.model,
1503
+ temperature: 0,
1504
+ max_tokens: 600,
1505
+ messages: [{ role: 'system', content: ASSISTANT_SYSTEM }, { role: 'user', content: lines.join('\n') }],
1506
+ }),
1507
+ signal: controller.signal,
1508
+ })
1509
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
1510
+ const body = await response.json()
1511
+ raw = String(body?.choices?.[0]?.message?.content ?? '')
1512
+ }
1513
+ const proposal = parseProposal(raw)
1301
1514
  if (!proposal) throw new Error('proposal-unparsable')
1302
1515
  o.assistantError = ''
1303
1516
  o.assistantNote = String(proposal.note || '').slice(0, 200)
1304
- if (cfg.assistant.autoApply !== false && Array.isArray(proposal.changes) && proposal.changes.length > 0) {
1305
- const byId = new Map(state.items.map((item) => [item.id, item]))
1306
- const changes = []
1307
- for (const candidate of proposal.changes.slice(0, 10)) {
1308
- if (!isObject(candidate)) continue
1309
- const target = byId.get(String(candidate.id || ''))
1310
- if (!target) continue
1311
- const patch = { id: target.id }
1312
- if (typeof candidate.current === 'string') patch.current = candidate.current
1313
- if (typeof candidate.next === 'string') patch.next = candidate.next
1314
- if (typeof candidate.percent === 'number' && Number.isFinite(candidate.percent)) {
1315
- patch.percent = Math.max(0, Math.min(100, Math.round(candidate.percent)))
1316
- }
1317
- if (Object.keys(patch).length > 1) changes.push(patch)
1318
- }
1319
- if (changes.length > 0) {
1320
- await applyChanges({ sessionId: sid, changes, origin: 'assistant' })
1321
- }
1517
+ // 轮次草案:写进 observers,供下一次 followup 的 <progress_goal_round> 拼入。
1518
+ applyAssistantRoundDraft(sid, proposal, a)
1519
+ // 槽位管理:护栏后落地,每项 updatedBy='assistant'(applyChanges 用 origin 保证)。
1520
+ if (a.autoApply !== false && (a.authority === 'slots' || a.authority === 'both')) {
1521
+ const g = applyAssistantSlotChanges(state, sid, proposal, a)
1522
+ if (g.count > 0) await applyChanges({ sessionId: sid, changes: g.changes, origin: 'assistant', ackUserRevision: g.ackUserRevision })
1322
1523
  }
1323
1524
  } catch (err) {
1324
1525
  o.assistantError = err instanceof Error ? err.message : String(err)
@@ -1380,6 +1581,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1380
1581
  lines.push(`⚠ 进度已滞后(${synced}${idleMin >= 1 ? ',' + idleMin + ' 分钟' : ''}):先调用 progress_update 同步再继续;无变化就传 changes=[]。观察者已用最近动作自动刷新 current(updatedBy=observer),但状态/百分比仍需你确认。`)
1381
1582
  }
1382
1583
  if (o.assistantNote) lines.push(`助手审查:${o.assistantNote}`)
1584
+ if (o.roundDraft) lines.push(`助手轮次草案(仅供参考):${o.roundDraft}`)
1383
1585
  if (o.assistantError) lines.push(`助手审查失败:${o.assistantError}(仅影响审查建议,不阻断主流程)`)
1384
1586
  return `<progress-observer revision="${state.revision}" synced="${synced}">\n${lines.join('\n')}\n</progress-observer>`
1385
1587
  }
@@ -1400,14 +1602,38 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1400
1602
  hookedAgents.add(agent)
1401
1603
  try {
1402
1604
  agent.ctx.on('agent/pre-step', async (payload, next) => {
1605
+ const sid = String(agent.session?.id ?? agent.id)
1606
+ const stepMessages = ((payload && payload.messages) || [])
1607
+
1608
+ // /progress-goal 身份栅栏:目标续轮消息必须精确匹配 attempt,否则拒绝本步。
1609
+ const goalRound = stepMessages.find((m) => isGoalRoundMessage(m))
1610
+ if (goalRound) {
1611
+ const ds = driveStateFor(agent)
1612
+ const attempt = ds.attempt
1613
+ const src = goalRound.source
1614
+ const current = states.get(sid)
1615
+ const g = current && current.goal
1616
+ const valid = Boolean(
1617
+ attempt && sameGoalSource(goalRound, attempt) && !attempt.stale &&
1618
+ g && g.id === src.goalId && g.phase === 'active' && g.activation === 'armed' &&
1619
+ src.round === g.roundsStarted && src.round === attempt.round
1620
+ )
1621
+ if (!valid) {
1622
+ if (attempt && attempt.goalId === src.goalId) { attempt.stale = true; ds.attempt = undefined }
1623
+ return { kind: 'reject' }
1624
+ }
1625
+ attempt.phase = 'claimed'
1626
+ }
1627
+
1403
1628
  const decision = await next()
1404
1629
  try {
1405
1630
  if (!cfg.protocolHint) return decision
1631
+ // /progress-goal 续轮消息绝不注入协议消息:避免重蹈 /goal 身份污染覆辙。
1632
+ if (stepMessages.some((m) => isGoalRoundMessage(m))) return decision
1406
1633
  // 单协议收敛:本会话板已启用 → 不再注入文件上报协议。
1407
- const sid = String(agent.session?.id ?? agent.id)
1408
1634
  if (isEnabled(sid)) return decision
1409
1635
  if (!decision || decision.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
1410
- const freshUser = ((payload && payload.messages) || []).find((m) => m && m.source && m.source.kind === 'user')
1636
+ const freshUser = stepMessages.find((m) => m && m.source && m.source.kind === 'user')
1411
1637
  if (!freshUser) return decision
1412
1638
  decision.messages.push({
1413
1639
  id: 'dpg-' + now().toString(36) + '-' + Math.random().toString(36).slice(2, 8),
@@ -1724,6 +1950,49 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1724
1950
  } catch (_err) {}
1725
1951
  for (const agent of agents?.list?.() ?? []) installAgentHook(agent)
1726
1952
 
1953
+ // /progress-goal:任何非本域的新消息进入 inbox 视为用户抢占 → 标记 attempt stale 并暂停目标。
1954
+ try {
1955
+ disposers.push(ctx.on('agent/inbox/inserted', ({ agent, message }) => {
1956
+ if (!agent) return
1957
+ const ds = driveStateFor(agent)
1958
+ const attempt = ds.attempt
1959
+ if (!attempt) return
1960
+ if (sameGoalSource(message, attempt)) return // 自己派发的轮次不算竞争
1961
+ const src = message && message.source
1962
+ if (src && src.kind === GOAL_SOURCE_KIND) return
1963
+ // 用户/他人的新消息 → 抢占:暂停目标,清 attempt(等用户下一次明确 resume 或继续)
1964
+ attempt.stale = true
1965
+ ds.attempt = undefined
1966
+ try {
1967
+ const sid = String(agent.session?.id ?? agent.id)
1968
+ const g = ensureState(sid).goal
1969
+ if (g.phase === 'active') {
1970
+ g.phase = 'paused'
1971
+ g.activation = 'disarmed'
1972
+ g.currentRound = 0
1973
+ void saveGoal(sid)
1974
+ }
1975
+ } catch (_err) {}
1976
+ }))
1977
+ disposers.push(ctx.on('agent/inbox/claimed', ({ agent, message }) => {
1978
+ if (!agent) return
1979
+ const attempt = driveStateFor(agent).attempt
1980
+ if (attempt && sameGoalSource(message, attempt)) attempt.phase = 'claimed'
1981
+ }))
1982
+ disposers.push(ctx.on('agent/inbox/discarded', ({ agent, message }) => {
1983
+ if (!agent) return
1984
+ const attempt = driveStateFor(agent).attempt
1985
+ if (attempt && sameGoalSource(message, attempt)) {
1986
+ attempt.stale = true
1987
+ driveStateFor(agent).attempt = undefined
1988
+ }
1989
+ }))
1990
+ disposers.push(ctx.on('agent/disposed', ({ agent }) => {
1991
+ const ds = goalDrives.get(agent)
1992
+ if (ds) ds.stopping = true
1993
+ }))
1994
+ } catch (_err) {}
1995
+
1727
1996
  disposers.push(ctx.on('session/event', (session, event) => {
1728
1997
  try {
1729
1998
  if (!event) return
@@ -1804,8 +2073,9 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1804
2073
  markLineage(task, session)
1805
2074
  const pendingText = userTextMap.get(sid) || ''
1806
2075
  task.open = true
1807
- // 辅助 LLM 的每回合配额:开新回合重置
2076
+ // 辅助 LLM 的每回合配额:开新回合重置(轮次草案不跨回合复用)
1808
2077
  obsOf(sid).assistantCalls = 0
2078
+ obsOf(sid).roundDraft = ''
1809
2079
  if (!task.active) {
1810
2080
  task.active = true
1811
2081
  task.startedAt = now()
@@ -1873,6 +2143,10 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1873
2143
  const task = taskMap.get(String(agent.id))
1874
2144
  if (task && task.active) task.lastActivityAt = now()
1875
2145
  }
2146
+ // /progress-goal 续轮:agent 空载时自动派发下一轮(用户主动消息会抢占 attempt 而停)。
2147
+ if (agent && st === 'idle') {
2148
+ requestGoalDrive(agent)
2149
+ }
1876
2150
  // idle 不直接结束任务:maintenance 阶段也报 idle,会误杀进行中任务;结束统一走 sweep。
1877
2151
  }))
1878
2152
  } catch (_err) {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-progress-union",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "进度结合原型:dsh-progress-board 槽位真相源 × 鲸程 widget 时间/ETA 引擎,另向压缩插件暴露只读三层进度锚点(service + HTTP 双平面)。基于 l3j3y3/dsh-progress-board (MIT) 与 uuhihj/task-progress-bar dsh-progress-widget (MIT)。",
6
6
  "license": "MIT",