@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.
package/dist/qmind.js CHANGED
@@ -1,10 +1,11 @@
1
+ import { A as notebookSchema, B as sourceSchema, C as chatMessageListSchema, D as imageUrlsSchema, E as imageUploadTicketSchema, F as sourceContentSchema, G as sourceWebOfficeTokenSchema, H as sourceUploadCapabilitiesSchema, I as sourceImportResultsSchema, J as taskRunSchema, K as streamWireEventSchema, L as sourceListSchema, M as sharedNotebookListSchema, N as sourceActionAccessSchema, P as sourceChildrenCountsSchema, R as sourcePreviewSchema, T as chatSessionSchema, V as sourceTreeSchema, W as sourceWebOfficeSessionSchema, X as voidResponseSchema, Z as wikiBranchListSchema, a as invalidArgument$1, b as cancelQuestionResultSchema, c as optionalRecord, d as pagination$1, et as assertCapability, f as positiveInteger$1, g as stringList, i as httpUrl, j as retrieveResultSchema, k as notebookListSchema, l as optionalString$1, m as requiredString$2, n as call, o as nonNegativeInteger$1, p as queryPath, q as taskRunListSchema, r as compactUndefined, rt as QMindError, s as optionalBoolean, t as assertNonEmptyPatch, tt as executeStream, u as optionalTrimmedString, w as chatSessionListSchema, y as batchMutationResultSchema, z as sourceRawContentSchema } from "./shared-BkQJzIZF.js";
2
+ import { t as preflightSourceUpload } from "./source-upload-DBm1Hyki.js";
1
3
  import { createInterface } from "node:readline/promises";
4
+ import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
2
5
  import { z } from "zod";
3
- import { Command, CommanderError, Option } from "commander";
4
6
  import { createHash, randomBytes } from "node:crypto";
