@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.
- package/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/client.js +2 -0
- package/lib/index.js +980 -0
- package/lib/types/archive.d.ts +132 -0
- package/lib/types/client/CopyToast.d.ts +21 -0
- package/lib/types/client/Dialog.d.ts +22 -0
- package/lib/types/client/controller.d.ts +69 -0
- package/lib/types/client/copy-controller.d.ts +76 -0
- package/lib/types/client/index.d.ts +24 -0
- package/lib/types/client/locales.d.ts +126 -0
- package/lib/types/index.d.ts +24 -0
- package/lib/types/markdown.d.ts +22 -0
- package/lib/types/routes.d.ts +14 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +57 -4
- package/src/archive.ts +706 -0
- package/src/client/CopyToast.tsx +40 -0
- package/src/client/Dialog.tsx +55 -0
- package/src/client/controller.ts +139 -0
- package/src/client/copy-controller.ts +201 -0
- package/src/client/index.ts +105 -0
- package/src/client/locales.ts +149 -0
- package/src/index.ts +234 -0
- package/src/markdown.ts +367 -0
- package/src/routes.ts +17 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeepSeek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @unieai/rabi-session-log-export
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Web Session-log ZIP export and Session Markdown copy
|
|
4
|
+
|
|
5
|
+
Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
|
|
6
|
+
not meant to be used on its own.
|
|
7
|
+
|
|
8
|
+
See LICENSE for the license and copyright of this package.
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
|
|
2
|
+
window.__ModuleLoader__.load({id:`@unieai/rabi-session-log-export`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _unieai_rabi_client_store=require("@unieai/rabi-client-store");let _unieai_rabi_client_ui_primitives=require("@unieai/rabi-client-ui-primitives");let react_jsx_runtime=require("react/jsx-runtime");const SESSION_LOG_EXPORT_PATH=`/api/session.export`;const SESSION_LOG_EXPORT_ROUTE=SESSION_LOG_EXPORT_PATH.slice(1);const SESSION_MARKDOWN_EXPORT_PATH=`/api/session.markdown`;const SESSION_MARKDOWN_EXPORT_ROUTE=SESSION_MARKDOWN_EXPORT_PATH.slice(1);const INITIAL$1={bySession:{}};function sessionLogZipFilename(sessionId){return`rabi-session-${String(sessionId).replace(/[^A-Za-z0-9_-]/g,`_`)}.zip`}function downloadUrl(url,filename){const anchor=document.createElement(`a`);anchor.href=url;anchor.download=filename;anchor.click()}function messageOf(error){return error instanceof Error?error.message:String(error)}var SessionLogDownloadController=class{fetcher;save;store=(0,_unieai_rabi_client_store.createSnapshotStore)(INITIAL$1);active=new Map;disposed=false;nextOrder=0;constructor(fetcher=(input,init)=>fetch(input,init),save=downloadUrl){this.fetcher=fetcher;this.save=save}download(sessionId){const existing=this.active.get(sessionId);if(existing!==void 0)return existing.done;if(this.disposed)return Promise.resolve();const abort=new AbortController;const done=this.run(sessionId,abort.signal,this.nextOrder++).finally(()=>{this.active.delete(sessionId)});this.active.set(sessionId,{abort,done});return done}dismiss(sessionId){const current=this.store.getSnapshot().bySession[String(sessionId)];if(current===void 0||!current.open)return;this.publish(sessionId,{...current,open:false})}async dispose(){this.disposed=true;const active=[...this.active.values()];for(const operation of active)operation.abort.abort();await Promise.allSettled(active.map(operation=>operation.done))}async run(sessionId,signal,order){this.publish(sessionId,{order,open:true,status:`downloading`,error:null});try{const route=`${SESSION_LOG_EXPORT_ROUTE}?${new URLSearchParams({sessionId,includeDescendants:`true`}).toString()}`;const response=await this.fetcher(route,{method:`HEAD`,signal});if(!response.ok){const detail=await response.text().catch(()=>``);throw new Error(`Export failed: HTTP ${response.status}${detail===``?``:` ${detail}`}`)}if(signal.aborted)return;this.save(route,sessionLogZipFilename(sessionId));const open=this.store.getSnapshot().bySession[String(sessionId)]?.open??true;this.publish(sessionId,{order,open,status:`success`,error:null})}catch(error){if(signal.aborted)return;const open=this.store.getSnapshot().bySession[String(sessionId)]?.open??true;this.publish(sessionId,{order,open,status:`error`,error:messageOf(error)})}}publish(sessionId,entry){this.store.update(state=>{state.bySession={...state.bySession,[String(sessionId)]:entry}})}};const INITIAL={copying:false,notice:null};const browserClipboard={supportsDeferredWrite(){const clipboard=Reflect.get(navigator,`clipboard`);return typeof globalThis.ClipboardItem===`function`&&typeof clipboard===`object`&&clipboard!==null&&typeof Reflect.get(clipboard,`write`)===`function`},writeDeferred(data){return navigator.clipboard.write([new ClipboardItem({"text/plain":data})])},writeText:_unieai_rabi_client_ui_primitives.writeClipboard};function startWrite(start){try{return start()}catch(error){return Promise.reject(new Error(`clipboard write could not start`,{cause:error}))}}var SessionMarkdownCopyController=class{fetcher;clipboard;store=(0,_unieai_rabi_client_store.createSnapshotStore)(INITIAL);pending;disposed=false;noticeSeq=0;constructor(fetcher=(input,init)=>fetch(input,init),clipboard=browserClipboard){this.fetcher=fetcher;this.clipboard=clipboard}copy(sessionId){if(this.disposed)return Promise.resolve();if(this.pending!==void 0)return this.pending.done;const abort=new AbortController;const done=this.run(sessionId,abort.signal).finally(()=>{this.pending=void 0});this.pending={abort,done};return done}dismiss(){if(this.store.getSnapshot().notice===null)return;this.store.update(state=>{state.notice=null})}async dispose(){this.disposed=true;const pending=this.pending;pending?.abort.abort();await pending?.done;this.store.set(INITIAL)}run(sessionId,signal){this.store.update(state=>{state.copying=true});const preparation=this.prepare(sessionId,signal);if(this.clipboard.supportsDeferredWrite()){const data=preparation.then(markdown=>{if(this.isCancelled()||signal.aborted)throw new Error(`Session Markdown copy cancelled`);return new Blob([markdown],{type:`text/plain`})});const write=startWrite(()=>this.clipboard.writeDeferred(data));return this.settleDeferred(preparation,data,write)}return this.settleFallback(preparation)}async prepare(sessionId,signal){const route=`${SESSION_MARKDOWN_EXPORT_ROUTE}?${new URLSearchParams({sessionId}).toString()}`;const response=await this.fetcher(route,{signal});if(!response.ok)throw new Error(`Session Markdown request failed: HTTP ${String(response.status)}`);return response.text()}async settleDeferred(preparation,data,write){try{const[prepared,blob,written]=await Promise.allSettled([preparation,data,write]);if(this.isCancelled())return;if(prepared.status===`rejected`||blob.status===`rejected`){this.publishNotice(`preparationFailed`);return}if(written.status===`rejected`){this.publishNotice(`clipboardFailed`);return}this.publishNotice(`success`)}finally{this.store.update(state=>{state.copying=false})}}async settleFallback(preparation){try{let markdown;try{markdown=await preparation}catch{if(!this.isCancelled())this.publishNotice(`preparationFailed`);return}if(this.isCancelled())return;let accepted=false;try{accepted=await this.clipboard.writeText(markdown)}catch{accepted=false}if(this.isCancelled())return;this.publishNotice(accepted?`success`:`clipboardFailed`)}finally{this.store.update(state=>{state.copying=false})}}isCancelled(){return this.disposed}publishNotice(kind){this.store.update(state=>{state.notice={kind,seq:++this.noticeSeq}})}};function SessionMarkdownCopyToast({useSessionMarkdownCopy,dismiss,t}){const notice=useSessionMarkdownCopy(state=>state.notice);if(notice===null)return null;return notice.kind===`success`?(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Toast,{text:t(`toast.copied`),tone:`success`,onDone:dismiss},notice.seq):(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Toast,{text:t(notice.kind===`preparationFailed`?`toast.preparationFailed`:`toast.clipboardFailed`),icon:(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.IconWarningOutlineRegular,{}),onDone:dismiss},notice.seq)}function SessionLogDownloadDialog({useSessionLogDownload,dismiss,t}){const bySession=useSessionLogDownload(state=>state.bySession);const pending=Object.entries(bySession).filter(pair=>pair[1]?.open===true).sort((a,b)=>a[1].order-b[1].order)[0];if(pending===void 0)return null;const[id,entry]=pending;const sessionId=id;const{status}=entry;const title=status===`downloading`?t(`dialog.preparingTitle`):status===`success`?t(`dialog.successTitle`):t(`dialog.errorTitle`);const description=status===`downloading`?t(`dialog.preparingDescription`):status===`success`?t(`dialog.successDescription`):entry.error||t(`dialog.commandFailed`);return(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Modal,{open:true,onClose:()=>{dismiss(sessionId)},title,description:`${t(`dialog.session`,{sessionId})} ${description}`,closeLabel:t(`dialog.close`),footer:(0,react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Button,{variant:`primary`,onClick:()=>{dismiss(sessionId)},children:t(`dialog.close`)})})}const NS=`session-log-download`;const zh={"menu.copyMarkdown":`复制会话为 Markdown`,"menu.download":`下载 Session 日志`,"menu.feedback":`反馈`,"toast.copied":`Session 已复制为 Markdown`,"toast.preparationFailed":`无法读取 Session 进行复制,请重试`,"toast.clipboardFailed":`无法写入剪贴板,请检查剪贴板权限后重试`,"dialog.session":`Session:{sessionId}`,"dialog.preparingTitle":`正在导出 Session`,"dialog.preparingDescription":`正在准备包含指定 Session、子 Session 和附件的 ZIP 文件`,"dialog.successTitle":`Session 导出已开始下载`,"dialog.successDescription":`浏览器正在下载 Session ZIP 文件。`,"dialog.errorTitle":`Session 导出失败`,"dialog.close":`关闭`,"dialog.commandFailed":`无法启动 Session 导出。`};const en={"menu.copyMarkdown":`Copy Session as Markdown`,"menu.download":`Download session log`,"menu.feedback":`Feedback`,"toast.copied":`Session copied as Markdown.`,"toast.preparationFailed":`Could not read the Session for copying. Try again.`,"toast.clipboardFailed":`Could not write to the clipboard. Check clipboard permission and try again.`,"dialog.session":`Session: {sessionId}`,"dialog.preparingTitle":`Exporting Session`,"dialog.preparingDescription":`Preparing a ZIP containing the selected Session, its sub-Sessions, and attachments.`,"dialog.successTitle":`Session download started`,"dialog.successDescription":`The browser is downloading the Session ZIP.`,"dialog.errorTitle":`Session export failed`,"dialog.close":`Close`,"dialog.commandFailed":`Could not start the Session export.`};const ja={"menu.copyMarkdown":`セッションを Markdown としてコピー`,"menu.download":`セッションログをダウンロード`,"menu.feedback":`フィードバック`,"toast.copied":`セッションを Markdown としてコピーしました`,"toast.preparationFailed":`コピーするセッションを読み取れませんでした。再試行してください。`,"toast.clipboardFailed":`クリップボードに書き込めませんでした。クリップボードの権限を確認して再試行してください。`,"dialog.session":`セッション: {sessionId}`,"dialog.preparingTitle":`セッションをエクスポート中`,"dialog.preparingDescription":`指定のセッション、そのサブセッション、添付ファイルを含むZIPを準備しています。`,"dialog.successTitle":`セッションのダウンロードを開始しました`,"dialog.successDescription":`ブラウザがセッションZIPをダウンロードしています。`,"dialog.errorTitle":`セッションのエクスポートに失敗しました`,"dialog.close":`閉じる`,"dialog.commandFailed":`セッションのエクスポートを開始できませんでした。`};const es={"menu.copyMarkdown":`Copiar sesión como Markdown`,"menu.download":`Descargar registro de sesión`,"menu.feedback":`Comentarios`,"toast.copied":`Sesión copiada como Markdown.`,"toast.preparationFailed":`No se pudo leer la sesión para copiarla. Intentar otra vez.`,"toast.clipboardFailed":`No se pudo escribir en el portapapeles. Verifique los permisos del portapapeles e inténtelo nuevamente.`,"dialog.session":`Sesión: {sessionId}`,"dialog.preparingTitle":`Sesión de exportación`,"dialog.preparingDescription":`Preparar un ZIP que contenga la sesión seleccionada, sus subsesiones y archivos adjuntos.`,"dialog.successTitle":`Descarga de sesión iniciada`,"dialog.successDescription":`El navegador está descargando el ZIP de la sesión.`,"dialog.errorTitle":`Error al exportar la sesión`,"dialog.close":`Cerrar`,"dialog.commandFailed":`No se pudo iniciar la exportación de la sesión.`};const fr={"menu.copyMarkdown":`Copier la session sous Markdown`,"menu.download":`Télécharger le journal de session`,"menu.feedback":`Commentaires`,"toast.copied":`Session copiée sous le nom Markdown.`,"toast.preparationFailed":`Impossible de lire la session pour la copier. Essayer à nouveau.`,"toast.clipboardFailed":`Impossible d'écrire dans le presse-papiers. Vérifiez l'autorisation du presse-papiers et réessayez.`,"dialog.session":`Session : {sessionId}`,"dialog.preparingTitle":`Session d'exportation`,"dialog.preparingDescription":`Préparation d'un ZIP contenant la session sélectionnée, ses sous-sessions et les pièces jointes.`,"dialog.successTitle":`Le téléchargement de la session a commencé`,"dialog.successDescription":`Le navigateur télécharge le ZIP de la session.`,"dialog.errorTitle":`Échec de l'exportation de la session`,"dialog.close":`Fermer`,"dialog.commandFailed":`Impossible de démarrer l'exportation de session.`};const de={"menu.copyMarkdown":`Kopieren Sie die Sitzung als Markdown`,"menu.download":`Sitzungsprotokoll herunterladen`,"menu.feedback":`Rückmeldung`,"toast.copied":`Sitzung als Markdown kopiert.`,"toast.preparationFailed":`Die Sitzung zum Kopieren konnte nicht gelesen werden. Versuchen Sie es erneut.`,"toast.clipboardFailed":`Es konnte nicht in die Zwischenablage geschrieben werden. Überprüfen Sie die Berechtigung für die Zwischenablage und versuchen Sie es erneut.`,"dialog.session":`Sitzung: {sessionId}`,"dialog.preparingTitle":`Sitzung exportieren`,"dialog.preparingDescription":`Vorbereiten einer ZIP-Datei mit der ausgewählten Sitzung, ihren Untersitzungen und Anhängen.`,"dialog.successTitle":`Sitzungsdownload gestartet`,"dialog.successDescription":`Der Browser lädt die Sitzungs-ZIP herunter.`,"dialog.errorTitle":`Der Sitzungsexport ist fehlgeschlagen`,"dialog.close":`Schließen`,"dialog.commandFailed":`Der Sitzungsexport konnte nicht gestartet werden.`};const ru={"menu.copyMarkdown":`Скопировать сеанс как Markdown`,"menu.download":`Скачать журнал сеанса`,"menu.feedback":`Обратная связь`,"toast.copied":`Сессия скопирована как Markdown.`,"toast.preparationFailed":`Не удалось прочитать сеанс для копирования. Попробуйте еще раз.`,"toast.clipboardFailed":`Не удалось записать в буфер обмена. Проверьте разрешение буфера обмена и повторите попытку.`,"dialog.session":`Сеанс: {sessionId}`,"dialog.preparingTitle":`Экспорт сеанса`,"dialog.preparingDescription":`Подготовка ZIP-файла, содержащего выбранный сеанс, его подсеансы и вложения.`,"dialog.successTitle":`Загрузка сеанса началась`,"dialog.successDescription":`Браузер загружает ZIP-файл сеанса.`,"dialog.errorTitle":`Экспорт сеанса не удался`,"dialog.close":`Закрыть`,"dialog.commandFailed":`Не удалось начать экспорт сеанса.`};const pt={"menu.copyMarkdown":`Copiar sessão como Markdown`,"menu.download":`Baixar registro da sessão`,"menu.feedback":`Comentários`,"toast.copied":`Sessão copiada como Markdown.`,"toast.preparationFailed":`Não foi possível ler a sessão para cópia. Tente novamente.`,"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.`,"dialog.session":`Sessão: {sessionId}`,"dialog.preparingTitle":`Exportando Sessão`,"dialog.preparingDescription":`Preparando um ZIP contendo a sessão selecionada, suas subsessões e anexos.`,"dialog.successTitle":`Download da sessão iniciado`,"dialog.successDescription":`O navegador está baixando o ZIP da sessão.`,"dialog.errorTitle":`Falha na exportação da sessão`,"dialog.close":`Fechar`,"dialog.commandFailed":`Não foi possível iniciar a exportação da sessão.`};const inject=[`slots`,`locale`,`contextMenus`];function apply(ctx){const controller=new SessionLogDownloadController;const copyController=new SessionMarkdownCopyController;ctx.provide(`sessionLogDownload`,controller);ctx.effect(()=>async()=>{await controller.dispose()},`session-log-download: browser download lifecycle`);ctx.effect(()=>async()=>{await copyController.dispose()},`session-log-download: browser Markdown copy lifecycle`);ctx.effect(()=>ctx.locale.register(NS,{zh,en,ja,es,fr,de,ru,pt}),`session-log-download: browser dictionaries`);const feedbackAvailable=(0,_unieai_rabi_client_store.createSnapshotStore)(false);ctx.inject([`feedbackUi`],scope=>{scope.effect(()=>{feedbackAvailable.set(true);return()=>{feedbackAvailable.set(false)}},`session-log-download: feedback availability`)});const t=ctx.locale.bind(NS);ctx.slots.inject(`contextMenu.icon`,function*(){for(const[key,Icon]of Object.entries({"session-log-download.copy":_unieai_rabi_client_ui_primitives.IconCopyOutlineRegular,"session-log-download.download":_unieai_rabi_client_ui_primitives.IconDownloadOutlineRegular,"session-log-download.feedback":_unieai_rabi_client_ui_primitives.IconPaperPlaneOutlineRegular}))yield ctx.slots.register({name:`contextMenu.icon`,key},Icon)});ctx.effect(()=>ctx.contextMenus.register({id:`session-log-download.export`,target:`sessionHeader`,order:100,observe:()=>[controller.store,copyController.store,ctx.locale],resolve:({sessionId})=>[{id:`copy`,label:t(`menu.copyMarkdown`),icon:{key:`session-log-download.copy`},disabled:copyController.store.getSnapshot().copying,run:()=>copyController.copy(sessionId)},{id:`download`,label:t(`menu.download`),icon:{key:`session-log-download.download`},disabled:controller.store.getSnapshot().bySession[sessionId]?.status===`downloading`,run:()=>controller.download(sessionId)}]}),`session-log-download: Header exports`);ctx.effect(()=>ctx.contextMenus.register({id:`session-log-download.feedback`,target:`sessionHeader`,order:600,observe:()=>[feedbackAvailable,ctx.locale],resolve:({sessionId})=>feedbackAvailable.getSnapshot()?[{id:`feedback`,label:t(`menu.feedback`),icon:{key:`session-log-download.feedback`},separatorBefore:true,run:()=>{ctx.get(`feedbackUi`)?.openSession(sessionId)}}]:[]}),`session-log-download: Header feedback`);ctx.on(`command/executed`,(sessionId,commandName,result)=>{if(commandName===`export`&&result.kind===`success`)controller.download(sessionId)});ctx.slots.inject(`shell.overlay`,()=>ctx.slots.register({name:`shell.overlay`,id:`session-log-download.copy-toast`,locale:NS,inject:()=>({hooks:{sessionMarkdownCopy:copyController.store},dismiss:()=>{copyController.dismiss()}})},SessionMarkdownCopyToast));ctx.slots.inject(`shell.overlay`,()=>ctx.slots.register({name:`shell.overlay`,id:`session-log-download`,locale:NS,inject:()=>({hooks:{sessionLogDownload:controller.store},dismiss:sessionId=>{controller.dismiss(sessionId)}})},SessionLogDownloadDialog))}exports.apply=apply;exports.inject=inject;return module.exports}});
|