@agentguard-run/spend 0.1.3 → 0.1.6

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.
@@ -0,0 +1,128 @@
1
+ # @agentguard-run/spend
2
+
3
+ > Límites de gasto de tiempo de ejecución local y enrutamiento de modelos con capacidades para agentes de IA.
4
+
5
+ Cada decisión de política se ejecuta dentro de su proceso. Los prompts, claves API del proveedor y claves de firma nunca salen de su entorno de ejecución. Cada decisión de aplicación produce un recibo firmado con Ed25519, encadenado por hash, apto para auditoría y revisión de cumplimiento.
6
+
7
+ > Disponible también en: [English](README.md) · [Português (BR)](README.pt-BR.md)
8
+
9
+ ## Por qué sin proxy
10
+
11
+ Cada competidor financiado en gobernanza del gasto en IA (Portkey, Helicone, LiteLLM, Cloudflare AI Gateway, Vercel AI Gateway) usa proxy sobre su tráfico. Eso significa que sus prompts y claves de proveedor pasan por la infraestructura de ellos. `@agentguard-run/spend` nunca ve nada de eso. La política corre en su proceso. El registro firmado vive en su almacenamiento.
12
+
13
+ ## Instalación
14
+
15
+ ```bash
16
+ npm install @agentguard-run/spend
17
+ # o
18
+ pnpm add @agentguard-run/spend
19
+ # o
20
+ yarn add @agentguard-run/spend
21
+ ```
22
+
23
+ ## Inicio rápido
24
+
25
+ ```ts
26
+ import OpenAI from 'openai';
27
+ import {
28
+ withSpendGuard,
29
+ AgentGuardBlockedError,
30
+ type SpendPolicy,
31
+ } from '@agentguard-run/spend';
32
+ import { randomBytes } from 'crypto';
33
+
34
+ const policy: SpendPolicy = {
35
+ id: 'finance-ops-v1',
36
+ name: 'Límites diarios de operaciones financieras',
37
+ scope: { tenantId: 'acme-corp' },
38
+ caps: [
39
+ {
40
+ amountCents: 500,
41
+ window: 'per_day',
42
+ action: 'downgrade',
43
+ downgradeTo: 'gpt-4o-mini',
44
+ reason: 'Límite blando diario alcanzado, enrutando al modelo más económico',
45
+ },
46
+ {
47
+ amountCents: 2000,
48
+ window: 'per_day',
49
+ action: 'block',
50
+ reason: 'Tope diario duro',
51
+ },
52
+ ],
53
+ mode: 'enforce',
54
+ version: 1,
55
+ effectiveFrom: '2026-05-24T00:00:00Z',
56
+ };
57
+
58
+ const privateKey = new Uint8Array(randomBytes(32));
59
+
60
+ const client = withSpendGuard(new OpenAI(), {
61
+ policy,
62
+ scope: { tenantId: 'acme-corp', agentId: 'finance-bot' },
63
+ config: {
64
+ policy,
65
+ signingKeys: {
66
+ privateKey,
67
+ publicKey: new Uint8Array(32), // derivar de privateKey en producción
68
+ },
69
+ locale: 'es-419', // opcional - también detecta automáticamente
70
+ },
71
+ });
72
+
73
+ try {
74
+ const completion = await client.chat.completions.create({
75
+ model: 'gpt-4o',
76
+ messages: [{ role: 'user', content: 'Hola' }],
77
+ });
78
+ } catch (err) {
79
+ if (err instanceof AgentGuardBlockedError) {
80
+ // El mensaje será mostrado en español por el detector de locale
81
+ console.error(err.message);
82
+ }
83
+ }
84
+ ```
85
+
86
+ Cuando se dispara la política:
87
+
88
+ | Acción | Resultado |
89
+ |-------------|------------------------------------------------------------------------------------|
90
+ | `allow` | La llamada pasa sin modificaciones |
91
+ | `downgrade` | El parámetro `model` se reescribe a `downgradeTo`, luego la llamada continúa |
92
+ | `block` | Se lanza `AgentGuardBlockedError` antes de contactar al proveedor |
93
+ | `shadow` | La llamada pasa; la decisión se registra solo para análisis |
94
+
95
+ ## Localización (v0.1.4+)
96
+
97
+ Los mensajes de bloqueo legibles están localizados en **inglés (en-US)**, **español de América Latina (es-419)** y **portugués brasileño (pt-BR)**. La resolución del locale sigue la cadena de prioridad estándar:
98
+
99
+ 1. Configuración explícita: `config: { locale: 'es-419', ... }`
100
+ 2. Variable de entorno: `export AGENTGUARD_LOCALE=es-419`
101
+ 3. Variables de entorno del sistema: `LC_ALL`, `LC_MESSAGES`, `LANG`
102
+ 4. `Intl.DateTimeFormat().resolvedOptions().locale` (navegador / Deno / Bun)
103
+ 5. Respaldo: `en-US`
104
+
105
+ ## Estado
106
+
107
+ Vista previa privada. Diseñado para integración empresarial, OEM y de plataforma.
108
+
109
+ Para acceso a evaluación, licencias OEM o consultas de asociación estratégica: `invest@agentguard.run`
110
+
111
+ ## Licencia y umbrales de uso
112
+
113
+ El SDK es **gratuito** para:
114
+
115
+ - Evaluación, prototipado y desarrollo no comercial a cualquier volumen
116
+ - Despliegues de producción que procesan **hasta 10 000 llamadas de aplicación por mes calendario**
117
+
118
+ Se requiere una licencia comercial separada para volúmenes mayores o redistribución. Consultas: `invest@agentguard.run`
119
+
120
+ ## Aviso de patentes
121
+
122
+ Protegido por solicitudes de patente pendientes en EE. UU. (App. Nos. 63/983,615; 63/983,621; 63/983,843; 63/984,626; 64/071,781; 64/071,789).
123
+
124
+ ## Enlaces
125
+
126
+ - agentguard.run
127
+ - Contacto: `invest@agentguard.run`
128
+ - SDK Python: [`agentguard-spend`](https://pypi.org/project/agentguard-spend/)
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  > Local-runtime spend caps and capability-gated model routing for AI agents.
4
4
 
5
+ > Also available in: [Español (LATAM)](README.es-419.md) · [Português (BR)](README.pt-BR.md)
6
+
5
7
  Every policy decision runs inside your process. Prompts, provider API keys, and signing keys never leave your runtime. Each enforcement decision produces an Ed25519-signed, hash-chained receipt suitable for audit and compliance review.
6
8
 
7
9
  ## Why no proxy
@@ -0,0 +1,128 @@
1
+ # @agentguard-run/spend
2
+
3
+ > Limites de gasto em tempo de execução local e roteamento de modelos com capacidades para agentes de IA.
4
+
5
+ Toda decisão de política é executada dentro do seu processo. Prompts, chaves de API do provedor e chaves de assinatura nunca saem do seu runtime. Cada decisão de aplicação produz um recibo assinado com Ed25519, encadeado por hash, adequado para auditoria e revisão de compliance.
6
+
7
+ > Disponível também em: [English](README.md) · [Español (LATAM)](README.es-419.md)
8
+
9
+ ## Por que sem proxy
10
+
11
+ Todo concorrente financiado em governança de gasto em IA (Portkey, Helicone, LiteLLM, Cloudflare AI Gateway, Vercel AI Gateway) faz proxy do seu tráfego. Isso significa que seus prompts e chaves de provedor passam pela infraestrutura deles. `@agentguard-run/spend` nunca vê nada disso. A política roda no seu processo. O log assinado vive no seu armazenamento.
12
+
13
+ ## Instalação
14
+
15
+ ```bash
16
+ npm install @agentguard-run/spend
17
+ # ou
18
+ pnpm add @agentguard-run/spend
19
+ # ou
20
+ yarn add @agentguard-run/spend
21
+ ```
22
+
23
+ ## Quickstart
24
+
25
+ ```ts
26
+ import OpenAI from 'openai';
27
+ import {
28
+ withSpendGuard,
29
+ AgentGuardBlockedError,
30
+ type SpendPolicy,
31
+ } from '@agentguard-run/spend';
32
+ import { randomBytes } from 'crypto';
33
+
34
+ const policy: SpendPolicy = {
35
+ id: 'finance-ops-v1',
36
+ name: 'Limites diários de operações financeiras',
37
+ scope: { tenantId: 'acme-corp' },
38
+ caps: [
39
+ {
40
+ amountCents: 500,
41
+ window: 'per_day',
42
+ action: 'downgrade',
43
+ downgradeTo: 'gpt-4o-mini',
44
+ reason: 'Limite leve diário atingido, redirecionando para modelo mais barato',
45
+ },
46
+ {
47
+ amountCents: 2000,
48
+ window: 'per_day',
49
+ action: 'block',
50
+ reason: 'Teto diário rígido',
51
+ },
52
+ ],
53
+ mode: 'enforce',
54
+ version: 1,
55
+ effectiveFrom: '2026-05-24T00:00:00Z',
56
+ };
57
+
58
+ const privateKey = new Uint8Array(randomBytes(32));
59
+
60
+ const client = withSpendGuard(new OpenAI(), {
61
+ policy,
62
+ scope: { tenantId: 'acme-corp', agentId: 'finance-bot' },
63
+ config: {
64
+ policy,
65
+ signingKeys: {
66
+ privateKey,
67
+ publicKey: new Uint8Array(32), // derivar de privateKey em produção
68
+ },
69
+ locale: 'pt-BR', // opcional - também detecta automaticamente
70
+ },
71
+ });
72
+
73
+ try {
74
+ const completion = await client.chat.completions.create({
75
+ model: 'gpt-4o',
76
+ messages: [{ role: 'user', content: 'Olá' }],
77
+ });
78
+ } catch (err) {
79
+ if (err instanceof AgentGuardBlockedError) {
80
+ // A mensagem será exibida em português pelo detector de locale
81
+ console.error(err.message);
82
+ }
83
+ }
84
+ ```
85
+
86
+ Quando a política dispara:
87
+
88
+ | Ação | Resultado |
89
+ |-------------|------------------------------------------------------------------------------------------|
90
+ | `allow` | A chamada passa sem alterações |
91
+ | `downgrade` | O parâmetro `model` é reescrito para `downgradeTo`, então a chamada prossegue |
92
+ | `block` | `AgentGuardBlockedError` é lançado antes de contatar o provedor |
93
+ | `shadow` | A chamada passa; a decisão é registrada apenas para análise |
94
+
95
+ ## Localização (v0.1.4+)
96
+
97
+ Mensagens de bloqueio legíveis estão localizadas em **inglês (en-US)**, **espanhol latino-americano (es-419)** e **português brasileiro (pt-BR)**. A resolução do locale segue a cadeia de prioridade padrão:
98
+
99
+ 1. Configuração explícita: `config: { locale: 'pt-BR', ... }`
100
+ 2. Variável de ambiente: `export AGENTGUARD_LOCALE=pt-BR`
101
+ 3. Variáveis de ambiente do sistema: `LC_ALL`, `LC_MESSAGES`, `LANG`
102
+ 4. `Intl.DateTimeFormat().resolvedOptions().locale` (browser / Deno / Bun)
103
+ 5. Fallback: `en-US`
104
+
105
+ ## Status
106
+
107
+ Preview privado. Projetado para integração corporativa, OEM e de plataforma.
108
+
109
+ Para acesso de avaliação, licenciamento OEM ou consultas de parceria estratégica: `invest@agentguard.run`
110
+
111
+ ## Licença e limiares de uso
112
+
113
+ O SDK é **gratuito** para:
114
+
115
+ - Avaliação, prototipagem e desenvolvimento não comercial em qualquer volume
116
+ - Implantações de produção processando **até 10.000 chamadas de aplicação por mês calendário**
117
+
118
+ Uma licença comercial separada é necessária para volumes maiores ou redistribuição. Consultas: `invest@agentguard.run`
119
+
120
+ ## Aviso de patentes
121
+
122
+ Protegido por aplicações de patente pendentes nos EUA (App. Nos. 63/983,615; 63/983,621; 63/983,843; 63/984,626; 64/071,781; 64/071,789).
123
+
124
+ ## Links
125
+
126
+ - agentguard.run
127
+ - Contato: `invest@agentguard.run`
128
+ - SDK Python: [`agentguard-spend`](https://pypi.org/project/agentguard-spend/)
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ // AgentGuard CLI entry point (executable via `agentguard` after npm install).
3
+ require('../dist/cli/main')
4
+ .main()
5
+ .then((code) => process.exit(code))
6
+ .catch((err) => {
7
+ console.error(err);
8
+ process.exit(1);
9
+ });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * ANSI color helpers with TTY detection.
3
+ *
4
+ * Honors:
5
+ * - NO_COLOR=1 (industry standard; https://no-color.org)
6
+ * - AGENTGUARD_COLOR=0 (product-specific opt-out)
7
+ * - process.stdout.isTTY (no color when piped to file or non-TTY)
8
+ */
9
+ export declare const red: (text: string) => string;
10
+ export declare const green: (text: string) => string;
11
+ export declare const yellow: (text: string) => string;
12
+ export declare const cyan: (text: string) => string;
13
+ export declare const brightRed: (text: string) => string;
14
+ export declare const brightGreen: (text: string) => string;
15
+ export declare const brightCyan: (text: string) => string;
16
+ export declare const bold: (text: string) => string;
17
+ export declare const dim: (text: string) => string;
18
+ export declare function cyanBold(text: string): string;
19
+ export declare function redBold(text: string): string;
20
+ export declare function greenBold(text: string): string;
21
+ export declare function banner(version: string): string;
22
+ //# sourceMappingURL=colors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"colors.d.ts","sourceRoot":"","sources":["../../src/cli/colors.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAeH,eAAO,MAAM,GAAG,SAJoB,MAAM,KAAK,MAIlB,CAAC;AAC9B,eAAO,MAAM,KAAK,SALkB,MAAM,KAAK,MAKhB,CAAC;AAChC,eAAO,MAAM,MAAM,SANiB,MAAM,KAAK,MAMf,CAAC;AACjC,eAAO,MAAM,IAAI,SAPmB,MAAM,KAAK,MAOjB,CAAC;AAC/B,eAAO,MAAM,SAAS,SARc,MAAM,KAAK,MAQZ,CAAC;AACpC,eAAO,MAAM,WAAW,SATY,MAAM,KAAK,MASV,CAAC;AACtC,eAAO,MAAM,UAAU,SAVa,MAAM,KAAK,MAUX,CAAC;AACrC,eAAO,MAAM,IAAI,SAXmB,MAAM,KAAK,MAWlB,CAAC;AAC9B,eAAO,MAAM,GAAG,SAZoB,MAAM,KAAK,MAYnB,CAAC;AAE7B,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE7C;AAED,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE5C;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,wBAAgB,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE9C"}
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * ANSI color helpers with TTY detection.
4
+ *
5
+ * Honors:
6
+ * - NO_COLOR=1 (industry standard; https://no-color.org)
7
+ * - AGENTGUARD_COLOR=0 (product-specific opt-out)
8
+ * - process.stdout.isTTY (no color when piped to file or non-TTY)
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.dim = exports.bold = exports.brightCyan = exports.brightGreen = exports.brightRed = exports.cyan = exports.yellow = exports.green = exports.red = void 0;
12
+ exports.cyanBold = cyanBold;
13
+ exports.redBold = redBold;
14
+ exports.greenBold = greenBold;
15
+ exports.banner = banner;
16
+ function colorEnabled() {
17
+ if (typeof process === 'undefined')
18
+ return false;
19
+ if (process.env.NO_COLOR)
20
+ return false;
21
+ const ag = (process.env.AGENTGUARD_COLOR || '').toLowerCase();
22
+ if (['0', 'false', 'no', 'off'].includes(ag))
23
+ return false;
24
+ if (!process.stdout || !process.stdout.isTTY)
25
+ return false;
26
+ return true;
27
+ }
28
+ function wrap(code) {
29
+ return (text) => (colorEnabled() ? `\x1b[${code}m${text}\x1b[0m` : text);
30
+ }
31
+ exports.red = wrap('31');
32
+ exports.green = wrap('32');
33
+ exports.yellow = wrap('33');
34
+ exports.cyan = wrap('36');
35
+ exports.brightRed = wrap('91');
36
+ exports.brightGreen = wrap('92');
37
+ exports.brightCyan = wrap('96');
38
+ exports.bold = wrap('1');
39
+ exports.dim = wrap('2');
40
+ function cyanBold(text) {
41
+ return colorEnabled() ? `\x1b[1;36m${text}\x1b[0m` : text;
42
+ }
43
+ function redBold(text) {
44
+ return colorEnabled() ? `\x1b[1;31m${text}\x1b[0m` : text;
45
+ }
46
+ function greenBold(text) {
47
+ return colorEnabled() ? `\x1b[1;32m${text}\x1b[0m` : text;
48
+ }
49
+ function banner(version) {
50
+ return cyanBold(`⬡ AGENTGUARD SPEND · v${version}`);
51
+ }
52
+ //# sourceMappingURL=colors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"colors.js","sourceRoot":"","sources":["../../src/cli/colors.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAyBH,4BAEC;AAED,0BAEC;AAED,8BAEC;AAED,wBAEC;AArCD,SAAS,YAAY;IACnB,IAAI,OAAO,OAAO,KAAK,WAAW;QAAE,OAAO,KAAK,CAAC;IACjD,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ;QAAE,OAAO,KAAK,CAAC;IACvC,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IAC9D,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3D,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IAC3D,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,IAAI,CAAC,IAAY;IACxB,OAAO,CAAC,IAAY,EAAE,EAAE,CAAC,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,QAAQ,IAAI,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AACnF,CAAC;AAEY,QAAA,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;AACjB,QAAA,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;AACnB,QAAA,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;AACpB,QAAA,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;AAClB,QAAA,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;AACvB,QAAA,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,QAAA,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;AACxB,QAAA,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AACjB,QAAA,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AAE7B,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,aAAa,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;AAC5D,CAAC;AAED,SAAgB,OAAO,CAAC,IAAY;IAClC,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,aAAa,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;AAC5D,CAAC;AAED,SAAgB,SAAS,CAAC,IAAY;IACpC,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,aAAa,IAAI,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;AAC5D,CAAC;AAED,SAAgB,MAAM,CAAC,OAAe;IACpC,OAAO,QAAQ,CAAC,2BAA2B,OAAO,EAAE,CAAC,CAAC;AACxD,CAAC"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `agentguard demo` — deterministic simulation with real cryptographic receipt.
3
+ *
4
+ * Output matches agentguard.run/the-block/ exactly. Dollar amounts and
5
+ * agent name are simulated parameters (fixed for reproducibility). The
6
+ * Ed25519 signature, SHA-256 chain hash, and canonical-JSON
7
+ * serialization are REAL — the receipt can be verified with
8
+ * `agentguard verify --trace latest`.
9
+ *
10
+ * No network calls. Fully offline. Deterministic across runs.
11
+ */
12
+ export declare function runDemo(argv: string[]): Promise<number>;
13
+ //# sourceMappingURL=demo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"demo.d.ts","sourceRoot":"","sources":["../../src/cli/demo.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAuBH,wBAAsB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAmI7D"}
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+ /**
3
+ * `agentguard demo` — deterministic simulation with real cryptographic receipt.
4
+ *
5
+ * Output matches agentguard.run/the-block/ exactly. Dollar amounts and
6
+ * agent name are simulated parameters (fixed for reproducibility). The
7
+ * Ed25519 signature, SHA-256 chain hash, and canonical-JSON
8
+ * serialization are REAL — the receipt can be verified with
9
+ * `agentguard verify --trace latest`.
10
+ *
11
+ * No network calls. Fully offline. Deterministic across runs.
12
+ */
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || (function () {
30
+ var ownKeys = function(o) {
31
+ ownKeys = Object.getOwnPropertyNames || function (o) {
32
+ var ar = [];
33
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
34
+ return ar;
35
+ };
36
+ return ownKeys(o);
37
+ };
38
+ return function (mod) {
39
+ if (mod && mod.__esModule) return mod;
40
+ var result = {};
41
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
42
+ __setModuleDefault(result, mod);
43
+ return result;
44
+ };
45
+ })();
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.runDemo = runDemo;
48
+ const fs = __importStar(require("fs"));
49
+ const os = __importStar(require("os"));
50
+ const path = __importStar(require("path"));
51
+ const ed = __importStar(require("@noble/ed25519"));
52
+ const decision_log_1 = require("../decision-log");
53
+ const i18n_1 = require("../i18n");
54
+ const index_1 = require("../index");
55
+ const colors_1 = require("./colors");
56
+ const DEMO_HOME = path.join(os.homedir(), '.agentguard', 'demo');
57
+ const DEMO_PRIVATE_KEY = path.join(DEMO_HOME, 'demo-private.key');
58
+ const DEMO_PUBLIC_KEY = path.join(DEMO_HOME, 'demo-public.key');
59
+ const DEMO_RECEIPT = path.join(DEMO_HOME, 'latest-receipt.json');
60
+ async function runDemo(argv) {
61
+ if (argv.includes('--no-color')) {
62
+ process.env.NO_COLOR = '1';
63
+ }
64
+ if (argv.includes('--help') || argv.includes('-h')) {
65
+ console.log('agentguard demo');
66
+ console.log('Run a deterministic simulation with a real cryptographic receipt.');
67
+ console.log('Options:');
68
+ console.log(' --no-color Disable colored output (same as NO_COLOR=1).');
69
+ return 0;
70
+ }
71
+ // Simulated parameters - match the marketing screenshot at agentguard.run/the-block/.
72
+ const agentId = 'agent-finance-bot-v3';
73
+ const provider = 'anthropic';
74
+ const modelRequested = 'claude-opus-4-7';
75
+ const dailyCapCents = 50000; // $500.00
76
+ const projectedCents = 112241; // $1,122.41
77
+ const windowSpendBefore = 0;
78
+ const timestamp = '2026-05-24T18:00:00.000Z';
79
+ // Deterministic keypair from a fixed seed.
80
+ // Public + reproducible by design - NEVER use for production.
81
+ const privateSeed = new Uint8Array(32);
82
+ for (let i = 0; i < 32; i++)
83
+ privateSeed[i] = i;
84
+ const publicKey = await ed.getPublicKeyAsync(privateSeed);
85
+ const triggeredCap = {
86
+ amountCents: dailyCapCents,
87
+ window: 'per_day',
88
+ action: 'block',
89
+ reason: `Hard daily ceiling ($${(dailyCapCents / 100).toFixed(2)}/day)`,
90
+ };
91
+ const decision = {
92
+ decisionId: 'agentguard-demo-decision-v1',
93
+ timestamp,
94
+ policyId: 'agentguard-demo-policy-v1',
95
+ policyVersion: 1,
96
+ enforcementMode: 'enforce',
97
+ action: 'block',
98
+ reasons: [`Cap 'per_day=${dailyCapCents}c' exceeded`],
99
+ provider,
100
+ modelRequested,
101
+ modelResolved: modelRequested,
102
+ projectedCents,
103
+ windowSpendBefore,
104
+ windowSpendAfter: windowSpendBefore,
105
+ triggeredCap,
106
+ triggeredScopeKey: `tenantId=demo|agentId=${agentId}`,
107
+ };
108
+ // REAL Ed25519 signature over REAL canonical JSON.
109
+ const sequence = 0;
110
+ const previousHash = decision_log_1.GENESIS_PREVIOUS_HASH;
111
+ const entryHash = (0, decision_log_1.computeEntryHash)({ sequence, decision, previousHash });
112
+ void entryHash; // computed for the persisted receipt below
113
+ const signedEntry = await (0, decision_log_1.signDecision)({
114
+ sequence,
115
+ decision,
116
+ previousHash,
117
+ privateKey: privateSeed,
118
+ publicKey,
119
+ });
120
+ const signerFingerprint = (0, decision_log_1.computeSignerFingerprint)(publicKey);
121
+ console.log('');
122
+ console.log(' ' + (0, colors_1.banner)(index_1.AGENTGUARD_SPEND_VERSION));
123
+ console.log('');
124
+ console.log(' ' +
125
+ (0, colors_1.cyanBold)('AgentGuard Demo') +
126
+ (0, colors_1.dim)(' · ') +
127
+ (0, colors_1.dim)('[simulated transaction · real cryptographic receipt]'));
128
+ console.log('');
129
+ console.log((0, i18n_1.formatBlockedTrace)({
130
+ policyId: decision.policyId,
131
+ provider: decision.provider,
132
+ projectedCents: decision.projectedCents,
133
+ windowSpendBefore: decision.windowSpendBefore,
134
+ reasons: decision.reasons,
135
+ triggeredCap: { amountCents: triggeredCap.amountCents, window: triggeredCap.window },
136
+ agentId,
137
+ }));
138
+ console.log('');
139
+ // Persist the receipt so `agentguard verify --trace latest` works.
140
+ try {
141
+ fs.mkdirSync(DEMO_HOME, { recursive: true });
142
+ fs.writeFileSync(DEMO_PRIVATE_KEY, Buffer.from(privateSeed), { mode: 0o600 });
143
+ fs.writeFileSync(DEMO_PUBLIC_KEY, Buffer.from(publicKey));
144
+ fs.writeFileSync(DEMO_RECEIPT, JSON.stringify({
145
+ sequence,
146
+ entryHash,
147
+ previousHash,
148
+ signature: signedEntry.signature,
149
+ signerFingerprint,
150
+ publicKeyHex: Buffer.from(publicKey).toString('hex'),
151
+ decision,
152
+ }, null, 2));
153
+ }
154
+ catch {
155
+ // best-effort persist; demo still prints if disk write fails
156
+ }
157
+ const receiptId = entryHash.slice(0, 16);
158
+ console.log((0, colors_1.dim)(' ───────────────────────────────────────────'));
159
+ console.log(` ${(0, colors_1.dim)('receipt ')} ${receiptId}${(0, colors_1.dim)('...')}`);
160
+ console.log(` ${(0, colors_1.dim)('signer ')} ${signerFingerprint.slice(0, 16)}${(0, colors_1.dim)('...')}`);
161
+ console.log(` ${(0, colors_1.dim)('sequence ')} ${sequence}`);
162
+ console.log((0, colors_1.dim)(' ───────────────────────────────────────────'));
163
+ console.log('');
164
+ console.log(' ' +
165
+ (0, colors_1.green)('→') +
166
+ ' ' +
167
+ (0, colors_1.dim)('verify this receipt:') +
168
+ ' ' +
169
+ (0, colors_1.greenBold)('agentguard verify --trace latest'));
170
+ console.log('');
171
+ return 0;
172
+ }
173
+ //# sourceMappingURL=demo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"demo.js","sourceRoot":"","sources":["../../src/cli/demo.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBH,0BAmIC;AAxJD,uCAAyB;AACzB,uCAAyB;AACzB,2CAA6B;AAC7B,mDAAqC;AAErC,kDAKyB;AAEzB,kCAA6C;AAC7C,oCAAo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CAAC,CAAC;AACX,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * AgentGuard CLI entry point.
3
+ *
4
+ * Usage:
5
+ * agentguard demo Run a deterministic simulation
6
+ * agentguard verify --trace latest Verify the latest demo receipt
7
+ * agentguard --version Show installed SDK version
8
+ * agentguard --help Show this help
9
+ */
10
+ export declare function main(argv?: string[]): Promise<number>;
11
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/cli/main.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAuBH,wBAAsB,IAAI,CAAC,IAAI,GAAE,MAAM,EAA0B,GAAG,OAAO,CAAC,MAAM,CAAC,CAyBlF"}
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ /**
3
+ * AgentGuard CLI entry point.
4
+ *
5
+ * Usage:
6
+ * agentguard demo Run a deterministic simulation
7
+ * agentguard verify --trace latest Verify the latest demo receipt
8
+ * agentguard --version Show installed SDK version
9
+ * agentguard --help Show this help
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.main = main;
46
+ const index_1 = require("../index");
47
+ const HELP = `agentguard — local-runtime spend caps + signed receipts for AI agents
48
+
49
+ usage:
50
+ agentguard <command> [options]
51
+
52
+ commands:
53
+ demo Run a deterministic simulation with a real cryptographic receipt.
54
+ verify Verify a signed AgentGuard receipt.
55
+ --version Show the installed SDK version.
56
+ --help Show this help.
57
+
58
+ examples:
59
+ agentguard demo
60
+ agentguard verify --trace latest
61
+
62
+ docs: https://agentguard.run
63
+ install: pip install agentguard-spend / npm install @agentguard-run/spend
64
+ `;
65
+ async function main(argv = process.argv.slice(2)) {
66
+ if (argv.length === 0 || ['-h', '--help', 'help'].includes(argv[0])) {
67
+ process.stdout.write(HELP);
68
+ return 0;
69
+ }
70
+ if (['-v', '--version', 'version'].includes(argv[0])) {
71
+ console.log(`agentguard ${index_1.AGENTGUARD_SPEND_VERSION}`);
72
+ return 0;
73
+ }
74
+ const command = argv[0];
75
+ const rest = argv.slice(1);
76
+ if (command === 'demo') {
77
+ const { runDemo } = await Promise.resolve().then(() => __importStar(require('./demo')));
78
+ return runDemo(rest);
79
+ }
80
+ if (command === 'verify') {
81
+ const { runVerify } = await Promise.resolve().then(() => __importStar(require('./verify')));
82
+ return runVerify(rest);
83
+ }
84
+ process.stderr.write(`agentguard: unknown command '${command}'\n\n`);
85
+ process.stderr.write(HELP);
86
+ return 2;
87
+ }
88
+ // Allow `node dist/cli/main.js demo` directly
89
+ if (require.main === module) {
90
+ main().then((code) => process.exit(code), (err) => {
91
+ console.error(err);
92
+ process.exit(1);
93
+ });
94
+ }
95
+ //# sourceMappingURL=main.js.map