@jxsuite/server 4.2.1 → 4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jxsuite/server",
3
- "version": "4.2.1",
3
+ "version": "4.3.0",
4
4
  "description": "Jx development server with live reload, server-side proxy, and studio integration",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -22,6 +22,7 @@
22
22
  "./packages": "./src/packages.ts",
23
23
  "./project-server": "./src/project-server.ts",
24
24
  "./oauth-loopback": "./src/oauth-loopback.ts",
25
+ "./net-guard": "./src/net-guard.ts",
25
26
  "./live-preview": "./src/live-preview.ts",
26
27
  "./site-preview": "./src/site-preview.ts",
27
28
  "./refactor": "./src/refactor/index.ts",
@@ -40,23 +41,24 @@
40
41
  "upgrade": "bun update --latest && bun install"
41
42
  },
42
43
  "dependencies": {
44
+ "@jxsuite/ai": "^0.38.0",
43
45
  "@jxsuite/catalog": "^0.1.0",
44
- "@jxsuite/collab": "^0.9.0",
45
- "@jxsuite/compiler": "^4.0.1",
46
- "@jxsuite/create": "^1.3.11",
47
- "@jxsuite/import": "^0.40.3",
48
- "@jxsuite/protocol": "^2.3.0",
49
- "@jxsuite/runtime": "^4.0.1",
50
- "@jxsuite/schema": "^2.2.0",
51
- "@jxsuite/site": "^2.0.1",
52
- "@jxsuite/starters": "^1.8.1",
46
+ "@jxsuite/collab": "^0.10.0",
47
+ "@jxsuite/compiler": "^4.0.2",
48
+ "@jxsuite/create": "^1.3.12",
49
+ "@jxsuite/import": "^0.40.4",
50
+ "@jxsuite/protocol": "^2.4.0",
51
+ "@jxsuite/runtime": "^4.0.2",
52
+ "@jxsuite/schema": "^2.3.0",
53
+ "@jxsuite/site": "^2.0.2",
54
+ "@jxsuite/starters": "^1.8.2",
53
55
  "chokidar": "^5.0.0",
54
- "kysely": "^0.29.5",
55
- "zod": "^4.6.4"
56
+ "kysely": "^0.29.6",
57
+ "zod": "^4.6.5"
56
58
  },
57
59
  "devDependencies": {
58
- "@jxsuite/auth": "^0.6.0",
59
- "@jxsuite/connector": "^0.6.0",
60
- "@jxsuite/parser": "^1.8.1"
60
+ "@jxsuite/auth": "^0.6.1",
61
+ "@jxsuite/connector": "^0.6.1",
62
+ "@jxsuite/parser": "^1.8.2"
61
63
  }
62
64
  }
package/src/ai-api.ts CHANGED
@@ -5,6 +5,10 @@
5
5
  * The server acts as a thin proxy: validates the request shape, forwards to OpenAI,
6
6
  * normalizes the SSE stream into StreamEvent-compatible format, and pipes back.
7
7
  *
8
+ * The wire half of that (reading the body, the upstream request, the stream normalizer, the SSE
9
+ * framing, the problem responses) is `@jxsuite/ai/gateway`, which every backend serving these
10
+ * routes can share. What stays here is this server's POLICY, which no other host shares:
11
+ *
8
12
  * API key flow:
9
13
  * 1. Request header X-Api-Key or Authorization: Bearer <key>
10
14
  * 2. Fallback: OPENAI_API_KEY env var — attached ONLY to the env/default base URL, never to a
@@ -17,38 +21,27 @@
17
21
  * 3. Default: https://api.openai.com/v1
18
22
  * A base URL resolving to a cloud metadata / link-local host is refused (SSRF defense).
19
23
  *
24
+ * The model catalogue for /models is this server's too: its defaults, and how it reads the
25
+ * upstream's own listing.
26
+ *
20
27
  * @license MIT
21
28
  */
