relevo-pi 0.0.0-stage → 0.1.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 +7 -0
- package/package.json +16 -4
- package/relevo.js +131 -0
- package/turnos.js +129 -0
- package/README.md +0 -3
package/CHANGELOG.md
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "relevo-pi",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Panel de Relevo para Pi: turnos simultáneos, CPU objetivo y memoria mínima",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/fjararibet/relevo.git",
|
|
9
|
+
"directory": "extensions"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/fjararibet/relevo#readme",
|
|
12
|
+
"keywords": ["pi-package", "relevo"],
|
|
13
|
+
"files": ["relevo.js", "turnos.js", "CHANGELOG.md"],
|
|
14
|
+
"peerDependencies": {
|
|
15
|
+
"@earendil-works/pi-tui": "*"
|
|
16
|
+
},
|
|
17
|
+
"pi": { "extensions": ["./relevo.js"] }
|
|
18
|
+
}
|
package/relevo.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { access } from "node:fs/promises";
|
|
2
|
+
import { matchesKey, Key, truncateToWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import { iniciarSesionViva } from "./en-vivo.js";
|
|
4
|
+
import { verThreads } from "./threads.js";
|
|
5
|
+
import { coordinarTurnos } from "./turnos.js";
|
|
6
|
+
|
|
7
|
+
async function api(path, data, { signal, timeout = 5000 } = {}) {
|
|
8
|
+
const headers = { "Content-Type": "application/json" };
|
|
9
|
+
if (process.env.RELEVO_TOKEN) headers.Authorization = "Bearer " + process.env.RELEVO_TOKEN;
|
|
10
|
+
const response = await fetch(new URL("/api/" + path, process.env.RELEVO_URL || "http://127.0.0.1:3000"), {
|
|
11
|
+
method: data === undefined ? "GET" : "POST", headers, redirect: "error",
|
|
12
|
+
body: JSON.stringify(data), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout),
|
|
13
|
+
});
|
|
14
|
+
const result = await response.json();
|
|
15
|
+
if (!response.ok) throw Object.assign(Error(result.error || "HTTP " + response.status), { status: response.status, view: result });
|
|
16
|
+
return result;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const fields = [
|
|
20
|
+
["minSlots", "Mínimo de cupos", 0, 64],
|
|
21
|
+
["maxSlots", "Máximo de turnos simultáneos", 0, 64],
|
|
22
|
+
["minAvailableMemoryMiB", "Memoria disponible mínima (MiB)", 1, Number.MAX_SAFE_INTEGER],
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
function panel(ctx, state) {
|
|
26
|
+
const r = state.resources;
|
|
27
|
+
// Después de 100 % se puede desactivar el objetivo sin cambiar los demás ajustes.
|
|
28
|
+
const off = 101;
|
|
29
|
+
let cpu = r.targetCpuPercent ?? off;
|
|
30
|
+
let row = 0;
|
|
31
|
+
return ctx.ui.custom((tui, theme, keys, done) => ({
|
|
32
|
+
render(width) {
|
|
33
|
+
const size = Math.max(3, Math.min(24, width - 28));
|
|
34
|
+
const marker = Math.round((cpu - 1) / (off - 1) * (size - 1));
|
|
35
|
+
const slider = "─".repeat(marker) + "●" + "─".repeat(size - marker - 1);
|
|
36
|
+
const options = ["CPU objetivo " + (cpu === off ? "Sin objetivo" : cpu + " %") + " " + slider,
|
|
37
|
+
...fields.map(([key, label]) => label + " " + (r[key] ?? "Sin configurar")), "Política de planificación", "Ver threads"];
|
|
38
|
+
return [theme.fg("accent", "Relevo"), "Máximo " + r.maxSlots +
|
|
39
|
+
" · " + state.occupied + " ocupados · " + r.effectiveLimit + " efectivos · " + state.queue.length + " en cola",
|
|
40
|
+
"", ...options.map((label, i) => i === row ? theme.fg("accent", "› " + label) : " " + label),
|
|
41
|
+
"", "↑↓ Elegir ←→ Ajustar CPU Enter Aplicar/editar Esc Cerrar"].map(line => truncateToWidth(line, width));
|
|
42
|
+
},
|
|
43
|
+
handleInput(key) {
|
|
44
|
+
if (keys.matches(key, "tui.select.cancel")) return done(null);
|
|
45
|
+
if (keys.matches(key, "tui.select.confirm")) {
|
|
46
|
+
done({ row, targetCpuPercent: cpu === off ? undefined : cpu });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (matchesKey(key, Key.up)) row = Math.max(0, row - 1);
|
|
50
|
+
if (matchesKey(key, Key.down)) row = Math.min(fields.length + 2, row + 1);
|
|
51
|
+
if (row === 0) {
|
|
52
|
+
if (matchesKey(key, Key.left)) cpu = Math.max(1, cpu - 1);
|
|
53
|
+
if (matchesKey(key, Key.right)) cpu = Math.min(off, cpu + 1);
|
|
54
|
+
}
|
|
55
|
+
tui.requestRender();
|
|
56
|
+
},
|
|
57
|
+
invalidate() {},
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function configure(ctx) {
|
|
62
|
+
while (true) {
|
|
63
|
+
const state = await api("state");
|
|
64
|
+
const choice = await panel(ctx, state);
|
|
65
|
+
if (!choice) return;
|
|
66
|
+
if (choice.row === fields.length + 2) {
|
|
67
|
+
const history = await verThreads(ctx, api);
|
|
68
|
+
if (history) return history;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (choice.row === fields.length + 1) {
|
|
72
|
+
const { policy, recipes } = await api("policy");
|
|
73
|
+
const custom = "Editar política completa";
|
|
74
|
+
const name = await ctx.ui.select("Política de planificación", [custom, ...recipes.map(r => r.name)]);
|
|
75
|
+
if (!name) continue;
|
|
76
|
+
if (name === custom) {
|
|
77
|
+
const raw = await ctx.ui.editor(custom, JSON.stringify(policy, null, 2));
|
|
78
|
+
if (raw === undefined) continue;
|
|
79
|
+
await api("policy", JSON.parse(raw));
|
|
80
|
+
} else {
|
|
81
|
+
await api("policy", recipes.find(r => r.name === name).policy);
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
let key = "targetCpuPercent";
|
|
85
|
+
let value = choice.targetCpuPercent;
|
|
86
|
+
if (choice.row !== 0) {
|
|
87
|
+
const [field, label, min, max] = fields[choice.row - 1];
|
|
88
|
+
key = field;
|
|
89
|
+
const hint = key === "maxSlots" ? label : label + " (vacío para desactivar)";
|
|
90
|
+
const raw = await ctx.ui.input(hint, String(state.resources[key] ?? ""));
|
|
91
|
+
if (raw === undefined) continue;
|
|
92
|
+
value = raw.trim() ? Number(raw) : undefined;
|
|
93
|
+
if (value === undefined ? key === "maxSlots" : !Number.isSafeInteger(value) || value < min || value > max) {
|
|
94
|
+
ctx.ui.notify("Valor fuera de rango.", "warning");
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (key === "maxSlots") {
|
|
99
|
+
await api("limit", { limit: value });
|
|
100
|
+
} else {
|
|
101
|
+
const { resources } = await api("state");
|
|
102
|
+
const { minSlots, targetCpuPercent, minAvailableMemoryMiB } = resources;
|
|
103
|
+
await api("resources", { minSlots, targetCpuPercent, minAvailableMemoryMiB, [key]: value });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
ctx.ui.notify("Configuración guardada en Relevo.", "info");
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export default function relevo(pi) {
|
|
111
|
+
const estadoVivo = iniciarSesionViva(pi);
|
|
112
|
+
coordinarTurnos(pi, api, estadoVivo);
|
|
113
|
+
pi.registerCommand("relevo", {
|
|
114
|
+
description: "Abrir el panel de Relevo: recursos y planificación",
|
|
115
|
+
async handler(args, ctx) {
|
|
116
|
+
if (!ctx.hasUI) return ctx.ui.notify("Abre /relevo en una sesión interactiva.", "warning");
|
|
117
|
+
try {
|
|
118
|
+
const history = args.trim().toLowerCase() === "threads" ? await verThreads(ctx, api) : await configure(ctx);
|
|
119
|
+
if (!history) return;
|
|
120
|
+
const paths = history.map(s => s.path);
|
|
121
|
+
const path = paths.length === 1 ? paths[0] : await ctx.ui.select("Abrir sesión de Pi", paths);
|
|
122
|
+
if (!path || path === ctx.sessionManager.getSessionFile()) return;
|
|
123
|
+
try { await access(path); }
|
|
124
|
+
catch { return ctx.ui.notify("El historial ya no está disponible en este equipo.", "warning"); }
|
|
125
|
+
const result = await ctx.switchSession(path);
|
|
126
|
+
if (result.cancelled) ctx.ui.notify("Cambio de sesión cancelado.", "info");
|
|
127
|
+
}
|
|
128
|
+
catch (error) { ctx.ui.notify("Relevo: " + error.message, "error"); }
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
}
|
package/turnos.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
|
|
3
|
+
// Una instancia de la extensión por sesión de Pi. Ningún prompt ni credencial del modelo sale hacia Relevo.
|
|
4
|
+
export function coordinarTurnos(pi, api, onStatus) {
|
|
5
|
+
let session;
|
|
6
|
+
let current;
|
|
7
|
+
let closing = false;
|
|
8
|
+
|
|
9
|
+
const path = (id, action) => "sessions/" + id + "/" + action;
|
|
10
|
+
const active = view => view.status === "running" || view.status === "cancelling";
|
|
11
|
+
const warn = (ctx, error) => ctx.ui.notify("Relevo: " + error.message, "error");
|
|
12
|
+
|
|
13
|
+
async function request(ctx, signal) {
|
|
14
|
+
if (session) {
|
|
15
|
+
try {
|
|
16
|
+
return await api(path(session.id, "turn"), { turn: session.turn });
|
|
17
|
+
} catch (error) {
|
|
18
|
+
// Una sesión inactiva caduca en diez minutos; el historial de Pi sigue siendo el mismo.
|
|
19
|
+
if (error.status !== 404 && !(error.status === 409 && error.view?.status === "cancelled")) throw error;
|
|
20
|
+
session = undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
// Registrar primero en espera permite recuperar el número antes de solicitar capacidad.
|
|
24
|
+
const id = ctx.sessionManager.getSessionId();
|
|
25
|
+
const suffix = id.length <= 110 ? " · #" + id : "";
|
|
26
|
+
const label = ("Pi · " + basename(ctx.cwd)).slice(0, 120 - suffix.length) + suffix;
|
|
27
|
+
session = await api("sessions", { client: "pi", label });
|
|
28
|
+
signal.throwIfAborted();
|
|
29
|
+
return api(path(session.id, "turn"), { turn: session.turn });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function finish(slot, ctx) {
|
|
33
|
+
clearTimeout(slot.pulse);
|
|
34
|
+
try {
|
|
35
|
+
if (!session) return;
|
|
36
|
+
const { id, turn } = session;
|
|
37
|
+
if (!slot.granted) {
|
|
38
|
+
try {
|
|
39
|
+
session = await api(path(id, "cancel"), { turn });
|
|
40
|
+
return;
|
|
41
|
+
} catch (error) {
|
|
42
|
+
// La cola puede haber concedido el turno mientras la persona pulsaba Esc.
|
|
43
|
+
if (error.status !== 409 || error.view?.turn !== turn) throw error;
|
|
44
|
+
if (error.view.status === "waiting") { session = error.view; return; }
|
|
45
|
+
if (!active(error.view)) throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
session = await api(path(id, "release"), { turn, next: closing ? "done" : "idle" });
|
|
49
|
+
} catch (error) {
|
|
50
|
+
session = undefined;
|
|
51
|
+
if (!closing) warn(ctx, error);
|
|
52
|
+
} finally {
|
|
53
|
+
if (!closing) ctx.ui.setStatus("relevo", undefined);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function keepAlive(slot, ctx, view) {
|
|
58
|
+
slot.pulse = setTimeout(async () => {
|
|
59
|
+
try {
|
|
60
|
+
const next = await api(path(view.id, "heartbeat"), { turn: view.turn });
|
|
61
|
+
if (current !== slot || closing) return;
|
|
62
|
+
if (next.status !== "running" || next.turn !== view.turn) throw Error("El permiso ya no está activo.");
|
|
63
|
+
keepAlive(slot, ctx, next);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (current !== slot || closing) return;
|
|
66
|
+
ctx.abort();
|
|
67
|
+
if (!closing) warn(ctx, error);
|
|
68
|
+
}
|
|
69
|
+
}, view.heartbeatMs);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
pi.on("turn_start", async (_event, ctx) => {
|
|
73
|
+
if (ctx.mode !== "tui") return;
|
|
74
|
+
if (closing) { ctx.abort(); return; }
|
|
75
|
+
const slot = { stop: new AbortController(), granted: false };
|
|
76
|
+
current = slot;
|
|
77
|
+
const signal = ctx.signal ? AbortSignal.any([ctx.signal, slot.stop.signal]) : slot.stop.signal;
|
|
78
|
+
try {
|
|
79
|
+
signal.throwIfAborted();
|
|
80
|
+
let view = await request(ctx, signal);
|
|
81
|
+
const turn = session.turn;
|
|
82
|
+
if (view.status === "queued") await onStatus?.(ctx, "queued");
|
|
83
|
+
while (view.status === "queued" && view.turn === turn) {
|
|
84
|
+
ctx.ui.setStatus("relevo", "Relevo · esperando cupo");
|
|
85
|
+
view = await api("sessions/" + view.id + "?wait=10000", undefined, { signal, timeout: 15000 });
|
|
86
|
+
}
|
|
87
|
+
signal.throwIfAborted();
|
|
88
|
+
if (view.turn !== turn || view.status !== "running" || view.leaseExpiresAt <= Date.now()) {
|
|
89
|
+
throw Error("El turno no tiene un cupo vigente.");
|
|
90
|
+
}
|
|
91
|
+
slot.granted = true;
|
|
92
|
+
ctx.ui.setStatus("relevo", "Relevo · cupo activo");
|
|
93
|
+
keepAlive(slot, ctx, view);
|
|
94
|
+
await onStatus?.(ctx, "running");
|
|
95
|
+
} catch (error) {
|
|
96
|
+
// Pi registra los errores de extensiones y continúa. Abortar explícitamente impide enviar el prompt.
|
|
97
|
+
if (!signal.aborted) { ctx.abort(); warn(ctx, error); }
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
async function endTurn(_event, ctx) {
|
|
102
|
+
const slot = current;
|
|
103
|
+
if (!slot) return;
|
|
104
|
+
current = undefined;
|
|
105
|
+
await finish(slot, ctx);
|
|
106
|
+
}
|
|
107
|
+
pi.on("turn_end", endTurn);
|
|
108
|
+
pi.on("agent_end", endTurn);
|
|
109
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
110
|
+
closing = true;
|
|
111
|
+
if (current) {
|
|
112
|
+
ctx.abort();
|
|
113
|
+
current.stop.abort();
|
|
114
|
+
}
|
|
115
|
+
if (current?.granted) {
|
|
116
|
+
// Si Pi cierra con herramientas en curso, conservar el cupo hasta el punto seguro o la caducidad.
|
|
117
|
+
clearTimeout(current.pulse);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (session) {
|
|
121
|
+
try { await api(path(session.id, "cancel"), {}); }
|
|
122
|
+
catch (error) {
|
|
123
|
+
if (error.status === 409 && error.view?.turn === session?.turn && active(error.view)) {
|
|
124
|
+
await api(path(session.id, "release"), { turn: error.view.turn, next: "done" });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
package/README.md
DELETED