@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 CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.0] - 2026-11-16
4
+
5
+ - Sessões: `/ponte ver` (visualizador HTML com busca, níveis e "copiar para o chat"), `/ponte sessao` e `/ponte sessoes` (exportação em texto limpo, níveis conversa/normal/completo).
6
+ - Ferramenta `ponte_sessoes` para o modelo listar, buscar e ler sessões anteriores sem abrir os `.jsonl`.
7
+
3
8
  ## [0.1.0] - 2026-11-16
4
9
 
5
10
  - `/ponte pack`, `delta`, `apply`, `undo`, `status`, `copy`, `abrir`, `formato`.
package/README.md CHANGED
@@ -5,6 +5,7 @@ Extensão do [pi](https://github.com/earendil-works/pi) que faz a ponte entre o
5
5
  - **Ida:** `/ponte pack` gera o repositório inteiro num único `.txt`, com estrutura, conteúdo e instruções de como o modelo externo deve responder.
6
6
  - **Volta:** `/ponte apply` lê a resposta do chat e aplica as alterações nos arquivos. Quem aplica é a extensão, não o modelo do pi.
7
7
  - **Manter atualizado:** `/ponte delta` gera só o que mudou desde o último envio, para continuar a mesma conversa sem reenviar tudo.
8
+ - **Sessões:** `/ponte ver` abre um visualizador das sessões do projeto, e `/ponte sessao` e `/ponte sessoes` exportam sessões em texto limpo para mandar ao chat externo. O modelo do pi ganha a ferramenta `ponte_sessoes` para consultar sessões anteriores sem abrir os `.jsonl`.
8
9
 
9
10
  ## Instalação
10
11
 
@@ -46,8 +47,37 @@ O rodapé do pi mostra `ponte: N mudança(s) para enviar` quando o repositório
46
47
  | `/ponte abrir` | Abre a pasta `.pi/ponte` no Explorer ou Finder |
47
48
  | `/ponte formato` | Copia só as instruções de formato, útil para colar num chat já aberto |
48
49
 
50
+ | `/ponte ver` | Gera `.pi/ponte/sessoes.html` e abre no navegador: todas as sessões do projeto, com busca, níveis de detalhe e botão "Copiar para o chat" (marque várias para juntar) |
51
+ | `/ponte sessao [nível]` | Exporta a sessão atual para `.pi/ponte/sessoes/` |
52
+ | `/ponte sessoes [todas \| 1 3 5] [nível]` | Exporta sessões anteriores. Sem argumentos, abre um seletor |
53
+
49
54
  O modelo do pi também ganha duas ferramentas: `ponte_pack` ("gera o pacote só da pasta src") e `ponte_apply` ("aplica a resposta que salvei em resposta.txt"). Assim ele chama a extensão em vez de redigitar o código.
50
55
 
56
+ ## Sessões
57
+
58
+ Um `.jsonl` de sessão do pi guarda tudo: imagens em base64, assinaturas de raciocínio, o prompt de sistema com a declaração de todas as ferramentas e cada saída de comando. Numa sessão real de 16 MB, o que você e o modelo escreveram somava 24 KB. Por isso os modelos "ignoram" as sessões anteriores: o arquivo não cabe no contexto deles.
59
+
60
+ A ponte converte a sessão em texto, sem modelo nenhum no meio. Há três níveis:
61
+
62
+ | Nível | O que entra | Sessão de 16 MB vira |
63
+ |---|---|---|
64
+ | `conversa` | o que você e o assistente escreveram, com as ações resumidas em uma linha (`[ações: alterou src/a.ts; rodou 3 comandos; 1 com erro]`) | 27 KB, ~7k tokens |
65
+ | `normal` | mais uma linha por ferramenta (`$ npm test`, `editou src/a.ts`) e a saída das que falharam | 42 KB, ~10k tokens |
66
+ | `completo` | mais diffs das edições, saídas (cortadas no meio quando longas) e o raciocínio | 316 KB, ~80k tokens |
67
+
68
+ - Sempre ficam de fora: imagens, o prompt de sistema e as declarações de ferramentas.
69
+ - Uma skill expandida no pedido vira uma linha (`[skill x carregada]`).
70
+ - Mostra o ramo ativo da árvore da sessão; os ramos abandonados aparecem só como contagem.
71
+ - Compactações aparecem como marcador, junto com o resumo.
72
+
73
+ A ferramenta `ponte_sessoes` dá ao modelo do pi três ações:
74
+
75
+ - `list` lista as sessões;
76
+ - `search` busca palavras em todas as sessões;
77
+ - `read` lê uma sessão (ou `all`) no nível escolhido, em páginas.
78
+
79
+ O prompt do sistema instrui o modelo a usá-la sempre que você falar de sessões anteriores. Basta pedir "olha as sessões anteriores sobre o login".
80
+
51
81
  ## Formato da resposta
52
82
 
53
83
  Este é o formato que o pacote pede ao modelo externo:
@@ -118,5 +148,8 @@ npm test # node --test (Node >= 22.18, que roda TypeScript direto)
118
148
  - `src/pack.ts`: pacote, delta e manifesto
119
149
  - `src/parse.ts`: leitura da resposta
120
150
  - `src/apply.ts`: plano, gravação e undo
151
+ - `src/sessions.ts`: leitura e transcrição de sessões
152
+ - `src/session-tool.ts`: ferramenta `ponte_sessoes`
153
+ - `src/viewer.ts`: visualizador HTML
121
154
  - `src/clipboard.ts`: área de transferência
122
155
  - `src/index.ts`: ligação com o pi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincolness/ponte",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Extensão do pi: empacota o repositório num arquivo para um chat externo (Copilot, ChatGPT) e aplica a resposta de volta",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -9,7 +9,8 @@
9
9
  "pi",
10
10
  "copilot",
11
11
  "repo-pack",
12
- "search-replace"
12
+ "search-replace",
13
+ "sessions"
13
14
  ],
