@qoder-ai/qmind-cli 4.3.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/qmind.js CHANGED
@@ -1,14 +1,14 @@
1
- import { A as sourceWebOfficeSessionSchema, C as sourcePreviewSchema, D as sourceTreeSchema, E as sourceSchema, I as voidResponseSchema, M as streamWireEventSchema, N as taskRunListSchema, O as sourceUploadCapabilitiesSchema, P as taskRunSchema, S as sourceListSchema, T as sourceRawContentSchema, _ as sharedNotebookListSchema, a as chatMessageListSchema, b as sourceContentSchema, d as imageUrlsSchema, g as retrieveResultSchema, h as retrieveNotebooksResultSchema, i as cancelQuestionResultSchema, j as sourceWebOfficeTokenSchema, m as notebookSchema, o as chatSessionListSchema, p as notebookListSchema, r as batchDeleteResultSchema, s as chatSessionSchema, u as imageUploadTicketSchema, v as sourceActionAccessSchema, w as sourceQuotaSchema, x as sourceImportResultsSchema, y as sourceChildrenCountsSchema } from "./schemas-DG7vaJMR.js";
2
- import { _ as assertCapability, a as invalidArgument$1, b as QMindError, c as optionalRecord, d as pagination$1, f as positiveInteger$1, g as stringList, i as httpUrl, l as optionalString$1, m as requiredString$2, n as call, o as nonNegativeInteger$1, p as queryPath, r as compactUndefined, s as optionalBoolean, t as assertNonEmptyPatch, u as optionalTrimmedString, v as executeStream } from "./shared-CbvrtGyv.js";
3
- import { t as preflightSourceUpload } from "./source-upload-XrNG4_4V.js";
1
+ import { $ as taskRunListSchema, B as sourceActionAccessSchema, D as chatMessageListSchema, E as cancelQuestionResultSchema, F as notebookListSchema, G as sourcePreviewSchema, H as sourceContentSchema, I as notebookSchema, J as sourceSchema, K as sourceQuotaSchema, L as retrieveNotebooksResultSchema, M as imageUploadTicketSchema, N as imageUrlsSchema, O as chatSessionListSchema, Q as sourceWebOfficeTokenSchema, R as retrieveResultSchema, S as qmindRoutes, T as batchDeleteResultSchema, U as sourceImportResultsSchema, V as sourceChildrenCountsSchema, W as sourceListSchema, Y as sourceUploadCapabilitiesSchema, Z as sourceWebOfficeSessionSchema, _ as assertCapability, a as invalidArgument$1, c as optionalRecord, d as pagination$1, et as taskRunSchema, f as positiveInteger$1, g as stringList, i as httpUrl, k as chatSessionSchema, l as optionalString$1, m as requiredString$1, n as call, nt as voidResponseSchema, o as nonNegativeInteger$1, p as queryPath, q as sourceRawContentSchema, r as compactUndefined, s as optionalBoolean, t as assertNonEmptyPatch, u as optionalTrimmedString, ut as QMindError, v as executeStream, x as qmindPath, z as sharedNotebookListSchema } from "./shared-CWO5bxZy.js";
2
+ import { n as nezhaWebOfficePath } from "./nezha-DtT7HGFc.js";
3
+ import { t as preflightSourceUpload } from "./source-upload-GjQToHLv.js";
4
4
  import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
5
5
  import { z } from "zod";
6
6
  import { createHash, randomBytes, randomUUID } from "node:crypto";
