@lincolness/ponte 0.0.0-stage → 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.
@@ -0,0 +1,114 @@
1
+ // Lógica da ferramenta ponte_sessoes e acesso às sessões do projeto atual.
2
+ // Sem typebox nem código do pi em tempo de execução, para poder ser testada com `node --test`.
3
+
4
+ import path from "node:path";
5
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ fmtDate,
8
+ loadAllSessions,
9
+ loadSessionCached,
10
+ pickSession,
11
+ renderMany,
12
+ searchSessions,
13
+ sessionTitle,
14
+ type Level,
15
+ type LoadedSession,
16
+ } from "./sessions.ts";
17
+
18
+ type Ctx = Pick<ExtensionContext, "sessionManager">;
19
+
20
+ let agentDir = "";
21
+
22
+ /** Chamado na carga da extensão com o getAgentDir() do pi (respeita diretório customizado). */
23
+ export function setAgentDir(dir: string) {
24
+ agentDir = dir;
25
+ }
26
+
27
+ /** Mesma regra do pi: ~/.pi/agent/sessions/--<cwd com / \\ : trocados por ->--/ */
28
+ export function defaultSessionDir(cwd: string, base: string): string {
29
+ const safe = `--${path.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
30
+ return path.join(base, "sessions", safe);
31
+ }
32
+
33
+ function sessionDir(ctx: Ctx): string {
34
+ const dir = ctx.sessionManager.getSessionDir();
35
+ if (dir) return dir;
36
+ // sessão só em memória (--no-session, pi -p em scripts): usa a pasta padrão do projeto
37
+ return agentDir ? defaultSessionDir(ctx.sessionManager.getCwd(), agentDir) : "";
38
+ }
39
+
40
+ /** Todas as sessões do projeto; a atual usa a folha em que você está agora. */
41
+ export async function allSessions(ctx: Ctx): Promise<LoadedSession[]> {
42
+ const list = await loadAllSessions(sessionDir(ctx));
43
+ const current = ctx.sessionManager.getSessionFile();
44
+ if (!current) return list;
45
+ try {
46
+ const cur = await loadSessionCached(current, ctx.sessionManager.getLeafId());
47
+ return list.map((s) => (s.meta.file === current ? cur : s));
48
+ } catch {
49
+ return list;
50
+ }
51
+ }
52
+
53
+ export async function currentSession(ctx: Ctx): Promise<LoadedSession | null> {
54
+ const file = ctx.sessionManager.getSessionFile();
55
+ if (!file) return null;
56
+ try {
57
+ return await loadSessionCached(file, ctx.sessionManager.getLeafId());
58
+ } catch {
59
+ return null; // sessão ainda sem nada gravado
60
+ }
61
+ }
62
+
63
+ /** Exportada para teste. Só usa ctx.sessionManager. */
64
+ export async function runTool(
65
+ ctx: Ctx,
66
+ p: { action: string; session?: string; query?: string; level?: Level; offset?: number; max_chars?: number },
67
+ ): Promise<string> {
68
+ const all = await allSessions(ctx);
69
+ if (!all.length) return "No saved sessions for this project.";
70
+ const current = ctx.sessionManager.getSessionFile();
71
+
72
+ if (p.action === "list") {
73
+ return [
74
+ `${all.length} session(s), newest first:`,
75
+ ...all.map(
76
+ (s, i) =>
77
+ `${i + 1}. ${fmtDate(s.meta.created)} → ${fmtDate(s.meta.updated)} | ${s.meta.userTurns} request(s) | id ${s.meta.id.slice(0, 8)}${s.meta.file === current ? " | CURRENT" : ""}\n ${sessionTitle(s.meta).slice(0, 200)}`,
78
+ ),
79
+ ].join("\n");
80
+ }
81
+
82
+ if (p.action === "search") {
83
+ if (!p.query?.trim()) return "search needs a query.";
84
+ const hits = searchSessions(all, p.query, 40);
85
+ if (!hits.length) return `No matches for "${p.query}".`;
86
+ const index = new Map(all.map((s, i) => [s.meta.file, i + 1]));
87
+ return [
88
+ `${hits.length} match(es) for "${p.query}" (session number from the list, time, where):`,
89
+ ...hits.map((h) => `- #${index.get(h.session.file)} ${fmtDate(h.t)} [${h.where}] ${h.snippet}`),
90
+ ].join("\n");
91
+ }
92
+
93
+ // read
94
+ const ref = (p.session ?? "current").trim();
95
+ let chosen: LoadedSession[];
96
+ if (ref === "all" || ref === "todas") chosen = all;
97
+ else if (ref === "current" || ref === "atual") chosen = all.filter((s) => s.meta.file === current);
98
+ else {
99
+ const m = pickSession(all.map((s) => s.meta), ref);
100
+ chosen = m ? all.filter((s) => s.meta.file === m.file) : [];
101
+ }
102
+ if (!chosen.length) return `Session not found: ${ref}. Use action 'list' first.`;
103
+ const text = renderMany(chosen, p.level ?? "normal");
104
+ const offset = Math.max(0, Math.floor(p.offset ?? 0));
105
+ const size = Math.min(Math.max(500, Math.floor(p.max_chars ?? 16000)), 60000);
106
+ const page = text.slice(offset, offset + size);
107
+ const end = offset + page.length;
108
+ const tail =
109
+ end < text.length
110
+ ? `\n\n[showing characters ${offset}-${end} of ${text.length}; next_offset=${end}]`
111
+ : `\n\n[end of transcript; ${text.length} characters]`;
112
+ return page + tail;
113
+ }
114
+
@@ -0,0 +1,171 @@
1
+ // Sessões no pi: /ponte sessao, /ponte sessoes, /ponte ver e a ferramenta ponte_sessoes.
2
+
3
+ import { promises as fs } from "node:fs";
4
+ import path from "node:path";
5
+ import { getAgentDir, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { Type } from "typebox";
7
+ import { openFolder } from "./clipboard.ts";
8
+ import { env, readState, rel, writeState, type Env } from "./env.ts";
9
+ import { ensureOutDir, stamp } from "./pack.ts";
10
+ import { formatTokens } from "./prompt.ts";
11
+ import { allSessions, currentSession, runTool, setAgentDir } from "./session-tool.ts";
12
+ import {
13
+ LEVELS,
14
+ approxTokens,
15
+ fmtDate,
16
+ pickSession,
17
+ renderMany,
18
+ sessionTitle,
19
+ type Level,
20
+ type LoadedSession,
21
+ } from "./sessions.ts";
22
+ import { renderViewer } from "./viewer.ts";
23
+
24
+ function slug(s: LoadedSession): string {
25
+ return `${fmtDate(s.meta.created).replace(/[: ]/g, "-")}_${s.meta.id.slice(0, 8)}`;
26
+ }
27
+
28
+ async function writeExport(e: Env, sessions: LoadedSession[], level: Level): Promise<{ abs: string; tokens: number }> {
29
+ const dir = path.join(e.outAbs, "sessoes");
30
+ await ensureOutDir(e.outAbs);
31
+ await fs.mkdir(dir, { recursive: true });
32
+ const name = sessions.length === 1 ? `${slug(sessions[0])}.${level}.${e.cfg.ext}` : `historico-${sessions.length}.${level}.${e.cfg.ext}`;
33
+ const abs = path.join(dir, name);
34
+ const text = renderMany(sessions, level);
35
+ await fs.writeFile(abs, text, "utf8");
36
+ const state = await readState(e);
37
+ await writeState(e, { ...state, last: [rel(e, abs)] });
38
+ return { abs, tokens: approxTokens(text) };
39
+ }
40
+
41
+ function listLine(s: LoadedSession, i: number): string {
42
+ return `${i + 1}. ${fmtDate(s.meta.updated)} · ${s.meta.userTurns} pedido(s) · ${sessionTitle(s.meta).slice(0, 90)}`;
43
+ }
44
+
45
+ function parseLevel(tokens: string[]): { level?: Level; rest: string[] } {
46
+ const level = tokens.find((t) => (LEVELS as string[]).includes(t)) as Level | undefined;
47
+ return { level, rest: tokens.filter((t) => t !== level) };
48
+ }
49
+
50
+ const LEVEL_OPTIONS: Record<string, Level> = {
51
+ "normal: conversa + uma linha por ferramenta e os erros (recomendado)": "normal",
52
+ "conversa: só o que vocês escreveram, ações resumidas (menor)": "conversa",
53
+ "completo: + diffs, saídas e raciocínio (maior)": "completo",
54
+ };
55
+
56
+ async function askLevel(ctx: ExtensionContext): Promise<Level | undefined> {
57
+ const choice = await ctx.ui.select("Nível de detalhe", Object.keys(LEVEL_OPTIONS));
58
+ return choice ? LEVEL_OPTIONS[choice] : undefined;
59
+ }
60
+
61
+ /** Trata os subcomandos de sessão. Devolve false se o subcomando não é daqui. */
62
+ export async function sessionCommand(sub: string, tokens: string[], ctx: ExtensionContext): Promise<boolean> {
63
+ const say = (msg: string, level: "info" | "warning" | "error" = "info") => ctx.ui.notify(msg, level);
64
+ const e = await env(ctx);
65
+
66
+ if (sub === "sessao") {
67
+ const { level: given } = parseLevel(tokens);
68
+ const s = await currentSession(ctx);
69
+ if (!s) {
70
+ say("A sessão atual ainda não tem nada gravado.", "warning");
71
+ return true;
72
+ }
73
+ const level = given ?? (ctx.hasUI ? await askLevel(ctx) : "normal");
74
+ if (!level) return true;
75
+ const r = await writeExport(e, [s], level);
76
+ say(`Sessão exportada: ${rel(e, r.abs)} (~${formatTokens(r.tokens)} tokens, de ${Math.round(s.meta.bytes / 1024)} KB no .jsonl). Use /ponte copy para colar como anexo.`);
77
+ return true;
78
+ }
79
+
80
+ if (sub === "sessoes") {
81
+ const all = await allSessions(ctx);
82
+ if (!all.length) {
83
+ say("Nenhuma sessão salva para este projeto.", "warning");
84
+ return true;
85
+ }
86
+ const { level: given, rest } = parseLevel(tokens);
87
+ let chosen: LoadedSession[] = [];
88
+ if (rest[0] === "todas" || rest[0] === "all") chosen = all;
89
+ else if (rest.length) {
90
+ for (const ref of rest) {
91
+ const m = pickSession(all.map((s) => s.meta), ref);
92
+ const s = m && all.find((x) => x.meta.file === m.file);
93
+ if (!s) {
94
+ say(`Sessão não encontrada: ${ref}`, "warning");
95
+ return true;
96
+ }
97
+ chosen.push(s);
98
+ }
99
+ } else if (ctx.hasUI) {
100
+ const ALL = `Todas deste projeto (${all.length})`;
101
+ const options = [ALL, ...all.map(listLine)];
102
+ const picked = await ctx.ui.select("Qual sessão? (para várias: /ponte sessoes 1 3 5)", options);
103
+ if (!picked) return true;
104
+ chosen = picked === ALL ? all : [all[options.indexOf(picked) - 1]];
105
+ } else {
106
+ say(all.map(listLine).join("\n"));
107
+ return true;
108
+ }
109
+ const level = given ?? (ctx.hasUI ? await askLevel(ctx) : "normal");
110
+ if (!level) return true;
111
+ const r = await writeExport(e, chosen, level);
112
+ say(`${chosen.length} sessão(ões) exportada(s): ${rel(e, r.abs)} (~${formatTokens(r.tokens)} tokens). Use /ponte copy para colar como anexo.`);
113
+ return true;
114
+ }
115
+
116
+ if (sub === "ver") {
117
+ const all = await allSessions(ctx);
118
+ if (!all.length) {
119
+ say("Nenhuma sessão salva para este projeto.", "warning");
120
+ return true;
121
+ }
122
+ await ensureOutDir(e.outAbs);
123
+ const abs = path.join(e.outAbs, "sessoes.html");
124
+ await fs.writeFile(abs, renderViewer(e.repoName, all, stamp()), "utf8");
125
+ openFolder(abs); // abre no navegador padrão
126
+ say(`Visualizador aberto: ${rel(e, abs)} (${all.length} sessão(ões)). Rode /ponte ver de novo para atualizar.`);
127
+ return true;
128
+ }
129
+
130
+ return false;
131
+ }
132
+
133
+ export function registerSessionTool(pi: ExtensionAPI) {
134
+ try {
135
+ setAgentDir(getAgentDir());
136
+ } catch {
137
+ // versão do pi sem getAgentDir: só funciona com sessão salva em disco
138
+ }
139
+ pi.registerTool({
140
+ name: "ponte_sessoes",
141
+ label: "Ponte: sessões",
142
+ description:
143
+ "Lists, searches and reads this project's previous pi sessions as clean transcripts (no images, tool schemas or huge outputs). " +
144
+ "action 'list' shows sessions newest first; 'search' finds keywords across all sessions; 'read' returns one session (or 'all') " +
145
+ "at level 'conversa' (messages only), 'normal' (plus one line per tool call and errors) or 'completo' (plus diffs and outputs), paginated by characters.",
146
+ promptSnippet: "List, search and read previous sessions of this project as clean transcripts",
147
+ promptGuidelines: [
148
+ "Use ponte_sessoes whenever the user mentions previous or earlier sessions, past work, or asks to review what was done before: start with action 'list' (titles are often enough to pick the session) or 'search', then 'read' the relevant sessions. Sessions may be in another language than the question: search with the words the session itself would use. Never open session .jsonl files with read or bash.",
149
+ "When ponte_sessoes returns a 'next_offset', call it again with that offset if you still need the rest of the session.",
150
+ ],
151
+ parameters: Type.Object({
152
+ action: Type.Union([Type.Literal("list"), Type.Literal("search"), Type.Literal("read")]),
153
+ session: Type.Optional(
154
+ Type.String({ description: "For read: number from the list (1 = newest), id prefix, 'current' or 'all'" }),
155
+ ),
156
+ query: Type.Optional(Type.String({ description: "For search: words that must all appear" })),
157
+ level: Type.Optional(
158
+ Type.Union([Type.Literal("conversa"), Type.Literal("normal"), Type.Literal("completo")], {
159
+ description: "For read: detail level (default normal)",
160
+ }),
161
+ ),
162
+ offset: Type.Optional(Type.Number({ description: "For read: character offset to continue from" })),
163
+ max_chars: Type.Optional(Type.Number({ description: "For read: page size in characters (default 16000)" })),
164
+ }),
165
+ async execute(_id, params, _signal, _onUpdate, ctx) {
166
+ const text = await runTool(ctx, params);
167
+ return { content: [{ type: "text", text }], details: undefined };
168
+ },
169
+ });
170
+ }
171
+