@unieai/rabi-session-log-export 0.0.0-stage → 0.2.1-rc.3

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 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
- # Temporary Holding Version
1
+ # @unieai/rabi-session-log-export
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Web Session-log export command and shared download dialog
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,316 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@unieai/rabi-session-log-export",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let _unieai_rabi_client_store = require("@unieai/rabi-client-store");
8
+ let react_jsx_runtime = require("react/jsx-runtime");
9
+ let react = require("react");
10
+ let _unieai_rabi_client_ui_primitives = require("@unieai/rabi-client-ui-primitives");
11
+ /** Browser-relative form of {@link SESSION_LOG_EXPORT_PATH}. */
12
+ const SESSION_LOG_EXPORT_ROUTE = "/api/session.export".slice(1);
13
+ //#endregion
14
+ //#region lib/types/client/controller.js
15
+ /** Browser download state shared by the Session Header button and `/export`. */
16
+ const INITIAL = { bySession: {} };
17
+ /**
18
+ * Collapse an untrusted Session id into the filename convention owned by the host endpoint.
19
+ * @param sessionId - Session whose archive is downloaded.
20
+ * @returns one safe browser download filename.
21
+ */
22
+ function sessionLogZipFilename(sessionId) {
23
+ return `rabi-session-${String(sessionId).replace(/[^A-Za-z0-9_-]/g, "_")}.zip`;
24
+ }
25
+ /**
26
+ * Hand a Host download route to the browser download manager, which resolves it
27
+ * against the document's own base.
28
+ * @param url - document-relative Host download route.
29
+ * @param filename - browser download filename.
30
+ */
31
+ function downloadUrl(url, filename) {
32
+ const anchor = document.createElement("a");
33
+ anchor.href = url;
34
+ anchor.download = filename;
35
+ anchor.click();
36
+ }
37
+ function messageOf(error) {
38
+ return error instanceof Error ? error.message : String(error);
39
+ }
40
+ /** Owns one in-flight browser download per Session and publishes modal state. */
41
+ var SessionLogDownloadController = class {
42
+ fetcher;
43
+ save;
44
+ /** uSES-safe state source shared by every Session-scoped modal contribution. */
45
+ store = (0, _unieai_rabi_client_store.createSnapshotStore)(INITIAL);
46
+ active = /* @__PURE__ */ new Map();
47
+ disposed = false;
48
+ /**
49
+ * @param fetcher - HTTP carrier used to read the host-streamed ZIP.
50
+ * @param save - browser save operation.
51
+ */
52
+ constructor(fetcher = (input, init) => fetch(input, init), save = downloadUrl) {
53
+ this.fetcher = fetcher;
54
+ this.save = save;
55
+ }
56
+ /**
57
+ * Download one Session tree; concurrent gestures for the same Session share one operation.
58
+ * @param sessionId - root Session whose ZIP includes descendants and attachments.
59
+ * @returns after the browser save starts, an error state is published, or a late post-disposal request is ignored.
60
+ */
61
+ download(sessionId) {
62
+ const existing = this.active.get(sessionId);
63
+ if (existing !== void 0) return existing.done;
64
+ if (this.disposed) return Promise.resolve();
65
+ const abort = new AbortController();
66
+ const done = this.run(sessionId, abort.signal).finally(() => {
67
+ this.active.delete(sessionId);
68
+ });
69
+ this.active.set(sessionId, {
70
+ abort,
71
+ done
72
+ });
73
+ return done;
74
+ }
75
+ /**
76
+ * Close one Session's dialog without cancelling an in-flight browser download.
77
+ * @param sessionId - Session whose modal closes.
78
+ */
79
+ dismiss(sessionId) {
80
+ const current = this.store.getSnapshot().bySession[String(sessionId)];
81
+ if (current === void 0 || !current.open) return;
82
+ this.publish(sessionId, {
83
+ ...current,
84
+ open: false
85
+ });
86
+ }
87
+ /**
88
+ * Abort active fetches and reach quiescence.
89
+ * @returns after every active operation settles.
90
+ */
91
+ async dispose() {
92
+ this.disposed = true;
93
+ const active = [...this.active.values()];
94
+ for (const operation of active) operation.abort.abort();
95
+ await Promise.allSettled(active.map((operation) => operation.done));
96
+ }
97
+ async run(sessionId, signal) {
98
+ this.publish(sessionId, {
99
+ open: true,
100
+ status: "downloading",
101
+ error: null
102
+ });
103
+ try {
104
+ const route = `${SESSION_LOG_EXPORT_ROUTE}?${new URLSearchParams({
105
+ sessionId,
106
+ includeDescendants: "true"
107
+ }).toString()}`;
108
+ const response = await this.fetcher(route, {
109
+ method: "HEAD",
110
+ signal
111
+ });
112
+ if (!response.ok) {
113
+ const detail = await response.text().catch(() => "");
114
+ throw new Error(`Export failed: HTTP ${response.status}${detail === "" ? "" : ` ${detail}`}`);
115
+ }
116
+ this.save(route, sessionLogZipFilename(sessionId));
117
+ const open = this.store.getSnapshot().bySession[String(sessionId)]?.open ?? true;
118
+ this.publish(sessionId, {
119
+ open,
120
+ status: "success",
121
+ error: null
122
+ });
123
+ } catch (error) {
124
+ if (signal.aborted) return;
125
+ const open = this.store.getSnapshot().bySession[String(sessionId)]?.open ?? true;
126
+ this.publish(sessionId, {
127
+ open,
128
+ status: "error",
129
+ error: messageOf(error)
130
+ });
131
+ }
132
+ }
133
+ publish(sessionId, entry) {
134
+ this.store.update((state) => {
135
+ state.bySession = {
136
+ ...state.bySession,
137
+ [String(sessionId)]: entry
138
+ };
139
+ });
140
+ }
141
+ };
142
+ //#endregion
143
+ //#region lib/types/client/Dialog.js
144
+ /**
145
+ * Modal shared by the Session Header download menu item and this browser's `/export` command.
146
+ * @param props - Session runtime, bound controller state, actions, and localized copy.
147
+ * @returns the modal portal contribution.
148
+ */
149
+ function SessionLogDownloadDialog({ sessionId, useSessionLogDownload, dismiss, t }) {
150
+ const entry = useSessionLogDownload((state) => state.bySession[String(sessionId)]);
151
+ const status = entry?.status;
152
+ const open = entry?.open === true;
153
+ const error = status === "error" ? entry?.error || t("dialog.commandFailed") : null;
154
+ return (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Modal, {
155
+ open,
156
+ onClose: () => {
157
+ dismiss(sessionId);
158
+ },
159
+ title: status === "downloading" ? t("dialog.preparingTitle") : status === "success" ? t("dialog.successTitle") : t("dialog.errorTitle"),
160
+ description: status === "downloading" ? t("dialog.preparingDescription") : status === "success" ? t("dialog.successDescription") : error ?? t("dialog.commandFailed"),
161
+ closeLabel: t("dialog.close"),
162
+ footer: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Button, {
163
+ variant: "primary",
164
+ onClick: () => {
165
+ dismiss(sessionId);
166
+ },
167
+ children: t("dialog.close")
168
+ })
169
+ });
170
+ }
171
+ //#endregion
172
+ //#region \0rabi-css:/home/runner/work/rabi-harness/rabi-harness/packages/session-query/session-log-export/src/client/HeaderAction.module.css.mjs
173
+ const css = ".nL4_yW_moreButton{width:28px;color:var(--dsw-alias-label-secondary);flex:none;padding:0}.nL4_yW_moreButton svg{width:15px;height:15px}";
174
+ const tagId = "@unieai/rabi-session-log-export/HeaderAction.module.css";
175
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
176
+ const tag = document.createElement("style");
177
+ tag.dataset.plugin = "@unieai/rabi-session-log-export";
178
+ tag.dataset.pluginCss = tagId;
179
+ tag.textContent = css;
180
+ document.head.appendChild(tag);
181
+ }
182
+ var HeaderAction_module_css_default = { "moreButton": "nL4_yW_moreButton" };
183
+ //#endregion
184
+ //#region lib/types/client/HeaderAction.js
185
+ /**
186
+ * Render the Session Header menu with download and optional feedback actions.
187
+ * @param props - Session runtime, download controller, and localized copy.
188
+ * @returns the persistent Header action and Session-scoped dialog.
189
+ */
190
+ function SessionLogDownloadHeaderAction(props) {
191
+ const { sessionId, useSessionLogDownload, useFeedbackAvailable, request, openFeedback, t } = props;
192
+ const feedbackAvailable = useFeedbackAvailable((value) => value);
193
+ const busy = useSessionLogDownload((state) => state.bySession[String(sessionId)])?.status === "downloading";
194
+ const [open, setOpen] = (0, react.useState)(false);
195
+ return (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Menu, {
196
+ open,
197
+ align: "end",
198
+ dense: true,
199
+ onClose: () => {
200
+ setOpen(false);
201
+ },
202
+ items: [{
203
+ id: "download",
204
+ label: t("menu.download"),
205
+ icon: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.IconDownloadOutlineRegular, {}),
206
+ disabled: busy
207
+ }, ...feedbackAvailable ? [{
208
+ id: "feedback",
209
+ label: t("menu.feedback"),
210
+ icon: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.IconPaperPlaneOutlineRegular, {})
211
+ }] : []],
212
+ onSelect: (id) => {
213
+ setOpen(false);
214
+ if (id === "feedback") openFeedback(sessionId);
215
+ else request(sessionId);
216
+ },
217
+ anchor: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.Button, {
218
+ size: "sm",
219
+ className: HeaderAction_module_css_default.moreButton,
220
+ "aria-label": t("header.more"),
221
+ "aria-haspopup": "menu",
222
+ "aria-expanded": open,
223
+ "aria-busy": busy,
224
+ onClick: () => {
225
+ setOpen((value) => !value);
226
+ },
227
+ children: (0, react_jsx_runtime.jsx)(_unieai_rabi_client_ui_primitives.IconEllipsisOutlineRegular, {})
228
+ })
229
+ }), (0, react_jsx_runtime.jsx)(SessionLogDownloadDialog, { ...props })] });
230
+ }
231
+ //#endregion
232
+ //#region lib/types/client/locales.js
233
+ /** Locale namespace owned by Session export browser feedback. */
234
+ const NS = "session-log-download";
235
+ /** Simplified-Chinese Session export strings. */
236
+ const zh = {
237
+ "header.more": "更多操作",
238
+ "menu.download": "下载 Session 日志",
239
+ "menu.feedback": "反馈",
240
+ "dialog.preparingTitle": "正在导出 Session",
241
+ "dialog.preparingDescription": "正在准备包含当前 Session、子 Session 和附件的 ZIP 文件。",
242
+ "dialog.successTitle": "Session 导出已开始下载",
243
+ "dialog.successDescription": "浏览器正在下载 Session ZIP 文件。",
244
+ "dialog.errorTitle": "Session 导出失败",
245
+ "dialog.close": "关闭",
246
+ "dialog.commandFailed": "无法启动 Session 导出。"
247
+ };
248
+ /** English Session export strings. */
249
+ const en = {
250
+ "header.more": "More actions",
251
+ "menu.download": "Download session log",
252
+ "menu.feedback": "Feedback",
253
+ "dialog.preparingTitle": "Exporting Session",
254
+ "dialog.preparingDescription": "Preparing a ZIP containing this Session, its sub-Sessions, and attachments.",
255
+ "dialog.successTitle": "Session download started",
256
+ "dialog.successDescription": "The browser is downloading the Session ZIP.",
257
+ "dialog.errorTitle": "Session export failed",
258
+ "dialog.close": "Close",
259
+ "dialog.commandFailed": "Could not start the Session export."
260
+ };
261
+ //#endregion
262
+ //#region lib/types/client/index.js
263
+ /** Browser plugin owning Session export download state and its shared modal. */
264
+ const inject = ["slots", "locale"];
265
+ /**
266
+ * Provide the download controller and mount its modal into the Session Header.
267
+ * @param ctx - browser context carrying slots and locale services.
268
+ */
269
+ function apply(ctx) {
270
+ const controller = new SessionLogDownloadController();
271
+ ctx.provide("sessionLogDownload", controller);
272
+ ctx.effect(() => async () => {
273
+ await controller.dispose();
274
+ }, "session-log-download: browser download lifecycle");
275
+ ctx.effect(() => ctx.locale.register(NS, {
276
+ zh,
277
+ en
278
+ }), "session-log-download: browser dictionaries");
279
+ const feedbackAvailable = (0, _unieai_rabi_client_store.createSnapshotStore)(false);
280
+ ctx.inject(["feedbackUi"], (scope) => {
281
+ scope.effect(() => {
282
+ feedbackAvailable.set(true);
283
+ return () => {
284
+ feedbackAvailable.set(false);
285
+ };
286
+ }, "session-log-download: feedback availability");
287
+ });
288
+ ctx.on("command/executed", (sessionId, commandName, result) => {
289
+ if (commandName === "export" && result.kind === "success") controller.download(sessionId);
290
+ });
291
+ ctx.slots.inject("conversation.session.header.utilities", () => ctx.slots.register({
292
+ name: "conversation.session.header.utilities",
293
+ id: "session-log-download",
294
+ locale: NS,
295
+ inject: () => ({
296
+ hooks: {
297
+ sessionLogDownload: controller.store,
298
+ feedbackAvailable
299
+ },
300
+ request: (sessionId) => controller.download(sessionId),
301
+ dismiss: (sessionId) => {
302
+ controller.dismiss(sessionId);
303
+ },
304
+ openFeedback: (sessionId) => {
305
+ ctx.get("feedbackUi")?.openSession(sessionId);
306
+ }
307
+ })
308
+ }, SessionLogDownloadHeaderAction));
309
+ }
310
+ //#endregion
311
+ exports.apply = apply;
312
+ exports.inject = inject;
313
+ return module.exports;
314
+ }
315
+ });
316
+
package/lib/index.js ADDED
@@ -0,0 +1,565 @@
1
+ import Schema from "@unieai/schemastery";
2
+ import { brandString } from "@unieai/rabi-brand";
3
+ import { Zip, ZipDeflate } from "fflate";
4
+ import { SESSION_FORMAT_VERSION } from "@unieai/rabi-session";
5
+ import { sessionFormatLogFilename } from "@unieai/rabi-session-format";
6
+ import { SessionPersistenceNotFoundError } from "@unieai/rabi-session-persistence";
7
+ //#region lib/types/archive.js
8
+ /**
9
+ * Host-side session-log download: streams one ZIP archive whose files are the
10
+ * sessions' logical session logs plus every referenced attachment. Each log
11
+ * is read through a persistence read handle and serialized here as canonical
12
+ * JSONL — one header line, then one line per validated event — so every
13
+ * backend (JSONL, SQLite, future) exports identically. The root log uses the
14
+ * current generation's canonical `session[.vN].jsonl` name; each subagent
15
+ * descendant uses `subagents/<id>/session[.vN].jsonl`; each image referenced by any included log
16
+ * under `media/<attachmentId>.<ext>` (content-addressed, so one archive never
17
+ * duplicates a shared image); each generic file sits under
18
+ * `files/<prefix>/<digest>/<name>` and streams from the attachment store. No
19
+ * manifest is written. Before each live session's log read, the SessionStore
20
+ * flush barrier makes the current in-memory log durable; cold sessions need no
21
+ * barrier. Request abort and response-consumer cancellation share one producer
22
+ * signal and terminate the active compressor.
23
+ * Compression runs on the host with fflate's streaming Zip API, so the archive
24
+ * bytes are produced incrementally and the host never holds the whole archive
25
+ * in one buffer; production waits for consumer pull whenever the response queue
26
+ * reaches its byte high-water mark, so a slow consumer bounds accumulation to
27
+ * the fixed 64 KiB response queue plus one synchronous fflate push.
28
+ * @module
29
+ */
30
+ /** Balanced default used when Session export configuration omits a compression level. */
31
+ const DEFAULT_SESSION_LOG_COMPRESSION_LEVEL = 6;
32
+ /**
33
+ * Resolve the persistence, session-query, and attachment services a log export needs.
34
+ * @param ctx - the composed host context.
35
+ * @returns the export services (absent when the deployment does not mount them).
36
+ */
37
+ function sessionLogExportDeps(ctx) {
38
+ return {
39
+ sessionQuery: ctx.get("sessionQuery"),
40
+ sessionPersistence: ctx.get("sessionPersistence"),
41
+ attachments: ctx.get("attachments"),
42
+ sessions: ctx.get("sessions")
43
+ };
44
+ }
45
+ /**
46
+ * Flush one currently live session through the store's authoritative durability
47
+ * barrier immediately before its logical log is read. A cold or absent id has
48
+ * no in-memory work to flush.
49
+ * @param deps - export services, including the optional live-session store.
50
+ * @param id - the session whose artifact is about to be read.
51
+ * @param signal - optional cancellation observed around the flush barrier.
52
+ */
53
+ async function flushLiveSessionLog(deps, id, signal) {
54
+ signal?.throwIfAborted();
55
+ const sessions = deps.sessions;
56
+ if (sessions === void 0) return;
57
+ const session = sessions.get(id);
58
+ if (session === void 0) return;
59
+ await sessions.flush(session);
60
+ signal?.throwIfAborted();
61
+ }
62
+ /** The current generation's canonical base filename for every exported session log. */
63
+ const SESSION_LOG_FILENAME = sessionFormatLogFilename(SESSION_FORMAT_VERSION);
64
+ /**
65
+ * Serialize one session's logical log as canonical JSONL text: the header
66
+ * line, then one line per event, with a trailing newline.
67
+ * @param header - the session's immutable header.
68
+ * @param events - the validated committed events in seq order.
69
+ * @returns the JSONL text.
70
+ */
71
+ function serializeSessionLog(header, events) {
72
+ const lines = [JSON.stringify({
73
+ type: "session",
74
+ version: header.version,
75
+ id: header.id,
76
+ createdAt: header.createdAt,
77
+ ...header.cwd !== void 0 ? { cwd: header.cwd } : {},
78
+ ...header.parentSession !== void 0 ? { parentSession: header.parentSession } : {},
79
+ isSeeded: header.isSeeded,
80
+ ...header.origin !== void 0 ? { origin: header.origin } : {},
81
+ delegationDepth: header.delegationDepth ?? 0,
82
+ ...header.agentPreset !== void 0 ? { agentPreset: header.agentPreset } : {}
83
+ })];
84
+ for (const event of events) lines.push(JSON.stringify(event));
85
+ return `${lines.join("\n")}\n`;
86
+ }
87
+ /**
88
+ * Read one session's complete logical log through a read handle and serialize
89
+ * it. The read observes the committed log only — persistence never returns a
90
+ * torn tail — and a handle read after a resolved flush observes at least the
91
+ * flushed prefix.
92
+ * @param persistence - the mounted persistence backend.
93
+ * @param id - the session to read.
94
+ * @param signal - optional cancellation forwarded to the open and read.
95
+ * @returns the serialized JSONL text, or `undefined` when the session does not exist.
96
+ */
97
+ async function readSessionLogText(persistence, id, signal) {
98
+ const options = signal === void 0 ? {} : { signal };
99
+ let handle;
100
+ try {
101
+ handle = await persistence.open(id, "read", options);
102
+ } catch (error) {
103
+ if (error instanceof SessionPersistenceNotFoundError) return void 0;
104
+ throw error;
105
+ }
106
+ try {
107
+ const { events } = await handle.read(0, void 0, options);
108
+ return serializeSessionLog(handle.header, events);
109
+ } finally {
110
+ await handle.close();
111
+ }
112
+ }
113
+ /** Zip extension for each accepted raster media type. */
114
+ const MEDIA_TYPE_EXTENSIONS = {
115
+ "image/png": "png",
116
+ "image/jpeg": "jpg",
117
+ "image/webp": "webp",
118
+ "image/gif": "gif"
119
+ };
120
+ /**
121
+ * The zip path for one media object: content-addressed by the opaque
122
+ * attachment id so shared images land once and the id in the log maps back to
123
+ * the archive entry without a manifest.
124
+ * @param ref - the durable reference from a session log.
125
+ * @returns the archive path.
126
+ */
127
+ function mediaEntryPath(ref) {
128
+ return `media/${String(ref.attachmentId)}.${MEDIA_TYPE_EXTENSIONS[ref.mediaType]}`;
129
+ }
130
+ /** Archive path that preserves one stored file reference's digest and name. */
131
+ function fileEntryPath(ref) {
132
+ const digest = String(ref.attachmentId).replace(/^sha256:/u, "");
133
+ const name = ref.name.replace(/[\\/\u0000-\u001f\u007f]/gu, "_");
134
+ const safeName = name === "." || name === ".." || name === "" ? "file" : name;
135
+ return `files/${digest.slice(0, 2)}/${digest}/${safeName}`;
136
+ }
137
+ /**
138
+ * Collect direct attachment blocks from one declared V4 content array.
139
+ * @param content - an event or message content array.
140
+ * @param images - image dedupe map keyed by attachment id.
141
+ * @param files - file dedupe map keyed by attachment id and stored name.
142
+ */
143
+ function collectAttachmentRefs(content, images, files) {
144
+ if (!Array.isArray(content)) return;
145
+ for (const value of content) {
146
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
147
+ const block = value;
148
+ if (block.type === "image" && typeof block.attachment === "object" && block.attachment !== null) {
149
+ const ref = block.attachment;
150
+ images.set(String(ref.attachmentId), ref);
151
+ }
152
+ if (block.type === "file" && typeof block.attachment === "object" && block.attachment !== null) {
153
+ const ref = block.attachment;
154
+ files.set(`${String(ref.attachmentId)}\u0000${ref.name}`, ref);
155
+ }
156
+ }
157
+ }
158
+ /**
159
+ * Collect references only from declared first-party content fields and completed
160
+ * Assistant blocks. Unknown events and unrelated payload fields remain opaque.
161
+ * @param event - one parsed JSONL event object.
162
+ * @param images - image dedupe map keyed by attachment id.
163
+ * @param files - file dedupe map keyed by attachment id and stored name.
164
+ */
165
+ function collectEventAttachmentRefs(event, images, files) {
166
+ if (typeof event !== "object" || event === null || Array.isArray(event)) return;
167
+ const row = event;
168
+ const data = row.data;
169
+ if (typeof data !== "object" || data === null) return;
170
+ const carrier = data;
171
+ switch (row.type) {
172
+ case "user/message":
173
+ case "tool/ptc-dispatch":
174
+ collectAttachmentRefs(carrier.content, images, files);
175
+ return;
176
+ case "system/message":
177
+ case "developer/message":
178
+ case "tool/result":
179
+ case "team/message/queued":
180
+ collectAttachmentRefs(carrier.message?.content, images, files);
181
+ return;
182
+ case "agent/inbox/spliced": {
183
+ const messages = carrier.inserted;
184
+ if (!Array.isArray(messages)) return;
185
+ for (const message of messages) {
186
+ if (typeof message !== "object" || message === null || Array.isArray(message)) continue;
187
+ collectAttachmentRefs(message.content, images, files);
188
+ }
189
+ return;
190
+ }
191
+ case "compaction/summary":
192
+ collectAttachmentRefs(carrier.summary, images, files);
193
+ collectAttachmentRefs(carrier.rawOutput, images, files);
194
+ return;
195
+ case "assistant/message":
196
+ collectAttachmentRefs(carrier.message?.content, images, files);
197
+ break;
198
+ case "assistant/attempt": break;
199
+ default: return;
200
+ }
201
+ if (carrier.stream !== void 0) {
202
+ for (const record of carrier.stream) if (record.type === "chunk" && record.chunk?.type === "block-end") collectAttachmentRefs([record.chunk.block], images, files);
203
+ }
204
+ }
205
+ /**
206
+ * Collect the distinct attachment references one stored artifact text names.
207
+ * Lines that fail to parse cannot reference attachments and are skipped (the
208
+ * artifact text itself is exported verbatim regardless).
209
+ * @param content - the stored artifact text.
210
+ * @returns image and file dedupe maps.
211
+ */
212
+ function attachmentRefsInArtifact(content) {
213
+ const images = /* @__PURE__ */ new Map();
214
+ const files = /* @__PURE__ */ new Map();
215
+ for (const line of content.split("\n")) {
216
+ if (line === "") continue;
217
+ let event;
218
+ try {
219
+ event = JSON.parse(line);
220
+ } catch {
221
+ continue;
222
+ }
223
+ collectEventAttachmentRefs(event, images, files);
224
+ }
225
+ return {
226
+ images,
227
+ files
228
+ };
229
+ }
230
+ /**
231
+ * One safe zip path segment from an untrusted session id. Session ids are
232
+ * host-controlled, but the brand allows any non-empty string, so `../`, dot
233
+ * segments, and separator characters are neutralized before they can shape
234
+ * archive entries. Distinct ids may collapse onto one segment (id collision
235
+ * is impossible for the host-minted UUIDs, so no uniqueness suffix is kept).
236
+ * @param id - the raw session id.
237
+ * @returns a filesystem-safe single path segment.
238
+ */
239
+ function safeSessionIdSegment(id) {
240
+ return id.replace(/[^A-Za-z0-9_-]/g, "_");
241
+ }
242
+ /**
243
+ * The export archive filename for one root session.
244
+ * @param sessionId - the root session id (sanitized to one safe path segment).
245
+ * @returns the attachment filename for the session's export archive.
246
+ */
247
+ function sessionLogZipFilename(sessionId) {
248
+ return `rabi-session-${safeSessionIdSegment(sessionId)}.zip`;
249
+ }
250
+ /**
251
+ * Yield the export entries in zip order: the preloaded root log first, then
252
+ * every subagent descendant in lineage order (each flushed when live, read
253
+ * through a persistence read handle right before it is yielded, and dropped
254
+ * after the consumer moves on), then every distinct attachment referenced by
255
+ * the included logs. Images are read and verified as bounded stored objects;
256
+ * generic files remain streamed through the ZIP writer. The host holds at most
257
+ * one descendant log, one image, and one file chunk beyond the root.
258
+ * @param deps - the mounted export services (the caller answered 500 before this runs).
259
+ * @param rootContent - the already-serialized root log (read by the caller so
260
+ * the missing-session path can answer cleanly before streaming starts).
261
+ * @param sessionId - the root session id.
262
+ * @param includeDescendants - whether to include every subagent descendant.
263
+ * @param signal - optional cancellation forwarded to lineage, persistence, and attachment reads.
264
+ * @returns the export entries in zip order.
265
+ */
266
+ async function* sessionLogZipEntries(deps, rootContent, sessionId, includeDescendants, signal) {
267
+ const media = /* @__PURE__ */ new Map();
268
+ const files = /* @__PURE__ */ new Map();
269
+ const rememberAttachments = (content) => {
270
+ const refs = attachmentRefsInArtifact(content);
271
+ for (const [id, ref] of refs.images) media.set(id, ref);
272
+ for (const [id, ref] of refs.files) files.set(id, ref);
273
+ };
274
+ rememberAttachments(rootContent);
275
+ yield {
276
+ path: SESSION_LOG_FILENAME,
277
+ content: rootContent
278
+ };
279
+ if (includeDescendants) {
280
+ const seen = new Set([sessionId]);
281
+ const collect = async function* (nodes) {
282
+ for (const node of nodes) {
283
+ signal?.throwIfAborted();
284
+ const id = node.session.header.id;
285
+ if (seen.has(id)) continue;
286
+ seen.add(id);
287
+ await flushLiveSessionLog(deps, id, signal);
288
+ const content = await readSessionLogText(deps.sessionPersistence, id, signal);
289
+ signal?.throwIfAborted();
290
+ if (content === void 0) throw new Error(`subagent "${id}" has no stored log`);
291
+ rememberAttachments(content);
292
+ yield {
293
+ path: `subagents/${safeSessionIdSegment(id)}/${SESSION_LOG_FILENAME}`,
294
+ content
295
+ };
296
+ yield* collect(node.descendants);
297
+ }
298
+ };
299
+ const lineage = await deps.sessionQuery.traceSession(sessionId, signal);
300
+ signal?.throwIfAborted();
301
+ yield* collect(lineage.descendants);
302
+ }
303
+ for (const ref of media.values()) {
304
+ signal?.throwIfAborted();
305
+ const stored = await deps.attachments.readImage(ref, signal);
306
+ signal?.throwIfAborted();
307
+ yield {
308
+ path: mediaEntryPath(ref),
309
+ data: stored.data
310
+ };
311
+ }
312
+ for (const ref of files.values()) {
313
+ signal?.throwIfAborted();
314
+ yield {
315
+ path: fileEntryPath(ref),
316
+ chunks: deps.attachments.readFileStream(ref, signal)
317
+ };
318
+ }
319
+ }
320
+ /** How many code units of Session-log text one zip push carries (bounded encode memory). */
321
+ const PUSH_CHUNK_CODE_UNITS = 65536;
322
+ /** How many bytes of media one zip push carries (bounded memory; images are already size-capped). */
323
+ const PUSH_CHUNK_BYTES = 65536;
324
+ /** Byte capacity retained by the response stream before ZIP production waits for pull. */
325
+ const RESPONSE_HIGH_WATER_MARK_BYTES = 65536;
326
+ /** One producer waiter released only when ReadableStream pull restores capacity. */
327
+ var ResponseCapacityGate = class {
328
+ releasePending;
329
+ /**
330
+ * Wait until the response queue has positive byte capacity or cancellation wins.
331
+ * @param controller - response controller whose desired size owns capacity.
332
+ * @param signal - combined request/consumer cancellation.
333
+ */
334
+ async wait(controller, signal) {
335
+ signal.throwIfAborted();
336
+ if (controller.desiredSize === null || controller.desiredSize > 0) return;
337
+ await new Promise((resolve) => {
338
+ const release = () => {
339
+ this.releasePending = void 0;
340
+ signal.removeEventListener("abort", release);
341
+ resolve();
342
+ };
343
+ this.releasePending = release;
344
+ signal.addEventListener("abort", release, { once: true });
345
+ });
346
+ signal.throwIfAborted();
347
+ }
348
+ /** Release the current producer waiter after a consumer pull. */
349
+ pulled() {
350
+ this.releasePending?.();
351
+ }
352
+ };
353
+ /**
354
+ * Push one media object's bytes into a deflate stream in bounded chunks,
355
+ * waiting for consumer capacity between chunks like the artifact path does.
356
+ * @param deflate - the zip entry's deflate stream.
357
+ * @param data - the stored image bytes.
358
+ * @param controller - response queue controller.
359
+ * @param capacity - pull-driven response-capacity gate.
360
+ * @param signal - cancellation; throws when aborted.
361
+ */
362
+ async function pushBinaryChunks(deflate, data, controller, capacity, signal) {
363
+ let offset = 0;
364
+ do {
365
+ signal.throwIfAborted();
366
+ const end = Math.min(offset + PUSH_CHUNK_BYTES, data.byteLength);
367
+ const finalChunk = end >= data.byteLength;
368
+ deflate.push(data.subarray(offset, end), finalChunk);
369
+ offset = end;
370
+ await capacity.wait(controller, signal);
371
+ } while (offset < data.byteLength);
372
+ }
373
+ /** Push one streamed file entry without retaining its complete byte sequence. */
374
+ async function pushStreamChunks(deflate, chunks, controller, capacity, signal) {
375
+ for await (const chunk of chunks) {
376
+ signal.throwIfAborted();
377
+ if (chunk.byteLength === 0) continue;
378
+ deflate.push(chunk, false);
379
+ await capacity.wait(controller, signal);
380
+ }
381
+ signal.throwIfAborted();
382
+ deflate.push(new Uint8Array(), true);
383
+ await capacity.wait(controller, signal);
384
+ }
385
+ /**
386
+ * Push one artifact's text into a deflate stream in bounded chunks, never
387
+ * splitting a surrogate pair across a chunk boundary (a lone high surrogate
388
+ * re-encodes as U+FFFD and would silently corrupt the exported artifact).
389
+ * @param deflate - the zip entry's deflate stream.
390
+ * @param content - the canonical Session-log text.
391
+ * @param controller - response queue controller.
392
+ * @param capacity - pull-driven response-capacity gate.
393
+ * @param signal - cancellation; throws when aborted.
394
+ */
395
+ async function pushArtifactChunks(deflate, content, controller, capacity, signal) {
396
+ const encoder = new TextEncoder();
397
+ let offset = 0;
398
+ let finalChunk;
399
+ do {
400
+ signal.throwIfAborted();
401
+ let end = Math.min(offset + PUSH_CHUNK_CODE_UNITS, content.length);
402
+ if (end < content.length && end - offset > 1) {
403
+ const last = content.charCodeAt(end - 1);
404
+ if (last >= 55296 && last <= 56319) end -= 1;
405
+ }
406
+ finalChunk = end >= content.length;
407
+ deflate.push(encoder.encode(content.slice(offset, end)), finalChunk);
408
+ offset = end;
409
+ await capacity.wait(controller, signal);
410
+ } while (!finalChunk);
411
+ }
412
+ /**
413
+ * Stream one session-log ZIP as a WHATWG ReadableStream. The root log is read
414
+ * and serialized by the caller before this is called (a missing root or
415
+ * missing services answer cleanly before any byte is produced); each entry is
416
+ * then encoded and deflated in bounded chunks as it is produced, so the
417
+ * archive bytes arrive incrementally. A descendant that fails to read errors
418
+ * the stream (fail-loud, never silent under-export).
419
+ * @param deps - the mounted export services (the caller answered 500 before this runs).
420
+ * @param rootContent - the already-serialized root log (first zip entry).
421
+ * @param sessionId - the root session id.
422
+ * @param includeDescendants - whether to include every subagent descendant.
423
+ * @param compressionLevel - validated fflate DEFLATE level for every ZIP entry.
424
+ * @param signal - request cancellation combined with response-consumer cancellation.
425
+ * @returns the zip byte stream.
426
+ */
427
+ function streamSessionLogZip(deps, rootContent, sessionId, includeDescendants, compressionLevel, signal) {
428
+ const consumerAbort = new AbortController();
429
+ const producerSignal = AbortSignal.any([signal, consumerAbort.signal]);
430
+ let zip;
431
+ let zipTerminated = false;
432
+ const capacity = new ResponseCapacityGate();
433
+ const terminateZip = () => {
434
+ if (zip === void 0 || zipTerminated) return;
435
+ zipTerminated = true;
436
+ zip.terminate();
437
+ };
438
+ return new ReadableStream({
439
+ start(controller) {
440
+ const archive = new Zip((error, data, final) => {
441
+ /* v8 ignore next 3 -- fflate reports only internal zip failures, unreachable for valid inputs */
442
+ if (error) {
443
+ controller.error(error);
444
+ return;
445
+ }
446
+ /* v8 ignore next -- fflate may emit empty chunks; not controllable from tests */
447
+ if (data.byteLength > 0) controller.enqueue(data);
448
+ if (final) controller.close();
449
+ });
450
+ zip = archive;
451
+ (async () => {
452
+ try {
453
+ for await (const entry of sessionLogZipEntries(deps, rootContent, sessionId, includeDescendants, producerSignal)) {
454
+ const deflate = new ZipDeflate(entry.path, { level: compressionLevel });
455
+ archive.add(deflate);
456
+ if ("content" in entry) await pushArtifactChunks(deflate, entry.content, controller, capacity, producerSignal);
457
+ else if ("data" in entry) await pushBinaryChunks(deflate, entry.data, controller, capacity, producerSignal);
458
+ else await pushStreamChunks(deflate, entry.chunks, controller, capacity, producerSignal);
459
+ }
460
+ archive.end();
461
+ } catch (error) {
462
+ /* v8 ignore next -- typed backends reject with Error, and DOMException is one in Node */
463
+ terminateZip();
464
+ controller.error(error instanceof Error ? error : new Error(String(error)));
465
+ }
466
+ })();
467
+ },
468
+ pull() {
469
+ capacity.pulled();
470
+ },
471
+ cancel(reason) {
472
+ consumerAbort.abort(reason instanceof Error ? reason : /* @__PURE__ */ new Error("session log export stream cancelled"));
473
+ terminateZip();
474
+ }
475
+ }, {
476
+ highWaterMark: RESPONSE_HIGH_WATER_MARK_BYTES,
477
+ size: (chunk) => chunk.byteLength
478
+ });
479
+ }
480
+ //#endregion
481
+ //#region lib/types/routes.js
482
+ /**
483
+ * The absolute pathname the Host registers the export under and the
484
+ * document-relative form the browser addresses; see
485
+ * .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
486
+ */
487
+ /** Absolute registration path for the ZIP download route. */
488
+ const SESSION_LOG_EXPORT_PATH = "/api/session.export";
489
+ SESSION_LOG_EXPORT_PATH.slice(1);
490
+ //#endregion
491
+ //#region lib/types/index.js
492
+ /** Session-log download command and Host-owned streaming route. */
493
+ const name = "session-log-download";
494
+ const inject = ["commands", "connection"];
495
+ /** Validate Session-log archive configuration. */
496
+ const Config = Schema.object({ compressionLevel: Schema.number().step(1).min(0).max(9).default(6) });
497
+ const REQUESTED = {
498
+ kind: "success",
499
+ text: "Session log download requested."
500
+ };
501
+ /**
502
+ * Register the Web-only `/export` command and authenticated ZIP download route.
503
+ * @param ctx - Host context carrying the human-command registry.
504
+ * @param config - resolved compression policy.
505
+ */
506
+ function apply(ctx, config = {}) {
507
+ ctx.effect(() => ctx.commands.register({
508
+ definitionId: brandString("@unieai/rabi-session-log-export"),
509
+ name: "export",
510
+ description: "Download this Session log as a ZIP archive",
511
+ handler: (invocation) => Promise.resolve(invocation.rawInput.trim() === "" ? REQUESTED : {
512
+ kind: "error",
513
+ text: "The Web /export command does not accept a path."
514
+ })
515
+ }), "session-log-download: command");
516
+ connectionOf(ctx).fetch.register({
517
+ path: SESSION_LOG_EXPORT_PATH,
518
+ methods: ["GET", "HEAD"],
519
+ requestBody: "buffered",
520
+ fetch: async (request) => {
521
+ const response = await sessionLogExportResponse(ctx, request, config.compressionLevel ?? 6);
522
+ if (request.method === "GET") return response;
523
+ await response.body?.cancel();
524
+ return new Response(null, {
525
+ status: response.status,
526
+ headers: response.headers
527
+ });
528
+ }
529
+ });
530
+ }
531
+ function connectionOf(ctx) {
532
+ return Reflect.get(ctx, "connection");
533
+ }
534
+ async function sessionLogExportResponse(ctx, request, compressionLevel) {
535
+ const url = new URL(request.url);
536
+ const query = Object.fromEntries(url.searchParams);
537
+ const sessionIdValue = query["sessionId"];
538
+ const descendantsValue = query["includeDescendants"];
539
+ if (sessionIdValue === void 0 || sessionIdValue.length === 0 || descendantsValue !== void 0 && descendantsValue !== "true" && descendantsValue !== "false") return new Response("missing or invalid sessionId query parameter", { status: 400 });
540
+ const sessionId = brandString(sessionIdValue);
541
+ const deps = sessionLogExportDeps(ctx);
542
+ if (deps.sessionQuery === void 0 || deps.sessionPersistence === void 0 || deps.attachments === void 0) return new Response("session log export is unavailable: missing session-query, session-persistence, or attachments service", { status: 500 });
543
+ const ready = {
544
+ sessionQuery: deps.sessionQuery,
545
+ sessionPersistence: deps.sessionPersistence,
546
+ attachments: deps.attachments,
547
+ sessions: deps.sessions
548
+ };
549
+ let rootContent;
550
+ try {
551
+ await flushLiveSessionLog(deps, sessionId, request.signal);
552
+ rootContent = await readSessionLogText(deps.sessionPersistence, sessionId, request.signal);
553
+ request.signal.throwIfAborted();
554
+ } catch {
555
+ request.signal.throwIfAborted();
556
+ return new Response("session log export failed to read the stored log", { status: 500 });
557
+ }
558
+ if (rootContent === void 0) return new Response("session not found", { status: 404 });
559
+ return new Response(streamSessionLogZip(ready, rootContent, sessionId, descendantsValue === "true", compressionLevel, request.signal), { headers: {
560
+ "content-type": "application/zip",
561
+ "content-disposition": `attachment; filename="${sessionLogZipFilename(sessionId)}"`
562
+ } });
563
+ }
564
+ //#endregion
565
+ export { Config, DEFAULT_SESSION_LOG_COMPRESSION_LEVEL, SESSION_LOG_EXPORT_PATH, SESSION_LOG_FILENAME, apply, flushLiveSessionLog, inject, name, readSessionLogText, serializeSessionLog, sessionLogExportDeps, sessionLogZipEntries, sessionLogZipFilename, streamSessionLogZip };
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Host-side session-log download: streams one ZIP archive whose files are the
3
+ * sessions' logical session logs plus every referenced attachment. Each log
4
+ * is read through a persistence read handle and serialized here as canonical
5
+ * JSONL — one header line, then one line per validated event — so every
6
+ * backend (JSONL, SQLite, future) exports identically. The root log uses the
7
+ * current generation's canonical `session[.vN].jsonl` name; each subagent
8
+ * descendant uses `subagents/<id>/session[.vN].jsonl`; each image referenced by any included log
9
+ * under `media/<attachmentId>.<ext>` (content-addressed, so one archive never
10
+ * duplicates a shared image); each generic file sits under
11
+ * `files/<prefix>/<digest>/<name>` and streams from the attachment store. No
12
+ * manifest is written. Before each live session's log read, the SessionStore
13
+ * flush barrier makes the current in-memory log durable; cold sessions need no
14
+ * barrier. Request abort and response-consumer cancellation share one producer
15
+ * signal and terminate the active compressor.
16
+ * Compression runs on the host with fflate's streaming Zip API, so the archive
17
+ * bytes are produced incrementally and the host never holds the whole archive
18
+ * in one buffer; production waits for consumer pull whenever the response queue
19
+ * reaches its byte high-water mark, so a slow consumer bounds accumulation to
20
+ * the fixed 64 KiB response queue plus one synchronous fflate push.
21
+ * @module
22
+ */
23
+ import type { Context } from '@unieai/cordis';
24
+ import type { AttachmentStore } from '@unieai/rabi-attachment';
25
+ import type { SessionQueryEngine } from '@unieai/rabi-session-query';
26
+ import type { SessionEvent, SessionHeader, SessionId, SessionStore } from '@unieai/rabi-session';
27
+ import type { SessionPersistence } from '@unieai/rabi-session-persistence';
28
+ /** Valid fflate DEFLATE levels accepted by session-log export. */
29
+ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
30
+ /** Balanced default used when Session export configuration omits a compression level. */
31
+ export declare const DEFAULT_SESSION_LOG_COMPRESSION_LEVEL: SessionLogCompressionLevel;
32
+ /** The services a session-log export needs (the live-session store is optional). */
33
+ export interface SessionLogExportDeps {
34
+ readonly sessionQuery: SessionQueryEngine | undefined;
35
+ readonly sessionPersistence: SessionPersistence | undefined;
36
+ readonly attachments: AttachmentStore | undefined;
37
+ readonly sessions: SessionStore | undefined;
38
+ }
39
+ /** The export services narrowed to the mounted ones streaming actually reads. */
40
+ export interface SessionLogExportReady {
41
+ readonly sessionQuery: SessionQueryEngine;
42
+ readonly sessionPersistence: SessionPersistence;
43
+ readonly attachments: AttachmentStore;
44
+ readonly sessions: SessionStore | undefined;
45
+ }
46
+ /**
47
+ * Resolve the persistence, session-query, and attachment services a log export needs.
48
+ * @param ctx - the composed host context.
49
+ * @returns the export services (absent when the deployment does not mount them).
50
+ */
51
+ export declare function sessionLogExportDeps(ctx: Context): SessionLogExportDeps;
52
+ /**
53
+ * Flush one currently live session through the store's authoritative durability
54
+ * barrier immediately before its logical log is read. A cold or absent id has
55
+ * no in-memory work to flush.
56
+ * @param deps - export services, including the optional live-session store.
57
+ * @param id - the session whose artifact is about to be read.
58
+ * @param signal - optional cancellation observed around the flush barrier.
59
+ */
60
+ export declare function flushLiveSessionLog(deps: Pick<SessionLogExportDeps, 'sessions'>, id: SessionId, signal?: AbortSignal): Promise<void>;
61
+ /** One exported file: a serialized session log or one referenced attachment object. */
62
+ export type SessionLogZipEntry = {
63
+ readonly path: string;
64
+ readonly content: string;
65
+ } | {
66
+ readonly path: string;
67
+ readonly data: Uint8Array;
68
+ } | {
69
+ readonly path: string;
70
+ readonly chunks: AsyncIterable<Uint8Array>;
71
+ };
72
+ /** The current generation's canonical base filename for every exported session log. */
73
+ export declare const SESSION_LOG_FILENAME: string;
74
+ /**
75
+ * Serialize one session's logical log as canonical JSONL text: the header
76
+ * line, then one line per event, with a trailing newline.
77
+ * @param header - the session's immutable header.
78
+ * @param events - the validated committed events in seq order.
79
+ * @returns the JSONL text.
80
+ */
81
+ export declare function serializeSessionLog(header: SessionHeader, events: readonly SessionEvent[]): string;
82
+ /**
83
+ * Read one session's complete logical log through a read handle and serialize
84
+ * it. The read observes the committed log only — persistence never returns a
85
+ * torn tail — and a handle read after a resolved flush observes at least the
86
+ * flushed prefix.
87
+ * @param persistence - the mounted persistence backend.
88
+ * @param id - the session to read.
89
+ * @param signal - optional cancellation forwarded to the open and read.
90
+ * @returns the serialized JSONL text, or `undefined` when the session does not exist.
91
+ */
92
+ export declare function readSessionLogText(persistence: SessionPersistence, id: SessionId, signal?: AbortSignal): Promise<string | undefined>;
93
+ /**
94
+ * The export archive filename for one root session.
95
+ * @param sessionId - the root session id (sanitized to one safe path segment).
96
+ * @returns the attachment filename for the session's export archive.
97
+ */
98
+ export declare function sessionLogZipFilename(sessionId: string): string;
99
+ /**
100
+ * Yield the export entries in zip order: the preloaded root log first, then
101
+ * every subagent descendant in lineage order (each flushed when live, read
102
+ * through a persistence read handle right before it is yielded, and dropped
103
+ * after the consumer moves on), then every distinct attachment referenced by
104
+ * the included logs. Images are read and verified as bounded stored objects;
105
+ * generic files remain streamed through the ZIP writer. The host holds at most
106
+ * one descendant log, one image, and one file chunk beyond the root.
107
+ * @param deps - the mounted export services (the caller answered 500 before this runs).
108
+ * @param rootContent - the already-serialized root log (read by the caller so
109
+ * the missing-session path can answer cleanly before streaming starts).
110
+ * @param sessionId - the root session id.
111
+ * @param includeDescendants - whether to include every subagent descendant.
112
+ * @param signal - optional cancellation forwarded to lineage, persistence, and attachment reads.
113
+ * @returns the export entries in zip order.
114
+ */
115
+ export declare function sessionLogZipEntries(deps: SessionLogExportReady, rootContent: string, sessionId: SessionId, includeDescendants: boolean, signal?: AbortSignal): AsyncGenerator<SessionLogZipEntry>;
116
+ /**
117
+ * Stream one session-log ZIP as a WHATWG ReadableStream. The root log is read
118
+ * and serialized by the caller before this is called (a missing root or
119
+ * missing services answer cleanly before any byte is produced); each entry is
120
+ * then encoded and deflated in bounded chunks as it is produced, so the
121
+ * archive bytes arrive incrementally. A descendant that fails to read errors
122
+ * the stream (fail-loud, never silent under-export).
123
+ * @param deps - the mounted export services (the caller answered 500 before this runs).
124
+ * @param rootContent - the already-serialized root log (first zip entry).
125
+ * @param sessionId - the root session id.
126
+ * @param includeDescendants - whether to include every subagent descendant.
127
+ * @param compressionLevel - validated fflate DEFLATE level for every ZIP entry.
128
+ * @param signal - request cancellation combined with response-consumer cancellation.
129
+ * @returns the zip byte stream.
130
+ */
131
+ export declare function streamSessionLogZip(deps: SessionLogExportReady, rootContent: string, sessionId: SessionId, includeDescendants: boolean, compressionLevel: SessionLogCompressionLevel, signal: AbortSignal): ReadableStream<Uint8Array>;
132
+ //# sourceMappingURL=archive.d.ts.map
@@ -0,0 +1,21 @@
1
+ import type { ObservableSnapshot } from '@unieai/rabi-client-store';
2
+ import type { SessionId } from '@unieai/rabi-session/types';
3
+ import type { InjectFace, PropsLocale, PropsRuntime } from '@unieai/rabi-client-ui-slots';
4
+ import type { SessionLogDownloadState } from './controller.ts';
5
+ import { NS } from './locales.ts';
6
+ /** Browser operations and state injected into the Session Header contribution. */
7
+ export interface SessionLogDownloadDialogInjected {
8
+ hooks: {
9
+ sessionLogDownload: ObservableSnapshot<SessionLogDownloadState>;
10
+ };
11
+ request: (sessionId: SessionId) => Promise<void>;
12
+ dismiss: (sessionId: SessionId) => void;
13
+ }
14
+ export type SessionLogDownloadDialogProps = PropsRuntime<'conversation.session.header.utilities'> & PropsLocale<typeof NS> & InjectFace<SessionLogDownloadDialogInjected>;
15
+ /**
16
+ * Modal shared by the Session Header download menu item and this browser's `/export` command.
17
+ * @param props - Session runtime, bound controller state, actions, and localized copy.
18
+ * @returns the modal portal contribution.
19
+ */
20
+ export declare function SessionLogDownloadDialog({ sessionId, useSessionLogDownload, dismiss, t, }: SessionLogDownloadDialogProps): import("react").JSX.Element;
21
+ //# sourceMappingURL=Dialog.d.ts.map
@@ -0,0 +1,26 @@
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
@@ -0,0 +1,65 @@
1
+ /** Browser download state shared by the Session Header button and `/export`. */
2
+ import { type SnapshotStore } from '@unieai/rabi-client-store';
3
+ import type { SessionId } from '@unieai/rabi-session/types';
4
+ /** Download phases presented by the shared modal. */
5
+ export type SessionLogDownloadStatus = 'downloading' | 'success' | 'error';
6
+ /** One Session's current download-dialog state. */
7
+ export interface SessionLogDownloadEntry {
8
+ readonly open: boolean;
9
+ readonly status: SessionLogDownloadStatus;
10
+ readonly error: string | null;
11
+ }
12
+ /** Download states keyed by the Session whose Header owns the dialog. */
13
+ export interface SessionLogDownloadState {
14
+ bySession: Record<string, SessionLogDownloadEntry | undefined>;
15
+ }
16
+ /** HTTP carrier for the export route. */
17
+ type Fetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
18
+ type Save = (url: string, filename: string) => void;
19
+ /**
20
+ * Collapse an untrusted Session id into the filename convention owned by the host endpoint.
21
+ * @param sessionId - Session whose archive is downloaded.
22
+ * @returns one safe browser download filename.
23
+ */
24
+ export declare function sessionLogZipFilename(sessionId: SessionId): string;
25
+ /**
26
+ * Hand a Host download route to the browser download manager, which resolves it
27
+ * against the document's own base.
28
+ * @param url - document-relative Host download route.
29
+ * @param filename - browser download filename.
30
+ */
31
+ export declare function downloadUrl(url: string, filename: string): void;
32
+ /** Owns one in-flight browser download per Session and publishes modal state. */
33
+ export declare class SessionLogDownloadController {
34
+ private readonly fetcher;
35
+ private readonly save;
36
+ /** uSES-safe state source shared by every Session-scoped modal contribution. */
37
+ readonly store: SnapshotStore<SessionLogDownloadState>;
38
+ private readonly active;
39
+ private disposed;
40
+ /**
41
+ * @param fetcher - HTTP carrier used to read the host-streamed ZIP.
42
+ * @param save - browser save operation.
43
+ */
44
+ constructor(fetcher?: Fetch, save?: Save);
45
+ /**
46
+ * Download one Session tree; concurrent gestures for the same Session share one operation.
47
+ * @param sessionId - root Session whose ZIP includes descendants and attachments.
48
+ * @returns after the browser save starts, an error state is published, or a late post-disposal request is ignored.
49
+ */
50
+ download(sessionId: SessionId): Promise<void>;
51
+ /**
52
+ * Close one Session's dialog without cancelling an in-flight browser download.
53
+ * @param sessionId - Session whose modal closes.
54
+ */
55
+ dismiss(sessionId: SessionId): void;
56
+ /**
57
+ * Abort active fetches and reach quiescence.
58
+ * @returns after every active operation settles.
59
+ */
60
+ dispose(): Promise<void>;
61
+ private run;
62
+ private publish;
63
+ }
64
+ export {};
65
+ //# sourceMappingURL=controller.d.ts.map
@@ -0,0 +1,23 @@
1
+ /** Browser plugin owning Session export download state and its shared modal. */
2
+ import type { Context as ClientContext } from '@unieai/cordis';
3
+ import { SessionLogDownloadController } from './controller.ts';
4
+ import { type SessionLogDownloadKey } from './locales.ts';
5
+ declare module '@unieai/cordis' {
6
+ interface Context {
7
+ sessionLogDownload: SessionLogDownloadController;
8
+ }
9
+ }
10
+ declare module '@unieai/rabi-client-ui-slots' {
11
+ interface LocaleNamespaceMap {
12
+ 'session-log-download': SessionLogDownloadKey;
13
+ }
14
+ }
15
+ export type { SessionLogDownloadEntry, SessionLogDownloadState } from './controller.ts';
16
+ export declare const inject: string[];
17
+ /**
18
+ * Provide the download controller and mount its modal into the Session Header.
19
+ * @param ctx - browser context carrying slots and locale services.
20
+ */
21
+ export declare function apply(ctx: ClientContext): void;
22
+ export type { SessionLogDownloadDialogInjected, SessionLogDownloadDialogProps } from './Dialog.tsx';
23
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,20 @@
1
+ /** Locale namespace owned by Session export browser feedback. */
2
+ export declare const NS = "session-log-download";
3
+ /** Simplified-Chinese Session export strings. */
4
+ export declare const zh: {
5
+ readonly 'header.more': "更多操作";
6
+ readonly 'menu.download': "下载 Session 日志";
7
+ readonly 'menu.feedback': "反馈";
8
+ readonly 'dialog.preparingTitle': "正在导出 Session";
9
+ readonly 'dialog.preparingDescription': "正在准备包含当前 Session、子 Session 和附件的 ZIP 文件。";
10
+ readonly 'dialog.successTitle': "Session 导出已开始下载";
11
+ readonly 'dialog.successDescription': "浏览器正在下载 Session ZIP 文件。";
12
+ readonly 'dialog.errorTitle': "Session 导出失败";
13
+ readonly 'dialog.close': "关闭";
14
+ readonly 'dialog.commandFailed': "无法启动 Session 导出。";
15
+ };
16
+ /** English Session export strings. */
17
+ export declare const en: Record<keyof typeof zh, string>;
18
+ /** Stable locale keys consumed by the shared modal. */
19
+ export type SessionLogDownloadKey = keyof typeof zh;
20
+ //# sourceMappingURL=locales.d.ts.map
@@ -0,0 +1,23 @@
1
+ /** Session-log download command and Host-owned streaming route. */
2
+ import type { Context } from '@unieai/cordis';
3
+ import Schema from '@unieai/schemastery';
4
+ import { type SessionLogCompressionLevel } from './archive.ts';
5
+ export { DEFAULT_SESSION_LOG_COMPRESSION_LEVEL, flushLiveSessionLog, readSessionLogText, serializeSessionLog, SESSION_LOG_FILENAME, sessionLogExportDeps, sessionLogZipEntries, sessionLogZipFilename, streamSessionLogZip, } from './archive.ts';
6
+ export type { SessionLogCompressionLevel, SessionLogExportDeps, SessionLogExportReady, SessionLogZipEntry, } from './archive.ts';
7
+ export declare const name = "session-log-download";
8
+ export declare const inject: string[];
9
+ export { SESSION_LOG_EXPORT_PATH } from './routes.ts';
10
+ /** Session-log archive policy. */
11
+ export interface Config {
12
+ /** DEFLATE level for each ZIP entry. @default 6 */
13
+ readonly compressionLevel?: SessionLogCompressionLevel;
14
+ }
15
+ /** Validate Session-log archive configuration. */
16
+ export declare const Config: Schema<Config>;
17
+ /**
18
+ * Register the Web-only `/export` command and authenticated ZIP download route.
19
+ * @param ctx - Host context carrying the human-command registry.
20
+ * @param config - resolved compression policy.
21
+ */
22
+ export declare function apply(ctx: Context, config?: Config): void;
23
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The absolute pathname the Host registers the export under and the
3
+ * document-relative form the browser addresses; see
4
+ * .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
5
+ */
6
+ /** Absolute registration path for the ZIP download route. */
7
+ export declare const SESSION_LOG_EXPORT_PATH = "/api/session.export";
8
+ /** Browser-relative form of {@link SESSION_LOG_EXPORT_PATH}. */
9
+ export declare const SESSION_LOG_EXPORT_ROUTE: string;
10
+ //# sourceMappingURL=routes.d.ts.map
package/locale/en.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "meta": {
3
+ "title": "session-log-export"
4
+ }
5
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "会话日志导出",
4
+ "description": "提供会话日志导出命令和下载功能。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@unieai/rabi-session-log-export",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Web Session-log export command and shared download dialog",
4
+ "version": "0.2.1-rc.3",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "main": "lib/index.js",
10
+ "types": "lib/types/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/types/index.d.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./client": {
17
+ "types": "./lib/types/client/index.d.ts",
18
+ "default": "./lib/client.js"
19
+ },
20
+ "./src/*": "./src/*",
21
+ "./package.json": "./package.json",
22
+ "./locale/*.json": "./locale/*.json"
23
+ },
24
+ "files": [
25
+ "locale/*.json",
26
+ "lib/index.js",
27
+ "lib/client.js",
28
+ "lib/types/**/*.d.ts",
29
+ "README.md"
30
+ ],
31
+ "license": "MIT",
32
+ "dependencies": {
33
+ "@unieai/rabi-session-format": "0.2.1-rc.3",
34
+ "@unieai/schemastery": "3.18.5",
35
+ "fflate": "^0.8.2",
36
+ "@unieai/rabi-brand": "0.2.1-rc.3"
37
+ },
38
+ "peerDependencies": {
39
+ "@unieai/cordis": "4.0.5",
40
+ "@unieai/rabi-session": "0.2.1-rc.3",
41
+ "@unieai/rabi-session-persistence": "0.2.1-rc.3"
42
+ },
43
+ "rabi": {
44
+ "client": {
45
+ "inject": [
46
+ "@unieai/rabi-client-locale",
47
+ "@unieai/rabi-client-ui-commands",
48
+ "@unieai/rabi-client-ui-conversation",
49
+ "@unieai/rabi-client-ui-renderer",
50
+ "@unieai/rabi-client-ui-session"
51
+ ],
52
+ "platform": "web"
53
+ }
54
+ }
55
+ }