@unieai/rabi-session-log-export 0.0.0-stage → 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,149 @@
1
+ /** Locale namespace owned by Session export browser feedback. */
2
+ export const NS = 'session-log-download'
3
+
4
+ /** Simplified-Chinese Session export strings. */
5
+ export const zh = {
6
+ 'menu.copyMarkdown': '复制会话为 Markdown',
7
+ 'menu.download': '下载 Session 日志',
8
+ 'menu.feedback': '反馈',
9
+ 'toast.copied': 'Session 已复制为 Markdown',
10
+ 'toast.preparationFailed': '无法读取 Session 进行复制,请重试',
11
+ 'toast.clipboardFailed': '无法写入剪贴板,请检查剪贴板权限后重试',
12
+ 'dialog.session': 'Session:{sessionId}',
13
+ 'dialog.preparingTitle': '正在导出 Session',
14
+ 'dialog.preparingDescription': '正在准备包含指定 Session、子 Session 和附件的 ZIP 文件',
15
+ 'dialog.successTitle': 'Session 导出已开始下载',
16
+ 'dialog.successDescription': '浏览器正在下载 Session ZIP 文件。',
17
+ 'dialog.errorTitle': 'Session 导出失败',
18
+ 'dialog.close': '关闭',
19
+ 'dialog.commandFailed': '无法启动 Session 导出。',
20
+ } as const
21
+
22
+ /** English Session export strings. */
23
+ export const en: Record<keyof typeof zh, string> = {
24
+ 'menu.copyMarkdown': 'Copy Session as Markdown',
25
+ 'menu.download': 'Download session log',
26
+ 'menu.feedback': 'Feedback',
27
+ 'toast.copied': 'Session copied as Markdown.',
28
+ 'toast.preparationFailed': 'Could not read the Session for copying. Try again.',
29
+ 'toast.clipboardFailed': 'Could not write to the clipboard. Check clipboard permission and try again.',
30
+ 'dialog.session': 'Session: {sessionId}',
31
+ 'dialog.preparingTitle': 'Exporting Session',
32
+ 'dialog.preparingDescription': 'Preparing a ZIP containing the selected Session, its sub-Sessions, and attachments.',
33
+ 'dialog.successTitle': 'Session download started',
34
+ 'dialog.successDescription': 'The browser is downloading the Session ZIP.',
35
+ 'dialog.errorTitle': 'Session export failed',
36
+ 'dialog.close': 'Close',
37
+ 'dialog.commandFailed': 'Could not start the Session export.',
38
+ }
39
+
40
+ /** Stable locale keys consumed by the shared modal. */
41
+ export type SessionLogDownloadKey = keyof typeof zh
42
+
43
+ /** Japanese copy, checked against the English keys. */
44
+ export const ja = {
45
+ 'menu.copyMarkdown': 'セッションを Markdown としてコピー',
46
+ 'menu.download': 'セッションログをダウンロード',
47
+ 'menu.feedback': 'フィードバック',
48
+ 'toast.copied': 'セッションを Markdown としてコピーしました',
49
+ 'toast.preparationFailed': 'コピーするセッションを読み取れませんでした。再試行してください。',
50
+ 'toast.clipboardFailed': 'クリップボードに書き込めませんでした。クリップボードの権限を確認して再試行してください。',
51
+ 'dialog.session': 'セッション: {sessionId}',
52
+ 'dialog.preparingTitle': 'セッションをエクスポート中',
53
+ 'dialog.preparingDescription': '指定のセッション、そのサブセッション、添付ファイルを含むZIPを準備しています。',
54
+ 'dialog.successTitle': 'セッションのダウンロードを開始しました',
55
+ 'dialog.successDescription': 'ブラウザがセッションZIPをダウンロードしています。',
56
+ 'dialog.errorTitle': 'セッションのエクスポートに失敗しました',
57
+ 'dialog.close': '閉じる',
58
+ 'dialog.commandFailed': 'セッションのエクスポートを開始できませんでした。',
59
+ } satisfies Record<keyof typeof en, string>
60
+
61
+ /** Spanish dictionary, checked against the English keys. */
62
+ export const es = {
63
+ 'menu.copyMarkdown': 'Copiar sesión como Markdown',
64
+ 'menu.download': 'Descargar registro de sesión',
65
+ 'menu.feedback': 'Comentarios',
66
+ 'toast.copied': 'Sesión copiada como Markdown.',
67
+ 'toast.preparationFailed': 'No se pudo leer la sesión para copiarla. Intentar otra vez.',
68
+ 'toast.clipboardFailed': 'No se pudo escribir en el portapapeles. Verifique los permisos del portapapeles e inténtelo nuevamente.',
69
+ 'dialog.session': 'Sesión: {sessionId}',
70
+ 'dialog.preparingTitle': 'Sesión de exportación',
71
+ 'dialog.preparingDescription': 'Preparar un ZIP que contenga la sesión seleccionada, sus subsesiones y archivos adjuntos.',
72
+ 'dialog.successTitle': 'Descarga de sesión iniciada',
73
+ 'dialog.successDescription': 'El navegador está descargando el ZIP de la sesión.',
74
+ 'dialog.errorTitle': 'Error al exportar la sesión',
75
+ 'dialog.close': 'Cerrar',
76
+ 'dialog.commandFailed': 'No se pudo iniciar la exportación de la sesión.',
77
+ } satisfies Record<keyof typeof en, string>
78
+
79
+ /** French dictionary, checked against the English keys. */
80
+ export const fr = {
81
+ 'menu.copyMarkdown': 'Copier la session sous Markdown',
82
+ 'menu.download': 'Télécharger le journal de session',
83
+ 'menu.feedback': 'Commentaires',
84
+ 'toast.copied': 'Session copiée sous le nom Markdown.',
85
+ 'toast.preparationFailed': 'Impossible de lire la session pour la copier. Essayer à nouveau.',
86
+ 'toast.clipboardFailed': "Impossible d'écrire dans le presse-papiers. Vérifiez l'autorisation du presse-papiers et réessayez.",
87
+ 'dialog.session': 'Session : {sessionId}',
88
+ 'dialog.preparingTitle': "Session d'exportation",
89
+ 'dialog.preparingDescription': "Préparation d'un ZIP contenant la session sélectionnée, ses sous-sessions et les pièces jointes.",
90
+ 'dialog.successTitle': 'Le téléchargement de la session a commencé',
91
+ 'dialog.successDescription': 'Le navigateur télécharge le ZIP de la session.',
92
+ 'dialog.errorTitle': "Échec de l'exportation de la session",
93
+ 'dialog.close': 'Fermer',
94
+ 'dialog.commandFailed': "Impossible de démarrer l'exportation de session.",
95
+ } satisfies Record<keyof typeof en, string>
96
+
97
+ /** German dictionary, checked against the English keys. */
98
+ export const de = {
99
+ 'menu.copyMarkdown': 'Kopieren Sie die Sitzung als Markdown',
100
+ 'menu.download': 'Sitzungsprotokoll herunterladen',
101
+ 'menu.feedback': 'Rückmeldung',
102
+ 'toast.copied': 'Sitzung als Markdown kopiert.',
103
+ 'toast.preparationFailed': 'Die Sitzung zum Kopieren konnte nicht gelesen werden. Versuchen Sie es erneut.',
104
+ 'toast.clipboardFailed': 'Es konnte nicht in die Zwischenablage geschrieben werden. Überprüfen Sie die Berechtigung für die Zwischenablage und versuchen Sie es erneut.',
105
+ 'dialog.session': 'Sitzung: {sessionId}',
106
+ 'dialog.preparingTitle': 'Sitzung exportieren',
107
+ 'dialog.preparingDescription': 'Vorbereiten einer ZIP-Datei mit der ausgewählten Sitzung, ihren Untersitzungen und Anhängen.',
108
+ 'dialog.successTitle': 'Sitzungsdownload gestartet',
109
+ 'dialog.successDescription': 'Der Browser lädt die Sitzungs-ZIP herunter.',
110
+ 'dialog.errorTitle': 'Der Sitzungsexport ist fehlgeschlagen',
111
+ 'dialog.close': 'Schließen',
112
+ 'dialog.commandFailed': 'Der Sitzungsexport konnte nicht gestartet werden.',
113
+ } satisfies Record<keyof typeof en, string>
114
+
115
+ /** Russian dictionary, checked against the English keys. */
116
+ export const ru = {
117
+ 'menu.copyMarkdown': 'Скопировать сеанс как Markdown',
118
+ 'menu.download': 'Скачать журнал сеанса',
119
+ 'menu.feedback': 'Обратная связь',
120
+ 'toast.copied': 'Сессия скопирована как Markdown.',
121
+ 'toast.preparationFailed': 'Не удалось прочитать сеанс для копирования. Попробуйте еще раз.',
122
+ 'toast.clipboardFailed': 'Не удалось записать в буфер обмена. Проверьте разрешение буфера обмена и повторите попытку.',
123
+ 'dialog.session': 'Сеанс: {sessionId}',
124
+ 'dialog.preparingTitle': 'Экспорт сеанса',
125
+ 'dialog.preparingDescription': 'Подготовка ZIP-файла, содержащего выбранный сеанс, его подсеансы и вложения.',
126
+ 'dialog.successTitle': 'Загрузка сеанса началась',
127
+ 'dialog.successDescription': 'Браузер загружает ZIP-файл сеанса.',
128
+ 'dialog.errorTitle': 'Экспорт сеанса не удался',
129
+ 'dialog.close': 'Закрыть',
130
+ 'dialog.commandFailed': 'Не удалось начать экспорт сеанса.',
131
+ } satisfies Record<keyof typeof en, string>
132
+
133
+ /** Portuguese dictionary, checked against the English keys. */
134
+ export const pt = {
135
+ 'menu.copyMarkdown': 'Copiar sessão como Markdown',
136
+ 'menu.download': 'Baixar registro da sessão',
137
+ 'menu.feedback': 'Comentários',
138
+ 'toast.copied': 'Sessão copiada como Markdown.',
139
+ 'toast.preparationFailed': 'Não foi possível ler a sessão para cópia. Tente novamente.',
140
+ 'toast.clipboardFailed': 'Não foi possível gravar na área de transferência. Verifique a permissão da área de transferência e tente novamente.',
141
+ 'dialog.session': 'Sessão: {sessionId}',
142
+ 'dialog.preparingTitle': 'Exportando Sessão',
143
+ 'dialog.preparingDescription': 'Preparando um ZIP contendo a sessão selecionada, suas subsessões e anexos.',
144
+ 'dialog.successTitle': 'Download da sessão iniciado',
145
+ 'dialog.successDescription': 'O navegador está baixando o ZIP da sessão.',
146
+ 'dialog.errorTitle': 'Falha na exportação da sessão',
147
+ 'dialog.close': 'Fechar',
148
+ 'dialog.commandFailed': 'Não foi possível iniciar a exportação da sessão.',
149
+ } satisfies Record<keyof typeof en, string>
package/src/index.ts ADDED
@@ -0,0 +1,234 @@
1
+ /** Session export command and Host-owned ZIP download and Markdown copy routes. */
2
+
3
+ import type { Context } from '@unieai/cordis'
4
+ import type { CommandDefinitionId } from '@unieai/rabi-commands/brand'
5
+ import Schema from '@unieai/schemastery'
6
+ import { brandString } from '@unieai/rabi-brand'
7
+ import type {} from '@unieai/rabi-attachment'
8
+ import type { CommandResult } from '@unieai/rabi-commands'
9
+ import type { SessionId } from '@unieai/rabi-session/types'
10
+ import {
11
+ DEFAULT_SESSION_LOG_COMPRESSION_LEVEL,
12
+ flushLiveSessionLog,
13
+ readSessionLogText,
14
+ sessionLogExportDeps,
15
+ sessionLogZipFilename,
16
+ streamSessionLogZip,
17
+ type SessionLogCompressionLevel,
18
+ type SessionLogExportReady,
19
+ } from './archive.ts'
20
+ import { formatSessionMarkdown } from './markdown.ts'
21
+ import { SESSION_LOG_EXPORT_PATH, SESSION_MARKDOWN_EXPORT_PATH } from './routes.ts'
22
+
23
+ export {
24
+ DEFAULT_SESSION_LOG_COMPRESSION_LEVEL,
25
+ flushLiveSessionLog,
26
+ readSessionLogText,
27
+ serializeSessionLog,
28
+ SESSION_LOG_FILENAME,
29
+ sessionLogExportDeps,
30
+ sessionLogZipEntries,
31
+ sessionLogZipFilename,
32
+ streamSessionLogZip,
33
+ } from './archive.ts'
34
+ export type {
35
+ SessionLogCompressionLevel,
36
+ SessionLogExportDeps,
37
+ SessionLogExportReady,
38
+ SessionLogZipEntry,
39
+ } from './archive.ts'
40
+ export { formatSessionMarkdown } from './markdown.ts'
41
+
42
+ export const name = 'session-log-download'
43
+ export const inject = ['commands', 'connection']
44
+
45
+ export { SESSION_LOG_EXPORT_PATH } from './routes.ts'
46
+
47
+ /** Session-log archive policy. */
48
+ export interface Config {
49
+ /** DEFLATE level for each ZIP entry. @default 6 */
50
+ readonly compressionLevel?: SessionLogCompressionLevel
51
+ }
52
+
53
+ /** Validate Session-log archive configuration. */
54
+ export const Config: Schema<Config> = Schema.object({
55
+ compressionLevel: Schema.number().step(1).min(0).max(9)
56
+ .default(DEFAULT_SESSION_LOG_COMPRESSION_LEVEL) as Schema<SessionLogCompressionLevel>,
57
+ })
58
+
59
+ interface SessionLogConnection {
60
+ readonly fetch: {
61
+ register(route: {
62
+ readonly path: string
63
+ readonly methods: readonly ('GET' | 'HEAD')[]
64
+ readonly requestBody: 'buffered'
65
+ readonly fetch: (request: Request) => Promise<Response>
66
+ }): () => Promise<void>
67
+ }
68
+ }
69
+
70
+ const REQUESTED: CommandResult = {
71
+ kind: 'success',
72
+ text: 'Session log download requested.',
73
+ }
74
+
75
+ /**
76
+ * Register the `/export` command and authenticated ZIP download and Markdown copy routes.
77
+ * @param ctx - Host context carrying the human-command registry.
78
+ * @param config - resolved compression policy.
79
+ */
80
+ export function apply(ctx: Context, config: Config = {}): void {
81
+ ctx.effect(() => ctx.commands.register({
82
+ definitionId: brandString<CommandDefinitionId>('@unieai/rabi-session-log-export'),
83
+ name: 'export',
84
+ description: 'Download this Session log as a ZIP archive',
85
+ handler: invocation => Promise.resolve(invocation.rawInput.trim() === ''
86
+ ? REQUESTED
87
+ : { kind: 'error', text: 'The Web /export command does not accept a path.' }),
88
+ }), 'session-log-download: command')
89
+ connectionOf(ctx).fetch.register({
90
+ path: SESSION_LOG_EXPORT_PATH,
91
+ methods: ['GET', 'HEAD'],
92
+ requestBody: 'buffered',
93
+ fetch: async (request) => {
94
+ const response = await sessionLogExportResponse(
95
+ ctx,
96
+ request,
97
+ config.compressionLevel ?? DEFAULT_SESSION_LOG_COMPRESSION_LEVEL,
98
+ )
99
+ if (request.method === 'GET') return response
100
+ await response.body?.cancel()
101
+ return new Response(null, { status: response.status, headers: response.headers })
102
+ },
103
+ })
104
+ connectionOf(ctx).fetch.register({
105
+ path: SESSION_MARKDOWN_EXPORT_PATH,
106
+ methods: ['GET', 'HEAD'],
107
+ requestBody: 'buffered',
108
+ fetch: async (request) => {
109
+ const response = await sessionMarkdownResponse(ctx, request)
110
+ if (request.method === 'GET') return response
111
+ await response.body?.cancel()
112
+ return new Response(null, { status: response.status, headers: response.headers })
113
+ },
114
+ })
115
+ }
116
+
117
+ function connectionOf(ctx: Context): SessionLogConnection {
118
+ return Reflect.get(ctx, 'connection') as SessionLogConnection
119
+ }
120
+
121
+ /**
122
+ * Produce one complete Session transcript as Markdown from one Session
123
+ * observation. The read is a detached export observation through
124
+ * session-query's live-preferred corpus, so it creates no Agent, retains no
125
+ * Session, and writes no Session data. The formatter reads the latest title from
126
+ * the same event snapshot as the body. Abort is observed before and after the
127
+ * read; the corpus read itself has no cancellation parameter.
128
+ * @param ctx - host context carrying Connection and session-query.
129
+ * @param request - authenticated Fetch request with a required `sessionId` query.
130
+ * @returns the Markdown response, or a sanitized status for invalid, missing, or unavailable reads.
131
+ */
132
+ async function sessionMarkdownResponse(ctx: Context, request: Request): Promise<Response> {
133
+ const sessionIdValue = new URL(request.url).searchParams.get('sessionId')
134
+ if (sessionIdValue === null || sessionIdValue.length === 0) {
135
+ return new Response('missing or invalid sessionId query parameter', { status: 400 })
136
+ }
137
+ const sessionQuery = ctx.get('sessionQuery')
138
+ if (sessionQuery === undefined) {
139
+ return new Response('session markdown export is unavailable: missing session-query service', { status: 500 })
140
+ }
141
+ const sessionId = brandString<SessionId>(sessionIdValue)
142
+ try {
143
+ request.signal.throwIfAborted()
144
+ const snapshot = await sessionQuery.readSession(sessionId)
145
+ request.signal.throwIfAborted()
146
+ const metadata = await ctx.get('sessionPersistence')?.stat(sessionId, { signal: request.signal })
147
+ request.signal.throwIfAborted()
148
+ return new Response(formatSessionMarkdown(snapshot.events, metadata?.location?.path), {
149
+ headers: { 'content-type': 'text/markdown; charset=utf-8' },
150
+ })
151
+ } catch (error: unknown) {
152
+ request.signal.throwIfAborted()
153
+ // Absence is session-query's decision: match its stable error code rather
154
+ // than adding a Host value dependency on the session-query error class.
155
+ if (isSessionNotFound(error)) return new Response('session not found', { status: 404 })
156
+ // Every other failure stays opaque: the message may carry absolute host
157
+ // paths into the browser toast.
158
+ return new Response('session markdown export failed to read the stored log', { status: 500 })
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Identify the session-query "not found" failure by its stable machine code.
164
+ * @param error - an arbitrary rejection from the query service.
165
+ * @returns whether the error reports a missing Session.
166
+ */
167
+ function isSessionNotFound(error: unknown): boolean {
168
+ return error instanceof Error
169
+ && 'code' in error
170
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND'
171
+ }
172
+
173
+ async function sessionLogExportResponse(
174
+ ctx: Context,
175
+ request: Request,
176
+ compressionLevel: SessionLogCompressionLevel,
177
+ ): Promise<Response> {
178
+ const url = new URL(request.url)
179
+ const query = Object.fromEntries(url.searchParams)
180
+ const sessionIdValue = query['sessionId']
181
+ const descendantsValue = query['includeDescendants']
182
+ if (sessionIdValue === undefined || sessionIdValue.length === 0
183
+ || (descendantsValue !== undefined && descendantsValue !== 'true' && descendantsValue !== 'false')) {
184
+ return new Response('missing or invalid sessionId query parameter', { status: 400 })
185
+ }
186
+ const sessionId = brandString<SessionId>(sessionIdValue)
187
+ const deps = sessionLogExportDeps(ctx)
188
+ if (deps.sessionQuery === undefined
189
+ || deps.sessionPersistence === undefined
190
+ || deps.attachments === undefined) {
191
+ return new Response(
192
+ 'session log export is unavailable: missing session-query, session-persistence, or attachments service',
193
+ { status: 500 },
194
+ )
195
+ }
196
+ const ready: SessionLogExportReady = {
197
+ sessionQuery: deps.sessionQuery,
198
+ sessionPersistence: deps.sessionPersistence,
199
+ attachments: deps.attachments,
200
+ sessions: deps.sessions,
201
+ }
202
+ let rootContent: string | undefined
203
+ try {
204
+ await flushLiveSessionLog(deps, sessionId, request.signal)
205
+ rootContent = await readSessionLogText(deps.sessionPersistence, sessionId, request.signal)
206
+ request.signal.throwIfAborted()
207
+ } catch {
208
+ request.signal.throwIfAborted()
209
+ // Root preparation failure (flush, open, or read): answer 500 without
210
+ // echoing the error, which may carry absolute host paths into the
211
+ // browser error bar.
212
+ return new Response('session log export failed to read the stored log', { status: 500 })
213
+ }
214
+ if (rootContent === undefined) {
215
+ return new Response('session not found', { status: 404 })
216
+ }
217
+ const response = new Response(
218
+ streamSessionLogZip(
219
+ ready,
220
+ rootContent,
221
+ sessionId,
222
+ descendantsValue === 'true',
223
+ compressionLevel,
224
+ request.signal,
225
+ ),
226
+ {
227
+ headers: {
228
+ 'content-type': 'application/zip',
229
+ 'content-disposition': `attachment; filename="${sessionLogZipFilename(sessionId)}"`,
230
+ },
231
+ },
232
+ )
233
+ return response
234
+ }