transloadit 5.1.0 → 6.0.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 (76) hide show
  1. package/dist/Transloadit.d.ts +10 -0
  2. package/dist/Transloadit.d.ts.map +1 -1
  3. package/dist/Transloadit.js +26 -1
  4. package/dist/Transloadit.js.map +1 -1
  5. package/dist/alphalib/aiMessages.d.ts +1 -1
  6. package/dist/alphalib/aiMessages.d.ts.map +1 -1
  7. package/dist/alphalib/aiMessages.js +1 -1
  8. package/dist/alphalib/aiMessages.js.map +1 -1
  9. package/dist/alphalib/types/assemblyStatus.d.ts +682 -682
  10. package/dist/alphalib/types/assemblyStatus.d.ts.map +1 -1
  11. package/dist/alphalib/types/assemblyStatus.js +23 -14
  12. package/dist/alphalib/types/assemblyStatus.js.map +1 -1
  13. package/dist/alphalib/types/robots/_ai-models.d.ts.map +1 -1
  14. package/dist/alphalib/types/robots/_ai-models.js +2 -0
  15. package/dist/alphalib/types/robots/_ai-models.js.map +1 -1
  16. package/dist/alphalib/types/robots/_google-image-seed.d.ts +8 -0
  17. package/dist/alphalib/types/robots/_google-image-seed.d.ts.map +1 -0
  18. package/dist/alphalib/types/robots/_google-image-seed.js +12 -0
  19. package/dist/alphalib/types/robots/_google-image-seed.js.map +1 -0
  20. package/dist/alphalib/types/robots/_instructions-primitives.d.ts +2 -0
  21. package/dist/alphalib/types/robots/_instructions-primitives.d.ts.map +1 -1
  22. package/dist/alphalib/types/robots/_instructions-primitives.js +11 -14
  23. package/dist/alphalib/types/robots/_instructions-primitives.js.map +1 -1
  24. package/dist/alphalib/types/robots/ai-chat.d.ts +1 -1
  25. package/dist/alphalib/types/robots/ai-chat.d.ts.map +1 -1
  26. package/dist/alphalib/types/robots/ai-chat.js.map +1 -1
  27. package/dist/alphalib/types/robots/google-import.d.ts +4 -6
  28. package/dist/alphalib/types/robots/google-import.d.ts.map +1 -1
  29. package/dist/alphalib/types/robots/google-import.js +5 -2
  30. package/dist/alphalib/types/robots/google-import.js.map +1 -1
  31. package/dist/alphalib/types/robots/google-store.d.ts.map +1 -1
  32. package/dist/alphalib/types/robots/google-store.js +5 -13
  33. package/dist/alphalib/types/robots/google-store.js.map +1 -1
  34. package/dist/alphalib/types/robots/http-import.d.ts.map +1 -1
  35. package/dist/alphalib/types/robots/http-import.js +4 -0
  36. package/dist/alphalib/types/robots/http-import.js.map +1 -1
  37. package/dist/alphalib/types/robots/image-generate.d.ts.map +1 -1
  38. package/dist/alphalib/types/robots/image-generate.js +6 -1
  39. package/dist/alphalib/types/robots/image-generate.js.map +1 -1
  40. package/dist/alphalib/types/robots/image-resize.d.ts +4 -0
  41. package/dist/alphalib/types/robots/image-resize.d.ts.map +1 -1
  42. package/dist/alphalib/types/robots/image-resize.js +34 -6
  43. package/dist/alphalib/types/robots/image-resize.js.map +1 -1
  44. package/dist/alphalib/types/robots/s3-store.d.ts.map +1 -1
  45. package/dist/alphalib/types/robots/s3-store.js +21 -17
  46. package/dist/alphalib/types/robots/s3-store.js.map +1 -1
  47. package/dist/alphalib/types/robots/video-thumbs.d.ts +6 -0
  48. package/dist/alphalib/types/robots/video-thumbs.d.ts.map +1 -1
  49. package/dist/alphalib/types/robots/video-thumbs.js +15 -5
  50. package/dist/alphalib/types/robots/video-thumbs.js.map +1 -1
  51. package/dist/alphalib/zodParseWithContext.d.ts +1 -1
  52. package/dist/alphalib/zodParseWithContext.d.ts.map +1 -1
  53. package/dist/apiTypes.d.ts +2 -0
  54. package/dist/apiTypes.d.ts.map +1 -1
  55. package/dist/inputFiles.d.ts +9 -0
  56. package/dist/inputFiles.d.ts.map +1 -1
  57. package/dist/inputFiles.js +62 -10
  58. package/dist/inputFiles.js.map +1 -1
  59. package/package.json +1 -1
  60. package/src/Transloadit.ts +42 -1
  61. package/src/alphalib/aiMessages.ts +1 -1
  62. package/src/alphalib/types/assemblyStatus.ts +24 -14
  63. package/src/alphalib/types/robots/_ai-models.ts +2 -0
  64. package/src/alphalib/types/robots/_google-image-seed.ts +14 -0
  65. package/src/alphalib/types/robots/_instructions-primitives.ts +13 -15
  66. package/src/alphalib/types/robots/ai-chat.ts +6 -7
  67. package/src/alphalib/types/robots/google-import.ts +7 -1
  68. package/src/alphalib/types/robots/google-store.ts +6 -11
  69. package/src/alphalib/types/robots/http-import.ts +4 -0
  70. package/src/alphalib/types/robots/image-generate.ts +8 -1
  71. package/src/alphalib/types/robots/image-resize.ts +36 -6
  72. package/src/alphalib/types/robots/s3-store.ts +21 -17
  73. package/src/alphalib/types/robots/video-thumbs.ts +19 -5
  74. package/src/alphalib/zodParseWithContext.ts +1 -1
  75. package/src/apiTypes.ts +2 -0
  76. package/src/inputFiles.ts +83 -8
