@qoder-ai/qmind-cli 1.1.2 → 3.0.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,1147 @@
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
+ id: z.string().min(1),
570
+ name: z.string().default(""),
571
+ path: z.string().default(""),
572
+ sourceType: z.string().default(""),
573
+ status: z.string().default(""),
574
+ type: z.enum(["file", "directory"])
575
+ }));
576
+ const sourceTreeSchema = z.object({
577
+ totalSize: z.number().int().nonnegative().default(0),
578
+ tree: z.array(sourceTreeNodeSchema)
579
+ });
580
+ const sourceContentSchema = z.object({
581
+ content: z.string(),
582
+ contentType: z.string().default("text/markdown"),
583
+ size: z.number().int().nonnegative().optional(),
584
+ sourceId: z.string().default("")
585
+ });
586
+ /** proto3 JSON serializes int64 as a string, so byte counts arrive either way. */
587
+ const wireInt64Schema = z.union([z.number(), z.string()]).nullish().transform((value) => {
588
+ const parsed = typeof value === "string" ? Number(value) : value ?? 0;
589
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;
590
+ });
591
+ const sourceUploadExtensionSchema = z.string().regex(/^\.[a-z0-9]+$/);
592
+ const sourceUploadMethodSchema = z.preprocess((value) => isRecord(value) ? {
593
+ ...value,
594
+ maxSizeBytes: value.maxSizeBytes ?? value.max_size_bytes,
595
+ supportedExtensions: value.supportedExtensions ?? value.supported_extensions
596
+ } : value, z.object({
597
+ available: z.boolean(),
598
+ maxSizeBytes: wireInt64Schema,
599
+ method: z.string().min(1),
600
+ supportedExtensions: z.array(sourceUploadExtensionSchema).default([])
601
+ }));
602
+ const sourceUploadFileTypeSchema = z.preprocess((value) => isRecord(value) ? {
603
+ ...value,
604
+ displayName: value.displayName ?? value.display_name,
605
+ mimeTypes: value.mimeTypes ?? value.mime_types,
606
+ sourceType: value.sourceType ?? value.source_type,
607
+ uploadMethods: value.uploadMethods ?? value.upload_methods
608
+ } : value, z.object({
609
+ displayName: z.string().default(""),
610
+ extensions: z.array(sourceUploadExtensionSchema).default([]),
611
+ mimeTypes: z.array(z.string()).default([]),
612
+ sourceType: z.string().min(1),
613
+ uploadMethods: z.array(z.string().min(1)).default([])
614
+ }));
615
+ const sourceUploadCapabilitiesSchema = z.preprocess((value) => isRecord(value) ? {
616
+ ...value,
617
+ fileTypes: value.fileTypes ?? value.file_types,
618
+ uploadMethods: value.uploadMethods ?? value.upload_methods
619
+ } : value, z.object({
620
+ fileTypes: z.array(sourceUploadFileTypeSchema).default([]),
621
+ uploadMethods: z.array(sourceUploadMethodSchema).default([])
622
+ }));
623
+ const downloadOriginalActionAccessSchema = z.discriminatedUnion("state", [z.object({
624
+ action: z.literal("download_original"),
625
+ reason: z.undefined().optional(),
626
+ state: z.literal("allowed")
627
+ }), z.object({
628
+ action: z.literal("download_original"),
629
+ reason: z.literal("organization_policy"),
630
+ state: z.literal("denied")
631
+ })]);
632
+ const sourceActionAccessSchema = z.preprocess((value) => {
633
+ if (!isRecord(value) || !Array.isArray(value.actions)) return value;
634
+ return {
635
+ ...value,
636
+ actions: value.actions.filter((action) => {
637
+ if (!isRecord(action)) return true;
638
+ return typeof action.action !== "string" || action.action.length === 0 || action.action === "download_original";
639
+ })
640
+ };
641
+ }, z.object({ actions: z.array(downloadOriginalActionAccessSchema).length(1) }));
642
+ const sourceRawContentSchema = z.preprocess((value) => isRecord(value) ? {
643
+ ...value,
644
+ contentType: value.contentType ?? value.content_type,
645
+ sizeBytes: value.sizeBytes ?? value.size_bytes,
646
+ sourceFormat: value.sourceFormat ?? value.source_format,
647
+ sourceId: value.sourceId ?? value.source_id
648
+ } : value, z.object({
649
+ content: z.string().default(""),
650
+ contentType: z.string().default(""),
651
+ sizeBytes: wireInt64Schema,
652
+ sourceFormat: z.string().default(""),
653
+ sourceId: z.string().default("")
654
+ }));
655
+ const sourcePreviewSchema = z.preprocess((value) => isRecord(value) ? {
656
+ ...value,
657
+ contentType: value.contentType ?? value.content_type,
658
+ expiresAt: value.expiresAt ?? value.expires_at,
659
+ sourceFormat: value.sourceFormat ?? value.source_format,
660
+ sourceId: value.sourceId ?? value.source_id
661
+ } : value, z.object({
662
+ contentType: z.string().default(""),
663
+ expiresAt: timestampSchema.optional(),
664
+ sourceFormat: z.string().default(""),
665
+ sourceId: z.string().default(""),
666
+ url: httpsUrlSchema
667
+ }));
668
+ /** proto3 JSON serializes the token timeout and version as int64, so both arrive either way. */
669
+ const webOfficeTokenFields = {
670
+ accessToken: z.string().min(1),
671
+ accessTokenExpiresAt: timestampSchema.optional(),
672
+ tokenTimeoutMs: wireInt64Schema,
673
+ tokenVersion: wireInt64Schema
674
+ };
675
+ function webOfficeTokenAliases(value) {
676
+ return isRecord(value) ? {
677
+ ...value,
678
+ accessToken: value.accessToken ?? value.access_token,
679
+ accessTokenExpiresAt: value.accessTokenExpiresAt ?? value.access_token_expires_at,
680
+ tokenTimeoutMs: value.tokenTimeoutMs ?? value.token_timeout_ms,
681
+ tokenVersion: value.tokenVersion ?? value.token_version
682
+ } : value;
683
+ }
684
+ const sourceWebOfficeSessionSchema = z.preprocess((value) => {
685
+ const aliased = webOfficeTokenAliases(value);
686
+ return isRecord(aliased) ? {
687
+ ...aliased,
688
+ readOnly: aliased.readOnly ?? aliased.readonly,
689
+ sessionId: aliased.sessionId ?? aliased.session_id,
690
+ sourceFormat: aliased.sourceFormat ?? aliased.source_format,
691
+ sourceId: aliased.sourceId ?? aliased.source_id,
692
+ webOfficeUrl: aliased.webOfficeUrl ?? aliased.web_office_url
693
+ } : aliased;
694
+ }, z.object({
695
+ ...webOfficeTokenFields,
696
+ readOnly: z.boolean().default(true),
697
+ reused: z.boolean().default(false),
698
+ sessionId: z.string().min(1),
699
+ sourceFormat: z.string().default(""),
700
+ sourceId: z.string().default(""),
701
+ webOfficeUrl: httpsUrlSchema
702
+ }));
703
+ const sourceWebOfficeTokenSchema = z.preprocess(webOfficeTokenAliases, z.object(webOfficeTokenFields));
704
+ const sourceChildrenCountsSchema = z.object({ counts: z.array(z.preprocess((value) => isRecord(value) ? {
705
+ ...value,
706
+ parentId: value.parentId ?? value.parent_id
707
+ } : value, z.object({
708
+ count: z.number().int().nonnegative().default(0),
709
+ parentId: z.string().default("")
710
+ }))).nullish().transform((counts) => counts ?? []) }).transform((value) => value.counts);
711
+ 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));
712
+ const aliDingImportRunSchema = z.preprocess((value) => isRecord(value) ? {
713
+ ...value,
714
+ bindingId: value.bindingId ?? value.binding_id,
715
+ canonicalUrl: value.canonicalUrl ?? value.canonical_url,
716
+ contentFailedCount: value.contentFailedCount ?? value.content_failed_count,
717
+ contentSuccessCount: value.contentSuccessCount ?? value.content_success_count,
718
+ contentUnsupportedCount: value.contentUnsupportedCount ?? value.content_unsupported_count,
719
+ descendantsFailedCount: value.descendantsFailedCount ?? value.descendants_failed_count,
720
+ discoveredCount: value.discoveredCount ?? value.discovered_count,
721
+ documentCount: value.documentCount ?? value.document_count,
722
+ errorCode: value.errorCode ?? value.error_code,
723
+ errorMessage: value.errorMessage ?? value.error_message,
724
+ finishedAt: value.finishedAt ?? value.finished_at,
725
+ notebookId: value.notebookId ?? value.notebook_id,
726
+ processedCount: value.processedCount ?? value.processed_count,
727
+ requestId: value.requestId ?? value.request_id,
728
+ rootSourceId: value.rootSourceId ?? value.root_source_id,
729
+ startedAt: value.startedAt ?? value.started_at,
730
+ structuralCount: value.structuralCount ?? value.structural_count
731
+ } : value, z.object({
732
+ bindingId: z.string().optional(),
733
+ canonicalUrl: z.string().default(""),
734
+ contentFailedCount: wireInt64Schema,
735
+ contentSuccessCount: wireInt64Schema,
736
+ contentUnsupportedCount: wireInt64Schema,
737
+ createdAt: timestampSchema.optional(),
738
+ descendantsFailedCount: wireInt64Schema,
739
+ discoveredCount: wireInt64Schema,
740
+ documentCount: wireInt64Schema,
741
+ errorCode: z.string().default(""),
742
+ errorMessage: z.string().default(""),
743
+ finishedAt: timestampSchema.optional(),
744
+ id: z.string().min(1),
745
+ notebookId: z.string().default(""),
746
+ processedCount: wireInt64Schema,
747
+ requestId: z.string().default(""),
748
+ rootSourceId: z.string().optional(),
749
+ scope: z.string().default(""),
750
+ startedAt: timestampSchema.optional(),
751
+ status: z.string().default(""),
752
+ structuralCount: wireInt64Schema,
753
+ updatedAt: timestampSchema.optional()
754
+ })).transform((value) => ({
755
+ ...value.bindingId === void 0 ? {} : { bindingId: value.bindingId },
756
+ canonicalUrl: value.canonicalUrl,
757
+ counts: {
758
+ contentFailed: value.contentFailedCount,
759
+ contentSuccess: value.contentSuccessCount,
760
+ contentUnsupported: value.contentUnsupportedCount,
761
+ descendantsFailed: value.descendantsFailedCount,
762
+ discovered: value.discoveredCount,
763
+ document: value.documentCount,
764
+ processed: value.processedCount,
765
+ structural: value.structuralCount
766
+ },
767
+ ...value.createdAt === void 0 ? {} : { createdAt: value.createdAt },
768
+ errorCode: value.errorCode,
769
+ errorMessage: value.errorMessage,
770
+ ...value.finishedAt === void 0 ? {} : { finishedAt: value.finishedAt },
771
+ id: value.id,
772
+ notebookId: value.notebookId,
773
+ rawStatus: value.status,
774
+ requestId: value.requestId,
775
+ ...value.rootSourceId === void 0 ? {} : { rootSourceId: value.rootSourceId },
776
+ scope: normalizeQMindAliDingImportScope(value.scope),
777
+ ...value.startedAt === void 0 ? {} : { startedAt: value.startedAt },
778
+ status: normalizeQMindAliDingImportRunStatus(value.status),
779
+ ...value.updatedAt === void 0 ? {} : { updatedAt: value.updatedAt }
780
+ }));
781
+ const aliDingImportRunItemSchema = z.preprocess((value) => isRecord(value) ? {
782
+ ...value,
783
+ contentStatus: value.contentStatus ?? value.content_status,
784
+ descendantsStatus: value.descendantsStatus ?? value.descendants_status,
785
+ errorMessage: value.errorMessage ?? value.error_message,
786
+ errorReason: value.errorReason ?? value.error_reason,
787
+ nodeId: value.nodeId ?? value.node_id,
788
+ nodeKind: value.nodeKind ?? value.node_kind,
789
+ parentNodeId: value.parentNodeId ?? value.parent_node_id,
790
+ runId: value.runId ?? value.run_id,
791
+ sourceId: value.sourceId ?? value.source_id
792
+ } : value, z.object({
793
+ contentStatus: z.string().default(""),
794
+ createdAt: timestampSchema.optional(),
795
+ descendantsStatus: z.string().default(""),
796
+ errorMessage: z.string().default(""),
797
+ errorReason: z.string().default(""),
798
+ name: z.string().default(""),
799
+ nodeId: z.string().default(""),
800
+ nodeKind: z.string().default(""),
801
+ parentNodeId: z.string().default(""),
802
+ runId: z.string().default(""),
803
+ sequence: z.union([z.number(), z.string()]).default(""),
804
+ sourceId: z.string().optional(),
805
+ status: z.string().default(""),
806
+ updatedAt: timestampSchema.optional()
807
+ })).transform((value) => ({
808
+ contentStatus: normalizeQMindAliDingImportContentStatus(value.contentStatus),
809
+ ...value.createdAt === void 0 ? {} : { createdAt: value.createdAt },
810
+ descendantsStatus: normalizeQMindAliDingImportDescendantsStatus(value.descendantsStatus),
811
+ errorMessage: value.errorMessage,
812
+ errorReason: value.errorReason,
813
+ name: value.name,
814
+ nodeId: value.nodeId,
815
+ nodeKind: normalizeQMindAliDingImportNodeKind(value.nodeKind),
816
+ parentNodeId: value.parentNodeId,
817
+ runId: value.runId,
818
+ sequence: String(value.sequence),
819
+ ...value.sourceId === void 0 ? {} : { sourceId: value.sourceId },
820
+ status: normalizeQMindAliDingImportItemStatus(value.status),
821
+ ...value.updatedAt === void 0 ? {} : { updatedAt: value.updatedAt }
822
+ }));
823
+ const aliDingImportPageInfoSchema = z.preprocess((value) => isRecord(value) ? {
824
+ ...value,
825
+ currentPage: value.currentPage ?? value.current_page,
826
+ lastPage: value.lastPage ?? value.last_page,
827
+ nextPage: value.nextPage ?? value.next_page,
828
+ pageSize: value.pageSize ?? value.page_size,
829
+ prevPage: value.prevPage ?? value.prev_page,
830
+ totalSize: value.totalSize ?? value.total_size
831
+ } : value, z.object({
832
+ currentPage: z.number().int().nonnegative().default(0),
833
+ lastPage: z.number().int().nonnegative().default(0),
834
+ nextPage: wirePageNumberSchema,
835
+ pageSize: z.number().int().nonnegative().default(0),
836
+ prevPage: wirePageNumberSchema,
837
+ totalSize: wireInt64Schema
838
+ }));
839
+ const aliDingImportRunItemListSchema = z.object({
840
+ items: z.array(aliDingImportRunItemSchema).nullish().transform((items) => items ?? []),
841
+ pages: aliDingImportPageInfoSchema.optional()
842
+ });
843
+ const sourceImportResultSchema = z.object({
844
+ error: z.string().optional(),
845
+ source: sourceSchema.optional(),
846
+ url: z.string().default("")
847
+ });
848
+ const sourceImportResultsSchema = z.object({ results: z.array(sourceImportResultSchema) }).transform((value) => value.results);
849
+ const batchMutationResultSchema = z.object({
850
+ failureCount: z.number().int().nonnegative().default(0),
851
+ successCount: z.number().int().nonnegative().default(0)
852
+ });
853
+ const voidResponseSchema = z.unknown().transform(() => void 0);
854
+ const imageUploadTicketSchema = z.object({
855
+ expiresAt: z.string().optional(),
856
+ headers: z.record(z.string(), z.string()).default({}),
857
+ method: z.literal("PUT").default("PUT"),
858
+ ossKey: z.string().min(1),
859
+ uploadUrl: httpsUrlSchema
860
+ });
861
+ const imageUrlsSchema = z.object({
862
+ expiresAt: z.string().optional(),
863
+ urls: z.record(z.string(), httpsUrlSchema)
864
+ });
865
+ const notebookCitationSchema = z.preprocess((value) => isRecord(value) ? {
866
+ ...value,
867
+ chunkId: value.chunkId ?? value.chunk_id,
868
+ chunkIndex: value.chunkIndex ?? value.chunk_index,
869
+ originUrl: value.originUrl ?? value.origin_url,
870
+ sourceId: value.sourceId ?? value.source_id,
871
+ sourceTitle: value.sourceTitle ?? value.source_title,
872
+ sourceUri: value.sourceUri ?? value.source_uri
873
+ } : value, z.object({
874
+ chunkId: z.string().default(""),
875
+ chunkIndex: z.number().int().nonnegative().default(0),
876
+ metadata: z.record(z.string(), z.unknown()).optional(),
877
+ originUrl: z.string().optional(),
878
+ snippet: z.string().default(""),
879
+ sourceId: z.string().default(""),
880
+ sourceTitle: z.string().default(""),
881
+ sourceUri: z.string().default("")
882
+ }));
883
+ const chatMessageSchema = z.object({
884
+ chatSessionId: z.string().optional(),
885
+ citations: z.array(notebookCitationSchema).nullish().transform((citations) => citations === null ? [] : citations),
886
+ content: z.string().default(""),
887
+ createdAt: timestampSchema.optional(),
888
+ id: z.string().min(1),
889
+ metadata: z.record(z.string(), z.unknown()).optional(),
890
+ model: z.string().optional(),
891
+ notebookId: z.string().optional(),
892
+ orgId: z.string().optional(),
893
+ role: z.string().default(""),
894
+ sceneType: z.string().optional(),
895
+ sequence: z.number().int().nonnegative().optional(),
896
+ updatedAt: timestampSchema.optional(),
897
+ userId: z.string().optional()
898
+ });
899
+ const streamWireEventSchema = z.object({
900
+ assistantMessage: chatMessageSchema.optional(),
901
+ assistantMessageId: z.string().optional(),
902
+ cancelReason: z.string().optional(),
903
+ canceled: z.boolean().optional(),
904
+ citations: z.array(z.string()).optional(),
905
+ delta: z.string().optional(),
906
+ errorMessage: z.string().optional(),
907
+ error: z.string().optional(),
908
+ eventType: z.string().optional(),
909
+ event_type: z.string().optional(),
910
+ metadata: z.record(z.string(), z.string()).optional(),
911
+ promptContext: z.string().optional(),
912
+ reranked: z.boolean().optional(),
913
+ step: z.number().int().optional(),
914
+ toolArguments: z.string().optional(),
915
+ toolDisplayName: z.string().optional(),
916
+ toolName: z.string().optional(),
917
+ toolResult: z.string().optional(),
918
+ totalContextChunks: z.number().int().nonnegative().optional(),
919
+ type: z.string().optional(),
920
+ userMessage: chatMessageSchema.optional()
921
+ });
922
+ const sourceUploadTicketSchema = z.object({
923
+ expiresAt: z.string().optional(),
924
+ headers: z.record(z.string(), z.string()).default({}),
925
+ method: z.literal("PUT").default("PUT"),
926
+ uploadUrl: httpsUrlSchema,
927
+ uri: z.string().min(1)
928
+ });
929
+ const chatSessionSchema = z.object({
930
+ createdAt: timestampSchema.optional(),
931
+ id: z.string().min(1),
932
+ metadata: z.record(z.string(), z.unknown()).optional(),
933
+ modelOverride: z.string().default(""),
934
+ notebookId: z.string().default(""),
935
+ orgId: z.string().default(""),
936
+ sceneType: z.string().default("rag"),
937
+ status: z.string().default("active"),
938
+ title: z.string().default(""),
939
+ updatedAt: timestampSchema.optional(),
940
+ userId: z.string().default("")
941
+ });
942
+ const chatSessionListSchema = z.object({
943
+ chatSessions: z.array(chatSessionSchema).nullish().transform((sessions) => sessions ?? []),
944
+ currentPage: wirePageNumberSchema,
945
+ pageSize: wirePageNumberSchema,
946
+ totalSize: z.number().int().nonnegative().default(0)
947
+ });
948
+ const chatMessageListSchema = z.object({
949
+ currentPage: wirePageNumberSchema,
950
+ messages: z.array(chatMessageSchema).nullish().transform((messages) => messages ?? []),
951
+ pageSize: wirePageNumberSchema,
952
+ sceneType: z.string().optional(),
953
+ totalSize: z.number().int().nonnegative().default(0)
954
+ });
955
+ const notebookContextChunkSchema = z.object({
956
+ chunkId: z.string().default(""),
957
+ chunkIndex: z.number().int().nonnegative().default(0),
958
+ content: z.string().default(""),
959
+ metadata: z.record(z.string(), z.unknown()).optional(),
960
+ originUrl: z.string().optional(),
961
+ score: z.number().finite().default(0),
962
+ sourceId: z.string().default(""),
963
+ sourceTitle: z.string().default(""),
964
+ sourceUri: z.string().default(""),
965
+ tokenCount: z.number().int().nonnegative().default(0)
966
+ });
967
+ const retrievedCardLinkSchema = z.object({
968
+ description: z.string().optional(),
969
+ linkType: z.string().default(""),
970
+ targetId: z.string().min(1),
971
+ targetTitle: z.string().optional()
972
+ });
973
+ const retrievedCardSchema = z.object({
974
+ cardType: z.string().optional(),
975
+ category: z.string().optional(),
976
+ content: z.string().default(""),
977
+ depth: z.number().int().nonnegative().default(0),
978
+ id: z.string().min(1),
979
+ keywords: z.array(z.string()).default([]),
980
+ links: z.array(retrievedCardLinkSchema).default([]),
981
+ score: z.number().finite().default(0),
982
+ title: z.string().default("")
983
+ });
984
+ const retrieveResultSchema = z.object({
985
+ cards: z.array(retrievedCardSchema).default([]),
986
+ chunks: z.array(notebookContextChunkSchema).default([]),
987
+ citations: z.array(notebookCitationSchema).default([]),
988
+ promptContext: z.string().default(""),
989
+ reranked: z.boolean().default(false),
990
+ total: z.number().int().nonnegative().default(0)
991
+ });
992
+ const cancelQuestionResultSchema = z.object({ accepted: z.boolean() });
993
+ const taskRunSchema = z.object({
994
+ assistantMessageId: z.string().optional(),
995
+ chatSessionId: z.string().optional(),
996
+ config: z.record(z.string(), z.unknown()).optional(),
997
+ createdAt: timestampSchema.optional(),
998
+ durationMs: z.number().int().nonnegative().optional(),
999
+ errorMessage: z.string().optional(),
1000
+ finishedAt: timestampSchema.optional(),
1001
+ id: z.string().min(1),
1002
+ message: chatMessageSchema.optional(),
1003
+ notebookId: z.string().default(""),
1004
+ orgId: z.string().default(""),
1005
+ parentRunId: z.string().optional(),
1006
+ reportMarkdown: z.string().optional(),
1007
+ sceneType: z.string().default(""),
1008
+ scheduledTaskId: z.string().optional(),
1009
+ sourceId: z.string().optional(),
1010
+ startedAt: timestampSchema.optional(),
1011
+ stats: z.record(z.string(), z.unknown()).optional(),
1012
+ status: z.string().default(""),
1013
+ trigger: z.string().default(""),
1014
+ updatedAt: timestampSchema.optional(),
1015
+ userId: z.string().default("")
1016
+ }).transform((value) => ({
1017
+ ...value,
1018
+ rawStatus: value.status,
1019
+ status: normalizeQMindTaskRunStatus(value.status)
1020
+ }));
1021
+ const taskRunListSchema = z.object({
1022
+ currentPage: wirePageNumberSchema,
1023
+ pageSize: wirePageNumberSchema,
1024
+ runs: z.array(taskRunSchema).nullish().transform((runs) => runs ?? []),
1025
+ totalSize: z.number().int().nonnegative().default(0)
1026
+ });
1027
+ //#endregion
1028
+ //#region ../sdk/src/operations/shared.ts
1029
+ function invalidArgument(message, field, details) {
1030
+ return new QMindError("INVALID_ARGUMENT", message, { details: details ?? { field } });
1031
+ }
1032
+ function requiredString(value, field) {
1033
+ if (typeof value !== "string" || value.trim().length === 0) throw invalidArgument(`${field} must be a non-empty string`, field);
1034
+ return value.trim();
1035
+ }
1036
+ function optionalString(value, field) {
1037
+ if (value === void 0) return void 0;
1038
+ if (typeof value !== "string") throw invalidArgument(`${field} must be a string`, field);
1039
+ return value;
1040
+ }
1041
+ function optionalTrimmedString(value, field) {
1042
+ const string = optionalString(value, field)?.trim();
1043
+ return string === "" ? void 0 : string;
1044
+ }
1045
+ function optionalRecord(value, field) {
1046
+ if (value === void 0) return void 0;
1047
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidArgument(`${field} must be an object`, field);
1048
+ return value;
1049
+ }
1050
+ function optionalBoolean(value, field) {
1051
+ if (value === void 0) return void 0;
1052
+ if (typeof value !== "boolean") throw invalidArgument(`${field} must be a boolean`, field);
1053
+ return value;
1054
+ }
1055
+ function positiveInteger(value, field) {
1056
+ if (value === void 0) return void 0;
1057
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw invalidArgument(`${field} must be a positive integer`, field);
1058
+ return value;
1059
+ }
1060
+ function nonNegativeInteger(value, field) {
1061
+ if (value === void 0) return void 0;
1062
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw invalidArgument(`${field} must be a non-negative integer`, field);
1063
+ return value;
1064
+ }
1065
+ function pagination(input) {
1066
+ const page = positiveInteger(input.page, "page");
1067
+ const pageSize = positiveInteger(input.pageSize, "pageSize");
1068
+ return {
1069
+ ...page === void 0 ? {} : { page },
1070
+ ...pageSize === void 0 ? {} : { pageSize }
1071
+ };
1072
+ }
1073
+ function stringList(value, field, options = {}) {
1074
+ if (!Array.isArray(value)) throw invalidArgument(`${field} must be an array`, field);
1075
+ const result = [];
1076
+ const seen = /* @__PURE__ */ new Set();
1077
+ for (const item of value) {
1078
+ if (typeof item !== "string") throw invalidArgument(`${field} must contain only strings`, field);
1079
+ const normalized = item.trim();
1080
+ if (normalized.length === 0 || seen.has(normalized)) continue;
1081
+ seen.add(normalized);
1082
+ result.push(normalized);
1083
+ }
1084
+ if (options.min !== void 0 && result.length < options.min) throw invalidArgument(`${field} must contain at least ${options.min} item(s)`, field);
1085
+ if (options.max !== void 0 && result.length > options.max) throw invalidArgument(`${field} must contain at most ${options.max} item(s)`, field);
1086
+ return result;
1087
+ }
1088
+ function httpUrl(value, field) {
1089
+ const raw = requiredString(value, field);
1090
+ let url;
1091
+ try {
1092
+ url = new URL(raw);
1093
+ } catch (cause) {
1094
+ throw invalidArgument(`${field} must be a valid HTTP(S) URL`, field, {
1095
+ cause,
1096
+ field
1097
+ });
1098
+ }
1099
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.host.length === 0) throw invalidArgument(`${field} must be a valid HTTP(S) URL`, field);
1100
+ url.hash = "";
1101
+ return url.toString();
1102
+ }
1103
+ function compactUndefined(value) {
1104
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
1105
+ }
1106
+ function assertNonEmptyPatch(patch, field) {
1107
+ if (Object.keys(patch).length > 0) return;
1108
+ throw invalidArgument(`${field} must contain at least one change`, field);
1109
+ }
1110
+ function queryPath(path, entries) {
1111
+ const query = new URLSearchParams();
1112
+ for (const [key, value] of entries) if (value !== void 0 && value !== "") query.set(key, String(value));
1113
+ const suffix = query.toString();
1114
+ return suffix.length === 0 ? path : `${path}?${suffix}`;
1115
+ }
1116
+ function wireRequest(options) {
1117
+ const timeoutMs = options.callOptions?.timeoutMs;
1118
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw invalidArgument("timeoutMs must be a positive finite number", "timeoutMs");
1119
+ const authorization = options.callOptions?.authorization?.trim();
1120
+ return {
1121
+ ...options.body === void 0 ? {} : { body: {
1122
+ kind: "json",
1123
+ value: options.body
1124
+ } },
1125
+ destination: {
1126
+ kind: "host",
1127
+ path: options.path
1128
+ },
1129
+ ...authorization === void 0 || authorization.length === 0 ? {} : { headers: { authorization: `Bearer ${authorization}` } },
1130
+ idempotent: options.idempotent,
1131
+ method: options.method,
1132
+ ...options.callOptions?.signal === void 0 ? {} : { signal: options.callOptions.signal },
1133
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
1134
+ };
1135
+ }
1136
+ function call(context, options) {
1137
+ return executeUnary({
1138
+ capability: options.capability,
1139
+ operation: options.operation,
1140
+ profile: context.profile,
1141
+ request: wireRequest(options),
1142
+ schema: options.schema,
1143
+ transport: context.transport
1144
+ });
1145
+ }
1146
+ //#endregion
1147
+ export { executeStream as $, retrieveResultSchema as A, sourceTreeSchema as B, chatSessionListSchema as C, importProvidersSchema as D, imageUrlsSchema as E, sourceImportResultsSchema as F, streamWireEventSchema as G, sourceUploadTicketSchema as H, sourceListSchema as I, voidResponseSchema as J, taskRunListSchema as K, sourcePreviewSchema as L, sourceActionAccessSchema as M, sourceChildrenCountsSchema as N, notebookListSchema as O, sourceContentSchema as P, assertCapability as Q, sourceRawContentSchema as R, chatMessageListSchema as S, imageUploadTicketSchema as T, sourceWebOfficeSessionSchema as U, sourceUploadCapabilitiesSchema as V, sourceWebOfficeTokenSchema as W, QMIND_MULTIPART_UPLOAD_MAX_BYTES as X, wikiBranchListSchema as Y, QMIND_SOURCE_UPLOAD_MAX_BYTES as Z, aliDingImportRunSchema as _, invalidArgument as a, cardListSchema as b, optionalRecord as c, pagination as d, executeUnary as et, positiveInteger as f, aliDingImportRunItemListSchema as g, stringList as h, httpUrl as i, sharedNotebookListSchema as j, notebookSchema as k, optionalString as l, requiredString as m, call as n, nonNegativeInteger as o, queryPath as p, taskRunSchema as q, compactUndefined as r, optionalBoolean as s, assertNonEmptyPatch as t, QMindError as tt, optionalTrimmedString as u, batchMutationResultSchema as v, chatSessionSchema as w, cardSchema as x, cancelQuestionResultSchema as y, sourceSchema as z };