@unieai/rabi-session-log-export 0.2.1-rc.3 → 0.2.2-rc.5

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,367 @@
1
+ /**
2
+ * Pure backend converter for one complete committed Session log. The Session
3
+ * Markdown copy Host route uses it, and the package entry exports it for
4
+ * callers that already hold the logical events. The raw log is authoritative:
5
+ * compaction surface replacements never remove earlier messages, and
6
+ * fork-inherited history appears once. Reasoning, system and developer
7
+ * messages, injected non-human context, request headers, and runtime records
8
+ * are omitted.
9
+ * @module
10
+ */
11
+
12
+ import type {
13
+ AssistantMessage,
14
+ SessionEvent,
15
+ ToolResultMessage,
16
+ UserMessage,
17
+ } from '@unieai/rabi-session'
18
+ import type {} from '@unieai/rabi-session-title'
19
+ import type { FileAttachmentRef, ImageAttachmentRef } from '@unieai/rabi-attachment'
20
+
21
+ /** Heading used when the log carries no title and the Session has no name. */
22
+ const UNTITLED_SESSION_MARKDOWN_TITLE = 'Untitled Session'
23
+
24
+ interface AssistantEntry {
25
+ readonly kind: 'assistant'
26
+ readonly text: string
27
+ readonly toolCalls: boolean
28
+ }
29
+
30
+ interface ToolEntry {
31
+ readonly kind: 'tool'
32
+ readonly name: string
33
+ readonly arguments: string
34
+ result: ToolResult | undefined
35
+ }
36
+
37
+ interface ToolResult {
38
+ readonly text: string
39
+ readonly isError: boolean
40
+ readonly reason: string | undefined
41
+ }
42
+
43
+ interface UserSegment {
44
+ readonly kind: 'user'
45
+ readonly text: string
46
+ }
47
+
48
+ type TurnEntry = AssistantEntry | ToolEntry
49
+ type TurnSegment = UserSegment | TurnEntry
50
+
51
+ interface Turn {
52
+ readonly segments: TurnSegment[]
53
+ readonly calls: Map<string, ToolEntry>
54
+ }
55
+
56
+ /**
57
+ * Render one complete committed Session log as Markdown. This is a pure backend
58
+ * utility: it needs no mounted plugin, reads no storage, and does not mutate the
59
+ * supplied events. The latest `session/title` event supplies the heading; the
60
+ * rest of the transcript is derived only from the supplied logical events.
61
+ * @param events - complete committed logical event snapshot in seq order, including any inherited prefix.
62
+ * @param sourcePath - optional backend-resolved path to the selected Session artifact; emitted verbatim in a fenced text block.
63
+ * @returns Markdown ending in exactly one newline; an empty log returns the heading and optional source metadata only.
64
+ */
65
+ export function formatSessionMarkdown(events: readonly SessionEvent[], sourcePath?: string): string {
66
+ const title = events.findLast(event => event.type === 'session/title')?.data.title
67
+ const sections = [`# ${normalizedTitle(title)}`]
68
+ if (sourcePath !== undefined && sourcePath !== '') {
69
+ sections.push(`Session file:
70
+
71
+ ${fenced(sourcePath, 'text', false)}`)
72
+ }
73
+ for (const turn of collectTurns(events)) {
74
+ const finalIndex = finalReplyIndex(turn.segments)
75
+ const end = finalIndex < 0 ? turn.segments.length : finalIndex
76
+ let pending: TurnEntry[] = []
77
+ for (const segment of turn.segments.slice(0, end)) {
78
+ if (segment.kind === 'user') {
79
+ if (pending.length > 0) {
80
+ sections.push(collapsibleSection(pending))
81
+ pending = []
82
+ }
83
+ sections.push(quote(segment.text))
84
+ } else {
85
+ pending.push(segment)
86
+ }
87
+ }
88
+ if (pending.length > 0) sections.push(collapsibleSection(pending))
89
+ const final = turn.segments[finalIndex]
90
+ const finalText = final?.kind === 'assistant'
91
+ ? closeUnfinishedFence(trimBlankEdgeLines(final.text))
92
+ : ''
93
+ if (finalText !== '') sections.push(finalText)
94
+ }
95
+ return `${sections.join('\n\n').trimEnd()}\n`
96
+ }
97
+
98
+ function normalizedTitle(title: string | undefined): string {
99
+ const line = title?.replace(/\r\n?|\n/gu, ' ').trim() ?? ''
100
+ return line === '' ? UNTITLED_SESSION_MARKDOWN_TITLE : line
101
+ }
102
+
103
+ function collectTurns(events: readonly SessionEvent[]): Turn[] {
104
+ const turns: Turn[] = []
105
+ let current: Turn | undefined
106
+ const begin = (): Turn => {
107
+ current = { segments: [], calls: new Map() }
108
+ turns.push(current)
109
+ return current
110
+ }
111
+ const active = (): Turn => current ?? begin()
112
+ for (const event of events) {
113
+ switch (event.type) {
114
+ case 'turn/start':
115
+ begin()
116
+ break
117
+ case 'turn/end':
118
+ current = undefined
119
+ break
120
+ case 'user/message': {
121
+ if (event.surfaceOp !== 'append' || event.data.source.kind !== 'user') break
122
+ const text = visibleContent(event.data.content)
123
+ if (text !== '') active().segments.push({ kind: 'user', text })
124
+ break
125
+ }
126
+ case 'assistant/message': {
127
+ if (event.surfaceOp !== 'append') break
128
+ const message = event.data.message
129
+ const text = assistantText(message)
130
+ const toolCalls = message.content.some(block => block.type === 'tool-call')
131
+ if (trimBlankEdgeLines(text) !== '') active().segments.push({ kind: 'assistant', text, toolCalls })
132
+ break
133
+ }
134
+ case 'tool/call': {
135
+ const turn = active()
136
+ const entry: ToolEntry = {
137
+ kind: 'tool',
138
+ name: event.data.name,
139
+ arguments: event.data.arguments,
140
+ result: undefined,
141
+ }
142
+ turn.segments.push(entry)
143
+ turn.calls.set(String(event.data.callId), entry)
144
+ break
145
+ }
146
+ case 'tool/result': {
147
+ if (event.surfaceOp !== 'append') break
148
+ const turn = active()
149
+ const callId = String(event.data.message.toolCallId)
150
+ let entry = turn.calls.get(callId)
151
+ if (entry === undefined) {
152
+ entry = { kind: 'tool', name: 'unknown', arguments: '', result: undefined }
153
+ turn.segments.push(entry)
154
+ turn.calls.set(callId, entry)
155
+ }
156
+ entry.result = toolResult(event.data)
157
+ break
158
+ }
159
+ default:
160
+ break
161
+ }
162
+ }
163
+ return turns.filter(turn => turn.segments.length > 0)
164
+ }
165
+
166
+ function finalReplyIndex(segments: readonly TurnSegment[]): number {
167
+ const index = segments.length - 1
168
+ const entry = segments[index]
169
+ return entry?.kind === 'assistant' && !entry.toolCalls ? index : -1
170
+ }
171
+
172
+ function collapsibleSection(entries: readonly TurnEntry[]): string {
173
+ const summary = entries.length === 1 ? '1 previous message' : `${String(entries.length)} previous messages`
174
+ const body = entries.map(renderEntry).join('\n\n')
175
+ return `<details><summary>${summary}</summary>\n\n${body}\n\n</details>`
176
+ }
177
+
178
+ function renderEntry(entry: TurnEntry): string {
179
+ if (entry.kind === 'assistant') {
180
+ const text = escapeWrapperTagsOutsideFences(
181
+ closeUnfinishedFence(trimBlankEdgeLines(entry.text)),
182
+ )
183
+ return `**Assistant**\n\n${text}`
184
+ }
185
+ const heading = `**Tool: \`${escapeWrapperTags(entry.name)}\`**`
186
+ const argumentsText = entry.arguments === ''
187
+ ? '(no arguments)'
188
+ : fenced(jsonArguments(entry.arguments), 'json')
189
+ const result = entry.result
190
+ const resultHeading = result?.isError === true ? '**Result (error)**' : '**Result**'
191
+ let resultBody = ''
192
+ if (result === undefined) {
193
+ resultBody = '(no result recorded)'
194
+ } else if (result.reason !== undefined && result.reason !== '') {
195
+ resultBody = `Error: ${escapeWrapperTags(result.reason)}`
196
+ if (result.text !== '') resultBody += `\n\n${fenced(result.text)}`
197
+ } else if (result.text === '') {
198
+ resultBody = '(no output)'
199
+ } else {
200
+ resultBody = fenced(result.text)
201
+ }
202
+ return `${heading}\n\n${argumentsText}\n\n${resultHeading}\n\n${resultBody}`
203
+ }
204
+
205
+ function visibleContent(content: UserMessage['content']): string {
206
+ const parts: string[] = []
207
+ for (const block of content) {
208
+ switch (block.type) {
209
+ case 'text':
210
+ if (block.text !== '') parts.push(block.text)
211
+ break
212
+ case 'image':
213
+ parts.push(imageLabel(block.attachment))
214
+ break
215
+ case 'file':
216
+ parts.push(fileLabel(block.attachment))
217
+ break
218
+ default:
219
+ break
220
+ }
221
+ }
222
+ return parts.join('\n\n')
223
+ }
224
+
225
+ function assistantText(message: AssistantMessage): string {
226
+ return visibleContent(message.content)
227
+ }
228
+
229
+ function toolResult(data: {
230
+ readonly message: ToolResultMessage
231
+ readonly error?: { readonly name: string; readonly code: string; readonly reason?: string }
232
+ }): ToolResult {
233
+ return {
234
+ text: visibleContent(data.message.content),
235
+ isError: data.message.isError === true,
236
+ reason: data.error?.reason,
237
+ }
238
+ }
239
+
240
+ function quote(text: string): string {
241
+ const normalized = text.replace(/\r\n?/gu, '\n').replace(/\n+$/u, '')
242
+ return normalized.split('\n').map(line => line === '' ? '>' : `> ${line}`).join('\n')
243
+ }
244
+
245
+ function imageLabel(ref: ImageAttachmentRef): string {
246
+ return `[Image: ${labelName(ref.name)} (${String(ref.width)}×${String(ref.height)}, ${String(ref.bytes)} bytes)]`
247
+ }
248
+
249
+ function fileLabel(ref: FileAttachmentRef): string {
250
+ return `[File: ${labelName(ref.name)} (${String(ref.bytes)} bytes)]`
251
+ }
252
+
253
+ function labelName(name: string | undefined): string {
254
+ const normalized = name?.replace(/\s+/gu, ' ').replace(/\]/gu, '\\]').trim() ?? ''
255
+ return normalized === '' ? 'attachment' : normalized
256
+ }
257
+
258
+ function jsonArguments(argumentsText: string): string {
259
+ let parsed: unknown
260
+ try {
261
+ parsed = JSON.parse(argumentsText)
262
+ } catch {
263
+ return argumentsText
264
+ }
265
+ return JSON.stringify(parsed, null, 2)
266
+ }
267
+
268
+ function fenced(text: string, language = '', trimTrailing = true): string {
269
+ const content = trimTrailing ? text.replace(/\n+$/u, '') : text
270
+ let longest = 0
271
+ for (const match of content.matchAll(/`+/gu)) longest = Math.max(longest, match[0].length)
272
+ const fence = '`'.repeat(Math.max(3, longest + 1))
273
+ return `${fence}${language}\n${content}\n${fence}`
274
+ }
275
+
276
+ interface Fence {
277
+ readonly character: string
278
+ readonly length: number
279
+ }
280
+
281
+ interface ScannedLine {
282
+ readonly text: string
283
+ readonly code: boolean
284
+ }
285
+
286
+ interface MarkdownScan {
287
+ readonly lines: readonly ScannedLine[]
288
+ readonly openFence: Fence | undefined
289
+ }
290
+
291
+ // Remove only blank edge lines, preserving the first and last content line's
292
+ // indentation and interior blank lines.
293
+ function trimBlankEdgeLines(text: string): string {
294
+ const lines = text.replace(/\r\n?/gu, '\n').split('\n')
295
+ let start = 0
296
+ let end = lines.length
297
+ while (start < end && lines[start]?.trim() === '') start += 1
298
+ while (end > start && lines[end - 1]?.trim() === '') end -= 1
299
+ return lines.slice(start, end).join('\n')
300
+ }
301
+
302
+ // Scan fenced and indented code once so wrapper escaping and unfinished-fence
303
+ // closure agree on what is code. This is a narrow Markdown block heuristic, not
304
+ // a parser.
305
+ function scanMarkdown(markdown: string): MarkdownScan {
306
+ const lines = markdown.replace(/\r\n?/gu, '\n').split('\n')
307
+ const scanned: ScannedLine[] = []
308
+ let fence: Fence | undefined
309
+ let indented = false
310
+ for (const line of lines) {
311
+ if (fence !== undefined) {
312
+ scanned.push({ text: line, code: true })
313
+ if (closesFence(line, fence)) fence = undefined
314
+ continue
315
+ }
316
+ const opening = openingFence(line)
317
+ if (opening !== undefined) {
318
+ fence = opening
319
+ indented = false
320
+ scanned.push({ text: line, code: true })
321
+ continue
322
+ }
323
+ if (/^(?: {4}|\t)/u.test(line)) {
324
+ indented = true
325
+ scanned.push({ text: line, code: true })
326
+ continue
327
+ }
328
+ scanned.push({ text: line, code: indented && line.trim() === '' })
329
+ if (line.trim() !== '') indented = false
330
+ }
331
+ return { lines: scanned, openFence: fence }
332
+ }
333
+
334
+ function openingFence(line: string): Fence | undefined {
335
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(line)
336
+ if (opening === null) return undefined
337
+ const marker = String(opening[1])
338
+ const info = String(opening[2])
339
+ if (marker.startsWith('`') && info.includes('`')) return undefined
340
+ return { character: marker.slice(0, 1), length: marker.length }
341
+ }
342
+
343
+ function closesFence(line: string, fence: Fence): boolean {
344
+ const closing = new RegExp(`^ {0,3}${fence.character}{${String(fence.length)},}\\s*$`, 'u')
345
+ return closing.test(line)
346
+ }
347
+
348
+ // Close an assistant message that ended inside a code fence so the next
349
+ // message or generated details closer cannot be swallowed by that block.
350
+ function closeUnfinishedFence(markdown: string): string {
351
+ const scan = scanMarkdown(markdown)
352
+ if (scan.openFence === undefined) return markdown
353
+ const content = markdown.replace(/\n+$/u, '')
354
+ return `${content}\n${scan.openFence.character.repeat(scan.openFence.length)}`
355
+ }
356
+
357
+ // Arbitrary commentary inside a generated details section must not close the
358
+ // wrapper. Fenced and indented code keep their exact text.
359
+ function escapeWrapperTagsOutsideFences(markdown: string): string {
360
+ return scanMarkdown(markdown).lines
361
+ .map(line => line.code ? line.text : escapeWrapperTags(line.text))
362
+ .join('\n')
363
+ }
364
+
365
+ function escapeWrapperTags(text: string): string {
366
+ return text.replace(/<(?=\/?(?:details|summary)(?=[\s/>]))/giu, '&lt;')
367
+ }
package/src/routes.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The absolute pathnames the Host registers the export routes under and the
3
+ * document-relative forms the browser addresses; see
4
+ * .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
5
+ */
6
+
7
+ /** Absolute registration path for the ZIP download route. */
8
+ export const SESSION_LOG_EXPORT_PATH = '/api/session.export'
9
+
10
+ /** Browser-relative form of {@link SESSION_LOG_EXPORT_PATH}. */
11
+ export const SESSION_LOG_EXPORT_ROUTE = SESSION_LOG_EXPORT_PATH.slice(1)
12
+
13
+ /** Absolute registration path for the Markdown copy route. */
14
+ export const SESSION_MARKDOWN_EXPORT_PATH = '/api/session.markdown'
15
+
16
+ /** Browser-relative form of {@link SESSION_MARKDOWN_EXPORT_PATH}. */
17
+ export const SESSION_MARKDOWN_EXPORT_ROUTE = SESSION_MARKDOWN_EXPORT_PATH.slice(1)
@@ -1,26 +0,0 @@
1
- import type { ReactNode } from 'react';
2
- import type { ObservableSnapshot } from '@unieai/rabi-client-store';
3
- import type { InjectFace } from '@unieai/rabi-client-ui-slots';
4
- import type { SessionId } from '@unieai/rabi-session/types';
5
- import { type SessionLogDownloadDialogProps } from './Dialog.tsx';
6
- import type { SessionLogDownloadDialogInjected } from './Dialog.tsx';
7
- /** Session download controls with observable feedback availability and a Session feedback action. */
8
- export interface SessionLogDownloadHeaderInjected extends SessionLogDownloadDialogInjected {
9
- hooks: SessionLogDownloadDialogInjected['hooks'] & {
10
- feedbackAvailable: ObservableSnapshot<boolean>;
11
- };
12
- /**
13
- * Open the existing Session feedback draft without recording feedback; no-op after the feedback plugin unloads.
14
- * @param sessionId - Session whose feedback form to open.
15
- */
16
- openFeedback: (sessionId: SessionId) => void;
17
- }
18
- /** Session download props plus the optional feedback action. */
19
- export type SessionLogDownloadHeaderProps = SessionLogDownloadDialogProps & InjectFace<SessionLogDownloadHeaderInjected>;
20
- /**
21
- * Render the Session Header menu with download and optional feedback actions.
22
- * @param props - Session runtime, download controller, and localized copy.
23
- * @returns the persistent Header action and Session-scoped dialog.
24
- */
25
- export declare function SessionLogDownloadHeaderAction(props: SessionLogDownloadHeaderProps): ReactNode;
26
- //# sourceMappingURL=HeaderAction.d.ts.map