@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.
package/src/index.mjs CHANGED
@@ -1,6 +1,10 @@
1
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
- import { basename, join, resolve } from 'node:path'
1
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+ import { antigravitySummaries, nativeAntigravityLog, readAntigravity } from './antigravity.mjs'
3
5
  import { readClaudeAi } from './claude-ai.mjs'
6
+ import { prepareAttachmentPreviews } from './attachment-previews.mjs'
7
+ import { collectExternalFiles, nativeSessionRoot } from './external-files.mjs'
4
8
  import { readClaudeCode } from './claude-code.mjs'
5
9
  import { readCodex } from './codex.mjs'
6
10
  import { readWorkBuddy } from './workbuddy.mjs'
@@ -17,21 +21,22 @@ import { openBrowser, serveReplayDir } from './server.mjs'
17
21
  import { binSeconds, describeStats, kindOf, minutes, sumStats, timeline, waitThreshold } from './timeline.mjs'
18
22
 
19
23
  const readers = {
20
- codex: async (files, options) => readCodex(await readJsonl(files, options), options),
21
- workbuddy: async (files, options) => readWorkBuddy(await readJsonl(files, options), options),
22
- 'claude-code': async (files, options) => readClaudeCode(await readJsonl(files, options), options),
23
- 'claude-ai': async (files, options) => readClaudeAi(JSON.parse(readFileSync(files[0], 'utf8')), options),
24
+ codex: readCodex,
25
+ workbuddy: readWorkBuddy,
26
+ 'claude-code': readClaudeCode,
27
+ 'claude-ai': readClaudeAi,
24
28
  }
25
29
 
26
- function defaultOutDirForLog(filePath, tool) {
30
+ function createDefaultOutDir(filePath, tool) {
27
31
  const base = basename(filePath)
28
32
  .replace(/\.jsonl(?:\.zst)?$|\.json$/i, '')
29
33
  .replace(/^rollout-/, '')
30
34
  .replace(/[^a-zA-Z0-9_-]+/g, '-')
31
35
  .replace(/^-+|-+$/g, '')
32
36
  .slice(0, 32)
33
- const slug = base || `${tool || 'session'}-${Date.now().toString(36)}`
34
- return resolve('replays', slug)
37
+ .replace(/-+$/g, '')
38
+ const slug = base || tool || 'session'
39
+ return mkdtempSync(join(resolve(tmpdir()), `encore-${slug}-`))
35
40
  }
36
41
 
37
42
  export async function importRawSession(files, {
@@ -47,15 +52,24 @@ export async function importRawSession(files, {
47
52
  clip,
48
53
  conversation,
49
54
  includeMemory = false,
55
+ assetRoots,
50
56
  } = {}) {
51
57
  const fileList = [].concat(files).map(f => resolve(f))
52
- const detectedTool = tool || (await detectInput(fileList[0])).tool || 'codex'
53
- if (!readers[detectedTool]) {
58
+ let detectedTool = tool || (await detectInput(fileList[0])).tool || 'codex'
59
+ const isAntigravity = ['antigravity', 'antigravity-app', 'antigravity-cli'].includes(detectedTool)
60
+ const native = isAntigravity && nativeAntigravityLog(fileList[0])
61
+ if (native) Object.assign(native, antigravitySummaries(dirname(native.root)).get(native.id))
62
+ if (isAntigravity) detectedTool = native?.tool || 'antigravity'
63
+ if (!isAntigravity && !readers[detectedTool]) {
54
64
  throw new Error(`Unsupported session format: ${detectedTool}`)
55
65
  }
56
- const targetDir = outDir ? resolve(outDir) : defaultOutDirForLog(fileList[0], detectedTool)
57
66
  const window = { from, to }
58
- const raw = cutSession(await readers[detectedTool](fileList, { ...window, conversation, includeMemory }), window)
67
+ const records = detectedTool === 'claude-ai' ? JSON.parse(readFileSync(fileList[0], 'utf8')) : await readJsonl(fileList, window)
68
+ const nativeRoot = isAntigravity ? native?.workspaces?.[0] : await nativeSessionRoot(fileList[0], detectedTool, records)
69
+ const sessionData = isAntigravity
70
+ ? await readAntigravity(records, { file: fileList[0], tool: detectedTool, native, images, assetRoots })
71
+ : readers[detectedTool](records, { ...window, conversation, includeMemory })
72
+ const raw = cutSession(sessionData, window)
59
73
 
60
74
  if (title) raw.title = title
61
75
  if (description !== undefined) raw.description = description
@@ -64,40 +78,53 @@ export async function importRawSession(files, {
64
78
  if (raw.description === undefined) raw.description = ''
65
79
  if (!raw.deliverables) raw.deliverables = []
66
80
 
67
- if (existsSync(targetDir) && images) {
68
- for (const name of readdirSync(targetDir).filter(file => file.endsWith('.webp'))) {
69
- rmSync(join(targetDir, name))
81
+ const createdTempDir = !outDir
82
+ const targetDir = outDir ? resolve(outDir) : createDefaultOutDir(fileList[0], detectedTool)
83
+
84
+ try {
85
+ if (outDir && existsSync(targetDir) && images) {
86
+ for (const name of readdirSync(targetDir).filter(file => file.endsWith('.webp'))) {
87
+ rmSync(join(targetDir, name))
88
+ }
70
89
  }
71
- }
72
90
 
73
- const resolvedLang = resolveLang(lang === 'auto' ? undefined : lang)
74
- const withImages = await extractImages(raw, targetDir, {
75
- keep: images,
76
- width: imageWidth,
77
- lang: resolvedLang,
78
- })
79
- const redacted = redactSession(withImages)
80
- const limit = clip ? Number(clip) : undefined
81
- const session = clipSession(redacted, limit ? { input: limit, output: limit } : undefined)
82
- const leaks = findLeaks(session)
91
+ const resolvedLang = resolveLang(lang === 'auto' ? undefined : lang)
92
+ const withImages = await extractImages(raw, targetDir, {
93
+ keep: images,
94
+ width: imageWidth,
95
+ lang: resolvedLang,
96
+ })
97
+ const sessionRoots = native && !assetRoots
98
+ ? [native.root, ...(native.workspaces || []).slice(1).filter(dir => existsSync(dir))]
99
+ : []
100
+ await collectExternalFiles(withImages, targetDir, assetRoots, nativeRoot, sessionRoots)
101
+ const redacted = redactSession(withImages)
102
+ const limit = clip ? Number(clip) : undefined
103
+ const session = clipSession(redacted, limit ? { input: limit, output: limit } : undefined)
104
+ const leaks = findLeaks(session)
83
105
 
84
- mkdirSync(targetDir, { recursive: true })
85
- const sessionFile = join(targetDir, 'session.json')
86
- writeFileSync(sessionFile, `${JSON.stringify(session, null, 2)}\n`, 'utf8')
87
- const assets = writePlayerAssets(targetDir, {
88
- title: session.title,
89
- lang: lang || session.lang || 'auto',
90
- })
106
+ mkdirSync(targetDir, { recursive: true })
107
+ await prepareAttachmentPreviews(session, targetDir)
108
+ const sessionFile = join(targetDir, 'session.json')
109
+ writeFileSync(sessionFile, `${JSON.stringify(session, null, 2)}\n`, 'utf8')
110
+ const assets = writePlayerAssets(targetDir, {
111
+ title: session.title,
112
+ lang: lang || session.lang || 'auto',
113
+ })
91
114
 
92
- return {
93
- mode: 'import',
94
- tool: detectedTool,
95
- toolLabel: tools[detectedTool] || detectedTool,
96
- dir: targetDir,
97
- sessionFile,
98
- session,
99
- leaks,
100
- assets,
115
+ return {
116
+ mode: 'import',
117
+ tool: detectedTool,
118
+ toolLabel: tools[detectedTool] || detectedTool,
119
+ dir: targetDir,
120
+ sessionFile,
121
+ session,
122
+ leaks,
123
+ assets,
124
+ }
125
+ } catch (err) {
126
+ if (createdTempDir) rmSync(targetDir, { recursive: true, force: true })
127
+ throw err
101
128
  }
102
129
  }
103
130
 
@@ -105,13 +132,14 @@ export async function rebuildReplayDir(dirOrSessionFile, {
105
132
  lang,
106
133
  title,
107
134
  description,
135
+ assetRoots,
108
136
  } = {}) {
109
137
  const detected = await detectInput(dirOrSessionFile)
110
138
  const targetDir = detected.dir
111
139
  const sessionFile = detected.sessionFile
112
140
  const session = JSON.parse(readFileSync(sessionFile, 'utf8'))
113
141
 
114
- let modified = false
142
+ let modified = await collectExternalFiles(session, targetDir, assetRoots)
115
143
  if (title !== undefined && title !== session.title) {
116
144
  session.title = title
117
145
  modified = true
@@ -154,6 +182,7 @@ export async function rebuildReplayDir(dirOrSessionFile, {
154
182
  }
155
183
  }
156
184
  }
185
+ if (await prepareAttachmentPreviews(session, targetDir)) modified = true
157
186
  if (modified) {
158
187
  writeFileSync(sessionFile, `${JSON.stringify(session, null, 2)}\n`, 'utf8')
159
188
  }
package/src/markdown.mjs CHANGED
@@ -58,6 +58,9 @@ function isTableSeparator(line) {
58
58
  return cells.length > 0 && cells.every(c => /^:?-{2,}:?$/.test(c))
59
59
  }
60
60
 
61
+ const openingFence = /^ {0,3}(`{3,})([^`]*)$/
62
+ const closingFence = /^ {0,3}(`{3,})[ \t]*$/
63
+
61
64
  export function renderMarkdown(source) {
62
65
  const raw = String(source ?? '').replace(/\r\n/g, '\n').trim()
63
66
  if (!raw) return ''
@@ -74,16 +77,17 @@ export function renderMarkdown(source) {
74
77
  continue
75
78
  }
76
79
 
77
- const fence = line.match(/^```([\w-]*)\s*$/)
80
+ const fence = line.match(openingFence)
78
81
  if (fence) {
79
- const lang = fence[1]
82
+ const lang = fence[2].trim().split(/\s+/, 1)[0]
80
83
  const codeLines = []
81
84
  i++
82
- while (i < lines.length && !/^```\s*$/.test(lines[i])) {
83
- codeLines.push(lines[i])
84
- i++
85
+ while (i < lines.length) {
86
+ const codeLine = lines[i++]
87
+ const close = codeLine.match(closingFence)
88
+ if (close && close[1].length >= fence[1].length) break
89
+ codeLines.push(codeLine)
85
90
  }
86
- if (i < lines.length) i++
87
91
  const cls = lang ? ` class="language-${escapeHtml(lang)}"` : ''
88
92
  out.push(`<pre><code${cls}>${escapeHtml(codeLines.join('\n'))}</code></pre>`)
89
93
  continue
@@ -149,11 +153,12 @@ export function renderMarkdown(source) {
149
153
  continue
150
154
  }
151
155
 
152
- const paraLines = []
156
+ const paraLines = [renderInline(line)]
157
+ i++
153
158
  while (
154
159
  i < lines.length &&
155
160
  lines[i].trim() !== '' &&
156
- !/^```/.test(lines[i]) &&
161
+ !openingFence.test(lines[i]) &&
157
162
  !/^(#{1,6})\s+/.test(lines[i]) &&
158
163
  !/^(?:-{3,}|\*{3,}|_{3,})\s*$/.test(lines[i].trim()) &&
159
164
  !/^\s*>\s?/.test(lines[i]) &&
@@ -164,9 +169,7 @@ export function renderMarkdown(source) {
164
169
  paraLines.push(renderInline(lines[i]))
165
170
  i++
166
171
  }
167
- if (paraLines.length) {
168
- out.push(`<p>${paraLines.join('<br>')}</p>`)
169
- }
172
+ out.push(`<p>${paraLines.join('<br>')}</p>`)
170
173
  }
171
174
 
172
175
  return out.join('\n')
@@ -20,6 +20,7 @@ export function buildStandalonePlayerJs({ write = true } = {}) {
20
20
  'i18n.mjs',
21
21
  'markdown.mjs',
22
22
  'timeline.mjs',
23
+ 'attachment-reader.mjs',
23
24
  'render.mjs',
24
25
  'player-runtime.mjs',
25
26
  ]
@@ -68,7 +69,9 @@ export function renderIndexHtml({ title = 'Agent Session Replay', lang = 'auto',
68
69
  <link rel="stylesheet" href="./encore-player.css">
69
70
  </head>
70
71
  <body class="encore-page">
71
- <div data-encore-player src="${escapeHtml(sessionSrc)}"${dataLangAttr}></div>
72
+ <div data-encore-player src="${escapeHtml(sessionSrc)}"${dataLangAttr}>
73
+ <div class="encore-loading" role="status">${htmlLang === 'en' ? 'Loading replay…' : '正在加载回放…'}</div>
74
+ </div>
72
75
  <script src="./encore-player.js" defer></script>
73
76
  </body>
74
77
  </html>