avantgate 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -809,19 +809,20 @@ var AvantGateControlLayer = class {
809
809
  this.config.emergencyFallback
810
810
  ].filter((provider) => Boolean(provider?.client));
811
811
  };
812
- executeSimulation = (query, systemPrompt) => {
812
+ executeSimulation = (query, systemPrompt, modelOverride) => {
813
+ const targetModel = modelOverride ?? this.config.primary.model;
813
814
  const promptTokens = Math.ceil(((systemPrompt?.length ?? 0) + query.length) / 4);
814
815
  const completionTokens = 50;
815
- const cost = this.calculateCost(this.config.primary.model, promptTokens, completionTokens);
816
+ const cost = this.calculateCost(targetModel, promptTokens, completionTokens);
816
817
  return {
817
- text: `[AvantGate In-Process Engine] Response simulation for model: ${this.config.primary.model}`,
818
+ text: `[AvantGate In-Process Engine] Response simulation for model: ${targetModel}`,
818
819
  tokens: {
819
820
  prompt: promptTokens,
820
821
  completion: completionTokens,
821
822
  total: promptTokens + completionTokens
822
823
  },
823
824
  costUSD: cost,
824
- modelUsed: this.config.primary.model,
825
+ modelUsed: targetModel,
825
826
  failoverOccurred: false,
826
827
  attempts: 1
827
828
  };
@@ -901,9 +902,6 @@ var AvantGateControlLayer = class {
901
902
  attempts: result.attempts
902
903
  });
903
904
  };
