avantgate 1.1.0 → 1.1.1

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/README.md CHANGED
@@ -7,6 +7,7 @@
7
7
  [![TypeScript](https://img.shields.io/badge/TypeScript-Strict-blue?logo=typescript)](https://www.typescriptlang.org/)
8
8
  [![Zod Native](https://img.shields.io/badge/Schema-Zod%20Native-orange)](https://zod.dev/)
9
9
  [![Zero Infra](https://img.shields.io/badge/Infrastructure-Zero%20Servers-emerald)](#why-avantgate)
10
+ [![avantGate Cloud](https://img.shields.io/badge/avantGate%20Cloud-Coming%20Soon-8A2BE2)](#-avantgate-cloud-coming-soon)
10
11
 
11
12
  ---
12
13
 
@@ -33,6 +34,14 @@ flowchart LR
33
34
 
34
35
  ---
35
36
 
37
+ ## ☁️ AvantGate Cloud *(Coming Soon)*
38
+
39
+ For engineering teams running autonomous agents in production, **AvantGate Cloud** will provide an optional centralized control plane (remote telemetry ingestion, team-wide cost visibility, and human-in-the-loop approval workflows) that connects directly to the open-source SDK with zero friction.
40
+
41
+ > 🚀 **Interested in private preview or enterprise VPC deployment?** Contact us at [contact@lextalk.fr](mailto:contact@lextalk.fr) for early access.
42
+
43
+ ---
44
+
36
45
  ## 🚀 Key Features
37
46
 
38
47
  - 💰 **Pre-Flight Token Budgeting**: Rejects or truncates requests exceeding budget *before* invoking external APIs.
@@ -40,6 +49,8 @@ flowchart LR
40
49
  - 🛡️ **Active Security & PII Redaction**: In-flight masking of emails, phone numbers, and French/EU identifiers before sending to cloud providers. Blocks prompt injection & jailbreaks.
41
50
  - 🔀 **Zero-Downtime Multi-Model Failover**: If DeepSeek or Mistral returns HTTP 429/500, seamlessly failover to a backup provider (or local Ollama) in milliseconds.
42
51
  - 🔧 **Self-Repairing Structured Outputs**: Strict Zod runtime validation with automated markdown/JSON repair if the LLM hallucinates formatting.
52
+ - 🤖 **Durable Agent Harness & PII Shield (`avantgate/agent`)**: Serverless memoized step execution (`step.run()`), native Human-in-the-Loop approval (`step.waitForApproval()`), and Dual-Channel tool data isolation without Temporal or Redis.
53
+ - 📡 **Zero-Dependency Telemetry Bridge (`HttpTelemetryExporter`, `PlatformStorageAdapter`)**: Mirror in-process executions and hierarchical tool traces asynchronously to any HTTP sink or observability endpoint with $0 external npm dependencies.
43
54
  - 📦 **100% Framework Agnostic**: Works in Next.js, Express, Fastify, NestJS, Cloudflare Workers, AWS Lambda, or CLI scripts.
44
55
 
45
56
  ---
@@ -54,7 +65,11 @@ flowchart LR
54
65
  | **In-Flight PII Redaction** | ❌ Logs all raw data | ✅ **Automatic local masking** before API dispatch |
55
66
  | **Multi-Provider Failover** | ❌ No | ✅ **Built-in Fallback Router & Exponential Retry** |
56
67
  | **Zod Schema Auto-Repair** | ❌ No | ✅ **Built-in JSON Heuristic Repair** |
68
+ | **Durable Workflow & HITL** | Requires Temporal / Inngest | ✅ **Built-in In-Process Step Runner & HITL** |
69
+ | **Tool PII & Dual-Channel** | ❌ No | ✅ **Built-in `createIsolatedTool`** |
57
70
  | **Telemetry Network Latency** | ❌ +50ms - 200ms per trace call | ✅ **0 ms** (In-process memory accounting) |
71
+ | **Central Web Dashboard** | Heavy self-hosted web app | ✅ **Optional Remote Sink** (Plug any HTTP endpoint via `PlatformStorageAdapter`) |
72
+ | **Hierarchical Session Replay** | ❌ Flat span waterfall | ✅ **Causality Tree + Dual-Channel Isolation** |
58
73
 
59
74
  ---
60
75
 
@@ -68,6 +83,14 @@ pnpm add avantgate zod
68
83
  yarn add avantgate zod
69
84
  ```
70
85
 
86
+ ### 🧩 Subpath Exports
87
+
88
+ | Import Path | Description |
89
+ |---|---|
90
+ | `avantgate` | Core control plane: token budgets, cost ledger, prompt guards, multi-model failover & Zod repair. |
91
+ | `avantgate/finance` | Financial data normalizer (accounting parentheses, EU/US/UK/CH currencies & magnitudes). |
92
+ | `avantgate/agent` | *(Preview / Experimental)* Durable step runner, Human-in-the-Loop, dual-channel PII tool isolation & storage adapters. |
93
+
71
94
  ---
72
95
 
73
96
  ## 🛠️ Quickstart
@@ -206,7 +229,70 @@ try {
206
229
 
207
230
  ---
208
231
 
209
- ### 4. In-Process Prompt Engine (`PromptTemplate`, `PromptBuilder`, `PromptRegistry`)
232
+ ### 5. Pre-Flight Budget Guarding (`maxTokenBudget` & `maxCostUSD`)
233
+
234
+ AvantGate enforces financial and resource limits **before** making external API calls. If a prompt or estimated cost exceeds your budget, it fails immediately with a `BudgetExceededError`, avoiding wasted spend:
235
+
236
+ ```typescript
237
+ import { createAvantGate, BudgetExceededError } from "avantgate";
238
+
239
+ const control = createAvantGate({
240
+ primary: { provider: "deepseek", model: "deepseek-chat", apiKey: process.env.DEEPSEEK_API_KEY! },
241
+ maxTokenBudget: 500, // Maximum allowed tokens for request + completion
242
+ maxCostUSD: 0.005, // Block if estimated input cost exceeds half a cent
243
+ });
244
+
245
+ try {
246
+ await control.execute({
247
+ userQuery: "Exhaustive contract legal analysis...",
248
+ });
249
+ } catch (error) {
250
+ if (error instanceof BudgetExceededError) {
251
+ console.warn("Blocked by AvantGate Pre-Flight Budget Guard:", error.message);
252
+ }
253
+ }
254
+ ```
255
+
256
+ ---
257
+
258
+ ### 6. Decoupled Token Pricing & Database Adapter (`PricingAdapter`, `PricingRegistry`)
259
+
260
+ Token prices vary across distributors (`openrouter`, `mistral`, `deepseek`, `azure`). AvantGate eliminates hardcoded pricing: you can dynamically plug your own database (Prisma, PostgreSQL, etc.) with in-memory TTL caching for **0 ms overhead**:
261
+
262
+ ```typescript
263
+ import { createAvantGate, type PricingAdapter, PricingRegistry } from "avantgate";
264
+ import { prisma } from "@/lib/prisma";
265
+
266
+ // 1. Connect your database with automatic in-memory TTL caching (5 minutes)
267
+ const control = createAvantGate({
268
+ primary: { provider: "deepseek", model: "deepseek-chat", apiKey: process.env.DEEPSEEK_API_KEY! },
269
+ pricingAdapter: {
270
+ async fetchPrice(model, provider) {
271
+ const dbPrice = await prisma.modelPricing.findFirst({
272
+ where: { model, distributor: provider, isActive: true },
273
+ });
274
+ if (!dbPrice) return undefined; // Falls back to default registry
275
+ return {
276
+ promptUSDPerMillion: Number(dbPrice.promptPriceUSDPerM),
277
+ completionUSDPerMillion: Number(dbPrice.completionPriceUSDPerM),
278
+ };
279
+ },
280
+ },
281
+ pricingCacheTtlMs: 5 * 60 * 1000,
282
+ });
283
+
284
+ // 2. Or override distributor prices globally at runtime
285
+ PricingRegistry.registerPrice("openrouter/deepseek/deepseek-chat", {
286
+ promptUSDPerMillion: 0.18,
287
+ completionUSDPerMillion: 0.35,
288
+ });
289
+ ```
290
+
291
+ > 📖 **Deep Dive & Production DB Setup** : Consultez le guide complet [docs/pricing.md](docs/pricing.md) pour les schémas Prisma, Drizzle, invalidation de cache à chaud, et scripts de seed.
292
+
293
+ ---
294
+
295
+ ### 7. In-Process Prompt Engine (`PromptTemplate`, `PromptBuilder`, `PromptRegistry`)
210
296
 
211
297
  Assemble prompts systematically with strict token slots, KV-cache prefix hits, automated Zod output contracts, and jailbreak guardrails.
212
298
 
@@ -248,7 +334,7 @@ const messages = builder.toMessages();
248
334
 
249
335
  ---
250
336
 
251
- ### 5. Modular Financial Normalizer & Accounting Strategies (`avantgate/finance`)
337
+ ### 8. Modular Financial Normalizer & Accounting Strategies (`avantgate/finance`)
252
338
 
253
339
  Opt-in, zero-overhead financial accounting module. Automatically normalizes negative parentheses `(150 000)` ➔ `-150000`, magnitudes (`1 850 k€` ➔ `1850000`), European decimal commas, and currency symbols across jurisdictions (**FR PCG / Cerfa**, **US GAAP**, **UK IFRS**, **Swiss CO**).
254
340
 
@@ -283,7 +369,7 @@ const data = validateWithZod(rawLLMText, schema, { financialNormalizer: true, ju
283
369
 
284
370
  ---
285
371
 
286
- ### 6. Unified `generateStructuredOutput` with Multi-Provider Failover
372
+ ### 9. Unified `generateStructuredOutput` with Multi-Provider Failover
287
373
 
288
374
  Extract type-safe data with zero boilerplate. Automatically handles failover, retries, cost tracking, and financial repair:
289
375
 
@@ -303,6 +389,107 @@ console.log(result.modelUsed); // Final provider model that succeeded
303
389
 
304
390
  ---
305
391
 
392
+ ### 10. Durable Agent Harness & Dual-Channel Tool Isolation (`avantgate/agent`)
393
+
394
+ > [!WARNING]
395
+ > **NOT USED IN PRODUCTION / EXPERIMENTAL PREVIEW**
396
+ > The `avantgate/agent` submodule is currently in developer preview and is **NOT intended for production workloads**. Internal APIs, causality tracing, and storage contracts are subject to breaking changes. For production environments, use the core control plane (`avantgate`) and financial normalizers (`avantgate/finance`).
397
+
398
+ Deploy stateful TypeScript agents without spinning up Temporal, Inngest, or Redis queues:
399
+
400
+ ```typescript
401
+ import { createIsolatedTool, createStepRunner, StepSuspendedError } from "avantgate/agent";
402
+ import { z } from "zod";
403
+
404
+ // 1. Dual-Channel Isolated Tool (Automatic PII redaction + direct UI client streaming)
405
+ const fetchClientDataTool = createIsolatedTool({
406
+ name: "fetch_client_data",
407
+ description: "Fetches corporate client dossier",
408
+ parameters: z.object({ clientId: z.string() }),
409
+ async execute({ clientId }) {
410
+ return {
411
+ clientId,
412
+ ssn: "1 85 12 75 108 123 45", // Auto-redacted before reaching LLM!
413
+ email: "finance@corp.fr",
414
+ turnover: 1500000,
415
+ };
416
+ },
417
+ // Rich data sent directly to the client UI (out-of-band)
418
+ toClientData(data) {
419
+ uiSocket.emit("client_dossier", data);
420
+ },
421
+ // Safe minimal summary for LLM context window (saves tokens and protects privacy)
422
+ toLLMSummary(data) {
423
+ return { clientId: data.clientId, note: "Dossier dispatched to UI" };
424
+ },
425
+ });
426
+
427
+ // 2. Serverless Durable Step Execution & Human-in-the-Loop (HITL)
428
+ const runner = createStepRunner({ workflowId: "wf-deal-42" });
429
+
430
+ try {
431
+ // Idempotent execution: memoized and skipped on re-run if already completed
432
+ const scoring = await runner.run("risk-assessment", async () => {
433
+ return await computeRiskScore();
434
+ });
435
+
436
+ // Suspends execution cleanly until human validation
437
+ const approval = await runner.waitForApproval("director-signature", {
438
+ metadata: { dealAmount: 250000 },
439
+ });
440
+
441
+ // Continues seamlessly after approval
442
+ await runner.run("finalize-deal", async () => {
443
+ return await commitContract(approval);
444
+ });
445
+ } catch (error) {
446
+ if (error instanceof StepSuspendedError) {
447
+ console.log(`Workflow paused at step [${error.stepId}] awaiting human validation.`);
448
+ }
449
+ }
450
+ ```
451
+
452
+ > 📖 **Full Agent Documentation & Storage Adapters (Memory, Custom, Key-Value, Prisma, SQLite)**: [docs/agent.md](docs/agent.md)
453
+
454
+ ---
455
+
456
+ ### 11. Streaming Telemetry to an External Sink (Observability & Replay)
457
+
458
+ Connect your agents to an external observability sink or custom webhook in 2 lines of code. It persists locally first, and streams telemetry in the background with **zero performance impact**:
459
+
460
+ ```typescript
461
+ import {
462
+ PlatformStorageAdapter,
463
+ SQLiteStorageAdapter,
464
+ HttpTelemetryExporter,
465
+ createStepRunner,
466
+ } from "avantgate/agent";
467
+ import Database from "better-sqlite3";
468
+
469
+ // 1. Configure the non-blocking background telemetry exporter
470
+ const exporter = new HttpTelemetryExporter({
471
+ apiKey: process.env.AVANTGATE_API_KEY,
472
+ endpoint: "https://telemetry.your-domain.com/api/v1/events",
473
+ agentName: "prospect-qualifier",
474
+ batchIntervalMs: 5000,
475
+ });
476
+
477
+ // 2. Hybrid Hexagonal Adapter: SQLite local durability + Remote mirror
478
+ const storage = new PlatformStorageAdapter({
479
+ primaryStorage: new SQLiteStorageAdapter(new Database("agent.db")),
480
+ exporter,
481
+ });
482
+
483
+ // 3. StepRunner with unified runId for FinOps & Session Replay
484
+ const runner = createStepRunner({
485
+ workflowId: "deal-pipeline-42",
486
+ runId: "run-2026-09-13-alpha",
487
+ storage,
488
+ });
489
+ ```
490
+
491
+ ---
492
+
306
493
  ## 🏗️ Architecture & Extensibility
307
494
 
308
495
  AvantGate is built around clean **Ports and Adapters**:
@@ -365,17 +552,26 @@ npm test
365
552
 
366
553
  ## 🙏 Acknowledgements & Credits
367
554
 
368
- AvantGate builds upon foundational ideas and inspirations from the open source AI engineering community:
555
+ AvantGate builds upon foundational ideas and inspirations from the open source AI engineering and durable execution communities:
556
+
557
+ ### 🛡️ In-Process Control & Production Layers
369
558
  - Special credit to [**Emmimal/control-layer**](https://github.com/Emmimal/control-layer) for pioneering the in-process control layer architecture.
370
559
  - Valuable insights and launch safety principles inspired by [**ShipYourAI.com**](https://shipyourai.com).
371
-
372
- ### 📚 Related Series — Production Layers for LLM Systems (by Emmimal)
373
- AvantGate is inspired by and designed to compose with the production layers series:
374
560
  - **[context-engine](https://github.com/Emmimal/context-engine)** — Retrieval, re-ranking, memory decay, and token budget control for RAG systems. *The control layer handles what the model returns. The context engine handles what it receives. They compose.*
375
561
  - **[RAG Is Blind to Time — Temporal Layer](https://github.com/Emmimal/temporal-layer)** — Temporal awareness layer for RAG systems that treats time as a first-class retrieval signal.
376
562
  - **[LLM Evals Are Based on Vibes — Evaluation Layer](https://github.com/Emmimal/eval-layer)** — Evaluation layer that replaces gut-feel shipping decisions with measurable output quality gates.
377
563
  - **[PyTorch NaNs Are Silent Killers — NaN Catch Hook](https://github.com/Emmimal/nan-hook)** — Lightweight hook that catches NaN propagation at the exact layer it originates, in under 3ms overhead.
378
564
 
565
+ ### 📊 FinOps & Observability Platforms
566
+ - **[Helicone](https://github.com/Helicone/helicone)** — Pioneering LLM request caching, granular cost estimation, and developer-first proxy design that inspired our FinOps engine and semantic tool caching patterns.
567
+ - **[AgentOps](https://github.com/AgentOps-AI/agentops)** — State-of-the-art agent tracking, session replay visualization, and recursive loop detection that inspired our Session Replay and Infinite Loop Shield.
568
+
569
+ ### 🤖 Durable Workflows & Agent Architecture (`avantgate/agent`)
570
+ - **[Inngest](https://www.inngest.com)** & **[Temporal](https://temporal.io)** — The developer experience of durable step memoization (`step.run()`) and human validation pauses (`step.waitForApproval()`), reimagined here as a **$0-infrastructure, serverless in-process harness** without requiring external worker queues or Redis clusters.
571
+ - **[Vercel AI SDK (`ai`)](https://sdk.vercel.ai)** — Standardized TypeScript tool schema contracts (`parameters`, `execute`) natively embraced and augmented by `createIsolatedTool`.
572
+ - **Least-Privilege & Dual-Channel Isolation** — Security patterns separating sensitive payload data (streamed out-of-band directly to trusted user interfaces) from LLM prompts (receiving sanitized summaries), preventing context pollution and PII leakage.
573
+ - **Alistair Cockburn's Ports & Adapters (Hexagonal Architecture)** — Pure domain isolation enabling developers to plug any database (Prisma, SQLite, Drizzle, Kysely, Mongo, Redis) with zero hard framework dependencies.
574
+
379
575
  ---
380
576
 
381
577
  ## 📜 License