@hiai-gg/docsmint 2.1.5 → 2.2.1

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.
@@ -22,6 +22,7 @@ __export(exports_schema, {
22
22
  apiKeys: () => apiKeys,
23
23
  attachmentRelations: () => attachmentRelations,
24
24
  attachmentStorageCleanupOutbox: () => attachmentStorageCleanupOutbox,
25
+ attachmentUploadOperations: () => attachmentUploadOperations,
25
26
  attachments: () => attachments,
26
27
  auditLog: () => auditLog,
27
28
  categories: () => categories,
@@ -38,6 +39,7 @@ __export(exports_schema, {
38
39
  documentVisibilityEnum: () => documentVisibilityEnum,
39
40
  documents: () => documents,
40
41
  embeddingStatusEnum: () => embeddingStatusEnum,
42
+ folderCreateOperations: () => folderCreateOperations,
41
43
  folderRelations: () => folderRelations,
42
44
  folders: () => folders,
43
45
  guestAccess: () => guestAccess,
@@ -514,6 +516,21 @@ var pendingAttachmentUploads = pgTable("pending_attachment_uploads", {
514
516
  index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
515
517
  check("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
516
518
  ]);
519
+ var attachmentUploadOperations = pgTable("attachment_upload_operations", {
520
+ id: uuid("id").primaryKey().defaultRandom(),
521
+ workspaceId: text("workspace_id").notNull(),
522
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
523
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
524
+ idempotencyKey: text("idempotency_key").notNull(),
525
+ requestFingerprint: text("request_fingerprint").notNull(),
526
+ sourceSha256: text("source_sha256").notNull(),
527
+ storageKey: text("storage_key").notNull(),
528
+ expiresAt: timestamp("expires_at").notNull(),
529
+ createdAt: timestamp("created_at").defaultNow().notNull()
530
+ }, (table) => [
531
+ uniqueIndex("attachment_upload_operations_actor_document_key_unique").on(table.workspaceId, table.actorUserId, table.documentId, table.idempotencyKey),
532
+ uniqueIndex("attachment_upload_operations_storage_key_unique").on(table.storageKey)
533
+ ]);
517
534
  var attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
518
535
  id: uuid("id").primaryKey().defaultRandom(),
519
536
  sourceKind: text("source_kind").notNull(),
@@ -686,6 +703,18 @@ var documentCreateOperations = pgTable("document_create_operations", {
686
703
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
687
704
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
688
705
  ]);
706
+ var folderCreateOperations = pgTable("folder_create_operations", {
707
+ id: uuid("id").primaryKey().defaultRandom(),
708
+ workspaceId: text("workspace_id").notNull(),
709
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
710
+ idempotencyKey: text("idempotency_key").notNull(),
711
+ folderId: uuid("folder_id").notNull(),
712
+ requestFingerprint: text("request_fingerprint").notNull(),
713
+ createdAt: timestamp("created_at").defaultNow().notNull()
714
+ }, (table) => [
715
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
716
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
717
+ ]);
689
718
  var versionRelations = relations(versions, ({ one }) => ({
690
719
  document: one(documents, {
691
720
  fields: [versions.documentId],
@@ -22,6 +22,7 @@ __export(exports_schema, {
22
22
  apiKeys: () => apiKeys,
23
23
  attachmentRelations: () => attachmentRelations,
24
24
  attachmentStorageCleanupOutbox: () => attachmentStorageCleanupOutbox,
25
+ attachmentUploadOperations: () => attachmentUploadOperations,
25
26
  attachments: () => attachments,
26
27
  auditLog: () => auditLog,
27
28
  categories: () => categories,
@@ -38,6 +39,7 @@ __export(exports_schema, {
38
39
  documentVisibilityEnum: () => documentVisibilityEnum,
39
40
  documents: () => documents,
40
41
  embeddingStatusEnum: () => embeddingStatusEnum,
42
+ folderCreateOperations: () => folderCreateOperations,
41
43
  folderRelations: () => folderRelations,
42
44
  folders: () => folders,
43
45
  guestAccess: () => guestAccess,
@@ -514,6 +516,21 @@ var pendingAttachmentUploads = pgTable("pending_attachment_uploads", {
514
516
  index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
515
517
  check("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
516
518
  ]);
519
+ var attachmentUploadOperations = pgTable("attachment_upload_operations", {
520
+ id: uuid("id").primaryKey().defaultRandom(),
521
+ workspaceId: text("workspace_id").notNull(),
522
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
523
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
524
+ idempotencyKey: text("idempotency_key").notNull(),
525
+ requestFingerprint: text("request_fingerprint").notNull(),
526
+ sourceSha256: text("source_sha256").notNull(),
527
+ storageKey: text("storage_key").notNull(),
528
+ expiresAt: timestamp("expires_at").notNull(),
529
+ createdAt: timestamp("created_at").defaultNow().notNull()
530
+ }, (table) => [
531
+ uniqueIndex("attachment_upload_operations_actor_document_key_unique").on(table.workspaceId, table.actorUserId, table.documentId, table.idempotencyKey),
532
+ uniqueIndex("attachment_upload_operations_storage_key_unique").on(table.storageKey)
533
+ ]);
517
534
  var attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
518
535
  id: uuid("id").primaryKey().defaultRandom(),
519
536
  sourceKind: text("source_kind").notNull(),
@@ -686,6 +703,18 @@ var documentCreateOperations = pgTable("document_create_operations", {
686
703
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
687
704
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
688
705
  ]);
706
+ var folderCreateOperations = pgTable("folder_create_operations", {
707
+ id: uuid("id").primaryKey().defaultRandom(),
708
+ workspaceId: text("workspace_id").notNull(),
709
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
710
+ idempotencyKey: text("idempotency_key").notNull(),
711
+ folderId: uuid("folder_id").notNull(),
712
+ requestFingerprint: text("request_fingerprint").notNull(),
713
+ createdAt: timestamp("created_at").defaultNow().notNull()
714
+ }, (table) => [
715
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
716
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
717
+ ]);
689
718
  var versionRelations = relations(versions, ({ one }) => ({
690
719
  document: one(documents, {
691
720
  fields: [versions.documentId],
@@ -22,6 +22,7 @@ __export(exports_schema, {
22
22
  apiKeys: () => apiKeys,
23
23
  attachmentRelations: () => attachmentRelations,
24
24
  attachmentStorageCleanupOutbox: () => attachmentStorageCleanupOutbox,
25
+ attachmentUploadOperations: () => attachmentUploadOperations,
25
26
  attachments: () => attachments,
26
27
  auditLog: () => auditLog,
27
28
  categories: () => categories,
@@ -38,6 +39,7 @@ __export(exports_schema, {
38
39
  documentVisibilityEnum: () => documentVisibilityEnum,
39
40
  documents: () => documents,
40
41
  embeddingStatusEnum: () => embeddingStatusEnum,
42
+ folderCreateOperations: () => folderCreateOperations,
41
43
  folderRelations: () => folderRelations,
42
44
  folders: () => folders,
43
45
  guestAccess: () => guestAccess,
@@ -514,6 +516,21 @@ var pendingAttachmentUploads = pgTable("pending_attachment_uploads", {
514
516
  index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
515
517
  check("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
516
518
  ]);
519
+ var attachmentUploadOperations = pgTable("attachment_upload_operations", {
520
+ id: uuid("id").primaryKey().defaultRandom(),
521
+ workspaceId: text("workspace_id").notNull(),
522
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
523
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
524
+ idempotencyKey: text("idempotency_key").notNull(),
525
+ requestFingerprint: text("request_fingerprint").notNull(),
526
+ sourceSha256: text("source_sha256").notNull(),
527
+ storageKey: text("storage_key").notNull(),
528
+ expiresAt: timestamp("expires_at").notNull(),
529
+ createdAt: timestamp("created_at").defaultNow().notNull()
530
+ }, (table) => [
531
+ uniqueIndex("attachment_upload_operations_actor_document_key_unique").on(table.workspaceId, table.actorUserId, table.documentId, table.idempotencyKey),
532
+ uniqueIndex("attachment_upload_operations_storage_key_unique").on(table.storageKey)
533
+ ]);
517
534
  var attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
518
535
  id: uuid("id").primaryKey().defaultRandom(),
519
536
  sourceKind: text("source_kind").notNull(),
@@ -686,6 +703,18 @@ var documentCreateOperations = pgTable("document_create_operations", {
686
703
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
687
704
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
688
705
  ]);
706
+ var folderCreateOperations = pgTable("folder_create_operations", {
707
+ id: uuid("id").primaryKey().defaultRandom(),
708
+ workspaceId: text("workspace_id").notNull(),
709
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
710
+ idempotencyKey: text("idempotency_key").notNull(),
711
+ folderId: uuid("folder_id").notNull(),
712
+ requestFingerprint: text("request_fingerprint").notNull(),
713
+ createdAt: timestamp("created_at").defaultNow().notNull()
714
+ }, (table) => [
715
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
716
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
717
+ ]);
689
718
  var versionRelations = relations(versions, ({ one }) => ({
690
719
  document: one(documents, {
691
720
  fields: [versions.documentId],
package/dist/client.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * failures (502 / 503 / 504 / timeout / network reset) are retried
8
8
  * with exponential backoff up to `config.retries` attempts.
9
9
  */
10
- import type { DocsApiKeyCreated, DocsApiKeyListResponse, DocsAttachment, DocsAttachmentConfirmInput, DocsAttachmentListResponse, DocsAttachmentPresignInput, DocsAttachmentPresignResponse, DocsCategory, DocsCategoryListItem, DocsCategoryInput, DocsCategoryUpdate, DocsDocument, DocsDocumentCreateInput, DocsDocumentCursorPage, DocsDocumentIndexRefresh, DocsDocumentIndexStatus, DocsDocumentKnowledgeSummary, DocsDocumentListResponse, DocsDocumentPipeline, DocsPipelineWarningRetry, DocsDocumentUpdateInput, DocsFolder, DocsFolderCreateInput, DocsFolderUpdateInput, DocsGraphEntitiesResponse, DocsGraphRelatedResponse, DocsGraphSearchResponse, DocsHealthResponse, DocsRequestContext, DocsSearchOptions, DocsSearchResponse, DocsSearchSuggestItem, DocsSharedContent, DocsShareLink, DocsShareListResponse, DocsShareRole, DocsTag, DocsTrashResponse, DocsVersion, DocsVersionDiff } from "./types.js";
10
+ import type { DocsApiKeyCreated, DocsApiKeyListResponse, DocsAttachment, DocsAttachmentConfirmInput, DocsAttachmentListResponse, DocsAttachmentPresignInput, DocsAttachmentPresignResponse, DocsCategory, DocsCategoryListItem, DocsCategoryInput, DocsCategoryUpdate, DocsDocument, DocsDocumentCreateInput, DocsDocumentCursorPage, DocsCatalogCursorPage, DocsDocumentIndexRefresh, DocsDocumentIndexStatus, DocsDocumentKnowledgeSummary, DocsDocumentListResponse, DocsDocumentPipeline, DocsPipelineWarningRetry, DocsDocumentUpdateInput, DocsFolder, DocsFolderCreateInput, DocsFolderUpdateInput, DocsGraphEntitiesResponse, DocsGraphRelatedResponse, DocsGraphSearchResponse, DocsHealthResponse, DocsRequestContext, DocsSearchOptions, DocsSearchResponse, DocsSearchSuggestItem, DocsSharedContent, DocsShareLink, DocsShareListResponse, DocsShareRole, DocsTag, DocsTrashResponse, DocsVersion, DocsVersionDiff } from "./types.js";
11
11
  export interface DocsClientConfig {
12
12
  /** Explicit API prefix. Existing clients keep /api; no endpoint probing is performed. */
13
13
  apiPrefix?: "/api" | "/api/v1";
@@ -81,9 +81,12 @@ export declare class DocsClient {
81
81
  categoryId?: string;
82
82
  cursor?: string;
83
83
  limit?: number;
84
+ includeTotal?: boolean;
84
85
  sortBy?: import("./types").DocsDocumentSortField;
85
86
  sortOrder?: import("./types").DocsSortOrder;
86
87
  }, context?: DocsRequestContext): Promise<DocsDocumentCursorPage>;
88
+ listCatalogDocuments(options?: Parameters<DocsClient["listDocuments"]>[0], context?: DocsRequestContext): Promise<DocsCatalogCursorPage>;
89
+ private listDocumentCursor;
87
90
  duplicateDoc(id: string, context?: DocsRequestContext): Promise<DocsDocument>;
88
91
  getDocumentPipeline(id: string, context?: DocsRequestContext): Promise<DocsDocumentPipeline>;
89
92
  retryDocumentPipelineWarnings(id: string, context?: DocsRequestContext): Promise<DocsPipelineWarningRetry>;
@@ -203,6 +206,8 @@ export declare class DocsClient {
203
206
  presignAttachment(documentId: string, input: DocsAttachmentPresignInput, context?: DocsRequestContext): Promise<DocsAttachmentPresignResponse>;
204
207
  confirmAttachment(documentId: string, input: DocsAttachmentConfirmInput, context?: DocsRequestContext): Promise<DocsAttachment>;
205
208
  listAttachments(documentId: string, context?: DocsRequestContext): Promise<DocsAttachmentListResponse>;
209
+ /** Fetch an authorized attachment without exposing its storage URL. */
210
+ fetchAttachment(id: string, context?: DocsRequestContext): Promise<Response>;
206
211
  deleteAttachment(id: string, context?: DocsRequestContext): Promise<void>;
207
212
  listVersions(documentId: string, options?: {
208
213
  onlySnapshots?: boolean;
package/dist/client.js CHANGED
@@ -151,6 +151,12 @@ export class DocsClient {
151
151
  * bound by the server to the authenticated workspace and category scope.
152
152
  */
153
153
  async listDocuments(options = {}, context) {
154
+ return this.listDocumentCursor(options, context);
155
+ }
156
+ async listCatalogDocuments(options = {}, context) {
157
+ return this.listDocumentCursor(options, context, "catalog");
158
+ }
159
+ async listDocumentCursor(options, context, view) {
154
160
  return this.request("GET", "/api/documents/cursor", {
155
161
  query: this.cleanQuery({
156
162
  categoryId: options.categoryId,
@@ -165,6 +171,8 @@ export class DocsClient {
165
171
  updatedTo: options.updatedTo,
166
172
  cursor: options.cursor,
167
173
  limit: options.limit,
174
+ view,
175
+ includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
168
176
  sortBy: options.sortBy,
169
177
  sortOrder: options.sortOrder,
170
178
  }),
@@ -409,6 +417,13 @@ export class DocsClient {
409
417
  async listAttachments(documentId, context) {
410
418
  return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
411
419
  }
420
+ /** Fetch an authorized attachment without exposing its storage URL. */
421
+ async fetchAttachment(id, context) {
422
+ const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
423
+ if (!response.ok)
424
+ throw await this.toApiError(response);
425
+ return response;
426
+ }
412
427
  async deleteAttachment(id, context) {
413
428
  await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
414
429
  }
@@ -477,8 +492,12 @@ export class DocsClient {
477
492
  headers.set("Cookie", requestContext.cookie);
478
493
  if (requestContext?.requestId)
479
494
  headers.set("X-Request-Id", requestContext.requestId);
480
- if (requestContext?.idempotencyKey)
495
+ if (requestContext?.idempotencyKey === null) {
496
+ headers.delete("Idempotency-Key");
497
+ }
498
+ else if (requestContext?.idempotencyKey) {
481
499
  headers.set("Idempotency-Key", requestContext.idempotencyKey);
500
+ }
482
501
  // Document creation supports replay on the server. Generate once before
483
502
  // the retry loop so a lost response cannot create a second document.
484
503
  if (method === "POST" &&
@@ -37519,6 +37519,7 @@ __export(exports_schema, {
37519
37519
  apiKeys: () => apiKeys,
37520
37520
  attachmentRelations: () => attachmentRelations,
37521
37521
  attachmentStorageCleanupOutbox: () => attachmentStorageCleanupOutbox,
37522
+ attachmentUploadOperations: () => attachmentUploadOperations,
37522
37523
  attachments: () => attachments,
37523
37524
  auditLog: () => auditLog,
37524
37525
  categories: () => categories,
@@ -37535,6 +37536,7 @@ __export(exports_schema, {
37535
37536
  documentVisibilityEnum: () => documentVisibilityEnum,
37536
37537
  documents: () => documents,
37537
37538
  embeddingStatusEnum: () => embeddingStatusEnum,
37539
+ folderCreateOperations: () => folderCreateOperations,
37538
37540
  folderRelations: () => folderRelations,
37539
37541
  folders: () => folders,
37540
37542
  guestAccess: () => guestAccess,
@@ -38023,6 +38025,21 @@ var pendingAttachmentUploads = pgTable("pending_attachment_uploads", {
38023
38025
  index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
38024
38026
  check("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
38025
38027
  ]);
38028
+ var attachmentUploadOperations = pgTable("attachment_upload_operations", {
38029
+ id: uuid("id").primaryKey().defaultRandom(),
38030
+ workspaceId: text("workspace_id").notNull(),
38031
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
38032
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
38033
+ idempotencyKey: text("idempotency_key").notNull(),
38034
+ requestFingerprint: text("request_fingerprint").notNull(),
38035
+ sourceSha256: text("source_sha256").notNull(),
38036
+ storageKey: text("storage_key").notNull(),
38037
+ expiresAt: timestamp("expires_at").notNull(),
38038
+ createdAt: timestamp("created_at").defaultNow().notNull()
38039
+ }, (table) => [
38040
+ uniqueIndex("attachment_upload_operations_actor_document_key_unique").on(table.workspaceId, table.actorUserId, table.documentId, table.idempotencyKey),
38041
+ uniqueIndex("attachment_upload_operations_storage_key_unique").on(table.storageKey)
38042
+ ]);
38026
38043
  var attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
38027
38044
  id: uuid("id").primaryKey().defaultRandom(),
38028
38045
  sourceKind: text("source_kind").notNull(),
@@ -38195,6 +38212,18 @@ var documentCreateOperations = pgTable("document_create_operations", {
38195
38212
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
38196
38213
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
38197
38214
  ]);
38215
+ var folderCreateOperations = pgTable("folder_create_operations", {
38216
+ id: uuid("id").primaryKey().defaultRandom(),
38217
+ workspaceId: text("workspace_id").notNull(),
38218
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
38219
+ idempotencyKey: text("idempotency_key").notNull(),
38220
+ folderId: uuid("folder_id").notNull(),
38221
+ requestFingerprint: text("request_fingerprint").notNull(),
38222
+ createdAt: timestamp("created_at").defaultNow().notNull()
38223
+ }, (table) => [
38224
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
38225
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
38226
+ ]);
38198
38227
  var versionRelations = relations(versions, ({ one }) => ({
38199
38228
  document: one(documents, {
38200
38229
  fields: [versions.documentId],
@@ -40244,6 +40273,12 @@ async function withTenantDatabase(database, ctx, fn) {
40244
40273
  // ../../backend/src/lib/attachment-storage-cleanup.ts
40245
40274
  import { and, eq, inArray, sql as sql3 } from "drizzle-orm";
40246
40275
 
40276
+ // ../../backend/src/lib/attachment-image-key.ts
40277
+ var pendingWebpSuffix = ".webp.pending";
40278
+ function committedAttachmentKey(sourceKey) {
40279
+ return sourceKey.endsWith(pendingWebpSuffix) ? sourceKey.slice(0, -".pending".length) : sourceKey;
40280
+ }
40281
+
40247
40282
  // ../../backend/src/lib/logger.ts
40248
40283
  var import_pino = __toESM(require_pino(), 1);
40249
40284
  function resolvePrettyTransport(environment, resolveModule) {
@@ -45920,6 +45955,7 @@ var envSchema = object({
45920
45955
  HIAI_DOCS_API_KEY: string2().trim().optional().default("").transform((value) => value || undefined).refine((value) => true, "HIAI_DOCS_API_KEY must be set to a non-placeholder value in production"),
45921
45956
  API_KEY_ENCRYPTION_SECRET: string2().min(32, "API_KEY_ENCRYPTION_SECRET must be at least 32 characters").default("change-me-to-random-32-chars-long").refine((value) => true, "API_KEY_ENCRYPTION_SECRET must be set in production"),
45922
45957
  OWNER_ID: string2().uuid().default("00000000-0000-4000-8000-000000000001"),
45958
+ DOCSMINT_ATTACHMENT_WEBP_ENABLED: _enum(["true", "false"]).default("false").transform((value) => value === "true"),
45923
45959
  DOCSMINT_WORKSPACE_ENABLED: string2().optional().default("false").transform((value) => value === "true"),
45924
45960
  DOCSMINT_WORKSPACE_ISSUER: string2().trim().optional(),
45925
45961
  DOCSMINT_WORKSPACE_SECRET: string2().optional(),
@@ -46189,7 +46225,9 @@ async function claimCleanupPage(leaseOwner, now, pageSize, quotaReleaseAvailable
46189
46225
  AND NOT EXISTS (
46190
46226
  SELECT 1
46191
46227
  FROM public.pending_attachment_uploads AS pending
46192
- WHERE pending.storage_key = candidate.storage_key
46228
+ WHERE (pending.storage_key = candidate.storage_key
46229
+ OR (pending.storage_key LIKE '%.webp.pending'
46230
+ AND left(pending.storage_key, length(pending.storage_key) - 8) = candidate.storage_key))
46193
46231
  AND pending.lease_owner LIKE 'confirm:%'
46194
46232
  AND pending.lease_expires_at IS NOT NULL
46195
46233
  AND pending.lease_expires_at > ${nowTimestamp}
@@ -46231,7 +46269,7 @@ function quotaContext(row, signal) {
46231
46269
  workspaceId: row.workspace_id,
46232
46270
  actorUserId: row.actor_user_id,
46233
46271
  documentId: row.document_id,
46234
- storageKey: row.storage_key,
46272
+ storageKey: committedAttachmentKey(row.storage_key),
46235
46273
  proposedSize: row.size,
46236
46274
  requestId: row.id,
46237
46275
  idempotencyKey: row.quota_operation_key,
package/dist/mcp-cli.js CHANGED
@@ -305,6 +305,12 @@ class DocsClient {
305
305
  }, context);
306
306
  }
307
307
  async listDocuments(options = {}, context) {
308
+ return this.listDocumentCursor(options, context);
309
+ }
310
+ async listCatalogDocuments(options = {}, context) {
311
+ return this.listDocumentCursor(options, context, "catalog");
312
+ }
313
+ async listDocumentCursor(options, context, view) {
308
314
  return this.request("GET", "/api/documents/cursor", {
309
315
  query: this.cleanQuery({
310
316
  categoryId: options.categoryId,
@@ -319,6 +325,8 @@ class DocsClient {
319
325
  updatedTo: options.updatedTo,
320
326
  cursor: options.cursor,
321
327
  limit: options.limit,
328
+ view,
329
+ includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
322
330
  sortBy: options.sortBy,
323
331
  sortOrder: options.sortOrder
324
332
  })
@@ -529,6 +537,12 @@ class DocsClient {
529
537
  async listAttachments(documentId, context) {
530
538
  return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
531
539
  }
540
+ async fetchAttachment(id, context) {
541
+ const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
542
+ if (!response.ok)
543
+ throw await this.toApiError(response);
544
+ return response;
545
+ }
532
546
  async deleteAttachment(id, context) {
533
547
  await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
534
548
  }
@@ -590,8 +604,11 @@ class DocsClient {
590
604
  headers.set("Cookie", requestContext.cookie);
591
605
  if (requestContext?.requestId)
592
606
  headers.set("X-Request-Id", requestContext.requestId);
593
- if (requestContext?.idempotencyKey)
607
+ if (requestContext?.idempotencyKey === null) {
608
+ headers.delete("Idempotency-Key");
609
+ } else if (requestContext?.idempotencyKey) {
594
610
  headers.set("Idempotency-Key", requestContext.idempotencyKey);
611
+ }
595
612
  if (method === "POST" && path === "/api/documents" && !headers.has("Idempotency-Key")) {
596
613
  headers.set("Idempotency-Key", crypto.randomUUID());
597
614
  }
@@ -1030,6 +1047,14 @@ var operationOutputSchemas = {
1030
1047
  permanently_delete_document: deleteAcknowledgmentSchema
1031
1048
  };
1032
1049
  var variant = (operation, result) => z.object({ operation: z.literal(operation), result });
1050
+ var attachment = z.object({
1051
+ id: z.string().uuid(),
1052
+ documentId: z.string().uuid().optional(),
1053
+ filename: z.string(),
1054
+ mimeType: z.string(),
1055
+ size: z.number().int().nonnegative(),
1056
+ url: z.string()
1057
+ });
1033
1058
  var singleToolOutputSchemas = {
1034
1059
  delete_document: operationOutputSchemas.delete_document,
1035
1060
  delete_folder: operationOutputSchemas.delete_folder,
@@ -1051,6 +1076,16 @@ var singleToolOutputSchemas = {
1051
1076
  variant("markdown", operationOutputSchemas.export_document),
1052
1077
  variant("versions", operationOutputSchemas.get_version_history)
1053
1078
  ]),
1079
+ upload_document_image: attachment,
1080
+ check_document_attachments: z.strictObject({
1081
+ items: z.array(attachment),
1082
+ verifiedAttachmentId: z.string().uuid().optional(),
1083
+ verification: z.strictObject({
1084
+ size: z.number().int().positive(),
1085
+ mimeType: z.string(),
1086
+ sha256: z.string().regex(/^[a-f0-9]{64}$/)
1087
+ }).optional()
1088
+ }),
1054
1089
  save_document: z.union([
1055
1090
  variant("create", operationOutputSchemas.create_document),
1056
1091
  variant("update", operationOutputSchemas.update_document)
@@ -1118,8 +1153,55 @@ var toolOutputSchemas = {
1118
1153
  // ../mcp-server/src/compact.ts
1119
1154
  import { z as z4 } from "zod";
1120
1155
 
1121
- // ../mcp-server/src/batch-workspace.ts
1122
- import { z as z3 } from "zod";
1156
+ // ../mcp-server/src/client.ts
1157
+ import { createHash as createHash2 } from "crypto";
1158
+
1159
+ // ../mcp-server/src/attachment-verification.ts
1160
+ import { createHash } from "crypto";
1161
+ var MAX_VERIFIED_IMAGE_BYTES = 16 * 1024 * 1024;
1162
+ async function verifyAttachmentResponse(response, attachment) {
1163
+ const reader = response.body?.getReader();
1164
+ if (!reader)
1165
+ throw new Error("The attachment response has no body.");
1166
+ try {
1167
+ const mimeType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
1168
+ if (!response.ok || mimeType !== attachment.mimeType.toLowerCase())
1169
+ throw new Error("The stored attachment MIME type does not match its record.");
1170
+ if (!Number.isSafeInteger(attachment.size) || attachment.size <= 0 || attachment.size > MAX_VERIFIED_IMAGE_BYTES)
1171
+ throw new Error("The attachment exceeds the verification size limit.");
1172
+ const declaredLength = response.headers.get("content-length");
1173
+ if (declaredLength !== null && (!/^[0-9]+$/.test(declaredLength) || Number(declaredLength) !== attachment.size))
1174
+ throw new Error("The stored attachment length does not match its record.");
1175
+ const hash = createHash("sha256");
1176
+ let size = 0;
1177
+ let prefix = Buffer.alloc(0);
1178
+ for (;; ) {
1179
+ const { done, value } = await reader.read();
1180
+ if (done)
1181
+ break;
1182
+ size += value.byteLength;
1183
+ if (size > attachment.size || size > MAX_VERIFIED_IMAGE_BYTES)
1184
+ throw new Error("The attachment response exceeds its recorded size.");
1185
+ if (prefix.length < 12)
1186
+ prefix = Buffer.concat([
1187
+ prefix,
1188
+ Buffer.from(value.subarray(0, 12 - prefix.length))
1189
+ ]);
1190
+ hash.update(value);
1191
+ }
1192
+ if (size !== attachment.size)
1193
+ throw new Error("The attachment response is incomplete.");
1194
+ const imageMatches = mimeType === "image/webp" && prefix.toString("ascii", 0, 4) === "RIFF" && prefix.toString("ascii", 8, 12) === "WEBP" || mimeType === "image/png" && prefix.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || mimeType === "image/jpeg" && prefix[0] === 255 && prefix[1] === 216 && prefix[2] === 255 || mimeType === "image/gif" && ["GIF87a", "GIF89a"].includes(prefix.toString("ascii", 0, 6));
1195
+ if (!imageMatches)
1196
+ throw new Error("The attachment bytes do not match its image MIME type.");
1197
+ return { size, mimeType, sha256: hash.digest("hex") };
1198
+ } finally {
1199
+ await reader.cancel().catch(() => {
1200
+ return;
1201
+ });
1202
+ reader.releaseLock();
1203
+ }
1204
+ }
1123
1205
 
1124
1206
  // ../mcp-server/src/client.ts
1125
1207
  var DEFAULT_BASE_URL = "http://localhost:50700";
@@ -1159,6 +1241,45 @@ function sanitizeMcpRequestContext(context) {
1159
1241
  function createMcpDocsClient(docsClient, requestContext) {
1160
1242
  const context = sanitizeMcpRequestContext(requestContext);
1161
1243
  return {
1244
+ uploadDocumentImage: async (id, filename, mimeType, bytes, operationId) => {
1245
+ const descriptor = {
1246
+ filename,
1247
+ contentType: mimeType,
1248
+ size: bytes.byteLength,
1249
+ ...operationId ? { sourceSha256: createHash2("sha256").update(bytes).digest("hex") } : {}
1250
+ };
1251
+ const signal = context?.signal ? AbortSignal.any([context.signal, AbortSignal.timeout(30000)]) : AbortSignal.timeout(30000);
1252
+ const uploadContext = { ...context, signal, idempotencyKey: operationId ?? null };
1253
+ const upload = await docsClient.presignAttachment(id, descriptor, uploadContext);
1254
+ if (!upload.alreadyConfirmed) {
1255
+ const response = await fetch(upload.url, {
1256
+ method: "PUT",
1257
+ body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
1258
+ redirect: "error",
1259
+ signal
1260
+ }).catch(() => {
1261
+ throw new HiaiDocsError("Could not send image bytes to DocsMint storage.", 502, null, "IMAGE_STORAGE_UNAVAILABLE");
1262
+ });
1263
+ await response.body?.cancel();
1264
+ if (!response.ok)
1265
+ throw new HiaiDocsError(`DocsMint storage rejected the image (${response.status}).`, response.status, null, "IMAGE_STORAGE_REJECTED");
1266
+ }
1267
+ return docsClient.confirmAttachment(id, {
1268
+ ...descriptor,
1269
+ key: upload.key,
1270
+ uploadToken: upload.uploadToken,
1271
+ quotaReservationId: upload.quotaReservationId
1272
+ }, uploadContext);
1273
+ },
1274
+ listAttachments: (id) => docsClient.listAttachments(id, context),
1275
+ verifyAttachment: async (attachment) => {
1276
+ const signal = context?.signal ? AbortSignal.any([context.signal, AbortSignal.timeout(30000)]) : AbortSignal.timeout(30000);
1277
+ const response = await docsClient.fetchAttachment(attachment.id, {
1278
+ ...context,
1279
+ signal
1280
+ });
1281
+ return verifyAttachmentResponse(response, attachment);
1282
+ },
1162
1283
  getFolder: (id) => docsClient.getFolder(id, context),
1163
1284
  createTag: (input) => docsClient.createTag(input, context),
1164
1285
  updateTag: (id, input) => docsClient.updateTag(id, input, context),
@@ -1215,6 +1336,9 @@ var client = new Proxy({}, {
1215
1336
  }
1216
1337
  });
1217
1338
 
1339
+ // ../mcp-server/src/batch-workspace.ts
1340
+ import { z as z3 } from "zod";
1341
+
1218
1342
  // ../mcp-server/src/client-routing-schema.ts
1219
1343
  import { z as z2 } from "zod";
1220
1344
  function canonical(value) {
@@ -1424,6 +1548,18 @@ var content = z4.string().describe("Markdown document content; an empty string c
1424
1548
  var read = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
1425
1549
  var write = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
1426
1550
  var destructive = { ...write, destructiveHint: true };
1551
+ function matchesImageType(bytes, mimeType) {
1552
+ switch (mimeType) {
1553
+ case "image/png":
1554
+ return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
1555
+ case "image/jpeg":
1556
+ return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
1557
+ case "image/webp":
1558
+ return bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP";
1559
+ default:
1560
+ return false;
1561
+ }
1562
+ }
1427
1563
  function required2(value, name) {
1428
1564
  if (!value)
1429
1565
  throw new Error(`The injected legacy MCP client does not support ${name}; use a public DocsClient.`);
@@ -1459,6 +1595,35 @@ function registerCompactCapabilities(server, client, wrap) {
1459
1595
  const { action: _action, id, ...data } = input;
1460
1596
  return { operation: "update", result: await client.updateDocument(id, data) };
1461
1597
  });
1598
+ const maxImageBytes = 2 * 1024 * 1024;
1599
+ register("upload_document_image", "Upload one PNG, JPEG or WebP image to an existing editable document. Send the file bytes as base64, up to 2 MiB before encoding. Insert the returned url as an image using save_document. If the result is lost, check attachments before uploading again.", z4.strictObject({
1600
+ documentId: uuid2,
1601
+ filename: z4.string().min(1).max(255).regex(/^[^/\\\u0000-\u001f\u007f]+$/).describe("Image file name with extension and without path segments."),
1602
+ mimeType: z4.enum(["image/png", "image/jpeg", "image/webp"]).describe("MIME type of the source image."),
1603
+ operationId: z4.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/).optional().describe("Stable upload operation ID. Reuse with identical bytes and metadata after timeout to prevent duplicates. Requires WebP finalization on the server."),
1604
+ contentBase64: z4.base64().min(4).max(Math.ceil(maxImageBytes / 3) * 4).describe("Base64 file bytes without a data: prefix.")
1605
+ }), write, async ({ documentId, filename, mimeType, contentBase64, operationId }) => {
1606
+ const bytes = Buffer.from(contentBase64, "base64");
1607
+ if (!bytes.length || bytes.length > maxImageBytes)
1608
+ throw new HiaiDocsError("Image must be between 1 byte and 2 MiB.", 413, null, "IMAGE_TOO_LARGE");
1609
+ if (!matchesImageType(bytes, mimeType))
1610
+ throw new HiaiDocsError("Image bytes do not match the declared MIME type.", 415, null, "IMAGE_MIME_MISMATCH");
1611
+ return { ...await required2(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes, operationId), documentId };
1612
+ });
1613
+ register("check_document_attachments", "List attachments on a readable document. Supply attachmentId to verify that this attachment belongs to the document and that its stored bytes can be opened with the current access.", z4.strictObject({
1614
+ documentId: uuid2,
1615
+ attachmentId: uuid2.optional()
1616
+ }), read, async ({ documentId, attachmentId }) => {
1617
+ const response = await required2(client.listAttachments, "check_document_attachments")(documentId);
1618
+ const items = response.items.map((item) => ({ ...item, documentId }));
1619
+ if (!attachmentId)
1620
+ return { items };
1621
+ const attachment = items.find((item) => item.id === attachmentId);
1622
+ if (!attachment)
1623
+ throw new HiaiDocsError("Attachment not found in this document.", 404, null, "ATTACHMENT_NOT_FOUND");
1624
+ const verification = await required2(client.verifyAttachment, "check_document_attachments")(attachment);
1625
+ return { items, verifiedAttachmentId: attachmentId, verification };
1626
+ });
1462
1627
  register("delete_document", "Move one document to trash without purging content or versions. Use batch_documents(action=trash) for multiple explicit IDs. Requires write access and an explicit delete request; permanently_delete_document is a separate irreversible action.", z4.strictObject({ id: uuid2 }), destructive, async ({ id }) => {
1463
1628
  await required2(client.deleteDocument, "delete_document")(id);
1464
1629
  return { id, deleted: true };
@@ -1687,7 +1852,7 @@ function registerDocsmintMcpCapabilities(server, client, workspaceRouting, decor
1687
1852
  registerPromptsAndResources(server, client);
1688
1853
  }
1689
1854
  function createDocsmintMcpServer(options = {}) {
1690
- const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.5" });
1855
+ const server = new DocsMintMcpServer({ name: "docsmint", version: "2.2.1" });
1691
1856
  const client = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
1692
1857
  registerDocsmintMcpCapabilities(server, client, options.workspaceRouting, options.decorateResult);
1693
1858
  return server;