904
- /**
905
- * Exécute une requête avec garde d'entrée, masquage PII, garde pré-vol et calcul des coûts.
906
- */
907
905
  execute = async (options) => {
908
906
  const sanitizedQuery = this.applySecurityGuards(options.userQuery);
909
907
  const messages = this.buildMessages(options.systemPrompt, sanitizedQuery);
@@ -926,9 +924,6 @@ var AvantGateControlLayer = class {
926
924
  await this.notifyAuditSink(result);
927
925
  return result;
928
926
  };
929
- /**
930
- * Exécute une requête et valide/répare le résultat selon un schéma Zod.
931
- */
932
927
  executeStructured = async (options) => {
933
928
  const rawResult = await this.execute({
934
929
  userQuery: options.userQuery,
@@ -952,107 +947,147 @@ var AvantGateControlLayer = class {
952
947
  failoverOccurred: rawResult.failoverOccurred
953
948
  };
954
949
  };
955
- /**
956
- * Méthode unifiée de premier niveau pour l'extraction structurée sans code boilerplate.
957
- * Gère le failover multi-fournisseurs, les retries, la validation Zod et la normalisation financière.
958
- */
959
- generateStructuredOutput = async (options) => {
960
- const maxRetries = options.maxRetries ?? this.config.retryOptions?.maxRetries ?? 2;
961
- const modelToUse = options.model ?? this.config.primary.model;
962
- const processedMessages = options.messages.map((msg) => {
950
+ sanitizeIncomingMessages = (messages) => {
951
+ return messages.map((msg) => {
963
952
  if (msg.role === "user") {
964
953
  return { ...msg, content: this.applySecurityGuards(msg.content) };
965
954
  }
966
955
  return msg;
967
956
  });
968
- const promptLength = processedMessages.reduce((sum, msg) => sum + msg.content.length, 0);
957
+ };
958
+ verifyPromptBudget = async (messages, model) => {
959
+ const promptLength = messages.reduce((sum, msg) => sum + msg.content.length, 0);
969
960
  const estimatedPromptTokens = Math.ceil(promptLength / 4);
970
- await this.checkPreflightBudget(estimatedPromptTokens, modelToUse);
961
+ await this.checkPreflightBudget(estimatedPromptTokens, model);
962
+ };
963
+ dispatchOverrideAttempt = async (override, messages, model, temperature) => {
964
+ const res = await override.complete({ model, messages, temperature: temperature ?? 0.1 });
965
+ const usage = this.resolveTokens(res.usage, JSON.stringify(messages), res.text);
966
+ return {
967
+ responseText: res.text,
968
+ promptTokens: usage.promptTokens,
969
+ completionTokens: usage.completionTokens,
970
+ modelUsed: model,
971
+ failoverOccurred: false
972
+ };
973
+ };
974
+ dispatchSimulatedAttempt = (messages, modelOverride) => {
975
+ if (!this.config.mockSimulation) {
976
+ throw new ConfigurationError(
977
+ "[AvantGate Configuration Error] No active LLM provider configured. Provide a client implementing LLMProviderPort or configure credentials (apiKey / baseUrl)."
978
+ );
979
+ }
980
+ const sim = this.executeSimulation(JSON.stringify(messages), void 0, modelOverride);
981
+ const responseText = sim.text.includes("{") ? sim.text : JSON.stringify({ simulation: true, model: sim.modelUsed });
982
+ return {
983
+ responseText,
984
+ promptTokens: sim.tokens.prompt,
985
+ completionTokens: sim.tokens.completion,
986
+ modelUsed: sim.modelUsed,
987
+ failoverOccurred: false
988
+ };
989
+ };
990
+ dispatchPipelineAttempt = async (messages, modelOverride, temperature) => {
991
+ const output = await this.executeProviderPipeline(
992
+ messages,
993
+ JSON.stringify(messages),
994
+ temperature ?? 0.1,
995
+ modelOverride
996
+ );
997
+ return {
998
+ responseText: output.responseText,
999
+ promptTokens: output.usage.promptTokens,
1000
+ completionTokens: output.usage.completionTokens,
1001
+ modelUsed: output.modelUsed,
1002
+ failoverOccurred: output.failoverOccurred
1003
+ };
1004
+ };
1005
+ dispatchProviderAttempt = async (options, messages, targetModel) => {
1006
+ if (options.providerOverride) {
1007
+ return this.dispatchOverrideAttempt(options.providerOverride, messages, targetModel, options.temperature);
1008
+ }
1009
+ if (this.getProviderChain().length === 0) {
1010
+ return this.dispatchSimulatedAttempt(messages, options.model);
1011
+ }
1012
+ return this.dispatchPipelineAttempt(messages, options.model ?? targetModel, options.temperature);
1013
+ };
1014
+ parseAndValidateStructuredResult = (rawText, options) => {
1015
+ const sanitizedResponse = this.applyOutputSecurityGuards(rawText);
1016
+ const isFinancial = options.financialNormalizer ?? Boolean(
1017
+ this.config.features?.finance?.enableFrenchAccounting || this.config.features?.finance
1018
+ );
1019
+ const parsedData = validateWithZod(sanitizedResponse, options.schema, {
1020
+ financialNormalizer: isFinancial,
1021
+ jurisdiction: this.config.features?.finance?.jurisdiction
1022
+ });
1023
+ return { parsedData, sanitizedResponse };
1024
+ };
1025
+ buildStructuredResult = (params) => {
1026
+ const totalTokens = params.promptTokens + params.completionTokens;
1027
+ const costUSD = this.calculateCost(params.modelUsed, params.promptTokens, params.completionTokens);
1028
+ this.checkPostExecutionBudget(totalTokens, costUSD);
1029
+ return {
1030
+ data: params.data,
1031
+ rawText: params.rawText,
1032
+ tokens: {
1033
+ prompt: params.promptTokens,
1034
+ completion: params.completionTokens,
1035
+ total: totalTokens
1036
+ },
1037
+ costUSD,
1038
+ modelUsed: params.modelUsed,
1039
+ failoverOccurred: params.failoverOccurred
1040
+ };
1041
+ };
1042
+ notifyAuditSinkSafe = async (sanitizedText, result, attempts) => {
1043
+ await this.notifyAuditSink({
1044
+ text: sanitizedText,
1045
+ tokens: result.tokens,
1046
+ costUSD: result.costUSD,
1047
+ modelUsed: result.modelUsed,
1048
+ failoverOccurred: result.failoverOccurred,
1049
+ attempts
1050
+ });
1051
+ };
1052
+ waitRetryBackoff = async (attempt, maxRetries) => {
1053
+ if (attempt >= maxRetries) {
1054
+ return;
1055
+ }
1056
+ const initialDelay = this.config.retryOptions?.initialDelayMs ?? 200;
1057
+ const factor = this.config.retryOptions?.backoffFactor ?? 1.5;
1058
+ const delay = initialDelay * Math.pow(factor, attempt);
1059
+ await new Promise((resolve) => setTimeout(resolve, delay));
1060
+ };
1061
+ generateStructuredOutput = async (options) => {
1062
+ const maxRetries = options.maxRetries ?? this.config.retryOptions?.maxRetries ?? 2;
1063
+ const targetModel = options.model ?? this.config.primary.model;
1064
+ const processedMessages = this.sanitizeIncomingMessages(options.messages);
1065
+ await this.verifyPromptBudget(processedMessages, targetModel);
971
1066
  let lastError;
972
1067
  let accumulatedPromptTokens = 0;
973
1068
  let accumulatedCompletionTokens = 0;
974
- let failoverOccurred = false;
975
- let modelUsed = modelToUse;
976
1069
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
977
1070
  try {
978
- let responseText = "";
979
- let attemptPromptTokens = 0;
980
- let attemptCompletionTokens = 0;
981
- if (options.providerOverride) {
982
- const res = await options.providerOverride.complete({
983
- model: modelToUse,
984
- messages: processedMessages,
985
- temperature: options.temperature ?? 0.1
986
- });
987
- responseText = res.text;
988
- const usage = this.resolveTokens(res.usage, JSON.stringify(processedMessages), responseText);
989
- attemptPromptTokens = usage.promptTokens;
990
- attemptCompletionTokens = usage.completionTokens;
991
- modelUsed = modelToUse;
992
- } else if (this.getProviderChain().length === 0) {
993
- if (this.config.mockSimulation) {
994
- const sim = this.executeSimulation(JSON.stringify(processedMessages));
995
- responseText = sim.text;
996
- attemptPromptTokens = sim.tokens.prompt;
997
- attemptCompletionTokens = sim.tokens.completion;
998
- } else {
999
- throw new ConfigurationError(
1000
- "[AvantGate Configuration Error] No active LLM provider configured. Provide a client implementing LLMProviderPort or configure credentials (apiKey / baseUrl)."
1001
- );
1002
- }
1003
- } else {
1004
- const output = await this.executeProviderPipeline(
1005
- processedMessages,
1006
- JSON.stringify(processedMessages),
1007
- options.temperature ?? 0.1,
1008
- options.model
1009
- );
1010
- responseText = output.responseText;
1011
- attemptPromptTokens = output.usage.promptTokens;
1012
- attemptCompletionTokens = output.usage.completionTokens;
1013
- modelUsed = output.modelUsed;
1014
- failoverOccurred = output.failoverOccurred;
1015
- }
1016
- accumulatedPromptTokens += attemptPromptTokens;
1017
- accumulatedCompletionTokens += attemptCompletionTokens;
1018
- const sanitizedResponse = this.applyOutputSecurityGuards(responseText);
1019
- const isFinancial = options.financialNormalizer ?? Boolean(
1020
- this.config.features?.finance?.enableFrenchAccounting || this.config.features?.finance
1071
+ const output = await this.dispatchProviderAttempt(options, processedMessages, targetModel);
1072
+ accumulatedPromptTokens += output.promptTokens;
1073
+ accumulatedCompletionTokens += output.completionTokens;
1074
+ const { parsedData, sanitizedResponse } = this.parseAndValidateStructuredResult(
1075
+ output.responseText,
1076
+ options
1021
1077
  );
1022
- const parsedData = validateWithZod(sanitizedResponse, options.schema, {
1023
- financialNormalizer: isFinancial,
1024
- jurisdiction: this.config.features?.finance?.jurisdiction
1025
- });
1026
- const totalTokens = accumulatedPromptTokens + accumulatedCompletionTokens;
1027
- const costUSD = this.calculateCost(modelUsed, accumulatedPromptTokens, accumulatedCompletionTokens);
1028
- this.checkPostExecutionBudget(totalTokens, costUSD);
1029
- const result = {
1078
+ const result = this.buildStructuredResult({
1030
1079
  data: parsedData,
1031
1080
  rawText: sanitizedResponse,
1032
- tokens: {
1033
- prompt: accumulatedPromptTokens,
1034
- completion: accumulatedCompletionTokens,
1035
- total: totalTokens
1036
- },
1037
- costUSD,
1038
- modelUsed,
1039
- failoverOccurred
1040
- };
1041
- await this.notifyAuditSink({
1042
- text: responseText,
1043
- tokens: result.tokens,
1044
- costUSD: result.costUSD,
1045
- modelUsed: result.modelUsed,
1046
- failoverOccurred: result.failoverOccurred,
1047
- attempts: attempt + 1
1081
+ promptTokens: accumulatedPromptTokens,
1082
+ completionTokens: accumulatedCompletionTokens,
1083
+ modelUsed: output.modelUsed,
1084
+ failoverOccurred: output.failoverOccurred
1048
1085
  });
1086
+ await this.notifyAuditSinkSafe(sanitizedResponse, result, attempt + 1);
1049
1087
  return result;
1050
1088
  } catch (err) {
1051
1089
  lastError = err;
1052
- if (attempt < maxRetries) {
1053
- const delay = (this.config.retryOptions?.initialDelayMs ?? 200) * Math.pow(this.config.retryOptions?.backoffFactor ?? 1.5, attempt);
1054
- await new Promise((resolve) => setTimeout(resolve, delay));
1055
- }
1090
+ await this.waitRetryBackoff(attempt, maxRetries);
1056
1091
  }
1057
1092
  }
1058
1093
  throw lastError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "avantgate",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "Zero-infrastructure, in-process AI Application Firewall (AI-WAF) & privacy control plane for TypeScript: real-time prompt guardrails, zero-egress PII redaction, agent tool isolation, anti-IDOR defense, pre-flight token budgets, and multi-model failover.",
5
5
  "author": "Gatewall Team",
6
6
  "license": "MIT",
@@ -90,18 +90,19 @@
90
90
  "test:pii": "tsx tests/pii-extended.test.ts",
91
91
  "test:agent": "tsx tests/agent/step-runner.test.ts && tsx tests/agent/isolated-tool.test.ts && tsx tests/agent/dto-pattern.test.ts && tsx tests/agent/tool-patterns.test.ts && tsx tests/agent/storage-adapters.test.ts && tsx tests/agent/tool-aliasing.test.ts && tsx tests/agent/tool-chaining.test.ts && tsx tests/agent/tool-storage.test.ts && tsx tests/agent/telemetry-exporter.test.ts && tsx tests/agent/platform-adapter.test.ts && tsx tests/agent/tool-governance.test.ts && tsx tests/agent/tool-impact.test.ts",
92
92
  "test:workflow": "tsx tests/workflow/workflow-saga.test.ts && tsx tests/workflow/workflow-abort.test.ts",
93
- "test:client": "tsx tests/client/browser-exporter.test.ts",
93
+ "test:client": "tsx tests/client/browser-exporter.test.ts && tsx tests/client/use-avantgate-task.test.ts && tsx tests/client/task-runner.test.ts",
94
94
  "test:demo": "tsx tests/agent/prospect-ai-demo-scenario.test.ts",
95
95
  "gatewall": "npm --prefix gatewall run dev",
96
96
  "gatewall:dev": "npm --prefix gatewall run dev",
97
97
  "gatewall:build": "npm --prefix gatewall run build",
98
+ "gatewall:seed": "npm --prefix gatewall run seed:mock",
98
99
  "gatewall:start": "npm --prefix gatewall run start",
99
100
  "gatewall:docker": "docker compose up -d",
100
101
  "lint": "tsc --noEmit",
101
102
  "prepublishOnly": "npm run build && npm test"
102
103
  },
103
104
  "dependencies": {
104
- "zod": "^3.23.0 || ^4.0.0"
105
+ "zod": "^4.6.5"
105
106
  },
106
107
  "devDependencies": {
107
108
  "@types/node": "^26.6.2",
@@ -1,14 +0,0 @@
1
- import { type TrackSecurityAlertDetails, type TrackDataRenderedOptions, type TrackFeedbackOptions } from "./client";
2
- import type { BrowserTelemetryExporterConfig, ClientSecurityAlertEvent } from "./types";
3
- export type { TrackSecurityAlertDetails, TrackDataRenderedOptions, TrackFeedbackOptions, };
4
- /**
5
- * Lightweight React Hook for front-end telemetry and client-side security event tracking.
6
- * Encapsulates lifecycle management, useRef persistence, useCallback and useMemo optimization.
7
- */
8
- export declare const useAvantGateTelemetry: (config: BrowserTelemetryExporterConfig) => {
9
- trackSecurityAlert: (alertType: ClientSecurityAlertEvent["alertType"], details: TrackSecurityAlertDetails) => void;
10
- trackClientDataRendered: (toolId: string, options?: TrackDataRenderedOptions) => void;
11
- trackFeedback: (feedback: TrackFeedbackOptions) => void;
12
- exporter: import("./browser-exporter").BrowserTelemetryExporter | undefined;
13
- };
14
- //# sourceMappingURL=useAvantGateTelemetry.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAvantGateTelemetry.d.ts","sourceRoot":"","sources":["../../src/client/useAvantGateTelemetry.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,yBAAyB,EAC9B,KAAK,wBAAwB,EAC7B,KAAK,oBAAoB,EAC1B,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EACV,8BAA8B,EAC9B,wBAAwB,EACzB,MAAM,SAAS,CAAC;AAEjB,YAAY,EACV,yBAAyB,EACzB,wBAAwB,EACxB,oBAAoB,GACrB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,qBAAqB,GAAI,QAAQ,8BAA8B;oCAuB3D,wBAAwB,CAAC,WAAW,CAAC,WACvC,yBAAyB,KACjC,IAAI;sCAQG,MAAM,YACJ,wBAAwB,KACjC,IAAI;8BAOI,oBAAoB,KAAG,IAAI;;CAezC,CAAC"}