14
15
  "pi": {
15
16
  "extensions": [
package/src/env.ts ADDED
@@ -0,0 +1,41 @@
1
+ // Contexto comum aos comandos: raiz, configuração, pasta de saída e estado.
2
+
3
+ import { promises as fs } from "node:fs";
4
+ import path from "node:path";
5
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { loadConfig, toPosix, type PonteConfig } from "./files.ts";
7
+ import { ensureOutDir } from "./pack.ts";
8
+
9
+ const STATE = "state.json";
10
+
11
+ export interface Env {
12
+ root: string;
13
+ cfg: PonteConfig;
14
+ outRel: string;
15
+ outAbs: string;
16
+ repoName: string;
17
+ }
18
+
19
+ export async function env(ctx: ExtensionContext): Promise<Env> {
20
+ const root = ctx.cwd;
21
+ const cfg = await loadConfig(root);
22
+ const outRel = toPosix(cfg.outDir).replace(/^\.\//, "").replace(/\/+$/, "");
23
+ return { root, cfg, outRel, outAbs: path.join(root, outRel), repoName: path.basename(root) };
24
+ }
25
+
26
+ export async function readState(e: Env): Promise<{ last: string[]; deltas: number }> {
27
+ try {
28
+ return { last: [], deltas: 0, ...JSON.parse(await fs.readFile(path.join(e.outAbs, STATE), "utf8")) };
29
+ } catch {
30
+ return { last: [], deltas: 0 };
31
+ }
32
+ }
33
+
34
+ export async function writeState(e: Env, s: { last: string[]; deltas: number }) {
35
+ await ensureOutDir(e.outAbs);
36
+ await fs.writeFile(path.join(e.outAbs, STATE), JSON.stringify(s, null, 2));
37
+ }
38
+
39
+ export function rel(e: Env, abs: string) {
40
+ return toPosix(path.relative(e.root, abs));
41
+ }
package/src/index.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  // /ponte delta só o que mudou desde o último envio
5
5
  // /ponte apply [arquivo] aplica a resposta (da área de transferência, de um arquivo ou colada)
6
6
  // /ponte undo desfaz a última aplicação
7
+ // /ponte sessao | sessoes exporta a sessão atual / sessões anteriores em texto limpo
8
+ // /ponte ver visualizador HTML das sessões do projeto
7
9
  // /ponte status | copy | abrir | formato | ajuda
8
10
 
9
11
  import { promises as fs } from "node:fs";
@@ -12,7 +14,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
12
14
  import { Type } from "typebox";
13
15
  import { errorReport, planOps, summarize, undoLast, writeChanges } from "./apply.ts";
14
16
  import { copyFiles, copyText, openFolder, readClipboard } from "./clipboard.ts";
15
- import { loadConfig, toPosix, type PonteConfig } from "./files.ts";
17
+ import { env, readState, rel, writeState, type Env } from "./env.ts";
16
18
  import {
17
19
  approxTokens,
18
20
  collect,
@@ -27,42 +29,9 @@ import {
27
29
  writeManifest,
28
30
  } from "./pack.ts";
29
31
  import { looksLikePonteResponse, parseResponse } from "./parse.ts";
32
+ import { registerSessionTool, sessionCommand } from "./sessions-pi.ts";
30
33
  import { FORMAT_INSTRUCTIONS, formatTokens } from "./prompt.ts";
31
34
 
32
- const STATE = "state.json";
33
-
34
- interface Env {
35
- root: string;
36
- cfg: PonteConfig;
37
- outRel: string;
38
- outAbs: string;
39
- repoName: string;
40
- }
41
-
42
- async function env(ctx: ExtensionContext): Promise<Env> {
43
- const root = ctx.cwd;
44
- const cfg = await loadConfig(root);
45
- const outRel = toPosix(cfg.outDir).replace(/^\.\//, "").replace(/\/+$/, "");
46
- return { root, cfg, outRel, outAbs: path.join(root, outRel), repoName: path.basename(root) };
47
- }
48
-
49
- async function readState(e: Env): Promise<{ last: string[]; deltas: number }> {
50
- try {
51
- return { last: [], deltas: 0, ...JSON.parse(await fs.readFile(path.join(e.outAbs, STATE), "utf8")) };
52
- } catch {
53
- return { last: [], deltas: 0 };
54
- }
55
- }
56
-
57
- async function writeState(e: Env, s: { last: string[]; deltas: number }) {
58
- await ensureOutDir(e.outAbs);
59
- await fs.writeFile(path.join(e.outAbs, STATE), JSON.stringify(s, null, 2));
60
- }
61
-
62
- function rel(e: Env, abs: string) {
63
- return toPosix(path.relative(e.root, abs));
64
- }
65
-
66
35
  // ---------------------------------------------------------------- pack / delta
67
36
 
68
37
  interface PackResult {
@@ -262,6 +231,9 @@ const SUBCOMMANDS: Array<[string, string]> = [
262
231
  ["apply", "aplica a resposta do chat externo (área de transferência, arquivo ou colar)"],
263
232
  ["undo", "desfaz a última aplicação"],
264
233
  ["status", "mostra o que mudou desde o último envio"],
234
+ ["sessao", "exporta a sessão atual em texto limpo (conversa | normal | completo)"],
235
+ ["sessoes", "exporta sessões anteriores: escolher, 'todas', ou números (1 3 5)"],
236
+ ["ver", "abre o visualizador de sessões no navegador"],
265
237
  ["copy", "copia o último pacote/delta (como arquivo; 'copy texto' copia o conteúdo)"],
266
238
  ["abrir", "abre a pasta dos pacotes (para arrastar para o chat)"],
267
239
  ["formato", "copia as instruções de formato de resposta"],
@@ -277,6 +249,12 @@ const ALIASES: Record<string, string> = {
277
249
  open: "abrir",
278
250
  format: "formato",
279
251
  help: "ajuda",
252
+ "sessão": "sessao",
253
+ session: "sessao",
254
+ "sessões": "sessoes",
255
+ sessions: "sessoes",
256
+ view: "ver",
257
+ visualizar: "ver",
280
258
  };
281
259
 
282
260
  function tokenize(args: string): string[] {
@@ -292,7 +270,7 @@ function packMessage(e: Env, r: PackResult): string {
292
270
 
293
271
  export default function ponte(pi: ExtensionAPI) {
294
272
  pi.registerCommand("ponte", {
295
- description: "Ponte com chat externo: pack, delta, apply, undo, status, copy, abrir, formato",
273
+ description: "Ponte com chat externo: pack, delta, apply, undo, sessao, sessoes, ver, status, copy, abrir, formato",
296
274
  getArgumentCompletions: (prefix: string) => {
297
275
  const items = SUBCOMMANDS.filter(([n]) => n.startsWith(prefix.trim())).map(([n, d]) => ({
298
276
  value: n,
@@ -308,6 +286,7 @@ export default function ponte(pi: ExtensionAPI) {
308
286
  const say = (msg: string, level: "info" | "warning" | "error" = "info") => ctx.ui.notify(msg, level);
309
287
 
310
288
  try {
289
+ if (await sessionCommand(sub, rest, ctx)) return;
311
290
  switch (sub) {
312
291
  case "pack": {
313
292
  const r = await doPack(e, rest);
@@ -432,6 +411,8 @@ export default function ponte(pi: ExtensionAPI) {
432
411
  return { action: "handled" };
433
412
  });
434
413
 
414
+ registerSessionTool(pi);
415
+
435
416
  pi.registerTool({
436
417
  name: "ponte_pack",
437
418
  label: "Ponte: pacote",
@@ -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
+