@mitralab.io/sdk-core 0.3.9 → 0.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -22,6 +22,7 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  API_KEY_EXCHANGE_PATH: () => API_KEY_EXCHANGE_PATH,
24
24
  AgentTaskTurnError: () => AgentTaskTurnError,
25
+ FileTransferError: () => FileTransferError,
25
26
  SdkCoreConfigurationError: () => SdkCoreConfigurationError,
26
27
  SdkCoreResponseError: () => SdkCoreResponseError,
27
28
  appAccessTokenPath: () => appAccessTokenPath,
@@ -37,6 +38,7 @@ __export(index_exports, {
37
38
  createCustomQueriesModule: () => createCustomQueriesModule,
38
39
  createDataSourcesModule: () => createDataSourcesModule,
39
40
  createEntitiesModule: () => createEntitiesModule,
41
+ createFilesModule: () => createFilesModule,
40
42
  createFunctionsAdminModule: () => createFunctionsAdminModule,
41
43
  createFunctionsModule: () => createFunctionsModule,
42
44
  createImportsModule: () => createImportsModule,
@@ -746,6 +748,55 @@ function expectImportExecution(value, context, errors = defaultSdkCoreErrorFacto
746
748
  if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
747
749
  return execution;
748
750
  }
751
+ function expectFileMetadata(value, context, errors = defaultSdkCoreErrorFactory) {
752
+ const file = expectObject(value, context, errors);
753
+ for (const field of ["id", "name", "contentType", "createdAt"]) {
754
+ if (typeof file[field] !== "string") invalidField(context, field, errors);
755
+ }
756
+ if (!isInteger(file.sizeBytes)) invalidField(context, "sizeBytes", errors);
757
+ if (!isOneOf(file.kind, ["TEMPORARY", "PERMANENT"])) {
758
+ invalidField(context, "kind", errors);
759
+ }
760
+ if (!isOneOf(file.visibility, ["PRIVATE", "RESTRICTED", "APP"])) {
761
+ invalidField(context, "visibility", errors);
762
+ }
763
+ if (!isOneOf(file.status, ["PENDING", "READY", "DELETED"])) {
764
+ invalidField(context, "status", errors);
765
+ }
766
+ if (!isOneOf(file.createdBy, ["USER", "FUNCTION"])) {
767
+ invalidField(context, "createdBy", errors);
768
+ }
769
+ for (const field of ["ownerUserId", "confirmedAt", "expiresAt"]) {
770
+ if (!isNullableString(file[field])) invalidField(context, field, errors);
771
+ }
772
+ return file;
773
+ }
774
+ function expectFileUpload(value, context, errors = defaultSdkCoreErrorFactory) {
775
+ const upload = expectObject(value, context, errors);
776
+ for (const field of ["fileId", "uploadUrl", "uploadMethod", "expiresAt"]) {
777
+ if (typeof upload[field] !== "string" || !upload[field]) invalidField(context, field, errors);
778
+ }
779
+ if (!isStringRecord(upload.uploadHeaders)) invalidField(context, "uploadHeaders", errors);
780
+ return upload;
781
+ }
782
+ function expectFileReadUrl(value, context, errors = defaultSdkCoreErrorFactory) {
783
+ const read = expectObject(value, context, errors);
784
+ if (typeof read.url !== "string" || !read.url) invalidField(context, "url", errors);
785
+ if (typeof read.expiresAt !== "string") invalidField(context, "expiresAt", errors);
786
+ return read;
787
+ }
788
+ function expectFileReadUrls(value, context, errors = defaultSdkCoreErrorFactory) {
789
+ const response = expectObject(value, context, errors);
790
+ expectObjectArray(response.results, `${context} results`, errors).forEach(
791
+ (item, position) => {
792
+ const itemContext = `${context} result ${position}`;
793
+ if (typeof item.fileId !== "string") invalidField(itemContext, "fileId", errors);
794
+ if (typeof item.errorCode === "string") return;
795
+ expectFileReadUrl(item, itemContext, errors);
796
+ }
797
+ );
798
+ return response;
799
+ }
749
800
  function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFactory) {
750
801
  const response = expectObject(value, context, errors);
751
802
  if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
@@ -2371,6 +2422,248 @@ function createEntitiesModule(transport, errors = defaultSdkCoreErrorFactory) {
2371
2422
  });
2372
2423
  }
