@vaia-lab/sdk 0.1.3 → 0.3.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/LICENSE +21 -0
- package/README.md +107 -151
- package/dist/cli.js +252 -0
- package/dist/index.cjs +747 -28
- package/dist/index.d.cts +754 -5
- package/dist/index.d.ts +754 -5
- package/dist/index.js +728 -27
- package/package.json +13 -2
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -23,10 +23,12 @@ __export(gandia_exports, {
|
|
|
23
23
|
// src/crypto.ts
|
|
24
24
|
var enc = new TextEncoder();
|
|
25
25
|
function hexToBytes(hex) {
|
|
26
|
-
if (hex.length % 2 !== 0
|
|
27
|
-
|
|
26
|
+
if (hex.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(hex)) {
|
|
27
|
+
throw new Error("Invalid hex string");
|
|
28
|
+
}
|
|
29
|
+
const bytes = new Uint8Array(new ArrayBuffer(hex.length / 2));
|
|
28
30
|
for (let i = 0; i < hex.length; i += 2) {
|
|
29
|
-
bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
|
|
31
|
+
bytes[i / 2] = Number.parseInt(hex.slice(i, i + 2), 16);
|
|
30
32
|
}
|
|
31
33
|
return bytes;
|
|
32
34
|
}
|
|
@@ -70,9 +72,7 @@ async function verify(request, secret) {
|
|
|
70
72
|
const sigHeader = headers.get("x-gandia-signature") ?? "";
|
|
71
73
|
const tsHeader = headers.get("x-gandia-timestamp") ?? "";
|
|
72
74
|
const callId = headers.get("x-gandia-call-id") ?? "";
|
|
73
|
-
|
|
74
|
-
return { ctx: buildProbeCtx(callId), raw: rawBody };
|
|
75
|
-
}
|
|
75
|
+
const esProbe = headers.get(PROBE_HEADER) === "1";
|
|
76
76
|
if (!sigHeader || !tsHeader) {
|
|
77
77
|
throw new VAIAError(
|
|
78
78
|
"Faltan headers de autenticaci\xF3n (X-Gandia-Signature, X-Gandia-Timestamp)",
|
|
@@ -90,6 +90,9 @@ async function verify(request, secret) {
|
|
|
90
90
|
if (!valid) {
|
|
91
91
|
throw new VAIAError("Firma HMAC inv\xE1lida", "HMAC_INVALID", 401);
|
|
92
92
|
}
|
|
93
|
+
if (esProbe) {
|
|
94
|
+
return { ctx: buildProbeCtx(callId), raw: rawBody };
|
|
95
|
+
}
|
|
93
96
|
let body;
|
|
94
97
|
try {
|
|
95
98
|
body = JSON.parse(rawBody);
|
|
@@ -174,14 +177,28 @@ __export(jwt_exports, {
|
|
|
174
177
|
|
|
175
178
|
// src/jwt-utils.ts
|
|
176
179
|
var enc2 = new TextEncoder();
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
+
var utf8Strict = new TextDecoder("utf-8", { fatal: true });
|
|
181
|
+
var utf8Loose = new TextDecoder("utf-8");
|
|
182
|
+
var latin1 = new TextDecoder("latin1");
|
|
183
|
+
var JWT_PAYLOAD_VERSION = 2;
|
|
184
|
+
function bytesToB64url(bytes) {
|
|
185
|
+
let bin = "";
|
|
186
|
+
const CHUNK = 32768;
|
|
187
|
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
188
|
+
bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
|
|
189
|
+
}
|
|
190
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
180
191
|
}
|
|
181
|
-
function
|
|
192
|
+
function b64urlToBytes(str2) {
|
|
182
193
|
const padded = str2.replace(/-/g, "+").replace(/_/g, "/");
|
|
183
194
|
const pad = padded.length % 4;
|
|
184
|
-
|
|
195
|
+
const bin = atob(pad ? padded + "=".repeat(4 - pad) : padded);
|
|
196
|
+
const out = new Uint8Array(new ArrayBuffer(bin.length));
|
|
197
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
function textToB64url(text) {
|
|
201
|
+
return bytesToB64url(enc2.encode(text));
|
|
185
202
|
}
|
|
186
203
|
async function importHMACKey2(secret) {
|
|
187
204
|
return crypto.subtle.importKey(
|
|
@@ -192,13 +209,33 @@ async function importHMACKey2(secret) {
|
|
|
192
209
|
["sign", "verify"]
|
|
193
210
|
);
|
|
194
211
|
}
|
|
195
|
-
var HEADER =
|
|
212
|
+
var HEADER = textToB64url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
|
|
196
213
|
async function jwtSign(payload, secret) {
|
|
197
|
-
const body =
|
|
214
|
+
const body = textToB64url(JSON.stringify({ ...payload, v: JWT_PAYLOAD_VERSION }));
|
|
198
215
|
const unsigned = `${HEADER}.${body}`;
|
|
199
216
|
const key = await importHMACKey2(secret);
|
|
200
217
|
const sig = await crypto.subtle.sign("HMAC", key, enc2.encode(unsigned));
|
|
201
|
-
return `${unsigned}.${
|
|
218
|
+
return `${unsigned}.${bytesToB64url(new Uint8Array(sig))}`;
|
|
219
|
+
}
|
|
220
|
+
function decodePayload(body) {
|
|
221
|
+
const bytes = b64urlToBytes(body);
|
|
222
|
+
let sonda;
|
|
223
|
+
try {
|
|
224
|
+
sonda = JSON.parse(latin1.decode(bytes));
|
|
225
|
+
} catch {
|
|
226
|
+
throw new VAIAError("JWT payload inv\xE1lido", "JWT_PAYLOAD_INVALID", 401);
|
|
227
|
+
}
|
|
228
|
+
const version = typeof sonda["v"] === "number" ? sonda["v"] : 1;
|
|
229
|
+
if (version < 2) return sonda;
|
|
230
|
+
try {
|
|
231
|
+
return JSON.parse(utf8Strict.decode(bytes));
|
|
232
|
+
} catch {
|
|
233
|
+
try {
|
|
234
|
+
return JSON.parse(utf8Loose.decode(bytes));
|
|
235
|
+
} catch {
|
|
236
|
+
throw new VAIAError("JWT payload inv\xE1lido", "JWT_PAYLOAD_INVALID", 401);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
202
239
|
}
|
|
203
240
|
async function jwtVerify(token, secret) {
|
|
204
241
|
const parts = token.split(".");
|
|
@@ -208,17 +245,16 @@ async function jwtVerify(token, secret) {
|
|
|
208
245
|
const [header, body, sig] = parts;
|
|
209
246
|
const unsigned = `${header}.${body}`;
|
|
210
247
|
const key = await importHMACKey2(secret);
|
|
211
|
-
|
|
212
|
-
const valid = await crypto.subtle.verify("HMAC", key, sigBytes, enc2.encode(unsigned));
|
|
213
|
-
if (!valid) {
|
|
214
|
-
throw new VAIAError("Firma JWT inv\xE1lida", "JWT_SIGNATURE_INVALID", 401);
|
|
215
|
-
}
|
|
216
|
-
let payload;
|
|
248
|
+
let valid;
|
|
217
249
|
try {
|
|
218
|
-
|
|
250
|
+
valid = await crypto.subtle.verify("HMAC", key, b64urlToBytes(sig), enc2.encode(unsigned));
|
|
219
251
|
} catch {
|
|
220
|
-
throw new VAIAError("JWT
|
|
252
|
+
throw new VAIAError("JWT malformado", "JWT_MALFORMED", 401);
|
|
221
253
|
}
|
|
254
|
+
if (!valid) {
|
|
255
|
+
throw new VAIAError("Firma JWT inv\xE1lida", "JWT_SIGNATURE_INVALID", 401);
|
|
256
|
+
}
|
|
257
|
+
const payload = decodePayload(body);
|
|
222
258
|
if (typeof payload.exp === "number" && Date.now() / 1e3 > payload.exp) {
|
|
223
259
|
throw new VAIAError("JWT expirado", "JWT_EXPIRED", 401);
|
|
224
260
|
}
|
|
@@ -416,9 +452,7 @@ async function verify3(request, secret) {
|
|
|
416
452
|
const sigHeader = headers.get("x-handeia-signature") ?? "";
|
|
417
453
|
const tsHeader = headers.get("x-handeia-timestamp") ?? "";
|
|
418
454
|
const callId = headers.get("x-handeia-call-id") ?? "";
|
|
419
|
-
|
|
420
|
-
return { ctx: buildProbeCtx2(callId), raw: rawBody };
|
|
421
|
-
}
|
|
455
|
+
const esProbe = headers.get(PROBE_HEADER2) === "1";
|
|
422
456
|
if (!sigHeader || !tsHeader) {
|
|
423
457
|
throw new VAIAError(
|
|
424
458
|
"Faltan headers de autenticaci\xF3n (X-Handeia-Signature, X-Handeia-Timestamp)",
|
|
@@ -436,6 +470,9 @@ async function verify3(request, secret) {
|
|
|
436
470
|
if (!valid) {
|
|
437
471
|
throw new VAIAError("Firma HMAC inv\xE1lida", "HMAC_INVALID", 401);
|
|
438
472
|
}
|
|
473
|
+
if (esProbe) {
|
|
474
|
+
return { ctx: buildProbeCtx2(callId), raw: rawBody };
|
|
475
|
+
}
|
|
439
476
|
let body;
|
|
440
477
|
try {
|
|
441
478
|
body = JSON.parse(rawBody);
|
|
@@ -519,6 +556,154 @@ async function fromUrl2(url, secret) {
|
|
|
519
556
|
return verify4(token, secret);
|
|
520
557
|
}
|
|
521
558
|
|
|
559
|
+
// src/agent.ts
|
|
560
|
+
var AGENT_PROTOCOL_VERSION = 1;
|
|
561
|
+
var CONNECTOR_OF_OPERATION = {
|
|
562
|
+
"github.repos": "github",
|
|
563
|
+
"github.issues": "github",
|
|
564
|
+
"drive.files": "drive",
|
|
565
|
+
"calendar.events": "calendar",
|
|
566
|
+
"email.recent": "email",
|
|
567
|
+
"notion.pages": "notion"
|
|
568
|
+
};
|
|
569
|
+
var NOMBRE_ACCION = /^[a-z][a-z0-9_]{1,48}$/;
|
|
570
|
+
function validateAgentSurface(cfg) {
|
|
571
|
+
const errores = [];
|
|
572
|
+
const vistos = /* @__PURE__ */ new Set();
|
|
573
|
+
for (const accion of cfg.actions ?? []) {
|
|
574
|
+
if (!NOMBRE_ACCION.test(accion.name)) {
|
|
575
|
+
errores.push(`Acci\xF3n "${accion.name}": el nombre debe ser min\xFAsculas, n\xFAmeros o guion bajo.`);
|
|
576
|
+
}
|
|
577
|
+
if (vistos.has(accion.name)) {
|
|
578
|
+
errores.push(`Acci\xF3n "${accion.name}": declarada dos veces.`);
|
|
579
|
+
}
|
|
580
|
+
vistos.add(accion.name);
|
|
581
|
+
if (!accion.description?.trim()) {
|
|
582
|
+
errores.push(`Acci\xF3n "${accion.name}": falta la descripci\xF3n, que es lo que el agente lee para elegirla.`);
|
|
583
|
+
}
|
|
584
|
+
if (accion.writes && !accion.permission) {
|
|
585
|
+
errores.push(`Acci\xF3n "${accion.name}": modifica datos, as\xED que necesita un permiso declarado.`);
|
|
586
|
+
}
|
|
587
|
+
for (const p of accion.params ?? []) {
|
|
588
|
+
if (!p.name?.trim()) errores.push(`Acci\xF3n "${accion.name}": un par\xE1metro no tiene nombre.`);
|
|
589
|
+
if (!p.description?.trim()) {
|
|
590
|
+
errores.push(`Acci\xF3n "${accion.name}", par\xE1metro "${p.name}": falta la descripci\xF3n.`);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if (cfg.queryEndpoint && !cfg.queryEndpoint.startsWith("/")) {
|
|
595
|
+
errores.push('queryEndpoint debe ser una ruta de tu propio servidor, empezando por "/".');
|
|
596
|
+
}
|
|
597
|
+
return errores;
|
|
598
|
+
}
|
|
599
|
+
function validateActionCall(llamada, declaradas) {
|
|
600
|
+
const action = declaradas.find((a) => a.name === llamada.name);
|
|
601
|
+
if (!action) return { ok: false, reason: `La acci\xF3n "${llamada.name}" no est\xE1 declarada por el espacio.` };
|
|
602
|
+
const args = llamada.args ?? {};
|
|
603
|
+
for (const p of action.params ?? []) {
|
|
604
|
+
const v = args[p.name];
|
|
605
|
+
if (v === void 0 || v === null) {
|
|
606
|
+
if (p.required) return { ok: false, reason: `Falta el par\xE1metro obligatorio "${p.name}".` };
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
if (typeof v !== p.type) {
|
|
610
|
+
return { ok: false, reason: `El par\xE1metro "${p.name}" debe ser ${p.type}.` };
|
|
611
|
+
}
|
|
612
|
+
if (p.enum && !p.enum.includes(String(v))) {
|
|
613
|
+
return { ok: false, reason: `El par\xE1metro "${p.name}" no admite el valor "${String(v)}".` };
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
const permitidos = new Set((action.params ?? []).map((p) => p.name));
|
|
617
|
+
for (const k of Object.keys(args)) {
|
|
618
|
+
if (!permitidos.has(k)) return { ok: false, reason: `El par\xE1metro "${k}" no est\xE1 declarado.` };
|
|
619
|
+
}
|
|
620
|
+
return { ok: true, action };
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// src/pieces.ts
|
|
624
|
+
var NOMBRE = /^[a-z][a-z0-9_]{1,48}$/;
|
|
625
|
+
var ORDEN = {
|
|
626
|
+
prohibida: 0,
|
|
627
|
+
requiere_aprobacion: 1,
|
|
628
|
+
autonoma: 2
|
|
629
|
+
};
|
|
630
|
+
function validatePieces(cfg) {
|
|
631
|
+
const errores = [];
|
|
632
|
+
const vistos = /* @__PURE__ */ new Set();
|
|
633
|
+
const revisarNombre = (pieza, name) => {
|
|
634
|
+
if (!NOMBRE.test(name)) errores.push(`${pieza} "${name}": el nombre debe ser min\xFAsculas, n\xFAmeros o guion bajo.`);
|
|
635
|
+
if (vistos.has(name)) errores.push(`"${name}": hay dos piezas con el mismo nombre.`);
|
|
636
|
+
vistos.add(name);
|
|
637
|
+
};
|
|
638
|
+
const revisarAutoridad = (pieza, a) => {
|
|
639
|
+
if (a.consequence === "irreversible" && a.level === "autonoma") {
|
|
640
|
+
errores.push(`${pieza}: una acci\xF3n irreversible no puede ser aut\xF3noma \u2014 como m\xEDnimo requiere aprobaci\xF3n.`);
|
|
641
|
+
}
|
|
642
|
+
if (a.maxAmount !== void 0) {
|
|
643
|
+
if (a.maxAmount <= 0) errores.push(`${pieza}: el tope de gasto debe ser mayor que cero.`);
|
|
644
|
+
if (!a.currency) errores.push(`${pieza}: hay tope de gasto pero no se declar\xF3 la moneda.`);
|
|
645
|
+
}
|
|
646
|
+
if (a.consequence === "costosa" && a.level === "autonoma" && a.maxAmount === void 0) {
|
|
647
|
+
errores.push(`${pieza}: es aut\xF3noma y cuesta dinero, as\xED que necesita un tope declarado.`);
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
for (const s2 of cfg.skills ?? []) {
|
|
651
|
+
revisarNombre("Skill", s2.name);
|
|
652
|
+
if (!s2.description?.trim()) errores.push(`Skill "${s2.name}": falta la descripci\xF3n, que es lo que el modelo lee para elegirla.`);
|
|
653
|
+
if (s2.evidence?.required && (s2.evidence.accepts?.length ?? 0) === 0) {
|
|
654
|
+
errores.push(`Skill "${s2.name}": exige evidencia pero no declara qu\xE9 tipos acepta.`);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
for (const t of cfg.tools ?? []) {
|
|
658
|
+
revisarNombre("Herramienta", t.name);
|
|
659
|
+
if (!t.description?.trim()) errores.push(`Herramienta "${t.name}": falta la descripci\xF3n.`);
|
|
660
|
+
if (!t.permission?.trim()) errores.push(`Herramienta "${t.name}": toca el mundo real, as\xED que necesita un permiso declarado.`);
|
|
661
|
+
revisarAutoridad(`Herramienta "${t.name}"`, t.authority);
|
|
662
|
+
}
|
|
663
|
+
for (const w of cfg.workflows ?? []) {
|
|
664
|
+
revisarNombre("Workflow", w.name);
|
|
665
|
+
if ((w.steps?.length ?? 0) === 0) errores.push(`Workflow "${w.name}": no tiene pasos.`);
|
|
666
|
+
revisarAutoridad(`Workflow "${w.name}"`, w.authority);
|
|
667
|
+
}
|
|
668
|
+
const porNombre = new Map((cfg.tools ?? []).map((t) => [t.name, t]));
|
|
669
|
+
for (const a of cfg.agents ?? []) {
|
|
670
|
+
revisarNombre("Agente", a.name);
|
|
671
|
+
if (!a.purpose?.trim()) {
|
|
672
|
+
errores.push(`Agente "${a.name}": falta el prop\xF3sito \u2014 para qu\xE9 existe.`);
|
|
673
|
+
}
|
|
674
|
+
revisarAutoridad(`Agente "${a.name}"`, a.authority);
|
|
675
|
+
for (const nombreTool of a.tools ?? []) {
|
|
676
|
+
const tool = porNombre.get(nombreTool);
|
|
677
|
+
if (!tool) {
|
|
678
|
+
errores.push(`Agente "${a.name}": usa la herramienta "${nombreTool}", que no est\xE1 declarada.`);
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
if (ORDEN[tool.authority.level] > ORDEN[a.authority.level]) {
|
|
682
|
+
errores.push(
|
|
683
|
+
`Agente "${a.name}": su herramienta "${nombreTool}" tiene m\xE1s autoridad que \xE9l. Ninguna pieza puede superar el techo de su agente.`
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return errores;
|
|
689
|
+
}
|
|
690
|
+
function requiresApproval(a) {
|
|
691
|
+
return a.level !== "autonoma";
|
|
692
|
+
}
|
|
693
|
+
function checkAuthority(a, intento = {}) {
|
|
694
|
+
if (a.level === "prohibida") return { ok: false, reason: "Esta acci\xF3n est\xE1 prohibida para esta pieza." };
|
|
695
|
+
if (intento.amount !== void 0) {
|
|
696
|
+
if (a.maxAmount === void 0) return { ok: false, reason: "Mueve dinero pero no hay tope declarado." };
|
|
697
|
+
if (intento.currency && a.currency && intento.currency !== a.currency) {
|
|
698
|
+
return { ok: false, reason: `Moneda distinta a la declarada (${a.currency}).` };
|
|
699
|
+
}
|
|
700
|
+
if (intento.amount > a.maxAmount) {
|
|
701
|
+
return { ok: false, reason: `Excede el tope declarado (${a.maxAmount} ${a.currency ?? ""}).`.trim() };
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
return { ok: true };
|
|
705
|
+
}
|
|
706
|
+
|
|
522
707
|
// src/define.ts
|
|
523
708
|
function defineCapability(config) {
|
|
524
709
|
const required = ["id", "name", "version", "target", "type", "sector", "permissions", "risk"];
|
|
@@ -535,6 +720,20 @@ function defineCapability(config) {
|
|
|
535
720
|
if (Object.keys(config.surfaces).length === 0) {
|
|
536
721
|
throw new Error(`[@vaia/sdk] defineCapability: 'surfaces' no puede estar vac\xEDo. Define al menos un surface con su endpoint.`);
|
|
537
722
|
}
|
|
723
|
+
if (config.pieces) {
|
|
724
|
+
const errores = validatePieces(config.pieces);
|
|
725
|
+
if (errores.length > 0) {
|
|
726
|
+
throw new Error(`[@vaia/sdk] defineCapability: piezas inv\xE1lidas:
|
|
727
|
+
- ${errores.join("\n - ")}`);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
if (config.agent) {
|
|
731
|
+
const errores = validateAgentSurface(config.agent);
|
|
732
|
+
if (errores.length > 0) {
|
|
733
|
+
throw new Error(`[@vaia/sdk] defineCapability: superficie de agente inv\xE1lida:
|
|
734
|
+
- ${errores.join("\n - ")}`);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
538
737
|
return config;
|
|
539
738
|
}
|
|
540
739
|
function toManifest(config) {
|
|
@@ -549,6 +748,16 @@ function toManifest(config) {
|
|
|
549
748
|
level: config.level,
|
|
550
749
|
sector: config.sector,
|
|
551
750
|
surfaces,
|
|
751
|
+
// El agente viaja en el manifest para que el portal y Handeia sepan qué
|
|
752
|
+
// puede hacer este espacio sin abrir su código.
|
|
753
|
+
agent: config.agent ? {
|
|
754
|
+
protocol: AGENT_PROTOCOL_VERSION,
|
|
755
|
+
actions: config.agent.actions ?? [],
|
|
756
|
+
query_endpoint: config.agent.queryEndpoint
|
|
757
|
+
} : void 0,
|
|
758
|
+
// Las piezas viajan al manifest: el portal necesita mostrar qué autoridad
|
|
759
|
+
// pide una capacidad ANTES de que alguien la instale.
|
|
760
|
+
pieces: config.pieces,
|
|
552
761
|
permissions: config.permissions,
|
|
553
762
|
risk: config.risk,
|
|
554
763
|
has_own_auth: config.has_own_auth ?? false,
|
|
@@ -563,14 +772,506 @@ function toManifest(config) {
|
|
|
563
772
|
};
|
|
564
773
|
}
|
|
565
774
|
|
|
775
|
+
// src/agent-mount.ts
|
|
776
|
+
var HANDEIA_POR_DEFECTO = "https://handeia.com";
|
|
777
|
+
var RUTA_TURNO = "/api/agent/space";
|
|
778
|
+
var CSS = `
|
|
779
|
+
.hdi-agent-root{position:fixed;z-index:2147483000;bottom:20px;right:20px;font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
780
|
+
.hdi-agent-orb{width:44px;height:44px;border-radius:9999px;border:0;cursor:pointer;background:#000;color:#fff;display:flex;align-items:center;justify-content:center;box-shadow:0 10px 30px -6px rgba(0,0,0,.4);transition:transform .15s}
|
|
781
|
+
.hdi-agent-orb:hover{transform:scale(1.05)}
|
|
782
|
+
.hdi-agent-orb:active{transform:scale(.95)}
|
|
783
|
+
.hdi-agent-panel{position:absolute;bottom:56px;right:0;width:min(360px,calc(100vw - 40px));background:#fff;color:#111;border:1px solid rgba(0,0,0,.09);border-radius:18px;box-shadow:0 24px 60px -18px rgba(0,0,0,.32);overflow:hidden;display:flex;flex-direction:column;max-height:min(60vh,460px)}
|
|
784
|
+
.hdi-agent-head{display:flex;align-items:center;gap:8px;padding:12px 14px;border-bottom:1px solid rgba(0,0,0,.06);font-size:12.5px;font-weight:600}
|
|
785
|
+
.hdi-agent-dot{width:7px;height:7px;border-radius:9999px;background:#8b5cf6}
|
|
786
|
+
.hdi-agent-log{flex:1;overflow-y:auto;padding:12px 14px;display:flex;flex-direction:column;gap:10px;font-size:13px;line-height:1.55}
|
|
787
|
+
.hdi-agent-turn{white-space:pre-wrap}
|
|
788
|
+
.hdi-agent-q{font-size:10.5px;letter-spacing:.14em;text-transform:uppercase;color:rgba(0,0,0,.34)}
|
|
789
|
+
.hdi-agent-form{display:flex;gap:8px;padding:10px 12px;border-top:1px solid rgba(0,0,0,.06)}
|
|
790
|
+
.hdi-agent-input{flex:1;border:1px solid rgba(0,0,0,.12);border-radius:10px;padding:8px 10px;font:inherit;font-size:13px;outline:none}
|
|
791
|
+
.hdi-agent-input:focus{border-color:rgba(0,0,0,.34)}
|
|
792
|
+
.hdi-agent-send{border:0;border-radius:10px;padding:0 12px;background:#000;color:#fff;cursor:pointer;font-size:12.5px}
|
|
793
|
+
.hdi-agent-confirm{display:flex;gap:8px;margin-top:4px}
|
|
794
|
+
.hdi-agent-btn{border:1px solid rgba(0,0,0,.14);background:#fff;border-radius:9999px;padding:5px 12px;font-size:12px;cursor:pointer}
|
|
795
|
+
.hdi-agent-btn-primary{background:#000;color:#fff;border-color:#000}
|
|
796
|
+
@media (prefers-color-scheme:dark){
|
|
797
|
+
.hdi-agent-orb{background:#fff;color:#000}
|
|
798
|
+
.hdi-agent-panel{background:#171717;color:#f5f5f5;border-color:rgba(255,255,255,.13)}
|
|
799
|
+
.hdi-agent-head,.hdi-agent-form{border-color:rgba(255,255,255,.1)}
|
|
800
|
+
.hdi-agent-q{color:rgba(255,255,255,.5)}
|
|
801
|
+
.hdi-agent-input{background:transparent;color:inherit;border-color:rgba(255,255,255,.16)}
|
|
802
|
+
.hdi-agent-send{background:#fff;color:#000}
|
|
803
|
+
.hdi-agent-btn{background:transparent;color:inherit;border-color:rgba(255,255,255,.18)}
|
|
804
|
+
.hdi-agent-btn-primary{background:#fff;color:#000}
|
|
805
|
+
}`;
|
|
806
|
+
function el(tag, cls, text) {
|
|
807
|
+
const n = document.createElement(tag);
|
|
808
|
+
if (cls) n.className = cls;
|
|
809
|
+
if (text !== void 0) n.textContent = text;
|
|
810
|
+
return n;
|
|
811
|
+
}
|
|
812
|
+
function mountAgent(opts) {
|
|
813
|
+
if (typeof document === "undefined") {
|
|
814
|
+
throw new Error("[@vaia-lab/sdk] mountAgent solo corre en el navegador.");
|
|
815
|
+
}
|
|
816
|
+
const base = (opts.handeiaUrl ?? HANDEIA_POR_DEFECTO).replace(/\/$/, "");
|
|
817
|
+
const contenedor = opts.container ?? document.body;
|
|
818
|
+
const previo = contenedor.querySelector(".hdi-agent-root");
|
|
819
|
+
if (previo) previo.remove();
|
|
820
|
+
if (!document.getElementById("hdi-agent-css")) {
|
|
821
|
+
const estilo = el("style");
|
|
822
|
+
estilo.id = "hdi-agent-css";
|
|
823
|
+
estilo.textContent = CSS;
|
|
824
|
+
document.head.appendChild(estilo);
|
|
825
|
+
}
|
|
826
|
+
const raiz = el("div", "hdi-agent-root");
|
|
827
|
+
const orbe = el("button", "hdi-agent-orb");
|
|
828
|
+
orbe.type = "button";
|
|
829
|
+
orbe.setAttribute("aria-label", "Abrir asistente de Handeia");
|
|
830
|
+
orbe.textContent = "\u2726";
|
|
831
|
+
const panel = el("div", "hdi-agent-panel");
|
|
832
|
+
panel.hidden = true;
|
|
833
|
+
panel.setAttribute("role", "dialog");
|
|
834
|
+
panel.setAttribute("aria-label", "Asistente de Handeia");
|
|
835
|
+
const cabeza = el("div", "hdi-agent-head");
|
|
836
|
+
cabeza.appendChild(el("span", "hdi-agent-dot"));
|
|
837
|
+
cabeza.appendChild(el("span", void 0, "Handeia"));
|
|
838
|
+
const registro = el("div", "hdi-agent-log");
|
|
839
|
+
if (opts.greeting) registro.appendChild(el("div", "hdi-agent-turn", opts.greeting));
|
|
840
|
+
const forma = el("form", "hdi-agent-form");
|
|
841
|
+
const entrada = el("input", "hdi-agent-input");
|
|
842
|
+
entrada.type = "text";
|
|
843
|
+
entrada.placeholder = "Preg\xFAntale a Handeia\u2026";
|
|
844
|
+
entrada.autocomplete = "off";
|
|
845
|
+
const enviar = el("button", "hdi-agent-send", "Enviar");
|
|
846
|
+
enviar.type = "submit";
|
|
847
|
+
forma.append(entrada, enviar);
|
|
848
|
+
panel.append(cabeza, registro, forma);
|
|
849
|
+
raiz.append(panel, orbe);
|
|
850
|
+
contenedor.appendChild(raiz);
|
|
851
|
+
const historial = [];
|
|
852
|
+
const decir = (texto, clase = "hdi-agent-turn") => {
|
|
853
|
+
const n = el("div", clase, texto);
|
|
854
|
+
registro.appendChild(n);
|
|
855
|
+
registro.scrollTop = registro.scrollHeight;
|
|
856
|
+
return n;
|
|
857
|
+
};
|
|
858
|
+
async function turno(mensaje, actionResult) {
|
|
859
|
+
let context;
|
|
860
|
+
try {
|
|
861
|
+
context = await opts.getContext?.();
|
|
862
|
+
} catch {
|
|
863
|
+
context = void 0;
|
|
864
|
+
}
|
|
865
|
+
let res;
|
|
866
|
+
try {
|
|
867
|
+
res = await fetch(`${base}${RUTA_TURNO}`, {
|
|
868
|
+
method: "POST",
|
|
869
|
+
// La identidad va en la cookie de sesión de Handeia. El espacio nunca
|
|
870
|
+
// toca ni ve el token del usuario.
|
|
871
|
+
credentials: "include",
|
|
872
|
+
headers: { "Content-Type": "application/json; charset=utf-8" },
|
|
873
|
+
body: JSON.stringify({
|
|
874
|
+
protocol: AGENT_PROTOCOL_VERSION,
|
|
875
|
+
capId: opts.capabilityId,
|
|
876
|
+
message: mensaje,
|
|
877
|
+
context,
|
|
878
|
+
actions: opts.actions ?? [],
|
|
879
|
+
history: historial.slice(-12),
|
|
880
|
+
actionResult
|
|
881
|
+
})
|
|
882
|
+
});
|
|
883
|
+
} catch {
|
|
884
|
+
decir("No pude comunicarme con Handeia. Revisa tu conexi\xF3n.");
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
let data;
|
|
888
|
+
try {
|
|
889
|
+
data = await res.json();
|
|
890
|
+
} catch {
|
|
891
|
+
decir("Handeia respondi\xF3 algo que no pude leer.");
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
if (!res.ok || data.ok === false) {
|
|
895
|
+
decir(
|
|
896
|
+
data.error === "no_autenticado" ? "Inicia sesi\xF3n en Handeia para usar el asistente." : data.error === "espacio_no_instalado" ? "Este espacio no est\xE1 instalado en tu Handeia." : "Handeia no pudo responder ahora mismo."
|
|
897
|
+
);
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
if (data.text) {
|
|
901
|
+
decir(data.text);
|
|
902
|
+
historial.push({ role: "agent", text: data.text });
|
|
903
|
+
}
|
|
904
|
+
if (!data.action) return;
|
|
905
|
+
if (!opts.onAction) {
|
|
906
|
+
decir("Esto requiere una acci\xF3n que este espacio todav\xEDa no sabe ejecutar.");
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
const ejecutar = async () => {
|
|
910
|
+
let resultado;
|
|
911
|
+
try {
|
|
912
|
+
resultado = await opts.onAction(data.action.name, data.action.args ?? {});
|
|
913
|
+
} catch (e) {
|
|
914
|
+
resultado = { action: data.action.name, ok: false, error: e instanceof Error ? e.message : "fall\xF3" };
|
|
915
|
+
}
|
|
916
|
+
await turno(mensaje, resultado);
|
|
917
|
+
};
|
|
918
|
+
if (data.confirm) {
|
|
919
|
+
const fila = el("div", "hdi-agent-confirm");
|
|
920
|
+
const si = el("button", "hdi-agent-btn hdi-agent-btn-primary", "Hacerlo");
|
|
921
|
+
const no = el("button", "hdi-agent-btn", "Cancelar");
|
|
922
|
+
si.type = "button";
|
|
923
|
+
no.type = "button";
|
|
924
|
+
si.onclick = () => {
|
|
925
|
+
fila.remove();
|
|
926
|
+
void ejecutar();
|
|
927
|
+
};
|
|
928
|
+
no.onclick = () => {
|
|
929
|
+
fila.remove();
|
|
930
|
+
decir("Cancelado.");
|
|
931
|
+
};
|
|
932
|
+
fila.append(si, no);
|
|
933
|
+
registro.appendChild(fila);
|
|
934
|
+
registro.scrollTop = registro.scrollHeight;
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
await ejecutar();
|
|
938
|
+
}
|
|
939
|
+
forma.onsubmit = async (e) => {
|
|
940
|
+
e.preventDefault();
|
|
941
|
+
const texto = entrada.value.trim();
|
|
942
|
+
if (!texto) return;
|
|
943
|
+
entrada.value = "";
|
|
944
|
+
decir(texto, "hdi-agent-q");
|
|
945
|
+
historial.push({ role: "user", text: texto });
|
|
946
|
+
enviar.disabled = true;
|
|
947
|
+
try {
|
|
948
|
+
await turno(texto);
|
|
949
|
+
} finally {
|
|
950
|
+
enviar.disabled = false;
|
|
951
|
+
entrada.focus();
|
|
952
|
+
}
|
|
953
|
+
};
|
|
954
|
+
const abrir = () => {
|
|
955
|
+
panel.hidden = false;
|
|
956
|
+
entrada.focus();
|
|
957
|
+
};
|
|
958
|
+
const cerrar = () => {
|
|
959
|
+
panel.hidden = true;
|
|
960
|
+
};
|
|
961
|
+
orbe.onclick = () => panel.hidden ? abrir() : cerrar();
|
|
962
|
+
const alTeclear = (e) => {
|
|
963
|
+
if (e.key === "Escape") cerrar();
|
|
964
|
+
};
|
|
965
|
+
document.addEventListener("keydown", alTeclear);
|
|
966
|
+
return {
|
|
967
|
+
open: abrir,
|
|
968
|
+
close: cerrar,
|
|
969
|
+
destroy: () => {
|
|
970
|
+
document.removeEventListener("keydown", alTeclear);
|
|
971
|
+
raiz.remove();
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
// src/capabilities.ts
|
|
977
|
+
async function conAutoridad(tools, call, ejecutar) {
|
|
978
|
+
const tool = tools.find((t) => t.name === call.name);
|
|
979
|
+
if (!tool) {
|
|
980
|
+
return { ok: false, error: `La operaci\xF3n "${call.name}" no est\xE1 declarada en esta capacidad.` };
|
|
981
|
+
}
|
|
982
|
+
const permitido = checkAuthority(tool.authority, {
|
|
983
|
+
amount: call.amount,
|
|
984
|
+
currency: call.currency
|
|
985
|
+
});
|
|
986
|
+
if (!permitido.ok) return { ok: false, error: permitido.reason };
|
|
987
|
+
if (tool.authority.level === "prohibida") {
|
|
988
|
+
return { ok: false, error: `"${call.name}" est\xE1 prohibida.` };
|
|
989
|
+
}
|
|
990
|
+
if (tool.authority.level !== "autonoma" && !call.approved) {
|
|
991
|
+
return { ok: false, needsApproval: true, error: "Requiere aprobaci\xF3n humana antes de ejecutarse." };
|
|
992
|
+
}
|
|
993
|
+
try {
|
|
994
|
+
return await ejecutar();
|
|
995
|
+
} catch (e) {
|
|
996
|
+
return { ok: false, error: e instanceof Error ? e.message : "La capacidad fall\xF3." };
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
function local(opts) {
|
|
1000
|
+
return {
|
|
1001
|
+
id: opts.id,
|
|
1002
|
+
tools: opts.tools,
|
|
1003
|
+
run: (call) => conAutoridad(opts.tools, call, async () => ({
|
|
1004
|
+
ok: true,
|
|
1005
|
+
data: await opts.handler(call.name, call.args ?? {}),
|
|
1006
|
+
evidence: { source: "local", label: opts.id }
|
|
1007
|
+
}))
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
function http(opts) {
|
|
1011
|
+
const base = opts.baseUrl.replace(/\/$/, "");
|
|
1012
|
+
return {
|
|
1013
|
+
id: opts.id,
|
|
1014
|
+
tools: opts.tools,
|
|
1015
|
+
run: (call) => conAutoridad(opts.tools, call, async () => {
|
|
1016
|
+
const res = await fetch(`${base}/${call.name}`, {
|
|
1017
|
+
method: "POST",
|
|
1018
|
+
headers: { "Content-Type": "application/json; charset=utf-8", ...opts.headers },
|
|
1019
|
+
body: JSON.stringify(call.args ?? {}),
|
|
1020
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? 15e3)
|
|
1021
|
+
});
|
|
1022
|
+
const texto = await res.text();
|
|
1023
|
+
if (!res.ok) return { ok: false, error: `${opts.id} respondi\xF3 ${res.status}` };
|
|
1024
|
+
let data;
|
|
1025
|
+
try {
|
|
1026
|
+
data = JSON.parse(texto);
|
|
1027
|
+
} catch {
|
|
1028
|
+
data = texto;
|
|
1029
|
+
}
|
|
1030
|
+
return { ok: true, data, evidence: { source: "http", label: `${opts.id}/${call.name}` } };
|
|
1031
|
+
})
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
function httpTransport(url, headers) {
|
|
1035
|
+
return {
|
|
1036
|
+
async send(mensaje) {
|
|
1037
|
+
const res = await fetch(url, {
|
|
1038
|
+
method: "POST",
|
|
1039
|
+
headers: { "Content-Type": "application/json", Accept: "application/json", ...headers },
|
|
1040
|
+
body: JSON.stringify(mensaje),
|
|
1041
|
+
signal: AbortSignal.timeout(2e4)
|
|
1042
|
+
});
|
|
1043
|
+
if (!res.ok) throw new VAIAError(`Servidor MCP respondi\xF3 ${res.status}`, "MCP_HTTP_ERROR", 502);
|
|
1044
|
+
return res.json();
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
var PROHIBIDA = { level: "prohibida", consequence: "irreversible" };
|
|
1049
|
+
async function mcp(opts) {
|
|
1050
|
+
let siguienteId = 1;
|
|
1051
|
+
const rpc = async (method, params) => {
|
|
1052
|
+
const r = await opts.transport.send({
|
|
1053
|
+
jsonrpc: "2.0",
|
|
1054
|
+
id: siguienteId++,
|
|
1055
|
+
method,
|
|
1056
|
+
...params ? { params } : {}
|
|
1057
|
+
});
|
|
1058
|
+
if (r?.["error"]) {
|
|
1059
|
+
const e = r["error"];
|
|
1060
|
+
throw new VAIAError(e?.message ?? "Error del servidor MCP", "MCP_ERROR", 502);
|
|
1061
|
+
}
|
|
1062
|
+
return r?.["result"] ?? {};
|
|
1063
|
+
};
|
|
1064
|
+
await rpc("initialize", {
|
|
1065
|
+
protocolVersion: "2024-11-05",
|
|
1066
|
+
capabilities: {},
|
|
1067
|
+
clientInfo: { name: "@vaia-lab/sdk", version: "0.3.0" }
|
|
1068
|
+
});
|
|
1069
|
+
const listadas = (await rpc("tools/list"))["tools"] ?? [];
|
|
1070
|
+
const tools = listadas.map((t) => ({
|
|
1071
|
+
name: normalizar(t.name),
|
|
1072
|
+
description: t.description?.trim() || `Herramienta MCP "${t.name}".`,
|
|
1073
|
+
authority: opts.authority[t.name] ?? opts.defaultAuthority ?? PROHIBIDA,
|
|
1074
|
+
permission: opts.permission ?? `mcp:${opts.id}`
|
|
1075
|
+
}));
|
|
1076
|
+
const original = new Map(listadas.map((t) => [normalizar(t.name), t.name]));
|
|
1077
|
+
return {
|
|
1078
|
+
id: opts.id,
|
|
1079
|
+
tools,
|
|
1080
|
+
run: (call) => conAutoridad(tools, call, async () => {
|
|
1081
|
+
const nombreReal = original.get(call.name) ?? call.name;
|
|
1082
|
+
const r = await rpc("tools/call", { name: nombreReal, arguments: call.args ?? {} });
|
|
1083
|
+
return {
|
|
1084
|
+
ok: !r["isError"],
|
|
1085
|
+
data: r["content"] ?? r,
|
|
1086
|
+
error: r["isError"] ? "La herramienta MCP devolvi\xF3 un error." : void 0,
|
|
1087
|
+
evidence: { source: "mcp", label: `${opts.id}/${nombreReal}` }
|
|
1088
|
+
};
|
|
1089
|
+
}),
|
|
1090
|
+
dispose: () => opts.transport.close?.()
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
function normalizar(n) {
|
|
1094
|
+
return n.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").slice(0, 48);
|
|
1095
|
+
}
|
|
1096
|
+
var capabilities = { local, http, mcp, httpTransport };
|
|
1097
|
+
|
|
1098
|
+
// src/ecosystem.ts
|
|
1099
|
+
function coincide(patron, nombre) {
|
|
1100
|
+
if (patron === "*") return true;
|
|
1101
|
+
if (patron.endsWith("*")) return nombre.startsWith(patron.slice(0, -1));
|
|
1102
|
+
return patron === nombre;
|
|
1103
|
+
}
|
|
1104
|
+
var ORDEN2 = { prohibida: 0, requiere_aprobacion: 1, autonoma: 2 };
|
|
1105
|
+
function aplicarReglas(tool, reglas) {
|
|
1106
|
+
if (!reglas) return tool;
|
|
1107
|
+
let resultado = tool.authority;
|
|
1108
|
+
for (const [patron, regla] of Object.entries(reglas)) {
|
|
1109
|
+
if (!coincide(patron, tool.name)) continue;
|
|
1110
|
+
if (ORDEN2[regla.level] < ORDEN2[resultado.level]) resultado = regla;
|
|
1111
|
+
else if (regla.maxAmount !== void 0 && (resultado.maxAmount === void 0 || regla.maxAmount < resultado.maxAmount)) {
|
|
1112
|
+
resultado = { ...resultado, maxAmount: regla.maxAmount, currency: regla.currency ?? resultado.currency };
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
return { ...tool, authority: resultado };
|
|
1116
|
+
}
|
|
1117
|
+
function defineEcosystem(cfg) {
|
|
1118
|
+
const caps = new Map(cfg.capabilities.map((c) => [c.id, c]));
|
|
1119
|
+
const recopilar = () => [...caps.values()].flatMap(
|
|
1120
|
+
(c) => c.tools.map((t) => ({ ...aplicarReglas(t, cfg.authority), capability: c.id }))
|
|
1121
|
+
);
|
|
1122
|
+
let tools = recopilar();
|
|
1123
|
+
return {
|
|
1124
|
+
name: cfg.name,
|
|
1125
|
+
get tools() {
|
|
1126
|
+
return tools;
|
|
1127
|
+
},
|
|
1128
|
+
async run(call) {
|
|
1129
|
+
const due\u00F1o = [...caps.values()].find((c) => c.tools.some((t) => t.name === call.name));
|
|
1130
|
+
if (!due\u00F1o) {
|
|
1131
|
+
return { ok: false, error: `Ninguna capacidad de "${cfg.name}" declara "${call.name}".` };
|
|
1132
|
+
}
|
|
1133
|
+
const conReglas = tools.find((t) => t.name === call.name);
|
|
1134
|
+
if (conReglas && conReglas.authority.level === "prohibida") {
|
|
1135
|
+
return { ok: false, error: `"${call.name}" est\xE1 prohibida por las reglas de ${cfg.name}.` };
|
|
1136
|
+
}
|
|
1137
|
+
if (conReglas && conReglas.authority.level !== "autonoma" && !call.approved) {
|
|
1138
|
+
return { ok: false, needsApproval: true, error: "Requiere aprobaci\xF3n humana antes de ejecutarse." };
|
|
1139
|
+
}
|
|
1140
|
+
return due\u00F1o.run(call);
|
|
1141
|
+
},
|
|
1142
|
+
add(capability) {
|
|
1143
|
+
caps.set(capability.id, capability);
|
|
1144
|
+
tools = recopilar();
|
|
1145
|
+
},
|
|
1146
|
+
async remove(capabilityId) {
|
|
1147
|
+
const c = caps.get(capabilityId);
|
|
1148
|
+
if (!c) return;
|
|
1149
|
+
await c.dispose?.();
|
|
1150
|
+
caps.delete(capabilityId);
|
|
1151
|
+
tools = recopilar();
|
|
1152
|
+
},
|
|
1153
|
+
async dispose() {
|
|
1154
|
+
for (const c of caps.values()) await c.dispose?.();
|
|
1155
|
+
caps.clear();
|
|
1156
|
+
tools = [];
|
|
1157
|
+
}
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
async function agentLoop(opts) {
|
|
1161
|
+
const maxSteps = opts.maxSteps ?? 6;
|
|
1162
|
+
return async function turno(message, history = []) {
|
|
1163
|
+
const steps = [];
|
|
1164
|
+
let lastResult;
|
|
1165
|
+
for (let i = 0; i < maxSteps; i++) {
|
|
1166
|
+
const salida = await opts.model({
|
|
1167
|
+
message,
|
|
1168
|
+
tools: opts.ecosystem.tools.map((t) => ({ name: t.name, description: t.description })),
|
|
1169
|
+
history,
|
|
1170
|
+
lastResult
|
|
1171
|
+
});
|
|
1172
|
+
if (!salida.action) return { text: salida.text, steps };
|
|
1173
|
+
let resultado = await opts.ecosystem.run(salida.action);
|
|
1174
|
+
if (resultado.needsApproval && opts.onApproval) {
|
|
1175
|
+
const aprobado = await opts.onApproval(salida.action.name, salida.action.args ?? {});
|
|
1176
|
+
if (aprobado) {
|
|
1177
|
+
resultado = await ejecutarAprobado(opts.ecosystem, salida.action);
|
|
1178
|
+
} else {
|
|
1179
|
+
resultado = { ok: false, error: "El usuario no lo autoriz\xF3." };
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
steps.push({ action: salida.action.name, ok: resultado.ok, error: resultado.error });
|
|
1183
|
+
lastResult = resultado;
|
|
1184
|
+
}
|
|
1185
|
+
return { text: "No pude completarlo en los pasos disponibles.", steps };
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
async function ejecutarAprobado(eco, action) {
|
|
1189
|
+
const t = eco.tools.find((x) => x.name === action.name);
|
|
1190
|
+
if (!t) return { ok: false, error: "La herramienta ya no existe." };
|
|
1191
|
+
if (t.authority.level === "prohibida") {
|
|
1192
|
+
return { ok: false, error: "Prohibida: ni con aprobaci\xF3n se ejecuta." };
|
|
1193
|
+
}
|
|
1194
|
+
return eco.run({ ...action, approved: true });
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
// src/mcp.ts
|
|
1198
|
+
function fromMCPTool(tool, authority, permission) {
|
|
1199
|
+
const warnings = [];
|
|
1200
|
+
if (tool.annotations?.destructiveHint && authority.consequence === "reversible") {
|
|
1201
|
+
warnings.push(
|
|
1202
|
+
`"${tool.name}": el servidor MCP la marca como destructiva, pero se declar\xF3 como reversible. Rev\xEDsalo.`
|
|
1203
|
+
);
|
|
1204
|
+
}
|
|
1205
|
+
if (tool.annotations?.readOnlyHint === false && authority.level === "autonoma") {
|
|
1206
|
+
warnings.push(
|
|
1207
|
+
`"${tool.name}": escribe y se le dio autoridad aut\xF3noma. Aseg\xFArate de que sea lo que quieres.`
|
|
1208
|
+
);
|
|
1209
|
+
}
|
|
1210
|
+
if (!tool.description?.trim()) {
|
|
1211
|
+
warnings.push(`"${tool.name}": el servidor MCP no la describe, as\xED que el agente no sabr\xE1 cu\xE1ndo usarla.`);
|
|
1212
|
+
}
|
|
1213
|
+
return {
|
|
1214
|
+
tool: {
|
|
1215
|
+
// Prefijo para que se vea de dónde viene y no choque con lo propio.
|
|
1216
|
+
name: normalizarNombre(`mcp_${tool.name}`),
|
|
1217
|
+
description: tool.description?.trim() || `Herramienta MCP "${tool.name}" (sin descripci\xF3n del servidor).`,
|
|
1218
|
+
authority,
|
|
1219
|
+
permission
|
|
1220
|
+
},
|
|
1221
|
+
warnings
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
1224
|
+
function toMCPTool(tool) {
|
|
1225
|
+
if (tool.authority.level !== "autonoma") return null;
|
|
1226
|
+
return {
|
|
1227
|
+
name: tool.name,
|
|
1228
|
+
description: tool.description,
|
|
1229
|
+
annotations: {
|
|
1230
|
+
readOnlyHint: tool.authority.consequence === "reversible",
|
|
1231
|
+
destructiveHint: tool.authority.consequence === "irreversible",
|
|
1232
|
+
idempotentHint: false
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
function toMCPTools(tools) {
|
|
1237
|
+
const published = [];
|
|
1238
|
+
const withheld = [];
|
|
1239
|
+
for (const t of tools) {
|
|
1240
|
+
const m = toMCPTool(t);
|
|
1241
|
+
if (m) published.push(m);
|
|
1242
|
+
else withheld.push(t.name);
|
|
1243
|
+
}
|
|
1244
|
+
return { published, withheld };
|
|
1245
|
+
}
|
|
1246
|
+
function normalizarNombre(n) {
|
|
1247
|
+
return n.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").slice(0, 48);
|
|
1248
|
+
}
|
|
1249
|
+
|
|
566
1250
|
// src/index.ts
|
|
567
1251
|
var gandia = gandia_exports;
|
|
568
1252
|
var handeia = handeia_exports;
|
|
569
1253
|
export {
|
|
1254
|
+
AGENT_PROTOCOL_VERSION,
|
|
1255
|
+
CONNECTOR_OF_OPERATION,
|
|
570
1256
|
VAIAError,
|
|
1257
|
+
agentLoop,
|
|
1258
|
+
capabilities,
|
|
1259
|
+
checkAuthority,
|
|
571
1260
|
defineCapability,
|
|
1261
|
+
defineEcosystem,
|
|
1262
|
+
fromMCPTool,
|
|
572
1263
|
gandia,
|
|
573
1264
|
handeia,
|
|
574
|
-
|
|
1265
|
+
http,
|
|
1266
|
+
httpTransport,
|
|
1267
|
+
local,
|
|
1268
|
+
mcp,
|
|
1269
|
+
mountAgent,
|
|
1270
|
+
requiresApproval,
|
|
1271
|
+
toMCPTool,
|
|
1272
|
+
toMCPTools,
|
|
1273
|
+
toManifest,
|
|
1274
|
+
validateActionCall,
|
|
1275
|
+
validateAgentSurface,
|
|
1276
|
+
validatePieces
|
|
575
1277
|
};
|
|
576
|
-
//# sourceMappingURL=index.js.map
|