@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
@@ -0,0 +1,44 @@
1
+ -- Consolidate GatewayAuditLog into AuditLog
2
+ --
3
+ -- The AI gateway shipped with its own GatewayAuditLog table + GatewayAuditAction enum.
4
+ -- That was an information-architecture mistake — governance events should live in one
5
+ -- place. Per rchaves: no beta users yet, no records to preserve, drop freely.
6
+ --
7
+ -- Forward direction:
8
+ -- 1. Extend AuditLog with the gateway-shape columns (targetKind/targetId/before/after).
9
+ -- 2. Add indexes mirroring the gateway table's read patterns.
10
+ -- 3. Drop GatewayAuditLog table + GatewayAuditAction enum.
11
+ --
12
+ -- After this migration the gateway services (virtualKey/budget/providerCredential/
13
+ -- cacheRule) write to AuditLog directly via the same `GatewayAuditLogRepository`
14
+ -- TypeScript class (preserved as a thin shape adapter — see
15
+ -- langwatch/src/server/gateway/auditLog.repository.ts).
16
+
17
+ -- 1. Extend AuditLog with governance fields ---------------------------------
18
+ --
19
+ -- userId is dropped to nullable so system-actor writes (background jobs,
20
+ -- migrations, internal cron) can record audit rows without a user. Spec:
21
+ -- specs/audit-log/audit-log.feature ("userId is changed to String? (nullable)
22
+ -- so system actions can write rows without a user"). Live consumers always
23
+ -- supply userId today; this is forward-defense for the system-actor path.
24
+ -- DROP NOT NULL is a fast metadata-only operation on PG — no rewrite.
25
+
26
+ ALTER TABLE "AuditLog"
27
+ ADD COLUMN "targetKind" TEXT,
28
+ ADD COLUMN "targetId" TEXT,
29
+ ADD COLUMN "before" JSONB,
30
+ ADD COLUMN "after" JSONB,
31
+ ALTER COLUMN "userId" DROP NOT NULL;
32
+
33
+ -- 2. Indexes mirroring the dropped GatewayAuditLog read patterns -----------
34
+
35
+ CREATE INDEX "AuditLog_organizationId_createdAt_idx"
36
+ ON "AuditLog" ("organizationId", "createdAt" DESC);
37
+
38
+ CREATE INDEX "AuditLog_targetKind_targetId_idx"
39
+ ON "AuditLog" ("targetKind", "targetId");
40
+
41
+ -- 3. Drop the gateway-only audit table + enum ------------------------------
42
+
43
+ DROP TABLE IF EXISTS "GatewayAuditLog";
44
+ DROP TYPE IF EXISTS "GatewayAuditAction";
@@ -0,0 +1,25 @@
1
+ -- Drop the redundant single-column index `AuditLog_organizationId_idx`.
2
+ --
3
+ -- The composite `AuditLog_organizationId_createdAt_idx` (added in
4
+ -- 20260425000000_consolidate_gateway_audit_into_audit_log) covers every
5
+ -- query the dropped index served via leftmost-prefix indexing — Postgres
6
+ -- will use the composite for both `WHERE organizationId = X` and
7
+ -- `WHERE organizationId = X ORDER BY createdAt DESC` lookups.
8
+ --
9
+ -- Removing the duplicate cuts write amplification on a hot table (every
10
+ -- gateway + platform mutation appends an AuditLog row) without changing
11
+ -- read-path behavior.
12
+ --
13
+ -- LOCKING NOTE: Plain `DROP INDEX [IF EXISTS]` acquires an ACCESS
14
+ -- EXCLUSIVE lock on the table for the duration of the drop — this
15
+ -- blocks concurrent reads and writes on `AuditLog` until the operation
16
+ -- completes. The `IF EXISTS` clause only changes error handling
17
+ -- (NOTICE instead of ERROR when the index is missing), it does NOT
18
+ -- change locking behavior. Dropping a single index is a fast
19
+ -- metadata-only operation (typically milliseconds even on large
20
+ -- tables, since the index file is just unlinked), so the brief lock
21
+ -- is acceptable for AuditLog. If we ever need a truly non-blocking
22
+ -- variant, swap to `DROP INDEX CONCURRENTLY IF EXISTS` — but that
23
+ -- can't run inside a transaction, so it would need a Prisma
24
+ -- non-transactional migration setup we don't have today.
25
+ DROP INDEX IF EXISTS "AuditLog_organizationId_idx";
@@ -97,7 +97,6 @@ model User {
97
97
  gatewayBudgetsCreated GatewayBudget[] @relation("GatewayBudgetCreatedBy")
98
98
  principalVirtualKeys VirtualKey[] @relation("VirtualKeyPrincipalUser")
99
99
  principalGatewayBudgets GatewayBudget[] @relation("PrincipalScopedGatewayBudgets")
100
- gatewayAuditLogs GatewayAuditLog[] @relation("GatewayAuditLogActor")
101
100
  }
102
101
 
103
102
  model VerificationToken {
@@ -341,7 +340,6 @@ model Project {
341
340
  gatewayProviderCreds GatewayProviderCredential[]
342
341
  gatewayBudgets GatewayBudget[] @relation("ProjectScopedGatewayBudgets")
343
342
  gatewayChangeEvents GatewayChangeEvent[]
344
- gatewayAuditLogs GatewayAuditLog[]
345
343
 
346
344
  @@index([teamId])
347
345
  }
@@ -952,10 +950,23 @@ model OrganizationFeature {
952
950
  @@index([organizationId])
953
951
  }
954
952
 
953
+ // AuditLog is the unified governance ledger. Both gateway-driven mutations
954
+ // (VK/budget/provider-binding/cache-rule via the 4 gateway services) and
955
+ // platform-driven actions (tRPC mutations via auditLogMutations middleware)
956
+ // write here. There is no separate GatewayAuditLog table — see migration
957
+ // 20260425000000_consolidate_gateway_audit_into_audit_log.
958
+ //
959
+ // Two write shapes coexist on the same table:
960
+ // * Platform shape — `args` + `metadata` + `error` carry the call-site
961
+ // context. `targetKind`, `targetId`, `before`, `after` stay null.
962
+ // * Gateway shape — `targetKind`, `targetId`, `before`, `after` carry
963
+ // resource identity + diff. `args` / `metadata` / `error` stay null.
964
+ // The /settings/audit-log page renders both via a `source` field computed
965
+ // from the presence of `targetKind` (gateway = purple badge, platform = grey).
955
966
  model AuditLog {
956
967
  id String @id @default(cuid())
957
968
  createdAt DateTime @default(now())
958
- userId String
969
+ userId String?
959
970
  projectId String?
960
971
  organizationId String?
961
972
  action String
@@ -965,12 +976,19 @@ model AuditLog {
965
976
  userAgent String?
966
977
  metadata Json?
967
978
 
979
+ // Gateway-shape governance fields (see model docstring above).
980
+ targetKind String?
981
+ targetId String?
982
+ before Json?
983
+ after Json?
984
+
968
985
  @@index([createdAt])
969
986
  @@index([userId])
970
987
  @@index([projectId])
971
- @@index([organizationId])
972
988
  @@index([action])
973
989
  @@index([ipAddress])
990
+ @@index([organizationId, createdAt])
991
+ @@index([targetKind, targetId])
974
992
  }
975
993
 
976
994
  enum PromptScope {
@@ -1413,8 +1431,8 @@ model BillingMeterCheckpoint {
1413
1431
  // gateway_request_id (outbox pattern — writes from the Go gateway).
1414
1432
  // - GatewayChangeEvent: monotonically-increasing revision feed consumed by
1415
1433
  // the gateway's long-poll `/internal/gateway/changes?since=N` endpoint.
1416
- // - GatewayAuditLog: full actor/action/before/after audit for every
1417
- // gateway-surface mutation.
1434
+ // - AuditLog (top of file): unified actor/action/before/after audit for
1435
+ // every gateway-surface mutation alongside platform mutations.
1418
1436
  // ============================================================================
1419
1437
 
1420
1438
  enum VirtualKeyEnvironment {
@@ -1489,22 +1507,13 @@ enum GatewayChangeEventKind {
1489
1507
  CACHE_RULE_DELETED
1490
1508
  }
1491
1509
 
1492
- enum GatewayAuditAction {
1493
- VIRTUAL_KEY_CREATED
1494
- VIRTUAL_KEY_UPDATED
1495
- VIRTUAL_KEY_ROTATED
1496
- VIRTUAL_KEY_REVOKED
1497
- VIRTUAL_KEY_DELETED
1498
- BUDGET_CREATED
1499
- BUDGET_UPDATED
1500
- BUDGET_DELETED
1501
- PROVIDER_BINDING_CREATED
1502
- PROVIDER_BINDING_UPDATED
1503
- PROVIDER_BINDING_DELETED
1504
- CACHE_RULE_CREATED
1505
- CACHE_RULE_UPDATED
1506
- CACHE_RULE_DELETED
1507
- }
1510
+ // Gateway audit action codes — kept as a TypeScript const union in
1511
+ // langwatch/src/server/gateway/auditLog.repository.ts (no Prisma enum
1512
+ // because gateway rows now write to the shared `AuditLog` table whose
1513
+ // `action` column is a free-form String).
1514
+ //
1515
+ // enum GatewayAuditAction { ... } — removed in migration
1516
+ // 20260425000000_consolidate_gateway_audit_into_audit_log.
1508
1517
 
1509
1518
  enum GatewayCacheRuleMode {
1510
1519
  RESPECT
@@ -1736,25 +1745,9 @@ model GatewayChangeEvent {
1736
1745
  @@index([budgetId])
1737
1746
  }
1738
1747
 
1739
- model GatewayAuditLog {
1740
- id String @id @default(nanoid())
1741
- organizationId String
1742
- projectId String?
1743
- project Project? @relation(fields: [projectId], references: [id], onDelete: SetNull)
1744
- actorUserId String?
1745
- actor User? @relation("GatewayAuditLogActor", fields: [actorUserId], references: [id], onDelete: SetNull)
1746
- action GatewayAuditAction
1747
- targetKind String // "virtual_key" | "budget" | "provider_binding"
1748
- targetId String
1749
- before Json?
1750
- after Json?
1751
- createdAt DateTime @default(now())
1752
-
1753
- @@index([organizationId, createdAt])
1754
- @@index([projectId, createdAt])
1755
- @@index([actorUserId])
1756
- @@index([targetKind, targetId])
1757
- }
1748
+ // model GatewayAuditLog removed — gateway services now write to the
1749
+ // shared `AuditLog` model (top of file). See migration
1750
+ // 20260425000000_consolidate_gateway_audit_into_audit_log.
1758
1751
 
1759
1752
  // AI Gateway cache-control rules — operator-defined overrides without
1760
1753
  // client code changes. Org-scoped; compiled into the VK bundle at
@@ -846,30 +846,30 @@ async function seedAuditLog(args: {
846
846
  cacheRules: Array<{ id: string; name: string }>;
847
847
  providerBindings: Array<{ id: string; slot: string }>;
848
848
  }) {
849
- // Idempotency guard: GatewayAuditLog has no natural unique key
850
- // (PK=nanoid, no composite constraint on target + action + day), so
851
- // a second run of this seed would pile on synthetic VIRTUAL_KEY_CREATED
849
+ // Idempotency guard: AuditLog has no natural unique key for gateway-shape
850
+ // rows (PK=cuid, no composite constraint on target + action + day), so
851
+ // a second run of this seed would pile on synthetic gateway.virtual_key.created
852
852
  // rows and make the Audit page show two (or more) 'created' events per
853
853
  // VK. @ariana finding #10. If the first seeded VK already has any
854
854
  // audit rows attached, assume the full replay ran before and skip.
855
855
  const firstVkId = args.virtualKeys[0]?.id;
856
856
  if (firstVkId) {
857
- const alreadySeeded = await prisma.gatewayAuditLog.count({
857
+ const alreadySeeded = await prisma.auditLog.count({
858
858
  where: {
859
859
  organizationId: args.organizationId,
860
860
  targetKind: "virtual_key",
861
861
  targetId: firstVkId,
862
- action: "VIRTUAL_KEY_CREATED",
862
+ action: "gateway.virtual_key.created",
863
863
  },
864
864
  });
865
865
  if (alreadySeeded > 0) {
866
866
  console.log(
867
- "· audit log already seeded (found VIRTUAL_KEY_CREATED for first VK) — skipping replay",
867
+ "· audit log already seeded (found gateway.virtual_key.created for first VK) — skipping replay",
868
868
  );
869
869
  return;
870
870
  }
871
871
  }
872
- const events: Prisma.GatewayAuditLogCreateManyInput[] = [];
872
+ const events: Prisma.AuditLogCreateManyInput[] = [];
873
873
  const now = Date.now();
874
874
  const daysAgo = (d: number) => new Date(now - d * 24 * 60 * 60 * 1000);
875
875
 
@@ -877,8 +877,8 @@ async function seedAuditLog(args: {
877
877
  events.push({
878
878
  organizationId: args.organizationId,
879
879
  projectId: args.projectId,
880
- actorUserId: args.actorUserId,
881
- action: "VIRTUAL_KEY_CREATED",
880
+ userId: args.actorUserId,
881
+ action: "gateway.virtual_key.created",
882
882
  targetKind: "virtual_key",
883
883
  targetId: vk.id,
884
884
  before: Prisma.JsonNull,
@@ -890,8 +890,8 @@ async function seedAuditLog(args: {
890
890
  events.push({
891
891
  organizationId: args.organizationId,
892
892
  projectId: args.projectId,
893
- actorUserId: args.actorUserId,
894
- action: "VIRTUAL_KEY_UPDATED",
893
+ userId: args.actorUserId,
894
+ action: "gateway.virtual_key.updated",
895
895
  targetKind: "virtual_key",
896
896
  targetId: args.virtualKeys[0]?.id ?? "vk_unknown",
897
897
  before: { rateLimits: { rpm: 300 } } as Prisma.InputJsonValue,
@@ -901,8 +901,8 @@ async function seedAuditLog(args: {
901
901
  events.push({
902
902
  organizationId: args.organizationId,
903
903
  projectId: args.projectId,
904
- actorUserId: args.actorUserId,
905
- action: "VIRTUAL_KEY_ROTATED",
904
+ userId: args.actorUserId,
905
+ action: "gateway.virtual_key.rotated",
906
906
  targetKind: "virtual_key",
907
907
  targetId: args.virtualKeys[1]?.id ?? "vk_unknown",
908
908
  before: { displayPrefix: "lw_vk_a1b2c3" } as Prisma.InputJsonValue,
@@ -915,8 +915,8 @@ async function seedAuditLog(args: {
915
915
  events.push({
916
916
  organizationId: args.organizationId,
917
917
  projectId: args.projectId,
918
- actorUserId: args.actorUserId,
919
- action: "VIRTUAL_KEY_REVOKED",
918
+ userId: args.actorUserId,
919
+ action: "gateway.virtual_key.revoked",
920
920
  targetKind: "virtual_key",
921
921
  targetId: revoked.id,
922
922
  before: { status: "ACTIVE" } as Prisma.InputJsonValue,
@@ -928,8 +928,8 @@ async function seedAuditLog(args: {
928
928
  events.push({
929
929
  organizationId: args.organizationId,
930
930
  projectId: args.projectId,
931
- actorUserId: args.actorUserId,
932
- action: "BUDGET_CREATED",
931
+ userId: args.actorUserId,
932
+ action: "gateway.budget.created",
933
933
  targetKind: "budget",
934
934
  targetId: b.id,
935
935
  before: Prisma.JsonNull,
@@ -942,8 +942,8 @@ async function seedAuditLog(args: {
942
942
  events.push({
943
943
  organizationId: args.organizationId,
944
944
  projectId: args.projectId,
945
- actorUserId: args.actorUserId,
946
- action: "BUDGET_UPDATED",
945
+ userId: args.actorUserId,
946
+ action: "gateway.budget.updated",
947
947
  targetKind: "budget",
948
948
  targetId: args.budgets[0].id,
949
949
  before: { limitUsd: "3000", onBreach: "WARN" } as Prisma.InputJsonValue,
@@ -955,8 +955,8 @@ async function seedAuditLog(args: {
955
955
  events.push({
956
956
  organizationId: args.organizationId,
957
957
  projectId: args.projectId,
958
- actorUserId: args.actorUserId,
959
- action: "PROVIDER_BINDING_CREATED",
958
+ userId: args.actorUserId,
959
+ action: "gateway.provider_binding.created",
960
960
  targetKind: "provider_binding",
961
961
  targetId: pb.id,
962
962
  before: Prisma.JsonNull,
@@ -968,8 +968,8 @@ async function seedAuditLog(args: {
968
968
  events.push({
969
969
  organizationId: args.organizationId,
970
970
  projectId: args.projectId,
971
- actorUserId: args.actorUserId,
972
- action: "CACHE_RULE_CREATED",
971
+ userId: args.actorUserId,
972
+ action: "gateway.cache_rule.created",
973
973
  targetKind: "cache_rule",
974
974
  targetId: cr.id,
975
975
  before: Prisma.JsonNull,
@@ -981,8 +981,8 @@ async function seedAuditLog(args: {
981
981
  events.push({
982
982
  organizationId: args.organizationId,
983
983
  projectId: args.projectId,
984
- actorUserId: args.actorUserId,
985
- action: "CACHE_RULE_UPDATED",
984
+ userId: args.actorUserId,
985
+ action: "gateway.cache_rule.updated",
986
986
  targetKind: "cache_rule",
987
987
  targetId: args.cacheRules[0].id,
988
988
  before: { priority: 200, "action.ttl": 300 } as Prisma.InputJsonValue,
@@ -991,7 +991,7 @@ async function seedAuditLog(args: {
991
991
  });
992
992
  }
993
993
 
994
- const result = await prisma.gatewayAuditLog.createMany({
994
+ const result = await prisma.auditLog.createMany({
995
995
  data: events,
996
996
  skipDuplicates: true,
997
997
  });
@@ -4,10 +4,14 @@
4
4
  * `gatewayBudgets` tRPC routers consumed by the UI.
5
5
  *
6
6
  * Auth: standard project API key (`Authorization: Bearer <projectApiKey>`
7
- * or `X-Auth-Token`). All writes are audited to `GatewayAuditLog` with the
8
- * actor set to `svc_<projectApiKeyId>` (machine principal) rather than a
9
- * human user — the audit repository already accepts a null actorUserId for
10
- * this case.
7
+ * or `X-Auth-Token`). All writes are audited to `AuditLog` (gateway shape)
8
+ * with the actor set to a synthetic machine principal of the form
9
+ * `svc_<projectId>` (see `machineActorForProject`) — the API key bearer is
10
+ * a project-scoped credential, not a `User.id`, so the audit row records
11
+ * the project as the principal rather than fabricating a user link.
12
+ * `AuditLog.userId` is now nullable post-consolidation, so a future
13
+ * service-to-service write path can drop the synthetic id entirely; until
14
+ * then this preserves a stable per-project actor for forensic queries.
11
15
  */
12
16
  import { Hono } from "hono";
13
17
  import { describeRoute } from "hono-openapi";
@@ -36,6 +36,16 @@ export const blockTraceUsageExceededMiddleware: MiddlewareHandler = async (
36
36
  logger.error({ error, projectId: project.id }, "Plan limit notification failed");
37
37
  }
38
38
 
39
+ logger.info(
40
+ {
41
+ projectId: project.id,
42
+ currentMonthMessagesCount: result.count,
43
+ activePlanName: result.planName,
44
+ maxMessagesPerMonth: result.maxMessagesPerMonth,
45
+ },
46
+ "Project has reached plan limit",
47
+ );
48
+
39
49
  return c.json({ error: "ERR_PLAN_LIMIT", message: result.message }, 429);
40
50
  }
41
51
 
@@ -3,7 +3,6 @@ import type { Project } from "@prisma/client";
3
3
  import {
4
4
  Activity,
5
5
  Anvil,
6
- FileClock,
7
6
  Film,
8
7
  Gauge,
9
8
  History,
@@ -364,20 +363,10 @@ export const MainMenu = React.memo(function MainMenu({
364
363
  },
365
364
  ]
366
365
  : []),
367
- ...(hasPermission("gatewayLogs:view")
368
- ? [
369
- {
370
- icon: FileClock,
371
- label: projectRoutes.gateway_audit.title,
372
- href: projectRoutes.gateway_audit.path.replace(
373
- "[project]",
374
- project.slug,
375
- ),
376
- isActive:
377
- router.pathname.includes("/gateway/audit"),
378
- },
379
- ]
380
- : []),
366
+ // Audit log entry removed — gateway audit rows are now
367
+ // surfaced under /settings/audit-log alongside platform
368
+ // governance events. Deep-links from VK / Budget detail
369
+ // pages target /settings/audit-log directly.
381
370
  ]}
382
371
  />
383
372
  </>
@@ -153,7 +153,7 @@ export default function SettingsLayout({
153
153
  {isEnterprise && !isLiteMember && (
154
154
  <MenuLink href="/settings/access-audit">Access Audit</MenuLink>
155
155
  )}
156
- {isEnterprise && !isLiteMember && hasPermission("organization:manage") && (
156
+ {isEnterprise && !isLiteMember && hasPermission("auditLog:view") && (
157
157
  <MenuLink href="/settings/audit-log">Audit Log</MenuLink>
158
158
  )}
159
159
  </NavSection>
@@ -89,6 +89,19 @@ const mockModelMetadata = {
89
89
  pricing: { inputCostPerToken: 0.000003, outputCostPerToken: 0.000015 },
90
90
  reasoningConfig: undefined,
91
91
  },
92
+ "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0": {
93
+ id: "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
94
+ name: "us.anthropic.claude-haiku-4-5-20251001-v1:0",
95
+ provider: "bedrock",
96
+ supportedParameters: ["temperature"],
97
+ contextLength: 0,
98
+ maxCompletionTokens: 8192,
99
+ defaultParameters: null,
100
+ supportsImageInput: false,
101
+ supportsAudioInput: false,
102
+ pricing: { inputCostPerToken: 0, outputCostPerToken: 0 },
103
+ reasoningConfig: undefined,
104
+ },
92
105
  };
93
106
 
94
107
  vi.mock("~/hooks/useModelProvidersSettings", () => ({
@@ -110,6 +123,7 @@ vi.mock("../../ModelSelector", () => ({
110
123
  "openai/gpt-4.1",
111
124
  "openai/gpt-5",
112
125
  "anthropic/claude-3.5-sonnet",
126
+ "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
113
127
  ],
114
128
  ModelSelector: ({
115
129
  model,
@@ -126,6 +140,9 @@ vi.mock("../../ModelSelector", () => ({
126
140
  <option value="openai/gpt-4.1">GPT-4.1</option>
127
141
  <option value="openai/gpt-5">GPT-5</option>
128
142
  <option value="anthropic/claude-3.5-sonnet">Claude 3.5 Sonnet</option>
143
+ <option value="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0">
144
+ Claude Haiku 4.5 (Bedrock)
145
+ </option>
129
146
  </select>
130
147
  ),
131
148
  }));
@@ -303,6 +320,34 @@ describe("LLMConfigPopover", () => {
303
320
  });
304
321
  });
305
322
 
323
+ describe("when the model entry omits max_tokens from supportedParameters", () => {
324
+ describe("for a managed-Bedrock chat custom model registered with only temperature", () => {
325
+ it("renders the Max Tokens slider so the user can configure per-invocation output limits", () => {
326
+ renderComponent({
327
+ values: {
328
+ model: "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
329
+ temperature: 1,
330
+ },
331
+ });
332
+ expect(
333
+ screen.getByTestId("parameter-row-max_tokens"),
334
+ ).toBeInTheDocument();
335
+ });
336
+
337
+ it("still renders the Temperature slider that the entry does declare", () => {
338
+ renderComponent({
339
+ values: {
340
+ model: "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
341
+ temperature: 1,
342
+ },
343
+ });
344
+ expect(
345
+ screen.getByTestId("parameter-row-temperature"),
346
+ ).toBeInTheDocument();
347
+ });
348
+ });
349
+ });
350
+
306
351
  describe("structured outputs section", () => {
307
352
  it("does not show structured outputs by default", () => {
308
353
  renderComponent();
@@ -188,23 +188,32 @@ export class ParameterRegistry {
188
188
 
189
189
  /**
190
190
  * Filter and sort parameters for display.
191
+ *
192
+ * `max_tokens` is always included regardless of whether the model entry
193
+ * declares it: every chat model accepts a per-invocation token ceiling,
194
+ * and the popover is chat-only. Treating it as opt-in caused the slider
195
+ * to flicker-then-disappear for legacy custom models (notably managed
196
+ * Bedrock entries registered with `["temperature"]` only).
191
197
  */
192
198
  getDisplayParameters(supportedParameters: string[]): string[] {
193
- if (!supportedParameters || supportedParameters.length === 0) {
194
- return ["temperature", "max_tokens"]; // Default
195
- }
196
-
197
199
  const displayOrder = this.getDisplayOrder();
198
200
 
199
- return supportedParameters
200
- .filter((param) => this.parameters.has(param))
201
- .sort((a, b) => {
202
- const aIndex = displayOrder.indexOf(a);
203
- const bIndex = displayOrder.indexOf(b);
204
- const aOrder = aIndex === -1 ? 999 : aIndex;
205
- const bOrder = bIndex === -1 ? 999 : bIndex;
206
- return aOrder - bOrder;
207
- });
201
+ const base =
202
+ !supportedParameters || supportedParameters.length === 0
203
+ ? ["temperature"]
204
+ : supportedParameters.filter((param) => this.parameters.has(param));
205
+
206
+ const withMaxTokens = base.includes("max_tokens")
207
+ ? base
208
+ : [...base, "max_tokens"];
209
+
210
+ return withMaxTokens.sort((a, b) => {
211
+ const aIndex = displayOrder.indexOf(a);
212
+ const bIndex = displayOrder.indexOf(b);
213
+ const aOrder = aIndex === -1 ? 999 : aIndex;
214
+ const bOrder = bIndex === -1 ? 999 : bIndex;
215
+ return aOrder - bOrder;
216
+ });
208
217
  }
209
218
 
210
219
  /**
@@ -402,9 +402,10 @@ export function PromptEditorDrawer(props: PromptEditorDrawerProps) {
402
402
  });
403
403
  }
404
404
 
405
- } else if (!promptId && modelMetadata) {
406
- // New prompt - use defaults with model's max tokens
407
- // Wait for modelMetadata to be loaded before initializing
405
+ } else if ((!promptId || (!promptQuery.data && !promptQuery.isLoading)) && modelMetadata) {
406
+ // New prompt OR prompt referenced by ID but not found in DB (e.g. after
407
+ // importing a workflow from another project). Use defaults with model's
408
+ // max tokens, merging initialLocalConfig if available.
408
409
  const defaultModel = project?.defaultModel ?? DEFAULT_MODEL;
409
410
  const defaultModelMetadata = modelMetadata[defaultModel];
410
411
  const maxTokens = getMaxTokenLimit(defaultModelMetadata);
@@ -495,6 +496,7 @@ export function PromptEditorDrawer(props: PromptEditorDrawerProps) {
495
496
  }, [
496
497
  isOpen,
497
498
  promptQuery.data,
499
+ promptQuery.isLoading,
498
500
  promptId,
499
501
  props.initialLocalConfig,
500
502
  methods,
@@ -24,20 +24,21 @@ import { Checkbox } from "../ui/checkbox";
24
24
  import { HorizontalFormControl } from "../HorizontalFormControl";
25
25
 
26
26
  /**
27
- * Parameters shown in the dialog — only the ones we actually
28
- * render in LLMConfigPopover. The "Max Tokens" field above captures
29
- * the model's ceiling; this checkbox controls whether users can
30
- * configure max_tokens per-invocation in the LLM config popover.
27
+ * Optional sampling parameters the popover renders for this model.
28
+ *
29
+ * `max_tokens` is intentionally absent: every chat model accepts a
30
+ * per-invocation token ceiling, so the popover always renders that slider
31
+ * regardless of what's stored here. The numeric "Max Tokens" field elsewhere
32
+ * in this dialog captures the model's hard ceiling.
31
33
  */
32
34
  const DIALOG_PARAMETERS: { value: SupportedParameter; label: string }[] = [
33
35
  { value: "temperature", label: "Temperature" },
34
- { value: "max_tokens", label: "Max Tokens" },
35
36
  { value: "top_p", label: "Top P" },
36
37
  { value: "top_k", label: "Top K" },
37
38
  { value: "reasoning", label: "Reasoning" },
38
39
  ];
39
40
 
40
- const DEFAULT_PARAMETERS: SupportedParameter[] = ["temperature", "max_tokens"];
41
+ const DEFAULT_PARAMETERS: SupportedParameter[] = ["temperature"];
41
42
  const DEFAULT_MAX_TOKENS = 8192;
42
43
 
43
44
  const MULTIMODAL_LABELS: Record<MultimodalInput, string> = {