oc-transcript-save 0.0.1

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 ADDED
@@ -0,0 +1,94 @@
1
+ # oc-transcript-save
2
+
3
+ An [OpenCode](https://github.com/mdrv/opencode) plugin that automatically saves full session transcripts to markdown files.
4
+
5
+ ## Features
6
+
7
+ - **Automatic saving**: Exports transcripts when sessions become idle
8
+ - **Rich markdown output**: Messages, tool calls, reasoning, files, and todos formatted as readable markdown
9
+ - **YAML frontmatter**: Session metadata (ID, title, timestamps) embedded in document header
10
+ - **Smart caching**: Prefetches data during sessions for faster saves
11
+ - **Change detection**: Skips redundant writes when content hasn't changed
12
+ - **Atomic writes**: Uses temp files to prevent corrupted output
13
+ - **Configurable output**: Customizable save directory via environment variable
14
+ - **Debug logging**: Optional verbose logging for troubleshooting
15
+
16
+ ## Installation
17
+
18
+ 1. Install dependencies:
19
+
20
+ ```bash
21
+ bun install
22
+ ```
23
+
24
+ 2. The plugin exports `TranscriptSavePlugin` which can be registered with your OpenCode instance.
25
+
26
+ ## Configuration
27
+
28
+ ### Environment Variables
29
+
30
+ | Variable | Description | Default |
31
+ | -------------------------------- | ---------------------------------------- | -------------------------------------- |
32
+ | `OC_TRANSCRIPT_SAVE_PATH` | Directory where markdown files are saved | `os.tmpdir()/oc-transcript-save` |
33
+ | `OC_TRANSCRIPT_SAVE_DEBUG` | Enable debug logging (`1` or `true`) | `false` |
34
+
35
+ ### Output File Format
36
+
37
+ Files are named: `{timestamp}-{session-id}.md`
38
+
39
+ Example: `2026-03-11-09-30-45-abc123.md`
40
+
41
+ ### Output Structure
42
+
43
+ Each markdown file contains:
44
+
45
+ ```yaml
46
+ ---
47
+ session_id: abc123
48
+ title: "Session Title"
49
+ created_at: "2026-03-11T09:30:45.000Z"
50
+ updated_at: "2026-03-11T09:45:30.000Z"
51
+ ---
52
+
53
+ ### User
54
+
55
+ Your message content...
56
+
57
+ ---
58
+
59
+ ### Agent
60
+
61
+ Response with reasoning, tool calls, etc.
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ The plugin automatically hooks into OpenCode events:
67
+
68
+ - **session.status**: Triggers when session becomes idle
69
+ - **session.idle**: Explicit idle state trigger
70
+ - Prefetches during busy/retry states for performance
71
+
72
+ No manual invocation needed—it runs automatically as you work.
73
+
74
+ ## Development
75
+
76
+ Run type checking:
77
+
78
+ ```bash
79
+ bun run check
80
+ ```
81
+
82
+ Format code:
83
+
84
+ ```bash
85
+ bun run fmt
86
+ ```
87
+
88
+ ## License
89
+
90
+ MIT
91
+
92
+ ## Repository
93
+
94
+ https://github.com/mdrv/oc-transcript-save
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "oc-transcript-save",
3
+ "description": "OpenCode plugin that autosaves full transcript in specified directory",
4
+ "version": "0.0.1",
5
+ "type": "module",
6
+ "module": "./transcript-save.ts",
7
+ "types": "./transcript-save.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./transcript-save.ts",
11
+ "import": "./transcript-save.ts"
12
+ }
13
+ },
14
+ "author": "Umar Alfarouk",
15
+ "scripts": {
16
+ "prepublishOnly": "bun run check",
17
+ "check": "bun tsc --noEmit",
18
+ "fmt": "dprint fmt"
19
+ },
20
+ "files": [
21
+ "transcript-save.ts",
22
+ "tsconfig.json",
23
+ "README.md"
24
+ ],
25
+ "keywords": [
26
+ "opencode",
27
+ "plugin",
28
+ "transcript"
29
+ ],
30
+ "license": "MIT",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/mdrv/oc-transcript-save.git"
34
+ },
35
+ "homepage": "https://github.com/mdrv/oc-transcript-save",
36
+ "dependencies": {
37
+ "@opencode-ai/plugin": "1.1.23"
38
+ },
39
+ "devDependencies": {
40
+ "@types/bun": "latest"
41
+ },
42
+ "peerDependencies": {
43
+ "typescript": "^5"
44
+ }
45
+ }
@@ -0,0 +1,924 @@
1
+ import type { Plugin } from '@opencode-ai/plugin'
2
+ import { mkdir, rename, unlink, writeFile } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import path from 'node:path'
5
+
6
+ type Context = Parameters<Plugin>[0]
7
+ type Event = Parameters<Exclude<Awaited<ReturnType<Plugin>>['event'], undefined>>[0]['event']
8
+ type Session = Context['client']['session']
9
+
10
+ const SERVICE_NAME = 'oc-transcript-save'
11
+ type UnknownRecord = Record<string, unknown>
12
+
13
+ type SessionState = {
14
+ queue: Promise<void>
15
+ scheduled?: boolean
16
+ pendingTrigger?: string
17
+ lastWriteAt?: number
18
+ lastFingerprint?: string
19
+ cachedSnapshot?: SessionSnapshot
20
+ prefetching?: Promise<void>
21
+ lastPrefetchAt?: number
22
+ }
23
+
24
+ type SessionSnapshot = {
25
+ session: UnknownRecord
26
+ messages: unknown[]
27
+ todos: unknown
28
+ diff: unknown
29
+ }
30
+
31
+ function normaliseNewlines(value: string): string {
32
+ return value.replace(/\r\n?/g, '\n')
33
+ }
34
+
35
+ function asString(value: unknown, fallback = ''): string {
36
+ if (typeof value === 'string') return value
37
+ if (value === null || value === undefined) return fallback
38
+ return String(value)
39
+ }
40
+
41
+ function asObject(value: unknown): UnknownRecord {
42
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {}
43
+ return value as UnknownRecord
44
+ }
45
+
46
+ function asArray(value: unknown): unknown[] {
47
+ return Array.isArray(value) ? value : []
48
+ }
49
+
50
+ function bindMethod<T extends (...args: any[]) => any>(target: unknown, key: string): T | null {
51
+ if (!target || (typeof target !== 'object' && typeof target !== 'function')) return null
52
+ const candidate = (target as Record<string, unknown>)[key]
53
+ if (typeof candidate !== 'function') return null
54
+ return candidate.bind(target) as T
55
+ }
56
+
57
+ function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | null> {
58
+ return Promise.race([
59
+ promise.catch(() => null as T | null),
60
+ new Promise<null>((resolve) => setTimeout(() => resolve(null), timeoutMs)),
61
+ ])
62
+ }
63
+
64
+ function parseDate(value: unknown): Date | null {
65
+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value
66
+
67
+ if (typeof value === 'number' && Number.isFinite(value)) {
68
+ const asMillis = value < 1_000_000_000_000 ? value * 1000 : value
69
+ const parsed = new Date(asMillis)
70
+ return Number.isNaN(parsed.getTime()) ? null : parsed
71
+ }
72
+
73
+ if (typeof value === 'string' && value.trim() !== '') {
74
+ const parsed = new Date(value)
75
+ return Number.isNaN(parsed.getTime()) ? null : parsed
76
+ }
77
+
78
+ return null
79
+ }
80
+
81
+ function toISO(value: unknown): string | null {
82
+ const parsed = parseDate(value)
83
+ return parsed ? parsed.toISOString() : null
84
+ }
85
+
86
+ function formatFilenameTimestamp(value: unknown): string {
87
+ const parsed = parseDate(value) ?? new Date()
88
+ const year = parsed.getFullYear().toString().padStart(4, '0')
89
+ const month = (parsed.getMonth() + 1).toString().padStart(2, '0')
90
+ const day = parsed.getDate().toString().padStart(2, '0')
91
+ const hour = parsed.getHours().toString().padStart(2, '0')
92
+ const minute = parsed.getMinutes().toString().padStart(2, '0')
93
+ const second = parsed.getSeconds().toString().padStart(2, '0')
94
+ return `${year}-${month}-${day}-${hour}-${minute}-${second}`
95
+ }
96
+
97
+ function sanitiseFilename(value: string): string {
98
+ const safe = value.replace(/[^a-zA-Z0-9._-]/g, '_')
99
+ return safe || 'unknown-session'
100
+ }
101
+
102
+ function quoteYamlString(value: string): string {
103
+ const escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
104
+ return `"${escaped}"`
105
+ }
106
+
107
+ function writeYamlPair(lines: string[], key: string, value: unknown, indent: number): void {
108
+ const pad = ' '.repeat(indent)
109
+
110
+ if (value === null || value === undefined) {
111
+ lines.push(`${pad}${key}: null`)
112
+ return
113
+ }
114
+
115
+ if (typeof value === 'string') {
116
+ if (value.includes('\n')) {
117
+ lines.push(`${pad}${key}: |-`)
118
+ for (const segment of value.split('\n')) {
119
+ lines.push(`${pad} ${segment}`)
120
+ }
121
+ } else {
122
+ lines.push(`${pad}${key}: ${quoteYamlString(value)}`)
123
+ }
124
+ return
125
+ }
126
+
127
+ if (typeof value === 'number' || typeof value === 'boolean') {
128
+ lines.push(`${pad}${key}: ${String(value)}`)
129
+ return
130
+ }
131
+
132
+ if (Array.isArray(value)) {
133
+ if (value.length === 0) {
134
+ lines.push(`${pad}${key}: []`)
135
+ return
136
+ }
137
+
138
+ lines.push(`${pad}${key}:`)
139
+ for (const item of value) {
140
+ writeYamlArrayItem(lines, item, indent + 2)
141
+ }
142
+ return
143
+ }
144
+
145
+ const objectValue = asObject(value)
146
+ const entries = Object.entries(objectValue)
147
+ if (entries.length === 0) {
148
+ lines.push(`${pad}${key}: {}`)
149
+ return
150
+ }
151
+
152
+ lines.push(`${pad}${key}:`)
153
+ for (const [childKey, childValue] of entries) {
154
+ writeYamlPair(lines, childKey, childValue, indent + 2)
155
+ }
156
+ }
157
+
158
+ function writeYamlArrayItem(lines: string[], value: unknown, indent: number): void {
159
+ const pad = ' '.repeat(indent)
160
+
161
+ if (value === null || value === undefined) {
162
+ lines.push(`${pad}- null`)
163
+ return
164
+ }
165
+
166
+ if (typeof value === 'string') {
167
+ if (value.includes('\n')) {
168
+ lines.push(`${pad}- |-`)
169
+ for (const segment of value.split('\n')) {
170
+ lines.push(`${pad} ${segment}`)
171
+ }
172
+ } else {
173
+ lines.push(`${pad}- ${quoteYamlString(value)}`)
174
+ }
175
+ return
176
+ }
177
+
178
+ if (typeof value === 'number' || typeof value === 'boolean') {
179
+ lines.push(`${pad}- ${String(value)}`)
180
+ return
181
+ }
182
+
183
+ if (Array.isArray(value)) {
184
+ if (value.length === 0) {
185
+ lines.push(`${pad}- []`)
186
+ return
187
+ }
188
+
189
+ lines.push(`${pad}-`)
190
+ for (const item of value) {
191
+ writeYamlArrayItem(lines, item, indent + 2)
192
+ }
193
+ return
194
+ }
195
+
196
+ const objectValue = asObject(value)
197
+ const entries = Object.entries(objectValue)
198
+ if (entries.length === 0) {
199
+ lines.push(`${pad}- {}`)
200
+ return
201
+ }
202
+
203
+ let first = true
204
+ for (const [key, child] of entries) {
205
+ if (first) {
206
+ if (
207
+ child === null
208
+ || child === undefined
209
+ || typeof child === 'string'
210
+ || typeof child === 'number'
211
+ || typeof child === 'boolean'
212
+ ) {
213
+ if (typeof child === 'string' && child.includes('\n')) {
214
+ lines.push(`${pad}- ${key}: |-`)
215
+ for (const segment of child.split('\n')) {
216
+ lines.push(`${pad} ${segment}`)
217
+ }
218
+ } else if (child === null || child === undefined) {
219
+ lines.push(`${pad}- ${key}: null`)
220
+ } else if (typeof child === 'string') {
221
+ lines.push(`${pad}- ${key}: ${quoteYamlString(child)}`)
222
+ } else {
223
+ lines.push(`${pad}- ${key}: ${String(child)}`)
224
+ }
225
+ } else {
226
+ lines.push(`${pad}- ${key}:`)
227
+ if (Array.isArray(child)) {
228
+ if (child.length === 0) {
229
+ lines.push(`${pad} []`)
230
+ } else {
231
+ for (const nested of child) {
232
+ writeYamlArrayItem(lines, nested, indent + 4)
233
+ }
234
+ }
235
+ } else {
236
+ const nestedEntries = Object.entries(asObject(child))
237
+ if (nestedEntries.length === 0) {
238
+ lines.push(`${pad} {}`)
239
+ } else {
240
+ for (const [nestedKey, nestedValue] of nestedEntries) {
241
+ writeYamlPair(lines, nestedKey, nestedValue, indent + 4)
242
+ }
243
+ }
244
+ }
245
+ }
246
+ first = false
247
+ continue
248
+ }
249
+
250
+ writeYamlPair(lines, key, child, indent + 2)
251
+ }
252
+ }
253
+
254
+ function toYaml(value: UnknownRecord): string {
255
+ const lines: string[] = []
256
+ for (const [key, child] of Object.entries(value)) {
257
+ writeYamlPair(lines, key, child, 0)
258
+ }
259
+ return lines.join('\n')
260
+ }
261
+
262
+ function sortForStableJson(value: unknown): unknown {
263
+ if (Array.isArray(value)) return value.map(sortForStableJson)
264
+ if (!value || typeof value !== 'object') return value
265
+
266
+ const sorted: UnknownRecord = {}
267
+ const entries = Object.entries(value as UnknownRecord).sort(([a], [b]) => a.localeCompare(b))
268
+ for (const [key, child] of entries) {
269
+ sorted[key] = sortForStableJson(child)
270
+ }
271
+ return sorted
272
+ }
273
+
274
+ function stableJson(value: unknown): string {
275
+ return JSON.stringify(sortForStableJson(value), null, 2)
276
+ }
277
+
278
+ function snapshotFingerprint(snapshot: SessionSnapshot): string {
279
+ return stableJson({
280
+ session: snapshot.session,
281
+ messages: snapshot.messages,
282
+ todos: snapshot.todos,
283
+ diff: snapshot.diff,
284
+ })
285
+ }
286
+
287
+ function chooseTrigger(existing: string | undefined, incoming: string): string {
288
+ if (!existing) return incoming
289
+ if (existing === 'session.status:idle') return existing
290
+ if (incoming === 'session.status:idle') return incoming
291
+ return incoming
292
+ }
293
+
294
+ function codeFence(content: string): string {
295
+ let longest = 2
296
+ for (const match of content.matchAll(/`+/g)) {
297
+ const runLength = match[0]?.length ?? 0
298
+ if (runLength > longest) longest = runLength
299
+ }
300
+ return '`'.repeat(longest + 1)
301
+ }
302
+
303
+ function renderCodeBlock(content: string, language = ''): string {
304
+ const clean = normaliseNewlines(content)
305
+ const fence = codeFence(clean)
306
+ const suffix = language ? language : ''
307
+ return `${fence}${suffix}\n${clean}\n${fence}`
308
+ }
309
+
310
+ function resolveSessionIdFromEvent(event: Event): string | null {
311
+ const props = asObject(event.properties)
312
+ const session = asObject(props.session)
313
+
314
+ const candidate = props.sessionID
315
+ ?? props.sessionId
316
+ ?? props.id
317
+ ?? props.session_id
318
+ ?? session.id
319
+ ?? session.sessionID
320
+ ?? session.sessionId
321
+
322
+ if (typeof candidate !== 'string' || candidate.trim() === '') return null
323
+ return candidate
324
+ }
325
+
326
+ function getMessageRole(message: unknown): string {
327
+ const msg = asObject(message)
328
+ const info = asObject(msg.info)
329
+ const role = msg.role ?? info.role ?? info.type
330
+ return asString(role, 'unknown')
331
+ }
332
+
333
+ function buildFrontmatter(session: UnknownRecord): UnknownRecord {
334
+ const time = asObject(session.time)
335
+
336
+ return {
337
+ session_id: session.id ?? null,
338
+ title: session.title ?? null,
339
+ created_at: toISO(time.created ?? session.createdAt ?? session.created_at),
340
+ updated_at: toISO(time.updated ?? session.updatedAt ?? session.updated_at),
341
+ }
342
+ }
343
+
344
+ function truncateText(value: string, maxChars = 5000): string {
345
+ const normalised = normaliseNewlines(value)
346
+ if (normalised.length <= maxChars) return normalised
347
+
348
+ const omitted = normalised.length - maxChars
349
+ return `${normalised.slice(0, maxChars)}\n\n... [truncated ${omitted} chars]`
350
+ }
351
+
352
+ function renderQuoteBlock(value: string, maxChars = 7000): string {
353
+ const text = truncateText(value, maxChars)
354
+ if (text.trim() === '') return '>'
355
+
356
+ return text
357
+ .split('\n')
358
+ .map((line) => (line === '' ? '>' : `> ${line}`))
359
+ .join('\n')
360
+ }
361
+
362
+ function renderPlainText(value: string, maxChars = 7000): string {
363
+ return truncateText(value, maxChars).trim()
364
+ }
365
+
366
+ function truncateInlineText(value: string, maxChars: number): string {
367
+ const flattened = normaliseNewlines(value).replace(/\s+/g, ' ').trim()
368
+ if (flattened.length <= maxChars) return flattened
369
+ if (maxChars <= 3) return '...'
370
+ return `${flattened.slice(0, maxChars - 3)}...`
371
+ }
372
+
373
+ function compactToolJsonValue(value: unknown, baseLimit: number, depth = 0): unknown {
374
+ if (value === null || value === undefined) return null
375
+
376
+ if (typeof value === 'string') {
377
+ const maxChars = Math.max(16, baseLimit - depth * 4)
378
+ return truncateInlineText(value, maxChars)
379
+ }
380
+
381
+ if (typeof value === 'number' || typeof value === 'boolean') return value
382
+
383
+ if (Array.isArray(value)) {
384
+ const limit = 16
385
+ const items = value.slice(0, limit).map((item) => compactToolJsonValue(item, baseLimit, depth + 1))
386
+ if (value.length > limit) {
387
+ items.push(`... (${value.length - limit} more items)`)
388
+ }
389
+ return items
390
+ }
391
+
392
+ if (typeof value === 'object') {
393
+ const entries = Object.entries(asObject(value))
394
+ const limit = 24
395
+ const result: UnknownRecord = {}
396
+
397
+ for (const [key, child] of entries.slice(0, limit)) {
398
+ result[key] = compactToolJsonValue(child, baseLimit, depth + 1)
399
+ }
400
+
401
+ if (entries.length > limit) {
402
+ result._truncated = `${entries.length - limit} additional keys`
403
+ }
404
+
405
+ return result
406
+ }
407
+
408
+ return asString(value)
409
+ }
410
+
411
+ function formatToolCallJson(value: UnknownRecord): string {
412
+ for (const limit of [56, 48, 40, 32, 24]) {
413
+ const compact = compactToolJsonValue(value, limit)
414
+ const rendered = JSON.stringify(compact, null, 2)
415
+ if (rendered.split('\n').every((line) => line.length <= 80)) {
416
+ return rendered
417
+ }
418
+ }
419
+
420
+ return JSON.stringify(compactToolJsonValue(value, 20), null, 2)
421
+ }
422
+
423
+ function renderCompactJson(value: unknown, maxChars = 3200): string {
424
+ const raw = typeof value === 'string' ? value : stableJson(value)
425
+ const language = typeof value === 'string' ? 'text' : 'json'
426
+ return renderCodeBlock(truncateText(raw, maxChars), language)
427
+ }
428
+
429
+ function hasContent(value: unknown): boolean {
430
+ if (value === null || value === undefined) return false
431
+ if (typeof value === 'string') return value.trim() !== ''
432
+ if (Array.isArray(value)) return value.length > 0
433
+ if (typeof value === 'object') return Object.keys(asObject(value)).length > 0
434
+ return true
435
+ }
436
+
437
+ function formatRole(role: string): string {
438
+ if (!role) return 'Unknown'
439
+ if (role.toLowerCase() === 'assistant') return 'Agent'
440
+ return `${role.charAt(0).toUpperCase()}${role.slice(1)}`
441
+ }
442
+
443
+ function renderPart(part: UnknownRecord): string {
444
+ const type = asString(part.type, 'unknown')
445
+ const section: string[] = []
446
+
447
+ if (type === 'text') {
448
+ const text = renderPlainText(asString(part.text ?? part.content, ''))
449
+ if (text) section.push(text)
450
+
451
+ const flags: string[] = []
452
+ if (part.synthetic === true) flags.push('synthetic')
453
+ if (part.ignored === true) flags.push('ignored')
454
+ if (flags.length > 0) {
455
+ section.push('')
456
+ section.push(`_(${flags.join(', ')})_`)
457
+ }
458
+ } else if (type === 'reasoning') {
459
+ const thinking = asString(part.text ?? part.reasoning ?? part.content, '')
460
+ if (thinking.trim() !== '') {
461
+ section.push(renderQuoteBlock(thinking, 12000))
462
+ }
463
+ } else if (type === 'tool') {
464
+ const state = asObject(part.state)
465
+ const toolInput = part.input ?? part.arguments ?? part.args ?? state.input ?? null
466
+ const toolResult = part.output ?? part.result ?? state.output
467
+ const toolError = part.error ?? state.error
468
+ const toolAttachments = part.attachments ?? state.attachments
469
+
470
+ const outputPayload: UnknownRecord = {}
471
+ if (hasContent(toolResult)) outputPayload.result = toolResult
472
+ if (hasContent(toolError)) outputPayload.error = toolError
473
+ if (hasContent(toolAttachments)) outputPayload.attachments = toolAttachments
474
+
475
+ const toolCall: UnknownRecord = {
476
+ tool: asString(part.tool ?? part.name ?? part.toolName, 'unknown'),
477
+ input: toolInput,
478
+ output: Object.keys(outputPayload).length > 0 ? outputPayload : null,
479
+ }
480
+
481
+ section.push(renderCodeBlock(formatToolCallJson(toolCall), 'json'))
482
+ } else if (type === 'file') {
483
+ section.push(
484
+ `File \`${asString(part.filename ?? part.name, 'unknown')}\` (${
485
+ asString(part.mime ?? part.mimeType, 'unknown')
486
+ })`,
487
+ )
488
+ if (part.url) section.push(`- URL: ${asString(part.url)}`)
489
+ if (part.source !== undefined) {
490
+ section.push('- Source:')
491
+ section.push(renderCompactJson(part.source, 1800))
492
+ }
493
+ } else if (type === 'subtask') {
494
+ section.push(`Subtask \`${asString(part.agent, 'unknown')}\` (${asString(part.model, 'unknown')})`)
495
+
496
+ const command = asString(part.command, '')
497
+ if (command) section.push(`- Command: \`${command}\``)
498
+
499
+ if (part.description !== undefined) {
500
+ section.push('')
501
+ section.push('Description:')
502
+ section.push(renderQuoteBlock(asString(part.description, ''), 6000))
503
+ }
504
+
505
+ if (part.prompt !== undefined) {
506
+ section.push('')
507
+ section.push('Prompt:')
508
+ section.push(renderQuoteBlock(asString(part.prompt, ''), 6000))
509
+ }
510
+ } else if (type === 'step-start' || type === 'step-finish') {
511
+ return ''
512
+ } else {
513
+ section.push(`${type}:`)
514
+ section.push('')
515
+ section.push('Details:')
516
+ section.push(renderCompactJson(part, 2200))
517
+ }
518
+
519
+ return section.join('\n')
520
+ }
521
+
522
+ function renderMessage(message: unknown, index: number): string {
523
+ const msg = asObject(message)
524
+ const parts = asArray(msg.parts)
525
+ const role = getMessageRole(msg)
526
+ void index
527
+
528
+ const section: string[] = []
529
+ section.push(`### ${formatRole(role)}`)
530
+ section.push('')
531
+
532
+ if (parts.length === 0) {
533
+ section.push('_No content._')
534
+ return section.join('\n')
535
+ }
536
+
537
+ let hasRenderedPart = false
538
+
539
+ for (let i = 0; i < parts.length; i += 1) {
540
+ const renderedPart = renderPart(asObject(parts[i]))
541
+ if (!renderedPart) continue
542
+
543
+ if (hasRenderedPart) section.push('')
544
+ section.push(renderedPart)
545
+ hasRenderedPart = true
546
+ }
547
+
548
+ if (!hasRenderedPart) {
549
+ section.push('_No content._')
550
+ }
551
+
552
+ return section.join('\n')
553
+ }
554
+
555
+ function renderMarkdown(snapshot: SessionSnapshot, trigger: string, ctx: UnknownRecord): string {
556
+ const session = snapshot.session
557
+ const messages = snapshot.messages
558
+
559
+ void trigger
560
+ void ctx
561
+
562
+ const frontmatter = buildFrontmatter(session)
563
+
564
+ const content: string[] = []
565
+ content.push('---')
566
+ content.push(toYaml(frontmatter))
567
+ content.push('---')
568
+
569
+ if (messages.length === 0) {
570
+ content.push('')
571
+ content.push('_No messages yet._')
572
+ } else {
573
+ for (let i = 0; i < messages.length; i += 1) {
574
+ if (i > 0) {
575
+ content.push('')
576
+ content.push('---')
577
+ }
578
+
579
+ content.push('')
580
+ content.push(renderMessage(messages[i], i))
581
+ }
582
+ }
583
+
584
+ return normaliseNewlines(content.join('\n'))
585
+ }
586
+
587
+ async function atomicWrite(filePath: string, content: string): Promise<number> {
588
+ const dirPath = path.dirname(filePath)
589
+ await mkdir(dirPath, { recursive: true })
590
+
591
+ const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
592
+ const normalised = normaliseNewlines(content)
593
+
594
+ await writeFile(tmpPath, normalised, 'utf8')
595
+
596
+ try {
597
+ await rename(tmpPath, filePath)
598
+ } catch (error) {
599
+ await unlink(tmpPath).catch(() => undefined)
600
+ throw error
601
+ }
602
+
603
+ return Buffer.byteLength(normalised, 'utf8')
604
+ }
605
+
606
+ async function fetchSessionSnapshot(ctx: Parameters<Plugin>[0], sessionID: string): Promise<SessionSnapshot> {
607
+ const sessionClient = ctx.client.session
608
+
609
+ const get = bindMethod<(arg: unknown) => Promise<{ data: unknown }>>(sessionClient, 'get')
610
+ const messages = bindMethod<(arg: unknown) => Promise<{ data: unknown }>>(sessionClient, 'messages')
611
+ const todo = bindMethod<(arg: unknown) => Promise<{ data: unknown }>>(sessionClient, 'todo')
612
+ const diff = bindMethod<(arg: unknown) => Promise<{ data: unknown }>>(sessionClient, 'diff')
613
+
614
+ if (typeof get !== 'function' || typeof messages !== 'function') {
615
+ throw new Error('Session API unavailable on plugin context')
616
+ }
617
+
618
+ const [sessionResult, messagesResult, todoResult, diffResult] = await Promise.all([
619
+ get({ path: { id: sessionID } }),
620
+ messages({ path: { id: sessionID } }),
621
+ typeof todo === 'function'
622
+ ? todo({ path: { id: sessionID } }).catch(() => ({ data: null }))
623
+ : Promise.resolve({ data: null }),
624
+ typeof diff === 'function'
625
+ ? diff({ path: { id: sessionID } }).catch(() => ({ data: null }))
626
+ : Promise.resolve({ data: null }),
627
+ ])
628
+
629
+ const session = asObject(sessionResult?.data)
630
+ if (!session.id) {
631
+ throw new Error(`Session not found for id '${sessionID}'`)
632
+ }
633
+
634
+ return {
635
+ session,
636
+ messages: asArray(messagesResult?.data),
637
+ todos: todoResult?.data ?? null,
638
+ diff: diffResult?.data ?? null,
639
+ }
640
+ }
641
+
642
+ function resolveOutputRoot(ctx: UnknownRecord, session: UnknownRecord): string {
643
+ const sessionWorktree = asString(session.worktree, '')
644
+ if (sessionWorktree && sessionWorktree !== '/') return sessionWorktree
645
+
646
+ const ctxWorktree = asString(ctx.worktree, '')
647
+ if (ctxWorktree && ctxWorktree !== '/') return ctxWorktree
648
+
649
+ const sessionDirectory = asString(session.directory, '')
650
+ if (sessionDirectory) return sessionDirectory
651
+
652
+ const ctxDirectory = asString(ctx.directory, '')
653
+ if (ctxDirectory) return ctxDirectory
654
+
655
+ return process.cwd()
656
+ }
657
+
658
+ function resolveOutputPath(snapshot: SessionSnapshot): string {
659
+ const session = snapshot.session
660
+ const time = asObject(session.time)
661
+ const created = time.created ?? session.createdAt ?? session.created_at
662
+ const timestamp = formatFilenameTimestamp(created)
663
+ const id = sanitiseFilename(asString(session.id, 'unknown-session'))
664
+
665
+ return path.join(
666
+ process.env.OC_TRANSCRIPT_SAVE_PATH || path.join(tmpdir(), 'oc-transcript-save'),
667
+ `${timestamp}-${id}.md`,
668
+ )
669
+ }
670
+
671
+ async function logEvent(
672
+ ctx: Parameters<Plugin>[0],
673
+ level: 'info' | 'error' | 'debug' | 'warn',
674
+ message: string,
675
+ extra: UnknownRecord = {},
676
+ ): Promise<void> {
677
+ const logger = ctx.client.app.log.bind(ctx)
678
+
679
+ if (typeof logger === 'function') {
680
+ await logger({
681
+ body: {
682
+ service: SERVICE_NAME,
683
+ level,
684
+ message,
685
+ extra,
686
+ },
687
+ }).catch(() => undefined)
688
+ return
689
+ }
690
+
691
+ if (
692
+ level === 'error' || process.env.OC_TRANSCRIPT_SAVE_DEBUG === '1'
693
+ || process.env.OC_TRANSCRIPT_SAVE_DEBUG === 'true'
694
+ ) {
695
+ const serialised = Object.keys(extra).length > 0 ? ` ${stableJson(extra)}` : ''
696
+ console.error(`[${SERVICE_NAME}] ${level} ${message}${serialised}`)
697
+ }
698
+ }
699
+
700
+ export const TranscriptSavePlugin: Plugin = async (ctx) => {
701
+ const state = new Map<string, SessionState>()
702
+ let firstBoot = true
703
+ const debug = process.env.OC_TRANSCRIPT_SAVE_DEBUG === '1'
704
+ || process.env.OC_TRANSCRIPT_SAVE_DEBUG === 'true'
705
+
706
+ if (debug) {
707
+ const sessionClient = asObject(ctx.client).session
708
+ console.error(
709
+ `[${SERVICE_NAME}] init hasGet=${String(Boolean(bindMethod(sessionClient, 'get')))} hasMessages=${
710
+ String(Boolean(bindMethod(sessionClient, 'messages')))
711
+ } hasTodo=${String(Boolean(bindMethod(sessionClient, 'todo')))} hasDiff=${
712
+ String(Boolean(bindMethod(sessionClient, 'diff')))
713
+ }`,
714
+ )
715
+ }
716
+
717
+ function sessionState(sessionID: string): SessionState {
718
+ const existing = state.get(sessionID)
719
+ if (existing) return existing
720
+
721
+ const created: SessionState = { queue: Promise.resolve() }
722
+ state.set(sessionID, created)
723
+ return created
724
+ }
725
+
726
+ function schedule(sessionID: string, trigger: string): void {
727
+ const entry = sessionState(sessionID)
728
+ entry.pendingTrigger = chooseTrigger(entry.pendingTrigger, trigger)
729
+ if (debug) {
730
+ console.error(
731
+ `[${SERVICE_NAME}] schedule session=${sessionID} trigger=${trigger} pending=${entry.pendingTrigger}`,
732
+ )
733
+ }
734
+
735
+ if (entry.scheduled) return
736
+ entry.scheduled = true
737
+
738
+ entry.queue = entry.queue
739
+ .then(async () => {
740
+ const enqueueTrigger = entry.pendingTrigger ?? trigger
741
+ entry.pendingTrigger = undefined
742
+
743
+ const hold = setInterval(() => undefined, 50)
744
+ const start = Date.now()
745
+ try {
746
+ if (debug) {
747
+ console.error(`[${SERVICE_NAME}] export begin session=${sessionID} trigger=${enqueueTrigger}`)
748
+ }
749
+ void logEvent(ctx, 'info', 'export.started', { sessionID, trigger: enqueueTrigger })
750
+
751
+ let snapshot = entry.cachedSnapshot
752
+ if (snapshot) {
753
+ const refreshed = await withTimeout(fetchSessionSnapshot(ctx, sessionID), 120)
754
+ if (refreshed) {
755
+ snapshot = refreshed
756
+ entry.cachedSnapshot = refreshed
757
+ } else if (debug) {
758
+ console.error(`[${SERVICE_NAME}] export refresh timed out, using cached snapshot session=${sessionID}`)
759
+ }
760
+ } else {
761
+ snapshot = await fetchSessionSnapshot(ctx, sessionID)
762
+ entry.cachedSnapshot = snapshot
763
+ }
764
+
765
+ if (!snapshot) {
766
+ throw new Error(`No snapshot available for session '${sessionID}'`)
767
+ }
768
+
769
+ const fingerprint = snapshotFingerprint(snapshot)
770
+ if (entry.lastFingerprint === fingerprint) {
771
+ if (debug) {
772
+ console.error(`[${SERVICE_NAME}] export skipped unchanged session=${sessionID}`)
773
+ }
774
+ void logEvent(ctx, 'info', 'export.skipped.unchanged', {
775
+ sessionID,
776
+ trigger: enqueueTrigger,
777
+ duration_ms: Date.now() - start,
778
+ })
779
+ return
780
+ }
781
+
782
+ // const outputRoot = resolveOutputRoot(ctx, snapshot.session)
783
+ const filePath = resolveOutputPath(snapshot)
784
+ const markdown = renderMarkdown(snapshot, enqueueTrigger, ctx)
785
+ const bytes = await atomicWrite(filePath, markdown)
786
+
787
+ entry.lastWriteAt = Date.now()
788
+ entry.lastFingerprint = fingerprint
789
+ if (debug) {
790
+ console.error(`[${SERVICE_NAME}] export wrote session=${sessionID} file=${filePath} bytes=${bytes}`)
791
+ }
792
+ void logEvent(ctx, 'info', 'export.completed', {
793
+ sessionID,
794
+ trigger: enqueueTrigger,
795
+ filePath,
796
+ bytes,
797
+ duration_ms: Date.now() - start,
798
+ last_write_at: entry.lastWriteAt,
799
+ })
800
+ } finally {
801
+ clearInterval(hold)
802
+ entry.scheduled = false
803
+ if (entry.pendingTrigger) {
804
+ schedule(sessionID, entry.pendingTrigger)
805
+ }
806
+ }
807
+ })
808
+ .catch(async (error) => {
809
+ entry.scheduled = false
810
+ const errorMessage = asString((error as Error)?.stack ?? (error as Error)?.message ?? error)
811
+ if (debug) {
812
+ console.error(`[${SERVICE_NAME}] export failed session=${sessionID} error=${errorMessage}`)
813
+ }
814
+ void logEvent(ctx, 'error', 'export.failed', {
815
+ sessionID,
816
+ trigger: entry.pendingTrigger ?? trigger,
817
+ error: errorMessage,
818
+ })
819
+
820
+ if (entry.pendingTrigger) {
821
+ schedule(sessionID, entry.pendingTrigger)
822
+ }
823
+ })
824
+ }
825
+
826
+ function prefetchSnapshot(sessionID: string, reason: string): void {
827
+ const entry = sessionState(sessionID)
828
+ const now = Date.now()
829
+
830
+ if (entry.prefetching) return
831
+ if (entry.lastPrefetchAt && now - entry.lastPrefetchAt < 300) return
832
+
833
+ entry.lastPrefetchAt = now
834
+ entry.prefetching = fetchSessionSnapshot(ctx, sessionID)
835
+ .then((snapshot) => {
836
+ entry.cachedSnapshot = snapshot
837
+ if (debug) {
838
+ console.error(`[${SERVICE_NAME}] prefetched session=${sessionID} reason=${reason}`)
839
+ }
840
+ })
841
+ .catch((error) => {
842
+ if (debug) {
843
+ console.error(
844
+ `[${SERVICE_NAME}] prefetch failed session=${sessionID} reason=${reason} error=${
845
+ asString((error as Error)?.message ?? error)
846
+ }`,
847
+ )
848
+ }
849
+ })
850
+ .finally(() => {
851
+ entry.prefetching = undefined
852
+ })
853
+ }
854
+
855
+ return {
856
+ event: async ({ event }) => {
857
+ try {
858
+ const type = asString(event.type)
859
+ const sessionID = resolveSessionIdFromEvent(event)
860
+ if (debug) {
861
+ console.error(`[${SERVICE_NAME}] event type=${type} sessionID=${sessionID ?? ''}`)
862
+ }
863
+ if (!sessionID) return
864
+
865
+ // check logged events
866
+ ctx.client.app.log({
867
+ body: {
868
+ service: SERVICE_NAME,
869
+ level: 'info',
870
+ message: sessionID,
871
+ extra: { event },
872
+ },
873
+ })
874
+
875
+ if (type === 'session.status') {
876
+ if (firstBoot) {
877
+ firstBoot = false
878
+ const snapshot = await fetchSessionSnapshot(ctx, sessionID)
879
+ ctx.client.tui.showToast({
880
+ body: {
881
+ title: SERVICE_NAME,
882
+ message: `Saved to:\n${resolveOutputPath(snapshot)}`,
883
+ variant: 'info',
884
+ duration: 3000,
885
+ },
886
+ })
887
+ }
888
+ const status = asObject(asObject(event.properties).status)
889
+ if (debug) {
890
+ console.error(`[${SERVICE_NAME}] session.status state=${asString(status.type, 'unknown')}`)
891
+ }
892
+ const statusType = asString(status.type)
893
+ if (statusType === 'busy' || statusType === 'retry') {
894
+ prefetchSnapshot(sessionID, `session.status:${statusType}`)
895
+ }
896
+ if (status.type === 'idle') {
897
+ schedule(sessionID, 'session.status:idle')
898
+ }
899
+ return
900
+ }
901
+
902
+ if (type === 'session.idle') {
903
+ schedule(sessionID, 'session.idle')
904
+ return
905
+ }
906
+
907
+ if (type === 'session.diff' || type === 'todo.updated') {
908
+ prefetchSnapshot(sessionID, type)
909
+ return
910
+ }
911
+
912
+ if (debug && (type === 'message.updated' || type === 'message.part.updated')) {
913
+ await logEvent(ctx, 'debug', 'event.observed', { type, sessionID })
914
+ }
915
+ } catch (error) {
916
+ await logEvent(ctx, 'error', 'event.handler.failed', {
917
+ error: asString((error as Error)?.stack ?? (error as Error)?.message ?? error),
918
+ })
919
+ }
920
+ },
921
+ }
922
+ }
923
+
924
+ export default TranscriptSavePlugin
package/tsconfig.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ "target": "ESNext",
6
+ "module": "Preserve",
7
+ "moduleDetection": "force",
8
+ "jsx": "react-jsx",
9
+ "allowJs": true,
10
+
11
+ // Bundler mode
12
+ "moduleResolution": "bundler",
13
+ "allowImportingTsExtensions": true,
14
+ "verbatimModuleSyntax": true,
15
+ "noEmit": true,
16
+
17
+ // Best practices
18
+ "strict": true,
19
+ "skipLibCheck": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+ "noUncheckedIndexedAccess": true,
22
+ "noImplicitOverride": true,
23
+
24
+ // Some stricter flags (disabled by default)
25
+ "noUnusedLocals": false,
26
+ "noUnusedParameters": false,
27
+ "noPropertyAccessFromIndexSignature": false
28
+ }
29
+ }