Skip to content

Instantly share code, notes, and snippets.

@nineninesevenfour
Last active January 4, 2026 18:42
Show Gist options
  • Select an option

  • Save nineninesevenfour/9e63ea6cbbf4c307814614ebd8e442e8 to your computer and use it in GitHub Desktop.

Select an option

Save nineninesevenfour/9e63ea6cbbf4c307814614ebd8e442e8 to your computer and use it in GitHub Desktop.
Copilot Chat Export

Copilot Chat Export (IntelliJ + Mac)

Motivation

This Java program was created, because the GitHub Copilot plugin for IntelliJ does not provide an export functionality (as of the time of writing).

How it works

It scans the configuration files stored by the GitHub Copilot plugin under ~/.config/github-copilot and tries to extract the contents, exporting each chat as a separate markdown file.

⚠️ Important: It does not work for workspaces that are open! Every workspace you want to export the chats of, must be closed before!

Notes & Disclaimer

  • I do not take any warranty for damages caused by using this program. I tested it successfully multiple times, though.
  • It might stop working at any time with updates of the GitHub Copilot plugin.
  • It was tested for the GitHub Copilot IntelliJ plugin on Mac. It wasn't tested on Windows. Feel free to adapt it to your needs.
  • The exported files will be written in a folder chat-export under the current folder, where the program is running. It creates markdown files named YYYY-MM-DD_<Title_of_chat>.md.
  • It will overwrite previously created files with the same name (this is intentional to be able to repeat the export multiple times), however if by chance there are two or more equally named chats from the same date found in the same run, they will receive a sequential number in the end and NOT be overwritten.
  • It detects chats of mode "Ask" and "Agent". I think it does not support chats of mode "Edit" or "Plan".
  • Empty chats are skipped.
  • The user's chat message might not be 100% identical to the original due to some markdown reformatting.
  • Chats of the currently open workspaces can not be exported, because those configrations are locked. There will be an error logged, which you can ignore.
  • Older chats will probably not have the model name in the output.

How to use

  • Download the files of this Gist into a folder.
  • Adapt to Maven outline:
    • Move the file CopilotChatExport.java to the subfolder src/main/java/com/example
    • Move the file chat_template.th to the subfolder src/main/resources
  • Import as Maven project into the IDE of your choice.
  • Compile and run.
  • Hint: Use a new workspace for running to be able to access all previous Copilot chats.

Styled Template (Alternative)

There is a second template chat_template_styled.th in this Gist. It is optimized for dark mode.

To use it, either adapt method exportChat in the source code, or exchange it with chat_template.th. If it works for you, will depend on the markdown viewer used (tested with IntelliJ and VSCode).

Dependencies Used

Gist TOC

You need at least the three files marked with 👉.

Sample Output

Java Hello World Program

  • User: nineninesevenfour
  • Start: 2025-12-22 15:17:45
  • End / Last Change: 2025-12-22 15:18:57

Request:

  • Mode: Ask

Hello

Response:

  • Model: Claude Sonnet 4.5

  • References:

    • ~/my-workspaces/workspace1/.gitignore
  • Steps:

    • ✅ Collecting context
    • ✅ Reading git information
    • ✅ Analyzing problems and errors
    • ✅ Reading runtime logs
    • ✅ Generating response

Hello! How can I assist you with your code or any technical questions you might have?


Request:

Please give me a hello world Java main

Response:

Sure, here is a simple "Hello, World!" program in Java:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

This program defines a class named HelloWorld. Inside this class, there is a single method main. This method is the entry point for any Java application. The System.out.println("Hello, World!"); statement is used to print the string "Hello, World!" to the console.


End of Chat

Sample Output with Styled Template

image

