@kwirthmagnify/kwirth-common-ai 0.5.77 → 0.5.79

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,4 +1,4 @@
1
- import { ILlm, ILlmProvider, ECapability, EToolEffect, EToolSensitivity, EUsagePeriod, EUsageUnit, IAiToolInfo, IAiToolsetInfo, IToolsetConfig, IUsageAmounts, IUsageLimits } from './index';
1
+ import { ILlm, ILlmProvider, ECapability, EToolEffect, EToolSensitivity, EUsagePeriod, EUsageUnit, IAiToolInfo, IAiToolsetInfo, IToolsetConfig, IToolsetGrant, IUsageAmounts, IUsageLimits } from './index';
2
2
  import type { AppsV1Api, CoreV1Api, CustomObjectsApi, NetworkingV1Api } from '@kubernetes/client-node';
3
3
  interface ILogChannel {
4
4
  logInfo?: (msg: string) => void;
@@ -230,12 +230,20 @@ export declare const defineTool: <S extends z.ZodTypeAny>(definition: {
230
230
  execute: (args: z.infer<S>, host: IToolHost) => Promise<unknown>;
231
231
  }) => IAiTool;
232
232
  export declare const isBuiltInToolsetId: (id: string) => boolean;
233
- /** Grants a toolset to a list of plugins. Replaces the previous grant; `[]` takes it away from everyone. */
234
- export declare const setToolsetGrants: (toolsetId: string, pluginIds: string[]) => void;
235
- /** Who a toolset is granted to. Empty = nobody, which is the default state. */
236
- export declare const getToolsetGrants: (toolsetId: string) => string[];
237
- /** Whether THAT plugin may use THAT toolset. */
233
+ /**
234
+ * Sets a toolset's grant. Replaces the previous one; `[]` takes it away from everyone.
235
+ *
236
+ * A plugin granted nothing (`allTools: false`, `tools: []`) is NOT kept: "granted nothing" and "not
237
+ * granted" must behave the same, or `isToolsetGrantedTo` would say yes to a plugin that can use nothing.
238
+ * Repeated plugins are merged: the union of their tools, and `allTools` if any of them says so.
239
+ */
240
+ export declare const setToolsetGrants: (toolsetId: string, grants: IToolsetGrant[]) => void;
241
+ /** A toolset's grant, as it lives in the registry. Empty = nobody, which is the default state. */
242
+ export declare const getToolsetGrants: (toolsetId: string) => IToolsetGrant[];
243
+ /** Whether THAT plugin may use THAT toolset: at least one of its tools is granted to it. */
238
244
  export declare const isToolsetGrantedTo: (toolsetId: string, pluginId: string) => boolean;
245
+ /** Whether THAT plugin may use THAT tool of THAT toolset. */
246
+ export declare const isToolGrantedTo: (toolsetId: string, toolName: string, pluginId: string) => boolean;
239
247
  /**
240
248
  * Registers a toolset. `builtIn` is only used by the core for its own: it marks the id as reserved.
241
249
  * Throws if the id is already taken — registering the same id twice is a packaging error, not something
@@ -259,6 +267,9 @@ export declare const buildToolHost: (requires: ECapability[], context: IToolCont
259
267
  /**
260
268
  * Invokes a tool by its qualified reference. A single invocation path for built-in and installed alike,
261
269
  * with the host built according to the `requires` of ITS toolset.
270
+ *
271
+ * ⚠️ It is NOT a gate: it does not know who is asking, so it does not check the grant. Whatever runs on
272
+ * behalf of a plugin goes through `buildAgentTools`, which resolves with the requester.
262
273
  */
263
274
  export declare const invokeToolRef: (ref: string, args: Record<string, unknown>, context: IToolContext) => Promise<unknown>;
264
275
  /** Resolves a qualified reference '<toolset>/<tool>' against the registry. */
@@ -296,6 +307,13 @@ export interface IToolResolution {
296
307
  * looking in the wrong place.
297
308
  */
298
309
  notGranted: string[];
310
+ /**
311
+ * Tools of a GRANTED toolset that the admin did not grant to this plugin, as qualified references.
312
+ *
313
+ * Apart from `disabledTools` on purpose: "the admin took it from you" is fixed in the toolset's grant,
314
+ * "you turned it off" in the plugin's own config.
315
+ */
316
+ notGrantedTools: string[];
299
317
  }
300
318
  /**
301
319
  * Applies a client's ceiling over the registry. Pure: it neither executes nor touches the context, so the
package/dist/back.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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.streamText = exports.generateText = exports.loadModels = exports.generateVision = exports.runWithUsageGuard = exports.effectiveLimits = exports.usageSubjectForKey = exports.getUsageService = exports.setUsageService = exports.setAiLogger = exports.UsageLimitError = exports.EUsageScope = 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.isToolGrantedTo = 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.streamText = exports.generateText = exports.loadModels = exports.generateVision = exports.runWithUsageGuard = exports.effectiveLimits = exports.usageSubjectForKey = exports.getUsageService = exports.setUsageService = exports.setAiLogger = exports.UsageLimitError = exports.EUsageScope = exports.buildModel = void 0;
4
4
  const index_1 = require("./index");
5
5
  // Aliased on purpose: the generateText this module EXPORTS is the wrapped one, and nothing below should
6
6
  // be able to reach the raw SDK call by accident — that is exactly how a call would escape the counters.
@@ -294,6 +294,7 @@ const usageRecord = (options, result) => {
294
294
  }).catch(err => logUsage(`AI usage: could not record ${tokensIn + tokensOut} token(s) of a call that DID happen (${err}) — the counters are now short`));
295
295
  };
296
296
  const runWithUsageGuard = async (options, call) => {
297
+ var _a, _b, _c, _d;
297
298
  await usageGuardCheck(options);
298
299
  /* 🔴 En `finally`, no después del `await`. La primera versión medía solo el camino feliz, que es
299
300
  justo el que no hacía falta medir: cuando una llamada se aborta por tiempo —el caso que se estaba
@@ -301,21 +302,65 @@ const runWithUsageGuard = async (options, call) => {
301
302
  contabilidad de aquí arriba (2026-10-14). Un tramo instrumentado solo cuando va bien no está
302
303
  instrumentado. */
303
304
  const callStarted = Date.now();
304
- let ok = false;
305
- let result;
306
305
  try {
307
- result = await call();
308
- ok = true;
306
+ const result = await call();
307
+ const callMs = Date.now() - callStarted;
308
+ if (callMs > 30000)
309
+ logUsage(`AI usage: the model took ${Math.round(callMs / 1000)} s`);
310
+ usageRecord(options, result);
311
+ return result;
309
312
  }
310
- finally {
313
+ catch (err) {
314
+ /* 🔴 Una llamada que LANZA puede haber gastado igual, y hasta aquí ese gasto se tiraba.
315
+
316
+ `generateObject` lanza cuando lo que devuelve el modelo no valida contra el esquema, pero
317
+ para entonces el modelo ya ha contestado y ya ha cobrado: el error del SDK
318
+ (`NoObjectGeneratedError`) trae su `usage` dentro. Como `usageRecord` vivía DESPUÉS del
319
+ `await`, no llegaba a ejecutarse y esos tokens no contaban contra ningún tope — y no es un
320
+ caso raro: un canal cuyo modelo devuelve algo que no casa el ejemplo lo hace en cada
321
+ llamada, así que podía gastar sin límite y sin dejar rastro en los contadores.
322
+
323
+ Y entonces tampoco se llama FAILED: el modelo respondió. Decir que falló mandaba a mirar al
324
+ sitio equivocado —la conexión, el tiempo— cuando lo que hay que mirar es el esquema. */
311
325
  const callMs = Date.now() - callStarted;
312
- if (callMs > 30000 || !ok)
313
- logUsage(`AI usage: the model ${ok ? 'took' : 'FAILED after'} ${Math.round(callMs / 1000)} s`);
326
+ const gastado = usageOfRejected(err);
327
+ if (gastado) {
328
+ const total = ((_b = (_a = gastado.usage) === null || _a === void 0 ? void 0 : _a.inputTokens) !== null && _b !== void 0 ? _b : 0) + ((_d = (_c = gastado.usage) === null || _c === void 0 ? void 0 : _c.outputTokens) !== null && _d !== void 0 ? _d : 0);
329
+ logUsage(`AI usage: the model answered in ${Math.round(callMs / 1000)} s but its answer was rejected (${errorName(err)}) — the ${total} token(s) it spent are counted anyway`);
330
+ usageRecord(options, gastado);
331
+ }
332
+ else {
333
+ logUsage(`AI usage: the model FAILED after ${Math.round(callMs / 1000)} s`);
334
+ }
335
+ throw err;
314
336
  }
315
- usageRecord(options, result);
316
- return result;
317
337
  };
318
338
  exports.runWithUsageGuard = runWithUsageGuard;
339
+ /** El nombre del error del SDK (`NoObjectGeneratedError`, `AI_TypeValidationError`…), para decir POR QUÉ. */
340
+ const errorName = (err) => typeof err === 'object' && err !== null && typeof err.name === 'string'
341
+ ? err.name
342
+ : 'unknown error';
343
+ /*
344
+ Lo que gastó una llamada que el SDK dio por fallida, si es que lo dice.
345
+
346
+ Se lee a mano en vez de con `NoObjectGeneratedError.isInstance`: el error puede venir de otra copia
347
+ del SDK —cada canal trae la suya— y entonces el `instanceof` falla aunque el error sea exactamente
348
+ ese. Lo que importa son los números, y los números están o no están.
349
+ */
350
+ const usageOfRejected = (err) => {
351
+ if (typeof err !== 'object' || err === null)
352
+ return undefined;
353
+ const usage = err.usage;
354
+ if (typeof usage !== 'object' || usage === null)
355
+ return undefined;
356
+ const { inputTokens, outputTokens } = usage;
357
+ const entrada = typeof inputTokens === 'number' ? inputTokens : undefined;
358
+ const salida = typeof outputTokens === 'number' ? outputTokens : undefined;
359
+ // sin ninguna de las dos cifras no hay nada que apuntar, y apuntar ceros falsearia los contadores
360
+ if (entrada === undefined && salida === undefined)
361
+ return undefined;
362
+ return { usage: { inputTokens: entrada, outputTokens: salida } };
363
+ };
319
364
  // Generic MULTIMODAL call: sends an image plus a prompt to an LLM and returns STRUCTURED output validated by
320
365
  // a Zod schema (the Output.object pattern). Reusable across the whole platform (Iter uses it to extract a map
321
366
  // from a diagram). It never throws: errors come back in `error`.
@@ -681,20 +726,49 @@ const builtInToolsetIds = new Set();
681
726
  And by default nobody uses it (user's decision, 2026-09-17): installing a toolset leaves it available,
682
727
  not granted. Installing `k8s-ops` must not give anyone write access by accident.
683
728
  */
684
- const toolsetGrants = new Map(); // toolsetId → invited plugins
729
+ // And the grant is per TOOL (plan: plans/ai-tool-grants/PLAN.md, T1): the admin grants a plugin either every
730
+ // tool of the toolset (`allTools`, future ones included) or an explicit list (new ones are NOT granted).
731
+ const toolsetGrants = new Map(); // toolsetId → pluginId → its grant
685
732
  const isBuiltInToolsetId = (id) => builtInToolsetIds.has(id);
686
733
  exports.isBuiltInToolsetId = isBuiltInToolsetId;
687
- /** Grants a toolset to a list of plugins. Replaces the previous grant; `[]` takes it away from everyone. */
688
- const setToolsetGrants = (toolsetId, pluginIds) => {
689
- toolsetGrants.set(toolsetId, new Set(pluginIds));
734
+ /** Whether a grant gives anything at all. */
735
+ const grantsSomething = (g) => g.allTools || g.tools.length > 0;
736
+ /**
737
+ * Sets a toolset's grant. Replaces the previous one; `[]` takes it away from everyone.
738
+ *
739
+ * A plugin granted nothing (`allTools: false`, `tools: []`) is NOT kept: "granted nothing" and "not
740
+ * granted" must behave the same, or `isToolsetGrantedTo` would say yes to a plugin that can use nothing.
741
+ * Repeated plugins are merged: the union of their tools, and `allTools` if any of them says so.
742
+ */
743
+ const setToolsetGrants = (toolsetId, grants) => {
744
+ var _a, _b;
745
+ const byPlugin = new Map();
746
+ for (const g of grants) {
747
+ if (!grantsSomething(g))
748
+ continue;
749
+ const previous = byPlugin.get(g.pluginId);
750
+ byPlugin.set(g.pluginId, {
751
+ pluginId: g.pluginId,
752
+ allTools: g.allTools || ((_a = previous === null || previous === void 0 ? void 0 : previous.allTools) !== null && _a !== void 0 ? _a : false),
753
+ tools: [...new Set([...((_b = previous === null || previous === void 0 ? void 0 : previous.tools) !== null && _b !== void 0 ? _b : []), ...g.tools])]
754
+ });
755
+ }
756
+ toolsetGrants.set(toolsetId, byPlugin);
690
757
  };
691
758
  exports.setToolsetGrants = setToolsetGrants;
692
- /** Who a toolset is granted to. Empty = nobody, which is the default state. */
693
- const getToolsetGrants = (toolsetId) => { var _a; return [...((_a = toolsetGrants.get(toolsetId)) !== null && _a !== void 0 ? _a : [])]; };
759
+ /** A toolset's grant, as it lives in the registry. Empty = nobody, which is the default state. */
760
+ const getToolsetGrants = (toolsetId) => { var _a, _b; return [...((_b = (_a = toolsetGrants.get(toolsetId)) === null || _a === void 0 ? void 0 : _a.values()) !== null && _b !== void 0 ? _b : [])].map(g => (Object.assign(Object.assign({}, g), { tools: [...g.tools] }))); };
694
761
  exports.getToolsetGrants = getToolsetGrants;
695
- /** Whether THAT plugin may use THAT toolset. */
762
+ /** Whether THAT plugin may use THAT toolset: at least one of its tools is granted to it. */
696
763
  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; };
697
764
  exports.isToolsetGrantedTo = isToolsetGrantedTo;
765
+ /** Whether THAT plugin may use THAT tool of THAT toolset. */
766
+ const isToolGrantedTo = (toolsetId, toolName, pluginId) => {
767
+ var _a;
768
+ const g = (_a = toolsetGrants.get(toolsetId)) === null || _a === void 0 ? void 0 : _a.get(pluginId);
769
+ return g !== undefined && (g.allTools || g.tools.includes(toolName));
770
+ };
771
+ exports.isToolGrantedTo = isToolGrantedTo;
698
772
  /**
699
773
  * Registers a toolset. `builtIn` is only used by the core for its own: it marks the id as reserved.
700
774
  * Throws if the id is already taken — registering the same id twice is a packaging error, not something
@@ -776,6 +850,9 @@ exports.buildToolHost = buildToolHost;
776
850
  /**
777
851
  * Invokes a tool by its qualified reference. A single invocation path for built-in and installed alike,
778
852
  * with the host built according to the `requires` of ITS toolset.
853
+ *
854
+ * ⚠️ It is NOT a gate: it does not know who is asking, so it does not check the grant. Whatever runs on
855
+ * behalf of a plugin goes through `buildAgentTools`, which resolves with the requester.
779
856
  */
780
857
  const invokeToolRef = async (ref, args, context) => {
781
858
  const resolved = (0, exports.resolveToolRef)(ref);
@@ -807,6 +884,7 @@ const resolveTools = (config, requesterId) => {
807
884
  const shadowed = [];
808
885
  const missing = [];
809
886
  const notGranted = [];
887
+ const notGrantedTools = [];
810
888
  const taken = new Map(); // short name → toolset serving it
811
889
  for (const toolsetId of config.activeToolsets) {
812
890
  const toolset = toolsetRegistry.get(toolsetId);
@@ -825,6 +903,12 @@ const resolveTools = (config, requesterId) => {
825
903
  }
826
904
  for (const tool of toolset.tools) {
827
905
  const ref = (0, index_1.toolRef)(toolsetId, tool.name);
906
+ // A tool not granted is out of play BEFORE the shadowing, like a disabled one: it must not hide a
907
+ // tool with the same name from a toolset of lower precedence.
908
+ if (requesterId !== undefined && !(0, exports.isToolGrantedTo)(toolsetId, tool.name, requesterId)) {
909
+ notGrantedTools.push(ref);
910
+ continue;
911
+ }
828
912
  if (disabled.has(ref))
829
913
  continue;
830
914
  const owner = taken.get(tool.name);
@@ -836,7 +920,7 @@ const resolveTools = (config, requesterId) => {
836
920
  effective.push({ name: tool.name, ref, toolsetId, tool });
837
921
  }
838
922
  }
839
- return { effective, shadowed, missing, notGranted };
923
+ return { effective, shadowed, missing, notGranted, notGrantedTools };
840
924
  };
841
925
  exports.resolveTools = resolveTools;
842
926
  /**
package/dist/front.js CHANGED
@@ -130,7 +130,9 @@ const UsageLimitsEditor = (props) => {
130
130
  model has answered — is still said, in one line, where the limit is set.
131
131
  */
132
132
  return (react_1.default.createElement(material_1.Stack, { direction: 'column', spacing: 0.5, sx: { mt: 0.5 } },
133
- react_1.default.createElement(material_1.Typography, { variant: 'caption', color: 'text.secondary' },
133
+ react_1.default.createElement(material_1.Typography, { variant: 'caption', sx: {
134
+ color: 'text.secondary'
135
+ } },
134
136
  "Stop spending on ",
135
137
  react_1.default.createElement("b", null, props.subject),
136
138
  ": a call goes out only if ",
@@ -145,7 +147,9 @@ const UsageLimitsEditor = (props) => {
145
147
  react_1.default.createElement("b", null, "next"),
146
148
  " one."),
147
149
  props.usage && props.durable === false &&
148
- react_1.default.createElement(material_1.Typography, { variant: 'caption', color: 'warning.main' },
150
+ react_1.default.createElement(material_1.Typography, { variant: 'caption', sx: {
151
+ color: 'warning.main'
152
+ } },
149
153
  "\u26A0\uFE0F Counters kept ",
150
154
  react_1.default.createElement("b", null, "in memory"),
151
155
  " (no SQL): they reset on every restart, and so do these limits."),
@@ -159,10 +163,16 @@ const UsageLimitsEditor = (props) => {
159
163
  salta bajo el cursor. Un diálogo que se mueve mientras lo lees cuesta más que el dato
160
164
  que daba, y el dato está en el panel de consumo.
161
165
  */
162
- return (react_1.default.createElement(material_1.Stack, { key: unit, direction: 'row', spacing: 1, alignItems: 'flex-start' },
166
+ return (react_1.default.createElement(material_1.Stack, { key: unit, direction: 'row', spacing: 1, sx: {
167
+ alignItems: 'flex-start'
168
+ } },
163
169
  react_1.default.createElement(material_1.FormControlLabel, { sx: { width: '150px', flexShrink: 0, mr: 0, mt: 0.5 }, control: react_1.default.createElement(material_1.Checkbox, { size: 'small', checked: !!w.enabled, disabled: props.disabled, onChange: e => patch(unit, { enabled: e.target.checked }) }), label: react_1.default.createElement(material_1.Typography, { variant: 'body2' }, label) }),
164
- react_1.default.createElement(material_1.TextField, { value: (_b = w.daily) !== null && _b !== void 0 ? _b : '', onChange: e => patch(unit, { daily: numberOrUndefined(e.target.value) }), label: 'Per day', variant: 'standard', type: 'number', fullWidth: true, size: 'small', disabled: props.disabled || !w.enabled, inputProps: { min: 0 }, placeholder: 'no limit' }),
165
- react_1.default.createElement(material_1.TextField, { value: (_c = w.monthly) !== null && _c !== void 0 ? _c : '', onChange: e => patch(unit, { monthly: numberOrUndefined(e.target.value) }), label: 'Per month', variant: 'standard', type: 'number', fullWidth: true, size: 'small', disabled: props.disabled || !w.enabled, inputProps: { min: 0 }, placeholder: 'no limit' })));
170
+ react_1.default.createElement(material_1.TextField, { value: (_b = w.daily) !== null && _b !== void 0 ? _b : '', onChange: e => patch(unit, { daily: numberOrUndefined(e.target.value) }), label: 'Per day', variant: 'standard', type: 'number', fullWidth: true, size: 'small', disabled: props.disabled || !w.enabled, placeholder: 'no limit', slotProps: {
171
+ htmlInput: { min: 0 }
172
+ } }),
173
+ react_1.default.createElement(material_1.TextField, { value: (_c = w.monthly) !== null && _c !== void 0 ? _c : '', onChange: e => patch(unit, { monthly: numberOrUndefined(e.target.value) }), label: 'Per month', variant: 'standard', type: 'number', fullWidth: true, size: 'small', disabled: props.disabled || !w.enabled, placeholder: 'no limit', slotProps: {
174
+ htmlInput: { min: 0 }
175
+ } })));
166
176
  })));
167
177
  };
168
178
  const LlmSelector = ({ llms, value, onChange, label = 'LLM', size = 'small', fullWidth = true }) => {
@@ -262,7 +272,9 @@ const AiConfigLlm = (props) => {
262
272
  Add/Update button below the fold on a short screen: the form grew, the dialog did not, and the
263
273
  control that applies the form to the list scrolled out of sight.
264
274
  */
265
- return (react_1.default.createElement(material_1.Dialog, { open: true, onClose: () => props.onClose(undefined), PaperProps: { sx: { width: 'auto', maxWidth: 'none', height: 'auto' } } },
275
+ return (react_1.default.createElement(material_1.Dialog, { open: true, onClose: () => props.onClose(undefined), maxWidth: false, slotProps: {
276
+ paper: { sx: { width: 'auto', height: 'auto' } }
277
+ } },
266
278
  react_1.default.createElement(material_1.DialogTitle, { sx: { pb: 1 } }, "AI \u2014 LLM config"),
267
279
  react_1.default.createElement(material_1.DialogContent, { style: { display: 'flex' } },
268
280
  react_1.default.createElement(material_1.Box, { sx: { flex: '0 0 220px', boxSizing: 'border-box', position: 'relative' } },
@@ -270,10 +282,16 @@ const AiConfigLlm = (props) => {
270
282
  react_1.default.createElement(material_1.List, { sx: { flexGrow: 1, mr: 2, width: '100%' } }, llms.map((llm, index) => (react_1.default.createElement(material_1.ListItemButton, { key: index, selected: selectedIndex === index, onClick: () => onLlmSelected(index) },
271
283
  react_1.default.createElement(material_1.Stack, { direction: 'column' },
272
284
  react_1.default.createElement(material_1.Typography, { sx: { fontWeight: selectedIndex === index ? 'bold' : 'normal' } }, llm.id),
273
- react_1.default.createElement(material_1.Typography, { color: 'darkgray', fontSize: 12 }, llm.provider)))))))),
285
+ react_1.default.createElement(material_1.Typography, { color: 'darkgray', sx: {
286
+ fontSize: 12
287
+ } }, llm.provider)))))))),
274
288
  react_1.default.createElement(material_1.Box, { sx: { flex: 1, display: 'flex', flexDirection: 'column', padding: '16px', minWidth: 0 } },
275
289
  react_1.default.createElement(material_1.Stack, { spacing: 2, style: { width: '100%' } },
276
- react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 3, alignItems: 'stretch', sx: { flexWrap: 'wrap', height: '100%' } },
290
+ react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 3, sx: {
291
+ alignItems: 'stretch',
292
+ flexWrap: 'nowrap',
293
+ height: '100%'
294
+ } },
277
295
  react_1.default.createElement(material_1.Stack, { direction: 'column', spacing: 1, sx: { flex: `0 0 ${COL_WIDTH}px`, width: COL_WIDTH } },
278
296
  react_1.default.createElement(material_1.TextField, { value: id, onChange: e => setId(e.target.value), placeholder: 'Enter LLM id', label: 'LLM ID', variant: 'standard', fullWidth: true }),
279
297
  react_1.default.createElement(material_1.FormControl, { variant: 'standard', sx: { width: '100%' } },
@@ -289,26 +307,44 @@ const AiConfigLlm = (props) => {
289
307
  : (react_1.default.createElement(material_1.TextField, { value: model, onChange: e => setModel(e.target.value), label: 'Model ID', placeholder: 'e.g. claude-sonnet-4-5, glm-5.2', variant: 'standard', fullWidth: true })),
290
308
  react_1.default.createElement(material_1.TextField, { value: temperature, onChange: e => setTemperature(+e.target.value), label: 'Temperature', variant: 'standard', type: 'number', fullWidth: true }),
291
309
  react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 1, sx: { flexWrap: 'nowrap' } },
292
- react_1.default.createElement(material_1.TextField, { value: inputCostPerMillion, onChange: e => setInputCostPerMillion(e.target.value === '' ? '' : +e.target.value), label: 'Input cost /M', variant: 'standard', type: 'number', sx: { flex: 1, minWidth: 0 }, inputProps: { min: 0, step: 0.01 }, placeholder: providerCost(provider, 'inputCostPerMillion'), InputLabelProps: { shrink: true } }),
293
- react_1.default.createElement(material_1.TextField, { value: outputCostPerMillion, onChange: e => setOutputCostPerMillion(e.target.value === '' ? '' : +e.target.value), label: 'Output cost /M', variant: 'standard', type: 'number', sx: { flex: 1, minWidth: 0 }, inputProps: { min: 0, step: 0.01 }, placeholder: providerCost(provider, 'outputCostPerMillion'), InputLabelProps: { shrink: true } })),
294
- react_1.default.createElement(material_1.Stack, { direction: 'row', alignItems: 'center' },
295
- react_1.default.createElement(material_1.Typography, { flex: 1 }, "Use provider API Key"),
310
+ react_1.default.createElement(material_1.TextField, { value: inputCostPerMillion, onChange: e => setInputCostPerMillion(e.target.value === '' ? '' : +e.target.value), label: 'Input cost /M', variant: 'standard', type: 'number', sx: { flex: 1, minWidth: 0 }, placeholder: providerCost(provider, 'inputCostPerMillion'), slotProps: {
311
+ htmlInput: { min: 0, step: 0.01 },
312
+ inputLabel: { shrink: true }
313
+ } }),
314
+ react_1.default.createElement(material_1.TextField, { value: outputCostPerMillion, onChange: e => setOutputCostPerMillion(e.target.value === '' ? '' : +e.target.value), label: 'Output cost /M', variant: 'standard', type: 'number', sx: { flex: 1, minWidth: 0 }, placeholder: providerCost(provider, 'outputCostPerMillion'), slotProps: {
315
+ htmlInput: { min: 0, step: 0.01 },
316
+ inputLabel: { shrink: true }
317
+ } })),
318
+ react_1.default.createElement(material_1.Stack, { direction: 'row', sx: {
319
+ alignItems: 'center'
320
+ } },
321
+ react_1.default.createElement(material_1.Typography, { sx: {
322
+ flex: 1
323
+ } }, "Use provider API Key"),
296
324
  react_1.default.createElement(material_1.Checkbox, { checked: useProviderKey, onChange: e => setUseProviderKey(e.target.checked) })),
297
- react_1.default.createElement(material_1.TextField, { value: key, onChange: e => setKey(e.target.value), disabled: useProviderKey, label: 'API Key', placeholder: 'Enter API Key', variant: 'standard', fullWidth: true, type: showPassword ? 'text' : 'password', InputProps: {
298
- endAdornment: (react_1.default.createElement(material_1.InputAdornment, { position: 'end' },
299
- react_1.default.createElement(material_1.IconButton, { onClick: () => setShowPassword(!showPassword), edge: 'end' }, showPassword ? react_1.default.createElement(VisibilityOff_1.default, null) : react_1.default.createElement(Visibility_1.default, null))))
325
+ react_1.default.createElement(material_1.TextField, { value: key, onChange: e => setKey(e.target.value), disabled: useProviderKey, label: 'API Key', placeholder: 'Enter API Key', variant: 'standard', fullWidth: true, type: showPassword ? 'text' : 'password', slotProps: {
326
+ input: {
327
+ endAdornment: (react_1.default.createElement(material_1.InputAdornment, { position: 'end' },
328
+ react_1.default.createElement(material_1.IconButton, { onClick: () => setShowPassword(!showPassword), edge: 'end' }, showPassword ? react_1.default.createElement(VisibilityOff_1.default, null) : react_1.default.createElement(Visibility_1.default, null))))
329
+ }
300
330
  } })),
301
331
  react_1.default.createElement(material_1.Stack, { direction: 'column', spacing: 1, sx: { flex: `0 0 ${COL_WIDTH}px`, width: COL_WIDTH } },
302
332
  react_1.default.createElement(material_1.Typography, { variant: 'subtitle2' }, "Usage limits"),
303
333
  react_1.default.createElement(UsageLimitsEditor, { value: limits, onChange: setLimits, subject: `the key this model uses`, usage: (_c = props.usage) === null || _c === void 0 ? void 0 : _c[id], durable: props.usageDurable }),
304
- react_1.default.createElement(material_1.Typography, { variant: 'caption', color: 'text.secondary' }, "Left empty, the provider's limits apply. Spending is counted per API key.")))),
334
+ react_1.default.createElement(material_1.Typography, { variant: 'caption', sx: {
335
+ color: 'text.secondary'
336
+ } }, "Left empty, the provider's limits apply. Spending is counted per API key.")))),
305
337
  react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 1, sx: { pt: 2 } },
306
338
  react_1.default.createElement(material_1.Button, { variant: 'outlined', size: 'small', onClick: onNew }, "New"),
307
- react_1.default.createElement(material_1.Typography, { flex: 1 }),
339
+ react_1.default.createElement(material_1.Typography, { sx: {
340
+ flex: 1
341
+ } }),
308
342
  react_1.default.createElement(material_1.Button, { color: 'error', onClick: onRemove, disabled: selectedIndex === null }, "Remove"),
309
343
  react_1.default.createElement(material_1.Button, { variant: 'contained', onClick: onAdd, disabled: !id || !model }, selectedIndex !== null ? 'Update' : 'Add')))),
