@hiai-gg/docsmint 2.1.9 → 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,
@@ -515,6 +516,21 @@ var pendingAttachmentUploads = pgTable("pending_attachment_uploads", {
515
516
  index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
516
517
  check("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
517
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
+ ]);
518
534
  var attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
519
535
  id: uuid("id").primaryKey().defaultRandom(),
520
536
  sourceKind: text("source_kind").notNull(),
@@ -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,
@@ -515,6 +516,21 @@ var pendingAttachmentUploads = pgTable("pending_attachment_uploads", {
515
516
  index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
516
517
  check("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
517
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
+ ]);
518
534
  var attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
519
535
  id: uuid("id").primaryKey().defaultRandom(),
520
536
  sourceKind: text("source_kind").notNull(),
@@ -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,
@@ -515,6 +516,21 @@ var pendingAttachmentUploads = pgTable("pending_attachment_uploads", {
515
516
  index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
516
517
  check("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
517
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
+ ]);
518
534
  var attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
519
535
  id: uuid("id").primaryKey().defaultRandom(),
520
536
  sourceKind: text("source_kind").notNull(),
package/dist/client.js CHANGED
@@ -492,8 +492,12 @@ export class DocsClient {
492
492
  headers.set("Cookie", requestContext.cookie);
493
493
  if (requestContext?.requestId)
494
494
  headers.set("X-Request-Id", requestContext.requestId);
495
- if (requestContext?.idempotencyKey)
495
+ if (requestContext?.idempotencyKey === null) {
496
+ headers.delete("Idempotency-Key");
497
+ }
498
+ else if (requestContext?.idempotencyKey) {
496
499
  headers.set("Idempotency-Key", requestContext.idempotencyKey);
500
+ }
497
501
  // Document creation supports replay on the server. Generate once before
498
502
  // the retry loop so a lost response cannot create a second document.
499
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,
@@ -38024,6 +38025,21 @@ var pendingAttachmentUploads = pgTable("pending_attachment_uploads", {
38024
38025
  index("pending_attachment_uploads_cleanup_lease_idx").on(table.expiresAt, table.leaseExpiresAt, table.id),
38025
38026
  check("pending_attachment_uploads_quota_state_check", sql`${table.quotaState} IN ('not_required', 'reserve_pending', 'reserved', 'finalize_pending', 'committed')`)
38026
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
+ ]);
38027
38043
  var attachmentStorageCleanupOutbox = pgTable("attachment_storage_cleanup_outbox", {
38028
38044
  id: uuid("id").primaryKey().defaultRandom(),
38029
38045
  sourceKind: text("source_kind").notNull(),
@@ -40257,6 +40273,12 @@ async function withTenantDatabase(database, ctx, fn) {
40257
40273
  // ../../backend/src/lib/attachment-storage-cleanup.ts
40258
40274
  import { and, eq, inArray, sql as sql3 } from "drizzle-orm";
40259
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
+
40260
40282
  // ../../backend/src/lib/logger.ts
40261
40283
  var import_pino = __toESM(require_pino(), 1);
40262
40284
  function resolvePrettyTransport(environment, resolveModule) {
@@ -45933,6 +45955,7 @@ var envSchema = object({
45933
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"),
45934
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"),
45935
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"),
45936
45959
  DOCSMINT_WORKSPACE_ENABLED: string2().optional().default("false").transform((value) => value === "true"),
45937
45960
  DOCSMINT_WORKSPACE_ISSUER: string2().trim().optional(),
45938
45961
  DOCSMINT_WORKSPACE_SECRET: string2().optional(),
@@ -46202,7 +46225,9 @@ async function claimCleanupPage(leaseOwner, now, pageSize, quotaReleaseAvailable
46202
46225
  AND NOT EXISTS (
46203
46226
  SELECT 1
46204
46227
  FROM public.pending_attachment_uploads AS pending
46205
- 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))
46206
46231
  AND pending.lease_owner LIKE 'confirm:%'
46207
46232
  AND pending.lease_expires_at IS NOT NULL
46208
46233
  AND pending.lease_expires_at > ${nowTimestamp}
@@ -46244,7 +46269,7 @@ function quotaContext(row, signal) {
46244
46269
  workspaceId: row.workspace_id,
46245
46270
  actorUserId: row.actor_user_id,
46246
46271
  documentId: row.document_id,
46247
- storageKey: row.storage_key,
46272
+ storageKey: committedAttachmentKey(row.storage_key),
46248
46273
  proposedSize: row.size,
46249
46274
  requestId: row.id,
46250
46275
  idempotencyKey: row.quota_operation_key,
package/dist/mcp-cli.js CHANGED
@@ -604,8 +604,11 @@ class DocsClient {
604
604
  headers.set("Cookie", requestContext.cookie);
605
605
  if (requestContext?.requestId)
606
606
  headers.set("X-Request-Id", requestContext.requestId);
607
- if (requestContext?.idempotencyKey)
607
+ if (requestContext?.idempotencyKey === null) {
608
+ headers.delete("Idempotency-Key");
609
+ } else if (requestContext?.idempotencyKey) {
608
610
  headers.set("Idempotency-Key", requestContext.idempotencyKey);
611
+ }
609
612
  if (method === "POST" && path === "/api/documents" && !headers.has("Idempotency-Key")) {
610
613
  headers.set("Idempotency-Key", crypto.randomUUID());
611
614
  }
@@ -1046,6 +1049,7 @@ var operationOutputSchemas = {
1046
1049
  var variant = (operation, result) => z.object({ operation: z.literal(operation), result });
1047
1050
  var attachment = z.object({
1048
1051
  id: z.string().uuid(),
1052
+ documentId: z.string().uuid().optional(),
1049
1053
  filename: z.string(),
1050
1054
  mimeType: z.string(),
1051
1055
  size: z.number().int().nonnegative(),
@@ -1075,7 +1079,12 @@ var singleToolOutputSchemas = {
1075
1079
  upload_document_image: attachment,
1076
1080
  check_document_attachments: z.strictObject({
1077
1081
  items: z.array(attachment),
1078
- verifiedAttachmentId: z.string().uuid().optional()
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()
1079
1088
  }),
1080
1089
  save_document: z.union([
1081
1090
  variant("create", operationOutputSchemas.create_document),
@@ -1144,8 +1153,55 @@ var toolOutputSchemas = {
1144
1153
  // ../mcp-server/src/compact.ts
1145
1154
  import { z as z4 } from "zod";
1146
1155
 
1147
- // ../mcp-server/src/batch-workspace.ts
1148
- 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
+ }
1149
1205
 
1150
1206
  // ../mcp-server/src/client.ts
1151
1207
  var DEFAULT_BASE_URL = "http://localhost:50700";
@@ -1185,39 +1241,44 @@ function sanitizeMcpRequestContext(context) {
1185
1241
  function createMcpDocsClient(docsClient, requestContext) {
1186
1242
  const context = sanitizeMcpRequestContext(requestContext);
1187
1243
  return {
1188
- uploadDocumentImage: async (id, filename, mimeType, bytes) => {
1189
- const descriptor = { filename, contentType: mimeType, size: bytes.byteLength };
1190
- const upload = await docsClient.presignAttachment(id, descriptor, context);
1191
- const response = await fetch(upload.url, {
1192
- method: "PUT",
1193
- body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
1194
- redirect: "error",
1195
- signal: context?.signal
1196
- }).catch(() => {
1197
- throw new Error("Could not send image bytes to DocsMint storage.");
1198
- });
1199
- await response.body?.cancel();
1200
- if (!response.ok)
1201
- throw new Error(`DocsMint storage rejected the image (${response.status}).`);
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
+ }
1202
1267
  return docsClient.confirmAttachment(id, {
1203
1268
  ...descriptor,
1204
1269
  key: upload.key,
1205
1270
  uploadToken: upload.uploadToken,
1206
1271
  quotaReservationId: upload.quotaReservationId
1207
- }, context);
1272
+ }, uploadContext);
1208
1273
  },
1209
1274
  listAttachments: (id) => docsClient.listAttachments(id, context),
1210
- verifyAttachment: async (id) => {
1211
- const response = await docsClient.fetchAttachment(id, context);
1212
- const reader = response.body?.getReader();
1213
- if (!reader)
1214
- throw new Error("The attachment response has no body.");
1215
- try {
1216
- if (!(await reader.read()).value?.byteLength)
1217
- throw new Error("The attachment is empty.");
1218
- } finally {
1219
- await reader.cancel();
1220
- }
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);
1221
1282
  },
1222
1283
  getFolder: (id) => docsClient.getFolder(id, context),
1223
1284
  createTag: (input) => docsClient.createTag(input, context),
@@ -1275,6 +1336,9 @@ var client = new Proxy({}, {
1275
1336
  }
1276
1337
  });
1277
1338
 
1339
+ // ../mcp-server/src/batch-workspace.ts
1340
+ import { z as z3 } from "zod";
1341
+
1278
1342
  // ../mcp-server/src/client-routing-schema.ts
1279
1343
  import { z as z2 } from "zod";
1280
1344
  function canonical(value) {
@@ -1536,26 +1600,29 @@ function registerCompactCapabilities(server, client, wrap) {
1536
1600
  documentId: uuid2,
1537
1601
  filename: z4.string().min(1).max(255).regex(/^[^/\\\u0000-\u001f\u007f]+$/).describe("Image file name with extension and without path segments."),
1538
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."),
1539
1604
  contentBase64: z4.base64().min(4).max(Math.ceil(maxImageBytes / 3) * 4).describe("Base64 file bytes without a data: prefix.")
1540
- }), write, async ({ documentId, filename, mimeType, contentBase64 }) => {
1605
+ }), write, async ({ documentId, filename, mimeType, contentBase64, operationId }) => {
1541
1606
  const bytes = Buffer.from(contentBase64, "base64");
1542
1607
  if (!bytes.length || bytes.length > maxImageBytes)
1543
- throw new Error("Image must be between 1 byte and 2 MiB.");
1608
+ throw new HiaiDocsError("Image must be between 1 byte and 2 MiB.", 413, null, "IMAGE_TOO_LARGE");
1544
1609
  if (!matchesImageType(bytes, mimeType))
1545
- throw new Error("Image bytes do not match the declared MIME type.");
1546
- return required2(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes);
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 };
1547
1612
  });
1548
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({
1549
1614
  documentId: uuid2,
1550
1615
  attachmentId: uuid2.optional()
1551
1616
  }), read, async ({ documentId, attachmentId }) => {
1552
- const { items } = await required2(client.listAttachments, "check_document_attachments")(documentId);
1617
+ const response = await required2(client.listAttachments, "check_document_attachments")(documentId);
1618
+ const items = response.items.map((item) => ({ ...item, documentId }));
1553
1619
  if (!attachmentId)
1554
1620
  return { items };
1555
- if (!items.some((item) => item.id === attachmentId))
1556
- throw new Error("Attachment not found in this document.");
1557
- await required2(client.verifyAttachment, "check_document_attachments")(attachmentId);
1558
- return { items, verifiedAttachmentId: attachmentId };
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 };
1559
1626
  });
1560
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 }) => {
1561
1628
  await required2(client.deleteDocument, "delete_document")(id);
@@ -1785,7 +1852,7 @@ function registerDocsmintMcpCapabilities(server, client, workspaceRouting, decor
1785
1852
  registerPromptsAndResources(server, client);
1786
1853
  }
1787
1854
  function createDocsmintMcpServer(options = {}) {
1788
- const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.9" });
1855
+ const server = new DocsMintMcpServer({ name: "docsmint", version: "2.2.1" });
1789
1856
  const client = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
1790
1857
  registerDocsmintMcpCapabilities(server, client, options.workspaceRouting, options.decorateResult);
1791
1858
  return server;
@@ -599,8 +599,11 @@ class DocsClient {
599
599
  headers.set("Cookie", requestContext.cookie);
600
600
  if (requestContext?.requestId)
601
601
  headers.set("X-Request-Id", requestContext.requestId);
602
- if (requestContext?.idempotencyKey)
602
+ if (requestContext?.idempotencyKey === null) {
603
+ headers.delete("Idempotency-Key");
604
+ } else if (requestContext?.idempotencyKey) {
603
605
  headers.set("Idempotency-Key", requestContext.idempotencyKey);
606
+ }
604
607
  if (method === "POST" && path === "/api/documents" && !headers.has("Idempotency-Key")) {
605
608
  headers.set("Idempotency-Key", crypto.randomUUID());
606
609
  }
@@ -1041,6 +1044,7 @@ var operationOutputSchemas = {
1041
1044
  var variant = (operation, result) => z.object({ operation: z.literal(operation), result });
1042
1045
  var attachment = z.object({
1043
1046
  id: z.string().uuid(),
1047
+ documentId: z.string().uuid().optional(),
1044
1048
  filename: z.string(),
1045
1049
  mimeType: z.string(),
1046
1050
  size: z.number().int().nonnegative(),
@@ -1070,7 +1074,12 @@ var singleToolOutputSchemas = {
1070
1074
  upload_document_image: attachment,
1071
1075
  check_document_attachments: z.strictObject({
1072
1076
  items: z.array(attachment),
1073
- verifiedAttachmentId: z.string().uuid().optional()
1077
+ verifiedAttachmentId: z.string().uuid().optional(),
1078
+ verification: z.strictObject({
1079
+ size: z.number().int().positive(),
1080
+ mimeType: z.string(),
1081
+ sha256: z.string().regex(/^[a-f0-9]{64}$/)
1082
+ }).optional()
1074
1083
  }),
1075
1084
  save_document: z.union([
1076
1085
  variant("create", operationOutputSchemas.create_document),
@@ -1142,8 +1151,55 @@ function createMcpScopedResult(toolName, input) {
1142
1151
  // ../mcp-server/src/compact.ts
1143
1152
  import { z as z4 } from "zod";
1144
1153
 
1145
- // ../mcp-server/src/batch-workspace.ts
1146
- import { z as z3 } from "zod";
1154
+ // ../mcp-server/src/client.ts
1155
+ import { createHash as createHash2 } from "crypto";
1156
+
1157
+ // ../mcp-server/src/attachment-verification.ts
1158
+ import { createHash } from "crypto";
1159
+ var MAX_VERIFIED_IMAGE_BYTES = 16 * 1024 * 1024;
1160
+ async function verifyAttachmentResponse(response, attachment) {
1161
+ const reader = response.body?.getReader();
1162
+ if (!reader)
1163
+ throw new Error("The attachment response has no body.");
1164
+ try {
1165
+ const mimeType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
1166
+ if (!response.ok || mimeType !== attachment.mimeType.toLowerCase())
1167
+ throw new Error("The stored attachment MIME type does not match its record.");
1168
+ if (!Number.isSafeInteger(attachment.size) || attachment.size <= 0 || attachment.size > MAX_VERIFIED_IMAGE_BYTES)
1169
+ throw new Error("The attachment exceeds the verification size limit.");
1170
+ const declaredLength = response.headers.get("content-length");
1171
+ if (declaredLength !== null && (!/^[0-9]+$/.test(declaredLength) || Number(declaredLength) !== attachment.size))
1172
+ throw new Error("The stored attachment length does not match its record.");
1173
+ const hash = createHash("sha256");
1174
+ let size = 0;
1175
+ let prefix = Buffer.alloc(0);
1176
+ for (;; ) {
1177
+ const { done, value } = await reader.read();
1178
+ if (done)
1179
+ break;
1180
+ size += value.byteLength;
1181
+ if (size > attachment.size || size > MAX_VERIFIED_IMAGE_BYTES)
1182
+ throw new Error("The attachment response exceeds its recorded size.");
1183
+ if (prefix.length < 12)
1184
+ prefix = Buffer.concat([
1185
+ prefix,
1186
+ Buffer.from(value.subarray(0, 12 - prefix.length))
1187
+ ]);
1188
+ hash.update(value);
1189
+ }
1190
+ if (size !== attachment.size)
1191
+ throw new Error("The attachment response is incomplete.");
1192
+ 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));
1193
+ if (!imageMatches)
1194
+ throw new Error("The attachment bytes do not match its image MIME type.");
1195
+ return { size, mimeType, sha256: hash.digest("hex") };
1196
+ } finally {
1197
+ await reader.cancel().catch(() => {
1198
+ return;
1199
+ });
1200
+ reader.releaseLock();
1201
+ }
1202
+ }
1147
1203
 
1148
1204
  // ../mcp-server/src/client.ts
1149
1205
  var DEFAULT_BASE_URL = "http://localhost:50700";
@@ -1183,39 +1239,44 @@ function sanitizeMcpRequestContext(context) {
1183
1239
  function createMcpDocsClient(docsClient, requestContext) {
1184
1240
  const context = sanitizeMcpRequestContext(requestContext);
1185
1241
  return {
1186
- uploadDocumentImage: async (id, filename, mimeType, bytes) => {
1187
- const descriptor = { filename, contentType: mimeType, size: bytes.byteLength };
1188
- const upload = await docsClient.presignAttachment(id, descriptor, context);
1189
- const response = await fetch(upload.url, {
1190
- method: "PUT",
1191
- body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
1192
- redirect: "error",
1193
- signal: context?.signal
1194
- }).catch(() => {
1195
- throw new Error("Could not send image bytes to DocsMint storage.");
1196
- });
1197
- await response.body?.cancel();
1198
- if (!response.ok)
1199
- throw new Error(`DocsMint storage rejected the image (${response.status}).`);
1242
+ uploadDocumentImage: async (id, filename, mimeType, bytes, operationId) => {
1243
+ const descriptor = {
1244
+ filename,
1245
+ contentType: mimeType,
1246
+ size: bytes.byteLength,
1247
+ ...operationId ? { sourceSha256: createHash2("sha256").update(bytes).digest("hex") } : {}
1248
+ };
1249
+ const signal = context?.signal ? AbortSignal.any([context.signal, AbortSignal.timeout(30000)]) : AbortSignal.timeout(30000);
1250
+ const uploadContext = { ...context, signal, idempotencyKey: operationId ?? null };
1251
+ const upload = await docsClient.presignAttachment(id, descriptor, uploadContext);
1252
+ if (!upload.alreadyConfirmed) {
1253
+ const response = await fetch(upload.url, {
1254
+ method: "PUT",
1255
+ body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
1256
+ redirect: "error",
1257
+ signal
1258
+ }).catch(() => {
1259
+ throw new HiaiDocsError("Could not send image bytes to DocsMint storage.", 502, null, "IMAGE_STORAGE_UNAVAILABLE");
1260
+ });
1261
+ await response.body?.cancel();
1262
+ if (!response.ok)
1263
+ throw new HiaiDocsError(`DocsMint storage rejected the image (${response.status}).`, response.status, null, "IMAGE_STORAGE_REJECTED");
1264
+ }
1200
1265
  return docsClient.confirmAttachment(id, {
1201
1266
  ...descriptor,
1202
1267
  key: upload.key,
1203
1268
  uploadToken: upload.uploadToken,
1204
1269
  quotaReservationId: upload.quotaReservationId
1205
- }, context);
1270
+ }, uploadContext);
1206
1271
  },
1207
1272
  listAttachments: (id) => docsClient.listAttachments(id, context),
1208
- verifyAttachment: async (id) => {
1209
- const response = await docsClient.fetchAttachment(id, context);
1210
- const reader = response.body?.getReader();
1211
- if (!reader)
1212
- throw new Error("The attachment response has no body.");
1213
- try {
1214
- if (!(await reader.read()).value?.byteLength)
1215
- throw new Error("The attachment is empty.");
1216
- } finally {
1217
- await reader.cancel();
1218
- }
1273
+ verifyAttachment: async (attachment) => {
1274
+ const signal = context?.signal ? AbortSignal.any([context.signal, AbortSignal.timeout(30000)]) : AbortSignal.timeout(30000);
1275
+ const response = await docsClient.fetchAttachment(attachment.id, {
1276
+ ...context,
1277
+ signal
1278
+ });
1279
+ return verifyAttachmentResponse(response, attachment);
1219
1280
  },
1220
1281
  getFolder: (id) => docsClient.getFolder(id, context),
1221
1282
  createTag: (input) => docsClient.createTag(input, context),
@@ -1273,6 +1334,9 @@ var client = new Proxy({}, {
1273
1334
  }
1274
1335
  });
1275
1336
 
1337
+ // ../mcp-server/src/batch-workspace.ts
1338
+ import { z as z3 } from "zod";
1339
+
1276
1340
  // ../mcp-server/src/client-routing-schema.ts
1277
1341
  import { z as z2 } from "zod";
1278
1342
  function canonical(value) {
@@ -1534,26 +1598,29 @@ function registerCompactCapabilities(server, client, wrap) {
1534
1598
  documentId: uuid2,
1535
1599
  filename: z4.string().min(1).max(255).regex(/^[^/\\\u0000-\u001f\u007f]+$/).describe("Image file name with extension and without path segments."),
1536
1600
  mimeType: z4.enum(["image/png", "image/jpeg", "image/webp"]).describe("MIME type of the source image."),
1601
+ 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."),
1537
1602
  contentBase64: z4.base64().min(4).max(Math.ceil(maxImageBytes / 3) * 4).describe("Base64 file bytes without a data: prefix.")
1538
- }), write, async ({ documentId, filename, mimeType, contentBase64 }) => {
1603
+ }), write, async ({ documentId, filename, mimeType, contentBase64, operationId }) => {
1539
1604
  const bytes = Buffer.from(contentBase64, "base64");
1540
1605
  if (!bytes.length || bytes.length > maxImageBytes)
1541
- throw new Error("Image must be between 1 byte and 2 MiB.");
1606
+ throw new HiaiDocsError("Image must be between 1 byte and 2 MiB.", 413, null, "IMAGE_TOO_LARGE");
1542
1607
  if (!matchesImageType(bytes, mimeType))
1543
- throw new Error("Image bytes do not match the declared MIME type.");
1544
- return required2(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes);
1608
+ throw new HiaiDocsError("Image bytes do not match the declared MIME type.", 415, null, "IMAGE_MIME_MISMATCH");
1609
+ return { ...await required2(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes, operationId), documentId };
1545
1610
  });
1546
1611
  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({
1547
1612
  documentId: uuid2,
1548
1613
  attachmentId: uuid2.optional()
1549
1614
  }), read, async ({ documentId, attachmentId }) => {
1550
- const { items } = await required2(client.listAttachments, "check_document_attachments")(documentId);
1615
+ const response = await required2(client.listAttachments, "check_document_attachments")(documentId);
1616
+ const items = response.items.map((item) => ({ ...item, documentId }));
1551
1617
  if (!attachmentId)
1552
1618
  return { items };
1553
- if (!items.some((item) => item.id === attachmentId))
1554
- throw new Error("Attachment not found in this document.");
1555
- await required2(client.verifyAttachment, "check_document_attachments")(attachmentId);
1556
- return { items, verifiedAttachmentId: attachmentId };
1619
+ const attachment = items.find((item) => item.id === attachmentId);
1620
+ if (!attachment)
1621
+ throw new HiaiDocsError("Attachment not found in this document.", 404, null, "ATTACHMENT_NOT_FOUND");
1622
+ const verification = await required2(client.verifyAttachment, "check_document_attachments")(attachment);
1623
+ return { items, verifiedAttachmentId: attachmentId, verification };
1557
1624
  });
1558
1625
  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 }) => {
1559
1626
  await required2(client.deleteDocument, "delete_document")(id);
@@ -1987,7 +2054,7 @@ function registerDocsmintMcpCapabilities(server, client, workspaceRouting, decor
1987
2054
  registerPromptsAndResources(server, client);
1988
2055
  }
1989
2056
  function createDocsmintMcpServer(options = {}) {
1990
- const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.9" });
2057
+ const server = new DocsMintMcpServer({ name: "docsmint", version: "2.2.1" });
1991
2058
  const client = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
1992
2059
  registerDocsmintMcpCapabilities(server, client, options.workspaceRouting, options.decorateResult);
1993
2060
  return server;