@qoder-ai/qmind-cli 4.3.0 → 5.1.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,4 +1,175 @@
1
1
  import { z } from "zod";
2
+ //#region ../sdk/src/errors.ts
3
+ var QMindError = class extends Error {
4
+ code;
5
+ details;
6
+ dataSourceAppPermission;
7
+ operation;
8
+ rawBody;
9
+ requestId;
10
+ status;
11
+ upstreamCode;
12
+ constructor(code, message, options = {}) {
13
+ super(message, { cause: options.cause });
14
+ this.name = "QMindError";
15
+ this.code = code;
16
+ this.details = options.details;
17
+ this.dataSourceAppPermission = options.dataSourceAppPermission;
18
+ this.operation = options.operation;
19
+ this.rawBody = options.rawBody;
20
+ this.requestId = options.requestId;
21
+ this.status = options.status;
22
+ this.upstreamCode = options.upstreamCode;
23
+ }
24
+ };
25
+ const scopeList = z.array(z.string().max(128).regex(/^[a-zA-Z][a-zA-Z0-9_]*(?:[.:][a-zA-Z0-9_]+)+$/)).min(1).max(16).refine((scopes) => new Set(scopes).size === scopes.length);
26
+ const permissionCapabilities = [
27
+ "wiki_spaces",
28
+ "wiki_children",
29
+ "wiki_node",
30
+ "drive_listing",
31
+ "document_read",
32
+ "document_export",
33
+ "file_download",
34
+ "document_media",
35
+ "whiteboard_image",
36
+ "embedded_sheet",
37
+ "embedded_bitable_fields",
38
+ "embedded_bitable_records",
39
+ "linked_document_titles",
40
+ "mentioned_user_lookup",
41
+ "mentioned_user_names"
42
+ ];
43
+ function permissionEntries(entry) {
44
+ return z.array(z.unknown()).max(16).transform((values) => {
45
+ const seen = /* @__PURE__ */ new Set();
46
+ return values.flatMap((value) => {
47
+ const parsed = entry.safeParse(value);
48
+ if (!parsed.success || seen.has(parsed.data.capability)) return [];
49
+ seen.add(parsed.data.capability);
50
+ return [parsed.data];
51
+ });
52
+ });
53
+ }
54
+ const permissionGroups = permissionEntries(z.object({
55
+ capability: z.enum(permissionCapabilities),
56
+ anyOfScopes: scopeList
57
+ })).optional().catch(void 0);
58
+ const permissionGrants = permissionEntries(z.object({
59
+ capability: z.enum(permissionCapabilities),
60
+ grantedScopes: scopeList
61
+ })).optional().catch(void 0);
62
+ const dataSourceAppPermissionSchema = z.object({
63
+ requiredScopes: scopeList,
64
+ anyOf: z.boolean(),
65
+ permissionRequirements: permissionGroups,
66
+ permissionWarnings: permissionGroups,
67
+ permissionGrants
68
+ });
69
+ /** 只提取应用权限标识与匹配方式。 */
70
+ function readQMindDataSourceAppPermission(code, details) {
71
+ if (code !== "DataSourceAppPermissionRequired") return void 0;
72
+ const parsed = dataSourceAppPermissionSchema.safeParse(details);
73
+ return parsed.success ? parsed.data : void 0;
74
+ }
75
+ const dataSourceConfigurationSchema = z.object({
76
+ name: z.string().min(1).max(255),
77
+ provider: z.enum([
78
+ "feishu",
79
+ "feishu_drive",
80
+ "dingtalk",
81
+ "dingtalk_mcp"
82
+ ]),
83
+ resourceIds: z.array(z.string().min(1)).max(1e3).default([]),
84
+ settings: z.record(z.string(), z.unknown()).default({}),
85
+ schedule: z.string().default(""),
86
+ paused: z.boolean().default(false),
87
+ syncDeletions: z.boolean().default(false)
88
+ });
89
+ const dataSourceSchema = z.object({
90
+ id: z.string().min(1),
91
+ configuration: dataSourceConfigurationSchema,
92
+ credentialsConfigured: z.boolean().default(false),
93
+ lastSyncAt: z.string().nullish()
94
+ });
95
+ const dataSourceResourceSchema = z.object({
96
+ externalId: z.string().min(1),
97
+ name: z.string(),
98
+ type: z.string(),
99
+ url: z.string().default(""),
100
+ parentId: z.string().default(""),
101
+ hasChildren: z.boolean().default(false)
102
+ });
103
+ const dataSourceRunSchema = z.object({
104
+ id: z.string().min(1),
105
+ status: z.enum([
106
+ "queued",
107
+ "running",
108
+ "success",
109
+ "partial",
110
+ "failed",
111
+ "canceled"
112
+ ]),
113
+ startedAt: z.string().nullish(),
114
+ finishedAt: z.string().nullish(),
115
+ total: z.number().int().default(0),
116
+ created: z.number().int().default(0),
117
+ updated: z.number().int().default(0),
118
+ deleted: z.number().int().default(0),
119
+ skipped: z.number().int().default(0),
120
+ failed: z.number().int().default(0),
121
+ errorCode: z.string().default(""),
122
+ issuesTruncated: z.boolean().default(false),
123
+ issues: z.array(z.object({
124
+ externalId: z.string(),
125
+ resourceId: z.string(),
126
+ code: z.string(),
127
+ retryState: z.string()
128
+ })).default([])
129
+ });
130
+ const dataSourceListSchema = z.object({
131
+ dataSources: z.array(dataSourceSchema).default([]),
132
+ managedDataSources: z.array(dataSourceSchema).default([]),
133
+ nextAfterId: z.string().default(""),
134
+ dingtalkDocServerId: z.string().nullish().transform((id) => id || void 0),
135
+ availableProviders: z.array(z.string()).default([])
136
+ }).transform(({ managedDataSources, dataSources, ...page }) => ({
137
+ ...page,
138
+ dataSources: managedDataSources.length ? [...dataSources, ...managedDataSources].sort((a, b) => a.id.localeCompare(b.id, "en")) : dataSources
139
+ }));
140
+ const dataSourceRunsSchema = z.object({
141
+ runs: z.array(dataSourceRunSchema).default([]),
142
+ nextBeforeStartedAt: z.string().nullish(),
143
+ nextBeforeId: z.string().default("")
144
+ });
145
+ const dataSourcePreviewSchema = z.object({
146
+ importCheck: z.enum([
147
+ "readable",
148
+ "empty",
149
+ "unverified"
150
+ ]).optional().catch(void 0),
151
+ resources: z.array(dataSourceResourceSchema).default([]),
152
+ permissionWarnings: permissionGroups,
153
+ permissionGrants
154
+ });
155
+ //#endregion
156
+ //#region ../sdk/src/wiki.ts
157
+ /** 保留 HTTP 错误证据,并以有界状态供宿主选择本地化提示。 */
158
+ var QMindWikiReadError = class extends QMindError {
159
+ wikiState;
160
+ constructor(wikiState, error) {
161
+ super(error.code, error.message, {
162
+ cause: error,
163
+ ...error.operation === void 0 ? {} : { operation: error.operation },
164
+ ...error.status === void 0 ? {} : { status: error.status },
165
+ ...error.upstreamCode === void 0 ? {} : { upstreamCode: error.upstreamCode },
166
+ ...error.requestId === void 0 ? {} : { requestId: error.requestId },
167
+ details: error.details
168
+ });
169
+ this.wikiState = wikiState;
170
+ }
171
+ };
172
+ //#endregion
2
173
  //#region ../sdk/src/imports.ts
