Repository navigation
Expand file tree
/
Copy paththreadTranscript.ts
More file actions
177 lines (163 loc) · 6.1 KB
/
Copy paththreadTranscript.ts
File metadata and controls
177 lines (163 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
import * as DateTime from "effect/DateTime";
import { deriveTimelineEntriesFromVisibleTurnItems, type WorkLogEntry } from "../session-logic";
import type { ChatMessage } from "../types";
import { resolveUserMessageContext } from "./composerContextRecords";
/** Concise keeps the conversation; full adds the work log and proposed plans. */
export type TranscriptDetail = "concise" | "full";
export interface ThreadTranscript {
readonly markdown: string;
readonly messageCount: number;
readonly toolCallCount: number;
}
type TranscriptItem =
| { readonly kind: "user" | "assistant"; readonly text: string }
| { readonly kind: "work"; readonly entry: WorkLogEntry }
| { readonly kind: "plan"; readonly markdown: string };
function userMessageText(message: ChatMessage): string {
// Inline context chips are links to records only T3 can resolve; keep their labels.
const text = replaceComposerContextReferences(
resolveUserMessageContext(message).text,
(reference) => (reference.image ? `[image: ${reference.label}]` : reference.label),
).trim();
const unmentioned = (message.attachments ?? [])
.filter((attachment) => !text.includes(attachment.name))
.map((attachment) => `[${attachment.type}: ${attachment.name}]`);
return [text, ...unmentioned].filter((part) => part.length > 0).join("\n\n");
}
/** Inline code that survives backticks inside the value. */
function inlineCode(value: string): string {
const singleLine = value.replace(/\s+/g, " ").trim();
return singleLine.includes("`") ? `\`\` ${singleLine} \`\`` : `\`${singleLine}\``;
}
function formatWorkEntry(entry: WorkLogEntry): string {
let line = `- **${entry.label}**`;
if (entry.command) {
line += ` ${inlineCode(entry.command)}`;
} else if (entry.detail && !entry.detail.includes("\n") && entry.detail.length <= 200) {
line += ` — ${entry.detail}`;
}
if (entry.changedFiles && entry.changedFiles.length > 0) {
line += `: ${entry.changedFiles.map(inlineCode).join(", ")}`;
}
return line;
}
function yamlString(value: string): string {
return JSON.stringify(value);
}
function formatHeader(input: {
readonly projection: OrchestrationV2ThreadProjection;
readonly projectTitle: string | null;
readonly exportedAt: Date;
}): string {
const { thread } = input.projection;
const lines = [
`thread: ${yamlString(thread.title)}`,
...(input.projectTitle ? [`project: ${yamlString(input.projectTitle)}`] : []),
...(thread.branch ? [`branch: ${yamlString(thread.branch)}`] : []),
`provider: ${yamlString(thread.modelSelection.instanceId)}`,
`model: ${yamlString(thread.modelSelection.model)}`,
`created: ${DateTime.formatIso(thread.createdAt)}`,
`exported: ${input.exportedAt.toISOString()}`,
];
return ["---", ...lines, "---"].join("\n");
}
/** Messages, plans, and work in the order the thread's timeline shows them. */
function transcriptItems(
projection: OrchestrationV2ThreadProjection,
detail: TranscriptDetail,
): TranscriptItem[] {
const entries = deriveTimelineEntriesFromVisibleTurnItems({
visibleTurnItems: projection.visibleTurnItems,
optimisticMessages: [],
attempts: projection.attempts,
nodes: projection.nodes,
plans: projection.plans,
});
const items: TranscriptItem[] = [];
for (const entry of entries) {
switch (entry.kind) {
case "message": {
const { message } = entry;
if (message.role !== "user" && message.role !== "assistant") break;
const text = message.role === "user" ? userMessageText(message) : message.text.trim();
if (text.length > 0) items.push({ kind: message.role, text });
break;
}
case "proposed-plan":
if (detail === "full") {
items.push({ kind: "plan", markdown: entry.proposedPlan.planMarkdown });
}
break;
case "work":
// Reasoning is always left out.
if (detail === "full" && entry.entry.tone !== "thinking") {
items.push({ kind: "work", entry: entry.entry });
}
break;
case "event":
break;
}
}
return items;
}
/**
* Renders a thread as Markdown for pasting into another app. Reasoning is
* always left out; `full` interleaves the work log (tool calls, commands, file
* edits) and proposed plans in timeline order.
*/
export function buildThreadTranscript(input: {
readonly projection: OrchestrationV2ThreadProjection;
readonly projectTitle: string | null;
readonly detail: TranscriptDetail;
readonly includeHeader: boolean;
readonly exportedAt: Date;
}): ThreadTranscript {
const items = transcriptItems(input.projection, input.detail);
const blocks: string[] = [];
if (input.includeHeader) blocks.push(formatHeader(input));
blocks.push(`# ${input.projection.thread.title}`);
let speaker: "user" | "assistant" | null = null;
let workLines: string[] = [];
let messageCount = 0;
let toolCallCount = 0;
const flushWork = () => {
if (workLines.length === 0) return;
blocks.push(workLines.join("\n"));
workLines = [];
};
for (const item of items) {
const itemSpeaker = item.kind === "user" ? "user" : "assistant";
if (itemSpeaker !== speaker) {
flushWork();
blocks.push(itemSpeaker === "user" ? "## User" : "## Assistant");
speaker = itemSpeaker;
}
if (item.kind === "work") {
toolCallCount += 1;
workLines.push(formatWorkEntry(item.entry));
continue;
}
flushWork();
if (item.kind === "plan") {
blocks.push(`### Plan\n\n${item.markdown.trim()}`);
} else {
messageCount += 1;
blocks.push(item.text);
}
}
flushWork();
return { markdown: `${blocks.join("\n\n")}\n`, messageCount, toolCallCount };
}
/** A filesystem-safe `.md` name from the thread title. */
export function transcriptFileName(title: string): string {
const slug = title
.toLowerCase()
.normalize("NFKD")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 80)
.replace(/-+$/, "");
return `${slug || "transcript"}.md`;
}