dsh-progress-union 0.1.3 → 0.1.5

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.3",
3
+ "version": "0.1.5",
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)
@@ -1359,11 +1368,18 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1359
1368
  void applyChanges({ sessionId: sid, changes: [{ id: doing.id, current: line }], origin: 'observer' }).catch(() => {})
1360
1369
  }
1361
1370
 
1362
- // —— 辅助 LLM(审查/监视):命题 → 校验 → 落地(只动 current/next/percent)——
1371
+ // —— 辅助 LLM:registered(宿主 llm.stream) / direct(自建端点),默认关 ——
1363
1372
  function assistantReady() {
1364
- return cfg.assistant.mode === 'direct'
1365
- && String(cfg.assistant.baseUrl || '').trim() !== ''
1366
- && 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
1367
1383
  }
1368
1384
 
1369
1385
  // 从模型回复里抠出唯一 JSON 对象(容忍 ```json 围栏与前后废话)。
@@ -1384,12 +1400,66 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1384
1400
  * 板滞后(或模型久未同步)时问一次辅助模型。失败静默(记 assistantError),
1385
1401
  * 绝不阻断主流程;每回合至多 maxCallsPerTurn 次、两次至少间隔 minIntervalMs。
1386
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
+
1387
1456
  async function maybeAskAssistant(sid, at) {
1457
+ const a = liveAssistant()
1388
1458
  if (!assistantReady() || !boardHasWork(sid)) return
1389
1459
  const o = obsOf(sid)
1390
1460
  if (!modelIsLate(sid, at) && o.stepsSinceBoard < cfg.observer.maxIdleSteps) return
1391
- if (at - o.lastAssistantAt < cfg.assistant.minIntervalMs) return
1392
- 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
1393
1463
  const state = states.get(sid)
1394
1464
  if (!state) return
1395
1465
  o.assistantCalls += 1
@@ -1397,56 +1467,59 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1397
1467
  const lastOutput = o.outputs[o.outputs.length - 1]
1398
1468
  const files = Array.isArray(o.files) ? o.files.slice(-4).map((f) => f.path) : []
1399
1469
  const lines = [
1470
+ `目标:${state.goal && state.goal.phase === 'active' ? JSON.stringify(state.goal.objective) : '(无)'}`,
1400
1471
  ...renderChecklist(state, cfg.observer.maxItems),
1401
1472
  lastOutput ? `最近输出:${lastOutput.text}` : '最近输出:—',
1402
1473
  o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
1403
1474
  files.length ? `最近改动:${files.join(' · ')}` : '最近改动:—',
1404
1475
  ]
1405
1476
  const controller = new AbortController()
1406
- 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))
1407
1478
  try {
1408
- const base = String(cfg.assistant.baseUrl || '').replace(/\/+$/, '')
1409
- const response = await fetch(`${base}/chat/completions`, {
1410
- method: 'POST',
1411
- headers: {
1412
- 'content-type': 'application/json',
1413
- ...(String(cfg.assistant.apiKey || '') !== '' ? { authorization: `Bearer ${cfg.assistant.apiKey}` } : {}),
1414
- },
1415
- body: JSON.stringify({
1416
- model: cfg.assistant.model,
1417
- temperature: 0,
1418
- max_tokens: 300,
1419
- messages: [
1420
- { role: 'system', content: ASSISTANT_SYSTEM },
1421
- { role: 'user', content: lines.join('\n') },
1422
- ],
1423
- }),
1424
- signal: controller.signal,
1425
- })
1426
- if (!response.ok) throw new Error(`HTTP ${response.status}`)
1427
- const body = await response.json()
1428
- 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)
1429
1514
  if (!proposal) throw new Error('proposal-unparsable')
1430
1515
  o.assistantError = ''
1431
1516
  o.assistantNote = String(proposal.note || '').slice(0, 200)
1432
- if (cfg.assistant.autoApply !== false && Array.isArray(proposal.changes) && proposal.changes.length > 0) {
1433
- const byId = new Map(state.items.map((item) => [item.id, item]))
1434
- const changes = []
1435
- for (const candidate of proposal.changes.slice(0, 10)) {
1436
- if (!isObject(candidate)) continue
1437
- const target = byId.get(String(candidate.id || ''))
1438
- if (!target) continue
1439
- const patch = { id: target.id }
1440
- if (typeof candidate.current === 'string') patch.current = candidate.current
1441
- if (typeof candidate.next === 'string') patch.next = candidate.next
1442
- if (typeof candidate.percent === 'number' && Number.isFinite(candidate.percent)) {
1443
- patch.percent = Math.max(0, Math.min(100, Math.round(candidate.percent)))
1444
- }
1445
- if (Object.keys(patch).length > 1) changes.push(patch)
1446
- }
1447
- if (changes.length > 0) {
1448
- await applyChanges({ sessionId: sid, changes, origin: 'assistant' })
1449
- }
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 })
1450
1523
  }
