@langwatch/server 3.1.0-beta.19 → 3.1.0-beta.20

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 (75) hide show
  1. package/langwatch/prisma/migrations/20260425000000_consolidate_gateway_audit_into_audit_log/migration.sql +44 -0
  2. package/langwatch/prisma/migrations/20260426150000_drop_redundant_audit_log_org_index/migration.sql +25 -0
  3. package/langwatch/prisma/schema.prisma +34 -41
  4. package/langwatch/scripts/seed-gateway-dogfood.ts +26 -26
  5. package/langwatch/src/app/api/gateway-platform/[[...route]]/app.ts +8 -4
  6. package/langwatch/src/app/api/middleware/trace-limit.ts +10 -0
  7. package/langwatch/src/components/MainMenu.tsx +4 -15
  8. package/langwatch/src/components/SettingsLayout.tsx +1 -1
  9. package/langwatch/src/components/llmPromptConfigs/__tests__/LLMConfigPopover.test.tsx +45 -0
  10. package/langwatch/src/components/llmPromptConfigs/parameterRegistry.ts +22 -13
  11. package/langwatch/src/components/prompts/PromptEditorDrawer.tsx +5 -3
  12. package/langwatch/src/components/settings/AddCustomModelDialog.tsx +7 -6
  13. package/langwatch/src/evaluations-v3/__tests__/TableDisplay.integration.test.tsx +90 -5
  14. package/langwatch/src/evaluations-v3/__tests__/TableSettingsMenu.integration.test.tsx +26 -26
  15. package/langwatch/src/evaluations-v3/components/DatasetSection/TableCell.tsx +2 -10
  16. package/langwatch/src/evaluations-v3/components/EvaluationsV3Table.tsx +10 -4
  17. package/langwatch/src/evaluations-v3/components/TableSettingsMenu.tsx +6 -6
  18. package/langwatch/src/evaluations-v3/components/TargetSection/EvaluatorChip.tsx +19 -11
  19. package/langwatch/src/evaluations-v3/components/TargetSection/TargetCell.tsx +55 -42
  20. package/langwatch/src/evaluations-v3/components/TargetSection/TargetHeader.tsx +2 -1
  21. package/langwatch/src/evaluations-v3/components/TargetSection/__tests__/EvaluatorChip.test.tsx +57 -0
  22. package/langwatch/src/evaluations-v3/components/TargetSection/__tests__/TargetCell.test.tsx +199 -11
  23. package/langwatch/src/evaluations-v3/components/VirtualizedTableBody.tsx +1 -1
  24. package/langwatch/src/evaluations-v3/constants.ts +9 -0
  25. package/langwatch/src/evaluations-v3/types/__tests__/persistence.test.ts +1 -1
  26. package/langwatch/src/evaluations-v3/types.ts +13 -1
  27. package/langwatch/src/evaluations-v3/utils/__tests__/evaluatorEditorCallbacks.test.ts +32 -0
  28. package/langwatch/src/evaluations-v3/utils/evaluatorEditorCallbacks.ts +36 -5
  29. package/langwatch/src/optimization_studio/components/datasets/DatasetSelection.tsx +1 -6
  30. package/langwatch/src/optimization_studio/components/datasets/__tests__/DatasetSelection.integration.test.tsx +194 -0
  31. package/langwatch/src/optimization_studio/components/drawers/SignaturePromptEditorBridge.tsx +6 -6
  32. package/langwatch/src/optimization_studio/components/drawers/__tests__/SignaturePromptEditorBridge.integration.test.tsx +36 -11
  33. package/langwatch/src/pages/[project]/gateway/budgets/[id].tsx +1 -1
  34. package/langwatch/src/pages/[project]/gateway/virtual-keys/[id].tsx +1 -1
  35. package/langwatch/src/pages/settings/audit-log.tsx +82 -59
  36. package/langwatch/src/routes.tsx +0 -4
  37. package/langwatch/src/server/agents/agent.service.ts +6 -2
  38. package/langwatch/src/server/api/__tests__/rbac-integration.test.ts +53 -0
  39. package/langwatch/src/server/api/__tests__/rbac.auditLog.test.ts +100 -0
  40. package/langwatch/src/server/api/rbac.ts +12 -0
  41. package/langwatch/src/server/api/root.ts +0 -2
  42. package/langwatch/src/server/api/routers/organization.ts +1 -1
  43. package/langwatch/src/server/app-layer/organizations/repositories/organization.prisma.repository.ts +58 -120
  44. package/langwatch/src/server/app-layer/organizations/repositories/organization.repository.ts +8 -11
  45. package/langwatch/src/server/evaluators/evaluator.service.ts +6 -2
  46. package/langwatch/src/server/gateway/__tests__/auditLog.consolidation.integration.test.ts +237 -0
  47. package/langwatch/src/server/gateway/__tests__/cacheRule.service.unit.test.ts +2 -2
  48. package/langwatch/src/server/gateway/__tests__/providerCredential.service.unit.test.ts +6 -6
  49. package/langwatch/src/server/gateway/__tests__/virtualKey.service.unit.test.ts +6 -6
  50. package/langwatch/src/server/gateway/auditLog.repository.ts +46 -8
  51. package/langwatch/src/server/gateway/auditSerializer.ts +2 -2
  52. package/langwatch/src/server/gateway/budget.service.ts +6 -6
  53. package/langwatch/src/server/gateway/cacheRule.service.ts +5 -5
  54. package/langwatch/src/server/gateway/providerCredential.service.ts +5 -5
  55. package/langwatch/src/server/gateway/virtualKey.service.ts +9 -9
  56. package/langwatch/src/server/pat/__tests__/auth-middleware.unit.test.ts +138 -3
  57. package/langwatch/src/server/pat/auth-middleware.ts +68 -13
  58. package/langwatch/src/server/routes/__tests__/otel.unit.test.ts +241 -0
  59. package/langwatch/src/server/routes/otel.ts +281 -45
  60. package/langwatch/src/server/scenarios/adapters/__tests__/http-agent.adapter.test.ts +271 -6
  61. package/langwatch/src/server/scenarios/adapters/http-agent.adapter.ts +43 -35
  62. package/langwatch/src/server/scenarios/execution/http-template-engine.ts +124 -0
  63. package/langwatch/src/server/scenarios/execution/serialized-adapters/__tests__/http-agent.adapter.unit.test.ts +180 -0
  64. package/langwatch/src/server/scenarios/execution/serialized-adapters/http-agent.adapter.ts +26 -30
  65. package/langwatch/src/tasks/__tests__/migrateCustomModels.unit.test.ts +0 -2
  66. package/langwatch/src/tasks/migrateCustomModels.ts +1 -1
  67. package/langwatch/src/utils/__tests__/dbMultiTenancyProtection.unit.test.ts +0 -17
  68. package/langwatch/src/utils/permissionsConfig.ts +6 -0
  69. package/langwatch/src/utils/routes.ts +0 -5
  70. package/package.json +1 -1
  71. package/packages/server/dist/cli.cjs +39 -70
  72. package/langwatch/src/pages/[project]/gateway/audit.tsx +0 -606
  73. package/langwatch/src/server/api/routers/gatewayAudit.ts +0 -109
  74. package/langwatch/src/server/gateway/__tests__/audit.service.unit.test.ts +0 -156
  75. package/langwatch/src/server/gateway/audit.service.ts +0 -104
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { AgentRole, type AgentInput } from "@langwatch/scenario";
6
6
  import { beforeEach, describe, expect, it, vi } from "vitest";
7
+ import { TemplateRenderError } from "../../http-template-engine";
7
8
  import type { HttpAgentData } from "../../types";
8
9
  import { SerializedHttpAgentAdapter } from "../http-agent.adapter";
9
10
 
@@ -364,4 +365,183 @@ describe("SerializedHttpAgentAdapter", () => {
364
365
  });
365
366
  });
366
367
  });
368
+
369
+ describe("URL template interpolation", () => {
370
+ it("renders {{threadId}} placeholder in url", async () => {
371
+ const config: HttpAgentData = {
372
+ ...defaultConfig,
373
+ url: "https://api.example.com/conversations/{{threadId}}/messages",
374
+ };
375
+ const adapter = new SerializedHttpAgentAdapter(config);
376
+
377
+ await adapter.call(defaultInput);
378
+
379
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
380
+ "https://api.example.com/conversations/thread_123/messages",
381
+ expect.any(Object),
382
+ );
383
+ });
384
+
385
+ it("URL-encodes interpolated values by default", async () => {
386
+ const config: HttpAgentData = {
387
+ ...defaultConfig,
388
+ url: "https://api.example.com/search/{{input}}",
389
+ };
390
+ const input: AgentInput = {
391
+ ...defaultInput,
392
+ messages: [{ role: "user", content: "hello world & friends?" }],
393
+ newMessages: [{ role: "user", content: "hello world & friends?" }],
394
+ };
395
+
396
+ const adapter = new SerializedHttpAgentAdapter(config);
397
+ await adapter.call(input);
398
+
399
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
400
+ "https://api.example.com/search/hello%20world%20%26%20friends%3F",
401
+ expect.any(Object),
402
+ );
403
+ });
404
+
405
+ it("does NOT URL-encode the body template (BC preserved)", async () => {
406
+ const config: HttpAgentData = {
407
+ ...defaultConfig,
408
+ bodyTemplate: '{"query": "{{input}}"}',
409
+ };
410
+ const input: AgentInput = {
411
+ ...defaultInput,
412
+ messages: [{ role: "user", content: "hello world & friends" }],
413
+ newMessages: [{ role: "user", content: "hello world & friends" }],
414
+ };
415
+
416
+ const adapter = new SerializedHttpAgentAdapter(config);
417
+ await adapter.call(input);
418
+
419
+ const callArgs = mockSsrfSafeFetch.mock.calls[0]![1];
420
+ const body = JSON.parse(callArgs?.body as string);
421
+ expect(body.query).toBe("hello world & friends");
422
+ });
423
+
424
+ describe("when using `| raw` filter", () => {
425
+ it("skips URL-encoding for raw-filtered values only", async () => {
426
+ const config: HttpAgentData = {
427
+ ...defaultConfig,
428
+ url: "https://api.example.com/{{threadId | raw}}/q/{{input}}",
429
+ };
430
+ const input: AgentInput = {
431
+ ...defaultInput,
432
+ threadId: "path/with/slash",
433
+ messages: [{ role: "user", content: "needs encoding" }],
434
+ newMessages: [{ role: "user", content: "needs encoding" }],
435
+ };
436
+
437
+ const adapter = new SerializedHttpAgentAdapter(config);
438
+ await adapter.call(input);
439
+
440
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
441
+ "https://api.example.com/path/with/slash/q/needs%20encoding",
442
+ expect.any(Object),
443
+ );
444
+ });
445
+ });
446
+
447
+ describe("when url has no placeholders", () => {
448
+ it("passes url through unchanged", async () => {
449
+ const adapter = new SerializedHttpAgentAdapter(defaultConfig);
450
+ await adapter.call(defaultInput);
451
+
452
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
453
+ "https://api.example.com/chat",
454
+ expect.any(Object),
455
+ );
456
+ });
457
+ });
458
+
459
+ describe("when url contains Liquid conditional", () => {
460
+ it("renders if-branch when condition is truthy via scenarioMappings", async () => {
461
+ const config: HttpAgentData = {
462
+ ...defaultConfig,
463
+ url: "https://api.example.com{% if conversationId %}/chat/{{conversationId}}/message{% else %}/chat/start{% endif %}",
464
+ scenarioMappings: {
465
+ conversationId: { type: "value", value: "conv-42" },
466
+ },
467
+ };
468
+ const adapter = new SerializedHttpAgentAdapter(config);
469
+
470
+ await adapter.call(defaultInput);
471
+
472
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
473
+ "https://api.example.com/chat/conv-42/message",
474
+ expect.any(Object),
475
+ );
476
+ });
477
+
478
+ it("renders else-branch when condition is falsy", async () => {
479
+ const config: HttpAgentData = {
480
+ ...defaultConfig,
481
+ url: "https://api.example.com{% if conversationId %}/chat/{{conversationId}}/message{% else %}/chat/start{% endif %}",
482
+ };
483
+ const adapter = new SerializedHttpAgentAdapter(config);
484
+
485
+ await adapter.call(defaultInput);
486
+
487
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
488
+ "https://api.example.com/chat/start",
489
+ expect.any(Object),
490
+ );
491
+ });
492
+ });
493
+
494
+ describe("SSRF regression", () => {
495
+ beforeEach(() => {
496
+ mockSsrfSafeFetch.mockRejectedValue(
497
+ new Error("Access to private IP denied"),
498
+ );
499
+ });
500
+
501
+ it.each([
502
+ ["localhost"],
503
+ ["127.0.0.1"],
504
+ ["169.254.169.254"],
505
+ ])(
506
+ "passes the %s-resolved url (post-render) to ssrfSafeFetch",
507
+ async (host) => {
508
+ const config: HttpAgentData = {
509
+ ...defaultConfig,
510
+ url: "https://{{input | raw}}/path",
511
+ };
512
+ const input: AgentInput = {
513
+ ...defaultInput,
514
+ messages: [{ role: "user", content: host }],
515
+ newMessages: [{ role: "user", content: host }],
516
+ };
517
+ const adapter = new SerializedHttpAgentAdapter(config);
518
+
519
+ await expect(adapter.call(input)).rejects.toThrow();
520
+
521
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
522
+ `https://${host}/path`,
523
+ expect.any(Object),
524
+ );
525
+ },
526
+ );
527
+ });
528
+
529
+ describe("when url template is malformed", () => {
530
+ it("throws TemplateRenderError with field=url", async () => {
531
+ const config: HttpAgentData = {
532
+ ...defaultConfig,
533
+ url: "https://api.example.com/{% if %}/broken",
534
+ };
535
+ const adapter = new SerializedHttpAgentAdapter(config);
536
+
537
+ await expect(adapter.call(defaultInput)).rejects.toThrow(
538
+ TemplateRenderError,
539
+ );
540
+
541
+ await expect(adapter.call(defaultInput)).rejects.toMatchObject({
542
+ field: "url",
543
+ });
544
+ });
545
+ });
546
+ });
367
547
  });
@@ -8,18 +8,16 @@
8
8
  import type { AgentInput } from "@langwatch/scenario";
9
9
  import { AgentAdapter, AgentRole } from "@langwatch/scenario";
10
10
  import { JSONPath } from "jsonpath-plus";
11
- import { Liquid } from "liquidjs";
12
11
  import { ssrfSafeFetch } from "~/utils/ssrfProtection";
13
12
  import { applyAuthentication } from "../../adapters/auth.strategies";
14
- import { resolveFieldMappings } from "../resolve-field-mappings";
13
+ import {
14
+ buildTemplateContext,
15
+ renderBodyTemplate,
16
+ renderUrlTemplate,
17
+ } from "../http-template-engine";
15
18
  import { injectTraceContextHeaders } from "../trace-context-headers";
16
19
  import type { HttpAgentData } from "../types";
17
20
 
18
- // Shared Liquid engine instance for template interpolation
19
- const liquid = new Liquid();
20
-
21
- const DEFAULT_SCENARIO_THREAD_ID = "scenario-test";
22
-
23
21
  /**
24
22
  * Serialized HTTP agent adapter that uses pre-fetched configuration.
25
23
  * No database access required.
@@ -42,9 +40,14 @@ export class SerializedHttpAgentAdapter extends AgentAdapter {
42
40
  }
43
41
 
44
42
  async call(input: AgentInput): Promise<string> {
43
+ const templateContext = buildTemplateContext({
44
+ input,
45
+ scenarioMappings: this.config.scenarioMappings,
46
+ });
47
+ const url = this.buildUrl(templateContext);
45
48
  const headers = this.buildRequestHeaders();
46
- const body = this.buildRequestBody(input);
47
- const responseData = await this.executeHttpRequest(headers, body);
49
+ const body = this.buildRequestBody(input, templateContext);
50
+ const responseData = await this.executeHttpRequest(url, headers, body);
48
51
  return this.extractResponseContent(responseData);
49
52
  }
50
53
 
@@ -68,12 +71,17 @@ export class SerializedHttpAgentAdapter extends AgentAdapter {
68
71
  return headers;
69
72
  }
70
73
 
74
+ private buildUrl(context: Record<string, unknown>): string {
75
+ return renderUrlTemplate({ template: this.config.url, context });
76
+ }
77
+
71
78
  private async executeHttpRequest(
79
+ url: string,
72
80
  headers: Record<string, string>,
73
81
  body: string,
74
82
  ): Promise<unknown> {
75
83
  const method = this.config.method.toUpperCase();
76
- const response = await ssrfSafeFetch(this.config.url, {
84
+ const response = await ssrfSafeFetch(url, {
77
85
  method,
78
86
  headers,
79
87
  body: method !== "GET" ? body : undefined,
@@ -110,29 +118,17 @@ export class SerializedHttpAgentAdapter extends AgentAdapter {
110
118
  return typeof value === "string" ? value : JSON.stringify(value);
111
119
  }
112
120
 
113
- private buildRequestBody(input: AgentInput): string {
121
+ private buildRequestBody(
122
+ input: AgentInput,
123
+ context: Record<string, unknown>,
124
+ ): string {
114
125
  if (!this.config.bodyTemplate) {
115
126
  return JSON.stringify({ messages: input.messages });
116
127
  }
117
128
 
118
- // Build base template context for Liquid (legacy defaults)
119
- const lastUserMessage = input.messages.findLast((m) => m.role === "user");
120
- const baseContext = {
121
- messages: JSON.stringify(input.messages),
122
- threadId: input.threadId ?? DEFAULT_SCENARIO_THREAD_ID,
123
- input:
124
- typeof lastUserMessage?.content === "string"
125
- ? lastUserMessage.content
126
- : JSON.stringify(lastUserMessage?.content ?? ""),
127
- };
128
-
129
- // Merge resolved scenarioMappings into the template context (overrides defaults)
130
- const mappedValues = this.config.scenarioMappings
131
- ? resolveFieldMappings({ fieldMappings: this.config.scenarioMappings, agentInput: input })
132
- : {};
133
-
134
- const templateContext = { ...baseContext, ...mappedValues };
135
-
136
- return liquid.parseAndRenderSync(this.config.bodyTemplate, templateContext);
129
+ return renderBodyTemplate({
130
+ template: this.config.bodyTemplate,
131
+ context,
132
+ });
137
133
  }
138
134
  }
@@ -87,7 +87,6 @@ describe("migrateCustomModelsRow()", () => {
87
87
  maxTokens: 8192,
88
88
  supportedParameters: [
89
89
  "temperature",
90
- "max_tokens",
91
90
  ],
92
91
  },
93
92
  ]);
@@ -175,7 +174,6 @@ describe("migrateCustomModelsRow()", () => {
175
174
  maxTokens: 8192,
176
175
  supportedParameters: [
177
176
  "temperature",
178
- "max_tokens",
179
177
  ],
180
178
  },
181
179
  ]);
@@ -47,7 +47,7 @@ type MigrationResult = {
47
47
  // ============================================================================
48
48
 
49
49
  const CHAT_DEFAULTS = {
50
- supportedParameters: ["temperature", "max_tokens"],
50
+ supportedParameters: ["temperature"],
51
51
  maxTokens: 8192,
52
52
  } as const;
53
53
 
@@ -74,23 +74,6 @@ describe("guardProjectId — exempt org-scoped gateway models", () => {
74
74
  });
75
75
  });
76
76
 
77
- describe("findMany on GatewayAuditLog with organizationId + cursor", () => {
78
- it("does NOT throw (audit is org-level, projectId column allows null)", async () => {
79
- await expect(
80
- runGuard({
81
- model: "GatewayAuditLog",
82
- action: "findMany",
83
- args: {
84
- where: {
85
- organizationId: "org_01",
86
- createdAt: { lt: new Date() },
87
- },
88
- },
89
- }),
90
- ).resolves.toBe("ok");
91
- });
92
- });
93
-
94
77
  describe("createMany on VirtualKeyProviderCredential without projectId", () => {
95
78
  it("does NOT throw — join table, projectId reachable via parent VK", async () => {
96
79
  // This path is hit on every VK create + every update that changes the
@@ -20,6 +20,7 @@ export const orderedResources: Resource[] = [
20
20
  Resources.WORKFLOWS,
21
21
  Resources.PROMPTS,
22
22
  Resources.SECRETS,
23
+ Resources.AUDIT_LOG,
23
24
  Resources.TEAM,
24
25
  Resources.PROJECT,
25
26
  // Resources.PLAYGROUND, // Hidden intentionally
@@ -38,6 +39,11 @@ export function getValidActionsForResource(resource: Resource): Action[] {
38
39
  if (resource === Resources.SCENARIOS) {
39
40
  return [Actions.VIEW];
40
41
  }
42
+ if (resource === Resources.AUDIT_LOG) {
43
+ // Audit log is read-only; rows are emitted by other services and never
44
+ // mutated through this surface. Only :view is meaningful.
45
+ return [Actions.VIEW];
46
+ }
41
47
  return [
42
48
  Actions.MANAGE,
43
49
  Actions.VIEW,
@@ -204,11 +204,6 @@ export const projectRoutes = {
204
204
  title: "Usage",
205
205
  parent: "gateway",
206
206
  },
207
- gateway_audit: {
208
- path: "/[project]/gateway/audit",
209
- title: "Audit log",
210
- parent: "gateway",
211
- },
212
207
  gateway_cache_rules: {
213
208
  path: "/[project]/gateway/cache-rules",
214
209
  title: "Cache Rules",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langwatch/server",
3
- "version": "3.1.0-beta.19",
3
+ "version": "3.1.0-beta.20",
4
4
  "description": "Run LangWatch locally with one command — `npx @langwatch/server`. Bundles the Next.js control plane, Python NLP service, evaluators, and the Go AI gateway with embedded postgres, redis, and clickhouse.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://langwatch.ai",
@@ -22341,7 +22341,7 @@ function execCheck(command, args, opts = {}) {
22341
22341
  return async () => {
22342
22342
  const start = Date.now();
22343
22343
  try {
22344
- const { exitCode, stdout } = await execa(command, args, { reject: false });
22344
+ const { exitCode, stdout } = await execa(command, args, { reject: false, env: opts.env });
22345
22345
  if (exitCode !== 0) {
22346
22346
  return { ok: false, durationMs: Date.now() - start, reason: `exit ${exitCode}` };
22347
22347
  }
@@ -23165,8 +23165,9 @@ async function runMigrations(ctx, bus, envFromFile) {
23165
23165
  SKIP_PRISMA_MIGRATE: "false",
23166
23166
  SKIP_CLICKHOUSE_MIGRATE: "false"
23167
23167
  };
23168
- await execAndPipe(bus, "migrate:prisma", "pnpm", ["run", "prisma:migrate"], { cwd: langwatchDir, env: env3 });
23169
- await execAndPipe(bus, "migrate:clickhouse", "pnpm", ["run", "clickhouse:migrate"], { cwd: langwatchDir, env: env3 });
23168
+ const pnpm = await resolvePnpm();
23169
+ await execAndPipe(bus, "migrate:prisma", pnpm.command, [...pnpm.args, "run", "prisma:migrate"], { cwd: langwatchDir, env: env3 });
23170
+ await execAndPipe(bus, "migrate:clickhouse", pnpm.command, [...pnpm.args, "run", "clickhouse:migrate"], { cwd: langwatchDir, env: env3 });
23170
23171
  bus.emit({ type: "healthy", service: "postgres", durationMs: Date.now() - start });
23171
23172
  }
23172
23173
  var init_migrate = __esm({
@@ -23188,16 +23189,27 @@ function postgresLayout(postgresBinPath) {
23188
23189
  createdb: (0, import_node_path31.join)(binDir, "createdb")
23189
23190
  };
23190
23191
  }
23192
+ function pgEnv(resolvedPath, base = process.env) {
23193
+ const libDir = (0, import_node_path31.join)((0, import_node_path31.dirname)((0, import_node_path31.dirname)(resolvedPath)), "lib");
23194
+ if (!(0, import_node_fs29.existsSync)(libDir)) return base;
23195
+ const var_ = process.platform === "darwin" ? "DYLD_LIBRARY_PATH" : "LD_LIBRARY_PATH";
23196
+ const existing = base[var_];
23197
+ return {
23198
+ ...base,
23199
+ [var_]: existing ? `${libDir}:${existing}` : libDir
23200
+ };
23201
+ }
23191
23202
  async function startPostgres(ctx, bus) {
23192
23203
  bus.emit({ type: "starting", service: "postgres" });
23193
23204
  const start = Date.now();
23194
23205
  const resolvedPath = ctx.predeps.postgres?.resolvedPath;
23195
23206
  if (!resolvedPath) throw new Error("postgres predep not resolved \u2014 run install first");
23196
23207
  const layout = postgresLayout(resolvedPath);
23208
+ const env3 = pgEnv(resolvedPath);
23197
23209
  const dataDir = ctx.paths.postgresData;
23198
23210
  const sp = servicePaths(ctx.paths);
23199
23211
  if (!(0, import_node_fs29.existsSync)((0, import_node_path31.join)(dataDir, "PG_VERSION"))) {
23200
- await initdb(layout, dataDir);
23212
+ await initdb(layout, dataDir, env3);
23201
23213
  }
23202
23214
  const handle = supervise({
23203
23215
  spec: {
@@ -23217,101 +23229,54 @@ async function startPostgres(ctx, bus) {
23217
23229
  "-c",
23218
23230
  "logging_collector=off"
23219
23231
  ],
23220
- env: process.env
23232
+ env: env3
23221
23233
  },
23222
23234
  paths: sp,
23223
23235
  bus
23224
23236
  });
23225
23237
  const ready = await pollUntilHealthy({
23226
- check: execCheck(layout.psql.replace(/psql$/, "pg_isready"), [
23227
- "-h",
23228
- "127.0.0.1",
23229
- "-p",
23230
- String(ctx.ports.postgres),
23231
- "-U",
23232
- DB_USER,
23233
- "-d",
23234
- "postgres",
23235
- "-q"
23236
- ]),
23238
+ check: execCheck(
23239
+ layout.psql.replace(/psql$/, "pg_isready"),
23240
+ ["-h", "127.0.0.1", "-p", String(ctx.ports.postgres), "-U", DB_USER, "-d", "postgres", "-q"],
23241
+ { env: env3 }
23242
+ ),
23237
23243
  timeoutMs: 3e4
23238
23244
  });
23239
23245
  if (!ready.ok) {
23240
23246
  await handle.stop();
23241
23247
  throw new Error(`postgres did not become ready: ${ready.reason}`);
23242
23248
  }
23243
- await ensureDatabase2(layout, ctx.ports.postgres);
23249
+ await ensureDatabase2(layout, ctx.ports.postgres, env3);
23244
23250
  bus.emit({ type: "healthy", service: "postgres", durationMs: Date.now() - start });
23245
23251
  return handle;
23246
23252
  }
23247
- async function initdb(layout, dataDir) {
23253
+ async function initdb(layout, dataDir, env3) {
23248
23254
  (0, import_node_fs29.mkdirSync)(dataDir, { recursive: true });
23249
23255
  await execa(
23250
23256
  layout.initdb,
23251
- [
23252
- "-D",
23253
- dataDir,
23254
- "-U",
23255
- DB_USER,
23256
- "-A",
23257
- "trust",
23258
- "--no-locale",
23259
- "--encoding=UTF8"
23260
- ],
23261
- { stdio: "ignore" }
23257
+ ["-D", dataDir, "-U", DB_USER, "-A", "trust", "--no-locale", "--encoding=UTF8"],
23258
+ { stdio: "ignore", env: env3 }
23262
23259
  );
23263
23260
  }
23264
- async function ensureDatabase2(layout, port) {
23261
+ async function ensureDatabase2(layout, port, env3) {
23265
23262
  const probe1 = await execa(
23266
23263
  layout.psql,
23267
- [
23268
- "-h",
23269
- "127.0.0.1",
23270
- "-p",
23271
- String(port),
23272
- "-U",
23273
- DB_USER,
23274
- "-d",
23275
- "postgres",
23276
- "-tc",
23277
- `SELECT 1 FROM pg_database WHERE datname='${DB_NAME2}'`
23278
- ],
23279
- { reject: false }
23264
+ ["-h", "127.0.0.1", "-p", String(port), "-U", DB_USER, "-d", "postgres", "-tc", `SELECT 1 FROM pg_database WHERE datname='${DB_NAME2}'`],
23265
+ { reject: false, env: env3 }
23280
23266
  );
23281
23267
  if (probe1.exitCode !== 0) {
23282
- throw new Error(
23283
- `postgres connect probe failed (psql exit ${probe1.exitCode}): ${probe1.stderr || probe1.stdout || "no output"}`
23284
- );
23268
+ throw new Error(`postgres connect probe failed (psql exit ${probe1.exitCode}): ${probe1.stderr || probe1.stdout || "no output"}`);
23285
23269
  }
23286
23270
  const probe = await execa(
23287
23271
  layout.psql,
23288
- [
23289
- "-h",
23290
- "127.0.0.1",
23291
- "-p",
23292
- String(port),
23293
- "-U",
23294
- DB_USER,
23295
- "-d",
23296
- "postgres",
23297
- "-tAc",
23298
- `SELECT 1 FROM pg_database WHERE datname='${DB_NAME2}'`
23299
- ],
23300
- { reject: false }
23272
+ ["-h", "127.0.0.1", "-p", String(port), "-U", DB_USER, "-d", "postgres", "-tAc", `SELECT 1 FROM pg_database WHERE datname='${DB_NAME2}'`],
23273
+ { reject: false, env: env3 }
23301
23274
  );
23302
23275
  if (probe.stdout.trim() === "1") return;
23303
23276
  await execa(
23304
23277
  layout.createdb,
23305
- [
23306
- "-h",
23307
- "127.0.0.1",
23308
- "-p",
23309
- String(port),
23310
- "-U",
23311
- DB_USER,
23312
- DB_NAME2
23313
- ],
23314
- { stdio: "ignore" }
23278
+ ["-h", "127.0.0.1", "-p", String(port), "-U", DB_USER, DB_NAME2],
23279
+ { stdio: "ignore", env: env3 }
23315
23280
  );
23316
23281
  }
23317
23282
  var import_node_fs29, import_node_path31, DB_USER, DB_NAME2;
@@ -26556,11 +26521,15 @@ var postgresPredep = {
26556
26521
  label: `postgresql ${PG_MAJOR}`,
26557
26522
  required: true,
26558
26523
  async detect(paths2) {
26524
+ const forceBundled = /^(1|true|yes)$/i.test(process.env.LANGWATCH_FORCE_BUNDLED_POSTGRES ?? "");
26559
26525
  const bundled = (0, import_node_path19.join)(paths2.bin, "postgres", "bin", "postgres");
26560
26526
  if ((0, import_node_fs16.existsSync)(bundled)) {
26561
26527
  const v2 = await resolveVersion4(bundled);
26562
26528
  if (v2) return { installed: true, version: v2, resolvedPath: bundled };
26563
26529
  }
26530
+ if (forceBundled) {
26531
+ return { installed: false, reason: "LANGWATCH_FORCE_BUNDLED_POSTGRES=1 \u2014 skipping system postgres; bundled tarball will be downloaded" };
26532
+ }
26564
26533
  try {
26565
26534
  const { stdout } = await execa("which", ["postgres"], { reject: false });
26566
26535
  const path6 = stdout.trim();
@@ -26988,7 +26957,7 @@ var placeholderRuntime = {
26988
26957
  };
26989
26958
 
26990
26959
  // src/cli.ts
26991
- var VERSION = true ? "3.1.0-beta.19" : "0.0.0-dev";
26960
+ var VERSION = true ? "3.1.0-beta.20" : "0.0.0-dev";
26992
26961
  async function loadRuntime() {
26993
26962
  try {
26994
26963
  const real = await Promise.resolve().then(() => (init_runtime(), runtime_exports));