@niracler/encore 0.2.0 → 0.4.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()
@@ -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
@@ -171,6 +171,7 @@ const normAgentName = value => String(value || '').split('/').filter(Boolean).po
171
171
 
172
172
  export function readCodex(records, { includeMemory = false } = {}) {
173
173
  const transcript = createTranscript()
174
+ let cwd
174
175
  const working = new Map()
175
176
  let model
176
177
  let title
@@ -246,6 +247,7 @@ export function readCodex(records, { includeMemory = false } = {}) {
246
247
  const payload = record.payload || {}
247
248
  const time = isoTime(record.timestamp)
248
249
  if (record.type === 'session_meta') {
250
+ cwd = payload.cwd || cwd
249
251
  model = model || payload.model
250
252
  if (payload.title && !title) title = payload.title
251
253
  const baseText = typeof payload.base_instructions === 'string' ? payload.base_instructions : payload.base_instructions?.text
@@ -254,7 +256,10 @@ export function readCodex(records, { includeMemory = false } = {}) {
254
256
  initSys.unshift(...splitMarkdownSections(baseText, 'init-sys-base', 'Core'))
255
257
  }
256
258
  }
257
- 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
+ }
258
263
  if (record.type === 'world_state' && payload.state?.agents_md?.text) {
259
264
  addMem('agents-md', 'AGENTS.md', 'AGENTS.md(工作区与全局协作指令)', payload.state.agents_md.text)
260
265
  }
@@ -352,10 +357,12 @@ export function readCodex(records, { includeMemory = false } = {}) {
352
357
  } else if (!injected.test(text)) {
353
358
  sawFirstUserTurn = true
354
359
  pendingCompact = null
355
- 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 })
356
363
  }
357
364
  } else if (payload.type === 'message' && payload.role === 'assistant') {
358
- transcript.assistant(textOf(payload.content), time)
365
+ transcript.assistant(textOf(payload.content), time, { cwd })
359
366
  } else if (payload.type === 'reasoning') {
360
367
  transcript.reasoning((payload.summary || []).map(part => part.text).join('\n\n'), time)
361
368
  } else if (payload.type === 'custom_tool_call') {
package/src/common.mjs CHANGED
@@ -1,10 +1,14 @@
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',
7
8
  workbuddy: 'WorkBuddy',
9
+ antigravity: 'Antigravity',
10
+ 'antigravity-app': 'Antigravity App',
11
+ 'antigravity-cli': 'Antigravity CLI',
8
12
  'claude-code': 'Claude Code',
9
13
  'claude-ai': 'Claude',
10
14
  }
@@ -116,11 +120,12 @@ export function isoTime(value) {
116
120
  return Number.isNaN(date.getTime()) ? undefined : date.toISOString()
117
121
  }
118
122
 
119
- export function mentions(text) {
123
+ export function mentions(text, references = []) {
120
124
  const files = []
121
125
  const request = String(text)
122
126
  .replace(/(^|\s)@(?:"([^"]+)"|(~?[/\\][^\s"]+))/g, (whole, space, quoted, bare) => {
123
127
  const name = (quoted || bare).split(/[/\\]/).pop()
128
+ references.push(quoted || bare)
124
129
  files.push(attachmentLabel(name))
125
130
  return space === '\n' ? space : ''
126
131
  })
@@ -185,9 +190,9 @@ const toolKinds = {
185
190
  Bash: 'command', shell: 'command', exec_command: 'command', execute_command: 'command', run_command: 'command',
186
191
  Read: 'read', read_file: 'read', view: 'read', Glob: 'find', Grep: 'find', LS: 'find', list_dir: 'find',
187
192
  Write: 'edit', Edit: 'edit', MultiEdit: 'edit', NotebookEdit: 'edit', apply_patch: 'edit',
188
- create_file: 'edit', write_file: 'edit', str_replace: 'edit', str_replace_based_edit_tool: 'edit',
193
+ create_file: 'edit', write_file: 'edit', edit_file: 'edit', str_replace: 'edit', str_replace_based_edit_tool: 'edit',
189
194
  Agent: 'agent', Task: 'agent', Skill: 'skill', start_process: 'command', device_bash: 'command',
190
- view_image: 'view',
195
+ view_image: 'view', webview_browser: 'view', search_web: 'search', invoke_subagent: 'agent',
191
196
  }
