@getmodus/sdk 0.4.0 → 0.6.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.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  CustomContextItemsResource,
3
3
  ModusClientBase,
4
+ ModusError,
4
5
  ScopeConversationsResource,
5
6
  aipListParams,
6
7
  asRecord,
@@ -9,7 +10,7 @@ import {
9
10
  omitUndefined,
10
11
  validateId,
11
12
  validatePageSize
12
- } from "../chunk-I56O44TR.js";
13
+ } from "../chunk-HEHHN4D6.js";
13
14
 
14
15
  // src/_query.ts
15
16
  function updateMaskQuery(updateMask) {
@@ -471,6 +472,334 @@ async function resolveAndUpdateLink(items, uid, options) {
471
472
  });
472
473
  }
473
474
 
475
+ // src/management/context/files.ts
476
+ import { readdir, readFile, stat } from "fs/promises";
477
+ import { join } from "path";
478
+ var MAX_BULK_UPLOAD_FILES = 100;
479
+ var DEFAULT_LIST_PAGE_SIZE = 50;
480
+ var DEFAULT_PUT_TIMEOUT_MS = 6e4;
481
+ var DEFAULT_POLL_INTERVAL_MS = 500;
482
+ var DEFAULT_UPLOAD_TIMEOUT_MS = 12e4;
483
+ var DEFAULT_CONCURRENCY = 10;
484
+ var STATUS_ORDER = { pending: 0, processing: 1, ready: 2 };
485
+ var WAIT_UNTIL_VALUES = /* @__PURE__ */ new Set(["processing", "ready"]);
486
+ var DEFER_CONTENT_TYPE_TO_SERVER = "application/octet-stream";
487
+ function validateWaitUntil(waitUntil) {
488
+ if (!WAIT_UNTIL_VALUES.has(waitUntil)) {
489
+ throw new Error(`waitUntil must be one of ${[...WAIT_UNTIL_VALUES].join(", ")}, got ${waitUntil}`);
490
+ }
491
+ }
492
+ function validateBulkSize(count, name) {
493
+ if (count === 0) throw new Error(`${name} must not be empty`);
494
+ if (count > MAX_BULK_UPLOAD_FILES) {
495
+ throw new Error(`${name} must have at most ${MAX_BULK_UPLOAD_FILES} entries, got ${count}`);
496
+ }
497
+ }
498
+ function statusSatisfies(status, waitUntil) {
499
+ if (status === "failed") return true;
500
+ return (STATUS_ORDER[status] ?? 0) >= STATUS_ORDER[waitUntil];
501
+ }
502
+ function sleep(ms) {
503
+ return new Promise((resolve) => setTimeout(resolve, ms));
504
+ }
505
+ function chunked(items, size) {
506
+ const out = [];
507
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
508
+ return out;
509
+ }
510
+ async function mapWithConcurrency(items, concurrency, worker) {
511
+ const results = new Array(items.length);
512
+ let cursor = 0;
513
+ async function run() {
514
+ for (; ; ) {
515
+ const index = cursor++;
516
+ if (index >= items.length) return;
517
+ results[index] = await worker(items[index]);
518
+ }
519
+ }
520
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, run));
521
+ return results;
522
+ }
523
+ async function walkFiles(root, recursive) {
524
+ const out = [];
525
+ async function walk(dir) {
526
+ const entries = await readdir(dir, { withFileTypes: true });
527
+ entries.sort((a, b) => a.name.localeCompare(b.name));
528
+ for (const entry of entries) {
529
+ if (entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
530
+ const full = join(dir, entry.name);
531
+ if (entry.isDirectory()) {
532
+ if (recursive) await walk(full);
533
+ } else if (entry.isFile()) {
534
+ out.push(full);
535
+ }
536
+ }
537
+ }
538
+ await walk(root);
539
+ return out;
540
+ }
541
+ async function putBytes(fetchImpl, url, data, contentType, timeoutMs) {
542
+ const response = await fetchImpl(url, {
543
+ method: "PUT",
544
+ body: data,
545
+ headers: { "Content-Type": contentType },
546
+ signal: AbortSignal.timeout(timeoutMs)
547
+ });
548
+ if (!response.ok) {
549
+ const text = await response.text().catch(() => "");
550
+ throw new ModusError(`Upload PUT to presigned URL failed with HTTP ${response.status}.`, {
551
+ statusCode: response.status,
552
+ body: text ? text.slice(0, 500) : void 0
553
+ });
554
+ }
555
+ }
556
+ function createSlotsPayload(files) {
557
+ return {
558
+ files: files.map((f) => ({ fileName: f.fileName, contentType: f.contentType, fileSize: f.fileSize }))
559
+ };
560
+ }
561
+ function uploadFromUrlsPayload(urls) {
562
+ return {
563
+ urls: urls.map((u) => u.fileName !== void 0 ? { url: u.url, fileName: u.fileName } : { url: u.url })
564
+ };
565
+ }
566
+ function assignSlots(batch, result, failed) {
567
+ const failedIndices = new Set(result.failed.map((f) => f.index));
568
+ for (const f of result.failed) {
569
+ failed.push({ path: batch[f.index], error: f.error });
570
+ }
571
+ const remaining = batch.filter((_, i) => !failedIndices.has(i));
572
+ const uploaded = result.uploaded;
573
+ if (uploaded.length < remaining.length) {
574
+ for (const path of remaining.slice(uploaded.length)) {
575
+ failed.push({ path, error: "Server returned fewer upload slots than requested files." });
576
+ }
577
+ }
578
+ const paired = Math.min(remaining.length, uploaded.length);
579
+ const assignments = [];
580
+ for (let i = 0; i < paired; i++) {
581
+ assignments.push({ path: remaining[i], slot: uploaded[i] });
582
+ }
583
+ return assignments;
584
+ }
585
+ var ManagementContextFilesResource = class {
586
+ /** @internal */
587
+ constructor(http, config) {
588
+ this.http = http;
589
+ this.config = config;
590
+ }
591
+ /**
592
+ * Get a presigned S3 PUT URL for one file.
593
+ *
594
+ * @param input.fileName - Original file name — used to build the S3 object key.
595
+ * @param input.contentType - MIME type. Allowed categories: PDF, images, text,
596
+ * Office/OpenDocument documents, audio, and video.
597
+ * @param input.fileSize - File size in bytes. Rejected above 50MB.
598
+ * @returns Presigned upload slot. PUT the raw bytes to `uploadUrl` within 15
599
+ * minutes, then poll `get(uploadId)` — there is no separate finalize call.
600
+ */
601
+ async createUploadUrl(input) {
602
+ return asRecord(
603
+ await invokeWithRetry(this.config, this.http, "ContextFilesController_uploadUrl", {
604
+ jsonBody: { fileName: input.fileName, contentType: input.contentType, fileSize: input.fileSize }
605
+ })
606
+ );
607
+ }
608
+ /**
609
+ * Get presigned S3 PUT URLs for up to 100 files in one call.
610
+ *
611
+ * @param files - Files to create upload slots for (max 100).
612
+ * @returns Slots for every file that passed validation, plus per-index
613
+ * failures (bad MIME type, oversize) for the rest — never a partial 4xx.
614
+ */
615
+ async createUploadUrls(files) {
616
+ validateBulkSize(files.length, "files");
617
+ return asRecord(
618
+ await invokeWithRetry(this.config, this.http, "ContextFilesController_uploadUrls", {
619
+ jsonBody: createSlotsPayload(files)
620
+ })
621
+ );
622
+ }
623
+ /**
624
+ * Fetch one file from a URL and land it as durable context.
625
+ *
626
+ * @param url - Source URL to fetch (SSRF-guarded, 50MB cap, same MIME
627
+ * allow-list as `createUploadUrl`).
628
+ * @param options.fileName - Override file name. Inferred from the URL path when omitted.
629
+ * @returns File upload resource with status `processing` — parsing continues async.
630
+ */
631
+ async uploadFromUrl(url, options = {}) {
632
+ return asRecord(
633
+ await invokeWithRetry(this.config, this.http, "ContextFilesController_uploadFromUrl", {
634
+ jsonBody: options.fileName !== void 0 ? { url, fileName: options.fileName } : { url }
635
+ })
636
+ );
637
+ }
638
+ /**
639
+ * Fetch up to 100 files from URLs in one call.
640
+ *
641
+ * @param urls - URLs to fetch and upload (max 100).
642
+ * @returns File upload resources for every URL that landed, plus per-index
643
+ * failures for the rest — never a partial 4xx.
644
+ */
645
+ async uploadFromUrls(urls) {
646
+ validateBulkSize(urls.length, "urls");
647
+ return asRecord(
648
+ await invokeWithRetry(this.config, this.http, "ContextFilesController_uploadFromUrls", {
649
+ jsonBody: uploadFromUrlsPayload(urls)
650
+ })
651
+ );
652
+ }
653
+ /**
654
+ * Fetch one file upload by its id.
655
+ *
656
+ * @param uploadId - Upload id returned by `createUploadUrl` / `uploadFromUrl`.
657
+ * @returns The file upload resource, including its processing `status`.
658
+ */
659
+ async get(uploadId) {
660
+ validateId(uploadId, "uploadId");
661
+ return asRecord(
662
+ await invokeWithRetry(this.config, this.http, "ContextFilesController_get", {
663
+ pathParams: { uploadId }
664
+ })
665
+ );
666
+ }
667
+ /**
668
+ * List durable file uploads.
669
+ *
670
+ * @param options.pageSize - Items per page (default 50).
671
+ * @param options.pageToken - Opaque token from a previous page's `nextPageToken`.
672
+ * @returns Page of file uploads. Uploads that only have a pending row (not yet
673
+ * landed) aren't included here — use `get(uploadId)` for those.
674
+ */
675
+ list(options = {}) {
676
+ const pageSize = options.pageSize ?? DEFAULT_LIST_PAGE_SIZE;
677
+ validatePageSize(pageSize, 200);
678
+ return this.listPage(pageSize, options.pageToken);
679
+ }
680
+ async listPage(pageSize, pageToken) {
681
+ const data = asRecord(
682
+ await invokeWithRetry(this.config, this.http, "ContextFilesController_list", {
683
+ query: aipListParams(pageSize, pageToken)
684
+ })
685
+ );
686
+ return buildAipPage(data, "files", (raw) => raw, (token) => this.listPage(pageSize, token));
687
+ }
688
+ /**
689
+ * Upload a local file and wait for it to reach `"processing"` or `"ready"`.
690
+ *
691
+ * Gets a presigned URL, PUTs the file bytes, then polls `get()` until the
692
+ * upload leaves `"pending"` (or reaches `"ready"`/`"failed"`).
693
+ *
694
+ * @param path - Path to a local file.
695
+ * @param options.waitUntil - `"processing"` (parsing started, default) or
696
+ * `"ready"` (parsing finished).
697
+ * @param options.pollIntervalMs - Milliseconds between status polls.
698
+ * @param options.timeoutMs - Max milliseconds to wait before raising.
699
+ * @returns The file upload resource once it reaches `waitUntil` (or `"failed"`).
700
+ * @throws {ModusError} If the PUT fails, or polling times out.
701
+ */
702
+ async upload(path, options = {}) {
703
+ const waitUntil = options.waitUntil ?? "processing";
704
+ validateWaitUntil(waitUntil);
705
+ const fileStat = await stat(path);
706
+ if (!fileStat.isFile()) throw new Error(`Not a file: ${path}`);
707
+ const fileName = path.split(/[/\\]/).pop();
708
+ const slot = await this.createUploadUrl({
709
+ fileName,
710
+ contentType: DEFER_CONTENT_TYPE_TO_SERVER,
711
+ fileSize: fileStat.size
712
+ });
713
+ const data = await readFile(path);
714
+ await putBytes(this.config.fetch, slot.uploadUrl, data, slot.contentType, DEFAULT_PUT_TIMEOUT_MS);
715
+ return this.pollUntil(
716
+ slot.uploadId,
717
+ waitUntil,
718
+ options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,
719
+ options.timeoutMs ?? DEFAULT_UPLOAD_TIMEOUT_MS
720
+ );
721
+ }
722
+ async pollUntil(uploadId, waitUntil, pollIntervalMs, timeoutMs) {
723
+ const deadline = Date.now() + timeoutMs;
724
+ for (; ; ) {
725
+ const item = await this.get(uploadId);
726
+ if (statusSatisfies(item.status, waitUntil)) return item;
727
+ if (Date.now() >= deadline) {
728
+ throw new ModusError(
729
+ `Timed out after ${timeoutMs}ms waiting for upload ${JSON.stringify(uploadId)} to reach status ${JSON.stringify(waitUntil)}; last status was ${JSON.stringify(item.status)}.`
730
+ );
731
+ }
732
+ await sleep(pollIntervalMs);
733
+ }
734
+ }
735
+ /**
736
+ * Upload every file in a local directory.
737
+ *
738
+ * Walks `path` (skipping hidden files/directories and symlinks), pages
739
+ * through `createUploadUrls()` in batches of up to 100, then PUTs and polls
740
+ * each file with up to `concurrency` in flight at once. A failure on one
741
+ * file does not stop the others — check `result.failed`.
742
+ *
743
+ * @param path - Path to a local directory.
744
+ * @param options.recursive - Recurse into subdirectories (default `true`).
745
+ * @param options.concurrency - Max concurrent PUT+poll operations (default 10).
746
+ * @param options.waitUntil - `"processing"` (default) or `"ready"` — same as `upload()`.
747
+ * @returns `UploadDirResult` with every successful `FileUpload` and every
748
+ * per-file failure (slot creation or PUT/poll), each tagged with its local path.
749
+ */
750
+ async uploadDir(path, options = {}) {
751
+ const waitUntil = options.waitUntil ?? "processing";
752
+ validateWaitUntil(waitUntil);
753
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
754
+ if (concurrency < 1) throw new Error(`concurrency must be >= 1, got ${concurrency}`);
755
+ const dirStat = await stat(path);
756
+ if (!dirStat.isDirectory()) throw new Error(`Not a directory: ${path}`);
757
+ const uploaded = [];
758
+ const failed = [];
759
+ const files = await walkFiles(path, options.recursive ?? true);
760
+ for (const batch of chunked(files, MAX_BULK_UPLOAD_FILES)) {
761
+ const slots = await this.createSlots(batch, failed);
762
+ const results = await this.uploadBatch(slots, waitUntil, concurrency);
763
+ for (const result of results) {
764
+ if ("error" in result) failed.push(result);
765
+ else uploaded.push(result);
766
+ }
767
+ }
768
+ return { uploaded, failed };
769
+ }
770
+ async createSlots(batch, failed) {
771
+ const readable = [];
772
+ const inputs = [];
773
+ for (const path of batch) {
774
+ try {
775
+ const fileStat = await stat(path);
776
+ const fileName = path.split(/[/\\]/).pop();
777
+ inputs.push({ fileName, contentType: DEFER_CONTENT_TYPE_TO_SERVER, fileSize: fileStat.size });
778
+ readable.push(path);
779
+ } catch (error) {
780
+ const message = error instanceof Error ? error.message : String(error);
781
+ failed.push({ path, error: message });
782
+ }
783
+ }
784
+ if (inputs.length === 0) return [];
785
+ const result = await this.createUploadUrls(inputs);
786
+ return assignSlots(readable, result, failed);
787
+ }
788
+ async uploadBatch(slots, waitUntil, concurrency) {
789
+ if (slots.length === 0) return [];
790
+ return mapWithConcurrency(slots, concurrency, async ({ path, slot }) => {
791
+ try {
792
+ const data = await readFile(path);
793
+ await putBytes(this.config.fetch, slot.uploadUrl, data, slot.contentType, DEFAULT_PUT_TIMEOUT_MS);
794
+ return await this.pollUntil(slot.uploadId, waitUntil, DEFAULT_POLL_INTERVAL_MS, DEFAULT_UPLOAD_TIMEOUT_MS);
795
+ } catch (error) {
796
+ const message = error instanceof Error ? error.message : String(error);
797
+ return { path, error: message };
798
+ }
799
+ });
800
+ }
801
+ };
802
+
474
803
  // src/management/context/items.ts
475
804
  function contextListParams(pageSize, pageToken, contextType) {
476
805
  const extra = {};
@@ -581,6 +910,7 @@ var ManagementContextResource = class {
581
910
  this.config = config;
582
911
  this.items = new ManagementContextItemsResource(http, config);
583
912
  this.customItems = new CustomContextItemsResource(http, config);
913
+ this.files = new ManagementContextFilesResource(http, config);
584
914
  }
585
915
  /**
586
916
  * Add a free-form text note to the knowledge base.