@lincolness/ponte 0.1.0 → 0.2.0
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/CHANGELOG.md +5 -0
- package/README.md +33 -0
- package/package.json +3 -2
- package/src/env.ts +41 -0
- package/src/index.ts +17 -36
- package/src/session-tool.ts +114 -0
- package/src/sessions-pi.ts +171 -0
- package/src/sessions.ts +538 -0
- package/src/viewer.ts +344 -0
package/src/sessions.ts
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
// Sessões do pi (.jsonl) em texto limpo: sem imagens base64, assinaturas, declarações de
|
|
2
|
+
// ferramentas e saídas gigantes. Sem dependência do pi, para poder ser testado com `node --test`.
|
|
3
|
+
|
|
4
|
+
import { promises as fs } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
export type Level = "conversa" | "normal" | "completo";
|
|
8
|
+
export const LEVELS: Level[] = ["conversa", "normal", "completo"];
|
|
9
|
+
|
|
10
|
+
export interface SessionMeta {
|
|
11
|
+
file: string;
|
|
12
|
+
id: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
cwd: string;
|
|
15
|
+
created: string;
|
|
16
|
+
updated: string;
|
|
17
|
+
firstPrompt: string;
|
|
18
|
+
userTurns: number;
|
|
19
|
+
bytes: number;
|
|
20
|
+
models: string[];
|
|
21
|
+
parentSession?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type Item =
|
|
25
|
+
| { k: "user"; t: string; text: string; images: number }
|
|
26
|
+
| { k: "assistant"; t: string; model: string; text: string; thinking: string }
|
|
27
|
+
| {
|
|
28
|
+
k: "tool";
|
|
29
|
+
t: string;
|
|
30
|
+
id: string;
|
|
31
|
+
name: string;
|
|
32
|
+
summary: string;
|
|
33
|
+
detail: string;
|
|
34
|
+
output: string;
|
|
35
|
+
isError: boolean;
|
|
36
|
+
/** arquivo alterado (edit/write), para o resumo de ações */
|
|
37
|
+
changed?: string;
|
|
38
|
+
}
|
|
39
|
+
| { k: "bash"; t: string; command: string; output: string; exitCode?: number }
|
|
40
|
+
| { k: "note"; t: string; text: string; hidden: boolean }
|
|
41
|
+
| { k: "summary"; t: string; kind: "compactação" | "ramo"; text: string };
|
|
42
|
+
|
|
43
|
+
export interface LoadedSession {
|
|
44
|
+
meta: SessionMeta;
|
|
45
|
+
items: Item[];
|
|
46
|
+
/** entradas em outros ramos da árvore (não mostradas) */
|
|
47
|
+
otherBranch: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ---------------------------------------------------------------- leitura
|
|
51
|
+
|
|
52
|
+
type Entry = Record<string, any>;
|
|
53
|
+
|
|
54
|
+
async function readEntries(file: string): Promise<{ header: Entry | null; entries: Entry[]; bytes: number }> {
|
|
55
|
+
const raw = await fs.readFile(file, "utf8");
|
|
56
|
+
let header: Entry | null = null;
|
|
57
|
+
const entries: Entry[] = [];
|
|
58
|
+
for (const line of raw.split("\n")) {
|
|
59
|
+
if (!line.trim()) continue;
|
|
60
|
+
let e: Entry;
|
|
61
|
+
try {
|
|
62
|
+
e = JSON.parse(line);
|
|
63
|
+
} catch {
|
|
64
|
+
continue; // linha truncada (sessão sendo escrita)
|
|
65
|
+
}
|
|
66
|
+
if (e.type === "session") header = e;
|
|
67
|
+
else entries.push(e);
|
|
68
|
+
}
|
|
69
|
+
return { header, entries, bytes: Buffer.byteLength(raw) };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Caminho ativo: da folha até a raiz. Sem folha explícita, a última entrada gravada. */
|
|
73
|
+
function activeBranch(entries: Entry[], leafId?: string | null): Entry[] {
|
|
74
|
+
const byId = new Map<string, Entry>();
|
|
75
|
+
for (const e of entries) if (e.id) byId.set(e.id, e);
|
|
76
|
+
let cur = leafId ? byId.get(leafId) : [...entries].reverse().find((e) => e.id);
|
|
77
|
+
const path: Entry[] = [];
|
|
78
|
+
const seen = new Set<string>();
|
|
79
|
+
while (cur && !seen.has(cur.id)) {
|
|
80
|
+
seen.add(cur.id);
|
|
81
|
+
path.push(cur);
|
|
82
|
+
cur = cur.parentId ? byId.get(cur.parentId) : undefined;
|
|
83
|
+
}
|
|
84
|
+
return path.reverse();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function contentText(content: unknown): { text: string; images: number } {
|
|
88
|
+
if (typeof content === "string") return { text: content, images: 0 };
|
|
89
|
+
if (!Array.isArray(content)) return { text: "", images: 0 };
|
|
90
|
+
const parts: string[] = [];
|
|
91
|
+
let images = 0;
|
|
92
|
+
for (const b of content) {
|
|
93
|
+
if (b?.type === "text" && typeof b.text === "string") parts.push(b.text);
|
|
94
|
+
else if (b?.type === "image") {
|
|
95
|
+
images++;
|
|
96
|
+
parts.push("[imagem]");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { text: parts.join("\n"), images };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Skill expandida no pedido (<skill name="x">…</skill>) vira uma linha: o conteúdo é do pi, não seu. */
|
|
103
|
+
export function collapseSkills(text: string): string {
|
|
104
|
+
return text.replace(/<skill name="([^"]+)"[^>]*>[\s\S]*?<\/skill>\s*/g, (block, name) => {
|
|
105
|
+
const lines = block.split("\n").length;
|
|
106
|
+
return `[skill ${name} carregada, ${lines} linhas] `;
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function oneLine(s: string, max = 160): string {
|
|
111
|
+
const t = String(s ?? "").replace(/\s+/g, " ").trim();
|
|
112
|
+
return t.length > max ? t.slice(0, max - 1) + "…" : t;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Mantém começo e fim de textos longos. */
|
|
116
|
+
export function clip(s: string, maxLines: number, maxChars: number): string {
|
|
117
|
+
let text = String(s ?? "").replace(/\s+$/, "");
|
|
118
|
+
const lines = text.split("\n");
|
|
119
|
+
if (lines.length > maxLines) {
|
|
120
|
+
const head = Math.ceil(maxLines / 2);
|
|
121
|
+
const tail = maxLines - head;
|
|
122
|
+
text = [...lines.slice(0, head), `[… ${lines.length - maxLines} linha(s) omitida(s) …]`, ...lines.slice(-tail)].join("\n");
|
|
123
|
+
}
|
|
124
|
+
if (text.length > maxChars) {
|
|
125
|
+
const half = Math.floor(maxChars / 2);
|
|
126
|
+
text = `${text.slice(0, half)}\n[… ${text.length - maxChars} caractere(s) omitido(s) …]\n${text.slice(-half)}`;
|
|
127
|
+
}
|
|
128
|
+
return text;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function argPath(a: Record<string, any>): string {
|
|
132
|
+
return String(a.path ?? a.file_path ?? a.filePath ?? a.file ?? "").replace(/^@/, "");
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function describeCall(name: string, a: Record<string, any>): { summary: string; detail: string; changed?: string } {
|
|
136
|
+
const p = argPath(a);
|
|
137
|
+
switch (name) {
|
|
138
|
+
case "bash":
|
|
139
|
+
case "powershell":
|
|
140
|
+
return { summary: `$ ${oneLine(a.command ?? "", 200)}`, detail: String(a.command ?? "").includes("\n") ? String(a.command) : "" };
|
|
141
|
+
case "read": {
|
|
142
|
+
const range = a.offset || a.limit ? ` (linhas ${a.offset ?? 1}${a.limit ? `+${a.limit}` : ""})` : "";
|
|
143
|
+
return { summary: `leu ${p}${range}`, detail: "" };
|
|
144
|
+
}
|
|
145
|
+
case "edit": {
|
|
146
|
+
const edits: Array<{ oldText?: string; newText?: string }> = Array.isArray(a.edits)
|
|
147
|
+
? a.edits
|
|
148
|
+
: a.oldText !== undefined
|
|
149
|
+
? [{ oldText: a.oldText, newText: a.newText }]
|
|
150
|
+
: [];
|
|
151
|
+
const detail = edits
|
|
152
|
+
.map((e) =>
|
|
153
|
+
[
|
|
154
|
+
...String(e.oldText ?? "").split("\n").map((l) => `- ${l}`),
|
|
155
|
+
...String(e.newText ?? "").split("\n").map((l) => `+ ${l}`),
|
|
156
|
+
].join("\n"),
|
|
157
|
+
)
|
|
158
|
+
.join("\n@@\n");
|
|
159
|
+
return { summary: `editou ${p}${edits.length > 1 ? ` (${edits.length} trechos)` : ""}`, detail, changed: p };
|
|
160
|
+
}
|
|
161
|
+
case "write": {
|
|
162
|
+
const content = String(a.content ?? "");
|
|
163
|
+
const n = content ? content.split("\n").length : 0;
|
|
164
|
+
return { summary: `escreveu ${p} (${n} linhas)`, detail: content, changed: p };
|
|
165
|
+
}
|
|
166
|
+
case "grep":
|
|
167
|
+
return { summary: `grep ${oneLine(a.pattern ?? "", 80)}${p ? ` em ${p}` : ""}`, detail: "" };
|
|
168
|
+
case "find":
|
|
169
|
+
return { summary: `find ${oneLine(a.pattern ?? a.glob ?? "", 80)}${p ? ` em ${p}` : ""}`, detail: "" };
|
|
170
|
+
case "ls":
|
|
171
|
+
return { summary: `ls ${p || "."}`, detail: "" };
|
|
172
|
+
default: {
|
|
173
|
+
const json = JSON.stringify(a ?? {});
|
|
174
|
+
return { summary: `${name} ${oneLine(json, 140)}`, detail: json.length > 140 ? JSON.stringify(a, null, 2) : "" };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const OUTPUT_LINES = 80;
|
|
180
|
+
const OUTPUT_CHARS = 6000;
|
|
181
|
+
|
|
182
|
+
export async function loadSession(file: string, leafId?: string | null): Promise<LoadedSession> {
|
|
183
|
+
const { header, entries, bytes } = await readEntries(file);
|
|
184
|
+
const branch = activeBranch(entries, leafId);
|
|
185
|
+
const items: Item[] = [];
|
|
186
|
+
const tools = new Map<string, Extract<Item, { k: "tool" }>>();
|
|
187
|
+
const models = new Set<string>();
|
|
188
|
+
let name: string | undefined;
|
|
189
|
+
let firstPrompt = "";
|
|
190
|
+
let userTurns = 0;
|
|
191
|
+
|
|
192
|
+
for (const e of entries) if (e.type === "session_info" && e.name) name = e.name;
|
|
193
|
+
|
|
194
|
+
for (const e of branch) {
|
|
195
|
+
const t: string = e.timestamp ?? "";
|
|
196
|
+
switch (e.type) {
|
|
197
|
+
case "message": {
|
|
198
|
+
const m = e.message ?? {};
|
|
199
|
+
if (m.role === "user") {
|
|
200
|
+
const raw = contentText(m.content);
|
|
201
|
+
const text = collapseSkills(raw.text);
|
|
202
|
+
const images = raw.images;
|
|
203
|
+
items.push({ k: "user", t, text, images });
|
|
204
|
+
userTurns++;
|
|
205
|
+
if (!firstPrompt) firstPrompt = oneLine(text, 200);
|
|
206
|
+
} else if (m.role === "assistant") {
|
|
207
|
+
const model = m.model ? String(m.model) : "";
|
|
208
|
+
if (model) models.add(model);
|
|
209
|
+
const blocks: any[] = Array.isArray(m.content) ? m.content : [];
|
|
210
|
+
const text = blocks.filter((b) => b.type === "text").map((b) => b.text).join("\n").trim();
|
|
211
|
+
const thinking = blocks.filter((b) => b.type === "thinking" && b.thinking).map((b) => b.thinking).join("\n").trim();
|
|
212
|
+
const err = m.stopReason === "error" || m.stopReason === "aborted" ? m.errorMessage || m.stopReason : "";
|
|
213
|
+
if (text || thinking || err) {
|
|
214
|
+
items.push({ k: "assistant", t, model, text: err ? `${text}\n[resposta interrompida: ${err}]`.trim() : text, thinking });
|
|
215
|
+
}
|
|
216
|
+
for (const b of blocks) {
|
|
217
|
+
if (b.type !== "toolCall") continue;
|
|
218
|
+
const d = describeCall(b.name, b.arguments ?? {});
|
|
219
|
+
const item: Extract<Item, { k: "tool" }> = {
|
|
220
|
+
k: "tool", t, id: b.id, name: b.name, summary: d.summary, detail: d.detail, output: "", isError: false, changed: d.changed,
|
|
221
|
+
};
|
|
222
|
+
tools.set(b.id, item);
|
|
223
|
+
items.push(item);
|
|
224
|
+
}
|
|
225
|
+
} else if (m.role === "toolResult") {
|
|
226
|
+
const item = tools.get(m.toolCallId);
|
|
227
|
+
const { text } = contentText(m.content);
|
|
228
|
+
if (item) {
|
|
229
|
+
item.output = clip(text, OUTPUT_LINES, OUTPUT_CHARS);
|
|
230
|
+
item.isError = !!m.isError;
|
|
231
|
+
if (item.isError) item.changed = undefined; // edição que falhou não alterou nada
|
|
232
|
+
}
|
|
233
|
+
} else if (m.role === "bashExecution") {
|
|
234
|
+
items.push({ k: "bash", t, command: String(m.command ?? ""), output: clip(String(m.output ?? ""), OUTPUT_LINES, OUTPUT_CHARS), exitCode: m.exitCode });
|
|
235
|
+
} else if (m.role === "custom") {
|
|
236
|
+
const { text } = contentText(m.content);
|
|
237
|
+
items.push({ k: "note", t, text: `[${m.customType ?? "extensão"}] ${clip(text, 30, 3000)}`, hidden: !m.display });
|
|
238
|
+
}
|
|
239
|
+
// role "system": prompt e declarações de ferramentas — fora
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
case "custom_message": {
|
|
243
|
+
const { text } = contentText(e.content);
|
|
244
|
+
items.push({ k: "note", t, text: `[${e.customType ?? "extensão"}] ${clip(text, 30, 3000)}`, hidden: !e.display });
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
case "compaction":
|
|
248
|
+
items.push({ k: "summary", t, kind: "compactação", text: String(e.summary ?? "") });
|
|
249
|
+
break;
|
|
250
|
+
case "branch_summary":
|
|
251
|
+
items.push({ k: "summary", t, kind: "ramo", text: String(e.summary ?? "") });
|
|
252
|
+
break;
|
|
253
|
+
case "model_change":
|
|
254
|
+
if (!userTurns) break; // escolha inicial do modelo: já aparece no cabeçalho
|
|
255
|
+
items.push({ k: "note", t, text: `[modelo trocado para ${e.provider ? e.provider + "/" : ""}${e.modelId}]`, hidden: false });
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const ts = branch.map((e) => e.timestamp).filter(Boolean);
|
|
261
|
+
const meta: SessionMeta = {
|
|
262
|
+
file,
|
|
263
|
+
id: String(header?.id ?? path.basename(file, ".jsonl")),
|
|
264
|
+
name,
|
|
265
|
+
cwd: String(header?.cwd ?? ""),
|
|
266
|
+
created: String(header?.timestamp ?? ts[0] ?? ""),
|
|
267
|
+
updated: String(ts[ts.length - 1] ?? header?.timestamp ?? ""),
|
|
268
|
+
firstPrompt,
|
|
269
|
+
userTurns,
|
|
270
|
+
bytes,
|
|
271
|
+
models: [...models],
|
|
272
|
+
parentSession: header?.parentSession,
|
|
273
|
+
};
|
|
274
|
+
const onBranch = new Set(branch.map((e) => e.id));
|
|
275
|
+
return { meta, items, otherBranch: entries.filter((e) => e.id && !onBranch.has(e.id)).length };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const cache = new Map<string, { mtimeMs: number; size: number; leaf?: string | null; loaded: LoadedSession }>();
|
|
279
|
+
|
|
280
|
+
/** loadSession com cache por data/tamanho do arquivo (a versão limpa é pequena; o .jsonl, não). */
|
|
281
|
+
export async function loadSessionCached(file: string, leafId?: string | null): Promise<LoadedSession> {
|
|
282
|
+
const st = await fs.stat(file);
|
|
283
|
+
const hit = cache.get(file);
|
|
284
|
+
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size && hit.leaf === leafId) return hit.loaded;
|
|
285
|
+
const loaded = await loadSession(file, leafId);
|
|
286
|
+
cache.set(file, { mtimeMs: st.mtimeMs, size: st.size, leaf: leafId, loaded });
|
|
287
|
+
return loaded;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Sessões de uma pasta, da mais recente para a mais antiga. */
|
|
291
|
+
export async function loadAllSessions(dir: string): Promise<LoadedSession[]> {
|
|
292
|
+
let names: string[];
|
|
293
|
+
try {
|
|
294
|
+
names = (await fs.readdir(dir)).filter((n) => n.endsWith(".jsonl"));
|
|
295
|
+
} catch {
|
|
296
|
+
return [];
|
|
297
|
+
}
|
|
298
|
+
const out: LoadedSession[] = [];
|
|
299
|
+
for (const n of names) {
|
|
300
|
+
try {
|
|
301
|
+
out.push(await loadSessionCached(path.join(dir, n)));
|
|
302
|
+
} catch {
|
|
303
|
+
// arquivo ilegível: ignora
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return out.sort((a, b) => (a.meta.updated < b.meta.updated ? 1 : a.meta.updated > b.meta.updated ? -1 : 0));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export async function listSessions(dir: string): Promise<SessionMeta[]> {
|
|
310
|
+
return (await loadAllSessions(dir)).map((s) => s.meta);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Aceita: número da lista (1 = mais recente), prefixo do id, ou parte do nome/primeiro pedido. */
|
|
314
|
+
export function pickSession(list: SessionMeta[], ref: string): SessionMeta | undefined {
|
|
315
|
+
const r = ref.trim().toLowerCase();
|
|
316
|
+
if (/^\d+$/.test(r) && Number(r) >= 1 && Number(r) <= list.length) return list[Number(r) - 1];
|
|
317
|
+
return (
|
|
318
|
+
list.find((s) => s.id.toLowerCase().startsWith(r)) ??
|
|
319
|
+
list.find((s) => path.basename(s.file).toLowerCase().includes(r)) ??
|
|
320
|
+
list.find((s) => (s.name ?? "").toLowerCase().includes(r) || s.firstPrompt.toLowerCase().includes(r))
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// ---------------------------------------------------------------- texto
|
|
325
|
+
|
|
326
|
+
export function fmtDate(iso: string): string {
|
|
327
|
+
const d = new Date(iso);
|
|
328
|
+
if (Number.isNaN(d.getTime())) return iso;
|
|
329
|
+
const p = (n: number) => String(n).padStart(2, "0");
|
|
330
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function fmtTime(iso: string): string {
|
|
334
|
+
return fmtDate(iso).slice(11);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export function sessionTitle(m: SessionMeta): string {
|
|
338
|
+
return m.name || m.firstPrompt || "(sem pedidos)";
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function fence(text: string): string {
|
|
342
|
+
let max = 0;
|
|
343
|
+
for (const x of text.matchAll(/`+/g)) max = Math.max(max, x[0].length);
|
|
344
|
+
return "`".repeat(Math.max(3, max + 1));
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function block(text: string, lang = ""): string {
|
|
348
|
+
const f = fence(text);
|
|
349
|
+
return `${f}${lang}\n${text}\n${f}`;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function actionsLine(tools: Extract<Item, { k: "tool" }>[]): string {
|
|
353
|
+
const changed = [...new Set(tools.map((t) => t.changed).filter(Boolean))] as string[];
|
|
354
|
+
const read = new Set(tools.filter((t) => t.name === "read").map((t) => t.summary));
|
|
355
|
+
const cmds = tools.filter((t) => t.name === "bash" || t.name === "powershell");
|
|
356
|
+
const errors = tools.filter((t) => t.isError).length;
|
|
357
|
+
const others = tools.filter((t) => !["read", "bash", "powershell", "edit", "write"].includes(t.name));
|
|
358
|
+
const parts: string[] = [];
|
|
359
|
+
if (changed.length) parts.push(`alterou ${changed.join(", ")}`);
|
|
360
|
+
if (cmds.length) parts.push(`rodou ${cmds.length} comando(s)`);
|
|
361
|
+
if (read.size) parts.push(`leu ${read.size} arquivo(s)`);
|
|
362
|
+
if (others.length) parts.push(`${others.length} outra(s) ferramenta(s)`);
|
|
363
|
+
if (errors) parts.push(`${errors} com erro`);
|
|
364
|
+
return parts.length ? `_[ações: ${parts.join("; ")}]_` : "";
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export function renderSession(s: LoadedSession, level: Level): string {
|
|
368
|
+
const m = s.meta;
|
|
369
|
+
const out: string[] = [
|
|
370
|
+
`# Sessão: ${sessionTitle(m)}`,
|
|
371
|
+
"",
|
|
372
|
+
`- Início: ${fmtDate(m.created)} · última atividade: ${fmtDate(m.updated)}`,
|
|
373
|
+
`- Pasta: ${m.cwd}`,
|
|
374
|
+
`- Modelos: ${m.models.join(", ") || "—"} · ${m.userTurns} pedido(s) · id ${m.id}`,
|
|
375
|
+
];
|
|
376
|
+
if (s.otherBranch) out.push(`- ${s.otherBranch} entrada(s) de ramos abandonados não mostradas`);
|
|
377
|
+
out.push("");
|
|
378
|
+
|
|
379
|
+
let lastRole = "";
|
|
380
|
+
let toolLines = false;
|
|
381
|
+
let pendingTools: Extract<Item, { k: "tool" }>[] = [];
|
|
382
|
+
const flush = () => {
|
|
383
|
+
if (level === "conversa" && pendingTools.length) {
|
|
384
|
+
const line = actionsLine(pendingTools);
|
|
385
|
+
if (line) {
|
|
386
|
+
head("assistant", "Assistente", pendingTools[0].t);
|
|
387
|
+
out.push(line, "");
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
pendingTools = [];
|
|
391
|
+
};
|
|
392
|
+
const head = (role: string, label: string, t: string) => {
|
|
393
|
+
if (lastRole !== role) out.push(`### ${label} · ${fmtTime(t)}`, "");
|
|
394
|
+
lastRole = role;
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
for (const it of s.items) {
|
|
398
|
+
if (it.k === "tool") {
|
|
399
|
+
if (level === "conversa") {
|
|
400
|
+
pendingTools.push(it);
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
head("assistant", "Assistente", it.t);
|
|
404
|
+
out.push(`- ${it.isError ? "✗ " : ""}${it.summary}`);
|
|
405
|
+
toolLines = true;
|
|
406
|
+
if (level === "completo") {
|
|
407
|
+
if (it.detail) out.push(indent(block(clip(it.detail, 60, 5000), it.name === "edit" ? "diff" : "")));
|
|
408
|
+
if (it.output && !["edit", "write"].includes(it.name)) out.push(indent(block(it.output)));
|
|
409
|
+
else if (it.isError && it.output) out.push(indent(block(it.output)));
|
|
410
|
+
} else if (it.isError && it.output) {
|
|
411
|
+
out.push(indent(block(clip(it.output, 12, 1500))));
|
|
412
|
+
}
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
// mensagem do assistente só com raciocínio: não interrompe a sequência de ações
|
|
416
|
+
if (it.k === "assistant" && !it.text && level !== "completo") continue;
|
|
417
|
+
if (toolLines) {
|
|
418
|
+
out.push(""); // fecha a lista de ações
|
|
419
|
+
toolLines = false;
|
|
420
|
+
}
|
|
421
|
+
flush();
|
|
422
|
+
switch (it.k) {
|
|
423
|
+
case "user":
|
|
424
|
+
head("user", "Você", it.t);
|
|
425
|
+
out.push(it.text.trim() || "(vazio)", "");
|
|
426
|
+
break;
|
|
427
|
+
case "assistant":
|
|
428
|
+
head("assistant", `Assistente${it.model ? ` (${it.model})` : ""}`, it.t);
|
|
429
|
+
if (level === "completo" && it.thinking) {
|
|
430
|
+
out.push(clip(it.thinking, 30, 2500).split("\n").map((l) => `> ${l}`).join("\n"), "");
|
|
431
|
+
}
|
|
432
|
+
if (it.text) out.push(it.text, "");
|
|
433
|
+
break;
|
|
434
|
+
case "bash":
|
|
435
|
+
head("user", "Você", it.t);
|
|
436
|
+
out.push(`$ ${it.command}${it.exitCode ? ` (saída ${it.exitCode})` : ""}`);
|
|
437
|
+
if (level !== "conversa" && it.output) out.push(block(level === "completo" ? it.output : clip(it.output, 15, 2000)));
|
|
438
|
+
out.push("");
|
|
439
|
+
break;
|
|
440
|
+
case "note":
|
|
441
|
+
if (it.hidden && level !== "completo") break;
|
|
442
|
+
out.push(`_${oneLine(it.text, level === "completo" ? 2000 : 300)}_`, "");
|
|
443
|
+
lastRole = "";
|
|
444
|
+
break;
|
|
445
|
+
case "summary":
|
|
446
|
+
out.push(`--- ${it.kind === "compactação" ? "contexto compactado aqui; resumo do que veio antes" : "resumo de um ramo abandonado"} ---`, "");
|
|
447
|
+
out.push(level === "conversa" ? clip(it.text, 40, 4000) : it.text, "", "---", "");
|
|
448
|
+
lastRole = "";
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
flush();
|
|
453
|
+
return out.join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function indent(s: string): string {
|
|
457
|
+
return s.split("\n").map((l) => ` ${l}`).join("\n");
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export function renderMany(sessions: LoadedSession[], level: Level): string {
|
|
461
|
+
const sorted = [...sessions].sort((a, b) => (a.meta.created < b.meta.created ? -1 : 1));
|
|
462
|
+
const intro = [
|
|
463
|
+
`# Histórico de ${sorted.length} sessão(ões) do agente de código, em ordem cronológica`,
|
|
464
|
+
"",
|
|
465
|
+
"Cada sessão começa com um cabeçalho `# Sessão:`. \"Você\" é o usuário; \"Assistente\" é o agente local.",
|
|
466
|
+
level === "conversa" ? "As ações das ferramentas aparecem resumidas em linhas _[ações: …]_." : "Linhas \"- …\" são ações de ferramentas; ✗ marca as que falharam.",
|
|
467
|
+
"",
|
|
468
|
+
].join("\n");
|
|
469
|
+
return sorted.length === 1 ? renderSession(sorted[0], level) : intro + "\n" + sorted.map((s) => renderSession(s, level)).join("\n\n");
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// ---------------------------------------------------------------- busca
|
|
473
|
+
|
|
474
|
+
export interface SearchHit {
|
|
475
|
+
session: SessionMeta;
|
|
476
|
+
t: string;
|
|
477
|
+
where: string;
|
|
478
|
+
snippet: string;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function itemText(it: Item): { where: string; text: string }[] {
|
|
482
|
+
switch (it.k) {
|
|
483
|
+
case "user":
|
|
484
|
+
return [{ where: "você", text: it.text }];
|
|
485
|
+
case "assistant":
|
|
486
|
+
return [{ where: "assistente", text: it.text }];
|
|
487
|
+
case "tool":
|
|
488
|
+
return [
|
|
489
|
+
{ where: `ferramenta ${it.name}`, text: it.summary },
|
|
490
|
+
{ where: `saída de ${it.name}`, text: it.output },
|
|
491
|
+
];
|
|
492
|
+
case "bash":
|
|
493
|
+
return [{ where: "comando", text: `$ ${it.command}\n${it.output}` }];
|
|
494
|
+
case "summary":
|
|
495
|
+
return [{ where: `resumo (${it.kind})`, text: it.text }];
|
|
496
|
+
case "note":
|
|
497
|
+
return [{ where: "nota", text: it.text }];
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** Sem acento e em minúsculas, para "sessão" casar com "sessao". */
|
|
502
|
+
function norm(s: string): string {
|
|
503
|
+
return s.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "");
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Busca ranqueada: trechos com mais termos vêm primeiro. Com vários termos, aceita trechos que
|
|
508
|
+
* tenham pelo menos metade deles (modelos costumam buscar em outra língua ou com sinônimos).
|
|
509
|
+
*/
|
|
510
|
+
export function searchSessions(sessions: LoadedSession[], query: string, maxHits = 30): SearchHit[] {
|
|
511
|
+
const terms = [...new Set(norm(query).split(/\s+/).filter((t) => t.length > 1))];
|
|
512
|
+
if (!terms.length) return [];
|
|
513
|
+
const need = terms.length <= 2 ? terms.length : Math.ceil(terms.length / 2);
|
|
514
|
+
const scored: Array<SearchHit & { score: number; order: number }> = [];
|
|
515
|
+
let order = 0;
|
|
516
|
+
for (const s of sessions) {
|
|
517
|
+
for (const it of s.items) {
|
|
518
|
+
for (const { where, text } of itemText(it)) {
|
|
519
|
+
order++;
|
|
520
|
+
const low = norm(text);
|
|
521
|
+
const found = terms.filter((t) => low.includes(t));
|
|
522
|
+
if (found.length < need) continue;
|
|
523
|
+
const at = low.indexOf(found[0]);
|
|
524
|
+
const start = Math.max(0, at - 120);
|
|
525
|
+
const snippet = (start > 0 ? "…" : "") + oneLine(text.slice(start, at + 240), 360);
|
|
526
|
+
scored.push({ session: s.meta, t: it.t, where, snippet, score: found.length, order });
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
return scored
|
|
531
|
+
.sort((a, b) => b.score - a.score || a.order - b.order)
|
|
532
|
+
.slice(0, maxHits)
|
|
533
|
+
.map(({ score: _s, order: _o, ...hit }) => hit);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export function approxTokens(text: string): number {
|
|
537
|
+
return Math.round(text.length / 4);
|
|
538
|
+
}
|