192
197
 
193
198
  const toolNames = {
@@ -288,15 +293,22 @@ export function createTranscript() {
288
293
  }
289
294
  return {
290
295
  items,
291
- user(text, time, { images = [], ...extra } = {}) {
296
+ user(text, time, { images = [], references = [], cwd, ...extra } = {}) {
292
297
  text = String(text ?? '').trim() || (images.length ? '[图片]' : '')
298
+ const files = fileReferences([...references, ...messageReferences(text)], cwd)
299
+ if (files.length) extra.deliverables = [...(extra.deliverables || []), ...files]
293
300
  if (text) add({ type: 'user', text, time, ...extra, images: images.length ? images : undefined })
294
301
  },
295
- assistant(text, time, { key, ...extra } = {}) {
302
+ assistant(text, time, { key, cwd, ...extra } = {}) {
296
303
  text = String(text ?? '').trim()
297
304
  if (!text) return
298
305
  const last = items.at(-1)
299
- if (key && last?.type === 'assistant' && last.key === key) last.text += `\n\n${text}`
306
+ const files = fileReferences(messageReferences(text), cwd)
307
+ if (files.length) extra.deliverables = files
308
+ if (key && last?.type === 'assistant' && last.key === key) {
309
+ last.text += `\n\n${text}`
310
+ if (files.length) last.deliverables = [...(last.deliverables || []), ...files]
311
+ }
300
312
  else add({ type: 'assistant', text, time, key, ...extra })
301
313
  },
302
314
  reasoning(text, time) {
@@ -311,13 +323,24 @@ export function createTranscript() {
311
323
  compact(info, time) {
312
324
  return add({ type: 'compact', ...info, time })
313
325
  },
314
- result(id, output, time, images = []) {
326
+ result(id, output, time, images = [], cwd) {
315
327
  const item = id ? calls.get(id) : items.findLast(entry => entry.type === 'tool' && !entry.output)
316
328
  if (!item) return
317
329
  if (time) item.done = time
318
330
  output = String(output ?? '').trim()
319
331
  if (output) item.output = item.output ? `${item.output}\n${output}` : output
320
332
  if (images.length) item.images = [...(item.images || []), ...images]
333
+ const name = item.name?.split('__').at(-1)
334
+ if (name === 'present_files' || name === 'SendUserFile') {
335
+ const result = parseArguments(output)
336
+ const args = parseArguments(item.input)
337
+ const entries = result?.type === 'present_files_result' ? result.files
338
+ : name === 'SendUserFile' && /\b\d+ files? delivered to user\b/i.test(output) ? args?.files : undefined
339
+ if (Array.isArray(entries)) {
340
+ const files = fileReferences(entries, args?.cwd || cwd)
341
+ if (files.length) item.deliverables = files
342
+ }
343
+ }
321
344
  },
322
345
  finish({ tool, model, title, description = '', deliverables = [], tokens, contextWindow, initialContext }) {
323
346
  for (const item of items) delete item.key
package/src/detect.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
2
2
  import { homedir } from 'node:os'
3
- import { dirname, join, resolve } from 'node:path'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+ import { antigravityPrompt, antigravityStores, antigravitySummaries, antigravityTitle, isAntigravityRecord, nativeAntigravityLog } from './antigravity.mjs'
4
5
  import { cleanPrompt } from './codex.mjs'
5
6
  import { userText } from './claude-code.mjs'
6
7
  import { lines, textOf, tools } from './common.mjs'
@@ -37,17 +38,18 @@ export async function detectInput(targetPath) {
37
38
  }
38
39
 
39
40
  export async function detectJsonlTool(filePath) {
40
- const stream = createReadStream(filePath, { start: 0, end: 256 * 1024 })
41
+ const stream = createReadStream(filePath)
41
42
  let count = 0
42
43
  for await (const line of lines(stream)) {
43
44
  const trimmed = line.trim()
44
45
  if (!trimmed) continue
45
46
  count++
46
- if (count === 1 && (trimmed.startsWith('[') || trimmed.includes('"chat_messages"'))) {
47
+ if (count === 1 && trimmed.startsWith('[')) {
47
48
  return 'claude-ai'
48
49
  }
49
50
  try {
50
51
  const rec = JSON.parse(trimmed)
52
+ if (isAntigravityRecord(rec)) return nativeAntigravityLog(filePath)?.tool || 'antigravity'
51
53
  if (rec.type === 'session_meta' || rec.type === 'turn_context' || rec.type === 'response_item' || rec.type === 'event_msg') {
52
54
  return 'codex'
53
55
  }
@@ -74,7 +76,7 @@ export async function detectJsonlTool(filePath) {
74
76
  return 'claude-ai'
75
77
  }
76
78
  } catch {
77
- // Ignore partial line at slice boundary
79
+ // Skip malformed records while identifying a log.
78
80
  }
79
81
  if (count >= 40) break
80
82
  }
@@ -98,7 +100,7 @@ function walkFiles(dir, matcher, results = [], maxDepth = 5, depth = 0) {
98
100
  } else if (entry.isFile() && matcher(entry.name, full)) {
99
101
  try {
100
102
  const st = statSync(full)
101
- if (st.size > 200) {
103
+ if (st.size > 0) {
102
104
  results.push({ file: full, mtimeMs: st.mtimeMs, size: st.size })
103
105
  }
104
106
  } catch {
@@ -109,27 +111,21 @@ function walkFiles(dir, matcher, results = [], maxDepth = 5, depth = 0) {
109
111
  return results
110
112
  }
111
113
 
112
- async function summarizeLogFile(file, toolHint) {
113
- const stream = createReadStream(file, { start: 0, end: 512 * 1024 })
114
+ async function summarizeLogFile(file, toolHint, knownTitle) {
115
+ const stream = createReadStream(file)
114
116
  let tool = toolHint
115
- let title = ''
117
+ let title = knownTitle || ''
116
118
  let firstPrompt = ''
117
- let timestamp = ''
118
- let lineCount = 0
119
-
120
119
  for await (const line of lines(stream)) {
121
120
  const trimmed = line.trim()
122
121
  if (!trimmed) continue
123
- lineCount++
122
+
124
123
  let rec
125
124
  try {
126
125
  rec = JSON.parse(trimmed)
127
126
  } catch {
128
127
  continue
129
128
  }
130
- if (!timestamp && rec.timestamp) {
131
- timestamp = typeof rec.timestamp === 'number' ? new Date(rec.timestamp).toISOString() : String(rec.timestamp)
132
- }
133
129
  if (rec.type === 'session_meta' || rec.type === 'response_item') tool = 'codex'
134
130
  if (rec.providerData || rec.type === 'function_call_result') tool = 'workbuddy'
135
131
  if (rec.type === 'custom-title' && rec.customTitle) title = rec.customTitle
@@ -137,7 +133,9 @@ async function summarizeLogFile(file, toolHint) {
137
133
  if (rec.type === 'summary' && rec.summary && !title) title = rec.summary
138
134
 
139
135
  if (!firstPrompt) {
140
- if (tool === 'codex' && rec.type === 'response_item' && rec.payload?.type === 'message' && rec.payload?.role === 'user') {
136
+ if (tool.startsWith('antigravity') && rec.type === 'USER_INPUT') {
137
+ firstPrompt = antigravityPrompt(rec.content) || (rec.media?.length ? '[图片]' : '')
138
+ } else if (tool === 'codex' && rec.type === 'response_item' && rec.payload?.type === 'message' && rec.payload?.role === 'user') {
141
139
  const raw = textOf(rec.payload.content)
142
140
  .replace(/^\s*<([a-z][\w-]*context)\b[^>]*>[\s\S]*?<\/\1>\s*/g, '')
143
141
  .trim()
@@ -162,15 +160,14 @@ async function summarizeLogFile(file, toolHint) {
162
160
  if (txt && txt !== '(中途打断)') firstPrompt = txt
163
161
  }
164
162
  }
165
- if (title && firstPrompt) break
166
- if (lineCount > 240 && firstPrompt) break
163
+ if (firstPrompt && (tool === 'codex' || tool.startsWith('antigravity'))) break
167
164
  }
168
165
 
169
- const rawPreview = (title || firstPrompt || '').replace(/\[(?:附图|图片|附件:[^\]]+)\]/g, '').replace(/\s+/g, ' ').trim()
166
+ const rawPreview = (title || firstPrompt || '').replace(/\s+/g, ' ').trim()
170
167
  return {
171
168
  tool,
169
+ title, firstPrompt,
172
170
  preview: rawPreview ? (rawPreview.length > 58 ? `${rawPreview.slice(0, 57)}…` : rawPreview) : '',
173
- timestamp,
174
171
  }
175
172
  }
176
173
 
@@ -180,46 +177,94 @@ function formatLocalTime(ms) {
180
177
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
181
178
  }
182
179
 
183
- export async function* iterateRecentSessions({
180
+ function antigravityFiles(root, toolHint) {
181
+ if (!existsSync(root)) return []
182
+ const files = []
183
+ const summaries = antigravitySummaries(root)
184
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
185
+ if (!entry.isDirectory()) continue
186
+ const logs = join(root, entry.name, '.system_generated', 'logs')
187
+ for (const name of ['transcript_full.jsonl', 'transcript.jsonl']) {
188
+ const file = join(logs, name)
189
+ const st = statSync(file, { throwIfNoEntry: false })
190
+ if (!st?.isFile() || !st.size) continue
191
+ const summary = summaries.get(entry.name)
192
+ files.push({ file, mtimeMs: summary?.updated || st.mtimeMs, size: st.size, toolHint, id: entry.name, root,
193
+ title: summary?.title, archived: summary?.archived })
194
+ break
195
+ }
196
+ }
197
+ return files
198
+ }
199
+
200
+ function codexTitles(dir) {
201
+ const index = join(dirname(dir), 'session_index.jsonl')
202
+ const titles = new Map()
203
+ if (!existsSync(index)) return titles
204
+ for (const line of readFileSync(index, 'utf8').split('\n')) {
205
+ if (!line) continue
206
+ try {
207
+ const { id, thread_name } = JSON.parse(line)
208
+ if (thread_name) titles.set(id, thread_name)
209
+ } catch { /* A live index can end in an incomplete line. */ }
210
+ }
211
+ return titles
212
+ }
213
+
214
+ export function createSessionCatalog({
184
215
  codexDir = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'sessions'),
185
216
  claudeDir = join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects'),
186
217
  workbuddyDir = join(process.env.WORKBUDDY_HOME || join(homedir(), '.workbuddy'), 'projects'),
187
- } = {}, maxCandidates = Infinity) {
188
- const codexFiles = walkFiles(codexDir, name => name.startsWith('rollout-') && name.endsWith('.jsonl'))
189
- .map(item => ({ ...item, toolHint: 'codex' }))
190
- const claudeFiles = walkFiles(claudeDir, name => name.endsWith('.jsonl') && !name.startsWith('agent-'))
191
- .map(item => ({ ...item, toolHint: 'claude-code' }))
192
- const workbuddyFiles = walkFiles(workbuddyDir, name => name.endsWith('.jsonl'))
193
- .map(item => ({ ...item, toolHint: 'workbuddy' }))
194
-
195
- const candidates = [...codexFiles, ...claudeFiles, ...workbuddyFiles]
196
- .sort((a, b) => b.mtimeMs - a.mtimeMs)
197
- .slice(0, maxCandidates)
198
-
199
- for (const cand of candidates) {
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
- }
207
- if (!info.preview) continue
208
- yield {
209
- tool: info.tool,
210
- toolLabel: tools[info.tool] || info.tool,
211
- file: cand.file,
212
- mtimeMs: cand.mtimeMs,
213
- timeLabel: formatLocalTime(cand.mtimeMs),
214
- sizeKB: Math.max(1, Math.round(cand.size / 1024)),
215
- preview: info.preview,
218
+ antigravityAppDir = antigravityStores()['antigravity-app'],
219
+ antigravityCliDir = antigravityStores()['antigravity-cli'],
220
+ } = {}) {
221
+ const rollout = name => name.startsWith('rollout-') && name.endsWith('.jsonl')
222
+ const index = codexTitles(codexDir)
223
+ const codex = (dir, archived) => walkFiles(dir, rollout).map(item => ({
224
+ ...item, toolHint: 'codex', archived,
225
+ title: index.get(basename(item.file, '.jsonl').slice(-36)),
226
+ }))
227
+ const candidates = [
228
+ ...codex(codexDir, false),
229
+ ...codex(join(dirname(codexDir), 'archived_sessions'), true),
230
+ ...walkFiles(claudeDir, name => name.endsWith('.jsonl') && !name.startsWith('agent-')).map(item => ({ ...item, toolHint: 'claude-code' })),
231
+ ...walkFiles(workbuddyDir, name => name.endsWith('.jsonl')).map(item => ({ ...item, toolHint: 'workbuddy' })),
232
+ ...antigravityFiles(antigravityAppDir, 'antigravity-app'),
233
+ ...antigravityFiles(antigravityCliDir, 'antigravity-cli'),
234
+ ].sort((a, b) => b.mtimeMs - a.mtimeMs)
235
+ const summaries = new Map()
236
+ return async function* list({ group, query, signal } = {}) {
237
+ const term = query?.trim().toLowerCase()
238
+ for (const cand of candidates) {
239
+ if (signal?.aborted) return
240
+ if (cand.archived && query === undefined) continue
241
+ if (group && group !== (cand.toolHint.startsWith('antigravity') ? 'antigravity' : cand.toolHint)) continue
242
+ if (!summaries.has(cand.file)) {
243
+ const title = cand.title || (cand.id && antigravityTitle(cand.root, cand.id))
244
+ summaries.set(cand.file, summarizeLogFile(cand.file, cand.toolHint, title))
245
+ }
246
+ let info
247
+ try {
248
+ info = await summaries.get(cand.file)
249
+ } catch (error) {
250
+ if (error.code === 'ENOENT') continue
251
+ throw error
252
+ }
253
+ if (!info.preview || (term && ![info.title, info.firstPrompt].some(s => s.toLowerCase().includes(term)))) continue
254
+ yield {
255
+ tool: info.tool, toolLabel: tools[info.tool] || info.tool, file: cand.file,
256
+ mtimeMs: cand.mtimeMs, timeLabel: formatLocalTime(cand.mtimeMs),
257
+ sizeKB: Math.max(1, Math.round(cand.size / 1024)), preview: info.preview,
258
+ ...(cand.archived && { archived: true }),
259
+ }
216
260
  }
217
261
  }
218
262
  }
219
263
 
220
264
  export async function scanRecentSessions({ limit = 12, ...directories } = {}) {
221
265
  const results = []
222
- for await (const session of iterateRecentSessions(directories, limit * 3)) {
266
+ if (limit <= 0) return results
267
+ for await (const session of createSessionCatalog(directories)()) {
223
268
  results.push(session)
224
269
  if (results.length >= limit) break
225
270
  }