@qoder-ai/qmind-cli 2.0.0 → 3.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.
@@ -0,0 +1,1155 @@
1
+ import { z } from "zod";
2
+ //#region ../sdk/src/errors.ts
3
+ var QMindError = class extends Error {
4
+ access;
5
+ code;
6
+ details;
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.access = options.access;
16
+ this.code = code;
17
+ this.details = options.details;
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
+ //#endregion
26
+ //#region ../sdk/src/execution.ts
27
+ const credentialHeaders = /* @__PURE__ */ new Set([
28
+ "authorization",
29
+ "cookie",
30
+ "proxy-authorization",
31
+ "x-csrf-token",
32
+ "x-xsrf-token"
33
+ ]);
34
+ function isRecord$1(value) {
35
+ return typeof value === "object" && value !== null && !Array.isArray(value);
36
+ }
37
+ function nestedRecord(value, key) {
38
+ const nested = value[key];
39
+ return isRecord$1(nested) ? nested : void 0;
40
+ }
41
+ function firstString(records, keys) {
42
+ for (const record of records) {
43
+ if (record === void 0) continue;
44
+ for (const key of keys) {
45
+ const value = record[key];
46
+ if (typeof value === "string" && value.length > 0) return value;
47
+ }
48
+ }
49
+ }
50
+ function headerValue(headers, name) {
51
+ const normalizedName = name.toLowerCase();
52
+ for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === normalizedName && value.length > 0) return value;
53
+ }
54
+ function errorCodeForStatus(status) {
55
+ if (status === 401) return "AUTH_REQUIRED";
56
+ if (status === 403) return "FORBIDDEN";
57
+ if (status === 404) return "NOT_FOUND";
58
+ if (status === 409) return "CONFLICT";
59
+ if (status === 429) return "RATE_LIMITED";
60
+ if (status >= 400 && status < 500) return "INVALID_ARGUMENT";
61
+ return "REMOTE_ERROR";
62
+ }
63
+ function httpError(access, operation, profile, response) {
64
+ const body = profile.unwrapError(response.body);
65
+ const root = isRecord$1(body) ? body : void 0;
66
+ const records = [
67
+ root,
68
+ root === void 0 ? void 0 : nestedRecord(root, "error"),
69
+ root === void 0 ? void 0 : nestedRecord(root, "details")
70
+ ];
71
+ const upstreamCode = firstString(records, [
72
+ "errorCode",
73
+ "error_code",
74
+ "code"
75
+ ]);
76
+ const requestId = firstString(records, ["requestId", "request_id"]) ?? headerValue(response.headers, "x-request-id") ?? headerValue(response.headers, "request-id");
77
+ const message = firstString(records, [
78
+ "message",
79
+ "errorMessage",
80
+ "error_message"
81
+ ]) ?? `QMind request failed with HTTP ${response.status}`;
82
+ return new QMindError(errorCodeForStatus(response.status), message, {
83
+ access,
84
+ details: body,
85
+ operation,
86
+ ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
87
+ ...requestId === void 0 ? {} : { requestId },
88
+ status: response.status,
89
+ ...upstreamCode === void 0 ? {} : { upstreamCode }
90
+ });
91
+ }
92
+ function isAbortLike(cause) {
93
+ return isRecord$1(cause) && (cause.name === "AbortError" && typeof cause.name === "string" || cause.code === "ABORT_ERR");
94
+ }
95
+ function transportError(access, operation, request, cause) {
96
+ if (cause instanceof QMindError) return cause;
97
+ const aborted = request.signal?.aborted === true || isAbortLike(cause);
98
+ return new QMindError(aborted ? "ABORTED" : "NETWORK_ERROR", aborted ? "QMind request was aborted" : "QMind transport failed", {
99
+ access,
100
+ cause,
101
+ operation
102
+ });
103
+ }
104
+ function requestWasAborted(request) {
105
+ return request.signal?.aborted === true;
106
+ }
107
+ function assertWireRequestInvariant(request) {
108
+ for (const [field, value] of [
109
+ ["connectTimeoutMs", request.connectTimeoutMs],
110
+ ["idleTimeoutMs", request.idleTimeoutMs],
111
+ ["timeoutMs", request.timeoutMs]
112
+ ]) if (!Number.isFinite(value ?? 1) || (value ?? 1) <= 0) throw new QMindError("INVALID_ARGUMENT", `${field} must be a positive finite number`, { details: { field } });
113
+ if (request.destination.kind === "host") {
114
+ 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 } });
115
+ return;
116
+ }
117
+ let url;
118
+ try {
119
+ url = new URL(request.destination.url);
120
+ } catch (cause) {
121
+ throw new QMindError("HOST_POLICY_ERROR", "signed destination must be a valid HTTPS URL", {
122
+ cause,
123
+ details: { destination: request.destination.kind }
124
+ });
125
+ }
126
+ 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 } });
127
+ 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: {
128
+ destination: request.destination.kind,
129
+ header: header.toLowerCase()
130
+ } });
131
+ }
132
+ function assertCapability(profile, capability, operation) {
133
+ if (profile.capabilities[capability]) return;
134
+ throw new QMindError("UNSUPPORTED_OPERATION", `${operation} is not supported by the ${profile.access} access profile`, {
135
+ access: profile.access,
136
+ details: { capability },
137
+ operation
138
+ });
139
+ }
140
+ async function executeUnary(options) {
141
+ const { capability, operation, profile, request, schema, transport } = options;
142
+ assertCapability(profile, capability, operation);
143
+ assertWireRequestInvariant(request);
144
+ if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", {
145
+ access: profile.access,
146
+ operation
147
+ });
148
+ let response;
149
+ try {
150
+ response = await transport.request(request);
151
+ } catch (cause) {
152
+ throw transportError(profile.access, operation, request, cause);
153
+ }
154
+ if (response.status < 200 || response.status >= 300) throw httpError(profile.access, operation, profile, response);
155
+ const body = profile.unwrapSuccess(operation, response.body);
156
+ const parsed = schema.safeParse(body);
157
+ if (!parsed.success) throw new QMindError("PROTOCOL_ERROR", "server response does not match the QMind contract", {
158
+ access: profile.access,
159
+ details: { issues: parsed.error.issues },
160
+ operation,
161
+ ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
162
+ status: response.status
163
+ });
164
+ return parsed.data;
165
+ }
166
+ function streamContractError(profile, operation, message, details) {
167
+ return new QMindError("STREAM_ERROR", message, {
168
+ access: profile.access,
169
+ ...details === void 0 ? {} : { details },
170
+ operation
171
+ });
172
+ }
173
+ function streamFailureResponse(response) {
174
+ return {
175
+ body: response.body,
176
+ headers: response.headers,
177
+ ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
178
+ status: response.status
179
+ };
180
+ }
181
+ async function* executeStream(options) {
182
+ const { capability, operation, profile, request, transport } = options;
183
+ assertCapability(profile, capability, operation);
184
+ assertWireRequestInvariant(request);
185
+ if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", {
186
+ access: profile.access,
187
+ operation
188
+ });
189
+ let response;
190
+ try {
191
+ response = await transport.stream(request);
192
+ } catch (cause) {
193
+ throw transportError(profile.access, operation, request, cause);
194
+ }
195
+ if (response.kind === "response") {
196
+ if (response.status >= 200 && response.status < 300) throw streamContractError(profile, operation, "stream handshake returned no event stream", { status: response.status });
197
+ throw httpError(profile.access, operation, profile, streamFailureResponse(response));
198
+ }
199
+ if (response.status < 200 || response.status >= 300) throw streamContractError(profile, operation, "stream handshake returned events for a failure status", { status: response.status });
200
+ let doneMarkerSeen = false;
201
+ let started = false;
202
+ let terminal = false;
203
+ try {
204
+ for await (const payload of response.events) {
205
+ if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", {
206
+ access: profile.access,
207
+ operation
208
+ });
209
+ if (payload.trim() === "[DONE]") {
210
+ if (doneMarkerSeen) throw streamContractError(profile, operation, "stream emitted more than one [DONE] marker");
211
+ doneMarkerSeen = true;
212
+ continue;
213
+ }
214
+ if (doneMarkerSeen) throw streamContractError(profile, operation, "stream emitted an event after [DONE]");
215
+ if (terminal) throw streamContractError(profile, operation, "stream emitted an event after messageComplete");
216
+ const event = profile.decodeStreamPayload(payload);
217
+ if (event.type === "error") throw streamContractError(profile, operation, event.message, { event });
218
+ if (event.type === "messageStart") {
219
+ if (started) throw streamContractError(profile, operation, "stream emitted duplicate messageStart");
220
+ started = true;
221
+ } else if (!started) throw streamContractError(profile, operation, "stream event arrived before messageStart", { eventType: event.type });
222
+ if (event.type === "messageComplete") terminal = true;
223
+ yield event;
224
+ }
225
+ } catch (cause) {
226
+ throw transportError(profile.access, operation, request, cause);
227
+ }
228
+ if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", {
229
+ access: profile.access,
230
+ operation
231
+ });
232
+ if (!terminal) throw streamContractError(profile, operation, "stream ended before messageComplete", {
233
+ doneMarkerSeen,
234
+ started
235
+ });
236
+ }
237
+ //#endregion
238
+ //#region ../sdk/src/imports.ts
239
+ const runStatuses = Object.freeze({
240
+ ALI_DING_IMPORT_RUN_STATUS_FAILED: "failed",
241
+ ALI_DING_IMPORT_RUN_STATUS_PARTIAL: "partial",
242
+ ALI_DING_IMPORT_RUN_STATUS_PENDING: "pending",
243
+ ALI_DING_IMPORT_RUN_STATUS_RUNNING: "running",
244
+ ALI_DING_IMPORT_RUN_STATUS_SUCCESS: "success",
245
+ ALI_DING_IMPORT_RUN_STATUS_UNSPECIFIED: "unspecified"
246
+ });
247
+ const itemStatuses = Object.freeze({
248
+ ALI_DING_IMPORT_ITEM_STATUS_FAILED: "failed",
249
+ ALI_DING_IMPORT_ITEM_STATUS_PARTIAL: "partial",
250
+ ALI_DING_IMPORT_ITEM_STATUS_PENDING: "pending",
251
+ ALI_DING_IMPORT_ITEM_STATUS_RUNNING: "running",
252
+ ALI_DING_IMPORT_ITEM_STATUS_SUCCESS: "success",
253
+ ALI_DING_IMPORT_ITEM_STATUS_UNSPECIFIED: "unspecified"
254
+ });
255
+ const contentStatuses = Object.freeze({
256
+ ALI_DING_IMPORT_CONTENT_STATUS_FAILED: "failed",
257
+ ALI_DING_IMPORT_CONTENT_STATUS_NOT_APPLICABLE: "notApplicable",
258
+ ALI_DING_IMPORT_CONTENT_STATUS_PENDING: "pending",
259
+ ALI_DING_IMPORT_CONTENT_STATUS_RUNNING: "running",
260
+ ALI_DING_IMPORT_CONTENT_STATUS_SUCCESS: "success",
261
+ ALI_DING_IMPORT_CONTENT_STATUS_UNSPECIFIED: "unspecified",
262
+ ALI_DING_IMPORT_CONTENT_STATUS_UNSUPPORTED: "unsupported"
263
+ });
264
+ const descendantsStatuses = Object.freeze({
265
+ ALI_DING_IMPORT_DESCENDANTS_STATUS_FAILED: "failed",
266
+ ALI_DING_IMPORT_DESCENDANTS_STATUS_NOT_APPLICABLE: "notApplicable",
267
+ ALI_DING_IMPORT_DESCENDANTS_STATUS_PARTIAL: "partial",
268
+ ALI_DING_IMPORT_DESCENDANTS_STATUS_PENDING: "pending",
269
+ ALI_DING_IMPORT_DESCENDANTS_STATUS_RUNNING: "running",
270
+ ALI_DING_IMPORT_DESCENDANTS_STATUS_SUCCESS: "success",
271
+ ALI_DING_IMPORT_DESCENDANTS_STATUS_UNSPECIFIED: "unspecified"
272
+ });
273
+ const nodeKinds = Object.freeze({
274
+ ALI_DING_IMPORT_NODE_KIND_DOCUMENT: "document",
275
+ ALI_DING_IMPORT_NODE_KIND_STRUCTURAL: "structural",
276
+ ALI_DING_IMPORT_NODE_KIND_UNSPECIFIED: "unspecified"
277
+ });
278
+ const scopes = Object.freeze({
279
+ ALI_DING_IMPORT_SCOPE_KNOWLEDGE_BASE: "knowledgeBase",
280
+ ALI_DING_IMPORT_SCOPE_NODE_SUBTREE: "nodeSubtree"
281
+ });
282
+ function normalizeQMindAliDingImportRunStatus(value) {
283
+ return runStatuses[value] ?? "unspecified";
284
+ }
285
+ function normalizeQMindAliDingImportItemStatus(value) {
286
+ return itemStatuses[value] ?? "unspecified";
287
+ }
288
+ function normalizeQMindAliDingImportContentStatus(value) {
289
+ return contentStatuses[value] ?? "unspecified";
290
+ }
291
+ function normalizeQMindAliDingImportDescendantsStatus(value) {
292
+ return descendantsStatuses[value] ?? "unspecified";
293
+ }
294
+ function normalizeQMindAliDingImportNodeKind(value) {
295
+ return nodeKinds[value] ?? "unspecified";
296
+ }
297
+ function normalizeQMindAliDingImportScope(value) {
298
+ return scopes[value] ?? "nodeSubtree";
299
+ }
300
+ //#endregion
301
+ //#region ../sdk/src/workflows.ts
302
+ const QMIND_MULTIPART_UPLOAD_MAX_BYTES = 52428800;
303
+ const QMIND_SOURCE_UPLOAD_MAX_BYTES = 524288e3;
304
+ Object.freeze({
305
+ canceled: {
306
+ order: 2,
307
+ outcome: "canceled",
308
+ phase: "terminal",
309
+ terminal: true
310
+ },
311
+ failed: {
312
+ order: 2,
313
+ outcome: "failure",
314
+ phase: "terminal",
315
+ terminal: true
316
+ },
317
+ partial: {
318
+ order: 2,
319
+ outcome: "partial",
320
+ phase: "terminal",
321
+ terminal: true
322
+ },
323
+ pending: {
324
+ order: 0,
325
+ outcome: "none",
326
+ phase: "queued",
327
+ terminal: false
328
+ },
329
+ running: {
330
+ order: 1,
331
+ outcome: "none",
332
+ phase: "active",
333
+ terminal: false
334
+ },
335
+ success: {
336
+ order: 2,
337
+ outcome: "success",
338
+ phase: "terminal",
339
+ terminal: true
340
+ },
341
+ unknown: {
342
+ order: -1,
343
+ outcome: "none",
344
+ phase: "unknown",
345
+ terminal: false
346
+ }
347
+ });
348
+ function normalizeQMindTaskRunStatus(status) {
349
+ switch (status.trim().toLowerCase()) {
350
+ case "pending":
351
+ case "running":
352
+ case "success":
353
+ case "partial":
354
+ case "failed":
355
+ case "canceled": return status.trim().toLowerCase();
356
+ default: return "unknown";
357
+ }
358
+ }
359
+ //#endregion
360
+ //#region ../sdk/src/schemas.ts
361
+ function isRecord(value) {
362
+ return typeof value === "object" && value !== null && !Array.isArray(value);
363
+ }
364
+ const wirePageNumberSchema = z.number().int().nonnegative().optional();
365
+ /**
366
+ * A brokered address must be HTTPS and carry no inline credentials: the token that authorizes it
367
+ * travels separately, so a userinfo component here would only leak a secret into logs and referrers.
368
+ */
369
+ const httpsUrlSchema = z.string().url().refine((value) => new URL(value).protocol === "https:", "expected an HTTPS URL").refine((value) => new URL(value).username.length === 0 && new URL(value).password.length === 0, "expected a URL without inline credentials");
370
+ const timestampPartsSchema = z.object({
371
+ nanos: z.number().int().min(0).max(999999999).optional(),
372
+ seconds: z.union([z.number().int(), z.string().regex(/^-?\d+$/u)])
373
+ });
374
+ const timestampSchema = z.union([z.iso.datetime({ offset: true }), timestampPartsSchema]).nullable().transform((value, context) => {
375
+ if (value === null) return null;
376
+ const milliseconds = typeof value === "string" ? Date.parse(value) : Number(value.seconds) * 1e3 + (value.nanos ?? 0) / 1e6;
377
+ const date = new Date(milliseconds);
378
+ if (!Number.isFinite(milliseconds) || Number.isNaN(date.valueOf())) {
379
+ context.addIssue({
380
+ code: "custom",
381
+ message: "Invalid QMind timestamp"
382
+ });
383
+ return z.NEVER;
384
+ }
385
+ return date.toISOString();
386
+ });
387
+ const notebookOverviewSchema = z.object({
388
+ status: z.string().default("empty"),
389
+ summary: z.string().default(""),
390
+ topics: z.array(z.string()).nullish().transform((topics) => topics ?? [])
391
+ });
392
+ const notebookMaintenanceSchema = z.object({
393
+ lastRunAt: timestampSchema.optional(),
394
+ lastRunId: z.string().optional(),
395
+ status: z.string().default("idle")
396
+ });
397
+ const notebookAccessInfoSchema = z.object({
398
+ canDeleteNotebook: z.boolean(),
399
+ canEdit: z.boolean(),
400
+ canManageMembers: z.boolean(),
401
+ canManageTasks: z.boolean(),
402
+ currentUserPermission: z.string(),
403
+ memberCount: z.number().int().nonnegative()
404
+ });
405
+ const notebookSchema = z.object({
406
+ access: notebookAccessInfoSchema.nullable().optional(),
407
+ client: z.string().optional(),
408
+ createdAt: timestampSchema.optional(),
409
+ description: z.string().default(""),
410
+ id: z.string().min(1),
411
+ maintenance: notebookMaintenanceSchema.optional(),
412
+ materialCount: z.number().int().nonnegative().default(0),
413
+ orgId: z.string().default(""),
414
+ overview: notebookOverviewSchema.optional(),
415
+ settings: z.record(z.string(), z.unknown()).optional(),
416
+ sourceCount: z.number().int().nonnegative().default(0),
417
+ status: z.string().default("active"),
418
+ title: z.string(),
419
+ updatedAt: timestampSchema.optional(),
420
+ userId: z.string().default("")
421
+ });
422
+ const notebookListSchema = z.object({
423
+ currentPage: wirePageNumberSchema,
424
+ notebooks: z.array(notebookSchema).nullish().transform((notebooks) => notebooks ?? []),
425
+ pageSize: wirePageNumberSchema,
426
+ totalSize: z.number().int().nonnegative().default(0)
427
+ });
428
+ const sharedNotebookListSchema = z.object({
429
+ currentPage: wirePageNumberSchema,
430
+ notebooks: z.array(z.object({
431
+ notebook: notebookSchema,
432
+ permission: z.string().optional()
433
+ })).nullish().transform((notebooks) => notebooks ?? []),
434
+ pageSize: wirePageNumberSchema,
435
+ totalSize: z.number().int().nonnegative().default(0)
436
+ });
437
+ const wikiDocumentSchema = z.preprocess((value) => isRecord(value) ? {
438
+ ...value,
439
+ contentHash: value.contentHash ?? value.content_hash,
440
+ contentUrl: value.contentUrl ?? value.content_url
441
+ } : value, z.object({
442
+ contentHash: z.string().default(""),
443
+ contentUrl: z.string().min(1),
444
+ language: z.string().default("")
445
+ }));
446
+ const wikiBranchSchema = z.preprocess((value) => isRecord(value) ? {
447
+ ...value,
448
+ commitTimestamp: value.commitTimestamp ?? value.commit_timestamp,
449
+ knowledgeCount: value.knowledgeCount ?? value.knowledge_count,
450
+ repoUrl: value.repoUrl ?? value.repo_url,
451
+ resultVersion: value.resultVersion ?? value.result_version,
452
+ updatedAt: value.updatedAt ?? value.updated_at
453
+ } : value, z.object({
454
+ branch: z.string().min(1),
455
+ commitTimestamp: z.number().optional(),
456
+ documents: z.array(wikiDocumentSchema).nullish().transform((documents) => documents ?? []),
457
+ exists: z.boolean().optional(),
458
+ knowledgeCount: z.number().int().nonnegative().default(0),
459
+ repo: z.string().min(1),
460
+ repoUrl: z.string().optional(),
461
+ resultVersion: z.string().default(""),
462
+ updatedAt: timestampSchema.optional()
463
+ }));
464
+ const wikiBranchListSchema = z.object({ branches: z.array(wikiBranchSchema).nullish().transform((branches) => branches ?? []) });
465
+ const cardLinkSchema = z.object({
466
+ description: z.string().optional(),
467
+ linkType: z.string().default(""),
468
+ targetId: z.string().min(1),
469
+ targetTitle: z.string().optional()
470
+ });
471
+ const cardSchema = z.object({
472
+ branch: z.string().optional(),
473
+ cardType: z.string().optional(),
474
+ category: z.string().optional(),
475
+ content: z.string().default(""),
476
+ createdAt: timestampSchema.optional(),
477
+ extra: z.string().optional(),
478
+ id: z.string().min(1),
479
+ keywords: z.array(z.string()).default([]),
480
+ knowledgeId: z.string().optional(),
481
+ language: z.string().optional(),
482
+ links: z.array(cardLinkSchema).default([]),
483
+ notebookId: z.string().optional(),
484
+ orgId: z.string().optional(),
485
+ repo: z.string().optional(),
486
+ score: z.number().optional(),
487
+ source: z.string().optional(),
488
+ title: z.string().default(""),
489
+ updatedAt: timestampSchema.optional()
490
+ });
491
+ const cardCategoryCountSchema = z.object({
492
+ category: z.string(),
493
+ count: z.number().int().nonnegative()
494
+ });
495
+ const cardLanguageCountSchema = z.object({
496
+ count: z.number().int().nonnegative(),
497
+ language: z.string()
498
+ });
499
+ const cardAppliedFiltersSchema = z.object({
500
+ branch: z.string().optional(),
501
+ category: z.string().optional(),
502
+ language: z.string().optional(),
503
+ query: z.string().optional(),
504
+ repo: z.string().optional(),
505
+ source: z.string().optional()
506
+ });
507
+ const cardListSchema = z.object({
508
+ appliedFilters: cardAppliedFiltersSchema.optional(),
509
+ cards: z.array(cardSchema).nullish().transform((cards) => cards ?? []),
510
+ categoryCounts: z.array(cardCategoryCountSchema).nullish().transform((counts) => counts ?? []),
511
+ currentPage: wirePageNumberSchema,
512
+ languageCounts: z.array(cardLanguageCountSchema).nullish().transform((counts) => counts ?? []),
513
+ pageSize: wirePageNumberSchema,
514
+ totalSize: z.number().int().nonnegative().default(0)
515
+ });
516
+ const sourcePageInfoSchema = z.object({
517
+ currentPage: wirePageNumberSchema,
518
+ lastPage: wirePageNumberSchema,
519
+ nextPage: wirePageNumberSchema,
520
+ nextToken: z.string().optional(),
521
+ pageSize: wirePageNumberSchema,
522
+ prevPage: wirePageNumberSchema,
523
+ totalSize: z.number().int().nonnegative().optional()
524
+ });
525
+ const sourceExternalBindingSchema = z.preprocess((value) => isRecord(value) ? {
526
+ ...value,
527
+ bindingId: value.bindingId ?? value.binding_id,
528
+ isRoot: value.isRoot ?? value.is_root
529
+ } : value, z.object({
530
+ bindingId: z.string().default(""),
531
+ isRoot: z.boolean().default(false),
532
+ provider: z.string().default("")
533
+ }));
534
+ const sourceSchema = z.object({
535
+ childrenCount: z.number().int().nonnegative().optional(),
536
+ createdAt: timestampSchema.optional(),
537
+ errorCode: z.string().default(""),
538
+ errorMessage: z.string().default(""),
539
+ externalBinding: sourceExternalBindingSchema.optional(),
540
+ filename: z.string().optional(),
541
+ hasChildren: z.boolean().optional(),
542
+ id: z.string().min(1),
543
+ isDir: z.boolean().default(false),
544
+ metadata: z.record(z.string(), z.unknown()).nullable().optional(),
545
+ mimeType: z.string().optional(),
546
+ name: z.string().optional(),
547
+ notebookId: z.string().default(""),
548
+ orgId: z.string().default(""),
549
+ originUrl: z.string().optional(),
550
+ parentSourceId: z.string().default(""),
551
+ path: z.string().default(""),
552
+ sourceType: z.string().default(""),
553
+ size: z.number().int().nonnegative().optional(),
554
+ status: z.string().default(""),
555
+ title: z.string().default(""),
556
+ updatedAt: timestampSchema.optional(),
557
+ uri: z.string().default(""),
558
+ userId: z.string().default("")
559
+ });
560
+ const sourceListSchema = z.object({
561
+ currentPage: wirePageNumberSchema,
562
+ pageSize: wirePageNumberSchema,
563
+ pages: sourcePageInfoSchema.optional(),
564
+ sources: z.array(sourceSchema).nullish().transform((sources) => sources ?? []),
565
+ totalSize: z.number().int().nonnegative().optional()
566
+ });
567
+ const sourceTreeNodeSchema = z.lazy(() => z.object({
568
+ files: z.array(sourceTreeNodeSchema).default([]),
569
+ hasChildren: z.boolean().optional(),
570
+ id: z.string().min(1),
571
+ name: z.string().default(""),
572
+ path: z.string().default(""),
573
+ sourceType: z.string().default(""),
574
+ status: z.string().default(""),
575
+ type: z.enum(["file", "directory"])
576
+ }));
577
+ const sourceTreeSchema = z.object({
578
+ totalSize: z.number().int().nonnegative().default(0),
579
+ tree: z.array(sourceTreeNodeSchema)
580
+ });
581
+ const sourceContentSchema = z.object({
582
+ content: z.string(),
583
+ contentType: z.string().default("text/markdown"),
584
+ size: z.number().int().nonnegative().optional(),
585
+ sourceId: z.string().default("")
586
+ });
587
+ /** proto3 JSON serializes int64 as a string, so byte counts arrive either way. */
588
+ const wireInt64Schema = z.union([z.number(), z.string()]).nullish().transform((value) => {
589
+ const parsed = typeof value === "string" ? Number(value) : value ?? 0;
590
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;
591
+ });
592
+ const sourceUploadExtensionSchema = z.string().regex(/^\.[a-z0-9]+$/);
593
+ const sourceUploadMethodSchema = z.preprocess((value) => isRecord(value) ? {
594
+ ...value,
595
+ maxSizeBytes: value.maxSizeBytes ?? value.max_size_bytes,
596
+ supportedExtensions: value.supportedExtensions ?? value.supported_extensions
597
+ } : value, z.object({
598
+ available: z.boolean(),
599
+ maxSizeBytes: wireInt64Schema,
600
+ method: z.string().min(1),
601
+ supportedExtensions: z.array(sourceUploadExtensionSchema).default([])
602
+ }));
603
+ const sourceUploadFileTypeSchema = z.preprocess((value) => isRecord(value) ? {
604
+ ...value,
605
+ displayName: value.displayName ?? value.display_name,
606
+ mimeTypes: value.mimeTypes ?? value.mime_types,
607
+ sourceType: value.sourceType ?? value.source_type,
608
+ uploadMethods: value.uploadMethods ?? value.upload_methods
609
+ } : value, z.object({
610
+ displayName: z.string().default(""),
611
+ extensions: z.array(sourceUploadExtensionSchema).default([]),
612
+ mimeTypes: z.array(z.string()).default([]),
613
+ sourceType: z.string().min(1),
614
+ uploadMethods: z.array(z.string().min(1)).default([])
615
+ }));
616
+ const sourceUploadCapabilitiesSchema = z.preprocess((value) => isRecord(value) ? {
617
+ ...value,
618
+ fileTypes: value.fileTypes ?? value.file_types,
619
+ uploadMethods: value.uploadMethods ?? value.upload_methods
620
+ } : value, z.object({
621
+ fileTypes: z.array(sourceUploadFileTypeSchema).default([]),
622
+ uploadMethods: z.array(sourceUploadMethodSchema).default([])
623
+ }));
624
+ const downloadOriginalActionAccessSchema = z.discriminatedUnion("state", [z.object({
625
+ action: z.literal("download_original"),
626
+ reason: z.undefined().optional(),
627
+ state: z.literal("allowed")
628
+ }), z.object({
629
+ action: z.literal("download_original"),
630
+ reason: z.literal("organization_policy"),
631
+ state: z.literal("denied")
632
+ })]);
633
+ const sourceActionAccessSchema = z.preprocess((value) => {
634
+ if (!isRecord(value) || !Array.isArray(value.actions)) return value;
635
+ return {
636
+ ...value,
637
+ actions: value.actions.filter((action) => {
638
+ if (!isRecord(action)) return true;
639
+ return typeof action.action !== "string" || action.action.length === 0 || action.action === "download_original";
640
+ })
641
+ };
642
+ }, z.object({ actions: z.array(downloadOriginalActionAccessSchema).length(1) }));
643
+ const sourceRawContentSchema = z.preprocess((value) => isRecord(value) ? {
644
+ ...value,
645
+ contentType: value.contentType ?? value.content_type,
646
+ sizeBytes: value.sizeBytes ?? value.size_bytes,
647
+ sourceFormat: value.sourceFormat ?? value.source_format,
648
+ sourceId: value.sourceId ?? value.source_id
649
+ } : value, z.object({
650
+ content: z.string().default(""),
651
+ contentType: z.string().default(""),
652
+ sizeBytes: wireInt64Schema,
653
+ sourceFormat: z.string().default(""),
654
+ sourceId: z.string().default("")
655
+ }));
656
+ const sourcePreviewSchema = z.preprocess((value) => isRecord(value) ? {
657
+ ...value,
658
+ contentType: value.contentType ?? value.content_type,
659
+ expiresAt: value.expiresAt ?? value.expires_at,
660
+ sourceFormat: value.sourceFormat ?? value.source_format,
661
+ sourceId: value.sourceId ?? value.source_id
662
+ } : value, z.object({
663
+ contentType: z.string().default(""),
664
+ expiresAt: timestampSchema.optional(),
665
+ sourceFormat: z.string().default(""),
666
+ sourceId: z.string().default(""),
667
+ url: httpsUrlSchema
668
+ }));
669
+ /** proto3 JSON serializes the token timeout and version as int64, so both arrive either way. */
670
+ const officeTokenIntegerSchema = z.union([z.number(), z.string().regex(/^\d+$/).transform(Number)]).pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));
671
+ const webOfficeTokenFields = {
672
+ accessToken: z.string().min(1),
673
+ accessTokenExpiresAt: timestampSchema.optional(),
674
+ tokenTimeoutMs: officeTokenIntegerSchema.refine((value) => value > 0),
675
+ tokenVersion: officeTokenIntegerSchema
676
+ };
677
+ function webOfficeTokenAliases(value) {
678
+ return isRecord(value) ? {
679
+ ...value,
680
+ accessToken: value.accessToken ?? value.access_token,
681
+ accessTokenExpiresAt: value.accessTokenExpiresAt ?? value.access_token_expires_at,
682
+ tokenTimeoutMs: value.tokenTimeoutMs ?? value.token_timeout_ms,
683
+ tokenVersion: value.tokenVersion ?? value.token_version
684
+ } : value;
685
+ }
686
+ const sourceWebOfficeSessionSchema = z.preprocess((value) => {
687
+ const aliased = webOfficeTokenAliases(value);
688
+ return isRecord(aliased) ? {
689
+ ...aliased,
690
+ readOnly: aliased.readOnly ?? aliased.readonly,
691
+ sessionId: aliased.sessionId ?? aliased.session_id,
692
+ sourceFormat: aliased.sourceFormat ?? aliased.source_format,
693
+ sourceId: aliased.sourceId ?? aliased.source_id,
694
+ webOfficeUrl: aliased.webOfficeUrl ?? aliased.web_office_url
695
+ } : aliased;
696
+ }, z.object({
697
+ ...webOfficeTokenFields,
698
+ readOnly: z.literal(true),
699
+ reused: z.boolean().default(false),
700
+ sessionId: z.string().min(1),
701
+ sourceFormat: z.string().min(1).transform((value) => value.trim().toLowerCase().replace(/^\./, "")).pipe(z.string().min(1)),
702
+ sourceId: z.string().min(1),
703
+ webOfficeUrl: httpsUrlSchema
704
+ }));
705
+ const sourceWebOfficeTokenSchema = z.preprocess(webOfficeTokenAliases, z.object(webOfficeTokenFields));
706
+ const sourceChildrenCountsSchema = z.object({ counts: z.array(z.preprocess((value) => isRecord(value) ? {
707
+ ...value,
708
+ parentId: value.parentId ?? value.parent_id
709
+ } : value, z.object({
710
+ count: z.number().int().nonnegative().default(0),
711
+ parentId: z.string().default("")
712
+ }))).nullish().transform((counts) => counts ?? []) }).transform((value) => value.counts);
713
+ 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));
714
+ const aliDingImportRunSchema = z.preprocess((value) => isRecord(value) ? {
715
+ ...value,
716
+ bindingId: value.bindingId ?? value.binding_id,
717
+ canonicalUrl: value.canonicalUrl ?? value.canonical_url,
718
+ contentFailedCount: value.contentFailedCount ?? value.content_failed_count,
719
+ contentSuccessCount: value.contentSuccessCount ?? value.content_success_count,
720
+ contentUnsupportedCount: value.contentUnsupportedCount ?? value.content_unsupported_count,
721
+ descendantsFailedCount: value.descendantsFailedCount ?? value.descendants_failed_count,
722
+ discoveredCount: value.discoveredCount ?? value.discovered_count,
723
+ documentCount: value.documentCount ?? value.document_count,
724
+ errorCode: value.errorCode ?? value.error_code,
725
+ errorMessage: value.errorMessage ?? value.error_message,
726
+ finishedAt: value.finishedAt ?? value.finished_at,
727
+ notebookId: value.notebookId ?? value.notebook_id,
728
+ processedCount: value.processedCount ?? value.processed_count,
729
+ requestId: value.requestId ?? value.request_id,
730
+ rootSourceId: value.rootSourceId ?? value.root_source_id,
731
+ startedAt: value.startedAt ?? value.started_at,
732
+ structuralCount: value.structuralCount ?? value.structural_count
733
+ } : value, z.object({
734
+ bindingId: z.string().optional(),
735
+ canonicalUrl: z.string().default(""),
736
+ contentFailedCount: wireInt64Schema,
737
+ contentSuccessCount: wireInt64Schema,
738
+ contentUnsupportedCount: wireInt64Schema,
739
+ createdAt: timestampSchema.optional(),
740
+ descendantsFailedCount: wireInt64Schema,
741
+ discoveredCount: wireInt64Schema,
742
+ documentCount: wireInt64Schema,
743
+ errorCode: z.string().default(""),
744
+ errorMessage: z.string().default(""),
745
+ finishedAt: timestampSchema.optional(),
746
+ id: z.string().min(1),
747
+ notebookId: z.string().default(""),
748
+ processedCount: wireInt64Schema,
749
+ requestId: z.string().default(""),
750
+ rootSourceId: z.string().optional(),
751
+ scope: z.string().default(""),
752
+ startedAt: timestampSchema.optional(),
753
+ status: z.string().default(""),
754
+ structuralCount: wireInt64Schema,
755
+ updatedAt: timestampSchema.optional()
756
+ })).transform((value) => ({
757
+ ...value.bindingId === void 0 ? {} : { bindingId: value.bindingId },
758
+ canonicalUrl: value.canonicalUrl,
759
+ counts: {
760
+ contentFailed: value.contentFailedCount,
761
+ contentSuccess: value.contentSuccessCount,
762
+ contentUnsupported: value.contentUnsupportedCount,
763
+ descendantsFailed: value.descendantsFailedCount,
764
+ discovered: value.discoveredCount,
765
+ document: value.documentCount,
766
+ processed: value.processedCount,
767
+ structural: value.structuralCount
768
+ },
769
+ ...value.createdAt === void 0 ? {} : { createdAt: value.createdAt },
770
+ errorCode: value.errorCode,
771
+ errorMessage: value.errorMessage,
772
+ ...value.finishedAt === void 0 ? {} : { finishedAt: value.finishedAt },
773
+ id: value.id,
774
+ notebookId: value.notebookId,
775
+ rawStatus: value.status,
776
+ requestId: value.requestId,
777
+ ...value.rootSourceId === void 0 ? {} : { rootSourceId: value.rootSourceId },
778
+ scope: normalizeQMindAliDingImportScope(value.scope),
779
+ ...value.startedAt === void 0 ? {} : { startedAt: value.startedAt },
780
+ status: normalizeQMindAliDingImportRunStatus(value.status),
781
+ ...value.updatedAt === void 0 ? {} : { updatedAt: value.updatedAt }
782
+ }));
783
+ const aliDingImportRunItemSchema = z.preprocess((value) => isRecord(value) ? {
784
+ ...value,
785
+ contentStatus: value.contentStatus ?? value.content_status,
786
+ descendantsStatus: value.descendantsStatus ?? value.descendants_status,
787
+ errorMessage: value.errorMessage ?? value.error_message,
788
+ errorReason: value.errorReason ?? value.error_reason,
789
+ nodeId: value.nodeId ?? value.node_id,
790
+ nodeKind: value.nodeKind ?? value.node_kind,
791
+ parentNodeId: value.parentNodeId ?? value.parent_node_id,
792
+ runId: value.runId ?? value.run_id,
793
+ sourceId: value.sourceId ?? value.source_id
794
+ } : value, z.object({
795
+ contentStatus: z.string().default(""),
796
+ createdAt: timestampSchema.optional(),
797
+ descendantsStatus: z.string().default(""),
798
+ errorMessage: z.string().default(""),
799
+ errorReason: z.string().default(""),
800
+ name: z.string().default(""),
801
+ nodeId: z.string().default(""),
802
+ nodeKind: z.string().default(""),
803
+ parentNodeId: z.string().default(""),
804
+ runId: z.string().default(""),
805
+ sequence: z.union([z.number(), z.string()]).default(""),
806
+ sourceId: z.string().optional(),
807
+ status: z.string().default(""),
808
+ updatedAt: timestampSchema.optional()
809
+ })).transform((value) => ({
810
+ contentStatus: normalizeQMindAliDingImportContentStatus(value.contentStatus),
811
+ ...value.createdAt === void 0 ? {} : { createdAt: value.createdAt },
812
+ descendantsStatus: normalizeQMindAliDingImportDescendantsStatus(value.descendantsStatus),
813
+ errorMessage: value.errorMessage,
814
+ errorReason: value.errorReason,
815
+ name: value.name,
816
+ nodeId: value.nodeId,
817
+ nodeKind: normalizeQMindAliDingImportNodeKind(value.nodeKind),
818
+ parentNodeId: value.parentNodeId,
819
+ runId: value.runId,
820
+ sequence: String(value.sequence),
821
+ ...value.sourceId === void 0 ? {} : { sourceId: value.sourceId },
822
+ status: normalizeQMindAliDingImportItemStatus(value.status),
823
+ ...value.updatedAt === void 0 ? {} : { updatedAt: value.updatedAt }
824
+ }));
825
+ const aliDingImportPageInfoSchema = z.preprocess((value) => isRecord(value) ? {
826
+ ...value,
827
+ currentPage: value.currentPage ?? value.current_page,
828
+ lastPage: value.lastPage ?? value.last_page,
829
+ nextPage: value.nextPage ?? value.next_page,
830
+ pageSize: value.pageSize ?? value.page_size,
831
+ prevPage: value.prevPage ?? value.prev_page,
832
+ totalSize: value.totalSize ?? value.total_size
833
+ } : value, z.object({
834
+ currentPage: z.number().int().nonnegative().default(0),
835
+ lastPage: z.number().int().nonnegative().default(0),
836
+ nextPage: wirePageNumberSchema,
837
+ pageSize: z.number().int().nonnegative().default(0),
838
+ prevPage: wirePageNumberSchema,
839
+ totalSize: wireInt64Schema
840
+ }));
841
+ const aliDingImportRunItemListSchema = z.object({
842
+ items: z.array(aliDingImportRunItemSchema).nullish().transform((items) => items ?? []),
843
+ pages: aliDingImportPageInfoSchema.optional()
844
+ });
845
+ const sourceImportResultSchema = z.object({
846
+ error: z.string().optional(),
847
+ source: sourceSchema.optional(),
848
+ url: z.string().default("")
849
+ });
850
+ const sourceImportResultsSchema = z.object({ results: z.array(sourceImportResultSchema) }).transform((value) => value.results);
851
+ const batchMutationResultSchema = z.object({
852
+ failureCount: z.number().int().nonnegative().default(0),
853
+ successCount: z.number().int().nonnegative().default(0)
854
+ });
855
+ const voidResponseSchema = z.unknown().transform(() => void 0);
856
+ const imageUploadTicketSchema = z.object({
857
+ expiresAt: z.string().optional(),
858
+ headers: z.record(z.string(), z.string()).default({}),
859
+ method: z.literal("PUT").default("PUT"),
860
+ ossKey: z.string().min(1),
861
+ uploadUrl: httpsUrlSchema
862
+ });
863
+ const imageUrlsSchema = z.object({
864
+ expiresAt: z.string().optional(),
865
+ urls: z.record(z.string(), httpsUrlSchema)
866
+ });
867
+ const notebookCitationSchema = z.preprocess((value) => isRecord(value) ? {
868
+ ...value,
869
+ chunkId: value.chunkId ?? value.chunk_id,
870
+ chunkIndex: value.chunkIndex ?? value.chunk_index,
871
+ originUrl: value.originUrl ?? value.origin_url,
872
+ sourceId: value.sourceId ?? value.source_id,
873
+ sourceTitle: value.sourceTitle ?? value.source_title,
874
+ sourceUri: value.sourceUri ?? value.source_uri
875
+ } : value, z.object({
876
+ chunkId: z.string().default(""),
877
+ chunkIndex: z.number().int().nonnegative().default(0),
878
+ metadata: z.record(z.string(), z.unknown()).optional(),
879
+ originUrl: z.string().optional(),
880
+ snippet: z.string().default(""),
881
+ sourceId: z.string().default(""),
882
+ sourceTitle: z.string().default(""),
883
+ sourceUri: z.string().default("")
884
+ }));
885
+ const chatMessageSchema = z.object({
886
+ chatSessionId: z.string().optional(),
887
+ citations: z.array(notebookCitationSchema).nullish().transform((citations) => citations === null ? [] : citations),
888
+ content: z.string().default(""),
889
+ createdAt: timestampSchema.optional(),
890
+ id: z.string().min(1),
891
+ metadata: z.record(z.string(), z.unknown()).optional(),
892
+ model: z.string().optional(),
893
+ notebookId: z.string().optional(),
894
+ orgId: z.string().optional(),
895
+ role: z.string().default(""),
896
+ sceneType: z.string().optional(),
897
+ sequence: z.number().int().nonnegative().optional(),
898
+ updatedAt: timestampSchema.optional(),
899
+ userId: z.string().optional()
900
+ });
901
+ const streamWireEventSchema = z.object({
902
+ assistantMessage: chatMessageSchema.optional(),
903
+ assistantMessageId: z.string().optional(),
904
+ cancelReason: z.string().optional(),
905
+ canceled: z.boolean().optional(),
906
+ citations: z.array(z.string()).optional(),
907
+ delta: z.string().optional(),
908
+ errorMessage: z.string().optional(),
909
+ error: z.string().optional(),
910
+ eventType: z.string().optional(),
911
+ event_type: z.string().optional(),
912
+ metadata: z.record(z.string(), z.string()).optional(),
913
+ promptContext: z.string().optional(),
914
+ reranked: z.boolean().optional(),
915
+ step: z.number().int().optional(),
916
+ toolArguments: z.string().optional(),
917
+ toolDisplayName: z.string().optional(),
918
+ toolName: z.string().optional(),
919
+ toolResult: z.string().optional(),
920
+ totalContextChunks: z.number().int().nonnegative().optional(),
921
+ type: z.string().optional(),
922
+ userMessage: chatMessageSchema.optional()
923
+ });
924
+ const sourceUploadTicketSchema = z.object({
925
+ expiresAt: z.string().optional(),
926
+ headers: z.record(z.string(), z.string()).default({}),
927
+ method: z.literal("PUT").default("PUT"),
928
+ uploadUrl: httpsUrlSchema,
929
+ uri: z.string().min(1)
930
+ });
931
+ const chatSessionSchema = z.object({
932
+ createdAt: timestampSchema.optional(),
933
+ id: z.string().min(1),
934
+ metadata: z.record(z.string(), z.unknown()).optional(),
935
+ modelOverride: z.string().default(""),
936
+ notebookId: z.string().default(""),
937
+ orgId: z.string().default(""),
938
+ sceneType: z.string().default("rag"),
939
+ status: z.string().default("active"),
940
+ title: z.string().default(""),
941
+ updatedAt: timestampSchema.optional(),
942
+ userId: z.string().default("")
943
+ });
944
+ const chatSessionListSchema = z.object({
945
+ chatSessions: z.array(chatSessionSchema).nullish().transform((sessions) => sessions ?? []),
946
+ currentPage: wirePageNumberSchema,
947
+ pageSize: wirePageNumberSchema,
948
+ totalSize: z.number().int().nonnegative().default(0)
949
+ });
950
+ const chatMessageListSchema = z.object({
951
+ currentPage: wirePageNumberSchema,
952
+ messages: z.array(chatMessageSchema).nullish().transform((messages) => messages ?? []),
953
+ pageSize: wirePageNumberSchema,
954
+ sceneType: z.string().optional(),
955
+ totalSize: z.number().int().nonnegative().default(0)
956
+ });
957
+ const notebookContextChunkSchema = z.object({
958
+ chunkId: z.string().default(""),
959
+ chunkIndex: z.number().int().nonnegative().default(0),
960
+ content: z.string().default(""),
961
+ metadata: z.record(z.string(), z.unknown()).optional(),
962
+ originUrl: z.string().optional(),
963
+ score: z.number().finite().default(0),
964
+ sourceId: z.string().default(""),
965
+ sourceTitle: z.string().default(""),
966
+ sourceUri: z.string().default(""),
967
+ tokenCount: z.number().int().nonnegative().default(0)
968
+ });
969
+ const retrievedCardLinkSchema = z.object({
970
+ description: z.string().optional(),
971
+ linkType: z.string().default(""),
972
+ targetId: z.string().min(1),
973
+ targetTitle: z.string().optional()
974
+ });
975
+ const retrievedCardSchema = z.object({
976
+ cardType: z.string().optional(),
977
+ category: z.string().optional(),
978
+ content: z.string().default(""),
979
+ depth: z.number().int().nonnegative().default(0),
980
+ id: z.string().min(1),
981
+ keywords: z.array(z.string()).default([]),
982
+ links: z.array(retrievedCardLinkSchema).default([]),
983
+ score: z.number().finite().default(0),
984
+ title: z.string().default("")
985
+ });
986
+ const retrieveResultSchema = z.object({
987
+ cards: z.array(retrievedCardSchema).default([]),
988
+ chunks: z.array(notebookContextChunkSchema).default([]),
989
+ citations: z.array(notebookCitationSchema).default([]),
990
+ promptContext: z.string().default(""),
991
+ reranked: z.boolean().default(false),
992
+ total: z.number().int().nonnegative().default(0)
993
+ });
994
+ const cancelQuestionResultSchema = z.object({ accepted: z.boolean() });
995
+ const taskRunSchema = z.object({
996
+ assistantMessageId: z.string().optional(),
997
+ chatSessionId: z.string().optional(),
998
+ config: z.record(z.string(), z.unknown()).optional(),
999
+ createdAt: timestampSchema.optional(),
1000
+ durationMs: z.number().int().nonnegative().optional(),
1001
+ errorMessage: z.string().optional(),
1002
+ finishedAt: timestampSchema.optional(),
1003
+ id: z.string().min(1),
1004
+ message: chatMessageSchema.optional(),
1005
+ notebookId: z.string().default(""),
1006
+ orgId: z.string().default(""),
1007
+ parentRunId: z.string().optional(),
1008
+ reportMarkdown: z.string().optional(),
1009
+ sceneType: z.string().default(""),
1010
+ scheduledTaskId: z.string().optional(),
1011
+ sourceId: z.string().optional(),
1012
+ startedAt: timestampSchema.optional(),
1013
+ stats: z.record(z.string(), z.unknown()).optional(),
1014
+ status: z.string().default(""),
1015
+ trigger: z.string().default(""),
1016
+ updatedAt: timestampSchema.optional(),
1017
+ userId: z.string().default("")
1018
+ }).transform((value) => ({
1019
+ ...value,
1020
+ rawStatus: value.status,
1021
+ status: normalizeQMindTaskRunStatus(value.status)
1022
+ }));
1023
+ const taskRunListSchema = z.object({
1024
+ currentPage: wirePageNumberSchema,
1025
+ pageSize: wirePageNumberSchema,
1026
+ runs: z.array(taskRunSchema).nullish().transform((runs) => runs ?? []),
1027
+ totalSize: z.number().int().nonnegative().default(0)
1028
+ });
1029
+ //#endregion
1030
+ //#region ../sdk/src/operations/shared.ts
1031
+ function invalidArgument(message, field, details) {
1032
+ return new QMindError("INVALID_ARGUMENT", message, { details: details ?? { field } });
1033
+ }
1034
+ function requiredString(value, field) {
1035
+ if (typeof value !== "string" || value.trim().length === 0) throw invalidArgument(`${field} must be a non-empty string`, field);
1036
+ return value.trim();
1037
+ }
1038
+ function optionalString(value, field) {
1039
+ if (value === void 0) return void 0;
1040
+ if (typeof value !== "string") throw invalidArgument(`${field} must be a string`, field);
1041
+ return value;
1042
+ }
1043
+ /** Validate body text without trimming meaningful Markdown indentation or trailing newlines. */
1044
+ function requiredText(value, field) {
1045
+ const text = optionalString(value, field);
1046
+ if (text === void 0 || text.trim().length === 0) throw invalidArgument(`${field} must be a non-empty string`, field);
1047
+ return text;
1048
+ }
1049
+ function optionalTrimmedString(value, field) {
1050
+ const string = optionalString(value, field)?.trim();
1051
+ return string === "" ? void 0 : string;
1052
+ }
1053
+ function optionalRecord(value, field) {
1054
+ if (value === void 0) return void 0;
1055
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidArgument(`${field} must be an object`, field);
1056
+ return value;
1057
+ }
1058
+ function optionalBoolean(value, field) {
1059
+ if (value === void 0) return void 0;
1060
+ if (typeof value !== "boolean") throw invalidArgument(`${field} must be a boolean`, field);
1061
+ return value;
1062
+ }
1063
+ function positiveInteger(value, field) {
1064
+ if (value === void 0) return void 0;
1065
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw invalidArgument(`${field} must be a positive integer`, field);
1066
+ return value;
1067
+ }
1068
+ function nonNegativeInteger(value, field) {
1069
+ if (value === void 0) return void 0;
1070
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw invalidArgument(`${field} must be a non-negative integer`, field);
1071
+ return value;
1072
+ }
1073
+ function pagination(input) {
1074
+ const page = positiveInteger(input.page, "page");
1075
+ const pageSize = positiveInteger(input.pageSize, "pageSize");
1076
+ return {
1077
+ ...page === void 0 ? {} : { page },
1078
+ ...pageSize === void 0 ? {} : { pageSize }
1079
+ };
1080
+ }
1081
+ function stringList(value, field, options = {}) {
1082
+ if (!Array.isArray(value)) throw invalidArgument(`${field} must be an array`, field);
1083
+ const result = [];
1084
+ const seen = /* @__PURE__ */ new Set();
1085
+ for (const item of value) {
1086
+ if (typeof item !== "string") throw invalidArgument(`${field} must contain only strings`, field);
1087
+ const normalized = item.trim();
1088
+ if (normalized.length === 0 || seen.has(normalized)) continue;
1089
+ seen.add(normalized);
1090
+ result.push(normalized);
1091
+ }
1092
+ if (options.min !== void 0 && result.length < options.min) throw invalidArgument(`${field} must contain at least ${options.min} item(s)`, field);
1093
+ if (options.max !== void 0 && result.length > options.max) throw invalidArgument(`${field} must contain at most ${options.max} item(s)`, field);
1094
+ return result;
1095
+ }
1096
+ function httpUrl(value, field) {
1097
+ const raw = requiredString(value, field);
1098
+ let url;
1099
+ try {
1100
+ url = new URL(raw);
1101
+ } catch (cause) {
1102
+ throw invalidArgument(`${field} must be a valid HTTP(S) URL`, field, {
1103
+ cause,
1104
+ field
1105
+ });
1106
+ }
1107
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.host.length === 0) throw invalidArgument(`${field} must be a valid HTTP(S) URL`, field);
1108
+ url.hash = "";
1109
+ return url.toString();
1110
+ }
1111
+ function compactUndefined(value) {
1112
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
1113
+ }
1114
+ function assertNonEmptyPatch(patch, field) {
1115
+ if (Object.keys(patch).length > 0) return;
1116
+ throw invalidArgument(`${field} must contain at least one change`, field);
1117
+ }
1118
+ function queryPath(path, entries) {
1119
+ const query = new URLSearchParams();
1120
+ for (const [key, value] of entries) if (value !== void 0 && value !== "") query.set(key, String(value));
1121
+ const suffix = query.toString();
1122
+ return suffix.length === 0 ? path : `${path}?${suffix}`;
1123
+ }
1124
+ function wireRequest(options) {
1125
+ const timeoutMs = options.callOptions?.timeoutMs;
1126
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw invalidArgument("timeoutMs must be a positive finite number", "timeoutMs");
1127
+ const authorization = options.callOptions?.authorization?.trim();
1128
+ return {
1129
+ ...options.body === void 0 ? {} : { body: {
1130
+ kind: "json",
1131
+ value: options.body
1132
+ } },
1133
+ destination: {
1134
+ kind: "host",
1135
+ path: options.path
1136
+ },
1137
+ ...authorization === void 0 || authorization.length === 0 ? {} : { headers: { authorization: `Bearer ${authorization}` } },
1138
+ idempotent: options.idempotent,
1139
+ method: options.method,
1140
+ ...options.callOptions?.signal === void 0 ? {} : { signal: options.callOptions.signal },
1141
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
1142
+ };
1143
+ }
1144
+ function call(context, options) {
1145
+ return executeUnary({
1146
+ capability: options.capability,
1147
+ operation: options.operation,
1148
+ profile: context.profile,
1149
+ request: wireRequest(options),
1150
+ schema: options.schema,
1151
+ transport: context.transport
1152
+ });
1153
+ }
1154
+ //#endregion
1155
+ export { QMIND_SOURCE_UPLOAD_MAX_BYTES as $, notebookSchema as A, sourceSchema as B, chatMessageListSchema as C, imageUrlsSchema as D, imageUploadTicketSchema as E, sourceContentSchema as F, sourceWebOfficeTokenSchema as G, sourceUploadCapabilitiesSchema as H, sourceImportResultsSchema as I, taskRunSchema as J, streamWireEventSchema as K, sourceListSchema as L, sharedNotebookListSchema as M, sourceActionAccessSchema as N, importProvidersSchema as O, sourceChildrenCountsSchema as P, QMIND_MULTIPART_UPLOAD_MAX_BYTES as Q, sourcePreviewSchema as R, cardSchema as S, chatSessionSchema as T, sourceUploadTicketSchema as U, sourceTreeSchema as V, sourceWebOfficeSessionSchema as W, voidResponseSchema as X, timestampSchema as Y, wikiBranchListSchema as Z, aliDingImportRunItemListSchema as _, invalidArgument as a, cancelQuestionResultSchema as b, optionalRecord as c, pagination as d, assertCapability as et, positiveInteger as f, stringList as g, requiredText as h, httpUrl as i, retrieveResultSchema as j, notebookListSchema as k, optionalString as l, requiredString as m, call as n, executeUnary as nt, nonNegativeInteger as o, queryPath as p, taskRunListSchema as q, compactUndefined as r, QMindError as rt, optionalBoolean as s, assertNonEmptyPatch as t, executeStream as tt, optionalTrimmedString as u, aliDingImportRunSchema as v, chatSessionListSchema as w, cardListSchema as x, batchMutationResultSchema as y, sourceRawContentSchema as z };