@libregrid/ai-gateway 1.3.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.
Files changed (46) hide show
  1. package/.env.example +36 -0
  2. package/Dockerfile +16 -0
  3. package/LICENSE +21 -0
  4. package/NOTICE +34 -0
  5. package/README.md +156 -0
  6. package/dist/conformance.d.ts +14 -0
  7. package/dist/conformance.js +57 -0
  8. package/dist/conformance.js.map +1 -0
  9. package/dist/conformanceCli.d.ts +1 -0
  10. package/dist/conformanceCli.js +277 -0
  11. package/dist/conformanceCli.js.map +1 -0
  12. package/dist/gateway.d.ts +16 -0
  13. package/dist/gateway.js +169 -0
  14. package/dist/gateway.js.map +1 -0
  15. package/dist/index.d.ts +9 -0
  16. package/dist/index.js +10 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/mockProvider.d.ts +7 -0
  19. package/dist/mockProvider.js +28 -0
  20. package/dist/mockProvider.js.map +1 -0
  21. package/dist/nodeServer.d.ts +9 -0
  22. package/dist/nodeServer.js +64 -0
  23. package/dist/nodeServer.js.map +1 -0
  24. package/dist/openAiChatCompletionsProvider.d.ts +22 -0
  25. package/dist/openAiChatCompletionsProvider.js +135 -0
  26. package/dist/openAiChatCompletionsProvider.js.map +1 -0
  27. package/dist/openAiResponsesProvider.d.ts +10 -0
  28. package/dist/openAiResponsesProvider.js +122 -0
  29. package/dist/openAiResponsesProvider.js.map +1 -0
  30. package/dist/provider.d.ts +24 -0
  31. package/dist/provider.js +15 -0
  32. package/dist/provider.js.map +1 -0
  33. package/dist/server.d.ts +1 -0
  34. package/dist/server.js +815 -0
  35. package/dist/server.js.map +1 -0
  36. package/dist/serverConfig.d.ts +1 -0
  37. package/dist/serverConfig.js +11 -0
  38. package/dist/serverConfig.js.map +1 -0
  39. package/dist/turnstile.d.ts +18 -0
  40. package/dist/turnstile.js +60 -0
  41. package/dist/turnstile.js.map +1 -0
  42. package/dist/version.d.ts +1 -0
  43. package/dist/version.js +2 -0
  44. package/dist/version.js.map +1 -0
  45. package/docker-compose.example.yml +16 -0
  46. package/package.json +24 -0
package/.env.example ADDED
@@ -0,0 +1,36 @@
1
+ # Select the provider adapter: openai-responses (default) or openai-chat.
2
+ AI_PROVIDER=openai-responses
3
+ OPENAI_API_KEY=
4
+ OPENAI_MODEL=gpt-5.6
5
+ # Optional for a compatible proxy or private gateway.
6
+ OPENAI_BASE_URL=https://api.openai.com/v1
7
+ # Optional OpenAI tenant routing headers. Responses adapter only.
8
+ OPENAI_ORGANIZATION=
9
+ OPENAI_PROJECT=
10
+ HOST=0.0.0.0
11
+ PORT=8787
12
+ # Provider response deadline. Keep this below the hosting platform's request
13
+ # timeout so the gateway can return a conformant TIMEOUT response.
14
+ GATEWAY_TIMEOUT_MS=30000
15
+
16
+ # Optional Turnstile guard for the public endpoint.
17
+ # Get the secret key from the Turnstile widget settings in the Cloudflare
18
+ # dashboard. Keep the secret key private. Never put it in browser code.
19
+ # Leave this unset for local development. The gateway skips the check.
20
+ # Set this value before you deploy to a public endpoint. An unset value
21
+ # means the endpoint accepts every request with no check.
22
+ TURNSTILE_SECRET_KEY=
23
+ # Required when TURNSTILE_SECRET_KEY is set. Siteverify must return the fixed
24
+ # grid_command action and one of these exact comma-separated hostnames.
25
+ TURNSTILE_HOSTNAMES=localhost,127.0.0.1
26
+
27
+ # OpenRouter recipe. Set AI_PROVIDER=openai-chat and use these values.
28
+ # AI_PROVIDER=openai-chat
29
+ # OPENAI_BASE_URL=https://openrouter.ai/api/v1
30
+ # OPENAI_API_KEY=sk-or-v1-...
31
+ # OPENAI_MODEL=openrouter/free
32
+ # Keep this on. It stops OpenRouter from routing to an endpoint that
33
+ # treats the JSON Schema as a hint instead of a constraint.
34
+ # OPENROUTER_REQUIRE_PARAMETERS=true
35
+ # OPENROUTER_REFERER=https://libregrid.dev
36
+ # OPENROUTER_TITLE=LibreGrid Docs
package/Dockerfile ADDED
@@ -0,0 +1,16 @@
1
+ FROM node:22-alpine AS build
2
+ WORKDIR /app
3
+ COPY package.json package-lock.json nx.json tsconfig.base.json ./
4
+ COPY tools ./tools
5
+ COPY packages ./packages
6
+ RUN npm ci
7
+ RUN npx nx build ai-protocol && npx nx build ai-gateway
8
+
9
+ FROM node:22-alpine
10
+ WORKDIR /app
11
+ ENV NODE_ENV=production HOST=0.0.0.0 PORT=8787
12
+ COPY --from=build /app/packages/ai-gateway/dist/server.js ./server.js
13
+ USER node
14
+ EXPOSE 8787
15
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 CMD node -e "fetch('http://127.0.0.1:8787/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"
16
+ CMD ["node", "server.js"]
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LibreGrid contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,34 @@
1
+ LibreGrid
2
+ Copyright (c) 2026 LibreGrid contributors
3
+
4
+ This product depends on and builds against software developed by AG Grid Ltd,
5
+ made available under the MIT License:
6
+
7
+ ag-grid-community, ag-stack, ag-grid-angular,
8
+ ag-charts-community, ag-charts-types
9
+
10
+ The MIT License
11
+
12
+ Copyright (c) 2015-2026 AG GRID LTD
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a
15
+ copy of this software and associated documentation files (the "Software"),
16
+ to deal in the Software without restriction, including without limitation
17
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
18
+ and/or sell copies of the Software, and to permit persons to whom the
19
+ Software is furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in
22
+ all copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
30
+ DEALINGS IN THE SOFTWARE.
31
+
32
+ LibreGrid is an independent open-source project. It is not affiliated with,
33
+ endorsed by, or sponsored by AG Grid Ltd. "AG Grid" is a trademark of
34
+ AG Grid Ltd.
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # @libregrid/ai-gateway
2
+
3
+ A small provider-neutral HTTP gateway for LibreGrid grid commands. It validates
4
+ the browser request, calls an injected provider through one tiny port, validates
5
+ the provider output against the live grid schema, and returns the versioned
6
+ protocol envelope. No provider credential is accepted from the browser.
7
+
8
+ ## Choose the lowest-burden integration
9
+
10
+ | Your server environment | Integration work |
11
+ | --- | --- |
12
+ | Any language, no AI route desired | Run the included container as a private sidecar/service and reverse-proxy `/v1/grid-command` through your existing authenticated API boundary. |
13
+ | Node or a Node framework with Web `Request`/`Response` support | Mount `createGridCommandHandler()` in one route; provider and validation behavior remain inside this package. |
14
+ | Java, C#, Go, Python, Rust, PHP, Ruby, or another stack | Generate a route stub from the shipped OpenAPI document, or call the sidecar. Run the conformance executable against the result. |
15
+ | Custom model/provider protocol | Implement only the small `GridModelProvider.complete()` port; the browser protocol, limits, validation, errors, and state safety remain unchanged. |
16
+
17
+ This keeps framework and identity policy outside LibreGrid without making each
18
+ consumer rebuild the provider plumbing.
19
+
20
+ ## Run the included OpenAI gateway
21
+
22
+ ```bash
23
+ OPENAI_API_KEY=... OPENAI_MODEL=gpt-5.6 npx libregrid-ai-gateway
24
+ ```
25
+
26
+ It exposes `POST /v1/grid-command` and `GET /health` on `127.0.0.1:8787` by
27
+ default. Set `HOST` and `PORT` as needed. Put the process behind your normal API
28
+ authentication, rate limiting, and TLS, or use the `authorize` hook when
29
+ embedding the handler.
30
+
31
+ Set `OPENAI_BASE_URL` to use a private or proxied endpoint that implements the
32
+ same Responses API contract. `OPENAI_ORGANIZATION` and `OPENAI_PROJECT` add the
33
+ corresponding optional routing headers. These values and `OPENAI_MODEL` are
34
+ server configuration; none are accepted from browser requests.
35
+
36
+ The included Dockerfile and `docker-compose.example.yml` provide the same
37
+ zero-code deployment. Copy `.env.example`, set the provider key in your secret
38
+ manager or local environment (never in source control), then build from the
39
+ repository root.
40
+
41
+ ```ts
42
+ import {
43
+ createGridCommandHandler,
44
+ createOpenAiResponsesProvider,
45
+ } from '@libregrid/ai-gateway';
46
+
47
+ const handler = createGridCommandHandler({
48
+ provider: createOpenAiResponsesProvider({
49
+ apiKey: () => secrets.OPENAI_API_KEY,
50
+ model: 'gpt-5.6',
51
+ }),
52
+ authorize: (request) => verifyYourSession(request),
53
+ });
54
+ ```
55
+
56
+ The OpenAI adapter uses the Responses API strict `text.format` JSON Schema
57
+ contract. There is no OpenAI SDK dependency. Inject another `GridModelProvider`
58
+ for Azure OpenAI, Anthropic, Gemini, Ollama, vLLM, LocalAI, or an internal model
59
+ gateway; the HTTP contract and browser package do not change.
60
+
61
+ `createMockProvider()` provides a deterministic, network-free adapter for CI,
62
+ local development, and contract tests. A production-oriented Dockerfile is
63
+ included. Teams implementing the endpoint in another language can generate
64
+ server stubs from `@libregrid/ai-protocol/openapi.json`.
65
+
66
+ ## OpenAI-compatible chat completions
67
+
68
+ Set `AI_PROVIDER=openai-chat` to use a service that speaks the OpenAI Chat
69
+ Completions API. OpenRouter is one such service.
70
+
71
+ ```sh
72
+ AI_PROVIDER=openai-chat
73
+ OPENAI_BASE_URL=https://openrouter.ai/api/v1
74
+ OPENAI_API_KEY=sk-or-v1-...
75
+ OPENAI_MODEL=openrouter/free
76
+ OPENROUTER_REQUIRE_PARAMETERS=true
77
+ ```
78
+
79
+ Keep `OPENROUTER_REQUIRE_PARAMETERS` on. OpenRouter serves one model through
80
+ more than one provider. Only some of those providers apply a JSON Schema as a
81
+ constraint. The others apply it as a hint. This flag tells OpenRouter to use
82
+ only the providers that apply the constraint.
83
+
84
+ The gateway validates every provider response, and the browser validates it a
85
+ second time. A weak provider therefore causes a clean `INVALID_PROVIDER_OUTPUT`
86
+ failure, not a bad grid change.
87
+
88
+ Verify any implementation—Node or otherwise—with the shipped executable:
89
+
90
+ ```bash
91
+ libregrid-ai-conformance https://your-api.example/v1/grid-command
92
+ ```
93
+
94
+ If the endpoint needs a bearer or application token, put the complete value in
95
+ `LIBREGRID_AI_AUTHORIZATION`; the tool sends it without printing it.
96
+
97
+ ## Guard the public endpoint with Turnstile
98
+
99
+ Set `TURNSTILE_SECRET_KEY` and `TURNSTILE_HOSTNAMES` to require a valid
100
+ Cloudflare Turnstile token on every request. Without the secret variable, the
101
+ gateway accepts every request with no check. If the secret is set without an
102
+ approved hostname, the process refuses to start.
103
+
104
+ Get the secret key from the Turnstile widget settings in the Cloudflare
105
+ dashboard. Keep the secret key private. Never put it in browser code or in
106
+ source control.
107
+
108
+ The Turnstile site key is a different value. The site key is public. You may
109
+ put it in browser code. You may commit it to source control.
110
+
111
+ ```bash
112
+ TURNSTILE_SECRET_KEY=0x0000000000000000000000000000000AA \
113
+ TURNSTILE_HOSTNAMES=localhost,127.0.0.1 \
114
+ npx libregrid-ai-gateway
115
+ ```
116
+
117
+ The browser client sends the token in the `x-turnstile-token` header. The
118
+ gateway requires Siteverify to return the exact action `grid_command` and a
119
+ hostname in `TURNSTILE_HOSTNAMES`. Mint a fresh token for every request. Each
120
+ Turnstile token works only once.
121
+
122
+ Set `GATEWAY_TIMEOUT_MS` to change the provider response deadline from its
123
+ 30-second default. Keep it below your hosting platform's request timeout so the
124
+ gateway can still return a conformant `TIMEOUT` response. The startup log line
125
+ reports both the provider timeout and whether Turnstile is enabled. Check this
126
+ line before you expose the endpoint publicly.
127
+
128
+ ## Production checklist
129
+
130
+ - Authenticate the caller before invoking the handler. The gateway deliberately
131
+ does not invent an identity system for your application.
132
+ - Set `TURNSTILE_SECRET_KEY` and the public deployment's exact
133
+ `TURNSTILE_HOSTNAMES` before you expose the endpoint publicly. An unset
134
+ secret means the endpoint accepts every request with no bot check.
135
+ - Store `OPENAI_API_KEY` (or another provider credential) only in server-side
136
+ secret storage. The protocol has no credential or model-name request field.
137
+ - Treat the live grid schema, current GridState, command, and context metadata
138
+ as potentially sensitive outbound data. Apply your provider/data-residency
139
+ policy and disclose it to users.
140
+ - Keep the configured model server-side. Because requests cannot select a
141
+ model, the configured provider is also the effective model allowlist.
142
+ - Retain the default 512 KiB request limit. Change the 30-second provider
143
+ timeout only from measured workload data, and keep it below the platform
144
+ request timeout. Apply rate limits at the reverse proxy or application
145
+ boundary.
146
+ - Log request IDs, status, latency, and normalized error codes—not commands,
147
+ schemas, state payloads, authorization headers, or provider keys. The built-in
148
+ log callback follows that metadata-only shape.
149
+ - Keep TLS termination, CORS, CSRF protection, and session-cookie policy in the
150
+ same trusted edge that protects the rest of your API.
151
+
152
+ ## License
153
+
154
+ MIT — see [LICENSE](./LICENSE). LibreGrid is an independent open-source
155
+ project and is not affiliated with, endorsed by, or sponsored by AG Grid Ltd.
156
+ See [NOTICE](./NOTICE) for third-party attribution.
@@ -0,0 +1,14 @@
1
+ import { AI_PROTOCOL, type GridCommandRequest, type GridCommandResponse } from '@libregrid/ai-protocol';
2
+ export interface GatewayConformanceOptions {
3
+ endpoint: string;
4
+ authorization?: string;
5
+ fetch?: typeof globalThis.fetch;
6
+ }
7
+ export interface GatewayConformanceReport {
8
+ ok: true;
9
+ endpoint: string;
10
+ protocol: typeof AI_PROTOCOL;
11
+ status: GridCommandResponse['status'];
12
+ }
13
+ export declare function conformanceRequest(): GridCommandRequest;
14
+ export declare function runGatewayConformance(options: GatewayConformanceOptions): Promise<GatewayConformanceReport>;
@@ -0,0 +1,57 @@
1
+ import { AI_PROTOCOL, revisionFor, validateGridCommandResponse, } from '@libregrid/ai-protocol';
2
+ export function conformanceRequest() {
3
+ const gridSchema = {
4
+ type: 'object',
5
+ properties: {
6
+ columnVisibility: {
7
+ type: ['object', 'null'],
8
+ properties: {
9
+ hiddenColIds: { type: 'array', items: { type: 'string', enum: ['customer', 'internalNotes'] } },
10
+ },
11
+ required: ['hiddenColIds'],
12
+ additionalProperties: false,
13
+ },
14
+ },
15
+ required: ['columnVisibility'],
16
+ additionalProperties: false,
17
+ };
18
+ const currentState = { columnVisibility: { hiddenColIds: [] } };
19
+ return {
20
+ protocol: AI_PROTOCOL,
21
+ requestId: 'libregrid-conformance',
22
+ revision: revisionFor({ gridSchema, currentState }),
23
+ command: 'Hide internal notes',
24
+ gridSchema,
25
+ currentState,
26
+ context: { totalRecordCount: 2 },
27
+ };
28
+ }
29
+ export async function runGatewayConformance(options) {
30
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
31
+ if (!fetchImplementation)
32
+ throw new Error('ai-gateway: fetch is unavailable');
33
+ const request = conformanceRequest();
34
+ const headers = { 'content-type': 'application/json' };
35
+ if (options.authorization)
36
+ headers.authorization = options.authorization;
37
+ const response = await fetchImplementation(options.endpoint, {
38
+ method: 'POST',
39
+ headers,
40
+ body: JSON.stringify(request),
41
+ });
42
+ let payload;
43
+ try {
44
+ payload = await response.json();
45
+ }
46
+ catch (cause) {
47
+ throw new Error(`AI gateway returned non-JSON data (HTTP ${response.status})`, { cause });
48
+ }
49
+ const validated = validateGridCommandResponse(request, payload);
50
+ if (!validated.ok) {
51
+ throw new Error(`AI gateway response is not conformant: ${validated.issues.map((entry) => `${entry.path}: ${entry.message}`).join('; ')}`);
52
+ }
53
+ if (!response.ok)
54
+ throw new Error(`AI gateway returned a conformant error: ${JSON.stringify(validated.value)}`);
55
+ return { ok: true, endpoint: options.endpoint, protocol: AI_PROTOCOL, status: validated.value.status };
56
+ }
57
+ //# sourceMappingURL=conformance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conformance.js","sourceRoot":"","sources":["../src/conformance.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,277 @@
1
+ #!/usr/bin/env node
2
+
3
+ // packages/ai-protocol/src/types.ts
4
+ var AI_PROTOCOL = "libregrid.ai/v1";
5
+ var GRID_STATE_KEYS = [
6
+ "aggregation",
7
+ "columnGroup",
8
+ "columnOrder",
9
+ "columnPinning",
10
+ "columnSizing",
11
+ "columnVisibility",
12
+ "columnHeaderName",
13
+ "filter",
14
+ "focusedCell",
15
+ "pagination",
16
+ "rowPinning",
17
+ "pivot",
18
+ "cellSelection",
19
+ "rowGroup",
20
+ "rowGroupExpansion",
21
+ "ssrmRowGroupExpansion",
22
+ "rowSelection",
23
+ "scroll",
24
+ "sideBar",
25
+ "sort",
26
+ "showValuesAs",
27
+ "userColumns"
28
+ ];
29
+
30
+ // packages/ai-protocol/src/providerSchema.ts
31
+ function isRecord(value) {
32
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
33
+ }
34
+ function buildProviderOutputSchema(gridSchema) {
35
+ if (gridSchema.type !== "object" || !isRecord(gridSchema.properties)) {
36
+ throw new Error("ai-protocol: gridSchema must be a root object schema");
37
+ }
38
+ const { $defs, ...gridState } = gridSchema;
39
+ const includedFeatures = Object.keys(gridSchema.properties).filter((key) => GRID_STATE_KEYS.includes(key));
40
+ const ignoreItems = includedFeatures.length > 0 ? { type: "string", enum: includedFeatures } : { type: "string" };
41
+ const result = {
42
+ type: "object",
43
+ properties: {
44
+ gridState,
45
+ propertiesToIgnore: {
46
+ type: "array",
47
+ items: ignoreItems,
48
+ maxItems: includedFeatures.length,
49
+ description: "GridState keys that must remain untouched. Include every nullable gridState feature returned as null."
50
+ },
51
+ explanation: {
52
+ type: "string",
53
+ maxLength: 2e3,
54
+ description: "A short user-facing explanation of the proposed grid changes."
55
+ }
56
+ },
57
+ required: ["gridState", "propertiesToIgnore", "explanation"],
58
+ additionalProperties: false
59
+ };
60
+ if (isRecord($defs) && Object.keys($defs).length > 0) result.$defs = $defs;
61
+ return result;
62
+ }
63
+
64
+ // packages/ai-protocol/src/validator.ts
65
+ function isRecord2(value) {
66
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
67
+ }
68
+ function issue(path, message) {
69
+ return { path, message };
70
+ }
71
+ function unknownKeys(value, allowed, path) {
72
+ const accepted = new Set(allowed);
73
+ return Object.keys(value).filter((key) => !accepted.has(key)).map((key) => issue(`${path}.${key}`, "is not allowed"));
74
+ }
75
+ function sameJson(left, right) {
76
+ return JSON.stringify(left) === JSON.stringify(right);
77
+ }
78
+ function resolveReference(root, reference) {
79
+ if (!reference.startsWith("#/$defs/")) return void 0;
80
+ const name = reference.slice("#/$defs/".length);
81
+ const definitions = root.$defs;
82
+ if (!isRecord2(definitions)) return void 0;
83
+ const target = definitions[name];
84
+ return isRecord2(target) ? target : void 0;
85
+ }
86
+ function matchesType(type, value) {
87
+ if (type === "null") return value === null;
88
+ if (type === "array") return Array.isArray(value);
89
+ if (type === "object") return isRecord2(value);
90
+ if (type === "integer") return typeof value === "number" && Number.isInteger(value);
91
+ return typeof value === type;
92
+ }
93
+ function validateAt(schema, value, root, path, depth) {
94
+ if (depth > 64) return [issue(path, "exceeded maximum validation depth")];
95
+ if (typeof schema.$ref === "string") {
96
+ const resolved = resolveReference(root, schema.$ref);
97
+ return resolved ? validateAt(resolved, value, root, path, depth + 1) : [issue(path, `unresolved reference ${schema.$ref}`)];
98
+ }
99
+ if (Array.isArray(schema.anyOf)) {
100
+ if (schema.anyOf.some((option) => isRecord2(option) && validateAt(option, value, root, path, depth + 1).length === 0)) return [];
101
+ return [issue(path, "did not match any allowed schema variant")];
102
+ }
103
+ if ("const" in schema && !sameJson(schema.const, value)) return [issue(path, `must equal ${JSON.stringify(schema.const)}`)];
104
+ if (Array.isArray(schema.enum) && !schema.enum.some((allowed) => sameJson(allowed, value))) {
105
+ return [issue(path, "must be one of the allowed values")];
106
+ }
107
+ const types = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
108
+ if (types.length > 0 && !types.some((type) => typeof type === "string" && matchesType(type, value))) {
109
+ return [issue(path, `must be ${types.join(" or ")}`)];
110
+ }
111
+ if (isRecord2(value) && (schema.type === "object" || Array.isArray(schema.type) && schema.type.includes("object"))) {
112
+ const properties = isRecord2(schema.properties) ? schema.properties : {};
113
+ const required = Array.isArray(schema.required) ? schema.required.filter((key) => typeof key === "string") : [];
114
+ const issues = [];
115
+ for (const key of required) if (!(key in value)) issues.push(issue(`${path}.${key}`, "is required"));
116
+ if (schema.additionalProperties === false) {
117
+ for (const key of Object.keys(value)) if (!(key in properties)) issues.push(issue(`${path}.${key}`, "is not allowed"));
118
+ }
119
+ for (const [key, propertySchema] of Object.entries(properties)) {
120
+ if (key in value && isRecord2(propertySchema)) {
121
+ issues.push(...validateAt(propertySchema, value[key], root, `${path}.${key}`, depth + 1));
122
+ }
123
+ }
124
+ return issues;
125
+ }
126
+ if (Array.isArray(value) && schema.type === "array") {
127
+ const issues = [];
128
+ if (typeof schema.minItems === "number" && value.length < schema.minItems) issues.push(issue(path, `must contain at least ${schema.minItems} items`));
129
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems) issues.push(issue(path, `must contain at most ${schema.maxItems} items`));
130
+ if (isRecord2(schema.items)) value.forEach((entry, index) => issues.push(...validateAt(schema.items, entry, root, `${path}[${index}]`, depth + 1)));
131
+ return issues;
132
+ }
133
+ if (typeof value === "number") {
134
+ if (typeof schema.minimum === "number" && value < schema.minimum) return [issue(path, `must be >= ${schema.minimum}`)];
135
+ if (typeof schema.maximum === "number" && value > schema.maximum) return [issue(path, `must be <= ${schema.maximum}`)];
136
+ }
137
+ if (typeof value === "string" && typeof schema.pattern === "string") {
138
+ try {
139
+ if (!new RegExp(schema.pattern).test(value)) return [issue(path, `must match ${schema.pattern}`)];
140
+ } catch {
141
+ return [issue(path, "schema contains an invalid pattern")];
142
+ }
143
+ }
144
+ if (typeof value === "string") {
145
+ if (typeof schema.minLength === "number" && value.length < schema.minLength) return [issue(path, `must contain at least ${schema.minLength} characters`)];
146
+ if (typeof schema.maxLength === "number" && value.length > schema.maxLength) return [issue(path, `must contain at most ${schema.maxLength} characters`)];
147
+ }
148
+ return [];
149
+ }
150
+ function validateJsonSchemaInstance(schema, value) {
151
+ const issues = validateAt(schema, value, schema, "$", 0);
152
+ return issues.length === 0 ? { ok: true, value } : { ok: false, issues };
153
+ }
154
+ function validateProviderGridOutput(request, value) {
155
+ const result = validateJsonSchemaInstance(buildProviderOutputSchema(request.gridSchema), value);
156
+ if (!result.ok) return result;
157
+ const raw = value;
158
+ const ignored = new Set(raw.propertiesToIgnore);
159
+ for (const [feature, featureValue] of Object.entries(raw.gridState)) {
160
+ if (!GRID_STATE_KEYS.includes(feature)) continue;
161
+ if (featureValue === null) ignored.add(feature);
162
+ else if (ignored.has(feature)) {
163
+ return { ok: false, issues: [issue(`$.propertiesToIgnore`, `cannot ignore non-null gridState feature ${feature}`)] };
164
+ }
165
+ }
166
+ return { ok: true, value: { ...raw, propertiesToIgnore: GRID_STATE_KEYS.filter((key) => ignored.has(key)) } };
167
+ }
168
+ function validateGridCommandResponse(request, value) {
169
+ if (!isRecord2(value)) return { ok: false, issues: [issue("$", "response must be an object")] };
170
+ const issues = [];
171
+ if (value.protocol !== AI_PROTOCOL) issues.push(issue("$.protocol", `must equal ${AI_PROTOCOL}`));
172
+ if (value.requestId !== request.requestId) issues.push(issue("$.requestId", "does not match request"));
173
+ if (value.revision !== request.revision) issues.push(issue("$.revision", "does not match request"));
174
+ if (value.status === "ok") {
175
+ issues.push(...unknownKeys(value, ["protocol", "requestId", "revision", "status", "output", "provider"], "$"));
176
+ const output = validateProviderGridOutput(request, value.output);
177
+ if (!output.ok) issues.push(...output.issues.map((entry) => ({ ...entry, path: `$.output${entry.path.slice(1)}` })));
178
+ if (!isRecord2(value.provider)) issues.push(issue("$.provider", "must be an object"));
179
+ else {
180
+ issues.push(...unknownKeys(value.provider, ["service", "model", "providerRequestId", "latencyMs"], "$.provider"));
181
+ if (typeof value.provider.service !== "string" || value.provider.service === "") issues.push(issue("$.provider.service", "must be a non-empty string"));
182
+ if (typeof value.provider.model !== "string" || value.provider.model === "") issues.push(issue("$.provider.model", "must be a non-empty string"));
183
+ if (value.provider.providerRequestId !== null && typeof value.provider.providerRequestId !== "string") issues.push(issue("$.provider.providerRequestId", "must be a string or null"));
184
+ if (typeof value.provider.latencyMs !== "number" || value.provider.latencyMs < 0) issues.push(issue("$.provider.latencyMs", "must be a non-negative number"));
185
+ }
186
+ } else if (value.status === "error") {
187
+ issues.push(...unknownKeys(value, ["protocol", "requestId", "revision", "status", "error"], "$"));
188
+ if (!isRecord2(value.error) || typeof value.error.code !== "string" || typeof value.error.message !== "string" || typeof value.error.retryable !== "boolean") {
189
+ issues.push(issue("$.error", "must contain code, message, and retryable"));
190
+ } else {
191
+ issues.push(...unknownKeys(value.error, ["code", "message", "retryable"], "$.error"));
192
+ const codes = ["BAD_REQUEST", "MODEL_REFUSAL", "PROVIDER_ERROR", "RATE_LIMITED", "TIMEOUT", "INVALID_PROVIDER_OUTPUT", "INTERNAL_ERROR"];
193
+ if (!codes.includes(value.error.code)) issues.push(issue("$.error.code", "is not a supported error code"));
194
+ }
195
+ } else issues.push(issue("$.status", "must be ok or error"));
196
+ return issues.length === 0 ? { ok: true, value } : { ok: false, issues };
197
+ }
198
+
199
+ // packages/ai-protocol/src/stableJson.ts
200
+ function stableJson(value) {
201
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
202
+ if (value && typeof value === "object") {
203
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key] ?? null)}`).join(",")}}`;
204
+ }
205
+ return JSON.stringify(value);
206
+ }
207
+ function revisionFor(value) {
208
+ const text = stableJson(value);
209
+ let hash = 2166136261;
210
+ for (let index = 0; index < text.length; index += 1) {
211
+ hash ^= text.charCodeAt(index);
212
+ hash = Math.imul(hash, 16777619);
213
+ }
214
+ return `fnv1a-${(hash >>> 0).toString(16).padStart(8, "0")}`;
215
+ }
216
+
217
+ // packages/ai-gateway/src/conformance.ts
218
+ function conformanceRequest() {
219
+ const gridSchema = {
220
+ type: "object",
221
+ properties: {
222
+ columnVisibility: {
223
+ type: ["object", "null"],
224
+ properties: {
225
+ hiddenColIds: { type: "array", items: { type: "string", enum: ["customer", "internalNotes"] } }
226
+ },
227
+ required: ["hiddenColIds"],
228
+ additionalProperties: false
229
+ }
230
+ },
231
+ required: ["columnVisibility"],
232
+ additionalProperties: false
233
+ };
234
+ const currentState = { columnVisibility: { hiddenColIds: [] } };
235
+ return {
236
+ protocol: AI_PROTOCOL,
237
+ requestId: "libregrid-conformance",
238
+ revision: revisionFor({ gridSchema, currentState }),
239
+ command: "Hide internal notes",
240
+ gridSchema,
241
+ currentState,
242
+ context: { totalRecordCount: 2 }
243
+ };
244
+ }
245
+ async function runGatewayConformance(options) {
246
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
247
+ if (!fetchImplementation) throw new Error("ai-gateway: fetch is unavailable");
248
+ const request = conformanceRequest();
249
+ const headers = { "content-type": "application/json" };
250
+ if (options.authorization) headers.authorization = options.authorization;
251
+ const response = await fetchImplementation(options.endpoint, {
252
+ method: "POST",
253
+ headers,
254
+ body: JSON.stringify(request)
255
+ });
256
+ let payload;
257
+ try {
258
+ payload = await response.json();
259
+ } catch (cause) {
260
+ throw new Error(`AI gateway returned non-JSON data (HTTP ${response.status})`, { cause });
261
+ }
262
+ const validated = validateGridCommandResponse(request, payload);
263
+ if (!validated.ok) {
264
+ throw new Error(`AI gateway response is not conformant: ${validated.issues.map((entry) => `${entry.path}: ${entry.message}`).join("; ")}`);
265
+ }
266
+ if (!response.ok) throw new Error(`AI gateway returned a conformant error: ${JSON.stringify(validated.value)}`);
267
+ return { ok: true, endpoint: options.endpoint, protocol: AI_PROTOCOL, status: validated.value.status };
268
+ }
269
+
270
+ // packages/ai-gateway/src/conformanceCli.ts
271
+ var endpoint = process.argv[2] ?? process.env.LIBREGRID_AI_ENDPOINT ?? "http://127.0.0.1:8787/v1/grid-command";
272
+ var report = await runGatewayConformance({
273
+ endpoint,
274
+ ...process.env.LIBREGRID_AI_AUTHORIZATION ? { authorization: process.env.LIBREGRID_AI_AUTHORIZATION } : {}
275
+ });
276
+ process.stdout.write(`${JSON.stringify(report, null, 2)}
277
+ `);
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conformanceCli.js","sourceRoot":"","sources":["../src/conformanceCli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAEtD,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,qBAAqB,IAAI,uCAAuC,CAAC;AACjH,MAAM,MAAM,GAAG,MAAM,qBAAqB,CAAC;IACzC,QAAQ;IACR,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,OAAO,CAAC,GAAG,CAAC,0BAA0B,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;CAC7G,CAAC,CAAC;AACH,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC"}
@@ -0,0 +1,16 @@
1
+ import { type GridCommandErrorCode } from '@libregrid/ai-protocol';
2
+ import { type GridModelProvider } from './provider';
3
+ export interface GatewayLogEvent {
4
+ event: 'completed' | 'failed' | 'rejected';
5
+ requestId: string;
6
+ code?: GridCommandErrorCode;
7
+ latencyMs: number;
8
+ }
9
+ export interface GridCommandGatewayOptions {
10
+ provider: GridModelProvider;
11
+ authorize?: (request: Request) => boolean | Promise<boolean>;
12
+ maxBodyBytes?: number;
13
+ timeoutMs?: number;
14
+ log?: (event: GatewayLogEvent) => void;
15
+ }
16
+ export declare function createGridCommandHandler(options: GridCommandGatewayOptions): (request: Request) => Promise<Response>;