2373
2424
 
2425
+ // src/fileTransferError.ts
2426
+ var FileTransferError = class extends Error {
2427
+ fileId;
2428
+ step;
2429
+ /**
2430
+ * HTTP status storage answered in `send` and `download`; null when storage gave no status or the
2431
+ * content failed to arrive, and always in `confirm`.
2432
+ */
2433
+ status;
2434
+ /**
2435
+ * True when the `PENDING` file a failed `send` left behind was deleted. False when that delete
2436
+ * failed too, and always in `confirm` and `download`, where nothing is deleted.
2437
+ */
2438
+ cleanedUp;
2439
+ constructor(message, details) {
2440
+ super(message, details.cause === void 0 ? void 0 : { cause: details.cause });
2441
+ this.name = "FileTransferError";
2442
+ this.fileId = details.fileId;
2443
+ this.step = details.step;
2444
+ this.status = details.status ?? null;
2445
+ this.cleanedUp = details.cleanedUp ?? false;
2446
+ }
2447
+ };
2448
+
2449
+ // src/modules/files.ts
2450
+ var MAX_READ_URLS = 100;
2451
+ var UNTYPED_CONTENT = "application/octet-stream";
2452
+ var REDACTED = "<redacted>";
2453
+ var MAX_CAUSE_DEPTH = 5;
2454
+ var MIN_SECRET_LENGTH = 16;
2455
+ var UNREADABLE_STORAGE_ERROR = "storage failed with an error the Core cannot show";
2456
+ function createFilesModule(transport, options = {}, errors = defaultSdkCoreErrorFactory) {
2457
+ const path = (fileId) => `/api/v1/files/${encodePathSegment(fileId, "file id", errors)}`;
2458
+ const storageFetch = () => {
2459
+ if (options.fetch) return options.fetch;
2460
+ const global = globalThis.fetch;
2461
+ if (typeof global !== "function") {
2462
+ configurationError("fetch is not available: pass files.fetch to the Core", errors);
2463
+ }
2464
+ return global;
2465
+ };
2466
+ const requestUpload = async (input) => expectFileUpload(
2467
+ await transport.request("/api/v1/files", { method: "POST", body: input }),
2468
+ "File upload response",
2469
+ errors
2470
+ );
2471
+ const confirmUpload = async (fileId) => expectFileMetadata(
2472
+ await transport.request(`${path(fileId)}/confirm`, { method: "POST" }),
2473
+ "Confirm file upload response",
2474
+ errors
2475
+ );
2476
+ const getUrl = async (fileId, { expiresInSeconds } = {}) => expectFileReadUrl(
2477
+ await transport.request(`${path(fileId)}/read-url`, {
2478
+ method: "POST",
2479
+ ...expiresInSeconds === void 0 ? {} : { body: { expiresInSeconds } }
2480
+ }),
2481
+ "File read URL response",
2482
+ errors
2483
+ );
2484
+ const deleteFile = async (fileId) => {
2485
+ expectEmpty(
2486
+ await transport.request(path(fileId), { method: "DELETE" }),
2487
+ "Delete file response",
2488
+ errors
2489
+ );
2490
+ };
2491
+ const sendContent = async (fetch, upload, content, signal) => {
2492
+ const failure = await putContent(fetch, upload, content, signal);
2493
+ if (failure === null) return;
2494
+ const cleanedUp = await deleteFile(upload.fileId).then(
2495
+ () => true,
2496
+ () => false
2497
+ );
2498
+ if (failure.aborted && signal !== void 0) throw abortReason(signal);
2499
+ throw new FileTransferError(`File ${upload.fileId} was not sent: ${failure.reason}`, {
2500
+ fileId: upload.fileId,
2501
+ step: "send",
2502
+ status: failure.status,
2503
+ cause: "error" in failure ? storageCause(failure.error, upload.uploadUrl) : void 0,
2504
+ cleanedUp
2505
+ });
2506
+ };
2507
+ const confirmSent = async (fileId) => {
2508
+ try {
2509
+ return await confirmUpload(fileId);
2510
+ } catch (error) {
2511
+ throw new FileTransferError(
2512
+ `File ${fileId} was sent but not confirmed: ${messageOf(error)}`,
2513
+ {
2514
+ fileId,
2515
+ step: "confirm",
2516
+ cause: error
2517
+ }
2518
+ );
2519
+ }
2520
+ };
2521
+ return {
2522
+ requestUpload,
2523
+ confirmUpload,
2524
+ async upload(content, uploadOptions) {
2525
+ const fetch = storageFetch();
2526
+ const input = uploadInput(content, uploadOptions, errors);
2527
+ const { signal } = uploadOptions;
2528
+ if (signal?.aborted) throw abortReason(signal);
2529
+ const upload = await requestUpload(input);
2530
+ await sendContent(fetch, upload, content, signal);
2531
+ return confirmSent(upload.fileId);
2532
+ },
2533
+ getUrl,
2534
+ async getUrls(fileIds, { expiresInSeconds } = {}) {
2535
+ requireBatchSize(fileIds, "fileIds", MAX_READ_URLS, errors);
2536
+ return expectFileReadUrls(
2537
+ await transport.request("/api/v1/files/read-urls", {
2538
+ method: "POST",
2539
+ body: { fileIds, ...expiresInSeconds === void 0 ? {} : { expiresInSeconds } }
2540
+ }),
2541
+ "File read URLs response",
2542
+ errors
2543
+ );
2544
+ },
2545
+ async download(fileId, { signal } = {}) {
2546
+ const fetch = storageFetch();
2547
+ if (signal?.aborted) throw abortReason(signal);
2548
+ const { url } = await getUrl(fileId);
2549
+ return fetchContent(fetch, fileId, url, signal);
2550
+ },
2551
+ async get(fileId) {
2552
+ return expectFileMetadata(
2553
+ await transport.request(path(fileId), { method: "GET" }),
2554
+ "File response",
2555
+ errors
2556
+ );
2557
+ },
2558
+ delete: deleteFile
2559
+ };
2560
+ }
2561
+ function uploadInput(content, options, errors) {
2562
+ const name = options.name ?? fileNameOf(content);
2563
+ if (!name) configurationError("name is required when the content is not a named File", errors);
2564
+ const contentType = options.contentType || content.type || UNTYPED_CONTENT;
2565
+ return {
2566
+ name,
2567
+ contentType,
2568
+ sizeBytes: content.size,
2569
+ kind: options.kind,
2570
+ visibility: options.visibility,
2571
+ ...options.appOwned === void 0 ? {} : { appOwned: options.appOwned }
2572
+ };
2573
+ }
2574
+ function fileNameOf(content) {
2575
+ const name = content.name;
2576
+ return typeof name === "string" ? name : void 0;
2577
+ }
2578
+ async function putContent(fetch, upload, content, signal) {
2579
+ try {
2580
+ const response = await fetch(upload.uploadUrl, {
2581
+ method: upload.uploadMethod,
2582
+ headers: upload.uploadHeaders,
2583
+ body: content,
2584
+ redirect: "error",
2585
+ ...signal === void 0 ? {} : { signal }
2586
+ });
2587
+ discardBody(response);
2588
+ if (response.ok) return null;
2589
+ return {
2590
+ reason: `storage answered ${response.status}`,
2591
+ status: response.status,
2592
+ aborted: false
2593
+ };
2594
+ } catch (error) {
2595
+ return {
2596
+ reason: "the transfer to storage failed",
2597
+ status: null,
2598
+ aborted: signal?.aborted === true,
2599
+ error
2600
+ };
2601
+ }
2602
+ }
2603
+ async function fetchContent(fetch, fileId, url, signal) {
2604
+ let response;
2605
+ try {
2606
+ response = await fetch(url, {
2607
+ method: "GET",
2608
+ redirect: "error",
2609
+ ...signal === void 0 ? {} : { signal }
2610
+ });
2611
+ if (response.ok) return await response.blob();
2612
+ } catch (error) {
2613
+ if (signal?.aborted) throw abortReason(signal);
2614
+ throw new FileTransferError(
2615
+ `File ${fileId} was not downloaded: the transfer from storage failed`,
2616
+ { fileId, step: "download", cause: storageCause(error, url) }
2617
+ );
2618
+ }
2619
+ discardBody(response);
2620
+ throw new FileTransferError(
2621
+ `File ${fileId} was not downloaded: storage answered ${response.status}`,
2622
+ { fileId, step: "download", status: response.status }
2623
+ );
2624
+ }
2625
+ function storageCause(thrown, link) {
2626
+ const secrets = linkSecrets(link);
2627
+ const redact = (text) => secrets.reduce((result, secret) => result.replaceAll(secret, REDACTED), text);
2628
+ const rebuild = (value, depth) => {
2629
+ if (!(value instanceof Error)) {
2630
+ const opaque = typeof value === "function" || typeof value === "object" && value !== null;
2631
+ return new Error(opaque ? UNREADABLE_STORAGE_ERROR : redact(String(value)));
2632
+ }
2633
+ const below = depth < MAX_CAUSE_DEPTH && value.cause != null ? rebuild(value.cause, depth + 1) : void 0;
2634
+ const error = new Error(
2635
+ redact(String(value.message)),
2636
+ below === void 0 ? void 0 : { cause: below }
2637
+ );
2638
+ error.name = redact(String(value.name));
2639
+ if (typeof value.stack === "string") error.stack = redact(value.stack);
2640
+ const { code } = value;
2641
+ return typeof code === "string" ? Object.assign(error, { code: redact(code) }) : error;
2642
+ };
2643
+ try {
2644
+ return rebuild(thrown, 1);
2645
+ } catch {
2646
+ return new Error(UNREADABLE_STORAGE_ERROR);
2647
+ }
2648
+ }
2649
+ function linkSecrets(link) {
2650
+ const start = link.indexOf("?");
2651
+ const query = start < 0 ? "" : link.slice(start + 1);
2652
+ const raw = query.split("&").map((pair) => pair.slice(pair.indexOf("=") + 1));
2653
+ const decoded = [...new URLSearchParams(query).values()];
2654
+ const values = [...raw, ...decoded].filter((value) => value.length >= MIN_SECRET_LENGTH);
2655
+ return [link, query, ...values].filter((secret) => secret.length > 0);
2656
+ }
2657
+ function discardBody(response) {
2658
+ void Promise.resolve().then(() => response.body?.cancel()).catch(() => void 0);
2659
+ }
2660
+ function abortReason(signal) {
2661
+ return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
2662
+ }
2663
+ function messageOf(error) {
2664
+ return error instanceof Error ? error.message : String(error);
2665
+ }
2666
+
2374
2667
  // src/modules/functions.ts