22
- import { problem, problemTypeForStatus } from "./problem.ts";
29
+ import {
30
+ createChatHandler,
31
+ extractUpstreamErrorMessage,
32
+ modelsResponse,
33
+ problemResponse,
34
+ } from "@jxsuite/ai/gateway";
35
+ import type { GatewayRefusal, Upstream } from "@jxsuite/ai/gateway";
23
36
  import { problemDetails } from "@jxsuite/protocol";
37
+ import { problemTypeForStatus } from "./problem.ts";
24
38
 
25
39
  // ─── Configuration ───────────────────────────────────────────────────────────
26
40
 
27
41
  const DEFAULT_BASE_URL = "https://api.openai.com/v1";
28
42
 
29
- /** A tool-call fragment inside an OpenAI streaming `delta`. */
30
- interface ToolCallDelta {
31
- index: number;
32
- id?: string;
33
- type?: string;
34
- function?: { name?: string; arguments?: string };
35
- }
36
-
37
- /** A single OpenAI chat-completions streaming chunk (the JSON after `data: `). */
38
- interface OpenAIStreamChunk {
39
- choices?: {
40
- index?: number;
41
- delta?: {
42
- content?: string;
43
- /** Thinking models' chain-of-thought: DeepSeek/Volcengine spell it this way… */
44
- reasoning_content?: string;
45
- /** …and OpenRouter this way. Both carry the same thing. */
46
- reasoning?: string;
47
- tool_calls?: ToolCallDelta[];
48
- };
49
- finish_reason?: string | null;
50
- }[];
51
- }
43
+ /** The model a chat request that names none is forwarded with. */
44
+ const DEFAULT_MODEL = "gpt-4o";
52
45
 
53
46
  /** A model entry from the upstream `/models` listing. */
