@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/README.md +64 -103
- package/README.zh-CN.md +65 -97
- package/bin/encore.mjs +60 -120
- package/package.json +5 -3
- package/player/encore-player.css +125 -44
- package/player/encore-player.js +563 -287
- package/schema/session.schema.json +64 -2
- package/skills/encore/SKILL.md +39 -35
- package/src/antigravity.mjs +162 -0
- package/src/attachment-previews.mjs +169 -0
- package/src/attachment-reader.mjs +169 -0
- package/src/claude-ai.mjs +3 -1
- package/src/claude-code.mjs +11 -7
- package/src/codex.mjs +10 -3
- package/src/common.mjs +30 -7
- package/src/detect.mjs +96 -51
- package/src/external-files.mjs +193 -0
- package/src/i18n.mjs +108 -28
- package/src/index.d.ts +22 -3
- package/src/index.mjs +73 -44
- package/src/markdown.mjs +14 -11
- package/src/player-assets.mjs +4 -1
- package/src/player-runtime.mjs +147 -131
- package/src/render.mjs +83 -83
- package/src/server.mjs +2 -0
- package/src/session-picker.mjs +162 -0
- package/src/timeline.mjs +44 -35
- package/src/workbuddy.mjs +6 -5
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
},
|
|
13
13
|
"tool": {
|
|
14
14
|
"type": "string",
|
|
15
|
-
"enum": ["codex", "claude-code", "claude-ai", "workbuddy"],
|
|
15
|
+
"enum": ["codex", "claude-code", "claude-ai", "workbuddy", "antigravity", "antigravity-app", "antigravity-cli"],
|
|
16
16
|
"description": "Source AI agent environment identifier."
|
|
17
17
|
},
|
|
18
18
|
"model": {
|
|
@@ -144,13 +144,75 @@
|
|
|
144
144
|
"title": { "type": "string" },
|
|
145
145
|
"href": { "type": "string" },
|
|
146
146
|
"meta": { "type": "string" },
|
|
147
|
-
"cover": { "type": "string" }
|
|
147
|
+
"cover": { "type": "string" },
|
|
148
|
+
"previewSheet": { "type": "string" },
|
|
149
|
+
"source": {
|
|
150
|
+
"type": "object", "required": ["path"],
|
|
151
|
+
"description": "External reference consumed at export. An optional SHA-256 must come from the session at handoff.",
|
|
152
|
+
"properties": { "path": { "type": "string" }, "sha256": { "type": "string", "pattern": "^[0-9a-fA-F]{64}$" } }
|
|
153
|
+
},
|
|
154
|
+
"availability": { "enum": ["verified", "export-copy", "missing"] },
|
|
155
|
+
"sessionSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
|
|
156
|
+
"unavailableReason": { "enum": ["outside-root", "unreadable"] },
|
|
157
|
+
"previewColumns": { "type": "array", "items": { "type": "string" } },
|
|
158
|
+
"revision": {
|
|
159
|
+
"type": "object",
|
|
160
|
+
"description": "Earlier local file and the corresponding line or cell to compare in both versions.",
|
|
161
|
+
"required": ["href", "label"],
|
|
162
|
+
"oneOf": [{ "required": ["page", "linePrefix"] }, { "required": ["sheet", "cell"] }],
|
|
163
|
+
"properties": {
|
|
164
|
+
"href": { "type": "string" }, "label": { "type": "string" },
|
|
165
|
+
"page": { "type": "integer", "minimum": 1 }, "linePrefix": { "type": "string", "minLength": 1 },
|
|
166
|
+
"sheet": { "type": "string", "minLength": 1 }, "cell": { "type": "string", "pattern": "^[a-zA-Z]+[1-9][0-9]*$" }
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
"preview": {
|
|
170
|
+
"properties": {
|
|
171
|
+
"change": {
|
|
172
|
+
"type": "object", "required": ["before", "after"],
|
|
173
|
+
"properties": { "before": { "type": "string" }, "after": { "type": "string" } }
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
"oneOf": [
|
|
177
|
+
{
|
|
178
|
+
"type": "object", "required": ["type", "pages"],
|
|
179
|
+
"properties": {
|
|
180
|
+
"type": { "const": "pdf" },
|
|
181
|
+
"pages": { "type": "array", "minItems": 1, "items": {
|
|
182
|
+
"type": "object", "required": ["src", "width", "height"],
|
|
183
|
+
"properties": { "src": { "type": "string" }, "width": { "type": "integer", "minimum": 1 }, "height": { "type": "integer", "minimum": 1 } }
|
|
184
|
+
} }
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
"type": "object", "required": ["type", "src", "sheet", "count", "rows"],
|
|
189
|
+
"properties": {
|
|
190
|
+
"type": { "const": "xlsx" }, "src": { "type": "string" }, "sheet": { "type": "string" },
|
|
191
|
+
"count": { "type": "integer", "minimum": 1 },
|
|
192
|
+
"rows": { "type": "array", "items": { "type": "array", "items": { "type": "string" } } }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
]
|
|
196
|
+
},
|
|
197
|
+
"portrait": {
|
|
198
|
+
"description": "Portrait cut of the same video, sharing the landscape cut's timeline.",
|
|
199
|
+
"type": "object",
|
|
200
|
+
"required": ["href"],
|
|
201
|
+
"properties": {
|
|
202
|
+
"href": { "type": "string" },
|
|
203
|
+
"cover": { "type": "string" }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
148
206
|
}
|
|
149
207
|
},
|
|
150
208
|
"sessionItem": {
|
|
151
209
|
"type": "object",
|
|
152
210
|
"required": ["type"],
|
|
153
211
|
"properties": {
|
|
212
|
+
"deliverables": {
|
|
213
|
+
"type": "array", "description": "Files handed over at this event.",
|
|
214
|
+
"items": { "$ref": "#/$defs/deliverable" }
|
|
215
|
+
},
|
|
154
216
|
"type": {
|
|
155
217
|
"type": "string",
|
|
156
218
|
"enum": ["user", "assistant", "reasoning", "tool", "compact"]
|
package/skills/encore/SKILL.md
CHANGED
|
@@ -1,80 +1,84 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: encore
|
|
3
3
|
description: >
|
|
4
|
-
Export, curate, and
|
|
5
|
-
Use when the user asks to export a
|
|
4
|
+
Export, curate, and rebuild portable AI Agent replays (Codex, Claude Code, Claude.ai, WorkBuddy, Antigravity App and CLI) with Encore.
|
|
5
|
+
Use when the user asks to export a Raw Log into a Replay, curate `session.json`, select and label `.webp` Frames, review packaged Attachments or Deliverables, write a title and opening description, or redact residual sensitive details before publishing.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
# Encore —
|
|
8
|
+
# Encore — Session Replay & Curation Skill
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
Encore turns a Raw Log from **Codex**, **Claude Code**, **Claude.ai**, **WorkBuddy**, or **Antigravity** into a portable **Replay** rendered by the standalone **Player** (**Left**: Turns, Tool calls, Sub-agents, Attachments, Deliverables, and Frames; **Right**: live Context Snapshot inspector and Compaction boundaries; **Bottom**: Step timeline).
|
|
11
11
|
|
|
12
|
-
While `npx @niracler/encore`
|
|
12
|
+
While `npx @niracler/encore@latest` builds an immediately playable Replay, this skill guides **Curation** before publishing.
|
|
13
13
|
|
|
14
14
|
---
|
|
15
15
|
|
|
16
16
|
## Workflow
|
|
17
17
|
|
|
18
|
-
### 1.
|
|
18
|
+
### 1. Export the Initial Replay
|
|
19
19
|
|
|
20
|
-
- If the user
|
|
20
|
+
- If the user has not specified a Raw Log yet, list recent local sessions:
|
|
21
21
|
```bash
|
|
22
|
-
npx @niracler/encore --list
|
|
22
|
+
npx @niracler/encore@latest --list
|
|
23
23
|
```
|
|
24
|
-
- Export the target
|
|
24
|
+
- Export the target Raw Log into an explicit Replay directory with `-o` so it is saved outside the default temporary preview directory, without blocking on the preview server (pass `--asset-root <dir>` if referenced Attachments or Deliverables live outside the current working directory and native session workspace):
|
|
25
25
|
```bash
|
|
26
|
-
npx @niracler/encore <path-to-log.jsonl> -o ./replays/<slug> --no-serve
|
|
26
|
+
npx @niracler/encore@latest <path-to-log.jsonl> -o ./replays/<slug> --no-serve
|
|
27
27
|
```
|
|
28
|
-
-
|
|
29
|
-
- `session.json` —
|
|
30
|
-
- `*.webp` — deduplicated embedded
|
|
31
|
-
- `
|
|
28
|
+
- Output files:
|
|
29
|
+
- `session.json` — canonical **Session** data (`title`, `description`, `initialContext`, `deliverables`, `frames`, `items`)
|
|
30
|
+
- `*.webp` — deduplicated embedded **Frames** extracted from the Raw Log
|
|
31
|
+
- `attachments/` — collected **Attachments** and **Deliverables** within allowed **Asset Roots**, plus generated PDF/XLSX previews when applicable
|
|
32
|
+
- `index.html`, `encore-player.js`, `encore-player.css` — standalone **Player** (`<div data-encore-player src="./session.json"></div>`)
|
|
32
33
|
|
|
33
34
|
---
|
|
34
35
|
|
|
35
|
-
### 2.
|
|
36
|
+
### 2. Curate & Label Frames (`frames[]`)
|
|
36
37
|
|
|
37
|
-
Raw
|
|
38
|
+
Raw exports often contain 15–40 Frames, including terminal errors, minor tweaks, or duplicate views.
|
|
38
39
|
|
|
39
40
|
1. **Inspect every image**: Use `view_image` (or `Read`) to visually inspect each `.webp` file listed in `session.json -> frames`.
|
|
40
|
-
2. **
|
|
41
|
-
3. **Write
|
|
41
|
+
2. **Keep key milestones**: Remove broken renders, repetitive micro-adjustments, or uninformative entries from `session.json -> frames`. Keep **3 to 12 milestone Frames** showing progression from reference to final result.
|
|
42
|
+
3. **Write concrete labels**: Replace fallback labels (`过程画面 #1` / `Agent Frame #1`) with concrete 6–16 character labels stating what changed:
|
|
42
43
|
- Good: `"第一张草图:信息过载"`, `"V2:改为深色双栏网格"`, `"终稿:定版课程海报"`
|
|
43
44
|
- Bad: `"图片 1"`, `"修改后"`, `"赋能视觉升级版"`
|
|
44
45
|
|
|
45
46
|
---
|
|
46
47
|
|
|
47
|
-
### 3. Title &
|
|
48
|
+
### 3. Write Title & Opening Description (`title` & `description`)
|
|
48
49
|
|
|
49
|
-
Edit the top-level `title` and `description` in `session.json
|
|
50
|
+
Edit the top-level `title` and `description` in `session.json`:
|
|
50
51
|
|
|
51
52
|
1. **`title` (8–24 chars)**:
|
|
52
53
|
- State the concrete task, turning point, or friction directly.
|
|
53
54
|
- Good: `"嫌太难看,重新设计七阶段图"`, `"把内部播放器拆成开源工具 Encore"`, `"排查 Mesh 40940 冲突并补齐测试"`
|
|
54
|
-
-
|
|
55
|
+
- Skip empty buzzwords (`赋能`, `深度剖析`, `全方位重构`, `探索与实践`, `基于 AI 的…`).
|
|
55
56
|
2. **`description` (1–3 sentences, 40–120 chars)**:
|
|
56
|
-
- Shown
|
|
57
|
-
-
|
|
58
|
-
- Write
|
|
57
|
+
- Shown in the **Player** before the viewer clicks **Play**.
|
|
58
|
+
- State **what problem the Session tackled**, **what key pivot or Sub-agent collaboration happened**, and **what Deliverable or outcome was reached**.
|
|
59
|
+
- Write plain, direct prose without repeating the title.
|
|
59
60
|
|
|
60
61
|
---
|
|
61
62
|
|
|
62
|
-
### 4.
|
|
63
|
+
### 4. Redaction, Packaged Files, & Turn Trimming
|
|
63
64
|
|
|
64
|
-
`
|
|
65
|
+
Automatic **Redaction** rewrites `session.json` to hide home paths (`~`), API keys (`[密钥]`), emails (`[邮箱]`), and private IPs (`[内网地址]`), and prints non-blocking **Leak Check** warnings.
|
|
65
66
|
|
|
66
|
-
1. **Check
|
|
67
|
-
2. **
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
1. **Review Leak Check warnings**: Inspect every path reported under `Leak check found ... potential sensitive snippet(s)`.
|
|
68
|
+
2. **Redact residual sensitive details in `initialContext` and `items[]`**: Regex cannot catch internal codenames, colleague names, intranet hostnames, or business figures. Inspect `initialContext.mem`, `initialContext.sys`, `items[type="compact"].text`, and `items[]`, replacing sensitive passages with a clear marker such as `(涉及内部业务细节,已略去)` or `(Internal context redacted)`.
|
|
69
|
+
3. **Inspect packaged Attachments and Deliverables (`attachments/`)**: Automatic Redaction only rewrites `session.json`; it does not modify packaged PDFs, spreadsheets, images, or videos. Verify each collected file before publishing, and remove or replace any file that contains private data.
|
|
70
|
+
4. **Trim off-topic Turns**: If the Raw Log starts or ends with an unrelated topic, either re-export with `--from <ISO> --to <ISO>` or remove those Events from `session.json -> items`.
|
|
70
71
|
|
|
71
72
|
---
|
|
72
73
|
|
|
73
|
-
### 5.
|
|
74
|
+
### 5. Rebuild & Verify
|
|
74
75
|
|
|
75
|
-
- Because `index.html`
|
|
76
|
-
- Run
|
|
77
|
-
- To launch a live local preview for the user:
|
|
76
|
+
- Because `index.html` loads `./session.json` at runtime, edits to `session.json` appear immediately on browser refresh.
|
|
77
|
+
- Run a **Rebuild** after editing `session.json` so Encore refreshes Player assets, syncs `<title>`, refreshes attachment previews, drops references to deleted Frames, and re-runs the **Leak Check** without re-importing the Raw Log or overwriting Curation edits:
|
|
78
78
|
```bash
|
|
79
|
-
npx @niracler/encore
|
|
79
|
+
npx @niracler/encore@latest ./replays/<slug> --no-serve
|
|
80
|
+
```
|
|
81
|
+
- Launch a local preview for the user:
|
|
82
|
+
```bash
|
|
83
|
+
npx @niracler/encore@latest play ./replays/<slug>
|
|
80
84
|
```
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs'
|
|
4
|
+
import { readFile, realpath, stat } from 'node:fs/promises'
|
|
5
|
+
import { homedir } from 'node:os'
|
|
6
|
+
import { dirname, join, relative, resolve, sep } from 'node:path'
|
|
7
|
+
import { createTranscript, describeTool } from './common.mjs'
|
|
8
|
+
import { redactText } from './redact.mjs'
|
|
9
|
+
import { fileReferences, recordedText, within } from './external-files.mjs'
|
|
10
|
+
|
|
11
|
+
export const antigravityStores = () => ({
|
|
12
|
+
'antigravity-app': join(homedir(), '.gemini', 'antigravity', 'brain'),
|
|
13
|
+
'antigravity-cli': join(homedir(), '.gemini', 'antigravity-cli', 'brain'),
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
export function nativeAntigravityLog(file) {
|
|
17
|
+
const path = realpathSync.native(file)
|
|
18
|
+
for (const [tool, store] of Object.entries(antigravityStores())) {
|
|
19
|
+
if (!existsSync(store)) continue
|
|
20
|
+
const root = realpathSync.native(store)
|
|
21
|
+
const [id, system, logs, name, ...rest] = relative(root, path).split(sep)
|
|
22
|
+
if (id !== '..' && system === '.system_generated' && logs === 'logs' &&
|
|
23
|
+
/^transcript(?:_full)?\.jsonl$/.test(name) && !rest.length) {
|
|
24
|
+
return { tool, root: join(root, id), id }
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Newer installations index conversation titles, activity, workspaces and App archives in SQLite.
|
|
30
|
+
export function antigravitySummaries(root) {
|
|
31
|
+
const path = join(dirname(root), 'conversation_summaries.db')
|
|
32
|
+
if (!existsSync(path)) return new Map()
|
|
33
|
+
let db
|
|
34
|
+
try {
|
|
35
|
+
const Database = process.getBuiltinModule?.('node:sqlite')?.DatabaseSync
|
|
36
|
+
db = Database && new Database(path, { readOnly: true })
|
|
37
|
+
function query(sql) {
|
|
38
|
+
if (db) return db.prepare(sql).all()
|
|
39
|
+
const result = spawnSync('sqlite3', ['-readonly', '-json', path, sql], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
|
|
40
|
+
if (result.error || result.status !== 0) throw result.error || new Error(result.stderr)
|
|
41
|
+
return JSON.parse(result.stdout || '[]')
|
|
42
|
+
}
|
|
43
|
+
const summaries = query('SELECT conversation_id, title, last_modified_time, workspace_uris FROM conversation_summaries')
|
|
44
|
+
const hasSearch = query("SELECT 1 FROM sqlite_master WHERE name = 'conversations_fts'").length
|
|
45
|
+
const archived = new Set(hasSearch ? query("SELECT DISTINCT conversation_id FROM conversations_fts WHERE archived IN (1, '1')").map(r => r.conversation_id) : [])
|
|
46
|
+
return new Map(summaries.map(row => {
|
|
47
|
+
const uris = JSON.parse(row.workspace_uris || '[]') || []
|
|
48
|
+
const workspaces = uris.filter(uri => typeof uri === 'string' && uri.startsWith('file:///')).map(uri => fileURLToPath(uri))
|
|
49
|
+
return [row.conversation_id, { title: row.title, workspaces, archived: archived.has(row.conversation_id),
|
|
50
|
+
updated: Date.parse(row.last_modified_time.replace(' ', 'T')) }]
|
|
51
|
+
}))
|
|
52
|
+
} catch {
|
|
53
|
+
// The index is optional on older installations. The transcript and annotations remain usable.
|
|
54
|
+
return new Map()
|
|
55
|
+
} finally {
|
|
56
|
+
db?.close()
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function antigravityTitle(root, id) {
|
|
61
|
+
const path = join(dirname(root), 'annotations', id + '.pbtxt')
|
|
62
|
+
if (!existsSync(path)) return ''
|
|
63
|
+
const literal = readFileSync(path, 'utf8').match(/^title:\s*("(?:[^"\\]|\\.)*")/m)?.[1]
|
|
64
|
+
if (!literal) return ''
|
|
65
|
+
try { return JSON.parse(literal) } catch { return '' } // Unrecognized protobuf escape: use the first prompt.
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function antigravityPrompt(content = '') {
|
|
69
|
+
const request = content.match(/<USER_REQUEST>([\s\S]*?)(?:<\/USER_REQUEST>|$)/)?.[1] ?? content
|
|
70
|
+
return request.replace(/<external_system_instructions>[\s\S]*?(?:<\/external_system_instructions>|$)/g, '').trim()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function isAntigravityRecord(rec) {
|
|
74
|
+
return Number.isInteger(rec?.step_index) && typeof rec.created_at === 'string' &&
|
|
75
|
+
typeof rec.source === 'string' && typeof rec.type === 'string'
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function loadMedia(media, logDir, roots, userSelected = false) {
|
|
79
|
+
const images = []
|
|
80
|
+
for (const { uri, mime_type: mime } of media || []) {
|
|
81
|
+
if (!mime?.startsWith('image/')) continue
|
|
82
|
+
const path = fileReferences([uri], logDir)[0]?.source?.path
|
|
83
|
+
if (!path) continue
|
|
84
|
+
try {
|
|
85
|
+
const actual = await realpath(path)
|
|
86
|
+
if ((userSelected || roots.some(root => within(actual, root))) && (await stat(actual)).isFile()) {
|
|
87
|
+
images.push({ mime, base64: (await readFile(actual)).toString('base64') })
|
|
88
|
+
}
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (!['ENOENT', 'ENOTDIR', 'EACCES', 'EPERM', 'ELOOP'].includes(error.code)) throw error
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return images
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function reviewedFiles(name, args, cwd) {
|
|
97
|
+
if (name === 'notify_user' && Array.isArray(args.PathsToReview)) return fileReferences(args.PathsToReview, cwd)
|
|
98
|
+
if (name === 'exit_plan_mode' && typeof args.plan === 'string' && args.plan.trim()) {
|
|
99
|
+
const plan = args.plan.trim()
|
|
100
|
+
if (/^(?:file:\/\/|\/|[A-Z]:[\\/])[^\n]*\.md$/i.test(plan)) return fileReferences([plan], cwd)
|
|
101
|
+
return [{ title: 'implementation_plan.md', [recordedText]: redactText(plan) }]
|
|
102
|
+
}
|
|
103
|
+
return []
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function readAntigravity(records, { file, tool, native, images, assetRoots }) {
|
|
107
|
+
const transcript = createTranscript()
|
|
108
|
+
const logDir = dirname(file)
|
|
109
|
+
const defaults = [process.cwd(), ...(native?.workspaces || []).filter(dir => existsSync(dir))]
|
|
110
|
+
const roots = await Promise.all((assetRoots?.length ? assetRoots : defaults).map(dir => realpath(resolve(dir))))
|
|
111
|
+
const cwd = native?.workspaces?.[0] || native?.root
|
|
112
|
+
// Native recordings own their media directory. A detached log only gets the caller's asset roots.
|
|
113
|
+
if (native) roots.push(await realpath(native.root))
|
|
114
|
+
const userSelected = Boolean(native?.workspaces?.length && !assetRoots)
|
|
115
|
+
let pending = []
|
|
116
|
+
let model
|
|
117
|
+
let tokens = 0
|
|
118
|
+
for (const record of records) {
|
|
119
|
+
const { type, created_at: time, content = '', step_index: step } = record
|
|
120
|
+
if (type === 'USER_INPUT') {
|
|
121
|
+
pending = []
|
|
122
|
+
transcript.user(antigravityPrompt(content), time, {
|
|
123
|
+
images: images ? await loadMedia(record.media, logDir, roots, userSelected) : [],
|
|
124
|
+
cwd,
|
|
125
|
+
})
|
|
126
|
+
} else if (type === 'PLANNER_RESPONSE') {
|
|
127
|
+
pending = []
|
|
128
|
+
model = record.model || model
|
|
129
|
+
const contextTokens = (record.input_tokens || 0) + (record.cache_read_tokens || 0)
|
|
130
|
+
tokens += contextTokens + (record.output_tokens || 0)
|
|
131
|
+
transcript.reasoning(record.thinking, time)
|
|
132
|
+
transcript.assistant(content, time, { cwd, ...(contextTokens && { contextTokens }) })
|
|
133
|
+
for (const [i, call] of (record.tool_calls || []).entries()) {
|
|
134
|
+
const id = step + '/' + i
|
|
135
|
+
const args = call.args || {}
|
|
136
|
+
const name = call.name || 'tool'
|
|
137
|
+
const base = name.replace(/^mcp_ide-tools_/, '')
|
|
138
|
+
const details = describeTool(base, {
|
|
139
|
+
...args,
|
|
140
|
+
...(args.CommandLine && { command: args.CommandLine }),
|
|
141
|
+
...(args.Path && { path: args.Path }),
|
|
142
|
+
})
|
|
143
|
+
const item = transcript.tool(id, { ...details, name }, time)
|
|
144
|
+
if (contextTokens) item.contextTokens = contextTokens
|
|
145
|
+
const files = reviewedFiles(base, args, cwd)
|
|
146
|
+
if (files.length) item.deliverables = files
|
|
147
|
+
pending.push(id)
|
|
148
|
+
}
|
|
149
|
+
} else if (type === 'GENERIC') {
|
|
150
|
+
// Each batch's result steps follow its tool calls in trajectory order.
|
|
151
|
+
const id = pending.shift()
|
|
152
|
+
const output = content.replace(/^(?:(?:Created At|Completed At):[^\n]*(?:\n|$))+/u, '').trim()
|
|
153
|
+
const done = content.match(/^Completed At:\s*([^\r\n]+)/m)?.[1] || time
|
|
154
|
+
if (id !== undefined) transcript.result(id, [output, record.error].filter(Boolean).join('\n'), done,
|
|
155
|
+
images ? await loadMedia(record.media, logDir, roots) : [], cwd)
|
|
156
|
+
} else if (type === 'ERROR_MESSAGE') {
|
|
157
|
+
transcript.assistant(record.error || content, time)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return transcript.finish({ tool, model, tokens: tokens || undefined,
|
|
161
|
+
title: native?.title || (native && antigravityTitle(dirname(native.root), native.id)) })
|
|
162
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { extname, join, resolve, sep } from 'node:path'
|
|
4
|
+
import sharp from 'sharp'
|
|
5
|
+
|
|
6
|
+
function assertZipArchive(bytes) {
|
|
7
|
+
const isZip = bytes.length >= 4 && bytes[0] === 0x50 && bytes[1] === 0x4b
|
|
8
|
+
&& ((bytes[2] === 0x03 && bytes[3] === 0x04) || (bytes[2] === 0x05 && bytes[3] === 0x06))
|
|
9
|
+
if (!isZip) throw new Error('Invalid XLSX archive')
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function sheetRangeFromA1(sheet) {
|
|
13
|
+
const ref = sheet['!ref']
|
|
14
|
+
if (!ref) return undefined
|
|
15
|
+
const end = ref.includes(':') ? ref.split(':')[1] : ref
|
|
16
|
+
return `A1:${end}`
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function cellText(value) {
|
|
20
|
+
if (value instanceof Date) return value.toISOString()
|
|
21
|
+
return value == null ? '' : String(value)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function parseWorkbook(bytes, options = {}) {
|
|
25
|
+
assertZipArchive(bytes)
|
|
26
|
+
const { default: xlsx } = await import('node-xlsx')
|
|
27
|
+
return xlsx.parse(bytes, {
|
|
28
|
+
raw: true,
|
|
29
|
+
cellDates: true,
|
|
30
|
+
UTC: true,
|
|
31
|
+
defval: '',
|
|
32
|
+
blankrows: true,
|
|
33
|
+
...options,
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function readReplayAsset(directory, href) {
|
|
38
|
+
if (!href || /^(?:[a-z][\w+.-]*:|[/\\])/i.test(href)) throw new Error('Expected a replay-relative file')
|
|
39
|
+
const path = realpathSync(resolve(directory, href))
|
|
40
|
+
if (!path.startsWith(realpathSync(directory) + sep)) throw new Error('File is outside the replay')
|
|
41
|
+
return readFileSync(path)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function revisionValue(bytes, ext, revision) {
|
|
45
|
+
if (ext === '.xlsx') {
|
|
46
|
+
const address = /^([A-Z]+)([1-9]\d*)$/i.exec(revision.cell)
|
|
47
|
+
if (!address || !revision.sheet) throw new Error('Expected a sheet name and A1 cell address')
|
|
48
|
+
const cell = revision.cell.toUpperCase()
|
|
49
|
+
const [sheet] = await parseWorkbook(bytes, { sheets: [revision.sheet], range: `${cell}:${cell}` })
|
|
50
|
+
if (!sheet) throw new Error(`Worksheet not found: ${revision.sheet}`)
|
|
51
|
+
return cellText(sheet.data[0]?.[0])
|
|
52
|
+
}
|
|
53
|
+
const { PDFiumLibrary } = await import('@hyzyla/pdfium')
|
|
54
|
+
const library = await PDFiumLibrary.init()
|
|
55
|
+
let document
|
|
56
|
+
try {
|
|
57
|
+
document = await library.loadDocument(bytes)
|
|
58
|
+
if (!Number.isInteger(revision.page) || revision.page < 1 || revision.page > document.getPageCount()) {
|
|
59
|
+
throw new Error('PDF page is out of range')
|
|
60
|
+
}
|
|
61
|
+
const lines = document.getPage(revision.page - 1).getText().split(/\r\n|[\r\n]/).map(line => line.trim())
|
|
62
|
+
const matches = lines.filter(line => revision.linePrefix && line.startsWith(revision.linePrefix))
|
|
63
|
+
if (matches.length !== 1) throw new Error(`Expected one matching PDF line on page ${revision.page}, found ${matches.length}`)
|
|
64
|
+
return matches[0]
|
|
65
|
+
} finally {
|
|
66
|
+
document?.destroy()
|
|
67
|
+
library.destroy()
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function previewPdf(bytes, staging, url) {
|
|
72
|
+
const { PDFiumLibrary } = await import('@hyzyla/pdfium')
|
|
73
|
+
const library = await PDFiumLibrary.init()
|
|
74
|
+
let document
|
|
75
|
+
try {
|
|
76
|
+
document = await library.loadDocument(bytes)
|
|
77
|
+
const pages = []
|
|
78
|
+
for (const page of document.pages()) {
|
|
79
|
+
const { originalWidth, originalHeight } = page.getOriginalSize()
|
|
80
|
+
const image = await page.render({ scale: 1800 / Math.max(originalWidth, originalHeight), render: 'bitmap' })
|
|
81
|
+
const name = `page-${pages.length + 1}.webp`
|
|
82
|
+
await sharp(image.data, { raw: { width: image.width, height: image.height, channels: 4 } })
|
|
83
|
+
.webp({ quality: 85 }).toFile(join(staging, name))
|
|
84
|
+
pages.push({ src: url + name, width: image.width, height: image.height })
|
|
85
|
+
}
|
|
86
|
+
if (!pages.length) throw new Error('Empty PDF')
|
|
87
|
+
return { type: 'pdf', pages }
|
|
88
|
+
} finally {
|
|
89
|
+
document?.destroy()
|
|
90
|
+
library.destroy()
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function previewWorkbook(bytes, staging, url, file) {
|
|
95
|
+
const parsed = await parseWorkbook(bytes, { range: sheetRangeFromA1 })
|
|
96
|
+
const sheets = parsed.map(({ name, data }) => ({
|
|
97
|
+
sheet: name,
|
|
98
|
+
data: data.map(row => row.map(cellText)),
|
|
99
|
+
}))
|
|
100
|
+
const selected = sheets.find(sheet => sheet.sheet === file.previewSheet) || sheets[0]
|
|
101
|
+
if (!selected) throw new Error('Empty workbook')
|
|
102
|
+
const header = selected.data[0] || []
|
|
103
|
+
const indexes = file.previewColumns?.length
|
|
104
|
+
? file.previewColumns.map(name => header.indexOf(name)).filter(index => index >= 0)
|
|
105
|
+
: []
|
|
106
|
+
if (!indexes.length) indexes.push(...header.slice(0, 3).map((_, i) => i))
|
|
107
|
+
const rows = selected.data.slice(0, 4).map(row => indexes.map(i => String(row[i] ?? '')))
|
|
108
|
+
writeFileSync(join(staging, 'sheets.json'), JSON.stringify(sheets))
|
|
109
|
+
return { type: 'xlsx', src: url + 'sheets.json', sheet: selected.sheet, count: sheets.length, rows }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Preview only files packaged inside this replay. External links keep their existing behavior.
|
|
113
|
+
export async function prepareAttachmentPreviews(session, directory) {
|
|
114
|
+
let changed = false
|
|
115
|
+
const files = [...(session.deliverables || session.files || []), ...(session.items || []).flatMap(item => item.deliverables || [])]
|
|
116
|
+
for (const file of files) {
|
|
117
|
+
if (file.availability === 'missing') continue
|
|
118
|
+
const href = file.href || ''
|
|
119
|
+
const ext = extname(href).toLowerCase()
|
|
120
|
+
if (!['.pdf', '.xlsx'].includes(ext) || /^(?:[a-z][\w+.-]*:|[/\\])/i.test(href)) continue
|
|
121
|
+
let preview
|
|
122
|
+
try {
|
|
123
|
+
const bytes = readReplayAsset(directory, href)
|
|
124
|
+
const key = createHash('sha256').update(bytes)
|
|
125
|
+
.update(JSON.stringify([1, ext, file.previewSheet, file.previewColumns])).digest('hex').slice(0, 24)
|
|
126
|
+
const url = `encore-previews/${key}/`
|
|
127
|
+
const target = join(directory, url)
|
|
128
|
+
const manifest = join(target, 'preview.json')
|
|
129
|
+
if (!existsSync(manifest)) {
|
|
130
|
+
const root = join(directory, 'encore-previews')
|
|
131
|
+
mkdirSync(root, { recursive: true })
|
|
132
|
+
const staging = mkdtempSync(join(root, 'building-'))
|
|
133
|
+
try {
|
|
134
|
+
preview = ext === '.pdf' ? await previewPdf(bytes, staging, url) : await previewWorkbook(bytes, staging, url, file)
|
|
135
|
+
writeFileSync(join(staging, 'preview.json'), JSON.stringify(preview))
|
|
136
|
+
try {
|
|
137
|
+
renameSync(staging, target)
|
|
138
|
+
} catch (err) {
|
|
139
|
+
if (!existsSync(manifest)) throw err
|
|
140
|
+
}
|
|
141
|
+
} finally {
|
|
142
|
+
rmSync(staging, { recursive: true, force: true })
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
preview = JSON.parse(readFileSync(manifest, 'utf8'))
|
|
146
|
+
if (file.revision) {
|
|
147
|
+
try {
|
|
148
|
+
const previous = readReplayAsset(directory, file.revision.href)
|
|
149
|
+
const before = await revisionValue(previous, ext, file.revision)
|
|
150
|
+
const after = await revisionValue(bytes, ext, file.revision)
|
|
151
|
+
if (before !== after) preview.change = { before, after }
|
|
152
|
+
} catch (err) {
|
|
153
|
+
// A missing earlier version does not prevent reading the current file.
|
|
154
|
+
console.warn(`Could not compare ${href}: ${err.message}`)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
} catch (err) {
|
|
158
|
+
// An unreadable attachment can still be downloaded. Keep the rest of the replay usable.
|
|
159
|
+
console.warn(`Could not preview ${href}: ${err.message}`)
|
|
160
|
+
preview = undefined
|
|
161
|
+
}
|
|
162
|
+
if (JSON.stringify(file.preview) !== JSON.stringify(preview)) {
|
|
163
|
+
if (preview) file.preview = preview
|
|
164
|
+
else delete file.preview
|
|
165
|
+
changed = true
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return changed
|
|
169
|
+
}
|