@niracler/encore 0.1.0 → 0.3.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/src/timeline.mjs CHANGED
@@ -32,13 +32,21 @@ function resolveWindowCapacity(tool = 'codex', model = '', contextWindow = 0) {
32
32
  return { tokens: 200000, label: '200k' }
33
33
  }
34
34
 
35
- export function kindOf(stats = {}) {
35
+ export function kindOf(stats = {}, fallbackKind = '') {
36
+ if (fallbackKind && kinds[fallbackKind]) return kinds[fallbackKind]
36
37
  const found = Object.keys(stats).map(key => kinds[key] || 'make')
37
38
  return order.find(kind => found.includes(kind)) || 'make'
38
39
  }
39
40
 
40
41
  function extractSkillNames(item, knownSkills = new Set()) {
41
42
  const names = new Set()
43
+ if (typeof item.skill === 'string' && item.skill.trim()) {
44
+ names.add(item.skill.trim())
45
+ } else if (Array.isArray(item.skill)) {
46
+ for (const entry of item.skill) {
47
+ if (typeof entry === 'string' && entry.trim()) names.add(entry.trim())
48
+ }
49
+ }
42
50
  const text = `${item.text || ''}\n${item.summary || ''}\n${item.input || ''}`
43
51
  const known = new Set([
44
52
  ...knownSkills,
@@ -59,83 +67,112 @@ function extractFileChips(work) {
59
67
  const tools = []
60
68
  const changes = []
61
69
  const memories = []
70
+ const pushTarget = (rawTarget, isEdit) => {
71
+ const target = String(rawTarget || '').trim().split(/[/\\]/).pop()
72
+ if (!target) return
73
+ if (/AGENTS\.md|CLAUDE\.md|memory/i.test(target)) memories.push(target)
74
+ else tools.push(target)
75
+ if (isEdit) changes.push(target)
76
+ }
62
77
  for (const item of work) {
78
+ const isEdit = Boolean(item.kind === 'edit' || item.stats?.edit)
79
+ const explicitFiles = [
80
+ ...(typeof item.file === 'string' && item.file.trim() ? [item.file.trim()] : []),
81
+ ...(Array.isArray(item.files) ? item.files : []),
82
+ ]
63
83
  const summary = String(item.summary || '')
64
84
  const input = String(item.input || '')
65
- for (const match of summary.matchAll(/(?:读取|写入|修改|查看)\s+([^\s,;,]+)/g)) {
66
- const target = match[1].trim()
67
- if (!target) continue
68
- if (/AGENTS\.md|CLAUDE\.md|memory/i.test(target)) memories.push(target)
69
- else tools.push(target)
70
- if (summary.startsWith('写入') || summary.startsWith('修改')) changes.push(target)
71
- }
72
- for (const match of input.matchAll(/\*\*\* (?:Add|Update|Delete) File: ([^\n\\"]+)/g)) {
73
- const name = match[1].trim().split('/').pop()
74
- if (name) {
75
- tools.push(name)
76
- changes.push(name)
85
+ if (explicitFiles.length) {
86
+ for (const f of [...new Set(explicitFiles)]) pushTarget(f, isEdit)
87
+ } else {
88
+ for (const match of summary.matchAll(/(?:读取|写入|修改|查看)\s+([^\s,;,]+)/g)) {
89
+ pushTarget(match[1], summary.startsWith('写入') || summary.startsWith('修改') || isEdit)
90
+ }
91
+ for (const match of input.matchAll(/\*\*\* (?:Add|Update|Delete) File: ([^\n\\"]+)/g)) {
92
+ pushTarget(match[1], true)
93
+ }
94
+ for (const match of input.matchAll(/"(?:file_path|path)"\s*:\s*"([^"]+)"/g)) {
95
+ pushTarget(match[1], isEdit)
77
96
  }
78
97
  }
79
- for (const match of input.matchAll(/"(?:file_path|path)"\s*:\s*"([^"]+)"/g)) {
80
- const name = match[1].trim().split('/').pop()
81
- if (!name) continue
82
- if (/AGENTS\.md|CLAUDE\.md|memory/i.test(name)) memories.push(name)
83
- else tools.push(name)
84
- if (item.stats?.edit) changes.push(name)
85
- }
86
- if (!tools.length && summary) tools.push(summary.slice(0, 28))
98
+ }
99
+ if (!tools.length && work[0]?.summary) {
100
+ tools.push(String(work[0].summary).slice(0, 28))
87
101
  }
88
102
  return { tools, changes, memories }
89
103
  }
90
104
 
105
+ function documentEdits(item) {
106
+ const input = String(item.input || '').trim()
107
+ if (!input) return []
108
+ const isEdit = item.kind === 'edit' || item.stats?.edit
109
+ const summaryFile = String(item.summary || '').match(/^(?:写入|修改|Write|Edit)\s+([^\s、,]+\.md)(?:\s|$)/i)?.[1]
110
+ if (!isEdit && !summaryFile && item.name !== 'apply_patch') return []
111
+ if (!/^\*\*\* Begin Patch\b/.test(input)) {
112
+ const path = isEdit && typeof item.file === 'string' && /\.md$/i.test(item.file.trim())
113
+ ? item.file.trim() : summaryFile
114
+ return path ? [{ path, content: input }] : []
115
+ }
116
+
117
+ const edits = []
118
+ let current
119
+ for (const line of input.split(/\r?\n/)) {
120
+ const header = line.match(/^\*\*\* (Add|Update|Delete) File: (.+)$/)
121
+ if (header) {
122
+ current = undefined
123
+ if (header[1] !== 'Delete') {
124
+ current = { path: header[2].trim(), lines: [] }
125
+ edits.push(current)
126
+ }
127
+ } else if (line === '*** End Patch') {
128
+ break
129
+ } else if (line.startsWith('…(中间省略 ')) {
130
+ // A clipped section may contain a file header. Wait for the next one.
131
+ current = undefined
132
+ } else if (current && line.startsWith('*** Move to: ')) {
133
+ current.path = line.slice('*** Move to: '.length).trim()
134
+ } else if (current && /^[+ ]/.test(line)) {
135
+ current.lines.push(line.slice(1))
136
+ }
137
+ }
138
+ return edits.map(({ path, lines }) => ({ path, content: lines.join('\n').trim() }))
139
+ }
140
+
91
141
  function extractStepDocs(toolItems, stepIndex) {
92
- const byFile = new Map()
142
+ const byPath = new Map()
93
143
  toolItems.forEach((item, idx) => {
94
- if (!item.input) return
95
- const m = String(item.summary || '').match(/^(?:写入|修改|Write|Edit)\s+([^\s、,]+\.md)(?:\s|$)/i)
96
- if (!m) return
97
- const file = m[1]
98
- if (file.startsWith('_') || /^\d{4}-\d{2}-\d{2}\.md$/.test(file)) return
99
- let content = String(item.input).trim()
100
- if (/^\*\*\* Begin Patch\b/.test(content)) {
101
- const bodyLines = content
102
- .split('\n')
103
- .filter(line => !/^(\*\*\* (?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)|@@)/.test(line) && !line.startsWith('-'))
104
- .map(line => (line.startsWith('+') || line.startsWith(' ')) ? line.slice(1) : line)
105
- content = bodyLines.join('\n').trim()
144
+ for (const [part, { path, content }] of documentEdits(item).entries()) {
145
+ const file = path.split(/[/\\]/).pop()
146
+ if (!/\.md$/i.test(file) || file.startsWith('_') || /^\d{4}-\d{2}-\d{2}\.md$/.test(file)) continue
147
+ const fm = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/)
148
+ const body = fm ? fm[2].trim() : content
149
+ const heading = body.match(/^#{1,3}\s+([^\r\n]+)/m)?.[1]?.replace(/^#+\s*/, '').trim()
150
+ const title = heading || fm?.[1].match(/^\s*title\s*:\s*['"]?([^\r\n'"]+)['"]?\s*$/m)?.[1]?.trim()
151
+ if (!title) continue
152
+ byPath.set(path, {
153
+ id: part ? `doc-${stepIndex}-${idx}-${part}` : `doc-${stepIndex}-${idx}`,
154
+ file,
155
+ title,
156
+ chars: content.length,
157
+ content: body || content,
158
+ t: item.t || 0,
159
+ })
106
160
  }
107
- let bodyWithoutFm = content
108
- let fmTitle = ''
109
- const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/)
110
- if (fmMatch) {
111
- fmTitle = fmMatch[1].match(/^\s*title\s*:\s*['"]?([^\r\n'"]+)['"]?\s*$/m)?.[1]?.trim() || ''
112
- bodyWithoutFm = fmMatch[2].trim()
113
- }
114
- const headingMatch = bodyWithoutFm.match(/^#{1,3}\s+([^\r\n]+)/m)
115
- if (!headingMatch && !fmTitle) return
116
- const title = (headingMatch ? headingMatch[1].replace(/^#+\s*/, '').trim() : fmTitle) || file
117
- byFile.set(file, {
118
- id: `doc-${stepIndex}-${idx}`,
119
- file,
120
- title,
121
- chars: content.length,
122
- content: bodyWithoutFm || content,
123
- t: item.t || 0,
124
- })
125
161
  })
126
- return [...byFile.values()]
162
+ return [...byPath.values()]
127
163
  }
128
164
 
129
- function extractStepSubagents(toolItems, stepIndex) {
165
+ function extractStepSubagents(toolItems, stepIndex, t) {
130
166
  const list = []
131
167
  toolItems.forEach((item, idx) => {
132
168
  const rawSum = String(item.summary || '')
133
169
  const isSub = Boolean(
170
+ item.kind === 'agent' ||
134
171
  item.stats?.agent ||
135
172
  item.agent ||
136
173
  item.name === 'agent_message' ||
137
174
  item.name === 'agent-message' ||
138
- (item.stats?.reply && /Agent\s+"|^子任务/.test(rawSum) && !/Background command/i.test(rawSum))
175
+ ((item.kind === 'reply' || item.stats?.reply) && /Agent\s+"|^子任务/.test(rawSum) && !/Background command/i.test(rawSum))
139
176
  )
140
177
  if (!isSub) return
141
178
  const label = (
@@ -146,21 +183,22 @@ function extractStepSubagents(toolItems, stepIndex) {
146
183
  .replace(/\s+交回结果$/, '')
147
184
  .trim()
148
185
  )
149
- if (!label || /^给子任务发消息/.test(rawSum)) return
186
+ const isSendMsg = /^(?:send_message|collaboration__send_message)$/.test(item.name || '')
187
+ if (!label || isSendMsg || /^给子任务发消息/.test(rawSum)) return
150
188
  const combined = `${rawSum}\n${item.output || ''}`
151
189
  const isAsyncSpawn = /^(?:spawn_agent|collaboration__spawn_agent|followup_task|collaboration__followup_task)$/.test(item.name || '')
152
190
  let state = 'sent'
153
- let badge = '派出'
191
+ let badge = t('agentSent')
154
192
  let report = ''
155
193
  if (/was stopped|中途打断|已取消/i.test(combined)) {
156
194
  state = 'stopped'
157
- badge = '已叫停'
195
+ badge = t('agentStopped')
158
196
  } else if (/failed:|terminated early|rate_limit|hit your session limit|^Error:\s*Failed/im.test(combined)) {
159
197
  state = 'failed'
160
- badge = /limit|429/i.test(combined) ? '额度中断' : '失败'
161
- } else if (item.stats?.reply || (!isAsyncSpawn && item.output && item.output.length > 80 && !item.output.trim().startsWith('{'))) {
198
+ badge = /limit|429/i.test(combined) ? t('agentRateLimited') : t('agentFailed')
199
+ } else if (item.kind === 'reply' || item.stats?.reply || (!isAsyncSpawn && item.output && item.output.length > 80 && !item.output.trim().startsWith('{'))) {
162
200
  state = 'done'
163
- badge = '已交回'
201
+ badge = t('agentDone')
164
202
  if (item.output && item.output.length > 40 && !item.output.trim().startsWith('{')) {
165
203
  report = String(item.output).trim()
166
204
  }
@@ -213,6 +251,28 @@ function defaultSystemPrompts(toolName) {
213
251
  },
214
252
  ]
215
253
  }
254
+ if (toolName === 'workbuddy') {
255
+ return [
256
+ {
257
+ id: 'sys-core',
258
+ stepIndex: -1,
259
+ tokEst: 3200,
260
+ tag: 'Core',
261
+ title: 'WorkBuddy Desktop Agent · Core Role & Execution Rules',
262
+ meta: '≈3.2k · Initial',
263
+ payload: `You are WorkBuddy, a desktop agent bound to the active local workspace directory.\n\n# Core Responsibilities\n1. Search and read workspace documents, spreadsheets, PDFs, and images on demand; ground answers in primary sources.\n2. Decompose complex research into parallel sub-tasks and synthesize verified deliverables.\n3. Confirm with the user before overwriting formal documents or sending external messages.`,
264
+ },
265
+ {
266
+ id: 'sys-workspace',
267
+ stepIndex: -1,
268
+ tokEst: 1800,
269
+ tag: 'Workspace',
270
+ title: 'Workspace File I/O & Deliverable Conventions',
271
+ meta: '≈1.8k · Initial',
272
+ payload: `# Workspace Conventions\n- Inspect directory structure and project notes before modifying files.\n- Save intermediate drafts, tables, and final reports under the designated workspace path.`,
273
+ },
274
+ ]
275
+ }
216
276
  return [
217
277
  {
218
278
  id: 'sys-core',
@@ -244,6 +304,14 @@ function defaultToolSchemas(toolName) {
244
304
  { id: 'schema-agent-skill', stepIndex: -1, tokEst: 2000, tag: 'Schema', title: 'Agent / Skill / TodoWrite · Delegation & Skills', meta: '≈2.0k · Schema', payload: '{\n "tools": ["Agent", "Skill", "TodoWrite"]\n}' },
245
305
  ]
246
306
  }
307
+ if (toolName === 'workbuddy') {
308
+ return [
309
+ { id: 'schema-wb-read', stepIndex: -1, tokEst: 1800, tag: 'Schema', title: 'read_file / list_dir · Workspace Document Reader', meta: '≈1.8k · Schema', payload: '{\n "tools": ["read_file", "list_dir"]\n}' },
310
+ { id: 'schema-wb-write', stepIndex: -1, tokEst: 1900, tag: 'Schema', title: 'write_file / edit_file · Deliverable & Note Writer', meta: '≈1.9k · Schema', payload: '{\n "tools": ["write_file", "edit_file"]\n}' },
311
+ { id: 'schema-wb-web', stepIndex: -1, tokEst: 2000, tag: 'Schema', title: 'web_search / run_command · Web Research & Scripts', meta: '≈2.0k · Schema', payload: '{\n "tools": ["web_search", "run_command"]\n}' },
312
+ { id: 'schema-wb-agent', stepIndex: -1, tokEst: 2100, tag: 'Schema', title: 'Agent · Parallel Research Sub-tasks', meta: '≈2.1k · Schema', payload: '{\n "tools": ["Agent"]\n}' },
313
+ ]
314
+ }
247
315
  return [
248
316
  { id: 'schema-exec', stepIndex: -1, tokEst: 2200, tag: 'Schema', title: 'exec_command / write_stdin · Shell Execution', meta: '≈2.2k · Schema', payload: '{\n "name": "exec_command",\n "parameters": { "cmd": "string", "workdir": "string" }\n}' },
249
317
  { id: 'schema-patch', stepIndex: -1, tokEst: 2100, tag: 'Schema', title: 'apply_patch · Freeform File Patching', meta: '≈2.1k · Schema', payload: '{\n "name": "apply_patch",\n "grammar": "*** Begin Patch ... *** End Patch"\n}' },
@@ -394,7 +462,9 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
394
462
  }
395
463
  for (const item of items) {
396
464
  if (item.type === 'tool' || item.type === 'reasoning') {
465
+ if (item.deliverables?.length) flushWork()
397
466
  work.push(item)
467
+ if (item.deliverables?.length) flushWork()
398
468
  continue
399
469
  }
400
470
  flushWork()
@@ -504,7 +574,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
504
574
  name,
505
575
  color,
506
576
  itemCount: records.length,
507
- count: `${records.length} Items`,
577
+ count: t('itemCount', { n: records.length }),
508
578
  tok: `≈${(curTok / 1000).toFixed(1)}k`,
509
579
  pct: `${kindPct(curTok)}%`,
510
580
  delta: stepIdx >= 0 ? fmtCountDelta(records.length, prevCount) : '',
@@ -614,8 +684,8 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
614
684
  id: `user-${userSeq}`,
615
685
  stepIndex: index,
616
686
  tokEst: userTok,
617
- tag: `Turn #${turnCount}`,
618
- title: cleanPromptText.slice(0, 56) || 'User message',
687
+ tag: t('turnTag', { n: turnCount }),
688
+ title: cleanPromptText.slice(0, 56) || t('userMessage'),
619
689
  meta: `≈${(userTok / 1000).toFixed(1)}k · ${stepTime}s`,
620
690
  payload: String(first.text || ''),
621
691
  ...(first.images?.length ? { images: first.images } : {}),
@@ -632,7 +702,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
632
702
  tokEst: skTok,
633
703
  tag: 'SKILL.md',
634
704
  title: `${skill}/SKILL.md`,
635
- meta: `≈${(skTok / 1000).toFixed(1)}k · Turn #${turnCount}`,
705
+ meta: `≈${(skTok / 1000).toFixed(1)}k · ${t('turnTag', { n: turnCount })}`,
636
706
  payload: `# ${skill} (SKILL.md)\nLoaded into active context.`,
637
707
  }))
638
708
  }
@@ -641,10 +711,10 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
641
711
  primaryCat = 'user'
642
712
  speedLabel = '1.0×'
643
713
  dwellMs = 1500
644
- detailTitle = `Prompt #${turnCount}`
714
+ detailTitle = t('promptTitle', { n: turnCount })
645
715
  detailSnippet = (first.text || '').slice(0, 260)
646
- inBrief = 'User message appended to context'
647
- responseBrief = 'Waiting for Agent reasoning & tool calls'
716
+ inBrief = t('appendedPrompt')
717
+ responseBrief = t('waitingForTools')
648
718
  } else if (group.groupType === 'compact') {
649
719
  compactSeq++
650
720
  const cItem = first
@@ -697,10 +767,10 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
697
767
  speedLabel = '0.8×'
698
768
  dwellMs = 2100
699
769
  spotlight = 'context-compact'
700
- detailTitle = `Context Compaction #${compactInfo.seq}`
770
+ detailTitle = t('compactTitle', { seq: compactInfo.seq })
701
771
  detailSnippet = summaryText.slice(0, 260)
702
772
  inBrief = `${(preTokens / 1000).toFixed(1)}k → ${(postTokens / 1000).toFixed(1)}k`
703
- responseBrief = `Archived ${archivedTools} tool outputs (-${(droppedTokens / 1000).toFixed(1)}k tokens)`
773
+ responseBrief = t('archivedTools', { n: archivedTools, tokens: (droppedTokens / 1000).toFixed(1) })
704
774
  } else if (group.groupType === 'assistant') {
705
775
  msgSeq++
706
776
  const cleanReply = (first.text || '').replace(/\s+/g, ' ').trim()
@@ -711,8 +781,8 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
711
781
  id: `msg-${msgSeq}`,
712
782
  stepIndex: index,
713
783
  tokEst: msgTok,
714
- tag: `Reply #${msgSeq}`,
715
- title: cleanReply.slice(0, 56) || 'Assistant reply',
784
+ tag: t('replyTag', { n: msgSeq }),
785
+ title: cleanReply.slice(0, 56) || t('assistantReply'),
716
786
  meta: `≈${(msgTok / 1000).toFixed(1)}k · ${stepTime}s`,
717
787
  payload: String(first.text || ''),
718
788
  }))
@@ -726,17 +796,17 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
726
796
  primaryCat = 'msg'
727
797
  speedLabel = '1.0×'
728
798
  dwellMs = 1750
729
- detailTitle = 'Assistant Response'
799
+ detailTitle = t('assistantReply')
730
800
  detailSnippet = (first.text || '').slice(0, 260)
731
- inBrief = allTools.length ? `Synthesizing (${allTools.slice(-2).join(', ')})` : 'Direct response'
732
- responseBrief = cleanReply.slice(0, 96) || 'Completed response'
801
+ inBrief = allTools.length ? t('synthesizing', { tools: allTools.slice(-2).join(', ') }) : t('directResponse')
802
+ responseBrief = cleanReply.slice(0, 96) || t('completedResponse')
733
803
  } else {
734
804
  const toolItems = group.items.filter(item => item.type === 'tool')
735
805
  const reasoningItems = group.items.filter(item => item.type === 'reasoning')
736
806
  const stats = sumStats(toolItems)
737
807
  const extracted = extractFileChips(toolItems)
738
808
  stepDocs = extractStepDocs(toolItems, index)
739
- stepSubagents = extractStepSubagents(toolItems, index)
809
+ stepSubagents = extractStepSubagents(toolItems, index, t)
740
810
  stepAudios = extractStepAudios(toolItems, t)
741
811
  allTools.push(...extracted.tools)
742
812
  allChanges.push(...extracted.changes)
@@ -751,9 +821,9 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
751
821
  id: `mem-dyn-${memRecords.length + 1}`,
752
822
  stepIndex: index,
753
823
  tokEst: memTok,
754
- tag: 'Rule',
824
+ tag: t('rule'),
755
825
  title: `${memName}`,
756
- meta: `≈${(memTok / 1000).toFixed(1)}k · Step ${index + 1}`,
826
+ meta: `≈${(memTok / 1000).toFixed(1)}k · ${t('stepTag', { n: index + 1 })}`,
757
827
  payload: `# ${memName}\nLoaded into context during step ${index + 1}.`,
758
828
  }))
759
829
  }
@@ -769,9 +839,9 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
769
839
  id: `think-${msgSeq}`,
770
840
  stepIndex: index,
771
841
  tokEst: rTok,
772
- tag: 'Thinking',
842
+ tag: t('thinking'),
773
843
  title: rItem.text.replace(/\s+/g, ' ').trim().slice(0, 54),
774
- meta: `≈${(rTok / 1000).toFixed(1)}k · Reasoning`,
844
+ meta: `≈${(rTok / 1000).toFixed(1)}k · ${t('reasoning')}`,
775
845
  payload: String(rItem.text),
776
846
  }))
777
847
  }
@@ -797,7 +867,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
797
867
  tokEst: skTok,
798
868
  tag: 'SKILL.md',
799
869
  title: `${skill}/SKILL.md`,
800
- meta: `≈${(skTok / 1000).toFixed(1)}k · Step ${index + 1}`,
870
+ meta: `≈${(skTok / 1000).toFixed(1)}k · ${t('stepTag', { n: index + 1 })}`,
801
871
  payload: String(item.output || item.input || `# ${skill} (SKILL.md)`),
802
872
  }))
803
873
  }
@@ -822,7 +892,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
822
892
  payload: parts.join('\n\n'),
823
893
  ...(item.images?.length ? { images: item.images } : {}),
824
894
  }))
