@kwirthmagnify/kwirth-common-ai 0.5.54 → 0.5.55

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.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { ILlm, ILlmProvider, IAgent, ECapability, EToolEffect, IAiToolInfo, IAiToolsetInfo } from './index';
1
+ import { ILlm, ILlmProvider, IAgent, ECapability, EToolEffect, IAiToolInfo, IAiToolsetInfo, IToolsetConfig } from './index';
2
2
  import type { AppsV1Api, CoreV1Api, NetworkingV1Api } from '@kubernetes/client-node';
3
3
  interface ILogChannel {
4
4
  logInfo?: (msg: string) => void;
5
5
  logWarning?: (msg: string) => void;
6
6
  logError?: (msg: string) => void;
7
7
  }
8
- import { LanguageModel } from 'ai';
8
+ import { LanguageModel, ToolSet } from 'ai';
9
9
  import { z } from 'zod';
10
10
  export declare const buildModel: (llm: ILlm, providers: ILlmProvider[]) => LanguageModel | null;
11
11
  export interface IVisionResult<T> {
@@ -140,6 +140,69 @@ export declare const resolveToolRef: (ref: string) => {
140
140
  toolset: IAiToolset;
141
141
  tool: IAiTool;
142
142
  } | undefined;
143
+ /** Una tool que SI se le ofrece al modelo. */
144
+ export interface IEffectiveTool {
145
+ /** El nombre corto: lo que viaja al LLM. */
146
+ name: string;
147
+ /** La referencia cualificada: lo que se persiste. */
148
+ ref: string;
149
+ toolsetId: string;
150
+ tool: IAiTool;
151
+ }
152
+ /** Una tool que existe pero NO se ofrece, porque otro toolset de mas precedencia trae ese nombre. */
153
+ export interface IShadowedTool {
154
+ name: string;
155
+ ref: string;
156
+ toolsetId: string;
157
+ /** Quien la tapa. El editor tiene que decirlo: si no, apagar esta parece hacer algo y no hace nada. */
158
+ shadowedBy: string;
159
+ }
160
+ export interface IToolResolution {
161
+ effective: IEffectiveTool[];
162
+ shadowed: IShadowedTool[];
163
+ /** Toolsets asignados que no estan registrados (desinstalados, o nunca instalados). */
164
+ missing: string[];
165
+ }
166
+ /**
167
+ * Aplica el techo de un cliente sobre el registro. Pura: ni ejecuta ni toca el contexto, asi que el
168
+ * editor puede llamarla para PINTAR lo mismo que se va a ejecutar.
169
+ *
170
+ * Una tool apagada no tapa: se apaga una referencia concreta ('ts1/td'), no un nombre, asi que si `ts1/td`
171
+ * esta apagada y `ts2` trae otra `td`, aflora la de `ts2`.
172
+ */
173
+ export declare const resolveTools: (config: IToolsetConfig) => IToolResolution;
174
+ /** Una invocacion concreta, tal y como la ven los dos ganchos. */
175
+ export interface IToolInvocation {
176
+ ref: string;
177
+ toolsetId: string;
178
+ toolName: string;
179
+ args: Record<string, unknown>;
180
+ }
181
+ export interface IToolAuthorization {
182
+ allowed: boolean;
183
+ /** Por que no. Viaja al modelo, asi que se escribe para que pueda decidir otra cosa. */
184
+ reason?: string;
185
+ }
186
+ /** Como acabo una invocacion. `ms` incluido: una tool lenta es un problema aunque devuelva bien. */
187
+ export interface IToolOutcome {
188
+ ok: boolean;
189
+ result?: unknown;
190
+ error?: string;
191
+ ms: number;
192
+ /** Si no llego a ejecutarse por el gancho de autorizacion. */
193
+ denied?: boolean;
194
+ }
195
+ export interface IAgentToolHooks {
196
+ /** ANTES de ejecutar. Sin gancho, se permite todo: hoy el techo lo pone la seleccion (S4 lo llena). */
197
+ authorize?: (invocation: IToolInvocation, tool: IAiTool) => IToolAuthorization | Promise<IToolAuthorization>;
198
+ /** DESPUES, pase lo que pase. No puede romper la invocacion (S6 lo llena). */
199
+ observe?: (invocation: IToolInvocation, outcome: IToolOutcome) => void;
200
+ }
201
+ /**
202
+ * Las tools listas para pasarselas al SDK de IA, ya resueltas por precedencia y con los dos ganchos
203
+ * puestos. La clave del objeto es el nombre CORTO, que es lo unico que el proveedor acepta.
204
+ */
205
+ export declare const buildAgentTools: (config: IToolsetConfig, context: IToolContext, hooks?: IAgentToolHooks) => ToolSet;
143
206
  export declare const tools: {
144
207
  readonly list_namespaces: import("ai").Tool<Record<string, never>, {
145
208
  namespaces: any;
package/dist/back.js CHANGED
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.runAgent = exports.selectAgentToolNames = exports.toolInfoList = exports.tools = exports.resolveToolRef = exports.invokeToolRef = exports.buildToolHost = exports.listToolsetInfos = exports.listToolsets = exports.getToolset = exports.unregisterToolset = exports.registerToolset = exports.isBuiltInToolsetId = exports.runWithToolContext = exports.EToolEffect = exports.zodFromExample = exports.z = exports.tool = exports.stepCountIs = exports.Output = exports.generateText = exports.loadModels = exports.generateVision = exports.buildModel = void 0;
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.isBuiltInToolsetId = 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
37
  const index_1 = require("./index");
38
38
  const ai_1 = require("ai");
39
39
  const zod_1 = require("zod");
@@ -486,6 +486,89 @@ const resolveToolRef = (ref) => {
486
486
  return toolset && tool ? { toolset, tool } : undefined;
487
487
  };
488
488
  exports.resolveToolRef = resolveToolRef;
489
+ /**
490
+ * Aplica el techo de un cliente sobre el registro. Pura: ni ejecuta ni toca el contexto, asi que el
491
+ * editor puede llamarla para PINTAR lo mismo que se va a ejecutar.
492
+ *
493
+ * Una tool apagada no tapa: se apaga una referencia concreta ('ts1/td'), no un nombre, asi que si `ts1/td`
494
+ * esta apagada y `ts2` trae otra `td`, aflora la de `ts2`.
495
+ */
496
+ const resolveTools = (config) => {
497
+ const disabled = new Set(config.disabledTools);
498
+ const effective = [];
499
+ const shadowed = [];
500
+ const missing = [];
501
+ const taken = new Map(); // nombre corto → toolset que lo sirve
502
+ for (const toolsetId of config.activeToolsets) {
503
+ const toolset = toolsetRegistry.get(toolsetId);
504
+ if (!toolset) {
505
+ // No se calla: un techo que nombra algo que no esta instalado es una config rota, y el
506
+ // sintoma sin esto seria "el agente responde peor" sin que nadie sepa por que.
507
+ missing.push(toolsetId);
508
+ continue;
509
+ }
510
+ for (const tool of toolset.tools) {
511
+ const ref = (0, index_1.toolRef)(toolsetId, tool.name);
512
+ if (disabled.has(ref))
513
+ continue;
514
+ const owner = taken.get(tool.name);
515
+ if (owner) {
516
+ shadowed.push({ name: tool.name, ref, toolsetId, shadowedBy: owner });
517
+ continue;
518
+ }
519
+ taken.set(tool.name, toolsetId);
520
+ effective.push({ name: tool.name, ref, toolsetId, tool });
521
+ }
522
+ }
523
+ return { effective, shadowed, missing };
524
+ };
525
+ exports.resolveTools = resolveTools;
526
+ /**
527
+ * Las tools listas para pasarselas al SDK de IA, ya resueltas por precedencia y con los dos ganchos
528
+ * puestos. La clave del objeto es el nombre CORTO, que es lo unico que el proveedor acepta.
529
+ */
530
+ const buildAgentTools = (config, context, hooks = {}) => {
531
+ const { effective } = (0, exports.resolveTools)(config);
532
+ const entries = effective.map(e => {
533
+ const invocationOf = (args) => ({ ref: e.ref, toolsetId: e.toolsetId, toolName: e.name, args });
534
+ // `dynamicTool` y no `tool`: el esquema de una tool empaquetada no se conoce en compilacion, y el
535
+ // helper tipado infiere `never` para un ZodTypeAny generico.
536
+ return [e.name, (0, ai_1.dynamicTool)({
537
+ description: e.tool.description,
538
+ inputSchema: e.tool.inputSchema,
539
+ execute: async (rawArgs) => {
540
+ var _a, _b, _c, _d, _e;
541
+ const args = (rawArgs !== null && rawArgs !== void 0 ? rawArgs : {});
542
+ const invocation = invocationOf(args);
543
+ const started = Date.now();
544
+ const verdict = hooks.authorize ? await hooks.authorize(invocation, e.tool) : { allowed: true };
545
+ if (!verdict.allowed) {
546
+ // Se devuelve como DATO, no como excepcion: una excepcion corta la conversacion, y lo
547
+ // que queremos es que el modelo sepa que esa via esta cerrada y pruebe otra.
548
+ const denial = { error: `tool '${e.name}' not allowed${verdict.reason ? `: ${verdict.reason}` : ''}` };
549
+ (_a = hooks.observe) === null || _a === void 0 ? void 0 : _a.call(hooks, invocation, { ok: false, error: denial.error, ms: Date.now() - started, denied: true });
550
+ return denial;
551
+ }
552
+ 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);
553
+ try {
554
+ // El runWithToolContext envuelve tambien a las tools escritas contra el contrato VIEJO
555
+ // (las que leen ctx()). Es lo que permite migrar las 43 paquete a paquete en S3 en vez
556
+ // de tener que reescribirlas todas antes de poder usar este camino.
557
+ const result = await (0, exports.runWithToolContext)(context, () => e.tool.execute(args, host));
558
+ (_d = hooks.observe) === null || _d === void 0 ? void 0 : _d.call(hooks, invocation, { ok: true, result, ms: Date.now() - started });
559
+ return result;
560
+ }
561
+ catch (err) {
562
+ const message = err instanceof Error ? err.message : String(err);
563
+ (_e = hooks.observe) === null || _e === void 0 ? void 0 : _e.call(hooks, invocation, { ok: false, error: message, ms: Date.now() - started });
564
+ return { error: message };
565
+ }
566
+ }
567
+ })];
568
+ });
569
+ return Object.fromEntries(entries);
570
+ };
571
+ exports.buildAgentTools = buildAgentTools;
489
572
  exports.tools = {
490
573
  // ── CLUSTER CONFIG ───────────────────────────────────────────────────────
491
574
  list_namespaces: (0, ai_1.tool)({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kwirthmagnify/kwirth-common-ai",
3
- "version": "0.5.54",
3
+ "version": "0.5.55",
4
4
  "description": "Shared AI/LLM types and utilities for Kwirth AI plugins",
5
5
  "scripts": {
6
6
  "build": "del .\\dist\\* /s /q 2>nul & tsc",