310
344
  react_1.default.createElement(material_1.DialogActions, null,
311
- react_1.default.createElement(material_1.Box, { flex: 1 }),
345
+ react_1.default.createElement(material_1.Box, { sx: {
346
+ flex: 1
347
+ } }),
312
348
  react_1.default.createElement(material_1.Button, { onClick: () => props.onClose(llms), variant: 'contained' }, "OK"),
313
349
  react_1.default.createElement(material_1.Button, { onClick: () => props.onClose(undefined), variant: 'outlined' }, "Cancel"))));
314
350
  };
@@ -400,7 +436,9 @@ const AiConfigProvider = (props) => {
400
436
  setLoadingModels(false);
401
437
  }
402
438
  };
403
- return (react_1.default.createElement(material_1.Dialog, { open: true, onClose: () => props.onClose(undefined), PaperProps: { sx: { width: 'auto', maxWidth: 'none', height: 'auto' } } },
439
+ return (react_1.default.createElement(material_1.Dialog, { open: true, onClose: () => props.onClose(undefined), maxWidth: false, slotProps: {
440
+ paper: { sx: { width: 'auto', height: 'auto' } }
441
+ } },
404
442
  react_1.default.createElement(material_1.DialogTitle, { sx: { pb: 1 } }, "AI \u2014 Provider config"),
405
443
  react_1.default.createElement(material_1.DialogContent, { style: { display: 'flex' } },
406
444
  react_1.default.createElement(material_1.Box, { sx: { flex: '0 0 220px', boxSizing: 'border-box', position: 'relative' } },
@@ -410,45 +448,68 @@ const AiConfigProvider = (props) => {
410
448
  return (react_1.default.createElement(material_1.ListItemButton, { key: index, selected: selectedIndex === index, onClick: () => onProviderSelected(p, index) },
411
449
  react_1.default.createElement(material_1.Stack, { direction: 'column' },
412
450
  react_1.default.createElement(material_1.Typography, { sx: { fontWeight: selectedIndex === index ? 'bold' : 'normal' } }, p.name),
413
- react_1.default.createElement(material_1.Typography, { color: 'darkgray', fontSize: 11 },
451
+ react_1.default.createElement(material_1.Typography, { color: 'darkgray', sx: {
452
+ fontSize: 11
453
+ } },
414
454
  ((_a = p.models) === null || _a === void 0 ? void 0 : _a.length) || 0,
415
455
  " models loaded"))));
416
456
  })))),
417
457
  react_1.default.createElement(material_1.Box, { sx: { flex: 1, display: 'flex', flexDirection: 'column', padding: '16px', minWidth: 0 } },
418
458
  react_1.default.createElement(material_1.Stack, { spacing: 2, style: { width: '100%' } },
419
- react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 3, alignItems: 'flex-start', sx: { flexWrap: 'wrap' } },
459
+ react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 3, sx: {
460
+ alignItems: 'flex-start',
461
+ flexWrap: 'nowrap'
462
+ } },
420
463
  react_1.default.createElement(material_1.Stack, { direction: 'column', spacing: 1, sx: { flex: `0 0 ${COL_WIDTH}px`, width: COL_WIDTH } },
421
464
  react_1.default.createElement(material_1.TextField, { label: 'Name', variant: 'standard', fullWidth: true, placeholder: 'e.g. huawei-maas, openai-prod', value: providerName, onChange: e => setProviderName(e.target.value), helperText: 'Unique identifier for this provider instance' }),
422
465
  react_1.default.createElement(material_1.FormControl, { variant: 'standard', sx: { width: '100%' } },
423
466
  react_1.default.createElement(material_1.InputLabel, null, "Type"),
424
467
  react_1.default.createElement(material_1.Select, { value: providerType, onChange: e => { setProviderType(e.target.value); if (!providerName)
425
468
  setProviderName(e.target.value); }, variant: 'standard', fullWidth: true }, props.providersAvailable.map(t => (react_1.default.createElement(material_1.MenuItem, { key: t, value: t }, t))))),
426
- react_1.default.createElement(material_1.TextField, { label: 'API Key / Token', type: showPassword ? 'text' : 'password', variant: 'standard', fullWidth: true, value: providerKey, onChange: e => setProviderKey(e.target.value), helperText: 'This key can be afterwards linked to specific uses.', InputProps: {
427
- endAdornment: (react_1.default.createElement(material_1.InputAdornment, { position: 'end' },
428
- react_1.default.createElement(material_1.IconButton, { onClick: () => setShowPassword(!showPassword), edge: 'end' }, showPassword ? react_1.default.createElement(VisibilityOff_1.default, null) : react_1.default.createElement(Visibility_1.default, null))))
469
+ react_1.default.createElement(material_1.TextField, { label: 'API Key / Token', type: showPassword ? 'text' : 'password', variant: 'standard', fullWidth: true, value: providerKey, onChange: e => setProviderKey(e.target.value), helperText: 'This key can be afterwards linked to specific uses.', slotProps: {
470
+ input: {
471
+ endAdornment: (react_1.default.createElement(material_1.InputAdornment, { position: 'end' },
472
+ react_1.default.createElement(material_1.IconButton, { onClick: () => setShowPassword(!showPassword), edge: 'end' }, showPassword ? react_1.default.createElement(VisibilityOff_1.default, null) : react_1.default.createElement(Visibility_1.default, null))))
473
+ }
429
474
  } }),
430
475
  react_1.default.createElement(material_1.TextField, { label: 'Base URL', variant: 'standard', fullWidth: true, placeholder: 'https://your-maas-host/v1', value: providerEndpoint, onChange: e => setProviderEndpoint(e.target.value), disabled: providerType !== 'openai-compat' }),
431
476
  react_1.default.createElement(material_1.Typography, { variant: 'subtitle2', sx: { pt: 1 } }, "Default model costs"),
432
- react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 1, sx: { flexWrap: 'wrap' } },
433
- react_1.default.createElement(material_1.TextField, { value: providerInputCost, onChange: e => setProviderInputCost(e.target.value === '' ? '' : +e.target.value), label: 'Input cost /M', variant: 'standard', type: 'number', sx: { flex: 1, minWidth: '110px' }, inputProps: { min: 0, step: 0.01 } }),
434
- react_1.default.createElement(material_1.TextField, { value: providerOutputCost, onChange: e => setProviderOutputCost(e.target.value === '' ? '' : +e.target.value), label: 'Output cost /M', variant: 'standard', type: 'number', sx: { flex: 1, minWidth: '110px' }, inputProps: { min: 0, step: 0.01 } })),
435
- react_1.default.createElement(material_1.Typography, { variant: 'caption', color: 'text.secondary' }, "Used by models that declare no cost of their own.")),
477
+ react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 1, sx: { flexWrap: 'nowrap' } },
478
+ react_1.default.createElement(material_1.TextField, { value: providerInputCost, onChange: e => setProviderInputCost(e.target.value === '' ? '' : +e.target.value), label: 'Input cost /M', variant: 'standard', type: 'number', sx: { flex: 1, minWidth: 0 }, slotProps: {
479
+ htmlInput: { min: 0, step: 0.01 }
480
+ } }),
481
+ react_1.default.createElement(material_1.TextField, { value: providerOutputCost, onChange: e => setProviderOutputCost(e.target.value === '' ? '' : +e.target.value), label: 'Output cost /M', variant: 'standard', type: 'number', sx: { flex: 1, minWidth: 0 }, slotProps: {
482
+ htmlInput: { min: 0, step: 0.01 }
483
+ } })),
484
+ react_1.default.createElement(material_1.Typography, { variant: 'caption', sx: {
485
+ color: 'text.secondary'
486
+ } }, "Used by models that declare no cost of their own.")),
436
487
  react_1.default.createElement(material_1.Stack, { direction: 'column', spacing: 1, sx: { flex: `0 0 ${COL_WIDTH}px`, width: COL_WIDTH } },
437
488
  react_1.default.createElement(material_1.Typography, { variant: 'subtitle2' }, "Usage limits"),
438
489
  react_1.default.createElement(UsageLimitsEditor, { value: providerLimits, onChange: setProviderLimits, subject: `this provider's key`, disabled: !providerName.trim(), usage: (_b = props.usage) === null || _b === void 0 ? void 0 : _b[providerName], durable: props.usageDurable })))),