7
- import { chmod, copyFile, link, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
7
+ import { chmod, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
8
8
  import { homedir, tmpdir } from "node:os";
9
9
  import lockfile from "proper-lockfile";
10
- import open from "open";
11
- import { createReadStream, createWriteStream } from "node:fs";
10
+ import open$1 from "open";
11
+ import { constants, createReadStream, createWriteStream } from "node:fs";
12
12
  import { Readable } from "node:stream";
13
13
  import { pipeline } from "node:stream/promises";
14
14
  import { createParser } from "eventsource-parser";
@@ -23,13 +23,16 @@ import semver from "semver";
23
23
  import { createInterface } from "node:readline/promises";
24
24
  //#region ../agent-core/src/scheduled-task-inputs.ts
25
25
  const id = z.string().trim().min(1).max(512);
26
- const scheduledTaskScene = z.enum([
27
- "compilation",
26
+ const writableScene$1 = z.enum([
28
27
  "condensation",
29
- "lint",
30
28
  "source_refresh",
31
29
  "source_binding_sync"
32
30
  ]);
31
+ const scheduledTaskScene = z.enum([
32
+ ...writableScene$1.options,
33
+ "compilation",
34
+ "lint"
35
+ ]);
33
36
  const schedule = z.string().trim().min(1).max(512).refine((value) => {
34
37
  const fields = value.split(/\s+/u);
35
38
  const zone = /^(?:CRON_TZ|TZ)=(.+)$/u.exec(fields[0] ?? "")?.[1];
@@ -43,7 +46,7 @@ const schedule = z.string().trim().min(1).max(512).refine((value) => {
43
46
  }, "schedule requires an explicit CRON_TZ/TZ IANA zone and five or six cron fields");
44
47
  const createScheduledTaskInputSchema = z.object({
45
48
  notebookId: id,
46
- sceneType: scheduledTaskScene,
49
+ sceneType: writableScene$1,
47
50
  schedule
48
51
  }).strict();
49
52
  const updateScheduledTaskInputSchema = z.object({
@@ -66,77 +69,190 @@ const listScheduledTasksInputSchema = z.object({
66
69
  }).strict();
67
70
  //#endregion
68
71
  //#region ../sdk/src/operations/office-preview.ts
69
- const secret = /^[A-Za-z0-9_-]{32,128}$/;
70
- const ticketSchema = z.object({
71
- sessionId: z.string().regex(secret),
72
- ticket: z.string().regex(secret),
73
- orgId: z.string(),
74
- expiresAt: z.iso.datetime({ offset: true })
75
- });
76
- function origin(value, field) {
72
+ const secret = z.string().regex(/^[A-Za-z0-9_-]{43}$/);
73
+ const grantSchema = z.object({
74
+ sessionId: secret,
75
+ ticket: secret,
76
+ previewUrl: z.string(),
77
+ expiresAt: z.iso.datetime({ offset: true }),
78
+ authorizationExpiresAt: z.iso.datetime({ offset: true })
79
+ }).refine((grant) => {
77
80
  try {
78
- const url = new URL(value);
79
- if (url.protocol === "https:" && url.origin === value) return value;
80
- } catch {}
81
- throw invalidArgument$1("Office preview requires an exact HTTPS origin", field);
81
+ const url = new URL(grant.previewUrl);
82
+ return url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash && url.pathname === `/algo/api/mind-preview/${grant.sessionId}/gate` && Date.parse(grant.authorizationExpiresAt) <= Date.parse(grant.expiresAt);
83
+ } catch {
84
+ return false;
85
+ }
86
+ });
87
+ function createOfficePreviewOperations(context) {
88
+ async function grant(notebookId, sourceId, sessionId, options) {
89
+ const operation = sessionId === void 0 ? "sources.officeProxy.create" : "sources.officeProxy.renew";
90
+ assertCapability(context.capabilities, "sources.officeProxy", operation);
91
+ const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
92
+ const notebook = requiredString$1(notebookId, "notebookId");
93
+ const source = requiredString$1(sourceId, "sourceId");
94
+ const segments = ["preview"];
95
+ if (sessionId !== void 0) {
96
+ if (!secret.safeParse(sessionId).success) throw invalidArgument$1("sessionId must be a valid Office preview session ID", "sessionId");
97
+ segments.push(sessionId, "renew");
98
+ }
99
+ const result = await call(context, {
100
+ capability: "sources.officeProxy",
101
+ operation,
102
+ method: "POST",
103
+ idempotent: false,
104
+ path: nezhaWebOfficePath(context.webOffice, notebook, source, ...segments),
105
+ body: { nonce },
106
+ schema: grantSchema,
107
+ callOptions: options
108
+ });
109
+ if (sessionId !== void 0 && result.sessionId !== sessionId) throw new QMindError("PROTOCOL_ERROR", "Office preview session mismatch");
110
+ return {
111
+ ...result,
112
+ nonce
113
+ };
114
+ }
115
+ return {
116
+ createOfficePreview: (notebookId, sourceId, options) => grant(notebookId, sourceId, void 0, options),
117
+ renewOfficePreviewAuthorization: (notebookId, sourceId, sessionId, options) => grant(notebookId, sourceId, sessionId, options)
118
+ };
82
119
  }
83
- function opaque(value, field) {
84
- if (typeof value !== "string" || !secret.test(value)) throw invalidArgument$1("Invalid preview binding", field);
85
- return value;
120
+ //#endregion
121
+ //#region ../sdk/src/capabilities.ts
122
+ const notebookCapabilities = Object.freeze({
123
+ dataSources: true,
124
+ "wiki.read": false,
125
+ chat: true,
126
+ "featuredChat.delete": false,
127
+ "featuredNotebooks.read": true,
128
+ "featuredNotebooks.copy": true,
129
+ "images.presignUpload": true,
130
+ "images.presignUrls": true,
131
+ "imports.aliDing": true,
132
+ "imports.discover": true,
133
+ "imports.fullSiteURL": true,
134
+ members: true,
135
+ "members.search": false,
136
+ "members.resolve": true,
137
+ "notebooks.filterByClient": true,
138
+ "notebooks.read": true,
139
+ "notebooks.write": true,
140
+ "notes.read": true,
141
+ "notes.write": true,
142
+ "notes.saveCondensation": true,
143
+ retrieval: true,
144
+ scheduledTasks: true,
145
+ "sharedNotebooks.read": true,
146
+ "sources.children": true,
147
+ "sources.childrenCount": true,
148
+ "sources.actionAccess": true,
149
+ "sources.importWeb": true,
150
+ "sources.preview": true,
151
+ "sources.rawContent": true,
152
+ "sources.read": true,
153
+ "sources.quota": true,
154
+ "sources.search": true,
155
+ "sources.tree": true,
156
+ "sources.webOffice": false,
157
+ "sources.officeProxy": false,
158
+ "sources.write": true,
159
+ "taskRuns.read": true,
160
+ "taskRuns.write": true,
161
+ transfers: true,
162
+ "wikiBranches.read": true,
163
+ "wikiBranches.page": true
164
+ });
165
+ function createCapabilities(nezha) {
166
+ const webOffice = nezha.webOffice !== void 0;
167
+ return Object.freeze({
168
+ ...notebookCapabilities,
169
+ "sources.webOffice": webOffice,
170
+ "sources.officeProxy": webOffice,
171
+ "wiki.read": nezha.repoWiki === true
172
+ });
86
173
  }
87
- function createOfficePreviewOperations(context) {
88
- const path = (notebookId, sourceId) => context.profile.apiPath("notebooks", requiredString$2(notebookId, "notebookId"), "sources", requiredString$2(sourceId, "sourceId"), "weboffice", "preview");
174
+ //#endregion
175
+ //#region ../sdk/src/management.ts
176
+ /** Retired scenes remain readable in historical sessions, task runs and schedules. */
177
+ function isQMindRetiredScene(scene) {
178
+ return scene === "compilation" || scene === "lint";
179
+ }
180
+ //#endregion
181
+ //#region ../sdk/src/retrieval-image.ts
182
+ const QMIND_RETRIEVAL_IMAGE_MAX_BYTES = 10485760;
183
+ const maxQueryImageBase64Length = 4 * Math.ceil(QMIND_RETRIEVAL_IMAGE_MAX_BYTES / 3);
184
+ const imageFormats = /* @__PURE__ */ new Set([
185
+ "jpeg",
186
+ "png",
187
+ "webp",
188
+ "bmp",
189
+ "tiff",
190
+ "gif"
191
+ ]);
192
+ function normalizeImageFormat(value) {
193
+ const format = value.toLowerCase();
194
+ return format === "jpg" ? "jpeg" : format;
195
+ }
196
+ function isBase64(value) {
197
+ return value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
198
+ }
199
+ /** Check the encoding and size accepted by the retrieval API. Mind validates the image bytes. */
200
+ function qmindRetrievalImageIssue({ imageBase64, imageFormat, query }) {
201
+ if (imageBase64 === void 0) return imageFormat === void 0 ? void 0 : {
202
+ field: "imageFormat",
203
+ message: "imageFormat requires imageBase64"
204
+ };
205
+ if (query !== void 0 && query.length > 128) return {
206
+ field: "query",
207
+ message: `image retrieval query must be at most 128 UTF-16 units`
208
+ };
209
+ let payload = imageBase64;
210
+ const format = imageFormat === void 0 ? void 0 : normalizeImageFormat(imageFormat);
211
+ if (/^data:/i.test(imageBase64)) {
212
+ const header = /^data:image\/([a-zA-Z]{3,4});base64,/.exec(imageBase64);
213
+ const urlFormat = normalizeImageFormat(header?.[1] ?? "");
214
+ if (!header || !imageFormats.has(urlFormat)) return {
215
+ field: "imageBase64",
216
+ message: "invalid image data URL header"
217
+ };
218
+ if (format !== void 0 && format !== urlFormat) return {
219
+ field: "imageFormat",
220
+ message: "imageFormat does not match data URL"
221
+ };
222
+ payload = imageBase64.slice(header[0].length);
223
+ } else if (format === void 0 || !imageFormats.has(format)) return {
224
+ field: "imageFormat",
225
+ message: "raw imageBase64 requires imageFormat (jpeg, jpg, png, webp, bmp, tiff or gif)"
226
+ };
227
+ const tooLarge = {
228
+ field: "imageBase64",
229
+ message: "query image exceeds 10 MiB"
230
+ };
231
+ if (payload.length > maxQueryImageBase64Length) return tooLarge;
232
+ const base64 = payload.replace(/[\r\n]/g, "");
233
+ if (!isBase64(base64)) return {
234
+ field: "imageBase64",
235
+ message: "invalid image base64"
236
+ };
237
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
238
+ return base64.length / 4 * 3 - padding > 10485760 ? tooLarge : void 0;
239
+ }
240
+ /** Read an inline image from a retrieval hit without resolving URLs or decoding image bytes. */
241
+ function readQMindRetrievalImage(chunk) {
242
+ const url = chunk.metadata?.imageDataUrl;
243
+ if (typeof url !== "string" || url.length > 14e5) return void 0;
244
+ const header = /^data:(image\/(?:jpeg|png|webp));base64,/.exec(url);
245
+ if (!header) return void 0;
246
+ const data = url.slice(header[0].length).replace(/[\r\n]/g, "");
247
+ if (!isBase64(data)) return void 0;
89
248
  return {
90
- async createOfficePreview(notebookId, sourceId, input, options) {
91
- const audience = origin(input?.audience, "audience");
92
- const parentOrigin = origin(input?.parentOrigin, "parentOrigin");
93
- if (new URL(audience).hostname === new URL(parentOrigin).hostname) throw invalidArgument$1("Preview requires a separate hostname", "audience");
94
- return call(context, {
95
- capability: "sources.officeProxy",
96
- operation: "sources.officeProxy.create",
97
- method: "POST",
98
- idempotent: false,
99
- path: path(notebookId, sourceId),
100
- body: {
101
- nonce: opaque(input?.nonce, "nonce"),
102
- audience,
103
- parentOrigin
104
- },
105
- schema: ticketSchema,
106
- callOptions: options
107
- });
108
- },
109
- async revokeOfficePreview(notebookId, sourceId, sessionId, orgId, options) {
110
- if (typeof orgId !== "string") throw invalidArgument$1("Resource organization is required", "orgId");
111
- return call(context, {
112
- capability: "sources.officeProxy",
113
- operation: "sources.officeProxy.revoke",
114
- method: "POST",
115
- idempotent: false,
116
- path: `${path(notebookId, sourceId)}/${opaque(sessionId, "sessionId")}/revoke`,
117
- body: { orgId },
118
- schema: voidResponseSchema,
119
- callOptions: options
120
- });
121
- },
122
- async revokeAllOfficePreviews(options) {
123
- return call(context, {
124
- capability: "sources.officeProxy",
125
- operation: "sources.officeProxy.revokeAll",
126
- method: "POST",
127
- idempotent: false,
128
- path: context.profile.apiPath("weboffice", "previews", "revoke"),
129
- body: {},
130
- schema: voidResponseSchema,
131
- callOptions: options
132
- });
133
- }
249
+ mimeType: header[1],
250
+ data
134
251
  };
135
252
  }
136
253
  //#endregion
137
254
  //#region ../sdk/src/operations/agents.ts
138
- 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.";
139
- function isRecord$3(value) {
255
+ function isRecord$2(value) {
140
256
  return typeof value === "object" && value !== null && !Array.isArray(value);
141
257
  }
142
258
  function finiteNumber(value, field) {
@@ -180,52 +296,69 @@ function billingContext(value) {
180
296
  });
181
297
  }
182
298
  function retrieveBody(input) {
183
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
299
+ const fields = optionalRecord(input, "input");
300
+ if (!fields) throw invalidArgument$1("input must be an object", "input");
301
+ if (fields.imageUrl !== void 0 || fields.image_url !== void 0) throw invalidArgument$1("remote image URLs are unsupported", "imageUrl");
302
+ const imageBase64 = input.imageBase64 === void 0 ? void 0 : requiredString$1(input.imageBase64, "imageBase64");
303
+ const imageFormat = optionalTrimmedString(input.imageFormat, "imageFormat");
304
+ const query = imageBase64 ? optionalTrimmedString(input.query, "query") : requiredString$1(input.query, "query");
305
+ const issue = qmindRetrievalImageIssue({
306
+ imageBase64,
307
+ imageFormat: imageBase64 === void 0 ? input.imageFormat : imageFormat,
308
+ query
309
+ });
310
+ if (issue) throw invalidArgument$1(issue.message, issue.field);
184
311
  return compactUndefined({
312
+ imageBase64,
313
+ imageFormat,
185
314
  billingContext: billingContext(input.billingContext),
186
315
  maxResults: nonNegativeInteger$1(input.maxResults, "maxResults"),
187
- query: requiredString$2(input.query, "query"),
316
+ query,
188
317
  queryHints: queryHints(input.queryHints),
189
318
  scoreThreshold: finiteNumber(input.scoreThreshold, "scoreThreshold"),
190
319
  sourceIds: stringList(input.sourceIds ?? [], "sourceIds"),
191
320
  topK: nonNegativeInteger$1(input.topK, "topK")
192
321
  });
193
322
  }
323
+ function writableScene(value) {
324
+ if (isQMindRetiredScene(value)) throw invalidArgument$1("This Notebook scene has been retired", "sceneType");
325
+ return value;
326
+ }
194
327
  function chatSessionBody(input = {}) {
195
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
328
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
196
329
  return compactUndefined({
197
330
  metadata: optionalRecord(input.metadata, "metadata"),
198
331
  modelOverride: optionalTrimmedString(input.modelOverride, "modelOverride"),
199
- sceneType: optionalTrimmedString(input.sceneType, "sceneType") ?? "rag",
332
+ sceneType: writableScene(optionalTrimmedString(input.sceneType, "sceneType")) ?? "rag",
200
333
  status: optionalTrimmedString(input.status, "status"),
201
334
  title: optionalString$1(input.title, "title")
202
335
  });
203
336
  }
204
337
  function streamBody(input) {
205
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
338
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
206
339
  return compactUndefined({
207
- content: requiredString$2(input.content, "content"),
340
+ content: requiredString$1(input.content, "content"),
208
341
  maxResults: nonNegativeInteger$1(input.maxResults, "maxResults"),
209
342
  modelOverride: optionalTrimmedString(input.modelOverride, "modelOverride"),
210
- sceneType: optionalTrimmedString(input.sceneType, "sceneType"),
343
+ sceneType: writableScene(optionalTrimmedString(input.sceneType, "sceneType")),
211
344
  sourceIds: stringList(input.sourceIds ?? [], "sourceIds"),
212
345
  topK: nonNegativeInteger$1(input.topK, "topK")
213
346
  });
214
347
  }
215
348
  function taskRunBody(input) {
216
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
349
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
217
350
  return compactUndefined({
218
351
  chatSessionId: optionalTrimmedString(input.chatSessionId, "chatSessionId"),
219
352
  config: optionalRecord(input.config, "config"),
220
353
  parentRunId: optionalTrimmedString(input.parentRunId, "parentRunId"),
221
- sceneType: requiredString$2(input.sceneType, "sceneType"),
354
+ sceneType: writableScene(requiredString$1(input.sceneType, "sceneType")),
222
355
  settings: optionalRecord(input.settings, "settings"),
223
356
  scheduledTaskId: optionalTrimmedString(input.scheduledTaskId, "scheduledTaskId"),
224
357
  trigger: optionalTrimmedString(input.trigger, "trigger")
225
358
  });
226
359
  }
227
- function taskRunListPath(context, notebookId, input = {}) {
228
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
360
+ function taskRunListPath(notebookId, input = {}) {
361
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
229
362
  const normalizedPage = pagination$1(input);
230
363
  const status = optionalTrimmedString(input.status, "status");
231
364
  if (status !== void 0 && ![
@@ -236,7 +369,7 @@ function taskRunListPath(context, notebookId, input = {}) {
236
369
  "failed",
237
370
  "canceled"
238
371
  ].includes(status)) throw invalidArgument$1("status must be a known task run status", "status");
239
- return queryPath(context.profile.apiPath("notebooks", notebookId, "task-runs"), [
372
+ return queryPath(qmindPath("notebooks", notebookId, "task-runs"), [
240
373
  ["scheduled_task_id", optionalTrimmedString(input.scheduledTaskId, "scheduledTaskId")],
241
374
  ["parent_run_id", optionalTrimmedString(input.parentRunId, "parentRunId")],
242
375
  ["scene_type", optionalTrimmedString(input.sceneType, "sceneType")],
@@ -248,19 +381,14 @@ function taskRunListPath(context, notebookId, input = {}) {
248
381
  ]);
249
382
  }
250
383
  function agentContent(input) {
251
- if (input.scene === "rag") return {
252
- content: requiredString$2(input.question, "question"),
384
+ return {
385
+ content: requiredString$1(input.question, "question"),
253
386
  maxResults: input.maxResults,
254
387
  modelOverride: input.modelOverride,
255
388
  sceneType: "rag",
256
389
  sourceIds: input.sourceIds,
257
390
  topK: input.topK
258
391
  };
259
- return {
260
- content: `Begin the ${input.scene} workflow now for this notebook. ${workflowPrompt}`,
261
- modelOverride: input.modelOverride,
262
- sceneType: input.scene
263
- };
264
392
  }
265
393
  function callOptions$1(options) {
266
394
  return {
@@ -277,20 +405,20 @@ function streamCallOptions(options) {
277
405
  }
278
406
  function createAgentOperations(context) {
279
407
  const getChatSessionFor = (notebookId, sessionId, options, featured) => {
280
- const notebook = requiredString$2(notebookId, "notebookId");
281
- const session = requiredString$2(sessionId, "sessionId");
408
+ const notebook = requiredString$1(notebookId, "notebookId");
409
+ const session = requiredString$1(sessionId, "sessionId");
282
410
  return call(context, {
283
411
  callOptions: options,
284
412
  capability: featured ? "featuredNotebooks.read" : "chat",
285
413
  idempotent: true,
286
414
  method: "GET",
287
415
  operation: featured ? "featuredChatSessions.get" : "chatSessions.get",
288
- path: context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session),
416
+ path: qmindPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session),
289
417
  schema: chatSessionSchema
290
418
  });
291
419
  };
292
420
  const createChatSessionFor = (notebookId, input, options, featured) => {
293
- const notebook = requiredString$2(notebookId, "notebookId");
421
+ const notebook = requiredString$1(notebookId, "notebookId");
294
422
  return call(context, {
295
423
  body: chatSessionBody(input),
296
424
  callOptions: options,
@@ -298,19 +426,19 @@ function createAgentOperations(context) {
298
426
  idempotent: false,
299
427
  method: "POST",
300
428
  operation: featured ? "featuredChatSessions.create" : "chatSessions.create",
301
- path: context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions"),
429
+ path: qmindPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions"),
302
430
  schema: chatSessionSchema
303
431
  });
304
432
  };
305
433
  const createChatSession = (notebookId, input, options) => createChatSessionFor(notebookId, input, options, false);
306
434
  const createFeaturedChatSession = (notebookId, input, options) => createChatSessionFor(notebookId, input, options, true);
307
435
  const streamQuestionFor = (notebookId, sessionId, input, options, featured) => {
308
- const notebook = requiredString$2(notebookId, "notebookId");
309
- const session = requiredString$2(sessionId, "sessionId");
436
+ const notebook = requiredString$1(notebookId, "notebookId");
437
+ const session = requiredString$1(sessionId, "sessionId");
310
438
  return executeStream({
311
439
  capability: featured ? "featuredNotebooks.read" : "chat",
312
440
  operation: featured ? "featuredChat.stream" : "chat.stream",
313
- profile: context.profile,
441
+ capabilities: context.capabilities,
314
442
  request: {
315
443
  body: {
316
444
  kind: "json",
@@ -318,7 +446,7 @@ function createAgentOperations(context) {
318
446
  },
319
447
  destination: {
320
448
  kind: "host",
321
- path: queryPath(context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages", "stream"), [["client", context.client]])
449
+ path: queryPath(qmindPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages", "stream"), [["client", context.client]])
322
450
  },
323
451
  idempotent: false,
324
452
  method: "POST",
@@ -330,9 +458,9 @@ function createAgentOperations(context) {
330
458
  const streamQuestion = (notebookId, sessionId, input, options) => streamQuestionFor(notebookId, sessionId, input, options, false);
331
459
  const streamFeaturedQuestion = (notebookId, sessionId, input, options) => streamQuestionFor(notebookId, sessionId, input, options, true);
332
460
  const cancelQuestionFor = (notebookId, sessionId, input = {}, options, featured = false) => {
333
- const notebook = requiredString$2(notebookId, "notebookId");
334
- const session = requiredString$2(sessionId, "sessionId");
335
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
461
+ const notebook = requiredString$1(notebookId, "notebookId");
462
+ const session = requiredString$1(sessionId, "sessionId");
463
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
336
464
  return call(context, {
337
465
  body: compactUndefined({ reason: optionalTrimmedString(input.reason, "reason") }),
338
466
  callOptions: options,
@@ -340,12 +468,12 @@ function createAgentOperations(context) {
340
468
  idempotent: false,
341
469
  method: "POST",
342
470
  operation: featured ? "featuredChat.cancel" : "chat.cancel",
343
- path: context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages", "cancel"),
471
+ path: qmindPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages", "cancel"),
344
472
  schema: cancelQuestionResultSchema
345
473
  });
346
474
  };
347
475
  const listChatSessionsFor = (notebookId, input = {}, options, featured = false) => {
348
- const notebook = requiredString$2(notebookId, "notebookId");
476
+ const notebook = requiredString$1(notebookId, "notebookId");
349
477
  const normalizedPage = pagination$1({
350
478
  page: input.page ?? 1,
351
479
  pageSize: input.pageSize ?? 20
@@ -356,13 +484,13 @@ function createAgentOperations(context) {
356
484
  idempotent: true,
357
485
  method: "GET",
358
486
  operation: featured ? "featuredChatSessions.list" : "chatSessions.list",
359
- path: queryPath(context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions"), [["page", normalizedPage.page], ["page_size", normalizedPage.pageSize]]),
487
+ path: queryPath(qmindPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions"), [["page", normalizedPage.page], ["page_size", normalizedPage.pageSize]]),
360
488
  schema: chatSessionListSchema
361
489
  });
362
490
  };
363
491
  const listChatMessagesFor = (notebookId, sessionId, input = {}, options, featured = false) => {
364
- const notebook = requiredString$2(notebookId, "notebookId");
365
- const session = requiredString$2(sessionId, "sessionId");
492
+ const notebook = requiredString$1(notebookId, "notebookId");
493
+ const session = requiredString$1(sessionId, "sessionId");
366
494
  const normalizedPage = pagination$1({
367
495
  page: input.page ?? 1,
368
496
  pageSize: input.pageSize ?? 100
@@ -373,27 +501,27 @@ function createAgentOperations(context) {
373
501
  idempotent: true,
374
502
  method: "GET",
375
503
  operation: featured ? "featuredChatMessages.list" : "chatMessages.list",
376
- path: queryPath(context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages"), [["page", normalizedPage.page], ["page_size", normalizedPage.pageSize]]),
504
+ path: queryPath(qmindPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session, "messages"), [["page", normalizedPage.page], ["page_size", normalizedPage.pageSize]]),
377
505
  schema: chatMessageListSchema
378
506
  });
379
507
  };
380
508
  const deleteChatSessionFor = (notebookId, sessionId, options, featured = false) => {
381
- const notebook = requiredString$2(notebookId, "notebookId");
382
- const session = requiredString$2(sessionId, "sessionId");
509
+ const notebook = requiredString$1(notebookId, "notebookId");
510
+ const session = requiredString$1(sessionId, "sessionId");
383
511
  return call(context, {
384
512
  callOptions: options,
385
513
  capability: featured ? "featuredChat.delete" : "chat",
386
514
  idempotent: false,
387
515
  method: "DELETE",
388
516
  operation: featured ? "featuredChatSessions.delete" : "chatSessions.delete",
389
- path: context.profile.apiPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session),
517
+ path: qmindPath(featured ? "featured-notebooks" : "notebooks", notebook, "chat-sessions", session),
390
518
  schema: voidResponseSchema
391
519
  });
392
520
  };
393
521
  const startAgentRunFor = async (notebookId, input, options, featured) => {
394
- if (!isRecord$3(input)) throw invalidArgument$1("input must be an object", "input");
395
- if (input.scene !== "rag" && input.scene !== "compilation" && input.scene !== "lint") throw invalidArgument$1("scene must be rag, compilation or lint", "scene");
396
- const notebook = requiredString$2(notebookId, "notebookId");
522
+ if (!isRecord$2(input)) throw invalidArgument$1("input must be an object", "input");
523
+ if (input.scene !== "rag") throw invalidArgument$1("scene must be rag", "scene");
524
+ const notebook = requiredString$1(notebookId, "notebookId");
397
525
  const scene = input.scene;
398
526
  const modelOverride = optionalTrimmedString(input.modelOverride, "modelOverride");
399
527
  const title = optionalString$1(input.title, "title");
@@ -418,7 +546,7 @@ function createAgentOperations(context) {
418
546
  deleteChatSession: (notebookId, sessionId, options) => deleteChatSessionFor(notebookId, sessionId, options),
419
547
  deleteFeaturedChatSession: (notebookId, sessionId, options) => deleteChatSessionFor(notebookId, sessionId, options, true),
420
548
  async createTaskRun(notebookId, input, options) {
421
- const notebook = requiredString$2(notebookId, "notebookId");
549
+ const notebook = requiredString$1(notebookId, "notebookId");
422
550
  const body = taskRunBody(input);
423
551
  if ("sourceId" in input) throw invalidArgument$1("Use refreshSource for a source-scoped refresh.", "sourceId");
424
552
  return call(context, {
@@ -428,25 +556,25 @@ function createAgentOperations(context) {
428
556
  idempotent: false,
429
557
  method: "POST",
430
558
  operation: "taskRuns.create",
431
- path: context.profile.apiPath("notebooks", notebook, "task-runs"),
559
+ path: qmindPath("notebooks", notebook, "task-runs"),
432
560
  schema: taskRunSchema
433
561
  });
434
562
  },
435
563
  async getTaskRun(notebookId, runId, options) {
436
- const notebook = requiredString$2(notebookId, "notebookId");
437
- const run = requiredString$2(runId, "runId");
564
+ const notebook = requiredString$1(notebookId, "notebookId");
565
+ const run = requiredString$1(runId, "runId");
438
566
  return call(context, {
439
567
  callOptions: options,
440
568
  capability: "taskRuns.read",
441
569
  idempotent: true,
442
570
  method: "GET",
443
571
  operation: "taskRuns.get",
444
- path: context.profile.apiPath("notebooks", notebook, "task-runs", run),
572
+ path: qmindPath("notebooks", notebook, "task-runs", run),
445
573
  schema: taskRunSchema
446
574
  });
447
575
  },
448
576
  async listTaskRuns(notebookId, input, options) {
449
- const notebook = requiredString$2(notebookId, "notebookId");
577
+ const notebook = requiredString$1(notebookId, "notebookId");
450
578
  const sourceId = optionalTrimmedString(input?.sourceId, "sourceId");
451
579
  const result = await call(context, {
452
580
  callOptions: options,
@@ -454,7 +582,7 @@ function createAgentOperations(context) {
454
582
  idempotent: true,
455
583
  method: "GET",
456
584
  operation: "taskRuns.list",
457
- path: taskRunListPath(context, notebook, input),
585
+ path: taskRunListPath(notebook, input),
458
586
  schema: taskRunListSchema
459
587
  });
460
588
  if (sourceId !== void 0 && result.runs.some((run) => run.sourceId !== sourceId || run.notebookId !== notebook)) throw new QMindError("UNSUPPORTED_OPERATION", "The server did not honor source-scoped task history.", { operation: "taskRuns.list" });
@@ -465,11 +593,11 @@ function createAgentOperations(context) {
465
593
  listFeaturedChatMessages: (notebookId, sessionId, input, options) => listChatMessagesFor(notebookId, sessionId, input, options, true),
466
594
  listFeaturedChatSessions: (notebookId, input, options) => listChatSessionsFor(notebookId, input, options, true),
467
595
  async retrieveNotebooks(input, options) {
468
- if (!isRecord$3(input) || !Array.isArray(input.targets) || input.targets.length === 0) throw invalidArgument$1("targets must be a non-empty array", "targets");
596
+ if (!isRecord$2(input) || !Array.isArray(input.targets) || input.targets.length === 0) throw invalidArgument$1("targets must be a non-empty array", "targets");
469
597
  const seen = /* @__PURE__ */ new Set();
470
598
  const targets = input.targets.map((target) => {
471
- if (!isRecord$3(target)) throw invalidArgument$1("target must be an object", "targets");
472
- const notebookId = requiredString$2(target.notebookId, "notebookId");
599
+ if (!isRecord$2(target)) throw invalidArgument$1("target must be an object", "targets");
600
+ const notebookId = requiredString$1(target.notebookId, "notebookId");
473
601
  if (seen.has(notebookId)) throw invalidArgument$1("targets must be unique", "targets");
474
602
  seen.add(notebookId);
475
603
  if (target.preference !== void 0 && target.preference !== "default" && target.preference !== "preferred") throw invalidArgument$1("preference must be default or preferred", "preference");
@@ -490,12 +618,12 @@ function createAgentOperations(context) {
490
618
  idempotent: false,
491
619
  method: "POST",
492
620
  operation: "retrieval.retrieveNotebooks",
493
- path: context.profile.apiPath("notebooks", "retrieve"),
621
+ path: qmindPath("notebooks", "retrieve"),
494
622
  schema: retrieveNotebooksResultSchema
495
623
  });
496
624
  },
497
625
  async retrieve(notebookId, input, options) {
498
- const notebook = requiredString$2(notebookId, "notebookId");
626
+ const notebook = requiredString$1(notebookId, "notebookId");
499
627
  return call(context, {
500
628
  body: retrieveBody(input),
501
629
  callOptions: options,
@@ -503,12 +631,12 @@ function createAgentOperations(context) {
503
631
  idempotent: false,
504
632
  method: "POST",
505
633
  operation: "retrieval.retrieve",
506
- path: context.profile.apiPath("notebooks", notebook, "retrieve"),
634
+ path: qmindPath("notebooks", notebook, "retrieve"),
507
635
  schema: retrieveResultSchema
508
636
  });
509
637
  },
510
638
  async retrieveFeatured(notebookId, input, options) {
511
- const notebook = requiredString$2(notebookId, "notebookId");
639
+ const notebook = requiredString$1(notebookId, "notebookId");
512
640
  return call(context, {
513
641
  body: retrieveBody(input),
514
642
  callOptions: options,
@@ -516,7 +644,7 @@ function createAgentOperations(context) {
516
644
  idempotent: false,
517
645
  method: "POST",
518
646
  operation: "retrieval.retrieveFeatured",
519
- path: context.profile.apiPath("featured-notebooks", notebook, "retrieve"),
647
+ path: qmindPath("featured-notebooks", notebook, "retrieve"),
520
648
  schema: retrieveResultSchema
521
649
  });
522
650
  },
@@ -530,22 +658,22 @@ function createAgentOperations(context) {
530
658
  //#region ../sdk/src/operations/notebooks.ts
531
659
  function createNotebookOperations(context) {
532
660
  let wikiOperations;
533
- const loadWiki = () => wikiOperations ??= import("./wiki-branches-BfEMuXDW.js").then(({ createWikiBranchOperations }) => createWikiBranchOperations(context));
661
+ const loadWiki = () => wikiOperations ??= import("./wiki-branches-ClpusERr.js").then(({ createWikiBranchOperations }) => createWikiBranchOperations(context));
534
662
  return {
535
663
  async copyFeaturedNotebook(notebookId, options) {
536
- const notebook = requiredString$2(notebookId, "notebookId");
664
+ const notebook = requiredString$1(notebookId, "notebookId");
537
665
  return call(context, {
538
666
  callOptions: options,
539
667
  capability: "featuredNotebooks.copy",
540
668
  idempotent: false,
541
669
  method: "POST",
542
670
  operation: "featuredNotebooks.copy",
543
- path: context.profile.apiPath("featured-notebooks", notebook, "copy"),
671
+ path: qmindPath("featured-notebooks", notebook, "copy"),
544
672
  schema: notebookSchema
545
673
  });
546
674
  },
547
675
  async createNotebook(input, options) {
548
- const title = requiredString$2(input?.title, "title");
676
+ const title = requiredString$1(input?.title, "title");
549
677
  const description = optionalString$1(input?.description, "description");
550
678
  const settings = optionalRecord(input?.settings, "settings");
551
679
  return call(context, {
@@ -560,43 +688,43 @@ function createNotebookOperations(context) {
560
688
  idempotent: false,
561
689
  method: "POST",
562
690
  operation: "notebooks.create",
563
- path: context.profile.apiPath("notebooks"),
691
+ path: qmindPath("notebooks"),
564
692
  schema: notebookSchema
565
693
  });
566
694
  },
567
695
  async deleteNotebook(notebookId, options) {
568
- const id = requiredString$2(notebookId, "notebookId");
696
+ const id = requiredString$1(notebookId, "notebookId");
569
697
  return call(context, {
570
698
  callOptions: options,
571
699
  capability: "notebooks.write",
572
700
  idempotent: false,
573
701
  method: "DELETE",
574
702
  operation: "notebooks.delete",
575
- path: context.profile.apiPath("notebooks", id),
703
+ path: qmindPath("notebooks", id),
576
704
  schema: voidResponseSchema
577
705
  });
578
706
  },
579
707
  async getNotebook(notebookId, options) {
580
- const id = requiredString$2(notebookId, "notebookId");
708
+ const id = requiredString$1(notebookId, "notebookId");
581
709
  return call(context, {
582
710
  callOptions: options,
583
711
  capability: "notebooks.read",
584
712
  idempotent: true,
585
713
  method: "GET",
586
714
  operation: "notebooks.get",
587
- path: context.profile.apiPath("notebooks", id),
715
+ path: qmindPath("notebooks", id),
588
716
  schema: notebookSchema
589
717
  });
590
718
  },
591
719
  async getFeaturedNotebook(notebookId, options) {
592
- const id = requiredString$2(notebookId, "notebookId");
720
+ const id = requiredString$1(notebookId, "notebookId");
593
721
  return call(context, {
594
722
  callOptions: options,
595
723
  capability: "featuredNotebooks.read",
596
724
  idempotent: true,
597
725
  method: "GET",
598
726
  operation: "featuredNotebooks.get",
599
- path: context.profile.featuredNotebookPath(id),
727
+ path: qmindRoutes.featuredNotebookPath(id),
600
728
  schema: notebookSchema
601
729
  });
602
730
  },
@@ -608,7 +736,7 @@ function createNotebookOperations(context) {
608
736
  idempotent: true,
609
737
  method: "GET",
610
738
  operation: "featuredNotebooks.list",
611
- path: context.profile.listFeaturedNotebooksPath(normalized),
739
+ path: qmindRoutes.listFeaturedNotebooksPath(normalized),
612
740
  schema: notebookListSchema
613
741
  });
614
742
  },
@@ -616,7 +744,7 @@ function createNotebookOperations(context) {
616
744
  const normalizedPage = pagination$1(input);
617
745
  const retrievalEligibleOnly = optionalBoolean(input.retrievalEligibleOnly, "retrievalEligibleOnly");
618
746
  const client = optionalTrimmedString(input.client, "client");
619
- if (client !== void 0 && !context.profile.capabilities["notebooks.filterByClient"]) assertCapability(context.profile, "notebooks.filterByClient", "notebooks.list");
747
+ if (client !== void 0 && !context.capabilities["notebooks.filterByClient"]) assertCapability(context.capabilities, "notebooks.filterByClient", "notebooks.list");
620
748
  const normalized = {
621
749
  ...normalizedPage,
622
750
  ...retrievalEligibleOnly === void 0 ? {} : { retrievalEligibleOnly },
@@ -628,7 +756,7 @@ function createNotebookOperations(context) {
628
756
  idempotent: true,
629
757
  method: "GET",
630
758
  operation: "notebooks.list",
631
- path: context.profile.listNotebooksPath(normalized),
759
+ path: qmindRoutes.listNotebooksPath(normalized),
632
760
  schema: notebookListSchema
633
761
  });
634
762
  },
@@ -644,19 +772,19 @@ function createNotebookOperations(context) {
644
772
  idempotent: true,
645
773
  method: "GET",
646
774
  operation: "sharedNotebooks.list",
647
- path: context.profile.listSharedNotebooksPath(normalized),
775
+ path: qmindRoutes.listSharedNotebooksPath(normalized),
648
776
  schema: sharedNotebookListSchema
649
777
  });
650
778
  },
651
779
  listWikiBranches: (...args) => loadWiki().then((loaded) => loaded.listWikiBranches(...args)),
652
780
  listWikiBranchesPage: (...args) => loadWiki().then((loaded) => loaded.listWikiBranchesPage(...args)),
653
781
  async updateNotebook(notebookId, input, options) {
654
- const id = requiredString$2(notebookId, "notebookId");
782
+ const id = requiredString$1(notebookId, "notebookId");
655
783
  const body = compactUndefined({
656
784
  description: optionalString$1(input?.description, "description"),
657
785
  settings: optionalRecord(input?.settings, "settings"),
658
786
  status: optionalString$1(input?.status, "status"),
659
- title: input?.title === void 0 ? void 0 : requiredString$2(input.title, "title")
787
+ title: input?.title === void 0 ? void 0 : requiredString$1(input.title, "title")
660
788
  });
661
789
  assertNonEmptyPatch(body, "input");
662
790
  return call(context, {
@@ -666,7 +794,7 @@ function createNotebookOperations(context) {
666
794
  idempotent: false,
667
795
  method: "PUT",
668
796
  operation: "notebooks.update",
669
- path: context.profile.apiPath("notebooks", id),
797
+ path: qmindPath("notebooks", id),
670
798
  schema: notebookSchema
671
799
  });
672
800
  }
@@ -735,7 +863,7 @@ function metadataOf(source) {
735
863
  const metadata = source?.metadata;
736
864
  return metadata !== null && typeof metadata === "object" ? metadata : {};
737
865
  }
738
- function isRecord$2(value) {
866
+ function isRecord$1(value) {
739
867
  return typeof value === "object" && value !== null && !Array.isArray(value);
740
868
  }
741
869
  function text(value) {
@@ -766,7 +894,7 @@ function isQMindEmailSource(source) {
766
894
  }
767
895
  function qmindEmailAttachmentRef(source) {
768
896
  const value = metadataOf(source).emailAttachment;
769
- if (!isRecord$2(value)) return null;
897
+ if (!isRecord$1(value)) return null;
770
898
  return Object.freeze({
771
899
  emailSourceId: text(value.emailSourceId),
772
900
  index: typeof value.index === "number" && Number.isFinite(value.index) ? Math.floor(value.index) : -1,
@@ -804,7 +932,7 @@ function isQMindEmailAggregateMember(source, siblings) {
804
932
  }
805
933
  /** The external provider that owns this source, lowercased, or '' when QMind owns it. */
806
934
  function qmindSourceProvider(source) {
807
- return (source?.externalBinding?.provider ?? metadataText(source, "externalProvider", "external_provider")).toLowerCase();
935
+ return (source?.dataSource?.provider ?? source?.externalBinding?.provider ?? metadataText(source, "externalProvider", "external_provider")).toLowerCase();
808
936
  }
809
937
  /**
810
938
  * `externalBinding` is authoritative; the metadata fallback keeps sources readable on gateways that
@@ -812,11 +940,22 @@ function qmindSourceProvider(source) {
812
940
  */
813
941
  function isQMindExternalSource(source) {
814
942
  const provider = qmindSourceProvider(source);
815
- return source?.externalBinding !== void 0 || provider === "aliding" || provider === "repowiki";
943
+ return source?.dataSource !== void 0 || source?.externalBinding !== void 0 || provider === "aliding" || provider === "repowiki";
816
944
  }
817
945
  [.../* @__PURE__ */ new Set(["axls", "alxs"])];
818
- /** Operations allowed by persisted ownership, independent of the visible tree position. */
946
+ /**
947
+ * Operations allowed by persisted ownership, independent of the visible tree position.
948
+ * Managed roots may be removed as a whole through their own entry; the managed tree
949
+ * below any root is only changed by provider synchronization.
950
+ */
819
951
  function qmindSourceOperationPolicy(source) {
952
+ if (source?.dataSource) return {
953
+ rename: !source.dataSource.readOnly,
954
+ move: !source.dataSource.readOnly,
955
+ addChildren: !source.dataSource.readOnly,
956
+ delete: source.dataSource.canDelete,
957
+ menu: "ordinary"
958
+ };
820
959
  const binding = source?.externalBinding;
821
960
  if (binding === void 0) return {
822
961
  rename: true,
@@ -825,7 +964,7 @@ function qmindSourceOperationPolicy(source) {
825
964
  addChildren: true,
826
965
  menu: "ordinary"
827
966
  };
828
- const menu = binding.isRoot && binding.provider === "site_catalog" ? "site" : binding.isRoot && binding.provider === "aliding" ? "aliding" : "none";
967
+ const menu = binding.isRoot && binding.provider === "site_catalog" ? "site" : binding.isRoot && binding.provider === "aliding" ? "aliding" : binding.isRoot && binding.provider === "repowiki" ? "repowiki" : "none";
829
968
  return {
830
969
  rename: false,
831
970
  move: false,
@@ -870,7 +1009,10 @@ function buildQMindSourceTree(sources) {
870
1009
  if (node === void 0) continue;
871
1010
  const parent = nodesById.get(source.parentSourceId);
872
1011
  if (parent === void 0 || createsSourceCycle(source, sourcesById)) tree.push(node);
873
- else parent.files.push(node);
1012
+ else {
1013
+ parent.files.push(node);
1014
+ parent.hasChildren = true;
1015
+ }
874
1016
  }
875
1017
  sortSourceTree(tree);
876
1018
  return {
@@ -885,6 +1027,7 @@ function projectQMindSourceTreeNode(source, sources, files = []) {
885
1027
  ...source.learning === void 0 ? {} : { learning: source.learning },
886
1028
  ...source.learningStatus === void 0 ? {} : { learningStatus: source.learningStatus },
887
1029
  ...source.learningErrorCode === void 0 ? {} : { learningErrorCode: source.learningErrorCode },
1030
+ ...source.dataSource === void 0 ? {} : { dataSource: source.dataSource },
888
1031
  ...source.externalBinding === void 0 ? {} : { externalBinding: source.externalBinding },
889
1032
  ...source.originUrl === void 0 ? {} : { originUrl: source.originUrl },
890
1033
  ...source.metadata === void 0 ? {} : { metadata: source.metadata },
@@ -904,6 +1047,7 @@ function projectQMindSourceTreeNode(source, sources, files = []) {
904
1047
  }
905
1048
  //#endregion
906
1049
  //#region ../sdk/src/operations/sources.ts
1050
+ var SourcePaginationDrift = class extends QMindError {};
907
1051
  const maxImageBytes = 52428800;
908
1052
  function sourceBody(input) {
909
1053
  return compactUndefined({
@@ -913,7 +1057,7 @@ function sourceBody(input) {
913
1057
  path: optionalString$1(input?.path, "path"),
914
1058
  sourceType: optionalTrimmedString(input?.sourceType, "sourceType"),
915
1059
  status: optionalTrimmedString(input?.status, "status"),
916
- title: requiredString$2(input?.title, "title"),
1060
+ title: requiredString$1(input?.title, "title"),
917
1061
  uri: optionalString$1(input?.uri, "uri")
918
1062
  });
919
1063
  }
@@ -934,30 +1078,34 @@ function sourcePatch(input) {
934
1078
  return patch;
935
1079
  }
936
1080
  function siteBody(input) {
1081
+ if (typeof input === "object" && input !== null) {
1082
+ const removed = [
1083
+ "parentSourceId",
1084
+ "pathPrefix",
1085
+ "compileAfterRefresh"
1086
+ ].find((field) => Reflect.get(input, field) !== void 0);
1087
+ if (removed !== void 0) throw invalidArgument$1(`${removed} is unsupported for site import`, removed);
1088
+ }
937
1089
  const maxPages = positiveInteger$1(input?.maxPages, "maxPages") ?? 50;
938
1090
  if (maxPages > 200) throw invalidArgument$1("maxPages must not exceed 200", "maxPages");
939
1091
  const includePaths = stringList(input?.includePaths ?? [], "includePaths");
940
1092
  const excludePaths = stringList(input?.excludePaths ?? [], "excludePaths");
941
1093
  const sitemap = optionalTrimmedString(input?.sitemapUrl, "sitemapUrl");
942
- const compileAfterRefresh = optionalBoolean(input?.compileAfterRefresh, "compileAfterRefresh");
943
1094
  return compactUndefined({
944
1095
  config: compactUndefined({
945
- compileAfterRefresh,
946
1096
  excludePaths,
947
1097
  includePaths,
948
1098
  maxPages,
949
1099
  rootUrl: httpUrl(input?.rootUrl, "rootUrl"),
950
1100
  sitemapUrl: sitemap === void 0 ? void 0 : httpUrl(sitemap, "sitemapUrl")
951
1101
  }),
952
- parentSourceId: optionalString$1(input?.parentSourceId, "parentSourceId"),
953
- path: optionalString$1(input?.pathPrefix, "pathPrefix"),
954
1102
  sourceType: "site_import",
955
1103
  title: optionalTrimmedString(input?.title, "title")
956
1104
  });
957
1105
  }
958
1106
  function createSourceOperations(context) {
959
1107
  const createSource = async (notebookId, input, options) => {
960
- const notebook = requiredString$2(notebookId, "notebookId");
1108
+ const notebook = requiredString$1(notebookId, "notebookId");
961
1109
  return call(context, {
962
1110
  body: sourceBody(input),
963
1111
  callOptions: options,
@@ -965,13 +1113,13 @@ function createSourceOperations(context) {
965
1113
  idempotent: false,
966
1114
  method: "POST",
967
1115
  operation: "sources.create",
968
- path: context.profile.apiPath("notebooks", notebook, "sources"),
1116
+ path: qmindPath("notebooks", notebook, "sources"),
969
1117
  schema: sourceSchema
970
1118
  });
971
1119
  };
972
1120
  const updateSource = async (notebookId, sourceId, input, options) => {
973
- const notebook = requiredString$2(notebookId, "notebookId");
974
- const source = requiredString$2(sourceId, "sourceId");
1121
+ const notebook = requiredString$1(notebookId, "notebookId");
1122
+ const source = requiredString$1(sourceId, "sourceId");
975
1123
  return call(context, {
976
1124
  body: sourcePatch(input),
977
1125
  callOptions: options,
@@ -979,22 +1127,26 @@ function createSourceOperations(context) {
979
1127
  idempotent: false,
980
1128
  method: "PUT",
981
1129
  operation: "sources.update",
982
- path: context.profile.apiPath("notebooks", notebook, "sources", source),
1130
+ path: qmindPath("notebooks", notebook, "sources", source),
983
1131
  schema: sourceSchema
984
1132
  });
985
1133
  };
986
1134
  const readSourcePage = async (notebookId, input = {}, options, operation = "sources.list") => {
987
- const notebook = requiredString$2(notebookId, "notebookId");
988
- const normalizedPage = pagination$1(input);
1135
+ const notebook = requiredString$1(notebookId, "notebookId");
1136
+ const featured = operation === "featuredSources.list" || operation === "featuredSources.children.list";
1137
+ const normalizedPage = pagination$1(featured ? {
1138
+ page: input.page ?? 1,
1139
+ pageSize: input.pageSize ?? 200
1140
+ } : input);
989
1141
  const isDir = optionalBoolean(input.isDir, "isDir");
990
1142
  const view = input.view ?? "list";
991
1143
  if (view !== "list" && view !== "children") throw invalidArgument$1("view must be either \"list\" or \"children\"", "view");
992
1144
  const parentSourceId = optionalString$1(input.parentSourceId, "parentSourceId");
993
1145
  const query = optionalTrimmedString(input.query, "query");
994
- if (view === "children") assertCapability(context.profile, "sources.children", "sources.list");
995
- if (query !== void 0) assertCapability(context.profile, "sources.search", "sources.list");
1146
+ if (!featured && view === "children") assertCapability(context.capabilities, "sources.children", operation);
1147
+ if (!featured && query !== void 0) assertCapability(context.capabilities, "sources.search", operation);
996
1148
  if (parentSourceId !== void 0 && view !== "children") throw invalidArgument$1("parentSourceId requires view=\"children\"", "parentSourceId");
997
- const path = queryPath(context.profile.apiPath("notebooks", notebook, "sources"), [
1149
+ const path = queryPath(qmindPath(featured ? "featured-notebooks" : "notebooks", notebook, "sources"), [
998
1150
  ["view", view === "list" ? void 0 : view],
999
1151
  ["is_dir", isDir === void 0 ? void 0 : String(isDir)],
1000
1152
  ["parent_source_id", parentSourceId],
@@ -1004,7 +1156,7 @@ function createSourceOperations(context) {
1004
1156
  ]);
1005
1157
  return call(context, {
1006
1158
  callOptions: options,
1007
- capability: "sources.read",
1159
+ capability: featured ? "featuredNotebooks.read" : "sources.read",
1008
1160
  idempotent: true,
1009
1161
  method: "GET",
1010
1162
  operation,
@@ -1013,6 +1165,7 @@ function createSourceOperations(context) {
1013
1165
  });
1014
1166
  };
1015
1167
  const listSources = (notebookId, input, options) => readSourcePage(notebookId, input, options);
1168
+ const listFeaturedSources = (notebookId, input, options) => readSourcePage(notebookId, input, options, "featuredSources.list");
1016
1169
  const normalizeChildrenPage = (page) => ({
1017
1170
  ...page,
1018
1171
  sources: page.sources.map((source) => ({
@@ -1020,85 +1173,69 @@ function createSourceOperations(context) {
1020
1173
  hasChildren: source.hasChildren ?? (source.childrenCount === void 0 ? source.isDir : source.childrenCount > 0)
1021
1174
  }))
1022
1175
  });
1023
- const isMissingChildrenRoute = (error) => error instanceof QMindError && (error.status === 404 || error.status === 405 || error.upstreamCode?.toLowerCase() === "routenotfound");
1024
- const listFeaturedSources = async (notebookId, input = {}, options) => {
1025
- const notebook = requiredString$2(notebookId, "notebookId");
1026
- const normalizedPage = pagination$1({
1027
- page: input.page ?? 1,
1028
- pageSize: input.pageSize ?? 200
1029
- });
1030
- const parentSourceId = optionalString$1(input.parentSourceId, "parentSourceId");
1031
- const view = input.view ?? "list";
1032
- if (view !== "list" && view !== "children") throw invalidArgument$1("view must be either \"list\" or \"children\"", "view");
1033
- return call(context, {
1034
- callOptions: options,
1035
- capability: "featuredNotebooks.read",
1036
- idempotent: true,
1037
- method: "GET",
1038
- operation: "featuredSources.list",
1039
- path: queryPath(context.profile.apiPath("featured-notebooks", notebook, "sources"), [
1040
- ["view", view === "list" ? void 0 : view],
1041
- ["parent_source_id", parentSourceId],
1042
- ["page", normalizedPage.page],
1043
- ["page_size", normalizedPage.pageSize]
1044
- ]),
1045
- schema: sourceListSchema
1046
- });
1047
- };
1048
- const listSourceChildrenPage = async (featured, notebookId, input, options) => {
1049
- const notebook = requiredString$2(notebookId, "notebookId");
1050
- const { page, pageSize } = pagination$1({
1051
- page: input.page ?? 1,
1052
- pageSize: input.pageSize ?? 100
1053
- });
1054
- const parentSourceId = optionalString$1(input.parentSourceId, "parentSourceId");
1055
- const collection = featured ? "featured-notebooks" : "notebooks";
1056
- const operation = featured ? "featuredSources.children.list" : "sources.children.list";
1057
- if (featured || context.profile.access !== "sash") try {
1058
- const result = await call(context, {
1059
- callOptions: options,
1060
- capability: featured ? "featuredNotebooks.read" : "sources.children",
1061
- idempotent: true,
1062
- method: "GET",
1063
- operation,
1064
- path: queryPath(context.profile.apiPath(collection, notebook, "source-tree", "children"), [
1065
- ["parent_source_id", parentSourceId],
1066
- ["page", page],
1067
- ["page_size", pageSize]
1068
- ]),
1069
- schema: sourceListSchema.nullable()
1070
- });
1071
- if (result !== null) return normalizeChildrenPage(result);
1072
- } catch (error) {
1073
- if (!isMissingChildrenRoute(error)) throw error;
1074
- }
1075
- const fallbackInput = {
1176
+ const listSourceChildrenPage = async (operation, notebookId, input, options) => {
1177
+ const page = input.page ?? 1;
1178
+ const pageSize = input.pageSize ?? 100;
1179
+ if (page > 2147483647 || pageSize > 500) throw invalidArgument$1("Source children pagination exceeds the supported range", "pagination");
1180
+ const result = await readSourcePage(notebookId, {
1181
+ parentSourceId: input.parentSourceId,
1182
+ isDir: input.isDir,
1076
1183
  page,
1077
1184
  pageSize,
1078
- parentSourceId,
1079
1185
  view: "children"
1080
- };
1081
- return normalizeChildrenPage(featured ? await listFeaturedSources(notebook, fallbackInput, options) : await readSourcePage(notebook, fallbackInput, options, "sources.children.list"));
1186
+ }, options, operation);
1187
+ return normalizeChildrenPage(result);
1082
1188
  };
1083
- const listSourceChildren = (notebookId, input = {}, options) => listSourceChildrenPage(false, notebookId, input, options);
1084
- const listFeaturedSourceChildren = (notebookId, input = {}, options) => listSourceChildrenPage(true, notebookId, input, options);
1085
- const collectAllSources = async (notebookId, input = {}, options, operation) => {
1086
- const notebook = requiredString$2(notebookId, "notebookId");
1189
+ const listSourceChildren = (notebookId, input = {}, options) => listSourceChildrenPage("sources.children.list", notebookId, input, options);
1190
+ const listFeaturedSourceChildren = (notebookId, input = {}, options) => listSourceChildrenPage("featuredSources.children.list", notebookId, input, options);
1191
+ const readAllSourcePages = async (notebookId, input, options, operation) => {
1192
+ const notebook = requiredString$1(notebookId, "notebookId");
1087
1193
  const pageSize = positiveInteger$1(input.pageSize, "pageSize") ?? 200;
1088
1194
  const maxPages = positiveInteger$1(input.maxPages, "maxPages") ?? 1e4;
1089
1195
  const sources = [];
1196
+ const seenOnPage = /* @__PURE__ */ new Map();
1197
+ let lastPage = 0;
1198
+ let totalSize = 0;
1090
1199
  for (let page = 1; page <= maxPages; page += 1) {
1091
1200
  const result = await readSourcePage(notebook, {
1092
1201
  page,
1093
- pageSize,
1094
- view: "list"
1202
+ pageSize
1095
1203
  }, options, operation);
1096
- sources.push(...result.sources);
1097
- const lastPage = result.pages?.lastPage;
1098
- if (result.sources.length < pageSize || lastPage !== void 0 && page >= lastPage) return sources;
1204
+ for (const source of result.sources) {
1205
+ const previousPage = seenOnPage.get(source.id);
1206
+ if (previousPage !== void 0) throw new (previousPage === page ? QMindError : SourcePaginationDrift)("PROTOCOL_ERROR", "source pagination returned a duplicate ID", {
1207
+ details: { page },
1208
+ operation
1209
+ });
1210
+ seenOnPage.set(source.id, page);
1211
+ sources.push(source);
1212
+ }
1213
+ lastPage = Math.max(lastPage, result.pages?.lastPage ?? 0);
1214
+ totalSize = Math.max(totalSize, result.totalSize ?? 0, result.pages?.totalSize ?? 0);
1215
+ const emptyPage = result.sources.length === 0;
1216
+ if (emptyPage || lastPage > 0 && page >= lastPage) {
1217
+ if (sources.length < totalSize || emptyPage && lastPage > 1 && page <= lastPage) throw new SourcePaginationDrift("PROTOCOL_ERROR", "source pagination ended before the declared end", {
1218
+ details: {
1219
+ page,
1220
+ lastPage,
1221
+ totalSize,
1222
+ received: sources.length
1223
+ },
1224
+ operation
1225
+ });
1226
+ return sources;
1227
+ }
1228
+ if (lastPage > page) continue;
1229
+ if (totalSize > 0) {
1230
+ if (sources.length >= totalSize) return sources;
1231
+ } else {
1232
+ const serverPageSize = result.pageSize || result.pages?.pageSize;
1233
+ const nextPage = result.pages?.nextPage;
1234
+ if (nextPage && nextPage > page) continue;
1235
+ if (nextPage === page || serverPageSize && result.sources.length < serverPageSize) return sources;
1236
+ }
1099
1237
  }
1100
1238
  throw new QMindError("PROTOCOL_ERROR", `source pagination exceeded ${maxPages} pages`, {
1101
- access: context.profile.access,
1102
1239
  details: {
1103
1240
  maxPages,
1104
1241
  pageSize
@@ -1106,24 +1243,19 @@ function createSourceOperations(context) {
1106
1243
  operation
1107
1244
  });
1108
1245
  };
1109
- const listAllSources = (notebookId, input, options) => collectAllSources(notebookId, input, options, "sources.list");
1110
- const getSourceTree = async (notebookId, options) => {
1111
- const notebook = requiredString$2(notebookId, "notebookId");
1112
- assertCapability(context.profile, "sources.tree", "sources.tree");
1113
- if (context.profile.access === "sash") return buildQMindSourceTree(await collectAllSources(notebook, {}, options, "sources.tree"));
1114
- return call(context, {
1115
- callOptions: options,
1116
- capability: "sources.tree",
1117
- idempotent: true,
1118
- method: "GET",
1119
- operation: "sources.tree",
1120
- path: queryPath(context.profile.apiPath("notebooks", notebook, "sources"), [["view", "filetree"]]),
1121
- schema: sourceTreeSchema
1122
- });
1246
+ const collectAllSources = async (notebookId, input, options, operation) => {
1247
+ try {
1248
+ return await readAllSourcePages(notebookId, input, options, operation);
1249
+ } catch (error) {
1250
+ if (!(error instanceof SourcePaginationDrift)) throw error;
1251
+ return readAllSourcePages(notebookId, input, options, operation);
1252
+ }
1123
1253
  };
1254
+ const listAllSources = (notebookId, input = {}, options) => collectAllSources(notebookId, input, options, "sources.list");
1255
+ const getSourceTree = async (notebookId, options) => buildQMindSourceTree(await collectAllSources(notebookId, {}, options, "sources.tree"));
1124
1256
  return {
1125
1257
  async batchDeleteSources(notebookId, sourceIds, options) {
1126
- const notebook = requiredString$2(notebookId, "notebookId");
1258
+ const notebook = requiredString$1(notebookId, "notebookId");
1127
1259
  const ids = stringList(sourceIds, "sourceIds", { min: 1 });
1128
1260
  return call(context, {
1129
1261
  body: { sourceIds: ids },
@@ -1132,18 +1264,19 @@ function createSourceOperations(context) {
1132
1264
  idempotent: false,
1133
1265
  method: "POST",
1134
1266
  operation: "sources.batchDelete",
1135
- path: context.profile.apiPath("notebooks", notebook, "sources", "batch-delete"),
1267
+ path: qmindPath("notebooks", notebook, "sources", "batch-delete"),
1136
1268
  schema: batchDeleteResultSchema
1137
1269
  });
1138
1270
  },
1139
1271
  async countSourceChildren(notebookId, parentIds, options) {
1140
- const notebook = requiredString$2(notebookId, "notebookId");
1272
+ const notebook = requiredString$1(notebookId, "notebookId");
1141
1273
  const ids = stringList(parentIds, "parentIds", {
1142
1274
  max: 200,
1143
- min: 1
1275
+ min: 1,
1276
+ keepEmptyString: true
1144
1277
  });
1145
- assertCapability(context.profile, "sources.childrenCount", "sources.childrenCount");
1146
- const path = context.profile.mindPath("notebooks", notebook, "sources", "children-count");
1278
+ assertCapability(context.capabilities, "sources.childrenCount", "sources.childrenCount");
1279
+ const path = qmindPath("notebooks", notebook, "sources", "children-count");
1147
1280
  const query = new URLSearchParams();
1148
1281
  for (const id of ids) query.append("parent_ids", id);
1149
1282
  return call(context, {
@@ -1157,7 +1290,7 @@ function createSourceOperations(context) {
1157
1290
  });
1158
1291
  },
1159
1292
  async createDirectory(notebookId, input, options) {
1160
- const title = requiredString$2(input?.title, "title");
1293
+ const title = requiredString$1(input?.title, "title");
1161
1294
  return createSource(notebookId, {
1162
1295
  isDir: true,
1163
1296
  parentSourceId: input?.parentSourceId,
@@ -1168,100 +1301,100 @@ function createSourceOperations(context) {
1168
1301
  },
1169
1302
  createSource,
1170
1303
  async createSourceWebOfficeSession(notebookId, sourceId, options) {
1171
- const notebook = requiredString$2(notebookId, "notebookId");
1172
- const source = requiredString$2(sourceId, "sourceId");
1173
- assertCapability(context.profile, "sources.webOffice", "sources.webOffice.create");
1304
+ const notebook = requiredString$1(notebookId, "notebookId");
1305
+ const source = requiredString$1(sourceId, "sourceId");
1306
+ assertCapability(context.capabilities, "sources.webOffice", "sources.webOffice.create");
1174
1307
  return call(context, {
1175
1308
  callOptions: options,
1176
1309
  capability: "sources.webOffice",
1177
1310
  idempotent: false,
1178
1311
  method: "POST",
1179
1312
  operation: "sources.webOffice.create",
1180
- path: context.profile.apiPath("notebooks", notebook, "sources", source, "weboffice", "session"),
1313
+ path: nezhaWebOfficePath(context.webOffice, notebook, source, "session"),
1181
1314
  schema: sourceWebOfficeSessionSchema
1182
1315
  });
1183
1316
  },
1184
1317
  async deleteSource(notebookId, sourceId, options) {
1185
- const notebook = requiredString$2(notebookId, "notebookId");
1186
- const source = requiredString$2(sourceId, "sourceId");
1318
+ const notebook = requiredString$1(notebookId, "notebookId");
1319
+ const source = requiredString$1(sourceId, "sourceId");
1187
1320
  return call(context, {
1188
1321
  callOptions: options,
1189
1322
  capability: "sources.write",
1190
1323
  idempotent: false,
1191
1324
  method: "DELETE",
1192
1325
  operation: "sources.delete",
1193
- path: context.profile.apiPath("notebooks", notebook, "sources", source),
1326
+ path: qmindPath("notebooks", notebook, "sources", source),
1194
1327
  schema: voidResponseSchema
1195
1328
  });
1196
1329
  },
1197
1330
  async getFeaturedSource(notebookId, sourceId, options) {
1198
- const notebook = requiredString$2(notebookId, "notebookId");
1199
- const source = requiredString$2(sourceId, "sourceId");
1331
+ const notebook = requiredString$1(notebookId, "notebookId");
1332
+ const source = requiredString$1(sourceId, "sourceId");
1200
1333
  return call(context, {
1201
1334
  callOptions: options,
1202
1335
  capability: "featuredNotebooks.read",
1203
1336
  idempotent: true,
1204
1337
  method: "GET",
1205
1338
  operation: "featuredSources.get",
1206
- path: context.profile.apiPath("featured-notebooks", notebook, "sources", source),
1339
+ path: qmindPath("featured-notebooks", notebook, "sources", source),
1207
1340
  schema: sourceSchema
1208
1341
  });
1209
1342
  },
1210
1343
  async getFeaturedSourceContent(notebookId, sourceId, options) {
1211
- const notebook = requiredString$2(notebookId, "notebookId");
1212
- const source = requiredString$2(sourceId, "sourceId");
1344
+ const notebook = requiredString$1(notebookId, "notebookId");
1345
+ const source = requiredString$1(sourceId, "sourceId");
1213
1346
  return call(context, {
1214
1347
  callOptions: options,
1215
1348
  capability: "featuredNotebooks.read",
1216
1349
  idempotent: true,
1217
1350
  method: "GET",
1218
1351
  operation: "featuredSources.content",
1219
- path: context.profile.apiPath("featured-notebooks", notebook, "sources", source, "content"),
1352
+ path: qmindPath("featured-notebooks", notebook, "sources", source, "content"),
1220
1353
  schema: sourceContentSchema
1221
1354
  });
1222
1355
  },
1223
1356
  async getFeaturedSourcePreview(notebookId, sourceId, options) {
1224
- const notebook = requiredString$2(notebookId, "notebookId");
1225
- const source = requiredString$2(sourceId, "sourceId");
1357
+ const notebook = requiredString$1(notebookId, "notebookId");
1358
+ const source = requiredString$1(sourceId, "sourceId");
1226
1359
  return call(context, {
1227
1360
  callOptions: options,
1228
1361
  capability: "featuredNotebooks.read",
1229
1362
  idempotent: true,
1230
1363
  method: "GET",
1231
1364
  operation: "featuredSources.preview",
1232
- path: context.profile.apiPath("featured-notebooks", notebook, "sources", source, "preview"),
1365
+ path: qmindPath("featured-notebooks", notebook, "sources", source, "preview"),
1233
1366
  schema: sourcePreviewSchema
1234
1367
  });
1235
1368
  },
1236
1369
  async getFeaturedSourceRawContent(notebookId, sourceId, options) {
1237
- const notebook = requiredString$2(notebookId, "notebookId");
1238
- const source = requiredString$2(sourceId, "sourceId");
1370
+ const notebook = requiredString$1(notebookId, "notebookId");
1371
+ const source = requiredString$1(sourceId, "sourceId");
1239
1372
  return call(context, {
1240
1373
  callOptions: options,
1241
1374
  capability: "featuredNotebooks.read",
1242
1375
  idempotent: true,
1243
1376
  method: "GET",
1244
1377
  operation: "featuredSources.rawContent",
1245
- path: context.profile.apiPath("featured-notebooks", notebook, "sources", source, "raw-content"),
1378
+ path: qmindPath("featured-notebooks", notebook, "sources", source, "raw-content"),
1246
1379
  schema: sourceRawContentSchema
1247
1380
  });
1248
1381
  },
1249
1382
  async getSource(notebookId, sourceId, options) {
1250
- const notebook = requiredString$2(notebookId, "notebookId");
1251
- const source = requiredString$2(sourceId, "sourceId");
1383
+ const notebook = requiredString$1(notebookId, "notebookId");
1384
+ const source = requiredString$1(sourceId, "sourceId");
1252
1385
  return call(context, {
1253
1386
  callOptions: options,
1254
1387
  capability: "sources.read",
1255
1388
  idempotent: true,
1256
1389
  method: "GET",
1257
1390
  operation: "sources.get",
1258
- path: context.profile.apiPath("notebooks", notebook, "sources", source),
1391
+ path: qmindPath("notebooks", notebook, "sources", source),
1259
1392
  schema: sourceSchema
1260
1393
  });
1261
1394
  },
1262
1395
  async refreshSource(notebookId, sourceId, options) {
1263
- const notebook = requiredString$2(notebookId, "notebookId");
1264
- const source = requiredString$2(sourceId, "sourceId");
1396
+ const notebook = requiredString$1(notebookId, "notebookId");
1397
+ const source = requiredString$1(sourceId, "sourceId");
1265
1398
  try {
1266
1399
  const run = await call(context, {
1267
1400
  callOptions: options,
@@ -1269,7 +1402,7 @@ function createSourceOperations(context) {
1269
1402
  idempotent: false,
1270
1403
  method: "POST",
1271
1404
  operation: "sources.refresh",
1272
- path: context.profile.apiPath("notebooks", notebook, "sources", source, "refresh"),
1405
+ path: qmindPath("notebooks", notebook, "sources", source, "refresh"),
1273
1406
  body: {},
1274
1407
  schema: taskRunSchema
1275
1408
  });
@@ -1290,25 +1423,25 @@ function createSourceOperations(context) {
1290
1423
  idempotent: true,
1291
1424
  method: "POST",
1292
1425
  operation: "sources.retryIngestion",
1293
- path: context.profile.apiPath("notebooks", requiredString$2(notebookId, "notebookId"), "sources", requiredString$2(sourceId, "sourceId"), "retry"),
1426
+ path: qmindPath("notebooks", requiredString$1(notebookId, "notebookId"), "sources", requiredString$1(sourceId, "sourceId"), "retry"),
1294
1427
  body: {
1295
- retryKey: requiredString$2(input.retryKey, "retryKey"),
1296
- expectedUpdatedAt: requiredString$2(input.expectedUpdatedAt, "expectedUpdatedAt"),
1428
+ retryKey: requiredString$1(input.retryKey, "retryKey"),
1429
+ expectedUpdatedAt: requiredString$1(input.expectedUpdatedAt, "expectedUpdatedAt"),
1297
1430
  ...input.expectedVectorRetryAt !== void 0 ? { expectedVectorRetryAt: input.expectedVectorRetryAt } : {}
1298
1431
  },
1299
1432
  schema: sourceSchema
1300
1433
  });
1301
1434
  },
1302
1435
  async getSourceContent(notebookId, sourceId, options) {
1303
- const notebook = requiredString$2(notebookId, "notebookId");
1304
- const source = requiredString$2(sourceId, "sourceId");
1436
+ const notebook = requiredString$1(notebookId, "notebookId");
1437
+ const source = requiredString$1(sourceId, "sourceId");
1305
1438
  return call(context, {
1306
1439
  callOptions: options,
1307
1440
  capability: "sources.read",
1308
1441
  idempotent: true,
1309
1442
  method: "GET",
1310
1443
  operation: "sources.content",
1311
- path: context.profile.apiPath("notebooks", notebook, "sources", source, "content"),
1444
+ path: qmindPath("notebooks", notebook, "sources", source, "content"),
1312
1445
  schema: sourceContentSchema
1313
1446
  });
1314
1447
  },
@@ -1319,33 +1452,33 @@ function createSourceOperations(context) {
1319
1452
  idempotent: true,
1320
1453
  method: "GET",
1321
1454
  operation: "sources.actionAccess",
1322
- path: context.profile.mindPath("source-actions", "access"),
1455
+ path: qmindPath("source-actions", "access"),
1323
1456
  schema: sourceActionAccessSchema
1324
1457
  });
1325
1458
  },
1326
1459
  async getSourcePreview(notebookId, sourceId, options) {
1327
- const notebook = requiredString$2(notebookId, "notebookId");
1328
- const source = requiredString$2(sourceId, "sourceId");
1460
+ const notebook = requiredString$1(notebookId, "notebookId");
1461
+ const source = requiredString$1(sourceId, "sourceId");
1329
1462
  return call(context, {
1330
1463
  callOptions: options,
1331
1464
  capability: "sources.preview",
1332
1465
  idempotent: true,
1333
1466
  method: "GET",
1334
1467
  operation: "sources.preview",
1335
- path: context.profile.apiPath("notebooks", notebook, "sources", source, "preview"),
1468
+ path: qmindPath("notebooks", notebook, "sources", source, "preview"),
1336
1469
  schema: sourcePreviewSchema
1337
1470
  });
1338
1471
  },
1339
1472
  async getSourceRawContent(notebookId, sourceId, options) {
1340
- const notebook = requiredString$2(notebookId, "notebookId");
1341
- const source = requiredString$2(sourceId, "sourceId");
1473
+ const notebook = requiredString$1(notebookId, "notebookId");
1474
+ const source = requiredString$1(sourceId, "sourceId");
1342
1475
  return call(context, {
1343
1476
  callOptions: options,
1344
1477
  capability: "sources.rawContent",
1345
1478
  idempotent: true,
1346
1479
  method: "GET",
1347
1480
  operation: "sources.rawContent",
1348
- path: context.profile.apiPath("notebooks", notebook, "sources", source, "raw-content"),
1481
+ path: qmindPath("notebooks", notebook, "sources", source, "raw-content"),
1349
1482
  schema: sourceRawContentSchema
1350
1483
  });
1351
1484
  },
@@ -1356,7 +1489,7 @@ function createSourceOperations(context) {
1356
1489
  idempotent: true,
1357
1490
  method: "GET",
1358
1491
  operation: "sources.quota",
1359
- path: context.profile.mindPath("source-quota"),
1492
+ path: qmindPath("source-quota"),
1360
1493
  schema: sourceQuotaSchema
1361
1494
  });
1362
1495
  },
@@ -1367,7 +1500,7 @@ function createSourceOperations(context) {
1367
1500
  idempotent: true,
1368
1501
  method: "GET",
1369
1502
  operation: "sources.uploadCapabilities",
1370
- path: context.profile.mindPath("source-upload", "capabilities"),
1503
+ path: qmindPath("source-upload", "capabilities"),
1371
1504
  schema: sourceUploadCapabilitiesSchema
1372
1505
  });
1373
1506
  },
@@ -1375,16 +1508,13 @@ function createSourceOperations(context) {
1375
1508
  return preflightSourceUpload(context, notebookId, options);
1376
1509
  },
1377
1510
  async getFeaturedSourceTree(notebookId, options) {
1378
- return buildQMindSourceTree((await listFeaturedSources(notebookId, {
1379
- page: 1,
1380
- pageSize: 200
1381
- }, options)).sources);
1511
+ return buildQMindSourceTree(await collectAllSources(notebookId, {}, options, "featuredSources.list"));
1382
1512
  },
1383
1513
  getSourceTree,
1384
1514
  listFeaturedSourceChildren,
1385
1515
  listSourceChildren,
1386
1516
  async importSite(notebookId, input, options) {
1387
- const notebook = requiredString$2(notebookId, "notebookId");
1517
+ const notebook = requiredString$1(notebookId, "notebookId");
1388
1518
  return call(context, {
1389
1519
  body: siteBody(input),
1390
1520
  callOptions: options,
@@ -1392,12 +1522,12 @@ function createSourceOperations(context) {
1392
1522
  idempotent: false,
1393
1523
  method: "POST",
1394
1524
  operation: "sources.importSite",
1395
- path: context.profile.apiPath("notebooks", notebook, "sources"),
1525
+ path: qmindPath("notebooks", notebook, "sources"),
1396
1526
  schema: sourceSchema
1397
1527
  });
1398
1528
  },
1399
1529
  async importWebLinks(notebookId, input, options) {
1400
- const notebook = requiredString$2(notebookId, "notebookId");
1530
+ const notebook = requiredString$1(notebookId, "notebookId");
1401
1531
  const urls = stringList(input?.urls ?? [], "urls", {
1402
1532
  max: 5,
1403
1533
  min: 1
@@ -1414,12 +1544,12 @@ function createSourceOperations(context) {
1414
1544
  idempotent: false,
1415
1545
  method: "POST",
1416
1546
  operation: "sources.importWeb",
1417
- path: context.profile.apiPath("notebooks", notebook, "sources"),
1547
+ path: qmindPath("notebooks", notebook, "sources"),
1418
1548
  schema: sourceImportResultsSchema
1419
1549
  });
1420
1550
  },
1421
1551
  async importWikiDocuments(notebookId, input, options) {
1422
- const notebook = requiredString$2(notebookId, "notebookId");
1552
+ const notebook = requiredString$1(notebookId, "notebookId");
1423
1553
  const urls = stringList(input?.urls ?? [], "urls", {
1424
1554
  max: 5,
1425
1555
  min: 1
@@ -1436,7 +1566,7 @@ function createSourceOperations(context) {
1436
1566
  idempotent: false,
1437
1567
  method: "POST",
1438
1568
  operation: "sources.importWiki",
1439
- path: context.profile.apiPath("notebooks", notebook, "sources"),
1569
+ path: qmindPath("notebooks", notebook, "sources"),
1440
1570
  schema: sourceImportResultsSchema
1441
1571
  });
1442
1572
  },
@@ -1458,10 +1588,10 @@ function createSourceOperations(context) {
1458
1588
  return updateSource(notebookId, sourceId, patch, options);
1459
1589
  },
1460
1590
  async presignImageUpload(notebookId, sourceId, input, options) {
1461
- const notebook = requiredString$2(notebookId, "notebookId");
1462
- const source = requiredString$2(sourceId, "sourceId");
1463
- const filename = requiredString$2(input?.filename, "filename");
1464
- const mimeType = requiredString$2(input?.mimeType, "mimeType");
1591
+ const notebook = requiredString$1(notebookId, "notebookId");
1592
+ const source = requiredString$1(sourceId, "sourceId");
1593
+ const filename = requiredString$1(input?.filename, "filename");
1594
+ const mimeType = requiredString$1(input?.mimeType, "mimeType");
1465
1595
  const size = nonNegativeInteger$1(input?.size, "size");
1466
1596
  if (size === void 0) throw invalidArgument$1("size must be a non-negative integer", "size");
1467
1597
  if (size > maxImageBytes) throw invalidArgument$1(`size must not exceed ${maxImageBytes} bytes`, "size");
@@ -1476,16 +1606,16 @@ function createSourceOperations(context) {
1476
1606
  idempotent: false,
1477
1607
  method: "POST",
1478
1608
  operation: "images.presignUpload",
1479
- path: context.profile.apiPath("notebooks", notebook, "sources", source, "images", "presign"),
1609
+ path: qmindPath("notebooks", notebook, "sources", source, "images", "presign"),
1480
1610
  schema: imageUploadTicketSchema
1481
1611
  });
1482
1612
  },
1483
1613
  async refreshSourceWebOfficeSession(notebookId, sourceId, input, options) {
1484
- const notebook = requiredString$2(notebookId, "notebookId");
1485
- const source = requiredString$2(sourceId, "sourceId");
1486
- const sessionId = requiredString$2(input?.sessionId, "sessionId");
1614
+ const notebook = requiredString$1(notebookId, "notebookId");
1615
+ const source = requiredString$1(sourceId, "sourceId");
1616
+ const sessionId = requiredString$1(input?.sessionId, "sessionId");
1487
1617
  const tokenVersion = nonNegativeInteger$1(input?.tokenVersion, "tokenVersion") ?? 0;
1488
- assertCapability(context.profile, "sources.webOffice", "sources.webOffice.refresh");
1618
+ assertCapability(context.capabilities, "sources.webOffice", "sources.webOffice.refresh");
1489
1619
  return call(context, {
1490
1620
  body: { tokenVersion },
1491
1621
  callOptions: options,
@@ -1493,12 +1623,12 @@ function createSourceOperations(context) {
1493
1623
  idempotent: false,
1494
1624
  method: "POST",
1495
1625
  operation: "sources.webOffice.refresh",
1496
- path: context.profile.apiPath("notebooks", notebook, "sources", source, "weboffice", "session", sessionId, "refresh"),
1626
+ path: nezhaWebOfficePath(context.webOffice, notebook, source, "session", sessionId, "refresh"),
1497
1627
  schema: sourceWebOfficeTokenSchema
1498
1628
  });
1499
1629
  },
1500
1630
  async presignImageUrls(notebookId, ossKeys, options) {
1501
- const notebook = requiredString$2(notebookId, "notebookId");
1631
+ const notebook = requiredString$1(notebookId, "notebookId");
1502
1632
  const keys = stringList(ossKeys, "ossKeys", {
1503
1633
  max: 100,
1504
1634
  min: 1
@@ -1510,7 +1640,7 @@ function createSourceOperations(context) {
1510
1640
  idempotent: false,
1511
1641
  method: "POST",
1512
1642
  operation: "images.presignUrls",
1513
- path: context.profile.apiPath("notebooks", notebook, "images", "presign-urls"),
1643
+ path: qmindPath("notebooks", notebook, "images", "presign-urls"),
1514
1644
  schema: imageUrlsSchema
1515
1645
  });
1516
1646
  },
@@ -1518,292 +1648,10 @@ function createSourceOperations(context) {
1518
1648
  };
1519
1649
  }
1520
1650
  //#endregion
1521
- //#region ../sdk/src/capabilities.ts
1522
- const dashboardCapabilities = Object.freeze({
1523
- "wiki.read": true,
1524
- botGateway: true,
1525
- chat: true,
1526
- "featuredChat.delete": false,
1527
- compilation: true,
1528
- "featuredNotebooks.read": true,
1529
- "featuredNotebooks.copy": true,
1530
- "images.presignUpload": false,
1531
- "images.presignUrls": false,
1532
- "imports.aliDing": true,
1533
- "imports.discover": true,
1534
- "imports.fullSiteURL": true,
1535
- members: true,
1536
- "members.search": true,
1537
- "members.resolve": true,
1538
- "notebooks.filterByClient": false,
1539
- "notebooks.read": true,
1540
- "notebooks.write": true,
1541
- "notes.read": true,
1542
- "notes.write": true,
1543
- "notes.saveCondensation": true,
1544
- retrieval: true,
1545
- scheduledTasks: true,
1546
- "sharedNotebooks.read": true,
1547
- "sources.children": true,
1548
- "sources.childrenCount": true,
1549
- "sources.actionAccess": false,
1550
- "sources.importWeb": true,
1551
- "sources.preview": true,
1552
- "sources.rawContent": true,
1553
- "sources.read": true,
1554
- "sources.quota": true,
1555
- "sources.search": true,
1556
- "sources.tree": true,
1557
- "sources.webOffice": true,
1558
- "sources.officeProxy": true,
1559
- "sources.write": true,
1560
- "taskRuns.read": true,
1561
- "taskRuns.write": true,
1562
- transfers: true,
1563
- "wikiBranches.read": true,
1564
- "wikiBranches.page": true
1565
- });
1566
- const sashCapabilities = Object.freeze({
1567
- "wiki.read": false,
1568
- botGateway: false,
1569
- chat: true,
1570
- "featuredChat.delete": false,
1571
- compilation: false,
1572
- "featuredNotebooks.read": true,
1573
- "featuredNotebooks.copy": true,
1574
- "images.presignUpload": true,
1575
- "images.presignUrls": true,
1576
- "imports.aliDing": true,
1577
- "imports.discover": true,
1578
- "imports.fullSiteURL": false,
1579
- members: true,
1580
- "members.search": false,
1581
- "members.resolve": true,
1582
- "notebooks.filterByClient": true,
1583
- "notebooks.read": true,
1584
- "notebooks.write": true,
1585
- "notes.read": true,
1586
- "notes.write": true,
1587
- "notes.saveCondensation": false,
1588
- retrieval: true,
1589
- scheduledTasks: true,
1590
- "sharedNotebooks.read": true,
1591
- "sources.children": true,
1592
- "sources.childrenCount": false,
1593
- "sources.actionAccess": true,
1594
- "sources.importWeb": true,
1595
- "sources.preview": true,
1596
- "sources.rawContent": true,
1597
- "sources.read": true,
1598
- "sources.quota": true,
1599
- "sources.search": false,
1600
- "sources.tree": true,
1601
- "sources.webOffice": true,
1602
- "sources.officeProxy": true,
1603
- "sources.write": true,
1604
- "taskRuns.read": true,
1605
- "taskRuns.write": true,
1606
- transfers: true,
1607
- "wikiBranches.read": true,
1608
- "wikiBranches.page": true
1609
- });
1610
- function capabilitiesFor(access) {
1611
- return access === "sash" ? sashCapabilities : dashboardCapabilities;
1612
- }
1613
- //#endregion
1614
- //#region ../sdk/src/profiles.ts
1615
- function isRecord$1(value) {
1616
- return typeof value === "object" && value !== null && !Array.isArray(value);
1617
- }
1618
- function encodeId(value) {
1619
- return encodeURIComponent(value);
1620
- }
1621
- function appendQuery(path, entries) {
1622
- const query = new URLSearchParams();
1623
- for (const [key, value] of entries) if (value !== void 0 && value !== "") query.set(key, String(value));
1624
- const suffix = query.toString();
1625
- return suffix ? `${path}?${suffix}` : path;
1626
- }
1627
- function dashboardEnvelope(body) {
1628
- if (!isRecord$1(body) || typeof body.status !== "number" || !("data" in body)) return body;
1629
- return body.data;
1630
- }
1631
- function firstResultSource(access, operation, body) {
1632
- if (!isRecord$1(body) || !Array.isArray(body.results)) return body;
1633
- const first = body.results[0];
1634
- if (!isRecord$1(first)) return void 0;
1635
- if ("source" in first) return first.source;
1636
- if (typeof first.error === "string" && first.error.length > 0) throw new QMindError("REMOTE_ERROR", first.error, {
1637
- access,
1638
- details: first,
1639
- operation,
1640
- status: 200
1641
- });
1642
- }
1643
- function normalizeSuccess(access, operation, body) {
1644
- const unwrapped = access === "dashboard" ? dashboardEnvelope(body) : body;
1645
- if (access !== "dashboard") return unwrapped;
1646
- if (operation === "sources.create" || operation === "sources.importSite") return firstResultSource(access, operation, unwrapped);
1647
- if (operation === "transfers.source.multipart" || operation === "transfers.source.register") return firstResultSource(access, operation, unwrapped);
1648
- return unwrapped;
1649
- }
1650
- function streamError(access, message, details) {
1651
- return new QMindError("STREAM_ERROR", message, {
1652
- access,
1653
- ...details === void 0 ? {} : { details },
1654
- operation: "chat.stream"
1655
- });
1656
- }
1657
- function requiredString$1(access, value, field) {
1658
- if (value !== void 0 && value.length > 0) return value;
1659
- throw streamError(access, `stream event is missing ${field}`, { field });
1660
- }
1661
- function stringValue$1(value) {
1662
- return value ?? "";
1663
- }
1664
- function presentString(access, value, field) {
1665
- if (value !== void 0) return value;
1666
- throw streamError(access, `stream event is missing ${field}`, { field });
1667
- }
1668
- function decodeStreamEvent(access, rawBody) {
1669
- const candidate = access === "dashboard" ? dashboardEnvelope(rawBody) : rawBody;
1670
- const parsed = streamWireEventSchema.safeParse(candidate);
1671
- if (!parsed.success) throw streamError(access, "stream event does not match the QMind contract", { issues: parsed.error.issues });
1672
- const event = parsed.data;
1673
- const eventType = event.eventType ?? event.event_type ?? event.type;
1674
- switch (eventType) {
1675
- case "message_start": return {
1676
- citations: event.citations ?? [],
1677
- reranked: event.reranked ?? false,
1678
- totalContextChunks: event.totalContextChunks ?? 0,
1679
- type: "messageStart",
1680
- ...event.assistantMessageId === void 0 ? {} : { assistantMessageId: event.assistantMessageId },
1681
- ...event.userMessage === void 0 ? {} : { userMessage: event.userMessage }
1682
- };
1683
- case "tool_call_start": return {
1684
- step: event.step ?? 0,
1685
- toolArguments: stringValue$1(event.toolArguments),
1686
- toolName: requiredString$1(access, event.toolName, "toolName"),
1687
- type: "toolCallStart",
1688
- ...event.toolDisplayName === void 0 ? {} : { toolDisplayName: event.toolDisplayName }
1689
- };
1690
- case "tool_call_result": return {
1691
- step: event.step ?? 0,
1692
- toolName: requiredString$1(access, event.toolName, "toolName"),
1693
- toolResult: stringValue$1(event.toolResult),
1694
- type: "toolCallResult",
1695
- ...event.toolDisplayName === void 0 ? {} : { toolDisplayName: event.toolDisplayName }
1696
- };
1697
- case "delta": return {
1698
- delta: presentString(access, event.delta, "delta"),
1699
- type: "delta"
1700
- };
1701
- case "batch_progress": return {
1702
- metadata: event.metadata ?? {},
1703
- type: "batchProgress"
1704
- };
1705
- case "heartbeat": return {
1706
- metadata: event.metadata ?? {},
1707
- type: "heartbeat"
1708
- };
1709
- case "cancel": return {
1710
- canceled: true,
1711
- type: "cancel",
1712
- ...event.cancelReason === void 0 ? {} : { cancelReason: event.cancelReason }
1713
- };
1714
- case "message_complete": return {
1715
- canceled: event.canceled ?? false,
1716
- citations: event.citations ?? [],
1717
- metadata: event.metadata ?? {},
1718
- promptContext: event.promptContext ?? "",
1719
- reranked: event.reranked ?? false,
1720
- totalContextChunks: event.totalContextChunks ?? 0,
1721
- type: "messageComplete",
1722
- ...event.assistantMessage === void 0 ? {} : { assistantMessage: event.assistantMessage },
1723
- ...event.cancelReason === void 0 ? {} : { cancelReason: event.cancelReason }
1724
- };
1725
- case "error": return {
1726
- message: requiredString$1(access, event.errorMessage ?? event.error, "errorMessage"),
1727
- type: "error"
1728
- };
1729
- default: throw streamError(access, "stream event has an unsupported event type", { eventType });
1730
- }
1731
- }
1732
- function decodeStreamPayload(access, payload) {
1733
- let value;
1734
- try {
1735
- value = JSON.parse(payload);
1736
- } catch (cause) {
1737
- throw streamError(access, "stream event is not valid JSON", { cause });
1738
- }
1739
- return decodeStreamEvent(access, value);
1740
- }
1741
- function createProfile(access, apiPrefix) {
1742
- const capabilities = capabilitiesFor(access);
1743
- const apiPath = (...segments) => {
1744
- return `${apiPrefix}/${segments.map((segment) => encodeId(segment)).join("/")}`;
1745
- };
1746
- return Object.freeze({
1747
- access,
1748
- capabilities,
1749
- apiPath,
1750
- wikiReadPath(organizationId, operation) {
1751
- return apiPath("organizations", organizationId, "knowledge", "wiki", operation);
1752
- },
1753
- decodeStreamPayload(payload) {
1754
- return decodeStreamPayload(access, payload);
1755
- },
1756
- featuredNotebookPath(notebookId) {
1757
- return notebookId === void 0 ? apiPath("featured-notebooks") : apiPath("featured-notebooks", notebookId);
1758
- },
1759
- listFeaturedNotebooksPath(input) {
1760
- return appendQuery(`${apiPrefix}/featured-notebooks`, [["page", input.page], ["page_size", input.pageSize]]);
1761
- },
1762
- listNotebooksPath(input) {
1763
- return appendQuery(`${apiPrefix}/notebooks`, [
1764
- ["page", input.page],
1765
- ["page_size", input.pageSize],
1766
- ["client", input.client],
1767
- ["retrieval_eligible_only", input.retrievalEligibleOnly]
1768
- ]);
1769
- },
1770
- listSharedNotebooksPath(input) {
1771
- return appendQuery(`${apiPrefix}/notebooks/shared`, [
1772
- ["page", input.page],
1773
- ["page_size", input.pageSize],
1774
- ["retrieval_eligible_only", input.retrievalEligibleOnly]
1775
- ]);
1776
- },
1777
- mindPath(...segments) {
1778
- return `/api/v1/mind/${segments.map((segment) => encodeId(segment)).join("/")}`;
1779
- },
1780
- notebookPath(notebookId) {
1781
- return notebookId === void 0 ? apiPath("notebooks") : apiPath("notebooks", notebookId);
1782
- },
1783
- unwrapError(body) {
1784
- return access === "dashboard" ? dashboardEnvelope(body) : body;
1785
- },
1786
- unwrapSuccess(operation, body) {
1787
- return normalizeSuccess(access, operation, body);
1788
- },
1789
- wikiBranchesPath(notebookId) {
1790
- return apiPath("notebooks", notebookId, "wiki-branches");
1791
- }
1792
- });
1793
- }
1794
- const dashboardProfile = createProfile("dashboard", "/api/v1");
1795
- const sashProfile = createProfile("sash", "/sash/api/v1");
1796
- function profileFor(access) {
1797
- return access === "sash" ? sashProfile : dashboardProfile;
1798
- }
1799
- //#endregion
1800
1651
  //#region ../sdk/src/client.ts
1801
1652
  function isRecord(value) {
1802
1653
  return typeof value === "object" && value !== null && !Array.isArray(value);
1803
1654
  }
1804
- function isQMindAccess(value) {
1805
- return value === "sash" || value === "dashboard";
1806
- }
1807
1655
  function isQMindTransport(value) {
1808
1656
  if (!isRecord(value)) return false;
1809
1657
  return typeof value.request === "function" && typeof value.stream === "function";
@@ -1812,15 +1660,11 @@ const managementOperationNames = [
1812
1660
  "addMember",
1813
1661
  "createScheduledTask",
1814
1662
  "deleteScheduledTask",
1815
- "getCompilationSettings",
1816
- "getCompilationStatus",
1817
1663
  "listMembers",
1818
1664
  "listScheduledTasks",
1819
1665
  "removeMember",
1820
1666
  "resolveMemberCandidate",
1821
- "saveCompilationSettings",
1822
1667
  "searchMemberCandidates",
1823
- "startCompilation",
1824
1668
  "updateMemberPermission",
1825
1669
  "updateScheduledTask"
1826
1670
  ];
@@ -1841,25 +1685,30 @@ const noteOperationNames = [
1841
1685
  "saveCondensationResult",
1842
1686
  "updateNote"
1843
1687
  ];
1844
- const botGatewayOperationNames = [
1845
- "listPlatformApps",
1846
- "createPlatformApp",
1847
- "updatePlatformApp",
1848
- "deletePlatformApp",
1849
- "listExpertBindings",
1850
- "updateExpertBinding",
1851
- "deleteExpertBinding",
1852
- "listGroupBindings",
1853
- "createGroupBinding",
1854
- "updateGroupBinding",
1855
- "deleteGroupBinding",
1856
- "publishDingTalk",
1857
- "inviteDingTalkExpert"
1858
- ];
1688
+ function createLazyDataSourceOperations(context) {
1689
+ let operations;
1690
+ const load = () => {
1691
+ operations ??= import("./data-sources-BMWzGZMy.js").then(({ createDataSourceOperations }) => createDataSourceOperations(context));
1692
+ return operations;
1693
+ };
1694
+ return {
1695
+ listDataSources: (...args) => load().then((value) => value.listDataSources(...args)),
1696
+ getDataSource: (...args) => load().then((value) => value.getDataSource(...args)),
1697
+ createDataSource: (...args) => load().then((value) => value.createDataSource(...args)),
1698
+ updateDataSource: (...args) => load().then((value) => value.updateDataSource(...args)),
1699
+ setDataSourceCredentials: (...args) => load().then((value) => value.setDataSourceCredentials(...args)),
1700
+ deleteDataSource: (...args) => load().then((value) => value.deleteDataSource(...args)),
1701
+ previewDataSource: (...args) => load().then((value) => value.previewDataSource(...args)),
1702
+ validateDataSource: (...args) => load().then((value) => value.validateDataSource(...args)),
1703
+ listDataSourceResources: (...args) => load().then((value) => value.listDataSourceResources(...args)),
1704
+ requestDataSourceSync: (...args) => load().then((value) => value.requestDataSourceSync(...args)),
1705
+ listDataSourceRuns: (...args) => load().then((value) => value.listDataSourceRuns(...args))
1706
+ };
1707
+ }
1859
1708
  function createLazyTransferOperations(context) {
1860
1709
  let operations;
1861
1710
  const load = () => {
1862
- operations ??= import("./transfers-DONoEIKT.js").then(({ createTransferOperations }) => createTransferOperations(context));
1711
+ operations ??= import("./transfers-BUZM2vVy.js").then(({ createTransferOperations }) => createTransferOperations(context));
1863
1712
  return operations;
1864
1713
  };
1865
1714
  return {
@@ -1870,7 +1719,7 @@ function createLazyTransferOperations(context) {
1870
1719
  function createLazyWikiOperations(context) {
1871
1720
  let operations;
1872
1721
  const load = () => {
1873
- operations ??= import("./wiki-DBT6JdyN.js").then(({ createWikiOperations }) => createWikiOperations(context));
1722
+ operations ??= import("./wiki-C76wZ3j_.js").then(({ createWikiOperations }) => createWikiOperations(context));
1874
1723
  return operations;
1875
1724
  };
1876
1725
  return {
@@ -1879,18 +1728,10 @@ function createLazyWikiOperations(context) {
1879
1728
  searchWikiSections: (...args) => load().then((loaded) => loaded.searchWikiSections(...args))
1880
1729
  };
1881
1730
  }
1882
- function createLazyBotGatewayOperations(context) {
1883
- let operations;
1884
- const load = () => {
1885
- operations ??= import("./bot-gateway-C4c1bMi9.js").then(({ createBotGatewayOperations }) => createBotGatewayOperations(context));
1886
- return operations;
1887
- };
1888
- return Object.fromEntries(botGatewayOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
1889
- }
1890
1731
  function createLazyNoteOperations(context) {
1891
1732
  let operations;
1892
1733
  const load = () => {
1893
- operations ??= import("./notes-HS_N--cJ.js").then(({ createNoteOperations }) => createNoteOperations(context));
1734
+ operations ??= import("./notes-Cz178zE-.js").then(({ createNoteOperations }) => createNoteOperations(context));
1894
1735
  return operations;
1895
1736
  };
1896
1737
  return Object.fromEntries(noteOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
@@ -1898,7 +1739,7 @@ function createLazyNoteOperations(context) {
1898
1739
  function createLazyImportOperations(context) {
1899
1740
  let operations;
1900
1741
  const load = () => {
1901
- operations ??= import("./imports-Bb3NHsmd.js").then(({ createImportOperations }) => createImportOperations(context));
1742
+ operations ??= import("./imports-DHdWJ9rK.js").then(({ createImportOperations }) => createImportOperations(context));
1902
1743
  return operations;
1903
1744
  };
1904
1745
  return Object.fromEntries(importOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
@@ -1906,24 +1747,27 @@ function createLazyImportOperations(context) {
1906
1747
  function createLazyManagementOperations(context) {
1907
1748
  let operations;
1908
1749
  const load = () => {
1909
- operations ??= import("./management-BYR88TwO.js").then(({ createManagementOperations }) => createManagementOperations(context));
1750
+ operations ??= import("./management-D4dfHim9.js").then(({ createManagementOperations }) => createManagementOperations(context));
1910
1751
  return operations;
1911
1752
  };
1912
1753
  return Object.fromEntries(managementOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
1913
1754
  }
1914
1755
  function createQMindClient(options) {
1915
1756
  if (!isRecord(options)) throw invalidArgument$1("client options must be an object", "options");
1916
- if (!isQMindAccess(options.access)) throw invalidArgument$1("access must be either \"sash\" or \"dashboard\"", "access");
1917
1757
  if (!isQMindTransport(options.transport)) throw invalidArgument$1("transport must implement request() and stream()", "transport");
1918
- const profile = profileFor(options.access);
1758
+ const nezha = options.nezha;
1759
+ const webOffice = nezha?.webOffice;
1760
+ if (nezha !== void 0 && (!isRecord(nezha) || webOffice !== void 0 && webOffice !== "sash" && webOffice !== "dashboard" || nezha.repoWiki !== void 0 && typeof nezha.repoWiki !== "boolean")) throw invalidArgument$1("invalid Nezha capability options", "nezha");
1761
+ const capabilities = createCapabilities(nezha ?? {});
1919
1762
  const context = {
1920
1763
  client: optionalTrimmedString(options.client, "client") ?? "qmind",
1921
- profile,
1764
+ capabilities,
1765
+ webOffice,
1922
1766
  transport: options.transport
1923
1767
  };
1924
1768
  return Object.freeze({
1925
- access: profile.access,
1926
- capabilities: profile.capabilities,
1769
+ capabilities,
1770
+ ...createLazyDataSourceOperations(context),
1927
1771
  ...createNotebookOperations(context),
1928
1772
  ...createLazyWikiOperations(context),
1929
1773
  ...createSourceOperations(context),
@@ -1931,11 +1775,10 @@ function createQMindClient(options) {
1931
1775
  ...createLazyImportOperations(context),
1932
1776
  ...createLazyManagementOperations(context),
1933
1777
  ...createLazyNoteOperations(context),
1934
- ...createLazyBotGatewayOperations(context),
1935
1778
  ...createLazyTransferOperations(context),
1936
1779
  ...createAgentOperations(context),
1937
1780
  supports(capability) {
1938
- return profile.capabilities[capability] === true;
1781
+ return capabilities[capability] === true;
1939
1782
  }
1940
1783
  });
1941
1784
  }
@@ -2003,7 +1846,7 @@ function canonicalize(object, seen = /* @__PURE__ */ new Set()) {
2003
1846
  }
2004
1847
  //#endregion
2005
1848
  //#region ../agent-core/src/contract.ts
2006
- const CONTRACT_VERSION = "7.0.0";
1849
+ const CONTRACT_VERSION = "8.1.0";
2007
1850
  const AGENT_ERROR_CODES = Object.freeze([
2008
1851
  "invalid_input",
2009
1852
  "selection_required",
@@ -2054,17 +1897,35 @@ const listNotebooksInputSchema = z.object({
2054
1897
  cursor: z.string().min(1).max(512).optional()
2055
1898
  }).strict();
2056
1899
  const retrieveInputSchema = z.object({
1900
+ imageBase64: z.string().trim().min(1).describe("Image data URL or standard Base64. One image, up to 10 MiB before encoding.").optional(),
1901
+ imageFormat: z.string().trim().min(1).describe("Required for raw Base64: jpeg, jpg, png, webp, bmp, tiff or gif.").optional(),
2057
1902
  maxResults: z.number().int().min(1).max(50).default(8),
2058
1903
  notebookId: opaqueId.optional(),
2059
1904
  targets: z.array(z.object({
2060
1905
  notebookId: opaqueId,
2061
1906
  sourceIds: z.array(opaqueId).min(1).max(100).refine((ids) => new Set(ids).size === ids.length).optional()
2062
1907
  }).strict()).min(1).max(32).refine((targets) => new Set(targets.map((target) => target.notebookId)).size === targets.length).optional(),
2063
- query: z.string().trim().min(1).max(2e3),
2064
- scoreThreshold: z.number().min(0).max(1).optional(),
1908
+ query: z.string().trim().min(1).max(2e3).describe(`Text query, up to 128 UTF-16 units with an image.`).optional(),
1909
+ scoreThreshold: z.number().min(0).max(1).describe("Minimum score for non-OTS retrieval.").optional(),
2065
1910
  sourceIds: z.array(opaqueId).min(1).max(50).refine((values) => new Set(values).size === values.length, { message: "sourceIds must be unique" }).optional(),
2066
1911
  topK: z.number().int().min(1).max(100).optional()
2067
- }).strict().refine((value) => value.notebookId === void 0 || value.targets === void 0, { message: "notebookId and targets are mutually exclusive" }).refine((value) => value.sourceIds === void 0 || value.notebookId !== void 0, { message: "sourceIds requires notebookId; otherwise put sourceIds inside each target" });
1912
+ }).strict().refine((value) => value.notebookId === void 0 || value.targets === void 0, { message: "notebookId and targets are mutually exclusive" }).refine((value) => value.sourceIds === void 0 || value.notebookId !== void 0, { message: "sourceIds requires notebookId; otherwise put sourceIds inside each target" }).superRefine(({ query, imageBase64, imageFormat }, context) => {
1913
+ if (query === void 0 && imageBase64 === void 0 && imageFormat === void 0) context.addIssue({
1914
+ code: "custom",
1915
+ path: ["query"],
1916
+ message: "Provide query or imageBase64"
1917
+ });
1918
+ const issue = qmindRetrievalImageIssue({
1919
+ imageBase64,
1920
+ imageFormat,
1921
+ query
1922
+ });
1923
+ if (issue) context.addIssue({
1924
+ code: "custom",
1925
+ path: [issue.field],
1926
+ message: issue.message
1927
+ });
1928
+ });
2068
1929
  const listSourcesInputSchema = z.object({
2069
1930
  notebookId: opaqueId,
2070
1931
  page,
@@ -2161,7 +2022,7 @@ const agentToolDefinitions = Object.freeze([
2161
2022
  intent: "write",
2162
2023
  destructive: true,
2163
2024
  deadlineMs: 12e4,
2164
- description: "Update source text using baseUpdatedAt from a fresh read and optionally a SHA-256 content snapshot. This preflight is not atomic compare-and-swap. The server automatically handles learning for the updated source; observe get_source/read_source for readiness. No separate task is created. Reconcile outcome_unknown before any new write."
2025
+ description: "Update source text and optional title without changing source type or original format, using baseUpdatedAt from a fresh read and optionally a SHA-256 content snapshot. Conflicting Markdown type and original format are rejected. This preflight is not atomic compare-and-swap. The server automatically handles learning for the updated source; observe get_source/read_source for readiness. No separate task is created. Reconcile outcome_unknown before any new write."
2165
2026
  },
2166
2027
  {
2167
2028
  id: "qmind.refresh_source",
@@ -2194,7 +2055,7 @@ const agentToolDefinitions = Object.freeze([
2194
2055
  },
2195
2056
  {
2196
2057
  deadlineMs: 6e4,
2197
- description: `Retrieve globally ranked context from up to 32 QMind notebooks using targets [{notebookId, sourceIds?}]. Discover candidates with list_notebooks; continue with nextCursor as needed and select relevant targets using summary/topics (overview), with title/description as fallback. The server authorizes each target within the current retrieval scope, including configured sharing groups. Do not select or switch organizations. Workspace-linked notebooks are preferred automatically; preference never expands scope. Use notebookId for one notebook or targets for one to 32 notebooks. Omitted selection uses configured defaults; maxResults is the global result limit.`,
2058
+ description: `Retrieve globally ranked context from up to 32 QMind notebooks using text (query), an image (imageBase64), or both. For imageBase64 send an image data URL or raw Base64 with imageFormat; use actual image bytes from an attachment. Discover candidates with list_notebooks; continue with nextCursor as needed and select relevant targets using summary/topics (overview), with title/description as fallback. The server authorizes each target within the current retrieval scope, including configured sharing groups. Do not select or switch organizations. Workspace-linked notebooks are preferred automatically; preference never expands scope. Use notebookId for one notebook or targets [{notebookId, sourceIds?}] for one to 32 notebooks. Omitted selection uses configured defaults; maxResults is the global result limit.`,
2198
2059
  id: "qmind.retrieve",
2199
2060
  intent: "read",
2200
2061
  leaf: "retrieve"
@@ -2259,14 +2120,14 @@ const agentToolDefinitions = Object.freeze([
2259
2120
  },
2260
2121
  {
2261
2122
  deadlineMs: 3e4,
2262
- description: "Create an enabled built-in scheduled task in one QMind notebook. Requires manage permission. Use an explicit CRON_TZ/TZ IANA zone followed by five or six cron fields; the server validates cron syntax. No arbitrary prompt or config. source_binding_sync is AliDing-only, one active configuration per notebook (including paused tasks), five fields and at least five minutes apart. compilation may be retired by the server. Saving does not execute the task or prove ingestion completed. Never retry outcome_unknown automatically; list current tasks to reconcile, and do not treat an identical schedule as proof of creation.",
2123
+ description: "Create an enabled built-in scheduled task in one QMind notebook. Requires manage permission. Use an explicit CRON_TZ/TZ IANA zone followed by five or six cron fields; the server validates cron syntax. No arbitrary prompt or config. source_binding_sync is AliDing-only, one active configuration per notebook (including paused tasks), five fields and at least five minutes apart. Supported creation scenes are condensation, source_refresh and source_binding_sync. Saving does not execute the task or prove ingestion completed. Never retry outcome_unknown automatically; list current tasks to reconcile, and do not treat an identical schedule as proof of creation.",
2263
2124
  id: "qmind.create_scheduled_task",
2264
2125
  intent: "write",
2265
2126
  leaf: "create_scheduled_task"
2266
2127
  },
2267
2128
  {
2268
2129
  deadlineMs: 3e4,
2269
- description: "Update a scheduled task in one QMind notebook by taskId. Requires manage permission. Provide schedule and/or enabled; false pauses and true resumes. Schedule requires an explicit CRON_TZ/TZ IANA zone. Config and sceneType cannot be changed. Resuming an overdue task can dispatch at the next scheduler tick; it does not recalculate nextRunAt. Pausing cannot cancel work already dispatched or read by the scheduler. Never retry outcome_unknown automatically; list tasks to inspect current state first. Preflight and write are not atomic.",
2130
+ description: "Update a scheduled task in one QMind notebook by taskId. Requires manage permission. Provide schedule and/or enabled; false pauses and true resumes. Historical compilation and lint tasks accept only enabled=false. Schedule requires an explicit CRON_TZ/TZ IANA zone. Config and sceneType cannot be changed. Resuming an overdue task can dispatch at the next scheduler tick; it does not recalculate nextRunAt. Pausing cannot cancel work already dispatched or read by the scheduler. Never retry outcome_unknown automatically; list tasks to inspect current state first. Preflight and write are not atomic.",
2270
2131
  id: "qmind.update_scheduled_task",
2271
2132
  intent: "write",
2272
2133
  destructive: true,
@@ -2354,6 +2215,7 @@ const canonicalDescriptor = canonicalize(deepFreeze({
2354
2215
  defaultRetrievalMode: "all?; explicit host opt-in searches each authorized target with concurrency at most 3 and bounded partial results",
2355
2216
  defaultNotebookRelationship: "owned|shared|featured|all?; host discovery default independent of notebookPolicy; omitted means owned",
2356
2217
  approvedDeletionTargets: "SourceDeletionTarget[1..100]?; host-only, must match fresh targets",
2218
+ includeRetrievalImages: "boolean?; host opt-in to inline images in retrieve results",
2357
2219
  notebookPolicy: { selectNotebook: "host callback: excluded|allowed|preferred; request-local; intersects server ACL" },
2358
2220
  notebookScope: {
2359
2221
  allowedNotebookIds: "uniqueOpaqueId[]",
@@ -2418,6 +2280,8 @@ const canonicalDescriptor = canonicalize(deepFreeze({
2418
2280
  {
2419
2281
  id: "qmind.update_source_content",
2420
2282
  intent: "write",
2283
+ writeFields: ["content", "title?"],
2284
+ sourceIdentity: "preserved; conflicting Markdown type and original format rejected",
2421
2285
  timeoutMs: 12e4,
2422
2286
  annotations: {
2423
2287
  destructiveHint: true,
@@ -2525,11 +2389,13 @@ const canonicalDescriptor = canonicalize(deepFreeze({
2525
2389
  defaults: { maxResults: 8 },
2526
2390
  id: "qmind.retrieve",
2527
2391
  input: {
2392
+ imageBase64: "image data URL or standard Base64?; at most 10 MiB decoded",
2393
+ imageFormat: "jpeg|jpg|png|webp|bmp|tiff|gif?; required for raw Base64",
2528
2394
  maxResults: "integer:1..50?",
2529
2395
  notebookId: "opaqueId?; exclusive with targets",
2530
- targets: "[{notebookId, sourceIds?}][1..5]?; unique notebooks",
2531
- query: "string:1..2000",
2532
- scoreThreshold: "number:0..1?",
2396
+ targets: `[{notebookId, sourceIds?}][1..32]?; unique notebooks`,
2397
+ query: `string:1..2000?; at most 128 UTF-16 units with an image; at least one of query and imageBase64 is required`,
2398
+ scoreThreshold: "number:0..1?; applies to non-OTS retrieval",
2533
2399
  sourceIds: "uniqueOpaqueId[1..50]?",
2534
2400
  topK: "integer:1..100?"
2535
2401
  },
@@ -2539,6 +2405,7 @@ const canonicalDescriptor = canonicalize(deepFreeze({
2539
2405
  chunkId: "opaqueId",
2540
2406
  chunkIndex: "integer:0..",
2541
2407
  content: "string",
2408
+ image: "{mimeType: image/jpeg|image/png|image/webp, data: Base64}?; bounded inline image",
2542
2409
  notebookId: "opaqueId",
2543
2410
  notebookTitle: "string",
2544
2411
  originUrl: "string?",
@@ -2771,7 +2638,7 @@ const canonicalDescriptor = canonicalize(deepFreeze({
2771
2638
  intent: "write",
2772
2639
  input: {
2773
2640
  notebookId: "opaqueId",
2774
- sceneType: "ScheduledTask.sceneType",
2641
+ sceneType: "condensation|source_refresh|source_binding_sync",
2775
2642
  schedule: "explicit-IANA-zone-prefixed-cron:1..512; server validates syntax and scene interval"
2776
2643
  },
2777
2644
  output: "ScheduledTask; enabled=true",
@@ -2790,7 +2657,7 @@ const canonicalDescriptor = canonicalize(deepFreeze({
2790
2657
  notebookId: "opaqueId",
2791
2658
  taskId: "opaqueId",
2792
2659
  schedule: "explicit-IANA-zone-prefixed-cron:1..512?",
2793
- enabled: "boolean?; at least one patch field"
2660
+ enabled: "boolean?; at least one patch field; retired scenes accept only enabled=false"
2794
2661
  },
2795
2662
  output: "ScheduledTask",
2796
2663
  timeoutMs: 3e4
@@ -2979,6 +2846,7 @@ async function updateSourceContent(client, input, invocation) {
2979
2846
  if (!client.updateSource) return failure$1(invocation.operationId, "capability_unavailable", "Source writeback is unavailable.");
2980
2847
  const current = await client.getSource(input.notebookId, input.sourceId, callOptions(invocation));
2981
2848
  if (current.isDir) return failure$1(invocation.operationId, "invalid_input", "Directory content cannot be updated.");
2849
+ if (/^(md|markdown)$/iu.test(current.sourceType.trim()) && [current.metadata?.sourceFormat, current.metadata?.source_format].some((format) => format !== void 0 && format !== null && format !== "" && (typeof format !== "string" || !/^(md|markdown)$/iu.test(format.trim())))) return failure$1(invocation.operationId, "invalid_input", "Source type conflicts with its original format; resolve the source identity before editing.");
2982
2850
  if (current.updatedAt !== input.baseUpdatedAt) return failure$1(invocation.operationId, "source_conflict", "Source changed; read it before editing.");
2983
2851
  if (input.baseContentHash !== void 0) {
2984
2852
  const content = await client.getSourceContent(input.notebookId, input.sourceId, callOptions(invocation));
@@ -2990,7 +2858,6 @@ async function updateSourceContent(client, input, invocation) {
2990
2858
  try {
2991
2859
  updated = await client.updateSource(input.notebookId, input.sourceId, {
2992
2860
  content: input.content,
2993
- sourceType: "markdown",
2994
2861
  ...input.title === void 0 ? {} : { title: input.title }
2995
2862
  }, options);
2996
2863
  if (updated.id !== input.sourceId || updated.notebookId !== input.notebookId) throw new TypeError("Unconfirmed source update.");
@@ -3148,6 +3015,7 @@ async function runScheduledTask(client, tool, rawInput, invocation) {
3148
3015
  };
3149
3016
  }
3150
3017
  const update = rawInput;
3018
+ if (isQMindRetiredScene(current.sceneType) && (update.enabled !== false || update.schedule !== void 0)) return failure$1(invocation.operationId, "invalid_input", "A retired scheduled task can only be paused or deleted.");
3151
3019
  const patch = {
3152
3020
  ...update.schedule === void 0 ? {} : { schedule: update.schedule },
3153
3021
  ...update.enabled === void 0 ? {} : { enabled: update.enabled }
@@ -3413,6 +3281,7 @@ const sourceStatus = /* @__PURE__ */ new Set([
3413
3281
  "unsupported",
3414
3282
  "failed"
3415
3283
  ]);
3284
+ const maxRetrievalImageChars = 28e5;
3416
3285
  /**
3417
3286
  * Snapshots and validates host policy at the Core boundary. Invocation context is not model input,
3418
3287
  * but it still crosses an adapter seam and must fail closed when malformed.
@@ -3544,7 +3413,7 @@ async function retrieve(client, input, invocation) {
3544
3413
  for (let offset = 0; offset < targets.length; offset += batchSize) batches.push(targets.slice(offset, offset + batchSize));
3545
3414
  const results = [];
3546
3415
  const warnings = [];
3547
- let deniedBatches = 0;
3416
+ const failedCodes = /* @__PURE__ */ new Set();
3548
3417
  const request = async (batch) => {
3549
3418
  return client.retrieveNotebooks({
3550
3419
  targets: batch.map(({ notebookId, sourceIds }) => ({
@@ -3553,7 +3422,9 @@ async function retrieve(client, input, invocation) {
3553
3422
  ...notebookSelection(invocation, notebookId) === "preferred" ? { preference: "preferred" } : {}
3554
3423
  })),
3555
3424
  maxResults: input.maxResults,
3556
- query: input.query,
3425
+ ...input.query === void 0 ? {} : { query: input.query },
3426
+ ...input.imageBase64 === void 0 ? {} : { imageBase64: input.imageBase64 },
3427
+ ...input.imageFormat === void 0 ? {} : { imageFormat: input.imageFormat },
3557
3428
  ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold },
3558
3429
  ...input.topK === void 0 ? {} : { topK: input.topK }
3559
3430
  }, callOptions(invocation));
@@ -3567,8 +3438,9 @@ async function retrieve(client, input, invocation) {
3567
3438
  settled.forEach((entry, index) => {
3568
3439
  if (entry.status === "fulfilled") results.push(entry.value);
3569
3440
  else {
3570
- if (batches.length === 1 || qmindOrganizationPolicyError(entry.reason) || errorCode(entry.reason) === "unauthenticated") throw entry.reason;
3571
- if (errorCode(entry.reason) === "permission_denied") deniedBatches++;
3441
+ const code = errorCode(entry.reason);
3442
+ if (batches.length === 1 || qmindOrganizationPolicyError(entry.reason) || code === "unauthenticated") throw entry.reason;
3443
+ failedCodes.add(code);
3572
3444
  for (const target of current[index]) warnings.push({
3573
3445
  code: "notebook_search_failed",
3574
3446
  notebookId: target.notebookId
@@ -3576,7 +3448,10 @@ async function retrieve(client, input, invocation) {
3576
3448
  }
3577
3449
  });
3578
3450
  }
3579
- if (results.length === 0) return failure$1(invocation.operationId, deniedBatches === batches.length ? "permission_denied" : "upstream_unavailable", "Notebook retrieval failed.");
3451
+ if (results.length === 0) {
3452
+ const [code] = failedCodes;
3453
+ return failure$1(invocation.operationId, failedCodes.size === 1 && (code === "permission_denied" || code === "invalid_input") ? code : "upstream_unavailable", "Notebook retrieval failed.");
3454
+ }
3580
3455
  const result = {
3581
3456
  chunks: results.flatMap((item) => item.chunks.map((chunk) => {
3582
3457
  if (chunkLineRange(chunk.metadata).lineStart !== void 0) return chunk;
@@ -3593,9 +3468,19 @@ async function retrieve(client, input, invocation) {
3593
3468
  reranked: results.length === 1 && results[0].reranked
3594
3469
  };
3595
3470
  const bounded = result.chunks.slice(0, input.maxResults);
3471
+ let remainingImageChars = maxRetrievalImageChars;
3596
3472
  return {
3597
3473
  data: {
3598
- chunks: bounded.map(chunkData),
3474
+ chunks: bounded.map((chunk) => {
3475
+ const data = chunkData(chunk);
3476
+ const image = invocation.includeRetrievalImages === true ? readQMindRetrievalImage(chunk) : void 0;
3477
+ if (image === void 0 || image.data.length > remainingImageChars) return data;
3478
+ remainingImageChars -= image.data.length;
3479
+ return {
3480
+ ...data,
3481
+ image
3482
+ };
3483
+ }),
3599
3484
  promptContext: chunkPromptContext(bounded),
3600
3485
  reranked: result.reranked,
3601
3486
  total: result.total
@@ -4045,6 +3930,7 @@ async function runQMindAgentOperation(dependencies, toolId, input, runtimeSignal
4045
3930
  ...fileSource === void 0 ? {} : { fileSource },
4046
3931
  ...dependencies.defaultNotebookIds === void 0 ? {} : { defaultNotebookIds: dependencies.defaultNotebookIds },
4047
3932
  ...operationContext.approvedDeletionTargets === void 0 ? {} : { approvedDeletionTargets: operationContext.approvedDeletionTargets },
3933
+ ...operationContext.includeRetrievalImages === true ? { includeRetrievalImages: true } : {},
4048
3934
  ...operationContext.notebookScope === void 0 ? {} : { notebookScope: operationContext.notebookScope },
4049
3935
  operationId,
4050
3936
  signal,
@@ -5633,7 +5519,7 @@ function defaultReporter() {
5633
5519
  }
5634
5520
  function defaultBrowser() {
5635
5521
  return Object.freeze({ async open(url) {
5636
- (await open(url, { wait: false })).unref();
5522
+ (await open$1(url, { wait: false })).unref();
5637
5523
  } });
5638
5524
  }
5639
5525
  async function tlsAuthority(path) {
@@ -5710,7 +5596,7 @@ async function createQMindCliHost(options = {}) {
5710
5596
  vault
5711
5597
  });
5712
5598
  const client = createQMindClient({
5713
- access: "sash",
5599
+ nezha: { webOffice: "sash" },
5714
5600
  client: resolved.runtime.client,
5715
5601
  transport: createAuthenticatedQMindTransport(rawTransport, auth, options.adapters?.requestCredential)
5716
5602
  });
@@ -5788,8 +5674,8 @@ function requestsNdjsonOutput(argv) {
5788
5674
  //#region src/build-info.ts
5789
5675
  /** Bundled identity, never inferred from argv, environment, or an endpoint. */
5790
5676
  const QMIND_CLI_DISTRIBUTION = "global";
5791
- const QMIND_CLI_VERSION = "4.3.0";
5792
- const QMIND_CLI_BUILD_TIME = "2026-11-05T13:21:19.000Z";
5677
+ const QMIND_CLI_VERSION = "5.1.0";
5678
+ const QMIND_CLI_BUILD_TIME = "2026-11-23T13:41:36.000Z";
5793
5679
  function qmindCliPlatform() {
5794
5680
  return process.platform === "win32" ? "windows" : process.platform;
5795
5681
  }
@@ -6547,6 +6433,7 @@ function renderRetrieve(value, format, multiNotebook = false) {
6547
6433
  agentField(writer, "sourceUri", chunk.sourceUri);
6548
6434
  agentField(writer, "score", chunk.score.toFixed(4));
6549
6435
  agentField(writer, "tokenCount", chunk.tokenCount);
6436
+ agentField(writer, "imageMimeType", readQMindRetrievalImage(chunk)?.mimeType);
6550
6437
  agentText(writer, "content", unescapeText(chunk.content));
6551
6438
  });
6552
6439
  value.citations.forEach((citation, index) => {
@@ -6596,6 +6483,8 @@ function renderRetrieve(value, format, multiNotebook = false) {
6596
6483
  writer.line(`[${index + 1}] chunkId=${chunk.chunkId} sourceId=${chunk.sourceId} sourceTitle=${chunk.sourceTitle} score=${chunk.score.toFixed(4)} tokens=${chunk.tokenCount}`);
6597
6484
  if ("notebookId" in chunk && "notebookTitle" in chunk) writer.line(` notebookId: ${oneLine(chunk.notebookId)} notebookTitle: ${oneLine(chunk.notebookTitle)}`);
6598
6485
  if (chunk.sourceUri.length > 0) writer.line(` uri: ${chunk.sourceUri}`);
6486
+ const image = readQMindRetrievalImage(chunk);
6487
+ if (image !== void 0) writer.line(` image: ${image.mimeType}`);
6599
6488
  if (chunk.content.length > 0) writer.line(` content: ${unescapeText(chunk.content)}`);
6600
6489
  writer.line();
6601
6490
  });
@@ -7167,8 +7056,13 @@ function render(context, options, presentation) {
7167
7056
  context.io.stdout(renderQMindCliPresentation(presentation, formatOf(options)));
7168
7057
  }
7169
7058
  function withCommon(command, output = true) {
7170
- 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");
7171
- if (output) command.option("--format <format>", "output format: table | json | agent | ndjson", "table");
7059
+ 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("--client <name>", "originating client identifier").option("--non-interactive", "never open a browser when credentials are missing");
7060
+ if (output) command.addOption(new Option("--format <format>", "output format").choices([
7061
+ "table",
7062
+ "json",
7063
+ "agent",
7064
+ "ndjson"
7065
+ ]).default("table"));
7172
7066
  return command;
7173
7067
  }
7174
7068
  //#endregion
@@ -7181,11 +7075,12 @@ async function runCanonicalCommand(context, raw, tool, input) {
7181
7075
  throw new QMindError("INVALID_ARGUMENT", `Invalid ${tool} arguments: ${fields.join(", ")}`);
7182
7076
  }
7183
7077
  const host = await hostFor(context, raw);
7078
+ const includeRetrievalImages = tool === "qmind.retrieve" && (raw.format === "json" || raw.format === "ndjson");
7184
7079
  const result = await runQMindAgentOperation({
7185
7080
  core: createQMindAgentCore(host.client),
7186
7081
  createFileSource: (path) => host.createFileSource(path),
7187
7082
  auditSink: { accept: () => {} }
7188
- }, tool, parsed.data);
7083
+ }, tool, parsed.data, void 0, void 0, includeRetrievalImages ? { includeRetrievalImages: true } : void 0);
7189
7084
  render(context, raw, {
7190
7085
  kind: "json",
7191
7086
  value: result
@@ -7214,7 +7109,7 @@ function notebookId(raw) {
7214
7109
  return requiredString(raw.nb, "--nb");
7215
7110
  }
7216
7111
  function registerCanonicalCommands(context, program) {
7217
- withCommon(program.commands.find((command) => command.name() === "notebook").command("discover").description("Discover retrieval-eligible notebooks with summaries")).option("--relationship <relationship>", "owned | shared | all", "all").option("--cursor <cursor>", "continuation cursor from the preceding result").option("--page-size <number>", "maximum results (1..50)", integer).action(async (raw) => {
7112
+ withCommon(program.commands.find((command) => command.name() === "notebook").command("discover").description("Discover retrieval-eligible notebooks with summaries")).option("--relationship <relationship>", "owned | shared | featured | all", "all").option("--cursor <cursor>", "continuation cursor from the preceding result").option("--page-size <number>", "maximum results (1..50)", integer).action(async (raw) => {
7218
7113
  await runCanonicalCommand(context, raw, "qmind.list_notebooks", {
7219
7114
  relationship: raw.relationship,
7220
7115
  cursor: raw.cursor,
@@ -7253,7 +7148,7 @@ function registerCanonicalCommands(context, program) {
7253
7148
  await runCanonicalCommand(context, raw, "qmind.delete_source", input);
7254
7149
  });
7255
7150
  const scheduled = program.command("scheduled-task").description("Manage notebook schedule configurations (not task runs)");
7256
- withCommon(scheduled.command("create").description("Create an enabled built-in scene schedule with empty config")).requiredOption("--nb <id>", "notebook ID").requiredOption("--scene <scene>", "built-in scheduled task scene").requiredOption("--schedule <cron>", "Cron with explicit IANA timezone, e.g. CRON_TZ=Asia/Shanghai 0 9 * * *").action(async (raw) => {
7151
+ withCommon(scheduled.command("create").description("Create an enabled built-in scene schedule with empty config")).requiredOption("--nb <id>", "notebook ID").requiredOption("--scene <scene>", "condensation, source_refresh or source_binding_sync").requiredOption("--schedule <cron>", "Cron with explicit IANA timezone, e.g. CRON_TZ=Asia/Shanghai 0 9 * * *").action(async (raw) => {
7257
7152
  await runCanonicalCommand(context, raw, "qmind.create_scheduled_task", {
7258
7153
  notebookId: notebookId(raw),
7259
7154
  sceneType: raw.scene,
@@ -7293,6 +7188,44 @@ function registerCanonicalCommands(context, program) {
7293
7188
  });
7294
7189
  }
7295
7190
  //#endregion
7191
+ //#region src/retrieval-image.ts
7192
+ async function readRetrievalImage(path) {
7193
+ const extension = extname(path).slice(1).toLowerCase();
7194
+ if (!/^(?:jpe?g|png|webp|bmp|tiff?|gif)$/.test(extension)) throw new QMindError("INVALID_ARGUMENT", "--image requires a JPEG, PNG, WebP, BMP, TIFF or GIF file");
7195
+ const tooLarge = new QMindError("INVALID_ARGUMENT", "--image must be at most 10 MiB");
7196
+ const unreadable = new QMindError("INVALID_ARGUMENT", "--image must be a readable, non-empty local file");
7197
+ const chunks = [];
7198
+ let size = 0;
7199
+ try {
7200
+ const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
7201
+ try {
7202
+ const info = await file.stat();
7203
+ if (!info.isFile() || info.size === 0) throw unreadable;
7204
+ if (info.size > 10485760) throw tooLarge;
7205
+ const stream = file.createReadStream({
7206
+ autoClose: false,
7207
+ end: QMIND_RETRIEVAL_IMAGE_MAX_BYTES
7208
+ });
7209
+ for await (const chunk of stream) {
7210
+ const bytes = chunk;
7211
+ size += bytes.byteLength;
7212
+ chunks.push(bytes);
7213
+ }
7214
+ } finally {
7215
+ await file.close();
7216
+ }
7217
+ } catch (error) {
7218
+ if (error === tooLarge) throw error;
7219
+ throw unreadable;
7220
+ }
7221
+ if (size === 0) throw unreadable;
7222
+ if (size > 10485760) throw tooLarge;
7223
+ return {
7224
+ imageBase64: Buffer.concat(chunks, size).toString("base64"),
7225
+ imageFormat: extension === "tif" ? "tiff" : extension
7226
+ };
7227
+ }
7228
+ //#endregion
7296
7229
  //#region src/application.ts
7297
7230
  const distribution = CLI_DISTRIBUTIONS[QMIND_CLI_DISTRIBUTION];
7298
7231
  function registerCoreCommands(context, program) {
@@ -7375,30 +7308,34 @@ function registerCoreCommands(context, program) {
7375
7308
  });
7376
7309
  else context.io.stdout("deleted\n");
7377
7310
  });
7378
- withCommon(program.command("retrieve [query]").description("Retrieve context from one or more notebooks without an LLM call")).option("--nb <ids>", `notebook IDs (required, comma-separated or repeatable, maximum 32)`, collectNotebookIds, []).option("--unified", "use unified retrieval with notebook identity, including for one notebook").addOption(new Option("--targets <json>", "JSON array of {notebookId, sourceIds?}; uses unified retrieval").argParser(parseTargets).conflicts(["nb", "sources"])).option("--score-threshold <number>", "minimum retrieval score (0..1)", scoreThreshold).option("-q, --query <query>", "retrieval query").option("--sources <ids>", "comma-separated source IDs (single notebook only)", "").option("--top-k <number>", "joint recall candidate limit", integer, 0).option("--max-results <number>", "maximum context results across selected notebooks", integer, 0).action(async (query, raw) => {
7311
+ withCommon(program.command("retrieve [query]").description("Retrieve context from notebooks using text, an image, or both")).option("--nb <ids>", `notebook IDs (required, comma-separated or repeatable, maximum 32)`, collectNotebookIds, []).option("--unified", "use unified retrieval with notebook identity, including for one notebook").addOption(new Option("--targets <json>", "JSON array of {notebookId, sourceIds?}; uses unified retrieval").argParser(parseTargets).conflicts(["nb", "sources"])).option("--score-threshold <number>", "minimum score for non-OTS retrieval (0..1)", scoreThreshold).option("-q, --query <query>", "retrieval query").option("--image <path>", "local query image (JPEG, PNG, WebP, BMP, TIFF or GIF, up to 10 MiB)").option("--sources <ids>", "comma-separated source IDs (single notebook only)", "").option("--top-k <number>", "joint recall candidate limit", integer, 0).option("--max-results <number>", "maximum context results across selected notebooks", integer, 0).action(async (query, raw) => {
7379
7312
  const notebookIds = raw.nb;
7380
7313
  const [notebookId] = notebookIds;
7381
7314
  if (raw.targets === void 0 && notebookId === void 0) throw new QMindError("INVALID_ARGUMENT", "--nb is required");
7382
7315
  if (notebookIds.length > 32) throw new QMindError("INVALID_ARGUMENT", `--nb accepts at most 32 distinct notebook IDs`);
7383
- const input = {
7384
- maxResults: numberOption(raw, "maxResults", 0),
7385
- query: requiredString(raw.query || query, "--query or positional query"),
7386
- sourceIds: splitCsv(stringOption(raw, "sources")),
7387
- topK: numberOption(raw, "topK", 0),
7316
+ const imagePath = stringOption(raw, "image");
7317
+ const text = stringOption(raw, "query") || query;
7318
+ const textQuery = imagePath === void 0 ? requiredString(text, "--query or positional query") : text?.trim() || void 0;
7319
+ if (imagePath !== void 0 && textQuery !== void 0 && textQuery.length > 128) throw new QMindError("INVALID_ARGUMENT", `image retrieval query must be at most 128 UTF-16 units`);
7320
+ const maxResults = numberOption(raw, "maxResults", 0);
7321
+ const topK = numberOption(raw, "topK", 0);
7322
+ const sourceIds = splitCsv(stringOption(raw, "sources"));
7323
+ if (maxResults < 0 || topK < 0) throw new QMindError("INVALID_ARGUMENT", "--top-k and --max-results must be non-negative");
7324
+ if (notebookIds.length > 1 && sourceIds.length > 0) throw new QMindError("INVALID_ARGUMENT", "--sources requires a single notebook");
7325
+ const criteria = {
7326
+ ...textQuery === void 0 ? {} : { query: textQuery },
7327
+ ...imagePath === void 0 ? {} : await readRetrievalImage(imagePath),
7388
7328
  ...raw.scoreThreshold === void 0 ? {} : { scoreThreshold: Number(raw.scoreThreshold) }
7389
7329
  };
7390
- if (input.maxResults < 0 || input.topK < 0) throw new QMindError("INVALID_ARGUMENT", "--top-k and --max-results must be non-negative");
7391
- if (notebookIds.length > 1 && input.sourceIds.length > 0) throw new QMindError("INVALID_ARGUMENT", "--sources requires a single notebook");
7392
7330
  if (raw.unified === true || raw.targets !== void 0) {
7393
7331
  await runCanonicalCommand(context, raw, "qmind.retrieve", {
7394
- query: input.query,
7332
+ ...criteria,
7395
7333
  ...raw.targets !== void 0 ? { targets: raw.targets } : notebookIds.length === 1 ? {
7396
7334
  notebookId,
7397
- ...input.sourceIds.length ? { sourceIds: input.sourceIds } : {}
7335
+ ...sourceIds.length ? { sourceIds } : {}
7398
7336
  } : { targets: notebookIds.map((id) => ({ notebookId: id })) },
7399
- ...input.maxResults === 0 ? {} : { maxResults: input.maxResults },
7400
- ...input.topK === 0 ? {} : { topK: input.topK },
7401
- ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold }
7337
+ ...maxResults === 0 ? {} : { maxResults },
7338
+ ...topK === 0 ? {} : { topK }
7402
7339
  });
7403
7340
  return;
7404
7341
  }
@@ -7406,17 +7343,21 @@ function registerCoreCommands(context, program) {
7406
7343
  if (notebookIds.length === 1 && notebookId !== void 0) {
7407
7344
  render(context, raw, {
7408
7345
  kind: "retrieve",
7409
- value: await host.client.retrieve(notebookId, input)
7346
+ value: await host.client.retrieve(notebookId, {
7347
+ ...criteria,
7348
+ maxResults,
7349
+ sourceIds,
7350
+ topK
7351
+ })
7410
7352
  });
7411
7353
  return;
7412
7354
  }
7413
7355
  render(context, raw, {
7414
7356
  kind: "multiRetrieve",
7415
7357
  value: await host.client.retrieveNotebooks({
7416
- query: input.query,
7417
- topK: input.topK,
7418
- maxResults: input.maxResults,
7419
- ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold },
7358
+ ...criteria,
7359
+ maxResults,
7360
+ topK,
7420
7361
  targets: notebookIds.map((notebookId) => ({ notebookId }))
7421
7362
  })
7422
7363
  });
@@ -7457,9 +7398,10 @@ function registerSourceCommands(context, program) {
7457
7398
  }))
7458
7399
  });
7459
7400
  });
7460
- withCommon(source.command("list").description("List sources")).option("--nb <id>", "notebook ID (required)").option("--page <number>", "page number", integer, 0).option("--page-size <number>", "page size", integer, 0).option("--all", "fetch and merge every page").addOption(new Option("--parent <id>", "list direct children of a directory").conflicts("all")).option("--max-pages <number>", "all-pages safety limit", integer, 1e4).action(async (raw) => {
7461
- const host = await hostFor(context, raw);
7401
+ withCommon(source.command("list").description("List sources")).option("--nb <id>", "notebook ID (required)").option("--page <number>", "page number", integer, 0).option("--page-size <number>", "page size", integer, 0).addOption(new Option("--all", "fetch and merge every page").conflicts("page")).addOption(new Option("--parent <id>", "list direct children of a directory").conflicts("all")).option("--max-pages <number>", "safety limit for --all (default: 10000)", integer).action(async (raw) => {
7462
7402
  const notebookId = requiredString(raw.nb, "--nb");
7403
+ if (raw.maxPages !== void 0 && raw.all !== true) throw new QMindError("INVALID_ARGUMENT", "--max-pages requires --all");
7404
+ const host = await hostFor(context, raw);
7463
7405
  let value;
7464
7406
  if (raw.all === true) {
7465
7407
  const pageSize = positiveNumberOption(raw, "pageSize", 0) ?? 100;
@@ -7550,8 +7492,9 @@ function registerSourceCommands(context, program) {
7550
7492
  });
7551
7493
  });
7552
7494
  withCommon(source.command("content <source_id>").description("Read parsed source content"), false).option("--nb <id>", "notebook ID (required)").option("--download <path>", "save content to a file").option("--no-overwrite", "refuse to replace an existing file").action(async (sourceId, raw) => {
7553
- const content = await (await hostFor(context, raw)).client.getSourceContent(requiredString(raw.nb, "--nb"), sourceId);
7554
7495
  const path = optionalString(raw, "download");
7496
+ if (raw.overwrite === false && path === void 0) throw new QMindError("INVALID_ARGUMENT", "--no-overwrite requires --download");
7497
+ const content = await (await hostFor(context, raw)).client.getSourceContent(requiredString(raw.nb, "--nb"), sourceId);
7555
7498
  if (path === void 0) context.io.stdout(content.content);
7556
7499
  else {
7557
7500
  await atomicQMindWrite(path, content.content, raw.overwrite !== false);
@@ -7580,15 +7523,13 @@ function registerSourceCommands(context, program) {
7580
7523
  });
7581
7524
  else context.io.stdout("deleted\n");
7582
7525
  });
7583
- withCommon(source.command("import-site").description("Import a complete web site")).option("--nb <id>", "notebook ID (required)").option("--url <url>", "site root URL (required)").option("--title <title>", "source title").option("--parent <id>", "parent source ID", "").option("--path-prefix <path>", "path prefix", "").option("--max-pages <number>", "maximum page count", integer, 50).option("--sitemap <url>", "sitemap URL", "").option("--include <patterns>", "comma-separated include patterns", "").option("--exclude <patterns>", "comma-separated exclude patterns", "").action(async (raw) => {
7526
+ withCommon(source.command("import-site").description("Import a website into the notebook root")).option("--nb <id>", "notebook ID (required)").option("--url <url>", "site root URL (required)").option("--title <title>", "source title").option("--max-pages <number>", "maximum page count (1..200)", integer, 50).option("--sitemap <url>", "sitemap URL", "").option("--include <patterns>", "comma-separated include patterns", "").option("--exclude <patterns>", "comma-separated exclude patterns", "").action(async (raw) => {
7584
7527
  const host = await hostFor(context, raw);
7585
7528
  const rootUrl = requiredString(raw.url, "--url");
7586
7529
  const value = await submitCliMutation(async () => host.client.importSite(requiredString(raw.nb, "--nb"), {
7587
7530
  excludePaths: splitCsv(stringOption(raw, "exclude")),
7588
7531
  includePaths: splitCsv(stringOption(raw, "include")),
7589
7532
  maxPages: numberOption(raw, "maxPages", 50),
7590
- parentSourceId: String(raw.parent ?? ""),
7591
- pathPrefix: String(raw.pathPrefix ?? ""),
7592
7533
  rootUrl,
7593
7534
  sitemapUrl: optionalString(raw, "sitemap"),
7594
7535
  title: optionalString(raw, "title")
@@ -7601,7 +7542,7 @@ function registerSourceCommands(context, program) {
7601
7542
  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`);
7602
7543
  });
7603
7544
  const image = program.command("image").description("Notebook image presign operations");
7604
- 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) => {
7545
+ 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)").addOption(new Option("--size <bytes>", "file size for presign mode").argParser(integer).conflicts("file")).option("--file <path>", "local image to upload").action(async (raw) => {
7605
7546
  const host = await hostFor(context, raw);
7606
7547
  const notebookId = requiredString(raw.nb, "--nb");
7607
7548
  const sourceId = requiredString(raw.source, "--source");
@@ -7653,17 +7594,17 @@ function registerSceneCommands(context, program) {
7653
7594
  }
7654
7595
  function registerTaskCommands(context, program) {
7655
7596
  const task = program.command("task").description("Manage notebook task runs");
7656
- withCommon(task.command("create").description("Create a notebook task run")).option("--nb <id>", "notebook ID (required)").option("--scene <scene>", "task scene (required)").option("--trigger <trigger>", "task trigger", "manual").option("--sources <ids>", "comma-separated source IDs", "").action(async (raw) => {
7597
+ withCommon(task.command("create").description("Create a notebook task run")).option("--nb <id>", "notebook ID (required)").option("--scene <scene>", "manual task scene: condensation or source_refresh (required)").action(async (raw) => {
7657
7598
  const scene = requiredString(raw.scene, "--scene").trim();
7658
7599
  if (scene === "compilation" || scene === "lint") throw new QMindError("INVALID_ARGUMENT", `task creation does not support scene ${JSON.stringify(scene)}`);
7600
+ if (scene === "source_binding_sync") throw new QMindError("INVALID_ARGUMENT", "source_binding_sync requires a scheduled task");
7601
+ const notebookId = requiredString(raw.nb, "--nb");
7659
7602
  const host = await hostFor(context, raw);
7660
- const sourceIds = splitCsv(stringOption(raw, "sources"));
7661
7603
  render(context, raw, {
7662
7604
  kind: "json",
7663
- value: await submitCliMutation(async () => host.client.createTaskRun(requiredString(raw.nb, "--nb"), {
7664
- ...sourceIds.length === 0 ? {} : { config: { sourceIds } },
7605
+ value: await submitCliMutation(async () => host.client.createTaskRun(notebookId, {
7665
7606
  sceneType: scene,
7666
- trigger: String(raw.trigger ?? "manual")
7607
+ trigger: "manual"
7667
7608
  }))
7668
7609
  });
7669
7610
  });
@@ -7694,7 +7635,7 @@ function syncText(stats) {
7694
7635
  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";
7695
7636
  }
7696
7637
  function registerSyncCommand(context, program) {
7697
- 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([
7638
+ 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").addOption(new Option("--format <format>", "summary output format").choices(["json", "text"]).default("json")).addOption(new Option("--mode <mode>", "existing-file behavior").choices([
7698
7639
  "skip",
7699
7640
  "overwrite",
7700
7641
  "if-changed"
@@ -7728,11 +7669,7 @@ function registerSyncCommand(context, program) {
7728
7669
  });
7729
7670
  }
7730
7671
  function registerUpdateCommand(context, program) {
7731
- program.command("update").alias("self-update").description("Update a Native CLI or show the npm upgrade path").option("--url <url>", "legacy update URL (ignored)").addOption(new Option("--channel <channel>", "legacy release channel (ignored)").choices([
7732
- "stable",
7733
- "beta",
7734
- "daily"
7735
- ]).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(async (raw) => {
7672
+ program.command("update").alias("self-update").description("Update a Native CLI or show the npm upgrade path").option("--check", "check the Native stable release without installing it").action(async (raw) => {
7736
7673
  const result = await context.updater.run({ check: raw.check === true });
7737
7674
  if (result.status === "unsupported") throw new QMindError("UNSUPPORTED_OPERATION", `self-update is unavailable for npm installs; run ${result.command}`);
7738
7675
  if (result.status === "up-to-date") context.io.stdout(`${distribution.command} ${result.currentVersion} is up to date\n`);
@@ -7771,7 +7708,7 @@ async function runQMindCli(argv, options = {}) {
7771
7708
  updater: options.updater ?? createQMindCliUpdater({ identity: {
7772
7709
  artifactKind: "npm",
7773
7710
  command: distribution.command,
7774
- currentVersion: "4.3.0",
7711
+ currentVersion: "5.1.0",
7775
7712
  distribution: distribution.id,
7776
7713
  executablePath: process.execPath,
7777
7714
  package: distribution.package,