825
- const isSpot = Boolean(item.stats?.edit || item.stats?.skill)
895
+ const isSpot = Boolean(item.kind === 'edit' || item.kind === 'skill' || item.stats?.edit || item.stats?.skill)
826
896
  rawMontage.push({
827
897
  tag: toolTag,
828
898
  title: cleanSum.slice(0, 56),
@@ -837,7 +907,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
837
907
  toolRecords.push(registerRecord({
838
908
  id: `frame-${++toolSeq}`,
839
909
  stepIndex: index,
840
- tag: 'Preview',
910
+ tag: t('preview'),
841
911
  title: `${fr.label}`,
842
912
  meta: '≈1.2k tok',
843
913
  payload: `Preview frame: ${fr.label}`,
@@ -845,7 +915,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
845
915
  }))
846
916
  }
847
917
  rawMontage.push({
848
- tag: 'Preview',
918
+ tag: t('preview'),
849
919
  title: `${fr.label}`,
850
920
  isSpot: true,
851
921
  speed: '🖼',
@@ -853,7 +923,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
853
923
  }
854
924
  for (const doc of stepDocs) {
855
925
  rawMontage.push({
856
- tag: 'Draft',
926
+ tag: t('draft'),
857
927
  title: `${doc.title}`,
858
928
  isSpot: true,
859
929
  speed: '📄',
@@ -900,7 +970,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
900
970
  dwellMs = 1100
901
971
  }
902
972
  if (toolItems.length) {
903
- detailTitle = `Tool Call × ${toolItems.length}`
973
+ detailTitle = t('toolCalls', { n: toolItems.length })
904
974
  detailSnippet = toolItems.slice(0, 3).map(item => item.summary).join('\n')
905
975
  const primaryTool = toolItems[0]?.name || 'tool'
906
976
  inBrief = `${primaryTool} · ${toolItems.slice(0, 2).map(i => i.summary).join(';')}`
@@ -991,7 +1061,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
991
1061
  snippet: detailSnippet,
992
1062
  },
993
1063
  brief: {
994
- user: latestUserPrompt || 'Session Start',
1064
+ user: latestUserPrompt || t('sessionStart'),
995
1065
  in: inBrief,
996
1066
  response: responseBrief,
997
1067
  },
@@ -1015,10 +1085,10 @@ export function timeline(session, { lang = 'zh' } = {}) {
1015
1085
  ...item,
1016
1086
  t: at(item.time),
1017
1087
  ...(item.done ? { d: Math.min(end, at(item.done)) } : {}),
1018
- ...(item.type === 'tool' ? { k: kindOf(item.stats) } : {}),
1088
+ ...(item.type === 'tool' ? { k: kindOf(item.stats, item.kind) } : {}),
1019
1089
  }))
1020
1090
  const lanes = items
1021
- .filter(item => item.type === 'tool' && item.agent && item.d !== undefined && (item.stats?.agent || item.name === 'followup_task'))
1091
+ .filter(item => item.type === 'tool' && item.agent && item.d !== undefined && (item.kind === 'agent' || item.stats?.agent || item.name === 'followup_task'))
1022
1092
  .map(item => ({ agent: item.agent, s: item.t, e: Math.max(item.t, item.d) }))
1023
1093
  const waits = []
1024
1094
  items.forEach((item, index) => {
@@ -1062,8 +1132,12 @@ export function timeline(session, { lang = 'zh' } = {}) {
1062
1132
  export function sumStats(items) {
1063
1133
  const totals = {}
1064
1134
  for (const item of items || []) {
1065
- for (const [key, value] of Object.entries(item.stats || {})) {
1066
- totals[key] = (totals[key] || 0) + value
1135
+ if (item.stats && Object.keys(item.stats).length) {
1136
+ for (const [key, value] of Object.entries(item.stats)) {
1137
+ totals[key] = (totals[key] || 0) + value
1138
+ }
1139
+ } else if (item.kind) {
1140
+ totals[item.kind] = (totals[item.kind] || 0) + 1
1067
1141
  }
1068
1142
  }
1069
1143
  return totals
@@ -0,0 +1,48 @@
1
+ import {
2
+ createTranscript,
3
+ describeTool,
4
+ imagesOf,
5
+ isoTime,
6
+ mentions,
7
+ parseArguments,
8
+ stripInjected,
9
+ textOf,
10
+ } from './common.mjs'
11
+
12
+ // WorkBuddy sessions: ~/.workbuddy/projects/<workspace>/<id>.jsonl, records in OpenAI Responses shape.
13
+ export function workBuddyUserText(content, references) {
14
+ const text = textOf(content)
15
+ const queries = [...text.matchAll(/<user_query>([\s\S]*?)<\/user_query>/g)].map(match => match[1].trim())
16
+ return mentions(queries.length ? queries.join('\n\n') : stripInjected(text), references)
17
+ }
18
+
19
+ export function readWorkBuddy(records) {
20
+ const transcript = createTranscript()
21
+ const usage = new Map()
22
+ let model
23
+ let title
24
+ for (const record of records) {
25
+ const time = isoTime(record.timestamp)
26
+ const provider = record.providerData || {}
27
+ model = model || provider.model
28
+ if (provider.rawUsage && provider.messageId) {
29
+ usage.set(provider.messageId, provider.rawUsage.total_tokens || 0)
30
+ }
31
+ if (record.type === 'ai-title') {
32
+ title = record.aiTitle
33
+ } else if (record.type === 'message' && record.role === 'user') {
34
+ const references = []
35
+ transcript.user(workBuddyUserText(record.content, references), time, { images: imagesOf(record.content), references, cwd: record.cwd })
36
+ } else if (record.type === 'message' && record.role === 'assistant') {
37
+ transcript.assistant(textOf(record.content), time, { cwd: record.cwd })
38
+ } else if (record.type === 'reasoning') {
39
+ transcript.reasoning(textOf(record.rawContent?.length ? record.rawContent : record.content), time)
40
+ } else if (record.type === 'function_call') {
41
+ transcript.tool(record.callId, describeTool(record.name, parseArguments(record.arguments)), time)
42
+ } else if (record.type === 'function_call_result') {
43
+ transcript.result(record.callId, stripInjected(textOf(record.output)), time, imagesOf(record.output), record.cwd)
44
+ }
45
+ }
46
+ const tokens = [...usage.values()].reduce((sum, value) => sum + value, 0) || undefined
47
+ return transcript.finish({ tool: 'workbuddy', model, title, tokens })
48
+ }