@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.
- package/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +154 -2
- package/package.json +37 -4
- package/src/apply.ts +417 -0
- package/src/clipboard.ts +88 -0
- package/src/env.ts +41 -0
- package/src/files.ts +297 -0
- package/src/index.ts +498 -0
- package/src/pack.ts +228 -0
- package/src/parse.ts +247 -0
- package/src/prompt.ts +116 -0
- 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/index.ts
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
// pi-ponte: leva o repositório para um chat externo (Copilot, ChatGPT...) e aplica a resposta de volta.
|
|
2
|
+
//
|
|
3
|
+
// /ponte pack [filtros...] gera o pacote (repo inteiro num arquivo .txt)
|
|
4
|
+
// /ponte delta só o que mudou desde o último envio
|
|
5
|
+
// /ponte apply [arquivo] aplica a resposta (da área de transferência, de um arquivo ou colada)
|
|
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
|
|
9
|
+
// /ponte status | copy | abrir | formato | ajuda
|
|
10
|
+
|
|
11
|
+
import { promises as fs } from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import { Type } from "typebox";
|
|
15
|
+
import { errorReport, planOps, summarize, undoLast, writeChanges } from "./apply.ts";
|
|
16
|
+
import { copyFiles, copyText, openFolder, readClipboard } from "./clipboard.ts";
|
|
17
|
+
import { env, readState, rel, writeState, type Env } from "./env.ts";
|
|
18
|
+
import {
|
|
19
|
+
approxTokens,
|
|
20
|
+
collect,
|
|
21
|
+
computeDelta,
|
|
22
|
+
ensureOutDir,
|
|
23
|
+
hashText,
|
|
24
|
+
makeManifest,
|
|
25
|
+
readManifest,
|
|
26
|
+
renderDelta,
|
|
27
|
+
renderPack,
|
|
28
|
+
stamp,
|
|
29
|
+
writeManifest,
|
|
30
|
+
} from "./pack.ts";
|
|
31
|
+
import { looksLikePonteResponse, parseResponse } from "./parse.ts";
|
|
32
|
+
import { registerSessionTool, sessionCommand } from "./sessions-pi.ts";
|
|
33
|
+
import { FORMAT_INSTRUCTIONS, formatTokens } from "./prompt.ts";
|
|
34
|
+
|
|
35
|
+
// ---------------------------------------------------------------- pack / delta
|
|
36
|
+
|
|
37
|
+
interface PackResult {
|
|
38
|
+
outputs: string[];
|
|
39
|
+
fileCount: number;
|
|
40
|
+
omitted: number;
|
|
41
|
+
tokens: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function doPack(e: Env, filters: string[]): Promise<PackResult> {
|
|
45
|
+
const { files, omitted } = await collect(e.root, e.cfg, filters);
|
|
46
|
+
const date = stamp();
|
|
47
|
+
const parts = renderPack({
|
|
48
|
+
repoName: e.repoName,
|
|
49
|
+
files,
|
|
50
|
+
omitted,
|
|
51
|
+
filters,
|
|
52
|
+
date,
|
|
53
|
+
maxPartChars: e.cfg.maxPartKB * 1024,
|
|
54
|
+
});
|
|
55
|
+
await ensureOutDir(e.outAbs);
|
|
56
|
+
// limpa pacotes e deltas anteriores: um pacote novo é um ponto de partida novo
|
|
57
|
+
for (const f of await fs.readdir(e.outAbs)) {
|
|
58
|
+
if (/^(repo|delta)[.-]/.test(f)) await fs.rm(path.join(e.outAbs, f), { force: true });
|
|
59
|
+
}
|
|
60
|
+
const outputs: string[] = [];
|
|
61
|
+
for (let i = 0; i < parts.length; i++) {
|
|
62
|
+
const name = parts.length === 1 ? `repo.${e.cfg.ext}` : `repo.parte${i + 1}.${e.cfg.ext}`;
|
|
63
|
+
const abs = path.join(e.outAbs, name);
|
|
64
|
+
await fs.writeFile(abs, parts[i], "utf8");
|
|
65
|
+
outputs.push(abs);
|
|
66
|
+
}
|
|
67
|
+
await writeManifest(e.outAbs, makeManifest(files, filters, date));
|
|
68
|
+
await writeState(e, { last: outputs.map((o) => rel(e, o)), deltas: 0 });
|
|
69
|
+
const chars = parts.reduce((n, p) => n + p.length, 0);
|
|
70
|
+
return { outputs, fileCount: files.length, omitted: omitted.length, tokens: approxTokens(chars) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function currentDelta(e: Env) {
|
|
74
|
+
const manifest = await readManifest(e.outAbs);
|
|
75
|
+
if (!manifest) return null;
|
|
76
|
+
const { files } = await collect(e.root, e.cfg, manifest.filters);
|
|
77
|
+
const delta = computeDelta(manifest, files);
|
|
78
|
+
// "removido" só se o arquivo sumiu mesmo do disco (e não apenas saiu do recorte)
|
|
79
|
+
const deleted: string[] = [];
|
|
80
|
+
for (const p of delta.deleted) {
|
|
81
|
+
try {
|
|
82
|
+
await fs.access(path.join(e.root, p));
|
|
83
|
+
} catch {
|
|
84
|
+
deleted.push(p);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
delta.deleted = deleted;
|
|
88
|
+
return { manifest, files, delta };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function doDelta(e: Env): Promise<{ output: string | null; changed: number; deleted: number } | null> {
|
|
92
|
+
const cur = await currentDelta(e);
|
|
93
|
+
if (!cur) return null;
|
|
94
|
+
const { manifest, files, delta } = cur;
|
|
95
|
+
if (!delta.changed.length && !delta.deleted.length) return { output: null, changed: 0, deleted: 0 };
|
|
96
|
+
const state = await readState(e);
|
|
97
|
+
const n = state.deltas + 1;
|
|
98
|
+
const abs = path.join(e.outAbs, `delta-${String(n).padStart(3, "0")}.${e.cfg.ext}`);
|
|
99
|
+
await fs.writeFile(abs, renderDelta(e.repoName, stamp(), delta), "utf8");
|
|
100
|
+
// a linha de base passa a ser o estado atual
|
|
101
|
+
const next = makeManifest(files, manifest.filters, manifest.createdAt);
|
|
102
|
+
for (const p of Object.keys(manifest.files)) {
|
|
103
|
+
if (!(p in next.files) && !delta.deleted.includes(p)) next.files[p] = manifest.files[p];
|
|
104
|
+
}
|
|
105
|
+
await writeManifest(e.outAbs, next);
|
|
106
|
+
await writeState(e, { last: [rel(e, abs)], deltas: n });
|
|
107
|
+
return { output: abs, changed: delta.changed.length, deleted: delta.deleted.length };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ---------------------------------------------------------------- apply
|
|
111
|
+
|
|
112
|
+
interface ApplyOutcome {
|
|
113
|
+
text: string;
|
|
114
|
+
applied: string[];
|
|
115
|
+
failed: boolean;
|
|
116
|
+
cancelled: boolean;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** confirm: "pasted" = resposta colada no prompt; "Não" devolve cancelled para o texto seguir ao modelo. */
|
|
120
|
+
async function doApply(
|
|
121
|
+
e: Env,
|
|
122
|
+
ctx: ExtensionContext,
|
|
123
|
+
response: string,
|
|
124
|
+
confirm: boolean | "pasted",
|
|
125
|
+
): Promise<ApplyOutcome> {
|
|
126
|
+
const parsed = parseResponse(response);
|
|
127
|
+
const parseIssues = parsed.issues.map((i) => `linha ${i.line} da resposta: ${i.message}`);
|
|
128
|
+
if (!parsed.ops.length) {
|
|
129
|
+
return {
|
|
130
|
+
text: ["Nenhum bloco FILE / EDIT / DELETE / MOVE encontrado na resposta.", ...parseIssues].join("\n"),
|
|
131
|
+
applied: [],
|
|
132
|
+
failed: true,
|
|
133
|
+
cancelled: false,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const plan = await planOps(e.root, parsed.ops, [e.outRel]);
|
|
138
|
+
const ok = plan.changes.filter((c) => !plan.failedPaths.has(c.path));
|
|
139
|
+
const hasErrors = plan.failures.length > 0 || parseIssues.length > 0;
|
|
140
|
+
let summary = summarize(plan);
|
|
141
|
+
if (parseIssues.length) summary += `\n\nBlocos ilegíveis:\n${parseIssues.map((i) => `✗ ${i}`).join("\n")}`;
|
|
142
|
+
|
|
143
|
+
if (!ok.length) {
|
|
144
|
+
const report = await errorReport(e.root, plan, [], parseIssues);
|
|
145
|
+
const where = await saveReport(e, report);
|
|
146
|
+
return { text: `Nada aplicado.\n${summary}\n\n${where}`, applied: [], failed: true, cancelled: false };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (confirm && ctx.hasUI) {
|
|
150
|
+
let title = hasErrors
|
|
151
|
+
? `Aplicar só os ${ok.length} arquivo(s) sem erro?`
|
|
152
|
+
: `Aplicar ${ok.length} alteração(ões)?`;
|
|
153
|
+
if (confirm === "pasted") title = `Resposta de chat externo detectada. ${title} (Não = mandar ao modelo)`;
|
|
154
|
+
const yes = await ctx.ui.confirm(title, summary);
|
|
155
|
+
if (!yes) return { text: "Cancelado. Nada foi alterado.", applied: [], failed: false, cancelled: true };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
await writeChanges(e.root, path.join(e.outAbs, "backups"), ok);
|
|
159
|
+
|
|
160
|
+
// o modelo externo já conhece o que ele mesmo escreveu: atualiza a linha de base
|
|
161
|
+
const manifest = await readManifest(e.outAbs);
|
|
162
|
+
if (manifest) {
|
|
163
|
+
for (const c of ok) {
|
|
164
|
+
if (c.after === null) delete manifest.files[c.path];
|
|
165
|
+
else manifest.files[c.path] = hashText(c.after);
|
|
166
|
+
}
|
|
167
|
+
await writeManifest(e.outAbs, manifest);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const applied = ok.map((c) => c.path);
|
|
171
|
+
let text = `Aplicado (${applied.length} arquivo(s); desfazer com /ponte undo):\n${summarize(plan, true)}`;
|
|
172
|
+
if (hasErrors) {
|
|
173
|
+
const report = await errorReport(e.root, plan, applied, parseIssues);
|
|
174
|
+
text += `\n\n${await saveReport(e, report)}`;
|
|
175
|
+
}
|
|
176
|
+
return { text, applied, failed: hasErrors, cancelled: false };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function saveReport(e: Env, report: string): Promise<string> {
|
|
180
|
+
await ensureOutDir(e.outAbs);
|
|
181
|
+
const abs = path.join(e.outAbs, `erros.${e.cfg.ext}`);
|
|
182
|
+
await fs.writeFile(abs, report, "utf8");
|
|
183
|
+
try {
|
|
184
|
+
await copyText(report);
|
|
185
|
+
return `Relatório de erros copiado para a área de transferência (e salvo em ${rel(e, abs)}). Cole no chat externo para ele corrigir.`;
|
|
186
|
+
} catch {
|
|
187
|
+
return `Relatório de erros salvo em ${rel(e, abs)}. Envie ao chat externo para ele corrigir.`;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function getResponse(e: Env, ctx: ExtensionContext, arg: string): Promise<{ text: string; source: string } | null> {
|
|
192
|
+
if (arg) {
|
|
193
|
+
const abs = path.resolve(e.root, arg.replace(/^@/, ""));
|
|
194
|
+
return { text: await fs.readFile(abs, "utf8"), source: arg };
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
const clip = await readClipboard();
|
|
198
|
+
if (looksLikePonteResponse(clip)) return { text: clip, source: "área de transferência" };
|
|
199
|
+
} catch {
|
|
200
|
+
// sem área de transferência: cai no editor
|
|
201
|
+
}
|
|
202
|
+
if (!ctx.hasUI) return null;
|
|
203
|
+
const pasted = await ctx.ui.editor("Cole aqui a resposta do chat externo e confirme", "");
|
|
204
|
+
if (!pasted || !pasted.trim()) return null;
|
|
205
|
+
return { text: pasted, source: "colada no editor" };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// ---------------------------------------------------------------- status
|
|
209
|
+
|
|
210
|
+
async function refreshStatus(ctx: ExtensionContext) {
|
|
211
|
+
if (!ctx.hasUI) return;
|
|
212
|
+
try {
|
|
213
|
+
const e = await env(ctx);
|
|
214
|
+
const cur = await currentDelta(e);
|
|
215
|
+
if (!cur) {
|
|
216
|
+
ctx.ui.setStatus("ponte", undefined);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const n = cur.delta.changed.length + cur.delta.deleted.length;
|
|
220
|
+
ctx.ui.setStatus("ponte", n ? `ponte: ${n} mudança(s) para enviar (/ponte delta)` : "ponte: em dia");
|
|
221
|
+
} catch {
|
|
222
|
+
// status é só conveniência
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ---------------------------------------------------------------- comando
|
|
227
|
+
|
|
228
|
+
const SUBCOMMANDS: Array<[string, string]> = [
|
|
229
|
+
["pack", "gera o pacote do repositório (aceita filtros: src tests/*.py)"],
|
|
230
|
+
["delta", "gera só o que mudou desde o último envio"],
|
|
231
|
+
["apply", "aplica a resposta do chat externo (área de transferência, arquivo ou colar)"],
|
|
232
|
+
["undo", "desfaz a última aplicação"],
|
|
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"],
|
|
237
|
+
["copy", "copia o último pacote/delta (como arquivo; 'copy texto' copia o conteúdo)"],
|
|
238
|
+
["abrir", "abre a pasta dos pacotes (para arrastar para o chat)"],
|
|
239
|
+
["formato", "copia as instruções de formato de resposta"],
|
|
240
|
+
["ajuda", "mostra esta ajuda"],
|
|
241
|
+
];
|
|
242
|
+
|
|
243
|
+
const ALIASES: Record<string, string> = {
|
|
244
|
+
pacote: "pack",
|
|
245
|
+
empacotar: "pack",
|
|
246
|
+
aplicar: "apply",
|
|
247
|
+
desfazer: "undo",
|
|
248
|
+
copiar: "copy",
|
|
249
|
+
open: "abrir",
|
|
250
|
+
format: "formato",
|
|
251
|
+
help: "ajuda",
|
|
252
|
+
"sessão": "sessao",
|
|
253
|
+
session: "sessao",
|
|
254
|
+
"sessões": "sessoes",
|
|
255
|
+
sessions: "sessoes",
|
|
256
|
+
view: "ver",
|
|
257
|
+
visualizar: "ver",
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
function tokenize(args: string): string[] {
|
|
261
|
+
return (args.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((t) => t.replace(/^["']|["']$/g, ""));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function packMessage(e: Env, r: PackResult): string {
|
|
265
|
+
const files = r.outputs.map((o) => rel(e, o)).join(", ");
|
|
266
|
+
const parts = r.outputs.length > 1 ? ` em ${r.outputs.length} partes` : "";
|
|
267
|
+
const omitted = r.omitted ? `, ${r.omitted} omitido(s)` : "";
|
|
268
|
+
return `Pacote gerado${parts}: ${files} (${r.fileCount} arquivos${omitted}, ~${formatTokens(r.tokens)} tokens). Use /ponte copy para colar como anexo.`;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export default function ponte(pi: ExtensionAPI) {
|
|
272
|
+
pi.registerCommand("ponte", {
|
|
273
|
+
description: "Ponte com chat externo: pack, delta, apply, undo, sessao, sessoes, ver, status, copy, abrir, formato",
|
|
274
|
+
getArgumentCompletions: (prefix: string) => {
|
|
275
|
+
const items = SUBCOMMANDS.filter(([n]) => n.startsWith(prefix.trim())).map(([n, d]) => ({
|
|
276
|
+
value: n,
|
|
277
|
+
label: n,
|
|
278
|
+
description: d,
|
|
279
|
+
}));
|
|
280
|
+
return items.length ? items : null;
|
|
281
|
+
},
|
|
282
|
+
handler: async (args, ctx) => {
|
|
283
|
+
const [rawSub = "ajuda", ...rest] = tokenize(args ?? "");
|
|
284
|
+
const sub = ALIASES[rawSub] ?? rawSub;
|
|
285
|
+
const e = await env(ctx);
|
|
286
|
+
const say = (msg: string, level: "info" | "warning" | "error" = "info") => ctx.ui.notify(msg, level);
|
|
287
|
+
|
|
288
|
+
try {
|
|
289
|
+
if (await sessionCommand(sub, rest, ctx)) return;
|
|
290
|
+
switch (sub) {
|
|
291
|
+
case "pack": {
|
|
292
|
+
const r = await doPack(e, rest);
|
|
293
|
+
say(packMessage(e, r));
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
case "delta": {
|
|
297
|
+
const r = await doDelta(e);
|
|
298
|
+
if (!r) say("Ainda não há pacote. Rode /ponte pack primeiro.", "warning");
|
|
299
|
+
else if (!r.output) say("Nada mudou desde o último envio.");
|
|
300
|
+
else
|
|
301
|
+
say(
|
|
302
|
+
`Delta gerado: ${rel(e, r.output)} (${r.changed} alterado(s), ${r.deleted} removido(s)). Use /ponte copy para colar como anexo.`,
|
|
303
|
+
);
|
|
304
|
+
break;
|
|
305
|
+
}
|
|
306
|
+
case "apply": {
|
|
307
|
+
const resp = await getResponse(e, ctx, rest.join(" "));
|
|
308
|
+
if (!resp) {
|
|
309
|
+
say("Nenhuma resposta para aplicar.", "warning");
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
312
|
+
const out = await doApply(e, ctx, resp.text, true);
|
|
313
|
+
say(`[${resp.source}] ${out.text}`, out.failed ? "warning" : "info");
|
|
314
|
+
if (out.applied.length) informAgent(pi, out);
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
case "undo": {
|
|
318
|
+
const r = await undoLast(e.root, path.join(e.outAbs, "backups"));
|
|
319
|
+
if (!r) say("Não há aplicação para desfazer.", "warning");
|
|
320
|
+
else {
|
|
321
|
+
say(
|
|
322
|
+
`Desfeito: ${r.modified.length} restaurado(s), ${r.deleted.length} recriado(s), ${r.created.length} removido(s). ` +
|
|
323
|
+
"O chat externo não sabe disso: rode /ponte delta e envie.",
|
|
324
|
+
);
|
|
325
|
+
pi.sendMessage(
|
|
326
|
+
{
|
|
327
|
+
customType: "ponte",
|
|
328
|
+
content: `[ponte] A última aplicação foi desfeita. Arquivos restaurados: ${[...r.modified, ...r.deleted, ...r.created].join(", ")}`,
|
|
329
|
+
display: true,
|
|
330
|
+
},
|
|
331
|
+
{ deliverAs: "nextTurn" },
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
case "status": {
|
|
337
|
+
const cur = await currentDelta(e);
|
|
338
|
+
if (!cur) say("Ainda não há pacote. Rode /ponte pack.");
|
|
339
|
+
else {
|
|
340
|
+
const d = cur.delta;
|
|
341
|
+
const lines = [
|
|
342
|
+
...d.added.map((p) => `+ ${p}`),
|
|
343
|
+
...d.modified.map((p) => `~ ${p}`),
|
|
344
|
+
...d.deleted.map((p) => `- ${p}`),
|
|
345
|
+
];
|
|
346
|
+
say(
|
|
347
|
+
lines.length
|
|
348
|
+
? `Desde o último envio (${cur.manifest.createdAt}):\n${lines.join("\n")}\nUse /ponte delta para gerar a atualização.`
|
|
349
|
+
: `Em dia com o último envio (${cur.manifest.createdAt}).`,
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
case "copy": {
|
|
355
|
+
const state = await readState(e);
|
|
356
|
+
if (!state.last.length) {
|
|
357
|
+
say("Nada gerado ainda. Rode /ponte pack.", "warning");
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
const abs = state.last.map((p) => path.join(e.root, p));
|
|
361
|
+
if (rest[0] === "texto" || rest[0] === "text") {
|
|
362
|
+
const text = (await Promise.all(abs.map((a) => fs.readFile(a, "utf8")))).join("\n\n");
|
|
363
|
+
await copyText(text);
|
|
364
|
+
say(`Texto copiado (${state.last.join(", ")}, ~${formatTokens(approxTokens(text.length))} tokens).`);
|
|
365
|
+
} else {
|
|
366
|
+
try {
|
|
367
|
+
await copyFiles(abs);
|
|
368
|
+
say(`Arquivo(s) copiado(s): ${state.last.join(", ")}. Cole no chat com Ctrl+V / Cmd+V.`);
|
|
369
|
+
} catch {
|
|
370
|
+
openFolder(e.outAbs);
|
|
371
|
+
say(`Não deu para copiar como arquivo; abri a pasta ${e.outRel} para você arrastar.`, "warning");
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
case "abrir": {
|
|
377
|
+
await ensureOutDir(e.outAbs);
|
|
378
|
+
openFolder(e.outAbs);
|
|
379
|
+
break;
|
|
380
|
+
}
|
|
381
|
+
case "formato": {
|
|
382
|
+
await copyText(FORMAT_INSTRUCTIONS);
|
|
383
|
+
say("Instruções de formato copiadas. Cole no início da conversa no chat externo.");
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
default: {
|
|
387
|
+
say(
|
|
388
|
+
["Uso: /ponte <subcomando>", ...SUBCOMMANDS.map(([n, d]) => ` ${n.padEnd(8)} ${d}`)].join("\n"),
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
} catch (err) {
|
|
393
|
+
say(`ponte: ${(err as Error).message}`, "error");
|
|
394
|
+
}
|
|
395
|
+
await refreshStatus(ctx);
|
|
396
|
+
},
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
// Colou a resposta do chat externo direto no prompt do pi? Oferece aplicar sem gastar o modelo.
|
|
400
|
+
pi.on("input", async (event, ctx) => {
|
|
401
|
+
if (event.source === "extension" || !ctx.hasUI) return { action: "continue" };
|
|
402
|
+
const text = event.text ?? "";
|
|
403
|
+
if (text.trimStart().startsWith("/") || !looksLikePonteResponse(text)) return { action: "continue" };
|
|
404
|
+
if (!parseResponse(text).ops.length) return { action: "continue" };
|
|
405
|
+
const e = await env(ctx);
|
|
406
|
+
const out = await doApply(e, ctx, text, "pasted");
|
|
407
|
+
if (out.cancelled) return { action: "continue" };
|
|
408
|
+
ctx.ui.notify(out.text, out.failed ? "warning" : "info");
|
|
409
|
+
if (out.applied.length) informAgent(pi, out);
|
|
410
|
+
await refreshStatus(ctx);
|
|
411
|
+
return { action: "handled" };
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
registerSessionTool(pi);
|
|
415
|
+
|
|
416
|
+
pi.registerTool({
|
|
417
|
+
name: "ponte_pack",
|
|
418
|
+
label: "Ponte: pacote",
|
|
419
|
+
description:
|
|
420
|
+
"Writes the repository (or a filtered subset) into a single text file to be uploaded to an external chat model, " +
|
|
421
|
+
"or writes a delta with only the files changed since the last package. Returns the output file paths.",
|
|
422
|
+
promptSnippet: "Package the repo into one file for an external chat model (full or delta)",
|
|
423
|
+
promptGuidelines: [
|
|
424
|
+
"Use ponte_pack when the user wants to send the repository, or part of it, to an external chat (Copilot, ChatGPT); use mode 'delta' when a package was already sent and only the changes are needed.",
|
|
425
|
+
],
|
|
426
|
+
parameters: Type.Object({
|
|
427
|
+
mode: Type.Optional(
|
|
428
|
+
Type.Union([Type.Literal("full"), Type.Literal("delta")], { description: "full (default) or delta" }),
|
|
429
|
+
),
|
|
430
|
+
filters: Type.Optional(
|
|
431
|
+
Type.Array(Type.String(), {
|
|
432
|
+
description: "Optional gitignore-style patterns to include only some files, e.g. ['src/api', '*.sql']",
|
|
433
|
+
}),
|
|
434
|
+
),
|
|
435
|
+
}),
|
|
436
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
437
|
+
const e = await env(ctx);
|
|
438
|
+
let text: string;
|
|
439
|
+
if (params.mode === "delta") {
|
|
440
|
+
const r = await doDelta(e);
|
|
441
|
+
text = !r
|
|
442
|
+
? "No package yet; call ponte_pack with mode 'full' first."
|
|
443
|
+
: !r.output
|
|
444
|
+
? "Nothing changed since the last package."
|
|
445
|
+
: `Delta written to ${rel(e, r.output)} (${r.changed} changed, ${r.deleted} deleted).`;
|
|
446
|
+
} else {
|
|
447
|
+
text = packMessage(e, await doPack(e, params.filters ?? []));
|
|
448
|
+
}
|
|
449
|
+
await refreshStatus(ctx);
|
|
450
|
+
return { content: [{ type: "text", text }], details: undefined };
|
|
451
|
+
},
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
pi.registerTool({
|
|
455
|
+
name: "ponte_apply",
|
|
456
|
+
label: "Ponte: aplicar",
|
|
457
|
+
description:
|
|
458
|
+
"Applies an external chat model's response saved in a file (FILE / EDIT with SEARCH/REPLACE / DELETE / MOVE blocks) " +
|
|
459
|
+
"to the repository, atomically per file, with backup (undo via /ponte undo). Returns what was applied and what failed.",
|
|
460
|
+
promptSnippet: "Apply an external model's response file (FILE/EDIT/DELETE/MOVE blocks) to the repo",
|
|
461
|
+
promptGuidelines: [
|
|
462
|
+
"Use ponte_apply when the user points to a file containing a response from an external chat model; never retype or re-edit those changes by hand.",
|
|
463
|
+
],
|
|
464
|
+
parameters: Type.Object({
|
|
465
|
+
path: Type.String({ description: "Path of the file containing the external response" }),
|
|
466
|
+
}),
|
|
467
|
+
executionMode: "sequential",
|
|
468
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
469
|
+
const e = await env(ctx);
|
|
470
|
+
const abs = path.resolve(e.root, params.path.replace(/^@/, ""));
|
|
471
|
+
const out = await doApply(e, ctx, await fs.readFile(abs, "utf8"), true);
|
|
472
|
+
await refreshStatus(ctx);
|
|
473
|
+
return {
|
|
474
|
+
content: [{ type: "text", text: out.text }],
|
|
475
|
+
details: undefined,
|
|
476
|
+
isError: out.failed && !out.applied.length && !out.cancelled,
|
|
477
|
+
};
|
|
478
|
+
},
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
482
|
+
await refreshStatus(ctx);
|
|
483
|
+
});
|
|
484
|
+
pi.on("agent_end", async (_event, ctx) => {
|
|
485
|
+
await refreshStatus(ctx);
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function informAgent(pi: ExtensionAPI, out: ApplyOutcome) {
|
|
490
|
+
pi.sendMessage(
|
|
491
|
+
{
|
|
492
|
+
customType: "ponte",
|
|
493
|
+
content: `[ponte] Alterações vindas de um modelo externo foram aplicadas no repositório:\n${out.text}`,
|
|
494
|
+
display: false,
|
|
495
|
+
},
|
|
496
|
+
{ deliverAs: "nextTurn" },
|
|
497
|
+
);
|
|
498
|
+
}
|