2375
2668
  var DefaultFunctionsModule = class {
2376
2669
  constructor(transport, errors, options) {
@@ -3380,6 +3673,7 @@ function createSdkCore(options) {
3380
3673
  customQueries: createCustomQueriesModule(options.transports.dataManager, errors),
3381
3674
  dataSources: createDataSourcesModule(options.transports.dataManager, errors),
3382
3675
  entities: createEntitiesModule(options.transports.dataManager, errors),
3676
+ files: createFilesModule(options.transports.dataManager, options.files, errors),
3383
3677
  functions: createFunctionsModule(options.transports.functions, options.functions, errors),
3384
3678
  functionsAdmin,
3385
3679
  imports: createImportsModule(options.transports.dataManager, errors),
@@ -6143,6 +6437,7 @@ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreEr
6143
6437
  0 && (module.exports = {
6144
6438
  API_KEY_EXCHANGE_PATH,
6145
6439
  AgentTaskTurnError,
6440
+ FileTransferError,
6146
6441
  SdkCoreConfigurationError,
6147
6442
  SdkCoreResponseError,
6148
6443
  appAccessTokenPath,
@@ -6158,6 +6453,7 @@ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreEr
6158
6453
  createCustomQueriesModule,
6159
6454
  createDataSourcesModule,
6160
6455
  createEntitiesModule,
6456
+ createFilesModule,
6161
6457
  createFunctionsAdminModule,
6162
6458
  createFunctionsModule,
6163
6459
  createImportsModule,
package/dist/index.d.cts CHANGED
@@ -858,6 +858,98 @@ interface ImportExecution {
858
858
  durationSeconds: number | null;
859
859
  errorMessage: string | null;
860
860
  }
861
+ /**
862
+ * Once confirmed, `TEMPORARY` expires seven days after the upload request and `PERMANENT` never
863
+ * does. Each kind has its own quota in the app and its own quota per owner; a file without an
864
+ * owner counts only toward the app's.
865
+ */
866
+ type FileKind = "TEMPORARY" | "PERMANENT";
867
+ /**
868
+ * Who gets a read link: `PRIVATE` the owner only, `RESTRICTED` the owner or a Server Function of
869
+ * the app running for a user (a public execution does not), `APP` anyone with `FILE_READ` on the
870
+ * app. A file without an owner is always `APP`.
871
+ */
872
+ type FileVisibility = "PRIVATE" | "RESTRICTED" | "APP";
873
+ /** `PENDING` until the upload is confirmed; only `READY` files can be read. */
874
+ type FileStatus = "PENDING" | "READY" | "DELETED";
875
+ type FileCreator = "USER" | "FUNCTION";
876
+ interface FileUploadInput {
877
+ /** Original file name, at most 255 characters and without control characters. */
878
+ name: string;
879
+ /** Media type such as `image/png`; storage serves the file back with it. */
880
+ contentType: string;
881
+ /** Exact size in bytes. The upload link is signed with it, so storage refuses any other size. */
882
+ sizeBytes: number;
883
+ kind: FileKind;
884
+ visibility: FileVisibility;
885
+ /**
886
+ * Server Functions only: the file belongs to the app instead of the token's user, and must be
887
+ * `APP`. Any other caller gets `400 INVALID_FILE_REQUEST`.
888
+ */
889
+ appOwned?: boolean;
890
+ }
891
+ /** A `PENDING` file and the signed link that takes its bytes. */
892
+ interface FileUpload {
893
+ fileId: string;
894
+ /** Signed storage URL. It authorizes the upload by itself, so it is never logged. */
895
+ uploadUrl: string;
896
+ /** HTTP method the upload must use. */
897
+ uploadMethod: string;
898
+ /** Headers the upload must repeat exactly, because the link is signed with them. */
899
+ uploadHeaders: Record<string, string>;
900
+ /** When the link stops accepting the upload. */
901
+ expiresAt: string;
902
+ }
903
+ interface FileMetadata {
904
+ id: string;
905
+ name: string;
906
+ contentType: string;
907
+ sizeBytes: number;
908
+ kind: FileKind;
909
+ visibility: FileVisibility;
910
+ status: FileStatus;
911
+ /**
912
+ * Null for a file of the app: one a Server Function uploaded with `appOwned`, or uploaded by a
913
+ * Server Function running without a user, such as a public execution.
914
+ */
915
+ ownerUserId: string | null;
916
+ createdBy: FileCreator;
917
+ createdAt: string;
918
+ /** Null while the file is `PENDING`. */
919
+ confirmedAt: string | null;
920
+ /**
921
+ * When the file stops answering: 24 hours after the request while `PENDING`, of either kind.
922
+ * Null only for a confirmed `PERMANENT` file.
923
+ */
924
+ expiresAt: string | null;
925
+ }
926
+ interface FileReadUrlOptions {
927
+ /**
928
+ * Requested link validity. Only `APP` files get more than the service default, up to its
929
+ * ceiling; `expiresAt` in the response carries the validity actually granted.
930
+ */
931
+ expiresInSeconds?: number;
932
+ }
933
+ interface FileReadUrl {
934
+ /** Signed storage URL that opens the file by itself, so it is never logged. */
935
+ url: string;
936
+ expiresAt: string;
937
+ }
938
+ /**
939
+ * One item per distinct `fileId`, in the order asked. A file the caller cannot read, for any
940
+ * reason, comes with `errorCode` (`NOT_FOUND`) instead of a link, without failing the others.
941
+ */
942
+ type FileReadUrlItem = {
943
+ fileId: string;
944
+ url: string;
945
+ expiresAt: string;
946
+ } | {
947
+ fileId: string;
948
+ errorCode: string;
949
+ };
950
+ interface FileReadUrls {
951
+ results: FileReadUrlItem[];
952
+ }
861
953
  interface AgentInput {
862
954
  /** Agent name, 3 to 255 characters. */
863
955
  name: string;
@@ -1867,6 +1959,95 @@ type EntitiesProxy = EntitiesModule & {
1867
1959
  };
1868
1960
  declare function createEntitiesModule(transport: Transport, errors?: SdkCoreErrorFactory): EntitiesProxy;
1869
1961
 
1962
+ /** The part of a fetch response the signed storage links need. */
1963
+ interface FilesFetchResponse {
1964
+ readonly ok: boolean;
1965
+ readonly status: number;
1966
+ /** Cancelled when the content is not read. */
1967
+ readonly body?: {
1968
+ cancel(): Promise<void>;
1969
+ } | null;
1970
+ blob(): Promise<Blob>;
1971
+ }
1972
+ type FilesFetch = (url: string, init: {
1973
+ method: string;
1974
+ headers?: Record<string, string>;
1975
+ body?: Blob;
1976
+ redirect: "error";
1977
+ signal?: AbortSignal;
1978
+ }) => Promise<FilesFetchResponse>;
1979
+ interface FilesModuleOptions {
1980
+ /**
1981
+ * fetch for the signed storage links. Defaults to `globalThis.fetch`. It must send the request
1982
+ * as given, without adding `Authorization` or any other header: the link is already the
1983
+ * credential, so a fetch that adds the app token leaks it to storage, which refuses a request
1984
+ * with a second credential, and one that sets headers can replace the ones the link was signed
1985
+ * with, such as `content-type`.
1986
+ */
1987
+ fetch?: FilesFetch;
1988
+ }
1989
+ interface FileUploadOptions {
1990
+ kind: FileKind;
1991
+ visibility: FileVisibility;
1992
+ /** Defaults to the name of a `File`; required for any other `Blob`. */
1993
+ name?: string;
1994
+ /** Defaults to the type of the `Blob`, and to `application/octet-stream` when it has none. */
1995
+ contentType?: string;
1996
+ /** Server Functions only, as in `FileUploadInput`. */
1997
+ appOwned?: boolean;
1998
+ /**
1999
+ * Aborts the upload until the bytes reach storage, and the upload then rejects with
2000
+ * `signal.reason`: before any request when it is already aborted, after deleting the `PENDING`
2001
+ * file otherwise. The API calls do not take it, so the confirmation runs to the end.
2002
+ */
2003
+ signal?: AbortSignal;
2004
+ }
2005
+ interface FileDownloadOptions {
2006
+ /**
2007
+ * Aborts the transfer of the content from storage, and the download then rejects with
2008
+ * `signal.reason`. Already aborted, it rejects before asking for the read link, which does not
2009
+ * take it.
2010
+ */
2011
+ signal?: AbortSignal;
2012
+ }
2013
+ interface FilesModule {
2014
+ /** Records a `PENDING` file and returns the signed link that takes its bytes. */
2015
+ requestUpload(input: FileUploadInput): Promise<FileUpload>;
2016
+ /**
2017
+ * Marks the file `READY` once storage holds bytes of the declared size. Only the uploader
2018
+ * confirms, and repeating it returns the same file.
2019
+ */
2020
+ confirmUpload(fileId: string): Promise<FileMetadata>;
2021
+ /**
2022
+ * Requests the upload, sends the bytes straight to storage with the method and headers the API
2023
+ * returned, and confirms. Resolves only once the file is `READY`. A failure of the request
2024
+ * propagates unchanged. When the send fails, the `PENDING` file is deleted, even if the bytes
2025
+ * may already be in storage, and an abort then rejects with `signal.reason`. Any other failure
2026
+ * after the request is a `FileTransferError` with the step and the `fileId`: a failed `send`
2027
+ * says in `cleanedUp` whether the delete worked, and a failed `confirm` keeps the file, so the
2028
+ * caller can confirm again or delete it.
2029
+ */
2030
+ upload(content: Blob, options: FileUploadOptions): Promise<FileMetadata>;
2031
+ /** Signed read link of one `READY` file the caller may read; any other file answers 404. */
2032
+ getUrl(fileId: string, options?: FileReadUrlOptions): Promise<FileReadUrl>;
2033
+ /** Signed read links of 1 to 100 files in one call, one item per distinct id. */
2034
+ getUrls(fileIds: string[], options?: FileReadUrlOptions): Promise<FileReadUrls>;
2035
+ /**
2036
+ * Asks for a read link and downloads the content from storage. A failure of the link request
2037
+ * propagates unchanged, an abort rejects with `signal.reason`, and a failed transfer is a
2038
+ * `FileTransferError` with the `download` step.
2039
+ */
2040
+ download(fileId: string, options?: FileDownloadOptions): Promise<Blob>;
2041
+ /** Metadata only, without a link. */
2042
+ get(fileId: string): Promise<FileMetadata>;
2043
+ /**
2044
+ * Deletes the file. The uploader deletes their own, `PENDING` included; a file of someone else
2045
+ * or of the app needs `FILE_DELETE`.
2046
+ */
2047
+ delete(fileId: string): Promise<void>;
2048
+ }
2049
+ declare function createFilesModule(transport: Transport, options?: FilesModuleOptions, errors?: SdkCoreErrorFactory): FilesModule;
2050
+
1870
2051
  type InvocationType = "sync" | "async";
1871
2052
  type EmptyFunctionInput = "empty-object" | "omit-body";
1872
2053
  interface FunctionsModuleOptions {
@@ -2044,6 +2225,7 @@ interface SdkCoreOptions {
2044
2225
  /** Resolves the app fixed by the concrete client without inspecting tokens in core. */
2045
2226
  getAppId?: () => string | undefined;
2046
2227
  functions?: FunctionsModuleOptions;
2228
+ files?: FilesModuleOptions;
2047
2229
  errors?: SdkCoreErrorFactory;
2048
2230
  }
2049
2231
  interface SdkCore {
@@ -2058,6 +2240,7 @@ interface SdkCore {
2058
2240
  readonly customQueries: CustomQueriesModule;
2059
2241
  readonly dataSources: DataSourcesModule;
2060
2242
  readonly entities: EntitiesProxy;
2243
+ readonly files: FilesModule;
2061
2244
  readonly functions: FunctionsModule;
2062
2245
  readonly functionsAdmin: FunctionsAdminModule;
2063
2246
  readonly imports: ImportsModule;
@@ -2591,6 +2774,38 @@ declare function toAgentTimelineItem(message: AgentMessage): AgentTimelineItem;
2591
2774
  declare function createAgentTaskSessionManager(options: AgentTaskSessionManagerOptions): AgentTaskSessionManager;
2592
2775
  declare function withAgentTaskSessions(tasks: AgentTasksModule, manager: AgentTaskSessionManager): AgentTasksWithSessions;
2593
2776
 
2777
+ type FileTransferStep = "send" | "confirm" | "download";
2778
+ interface FileTransferErrorDetails {
2779
+ fileId: string;
2780
+ step: FileTransferStep;
2781
+ status?: number | null;
2782
+ cause?: unknown;
2783
+ cleanedUp?: boolean;
2784
+ }
2785
+ /**
2786
+ * A file upload or download that failed after the file already existed: the bytes did not reach
2787
+ * storage (`send`), the upload was not confirmed (`confirm`) or the content did not come back
2788
+ * (`download`). In `send` and `download`, `cause` is never the error of the fetch: it is a new
2789
+ * `Error` with its name, message, stack and text `code`, with the signed link, its query and each
2790
+ * long query value, raw or decoded, cut out, and its causes rebuilt the same way up to five
2791
+ * levels. In `confirm` it is the `Transport` error as it came.
2792
+ */
2793
+ declare class FileTransferError extends Error {
2794
+ readonly fileId: string;
2795
+ readonly step: FileTransferStep;
2796
+ /**
2797
+ * HTTP status storage answered in `send` and `download`; null when storage gave no status or the
2798
+ * content failed to arrive, and always in `confirm`.
2799
+ */
2800
+ readonly status: number | null;
2801
+ /**
2802
+ * True when the `PENDING` file a failed `send` left behind was deleted. False when that delete
2803
+ * failed too, and always in `confirm` and `download`, where nothing is deleted.
2804
+ */
2805
+ readonly cleanedUp: boolean;
2806
+ constructor(message: string, details: FileTransferErrorDetails);
2807
+ }
2808
+
2594
2809
  /**
2595
2810
  * What the SDKs have to know about trading an api key for a token.
2596
2811
  *
@@ -2645,4 +2860,4 @@ declare function expectPage<T extends object>(value: unknown, context: string, e
2645
2860
  declare function expectLegacyPage<T extends object>(value: unknown, context: string, errors?: SdkCoreErrorFactory, validateItem?: (value: unknown, context: string, errors: SdkCoreErrorFactory) => T): LegacyPage<T>;
2646
2861
  declare function expectEmpty(value: unknown, context: string, errors?: SdkCoreErrorFactory): void;
2647
2862
 
2648
- export { API_KEY_EXCHANGE_PATH, type AgentBackgroundTask, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionCustomProvider, type AgentConnectionCustomProviderInput, type AgentConnectionsModule, type AgentCredentialOptions, type AgentCredentialScope, type AgentCredentialsModule, type AgentDefinition, type AgentDirectChannelOptions, type AgentFetch, type AgentFetchResponse, type AgentHistoryCursor, type AgentInput, type AgentMessage, type AgentMessageListOptions, type AgentModel, type AgentNotification, type AgentPieceIdentity, type AgentPlan, type AgentPlanStep, type AgentProviderUsage, type AgentQueueItem, type AgentReadyProvider, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentSubagent, type AgentSubagentFrame, type AgentSubagentStatus, type AgentTask, type AgentTaskChannel, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskRuntime, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentTimelineItemIdentity, type AgentToolEvent, type AgentTurnResult, type AgentTurnUsage, type AgentTurnUsageRequest, type AgentUpdateItem, type AgentWebSocket, type AgentWebSocketConstructor, type AgentsModule, type AiProviders, type AiProvidersModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CredentialUsage, type CredentialUsageWindow, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IncludedAiQuota, type IncludedAiQuotaWindow, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type ManagedAiProfile, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type OpencodeAiProvider, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SendEmailInput, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAiProvidersModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
2863
+ export { API_KEY_EXCHANGE_PATH, type AgentBackgroundTask, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionCustomProvider, type AgentConnectionCustomProviderInput, type AgentConnectionsModule, type AgentCredentialOptions, type AgentCredentialScope, type AgentCredentialsModule, type AgentDefinition, type AgentDirectChannelOptions, type AgentFetch, type AgentFetchResponse, type AgentHistoryCursor, type AgentInput, type AgentMessage, type AgentMessageListOptions, type AgentModel, type AgentNotification, type AgentPieceIdentity, type AgentPlan, type AgentPlanStep, type AgentProviderUsage, type AgentQueueItem, type AgentReadyProvider, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentSubagent, type AgentSubagentFrame, type AgentSubagentStatus, type AgentTask, type AgentTaskChannel, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskListOptions, type AgentTaskRuntime, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, AgentTaskTurnError, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentTimelineItemIdentity, type AgentToolEvent, type AgentTurnResult, type AgentTurnUsage, type AgentTurnUsageRequest, type AgentUpdateItem, type AgentWebSocket, type AgentWebSocketConstructor, type AgentsModule, type AiProviders, type AiProvidersModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CredentialUsage, type CredentialUsageWindow, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FileCreator, type FileDownloadOptions, type FileKind, type FileMetadata, type FileReadUrl, type FileReadUrlItem, type FileReadUrlOptions, type FileReadUrls, type FileStatus, FileTransferError, type FileTransferErrorDetails, type FileTransferStep, type FileUpload, type FileUploadInput, type FileUploadOptions, type FileVisibility, type FilesFetch, type FilesFetchResponse, type FilesModule, type FilesModuleOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IncludedAiQuota, type IncludedAiQuotaWindow, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type ManagedAiProfile, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type OpencodeAiProvider, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SendEmailInput, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAiProvidersModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFilesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };