@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.
- package/.env.example +36 -0
- package/Dockerfile +16 -0
- package/LICENSE +21 -0
- package/NOTICE +34 -0
- package/README.md +156 -0
- package/dist/conformance.d.ts +14 -0
- package/dist/conformance.js +57 -0
- package/dist/conformance.js.map +1 -0
- package/dist/conformanceCli.d.ts +1 -0
- package/dist/conformanceCli.js +277 -0
- package/dist/conformanceCli.js.map +1 -0
- package/dist/gateway.d.ts +16 -0
- package/dist/gateway.js +169 -0
- package/dist/gateway.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/mockProvider.d.ts +7 -0
- package/dist/mockProvider.js +28 -0
- package/dist/mockProvider.js.map +1 -0
- package/dist/nodeServer.d.ts +9 -0
- package/dist/nodeServer.js +64 -0
- package/dist/nodeServer.js.map +1 -0
- package/dist/openAiChatCompletionsProvider.d.ts +22 -0
- package/dist/openAiChatCompletionsProvider.js +135 -0
- package/dist/openAiChatCompletionsProvider.js.map +1 -0
- package/dist/openAiResponsesProvider.d.ts +10 -0
- package/dist/openAiResponsesProvider.js +122 -0
- package/dist/openAiResponsesProvider.js.map +1 -0
- package/dist/provider.d.ts +24 -0
- package/dist/provider.js +15 -0
- package/dist/provider.js.map +1 -0
- package/dist/server.d.ts +1 -0
- package/dist/server.js +815 -0
- package/dist/server.js.map +1 -0
- package/dist/serverConfig.d.ts +1 -0
- package/dist/serverConfig.js +11 -0
- package/dist/serverConfig.js.map +1 -0
- package/dist/turnstile.d.ts +18 -0
- package/dist/turnstile.js +60 -0
- package/dist/turnstile.js.map +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +2 -0
- package/dist/version.js.map +1 -0
- package/docker-compose.example.yml +16 -0
- package/package.json +24 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,815 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// packages/ai-protocol/src/types.ts
|
|
4
|
+
var AI_PROTOCOL = "libregrid.ai/v1";
|
|
5
|
+
var GRID_FEATURES = [
|
|
6
|
+
"aggregation",
|
|
7
|
+
"filter",
|
|
8
|
+
"sort",
|
|
9
|
+
"pivot",
|
|
10
|
+
"columnVisibility",
|
|
11
|
+
"columnSizing",
|
|
12
|
+
"rowGroup"
|
|
13
|
+
];
|
|
14
|
+
var GRID_STATE_KEYS = [
|
|
15
|
+
"aggregation",
|
|
16
|
+
"columnGroup",
|
|
17
|
+
"columnOrder",
|
|
18
|
+
"columnPinning",
|
|
19
|
+
"columnSizing",
|
|
20
|
+
"columnVisibility",
|
|
21
|
+
"columnHeaderName",
|
|
22
|
+
"filter",
|
|
23
|
+
"focusedCell",
|
|
24
|
+
"pagination",
|
|
25
|
+
"rowPinning",
|
|
26
|
+
"pivot",
|
|
27
|
+
"cellSelection",
|
|
28
|
+
"rowGroup",
|
|
29
|
+
"rowGroupExpansion",
|
|
30
|
+
"ssrmRowGroupExpansion",
|
|
31
|
+
"rowSelection",
|
|
32
|
+
"scroll",
|
|
33
|
+
"sideBar",
|
|
34
|
+
"sort",
|
|
35
|
+
"showValuesAs",
|
|
36
|
+
"userColumns"
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
// packages/ai-protocol/src/providerSchema.ts
|
|
40
|
+
function isRecord(value) {
|
|
41
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
42
|
+
}
|
|
43
|
+
function buildProviderOutputSchema(gridSchema) {
|
|
44
|
+
if (gridSchema.type !== "object" || !isRecord(gridSchema.properties)) {
|
|
45
|
+
throw new Error("ai-protocol: gridSchema must be a root object schema");
|
|
46
|
+
}
|
|
47
|
+
const { $defs, ...gridState } = gridSchema;
|
|
48
|
+
const includedFeatures = Object.keys(gridSchema.properties).filter((key) => GRID_STATE_KEYS.includes(key));
|
|
49
|
+
const ignoreItems = includedFeatures.length > 0 ? { type: "string", enum: includedFeatures } : { type: "string" };
|
|
50
|
+
const result = {
|
|
51
|
+
type: "object",
|
|
52
|
+
properties: {
|
|
53
|
+
gridState,
|
|
54
|
+
propertiesToIgnore: {
|
|
55
|
+
type: "array",
|
|
56
|
+
items: ignoreItems,
|
|
57
|
+
maxItems: includedFeatures.length,
|
|
58
|
+
description: "GridState keys that must remain untouched. Include every nullable gridState feature returned as null."
|
|
59
|
+
},
|
|
60
|
+
explanation: {
|
|
61
|
+
type: "string",
|
|
62
|
+
maxLength: 2e3,
|
|
63
|
+
description: "A short user-facing explanation of the proposed grid changes."
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
required: ["gridState", "propertiesToIgnore", "explanation"],
|
|
67
|
+
additionalProperties: false
|
|
68
|
+
};
|
|
69
|
+
if (isRecord($defs) && Object.keys($defs).length > 0) result.$defs = $defs;
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
function buildProviderPrompt(request) {
|
|
73
|
+
const applicable = isRecord(request.gridSchema.properties) ? Object.keys(request.gridSchema.properties).filter((key) => GRID_FEATURES.includes(key)) : [];
|
|
74
|
+
return {
|
|
75
|
+
system: [
|
|
76
|
+
"You translate one natural-language command into AG Grid state.",
|
|
77
|
+
"Use only column ids and capabilities allowed by the supplied strict output schema.",
|
|
78
|
+
"Preserve current state unless the command asks to change it.",
|
|
79
|
+
"For every applicable feature not changed by the command, return null and include that feature in propertiesToIgnore.",
|
|
80
|
+
"Never invent row values, columns, operators, aggregation functions, or unsupported state.",
|
|
81
|
+
"If the command is impossible or ambiguous, preserve every feature and explain why."
|
|
82
|
+
].join(" "),
|
|
83
|
+
user: JSON.stringify({
|
|
84
|
+
command: request.command,
|
|
85
|
+
applicableFeatures: applicable,
|
|
86
|
+
currentState: request.currentState,
|
|
87
|
+
context: request.context
|
|
88
|
+
})
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// packages/ai-protocol/src/validator.ts
|
|
93
|
+
function isRecord2(value) {
|
|
94
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
95
|
+
}
|
|
96
|
+
function issue(path, message) {
|
|
97
|
+
return { path, message };
|
|
98
|
+
}
|
|
99
|
+
function unknownKeys(value, allowed, path) {
|
|
100
|
+
const accepted = new Set(allowed);
|
|
101
|
+
return Object.keys(value).filter((key) => !accepted.has(key)).map((key) => issue(`${path}.${key}`, "is not allowed"));
|
|
102
|
+
}
|
|
103
|
+
function sameJson(left, right) {
|
|
104
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
105
|
+
}
|
|
106
|
+
function resolveReference(root, reference) {
|
|
107
|
+
if (!reference.startsWith("#/$defs/")) return void 0;
|
|
108
|
+
const name = reference.slice("#/$defs/".length);
|
|
109
|
+
const definitions = root.$defs;
|
|
110
|
+
if (!isRecord2(definitions)) return void 0;
|
|
111
|
+
const target = definitions[name];
|
|
112
|
+
return isRecord2(target) ? target : void 0;
|
|
113
|
+
}
|
|
114
|
+
function matchesType(type, value) {
|
|
115
|
+
if (type === "null") return value === null;
|
|
116
|
+
if (type === "array") return Array.isArray(value);
|
|
117
|
+
if (type === "object") return isRecord2(value);
|
|
118
|
+
if (type === "integer") return typeof value === "number" && Number.isInteger(value);
|
|
119
|
+
return typeof value === type;
|
|
120
|
+
}
|
|
121
|
+
function validateAt(schema, value, root, path, depth) {
|
|
122
|
+
if (depth > 64) return [issue(path, "exceeded maximum validation depth")];
|
|
123
|
+
if (typeof schema.$ref === "string") {
|
|
124
|
+
const resolved = resolveReference(root, schema.$ref);
|
|
125
|
+
return resolved ? validateAt(resolved, value, root, path, depth + 1) : [issue(path, `unresolved reference ${schema.$ref}`)];
|
|
126
|
+
}
|
|
127
|
+
if (Array.isArray(schema.anyOf)) {
|
|
128
|
+
if (schema.anyOf.some((option) => isRecord2(option) && validateAt(option, value, root, path, depth + 1).length === 0)) return [];
|
|
129
|
+
return [issue(path, "did not match any allowed schema variant")];
|
|
130
|
+
}
|
|
131
|
+
if ("const" in schema && !sameJson(schema.const, value)) return [issue(path, `must equal ${JSON.stringify(schema.const)}`)];
|
|
132
|
+
if (Array.isArray(schema.enum) && !schema.enum.some((allowed) => sameJson(allowed, value))) {
|
|
133
|
+
return [issue(path, "must be one of the allowed values")];
|
|
134
|
+
}
|
|
135
|
+
const types = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
|
|
136
|
+
if (types.length > 0 && !types.some((type) => typeof type === "string" && matchesType(type, value))) {
|
|
137
|
+
return [issue(path, `must be ${types.join(" or ")}`)];
|
|
138
|
+
}
|
|
139
|
+
if (isRecord2(value) && (schema.type === "object" || Array.isArray(schema.type) && schema.type.includes("object"))) {
|
|
140
|
+
const properties = isRecord2(schema.properties) ? schema.properties : {};
|
|
141
|
+
const required = Array.isArray(schema.required) ? schema.required.filter((key) => typeof key === "string") : [];
|
|
142
|
+
const issues = [];
|
|
143
|
+
for (const key of required) if (!(key in value)) issues.push(issue(`${path}.${key}`, "is required"));
|
|
144
|
+
if (schema.additionalProperties === false) {
|
|
145
|
+
for (const key of Object.keys(value)) if (!(key in properties)) issues.push(issue(`${path}.${key}`, "is not allowed"));
|
|
146
|
+
}
|
|
147
|
+
for (const [key, propertySchema] of Object.entries(properties)) {
|
|
148
|
+
if (key in value && isRecord2(propertySchema)) {
|
|
149
|
+
issues.push(...validateAt(propertySchema, value[key], root, `${path}.${key}`, depth + 1));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return issues;
|
|
153
|
+
}
|
|
154
|
+
if (Array.isArray(value) && schema.type === "array") {
|
|
155
|
+
const issues = [];
|
|
156
|
+
if (typeof schema.minItems === "number" && value.length < schema.minItems) issues.push(issue(path, `must contain at least ${schema.minItems} items`));
|
|
157
|
+
if (typeof schema.maxItems === "number" && value.length > schema.maxItems) issues.push(issue(path, `must contain at most ${schema.maxItems} items`));
|
|
158
|
+
if (isRecord2(schema.items)) value.forEach((entry, index) => issues.push(...validateAt(schema.items, entry, root, `${path}[${index}]`, depth + 1)));
|
|
159
|
+
return issues;
|
|
160
|
+
}
|
|
161
|
+
if (typeof value === "number") {
|
|
162
|
+
if (typeof schema.minimum === "number" && value < schema.minimum) return [issue(path, `must be >= ${schema.minimum}`)];
|
|
163
|
+
if (typeof schema.maximum === "number" && value > schema.maximum) return [issue(path, `must be <= ${schema.maximum}`)];
|
|
164
|
+
}
|
|
165
|
+
if (typeof value === "string" && typeof schema.pattern === "string") {
|
|
166
|
+
try {
|
|
167
|
+
if (!new RegExp(schema.pattern).test(value)) return [issue(path, `must match ${schema.pattern}`)];
|
|
168
|
+
} catch {
|
|
169
|
+
return [issue(path, "schema contains an invalid pattern")];
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (typeof value === "string") {
|
|
173
|
+
if (typeof schema.minLength === "number" && value.length < schema.minLength) return [issue(path, `must contain at least ${schema.minLength} characters`)];
|
|
174
|
+
if (typeof schema.maxLength === "number" && value.length > schema.maxLength) return [issue(path, `must contain at most ${schema.maxLength} characters`)];
|
|
175
|
+
}
|
|
176
|
+
return [];
|
|
177
|
+
}
|
|
178
|
+
function validateJsonSchemaInstance(schema, value) {
|
|
179
|
+
const issues = validateAt(schema, value, schema, "$", 0);
|
|
180
|
+
return issues.length === 0 ? { ok: true, value } : { ok: false, issues };
|
|
181
|
+
}
|
|
182
|
+
function inspectStrictSchema(schema, root, path, seen) {
|
|
183
|
+
if (seen.has(schema)) return [];
|
|
184
|
+
seen.add(schema);
|
|
185
|
+
if (typeof schema.$ref === "string") {
|
|
186
|
+
const resolved = resolveReference(root, schema.$ref);
|
|
187
|
+
return resolved ? inspectStrictSchema(resolved, root, path, seen) : [issue(path, `unresolved or non-local reference ${schema.$ref}`)];
|
|
188
|
+
}
|
|
189
|
+
const issues = [];
|
|
190
|
+
if (schema.type === "object" || Array.isArray(schema.type) && schema.type.includes("object")) {
|
|
191
|
+
const props = isRecord2(schema.properties) ? schema.properties : {};
|
|
192
|
+
if (schema.additionalProperties !== false) issues.push(issue(path, "object schema must set additionalProperties to false"));
|
|
193
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
194
|
+
if (!sameJson([...required].sort(), Object.keys(props).sort())) issues.push(issue(path, "object schema must require every property"));
|
|
195
|
+
}
|
|
196
|
+
for (const key of ["properties", "$defs"]) {
|
|
197
|
+
const collection = schema[key];
|
|
198
|
+
if (isRecord2(collection)) {
|
|
199
|
+
for (const [name, child] of Object.entries(collection)) if (isRecord2(child)) issues.push(...inspectStrictSchema(child, root, `${path}.${key}.${name}`, seen));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (isRecord2(schema.items)) issues.push(...inspectStrictSchema(schema.items, root, `${path}.items`, seen));
|
|
203
|
+
if (Array.isArray(schema.anyOf)) {
|
|
204
|
+
schema.anyOf.forEach((child, index) => {
|
|
205
|
+
if (isRecord2(child)) issues.push(...inspectStrictSchema(child, root, `${path}.anyOf[${index}]`, seen));
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
return issues;
|
|
209
|
+
}
|
|
210
|
+
function validateGridSchema(schema) {
|
|
211
|
+
if (!isRecord2(schema)) return { ok: false, issues: [issue("$.gridSchema", "must be an object")] };
|
|
212
|
+
const issues = [];
|
|
213
|
+
if (schema.type !== "object") issues.push(issue("$.gridSchema.type", "root must be an object schema"));
|
|
214
|
+
if (!isRecord2(schema.properties)) issues.push(issue("$.gridSchema.properties", "must be an object"));
|
|
215
|
+
else {
|
|
216
|
+
for (const key of Object.keys(schema.properties)) if (!GRID_FEATURES.includes(key)) {
|
|
217
|
+
issues.push(issue(`$.gridSchema.properties.${key}`, "is not a supported AI grid feature"));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
issues.push(...inspectStrictSchema(schema, schema, "$.gridSchema", /* @__PURE__ */ new Set()));
|
|
221
|
+
return issues.length === 0 ? { ok: true, value: schema } : { ok: false, issues };
|
|
222
|
+
}
|
|
223
|
+
function validateGridCommandRequest(value) {
|
|
224
|
+
if (!isRecord2(value)) return { ok: false, issues: [issue("$", "request must be an object")] };
|
|
225
|
+
const issues = [];
|
|
226
|
+
issues.push(...unknownKeys(value, ["protocol", "requestId", "revision", "command", "gridSchema", "currentState", "context"], "$"));
|
|
227
|
+
if (value.protocol !== AI_PROTOCOL) issues.push(issue("$.protocol", `must equal ${AI_PROTOCOL}`));
|
|
228
|
+
for (const key of ["requestId", "revision", "command"]) {
|
|
229
|
+
if (typeof value[key] !== "string" || value[key].trim() === "") issues.push(issue(`$.${key}`, "must be a non-empty string"));
|
|
230
|
+
}
|
|
231
|
+
if (typeof value.requestId === "string" && value.requestId.length > 128) issues.push(issue("$.requestId", "must contain at most 128 characters"));
|
|
232
|
+
if (typeof value.revision === "string" && value.revision.length > 128) issues.push(issue("$.revision", "must contain at most 128 characters"));
|
|
233
|
+
if (typeof value.command === "string" && value.command.length > 4e3) issues.push(issue("$.command", "must contain at most 4000 characters"));
|
|
234
|
+
if (!isRecord2(value.currentState)) issues.push(issue("$.currentState", "must be an object"));
|
|
235
|
+
if (!isRecord2(value.context)) issues.push(issue("$.context", "must be an object"));
|
|
236
|
+
else {
|
|
237
|
+
issues.push(...unknownKeys(value.context, ["currentPage", "density", "pageSize", "totalRecordCount", "facts"], "$.context"));
|
|
238
|
+
for (const key of ["currentPage", "pageSize", "totalRecordCount"]) {
|
|
239
|
+
const entry = value.context[key];
|
|
240
|
+
if (entry !== void 0 && (typeof entry !== "number" || !Number.isInteger(entry) || entry < 0)) issues.push(issue(`$.context.${key}`, "must be a non-negative integer"));
|
|
241
|
+
}
|
|
242
|
+
if (value.context.pageSize === 0) issues.push(issue("$.context.pageSize", "must be greater than zero"));
|
|
243
|
+
if (value.context.density !== void 0 && typeof value.context.density !== "string") issues.push(issue("$.context.density", "must be a string"));
|
|
244
|
+
if (value.context.facts !== void 0 && !isRecord2(value.context.facts)) issues.push(issue("$.context.facts", "must be an object"));
|
|
245
|
+
}
|
|
246
|
+
const schemaResult = validateGridSchema(value.gridSchema);
|
|
247
|
+
if (!schemaResult.ok) issues.push(...schemaResult.issues);
|
|
248
|
+
return issues.length === 0 ? { ok: true, value } : { ok: false, issues };
|
|
249
|
+
}
|
|
250
|
+
function validateProviderGridOutput(request, value) {
|
|
251
|
+
const result = validateJsonSchemaInstance(buildProviderOutputSchema(request.gridSchema), value);
|
|
252
|
+
if (!result.ok) return result;
|
|
253
|
+
const raw = value;
|
|
254
|
+
const ignored = new Set(raw.propertiesToIgnore);
|
|
255
|
+
for (const [feature, featureValue] of Object.entries(raw.gridState)) {
|
|
256
|
+
if (!GRID_STATE_KEYS.includes(feature)) continue;
|
|
257
|
+
if (featureValue === null) ignored.add(feature);
|
|
258
|
+
else if (ignored.has(feature)) {
|
|
259
|
+
return { ok: false, issues: [issue(`$.propertiesToIgnore`, `cannot ignore non-null gridState feature ${feature}`)] };
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return { ok: true, value: { ...raw, propertiesToIgnore: GRID_STATE_KEYS.filter((key) => ignored.has(key)) } };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// packages/ai-gateway/src/provider.ts
|
|
266
|
+
var ModelProviderError = class extends Error {
|
|
267
|
+
constructor(code, message, retryable, status, cause) {
|
|
268
|
+
super(message);
|
|
269
|
+
this.code = code;
|
|
270
|
+
this.retryable = retryable;
|
|
271
|
+
this.status = status;
|
|
272
|
+
this.cause = cause;
|
|
273
|
+
this.name = "ModelProviderError";
|
|
274
|
+
}
|
|
275
|
+
code;
|
|
276
|
+
retryable;
|
|
277
|
+
status;
|
|
278
|
+
cause;
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
// packages/ai-gateway/src/gateway.ts
|
|
282
|
+
var RESPONSE_HEADERS = {
|
|
283
|
+
"cache-control": "no-store",
|
|
284
|
+
"content-type": "application/json; charset=utf-8",
|
|
285
|
+
"x-content-type-options": "nosniff"
|
|
286
|
+
};
|
|
287
|
+
function jsonResponse(body, status) {
|
|
288
|
+
return new Response(JSON.stringify(body), { status, headers: RESPONSE_HEADERS });
|
|
289
|
+
}
|
|
290
|
+
function identifiers(value) {
|
|
291
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return { requestId: "", revision: "" };
|
|
292
|
+
const item = value;
|
|
293
|
+
return {
|
|
294
|
+
requestId: typeof item.requestId === "string" ? item.requestId : "",
|
|
295
|
+
revision: typeof item.revision === "string" ? item.revision : ""
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
function failure(identity, code, message, retryable) {
|
|
299
|
+
return {
|
|
300
|
+
protocol: AI_PROTOCOL,
|
|
301
|
+
requestId: identity.requestId,
|
|
302
|
+
revision: identity.revision,
|
|
303
|
+
status: "error",
|
|
304
|
+
error: { code, message, retryable }
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
async function readBody(request, maxBytes) {
|
|
308
|
+
const declared = Number(request.headers.get("content-length"));
|
|
309
|
+
if (Number.isFinite(declared) && declared > maxBytes) throw new RangeError("request body is too large");
|
|
310
|
+
if (!request.body) throw new SyntaxError("request body is required");
|
|
311
|
+
const reader = request.body.getReader();
|
|
312
|
+
const decoder = new TextDecoder();
|
|
313
|
+
let bytes = 0;
|
|
314
|
+
let text = "";
|
|
315
|
+
while (true) {
|
|
316
|
+
const item = await reader.read();
|
|
317
|
+
if (item.done) break;
|
|
318
|
+
bytes += item.value.byteLength;
|
|
319
|
+
if (bytes > maxBytes) {
|
|
320
|
+
await reader.cancel();
|
|
321
|
+
throw new RangeError("request body is too large");
|
|
322
|
+
}
|
|
323
|
+
text += decoder.decode(item.value, { stream: true });
|
|
324
|
+
}
|
|
325
|
+
text += decoder.decode();
|
|
326
|
+
return JSON.parse(text);
|
|
327
|
+
}
|
|
328
|
+
function timeoutSignal(source, timeoutMs2) {
|
|
329
|
+
const controller = new AbortController();
|
|
330
|
+
const abort = () => controller.abort(source.reason);
|
|
331
|
+
if (source.aborted) abort();
|
|
332
|
+
else source.addEventListener("abort", abort, { once: true });
|
|
333
|
+
const timer = setTimeout(() => controller.abort(new Error("provider timeout")), timeoutMs2);
|
|
334
|
+
return {
|
|
335
|
+
signal: controller.signal,
|
|
336
|
+
clear() {
|
|
337
|
+
clearTimeout(timer);
|
|
338
|
+
source.removeEventListener("abort", abort);
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function providerFailure(error) {
|
|
343
|
+
if (error.code === "RATE_LIMITED") return { code: "RATE_LIMITED", status: 429 };
|
|
344
|
+
if (error.code === "TIMEOUT") return { code: "TIMEOUT", status: 504 };
|
|
345
|
+
if (error.code === "MODEL_REFUSAL") return { code: "MODEL_REFUSAL", status: 422 };
|
|
346
|
+
if (error.code === "INVALID_PROVIDER_OUTPUT") return { code: "INVALID_PROVIDER_OUTPUT", status: 502 };
|
|
347
|
+
return { code: "PROVIDER_ERROR", status: 502 };
|
|
348
|
+
}
|
|
349
|
+
function completeBeforeAbort(operation, signal) {
|
|
350
|
+
if (signal.aborted) return Promise.reject(new ModelProviderError("TIMEOUT", "Provider timed out", true));
|
|
351
|
+
return new Promise((resolve, reject) => {
|
|
352
|
+
const aborted = () => reject(new ModelProviderError("TIMEOUT", "Provider timed out", true));
|
|
353
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
354
|
+
operation.then(
|
|
355
|
+
(value) => {
|
|
356
|
+
signal.removeEventListener("abort", aborted);
|
|
357
|
+
resolve(value);
|
|
358
|
+
},
|
|
359
|
+
(error) => {
|
|
360
|
+
signal.removeEventListener("abort", aborted);
|
|
361
|
+
reject(error);
|
|
362
|
+
}
|
|
363
|
+
);
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
function createGridCommandHandler(options) {
|
|
367
|
+
const maxBodyBytes = options.maxBodyBytes ?? 512 * 1024;
|
|
368
|
+
const timeoutMs2 = options.timeoutMs ?? 3e4;
|
|
369
|
+
return async (httpRequest) => {
|
|
370
|
+
if (new URL(httpRequest.url).pathname === "/health") {
|
|
371
|
+
return jsonResponse({ status: "ok", protocol: AI_PROTOCOL }, 200);
|
|
372
|
+
}
|
|
373
|
+
if (new URL(httpRequest.url).pathname !== "/v1/grid-command" || httpRequest.method !== "POST") {
|
|
374
|
+
return jsonResponse({ error: "not found" }, 404);
|
|
375
|
+
}
|
|
376
|
+
const started = performance.now();
|
|
377
|
+
let raw;
|
|
378
|
+
try {
|
|
379
|
+
if (options.authorize && !await options.authorize(httpRequest)) {
|
|
380
|
+
options.log?.({ event: "rejected", requestId: "", code: "BAD_REQUEST", latencyMs: performance.now() - started });
|
|
381
|
+
return jsonResponse(failure({ requestId: "", revision: "" }, "BAD_REQUEST", "Unauthorized", false), 401);
|
|
382
|
+
}
|
|
383
|
+
raw = await readBody(httpRequest, maxBodyBytes);
|
|
384
|
+
} catch (error) {
|
|
385
|
+
const message = error instanceof RangeError ? error.message : "Request body must be valid JSON";
|
|
386
|
+
return jsonResponse(failure(identifiers(raw), "BAD_REQUEST", message, false), error instanceof RangeError ? 413 : 400);
|
|
387
|
+
}
|
|
388
|
+
const validatedRequest = validateGridCommandRequest(raw);
|
|
389
|
+
if (!validatedRequest.ok) {
|
|
390
|
+
options.log?.({ event: "rejected", requestId: identifiers(raw).requestId, code: "BAD_REQUEST", latencyMs: performance.now() - started });
|
|
391
|
+
return jsonResponse(failure(identifiers(raw), "BAD_REQUEST", validatedRequest.issues.map((entry) => `${entry.path}: ${entry.message}`).join("; "), false), 400);
|
|
392
|
+
}
|
|
393
|
+
const request = validatedRequest.value;
|
|
394
|
+
const timeout = timeoutSignal(httpRequest.signal, timeoutMs2);
|
|
395
|
+
try {
|
|
396
|
+
const providerResult = await completeBeforeAbort(options.provider.complete({
|
|
397
|
+
prompt: buildProviderPrompt(request),
|
|
398
|
+
outputSchema: buildProviderOutputSchema(request.gridSchema),
|
|
399
|
+
signal: timeout.signal
|
|
400
|
+
}), timeout.signal);
|
|
401
|
+
const output = validateProviderGridOutput(request, providerResult.output);
|
|
402
|
+
if (!output.ok) {
|
|
403
|
+
const response2 = failure(request, "INVALID_PROVIDER_OUTPUT", output.issues.map((entry) => `${entry.path}: ${entry.message}`).join("; "), false);
|
|
404
|
+
options.log?.({ event: "failed", requestId: request.requestId, code: response2.error.code, latencyMs: performance.now() - started });
|
|
405
|
+
return jsonResponse(response2, 502);
|
|
406
|
+
}
|
|
407
|
+
const response = {
|
|
408
|
+
protocol: AI_PROTOCOL,
|
|
409
|
+
requestId: request.requestId,
|
|
410
|
+
revision: request.revision,
|
|
411
|
+
status: "ok",
|
|
412
|
+
output: output.value,
|
|
413
|
+
provider: {
|
|
414
|
+
service: options.provider.service,
|
|
415
|
+
model: options.provider.model,
|
|
416
|
+
providerRequestId: providerResult.providerRequestId,
|
|
417
|
+
latencyMs: performance.now() - started
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
options.log?.({ event: "completed", requestId: request.requestId, latencyMs: response.provider.latencyMs });
|
|
421
|
+
return jsonResponse(response, 200);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
const providerError = error instanceof ModelProviderError ? error : timeout.signal.aborted ? new ModelProviderError("TIMEOUT", "Provider timed out", true) : new ModelProviderError("PROVIDER_ERROR", "Provider failed", true, void 0, error);
|
|
424
|
+
const mapped = providerFailure(providerError);
|
|
425
|
+
const response = failure(request, mapped.code, providerError.message, providerError.retryable);
|
|
426
|
+
options.log?.({ event: "failed", requestId: request.requestId, code: response.error.code, latencyMs: performance.now() - started });
|
|
427
|
+
return jsonResponse(response, mapped.status);
|
|
428
|
+
} finally {
|
|
429
|
+
timeout.clear();
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// packages/ai-gateway/src/nodeServer.ts
|
|
435
|
+
import { createServer } from "node:http";
|
|
436
|
+
async function nodeBody(request, maxBytes) {
|
|
437
|
+
if (request.method === "GET" || request.method === "HEAD") return void 0;
|
|
438
|
+
const chunks = [];
|
|
439
|
+
let size = 0;
|
|
440
|
+
for await (const chunk of request) {
|
|
441
|
+
const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
|
|
442
|
+
size += bytes.byteLength;
|
|
443
|
+
if (size > maxBytes) throw new RangeError("request body is too large");
|
|
444
|
+
chunks.push(bytes);
|
|
445
|
+
}
|
|
446
|
+
const body = new Uint8Array(size);
|
|
447
|
+
let offset = 0;
|
|
448
|
+
for (const chunk of chunks) {
|
|
449
|
+
body.set(chunk, offset);
|
|
450
|
+
offset += chunk.byteLength;
|
|
451
|
+
}
|
|
452
|
+
return body;
|
|
453
|
+
}
|
|
454
|
+
async function send(response, target) {
|
|
455
|
+
target.statusCode = response.status;
|
|
456
|
+
response.headers.forEach((value, key) => target.setHeader(key, value));
|
|
457
|
+
target.end(new Uint8Array(await response.arrayBuffer()));
|
|
458
|
+
}
|
|
459
|
+
function createNodeGatewayServer(options) {
|
|
460
|
+
return createServer(async (incoming, outgoing) => {
|
|
461
|
+
try {
|
|
462
|
+
const host2 = incoming.headers.host ?? "127.0.0.1";
|
|
463
|
+
const url = new URL(incoming.url ?? "/", `http://${host2}`);
|
|
464
|
+
const headers = new Headers();
|
|
465
|
+
for (const [key, value] of Object.entries(incoming.headers)) {
|
|
466
|
+
if (Array.isArray(value)) value.forEach((entry) => headers.append(key, entry));
|
|
467
|
+
else if (value !== void 0) headers.set(key, value);
|
|
468
|
+
}
|
|
469
|
+
const body = await nodeBody(incoming, options.maxBodyBytes ?? 512 * 1024);
|
|
470
|
+
const requestInit = { method: incoming.method ?? "GET", headers };
|
|
471
|
+
if (body) requestInit.body = new TextDecoder().decode(body);
|
|
472
|
+
const request = new Request(url, requestInit);
|
|
473
|
+
await send(await options.handler(request), outgoing);
|
|
474
|
+
} catch (error) {
|
|
475
|
+
outgoing.statusCode = error instanceof RangeError ? 413 : 500;
|
|
476
|
+
outgoing.setHeader("content-type", "application/json; charset=utf-8");
|
|
477
|
+
outgoing.end(JSON.stringify({ error: error instanceof RangeError ? error.message : "internal gateway error" }));
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
async function listenNodeGateway(options) {
|
|
482
|
+
const server = createNodeGatewayServer(options);
|
|
483
|
+
await new Promise((resolve, reject) => {
|
|
484
|
+
server.once("error", reject);
|
|
485
|
+
server.listen(options.port ?? 8787, options.host ?? "127.0.0.1", () => {
|
|
486
|
+
server.off("error", reject);
|
|
487
|
+
resolve();
|
|
488
|
+
});
|
|
489
|
+
});
|
|
490
|
+
return server;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// packages/ai-gateway/src/openAiChatCompletionsProvider.ts
|
|
494
|
+
function isRecord3(value) {
|
|
495
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
496
|
+
}
|
|
497
|
+
function errorMessage(value) {
|
|
498
|
+
if (!isRecord3(value)) return void 0;
|
|
499
|
+
if (typeof value.message === "string") return value.message;
|
|
500
|
+
return isRecord3(value.error) && typeof value.error.message === "string" ? value.error.message : void 0;
|
|
501
|
+
}
|
|
502
|
+
function mapHttpError(status, message) {
|
|
503
|
+
if (status === 429) return new ModelProviderError("RATE_LIMITED", message, true, status);
|
|
504
|
+
if (status === 408 || status === 504) return new ModelProviderError("TIMEOUT", message, true, status);
|
|
505
|
+
return new ModelProviderError("PROVIDER_ERROR", message, status >= 500, status);
|
|
506
|
+
}
|
|
507
|
+
function firstChoice(payload) {
|
|
508
|
+
if (!Array.isArray(payload.choices) || payload.choices.length === 0) {
|
|
509
|
+
throw new ModelProviderError("INVALID_PROVIDER_OUTPUT", "Chat completion contained no choices", false);
|
|
510
|
+
}
|
|
511
|
+
const choice = payload.choices[0];
|
|
512
|
+
if (!isRecord3(choice)) {
|
|
513
|
+
throw new ModelProviderError("INVALID_PROVIDER_OUTPUT", "Chat completion choice was not an object", false);
|
|
514
|
+
}
|
|
515
|
+
return choice;
|
|
516
|
+
}
|
|
517
|
+
function choiceText(choice) {
|
|
518
|
+
const message = isRecord3(choice.message) ? choice.message : void 0;
|
|
519
|
+
if (message && typeof message.refusal === "string" && message.refusal.length > 0) {
|
|
520
|
+
throw new ModelProviderError("MODEL_REFUSAL", message.refusal, false);
|
|
521
|
+
}
|
|
522
|
+
if (choice.finish_reason === "length") {
|
|
523
|
+
throw new ModelProviderError("PROVIDER_ERROR", "Chat completion stopped at the token limit", true);
|
|
524
|
+
}
|
|
525
|
+
if (!message || typeof message.content !== "string" || message.content.length === 0) {
|
|
526
|
+
throw new ModelProviderError("INVALID_PROVIDER_OUTPUT", "Chat completion contained no message content", false);
|
|
527
|
+
}
|
|
528
|
+
return message.content;
|
|
529
|
+
}
|
|
530
|
+
function requestBody(options, prompt, schema) {
|
|
531
|
+
return {
|
|
532
|
+
model: options.model,
|
|
533
|
+
messages: [
|
|
534
|
+
{ role: "system", content: prompt.system },
|
|
535
|
+
{ role: "user", content: prompt.user }
|
|
536
|
+
],
|
|
537
|
+
response_format: {
|
|
538
|
+
type: "json_schema",
|
|
539
|
+
json_schema: {
|
|
540
|
+
name: "libregrid_grid_command",
|
|
541
|
+
strict: true,
|
|
542
|
+
schema
|
|
543
|
+
}
|
|
544
|
+
},
|
|
545
|
+
...options.requireParameters ? { provider: { require_parameters: true } } : {}
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
function createOpenAiChatCompletionsProvider(options) {
|
|
549
|
+
if (!options.model.trim()) throw new Error("ai-gateway: chat completions model is required");
|
|
550
|
+
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
551
|
+
if (!fetchImplementation) throw new Error("ai-gateway: fetch is unavailable");
|
|
552
|
+
const endpoint = `${(options.baseUrl ?? "https://api.openai.com/v1").replace(/\/$/, "")}/chat/completions`;
|
|
553
|
+
return {
|
|
554
|
+
service: "openai-chat-completions",
|
|
555
|
+
model: options.model,
|
|
556
|
+
async complete(request) {
|
|
557
|
+
const apiKey2 = typeof options.apiKey === "function" ? await options.apiKey() : options.apiKey;
|
|
558
|
+
if (!apiKey2) throw new ModelProviderError("PROVIDER_ERROR", "Chat completions API key is not configured", false);
|
|
559
|
+
const headers = {
|
|
560
|
+
authorization: `Bearer ${apiKey2}`,
|
|
561
|
+
"content-type": "application/json"
|
|
562
|
+
};
|
|
563
|
+
if (options.referer) headers["http-referer"] = options.referer;
|
|
564
|
+
if (options.title) headers["x-title"] = options.title;
|
|
565
|
+
let response;
|
|
566
|
+
try {
|
|
567
|
+
response = await fetchImplementation(endpoint, {
|
|
568
|
+
method: "POST",
|
|
569
|
+
headers,
|
|
570
|
+
body: JSON.stringify(requestBody(options, request.prompt, request.outputSchema)),
|
|
571
|
+
signal: request.signal
|
|
572
|
+
});
|
|
573
|
+
} catch (cause) {
|
|
574
|
+
if (request.signal.aborted) {
|
|
575
|
+
throw new ModelProviderError("TIMEOUT", "Chat completions request was aborted", true, void 0, cause);
|
|
576
|
+
}
|
|
577
|
+
throw new ModelProviderError("PROVIDER_ERROR", "Chat completions request failed", true, void 0, cause);
|
|
578
|
+
}
|
|
579
|
+
let payload;
|
|
580
|
+
try {
|
|
581
|
+
payload = await response.json();
|
|
582
|
+
} catch (cause) {
|
|
583
|
+
throw new ModelProviderError(
|
|
584
|
+
"PROVIDER_ERROR",
|
|
585
|
+
`Chat completions returned non-JSON data (HTTP ${response.status})`,
|
|
586
|
+
response.status >= 500,
|
|
587
|
+
response.status,
|
|
588
|
+
cause
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
if (!response.ok) {
|
|
592
|
+
throw mapHttpError(response.status, errorMessage(payload) ?? `Chat completions returned HTTP ${response.status}`);
|
|
593
|
+
}
|
|
594
|
+
if (!isRecord3(payload)) {
|
|
595
|
+
throw new ModelProviderError("INVALID_PROVIDER_OUTPUT", "Chat completions response was not an object", false);
|
|
596
|
+
}
|
|
597
|
+
if (isRecord3(payload.error)) {
|
|
598
|
+
const status = typeof payload.error.code === "number" ? payload.error.code : 502;
|
|
599
|
+
throw mapHttpError(status, errorMessage(payload) ?? "Chat completions returned an error envelope");
|
|
600
|
+
}
|
|
601
|
+
const text = choiceText(firstChoice(payload));
|
|
602
|
+
let output;
|
|
603
|
+
try {
|
|
604
|
+
output = JSON.parse(text);
|
|
605
|
+
} catch (cause) {
|
|
606
|
+
throw new ModelProviderError("INVALID_PROVIDER_OUTPUT", "Chat completions output was not valid JSON", false, void 0, cause);
|
|
607
|
+
}
|
|
608
|
+
return { output, providerRequestId: typeof payload.id === "string" ? payload.id : null };
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// packages/ai-gateway/src/openAiResponsesProvider.ts
|
|
614
|
+
function isRecord4(value) {
|
|
615
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
616
|
+
}
|
|
617
|
+
function errorMessage2(value) {
|
|
618
|
+
if (!isRecord4(value)) return void 0;
|
|
619
|
+
if (typeof value.message === "string") return value.message;
|
|
620
|
+
return isRecord4(value.error) && typeof value.error.message === "string" ? value.error.message : void 0;
|
|
621
|
+
}
|
|
622
|
+
function outputText(value) {
|
|
623
|
+
if (typeof value.output_text === "string") return value.output_text;
|
|
624
|
+
if (!Array.isArray(value.output)) return void 0;
|
|
625
|
+
const parts = [];
|
|
626
|
+
for (const item of value.output) {
|
|
627
|
+
if (!isRecord4(item) || !Array.isArray(item.content)) continue;
|
|
628
|
+
for (const content of item.content) {
|
|
629
|
+
if (!isRecord4(content)) continue;
|
|
630
|
+
if (content.type === "refusal" && typeof content.refusal === "string") {
|
|
631
|
+
throw new ModelProviderError("MODEL_REFUSAL", content.refusal, false);
|
|
632
|
+
}
|
|
633
|
+
if (content.type === "output_text" && typeof content.text === "string") parts.push(content.text);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
return parts.length > 0 ? parts.join("") : void 0;
|
|
637
|
+
}
|
|
638
|
+
function mapHttpError2(status, message) {
|
|
639
|
+
if (status === 429) return new ModelProviderError("RATE_LIMITED", message, true, status);
|
|
640
|
+
if (status === 408 || status === 504) return new ModelProviderError("TIMEOUT", message, true, status);
|
|
641
|
+
return new ModelProviderError("PROVIDER_ERROR", message, status >= 500, status);
|
|
642
|
+
}
|
|
643
|
+
function requestBody2(model2, prompt, schema) {
|
|
644
|
+
return {
|
|
645
|
+
model: model2,
|
|
646
|
+
store: false,
|
|
647
|
+
input: [
|
|
648
|
+
{ role: "system", content: [{ type: "input_text", text: prompt.system }] },
|
|
649
|
+
{ role: "user", content: [{ type: "input_text", text: prompt.user }] }
|
|
650
|
+
],
|
|
651
|
+
text: {
|
|
652
|
+
format: {
|
|
653
|
+
type: "json_schema",
|
|
654
|
+
name: "libregrid_grid_command",
|
|
655
|
+
strict: true,
|
|
656
|
+
schema
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
function createOpenAiResponsesProvider(options) {
|
|
662
|
+
if (!options.model.trim()) throw new Error("ai-gateway: OpenAI model is required");
|
|
663
|
+
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
664
|
+
if (!fetchImplementation) throw new Error("ai-gateway: fetch is unavailable");
|
|
665
|
+
const endpoint = `${(options.baseUrl ?? "https://api.openai.com/v1").replace(/\/$/, "")}/responses`;
|
|
666
|
+
return {
|
|
667
|
+
service: "openai-responses",
|
|
668
|
+
model: options.model,
|
|
669
|
+
async complete(request) {
|
|
670
|
+
const apiKey2 = typeof options.apiKey === "function" ? await options.apiKey() : options.apiKey;
|
|
671
|
+
if (!apiKey2) throw new ModelProviderError("PROVIDER_ERROR", "OpenAI API key is not configured", false);
|
|
672
|
+
const headers = {
|
|
673
|
+
authorization: `Bearer ${apiKey2}`,
|
|
674
|
+
"content-type": "application/json"
|
|
675
|
+
};
|
|
676
|
+
if (options.organization) headers["openai-organization"] = options.organization;
|
|
677
|
+
if (options.project) headers["openai-project"] = options.project;
|
|
678
|
+
let response;
|
|
679
|
+
try {
|
|
680
|
+
response = await fetchImplementation(endpoint, {
|
|
681
|
+
method: "POST",
|
|
682
|
+
headers,
|
|
683
|
+
body: JSON.stringify(requestBody2(options.model, request.prompt, request.outputSchema)),
|
|
684
|
+
signal: request.signal
|
|
685
|
+
});
|
|
686
|
+
} catch (cause) {
|
|
687
|
+
if (request.signal.aborted) throw new ModelProviderError("TIMEOUT", "OpenAI request was aborted", true, void 0, cause);
|
|
688
|
+
throw new ModelProviderError("PROVIDER_ERROR", "OpenAI request failed", true, void 0, cause);
|
|
689
|
+
}
|
|
690
|
+
let payload;
|
|
691
|
+
try {
|
|
692
|
+
payload = await response.json();
|
|
693
|
+
} catch (cause) {
|
|
694
|
+
throw new ModelProviderError("PROVIDER_ERROR", `OpenAI returned non-JSON data (HTTP ${response.status})`, response.status >= 500, response.status, cause);
|
|
695
|
+
}
|
|
696
|
+
if (!response.ok) throw mapHttpError2(response.status, errorMessage2(payload) ?? `OpenAI returned HTTP ${response.status}`);
|
|
697
|
+
if (!isRecord4(payload)) throw new ModelProviderError("INVALID_PROVIDER_OUTPUT", "OpenAI response was not an object", false);
|
|
698
|
+
if (payload.status === "incomplete") {
|
|
699
|
+
throw new ModelProviderError("PROVIDER_ERROR", errorMessage2(payload.incomplete_details) ?? "OpenAI response was incomplete", true);
|
|
700
|
+
}
|
|
701
|
+
const text = outputText(payload);
|
|
702
|
+
if (!text) throw new ModelProviderError("INVALID_PROVIDER_OUTPUT", "OpenAI response did not contain output text", false);
|
|
703
|
+
let output;
|
|
704
|
+
try {
|
|
705
|
+
output = JSON.parse(text);
|
|
706
|
+
} catch (cause) {
|
|
707
|
+
throw new ModelProviderError("INVALID_PROVIDER_OUTPUT", "OpenAI output was not valid JSON", false, void 0, cause);
|
|
708
|
+
}
|
|
709
|
+
return { output, providerRequestId: typeof payload.id === "string" ? payload.id : null };
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// packages/ai-gateway/src/serverConfig.ts
|
|
715
|
+
var DEFAULT_GATEWAY_TIMEOUT_MS = 3e4;
|
|
716
|
+
function parseGatewayTimeoutMs(value) {
|
|
717
|
+
if (value === void 0) return DEFAULT_GATEWAY_TIMEOUT_MS;
|
|
718
|
+
const timeoutMs2 = Number(value);
|
|
719
|
+
if (!Number.isInteger(timeoutMs2) || timeoutMs2 <= 0) {
|
|
720
|
+
throw new Error("GATEWAY_TIMEOUT_MS must be a positive integer");
|
|
721
|
+
}
|
|
722
|
+
return timeoutMs2;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// packages/ai-gateway/src/turnstile.ts
|
|
726
|
+
var SITEVERIFY = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
|
727
|
+
function createTurnstileAuthorizer(options) {
|
|
728
|
+
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
729
|
+
if (!fetchImplementation) throw new Error("ai-gateway: fetch is unavailable");
|
|
730
|
+
if (!options.secretKey) throw new Error("ai-gateway: Turnstile secret key is required");
|
|
731
|
+
if (!options.expectedAction) throw new Error("ai-gateway: Turnstile action is required");
|
|
732
|
+
if (options.expectedHostnames.length === 0) {
|
|
733
|
+
throw new Error("ai-gateway: at least one Turnstile hostname is required");
|
|
734
|
+
}
|
|
735
|
+
const expectedHostnames = new Set(options.expectedHostnames);
|
|
736
|
+
const header = options.header ?? "x-turnstile-token";
|
|
737
|
+
return async (request) => {
|
|
738
|
+
const token = request.headers.get(header);
|
|
739
|
+
if (!token || token.length > 2048) return false;
|
|
740
|
+
const body = new URLSearchParams({ secret: options.secretKey, response: token });
|
|
741
|
+
const remoteIp = request.headers.get("cf-connecting-ip") ?? request.headers.get("x-forwarded-for");
|
|
742
|
+
if (remoteIp) body.set("remoteip", remoteIp.split(",")[0].trim());
|
|
743
|
+
let response;
|
|
744
|
+
try {
|
|
745
|
+
response = await fetchImplementation(SITEVERIFY, {
|
|
746
|
+
method: "POST",
|
|
747
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
748
|
+
body: body.toString(),
|
|
749
|
+
signal: AbortSignal.timeout(1e4)
|
|
750
|
+
});
|
|
751
|
+
} catch {
|
|
752
|
+
return false;
|
|
753
|
+
}
|
|
754
|
+
if (!response.ok) return false;
|
|
755
|
+
let payload;
|
|
756
|
+
try {
|
|
757
|
+
payload = await response.json();
|
|
758
|
+
} catch {
|
|
759
|
+
return false;
|
|
760
|
+
}
|
|
761
|
+
if (!payload || typeof payload !== "object") return false;
|
|
762
|
+
const verdict = payload;
|
|
763
|
+
return verdict.success === true && verdict.action === options.expectedAction && typeof verdict.hostname === "string" && expectedHostnames.has(verdict.hostname);
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// packages/ai-gateway/src/server.ts
|
|
768
|
+
var apiKey = process.env.OPENAI_API_KEY;
|
|
769
|
+
if (!apiKey) throw new Error("OPENAI_API_KEY is required");
|
|
770
|
+
var kind = process.env.AI_PROVIDER ?? "openai-responses";
|
|
771
|
+
if (kind !== "openai-responses" && kind !== "openai-chat") {
|
|
772
|
+
throw new Error('AI_PROVIDER must be "openai-responses" or "openai-chat"');
|
|
773
|
+
}
|
|
774
|
+
var model = process.env.OPENAI_MODEL ?? (kind === "openai-chat" ? "openrouter/free" : "gpt-5.6");
|
|
775
|
+
var port = Number(process.env.PORT ?? 8787);
|
|
776
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("PORT must be a valid TCP port");
|
|
777
|
+
var timeoutMs = parseGatewayTimeoutMs(process.env.GATEWAY_TIMEOUT_MS);
|
|
778
|
+
var provider = kind === "openai-chat" ? createOpenAiChatCompletionsProvider({
|
|
779
|
+
apiKey,
|
|
780
|
+
model,
|
|
781
|
+
...process.env.OPENAI_BASE_URL ? { baseUrl: process.env.OPENAI_BASE_URL } : {},
|
|
782
|
+
requireParameters: process.env.OPENROUTER_REQUIRE_PARAMETERS !== "false",
|
|
783
|
+
...process.env.OPENROUTER_REFERER ? { referer: process.env.OPENROUTER_REFERER } : {},
|
|
784
|
+
...process.env.OPENROUTER_TITLE ? { title: process.env.OPENROUTER_TITLE } : {}
|
|
785
|
+
}) : createOpenAiResponsesProvider({
|
|
786
|
+
apiKey,
|
|
787
|
+
model,
|
|
788
|
+
...process.env.OPENAI_BASE_URL ? { baseUrl: process.env.OPENAI_BASE_URL } : {},
|
|
789
|
+
...process.env.OPENAI_ORGANIZATION ? { organization: process.env.OPENAI_ORGANIZATION } : {},
|
|
790
|
+
...process.env.OPENAI_PROJECT ? { project: process.env.OPENAI_PROJECT } : {}
|
|
791
|
+
});
|
|
792
|
+
var turnstileSecret = process.env.TURNSTILE_SECRET_KEY;
|
|
793
|
+
var turnstileHostnames = (process.env.TURNSTILE_HOSTNAMES ?? "").split(",").map((hostname) => hostname.trim()).filter((hostname) => hostname.length > 0);
|
|
794
|
+
if (turnstileSecret && turnstileHostnames.length === 0) {
|
|
795
|
+
throw new Error("TURNSTILE_HOSTNAMES must list at least one hostname when TURNSTILE_SECRET_KEY is set");
|
|
796
|
+
}
|
|
797
|
+
var handler = createGridCommandHandler({
|
|
798
|
+
provider,
|
|
799
|
+
timeoutMs,
|
|
800
|
+
...turnstileSecret ? {
|
|
801
|
+
authorize: createTurnstileAuthorizer({
|
|
802
|
+
secretKey: turnstileSecret,
|
|
803
|
+
expectedAction: "grid_command",
|
|
804
|
+
expectedHostnames: turnstileHostnames
|
|
805
|
+
})
|
|
806
|
+
} : {},
|
|
807
|
+
log: (event) => process.stdout.write(`${JSON.stringify(event)}
|
|
808
|
+
`)
|
|
809
|
+
});
|
|
810
|
+
var host = process.env.HOST ?? "127.0.0.1";
|
|
811
|
+
await listenNodeGateway({ handler, host, port });
|
|
812
|
+
process.stdout.write(
|
|
813
|
+
`LibreGrid AI gateway listening on ${host}:${port} using ${provider.service} (${provider.model}); provider timeout ${timeoutMs} ms; turnstile ${turnstileSecret ? "enabled" : "disabled"}
|
|
814
|
+
`
|
|
815
|
+
);
|