# [(${chat.name})]
* **User:** [(${chat.user})]
* **Start:** [(${#dates.format(chat.createdAt, 'yyyy-MM-dd HH:mm:ss')})]
* **End / Last Change:** [(${#dates.format(chat.modifiedAt, 'yyyy-MM-dd HH:mm:ss')})]
---
[# th:each="turn : ${chat.turns}"]
_**Request:**_
[# th:if="${turn.chatModeChanged}"]
* **Mode:** [(${turn.chatMode})]
[/][# th:each="line : ${escapedMarkdownLines.apply(turn.request)}"]
> [(${line})]
[/]
_**Response:**_
[# th:if="${turn.modelChanged}"]
* **Model:** [(${turn.modelName})]
[/][# th:if="${turn.referencesChanged && !turn.references.isEmpty()}"]
* **References:** [# th:each="reference : ${turn.references}"]
* [ [(${reference.name})] ]([(${reference.uri})])
[/][/][# th:if="${!turn.steps.isEmpty()}"]
* **Steps:** [# th:each="step : ${turn.steps}"]
* [(${stepStatusToSymbol.apply(step.status)})] [(${step.title})][# th:if="${step.errorMessage != null}"]<br /><span style="color: red">[(${step.errorMessage})]</span>[/]
[/][/]
[(${turn.response})]
---
[/]_**End of Chat**_
<style>
@font-face {
font-family: 'MonaspaceNeon';
src: url('https://cdn.jsdelivr.net/gh/githubnext/monaspace@v1.200/fonts/webfonts/MonaspaceNeon-Regular.woff');
}
@font-face {
font-family: 'MonaspaceArgon';
src: url('https://cdn.jsdelivr.net/gh/githubnext/monaspace@v1.200/fonts/webfonts/MonaspaceArgon-Regular.woff');
}
body {
background-color: #10131AFF;
zoom: 1.1;
}
*::selection {
background-color: rgba(174,41,147,0.55);
}
hr {
margin-top: 1.2rem;
margin-bottom: 1.2rem;
}
.chat-meta {
display: flex;
flex-direction: row;
align-items: end;
}
@media (max-width: 48em) {
.chat-meta {
flex-direction: column;
align-items: start;
}
}
.chat-meta > h1 {
flex: 3;
margin-right: 1rem;
margin-bottom: 0;
border-bottom: none;
}
.chat-meta > ul {
flex: 1.5;
border: 2px solid #4eb3c1;;
border-radius: 10px;
padding: 10px 10px 10px 1.8rem;
margin-bottom: 0;
}
blockquote {
background-color: #252B5E;
padding: 10px 10px 10px 1rem;
margin-bottom: 1rem;
border: none;
margin-left: 10%;
border-radius: 10px;
text-shadow: 1px 1px 3px black;
filter: brightness(1.1);
}
blockquote > p {
margin-top: 0;
margin-bottom: 0.5em;
}
blockquote > p:last-child {
margin-bottom: 0;
}
.response-meta {
margin-bottom: 1rem;
}
.response-meta > ul {
background-color: #23272E;
border-radius: 10px;
padding: 10px 10px 10px 1.8rem;
margin-left: 10%;
line-height: 1.5;
}
.response-meta > ul > li > p {
margin-bottom: 0;
}
.response-meta > ul > li > ul {
margin-bottom: 0;
}
pre, code {
font-size: 1em;
font-family: "MonaspaceNeon", monospace;
}
pre {
border-radius: 10px !important;
background-color: #23272E;
}
code {
color: #4eb3c1;
}
h1, h2, h3 {
font-family: "MonaspaceArgon", monospace;
filter: brightness(1.1);
}
</style>
<section class="chat-meta">
# [(${chat.name})]
* **User:** [(${chat.user})]
* **Start:** [(${#dates.format(chat.createdAt, 'yyyy-MM-dd HH:mm:ss')})]
* **End / Last Change:** [(${#dates.format(chat.modifiedAt, 'yyyy-MM-dd HH:mm:ss')})]
</section>
---
[# th:each="turn : ${chat.turns}"]
[# th:each="line : ${escapedMarkdownLines.apply(turn.request)}"]
> [(${line})]
[/]<section class="response-meta">
[# th:if="${turn.chatModeChanged}"]
* **Mode:** [(${turn.chatMode})]
[/][# th:if="${turn.modelChanged}"]
* **Model:** [(${turn.modelName})]
[/][# th:if="${turn.referencesChanged && !turn.references.isEmpty()}"]
* **References:** [# th:each="reference : ${turn.references}"]
* [ [(${reference.name})] ]([(${reference.uri})])
[/][/][# th:if="${!turn.steps.isEmpty()}"]
* **Steps:** [# th:each="step : ${turn.steps}"]
* [(${stepStatusToSymbol.apply(step.status)})] [(${step.title})][# th:if="${step.errorMessage != null}"]<br /><span style="color: red">[(${step.errorMessage})]</span>[/]
[/][/]</section>
[(${turn.response})]
---
[/]_**End of Chat**_
/*
* Copyright 2025 nineninesevenfour
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.dizitart.no2.collection.Document;
import org.h2.mvstore.MVStore;
import org.h2.mvstore.MVStoreException;
import org.slf4j.Logger;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CopilotChatExport {
private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(CopilotChatExport.class);
private static final Pattern ESCAPE_PATTERN = Pattern.compile("`[^`]*`|([\\\\*_{}\\[\\]()#+-.!|<>$])");
private static final Pattern LEADING_SPACES = Pattern.compile("^( +)");
private static final SimpleDateFormat FILENAME_DATE = new SimpleDateFormat("yyyy-MM-dd");
private static final Pattern NON_ALPHABETIC_OR_NUMERIC = Pattern.compile("[^\\p{L}\\p{N}]+");
private static final Pattern LEADING_TRAILING_UNDERSCORES = Pattern.compile("^_+|_+$");
private static final Map<String, Integer> FILE_COUNTERS = new HashMap<>();
record Chat(
String id,
String name,
String user,
Date createdAt,
Date modifiedAt,
List<Turn> turns
) {}
record Turn(
String sessionId,
Date createdAt,
String chatMode,
boolean chatModeChanged,
String modelName,
boolean modelChanged,
String request,
String response,
List<Reference> references,
boolean referencesChanged,
List<Step> steps
) {}
record Reference(String name, String uri) {}
record Step(String title, String status, String errorMessage) {}
private static String USER_HOME;
private static String USER_HOME_FILE_URL;
private static TemplateEngine templateEngine;
public static void main(String[] args) throws IOException {
USER_HOME = System.getenv("HOME");
USER_HOME_FILE_URL = "^" + Pattern.quote("file://" + USER_HOME);
final Path copilotConfig = Paths.get(USER_HOME, ".config/github-copilot");
if (!Files.exists(copilotConfig)) {
LOGGER.error("no copilot config found, exiting.");
return;
}
templateEngine = createTemplateEngine();
final Path outputFolder = Paths.get(".", "chat-export");
Files.createDirectories(outputFolder);
final int[] sessions = {0, 0};
Files.walkFileTree(copilotConfig, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().equals("copilot-agent-sessions-nitrite.db")) {
String logFilePath = file.toAbsolutePath().toString().replaceFirst(USER_HOME, "~");
LOGGER.info("Database file found: {}", logFilePath);
sessions[0]++;
sessions[1] += exportAgentSessions(outputFolder, file);
}
return FileVisitResult.CONTINUE;
}
});
LOGGER.info("Sessions found: {}, skipped: {}", sessions[0], sessions[1]);
}
private static int exportAgentSessions(Path outputFolder, Path dbPath) throws IOException {
String dbPathAbsolute = dbPath.toAbsolutePath().toString();
List<Chat> chats = readAgentSessions(dbPathAbsolute);
int skipped = 0;
for (Chat chat : chats) {
if (!chat.turns.isEmpty()) {
String markdownChat = exportChat(chat);
Path fileName = createFileName(outputFolder, chat);
Files.writeString(fileName, markdownChat);
} else {
LOGGER.info("No turns found for chat with title \"{}\", skipping it.", chat.name);
skipped++;
}
}
return skipped;
}
private static Path createFileName(Path outputFolder, Chat chat) {
String chatNameCleared1 = NON_ALPHABETIC_OR_NUMERIC.matcher(chat.name).replaceAll("_");
String chatNameCleared2 = LEADING_TRAILING_UNDERSCORES.matcher(chatNameCleared1).replaceAll("");
String filename = FILENAME_DATE.format(chat.createdAt) + "_" + chatNameCleared2;
Integer number = FILE_COUNTERS.compute(filename, (_, v) -> v == null ? 0 : v + 1);
if (number > 0) {
filename += "_" + number;
}
return outputFolder.resolve(filename + ".md");
}
private static List<Chat> readAgentSessions(String path) {
List<Chat> chats = new ArrayList<>();
try (var mvStore = new MVStore.Builder().fileName(path).readOnly().open()) {
Map<String, List<Turn>> turnsBySessionId = getTurnsBySessionId(mvStore);
getSessions(mvStore, chats, turnsBySessionId);
} catch (MVStoreException e) {
LOGGER.error("unable to open {}", path, e);
return List.of();
}
return chats;
}
private static Map<String, List<Turn>> getTurnsBySessionId(MVStore mvStore) {
var agentTurnMap = mvStore.openMap("com.github.copilot.agent.session.persistence.nitrite.entity.NtAgentTurn");
return processTurns(agentTurnMap.values()).stream()
.sorted(Comparator.comparing(turn -> turn.sessionId + "|" + turn.createdAt.getTime()))
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(turn -> turn.sessionId), markTurnsFunction()));
}
private static Function<Map<String, List<Turn>>, Map<String, List<Turn>>> markTurnsFunction() {
return map -> {
map.replaceAll((_, turns) -> markTurnsOfSession(turns));
return map;
};
}
@SuppressWarnings("unchecked")
private static void getSessions(MVStore mvStore, List<Chat> chats, Map<String, List<Turn>> turnsBySessionId) {
var agentSessionMap = mvStore.openMap("com.github.copilot.agent.session.persistence.nitrite.entity.NtAgentSession");
for (Object value : agentSessionMap.values()) {
if (value instanceof Document document) {
String chatId = document.get("id", String.class);
String name = document.get("name.value", String.class);
String user = document.get("user", String.class);
Date createdAt = new Date(document.get("createdAt", Long.class));
Date modifiedAt = new Date(document.get("modifiedAt", Long.class));
List<Turn> chatTurns;
List<Object> nestedTurns = document.get("turns", List.class);
if (nestedTurns != null && !nestedTurns.isEmpty()) {
chatTurns = markTurnsOfSession(processTurns(nestedTurns));
} else {
chatTurns = turnsBySessionId.getOrDefault(chatId, List.of());
}
Chat chat = new Chat(chatId, name, user, createdAt, modifiedAt, chatTurns);
chats.add(chat);
}
}
}
private static List<Turn> markTurnsOfSession(List<Turn> turns) {
List<Turn> markedTurns = new ArrayList<>();
String previousChatMode = "";
String previousModelName = "";
List<Reference> previousReferences = List.of();
for (Turn turn : turns) {
String chatMode = turn.chatMode;
boolean chatModeChanged = chatMode != null && !previousChatMode.equals(chatMode);
previousChatMode = chatMode != null ? chatMode : "";
String modelName = turn.modelName;
boolean modelChanged = modelName != null && !previousModelName.equals(modelName);
previousModelName = modelName != null ? modelName : "";
var references = turn.references;
boolean referencesChanged = !previousReferences.equals(references);
previousReferences = references;
Turn markedTurn = new Turn(turn.sessionId, turn.createdAt, turn.chatMode, chatModeChanged,
turn.modelName, modelChanged, turn.request, turn.response, turn.references, referencesChanged,
turn.steps);
markedTurns.add(markedTurn);
}
return markedTurns;
}
private static List<Turn> processTurns(Collection<Object> turns) {
List<Turn> result = new ArrayList<>();
for (Object turn : turns) {
if (turn instanceof Document document) {
Long deletedAt = document.get("deletedAt", Long.class);
if (deletedAt != null) {
continue;
}
String sessionId = document.get("sessionId", String.class);
Date createdAt = new Date(document.get("createdAt", Long.class));
String chatMode = document.get("request.chatMode", String.class);
String modelName = document.get("response.modelInformation.modelName", String.class);
String requestString = document.get("request.stringContent", String.class);
String requestContent = document.get("request.contents", String.class);
Optional<JsonNode> requestJson = parseJson(requestContent);
String request = requestJson.map(jsonNode -> oneOrTheOther(requestString, jsonNode)).orElse(requestString);
String responseString = document.get("response.stringContent", String.class);
String responseContent = document.get("response.contents", String.class);
Optional<JsonNode> responseJson = parseJson(responseContent);
String response = responseJson.map(jsonNode -> oneOrTheOther(responseString, jsonNode)).orElse(responseString);
var references = responseJson.map(CopilotChatExport::getReferences).orElseGet(List::of);
var steps = responseJson.map(CopilotChatExport::getSteps).orElseGet(List::of);
Turn chatTurn = new Turn(sessionId, createdAt, chatMode, false,
modelName, false, request, response, references, false, steps);
result.add(chatTurn);
}
}
return result;
}
private static Optional<JsonNode> parseJson(String jsonString) {
if (jsonString == null || jsonString.isEmpty()) {
return Optional.empty();
}
if (jsonString.startsWith("{")) {
try {
return Optional.ofNullable(readTree(jsonString));
} catch (JsonProcessingException e) {
LOGGER.error("Error reading JSON", e);
}
}
return Optional.empty();
}
private static List<Reference> getReferences(JsonNode jsonNode) {
return getSubgraphData(jsonNode)
.filter(entry -> "References".equals(entry.getKey()))
.filter(entry -> entry.getValue().isArray())
.flatMap(entry -> entry.getValue().valueStream())
.map(node -> asSubNode(node, "type", "reference"))
.filter(Optional::isPresent)
.map(Optional::get)
.map(entry -> getTextualNode(entry.getValue(), "uri")
.map(uri -> new Reference(uri.replaceFirst(USER_HOME_FILE_URL, "~"), uri)))
.filter(Optional::isPresent)
.map(Optional::get)
.toList();
}
private static List<Step> getSteps(JsonNode jsonNode) {
return getSubgraphData(jsonNode)
.filter(entry -> "Steps".equals(entry.getKey()))
.filter(entry -> entry.getValue().isArray())
.flatMap(entry -> entry.getValue().valueStream())
.map(node -> {
String errorMessage = null;
if (node.has("error")) {
JsonNode errorNode = node.get("error");
if (errorNode.has("message")) {
errorMessage = errorNode.get("message").asText();
}
}
return new Step(node.get("title").asText(), node.get("status").asText(), errorMessage);
})
.toList();
}
private static Stream<Map.Entry<String, JsonNode>> getSubgraphData(JsonNode jsonNode) {
return jsonNode.propertyStream()
.map(property -> asSubNode(property.getValue(), "type", "value").orElse(property))
.filter(entry -> "Subgraph".equals(entry.getKey()))
.flatMap(entry -> entry.getValue().propertyStream())
.map(property -> asSubNode(property.getValue(), "type", "value").orElse(property))
.filter(entry -> "Value".equals(entry.getKey()))
.map(property -> asSubNode(property.getValue(), "type", "data").orElse(property));
}
private static String oneOrTheOther(String firstOption, JsonNode secondOption) {
if (firstOption != null && !firstOption.isEmpty()) {
return firstOption;
}
return getText(secondOption);
}
private static String getText(JsonNode jsonNode) {
String text = jsonNode.propertyStream()
.map(property -> asSubNode(property.getValue(), "type", "value").orElse(property))
.filter(entry -> "Value".equals(entry.getKey()))
.map(entry -> asSubNode(entry.getValue(), "type", "data").orElse(entry))
.filter(entry -> "Markdown".equals(entry.getKey()))
.map(CopilotChatExport::valueAsText)
.findFirst().orElse("");
if (text.isEmpty()) {
text = jsonNode.propertyStream()
.map(property -> asSubNode(property.getValue(), "type", "value").orElse(property))
.filter(entry -> "Value".equals(entry.getKey()))
.map(entry -> asSubNode(entry.getValue(), "type", "data").orElse(entry))
.filter(entry -> "AgentRound".equals(entry.getKey()))
.map(entry -> asSubNode(entry.getValue(), "roundId", "reply").orElse(entry))
.map(CopilotChatExport::valueAsText)
.collect(Collectors.joining(" \n"));
}
return text;
}
private static String valueAsText(Map.Entry<String, JsonNode> entry) {
if (entry.getValue() instanceof ObjectNode objectNode) {
return objectNode.get("text").asText();
} else if (entry.getValue().isTextual()) {
return entry.getValue().asText();
} else {
return "";
}
}
@SuppressWarnings("SameParameterValue")
private static Optional<String> getTextualNode(JsonNode jsonNode, String key) {
if (jsonNode instanceof ObjectNode && jsonNode.has(key) && jsonNode.get(key).isTextual()) {
String text = jsonNode.get(key).asText();
return text.isEmpty() ? Optional.empty() : Optional.of(text);
}
return Optional.empty();
}
private static Optional<Map.Entry<String, JsonNode>> asSubNode(JsonNode jsonNode, String typeKey, String valueKey) {
if (jsonNode instanceof ObjectNode objectNode) {
String type = objectNode.get(typeKey).asText();
JsonNode valueNode = objectNode.get(valueKey);
return Optional.of(Map.entry(type, valueNode));
} else {
return Optional.empty();
}
}
private static JsonNode readTree(String documentField) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(documentField);
processChildren(objectMapper, jsonNode);
return jsonNode;
}
private static void processChildren(ObjectMapper objectMapper, JsonNode jsonNode) throws JsonProcessingException {
Iterator<String> fieldNames = jsonNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
processNode(objectMapper, fieldName, jsonNode);
}
}
private static void processNode(ObjectMapper objectMapper, String fieldName, JsonNode jsonNode) throws JsonProcessingException {
JsonNode childNode = jsonNode.get(fieldName);
if (childNode == null) {
return;
}
if ((fieldName.equals("value") || fieldName.equals("data"))
&& childNode.isTextual()
&& (childNode.asText().startsWith("{") || childNode.asText().startsWith("["))) {
JsonNode subNode = objectMapper.readTree(childNode.asText());
if (subNode.isArray()) {
ArrayNode arrayNode = objectMapper.createArrayNode();
processElements(objectMapper, subNode, arrayNode);
((ObjectNode)jsonNode).replace(fieldName, arrayNode);
} else {
((ObjectNode)jsonNode).replace(fieldName, subNode);
processChildren(objectMapper, subNode);
}
} else {
processChildren(objectMapper, childNode);
}
}
private static void processElements(ObjectMapper objectMapper, JsonNode subNode, ArrayNode arrayNode) throws JsonProcessingException {
for (JsonNode node : subNode) {
if (node.isTextual() && node.asText().startsWith("{")) {
JsonNode elementNode = objectMapper.readTree(node.asText());
processChildren(objectMapper, elementNode);
arrayNode.add(elementNode);
} else {
arrayNode.add(node);
}
}
}
private static TemplateEngine createTemplateEngine() {
var resolver = new ClassLoaderTemplateResolver();
resolver.setTemplateMode(TemplateMode.TEXT);
var engine = new TemplateEngine();
engine.setTemplateResolver(resolver);
return engine;
}
private static String exportChat(Chat chat) {
var context = new Context();
context.setVariable("chat", chat);
context.setVariable("escapedMarkdownLines", escapedMarkdownLines());
context.setVariable("stepStatusToSymbol", stepStatusToSymbol());
return templateEngine.process("chat_template.th", context);
}
private static Function<String, List<String>> escapedMarkdownLines() {
return text -> {
String[] lines = text.split("\n");
boolean inCodeBlockFenced = false;
boolean inCodeBlock = false;
boolean wasEmptyLine = false;
int i = 0;
List<String> escapedLines = new ArrayList<>();
for (String line : lines) {
// set status for fenced code blocks marked with ```
boolean wasInCodeBlockFenced = inCodeBlockFenced;
inCodeBlockFenced = inCodeBlockFenced || line.startsWith("```");
// set status for code blocks marked with >= 4 spaces
inCodeBlock = line.startsWith(" ") && (inCodeBlock || wasEmptyLine);
// do not escape lines of code blocks
if (inCodeBlockFenced || inCodeBlock) {
// add line
escapedLines.add(line);
} else {
// escape
String escaped = ESCAPE_PATTERN.matcher(line).replaceAll(match -> {
String result = match.group(1) == null
? match.group(0)
: "\\" + match.group(1);
return Matcher.quoteReplacement(result);
});
// preserve leading spaces
escaped = LEADING_SPACES.matcher(escaped).replaceAll(match ->
match.group(0).replace(" ", "&nbsp;"));
// append two spaces for visible line breaks (except on empty lines or the end)
String suffix = line.trim().isEmpty() || i == lines.length - 1 ? "" : " ";
// add line
escapedLines.add(escaped + suffix);
}
// reset fenced code block status
if (wasInCodeBlockFenced && line.startsWith("```")) {
inCodeBlockFenced = false;
}
wasEmptyLine = line.trim().isEmpty();
i++;
}
return escapedLines;
};
}
private static Function<String, String> stepStatusToSymbol() {
return stepStatus -> switch (stepStatus) {
case "completed" -> "&#x2705;";
case "failed" -> "&#x274C;";
default -> "<" + stepStatus + ">";
};
}
}
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>copilot-chat-export</artifactId>
<version>1.0-SNAPSHOT</version>
<developers>
<developer>
<name>nineninesevenfour</name>
<url>https://github.com/nineninesevenfour</url>
</developer>
</developers>
<licenses>
<license>
<name>Apache-2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0</url>
<distribution>see also LINCENSE.txt</distribution>
</license>
</licenses>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.dizitart</groupId>
<artifactId>nitrite</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2-mvstore</artifactId>
<version>2.4.240</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.20.1</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.17</version>
</dependency>
</dependencies>
</project>
@billrobertson42
Copy link

asSubNode() was throwing NPE's on the value for the cancelled check. To get around this, I modified the function to fake it.

    private static Optional<Map.Entry<String, JsonNode>> asSubNode(JsonNode jsonNode, String typeKey, String valueKey) {
        if (jsonNode instanceof ObjectNode objectNode) {
            String type = objectNode.get(typeKey).asText();
            JsonNode valueNode = objectNode.get(valueKey);

            // added if statement
            if("Cancelled".equals(jsonNode.get(typeKey).textValue()) && valueNode == null) {
                valueNode = BooleanNode.FALSE;
            }

            return Optional.of(Map.entry(type, valueNode));
        } else {
            return Optional.empty();
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment