@bike4mind/cli 4.6.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +98 -0
  2. package/dist/{AgentHistoryStore--J3sgO_-.mjs → AgentHistoryStore-Bvmcy2kf.mjs} +23 -17
  3. package/dist/{ApiClient-CdO4Gamg.mjs → ApiClient-Yp2LPlX3.mjs} +3 -3
  4. package/dist/{BubblewrapRuntime-3jAbC60G.mjs → BubblewrapRuntime-OI4qFPNB.mjs} +2 -2
  5. package/dist/ConfigStore-Bo4od3Eu.mjs +2 -0
  6. package/dist/{ConfigStore-Dusy6glb.mjs → ConfigStore-CP1W86Ui.mjs} +100 -26
  7. package/dist/{Logger-C1Wj6xla.mjs → Logger-3RbeTZ9o.mjs} +1921 -319
  8. package/dist/{RemoteSkillSource-qTvRkaNA.mjs → RemoteSkillSource-D_F99yBR.mjs} +5 -0
  9. package/dist/{SandboxOrchestrator-CQwYq_uy.mjs → SandboxOrchestrator-lpxVEFO7.mjs} +1 -1
  10. package/dist/{SandboxRuntimeAdapter-BsT2iLky.mjs → SandboxRuntimeAdapter-C3xICJtQ.mjs} +2 -2
  11. package/dist/{SandboxRuntimeAdapter-Zg_0th7V.mjs → SandboxRuntimeAdapter-u6c_IrjP.mjs} +1 -1
  12. package/dist/{SeatbeltRuntime-C2DEkrjy.mjs → SeatbeltRuntime-Ccd_QbjX.mjs} +2 -2
  13. package/dist/{WorkItemsClient-CxNZaOmc.mjs → WorkItemsClient-D4sFGL9X.mjs} +1 -1
  14. package/dist/{buildToolSearch-DOb7mx6F.mjs → buildToolSearch-CqHKSLtG.mjs} +2 -2
  15. package/dist/commands/acpCommand.mjs +6 -6
  16. package/dist/commands/apiCommand.mjs +1 -1
  17. package/dist/commands/doctorCommand.mjs +2 -2
  18. package/dist/commands/envCommand.mjs +1 -1
  19. package/dist/commands/headlessCommand.mjs +7 -7
  20. package/dist/commands/hostCommand.mjs +1 -1
  21. package/dist/commands/mcpCommand.mjs +3 -3
  22. package/dist/commands/mirrorCommand.mjs +2 -2
  23. package/dist/commands/modelsCommand.mjs +5 -5
  24. package/dist/commands/pluginCommand.mjs +1 -1
  25. package/dist/commands/skillsCommand.mjs +4 -4
  26. package/dist/commands/updateCommand.mjs +2 -2
  27. package/dist/{dist-CbViwiS9.mjs → dist-BPhZ0dCz.mjs} +48 -11
  28. package/dist/{dist-Citbv0y0.mjs → dist-K7a9yOUb.mjs} +3 -3
  29. package/dist/{fit-CVWDiavv.mjs → fit-BOnDsgbk.mjs} +4 -4
  30. package/dist/{grepSearch-BgoOOwGe-B388GxRD.mjs → grepSearch-CLtEqT4j-BnKPtNWr.mjs} +2 -2
  31. package/dist/index.mjs +2493 -222
  32. package/dist/{modelServers-BaegigV-.mjs → modelServers-B7zI5XnO.mjs} +2 -2
  33. package/dist/{package-C9pfAdGF.mjs → package-WlxLVpUb.mjs} +1 -1
  34. package/dist/{serve-8wyGb8of.mjs → serve-DpsV0mag.mjs} +13 -9
  35. package/dist/store-Bpdo9Syo.mjs +2 -0
  36. package/dist/{store-BbvSi3KK.mjs → store-xeJRhBtO.mjs} +2 -0
  37. package/dist/{updateChecker-BAKb8KWP.mjs → updateChecker-Boq0RruU.mjs} +1 -1
  38. package/package.json +12 -12
  39. package/dist/ConfigStore-CausUCzY.mjs +0 -2
  40. package/dist/store-BYeE0shc.mjs +0 -2