1451
1524
  } catch (err) {
1452
1525
  o.assistantError = err instanceof Error ? err.message : String(err)
@@ -1508,6 +1581,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1508
1581
  lines.push(`⚠ 进度已滞后(${synced}${idleMin >= 1 ? ',' + idleMin + ' 分钟' : ''}):先调用 progress_update 同步再继续;无变化就传 changes=[]。观察者已用最近动作自动刷新 current(updatedBy=observer),但状态/百分比仍需你确认。`)
1509
1582
  }
1510
1583
  if (o.assistantNote) lines.push(`助手审查:${o.assistantNote}`)
1584
+ if (o.roundDraft) lines.push(`助手轮次草案(仅供参考):${o.roundDraft}`)
1511
1585
  if (o.assistantError) lines.push(`助手审查失败:${o.assistantError}(仅影响审查建议,不阻断主流程)`)
1512
1586
  return `<progress-observer revision="${state.revision}" synced="${synced}">\n${lines.join('\n')}\n</progress-observer>`
1513
1587
  }
@@ -1999,8 +2073,9 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1999
2073
  markLineage(task, session)
2000
2074
  const pendingText = userTextMap.get(sid) || ''
2001
2075
  task.open = true
2002
- // 辅助 LLM 的每回合配额:开新回合重置
2076
+ // 辅助 LLM 的每回合配额:开新回合重置(轮次草案不跨回合复用)
2003
2077
  obsOf(sid).assistantCalls = 0
2078
+ obsOf(sid).roundDraft = ''
2004
2079
  if (!task.active) {
2005
2080
  task.active = true
2006
2081
  task.startedAt = now()
@@ -2549,6 +2624,42 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2549
2624
  )
2550
2625
  }
2551
2626
 
2627
+ // —— 模型侧 progress_goal_report 工具(报告轮次状态;助手草案不自动调这里)——
2628
+ ctx.effect(
2629
+ () =>
2630
+ tools.register({
2631
+ name: 'progress_goal_report',
2632
+ description:
2633
+ '在 /progress-goal 续轮里报告本轮状态。complete 需 evidence 且进度板已全部完成;blocked 需 blocker(连续 3 轮同因才落 blocked);continue 表示仍在推进。',
2634
+ parameters: {
2635
+ type: 'object',
2636
+ additionalProperties: false,
2637
+ properties: {
2638
+ status: { type: 'string', enum: ['continue', 'complete', 'blocked'] },
2639
+ summary: { type: 'string' },
2640
+ evidence: { type: 'array', items: { type: 'string' } },
2641
+ nextSteps: { type: 'array', items: { type: 'string' } },
2642
+ blocker: { type: 'string' },
2643
+ },
2644
+ required: ['status'],
2645
+ },
2646
+ output: {
2647
+ schema: { type: 'object', additionalProperties: true, properties: { ok: { type: 'boolean' }, goal: { type: 'object', additionalProperties: true } } },
2648
+ render(_args, value) {
2649
+ return [{ type: 'text', text: JSON.stringify(value, null, 2) }]
2650
+ },
2651
+ },
2652
+ async execute(args, exec) {
2653
+ const agent = exec.agent
2654
+ if (!agent) throw new Error('progress_goal_report 只能在 Agent 会话中调用')
2655
+ if (!isObject(args)) throw new Error('参数必须是对象')
2656
+ const view = await applyGoalReport(String(agent.session?.id ?? agent.id), args)
2657
+ return { ok: true, goal: view }
2658
+ },
2659
+ }, { when: ({ agent }) => isEnabled(sessionOfAgent(agent)) }),
2660
+ 'progress-union: progress_goal_report tool',
2661
+ )
2662
+
2552
2663
  const agentDisposers = new Map()
2553
2664
  function bindAgentContext(agent) {
2554
2665
  const sessionId = sessionOfAgent(agent)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-progress-union",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
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",