5
7
  import { chmod, copyFile, link, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
6
8
  import { homedir } from "node:os";
7
- import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
8
9
  import lockfile from "proper-lockfile";
9
10
  import open from "open";
10
11
  import { createReadStream, createWriteStream } from "node:fs";
@@ -12,785 +13,13 @@ import { Readable } from "node:stream";
12
13
  import { pipeline } from "node:stream/promises";
13
14
  import { createParser } from "eventsource-parser";
14
15
  import { Agent, EnvHttpProxyAgent, request } from "undici";
16
+ import { Command, CommanderError, Option } from "commander";
15
17
  import pLimit from "p-limit";
16
18
  import picomatch from "picomatch";
17
19
  import { decodeHTML } from "entities";
18
- //#region ../sdk/src/errors.ts
19
- var QMindError = class extends Error {
20
- access;
21
- code;
22
- details;
23
- operation;
24
- rawBody;
25
- requestId;
26
- status;
27
- upstreamCode;
28
- constructor(code, message, options = {}) {
29
- super(message, { cause: options.cause });
30
- this.name = "QMindError";
31
- this.access = options.access;
32
- this.code = code;
33
- this.details = options.details;
34
- this.operation = options.operation;
35
- this.rawBody = options.rawBody;
36
- this.requestId = options.requestId;
37
- this.status = options.status;
38
- this.upstreamCode = options.upstreamCode;
39
- }
40
- };
41
- //#endregion
42
- //#region ../sdk/src/execution.ts
43
- const credentialHeaders = /* @__PURE__ */ new Set([
44
- "authorization",
45
- "cookie",
46
- "proxy-authorization",
47
- "x-csrf-token",
48
- "x-xsrf-token"
49
- ]);
50
- function isRecord$5(value) {
51
- return typeof value === "object" && value !== null && !Array.isArray(value);
52
- }
53
- function nestedRecord(value, key) {
54
- const nested = value[key];
55
- return isRecord$5(nested) ? nested : void 0;
56
- }
57
- function firstString(records, keys) {
58
- for (const record of records) {
59
- if (record === void 0) continue;
60
- for (const key of keys) {
61
- const value = record[key];
62
- if (typeof value === "string" && value.length > 0) return value;
63
- }
64
- }
65
- }
66
- function headerValue(headers, name) {
67
- const normalizedName = name.toLowerCase();
68
- for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === normalizedName && value.length > 0) return value;
69
- }
70
- function errorCodeForStatus$1(status) {
71
- if (status === 401) return "AUTH_REQUIRED";
72
- if (status === 403) return "FORBIDDEN";
73
- if (status === 404) return "NOT_FOUND";
74
- if (status === 409) return "CONFLICT";
75
- if (status === 429) return "RATE_LIMITED";
76
- if (status >= 400 && status < 500) return "INVALID_ARGUMENT";
77
- return "REMOTE_ERROR";
78
- }
79
- function httpError(access, operation, profile, response) {
80
- const body = profile.unwrapError(response.body);
81
- const root = isRecord$5(body) ? body : void 0;
82
- const records = [
83
- root,
84
- root === void 0 ? void 0 : nestedRecord(root, "error"),
85
- root === void 0 ? void 0 : nestedRecord(root, "details")
86
- ];
87
- const upstreamCode = firstString(records, [
88
- "errorCode",
89
- "error_code",
90
- "code"
91
- ]);
92
- const requestId = firstString(records, ["requestId", "request_id"]) ?? headerValue(response.headers, "x-request-id") ?? headerValue(response.headers, "request-id");
93
- const message = firstString(records, [
94
- "message",
95
- "errorMessage",
96
- "error_message"
97
- ]) ?? `QMind request failed with HTTP ${response.status}`;
98
- return new QMindError(errorCodeForStatus$1(response.status), message, {
99
- access,
100
- details: body,
101
- operation,
102
- ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
103
- ...requestId === void 0 ? {} : { requestId },
104
- status: response.status,
105
- ...upstreamCode === void 0 ? {} : { upstreamCode }
106
- });
107
- }
108
- function isAbortLike(cause) {
109
- return isRecord$5(cause) && (cause.name === "AbortError" && typeof cause.name === "string" || cause.code === "ABORT_ERR");
110
- }
111
- function transportError(access, operation, request, cause) {
112
- if (cause instanceof QMindError) return cause;
113
- const aborted = request.signal?.aborted === true || isAbortLike(cause);
114
- return new QMindError(aborted ? "ABORTED" : "NETWORK_ERROR", aborted ? "QMind request was aborted" : "QMind transport failed", {
115
- access,
116
- cause,
117
- operation
118
- });
119
- }
120
- function requestWasAborted(request) {
121
- return request.signal?.aborted === true;
122
- }
123
- function assertWireRequestInvariant(request) {
124
- for (const [field, value] of [
125
- ["connectTimeoutMs", request.connectTimeoutMs],
126
- ["idleTimeoutMs", request.idleTimeoutMs],
127
- ["timeoutMs", request.timeoutMs]
128
- ]) if (!Number.isFinite(value ?? 1) || (value ?? 1) <= 0) throw new QMindError("INVALID_ARGUMENT", `${field} must be a positive finite number`, { details: { field } });
129
- if (request.destination.kind === "host") {
130
- 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 } });
131
- return;
132
- }
133
- let url;
134
- try {
135
- url = new URL(request.destination.url);
136
- } catch (cause) {
137
- throw new QMindError("HOST_POLICY_ERROR", "signed destination must be a valid HTTPS URL", {
138
- cause,
139
- details: { destination: request.destination.kind }
140
- });
141
- }
142
- 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 } });
143
- 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: {
144
- destination: request.destination.kind,
145
- header: header.toLowerCase()
146
- } });
147
- }
148
- function assertCapability(profile, capability, operation) {
149
- if (profile.capabilities[capability]) return;
150
- throw new QMindError("UNSUPPORTED_OPERATION", `${operation} is not supported by the ${profile.access} access profile`, {
151
- access: profile.access,
152
- details: { capability },
153
- operation
154
- });
155
- }
156
- async function executeUnary(options) {
157
- const { capability, operation, profile, request, schema, transport } = options;
158
- assertCapability(profile, capability, operation);
159
- assertWireRequestInvariant(request);
160
- if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", {
161
- access: profile.access,
162
- operation
163
- });
164
- let response;
165
- try {
166
- response = await transport.request(request);
167
- } catch (cause) {
168
- throw transportError(profile.access, operation, request, cause);
169
- }
170
- if (response.status < 200 || response.status >= 300) throw httpError(profile.access, operation, profile, response);
171
- const body = profile.unwrapSuccess(operation, response.body);
172
- const parsed = schema.safeParse(body);
173
- if (!parsed.success) throw new QMindError("PROTOCOL_ERROR", "server response does not match the QMind contract", {
174
- access: profile.access,
175
- details: { issues: parsed.error.issues },
176
- operation,
177
- ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
178
- status: response.status
179
- });
180
- return parsed.data;
181
- }
182
- function streamContractError(profile, operation, message, details) {
183
- return new QMindError("STREAM_ERROR", message, {
184
- access: profile.access,
185
- ...details === void 0 ? {} : { details },
186
- operation
187
- });
188
- }
189
- function streamFailureResponse(response) {
190
- return {
191
- body: response.body,
192
- headers: response.headers,
193
- ...response.rawBody === void 0 ? {} : { rawBody: response.rawBody },
194
- status: response.status
195
- };
196
- }
197
- async function* executeStream(options) {
198
- const { capability, operation, profile, request, transport } = options;
199
- assertCapability(profile, capability, operation);
200
- assertWireRequestInvariant(request);
201
- if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", {
202
- access: profile.access,
203
- operation
204
- });
205
- let response;
206
- try {
207
- response = await transport.stream(request);
208
- } catch (cause) {
209
- throw transportError(profile.access, operation, request, cause);
210
- }
211
- if (response.kind === "response") {
212
- if (response.status >= 200 && response.status < 300) throw streamContractError(profile, operation, "stream handshake returned no event stream", { status: response.status });
213
- throw httpError(profile.access, operation, profile, streamFailureResponse(response));
214
- }
215
- if (response.status < 200 || response.status >= 300) throw streamContractError(profile, operation, "stream handshake returned events for a failure status", { status: response.status });
216
- let doneMarkerSeen = false;
217
- let started = false;
218
- let terminal = false;
219
- try {
220
- for await (const payload of response.events) {
221
- if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", {
222
- access: profile.access,
223
- operation
224
- });
225
- if (payload.trim() === "[DONE]") {
226
- if (doneMarkerSeen) throw streamContractError(profile, operation, "stream emitted more than one [DONE] marker");
227
- doneMarkerSeen = true;
228
- continue;
229
- }
230
- if (doneMarkerSeen) throw streamContractError(profile, operation, "stream emitted an event after [DONE]");
231
- if (terminal) throw streamContractError(profile, operation, "stream emitted an event after messageComplete");
232
- const event = profile.decodeStreamPayload(payload);
233
- if (event.type === "error") throw streamContractError(profile, operation, event.message, { event });
234
- if (event.type === "messageStart") {
235
- if (started) throw streamContractError(profile, operation, "stream emitted duplicate messageStart");
236
- started = true;
237
- } else if (!started) throw streamContractError(profile, operation, "stream event arrived before messageStart", { eventType: event.type });
238
- if (event.type === "messageComplete") terminal = true;
239
- yield event;
240
- }
241
- } catch (cause) {
242
- throw transportError(profile.access, operation, request, cause);
243
- }
244
- if (requestWasAborted(request)) throw new QMindError("ABORTED", "QMind request was aborted", {
245
- access: profile.access,
246
- operation
247
- });
248
- if (!terminal) throw streamContractError(profile, operation, "stream ended before messageComplete", {
249
- doneMarkerSeen,
250
- started
251
- });
252
- }
253
- //#endregion
254
- //#region ../sdk/src/workflows.ts
255
- const QMIND_MULTIPART_UPLOAD_MAX_BYTES = 52428800;
256
- const QMIND_SOURCE_UPLOAD_MAX_BYTES = 524288e3;
257
- Object.freeze({
258
- canceled: {
259
- order: 2,
260
- outcome: "canceled",
261
- phase: "terminal",
262
- terminal: true
263
- },
264
- failed: {
265
- order: 2,
266
- outcome: "failure",
267
- phase: "terminal",
268
- terminal: true
269
- },
270
- partial: {
271
- order: 2,
272
- outcome: "partial",
273
- phase: "terminal",
274
- terminal: true
275
- },
276
- pending: {
277
- order: 0,
278
- outcome: "none",
279
- phase: "queued",
280
- terminal: false
281
- },
282
- running: {
283
- order: 1,
284
- outcome: "none",
285
- phase: "active",
286
- terminal: false
287
- },
288
- success: {
289
- order: 2,
290
- outcome: "success",
291
- phase: "terminal",
292
- terminal: true
293
- },
294
- unknown: {
295
- order: -1,
296
- outcome: "none",
297
- phase: "unknown",
298
- terminal: false
299
- }
300
- });
301
- function normalizeQMindTaskRunStatus(status) {
302
- switch (status.trim().toLowerCase()) {
303
- case "pending":
304
- case "running":
305
- case "success":
306
- case "partial":
307
- case "failed":
308
- case "canceled": return status.trim().toLowerCase();
309
- default: return "unknown";
310
- }
311
- }
312
- //#endregion
313
- //#region ../sdk/src/schemas.ts
314
- function isRecord$4(value) {
315
- return typeof value === "object" && value !== null && !Array.isArray(value);
316
- }
317
- const wirePageNumberSchema = z.number().int().nonnegative().optional();
318
- const timestampSchema = z.union([z.string(), z.object({
319
- nanos: z.number().int().optional(),
320
- seconds: z.union([z.number(), z.string()])
321
- })]).nullable();
322
- const notebookOverviewSchema = z.object({
323
- status: z.string().default("empty"),
324
- summary: z.string().default(""),
325
- topics: z.array(z.string()).nullish().transform((topics) => topics ?? [])
326
- });
327
- const notebookMaintenanceSchema = z.object({
328
- lastRunAt: timestampSchema.optional(),
329
- lastRunId: z.string().optional(),
330
- status: z.string().default("idle")
331
- });
332
- const notebookAccessInfoSchema = z.object({
333
- canDeleteNotebook: z.boolean(),
334
- canEdit: z.boolean(),
335
- canManageMembers: z.boolean(),
336
- canManageTasks: z.boolean(),
337
- currentUserPermission: z.string(),
338
- memberCount: z.number().int().nonnegative()
339
- });
340
- const notebookSchema = z.object({
341
- access: notebookAccessInfoSchema.nullable().optional(),
342
- client: z.string().optional(),
343
- createdAt: timestampSchema.optional(),
344
- description: z.string().default(""),
345
- id: z.string().min(1),
346
- maintenance: notebookMaintenanceSchema.optional(),
347
- materialCount: z.number().int().nonnegative().default(0),
348
- orgId: z.string().default(""),
349
- overview: notebookOverviewSchema.optional(),
350
- settings: z.record(z.string(), z.unknown()).optional(),
351
- sourceCount: z.number().int().nonnegative().default(0),
352
- status: z.string().default("active"),
353
- title: z.string(),
354
- updatedAt: timestampSchema.optional(),
355
- userId: z.string().default("")
356
- });
357
- const notebookListSchema = z.object({
358
- currentPage: wirePageNumberSchema,
359
- notebooks: z.array(notebookSchema).nullish().transform((notebooks) => notebooks ?? []),
360
- pageSize: wirePageNumberSchema,
361
- totalSize: z.number().int().nonnegative().default(0)
362
- });
363
- const wikiDocumentSchema = z.preprocess((value) => isRecord$4(value) ? {
364
- ...value,
365
- contentHash: value.contentHash ?? value.content_hash,
366
- contentUrl: value.contentUrl ?? value.content_url
367
- } : value, z.object({
368
- contentHash: z.string().default(""),
369
- contentUrl: z.string().min(1),
370
- language: z.string().default("")
371
- }));
372
- const wikiBranchSchema = z.preprocess((value) => isRecord$4(value) ? {
373
- ...value,
374
- commitTimestamp: value.commitTimestamp ?? value.commit_timestamp,
375
- knowledgeCount: value.knowledgeCount ?? value.knowledge_count,
376
- repoUrl: value.repoUrl ?? value.repo_url,
377
- resultVersion: value.resultVersion ?? value.result_version,
378
- updatedAt: value.updatedAt ?? value.updated_at
379
- } : value, z.object({
380
- branch: z.string().min(1),
381
- commitTimestamp: z.number().optional(),
382
- documents: z.array(wikiDocumentSchema).nullish().transform((documents) => documents ?? []),
383
- exists: z.boolean().optional(),
384
- knowledgeCount: z.number().int().nonnegative().default(0),
385
- repo: z.string().min(1),
386
- repoUrl: z.string().optional(),
387
- resultVersion: z.string().default(""),
388
- updatedAt: timestampSchema.optional()
389
- }));
390
- const wikiBranchListSchema = z.object({ branches: z.array(wikiBranchSchema).nullish().transform((branches) => branches ?? []) });
391
- const cardLinkSchema = z.object({
392
- description: z.string().optional(),
393
- linkType: z.string().default(""),
394
- targetId: z.string().min(1),
395
- targetTitle: z.string().optional()
396
- });
397
- const cardSchema = z.object({
398
- branch: z.string().optional(),
399
- cardType: z.string().optional(),
400
- category: z.string().optional(),
401
- content: z.string().default(""),
402
- createdAt: timestampSchema.optional(),
403
- extra: z.string().optional(),
404
- id: z.string().min(1),
405
- keywords: z.array(z.string()).default([]),
406
- knowledgeId: z.string().optional(),
407
- language: z.string().optional(),
408
- links: z.array(cardLinkSchema).default([]),
409
- notebookId: z.string().optional(),
410
- orgId: z.string().optional(),
411
- repo: z.string().optional(),
412
- score: z.number().optional(),
413
- source: z.string().optional(),
414
- title: z.string().default(""),
415
- updatedAt: timestampSchema.optional()
416
- });
417
- const cardCategoryCountSchema = z.object({
418
- category: z.string(),
419
- count: z.number().int().nonnegative()
420
- });
421
- const cardLanguageCountSchema = z.object({
422
- count: z.number().int().nonnegative(),
423
- language: z.string()
424
- });
425
- const cardAppliedFiltersSchema = z.object({
426
- branch: z.string().optional(),
427
- category: z.string().optional(),
428
- language: z.string().optional(),
429
- query: z.string().optional(),
430
- repo: z.string().optional(),
431
- source: z.string().optional()
432
- });
433
- const cardListSchema = z.object({
434
- appliedFilters: cardAppliedFiltersSchema.optional(),
435
- cards: z.array(cardSchema).nullish().transform((cards) => cards ?? []),
436
- categoryCounts: z.array(cardCategoryCountSchema).nullish().transform((counts) => counts ?? []),
437
- currentPage: wirePageNumberSchema,
438
- languageCounts: z.array(cardLanguageCountSchema).nullish().transform((counts) => counts ?? []),
439
- pageSize: wirePageNumberSchema,
440
- totalSize: z.number().int().nonnegative().default(0)
441
- });
442
- const sourcePageInfoSchema = z.object({
443
- currentPage: wirePageNumberSchema,
444
- lastPage: wirePageNumberSchema,
445
- nextPage: wirePageNumberSchema,
446
- nextToken: z.string().optional(),
447
- pageSize: wirePageNumberSchema,
448
- prevPage: wirePageNumberSchema,
449
- totalSize: z.number().int().nonnegative().optional()
450
- });
451
- const sourceSchema = z.object({
452
- childrenCount: z.number().int().nonnegative().optional(),
453
- createdAt: timestampSchema.optional(),
454
- errorMessage: z.string().default(""),
455
- filename: z.string().optional(),
456
- hasChildren: z.boolean().optional(),
457
- id: z.string().min(1),
458
- isDir: z.boolean().default(false),
459
- metadata: z.record(z.string(), z.unknown()).nullable().optional(),
460
- mimeType: z.string().optional(),
461
- name: z.string().optional(),
462
- notebookId: z.string().default(""),
463
- orgId: z.string().default(""),
464
- originUrl: z.string().optional(),
465
- parentSourceId: z.string().default(""),
466
- path: z.string().default(""),
467
- sourceType: z.string().default(""),
468
- size: z.number().int().nonnegative().optional(),
469
- status: z.string().default(""),
470
- title: z.string().default(""),
471
- updatedAt: timestampSchema.optional(),
472
- uri: z.string().default(""),
473
- userId: z.string().default("")
474
- });
475
- const sourceListSchema = z.object({
476
- currentPage: wirePageNumberSchema,
477
- pageSize: wirePageNumberSchema,
478
- pages: sourcePageInfoSchema.optional(),
479
- sources: z.array(sourceSchema).nullish().transform((sources) => sources ?? []),
480
- totalSize: z.number().int().nonnegative().optional()
481
- });
482
- const sourceTreeNodeSchema = z.lazy(() => z.object({
483
- files: z.array(sourceTreeNodeSchema).default([]),
484
- id: z.string().min(1),
485
- name: z.string().default(""),
486
- path: z.string().default(""),
487
- sourceType: z.string().default(""),
488
- status: z.string().default(""),
489
- type: z.enum(["file", "directory"])
490
- }));
491
- const sourceTreeSchema = z.object({
492
- totalSize: z.number().int().nonnegative().default(0),
493
- tree: z.array(sourceTreeNodeSchema)
494
- });
495
- const sourceContentSchema = z.object({
496
- content: z.string(),
497
- contentType: z.string().default("text/markdown"),
498
- size: z.number().int().nonnegative().optional(),
499
- sourceId: z.string().default("")
500
- });
501
- const sourceImportResultSchema = z.object({
502
- error: z.string().optional(),
503
- source: sourceSchema.optional(),
504
- url: z.string().default("")
505
- });
506
- const sourceImportResultsSchema = z.object({ results: z.array(sourceImportResultSchema) }).transform((value) => value.results);
507
- const batchMutationResultSchema = z.object({
508
- failureCount: z.number().int().nonnegative().default(0),
509
- successCount: z.number().int().nonnegative().default(0)
510
- });
511
- const voidResponseSchema = z.unknown().transform(() => void 0);
512
- const httpsUrlSchema = z.string().url().refine((value) => new URL(value).protocol === "https:", "expected an HTTPS URL");
513
- const imageUploadTicketSchema = z.object({
514
- expiresAt: z.string().optional(),
515
- headers: z.record(z.string(), z.string()).default({}),
516
- method: z.literal("PUT").default("PUT"),
517
- ossKey: z.string().min(1),
518
- uploadUrl: httpsUrlSchema
519
- });
520
- const imageUrlsSchema = z.object({
521
- expiresAt: z.string().optional(),
522
- urls: z.record(z.string(), httpsUrlSchema)
523
- });
524
- const notebookCitationSchema = z.preprocess((value) => isRecord$4(value) ? {
525
- ...value,
526
- chunkId: value.chunkId ?? value.chunk_id,
527
- chunkIndex: value.chunkIndex ?? value.chunk_index,
528
- originUrl: value.originUrl ?? value.origin_url,
529
- sourceId: value.sourceId ?? value.source_id,
530
- sourceTitle: value.sourceTitle ?? value.source_title,
531
- sourceUri: value.sourceUri ?? value.source_uri
532
- } : value, z.object({
533
- chunkId: z.string().default(""),
534
- chunkIndex: z.number().int().nonnegative().default(0),
535
- metadata: z.record(z.string(), z.unknown()).optional(),
536
- originUrl: z.string().optional(),
537
- snippet: z.string().default(""),
538
- sourceId: z.string().default(""),
539
- sourceTitle: z.string().default(""),
540
- sourceUri: z.string().default("")
541
- }));
542
- const chatMessageSchema = z.object({
543
- chatSessionId: z.string().optional(),
544
- citations: z.array(notebookCitationSchema).nullish().transform((citations) => citations === null ? [] : citations),
545
- content: z.string().default(""),
546
- createdAt: timestampSchema.optional(),
547
- id: z.string().min(1),
548
- metadata: z.record(z.string(), z.unknown()).optional(),
549
- model: z.string().optional(),
550
- notebookId: z.string().optional(),
551
- orgId: z.string().optional(),
552
- role: z.string().default(""),
553
- sceneType: z.string().optional(),
554
- sequence: z.number().int().nonnegative().optional(),
555
- updatedAt: timestampSchema.optional(),
556
- userId: z.string().optional()
557
- });
558
- const streamWireEventSchema = z.object({
559
- assistantMessage: chatMessageSchema.optional(),
560
- assistantMessageId: z.string().optional(),
561
- cancelReason: z.string().optional(),
562
- canceled: z.boolean().optional(),
563
- citations: z.array(z.string()).optional(),
564
- delta: z.string().optional(),
565
- errorMessage: z.string().optional(),
566
- error: z.string().optional(),
567
- eventType: z.string().optional(),
568
- event_type: z.string().optional(),
569
- metadata: z.record(z.string(), z.string()).optional(),
570
- promptContext: z.string().optional(),
571
- reranked: z.boolean().optional(),
572
- step: z.number().int().optional(),
573
- toolArguments: z.string().optional(),
574
- toolDisplayName: z.string().optional(),
575
- toolName: z.string().optional(),
576
- toolResult: z.string().optional(),
577
- totalContextChunks: z.number().int().nonnegative().optional(),
578
- type: z.string().optional(),
579
- userMessage: chatMessageSchema.optional()
580
- });
581
- const sourceUploadTicketSchema = z.object({
582
- expiresAt: z.string().optional(),
583
- headers: z.record(z.string(), z.string()).default({}),
584
- method: z.literal("PUT").default("PUT"),
585
- uploadUrl: httpsUrlSchema,
586
- uri: z.string().min(1)
587
- });
588
- const chatSessionSchema = z.object({
589
- createdAt: timestampSchema.optional(),
590
- id: z.string().min(1),
591
- metadata: z.record(z.string(), z.unknown()).optional(),
592
- modelOverride: z.string().default(""),
593
- notebookId: z.string().default(""),
594
- orgId: z.string().default(""),
595
- sceneType: z.string().default("rag"),
596
- status: z.string().default("active"),
597
- title: z.string().default(""),
598
- updatedAt: timestampSchema.optional(),
599
- userId: z.string().default("")
600
- });
601
- const notebookContextChunkSchema = z.object({
602
- chunkId: z.string().default(""),
603
- chunkIndex: z.number().int().nonnegative().default(0),
604
- content: z.string().default(""),
605
- metadata: z.record(z.string(), z.unknown()).optional(),
606
- originUrl: z.string().optional(),
607
- score: z.number().finite().default(0),
608
- sourceId: z.string().default(""),
609
- sourceTitle: z.string().default(""),
610
- sourceUri: z.string().default(""),
611
- tokenCount: z.number().int().nonnegative().default(0)
612
- });
613
- const retrievedCardLinkSchema = z.object({
614
- description: z.string().optional(),
615
- linkType: z.string().default(""),
616
- targetId: z.string().min(1),
617
- targetTitle: z.string().optional()
618
- });
619
- const retrievedCardSchema = z.object({
620
- cardType: z.string().optional(),
621
- category: z.string().optional(),
622
- content: z.string().default(""),
623
- depth: z.number().int().nonnegative().default(0),
624
- id: z.string().min(1),
625
- keywords: z.array(z.string()).default([]),
626
- links: z.array(retrievedCardLinkSchema).default([]),
627
- score: z.number().finite().default(0),
628
- title: z.string().default("")
629
- });
630
- const retrieveResultSchema = z.object({
631
- cards: z.array(retrievedCardSchema).default([]),
632
- chunks: z.array(notebookContextChunkSchema).default([]),
633
- citations: z.array(notebookCitationSchema).default([]),
634
- promptContext: z.string().default(""),
635
- reranked: z.boolean().default(false),
636
- total: z.number().int().nonnegative().default(0)
637
- });
638
- const cancelQuestionResultSchema = z.object({ accepted: z.boolean() });
639
- const taskRunSchema = z.object({
640
- assistantMessageId: z.string().optional(),
641
- chatSessionId: z.string().optional(),
642
- config: z.record(z.string(), z.unknown()).optional(),
643
- createdAt: timestampSchema.optional(),
644
- durationMs: z.number().int().nonnegative().optional(),
645
- errorMessage: z.string().optional(),
646
- finishedAt: timestampSchema.optional(),
647
- id: z.string().min(1),
648
- message: chatMessageSchema.optional(),
649
- notebookId: z.string().default(""),
650
- orgId: z.string().default(""),
651
- parentRunId: z.string().optional(),
652
- reportMarkdown: z.string().optional(),
653
- sceneType: z.string().default(""),
654
- scheduledTaskId: z.string().optional(),
655
- sourceId: z.string().optional(),
656
- startedAt: timestampSchema.optional(),
657
- stats: z.record(z.string(), z.unknown()).optional(),
658
- status: z.string().default(""),
659
- trigger: z.string().default(""),
660
- updatedAt: timestampSchema.optional(),
661
- userId: z.string().default("")
662
- }).transform((value) => ({
663
- ...value,
664
- rawStatus: value.status,
665
- status: normalizeQMindTaskRunStatus(value.status)
666
- }));
667
- const taskRunListSchema = z.object({
668
- currentPage: wirePageNumberSchema,
669
- pageSize: wirePageNumberSchema,
670
- runs: z.array(taskRunSchema).nullish().transform((runs) => runs ?? []),
671
- totalSize: z.number().int().nonnegative().default(0)
672
- });
673
- //#endregion
674
- //#region ../sdk/src/operations/shared.ts
675
- function invalidArgument$1(message, field, details) {
676
- return new QMindError("INVALID_ARGUMENT", message, { details: details ?? { field } });
677
- }
678
- function requiredString$2(value, field) {
679
- if (typeof value !== "string" || value.trim().length === 0) throw invalidArgument$1(`${field} must be a non-empty string`, field);
680
- return value.trim();
681
- }
682
- function optionalString$1(value, field) {
683
- if (value === void 0) return void 0;
684
- if (typeof value !== "string") throw invalidArgument$1(`${field} must be a string`, field);
685
- return value;
686
- }
687
- function optionalTrimmedString(value, field) {
688
- const string = optionalString$1(value, field)?.trim();
689
- return string === "" ? void 0 : string;
690
- }
691
- function optionalRecord(value, field) {
692
- if (value === void 0) return void 0;
693
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw invalidArgument$1(`${field} must be an object`, field);
694
- return value;
695
- }
696
- function optionalBoolean(value, field) {
697
- if (value === void 0) return void 0;
698
- if (typeof value !== "boolean") throw invalidArgument$1(`${field} must be a boolean`, field);
699
- return value;
700
- }
701
- function positiveInteger$1(value, field) {
702
- if (value === void 0) return void 0;
703
- if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw invalidArgument$1(`${field} must be a positive integer`, field);
704
- return value;
705
- }
706
- function nonNegativeInteger$1(value, field) {
707
- if (value === void 0) return void 0;
708
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw invalidArgument$1(`${field} must be a non-negative integer`, field);
709
- return value;
710
- }
711
- function pagination$1(input) {
712
- const page = positiveInteger$1(input.page, "page");
713
- const pageSize = positiveInteger$1(input.pageSize, "pageSize");
714
- return {
715
- ...page === void 0 ? {} : { page },
716
- ...pageSize === void 0 ? {} : { pageSize }
717
- };
718
- }
719
- function stringList(value, field, options = {}) {
720
- if (!Array.isArray(value)) throw invalidArgument$1(`${field} must be an array`, field);
721
- const result = [];
722
- const seen = /* @__PURE__ */ new Set();
723
- for (const item of value) {
724
- if (typeof item !== "string") throw invalidArgument$1(`${field} must contain only strings`, field);
725
- const normalized = item.trim();
726
- if (normalized.length === 0 || seen.has(normalized)) continue;
727
- seen.add(normalized);
728
- result.push(normalized);
729
- }
730
- if (options.min !== void 0 && result.length < options.min) throw invalidArgument$1(`${field} must contain at least ${options.min} item(s)`, field);
731
- if (options.max !== void 0 && result.length > options.max) throw invalidArgument$1(`${field} must contain at most ${options.max} item(s)`, field);
732
- return result;
733
- }
734
- function httpUrl(value, field) {
735
- const raw = requiredString$2(value, field);
736
- let url;
737
- try {
738
- url = new URL(raw);
739
- } catch (cause) {
740
- throw invalidArgument$1(`${field} must be a valid HTTP(S) URL`, field, {
741
- cause,
742
- field
743
- });
744
- }
745
- if (url.protocol !== "http:" && url.protocol !== "https:" || url.host.length === 0) throw invalidArgument$1(`${field} must be a valid HTTP(S) URL`, field);
746
- url.hash = "";
747
- return url.toString();
748
- }
749
- function compactUndefined(value) {
750
- return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
751
- }
752
- function assertNonEmptyPatch(patch, field) {
753
- if (Object.keys(patch).length > 0) return;
754
- throw invalidArgument$1(`${field} must contain at least one change`, field);
755
- }
756
- function queryPath(path, entries) {
757
- const query = new URLSearchParams();
758
- for (const [key, value] of entries) if (value !== void 0 && value !== "") query.set(key, String(value));
759
- const suffix = query.toString();
760
- return suffix.length === 0 ? path : `${path}?${suffix}`;
761
- }
762
- function wireRequest(options) {
763
- const timeoutMs = options.callOptions?.timeoutMs;
764
- if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw invalidArgument$1("timeoutMs must be a positive finite number", "timeoutMs");
765
- return {
766
- ...options.body === void 0 ? {} : { body: {
767
- kind: "json",
768
- value: options.body
769
- } },
770
- destination: {
771
- kind: "host",
772
- path: options.path
773
- },
774
- idempotent: options.idempotent,
775
- method: options.method,
776
- ...options.callOptions?.signal === void 0 ? {} : { signal: options.callOptions.signal },
777
- ...timeoutMs === void 0 ? {} : { timeoutMs }
778
- };
779
- }
780
- function call(context, options) {
781
- return executeUnary({
782
- capability: options.capability,
783
- operation: options.operation,
784
- profile: context.profile,
785
- request: wireRequest(options),
786
- schema: options.schema,
787
- transport: context.transport
788
- });
789
- }
790
- //#endregion
791
20
  //#region ../sdk/src/operations/agents.ts
792
21
  const workflowPrompt = "Follow the system prompt strictly: use the provided tools to discover, process and prepare the result, then emit the final report. Do NOT greet, do NOT ask for clarification — act immediately.";
793
- function isRecord$3(value) {
22
+ function isRecord$2(value) {
794
23
  return typeof value === "object" && value !== null && !Array.isArray(value);
795
24
  }
796
25
  function finiteNumber(value, field) {
@@ -834,7 +63,7 @@ function billingContext(value) {
834
63
  });
835
64
  }