439
- react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 1, alignItems: 'center', sx: { pt: 2 } },
490
+ react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 1, sx: {
491
+ alignItems: 'center',
492
+ pt: 2
493
+ } },
440
494
  react_1.default.createElement(material_1.Button, { variant: 'outlined', onClick: onNew }, "New"),
441
495
  props.onLoadModels && (react_1.default.createElement(material_1.Button, { variant: 'outlined', onClick: onLoadModels, disabled: !providerType || !providerKey || loadingModels, startIcon: loadingModels ? react_1.default.createElement(material_1.CircularProgress, { size: 14 }) : undefined }, loadingModels ? 'Loading...' : `Load models${pendingModels.length ? ` (${pendingModels.length})` : ''}`)),
442
- react_1.default.createElement(material_1.Typography, { flex: 1 }),
496
+ react_1.default.createElement(material_1.Typography, { sx: {
497
+ flex: 1
498
+ } }),
443
499
  react_1.default.createElement(material_1.Button, { variant: 'text', color: 'error', onClick: onRemove, disabled: selectedIndex === null }, "Remove"),
444
500
  react_1.default.createElement(material_1.Button, { variant: 'contained', onClick: onAdd, disabled: !providerName.trim() || !providerType }, selectedIndex !== null ? 'Update' : 'Add')))),
