@nethiel/dsh-turn-report 0.0.0-stage → 0.1.0
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/CHANGELOG.md +41 -0
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/client.js +940 -0
- package/cordis.patch.yml +35 -0
- package/docs/DETAIL.md +161 -0
- package/docs/DETAIL.zh.md +136 -0
- package/docs/demo-card.png +0 -0
- package/docs/dsh-market-entry.json +12 -0
- package/icon.svg +16 -0
- package/index.js +1052 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +72 -3
- package/test/fold.test.mjs +718 -0
package/index.js
ADDED
|
@@ -0,0 +1,1052 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-turn-report — host half.
|
|
3
|
+
*
|
|
4
|
+
* Derives a compact per-turn project report entirely from the session log:
|
|
5
|
+
* every closed turn gets one entry holding what was finished, what is still
|
|
6
|
+
* in progress, what is left, plus tool/file/failure counts.
|
|
7
|
+
*
|
|
8
|
+
* The value reaches the browser through the session-projection wire view, so
|
|
9
|
+
* the client renders a finished value — it never folds session events itself.
|
|
10
|
+
* No model call is made and no token is spent: the report is deterministic.
|
|
11
|
+
*
|
|
12
|
+
* @module dsh-turn-report
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const name = 'turn-report'
|
|
16
|
+
|
|
17
|
+
/** The projection service this plugin folds on. */
|
|
18
|
+
export const inject = ['sessionProjections']
|
|
19
|
+
|
|
20
|
+
/** Projection key; the client reads the same key through `useProjection`. */
|
|
21
|
+
const KEY = 'turnReport'
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Bump when the fold semantics or the state shape change.
|
|
25
|
+
*
|
|
26
|
+
* v2: file labels became workspace-relative and the tree rows carry an explicit
|
|
27
|
+
* depth. A v1 checkpoint would otherwise be restored as-is and keep serving the
|
|
28
|
+
* old absolute-path strings, so the version has to move with the shape.
|
|
29
|
+
*
|
|
30
|
+
* v3: each turn's todo now carries a `pending` list (unfinished items only).
|
|
31
|
+
*
|
|
32
|
+
* v4: the todo area reports `finished` — the items this turn newly completed —
|
|
33
|
+
* instead of `pending`. Pending duplicated the built-in input-dock panel, which
|
|
34
|
+
* renders the same live list; "newly finished" is the fact only the card knows.
|
|
35
|
+
* `prevTodos` was added to state to compute it.
|
|
36
|
+
*
|
|
37
|
+
* v5: each turn carries `llm` — model route, response count and token buckets.
|
|
38
|
+
*
|
|
39
|
+
* v6: `live` — the current plan, its sections and next-up slice, for the status
|
|
40
|
+
* bar. Derived on read from `todos`/`prevTodos`, not folded into each turn.
|
|
41
|
+
*
|
|
42
|
+
* v7: `prevTodos` now survives plan-less turns instead of being nulled by the
|
|
43
|
+
* next `turn/start`. Before this the last real plan was erased two turns after it
|
|
44
|
+
* was written, so long sessions lost their todo section entirely.
|
|
45
|
+
*
|
|
46
|
+
* v8: plan groups are now a fixed three-slot list (done / doing / left) with an
|
|
47
|
+
* `empty` flag, instead of only the slots that happened to have rows. Without the
|
|
48
|
+
* bump, a cached v7 checkpoint would keep serving the old shape and the HUD would
|
|
49
|
+
* silently render the previous layout.
|
|
50
|
+
*
|
|
51
|
+
* v9: plan groups may now be STAGES (when items carry 【label】 prefixes) rather
|
|
52
|
+
* than status buckets, and every row's `c` has the stage prefix stripped. Same
|
|
53
|
+
* hazard as v8 and it was paid for again: the code changed, the version did not,
|
|
54
|
+
* so a cached v8 checkpoint kept replaying the status-grouped shape and the UI
|
|
55
|
+
* looked untouched across several restarts and green test runs.
|
|
56
|
+
*
|
|
57
|
+
* v10: `cleared` flag added, and the finished delta changed semantics. An explicit
|
|
58
|
+
* empty list now drops the plan (previously it kept carrying the old one), stage
|
|
59
|
+
* labels are excluded from the identity key (previously a relabel counted as new
|
|
60
|
+
* work), and duplicates are matched by count (previously a second completion was
|
|
61
|
+
* invisible). All three change what wire.view produces, so the checkpoint must be
|
|
62
|
+
* rebuilt.
|
|
63
|
+
*
|
|
64
|
+
* v11: each turn may carry `decisions` — human messages quoted verbatim when they
|
|
65
|
+
* read as a decision. New field, so the checkpoint changes again.
|
|
66
|
+
*
|
|
67
|
+
* v13: each turn records `sessionHasPlan` so a session that never used a task list
|
|
68
|
+
* can say so instead of rendering an unexplained empty card.
|
|
69
|
+
*
|
|
70
|
+
* v12: `plan.sourceTurn` names the turn whose list is shown when the current turn
|
|
71
|
+
* carried it forward, so the card can say "carried over from turn 2" instead of a
|
|
72
|
+
* bare "not updated this turn".
|
|
73
|
+
*/
|
|
74
|
+
const STATE_VERSION = 13
|
|
75
|
+
|
|
76
|
+
/** How many closed turns stay addressable. Older turns simply render no card. */
|
|
77
|
+
const MAX_TURNS = 15
|
|
78
|
+
|
|
79
|
+
/** Hard caps that keep the wire payload small; the config lowers them further. */
|
|
80
|
+
const HARD_MAX_ROWS = 20
|
|
81
|
+
const MAX_FILES = 6
|
|
82
|
+
|
|
83
|
+
/** Status bar budget: rows are scarce, so it shows a focused slice, not the list. */
|
|
84
|
+
const MAX_GROUP_ITEMS = HARD_MAX_ROWS
|
|
85
|
+
const LIVE_NEXT_UP = 3
|
|
86
|
+
/** How many quoted decisions to keep per turn. Two is already a busy turn. */
|
|
87
|
+
const MAX_DECISIONS = 2
|
|
88
|
+
|
|
89
|
+
/** How the todo area chooses between the finished list and the project tree. */
|
|
90
|
+
const TODO_VIEWS = ['auto', 'tree', 'both']
|
|
91
|
+
|
|
92
|
+
/** Argument keys that name a file a tool touches. */
|
|
93
|
+
const FILE_ARG_KEYS = ['file_path', 'filePath', 'path', 'notebook_path', 'target_file']
|
|
94
|
+
|
|
95
|
+
/** Tool names whose argument carries a file path worth reporting. */
|
|
96
|
+
const FILE_TOOLS = new Set([
|
|
97
|
+
'write', 'edit', 'multi_edit', 'insert', 'str_replace_editor', 'apply_patch',
|
|
98
|
+
'create_file', 'edit_file', 'write_file', 'notebook_edit',
|
|
99
|
+
])
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Resolve raw plugin config into the complete settings object with defaults,
|
|
103
|
+
* legacy aliases applied, and every value in range.
|
|
104
|
+
*
|
|
105
|
+
* Both the host's `Config` validation and `apply()` call this, so the settings a
|
|
106
|
+
* row declares mean the same thing whether or not the host ran validation on it —
|
|
107
|
+
* `apply()` must not assume a validated object arrives.
|
|
108
|
+
* @param {unknown} value - the row's raw `config`, possibly absent or partial.
|
|
109
|
+
* @returns {{ settings: object, issues: object[] }} the resolved settings and any problems.
|
|
110
|
+
*/
|
|
111
|
+
function resolveConfig(value) {
|
|
112
|
+
const raw = value !== null && typeof value === 'object' ? value : {}
|
|
113
|
+
const issues = []
|
|
114
|
+
const settings = { maxRows: 6, showWithoutTasks: true, showTree: true, showFiles: true, showFinished: true, showLlm: true, showStatusBar: true, statusBarOpen: true, replaceNativeTodo: true, todoView: 'auto' }
|
|
115
|
+
if (raw.maxRows !== undefined) {
|
|
116
|
+
if (typeof raw.maxRows === 'number' && Number.isFinite(raw.maxRows)) {
|
|
117
|
+
settings.maxRows = Math.max(1, Math.min(HARD_MAX_ROWS, Math.trunc(raw.maxRows)))
|
|
118
|
+
} else {
|
|
119
|
+
issues.push({ message: 'maxRows must be a finite number', path: ['maxRows'] })
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
for (const flag of ['showWithoutTasks', 'showTree', 'showFiles', 'showFinished', 'showLlm', 'showStatusBar', 'statusBarOpen', 'replaceNativeTodo']) {
|
|
123
|
+
const supplied = raw[flag]
|
|
124
|
+
if (supplied === undefined) continue
|
|
125
|
+
if (typeof supplied === 'boolean') settings[flag] = supplied
|
|
126
|
+
else issues.push({ message: `${flag} must be a boolean`, path: [flag] })
|
|
127
|
+
}
|
|
128
|
+
// `showPending` controlled the retired full-list block; honour it as an alias
|
|
129
|
+
// so an existing profile row keeps its intent instead of silently reverting.
|
|
130
|
+
if (raw.showPending !== undefined && raw.showFinished === undefined && typeof raw.showPending === 'boolean') {
|
|
131
|
+
settings.showFinished = raw.showPending
|
|
132
|
+
}
|
|
133
|
+
if (raw.todoView !== undefined) {
|
|
134
|
+
// `pending` was the retired view name; `auto` is its replacement.
|
|
135
|
+
const view = raw.todoView === 'pending' ? 'auto' : raw.todoView
|
|
136
|
+
if (TODO_VIEWS.includes(view)) settings.todoView = view
|
|
137
|
+
else issues.push({ message: `todoView must be one of ${TODO_VIEWS.join(', ')}`, path: ['todoView'] })
|
|
138
|
+
}
|
|
139
|
+
return { settings, issues }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Validate the resolved plugin configuration.
|
|
144
|
+
*
|
|
145
|
+
* Hand-rolled because the host only ever calls `Config['~standard'].validate`;
|
|
146
|
+
* this keeps the bundle free of a runtime schema dependency.
|
|
147
|
+
*/
|
|
148
|
+
export const Config = {
|
|
149
|
+
'~standard': {
|
|
150
|
+
version: 1,
|
|
151
|
+
vendor: 'dsh-turn-report',
|
|
152
|
+
validate(value) {
|
|
153
|
+
const { settings, issues } = resolveConfig(value)
|
|
154
|
+
return issues.length > 0 ? { issues } : { value: settings }
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Leading indentation of a todo line, in levels. Two spaces or one tab is one
|
|
161
|
+
* level; four or more spaces is two. `todo_write` has no parent field, so the
|
|
162
|
+
* nesting a person typed into the content is the only hierarchy available.
|
|
163
|
+
* @param {string} content - the raw todo line.
|
|
164
|
+
* @returns {number} the derived depth, 0 to 2.
|
|
165
|
+
*/
|
|
166
|
+
function depthOf(content) {
|
|
167
|
+
const leading = /^[ \t]*/.exec(content)?.[0] ?? ''
|
|
168
|
+
const width = leading.replace(/\t/g, ' ').length
|
|
169
|
+
if (width >= 4) return 2
|
|
170
|
+
if (width >= 2) return 1
|
|
171
|
+
return 0
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Strip the bullet or numbering marker a person may have typed ahead of a todo.
|
|
176
|
+
* @param {string} content - the raw todo line.
|
|
177
|
+
* @returns {string} the display text.
|
|
178
|
+
*/
|
|
179
|
+
function labelOf(content) {
|
|
180
|
+
return content.replace(/^[ \t]*/, '').replace(/^(?:[-*•·]|\d+[.)])\s+/, '').trim()
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Read a file path out of one tool call's raw argument JSON.
|
|
185
|
+
* @param {string} toolName - the called tool.
|
|
186
|
+
* @param {string} rawArguments - the model-produced JSON string.
|
|
187
|
+
* @returns {string | undefined} the path, when the call names one.
|
|
188
|
+
*/
|
|
189
|
+
function fileOf(toolName, rawArguments) {
|
|
190
|
+
if (!FILE_TOOLS.has(toolName)) return undefined
|
|
191
|
+
if (typeof rawArguments !== 'string' || rawArguments === '') return undefined
|
|
192
|
+
let parsed
|
|
193
|
+
try {
|
|
194
|
+
parsed = JSON.parse(rawArguments)
|
|
195
|
+
} catch {
|
|
196
|
+
return undefined
|
|
197
|
+
}
|
|
198
|
+
if (parsed === null || typeof parsed !== 'object') return undefined
|
|
199
|
+
for (const key of FILE_ARG_KEYS) {
|
|
200
|
+
const value = parsed[key]
|
|
201
|
+
if (typeof value === 'string' && value.trim() !== '') return value.trim()
|
|
202
|
+
}
|
|
203
|
+
return undefined
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Zeroed token buckets for one turn.
|
|
208
|
+
* @returns {object} a fresh accumulator.
|
|
209
|
+
*/
|
|
210
|
+
function emptyUsage() {
|
|
211
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Add one `assistant/message` usage report into the turn accumulator.
|
|
216
|
+
*
|
|
217
|
+
* Provider buckets are optional and individually untrustworthy, so each is read
|
|
218
|
+
* defensively; a missing bucket contributes 0 rather than poisoning the sum.
|
|
219
|
+
* @param {object} acc - the running accumulator.
|
|
220
|
+
* @param {object | undefined} usage - the event's reported usage.
|
|
221
|
+
* @returns {object} the same accumulator reference when nothing was addable.
|
|
222
|
+
*/
|
|
223
|
+
function addUsage(acc, usage) {
|
|
224
|
+
if (usage === null || typeof usage !== 'object') return acc
|
|
225
|
+
const count = value => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0)
|
|
226
|
+
const input = count(usage.inputTokens)
|
|
227
|
+
const output = count(usage.outputTokens)
|
|
228
|
+
const next = {
|
|
229
|
+
input: acc.input + input,
|
|
230
|
+
output: acc.output + output,
|
|
231
|
+
cacheRead: acc.cacheRead + count(usage.cacheReadTokens),
|
|
232
|
+
cacheWrite: acc.cacheWrite + count(usage.cacheWriteTokens),
|
|
233
|
+
total: acc.total + (count(usage.totalTokens) || input + output),
|
|
234
|
+
}
|
|
235
|
+
if (next.input === acc.input && next.output === acc.output
|
|
236
|
+
&& next.cacheRead === acc.cacheRead && next.cacheWrite === acc.cacheWrite
|
|
237
|
+
&& next.total === acc.total) return acc
|
|
238
|
+
return next
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* System-generated user messages that are not a person talking.
|
|
243
|
+
*
|
|
244
|
+
* The session log stores injected context as `user/message` too: reminders, skill
|
|
245
|
+
* catalogues, memory banners, per-step timestamps, approval-policy notices. Measured
|
|
246
|
+
* on this project's own session: 92 of 145 user events were these, so filtering them
|
|
247
|
+
* is most of the work — a decision extractor that reads them would fire on template
|
|
248
|
+
* text rather than on anything a person decided.
|
|
249
|
+
*/
|
|
250
|
+
const INJECTED_PREFIXES = [
|
|
251
|
+
'<system-reminder>',
|
|
252
|
+
'<hindsight_pages>',
|
|
253
|
+
'<hindsight_page_refresh>',
|
|
254
|
+
'Time sampled while preparing turn',
|
|
255
|
+
'The user changed the approval policy',
|
|
256
|
+
'The following workspace instructions',
|
|
257
|
+
'A skill is a reusable',
|
|
258
|
+
'This is an automatically generated checkpoint',
|
|
259
|
+
'[model changed:',
|
|
260
|
+
]
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Text of a `user/message` event, or null when it is not a person speaking.
|
|
264
|
+
* @param {object} event - the `user/message` event.
|
|
265
|
+
* @returns {string | null} the human text, trimmed; null for injected context.
|
|
266
|
+
*/
|
|
267
|
+
function humanTextOf(event) {
|
|
268
|
+
const content = event?.data?.content
|
|
269
|
+
let text = ''
|
|
270
|
+
if (typeof content === 'string') {
|
|
271
|
+
text = content
|
|
272
|
+
} else if (Array.isArray(content)) {
|
|
273
|
+
text = content
|
|
274
|
+
.filter(part => part?.type === 'text' && typeof part.text === 'string')
|
|
275
|
+
.map(part => part.text)
|
|
276
|
+
.join('\n')
|
|
277
|
+
}
|
|
278
|
+
const trimmed = text.trim()
|
|
279
|
+
if (trimmed === '') return null
|
|
280
|
+
for (const prefix of INJECTED_PREFIXES) {
|
|
281
|
+
if (trimmed.startsWith(prefix)) return null
|
|
282
|
+
}
|
|
283
|
+
return trimmed
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Phrases that mean the sentence is NOT a decision, checked first.
|
|
288
|
+
*
|
|
289
|
+
* The review that prompted this feature put it plainly: a false "they split the
|
|
290
|
+
* stage" changes what the reader believes happened, while a missed one only shows
|
|
291
|
+
* less. So exclusion runs before inclusion, and the net is deliberately tight.
|
|
292
|
+
*
|
|
293
|
+
* The first revision of this list went by substring cues ("方案", "决定") and
|
|
294
|
+
* therefore quoted "我还没决定用哪个方案。" and "请对比这两个方案的区别。" — sentences
|
|
295
|
+
* about the ABSENCE of a decision. That is the exact failure the review warned about,
|
|
296
|
+
* so the check now covers unanswered states and comparison requests explicitly, and
|
|
297
|
+
* a bare question is rejected regardless of punctuation.
|
|
298
|
+
*/
|
|
299
|
+
const NON_DECISION_MARKERS = [
|
|
300
|
+
// Still undecided.
|
|
301
|
+
'还没决定', '还没定', '没决定', '未决定', '决定不了', '不确定', '待定', '再想想',
|
|
302
|
+
// Asking for comparison or information rather than stating an outcome.
|
|
303
|
+
'对比', '区别', '哪个好', '推荐', '怎么看', '为什么', '怎么回事', '什么情况',
|
|
304
|
+
// Hypotheticals.
|
|
305
|
+
'要不要', '是否要', '如果', '假如', '假设', '可以考虑', '也许', '或许', '是不是要',
|
|
306
|
+
// Questions, with or without a question mark.
|
|
307
|
+
'吗', '呢', '是不是', '会不会', '可不可以', '能不能帮', '我感觉',
|
|
308
|
+
// A question mark anywhere turns the message into a question.
|
|
309
|
+
'?', '?',
|
|
310
|
+
// Negations of the action itself.
|
|
311
|
+
'先别', '不要', '别急', '不用', '暂不', '不拆', '不合并', '先不做',
|
|
312
|
+
// Reported speech / quoting.
|
|
313
|
+
'你说要', '你说的', '有人建议', '文档里说', 'README 里',
|
|
314
|
+
]
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Patterns that state an outcome. A message must match one to be quoted.
|
|
318
|
+
*
|
|
319
|
+
* This replaced a "contains a cue word" test, which was too loose: it fired on
|
|
320
|
+
* sentences that merely MENTION a decision. Requiring a selecting or acting verb
|
|
321
|
+
* with something after it is what keeps the card to real outcomes.
|
|
322
|
+
*/
|
|
323
|
+
const DECISION_SHAPES = [
|
|
324
|
+
// First-person selection: 我选方案 E / 我用 B / 我决定改成 X
|
|
325
|
+
/(?:我|就|还是)\s*(?:选|用|决定|采用|要)\s*(?:方案|选项)?\s*[\w\u4e00-\u9fa5@./-]{1,30}/,
|
|
326
|
+
// Imperative selection or change: 改成 X / 就按 A 做 / 用 B
|
|
327
|
+
/(?:改成|改为|换成|就按|按)\s*[\w\u4e00-\u9fa5@./-]{1,30}/,
|
|
328
|
+
// Acting decisions: 先建私有仓 / 要做 C / 继续做 X / 发 npm
|
|
329
|
+
/(?:先|就|直接|马上)\s*(?:建|发|做|写|改|加|删|放|上|跑|装)\s*[\w\u4e00-\u9fa5]{1,30}/,
|
|
330
|
+
// Structural changes to the plan.
|
|
331
|
+
/(?:拆分|拆成|合并|去掉|删掉|移除|放弃|停止|开始做|要做)\s*[\w\u4e00-\u9fa5]{1,30}/,
|
|
332
|
+
]
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Whole-message forms that are a decision despite being short.
|
|
336
|
+
*
|
|
337
|
+
* These match the ENTIRE trimmed message, so they cannot fire on a fragment of a
|
|
338
|
+
* longer sentence. Covers the answers this project actually received: a bare option
|
|
339
|
+
* letter, an option plus its wording, and a one-word go-ahead.
|
|
340
|
+
*
|
|
341
|
+
* "继续" is deliberately absent: it means "keep going", not "decided X". Quoting it
|
|
342
|
+
* would put a meaningless row on the card every time the reader says it, and the
|
|
343
|
+
* card is trying to report changes, not activity.
|
|
344
|
+
*
|
|
345
|
+
* "要做吗" is deliberately absent from the option forms: it is a question, and the
|
|
346
|
+
* review caught the earlier version accepting it.
|
|
347
|
+
*/
|
|
348
|
+
const SHORT_DECISION = [
|
|
349
|
+
/^(?:就)?(?:做吧|开始吧|开干|同意|批准)$/,
|
|
350
|
+
/^(?:选|用)?\s*(?:方案|选项)\s*[A-Za-z0-9一二三四五六七八九十]{1,3}$/,
|
|
351
|
+
/^(?:选|用)?\s*[A-Za-z0-9一二三四五六七八九十]{1,3}\s*(?:方案)$/,
|
|
352
|
+
]
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Marks a message as retracting the previous decision in the same turn.
|
|
356
|
+
*
|
|
357
|
+
* The review's case: "同一轮先说方案 A,再说先别做,刚才的决定撤回" kept the retracted
|
|
358
|
+
* choice. A retraction has to remove what it retracts, so it is matched first and
|
|
359
|
+
* clears the turn's decisions instead of adding to them.
|
|
360
|
+
*/
|
|
361
|
+
const RETRACTION = /(?:撤回|收回|取消|不算|当我没说|反悔|算了)/
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Shortest and longest message worth quoting as a decision.
|
|
366
|
+
*
|
|
367
|
+
* Too long is pasted material or a system prompt. Too short normally carries no
|
|
368
|
+
* subject ("继续", "A"), but a few very short messages ARE complete decisions and
|
|
369
|
+
* were the clearest ones in this session: "做吧", "方案 E", "C 方向要做". Those are
|
|
370
|
+
* admitted by `SHORT_DECISION` below instead of by lowering the general floor.
|
|
371
|
+
*/
|
|
372
|
+
const DECISION_MIN_LENGTH = 8
|
|
373
|
+
const DECISION_MAX_LENGTH = 120
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* A message a person wrote that reads as a decision, quoted rather than parsed.
|
|
377
|
+
*
|
|
378
|
+
* The card shows the person's own words, trimmed, prefixed by who said it. This is
|
|
379
|
+
* honest: it cannot mislabel an action, because it never labels one. What it does
|
|
380
|
+
* add beyond the task list is timing — the reader learns that on turn N the person
|
|
381
|
+
* said this, even if the todo list has not caught up yet.
|
|
382
|
+
*
|
|
383
|
+
* Returning `{ retract: true }` means the message withdraws an earlier decision in
|
|
384
|
+
* the same turn; the caller clears instead of appending.
|
|
385
|
+
* @param {string} text - one human message.
|
|
386
|
+
* @returns {{ quote?: string, retract?: boolean } | null} the effect, or null.
|
|
387
|
+
*/
|
|
388
|
+
function decisionOf(text) {
|
|
389
|
+
const body = text.trim()
|
|
390
|
+
if (body.length > DECISION_MAX_LENGTH) return null
|
|
391
|
+
// A retraction must be recognised even though it contains exclusion markers
|
|
392
|
+
// ("撤回" implies stopping), so it is tested before the exclusion sweep.
|
|
393
|
+
if (RETRACTION.test(body) && body.length <= 60) return { retract: true }
|
|
394
|
+
for (const marker of NON_DECISION_MARKERS) {
|
|
395
|
+
if (body.includes(marker)) return null
|
|
396
|
+
}
|
|
397
|
+
// Whole-message forms are checked before the length floor, because the shortest
|
|
398
|
+
// messages in this session were among the clearest decisions.
|
|
399
|
+
for (const re of SHORT_DECISION) {
|
|
400
|
+
if (re.test(body)) return { quote: body }
|
|
401
|
+
}
|
|
402
|
+
// An imperative decision is a decision at any length: "先建私有仓" is five
|
|
403
|
+
// characters and unmistakably an instruction, so the general length floor must not
|
|
404
|
+
// be what decides whether it counts.
|
|
405
|
+
for (const re of DECISION_SHAPES) {
|
|
406
|
+
if (re.test(body) && /^(?:我|就|还是|先|直接|马上|把)/.test(body)) return { quote: body }
|
|
407
|
+
}
|
|
408
|
+
if (body.length < DECISION_MIN_LENGTH) return null
|
|
409
|
+
// Require an outcome shape: mentioning the word "方案" is not deciding anything.
|
|
410
|
+
for (const re of DECISION_SHAPES) {
|
|
411
|
+
if (re.test(body)) return { quote: body }
|
|
412
|
+
}
|
|
413
|
+
return null
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* The `provider/model` route a finished assistant message came from.
|
|
418
|
+
* @param {object | undefined} event - the `assistant/message` event.
|
|
419
|
+
* @returns {string | undefined} the route, when the message names one.
|
|
420
|
+
*/
|
|
421
|
+
function routeOf(event) {
|
|
422
|
+
const source = event?.data?.message?.source
|
|
423
|
+
if (source === null || typeof source !== 'object') return undefined
|
|
424
|
+
const provider = typeof source.provider === 'string' ? source.provider.trim() : ''
|
|
425
|
+
const model = typeof source.model === 'string' ? source.model.trim() : ''
|
|
426
|
+
return provider !== '' && model !== '' ? `${provider}/${model}` : undefined
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Make a path relative to the session workspace so a card shows
|
|
431
|
+
* `docs/preview.svg` instead of the whole absolute path. Paths outside the
|
|
432
|
+
* workspace stay absolute: hiding the location would be worse than the width.
|
|
433
|
+
* @param {string} file - the absolute path a tool reported.
|
|
434
|
+
* @param {string | undefined} cwd - the session workspace root.
|
|
435
|
+
* @returns {string} the display path.
|
|
436
|
+
*/
|
|
437
|
+
function displayPath(file, cwd) {
|
|
438
|
+
if (typeof cwd !== 'string' || cwd === '') return file
|
|
439
|
+
const normalized = file.replace(/\\/g, '/')
|
|
440
|
+
const root = cwd.replace(/\\/g, '/').replace(/\/+$/, '')
|
|
441
|
+
if (normalized === root) return '.'
|
|
442
|
+
if (normalized.startsWith(root + '/')) return normalized.slice(root.length + 1)
|
|
443
|
+
return file
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Comparison key for one todo line, used only to decide whether two lists are
|
|
448
|
+
* talking about the same task.
|
|
449
|
+
*
|
|
450
|
+
* `todo_write` entries carry no id, so cross-turn matching has to go through the
|
|
451
|
+
* text. Comparing raw text over-reports: a model that rewords an already-finished
|
|
452
|
+
* item (`- 写测试` → `写测试`) would look like brand-new work. Stripping the list
|
|
453
|
+
* marker, heading marks, all whitespace and case folds those harmless rewrites
|
|
454
|
+
* together. It is still a heuristic — a genuine rewording reads as new work.
|
|
455
|
+
* @param {string} content - the raw todo line.
|
|
456
|
+
* @returns {string} the comparison key.
|
|
457
|
+
*/
|
|
458
|
+
/**
|
|
459
|
+
* Comparison key for one todo line — the TEXT only, with any 【stage】 prefix
|
|
460
|
+
* removed first.
|
|
461
|
+
*
|
|
462
|
+
* Two failure modes come from keeping the stage label in the key:
|
|
463
|
+
*
|
|
464
|
+
* 1. **False "finished".** Moving a completed item from 【实现】 to 【验证】 keeps
|
|
465
|
+
* the task but changes the label. With the label in the key the move reads as a
|
|
466
|
+
* brand-new completion, so the card claims work that did not happen.
|
|
467
|
+
* 2. **Missed "finished".** Matching by text alone collapses duplicates: two items
|
|
468
|
+
* literally named 文案 both hash to the same key, so finishing the second one is
|
|
469
|
+
* invisible once the first is in the "already done" set.
|
|
470
|
+
*
|
|
471
|
+
* Labels are stripped here because the stage is presentation, not identity; the
|
|
472
|
+
* duplicate case is handled downstream by counting, not by keying.
|
|
473
|
+
* @param {string} content - the raw todo line.
|
|
474
|
+
* @returns {string} the comparison key.
|
|
475
|
+
*/
|
|
476
|
+
function matchKey(content) {
|
|
477
|
+
return String(content)
|
|
478
|
+
.replace(/^[\s\u3000]+/, '')
|
|
479
|
+
.replace(/^(?:[-*•·]|\d+[.)]|#+)\s*/, '')
|
|
480
|
+
.replace(/^[【\[〔][^】\]〕]*[】\]〕]\s*/, '')
|
|
481
|
+
.replace(/[\s\u3000]+/g, '')
|
|
482
|
+
.toLowerCase()
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Count how many items with each key are `completed`.
|
|
487
|
+
* @param {object[] | null} todos - a whole list.
|
|
488
|
+
* @returns {Map<string, number>} completed count per key.
|
|
489
|
+
*/
|
|
490
|
+
function completedCounts(todos) {
|
|
491
|
+
const counts = new Map()
|
|
492
|
+
if (!Array.isArray(todos)) return counts
|
|
493
|
+
for (const item of todos) {
|
|
494
|
+
if (item?.status !== 'completed') continue
|
|
495
|
+
const key = matchKey(item?.content ?? '')
|
|
496
|
+
counts.set(key, (counts.get(key) ?? 0) + 1)
|
|
497
|
+
}
|
|
498
|
+
return counts
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* Which items this turn actually finished.
|
|
503
|
+
*
|
|
504
|
+
* Matching is by text key and then by COUNT, not by set membership. Comparing sets
|
|
505
|
+
* loses duplicate items entirely: going from one completed 文案 to two completed
|
|
506
|
+
* 文案 leaves the set unchanged (`{文案}` before and after), so the second
|
|
507
|
+
* completion never reaches the card.
|
|
508
|
+
*
|
|
509
|
+
* The reported delta is therefore an increase in the per-key completed count. When
|
|
510
|
+
* a key became more complete than before, the rows shown are the ones with that key
|
|
511
|
+
* that are completed now, capped at the increase.
|
|
512
|
+
*
|
|
513
|
+
* This is the one todo fact the built-in input-dock panel cannot show — that panel
|
|
514
|
+
* renders the live list, so it never says what changed.
|
|
515
|
+
* @param {object[]} todos - this turn's whole list.
|
|
516
|
+
* @param {object[] | null} prevTodos - the previous turn's list, or null.
|
|
517
|
+
* @param {number} maxRows - how many finished items to keep.
|
|
518
|
+
* @returns {{ finished: object[], finishedMore: number }} the delta.
|
|
519
|
+
*/
|
|
520
|
+
function finishedDuring(todos, prevTodos, maxRows) {
|
|
521
|
+
const before = completedCounts(prevTodos)
|
|
522
|
+
const finished = []
|
|
523
|
+
let extra = 0
|
|
524
|
+
// Walk this turn's list in order so the card keeps the author's ordering.
|
|
525
|
+
const seen = new Map()
|
|
526
|
+
for (const item of todos) {
|
|
527
|
+
if (item?.status !== 'completed') continue
|
|
528
|
+
const content = String(item?.content ?? '')
|
|
529
|
+
const key = matchKey(content)
|
|
530
|
+
const index = (seen.get(key) ?? 0) + 1
|
|
531
|
+
seen.set(key, index)
|
|
532
|
+
// Only the completions beyond what existed before are new; for a key that is
|
|
533
|
+
// newly repeated, each copy past the previous count counts as new.
|
|
534
|
+
const priorCount = before.get(key) ?? 0
|
|
535
|
+
if (index <= priorCount) continue
|
|
536
|
+
if (finished.length < maxRows) finished.push({ c: rowTextOf(content), d: depthOf(content) })
|
|
537
|
+
else extra += 1
|
|
538
|
+
}
|
|
539
|
+
return { finished, finishedMore: extra }
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* The plan HUD's data for one point in time: totals, the groups with their
|
|
544
|
+
* children, and what is next. Shared by the frozen per-turn snapshot and the
|
|
545
|
+
* live view so both render identically.
|
|
546
|
+
* @param {object[]} todos - the whole list at that moment.
|
|
547
|
+
* @param {number} maxRows - section budget from config.
|
|
548
|
+
* @returns {object} the HUD payload.
|
|
549
|
+
*/
|
|
550
|
+
function planSnapshot(todos, maxRows) {
|
|
551
|
+
let done = 0
|
|
552
|
+
let doing = 0
|
|
553
|
+
let left = 0
|
|
554
|
+
const nextUp = []
|
|
555
|
+
for (const item of todos) {
|
|
556
|
+
const status = statusOf(item)
|
|
557
|
+
if (status === 'done') done += 1
|
|
558
|
+
else if (status === 'doing') doing += 1
|
|
559
|
+
else left += 1
|
|
560
|
+
if (status !== 'done' && nextUp.length < LIVE_NEXT_UP) {
|
|
561
|
+
nextUp.push({ c: rowTextOf(String(item?.content ?? '')), s: status })
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
const { groups, more } = groupTodos(todos, MAX_GROUP_ITEMS)
|
|
565
|
+
return { total: todos.length, done, doing, left, nextUp, groups, more }
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* The plan HUD's data for the conversation as it stands right now: the open
|
|
570
|
+
* turn's list if it has written one, otherwise the last list the session saw.
|
|
571
|
+
* @param {object} state - the fold state.
|
|
572
|
+
* @param {number} maxRows - section budget from config.
|
|
573
|
+
* @returns {object | null} the HUD payload, or null when no plan is known.
|
|
574
|
+
*/
|
|
575
|
+
function livePlan(state, maxRows) {
|
|
576
|
+
const todos = Array.isArray(state.todos)
|
|
577
|
+
? state.todos
|
|
578
|
+
: Array.isArray(state.prevTodos) ? state.prevTodos : null
|
|
579
|
+
if (todos === null || todos.length === 0) return null
|
|
580
|
+
return planSnapshot(todos, maxRows)
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* The plan a closed turn should report.
|
|
585
|
+
*
|
|
586
|
+
* Three distinct inputs, which the naive implementation collapsed into two:
|
|
587
|
+
*
|
|
588
|
+
* | this turn | meaning | card |
|
|
589
|
+
* |---|---|---|
|
|
590
|
+
* | wrote a non-empty list | the plan changed | that list, no badge |
|
|
591
|
+
* | wrote an EMPTY list | the author cleared the plan | "plan cleared", no carry-over |
|
|
592
|
+
* | wrote nothing | no plan activity this turn | newest list still in force, marked stale |
|
|
593
|
+
*
|
|
594
|
+
* Treating "wrote empty" as "wrote nothing" made a deliberately cleared plan
|
|
595
|
+
* reappear on the card as if it were still live — flagged `stale`, which reads as
|
|
596
|
+
* "we could not update it" rather than "it was cleared".
|
|
597
|
+
* @param {object[] | null} todos - the list this turn wrote, if any.
|
|
598
|
+
* @param {object[] | null} prevTodos - the newest earlier list, if any.
|
|
599
|
+
* @param {number} maxRows - section budget from config.
|
|
600
|
+
* @param {boolean} wroteEmpty - the turn explicitly wrote an empty list.
|
|
601
|
+
* @returns {object | null} the plan payload, or null when there is nothing to show.
|
|
602
|
+
*/
|
|
603
|
+
function planFor(todos, prevTodos, maxRows, wroteEmpty, sourceTurn) {
|
|
604
|
+
if (wroteEmpty) return null
|
|
605
|
+
if (Array.isArray(todos) && todos.length > 0) {
|
|
606
|
+
return { ...planSnapshot(todos, maxRows), stale: false, sourceTurn }
|
|
607
|
+
}
|
|
608
|
+
if (Array.isArray(prevTodos) && prevTodos.length > 0) {
|
|
609
|
+
return { ...planSnapshot(prevTodos, maxRows), stale: true, sourceTurn }
|
|
610
|
+
}
|
|
611
|
+
return null
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Freeze the live turn into the compact entry the client renders.
|
|
616
|
+
* @param {object} turn - the live accumulator for the closing turn.
|
|
617
|
+
* @param {string} endKind - the `turn/end` reason kind.
|
|
618
|
+
* @param {object[] | null} todos - the latest whole todo list, or null.
|
|
619
|
+
* @param {object[] | null} prevTodos - the previous turn's whole list, or null.
|
|
620
|
+
* @param {number} maxRows - how many todo rows to keep.
|
|
621
|
+
* @param {string | undefined} cwd - the session workspace root, for shorter file labels.
|
|
622
|
+
* @returns {object} the frozen entry.
|
|
623
|
+
*/
|
|
624
|
+
function freezeTurn(turn, endKind, todos, prevTodos, maxRows, cwd, wroteEmpty, sourceTurn, sessionHasPlan) {
|
|
625
|
+
const entry = {
|
|
626
|
+
n: turn.n,
|
|
627
|
+
end: endKind,
|
|
628
|
+
tools: turn.tools,
|
|
629
|
+
failed: turn.failed,
|
|
630
|
+
files: turn.files.slice(0, MAX_FILES).map(file => displayPath(file, cwd)),
|
|
631
|
+
// Model spend for this turn: how many responses, from which route, costing
|
|
632
|
+
// how many tokens. The built-in usage panel shows totals per turn but never
|
|
633
|
+
// the call count, which is what makes a turn feel expensive.
|
|
634
|
+
llm: (turn.calls ?? 0) > 0
|
|
635
|
+
? { calls: turn.calls, models: turn.models ?? [], usage: turn.usage ?? emptyUsage() }
|
|
636
|
+
: null,
|
|
637
|
+
// Decisions the person stated in their own words during this turn, quoted
|
|
638
|
+
// verbatim. This is the only place the card can show a decision the task list
|
|
639
|
+
// has no row for yet.
|
|
640
|
+
decisions: Array.isArray(turn.decisions) && turn.decisions.length > 0 ? turn.decisions : null,
|
|
641
|
+
// Whether this session ever wrote a task list at all. When it never has, an
|
|
642
|
+
// empty plan block is not a bug the reader should puzzle over, so the card can
|
|
643
|
+
// say so instead of staying silent.
|
|
644
|
+
sessionHasPlan: sessionHasPlan === true,
|
|
645
|
+
// The plan state this card reports: the turn's own list when it wrote one,
|
|
646
|
+
// otherwise the most recent list that was still in force, marked `stale`.
|
|
647
|
+
//
|
|
648
|
+
// Both extremes failed in practice. Rendering nothing for plan-less turns left
|
|
649
|
+
// most cards with no HUD at all ("改完后怎么什么都没了"). Rendering the *live*
|
|
650
|
+
// plan let a dozen cards repeat today's state with no explanation, which reads
|
|
651
|
+
// as frozen. Carrying the newest known list forward and labelling it is the
|
|
652
|
+
// honest middle: the reader sees the plan that was actually in force, and the
|
|
653
|
+
// badge says the turn itself did not update it.
|
|
654
|
+
plan: planFor(todos, prevTodos, maxRows, wroteEmpty === true, sourceTurn),
|
|
655
|
+
// A deliberately cleared plan is a real event worth reporting, not an absent
|
|
656
|
+
// one. Without this flag a cleared turn is indistinguishable from a turn that
|
|
657
|
+
// did nothing, so the reader cannot tell "they dropped the plan" from "we have
|
|
658
|
+
// no news".
|
|
659
|
+
cleared: wroteEmpty === true,
|
|
660
|
+
todo: null,
|
|
661
|
+
}
|
|
662
|
+
if (Array.isArray(todos) && todos.length > 0) {
|
|
663
|
+
const rows = []
|
|
664
|
+
let done = 0
|
|
665
|
+
let doing = 0
|
|
666
|
+
let left = 0
|
|
667
|
+
for (const item of todos) {
|
|
668
|
+
const status = item?.status === 'completed' ? 'done' : item?.status === 'in_progress' ? 'doing' : 'left'
|
|
669
|
+
if (status === 'done') done += 1
|
|
670
|
+
else if (status === 'doing') doing += 1
|
|
671
|
+
else left += 1
|
|
672
|
+
const content = String(item?.content ?? '')
|
|
673
|
+
if (rows.length < maxRows) rows.push({ s: status, c: rowTextOf(content), d: depthOf(content) })
|
|
674
|
+
}
|
|
675
|
+
const delta = finishedDuring(todos, prevTodos, HARD_MAX_ROWS)
|
|
676
|
+
entry.todo = {
|
|
677
|
+
total: todos.length,
|
|
678
|
+
done,
|
|
679
|
+
doing,
|
|
680
|
+
left,
|
|
681
|
+
updated: turn.todosUpdated,
|
|
682
|
+
more: Math.max(0, todos.length - rows.length),
|
|
683
|
+
rows,
|
|
684
|
+
finished: delta.finished,
|
|
685
|
+
finishedMore: delta.finishedMore,
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return entry
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* One todo item's display status.
|
|
693
|
+
* @param {object} item - a `todo_write` entry.
|
|
694
|
+
* @returns {'done'|'doing'|'left'} the status.
|
|
695
|
+
*/
|
|
696
|
+
function statusOf(item) {
|
|
697
|
+
if (item?.status === 'completed') return 'done'
|
|
698
|
+
if (item?.status === 'in_progress') return 'doing'
|
|
699
|
+
return 'left'
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* The task text of a todo line, with list markers and any 【stage】 prefix removed.
|
|
704
|
+
*
|
|
705
|
+
* The stage prefix already appears as its own section heading, so repeating it on
|
|
706
|
+
* every row wastes the scarce width a card has.
|
|
707
|
+
* @param {string} content - the raw todo line.
|
|
708
|
+
* @returns {string} the display text.
|
|
709
|
+
*/
|
|
710
|
+
function rowTextOf(content) {
|
|
711
|
+
const stripped = labelOf(content).replace(/^[【\[〔][^】\]〕]*[】\]〕]\s*/, '').trim()
|
|
712
|
+
return stripped === '' ? labelOf(content) : stripped
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Stage label carried by a todo line, if the author wrote one.
|
|
717
|
+
*
|
|
718
|
+
* `todo_write` has no stage field, so the stage has to travel inside the item text.
|
|
719
|
+
* Accepted forms, matched anywhere at the start of the line (after list markers):
|
|
720
|
+
* 【阶段一】做某事 〔P1〕做某事 [阶段2] 做某事
|
|
721
|
+
* The captured text is returned trimmed, without the brackets.
|
|
722
|
+
* @param {string} content - the raw todo line.
|
|
723
|
+
* @returns {string | null} the stage label, or null when the line has none.
|
|
724
|
+
*/
|
|
725
|
+
function stageOf(content) {
|
|
726
|
+
const bare = String(content).replace(/^[\s\u3000]+/, '').replace(/^(?:[-*•·]|\d+[.)])\s*/, '')
|
|
727
|
+
const m = bare.match(/^[【\[〔]\s*([^】\]〕]{1,24}?)\s*[】\]〕]\s*(.*)$/)
|
|
728
|
+
if (m === null) return null
|
|
729
|
+
return m[1].trim() === '' ? null : m[1].trim()
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* Whether a stage label reads as its own stage grouping key.
|
|
734
|
+
*
|
|
735
|
+
* Anything the author wrapped in brackets counts, so no vocabulary is imposed on
|
|
736
|
+
* the writer: 【阶段一】, 【P1】, 【调研】 all become sections.
|
|
737
|
+
* @param {string} content - the raw todo line.
|
|
738
|
+
* @returns {boolean} true when the line opens a stage.
|
|
739
|
+
*/
|
|
740
|
+
function hasStage(content) {
|
|
741
|
+
return stageOf(content) !== null
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* Group a todo list into the status bar's collapsible sections.
|
|
746
|
+
*
|
|
747
|
+
* Two grouping axes, in priority order:
|
|
748
|
+
*
|
|
749
|
+
* 1. **Stages** — when any line carries a 【label】 prefix, sections are the stages
|
|
750
|
+
* in the order they first appear, and each section's status is derived from its
|
|
751
|
+
* own items (all done → done, any in progress → doing, else left). This is what
|
|
752
|
+
* "已完成 / 进行中 / 待办" means to a reader: which *phases of the work* are in
|
|
753
|
+
* which state, not which individual tasks are.
|
|
754
|
+
* 2. **Status** — with no stage markers the list is bucketed by task status. Real
|
|
755
|
+
* `todo_write` payloads are flat (measured: 0 of 5 items carried indentation),
|
|
756
|
+
* so this is the common path and gives three stable slots.
|
|
757
|
+
*
|
|
758
|
+
* @param {object[]} todos - the whole list.
|
|
759
|
+
* @param {number} maxItems - how many rows to keep per section.
|
|
760
|
+
* @returns {{ groups: object[], more: number }} the sections and the omitted count.
|
|
761
|
+
*/
|
|
762
|
+
function groupTodos(todos, maxItems) {
|
|
763
|
+
const anyStage = todos.some(item => hasStage(item?.content ?? ''))
|
|
764
|
+
if (anyStage) return groupByStage(todos, maxItems)
|
|
765
|
+
return groupByStatus(todos, maxItems)
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Group by the 【stage】 prefixes the author wrote.
|
|
770
|
+
* @param {object[]} todos - the whole list.
|
|
771
|
+
* @param {number} maxItems - how many rows to keep per section.
|
|
772
|
+
* @returns {{ groups: object[], more: number }} the sections and the omitted count.
|
|
773
|
+
*/
|
|
774
|
+
function groupByStage(todos, maxItems) {
|
|
775
|
+
const sections = new Map()
|
|
776
|
+
let omitted = 0
|
|
777
|
+
for (const item of todos) {
|
|
778
|
+
const content = String(item?.content ?? '')
|
|
779
|
+
const stage = stageOf(content) ?? '其他'
|
|
780
|
+
const status = statusOf(item)
|
|
781
|
+
let section = sections.get(stage)
|
|
782
|
+
if (section === undefined) {
|
|
783
|
+
section = { label: stage, rows: [], done: 0, doing: 0, left: 0 }
|
|
784
|
+
sections.set(stage, section)
|
|
785
|
+
}
|
|
786
|
+
if (status === 'done') section.done += 1
|
|
787
|
+
else if (status === 'doing') section.doing += 1
|
|
788
|
+
else section.left += 1
|
|
789
|
+
// The stage label itself is not a task row; store the remainder of the line.
|
|
790
|
+
if (section.rows.length < maxItems) {
|
|
791
|
+
section.rows.push({ c: rowTextOf(content), s: status, d: depthOf(content) })
|
|
792
|
+
} else {
|
|
793
|
+
omitted += 1
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
const groups = [...sections.values()].map((section, index) => {
|
|
797
|
+
const total = section.done + section.doing + section.left
|
|
798
|
+
// A stage is in whatever state its own items are: fully done beats running.
|
|
799
|
+
const state = total > 0 && section.done === total ? 'done' : section.doing > 0 ? 'doing' : 'left'
|
|
800
|
+
return {
|
|
801
|
+
k: 'stage-' + index,
|
|
802
|
+
t: section.label,
|
|
803
|
+
s: state,
|
|
804
|
+
total,
|
|
805
|
+
done: section.done,
|
|
806
|
+
empty: total === 0,
|
|
807
|
+
children: section.rows,
|
|
808
|
+
collapsible: section.rows.length > 1,
|
|
809
|
+
startOpen: state !== 'done',
|
|
810
|
+
stage: true,
|
|
811
|
+
}
|
|
812
|
+
})
|
|
813
|
+
return { groups, more: omitted }
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/**
|
|
817
|
+
* Group by task status — the fallback when no stage markers are present.
|
|
818
|
+
* @param {object[]} todos - the whole list.
|
|
819
|
+
* @param {number} maxItems - how many rows to keep per section.
|
|
820
|
+
* @returns {{ groups: object[], more: number }} the sections and the omitted count.
|
|
821
|
+
*/
|
|
822
|
+
function groupByStatus(todos, maxItems) {
|
|
823
|
+
const buckets = {
|
|
824
|
+
done: { key: 'done', t: '已完成', s: 'done', rows: [], collapsedByDefault: true },
|
|
825
|
+
doing: { key: 'doing', t: '进行中', s: 'doing', rows: [], collapsedByDefault: false },
|
|
826
|
+
left: { key: 'left', t: '待办', s: 'left', rows: [], collapsedByDefault: false },
|
|
827
|
+
}
|
|
828
|
+
const SLOT_ORDER = ['done', 'doing', 'left']
|
|
829
|
+
const order = []
|
|
830
|
+
let omitted = 0
|
|
831
|
+
for (const item of todos) {
|
|
832
|
+
const content = String(item?.content ?? '')
|
|
833
|
+
const status = statusOf(item)
|
|
834
|
+
const bucket = buckets[status]
|
|
835
|
+
if (order.includes(bucket) === false) order.push(bucket)
|
|
836
|
+
if (bucket.rows.length < maxItems) {
|
|
837
|
+
bucket.rows.push({ c: labelOf(content), s: status, d: depthOf(content) })
|
|
838
|
+
} else {
|
|
839
|
+
omitted += 1
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
// Every slot is always present and in a fixed order, independent of which
|
|
843
|
+
// statuses happened to occur — otherwise an all-done list would render
|
|
844
|
+
// done → left → doing and the HUD would shift between turns. An empty slot that
|
|
845
|
+
// stays put reads as "nothing here right now"; one that vanishes reads as lost
|
|
846
|
+
// data, which is exactly how the missing 待办/进行中 was reported.
|
|
847
|
+
const ordered = SLOT_ORDER.map(key => buckets[key])
|
|
848
|
+
const groups = ordered.map((bucket) => {
|
|
849
|
+
const total = bucket.rows.length + 0
|
|
850
|
+
const doneRows = bucket.rows.filter(row => row.s === 'done').length
|
|
851
|
+
return {
|
|
852
|
+
k: bucket.key,
|
|
853
|
+
t: bucket.t,
|
|
854
|
+
s: bucket.s,
|
|
855
|
+
total,
|
|
856
|
+
done: doneRows,
|
|
857
|
+
empty: bucket.rows.length === 0,
|
|
858
|
+
children: bucket.rows.map(row => ({ c: row.c, s: row.s, d: row.d })),
|
|
859
|
+
// A section with one item cannot usefully fold; two or more can.
|
|
860
|
+
collapsible: bucket.rows.length > 1,
|
|
861
|
+
startOpen: bucket.collapsedByDefault === false,
|
|
862
|
+
}
|
|
863
|
+
})
|
|
864
|
+
return { groups, more: omitted }
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* Register the `turnReport` projection.
|
|
869
|
+
* @param {object} ctx - host context carrying the projection registry.
|
|
870
|
+
* @param {object} config - the resolved plugin configuration.
|
|
871
|
+
* @returns {Promise<void>} when the projection is registered.
|
|
872
|
+
*/
|
|
873
|
+
export async function apply(ctx, config) {
|
|
874
|
+
// The host validates a row before activation, but activation must not depend on
|
|
875
|
+
// that: resolve here too so aliases and defaults hold either way.
|
|
876
|
+
const resolved = resolveConfig(config).settings
|
|
877
|
+
const maxRows = resolved.maxRows
|
|
878
|
+
|
|
879
|
+
/** Empty fold state: no open turn, no todo list seen yet, no closed turn. */
|
|
880
|
+
const initState = () => ({ turns: {}, order: [], cur: null, todos: null, prevTodos: null, todosTurn: null, cwd: undefined })
|
|
881
|
+
|
|
882
|
+
// One unit definition serves every session, so the view cache is keyed by the
|
|
883
|
+
// immutable state object itself rather than by a single slot: `apply` replaces
|
|
884
|
+
// the state on change, which makes the object an exact identity for its value.
|
|
885
|
+
const wireCache = new WeakMap()
|
|
886
|
+
|
|
887
|
+
const stateSchema = {
|
|
888
|
+
parse(value) {
|
|
889
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
890
|
+
throw new TypeError('turnReport state must be an object')
|
|
891
|
+
}
|
|
892
|
+
return value
|
|
893
|
+
},
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
const viewSchema = {
|
|
897
|
+
parse(value) {
|
|
898
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
899
|
+
throw new TypeError('turnReport view must be an object')
|
|
900
|
+
}
|
|
901
|
+
return value
|
|
902
|
+
},
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
await ctx.sessionProjections.register({
|
|
906
|
+
key: KEY,
|
|
907
|
+
stateSchema,
|
|
908
|
+
init: header => ({ ...initState(), cwd: header?.cwd }),
|
|
909
|
+
apply(state, event) {
|
|
910
|
+
switch (event.type) {
|
|
911
|
+
case 'turn/start': {
|
|
912
|
+
// Mirror the host's own `todos` projection: the list is per-turn, and a
|
|
913
|
+
// turn that never calls `todo_write` has no plan of its own. Keeping the
|
|
914
|
+
// previous turn's list as the current one would report old work as if it
|
|
915
|
+
// were current — but it is kept aside, because "what this turn newly
|
|
916
|
+
// finished" can only be known by comparing against it.
|
|
917
|
+
//
|
|
918
|
+
// `prevTodos` must NOT be overwritten with null when the closing turn had
|
|
919
|
+
// no list of its own: otherwise two plan-less turns in a row erase the
|
|
920
|
+
// last real plan, and a session that wrote its list 20 turns ago loses it
|
|
921
|
+
// entirely. Carry the newest non-null plan forward instead.
|
|
922
|
+
return {
|
|
923
|
+
...state,
|
|
924
|
+
todos: null,
|
|
925
|
+
prevTodos: state.todos === null ? state.prevTodos : state.todos,
|
|
926
|
+
cur: {
|
|
927
|
+
n: event.data.turn,
|
|
928
|
+
tools: 0,
|
|
929
|
+
failed: 0,
|
|
930
|
+
files: [],
|
|
931
|
+
todosUpdated: false,
|
|
932
|
+
wroteEmpty: false,
|
|
933
|
+
decisions: [],
|
|
934
|
+
calls: 0,
|
|
935
|
+
usage: emptyUsage(),
|
|
936
|
+
models: [],
|
|
937
|
+
},
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
case 'user/message': {
|
|
941
|
+
// The only event that can carry a human decision. `todo_write` records
|
|
942
|
+
// tasks, not intent, so a person saying "先建私有仓,明天再发 npm" leaves
|
|
943
|
+
// no trace in the task list until the next write — and often not even then.
|
|
944
|
+
// Quoting them here is what lets the card show a decision the plan has not
|
|
945
|
+
// caught up with yet.
|
|
946
|
+
const cur = state.cur
|
|
947
|
+
if (cur === null) return state
|
|
948
|
+
const text = humanTextOf(event)
|
|
949
|
+
if (text === null) return state
|
|
950
|
+
const decision = decisionOf(text)
|
|
951
|
+
if (decision === null) return state
|
|
952
|
+
// A retraction clears the turn's pending quotes instead of adding one:
|
|
953
|
+
// "方案 A" followed by "刚才的决定撤回" must leave nothing behind.
|
|
954
|
+
if (decision.retract === true) {
|
|
955
|
+
return cur.decisions.length === 0 ? state : { ...state, cur: { ...cur, decisions: [] } }
|
|
956
|
+
}
|
|
957
|
+
if (cur.decisions.includes(decision.quote)) return state
|
|
958
|
+
return { ...state, cur: { ...cur, decisions: [...cur.decisions, decision.quote].slice(-MAX_DECISIONS) } }
|
|
959
|
+
}
|
|
960
|
+
case 'assistant/message': {
|
|
961
|
+
// One finished model response. This is the only event pairing a billed
|
|
962
|
+
// attempt with its exact usage, so it is both the call count and the
|
|
963
|
+
// token source. `assistant/attempt` also fires for retries that produced
|
|
964
|
+
// no message, which would overstate "how many times the model answered".
|
|
965
|
+
const cur = state.cur
|
|
966
|
+
if (cur === null) return state
|
|
967
|
+
const usage = addUsage(cur.usage, event.data?.usage)
|
|
968
|
+
const route = routeOf(event)
|
|
969
|
+
const models = route === undefined || cur.models.includes(route)
|
|
970
|
+
? cur.models
|
|
971
|
+
: [...cur.models, route]
|
|
972
|
+
return { ...state, cur: { ...cur, calls: cur.calls + 1, usage, models } }
|
|
973
|
+
}
|
|
974
|
+
case 'todo/write': {
|
|
975
|
+
const todos = Array.isArray(event.data?.todos) ? event.data.todos : null
|
|
976
|
+
if (todos === null) return state
|
|
977
|
+
// `todosUpdated` alone cannot distinguish "wrote a list" from "wrote an
|
|
978
|
+
// empty list": both set it. `wroteEmpty` is what lets a cleared plan stop
|
|
979
|
+
// being carried forward instead of reappearing as a stale plan.
|
|
980
|
+
const wroteEmpty = todos.length === 0
|
|
981
|
+
return {
|
|
982
|
+
...state,
|
|
983
|
+
todos,
|
|
984
|
+
todosTurn: wroteEmpty ? state.todosTurn : (state.cur === null ? state.todosTurn : state.cur.n),
|
|
985
|
+
cur: state.cur === null ? null : { ...state.cur, todosUpdated: true, wroteEmpty },
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
case 'tool/call': {
|
|
989
|
+
const cur = state.cur
|
|
990
|
+
if (cur === null) return state
|
|
991
|
+
const file = fileOf(event.data?.name, event.data?.arguments)
|
|
992
|
+
const files = file === undefined || cur.files.includes(file)
|
|
993
|
+
? cur.files
|
|
994
|
+
: [...cur.files, file].slice(-MAX_FILES)
|
|
995
|
+
return { ...state, cur: { ...cur, tools: cur.tools + 1, files } }
|
|
996
|
+
}
|
|
997
|
+
case 'tool/result': {
|
|
998
|
+
const cur = state.cur
|
|
999
|
+
if (cur === null || event.data?.message?.isError !== true) return state
|
|
1000
|
+
return { ...state, cur: { ...cur, failed: cur.failed + 1 } }
|
|
1001
|
+
}
|
|
1002
|
+
case 'turn/end': {
|
|
1003
|
+
const n = event.data?.turn
|
|
1004
|
+
const endKind = event.data?.reason?.kind ?? 'completed'
|
|
1005
|
+
const live = state.cur !== null && state.cur.n === n
|
|
1006
|
+
? state.cur
|
|
1007
|
+
: { n, tools: 0, failed: 0, files: [], todosUpdated: false, wroteEmpty: false, decisions: [], calls: 0, usage: emptyUsage(), models: [] }
|
|
1008
|
+
const entry = freezeTurn(live, endKind, state.todos, state.prevTodos, maxRows, state.cwd, live.wroteEmpty, state.todos === null ? state.todosTurn : n, state.todosTurn !== null)
|
|
1009
|
+
const turns = { ...state.turns, [String(n)]: entry }
|
|
1010
|
+
let order = [...state.order.filter(value => value !== n), n]
|
|
1011
|
+
if (order.length > MAX_TURNS) {
|
|
1012
|
+
const dropped = order.slice(0, order.length - MAX_TURNS)
|
|
1013
|
+
order = order.slice(order.length - MAX_TURNS)
|
|
1014
|
+
for (const old of dropped) delete turns[String(old)]
|
|
1015
|
+
}
|
|
1016
|
+
return { ...state, turns, order, cur: null }
|
|
1017
|
+
}
|
|
1018
|
+
default:
|
|
1019
|
+
return state
|
|
1020
|
+
}
|
|
1021
|
+
},
|
|
1022
|
+
wire: {
|
|
1023
|
+
viewSchema,
|
|
1024
|
+
summary: false,
|
|
1025
|
+
view(state) {
|
|
1026
|
+
const cached = wireCache.get(state)
|
|
1027
|
+
if (cached !== undefined) return cached
|
|
1028
|
+
const wire = {
|
|
1029
|
+
v: 1,
|
|
1030
|
+
turns: state.turns,
|
|
1031
|
+
// Live plan state for the status bar. Separate from `turns` on purpose:
|
|
1032
|
+
// `turns` is frozen history, this is the plan as it stands right now.
|
|
1033
|
+
live: livePlan(state, maxRows),
|
|
1034
|
+
opts: {
|
|
1035
|
+
showTree: resolved.showTree !== false,
|
|
1036
|
+
showFiles: resolved.showFiles !== false,
|
|
1037
|
+
showWithoutTasks: resolved.showWithoutTasks === true,
|
|
1038
|
+
showFinished: resolved.showFinished !== false,
|
|
1039
|
+
showLlm: resolved.showLlm !== false,
|
|
1040
|
+
showStatusBar: resolved.showStatusBar !== false,
|
|
1041
|
+
statusBarOpen: resolved.statusBarOpen !== false,
|
|
1042
|
+
replaceNativeTodo: resolved.replaceNativeTodo !== false,
|
|
1043
|
+
todoView: resolved.todoView ?? 'auto',
|
|
1044
|
+
},
|
|
1045
|
+
}
|
|
1046
|
+
wireCache.set(state, wire)
|
|
1047
|
+
return wire
|
|
1048
|
+
},
|
|
1049
|
+
},
|
|
1050
|
+
stateVersion: STATE_VERSION,
|
|
1051
|
+
})
|
|
1052
|
+
}
|