@@ -244,15 +244,21 @@ const delegationPayloadSchema = z$1.looseObject({
244
244
  //#endregion
245
245
  //#region ../../b4m-core/common/dist/index.mjs
246
246
  const UNKNOWN_MODEL_ERROR_CODE = "unknown_model";
247
+ const MODEL_REQUIRES_SUBSCRIPTION_ERROR_CODE = "model_requires_subscription";
248
+ const FREE_QUEST_LIMIT_REACHED_ERROR_CODE = "free_quest_limit_reached";
247
249
  const BILLING_ORGANIZATION_MISMATCH_ERROR_CODE = "billing_organization_mismatch";
248
250
  const REQUEST_TIMEOUT_ERROR_CODE = "request_timeout";
249
251
  const OUTPUT_BUDGET_EXHAUSTED_ERROR_CODE = "output_budget_exhausted";
250
252
  const UPGRADE_REQUIRED_ERROR_CODE = "upgrade_required";
251
253
  const ACCOUNT_SUSPENDED_ERROR_CODE = "account_suspended";
252
254
  const RUN_NOT_FOUND_ERROR_CODE = "run_not_found";
255
+ const ORG_MODEL_NOT_ALLOWED_ERROR_CODE = "org_model_not_allowed";
256
+ const ORG_TOOL_NOT_ALLOWED_ERROR_CODE = "org_tool_not_allowed";
253
257
  const MCP_ACTION_REPLACED_ERROR_CODE = "action_replaced";
254
258
  const PENDING_ACTION_EXPIRED_ERROR_CODE = "action_expired";
255
259
  const PENDING_ACTION_ALREADY_RESOLVED_ERROR_CODE = "action_already_resolved";
260
+ const END_USER_ID_NOT_ALLOWED_ERROR_CODE = "end_user_id_not_allowed";
261
+ const INVALID_END_USER_ID_ERROR_CODE = "invalid_end_user_id";
256
262
  /** A recoverable tool refusal returned to the model so it can correct its request. */
257
263
  var ExpectedToolError = class extends Error {
258
264
  constructor(message) {
@@ -333,6 +339,19 @@ const RedactedStorageLimitErrorInfoSchema = StorageLimitErrorInfoSchema.pick({
333
339
  requested_bytes: z$1.never().optional()
334
340
  });
335
341
  z$1.union([StorageLimitErrorInfoSchema, RedactedStorageLimitErrorInfoSchema]);
342
+ var ForbiddenError = class extends HTTPError {
343
+ additionalInfo;
344
+ constructor(message, additionalInfo) {
345
+ super(403, message, additionalInfo);
346
+ this.additionalInfo = additionalInfo;
347
+ this.name = "ForbiddenError";
348
+ }
349
+ };
350
+ /**
351
+ * A 403 raised by a tool when the account lost AI access mid-turn. Terminal for the tool loop
352
+ * (`isTerminalToolError`, `@bike4mind/llm-adapters`): it ends the turn instead of going back to the model.
353
+ */
354
+ var AiAccessRefusedError = class extends ForbiddenError {};
336
355
  function isZodError(err) {
337
356
  return Boolean(err && (err instanceof ZodError || err.name === "ZodError"));
338
357
  }
@@ -2444,6 +2463,31 @@ const ADMIN_AUDIT_CATALOGUE = {
2444
2463
  severity: "critical",
2445
2464
  write: "bestEffort"
2446
2465
  },
2466
+ "access_review.confirmed": {
2467
+ category: "access",
2468
+ severity: "notice",
2469
+ write: "strict"
2470
+ },
2471
+ "access_review.revoked": {
2472
+ category: "access",
2473
+ severity: "notice",
2474
+ write: "strict"
2475
+ },
2476
+ "access_review.completed": {
2477
+ category: "access",
2478
+ severity: "notice",
2479
+ write: "strict"
2480
+ },
2481
+ "access_review.denied": {
2482
+ category: "access",
2483
+ severity: "critical",
2484
+ write: "bestEffort"
2485
+ },
2486
+ "access_review.exported": {
2487
+ category: "access",
2488
+ severity: "notice",
2489
+ write: "bestEffort"
2490
+ },
2447
2491
  "user.impersonation.started": {
2448
2492
  category: "access",
2449
2493
  severity: "critical",
@@ -2609,6 +2653,11 @@ const ADMIN_AUDIT_CATALOGUE = {
2609
2653
  severity: "info",
2610
2654
  write: "strict"
2611
2655
  },
2656
+ "org.segment.changed": {
2657
+ category: "org",
2658
+ severity: "notice",
2659
+ write: "strict"
2660
+ },
2612
2661
  "org.admins.updated": {
2613
2662
  category: "org",
2614
2663
  severity: "notice",
@@ -2684,6 +2733,11 @@ const ADMIN_AUDIT_CATALOGUE = {
2684
2733
  severity: "notice",
2685
2734
  write: "bestEffort"
2686
2735
  },
2736
+ "org.model_policy.updated": {
2737
+ category: "org",
2738
+ severity: "notice",
2739
+ write: "bestEffort"
2740
+ },
2687
2741
  "org.slack_channel_api_posting.updated": {
2688
2742
  category: "org",
2689
2743
  severity: "notice",
@@ -2739,6 +2793,81 @@ const ADMIN_AUDIT_CATALOGUE = {
2739
2793
  severity: "notice",
2740
2794
  write: "strict"
2741
2795
  },
2796
+ "org.settings.updated": {
2797
+ category: "org",
2798
+ severity: "notice",
2799
+ write: "bestEffort"
2800
+ },
2801
+ "org.viewed": {
2802
+ category: "org",
2803
+ severity: "info",
2804
+ write: "strict"
2805
+ },
2806
+ "org.logo.updated": {
2807
+ category: "org",
2808
+ severity: "info",
2809
+ write: "bestEffort"
2810
+ },
2811
+ "org.deleted": {
2812
+ category: "org",
2813
+ severity: "notice",
2814
+ write: "strict"
2815
+ },
2816
+ "org.slack.connected": {
2817
+ category: "org",
2818
+ severity: "notice",
2819
+ write: "bestEffort"
2820
+ },
2821
+ "org.webhook.created": {
2822
+ category: "org",
2823
+ severity: "notice",
2824
+ write: "bestEffort"
2825
+ },
2826
+ "org.webhook.updated": {
2827
+ category: "org",
2828
+ severity: "notice",
2829
+ write: "bestEffort"
2830
+ },
2831
+ "org.webhook.deleted": {
2832
+ category: "org",
2833
+ severity: "notice",
2834
+ write: "bestEffort"
2835
+ },
2836
+ "org.webhook.secret_rotated": {
2837
+ category: "access",
2838
+ severity: "notice",
2839
+ write: "bestEffort"
2840
+ },
2841
+ "org.webhook.deliveries_replayed": {
2842
+ category: "org",
2843
+ severity: "info",
2844
+ write: "bestEffort"
2845
+ },
2846
+ "org.github_connection.created": {
2847
+ category: "org",
2848
+ severity: "notice",
2849
+ write: "bestEffort"
2850
+ },
2851
+ "org.github_connection.updated": {
2852
+ category: "org",
2853
+ severity: "notice",
2854
+ write: "bestEffort"
2855
+ },
2856
+ "org.github_connection.deleted": {
2857
+ category: "org",
2858
+ severity: "notice",
2859
+ write: "bestEffort"
2860
+ },
2861
+ "org.github_connection.key_rotated": {
2862
+ category: "access",
2863
+ severity: "notice",
2864
+ write: "bestEffort"
2865
+ },
2866
+ "org.github_connection.pat_rotated": {
2867
+ category: "access",
2868
+ severity: "notice",
2869
+ write: "bestEffort"
2870
+ },
2742
2871
  "settings.admin_settings.updated": {
2743
2872
  category: "settings",
2744
2873
  severity: "notice",
@@ -2854,6 +2983,11 @@ const ADMIN_AUDIT_CATALOGUE = {
2854
2983
  severity: "notice",
2855
2984
  write: "strict"
2856
2985
  },
2986
+ "user.segment.changed": {
2987
+ category: "account",
2988
+ severity: "notice",
2989
+ write: "strict"
2990
+ },
2857
2991
  "user.email.unverified": {
2858
2992
  category: "identity",
2859
2993
  severity: "info",
@@ -3212,6 +3346,11 @@ const ADMIN_AUDIT_CATALOGUE = {
3212
3346
  severity: "critical",
3213
3347
  write: "strict"
3214
3348
  },
3349
+ "user.api_key.end_user_id_updated": {
3350
+ category: "access",
3351
+ severity: "critical",
3352
+ write: "strict"
3353
+ },
3215
3354
  "user.api_keys.revoked_all": {
3216
3355
  category: "access",
3217
3356
  severity: "notice",
@@ -3297,6 +3436,16 @@ const ADMIN_AUDIT_CATALOGUE = {
3297
3436
  severity: "notice",
3298
3437
  write: "bestEffort"
3299
3438
  },
3439
+ "ops.dlq.triage.dismissed": {
3440
+ category: "support",
3441
+ severity: "notice",
3442
+ write: "strict"
3443
+ },
3444
+ "ops.dlq.triage.accepted": {
3445
+ category: "support",
3446
+ severity: "notice",
3447
+ write: "strict"
3448
+ },
3300
3449
  "ops.agent_executions.cleaned_up": {
3301
3450
  category: "support",
3302
3451
  severity: "notice",
@@ -3647,6 +3796,11 @@ const ADMIN_AUDIT_CATALOGUE = {
3647
3796
  severity: "info",
3648
3797
  write: "bestEffort"
3649
3798
  },
3799
+ "security.ai_assessment.accepted": {
3800
+ category: "access",
3801
+ severity: "info",
3802
+ write: "strict"
3803
+ },
3650
3804
  "abuse.eval_set.created": {
3651
3805
  category: "access",
3652
3806
  severity: "info",
@@ -3697,6 +3851,11 @@ const ADMIN_AUDIT_CATALOGUE = {
3697
3851
  severity: "notice",
3698
3852
  write: "strict"
3699
3853
  },
3854
+ "moderation.incident.escalated": {
3855
+ category: "support",
3856
+ severity: "notice",
3857
+ write: "strict"
3858
+ },
3700
3859
  "moderation.published_artifact.taken_down": {
3701
3860
  category: "support",
3702
3861
  severity: "notice",
@@ -3821,6 +3980,21 @@ const ADMIN_AUDIT_CATALOGUE = {
3821
3980
  category: "access",
3822
3981
  severity: "critical",
3823
3982
  write: "bestEffort"
3983
+ },
3984
+ "admin.role.created": {
3985
+ category: "access",
3986
+ severity: "notice",
3987
+ write: "strict"
3988
+ },
3989
+ "admin.role.updated": {
3990
+ category: "access",
3991
+ severity: "critical",
3992
+ write: "strict"
3993
+ },
3994
+ "admin.role.deleted": {
3995
+ category: "access",
3996
+ severity: "notice",
3997
+ write: "strict"
3824
3998
  }
3825
3999
  };
3826
4000
  Object.keys(ADMIN_AUDIT_CATALOGUE).filter((action) => "escalatesAboveGrantThreshold" in ADMIN_AUDIT_CATALOGUE[action]);
@@ -3897,7 +4071,8 @@ const SreGateConfigSchema = z$1.object({
3897
4071
  enabled: z$1.boolean().default(SRE_GATE_DEFAULTS.enabled),
3898
4072
  autoThreshold: z$1.number().min(0).max(100).default(SRE_GATE_DEFAULTS.autoThreshold),
3899
4073
  askThreshold: z$1.number().min(0).max(100).default(SRE_GATE_DEFAULTS.askThreshold),
3900
- approvalTimeoutHours: z$1.number().min(1).default(SRE_GATE_DEFAULTS.approvalTimeoutHours)
4074
+ approvalTimeoutHours: z$1.number().min(1).default(SRE_GATE_DEFAULTS.approvalTimeoutHours),
4075
+ autoDispatchSources: z$1.array(z$1.nativeEnum(SreSourceType)).default([])
3901
4076
  }).refine((data) => data.autoThreshold >= data.askThreshold, {
3902
4077
  message: "autoThreshold must be >= askThreshold",
3903
4078
  path: ["autoThreshold"]
@@ -3947,11 +4122,23 @@ const SreRepoConfigSchema = z$1.object({
3947
4122
  callbackToken: z$1.string().default(""),
3948
4123
  /** Human-in-the-loop approval gates */
3949
4124
  gates: z$1.object({
3950
- sentinelToDiagnostician: SreGateConfigSchema.default({ ...SRE_GATE_DEFAULTS }),
3951
- diagnosticianToSurgeon: SreGateConfigSchema.default({ ...SRE_GATE_DEFAULTS })
4125
+ sentinelToDiagnostician: SreGateConfigSchema.default({
4126
+ ...SRE_GATE_DEFAULTS,
4127
+ autoDispatchSources: []
4128
+ }),
4129
+ diagnosticianToSurgeon: SreGateConfigSchema.default({
4130
+ ...SRE_GATE_DEFAULTS,
4131
+ autoDispatchSources: []
4132
+ })
3952
4133
  }).default({
3953
- sentinelToDiagnostician: { ...SRE_GATE_DEFAULTS },
3954
- diagnosticianToSurgeon: { ...SRE_GATE_DEFAULTS }
4134
+ sentinelToDiagnostician: {
4135
+ ...SRE_GATE_DEFAULTS,
4136
+ autoDispatchSources: []
4137
+ },
4138
+ diagnosticianToSurgeon: {
4139
+ ...SRE_GATE_DEFAULTS,
4140
+ autoDispatchSources: []
4141
+ }
3955
4142
  }),
3956
4143
  /** Circuit breaker */
3957
4144
  circuitBreaker: z$1.object({
@@ -4120,6 +4307,9 @@ const SreRevisionRequestSchema = z$1.object({
4120
4307
  ciFailureOutput: z$1.string().optional()
4121
4308
  });
4122
4309
  z$1.discriminatedUnion("jobType", [SreEventPayloadSchema.extend({ jobType: z$1.literal("analysis") }), SreRevisionRequestSchema.extend({ jobType: z$1.literal("revision") })]);
4310
+ /** An `owner/name` GitHub repository; also used by the worker's repository check. */
4311
+ const SECOPS_TRIAGE_REPO_PATTERN = /^[\w.-]+\/[\w.-]+$/;
4312
+ const MAX_ISSUES_MESSAGE = "Max issues per scan must be between 1 and 100";
4123
4313
  /**
4124
4314
  * Configuration schema for the SecOps Triage feature.
4125
4315
  *
@@ -4132,7 +4322,7 @@ const SecopsTriageConfigSchema = z$1.object({
4132
4322
  /** Master kill switch */
4133
4323
  enabled: z$1.boolean().default(false),
4134
4324
  /** GitHub repository to create issues in (e.g. 'owner/repo') */
4135
- githubRepo: z$1.string().default("MillionOnMars/lumina5"),
4325
+ githubRepo: z$1.string().default(""),
4136
4326
  /** Minimum ZAP severity level that triggers issue creation */
4137
4327
  severityThreshold: z$1.enum(["critical", "high"]).default("high"),
4138
4328
  /** Map ZAP severity levels to GitHub issue priority labels */
@@ -4144,7 +4334,7 @@ const SecopsTriageConfigSchema = z$1.object({
4144
4334
  high: "P1"
4145
4335
  }),
4146
4336
  /** Maximum number of issues to create per scan (sorted by severity, highest first) */
4147
- maxIssuesPerScan: z$1.number().min(1).max(100).default(20),
4337
+ maxIssuesPerScan: z$1.number({ error: MAX_ISSUES_MESSAGE }).min(1, MAX_ISSUES_MESSAGE).max(100, MAX_ISSUES_MESSAGE).default(20),
4148
4338
  /** Slack workspace ID to use for posting (must match an active workspace in Admin -> Slack Workspaces). Falls back to first active workspace if not set. */
4149
4339
  slackWorkspaceId: z$1.string().optional(),
4150
4340
  /** Slack channel ID to post triage summary to (optional) */
@@ -4156,8 +4346,11 @@ const SecopsTriageConfigSchema = z$1.object({
4156
4346
  /** Log actions without creating real GitHub issues or posting to Slack */
4157
4347
  dryRun: z$1.boolean().default(false)
4158
4348
  }).refine((data) => !data.llmEnrichment || !!data.modelId, {
4159
- message: "modelId is required when llmEnrichment is enabled",
4349
+ message: "A model must be selected when LLM enrichment is enabled",
4160
4350
  path: ["modelId"]
4351
+ }).refine((data) => !data.enabled || SECOPS_TRIAGE_REPO_PATTERN.test(data.githubRepo), {
4352
+ message: "A repository in owner/name form is required when SecOps triage is enabled",
4353
+ path: ["githubRepo"]
4161
4354
  });
4162
4355
  const MODAL_MEDIA_HOST_SUFFIXES = [".amazonaws.com", ".cloudfront.net"];
4163
4356
  const MODAL_MEDIA_URL_MAX_LENGTH = 2048;
@@ -4596,6 +4789,7 @@ z$1.enum([
4596
4789
  "BedrockGuardrailVersion",
4597
4790
  "ImageModerationEnabled",
4598
4791
  "ImageModerationReviewerEmails",
4792
+ "ImageModerationEscalationEmails",
4599
4793
  "tagLineMain",
4600
4794
  "tagLineSub",
4601
4795
  "defaultTags",
@@ -4658,6 +4852,7 @@ z$1.enum([
4658
4852
  "EnableStudioCreateV2",
4659
4853
  "EnableStudioImage",
4660
4854
  "EnableStudioProductions",
4855
+ "StudioProductionsAudience",
4661
4856
  "VectorThreshold",
4662
4857
  "bflApiKey",
4663
4858
  "EnableMCPServer",
@@ -4777,6 +4972,10 @@ z$1.enum([
4777
4972
  "spendMonitorTrustedAccountIds",
4778
4973
  "spendMonitorTrustedAccountSpikeFloorCredits",
4779
4974
  "spendMonitorTrustedAccountCeilingCredits",
4975
+ "spendMonitorMarginEnabled",
4976
+ "spendMonitorMarginMinRatio",
4977
+ "spendMonitorMarginWindowHours",
4978
+ "spendMonitorMarginCostFloorUsd",
4780
4979
  "youngAccountSpendPageUsdPerHour",
4781
4980
  "youngAccountSpendWarnUsdPerHour",
4782
4981
  "freeTierDailySystemCostCapUsd",
@@ -4910,7 +5109,6 @@ z$1.enum([
4910
5109
  "EnableHelpChat",
4911
5110
  "EnableCoreTutorials",
4912
5111
  "EnableBmPi",
4913
- "EnableBmPiDefault",
4914
5112
  "EnableBmPiJira",
4915
5113
  "EnableOptiHashi",
4916
5114
  "EnableComputeSubmission",
@@ -4967,6 +5165,9 @@ z$1.enum([
4967
5165
  "agentVideoClipsPerRun",
4968
5166
  "musicGeneration",
4969
5167
  "agentMusicTracksPerRun",
5168
+ "agentImagesPerRun",
5169
+ "agentSpeechClipsPerRun",
5170
+ "agentSoundEffectsPerRun",
4970
5171
  "enableModelDiscovery",
4971
5172
  "modelDiscoveryMode",
4972
5173
  "modelDiscoveryAutoEnable",
@@ -5154,6 +5355,8 @@ function isCalendarDate(value) {
5154
5355
  const date = /* @__PURE__ */ new Date(`${value}T00:00:00.000Z`);
5155
5356
  return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
5156
5357
  }
5358
+ /** Who Studio Productions opens to once enabled: admins only (the preview), or admins, developers and paid plans. */
5359
+ const STUDIO_PRODUCTIONS_AUDIENCES = ["admins", "paid"];
5157
5360
  function makeStringSetting(config) {
5158
5361
  return {
5159
5362
  ...config,
@@ -5512,7 +5715,15 @@ const AdminAiConfigSchema = z$1.object({
5512
5715
  feedbackTriage: decisionFeatureConfig("Feedback triage"),
5513
5716
  dlqTriage: textFeatureConfig("DLQ triage"),
5514
5717
  morningBrief: textFeatureConfig("Morning brief")
5515
- }).prefault({}).meta({ title: "Features" })
5718
+ }).prefault({}).meta({ title: "Features" }),
5719
+ dlqQueueModes: z$1.record(z$1.string(), z$1.enum([
5720
+ "off",
5721
+ "recommend",
5722
+ "act"
5723
+ ])).prefault({}).meta({
5724
+ title: "DLQ queue modes",
5725
+ description: "Queue label to autoTriage mode. Unlisted queues default to recommend. DLQ triage is recommend-only even when act is selected; replay has no real Undo. The master Enabled switch stops triage."
5726
+ })
5516
5727
  });
5517
5728
  const storedFeedbackDecisionModel = z$1.union([z$1.enum(DECISION_MODEL_IDS), supportedChatModels.transform(() => null)]).nullable().prefault(null);
5518
5729
  const storedAdminAiConfig = AdminAiConfigSchema.extend({ features: AdminAiConfigSchema.shape.features.unwrap().extend({ feedbackTriage: decisionFeatureConfig("Feedback triage").unwrap().extend({
@@ -5917,6 +6128,7 @@ z$1.object({
5917
6128
  regressionLookbackDays: z$1.number().min(LT.regressionLookbackDays.min).max(LT.regressionLookbackDays.max).default(LT.regressionLookbackDays.default),
5918
6129
  regressionGracePeriodHours: z$1.number().min(LT.regressionGracePeriodHours.min).max(LT.regressionGracePeriodHours.max).default(LT.regressionGracePeriodHours.default),
5919
6130
  autoCreateIssues: z$1.boolean().default(false),
6131
+ approverIds: z$1.string().default(""),
5920
6132
  promptTemplate: z$1.string().min(LT.promptTemplate.min, `Prompt template must be at least ${LT.promptTemplate.min} characters`).max(LT.promptTemplate.max, `Prompt template cannot exceed ${LT.promptTemplate.max.toLocaleString()} characters`).trim().optional(),
5921
6133
  lastRunAt: z$1.iso.datetime().optional(),
5922
6134
  lastRunDate: z$1.string().optional(),
@@ -6590,10 +6802,6 @@ const API_SERVICE_GROUPS = {
6590
6802
  key: "EnableBmPi",
6591
6803
  order: 30
6592
6804
  },
6593
- {
6594
- key: "EnableBmPiDefault",
6595
- order: 31
6596
- },
6597
6805
  {
6598
6806
  key: "EnableBmPiJira",
6599
6807
  order: 32
@@ -6801,6 +7009,10 @@ const API_SERVICE_GROUPS = {
6801
7009
  {
6802
7010
  key: "EnableStudioProductions",
6803
7011
  order: 302
7012
+ },
7013
+ {
7014
+ key: "StudioProductionsAudience",
7015
+ order: 303
6804
7016
  }
6805
7017
  ]
6806
7018
  },
@@ -6960,6 +7172,22 @@ const API_SERVICE_GROUPS = {
6960
7172
  key: "spendMonitorTrustedAccountCeilingCredits",
6961
7173
  order: 19.494
6962
7174
  },
7175
+ {
7176
+ key: "spendMonitorMarginEnabled",
7177
+ order: 19.4941
7178
+ },
7179
+ {
7180
+ key: "spendMonitorMarginMinRatio",
7181
+ order: 19.4942
7182
+ },
7183
+ {
7184
+ key: "spendMonitorMarginWindowHours",
7185
+ order: 19.4943
7186
+ },
7187
+ {
7188
+ key: "spendMonitorMarginCostFloorUsd",
7189
+ order: 19.4944
7190
+ },
6963
7191
  {
6964
7192
  key: "youngAccountSpendPageUsdPerHour",
6965
7193
  order: 19.495
@@ -8332,6 +8560,14 @@ const settingsMap = {
8332
8560
  category: "AI Moderation",
8333
8561
  schema: z$1.array(z$1.string())
8334
8562
  }),
8563
+ ImageModerationEscalationEmails: makeObjectSetting({
8564
+ key: "ImageModerationEscalationEmails",
8565
+ name: "Image Moderation Escalation Emails",
8566
+ defaultValue: [],
8567
+ description: "Email addresses for the second review step, one per line: alerted when an image moderation incident is escalated, by a reviewer or automatically when it waits too long for a verdict. The email carries incident metadata and an admin link only, never the image or user content. Empty sends no escalation email.",
8568
+ category: "AI Moderation",
8569
+ schema: z$1.array(z$1.string())
8570
+ }),
8335
8571
  SkillMarketHighRiskTools: makeStringSetting({
8336
8572
  key: "SkillMarketHighRiskTools",
8337
8573
  name: "Skill Market High-Risk Tools",
@@ -10258,6 +10494,46 @@ const settingsMap = {
10258
10494
  group: API_SERVICE_GROUPS.CREDITS.id,
10259
10495
  category: "SecOps"
10260
10496
  }),
10497
+ spendMonitorMarginEnabled: makeBooleanSetting({
10498
+ key: "spendMonitorMarginEnabled",
10499
+ name: "Spend Monitor: Model Margin Check",
10500
+ defaultValue: true,
10501
+ description: "Once a day, shortly after 00:00 UTC and only while Spend Monitor is enabled, flag any model whose credits charged, converted to USD at the lowest per-credit price, fall below its provider cost over the margin window. Posts follow \"Post Alerts to Slack\".",
10502
+ group: API_SERVICE_GROUPS.CREDITS.id,
10503
+ category: "SecOps"
10504
+ }),
10505
+ spendMonitorMarginMinRatio: makeNumberSetting({
10506
+ key: "spendMonitorMarginMinRatio",
10507
+ name: "Spend Monitor: Model Margin Min Ratio",
10508
+ defaultValue: 1,
10509
+ int: false,
10510
+ min: .01,
10511
+ max: 10,
10512
+ description: "Ratio of charged USD to provider cost. A model below it is flagged by the margin check. 1 (default) flags only models charged less than they cost; raise it to flag thin margins too.",
10513
+ group: API_SERVICE_GROUPS.CREDITS.id,
10514
+ category: "SecOps"
10515
+ }),
10516
+ spendMonitorMarginWindowHours: makeNumberSetting({
10517
+ key: "spendMonitorMarginWindowHours",
10518
+ name: "Spend Monitor: Model Margin Window",
10519
+ defaultValue: 24,
10520
+ int: true,
10521
+ min: 1,
10522
+ max: 168,
10523
+ description: "Hours of spend the daily margin check sums per model. 1 to 168.",
10524
+ group: API_SERVICE_GROUPS.CREDITS.id,
10525
+ category: "SecOps"
10526
+ }),
10527
+ spendMonitorMarginCostFloorUsd: makeNumberSetting({
10528
+ key: "spendMonitorMarginCostFloorUsd",
10529
+ name: "Spend Monitor: Model Margin Cost Floor",
10530
+ defaultValue: 5,
10531
+ int: true,
10532
+ min: 1,
10533
+ description: "USD of provider cost a model needs in the margin window before the margin check can flag it, so low-volume models do not alert. Minimum 1.",
10534
+ group: API_SERVICE_GROUPS.CREDITS.id,
10535
+ category: "SecOps"
10536
+ }),
10261
10537
  youngAccountSpendPageUsdPerHour: makeNumberSetting({
10262
10538
  key: "youngAccountSpendPageUsdPerHour",
10263
10539
  name: "Young-Account Spend Alarm: Page Ceiling (USD)",
@@ -10952,7 +11228,7 @@ const settingsMap = {
10952
11228
  key: "EnableStudioCreateV2",
10953
11229
  name: "Enable Studio Create v2",
10954
11230
  defaultValue: false,
10955
- description: "Admin-only preview of the restructured Studio Create area. Non-admins never see it, whatever this is set to.",
11231
+ description: "The restructured Studio Create area, for every user. Off, everyone gets the legacy Studio tabs; this is the kill switch.",
10956
11232
  category: "Experimental",
10957
11233
  group: API_SERVICE_GROUPS.EXPERIMENTAL.id,
10958
11234
  order: 300
@@ -10961,7 +11237,7 @@ const settingsMap = {
10961
11237
  key: "EnableStudioImage",
10962
11238
  name: "Enable Image in Studio",
10963
11239
  defaultValue: false,
10964
- description: "Admin-only preview of the Image tab in Studio. Non-admins never see it, whatever this is set to.",
11240
+ description: "The Image medium in Studio Create, for every user. Needs Enable Studio Create v2; off, the Image medium is hidden.",
10965
11241
  category: "Experimental",
10966
11242
  group: API_SERVICE_GROUPS.EXPERIMENTAL.id,
10967
11243
  order: 301,
@@ -10971,12 +11247,23 @@ const settingsMap = {
10971
11247
  key: "EnableStudioProductions",
10972
11248
  name: "Enable Studio Productions",
10973
11249
  defaultValue: false,
10974
- description: "Admin-only preview of Studio Productions (assembling many assets into one piece). Non-admins never see it, whatever this is set to.",
11250
+ description: "Studio Productions (assembling many assets into one piece). Off, nobody sees it. On, who it opens to is set by Studio Productions Audience.",
10975
11251
  category: "Experimental",
10976
11252
  group: API_SERVICE_GROUPS.EXPERIMENTAL.id,
10977
11253
  order: 302,
10978
11254
  dependsOn: "EnableStudioCreateV2"
10979
11255
  }),
11256
+ StudioProductionsAudience: makeStringSetting({
11257
+ key: "StudioProductionsAudience",
11258
+ name: "Studio Productions Audience",
11259
+ defaultValue: "admins",
11260
+ description: "Who Studio Productions opens to once enabled. 'admins' is the preview. 'paid' opens it to admins, developer-tagged users and users on a paid plan; free users see an upgrade prompt.",
11261
+ options: [...STUDIO_PRODUCTIONS_AUDIENCES],
11262
+ category: "Experimental",
11263
+ group: API_SERVICE_GROUPS.EXPERIMENTAL.id,
11264
+ order: 303,
11265
+ dependsOn: "EnableStudioProductions"
11266
+ }),
10980
11267
  EnablePotionQuest: makeBooleanSetting({
10981
11268
  key: "EnablePotionQuest",
10982
11269
  name: "Enable PotionQuest Tools",
@@ -12018,16 +12305,6 @@ const settingsMap = {
12018
12305
  group: API_SERVICE_GROUPS.EXPERIMENTAL.id,
12019
12306
  order: 30
12020
12307
  }),
12021
- EnableBmPiDefault: makeBooleanSetting({
12022
- key: "EnableBmPiDefault",
12023
- name: "B4M Pi: On by default for users",
12024
- defaultValue: false,
12025
- description: "When enabled, B4M Pi is active for users who have never explicitly toggled it.",
12026
- category: "Experimental",
12027
- group: API_SERVICE_GROUPS.EXPERIMENTAL.id,
12028
- order: 31,
12029
- dependsOn: "EnableBmPi"
12030
- }),
12031
12308
  EnableBmPiJira: makeBooleanSetting({
12032
12309
  key: "EnableBmPiJira",
12033
12310
  name: "Enable B4M Pi — Jira Integration",
@@ -12242,7 +12519,7 @@ const settingsMap = {
12242
12519
  key: "secopsTriageConfig",
12243
12520
  name: "SecOps Triage Config",
12244
12521
  defaultValue: SecopsTriageConfigSchema.parse({}),
12245
- description: "Configuration for SecOps Triage — auto-creates GitHub issues for critical/high OWASP ZAP scan findings via the b4m-prod GitHub App. Disabled by default.",
12522
+ description: "Configuration for SecOps triage: files a GitHub issue for each critical or high finding reported by a security scan through the system GitHub connection, and closes it when the finding is gone. Disabled by default.",
12246
12523
  category: "SecOps",
12247
12524
  order: 131,
12248
12525
  schema: SecopsTriageConfigSchema
@@ -12312,6 +12589,39 @@ const settingsMap = {
12312
12589
  order: 148,
12313
12590
  scope: { settableAt: ["organization"] }
12314
12591
  }),
12592
+ agentImagesPerRun: makeNumberSetting({
12593
+ key: "agentImagesPerRun",
12594
+ name: "Agent Images Per Run",
12595
+ defaultValue: 12,
12596
+ min: 1,
12597
+ int: true,
12598
+ description: "Most images image_generation and edit_image may start as jobs in one agent-mode run, counted across the run and all of its subagents. Each image still holds and settles its own credits.",
12599
+ category: "AI",
12600
+ order: 149,
12601
+ scope: { settableAt: ["organization"] }
12602
+ }),
12603
+ agentSpeechClipsPerRun: makeNumberSetting({
12604
+ key: "agentSpeechClipsPerRun",
12605
+ name: "Agent Speech Clips Per Run",
12606
+ defaultValue: 10,
12607
+ min: 0,
12608
+ int: true,
12609
+ description: "Most audio_generation speech clips one agent-mode run may start, counted across the run and all of its subagents. 0 refuses speech in agent mode. Each clip still holds and settles its own credits.",
12610
+ category: "AI",
12611
+ order: 150,
12612
+ scope: { settableAt: ["organization"] }
12613
+ }),
12614
+ agentSoundEffectsPerRun: makeNumberSetting({
12615
+ key: "agentSoundEffectsPerRun",
12616
+ name: "Agent Sound Effects Per Run",
12617
+ defaultValue: 10,
12618
+ min: 0,
12619
+ int: true,
12620
+ description: "Most audio_generation sound effects one agent-mode run may start, counted across the run and all of its subagents. 0 refuses sound effects in agent mode. Each effect still holds and settles its own credits.",
12621
+ category: "AI",
12622
+ order: 151,
12623
+ scope: { settableAt: ["organization"] }
12624
+ }),
12315
12625
  enableModelDiscovery: makeBooleanSetting({
12316
12626
  key: "enableModelDiscovery",
12317
12627
  name: "Enable Model Discovery",
@@ -12630,6 +12940,14 @@ const b4mLLMTools = z$1.enum([
12630
12940
  "bob_panel_read",
12631
12941
  "skill"
12632
12942
  ]);
12943
+ /**
12944
+ * The data-lake tools that write (make a lake, persist a file into one). A route withholds these
12945
+ * from an API key without datalake:write (dataLakeToolsDeniedFor in the client's
12946
+ * dataLakeScopes.ts).
12947
+ */
12948
+ const DATA_LAKE_WRITE_TOOL_NAMES = ["create_data_lake", "save_content_to_data_lake"];
12949
+ /** Every data-lake tool - offered, trimmed and paired together (see resolveEnabledTools in services). */
12950
+ const DATA_LAKE_TOOL_NAMES = [...["list_my_data_lakes"], ...DATA_LAKE_WRITE_TOOL_NAMES];
12633
12951
  b4mLLMTools.options.map((tool) => tool);
12634
12952
  /**
12635
12953
  * Recharts chart types.
@@ -13053,7 +13371,11 @@ z$1.object({
13053
13371
  * than a second vocabulary - a code added here that is not in `API_ERROR_CODES`
13054
13372
  * fails the build.
13055
13373
  */
13056
- const QUEST_ERROR_CODES = ["insufficient_credits", "spend_cap_exceeded"];
13374
+ const QUEST_ERROR_CODES = [
13375
+ "insufficient_credits",
13376
+ "spend_cap_exceeded",
13377
+ "free_quest_limit_reached"
13378
+ ];
13057
13379
  /**
13058
13380
  * Single source of truth for `IChatHistoryItem.type` / quest `type`. Restated by hand in
13059
13381
  * `schemas/actions.ts`, `schemas/chat.ts`, and `notebookExportService/types.ts` before this
@@ -13310,6 +13632,15 @@ let ApiKeyScope = /* @__PURE__ */ function(ApiKeyScope) {
13310
13632
  * revocation, so it is granted only by ticking it.
13311
13633
  */
13312
13634
  ApiKeyScope["API_KEYS_MANAGE"] = "api-keys:manage";
13635
+ /**
13636
+ * Lets the key send `end_user_id` on `POST /api/ai/v1/completions` and `POST /api/ai/tts`, so a
13637
+ * product serving many end users through one key reaches the model provider as one identifier per
13638
+ * end user rather than one for the whole account (toPlatformEndUserProviderId in
13639
+ * @bike4mind/llm-adapters). Admin-provisioned only: it changes how the provider attributes the
13640
+ * key's traffic, so the owner cannot tick it. It authorizes no route by itself, and the key still
13641
+ * needs `ai:chat`/`ai:generate`.
13642
+ */
13643
+ ApiKeyScope["AI_END_USER_ID"] = "ai:end-user-id";
13313
13644
  return ApiKeyScope;
13314
13645
  }({});
13315
13646
  new Set(Object.values(ApiKeyScope));
@@ -13348,6 +13679,8 @@ const UNDOCUMENTED_API_KEY_SCOPES = [
13348
13679
  "optihashi:compute"
13349
13680
  ];
13350
13681
  Object.values(ApiKeyScope).filter((scope) => !UNDOCUMENTED_API_KEY_SCOPES.includes(scope));
13682
+ /** Whether a key owner held paid standing when an exchange key was minted. */
13683
+ const PAYER_STANDINGS = ["paid", "unpaid"];
13351
13684
  const API_KEY_RATE_LIMIT_MAX_PER_MINUTE = 1e4;
13352
13685
  const API_KEY_RATE_LIMIT_MAX_PER_DAY = 1e6;
13353
13686
  Object.freeze({
@@ -13428,6 +13761,10 @@ const BaseCreditTransaction = z$1.object({
13428
13761
  * purchases/refunds) may not have it set. See CompletionSource in analytics.ts.
13429
13762
  */
13430
13763
  source: z$1.enum(COMPLETION_SOURCES).optional(),
13764
+ /** Connected app whose exchange key made this charge; stamped by the ledger repository. */
13765
+ oauthClientId: z$1.string().optional(),
13766
+ /** Payer's standing when the exchange key was minted; set only when the key's owner paid the charge. */
13767
+ payerStanding: z$1.enum(PAYER_STANDINGS).optional(),
13431
13768
  createdAt: z$1.date(),
13432
13769
  updatedAt: z$1.date()
13433
13770
  });
@@ -13943,6 +14280,19 @@ z$1.object({
13943
14280
  createdAt: z$1.date(),
13944
14281
  updatedAt: z$1.date()
13945
14282
  });
14283
+ z$1.enum([
14284
+ "internal",
14285
+ "partner",
14286
+ "customer"
14287
+ ]);
14288
+ z$1.object({
14289
+ version: z$1.literal(1),
14290
+ generatedAt: z$1.string().datetime(),
14291
+ rows: z$1.array(z$1.object({
14292
+ modelId: z$1.string(),
14293
+ pricing: z$1.record(z$1.string().regex(/^\d+$/), ModelPriceTier)
14294
+ }))
14295
+ });
13946
14296
  z$1.object({
13947
14297
  id: z$1.string().optional(),
13948
14298
  /** UTC month, matching monthlyCogsByProvider's group key. */
@@ -14391,13 +14741,22 @@ z$1.object({
14391
14741
  onBehalfOfUserId: z$1.string().optional()
14392
14742
  }).optional()
14393
14743
  });
14744
+ /** `compose` renders a Scene (a video with a music track muxed in) from files the caller already has. */
14394
14745
  const GENERATION_JOB_KINDS = [
14746
+ "video",
14747
+ "music",
14748
+ "image",
14749
+ "speech",
14750
+ "sound_effect",
14751
+ "compose"
14752
+ ];
14753
+ /** The kinds a chat message can start; every generation kind can now land on a quest. */
14754
+ const QUEST_GENERATION_JOB_KINDS = [
14395
14755
  "video",
14396
14756
  "music",
14397
14757
  "image"
14398
14758
  ];
14399
- /** The kinds a chat message can start. An image job is started from Studio only, so it never lands on a quest. */
14400
- const QUEST_GENERATION_JOB_KINDS = ["video", "music"];
14759
+ [...QUEST_GENERATION_JOB_KINDS];
14401
14760
  const GENERATION_JOB_STATES = [
14402
14761
  "pending",
14403
14762
  "running",
@@ -14467,7 +14826,8 @@ const AuditTargetSchema = z$1.object({
14467
14826
  "oauthClient",
14468
14827
  "apiKey",
14469
14828
  "system",
14470
- "curatedCatalog"
14829
+ "curatedCatalog",
14830
+ "adminRole"
14471
14831
  ]),
14472
14832
  id: z$1.string(),
14473
14833
  displayName: z$1.string()
@@ -14554,6 +14914,12 @@ z$1.object({
14554
14914
  note: z$1.string().trim().max(500).optional()
14555
14915
  });
14556
14916
  z$1.object({ entryIds: z$1.array(AuditEntryIdSchema).min(1).max(100) });
14917
+ const AccessReviewDecisionValueSchema = z$1.enum(["confirmed", "revoked"]);
14918
+ z$1.object({
14919
+ userId: z$1.string().regex(/^[a-f0-9]{24}$/, "Not a valid user id"),
14920
+ decision: AccessReviewDecisionValueSchema,
14921
+ dormantDays: z$1.number().int().min(7).max(365).optional()
14922
+ });
14557
14923
  z$1.enum(["target", "actor"]);
14558
14924
  const apiCompletionObservationSchema = z$1.strictObject({
14559
14925
  requestId: z$1.string().min(1).max(128),
@@ -15199,7 +15565,8 @@ const GENERATED_ASSET_GENERATORS = [
15199
15565
  "video",
15200
15566
  "image",
15201
15567
  "speech",
15202
- "sound_effect"
15568
+ "sound_effect",
15569
+ "scene"
15203
15570
  ];
15204
15571
  /**
15205
15572
  * How an input FabFile fed a generation; the trail view labels each lineage edge with it. Must stay a superset of
@@ -15213,7 +15580,10 @@ const GENERATED_ASSET_LINEAGE_ROLES = [
15213
15580
  "extend_of",
15214
15581
  "variation_of",
15215
15582
  "edit_source",
15216
- "mask"
15583
+ "mask",
15584
+ "scene_video",
15585
+ "scene_audio",
15586
+ "scene_cover"
15217
15587
  ];
15218
15588
  z.object({
15219
15589
  fileId: z.string().regex(/^[0-9a-f]{24}$/),
@@ -15735,6 +16105,12 @@ z$1.enum([
15735
16105
  "immediate_action"
15736
16106
  ]);
15737
16107
  /**
16108
+ * `end_user_id` on the AI routes: a platform key's own opaque id for the end user a request is for.
16109
+ * Deliberately a loose string so a malformed value never fails contract validation with a 422; the
16110
+ * format is checked by `isValidEndUserId` in `resolvePlatformEndUser`, which answers a 400.
16111
+ */
16112
+ const EndUserIdSchema = z$1.string().describe("Your own opaque identifier for the end user this request is for (1-64 characters: letters, digits, `_`, `:`, `-`; never an email). A malformed value is refused with a 400 (`errorCode: \"invalid_end_user_id\"`). Accepted only on an API key holding `ai:end-user-id`, which an administrator grants to keys that serve many end users; any other credential sending it is refused with a 400 (`errorCode: \"end_user_id_not_allowed\"`). On models served directly by OpenAI or Anthropic, the provider then receives an identifier derived from your account and this value instead of one for your whole account; other providers receive no end-user identifier.");
16113
+ /**
15738
16114
  * Largest legacy thinking budget (`budget_tokens`) a request may ask for. Anthropic rejects rather
15739
16115
  * than clamps an oversized budget, and the budget raises the max_tokens a turn is sent with, so it
15740
16116
  * is bounded both at the request schemas and where the adapter consumes it (buildThinkingParams).
@@ -15973,13 +16349,39 @@ const CompletionRunAttributionSchema = z$1.object({
15973
16349
  taskId: CompletionRunLabelSchema.optional().describe("Your own id for the worker's task within the run."),
15974
16350
  attemptId: CompletionRunLabelSchema.optional().describe("Your own id for this attempt at the task; retries get new ids."),
15975
16351
  parentSessionId: CompletionSessionIdSchema.optional().describe("The `sessionId` of the session that spawned this one, for nested workers.")
15976
- }).describe("Groups this request's spend under a run you created with `POST /api/v1/completion-runs`. A run you did not create is refused with `404` (`errorCode: \"run_not_found\"`).");
16352
+ }).describe("Groups this request's spend under a run you created with `POST /api/v1/completion-runs`. A run you did not create is refused with `404` (`errorCode: \"run_not_found\"`), as is a read of its spend.");
15977
16353
  const CreateCompletionRunRequestSchema = z$1.object({ rootSessionId: CompletionSessionIdSchema.optional().describe("Your own id for the conversation that starts the run. A conversation can start many runs; each gets its own id.") });
15978
16354
  const CompletionRunSchema = z$1.object({
15979
16355
  runId: CompletionRunIdSchema,
15980
16356
  rootSessionId: z$1.string().optional(),
15981
16357
  createdAt: z$1.iso.datetime()
15982
16358
  });
16359
+ const CompletionRunIdParamSchema = z$1.object({ runId: CompletionRunIdSchema });
16360
+ const TokenCountSchema = z$1.number().int().nonnegative();
16361
+ /** Settled spend of a set of run-attributed requests, summed from their ledger rows. */
16362
+ const CompletionRunSpendSchema = z$1.object({
16363
+ creditsCharged: z$1.number().nonnegative().describe("Credits the ledger recorded for these requests: the same amount each `settled` stream event reported."),
16364
+ requests: z$1.number().int().nonnegative().describe("Settled requests counted."),
16365
+ inputTokens: TokenCountSchema,
16366
+ outputTokens: TokenCountSchema,
16367
+ cacheReadTokens: TokenCountSchema,
16368
+ cacheWriteTokens: TokenCountSchema
16369
+ });
16370
+ const CompletionRunUsageSchema = z$1.object({
16371
+ runId: CompletionRunIdSchema,
16372
+ rootSessionId: z$1.string().optional(),
16373
+ createdAt: z$1.iso.datetime(),
16374
+ settled: CompletionRunSpendSchema.describe("Every settled request attributed to the run, each counted once."),
16375
+ byRole: z$1.array(CompletionRunSpendSchema.extend({ role: z$1.enum(COMPLETION_RUN_ROLES) })),
16376
+ byPurpose: z$1.array(CompletionRunSpendSchema.extend({ purpose: z$1.enum(COMPLETION_RUN_PURPOSES).describe("`turn` when sent without one.") })),
16377
+ byModel: z$1.array(CompletionRunSpendSchema.extend({ model: z$1.string() })).describe("Grouped by the model each request asked for, which is not always the model that ran."),
16378
+ byAttempt: z$1.array(CompletionRunSpendSchema.extend({
16379
+ role: z$1.enum(COMPLETION_RUN_ROLES),
16380
+ taskId: z$1.string().optional(),
16381
+ attemptId: z$1.string().optional()
16382
+ })).describe(`One entry per distinct role, \`taskId\` and \`attemptId\` sent; absent ids are their own entry. At most 500, largest spend first.`),
16383
+ byAttemptTruncated: z$1.boolean().describe("True when the run has more attempts than `byAttempt` lists; `settled` still counts all of them.")
16384
+ });
15983
16385
  /**
15984
16386
  * Schema for CLI LLM completion requests
15985
16387
  * Shared between Next.js API route (dev) and Lambda function (production)
@@ -16000,6 +16402,7 @@ const CompletionRequestSchema = z$1.object({
16000
16402
  max_tokens: z$1.number().optional(),
16001
16403
  sessionId: CompletionSessionIdSchema.optional(),
16002
16404
  run: CompletionRunAttributionSchema.optional(),
16405
+ end_user_id: EndUserIdSchema.optional(),
16003
16406
  options: z$1.object({
16004
16407
  temperature: z$1.number().optional(),
16005
16408
  maxTokens: z$1.number().optional(),
@@ -17465,14 +17868,16 @@ const StorageLimitErrorSchema = ApiErrorSchema.extend(StorageLimitErrorInfoSchem
17465
17868
  /** 503 when this deployment has no usable key for a provider the request needs (data-lake search, voice). */
17466
17869
  const ProviderNotConfiguredErrorSchema = ApiErrorSchema.extend({ errorCode: z$1.literal("provider_not_configured").optional() });
17467
17870
  /**
17468
- * 400 for provider-rejected caller input, a `model` the caller cannot use, or a refused tool search
17469
- * request; `errorCode` is absent on the other 400s (e.g. malformed JSON).
17871
+ * 400 for provider-rejected caller input, a `model` the caller cannot use, a refused tool search
17872
+ * request, or an `end_user_id` the credential may not send; `errorCode` is absent on the other 400s (e.g. malformed JSON).
17470
17873
  */
17471
17874
  const CompletionsBadRequestErrorSchema = ApiErrorSchema.extend({ errorCode: z$1.enum([
17472
17875
  "invalid_request",
17473
17876
  UNKNOWN_MODEL_ERROR_CODE,
17474
17877
  ASSISTANT_PREFILL_UNSUPPORTED_ERROR_CODE,
17475
- ...COMPLETION_TOOL_ERROR_CODES
17878
+ ...COMPLETION_TOOL_ERROR_CODES,
17879
+ END_USER_ID_NOT_ALLOWED_ERROR_CODE,
17880
+ INVALID_END_USER_ID_ERROR_CODE
17476
17881
  ]).optional() });
17477
17882
  /** 404 when a completion names a `run` that does not exist or that another user or billing owner minted. */
17478
17883
  const RunNotFoundErrorSchema = ApiErrorSchema.extend({ errorCode: z$1.literal(RUN_NOT_FOUND_ERROR_CODE) });
@@ -17502,11 +17907,34 @@ const ScopeForbiddenErrorSchema = ApiErrorSchema.extend({
17502
17907
  also_required_scopes: z$1.array(z$1.string()).optional().describe("API key scopes this route also requires. Every one must be held, on top of `required_scopes`.")
17503
17908
  });
17504
17909
  /**
17505
- * 403 on the v1 media create routes and POST /api/v1/agent-executions: the scope refusal above, or an
17910
+ * 403 on the v1 media create routes and POST /api/v1/agent-executions: the scope refusal above, an
17506
17911
  * organization-billed API key sent with another billing organization
17507
- * (apps/client/server/billing/resolveMediaBillingOrgId.ts).
17912
+ * (apps/client/server/billing/resolveMediaBillingOrgId.ts), or a model or built-in tool the
17913
+ * organization policy does not allow.
17914
+ */
17915
+ const BillingOrganizationForbiddenErrorSchema = ScopeForbiddenErrorSchema.extend({ errorCode: z$1.enum([
17916
+ ACCOUNT_SUSPENDED_ERROR_CODE,
17917
+ BILLING_ORGANIZATION_MISMATCH_ERROR_CODE,
17918
+ ORG_MODEL_NOT_ALLOWED_ERROR_CODE,
17919
+ ORG_TOOL_NOT_ALLOWED_ERROR_CODE
17920
+ ]).optional() });
17921
+ /**
17922
+ * 403 on the completions route: the scope refusal above, a model outside the free-tier allowlist, or a
17923
+ * model the organization policy does not allow.
17508
17924
  */
17509
- const BillingOrganizationForbiddenErrorSchema = ScopeForbiddenErrorSchema.extend({ errorCode: z$1.enum([ACCOUNT_SUSPENDED_ERROR_CODE, BILLING_ORGANIZATION_MISMATCH_ERROR_CODE]).optional() });
17925
+ const ModelPolicyForbiddenErrorSchema = ScopeForbiddenErrorSchema.extend({ errorCode: z$1.enum([
17926
+ ACCOUNT_SUSPENDED_ERROR_CODE,
17927
+ MODEL_REQUIRES_SUBSCRIPTION_ERROR_CODE,
17928
+ ORG_MODEL_NOT_ALLOWED_ERROR_CODE
17929
+ ]).optional() });
17930
+ /** 403 on POST /api/chat: the completions refusals, or a built-in tool the organization policy does not allow. */
17931
+ const ChatForbiddenErrorSchema = ScopeForbiddenErrorSchema.extend({ errorCode: z$1.enum([
17932
+ ACCOUNT_SUSPENDED_ERROR_CODE,
17933
+ MODEL_REQUIRES_SUBSCRIPTION_ERROR_CODE,
17934
+ FREE_QUEST_LIMIT_REACHED_ERROR_CODE,
17935
+ ORG_MODEL_NOT_ALLOWED_ERROR_CODE,
17936
+ ORG_TOOL_NOT_ALLOWED_ERROR_CODE
17937
+ ]).optional() });
17510
17938
  const supportedVoiceGenerationVendor = z.enum(["openai", "elevenlabs"]);
17511
17939
  const DEFAULT_TTS_PROVIDER = "openai";
17512
17940
  const voiceOutputFormatSchema = z.enum([
@@ -17517,11 +17945,10 @@ const voiceOutputFormatSchema = z.enum([
17517
17945
  "flac",
17518
17946
  "pcm"
17519
17947
  ]);
17520
- const TTS_MAX_INPUT_CHARS = {
17948
+ const TTS_ABSOLUTE_MAX_INPUT_CHARS = Math.max(...Object.values({
17521
17949
  openai: 4096,
17522
17950
  elevenlabs: 1e4
17523
- };
17524
- const TTS_ABSOLUTE_MAX_INPUT_CHARS = Math.max(...Object.values(TTS_MAX_INPUT_CHARS));
17951
+ }));
17525
17952
  const ttsLanguageCodeSchema = z.string().regex(/^[a-z]{2}$/, "languageCode must be a lowercase ISO 639-1 code, e.g. \"en\" or \"ja\"");
17526
17953
  const ttsRequestSchema = z.object({
17527
17954
  text: z.string().min(1).max(TTS_ABSOLUTE_MAX_INPUT_CHARS),
@@ -17533,8 +17960,19 @@ const ttsRequestSchema = z.object({
17533
17960
  similarityBoost: z.number().min(0).max(1).optional(),
17534
17961
  languageCode: ttsLanguageCodeSchema.optional(),
17535
17962
  organization_id: z.string().trim().min(1).nullable().optional().describe("The organization to bill: one you belong to, or null for your personal credits. Omitted bills your personal credits, as this endpoint always has. An organization-billed API key always bills its own organization: omit this or set it to the key's organization; any other value, null included, is rejected with a 403 (`errorCode: billing_organization_mismatch`)."),
17963
+ end_user_id: EndUserIdSchema.optional(),
17536
17964
  ...generatedAudioRequestFields
17537
17965
  });
17966
+ ttsRequestSchema.pick({
17967
+ text: true,
17968
+ provider: true,
17969
+ model: true,
17970
+ voice: true,
17971
+ format: true,
17972
+ stability: true,
17973
+ similarityBoost: true,
17974
+ languageCode: true
17975
+ });
17538
17976
  /**
17539
17977
  * JSON body of `POST /api/ai/tts` for `encoding: 'base64'`: the shared generated-audio
17540
17978
  * body plus the TTS fields. `provider`/`fallbackFrom` appear only when the requested
@@ -17560,10 +17998,13 @@ const ttsBase64ResponseSchema = extendGeneratedAudioResponseSchema({
17560
17998
  const TTS_ERROR_CODES = [
17561
17999
  "insufficient_credits",
17562
18000
  "provider_not_configured",
17563
- "provider_rejected"
18001
+ "provider_rejected",
18002
+ "end_user_id_not_allowed",
18003
+ "invalid_end_user_id",
18004
+ "request_timeout"
17564
18005
  ];
17565
18006
  /**
17566
- * Error body for `POST /api/ai/tts`, shared by the 401, 422, 429 and 502; the 413
18007
+ * Error body for `POST /api/ai/tts`, shared by the 401, 422, 429, 502 and 504; the 413
17567
18008
  * has a shape of its own (`ttsResponseTooLargeSchema`). `errorCode` is present only
17568
18009
  * on the conditions that carry a classifier; an ordinary validation 422 has none.
17569
18010
  *
@@ -17592,7 +18033,10 @@ const TTS_ERROR_CODES = [
17592
18033
  const ttsForbiddenResponseSchema = BillingOrganizationForbiddenErrorSchema.extend({ provider: supportedVoiceGenerationVendor.optional() });
17593
18034
  const ttsErrorResponseSchema = ApiErrorSchema.extend({
17594
18035
  provider: supportedVoiceGenerationVendor.optional(),
17595
- errorCode: z.enum(TTS_ERROR_CODES).optional()
18036
+ errorCode: z.enum(TTS_ERROR_CODES).optional(),
18037
+ /** The job a 504 left running (see unretrievableAudioResponse). */
18038
+ jobId: z.string().optional(),
18039
+ message: z.string().optional()
17596
18040
  });
17597
18041
  /**
17598
18042
  * TTS 413 body: `generatedAudioTooLargeSchema` plus the provider. The handler never
@@ -17614,92 +18058,6 @@ const ttsResponseTooLargeSchema = generatedAudioTooLargeSchema.extend({
17614
18058
  fileUrl: z.string().optional()
17615
18059
  });
17616
18060
  /**
17617
- * The model each vendor's service synthesizes and bills with when the caller
17618
- * names none. Read by OpenAIVoiceService / ElevenLabsVoiceService in
17619
- * @bike4mind/utils, so a pre-flight estimate prices the model the charge will use
17620
- * when the requested vendor serves the call. The TTS route reserves the highest
17621
- * estimate across its candidate vendors, using these defaults for alternates,
17622
- * then settles the actual vendor's cost and refunds the difference.
17623
- */
17624
- const TTS_DEFAULT_MODEL = {
17625
- openai: "gpt-4o-mini-tts",
17626
- elevenlabs: "eleven_multilingual_v2"
17627
- };
17628
- const GENERATION_OUTPUT_AVAILABILITIES = [
17629
- "ready",
17630
- "pending_scan",
17631
- "unavailable"
17632
- ];
17633
- const VIDEO_MODES = ["text_to_video", "image_to_video"];
17634
- const VIDEO_INPUT_ROLES = [
17635
- "first_frame",
17636
- "last_frame",
17637
- "reference",
17638
- "style"
17639
- ];
17640
- const ASPECT_RATIOS = [
17641
- "16:9",
17642
- "9:16",
17643
- "1:1",
17644
- "4:3",
17645
- "3:4",
17646
- "3:2",
17647
- "2:3",
17648
- "21:9"
17649
- ];
17650
- const RESOLUTION_TIERS = [
17651
- "360p",
17652
- "480p",
17653
- "720p",
17654
- "1080p",
17655
- "4k"
17656
- ];
17657
- const VideoModelIdSchema = z$1.enum([
17658
- "test-video",
17659
- "gemini-omni-1.1-flash",
17660
- "grok-imagine-video-1.5",
17661
- "veo-3.1-fast-generate-preview",
17662
- "flux-3-video"
17663
- ]);
17664
- const VideoInputSchema = z$1.union([z$1.strictObject({
17665
- role: z$1.enum(VIDEO_INPUT_ROLES),
17666
- fileId: z$1.string().min(1)
17667
- }), z$1.strictObject({
17668
- role: z$1.enum(VIDEO_INPUT_ROLES),
17669
- generatedImageKey: z$1.string().min(1)
17670
- })]);
17671
- z$1.object({
17672
- model: VideoModelIdSchema,
17673
- mode: z$1.enum(VIDEO_MODES),
17674
- prompt: z$1.string().trim().min(1).max(4e3),
17675
- durationSeconds: z$1.number().positive(),
17676
- aspectRatio: z$1.enum(ASPECT_RATIOS),
17677
- resolution: z$1.enum(RESOLUTION_TIERS),
17678
- inputs: z$1.array(VideoInputSchema).max(8).optional(),
17679
- inputImageFileId: z$1.string().min(1).optional(),
17680
- inputGeneratedImageKey: z$1.string().min(1).optional(),
17681
- audio: z$1.boolean().optional()
17682
- });
17683
- const VIDEO_VALIDATION_ERROR_CODES = [
17684
- "unsupported_duration",
17685
- "unsupported_aspect_ratio",
17686
- "unsupported_resolution",
17687
- "unsupported_mode",
17688
- "missing_input_image",
17689
- "unexpected_input_image",
17690
- "unsupported_input_role",
17691
- "unsupported_audio_option"
17692
- ];
17693
- const IMAGE_MODES = ["generate", "edit"];
17694
- const IMAGE_INPUT_ROLES = [
17695
- "edit_source",
17696
- "mask",
17697
- "reference"
17698
- ];
17699
- const TEST_IMAGE_MODEL = "test-image";
17700
- const LOCAL_IMAGE_MODEL_PREFIX = "local-image/";
17701
- const IMAGE_ALPHA_FORMATS = ["png", "webp"];
17702
- /**
17703
18061
  * Constants for BFL safety tolerance settings.
17704
18062
  *
17705
18063
  * BFL scale: 0 = strictest filtering, 6 = effectively unfiltered. MAX is a
@@ -17799,6 +18157,15 @@ z$1.object({
17799
18157
  output_format: z$1.enum(["jpeg", "png"]).prefault("png").optional(),
17800
18158
  safety_tolerance: z$1.number().min(0).max(1).prefault(.5).optional()
17801
18159
  });
18160
+ const IMAGE_MODES = ["generate", "edit"];
18161
+ const IMAGE_INPUT_ROLES = [
18162
+ "edit_source",
18163
+ "mask",
18164
+ "reference"
18165
+ ];
18166
+ const TEST_IMAGE_MODEL = "test-image";
18167
+ const LOCAL_IMAGE_MODEL_PREFIX = "local-image/";
18168
+ const IMAGE_ALPHA_FORMATS = ["png", "webp"];
17802
18169
  const ChatCompletionCreateInputSchema = z$1.object({
17803
18170
  model: ModelIdSchema,
17804
18171
  imageModel: ModelIdSchema.optional(),
@@ -18012,6 +18379,13 @@ const DATA_LAKES = [{
18012
18379
  }
18013
18380
  })()];
18014
18381
  new Set(DATA_LAKES.map((l) => l.id));
18382
+ const VideoModelIdSchema = z$1.enum([
18383
+ "test-video",
18384
+ "gemini-omni-1.1-flash",
18385
+ "grok-imagine-video-1.5",
18386
+ "veo-3.1-fast-generate-preview",
18387
+ "flux-3-video"
18388
+ ]);
18015
18389
  function isGPTImageModel(model) {
18016
18390
  if (!model) return false;
18017
18391
  return OPENAI_IMAGE_MODELS.includes(model) || model.startsWith("gpt-image-");
@@ -18480,6 +18854,16 @@ z$1.object({
18480
18854
  */
18481
18855
  messageOnlyFileIds: z$1.array(z$1.string()).optional()
18482
18856
  });
18857
+ const ga = (tier, releasedAt) => ({
18858
+ tier,
18859
+ releasedAt,
18860
+ preview: false
18861
+ });
18862
+ const preview = (tier, releasedAt) => ({
18863
+ tier,
18864
+ releasedAt,
18865
+ preview: true
18866
+ });
18483
18867
  const GPT_IMAGE_QUALITIES = [
18484
18868
  "low",
18485
18869
  "medium",
@@ -18531,7 +18915,8 @@ const editMode = (mode) => ({
18531
18915
  ...mode,
18532
18916
  maxOutputs: 1
18533
18917
  });
18534
- const gptImage = (overrides) => ({
18918
+ const gptImage = (standing, overrides) => ({
18919
+ ...standing,
18535
18920
  provider: "openai",
18536
18921
  modes: {
18537
18922
  generate: {
@@ -18560,7 +18945,8 @@ const bflGenerate = (aspectRatios) => ({
18560
18945
  aspectRatios,
18561
18946
  outputFormats: PNG_JPEG
18562
18947
  });
18563
- const bfl = (overrides) => ({
18948
+ const bfl = (standing, overrides) => ({
18949
+ ...standing,
18564
18950
  provider: "bfl",
18565
18951
  qualities: [],
18566
18952
  styles: [],
@@ -18568,7 +18954,7 @@ const bfl = (overrides) => ({
18568
18954
  seed: true,
18569
18955
  ...overrides
18570
18956
  });
18571
- const flux2 = (model) => bfl({
18957
+ const flux2 = (model, standing) => bfl(standing, {
18572
18958
  modes: {
18573
18959
  generate: {
18574
18960
  inputs: { reference: { max: getMaxReferenceImages(model) } },
@@ -18587,8 +18973,8 @@ const flux2 = (model) => bfl({
18587
18973
  },
18588
18974
  sizing: BFL_SIZING
18589
18975
  });
18590
- const flux3 = (model) => ({
18591
- ...bfl({
18976
+ const flux3 = (model, standing) => ({
18977
+ ...bfl(standing, {
18592
18978
  modes: {
18593
18979
  generate: {
18594
18980
  inputs: { reference: { max: getMaxReferenceImages(model) } },
@@ -18610,7 +18996,8 @@ const flux3 = (model) => ({
18610
18996
  }),
18611
18997
  seed: supportsBflSeed(model)
18612
18998
  });
18613
- const gemini = () => ({
18999
+ const gemini = (standing) => ({
19000
+ ...standing,
18614
19001
  provider: "gemini",
18615
19002
  modes: {
18616
19003
  generate: {
@@ -18631,40 +19018,40 @@ const gemini = () => ({
18631
19018
  transparentBackground: false,
18632
19019
  seed: false
18633
19020
  });
18634
- gptImage({
19021
+ gptImage(ga("flagship", "2025-04-23"), {
18635
19022
  sizing: GPT_IMAGE_1_SIZING,
18636
19023
  qualities: GPT_IMAGE_QUALITIES,
18637
19024
  transparentBackground: true
18638
- }), gptImage({
19025
+ }), gptImage(ga("flagship", "2025-12-16"), {
18639
19026
  sizing: GPT_IMAGE_1_SIZING,
18640
19027
  qualities: GPT_IMAGE_QUALITIES,
18641
19028
  transparentBackground: true
18642
- }), gptImage({
19029
+ }), gptImage(ga("fast", "2025-10-06"), {
18643
19030
  sizing: GPT_IMAGE_1_SIZING,
18644
19031
  qualities: GPT_IMAGE_QUALITIES,
18645
19032
  transparentBackground: true
18646
- }), gptImage({
19033
+ }), gptImage(ga("flagship", "2026-04-21"), {
18647
19034
  sizing: GPT_IMAGE_2_SIZING,
18648
19035
  qualities: GPT_IMAGE_QUALITIES,
18649
19036
  transparentBackground: false
18650
- }), gptImage({
19037
+ }), gptImage(ga("flagship", "2026-09-08"), {
18651
19038
  sizing: GPT_IMAGE_2_SIZING,
18652
19039
  qualities: GPT_IMAGE_25_QUALITIES,
18653
19040
  transparentBackground: true
18654
- }), gptImage({
19041
+ }), gptImage(ga("standard", "2026-09-08"), {
18655
19042
  sizing: GPT_IMAGE_2_SIZING,
18656
19043
  qualities: GPT_IMAGE_25_QUALITIES,
18657
19044
  transparentBackground: true
18658
- }), IMAGE_SIZE_CONSTRAINTS.DALL_E_2.sizes, IMAGE_SIZE_CONSTRAINTS.DALL_E_2.defaultSize, bfl({
19045
+ }), { ...ga("standard", "2022-11-03") }, IMAGE_SIZE_CONSTRAINTS.DALL_E_2.sizes, IMAGE_SIZE_CONSTRAINTS.DALL_E_2.defaultSize, bfl(ga("standard", "2024-08-01"), {
18659
19046
  modes: { generate: bflGenerate(null) },
18660
19047
  sizing: BFL_SIZING
18661
- }), bfl({
19048
+ }), bfl(ga("standard", "2024-10-02"), {
18662
19049
  modes: { generate: bflGenerate(null) },
18663
19050
  sizing: BFL_SIZING
18664
- }), bfl({
19051
+ }), bfl(ga("flagship", "2024-11-06"), {
18665
19052
  modes: { generate: bflGenerate(BFL_ASPECT_RATIOS) },
18666
19053
  sizing: { kind: "aspectRatio" }
18667
- }), bfl({
19054
+ }), bfl(ga("standard", "2024-11-21"), {
18668
19055
  modes: { edit: editMode({
18669
19056
  inputs: {
18670
19057
  edit_source: { max: 1 },
@@ -18680,7 +19067,7 @@ gptImage({
18680
19067
  kind: "inputImage",
18681
19068
  aspectRatio: false
18682
19069
  }
18683
- }), bfl({
19070
+ }), bfl(ga("standard", "2025-05-29"), {
18684
19071
  modes: { edit: editMode({
18685
19072
  inputs: { edit_source: { max: 1 } },
18686
19073
  aspectRatios: BFL_ASPECT_RATIOS,
@@ -18690,7 +19077,7 @@ gptImage({
18690
19077
  kind: "inputImage",
18691
19078
  aspectRatio: true
18692
19079
  }
18693
- }), bfl({
19080
+ }), bfl(ga("flagship", "2025-05-29"), {
18694
19081
  modes: { edit: editMode({
18695
19082
  inputs: { edit_source: { max: 1 } },
18696
19083
  aspectRatios: BFL_ASPECT_RATIOS,
@@ -18700,8 +19087,8 @@ gptImage({
18700
19087
  kind: "inputImage",
18701
19088
  aspectRatio: true
18702
19089
  }
18703
- }), flux2("flux-2-max"), flux2("flux-2-pro"), flux2("flux-2-pro-preview"), flux2("flux-2-flex"), flux2("flux-2-klein-9b"), flux2("flux-2-klein-9b-preview"), flux2("flux-2-klein-4b"), flux3("flux-3-image"), flux3("flux-3-image-klein"), gemini(), gemini(), gemini(), gemini();
18704
- editMode({
19090
+ }), flux2("flux-2-max", ga("flagship", "2025-12-16")), flux2("flux-2-pro", ga("standard", "2025-11-25")), flux2("flux-2-pro-preview", preview("standard", "2025-11-25")), flux2("flux-2-flex", ga("standard", "2025-11-25")), flux2("flux-2-klein-9b", ga("fast", "2026-01-15")), flux2("flux-2-klein-9b-preview", preview("fast", "2026-01-15")), flux2("flux-2-klein-4b", ga("fast", "2026-01-15")), flux3("flux-3-image", ga("flagship", "2026-10-01")), flux3("flux-3-image-klein", ga("fast", "2026-10-15")), { ...ga("flagship", "2026-01-28") }, gemini(ga("fast", "2025-08-26")), gemini(preview("flagship", "2025-11-30")), gemini(ga("fast", "2026-05-28")), gemini(ga("flagship", "2026-05-28"));
19091
+ ({ ...ga("fast", "1970-01-01") }), editMode({
18705
19092
  inputs: {
18706
19093
  edit_source: { max: 1 },
18707
19094
  mask: { max: 1 }
@@ -18709,6 +19096,88 @@ editMode({
18709
19096
  aspectRatios: null,
18710
19097
  outputFormats: []
18711
19098
  });
19099
+ ({ ...ga("fast", "1970-01-01") });
19100
+ const MAX_MUSIC_LYRICS_CHARS = 1e4;
19101
+ const MUSIC_OUTPUT_FORMATS = ["mp3"];
19102
+ const MusicModelIdSchema = z$1.enum([
19103
+ "test-music",
19104
+ "lyria-3.5",
19105
+ "lyria-3-clip-preview",
19106
+ "music_v2_5",
19107
+ "music_v2",
19108
+ "music_v1"
19109
+ ]);
19110
+ const GENERATION_OUTPUT_AVAILABILITIES = [
19111
+ "ready",
19112
+ "pending_scan",
19113
+ "unavailable"
19114
+ ];
19115
+ const MODEL_TIERS = [
19116
+ "flagship",
19117
+ "standard",
19118
+ "fast"
19119
+ ];
19120
+ const VIDEO_MODES = ["text_to_video", "image_to_video"];
19121
+ const VIDEO_INPUT_ROLES = [
19122
+ "first_frame",
19123
+ "last_frame",
19124
+ "reference",
19125
+ "style"
19126
+ ];
19127
+ const ASPECT_RATIOS = [
19128
+ "16:9",
19129
+ "9:16",
19130
+ "1:1",
19131
+ "4:3",
19132
+ "3:4",
19133
+ "3:2",
19134
+ "2:3",
19135
+ "21:9"
19136
+ ];
19137
+ const RESOLUTION_TIERS = [
19138
+ "360p",
19139
+ "480p",
19140
+ "720p",
19141
+ "1080p",
19142
+ "4k"
19143
+ ];
19144
+ const VideoInputSchema = z$1.union([z$1.strictObject({
19145
+ role: z$1.enum(VIDEO_INPUT_ROLES),
19146
+ fileId: z$1.string().min(1)
19147
+ }), z$1.strictObject({
19148
+ role: z$1.enum(VIDEO_INPUT_ROLES),
19149
+ generatedImageKey: z$1.string().min(1)
19150
+ })]);
19151
+ z$1.object({
19152
+ model: VideoModelIdSchema,
19153
+ mode: z$1.enum(VIDEO_MODES),
19154
+ prompt: z$1.string().trim().min(1).max(4e3),
19155
+ durationSeconds: z$1.number().positive(),
19156
+ aspectRatio: z$1.enum(ASPECT_RATIOS),
19157
+ resolution: z$1.enum(RESOLUTION_TIERS),
19158
+ keyframes: z$1.array(z$1.strictObject({
19159
+ fileId: z$1.string().min(1),
19160
+ timeSeconds: z$1.number().nonnegative()
19161
+ })).min(1).max(100).optional(),
19162
+ draft: z$1.boolean().optional(),
19163
+ inputs: z$1.array(VideoInputSchema).max(8).optional(),
19164
+ inputImageFileId: z$1.string().min(1).optional(),
19165
+ inputGeneratedImageKey: z$1.string().min(1).optional(),
19166
+ audio: z$1.boolean().optional()
19167
+ });
19168
+ const VIDEO_VALIDATION_ERROR_CODES = [
19169
+ "unsupported_duration",
19170
+ "unsupported_aspect_ratio",
19171
+ "unsupported_resolution",
19172
+ "unsupported_mode",
19173
+ "missing_input_image",
19174
+ "unexpected_input_image",
19175
+ "unsupported_input_role",
19176
+ "unsupported_audio_option",
19177
+ "unsupported_keyframes",
19178
+ "invalid_keyframes",
19179
+ "unsupported_draft"
19180
+ ];
18712
19181
  [...IMAGE_SIZE_CONSTRAINTS.DALL_E_2.sizes, ...IMAGE_SIZE_CONSTRAINTS.DALL_E_3.sizes];
18713
19182
  new Set(IMAGE_ALPHA_FORMATS);
18714
19183
  const IMAGE_JOB_PROMPT_MAX_CHARS = 4e3;
@@ -18962,16 +19431,6 @@ const EMBEDDING_MODEL_IDS = Object.keys(EMBEDDING_MODEL_CATALOG);
18962
19431
  const getEmbeddingModelCapabilities = (model) => EMBEDDING_MODEL_CATALOG[model];
18963
19432
  /** Every width the model serves, native first (the order `EmbeddingModelInfo.dimensions` has always used). */
18964
19433
  const servableEmbeddingDimensions = ({ dimensions }) => dimensions.kind === "discrete" ? [dimensions.native, ...dimensions.values.filter((width) => width !== dimensions.native)] : [dimensions.native];
18965
- const MAX_MUSIC_LYRICS_CHARS = 1e4;
18966
- const MUSIC_OUTPUT_FORMATS = ["mp3"];
18967
- const MusicModelIdSchema = z$1.enum([
18968
- "test-music",
18969
- "lyria-3.5",
18970
- "lyria-3-clip-preview",
18971
- "music_v2_5",
18972
- "music_v2",
18973
- "music_v1"
18974
- ]);
18975
19434
  z$1.object({
18976
19435
  model: MusicModelIdSchema,
18977
19436
  prompt: z$1.string().trim().min(1).max(4e3),
@@ -18989,6 +19448,29 @@ const MUSIC_VALIDATION_ERROR_CODES = [
18989
19448
  const SECONDS = String.raw`\d+(?:\.\d+)?`;
18990
19449
  String.raw`\[(?:${SECONDS}:${SECONDS}|:)\]`;
18991
19450
  /**
19451
+ * A Scene is one shareable clip rendered from a video and a music track the caller already has (and optionally a
19452
+ * cover image). It is a rendered file, stored as its own generated asset with lineage to its inputs, not a recipe
19453
+ * that is re-rendered on read.
19454
+ */
19455
+ /** `trim`: cut the audio at the video's end. `loop`: repeat the audio until the video ends. */
19456
+ const SCENE_AUDIO_FITS = ["trim", "loop"];
19457
+ const SCENE_DEFAULT_FADE_OUT_SECONDS = 1.5;
19458
+ /** Sum of the input files' sizes; the worker downloads all of them to local disk. */
19459
+ const SCENE_MAX_INPUT_BYTES = 209715200;
19460
+ const FileIdSchema = z$1.string().regex(/^[0-9a-f]{24}$/, "must be a lowercase 24-character hex file id");
19461
+ const SceneAudioOptionsSchema = z$1.strictObject({
19462
+ fit: z$1.enum(SCENE_AUDIO_FITS),
19463
+ fadeInSeconds: z$1.number().min(0).max(10),
19464
+ fadeOutSeconds: z$1.number().min(0).max(10)
19465
+ });
19466
+ z$1.strictObject({
19467
+ videoFileId: FileIdSchema,
19468
+ audioFileId: FileIdSchema,
19469
+ coverFileId: FileIdSchema.optional(),
19470
+ audio: SceneAudioOptionsSchema,
19471
+ title: z$1.string().trim().min(1).max(200).optional()
19472
+ }).extend({ audio: SceneAudioOptionsSchema.partial().optional() });
19473
+ /**
18992
19474
  * Building blocks for entity response schemas held to an entity's key list (see
18993
19475
  * selfUserResponseSchema in ./user.ts for the full rationale). A passthrough value is
18994
19476
  * `z.unknown()`: the boundary enforces WHICH keys leave the server, not their types, so a
@@ -19092,6 +19574,8 @@ const SELF_VIEW_PASSTHROUGH_FIELDS = {
19092
19574
  groups: true,
19093
19575
  isAdmin: true,
19094
19576
  adminPermissions: true,
19577
+ adminRoleIds: true,
19578
+ roleAdminPermissions: true,
19095
19579
  storageLimit: true,
19096
19580
  storageLimitOverride: true,
19097
19581
  planStorageLimit: true,
@@ -19155,8 +19639,10 @@ const SELF_VIEW_PASSTHROUGH_FIELDS = {
19155
19639
  acquisition: true,
19156
19640
  isSynthetic: true,
19157
19641
  isInternal: true,
19642
+ accountSegment: true,
19158
19643
  isPersona: true,
19159
19644
  personaExpiresAt: true,
19645
+ mfaEnforcement: true,
19160
19646
  personaName: true,
19161
19647
  personaOwnerId: true,
19162
19648
  firstValueAt: true,
@@ -19924,6 +20410,13 @@ const soundEffectsRequestSchema = z.object({
19924
20410
  organization_id: BillingOrganizationIdSchema,
19925
20411
  ...generatedAudioRequestFields
19926
20412
  });
20413
+ soundEffectsRequestSchema.pick({
20414
+ provider: true,
20415
+ text: true,
20416
+ durationSeconds: true,
20417
+ promptInfluence: true,
20418
+ format: true
20419
+ });
19927
20420
  /**
19928
20421
  * Supported background-music generation vendors. Currently only ElevenLabs.
19929
20422
  * New vendors are added here and in the `aiMusicService` factory.
@@ -19955,6 +20448,225 @@ const musicRequestSchema = z.object({
19955
20448
  format: z.string().optional(),
19956
20449
  ...generatedAudioRequestFields
19957
20450
  });
20451
+ /** Upper bounds keep one export render bounded in cost and the stored document small. */
20452
+ const STUDIO_TIMELINE_LIMITS = {
20453
+ maxDurationMs: 18e5,
20454
+ maxTracks: 32,
20455
+ maxClipsPerTrack: 500,
20456
+ maxOutputs: 8,
20457
+ maxCaptionLength: 500,
20458
+ minOutputEdgePx: 128,
20459
+ maxOutputEdgePx: 4096
20460
+ };
20461
+ const STUDIO_TIMELINE_FPS = [
20462
+ 24,
20463
+ 25,
20464
+ 30,
20465
+ 50,
20466
+ 60
20467
+ ];
20468
+ const STUDIO_OUTPUT_ASPECT_RATIOS = [
20469
+ "16:9",
20470
+ "9:16",
20471
+ "1:1",
20472
+ "4:5"
20473
+ ];
20474
+ const StudioFileIdSchema = z$1.string().regex(/^[a-f0-9]{24}$/, "Not a valid file id");
20475
+ const TimelineIdSchema = z$1.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/, "Ids may contain only letters, digits, \"_\" and \"-\"");
20476
+ const MsSchema = z$1.number().int().nonnegative();
20477
+ const PositiveMsSchema = z$1.number().int().positive();
20478
+ const HexColorSchema = z$1.string().regex(/^#[0-9a-fA-F]{6}$/, "Colors are #RRGGBB");
20479
+ const StudioTimelineOutputSchema = z$1.object({
20480
+ id: TimelineIdSchema,
20481
+ aspectRatio: z$1.enum(STUDIO_OUTPUT_ASPECT_RATIOS),
20482
+ width: z$1.number().int().min(STUDIO_TIMELINE_LIMITS.minOutputEdgePx).max(STUDIO_TIMELINE_LIMITS.maxOutputEdgePx),
20483
+ height: z$1.number().int().min(STUDIO_TIMELINE_LIMITS.minOutputEdgePx).max(STUDIO_TIMELINE_LIMITS.maxOutputEdgePx)
20484
+ });
20485
+ /** Placement on the timeline: the clip plays over [startMs, startMs + durationMs). */
20486
+ const ClipTimingShape = {
20487
+ id: TimelineIdSchema,
20488
+ startMs: MsSchema,
20489
+ durationMs: PositiveMsSchema
20490
+ };
20491
+ /**
20492
+ * Source media: the clip plays the source from `trimStartMs` for `durationMs`, so the out-point is implied. That
20493
+ * maps straight onto ffmpeg's `-ss trimStartMs -t durationMs` and the preview's `currentTime = trimStartMs + offset`.
20494
+ */
20495
+ const MediaClipShape = {
20496
+ ...ClipTimingShape,
20497
+ fileId: StudioFileIdSchema,
20498
+ trimStartMs: MsSchema.default(0)
20499
+ };
20500
+ /** On an audio clip a fade ramps the gain from and to silence. */
20501
+ const AudioShape = {
20502
+ volume: z$1.number().min(0).max(2).default(1),
20503
+ fadeInMs: MsSchema.default(0),
20504
+ fadeOutMs: MsSchema.default(0)
20505
+ };
20506
+ /** How a source whose shape differs from an output's fills that frame: crop to fill, or letterbox to fit. */
20507
+ const STUDIO_VIDEO_FIT_MODES = ["cover", "contain"];
20508
+ /**
20509
+ * On a video clip a fade ramps opacity from and to transparent (revealing what is below) and the clip's audio
20510
+ * gain with it, so a cross-fade is two overlapping clips on two video tracks.
20511
+ */
20512
+ const StudioVideoClipSchema = z$1.object({
20513
+ ...MediaClipShape,
20514
+ ...AudioShape,
20515
+ fit: z$1.enum(STUDIO_VIDEO_FIT_MODES).default("cover")
20516
+ });
20517
+ const StudioAudioClipSchema = z$1.object({
20518
+ ...MediaClipShape,
20519
+ ...AudioShape
20520
+ });
20521
+ /** Sizes are a percentage of the output height so one caption reads the same at every output size. */
20522
+ const StudioCaptionStyleSchema = z$1.object({
20523
+ position: z$1.enum([
20524
+ "top",
20525
+ "center",
20526
+ "bottom"
20527
+ ]).default("bottom"),
20528
+ align: z$1.enum([
20529
+ "left",
20530
+ "center",
20531
+ "right"
20532
+ ]).default("center"),
20533
+ fontFamily: z$1.string().trim().min(1).max(100).optional(),
20534
+ fontSizePct: z$1.number().min(1).max(20).default(5),
20535
+ maxWidthPct: z$1.number().min(10).max(100).default(90),
20536
+ color: HexColorSchema.default("#FFFFFF"),
20537
+ backgroundColor: HexColorSchema.optional()
20538
+ });
20539
+ const StudioCaptionClipSchema = z$1.object({
20540
+ ...ClipTimingShape,
20541
+ text: z$1.string().trim().min(1).max(STUDIO_TIMELINE_LIMITS.maxCaptionLength),
20542
+ style: StudioCaptionStyleSchema.prefault({})
20543
+ });
20544
+ const trackShape = (kind, clip) => z$1.object({
20545
+ id: TimelineIdSchema,
20546
+ kind: z$1.literal(kind),
20547
+ enabled: z$1.boolean().default(true),
20548
+ clips: z$1.array(clip).max(STUDIO_TIMELINE_LIMITS.maxClipsPerTrack)
20549
+ });
20550
+ /**
20551
+ * A track is one lane: its clips never overlap. Layering (two SFX at once, music under voice) is more tracks of the
20552
+ * same or another kind. Tracks are listed bottom to top, so a later video track draws over an earlier one.
20553
+ */
20554
+ const StudioTimelineTrackSchema = z$1.discriminatedUnion("kind", [
20555
+ trackShape("video", StudioVideoClipSchema),
20556
+ trackShape("voice", StudioAudioClipSchema),
20557
+ trackShape("sfx", StudioAudioClipSchema),
20558
+ trackShape("music", StudioAudioClipSchema),
20559
+ trackShape("captions", StudioCaptionClipSchema)
20560
+ ]);
20561
+ const StudioTimelineSchema = z$1.object({
20562
+ version: z$1.literal(1),
20563
+ durationMs: PositiveMsSchema.max(STUDIO_TIMELINE_LIMITS.maxDurationMs),
20564
+ fps: z$1.literal(STUDIO_TIMELINE_FPS),
20565
+ backgroundColor: HexColorSchema.default("#000000"),
20566
+ outputs: z$1.array(StudioTimelineOutputSchema).min(1).max(STUDIO_TIMELINE_LIMITS.maxOutputs),
20567
+ tracks: z$1.array(StudioTimelineTrackSchema).max(STUDIO_TIMELINE_LIMITS.maxTracks)
20568
+ });
20569
+ Object.fromEntries(STUDIO_OUTPUT_ASPECT_RATIOS.map((ratio) => [ratio, ratio.split(":").map(Number)]));
20570
+ /**
20571
+ * A Studio Production: a brief, a small brand kit, a shot list and a timeline that arrange many generated assets
20572
+ * into one output. The UI calls it a Production; code always says StudioComposition / compositionId so it never
20573
+ * reads as the prod environment. Assets are referenced by FabFile id only, never copied.
20574
+ *
20575
+ * The Mongoose model (packages/database models/content/StudioCompositionModel.ts) must declare exactly the
20576
+ * fields of StudioCompositionSchema; its parity test fails when they drift.
20577
+ */
20578
+ const STUDIO_COMPOSITION_TEMPLATES = [
20579
+ "ad_campaign",
20580
+ "social_pack",
20581
+ "product_video",
20582
+ "explainer",
20583
+ "short_film",
20584
+ "blank"
20585
+ ];
20586
+ const STUDIO_COMPOSITION_LIMITS = {
20587
+ titleMaxLength: 200,
20588
+ briefSummaryMaxLength: 4e3,
20589
+ briefFieldMaxLength: 500,
20590
+ brandColorsMax: 8,
20591
+ brandProductFilesMax: 20,
20592
+ shotsMax: 100,
20593
+ shotTitleMaxLength: 200,
20594
+ shotDescriptionMaxLength: 4e3,
20595
+ shotFilesMax: 20,
20596
+ shotPromptMaxLength: 4e3,
20597
+ shotIntentMaxLength: 500,
20598
+ shotVoiceLineMaxLength: 500,
20599
+ listLimitMax: 100
20600
+ };
20601
+ z$1.string().regex(/^[a-f0-9]{24}$/, "Not a valid composition id");
20602
+ const limits = STUDIO_COMPOSITION_LIMITS;
20603
+ const StudioCompositionBriefSchema = z$1.object({
20604
+ summary: z$1.string().trim().max(limits.briefSummaryMaxLength).optional(),
20605
+ audience: z$1.string().trim().max(limits.briefFieldMaxLength).optional(),
20606
+ callToAction: z$1.string().trim().max(limits.briefFieldMaxLength).optional(),
20607
+ productFileId: StudioFileIdSchema.optional()
20608
+ });
20609
+ /** A deliberately small first cut of a brand kit; it grows as templates need more. */
20610
+ const StudioBrandKitSchema = z$1.object({
20611
+ logoFileId: StudioFileIdSchema.optional(),
20612
+ colors: z$1.array(z$1.string().regex(/^#[0-9a-fA-F]{6}$/, "Colors are #RRGGBB")).max(limits.brandColorsMax).default([]),
20613
+ fontFamily: z$1.string().trim().min(1).max(100).optional(),
20614
+ productFileIds: z$1.array(StudioFileIdSchema).max(limits.brandProductFilesMax).default([])
20615
+ });
20616
+ /**
20617
+ * One planned shot: what it should show and the takes generated for it. `fileIds` lists every take, the chosen one
20618
+ * included, so the alternatives are `fileIds` without `chosenFileId`. Shots are stored as Mixed, so new optional
20619
+ * fields need no Mongoose change.
20620
+ */
20621
+ const StudioShotSchema = z$1.object({
20622
+ id: z$1.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/, "Ids may contain only letters, digits, \"_\" and \"-\""),
20623
+ title: z$1.string().trim().min(1).max(limits.shotTitleMaxLength),
20624
+ description: z$1.string().trim().max(limits.shotDescriptionMaxLength).optional(),
20625
+ durationMs: z$1.number().int().positive().optional(),
20626
+ fileIds: z$1.array(StudioFileIdSchema).max(limits.shotFilesMax).default([]),
20627
+ prompt: z$1.string().trim().max(limits.shotPromptMaxLength).optional(),
20628
+ intent: z$1.string().trim().max(limits.shotIntentMaxLength).optional(),
20629
+ chosenFileId: StudioFileIdSchema.optional(),
20630
+ clipFileId: StudioFileIdSchema.optional(),
20631
+ voiceLine: z$1.string().trim().max(limits.shotVoiceLineMaxLength).optional()
20632
+ });
20633
+ const StudioShotListSchema = z$1.array(StudioShotSchema).max(limits.shotsMax);
20634
+ /** The client-writable content of a composition. Ownership fields are server-set and live on the entity below. */
20635
+ const StudioCompositionContentSchema = z$1.object({
20636
+ title: z$1.string().trim().min(1).max(limits.titleMaxLength),
20637
+ template: z$1.enum(STUDIO_COMPOSITION_TEMPLATES).default("ad_campaign"),
20638
+ brief: StudioCompositionBriefSchema.prefault({}),
20639
+ brandKit: StudioBrandKitSchema.prefault({}),
20640
+ shots: StudioShotListSchema.default([]),
20641
+ timeline: StudioTimelineSchema,
20642
+ projectId: z$1.string().regex(/^[a-f0-9]{24}$/, "Not a valid project id").optional()
20643
+ });
20644
+ StudioCompositionContentSchema.extend({
20645
+ userId: z$1.string().min(1),
20646
+ organizationId: z$1.string().optional()
20647
+ });
20648
+ StudioCompositionContentSchema.extend({
20649
+ id: z$1.string(),
20650
+ createdAt: z$1.coerce.date(),
20651
+ updatedAt: z$1.coerce.date()
20652
+ }).omit({
20653
+ shots: true,
20654
+ timeline: true
20655
+ });
20656
+ z$1.strictObject({
20657
+ ...StudioCompositionContentSchema.shape,
20658
+ shots: StudioShotListSchema.optional(),
20659
+ timeline: StudioTimelineSchema.optional()
20660
+ });
20661
+ z$1.strictObject({
20662
+ title: StudioCompositionContentSchema.shape.title.optional(),
20663
+ template: z$1.enum(STUDIO_COMPOSITION_TEMPLATES).optional(),
20664
+ brief: StudioCompositionBriefSchema.optional(),
20665
+ brandKit: StudioBrandKitSchema.optional(),
20666
+ shots: StudioShotListSchema.optional(),
20667
+ timeline: StudioTimelineSchema.optional(),
20668
+ projectId: StudioCompositionContentSchema.shape.projectId.unwrap().nullable().optional()
20669
+ }).refine((update) => Object.values(update).some((value) => value !== void 0), "Nothing to update");
19958
20670
  const turnRetryShape = {
19959
20671
  reason: z$1.enum(TURN_RETRY_REASONS),
19960
20672
  status: z$1.number().optional(),
@@ -20161,6 +20873,8 @@ const DataSubscribeRequestAction = z$1.object({
20161
20873
  }),
20162
20874
  fields: z$1.record(z$1.string(), z$1.union([z$1.boolean(), z$1.number()])),
20163
20875
  fetchInitialData: z$1.boolean().prefault(true).optional(),
20876
+ /** Single-org signal listeners may require snapshot delivery after registration; not a snapshot-consistency guarantee. */
20877
+ initialDataAfterSubscribe: z$1.boolean().optional(),
20164
20878
  clientId: z$1.string().optional()
20165
20879
  });
20166
20880
  const DataUnsubscribeRequestAction = z$1.object({
@@ -21856,6 +22570,27 @@ const ToolExecutionResponseSchema = z$1.object({
21856
22570
  executionTimeMs: z$1.number().optional(),
21857
22571
  request_id: z$1.string()
21858
22572
  });
22573
+ /**
22574
+ * Request/response schemas for the web search, web fetch and weather tool routes. The public
22575
+ * /api/v1/tools/* contracts (api-contract/contracts/webTools.contract.ts) and the SPA-internal
22576
+ * /api/tools/* routes validate with these same objects, so the two doors cannot accept different
22577
+ * bodies. Plain Zod (no `.openapi()`) so any runtime can import them.
22578
+ */
22579
+ const WebSearchToolRequestSchema = z$1.object({
22580
+ query: z$1.string().describe("The search query."),
22581
+ num_results: z$1.number().int().min(1).max(10).optional().describe("How many results to return. Defaults to 3.")
22582
+ });
22583
+ const WebFetchToolRequestSchema = z$1.object({
22584
+ url: z$1.url().refine((value) => /^https?:\/\//i.test(value), { error: "URL must use http or https protocol" }).describe("The http or https page to read."),
22585
+ offset: z$1.coerce.number().int().min(0).optional().describe("Character offset to resume a long page from, as hinted at the end of a truncated result.")
22586
+ });
22587
+ const WeatherToolRequestSchema = z$1.object({
22588
+ lat: z$1.number().min(-90).max(90).describe("Latitude in decimal degrees."),
22589
+ lon: z$1.number().min(-180).max(180).describe("Longitude in decimal degrees."),
22590
+ units: z$1.enum(["imperial", "metric"]).optional().describe("Temperature units. Defaults to `imperial`.")
22591
+ });
22592
+ /** The tool's output as one string, formatted for a language model to read. */
22593
+ const WebToolResultResponseSchema = z$1.object({ result: z$1.string() });
21859
22594
  z$2.object({
21860
22595
  "Response ID": z$2.string(),
21861
22596
  EMPLOYMENT_STATUS_DESCIPTION: z$2.string(),
@@ -22350,9 +23085,9 @@ z$2.object({
22350
23085
  MULTIPLE_VENDOR_PRIMARY_OL: z$2.string()
22351
23086
  });
22352
23087
  z.object({
22353
- fileName: z.string(),
23088
+ fileName: z.string().min(1).max(255),
22354
23089
  mimeType: z.string(),
22355
- fileSize: z.number(),
23090
+ fileSize: z.number().int().positive(),
22356
23091
  /** The path to the file */
22357
23092
  path: z.string().optional(),
22358
23093
  /** SHA-256 content hash for deduplication */
@@ -22730,6 +23465,7 @@ const ORG_DOMAIN_JOIN_POLICIES = [
22730
23465
  const orgDomainSchema = z$1.string().trim().toLowerCase().min(3, "Domain is required").max(253, "Domain is too long").regex(/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/, "Enter a bare domain like example.com (no @ or path)");
22731
23466
  z$1.object({ domain: orgDomainSchema }).strict();
22732
23467
  z$1.object({ policy: z$1.enum(ORG_DOMAIN_JOIN_POLICIES) }).strict();
23468
+ z$1.object({ policy: z$1.enum(["off", "suggest"]) }).strict();
22733
23469
  const QueryPaginate = z$1.object({
22734
23470
  pageSize: z$1.coerce.number().int().positive().prefault(5),
22735
23471
  pageNumber: z$1.coerce.number().int().positive().prefault(1),
@@ -23027,6 +23763,9 @@ const chatMessageResponseSchema = z$2.object(passthroughShape({
23027
23763
  generationJobs: true,
23028
23764
  agentVideoClipsClaimed: true,
23029
23765
  agentMusicTracksClaimed: true,
23766
+ agentImagesClaimed: true,
23767
+ agentSpeechClipsClaimed: true,
23768
+ agentSoundEffectsClaimed: true,
23030
23769
  oob: true,
23031
23770
  promptMeta: true,
23032
23771
  status: true,
@@ -23956,7 +24695,8 @@ const researchConfigResponseSchema = z$2.object({
23956
24695
  blockedDomains: true,
23957
24696
  minRelevance: true,
23958
24697
  costCeilingMicroUsd: true,
23959
- proposedTags: true
24698
+ proposedTags: true,
24699
+ itemRules: true
23960
24700
  }),
23961
24701
  feedStatus: passthroughField
23962
24702
  });
@@ -24201,6 +24941,16 @@ z$1.object({
24201
24941
  z$1.boolean()
24202
24942
  ])).refine((v) => JSON.stringify(v).length <= 1024, "metadata must be ≤ 1KB serialized").optional()
24203
24943
  });
24944
+ z$1.object({
24945
+ allowedProviders: z$1.array(z$1.nativeEnum(ModelBackend)).min(1).max(50).nullable().default(null),
24946
+ allowedModels: z$1.array(z$1.string().trim().min(1).max(200)).min(1).max(500).nullable().default(null),
24947
+ allowedTools: z$1.array(b4mLLMTools).max(100).nullable().default(null)
24948
+ }).strict().extend({
24949
+ allowedProviders: z$1.array(z$1.string().min(1).max(200)).min(1).max(50).nullable().default(null),
24950
+ allowedTools: z$1.array(z$1.string().min(1).max(200)).max(100).nullable().default(null)
24951
+ });
24952
+ new Set(b4mLLMTools.options);
24953
+ DATA_LAKE_TOOL_NAMES.filter((name) => name !== "save_content_to_data_lake");
24204
24954
  /**
24205
24955
  * Public wire schema for the caller's spendable balance. Served on its own by
24206
24956
  * `GET /api/v1/credits` and embedded as `credits` in `GET /api/v1/me`, so the two
@@ -24407,11 +25157,59 @@ const ClientConfigModelsSchema = z$1.object({
24407
25157
  /** Every model the caller can use right now - the same list `GET /api/v1/models` pages through. */
24408
25158
  available: z$1.array(PublicModelSchema)
24409
25159
  });
25160
+ const ClientConfigPublicSchema = z$1.object({
25161
+ api_url: z$1.string(),
25162
+ default_theme: z$1.string(),
25163
+ allow_open_registration: z$1.boolean(),
25164
+ pyodide_base_url: z$1.string(),
25165
+ allow_trusted_devices: z$1.boolean(),
25166
+ turnstile_site_key: z$1.string(),
25167
+ apple_sign_in_enabled: z$1.boolean(),
25168
+ support_email: z$1.string()
25169
+ });
25170
+ const ClientConfigPickerModelSchema = PublicModelSchema.extend({
25171
+ max_output_tokens_derived: z$1.boolean().optional(),
25172
+ thinking_style: z$1.enum(["legacy", "adaptive"]).optional(),
25173
+ thinking_always_on: z$1.literal(true).optional(),
25174
+ openai_reasoning_effort: z$1.literal(true).optional(),
25175
+ effort_incompatible_with_tools: z$1.boolean().optional(),
25176
+ supports_image_variation: z$1.boolean(),
25177
+ supports_safety_tolerance: z$1.boolean().optional(),
25178
+ training_cutoff: z$1.string().optional(),
25179
+ release_date: z$1.string().optional(),
25180
+ is_superseded: z$1.boolean().optional(),
25181
+ is_slow_model: z$1.boolean().optional(),
25182
+ disabled: z$1.boolean().optional(),
25183
+ disabled_reason: z$1.string().optional(),
25184
+ access: z$1.object({
25185
+ locked: z$1.literal(true),
25186
+ reason: z$1.enum(["requires_paid_plan", "org_policy"])
25187
+ }).optional()
25188
+ });
25189
+ const ClientConfigCatalogSchema = z$1.object({
25190
+ /** Includes disabled and speech-to-text entries, in legacy picker order. */
25191
+ models: z$1.array(ClientConfigPickerModelSchema),
25192
+ locked_models: z$1.array(ClientConfigPickerModelSchema),
25193
+ superseded_models: z$1.array(z$1.object({
25194
+ id: z$1.string(),
25195
+ name: z$1.string(),
25196
+ replacement_id: z$1.string(),
25197
+ replacement_name: z$1.string()
25198
+ })),
25199
+ model_list_revision: z$1.string().nullable(),
25200
+ catalog_unavailable: z$1.boolean()
25201
+ });
24410
25202
  const ClientConfigResponseSchema = z$1.object({
24411
25203
  server: ClientConfigServerSchema,
24412
25204
  features: ClientConfigFeaturesSchema,
24413
25205
  limits: ClientConfigLimitsSchema,
24414
- models: ClientConfigModelsSchema
25206
+ models: ClientConfigModelsSchema,
25207
+ public_config: ClientConfigPublicSchema.optional(),
25208
+ transport: z$1.object({
25209
+ websocket_url: z$1.string(),
25210
+ sse_completions_url: z$1.string()
25211
+ }).optional(),
25212
+ catalog: ClientConfigCatalogSchema.optional()
24415
25213
  });
24416
25214
  /**
24417
25215
  * Wire schemas for the device push-token endpoints (`/api/v1/push-tokens`).
@@ -24421,7 +25219,7 @@ const ClientConfigResponseSchema = z$1.object({
24421
25219
  * first-party client's pinned payload.
24422
25220
  */
24423
25221
  const PUSH_TOKEN_KINDS = ["device", "liveActivity"];
24424
- const PUSH_TOKEN_PLATFORMS = ["ios"];
25222
+ const PUSH_TOKEN_PLATFORMS = ["ios", "android"];
24425
25223
  const PUSH_TOKEN_ENVIRONMENTS = ["sandbox", "production"];
24426
25224
  const MAX_TOKEN_LENGTH = 4096;
24427
25225
  const MAX_LABEL_LENGTH = 256;
@@ -24431,7 +25229,10 @@ const PushTokenRegisterRequestSchema = z$1.object({
24431
25229
  /** `device` is a per-install token; `liveActivity` is scoped to one activity. */
24432
25230
  kind: z$1.enum(PUSH_TOKEN_KINDS),
24433
25231
  platform: z$1.enum(PUSH_TOKEN_PLATFORMS),
24434
- /** Which push gateway the token was issued for; a token only works against its own. */
25232
+ /**
25233
+ * Which APNs gateway the token was issued for; a token only works against its own. Android (FCM) has
25234
+ * no such split: the value is stored but not used, and clients send `production`.
25235
+ */
24435
25236
  environment: z$1.enum(PUSH_TOKEN_ENVIRONMENTS),
24436
25237
  /** Live activity tokens: the activity the token drives. */
24437
25238
  activityId: z$1.string().min(1).max(MAX_LABEL_LENGTH).optional(),
@@ -26466,6 +27267,51 @@ const GenerateImageResponseSchema = z$1.object({
26466
27267
  promptWasEnhanced: z$1.boolean(),
26467
27268
  intent: PromptIntentSchema
26468
27269
  });
27270
+ /**
27271
+ * The public projection of IMAGE_MODEL_CATALOG served by `GET /api/v1/image-models` (built by toPublicImageModel in
27272
+ * @bike4mind/server-utils/imageGenerations/listUsableImageModels). Wire fields are snake_case (CONVENTIONS.md
27273
+ * section 2), as on video_model and music_model.
27274
+ */
27275
+ const AspectRatioCapabilitySchema = z$1.discriminatedUnion("kind", [z$1.object({
27276
+ kind: z$1.literal("discrete"),
27277
+ values: z$1.array(z$1.string())
27278
+ }), z$1.object({
27279
+ kind: z$1.literal("range"),
27280
+ tallest: z$1.string().describe("The tallest `W:H` ratio accepted."),
27281
+ widest: z$1.string().describe("The widest `W:H` ratio accepted; every ratio between the two is accepted.")
27282
+ })]);
27283
+ const ImageModeCapabilitiesSchema = z$1.object({
27284
+ input_roles: z$1.array(z$1.object({
27285
+ role: z$1.string(),
27286
+ max: z$1.number().int().positive(),
27287
+ required: z$1.boolean()
27288
+ })).describe(`The input image roles this mode accepts, the most of each, and whether one is required. Roles today: ${IMAGE_INPUT_ROLES.join(", ")}; ignore any you do not know.`),
27289
+ max_outputs: z$1.number().int().positive().describe("The most images one request renders in this mode."),
27290
+ aspect_ratios: AspectRatioCapabilitySchema.nullable().describe("null when the mode takes no `aspect_ratio`."),
27291
+ output_formats: z$1.array(z$1.string()).describe("Accepted output formats; empty when none can be chosen and the provider default comes back.")
27292
+ });
27293
+ const ImageModelSchema = z$1.object({
27294
+ id: z$1.string(),
27295
+ object: z$1.literal("image_model"),
27296
+ display_name: z$1.string(),
27297
+ provider: z$1.string(),
27298
+ provider_label: z$1.string().describe("The provider as shown to people (`OpenAI`, `Black Forest Labs`). Display text."),
27299
+ blurb: z$1.string().describe("One line on what the model is best at. Display text; may change."),
27300
+ tier: z$1.enum(MODEL_TIERS).describe("The model's quality class within its provider's line-up, best first. Not a price band."),
27301
+ released_at: z$1.string().describe("The provider's release date, `YYYY-MM-DD`."),
27302
+ preview: z$1.boolean().describe("Labelled preview by its provider: may change or be retired at short notice."),
27303
+ modes: z$1.object({
27304
+ generate: ImageModeCapabilitiesSchema.optional(),
27305
+ edit: ImageModeCapabilitiesSchema.optional()
27306
+ }).describe("What the model honours in each mode; a mode is offered exactly when it has an entry."),
27307
+ sizing: PublicImageSizingSchema,
27308
+ qualities: z$1.array(OpenAIImageQualitySchema).describe("Accepted `quality` tiers; empty when it takes none."),
27309
+ transparent_background: z$1.boolean().describe("Whether `background: 'transparent'` yields real alpha."),
27310
+ seed: z$1.boolean(),
27311
+ credits_per_image: z$1.number().nullable().describe("Credits for one image at the model's default quality and size with no input images; null when unpriced. Quality, size and input images change the price."),
27312
+ deprecation_date: z$1.string().nullable().describe("`YYYY-MM-DD`; null when no retirement is scheduled.")
27313
+ });
27314
+ const ListImageModelsResponseSchema = z$1.object({ models: z$1.array(ImageModelSchema).describe("Best first for a plain text-to-image request: generally available before preview, then flagship tier first, then newest release first.") });
26469
27315
  const VIDEO_GENERATION_API_ERROR_CODES = [
26470
27316
  ...VIDEO_VALIDATION_ERROR_CODES,
26471
27317
  "invalid_request",
@@ -26489,7 +27335,7 @@ const VideoGenerationErrorResponseSchema = ApiErrorSchema.extend({ errorCode: z$
26489
27335
  const CreateVideoGenerationBodySchema = z$1.strictObject({
26490
27336
  model: ModelIdSchema.describe("A model id from GET /api/v1/video-models."),
26491
27337
  prompt: z$1.string().min(1).max(4e3),
26492
- mode: z$1.enum(VIDEO_MODES).optional().describe("Defaults to image_to_video when a first_frame input (or input_image_file_id) is set, else text_to_video."),
27338
+ mode: z$1.enum(VIDEO_MODES).optional().describe("Defaults to image_to_video when keyframes, a first_frame input or input_image_file_id is set, else text_to_video."),
26493
27339
  duration_seconds: z$1.number().positive().optional().describe("Defaults to the model's default duration."),
26494
27340
  aspect_ratio: z$1.enum(ASPECT_RATIOS).optional(),
26495
27341
  resolution: z$1.enum(RESOLUTION_TIERS).optional(),
@@ -26499,6 +27345,11 @@ const CreateVideoGenerationBodySchema = z$1.strictObject({
26499
27345
  })).max(8).optional().describe("Image files you own, each tagged with what it is for. image_to_video needs a first_frame. The roles a model accepts, and how many of each, are its input_roles in GET /api/v1/video-models."),
26500
27346
  input_image_file_id: z$1.string().min(1).optional().describe("Deprecated: send inputs with role first_frame instead. Cannot be combined with inputs."),
26501
27347
  audio: z$1.boolean().optional(),
27348
+ keyframes: z$1.array(z$1.strictObject({
27349
+ file_id: z$1.string().min(1),
27350
+ time_seconds: z$1.number().nonnegative()
27351
+ })).min(1).max(100).optional().describe("Owned image files pinned to timestamps, in strictly increasing order starting at 0 and not exceeding duration_seconds. Cannot be combined with inputs or input_image_file_id. Requires model keyframes support; its max limits the count (FLUX 3: 10). Keyframe image mode is admitted separately from modes."),
27352
+ draft: z$1.boolean().optional().describe("Generate a lower-cost preview when true; omitted or false requests full quality. Requires model draft support at the requested resolution. FLUX 3 drafts require 720p and cost $0.06 per second."),
26502
27353
  organization_id: BillingOrganizationIdSchema
26503
27354
  });
26504
27355
  const VIDEO_OUTPUT_AVAILABILITIES = GENERATION_OUTPUT_AVAILABILITIES;
@@ -26512,6 +27363,7 @@ const VideoGenerationSchema = z$1.object({
26512
27363
  duration_seconds: z$1.number(),
26513
27364
  aspect_ratio: z$1.enum(ASPECT_RATIOS),
26514
27365
  resolution: z$1.enum(RESOLUTION_TIERS),
27366
+ draft: z$1.boolean().optional().describe("Whether this job requested draft quality; absent for requests that omitted draft."),
26515
27367
  source: z$1.enum(GENERATION_JOB_SOURCES),
26516
27368
  progress: z$1.number().min(0).max(1).nullable(),
26517
27369
  error: z$1.object({
@@ -26566,6 +27418,11 @@ const VideoModelSchema = z$1.object({
26566
27418
  "optional",
26567
27419
  "none"
26568
27420
  ]),
27421
+ keyframes: z$1.object({ max: z$1.number().int().positive() }).nullable().optional().describe("Timestamped keyframe limit; null when unsupported."),
27422
+ draft: z$1.object({
27423
+ resolutions: z$1.array(z$1.enum(RESOLUTION_TIERS)),
27424
+ credits_per_second: z$1.number()
27425
+ }).nullable().optional().describe("Draft resolutions and price; null when unsupported."),
26569
27426
  credits_per_second: z$1.record(z$1.string(), z$1.number()).nullable().describe("Credits per second of output by resolution; null for per-clip priced models."),
26570
27427
  deprecation_date: z$1.string().nullable()
26571
27428
  });
@@ -26670,6 +27527,126 @@ const ListMusicGenerationsQuerySchema = PaginationQuerySchema.extend({
26670
27527
  });
26671
27528
  const ListMusicGenerationsResponseSchema = paginatedResponseSchema(MusicGenerationSchema);
26672
27529
  const MusicGenerationIdParamSchema = z$1.object({ id: z$1.string().min(1) });
27530
+ const SCENE_COMPOSITION_API_ERROR_CODES = [
27531
+ "invalid_request",
27532
+ "input_file_not_found",
27533
+ "unsupported_input",
27534
+ "limit_exceeded",
27535
+ "storage_limit_exceeded",
27536
+ "idempotency_key_reused",
27537
+ "invalid_idempotency_key",
27538
+ "not_cancellable"
27539
+ ];
27540
+ const SCENE_JOB_PUBLIC_ERROR_CODES = [
27541
+ "unsupported_input",
27542
+ "provider_timeout",
27543
+ "provider_error",
27544
+ "output_too_large",
27545
+ "cancelled"
27546
+ ];
27547
+ const SceneCompositionErrorResponseSchema = ApiErrorSchema.extend({ errorCode: z$1.enum(SCENE_COMPOSITION_API_ERROR_CODES).optional() });
27548
+ const fileIdField = (what) => z$1.string().regex(/^[0-9a-fA-F]{24}$/).describe(`${what} One of your own files (GET /api/v1/files).`);
27549
+ const fadeField = (which, fallback) => z$1.number().min(0).max(10).optional().describe(`Seconds of audio fade-${which}, 0 to 10. Defaults to ${fallback}.`);
27550
+ const CreateSceneCompositionBodySchema = z$1.strictObject({
27551
+ video_file_id: fileIdField(`The picture: a video file of at most 300 seconds. The Scene runs exactly as long as it, and its video stream is copied unchanged (any audio it has is replaced).`),
27552
+ audio_file_id: fileIdField("The soundtrack: an audio file, e.g. a music generation output."),
27553
+ audio: z$1.strictObject({
27554
+ fit: z$1.enum(SCENE_AUDIO_FITS).optional().describe("`trim` (default): cut the audio where the video ends. `loop`: repeat the audio until the video ends."),
27555
+ fade_in_seconds: fadeField("in", 0),
27556
+ fade_out_seconds: fadeField("out", SCENE_DEFAULT_FADE_OUT_SECONDS)
27557
+ }).optional().describe("How the soundtrack is fitted to the video. Omitted, it is trimmed with a short fade-out."),
27558
+ cover_file_id: fileIdField("Optional cover art: an image file, embedded as the Scene thumbnail.").optional(),
27559
+ title: z$1.string().min(1).max(200).optional().describe("A name for the Scene; it also names the saved file.")
27560
+ });
27561
+ const SceneCompositionSchema = z$1.object({
27562
+ id: z$1.string(),
27563
+ object: z$1.literal("scene_composition"),
27564
+ state: z$1.enum(GENERATION_JOB_STATES),
27565
+ video_file_id: z$1.string(),
27566
+ audio_file_id: z$1.string(),
27567
+ cover_file_id: z$1.string().nullable(),
27568
+ title: z$1.string().nullable(),
27569
+ audio: z$1.object({
27570
+ fit: z$1.enum(SCENE_AUDIO_FITS),
27571
+ fade_in_seconds: z$1.number(),
27572
+ fade_out_seconds: z$1.number()
27573
+ }),
27574
+ source: z$1.enum(GENERATION_JOB_SOURCES),
27575
+ error: z$1.object({
27576
+ code: z$1.enum(SCENE_JOB_PUBLIC_ERROR_CODES),
27577
+ message: z$1.string()
27578
+ }).nullable(),
27579
+ output: z$1.object({
27580
+ availability: z$1.enum(GENERATION_OUTPUT_AVAILABILITIES).describe("`ready`: url is set. `pending_scan`: the saved file is still being scanned; re-fetch the job until it changes (self-hosted installs can stay here for up to ~30 minutes). `unavailable`: the file was blocked by the scan or deleted and url will never be set; stop polling."),
27581
+ url: z$1.string().nullable().describe("Signed download URL, valid until expires_at; re-fetch the job for a fresh one. Set only when availability is `ready`, otherwise null."),
27582
+ expires_at: z$1.string().nullable().describe("ISO 8601. When url stops working; null whenever url is."),
27583
+ content_type: z$1.string(),
27584
+ duration_seconds: z$1.number().describe("The length of the Scene, which is the length of its video."),
27585
+ file_id: z$1.string().nullable().describe("The Files entry, or null when the Scene was stored outside Files.")
27586
+ }).nullable(),
27587
+ credits: z$1.object({
27588
+ reserved: z$1.number().nullable(),
27589
+ settled: z$1.number().nullable()
27590
+ }).describe("Composing a Scene is free: nothing is reserved, and `settled` is 0 once the job ends."),
27591
+ created_at: z$1.string(),
27592
+ updated_at: z$1.string()
27593
+ });
27594
+ const ListSceneCompositionsQuerySchema = PaginationQuerySchema.extend({
27595
+ state: z$1.enum(GENERATION_JOB_STATES).optional(),
27596
+ source: z$1.enum(GENERATION_JOB_SOURCES).optional()
27597
+ });
27598
+ const ListSceneCompositionsResponseSchema = paginatedResponseSchema(SceneCompositionSchema);
27599
+ const SceneCompositionIdParamSchema = z$1.object({ id: z$1.string().min(1) });
27600
+ /** Published in the contract description so the limits are stated in one place. */
27601
+ const SCENE_COMPOSITION_LIMITS_DESCRIPTION = `The video may run at most 300 seconds, and the input files together may total at most ${SCENE_MAX_INPUT_BYTES / 1048576} MB.`;
27602
+ const AUDIO_JOB_PUBLIC_ERROR_CODES = [
27603
+ "content_blocked",
27604
+ "provider_timeout",
27605
+ "provider_error",
27606
+ "output_too_large",
27607
+ "cancelled"
27608
+ ];
27609
+ const audioJobOutputSchema = z$1.object({
27610
+ availability: z$1.enum(GENERATION_OUTPUT_AVAILABILITIES).describe("`ready`: url is set. `pending_scan`: the saved file is still being scanned. `unavailable`: the file was blocked by the scan or deleted and url will never be set."),
27611
+ url: z$1.string().nullable().describe("Signed download URL, valid until expires_at. Set only when availability is `ready`, otherwise null."),
27612
+ expires_at: z$1.string().nullable().describe("ISO 8601. When url stops working; null whenever url is."),
27613
+ content_type: z$1.string(),
27614
+ duration_seconds: z$1.number().nullable().describe("The length of the clip, or null when it could not be measured."),
27615
+ file_id: z$1.string().nullable().describe("The Files entry, or null when the clip was stored outside Files.")
27616
+ });
27617
+ const audioJobTrailingFields = {
27618
+ source: z$1.enum(GENERATION_JOB_SOURCES),
27619
+ error: z$1.object({
27620
+ code: z$1.enum(AUDIO_JOB_PUBLIC_ERROR_CODES),
27621
+ message: z$1.string()
27622
+ }).nullable(),
27623
+ output: audioJobOutputSchema.nullable(),
27624
+ credits: z$1.object({
27625
+ reserved: z$1.number().nullable(),
27626
+ settled: z$1.number().nullable()
27627
+ }),
27628
+ created_at: z$1.string(),
27629
+ updated_at: z$1.string()
27630
+ };
27631
+ const SpeechGenerationSchema = z$1.object({
27632
+ id: z$1.string(),
27633
+ object: z$1.literal("speech_generation"),
27634
+ state: z$1.enum(GENERATION_JOB_STATES),
27635
+ text: z$1.string(),
27636
+ provider: supportedVoiceGenerationVendor.describe("The provider asked for, with the default applied."),
27637
+ model: z$1.string().nullable().describe("The model you sent, or null for the provider default."),
27638
+ voice: z$1.string().nullable().describe("The voice you sent, or null for the default."),
27639
+ ...audioJobTrailingFields
27640
+ });
27641
+ const SoundEffectGenerationSchema = z$1.object({
27642
+ id: z$1.string(),
27643
+ object: z$1.literal("sound_effect_generation"),
27644
+ state: z$1.enum(GENERATION_JOB_STATES),
27645
+ text: z$1.string(),
27646
+ provider: supportedSoundGenerationVendor,
27647
+ duration_seconds: z$1.number().nullable().describe("The length requested, or null to let the provider choose."),
27648
+ ...audioJobTrailingFields
27649
+ });
26673
27650
  /**
26674
27651
  * Wire schemas for the public `/api/v1/voice/*` contracts (api-contract/contracts/voice.contract.ts).
26675
27652
  * The legacy `/api/voice/v2/*` paths serve the same handlers, so these shapes are also what the SPA
@@ -26791,13 +27768,14 @@ function assertValidDeprecation(operationId, { since, sunset }) {
26791
27768
  const EXAMPLE_RESOURCE_ID = "664f1c2b9a1e4d0012ab34cd";
26792
27769
  const EXAMPLE_SESSION_ID = "664f1c2b9a1e4d0012ab34aa";
26793
27770
  const EXAMPLE_FILE_ID = "664f1c2b9a1e4d0012ab34bb";
27771
+ const EXAMPLE_SECOND_FILE_ID = "664f1c2b9a1e4d0012ab34ee";
26794
27772
  const EXAMPLE_USER_ID = "507f1f77bcf86cd799439011";
26795
27773
  defineEndpoint({
26796
27774
  method: "post",
26797
27775
  path: "/api/chat",
26798
27776
  operationId: "sendChatMessage",
26799
27777
  summary: "Send a chat message",
26800
- description: "Sends a message to the AI and creates a quest to process it. By default (async) the call returns immediately with a quest id; poll `GET /api/v1/quests/{id}` for the reply. Send `wait: true` to block until the reply is ready and receive it inline. A `wait: true` turn is bounded at about 45 seconds: one that runs longer is ended (unused credits refunded) and answered with a 504 naming the quest in `quest_id`; one whose reasoning model spends its whole output budget thinking is answered with a 422 or 502 (see those responses). Send long or tool-heavy turns (large attachments, tool calls) in the default async mode and poll instead. A tool that produced machine-readable state reports it under `toolPayloads` - an array of `{ type, payload }` entries in emission order, alongside (never instead of) the prose reply - on the `wait: true` body and on the polled quest. A turn can FAIL after the ACK - reported on the polled quest as `type: \"error\"`, since the ACK was already sent. A terminal `status: \"stopped\"` (a missing session, a user-cancelled turn) is ALSO a failure even without `type: \"error\"` - it carries an explanatory string in `reply`/`replies` rather than an answer. `type` is the failure signal for the classified failure classes (an abort, a provider timeout, credit exhaustion); `errorCode` is an optional refinement present only when the failure is a classified billing reason. A recovered stuck quest is NOT in that list: one that still has renderable content resolves as a success by design. `QUEST_ERROR_CODES` has two members, but only `insufficient_credits` is raised as a quest errorCode by any current throw site on this endpoint - `spend_cap_exceeded` is thrown only by the embed chat route's pre-flight, which fires outside the process try/catch that would classify it onto a quest. A caller must treat `type: \"error\"` OR a terminal `status: \"stopped\"` as failure even when `errorCode` is absent, and must not read `reply` as an answer without checking those first. Authenticate with an API key (`b4m_live_`) or a JWT. Session resolution: pass `sessionId` to continue an existing notebook. An API-key caller that omits it gets a BRAND-NEW notebook rather than the notebook the human last had open, and `newConversation: true` forces a new notebook for any auth mode; both return the new id as `sessionId`, so the caller can continue the conversation by passing it back. A first-party JWT caller that omits `sessionId` keeps the last-opened-notebook fallback. Sending `sessionId` and `newConversation` together is a 422.",
27778
+ description: "Sends a message to the AI and creates a quest to process it. By default (async) the call returns immediately with a quest id; poll `GET /api/v1/quests/{id}` for the reply. Send `wait: true` to block until the reply is ready and receive it inline. A `wait: true` turn is bounded at about 45 seconds: one that runs longer is ended (unused credits refunded) and answered with a 504 naming the quest in `quest_id`; one whose reasoning model spends its whole output budget thinking is answered with a 422 or 502 (see those responses). Send long or tool-heavy turns (large attachments, tool calls) in the default async mode and poll instead. A tool that produced machine-readable state reports it under `toolPayloads` - an array of `{ type, payload }` entries in emission order, alongside (never instead of) the prose reply - on the `wait: true` body and on the polled quest. A turn can FAIL after the ACK - reported on the polled quest as `type: \"error\"`, since the ACK was already sent. A terminal `status: \"stopped\"` (a missing session, a user-cancelled turn) is ALSO a failure even without `type: \"error\"` - it carries an explanatory string in `reply`/`replies` rather than an answer. `type` is the failure signal for the classified failure classes (an abort, a provider timeout, credit exhaustion); `errorCode` is an optional refinement present only when the failure has a classified reason. A recovered stuck quest is NOT in that list: one that still has renderable content resolves as a success by design. `QUEST_ERROR_CODES` has three members: `insufficient_credits`, `spend_cap_exceeded`, and `free_quest_limit_reached`. A new exhausted QuestMaster start is refused synchronously with 403 before a quest exists; an older queued start can instead settle as an error quest with `free_quest_limit_reached`. `spend_cap_exceeded` is thrown only by the embed chat route's pre-flight, which fires outside the process try/catch that would classify it onto a quest. A caller must treat `type: \"error\"` OR a terminal `status: \"stopped\"` as failure even when `errorCode` is absent, and must not read `reply` as an answer without checking those first. Organization-policy preflight refusals use 403 with `errorCode: \"org_model_not_allowed\"` or `\"org_tool_not_allowed\"`. An explicit-model JWT request can instead be accepted and refused during quest execution: that refusal appears on the 200 `wait: true` body or polled quest as `type: \"error\"`, without a policy `errorCode`. Check the quest outcome as described above. Authenticate with an API key (`b4m_live_`) or a JWT. Session resolution: pass `sessionId` to continue an existing notebook. An API-key caller that omits it gets a BRAND-NEW notebook rather than the notebook the human last had open, and `newConversation: true` forces a new notebook for any auth mode; both return the new id as `sessionId`, so the caller can continue the conversation by passing it back. A first-party JWT caller that omits `sessionId` keeps the last-opened-notebook fallback. Sending `sessionId` and `newConversation` together is a 422.",
26801
27779
  tags: ["AI"],
26802
27780
  auth: "apiKeyOrJwt",
26803
27781
  scopes: ["ai:chat", "ai:generate"],
@@ -26809,11 +27787,11 @@ defineEndpoint({
26809
27787
  emitsRateLimitHeaders: true,
26810
27788
  responses: {
26811
27789
  200: {
26812
- description: "Message accepted - NOT a completed turn. The default (async) path returns this queued ACK; the outcome arrives on `GET /api/v1/quests/{id}` (see the `sendChatMessage200PollResult` schema). With `wait: true` the body is instead the completed turn: the ACK fields plus the reply (`response`/`responses`), `toolPayloads`, `createdAt`, `performance` timings and, when requested, `promptDetails`/`promptText`. A turn that FAILS still resolves with `200`, never a 4xx, on both that `wait: true` body and the polled quest (`GET /api/v1/quests/{id}`) - the prose explaining why lands in `reply`/`response` like any other answer, so the reply text alone cannot tell a failure from an answer. `type` is the field that can: both surfaces carry it unconditionally, so match on `type: \"error\"` first - it covers credit exhaustion, a provider timeout or overload, and an in-process aborted turn; a real answer carries the turn's actual completion type instead (`\"message\"` for an ordinary reply). Two related states do NOT set `type: \"error\"`: a user-cancelled turn resolves as `status: \"stopped\"` with `type` left at `\"message\"`, and a recovered stuck quest that still has renderable content resolves as a success (`status: \"done\"`, no error) by design, to avoid destroying content to report a failure. The one exception is output-budget exhaustion: a `wait: true` request answers it with the 422 or 502 error envelope (plus `quest_id`) instead of this body. `errorCode` then names the failure reason, but only for the billing failures that have one - `\"insufficient_credits\"` today; it is absent on every other `type: \"error\"` turn, so never use its absence to infer success. On a real answer `errorCode` is absent from the `wait: true` body. The body also carries `sessionId`, the notebook the turn was recorded in - for an API-key caller that sent none (or any caller sending `newConversation: true`), that is the freshly created notebook's id; pass it back as the request's `sessionId` to continue. Contrast the tts/music/soundEffects contracts, which reject synchronously with a 422 carrying the same `errorCode` vocabulary.",
27790
+ description: "Message accepted - NOT a completed turn. The default (async) path returns this queued ACK; the outcome arrives on `GET /api/v1/quests/{id}` (see the `sendChatMessage200PollResult` schema). With `wait: true` the body is instead the completed turn: the ACK fields plus the reply (`response`/`responses`), `toolPayloads`, `createdAt`, `performance` timings and, when requested, `promptDetails`/`promptText`. A turn that FAILS still resolves with `200`, never a 4xx, on both that `wait: true` body and the polled quest (`GET /api/v1/quests/{id}`) - the prose explaining why lands in `reply`/`response` like any other answer, so the reply text alone cannot tell a failure from an answer. `type` is the field that can: both surfaces carry it unconditionally, so match on `type: \"error\"` first - it covers credit exhaustion, a provider timeout or overload, and an in-process aborted turn; a real answer carries the turn's actual completion type instead (`\"message\"` for an ordinary reply). Two related states do NOT set `type: \"error\"`: a user-cancelled turn resolves as `status: \"stopped\"` with `type` left at `\"message\"`, and a recovered stuck quest that still has renderable content resolves as a success (`status: \"done\"`, no error) by design, to avoid destroying content to report a failure. The one exception is output-budget exhaustion: a `wait: true` request answers it with the 422 or 502 error envelope (plus `quest_id`) instead of this body. `errorCode` names a classified failure: `insufficient_credits`, or `free_quest_limit_reached` when an older queued QuestMaster start is refused during processing. A new exhausted start is refused synchronously with 403 before a quest exists. Other `type: \"error\"` turns may have no classifier, so never use its absence to infer success. On a real answer `errorCode` is absent from the `wait: true` body. The body also carries `sessionId`, the notebook the turn was recorded in - for an API-key caller that sent none (or any caller sending `newConversation: true`), that is the freshly created notebook's id; pass it back as the request's `sessionId` to continue. Contrast the tts/music/soundEffects contracts, which reject synchronously with a 422 carrying the same `errorCode` vocabulary.",
26813
27791
  schema: z$1.union([ChatWaitResponseSchema, ChatAckSchema]),
26814
27792
  pollResult: {
26815
27793
  schema: ChatQuestPollResultSchema,
26816
- description: "Outcome fields of the quest polled at `GET /api/v1/quests/{id}` after this ACK. A finished turn that failed is `status: \"done\"` with `type: \"error\"` and the failure text in `reply`, so a caller reading `reply` alone cannot tell a failure from an answer - check `type` first, and also treat a terminal `status: \"stopped\"` (a missing session, a user-cancelled turn) as failure even though it never sets `type`. `errorCode` is an optional refinement of `type: \"error\"`, present only for a classified billing failure; credit exhaustion arrives here as `insufficient_credits`, the same vocabulary the synchronous 422s on `/api/ai/music`, `/api/ai/sound-effects` and `/api/ai/tts` use. `QUEST_ERROR_CODES` publishes a second member, `spend_cap_exceeded`, but no current throw site on this endpoint raises it as a quest errorCode: its only one, the embed chat route's pre-flight 422, fires outside the process try/catch that would classify it onto the quest. Most `type: \"error\"` turns - an abort, a provider timeout or overload - have NO `errorCode`; its absence does not mean success, only that the failure is unclassified. A recovered stuck quest that still has renderable content is not a failure at all: it keeps `type: \"message\"` even though it did not finish, so a caller gets the content rather than an error. `fallbackInfo` is present only when the requested model failed and another model produced the reply: `fallbackModel` answered, `primaryModel` is what was asked for, and `reason` is the error from the first failed attempt on the requested model. The poll body carries further fields not modelled here, including `images`, `files`, `toolPayloads`, `promptMeta`, and the attachment report (`attachmentNotices`/`attachmentDelivery`) - only the outcome subset is modelled here.",
27794
+ description: "Outcome fields of the quest polled at `GET /api/v1/quests/{id}` after this ACK. A finished turn that failed is `status: \"done\"` with `type: \"error\"` and the failure text in `reply`, so a caller reading `reply` alone cannot tell a failure from an answer - check `type` first, and also treat a terminal `status: \"stopped\"` (a missing session, a user-cancelled turn) as failure even though it never sets `type`. `errorCode` is an optional refinement of `type: \"error\"`, present only for a classified failure; credit exhaustion arrives here as `insufficient_credits`, the same vocabulary the synchronous 422s on `/api/ai/music`, `/api/ai/sound-effects` and `/api/ai/tts` use. An older queued QuestMaster start can instead settle with `free_quest_limit_reached`; new exhausted starts are refused synchronously with 403 before a quest exists. `QUEST_ERROR_CODES` has three members; its other code is `spend_cap_exceeded`, but no current throw site on this endpoint raises it as a quest errorCode: its only one, the embed chat route's pre-flight 422, fires outside the process try/catch that would classify it onto the quest. Most `type: \"error\"` turns - an abort, a provider timeout or overload - have NO `errorCode`; its absence does not mean success, only that the failure is unclassified. A recovered stuck quest that still has renderable content is not a failure at all: it keeps `type: \"message\"` even though it did not finish, so a caller gets the content rather than an error. `fallbackInfo` is present only when the requested model failed and another model produced the reply: `fallbackModel` answered, `primaryModel` is what was asked for, and `reason` is the error from the first failed attempt on the requested model. The poll body carries further fields not modelled here, including `images`, `files`, `toolPayloads`, `promptMeta`, and the attachment report (`attachmentNotices`/`attachmentDelivery`) - only the outcome subset is modelled here.",
26817
27795
  example: {
26818
27796
  id: EXAMPLE_RESOURCE_ID,
26819
27797
  status: "done",
@@ -26827,6 +27805,10 @@ defineEndpoint({
26827
27805
  description: "The request was rejected before a turn was created: a supplied `model` is unknown, disabled or not a chat model; or no usable default chat model is configured and none was supplied.",
26828
27806
  schema: ApiErrorSchema
26829
27807
  },
27808
+ 403: {
27809
+ description: "The API key does not hold any of the required scopes, the account is suspended (`errorCode: \"account_suspended\"`), a free-tier account named a model outside the free-tier allowlist (`errorCode: \"model_requires_subscription\"`), a free account already started its QuestMaster quest (`errorCode: \"free_quest_limit_reached\"`), organization-policy preflight refuses the model (`errorCode: \"org_model_not_allowed\"`), or an API-key caller named a built-in tool the organization does not allow (`errorCode: \"org_tool_not_allowed\"`).",
27810
+ schema: ChatForbiddenErrorSchema
27811
+ },
26830
27812
  404: {
26831
27813
  description: "No notebook/session exists to attach the message to.",
26832
27814
  schema: ApiErrorSchema
@@ -26882,7 +27864,7 @@ defineEndpoint({
26882
27864
  schema: ApiErrorSchema
26883
27865
  },
26884
27866
  403: {
26885
- description: `The API key holds neither the \`ai:chat\` nor the \`ai:generate\` scope, or an organization-billed API key names any organization but its own (\`errorCode: ${BILLING_ORGANIZATION_MISMATCH_ERROR_CODE}\`), or a non-admin caller sent \`confidence_overrides\`.`,
27867
+ description: `The API key holds neither the \`ai:chat\` nor the \`ai:generate\` scope, or an organization-billed API key names any organization but its own (\`errorCode: ${BILLING_ORGANIZATION_MISMATCH_ERROR_CODE}\`), or a non-admin caller sent \`confidence_overrides\`, or an API-key caller named built-in \`tools\` the billed organization does not allow (\`errorCode: ${ORG_TOOL_NOT_ALLOWED_ERROR_CODE}\`).`,
26886
27868
  schema: BillingOrganizationForbiddenErrorSchema
26887
27869
  },
26888
27870
  404: {
@@ -27094,7 +28076,7 @@ defineEndpoint({
27094
28076
  path: "/api/ai/v1/tools",
27095
28077
  operationId: "executeTool",
27096
28078
  summary: "Execute a server-side tool",
27097
- description: "Runs one of the built-in server-side tools (`weather_info`, `web_search`, `web_fetch`, `decide`) and returns its result as JSON. Authenticate with a JWT access token only - API keys are NOT accepted on this endpoint. Rate-limited to 100 requests/hour per user, counted separately from other endpoints. `web_search` and `web_fetch` are billed per call from the caller's credits (or their organization's), and refused with a 422 `insufficient_credits` before the provider is called. `request_id` echoes the X-Request-ID response header.",
28079
+ description: "Runs one of the built-in server-side tools (`weather_info`, `web_search`, `web_fetch`, `decide`) and returns its result as JSON. Authenticate with a JWT access token only - API keys are NOT accepted on this endpoint. To call `web_search`, `web_fetch` or `weather_info` with an API key, use `POST /api/v1/tools/web-search`, `/api/v1/tools/web-fetch` or `/api/v1/tools/weather`. Rate-limited to 100 requests/hour per user, counted separately from other endpoints. `web_search` and `web_fetch` are billed per call from the caller's credits (or their organization's), and refused with a 422 `insufficient_credits` before the provider is called. `request_id` echoes the X-Request-ID response header.",
27098
28080
  tags: ["AI"],
27099
28081
  auth: "jwtOnly",
27100
28082
  request: ToolExecutionRequestSchema,
@@ -27149,12 +28131,166 @@ defineEndpoint({
27149
28131
  }
27150
28132
  }
27151
28133
  });
28134
+ /**
28135
+ * POST /api/v1/tools/{web-search,web-fetch,weather} - one built-in tool per call, for integrators
28136
+ * running their own agent loop.
28137
+ *
28138
+ * New /api/v1 routes rather than contracts wrapped around the SPA-internal /api/tools/* doors (which
28139
+ * the voice modal and the desktop app call): LEGACY_PUBLIC_PATHS is frozen. Both doors share their
28140
+ * implementation (apps/client/server/tools/webToolRoutes.ts), their scope gate, the outbound-action
28141
+ * gate and one hourly budget (toolRoutesRateLimit), so they cannot drift apart. The JWT-only
28142
+ * POST /api/ai/v1/tools (tools.contract.ts) is a separate surface serving the CLI.
28143
+ */
28144
+ const SCOPES$1 = ["ai:chat", "ai:generate"];
28145
+ const AUTH = "Authenticate with an API key (`b4m_live_`) carrying `ai:chat` or `ai:generate`, or a JWT. Every call counts against one hourly budget of 600 calls per user, shared by the three `/api/v1/tools/*` endpoints and the three `/api/tools/*` routes.";
28146
+ const BILLED = "Billed per call from the caller's credits (or their organization's) when the deployment's provider charges for it, and refused with a 422 `insufficient_credits` before the provider is called when the payer cannot cover it.";
28147
+ const FORBIDDEN$2 = {
28148
+ description: "The API key holds neither `ai:chat` nor `ai:generate`, or the account may not use outbound tools right now (an administrator restricted it, or it is new or unverified: `errorCode: \"account_trust_required\"`).",
28149
+ schema: ScopeForbiddenErrorSchema
28150
+ };
28151
+ const RATE_LIMITED$3 = {
28152
+ description: "Rate limit exceeded: the per-key limit, or the hourly budget shared by the tool endpoints.",
28153
+ schema: ApiErrorSchema
28154
+ };
28155
+ const BILLING_UNRESOLVED = {
28156
+ description: "The billing user or organization could not be resolved, or the API key bills an organization its owner is no longer a member of.",
28157
+ schema: ApiErrorSchema
28158
+ };
28159
+ const INSUFFICIENT_CREDITS = {
28160
+ description: "Request body failed validation, or the caller cannot afford the call (`errorCode: \"insufficient_credits\"`).",
28161
+ schema: InsufficientCreditsErrorSchema
28162
+ };
28163
+ const SEARCH_EXAMPLE = {
28164
+ query: "latest stable TypeScript release",
28165
+ num_results: 3
28166
+ };
28167
+ defineEndpoint({
28168
+ method: "post",
28169
+ path: "/api/v1/tools/web-search",
28170
+ operationId: "searchWeb",
28171
+ summary: "Search the web",
28172
+ description: "Runs one web search on the provider this deployment is configured with and returns the hits as one formatted text block (title, link and snippet per result), ready to hand to a model. When no search provider is configured, `result` says so instead of listing hits. " + BILLED + " " + AUTH,
28173
+ tags: ["Tools"],
28174
+ auth: "apiKeyOrJwt",
28175
+ scopes: SCOPES$1,
28176
+ request: WebSearchToolRequestSchema,
28177
+ requestExample: SEARCH_EXAMPLE,
28178
+ responses: {
28179
+ 200: {
28180
+ description: "The formatted search results.",
28181
+ schema: WebToolResultResponseSchema,
28182
+ example: { result: "1. TypeScript release notes\n https://example.com/release-notes\n ..." }
28183
+ },
28184
+ 400: BILLING_UNRESOLVED,
28185
+ 401: {
28186
+ description: "Missing or invalid credentials.",
28187
+ schema: ApiErrorSchema
28188
+ },
28189
+ 403: FORBIDDEN$2,
28190
+ 422: INSUFFICIENT_CREDITS,
28191
+ 429: RATE_LIMITED$3,
28192
+ 500: {
28193
+ description: "The search provider failed, or an unexpected server error.",
28194
+ schema: ApiErrorSchema
28195
+ }
28196
+ },
28197
+ emitsRateLimitHeaders: true,
28198
+ codeSample: {
28199
+ authToken: "b4m_live_<key>",
28200
+ streaming: false,
28201
+ body: SEARCH_EXAMPLE
28202
+ }
28203
+ });
28204
+ const FETCH_EXAMPLE = { url: "https://example.com/docs/getting-started" };
28205
+ defineEndpoint({
28206
+ method: "post",
28207
+ path: "/api/v1/tools/web-fetch",
28208
+ operationId: "fetchWebPage",
28209
+ summary: "Read a web page",
28210
+ description: "Fetches one public http or https page and returns its readable content as Markdown, headed by the page title when it has one. A long page is truncated, and the end of `result` says which `offset` to pass to read the next part. Private, loopback and cloud-metadata addresses are refused. " + BILLED + " " + AUTH,
28211
+ tags: ["Tools"],
28212
+ auth: "apiKeyOrJwt",
28213
+ scopes: SCOPES$1,
28214
+ request: WebFetchToolRequestSchema,
28215
+ requestExample: FETCH_EXAMPLE,
28216
+ responses: {
28217
+ 200: {
28218
+ description: "The page content as Markdown.",
28219
+ schema: WebToolResultResponseSchema,
28220
+ example: { result: "# Getting started\n\nInstall the package, then ..." }
28221
+ },
28222
+ 400: {
28223
+ description: "The URL points at an address that may not be fetched (private, loopback or cloud metadata), the billing user or organization could not be resolved, or the API key bills an organization its owner is no longer a member of.",
28224
+ schema: ApiErrorSchema
28225
+ },
28226
+ 401: {
28227
+ description: "Missing or invalid credentials.",
28228
+ schema: ApiErrorSchema
28229
+ },
28230
+ 403: FORBIDDEN$2,
28231
+ 422: {
28232
+ description: "Request body failed validation, the page cannot be read (unreachable, or a content type that is not a readable page), or the caller cannot afford the call (`errorCode: \"insufficient_credits\"`).",
28233
+ schema: InsufficientCreditsErrorSchema
28234
+ },
28235
+ 429: RATE_LIMITED$3,
28236
+ 500: {
28237
+ description: "The fetch failed, or an unexpected server error.",
28238
+ schema: ApiErrorSchema
28239
+ }
28240
+ },
28241
+ emitsRateLimitHeaders: true,
28242
+ codeSample: {
28243
+ authToken: "b4m_live_<key>",
28244
+ streaming: false,
28245
+ body: FETCH_EXAMPLE
28246
+ }
28247
+ });
28248
+ const WEATHER_EXAMPLE = {
28249
+ lat: 47.6062,
28250
+ lon: -122.3321,
28251
+ units: "metric"
28252
+ };
28253
+ defineEndpoint({
28254
+ method: "post",
28255
+ path: "/api/v1/tools/weather",
28256
+ operationId: "getCurrentWeather",
28257
+ summary: "Get the current weather",
28258
+ description: "Returns the current temperature and conditions at a coordinate as one sentence. Not billed. " + AUTH,
28259
+ tags: ["Tools"],
28260
+ auth: "apiKeyOrJwt",
28261
+ scopes: SCOPES$1,
28262
+ request: WeatherToolRequestSchema,
28263
+ requestExample: WEATHER_EXAMPLE,
28264
+ responses: {
28265
+ 200: {
28266
+ description: "The current weather as one sentence.",
28267
+ schema: WebToolResultResponseSchema,
28268
+ example: { result: "Right now it's 14° in Seattle, with light rain." }
28269
+ },
28270
+ 401: {
28271
+ description: "Missing or invalid credentials.",
28272
+ schema: ApiErrorSchema
28273
+ },
28274
+ 403: FORBIDDEN$2,
28275
+ 429: RATE_LIMITED$3,
28276
+ 500: {
28277
+ description: "The weather provider is not configured or failed, or an unexpected server error.",
28278
+ schema: ApiErrorSchema
28279
+ }
28280
+ },
28281
+ emitsRateLimitHeaders: true,
28282
+ codeSample: {
28283
+ authToken: "b4m_live_<key>",
28284
+ streaming: false,
28285
+ body: WEATHER_EXAMPLE
28286
+ }
28287
+ });
27152
28288
  defineEndpoint({
27153
28289
  method: "post",
27154
28290
  path: "/api/ai/v1/completions",
27155
28291
  operationId: "createCompletion",
27156
28292
  summary: "Create a chat completion",
27157
- description: "OpenAI-compatible completion. A successful request is ALWAYS answered with an SSE stream (`text/event-stream`), regardless of the `stream` flag: a `meta` event, then `content`/`tool_use` events carrying `usage`/`credits`, then one `settled` event once credits are committed (the charge can be 0), terminated by `data: [DONE]`. The terminal event carries `stopReason`; treat `max_tokens` as a TRUNCATED reply rather than a complete one, and note that omitting `max_tokens` on the request lets the server size the output ceiling for the model (recommended for reasoning models, which spend thinking tokens inside that ceiling). A message `content` may be a string or an array of parts; image parts are accepted in OpenAI Chat (`image_url`), OpenAI Responses (`input_image`) or Anthropic (`image` with a `source`) form and are translated to whatever the target model speaks. A final non-blank assistant message is an assistant prefill, except a server-tool continuation ending in `server_tool_use` or `tool_search_tool_result`. Plain system prompts and blank messages are ignored. Check the model's `supports_assistant_prefill` field from `GET /api/v1/models` before sending one. Authenticate with an API key (`b4m_live_`) or a JWT.\n\nRUNS AND SETTLEMENT. To group the spend of a multi-agent run (a root session and the workers it spawns), mint a run id with `POST /api/v1/completion-runs` and send it as `run` on each request. Spend is recorded against the run, never charged twice. The `settled` event (`{ type, requestId, creditsCharged, usdCost, runId }`) arrives after the last content event and before `[DONE]`, once the charge is committed: `creditsCharged` is what the ledger recorded, which can be below the terminal event's `credits.used` when the balance capped it, and `requestId` is the `X-Request-ID` you sent (or a generated one). Use it to count a settled charge once when your client sees the same event twice (replay or reconnect). Send a fresh `X-Request-ID` per request: reusing one does not deduplicate charges, since the server charges every request.\n\nTOOL SEARCH. On a model whose `GET /api/v1/models` row has `supports_tool_search: true` (`backend` `\"anthropic\"` or `\"bedrock\"`), a `tools` entry may set `toolSchema.defer_loading: true`, and a `{ \"serverTool\": { \"type\": \"tool_search_tool_regex_20251119\", \"name\": \"tool_search_tool_regex\" } }` (or the `bm25` pair) entry adds Anthropic's tool search, so deferred definitions load only when the model searches for them. The stream then carries `provider_block` events (`{ type, provider: \"anthropic\", block }`) for the server-run search; echo each block back verbatim, in order, in the assistant `messages` content of the next request, and never answer one with a `tool_result`. When the server-run search loop hits its iteration limit the stream ends with `stopReason: \"pause_turn\"`; continue by re-sending the conversation with that assistant turn's provider blocks echoed. A client-side search may return `{ \"type\": \"tool_reference\", \"tool_name\": \"...\" }` blocks inside a `tool_result`'s content. On every other model `defer_loading` is ignored (every tool is sent as usual) and a server tool, a `tool_reference` or an echoed tool search block is refused with a `400` rather than run without it.\n\nERRORS. Everything checked before the model provider is called fails with a JSON error body and a real HTTP status, before any stream opens: an empty `messages` array, a conversation with no non-empty user or assistant message (system-only, or only blank content), a malformed request, or an unknown `model` `400` (`errorCode: \"unknown_model\"` for an unknown model), a bad credential `401`, a key without a required scope `403` (with `required_scopes`), a free-tier account calling a model outside the free-tier allowlist `403` with `errorCode: \"model_requires_subscription\"` (upgrade the plan or pick a free-tier model), a body over 25 MB `413`, any other body that fails schema validation `422`, insufficient credits `422` with `errorCode: \"insufficient_credits\"` (personal or org balance, or an org per-member credit cap), a rate limit `429` with `Retry-After`, a `run` that does not exist or that another user or billing owner minted `404` with `errorCode: \"run_not_found\"`, and a catalogued model whose provider is not configured on this deployment, or a model that could only come from a self-hosted model server (Ollama, local image) that is currently unreachable, `503` with `errorCode: \"provider_not_configured\"` (retryable). A provider rejection of caller input that happens before the stream opens is also a JSON `400`, with `errorCode: \"invalid_request\"` (do not retry it unchanged). Once the stream has opened the status stays `200` and a failure arrives as one terminal in-band `error` event. Branch on that event's `code`, never on `message`, which is prose and may change: `insufficient_credits` (buy credits) when credits run out mid-generation, `invalid_request` when the provider rejects caller input (do not retry it unchanged), `provider_rejected` when the model provider refused our credentials, `content_blocked` when the model declined the request (do not retry it unchanged), `output_budget_exhausted` when a reasoning model spent your whole `max_tokens` thinking and wrote no answer (raise `max_tokens` or omit it; do not retry it unchanged), and `provider_error` for any other provider failure. Treat `code` as optional.",
28293
+ description: "OpenAI-compatible completion. A successful request is ALWAYS answered with an SSE stream (`text/event-stream`), regardless of the `stream` flag: a `meta` event, then `content`/`tool_use` events carrying `usage`/`credits`, then one `settled` event once credits are committed (the charge can be 0), terminated by `data: [DONE]`. The terminal event carries `stopReason`; treat `max_tokens` as a TRUNCATED reply rather than a complete one, and note that omitting `max_tokens` on the request lets the server size the output ceiling for the model (recommended for reasoning models, which spend thinking tokens inside that ceiling). A message `content` may be a string or an array of parts; image parts are accepted in OpenAI Chat (`image_url`), OpenAI Responses (`input_image`) or Anthropic (`image` with a `source`) form and are translated to whatever the target model speaks. A final non-blank assistant message is an assistant prefill, except a server-tool continuation ending in `server_tool_use` or `tool_search_tool_result`. Plain system prompts and blank messages are ignored. Check the model's `supports_assistant_prefill` field from `GET /api/v1/models` before sending one. Authenticate with an API key (`b4m_live_`) or a JWT.\n\nEND USERS. A key that serves many end users of your own product, and that an administrator has granted `ai:end-user-id`, may send `end_user_id` (your opaque id for the end user) so that, on models served directly by OpenAI or Anthropic, the model provider sees each end user separately rather than your whole account as one (other providers receive no end-user identifier).\n\nRUNS AND SETTLEMENT. To group the spend of a multi-agent run (a root session and the workers it spawns), mint a run id with `POST /api/v1/completion-runs` and send it as `run` on each request. Spend is recorded against the run, never charged twice. The `settled` event (`{ type, requestId, creditsCharged, usdCost, runId }`) arrives after the last content event and before `[DONE]`, once the charge is committed: `creditsCharged` is what the ledger recorded, which can be below the terminal event's `credits.used` when the balance capped it, and `requestId` is the `X-Request-ID` you sent (or a generated one). Use it to count a settled charge once when your client sees the same event twice (replay or reconnect). Send a fresh `X-Request-ID` per request: reusing one does not deduplicate charges, since the server charges every request.\n\nTOOL SEARCH. On a model whose `GET /api/v1/models` row has `supports_tool_search: true` (`backend` `\"anthropic\"` or `\"bedrock\"`), a `tools` entry may set `toolSchema.defer_loading: true`, and a `{ \"serverTool\": { \"type\": \"tool_search_tool_regex_20251119\", \"name\": \"tool_search_tool_regex\" } }` (or the `bm25` pair) entry adds Anthropic's tool search, so deferred definitions load only when the model searches for them. The stream then carries `provider_block` events (`{ type, provider: \"anthropic\", block }`) for the server-run search; echo each block back verbatim, in order, in the assistant `messages` content of the next request, and never answer one with a `tool_result`. When the server-run search loop hits its iteration limit the stream ends with `stopReason: \"pause_turn\"`; continue by re-sending the conversation with that assistant turn's provider blocks echoed. A client-side search may return `{ \"type\": \"tool_reference\", \"tool_name\": \"...\" }` blocks inside a `tool_result`'s content. On every other model `defer_loading` is ignored (every tool is sent as usual) and a server tool, a `tool_reference` or an echoed tool search block is refused with a `400` rather than run without it.\n\nERRORS. Everything checked before the model provider is called fails with a JSON error body and a real HTTP status, before any stream opens: an empty `messages` array, a conversation with no non-empty user or assistant message (system-only, or only blank content), a malformed request, or an unknown `model` `400` (`errorCode: \"unknown_model\"` for an unknown model), a bad credential `401`, a key without a required scope `403` (with `required_scopes`), a free-tier account calling a model outside the free-tier allowlist `403` with `errorCode: \"model_requires_subscription\"` (upgrade the plan or pick a free-tier model), a model the caller's organization policy does not allow `403` with `errorCode: \"org_model_not_allowed\"`, a body over 25 MB `413`, any other body that fails schema validation `422`, insufficient credits `422` with `errorCode: \"insufficient_credits\"` (personal or org balance, or an org per-member credit cap), a rate limit `429` with `Retry-After`, a `run` that does not exist or that another user or billing owner minted `404` with `errorCode: \"run_not_found\"`, and a catalogued model whose provider is not configured on this deployment, or a model that could only come from a self-hosted model server (Ollama, local image) that is currently unreachable, `503` with `errorCode: \"provider_not_configured\"` (retryable). A provider rejection of caller input that happens before the stream opens is also a JSON `400`, with `errorCode: \"invalid_request\"` (do not retry it unchanged). Once the stream has opened the status stays `200` and a failure arrives as one terminal in-band `error` event. Branch on that event's `code`, never on `message`, which is prose and may change: `insufficient_credits` (buy credits) when credits run out mid-generation, `invalid_request` when the provider rejects caller input (do not retry it unchanged), `provider_rejected` when the model provider refused our credentials, `content_blocked` when the model declined the request (do not retry it unchanged), `output_budget_exhausted` when a reasoning model spent your whole `max_tokens` thinking and wrote no answer (raise `max_tokens` or omit it; do not retry it unchanged), and `provider_error` for any other provider failure. Treat `code` as optional.",
27158
28294
  tags: ["AI"],
27159
28295
  auth: "apiKeyOrJwt",
27160
28296
  scopes: ["ai:chat", "ai:generate"],
@@ -27188,9 +28324,13 @@ defineEndpoint({
27188
28324
  }
27189
28325
  },
27190
28326
  400: {
27191
- description: "Malformed or otherwise invalid request (no `errorCode`), a model that rejects a final assistant message (`errorCode: \"assistant_prefill_unsupported\"`), provider-rejected caller input (`errorCode: \"invalid_request\"`), or a `model` the caller cannot use (`errorCode: \"unknown_model\"`): not in the catalog or not available to the caller. List valid ids with `GET /api/v1/models`. Tool search requests are refused with: `tool_search_unsupported` (a server tool, `tool_reference` or echoed tool search block on a model that cannot serve tool search here), `all_tools_deferred` (every tool deferred and no server tool), `deferred_tool_cache_control` (`cache_control` on a deferred tool), `unknown_tool_reference` (a `tool_reference` naming a tool not in `tools`, or carrying no string `tool_name`). Mid-conversation tool changes are refused with: `tool_changes_unsupported` (a `tool_addition` / `tool_removal` system message on a model that cannot serve it here), `invalid_tool_change` (a malformed block, or one placed where the provider does not accept it), and `unknown_tool_reference` (a changed tool not in `tools`).",
28327
+ description: "Malformed or otherwise invalid request (no `errorCode`), a model that rejects a final assistant message (`errorCode: \"assistant_prefill_unsupported\"`), provider-rejected caller input (`errorCode: \"invalid_request\"`), or a `model` the caller cannot use (`errorCode: \"unknown_model\"`): not in the catalog or not available to the caller. List valid ids with `GET /api/v1/models`. Tool search requests are refused with: `tool_search_unsupported` (a server tool, `tool_reference` or echoed tool search block on a model that cannot serve tool search here), `all_tools_deferred` (every tool deferred and no server tool), `deferred_tool_cache_control` (`cache_control` on a deferred tool), `unknown_tool_reference` (a `tool_reference` naming a tool not in `tools`, or carrying no string `tool_name`). Mid-conversation tool changes are refused with: `tool_changes_unsupported` (a `tool_addition` / `tool_removal` system message on a model that cannot serve it here), `invalid_tool_change` (a malformed block, or one placed where the provider does not accept it), and `unknown_tool_reference` (a changed tool not in `tools`). `end_user_id` sent on a credential other than an API key holding `ai:end-user-id` is refused with `end_user_id_not_allowed`; a malformed `end_user_id` is refused with `invalid_end_user_id`.",
27192
28328
  schema: CompletionsBadRequestErrorSchema
27193
28329
  },
28330
+ 403: {
28331
+ description: "The API key does not hold any of the required scopes, the account is suspended (`errorCode: \"account_suspended\"`), a free-tier account named a model outside the free-tier allowlist (`errorCode: \"model_requires_subscription\"`), or the caller's organization policy does not allow the model (`errorCode: \"org_model_not_allowed\"`).",
28332
+ schema: ModelPolicyForbiddenErrorSchema
28333
+ },
27194
28334
  404: {
27195
28335
  description: "The `run` does not exist, or another user or billing owner minted it (`errorCode: \"run_not_found\"`). Mint one with `POST /api/v1/completion-runs` using the same credential.",
27196
28336
  schema: RunNotFoundErrorSchema
@@ -27263,6 +28403,68 @@ defineEndpoint({
27263
28403
  body: { rootSessionId: "session-42" }
27264
28404
  }
27265
28405
  });
28406
+ const EXAMPLE_SPEND = {
28407
+ creditsCharged: 412,
28408
+ requests: 9,
28409
+ inputTokens: 18200,
28410
+ outputTokens: 4100,
28411
+ cacheReadTokens: 52e3,
28412
+ cacheWriteTokens: 6400
28413
+ };
28414
+ defineEndpoint({
28415
+ method: "get",
28416
+ path: "/api/v1/completion-runs/{runId}/usage",
28417
+ operationId: "getCompletionRunUsage",
28418
+ summary: "Get a completion run's spend",
28419
+ description: "Returns what a run has cost so far: every `POST /api/ai/v1/completions` request sent with this `run.runId` whose credits have settled, summed once per request from the credit ledger, with breakdowns by role, purpose, model and task attempt. `creditsCharged` is the sum of the amounts each request's `settled` stream event reports, so a client can reconcile its own totals against it. Only settled charges count: a request still running, one whose credits never settled, and one sent without `run` are not included. Readable only with a credential of the same user and billing owner that minted the run; any other run id, including one that does not exist, gets `404` (`errorCode: \"run_not_found\"`).",
28420
+ tags: ["AI"],
28421
+ auth: "apiKeyOrJwt",
28422
+ scopes: ["ai:chat", "ai:generate"],
28423
+ pathParams: CompletionRunIdParamSchema,
28424
+ emitsRateLimitHeaders: true,
28425
+ responses: {
28426
+ 200: {
28427
+ description: "The run and its settled spend.",
28428
+ schema: CompletionRunUsageSchema,
28429
+ example: {
28430
+ runId: "0b6f3c2e-7d4a-4f51-9a8e-2c1d5e6f7a80",
28431
+ rootSessionId: "session-42",
28432
+ createdAt: "2026-11-10T12:00:00.000Z",
28433
+ settled: EXAMPLE_SPEND,
28434
+ byRole: [{
28435
+ role: "root",
28436
+ ...EXAMPLE_SPEND
28437
+ }],
28438
+ byPurpose: [{
28439
+ purpose: "turn",
28440
+ ...EXAMPLE_SPEND
28441
+ }],
28442
+ byModel: [{
28443
+ model: "claude-sonnet-5-5",
28444
+ ...EXAMPLE_SPEND
28445
+ }],
28446
+ byAttempt: [{
28447
+ role: "root",
28448
+ ...EXAMPLE_SPEND
28449
+ }],
28450
+ byAttemptTruncated: false
28451
+ }
28452
+ },
28453
+ 404: {
28454
+ description: "The run does not exist, or another user or billing owner minted it (`errorCode: \"run_not_found\"`).",
28455
+ schema: RunNotFoundErrorSchema
28456
+ },
28457
+ 429: {
28458
+ description: "Per-user rate limit exceeded.",
28459
+ schema: ApiErrorSchema
28460
+ }
28461
+ },
28462
+ codeSample: {
28463
+ authToken: "b4m_live_<key>",
28464
+ streaming: false,
28465
+ body: {}
28466
+ }
28467
+ });
27266
28468
  /**
27267
28469
  * Responses shared by the endpoints that return generated audio (TTS, music,
27268
28470
  * sound effects). Not a contract - the pieces all three declare, kept in one place
@@ -27317,6 +28519,50 @@ function generatedAudioResponses(options) {
27317
28519
  }
27318
28520
  };
27319
28521
  }
28522
+ /**
28523
+ * The 202 a generated-audio endpoint answers when the clip outlasts the request. `noun` names the clip, `schema` is
28524
+ * the endpoint's job resource. Speech and sound effects only: music has its own job API. Answered only for a clip
28525
+ * that is being saved to the file browser, the one place it can be picked up later, and only to a caller that sent
28526
+ * `Prefer: respond-async`; any other caller gets the 504 (see unretrievableAudioResponse).
28527
+ */
28528
+ function outlastedAudioResponse(options) {
28529
+ return {
28530
+ description: `Returned only when the request sends \`Prefer: respond-async\` (RFC 7240), and echoed by \`Preference-Applied: respond-async\`. The ${options.noun} took longer than this request can wait (about 55 seconds), so no audio is returned. Generation carries on: the body is the job as it stands. When it finishes, the audio is saved to the file browser if your storage quota still has room for it. Credits are settled only if it succeeds and returned otherwise. This job cannot be polled through the API yet; look for the saved file instead of retrying, which would generate (and bill) a second clip.`,
28531
+ headers: { "Preference-Applied": "`respond-async`, confirming the opt-in." },
28532
+ schema: options.schema,
28533
+ example: options.example
28534
+ };
28535
+ }
28536
+ /**
28537
+ * The 504 a speech or sound-effect endpoint answers when the clip outlasts the request and either would not be saved
28538
+ * to the file browser (a `preview` call, or a storage quota with no room), so nothing could ever retrieve it, or is
28539
+ * being saved but the caller did not send `Prefer: respond-async`, so it could not use the 202.
28540
+ */
28541
+ function unretrievableAudioResponse(options) {
28542
+ return {
28543
+ description: `The ${options.noun} took longer than this request can wait. Tagged \`errorCode: "request_timeout"\`. Two cases. (1) It would not be saved to the file browser (a \`preview\` call, or a storage quota with no room for it), so it could never be retrieved: the generation is cancelled and its credits returned, unless the provider had already started it, in which case that one finishes and is billed, and the response carries \`jobId\` (also \`X-B4M-Generation-Job-Id\`) and a \`message\`. Retrying generates a new clip. (2) It is being saved to the file browser but the request did not send \`Prefer: respond-async\`: the generation is NOT cancelled and carries on, the audio lands in the file browser when it finishes, and it is billed only if it succeeds. Do not retry, which would generate and bill a second clip. The body carries \`jobId\`, also sent as \`X-B4M-Generation-Job-Id\`.`,
28544
+ headers: { "X-B4M-Generation-Job-Id": "The job left running (case 2, or case 1 once the provider had started it)." },
28545
+ schema: options.schema
28546
+ };
28547
+ }
28548
+ const exampleOutlastedJob$1 = {
28549
+ id: EXAMPLE_RESOURCE_ID,
28550
+ object: "speech_generation",
28551
+ state: "running",
28552
+ text: "Your password has been reset.",
28553
+ provider: "elevenlabs",
28554
+ model: null,
28555
+ voice: null,
28556
+ source: "api",
28557
+ error: null,
28558
+ output: null,
28559
+ credits: {
28560
+ reserved: 12,
28561
+ settled: null
28562
+ },
28563
+ created_at: "2026-10-14T00:00:00.000Z",
28564
+ updated_at: "2026-10-14T00:00:30.000Z"
28565
+ };
27320
28566
  defineEndpoint({
27321
28567
  method: "post",
27322
28568
  path: "/api/ai/tts",
@@ -27361,12 +28607,17 @@ defineEndpoint({
27361
28607
  },
27362
28608
  tooLargeSchema: ttsResponseTooLargeSchema
27363
28609
  }),
28610
+ 202: outlastedAudioResponse({
28611
+ noun: "speech",
28612
+ schema: SpeechGenerationSchema,
28613
+ example: exampleOutlastedJob$1
28614
+ }),
27364
28615
  401: {
27365
28616
  description: "Missing/invalid credentials, no provider has a usable key (`provider_not_configured`), or the provider refused the key we sent and no alternate could stand in (`provider_rejected`).",
27366
28617
  schema: ttsErrorResponseSchema
27367
28618
  },
27368
28619
  400: {
27369
- description: `The billing organization could not be resolved. ${BILLING_ORGANIZATION_STALE_KEY_DESCRIPTION}`,
28620
+ description: `The billing organization could not be resolved. ${BILLING_ORGANIZATION_STALE_KEY_DESCRIPTION} Also \`end_user_id\` sent on a credential other than an API key holding \`ai:end-user-id\` (\`errorCode: "end_user_id_not_allowed"\`), or a malformed \`end_user_id\` (\`errorCode: "invalid_end_user_id"\`).`,
27370
28621
  schema: ttsErrorResponseSchema
27371
28622
  },
27372
28623
  403: {
@@ -27386,9 +28637,13 @@ defineEndpoint({
27386
28637
  schema: ttsErrorResponseSchema
27387
28638
  },
27388
28639
  502: {
27389
- description: "The provider failed to generate speech.",
28640
+ description: "The provider failed to generate speech. When the clip was generated but could not be read back, the body carries `jobId`, also sent as `X-B4M-Generation-Job-Id`.",
27390
28641
  schema: ttsErrorResponseSchema
27391
- }
28642
+ },
28643
+ 504: unretrievableAudioResponse({
28644
+ noun: "speech",
28645
+ schema: ttsErrorResponseSchema
28646
+ })
27392
28647
  },
27393
28648
  emitsRateLimitHeaders: true,
27394
28649
  codeSample: {
@@ -27470,6 +28725,28 @@ defineEndpoint({
27470
28725
  }
27471
28726
  }
27472
28727
  });
28728
+ const soundEffectsTimeoutErrorSchema = ApiErrorSchema.extend({
28729
+ errorCode: z$1.literal("request_timeout").optional(),
28730
+ jobId: z$1.string().optional(),
28731
+ message: z$1.string().optional()
28732
+ });
28733
+ const exampleOutlastedJob = {
28734
+ id: EXAMPLE_RESOURCE_ID,
28735
+ object: "sound_effect_generation",
28736
+ state: "running",
28737
+ text: "heavy wooden door creaking open",
28738
+ provider: "elevenlabs",
28739
+ duration_seconds: 3,
28740
+ source: "api",
28741
+ error: null,
28742
+ output: null,
28743
+ credits: {
28744
+ reserved: 12,
28745
+ settled: null
28746
+ },
28747
+ created_at: "2026-10-14T00:00:00.000Z",
28748
+ updated_at: "2026-10-14T00:00:30.000Z"
28749
+ };
27473
28750
  defineEndpoint({
27474
28751
  method: "post",
27475
28752
  path: "/api/ai/sound-effects",
@@ -27500,6 +28777,11 @@ defineEndpoint({
27500
28777
  binaryContentTypes: GENERATED_AUDIO_CONTENT_TYPES,
27501
28778
  tooLargeSchema: generatedAudioTooLargeSchema
27502
28779
  }),
28780
+ 202: outlastedAudioResponse({
28781
+ noun: "sound effect",
28782
+ schema: SoundEffectGenerationSchema,
28783
+ example: exampleOutlastedJob
28784
+ }),
27503
28785
  400: {
27504
28786
  description: `The billing user or organization could not be resolved. ${BILLING_ORGANIZATION_STALE_KEY_DESCRIPTION}`,
27505
28787
  schema: ApiErrorSchema
@@ -27522,13 +28804,17 @@ defineEndpoint({
27522
28804
  headers: { "Retry-After": "Seconds to wait before retrying." }
27523
28805
  },
27524
28806
  502: {
27525
- description: "The provider failed to generate the effect; reserved credits are refunded.",
27526
- schema: ApiErrorSchema
28807
+ description: "The provider failed to generate the effect; reserved credits are refunded. When the clip was generated but could not be read back, the body carries `jobId`, also sent as `X-B4M-Generation-Job-Id`.",
28808
+ schema: soundEffectsTimeoutErrorSchema
27527
28809
  },
27528
28810
  503: {
27529
28811
  description: "No provider API key is configured for this deployment.",
27530
28812
  schema: ApiErrorSchema
27531
- }
28813
+ },
28814
+ 504: unretrievableAudioResponse({
28815
+ noun: "sound effect",
28816
+ schema: soundEffectsTimeoutErrorSchema
28817
+ })
27532
28818
  },
27533
28819
  emitsRateLimitHeaders: true,
27534
28820
  codeSample: {
@@ -27588,7 +28874,7 @@ defineEndpoint({
27588
28874
  path: "/api/v1/client-config",
27589
28875
  operationId: "getClientConfig",
27590
28876
  summary: "Get client configuration",
27591
- description: "Returns what a client needs to configure itself in one call: whether the deployment is live, which product features are switched on deployment-wide, upload and credit limits, the default and recommended model ids, and every model the caller can use right now (the same list `GET /api/v1/models` pages through, unpaginated here). A feature flag says whether the deployment offers the feature, not whether this caller has opted in. The caller's identity, plan and entitlements are not repeated here - read them from `GET /api/v1/me`. Responses are never cacheable. Authenticate with an API key (`b4m_live_`) carrying `me:read`, `ai:chat` or `ai:generate`, or a JWT.",
28877
+ description: "Returns what a client needs to configure itself in one call: whether the deployment is live, which product features are switched on deployment-wide, upload and credit limits, the default and recommended model ids, and every model the caller can use right now (the same list `GET /api/v1/models` pages through, unpaginated here). A feature flag says whether the deployment offers the feature, not whether this caller has opted in. The caller's identity, plan and entitlements are not repeated here - read them from `GET /api/v1/me`. Responses are never cacheable. The optional catalog preserves picker order, disabled entries, locked cards and revision/fallback signals; it never includes internal pricing or dispatch configuration. Transport URLs require authentication. Pre-login clients use `GET /api/v1/client-config/public`, which returns only public login configuration. Authenticate with an API key (`b4m_live_`) carrying `me:read`, `ai:chat` or `ai:generate`, or a JWT.",
27592
28878
  tags: ["Account"],
27593
28879
  auth: "apiKeyOrJwt",
27594
28880
  scopes: [
@@ -27680,6 +28966,29 @@ defineEndpoint({
27680
28966
  body: {}
27681
28967
  }
27682
28968
  });
28969
+ defineEndpoint({
28970
+ method: "get",
28971
+ path: "/api/v1/client-config/public",
28972
+ operationId: "getPublicClientConfig",
28973
+ summary: "Get pre-login client configuration",
28974
+ description: "Public login and registration configuration only. Empty strings preserve unconfigured values. No caller models, transport URLs, credentials or admin configuration are returned. Responses are never cacheable.",
28975
+ tags: ["Account"],
28976
+ auth: "public",
28977
+ responses: { 200: {
28978
+ description: "The public login configuration.",
28979
+ schema: ClientConfigPublicSchema,
28980
+ example: {
28981
+ api_url: "https://app.example.com",
28982
+ default_theme: "bike4mind",
28983
+ allow_open_registration: false,
28984
+ pyodide_base_url: "",
28985
+ allow_trusted_devices: true,
28986
+ turnstile_site_key: "",
28987
+ apple_sign_in_enabled: false,
28988
+ support_email: ""
28989
+ }
28990
+ } }
28991
+ });
27683
28992
  const JWT_ONLY_NOTE$1 = "Authenticate with a JWT access token of the signed-in user: an API key cannot answer an approval. The caller must own the session the action belongs to; anyone else gets `404`, exactly like a missing action. Nothing in a push notification authorizes this call. ";
27684
28993
  const LIFECYCLE = "An approval is answered once and only while it is current: it lapses 15 minutes after it was raised, and a newer approval on the same quest replaces it.";
27685
28994
  const CONFLICT = "The action was replaced by a newer one (`errorCode: action_replaced`), lapsed (`action_expired`, and it is cleared), or was already answered (`action_already_resolved`). Also a custom connector tool that is no longer offered. Do not retry; review the quest for a newer approval.";
@@ -27788,7 +29097,7 @@ defineEndpoint({
27788
29097
  path: "/api/v1/push-tokens",
27789
29098
  operationId: "registerPushToken",
27790
29099
  summary: "Register a device push token",
27791
- description: "Registers a push token for the signed-in device so the server can notify it. Idempotent: re-registering the same token refreshes it and rebinds it to the calling user and session, which is how a token moves when a different account signs in on the same device. The token is removed automatically when the registering session ends. " + JWT_ONLY_NOTE + "A token with no session claim (legacy access token) is refused with `401`; sign in again.",
29100
+ description: "Registers a push token for the signed-in device so the server can notify it. Idempotent: re-registering the same token refreshes it and rebinds it to the calling user and session, which is how a token moves when a different account signs in on the same device. The token is removed automatically when the registering session ends. `platform` selects the delivery service: `ios` (APNs) or `android` (FCM; send `production` as the environment). " + JWT_ONLY_NOTE + "A token with no session claim (legacy access token) is refused with `401`; sign in again.",
27792
29101
  tags: ["Account"],
27793
29102
  auth: "jwtOnly",
27794
29103
  request: PushTokenRegisterRequestSchema,
@@ -28220,7 +29529,7 @@ defineEndpoint({
28220
29529
  path: "/api/v1/files",
28221
29530
  operationId: "createFileUpload",
28222
29531
  summary: "Start a file upload",
28223
- description: "Registers a file and returns a presigned `upload_url`. Uploading is three steps: (1) call this endpoint with the file name, MIME type, and size in bytes; (2) `PUT` the raw bytes to `upload_url` before `upload_url_expires_at` - send no `Authorization` header, the URL signature is the credential, and do send a `Content-Type` matching `mime_type`; the URL is bound to `file_size`, so the body must be exactly that many bytes or storage refuses it with 403; (3) poll `GET /api/v1/files/{id}` until `moderation_status` is `clean` (usually a few seconds after the PUT), then pass `id` wherever an endpoint takes a file id (for example `fabFileIds` and `referenceImageFabFileIds` on `POST /api/v1/image-edits`). Unsupported types, a size over the upload limit, or a size that would exceed your storage quota are rejected with 400 before any URL is issued. Authenticate with an API key (`b4m_live_`) carrying `files:write`, or a JWT.",
29532
+ description: "Registers a file and returns a presigned `upload_url`. Uploading is three steps: (1) call this endpoint with the file name, MIME type, and size in bytes; (2) `PUT` the raw bytes to `upload_url` before `upload_url_expires_at` - send no `Authorization` header, the URL signature is the credential, and do send a `Content-Type` matching `mime_type` and `If-None-Match: *`, which makes the upload create-only (a URL may require it, and a PUT onto an object that already landed is refused with 412); the URL is bound to `file_size`, so the body must be exactly that many bytes or storage refuses it with 403; (3) poll `GET /api/v1/files/{id}` until `moderation_status` is `clean` (usually a few seconds after the PUT), then pass `id` wherever an endpoint takes a file id (for example `fabFileIds` and `referenceImageFabFileIds` on `POST /api/v1/image-edits`). Unsupported types, a size over the upload limit, or a size that would exceed your storage quota are rejected with 400 before any URL is issued. Authenticate with an API key (`b4m_live_`) carrying `files:write`, or a JWT.",
28224
29533
  tags: ["Files"],
28225
29534
  auth: "apiKeyOrJwt",
28226
29535
  scopes: ["files:write"],
@@ -28906,11 +30215,11 @@ defineEndpoint({
28906
30215
  }
28907
30216
  });
28908
30217
  const DECISION_SCOPES = ["ai:decide", "ai:generate"];
28909
- const scopeForbidden$2 = {
30218
+ const scopeForbidden$3 = {
28910
30219
  description: "The API key holds neither `ai:decide` nor `ai:generate`.",
28911
30220
  schema: ScopeForbiddenErrorSchema
28912
30221
  };
28913
- const rateLimited$2 = {
30222
+ const rateLimited$3 = {
28914
30223
  description: "Per-key or per-user decisions rate limit exceeded.",
28915
30224
  schema: ApiErrorSchema
28916
30225
  };
@@ -29047,7 +30356,7 @@ defineEndpoint({
29047
30356
  description: "Missing/invalid credentials, or the provider refused the configured key (`errorCode: \"provider_rejected\"`).",
29048
30357
  schema: DecisionsErrorSchema
29049
30358
  },
29050
- 403: scopeForbidden$2,
30359
+ 403: scopeForbidden$3,
29051
30360
  404: {
29052
30361
  description: "An image `file_id` does not exist or is not readable by the caller. Reading one also needs the `files:read` scope; a key without it gets 403.",
29053
30362
  schema: DecisionsErrorSchema
@@ -29056,7 +30365,7 @@ defineEndpoint({
29056
30365
  description: "The body failed validation, or the request exceeds a per-model cap (`limit_exceeded`), sends an image to a text-only model (`unsupported_input`), repeats a question name or choice value (`invalid_request`), names a model this deployment does not serve (`model_unavailable`), overflows the model context (`context_length_exceeded`), or the caller cannot afford it (`insufficient_credits`). `param` names the offending field when there is one.",
29057
30366
  schema: DecisionsErrorSchema
29058
30367
  },
29059
- 429: rateLimited$2,
30368
+ 429: rateLimited$3,
29060
30369
  502: {
29061
30370
  description: "The provider failed or answered something that does not fit the questions (`provider_error`).",
29062
30371
  schema: DecisionsErrorSchema
@@ -29088,8 +30397,8 @@ defineEndpoint({
29088
30397
  description: "The models you can call.",
29089
30398
  schema: ListDecisionModelsResponseSchema
29090
30399
  },
29091
- 403: scopeForbidden$2,
29092
- 429: rateLimited$2
30400
+ 403: scopeForbidden$3,
30401
+ 429: rateLimited$3
29093
30402
  },
29094
30403
  emitsRateLimitHeaders: true,
29095
30404
  codeSample: {
@@ -30376,7 +31685,37 @@ defineEndpoint({
30376
31685
  }
30377
31686
  }
30378
31687
  });
30379
- const exampleJob$1 = {
31688
+ defineEndpoint({
31689
+ method: "get",
31690
+ path: "/api/v1/image-models",
31691
+ operationId: "listImageModels",
31692
+ summary: "List the image models you can use",
31693
+ description: "Returns the image models that are offered to the caller, served by this deployment and backed by a usable provider key, best first, with their capabilities per mode and an indicative credit price. The capabilities and prices are those of image jobs, which refuse an unsupported size, aspect ratio, quality or input image rather than adjust it. `POST /api/v1/image-generations` and `POST /api/v1/image-edits` do not run as image jobs yet and may adapt a request to the model, for example by rendering a transparent background on a model that supports it.",
31694
+ tags: ["Images"],
31695
+ auth: "apiKeyOrJwt",
31696
+ scopes: ["ai:generate"],
31697
+ responses: {
31698
+ 200: {
31699
+ description: "The usable models, best first.",
31700
+ schema: ListImageModelsResponseSchema
31701
+ },
31702
+ 403: {
31703
+ description: "The API key lacks the `ai:generate` scope.",
31704
+ schema: ScopeForbiddenErrorSchema
31705
+ },
31706
+ 429: {
31707
+ description: "Per-user rate limit exceeded.",
31708
+ schema: ApiErrorSchema
31709
+ }
31710
+ },
31711
+ emitsRateLimitHeaders: true,
31712
+ codeSample: {
31713
+ authToken: "b4m_live_<key>",
31714
+ streaming: false,
31715
+ body: {}
31716
+ }
31717
+ });
31718
+ const exampleJob$2 = {
30380
31719
  id: EXAMPLE_RESOURCE_ID,
30381
31720
  object: "video_generation",
30382
31721
  state: "pending",
@@ -30397,15 +31736,15 @@ const exampleJob$1 = {
30397
31736
  created_at: "2026-10-06T00:00:00.000Z",
30398
31737
  updated_at: "2026-10-06T00:00:00.000Z"
30399
31738
  };
30400
- const scopeForbidden$1 = {
31739
+ const scopeForbidden$2 = {
30401
31740
  description: "The API key lacks the `ai:generate` scope.",
30402
31741
  schema: ScopeForbiddenErrorSchema
30403
31742
  };
30404
- const notFound$1 = {
31743
+ const notFound$2 = {
30405
31744
  description: "No video generation with that id was requested by the caller (a malformed id is also a 404).",
30406
31745
  schema: ApiErrorSchema
30407
31746
  };
30408
- const rateLimited$1 = {
31747
+ const rateLimited$2 = {
30409
31748
  description: "Per-user rate limit exceeded.",
30410
31749
  schema: ApiErrorSchema
30411
31750
  };
@@ -30423,8 +31762,8 @@ defineEndpoint({
30423
31762
  description: "The usable models.",
30424
31763
  schema: ListVideoModelsResponseSchema
30425
31764
  },
30426
- 403: scopeForbidden$1,
30427
- 429: rateLimited$1
31765
+ 403: scopeForbidden$2,
31766
+ 429: rateLimited$2
30428
31767
  },
30429
31768
  emitsRateLimitHeaders: true,
30430
31769
  codeSample: {
@@ -30451,7 +31790,7 @@ defineEndpoint({
30451
31790
  202: {
30452
31791
  description: "Accepted; the job is queued (or replayed for a repeated Idempotency-Key).",
30453
31792
  schema: VideoGenerationSchema,
30454
- example: exampleJob$1
31793
+ example: exampleJob$2
30455
31794
  },
30456
31795
  403: {
30457
31796
  description: `The API key lacks the \`ai:generate\` scope, or ${BILLING_ORGANIZATION_FORBIDDEN_DESCRIPTION}`,
@@ -30466,10 +31805,10 @@ defineEndpoint({
30466
31805
  schema: VideoGenerationErrorResponseSchema
30467
31806
  },
30468
31807
  422: {
30469
- description: "The request cannot run: a body or capability violation (`errorCode` names it, e.g. `unsupported_duration`, or `unsupported_input_role` for an input role the model does not take), an unknown, unavailable or retired model (`model_unavailable`; for a retired model the message names the model to use instead), a model your administrator disabled (`model_disabled`), too few credits (`insufficient_credits`), or an Idempotency-Key problem (`invalid_idempotency_key`, `idempotency_key_reused`).",
31808
+ description: "The request cannot run: a body or capability violation (`errorCode` names it, e.g. `unsupported_duration`, `unsupported_keyframes`, `invalid_keyframes`, `unsupported_draft`, or `unsupported_input_role` for an input role the model does not take). Keyframe/draft errors name the field. An unknown, unavailable or retired model (`model_unavailable`; for a retired model the message names the model to use instead), a model your administrator disabled (`model_disabled`), too few credits (`insufficient_credits`), or an Idempotency-Key problem (`invalid_idempotency_key`, `idempotency_key_reused`).",
30470
31809
  schema: VideoGenerationErrorResponseSchema
30471
31810
  },
30472
- 429: rateLimited$1
31811
+ 429: rateLimited$2
30473
31812
  },
30474
31813
  emitsRateLimitHeaders: true,
30475
31814
  codeSample: {
@@ -30495,11 +31834,11 @@ defineEndpoint({
30495
31834
  200: {
30496
31835
  description: "The job.",
30497
31836
  schema: VideoGenerationSchema,
30498
- example: exampleJob$1
31837
+ example: exampleJob$2
30499
31838
  },
30500
- 403: scopeForbidden$1,
30501
- 404: notFound$1,
30502
- 429: rateLimited$1
31839
+ 403: scopeForbidden$2,
31840
+ 404: notFound$2,
31841
+ 429: rateLimited$2
30503
31842
  },
30504
31843
  emitsRateLimitHeaders: true,
30505
31844
  codeSample: {
@@ -30523,12 +31862,12 @@ defineEndpoint({
30523
31862
  description: "A page of jobs.",
30524
31863
  schema: ListVideoGenerationsResponseSchema
30525
31864
  },
30526
- 403: scopeForbidden$1,
31865
+ 403: scopeForbidden$2,
30527
31866
  422: {
30528
31867
  description: "A malformed `cursor`, `limit`, `state` or `source`.",
30529
31868
  schema: ApiErrorSchema
30530
31869
  },
30531
- 429: rateLimited$1
31870
+ 429: rateLimited$2
30532
31871
  },
30533
31872
  emitsRateLimitHeaders: true,
30534
31873
  codeSample: {
@@ -30551,11 +31890,11 @@ defineEndpoint({
30551
31890
  200: {
30552
31891
  description: "The job after the cancel request.",
30553
31892
  schema: VideoGenerationSchema,
30554
- example: exampleJob$1
31893
+ example: exampleJob$2
30555
31894
  },
30556
- 403: scopeForbidden$1,
30557
- 404: notFound$1,
30558
- 429: rateLimited$1
31895
+ 403: scopeForbidden$2,
31896
+ 404: notFound$2,
31897
+ 429: rateLimited$2
30559
31898
  },
30560
31899
  emitsRateLimitHeaders: true,
30561
31900
  codeSample: {
@@ -30565,7 +31904,7 @@ defineEndpoint({
30565
31904
  }
30566
31905
  });
30567
31906
  const examplePrompt = "An upbeat synth-pop song about a road trip at sunrise";
30568
- const exampleJob = {
31907
+ const exampleJob$1 = {
30569
31908
  id: EXAMPLE_RESOURCE_ID,
30570
31909
  object: "music_generation",
30571
31910
  state: "pending",
@@ -30584,15 +31923,15 @@ const exampleJob = {
30584
31923
  created_at: "2026-10-14T00:00:00.000Z",
30585
31924
  updated_at: "2026-10-14T00:00:00.000Z"
30586
31925
  };
30587
- const scopeForbidden = {
31926
+ const scopeForbidden$1 = {
30588
31927
  description: "The API key lacks the `ai:generate` scope.",
30589
31928
  schema: ScopeForbiddenErrorSchema
30590
31929
  };
30591
- const notFound = {
31930
+ const notFound$1 = {
30592
31931
  description: "No music generation with that id was requested by the caller (a malformed id is also a 404).",
30593
31932
  schema: ApiErrorSchema
30594
31933
  };
30595
- const rateLimited = {
31934
+ const rateLimited$1 = {
30596
31935
  description: "Per-user rate limit exceeded.",
30597
31936
  schema: ApiErrorSchema
30598
31937
  };
@@ -30610,8 +31949,8 @@ defineEndpoint({
30610
31949
  description: "The usable models.",
30611
31950
  schema: ListMusicModelsResponseSchema
30612
31951
  },
30613
- 403: scopeForbidden,
30614
- 429: rateLimited
31952
+ 403: scopeForbidden$1,
31953
+ 429: rateLimited$1
30615
31954
  },
30616
31955
  emitsRateLimitHeaders: true,
30617
31956
  codeSample: {
@@ -30638,7 +31977,7 @@ defineEndpoint({
30638
31977
  202: {
30639
31978
  description: "Accepted; the job is queued (or replayed for a repeated Idempotency-Key).",
30640
31979
  schema: MusicGenerationSchema,
30641
- example: exampleJob
31980
+ example: exampleJob$1
30642
31981
  },
30643
31982
  400: {
30644
31983
  description: "Your Files storage has no room for the song (`storage_limit_exceeded`, as on the Files upload routes). The body carries `used_bytes`, `limit_bytes`, `requested_bytes` and `owner`, always together; `requested_bytes` here is the most the song can take at the requested length, not its final size. This endpoint checks only the user quota, so `org_storage_limit_exceeded` is never returned here. " + BILLING_ORGANIZATION_STALE_KEY_DESCRIPTION,
@@ -30656,7 +31995,7 @@ defineEndpoint({
30656
31995
  description: "The request cannot run: a malformed body, a capability violation (`errorCode` names it, e.g. `unsupported_duration` or `lyrics_too_long`), an unknown or unavailable model (`model_unavailable`), a model your administrator disabled (`model_disabled`), too few credits (`insufficient_credits`), or an Idempotency-Key problem (`invalid_idempotency_key`, `idempotency_key_reused`).",
30657
31996
  schema: MusicGenerationErrorResponseSchema
30658
31997
  },
30659
- 429: rateLimited
31998
+ 429: rateLimited$1
30660
31999
  },
30661
32000
  emitsRateLimitHeaders: true,
30662
32001
  codeSample: {
@@ -30682,11 +32021,11 @@ defineEndpoint({
30682
32021
  200: {
30683
32022
  description: "The job.",
30684
32023
  schema: MusicGenerationSchema,
30685
- example: exampleJob
32024
+ example: exampleJob$1
30686
32025
  },
30687
- 403: scopeForbidden,
30688
- 404: notFound,
30689
- 429: rateLimited
32026
+ 403: scopeForbidden$1,
32027
+ 404: notFound$1,
32028
+ 429: rateLimited$1
30690
32029
  },
30691
32030
  emitsRateLimitHeaders: true,
30692
32031
  codeSample: {
@@ -30710,12 +32049,12 @@ defineEndpoint({
30710
32049
  description: "A page of jobs.",
30711
32050
  schema: ListMusicGenerationsResponseSchema
30712
32051
  },
30713
- 403: scopeForbidden,
32052
+ 403: scopeForbidden$1,
30714
32053
  422: {
30715
32054
  description: "A malformed `cursor`, `limit`, `state` or `source`.",
30716
32055
  schema: ApiErrorSchema
30717
32056
  },
30718
- 429: rateLimited
32057
+ 429: rateLimited$1
30719
32058
  },
30720
32059
  emitsRateLimitHeaders: true,
30721
32060
  codeSample: {
@@ -30738,13 +32077,180 @@ defineEndpoint({
30738
32077
  200: {
30739
32078
  description: "The job after the cancel request.",
30740
32079
  schema: MusicGenerationSchema,
32080
+ example: exampleJob$1
32081
+ },
32082
+ 403: scopeForbidden$1,
32083
+ 404: notFound$1,
32084
+ 409: {
32085
+ description: "The song is already rendering (`running`); `errorCode` is `not_cancellable`.",
32086
+ schema: MusicGenerationErrorResponseSchema
32087
+ },
32088
+ 429: rateLimited$1
32089
+ },
32090
+ emitsRateLimitHeaders: true,
32091
+ codeSample: {
32092
+ authToken: "b4m_live_<key>",
32093
+ streaming: false,
32094
+ body: {}
32095
+ }
32096
+ });
32097
+ const exampleVideoFileId = EXAMPLE_FILE_ID;
32098
+ const exampleAudioFileId = EXAMPLE_SECOND_FILE_ID;
32099
+ const exampleJob = {
32100
+ id: EXAMPLE_RESOURCE_ID,
32101
+ object: "scene_composition",
32102
+ state: "pending",
32103
+ video_file_id: exampleVideoFileId,
32104
+ audio_file_id: exampleAudioFileId,
32105
+ cover_file_id: null,
32106
+ title: null,
32107
+ audio: {
32108
+ fit: "trim",
32109
+ fade_in_seconds: 0,
32110
+ fade_out_seconds: 1.5
32111
+ },
32112
+ source: "api",
32113
+ error: null,
32114
+ output: null,
32115
+ credits: {
32116
+ reserved: null,
32117
+ settled: null
32118
+ },
32119
+ created_at: "2026-11-17T00:00:00.000Z",
32120
+ updated_at: "2026-11-17T00:00:00.000Z"
32121
+ };
32122
+ const exampleBody = {
32123
+ video_file_id: exampleVideoFileId,
32124
+ audio_file_id: exampleAudioFileId
32125
+ };
32126
+ const scopeForbidden = {
32127
+ description: "The API key lacks the `ai:generate` scope.",
32128
+ schema: ScopeForbiddenErrorSchema
32129
+ };
32130
+ const notFound = {
32131
+ description: "No scene composition with that id was requested by the caller (a malformed id is also a 404).",
32132
+ schema: ApiErrorSchema
32133
+ };
32134
+ const rateLimited = {
32135
+ description: "Per-user rate limit exceeded.",
32136
+ schema: ApiErrorSchema
32137
+ };
32138
+ defineEndpoint({
32139
+ method: "post",
32140
+ path: "/api/v1/scene-compositions",
32141
+ operationId: "createSceneComposition",
32142
+ summary: "Compose a Scene from a video and a music track",
32143
+ description: `Queues a Scene: one shareable clip made from a video file and an audio file you own, with optional cover art, and returns \`202\` with the job. The Scene runs exactly as long as the video: its picture is copied unchanged and the audio is trimmed (or looped) to fit, with optional fades. ${SCENE_COMPOSITION_LIMITS_DESCRIPTION} Poll \`GET /api/v1/scene-compositions/{id}\` until \`state\` is \`succeeded\`, \`failed\` or \`cancelled\`. The finished Scene is saved to your Files with the \`generated\` and \`scene\` tags, linked to its inputs (see \`GET /api/v1/files/{id}/lineage\`); if that save fails it is kept outside Files and \`output.file_id\` is null. \`output.availability\` works as on the other generation jobs: \`ready\` means \`output.url\` is a signed download URL valid for 15 minutes (re-fetch the job for a fresh one), \`pending_scan\` means keep re-fetching, and \`unavailable\` means stop polling. A file that cannot be read as the media its slot needs (no video stream, an over-long video) ends the job \`failed\` with \`unsupported_input\`. Composing is free: no credits are reserved or charged. Send an \`Idempotency-Key\` header (1-255 printable ASCII characters) to make retries safe: a repeat with the same key and body returns the original job, and the same key with a different body is a 422 \`idempotency_key_reused\`.`,
32144
+ tags: ["Scenes"],
32145
+ auth: "apiKeyOrJwt",
32146
+ scopes: ["ai:generate"],
32147
+ request: CreateSceneCompositionBodySchema,
32148
+ requestExample: exampleBody,
32149
+ responses: {
32150
+ 202: {
32151
+ description: "Accepted; the job is queued (or replayed for a repeated Idempotency-Key).",
32152
+ schema: SceneCompositionSchema,
32153
+ example: exampleJob
32154
+ },
32155
+ 400: {
32156
+ description: "Your Files storage has no room for the Scene (`storage_limit_exceeded`, as on the Files upload routes). The body carries `used_bytes`, `limit_bytes`, `requested_bytes` and `owner`, always together; `requested_bytes` is the most the Scene can take (the size of its inputs), not its final size.",
32157
+ schema: StorageLimitErrorSchema
32158
+ },
32159
+ 403: scopeForbidden,
32160
+ 404: {
32161
+ description: "An input file id is not one of your files, is deleted, or is still being scanned (`errorCode: input_file_not_found`).",
32162
+ schema: SceneCompositionErrorResponseSchema
32163
+ },
32164
+ 422: {
32165
+ description: "The request cannot run: a malformed body (`invalid_request`), a file of the wrong kind for its slot (`unsupported_input`), inputs over the size limit (`limit_exceeded`), or an Idempotency-Key problem (`invalid_idempotency_key`, `idempotency_key_reused`).",
32166
+ schema: SceneCompositionErrorResponseSchema
32167
+ },
32168
+ 429: rateLimited
32169
+ },
32170
+ emitsRateLimitHeaders: true,
32171
+ codeSample: {
32172
+ authToken: "b4m_live_<key>",
32173
+ streaming: false,
32174
+ body: exampleBody
32175
+ }
32176
+ });
32177
+ defineEndpoint({
32178
+ method: "get",
32179
+ path: "/api/v1/scene-compositions/{id}",
32180
+ operationId: "getSceneComposition",
32181
+ summary: "Get a scene composition",
32182
+ description: "Returns one job you requested. Each read signs a fresh `output.url` (valid 15 minutes, see `expires_at`).",
32183
+ tags: ["Scenes"],
32184
+ auth: "apiKeyOrJwt",
32185
+ scopes: ["ai:generate"],
32186
+ pathParams: SceneCompositionIdParamSchema,
32187
+ responses: {
32188
+ 200: {
32189
+ description: "The job.",
32190
+ schema: SceneCompositionSchema,
32191
+ example: exampleJob
32192
+ },
32193
+ 403: scopeForbidden,
32194
+ 404: notFound,
32195
+ 429: rateLimited
32196
+ },
32197
+ emitsRateLimitHeaders: true,
32198
+ codeSample: {
32199
+ authToken: "b4m_live_<key>",
32200
+ streaming: false,
32201
+ body: {}
32202
+ }
32203
+ });
32204
+ defineEndpoint({
32205
+ method: "get",
32206
+ path: "/api/v1/scene-compositions",
32207
+ operationId: "listSceneCompositions",
32208
+ summary: "List your scene compositions",
32209
+ description: "Your jobs, newest first, optionally filtered by `state` and `source`. Cursor-paginated (see the pagination convention): pass `next_cursor` back as `cursor` until it is `null`.",
32210
+ tags: ["Scenes"],
32211
+ auth: "apiKeyOrJwt",
32212
+ scopes: ["ai:generate"],
32213
+ queryParams: ListSceneCompositionsQuerySchema,
32214
+ responses: {
32215
+ 200: {
32216
+ description: "A page of jobs.",
32217
+ schema: ListSceneCompositionsResponseSchema
32218
+ },
32219
+ 403: scopeForbidden,
32220
+ 422: {
32221
+ description: "A malformed `cursor`, `limit`, `state` or `source`.",
32222
+ schema: ApiErrorSchema
32223
+ },
32224
+ 429: rateLimited
32225
+ },
32226
+ emitsRateLimitHeaders: true,
32227
+ codeSample: {
32228
+ authToken: "b4m_live_<key>",
32229
+ streaming: false,
32230
+ body: {}
32231
+ }
32232
+ });
32233
+ defineEndpoint({
32234
+ method: "post",
32235
+ path: "/api/v1/scene-compositions/{id}/cancel",
32236
+ operationId: "cancelSceneComposition",
32237
+ summary: "Cancel a scene composition",
32238
+ description: "Requests cancellation and returns the job. A job still `pending` (waiting to start, or to retry) moves to `cancelled` shortly after. A Scene renders in one uninterruptible step, so a `running` job cannot be cancelled: the request is refused with a 409 (`not_cancellable`) and the job runs to its end. A finished job is returned unchanged.",
32239
+ tags: ["Scenes"],
32240
+ auth: "apiKeyOrJwt",
32241
+ scopes: ["ai:generate"],
32242
+ pathParams: SceneCompositionIdParamSchema,
32243
+ responses: {
32244
+ 200: {
32245
+ description: "The job after the cancel request.",
32246
+ schema: SceneCompositionSchema,
30741
32247
  example: exampleJob
30742
32248
  },
30743
32249
  403: scopeForbidden,
30744
32250
  404: notFound,
30745
32251
  409: {
30746
- description: "The song is already rendering (`running`); `errorCode` is `not_cancellable`.",
30747
- schema: MusicGenerationErrorResponseSchema
32252
+ description: "The Scene is already rendering (`running`); `errorCode` is `not_cancellable`.",
32253
+ schema: SceneCompositionErrorResponseSchema
30748
32254
  },
30749
32255
  429: rateLimited
30750
32256
  },
@@ -33780,6 +35286,7 @@ const INCIDENT_SURFACES = [
33780
35286
  "edit",
33781
35287
  "upload"
33782
35288
  ];
35289
+ const INCIDENT_ESCALATION_TRIGGERS = ["manual", "timeout"];
33783
35290
  const ModerationLabelHitSchema = z$1.object({
33784
35291
  name: z$1.string(),
33785
35292
  parentName: z$1.string(),
@@ -33807,6 +35314,11 @@ z$1.object({
33807
35314
  noActionAt: z$1.union([z$1.string(), z$1.date()]).optional(),
33808
35315
  alertedAt: z$1.union([z$1.string(), z$1.date()]).optional(),
33809
35316
  lastReminderAt: z$1.union([z$1.string(), z$1.date()]).optional(),
35317
+ escalatedAt: z$1.union([z$1.string(), z$1.date()]).optional(),
35318
+ escalatedBy: z$1.string().optional(),
35319
+ escalationTrigger: z$1.enum(INCIDENT_ESCALATION_TRIGGERS).optional(),
35320
+ escalationAlertedAt: z$1.union([z$1.string(), z$1.date()]).optional(),
35321
+ escalationLastReminderAt: z$1.union([z$1.string(), z$1.date()]).optional(),
33810
35322
  createdAt: z$1.union([z$1.string(), z$1.date()]).optional(),
33811
35323
  updatedAt: z$1.union([z$1.string(), z$1.date()]).optional()
33812
35324
  });
@@ -34100,6 +35612,85 @@ const completionSequenceEvidenceSchema = z$1.strictObject({
34100
35612
  lastObservedAt: z$1.date()
34101
35613
  });
34102
35614
  /**
35615
+ * Admin AI suggestions: a model's advisory verdict on one admin queue item (an abuse detection, a
35616
+ * domain hold, a feedback ticket, ...), stored for an admin to accept, override or dismiss. Stored in
35617
+ * the AdminAiSuggestion collection (packages/database/src/models/infra/admin/AdminAiSuggestionModel.ts);
35618
+ * the per-feature switches live in the adminAiConfig setting (schemas/settings.ts).
35619
+ */
35620
+ const ADMIN_AI_FEATURES = [
35621
+ "abuseAssessment",
35622
+ "domainHold",
35623
+ "detectionTriage",
35624
+ "feedbackTriage",
35625
+ "dlqTriage",
35626
+ "morningBrief"
35627
+ ];
35628
+ /** auto_applied and undone only occur in act mode; expired is a pending row whose input changed. */
35629
+ const ADMIN_AI_SUGGESTION_STATUSES = [
35630
+ "pending",
35631
+ "accepted",
35632
+ "overridden",
35633
+ "dismissed",
35634
+ "auto_applied",
35635
+ "undone",
35636
+ "expired"
35637
+ ];
35638
+ const ADMIN_AI_CONFIDENCE_BANDS = [
35639
+ "high",
35640
+ "medium",
35641
+ "low"
35642
+ ];
35643
+ const ADMIN_AI_MAX_OVERRIDE_REASON_CHARS = 1e3;
35644
+ const adminAiReasonSchema = z$1.object({
35645
+ text: z$1.string().min(1).max(500),
35646
+ evidenceLinks: z$1.array(z$1.string()).max(5)
35647
+ });
35648
+ z$1.object({
35649
+ id: z$1.string().min(1),
35650
+ feature: z$1.enum(ADMIN_AI_FEATURES),
35651
+ entityType: z$1.string().min(1),
35652
+ entityId: z$1.string().min(1),
35653
+ inputHash: z$1.string().min(1),
35654
+ policyVersion: z$1.string().min(1),
35655
+ actionClass: z$1.string().optional(),
35656
+ overrideCostly: z$1.boolean().nullable().optional(),
35657
+ costUnknown: z$1.boolean().optional(),
35658
+ model: z$1.string().min(1),
35659
+ escalated: z$1.boolean(),
35660
+ verdict: z$1.string().min(1),
35661
+ confidence: z$1.object({
35662
+ band: z$1.enum(ADMIN_AI_CONFIDENCE_BANDS),
35663
+ probability: z$1.number().min(0).max(1)
35664
+ }),
35665
+ reasons: z$1.array(adminAiReasonSchema).max(3),
35666
+ proposedAction: z$1.unknown(),
35667
+ status: z$1.enum(ADMIN_AI_SUGGESTION_STATUSES),
35668
+ decidedBy: z$1.object({
35669
+ userId: z$1.string().min(1),
35670
+ name: z$1.string().min(1)
35671
+ }).nullable(),
35672
+ decidedAt: z$1.date().nullable(),
35673
+ overrideAction: z$1.unknown(),
35674
+ overrideReason: z$1.string().max(ADMIN_AI_MAX_OVERRIDE_REASON_CHARS).nullable(),
35675
+ costUsd: z$1.number(),
35676
+ latencyMs: z$1.number(),
35677
+ createdAt: z$1.date(),
35678
+ updatedAt: z$1.date()
35679
+ });
35680
+ /**
35681
+ * Carried by an admin action taken from an assessment suggestion: the assessment the admin saw and,
35682
+ * on an override, why the model was wrong. The server decides accepted vs overridden itself.
35683
+ */
35684
+ const assessmentAiDecisionSchema = z$1.object({
35685
+ assessmentId: z$1.string().regex(/^[a-f0-9]{24}$/i, "Not a valid assessment id"),
35686
+ overrideReason: z$1.string().trim().min(1).max(ADMIN_AI_MAX_OVERRIDE_REASON_CHARS).optional()
35687
+ });
35688
+ z$1.object({
35689
+ surface: z$1.enum(["signupRiskReview", "heldSignupGrant"]),
35690
+ userId: z$1.string().regex(/^[a-f0-9]{24}$/i, "Not a valid user id"),
35691
+ assessmentId: z$1.string().regex(/^[a-f0-9]{24}$/i, "Not a valid assessment id")
35692
+ });
35693
+ /**
34103
35694
  * Shadow detections: what an abuse detector WOULD have done to an actor, recorded next to its alert
34104
35695
  * without acting, so admins can grade each one and measure detection errors before any automated
34105
35696
  * containment is switched on. Recording never changes access, credits, API keys or
@@ -34280,7 +35871,9 @@ z$1.object({
34280
35871
  id: ObjectIdStringSchema$2,
34281
35872
  expectedRevision: z$1.number().int().min(0),
34282
35873
  verdict: z$1.enum(SHADOW_DETECTION_VERDICTS),
34283
- reason: z$1.unknown()
35874
+ reason: z$1.unknown(),
35875
+ /** Set when the grade was taken from the detection's assessment suggestion (accepted or overridden). */
35876
+ aiDecision: assessmentAiDecisionSchema.optional()
34284
35877
  });
34285
35878
  z$1.object({
34286
35879
  items: z$1.array(z$1.object({
@@ -34625,6 +36218,13 @@ const ObjectIdStringSchema$1 = z$1.string().regex(/^[a-f0-9]{24}$/i, "Not a vali
34625
36218
  * approve or change reviewState. An abuse judgment wins over a newer non-abuse one.
34626
36219
  */
34627
36220
  const signupRiskReviewAdvisorySchema = z$1.object({
36221
+ /** The AbuseAssessment shown; an admin action taken from it names this id. */
36222
+ assessmentId: z$1.string(),
36223
+ /**
36224
+ * The admin's decision on this queue's suggestion for that assessment, null while undecided. Set by
36225
+ * each queue's list endpoint, since the same assessment is a separate suggestion on each queue.
36226
+ */
36227
+ decision: z$1.enum(["accepted", "overridden"]).nullable().optional(),
34628
36228
  detectionId: z$1.string(),
34629
36229
  detector: z$1.enum(SHADOW_DETECTORS),
34630
36230
  result: z$1.enum(ABUSE_ASSESSMENT_JUDGMENTS),
@@ -34675,7 +36275,9 @@ z$1.object({
34675
36275
  z$1.object({
34676
36276
  action: z$1.enum(["approve", "reopen"]),
34677
36277
  userIds: z$1.array(ObjectIdStringSchema$1).min(1).max(200),
34678
- reason: z$1.unknown()
36278
+ reason: z$1.unknown(),
36279
+ /** Approving one account over its abuse assessment: recorded as an override of that suggestion. */
36280
+ aiDecision: assessmentAiDecisionSchema.optional()
34679
36281
  });
34680
36282
  z$1.object({
34681
36283
  /** Users whose state changed. */
@@ -34737,72 +36339,6 @@ z$1.object({
34737
36339
  credits: z$1.number().nullable()
34738
36340
  }))
34739
36341
  });
34740
- /**
34741
- * Admin AI suggestions: a model's advisory verdict on one admin queue item (an abuse detection, a
34742
- * domain hold, a feedback ticket, ...), stored for an admin to accept, override or dismiss. Stored in
34743
- * the AdminAiSuggestion collection (packages/database/src/models/infra/admin/AdminAiSuggestionModel.ts);
34744
- * the per-feature switches live in the adminAiConfig setting (schemas/settings.ts).
34745
- */
34746
- const ADMIN_AI_FEATURES = [
34747
- "abuseAssessment",
34748
- "domainHold",
34749
- "detectionTriage",
34750
- "feedbackTriage",
34751
- "dlqTriage",
34752
- "morningBrief"
34753
- ];
34754
- /** auto_applied and undone only occur in act mode; expired is a pending row whose input changed. */
34755
- const ADMIN_AI_SUGGESTION_STATUSES = [
34756
- "pending",
34757
- "accepted",
34758
- "overridden",
34759
- "dismissed",
34760
- "auto_applied",
34761
- "undone",
34762
- "expired"
34763
- ];
34764
- const ADMIN_AI_CONFIDENCE_BANDS = [
34765
- "high",
34766
- "medium",
34767
- "low"
34768
- ];
34769
- const ADMIN_AI_MAX_OVERRIDE_REASON_CHARS = 1e3;
34770
- const adminAiReasonSchema = z$1.object({
34771
- text: z$1.string().min(1).max(500),
34772
- evidenceLinks: z$1.array(z$1.string()).max(5)
34773
- });
34774
- z$1.object({
34775
- id: z$1.string().min(1),
34776
- feature: z$1.enum(ADMIN_AI_FEATURES),
34777
- entityType: z$1.string().min(1),
34778
- entityId: z$1.string().min(1),
34779
- inputHash: z$1.string().min(1),
34780
- policyVersion: z$1.string().min(1),
34781
- actionClass: z$1.string().optional(),
34782
- overrideCostly: z$1.boolean().nullable().optional(),
34783
- costUnknown: z$1.boolean().optional(),
34784
- model: z$1.string().min(1),
34785
- escalated: z$1.boolean(),
34786
- verdict: z$1.string().min(1),
34787
- confidence: z$1.object({
34788
- band: z$1.enum(ADMIN_AI_CONFIDENCE_BANDS),
34789
- probability: z$1.number().min(0).max(1)
34790
- }),
34791
- reasons: z$1.array(adminAiReasonSchema).max(3),
34792
- proposedAction: z$1.unknown(),
34793
- status: z$1.enum(ADMIN_AI_SUGGESTION_STATUSES),
34794
- decidedBy: z$1.object({
34795
- userId: z$1.string().min(1),
34796
- name: z$1.string().min(1)
34797
- }).nullable(),
34798
- decidedAt: z$1.date().nullable(),
34799
- overrideAction: z$1.unknown(),
34800
- overrideReason: z$1.string().max(ADMIN_AI_MAX_OVERRIDE_REASON_CHARS).nullable(),
34801
- costUsd: z$1.number(),
34802
- latencyMs: z$1.number(),
34803
- createdAt: z$1.date(),
34804
- updatedAt: z$1.date()
34805
- });
34806
36342
  const FEEDBACK_AI_AREAS = [
34807
36343
  "chat",
34808
36344
  "models",
@@ -35972,7 +37508,7 @@ Array.from(new Set([
35972
37508
  id: "admin.credit_analytics",
35973
37509
  section: "admin",
35974
37510
  label: "Credit Analytics",
35975
- description: "Credits per user and adjustments, the model pricing catalog, margins against provider invoices, org and API usage, and the transaction ledger",
37511
+ description: "Credits per user and adjustments, margins against provider invoices, org and API usage, and the transaction ledger",
35976
37512
  navigationType: "tab",
35977
37513
  target: "15",
35978
37514
  keywords: [
@@ -36017,16 +37553,20 @@ Array.from(new Set([
36017
37553
  {
36018
37554
  id: "admin.llm_dashboard",
36019
37555
  section: "admin",
36020
- label: "LLM Dashboard",
36021
- description: "Enable or disable LLM models, set model rank and fallback, and choose which user tags and entitlements can use each model",
37556
+ label: "Models",
37557
+ description: "Models users can pick: status, access, rank, prices and discovery",
36022
37558
  navigationType: "tab",
36023
37559
  target: "24",
36024
37560
  keywords: [
36025
37561
  "llm",
36026
- "model",
37562
+ "models",
37563
+ "model access",
37564
+ "model pricing",
37565
+ "prices",
37566
+ "rank",
36027
37567
  "ai",
37568
+ "dashboard",
36028
37569
  "enable model",
36029
- "model access",
36030
37570
  "entitlements"
36031
37571
  ],
36032
37572
  requiresAdmin: true
@@ -36249,21 +37789,6 @@ Array.from(new Set([
36249
37789
  ],
36250
37790
  requiresAdmin: true
36251
37791
  },
36252
- {
36253
- id: "admin.secrets_rotation",
36254
- section: "admin",
36255
- label: "Secrets Rotation",
36256
- description: "Manage API key rotation and secret lifecycle",
36257
- navigationType: "tab",
36258
- target: "16",
36259
- keywords: [
36260
- "secrets",
36261
- "rotation",
36262
- "API keys",
36263
- "credentials"
36264
- ],
36265
- requiresAdmin: true
36266
- },
36267
37792
  {
36268
37793
  id: "admin.feedback",
36269
37794
  section: "admin",
@@ -36693,8 +38218,8 @@ Array.from(new Set([
36693
38218
  {
36694
38219
  id: "admin.secops_triage",
36695
38220
  section: "admin",
36696
- label: "SecOps triage",
36697
- description: "Configure the SecOps triage pipeline: enablement, dry-run, GitHub issue filing and Slack alerts for security findings",
38221
+ label: "Security scan issue filing",
38222
+ description: "Security page, Scans view: GitHub issue filing status, recent filing runs and its settings (dry run, repository, Slack)",
36698
38223
  navigationType: "tab",
36699
38224
  target: "51",
36700
38225
  keywords: [
@@ -36723,6 +38248,40 @@ Array.from(new Set([
36723
38248
  ],
36724
38249
  requiresAdmin: true
36725
38250
  },
38251
+ {
38252
+ id: "admin.access_review",
38253
+ section: "admin",
38254
+ label: "Access review",
38255
+ description: "Quarterly review of who holds admin access: confirm or revoke each admin, flag dormant and no-MFA accounts, export the signed-off review as CSV",
38256
+ navigationType: "tab",
38257
+ target: "81",
38258
+ keywords: [
38259
+ "access review",
38260
+ "quarterly review",
38261
+ "admin access",
38262
+ "dormant admins",
38263
+ "least privilege",
38264
+ "compliance"
38265
+ ],
38266
+ requiresAdmin: true
38267
+ },
38268
+ {
38269
+ id: "admin.spend_explorer",
38270
+ section: "admin",
38271
+ label: "Spend explorer",
38272
+ description: "AI provider cost per day or hour with spikes against the rolling median, split by provider, model, feature or account type, and the accounts that drove any day",
38273
+ navigationType: "tab",
38274
+ target: "82",
38275
+ keywords: [
38276
+ "spend",
38277
+ "ai cost",
38278
+ "cost spike",
38279
+ "provider cost",
38280
+ "top spenders",
38281
+ "cogs"
38282
+ ],
38283
+ requiresAdmin: true
38284
+ },
36726
38285
  {
36727
38286
  id: "admin.approvals",
36728
38287
  section: "admin",
@@ -36845,7 +38404,7 @@ Array.from(new Set([
36845
38404
  id: "admin.model_lifecycle",
36846
38405
  section: "admin",
36847
38406
  label: "Model lifecycle",
36848
- description: "Review detected LLM model deprecations, accept successor models and see stale model references",
38407
+ description: "Models > Discovery: discovery runs, lifecycle suggestions and stale model references",
36849
38408
  navigationType: "tab",
36850
38409
  target: "58",
36851
38410
  keywords: [
@@ -37009,6 +38568,24 @@ Array.from(new Set([
37009
38568
  ],
37010
38569
  requiresAdmin: true
37011
38570
  },
38571
+ {
38572
+ id: "admin.roles",
38573
+ section: "admin",
38574
+ label: "Roles",
38575
+ description: "Create admin roles from templates, edit the permissions each role grants, and delete roles nobody holds",
38576
+ navigationType: "tab",
38577
+ target: "80",
38578
+ keywords: [
38579
+ "roles",
38580
+ "admin roles",
38581
+ "permissions",
38582
+ "role templates",
38583
+ "delegated admin",
38584
+ "access",
38585
+ "support role"
38586
+ ],
38587
+ requiresAdmin: true
38588
+ },
37012
38589
  {
37013
38590
  id: "admin.rate_limits",
37014
38591
  section: "admin",
@@ -37532,11 +39109,36 @@ const ADMIN_PERMISSIONS = [
37532
39109
  ];
37533
39110
  const AdminPermissionSchema = z$1.enum(ADMIN_PERMISSIONS);
37534
39111
  const AdminPermissionsSchema = z$1.array(AdminPermissionSchema).max(ADMIN_PERMISSIONS.length).refine((ids) => new Set(ids).size === ids.length, "Admin permissions must not repeat");
39112
+ const AdminRoleIdSchema = z$1.string().regex(/^[0-9a-f]{24}$/i, "Expected an id");
39113
+ const AdminRoleIdsSchema = z$1.array(AdminRoleIdSchema).max(20).refine((ids) => new Set(ids.map((id) => id.toLowerCase())).size === ids.length, "Admin roles must not repeat");
37535
39114
  z$1.object({
37536
39115
  before: AdminPermissionsSchema,
37537
39116
  adminPermissions: AdminPermissionsSchema,
39117
+ beforeAdminRoleIds: AdminRoleIdsSchema.optional(),
39118
+ adminRoleIds: AdminRoleIdsSchema.optional(),
37538
39119
  reason: z$1.string()
39120
+ }).strict().refine((change) => change.beforeAdminRoleIds === void 0 === (change.adminRoleIds === void 0), "Send beforeAdminRoleIds and adminRoleIds together");
39121
+ /**
39122
+ * Orders a permission set the way ADMIN_PERMISSIONS lists them, so stored arrays and audit diffs are
39123
+ * stable. Drops repeats and ids no longer in the list.
39124
+ */
39125
+ const sortAdminPermissions = (ids) => ADMIN_PERMISSIONS.filter((id) => ids.includes(id));
39126
+ /** At least one permission: an empty role would still mark its members as holding admin access. */
39127
+ const AdminRolePermissionsSchema = z$1.array(AdminPermissionSchema).min(1, "A role needs at least one permission").refine((ids) => new Set(ids).size === ids.length, "Admin permissions must not repeat").transform((ids) => sortAdminPermissions(ids));
39128
+ const AdminRoleNameSchema = z$1.string().trim().min(1, "Name the role").max(60);
39129
+ const AdminRoleDescriptionSchema = z$1.string().trim().max(500);
39130
+ z$1.object({
39131
+ name: AdminRoleNameSchema,
39132
+ description: AdminRoleDescriptionSchema.default(""),
39133
+ permissions: AdminRolePermissionsSchema
37539
39134
  }).strict();
39135
+ z$1.object({
39136
+ name: AdminRoleNameSchema.optional(),
39137
+ description: AdminRoleDescriptionSchema.optional(),
39138
+ permissions: AdminRolePermissionsSchema.optional(),
39139
+ /** Why the role changes; recorded on the audit entry, never stored on the role. Required when `permissions` change (enforced by updateAdminRole). */
39140
+ reason: AdminActionReasonSchema.optional()
39141
+ }).strict().refine(({ reason: _reason, ...fields }) => Object.values(fields).some((value) => value !== void 0), "Nothing to change");
37540
39142
  /**
37541
39143
  * Where an IP block applies. `login` is the automatic failed-login lockout and covers the sign-in
37542
39144
  * routes only; `all` is an admin's fraud block and also covers signup, checkout and AI usage.
@@ -38116,4 +39718,4 @@ const logger = class Logger {
38116
39718
  }.getInstance();
38117
39719
  logger.setVerbose(process.env.B4M_VERBOSE === "1");
38118
39720
  //#endregion
38119
- export { TTS_DEFAULT_MODEL as $, selfClaimedActorKindSchema as $t, DecisionsRequestSchema as A, reasoningChannelOf as At, MODEL_INFO_FIELD_GROUP_OF as B, tokenEstimateMultiplier as Bt, CUSTOM_MCP_DATA_NOTICE as C, isRetryableError as Ct, DEFAULT_TTS_PROVIDER as D, joinReplySlots as Dt, CreateArtifactRequestSchema as E, isUserInitiatedAbort as Et, ImageModels as F, signImageUrl as Ft, OpenAIEmbeddingModel as G, withRetry as Gt, ModelBackend as H, ttsRequestSchema as Ht, ImagePromptResolutionSchema as I, splitEquals as It, REVIEW_GATE_STATUS_VALUES as J, DELEGATION_PAYLOAD_SCHEMA_NAME as Jt, PROMPT_TEXT_MAX as K, withholdsReasoning as Kt, LOCATION_MAP_LANGUAGE as L, stripDeliveredArtifactBlocks as Lt, EMBEDDING_MODEL_IDS as M, resolveSettingDefinition as Mt, ExpectedToolError as N, secureParameters as Nt, DEGENERATE_FINISH_REASON as O, obfuscateApiKey as Ot, GENERATED_IMAGE_EXTENSION_RE as P, servableEmbeddingDimensions as Pt, SupportedFabFileMimeTypes as Q, delegationPayloadSchema as Qt, LOW_CONFIDENCE_COMPLETION_MODES as R, stripToolArtifactMarkup as Rt, CREDIT_DEDUCT_TRANSACTION_TYPES as S, isProviderRefusalStopReason as St, CompletionReasoningEffortSchema as T, isSupportedFabFileMimeType as Tt, NotFoundError as U, ttsResponseTooLargeSchema as Ut, McpServerName as V, ttsBase64ResponseSchema as Vt, OllamaEmbeddingModel as W, visibleReplyText as Wt, SLUG_OWNED_BY_OTHER as X, actorKindMarker as Xt, SEARCH_RESULT_CARDS_LANGUAGE as Y, actorColorIndex as Yt, SUBQUEST_STATUS_VALUES as Z, actorKindSchema as Zt, BRIEFCASE_CATALOG_QUERIES as _, hasDeliverablePinnedArtifact as _t, htmlFirstH1 as a, assertAuthOriginMatchesApiKey as at, CONFIDENCE_GATE_MODES as b, isExpectedToolError as bt, AGENT_QUEST_MANIFEST as c, createReasoningWithholder as ct, ARTIFACT_REMOVED_PLACEHOLDER as d, filterToolArtifactMarkup as dt, frontmatterHasSourceStamp as en, TTS_MAX_INPUT_CHARS as et, AdminAiStoredConfigSchema as f, generatedAudioResponseSchema as ft, AudioMimeType as g, googleMapsSearchUrl as gt, ArtifactTypeSchema as h, getQuestErrorCode as ht, htmlErrorTitle as i, WEBSITE_URL as in, WORK_ITEM_STATUSES as it, EMBEDDING_MODEL_CATALOG as j, replacePromptVariables as jt, DecisionTextPartSchema as k, questReplyText as kt, AGENT_QUEST_MCP_URI as l, createThinkMarkerEscaper as lt, ApiKeyType as m, getMcpProviderMetadata as mt, SESSION_ID_PATTERN as n, splitSkillMdFrontmatter as nn, VisibilitySchema as nt, escapeArtifactBodyJson as o, buildPromptContext as ot, ApiKeyScope as p, getEmbeddingModelCapabilities as pt, PermissionDeniedError as q, ACTOR_COLOR_SLOTS as qt, isValidSessionId as r, APP_NAME as rn, VoyageAIEmbeddingModel as rt, AGENT_QUEST_ID as s, completionsSupportsToolSearch as st, logger as t, readSkillMdSourceUrl as tn, UnprocessableEntityError as tt, ARTIFACT_DELIVERED_PLACEHOLDER as u, escapeThinkMarkers as ut, BedrockEmbeddingModel as v, isEarlyStop as vt, ChatModels as w, isSupportedEmbeddingModel as wt, CONTEXT_WINDOW_SAFETY_BUFFER_TOKENS as x, isPlaceholderImageSigningSecret as xt, BriefcasePromptIdSchema as y, isEnforceCreditsLocked as yt, MODEL_DECLINED_MESSAGE as z, supportedVoiceGenerationVendor as zt };
39721
+ export { SupportedFabFileMimeTypes as $, frontmatterHasSourceStamp as $t, DecisionTextPartSchema as A, replacePromptVariables as At, MODEL_DECLINED_MESSAGE as B, ttsBase64ResponseSchema as Bt, CREDIT_DEDUCT_TRANSACTION_TYPES as C, isSupportedEmbeddingModel as Ct, CreateArtifactRequestSchema as D, obfuscateApiKey as Dt, CompletionReasoningEffortSchema as E, joinReplySlots as Et, GENERATED_IMAGE_EXTENSION_RE as F, splitEquals as Ft, OllamaEmbeddingModel as G, withholdsReasoning as Gt, McpServerName as H, ttsResponseTooLargeSchema as Ht, ImageModels as I, stripDeliveredArtifactBlocks as It, PermissionDeniedError as J, actorColorIndex as Jt, OpenAIEmbeddingModel as K, ACTOR_COLOR_SLOTS as Kt, ImagePromptResolutionSchema as L, stripToolArtifactMarkup as Lt, EMBEDDING_MODEL_CATALOG as M, secureParameters as Mt, EMBEDDING_MODEL_IDS as N, servableEmbeddingDimensions as Nt, DEFAULT_TTS_PROVIDER as O, questReplyText as Ot, ExpectedToolError as P, signImageUrl as Pt, SUBQUEST_STATUS_VALUES as Q, selfClaimedActorKindSchema as Qt, LOCATION_MAP_LANGUAGE as R, supportedVoiceGenerationVendor as Rt, CONTEXT_WINDOW_SAFETY_BUFFER_TOKENS as S, isRetryableError as St, ChatModels as T, isUserInitiatedAbort as Tt, ModelBackend as U, visibleReplyText as Ut, MODEL_INFO_FIELD_GROUP_OF as V, ttsRequestSchema as Vt, NotFoundError as W, withRetry as Wt, SEARCH_RESULT_CARDS_LANGUAGE as X, actorKindSchema as Xt, REVIEW_GATE_STATUS_VALUES as Y, actorKindMarker as Yt, SLUG_OWNED_BY_OTHER as Z, delegationPayloadSchema as Zt, AudioMimeType as _, isEarlyStop as _t, htmlFirstH1 as a, buildPromptContext as at, BriefcasePromptIdSchema as b, isPlaceholderImageSigningSecret as bt, AGENT_QUEST_MANIFEST as c, createThinkMarkerEscaper as ct, ARTIFACT_REMOVED_PLACEHOLDER as d, generatedAudioResponseSchema as dt, readSkillMdSourceUrl as en, UnprocessableEntityError as et, AdminAiStoredConfigSchema as f, getEmbeddingModelCapabilities as ft, ArtifactTypeSchema as g, hasDeliverablePinnedArtifact as gt, ApiKeyType as h, googleMapsSearchUrl as ht, htmlErrorTitle as i, assertAuthOriginMatchesApiKey as it, DecisionsRequestSchema as j, resolveSettingDefinition as jt, DEGENERATE_FINISH_REASON as k, reasoningChannelOf as kt, AGENT_QUEST_MCP_URI as l, escapeThinkMarkers as lt, ApiKeyScope as m, getQuestErrorCode as mt, SESSION_ID_PATTERN as n, APP_NAME as nn, VoyageAIEmbeddingModel as nt, escapeArtifactBodyJson as o, completionsSupportsToolSearch as ot, AiAccessRefusedError as p, getMcpProviderMetadata as pt, PROMPT_TEXT_MAX as q, DELEGATION_PAYLOAD_SCHEMA_NAME as qt, isValidSessionId as r, WEBSITE_URL as rn, WORK_ITEM_STATUSES as rt, AGENT_QUEST_ID as s, createReasoningWithholder as st, logger as t, splitSkillMdFrontmatter as tn, VisibilitySchema as tt, ARTIFACT_DELIVERED_PLACEHOLDER as u, filterToolArtifactMarkup as ut, BRIEFCASE_CATALOG_QUERIES as v, isEnforceCreditsLocked as vt, CUSTOM_MCP_DATA_NOTICE as w, isSupportedFabFileMimeType as wt, CONFIDENCE_GATE_MODES as x, isProviderRefusalStopReason as xt, BedrockEmbeddingModel as y, isExpectedToolError as yt, LOW_CONFIDENCE_COMPLETION_MODES as z, tokenEstimateMultiplier as zt };