@kwirthmagnify/kwirth-common-ai 0.5.61 → 0.5.62

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/dist/back.js CHANGED
@@ -1,47 +1,10 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.runAgent = exports.selectAgentToolNames = exports.toolInfoList = exports.tools = exports.buildAgentTools = exports.resolveTools = exports.resolveToolRef = exports.invokeToolRef = exports.buildToolHost = exports.listToolsetInfos = exports.listToolsets = exports.getToolset = exports.unregisterToolset = exports.registerToolset = exports.isToolsetGrantedTo = exports.getToolsetGrants = exports.setToolsetGrants = exports.isBuiltInToolsetId = exports.defineTool = exports.runWithToolContext = exports.EToolEffect = exports.zodFromExample = exports.z = exports.tool = exports.stepCountIs = exports.Output = exports.generateText = exports.loadModels = exports.generateVision = exports.buildModel = void 0;
3
+ exports.buildAgentTools = exports.resolveTools = exports.resolveToolRef = exports.invokeToolRef = exports.buildToolHost = exports.listToolsetInfos = exports.listToolsets = exports.getToolset = exports.unregisterToolset = exports.registerToolset = exports.isToolsetGrantedTo = exports.getToolsetGrants = exports.setToolsetGrants = exports.isBuiltInToolsetId = exports.defineTool = exports.runWithToolContext = exports.EToolEffect = exports.zodFromExample = exports.z = exports.tool = exports.stepCountIs = exports.Output = exports.generateText = exports.loadModels = exports.generateVision = exports.buildModel = void 0;
37
4
  const index_1 = require("./index");
38
5
  const ai_1 = require("ai");
39
6
  const zod_1 = require("zod");
40
7
  const async_hooks_1 = require("async_hooks");
41
- const child_process_1 = require("child_process");
42
- const util_1 = require("util");
43
- const tls = __importStar(require("tls"));
44
- const execAsync = (0, util_1.promisify)(child_process_1.exec);
45
8
  const openai_1 = require("@ai-sdk/openai");
46
9
  const groq_1 = require("@ai-sdk/groq");
47
10
  const mistral_1 = require("@ai-sdk/mistral");
@@ -67,9 +30,9 @@ const buildModel = (llm, providers) => {
67
30
  case 'openrouter': return (0, ai_sdk_provider_1.createOpenRouter)({ apiKey: key })(llm.model);
68
31
  case 'anthropic': return (0, anthropic_1.createAnthropic)({ apiKey: key })(llm.model);
69
32
  case 'openai-compat': {
70
- // baseURL debe terminar en /v1 (el SDK añade el path). Y usamos .chat() → Chat Completions API
71
- // (/v1/chat/completions): los endpoints OpenAI-compatibles (Huawei MaaS, etc.) NO exponen la
72
- // Responses API (/v1/responses) → si no, 404 APIG.0101.
33
+ // baseURL must end in /v1 (the SDK appends the path). And we use .chat() → Chat Completions API
34
+ // (/v1/chat/completions): OpenAI-compatible endpoints (Huawei MaaS and the like) do NOT expose the
35
+ // Responses API (/v1/responses) → otherwise, 404 APIG.0101.
73
36
  const b = ((_c = prov === null || prov === void 0 ? void 0 : prov.endpoint) !== null && _c !== void 0 ? _c : '').replace(/\/+$/, '');
74
37
  return (0, openai_1.createOpenAI)({ apiKey: key, baseURL: b.endsWith('/v1') ? b : `${b}/v1` }).chat(llm.model);
75
38
  }
@@ -79,9 +42,9 @@ const buildModel = (llm, providers) => {
79
42
  }
80
43
  };
81
44
  exports.buildModel = buildModel;