@@ -51,13 +51,12 @@ type Part<Type extends MessagePart['type']> = Extract<MessagePart, { type: Type
51
51
  type ToolOutput = Part<'tool-result'>['output']
52
52
 
53
53
  type ProviderMetadata = NonNullable<z.output<typeof providerMetadataSchema>>
54
- type CompatibleProviderOptions<Part extends { providerOptions?: ProviderMetadata }> = Omit<
55
- Part,
56
- 'providerOptions'
57
- > & {
58
- providerOptions?: ProviderMetadata
59
- experimental_providerMetadata?: ProviderMetadata
60
- }
54
+ // Zod output retains explicit undefined even when the consumer enables exact optional properties.
55
+ type CompatibleProviderOptions<Part extends { providerOptions?: ProviderMetadata | undefined }> =
56
+ Omit<Part, 'providerOptions'> & {
57
+ providerOptions?: ProviderMetadata
58
+ experimental_providerMetadata?: ProviderMetadata
59
+ }
61
60
  type MessageProviderOptions = {
62
61
  providerOptions?: ProviderMetadata
63
62
  experimental_providerMetadata?: ProviderMetadata
@@ -9,6 +9,7 @@ import { z } from 'zod'
9
9
  import {
10
10
  createStorageImportExample,
11
11
  defineRobot,
12
+ getGoogleCredentialsDescription,
12
13
  googleBase,
13
14
  next_page_token,
14
15
  path,
@@ -37,6 +38,11 @@ export const robotGoogleImportInstructionsSchema = robotBase
37
38
  .merge(googleBase)
38
39
  .extend({
39
40
  robot: z.literal('/google/import'),
41
+ credentials: googleBase.shape.credentials.describe(
42
+ getGoogleCredentialsDescription(`
43
+ Grant the service account the “Storage Object Viewer” role on the bucket you want to import from. This provides \`storage.objects.get\` to download objects and \`storage.objects.list\` to list them. Imports do not need permission to create or delete objects. See [Google’s IAM roles for Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/iam-roles).
44
+ `),
45
+ ),
40
46
  path: path.describe(`
41
47
  The path in your bucket to the specific file or directory. If the path points to a file, only this file will be imported. For example: \`images/avatar.jpg\`.
42
48
 
@@ -51,7 +57,7 @@ You can also use an array of path strings here to import multiple paths in the s
51
57
  recursive: recursive.describe(`
52
58
  Setting this to \`true\` will enable importing files from subdirectories and sub-subdirectories (etc.) of the given path.
53
59
 
54
- Please use the pagination parameters \`start_file_name\` and \`files_per_page\` wisely here.
60
+ Please use the pagination parameters \`next_page_token\` and \`files_per_page\` wisely here.
55
61
  `),
56
62
  next_page_token: next_page_token.describe(`
57
63
  A string token used for pagination. The returned files of one paginated call have the next page token inside of their meta data, which needs to be used for the subsequent paging call.
@@ -9,6 +9,7 @@ import { z } from 'zod'
9
9
  import {
10
10
  createStorageStoreExample,
11
11
  defineRobot,
12
+ getGoogleCredentialsDescription,
12
13
  googleBase,
13
14
  robotBase,
14
15
  robotStoreMeta,
@@ -39,19 +40,13 @@ The URL to the exported file in your Google bucket will be presented in the Tran
39
40
  .boolean()
40
41
  .optional()
41
42
  .describe('Whether the results of this Step should be present in the Assembly Status JSON'),
42
- credentials: z.string().describe(`
43
- Create a new [Google service account](https://cloud.google.com/storage/docs/authentication). Set its role to "Storage Object Creator". Choose "JSON" for the key file format and download it to your computer. You will need to upload this file when creating your <dfn>Template Credentials</dfn>.
43
+ credentials: z.string().describe(
44
+ getGoogleCredentialsDescription(`
45
+ Grant the service account \`storage.objects.create\` on the bucket you want to export to. The “Storage Object Creator” role provides this permission for new objects, but does not allow overwriting existing objects. Add \`storage.objects.delete\` only if you need to overwrite existing objects. See [Google’s IAM roles for Cloud Storage](https://docs.cloud.google.com/storage/docs/access-control/iam-roles).
44
46
 
45
- Go back to your Google credentials project and enable the "Google Cloud Storage JSON API" for it. Wait around ten minutes for the action to propagate through the Google network. Grab the project ID from the dropdown menu in the header bar on the Google site. You will also need it later on.
46
-
47
- Now you can set up the \`storage.objects.create\` and \`storage.objects.delete\` permissions. The latter is optional and only required if you intend to overwrite existing paths.
48
-
49
- To do this from the Google Cloud console, navigate to "IAM &amp; Admin" and select "Roles". From here, click "Create Role", enter a name, set the role launch stage to _General availability,_ and set the permissions stated above.
50
-
51
- Next, go to Storage browser and select the ellipsis on your bucket to edit bucket permissions. From here, select "Add Member", enter your service account as a new member, and select your newly created role.
52
-
53
- Then, create your associated [Template Credentials](/c/template-credentials/) in your Transloadit account and use the name of your <dfn>Template Credentials</dfn> as this parameter's value.
47
+ For overwrites, create a custom role in “IAM &amp; Admin” → “Roles” with \`storage.objects.create\` and \`storage.objects.delete\`, then grant it to the service account on your bucket.
54
48
  `),
49
+ ),
55
50
  path: z
56
51
  .string()
57
52
  .default('${unique_prefix}/${file.url_name}')
@@ -55,12 +55,16 @@ The URL from which the file to be imported can be retrieved.
55
55
  HTTPS URLs must present a valid certificate trusted by Transloadit and matching the requested hostname. Self-signed, expired, or hostname-mismatched certificates cause \`${httpImportRobotErrors.HTTP_IMPORT_FAILURE.error}\`.
56
56
 
57
57
  You can also specify an array of URLs or a string of \`|\` delimited URLs to import several files at once. Please also check the \`url_delimiter\` parameter for that.
58
+
59
+ Delimited URL lists are split before variables are interpolated. A delimiter introduced by a variable remains part of that URL. To supply several URLs through a variable, have the entire \`url\` value interpolate to an array of URLs.
58
60
  `),
59
61
  url_delimiter: z
60
62
  .string()
61
63
  .default('|')
62
64
  .describe(`
63
65
  Provides the delimiter that is used to split the URLs in your \`url\` parameter value.
66
+
67
+ The delimiter must be literal. Only delimiters outside interpolation expressions in the original \`url\` value separate imports; variable values are never split.
64
68
  `),
65
69
  headers: z
66
70
  .union([
@@ -7,6 +7,7 @@ import {
7
7
  imageGenerateLegacyModelAlias,
8
8
  imageGenerateModelIdentifiers,
9
9
  } from './_ai-models.ts'
10
+ import { googleImageSeedMaximum } from './_google-image-seed.ts'
10
11
  import {
11
12
  autoProviderDescription,
12
13
  interpolateRobot,
@@ -101,7 +102,13 @@ Best practice:
101
102
  .describe(
102
103
  'Output format. Defaults depend on model: png for Google and OpenAI models, svg for recraft-v3, jpeg for others. Google models currently return PNG only.',
103
104
  ),
104
- seed: z.number().optional().describe(robotParameterDocs.seed.description),
105
+ // Provider-specific limits are checked by the Robot so other models retain their seed range.
106
+ seed: z
107
+ .number()
108
+ .optional()
109
+ .describe(
110
+ `${robotParameterDocs.seed.description} For Google models, use an integer from 0 to ${googleImageSeedMaximum}. Each output increments the seed by 1, so the final output’s seed must also fit this range. A seed does not guarantee identical images.`,
111
+ ),
105
112
  aspect_ratio: z
106
113
  .string()
107
114
  .optional()
@@ -29,6 +29,34 @@ import {
29
29
 
30
30
  const imageResizeGravitySchema = z.union([positionSchema, z.enum(['attention', 'entropy'])])
31
31
 
32
+ /** Input MIME types eligible for automatic libvips processing in /image/resize. */
33
+ export const imageResizeDaemonInputMimes: readonly string[] = [
34
+ 'image/jpg',
35
+ 'image/jpeg',
36
+ 'image/jxl',
37
+ 'image/png',
38
+ 'image/tiff',
39
+ 'image/tiff-fx',
40
+ 'image/gif',
41
+ 'image/webp',
42
+ 'image/svg',
43
+ 'image/svg+xml',
44
+ ]
45
+
46
+ /** Output formats eligible for automatic libvips processing in /image/resize. */
47
+ export const imageResizeDaemonOutputFormats: readonly string[] = [
48
+ 'heic',
49
+ 'heif',
50
+ 'jpeg',
51
+ 'jpg',
52
+ 'jxl',
53
+ 'png',
54
+ 'raw',
55
+ 'tiff',
56
+ 'webp',
57
+ 'avif',
58
+ ]
59
+
32
60
  export const meta: RobotMetaInput = {
33
61
  ...robotImageProcessingMeta,
34
62
  example_code: createProcessingExample('resized', '/image/resize', {
@@ -171,14 +199,14 @@ Height of the new image, in pixels. If not specified, will default to the height
171
199
  .union([
172
200
  z
173
201
  .literal('crop')
174
- .describe(`Cuts an area out of an image, discarding any overlapping parts. If the source image is smaller than the crop frame, it will be zoomed. This strategy is implied when you specify coordinates in the \`crop\` parameter, and cannot be used without it.
202
+ .describe(`Cuts an area out of an image. Coordinates in the \`crop\` parameter imply this strategy. With coordinates, ImageMagick crops without resizing; libvips enlarges the image if \`x2\` or \`y2\` exceeds its dimensions, even with \`zoom: false\`. Without coordinates, set both \`width\` and \`height\`; this uses \`fillcrop\`, with \`gravity\` selecting which part is kept. With the default \`zoom\` setting, this coordinate-free path scales the image to cover that rectangle before trimming.
175
203
 
176
204
  To crop around human faces, see [🤖/image/facedetect](https://transloadit.com/docs/robots/image-facedetect/) instead.`),
177
205
  z
178
206
  .literal('fillcrop')
179
207
  .describe(`Scales the image to fit into our 100×100 target while preserving aspect ratio, while trimming away any excess surface. This means both sides will become exactly 100 pixels, at the tradeoff of destroying parts of the image.
180
208
 
181
- By default the resulting image is horizontally/vertically centered to fill the target rectangle. Use the \`gravity\` parameter to change where to crop the image, such as \`"bottom\`" or \`"left\`".`),
209
+ By default the resulting image is horizontally/vertically centered to fill the target rectangle. Use the \`gravity\` parameter to change where to crop the image, such as \`"bottom"\` or \`"left"\`.`),
182
210
  z
183
211
  .literal('fit')
184
212
  .describe(`Uses the larger side of the original image as a base for the resize. Aspect ratio is preserved. Either side will become at most 100 pixels.
@@ -224,7 +252,7 @@ For example:
224
252
  }
225
253
  \`\`\`
226
254
 
227
- This will crop the area from \`(80, 100)\` to \`(600, 800)\` from a 1000×1000 pixels image, which is a square whose width is 520px and height is 700px. If \`crop\` is set, the width and height parameters are ignored, and the \`resize_strategy\` is set to \`crop\` automatically.
255
+ This will crop the area from \`(80, 100)\` to \`(600, 800)\` from a 1000×1000 pixels image, which is a rectangle whose width is 520px and height is 700px. If \`crop\` is set, the width and height parameters are ignored, and the \`resize_strategy\` is set to \`crop\` automatically.
228
256
 
229
257
  You can also use a JSON string of such an object with coordinates in similar fashion:
230
258
 
@@ -235,9 +263,11 @@ You can also use a JSON string of such an object with coordinates in similar fas
235
263
  To crop around human faces, see [🤖/image/facedetect](/docs/robots/image-facedetect/).
236
264
  `),
237
265
  gravity: imageResizeGravitySchema.default('center').describe(`
238
- The direction from which the image is to be cropped when \`"resize_strategy"\` is set to \`"crop"\` or \`"fillcrop"\`, but no crop coordinates are defined.
239
-
240
- You can also use \`"entropy"\` or \`"attention"\` for automatic point-of-interest cropping. \`"entropy"\` keeps the region with the highest Shannon entropy, while \`"attention"\` favors areas with luminance frequency, saturation, and skin-tone cues.
266
+ Sets crop direction for \`crop\` or \`fillcrop\` without explicit coordinates.
267
+ Content-aware \`attention\` and \`entropy\` need libvips, \`fillcrop\`, \`width\` and \`height\`.
268
+ Effects such as \`sepia\` or \`text\`, and inputs such as HEIC, can use ImageMagick.
269
+ It centers these crops and the Assembly reports a warning.
270
+ Crop in a separate /image/resize Step before effects, or convert unsupported inputs to PNG first.
241
271
  `),
242
272
  strip: z
243
273
  .boolean()
@@ -38,48 +38,54 @@ export const robotS3StoreInstructionsSchema = robotBase
38
38
  .merge(robotUse)
39
39
  .merge(s3Base)
40
40
  .extend({
41
+ // URL rewriting does not fix bucket addressing, and custom paths need not use file.url_name.
42
+ // Keep the bucket warning separate from the old blanket filename-sanitization claim.
41
43
  robot: z.literal('/s3/store').describe(`
42
44
  If you are new to Amazon S3, see our tutorial on [using your own S3 bucket](/docs/faq/how-to-set-up-an-amazon-s3-bucket/).
43
45
 
44
- The URL to the result file in your S3 bucket will be returned in the <dfn>Assembly Status JSON</dfn>. If your S3 bucket has versioning enabled, the version ID of the file will be returned within \`meta.version_id\`
46
+ The URL to the result file in your S3 bucket will be returned in the <dfn>Assembly Status JSON</dfn>. A returned URL does not make a private object public or grant read access. If your S3 bucket has versioning enabled, the version ID of the file will be returned within \`meta.version_id\`.
45
47
 
46
48
  > [!Warning]
47
- > **Avoid permission errors.** By default, \`acl\` is set to \`"${s3StoreAclSchema.parse(undefined)}"\`. AWS S3 has a bucket setting called \`Block new public ACLs and uploading public objects\`. Set this to <strong>False</strong> in your bucket if you intend to leave \`acl\` as \`"${s3StoreAclSchema.parse(undefined)}"\`. Otherwise, you’ll receive permission errors in your Assemblies despite your S3 credentials being configured correctly.
49
+ > **Configure private buckets explicitly.** The Robot’s default \`acl\` is still \`"${s3StoreAclSchema.parse(undefined)}"\`. For a private bucket, set \`acl: "bucket-default"\` and do not supply ACL or grant headers. This omits the generated ACL header and works with [Bucket owner enforced Object Ownership](https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html), where ACLs are disabled. Keep S3 Block Public Access enabled. Setting \`acl: "private"\` still sends an ACL and is not equivalent to omitting it.
48
50
 
49
51
  > [!Warning]
50
- > **Use DNS-compliant bucket names.** Your bucket name [must be DNS-compliant](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html) and must not contain uppercase letters. Any non-alphanumeric characters in the file names will be replaced with an underscore, and spaces will be replaced with dashes. If your existing S3 bucket contains uppercase letters or is otherwise not DNS-compliant, rewrite the result URLs using the <dfn>Robot</dfn>’s \`url_prefix\` parameter.
52
+ > **Use DNS-compliant bucket names.** Follow AWS’s [bucket naming rules](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html). The \`url_prefix\` parameter changes returned URLs; it does not change the bucket or its access permissions.
51
53
 
52
54
  <span id="minimum-s3-iam-permissions" aria-hidden="true"></span>
53
55
 
54
56
  ## Limit access
55
57
 
56
- You will also need to add permissions to your bucket so that Transloadit can access it properly. Here is an example IAM policy that you can use. Following the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege), it contains the **minimum required permissions** to export a file to your S3 bucket using Transloadit. You may require more permissions (especially viewing permissions) depending on your application.
58
+ Use a dedicated AWS identity with access limited to the destination bucket and object prefix. Do not use [AWS root access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/root-user-best-practices.html). Store its access key ID, secret access key, bucket name and region as \`key\`, \`secret\`, \`bucket\` and \`bucket_region\` in <dfn>Template Credentials</dfn>, then reference their name with \`credentials\`. Trusted backend integrations can instead supply those parameters directly; do not expose AWS secrets in browser instructions.
57
59
 
58
- Please change \`{BUCKET_NAME}\` in the values for \`Sid\` and \`Resource\` accordingly. Also, this policy will grant the minimum required permissions to all your users. We advise you to create a separate Amazon IAM user, and use its User ARN (can be found in the "Summary" tab of a user [here](https://console.aws.amazon.com/iam/home#users)) for the \`Principal\` value. More information about this can be found [here](https://docs.aws.amazon.com/AmazonS3/latest/dev/AccessPolicyLanguage_UseCases_s3_a.html).
60
+ The following is an [identity-based IAM policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html), attached to that dedicated identity, not a bucket policy. It intentionally has no \`Principal\`. Replace \`{BUCKET_NAME}\` and use a Robot \`path\` beginning with \`uploads/\`, or adapt both the policy prefix and the path together.
61
+
62
+ This example covers uploads and failed multipart-upload cleanup with an explicit \`bucket_region\`, \`acl: "bucket-default"\`, no ACL/grant headers, no tags and S3-managed encryption (SSE-S3). Existing bucket policies, organization controls or endpoint policies can still deny access.
59
63
 
60
64
  \`\`\`json
61
65
  {
62
66
  "Version": "2012-10-17",
63
67
  "Statement": [
64
68
  {
65
- "Sid": "AllowTransloaditToStoreFilesIn{BUCKET_NAME}Bucket",
69
+ "Sid": "UploadAndAbortWithinPrefix",
66
70
  "Effect": "Allow",
67
- "Action": ["s3:GetBucketLocation", "s3:ListBucket", "s3:PutObject", "s3:PutObjectAcl"],
68
- "Resource": ["arn:aws:s3:::{BUCKET_NAME}", "arn:aws:s3:::{BUCKET_NAME}/*"]
71
+ "Action": ["s3:PutObject", "s3:AbortMultipartUpload"],
72
+ "Resource": "arn:aws:s3:::{BUCKET_NAME}/uploads/*"
69
73
  }
70
74
  ]
71
75
  }
72
76
  \`\`\`
73
77
 
74
- The \`Sid\` value is just an identifier for you to recognize the rule later. You can name it anything you like.
78
+ The uploader uses either \`PutObject\` or \`CreateMultipartUpload\`, \`UploadPart\` and \`CompleteMultipartUpload\`; failed multipart uploads can trigger \`AbortMultipartUpload\`. AWS maps the successful upload operations to \`s3:PutObject\`. Write access can **overwrite an existing object key**; it is not add-only. Choose unique object paths and consider versioning for recovery.
75
79
 
76
- The policy needs to be separated into two parts, because the \`ListBucket\` action requires permissions on the bucket while the other actions require permissions on the objects in the bucket. When targeting the objects there's a trailing slash and an asterisk in the \`Resource\` parameter, whereas when the policy targets the bucket, the slash and the asterisk are omitted.
80
+ Add permissions only for features you use, following AWS’s [operation permission reference](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-with-s3-policy-actions.html):
77
81
 
78
- Please note that if you give the <dfn>Robot</dfn>'s \`acl\` parameter a value of \`"bucket-default"\`, then you do not need the \`"s3:PutObjectAcl"\` permission in your bucket policy.
82
+ - Without an explicit \`bucket_region\`, region discovery can require \`s3:GetBucketLocation\` and fallback \`s3:ListBucket\` on the bucket ARN, \`arn:aws:s3:::{BUCKET_NAME}\`, without an object suffix. Supplying the correct region avoids these discovery requests.
83
+ - ACL or grant headers require \`s3:PutObjectAcl\`; tags require \`s3:PutObjectTagging\` on the allowed object prefix. \`bucket-default\` does not remove ACL/grant headers you supply in \`headers\`.
84
+ - Downloading private results requires separate read authorization. Even a URL generated with \`sign_urls_for\` needs the signing identity to have the appropriate read permissions.
79
85
 
80
- In order to build proper result URLs we need to know the region in which your S3 bucket resides. For this we require the \`GetBucketLocation\` permission. Figuring out your bucket's region this way will also slow down your Assemblies. To make this much faster and to also not require the \`GetBucketLocation\` permission, we have added the \`bucket_region\` parameter to the /s3/store and /s3/import Robots. We recommend using them at all times.
86
+ S3 applies its [bucket encryption configuration](https://docs.aws.amazon.com/AmazonS3/latest/userguide/default-bucket-encryption.html) when no encryption override is sent. You can request SSE-KMS through \`headers\`, using \`x-amz-server-side-encryption: aws:kms\` and \`x-amz-server-side-encryption-aws-kms-key-id\`. When either bucket default encryption or request headers select [SSE-KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html), the uploading identity needs \`kms:GenerateDataKey\` on the relevant key, plus \`kms:Decrypt\` for multipart uploads. For a customer-managed key, grant these permissions with a compatible KMS key policy; the base S3 policy above does not include them. Do not add blanket \`kms:*\` or \`sts:*\` grants.
81
87
 
82
- Please keep in mind that if you use bucket encryption you may also need to add \`"sts:*"\` and \`"kms:*"\` to the bucket policy. Please read [here](https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html) and [here](https://aws.amazon.com/blogs/security/how-to-restrict-amazon-s3-bucket-access-to-a-specific-iam-role/) in case you run into trouble with our example bucket policy.
88
+ Short-lived AWS credentials are a matching set of \`key\`, \`secret\` and \`session_token\`. Have a trusted backend obtain and refresh all three, then supply them together when it creates the Assembly. It can pass them directly in Robot instructions or save and update them together through the [Template Credentials API](/docs/api/template-credentials-post/). Keep all three out of browser instructions; replacing only the session token does not refresh expired access keys. This Robot passes the supplied credentials to S3; it does not assume a role or refresh expired credentials. Keep temporary credentials valid for the upload.
83
89
  `),
84
90
  path: storeFilePath,
85
91
  url_prefix: z
@@ -89,9 +95,7 @@ Please keep in mind that if you use bucket encryption you may also need to add \
89
95
  The URL prefix used for the returned URL, such as \`"http://my.cdn.com/some/path/"\`.
90
96
  `),
91
97
  acl: s3StoreAclSchema.describe(`
92
- The permissions used for this file.
93
-
94
- Please keep in mind that the default value \`"${s3StoreAclSchema.parse(undefined)}"\` can lead to permission errors due to the \`"Block all public access"\` checkbox that is checked by default when creating a new Amazon S3 Bucket in the AWS console.
98
+ The ACL used for this file. The default remains \`"${s3StoreAclSchema.parse(undefined)}"\`, which can conflict with S3 Block Public Access and disabled ACLs. For modern private buckets, explicitly set \`"bucket-default"\` to omit the generated ACL header, and do not supply ACL/grant headers in \`headers\`. \`"private"\` still sends an ACL.
95
99
  `),
96
100
  check_integrity: z
97
101
  .boolean()
@@ -139,7 +143,7 @@ This parameter provides signed URLs in the result JSON (in the \`signed_url\` an
139
143
  .string()
140
144
  .optional()
141
145
  .describe(`
142
- The session token to use for the S3 store. This is only used if the credentials are from an IAM user with the \`sts:AssumeRole\` permission.
146
+ The session token belonging to the temporary AWS access key ID and secret access key supplied for this upload. The Robot does not assume a role or refresh these credentials; they must remain valid for the upload.
143
147
  `),
144
148
  })
145
149
  .strict()
@@ -1,3 +1,4 @@
1
+ import type { MODEL_CAPABILITIES } from './_ai-models.ts'
1
2
  import type {
2
3
  RobotDefinition,
3
4
  RobotMetaInput,
@@ -22,6 +23,15 @@ import {
22
23
  /** Markup over the AI provider cost for smart thumbnail selection. */
23
24
  export const smartThumbnailMarkupPercent = 50
24
25
 
26
+ /** Dedicated vision model so /ai/chat default upgrades do not change thumbnail analysis costs. */
27
+ export const smartThumbnailModel = 'openai/gpt-5.4-mini' satisfies keyof typeof MODEL_CAPABILITIES
28
+
29
+ /** Maximum long-side dimension of scoring previews; returned thumbnails keep their output size. */
30
+ export const smartThumbnailAnalysisMaxSize = 512
31
+
32
+ /** Frame ranking needs little reasoning compared with general-purpose chat. */
33
+ export const smartThumbnailReasoningEffort = 'low'
34
+
25
35
  const thumbnailCountSchema = z.number().int().min(1).max(999).default(8)
26
36
  const smartMaximumCandidatesSchema = z.number().int().min(2).max(100).default(20)
27
37
  const defaultThumbnailCount = thumbnailCountSchema.parse(undefined)
@@ -58,13 +68,15 @@ export const robotVideoThumbsInstructionsSchema = robotBase
58
68
  .merge(robotFFmpeg)
59
69
  .extend({
60
70
  robot: z.literal('/video/thumbs').describe(`
61
- Set \`smart: true\` to select strong preview images with AI instead of taking frames only at regular intervals. The Robot scores candidate frames for clarity, brightness, composition, faces, expressions, action, and visual interest, then returns the best \`count\` frames in chronological order. Smart results include \`file.meta.smart_score\` and \`file.meta.smart_reasons\`. If AI scoring is unavailable, the Assembly continues with the candidate frames in fallback order. No AI credentials are required.
71
+ Set \`smart: true\` to select strong preview images with AI instead of taking frames only at regular intervals. The Robot scores candidate frames for clarity, brightness, composition, faces, expressions, action, and visual interest, then returns the best \`count\` frames in chronological order. Smart results include \`file.meta.smart_score\` and \`file.meta.smart_reasons\`. If AI scoring is unavailable, the Assembly continues with the candidate frames in fallback order and includes a warning. No AI credentials are required.
62
72
 
63
73
  ## AI pricing
64
74
 
65
- Regular \`/video/thumbs\` processing charges still apply. AI frame analysis is billed separately at the underlying provider cost plus a ${smartThumbnailMarkupPercent}% Transloadit markup. The exact AI charge varies with the number of candidate frames, the internally selected model and provider pricing, and the image payload size.
75
+ Regular \`/video/thumbs\` processing charges still apply. AI frame analysis is billed separately at the underlying provider cost plus a ${smartThumbnailMarkupPercent}% Transloadit markup. Smart selection uses the dedicated \`${smartThumbnailModel}\` vision model with \`${smartThumbnailReasoningEffort}\` reasoning, independently of the \`/ai/chat\` default. The exact AI charge varies with the number of candidate frames and provider pricing.
66
76
 
67
- \`smart_max_candidates\` is the main cost and latency control. The Robot analyzes up to three candidates per requested thumbnail, capped by \`smart_max_candidates\`, but never fewer than \`count\`. With the defaults of \`count: ${defaultThumbnailCount}\` and \`smart_max_candidates: ${defaultSmartMaximumCandidates}\`, it analyzes ${getSmartThumbnailCandidateCount(defaultThumbnailCount, defaultSmartMaximumCandidates)} frames and returns the best ${defaultThumbnailCount}. Lower the candidate limit to reduce AI cost and latency; raise it to give the AI more frames to choose from.
77
+ The AI scores preview copies capped at ${smartThumbnailAnalysisMaxSize} pixels on the long side, preserving aspect ratio and without enlarging smaller images. Returned thumbnails keep the requested output dimensions and format; larger outputs do not increase the scoring preview beyond this limit.
78
+
79
+ \`smart_max_candidates\` is the main cost and latency control. The Robot analyzes up to three candidates per requested thumbnail, capped by \`smart_max_candidates\`, but never fewer than \`count\`. With the defaults of \`count: ${defaultThumbnailCount}\` and \`smart_max_candidates: ${defaultSmartMaximumCandidates}\`, it analyzes ${getSmartThumbnailCandidateCount(defaultThumbnailCount, defaultSmartMaximumCandidates)} frames and returns the best ${defaultThumbnailCount}. Lower the candidate limit to reduce AI cost and latency. Raising it can enlarge the pool up to three times \`count\`; higher limits have no effect.
68
80
 
69
81
  > [!Note]
70
82
  > Use \`count\` with smart selection. To consistently extract exact timestamps with \`offsets\`, set \`smart: false\`.
@@ -146,17 +158,19 @@ The AI evaluates frames based on:
146
158
  - Action and motion (avoiding transition frames)
147
159
  - Overall visual interest
148
160
 
149
- Regular \`/video/thumbs\` processing charges still apply. AI frame analysis is billed separately at the underlying provider cost plus a ${smartThumbnailMarkupPercent}% Transloadit markup. You do not need to provide AI credentials.
161
+ Regular \`/video/thumbs\` processing charges still apply. AI frame analysis uses a dedicated low-cost vision model with \`${smartThumbnailReasoningEffort}\` reasoning and preview copies capped at ${smartThumbnailAnalysisMaxSize} pixels on the long side. Returned thumbnails retain their requested dimensions and format. Analysis is billed separately at the underlying provider cost plus a ${smartThumbnailMarkupPercent}% Transloadit markup. You do not need to provide AI credentials.
150
162
 
151
163
  Smart mode generates its own regularly spaced candidate timestamps; use \`smart: false\` with \`offsets\` when you need specified timestamps. Selected smart thumbnails are returned in chronological order, not score order. Inspect \`meta.thumb_offset\`, \`meta.smart_score\`, and \`meta.smart_reasons\` when evaluating the selection.
152
164
 
153
- If AI scoring fails, the Robot selects from the extracted candidates in chronological order and records a fallback reason. If no candidates can be extracted, it attempts standard thumbnail extraction. A completed Assembly does not guarantee a representative or publication-safe poster; check that outputs exist and apply your application’s review policy.
165
+ If AI scoring fails, the Robot selects extracted candidates in chronological order and records a fallback reason. With no candidates, it attempts standard extraction. Both fallbacks add an Assembly warning. A completed Assembly does not guarantee a representative or publication-safe poster; check that outputs exist and apply your application’s review policy.
154
166
  `),
155
167
  smart_max_candidates: smartMaximumCandidatesSchema.describe(`
156
168
  The maximum size of the candidate pool when \`smart\` is \`true\`. The Robot analyzes up to three candidates per requested thumbnail, capped by this value, but it will never analyze fewer candidates than the requested \`count\`.
157
169
 
158
170
  A higher number may yield better results but increases processing time and AI cost. With the defaults of \`count: ${defaultThumbnailCount}\` and \`smart_max_candidates: ${defaultSmartMaximumCandidates}\`, the Robot analyzes ${getSmartThumbnailCandidateCount(defaultThumbnailCount, defaultSmartMaximumCandidates)} frames and returns the best ${defaultThumbnailCount} in chronological order.
159
171
 
172
+ Raising this limit above three times \`count\` does not enlarge the pool. For example, \`count: 1\` analyzes at most three candidates.
173
+
160
174
  This parameter is only used when \`smart\` is \`true\`.
161
175
  `),
162
176
  })
@@ -1,4 +1,4 @@
1
- import type { z } from 'zod'
1
+ import type { z } from 'zod/v3'
2
2
 
3
3
  export type ZodIssueWithContext = z.ZodIssue & {
4
4
  parentObj: unknown
package/src/apiTypes.ts CHANGED
@@ -100,6 +100,8 @@ export type ListTemplatesParams = OptionalAuthParams & {
100
100
  todate?: string
101
101
  keywords?: string[]
102
102
  include_builtin?: 'all' | 'latest' | 'exclusively-all' | 'exclusively-latest'
103
+ /** Template columns to return, such as `['id', 'account_id']`; API2's default omits some. */
104
+ fields?: string[]
103
105
  }
104
106
 
105
107
  interface TemplateResponseBase {
package/src/inputFiles.ts CHANGED
@@ -13,6 +13,7 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
13
13
  import { isIP } from 'node:net'
14
14
  import { tmpdir } from 'node:os'
15
15
  import { basename, join, parse } from 'node:path'
16
+ import { Transform } from 'node:stream'
16
17
  import { pipeline } from 'node:stream/promises'
17
18
 
18
19
  import got from 'got'
@@ -53,6 +54,15 @@ export type PrepareInputFilesOptions = {
53
54
  urlStrategy?: UrlStrategy
54
55
  maxBase64Bytes?: number
55
56
  allowPrivateUrls?: boolean
57
+ /** Abort once all URL downloads of this call exceed this many bytes together. */
58
+ maxUrlDownloadBytes?: number
59
+ /** Abort a URL download (DNS checks and redirects included) after this many milliseconds. */
60
+ urlDownloadTimeoutMs?: number
61
+ /**
62
+ * Awaited before each URL input is downloaded locally (not for `/http/import`), so a caller can
63
+ * vouch for the requester first; rejecting aborts preparation.
64
+ */
65
+ beforeUrlDownload?: () => Promise<void>
56
66
  tempDir?: string
57
67
  }
58
68
 
@@ -202,6 +212,16 @@ const isPrivateIp = (address: string): boolean => {
202
212
  return false
203
213
  }
204
214
 
215
+ /**
216
+ * Names a URL in error messages without its query or fragment: input URLs are often presigned
217
+ * (ChatGPT attachments, S3), and these messages reach logs and model-visible tool results.
218
+ */
219
+ const describeUrl = (value: string): string => {
220
+ if (!URL.canParse(value)) return '[unparseable URL]'
221
+ const url = new URL(value)
222
+ return `${url.origin}${url.pathname}`
223
+ }
224
+
205
225
  export const resolvePublicDownloadAddresses = async (
206
226
  value: string,
207
227
  ): Promise<Array<{ address: string; family: 4 | 6 }>> => {
@@ -211,10 +231,10 @@ export const resolvePublicDownloadAddresses = async (
211
231
  ? parsed.hostname.slice(1, -1)
212
232
  : parsed.hostname
213
233
  if (!['http:', 'https:'].includes(parsed.protocol)) {
214
- throw new Error(`URL downloads are limited to http/https: ${value}`)
234
+ throw new Error(`URL downloads are limited to http/https: ${describeUrl(value)}`)
215
235
  }
216
236
  if (isPrivateIp(hostname)) {
217
- throw new Error(`URL downloads are limited to public hosts: ${value}`)
237
+ throw new Error(`URL downloads are limited to public hosts: ${describeUrl(value)}`)
218
238
  }
219
239
 
220
240
  const literalFamily = isIP(hostname)
@@ -226,11 +246,11 @@ export const resolvePublicDownloadAddresses = async (
226
246
  verbatim: true,
227
247
  })
228
248
  if (resolvedAddresses.some((address) => isPrivateIp(address.address))) {
229
- throw new Error(`URL downloads are limited to public hosts: ${value}`)
249
+ throw new Error(`URL downloads are limited to public hosts: ${describeUrl(value)}`)
230
250
  }
231
251
 
232
252
  if (resolvedAddresses.length === 0) {
233
- throw new Error(`Unable to resolve URL hostname: ${value}`)
253
+ throw new Error(`Unable to resolve URL hostname: ${describeUrl(value)}`)
234
254
  }
235
255
 
236
256
  return resolvedAddresses.map((address) => ({
@@ -370,22 +390,58 @@ export function createPinnedDnsLookup(
370
390
  return pinnedDnsLookup as PinnedDnsLookup
371
391
  }
372
392
 
393
+ /** A budget shared by every URL download of one `prepareInputFiles` call. */
394
+ type DownloadBudget = { totalBytes: number; remainingBytes: number }
395
+
396
+ const budgetExceeded = (budget: DownloadBudget, url: string): Error =>
397
+ new Error(`URL downloads exceed ${budget.totalBytes} bytes: ${describeUrl(url)}`)
398
+
399
+ /** Errors once the budget is used up, so temp files stay bounded while they stream in. */
400
+ const limitDownloadBytes = (budget: DownloadBudget, url: string): Transform =>
401
+ new Transform({
402
+ transform(chunk: Buffer, _encoding, callback) {
403
+ budget.remainingBytes -= chunk.length
404
+ if (budget.remainingBytes < 0) {
405
+ callback(budgetExceeded(budget, url))
406
+ return
407
+ }
408
+ callback(null, chunk)
409
+ },
410
+ })
411
+
373
412
  const downloadUrlToFile = async ({
374
413
  allowPrivateUrls,
375
414
  filePath,
376
415
  url,
416
+ budget,
417
+ timeoutMs,
377
418
  }: {
378
419
  allowPrivateUrls: boolean
379
420
  filePath: string
380
421
  url: string
422
+ budget?: DownloadBudget
423
+ timeoutMs?: number
381
424
  }): Promise<void> => {
382
425
  let currentUrl = url
426
+ // One deadline for the whole download, so DNS checks and redirects cannot each restart it.
427
+ const deadline = timeoutMs === undefined ? undefined : Date.now() + timeoutMs
428
+ const remainingMs = (): number | undefined => {
429
+ if (deadline === undefined) return undefined
430
+ const remaining = deadline - Date.now()
431
+ if (remaining <= 0) {
432
+ throw new Error(`URL download timed out after ${timeoutMs} ms: ${describeUrl(url)}`)
433
+ }
434
+ return remaining
435
+ }
383
436
 
384
437
  for (let redirectCount = 0; redirectCount <= MAX_URL_REDIRECTS; redirectCount += 1) {
385
438
  let validatedAddresses: Array<{ address: string; family: 4 | 6 }> | null = null
386
439
  if (!allowPrivateUrls) {
440
+ // Not raced against the deadline: the system resolver bounds each lookup with its own
441
+ // short timeout and no bytes are transferred, so checking the clock right after suffices.
387
442
  validatedAddresses = await resolvePublicDownloadAddresses(currentUrl)
388
443
  }
444
+ const requestTimeoutMs = remainingMs()
389
445
 
390
446
  const dnsLookup: LookupFunction | undefined =
391
447
  validatedAddresses == null ? undefined : createPinnedDnsLookup(validatedAddresses)
@@ -395,6 +451,7 @@ const downloadUrlToFile = async ({
395
451
  followRedirect: false,
396
452
  retry: { limit: 0 },
397
453
  throwHttpErrors: false,
454
+ ...(requestTimeoutMs === undefined ? {} : { timeout: { request: requestTimeoutMs } }),
398
455
  })
399
456
 
400
457
  const response = await new Promise<
@@ -416,7 +473,7 @@ const downloadUrlToFile = async ({
416
473
  responseStream.destroy()
417
474
  const location = response.headers.location
418
475
  if (location == null) {
419
- throw new Error(`Redirect response missing Location header: ${currentUrl}`)
476
+ throw new Error(`Redirect response missing Location header: ${describeUrl(currentUrl)}`)
420
477
  }
421
478
  currentUrl = new URL(location, currentUrl).toString()
422
479
  continue
@@ -424,14 +481,22 @@ const downloadUrlToFile = async ({
424
481
 
425
482
  if (statusCode >= 400) {
426
483
  responseStream.destroy()
427
- throw new Error(`Failed to download URL: ${currentUrl} (${statusCode})`)
484
+ throw new Error(`Failed to download URL: ${describeUrl(currentUrl)} (${statusCode})`)
428
485
  }
429
486
 
430
- await pipeline(responseStream, createWriteStream(filePath))
487
+ if (budget === undefined) {
488
+ await pipeline(responseStream, createWriteStream(filePath))
489
+ return
490
+ }
491
+ if (Number(response.headers['content-length']) > budget.remainingBytes) {
492
+ responseStream.destroy()
493
+ throw budgetExceeded(budget, url)
494
+ }
495
+ await pipeline(responseStream, limitDownloadBytes(budget, url), createWriteStream(filePath))
431
496
  return
432
497
  }
433
498
 
434
- throw new Error(`Too many redirects while downloading URL input: ${url}`)
499
+ throw new Error(`Too many redirects while downloading URL input: ${describeUrl(url)}`)
435
500
  }
436
501
 
437
502
  export const prepareInputFiles = async (
@@ -445,6 +510,9 @@ export const prepareInputFiles = async (
445
510
  urlStrategy = 'import',
446
511
  maxBase64Bytes,
447
512
  allowPrivateUrls = true,
513
+ maxUrlDownloadBytes,
514
+ urlDownloadTimeoutMs,
515
+ beforeUrlDownload,
448
516
  tempDir,
449
517
  } = options
450
518
 
@@ -452,6 +520,10 @@ export const prepareInputFiles = async (
452
520
  const files: Record<string, string> = {}
453
521
  const uploads: Record<string, UploadInput> = {}
454
522
  const cleanup: Array<() => Promise<void>> = []
523
+ const downloadBudget: DownloadBudget | undefined =
524
+ maxUrlDownloadBytes === undefined
525
+ ? undefined
526
+ : { totalBytes: maxUrlDownloadBytes, remainingBytes: maxUrlDownloadBytes }
455
527
 
456
528
  if (fields && Object.keys(fields).length > 0) {
457
529
  nextParams = {
@@ -530,10 +602,13 @@ export const prepareInputFiles = async (
530
602
  getFilenameFromUrl(file.url) ??
531
603
  `${file.field}.bin`
532
604
  const filePath = await ensureUniqueTempFilePath(root, filename, usedTempPaths)
605
+ await beforeUrlDownload?.()
533
606
  await downloadUrlToFile({
534
607
  allowPrivateUrls,
535
608
  filePath,
536
609
  url: file.url,
610
+ budget: downloadBudget,
611
+ timeoutMs: urlDownloadTimeoutMs,
537
612
  })
538
613
  files[file.field] = filePath
539
614
  }