54
47
  interface ModelEntry {
@@ -144,318 +137,45 @@ function getConfig(req: Request): AiConfig {
144
137
 
145
138
  // ─── Helpers ─────────────────────────────────────────────────────────────────
146
139
 
147
- /** Write an SSE event to the response stream. */
148
- function writeSSE(controller: ReadableStreamDefaultController, event: unknown): void {
149
- const data = JSON.stringify(event);
150
- controller.enqueue(new TextEncoder().encode(`data: ${data}\n\n`));
151
- }
152
-
153
140
  /**
154
- * Write a failure response for the non-streaming endpoints.
141
+ * A refusal at a status this file chose.
155
142
  *
156
- * The status is chosen by the caller here rather than by the type, because this file's callers
157
- * forward an upstream provider's status — which is information, and collapsing it to the type's own
158
- * would throw it away.
143
+ * The status picks the type rather than the other way round, because this file's refusals were
144
+ * always written as statuses (`reject.status`), and the response carries the TYPE's status, exactly
145
+ * as `problem()` answers.
159
146
  */
160
- function jsonError(status: number, message: string): Response {
161
- return problem(problemTypeForStatus(status), message);
147
+ function refuse(status: number, message: string): GatewayRefusal {
148
+ const problem = problemDetails(problemTypeForStatus(status), message);
149
+ return { problem, status: problem.status };
162
150
  }
163
151
 
164
- // ─── /__studio/ai/chat — SSE streaming proxy ───────────────────────────────
165
-
166
- /** Handle POST /__studio/ai/chat — proxy chat completions to OpenAI via SSE. */
167
- export async function handleChat(req: Request): Promise<Response> {
168
- const { apiKey, baseUrl, missingKey, reject } = getConfig(req);
152
+ /**
153
+ * This server's upstream for a request, or its refusal: the key-provenance and SSRF rules above,
154
+ * applied per request (the environment is read each time, so a key set later is honoured).
155
+ */
156
+ function resolveUpstream(req: Request): Upstream | GatewayRefusal {
157
+ const { apiKey, baseUrl, reject } = getConfig(req);
169
158
  if (reject) {
170
- return jsonError(reject.status, reject.message);
159
+ return refuse(reject.status, reject.message);
171
160
  }
172
- if (missingKey) {
173
- return jsonError(
161
+ if (!apiKey) {
162
+ return refuse(
174
163
  401,
175
164
  "No API key configured. Set OPENAI_API_KEY env var or send X-Api-Key header.",
176
165
  );
177
166
  }
167
+ return { apiKey, baseUrl, defaultModel: DEFAULT_MODEL, family: "openai-compat", managed: false };
168
+ }
178
169
 
179
- // Parse request body
180
- let body: {
181
- messages?: unknown[];
182
- tools?: unknown[];
183
- systemPrompt?: string;
184
- model?: string;
185
- };
186
- try {
187
- body = (await req.json()) as {
188
- messages?: unknown[];
189
- tools?: unknown[];
190
- systemPrompt?: string;
191
- model?: string;
192
- };
193
- } catch {
194
- return jsonError(400, "Invalid JSON body");
195
- }
196
-
197
- const { messages = [], tools = [], systemPrompt = "", model = "gpt-4o" } = body;
198
-
199
- if (!Array.isArray(messages)) {
200
- return jsonError(400, "messages must be an array");
201
- }
202
-
203
- // Build OpenAI request
204
- const openaiBody: {
205
- model: string;
206
- messages: unknown[];
207
- stream: boolean;
208
- stream_options: { include_usage: boolean };
209
- tools?: unknown[];
210
- tool_choice?: string;
211
- parallel_tool_calls?: boolean;
212
- } = {
213
- model,
214
- messages: [{ role: "system", content: systemPrompt }, ...messages],
215
- stream: true,
216
- stream_options: { include_usage: true },
217
- };
218
-
219
- if (tools && tools.length > 0) {
220
- openaiBody.tools = tools;
221
- openaiBody.tool_choice = "auto";
222
- openaiBody.parallel_tool_calls = true;
223
- }
224
-
225
- const upstreamUrl = `${baseUrl}/chat/completions`;
226
-
227
- // Create the SSE stream
228
- const stream = new ReadableStream({
229
- async start(controller) {
230
- let response;
231
- try {
232
- response = await fetch(upstreamUrl, {
233
- method: "POST",
234
- headers: {
235
- "Content-Type": "application/json",
236
- Authorization: `Bearer ${apiKey}`,
237
- },
238
- body: JSON.stringify(openaiBody),
239
- signal: req.signal,
240
- });
241
- } catch (error) {
242
- if ((error as Error).name === "AbortError") {
243
- writeSSE(controller, { type: "done", stopReason: "cancelled" });
244
- } else {
245
- const message = `Network error: ${(error as Error).message}`;
246
- writeSSE(controller, {
247
- message,
248
- /*
249
- * The frame carries a problem rather than being one: the response began with a 200
250
- * long before this failed, so nothing can change the status now. `message` stays for
251
- * the readers that already show it (server.md §4.3).
252
- */
253
- problem: problemDetails("upstreamFailure", message),
254
- type: "error",
255
- });
256
- }
257
- controller.close();
258
- return;
259
- }
260
-
261
- if (!response.ok) {
262
- let errorBody = "";
263
- try {
264
- errorBody = await response.text();
265
- } catch {
266
- /* Ignore */
267
- }
268
- // Parse the upstream JSON error body (OpenAI returns { error: { message: "..." } },
269
- // While some compatible providers return { error: "..." }). Extract a clean message
270
- // Instead of embedding the raw JSON in the error text.
271
- let cleanMessage = errorBody || response.statusText;
272
- try {
273
- const parsed = JSON.parse(errorBody) as { error?: string | { message?: string } };
274
- if (typeof parsed.error === "string") {
275
- cleanMessage = parsed.error;
276
- } else if (parsed.error?.message) {
277
- cleanMessage = parsed.error.message;
278
- }
279
- } catch {
280
- /* Not JSON — use the raw body. */
281
- }
282
- writeSSE(controller, {
283
- code: String(response.status),
284
- message: cleanMessage,
285
- // The upstream's own status is preserved in `code`; the problem names the KIND.
286
- problem: problemDetails(problemTypeForStatus(response.status), cleanMessage),
287
- type: "error",
288
- });
289
- controller.close();
290
- return;
291
- }
292
-
293
- const reader = response.body?.getReader();
294
- if (!reader) {
295
- writeSSE(controller, {
296
- message: "No response body from upstream",
297
- problem: problemDetails("upstreamFailure", "No response body from upstream"),
298
- type: "error",
299
- });
300
- controller.close();
301
- return;
302
- }
303
-
304
- const decoder = new TextDecoder();
305
- let buffer = "";
306
-
307
- const pendingToolCalls = new Map<number, { id: string; name: string; args: string }>();
308
-
309
- try {
310
- while (true) {
311
- const { done, value } = await reader.read();
312
- if (done) {
313
- break;
314
- }
315
-
316
- buffer += decoder.decode(value, { stream: true });
317
- const lines = buffer.split("\n");
318
- buffer = lines.pop() || "";
319
-
320
- for (const line of lines) {
321
- const trimmed = line.trim();
322
- if (!trimmed || !trimmed.startsWith("data: ")) {
323
- continue;
324
- }
325
-
326
- const dataStr = trimmed.slice(6);
327
- if (dataStr === "[DONE]") {
328
- // Emit pending tool call ends
329
- for (const [, tc] of pendingToolCalls) {
330
- writeSSE(controller, { type: "tool_call_end", id: tc.id });
331
- }
332
- pendingToolCalls.clear();
333
- writeSSE(controller, { type: "done", stopReason: "stop" });
334
- controller.close();
335
- return;
336
- }
337
-
338
- let parsed: OpenAIStreamChunk;
339
- try {
340
- parsed = JSON.parse(dataStr) as OpenAIStreamChunk;
341
- } catch {
342
- continue;
343
- }
344
-
345
- const choice = parsed.choices?.[0];
346
- if (!choice) {
347
- continue;
348
- }
349
-
350
- const { delta } = choice;
351
- if (!delta) {
352
- continue;
353
- }
354
-
355
- // Text content
356
- if (delta.content) {
357
- writeSSE(controller, { type: "delta", content: delta.content });
358
- }
359
-
360
- /* Chain-of-thought, under either of the two names providers give it. Forwarded rather
361
- than dropped: DeepSeek's thinking mode requires every prior turn's reasoning back on
362
- any request carrying `tools`, so a proxy that swallows these frames makes the NEXT
363
- round a 400 the client cannot repair. */
364
- const reasoning = delta.reasoning_content ?? delta.reasoning;
365
- if (typeof reasoning === "string" && reasoning) {
366
- writeSSE(controller, { type: "reasoning", content: reasoning });
367
- }
368
-
369
- // Tool calls
370
- if (delta.tool_calls) {
371
- for (const tc of delta.tool_calls) {
372
- if (tc.id) {
373
- // First appearance
374
- const entry = {
375
- id: tc.id,
376
- name: tc.function?.name || "",
377
- args: tc.function?.arguments || "",
378
- };
379
- pendingToolCalls.set(tc.index, entry);
380
-
381
- writeSSE(controller, { type: "tool_call_start", id: tc.id, name: entry.name });
382
-
383
- if (entry.args) {
384
- writeSSE(controller, { type: "tool_call_delta", id: tc.id, args: entry.args });
385
- }
386
- } else if (tc.function?.arguments) {
387
- // Subsequent fragment
388
- const existing = pendingToolCalls.get(tc.index);
389
- if (existing) {
390
- existing.args += tc.function.arguments;
391
- writeSSE(controller, {
392
- type: "tool_call_delta",
393
- id: existing.id,
394
- args: tc.function.arguments,
395
- });
396
- }
397
- }
398
- }
399
- }
400
-
401
- // Finish reason
402
- if (choice.finish_reason === "tool_calls") {
403
- for (const [, tc] of pendingToolCalls) {
404
- writeSSE(controller, { type: "tool_call_end", id: tc.id });
405
- }
406
- pendingToolCalls.clear();
407
- writeSSE(controller, { type: "done", stopReason: "tool_calls" });
408
- controller.close();
409
- return;
410
- }
411
-
412
- if (choice.finish_reason === "stop" || choice.finish_reason === "length") {
413
- for (const [, tc] of pendingToolCalls) {
414
- writeSSE(controller, { type: "tool_call_end", id: tc.id });
415
- }
416
- pendingToolCalls.clear();
417
- writeSSE(controller, {
418
- type: "done",
419
- stopReason: choice.finish_reason === "length" ? "length" : "stop",
420
- });
421
- controller.close();
422
- return;
423
- }
424
- }
425
- }
170
+ // ─── /__studio/ai/chat — SSE streaming proxy ───────────────────────────────
426
171
 
427
- // Stream ended without explicit finish_reason
428
- for (const [, tc] of pendingToolCalls) {
429
- writeSSE(controller, { type: "tool_call_end", id: tc.id });
430
- }
431
- pendingToolCalls.clear();
432
- writeSSE(controller, { type: "done", stopReason: "stop" });
433
- controller.close();
434
- } catch (error) {
435
- void reader.cancel();
436
- if ((error as Error).name === "AbortError") {
437
- writeSSE(controller, { type: "done", stopReason: "cancelled" });
438
- controller.close();
439
- return;
440
- }
441
- const message = `Stream error: ${(error as Error).message}`;
442
- writeSSE(controller, {
443
- message,
444
- problem: problemDetails("upstreamFailure", message),
445
- type: "error",
446
- });
447
- controller.close();
448
- }
449
- },
450
- });
172
+ const chatHandler = createChatHandler<{ readonly signal: AbortSignal }>({
173
+ resolveUpstream: (request) => resolveUpstream(request),
174
+ });
451
175
 
452
- return new Response(stream, {
453
- headers: {
454
- "Content-Type": "text/event-stream",
455
- "Cache-Control": "no-cache",
456
- Connection: "keep-alive",
457
- },
458
- });
176
+ /** Handle POST /__studio/ai/chat — proxy chat completions to OpenAI via SSE. */
177
+ export async function handleChat(req: Request): Promise<Response> {
178
+ return chatHandler(req, { signal: req.signal });
459
179
  }
460
180
 
461
181
  // ─── /__studio/ai/models — model listing ────────────────────────────────────
@@ -471,7 +191,7 @@ export async function handleChat(req: Request): Promise<Response> {
471
191
  export async function handleModels(req: Request): Promise<Response> {
472
192
  const { apiKey, baseUrl, missingKey, reject } = getConfig(req);
473
193
  if (reject) {
474
- return jsonError(reject.status, reject.message);
194
+ return problemResponse(refuse(reject.status, reject.message));
475
195
  }
476
196
 
477
197
  // No key available → return hardcoded defaults so the UI can at least render.
@@ -482,12 +202,7 @@ export async function handleModels(req: Request): Promise<Response> {
482
202
  { id: "gpt-4.1-mini", name: "GPT-4.1 Mini", contextWindow: 1_000_000 },
483
203
  { id: "gpt-4o-mini", name: "GPT-4o Mini", contextWindow: 128_000 },
484
204
  ];
485
- return Response.json(
486
- { models: defaults, configured: false, managed: false },
487
- {
488
- headers: { "Content-Type": "application/json" },
489
- },
490
- );
205
+ return modelsResponse({ models: defaults, configured: false, managed: false });
491
206
  }
492
207
 
493
208
  // Key is available — proxy to the upstream /models endpoint.
@@ -499,13 +214,21 @@ export async function handleModels(req: Request): Promise<Response> {
499
214
 
500
215
  if (!upstreamResp.ok) {
501
216
  // Upstream failed — return defaults with configured flag so user can still try.
217
+ let errorBody = "";
218
+ try {
219
+ errorBody = await upstreamResp.text();
220
+ } catch {
221
+ /* Ignore */
222
+ }
223
+ const upstreamMessage = extractUpstreamErrorMessage(errorBody, upstreamResp.statusText);
502
224
  const defaults = [{ id: "gpt-4o", name: "GPT-4o", contextWindow: 128_000 }];
503
- return Response.json(
504
- { models: defaults, configured: true, managed: false, upstreamError: upstreamResp.status },
505
- {
506
- headers: { "Content-Type": "application/json" },
507
- },
508
- );
225
+ return modelsResponse({
226
+ models: defaults,
227
+ configured: true,
228
+ managed: false,
229
+ upstreamError: upstreamResp.status,
230
+ upstreamMessage,
231
+ });
509
232
  }
510
233
 
511
234
  const data = (await upstreamResp.json()) as { data?: ModelEntry[] } | ModelEntry[];
@@ -523,21 +246,17 @@ export async function handleModels(req: Request): Promise<Response> {
523
246
  ownedBy: owned_by,
524
247
  }));
525
248
 
526
- return Response.json(
527
- { models, configured: true, managed: false },
528
- {
529
- headers: { "Content-Type": "application/json" },
530
- },
531
- );
532
- } catch {
249
+ return modelsResponse({ models, configured: true, managed: false });
250
+ } catch (error) {
533
251
  // Network error → return defaults.
534
252
  const defaults = [{ id: "gpt-4o", name: "GPT-4o", contextWindow: 128_000 }];
535
- return Response.json(
536
- { models: defaults, configured: true, managed: false, upstreamError: "network" },
537
- {
538
- headers: { "Content-Type": "application/json" },
539
- },
540
- );
253
+ return modelsResponse({
254
+ models: defaults,
255
+ configured: true,
256
+ managed: false,
257
+ upstreamError: "network",
258
+ upstreamMessage: (error as Error).message,
259
+ });
541
260
  }
542
261
  }
543
262
 
package/src/problem.ts CHANGED
@@ -44,9 +44,12 @@ export function problem(
44
44
  * The declared type for a status a caller already computed.
45
45
  *
46
46
  * Two files need this and no more should: `data-api.ts`, whose `ApiError` predates the registry and
47
- * carries only a status, and `ai-api.ts`, which forwards an upstream provider's status because
48
- * collapsing it to the type's own would discard information. Everywhere else the type is named at
49
- * the call site, which is what keeps the registry meaningful — a status is not a failure kind.
47
+ * carries only a status, and `ai-api.ts`, whose key and base-URL refusals are written as statuses.
48
+ * Everywhere else the type is named at the call site, which is what keeps the registry meaningful —
49
+ * a status is not a failure kind. The AI proxy's other use, forwarding an upstream provider's
50
+ * status because collapsing it would discard information, moved with the stream normalizer into
51
+ * `@jxsuite/ai/gateway`, which carries its own copy of this table; `tests/ai-api-gateway.test.ts`
52
+ * holds the two to agreement for every status.
50
53
  *
51
54
  * @param {number} status
52
55
  * @returns {ProblemTypeName}
package/src/studio-api.ts CHANGED
@@ -1206,6 +1206,33 @@ export async function handleStudioApi(
1206
1206
  }
1207
1207
  }
1208
1208
 
1209
+ /* Read a file's raw BYTES.
1210
+ The read side of `/__studio/file/upload`, and a separate route from `/__studio/file` rather
1211
+ than a flag on it, because the two differ in more than encoding: that route answers a JSON
1212
+ envelope `{ content, path }` with `max-age=5`, and both are wrong here. A caller wanting bytes
1213
+ wants a body, and a caller about to overwrite the file must not be handed a five-second-old
1214
+ copy of it — an edit applied to stale bytes is a silently wrong file.
1215
+
1216
+ `Bun.file` streams from disk and infers the media type from the extension, which is what makes
1217
+ this a handful of lines rather than a decoder. */
1218
+ if (path === "/__studio/file/bytes" && req.method === "GET") {
1219
+ const fp = url.searchParams.get("path");
1220
+ if (!fp) {
1221
+ return problem("invalidRequest", "Missing path");
1222
+ }
1223
+ const abs = expandTilde(fp);
1224
+ try {
1225
+ assertAccessible(abs, root, activeProjectRoot);
1226
+ } catch (error) {
1227
+ return new Response(errorMessage(error), { status: 400 });
1228
+ }
1229
+ const file = Bun.file(abs);
1230
+ if (!(await file.exists())) {
1231
+ return problem("notFound", "Not found");
1232
+ }
1233
+ return new Response(file, { headers: { "Cache-Control": "no-store" } });
1234
+ }
1235
+
1209
1236
  // Write file
1210
1237
  if (path === "/__studio/file" && req.method === "PUT") {
1211
1238
  const fp = url.searchParams.get("path");