82
- // Llamada MULTIMODAL genérica: manda una imagen + prompt a un LLM y devuelve salida ESTRUCTURADA validada por
83
- // un schema Zod (patrón Output.object). Reutilizable por toda la plataforma (Iter la usa para extraer un mapa
84
- // de un diagrama). No lanza: los errores vuelven en `error`.
45
+ // Generic MULTIMODAL call: sends an image plus a prompt to an LLM and returns STRUCTURED output validated by
46
+ // a Zod schema (the Output.object pattern). Reusable across the whole platform (Iter uses it to extract a map
47
+ // from a diagram). It never throws: errors come back in `error`.
85
48
  const generateVision = async (opts) => {
86
49
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p, _q, _r;
87
50
  try {
@@ -104,8 +67,8 @@ const generateVision = async (opts) => {
104
67
  catch (err) {
105
68
  const e = err;
106
69
  const body = typeof (e === null || e === void 0 ? void 0 : e.responseBody) === 'string' ? e.responseBody : ((e === null || e === void 0 ? void 0 : e.responseBody) ? JSON.stringify(e.responseBody) : undefined);
107
- // Serializa el body ENVIADO truncando cadenas largas (el base64 de la imagen) para ver la ESTRUCTURA
108
- // de content[] (qué campos lleva cada parte) sin volcar megas.
70
+ // Serializes the body that was SENT, truncating long strings (the image base64), so the STRUCTURE
71
+ // of content[] (which fields each part carries) is visible without dumping megabytes.
109
72
  const trunc = (o) => {
110
73
  try {
111
74
  return JSON.stringify(o, (_k, v) => (typeof v === 'string' && v.length > 120 ? `${v.slice(0, 60)}…[${v.length} chars]` : v)).slice(0, 4000);
@@ -114,7 +77,7 @@ const generateVision = async (opts) => {
114
77
  return String(o);
115
78
  }
116
79
  };
117
- // TRAZA COMPLETA del fallo de la llamada al LLM (URL, status, cuerpo de respuesta, causa, request).
80
+ // FULL TRACE of the failed LLM call (URL, status, response body, cause, request).
118
81
  console.error('[generateVision] FAILED', {
119
82
  name: e === null || e === void 0 ? void 0 : e.name, message: e === null || e === void 0 ? void 0 : e.message, statusCode: e === null || e === void 0 ? void 0 : e.statusCode, url: e === null || e === void 0 ? void 0 : e.url,
120
83
  responseBody: body, cause: (_r = (_q = e === null || e === void 0 ? void 0 : e.cause) === null || _q === void 0 ? void 0 : _q.message) !== null && _r !== void 0 ? _r : e === null || e === void 0 ? void 0 : e.cause,
@@ -258,8 +221,8 @@ const inferZod = (value) => {
258
221
  return zod_1.z.unknown();
259
222
  };
260
223
  // Re-export AI SDK symbols so plugins can use them without bundling the SDK
261
- // Se re-exportan tambien los TIPOS que necesita quien escriba un helper alrededor de generateText: sin
262
- // LanguageModel y ToolSet, un plugin no puede tipar sus propias funciones y acaba con 'any'.
224
+ // The TYPES needed by anyone writing a helper around generateText are re-exported too: without
225
+ // LanguageModel and ToolSet a plugin cannot type its own functions and ends up with 'any'.
263
226
  var ai_2 = require("ai");
264
227
  Object.defineProperty(exports, "generateText", { enumerable: true, get: function () { return ai_2.generateText; } });
265
228
  Object.defineProperty(exports, "Output", { enumerable: true, get: function () { return ai_2.Output; } });
@@ -306,9 +269,9 @@ const fetchSourceFile = async (cred, projectPath, ref, path) => {
306
269
  throw new Error(`GitLab ${resp.status} for ${projectPath}/${cleanPath}@${ref}`);
307
270
  return await resp.text();
308
271
  };
309
- // EToolEffect vive ahora en el contrato isomorfo (./index): el front tambien tiene que saber que hace una
310
- // tool para poder marcarla en el selector, y hasta ahora no le llegaba. Se re-exporta para no romper a
311
- // quien lo importe desde aqui.
272
+ // EToolEffect now lives in the isomorphic contract (./index): the front end also needs to know what a tool
273
+ // does in order to flag it in the selector, and until now it never got there. It is re-exported so that
274
+ // whoever imports it from here keeps working.
312
275
  var index_2 = require("./index");
313
276
  Object.defineProperty(exports, "EToolEffect", { enumerable: true, get: function () { return index_2.EToolEffect; } });
314
277
  const toolContextStorage = new async_hooks_1.AsyncLocalStorage();
@@ -391,56 +354,57 @@ const configRefsOfPodSpec = (spec) => {
391
354
  return refs;
392
355
  };
393
356
  /**
394
- * Declara una tool infiriendo el tipo de sus argumentos DESDE su propio `inputSchema`.
357
+ * Declares a tool, inferring the type of its arguments FROM its own `inputSchema`.
395
358
  *
396
- * Sin esto, `execute` recibe `Record<string, unknown>` y cada tool acaba llena de `String(args.namespace)`
397
- * y castings sueltos: treinta tools asi son treinta sitios donde equivocarse en silencio, y el compilador
398
- * no puede ayudar. Con esto, el esquema es la unica fuente de verdad y `args` viene tipado.
359
+ * Without this, `execute` receives `Record<string, unknown>` and every tool fills up with
360
+ * `String(args.namespace)` and loose casts: thirty tools like that are thirty places to go wrong in
361
+ * silence, with no help from the compiler. With this, the schema is the single source of truth and `args`
362
+ * arrives typed.
399
363
  *
400
- * El registro sigue guardando el tipo suelto (`IAiTool`): quien lo invoca no conoce el esquema, y ahi la
401
- * comprobacion la hace zod en tiempo de ejecucion, como debe ser.
364
+ * The registry still stores the loose type (`IAiTool`): whoever invokes it does not know the schema, and
365
+ * there the check is done by zod at run time, as it should be.
402
366
  */
403
367
  const defineTool = (definition) => definition;
404
368
  exports.defineTool = defineTool;
405
369
  const toolsetRegistry = new Map();
406
- // Los ids de los toolsets built-in del core estan RESERVADOS: un `aitoolset` de un tercero no puede
407
- // ocuparlos. Sin esta regla, instalar un toolset ajeno llamado 'k8s-inventory' obligaria a renombrar el
408
- // built-in, y con el se romperia todo techo y todo agente que lo tuviera configurado.
370
+ // The ids of the core's built-in toolsets are RESERVED: a third-party `aitoolset` cannot take them.
371
+ // Without this rule, installing a foreign toolset called 'k8s-inventory' would force renaming the built-in
372
+ // one, and with it would break every grant and every agent configured against it.
409
373
  const builtInToolsetIds = new Set();
410
374
  /*
411
- Quien puede usar cada toolset (plan: "El techo en dos fases", fase 1).
375
+ Who may use each toolset (plan: "The grant in two phases", phase 1).
412
376
 
413
- ⚠️ La concesion vive AQUI, en el registro, y no en la llamada. Si cada plugin armara su propia lista de
414
- toolsets, podria pedir los que no se le han concedido: el filtro tiene que estar del lado que el plugin
415
- no controla. El registro lo puebla el core, y un paquete de terceros no puede tocarlo.
377
+ ⚠️ The grant lives HERE, in the registry, and not at the call site. If each plugin assembled its own list
378
+ of toolsets it could ask for ones it was never granted: the filter has to sit on the side the plugin does
379
+ not control. The registry is populated by the core, and a third-party package cannot touch it.
416
380
 
417
- Y por defecto NO lo usa nadie (decision del usuario, 2026-09-17): instalar un toolset lo deja
418
- disponible, no concedido. Instalar `k8s-ops` no puede dar escritura a nadie por accidente.
381
+ And by default nobody uses it (user's decision, 2026-09-17): installing a toolset leaves it available,
382
+ not granted. Installing `k8s-ops` must not give anyone write access by accident.
419
383
  */
420
- const toolsetGrants = new Map(); // toolsetId → plugins invitados
384
+ const toolsetGrants = new Map(); // toolsetId → invited plugins
421
385
  const isBuiltInToolsetId = (id) => builtInToolsetIds.has(id);
422
386
  exports.isBuiltInToolsetId = isBuiltInToolsetId;
423
- /** Concede un toolset a una lista de plugins. Reemplaza la concesion anterior; `[]` se la quita a todos. */
387
+ /** Grants a toolset to a list of plugins. Replaces the previous grant; `[]` takes it away from everyone. */
424
388
  const setToolsetGrants = (toolsetId, pluginIds) => {
425
389
  toolsetGrants.set(toolsetId, new Set(pluginIds));
426
390
  };
427
391
  exports.setToolsetGrants = setToolsetGrants;
428
- /** A quien esta concedido un toolset. Vacio = a nadie, que es el estado por defecto. */
392
+ /** Who a toolset is granted to. Empty = nobody, which is the default state. */
429
393
  const getToolsetGrants = (toolsetId) => { var _a; return [...((_a = toolsetGrants.get(toolsetId)) !== null && _a !== void 0 ? _a : [])]; };
430
394
  exports.getToolsetGrants = getToolsetGrants;
431
- /** Si ESE plugin puede usar ESE toolset. */
395
+ /** Whether THAT plugin may use THAT toolset. */
432
396
  const isToolsetGrantedTo = (toolsetId, pluginId) => { var _a, _b; return (_b = (_a = toolsetGrants.get(toolsetId)) === null || _a === void 0 ? void 0 : _a.has(pluginId)) !== null && _b !== void 0 ? _b : false; };
433
397
  exports.isToolsetGrantedTo = isToolsetGrantedTo;
434
398
  /**
435
- * Registra un toolset. `builtIn` solo lo usa el core para los suyos: marca el id como reservado.
436
- * Lanza si el id ya esta ocupado — registrar dos veces el mismo id es un error de empaquetado, no algo
437
- * que deba resolverse en silencio pisando al primero.
399
+ * Registers a toolset. `builtIn` is only used by the core for its own: it marks the id as reserved.
400
+ * Throws if the id is already taken — registering the same id twice is a packaging error, not something
401
+ * to be resolved silently by overwriting the first one.
438
402
  */
439
403
  const registerToolset = (toolset, builtIn = false) => {
440
- // El id reservado se comprueba ANTES que el duplicado, y el orden importa: un built-in siempre esta
441
- // registrado, asi que chocar con uno da SIEMPRE duplicado tambien. Al reves, quien instala un toolset
442
- // ajeno leeria 'already registered' —que suena a que lo instalo dos veces— en vez de enterarse de que
443
- // ese id es del core y no lo puede ocupar.
404
+ // The reserved id is checked BEFORE the duplicate, and the order matters: a built-in is always
405
+ // registered, so clashing with one ALWAYS yields a duplicate as well. The other way round, whoever
406
+ // installs a foreign toolset would read 'already registered' — which sounds like they installed it
407
+ // twice — instead of learning that the id belongs to the core and cannot be taken.
444
408
  if (!builtIn && builtInToolsetIds.has(toolset.id))
445
409
  throw new Error(`[common-ai] toolset id '${toolset.id}' is reserved by a built-in toolset`);
446
410
  if (toolsetRegistry.has(toolset.id))
@@ -450,12 +414,12 @@ const registerToolset = (toolset, builtIn = false) => {
450
414
  builtInToolsetIds.add(toolset.id);
451
415
  };
452
416
  exports.registerToolset = registerToolset;
453
- /** Retira un toolset del registro (desinstalacion). Los built-in no se retiran. */
417
+ /** Removes a toolset from the registry (uninstall). Built-in ones are never removed. */
454
418
  const unregisterToolset = (id) => {
455
419
  if (builtInToolsetIds.has(id))
456
420
  return false;
457
- // La concesion se va con el toolset: dejarla huerfana haria que reinstalarlo resucitara permisos que
458
- // nadie ha vuelto a conceder.
421
+ // The grant goes with the toolset: leaving it orphaned would make reinstalling resurrect permissions
422
+ // nobody has granted again.
459
423
  toolsetGrants.delete(id);
460
424
  return toolsetRegistry.delete(id);
461
425
  };
@@ -464,7 +428,7 @@ const getToolset = (id) => toolsetRegistry.get(id);
464
428
  exports.getToolset = getToolset;
465
429
  const listToolsets = () => [...toolsetRegistry.values()];
466
430
  exports.listToolsets = listToolsets;
467
- /** Lo que se le manda al front: las fichas, sin inputSchema ni execute. */
431
+ /** What is sent to the front end: the descriptors, without inputSchema or execute. */
468
432
  const listToolsetInfos = () => (0, exports.listToolsets)().map(t => ({
469
433
  id: t.id,
470
434
  version: t.version,
@@ -475,18 +439,18 @@ const listToolsetInfos = () => (0, exports.listToolsets)().map(t => ({
475
439
  }));
476
440
  exports.listToolsetInfos = listToolsetInfos;
477
441
  /**
478
- * Construye el host de un toolset a partir del contexto del core, provisionando SOLO lo declarado.
442
+ * Builds a toolset's host from the core context, provisioning ONLY what was declared.
479
443
  *
480
- * Que el reparto se haga aqui y no en cada llamada es lo que hace cumplible la promesa de `ECapability`:
481
- * si cada sitio armara su propio objeto, bastaria con que uno se pasara de generoso para que la
482
- * declaracion dejara de significar nada.
444
+ * Doing the handing-out here and not at each call site is what makes the `ECapability` promise keepable:
445
+ * if every site assembled its own object, one of them being too generous would be enough for the
446
+ * declaration to stop meaning anything.
483
447
  */
484
448
  const buildToolHost = (requires, context) => {
485
449
  var _a, _b, _c;
486
450
  const host = { trace: context.trace };
487
451
  const ci = context.clusterInfo;
488
- // Sin cluster no hay capability de cluster, aunque se declare: es preferible que la tool reciba
489
- // 'undefined' y lo diga, a entregarle una fachada a medio montar que falle por dentro.
452
+ // No cluster means no cluster capability, even when declared: better that the tool receives
453
+ // 'undefined' and says so, than handing it a half-built facade that fails from the inside.
490
454
  if (requires.includes(index_1.ECapability.K8S) && ci) {
491
455
  host.k8s = {
492
456
  name: ci.name,
@@ -509,8 +473,8 @@ const buildToolHost = (requires, context) => {
509
473
  };
510
474
  exports.buildToolHost = buildToolHost;
511
475
  /**
512
- * Invoca una tool por su referencia cualificada. Un unico camino de invocacion para built-in e
513
- * instalado, con el host construido segun el `requires` de SU toolset.
476
+ * Invokes a tool by its qualified reference. A single invocation path for built-in and installed alike,
477
+ * with the host built according to the `requires` of ITS toolset.
514
478
  */
515
479
  const invokeToolRef = async (ref, args, context) => {
516
480
  const resolved = (0, exports.resolveToolRef)(ref);
@@ -519,7 +483,7 @@ const invokeToolRef = async (ref, args, context) => {
519
483
  return resolved.tool.execute(args, (0, exports.buildToolHost)(resolved.toolset.requires, context));
520
484
  };
521
485
  exports.invokeToolRef = invokeToolRef;
522
- /** Resuelve una referencia cualificada '<toolset>/<tool>' contra el registro. */
486
+ /** Resolves a qualified reference '<toolset>/<tool>' against the registry. */
523
487
  const resolveToolRef = (ref) => {
524
488
  const parsed = (0, index_1.parseToolRef)(ref);
525
489
  if (!parsed)
@@ -530,11 +494,11 @@ const resolveToolRef = (ref) => {
530
494
  };
531
495
  exports.resolveToolRef = resolveToolRef;
532
496
  /**
533
- * Aplica el techo de un cliente sobre el registro. Pura: ni ejecuta ni toca el contexto, asi que el
534
- * editor puede llamarla para PINTAR lo mismo que se va a ejecutar.
497
+ * Applies a client's ceiling over the registry. Pure: it neither executes nor touches the context, so the
498
+ * editor can call it to DRAW exactly what is going to run.
535
499
  *
536
- * Una tool apagada no tapa: se apaga una referencia concreta ('ts1/td'), no un nombre, asi que si `ts1/td`
537
- * esta apagada y `ts2` trae otra `td`, aflora la de `ts2`.
500
+ * A disabled tool does not shadow: what gets disabled is a concrete reference ('ts1/td'), not a name, so if
501
+ * `ts1/td` is off and `ts2` carries another `td`, the one from `ts2` surfaces.
538
502
  */
539
503
  const resolveTools = (config, requesterId) => {
540
504
  const disabled = new Set(config.disabledTools);
@@ -542,18 +506,18 @@ const resolveTools = (config, requesterId) => {
542
506
  const shadowed = [];
543
507
  const missing = [];
544
508
  const notGranted = [];
545
- const taken = new Map(); // nombre corto → toolset que lo sirve
509
+ const taken = new Map(); // short name → toolset serving it
546
510
  for (const toolsetId of config.activeToolsets) {
547
511
  const toolset = toolsetRegistry.get(toolsetId);
548
512
  if (!toolset) {
549
- // No se calla: un techo que nombra algo que no esta instalado es una config rota, y el
550
- // sintoma sin esto seria "el agente responde peor" sin que nadie sepa por que.
513
+ // It does not stay quiet: a ceiling naming something that is not installed is a broken config,
514
+ // and without this the symptom would be "the agent answers worse" with nobody knowing why.
551
515
  missing.push(toolsetId);
552
516
  continue;
553
517
  }
554
- // La concesion se comprueba AQUI y no la aporta quien llama: el plugin no puede concederse a si
555
- // mismo lo que el admin no le dio. Sin `requesterId` no se filtra — es el caso del core
556
- // resolviendo para PINTAR (el editor), no para ejecutar.
518
+ // The grant is checked HERE and not supplied by the caller: a plugin cannot grant itself what the
519
+ // admin never gave it. Without `requesterId` nothing is filtered — that is the core resolving in
520
+ // order to DRAW (the editor), not to execute.
557
521
  if (requesterId !== undefined && !(0, exports.isToolsetGrantedTo)(toolsetId, requesterId)) {
558
522
  notGranted.push(toolsetId);
559
523
  continue;
@@ -575,26 +539,26 @@ const resolveTools = (config, requesterId) => {
575
539
  };
576
540
  exports.resolveTools = resolveTools;
577
541
  /**
578
- * Las tools listas para pasarselas al SDK de IA, ya resueltas por precedencia y con los dos ganchos
579
- * puestos. La clave del objeto es el nombre CORTO, que es lo unico que el proveedor acepta.
542
+ * The tools ready to hand to the AI SDK, already resolved by precedence and with both hooks in place.
543
+ * The object key is the SHORT name, which is the only thing the provider accepts.
580
544
  */
581
545
  const buildAgentTools = (config, context, hooks = {},
582
546
  /**
583
- * Quien pide las tools. Sin esto no se filtra por concesion, asi que un plugin DEBE pasar su id: es lo
584
- * que impide que se sirva a si mismo un toolset que no le han concedido.
547
+ * Who is asking for the tools. Without it nothing is filtered by grant, so a plugin MUST pass its id:
548
+ * that is what stops it from serving itself a toolset it was never granted.
585
549
  */
586
550
  requesterId) => {
587
551
  const { effective } = (0, exports.resolveTools)(config, requesterId);
588
552
  const entries = effective.map(e => {
589
553
  const invocationOf = (args) => ({ ref: e.ref, toolsetId: e.toolsetId, toolName: e.name, args });
590
- // ⚠️ Un objeto PLANO, no `dynamicTool`. Parece equivalente y no lo es:
591
- // tool(t) => t (solo ayuda de tipos, no toca nada)
592
- // dynamicTool(t) => { ...t, type: 'dynamic' } (marca la tool en RUNTIME)
593
- // Una tool marcada como dinamica la trata el SDK por otro camino, y con `Output.object` la
594
- // ejecucion acaba en AI_NoOutputGeneratedError: la tool corre, devuelve, y la respuesta
595
- // estructurada no se genera. Se uso `dynamicTool` para esquivar una friccion de tipos —el helper
596
- // `tool()` infiere `never` con un ZodTypeAny generico— y el precio fue cambiar el comportamiento.
597
- // El casteo es la forma honesta: lo que el SDK necesita es exactamente este objeto.
554
+ // ⚠️ A PLAIN object, not `dynamicTool`. It looks equivalent and it is not:
555
+ // tool(t) => t (types only, touches nothing)
556
+ // dynamicTool(t) => { ...t, type: 'dynamic' } (marks the tool at RUNTIME)
557
+ // A tool marked as dynamic is handled by the SDK through another path, and with `Output.object` the
558
+ // run ends in AI_NoOutputGeneratedError: the tool executes, returns, and the structured response is
559
+ // never generated. `dynamicTool` was used to dodge a typing friction — the `tool()` helper infers
560
+ // `never` with a generic ZodTypeAny — and the price was a change in behaviour. The cast is the
561
+ // honest way: what the SDK needs is exactly this object.
598
562
  return [e.name, {
599
563
  description: e.tool.description,
600
564
  inputSchema: e.tool.inputSchema,
@@ -605,17 +569,17 @@ requesterId) => {
605
569
  const started = Date.now();
606
570
  const verdict = hooks.authorize ? await hooks.authorize(invocation, e.tool) : { allowed: true };
607
571
  if (!verdict.allowed) {
608
- // Se devuelve como DATO, no como excepcion: una excepcion corta la conversacion, y lo
609
- // que queremos es que el modelo sepa que esa via esta cerrada y pruebe otra.
572
+ // Returned as DATA, not as an exception: an exception cuts the conversation short, and
573
+ // what we want is for the model to learn that route is closed and try another.
610
574
  const denial = { error: `tool '${e.name}' not allowed${verdict.reason ? `: ${verdict.reason}` : ''}` };
611
575
  (_a = hooks.observe) === null || _a === void 0 ? void 0 : _a.call(hooks, invocation, { ok: false, error: denial.error, ms: Date.now() - started, denied: true });
612
576
  return denial;
613
577
  }
614
578
  const host = (0, exports.buildToolHost)((_c = (_b = (0, exports.getToolset)(e.toolsetId)) === null || _b === void 0 ? void 0 : _b.requires) !== null && _c !== void 0 ? _c : [], context);
615
579
  try {
616
- // El runWithToolContext envuelve tambien a las tools escritas contra el contrato VIEJO
617
- // (las que leen ctx()). Es lo que permite migrar las 43 paquete a paquete en S3 en vez
618
- // de tener que reescribirlas todas antes de poder usar este camino.
580
+ // runWithToolContext also wraps the tools written against the OLD contract (the ones
581
+ // that read ctx()). That is what lets the 43 be migrated package by package in S3,
582
+ // instead of having to rewrite them all before this path can be used at all.
619
583
  const result = await (0, exports.runWithToolContext)(context, () => e.tool.execute(args, host));
620
584
  (_d = hooks.observe) === null || _d === void 0 ? void 0 : _d.call(hooks, invocation, { ok: true, result, ms: Date.now() - started });
621
585
  return result;
@@ -631,1066 +595,3 @@ requesterId) => {
631
595
  return Object.fromEntries(entries);
632
596
  };
633
597
  exports.buildAgentTools = buildAgentTools;
634
- exports.tools = {
635
- // ── CLUSTER CONFIG ───────────────────────────────────────────────────────
636
- list_namespaces: (0, ai_1.tool)({
637
- description: 'Lists all namespaces in the cluster with their status and labels.',
638
- inputSchema: zod_1.z.object({}),
639
- execute: async () => {
640
- var _a;
641
- ctx().trace('list_namespaces', {});
642
- try {
643
- const resp = await ctx().clusterInfo.coreApi.listNamespace();
644
- return {
645
- namespaces: resp.items.map((ns) => {
646
- var _a, _b, _c, _d, _e;
647
- return ({
648
- name: (_a = ns.metadata) === null || _a === void 0 ? void 0 : _a.name,
649
- uid: (_b = ns.metadata) === null || _b === void 0 ? void 0 : _b.uid,
650
- status: (_c = ns.status) === null || _c === void 0 ? void 0 : _c.phase,
651
- labels: (_e = (_d = ns.metadata) === null || _d === void 0 ? void 0 : _d.labels) !== null && _e !== void 0 ? _e : {}
652
- });
653
- })
654
- };
655
- }
656
- catch (err) {
657
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
658
- }
659
- }
660
- }),
661
- get_node_data: (0, ai_1.tool)({
662
- description: 'Returns configuration info about all Kubernetes nodes (name, IP). Configuration only — not workload or usage data.',
663
- inputSchema: zod_1.z.object({}),
664
- execute: async () => { ctx().trace('get_node_data', {}); return mapToJson(ctx().nodes); }
665
- }),
666
- get_cluster_data: (0, ai_1.tool)({
667
- description: 'Returns general cluster info: name, flavour (AKS/EKS/GKE/k3s/k3d), total vCPUs, total memory, node count and readiness status.',
668
- inputSchema: zod_1.z.object({}),
669
- execute: async () => {
670
- var _a;
671
- ctx().trace('get_cluster_data', {});
672
- try {
673
- const resp = await ctx().clusterInfo.coreApi.listNode();
674
- return { name: ctx().clusterInfo.name, flavour: ctx().clusterInfo.flavour, vcpus: ctx().clusterInfo.vcpus, memoryGB: Math.round(ctx().clusterInfo.memory / 1024 / 1024 / 1024 * 100) / 100, nodeCount: resp.items.length, nodes: resp.items.map((n) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l; return ({ name: (_a = n.metadata) === null || _a === void 0 ? void 0 : _a.name, cpu: (_c = (_b = n.status) === null || _b === void 0 ? void 0 : _b.capacity) === null || _c === void 0 ? void 0 : _c['cpu'], memoryKi: (_e = (_d = n.status) === null || _d === void 0 ? void 0 : _d.capacity) === null || _e === void 0 ? void 0 : _e['memory'], ready: ((_h = (_g = (_f = n.status) === null || _f === void 0 ? void 0 : _f.conditions) === null || _g === void 0 ? void 0 : _g.find((c) => c.type === 'Ready')) === null || _h === void 0 ? void 0 : _h.status) === 'True', unschedulable: (_l = (_j = n.spec) === null || _j === void 0 ? void 0 : _j.unschedulable) !== null && _l !== void 0 ? _l : false }); }) };
675
- }
676
- catch (err) {
677
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
678
- }
679
- }
680
- }),
681
- get_workload_data: (0, ai_1.tool)({
682
- description: 'Returns all workloads in the cluster: deployments, statefulsets, daemonsets, pods and services. Optionally filter by namespace.',
683
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().optional().describe('Namespace to filter results (omit or pass "*" for all namespaces)') }),
684
- execute: async ({ namespace }) => {
685
- var _a;
686
- const ns = namespace && namespace !== '*' ? namespace : undefined;
687
- ctx().trace('get_workload_data', { namespace: ns !== null && ns !== void 0 ? ns : '*' });
688
- try {
689
- const c = ctx().clusterInfo;
690
- const [d, s, ds, p, svc] = await Promise.all([
691
- ns ? c.appsApi.listNamespacedDeployment({ namespace: ns }) : c.appsApi.listDeploymentForAllNamespaces(),
692
- ns ? c.appsApi.listNamespacedStatefulSet({ namespace: ns }) : c.appsApi.listStatefulSetForAllNamespaces(),
693
- ns ? c.appsApi.listNamespacedDaemonSet({ namespace: ns }) : c.appsApi.listDaemonSetForAllNamespaces(),
694
- ns ? c.coreApi.listNamespacedPod({ namespace: ns }) : c.coreApi.listPodForAllNamespaces(),
695
- ns ? c.coreApi.listNamespacedService({ namespace: ns }) : c.coreApi.listServiceForAllNamespaces()
696
- ]);
697
- return {
698
- deployments: d.items.map((x) => { var _a, _b, _c, _d, _e, _f, _g; return ({ name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name, namespace: (_b = x.metadata) === null || _b === void 0 ? void 0 : _b.namespace, replicas: (_c = x.spec) === null || _c === void 0 ? void 0 : _c.replicas, readyReplicas: (_e = (_d = x.status) === null || _d === void 0 ? void 0 : _d.readyReplicas) !== null && _e !== void 0 ? _e : 0, availableReplicas: (_g = (_f = x.status) === null || _f === void 0 ? void 0 : _f.availableReplicas) !== null && _g !== void 0 ? _g : 0 }); }),
699
- statefulSets: s.items.map((x) => { var _a, _b, _c, _d, _e; return ({ name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name, namespace: (_b = x.metadata) === null || _b === void 0 ? void 0 : _b.namespace, replicas: (_c = x.spec) === null || _c === void 0 ? void 0 : _c.replicas, readyReplicas: (_e = (_d = x.status) === null || _d === void 0 ? void 0 : _d.readyReplicas) !== null && _e !== void 0 ? _e : 0 }); }),
700
- daemonSets: ds.items.map((x) => { var _a, _b, _c, _d; return ({ name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name, namespace: (_b = x.metadata) === null || _b === void 0 ? void 0 : _b.namespace, desired: (_c = x.status) === null || _c === void 0 ? void 0 : _c.desiredNumberScheduled, ready: (_d = x.status) === null || _d === void 0 ? void 0 : _d.numberReady }); }),
701
- pods: p.items.map((x) => { var _a, _b, _c, _d, _e, _f, _g; return ({ name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name, namespace: (_b = x.metadata) === null || _b === void 0 ? void 0 : _b.namespace, nodeName: (_c = x.spec) === null || _c === void 0 ? void 0 : _c.nodeName, phase: (_d = x.status) === null || _d === void 0 ? void 0 : _d.phase, ready: ((_g = (_f = (_e = x.status) === null || _e === void 0 ? void 0 : _e.conditions) === null || _f === void 0 ? void 0 : _f.find((c) => c.type === 'Ready')) === null || _g === void 0 ? void 0 : _g.status) === 'True' }); }),
702
- services: svc.items.map((x) => { var _a, _b, _c, _d; return ({ name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name, namespace: (_b = x.metadata) === null || _b === void 0 ? void 0 : _b.namespace, type: (_c = x.spec) === null || _c === void 0 ? void 0 : _c.type, clusterIP: (_d = x.spec) === null || _d === void 0 ? void 0 : _d.clusterIP }); })
703
- };
704
- }
705
- catch (err) {
706
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
707
- }
708
- }
709
- }),
710
- get_space_data: (0, ai_1.tool)({
711
- description: 'Describes a Kubernetes namespace (equivalent to kubectl describe namespace + a rollup): its status and labels, ResourceQuota usage (used vs hard) and LimitRange defaults, plus the resources in it — pods (with restart count), deployments, services and configmap names.',
712
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().describe('Name of the namespace to retrieve data for') }),
713
- execute: async ({ namespace }) => {
714
- var _a, _b, _c, _d;
715
- ctx().trace('get_space_data', { namespace });
716
- try {
717
- const c = ctx().clusterInfo;
718
- // ns/quota/limits are best-effort: a missing RBAC for them must not hide the core namespace rollup.
719
- const [ns, p, d, s, cm, rq, lr] = await Promise.all([
720
- c.coreApi.readNamespace({ name: namespace }).catch(() => null),
721
- c.coreApi.listNamespacedPod({ namespace }),
722
- c.appsApi.listNamespacedDeployment({ namespace }),
723
- c.coreApi.listNamespacedService({ namespace }),
724
- c.coreApi.listNamespacedConfigMap({ namespace }),
725
- c.coreApi.listNamespacedResourceQuota({ namespace }).catch(() => ({ items: [] })),
726
- c.coreApi.listNamespacedLimitRange({ namespace }).catch(() => ({ items: [] }))
727
- ]);
728
- return {
729
- namespace,
730
- status: (_a = ns === null || ns === void 0 ? void 0 : ns.status) === null || _a === void 0 ? void 0 : _a.phase,
731
- labels: (_c = (_b = ns === null || ns === void 0 ? void 0 : ns.metadata) === null || _b === void 0 ? void 0 : _b.labels) !== null && _c !== void 0 ? _c : {},
732
- resourceQuotas: rq.items.map((q) => { var _a, _b, _c, _d, _e, _f, _g; return ({ name: (_a = q.metadata) === null || _a === void 0 ? void 0 : _a.name, hard: (_e = (_c = (_b = q.status) === null || _b === void 0 ? void 0 : _b.hard) !== null && _c !== void 0 ? _c : (_d = q.spec) === null || _d === void 0 ? void 0 : _d.hard) !== null && _e !== void 0 ? _e : {}, used: (_g = (_f = q.status) === null || _f === void 0 ? void 0 : _f.used) !== null && _g !== void 0 ? _g : {} }); }),
733
- limitRanges: lr.items.map((l) => { var _a, _b, _c; return ({ name: (_a = l.metadata) === null || _a === void 0 ? void 0 : _a.name, limits: (_c = (_b = l.spec) === null || _b === void 0 ? void 0 : _b.limits) !== null && _c !== void 0 ? _c : [] }); }),
734
- pods: p.items.map((x) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j; return ({ name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name, phase: (_b = x.status) === null || _b === void 0 ? void 0 : _b.phase, nodeName: (_c = x.spec) === null || _c === void 0 ? void 0 : _c.nodeName, ready: ((_f = (_e = (_d = x.status) === null || _d === void 0 ? void 0 : _d.conditions) === null || _e === void 0 ? void 0 : _e.find((c) => c.type === 'Ready')) === null || _f === void 0 ? void 0 : _f.status) === 'True', restartCount: (_j = (_h = (_g = x.status) === null || _g === void 0 ? void 0 : _g.containerStatuses) === null || _h === void 0 ? void 0 : _h.reduce((sum, cs) => sum + cs.restartCount, 0)) !== null && _j !== void 0 ? _j : 0 }); }),
735
- deployments: d.items.map((x) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j; return ({ name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name, replicas: (_b = x.spec) === null || _b === void 0 ? void 0 : _b.replicas, readyReplicas: (_d = (_c = x.status) === null || _c === void 0 ? void 0 : _c.readyReplicas) !== null && _d !== void 0 ? _d : 0, image: (_j = (_h = (_g = (_f = (_e = x.spec) === null || _e === void 0 ? void 0 : _e.template) === null || _f === void 0 ? void 0 : _f.spec) === null || _g === void 0 ? void 0 : _g.containers) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.image }); }),
736
- services: s.items.map((x) => { var _a, _b, _c; return ({ name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name, type: (_b = x.spec) === null || _b === void 0 ? void 0 : _b.type, clusterIP: (_c = x.spec) === null || _c === void 0 ? void 0 : _c.clusterIP }); }),
737
- configMaps: cm.items.map((x) => { var _a; return (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name; })
738
- };
739
- }
740
- catch (err) {
741
- return { error: (_d = err.message) !== null && _d !== void 0 ? _d : String(err) };
742
- }
743
- }
744
- }),
745
- get_namespace_yaml: (0, ai_1.tool)({
746
- description: 'Returns the full Kubernetes Namespace manifest (equivalent to kubectl get namespace -o yaml): complete metadata (uid, labels, annotations, creationTimestamp), spec (finalizers) and status. Use when you need a specific field the namespace summary doesn\'t include (e.g. its uid).',
747
- inputSchema: zod_1.z.object({ name: zod_1.z.string().describe('Name of the namespace') }),
748
- execute: async ({ name }) => {
749
- var _a;
750
- ctx().trace('get_namespace_yaml', { name });
751
- try {
752
- return await ctx().clusterInfo.coreApi.readNamespace({ name });
753
- }
754
- catch (err) {
755
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
756
- }
757
- }
758
- }),
759
- describe_service: (0, ai_1.tool)({
760
- description: 'Diagnostic summary of a Service (equivalent to kubectl describe service): type, clusterIP, ports, selector, sessionAffinity, external/loadBalancer, AND its live Endpoints — the pod IPs currently backing it (ready vs not-ready). Best tool to see WHY traffic isn\'t reaching pods (empty/not-ready endpoints = selector mismatch or unready pods).',
761
- inputSchema: zod_1.z.object({
762
- namespace: zod_1.z.string().describe('Namespace of the service'),
763
- name: zod_1.z.string().describe('Name of the service')
764
- }),
765
- execute: async ({ namespace, name }) => {
766
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p, _q, _r;
767
- ctx().trace('describe_service', { namespace, name });
768
- try {
769
- const c = ctx().clusterInfo;
770
- const svc = await c.coreApi.readNamespacedService({ name, namespace });
771
- const ep = await c.coreApi.readNamespacedEndpoints({ name, namespace }).catch(() => null);
772
- const endpoints = ((_a = ep === null || ep === void 0 ? void 0 : ep.subsets) !== null && _a !== void 0 ? _a : []).flatMap((ss) => {
773
- var _a, _b;
774
- return [
775
- ...((_a = ss.addresses) !== null && _a !== void 0 ? _a : []).map((a) => { var _a; return ({ ip: a.ip, ready: true, targetRef: a.targetRef ? `${a.targetRef.kind}/${a.targetRef.name}` : undefined, ports: ((_a = ss.ports) !== null && _a !== void 0 ? _a : []).map((p) => p.port) }); }),
776
- ...((_b = ss.notReadyAddresses) !== null && _b !== void 0 ? _b : []).map((a) => { var _a; return ({ ip: a.ip, ready: false, targetRef: a.targetRef ? `${a.targetRef.kind}/${a.targetRef.name}` : undefined, ports: ((_a = ss.ports) !== null && _a !== void 0 ? _a : []).map((p) => p.port) }); })
777
- ];
778
- });
779
- return {
780
- name, namespace,
781
- type: (_b = svc.spec) === null || _b === void 0 ? void 0 : _b.type, clusterIP: (_c = svc.spec) === null || _c === void 0 ? void 0 : _c.clusterIP, externalIPs: (_e = (_d = svc.spec) === null || _d === void 0 ? void 0 : _d.externalIPs) !== null && _e !== void 0 ? _e : [],
782
- loadBalancer: (_h = (_g = (_f = svc.status) === null || _f === void 0 ? void 0 : _f.loadBalancer) === null || _g === void 0 ? void 0 : _g.ingress) !== null && _h !== void 0 ? _h : [], sessionAffinity: (_j = svc.spec) === null || _j === void 0 ? void 0 : _j.sessionAffinity,
783
- selector: (_m = (_l = svc.spec) === null || _l === void 0 ? void 0 : _l.selector) !== null && _m !== void 0 ? _m : {},
784
- ports: (_q = (_p = (_o = svc.spec) === null || _o === void 0 ? void 0 : _o.ports) === null || _p === void 0 ? void 0 : _p.map((p) => ({ name: p.name, port: p.port, targetPort: p.targetPort, nodePort: p.nodePort, protocol: p.protocol }))) !== null && _q !== void 0 ? _q : [],
785
- endpoints, // the pods actually behind the service right now (empty = nothing serving)
786
- endpointCount: endpoints.length
787
- };
788
- }
789
- catch (err) {
790
- return { error: (_r = err.message) !== null && _r !== void 0 ? _r : String(err) };
791
- }
792
- }
793
- }),
794
- describe_ingress: (0, ai_1.tool)({
795
- description: 'Diagnostic summary of an Ingress (equivalent to kubectl describe ingress): ingressClass, the routing rules (host → path → backend service:port), the default backend, TLS (hosts + secret), and the load-balancer address assigned by the controller. Use to see how external traffic is routed to services.',
796
- inputSchema: zod_1.z.object({
797
- namespace: zod_1.z.string().describe('Namespace of the ingress'),
798
- name: zod_1.z.string().describe('Name of the ingress')
799
- }),
800
- execute: async ({ namespace, name }) => {
801
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l;
802
- ctx().trace('describe_ingress', { namespace, name });
803
- try {
804
- const ing = await ctx().clusterInfo.networkApi.readNamespacedIngress({ name, namespace });
805
- const backend = (b) => { var _a, _b, _c; return (b === null || b === void 0 ? void 0 : b.service) ? `${b.service.name}:${(_b = (_a = b.service.port) === null || _a === void 0 ? void 0 : _a.number) !== null && _b !== void 0 ? _b : (_c = b.service.port) === null || _c === void 0 ? void 0 : _c.name}` : ((b === null || b === void 0 ? void 0 : b.resource) ? `${b.resource.kind}/${b.resource.name}` : undefined); };
806
- return {
807
- name, namespace,
808
- ingressClass: (_a = ing.spec) === null || _a === void 0 ? void 0 : _a.ingressClassName,
809
- defaultBackend: backend((_b = ing.spec) === null || _b === void 0 ? void 0 : _b.defaultBackend),
810
- rules: ((_d = (_c = ing.spec) === null || _c === void 0 ? void 0 : _c.rules) !== null && _d !== void 0 ? _d : []).flatMap((r) => { var _a, _b; return ((_b = (_a = r.http) === null || _a === void 0 ? void 0 : _a.paths) !== null && _b !== void 0 ? _b : []).map((p) => ({ host: r.host, path: p.path, pathType: p.pathType, backend: backend(p.backend) })); }),
811
- tls: ((_f = (_e = ing.spec) === null || _e === void 0 ? void 0 : _e.tls) !== null && _f !== void 0 ? _f : []).map((t) => ({ hosts: t.hosts, secretName: t.secretName })),
812
- loadBalancer: (_j = (_h = (_g = ing.status) === null || _g === void 0 ? void 0 : _g.loadBalancer) === null || _h === void 0 ? void 0 : _h.ingress) !== null && _j !== void 0 ? _j : []
813
- };
814
- }
815
- catch (err) {
816
- return { error: (_l = err.message) !== null && _l !== void 0 ? _l : String(err) };
817
- }
818
- }
819
- }),
820
- describe_controller: (0, ai_1.tool)({
821
- description: 'Diagnostic summary of a workload controller (equivalent to kubectl describe deployment/statefulset/daemonset/replicaset): replica counts (desired/ready/available/updated), rollout strategy, conditions (Available/Progressing + reason — why it is not fully rolled out), selector, and its pod template (image, resources, probes). Parametrised by kind, so one call covers any controller type.',
822
- inputSchema: zod_1.z.object({
823
- namespace: zod_1.z.string().describe('Namespace of the controller'),
824
- kind: zod_1.z.enum(['Deployment', 'StatefulSet', 'DaemonSet', 'ReplicaSet']).describe('Controller kind'),
825
- name: zod_1.z.string().describe('Name of the controller')
826
- }),
827
- execute: async ({ namespace, kind, name }) => {
828
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p, _q, _r, _s;
829
- ctx().trace('describe_controller', { namespace, kind, name });
830
- try {
831
- const a = ctx().clusterInfo.appsApi;
832
- const obj = kind === 'StatefulSet' ? await a.readNamespacedStatefulSet({ name, namespace })
833
- : kind === 'DaemonSet' ? await a.readNamespacedDaemonSet({ name, namespace })
834
- : kind === 'ReplicaSet' ? await a.readNamespacedReplicaSet({ name, namespace })
835
- : await a.readNamespacedDeployment({ name, namespace });
836
- const spec = (_a = obj.spec) !== null && _a !== void 0 ? _a : {}, status = (_b = obj.status) !== null && _b !== void 0 ? _b : {};
837
- const tpl = (_d = (_c = spec.template) === null || _c === void 0 ? void 0 : _c.spec) !== null && _d !== void 0 ? _d : {};
838
- const container = (ct) => ({ name: ct.name, image: ct.image, resources: ct.resources, livenessProbe: !!ct.livenessProbe, readinessProbe: !!ct.readinessProbe });
839
- // DaemonSet reports scheduling counts; the others report replica counts.
840
- const replicas = kind === 'DaemonSet'
841
- ? { desired: status.desiredNumberScheduled, current: status.currentNumberScheduled, ready: status.numberReady, available: status.numberAvailable, updated: status.updatedNumberScheduled }
842
- : { desired: spec.replicas, ready: (_e = status.readyReplicas) !== null && _e !== void 0 ? _e : 0, available: (_f = status.availableReplicas) !== null && _f !== void 0 ? _f : 0, updated: (_g = status.updatedReplicas) !== null && _g !== void 0 ? _g : 0 };
843
- return {
844
- kind, name, namespace,
845
- replicas,
846
- strategy: (_j = (_h = spec.strategy) === null || _h === void 0 ? void 0 : _h.type) !== null && _j !== void 0 ? _j : (_l = spec.updateStrategy) === null || _l === void 0 ? void 0 : _l.type,
847
- conditions: ((_m = status.conditions) !== null && _m !== void 0 ? _m : []).map((c) => ({ type: c.type, status: c.status, reason: c.reason, message: c.message })),
848
- selector: (_p = (_o = spec.selector) === null || _o === void 0 ? void 0 : _o.matchLabels) !== null && _p !== void 0 ? _p : {},
849
- template: { containers: ((_q = tpl.containers) !== null && _q !== void 0 ? _q : []).map(container), initContainers: ((_r = tpl.initContainers) !== null && _r !== void 0 ? _r : []).map(container), serviceAccount: tpl.serviceAccountName }
850
- };
851
- }
852
- catch (err) {
853
- return { error: (_s = err.message) !== null && _s !== void 0 ? _s : String(err) };
854
- }
855
- }
856
- }),
857
- get_service_yaml: (0, ai_1.tool)({
858
- description: 'Returns the full Kubernetes Service manifest (equivalent to kubectl get service -o yaml) for a given namespace and service name.',
859
- inputSchema: zod_1.z.object({
860
- namespace: zod_1.z.string().describe('Namespace where the service lives'),
861
- name: zod_1.z.string().describe('Name of the service')
862
- }),
863
- execute: async ({ namespace, name }) => {
864
- var _a;
865
- ctx().trace('get_service_yaml', { namespace, name });
866
- try {
867
- const svc = await ctx().clusterInfo.coreApi.readNamespacedService({ name, namespace });
868
- return svc;
869
- }
870
- catch (err) {
871
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
872
- }
873
- }
874
- }),
875
- list_services: (0, ai_1.tool)({
876
- description: 'Lists all Services in the cluster with full details (type, clusterIP, ports, selector). Optionally filter by namespace.',
877
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().optional().describe('Namespace to filter results (omit or pass "*" for all namespaces)') }),
878
- execute: async ({ namespace }) => {
879
- var _a;
880
- const ns = namespace && namespace !== '*' ? namespace : undefined;
881
- ctx().trace('list_services', { namespace: ns !== null && ns !== void 0 ? ns : '*' });
882
- try {
883
- const c = ctx().clusterInfo;
884
- const resp = ns
885
- ? await c.coreApi.listNamespacedService({ namespace: ns })
886
- : await c.coreApi.listServiceForAllNamespaces();
887
- return {
888
- services: resp.items.map((x) => {
889
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m;
890
- return ({
891
- name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name,
892
- namespace: (_b = x.metadata) === null || _b === void 0 ? void 0 : _b.namespace,
893
- type: (_c = x.spec) === null || _c === void 0 ? void 0 : _c.type,
894
- clusterIP: (_d = x.spec) === null || _d === void 0 ? void 0 : _d.clusterIP,
895
- externalIPs: (_f = (_e = x.spec) === null || _e === void 0 ? void 0 : _e.externalIPs) !== null && _f !== void 0 ? _f : [],
896
- ports: (_j = (_h = (_g = x.spec) === null || _g === void 0 ? void 0 : _g.ports) === null || _h === void 0 ? void 0 : _h.map((p) => ({ name: p.name, port: p.port, targetPort: p.targetPort, protocol: p.protocol }))) !== null && _j !== void 0 ? _j : [],
897
- selector: (_m = (_l = x.spec) === null || _l === void 0 ? void 0 : _l.selector) !== null && _m !== void 0 ? _m : {}
898
- });
899
- })
900
- };
901
- }
902
- catch (err) {
903
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
904
- }
905
- }
906
- }),
907
- list_ingresses: (0, ai_1.tool)({
908
- description: 'Lists all Ingresses in the cluster (hosts, paths, TLS, backend services). Optionally filter by namespace.',
909
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().optional().describe('Namespace to filter results (omit or pass "*" for all namespaces)') }),
910
- execute: async ({ namespace }) => {
911
- var _a;
912
- const ns = namespace && namespace !== '*' ? namespace : undefined;
913
- ctx().trace('list_ingresses', { namespace: ns !== null && ns !== void 0 ? ns : '*' });
914
- try {
915
- const c = ctx().clusterInfo;
916
- const resp = ns
917
- ? await c.networkApi.listNamespacedIngress({ namespace: ns })
918
- : await c.networkApi.listIngressForAllNamespaces();
919
- return {
920
- ingresses: resp.items.map((x) => {
921
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p, _q, _r;
922
- return ({
923
- name: (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name,
924
- namespace: (_b = x.metadata) === null || _b === void 0 ? void 0 : _b.namespace,
925
- ingressClass: (_c = x.spec) === null || _c === void 0 ? void 0 : _c.ingressClassName,
926
- hosts: (_f = (_e = (_d = x.spec) === null || _d === void 0 ? void 0 : _d.rules) === null || _e === void 0 ? void 0 : _e.map((r) => r.host)) !== null && _f !== void 0 ? _f : [],
927
- paths: (_j = (_h = (_g = x.spec) === null || _g === void 0 ? void 0 : _g.rules) === null || _h === void 0 ? void 0 : _h.flatMap((r) => { var _a, _b, _c; return (_c = (_b = (_a = r.http) === null || _a === void 0 ? void 0 : _a.paths) === null || _b === void 0 ? void 0 : _b.map((p) => { var _a, _b, _c, _d, _e; return ({ host: r.host, path: p.path, pathType: p.pathType, service: (_b = (_a = p.backend) === null || _a === void 0 ? void 0 : _a.service) === null || _b === void 0 ? void 0 : _b.name, port: (_e = (_d = (_c = p.backend) === null || _c === void 0 ? void 0 : _c.service) === null || _d === void 0 ? void 0 : _d.port) === null || _e === void 0 ? void 0 : _e.number }); })) !== null && _c !== void 0 ? _c : []; })) !== null && _j !== void 0 ? _j : [],
928
- tls: (_o = (_m = (_l = x.spec) === null || _l === void 0 ? void 0 : _l.tls) === null || _m === void 0 ? void 0 : _m.map((t) => ({ secretName: t.secretName, hosts: t.hosts }))) !== null && _o !== void 0 ? _o : [],
929
- loadBalancer: (_r = (_q = (_p = x.status) === null || _p === void 0 ? void 0 : _p.loadBalancer) === null || _q === void 0 ? void 0 : _q.ingress) !== null && _r !== void 0 ? _r : []
930
- });
931
- })
932
- };
933
- }
934
- catch (err) {
935
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
936
- }
937
- }
938
- }),
939
- get_ingress_yaml: (0, ai_1.tool)({
940
- description: 'Returns the full Kubernetes Ingress manifest (equivalent to kubectl get ingress -o yaml) for a given namespace and ingress name.',
941
- inputSchema: zod_1.z.object({
942
- namespace: zod_1.z.string().describe('Namespace where the ingress lives'),
943
- name: zod_1.z.string().describe('Name of the ingress')
944
- }),
945
- execute: async ({ namespace, name }) => {
946
- var _a;
947
- ctx().trace('get_ingress_yaml', { namespace, name });
948
- try {
949
- const ing = await ctx().clusterInfo.networkApi.readNamespacedIngress({ name, namespace });
950
- return ing;
951
- }
952
- catch (err) {
953
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
954
- }
955
- }
956
- }),
957
- // ── CURRENT USAGE ────────────────────────────────────────────────────────
958
- get_cluster_usage: (0, ai_1.tool)({
959
- description: 'Returns current overall cluster resource usage: CPU%, memory%, network Mbps, total vCPUs and total memory GB.',
960
- inputSchema: zod_1.z.object({}),
961
- execute: async () => {
962
- ctx().trace('get_cluster_usage', {});
963
- if (ctx().clusterMetrics.length === 0)
964
- return { error: 'No metrics available yet' };
965
- const latest = ctx().clusterMetrics[ctx().clusterMetrics.length - 1];
966
- return { vcpus: latest.cluster.vcpus, memoryGB: Math.round(latest.cluster.memory / 1024 / 1024 / 1024 * 100) / 100, cpuUsagePercent: Math.round(latest.cluster.cpuUsage * 100) / 100, memoryUsagePercent: Math.round(latest.cluster.memoryUsage * 100) / 100, networkTxMbps: Math.round(latest.cluster.txmbps * 100) / 100, networkRxMbps: Math.round(latest.cluster.rxmbps * 100) / 100, metricsIntervalSeconds: latest.metricsInterval };
967
- }
968
- }),
969
- get_node_usage: (0, ai_1.tool)({
970
- description: 'Returns current CPU and memory usage for one node or all nodes from the latest metrics reading.',
971
- inputSchema: zod_1.z.object({ nodeName: zod_1.z.string().optional().describe('Node name to filter (omit for all nodes)') }),
972
- execute: async ({ nodeName }) => {
973
- ctx().trace('get_node_usage', { nodeName: nodeName !== null && nodeName !== void 0 ? nodeName : '*' });
974
- if (ctx().clusterMetrics.length === 0)
975
- return { error: 'No metrics available yet' };
976
- const latest = ctx().clusterMetrics[ctx().clusterMetrics.length - 1];
977
- const nodes = nodeName ? latest.nodes.filter((n) => n.name === nodeName) : latest.nodes;
978
- return nodes.map((n) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p, _q, _r; return ({ name: n.name, cpuMillicores: Math.round(((_c = (_b = (_a = n.summary) === null || _a === void 0 ? void 0 : _a.cpu) === null || _b === void 0 ? void 0 : _b.usageNanoCores) !== null && _c !== void 0 ? _c : 0) / 1000000), memoryMB: Math.round(((_f = (_e = (_d = n.summary) === null || _d === void 0 ? void 0 : _d.memory) === null || _e === void 0 ? void 0 : _e.workingSetBytes) !== null && _f !== void 0 ? _f : 0) / 1024 / 1024), networkRxMB: Math.round(((_j = (_h = (_g = n.summary) === null || _g === void 0 ? void 0 : _g.network) === null || _h === void 0 ? void 0 : _h.rxBytes) !== null && _j !== void 0 ? _j : 0) / 1024 / 1024), networkTxMB: Math.round(((_o = (_m = (_l = n.summary) === null || _l === void 0 ? void 0 : _l.network) === null || _m === void 0 ? void 0 : _m.txBytes) !== null && _o !== void 0 ? _o : 0) / 1024 / 1024), podCount: (_r = (_q = (_p = n.summary) === null || _p === void 0 ? void 0 : _p.pods) === null || _q === void 0 ? void 0 : _q.length) !== null && _r !== void 0 ? _r : 0, timestamp: n.timestamp }); });
979
- }
980
- }),
981
- get_deployment_usage: (0, ai_1.tool)({
982
- description: 'Returns current aggregated CPU and memory usage for all pods belonging to a specific deployment.',
983
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().describe('Namespace of the deployment'), name: zod_1.z.string().describe('Name of the deployment') }),
984
- execute: async ({ namespace, name }) => {
985
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p;
986
- ctx().trace('get_deployment_usage', { namespace, name });
987
- try {
988
- if (ctx().clusterMetrics.length === 0)
989
- return { error: 'No metrics available yet' };
990
- const latest = ctx().clusterMetrics[ctx().clusterMetrics.length - 1];
991
- const c = ctx().clusterInfo;
992
- const deployResp = await c.appsApi.readNamespacedDeployment({ name, namespace });
993
- const labelSelector = Object.entries((_c = (_b = (_a = deployResp.spec) === null || _a === void 0 ? void 0 : _a.selector) === null || _b === void 0 ? void 0 : _b.matchLabels) !== null && _c !== void 0 ? _c : {}).map(([k, v]) => `${k}=${v}`).join(',');
994
- const podsResp = await c.coreApi.listNamespacedPod({ namespace, labelSelector });
995
- const podNames = new Set(podsResp.items.map((p) => { var _a; return (_a = p.metadata) === null || _a === void 0 ? void 0 : _a.name; }));
996
- let totalCpu = 0, totalMem = 0, podCount = 0;
997
- for (const node of latest.nodes)
998
- for (const pod of ((_e = (_d = node.summary) === null || _d === void 0 ? void 0 : _d.pods) !== null && _e !== void 0 ? _e : []))
999
- if (((_f = pod.podRef) === null || _f === void 0 ? void 0 : _f.namespace) === namespace && podNames.has((_g = pod.podRef) === null || _g === void 0 ? void 0 : _g.name)) {
1000
- totalCpu += (_j = (_h = pod.cpu) === null || _h === void 0 ? void 0 : _h.usageNanoCores) !== null && _j !== void 0 ? _j : 0;
1001
- totalMem += (_m = (_l = pod.memory) === null || _l === void 0 ? void 0 : _l.workingSetBytes) !== null && _m !== void 0 ? _m : 0;
1002
- podCount++;
1003
- }
1004
- return { deployment: name, namespace, podCount, cpuMillicores: Math.round(totalCpu / 1000000), memoryMB: Math.round(totalMem / 1024 / 1024), timestamp: (_o = latest.nodes[0]) === null || _o === void 0 ? void 0 : _o.timestamp };
1005
- }
1006
- catch (err) {
1007
- return { error: (_p = err.message) !== null && _p !== void 0 ? _p : String(err) };
1008
- }
1009
- }
1010
- }),
1011
- // ── HISTORICAL USAGE ─────────────────────────────────────────────────────
1012
- get_prev_cluster_usage: (0, ai_1.tool)({
1013
- description: 'Returns historical overall cluster usage over the last N metrics readings (CPU%, memory%, network Mbps).',
1014
- inputSchema: zod_1.z.object({ count: zod_1.z.number().optional().describe('Number of historical readings to return (default: 5)') }),
1015
- execute: async ({ count = 5 }) => {
1016
- ctx().trace('get_prev_cluster_usage', { count });
1017
- if (ctx().clusterMetrics.length === 0)
1018
- return { error: 'No metrics available yet' };
1019
- return ctx().clusterMetrics.slice(-count).map((r) => ({ vcpus: r.cluster.vcpus, memoryGB: Math.round(r.cluster.memory / 1024 / 1024 / 1024 * 100) / 100, cpuUsagePercent: Math.round(r.cluster.cpuUsage * 100) / 100, memoryUsagePercent: Math.round(r.cluster.memoryUsage * 100) / 100, networkTxMbps: Math.round(r.cluster.txmbps * 100) / 100, networkRxMbps: Math.round(r.cluster.rxmbps * 100) / 100 }));
1020
- }
1021
- }),
1022
- get_prev_node_usage: (0, ai_1.tool)({
1023
- description: 'Returns historical CPU and memory usage for one or all nodes over the last N metrics readings.',
1024
- inputSchema: zod_1.z.object({ nodeName: zod_1.z.string().optional().describe('Node name to filter (omit for all nodes)'), count: zod_1.z.number().optional().describe('Number of historical readings (default: 5)') }),
1025
- execute: async ({ nodeName, count = 5 }) => {
1026
- ctx().trace('get_prev_node_usage', { nodeName: nodeName !== null && nodeName !== void 0 ? nodeName : '*', count });
1027
- if (ctx().clusterMetrics.length === 0)
1028
- return { error: 'No metrics available yet' };
1029
- return ctx().clusterMetrics.slice(-count).map((r) => ({ nodes: (nodeName ? r.nodes.filter((n) => n.name === nodeName) : r.nodes).map((n) => { var _a, _b, _c, _d, _e, _f; return ({ name: n.name, cpuMillicores: Math.round(((_c = (_b = (_a = n.summary) === null || _a === void 0 ? void 0 : _a.cpu) === null || _b === void 0 ? void 0 : _b.usageNanoCores) !== null && _c !== void 0 ? _c : 0) / 1000000), memoryMB: Math.round(((_f = (_e = (_d = n.summary) === null || _d === void 0 ? void 0 : _d.memory) === null || _e === void 0 ? void 0 : _e.workingSetBytes) !== null && _f !== void 0 ? _f : 0) / 1024 / 1024), timestamp: n.timestamp }); }) }));
1030
- }
1031
- }),
1032
- get_prev_deployment_usage: (0, ai_1.tool)({
1033
- description: 'Returns historical aggregated CPU and memory usage for a deployment over the last N metrics readings.',
1034
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().describe('Namespace of the deployment'), name: zod_1.z.string().describe('Name of the deployment'), count: zod_1.z.number().optional().describe('Number of historical readings (default: 5)') }),
1035
- execute: async ({ namespace, name, count = 5 }) => {
1036
- var _a, _b, _c, _d;
1037
- ctx().trace('get_prev_deployment_usage', { namespace, name, count });
1038
- try {
1039
- if (ctx().clusterMetrics.length === 0)
1040
- return { error: 'No metrics available yet' };
1041
- const c = ctx().clusterInfo;
1042
- const deployResp = await c.appsApi.readNamespacedDeployment({ name, namespace });
1043
- const labelSelector = Object.entries((_c = (_b = (_a = deployResp.spec) === null || _a === void 0 ? void 0 : _a.selector) === null || _b === void 0 ? void 0 : _b.matchLabels) !== null && _c !== void 0 ? _c : {}).map(([k, v]) => `${k}=${v}`).join(',');
1044
- const podsResp = await c.coreApi.listNamespacedPod({ namespace, labelSelector });
1045
- const podNames = new Set(podsResp.items.map((p) => { var _a; return (_a = p.metadata) === null || _a === void 0 ? void 0 : _a.name; }));
1046
- return ctx().clusterMetrics.slice(-count).map((r) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j; let cpu = 0, mem = 0, pc = 0; for (const node of r.nodes)
1047
- for (const pod of ((_b = (_a = node.summary) === null || _a === void 0 ? void 0 : _a.pods) !== null && _b !== void 0 ? _b : []))
1048
- if (((_c = pod.podRef) === null || _c === void 0 ? void 0 : _c.namespace) === namespace && podNames.has((_d = pod.podRef) === null || _d === void 0 ? void 0 : _d.name)) {
1049
- cpu += (_f = (_e = pod.cpu) === null || _e === void 0 ? void 0 : _e.usageNanoCores) !== null && _f !== void 0 ? _f : 0;
1050
- mem += (_h = (_g = pod.memory) === null || _g === void 0 ? void 0 : _g.workingSetBytes) !== null && _h !== void 0 ? _h : 0;
1051
- pc++;
1052
- } return { deployment: name, namespace, podCount: pc, cpuMillicores: Math.round(cpu / 1000000), memoryMB: Math.round(mem / 1024 / 1024), timestamp: (_j = r.nodes[0]) === null || _j === void 0 ? void 0 : _j.timestamp }; });
1053
- }
1054
- catch (err) {
1055
- return { error: (_d = err.message) !== null && _d !== void 0 ? _d : String(err) };
1056
- }
1057
- }
1058
- }),
1059
- get_prev_space_data: (0, ai_1.tool)({
1060
- description: 'Returns historical aggregated CPU and memory usage for all pods in a namespace over the last N metrics readings.',
1061
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().describe('Namespace name'), count: zod_1.z.number().optional().describe('Number of historical readings (default: 5)') }),
1062
- execute: async ({ namespace, count = 5 }) => {
1063
- ctx().trace('get_prev_space_data', { namespace, count });
1064
- if (ctx().clusterMetrics.length === 0)
1065
- return { error: 'No metrics available yet' };
1066
- return ctx().clusterMetrics.slice(-count).map((r) => { var _a, _b, _c, _d, _e, _f, _g, _h; let cpu = 0, mem = 0, pc = 0; for (const node of r.nodes)
1067
- for (const pod of ((_b = (_a = node.summary) === null || _a === void 0 ? void 0 : _a.pods) !== null && _b !== void 0 ? _b : []))
1068
- if (((_c = pod.podRef) === null || _c === void 0 ? void 0 : _c.namespace) === namespace) {
1069
- cpu += (_e = (_d = pod.cpu) === null || _d === void 0 ? void 0 : _d.usageNanoCores) !== null && _e !== void 0 ? _e : 0;
1070
- mem += (_g = (_f = pod.memory) === null || _f === void 0 ? void 0 : _f.workingSetBytes) !== null && _g !== void 0 ? _g : 0;
1071
- pc++;
1072
- } return { namespace, podCount: pc, cpuMillicores: Math.round(cpu / 1000000), memoryMB: Math.round(mem / 1024 / 1024), timestamp: (_h = r.nodes[0]) === null || _h === void 0 ? void 0 : _h.timestamp }; });
1073
- }
1074
- }),
1075
- // ── CLUSTER ACTIONS ──────────────────────────────────────────────────────
1076
- add_node: (0, ai_1.tool)({
1077
- description: 'Adds a new agent node to the cluster. For k3d uses `k3d node create`. Cloud providers not yet implemented.',
1078
- inputSchema: zod_1.z.object({ nodeName: zod_1.z.string().optional().describe('Suffix for the new node name'), nodePoolName: zod_1.z.string().optional().describe('Node pool name (cloud provider specific, ignored for k3d)') }),
1079
- execute: async ({ nodeName, nodePoolName }) => {
1080
- var _a;
1081
- ctx().trace('add_node', { nodeName: nodeName !== null && nodeName !== void 0 ? nodeName : 'auto', nodePoolName: nodePoolName !== null && nodePoolName !== void 0 ? nodePoolName : 'default' });
1082
- if (ctx().clusterInfo.flavour === 'k3d') {
1083
- const suffix = nodeName !== null && nodeName !== void 0 ? nodeName : `agent-${Date.now()}`;
1084
- const clusterName = ctx().clusterInfo.name.replace(/^k3d-/, '');
1085
- try {
1086
- const { stdout, stderr } = await execAsync(`k3d node create ${suffix} --cluster ${clusterName} --role agent`, { timeout: 120000 });
1087
- return { success: true, message: `Node '${suffix}' added to cluster '${clusterName}'`, stdout, stderr };
1088
- }
1089
- catch (err) {
1090
- return { success: false, error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
1091
- }
1092
- }
1093
- return { success: false, message: `add_node not yet implemented for flavour '${ctx().clusterInfo.flavour}'` };
1094
- }
1095
- }),
1096
- remove_node: (0, ai_1.tool)({
1097
- description: 'Removes a node from the cluster (cordon + delete). For k3d uses `k3d node delete`. Cloud providers not yet implemented.',
1098
- inputSchema: zod_1.z.object({ nodeName: zod_1.z.string().describe('Name of the Kubernetes node to remove'), nodePoolName: zod_1.z.string().optional().describe('Node pool name (cloud provider specific, ignored for k3d)') }),
1099
- execute: async ({ nodeName, nodePoolName }) => {
1100
- var _a;
1101
- ctx().trace('remove_node', { nodeName, nodePoolName: nodePoolName !== null && nodePoolName !== void 0 ? nodePoolName : 'default' });
1102
- try {
1103
- await ctx().clusterInfo.coreApi.patchNode({ name: nodeName, body: [{ op: 'add', path: '/spec/unschedulable', value: true }] });
1104
- }
1105
- catch (_) { }
1106
- if (ctx().clusterInfo.flavour === 'k3d') {
1107
- try {
1108
- const { stdout, stderr } = await execAsync(`k3d node delete ${nodeName}`, { timeout: 60000 });
1109
- return { success: true, message: `Node '${nodeName}' removed`, stdout, stderr };
1110
- }
1111
- catch (err) {
1112
- return { success: false, error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
1113
- }
1114
- }
1115
- return { success: false, message: `remove_node not yet implemented for flavour '${ctx().clusterInfo.flavour}'` };
1116
- }
1117
- }),
1118
- stop_node: (0, ai_1.tool)({
1119
- description: 'Stops a running cluster node: cordons it then stops the container. For k3d uses `k3d node stop`.',
1120
- inputSchema: zod_1.z.object({ nodeName: zod_1.z.string().describe('Name of the Kubernetes node to stop') }),
1121
- execute: async ({ nodeName }) => {
1122
- var _a, _b;
1123
- ctx().trace('stop_node', { nodeName });
1124
- try {
1125
- await ctx().clusterInfo.coreApi.patchNode({ name: nodeName, body: [{ op: 'add', path: '/spec/unschedulable', value: true }] });
1126
- }
1127
- catch (err) {
1128
- return { success: false, error: `Failed to cordon node: ${(_a = err.message) !== null && _a !== void 0 ? _a : String(err)}` };
1129
- }
1130
- if (ctx().clusterInfo.flavour !== 'k3d')
1131
- return { success: false, message: `Node '${nodeName}' cordoned but stop only implemented for k3d` };
1132
- try {
1133
- const { stdout, stderr } = await execAsync(`k3d node stop ${nodeName}`, { timeout: 30000 });
1134
- return { success: true, message: `Node '${nodeName}' cordoned and stopped`, stdout, stderr };
1135
- }
1136
- catch (err) {
1137
- return { success: false, error: `Node cordoned but stop failed: ${(_b = err.message) !== null && _b !== void 0 ? _b : String(err)}` };
1138
- }
1139
- }
1140
- }),
1141
- start_node: (0, ai_1.tool)({
1142
- description: 'Starts a previously stopped cluster node and uncordons it. For k3d uses `k3d node start`.',
1143
- inputSchema: zod_1.z.object({ nodeName: zod_1.z.string().describe('Name of the Kubernetes node to start') }),
1144
- execute: async ({ nodeName }) => {
1145
- var _a, _b;
1146
- ctx().trace('start_node', { nodeName });
1147
- if (ctx().clusterInfo.flavour === 'k3d') {
1148
- try {
1149
- const { stdout, stderr } = await execAsync(`k3d node start ${nodeName}`, { timeout: 30000 });
1150
- try {
1151
- await ctx().clusterInfo.coreApi.patchNode({ name: nodeName, body: [{ op: 'add', path: '/spec/unschedulable', value: false }] });
1152
- }
1153
- catch (_) { }
1154
- return { success: true, message: `Node '${nodeName}' started and uncordoned`, stdout, stderr };
1155
- }
1156
- catch (err) {
1157
- return { success: false, error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
1158
- }
1159
- }
1160
- try {
1161
- await ctx().clusterInfo.coreApi.patchNode({ name: nodeName, body: [{ op: 'add', path: '/spec/unschedulable', value: false }] });
1162
- return { success: false, message: `Node '${nodeName}' uncordoned but start only implemented for k3d` };
1163
- }
1164
- catch (err) {
1165
- return { success: false, error: (_b = err.message) !== null && _b !== void 0 ? _b : String(err) };
1166
- }
1167
- }
1168
- }),
1169
- add_replica: (0, ai_1.tool)({
1170
- description: 'Scales up a deployment by adding one replica.',
1171
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().describe('Namespace of the deployment'), name: zod_1.z.string().describe('Name of the deployment') }),
1172
- execute: async ({ namespace, name }) => {
1173
- var _a, _b, _c;
1174
- ctx().trace('add_replica', { namespace, name });
1175
- try {
1176
- const c = ctx().clusterInfo;
1177
- const d = await c.appsApi.readNamespacedDeployment({ name, namespace });
1178
- const cur = (_b = (_a = d.spec) === null || _a === void 0 ? void 0 : _a.replicas) !== null && _b !== void 0 ? _b : 1;
1179
- await c.appsApi.patchNamespacedDeployment({ name, namespace, body: [{ op: 'replace', path: '/spec/replicas', value: cur + 1 }] });
1180
- return { success: true, message: `Deployment ${namespace}/${name} scaled from ${cur} to ${cur + 1} replicas` };
1181
- }
1182
- catch (err) {
1183
- return { success: false, error: (_c = err.message) !== null && _c !== void 0 ? _c : String(err) };
1184
- }
1185
- }
1186
- }),
1187
- remove_replica: (0, ai_1.tool)({
1188
- description: 'Scales down a deployment by removing one replica. Minimum of 1 replica is enforced.',
1189
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().describe('Namespace of the deployment'), name: zod_1.z.string().describe('Name of the deployment') }),
1190
- execute: async ({ namespace, name }) => {
1191
- var _a, _b, _c;
1192
- ctx().trace('remove_replica', { namespace, name });
1193
- try {
1194
- const c = ctx().clusterInfo;
1195
- const d = await c.appsApi.readNamespacedDeployment({ name, namespace });
1196
- const cur = (_b = (_a = d.spec) === null || _a === void 0 ? void 0 : _a.replicas) !== null && _b !== void 0 ? _b : 1;
1197
- if (cur <= 1)
1198
- return { success: false, message: `Deployment ${namespace}/${name} already at minimum` };
1199
- await c.appsApi.patchNamespacedDeployment({ name, namespace, body: [{ op: 'replace', path: '/spec/replicas', value: cur - 1 }] });
1200
- return { success: true, message: `Deployment ${namespace}/${name} scaled from ${cur} to ${cur - 1} replicas` };
1201
- }
1202
- catch (err) {
1203
- return { success: false, error: (_c = err.message) !== null && _c !== void 0 ? _c : String(err) };
1204
- }
1205
- }
1206
- }),
1207
- restart_deployment: (0, ai_1.tool)({
1208
- description: 'Rollout-restarts a deployment (equivalent to `kubectl rollout restart`): recreates its pods gracefully, respecting the rolling-update strategy, by stamping the kubectl.kubernetes.io/restartedAt annotation on the pod template. Restarts a workload WITHOUT changing its spec — recover stuck/crashing pods or pick up a changed ConfigMap/Secret. Preferred over delete_pod for a whole workload.',
1209
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().describe('Namespace of the deployment'), name: zod_1.z.string().describe('Name of the deployment') }),
1210
- execute: async ({ namespace, name }) => {
1211
- var _a, _b, _c, _d, _e;
1212
- ctx().trace('restart_deployment', { namespace, name });
1213
- try {
1214
- const c = ctx().clusterInfo;
1215
- const d = await c.appsApi.readNamespacedDeployment({ name, namespace });
1216
- const restartedAt = new Date().toISOString();
1217
- // Merge (not replace) the existing template annotations, then `add` the whole map: `add` on an
1218
- // existing path replaces it and on a missing path creates it, so it is safe whether or not the
1219
- // pod template already had annotations.
1220
- const annotations = Object.assign(Object.assign({}, ((_d = (_c = (_b = (_a = d.spec) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.metadata) === null || _c === void 0 ? void 0 : _c.annotations) !== null && _d !== void 0 ? _d : {})), { 'kubectl.kubernetes.io/restartedAt': restartedAt });
1221
- await c.appsApi.patchNamespacedDeployment({ name, namespace, body: [{ op: 'add', path: '/spec/template/metadata/annotations', value: annotations }] });
1222
- return { success: true, message: `Deployment ${namespace}/${name} rollout-restarted at ${restartedAt}` };
1223
- }
1224
- catch (err) {
1225
- return { success: false, error: (_e = err.message) !== null && _e !== void 0 ? _e : String(err) };
1226
- }
1227
- }
1228
- }),
1229
- delete_pod: (0, ai_1.tool)({
1230
- description: 'Deletes a single pod (equivalent to `kubectl delete pod`). Its controller (Deployment/StatefulSet/DaemonSet) recreates it — a surgical way to restart ONE stuck or misbehaving pod. Does not respect a rolling update; for a whole workload prefer restart_deployment.',
1231
- inputSchema: zod_1.z.object({ namespace: zod_1.z.string().describe('Namespace of the pod'), name: zod_1.z.string().describe('Name of the pod') }),
1232
- execute: async ({ namespace, name }) => {
1233
- var _a;
1234
- ctx().trace('delete_pod', { namespace, name });
1235
- try {
1236
- await ctx().clusterInfo.coreApi.deleteNamespacedPod({ name, namespace });
1237
- return { success: true, message: `Pod ${namespace}/${name} deleted; its controller will recreate it` };
1238
- }
1239
- catch (err) {
1240
- return { success: false, error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
1241
- }
1242
- }
1243
- }),
1244
- // ── MISC ─────────────────────────────────────────────────────────────────
1245
- times_two: (0, ai_1.tool)({
1246
- description: 'Multiplies a number by two.',
1247
- inputSchema: zod_1.z.object({ data: zod_1.z.number() }),
1248
- execute: async ({ data }) => { ctx().trace('times_two', { data }); return data * 2; }
1249
- }),
1250
- father_of: (0, ai_1.tool)({
1251
- description: 'Returns the name of the father of a person.',
1252
- inputSchema: zod_1.z.object({ data: zod_1.z.string().describe('The name of the person whose father you want to discover') }),
1253
- execute: async ({ data }) => { ctx().trace('father_of', { data }); return 'Julio'; }
1254
- }),
1255
- get_certificate_info: (0, ai_1.tool)({
1256
- description: 'Connects to a hostname via HTTPS and returns TLS certificate details: subject, issuer, validity dates, SANs, fingerprint and whether it is currently valid.',
1257
- inputSchema: zod_1.z.object({ hostname: zod_1.z.string().describe('DNS name or IP to connect to'), port: zod_1.z.number().optional().describe('Port to connect to (default: 443)') }),
1258
- execute: async ({ hostname, port }) => {
1259
- ctx().trace('get_certificate_info', { hostname, port });
1260
- const targetPort = port !== null && port !== void 0 ? port : 443;
1261
- return new Promise((resolve) => {
1262
- const socket = tls.connect({ host: hostname, port: targetPort, servername: hostname, rejectUnauthorized: false }, () => {
1263
- var _a, _b;
1264
- try {
1265
- const cert = socket.getPeerCertificate(false);
1266
- socket.end();
1267
- if (!cert || !Object.keys(cert).length)
1268
- return resolve({ error: 'No certificate returned' });
1269
- const now = Date.now();
1270
- const validFrom = new Date(cert.valid_from);
1271
- const validTo = new Date(cert.valid_to);
1272
- resolve({ subject: cert.subject, issuer: cert.issuer, validFrom: cert.valid_from, validTo: cert.valid_to, daysUntilExpiry: Math.floor((validTo.getTime() - now) / 86400000), isCurrentlyValid: now >= validFrom.getTime() && now <= validTo.getTime(), subjectAltNames: (_a = cert.subjectaltname) !== null && _a !== void 0 ? _a : null, fingerprint: cert.fingerprint, serialNumber: cert.serialNumber, protocol: socket.getProtocol() });
1273
- }
1274
- catch (err) {
1275
- socket.end();
1276
- resolve({ error: (_b = err.message) !== null && _b !== void 0 ? _b : String(err) });
1277
- }
1278
- });
1279
- socket.setTimeout(5000, () => { socket.destroy(); resolve({ error: 'Connection timed out' }); });
1280
- socket.on('error', (err) => resolve({ error: err.message }));
1281
- });
1282
- }
1283
- }),
1284
- // ── EVENTS (from the cluster events buffer in ctx().clusterEvents) ──────────
1285
- get_cluster_events: (0, ai_1.tool)({
1286
- description: 'Returns recent Kubernetes events buffered for this cluster: kube Events (warnings like crashloops/OOM/failed scheduling) and object lifecycle changes. Optionally filter to warnings only or by namespace.',
1287
- inputSchema: zod_1.z.object({
1288
- warningsOnly: zod_1.z.boolean().optional().describe('Only Warning-type kube Events'),
1289
- namespace: zod_1.z.string().optional().describe('Filter by namespace'),
1290
- limit: zod_1.z.number().optional().describe('Max events to return (default 50)')
1291
- }),
1292
- execute: async ({ warningsOnly, namespace, limit = 50 }) => {
1293
- var _a;
1294
- ctx().trace('get_cluster_events', { warningsOnly: !!warningsOnly, namespace: namespace !== null && namespace !== void 0 ? namespace : '*', limit });
1295
- let evs = (_a = ctx().clusterEvents) !== null && _a !== void 0 ? _a : [];
1296
- if (warningsOnly)
1297
- evs = evs.filter(e => { var _a; return ((_a = e === null || e === void 0 ? void 0 : e.obj) === null || _a === void 0 ? void 0 : _a.kind) === 'Event' && e.obj.type === 'Warning'; });
1298
- if (namespace)
1299
- evs = evs.filter(e => { var _a, _b, _c, _d, _e; return ((_c = (_b = (_a = e === null || e === void 0 ? void 0 : e.obj) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.namespace) !== null && _c !== void 0 ? _c : (_e = (_d = e === null || e === void 0 ? void 0 : e.obj) === null || _d === void 0 ? void 0 : _d.involvedObject) === null || _e === void 0 ? void 0 : _e.namespace) === namespace; });
1300
- return { count: evs.length, events: evs.slice(-limit).map(summarizeClusterEvent) };
1301
- }
1302
- }),
1303
- get_object_events: (0, ai_1.tool)({
1304
- description: 'Returns recent events for a specific Kubernetes object (by namespace and name): its lifecycle changes and related kube Events (via involvedObject).',
1305
- inputSchema: zod_1.z.object({
1306
- namespace: zod_1.z.string().describe('Namespace of the object'),
1307
- name: zod_1.z.string().describe('Name of the object')
1308
- }),
1309
- execute: async ({ namespace, name }) => {
1310
- var _a;
1311
- ctx().trace('get_object_events', { namespace, name });
1312
- const evs = ((_a = ctx().clusterEvents) !== null && _a !== void 0 ? _a : []).filter(e => {
1313
- var _a, _b, _c, _d, _e;
1314
- const o = (_a = e === null || e === void 0 ? void 0 : e.obj) !== null && _a !== void 0 ? _a : {};
1315
- const isObj = ((_b = o.metadata) === null || _b === void 0 ? void 0 : _b.namespace) === namespace && ((_c = o.metadata) === null || _c === void 0 ? void 0 : _c.name) === name;
1316
- const isInvolved = ((_d = o.involvedObject) === null || _d === void 0 ? void 0 : _d.namespace) === namespace && ((_e = o.involvedObject) === null || _e === void 0 ? void 0 : _e.name) === name;
1317
- return isObj || isInvolved;
1318
- });
1319
- return { count: evs.length, events: evs.map(summarizeClusterEvent) };
1320
- }
1321
- }),
1322
- // ── POD DIAGNOSIS ────────────────────────────────────────────────────────
1323
- get_pod_logs: (0, ai_1.tool)({
1324
- description: 'Returns recent container logs for a pod (equivalent to kubectl logs). For a crashing pod (CrashLoopBackOff) pass previous:true to read the CRASHED container instance logs — that is where the root cause usually is (the events only say it is restarting, not why).',
1325
- inputSchema: zod_1.z.object({
1326
- namespace: zod_1.z.string().describe('Namespace of the pod'),
1327
- name: zod_1.z.string().describe('Name of the pod'),
1328
- container: zod_1.z.string().optional().describe('Container name (omit to use the pod default / first container)'),
1329
- previous: zod_1.z.boolean().optional().describe('Read the previous (crashed/restarted) container instance logs — key for CrashLoopBackOff'),
1330
- tailLines: zod_1.z.number().optional().describe('How many trailing lines to return (default 200)')
1331
- }),
1332
- execute: async ({ namespace, name, container, previous, tailLines = 200 }) => {
1333
- var _a, _b;
1334
- ctx().trace('get_pod_logs', { namespace, name, container: container !== null && container !== void 0 ? container : '(default)', previous: !!previous, tailLines });
1335
- try {
1336
- const raw = await ctx().clusterInfo.coreApi.readNamespacedPodLog({ name, namespace, container, previous: !!previous, tailLines });
1337
- const text = typeof raw === 'string' ? raw : ((_a = raw === null || raw === void 0 ? void 0 : raw.body) !== null && _a !== void 0 ? _a : JSON.stringify(raw));
1338
- const truncated = text.length > 15000;
1339
- return { namespace, name, container: container !== null && container !== void 0 ? container : null, previous: !!previous, truncated, logs: truncated ? text.slice(-15000) : text };
1340
- }
1341
- catch (err) {
1342
- return { error: (_b = err.message) !== null && _b !== void 0 ? _b : String(err) };
1343
- }
1344
- }
1345
- }),
1346
- describe_pod: (0, ai_1.tool)({
1347
- description: 'Returns a diagnostic summary of a pod (equivalent to kubectl describe pod): phase, conditions, and per-container status — waiting reason (CrashLoopBackOff/ImagePullBackOff…), last termination reason + exitCode (137=OOMKilled, 1=app error, 143=SIGTERM), restart count, image, resources and probes. Best first step to categorize a pod failure.',
1348
- inputSchema: zod_1.z.object({
1349
- namespace: zod_1.z.string().describe('Namespace of the pod'),
1350
- name: zod_1.z.string().describe('Name of the pod')
1351
- }),
1352
- execute: async ({ namespace, name }) => {
1353
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p, _q, _r;
1354
- ctx().trace('describe_pod', { namespace, name });
1355
- try {
1356
- const c = ctx().clusterInfo;
1357
- const pod = await c.coreApi.readNamespacedPod({ name, namespace });
1358
- const spec = (_a = pod.spec) !== null && _a !== void 0 ? _a : {}, status = (_b = pod.status) !== null && _b !== void 0 ? _b : {};
1359
- // image = the tag (spec); imageID = the resolved digest (catches a mutable tag repushed with a broken build).
1360
- const containerStatus = (cs) => {
1361
- var _a, _b, _c, _d;
1362
- return ({
1363
- name: cs.name, image: cs.image, imageID: cs.imageID, ready: cs.ready, restartCount: cs.restartCount,
1364
- state: ((_a = cs.state) === null || _a === void 0 ? void 0 : _a.waiting) ? { waiting: { reason: cs.state.waiting.reason, message: cs.state.waiting.message } }
1365
- : ((_b = cs.state) === null || _b === void 0 ? void 0 : _b.terminated) ? { terminated: { reason: cs.state.terminated.reason, exitCode: cs.state.terminated.exitCode } }
1366
- : ((_c = cs.state) === null || _c === void 0 ? void 0 : _c.running) ? { running: { startedAt: cs.state.running.startedAt } } : cs.state,
1367
- lastTerminated: ((_d = cs.lastState) === null || _d === void 0 ? void 0 : _d.terminated) ? { reason: cs.lastState.terminated.reason, exitCode: cs.lastState.terminated.exitCode, signal: cs.lastState.terminated.signal, finishedAt: cs.lastState.terminated.finishedAt } : undefined
1368
- });
1369
- };
1370
- const specContainer = (ct) => ({ name: ct.name, image: ct.image, resources: ct.resources, livenessProbe: !!ct.livenessProbe, readinessProbe: !!ct.readinessProbe, startupProbe: !!ct.startupProbe });
1371
- // Resolve the owning controller (pod → ReplicaSet → Deployment) so the bot can call get_rollout_history directly.
1372
- let controlledBy = undefined;
1373
- const podOwner = ((_d = (_c = pod.metadata) === null || _c === void 0 ? void 0 : _c.ownerReferences) !== null && _d !== void 0 ? _d : [])[0];
1374
- if ((podOwner === null || podOwner === void 0 ? void 0 : podOwner.kind) === 'ReplicaSet') {
1375
- try {
1376
- const rs = await c.appsApi.readNamespacedReplicaSet({ name: podOwner.name, namespace });
1377
- const rsOwner = ((_f = (_e = rs.metadata) === null || _e === void 0 ? void 0 : _e.ownerReferences) !== null && _f !== void 0 ? _f : [])[0];
1378
- controlledBy = rsOwner ? { kind: rsOwner.kind, name: rsOwner.name } : { kind: 'ReplicaSet', name: podOwner.name };
1379
- }
1380
- catch (_s) {
1381
- controlledBy = { kind: 'ReplicaSet', name: podOwner.name };
1382
- }
1383
- }
1384
- else if (podOwner) {
1385
- controlledBy = { kind: podOwner.kind, name: podOwner.name }; // StatefulSet/DaemonSet/Job own pods directly
1386
- }
1387
- // Source provenance: OCI standard annotations (org.opencontainers.image.*) with a kwirth.io fallback →
1388
- // the repo + commit the image was built from, so the bot can read the actual source (get_source_file).
1389
- const ann = (_h = (_g = pod.metadata) === null || _g === void 0 ? void 0 : _g.annotations) !== null && _h !== void 0 ? _h : {};
1390
- const sourceRepo = (_j = ann['org.opencontainers.image.source']) !== null && _j !== void 0 ? _j : ann['kwirth.io/source-repo'];
1391
- const source = sourceRepo ? { repo: sourceRepo, revision: (_l = ann['org.opencontainers.image.revision']) !== null && _l !== void 0 ? _l : ann['kwirth.io/source-ref'] } : undefined;
1392
- return {
1393
- name, namespace, phase: status.phase, node: spec.nodeName, startTime: status.startTime, reason: status.reason, message: status.message,
1394
- controlledBy, // e.g. { kind: 'Deployment', name: 'montag-agent' } → feed to get_rollout_history
1395
- source, // { repo, revision } from image annotations → feed to get_source_file
1396
- conditions: ((_m = status.conditions) !== null && _m !== void 0 ? _m : []).map((c) => ({ type: c.type, status: c.status, reason: c.reason })),
1397
- containers: ((_o = status.containerStatuses) !== null && _o !== void 0 ? _o : []).map(containerStatus),
1398
- initContainers: ((_p = status.initContainerStatuses) !== null && _p !== void 0 ? _p : []).map(containerStatus),
1399
- spec: { containers: ((_q = spec.containers) !== null && _q !== void 0 ? _q : []).map(specContainer), restartPolicy: spec.restartPolicy }
1400
- };
1401
- }
1402
- catch (err) {
1403
- return { error: (_r = err.message) !== null && _r !== void 0 ? _r : String(err) };
1404
- }
1405
- }
1406
- }),
1407
- get_pod_yaml: (0, ai_1.tool)({
1408
- description: 'Returns the full Kubernetes Pod manifest (equivalent to kubectl get pod -o yaml): complete spec (env, volumes, resources, probes) and status. Use for deeper misconfiguration analysis after describe_pod.',
1409
- inputSchema: zod_1.z.object({
1410
- namespace: zod_1.z.string().describe('Namespace of the pod'),
1411
- name: zod_1.z.string().describe('Name of the pod')
1412
- }),
1413
- execute: async ({ namespace, name }) => {
1414
- var _a;
1415
- ctx().trace('get_pod_yaml', { namespace, name });
1416
- try {
1417
- return await ctx().clusterInfo.coreApi.readNamespacedPod({ name, namespace });
1418
- }
1419
- catch (err) {
1420
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
1421
- }
1422
- }
1423
- }),
1424
- get_deployment_yaml: (0, ai_1.tool)({
1425
- description: 'Returns the full Kubernetes Deployment manifest (equivalent to kubectl get deployment -o yaml): the pod template (image, env, resources, probes) and strategy. Use to check if a pod problem comes from the owning workload spec.',
1426
- inputSchema: zod_1.z.object({
1427
- namespace: zod_1.z.string().describe('Namespace of the deployment'),
1428
- name: zod_1.z.string().describe('Name of the deployment')
1429
- }),
1430
- execute: async ({ namespace, name }) => {
1431
- var _a;
1432
- ctx().trace('get_deployment_yaml', { namespace, name });
1433
- try {
1434
- return await ctx().clusterInfo.appsApi.readNamespacedDeployment({ name, namespace });
1435
- }
1436
- catch (err) {
1437
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
1438
- }
1439
- }
1440
- }),
1441
- get_controller_yaml: (0, ai_1.tool)({
1442
- description: 'Returns the full manifest of a workload controller (equivalent to kubectl get <kind> -o yaml), for ANY kind — Deployment, StatefulSet, DaemonSet or ReplicaSet. Complete metadata (uid, labels, annotations), spec (pod template, strategy) and status. Use when you need a specific field the describe summary doesn\'t include.',
1443
- inputSchema: zod_1.z.object({
1444
- namespace: zod_1.z.string().describe('Namespace of the controller'),
1445
- kind: zod_1.z.enum(['Deployment', 'StatefulSet', 'DaemonSet', 'ReplicaSet']).describe('Controller kind'),
1446
- name: zod_1.z.string().describe('Name of the controller')
1447
- }),
1448
- execute: async ({ namespace, kind, name }) => {
1449
- var _a;
1450
- ctx().trace('get_controller_yaml', { namespace, kind, name });
1451
- try {
1452
- const a = ctx().clusterInfo.appsApi;
1453
- return kind === 'StatefulSet' ? await a.readNamespacedStatefulSet({ name, namespace })
1454
- : kind === 'DaemonSet' ? await a.readNamespacedDaemonSet({ name, namespace })
1455
- : kind === 'ReplicaSet' ? await a.readNamespacedReplicaSet({ name, namespace })
1456
- : await a.readNamespacedDeployment({ name, namespace });
1457
- }
1458
- catch (err) {
1459
- return { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) };
1460
- }
1461
- }
1462
- }),
1463
- get_rollout_history: (0, ai_1.tool)({
1464
- description: 'Returns the rollout history (revisions) of a Deployment via its ReplicaSets: per revision the image(s), replicas and pod-template summary (env with inline VALUES and their configMap/secret source, resources, command). Use to see WHAT CHANGED recently — a new image tag, a changed inline env value, a resource/command change — that may have broken the pods. Compare the newest revision against the previous one. NOTE: a change to a ConfigMap/Secret VALUE does NOT create a revision — use get_workload_config_refs for that.',
1465
- inputSchema: zod_1.z.object({
1466
- namespace: zod_1.z.string().describe('Namespace of the deployment'),
1467
- name: zod_1.z.string().describe('Name of the Deployment (the owning workload, e.g. describe_pod.controlledBy.name — NOT the pod name)')
1468
- }),
1469
- execute: async ({ namespace, name }) => {
1470
- var _a, _b;
1471
- ctx().trace('get_rollout_history', { namespace, name });
1472
- try {
1473
- const rsList = await ctx().clusterInfo.appsApi.listNamespacedReplicaSet({ namespace });
1474
- const owned = ((_a = rsList.items) !== null && _a !== void 0 ? _a : []).filter((rs) => { var _a, _b; return ((_b = (_a = rs.metadata) === null || _a === void 0 ? void 0 : _a.ownerReferences) !== null && _b !== void 0 ? _b : []).some((o) => o.kind === 'Deployment' && o.name === name); });
1475
- // env: inline value + where a valueFrom env is sourced (so the LLM can both diff inline values
1476
- // across revisions AND know which vars come from a ConfigMap/Secret to check separately).
1477
- const envSource = (e) => {
1478
- var _a, _b, _c;
1479
- return ((_a = e.valueFrom) === null || _a === void 0 ? void 0 : _a.configMapKeyRef) ? `configMap:${e.valueFrom.configMapKeyRef.name}/${e.valueFrom.configMapKeyRef.key}`
1480
- : ((_b = e.valueFrom) === null || _b === void 0 ? void 0 : _b.secretKeyRef) ? `secret:${e.valueFrom.secretKeyRef.name}/${e.valueFrom.secretKeyRef.key}`
1481
- : ((_c = e.valueFrom) === null || _c === void 0 ? void 0 : _c.fieldRef) ? `field:${e.valueFrom.fieldRef.fieldPath}`
1482
- : undefined;
1483
- };
1484
- const container = (ct) => { var _a; return ({ name: ct.name, image: ct.image, command: ct.command, args: ct.args, resources: ct.resources, env: ((_a = ct.env) !== null && _a !== void 0 ? _a : []).map((e) => ({ name: e.name, value: e.value, from: envSource(e) })) }); };
1485
- const revisions = owned.map((rs) => {
1486
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p;
1487
- const tmpl = (_c = (_b = (_a = rs.spec) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.spec) !== null && _c !== void 0 ? _c : {};
1488
- return {
1489
- revision: Number((_f = (_e = (_d = rs.metadata) === null || _d === void 0 ? void 0 : _d.annotations) === null || _e === void 0 ? void 0 : _e['deployment.kubernetes.io/revision']) !== null && _f !== void 0 ? _f : 0),
1490
- replicaSet: (_g = rs.metadata) === null || _g === void 0 ? void 0 : _g.name,
1491
- createdAt: (_h = rs.metadata) === null || _h === void 0 ? void 0 : _h.creationTimestamp,
1492
- replicas: (_l = (_j = rs.spec) === null || _j === void 0 ? void 0 : _j.replicas) !== null && _l !== void 0 ? _l : 0,
1493
- readyReplicas: (_o = (_m = rs.status) === null || _m === void 0 ? void 0 : _m.readyReplicas) !== null && _o !== void 0 ? _o : 0,
1494
- containers: ((_p = tmpl.containers) !== null && _p !== void 0 ? _p : []).map(container),
1495
- serviceAccount: tmpl.serviceAccountName,
1496
- securityContext: tmpl.securityContext
1497
- };
1498
- }).sort((a, b) => b.revision - a.revision); // newest first
1499
- return { deployment: name, namespace, revisionCount: revisions.length, revisions };
1500
- }
1501
- catch (err) {
1502
- return { error: (_b = err.message) !== null && _b !== void 0 ? _b : String(err) };
1503
- }
1504
- }
1505
- }),
1506
- get_configmap: (0, ai_1.tool)({
1507
- description: 'Returns a ConfigMap\'s data (key → value) plus metadata (resourceVersion, lastModified). Use to inspect the ACTUAL config a workload consumes and to check whether it changed recently — a ConfigMap value change (same env var, different value) does NOT create a Deployment revision, so it is invisible to get_rollout_history.',
1508
- inputSchema: zod_1.z.object({
1509
- namespace: zod_1.z.string().describe('Namespace of the ConfigMap'),
1510
- name: zod_1.z.string().describe('Name of the ConfigMap')
1511
- }),
1512
- execute: async ({ namespace, name }) => {
1513
- var _a, _b, _c, _d;
1514
- ctx().trace('get_configmap', { namespace, name });
1515
- try {
1516
- const cm = await ctx().clusterInfo.coreApi.readNamespacedConfigMap({ name, namespace });
1517
- return { name, namespace, resourceVersion: (_a = cm.metadata) === null || _a === void 0 ? void 0 : _a.resourceVersion, lastModified: lastModifiedOf(cm.metadata), data: (_b = cm.data) !== null && _b !== void 0 ? _b : {}, binaryDataKeys: Object.keys((_c = cm.binaryData) !== null && _c !== void 0 ? _c : {}) };
1518
- }
1519
- catch (err) {
1520
- return { error: (_d = err.message) !== null && _d !== void 0 ? _d : String(err) };
1521
- }
1522
- }
1523
- }),
1524
- get_secret: (0, ai_1.tool)({
1525
- description: 'Returns a Secret\'s KEYS, type and metadata (resourceVersion, lastModified) — VALUES ARE REDACTED (never returned). Use to check whether a Secret a workload consumes changed recently (a value change does NOT create a Deployment revision) and which keys it holds. You cannot read the secret values.',
1526
- inputSchema: zod_1.z.object({
1527
- namespace: zod_1.z.string().describe('Namespace of the Secret'),
1528
- name: zod_1.z.string().describe('Name of the Secret')
1529
- }),
1530
- execute: async ({ namespace, name }) => {
1531
- var _a, _b, _c;
1532
- ctx().trace('get_secret', { namespace, name });
1533
- try {
1534
- const s = await ctx().clusterInfo.coreApi.readNamespacedSecret({ name, namespace });
1535
- return { name, namespace, type: s.type, resourceVersion: (_a = s.metadata) === null || _a === void 0 ? void 0 : _a.resourceVersion, lastModified: lastModifiedOf(s.metadata), keys: Object.keys((_b = s.data) !== null && _b !== void 0 ? _b : {}) }; // values intentionally omitted
1536
- }
1537
- catch (err) {
1538
- return { error: (_c = err.message) !== null && _c !== void 0 ? _c : String(err) };
1539
- }
1540
- }
1541
- }),
1542
- get_workload_config_refs: (0, ai_1.tool)({
1543
- description: 'Given a Deployment, lists the ConfigMaps and Secrets its pods consume (via envFrom, env valueFrom, and volumes), each with its lastModified time and resourceVersion. Use on a crash to find a config source that CHANGED WITHOUT A ROLLOUT: editing a ConfigMap/Secret value keeps the same env spec (no new revision) yet can break the pod — compare each ref\'s lastModified against when the pods started crashing, then read the changed one with get_configmap / get_secret.',
1544
- inputSchema: zod_1.z.object({
1545
- namespace: zod_1.z.string().describe('Namespace of the deployment'),
1546
- name: zod_1.z.string().describe('Name of the Deployment (e.g. describe_pod.controlledBy.name)')
1547
- }),
1548
- execute: async ({ namespace, name }) => {
1549
- var _a, _b, _c, _d;
1550
- ctx().trace('get_workload_config_refs', { namespace, name });
1551
- try {
1552
- const c = ctx().clusterInfo;
1553
- const dep = await c.appsApi.readNamespacedDeployment({ name, namespace });
1554
- // dedupe by kind+name, merging the reasons (an object may be referenced several ways)
1555
- const byKey = new Map();
1556
- for (const r of configRefsOfPodSpec((_b = (_a = dep.spec) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.spec)) {
1557
- const cur = (_c = byKey.get(`${r.kind}/${r.name}`)) !== null && _c !== void 0 ? _c : { kind: r.kind, name: r.name, via: [] };
1558
- if (!cur.via.includes(r.via))
1559
- cur.via.push(r.via);
1560
- byKey.set(`${r.kind}/${r.name}`, cur);
1561
- }
1562
- const refs = await Promise.all([...byKey.values()].map(async (r) => {
1563
- var _a;
1564
- try {
1565
- const meta = (r.kind === 'ConfigMap'
1566
- ? await c.coreApi.readNamespacedConfigMap({ name: r.name, namespace })
1567
- : await c.coreApi.readNamespacedSecret({ name: r.name, namespace })).metadata;
1568
- return Object.assign(Object.assign({}, r), { resourceVersion: meta === null || meta === void 0 ? void 0 : meta.resourceVersion, lastModified: lastModifiedOf(meta) });
1569
- }
1570
- catch (err) {
1571
- return Object.assign(Object.assign({}, r), { error: (_a = err.message) !== null && _a !== void 0 ? _a : String(err) });
1572
- }
1573
- }));
1574
- return { deployment: name, namespace, refs };
1575
- }
1576
- catch (err) {
1577
- return { error: (_d = err.message) !== null && _d !== void 0 ? _d : String(err) };
1578
- }
1579
- }
1580
- }),
1581
- get_source_file: (0, ai_1.tool)({
1582
- description: 'Fetches the contents of a single source file from a Git repository (GitHub or GitLab) at a specific ref. Use to inspect the actual source behind a crash: read the stack-trace file:line from the logs, then fetch that file at the image build revision (describe_pod.source). Call repeatedly to follow the trace across files until you find the bug.',
1583
- inputSchema: zod_1.z.object({
1584
- repo: zod_1.z.string().describe('Repository URL or owner/name (e.g. https://github.com/org/app or org/app) — from describe_pod.source.repo'),
1585
- ref: zod_1.z.string().describe('Commit SHA, branch or tag — use the build revision (describe_pod.source.revision) so you read the code actually running'),
1586
- path: zod_1.z.string().describe('File path within the repo (e.g. src/regex/loader.go)')
1587
- }),
1588
- execute: async ({ repo, ref, path }) => {
1589
- var _a, _b;
1590
- ctx().trace('get_source_file', { repo, ref, path });
1591
- try {
1592
- const { host, projectPath } = parseRepoRef(repo);
1593
- const cred = ((_a = ctx().sourceRepos) !== null && _a !== void 0 ? _a : []).find(r => r.host === host);
1594
- if (!cred)
1595
- return { error: `No source-repo credentials configured for host '${host}'. Add it in Agora → Source repos.` };
1596
- const text = await fetchSourceFile(cred, projectPath, ref, path);
1597
- const truncated = text.length > 20000;
1598
- return { repo: projectPath, ref, path, truncated, content: truncated ? text.slice(0, 20000) : text };
1599
- }
1600
- catch (err) {
1601
- return { error: (_b = err.message) !== null && _b !== void 0 ? _b : String(err) };
1602
- }
1603
- }
1604
- }),
1605
- };
1606
- exports.toolInfoList = [
1607
- { name: 'list_namespaces', effect: index_1.EToolEffect.READ, description: 'Lists all namespaces in the cluster with their status and labels.' },
1608
- { name: 'get_node_data', effect: index_1.EToolEffect.READ, description: 'Returns configuration info about all Kubernetes nodes (name, IP). Configuration only — not workload or usage data.' },
1609
- { name: 'get_cluster_data', effect: index_1.EToolEffect.READ, description: 'Returns general cluster info: name, flavour (AKS/EKS/GKE/k3s/k3d), total vCPUs, total memory, node count and readiness status.' },
1610
- { name: 'get_workload_data', effect: index_1.EToolEffect.READ, description: 'Returns all workloads in the cluster: deployments, statefulsets, daemonsets, pods and services. Optionally filter by namespace.' },
1611
- { name: 'get_space_data', effect: index_1.EToolEffect.READ, description: 'Describes a namespace (kubectl describe namespace + rollup): status/labels, ResourceQuota (used vs hard), LimitRange, plus its pods (restart count), deployments, services and configmaps.' },
1612
- { name: 'get_namespace_yaml', effect: index_1.EToolEffect.READ, description: 'Full Namespace manifest (kubectl get namespace -o yaml): complete metadata (uid, labels, annotations, creationTimestamp), spec and status — for any field the summary omits (e.g. its uid).' },
1613
- { name: 'get_service_yaml', effect: index_1.EToolEffect.READ, description: 'Returns the full Kubernetes Service manifest (equivalent to kubectl get service -o yaml) for a given namespace and service name.' },
1614
- { name: 'describe_service', effect: index_1.EToolEffect.READ, description: 'Diagnostic summary of a Service (kubectl describe service): type/clusterIP/ports/selector + its live Endpoints (the pod IPs backing it, ready vs not) — see why traffic isn\'t reaching pods.' },
1615
- { name: 'list_services', effect: index_1.EToolEffect.READ, description: 'Lists all Services in the cluster with full details (type, clusterIP, ports, selector). Optionally filter by namespace.' },
1616
- { name: 'list_ingresses', effect: index_1.EToolEffect.READ, description: 'Lists all Ingresses in the cluster (hosts, paths, TLS, backend services). Optionally filter by namespace.' },
1617
- { name: 'get_ingress_yaml', effect: index_1.EToolEffect.READ, description: 'Returns the full Kubernetes Ingress manifest (equivalent to kubectl get ingress -o yaml) for a given namespace and ingress name.' },
1618
- { name: 'describe_ingress', effect: index_1.EToolEffect.READ, description: 'Diagnostic summary of an Ingress (kubectl describe ingress): ingressClass, rules (host → path → backend service:port), default backend, TLS, and the load-balancer address.' },
1619
- { name: 'get_cluster_usage', effect: index_1.EToolEffect.READ, description: 'Returns current overall cluster resource usage: CPU%, memory%, network Mbps, total vCPUs and total memory GB.' },
1620
- { name: 'get_node_usage', effect: index_1.EToolEffect.READ, description: 'Returns current CPU and memory usage for one node or all nodes from the latest metrics reading.' },
1621
- { name: 'get_deployment_usage', effect: index_1.EToolEffect.READ, description: 'Returns current aggregated CPU and memory usage for all pods belonging to a specific deployment.' },
1622
- { name: 'get_prev_cluster_usage', effect: index_1.EToolEffect.READ, description: 'Returns historical overall cluster usage over the last N metrics readings (CPU%, memory%, network Mbps).' },
1623
- { name: 'get_prev_node_usage', effect: index_1.EToolEffect.READ, description: 'Returns historical CPU and memory usage for one or all nodes over the last N metrics readings.' },
1624
- { name: 'get_prev_deployment_usage', effect: index_1.EToolEffect.READ, description: 'Returns historical aggregated CPU and memory usage for a deployment over the last N metrics readings.' },
1625
- { name: 'get_prev_space_data', effect: index_1.EToolEffect.READ, description: 'Returns historical aggregated CPU and memory usage for all pods in a namespace over the last N metrics readings.' },
1626
- { name: 'add_node', effect: index_1.EToolEffect.WRITE, description: 'Adds a new agent node to the cluster. For k3d uses `k3d node create`. Cloud providers not yet implemented.' },
1627
- { name: 'remove_node', effect: index_1.EToolEffect.WRITE, description: 'Removes a node from the cluster (cordon + delete). For k3d uses `k3d node delete`. Cloud providers not yet implemented.' },
1628
- { name: 'stop_node', effect: index_1.EToolEffect.WRITE, description: 'Stops a running cluster node: cordons it then stops the container. For k3d uses `k3d node stop`.' },
1629
- { name: 'start_node', effect: index_1.EToolEffect.WRITE, description: 'Starts a previously stopped cluster node and uncordons it. For k3d uses `k3d node start`.' },
1630
- { name: 'add_replica', effect: index_1.EToolEffect.WRITE, description: 'Scales up a deployment by adding one replica.' },
1631
- { name: 'remove_replica', effect: index_1.EToolEffect.WRITE, description: 'Scales down a deployment by removing one replica. Minimum of 1 replica is enforced.' },
1632
- { name: 'restart_deployment', effect: index_1.EToolEffect.WRITE, description: 'Rollout-restarts a deployment (recreates its pods gracefully via the restartedAt annotation, respecting the rolling update) — restart a workload without changing its spec.' },
1633
- { name: 'delete_pod', effect: index_1.EToolEffect.WRITE, description: 'Deletes a single pod; its controller recreates it. Surgical restart of one stuck pod (no rolling update — prefer restart_deployment for a whole workload).' },
1634
- { name: 'times_two', effect: index_1.EToolEffect.READ, description: 'Multiplies a number by two.' },
1635
- { name: 'father_of', effect: index_1.EToolEffect.READ, description: 'Returns the name of the father of a person.' },
1636
- { name: 'get_certificate_info', effect: index_1.EToolEffect.READ, description: 'Connects to a hostname via HTTPS and returns TLS certificate details: subject, issuer, validity dates, SANs, fingerprint and whether it is currently valid.' },
1637
- { name: 'get_cluster_events', effect: index_1.EToolEffect.READ, description: 'Returns recent buffered Kubernetes events for this cluster (warnings + object lifecycle changes); filter by warnings only or namespace.' },
1638
- { name: 'get_object_events', effect: index_1.EToolEffect.READ, description: 'Returns recent events for a specific Kubernetes object (namespace + name), including related kube Events.' },
1639
- { name: 'get_pod_logs', effect: index_1.EToolEffect.READ, description: 'Returns container logs for a pod (kubectl logs); previous:true reads the crashed instance logs — the root cause of a CrashLoopBackOff.' },
1640
- { name: 'describe_pod', effect: index_1.EToolEffect.READ, description: 'Diagnostic summary of a pod (kubectl describe pod): per-container waiting/terminated reason + exitCode (OOMKilled/CrashLoop…), restart count, probes.' },
1641
- { name: 'get_pod_yaml', effect: index_1.EToolEffect.READ, description: 'Full Pod manifest (kubectl get pod -o yaml): spec (env, volumes, resources, probes) and status.' },
1642
- { name: 'get_deployment_yaml', effect: index_1.EToolEffect.READ, description: 'Full Deployment manifest (kubectl get deployment -o yaml): pod template (image, env, resources, probes) and strategy.' },
1643
- { name: 'describe_controller', effect: index_1.EToolEffect.READ, description: 'Diagnostic summary of a workload controller (kubectl describe deployment/statefulset/daemonset/replicaset): replica counts (desired/ready/available/updated), strategy, conditions (why not rolled out), selector, pod template. Parametrised by kind.' },
1644
- { name: 'get_controller_yaml', effect: index_1.EToolEffect.READ, description: 'Full manifest of any workload controller (kubectl get <kind> -o yaml): Deployment/StatefulSet/DaemonSet/ReplicaSet — complete metadata (uid, annotations), spec and status. Parametrised by kind, for any field the describe omits.' },
1645
- { name: 'get_rollout_history', effect: index_1.EToolEffect.READ, description: 'Rollout revisions of a Deployment (via ReplicaSets): image + template per revision (env with inline values + configMap/secret source), to see what changed (new image/env/resource) that may have broken the pods.' },
1646
- { name: 'get_configmap', effect: index_1.EToolEffect.READ, description: 'A ConfigMap\'s data (key→value) + lastModified. A ConfigMap value change does NOT create a rollout revision, so check it for a crash with no deployment change.' },
1647
- { name: 'get_secret', effect: index_1.EToolEffect.READ, description: 'A Secret\'s keys + type + lastModified (VALUES REDACTED). Check whether a consumed Secret changed recently (no rollout revision is created by a value change).' },
1648
- { name: 'get_workload_config_refs', effect: index_1.EToolEffect.READ, description: 'The ConfigMaps/Secrets a Deployment consumes (envFrom/valueFrom/volumes) with each one\'s lastModified — find a config source that changed WITHOUT a rollout and broke the pods.' },
1649
- { name: 'get_source_file', effect: index_1.EToolEffect.READ, description: 'Fetches a file from a Git repo (GitHub/GitLab) at a ref — inspect the source behind a crash by following the stack trace to the offending file:line.' },
1650
- ];
1651
- // Resolves the tool names an agent may use: autoTools = full catalog, otherwise its own list
1652
- // (intersected with the catalog); readOnly filters out WRITE-effect tools. Pure (no LLM) → unit-testable.
1653
- const selectAgentToolNames = (agent) => {
1654
- const writeNames = new Set(exports.toolInfoList.filter(t => t.effect === index_1.EToolEffect.WRITE).map(t => t.name));
1655
- const catalogNames = exports.toolInfoList.map(t => t.name);
1656
- const wanted = agent.autoTools ? catalogNames : agent.tools.filter(n => catalogNames.includes(n));
1657
- return wanted.filter(n => !(agent.readOnly && writeNames.has(n)));
1658
- };
1659
- exports.selectAgentToolNames = selectAgentToolNames;
1660
- // Runs an IAgent: resolves its LLM, selects/filters its tools (readOnly drops WRITE-effect tools) and
1661
- // invokes the model within the k8s tool context. Wraps the existing engine (buildModel + generateText +
1662
- // runWithToolContext) — factors the pattern pinocchio does by hand, reusable by Agora/pinocchio/defender.
1663
- // No providerOptions here: pinocchio's are for structured output; a chat/tool agent returns free text.
1664
- const runAgent = async (agent, prompt, llms, providers, context) => {
1665
- var _a, _b, _c, _d, _e, _f, _g, _h;
1666
- const llm = llms.find(l => l.id === agent.llm);
1667
- if (!llm)
1668
- throw new Error(`[common-ai] runAgent: llm '${agent.llm}' not found`);
1669
- const model = (0, exports.buildModel)(llm, providers);
1670
- if (!model)
1671
- throw new Error(`[common-ai] runAgent: could not build model for llm '${agent.llm}'`);
1672
- const allowed = new Set((0, exports.selectAgentToolNames)(agent));
1673
- const selectedTools = Object.fromEntries(Object.entries(exports.tools).filter(([n]) => allowed.has(n)));
1674
- const result = await (0, exports.runWithToolContext)(context, () => (0, ai_1.generateText)({
1675
- model,
1676
- temperature: llm.temperature,
1677
- stopWhen: (0, ai_1.stepCountIs)(agent.steps || 15),
1678
- tools: selectedTools,
1679
- system: agent.system,
1680
- prompt
1681
- }));
1682
- const toolCalls = [];
1683
- for (const step of ((_a = result.steps) !== null && _a !== void 0 ? _a : [])) {
1684
- const s = step;
1685
- for (const call of ((_b = s.toolCalls) !== null && _b !== void 0 ? _b : []))
1686
- toolCalls.push(call.toolName);
1687
- }
1688
- return {
1689
- text: result.text,
1690
- inputTokens: (_d = (_c = result.usage) === null || _c === void 0 ? void 0 : _c.inputTokens) !== null && _d !== void 0 ? _d : 0,
1691
- outputTokens: (_f = (_e = result.usage) === null || _e === void 0 ? void 0 : _e.outputTokens) !== null && _f !== void 0 ? _f : 0,
1692
- steps: (_h = (_g = result.steps) === null || _g === void 0 ? void 0 : _g.length) !== null && _h !== void 0 ? _h : 0,
1693
- toolCalls
1694
- };
1695
- };
1696
- exports.runAgent = runAgent;