@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.
@@ -0,0 +1,169 @@
1
+ import { escapeHtml } from './markdown.mjs'
2
+
3
+ function attachmentTable(rows, { compact = false } = {}) {
4
+ if (!rows.length) return ''
5
+ const head = rows[0].map(cell => `<th scope="col">${escapeHtml(cell)}</th>`).join('')
6
+ const body = rows.slice(1).map(row => {
7
+ const cells = row.map(value => {
8
+ const text = String(value ?? '')
9
+ const content = !compact && text.length > 70
10
+ ? `<details><summary>${escapeHtml(text.slice(0, 52))}…</summary>${escapeHtml(text)}</details>`
11
+ : escapeHtml(text)
12
+ return `<td>${content}</td>`
13
+ })
14
+ return `<tr>${cells.join('')}</tr>`
15
+ })
16
+ return `<table><thead><tr>${head}</tr></thead><tbody>${body.join('')}</tbody></table>`
17
+ }
18
+
19
+ function renderRevision(file, t, url) {
20
+ const change = file.preview.change
21
+ if (!change || !file.revision) return ''
22
+ const revision = file.revision
23
+ const pdf = file.preview.type === 'pdf'
24
+ const location = pdf ? t('pdfPage', { n: revision.page }) : `${revision.sheet} · ${revision.cell}`
25
+ const before = Array.from(change.before), after = Array.from(change.after)
26
+ const shorter = Math.min(before.length, after.length)
27
+ let start = 0, end = 0
28
+ while (start < shorter && before[start] === after[start]) start++
29
+ while (end < shorter - start && before.at(-1 - end) === after.at(-1 - end)) end++
30
+ function side(chars, original) {
31
+ const stop = chars.length - end
32
+ const tag = original ? 'del' : 'ins'
33
+ const text = escapeHtml(chars.slice(0, start).join(''))
34
+ + `<${tag}>${escapeHtml(chars.slice(start, stop).join(''))}</${tag}>`
35
+ + escapeHtml(chars.slice(stop).join(''))
36
+ const src = url(original ? revision.href : file.href)
37
+ const link = pdf
38
+ ? `<a href="${escapeHtml(src)}#page=${Number(revision.page)}" target="_blank" rel="noopener noreferrer">${t('openSourcePage')}</a>`
39
+ : `<a href="${escapeHtml(src)}" download>${t('downloadFile', { type: 'Excel' })}</a>`
40
+ return `<section><strong>${t(original ? 'beforeRevision' : 'afterRevision')}</strong><p>${text}</p>${link}</section>`
41
+ }
42
+ return `<details class="session-revision"><summary>${t('viewChanges')}</summary>
43
+ <div class="session-revision-context"><b>${escapeHtml(revision.label)}</b><span>${escapeHtml(location)}</span></div>
44
+ <div class="session-revision-pair">${side(before, true)}${side(after, false)}</div></details>`
45
+ }
46
+
47
+ export function renderAttachment(file, t, url) {
48
+ const preview = file.preview
49
+ const pdf = preview.type === 'pdf'
50
+ const type = pdf ? 'PDF' : 'Excel'
51
+ const action = t(pdf ? 'readPdf' : 'readWorkbook')
52
+ const count = pdf ? t('pdfPages', { n: preview.pages.length }) : t('sheetCount', { n: preview.count })
53
+ const download = `<a href="${escapeHtml(url(file.href))}" download${file.availability ? `="${escapeHtml(file.title)}"` : ''}>${t('downloadFile', { type })}</a>`
54
+ const title = escapeHtml(file.title)
55
+ const toolbar = pdf
56
+ ? `<button type="button" data-page-prev aria-label="${t('prevPage')}">‹</button>
57
+ <label>${t('pageNumber')} <input data-page-number type="number" min="1" max="${preview.pages.length}" value="1"> / ${preview.pages.length}</label>
58
+ <button type="button" data-page-next aria-label="${t('nextPage')}">›</button>
59
+ <select data-page-zoom aria-label="${t('zoom')}"><option value="100">${t('fitWidth')}</option><option value="125">125%</option><option value="150">150%</option></select>`
60
+ : `<label>${t('sheetName')} <select data-sheet-picker></select></label>`
61
+ const content = pdf
62
+ ? `<template>${preview.pages.map((page, i) => `<img loading="lazy" src="${escapeHtml(url(page.src))}" width="${Number(page.width)}" height="${Number(page.height)}" alt="${escapeHtml(t('pdfPage', { n: i + 1 }))}">`).join('')}</template>`
63
+ : ''
64
+ const source = pdf ? '' : ` data-workbook-src="${escapeHtml(url(preview.src))}" data-first-sheet="${escapeHtml(preview.sheet)}"`
65
+ const summary = pdf
66
+ ? `<img class="session-pdf-cover" src="${escapeHtml(url(file.cover || preview.pages[0].src))}" alt="" loading="lazy">`
67
+ : ''
68
+ return `<section class="session-attachment" data-attachment="${preview.type}"${source}>
69
+ <div class="session-attachment-head">${summary}<div><strong>${title}</strong>
70
+ <small>${type} · ${count}${file.meta ? ' · ' + escapeHtml(file.meta) : ''}</small></div></div>
71
+ ${pdf ? '' : `<div class="session-sheet-sample">${attachmentTable(preview.rows, { compact: true })}</div>`}
72
+ <div class="session-attachment-actions"><button type="button" data-open-attachment>${action}</button>${download}</div>
73
+ ${renderRevision(file, t, url)}
74
+ <dialog class="session-attachment-dialog" aria-label="${title}">
75
+ <header><strong>${title}</strong>${download}<button type="button" data-close-attachment aria-label="${t('closePreview')}">✕</button></header>
76
+ <div class="session-attachment-toolbar">${toolbar}</div>
77
+ <div class="session-attachment-viewport" role="region" aria-label="${title}" tabindex="0"></div>
78
+ </dialog>${content}
79
+ </section>`
80
+ }
81
+
82
+ function attachPdfReader(card, viewport) {
83
+ viewport.append(card.querySelector('template').content.cloneNode(true))
84
+ const pages = [...viewport.querySelectorAll('img')]
85
+ const number = card.querySelector('[data-page-number]')
86
+ const previous = card.querySelector('[data-page-prev]')
87
+ const next = card.querySelector('[data-page-next]')
88
+ function setPage(n) {
89
+ number.value = n
90
+ previous.disabled = n === 1
91
+ next.disabled = n === pages.length
92
+ }
93
+ function jump(n) {
94
+ n = Math.max(1, Math.min(pages.length, Math.round(n) || 1))
95
+ pages[n - 1].scrollIntoView({ block: 'start', inline: 'nearest' })
96
+ setPage(n)
97
+ }
98
+ number.addEventListener('change', () => jump(number.valueAsNumber))
99
+ number.addEventListener('keydown', event => {
100
+ if (event.key === 'Enter') jump(number.valueAsNumber)
101
+ })
102
+ previous.addEventListener('click', () => jump(number.valueAsNumber - 1))
103
+ next.addEventListener('click', () => jump(number.valueAsNumber + 1))
104
+ card.querySelector('[data-page-zoom]').addEventListener('change', event => {
105
+ viewport.style.setProperty('--attachment-page-width', event.target.value + '%')
106
+ jump(number.valueAsNumber)
107
+ })
108
+ viewport.addEventListener('scroll', () => {
109
+ if (document.activeElement === number) return
110
+ const top = viewport.getBoundingClientRect().top + 32
111
+ const i = pages.findIndex(page => page.getBoundingClientRect().bottom > top)
112
+ setPage(i < 0 ? pages.length : i + 1)
113
+ }, { passive: true })
114
+ setPage(1)
115
+ }
116
+
117
+ async function attachWorkbookReader(card, viewport, t) {
118
+ const response = await fetch(card.dataset.workbookSrc)
119
+ if (!response.ok) throw new Error('HTTP ' + response.status)
120
+ const sheets = await response.json()
121
+ const picker = card.querySelector('[data-sheet-picker]')
122
+ for (const sheet of sheets) picker.add(new Option(sheet.sheet, sheet.sheet))
123
+ picker.value = card.dataset.firstSheet
124
+ function selectSheet() {
125
+ viewport.innerHTML = attachmentTable(sheets[picker.selectedIndex].data) || escapeHtml(t('emptySheet'))
126
+ viewport.scrollTo(0, 0)
127
+ }
128
+ picker.addEventListener('change', selectSheet)
129
+ selectSheet()
130
+ }
131
+
132
+ export function attachAttachmentReaders(container, t, pauseReplay) {
133
+ for (const card of container.querySelectorAll('[data-attachment]')) {
134
+ const revision = card.querySelector('.session-revision')
135
+ revision?.addEventListener('toggle', () => {
136
+ if (revision.open) {
137
+ pauseReplay()
138
+ revision.scrollIntoView({ block: 'nearest' })
139
+ }
140
+ })
141
+ const dialog = card.querySelector('dialog')
142
+ const viewport = card.querySelector('.session-attachment-viewport')
143
+ let initialized = false
144
+ card.querySelector('[data-open-attachment]').addEventListener('click', async () => {
145
+ pauseReplay()
146
+ dialog.showModal()
147
+ if (initialized) return
148
+ initialized = true
149
+ if (card.dataset.attachment === 'pdf') {
150
+ attachPdfReader(card, viewport)
151
+ } else {
152
+ viewport.textContent = t('loadingSheet')
153
+ try {
154
+ await attachWorkbookReader(card, viewport, t)
155
+ } catch {
156
+ viewport.textContent = t('sheetLoadError')
157
+ initialized = false
158
+ }
159
+ }
160
+ })
161
+ card.querySelector('[data-close-attachment]').addEventListener('click', () => dialog.close())
162
+ dialog.addEventListener('click', event => {
163
+ if (event.target === dialog) {
164
+ const box = dialog.getBoundingClientRect()
165
+ if (event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom) dialog.close()
166
+ }
167
+ })
168
+ }
169
+ }
package/src/claude-ai.mjs CHANGED
@@ -41,7 +41,9 @@ export function readClaudeAi(data, { conversation } = {}) {
41
41
  file => file.file_name || file.extracted_content?.match(/^#*\s*(\S.*)$/m)?.[1].trim()
42
42
  )
43
43
  const files = names.filter(Boolean).map(attachmentLabel)
44
- transcript.user([textOf(blocks.filter(block => block.type === 'text')).trim(), ...files].filter(Boolean).join('\n\n'), time)
44
+ const deliverables = names.filter(Boolean).map(title => ({ title, availability: 'missing' }))
45
+ transcript.user([textOf(blocks.filter(block => block.type === 'text')).trim(), ...files].filter(Boolean).join('\n\n'), time,
46
+ deliverables.length ? { deliverables } : {})
45
47
  continue
46
48
  }
47
49
  const stamps = blocks.map(block => isoTime(block.start_timestamp))
@@ -49,14 +49,14 @@ function parseSkillListing(content, seenSkills, skillOut) {
49
49
  }
50
50
  }
51
51
 
52
- export function userText(text) {
52
+ export function userText(text, references) {
53
53
  const command = String(text || '').match(/<command-name>([^<]*)<\/command-name>/)
54
54
  if (command) {
55
55
  const args = String(text || '').match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1].trim()
56
56
  return [command[1].trim(), args].filter(Boolean).join(' ')
57
57
  }
58
58
  if (/^\s*\[Request interrupted by user[^\]]*\]\s*$/.test(text)) return '(中途打断)'
59
- return mentions(stripInjected(String(text || '').replace(/<command-message>[\s\S]*?<\/command-message>/g, '')))
59
+ return mentions(stripInjected(String(text || '').replace(/<command-message>[\s\S]*?<\/command-message>/g, '')), references)
60
60
  }
61
61
 
62
62
  const field = (text, name) => String(text || '').match(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`))?.[1].trim()
@@ -99,7 +99,7 @@ export function readClaudeCode(records, { includeMemory = false } = {}) {
99
99
  waiting.delete(from)
100
100
  return
101
101
  }
102
- const item = transcript.tool(null, { name: 'task-notification', summary, output: from ? undefined : result, stats: { reply: 1 }, agent }, time)
102
+ const item = transcript.tool(null, { name: 'task-notification', kind: 'reply', summary, output: from ? undefined : result, stats: { reply: 1 }, agent }, time)
103
103
  if (from) waiting.set(from, item)
104
104
  }
105
105
  const reported = ({ from, report }, time) => {
@@ -108,7 +108,7 @@ export function readClaudeCode(records, { includeMemory = false } = {}) {
108
108
  waiting.delete(from)
109
109
  return
110
110
  }
111
- waiting.set(from, transcript.tool(null, { name: 'agent-message', summary: `子任务交回结果:${from}`, output: report, stats: { reply: 1 } }, time))
111
+ waiting.set(from, transcript.tool(null, { name: 'agent-message', kind: 'reply', summary: `子任务交回结果:${from}`, output: report, stats: { reply: 1 }, agent: from }, time))
112
112
  }
113
113
 
114
114
  for (const record of records) {
@@ -296,7 +296,10 @@ export function readClaudeCode(records, { includeMemory = false } = {}) {
296
296
  const back = handBack(text)
297
297
  if (back) reported(back, time)
298
298
  else if (/^\s*<task-notification>/.test(text)) notified(text, time)
299
- else transcript.user(userText(text), time, { images: typeof prompt === 'string' ? [] : imagesOf(prompt) })
299
+ else {
300
+ const references = []
301
+ transcript.user(userText(text, references), time, { references, cwd: record.cwd, images: typeof prompt === 'string' ? [] : imagesOf(prompt) })
302
+ }
300
303
  continue
301
304
  }
302
305
  if (!['user', 'assistant'].includes(record.type) || record.isApiErrorMessage) continue
@@ -342,7 +345,7 @@ export function readClaudeCode(records, { includeMemory = false } = {}) {
342
345
  if (ctxTokens > 0) lastContextTokens = ctxTokens
343
346
  }
344
347
  for (const block of blocks) {
345
- if (block.type === 'text' && block.text !== '(no content)') transcript.assistant(block.text, time, { key: message.id })
348
+ if (block.type === 'text' && block.text !== '(no content)') transcript.assistant(block.text, time, { key: message.id, cwd: record.cwd })
346
349
  else if (block.type === 'thinking') transcript.reasoning(block.thinking, time)
347
350
  else if (block.type === 'tool_use') transcript.tool(block.id, describeTool(block.name, block.input), time)
348
351
  }
@@ -358,14 +361,15 @@ export function readClaudeCode(records, { includeMemory = false } = {}) {
358
361
 
359
362
  const said = []
360
363
  const pictures = []
364
+ const references = []
361
365
  for (const block of blocks) {
362
366
  if (block.type === 'text' && /^\s*<task-notification>/.test(block.text)) {
363
367
  notified(block.text, time)
364
368
  } else if (block.type === 'tool_result') {
365
369
  const output = stripInjected(textOf(block.content))
366
- transcript.result(block.tool_use_id, /^Async agent launched successfully/.test(output) ? undefined : output, time, imagesOf(block.content))
370
+ transcript.result(block.tool_use_id, /^Async agent launched successfully/.test(output) ? undefined : output, time, imagesOf(block.content), record.cwd)
367
371
  } else if (block.type === 'text') {
368
- const cleaned = userText(block.text)
372
+ const cleaned = userText(block.text, references)
369
373
  if (/^The context window filled up while you were working, so the conversation was compacted\./i.test(cleaned)) continue
370
374
  said.push(cleaned)
371
375
  } else if (block.type === 'image') {
@@ -374,7 +378,7 @@ export function readClaudeCode(records, { includeMemory = false } = {}) {
374
378
  }
375
379
  const joinedSaid = said.filter(Boolean).join('\n\n')
376
380
  if (joinedSaid && joinedSaid !== '/compact') pendingCompact = null
377
- transcript.user(joinedSaid, time, { images: pictures })
381
+ transcript.user(joinedSaid, time, { images: pictures, references, cwd: record.cwd })
378
382
  }
379
383
  const tokens = [...usage.values()].reduce((sum, value) => sum + value, 0) || undefined
380
384
  const initialContext = (initSys.length || initSchema.length || initMem.length || initSkill.length)
package/src/codex.mjs CHANGED
@@ -149,13 +149,29 @@ function describeCodexCode(code) {
149
149
  if (images) parts.push(`查看 ${images} 张图片`)
150
150
  if (others.length) parts.push(`调用 ${[...new Set(others.map(name => name.replace(/^mcp__[^_]+(?:_[^_]+)*?__/, '')))].join('、')}`)
151
151
  const summary = parts.join(';') || '运行代码'
152
- return { name: 'exec', summary: summary.length > 120 ? `${summary.slice(0, 119)}…` : summary, input: code, stats }
152
+ const uniqueFiles = [...new Set(files.filter(Boolean))]
153
+ const file = uniqueFiles[0]
154
+ const skill = String(code || '').match(/skills\/([\w-]+)\/SKILL\.md\b/)?.[1]
155
+ const primaryKind = uniqueFiles.length
156
+ ? 'edit'
157
+ : (commands.length ? 'command' : (queries.length ? 'search' : (pages.length ? 'open' : (images ? 'view' : 'code'))))
158
+ return {
159
+ name: 'exec',
160
+ kind: primaryKind,
161
+ summary: summary.length > 120 ? `${summary.slice(0, 119)}…` : summary,
162
+ input: code,
163
+ stats,
164
+ file,
165
+ files: uniqueFiles.length > 1 ? uniqueFiles : undefined,
166
+ skill,
167
+ }
153
168
  }
154
169
 
155
170
  const normAgentName = value => String(value || '').split('/').filter(Boolean).pop() || String(value || '').trim()
156
171
 
157
172
  export function readCodex(records, { includeMemory = false } = {}) {
158
173
  const transcript = createTranscript()
174
+ let cwd
159
175
  const working = new Map()
160
176
  let model
161
177
  let title
@@ -231,6 +247,7 @@ export function readCodex(records, { includeMemory = false } = {}) {
231
247
  const payload = record.payload || {}
232
248
  const time = isoTime(record.timestamp)
233
249
  if (record.type === 'session_meta') {
250
+ cwd = payload.cwd || cwd
234
251
  model = model || payload.model
235
252
  if (payload.title && !title) title = payload.title
236
253
  const baseText = typeof payload.base_instructions === 'string' ? payload.base_instructions : payload.base_instructions?.text
@@ -239,7 +256,10 @@ export function readCodex(records, { includeMemory = false } = {}) {
239
256
  initSys.unshift(...splitMarkdownSections(baseText, 'init-sys-base', 'Core'))
240
257
  }
241
258
  }
242
- if (record.type === 'turn_context') model = model || payload.model
259
+ if (record.type === 'turn_context') {
260
+ model = model || payload.model
261
+ cwd = payload.cwd || cwd
262
+ }
243
263
  if (record.type === 'world_state' && payload.state?.agents_md?.text) {
244
264
  addMem('agents-md', 'AGENTS.md', 'AGENTS.md(工作区与全局协作指令)', payload.state.agents_md.text)
245
265
  }
@@ -337,10 +357,12 @@ export function readCodex(records, { includeMemory = false } = {}) {
337
357
  } else if (!injected.test(text)) {
338
358
  sawFirstUserTurn = true
339
359
  pendingCompact = null
340
- transcript.user(cleanPrompt(text), time, { images: imagesOf(payload.content) })
360
+ const header = text.match(/^# Files mentioned by the user:\s*\n([\s\S]*?)\n## My request:/)?.[1] || ''
361
+ const references = [...header.matchAll(/^## .+?: (.+)$/gm)].map(match => match[1].trim())
362
+ transcript.user(cleanPrompt(text), time, { images: imagesOf(payload.content), references, cwd })
341
363
  }
342
364
  } else if (payload.type === 'message' && payload.role === 'assistant') {
343
- transcript.assistant(textOf(payload.content), time)
365
+ transcript.assistant(textOf(payload.content), time, { cwd })
344
366
  } else if (payload.type === 'reasoning') {
345
367
  transcript.reasoning((payload.summary || []).map(part => part.text).join('\n\n'), time)
346
368
  } else if (payload.type === 'custom_tool_call') {
@@ -348,7 +370,9 @@ export function readCodex(records, { includeMemory = false } = {}) {
348
370
  payload.call_id,
349
371
  payload.name === 'exec'
350
372
  ? describeCodexCode(payload.input)
351
- : { name: payload.name, summary: payload.name, input: payload.input, stats: { other: 1 } },
373
+ : (payload.name === 'apply_patch'
374
+ ? describeTool(payload.name, payload.input)
375
+ : { name: payload.name, kind: 'other', summary: payload.name, input: payload.input, stats: { other: 1 } }),
352
376
  time
353
377
  )
354
378
  } else if (payload.type === 'function_call') {
@@ -357,14 +381,14 @@ export function readCodex(records, { includeMemory = false } = {}) {
357
381
  transcript.assistant((args.questions || []).map(question => question.title || question.question).join('\n'), time, { question: true })
358
382
  } else if (payload.name === 'spawn_agent' || payload.name === 'collaboration__spawn_agent') {
359
383
  const agentKey = normAgentName(args.task_name)
360
- working.set(agentKey, transcript.tool(payload.call_id, { name: payload.name, summary: `派出子任务 ${args.task_name}`, stats: { agent: 1 }, agent: agentKey }, time))
384
+ working.set(agentKey, transcript.tool(payload.call_id, { name: payload.name, kind: 'agent', summary: `派出子任务 ${args.task_name}`, stats: { agent: 1 }, agent: agentKey }, time))
361
385
  } else if (['send_message', 'followup_task', 'collaboration__send_message', 'collaboration__followup_task'].includes(payload.name)) {
362
386
  const isFollowup = payload.name.endsWith('followup_task')
363
387
  const agentKey = normAgentName(args.target)
364
- const item = transcript.tool(payload.call_id, { name: payload.name, summary: `${isFollowup ? '给子任务追加任务' : '给子任务发消息'} ${args.target}`, stats: { other: 1 }, agent: agentKey }, time)
388
+ const item = transcript.tool(payload.call_id, { name: payload.name, kind: 'other', summary: `${isFollowup ? '给子任务追加任务' : '给子任务发消息'} ${args.target}`, stats: { other: 1 }, agent: agentKey }, time)
365
389
  if (isFollowup && agentKey) working.set(agentKey, item)
366
390
  } else if (payload.name === 'wait' || payload.name === 'collaboration__wait_agent') {
367
- transcript.tool(payload.call_id, { name: payload.name, summary: '等待子任务', stats: { other: 1 } }, time)
391
+ transcript.tool(payload.call_id, { name: payload.name, kind: 'other', summary: '等待子任务', stats: { other: 1 } }, time)
368
392
  } else {
369
393
  transcript.tool(payload.call_id, describeTool(payload.name, args), time)
370
394
  }
@@ -372,12 +396,12 @@ export function readCodex(records, { includeMemory = false } = {}) {
372
396
  transcript.result(payload.call_id, textOf(payload.output), time, imagesOf(payload.output))
373
397
  } else if (payload.type === 'web_search_call') {
374
398
  const query = payload.action?.query || payload.action?.queries?.join('、') || ''
375
- transcript.tool(null, { name: 'web_search', summary: `搜索「${query}」`, stats: { search: 1 } }, time)
399
+ transcript.tool(null, { name: 'web_search', kind: 'search', summary: `搜索「${query}」`, stats: { search: 1 } }, time)
376
400
  } else if (payload.type === 'agent_message') {
377
401
  const message = textOf(payload.content).match(/^Message Type: (\w+)\n[\s\S]*?Sender: ([^\n]+)\nPayload:\n([\s\S]*)$/)
378
402
  if (!message || !message[3].trim()) continue
379
403
  const name = normAgentName(message[2])
380
- transcript.tool(null, { name: 'agent_message', summary: message[1] === 'FINAL_ANSWER' ? `子任务 ${name} 交回结果` : `子任务 ${name} 发来消息`, output: message[3].trim(), stats: { reply: 1 }, agent: name }, time)
404
+ transcript.tool(null, { name: 'agent_message', kind: 'reply', summary: message[1] === 'FINAL_ANSWER' ? `子任务 ${name} 交回结果` : `子任务 ${name} 发来消息`, output: message[3].trim(), stats: { reply: 1 }, agent: name }, time)
381
405
  if (message[1] === 'FINAL_ANSWER' && working.has(name)) {
382
406
  working.get(name).done = time
383
407
  working.delete(name)
package/src/common.mjs CHANGED
@@ -1,9 +1,11 @@
1
1
  import { createReadStream } from 'node:fs'
2
2
  import { spawn } from 'node:child_process'
3
3
  import { StringDecoder } from 'node:string_decoder'
4
+ import { fileReferences, messageReferences } from './external-files.mjs'
4
5
 
5
6
  export const tools = {
6
7
  codex: 'Codex',
8
+ workbuddy: 'WorkBuddy',
7
9
  'claude-code': 'Claude Code',
8
10
  'claude-ai': 'Claude',
9
11
  }
@@ -115,11 +117,12 @@ export function isoTime(value) {
115
117
  return Number.isNaN(date.getTime()) ? undefined : date.toISOString()
116
118
  }
117
119
 
118
- export function mentions(text) {
120
+ export function mentions(text, references = []) {
119
121
  const files = []
120
122
  const request = String(text)
121
123
  .replace(/(^|\s)@(?:"([^"]+)"|(~?[/\\][^\s"]+))/g, (whole, space, quoted, bare) => {
122
124
  const name = (quoted || bare).split(/[/\\]/).pop()
125
+ references.push(quoted || bare)
123
126
  files.push(attachmentLabel(name))
124
127
  return space === '\n' ? space : ''
125
128
  })
@@ -202,21 +205,30 @@ export function describeTool(name, input = {}) {
202
205
  const args = typeof input === 'object' && input !== null ? input : {}
203
206
  const base = String(name).split('__').pop()
204
207
  const kind = toolKinds[name] || toolKinds[base] || 'other'
205
- const patchMatch = typeof input === 'string'
206
- ? input.match(/\*\*\* (?:Add|Update|Delete) File:\s*([^\n\r]+)/)?.[1]?.trim()
207
- : (typeof args.input === 'string' ? args.input.match(/\*\*\* (?:Add|Update|Delete) File:\s*([^\n\r]+)/)?.[1]?.trim() : undefined)
208
+ const patchText = typeof input === 'string' ? input : (typeof args.input === 'string' ? args.input : '')
209
+ const patchFiles = [...patchText.matchAll(/\*\*\* (?:Add|Update|Delete) File:\s*([^\n\r\\"]+)/g)]
210
+ .map(match => fileName(match[1].trim()))
211
+ .filter(Boolean)
212
+ const patchMatch = patchFiles[0]
208
213
  const path = args.file_path || args.path || args.notebook_path || patchMatch
214
+ const file = fileName(path) || undefined
215
+ const files = patchFiles.length > 1 ? [...new Set(patchFiles)] : undefined
209
216
  const cmdText = args.command || args.cmd
217
+ const cmdLine = Array.isArray(cmdText) ? cmdText.join(' ') : cmdText
218
+ const rawSkill = kind === 'skill'
219
+ ? String(args.skill || args.name || '').trim()
220
+ : (String(path || cmdLine || '').match(/(?:^|[/\\])skills[/\\]([\w-]+)[/\\]SKILL\.md\b/)?.[1] || '')
221
+ const skill = rawSkill || undefined
210
222
  const summary = {
211
223
  search: () => `搜索「${oneLine(args.query || args.q, 60)}」`,
212
224
  open: () => `打开 ${shortUrl(args.url || args.ref_id)}`,
213
- command: () => `运行 ${oneLine(Array.isArray(cmdText) ? cmdText.join(' ') : cmdText)}`,
214
- read: () => `读取 ${fileName(path)}`,
215
- view: () => `查看 ${fileName(path) || '图片'}`,
225
+ command: () => `运行 ${oneLine(cmdLine)}`,
226
+ read: () => `读取 ${file || ''}`.trim(),
227
+ view: () => `查看 ${file || '图片'}`,
216
228
  find: () => `查找 ${oneLine(args.pattern || path, 60)}`,
217
- edit: () => `${/^(Write|create_file|write_file)$/.test(base) ? '写入' : '修改'} ${fileName(path)}`,
229
+ edit: () => `${/^(Write|create_file|write_file)$/.test(base) ? '写入' : '修改'} ${file || ''}`.trim(),
218
230
  agent: () => `派出子任务:${oneLine(args.description || args.prompt || args.task_name, 40)}`,
219
- skill: () => `加载技能 ${args.skill || args.name || ''}`.trim(),
231
+ skill: () => `加载技能 ${skill || ''}`.trim(),
220
232
  other: () => (
221
233
  typeof args.title === 'string' && typeof args.code === 'string'
222
234
  ? oneLine(args.title, 80)
@@ -224,14 +236,14 @@ export function describeTool(name, input = {}) {
224
236
  ),
225
237
  }[kind]()
226
238
  const shown = kind === 'command'
227
- ? (Array.isArray(cmdText) ? cmdText.join(' ') : cmdText)
239
+ ? cmdLine
228
240
  : kind === 'agent'
229
241
  ? (args.prompt || args.message)
230
242
  : kind === 'edit' && typeof (args.content || args.input) === 'string'
231
243
  ? (args.content || args.input)
232
244
  : input
233
245
  const agent = kind === 'agent' ? oneLine(args.description || args.prompt || args.task_name, 40) : undefined
234
- return { name, summary, input: inputText(shown), stats: { [kind]: 1 }, agent }
246
+ return { name, kind, summary, input: inputText(shown), stats: { [kind]: 1 }, file, files, skill, agent }
235
247
  }
236
248
 
237
249
  export function deriveDefaultTitle(session) {
@@ -278,15 +290,22 @@ export function createTranscript() {
278
290
  }
279
291
  return {
280
292
  items,
281
- user(text, time, { images = [], ...extra } = {}) {
293
+ user(text, time, { images = [], references = [], cwd, ...extra } = {}) {
282
294
  text = String(text ?? '').trim() || (images.length ? '[图片]' : '')
295
+ const files = fileReferences([...references, ...messageReferences(text)], cwd)
296
+ if (files.length) extra.deliverables = [...(extra.deliverables || []), ...files]
283
297
  if (text) add({ type: 'user', text, time, ...extra, images: images.length ? images : undefined })
284
298
  },
285
- assistant(text, time, { key, ...extra } = {}) {
299
+ assistant(text, time, { key, cwd, ...extra } = {}) {
286
300
  text = String(text ?? '').trim()
287
301
  if (!text) return
288
302
  const last = items.at(-1)
289
- if (key && last?.type === 'assistant' && last.key === key) last.text += `\n\n${text}`
303
+ const files = fileReferences(messageReferences(text), cwd)
304
+ if (files.length) extra.deliverables = files
305
+ if (key && last?.type === 'assistant' && last.key === key) {
306
+ last.text += `\n\n${text}`
307
+ if (files.length) last.deliverables = [...(last.deliverables || []), ...files]
308
+ }
290
309
  else add({ type: 'assistant', text, time, key, ...extra })
291
310
  },
292
311
  reasoning(text, time) {
@@ -301,13 +320,24 @@ export function createTranscript() {
301
320
  compact(info, time) {
302
321
  return add({ type: 'compact', ...info, time })
303
322
  },
304
- result(id, output, time, images = []) {
323
+ result(id, output, time, images = [], cwd) {
305
324
  const item = id ? calls.get(id) : items.findLast(entry => entry.type === 'tool' && !entry.output)
306
325
  if (!item) return
307
326
  if (time) item.done = time
308
327
  output = String(output ?? '').trim()
309
328
  if (output) item.output = item.output ? `${item.output}\n${output}` : output
310
329
  if (images.length) item.images = [...(item.images || []), ...images]
330
+ const name = item.name?.split('__').at(-1)
331
+ if (name === 'present_files' || name === 'SendUserFile') {
332
+ const result = parseArguments(output)
333
+ const args = parseArguments(item.input)
334
+ const entries = result?.type === 'present_files_result' ? result.files
335
+ : name === 'SendUserFile' && /\b\d+ files? delivered to user\b/i.test(output) ? args?.files : undefined
336
+ if (Array.isArray(entries)) {
337
+ const files = fileReferences(entries, args?.cwd || cwd)
338
+ if (files.length) item.deliverables = files
339
+ }
340
+ }
311
341
  },
312
342
  finish({ tool, model, title, description = '', deliverables = [], tokens, contextWindow, initialContext }) {
313
343
  for (const item of items) delete item.key
package/src/detect.mjs CHANGED
@@ -4,6 +4,7 @@ import { dirname, join, resolve } from 'node:path'
4
4
  import { cleanPrompt } from './codex.mjs'
5
5
  import { userText } from './claude-code.mjs'
6
6
  import { lines, textOf, tools } from './common.mjs'
7
+ import { workBuddyUserText } from './workbuddy.mjs'
7
8
 
8
9
  const codexInjected = /^(# AGENTS\.md instructions|<[a-z][\w-]*[\s>]|The following is the Codex agent history)/
9
10
 
@@ -50,6 +51,14 @@ export async function detectJsonlTool(filePath) {
50
51
  if (rec.type === 'session_meta' || rec.type === 'turn_context' || rec.type === 'response_item' || rec.type === 'event_msg') {
51
52
  return 'codex'
52
53
  }
54
+ if (
55
+ rec.providerData ||
56
+ rec.type === 'function_call_result' ||
57
+ (rec.type === 'message' && typeof rec.role === 'string' && !rec.payload) ||
58
+ (rec.type === 'function_call' && rec.callId && !rec.payload)
59
+ ) {
60
+ return 'workbuddy'
61
+ }
53
62
  if (
54
63
  rec.type === 'api-request-shape' ||
55
64
  rec.type === 'custom-title' ||
@@ -122,6 +131,7 @@ async function summarizeLogFile(file, toolHint) {
122
131
  timestamp = typeof rec.timestamp === 'number' ? new Date(rec.timestamp).toISOString() : String(rec.timestamp)
123
132
  }
124
133
  if (rec.type === 'session_meta' || rec.type === 'response_item') tool = 'codex'
134
+ if (rec.providerData || rec.type === 'function_call_result') tool = 'workbuddy'
125
135
  if (rec.type === 'custom-title' && rec.customTitle) title = rec.customTitle
126
136
  if (rec.type === 'ai-title' && rec.aiTitle && !title) title = rec.aiTitle
127
137
  if (rec.type === 'summary' && rec.summary && !title) title = rec.summary
@@ -134,6 +144,10 @@ async function summarizeLogFile(file, toolHint) {
134
144
  if (raw && !codexInjected.test(raw) && !raw.startsWith('<send_user_message_question_reply>')) {
135
145
  firstPrompt = cleanPrompt(raw)
136
146
  }
147
+ } else if (rec.type === 'message' && rec.role === 'user' && !rec.payload) {
148
+ tool = 'workbuddy'
149
+ const txt = workBuddyUserText(rec.content).trim()
150
+ if (txt) firstPrompt = txt
137
151
  } else if (rec.type === 'user' && !rec.isMeta && !rec.isCompactSummary && rec.message) {
138
152
  tool = 'claude-code'
139
153
  const blocks = typeof rec.message.content === 'string'
@@ -166,25 +180,32 @@ function formatLocalTime(ms) {
166
180
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
167
181
  }
168
182
 
169
- export async function scanRecentSessions({
170
- limit = 12,
183
+ export async function* iterateRecentSessions({
171
184
  codexDir = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'sessions'),
172
185
  claudeDir = join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects'),
173
- } = {}) {
186
+ workbuddyDir = join(process.env.WORKBUDDY_HOME || join(homedir(), '.workbuddy'), 'projects'),
187
+ } = {}, maxCandidates = Infinity) {
174
188
  const codexFiles = walkFiles(codexDir, name => name.startsWith('rollout-') && name.endsWith('.jsonl'))
175
189
  .map(item => ({ ...item, toolHint: 'codex' }))
176
190
  const claudeFiles = walkFiles(claudeDir, name => name.endsWith('.jsonl') && !name.startsWith('agent-'))
177
191
  .map(item => ({ ...item, toolHint: 'claude-code' }))
192
+ const workbuddyFiles = walkFiles(workbuddyDir, name => name.endsWith('.jsonl'))
193
+ .map(item => ({ ...item, toolHint: 'workbuddy' }))
178
194
 
179
- const candidates = [...codexFiles, ...claudeFiles]
195
+ const candidates = [...codexFiles, ...claudeFiles, ...workbuddyFiles]
180
196
  .sort((a, b) => b.mtimeMs - a.mtimeMs)
181
- .slice(0, limit * 3)
197
+ .slice(0, maxCandidates)
182
198
 
183
- const results = []
184
199
  for (const cand of candidates) {
185
- const info = await summarizeLogFile(cand.file, cand.toolHint)
200
+ let info
201
+ try {
202
+ info = await summarizeLogFile(cand.file, cand.toolHint)
203
+ } catch (error) {
204
+ if (error.code === 'ENOENT') continue
205
+ throw error
206
+ }
186
207
  if (!info.preview) continue
187
- results.push({
208
+ yield {
188
209
  tool: info.tool,
189
210
  toolLabel: tools[info.tool] || info.tool,
190
211
  file: cand.file,
@@ -192,7 +213,14 @@ export async function scanRecentSessions({
192
213
  timeLabel: formatLocalTime(cand.mtimeMs),
193
214
  sizeKB: Math.max(1, Math.round(cand.size / 1024)),
194
215
  preview: info.preview,
195
- })
216
+ }
217
+ }
218
+ }
219
+
220
+ export async function scanRecentSessions({ limit = 12, ...directories } = {}) {
221
+ const results = []
222
+ for await (const session of iterateRecentSessions(directories, limit * 3)) {
223
+ results.push(session)
196
224
  if (results.length >= limit) break
197
225
  }
198
226
  return results