avantgate 2.0.0 → 2.1.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # 🛡️ AvantGate (`avantgate`)
2
2
 
3
- > **The Zero-Infrastructure, In-Process AI Application Firewall (AI-WAF), Deterministic Workflow Engine & Privacy Guard for TypeScript.**
4
- > Real-time prompt guardrails, zero-egress PII redaction, deterministic Saga workflows, anti-IDOR tool boundary, and pre-flight token defense **without hosting Docker, proxies, PostgreSQL, ClickHouse, or Redis.**
3
+ > **The Zero-Infrastructure, In-Process AI Application Firewall (AI-WAF), Deterministic Workflow Engine, Privacy Guard & Headless UI Canvas for TypeScript.**
4
+ > Real-time prompt guardrails, zero-egress PII redaction, deterministic Saga workflows, canonical tool envelopes, anti-IDOR tool boundary, and pre-flight token defense **without hosting Docker, proxies, PostgreSQL, ClickHouse, or Redis.**
5
5
 
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
7
  [![TypeScript](https://img.shields.io/badge/TypeScript-Strict-blue?logo=typescript)](https://www.typescriptlang.org/)
@@ -73,7 +73,7 @@ bun run dev # or npm run dev
73
73
  | **🛡️ Loop Shield (Anti-Cycle Guard)** | Early visual detection of recursive agent loops and aberrant repetitive tool execution cycles. |
74
74
  | **💾 Zero-External-DB SQLite Storage** | Zero setup overhead: persistent storage uses embedded SQLite (`gatewall/data/gatewall.db`) without requiring PostgreSQL, Redis, or ClickHouse. |
75
75
 
76
- > 💡 **Agent Integration Recipes:** See [Connecting an Agent to GateWall Cockpit](docs/examples.md#12-connecting-an-agent-to-gatewall-cockpit-gatewall) in `docs/examples.md` for complete code recipes using `HttpTelemetryExporter` (`avantgate/agent`), direct HTTP ingestion, and React front-end streaming (`avantgate/client`).
76
+ > 💡 **Agent Integration Recipes:** See [GateWall Telemetry Recipe](examples/observability/10-gatewall-telemetry.ts) and [Integration Cookbook](examples/README.md) for complete code recipes using `HttpTelemetryExporter` (`avantgate/agent`), direct HTTP ingestion, and React front-end streaming (`avantgate/client`).
77
77
 
78
78
  ---
79
79
 
@@ -92,6 +92,7 @@ Contact our team at [contact@gatewall.fr](mailto:contact@gatewall.fr) for privat
92
92
  | 🛑 **Agent Isolation & Anti-IDOR** | • **Dual-Channel DTOs**: Streams full records to UI while injecting sanitized summaries into LLM.<br/>• **Anti-IDOR Boundary**: Compile-time tenant scoping (`createTenantTool`) & runtime ownership checks.<br/>• **Server Idempotency Guard**: Zero-infra in-process guard (`withServerIdempotency`) with memory or storage adapters.<br/>• **Infinite Loop Shield**: Detects and breaks recursive agent tool execution loops. |
93
93
  | 💰 **FinOps & Resilience** | • **Denial-of-Wallet**: Enforces hard token & USD budgets *before* external inference spend.<br/>• **Multi-Model Failover**: Instant client-side routing to fallback models or local Ollama on 429/500.<br/>• **FinOps Batch Deduplication**: Prevents double-counting of tokens & costs during network retries on GateWall.<br/>• **Live Cost Ledger**: Token burn calculation & pricing adapters with zero external DB. |
94
94
  | ⚡ **Sagas, Replay & Telemetry** | • **Deterministic Sagas (`avantgate/workflow`)**: In-process FSM with automatic reverse compensation ($k-1 \to 0$).<br/>• **In-Context Replay (`avantgate/client`)**: React hook (`useTask`) with causal parent linkage (`parentRunId`) & `Idempotency-Key`.<br/>• **Human-in-the-Loop (HITL)**: Non-blocking suspension, approval queues & fail-closed 24h SLA timeout (TTL).<br/>• **Lightweight Telemetry**: < 1.7 KB client SDK & async audit bridge to GateWall. |
95
+ | 🎨 **Presentation Plane (`avantgate/ui`)** | • **Canonical Tool Envelopes**: Typed format carrying merge strategies (`REPLACE`, `APPEND_UNIQUE`, `UPDATE_ENTITY`) & `UIIntent`.<br/>• **Deterministic Concurrency Reducer**: Algebraic $O(N)$ Set-based convergence solving parallel tool calling races.<br/>• **React View Registry (`avantgate/ui/react`)**: Polymorphic $O(1)$ dynamic dispatch linking tools to your design system (shadcn/ui).<br/>• **Native Anti-XSS Guard**: Zero-dependency WHATWG `URL` scanner neutralizing `javascript:` & protocol-relative (`//evil.com`) vectors. |
95
96
 
96
97
  ---
97
98
 
@@ -99,14 +100,15 @@ Contact our team at [contact@gatewall.fr](mailto:contact@gatewall.fr) for privat
99
100
 
100
101
  | Category | In-Depth Guides |
101
102
  |---|---|
102
- | 🚀 **Quickstart** | [Getting Started](docs/getting-started.md) • [Integration Cookbook](docs/examples.md) |
103
+ | 🚀 **Quickstart** | [Getting Started](docs/getting-started.md) • [Integration Cookbook](examples/README.md) |
103
104
  | 🛡️ **Security & AI-WAF** | [Prompt Guardrails](docs/security/prompt-guardrails.md) • [PII Redaction](docs/security/pii-redaction.md) • [Anti-IDOR Defense](docs/security/anti-idor.md) • [End-to-End Security](docs/security/end-to-end-security.md) |
104
105
  | 💰 **FinOps & Cost** | [Pre-Flight Budget Guards](docs/finops/budget-guards.md) • [Pricing Adapters & SQLite](docs/finops/pricing-adapters.md) |
105
106
  | 🤖 **Agents & Tools** | [Isolated Tools & DTOs](docs/agents/isolated-tools.md) • [Agent Runtime Manual](docs/agents/agent-runtime.md) • [Inter-Tool Chaining](docs/agents/inter-tool-chaining.md) |
106
107
  | 🔄 **Deterministic Sagas** | [Durable Workflows Engine](docs/workflows/durable-workflows.md) |
107
108
  | 📊 **Observability & Cockpit** | [GateWall Cockpit Console](docs/observability/gatewall-cockpit.md) • [Telemetry & Browser SDK](docs/observability/telemetry-and-browser-sdk.md) • [GateWall vs. Temporal](docs/observability/temporal-and-gatewall.md) |
108
109
  | 💶 **Accounting** | [Financial Normalizer](docs/finance/normalizer.md) |
109
- | 🚀 **Release Notes** | [v2.0.0 Release Notes](docs/release/release-2.0.0.md) • [v1.9.0 Release Notes](docs/release/release-1.9.0.md) |
110
+ | 🎨 **Presentation Plane** | [Headless UI Canvas & React Bindings](docs/ui/headless-canvas.md) |
111
+ | 🚀 **Release Notes** | [v2.1.0 Release Notes](docs/release/release-2.1.0.md) • [v2.0.0 Release Notes](docs/release/release-2.0.0.md) • [v1.9.0 Release Notes](docs/release/release-1.9.0.md) |
110
112
 
111
113
  ---
112
114
 
@@ -125,6 +127,7 @@ Contact our team at [contact@gatewall.fr](mailto:contact@gatewall.fr) for privat
125
127
  | **Multi-Model Failover** | ❌ App crashes | ⚠️ Proxy-dependent | ✅ **Built-in Fallback Router & Exponential Retry** |
126
128
  | **Zod Schema Auto-Repair** | ❌ No | ❌ No | ✅ **Built-in JSON Heuristic Repair** |
127
129
  | **Hierarchical Session Replay** | ❌ None | ⚠️ Flat span waterfall | ✅ **Causality Tree + In-Context Replay (`useTask`)** |
130
+ | **Headless UI Canvas State** | ❌ Manual parsing | ❌ Not supported | ✅ **Canonical Envelopes + Parallel Reducer (`avantgate/ui`)** |
128
131
 
129
132
  ---
130
133
 
@@ -140,13 +143,17 @@ yarn add avantgate zod
140
143
 
141
144
  ### 🧩 Subpath Exports
142
145
 
143
- | Import Path | Description |
144
- |---|---|
145
- | `avantgate` | Core control plane: token budgets, cost ledger, prompt guards, multi-model failover & Zod repair. |
146
- | `avantgate/finance` | Financial data normalizer (accounting parentheses, EU/US/UK/CH currencies & magnitudes). |
147
- | `avantgate/agent` | Durable step runner, Human-in-the-Loop, dual-channel PII tool isolation, server idempotency (`withServerIdempotency`), & storage adapters. |
148
- | `avantgate/workflow` | Deterministic sequential state machine, automatic reverse Saga rollback, durable HITL checkpoints & agent tool conversion. |
149
- | `avantgate/client` | Front-end SDK (< 1.7 KB) with in-context task replay (`useTask`, `createTaskRunner`), causal idempotency helpers (`getIdempotencyHeaders`), & GateWall telemetry adapter. |
146
+ | Import Path | Description | Documentation |
147
+ |---|---|---|
148
+ | `avantgate` | Core control plane: token budgets, cost ledger, prompt guards, multi-model failover & Zod repair. | [Getting Started](docs/getting-started.md) |
149
+ | `avantgate/finance` | Financial data normalizer (accounting parentheses, EU/US/UK/CH currencies & magnitudes). | [Financial Normalizer](docs/finance/normalizer.md) |
150
+ | `avantgate/agent` | Durable step runner, Human-in-the-Loop, dual-channel PII tool isolation, server idempotency (`withServerIdempotency`), & storage adapters. | [Isolated Tools & DTOs](docs/agents/isolated-tools.md) |
151
+ | `avantgate/workflow` | Deterministic sequential state machine, automatic reverse Saga rollback, durable HITL checkpoints & agent tool conversion. | [Durable Workflows](docs/workflows/durable-workflows.md) |
152
+ | `avantgate/client` | Front-end SDK (< 1.7 KB) with in-context task replay (`useTask`, `createTaskRunner`), causal idempotency helpers (`getIdempotencyHeaders`), & GateWall telemetry adapter. | [Telemetry & Browser SDK](docs/observability/telemetry-and-browser-sdk.md) |
153
+ | `avantgate/ui` | Headless UI canvas core (< 2.5 KB): canonical tool envelopes, deterministic $O(N)$ parallel reducer, `defineCanvas` factory. | [Headless UI Canvas](docs/ui/headless-canvas.md) |
154
+ | `avantgate/ui/react` | React presentation plane: polymorphic $O(1)$ view registry (`createViewRegistry`), `CanvasRenderer`, & anti-XSS URL sanitizer (`isValidSafeUrl`). | [Headless UI Canvas](docs/ui/headless-canvas.md) |
155
+
156
+ > 💡 **UI Canvas Cookbook:** See [Headless UI Canvas & React Bindings](docs/ui/headless-canvas.md) for complete step-by-step recipes connecting agent tools with typed envelopes and custom React views (shadcn/ui, Tailwind).
150
157
 
151
158
  ---
152
159
 
@@ -0,0 +1,6 @@
1
+ import { type ToolExecutionEnvelope } from "./envelope";
2
+ export declare const defineCanvas: <TContentMap extends Record<string, unknown>>() => {
3
+ createEnvelope: <K extends Extract<keyof TContentMap, string>>(options: Omit<ToolExecutionEnvelope<TContentMap[K], K>, "version">) => ToolExecutionEnvelope<TContentMap[K], K>;
4
+ canvasReducer: (currentState: import("./reducer").CanvasState<TContentMap> | null | undefined, envelope: ToolExecutionEnvelope<unknown, Extract<keyof TContentMap, string>>) => import("./reducer").CanvasState<TContentMap>;
5
+ };
6
+ //# sourceMappingURL=define-canvas.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define-canvas.d.ts","sourceRoot":"","sources":["../../src/ui/define-canvas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAG5E,eAAO,MAAM,YAAY,GAAI,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;qBAEnD,CAAC,SAAS,OAAO,CAAC,MAAM,WAAW,EAAE,MAAM,CAAC,WAClD,IAAI,CAAC,qBAAqB,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,SAAS,CAAC,KACjE,qBAAqB,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;;CAM9C,CAAC"}
@@ -0,0 +1,19 @@
1
+ export type ToolMergeStrategy = "REPLACE" | "APPEND_UNIQUE" | "UPDATE_ENTITY";
2
+ export type UIIntentAction = "HIGHLIGHT" | "SELECT" | "OPEN_MODAL" | "NAVIGATE";
3
+ export interface UIIntent {
4
+ action: UIIntentAction;
5
+ targetId: string;
6
+ targetType: "prospect" | "company" | "task" | "event" | string;
7
+ metadata?: Record<string, unknown>;
8
+ }
9
+ export interface ToolExecutionEnvelope<TPayload = unknown, TKind extends string = string> {
10
+ readonly version: 1;
11
+ readonly toolId: string;
12
+ readonly kind: TKind;
13
+ readonly mergeStrategy: ToolMergeStrategy;
14
+ readonly dedupeKey?: string;
15
+ readonly uiIntent?: UIIntent;
16
+ readonly data: TPayload;
17
+ }
18
+ export declare const createToolEnvelope: <TKind extends string, TPayload>(options: Omit<ToolExecutionEnvelope<TPayload, TKind>, "version">) => ToolExecutionEnvelope<TPayload, TKind>;
19
+ //# sourceMappingURL=envelope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../../src/ui/envelope.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,iBAAiB,GAAG,SAAS,GAAG,eAAe,GAAG,eAAe,CAAC;AAE9E,MAAM,MAAM,cAAc,GAAG,WAAW,GAAG,QAAQ,GAAG,YAAY,GAAG,UAAU,CAAC;AAEhF,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,cAAc,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,UAAU,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC/D,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,MAAM,WAAW,qBAAqB,CAAC,QAAQ,GAAG,OAAO,EAAE,KAAK,SAAS,MAAM,GAAG,MAAM;IACtF,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IACpB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,aAAa,EAAE,iBAAiB,CAAC;IAC1C,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;CACzB;AAED,eAAO,MAAM,kBAAkB,GAAI,KAAK,SAAS,MAAM,EAAE,QAAQ,EAC/D,SAAS,IAAI,CAAC,qBAAqB,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,SAAS,CAAC,KAC/D,qBAAqB,CAAC,QAAQ,EAAE,KAAK,CAKvC,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { createToolEnvelope, type ToolExecutionEnvelope, type ToolMergeStrategy, type UIIntent, type UIIntentAction, } from "./envelope";
2
+ export { createCanvasReducer, isSafeKey, mergeUniqueEntities, updateEntityInPlace, type CanvasContentState, type CanvasState, } from "./reducer";
3
+ export { defineCanvas } from "./define-canvas";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ui/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,KAAK,qBAAqB,EAC1B,KAAK,iBAAiB,EACtB,KAAK,QAAQ,EACb,KAAK,cAAc,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,SAAS,EACT,mBAAmB,EACnB,mBAAmB,EACnB,KAAK,kBAAkB,EACvB,KAAK,WAAW,GACjB,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/ui/index.ts
21
+ var ui_exports = {};
22
+ __export(ui_exports, {
23
+ createCanvasReducer: () => createCanvasReducer,
24
+ createToolEnvelope: () => createToolEnvelope,
25
+ defineCanvas: () => defineCanvas,
26
+ isSafeKey: () => isSafeKey,
27
+ mergeUniqueEntities: () => mergeUniqueEntities,
28
+ updateEntityInPlace: () => updateEntityInPlace
29
+ });
30
+ module.exports = __toCommonJS(ui_exports);
31
+
32
+ // src/ui/envelope.ts
33
+ var createToolEnvelope = (options) => {
34
+ return Object.freeze({
35
+ version: 1,
36
+ ...options
37
+ });
38
+ };
39
+
40
+ // src/ui/reducer.ts
41
+ var isSafeKey = (key) => {
42
+ return key !== "__proto__" && key !== "constructor" && key !== "prototype";
43
+ };
44
+ var filterSafeKeys = (source) => {
45
+ const result = {};
46
+ for (const key of Object.keys(source)) {
47
+ if (isSafeKey(key)) {
48
+ result[key] = source[key];
49
+ }
50
+ }
51
+ return result;
52
+ };
53
+ var mergeEntityArrays = (prevItems, incomingItems, dedupeKey) => {
54
+ const seenKeys = new Set(
55
+ prevItems.filter((item) => item && typeof item === "object" && dedupeKey in item).map((item) => String(item[dedupeKey]))
56
+ );
57
+ const uniqueIncoming = incomingItems.filter((item) => {
58
+ const keyVal = item && typeof item === "object" ? String(item[dedupeKey]) : null;
59
+ if (!keyVal || seenKeys.has(keyVal)) {
60
+ return false;
61
+ }
62
+ seenKeys.add(keyVal);
63
+ return true;
64
+ });
65
+ return [...prevItems, ...uniqueIncoming];
66
+ };
67
+ var mergeUniqueEntities = (prevContent, data, dedupeKey) => {
68
+ if (Array.isArray(data) && Array.isArray(prevContent)) {
69
+ return mergeEntityArrays(prevContent, data, dedupeKey);
70
+ }
71
+ if (!data || typeof data !== "object") {
72
+ return { ...prevContent };
73
+ }
74
+ const result = filterSafeKeys(prevContent);
75
+ const safeData = filterSafeKeys(data);
76
+ for (const key of Object.keys(safeData)) {
77
+ const incoming = safeData[key];
78
+ const prev = result[key];
79
+ result[key] = Array.isArray(incoming) && Array.isArray(prev) ? mergeEntityArrays(prev, incoming, dedupeKey) : incoming;
80
+ }
81
+ return result;
82
+ };
83
+ var updateEntityInArray = (items, data, dedupeKey) => {
84
+ let updated = false;
85
+ const targetId = String(data[dedupeKey]);
86
+ const newItems = items.map((item) => {
87
+ if (item && typeof item === "object" && String(item[dedupeKey]) === targetId) {
88
+ updated = true;
89
+ return { ...item, ...filterSafeKeys(data) };
90
+ }
91
+ return item;
92
+ });
93
+ return { updated, items: newItems };
94
+ };
95
+ var updateInternalArray = (target, safeData, dedupeKey) => {
96
+ for (const key of Object.keys(target)) {
97
+ if (!Array.isArray(target[key])) {
98
+ continue;
99
+ }
100
+ const { updated, items } = updateEntityInArray(target[key], safeData, dedupeKey);
101
+ if (updated) {
102
+ target[key] = items;
103
+ return true;
104
+ }
105
+ }
106
+ return false;
107
+ };
108
+ var updateEntityInPlace = (prevContent, data, dedupeKey) => {
109
+ if (!data || typeof data !== "object") {
110
+ return { ...prevContent };
111
+ }
112
+ const safeData = filterSafeKeys(data);
113
+ if (Array.isArray(prevContent)) {
114
+ return updateEntityInArray(prevContent, safeData, dedupeKey).items;
115
+ }
116
+ const result = filterSafeKeys(prevContent);
117
+ const targetId = safeData[dedupeKey] !== void 0 ? String(safeData[dedupeKey]) : null;
118
+ if (targetId && String(result[dedupeKey]) === targetId) {
119
+ return { ...result, ...safeData };
120
+ }
121
+ updateInternalArray(result, safeData, dedupeKey);
122
+ return result;
123
+ };
124
+ var createCanvasReducer = () => {
125
+ return (currentState, envelope) => {
126
+ const { kind, mergeStrategy, dedupeKey = "id", data, uiIntent } = envelope;
127
+ const prevContent = currentState?.content;
128
+ if (!prevContent || prevContent.kind !== kind || mergeStrategy === "REPLACE") {
129
+ return {
130
+ content: { kind, ...filterSafeKeys(data || {}) },
131
+ activeIntent: uiIntent
132
+ };
133
+ }
134
+ if (mergeStrategy === "APPEND_UNIQUE") {
135
+ return {
136
+ content: { kind, ...mergeUniqueEntities(prevContent, data, dedupeKey) },
137
+ activeIntent: uiIntent
138
+ };
139
+ }
140
+ if (mergeStrategy === "UPDATE_ENTITY") {
141
+ return {
142
+ content: { kind, ...updateEntityInPlace(prevContent, data, dedupeKey) },
143
+ activeIntent: uiIntent
144
+ };
145
+ }
146
+ return {
147
+ content: prevContent,
148
+ activeIntent: uiIntent ?? currentState?.activeIntent
149
+ };
150
+ };
151
+ };
152
+
153
+ // src/ui/define-canvas.ts
154
+ var defineCanvas = () => {
155
+ return {
156
+ createEnvelope: (options) => {
157
+ return createToolEnvelope(options);
158
+ },
159
+ canvasReducer: createCanvasReducer()
160
+ };
161
+ };
162
+ // Annotate the CommonJS export names for ESM import in node:
163
+ 0 && (module.exports = {
164
+ createCanvasReducer,
165
+ createToolEnvelope,
166
+ defineCanvas,
167
+ isSafeKey,
168
+ mergeUniqueEntities,
169
+ updateEntityInPlace
170
+ });
@@ -0,0 +1,140 @@
1
+ import "../chunk-Y6FXYEAI.mjs";
2
+
3
+ // src/ui/envelope.ts
4
+ var createToolEnvelope = (options) => {
5
+ return Object.freeze({
6
+ version: 1,
7
+ ...options
8
+ });
9
+ };
10
+
11
+ // src/ui/reducer.ts
12
+ var isSafeKey = (key) => {
13
+ return key !== "__proto__" && key !== "constructor" && key !== "prototype";
14
+ };
15
+ var filterSafeKeys = (source) => {
16
+ const result = {};
17
+ for (const key of Object.keys(source)) {
18
+ if (isSafeKey(key)) {
19
+ result[key] = source[key];
20
+ }
21
+ }
22
+ return result;
23
+ };
24
+ var mergeEntityArrays = (prevItems, incomingItems, dedupeKey) => {
25
+ const seenKeys = new Set(
26
+ prevItems.filter((item) => item && typeof item === "object" && dedupeKey in item).map((item) => String(item[dedupeKey]))
27
+ );
28
+ const uniqueIncoming = incomingItems.filter((item) => {
29
+ const keyVal = item && typeof item === "object" ? String(item[dedupeKey]) : null;
30
+ if (!keyVal || seenKeys.has(keyVal)) {
31
+ return false;
32
+ }
33
+ seenKeys.add(keyVal);
34
+ return true;
35
+ });
36
+ return [...prevItems, ...uniqueIncoming];
37
+ };
38
+ var mergeUniqueEntities = (prevContent, data, dedupeKey) => {
39
+ if (Array.isArray(data) && Array.isArray(prevContent)) {
40
+ return mergeEntityArrays(prevContent, data, dedupeKey);
41
+ }
42
+ if (!data || typeof data !== "object") {
43
+ return { ...prevContent };
44
+ }
45
+ const result = filterSafeKeys(prevContent);
46
+ const safeData = filterSafeKeys(data);
47
+ for (const key of Object.keys(safeData)) {
48
+ const incoming = safeData[key];
49
+ const prev = result[key];
50
+ result[key] = Array.isArray(incoming) && Array.isArray(prev) ? mergeEntityArrays(prev, incoming, dedupeKey) : incoming;
51
+ }
52
+ return result;
53
+ };
54
+ var updateEntityInArray = (items, data, dedupeKey) => {
55
+ let updated = false;
56
+ const targetId = String(data[dedupeKey]);
57
+ const newItems = items.map((item) => {
58
+ if (item && typeof item === "object" && String(item[dedupeKey]) === targetId) {
59
+ updated = true;
60
+ return { ...item, ...filterSafeKeys(data) };
61
+ }
62
+ return item;
63
+ });
64
+ return { updated, items: newItems };
65
+ };
66
+ var updateInternalArray = (target, safeData, dedupeKey) => {
67
+ for (const key of Object.keys(target)) {
68
+ if (!Array.isArray(target[key])) {
69
+ continue;
70
+ }
71
+ const { updated, items } = updateEntityInArray(target[key], safeData, dedupeKey);
72
+ if (updated) {
73
+ target[key] = items;
74
+ return true;
75
+ }
76
+ }
77
+ return false;
78
+ };
79
+ var updateEntityInPlace = (prevContent, data, dedupeKey) => {
80
+ if (!data || typeof data !== "object") {
81
+ return { ...prevContent };
82
+ }
83
+ const safeData = filterSafeKeys(data);
84
+ if (Array.isArray(prevContent)) {
85
+ return updateEntityInArray(prevContent, safeData, dedupeKey).items;
86
+ }
87
+ const result = filterSafeKeys(prevContent);
88
+ const targetId = safeData[dedupeKey] !== void 0 ? String(safeData[dedupeKey]) : null;
89
+ if (targetId && String(result[dedupeKey]) === targetId) {
90
+ return { ...result, ...safeData };
91
+ }
92
+ updateInternalArray(result, safeData, dedupeKey);
93
+ return result;
94
+ };
95
+ var createCanvasReducer = () => {
96
+ return (currentState, envelope) => {
97
+ const { kind, mergeStrategy, dedupeKey = "id", data, uiIntent } = envelope;
98
+ const prevContent = currentState?.content;
99
+ if (!prevContent || prevContent.kind !== kind || mergeStrategy === "REPLACE") {
100
+ return {
101
+ content: { kind, ...filterSafeKeys(data || {}) },
102
+ activeIntent: uiIntent
103
+ };
104
+ }
105
+ if (mergeStrategy === "APPEND_UNIQUE") {
106
+ return {
107
+ content: { kind, ...mergeUniqueEntities(prevContent, data, dedupeKey) },
108
+ activeIntent: uiIntent
109
+ };
110
+ }
111
+ if (mergeStrategy === "UPDATE_ENTITY") {
112
+ return {
113
+ content: { kind, ...updateEntityInPlace(prevContent, data, dedupeKey) },
114
+ activeIntent: uiIntent
115
+ };
116
+ }
117
+ return {
118
+ content: prevContent,
119
+ activeIntent: uiIntent ?? currentState?.activeIntent
120
+ };
121
+ };
122
+ };
123
+
124
+ // src/ui/define-canvas.ts
125
+ var defineCanvas = () => {
126
+ return {
127
+ createEnvelope: (options) => {
128
+ return createToolEnvelope(options);
129
+ },
130
+ canvasReducer: createCanvasReducer()
131
+ };
132
+ };
133
+ export {
134
+ createCanvasReducer,
135
+ createToolEnvelope,
136
+ defineCanvas,
137
+ isSafeKey,
138
+ mergeUniqueEntities,
139
+ updateEntityInPlace
140
+ };
@@ -0,0 +1,22 @@
1
+ import React from "react";
2
+ import type { UIIntent } from "../envelope";
3
+ import type { CanvasState } from "../reducer";
4
+ export interface CanvasViewContext {
5
+ onSendMessage?: (prompt: string) => void;
6
+ onSelectEntity?: (id: string, type?: string) => void;
7
+ isAgentBusy?: boolean;
8
+ }
9
+ export type CanvasViewComponent<TData> = React.FC<{
10
+ data: TData;
11
+ context: CanvasViewContext;
12
+ activeIntent?: UIIntent;
13
+ }>;
14
+ export interface CanvasRendererProps<TContentMap extends Record<string, unknown>> {
15
+ state: CanvasState<TContentMap> | null | undefined;
16
+ context?: CanvasViewContext;
17
+ }
18
+ export declare const createViewRegistry: <TContentMap extends Record<string, unknown>>(registry: { [K in keyof TContentMap]: CanvasViewComponent<TContentMap[K]>; }) => {
19
+ registry: { [K in keyof TContentMap]: CanvasViewComponent<TContentMap[K]>; };
20
+ CanvasRenderer: React.FC<CanvasRendererProps<TContentMap>>;
21
+ };
22
+ //# sourceMappingURL=create-view-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-view-registry.d.ts","sourceRoot":"","sources":["../../../src/ui/react/create-view-registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,WAAW,iBAAiB;IAChC,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACzC,cAAc,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IACrD,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,MAAM,mBAAmB,CAAC,KAAK,IAAI,KAAK,CAAC,EAAE,CAAC;IAChD,IAAI,EAAE,KAAK,CAAC;IACZ,OAAO,EAAE,iBAAiB,CAAC;IAC3B,YAAY,CAAC,EAAE,QAAQ,CAAC;CACzB,CAAC,CAAC;AAEH,MAAM,WAAW,mBAAmB,CAAC,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC9E,KAAK,EAAE,WAAW,CAAC,WAAW,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC;IACnD,OAAO,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAED,eAAO,MAAM,kBAAkB,GAAI,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5E,UAAU,GAAG,CAAC,IAAI,MAAM,WAAW,GAAG,mBAAmB,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,GAAE;iBAA9D,CAAC;;CA4Bf,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { createViewRegistry, type CanvasRendererProps, type CanvasViewComponent, type CanvasViewContext, } from "./create-view-registry";
2
+ export { isValidSafeUrl } from "./sanitize";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/ui/react/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,GACvB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/ui/react/index.ts
31
+ var react_exports = {};
32
+ __export(react_exports, {
33
+ createViewRegistry: () => createViewRegistry,
34
+ isValidSafeUrl: () => isValidSafeUrl
35
+ });
36
+ module.exports = __toCommonJS(react_exports);
37
+
38
+ // src/ui/react/create-view-registry.ts
39
+ var import_react = __toESM(require("react"));
40
+ var createViewRegistry = (registry) => {
41
+ const CanvasRenderer = ({
42
+ state,
43
+ context = {}
44
+ }) => {
45
+ if (!state?.content) {
46
+ return null;
47
+ }
48
+ const kind = state.content.kind;
49
+ const Component = registry[kind];
50
+ if (!Component) {
51
+ return null;
52
+ }
53
+ return import_react.default.createElement(Component, {
54
+ data: state.content,
55
+ context,
56
+ activeIntent: state.activeIntent
57
+ });
58
+ };
59
+ return {
60
+ registry,
61
+ CanvasRenderer
62
+ };
63
+ };
64
+
65
+ // src/ui/react/sanitize.ts
66
+ var ALLOWED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
67
+ var isValidSafeUrl = (rawUrl) => {
68
+ if (!rawUrl || typeof rawUrl !== "string") {
69
+ return false;
70
+ }
71
+ const trimmed = rawUrl.trim();
72
+ if (!trimmed) {
73
+ return false;
74
+ }
75
+ if (trimmed.startsWith("#")) {
76
+ return true;
77
+ }
78
+ if (trimmed.startsWith("/") && !trimmed.startsWith("//")) {
79
+ return true;
80
+ }
81
+ try {
82
+ const parsed = new URL(trimmed);
83
+ return ALLOWED_PROTOCOLS.has(parsed.protocol);
84
+ } catch {
85
+ return false;
86
+ }
87
+ };
88
+ // Annotate the CommonJS export names for ESM import in node:
89
+ 0 && (module.exports = {
90
+ createViewRegistry,
91
+ isValidSafeUrl
92
+ });
@@ -0,0 +1,56 @@
1
+ import "../../chunk-Y6FXYEAI.mjs";
2
+
3
+ // src/ui/react/create-view-registry.ts
4
+ import React from "react";
5
+ var createViewRegistry = (registry) => {
6
+ const CanvasRenderer = ({
7
+ state,
8
+ context = {}
9
+ }) => {
10
+ if (!state?.content) {
11
+ return null;
12
+ }
13
+ const kind = state.content.kind;
14
+ const Component = registry[kind];
15
+ if (!Component) {
16
+ return null;
17
+ }
18
+ return React.createElement(Component, {
19
+ data: state.content,
20
+ context,
21
+ activeIntent: state.activeIntent
22
+ });
23
+ };
24
+ return {
25
+ registry,
26
+ CanvasRenderer
27
+ };
28
+ };
29
+
30
+ // src/ui/react/sanitize.ts
31
+ var ALLOWED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
32
+ var isValidSafeUrl = (rawUrl) => {
33
+ if (!rawUrl || typeof rawUrl !== "string") {
34
+ return false;
35
+ }
36
+ const trimmed = rawUrl.trim();
37
+ if (!trimmed) {
38
+ return false;
39
+ }
40
+ if (trimmed.startsWith("#")) {
41
+ return true;
42
+ }
43
+ if (trimmed.startsWith("/") && !trimmed.startsWith("//")) {
44
+ return true;
45
+ }
46
+ try {
47
+ const parsed = new URL(trimmed);
48
+ return ALLOWED_PROTOCOLS.has(parsed.protocol);
49
+ } catch {
50
+ return false;
51
+ }
52
+ };
53
+ export {
54
+ createViewRegistry,
55
+ isValidSafeUrl
56
+ };
@@ -0,0 +1,2 @@
1
+ export declare const isValidSafeUrl: (rawUrl: string | null | undefined) => boolean;
2
+ //# sourceMappingURL=sanitize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize.d.ts","sourceRoot":"","sources":["../../../src/ui/react/sanitize.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,GAAI,QAAQ,MAAM,GAAG,IAAI,GAAG,SAAS,KAAG,OAwBlE,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { ToolExecutionEnvelope, UIIntent } from "./envelope";
2
+ export type CanvasContentState<TContentMap extends Record<string, unknown>> = {
3
+ [K in keyof TContentMap]: {
4
+ kind: K;
5
+ } & TContentMap[K];
6
+ }[keyof TContentMap] | null;
7
+ export interface CanvasState<TContentMap extends Record<string, unknown>> {
8
+ content: CanvasContentState<TContentMap>;
9
+ activeIntent?: UIIntent;
10
+ }
11
+ export declare const isSafeKey: (key: string) => boolean;
12
+ export declare const mergeUniqueEntities: (prevContent: Record<string, any>, data: any, dedupeKey: string) => Record<string, any>;
13
+ export declare const updateEntityInPlace: (prevContent: Record<string, any>, data: any, dedupeKey: string) => Record<string, any>;
14
+ export declare const createCanvasReducer: <TContentMap extends Record<string, unknown>>() => (currentState: CanvasState<TContentMap> | null | undefined, envelope: ToolExecutionEnvelope<unknown, Extract<keyof TContentMap, string>>) => CanvasState<TContentMap>;
15
+ //# sourceMappingURL=reducer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reducer.d.ts","sourceRoot":"","sources":["../../src/ui/reducer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAElE,MAAM,MAAM,kBAAkB,CAAC,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI;KAC3E,CAAC,IAAI,MAAM,WAAW,GAAG;QAAE,IAAI,EAAE,CAAC,CAAA;KAAE,GAAG,WAAW,CAAC,CAAC,CAAC;CACvD,CAAC,MAAM,WAAW,CAAC,GAAG,IAAI,CAAC;AAE5B,MAAM,WAAW,WAAW,CAAC,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACtE,OAAO,EAAE,kBAAkB,CAAC,WAAW,CAAC,CAAC;IACzC,YAAY,CAAC,EAAE,QAAQ,CAAC;CACzB;AAED,eAAO,MAAM,SAAS,GAAI,KAAK,MAAM,KAAG,OAEvC,CAAC;AAmCF,eAAO,MAAM,mBAAmB,GAC9B,aAAa,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAChC,MAAM,GAAG,EACT,WAAW,MAAM,KAChB,MAAM,CAAC,MAAM,EAAE,GAAG,CAoBpB,CAAC;AAuCF,eAAO,MAAM,mBAAmB,GAC9B,aAAa,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAChC,MAAM,GAAG,EACT,WAAW,MAAM,KAChB,MAAM,CAAC,MAAM,EAAE,GAAG,CAmBpB,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAAI,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,QAE3E,cAAc,WAAW,CAAC,WAAW,CAAC,GAAG,IAAI,GAAG,SAAS,EACzD,UAAU,qBAAqB,CAAC,OAAO,EAAE,OAAO,CAAC,MAAM,WAAW,EAAE,MAAM,CAAC,CAAC,KAC3E,WAAW,CAAC,WAAW,CA8B3B,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "avantgate",
3
- "version": "2.0.0",
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.",
3
+ "version": "2.1.0",
4
+ "description": "Zero-infrastructure, in-process AI Application Firewall (AI-WAF), privacy control plane & headless UI canvas for TypeScript: real-time prompt guardrails, zero-egress PII redaction, deterministic tool envelopes, anti-IDOR defense, pre-flight token budgets, and multi-model failover.",
5
5
  "author": "Gatewall Team",
6
6
  "license": "MIT",
7
7
  "keywords": [
@@ -16,6 +16,10 @@
16
16
  "llm",
17
17
  "ai",
18
18
  "agent",
19
+ "canvas",
20
+ "headless-ui",
21
+ "tool-envelope",
22
+ "copilot-ui",
19
23
  "dual-channel",
20
24
  "tool-governance",
21
25
  "blast-radius",
@@ -65,6 +69,16 @@
65
69
  "import": "./dist/client/index.mjs",
66
70
  "require": "./dist/client/index.js"
67
71
  },
72
+ "./ui": {
73
+ "types": "./dist/ui/index.d.ts",
74
+ "import": "./dist/ui/index.mjs",
75
+ "require": "./dist/ui/index.js"
76
+ },
77
+ "./ui/react": {
78
+ "types": "./dist/ui/react/index.d.ts",
79
+ "import": "./dist/ui/react/index.mjs",
80
+ "require": "./dist/ui/react/index.js"
81
+ },
68
82
  "./package.json": "./package.json"
69
83
  },
70
84
  "peerDependencies": {
@@ -81,8 +95,9 @@
81
95
  "LICENSE"
82
96
  ],
83
97
  "scripts": {
84
- "build": "tsup src/index.ts src/finance/index.ts src/agent/index.ts src/workflow/index.ts src/client/index.ts --format cjs --format esm --clean && tsc --emitDeclarationOnly --outDir dist",
85
- "test": "tsx tests/avantgate.test.ts && tsx tests/preflight-budget.test.ts && tsx tests/sqlite-pricing-adapter.test.ts && tsx tests/financial-normalizer.test.ts && tsx tests/prompt-builder.test.ts && tsx tests/pii-extended.test.ts && tsx tests/output-dlp-secret-guard.test.ts && npm run test:agent && npm run test:workflow && npm run test:client",
98
+ "build": "tsup src/index.ts src/finance/index.ts src/agent/index.ts src/workflow/index.ts src/client/index.ts src/ui/index.ts src/ui/react/index.ts --format cjs --format esm --clean && tsc --emitDeclarationOnly --outDir dist",
99
+ "test": "tsx tests/avantgate.test.ts && tsx tests/preflight-budget.test.ts && tsx tests/sqlite-pricing-adapter.test.ts && tsx tests/financial-normalizer.test.ts && tsx tests/prompt-builder.test.ts && tsx tests/pii-extended.test.ts && tsx tests/output-dlp-secret-guard.test.ts && npm run test:agent && npm run test:workflow && npm run test:client && npm run test:ui",
100
+ "test:ui": "tsx tests/ui/envelope.test.ts && tsx tests/ui/reducer.test.ts && tsx tests/ui/sanitize.test.ts && tsx tests/ui/react-registry.test.tsx",
86
101
  "test:secrets": "tsx tests/output-dlp-secret-guard.test.ts",
87
102
  "test:pricing": "tsx tests/sqlite-pricing-adapter.test.ts",
88
103
  "test:finance": "tsx tests/financial-normalizer.test.ts",