836
65
  function retrieveBody(input) {
837
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
66
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
838
67
  return compactUndefined({
839
68
  billingContext: billingContext(input.billingContext),
840
69
  maxResults: nonNegativeInteger$1(input.maxResults, "maxResults"),
@@ -846,7 +75,7 @@ function retrieveBody(input) {
846
75
  });
847
76
  }
848
77
  function chatSessionBody(input = {}) {
849
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
78
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
850
79
  return compactUndefined({
851
80
  metadata: optionalRecord(input.metadata, "metadata"),
852
81
  modelOverride: optionalTrimmedString(input.modelOverride, "modelOverride"),
@@ -856,7 +85,7 @@ function chatSessionBody(input = {}) {
856
85
  });
857
86
  }
858
87
  function streamBody(input) {
859
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
88
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
860
89
  return compactUndefined({
861
90
  content: requiredString$2(input.content, "content"),
862
91
  maxResults: nonNegativeInteger$1(input.maxResults, "maxResults"),
@@ -867,7 +96,7 @@ function streamBody(input) {
867
96
  });
868
97
  }
869
98
  function taskRunBody(input) {
870
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
99
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
871
100
  return compactUndefined({
872
101
  chatSessionId: optionalTrimmedString(input.chatSessionId, "chatSessionId"),
873
102
  config: optionalRecord(input.config, "config"),
@@ -880,7 +109,7 @@ function taskRunBody(input) {
880
109
  });
881
110
  }
882
111
  function taskRunListPath(context, notebookId, input = {}) {
883
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
112
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
884
113
  const normalizedPage = pagination$1(input);
885
114
  const status = optionalTrimmedString(input.status, "status");
886
115
  if (status !== void 0 && ![
@@ -931,25 +160,40 @@ function streamCallOptions(options) {
931
160
  };
932
161
  }
933
162
  function createAgentOperations(context) {
934
- const createChatSession = (notebookId, input, options) => {
163
+ const getChatSessionFor = (notebookId, sessionId, options, featured) => {
164
+ const notebook = requiredString$2(notebookId, "notebookId");
165
+ const session = requiredString$2(sessionId, "sessionId");
166
+ return call(context, {
167
+ callOptions: options,
168
+ capability: featured ? "featuredNotebooks.read" : "chat",
169
+ idempotent: true,
170
+ method: "GET",
171
+ operation: featured ? "featuredChatSessions.get" : "chatSessions.get",
172
+ path: context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session),
173
+ schema: chatSessionSchema
174
+ });
175
+ };
176
+ const createChatSessionFor = (notebookId, input, options, featured) => {
935
177
  const notebook = requiredString$2(notebookId, "notebookId");
936
178
  return call(context, {
937
179
  body: chatSessionBody(input),
938
180
  callOptions: options,
939
- capability: "chat",
181
+ capability: featured ? "featuredNotebooks.read" : "chat",
940
182
  idempotent: false,
941
183
  method: "POST",
942
- operation: "chatSessions.create",
943
- path: context.profile.apiPath("notebooks", notebook, "chat-sessions"),
184
+ operation: featured ? "featuredChatSessions.create" : "chatSessions.create",
185
+ path: context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions"),
944
186
  schema: chatSessionSchema
945
187
  });
946
188
  };
947
- const streamQuestion = (notebookId, sessionId, input, options) => {
189
+ const createChatSession = (notebookId, input, options) => createChatSessionFor(notebookId, input, options, false);
190
+ const createFeaturedChatSession = (notebookId, input, options) => createChatSessionFor(notebookId, input, options, true);
191
+ const streamQuestionFor = (notebookId, sessionId, input, options, featured) => {
948
192
  const notebook = requiredString$2(notebookId, "notebookId");
949
193
  const session = requiredString$2(sessionId, "sessionId");
950
194
  return executeStream({
951
- capability: "chat",
952
- operation: "chat.stream",
195
+ capability: featured ? "featuredNotebooks.read" : "chat",
196
+ operation: featured ? "featuredChat.stream" : "chat.stream",
953
197
  profile: context.profile,
954
198
  request: {
955
199
  body: {
@@ -958,7 +202,7 @@ function createAgentOperations(context) {
958
202
  },
959
203
  destination: {
960
204
  kind: "host",
961
- path: queryPath(context.profile.apiPath("notebooks", notebook, "chat-sessions", session, "messages", "stream"), [["client", context.client]])
205
+ path: queryPath(context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages", "stream"), [["client", context.client]])
962
206
  },
963
207
  idempotent: false,
964
208
  method: "POST",
@@ -967,23 +211,96 @@ function createAgentOperations(context) {
967
211
  transport: context.transport
968
212
  });
969
213
  };
214
+ const streamQuestion = (notebookId, sessionId, input, options) => streamQuestionFor(notebookId, sessionId, input, options, false);
215
+ const streamFeaturedQuestion = (notebookId, sessionId, input, options) => streamQuestionFor(notebookId, sessionId, input, options, true);
216
+ const cancelQuestionFor = (notebookId, sessionId, input = {}, options, featured = false) => {
217
+ const notebook = requiredString$2(notebookId, "notebookId");
218
+ const session = requiredString$2(sessionId, "sessionId");
219
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
220
+ return call(context, {
221
+ body: compactUndefined({ reason: optionalTrimmedString(input.reason, "reason") }),
222
+ callOptions: options,
223
+ capability: featured ? "featuredNotebooks.read" : "chat",
224
+ idempotent: false,
225
+ method: "POST",
226
+ operation: featured ? "featuredChat.cancel" : "chat.cancel",
227
+ path: context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages", "cancel"),
228
+ schema: cancelQuestionResultSchema
229
+ });
230
+ };
231
+ const listChatSessionsFor = (notebookId, input = {}, options, featured = false) => {
232
+ const notebook = requiredString$2(notebookId, "notebookId");
233
+ const normalizedPage = pagination$1({
234
+ page: input.page ?? 1,
235
+ pageSize: input.pageSize ?? 20
236
+ });
237
+ return call(context, {
238
+ callOptions: options,
239
+ capability: featured ? "featuredNotebooks.read" : "chat",
240
+ idempotent: true,
241
+ method: "GET",
242
+ operation: featured ? "featuredChatSessions.list" : "chatSessions.list",
243
+ path: queryPath(context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions"), [["page", normalizedPage.page], ["page_size", normalizedPage.pageSize]]),
244
+ schema: chatSessionListSchema
245
+ });
246
+ };
247
+ const listChatMessagesFor = (notebookId, sessionId, input = {}, options, featured = false) => {
248
+ const notebook = requiredString$2(notebookId, "notebookId");
249
+ const session = requiredString$2(sessionId, "sessionId");
250
+ const normalizedPage = pagination$1({
251
+ page: input.page ?? 1,
252
+ pageSize: input.pageSize ?? 100
253
+ });
254
+ return call(context, {
255
+ callOptions: options,
256
+ capability: featured ? "featuredNotebooks.read" : "chat",
257
+ idempotent: true,
258
+ method: "GET",
259
+ operation: featured ? "featuredChatMessages.list" : "chatMessages.list",
260
+ path: queryPath(context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages"), [["page", normalizedPage.page], ["page_size", normalizedPage.pageSize]]),
261
+ schema: chatMessageListSchema
262
+ });
263
+ };
264
+ const deleteChatSessionFor = (notebookId, sessionId, options, featured = false) => {
265
+ const notebook = requiredString$2(notebookId, "notebookId");
266
+ const session = requiredString$2(sessionId, "sessionId");
267
+ return call(context, {
268
+ callOptions: options,
269
+ capability: featured ? "featuredChat.delete" : "chat",
270
+ idempotent: false,
271
+ method: "DELETE",
272
+ operation: featured ? "featuredChatSessions.delete" : "chatSessions.delete",
273
+ path: context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session),
274
+ schema: voidResponseSchema
275
+ });
276
+ };
277
+ const startAgentRunFor = async (notebookId, input, options, featured) => {
278
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
279
+ if (input.scene !== "rag" && input.scene !== "compilation" && input.scene !== "lint") throw invalidArgument$1("scene must be rag, compilation or lint", "scene");
280
+ const notebook = requiredString$2(notebookId, "notebookId");
281
+ const scene = input.scene;
282
+ const modelOverride = optionalTrimmedString(input.modelOverride, "modelOverride");
283
+ const title = optionalString$1(input.title, "title");
284
+ const session = await (featured ? createFeaturedChatSession : createChatSession)(notebook, {
285
+ ...modelOverride === void 0 ? {} : { modelOverride },
286
+ sceneType: scene,
287
+ ...title === void 0 ? {} : { title }
288
+ }, options);
289
+ return {
290
+ events: (featured ? streamFeaturedQuestion : streamQuestion)(notebook, session.id, agentContent(input), options),
291
+ scene,
292
+ session
293
+ };
294
+ };
970
295
  return {
971
- async cancelQuestion(notebookId, sessionId, input = {}, options) {
972
- const notebook = requiredString$2(notebookId, "notebookId");
973
- const session = requiredString$2(sessionId, "sessionId");
974
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
975
- return call(context, {
976
- body: compactUndefined({ reason: optionalTrimmedString(input.reason, "reason") }),
977
- callOptions: options,
978
- capability: "chat",
979
- idempotent: false,
980
- method: "POST",
981
- operation: "chat.cancel",
982
- path: context.profile.apiPath("notebooks", notebook, "chat-sessions", session, "messages", "cancel"),
983
- schema: cancelQuestionResultSchema
984
- });
985
- },
296
+ getChatSession: (notebookId, sessionId, options) => getChatSessionFor(notebookId, sessionId, options, false),
297
+ getFeaturedChatSession: (notebookId, sessionId, options) => getChatSessionFor(notebookId, sessionId, options, true),
298
+ cancelFeaturedQuestion: (notebookId, sessionId, input, options) => cancelQuestionFor(notebookId, sessionId, input, options, true),
299
+ cancelQuestion: (notebookId, sessionId, input, options) => cancelQuestionFor(notebookId, sessionId, input, options),
986
300
  createChatSession,
301
+ createFeaturedChatSession,
302
+ deleteChatSession: (notebookId, sessionId, options) => deleteChatSessionFor(notebookId, sessionId, options),
303
+ deleteFeaturedChatSession: (notebookId, sessionId, options) => deleteChatSessionFor(notebookId, sessionId, options, true),
987
304
  async createTaskRun(notebookId, input, options) {
988
305
  const notebook = requiredString$2(notebookId, "notebookId");
989
306
  return call(context, {
@@ -1011,16 +328,21 @@ function createAgentOperations(context) {
1011
328
  });
1012
329
  },
1013
330
  async listTaskRuns(notebookId, input, options) {
331
+ const notebook = requiredString$2(notebookId, "notebookId");
1014
332
  return call(context, {
1015
333
  callOptions: options,
1016
334
  capability: "taskRuns.read",
1017
335
  idempotent: true,
1018
336
  method: "GET",
1019
337
  operation: "taskRuns.list",
1020
- path: taskRunListPath(context, requiredString$2(notebookId, "notebookId"), input),
338
+ path: taskRunListPath(context, notebook, input),
1021
339
  schema: taskRunListSchema
1022
340
  });
1023
341
  },
342
+ listChatMessages: (notebookId, sessionId, input, options) => listChatMessagesFor(notebookId, sessionId, input, options),
343
+ listChatSessions: (notebookId, input, options) => listChatSessionsFor(notebookId, input, options),
344
+ listFeaturedChatMessages: (notebookId, sessionId, input, options) => listChatMessagesFor(notebookId, sessionId, input, options, true),
345
+ listFeaturedChatSessions: (notebookId, input, options) => listChatSessionsFor(notebookId, input, options, true),
1024
346
  async retrieve(notebookId, input, options) {
1025
347
  const notebook = requiredString$2(notebookId, "notebookId");
1026
348
  return call(context, {
@@ -1034,96 +356,28 @@ function createAgentOperations(context) {
1034
356
  schema: retrieveResultSchema
1035
357
  });
1036
358
  },
1037
- async startAgentRun(notebookId, input, options) {
1038
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
1039
- if (input.scene !== "rag" && input.scene !== "compilation" && input.scene !== "lint") throw invalidArgument$1("scene must be rag, compilation or lint", "scene");
1040
- const notebook = requiredString$2(notebookId, "notebookId");
1041
- const scene = input.scene;
1042
- const modelOverride = optionalTrimmedString(input.modelOverride, "modelOverride");
1043
- const title = optionalString$1(input.title, "title");
1044
- const session = await createChatSession(notebook, {
1045
- ...modelOverride === void 0 ? {} : { modelOverride },
1046
- sceneType: scene,
1047
- ...title === void 0 ? {} : { title }
1048
- }, options);
1049
- return {
1050
- events: streamQuestion(notebook, session.id, agentContent(input), options),
1051
- scene,
1052
- session
1053
- };
1054
- },
359
+ startAgentRun: (notebookId, input, options) => startAgentRunFor(notebookId, input, options, false),
360
+ startFeaturedAgentRun: (notebookId, input, options) => startAgentRunFor(notebookId, input, options, true),
361
+ streamFeaturedQuestion,
1055
362
  streamQuestion
1056
363
  };
1057
364
  }
1058
365
  //#endregion
1059
- //#region ../sdk/src/operations/cards.ts
1060
- function createCardOperations(context) {
366
+ //#region ../sdk/src/operations/notebooks.ts
367
+ function createNotebookOperations(context) {
1061
368
  return {
1062
- async batchDeleteCards(notebookId, cardIds, options) {
369
+ async copyFeaturedNotebook(notebookId, options) {
1063
370
  const notebook = requiredString$2(notebookId, "notebookId");
1064
371
  return call(context, {
1065
- body: { cardIds: stringList(cardIds, "cardIds", { min: 1 }) },
1066
372
  callOptions: options,
1067
- capability: "cards.write",
373
+ capability: "featuredNotebooks.copy",
1068
374
  idempotent: false,
1069
375
  method: "POST",
1070
- operation: "cards.batchDelete",
1071
- path: context.profile.apiPath("notebooks", notebook, "cards", "batch-delete"),
1072
- schema: batchMutationResultSchema
1073
- });
1074
- },
1075
- async deleteCard(notebookId, cardId, options) {
1076
- const notebook = requiredString$2(notebookId, "notebookId");
1077
- const card = requiredString$2(cardId, "cardId");
1078
- return call(context, {
1079
- callOptions: options,
1080
- capability: "cards.write",
1081
- idempotent: false,
1082
- method: "DELETE",
1083
- operation: "cards.delete",
1084
- path: context.profile.apiPath("notebooks", notebook, "cards", card),
1085
- schema: batchMutationResultSchema
1086
- });
1087
- },
1088
- async getCard(notebookId, cardId, options) {
1089
- const notebook = requiredString$2(notebookId, "notebookId");
1090
- const card = requiredString$2(cardId, "cardId");
1091
- return call(context, {
1092
- callOptions: options,
1093
- capability: "cards.read",
1094
- idempotent: true,
1095
- method: "GET",
1096
- operation: "cards.get",
1097
- path: context.profile.apiPath("notebooks", notebook, "cards", card),
1098
- schema: cardSchema
376
+ operation: "featuredNotebooks.copy",
377
+ path: context.profile.apiPath("featured-notebooks", notebook, "copy"),
378
+ schema: notebookSchema
1099
379
  });
1100
380
  },
1101
- async listCards(notebookId, input = {}, options) {
1102
- const notebook = requiredString$2(notebookId, "notebookId");
1103
- const normalizedPage = pagination$1(input);
1104
- const category = optionalTrimmedString(input.category, "category");
1105
- const query = optionalTrimmedString(input.query, "query");
1106
- return call(context, {
1107
- callOptions: options,
1108
- capability: "cards.read",
1109
- idempotent: true,
1110
- method: "GET",
1111
- operation: "cards.list",
1112
- path: queryPath(context.profile.apiPath("notebooks", notebook, "cards"), [
1113
- ["category", category],
1114
- ["query", query],
1115
- ["page", normalizedPage.page],
1116
- ["page_size", normalizedPage.pageSize]
1117
- ]),
1118
- schema: cardListSchema
1119
- });
1120
- }
1121
- };
1122
- }
1123
- //#endregion
1124
- //#region ../sdk/src/operations/notebooks.ts
1125
- function createNotebookOperations(context) {
1126
- return {
1127
381
  async createNotebook(input, options) {
1128
382
  const title = requiredString$2(input?.title, "title");
1129
383
  const description = optionalString$1(input?.description, "description");
@@ -1168,6 +422,30 @@ function createNotebookOperations(context) {
1168
422
  schema: notebookSchema
1169
423
  });
1170
424
  },
425
+ async getFeaturedNotebook(notebookId, options) {
426
+ const id = requiredString$2(notebookId, "notebookId");
427
+ return call(context, {
428
+ callOptions: options,
429
+ capability: "featuredNotebooks.read",
430
+ idempotent: true,
431
+ method: "GET",
432
+ operation: "featuredNotebooks.get",
433
+ path: context.profile.featuredNotebookPath(id),
434
+ schema: notebookSchema
435
+ });
436
+ },
437
+ async listFeaturedNotebooks(input = {}, options) {
438
+ const normalized = pagination$1(input);
439
+ return call(context, {
440
+ callOptions: options,
441
+ capability: "featuredNotebooks.read",
442
+ idempotent: true,
443
+ method: "GET",
444
+ operation: "featuredNotebooks.list",
445
+ path: context.profile.listFeaturedNotebooksPath(normalized),
446
+ schema: notebookListSchema
447
+ });
448
+ },
1171
449
  async listNotebooks(input = {}, options) {
1172
450
  const normalizedPage = pagination$1(input);
1173
451
  const client = optionalTrimmedString(input.client, "client");
@@ -1186,6 +464,18 @@ function createNotebookOperations(context) {
1186
464
  schema: notebookListSchema
1187
465
  });
1188
466
  },
467
+ async listSharedNotebooks(input = {}, options) {
468
+ const normalized = pagination$1(input);
469
+ return call(context, {
470
+ callOptions: options,
471
+ capability: "sharedNotebooks.read",
472
+ idempotent: true,
473
+ method: "GET",
474
+ operation: "sharedNotebooks.list",
475
+ path: context.profile.listSharedNotebooksPath(normalized),
476
+ schema: sharedNotebookListSchema
477
+ });
478
+ },
1189
479
  async listWikiBranches(notebookId, options) {
1190
480
  const id = requiredString$2(notebookId, "notebookId");
1191
481
  return (await call(context, {
@@ -1246,15 +536,17 @@ function createsSourceCycle(source, sourcesById) {
1246
536
  }
1247
537
  function buildSourceTree(sources) {
1248
538
  const sourcesById = new Map(sources.map((source) => [source.id, source]));
539
+ const parentIds = new Set(sources.filter((source) => sourcesById.has(source.parentSourceId) && !createsSourceCycle(source, sourcesById)).map((source) => source.parentSourceId));
1249
540
  const nodesById = /* @__PURE__ */ new Map();
1250
541
  for (const source of sources) nodesById.set(source.id, {
1251
542
  files: [],
543
+ hasChildren: source.hasChildren ?? (source.childrenCount === void 0 ? source.isDir : source.childrenCount > 0),
1252
544
  id: source.id,
1253
545
  name: source.title,
1254
546
  path: source.path,
1255
547
  sourceType: source.sourceType,
1256
548
  status: source.status,
1257
- type: source.isDir ? "directory" : "file"
549
+ type: source.isDir || parentIds.has(source.id) ? "directory" : "file"
1258
550
  });
1259
551
  const tree = [];
1260
552
  for (const source of sources) {
@@ -1304,9 +596,10 @@ function siteBody(input) {
1304
596
  const includePaths = stringList(input?.includePaths ?? [], "includePaths");
1305
597
  const excludePaths = stringList(input?.excludePaths ?? [], "excludePaths");
1306
598
  const sitemap = optionalTrimmedString(input?.sitemapUrl, "sitemapUrl");
599
+ const compileAfterRefresh = optionalBoolean(input?.compileAfterRefresh, "compileAfterRefresh");
1307
600
  return compactUndefined({
1308
601
  config: compactUndefined({
1309
- compileAfterRefresh: optionalBoolean(input?.compileAfterRefresh, "compileAfterRefresh"),
602
+ compileAfterRefresh,
1310
603
  excludePaths,
1311
604
  includePaths,
1312
605
  maxPages,
@@ -1358,24 +651,94 @@ function createSourceOperations(context) {
1358
651
  if (view === "children") assertCapability(context.profile, "sources.children", "sources.list");
1359
652
  if (query !== void 0) assertCapability(context.profile, "sources.search", "sources.list");
1360
653
  if (parentSourceId !== void 0 && view !== "children") throw invalidArgument$1("parentSourceId requires view=\"children\"", "parentSourceId");
654
+ const path = queryPath(context.profile.apiPath("notebooks", notebook, "sources"), [
655
+ ["view", view === "list" ? void 0 : view],
656
+ ["is_dir", isDir === void 0 ? void 0 : String(isDir)],
657
+ ["parent_source_id", parentSourceId],
658
+ ["page", normalizedPage.page],
659
+ ["page_size", normalizedPage.pageSize],
660
+ ["query", query]
661
+ ]);
1361
662
  return call(context, {
1362
663
  callOptions: options,
1363
664
  capability: "sources.read",
1364
665
  idempotent: true,
1365
666
  method: "GET",
1366
667
  operation,
1367
- path: queryPath(context.profile.apiPath("notebooks", notebook, "sources"), [
668
+ path,
669
+ schema: sourceListSchema
670
+ });
671
+ };
672
+ const listSources = (notebookId, input, options) => readSourcePage(notebookId, input, options);
673
+ const normalizeChildrenPage = (page) => ({
674
+ ...page,
675
+ sources: page.sources.map((source) => ({
676
+ ...source,
677
+ hasChildren: source.hasChildren ?? (source.childrenCount === void 0 ? source.isDir : source.childrenCount > 0)
678
+ }))
679
+ });
680
+ const isMissingChildrenRoute = (error) => error instanceof QMindError && (error.status === 404 || error.status === 405 || error.upstreamCode?.toLowerCase() === "routenotfound");
681
+ const listFeaturedSources = async (notebookId, input = {}, options) => {
682
+ const notebook = requiredString$2(notebookId, "notebookId");
683
+ const normalizedPage = pagination$1({
684
+ page: input.page ?? 1,
685
+ pageSize: input.pageSize ?? 200
686
+ });
687
+ const parentSourceId = optionalString$1(input.parentSourceId, "parentSourceId");
688
+ const view = input.view ?? "list";
689
+ if (view !== "list" && view !== "children") throw invalidArgument$1("view must be either \"list\" or \"children\"", "view");
690
+ return call(context, {
691
+ callOptions: options,
692
+ capability: "featuredNotebooks.read",
693
+ idempotent: true,
694
+ method: "GET",
695
+ operation: "featuredSources.list",
696
+ path: queryPath(context.profile.apiPath("featured-notebooks", notebook, "sources"), [
1368
697
  ["view", view === "list" ? void 0 : view],
1369
- ["is_dir", isDir === void 0 ? void 0 : String(isDir)],
1370
698
  ["parent_source_id", parentSourceId],
1371
699
  ["page", normalizedPage.page],
1372
- ["page_size", normalizedPage.pageSize],
1373
- ["query", query]
700
+ ["page_size", normalizedPage.pageSize]
1374
701
  ]),
1375
702
  schema: sourceListSchema
1376
703
  });
1377
704
  };
1378
- const listSources = (notebookId, input, options) => readSourcePage(notebookId, input, options);
705
+ const listSourceChildrenPage = async (featured, notebookId, input, options) => {
706
+ const notebook = requiredString$2(notebookId, "notebookId");
707
+ const { page, pageSize } = pagination$1({
708
+ page: input.page ?? 1,
709
+ pageSize: input.pageSize ?? 100
710
+ });
711
+ const parentSourceId = optionalString$1(input.parentSourceId, "parentSourceId");
712
+ const collection = featured ? "featured-notebooks" : "notebooks";
713
+ const operation = featured ? "featuredSources.children.list" : "sources.children.list";
714
+ if (featured || context.profile.access !== "sash") try {
715
+ const result = await call(context, {
716
+ callOptions: options,
717
+ capability: featured ? "featuredNotebooks.read" : "sources.children",
718
+ idempotent: true,
719
+ method: "GET",
720
+ operation,
721
+ path: queryPath(context.profile.apiPath(collection, notebook, "source-tree", "children"), [
722
+ ["parent_source_id", parentSourceId],
723
+ ["page", page],
724
+ ["page_size", pageSize]
725
+ ]),
726
+ schema: sourceListSchema.nullable()
727
+ });
728
+ if (result !== null) return normalizeChildrenPage(result);
729
+ } catch (error) {
730
+ if (!isMissingChildrenRoute(error)) throw error;
731
+ }
732
+ const fallbackInput = {
733
+ page,
734
+ pageSize,
735
+ parentSourceId,
736
+ view: "children"
737
+ };
738
+ return normalizeChildrenPage(featured ? await listFeaturedSources(notebook, fallbackInput, options) : await readSourcePage(notebook, fallbackInput, options, "sources.children.list"));
739
+ };
740
+ const listSourceChildren = (notebookId, input = {}, options) => listSourceChildrenPage(false, notebookId, input, options);
741
+ const listFeaturedSourceChildren = (notebookId, input = {}, options) => listSourceChildrenPage(true, notebookId, input, options);
1379
742
  const collectAllSources = async (notebookId, input = {}, options, operation) => {
1380
743
  const notebook = requiredString$2(notebookId, "notebookId");
1381
744
  const pageSize = positiveInteger$1(input.pageSize, "pageSize") ?? 200;
@@ -1418,8 +781,9 @@ function createSourceOperations(context) {
1418
781
  return {
1419
782
  async batchDeleteSources(notebookId, sourceIds, options) {
1420
783
  const notebook = requiredString$2(notebookId, "notebookId");
784
+ const ids = stringList(sourceIds, "sourceIds", { min: 1 });
1421
785
  return call(context, {
1422
- body: { sourceIds: stringList(sourceIds, "sourceIds", { min: 1 }) },
786
+ body: { sourceIds: ids },
1423
787
  callOptions: options,
1424
788
  capability: "sources.write",
1425
789
  idempotent: false,
@@ -1429,6 +793,26 @@ function createSourceOperations(context) {
1429
793
  schema: batchMutationResultSchema
1430
794
  });
1431
795
  },
796
+ async countSourceChildren(notebookId, parentIds, options) {
797
+ const notebook = requiredString$2(notebookId, "notebookId");
798
+ const ids = stringList(parentIds, "parentIds", {
799
+ max: 200,
800
+ min: 1
801
+ });
802
+ assertCapability(context.profile, "sources.childrenCount", "sources.childrenCount");
803
+ const path = context.profile.mindPath("notebooks", notebook, "sources", "children-count");
804
+ const query = new URLSearchParams();
805
+ for (const id of ids) query.append("parent_ids", id);
806
+ return call(context, {
807
+ callOptions: options,
808
+ capability: "sources.childrenCount",
809
+ idempotent: true,
810
+ method: "GET",
811
+ operation: "sources.childrenCount",
812
+ path: `${path}?${query.toString()}`,
813
+ schema: sourceChildrenCountsSchema
814
+ });
815
+ },
1432
816
  async createDirectory(notebookId, input, options) {
1433
817
  const title = requiredString$2(input?.title, "title");
1434
818
  return createSource(notebookId, {
@@ -1440,6 +824,20 @@ function createSourceOperations(context) {
1440
824
  }, options);
1441
825
  },
1442
826
  createSource,
827
+ async createSourceWebOfficeSession(notebookId, sourceId, options) {
828
+ const notebook = requiredString$2(notebookId, "notebookId");
829
+ const source = requiredString$2(sourceId, "sourceId");
830
+ assertCapability(context.profile, "sources.webOffice", "sources.webOffice.create");
831
+ return call(context, {
832
+ callOptions: options,
833
+ capability: "sources.webOffice",
834
+ idempotent: false,
835
+ method: "POST",
836
+ operation: "sources.webOffice.create",
837
+ path: context.profile.apiPath("notebooks", notebook, "sources", source, "weboffice", "session"),
838
+ schema: sourceWebOfficeSessionSchema
839
+ });
840
+ },
1443
841
  async deleteSource(notebookId, sourceId, options) {
1444
842
  const notebook = requiredString$2(notebookId, "notebookId");
1445
843
  const source = requiredString$2(sourceId, "sourceId");
@@ -1453,6 +851,58 @@ function createSourceOperations(context) {
1453
851
  schema: voidResponseSchema
1454
852
  });
1455
853
  },
854
+ async getFeaturedSource(notebookId, sourceId, options) {
855
+ const notebook = requiredString$2(notebookId, "notebookId");
856
+ const source = requiredString$2(sourceId, "sourceId");
857
+ return call(context, {
858
+ callOptions: options,
859
+ capability: "featuredNotebooks.read",
860
+ idempotent: true,
861
+ method: "GET",
862
+ operation: "featuredSources.get",
863
+ path: context.profile.apiPath("featured-notebooks", notebook, "sources", source),
864
+ schema: sourceSchema
865
+ });
866
+ },
867
+ async getFeaturedSourceContent(notebookId, sourceId, options) {
868
+ const notebook = requiredString$2(notebookId, "notebookId");
869
+ const source = requiredString$2(sourceId, "sourceId");
870
+ return call(context, {
871
+ callOptions: options,
872
+ capability: "featuredNotebooks.read",
873
+ idempotent: true,
874
+ method: "GET",
875
+ operation: "featuredSources.content",
876
+ path: context.profile.apiPath("featured-notebooks", notebook, "sources", source, "content"),
877
+ schema: sourceContentSchema
878
+ });
879
+ },
880
+ async getFeaturedSourcePreview(notebookId, sourceId, options) {
881
+ const notebook = requiredString$2(notebookId, "notebookId");
882
+ const source = requiredString$2(sourceId, "sourceId");
883
+ return call(context, {
884
+ callOptions: options,
885
+ capability: "featuredNotebooks.read",
886
+ idempotent: true,
887
+ method: "GET",
888
+ operation: "featuredSources.preview",
889
+ path: context.profile.apiPath("featured-notebooks", notebook, "sources", source, "preview"),
890
+ schema: sourcePreviewSchema
891
+ });
892
+ },
893
+ async getFeaturedSourceRawContent(notebookId, sourceId, options) {
894
+ const notebook = requiredString$2(notebookId, "notebookId");
895
+ const source = requiredString$2(sourceId, "sourceId");
896
+ return call(context, {
897
+ callOptions: options,
898
+ capability: "featuredNotebooks.read",
899
+ idempotent: true,
900
+ method: "GET",
901
+ operation: "featuredSources.rawContent",
902
+ path: context.profile.apiPath("featured-notebooks", notebook, "sources", source, "raw-content"),
903
+ schema: sourceRawContentSchema
904
+ });
905
+ },
1456
906
  async getSource(notebookId, sourceId, options) {
1457
907
  const notebook = requiredString$2(notebookId, "notebookId");
1458
908
  const source = requiredString$2(sourceId, "sourceId");
@@ -1479,7 +929,66 @@ function createSourceOperations(context) {
1479
929
  schema: sourceContentSchema
1480
930
  });
1481
931
  },
932
+ async getSourceActionAccess(options) {
933
+ return call(context, {
934
+ callOptions: options,
935
+ capability: "sources.actionAccess",
936
+ idempotent: true,
937
+ method: "GET",
938
+ operation: "sources.actionAccess",
939
+ path: context.profile.mindPath("source-actions", "access"),
940
+ schema: sourceActionAccessSchema
941
+ });
942
+ },
943
+ async getSourcePreview(notebookId, sourceId, options) {
944
+ const notebook = requiredString$2(notebookId, "notebookId");
945
+ const source = requiredString$2(sourceId, "sourceId");
946
+ return call(context, {
947
+ callOptions: options,
948
+ capability: "sources.preview",
949
+ idempotent: true,
950
+ method: "GET",
951
+ operation: "sources.preview",
952
+ path: context.profile.apiPath("notebooks", notebook, "sources", source, "preview"),
953
+ schema: sourcePreviewSchema
954
+ });
955
+ },
956
+ async getSourceRawContent(notebookId, sourceId, options) {
957
+ const notebook = requiredString$2(notebookId, "notebookId");
958
+ const source = requiredString$2(sourceId, "sourceId");
959
+ return call(context, {
960
+ callOptions: options,
961
+ capability: "sources.rawContent",
962
+ idempotent: true,
963
+ method: "GET",
964
+ operation: "sources.rawContent",
965
+ path: context.profile.apiPath("notebooks", notebook, "sources", source, "raw-content"),
966
+ schema: sourceRawContentSchema
967
+ });
968
+ },
969
+ async getSourceUploadCapabilities(options) {
970
+ return call(context, {
971
+ callOptions: options,
972
+ capability: "sources.write",
973
+ idempotent: true,
974
+ method: "GET",
975
+ operation: "sources.uploadCapabilities",
976
+ path: context.profile.mindPath("source-upload", "capabilities"),
977
+ schema: sourceUploadCapabilitiesSchema
978
+ });
979
+ },
980
+ preflightSourceUpload(notebookId, options) {
981
+ return preflightSourceUpload(context, notebookId, options);
982
+ },
983
+ async getFeaturedSourceTree(notebookId, options) {
984
+ return buildSourceTree((await listFeaturedSources(notebookId, {
985
+ page: 1,
986
+ pageSize: 200
987
+ }, options)).sources);
988
+ },
1482
989
  getSourceTree,
990
+ listFeaturedSourceChildren,
991
+ listSourceChildren,
1483
992
  async importSite(notebookId, input, options) {
1484
993
  const notebook = requiredString$2(notebookId, "notebookId");
1485
994
  return call(context, {
@@ -1503,6 +1012,7 @@ function createSourceOperations(context) {
1503
1012
  body: compactUndefined({
1504
1013
  parentSourceId: optionalString$1(input?.parentSourceId, "parentSourceId"),
1505
1014
  path: optionalString$1(input?.path, "path"),
1015
+ sourceType: "url",
1506
1016
  urls
1507
1017
  }),
1508
1018
  callOptions: options,
@@ -1514,7 +1024,30 @@ function createSourceOperations(context) {
1514
1024
  schema: sourceImportResultsSchema
1515
1025
  });
1516
1026
  },
1027
+ async importWikiDocuments(notebookId, input, options) {
1028
+ const notebook = requiredString$2(notebookId, "notebookId");
1029
+ const urls = stringList(input?.urls ?? [], "urls", {
1030
+ max: 5,
1031
+ min: 1
1032
+ });
1033
+ return call(context, {
1034
+ body: compactUndefined({
1035
+ parentSourceId: optionalString$1(input?.parentSourceId, "parentSourceId"),
1036
+ path: "/repowiki",
1037
+ sourceType: "repowiki",
1038
+ urls
1039
+ }),
1040
+ callOptions: options,
1041
+ capability: "sources.write",
1042
+ idempotent: false,
1043
+ method: "POST",
1044
+ operation: "sources.importWiki",
1045
+ path: context.profile.apiPath("notebooks", notebook, "sources"),
1046
+ schema: sourceImportResultsSchema
1047
+ });
1048
+ },
1517
1049
  listAllSources,
1050
+ listFeaturedSources,
1518
1051
  listSources,
1519
1052
  async moveSource(notebookId, sourceId, input, options) {
1520
1053
  const parentSourceId = optionalString$1(input?.parentSourceId, "parentSourceId");
@@ -1553,257 +1086,79 @@ function createSourceOperations(context) {
1553
1086
  schema: imageUploadTicketSchema
1554
1087
  });
1555
1088
  },
1556
- async presignImageUrls(notebookId, ossKeys, options) {
1089
+ async refreshSourceWebOfficeSession(notebookId, sourceId, input, options) {
1557
1090
  const notebook = requiredString$2(notebookId, "notebookId");
1091
+ const source = requiredString$2(sourceId, "sourceId");
1092
+ const sessionId = requiredString$2(input?.sessionId, "sessionId");
1093
+ const tokenVersion = nonNegativeInteger$1(input?.tokenVersion, "tokenVersion") ?? 0;
1094
+ assertCapability(context.profile, "sources.webOffice", "sources.webOffice.refresh");
1558
1095
  return call(context, {
1559
- body: { ossKeys: stringList(ossKeys, "ossKeys", {
1560
- max: 100,
1561
- min: 1
1562
- }) },
1096
+ body: { tokenVersion },
1563
1097
  callOptions: options,
1564
- capability: "images.presignUrls",
1098
+ capability: "sources.webOffice",
1565
1099
  idempotent: false,
1566
1100
  method: "POST",
1567
- operation: "images.presignUrls",
1568
- path: context.profile.apiPath("notebooks", notebook, "images", "presign-urls"),
1569
- schema: imageUrlsSchema
1101
+ operation: "sources.webOffice.refresh",
1102
+ path: context.profile.apiPath("notebooks", notebook, "sources", source, "weboffice", "session", sessionId, "refresh"),
1103
+ schema: sourceWebOfficeTokenSchema
1570
1104
  });
1571
1105
  },
1572
- updateSource
1573
- };
1574
- }
1575
- //#endregion
1576
- //#region ../sdk/src/operations/transfers.ts
1577
- function isRecord$2(value) {
1578
- return typeof value === "object" && value !== null && !Array.isArray(value);
1579
- }
1580
- function binarySource(value) {
1581
- if (!isRecord$2(value)) throw invalidArgument$1("source must be a QMindBinarySource", "source");
1582
- const filename = requiredString$2(value.filename, "source.filename");
1583
- const mimeType = requiredString$2(value.mimeType, "source.mimeType");
1584
- const size = value.size;
1585
- if (typeof size !== "number" || !Number.isSafeInteger(size) || size <= 0) throw invalidArgument$1("source.size must be a positive safe integer", "source.size");
1586
- if (typeof value.open !== "function") throw invalidArgument$1("source.open must be a function", "source.open");
1587
- const source = value;
1588
- return {
1589
- filename,
1590
- mimeType,
1591
- open: () => source.open(),
1592
- size
1593
- };
1594
- }
1595
- function transferOptions(options) {
1596
- if (options === void 0) return {};
1597
- if (!isRecord$2(options)) throw invalidArgument$1("options must be an object", "options");
1598
- if (options.onProgress !== void 0 && typeof options.onProgress !== "function") throw invalidArgument$1("onProgress must be a function", "onProgress");
1599
- return options;
1600
- }
1601
- function uploadMetadata(value) {
1602
- if (value === void 0) return {};
1603
- if (!isRecord$2(value)) throw invalidArgument$1("metadata must be an object", "metadata");
1604
- return {
1605
- parentSourceId: optionalString$1(value.parentSourceId, "parentSourceId"),
1606
- path: optionalString$1(value.path, "path"),
1607
- sha256: optionalTrimmedString(value.sha256, "sha256"),
1608
- sourceType: optionalTrimmedString(value.sourceType, "sourceType"),
1609
- title: optionalTrimmedString(value.title, "title")
1610
- };
1611
- }
1612
- function progressReporter(context, operation, strategy, totalBytes, options) {
1613
- let lastUploadedBytes = 0;
1614
- const notify = (phase, uploadedBytes) => {
1615
- if (!Number.isSafeInteger(uploadedBytes) || uploadedBytes < lastUploadedBytes) throw new QMindError("HOST_POLICY_ERROR", "upload progress must be a monotonic integer", {
1616
- access: context.profile.access,
1617
- details: {
1618
- lastUploadedBytes,
1619
- totalBytes,
1620
- uploadedBytes
1621
- },
1622
- operation
1623
- });
1624
- if (uploadedBytes > totalBytes) throw new QMindError("HOST_POLICY_ERROR", "upload progress exceeds source size", {
1625
- access: context.profile.access,
1626
- details: {
1627
- totalBytes,
1628
- uploadedBytes
1629
- },
1630
- operation
1631
- });
1632
- lastUploadedBytes = uploadedBytes;
1633
- const progress = {
1634
- phase,
1635
- strategy,
1636
- totalBytes,
1637
- uploadedBytes
1638
- };
1639
- options.onProgress?.(progress);
1640
- };
1641
- return {
1642
- complete: () => notify("uploading", totalBytes),
1643
- registering: () => notify("registering", totalBytes),
1644
- start: () => notify("uploading", 0),
1645
- update: (uploadedBytes) => notify("uploading", uploadedBytes)
1646
- };
1647
- }
1648
- function requestOptions(options) {
1649
- return {
1650
- ...options.signal === void 0 ? {} : { signal: options.signal },
1651
- ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
1652
- };
1653
- }
1654
- function transferCall(context, operation, request, schema) {
1655
- return executeUnary({
1656
- capability: operation.startsWith("images.") ? "images.presignUpload" : "transfers",
1657
- operation,
1658
- profile: context.profile,
1659
- request,
1660
- schema,
1661
- transport: context.transport
1662
- });
1663
- }
1664
- function hostRequest(path, method, idempotent, options, body) {
1665
- return {
1666
- body,
1667
- destination: {
1668
- kind: "host",
1669
- path
1670
- },
1671
- idempotent,
1672
- method,
1673
- ...requestOptions(options)
1674
- };
1675
- }
1676
- function signedUploadRequest(ticket, source, progress, options) {
1677
- return {
1678
- body: {
1679
- kind: "binary",
1680
- onProgress: progress.update,
1681
- source
1682
- },
1683
- destination: {
1684
- kind: "signed",
1685
- url: ticket.uploadUrl
1686
- },
1687
- headers: ticket.headers,
1688
- idempotent: true,
1689
- method: "PUT",
1690
- ...requestOptions(options)
1691
- };
1692
- }
1693
- function createTransferOperations(context) {
1694
- return {
1695
- async uploadImage(notebookId, sourceId, rawSource, rawOptions) {
1106
+ async presignImageUrls(notebookId, ossKeys, options) {
1696
1107
  const notebook = requiredString$2(notebookId, "notebookId");
1697
- const sourceIdValue = requiredString$2(sourceId, "sourceId");
1698
- const source = binarySource(rawSource);
1699
- const options = transferOptions(rawOptions);
1700
- if (source.size > 52428800) throw new QMindError("FILE_TOO_LARGE", "image exceeds the 50 MiB upload limit", {
1701
- access: context.profile.access,
1702
- details: {
1703
- limitBytes: QMIND_MULTIPART_UPLOAD_MAX_BYTES,
1704
- size: source.size
1705
- },
1706
- operation: "images.upload"
1108
+ const keys = stringList(ossKeys, "ossKeys", {
1109
+ max: 100,
1110
+ min: 1
1111
+ });
1112
+ return call(context, {
1113
+ body: { ossKeys: keys },
1114
+ callOptions: options,
1115
+ capability: "images.presignUrls",
1116
+ idempotent: false,
1117
+ method: "POST",
1118
+ operation: "images.presignUrls",
1119
+ path: context.profile.apiPath("notebooks", notebook, "images", "presign-urls"),
1120
+ schema: imageUrlsSchema
1707
1121
  });
1708
- const ticket = await transferCall(context, "images.presignUpload", hostRequest(context.profile.apiPath("notebooks", notebook, "sources", sourceIdValue, "images", "presign"), "POST", false, options, {
1709
- kind: "json",
1710
- value: {
1711
- filename: source.filename,
1712
- mimeType: source.mimeType,
1713
- size: source.size
1714
- }
1715
- }), imageUploadTicketSchema);
1716
- const progress = progressReporter(context, "images.upload", "presigned", source.size, options);
1717
- progress.start();
1718
- await transferCall(context, "images.upload", signedUploadRequest(ticket, source, progress, options), voidResponseSchema);
1719
- progress.complete();
1720
- return ticket;
1721
1122
  },
1722
- async uploadSource(notebookId, rawSource, rawMetadata, rawOptions) {
1723
- const notebook = requiredString$2(notebookId, "notebookId");
1724
- const source = binarySource(rawSource);
1725
- const metadata = uploadMetadata(rawMetadata);
1726
- const options = transferOptions(rawOptions);
1727
- if (source.size > 524288e3) throw new QMindError("FILE_TOO_LARGE", "file exceeds the 500 MiB upload limit", {
1728
- access: context.profile.access,
1729
- details: {
1730
- limitBytes: QMIND_SOURCE_UPLOAD_MAX_BYTES,
1731
- size: source.size
1732
- },
1733
- operation: "transfers.source.multipart"
1734
- });
1735
- if (source.size <= 52428800) {
1736
- const progress = progressReporter(context, "transfers.source.multipart", "multipart", source.size, options);
1737
- progress.start();
1738
- const fields = compactUndefined({
1739
- parent_source_id: metadata.parentSourceId,
1740
- path: metadata.path,
1741
- retain_original_file: "true",
1742
- source_type: metadata.sourceType,
1743
- title: metadata.title
1744
- });
1745
- const result = await transferCall(context, "transfers.source.multipart", hostRequest(queryPath(context.profile.apiPath("notebooks", notebook, "sources", "upload"), [["client", context.client]]), "POST", false, options, {
1746
- file: source,
1747
- fields,
1748
- kind: "multipart",
1749
- onProgress: progress.update
1750
- }), sourceSchema);
1751
- progress.complete();
1752
- return result;
1753
- }
1754
- const ticket = await transferCall(context, "transfers.source.presign", hostRequest(context.profile.apiPath("notebooks", notebook, "sources", "presign"), "POST", false, options, {
1755
- kind: "json",
1756
- value: {
1757
- filename: source.filename,
1758
- mimeType: source.mimeType,
1759
- size: source.size
1760
- }
1761
- }), sourceUploadTicketSchema);
1762
- const progress = progressReporter(context, "transfers.source.upload", "presigned", source.size, options);
1763
- progress.start();
1764
- await transferCall(context, "transfers.source.upload", signedUploadRequest(ticket, source, progress, options), voidResponseSchema);
1765
- progress.complete();
1766
- progress.registering();
1767
- return transferCall(context, "transfers.source.register", hostRequest(context.profile.apiPath("notebooks", notebook, "sources", "register"), "POST", false, options, {
1768
- kind: "json",
1769
- value: compactUndefined({
1770
- filename: source.filename,
1771
- mimeType: source.mimeType,
1772
- parentSourceId: metadata.parentSourceId,
1773
- path: metadata.path,
1774
- sha256: metadata.sha256,
1775
- size: source.size,
1776
- sourceType: metadata.sourceType,
1777
- title: metadata.title,
1778
- uri: ticket.uri
1779
- })
1780
- }), sourceSchema);
1781
- }
1123
+ updateSource
1782
1124
  };
1783
1125
  }
1784
1126
  //#endregion
1785
1127
  //#region ../sdk/src/capabilities.ts
1786
1128
  const dashboardCapabilities = Object.freeze({
1787
- botGateway: false,
1129
+ botGateway: true,
1788
1130
  "cards.read": true,
1789
1131
  "cards.write": true,
1132
+ "cards.saveResults": true,
1790
1133
  chat: true,
1791
- "featuredNotebooks.read": false,
1134
+ "featuredChat.delete": false,
1135
+ compilation: true,
1136
+ "featuredNotebooks.read": true,
1137
+ "featuredNotebooks.copy": true,
1792
1138
  "images.presignUpload": false,
1793
1139
  "images.presignUrls": false,
1794
- members: false,
1140
+ "imports.aliDing": true,
1141
+ "imports.discover": true,
1142
+ members: true,
1795
1143
  "notebooks.filterByClient": false,
1796
1144
  "notebooks.read": true,
1797
1145
  "notebooks.write": true,
1798
- "notes.read": false,
1799
- "notes.write": false,
1146
+ "notes.read": true,
1147
+ "notes.write": true,
1148
+ "notes.saveCondensation": true,
1800
1149
  retrieval: true,
1801
- scheduledTasks: false,
1150
+ scheduledTasks: true,
1151
+ "sharedNotebooks.read": true,
1802
1152
  "sources.children": true,
1153
+ "sources.childrenCount": true,
1154
+ "sources.actionAccess": false,
1803
1155
  "sources.importWeb": true,
1156
+ "sources.preview": true,
1157
+ "sources.rawContent": true,
1804
1158
  "sources.read": true,
1805
1159
  "sources.search": true,
1806
1160
  "sources.tree": true,
1161
+ "sources.webOffice": true,
1807
1162
  "sources.write": true,
1808
1163
  "taskRuns.read": true,
1809
1164
  "taskRuns.write": true,
@@ -1814,23 +1169,36 @@ const sashCapabilities = Object.freeze({
1814
1169
  botGateway: false,
1815
1170
  "cards.read": true,
1816
1171
  "cards.write": true,
1172
+ "cards.saveResults": false,
1817
1173
  chat: true,
1174
+ "featuredChat.delete": false,
1175
+ compilation: false,
1818
1176
  "featuredNotebooks.read": false,
1177
+ "featuredNotebooks.copy": true,
1819
1178
  "images.presignUpload": true,
1820
1179
  "images.presignUrls": true,
1180
+ "imports.aliDing": false,
1181
+ "imports.discover": false,
1821
1182
  members: false,
1822
1183
  "notebooks.filterByClient": true,
1823
1184
  "notebooks.read": true,
1824
1185
  "notebooks.write": true,
1825
- "notes.read": false,
1826
- "notes.write": false,
1186
+ "notes.read": true,
1187
+ "notes.write": true,
1188
+ "notes.saveCondensation": false,
1827
1189
  retrieval: true,
1828
1190
  scheduledTasks: false,
1829
- "sources.children": false,
1830
- "sources.importWeb": false,
1191
+ "sharedNotebooks.read": false,
1192
+ "sources.children": true,
1193
+ "sources.childrenCount": false,
1194
+ "sources.actionAccess": true,
1195
+ "sources.importWeb": true,
1196
+ "sources.preview": true,
1197
+ "sources.rawContent": true,
1831
1198
  "sources.read": true,
1832
1199
  "sources.search": false,
1833
1200
  "sources.tree": true,
1201
+ "sources.webOffice": true,
1834
1202
  "sources.write": true,
1835
1203
  "taskRuns.read": true,
1836
1204
  "taskRuns.write": true,
@@ -1993,6 +1361,12 @@ function createProfile(access, apiPrefix) {
1993
1361
  decodeStreamPayload(payload) {
1994
1362
  return decodeStreamPayload(access, payload);
1995
1363
  },
1364
+ featuredNotebookPath(notebookId) {
1365
+ return notebookId === void 0 ? apiPath("featured-notebooks") : apiPath("featured-notebooks", notebookId);
1366
+ },
1367
+ listFeaturedNotebooksPath(input) {
1368
+ return appendQuery(`${apiPrefix}/featured-notebooks`, [["page", input.page], ["page_size", input.pageSize]]);
1369
+ },
1996
1370
  listNotebooksPath(input) {
1997
1371
  return appendQuery(`${apiPrefix}/notebooks`, [
1998
1372
  ["page", input.page],
@@ -2000,6 +1374,12 @@ function createProfile(access, apiPrefix) {
2000
1374
  ["client", input.client]
2001
1375
  ]);
2002
1376
  },
1377
+ listSharedNotebooksPath(input) {
1378
+ return appendQuery(`${apiPrefix}/notebooks/shared`, [["page", input.page], ["page_size", input.pageSize]]);
1379
+ },
1380
+ mindPath(...segments) {
1381
+ return `/api/v1/mind/${segments.map((segment) => encodeId(segment)).join("/")}`;
1382
+ },
2003
1383
  notebookPath(notebookId) {
2004
1384
  return notebookId === void 0 ? apiPath("notebooks") : apiPath("notebooks", notebookId);
2005
1385
  },
@@ -2031,6 +1411,109 @@ function isQMindTransport(value) {
2031
1411
  if (!isRecord(value)) return false;
2032
1412
  return typeof value.request === "function" && typeof value.stream === "function";
2033
1413
  }
1414
+ const managementOperationNames = [
1415
+ "addMember",
1416
+ "createScheduledTask",
1417
+ "deleteScheduledTask",
1418
+ "getCompilationSettings",
1419
+ "getCompilationStatus",
1420
+ "listMembers",
1421
+ "listScheduledTasks",
1422
+ "removeMember",
1423
+ "saveCompilationSettings",
1424
+ "startCompilation",
1425
+ "updateMemberPermission",
1426
+ "updateScheduledTask"
1427
+ ];
1428
+ const cardOperationNames = [
1429
+ "batchDeleteCards",
1430
+ "deleteCard",
1431
+ "getCard",
1432
+ "listCards",
1433
+ "listFeaturedCards",
1434
+ "saveCompilationResult"
1435
+ ];
1436
+ const importOperationNames = [
1437
+ "getAliDingImportRun",
1438
+ "listAliDingImportRunItems",
1439
+ "listImportProviders",
1440
+ "startAliDingKnowledgeBaseImport",
1441
+ "startAliDingNodeSubtreeImport"
1442
+ ];
1443
+ const noteOperationNames = [
1444
+ "createNote",
1445
+ "deleteNote",
1446
+ "getNote",
1447
+ "listNotes",
1448
+ "saveCondensationResult",
1449
+ "updateNote"
1450
+ ];
1451
+ const botGatewayOperationNames = [
1452
+ "listPlatformApps",
1453
+ "createPlatformApp",
1454
+ "updatePlatformApp",
1455
+ "deletePlatformApp",
1456
+ "listExpertBindings",
1457
+ "updateExpertBinding",
1458
+ "deleteExpertBinding",
1459
+ "listGroupBindings",
1460
+ "createGroupBinding",
1461
+ "updateGroupBinding",
1462
+ "deleteGroupBinding",
1463
+ "publishDingTalk",
1464
+ "inviteDingTalkExpert"
1465
+ ];
1466
+ function createLazyTransferOperations(context) {
1467
+ let operations;
1468
+ const load = () => {
1469
+ operations ??= import("./transfers-F1ZLLBdU.js").then(({ createTransferOperations }) => createTransferOperations(context));
1470
+ return operations;
1471
+ };
1472
+ return {
1473
+ uploadImage: (...args) => load().then((loaded) => loaded.uploadImage(...args)),
1474
+ uploadSource: (...args) => load().then((loaded) => loaded.uploadSource(...args))
1475
+ };
1476
+ }
1477
+ function createLazyBotGatewayOperations(context) {
1478
+ let operations;
1479
+ const load = () => {
1480
+ operations ??= import("./bot-gateway-Hzjl50zu.js").then(({ createBotGatewayOperations }) => createBotGatewayOperations(context));
1481
+ return operations;
1482
+ };
1483
+ return Object.fromEntries(botGatewayOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
1484
+ }
1485
+ function createLazyNoteOperations(context) {
1486
+ let operations;
1487
+ const load = () => {
1488
+ operations ??= import("./notes-BvucEfdi.js").then(({ createNoteOperations }) => createNoteOperations(context));
1489
+ return operations;
1490
+ };
1491
+ return Object.fromEntries(noteOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
1492
+ }
1493
+ function createLazyCardOperations(context) {
1494
+ let operations;
1495
+ const load = () => {
1496
+ operations ??= import("./cards-DsMbd-g1.js").then(({ createCardOperations }) => createCardOperations(context));
1497
+ return operations;
1498
+ };
1499
+ return Object.fromEntries(cardOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
1500
+ }
1501
+ function createLazyImportOperations(context) {
1502
+ let operations;
1503
+ const load = () => {
1504
+ operations ??= import("./imports-B01ERZgD.js").then(({ createImportOperations }) => createImportOperations(context));
1505
+ return operations;
1506
+ };
1507
+ return Object.fromEntries(importOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
1508
+ }
1509
+ function createLazyManagementOperations(context) {
1510
+ let operations;
1511
+ const load = () => {
1512
+ operations ??= import("./management-BIYQa9Al.js").then(({ createManagementOperations }) => createManagementOperations(context));
1513
+ return operations;
1514
+ };
1515
+ return Object.fromEntries(managementOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
1516
+ }
2034
1517
  function createQMindClient(options) {
2035
1518
  if (!isRecord(options)) throw invalidArgument$1("client options must be an object", "options");
2036
1519
  if (!isQMindAccess(options.access)) throw invalidArgument$1("access must be either \"sash\" or \"dashboard\"", "access");
@@ -2045,9 +1528,13 @@ function createQMindClient(options) {
2045
1528
  access: profile.access,
2046
1529
  capabilities: profile.capabilities,
2047
1530
  ...createNotebookOperations(context),
2048
- ...createCardOperations(context),
1531
+ ...createLazyCardOperations(context),
2049
1532
  ...createSourceOperations(context),
2050
- ...createTransferOperations(context),
1533
+ ...createLazyImportOperations(context),
1534
+ ...createLazyManagementOperations(context),
1535
+ ...createLazyNoteOperations(context),
1536
+ ...createLazyBotGatewayOperations(context),
1537
+ ...createLazyTransferOperations(context),
2051
1538
  ...createAgentOperations(context),
2052
1539
  supports(capability) {
2053
1540
  return profile.capabilities[capability] === true;
@@ -2055,65 +1542,6 @@ function createQMindClient(options) {
2055
1542
  });
2056
1543
  }
2057
1544
  //#endregion
2058
- //#region src/argv.ts
2059
- const SHORT_OPTIONS = /* @__PURE__ */ new Set([
2060
- "-h",
2061
- "-V",
2062
- "-o",
2063
- "-q"
2064
- ]);
2065
- /**
2066
- * Preserve the historical Go CLI spelling where long options used one dash.
2067
- * The delimiter is an intentional hard boundary: everything after `--` is a
2068
- * positional value and must remain byte-for-byte unchanged.
2069
- */
2070
- function normalizeLegacyArgv(argv) {
2071
- let positionalOnly = false;
2072
- return argv.map((argument) => {
2073
- if (argument === "--") {
2074
- positionalOnly = true;
2075
- return argument;
2076
- }
2077
- if (positionalOnly || SHORT_OPTIONS.has(argument) || argument.startsWith("--")) return argument;
2078
- if (/^-[A-Za-z][A-Za-z0-9-]+(?:=.*)?$/.test(argument)) return `-${argument}`;
2079
- return argument;
2080
- });
2081
- }
2082
- /** Runtime errors use the JSON error envelope only when the caller explicitly
2083
- * selected JSON, except folder sync whose compatibility default is JSON. */
2084
- function requestsJsonOutput(argv) {
2085
- let explicitFormat;
2086
- let positionalOnly = false;
2087
- for (let index = 0; index < argv.length; index += 1) {
2088
- const argument = argv[index];
2089
- if (argument === "--") {
2090
- positionalOnly = true;
2091
- continue;
2092
- }
2093
- if (positionalOnly) continue;
2094
- if (argument === "--format" || argument === "-format") {
2095
- explicitFormat = argv[index + 1];
2096
- index += 1;
2097
- continue;
2098
- }
2099
- const match = argument?.match(/^--?format=(.*)$/);
2100
- if (match !== null && match !== void 0) explicitFormat = match[1];
2101
- }
2102
- if (explicitFormat !== void 0) return explicitFormat === "json";
2103
- return argv[0] === "upload-folder" || argv[0] === "sync";
2104
- }
2105
- //#endregion
2106
- //#region src/build-info.ts
2107
- const QMIND_CLI_VERSION = "2.0.0";
2108
- const QMIND_CLI_BUILD_TIME = "development";
2109
- const QMIND_CLI_UPDATE_BASE_URL = typeof __QMIND_CLI_UPDATE_BASE_URL__ === "string" ? __QMIND_CLI_UPDATE_BASE_URL__ : "https://qoder-ide-cn.oss-cn-hangzhou.aliyuncs.com/qmind/cli/";
2110
- function qmindCliPlatform() {
2111
- return process.platform === "win32" ? "windows" : process.platform;
2112
- }
2113
- function qmindCliArchitecture() {
2114
- return process.arch === "x64" ? "amd64" : process.arch;
2115
- }
2116
- //#endregion
2117
1545
  //#region ../node-host/src/auth.ts
2118
1546
  const responseRecordSchema = z.record(z.string(), z.unknown());
2119
1547
  const personalTokenExchangeSchema = z.object({ token: z.string().min(1) });
@@ -2336,7 +1764,7 @@ function createQMindCliAuthManager(options) {
2336
1764
  if (token.length > 0) return token;
2337
1765
  const candidate = explicitToken || credentials?.deviceToken || "";
2338
1766
  if (candidate.length === 0) {
2339
- if (options.config.nonInteractive) throw new QMindError("AUTH_REQUIRED", "no credentials found; run 'qmind login' in an interactive terminal");
1767
+ if (options.config.nonInteractive) throw new QMindError("AUTH_REQUIRED", `no credentials found; run '${options.loginCommand ?? "qmind login"}' in an interactive terminal`);
2340
1768
  await login();
2341
1769
  return token;
2342
1770
  }
@@ -2372,18 +1800,32 @@ function createQMindCliAuthManager(options) {
2372
1800
  //#endregion
2373
1801
  //#region ../node-host/src/authenticated-transport.ts
2374
1802
  function withBearer(request, token) {
1803
+ const headers = Object.fromEntries(Object.entries(request.headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization"));
2375
1804
  return {
2376
1805
  ...request,
2377
1806
  headers: {
2378
- ...request.headers,
1807
+ ...headers,
2379
1808
  authorization: `Bearer ${token}`
2380
1809
  }
2381
1810
  };
2382
1811
  }
2383
- function createAuthenticatedQMindTransport(transport, auth) {
1812
+ /** A caller-supplied per-request bearer wins over process-level auth and skips refresh. */
1813
+ function hasRequestAuthorization(request) {
1814
+ const headers = request.headers;
1815
+ if (headers === void 0) return false;
1816
+ return Object.keys(headers).some((name) => name.toLowerCase() === "authorization");
1817
+ }
1818
+ function hostCredentialRequired() {
1819
+ return new QMindError("AUTH_REQUIRED", "The embedding host did not provide a credential for this request.");
1820
+ }
1821
+ function createAuthenticatedQMindTransport(transport, auth, requestCredential) {
2384
1822
  return Object.freeze({
2385
1823
  async request(request) {
2386
1824
  if (request.destination.kind === "signed") return await transport.request(request);
1825
+ const providedToken = (await requestCredential?.())?.trim();
1826
+ if (providedToken) return await transport.request(withBearer(request, providedToken));
1827
+ if (hasRequestAuthorization(request)) return await transport.request(request);
1828
+ if (requestCredential !== void 0) throw hostCredentialRequired();
2387
1829
  const token = await auth.getToken();
2388
1830
  const response = await transport.request(withBearer(request, token));
2389
1831
  if (response.status !== 401) return response;
@@ -2391,6 +1833,10 @@ function createAuthenticatedQMindTransport(transport, auth) {
2391
1833
  return await transport.request(withBearer(request, refreshed));
2392
1834
  },
2393
1835
  async stream(request) {
1836
+ const providedToken = (await requestCredential?.())?.trim();
1837
+ if (providedToken) return await transport.stream(withBearer(request, providedToken));
1838
+ if (hasRequestAuthorization(request)) return await transport.stream(request);
1839
+ if (requestCredential !== void 0) throw hostCredentialRequired();
2394
1840
  const token = await auth.getToken();
2395
1841
  const response = await transport.stream(withBearer(request, token));
2396
1842
  if (response.kind !== "response" || response.status !== 401) return response;
@@ -2426,10 +1872,31 @@ const PRESETS = Object.freeze({
2426
1872
  sashOrigin: "https://test-openapi.qoder.sh"
2427
1873
  }
2428
1874
  });
1875
+ /**
1876
+ * Embedding product identity → that product's backends per environment. Two products share neither
1877
+ * dashboard nor Sash, so a host that declares its identity must be routed by it; falling back to the
1878
+ * environment table alone would send the second product's requests to the first product's backend,
1879
+ * which is indistinguishable from a correct call on the wire.
1880
+ *
1881
+ * Cells that no backend exists for yet are absent rather than borrowed: resolving one throws.
1882
+ */
1883
+ const PRODUCT_PRESETS = Object.freeze({
1884
+ qoder: PRESETS,
1885
+ "qoder-cn": Object.freeze({
1886
+ prod: {
1887
+ dashboardOrigin: "https://qoder.cn",
1888
+ sashOrigin: "https://openapi.qoder.com.cn"
1889
+ },
1890
+ test: {
1891
+ dashboardOrigin: "https://test.qoder.com.cn",
1892
+ sashOrigin: "https://test-openapi.qoder.com.cn"
1893
+ }
1894
+ })
1895
+ });
2429
1896
  function invalidConfig(message, field) {
2430
1897
  return new QMindError("INVALID_ARGUMENT", message, { ...field === void 0 ? {} : { details: { field } } });
2431
1898
  }
2432
- function normalizeOrigin$1(rawValue, field) {
1899
+ function normalizeQMindOrigin(rawValue, field) {
2433
1900
  let url;
2434
1901
  try {
2435
1902
  url = new URL(rawValue);
@@ -2439,6 +1906,17 @@ function normalizeOrigin$1(rawValue, field) {
2439
1906
  if (url.protocol !== "http:" && url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0 || url.pathname !== "/" || url.search.length > 0 || url.hash.length > 0) throw invalidConfig(`${field} must contain only an HTTP(S) scheme and authority`, field);
2440
1907
  return url.origin;
2441
1908
  }
1909
+ /**
1910
+ * Resolves one registered product/environment without fallback. The default Host config loader
1911
+ * invokes this lazily after explicit overrides; fixed-product callers select the target up front.
1912
+ */
1913
+ function resolveQMindProductEndpoints(productId, presetName, field = "env") {
1914
+ const presets = Object.hasOwn(PRODUCT_PRESETS, productId) ? PRODUCT_PRESETS[productId] : void 0;
1915
+ if (presets === void 0) throw invalidConfig(`no QMind endpoints are registered for product ${JSON.stringify(productId)}`, field);
1916
+ const preset = Object.hasOwn(presets, presetName) ? presets[presetName] : void 0;
1917
+ if (preset === void 0) throw invalidConfig(`product ${JSON.stringify(productId)} has no ${JSON.stringify(presetName)} endpoints; set ${field} explicitly`, field);
1918
+ return { ...preset };
1919
+ }
2442
1920
  function optionalTrimmed(value) {
2443
1921
  const trimmed = value?.trim();
2444
1922
  return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
@@ -2487,31 +1965,73 @@ async function mergedEnvironment(environment, legacyEnvironmentPath) {
2487
1965
  }
2488
1966
  return merged;
2489
1967
  }
2490
- async function fileConfiguration(homeDirectory) {
1968
+ async function fileConfiguration(homeDirectory, fixedEndpoints = false) {
2491
1969
  try {
2492
1970
  return fileConfigSchema.parse(JSON.parse(await readFile(join(homeDirectory, "config.json"), "utf8")));
2493
1971
  } catch (error) {
2494
1972
  if (error.code === "ENOENT") return {};
1973
+ if (fixedEndpoints && error instanceof z.ZodError) {
1974
+ const field = error.issues.find((issue) => issue.path[0] === "sash_url" || issue.path[0] === "dashboard_url")?.path[0];
1975
+ if (field !== void 0) throw invalidEndpointHint(`config.json ${String(field)}`);
1976
+ }
2495
1977
  throw invalidConfig("stored QMind configuration is invalid");
2496
1978
  }
2497
1979
  }
2498
1980
  function defaultProcessEnvironment() {
2499
1981
  return process.env;
2500
1982
  }
1983
+ function invalidEndpointHint(field) {
1984
+ return invalidConfig(`${field} is invalid or conflicts with the selected target; remove ${field} and select the target with --env or paired --sash/--dashboard`, field);
1985
+ }
1986
+ function validateFixedEndpoints(options, environment, file) {
1987
+ const target = options.fixedEndpoints;
1988
+ if (target === void 0) return;
1989
+ const checkOrigin = (raw, expected, field, deprecated = true) => {
1990
+ if (raw === void 0) return;
1991
+ let normalized;
1992
+ try {
1993
+ normalized = normalizeQMindOrigin(raw.trim(), field);
1994
+ } catch {
1995
+ throw invalidEndpointHint(field);
1996
+ }
1997
+ if (normalized !== expected) throw invalidEndpointHint(field);
1998
+ if (deprecated) options.reporter?.warn(`warning: ${field} is deprecated and does not select a target; remove ${field}`);
1999
+ };
2000
+ checkOrigin(environment.QMIND_SASH_URL, target.sashOrigin, "QMIND_SASH_URL");
2001
+ checkOrigin(environment.QMIND_DASHBOARD_URL, target.dashboardOrigin, "QMIND_DASHBOARD_URL");
2002
+ checkOrigin(file.sash_url, target.sashOrigin, "config.json sash_url");
2003
+ checkOrigin(file.dashboard_url, target.dashboardOrigin, "config.json dashboard_url");
2004
+ checkOrigin(options.credentialSashOrigin, target.sashOrigin, "credentials.json sash_url", false);
2005
+ if (environment.QMIND_ENV !== void 0) {
2006
+ let legacy;
2007
+ try {
2008
+ legacy = resolveQMindProductEndpoints(options.productId ?? "", environment.QMIND_ENV.trim());
2009
+ } catch {
2010
+ throw invalidEndpointHint("QMIND_ENV");
2011
+ }
2012
+ if (legacy.sashOrigin !== target.sashOrigin || legacy.dashboardOrigin !== target.dashboardOrigin) throw invalidEndpointHint("QMIND_ENV");
2013
+ options.reporter?.warn("warning: QMIND_ENV is deprecated and does not select a target; remove QMIND_ENV");
2014
+ }
2015
+ }
2501
2016
  async function loadQMindCliConfig(options = {}) {
2502
2017
  const initialEnvironment = options.environment ?? defaultProcessEnvironment();
2503
2018
  const baseHome = options.homeDirectory ?? homedir();
2504
2019
  const environment = await mergedEnvironment(initialEnvironment, options.legacyEnvironmentPath === void 0 ? join(baseHome, ".qmind-env") : options.legacyEnvironmentPath);
2505
2020
  const configuredHome = optionalTrimmed(environment.QMIND_HOME);
2506
2021
  const homeDirectory = resolve(options.homeDirectory ?? configuredHome ?? join(baseHome, ".qmind"));
2507
- const file = await fileConfiguration(homeDirectory);
2022
+ const file = await fileConfiguration(homeDirectory, options.fixedEndpoints !== void 0);
2023
+ validateFixedEndpoints(options, environment, file);
2508
2024
  const flags = options.flags ?? {};
2509
2025
  const stdinIsTTY = options.stdinIsTTY ?? process.stdin.isTTY === true;
2510
2026
  const presetName = optionalTrimmed(environment.QMIND_ENV) ?? "prod";
2511
- const preset = PRESETS[presetName] ?? PRESETS.prod;
2512
- if (!(presetName in PRESETS)) options.reporter?.warn(`warning: unknown QMIND_ENV ${JSON.stringify(presetName)}, falling back to prod`);
2513
- const sashOrigin = normalizeOrigin$1(optionalTrimmed(flags.sash) ?? optionalTrimmed(environment.QMIND_SASH_URL) ?? optionalTrimmed(file.sash_url) ?? optionalTrimmed(options.credentialSashOrigin) ?? preset.sashOrigin, "sash");
2514
- const dashboardOrigin = normalizeOrigin$1(optionalTrimmed(flags.dashboard) ?? optionalTrimmed(environment.QMIND_DASHBOARD_URL) ?? optionalTrimmed(file.dashboard_url) ?? preset.dashboardOrigin, "dashboard");
2027
+ const productId = optionalTrimmed(options.productId);
2028
+ const defaultOrigin = (field) => {
2029
+ const preset = productId === void 0 ? PRESETS[presetName] ?? PRESETS.prod : resolveQMindProductEndpoints(productId, presetName, field);
2030
+ return field === "sash" ? preset.sashOrigin : preset.dashboardOrigin;
2031
+ };
2032
+ if (options.fixedEndpoints === void 0 && productId === void 0 && !(presetName in PRESETS)) options.reporter?.warn(`warning: unknown QMIND_ENV ${JSON.stringify(presetName)}, falling back to prod`);
2033
+ const sashOrigin = normalizeQMindOrigin(options.fixedEndpoints?.sashOrigin ?? optionalTrimmed(flags.sash) ?? optionalTrimmed(environment.QMIND_SASH_URL) ?? optionalTrimmed(file.sash_url) ?? optionalTrimmed(options.credentialSashOrigin) ?? defaultOrigin("sash"), "sash");
2034
+ const dashboardOrigin = normalizeQMindOrigin(options.fixedEndpoints?.dashboardOrigin ?? optionalTrimmed(flags.dashboard) ?? optionalTrimmed(environment.QMIND_DASHBOARD_URL) ?? optionalTrimmed(file.dashboard_url) ?? defaultOrigin("dashboard"), "dashboard");
2515
2035
  const runtime = Object.freeze({
2516
2036
  client: optionalTrimmed(flags.client) ?? optionalTrimmed(environment.QMIND_CLIENT) ?? optionalTrimmed(file.client) ?? "qmind",
2517
2037
  dashboardOrigin,
@@ -2631,27 +2151,17 @@ async function optionalSecret(operation, fallback) {
2631
2151
  return fallback;
2632
2152
  }
2633
2153
  }
2634
- function createOptionalKeyringSecretStore() {
2635
- const entry = async () => {
2636
- const { Entry } = await import("@napi-rs/keyring");
2637
- return new Entry("qmind-cli", "device-token");
2638
- };
2154
+ function createNoopQMindSecretStore() {
2639
2155
  return Object.freeze({
2640
- async delete() {
2641
- await optionalSecret(async () => void (await entry()).deletePassword(), void 0);
2642
- },
2643
- async get() {
2644
- return await optionalSecret(async () => (await entry()).getPassword() ?? void 0, void 0);
2645
- },
2646
- async set(token) {
2647
- await optionalSecret(async () => void (await entry()).setPassword(token), void 0);
2648
- }
2156
+ async delete() {},
2157
+ async get() {},
2158
+ async set(_token) {}
2649
2159
  });
2650
2160
  }
2651
2161
  function createFileCredentialVault(options) {
2652
2162
  const credentialsPath = join(options.homeDirectory, "credentials.json");
2653
2163
  const legacyBackupPath = `${credentialsPath}.v1.bak`;
2654
- const secretStore = options.secretStore ?? createOptionalKeyringSecretStore();
2164
+ const secretStore = options.secretStore ?? createNoopQMindSecretStore();
2655
2165
  const now = options.now ?? Date.now;
2656
2166
  const loadUnlocked = async () => {
2657
2167
  let serialized;
@@ -2890,6 +2400,11 @@ function headersToRecord(headers) {
2890
2400
  }
2891
2401
  return result;
2892
2402
  }
2403
+ function normalizedRequestHeaders(headers) {
2404
+ const result = {};
2405
+ for (const [name, value] of Object.entries(headers ?? {})) result[name.toLowerCase()] = value;
2406
+ return result;
2407
+ }
2893
2408
  function parseRawBody(rawBody) {
2894
2409
  if (rawBody.trim().length === 0) return void 0;
2895
2410
  try {
@@ -2958,7 +2473,7 @@ function byteLength(value) {
2958
2473
  return Buffer.byteLength(value, "utf8");
2959
2474
  }
2960
2475
  function encodeBody(request, boundary) {
2961
- const initialHeaders = { ...request.headers };
2476
+ const initialHeaders = normalizedRequestHeaders(request.headers);
2962
2477
  const body = request.body;
2963
2478
  if (body === void 0) return { headers: initialHeaders };
2964
2479
  if (body.kind === "json") {
@@ -3323,8 +2838,10 @@ function configurationOptions(options, reporter) {
3323
2838
  ...options.credentialSashOrigin === void 0 ? {} : { credentialSashOrigin: options.credentialSashOrigin },
3324
2839
  ...options.environment === void 0 ? {} : { environment: options.environment },
3325
2840
  ...options.flags === void 0 ? {} : { flags: options.flags },
2841
+ ...options.fixedEndpoints === void 0 ? {} : { fixedEndpoints: options.fixedEndpoints },
3326
2842
  ...options.homeDirectory === void 0 ? {} : { homeDirectory: options.homeDirectory },
3327
2843
  ...options.legacyEnvironmentPath === void 0 ? {} : { legacyEnvironmentPath: options.legacyEnvironmentPath },
2844
+ ...options.productId === void 0 ? {} : { productId: options.productId },
3328
2845
  ...reporter === void 0 ? {} : { reporter },
3329
2846
  ...options.stdinIsTTY === void 0 ? {} : { stdinIsTTY: options.stdinIsTTY }
3330
2847
  };
@@ -3335,7 +2852,7 @@ async function createQMindCliHost(options = {}) {
3335
2852
  const vault = createFileCredentialVault({
3336
2853
  homeDirectory: (await loadQMindCliConfig(configurationOptions(options))).runtime.homeDirectory,
3337
2854
  now: () => clock.now(),
3338
- secretStore: options.adapters?.secretStore ?? createOptionalKeyringSecretStore()
2855
+ secretStore: options.adapters?.secretStore ?? createNoopQMindSecretStore()
3339
2856
  });
3340
2857
  let credentials;
3341
2858
  try {
@@ -3347,7 +2864,7 @@ async function createQMindCliHost(options = {}) {
3347
2864
  }
3348
2865
  const resolved = await loadQMindCliConfig({
3349
2866
  ...configurationOptions(options, reporter),
3350
- ...credentials?.sashOrigin ? { credentialSashOrigin: credentials.sashOrigin } : {},
2867
+ ...options.adapters?.requestCredential === void 0 && credentials?.sashOrigin ? { credentialSashOrigin: credentials.sashOrigin } : {},
3351
2868
  reporter
3352
2869
  });
3353
2870
  const ca = await tlsAuthority(resolved.tlsCaFile);
@@ -3374,6 +2891,7 @@ async function createQMindCliHost(options = {}) {
3374
2891
  config: resolved.runtime,
3375
2892
  credentials,
3376
2893
  explicitToken: resolved.token,
2894
+ ...options.loginCommand === void 0 ? {} : { loginCommand: options.loginCommand },
3377
2895
  reporter,
3378
2896
  transport: rawTransport,
3379
2897
  vault
@@ -3381,7 +2899,7 @@ async function createQMindCliHost(options = {}) {
3381
2899
  const client = createQMindClient({
3382
2900
  access: "sash",
3383
2901
  client: resolved.runtime.client,
3384
- transport: createAuthenticatedQMindTransport(rawTransport, auth)
2902
+ transport: createAuthenticatedQMindTransport(rawTransport, auth, options.adapters?.requestCredential)
3385
2903
  });
3386
2904
  return Object.freeze({
3387
2905
  client,
@@ -3400,6 +2918,120 @@ async function createQMindCliHost(options = {}) {
3400
2918
  });
3401
2919
  }
3402
2920
  //#endregion
2921
+ //#region src/argv.ts
2922
+ const SHORT_OPTIONS = /* @__PURE__ */ new Set([
2923
+ "-h",
2924
+ "-V",
2925
+ "-o",
2926
+ "-q"
2927
+ ]);
2928
+ /**
2929
+ * Preserve the historical Go CLI spelling where long options used one dash.
2930
+ * The delimiter is an intentional hard boundary: everything after `--` is a
2931
+ * positional value and must remain byte-for-byte unchanged.
2932
+ */
2933
+ function normalizeLegacyArgv(argv) {
2934
+ let positionalOnly = false;
2935
+ return argv.map((argument) => {
2936
+ if (argument === "--") {
2937
+ positionalOnly = true;
2938
+ return argument;
2939
+ }
2940
+ if (positionalOnly || SHORT_OPTIONS.has(argument) || argument.startsWith("--")) return argument;
2941
+ if (/^-[A-Za-z][A-Za-z0-9-]+(?:=.*)?$/.test(argument)) return `-${argument}`;
2942
+ return argument;
2943
+ });
2944
+ }
2945
+ /** Runtime errors use the JSON error envelope only when the caller explicitly
2946
+ * selected JSON, except folder sync whose compatibility default is JSON. */
2947
+ function requestsJsonOutput(argv) {
2948
+ let explicitFormat;
2949
+ let positionalOnly = false;
2950
+ for (let index = 0; index < argv.length; index += 1) {
2951
+ const argument = argv[index];
2952
+ if (argument === "--") {
2953
+ positionalOnly = true;
2954
+ continue;
2955
+ }
2956
+ if (positionalOnly) continue;
2957
+ if (argument === "--format" || argument === "-format") {
2958
+ explicitFormat = argv[index + 1];
2959
+ index += 1;
2960
+ continue;
2961
+ }
2962
+ const match = argument?.match(/^--?format=(.*)$/);
2963
+ if (match !== null && match !== void 0) explicitFormat = match[1];
2964
+ }
2965
+ if (explicitFormat !== void 0) return explicitFormat === "json";
2966
+ return argv[0] === "upload-folder" || argv[0] === "sync";
2967
+ }
2968
+ //#endregion
2969
+ //#region src/build-info.ts
2970
+ /** Bundled identity, never inferred from argv, environment, or an endpoint. */
2971
+ const QMIND_CLI_DISTRIBUTION = "global";
2972
+ const QMIND_CLI_VERSION = "3.1.0";
2973
+ const QMIND_CLI_BUILD_TIME = "2026-09-01T12:26:44.000Z";
2974
+ function qmindCliPlatform() {
2975
+ return process.platform === "win32" ? "windows" : process.platform;
2976
+ }
2977
+ function qmindCliArchitecture() {
2978
+ return process.arch === "x64" ? "amd64" : process.arch;
2979
+ }
2980
+ //#endregion
2981
+ //#region src/distributions.ts
2982
+ /** Canonical runtime and release identity for every public CLI distribution. */
2983
+ const CLI_DISTRIBUTIONS = Object.freeze({
2984
+ global: {
2985
+ id: "global",
2986
+ command: "qmind",
2987
+ package: "@qoder-ai/qmind-cli",
2988
+ productId: "qoder",
2989
+ gitTagSlug: "qmind-cli",
2990
+ readmeDirectory: ".",
2991
+ productNames: {
2992
+ en: "Qoder Global",
2993
+ zhCN: "Qoder Global"
2994
+ }
2995
+ },
2996
+ cn: {
2997
+ id: "cn",
2998
+ command: "qmind-cn",
2999
+ package: "@qodercn-ai/qmind-cli",
3000
+ productId: "qoder-cn",
3001
+ gitTagSlug: "qmind-cli-cn",
3002
+ readmeDirectory: "readmes/cn",
3003
+ productNames: {
3004
+ en: "Qoder China",
3005
+ zhCN: "Qoder 中国版"
3006
+ }
3007
+ }
3008
+ });
3009
+ //#endregion
3010
+ //#region src/config.ts
3011
+ function cliHostConfiguration(distribution, flags, environment, stateRoot) {
3012
+ const { productId, command } = CLI_DISTRIBUTIONS[distribution];
3013
+ const custom = flags.sash !== void 0 || flags.dashboard !== void 0;
3014
+ if (custom && (typeof flags.sash !== "string" || typeof flags.dashboard !== "string" || flags.env !== void 0)) throw new QMindError("INVALID_ARGUMENT", "--sash and --dashboard must be supplied together and cannot be combined with --env");
3015
+ const preset = typeof flags.env === "string" ? flags.env.trim() : "prod";
3016
+ const endpoints = custom ? {
3017
+ dashboardOrigin: normalizeQMindOrigin(String(flags.dashboard).trim(), "--dashboard"),
3018
+ sashOrigin: normalizeQMindOrigin(String(flags.sash).trim(), "--sash")
3019
+ } : resolveQMindProductEndpoints(productId, preset);
3020
+ const target = custom ? `custom-${createHash("sha256").update(JSON.stringify([endpoints.dashboardOrigin, endpoints.sashOrigin])).digest("hex")}` : preset;
3021
+ return {
3022
+ environment: {
3023
+ ...environment,
3024
+ QMIND_TOKEN: target === "prod" ? environment.QMIND_TOKEN : environment.QMIND_DEBUG_TOKEN
3025
+ },
3026
+ flags,
3027
+ fixedEndpoints: endpoints,
3028
+ homeDirectory: join(resolve(stateRoot ?? (environment.QMIND_HOME?.trim() || join(homedir(), ".qmind"))), "cli", distribution, target),
3029
+ legacyEnvironmentPath: false,
3030
+ loginCommand: `${command} login${custom ? ` --sash ${endpoints.sashOrigin} --dashboard ${endpoints.dashboardOrigin}` : target === "prod" ? "" : ` --env ${target}`}`,
3031
+ productId
3032
+ };
3033
+ }
3034
+ //#endregion
3403
3035
  //#region src/folder-sync.ts
3404
3036
  const QMIND_FOLDER_SYNC_DEFAULT_EXTENSIONS = Object.freeze([
3405
3037
  ".mdx",
@@ -3761,13 +3393,6 @@ function table(writer, headers, rows, widths, separatorWidth) {
3761
3393
  }
3762
3394
  function goTimestamp(value) {
3763
3395
  if (value === void 0 || value === null || value === "") return null;
3764
- if (typeof value === "object") {
3765
- const source = record(value);
3766
- return {
3767
- nanos: numberValue(source.nanos),
3768
- seconds: numberValue(source.seconds)
3769
- };
3770
- }
3771
3396
  const text = stringValue(value);
3772
3397
  const milliseconds = Date.parse(text);
3773
3398
  if (!Number.isFinite(milliseconds)) return null;
@@ -3786,9 +3411,6 @@ function optionalMap(value) {
3786
3411
  const result = record(value);
3787
3412
  return Object.keys(result).length === 0 ? void 0 : result;
3788
3413
  }
3789
- function optionalStrings(value) {
3790
- return Array.isArray(value) && value.length > 0 ? value.map(stringValue) : void 0;
3791
- }
3792
3414
  function pagination(value) {
3793
3415
  if (value === void 0 || value === null) return "";
3794
3416
  const page = record(value);
@@ -3869,45 +3491,6 @@ function goSourceList(value) {
3869
3491
  pageSize: numberValue(value.pageSize)
3870
3492
  };
3871
3493
  }
3872
- function goCardLink(value) {
3873
- const source = record(value);
3874
- return {
3875
- linkType: stringValue(source.linkType),
3876
- targetId: stringValue(source.targetId),
3877
- ...source.targetTitle ? { targetTitle: stringValue(source.targetTitle) } : {},
3878
- ...source.description ? { description: stringValue(source.description) } : {}
3879
- };
3880
- }
3881
- function goCard(value) {
3882
- const source = record(value);
3883
- const keywords = optionalStrings(source.keywords);
3884
- const links = Array.isArray(source.links) && source.links.length > 0 ? source.links.map(goCardLink) : void 0;
3885
- return {
3886
- id: stringValue(source.id),
3887
- ...source.knowledgeId ? { knowledgeId: stringValue(source.knowledgeId) } : {},
3888
- orgId: stringValue(source.orgId),
3889
- ...source.notebookId ? { notebookId: stringValue(source.notebookId) } : {},
3890
- source: stringValue(source.source),
3891
- ...source.cardType ? { cardType: stringValue(source.cardType) } : {},
3892
- ...source.category ? { category: stringValue(source.category) } : {},
3893
- ...source.repo ? { repo: stringValue(source.repo) } : {},
3894
- title: stringValue(source.title),
3895
- content: stringValue(source.content),
3896
- ...keywords === void 0 ? {} : { keywords },
3897
- ...links === void 0 ? {} : { links },
3898
- ...source.extra ? { extra: stringValue(source.extra) } : {},
3899
- createdAt: goTimestamp(source.createdAt),
3900
- updatedAt: goTimestamp(source.updatedAt)
3901
- };
3902
- }
3903
- function goCardList(value) {
3904
- return {
3905
- cards: value.cards.map(goCard),
3906
- totalSize: numberValue(value.totalSize),
3907
- currentPage: numberValue(value.currentPage),
3908
- pageSize: numberValue(value.pageSize)
3909
- };
3910
- }
3911
3494
  function goRetrieve(value) {
3912
3495
  return {
3913
3496
  chunks: value.chunks.map((chunk) => ({
@@ -3994,32 +3577,6 @@ function renderAgentSource(writer, value, index = 0) {
3994
3577
  agentField(writer, "updatedAt", timestamp(value.updatedAt));
3995
3578
  agentText(writer, "error", value.errorMessage);
3996
3579
  }
3997
- function renderAgentCard(writer, value, index, score) {
3998
- writer.line("---");
3999
- agentField(writer, "type", "card");
4000
- if (index > 0) agentField(writer, "index", index);
4001
- if (score !== void 0) agentField(writer, "score", score.toFixed(4));
4002
- agentField(writer, "id", value.id);
4003
- agentField(writer, "knowledgeId", value.knowledgeId);
4004
- agentField(writer, "notebookId", value.notebookId);
4005
- agentField(writer, "source", value.source);
4006
- agentField(writer, "cardType", value.cardType);
4007
- agentField(writer, "category", value.category);
4008
- agentField(writer, "repo", value.repo);
4009
- agentField(writer, "title", value.title);
4010
- if (value.keywords.length > 0) agentField(writer, "keywords", value.keywords.join(", "));
4011
- agentField(writer, "createdAt", timestamp(value.createdAt));
4012
- agentField(writer, "updatedAt", timestamp(value.updatedAt));
4013
- agentText(writer, "content", value.content);
4014
- if (value.links.length > 0) {
4015
- writer.line("links:");
4016
- for (const link of value.links) {
4017
- writer.line(` - targetId: ${link.targetId}`);
4018
- agentField(writer, " linkType", link.linkType);
4019
- agentField(writer, " description", link.description);
4020
- }
4021
- }
4022
- }
4023
3580
  function json(value, pretty) {
4024
3581
  return `${JSON.stringify(value, null, pretty ? 2 : 0)}\n`;
4025
3582
  }
@@ -4126,42 +3683,6 @@ function renderSourceList(value, format) {
4126
3683
  }
4127
3684
  return writer.toString();
4128
3685
  }
4129
- function renderCardList(value, format) {
4130
- if (format === "json") return json(goCardList(value), true);
4131
- if (format === "ndjson") return value.cards.map((item) => json(goCard(item), false)).join("");
4132
- const writer = new TextWriter();
4133
- if (format === "agent") {
4134
- agentHeader(writer, "cards", value.totalSize || value.cards.length);
4135
- value.cards.forEach((item, index) => renderAgentCard(writer, item, index + 1));
4136
- } else if (value.cards.length === 0) writer.line("No cards found.");
4137
- else {
4138
- writer.line(`Total: ${value.totalSize || value.cards.length}`);
4139
- writer.line();
4140
- table(writer, [
4141
- "ID",
4142
- "TYPE",
4143
- "CATEGORY",
4144
- "TITLE",
4145
- "LINKS",
4146
- "UPDATED"
4147
- ], value.cards.map((item) => [
4148
- truncate(item.id, 36),
4149
- truncate(item.cardType, 8),
4150
- truncate(item.category, 16),
4151
- truncate(item.title, 30),
4152
- item.links.length,
4153
- timestamp(item.updatedAt)
4154
- ]), [
4155
- 36,
4156
- 8,
4157
- 16,
4158
- 30,
4159
- 5,
4160
- 20
4161
- ], 125);
4162
- }
4163
- return writer.toString();
4164
- }
4165
3686
  function renderRetrieve(value, format) {
4166
3687
  if (format === "json") return json(goRetrieve(value), true);
4167
3688
  if (format === "ndjson") return [...value.chunks.map((item) => ({
@@ -4287,7 +3808,6 @@ function renderQMindCliPresentation(presentation, format) {
4287
3808
  case "notebookList": return renderNotebookList(presentation.value, format);
4288
3809
  case "source": return renderSource(presentation.value, format);
4289
3810
  case "sourceList": return renderSourceList(presentation.value, format);
4290
- case "cardList": return renderCardList(presentation.value, format);
4291
3811
  case "retrieve": return renderRetrieve(presentation.value, format);
4292
3812
  case "imageUpload": return json({
4293
3813
  uploadUrl: presentation.value.uploadUrl,
@@ -4488,6 +4008,7 @@ function createQMindCliStreamRenderer(format) {
4488
4008
  }
4489
4009
  //#endregion
4490
4010
  //#region src/application.ts
4011
+ const distribution = CLI_DISTRIBUTIONS[QMIND_CLI_DISTRIBUTION];
4491
4012
  function processIO() {
4492
4013
  return Object.freeze({
4493
4014
  stdinIsTTY: process.stdin.isTTY === true,
@@ -4548,25 +4069,25 @@ function formatOf(options) {
4548
4069
  }
4549
4070
  function commonFlags(options) {
4550
4071
  const client = optionalString(options, "client");
4551
- const dashboard = optionalString(options, "dashboard");
4552
- const sash = optionalString(options, "sash");
4072
+ const dashboard = stringOption(options, "dashboard");
4073
+ const sash = stringOption(options, "sash");
4074
+ const env = stringOption(options, "env");
4553
4075
  const token = optionalString(options, "token");
4554
4076
  return {
4555
4077
  ...client === void 0 ? {} : { client },
4078
+ ...env === void 0 ? {} : { env },
4556
4079
  ...dashboard === void 0 ? {} : { dashboard },
4557
4080
  ...options.nonInteractive === true ? { nonInteractive: true } : {},
4558
4081
  ...sash === void 0 ? {} : { sash },
4559
4082
  ...token === void 0 ? {} : { token }
4560
4083
  };
4561
4084
  }
4562
- async function hostFor(context, options, environmentOverrides = {}) {
4085
+ async function hostFor(context, options) {
4563
4086
  if (context.host !== void 0) return context.host;
4564
- const environment = {
4565
- ...context.hostOptions.environment ?? process.env,
4566
- ...environmentOverrides
4567
- };
4087
+ const configuration = cliHostConfiguration(QMIND_CLI_DISTRIBUTION, commonFlags(options), context.hostOptions.environment ?? process.env, context.hostOptions.homeDirectory);
4568
4088
  const adapters = {
4569
4089
  ...context.hostOptions.adapters,
4090
+ secretStore: createNoopQMindSecretStore(),
4570
4091
  reporter: context.hostOptions.adapters?.reporter ?? {
4571
4092
  info(message) {
4572
4093
  context.io.stderr(`${message}\n`);
@@ -4578,9 +4099,8 @@ async function hostFor(context, options, environmentOverrides = {}) {
4578
4099
  };
4579
4100
  context.host = await context.hostFactory({
4580
4101
  ...context.hostOptions,
4102
+ ...configuration,
4581
4103
  adapters,
4582
- environment,
4583
- flags: commonFlags(options),
4584
4104
  stdinIsTTY: context.io.stdinIsTTY
4585
4105
  });
4586
4106
  return context.host;
@@ -4589,26 +4109,10 @@ function render(context, options, presentation) {
4589
4109
  context.io.stdout(renderQMindCliPresentation(presentation, formatOf(options)));
4590
4110
  }
4591
4111
  function withCommon(command, output = true) {
4592
- command.option("--token <token>", "Bearer access token").option("--sash <url>", "Sash server origin").option("--dashboard <url>", "Dashboard origin").option("--org <id>", "organization ID (deprecated and ignored)").option("--client <name>", "originating client identifier").option("--non-interactive", "never open a browser when credentials are missing");
4112
+ command.option("--token <token>", "Bearer access token").option("--env <name>", "product environment: prod (default), test, or daily where supported").option("--sash <url>", "custom debug Sash origin (requires --dashboard; excludes --env)").option("--dashboard <url>", "custom debug Dashboard origin (requires --sash; excludes --env)").option("--org <id>", "organization ID (deprecated and ignored)").option("--client <name>", "originating client identifier").option("--non-interactive", "never open a browser when credentials are missing");
4593
4113
  if (output) command.option("--format <format>", "output format: table | json | agent | ndjson", "table");
4594
4114
  return command;
4595
4115
  }
4596
- function registerCardQueryCommand(context, command) {
4597
- withCommon(command).option("--nb <id>", "notebook ID (required)").option("-q, --query <query>", "search query", "").option("--cat <category>", "category filter", "").option("--page <number>", "page number", integer, 0).option("--page-size <number>", "page size", integer, 20).action(async (raw) => {
4598
- const host = await hostFor(context, raw);
4599
- const page = positiveNumberOption(raw, "page", 0);
4600
- const pageSize = positiveNumberOption(raw, "pageSize", 20);
4601
- render(context, raw, {
4602
- kind: "cardList",
4603
- value: await host.client.listCards(requiredString(raw.nb, "--nb"), {
4604
- category: String(raw.cat ?? ""),
4605
- ...page === void 0 ? {} : { page },
4606
- ...pageSize === void 0 ? {} : { pageSize },
4607
- query: String(raw.query ?? "")
4608
- })
4609
- });
4610
- });
4611
- }
4612
4116
  function registerCoreCommands(context, program) {
4613
4117
  withCommon(program.command("login").description("Authorize via browser and save credentials"), false).option("--client-id <id>", "OAuth App client_id").action(async (raw) => {
4614
4118
  const host = await hostFor(context, raw);
@@ -4648,12 +4152,6 @@ function registerCoreCommands(context, program) {
4648
4152
  await (await hostFor(context, raw)).client.deleteNotebook(notebookId);
4649
4153
  context.io.stdout("deleted\n");
4650
4154
  });
4651
- const cards = program.command("cards").description("Manage notebook cards");
4652
- for (const action of ["list", "search"]) {
4653
- const description = action === "search" ? "Search notebook cards" : "List notebook cards";
4654
- registerCardQueryCommand(context, cards.command(action).description(description));
4655
- registerCardQueryCommand(context, program.command(action).description(`${description} (alias for cards ${action})`));
4656
- }
4657
4155
  withCommon(program.command("retrieve [query]").description("Retrieve notebook context without an LLM call")).option("--nb <id>", "notebook ID (required)").option("-q, --query <query>", "retrieval query").option("--sources <ids>", "comma-separated source IDs", "").option("--top-k <number>", "top-k for retrieval", integer, 0).option("--max-results <number>", "maximum context results", integer, 0).action(async (query, raw) => {
4658
4156
  render(context, raw, {
4659
4157
  kind: "retrieve",
@@ -4800,7 +4298,7 @@ function registerSourceCommands(context, program) {
4800
4298
  kind: "source",
4801
4299
  value
4802
4300
  });
4803
- else context.io.stdout(`Site source created: ${value.id}\n title : ${value.title}\n status: ${value.status}\n site : ${rootUrl}\n\nSite import is running asynchronously. Use 'qmind source list' to check imported pages.\n`);
4301
+ else context.io.stdout(`Site source created: ${value.id}\n title : ${value.title}\n status: ${value.status}\n site : ${rootUrl}\n\nSite import is running asynchronously. Use '${distribution.command} source list' to check imported pages.\n`);
4804
4302
  });
4805
4303
  const image = program.command("image").description("Notebook image presign operations");
4806
4304
  withCommon(image.command("presign-upload").description("Presign or upload a notebook image"), false).option("--nb <id>", "notebook ID (required)").option("--source <id>", "source ID (required)").option("--filename <name>", "image filename (required unless --file is set)").option("--mime <type>", "MIME type (required unless --file is set)").option("--size <bytes>", "file size", integer, 0).option("--file <path>", "local image to upload").action(async (raw) => {
@@ -4897,19 +4395,19 @@ function syncText(stats) {
4897
4395
  return `[upload-folder] 完成: 创建目录 ${stats.dirs_created} (复用 ${stats.dirs_reused}, 失败 ${stats.dirs_failed}), 上传文件 ${stats.files_uploaded}, 已存在跳过 ${stats.files_already_exist}, 不支持或忽略 ${stats.files_skipped}, 失败 ${stats.files_failed}, 时间戳刷新失败 ${stats.dirs_refresh_failed}` + (stats.files_deleted === void 0 ? "" : `, 删除文件 ${stats.files_deleted}, 删除目录 ${stats.dirs_deleted ?? 0}, 删除失败 ${stats.delete_failed ?? 0}`) + "\n";
4898
4396
  }
4899
4397
  function registerSyncCommand(context, program) {
4900
- withCommon(program.command("upload-folder").alias("sync").description("Synchronize a local folder"), false).option("--nb <id>", "notebook ID (required)").option("--dir <path>", "local directory (required)").option("--env <name>", "environment preset").option("--extensions <list>", "comma-separated extensions").option("--dir-ids <path>", "existing directory ID mapping").option("--skip-upload", "only refresh directory timestamps").option("--concurrency <number>", "parallel uploads", integer, 3).option("--save-dir-ids <path>", "directory ID mapping output").option("--ignore <patterns...>", "glob patterns to exclude").option("--delete", "delete remote entries absent from the local mirror").option("--dry-run", "calculate changes without mutating remote or local state").option("--format <format>", "summary output format: json | text", "json").addOption(new Option("--mode <mode>", "existing-file behavior").choices([
4398
+ withCommon(program.command("upload-folder").alias("sync").description("Synchronize a local folder"), false).option("--nb <id>", "notebook ID (required)").option("--dir <path>", "local directory (required)").option("--extensions <list>", "comma-separated extensions").option("--dir-ids <path>", "existing directory ID mapping").option("--skip-upload", "only refresh directory timestamps").option("--concurrency <number>", "parallel uploads", integer, 3).option("--save-dir-ids <path>", "directory ID mapping output").option("--ignore <patterns...>", "glob patterns to exclude").option("--delete", "delete remote entries absent from the local mirror").option("--dry-run", "calculate changes without mutating remote or local state").option("--format <format>", "summary output format: json | text", "json").addOption(new Option("--mode <mode>", "existing-file behavior").choices([
4901
4399
  "skip",
4902
4400
  "overwrite",
4903
4401
  "if-changed"
4904
4402
  ]).default("skip")).action(async (raw) => {
4905
- const environment = optionalString(raw, "env");
4906
- const host = await hostFor(context, raw, environment === void 0 ? {} : { QMIND_ENV: environment });
4403
+ const host = await hostFor(context, raw);
4907
4404
  const ignoreValues = Array.isArray(raw.ignore) ? raw.ignore.flatMap((value) => splitCsv(String(value))) : [];
4908
4405
  const directoryIdsPath = optionalString(raw, "dirIds");
4909
4406
  const saveDirectoryIdsPath = optionalString(raw, "saveDirIds");
4910
4407
  const extensions = splitCsv(optionalString(raw, "extensions"));
4911
4408
  const result = await synchronizeQMindFolder(host, {
4912
4409
  baseDirectory: requiredString(raw.dir, "--dir"),
4410
+ cacheDirectory: join(host.config.homeDirectory, "cache"),
4913
4411
  concurrency: Math.max(1, numberOption(raw, "concurrency", 3)),
4914
4412
  delete: raw.delete === true,
4915
4413
  dryRun: raw.dryRun === true,
@@ -4930,42 +4428,30 @@ function registerSyncCommand(context, program) {
4930
4428
  if (result.exitCode === 1) context.exitCode = 1;
4931
4429
  });
4932
4430
  }
4933
- function registerUpdateCommand(context, program) {
4934
- program.command("self-update").description("Show the supported qmind CLI upgrade path").option("--url <url>", "channel manifest or CLI base URL", QMIND_CLI_UPDATE_BASE_URL).addOption(new Option("--channel <channel>", "release channel").choices([
4431
+ function registerUpdateCommand(program) {
4432
+ program.command("self-update").description("Show the supported qmind CLI upgrade path").option("--url <url>", "legacy update URL (ignored)").addOption(new Option("--channel <channel>", "legacy release channel (ignored)").choices([
4935
4433
  "stable",
4936
4434
  "beta",
4937
4435
  "daily"
4938
- ]).default("stable")).option("--public-key <key>", "Ed25519 public key file, PEM, or base64").option("--check", "only check and verify the available update").option("--force", "reinstall the same version").option("--allow-downgrade", "explicitly allow installing an older signed version").action(async (raw) => {
4939
- if (context.selfUpdater === void 0) throw new QMindError("UNSUPPORTED_OPERATION", "self-update is unavailable for npm installs; run npm update --global @qoder-ai/qmind-cli");
4940
- const result = await context.selfUpdater.update({
4941
- allowDowngrade: raw.allowDowngrade === true,
4942
- baseUrl: String(raw.url),
4943
- channel: String(raw.channel),
4944
- check: raw.check === true,
4945
- currentVersion: QMIND_CLI_VERSION,
4946
- force: raw.force === true,
4947
- publicKey: String(raw.publicKey ?? "")
4948
- });
4949
- if (result.updated) context.io.stdout(`[self-update] updated ${QMIND_CLI_VERSION} -> ${result.version}\n`);
4950
- else if (result.version === "2.0.0".replace(/^v/, "")) context.io.stdout(`[self-update] already current: ${result.version}\n`);
4951
- else context.io.stdout(`[self-update] verified available version: ${result.version}\n`);
4436
+ ]).default("stable")).option("--public-key <key>", "legacy public key (ignored)").option("--check", "legacy check mode (ignored)").option("--force", "legacy reinstall mode (ignored)").option("--allow-downgrade", "legacy downgrade mode (ignored)").action(() => {
4437
+ throw new QMindError("UNSUPPORTED_OPERATION", `self-update is unavailable for npm installs; run npm update --global ${distribution.package}`);
4952
4438
  });
4953
4439
  }
4954
4440
  /** Internal parser adapter. Product consumers should call runQMindCli(). */
4955
4441
  function createQMindCliProgram(context) {
4956
- const program = new Command().name("qmind").description("QMind knowledge CLI").version(QMIND_CLI_VERSION).showHelpAfterError().exitOverride().configureOutput({
4442
+ const program = new Command().name(distribution.command).description("QMind knowledge CLI").version(QMIND_CLI_VERSION).showHelpAfterError().exitOverride().configureOutput({
4957
4443
  writeErr: (value) => context.io.stderr(value),
4958
4444
  writeOut: (value) => context.io.stdout(value)
4959
4445
  });
4960
4446
  program.command("version").description("Print version and build information").action(() => {
4961
- context.io.stdout(`qmind ${QMIND_CLI_VERSION} (built ${QMIND_CLI_BUILD_TIME}, ${qmindCliPlatform()}/${qmindCliArchitecture()})\n`);
4447
+ context.io.stdout(`${distribution.command} ${QMIND_CLI_VERSION} (built ${QMIND_CLI_BUILD_TIME}, ${qmindCliPlatform()}/${qmindCliArchitecture()})\n`);
4962
4448
  });
4963
4449
  registerCoreCommands(context, program);
4964
4450
  registerSourceCommands(context, program);
4965
4451
  registerSceneCommands(context, program);
4966
4452
  registerTaskCommands(context, program);
4967
4453
  registerSyncCommand(context, program);
4968
- registerUpdateCommand(context, program);
4454
+ registerUpdateCommand(program);
4969
4455
  return program;
4970
4456
  }
4971
4457
  async function runQMindCli(argv, options = {}) {
@@ -4976,13 +4462,11 @@ async function runQMindCli(argv, options = {}) {
4976
4462
  host: void 0,
4977
4463
  hostFactory: options.hostFactory ?? createQMindCliHost,
4978
4464
  hostOptions: options.hostOptions ?? {},
4979
- io,
4980
- ...options.selfUpdater === void 0 ? {} : { selfUpdater: options.selfUpdater }
4465
+ io
4981
4466
  };
4982
4467
  const normalized = normalizeLegacyArgv(argv);
4983
4468
  const requiresLegacyAction = normalized.length === 0 || normalized.length === 1 && (/* @__PURE__ */ new Set([
4984
4469
  "notebook",
4985
- "cards",
4986
4470
  "source",
4987
4471
  "image"
4988
4472
  ])).has(normalized[0] ?? "");