@unieai/rabi-session-log-export 0.2.1-rc.3 → 0.2.2-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/client.js +1 -315
- package/lib/index.js +434 -19
- package/lib/types/client/CopyToast.d.ts +21 -0
- package/lib/types/client/Dialog.d.ts +8 -7
- package/lib/types/client/controller.d.ts +7 -3
- package/lib/types/client/copy-controller.d.ts +76 -0
- package/lib/types/client/index.d.ts +3 -2
- package/lib/types/client/locales.d.ts +108 -2
- package/lib/types/index.d.ts +3 -2
- package/lib/types/markdown.d.ts +22 -0
- package/lib/types/routes.d.ts +6 -2
- package/locale/de.json +6 -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/package.json +14 -10
- 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/types/client/HeaderAction.d.ts +0 -26
package/lib/index.js
CHANGED
|
@@ -300,22 +300,103 @@ async function* sessionLogZipEntries(deps, rootContent, sessionId, includeDescen
|
|
|
300
300
|
signal?.throwIfAborted();
|
|
301
301
|
yield* collect(lineage.descendants);
|
|
302
302
|
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
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()));
|
|
311
337
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
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;
|
|
318
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
|
+
})();
|
|
319
400
|
}
|
|
320
401
|
/** How many code units of Session-log text one zip push carries (bounded encode memory). */
|
|
321
402
|
const PUSH_CHUNK_CODE_UNITS = 65536;
|
|
@@ -478,18 +559,300 @@ function streamSessionLogZip(deps, rootContent, sessionId, includeDescendants, c
|
|
|
478
559
|
});
|
|
479
560
|
}
|
|
480
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
|
|
481
841
|
//#region lib/types/routes.js
|
|
482
842
|
/**
|
|
483
|
-
* The absolute
|
|
484
|
-
* document-relative
|
|
843
|
+
* The absolute pathnames the Host registers the export routes under and the
|
|
844
|
+
* document-relative forms the browser addresses; see
|
|
485
845
|
* .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
|
|
486
846
|
*/
|
|
487
847
|
/** Absolute registration path for the ZIP download route. */
|
|
488
848
|
const SESSION_LOG_EXPORT_PATH = "/api/session.export";
|
|
489
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);
|
|
490
853
|
//#endregion
|
|
491
854
|
//#region lib/types/index.js
|
|
492
|
-
/** Session
|
|
855
|
+
/** Session export command and Host-owned ZIP download and Markdown copy routes. */
|
|
493
856
|
const name = "session-log-download";
|
|
494
857
|
const inject = ["commands", "connection"];
|
|
495
858
|
/** Validate Session-log archive configuration. */
|
|
@@ -499,7 +862,7 @@ const REQUESTED = {
|
|
|
499
862
|
text: "Session log download requested."
|
|
500
863
|
};
|
|
501
864
|
/**
|
|
502
|
-
* Register the
|
|
865
|
+
* Register the `/export` command and authenticated ZIP download and Markdown copy routes.
|
|
503
866
|
* @param ctx - Host context carrying the human-command registry.
|
|
504
867
|
* @param config - resolved compression policy.
|
|
505
868
|
*/
|
|
@@ -527,10 +890,62 @@ function apply(ctx, config = {}) {
|
|
|
527
890
|
});
|
|
528
891
|
}
|
|
529
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
|
+
});
|
|
530
907
|
}
|
|
531
908
|
function connectionOf(ctx) {
|
|
532
909
|
return Reflect.get(ctx, "connection");
|
|
533
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
|
+
}
|
|
534
949
|
async function sessionLogExportResponse(ctx, request, compressionLevel) {
|
|
535
950
|
const url = new URL(request.url);
|
|
536
951
|
const query = Object.fromEntries(url.searchParams);
|
|
@@ -562,4 +977,4 @@ async function sessionLogExportResponse(ctx, request, compressionLevel) {
|
|
|
562
977
|
} });
|
|
563
978
|
}
|
|
564
979
|
//#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 };
|
|
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 };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { ObservableSnapshot } from '@unieai/rabi-client-store';
|
|
3
|
+
import type { InjectFace, PropsLocale, PropsRuntime } from '@unieai/rabi-client-ui-slots';
|
|
4
|
+
import type { SessionMarkdownCopyState } from './copy-controller.ts';
|
|
5
|
+
import { NS } from './locales.ts';
|
|
6
|
+
/** Copy state and dismissal bound into the root overlay entry. */
|
|
7
|
+
export interface SessionMarkdownCopyToastInjected {
|
|
8
|
+
hooks: {
|
|
9
|
+
sessionMarkdownCopy: ObservableSnapshot<SessionMarkdownCopyState>;
|
|
10
|
+
};
|
|
11
|
+
dismiss: () => void;
|
|
12
|
+
}
|
|
13
|
+
/** Props of the root overlay copy notice. */
|
|
14
|
+
export type SessionMarkdownCopyToastProps = PropsRuntime<'shell.overlay'> & PropsLocale<typeof NS> & InjectFace<SessionMarkdownCopyToastInjected>;
|
|
15
|
+
/**
|
|
16
|
+
* Show the settled copy outcome outside the Session Header and menu lifetime.
|
|
17
|
+
* @param props - copy notice hook, dismissal action, and localized copy.
|
|
18
|
+
* @returns the success or failure toast, or null while no notice shows.
|
|
19
|
+
*/
|
|
20
|
+
export declare function SessionMarkdownCopyToast({ useSessionMarkdownCopy, dismiss, t, }: SessionMarkdownCopyToastProps): ReactNode;
|
|
21
|
+
//# sourceMappingURL=CopyToast.d.ts.map
|
|
@@ -1,21 +1,22 @@
|
|
|
1
|
+
/** Root overlay showing one Session export at a time in initiation order. */
|
|
1
2
|
import type { ObservableSnapshot } from '@unieai/rabi-client-store';
|
|
2
3
|
import type { SessionId } from '@unieai/rabi-session/types';
|
|
3
4
|
import type { InjectFace, PropsLocale, PropsRuntime } from '@unieai/rabi-client-ui-slots';
|
|
4
5
|
import type { SessionLogDownloadState } from './controller.ts';
|
|
5
6
|
import { NS } from './locales.ts';
|
|
6
|
-
/**
|
|
7
|
+
/** Download state and dismissal bound into the root overlay entry. */
|
|
7
8
|
export interface SessionLogDownloadDialogInjected {
|
|
8
9
|
hooks: {
|
|
9
10
|
sessionLogDownload: ObservableSnapshot<SessionLogDownloadState>;
|
|
10
11
|
};
|
|
11
|
-
request: (sessionId: SessionId) => Promise<void>;
|
|
12
12
|
dismiss: (sessionId: SessionId) => void;
|
|
13
13
|
}
|
|
14
|
-
|
|
14
|
+
/** Root runtime, localized copy, and injected download state and actions. */
|
|
15
|
+
export type SessionLogDownloadDialogProps = PropsRuntime<'shell.overlay'> & PropsLocale<typeof NS> & InjectFace<SessionLogDownloadDialogInjected>;
|
|
15
16
|
/**
|
|
16
|
-
*
|
|
17
|
-
* @param props -
|
|
18
|
-
* @returns
|
|
17
|
+
* Show the earliest open export independently of the displayed conversation.
|
|
18
|
+
* @param props - root runtime, bound controller state, dismissal, and localized copy.
|
|
19
|
+
* @returns one modal, or null when all exports are dismissed.
|
|
19
20
|
*/
|
|
20
|
-
export declare function SessionLogDownloadDialog({
|
|
21
|
+
export declare function SessionLogDownloadDialog({ useSessionLogDownload, dismiss, t, }: SessionLogDownloadDialogProps): import("react").JSX.Element | null;
|
|
21
22
|
//# sourceMappingURL=Dialog.d.ts.map
|
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
/** Browser download state shared by
|
|
1
|
+
/** Browser download operations and FIFO modal state shared by menu actions and `/export`. */
|
|
2
2
|
import { type SnapshotStore } from '@unieai/rabi-client-store';
|
|
3
3
|
import type { SessionId } from '@unieai/rabi-session/types';
|
|
4
4
|
/** Download phases presented by the shared modal. */
|
|
5
5
|
export type SessionLogDownloadStatus = 'downloading' | 'success' | 'error';
|
|
6
6
|
/** One Session's current download-dialog state. */
|
|
7
7
|
export interface SessionLogDownloadEntry {
|
|
8
|
+
/** Initiation order of this operation; repeated in-flight requests keep it. */
|
|
9
|
+
readonly order: number;
|
|
8
10
|
readonly open: boolean;
|
|
9
11
|
readonly status: SessionLogDownloadStatus;
|
|
10
12
|
readonly error: string | null;
|
|
11
13
|
}
|
|
12
|
-
/**
|
|
14
|
+
/** Authoritative download states; open entries display in initiation order across Sessions. */
|
|
13
15
|
export interface SessionLogDownloadState {
|
|
14
16
|
bySession: Record<string, SessionLogDownloadEntry | undefined>;
|
|
15
17
|
}
|
|
@@ -33,10 +35,11 @@ export declare function downloadUrl(url: string, filename: string): void;
|
|
|
33
35
|
export declare class SessionLogDownloadController {
|
|
34
36
|
private readonly fetcher;
|
|
35
37
|
private readonly save;
|
|
36
|
-
/**
|
|
38
|
+
/** Stable snapshot source for the root modal and menu availability. */
|
|
37
39
|
readonly store: SnapshotStore<SessionLogDownloadState>;
|
|
38
40
|
private readonly active;
|
|
39
41
|
private disposed;
|
|
42
|
+
private nextOrder;
|
|
40
43
|
/**
|
|
41
44
|
* @param fetcher - HTTP carrier used to read the host-streamed ZIP.
|
|
42
45
|
* @param save - browser save operation.
|
|
@@ -44,6 +47,7 @@ export declare class SessionLogDownloadController {
|
|
|
44
47
|
constructor(fetcher?: Fetch, save?: Save);
|
|
45
48
|
/**
|
|
46
49
|
* Download one Session tree; concurrent gestures for the same Session share one operation.
|
|
50
|
+
* Different Sessions run concurrently; each new operation joins the modal FIFO.
|
|
47
51
|
* @param sessionId - root Session whose ZIP includes descendants and attachments.
|
|
48
52
|
* @returns after the browser save starts, an error state is published, or a late post-disposal request is ignored.
|
|
49
53
|
*/
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser controller for the Session Header's "Copy Session as Markdown" action. One
|
|
3
|
+
* plugin instance owns one pending copy: the clipboard is a browser-wide
|
|
4
|
+
* destination, so a second request joins the pending operation instead of
|
|
5
|
+
* racing it.
|
|
6
|
+
*
|
|
7
|
+
* On hosts with `ClipboardItem` and `navigator.clipboard.write`, the controller
|
|
8
|
+
* starts that write synchronously from the click with a promised text Blob, so
|
|
9
|
+
* the browser keeps the user activation while the Host prepares the
|
|
10
|
+
* transcript. Other hosts fall back to `writeClipboard` after preparation. A
|
|
11
|
+
* disposal aborts the read and prevents later text from reaching the Blob, but
|
|
12
|
+
* an accepted operating-system clipboard write cannot be rolled back.
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
import { type SnapshotStore } from '@unieai/rabi-client-store';
|
|
16
|
+
import type { SessionId } from '@unieai/rabi-session/types';
|
|
17
|
+
/** Whether the latest copy attempt succeeded, prepared no transcript, or could not write. */
|
|
18
|
+
export type SessionMarkdownCopyNoticeKind = 'success' | 'preparationFailed' | 'clipboardFailed';
|
|
19
|
+
/** One settled copy notice; `seq` keys the toast so a repeat copy restarts it. */
|
|
20
|
+
export interface SessionMarkdownCopyNotice {
|
|
21
|
+
readonly kind: SessionMarkdownCopyNoticeKind;
|
|
22
|
+
readonly seq: number;
|
|
23
|
+
}
|
|
24
|
+
/** Copy state shared by every Header row and the root overlay toast. */
|
|
25
|
+
export interface SessionMarkdownCopyState {
|
|
26
|
+
/** Whether this plugin instance has a copy operation still pending. */
|
|
27
|
+
copying: boolean;
|
|
28
|
+
/** Latest settled copy notice, or null while none shows. */
|
|
29
|
+
notice: SessionMarkdownCopyNotice | null;
|
|
30
|
+
}
|
|
31
|
+
/** Browser clipboard operations used by one copy attempt. */
|
|
32
|
+
export interface SessionMarkdownClipboard {
|
|
33
|
+
/** Whether a deferred write can start inside the click's activation window. */
|
|
34
|
+
supportsDeferredWrite(): boolean;
|
|
35
|
+
/** Start one deferred text write; the browser observes the data promise as it settles. */
|
|
36
|
+
writeDeferred(data: Promise<Blob>): Promise<void>;
|
|
37
|
+
/** Write prepared text on hosts without the deferred API; false means the browser rejected it. */
|
|
38
|
+
writeText(text: string): Promise<boolean>;
|
|
39
|
+
}
|
|
40
|
+
/** HTTP carrier for the Markdown route. */
|
|
41
|
+
type Fetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
|
|
42
|
+
/** Owns the one pending Markdown copy for this plugin instance. */
|
|
43
|
+
export declare class SessionMarkdownCopyController {
|
|
44
|
+
private readonly fetcher;
|
|
45
|
+
private readonly clipboard;
|
|
46
|
+
/** uSES-safe state source shared by every Header row and the overlay toast. */
|
|
47
|
+
readonly store: SnapshotStore<SessionMarkdownCopyState>;
|
|
48
|
+
private pending;
|
|
49
|
+
private disposed;
|
|
50
|
+
private noticeSeq;
|
|
51
|
+
constructor(fetcher?: Fetch, clipboard?: SessionMarkdownClipboard);
|
|
52
|
+
/**
|
|
53
|
+
* Copy one Session's complete transcript. A request received while a copy is
|
|
54
|
+
* pending joins that operation and keeps its originally captured Session.
|
|
55
|
+
* @param sessionId - Session captured by the click.
|
|
56
|
+
* @returns after the clipboard work settles, a failure notice is published, or a late post-disposal request is ignored.
|
|
57
|
+
*/
|
|
58
|
+
copy(sessionId: SessionId): Promise<void>;
|
|
59
|
+
/** Clear the shown toast without affecting a pending copy. */
|
|
60
|
+
dismiss(): void;
|
|
61
|
+
/**
|
|
62
|
+
* Abort a pending read, suppress a late clipboard write or notice, and reach
|
|
63
|
+
* quiescence. A write already accepted by the operating system cannot be
|
|
64
|
+
* undone.
|
|
65
|
+
* @returns after the pending operation and any admitted clipboard work settle.
|
|
66
|
+
*/
|
|
67
|
+
dispose(): Promise<void>;
|
|
68
|
+
private run;
|
|
69
|
+
private prepare;
|
|
70
|
+
private settleDeferred;
|
|
71
|
+
private settleFallback;
|
|
72
|
+
private isCancelled;
|
|
73
|
+
private publishNotice;
|
|
74
|
+
}
|
|
75
|
+
export {};
|
|
76
|
+
//# sourceMappingURL=copy-controller.d.ts.map
|