@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/lib/index.js
ADDED
|
@@ -0,0 +1,980 @@
|
|
|
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
|
+
const missing = [];
|
|
304
|
+
const openStreams = /* @__PURE__ */ new Set();
|
|
305
|
+
try {
|
|
306
|
+
for (const ref of media.values()) {
|
|
307
|
+
signal?.throwIfAborted();
|
|
308
|
+
try {
|
|
309
|
+
const stored = await deps.attachments.readImage(ref, signal);
|
|
310
|
+
signal?.throwIfAborted();
|
|
311
|
+
yield {
|
|
312
|
+
path: mediaEntryPath(ref),
|
|
313
|
+
data: stored.data
|
|
314
|
+
};
|
|
315
|
+
} catch (error) {
|
|
316
|
+
if (!isUnreadableReference(error)) throw error;
|
|
317
|
+
missing.push(`${mediaEntryPath(ref)}\t${error.message}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
for (const ref of files.values()) {
|
|
321
|
+
signal?.throwIfAborted();
|
|
322
|
+
let chunks;
|
|
323
|
+
try {
|
|
324
|
+
chunks = await headOf(deps.attachments.readFileStream(ref, signal), openStreams);
|
|
325
|
+
} catch (error) {
|
|
326
|
+
if (!isUnreadableReference(error)) throw error;
|
|
327
|
+
missing.push(`${fileEntryPath(ref)}\t${error.message}`);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
yield {
|
|
331
|
+
path: fileEntryPath(ref),
|
|
332
|
+
chunks
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
} finally {
|
|
336
|
+
await Promise.allSettled([...openStreams].map((close) => close()));
|
|
337
|
+
}
|
|
338
|
+
if (missing.length > 0) yield {
|
|
339
|
+
path: MISSING_ATTACHMENTS_FILENAME,
|
|
340
|
+
content: `${missing.join("\n")}\n`
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
/** Zip entry naming the attachment objects this export could not include. */
|
|
344
|
+
const MISSING_ATTACHMENTS_FILENAME = "attachments-missing.txt";
|
|
345
|
+
/**
|
|
346
|
+
* Attachment codes that leave the reference nothing to read: the object was
|
|
347
|
+
* deleted or never stored, or the backend rejects the reference outright. Such
|
|
348
|
+
* a reference leaves the rest of the export intact; every other failure still
|
|
349
|
+
* fails it. The stable machine-routing codes identify them without importing
|
|
350
|
+
* the attachment package's class, which stays its owner's peer.
|
|
351
|
+
*/
|
|
352
|
+
const UNREADABLE_ATTACHMENT_CODES = new Set(["ATTACHMENT_NOT_FOUND", "INVALID_ATTACHMENT_REF"]);
|
|
353
|
+
/**
|
|
354
|
+
* Whether an attachment read failed because the reference names nothing this
|
|
355
|
+
* backend can read.
|
|
356
|
+
* @param error - the thrown value.
|
|
357
|
+
* @returns whether it reports an unreadable reference.
|
|
358
|
+
*/
|
|
359
|
+
function isUnreadableReference(error) {
|
|
360
|
+
if (!(error instanceof Error) || !("code" in error)) return false;
|
|
361
|
+
const code = error.code;
|
|
362
|
+
return typeof code === "string" && UNREADABLE_ATTACHMENT_CODES.has(code);
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Pull one chunk of a file stream before its ZIP entry is yielded, so an
|
|
366
|
+
* unreadable reference surfaces here instead of after part of the archive is
|
|
367
|
+
* written, and hand back the rest of the same iteration. The returned stream
|
|
368
|
+
* closes its iterator when drained or abandoned; `open` receives the same
|
|
369
|
+
* close so the entry's owner can release a stream no consumer started.
|
|
370
|
+
* @param stream - the stored file's chunks.
|
|
371
|
+
* @param open - close callbacks of the streams currently open.
|
|
372
|
+
* @returns the chunks, with the first one already read.
|
|
373
|
+
*/
|
|
374
|
+
async function headOf(stream, open) {
|
|
375
|
+
const iterator = stream[Symbol.asyncIterator]();
|
|
376
|
+
const close = async () => {
|
|
377
|
+
open.delete(close);
|
|
378
|
+
await iterator.return?.();
|
|
379
|
+
};
|
|
380
|
+
open.add(close);
|
|
381
|
+
let head;
|
|
382
|
+
try {
|
|
383
|
+
head = await iterator.next();
|
|
384
|
+
} catch (error) {
|
|
385
|
+
await close();
|
|
386
|
+
throw error;
|
|
387
|
+
}
|
|
388
|
+
return (async function* () {
|
|
389
|
+
try {
|
|
390
|
+
if (head.done !== true) yield head.value;
|
|
391
|
+
for (;;) {
|
|
392
|
+
const next = await iterator.next();
|
|
393
|
+
if (next.done === true) return;
|
|
394
|
+
yield next.value;
|
|
395
|
+
}
|
|
396
|
+
} finally {
|
|
397
|
+
await close();
|
|
398
|
+
}
|
|
399
|
+
})();
|
|
400
|
+
}
|
|
401
|
+
/** How many code units of Session-log text one zip push carries (bounded encode memory). */
|
|
402
|
+
const PUSH_CHUNK_CODE_UNITS = 65536;
|
|
403
|
+
/** How many bytes of media one zip push carries (bounded memory; images are already size-capped). */
|
|
404
|
+
const PUSH_CHUNK_BYTES = 65536;
|
|
405
|
+
/** Byte capacity retained by the response stream before ZIP production waits for pull. */
|
|
406
|
+
const RESPONSE_HIGH_WATER_MARK_BYTES = 65536;
|
|
407
|
+
/** One producer waiter released only when ReadableStream pull restores capacity. */
|
|
408
|
+
var ResponseCapacityGate = class {
|
|
409
|
+
releasePending;
|
|
410
|
+
/**
|
|
411
|
+
* Wait until the response queue has positive byte capacity or cancellation wins.
|
|
412
|
+
* @param controller - response controller whose desired size owns capacity.
|
|
413
|
+
* @param signal - combined request/consumer cancellation.
|
|
414
|
+
*/
|
|
415
|
+
async wait(controller, signal) {
|
|
416
|
+
signal.throwIfAborted();
|
|
417
|
+
if (controller.desiredSize === null || controller.desiredSize > 0) return;
|
|
418
|
+
await new Promise((resolve) => {
|
|
419
|
+
const release = () => {
|
|
420
|
+
this.releasePending = void 0;
|
|
421
|
+
signal.removeEventListener("abort", release);
|
|
422
|
+
resolve();
|
|
423
|
+
};
|
|
424
|
+
this.releasePending = release;
|
|
425
|
+
signal.addEventListener("abort", release, { once: true });
|
|
426
|
+
});
|
|
427
|
+
signal.throwIfAborted();
|
|
428
|
+
}
|
|
429
|
+
/** Release the current producer waiter after a consumer pull. */
|
|
430
|
+
pulled() {
|
|
431
|
+
this.releasePending?.();
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
/**
|
|
435
|
+
* Push one media object's bytes into a deflate stream in bounded chunks,
|
|
436
|
+
* waiting for consumer capacity between chunks like the artifact path does.
|
|
437
|
+
* @param deflate - the zip entry's deflate stream.
|
|
438
|
+
* @param data - the stored image bytes.
|
|
439
|
+
* @param controller - response queue controller.
|
|
440
|
+
* @param capacity - pull-driven response-capacity gate.
|
|
441
|
+
* @param signal - cancellation; throws when aborted.
|
|
442
|
+
*/
|
|
443
|
+
async function pushBinaryChunks(deflate, data, controller, capacity, signal) {
|
|
444
|
+
let offset = 0;
|
|
445
|
+
do {
|
|
446
|
+
signal.throwIfAborted();
|
|
447
|
+
const end = Math.min(offset + PUSH_CHUNK_BYTES, data.byteLength);
|
|
448
|
+
const finalChunk = end >= data.byteLength;
|
|
449
|
+
deflate.push(data.subarray(offset, end), finalChunk);
|
|
450
|
+
offset = end;
|
|
451
|
+
await capacity.wait(controller, signal);
|
|
452
|
+
} while (offset < data.byteLength);
|
|
453
|
+
}
|
|
454
|
+
/** Push one streamed file entry without retaining its complete byte sequence. */
|
|
455
|
+
async function pushStreamChunks(deflate, chunks, controller, capacity, signal) {
|
|
456
|
+
for await (const chunk of chunks) {
|
|
457
|
+
signal.throwIfAborted();
|
|
458
|
+
if (chunk.byteLength === 0) continue;
|
|
459
|
+
deflate.push(chunk, false);
|
|
460
|
+
await capacity.wait(controller, signal);
|
|
461
|
+
}
|
|
462
|
+
signal.throwIfAborted();
|
|
463
|
+
deflate.push(new Uint8Array(), true);
|
|
464
|
+
await capacity.wait(controller, signal);
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Push one artifact's text into a deflate stream in bounded chunks, never
|
|
468
|
+
* splitting a surrogate pair across a chunk boundary (a lone high surrogate
|
|
469
|
+
* re-encodes as U+FFFD and would silently corrupt the exported artifact).
|
|
470
|
+
* @param deflate - the zip entry's deflate stream.
|
|
471
|
+
* @param content - the canonical Session-log text.
|
|
472
|
+
* @param controller - response queue controller.
|
|
473
|
+
* @param capacity - pull-driven response-capacity gate.
|
|
474
|
+
* @param signal - cancellation; throws when aborted.
|
|
475
|
+
*/
|
|
476
|
+
async function pushArtifactChunks(deflate, content, controller, capacity, signal) {
|
|
477
|
+
const encoder = new TextEncoder();
|
|
478
|
+
let offset = 0;
|
|
479
|
+
let finalChunk;
|
|
480
|
+
do {
|
|
481
|
+
signal.throwIfAborted();
|
|
482
|
+
let end = Math.min(offset + PUSH_CHUNK_CODE_UNITS, content.length);
|
|
483
|
+
if (end < content.length && end - offset > 1) {
|
|
484
|
+
const last = content.charCodeAt(end - 1);
|
|
485
|
+
if (last >= 55296 && last <= 56319) end -= 1;
|
|
486
|
+
}
|
|
487
|
+
finalChunk = end >= content.length;
|
|
488
|
+
deflate.push(encoder.encode(content.slice(offset, end)), finalChunk);
|
|
489
|
+
offset = end;
|
|
490
|
+
await capacity.wait(controller, signal);
|
|
491
|
+
} while (!finalChunk);
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Stream one session-log ZIP as a WHATWG ReadableStream. The root log is read
|
|
495
|
+
* and serialized by the caller before this is called (a missing root or
|
|
496
|
+
* missing services answer cleanly before any byte is produced); each entry is
|
|
497
|
+
* then encoded and deflated in bounded chunks as it is produced, so the
|
|
498
|
+
* archive bytes arrive incrementally. A descendant that fails to read errors
|
|
499
|
+
* the stream (fail-loud, never silent under-export).
|
|
500
|
+
* @param deps - the mounted export services (the caller answered 500 before this runs).
|
|
501
|
+
* @param rootContent - the already-serialized root log (first zip entry).
|
|
502
|
+
* @param sessionId - the root session id.
|
|
503
|
+
* @param includeDescendants - whether to include every subagent descendant.
|
|
504
|
+
* @param compressionLevel - validated fflate DEFLATE level for every ZIP entry.
|
|
505
|
+
* @param signal - request cancellation combined with response-consumer cancellation.
|
|
506
|
+
* @returns the zip byte stream.
|
|
507
|
+
*/
|
|
508
|
+
function streamSessionLogZip(deps, rootContent, sessionId, includeDescendants, compressionLevel, signal) {
|
|
509
|
+
const consumerAbort = new AbortController();
|
|
510
|
+
const producerSignal = AbortSignal.any([signal, consumerAbort.signal]);
|
|
511
|
+
let zip;
|
|
512
|
+
let zipTerminated = false;
|
|
513
|
+
const capacity = new ResponseCapacityGate();
|
|
514
|
+
const terminateZip = () => {
|
|
515
|
+
if (zip === void 0 || zipTerminated) return;
|
|
516
|
+
zipTerminated = true;
|
|
517
|
+
zip.terminate();
|
|
518
|
+
};
|
|
519
|
+
return new ReadableStream({
|
|
520
|
+
start(controller) {
|
|
521
|
+
const archive = new Zip((error, data, final) => {
|
|
522
|
+
/* v8 ignore next 3 -- fflate reports only internal zip failures, unreachable for valid inputs */
|
|
523
|
+
if (error) {
|
|
524
|
+
controller.error(error);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
/* v8 ignore next -- fflate may emit empty chunks; not controllable from tests */
|
|
528
|
+
if (data.byteLength > 0) controller.enqueue(data);
|
|
529
|
+
if (final) controller.close();
|
|
530
|
+
});
|
|
531
|
+
zip = archive;
|
|
532
|
+
(async () => {
|
|
533
|
+
try {
|
|
534
|
+
for await (const entry of sessionLogZipEntries(deps, rootContent, sessionId, includeDescendants, producerSignal)) {
|
|
535
|
+
const deflate = new ZipDeflate(entry.path, { level: compressionLevel });
|
|
536
|
+
archive.add(deflate);
|
|
537
|
+
if ("content" in entry) await pushArtifactChunks(deflate, entry.content, controller, capacity, producerSignal);
|
|
538
|
+
else if ("data" in entry) await pushBinaryChunks(deflate, entry.data, controller, capacity, producerSignal);
|
|
539
|
+
else await pushStreamChunks(deflate, entry.chunks, controller, capacity, producerSignal);
|
|
540
|
+
}
|
|
541
|
+
archive.end();
|
|
542
|
+
} catch (error) {
|
|
543
|
+
/* v8 ignore next -- typed backends reject with Error, and DOMException is one in Node */
|
|
544
|
+
terminateZip();
|
|
545
|
+
controller.error(error instanceof Error ? error : new Error(String(error)));
|
|
546
|
+
}
|
|
547
|
+
})();
|
|
548
|
+
},
|
|
549
|
+
pull() {
|
|
550
|
+
capacity.pulled();
|
|
551
|
+
},
|
|
552
|
+
cancel(reason) {
|
|
553
|
+
consumerAbort.abort(reason instanceof Error ? reason : /* @__PURE__ */ new Error("session log export stream cancelled"));
|
|
554
|
+
terminateZip();
|
|
555
|
+
}
|
|
556
|
+
}, {
|
|
557
|
+
highWaterMark: RESPONSE_HIGH_WATER_MARK_BYTES,
|
|
558
|
+
size: (chunk) => chunk.byteLength
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
//#endregion
|
|
562
|
+
//#region lib/types/markdown.js
|
|
563
|
+
/**
|
|
564
|
+
* Pure backend converter for one complete committed Session log. The Session
|
|
565
|
+
* Markdown copy Host route uses it, and the package entry exports it for
|
|
566
|
+
* callers that already hold the logical events. The raw log is authoritative:
|
|
567
|
+
* compaction surface replacements never remove earlier messages, and
|
|
568
|
+
* fork-inherited history appears once. Reasoning, system and developer
|
|
569
|
+
* messages, injected non-human context, request headers, and runtime records
|
|
570
|
+
* are omitted.
|
|
571
|
+
* @module
|
|
572
|
+
*/
|
|
573
|
+
/** Heading used when the log carries no title and the Session has no name. */
|
|
574
|
+
const UNTITLED_SESSION_MARKDOWN_TITLE = "Untitled Session";
|
|
575
|
+
/**
|
|
576
|
+
* Render one complete committed Session log as Markdown. This is a pure backend
|
|
577
|
+
* utility: it needs no mounted plugin, reads no storage, and does not mutate the
|
|
578
|
+
* supplied events. The latest `session/title` event supplies the heading; the
|
|
579
|
+
* rest of the transcript is derived only from the supplied logical events.
|
|
580
|
+
* @param events - complete committed logical event snapshot in seq order, including any inherited prefix.
|
|
581
|
+
* @param sourcePath - optional backend-resolved path to the selected Session artifact; emitted verbatim in a fenced text block.
|
|
582
|
+
* @returns Markdown ending in exactly one newline; an empty log returns the heading and optional source metadata only.
|
|
583
|
+
*/
|
|
584
|
+
function formatSessionMarkdown(events, sourcePath) {
|
|
585
|
+
const title = events.findLast((event) => event.type === "session/title")?.data.title;
|
|
586
|
+
const sections = [`# ${normalizedTitle(title)}`];
|
|
587
|
+
if (sourcePath !== void 0 && sourcePath !== "") sections.push(`Session file:
|
|
588
|
+
|
|
589
|
+
${fenced(sourcePath, "text", false)}`);
|
|
590
|
+
for (const turn of collectTurns(events)) {
|
|
591
|
+
const finalIndex = finalReplyIndex(turn.segments);
|
|
592
|
+
const end = finalIndex < 0 ? turn.segments.length : finalIndex;
|
|
593
|
+
let pending = [];
|
|
594
|
+
for (const segment of turn.segments.slice(0, end)) if (segment.kind === "user") {
|
|
595
|
+
if (pending.length > 0) {
|
|
596
|
+
sections.push(collapsibleSection(pending));
|
|
597
|
+
pending = [];
|
|
598
|
+
}
|
|
599
|
+
sections.push(quote(segment.text));
|
|
600
|
+
} else pending.push(segment);
|
|
601
|
+
if (pending.length > 0) sections.push(collapsibleSection(pending));
|
|
602
|
+
const final = turn.segments[finalIndex];
|
|
603
|
+
const finalText = final?.kind === "assistant" ? closeUnfinishedFence(trimBlankEdgeLines(final.text)) : "";
|
|
604
|
+
if (finalText !== "") sections.push(finalText);
|
|
605
|
+
}
|
|
606
|
+
return `${sections.join("\n\n").trimEnd()}\n`;
|
|
607
|
+
}
|
|
608
|
+
function normalizedTitle(title) {
|
|
609
|
+
const line = title?.replace(/\r\n?|\n/gu, " ").trim() ?? "";
|
|
610
|
+
return line === "" ? UNTITLED_SESSION_MARKDOWN_TITLE : line;
|
|
611
|
+
}
|
|
612
|
+
function collectTurns(events) {
|
|
613
|
+
const turns = [];
|
|
614
|
+
let current;
|
|
615
|
+
const begin = () => {
|
|
616
|
+
current = {
|
|
617
|
+
segments: [],
|
|
618
|
+
calls: /* @__PURE__ */ new Map()
|
|
619
|
+
};
|
|
620
|
+
turns.push(current);
|
|
621
|
+
return current;
|
|
622
|
+
};
|
|
623
|
+
const active = () => current ?? begin();
|
|
624
|
+
for (const event of events) switch (event.type) {
|
|
625
|
+
case "turn/start":
|
|
626
|
+
begin();
|
|
627
|
+
break;
|
|
628
|
+
case "turn/end":
|
|
629
|
+
current = void 0;
|
|
630
|
+
break;
|
|
631
|
+
case "user/message": {
|
|
632
|
+
if (event.surfaceOp !== "append" || event.data.source.kind !== "user") break;
|
|
633
|
+
const text = visibleContent(event.data.content);
|
|
634
|
+
if (text !== "") active().segments.push({
|
|
635
|
+
kind: "user",
|
|
636
|
+
text
|
|
637
|
+
});
|
|
638
|
+
break;
|
|
639
|
+
}
|
|
640
|
+
case "assistant/message": {
|
|
641
|
+
if (event.surfaceOp !== "append") break;
|
|
642
|
+
const message = event.data.message;
|
|
643
|
+
const text = assistantText(message);
|
|
644
|
+
const toolCalls = message.content.some((block) => block.type === "tool-call");
|
|
645
|
+
if (trimBlankEdgeLines(text) !== "") active().segments.push({
|
|
646
|
+
kind: "assistant",
|
|
647
|
+
text,
|
|
648
|
+
toolCalls
|
|
649
|
+
});
|
|
650
|
+
break;
|
|
651
|
+
}
|
|
652
|
+
case "tool/call": {
|
|
653
|
+
const turn = active();
|
|
654
|
+
const entry = {
|
|
655
|
+
kind: "tool",
|
|
656
|
+
name: event.data.name,
|
|
657
|
+
arguments: event.data.arguments,
|
|
658
|
+
result: void 0
|
|
659
|
+
};
|
|
660
|
+
turn.segments.push(entry);
|
|
661
|
+
turn.calls.set(String(event.data.callId), entry);
|
|
662
|
+
break;
|
|
663
|
+
}
|
|
664
|
+
case "tool/result": {
|
|
665
|
+
if (event.surfaceOp !== "append") break;
|
|
666
|
+
const turn = active();
|
|
667
|
+
const callId = String(event.data.message.toolCallId);
|
|
668
|
+
let entry = turn.calls.get(callId);
|
|
669
|
+
if (entry === void 0) {
|
|
670
|
+
entry = {
|
|
671
|
+
kind: "tool",
|
|
672
|
+
name: "unknown",
|
|
673
|
+
arguments: "",
|
|
674
|
+
result: void 0
|
|
675
|
+
};
|
|
676
|
+
turn.segments.push(entry);
|
|
677
|
+
turn.calls.set(callId, entry);
|
|
678
|
+
}
|
|
679
|
+
entry.result = toolResult(event.data);
|
|
680
|
+
break;
|
|
681
|
+
}
|
|
682
|
+
default: break;
|
|
683
|
+
}
|
|
684
|
+
return turns.filter((turn) => turn.segments.length > 0);
|
|
685
|
+
}
|
|
686
|
+
function finalReplyIndex(segments) {
|
|
687
|
+
const index = segments.length - 1;
|
|
688
|
+
const entry = segments[index];
|
|
689
|
+
return entry?.kind === "assistant" && !entry.toolCalls ? index : -1;
|
|
690
|
+
}
|
|
691
|
+
function collapsibleSection(entries) {
|
|
692
|
+
return `<details><summary>${entries.length === 1 ? "1 previous message" : `${String(entries.length)} previous messages`}</summary>\n\n${entries.map(renderEntry).join("\n\n")}\n\n</details>`;
|
|
693
|
+
}
|
|
694
|
+
function renderEntry(entry) {
|
|
695
|
+
if (entry.kind === "assistant") return `**Assistant**\n\n${escapeWrapperTagsOutsideFences(closeUnfinishedFence(trimBlankEdgeLines(entry.text)))}`;
|
|
696
|
+
const heading = `**Tool: \`${escapeWrapperTags(entry.name)}\`**`;
|
|
697
|
+
const argumentsText = entry.arguments === "" ? "(no arguments)" : fenced(jsonArguments(entry.arguments), "json");
|
|
698
|
+
const result = entry.result;
|
|
699
|
+
const resultHeading = result?.isError === true ? "**Result (error)**" : "**Result**";
|
|
700
|
+
let resultBody = "";
|
|
701
|
+
if (result === void 0) resultBody = "(no result recorded)";
|
|
702
|
+
else if (result.reason !== void 0 && result.reason !== "") {
|
|
703
|
+
resultBody = `Error: ${escapeWrapperTags(result.reason)}`;
|
|
704
|
+
if (result.text !== "") resultBody += `\n\n${fenced(result.text)}`;
|
|
705
|
+
} else if (result.text === "") resultBody = "(no output)";
|
|
706
|
+
else resultBody = fenced(result.text);
|
|
707
|
+
return `${heading}\n\n${argumentsText}\n\n${resultHeading}\n\n${resultBody}`;
|
|
708
|
+
}
|
|
709
|
+
function visibleContent(content) {
|
|
710
|
+
const parts = [];
|
|
711
|
+
for (const block of content) switch (block.type) {
|
|
712
|
+
case "text":
|
|
713
|
+
if (block.text !== "") parts.push(block.text);
|
|
714
|
+
break;
|
|
715
|
+
case "image":
|
|
716
|
+
parts.push(imageLabel(block.attachment));
|
|
717
|
+
break;
|
|
718
|
+
case "file":
|
|
719
|
+
parts.push(fileLabel(block.attachment));
|
|
720
|
+
break;
|
|
721
|
+
default: break;
|
|
722
|
+
}
|
|
723
|
+
return parts.join("\n\n");
|
|
724
|
+
}
|
|
725
|
+
function assistantText(message) {
|
|
726
|
+
return visibleContent(message.content);
|
|
727
|
+
}
|
|
728
|
+
function toolResult(data) {
|
|
729
|
+
return {
|
|
730
|
+
text: visibleContent(data.message.content),
|
|
731
|
+
isError: data.message.isError === true,
|
|
732
|
+
reason: data.error?.reason
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
function quote(text) {
|
|
736
|
+
return text.replace(/\r\n?/gu, "\n").replace(/\n+$/u, "").split("\n").map((line) => line === "" ? ">" : `> ${line}`).join("\n");
|
|
737
|
+
}
|
|
738
|
+
function imageLabel(ref) {
|
|
739
|
+
return `[Image: ${labelName(ref.name)} (${String(ref.width)}×${String(ref.height)}, ${String(ref.bytes)} bytes)]`;
|
|
740
|
+
}
|
|
741
|
+
function fileLabel(ref) {
|
|
742
|
+
return `[File: ${labelName(ref.name)} (${String(ref.bytes)} bytes)]`;
|
|
743
|
+
}
|
|
744
|
+
function labelName(name) {
|
|
745
|
+
const normalized = name?.replace(/\s+/gu, " ").replace(/\]/gu, "\\]").trim() ?? "";
|
|
746
|
+
return normalized === "" ? "attachment" : normalized;
|
|
747
|
+
}
|
|
748
|
+
function jsonArguments(argumentsText) {
|
|
749
|
+
let parsed;
|
|
750
|
+
try {
|
|
751
|
+
parsed = JSON.parse(argumentsText);
|
|
752
|
+
} catch {
|
|
753
|
+
return argumentsText;
|
|
754
|
+
}
|
|
755
|
+
return JSON.stringify(parsed, null, 2);
|
|
756
|
+
}
|
|
757
|
+
function fenced(text, language = "", trimTrailing = true) {
|
|
758
|
+
const content = trimTrailing ? text.replace(/\n+$/u, "") : text;
|
|
759
|
+
let longest = 0;
|
|
760
|
+
for (const match of content.matchAll(/`+/gu)) longest = Math.max(longest, match[0].length);
|
|
761
|
+
const fence = "`".repeat(Math.max(3, longest + 1));
|
|
762
|
+
return `${fence}${language}\n${content}\n${fence}`;
|
|
763
|
+
}
|
|
764
|
+
function trimBlankEdgeLines(text) {
|
|
765
|
+
const lines = text.replace(/\r\n?/gu, "\n").split("\n");
|
|
766
|
+
let start = 0;
|
|
767
|
+
let end = lines.length;
|
|
768
|
+
while (start < end && lines[start]?.trim() === "") start += 1;
|
|
769
|
+
while (end > start && lines[end - 1]?.trim() === "") end -= 1;
|
|
770
|
+
return lines.slice(start, end).join("\n");
|
|
771
|
+
}
|
|
772
|
+
function scanMarkdown(markdown) {
|
|
773
|
+
const lines = markdown.replace(/\r\n?/gu, "\n").split("\n");
|
|
774
|
+
const scanned = [];
|
|
775
|
+
let fence;
|
|
776
|
+
let indented = false;
|
|
777
|
+
for (const line of lines) {
|
|
778
|
+
if (fence !== void 0) {
|
|
779
|
+
scanned.push({
|
|
780
|
+
text: line,
|
|
781
|
+
code: true
|
|
782
|
+
});
|
|
783
|
+
if (closesFence(line, fence)) fence = void 0;
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
const opening = openingFence(line);
|
|
787
|
+
if (opening !== void 0) {
|
|
788
|
+
fence = opening;
|
|
789
|
+
indented = false;
|
|
790
|
+
scanned.push({
|
|
791
|
+
text: line,
|
|
792
|
+
code: true
|
|
793
|
+
});
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
if (/^(?: {4}|\t)/u.test(line)) {
|
|
797
|
+
indented = true;
|
|
798
|
+
scanned.push({
|
|
799
|
+
text: line,
|
|
800
|
+
code: true
|
|
801
|
+
});
|
|
802
|
+
continue;
|
|
803
|
+
}
|
|
804
|
+
scanned.push({
|
|
805
|
+
text: line,
|
|
806
|
+
code: indented && line.trim() === ""
|
|
807
|
+
});
|
|
808
|
+
if (line.trim() !== "") indented = false;
|
|
809
|
+
}
|
|
810
|
+
return {
|
|
811
|
+
lines: scanned,
|
|
812
|
+
openFence: fence
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
function openingFence(line) {
|
|
816
|
+
const opening = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(line);
|
|
817
|
+
if (opening === null) return void 0;
|
|
818
|
+
const marker = String(opening[1]);
|
|
819
|
+
const info = String(opening[2]);
|
|
820
|
+
if (marker.startsWith("`") && info.includes("`")) return void 0;
|
|
821
|
+
return {
|
|
822
|
+
character: marker.slice(0, 1),
|
|
823
|
+
length: marker.length
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
function closesFence(line, fence) {
|
|
827
|
+
return new RegExp(`^ {0,3}${fence.character}{${String(fence.length)},}\\s*$`, "u").test(line);
|
|
828
|
+
}
|
|
829
|
+
function closeUnfinishedFence(markdown) {
|
|
830
|
+
const scan = scanMarkdown(markdown);
|
|
831
|
+
if (scan.openFence === void 0) return markdown;
|
|
832
|
+
return `${markdown.replace(/\n+$/u, "")}\n${scan.openFence.character.repeat(scan.openFence.length)}`;
|
|
833
|
+
}
|
|
834
|
+
function escapeWrapperTagsOutsideFences(markdown) {
|
|
835
|
+
return scanMarkdown(markdown).lines.map((line) => line.code ? line.text : escapeWrapperTags(line.text)).join("\n");
|
|
836
|
+
}
|
|
837
|
+
function escapeWrapperTags(text) {
|
|
838
|
+
return text.replace(/<(?=\/?(?:details|summary)(?=[\s/>]))/giu, "<");
|
|
839
|
+
}
|
|
840
|
+
//#endregion
|
|
841
|
+
//#region lib/types/routes.js
|
|
842
|
+
/**
|
|
843
|
+
* The absolute pathnames the Host registers the export routes under and the
|
|
844
|
+
* document-relative forms the browser addresses; see
|
|
845
|
+
* .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
|
|
846
|
+
*/
|
|
847
|
+
/** Absolute registration path for the ZIP download route. */
|
|
848
|
+
const SESSION_LOG_EXPORT_PATH = "/api/session.export";
|
|
849
|
+
SESSION_LOG_EXPORT_PATH.slice(1);
|
|
850
|
+
/** Absolute registration path for the Markdown copy route. */
|
|
851
|
+
const SESSION_MARKDOWN_EXPORT_PATH = "/api/session.markdown";
|
|
852
|
+
SESSION_MARKDOWN_EXPORT_PATH.slice(1);
|
|
853
|
+
//#endregion
|
|
854
|
+
//#region lib/types/index.js
|
|
855
|
+
/** Session export command and Host-owned ZIP download and Markdown copy routes. */
|
|
856
|
+
const name = "session-log-download";
|
|
857
|
+
const inject = ["commands", "connection"];
|
|
858
|
+
/** Validate Session-log archive configuration. */
|
|
859
|
+
const Config = Schema.object({ compressionLevel: Schema.number().step(1).min(0).max(9).default(6) });
|
|
860
|
+
const REQUESTED = {
|
|
861
|
+
kind: "success",
|
|
862
|
+
text: "Session log download requested."
|
|
863
|
+
};
|
|
864
|
+
/**
|
|
865
|
+
* Register the `/export` command and authenticated ZIP download and Markdown copy routes.
|
|
866
|
+
* @param ctx - Host context carrying the human-command registry.
|
|
867
|
+
* @param config - resolved compression policy.
|
|
868
|
+
*/
|
|
869
|
+
function apply(ctx, config = {}) {
|
|
870
|
+
ctx.effect(() => ctx.commands.register({
|
|
871
|
+
definitionId: brandString("@unieai/rabi-session-log-export"),
|
|
872
|
+
name: "export",
|
|
873
|
+
description: "Download this Session log as a ZIP archive",
|
|
874
|
+
handler: (invocation) => Promise.resolve(invocation.rawInput.trim() === "" ? REQUESTED : {
|
|
875
|
+
kind: "error",
|
|
876
|
+
text: "The Web /export command does not accept a path."
|
|
877
|
+
})
|
|
878
|
+
}), "session-log-download: command");
|
|
879
|
+
connectionOf(ctx).fetch.register({
|
|
880
|
+
path: SESSION_LOG_EXPORT_PATH,
|
|
881
|
+
methods: ["GET", "HEAD"],
|
|
882
|
+
requestBody: "buffered",
|
|
883
|
+
fetch: async (request) => {
|
|
884
|
+
const response = await sessionLogExportResponse(ctx, request, config.compressionLevel ?? 6);
|
|
885
|
+
if (request.method === "GET") return response;
|
|
886
|
+
await response.body?.cancel();
|
|
887
|
+
return new Response(null, {
|
|
888
|
+
status: response.status,
|
|
889
|
+
headers: response.headers
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
});
|
|
893
|
+
connectionOf(ctx).fetch.register({
|
|
894
|
+
path: SESSION_MARKDOWN_EXPORT_PATH,
|
|
895
|
+
methods: ["GET", "HEAD"],
|
|
896
|
+
requestBody: "buffered",
|
|
897
|
+
fetch: async (request) => {
|
|
898
|
+
const response = await sessionMarkdownResponse(ctx, request);
|
|
899
|
+
if (request.method === "GET") return response;
|
|
900
|
+
await response.body?.cancel();
|
|
901
|
+
return new Response(null, {
|
|
902
|
+
status: response.status,
|
|
903
|
+
headers: response.headers
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
function connectionOf(ctx) {
|
|
909
|
+
return Reflect.get(ctx, "connection");
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Produce one complete Session transcript as Markdown from one Session
|
|
913
|
+
* observation. The read is a detached export observation through
|
|
914
|
+
* session-query's live-preferred corpus, so it creates no Agent, retains no
|
|
915
|
+
* Session, and writes no Session data. The formatter reads the latest title from
|
|
916
|
+
* the same event snapshot as the body. Abort is observed before and after the
|
|
917
|
+
* read; the corpus read itself has no cancellation parameter.
|
|
918
|
+
* @param ctx - host context carrying Connection and session-query.
|
|
919
|
+
* @param request - authenticated Fetch request with a required `sessionId` query.
|
|
920
|
+
* @returns the Markdown response, or a sanitized status for invalid, missing, or unavailable reads.
|
|
921
|
+
*/
|
|
922
|
+
async function sessionMarkdownResponse(ctx, request) {
|
|
923
|
+
const sessionIdValue = new URL(request.url).searchParams.get("sessionId");
|
|
924
|
+
if (sessionIdValue === null || sessionIdValue.length === 0) return new Response("missing or invalid sessionId query parameter", { status: 400 });
|
|
925
|
+
const sessionQuery = ctx.get("sessionQuery");
|
|
926
|
+
if (sessionQuery === void 0) return new Response("session markdown export is unavailable: missing session-query service", { status: 500 });
|
|
927
|
+
const sessionId = brandString(sessionIdValue);
|
|
928
|
+
try {
|
|
929
|
+
request.signal.throwIfAborted();
|
|
930
|
+
const snapshot = await sessionQuery.readSession(sessionId);
|
|
931
|
+
request.signal.throwIfAborted();
|
|
932
|
+
const metadata = await ctx.get("sessionPersistence")?.stat(sessionId, { signal: request.signal });
|
|
933
|
+
request.signal.throwIfAborted();
|
|
934
|
+
return new Response(formatSessionMarkdown(snapshot.events, metadata?.location?.path), { headers: { "content-type": "text/markdown; charset=utf-8" } });
|
|
935
|
+
} catch (error) {
|
|
936
|
+
request.signal.throwIfAborted();
|
|
937
|
+
if (isSessionNotFound(error)) return new Response("session not found", { status: 404 });
|
|
938
|
+
return new Response("session markdown export failed to read the stored log", { status: 500 });
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Identify the session-query "not found" failure by its stable machine code.
|
|
943
|
+
* @param error - an arbitrary rejection from the query service.
|
|
944
|
+
* @returns whether the error reports a missing Session.
|
|
945
|
+
*/
|
|
946
|
+
function isSessionNotFound(error) {
|
|
947
|
+
return error instanceof Error && "code" in error && error.code === "SESSION_QUERY_SESSION_NOT_FOUND";
|
|
948
|
+
}
|
|
949
|
+
async function sessionLogExportResponse(ctx, request, compressionLevel) {
|
|
950
|
+
const url = new URL(request.url);
|
|
951
|
+
const query = Object.fromEntries(url.searchParams);
|
|
952
|
+
const sessionIdValue = query["sessionId"];
|
|
953
|
+
const descendantsValue = query["includeDescendants"];
|
|
954
|
+
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 });
|
|
955
|
+
const sessionId = brandString(sessionIdValue);
|
|
956
|
+
const deps = sessionLogExportDeps(ctx);
|
|
957
|
+
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 });
|
|
958
|
+
const ready = {
|
|
959
|
+
sessionQuery: deps.sessionQuery,
|
|
960
|
+
sessionPersistence: deps.sessionPersistence,
|
|
961
|
+
attachments: deps.attachments,
|
|
962
|
+
sessions: deps.sessions
|
|
963
|
+
};
|
|
964
|
+
let rootContent;
|
|
965
|
+
try {
|
|
966
|
+
await flushLiveSessionLog(deps, sessionId, request.signal);
|
|
967
|
+
rootContent = await readSessionLogText(deps.sessionPersistence, sessionId, request.signal);
|
|
968
|
+
request.signal.throwIfAborted();
|
|
969
|
+
} catch {
|
|
970
|
+
request.signal.throwIfAborted();
|
|
971
|
+
return new Response("session log export failed to read the stored log", { status: 500 });
|
|
972
|
+
}
|
|
973
|
+
if (rootContent === void 0) return new Response("session not found", { status: 404 });
|
|
974
|
+
return new Response(streamSessionLogZip(ready, rootContent, sessionId, descendantsValue === "true", compressionLevel, request.signal), { headers: {
|
|
975
|
+
"content-type": "application/zip",
|
|
976
|
+
"content-disposition": `attachment; filename="${sessionLogZipFilename(sessionId)}"`
|
|
977
|
+
} });
|
|
978
|
+
}
|
|
979
|
+
//#endregion
|
|
980
|
+
export { Config, DEFAULT_SESSION_LOG_COMPRESSION_LEVEL, SESSION_LOG_EXPORT_PATH, SESSION_LOG_FILENAME, apply, flushLiveSessionLog, formatSessionMarkdown, inject, name, readSessionLogText, serializeSessionLog, sessionLogExportDeps, sessionLogZipEntries, sessionLogZipFilename, streamSessionLogZip };
|