3
174
  const qmindFullSiteURLImportPageLimit = 2e3;
4
175
  const runStatuses = Object.freeze({
@@ -119,7 +290,7 @@ function normalizeQMindTaskRunStatus(status) {
119
290
  }
120
291
  //#endregion
121
292
  //#region ../sdk/src/schemas.ts
122
- function isRecord(value) {
293
+ function isRecord$1(value) {
123
294
  return typeof value === "object" && value !== null && !Array.isArray(value);
124
295
  }
125
296
  const wirePageNumberSchema = z.number().int().nonnegative().optional();
@@ -208,7 +379,7 @@ const sourcePageInfoSchema = z.object({
208
379
  prevPage: wirePageNumberSchema,
209
380
  totalSize: z.number().int().nonnegative().optional()
210
381
  });
211
- const sourceExternalBindingSchema = z.preprocess((value) => isRecord(value) ? {
382
+ const sourceExternalBindingSchema = z.preprocess((value) => isRecord$1(value) ? {
212
383
  ...value,
213
384
  bindingId: value.bindingId ?? value.binding_id,
214
385
  isRoot: value.isRoot ?? value.is_root
@@ -217,6 +388,15 @@ const sourceExternalBindingSchema = z.preprocess((value) => isRecord(value) ? {
217
388
  isRoot: z.boolean().default(false),
218
389
  provider: z.string().default("")
219
390
  }));
391
+ const sourceDataSourceSchema = z.object({
392
+ dataSourceId: z.string(),
393
+ provider: z.string(),
394
+ rootSourceId: z.string(),
395
+ isRoot: z.boolean(),
396
+ readOnly: z.boolean(),
397
+ canDelete: z.boolean(),
398
+ originalFileUnavailable: z.boolean()
399
+ });
220
400
  const sourceLearningSchema = z.object({
221
401
  status: z.string().default("unknown"),
222
402
  errorCode: z.string().default(""),
@@ -238,6 +418,7 @@ const sourceSchema = z.object({
238
418
  errorCode: z.string().default(""),
239
419
  errorMessage: z.string().default(""),
240
420
  externalBinding: sourceExternalBindingSchema.optional(),
421
+ dataSource: sourceDataSourceSchema.optional(),
241
422
  filename: z.string().optional(),
242
423
  hasChildren: z.boolean().optional(),
243
424
  id: z.string().min(1),
@@ -265,33 +446,6 @@ const sourceListSchema = z.object({
265
446
  sources: z.array(sourceSchema).nullish().transform((sources) => sources ?? []),
266
447
  totalSize: z.number().int().nonnegative().optional()
267
448
  });
268
- const sourceTreeNodeSchema = z.lazy(() => z.preprocess((value) => isRecord(value) ? {
269
- ...value,
270
- updatedAt: value.updatedAt ?? value.updated_at
271
- } : value, z.object({
272
- learning: sourceLearningSchema.optional(),
273
- learningStatus: z.string().optional(),
274
- learningErrorCode: z.string().optional(),
275
- metadata: z.record(z.string(), z.unknown()).nullable().optional(),
276
- externalBinding: sourceExternalBindingSchema.optional(),
277
- originUrl: z.string().optional(),
278
- isEmailFolder: z.boolean().optional(),
279
- isEmailAggregateMember: z.boolean().optional(),
280
- isExternalSource: z.boolean().optional(),
281
- files: z.array(sourceTreeNodeSchema).default([]),
282
- hasChildren: z.boolean().optional(),
283
- id: z.string().min(1),
284
- name: z.string().default(""),
285
- path: z.string().default(""),
286
- sourceType: z.string().default(""),
287
- status: z.string().default(""),
288
- type: z.enum(["file", "directory"]),
289
- updatedAt: timestampSchema.optional()
290
- })));
291
- const sourceTreeSchema = z.object({
292
- totalSize: z.number().int().nonnegative().default(0),
293
- tree: z.array(sourceTreeNodeSchema)
294
- });
295
449
  const sourceContentSchema = z.object({
296
450
  content: z.string(),
297
451
  contentType: z.string().default("text/markdown"),
@@ -304,7 +458,7 @@ const wireInt64Schema = z.union([z.number(), z.string()]).nullish().transform((v
304
458
  return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;
305
459
  });
306
460
  const sourceUploadExtensionSchema = z.string().regex(/^\.[a-z0-9]+$/);
307
- const sourceUploadMethodSchema = z.preprocess((value) => isRecord(value) ? {
461
+ const sourceUploadMethodSchema = z.preprocess((value) => isRecord$1(value) ? {
308
462
  ...value,
309
463
  maxSizeBytes: value.maxSizeBytes ?? value.max_size_bytes,
310
464
  supportedExtensions: value.supportedExtensions ?? value.supported_extensions
@@ -314,7 +468,7 @@ const sourceUploadMethodSchema = z.preprocess((value) => isRecord(value) ? {
314
468
  method: z.string().min(1),
315
469
  supportedExtensions: z.array(sourceUploadExtensionSchema).default([])
316
470
  }));
317
- const sourceUploadFileTypeSchema = z.preprocess((value) => isRecord(value) ? {
471
+ const sourceUploadFileTypeSchema = z.preprocess((value) => isRecord$1(value) ? {
318
472
  ...value,
319
473
  displayName: value.displayName ?? value.display_name,
320
474
  mimeTypes: value.mimeTypes ?? value.mime_types,
@@ -333,7 +487,7 @@ const sourceQuotaSchema = z.object({
333
487
  planTier: z.string().min(1),
334
488
  quotaEnabled: z.boolean()
335
489
  }).refine((value) => !value.quotaEnabled || value.limitBytes > 0);
336
- const sourceUploadCapabilitiesSchema = z.preprocess((value) => isRecord(value) ? {
490
+ const sourceUploadCapabilitiesSchema = z.preprocess((value) => isRecord$1(value) ? {
337
491
  ...value,
338
492
  fileTypes: value.fileTypes ?? value.file_types,
339
493
  uploadMethods: value.uploadMethods ?? value.upload_methods
@@ -351,16 +505,16 @@ const downloadOriginalActionAccessSchema = z.discriminatedUnion("state", [z.obje
351
505
  state: z.literal("denied")
352
506
  })]);
353
507
  const sourceActionAccessSchema = z.preprocess((value) => {
354
- if (!isRecord(value) || !Array.isArray(value.actions)) return value;
508
+ if (!isRecord$1(value) || !Array.isArray(value.actions)) return value;
355
509
  return {
356
510
  ...value,
357
511
  actions: value.actions.filter((action) => {
358
- if (!isRecord(action)) return true;
512
+ if (!isRecord$1(action)) return true;
359
513
  return typeof action.action !== "string" || action.action.length === 0 || action.action === "download_original";
360
514
  })
361
515
  };
362
516
  }, z.object({ actions: z.array(downloadOriginalActionAccessSchema).length(1) }));
363
- const sourceRawContentSchema = z.preprocess((value) => isRecord(value) ? {
517
+ const sourceRawContentSchema = z.preprocess((value) => isRecord$1(value) ? {
364
518
  ...value,
365
519
  contentType: value.contentType ?? value.content_type,
366
520
  sizeBytes: value.sizeBytes ?? value.size_bytes,
@@ -373,7 +527,7 @@ const sourceRawContentSchema = z.preprocess((value) => isRecord(value) ? {
373
527
  sourceFormat: z.string().default(""),
374
528
  sourceId: z.string().default("")
375
529
  }));
376
- const sourcePreviewSchema = z.preprocess((value) => isRecord(value) ? {
530
+ const sourcePreviewSchema = z.preprocess((value) => isRecord$1(value) ? {
377
531
  ...value,
378
532
  contentType: value.contentType ?? value.content_type,
379
533
  expiresAt: value.expiresAt ?? value.expires_at,
@@ -395,7 +549,7 @@ const webOfficeTokenFields = {
395
549
  tokenVersion: officeTokenIntegerSchema
396
550
  };
397
551
  function webOfficeTokenAliases(value) {
398
- return isRecord(value) ? {
552
+ return isRecord$1(value) ? {
399
553
  ...value,
400
554
  accessToken: value.accessToken ?? value.access_token,
401
555
  accessTokenExpiresAt: value.accessTokenExpiresAt ?? value.access_token_expires_at,
@@ -405,7 +559,7 @@ function webOfficeTokenAliases(value) {
405
559
  }
406
560
  const sourceWebOfficeSessionSchema = z.preprocess((value) => {
407
561
  const aliased = webOfficeTokenAliases(value);
408
- return isRecord(aliased) ? {
562
+ return isRecord$1(aliased) ? {
409
563
  ...aliased,
410
564
  readOnly: aliased.readOnly ?? aliased.readonly,
411
565
  sessionId: aliased.sessionId ?? aliased.session_id,
@@ -423,7 +577,7 @@ const sourceWebOfficeSessionSchema = z.preprocess((value) => {
423
577
  webOfficeUrl: httpsUrlSchema
424
578
  }));
425
579
  const sourceWebOfficeTokenSchema = z.preprocess(webOfficeTokenAliases, z.object(webOfficeTokenFields));
426
- const sourceChildrenCountsSchema = z.object({ counts: z.array(z.preprocess((value) => isRecord(value) ? {
580
+ const sourceChildrenCountsSchema = z.object({ counts: z.array(z.preprocess((value) => isRecord$1(value) ? {
427
581
  ...value,
428
582
  parentId: value.parentId ?? value.parent_id
429
583
  } : value, z.object({
@@ -431,7 +585,7 @@ const sourceChildrenCountsSchema = z.object({ counts: z.array(z.preprocess((valu
431
585
  parentId: z.string().default("")
432
586
  }))).nullish().transform((counts) => counts ?? []) }).transform((value) => value.counts);
433
587
  const importProvidersSchema = z.object({ sources: z.array(z.object({ provider: z.string().default("") })).nullish().transform((sources) => sources ?? []) }).transform((value) => value.sources.filter((source) => source.provider.length > 0));
434
- const aliDingImportRunSchema = z.preprocess((value) => isRecord(value) ? {
588
+ const aliDingImportRunSchema = z.preprocess((value) => isRecord$1(value) ? {
435
589
  ...value,
436
590
  bindingId: value.bindingId ?? value.binding_id,
437
591
  canonicalUrl: value.canonicalUrl ?? value.canonical_url,
@@ -500,7 +654,7 @@ const aliDingImportRunSchema = z.preprocess((value) => isRecord(value) ? {
500
654
  status: normalizeQMindAliDingImportRunStatus(value.status),
501
655
  ...value.updatedAt === void 0 ? {} : { updatedAt: value.updatedAt }
502
656
  }));
503
- const aliDingImportRunItemSchema = z.preprocess((value) => isRecord(value) ? {
657
+ const aliDingImportRunItemSchema = z.preprocess((value) => isRecord$1(value) ? {
504
658
  ...value,
505
659
  contentStatus: value.contentStatus ?? value.content_status,
506
660
  descendantsStatus: value.descendantsStatus ?? value.descendants_status,
@@ -542,7 +696,7 @@ const aliDingImportRunItemSchema = z.preprocess((value) => isRecord(value) ? {
542
696
  status: normalizeQMindAliDingImportItemStatus(value.status),
543
697
  ...value.updatedAt === void 0 ? {} : { updatedAt: value.updatedAt }
544
698
  }));
545
- const aliDingImportPageInfoSchema = z.preprocess((value) => isRecord(value) ? {
699
+ const aliDingImportPageInfoSchema = z.preprocess((value) => isRecord$1(value) ? {
546
700
  ...value,
547
701
  currentPage: value.currentPage ?? value.current_page,
548
702
  lastPage: value.lastPage ?? value.last_page,
@@ -584,7 +738,7 @@ const imageUrlsSchema = z.object({
584
738
  expiresAt: z.string().optional(),
585
739
  urls: z.record(z.string(), httpsUrlSchema)
586
740
  });
587
- const notebookCitationSchema = z.preprocess((value) => isRecord(value) ? {
741
+ const notebookCitationSchema = z.preprocess((value) => isRecord$1(value) ? {
588
742
  ...value,
589
743
  chunkId: value.chunkId ?? value.chunk_id,
590
744
  chunkIndex: value.chunkIndex ?? value.chunk_index,
@@ -595,7 +749,7 @@ const notebookCitationSchema = z.preprocess((value) => isRecord(value) ? {
595
749
  } : value, z.object({
596
750
  chunkId: z.string().default(""),
597
751
  chunkIndex: z.number().int().nonnegative().default(0),
598
- metadata: z.record(z.string(), z.unknown()).optional(),
752
+ metadata: z.record(z.string(), z.unknown()).nullish().transform((value) => value ?? void 0),
599
753
  originUrl: z.string().optional(),
600
754
  snippet: z.string().default(""),
601
755
  sourceId: z.string().default(""),
@@ -618,7 +772,7 @@ const chatMessageSchema = z.object({
618
772
  updatedAt: timestampSchema.optional(),
619
773
  userId: z.string().optional()
620
774
  });
621
- const streamChatMessageSchema = z.preprocess((value) => isRecord(value) && Array.isArray(value.citations) ? {
775
+ const streamChatMessageSchema = z.preprocess((value) => isRecord$1(value) && Array.isArray(value.citations) ? {
622
776
  ...value,
623
777
  citations: value.citations.map((citation) => typeof citation === "string" ? { sourceId: citation } : citation)
624
778
  } : value, chatMessageSchema);
@@ -682,7 +836,7 @@ const notebookContextChunkSchema = z.object({
682
836
  chunkId: z.string().default(""),
683
837
  chunkIndex: z.number().int().nonnegative().default(0),
684
838
  content: z.string().default(""),
685
- metadata: z.record(z.string(), z.unknown()).optional(),
839
+ metadata: z.record(z.string(), z.unknown()).nullish().transform((value) => value ?? void 0),
686
840
  originUrl: z.string().optional(),
687
841
  score: z.number().finite().default(0),
688
842
  sourceId: z.string().default(""),
@@ -768,4 +922,480 @@ const retrieveNotebooksResultSchema = z.object({
768
922
  total: z.number().int().nonnegative().default(0)
769
923
  });
770
924
  //#endregion
771
- export { sourceWebOfficeSessionSchema as A, sourcePreviewSchema as C, sourceTreeSchema as D, sourceSchema as E, timestampSchema as F, voidResponseSchema as I, qmindFullSiteURLImportPageLimit as L, streamWireEventSchema as M, taskRunListSchema as N, sourceUploadCapabilitiesSchema as O, taskRunSchema as P, sourceListSchema as S, sourceRawContentSchema as T, sharedNotebookListSchema as _, chatMessageListSchema as a, sourceContentSchema as b, fullSiteURLImportConfirmationSchema as c, imageUrlsSchema as d, importProvidersSchema as f, retrieveResultSchema as g, retrieveNotebooksResultSchema as h, cancelQuestionResultSchema as i, sourceWebOfficeTokenSchema as j, sourceUploadTicketSchema as k, fullSiteURLImportDiscoverySchema as l, notebookSchema as m, aliDingImportRunSchema as n, chatSessionListSchema as o, notebookListSchema as p, batchDeleteResultSchema as r, chatSessionSchema as s, aliDingImportRunItemListSchema as t, imageUploadTicketSchema as u, sourceActionAccessSchema as v, sourceQuotaSchema as w, sourceImportResultsSchema as x, sourceChildrenCountsSchema as y };
925
+ //#region ../sdk/src/protocol.ts
926
+ function encodeId(value) {
927
+ return encodeURIComponent(value);
928
+ }
929
+ function appendQuery(path, entries) {
930
+ const query = new URLSearchParams();
931
+ for (const [key, value] of entries) if (value !== void 0 && value !== "") query.set(key, String(value));
932
+ const suffix = query.toString();
933
+ return suffix ? `${path}?${suffix}` : path;
934
+ }
935
+ function streamError(message, details) {
936
+ return new QMindError("STREAM_ERROR", message, {
937
+ ...details === void 0 ? {} : { details },
938
+ operation: "chat.stream"
939
+ });
940
+ }
941
+ function requiredString$1(value, field) {
942
+ if (value !== void 0 && value.length > 0) return value;
943
+ throw streamError(`stream event is missing ${field}`, { field });
944
+ }
945
+ function stringValue(value) {
946
+ return value ?? "";
947
+ }
948
+ function presentString(value, field) {
949
+ if (value !== void 0) return value;
950
+ throw streamError(`stream event is missing ${field}`, { field });
951
+ }
952
+ function decodeStreamEvent(body) {
953
+ const parsed = streamWireEventSchema.safeParse(body);
954
+ if (!parsed.success) throw streamError("stream event does not match the QMind contract", { issues: parsed.error.issues });
955
+ const event = parsed.data;
956
+ const eventType = event.eventType ?? event.event_type ?? event.type;
957
+ switch (eventType) {
958
+ case "message_start": return {
959
+ citations: event.citations ?? [],
960
+ reranked: event.reranked ?? false,
961
+ totalContextChunks: event.totalContextChunks ?? 0,
962
+ type: "messageStart",
963
+ ...event.assistantMessageId === void 0 ? {} : { assistantMessageId: event.assistantMessageId },
964
+ ...event.userMessage === void 0 ? {} : { userMessage: event.userMessage }
965
+ };
966
+ case "tool_call_start": return {
967
+ step: event.step ?? 0,
968
+ toolArguments: stringValue(event.toolArguments),
969
+ toolName: requiredString$1(event.toolName, "toolName"),
970
+ type: "toolCallStart",
971
+ ...event.toolDisplayName === void 0 ? {} : { toolDisplayName: event.toolDisplayName }
972
+ };
973
+ case "tool_call_result": return {
974
+ step: event.step ?? 0,
975
+ toolName: requiredString$1(event.toolName, "toolName"),
976
+ toolResult: stringValue(event.toolResult),
977
+ type: "toolCallResult",
978
+ ...event.toolDisplayName === void 0 ? {} : { toolDisplayName: event.toolDisplayName }
979
+ };
980
+ case "delta": return {
981
+ delta: presentString(event.delta, "delta"),
982
+ type: "delta"
983
+ };
984
+ case "batch_progress": return {
985
+ metadata: event.metadata ?? {},
986
+ type: "batchProgress"
987
+ };
988
+ case "heartbeat": return {
989
+ metadata: event.metadata ?? {},
990
+ type: "heartbeat"
991
+ };
992
+ case "cancel": return {
993
+ canceled: true,
994
+ type: "cancel",
995
+ ...event.cancelReason === void 0 ? {} : { cancelReason: event.cancelReason }
996
+ };
997
+ case "message_complete": return {
998
+ canceled: event.canceled ?? false,
999
+ citations: event.citations ?? [],
1000
+ metadata: event.metadata ?? {},
1001
+ promptContext: event.promptContext ?? "",
1002
+ reranked: event.reranked ?? false,
1003
+ totalContextChunks: event.totalContextChunks ?? 0,
1004
+ type: "messageComplete",
1005
+ ...event.assistantMessage === void 0 ? {} : { assistantMessage: event.assistantMessage },
1006
+ ...event.cancelReason === void 0 ? {} : { cancelReason: event.cancelReason }
1007
+ };
1008
+ case "error": return {
1009
+ message: requiredString$1(event.errorMessage ?? event.error, "errorMessage"),
1010
+ type: "error"
1011
+ };
1012
+ default: throw streamError("stream event has an unsupported event type", { eventType });
1013
+ }
1014
+ }
1015
+ function decodeStreamPayload(payload) {
1016
+ let value;
1017
+ try {
1018
+ value = JSON.parse(payload);
1019
+ } catch (cause) {
1020
+ throw streamError("stream event is not valid JSON", { cause });
1021
+ }
1022
+ return decodeStreamEvent(value);
1023
+ }
1024
+ const publicPrefix = "/qmind/api/v1";
1025
+ function pathBuilder(prefix) {
1026
+ return (...segments) => `${prefix}/${segments.map(encodeId).join("/")}`;
1027
+ }
1028
+ const qmindPath = pathBuilder(publicPrefix);
1029
+ const qmindRoutes = {
1030
+ featuredNotebookPath(notebookId) {
1031
+ return notebookId === void 0 ? qmindPath("featured-notebooks") : qmindPath("featured-notebooks", notebookId);
1032
+ },
1033
+ listFeaturedNotebooksPath(input) {
1034
+ return appendQuery(`${publicPrefix}/featured-notebooks`, [["page", input.page], ["page_size", input.pageSize]]);
1035
+ },
1036
+ listNotebooksPath(input) {
1037
+ return appendQuery(`${publicPrefix}/notebooks`, [
1038
+ ["page", input.page],
1039
+ ["page_size", input.pageSize],
1040
+ ["client", input.client],
1041
+ ["retrieval_eligible_only", input.retrievalEligibleOnly]
1042
+ ]);
1043
+ },
1044
+ listSharedNotebooksPath(input) {
1045
+ return appendQuery(`${publicPrefix}/notebooks/shared`, [
1046
+ ["page", input.page],
1047
+ ["page_size", input.pageSize],
1048
+ ["retrieval_eligible_only", input.retrievalEligibleOnly]
1049
+ ]);
1050
+ },
1051
+ notebookPath(notebookId) {
1052
+ return notebookId === void 0 ? qmindPath("notebooks") : qmindPath("notebooks", notebookId);
1053
+ },
1054
+ wikiBranchesPath(notebookId) {
1055
+ return qmindPath("notebooks", notebookId, "wiki-branches");
1056
+ }
1057
+ };
1058
+ //#endregion
1059
+ //#region ../sdk/src/execution.ts
1060
+ const credentialHeaders = /* @__PURE__ */ new Set([
1061
+ "authorization",
1062
+ "cookie",
1063
+ "proxy-authorization",
1064
+ "x-csrf-token",
1065
+ "x-xsrf-token"
1066
+ ]);
1067
+ function isRecord(value) {
1068
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1069
+ }
1070
+ function nestedRecord(value, key) {
1071
+ const nested = value[key];
1072
+ return isRecord(nested) ? nested : void 0;
1073
+ }
1074
+ function firstString(records, keys) {
1075
+ for (const record of records) {
1076
+ if (record === void 0) continue;
1077
+ for (const key of keys) {
1078
+ const value = record[key];
1079
+ if (typeof value === "string" && value.length > 0) return value;
1080
+ }
1081
+ }
1082
+ }
1083
+ function headerValue(headers, name) {
1084
+ const normalizedName = name.toLowerCase();
1085
+ for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === normalizedName && value.length > 0) return value;
1086
+ }
1087
+ function errorCodeForStatus(status) {
1088
+ if (status === 401) return "AUTH_REQUIRED";
1089
+ if (status === 403) return "FORBIDDEN";
1090
+ if (status === 404) return "NOT_FOUND";
1091
+ if (status === 409) return "CONFLICT";
1092
+ if (status === 429) return "RATE_LIMITED";
1093
+ if (status >= 400 && status < 500) return "INVALID_ARGUMENT";
1094
+ return "REMOTE_ERROR";
1095
+ }
1096
+ function httpError(operation, response) {
1097
+ const body = response.body;
1098
+ const root = isRecord(body) ? body : void 0;
1099
+ const error = root === void 0 ? void 0 : nestedRecord(root, "error");
1100
+ const details = root === void 0 ? void 0 : nestedRecord(root, "details");
1101
+ const records = [
1102
+ root,
1103
+ error,
1104
+ details
1105
+ ];
1106
+ const upstreamCode = firstString(records, [
1107
+ "errorCode",
1108
+ "error_code",
1109
+ "code"
1110
+ ]);
1111
+ const dataSourceAppPermission = response.status === 400 && operation.startsWith("dataSources.") ? readQMindDataSourceAppPermission(upstreamCode, details) : void 0;
1112
+ const requestId = firstString(records, ["requestId", "request_id"]) ?? headerValue(response.headers, "x-request-id") ?? headerValue(response.headers, "request-id");
1113
+ const message = firstString(records, [
1114
+ "message",
1115
+ "errorMessage",
1116
+ "error_message"
1117
+ ]) ?? `QMind request failed with HTTP ${response.status}`;
1118
+ const failure = new QMindError(errorCodeForStatus(response.status), message, {
1119
+ details: body,
1120
+ ...dataSourceAppPermission ? { dataSourceAppPermission } : {},
1121
+ operation,
1122
+ ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
1123
+ ...requestId === void 0 ? {} : { requestId },
1124
+ status: response.status,
1125
+ ...upstreamCode === void 0 ? {} : { upstreamCode }
1126
+ });
1127
+ const state = headerValue(response.headers, "x-wiki-state");
1128
+ if (operation.startsWith("wiki.") && (state === "expired" || state === "busy" || state === "invalid" || state === "limit" || state === "missing")) return new QMindWikiReadError(state, failure);
1129
+ return failure;
1130
+ }
1131
+ function isAbortLike(cause) {
1132
+ return isRecord(cause) && (cause.name === "AbortError" && typeof cause.name === "string" || cause.code === "ABORT_ERR");
1133
+ }
1134
+ function normalizeTransportError(cause, signal, context = {}) {
1135
+ if (cause instanceof QMindError) return cause;
1136
+ if (signal?.aborted || isAbortLike(cause)) return new QMindError("ABORTED", "QMind request was aborted", {
1137
+ ...context,
1138
+ cause
1139
+ });
1140
+ if (isRecord(cause) && cause.name === "TimeoutError") return new QMindError("TIMEOUT", "QMind request timed out", {
1141
+ ...context,
1142
+ cause
1143
+ });
1144
+ return new QMindError("NETWORK_ERROR", "QMind transport failed", {
1145
+ ...context,
1146
+ cause
1147
+ });
1148
+ }
1149
+ function requestWasAborted(request) {
1150
+ return request.signal?.aborted === true;
1151
+ }
1152
+ function assertWireRequestInvariant(request) {
1153
+ for (const [field, value] of [
1154
+ ["connectTimeoutMs", request.connectTimeoutMs],
1155
+ ["idleTimeoutMs", request.idleTimeoutMs],
1156
+ ["timeoutMs", request.timeoutMs]
1157
+ ]) if (!Number.isFinite(value ?? 1) || (value ?? 1) <= 0) throw new QMindError("INVALID_ARGUMENT", `${field} must be a positive finite number`, { details: { field } });
1158
+ if (request.destination.kind === "host") {
1159
+ if (!request.destination.path.startsWith("/") || request.destination.path.startsWith("//")) throw new QMindError("HOST_POLICY_ERROR", "host destination must be a root-relative path", { details: { destination: request.destination.kind } });
1160
+ return;
1161
+ }
1162
+ let url;
1163
+ try {
1164
+ url = new URL(request.destination.url);
1165
+ } catch (cause) {
1166
+ throw new QMindError("HOST_POLICY_ERROR", "signed destination must be a valid HTTPS URL", {
1167
+ cause,
1168
+ details: { destination: request.destination.kind }
1169
+ });
1170
+ }
1171
+ if (url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0) throw new QMindError("HOST_POLICY_ERROR", "signed destination must be credential-free HTTPS", { details: { destination: request.destination.kind } });
1172
+ for (const header of Object.keys(request.headers ?? {})) if (credentialHeaders.has(header.toLowerCase())) throw new QMindError("HOST_POLICY_ERROR", "host credentials must never be sent to a signed destination", { details: {
1173
+ destination: request.destination.kind,
1174
+ header: header.toLowerCase()
1175
+ } });
1176
+ }
1177
+ function assertCapability(capabilities, capability, operation) {
1178
+ if (capabilities[capability]) return;
1179
+ throw new QMindError("UNSUPPORTED_OPERATION", `${operation} is unavailable on this client`, {
1180
+ details: { capability },
1181
+ operation
1182
+ });
1183
+ }
1184
+ async function executeUnary(options) {
1185
+ const { capabilities, capability, operation, request, schema, transport } = options;
1186
+ assertCapability(capabilities, capability, operation);
1187
+ assertWireRequestInvariant(request);
1188
+ if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", { operation });
1189
+ let response;
1190
+ try {
1191
+ response = await transport.request(request);
1192
+ } catch (cause) {
1193
+ throw normalizeTransportError(cause, request.signal, { operation });
1194
+ }
1195
+ if (response.status < 200 || response.status >= 300) throw httpError(operation, response);
1196
+ const body = response.body;
1197
+ const parsed = schema.safeParse(body);
1198
+ if (!parsed.success) throw new QMindError("PROTOCOL_ERROR", "server response does not match the QMind contract", {
1199
+ details: { issues: parsed.error.issues },
1200
+ operation,
1201
+ ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
1202
+ status: response.status
1203
+ });
1204
+ return parsed.data;
1205
+ }
1206
+ function streamContractError(operation, message, details) {
1207
+ return new QMindError("STREAM_ERROR", message, {
1208
+ ...details === void 0 ? {} : { details },
1209
+ operation
1210
+ });
1211
+ }
1212
+ function streamFailureResponse(response) {
1213
+ return {
1214
+ body: response.body,
1215
+ headers: response.headers,
1216
+ ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
1217
+ status: response.status
1218
+ };
1219
+ }
1220
+ async function* executeStream(options) {
1221
+ const { capabilities, capability, operation, request, transport } = options;
1222
+ assertCapability(capabilities, capability, operation);
1223
+ assertWireRequestInvariant(request);
1224
+ if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", { operation });
1225
+ let response;
1226
+ try {
1227
+ response = await transport.stream(request);
1228
+ } catch (cause) {
1229
+ throw normalizeTransportError(cause, request.signal, { operation });
1230
+ }
1231
+ if (response.kind === "response") {
1232
+ if (response.status >= 200 && response.status < 300) throw streamContractError(operation, "stream handshake returned no event stream", { status: response.status });
1233
+ throw httpError(operation, streamFailureResponse(response));
1234
+ }
1235
+ if (response.status < 200 || response.status >= 300) throw streamContractError(operation, "stream handshake returned events for a failure status", { status: response.status });
1236
+ let doneMarkerSeen = false;
1237
+ let started = false;
1238
+ let terminal = false;
1239
+ try {
1240
+ for await (const payload of response.events) {
1241
+ if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", { operation });
1242
+ if (payload.trim() === "[DONE]") {
1243
+ if (doneMarkerSeen) throw streamContractError(operation, "stream emitted more than one [DONE] marker");
1244
+ doneMarkerSeen = true;
1245
+ continue;
1246
+ }
1247
+ if (doneMarkerSeen) throw streamContractError(operation, "stream emitted an event after [DONE]");
1248
+ if (terminal) throw streamContractError(operation, "stream emitted an event after messageComplete");
1249
+ const event = decodeStreamPayload(payload);
1250
+ if (event.type === "error") throw streamContractError(operation, event.message, { event });
1251
+ if (event.type === "messageStart") {
1252
+ if (started) throw streamContractError(operation, "stream emitted duplicate messageStart");
1253
+ started = true;
1254
+ } else if (!started) throw streamContractError(operation, "stream event arrived before messageStart", { eventType: event.type });
1255
+ if (event.type === "messageComplete") terminal = true;
1256
+ yield event;
1257
+ }
1258
+ } catch (cause) {
1259
+ throw normalizeTransportError(cause, request.signal, { operation });
1260
+ }
1261
+ if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", { operation });
1262
+ if (!terminal) throw streamContractError(operation, "stream ended before messageComplete", {
1263
+ doneMarkerSeen,
1264
+ started
1265
+ });
1266
+ }
1267
+ //#endregion
1268
+ //#region ../sdk/src/operations/shared.ts
1269
+ function invalidArgument(message, field, details) {
1270
+ return new QMindError("INVALID_ARGUMENT", message, { details: details ?? { field } });
1271
+ }
1272
+ function requiredString(value, field) {
1273
+ if (typeof value !== "string" || value.trim().length === 0) throw invalidArgument(`${field} must be a non-empty string`, field);
1274
+ return value.trim();
1275
+ }
1276
+ function optionalString(value, field) {
1277
+ if (value === void 0) return void 0;
1278
+ if (typeof value !== "string") throw invalidArgument(`${field} must be a string`, field);
1279
+ return value;
1280
+ }
1281
+ /** Validate body text without trimming meaningful Markdown indentation or trailing newlines. */
1282
+ function requiredText(value, field) {
1283
+ const text = optionalString(value, field);
1284
+ if (text === void 0 || text.trim().length === 0) throw invalidArgument(`${field} must be a non-empty string`, field);
1285
+ return text;
1286
+ }
1287
+ function optionalTrimmedString(value, field) {
1288
+ const string = optionalString(value, field)?.trim();
1289
+ return string === "" ? void 0 : string;
1290
+ }
1291
+ function optionalRecord(value, field) {
1292
+ if (value === void 0) return void 0;
1293
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidArgument(`${field} must be an object`, field);
1294
+ return value;
1295
+ }
1296
+ function optionalBoolean(value, field) {
1297
+ if (value === void 0) return void 0;
1298
+ if (typeof value !== "boolean") throw invalidArgument(`${field} must be a boolean`, field);
1299
+ return value;
1300
+ }
1301
+ function positiveInteger(value, field) {
1302
+ if (value === void 0) return void 0;
1303
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw invalidArgument(`${field} must be a positive integer`, field);
1304
+ return value;
1305
+ }
1306
+ function nonNegativeInteger(value, field) {
1307
+ if (value === void 0) return void 0;
1308
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw invalidArgument(`${field} must be a non-negative integer`, field);
1309
+ return value;
1310
+ }
1311
+ function pagination(input) {
1312
+ const page = positiveInteger(input.page, "page");
1313
+ const pageSize = positiveInteger(input.pageSize, "pageSize");
1314
+ return {
1315
+ ...page === void 0 ? {} : { page },
1316
+ ...pageSize === void 0 ? {} : { pageSize }
1317
+ };
1318
+ }
1319
+ function stringList(value, field, options = {}) {
1320
+ if (!Array.isArray(value)) throw invalidArgument(`${field} must be an array`, field);
1321
+ const result = [];
1322
+ const seen = /* @__PURE__ */ new Set();
1323
+ for (const item of value) {
1324
+ if (typeof item !== "string") throw invalidArgument(`${field} must contain only strings`, field);
1325
+ const normalized = item.trim();
1326
+ if (!normalized && !(options.keepEmptyString && item === "")) continue;
1327
+ if (seen.has(normalized)) continue;
1328
+ seen.add(normalized);
1329
+ result.push(normalized);
1330
+ }
1331
+ if (options.min !== void 0 && result.length < options.min) throw invalidArgument(`${field} must contain at least ${options.min} item(s)`, field);
1332
+ if (options.max !== void 0 && result.length > options.max) throw invalidArgument(`${field} must contain at most ${options.max} item(s)`, field);
1333
+ return result;
1334
+ }
1335
+ function httpUrl(value, field) {
1336
+ const raw = requiredString(value, field);
1337
+ let url;
1338
+ try {
1339
+ url = new URL(raw);
1340
+ } catch (cause) {
1341
+ throw invalidArgument(`${field} must be a valid HTTP(S) URL`, field, {
1342
+ cause,
1343
+ field
1344
+ });
1345
+ }
1346
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.host.length === 0) throw invalidArgument(`${field} must be a valid HTTP(S) URL`, field);
1347
+ url.hash = "";
1348
+ return url.toString();
1349
+ }
1350
+ function compactUndefined(value) {
1351
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
1352
+ }
1353
+ function assertNonEmptyPatch(patch, field) {
1354
+ if (Object.keys(patch).length > 0) return;
1355
+ throw invalidArgument(`${field} must contain at least one change`, field);
1356
+ }
1357
+ function queryPath(path, entries) {
1358
+ const query = new URLSearchParams();
1359
+ for (const [key, value] of entries) if (value !== void 0 && value !== "") query.set(key, String(value));
1360
+ const suffix = query.toString();
1361
+ return suffix.length === 0 ? path : `${path}?${suffix}`;
1362
+ }
1363
+ function wireRequest(options) {
1364
+ const timeoutMs = options.callOptions?.timeoutMs;
1365
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw invalidArgument("timeoutMs must be a positive finite number", "timeoutMs");
1366
+ const maxResponseBytes = options.callOptions?.maxResponseBytes;
1367
+ if (maxResponseBytes !== void 0 && (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes <= 0)) throw invalidArgument("maxResponseBytes must be a positive integer", "maxResponseBytes");
1368
+ const authorization = options.callOptions?.authorization?.trim();
1369
+ const headers = authorization ? {
1370
+ ...options.headers,
1371
+ authorization: `Bearer ${authorization}`
1372
+ } : options.headers;
1373
+ return {
1374
+ ...options.body === void 0 ? {} : { body: {
1375
+ kind: "json",
1376
+ value: options.body
1377
+ } },
1378
+ destination: {
1379
+ kind: "host",
1380
+ path: options.path
1381
+ },
1382
+ ...headers === void 0 ? {} : { headers },
1383
+ idempotent: options.idempotent,
1384
+ method: options.method,
1385
+ ...options.callOptions?.signal === void 0 ? {} : { signal: options.callOptions.signal },
1386
+ ...timeoutMs === void 0 ? {} : { timeoutMs },
1387
+ ...maxResponseBytes === void 0 ? {} : { maxResponseBytes }
1388
+ };
1389
+ }
1390
+ function call(context, options) {
1391
+ return executeUnary({
1392
+ capability: options.capability,
1393
+ operation: options.operation,
1394
+ capabilities: context.capabilities,
1395
+ request: wireRequest(options),
1396
+ schema: options.schema,
1397
+ transport: context.transport
1398
+ });
1399
+ }
1400
+ //#endregion
1401
+ export { taskRunListSchema as $, fullSiteURLImportConfirmationSchema as A, sourceActionAccessSchema as B, aliDingImportRunItemListSchema as C, chatMessageListSchema as D, cancelQuestionResultSchema as E, notebookListSchema as F, sourcePreviewSchema as G, sourceContentSchema as H, notebookSchema as I, sourceSchema as J, sourceQuotaSchema as K, retrieveNotebooksResultSchema as L, imageUploadTicketSchema as M, imageUrlsSchema as N, chatSessionListSchema as O, importProvidersSchema as P, sourceWebOfficeTokenSchema as Q, retrieveResultSchema as R, qmindRoutes as S, batchDeleteResultSchema as T, sourceImportResultsSchema as U, sourceChildrenCountsSchema as V, sourceListSchema as W, sourceUploadTicketSchema as X, sourceUploadCapabilitiesSchema as Y, sourceWebOfficeSessionSchema as Z, assertCapability as _, invalidArgument as a, dataSourceListSchema as at, pathBuilder as b, optionalRecord as c, dataSourceRunsSchema as ct, pagination as d, taskRunSchema as et, positiveInteger as f, stringList as g, requiredText as h, httpUrl as i, dataSourceConfigurationSchema as it, fullSiteURLImportDiscoverySchema as j, chatSessionSchema as k, optionalString as l, dataSourceSchema as lt, requiredString as m, call as n, voidResponseSchema as nt, nonNegativeInteger as o, dataSourcePreviewSchema as ot, queryPath as p, sourceRawContentSchema as q, compactUndefined as r, qmindFullSiteURLImportPageLimit as rt, optionalBoolean as s, dataSourceResourceSchema as st, assertNonEmptyPatch as t, timestampSchema as tt, optionalTrimmedString as u, QMindError as ut, executeStream as v, aliDingImportRunSchema as w, qmindPath as x, executeUnary as y, sharedNotebookListSchema as z };