445
501
  react_1.default.createElement(material_1.DialogActions, { sx: { p: 2 } },
446
- react_1.default.createElement(material_1.Box, { flex: 1 }),
502
+ react_1.default.createElement(material_1.Box, { sx: {
503
+ flex: 1
504
+ } }),
447
505
  react_1.default.createElement(material_1.Button, { onClick: () => props.onClose(providers), variant: 'contained' }, "Save"),
448
506
  react_1.default.createElement(material_1.Button, { onClick: () => props.onClose(undefined), variant: 'outlined' }, "Cancel"))));
449
507
  };
450
508
  exports.AiConfigProvider = AiConfigProvider;
451
- const ToolSelector = ({ tools, selected, autoTools, disabled, onChange }) => (react_1.default.createElement(material_1.Stack, { direction: 'row', alignItems: 'flex-end', spacing: 1, sx: { width: '100%' } },
509
+ const ToolSelector = ({ tools, selected, autoTools, disabled, onChange }) => (react_1.default.createElement(material_1.Stack, { direction: 'row', spacing: 1, sx: {
510
+ alignItems: 'flex-end',
511
+ width: '100%'
512
+ } },
452
513
  react_1.default.createElement(material_1.FormControlLabel, { control: react_1.default.createElement(material_1.Switch, { size: 'small', checked: autoTools, onChange: e => onChange(selected, e.target.checked), disabled: disabled }), label: react_1.default.createElement(material_1.Typography, { variant: 'caption' }, "Auto"), sx: { ml: 1, mr: 0, flexShrink: 0 } }),
453
514
  react_1.default.createElement(material_1.FormControl, { variant: 'standard', fullWidth: true },
454
515
  react_1.default.createElement(material_1.InputLabel, null, "Tools"),
@@ -456,5 +517,8 @@ const ToolSelector = ({ tools, selected, autoTools, disabled, onChange }) => (re
456
517
  react_1.default.createElement(material_1.Checkbox, { size: 'small', checked: selected.includes(t.name) }),
457
518
  react_1.default.createElement(material_1.Stack, { direction: 'column' },
458
519
  react_1.default.createElement(material_1.Typography, { variant: 'body2' }, t.name),
459
- t.description && react_1.default.createElement(material_1.Typography, { variant: 'caption', color: 'text.secondary', sx: { fontSize: '0.65rem' } }, t.description)))))))));
520
+ t.description && react_1.default.createElement(material_1.Typography, { variant: 'caption', sx: {
521
+ color: 'text.secondary',
522
+ fontSize: '0.65rem'
523
+ } }, t.description)))))))));
460
524
  exports.ToolSelector = ToolSelector;
package/dist/index.d.ts CHANGED
@@ -112,6 +112,11 @@ export interface IAiToolsetInfo {
112
112
  requires: ECapability[];
113
113
  tools: IAiToolInfo[];
114
114
  }
115
+ export interface IToolsetGrant {
116
+ pluginId: string;
117
+ allTools: boolean;
118
+ tools: string[];
119
+ }
115
120
  export interface IToolsetConfig {
116
121
  activeToolsets: string[];
117
122
  disabledTools: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kwirthmagnify/kwirth-common-ai",
3
- "version": "0.5.77",
3
+ "version": "0.5.79",
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",
@@ -61,8 +61,8 @@
61
61
  },
62
62
  "devDependencies": {
63
63
  "@kwirthmagnify/kwirth-common": "^0.5.76",
64
- "@mui/icons-material": "7.1.2",
65
- "@mui/material": "7.1.2",
64
+ "@mui/icons-material": "9.5.0",
65
+ "@mui/material": "9.5.0",
66
66
  "@types/node": "^25.9.1",
67
67
  "@types/react": "^18.3.0",
68
68
  "typescript": "^5.4.0",