@qoder-ai/qmind-cli 3.5.0 → 4.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,9 +1,8 @@
1
- import { A as notebookSchema, B as sourceQuotaSchema, C as chatSessionSchema, D as imageUrlsSchema, E as imageUploadTicketSchema, F as sourceChildrenCountsSchema, H as sourceSchema, I as sourceContentSchema, J as streamWireEventSchema, K as sourceWebOfficeSessionSchema, L as sourceImportResultsSchema, M as retrieveResultSchema, N as sharedNotebookListSchema, P as sourceActionAccessSchema, Q as voidResponseSchema, R as sourceListSchema, S as chatSessionListSchema, U as sourceTreeSchema, V as sourceRawContentSchema, W as sourceUploadCapabilitiesSchema, X as taskRunSchema, Y as taskRunListSchema, a as invalidArgument$1, at as QMindError, b as cancelQuestionResultSchema, c as optionalRecord, d as pagination$1, f as positiveInteger$1, g as stringList, i as httpUrl, j as retrieveNotebooksResultSchema, k as notebookListSchema, l as optionalString$1, m as requiredString$2, n as call, nt as assertCapability, o as nonNegativeInteger$1, p as queryPath, q as sourceWebOfficeTokenSchema, r as compactUndefined, rt as executeStream, s as optionalBoolean, t as assertNonEmptyPatch, u as optionalTrimmedString, x as chatMessageListSchema, y as batchDeleteResultSchema, z as sourcePreviewSchema } from "./shared-DsqZroGJ.js";
2
- import { t as preflightSourceUpload } from "./source-upload-DdZ0J4gC.js";
3
- import { createInterface } from "node:readline/promises";
1
+ import { A as notebookSchema, B as sourceQuotaSchema, C as chatSessionSchema, D as imageUrlsSchema, E as imageUploadTicketSchema, F as sourceChildrenCountsSchema, H as sourceSchema, I as sourceContentSchema, J as streamWireEventSchema, K as sourceWebOfficeSessionSchema, L as sourceImportResultsSchema, M as retrieveResultSchema, N as sharedNotebookListSchema, P as sourceActionAccessSchema, Q as voidResponseSchema, R as sourceListSchema, S as chatSessionListSchema, U as sourceTreeSchema, V as sourceRawContentSchema, W as sourceUploadCapabilitiesSchema, X as taskRunSchema, Y as taskRunListSchema, a as invalidArgument$1, at as QMindError, b as cancelQuestionResultSchema, c as optionalRecord, d as pagination$1, f as positiveInteger$1, g as stringList, i as httpUrl, j as retrieveNotebooksResultSchema, k as notebookListSchema, l as optionalString$1, m as requiredString$2, n as call, nt as assertCapability, o as nonNegativeInteger$1, p as queryPath, q as sourceWebOfficeTokenSchema, r as compactUndefined, rt as executeStream, s as optionalBoolean, t as assertNonEmptyPatch, u as optionalTrimmedString, x as chatMessageListSchema, y as batchDeleteResultSchema, z as sourcePreviewSchema } from "./shared-53S5tNf6.js";
2
+ import { t as preflightSourceUpload } from "./source-upload-DlOLtECT.js";
4
3
  import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
5
4
  import { z } from "zod";
6
- import { createHash, randomBytes } from "node:crypto";
5
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
7
6
  import { chmod, copyFile, link, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
8
7
  import { homedir, tmpdir } from "node:os";
9
8
  import lockfile from "proper-lockfile";
@@ -20,6 +19,7 @@ import { decodeHTML } from "entities";
20
19
  import { execFile, spawn } from "node:child_process";
21
20
  import { promisify } from "node:util";
22
21
  import semver from "semver";
22
+ import { createInterface } from "node:readline/promises";
23
23
  //#region ../sdk/src/operations/agents.ts
24
24
  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.";
25
25
  function isRecord$3(value) {
@@ -149,7 +149,7 @@ function agentContent(input) {
149
149
  sceneType: input.scene
150
150
  };
151
151
  }
152
- function callOptions(options) {
152
+ function callOptions$1(options) {
153
153
  return {
154
154
  ...options?.signal === void 0 ? {} : { signal: options.signal },
155
155
  ...options?.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
@@ -157,7 +157,7 @@ function callOptions(options) {
157
157
  }
158
158
  function streamCallOptions(options) {
159
159
  return {
160
- ...callOptions(options),
160
+ ...callOptions$1(options),
161
161
  ...options?.connectTimeoutMs === void 0 ? {} : { connectTimeoutMs: options.connectTimeoutMs },
162
162
  ...options?.idleTimeoutMs === void 0 ? {} : { idleTimeoutMs: options.idleTimeoutMs }
163
163
  };
@@ -399,7 +399,7 @@ function createAgentOperations(context) {
399
399
  //#region ../sdk/src/operations/notebooks.ts
400
400
  function createNotebookOperations(context) {
401
401
  let wikiOperations;
402
- const loadWiki = () => wikiOperations ??= import("./wiki-branches-CNLpYYCl.js").then(({ createWikiBranchOperations }) => createWikiBranchOperations(context));
402
+ const loadWiki = () => wikiOperations ??= import("./wiki-branches-DmgHlIxc.js").then(({ createWikiBranchOperations }) => createWikiBranchOperations(context));
403
403
  return {
404
404
  async copyFeaturedNotebook(notebookId, options) {
405
405
  const notebook = requiredString$2(notebookId, "notebookId");
@@ -483,10 +483,12 @@ function createNotebookOperations(context) {
483
483
  },
484
484
  async listNotebooks(input = {}, options) {
485
485
  const normalizedPage = pagination$1(input);
486
+ const retrievalEligibleOnly = optionalBoolean(input.retrievalEligibleOnly, "retrievalEligibleOnly");
486
487
  const client = optionalTrimmedString(input.client, "client");
487
488
  if (client !== void 0 && !context.profile.capabilities["notebooks.filterByClient"]) assertCapability(context.profile, "notebooks.filterByClient", "notebooks.list");
488
489
  const normalized = {
489
490
  ...normalizedPage,
491
+ ...retrievalEligibleOnly === void 0 ? {} : { retrievalEligibleOnly },
490
492
  ...client === void 0 ? {} : { client }
491
493
  };
492
494
  return call(context, {
@@ -500,7 +502,11 @@ function createNotebookOperations(context) {
500
502
  });
501
503
  },
502
504
  async listSharedNotebooks(input = {}, options) {
503
- const normalized = pagination$1(input);
505
+ const retrievalEligibleOnly = optionalBoolean(input.retrievalEligibleOnly, "retrievalEligibleOnly");
506
+ const normalized = {
507
+ ...pagination$1(input),
508
+ ...retrievalEligibleOnly === void 0 ? {} : { retrievalEligibleOnly }
509
+ };
504
510
  return call(context, {
505
511
  callOptions: options,
506
512
  capability: "sharedNotebooks.read",
@@ -645,6 +651,16 @@ function qmindEmailSourceId(source) {
645
651
  return isQMindEmailSource(source) ? source?.id ?? "" : "";
646
652
  }
647
653
  /**
654
+ * Deleting an email body deletes the whole aggregate, so the folder is the real target. Attachments
655
+ * and emails without attachments delete themselves.
656
+ */
657
+ function qmindEmailDeleteTarget(source, siblings) {
658
+ if (!isQMindEmailSource(source) || source.parentSourceId.length === 0) return source;
659
+ const parent = siblings.find((item) => item.id === source.parentSourceId);
660
+ if (parent === void 0) return source;
661
+ return isQMindEmailFolder(parent) && qmindEmailSourceId(parent) === source.id ? parent : source;
662
+ }
663
+ /**
648
664
  * A body and its attachments cannot leave their email folder, because the folder is what carries
649
665
  * the email identity.
650
666
  */
@@ -668,6 +684,25 @@ function isQMindExternalSource(source) {
668
684
  return source?.externalBinding !== void 0 || provider === "aliding" || provider === "repowiki";
669
685
  }
670
686
  [.../* @__PURE__ */ new Set(["axls", "alxs"])];
687
+ /** Operations allowed by persisted ownership, independent of the visible tree position. */
688
+ function qmindSourceOperationPolicy(source) {
689
+ const binding = source?.externalBinding;
690
+ if (binding === void 0) return {
691
+ rename: true,
692
+ move: true,
693
+ delete: true,
694
+ addChildren: true,
695
+ menu: "ordinary"
696
+ };
697
+ const menu = binding.isRoot && binding.provider === "site_catalog" ? "site" : binding.isRoot && binding.provider === "aliding" ? "aliding" : "none";
698
+ return {
699
+ rename: false,
700
+ move: false,
701
+ delete: menu !== "none",
702
+ addChildren: false,
703
+ menu
704
+ };
705
+ }
671
706
  //#endregion
672
707
  //#region ../sdk/src/source-tree.ts
673
708
  function sourceTreeNodeOrder(left, right) {
@@ -1375,16 +1410,16 @@ const sashCapabilities = Object.freeze({
1375
1410
  chat: true,
1376
1411
  "featuredChat.delete": false,
1377
1412
  compilation: false,
1378
- "featuredNotebooks.read": false,
1413
+ "featuredNotebooks.read": true,
1379
1414
  "featuredNotebooks.copy": true,
1380
1415
  "images.presignUpload": true,
1381
1416
  "images.presignUrls": true,
1382
- "imports.aliDing": false,
1383
- "imports.discover": false,
1417
+ "imports.aliDing": true,
1418
+ "imports.discover": true,
1384
1419
  "imports.fullSiteURL": false,
1385
- members: false,
1420
+ members: true,
1386
1421
  "members.search": false,
1387
- "members.resolve": false,
1422
+ "members.resolve": true,
1388
1423
  "notebooks.filterByClient": true,
1389
1424
  "notebooks.read": true,
1390
1425
  "notebooks.write": true,
@@ -1392,7 +1427,7 @@ const sashCapabilities = Object.freeze({
1392
1427
  "notes.write": true,
1393
1428
  "notes.saveCondensation": false,
1394
1429
  retrieval: true,
1395
- scheduledTasks: false,
1430
+ scheduledTasks: true,
1396
1431
  "sharedNotebooks.read": true,
1397
1432
  "sources.children": true,
1398
1433
  "sources.childrenCount": false,
@@ -1401,7 +1436,7 @@ const sashCapabilities = Object.freeze({
1401
1436
  "sources.preview": true,
1402
1437
  "sources.rawContent": true,
1403
1438
  "sources.read": true,
1404
- "sources.quota": false,
1439
+ "sources.quota": true,
1405
1440
  "sources.search": false,
1406
1441
  "sources.tree": true,
1407
1442
  "sources.webOffice": true,
@@ -1565,11 +1600,16 @@ function createProfile(access, apiPrefix) {
1565
1600
  return appendQuery(`${apiPrefix}/notebooks`, [
1566
1601
  ["page", input.page],
1567
1602
  ["page_size", input.pageSize],
1568
- ["client", input.client]
1603
+ ["client", input.client],
1604
+ ["retrieval_eligible_only", input.retrievalEligibleOnly]
1569
1605
  ]);
1570
1606
  },
1571
1607
  listSharedNotebooksPath(input) {
1572
- return appendQuery(`${apiPrefix}/notebooks/shared`, [["page", input.page], ["page_size", input.pageSize]]);
1608
+ return appendQuery(`${apiPrefix}/notebooks/shared`, [
1609
+ ["page", input.page],
1610
+ ["page_size", input.pageSize],
1611
+ ["retrieval_eligible_only", input.retrievalEligibleOnly]
1612
+ ]);
1573
1613
  },
1574
1614
  mindPath(...segments) {
1575
1615
  return `/api/v1/mind/${segments.map((segment) => encodeId(segment)).join("/")}`;
@@ -1656,7 +1696,7 @@ const botGatewayOperationNames = [
1656
1696
  function createLazyTransferOperations(context) {
1657
1697
  let operations;
1658
1698
  const load = () => {
1659
- operations ??= import("./transfers-SJE97RLg.js").then(({ createTransferOperations }) => createTransferOperations(context));
1699
+ operations ??= import("./transfers-cf1MXHdB.js").then(({ createTransferOperations }) => createTransferOperations(context));
1660
1700
  return operations;
1661
1701
  };
1662
1702
  return {
@@ -1667,7 +1707,7 @@ function createLazyTransferOperations(context) {
1667
1707
  function createLazyBotGatewayOperations(context) {
1668
1708
  let operations;
1669
1709
  const load = () => {
1670
- operations ??= import("./bot-gateway-eajGWyYA.js").then(({ createBotGatewayOperations }) => createBotGatewayOperations(context));
1710
+ operations ??= import("./bot-gateway-B5cW3ErV.js").then(({ createBotGatewayOperations }) => createBotGatewayOperations(context));
1671
1711
  return operations;
1672
1712
  };
1673
1713
  return Object.fromEntries(botGatewayOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
@@ -1675,7 +1715,7 @@ function createLazyBotGatewayOperations(context) {
1675
1715
  function createLazyNoteOperations(context) {
1676
1716
  let operations;
1677
1717
  const load = () => {
1678
- operations ??= import("./notes-PwqGFJvk.js").then(({ createNoteOperations }) => createNoteOperations(context));
1718
+ operations ??= import("./notes-BRnv_Z10.js").then(({ createNoteOperations }) => createNoteOperations(context));
1679
1719
  return operations;
1680
1720
  };
1681
1721
  return Object.fromEntries(noteOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
@@ -1683,7 +1723,7 @@ function createLazyNoteOperations(context) {
1683
1723
  function createLazyImportOperations(context) {
1684
1724
  let operations;
1685
1725
  const load = () => {
1686
- operations ??= import("./imports-CebWSRju.js").then(({ createImportOperations }) => createImportOperations(context));
1726
+ operations ??= import("./imports-BZyUf1pq.js").then(({ createImportOperations }) => createImportOperations(context));
1687
1727
  return operations;
1688
1728
  };
1689
1729
  return Object.fromEntries(importOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
@@ -1691,7 +1731,7 @@ function createLazyImportOperations(context) {
1691
1731
  function createLazyManagementOperations(context) {
1692
1732
  let operations;
1693
1733
  const load = () => {
1694
- operations ??= import("./management-Avpo7nTn.js").then(({ createManagementOperations }) => createManagementOperations(context));
1734
+ operations ??= import("./management-DQVj17Hn.js").then(({ createManagementOperations }) => createManagementOperations(context));
1695
1735
  return operations;
1696
1736
  };
1697
1737
  return Object.fromEntries(managementOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
@@ -2626,15 +2666,22 @@ function createDispatchers(options) {
2626
2666
  const connect = tlsConnectOptions(options);
2627
2667
  const networkProxy = options.networkProxy === void 0 ? void 0 : parseQMindNodeNetworkProxy(options.networkProxy);
2628
2668
  if (networkProxy?.mode === "manual") {
2629
- const createAgent = () => new Agent({ factory(origin) {
2630
- const hostname = new URL(origin).hostname.replace(/\.$/, "");
2631
- return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname) ? new Pool(origin, { connect }) : new ProxyAgent({
2632
- uri: networkProxy.url,
2633
- requestTls: connect,
2634
- proxyTls: connect,
2635
- proxyTunnel: true
2636
- });
2637
- } });
2669
+ const createAgent = () => new Agent({
2670
+ allowH2: false,
2671
+ factory(origin) {
2672
+ const hostname = new URL(origin).hostname.replace(/\.$/, "");
2673
+ return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname) ? new Pool(origin, {
2674
+ allowH2: false,
2675
+ connect
2676
+ }) : new ProxyAgent({
2677
+ allowH2: false,
2678
+ uri: networkProxy.url,
2679
+ requestTls: connect,
2680
+ proxyTls: connect,
2681
+ proxyTunnel: true
2682
+ });
2683
+ }
2684
+ });
2638
2685
  return {
2639
2686
  host: createAgent(),
2640
2687
  signed: createAgent()
@@ -2642,15 +2689,27 @@ function createDispatchers(options) {
2642
2689
  }
2643
2690
  const environment = options.environment ?? process.env;
2644
2691
  if (networkProxy?.mode === "direct" || options.proxyFromEnvironment === false) return {
2645
- host: new Agent({ connect }),
2646
- signed: new Agent({ connect })
2692
+ host: new Agent({
2693
+ allowH2: false,
2694
+ connect
2695
+ }),
2696
+ signed: new Agent({
2697
+ allowH2: false,
2698
+ connect
2699
+ })
2647
2700
  };
2648
2701
  const httpProxy = environmentValue(environment, "HTTP_PROXY", "http_proxy");
2649
2702
  const httpsProxy = environmentValue(environment, "HTTPS_PROXY", "https_proxy");
2650
2703
  const noProxy = environmentValue(environment, "NO_PROXY", "no_proxy");
2651
2704
  if (httpProxy === void 0 && httpsProxy === void 0) return {
2652
- host: new Agent({ connect }),
2653
- signed: new Agent({ connect })
2705
+ host: new Agent({
2706
+ allowH2: false,
2707
+ connect
2708
+ }),
2709
+ signed: new Agent({
2710
+ allowH2: false,
2711
+ connect
2712
+ })
2654
2713
  };
2655
2714
  const proxy = {
2656
2715
  httpProxy: httpProxy ?? "",
@@ -2660,10 +2719,12 @@ function createDispatchers(options) {
2660
2719
  return {
2661
2720
  host: new EnvHttpProxyAgent({
2662
2721
  ...proxy,
2722
+ allowH2: false,
2663
2723
  requestTls: connect
2664
2724
  }),
2665
2725
  signed: new EnvHttpProxyAgent({
2666
2726
  ...proxy,
2727
+ allowH2: false,
2667
2728
  requestTls: connect
2668
2729
  })
2669
2730
  };
@@ -3269,9 +3330,7 @@ function normalizeLegacyArgv(argv) {
3269
3330
  return argument;
3270
3331
  });
3271
3332
  }
3272
- /** Runtime errors use the JSON error envelope only when the caller explicitly
3273
- * selected JSON, except folder sync whose compatibility default is JSON. */
3274
- function requestsJsonOutput(argv) {
3333
+ function requestedFormat(argv) {
3275
3334
  let explicitFormat;
3276
3335
  let positionalOnly = false;
3277
3336
  for (let index = 0; index < argv.length; index += 1) {
@@ -3289,15 +3348,23 @@ function requestsJsonOutput(argv) {
3289
3348
  const match = argument?.match(/^--?format=(.*)$/);
3290
3349
  if (match !== null && match !== void 0) explicitFormat = match[1];
3291
3350
  }
3292
- if (explicitFormat !== void 0) return explicitFormat === "json";
3351
+ return explicitFormat;
3352
+ }
3353
+ /** Machine formats keep errors on stdout; folder sync also defaults to JSON. */
3354
+ function requestsJsonOutput(argv) {
3355
+ const format = requestedFormat(argv);
3356
+ if (format !== void 0) return format === "json" || format === "ndjson";
3293
3357
  return argv[0] === "upload-folder" || argv[0] === "sync";
3294
3358
  }
3359
+ function requestsNdjsonOutput(argv) {
3360
+ return requestedFormat(argv) === "ndjson";
3361
+ }
3295
3362
  //#endregion
3296
3363
  //#region src/build-info.ts
3297
3364
  /** Bundled identity, never inferred from argv, environment, or an endpoint. */
3298
3365
  const QMIND_CLI_DISTRIBUTION = "global";
3299
- const QMIND_CLI_VERSION = "3.5.0";
3300
- const QMIND_CLI_BUILD_TIME = "2026-09-28T09:35:44.000Z";
3366
+ const QMIND_CLI_VERSION = "4.1.0";
3367
+ const QMIND_CLI_BUILD_TIME = "2026-10-21T08:05:30.000Z";
3301
3368
  function qmindCliPlatform() {
3302
3369
  return process.platform === "win32" ? "windows" : process.platform;
3303
3370
  }
@@ -3330,37 +3397,12 @@ const CLI_DISTRIBUTIONS = Object.freeze({
3330
3397
  gitTagSlug: "qmind-cli-cn",
3331
3398
  readmeDirectory: "readmes/cn",
3332
3399
  productNames: {
3333
- en: "Qoder China",
3334
- zhCN: "Qoder 中国版"
3400
+ en: "Qoder CN",
3401
+ zhCN: "Qoder CN"
3335
3402
  }
3336
3403
  }
3337
3404
  });
3338
3405
  //#endregion
3339
- //#region src/config.ts
3340
- function cliHostConfiguration(distribution, flags, environment, stateRoot) {
3341
- const { productId, command } = CLI_DISTRIBUTIONS[distribution];
3342
- const custom = flags.sash !== void 0 || flags.dashboard !== void 0;
3343
- if (custom && (typeof flags.sash !== "string" || typeof flags.dashboard !== "string" || flags.env !== void 0)) throw new QMindError("INVALID_ARGUMENT", "--sash and --dashboard must be supplied together and cannot be combined with --env");
3344
- const preset = typeof flags.env === "string" ? flags.env.trim() : "prod";
3345
- const endpoints = custom ? {
3346
- dashboardOrigin: normalizeQMindOrigin(String(flags.dashboard).trim(), "--dashboard"),
3347
- sashOrigin: normalizeQMindOrigin(String(flags.sash).trim(), "--sash")
3348
- } : resolveQMindProductEndpoints(productId, preset);
3349
- const target = custom ? `custom-${createHash("sha256").update(JSON.stringify([endpoints.dashboardOrigin, endpoints.sashOrigin])).digest("hex")}` : preset;
3350
- return {
3351
- environment: {
3352
- ...environment,
3353
- QMIND_TOKEN: target === "prod" ? environment.QMIND_TOKEN : environment.QMIND_DEBUG_TOKEN
3354
- },
3355
- flags,
3356
- fixedEndpoints: endpoints,
3357
- homeDirectory: join(resolve(stateRoot ?? (environment.QMIND_HOME?.trim() || join(homedir(), ".qmind"))), "cli", distribution, target),
3358
- legacyEnvironmentPath: false,
3359
- loginCommand: `${command} login${custom ? ` --sash ${endpoints.sashOrigin} --dashboard ${endpoints.dashboardOrigin}` : target === "prod" ? "" : ` --env ${target}`}`,
3360
- productId
3361
- };
3362
- }
3363
- //#endregion
3364
3406
  //#region src/folder-sync.ts
3365
3407
  const QMIND_FOLDER_SYNC_DEFAULT_EXTENSIONS = Object.freeze([
3366
3408
  ".mdx",
@@ -3669,6 +3711,32 @@ async function synchronizeQMindFolder(host, options) {
3669
3711
  };
3670
3712
  }
3671
3713
  //#endregion
3714
+ //#region src/mutations.ts
3715
+ /** Preserve SDK diagnostics while distinguishing an unconfirmed legacy command write. */
3716
+ var CliMutationOutcomeUnknown = class extends Error {
3717
+ original;
3718
+ retryable = false;
3719
+ outcome = "outcome_unknown";
3720
+ constructor(original) {
3721
+ super("The write outcome is unknown. Inspect current state before another call; do not retry automatically.", { cause: original });
3722
+ this.original = original;
3723
+ }
3724
+ };
3725
+ async function submitCliMutation(submit) {
3726
+ try {
3727
+ return await submit();
3728
+ } catch (error) {
3729
+ if (error instanceof QMindError && error.operation !== "sources.uploadPreflight" && error.upstreamCode !== "QMindDisabledByOrganization" && (error.status === 408 || [
3730
+ "TIMEOUT",
3731
+ "ABORTED",
3732
+ "NETWORK_ERROR",
3733
+ "REMOTE_ERROR",
3734
+ "PROTOCOL_ERROR"
3735
+ ].includes(error.code))) throw new CliMutationOutcomeUnknown(error);
3736
+ throw error;
3737
+ }
3738
+ }
3739
+ //#endregion
3672
3740
  //#region src/output.ts
3673
3741
  var TextWriter = class {
3674
3742
  #chunks = [];
@@ -3761,6 +3829,9 @@ function goNotebook(value) {
3761
3829
  orgId: stringValue(source.orgId),
3762
3830
  userId: stringValue(source.userId),
3763
3831
  title: stringValue(source.title),
3832
+ sourceCount: value.sourceCount,
3833
+ materialCount: value.materialCount,
3834
+ ...value.overview === void 0 ? {} : { overview: value.overview },
3764
3835
  description: stringValue(source.description),
3765
3836
  client: stringValue(source.client),
3766
3837
  status: stringValue(source.status),
@@ -3881,6 +3952,10 @@ function renderAgentNotebook(writer, value, index = 0) {
3881
3952
  agentField(writer, "createdAt", timestamp(value.createdAt));
3882
3953
  agentField(writer, "updatedAt", timestamp(value.updatedAt));
3883
3954
  agentText(writer, "description", value.description);
3955
+ agentField(writer, "sourceCount", value.sourceCount);
3956
+ agentField(writer, "materialCount", value.materialCount);
3957
+ agentText(writer, "summary", value.overview?.summary);
3958
+ if (value.overview?.topics) agentField(writer, "topics", value.overview.topics.join(", "));
3884
3959
  }
3885
3960
  function renderAgentSource(writer, value, index = 0) {
3886
3961
  writer.line("---");
@@ -3918,6 +3993,9 @@ function renderNotebook(value, format) {
3918
3993
  writer.line(`CreatedAt: ${timestamp(value.createdAt)}`);
3919
3994
  writer.line(`UpdatedAt: ${timestamp(value.updatedAt)}`);
3920
3995
  if (value.description.length > 0) writer.line(`\n${value.description}`);
3996
+ writer.line(`Sources: ${value.sourceCount} (materials: ${value.materialCount})`);
3997
+ if (value.overview?.summary) writer.line(`Summary: ${value.overview.summary}`);
3998
+ if (value.overview?.topics?.length) writer.line(`Topics: ${value.overview.topics.join(", ")}`);
3921
3999
  }
3922
4000
  return writer.toString();
3923
4001
  }
@@ -3939,6 +4017,8 @@ function renderNotebookList(value, format) {
3939
4017
  "USER",
3940
4018
  "PERMISSION",
3941
4019
  "MEMBERS",
4020
+ "SOURCES",
4021
+ "SUMMARY",
3942
4022
  "UPDATED"
3943
4023
  ], value.notebooks.map((item) => [
3944
4024
  truncate(item.id, 36),
@@ -3947,6 +4027,8 @@ function renderNotebookList(value, format) {
3947
4027
  truncate(item.userId, 18),
3948
4028
  item.access?.currentUserPermission ?? item.permission ?? "unknown",
3949
4029
  item.access?.memberCount ?? "-",
4030
+ item.sourceCount,
4031
+ truncate(oneLine(item.overview?.summary), 40),
3950
4032
  timestamp(item.updatedAt)
3951
4033
  ]), [
3952
4034
  36,
@@ -3955,8 +4037,10 @@ function renderNotebookList(value, format) {
3955
4037
  18,
3956
4038
  12,
3957
4039
  7,
4040
+ 7,
4041
+ 40,
3958
4042
  20
3959
- ], 143);
4043
+ ], 194);
3960
4044
  }
3961
4045
  return writer.toString();
3962
4046
  }
@@ -4130,42 +4214,49 @@ function renderQMindCliPresentation(presentation, format) {
4130
4214
  case "text": return presentation.value;
4131
4215
  }
4132
4216
  }
4133
- function renderQMindCliError(error, jsonOutput) {
4134
- const source = error instanceof QMindError ? {
4135
- code: error.code,
4136
- details: error.details,
4137
- message: error.message,
4138
- rawBody: error.rawBody,
4139
- requestId: error.requestId,
4140
- status: error.status,
4141
- upstreamCode: error.upstreamCode
4217
+ function renderQMindCliError(error, jsonOutput, pretty = true) {
4218
+ const unknownWrite = error instanceof CliMutationOutcomeUnknown ? error : void 0;
4219
+ const cause = unknownWrite?.original ?? error;
4220
+ const source = cause instanceof QMindError ? {
4221
+ code: cause.code,
4222
+ details: cause.details,
4223
+ message: cause.message,
4224
+ rawBody: cause.rawBody,
4225
+ requestId: cause.requestId,
4226
+ status: cause.status,
4227
+ upstreamCode: cause.upstreamCode
4142
4228
  } : {
4143
4229
  code: "INTERNAL_ERROR",
4144
4230
  details: void 0,
4145
- message: error instanceof Error ? error.message : String(error),
4231
+ message: cause instanceof Error ? cause.message : String(cause),
4146
4232
  rawBody: void 0,
4147
4233
  requestId: void 0,
4148
4234
  status: void 0,
4149
4235
  upstreamCode: void 0
4150
4236
  };
4151
- const exitCode = source.code === "INVALID_ARGUMENT" ? 2 : 1;
4237
+ const exitCode = unknownWrite === void 0 && source.code === "INVALID_ARGUMENT" ? 2 : 1;
4152
4238
  if (!jsonOutput) return {
4153
4239
  exitCode,
4154
- stderr: `error: ${source.message}\n`,
4240
+ stderr: `error: ${unknownWrite ? `outcome_unknown: ${unknownWrite.message}` : source.message}\n`,
4155
4241
  stdout: ""
4156
4242
  };
4157
4243
  return {
4158
4244
  exitCode,
4159
4245
  stderr: "",
4160
4246
  stdout: json({ error: {
4161
- code: source.code,
4162
- message: source.message,
4247
+ code: unknownWrite ? "outcome_unknown" : source.code,
4248
+ message: unknownWrite?.message ?? source.message,
4249
+ ...unknownWrite ? {
4250
+ causeCode: source.code,
4251
+ outcome: unknownWrite.outcome,
4252
+ retryable: unknownWrite.retryable
4253
+ } : {},
4163
4254
  status: source.status,
4164
4255
  errorCode: source.upstreamCode,
4165
4256
  requestId: source.requestId,
4166
4257
  rawBody: source.rawBody,
4167
4258
  details: source.details
4168
- } }, true)
4259
+ } }, pretty)
4169
4260
  };
4170
4261
  }
4171
4262
  function compatibilityQuestionEvent(event) {
@@ -4492,8 +4583,32 @@ function createQMindCliUpdater(options) {
4492
4583
  } });
4493
4584
  }
4494
4585
  //#endregion
4495
- //#region src/application.ts
4496
- const distribution = CLI_DISTRIBUTIONS[QMIND_CLI_DISTRIBUTION];
4586
+ //#region src/config.ts
4587
+ function cliHostConfiguration(distribution, flags, environment, stateRoot) {
4588
+ const { productId, command } = CLI_DISTRIBUTIONS[distribution];
4589
+ const custom = flags.sash !== void 0 || flags.dashboard !== void 0;
4590
+ if (custom && (typeof flags.sash !== "string" || typeof flags.dashboard !== "string" || flags.env !== void 0)) throw new QMindError("INVALID_ARGUMENT", "--sash and --dashboard must be supplied together and cannot be combined with --env");
4591
+ const preset = typeof flags.env === "string" ? flags.env.trim() : "prod";
4592
+ const endpoints = custom ? {
4593
+ dashboardOrigin: normalizeQMindOrigin(String(flags.dashboard).trim(), "--dashboard"),
4594
+ sashOrigin: normalizeQMindOrigin(String(flags.sash).trim(), "--sash")
4595
+ } : resolveQMindProductEndpoints(productId, preset);
4596
+ const target = custom ? `custom-${createHash("sha256").update(JSON.stringify([endpoints.dashboardOrigin, endpoints.sashOrigin])).digest("hex")}` : preset;
4597
+ return {
4598
+ environment: {
4599
+ ...environment,
4600
+ QMIND_TOKEN: target === "prod" ? environment.QMIND_TOKEN : environment.QMIND_DEBUG_TOKEN
4601
+ },
4602
+ flags,
4603
+ fixedEndpoints: endpoints,
4604
+ homeDirectory: join(resolve(stateRoot ?? (environment.QMIND_HOME?.trim() || join(homedir(), ".qmind"))), "cli", distribution, target),
4605
+ legacyEnvironmentPath: false,
4606
+ loginCommand: `${command} login${custom ? ` --sash ${endpoints.sashOrigin} --dashboard ${endpoints.dashboardOrigin}` : target === "prod" ? "" : ` --env ${target}`}`,
4607
+ productId
4608
+ };
4609
+ }
4610
+ //#endregion
4611
+ //#region src/command-context.ts
4497
4612
  function processIO() {
4498
4613
  return Object.freeze({
4499
4614
  stdinIsTTY: process.stdin.isTTY === true,
@@ -4603,6 +4718,1949 @@ function withCommon(command, output = true) {
4603
4718
  if (output) command.option("--format <format>", "output format: table | json | agent | ndjson", "table");
4604
4719
  return command;
4605
4720
  }
4721
+ //#endregion
4722
+ //#region ../agent-core/src/scheduled-task-inputs.ts
4723
+ const id = z.string().trim().min(1).max(512);
4724
+ const scheduledTaskScene = z.enum([
4725
+ "compilation",
4726
+ "condensation",
4727
+ "lint",
4728
+ "source_refresh",
4729
+ "source_binding_sync"
4730
+ ]);
4731
+ const schedule = z.string().trim().min(1).max(512).refine((value) => {
4732
+ const fields = value.split(/\s+/u);
4733
+ const zone = /^(?:CRON_TZ|TZ)=(.+)$/u.exec(fields[0] ?? "")?.[1];
4734
+ if (!zone || !/^[A-Za-z][A-Za-z0-9_+/-]*$/u.test(zone) || fields.length !== 6 && fields.length !== 7) return false;
4735
+ try {
4736
+ new Intl.DateTimeFormat("en-US", { timeZone: zone }).format();
4737
+ return true;
4738
+ } catch {
4739
+ return false;
4740
+ }
4741
+ }, "schedule requires an explicit CRON_TZ/TZ IANA zone and five or six cron fields");
4742
+ const createScheduledTaskInputSchema = z.object({
4743
+ notebookId: id,
4744
+ sceneType: scheduledTaskScene,
4745
+ schedule
4746
+ }).strict();
4747
+ const updateScheduledTaskInputSchema = z.object({
4748
+ notebookId: id,
4749
+ taskId: id,
4750
+ schedule: schedule.optional(),
4751
+ enabled: z.boolean().optional()
4752
+ }).strict().refine((input) => input.schedule !== void 0 || input.enabled !== void 0, "Empty patch");
4753
+ const deleteScheduledTaskInputSchema = z.object({
4754
+ notebookId: id,
4755
+ taskId: id
4756
+ }).strict();
4757
+ const listScheduledTasksInputSchema = z.object({
4758
+ notebookId: id,
4759
+ taskId: id.optional(),
4760
+ sceneType: scheduledTaskScene.optional(),
4761
+ enabled: z.boolean().optional(),
4762
+ page: z.number().int().min(1).max(1e6).default(1),
4763
+ pageSize: z.number().int().min(1).max(20).default(20)
4764
+ }).strict();
4765
+ //#endregion
4766
+ //#region ../../node_modules/.pnpm/canonicalize@4.0.0/node_modules/canonicalize/lib/canonicalize.js
4767
+ function hasLoneSurrogate(value) {
4768
+ for (let i = 0; i < value.length; i++) {
4769
+ const code = value.charCodeAt(i);
4770
+ if (code >= 55296 && code <= 56319) {
4771
+ if (i === value.length - 1) return true;
4772
+ const next = value.charCodeAt(i + 1);
4773
+ if (!(next >= 56320 && next <= 57343)) return true;
4774
+ i++;
4775
+ } else if (code >= 56320 && code <= 57343) return true;
4776
+ }
4777
+ return false;
4778
+ }
4779
+ function canonicalize(object, seen = /* @__PURE__ */ new Set()) {
4780
+ if (typeof object === "number" && isNaN(object)) throw new Error("NaN is not allowed");
4781
+ if (typeof object === "number" && !isFinite(object)) throw new Error("Infinity is not allowed");
4782
+ if (typeof object === "string" && hasLoneSurrogate(object)) throw new Error("Lone surrogate is not allowed");
4783
+ if (object === null || typeof object !== "object") return JSON.stringify(object);
4784
+ if (typeof object.toJSON === "function") {
4785
+ if (seen.has(object)) throw new Error("Circular reference detected");
4786
+ seen.add(object);
4787
+ const result = canonicalize(object.toJSON(), seen);
4788
+ seen.delete(object);
4789
+ return result;
4790
+ }
4791
+ if (seen.has(object)) throw new Error("Circular reference detected");
4792
+ seen.add(object);
4793
+ let result;
4794
+ if (Array.isArray(object)) result = `[${object.map((cv) => {
4795
+ return canonicalize(cv === void 0 || typeof cv === "symbol" ? null : cv, seen);
4796
+ }).join(",")}]`;
4797
+ else {
4798
+ const parts = [];
4799
+ for (const key of Object.keys(object).sort()) {
4800
+ if (object[key] === void 0 || typeof object[key] === "symbol") continue;
4801
+ parts.push(`${canonicalize(key)}:${canonicalize(object[key], seen)}`);
4802
+ }
4803
+ result = `{${parts.join(",")}}`;
4804
+ }
4805
+ seen.delete(object);
4806
+ return result;
4807
+ }
4808
+ //#endregion
4809
+ //#region ../agent-core/src/contract.ts
4810
+ const CONTRACT_VERSION = "5.4.0";
4811
+ const AGENT_ERROR_CODES = Object.freeze([
4812
+ "invalid_input",
4813
+ "selection_required",
4814
+ "not_found",
4815
+ "already_exists",
4816
+ "quota_exceeded",
4817
+ "capability_unavailable",
4818
+ "source_not_ready",
4819
+ "source_unsupported",
4820
+ "source_failed",
4821
+ "unauthenticated",
4822
+ "permission_denied",
4823
+ "rate_limited",
4824
+ "upstream_unavailable",
4825
+ "timeout",
4826
+ "cancelled",
4827
+ "outcome_unknown",
4828
+ "internal",
4829
+ "source_deletion_failed"
4830
+ ]);
4831
+ const retryableCodes = /* @__PURE__ */ new Set([
4832
+ "source_not_ready",
4833
+ "rate_limited",
4834
+ "upstream_unavailable",
4835
+ "timeout"
4836
+ ]);
4837
+ function isRetryableAgentError(code) {
4838
+ return retryableCodes.has(code);
4839
+ }
4840
+ const opaqueId = z.string().trim().min(1).max(512);
4841
+ const page = z.number().int().min(1).default(1);
4842
+ const pageSize = z.number().int().min(1).max(50).default(20);
4843
+ const createNotebookInputSchema = z.object({
4844
+ title: z.string().trim().min(1).max(500),
4845
+ description: z.string().max(2e3).optional()
4846
+ }).strict();
4847
+ const deleteNotebookInputSchema = z.object({ notebookId: opaqueId }).strict();
4848
+ const listNotebooksInputSchema = z.object({
4849
+ page,
4850
+ pageSize,
4851
+ relationship: z.enum([
4852
+ "owned",
4853
+ "shared",
4854
+ "all"
4855
+ ]).optional(),
4856
+ cursor: z.string().min(1).max(512).optional()
4857
+ }).strict();
4858
+ const retrieveInputSchema = z.object({
4859
+ maxResults: z.number().int().min(1).max(50).default(8),
4860
+ notebookId: opaqueId.optional(),
4861
+ targets: z.array(z.object({
4862
+ notebookId: opaqueId,
4863
+ sourceIds: z.array(opaqueId).min(1).max(100).refine((ids) => new Set(ids).size === ids.length).optional()
4864
+ }).strict()).min(1).max(5).refine((targets) => new Set(targets.map((target) => target.notebookId)).size === targets.length).optional(),
4865
+ query: z.string().trim().min(1).max(2e3),
4866
+ scoreThreshold: z.number().min(0).max(1).optional(),
4867
+ sourceIds: z.array(opaqueId).min(1).max(50).refine((values) => new Set(values).size === values.length, { message: "sourceIds must be unique" }).optional(),
4868
+ topK: z.number().int().min(1).max(100).optional()
4869
+ }).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" });
4870
+ const listSourcesInputSchema = z.object({
4871
+ notebookId: opaqueId,
4872
+ page,
4873
+ pageSize,
4874
+ parentSourceId: opaqueId.optional()
4875
+ }).strict();
4876
+ const getSourceInputSchema = z.object({
4877
+ notebookId: opaqueId,
4878
+ sourceId: opaqueId
4879
+ }).strict();
4880
+ const readSourceInputSchema = z.object({
4881
+ maxChars: z.number().int().min(1).max(5e4).default(2e4),
4882
+ notebookId: opaqueId,
4883
+ offset: z.number().int().min(0).default(0),
4884
+ sourceId: opaqueId
4885
+ }).strict();
4886
+ const sourceInputSchema = z.discriminatedUnion("kind", [z.object({
4887
+ kind: z.literal("url"),
4888
+ title: z.string().trim().min(1).max(500).optional(),
4889
+ url: z.string().trim().url().max(4096).refine((value) => {
4890
+ const url = new URL(value);
4891
+ return url.protocol === "https:" && url.username.length === 0 && url.password.length === 0;
4892
+ }, { message: "url must use HTTPS without embedded credentials" })
4893
+ }).strict(), z.object({
4894
+ filePath: z.string().trim().min(1).max(4096),
4895
+ kind: z.literal("file"),
4896
+ title: z.string().trim().min(1).max(500).optional()
4897
+ }).strict()]);
4898
+ const addSourceInputSchema = z.object({
4899
+ notebookId: opaqueId,
4900
+ source: sourceInputSchema
4901
+ }).strict();
4902
+ const deleteSourceInputSchema = z.object({
4903
+ notebookId: opaqueId,
4904
+ sourceIds: z.array(opaqueId).min(1).max(100).refine((ids) => new Set(ids).size === ids.length)
4905
+ }).strict();
4906
+ const directoryName = z.string().trim().min(1).max(500).refine((value) => value !== "." && value !== ".." && !/[\\/\0]/.test(value), { message: "title must be one path segment" });
4907
+ const createDirectoryInputSchema = z.object({
4908
+ notebookId: opaqueId,
4909
+ title: directoryName,
4910
+ parentSourceId: opaqueId.optional()
4911
+ }).strict();
4912
+ const moveSourceInputSchema = z.object({
4913
+ notebookId: opaqueId,
4914
+ sourceId: opaqueId,
4915
+ targetParentSourceId: opaqueId.nullable()
4916
+ }).strict();
4917
+ const agentToolInputSchemas = Object.freeze({
4918
+ "qmind.create_notebook": createNotebookInputSchema,
4919
+ "qmind.delete_notebook": deleteNotebookInputSchema,
4920
+ "qmind.create_scheduled_task": createScheduledTaskInputSchema,
4921
+ "qmind.update_scheduled_task": updateScheduledTaskInputSchema,
4922
+ "qmind.delete_scheduled_task": deleteScheduledTaskInputSchema,
4923
+ "qmind.list_scheduled_tasks": listScheduledTasksInputSchema,
4924
+ "qmind.create_directory": createDirectoryInputSchema,
4925
+ "qmind.move_source": moveSourceInputSchema,
4926
+ "qmind.add_source": addSourceInputSchema,
4927
+ "qmind.delete_source": deleteSourceInputSchema,
4928
+ "qmind.get_source": getSourceInputSchema,
4929
+ "qmind.list_notebooks": listNotebooksInputSchema,
4930
+ "qmind.list_sources": listSourcesInputSchema,
4931
+ "qmind.read_source": readSourceInputSchema,
4932
+ "qmind.retrieve": retrieveInputSchema
4933
+ });
4934
+ const agentToolDefinitions = Object.freeze([
4935
+ {
4936
+ deadlineMs: 3e4,
4937
+ description: "Create a QMind notebook with a title and optional description. Requires an account context without a host Notebook scope or policy; creation never binds the new notebook to a workspace or expands scope. Duplicate titles create independent notebooks. Never retry outcome_unknown automatically; inspect current notebooks first, and do not treat a matching title as proof of creation.",
4938
+ id: "qmind.create_notebook",
4939
+ intent: "write",
4940
+ leaf: "create_notebook"
4941
+ },
4942
+ {
4943
+ deadlineMs: 3e4,
4944
+ description: "Delete one entire QMind notebook by its explicit notebookId, including its contents. Host Notebook scope and server permissions apply. Execution follows the host permission policy; destructive annotations do not guarantee an approval prompt. Never retry outcome_unknown automatically; reconcile current notebook state before another call.",
4945
+ id: "qmind.delete_notebook",
4946
+ intent: "write",
4947
+ destructive: true,
4948
+ leaf: "delete_notebook"
4949
+ },
4950
+ {
4951
+ deadlineMs: 6e4,
4952
+ description: "Retrieve globally ranked context from up to 5 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 five notebooks. Omitted selection uses configured defaults; maxResults is the global result limit.",
4953
+ id: "qmind.retrieve",
4954
+ intent: "read",
4955
+ leaf: "retrieve"
4956
+ },
4957
+ {
4958
+ deadlineMs: 3e4,
4959
+ description: "Discover QMind notebooks using summary/topics and relationship (owned/shared). The host can default to owned plus shared; otherwise the default is owned. Discovery stays within the current chat scope and server-filtered retrieval scope. Discovery returns hasMore and nextCursor; continue with cursor and the same relationship, even after an empty page. Results are dynamic, ordered owned then shared, without an exact total. Use the question and overviews to select at most 5 relevant notebooks; never blindly retrieve every notebook. Legacy account listing without relationship or cursor retains page/pageSize and owned-only behavior.",
4960
+ id: "qmind.list_notebooks",
4961
+ intent: "read",
4962
+ leaf: "list_notebooks"
4963
+ },
4964
+ {
4965
+ deadlineMs: 3e4,
4966
+ description: "List sources in a QMind notebook.",
4967
+ id: "qmind.list_sources",
4968
+ intent: "read",
4969
+ leaf: "list_sources"
4970
+ },
4971
+ {
4972
+ deadlineMs: 3e4,
4973
+ description: "Get one source in a QMind notebook.",
4974
+ id: "qmind.get_source",
4975
+ intent: "read",
4976
+ leaf: "get_source"
4977
+ },
4978
+ {
4979
+ deadlineMs: 6e4,
4980
+ description: "Read a bounded slice of a ready QMind source.",
4981
+ id: "qmind.read_source",
4982
+ intent: "read",
4983
+ leaf: "read_source"
4984
+ },
4985
+ {
4986
+ deadlineMs: 12e4,
4987
+ description: "Add an HTTPS URL or a local file to QMind. For generated content, first write a meaningfully named .md or .txt file, then pass its absolute filePath readable by the MCP process. If the Agent and MCP do not share a filesystem, use host file transfer first. title is optional display metadata; file format and upload checks use the actual file.",
4988
+ id: "qmind.add_source",
4989
+ intent: "write",
4990
+ leaf: "add_source"
4991
+ },
4992
+ {
4993
+ deadlineMs: 3e4,
4994
+ description: "Delete 1 to 100 distinct sources from one QMind notebook in one batch. Directories include their descendants. Select actual email folders, not email bodies belonging to a folder. Execution follows the host permission policy; destructive annotations do not guarantee an approval prompt. If Qoder auto mode denies a permission request, explain the denial and ask the user to switch to an interactive approval mode before retrying. Do not change permission mode or use another tool to bypass the denial. Partial or unknown outcomes must be reconciled before a new call; never retry automatically.",
4995
+ id: "qmind.delete_source",
4996
+ intent: "write",
4997
+ destructive: true,
4998
+ leaf: "delete_source"
4999
+ },
5000
+ {
5001
+ deadlineMs: 3e4,
5002
+ description: "Create one directory in a QMind notebook. title is a single path segment; omit parentSourceId for root or use a real writable directory ID. Duplicate names create independent IDs, not get-or-create. Do not retry unknown outcomes automatically; a same-name directory cannot confirm this creation.",
5003
+ id: "qmind.create_directory",
5004
+ intent: "write",
5005
+ leaf: "create_directory"
5006
+ },
5007
+ {
5008
+ deadlineMs: 3e4,
5009
+ description: "Move one ordinary leaf document within the same QMind notebook. targetParentSourceId is required: use a real writable directory ID or null for root. Directories, documents with children, managed sources, email members and pending/processing/failed sources are rejected. Preserves basename and content. On outcome_unknown, get_source to inspect current parent/path before deciding another action; never retry automatically. Preflight and write are not atomic.",
5010
+ id: "qmind.move_source",
5011
+ intent: "write",
5012
+ destructive: true,
5013
+ leaf: "move_source"
5014
+ },
5015
+ {
5016
+ deadlineMs: 3e4,
5017
+ 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.",
5018
+ id: "qmind.create_scheduled_task",
5019
+ intent: "write",
5020
+ leaf: "create_scheduled_task"
5021
+ },
5022
+ {
5023
+ deadlineMs: 3e4,
5024
+ 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.",
5025
+ id: "qmind.update_scheduled_task",
5026
+ intent: "write",
5027
+ destructive: true,
5028
+ leaf: "update_scheduled_task"
5029
+ },
5030
+ {
5031
+ deadlineMs: 3e4,
5032
+ description: "Delete one scheduled-task configuration from a QMind notebook by taskId. Requires manage permission. Does not delete execution history or cancel running/dispatched work; a scheduler snapshot already read may still dispatch once. Never retry outcome_unknown automatically; list tasks to reconcile. Preflight and write are not atomic.",
5033
+ id: "qmind.delete_scheduled_task",
5034
+ intent: "write",
5035
+ destructive: true,
5036
+ leaf: "delete_scheduled_task"
5037
+ },
5038
+ {
5039
+ deadlineMs: 3e4,
5040
+ description: "List scheduled-task configurations in one QMind notebook, optionally filtered by taskId, sceneType and enabled. Requires view permission. Results are sorted by ID and paginated locally (pageSize at most 20); the server still reads the full notebook list. Continue with page when hasMore. Lists are dynamic, not a snapshot. Oversized config is omitted with configTruncated=true. lastRunAt means dispatch, not successful business completion. Execution uses the original creator identity; revoking membership does not automatically stop existing schedules.",
5041
+ id: "qmind.list_scheduled_tasks",
5042
+ intent: "read",
5043
+ leaf: "list_scheduled_tasks"
5044
+ }
5045
+ ]);
5046
+ function deadlineFor(toolId, input) {
5047
+ if (toolId === "qmind.add_source" && typeof input === "object" && input !== null && "source" in input && typeof input.source === "object" && input.source !== null && "kind" in input.source && input.source.kind === "file") return 3e5;
5048
+ return agentToolDefinitions.find((tool) => tool.id === toolId)?.deadlineMs ?? 3e4;
5049
+ }
5050
+ function deepFreeze(value) {
5051
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
5052
+ for (const nested of Object.values(value)) deepFreeze(nested);
5053
+ return Object.freeze(value);
5054
+ }
5055
+ const canonicalDescriptor = canonicalize(deepFreeze({
5056
+ contractVersion: CONTRACT_VERSION,
5057
+ definitions: {
5058
+ ScheduledTask: {
5059
+ id: "opaqueId",
5060
+ notebookId: "opaqueId",
5061
+ sceneType: "compilation|condensation|lint|source_refresh|source_binding_sync",
5062
+ schedule: "string:1..512",
5063
+ enabled: "boolean",
5064
+ nextRunAt: "iso8601",
5065
+ lastRunAt: "iso8601|empty",
5066
+ createdAt: "iso8601|empty",
5067
+ updatedAt: "iso8601|empty",
5068
+ config: "object; omitted contents if JSON exceeds 2000 UTF-8 bytes",
5069
+ configTruncated: "boolean"
5070
+ },
5071
+ SourceDeletionTarget: {
5072
+ sourceId: "opaqueId",
5073
+ title: "string",
5074
+ scope: "source|subtree",
5075
+ revision: "sha256"
5076
+ },
5077
+ Source: {
5078
+ createdAt: "iso8601?",
5079
+ errorCode: "source_unsupported|source_failed?",
5080
+ id: "opaqueId",
5081
+ isDir: "boolean",
5082
+ notebookId: "opaqueId",
5083
+ parentSourceId: "opaqueId?",
5084
+ path: "string?",
5085
+ sourceType: "string",
5086
+ status: "pending|processing|ready|unsupported|failed",
5087
+ title: "string",
5088
+ updatedAt: "iso8601?"
5089
+ }
5090
+ },
5091
+ errorCatalog: AGENT_ERROR_CODES.map((code) => ({
5092
+ code,
5093
+ retryable: isRetryableAgentError(code),
5094
+ ...code === "source_deletion_failed" ? { details: {
5095
+ successCount: "0",
5096
+ failureCount: "integer:1..100"
5097
+ } } : {}
5098
+ })),
5099
+ invocation: {
5100
+ defaultNotebookRelationship: "owned|shared|all?; host discovery default independent of notebookPolicy; omitted means owned",
5101
+ approvedDeletionTargets: "SourceDeletionTarget[1..100]?; host-only, must match fresh targets",
5102
+ notebookPolicy: { selectNotebook: "host callback: excluded|allowed|preferred; request-local; intersects server ACL" },
5103
+ notebookScope: {
5104
+ allowedNotebookIds: "uniqueOpaqueId[]",
5105
+ preferredNotebookIds: "uniqueOpaqueId[]?; subset of allowedNotebookIds",
5106
+ enforcement: "all-tools-before-qmind-client-call",
5107
+ omitted: "authenticated-account-scope",
5108
+ present: "restricted-upper-bound"
5109
+ }
5110
+ },
5111
+ lifecycle: {
5112
+ finished: {
5113
+ fields: [
5114
+ "eventId",
5115
+ "operationId",
5116
+ "toolId",
5117
+ "intent",
5118
+ "occurredAt",
5119
+ "outcome",
5120
+ "durationMs",
5121
+ "notebookIds?",
5122
+ "partial?",
5123
+ "warningCodes?",
5124
+ "errorCode?"
5125
+ ],
5126
+ outcomes: [
5127
+ "succeeded",
5128
+ "failed",
5129
+ "cancelled",
5130
+ "outcome_unknown"
5131
+ ],
5132
+ type: "qmind.operation.finished"
5133
+ },
5134
+ started: {
5135
+ fields: [
5136
+ "eventId",
5137
+ "operationId",
5138
+ "toolId",
5139
+ "intent",
5140
+ "occurredAt"
5141
+ ],
5142
+ type: "qmind.operation.started"
5143
+ }
5144
+ },
5145
+ resultEnvelope: {
5146
+ failure: [
5147
+ "ok",
5148
+ "error.code",
5149
+ "error.message",
5150
+ "error.retryable",
5151
+ "error.details?",
5152
+ "meta.operationId"
5153
+ ],
5154
+ success: [
5155
+ "ok",
5156
+ "data",
5157
+ "meta.operationId",
5158
+ "meta.partial?",
5159
+ "meta.warnings?"
5160
+ ]
5161
+ },
5162
+ tools: [
5163
+ {
5164
+ annotations: {
5165
+ destructiveHint: false,
5166
+ idempotentHint: false,
5167
+ openWorldHint: true,
5168
+ readOnlyHint: false
5169
+ },
5170
+ id: "qmind.create_notebook",
5171
+ intent: "write",
5172
+ input: {
5173
+ title: "trimmed-string:1..500",
5174
+ description: "string:0..2000?"
5175
+ },
5176
+ output: {
5177
+ id: "opaqueId",
5178
+ title: "string",
5179
+ description: "string"
5180
+ },
5181
+ scope: "requires omitted notebookScope and notebookPolicy; does not bind or expand scope",
5182
+ timeoutMs: 3e4
5183
+ },
5184
+ {
5185
+ annotations: {
5186
+ destructiveHint: true,
5187
+ idempotentHint: false,
5188
+ openWorldHint: true,
5189
+ readOnlyHint: false
5190
+ },
5191
+ id: "qmind.delete_notebook",
5192
+ intent: "write",
5193
+ input: { notebookId: "opaqueId" },
5194
+ output: {
5195
+ notebookId: "opaqueId",
5196
+ deleted: true
5197
+ },
5198
+ timeoutMs: 3e4
5199
+ },
5200
+ {
5201
+ annotations: {
5202
+ destructiveHint: false,
5203
+ idempotentHint: true,
5204
+ openWorldHint: true,
5205
+ readOnlyHint: true
5206
+ },
5207
+ defaults: { maxResults: 8 },
5208
+ id: "qmind.retrieve",
5209
+ input: {
5210
+ maxResults: "integer:1..50?",
5211
+ notebookId: "opaqueId?; exclusive with targets",
5212
+ targets: "[{notebookId, sourceIds?}][1..5]?; unique notebooks",
5213
+ query: "string:1..2000",
5214
+ scoreThreshold: "number:0..1?",
5215
+ sourceIds: "uniqueOpaqueId[1..50]?",
5216
+ topK: "integer:1..100?"
5217
+ },
5218
+ intent: "read",
5219
+ output: {
5220
+ chunks: [{
5221
+ chunkId: "opaqueId",
5222
+ chunkIndex: "integer:0..",
5223
+ content: "string",
5224
+ notebookId: "opaqueId",
5225
+ notebookTitle: "string",
5226
+ originUrl: "string?",
5227
+ score: "number",
5228
+ sourceId: "opaqueId",
5229
+ sourceTitle: "string",
5230
+ tokenCount: "integer:0.."
5231
+ }],
5232
+ promptContext: "string",
5233
+ reranked: "boolean",
5234
+ total: "integer:0.."
5235
+ },
5236
+ timeoutMs: 6e4
5237
+ },
5238
+ {
5239
+ annotations: {
5240
+ destructiveHint: false,
5241
+ idempotentHint: true,
5242
+ openWorldHint: true,
5243
+ readOnlyHint: true
5244
+ },
5245
+ defaults: {
5246
+ page: 1,
5247
+ pageSize: 20
5248
+ },
5249
+ discovery: { eligibility: "server filters before pagination; deploy server and gateway before clients" },
5250
+ id: "qmind.list_notebooks",
5251
+ input: {
5252
+ page: "integer:1..?",
5253
+ pageSize: "integer:1..50?",
5254
+ relationship: "owned|shared|all?",
5255
+ cursor: "opaqueString?; continuation for filtered discovery"
5256
+ },
5257
+ intent: "read",
5258
+ output: {
5259
+ notebooks: [{
5260
+ description: "string?",
5261
+ id: "opaqueId",
5262
+ materialCount: "integer",
5263
+ sourceCount: "integer",
5264
+ status: "string",
5265
+ preferred: "boolean",
5266
+ relationship: "owned|shared?",
5267
+ summary: "string?",
5268
+ title: "string",
5269
+ topics: "string[]?",
5270
+ updatedAt: "iso8601?"
5271
+ }],
5272
+ page: "integer:1..; legacy listing only",
5273
+ pageSize: "integer:1..50",
5274
+ totalSize: "integer:0..; legacy listing only",
5275
+ hasMore: "boolean; discovery only",
5276
+ nextCursor: "opaqueString?; discovery continuation",
5277
+ retrievalSelection: "{maxTargets:5, overviewSelectionRequired:boolean}"
5278
+ },
5279
+ timeoutMs: 3e4
5280
+ },
5281
+ {
5282
+ annotations: {
5283
+ destructiveHint: false,
5284
+ idempotentHint: true,
5285
+ openWorldHint: true,
5286
+ readOnlyHint: true
5287
+ },
5288
+ defaults: {
5289
+ page: 1,
5290
+ pageSize: 20
5291
+ },
5292
+ id: "qmind.list_sources",
5293
+ input: {
5294
+ notebookId: "opaqueId",
5295
+ page: "integer:1..?",
5296
+ pageSize: "integer:1..50?",
5297
+ parentSourceId: "opaqueId?"
5298
+ },
5299
+ intent: "read",
5300
+ output: {
5301
+ page: "integer:1..",
5302
+ pageSize: "integer:1..50",
5303
+ sources: ["Source"],
5304
+ totalSize: "integer:0..?"
5305
+ },
5306
+ timeoutMs: 3e4
5307
+ },
5308
+ {
5309
+ annotations: {
5310
+ destructiveHint: false,
5311
+ idempotentHint: true,
5312
+ openWorldHint: true,
5313
+ readOnlyHint: true
5314
+ },
5315
+ id: "qmind.get_source",
5316
+ input: {
5317
+ notebookId: "opaqueId",
5318
+ sourceId: "opaqueId"
5319
+ },
5320
+ intent: "read",
5321
+ output: "Source & { deletion: SourceDeletionTarget }",
5322
+ timeoutMs: 3e4
5323
+ },
5324
+ {
5325
+ annotations: {
5326
+ destructiveHint: false,
5327
+ idempotentHint: true,
5328
+ openWorldHint: true,
5329
+ readOnlyHint: true
5330
+ },
5331
+ defaults: {
5332
+ maxChars: 2e4,
5333
+ offset: 0
5334
+ },
5335
+ id: "qmind.read_source",
5336
+ input: {
5337
+ maxChars: "integer:1..50000?",
5338
+ notebookId: "opaqueId",
5339
+ offset: "integer:0..?",
5340
+ sourceId: "opaqueId"
5341
+ },
5342
+ intent: "read",
5343
+ output: {
5344
+ content: "string:0..50000",
5345
+ contentType: "string",
5346
+ nextOffset: "integer:0..?",
5347
+ sourceId: "opaqueId",
5348
+ truncated: "boolean"
5349
+ },
5350
+ timeoutMs: 6e4
5351
+ },
5352
+ {
5353
+ annotations: {
5354
+ destructiveHint: false,
5355
+ idempotentHint: false,
5356
+ openWorldHint: true,
5357
+ readOnlyHint: false
5358
+ },
5359
+ id: "qmind.add_source",
5360
+ input: {
5361
+ notebookId: "opaqueId",
5362
+ source: [{
5363
+ kind: "url",
5364
+ title: "string:1..500?",
5365
+ url: "credential-free-https:1..4096"
5366
+ }, {
5367
+ filePath: "string:1..4096",
5368
+ kind: "file",
5369
+ title: "string:1..500?"
5370
+ }]
5371
+ },
5372
+ intent: "write",
5373
+ output: "Source",
5374
+ timeoutMs: {
5375
+ file: 3e5,
5376
+ url: 12e4
5377
+ }
5378
+ },
5379
+ {
5380
+ annotations: {
5381
+ destructiveHint: true,
5382
+ idempotentHint: false,
5383
+ openWorldHint: true,
5384
+ readOnlyHint: false
5385
+ },
5386
+ id: "qmind.delete_source",
5387
+ input: {
5388
+ notebookId: "opaqueId",
5389
+ sourceIds: "uniqueOpaqueId[1..100]"
5390
+ },
5391
+ intent: "write",
5392
+ output: {
5393
+ notebookId: "opaqueId",
5394
+ sourceIds: "uniqueOpaqueId[1..100]",
5395
+ successCount: "integer:0..",
5396
+ failureCount: "integer:0.."
5397
+ },
5398
+ timeoutMs: 3e4
5399
+ },
5400
+ {
5401
+ annotations: {
5402
+ destructiveHint: false,
5403
+ idempotentHint: false,
5404
+ openWorldHint: true,
5405
+ readOnlyHint: false
5406
+ },
5407
+ id: "qmind.create_directory",
5408
+ input: {
5409
+ notebookId: "opaqueId",
5410
+ title: "single-path-segment:1..500; trimmed",
5411
+ parentSourceId: "opaqueId?; omitted means root"
5412
+ },
5413
+ intent: "write",
5414
+ output: "Source",
5415
+ timeoutMs: 3e4
5416
+ },
5417
+ {
5418
+ annotations: {
5419
+ destructiveHint: true,
5420
+ idempotentHint: false,
5421
+ openWorldHint: true,
5422
+ readOnlyHint: false
5423
+ },
5424
+ id: "qmind.move_source",
5425
+ input: {
5426
+ notebookId: "opaqueId",
5427
+ sourceId: "opaqueId",
5428
+ targetParentSourceId: "opaqueId|null; required, null means root"
5429
+ },
5430
+ intent: "write",
5431
+ output: "Source",
5432
+ timeoutMs: 3e4
5433
+ },
5434
+ {
5435
+ annotations: {
5436
+ destructiveHint: false,
5437
+ idempotentHint: false,
5438
+ openWorldHint: true,
5439
+ readOnlyHint: false
5440
+ },
5441
+ id: "qmind.create_scheduled_task",
5442
+ intent: "write",
5443
+ input: {
5444
+ notebookId: "opaqueId",
5445
+ sceneType: "ScheduledTask.sceneType",
5446
+ schedule: "explicit-IANA-zone-prefixed-cron:1..512; server validates syntax and scene interval"
5447
+ },
5448
+ output: "ScheduledTask; enabled=true",
5449
+ timeoutMs: 3e4
5450
+ },
5451
+ {
5452
+ annotations: {
5453
+ destructiveHint: true,
5454
+ idempotentHint: false,
5455
+ openWorldHint: true,
5456
+ readOnlyHint: false
5457
+ },
5458
+ id: "qmind.update_scheduled_task",
5459
+ intent: "write",
5460
+ input: {
5461
+ notebookId: "opaqueId",
5462
+ taskId: "opaqueId",
5463
+ schedule: "explicit-IANA-zone-prefixed-cron:1..512?",
5464
+ enabled: "boolean?; at least one patch field"
5465
+ },
5466
+ output: "ScheduledTask",
5467
+ timeoutMs: 3e4
5468
+ },
5469
+ {
5470
+ annotations: {
5471
+ destructiveHint: true,
5472
+ idempotentHint: false,
5473
+ openWorldHint: true,
5474
+ readOnlyHint: false
5475
+ },
5476
+ id: "qmind.delete_scheduled_task",
5477
+ intent: "write",
5478
+ input: {
5479
+ notebookId: "opaqueId",
5480
+ taskId: "opaqueId"
5481
+ },
5482
+ output: {
5483
+ notebookId: "opaqueId",
5484
+ taskId: "opaqueId",
5485
+ deleted: true
5486
+ },
5487
+ timeoutMs: 3e4
5488
+ },
5489
+ {
5490
+ annotations: {
5491
+ destructiveHint: false,
5492
+ idempotentHint: true,
5493
+ openWorldHint: true,
5494
+ readOnlyHint: true
5495
+ },
5496
+ id: "qmind.list_scheduled_tasks",
5497
+ intent: "read",
5498
+ input: {
5499
+ notebookId: "opaqueId",
5500
+ taskId: "opaqueId?",
5501
+ sceneType: "ScheduledTask.sceneType?",
5502
+ enabled: "boolean?",
5503
+ page: "integer:1..1000000?",
5504
+ pageSize: "integer:1..20?"
5505
+ },
5506
+ output: {
5507
+ tasks: ["ScheduledTask"],
5508
+ page: "integer:1..1000000",
5509
+ pageSize: "integer:1..20",
5510
+ totalSize: "integer:0..",
5511
+ hasMore: "boolean"
5512
+ },
5513
+ timeoutMs: 3e4,
5514
+ defaults: {
5515
+ page: 1,
5516
+ pageSize: 20
5517
+ }
5518
+ }
5519
+ ],
5520
+ warningCatalog: [{
5521
+ code: "notebook_search_failed",
5522
+ fields: ["code", "notebookId"]
5523
+ }, {
5524
+ code: "source_deletion_failed",
5525
+ fields: ["code", "notebookId"]
5526
+ }]
5527
+ }));
5528
+ if (canonicalDescriptor === void 0) throw new Error("QMind Agent Contract is not serializable");
5529
+ createHash("sha256").update(canonicalDescriptor, "utf8").digest("hex");
5530
+ //#endregion
5531
+ //#region ../agent-core/src/client-operation.ts
5532
+ function failure$1(operationId, code, message) {
5533
+ return {
5534
+ error: {
5535
+ code,
5536
+ message,
5537
+ retryable: isRetryableAgentError(code)
5538
+ },
5539
+ meta: { operationId },
5540
+ ok: false
5541
+ };
5542
+ }
5543
+ function errorCode(error, mutationStarted = false) {
5544
+ if (typeof error === "object" && error !== null) {
5545
+ const candidate = error;
5546
+ if (candidate.upstreamCode === "NotebookSourceQuotaExceeded") return "quota_exceeded";
5547
+ if (candidate.code === "AUTH_REQUIRED") return "unauthenticated";
5548
+ if (candidate.code === "FORBIDDEN") return "permission_denied";
5549
+ if (candidate.code === "NOT_FOUND") return "not_found";
5550
+ if (candidate.code === "CONFLICT") return "already_exists";
5551
+ if (candidate.code === "RATE_LIMITED") return "rate_limited";
5552
+ if (candidate.code === "UNSUPPORTED_OPERATION") return "capability_unavailable";
5553
+ if (candidate.status === 408) return mutationStarted ? "outcome_unknown" : "timeout";
5554
+ if (candidate.code === "FILE_TOO_LARGE" || candidate.code === "INVALID_ARGUMENT") return "invalid_input";
5555
+ if (candidate.code === "TIMEOUT") return mutationStarted ? "outcome_unknown" : "timeout";
5556
+ if (candidate.name === "TimeoutError") return mutationStarted ? "outcome_unknown" : "timeout";
5557
+ if (candidate.code === "ABORTED" || candidate.name === "AbortError") return mutationStarted ? "outcome_unknown" : "cancelled";
5558
+ if (candidate.code === "NETWORK_ERROR" || candidate.code === "REMOTE_ERROR") return mutationStarted ? "outcome_unknown" : "upstream_unavailable";
5559
+ }
5560
+ return "internal";
5561
+ }
5562
+ /**
5563
+ * Per-call options forwarded to every client method: the operation signal plus, when the host
5564
+ * pushed a per-operation identity, its bearer token as the request authorization override.
5565
+ */
5566
+ function callOptions(invocation) {
5567
+ return {
5568
+ ...invocation.token === void 0 ? {} : { authorization: invocation.token },
5569
+ signal: invocation.signal
5570
+ };
5571
+ }
5572
+ //#endregion
5573
+ //#region ../agent-core/src/organizationPolicy.ts
5574
+ /** Preserve the explicit policy denial without exposing arbitrary upstream error text. */
5575
+ function qmindOrganizationDisabledError(error) {
5576
+ if (typeof error !== "object" || error === null || !("upstreamCode" in error) || error.upstreamCode !== "QMindDisabledByOrganization") return void 0;
5577
+ return {
5578
+ code: "permission_denied",
5579
+ message: "企业管理员已禁用知识库功能,暂时无法使用。请联系企业管理员开启知识库功能后再试;重复调用无法恢复访问。",
5580
+ retryable: false
5581
+ };
5582
+ }
5583
+ //#endregion
5584
+ //#region ../agent-core/src/notebook-mutations.ts
5585
+ async function runNotebookMutation(client, tool, rawInput, invocation) {
5586
+ if (tool === "qmind.create_notebook" && !client.createNotebook || tool === "qmind.delete_notebook" && !client.deleteNotebook) return failure$1(invocation.operationId, "capability_unavailable", "This client does not support this notebook operation.");
5587
+ let mutationStarted = false;
5588
+ try {
5589
+ const options = callOptions(invocation);
5590
+ invocation.signal?.throwIfAborted();
5591
+ if (tool === "qmind.create_notebook") {
5592
+ const input = rawInput;
5593
+ mutationStarted = true;
5594
+ const notebook = await client.createNotebook(input, options);
5595
+ invocation.signal?.throwIfAborted();
5596
+ if (typeof notebook.id !== "string" || !notebook.id || notebook.id.length > 512 || notebook.id.trim() !== notebook.id || notebook.title !== input.title || notebook.description !== (input.description ?? "")) throw new TypeError("Unconfirmed notebook creation.");
5597
+ return {
5598
+ ok: true,
5599
+ data: {
5600
+ id: notebook.id,
5601
+ title: notebook.title,
5602
+ description: notebook.description
5603
+ },
5604
+ meta: { operationId: invocation.operationId }
5605
+ };
5606
+ }
5607
+ const input = rawInput;
5608
+ mutationStarted = true;
5609
+ const response = await client.deleteNotebook(input.notebookId, options);
5610
+ invocation.signal?.throwIfAborted();
5611
+ if (response !== void 0) throw new TypeError("Unconfirmed notebook deletion.");
5612
+ return {
5613
+ ok: true,
5614
+ data: {
5615
+ notebookId: input.notebookId,
5616
+ deleted: true
5617
+ },
5618
+ meta: { operationId: invocation.operationId }
5619
+ };
5620
+ } catch (error) {
5621
+ const policy = qmindOrganizationDisabledError(error);
5622
+ if (policy) return {
5623
+ ok: false,
5624
+ error: policy,
5625
+ meta: { operationId: invocation.operationId }
5626
+ };
5627
+ const mapped = errorCode(error, mutationStarted);
5628
+ const code = mutationStarted && mapped === "internal" ? "outcome_unknown" : mapped;
5629
+ return failure$1(invocation.operationId, code, code === "outcome_unknown" ? "The notebook operation did not return a confirmed result. Inspect current notebooks before another call; never retry automatically." : "The notebook operation failed.");
5630
+ }
5631
+ }
5632
+ //#endregion
5633
+ //#region ../agent-core/src/scheduled-tasks.ts
5634
+ function taskData(task, notebookId) {
5635
+ if (task.notebookId !== notebookId || typeof task.id !== "string" || !task.id || task.id.length > 512 || typeof task.enabled !== "boolean" || !scheduledTaskScene.safeParse(task.sceneType).success || typeof task.schedule !== "string" || !task.schedule || task.schedule.length > 512 || !Number.isFinite(Date.parse(task.nextRunAt)) || [
5636
+ task.createdAt,
5637
+ task.updatedAt,
5638
+ task.lastRunAt,
5639
+ task.nextRunAt
5640
+ ].some((value) => typeof value !== "string" || value.length > 128)) throw new TypeError("Unconfirmed scheduled task.");
5641
+ const config = JSON.stringify(task.config);
5642
+ if (config === void 0 || typeof task.config !== "object" || task.config === null || Array.isArray(task.config)) throw new TypeError("Invalid task config.");
5643
+ const configTruncated = new TextEncoder().encode(config).byteLength > 2e3;
5644
+ return {
5645
+ id: task.id,
5646
+ notebookId,
5647
+ sceneType: task.sceneType,
5648
+ schedule: task.schedule,
5649
+ enabled: task.enabled,
5650
+ nextRunAt: task.nextRunAt,
5651
+ lastRunAt: task.lastRunAt,
5652
+ createdAt: task.createdAt,
5653
+ updatedAt: task.updatedAt,
5654
+ config: configTruncated ? {} : JSON.parse(config),
5655
+ configTruncated
5656
+ };
5657
+ }
5658
+ async function runScheduledTask(client, tool, rawInput, invocation) {
5659
+ const input = rawInput;
5660
+ if (tool === "qmind.create_scheduled_task" && !client.createScheduledTask || tool === "qmind.update_scheduled_task" && (!client.updateScheduledTask || !client.listScheduledTasks) || tool === "qmind.delete_scheduled_task" && (!client.deleteScheduledTask || !client.listScheduledTasks) || tool === "qmind.list_scheduled_tasks" && !client.listScheduledTasks) return failure$1(invocation.operationId, "capability_unavailable", "This client does not support this scheduled-task operation.");
5661
+ let mutationStarted = false;
5662
+ try {
5663
+ const options = callOptions(invocation);
5664
+ invocation.signal?.throwIfAborted();
5665
+ if (tool === "qmind.create_scheduled_task") {
5666
+ const create = rawInput;
5667
+ mutationStarted = true;
5668
+ const task = await client.createScheduledTask(input.notebookId, {
5669
+ sceneType: create.sceneType,
5670
+ schedule: create.schedule,
5671
+ config: {}
5672
+ }, options);
5673
+ invocation.signal?.throwIfAborted();
5674
+ const data = taskData(task, input.notebookId);
5675
+ if (data.sceneType !== create.sceneType || data.schedule !== create.schedule || !data.enabled) throw new TypeError("Unconfirmed creation.");
5676
+ return {
5677
+ ok: true,
5678
+ data,
5679
+ meta: { operationId: invocation.operationId }
5680
+ };
5681
+ }
5682
+ const { tasks } = await client.listScheduledTasks(input.notebookId, options);
5683
+ invocation.signal?.throwIfAborted();
5684
+ if (new Set(tasks.map((task) => task.id)).size !== tasks.length || tasks.some((task) => task.notebookId !== input.notebookId)) throw new TypeError("Invalid task list.");
5685
+ if (tool === "qmind.list_scheduled_tasks") {
5686
+ const query = rawInput;
5687
+ const filtered = tasks.filter((task) => (query.taskId === void 0 || task.id === query.taskId) && (query.sceneType === void 0 || task.sceneType === query.sceneType) && (query.enabled === void 0 || task.enabled === query.enabled)).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
5688
+ const offset = (query.page - 1) * query.pageSize;
5689
+ return {
5690
+ ok: true,
5691
+ data: {
5692
+ tasks: filtered.slice(offset, offset + query.pageSize).map((task) => taskData(task, input.notebookId)),
5693
+ page: query.page,
5694
+ pageSize: query.pageSize,
5695
+ totalSize: filtered.length,
5696
+ hasMore: offset + query.pageSize < filtered.length
5697
+ },
5698
+ meta: { operationId: invocation.operationId }
5699
+ };
5700
+ }
5701
+ const current = tasks.find((task) => task.id === input.taskId);
5702
+ if (!current) return failure$1(invocation.operationId, "not_found", "The scheduled task was not found in this notebook.");
5703
+ taskData(current, input.notebookId);
5704
+ invocation.signal?.throwIfAborted();
5705
+ if (tool === "qmind.delete_scheduled_task") {
5706
+ mutationStarted = true;
5707
+ const response = await client.deleteScheduledTask(input.notebookId, input.taskId, options);
5708
+ invocation.signal?.throwIfAborted();
5709
+ if (response !== void 0) throw new TypeError("Unconfirmed deletion.");
5710
+ return {
5711
+ ok: true,
5712
+ data: {
5713
+ notebookId: input.notebookId,
5714
+ taskId: input.taskId,
5715
+ deleted: true
5716
+ },
5717
+ meta: { operationId: invocation.operationId }
5718
+ };
5719
+ }
5720
+ const update = rawInput;
5721
+ const patch = {
5722
+ ...update.schedule === void 0 ? {} : { schedule: update.schedule },
5723
+ ...update.enabled === void 0 ? {} : { enabled: update.enabled }
5724
+ };
5725
+ mutationStarted = true;
5726
+ const task = await client.updateScheduledTask(input.notebookId, input.taskId, patch, options);
5727
+ invocation.signal?.throwIfAborted();
5728
+ const data = taskData(task, input.notebookId);
5729
+ if (data.id !== input.taskId || data.sceneType !== current.sceneType || update.schedule !== void 0 && data.schedule !== update.schedule || update.enabled !== void 0 && data.enabled !== update.enabled) throw new TypeError("Unconfirmed update.");
5730
+ return {
5731
+ ok: true,
5732
+ data,
5733
+ meta: { operationId: invocation.operationId }
5734
+ };
5735
+ } catch (error) {
5736
+ const policy = qmindOrganizationDisabledError(error);
5737
+ if (policy) return {
5738
+ ok: false,
5739
+ error: policy,
5740
+ meta: { operationId: invocation.operationId }
5741
+ };
5742
+ const mapped = errorCode(error, mutationStarted);
5743
+ const code = mutationStarted && mapped === "internal" ? "outcome_unknown" : mapped;
5744
+ return failure$1(invocation.operationId, code, code === "outcome_unknown" ? "The scheduled-task operation did not return a confirmed result. Inspect current tasks before another call; never retry automatically." : "The scheduled-task operation failed.");
5745
+ }
5746
+ }
5747
+ //#endregion
5748
+ //#region ../agent-core/src/source-organization.ts
5749
+ var SourceOrganizationPreflightError = class extends Error {
5750
+ agentCode;
5751
+ constructor(agentCode, message) {
5752
+ super(message);
5753
+ this.agentCode = agentCode;
5754
+ }
5755
+ };
5756
+ function reject(code, message) {
5757
+ throw new SourceOrganizationPreflightError(code, message);
5758
+ }
5759
+ function segment(value) {
5760
+ if (!value || value.trim() !== value || value === "." || value === ".." || /[\\/\0]/.test(value)) reject("invalid_input", "The source path must contain valid single path segments.");
5761
+ return value;
5762
+ }
5763
+ function directoryPath(source) {
5764
+ const path = source.path;
5765
+ if (!path.startsWith("/") || path === "/") reject("invalid_input", "The target directory has no valid absolute path.");
5766
+ path.slice(1).split("/").forEach(segment);
5767
+ return path;
5768
+ }
5769
+ function reader(client, notebookId, options) {
5770
+ const cache = /* @__PURE__ */ new Map();
5771
+ return async (id) => {
5772
+ options.signal?.throwIfAborted();
5773
+ const cached = cache.get(id);
5774
+ if (cached) return cached;
5775
+ const source = await client.getSource(notebookId, id, options);
5776
+ if (source.id !== id || source.notebookId !== notebookId) reject("invalid_input", "The source does not match the requested Notebook and ID.");
5777
+ cache.set(id, source);
5778
+ return source;
5779
+ };
5780
+ }
5781
+ async function targetPath(read, id) {
5782
+ if (id === void 0) return "";
5783
+ const target = await read(id);
5784
+ if (!target.isDir) reject("invalid_input", "The target must be a directory.");
5785
+ if (!qmindSourceOperationPolicy(target).addChildren || isQMindExternalSource(target) || isQMindEmailFolder(target)) reject("permission_denied", "This directory cannot accept children.");
5786
+ if (target.status !== "ready") reject("source_not_ready", "The target directory is not ready.");
5787
+ return directoryPath(target);
5788
+ }
5789
+ async function prepareDirectoryCreation(client, input, options) {
5790
+ const parentPath = await targetPath(reader(client, input.notebookId, options), input.parentSourceId);
5791
+ return {
5792
+ title: input.title,
5793
+ path: `${parentPath}/${segment(input.title)}`,
5794
+ ...input.parentSourceId === void 0 ? {} : { parentSourceId: input.parentSourceId }
5795
+ };
5796
+ }
5797
+ /** Snapshot preflight only: the existing endpoint has no revision CAS or atomic path derivation. */
5798
+ async function prepareSourceMove(client, input, options) {
5799
+ const read = reader(client, input.notebookId, options);
5800
+ const source = await read(input.sourceId);
5801
+ if (source.isDir) reject("invalid_input", "Only leaf documents can be moved.");
5802
+ if (!qmindSourceOperationPolicy(source).move || isQMindExternalSource(source)) reject("permission_denied", "This managed source cannot be moved.");
5803
+ if (source.status === "failed") reject("source_failed", "The source failed during ingestion.");
5804
+ if (source.status !== "ready" && source.status !== "unsupported") reject("source_not_ready", "The source is not ready to move.");
5805
+ const parent = source.parentSourceId ? await read(source.parentSourceId) : void 0;
5806
+ if (parent && isQMindEmailFolder(parent) || isQMindEmailAggregateMember(source, parent ? [parent] : [])) reject("permission_denied", "Email aggregate members cannot be moved.");
5807
+ options.signal?.throwIfAborted();
5808
+ const children = await client.listSources(input.notebookId, {
5809
+ view: "children",
5810
+ parentSourceId: source.id,
5811
+ page: 1,
5812
+ pageSize: 1
5813
+ }, options);
5814
+ if (source.hasChildren === true || (source.childrenCount ?? 0) > 0 || children.sources.length > 0 || (children.totalSize ?? 0) > 0) reject("invalid_input", "Documents with children cannot be moved.");
5815
+ const parentSourceId = input.targetParentSourceId ?? "";
5816
+ const patch = {
5817
+ parentSourceId,
5818
+ path: `${await targetPath(read, parentSourceId || void 0)}/${segment(source.path.split("/").filter(Boolean).at(-1) ?? source.title)}`
5819
+ };
5820
+ const noop = source.parentSourceId === parentSourceId;
5821
+ if (noop && source.path !== patch.path) reject("invalid_input", "The source is already in this parent but its path differs. Inspect it before changing position.");
5822
+ return {
5823
+ source,
5824
+ patch,
5825
+ noop
5826
+ };
5827
+ }
5828
+ //#endregion
5829
+ //#region ../agent-core/src/notebook-discovery.ts
5830
+ const upstreamPageSize = 50;
5831
+ const maxPagesPerCall = 4;
5832
+ const cursorSchema = z.object({
5833
+ version: z.literal(1),
5834
+ relationship: z.enum([
5835
+ "owned",
5836
+ "shared",
5837
+ "all"
5838
+ ]),
5839
+ collection: z.enum(["owned", "shared"]),
5840
+ page: z.number().int().min(1).max(1e6),
5841
+ offset: z.number().int().min(0).max(49)
5842
+ }).strict();
5843
+ function invalidCursor() {
5844
+ throw Object.assign(/* @__PURE__ */ new Error("invalid notebook cursor"), { code: "INVALID_ARGUMENT" });
5845
+ }
5846
+ function initialPosition(input) {
5847
+ const relationship = input.relationship ?? "owned";
5848
+ if (input.cursor === void 0) return {
5849
+ version: 1,
5850
+ relationship,
5851
+ collection: relationship === "shared" ? "shared" : "owned",
5852
+ page: 1,
5853
+ offset: 0
5854
+ };
5855
+ try {
5856
+ if (!/^[A-Za-z0-9_-]+$/.test(input.cursor)) return invalidCursor();
5857
+ const position = cursorSchema.parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")));
5858
+ if (position.relationship !== relationship || relationship !== "all" && position.collection !== relationship) return invalidCursor();
5859
+ return position;
5860
+ } catch {
5861
+ return invalidCursor();
5862
+ }
5863
+ }
5864
+ /** 动态目录先遍历 owned,再遍历 shared;游标只记录位置,每页重新经过 ACL 与宿主过滤。 */
5865
+ async function discoverNotebooks(client, input, options, includes) {
5866
+ let position = initialPosition(input);
5867
+ if (position.relationship !== "owned" && client.listSharedNotebooks === void 0) throw Object.assign(/* @__PURE__ */ new Error("shared notebook listing is unavailable"), { code: "UNSUPPORTED_OPERATION" });
5868
+ const notebooks = [];
5869
+ const seen = /* @__PURE__ */ new Set();
5870
+ for (let requests = 0; position && requests < maxPagesPerCall && notebooks.length < input.pageSize; requests += 1) {
5871
+ options.signal?.throwIfAborted();
5872
+ const collection = position.collection;
5873
+ const page = position.page;
5874
+ const offset = position.offset;
5875
+ const relationship = position.relationship;
5876
+ const pagination = {
5877
+ page,
5878
+ pageSize: upstreamPageSize,
5879
+ retrievalEligibleOnly: true
5880
+ };
5881
+ const response = collection === "owned" ? await client.listNotebooks(pagination, options) : await client.listSharedNotebooks(pagination, options);
5882
+ options.signal?.throwIfAborted();
5883
+ const items = response.notebooks.map((item) => "notebook" in item ? item.notebook : item);
5884
+ if (items.length > upstreamPageSize || items.length > 0 && (response.currentPage !== void 0 && response.currentPage !== page || response.pageSize !== void 0 && response.pageSize !== upstreamPageSize)) throw Object.assign(/* @__PURE__ */ new Error("invalid notebook page"), { code: "REMOTE_ERROR" });
5885
+ let index = offset;
5886
+ for (; index < items.length && notebooks.length < input.pageSize; index += 1) {
5887
+ const notebook = items[index];
5888
+ if (!notebook.id || typeof notebook.id !== "string") throw Object.assign(/* @__PURE__ */ new Error("invalid notebook entry"), { code: "REMOTE_ERROR" });
5889
+ if (!seen.has(notebook.id) && includes(notebook.id)) notebooks.push({
5890
+ notebook,
5891
+ relationship: collection
5892
+ });
5893
+ seen.add(notebook.id);
5894
+ }
5895
+ if (index < items.length) position = {
5896
+ ...position,
5897
+ offset: index
5898
+ };
5899
+ else if (items.length === upstreamPageSize) position = {
5900
+ ...position,
5901
+ page: page + 1,
5902
+ offset: 0
5903
+ };
5904
+ else position = collection === "owned" && relationship === "all" ? {
5905
+ ...position,
5906
+ collection: "shared",
5907
+ page: 1,
5908
+ offset: 0
5909
+ } : void 0;
5910
+ }
5911
+ return {
5912
+ notebooks,
5913
+ hasMore: position !== void 0,
5914
+ ...position === void 0 ? {} : { nextCursor: Buffer.from(JSON.stringify(position)).toString("base64url") }
5915
+ };
5916
+ }
5917
+ //#endregion
5918
+ //#region ../agent-core/src/source-deletion.ts
5919
+ /** 仅绑定删除范围与展示身份;正文或索引状态变化不改变批准的对象。 */
5920
+ function sourceDeletionTarget(source) {
5921
+ return {
5922
+ sourceId: source.id,
5923
+ title: source.title,
5924
+ scope: source.isDir ? "subtree" : "source",
5925
+ revision: createHash("sha256").update(canonicalize({
5926
+ id: source.id,
5927
+ notebookId: source.notebookId,
5928
+ title: source.title,
5929
+ parentSourceId: source.parentSourceId,
5930
+ isDir: source.isDir,
5931
+ sourceType: source.sourceType,
5932
+ externalBinding: source.externalBinding ?? null
5933
+ })).digest("hex")
5934
+ };
5935
+ }
5936
+ /** 整批预检完成后才能提交;不替换邮件正文、不重复删除父子目标。 */
5937
+ async function prepareSourceDeletion(client, input, invocation) {
5938
+ const cache = /* @__PURE__ */ new Map();
5939
+ const selected = new Set(input.sourceIds);
5940
+ const read = async (id) => {
5941
+ invocation.signal?.throwIfAborted();
5942
+ const cached = cache.get(id);
5943
+ if (cached) return cached;
5944
+ const source = await client.getSource(input.notebookId, id, {
5945
+ signal: invocation.signal,
5946
+ ...invocation.token === void 0 ? {} : { authorization: invocation.token }
5947
+ });
5948
+ if (source.id !== id || source.notebookId !== input.notebookId) throw Object.assign(/* @__PURE__ */ new Error("Source identity changed."), { code: "INVALID_ARGUMENT" });
5949
+ cache.set(id, source);
5950
+ return source;
5951
+ };
5952
+ const targets = [];
5953
+ for (const id of input.sourceIds) {
5954
+ const source = await read(id);
5955
+ if (!qmindSourceOperationPolicy(source).delete) throw Object.assign(/* @__PURE__ */ new Error("This managed source cannot be deleted."), { code: "FORBIDDEN" });
5956
+ const family = [source];
5957
+ const seen = /* @__PURE__ */ new Set([id]);
5958
+ let parentId = source.parentSourceId;
5959
+ while (parentId) {
5960
+ if (selected.has(parentId) || seen.has(parentId) || seen.size > 100) throw Object.assign(/* @__PURE__ */ new Error("Overlapping or invalid source ancestry."), { code: "INVALID_ARGUMENT" });
5961
+ seen.add(parentId);
5962
+ const parent = await read(parentId);
5963
+ family.push(parent);
5964
+ parentId = parent.parentSourceId;
5965
+ }
5966
+ if (qmindEmailDeleteTarget(source, family).id !== id) throw Object.assign(/* @__PURE__ */ new Error("Select the email folder explicitly."), { code: "INVALID_ARGUMENT" });
5967
+ targets.push(sourceDeletionTarget(source));
5968
+ }
5969
+ return targets;
5970
+ }
5971
+ //#endregion
5972
+ //#region ../agent-core/src/core.ts
5973
+ const sourceStatus = /* @__PURE__ */ new Set([
5974
+ "pending",
5975
+ "processing",
5976
+ "ready",
5977
+ "unsupported",
5978
+ "failed"
5979
+ ]);
5980
+ /**
5981
+ * Snapshots and validates host policy at the Core boundary. Invocation context is not model input,
5982
+ * but it still crosses an adapter seam and must fail closed when malformed.
5983
+ */
5984
+ function scopedNotebookIds(invocation) {
5985
+ if (invocation.notebookScope === void 0) return void 0;
5986
+ const values = invocation.notebookScope.allowedNotebookIds;
5987
+ if (!Array.isArray(values)) throw new TypeError("The Agent Notebook scope is invalid.");
5988
+ const seen = /* @__PURE__ */ new Set();
5989
+ const snapshot = [];
5990
+ for (const value of values) {
5991
+ if (typeof value !== "string" || value.length === 0 || value.length > 512 || value.trim() !== value || seen.has(value)) throw new TypeError("The Agent Notebook scope is invalid.");
5992
+ seen.add(value);
5993
+ snapshot.push(value);
5994
+ }
5995
+ const preferred = invocation.notebookScope.preferredNotebookIds;
5996
+ if (preferred !== void 0 && (!Array.isArray(preferred) || new Set(preferred).size !== preferred.length || preferred.some((id) => !seen.has(id)))) throw new TypeError("The preferred Notebook scope is invalid.");
5997
+ return Object.freeze(snapshot);
5998
+ }
5999
+ function targetedNotebookIds(toolId, input, invocation) {
6000
+ if (toolId === "qmind.list_notebooks" || toolId === "qmind.create_notebook") return void 0;
6001
+ if (toolId === "qmind.retrieve") {
6002
+ const value = input;
6003
+ return value.targets?.map((target) => target.notebookId) ?? (value.notebookId === void 0 ? invocation.defaultNotebookIds : [value.notebookId]);
6004
+ }
6005
+ return [input.notebookId];
6006
+ }
6007
+ function enforceNotebookScope(toolId, input, invocation, allowedNotebookIds) {
6008
+ if (toolId === "qmind.create_notebook" && (allowedNotebookIds !== void 0 || invocation.notebookPolicy !== void 0)) return failure$1(invocation.operationId, "permission_denied", "Notebook creation requires an account context without a host Notebook scope or policy.");
6009
+ const targets = targetedNotebookIds(toolId, input, invocation);
6010
+ if (targets === void 0) return void 0;
6011
+ const allowed = allowedNotebookIds === void 0 ? void 0 : new Set(allowedNotebookIds);
6012
+ if (targets.every((notebookId) => (allowed === void 0 || allowed.has(notebookId)) && notebookSelection(invocation, notebookId) !== "excluded")) return void 0;
6013
+ return failure$1(invocation.operationId, "permission_denied", "The notebook is outside the current Agent Notebook scope.");
6014
+ }
6015
+ function notebookSelection(invocation, notebookId) {
6016
+ if (invocation.notebookPolicy === void 0) return invocation.notebookScope?.preferredNotebookIds?.includes(notebookId) ? "preferred" : "allowed";
6017
+ const selection = invocation.notebookPolicy.selectNotebook(notebookId);
6018
+ if (![
6019
+ "excluded",
6020
+ "allowed",
6021
+ "preferred"
6022
+ ].includes(selection)) throw new TypeError("Invalid Notebook policy result.");
6023
+ return selection;
6024
+ }
6025
+ function notebookData(notebook, invocation, relationship) {
6026
+ const updatedAt = notebook.updatedAt ?? void 0;
6027
+ return {
6028
+ description: notebook.description,
6029
+ preferred: notebookSelection(invocation, notebook.id) === "preferred",
6030
+ ...relationship === void 0 ? {} : { relationship },
6031
+ id: notebook.id,
6032
+ materialCount: notebook.materialCount,
6033
+ ...notebook.overview?.summary ? { summary: notebook.overview.summary } : {},
6034
+ sourceCount: notebook.sourceCount,
6035
+ status: notebook.status,
6036
+ title: notebook.title,
6037
+ ...notebook.overview?.topics ? { topics: notebook.overview.topics } : {},
6038
+ ...updatedAt === void 0 ? {} : { updatedAt }
6039
+ };
6040
+ }
6041
+ function normalizedSourceStatus(value) {
6042
+ const normalized = value.trim().toLowerCase();
6043
+ if (!sourceStatus.has(normalized)) throw new TypeError("QMind returned an unsupported Source ingestion state.");
6044
+ return normalized;
6045
+ }
6046
+ function sourceData(source) {
6047
+ const status = normalizedSourceStatus(source.status);
6048
+ const createdAt = source.createdAt ?? void 0;
6049
+ const updatedAt = source.updatedAt ?? void 0;
6050
+ return {
6051
+ ...createdAt === void 0 ? {} : { createdAt },
6052
+ ...status === "failed" ? { errorCode: "source_failed" } : {},
6053
+ ...status === "unsupported" ? { errorCode: "source_unsupported" } : {},
6054
+ id: source.id,
6055
+ isDir: source.isDir,
6056
+ notebookId: source.notebookId,
6057
+ ...source.parentSourceId.length === 0 ? {} : { parentSourceId: source.parentSourceId },
6058
+ ...source.path.length === 0 ? {} : { path: source.path },
6059
+ sourceType: source.sourceType,
6060
+ status,
6061
+ title: source.title,
6062
+ ...updatedAt === void 0 ? {} : { updatedAt }
6063
+ };
6064
+ }
6065
+ function abortedCode(signal) {
6066
+ if (signal?.aborted !== true) return void 0;
6067
+ return signal.reason?.name === "TimeoutError" ? "timeout" : "cancelled";
6068
+ }
6069
+ function chunkData(chunk) {
6070
+ const originUrl = chunk.originUrl ?? void 0;
6071
+ return {
6072
+ notebookId: chunk.notebookId,
6073
+ notebookTitle: chunk.notebookTitle,
6074
+ chunkId: chunk.chunkId,
6075
+ chunkIndex: chunk.chunkIndex,
6076
+ content: chunk.content,
6077
+ ...originUrl === void 0 || originUrl.length === 0 ? {} : { originUrl },
6078
+ score: chunk.score,
6079
+ sourceId: chunk.sourceId,
6080
+ sourceTitle: chunk.sourceTitle,
6081
+ tokenCount: chunk.tokenCount
6082
+ };
6083
+ }
6084
+ function chunkPromptContext(chunks) {
6085
+ return chunks.map((chunk) => `[Notebook: ${chunk.notebookTitle} | NotebookID: ${chunk.notebookId} | Source: ${chunk.sourceTitle} | Chunk: ${chunk.chunkIndex} | SourceID: ${chunk.sourceId} | ChunkID: ${chunk.chunkId} | Score: ${chunk.score.toFixed(3)}]\n${chunk.content}`).join("\n\n---\n\n");
6086
+ }
6087
+ async function retrieve(client, input, invocation) {
6088
+ const targets = input.targets ?? (input.notebookId === void 0 ? invocation.defaultNotebookIds?.map((notebookId) => ({ notebookId })) : [{
6089
+ notebookId: input.notebookId,
6090
+ ...input.sourceIds === void 0 ? {} : { sourceIds: input.sourceIds }
6091
+ }]);
6092
+ if (targets === void 0 || targets.length === 0 || targets.length > 5) return failure$1(invocation.operationId, "selection_required", "Use list_notebooks overview to select one to five relevant notebooks.");
6093
+ const result = await client.retrieveNotebooks({
6094
+ targets: targets.map(({ notebookId, sourceIds }) => ({
6095
+ notebookId,
6096
+ ...sourceIds === void 0 ? {} : { sourceIds },
6097
+ ...notebookSelection(invocation, notebookId) === "preferred" ? { preference: "preferred" } : {}
6098
+ })),
6099
+ maxResults: input.maxResults,
6100
+ query: input.query,
6101
+ ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold },
6102
+ ...input.topK === void 0 ? {} : { topK: input.topK }
6103
+ }, callOptions(invocation));
6104
+ const bounded = result.chunks.slice(0, input.maxResults);
6105
+ return {
6106
+ data: {
6107
+ chunks: bounded.map(chunkData),
6108
+ promptContext: chunkPromptContext(bounded),
6109
+ reranked: result.reranked,
6110
+ total: result.total
6111
+ },
6112
+ meta: { operationId: invocation.operationId },
6113
+ ok: true
6114
+ };
6115
+ }
6116
+ async function listNotebooks(client, input, invocation, allowedNotebookIds) {
6117
+ if (invocation.notebookPolicy !== void 0 || invocation.defaultNotebookRelationship !== void 0 || input.relationship !== void 0 || input.cursor !== void 0) {
6118
+ if (input.page !== 1) return failure$1(invocation.operationId, "invalid_input", "Use nextCursor to continue notebook discovery instead of page.");
6119
+ const allowed = allowedNotebookIds === void 0 ? void 0 : new Set(allowedNotebookIds);
6120
+ const relationship = input.relationship ?? invocation.defaultNotebookRelationship ?? "owned";
6121
+ if (![
6122
+ "owned",
6123
+ "shared",
6124
+ "all"
6125
+ ].includes(relationship)) throw new TypeError("Invalid default Notebook relationship.");
6126
+ const result = allowed?.size === 0 ? {
6127
+ notebooks: [],
6128
+ hasMore: false
6129
+ } : await discoverNotebooks(client, {
6130
+ ...input,
6131
+ relationship
6132
+ }, callOptions(invocation), (id) => (allowed === void 0 || allowed.has(id)) && notebookSelection(invocation, id) !== "excluded");
6133
+ return {
6134
+ ok: true,
6135
+ data: {
6136
+ ...result,
6137
+ notebooks: result.notebooks.map(({ notebook, relationship }) => notebookData(notebook, invocation, relationship)),
6138
+ pageSize: input.pageSize,
6139
+ retrievalSelection: {
6140
+ maxTargets: 5,
6141
+ overviewSelectionRequired: true
6142
+ }
6143
+ },
6144
+ meta: { operationId: invocation.operationId }
6145
+ };
6146
+ }
6147
+ if (allowedNotebookIds !== void 0) {
6148
+ const start = (input.page - 1) * input.pageSize;
6149
+ return {
6150
+ ok: true,
6151
+ data: {
6152
+ notebooks: (await Promise.all(allowedNotebookIds.slice(start, start + input.pageSize).map((id) => client.getNotebook(id, callOptions(invocation))))).map((notebook) => notebookData(notebook, invocation)),
6153
+ page: input.page,
6154
+ pageSize: input.pageSize,
6155
+ totalSize: allowedNotebookIds.length,
6156
+ retrievalSelection: {
6157
+ maxTargets: 5,
6158
+ overviewSelectionRequired: allowedNotebookIds.length >= 5
6159
+ }
6160
+ },
6161
+ meta: { operationId: invocation.operationId }
6162
+ };
6163
+ }
6164
+ const result = await client.listNotebooks({
6165
+ page: input.page,
6166
+ pageSize: input.pageSize
6167
+ }, callOptions(invocation));
6168
+ return {
6169
+ data: {
6170
+ notebooks: result.notebooks.map((notebook) => notebookData(notebook, invocation, "owned")),
6171
+ page: result.currentPage ?? input.page,
6172
+ pageSize: result.pageSize ?? input.pageSize,
6173
+ totalSize: result.totalSize,
6174
+ retrievalSelection: {
6175
+ maxTargets: 5,
6176
+ overviewSelectionRequired: result.totalSize >= 5
6177
+ }
6178
+ },
6179
+ meta: { operationId: invocation.operationId },
6180
+ ok: true
6181
+ };
6182
+ }
6183
+ async function listSources(client, input, invocation) {
6184
+ const result = await client.listSources(input.notebookId, {
6185
+ page: input.page,
6186
+ pageSize: input.pageSize,
6187
+ ...input.parentSourceId === void 0 ? {} : {
6188
+ parentSourceId: input.parentSourceId,
6189
+ view: "children"
6190
+ }
6191
+ }, callOptions(invocation));
6192
+ return {
6193
+ data: {
6194
+ page: result.currentPage ?? input.page,
6195
+ pageSize: result.pageSize ?? input.pageSize,
6196
+ sources: result.sources.map(sourceData),
6197
+ ...result.totalSize === void 0 ? {} : { totalSize: result.totalSize }
6198
+ },
6199
+ meta: { operationId: invocation.operationId },
6200
+ ok: true
6201
+ };
6202
+ }
6203
+ async function getSource(client, input, invocation) {
6204
+ const source = await client.getSource(input.notebookId, input.sourceId, callOptions(invocation));
6205
+ return {
6206
+ data: {
6207
+ ...sourceData(source),
6208
+ deletion: sourceDeletionTarget(source)
6209
+ },
6210
+ meta: { operationId: invocation.operationId },
6211
+ ok: true
6212
+ };
6213
+ }
6214
+ async function readSource(client, input, invocation) {
6215
+ const status = normalizedSourceStatus((await client.getSource(input.notebookId, input.sourceId, callOptions(invocation))).status);
6216
+ if (status === "pending" || status === "processing") return failure$1(invocation.operationId, "source_not_ready", "The source is not ready to read.");
6217
+ if (status === "unsupported") return failure$1(invocation.operationId, "source_unsupported", "The source format is unsupported.");
6218
+ if (status === "failed") return failure$1(invocation.operationId, "source_failed", "The source failed during ingestion.");
6219
+ const result = await client.getSourceContent(input.notebookId, input.sourceId, callOptions(invocation));
6220
+ const content = result.content.slice(input.offset, input.offset + input.maxChars);
6221
+ const nextOffset = input.offset + content.length;
6222
+ const truncated = nextOffset < result.content.length;
6223
+ return {
6224
+ data: {
6225
+ content,
6226
+ contentType: result.contentType,
6227
+ ...truncated ? { nextOffset } : {},
6228
+ sourceId: input.sourceId,
6229
+ truncated
6230
+ },
6231
+ meta: { operationId: invocation.operationId },
6232
+ ok: true
6233
+ };
6234
+ }
6235
+ async function addSource(client, input, invocation) {
6236
+ const cancelledBeforeMutation = abortedCode(invocation.signal);
6237
+ if (cancelledBeforeMutation !== void 0) return failure$1(invocation.operationId, cancelledBeforeMutation, cancelledBeforeMutation === "timeout" ? "The source mutation timed out before it was sent." : "The source mutation was cancelled before it was sent.");
6238
+ try {
6239
+ if (input.source.kind === "url") {
6240
+ const imported = (await client.importWebLinks(input.notebookId, { urls: [input.source.url] }, callOptions(invocation)))[0];
6241
+ if (imported?.source === void 0) {
6242
+ if (imported?.error !== void 0) return failure$1(invocation.operationId, "upstream_unavailable", "QMind could not import the URL source.");
6243
+ return failure$1(invocation.operationId, "outcome_unknown", "The URL source result could not be confirmed.");
6244
+ }
6245
+ return {
6246
+ data: sourceData(imported.source),
6247
+ meta: { operationId: invocation.operationId },
6248
+ ok: true
6249
+ };
6250
+ }
6251
+ const binary = invocation.fileSource;
6252
+ if (binary === void 0) return failure$1(invocation.operationId, "internal", "The local file source was not prepared.");
6253
+ const title = input.source.title;
6254
+ return {
6255
+ data: sourceData(await client.uploadSource(input.notebookId, binary, title === void 0 ? {} : { title }, callOptions(invocation))),
6256
+ meta: { operationId: invocation.operationId },
6257
+ ok: true
6258
+ };
6259
+ } catch (error) {
6260
+ const policyError = qmindOrganizationDisabledError(error);
6261
+ if (policyError) return {
6262
+ ok: false,
6263
+ error: policyError,
6264
+ meta: { operationId: invocation.operationId }
6265
+ };
6266
+ const code = errorCode(error, true);
6267
+ return failure$1(invocation.operationId, code, code === "outcome_unknown" ? "The source mutation outcome is unknown." : "QMind could not add the source.");
6268
+ }
6269
+ }
6270
+ async function deleteSource(client, input, invocation) {
6271
+ if (client.batchDeleteSources === void 0) return failure$1(invocation.operationId, "capability_unavailable", "This client does not support source deletion.");
6272
+ const targets = await prepareSourceDeletion(client, input, invocation);
6273
+ if (invocation.approvedDeletionTargets !== void 0 && (targets.length !== invocation.approvedDeletionTargets.length || targets.some((target, index) => {
6274
+ const approved = invocation.approvedDeletionTargets?.[index];
6275
+ return !approved || target.sourceId !== approved.sourceId || target.title !== approved.title || target.scope !== approved.scope || target.revision !== approved.revision;
6276
+ }))) return failure$1(invocation.operationId, "permission_denied", "Deletion targets changed. Request fresh approval.");
6277
+ invocation.signal?.throwIfAborted();
6278
+ try {
6279
+ const result = await client.batchDeleteSources(input.notebookId, input.sourceIds, callOptions(invocation));
6280
+ if (!Number.isInteger(result.successCount) || !Number.isInteger(result.failureCount) || result.successCount < 0 || result.failureCount < 0 || result.successCount + result.failureCount !== input.sourceIds.length) return failure$1(invocation.operationId, "outcome_unknown", "The batch deletion result could not be confirmed.");
6281
+ if (result.successCount === 0) return {
6282
+ ok: false,
6283
+ error: {
6284
+ code: "source_deletion_failed",
6285
+ message: "No source was deleted.",
6286
+ retryable: false,
6287
+ details: {
6288
+ successCount: result.successCount,
6289
+ failureCount: result.failureCount
6290
+ }
6291
+ },
6292
+ meta: { operationId: invocation.operationId }
6293
+ };
6294
+ return {
6295
+ ok: true,
6296
+ data: {
6297
+ notebookId: input.notebookId,
6298
+ sourceIds: input.sourceIds,
6299
+ successCount: result.successCount,
6300
+ failureCount: result.failureCount
6301
+ },
6302
+ meta: {
6303
+ operationId: invocation.operationId,
6304
+ ...result.failureCount > 0 ? {
6305
+ partial: true,
6306
+ warnings: [{
6307
+ code: "source_deletion_failed",
6308
+ notebookId: input.notebookId
6309
+ }]
6310
+ } : {}
6311
+ }
6312
+ };
6313
+ } catch (error) {
6314
+ const policyError = qmindOrganizationDisabledError(error);
6315
+ if (policyError) return {
6316
+ ok: false,
6317
+ error: policyError,
6318
+ meta: { operationId: invocation.operationId }
6319
+ };
6320
+ const code = errorCode(error, true);
6321
+ return failure$1(invocation.operationId, code === "internal" ? "outcome_unknown" : code, "The batch deletion did not return a confirmed successful result. Reconcile sources before another call.");
6322
+ }
6323
+ }
6324
+ async function organizeSource(client, tool, input, invocation) {
6325
+ if (tool === "qmind.create_directory" && !client.createDirectory || tool === "qmind.move_source" && !client.moveSource) return failure$1(invocation.operationId, "capability_unavailable", "This client does not support this source operation.");
6326
+ let mutationStarted = false;
6327
+ try {
6328
+ const options = callOptions(invocation);
6329
+ invocation.signal?.throwIfAborted();
6330
+ let source;
6331
+ let expectedParent;
6332
+ let expectedPath;
6333
+ if (tool === "qmind.create_directory") {
6334
+ const prepared = await prepareDirectoryCreation(client, input, options);
6335
+ invocation.signal?.throwIfAborted();
6336
+ mutationStarted = true;
6337
+ source = await client.createDirectory(input.notebookId, prepared, options);
6338
+ expectedParent = prepared.parentSourceId ?? "";
6339
+ expectedPath = prepared.path;
6340
+ if (!source.isDir || source.title !== prepared.title || source.status !== "ready") throw new TypeError("Unconfirmed directory result.");
6341
+ } else {
6342
+ const moveInput = input;
6343
+ const prepared = await prepareSourceMove(client, moveInput, options);
6344
+ invocation.signal?.throwIfAborted();
6345
+ if (prepared.noop) return {
6346
+ ok: true,
6347
+ data: sourceData(prepared.source),
6348
+ meta: { operationId: invocation.operationId }
6349
+ };
6350
+ mutationStarted = true;
6351
+ source = await client.moveSource(input.notebookId, moveInput.sourceId, prepared.patch, options);
6352
+ expectedParent = prepared.patch.parentSourceId;
6353
+ expectedPath = prepared.patch.path;
6354
+ if (source.id !== moveInput.sourceId || source.isDir) throw new TypeError("Unconfirmed move result.");
6355
+ }
6356
+ invocation.signal?.throwIfAborted();
6357
+ if (!source.id || source.notebookId !== input.notebookId || source.parentSourceId !== expectedParent || source.path !== expectedPath) throw new TypeError("Unconfirmed source location.");
6358
+ return {
6359
+ ok: true,
6360
+ data: sourceData(source),
6361
+ meta: { operationId: invocation.operationId }
6362
+ };
6363
+ } catch (error) {
6364
+ const policyError = qmindOrganizationDisabledError(error);
6365
+ if (policyError) return {
6366
+ ok: false,
6367
+ error: policyError,
6368
+ meta: { operationId: invocation.operationId }
6369
+ };
6370
+ const code = error instanceof SourceOrganizationPreflightError ? error.agentCode : errorCode(error, mutationStarted);
6371
+ return failure$1(invocation.operationId, mutationStarted && code === "internal" ? "outcome_unknown" : code, mutationStarted ? "The source operation did not return a confirmed result. Inspect the current source location before another call; do not retry automatically." : error instanceof SourceOrganizationPreflightError ? error.message : "The source operation failed before submission.");
6372
+ }
6373
+ }
6374
+ function createQMindAgentCore(client) {
6375
+ if (typeof client !== "object" || client === null) throw new TypeError("client is required");
6376
+ return Object.freeze({ async invoke(toolId, rawInput, invocation) {
6377
+ const parsed = agentToolInputSchemas[toolId].safeParse(rawInput);
6378
+ if (!parsed.success) return failure$1(invocation.operationId, "invalid_input", "The tool input is invalid.");
6379
+ try {
6380
+ if (invocation.notebookPolicy !== void 0 && typeof invocation.notebookPolicy.selectNotebook !== "function") throw new TypeError("Invalid Notebook policy.");
6381
+ const allowedNotebookIds = scopedNotebookIds(invocation);
6382
+ const denied = enforceNotebookScope(toolId, parsed.data, invocation, allowedNotebookIds);
6383
+ if (denied !== void 0) return denied;
6384
+ switch (toolId) {
6385
+ case "qmind.create_notebook":
6386
+ case "qmind.delete_notebook": return await runNotebookMutation(client, toolId, parsed.data, invocation);
6387
+ case "qmind.create_scheduled_task":
6388
+ case "qmind.update_scheduled_task":
6389
+ case "qmind.delete_scheduled_task":
6390
+ case "qmind.list_scheduled_tasks": return await runScheduledTask(client, toolId, parsed.data, invocation);
6391
+ case "qmind.retrieve": return await retrieve(client, parsed.data, invocation);
6392
+ case "qmind.list_notebooks": return await listNotebooks(client, parsed.data, invocation, allowedNotebookIds);
6393
+ case "qmind.list_sources": return await listSources(client, parsed.data, invocation);
6394
+ case "qmind.get_source": return await getSource(client, parsed.data, invocation);
6395
+ case "qmind.read_source": return await readSource(client, parsed.data, invocation);
6396
+ case "qmind.delete_source": return await deleteSource(client, parsed.data, invocation);
6397
+ case "qmind.create_directory":
6398
+ case "qmind.move_source": return await organizeSource(client, toolId, parsed.data, invocation);
6399
+ case "qmind.add_source": return await addSource(client, parsed.data, invocation);
6400
+ }
6401
+ } catch (error) {
6402
+ const policyError = qmindOrganizationDisabledError(error);
6403
+ if (policyError) return {
6404
+ ok: false,
6405
+ error: policyError,
6406
+ meta: { operationId: invocation.operationId }
6407
+ };
6408
+ const code = errorCode(error);
6409
+ return failure$1(invocation.operationId, code, "The QMind operation failed.");
6410
+ }
6411
+ } });
6412
+ }
6413
+ //#endregion
6414
+ //#region ../agent-core/src/operation.ts
6415
+ function failure(operationId, code, message) {
6416
+ return {
6417
+ error: {
6418
+ code,
6419
+ message,
6420
+ retryable: isRetryableAgentError(code)
6421
+ },
6422
+ meta: { operationId },
6423
+ ok: false
6424
+ };
6425
+ }
6426
+ function accept(sink, event) {
6427
+ try {
6428
+ sink.accept(event);
6429
+ } catch {}
6430
+ }
6431
+ function notebookIds(toolId, input, defaultNotebookIds) {
6432
+ if (toolId === "qmind.list_notebooks" || toolId === "qmind.create_notebook") return void 0;
6433
+ if (typeof input !== "object" || input === null) return void 0;
6434
+ if ("targets" in input && Array.isArray(input.targets)) return input.targets.flatMap((target) => typeof target === "object" && target !== null && "notebookId" in target && typeof target.notebookId === "string" ? [target.notebookId] : []);
6435
+ if ("notebookId" in input && typeof input.notebookId === "string") return [input.notebookId];
6436
+ return defaultNotebookIds;
6437
+ }
6438
+ function filePath(toolId, input) {
6439
+ if (toolId !== "qmind.add_source") return void 0;
6440
+ const parsed = agentToolInputSchemas[toolId].safeParse(input);
6441
+ if (!parsed.success || parsed.data.source.kind !== "file") return void 0;
6442
+ return parsed.data.source.filePath;
6443
+ }
6444
+ function abortCode(signal, timedOut) {
6445
+ return timedOut ? "timeout" : signal.aborted ? "cancelled" : "internal";
6446
+ }
6447
+ function fileSourceErrorCode(error) {
6448
+ if (typeof error !== "object" || error === null || !("code" in error)) return "internal";
6449
+ const code = error.code;
6450
+ return code === "INVALID_ARGUMENT" || code === "FILE_TOO_LARGE" ? "invalid_input" : "internal";
6451
+ }
6452
+ function outcomeFor(result) {
6453
+ if (result.ok) return "succeeded";
6454
+ if (result.error.code === "cancelled") return "cancelled";
6455
+ if (result.error.code === "outcome_unknown") return "outcome_unknown";
6456
+ return "failed";
6457
+ }
6458
+ async function runQMindAgentOperation(dependencies, toolId, input, runtimeSignal, perRequestToken, operationContext = {}) {
6459
+ const createId = dependencies.createId ?? randomUUID;
6460
+ const now = dependencies.now ?? Date.now;
6461
+ const operationId = createId();
6462
+ const definition = agentToolDefinitions.find((tool) => tool.id === toolId);
6463
+ if (definition === void 0) return failure(operationId, "internal", "Unknown QMind tool.");
6464
+ const startedAt = now();
6465
+ const started = {
6466
+ eventId: createId(),
6467
+ intent: definition.intent,
6468
+ occurredAt: new Date(startedAt).toISOString(),
6469
+ operationId,
6470
+ toolId,
6471
+ type: "qmind.operation.started"
6472
+ };
6473
+ accept(dependencies.auditSink, started);
6474
+ const deadlineController = new AbortController();
6475
+ let timedOut = false;
6476
+ const timer = setTimeout(() => {
6477
+ timedOut = true;
6478
+ deadlineController.abort(new DOMException("QMind Agent deadline exceeded", "TimeoutError"));
6479
+ }, deadlineFor(toolId, input));
6480
+ timer.unref?.();
6481
+ const signal = runtimeSignal === void 0 ? deadlineController.signal : AbortSignal.any([runtimeSignal, deadlineController.signal]);
6482
+ let result = failure(operationId, "internal", "The QMind operation did not produce a result.");
6483
+ try {
6484
+ if (signal.aborted) {
6485
+ const code = abortCode(signal, timedOut);
6486
+ result = failure(operationId, code, code === "timeout" ? "The QMind operation timed out." : "The QMind operation was cancelled.");
6487
+ } else {
6488
+ let fileSource;
6489
+ const requestedPath = filePath(toolId, input);
6490
+ if (requestedPath !== void 0) try {
6491
+ signal.throwIfAborted();
6492
+ fileSource = await dependencies.createFileSource(requestedPath);
6493
+ signal.throwIfAborted();
6494
+ } catch (error) {
6495
+ const code = signal.aborted ? abortCode(signal, timedOut) : fileSourceErrorCode(error);
6496
+ result = failure(operationId, code, code === "invalid_input" ? "The local file could not be read." : code === "timeout" ? "The QMind operation timed out." : code === "cancelled" ? "The QMind operation was cancelled." : "The local file source failed.");
6497
+ }
6498
+ if (requestedPath === void 0 || fileSource !== void 0) try {
6499
+ result = await dependencies.core.invoke(toolId, input, {
6500
+ ...operationContext.notebookPolicy === void 0 ? {} : { notebookPolicy: operationContext.notebookPolicy },
6501
+ ...operationContext.defaultNotebookRelationship === void 0 ? {} : { defaultNotebookRelationship: operationContext.defaultNotebookRelationship },
6502
+ ...fileSource === void 0 ? {} : { fileSource },
6503
+ ...dependencies.defaultNotebookIds === void 0 ? {} : { defaultNotebookIds: dependencies.defaultNotebookIds },
6504
+ ...operationContext.approvedDeletionTargets === void 0 ? {} : { approvedDeletionTargets: operationContext.approvedDeletionTargets },
6505
+ ...operationContext.notebookScope === void 0 ? {} : { notebookScope: operationContext.notebookScope },
6506
+ operationId,
6507
+ signal,
6508
+ ...perRequestToken === void 0 ? {} : { token: perRequestToken }
6509
+ });
6510
+ if (timedOut && definition.intent === "read" && result.ok === false && result.error.code === "cancelled") result = failure(operationId, "timeout", "The QMind operation timed out.");
6511
+ } catch {
6512
+ result = failure(operationId, "internal", "The QMind operation failed.");
6513
+ }
6514
+ }
6515
+ } finally {
6516
+ clearTimeout(timer);
6517
+ }
6518
+ const finishedAt = now();
6519
+ const resultErrorCode = result.ok === false ? result.error.code : void 0;
6520
+ const partial = result.ok === true ? result.meta.partial : void 0;
6521
+ const warningCodes = result.ok === true && result.meta.warnings !== void 0 ? result.meta.warnings.map((warning) => warning.code) : void 0;
6522
+ const operationNotebookIds = notebookIds(toolId, input, dependencies.defaultNotebookIds);
6523
+ const finished = {
6524
+ durationMs: Math.max(0, finishedAt - startedAt),
6525
+ ...resultErrorCode === void 0 ? {} : { errorCode: resultErrorCode },
6526
+ eventId: createId(),
6527
+ intent: definition.intent,
6528
+ ...operationNotebookIds === void 0 ? {} : { notebookIds: operationNotebookIds },
6529
+ occurredAt: new Date(finishedAt).toISOString(),
6530
+ operationId,
6531
+ outcome: outcomeFor(result),
6532
+ ...partial === true ? { partial: true } : {},
6533
+ toolId,
6534
+ type: "qmind.operation.finished",
6535
+ ...warningCodes === void 0 ? {} : { warningCodes }
6536
+ };
6537
+ accept(dependencies.auditSink, finished);
6538
+ return result;
6539
+ }
6540
+ //#endregion
6541
+ //#region src/canonical-commands.ts
6542
+ /** New CLI workflows use the same validation, deadlines and mutation receipts as MCP. */
6543
+ async function runCanonicalCommand(context, raw, tool, input) {
6544
+ const parsed = agentToolInputSchemas[tool].safeParse(input);
6545
+ if (!parsed.success) {
6546
+ const fields = [...new Set(parsed.error.issues.map((issue) => issue.path.join(".") || "input"))];
6547
+ throw new QMindError("INVALID_ARGUMENT", `Invalid ${tool} arguments: ${fields.join(", ")}`);
6548
+ }
6549
+ const host = await hostFor(context, raw);
6550
+ const result = await runQMindAgentOperation({
6551
+ core: createQMindAgentCore(host.client),
6552
+ createFileSource: (path) => host.createFileSource(path),
6553
+ auditSink: { accept: () => {} }
6554
+ }, tool, parsed.data);
6555
+ render(context, raw, {
6556
+ kind: "json",
6557
+ value: result
6558
+ });
6559
+ if (!result.ok) context.exitCode = result.error.code === "invalid_input" ? 2 : 1;
6560
+ else if (result.meta.partial) context.exitCode = 1;
6561
+ }
6562
+ function scoreThreshold(value) {
6563
+ const result = Number(value);
6564
+ if (!value.trim() || !Number.isFinite(result) || result < 0 || result > 1) throw new QMindError("INVALID_ARGUMENT", "--score-threshold must be between 0 and 1");
6565
+ return result;
6566
+ }
6567
+ function parseTargets(value) {
6568
+ try {
6569
+ return JSON.parse(value);
6570
+ } catch {
6571
+ throw new QMindError("INVALID_ARGUMENT", "--targets must be a JSON array of retrieval targets");
6572
+ }
6573
+ }
6574
+ function enabled(value) {
6575
+ if (value === "true") return true;
6576
+ if (value === "false") return false;
6577
+ throw new QMindError("INVALID_ARGUMENT", "--enabled must be true or false");
6578
+ }
6579
+ function notebookId(raw) {
6580
+ return requiredString(raw.nb, "--nb");
6581
+ }
6582
+ function registerCanonicalCommands(context, program) {
6583
+ 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) => {
6584
+ await runCanonicalCommand(context, raw, "qmind.list_notebooks", {
6585
+ relationship: raw.relationship,
6586
+ cursor: raw.cursor,
6587
+ pageSize: raw.pageSize
6588
+ });
6589
+ });
6590
+ const source = program.commands.find((command) => command.name() === "source");
6591
+ withCommon(source.command("import-url").description("Import one HTTPS page (not an entire site)")).requiredOption("--nb <id>", "notebook ID").requiredOption("--url <url>", "HTTPS URL without embedded credentials").action(async (raw) => {
6592
+ await runCanonicalCommand(context, raw, "qmind.add_source", {
6593
+ notebookId: notebookId(raw),
6594
+ source: {
6595
+ kind: "url",
6596
+ url: raw.url
6597
+ }
6598
+ });
6599
+ });
6600
+ withCommon(source.command("read <source_id>").description("Read a bounded section of parsed source content")).requiredOption("--nb <id>", "notebook ID").option("--offset <number>", "character offset", integer).option("--max-chars <number>", "maximum characters (1..50000; default 20000)", integer).action(async (sourceId, raw) => {
6601
+ await runCanonicalCommand(context, raw, "qmind.read_source", {
6602
+ notebookId: notebookId(raw),
6603
+ sourceId,
6604
+ offset: raw.offset,
6605
+ maxChars: raw.maxChars
6606
+ });
6607
+ });
6608
+ withCommon(source.command("delete-batch <source_ids...>").description("Delete 1..100 sources with confirmed batch counts")).requiredOption("--nb <id>", "notebook ID").option("--force", "skip confirmation of deletion including directory descendants").action(async (sourceIds, raw) => {
6609
+ const input = {
6610
+ notebookId: notebookId(raw),
6611
+ sourceIds
6612
+ };
6613
+ if (!agentToolInputSchemas["qmind.delete_source"].safeParse(input).success) throw new QMindError("INVALID_ARGUMENT", "Provide 1..100 distinct source IDs");
6614
+ if (raw.force !== true && !await context.confirm.confirm(`Delete Sources ${JSON.stringify(sourceIds)} and ALL descendants of selected directories? Type 'y' to proceed: `)) {
6615
+ context.io.stderr("aborted; pass --force to confirm non-interactively\n");
6616
+ context.exitCode = 1;
6617
+ return;
6618
+ }
6619
+ await runCanonicalCommand(context, raw, "qmind.delete_source", input);
6620
+ });
6621
+ const scheduled = program.command("scheduled-task").description("Manage notebook schedule configurations (not task runs)");
6622
+ 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) => {
6623
+ await runCanonicalCommand(context, raw, "qmind.create_scheduled_task", {
6624
+ notebookId: notebookId(raw),
6625
+ sceneType: raw.scene,
6626
+ schedule: raw.schedule
6627
+ });
6628
+ });
6629
+ withCommon(scheduled.command("update <task_id>").description("Change schedule and/or enabled state")).requiredOption("--nb <id>", "notebook ID").option("--schedule <cron>", "Cron with explicit IANA timezone").option("--enabled <boolean>", "true to resume, false to pause", enabled).action(async (taskId, raw) => {
6630
+ await runCanonicalCommand(context, raw, "qmind.update_scheduled_task", {
6631
+ notebookId: notebookId(raw),
6632
+ taskId,
6633
+ schedule: raw.schedule,
6634
+ enabled: raw.enabled
6635
+ });
6636
+ });
6637
+ for (const [name, state] of [["pause", false], ["resume", true]]) withCommon(scheduled.command(`${name} <task_id>`).description(`${name} a schedule configuration`)).requiredOption("--nb <id>", "notebook ID").action(async (taskId, raw) => {
6638
+ await runCanonicalCommand(context, raw, "qmind.update_scheduled_task", {
6639
+ notebookId: notebookId(raw),
6640
+ taskId,
6641
+ enabled: state
6642
+ });
6643
+ });
6644
+ withCommon(scheduled.command("delete <task_id>").description("Delete schedule configuration; dispatched runs are not cancelled")).requiredOption("--nb <id>", "notebook ID").action(async (taskId, raw) => {
6645
+ await runCanonicalCommand(context, raw, "qmind.delete_scheduled_task", {
6646
+ notebookId: notebookId(raw),
6647
+ taskId
6648
+ });
6649
+ });
6650
+ withCommon(scheduled.command("list").description("List and filter notebook schedule configurations")).requiredOption("--nb <id>", "notebook ID").option("--task <id>", "filter by task ID").option("--scene <scene>", "filter by built-in scene").option("--enabled <boolean>", "filter by enabled state", enabled).option("--page <number>", "page number", integer).option("--page-size <number>", "page size (1..20)", integer).action(async (raw) => {
6651
+ await runCanonicalCommand(context, raw, "qmind.list_scheduled_tasks", {
6652
+ notebookId: notebookId(raw),
6653
+ taskId: raw.task,
6654
+ sceneType: raw.scene,
6655
+ enabled: raw.enabled,
6656
+ page: raw.page,
6657
+ pageSize: raw.pageSize
6658
+ });
6659
+ });
6660
+ }
6661
+ //#endregion
6662
+ //#region src/application.ts
6663
+ const distribution = CLI_DISTRIBUTIONS[QMIND_CLI_DISTRIBUTION];
4606
6664
  function registerCoreCommands(context, program) {
4607
6665
  withCommon(program.command("login").description("Authorize via browser and save credentials"), false).option("--client-id <id>", "OAuth App client_id").action(async (raw) => {
4608
6666
  const host = await hostFor(context, raw);
@@ -4616,12 +6674,13 @@ function registerCoreCommands(context, program) {
4616
6674
  });
4617
6675
  const notebook = program.command("notebook").description("Manage notebooks");
4618
6676
  withCommon(notebook.command("create").description("Create a notebook")).option("--title <title>", "notebook title (required)").option("--desc <description>", "notebook description", "").action(async (raw) => {
6677
+ const host = await hostFor(context, raw);
4619
6678
  render(context, raw, {
4620
6679
  kind: "notebook",
4621
- value: await (await hostFor(context, raw)).client.createNotebook({
6680
+ value: await submitCliMutation(async () => host.client.createNotebook({
4622
6681
  description: String(raw.desc ?? ""),
4623
6682
  title: requiredString(raw.title, "--title")
4624
- })
6683
+ }))
4625
6684
  });
4626
6685
  });
4627
6686
  withCommon(notebook.command("list").description("List notebooks")).option("--filter-client <name>", "filter by originating client", "").addOption(new Option("--shared", "list notebooks shared with you").conflicts("filterClient")).option("--page <number>", "page number", integer).option("--page-size <number>", "items per page", integer).action(async (raw) => {
@@ -4649,25 +6708,47 @@ function registerCoreCommands(context, program) {
4649
6708
  value: await (await hostFor(context, raw)).client.getNotebook(notebookId)
4650
6709
  });
4651
6710
  });
4652
- withCommon(notebook.command("delete <notebook_id>").description("Delete a notebook"), false).action(async (notebookId, raw) => {
4653
- await (await hostFor(context, raw)).client.deleteNotebook(notebookId);
4654
- context.io.stdout("deleted\n");
6711
+ withCommon(notebook.command("delete <notebook_id>").description("Delete a notebook")).action(async (notebookId, raw) => {
6712
+ const host = await hostFor(context, raw);
6713
+ await submitCliMutation(() => host.client.deleteNotebook(notebookId));
6714
+ if (raw.format === "json" || raw.format === "ndjson") render(context, raw, {
6715
+ kind: "json",
6716
+ value: {
6717
+ notebookId,
6718
+ deleted: true
6719
+ }
6720
+ });
6721
+ else context.io.stdout("deleted\n");
4655
6722
  });
4656
- 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 5)", collectNotebookIds, []).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) => {
6723
+ 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 5)", 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) => {
4657
6724
  const notebookIds = raw.nb;
4658
6725
  const [notebookId] = notebookIds;
4659
- if (notebookId === void 0) throw new QMindError("INVALID_ARGUMENT", "--nb is required");
6726
+ if (raw.targets === void 0 && notebookId === void 0) throw new QMindError("INVALID_ARGUMENT", "--nb is required");
4660
6727
  if (notebookIds.length > 5) throw new QMindError("INVALID_ARGUMENT", "--nb accepts at most 5 distinct notebook IDs");
4661
6728
  const input = {
4662
6729
  maxResults: numberOption(raw, "maxResults", 0),
4663
6730
  query: requiredString(raw.query || query, "--query or positional query"),
4664
6731
  sourceIds: splitCsv(stringOption(raw, "sources")),
4665
- topK: numberOption(raw, "topK", 0)
6732
+ topK: numberOption(raw, "topK", 0),
6733
+ ...raw.scoreThreshold === void 0 ? {} : { scoreThreshold: Number(raw.scoreThreshold) }
4666
6734
  };
4667
6735
  if (input.maxResults < 0 || input.topK < 0) throw new QMindError("INVALID_ARGUMENT", "--top-k and --max-results must be non-negative");
4668
6736
  if (notebookIds.length > 1 && input.sourceIds.length > 0) throw new QMindError("INVALID_ARGUMENT", "--sources requires a single notebook");
6737
+ if (raw.unified === true || raw.targets !== void 0) {
6738
+ await runCanonicalCommand(context, raw, "qmind.retrieve", {
6739
+ query: input.query,
6740
+ ...raw.targets !== void 0 ? { targets: raw.targets } : notebookIds.length === 1 ? {
6741
+ notebookId,
6742
+ ...input.sourceIds.length ? { sourceIds: input.sourceIds } : {}
6743
+ } : { targets: notebookIds.map((id) => ({ notebookId: id })) },
6744
+ ...input.maxResults === 0 ? {} : { maxResults: input.maxResults },
6745
+ ...input.topK === 0 ? {} : { topK: input.topK },
6746
+ ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold }
6747
+ });
6748
+ return;
6749
+ }
4669
6750
  const host = await hostFor(context, raw);
4670
- if (notebookIds.length === 1) {
6751
+ if (notebookIds.length === 1 && notebookId !== void 0) {
4671
6752
  render(context, raw, {
4672
6753
  kind: "retrieve",
4673
6754
  value: await host.client.retrieve(notebookId, input)
@@ -4680,6 +6761,7 @@ function registerCoreCommands(context, program) {
4680
6761
  query: input.query,
4681
6762
  topK: input.topK,
4682
6763
  maxResults: input.maxResults,
6764
+ ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold },
4683
6765
  targets: notebookIds.map((notebookId) => ({ notebookId }))
4684
6766
  })
4685
6767
  });
@@ -4688,29 +6770,39 @@ function registerCoreCommands(context, program) {
4688
6770
  function registerSourceCommands(context, program) {
4689
6771
  const source = program.command("source").description("Manage notebook sources");
4690
6772
  withCommon(source.command("create").description("Create a source record")).option("--nb <id>", "notebook ID (required)").option("--title <title>", "source title (required)").option("--type <type>", "source type", "").option("--parent <id>", "parent source ID", "").option("--path <path>", "source path", "").option("--is-dir", "create a directory source").option("--status <status>", "source status", "").action(async (raw) => {
6773
+ const host = await hostFor(context, raw);
4691
6774
  render(context, raw, {
4692
6775
  kind: "source",
4693
- value: await (await hostFor(context, raw)).client.createSource(requiredString(raw.nb, "--nb"), {
6776
+ value: await submitCliMutation(async () => host.client.createSource(requiredString(raw.nb, "--nb"), {
4694
6777
  isDir: raw.isDir === true ? true : void 0,
4695
6778
  parentSourceId: String(raw.parent ?? ""),
4696
6779
  path: String(raw.path ?? ""),
4697
6780
  sourceType: String(raw.type ?? ""),
4698
6781
  status: String(raw.status ?? ""),
4699
6782
  title: requiredString(raw.title, "--title")
4700
- })
6783
+ }))
4701
6784
  });
4702
6785
  });
4703
- withCommon(source.command("mkdir").description("Create a directory source")).option("--nb <id>", "notebook ID (required)").option("--title <title>", "folder name (required)").option("--parent <id>", "parent source ID", "").option("--path <path>", "source path", "").action(async (raw) => {
6786
+ withCommon(source.command("mkdir").description("Create a directory source")).option("--nb <id>", "notebook ID (required)").option("--title <title>", "folder name (required)").option("--parent <id>", "parent source ID", "").option("--path <path>", "source path", "").addOption(new Option("--derive-path", "derive path from the actual parent and validate the destination").conflicts("path")).action(async (raw) => {
6787
+ if (raw.derivePath === true) {
6788
+ await runCanonicalCommand(context, raw, "qmind.create_directory", {
6789
+ notebookId: requiredString(raw.nb, "--nb"),
6790
+ title: requiredString(raw.title, "--title"),
6791
+ ...optionalString(raw, "parent") === void 0 ? {} : { parentSourceId: optionalString(raw, "parent") }
6792
+ });
6793
+ return;
6794
+ }
6795
+ const host = await hostFor(context, raw);
4704
6796
  render(context, raw, {
4705
6797
  kind: "source",
4706
- value: await (await hostFor(context, raw)).client.createDirectory(requiredString(raw.nb, "--nb"), {
6798
+ value: await submitCliMutation(async () => host.client.createDirectory(requiredString(raw.nb, "--nb"), {
4707
6799
  parentSourceId: String(raw.parent ?? ""),
4708
6800
  path: String(raw.path ?? ""),
4709
6801
  title: requiredString(raw.title, "--title")
4710
- })
6802
+ }))
4711
6803
  });
4712
6804
  });
4713
- 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").option("--max-pages <number>", "all-pages safety limit", integer, 1e4).action(async (raw) => {
6805
+ 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) => {
4714
6806
  const host = await hostFor(context, raw);
4715
6807
  const notebookId = requiredString(raw.nb, "--nb");
4716
6808
  let value;
@@ -4725,7 +6817,11 @@ function registerSourceCommands(context, program) {
4725
6817
  const pageSize = positiveNumberOption(raw, "pageSize", 0);
4726
6818
  value = await host.client.listSources(notebookId, {
4727
6819
  ...page === void 0 ? {} : { page },
4728
- ...pageSize === void 0 ? {} : { pageSize }
6820
+ ...pageSize === void 0 ? {} : { pageSize },
6821
+ ...raw.parent === void 0 ? {} : {
6822
+ parentSourceId: requiredString(raw.parent, "--parent"),
6823
+ view: "children"
6824
+ }
4729
6825
  });
4730
6826
  }
4731
6827
  render(context, raw, {
@@ -4744,12 +6840,12 @@ function registerSourceCommands(context, program) {
4744
6840
  const file = requiredString(raw.file, "--file");
4745
6841
  render(context, raw, {
4746
6842
  kind: "source",
4747
- value: await host.client.uploadSource(requiredString(raw.nb, "--nb"), await host.createFileSource(file), {
6843
+ value: await submitCliMutation(async () => host.client.uploadSource(requiredString(raw.nb, "--nb"), await host.createFileSource(file), {
4748
6844
  ...optionalString(raw, "title") === void 0 ? {} : { title: optionalString(raw, "title") },
4749
6845
  ...optionalString(raw, "type") === void 0 ? {} : { sourceType: optionalString(raw, "type") },
4750
6846
  ...optionalString(raw, "parent") === void 0 ? {} : { parentSourceId: optionalString(raw, "parent") },
4751
6847
  ...optionalString(raw, "path") === void 0 ? {} : { path: optionalString(raw, "path") }
4752
- })
6848
+ }))
4753
6849
  });
4754
6850
  });
4755
6851
  withCommon(source.command("download <source_id>").description("Download the original source file"), false).option("--nb <id>", "notebook ID (required)").option("-o, --output <path>", "output file path").option("--overwrite", "replace an existing target").action(async (sourceId, raw) => {
@@ -4764,7 +6860,27 @@ function registerSourceCommands(context, program) {
4764
6860
  });
4765
6861
  context.io.stderr(`Downloaded ${output} (${bytes} bytes)\n`);
4766
6862
  });
4767
- withCommon(source.command("mv <source_id>").alias("move").description("Move or rename a source")).option("--nb <id>", "notebook ID (required)").option("--parent <id>", "new parent; pass an empty string for root").option("--path <path>", "new source path").option("--rename <title>", "new source title").option("--status <status>", "new source status").action(async (sourceId, raw) => {
6863
+ withCommon(source.command("mv <source_id>").alias("move").description("Move or rename a source")).option("--nb <id>", "notebook ID (required)").option("--parent <id>", "new parent; pass an empty string for root").option("--path <path>", "new source path").option("--rename <title>", "new source title").option("--status <status>", "new source status").addOption(new Option("--to <id>", "move a leaf document to a directory and derive its path").conflicts([
6864
+ "parent",
6865
+ "path",
6866
+ "rename",
6867
+ "status",
6868
+ "toRoot"
6869
+ ])).addOption(new Option("--to-root", "move a leaf document to root and derive its path").conflicts([
6870
+ "parent",
6871
+ "path",
6872
+ "rename",
6873
+ "status",
6874
+ "to"
6875
+ ])).action(async (sourceId, raw) => {
6876
+ if (raw.to !== void 0 || raw.toRoot === true) {
6877
+ await runCanonicalCommand(context, raw, "qmind.move_source", {
6878
+ notebookId: requiredString(raw.nb, "--nb"),
6879
+ sourceId,
6880
+ targetParentSourceId: raw.toRoot === true ? null : requiredString(raw.to, "--to")
6881
+ });
6882
+ return;
6883
+ }
4768
6884
  const patch = {
4769
6885
  ...raw.parent === void 0 ? {} : { parentSourceId: String(raw.parent) },
4770
6886
  ...raw.path === void 0 ? {} : { path: String(raw.path) },
@@ -4772,9 +6888,10 @@ function registerSourceCommands(context, program) {
4772
6888
  ...raw.status === void 0 ? {} : { status: String(raw.status) }
4773
6889
  };
4774
6890
  if (Object.keys(patch).length === 0) throw new QMindError("INVALID_ARGUMENT", "at least one of --parent, --path, --rename or --status is required");
6891
+ const host = await hostFor(context, raw);
4775
6892
  render(context, raw, {
4776
6893
  kind: "source",
4777
- value: await (await hostFor(context, raw)).client.moveSource(requiredString(raw.nb, "--nb"), sourceId, patch)
6894
+ value: await submitCliMutation(async () => host.client.moveSource(requiredString(raw.nb, "--nb"), sourceId, patch))
4778
6895
  });
4779
6896
  });
4780
6897
  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) => {
@@ -4786,24 +6903,32 @@ function registerSourceCommands(context, program) {
4786
6903
  context.io.stdout(`content saved to ${path}\n`);
4787
6904
  }
4788
6905
  });
4789
- withCommon(source.command("delete <source_id>").description("Delete a source"), false).option("--nb <id>", "notebook ID (required)").option("--force", "skip directory cascade confirmation").action(async (sourceId, raw) => {
6906
+ withCommon(source.command("delete <source_id>").description("Delete a source")).option("--nb <id>", "notebook ID (required)").option("--force", "skip directory cascade confirmation").action(async (sourceId, raw) => {
4790
6907
  const host = await hostFor(context, raw);
4791
6908
  const notebookId = requiredString(raw.nb, "--nb");
4792
6909
  if (raw.force !== true) {
4793
- const record = await host.client.getSource(notebookId, sourceId).catch(() => void 0);
6910
+ const record = await host.client.getSource(notebookId, sourceId);
4794
6911
  if (record?.isDir === true && !await context.confirm.confirm(`warning: source ${JSON.stringify(record.title)} is a directory. Deleting it will cascade-delete ALL children.\nType 'y' to proceed: `)) {
4795
6912
  context.io.stderr("aborted\n");
4796
6913
  context.exitCode = 1;
4797
6914
  return;
4798
6915
  }
4799
6916
  }
4800
- await host.client.deleteSource(notebookId, sourceId);
4801
- context.io.stdout("deleted\n");
6917
+ await submitCliMutation(() => host.client.deleteSource(notebookId, sourceId));
6918
+ if (raw.format === "json" || raw.format === "ndjson") render(context, raw, {
6919
+ kind: "json",
6920
+ value: {
6921
+ notebookId,
6922
+ sourceId,
6923
+ deleted: true
6924
+ }
6925
+ });
6926
+ else context.io.stdout("deleted\n");
4802
6927
  });
4803
6928
  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) => {
4804
6929
  const host = await hostFor(context, raw);
4805
6930
  const rootUrl = requiredString(raw.url, "--url");
4806
- const value = await host.client.importSite(requiredString(raw.nb, "--nb"), {
6931
+ const value = await submitCliMutation(async () => host.client.importSite(requiredString(raw.nb, "--nb"), {
4807
6932
  excludePaths: splitCsv(stringOption(raw, "exclude")),
4808
6933
  includePaths: splitCsv(stringOption(raw, "include")),
4809
6934
  maxPages: numberOption(raw, "maxPages", 50),
@@ -4812,7 +6937,7 @@ function registerSourceCommands(context, program) {
4812
6937
  rootUrl,
4813
6938
  sitemapUrl: optionalString(raw, "sitemap"),
4814
6939
  title: optionalString(raw, "title")
4815
- });
6940
+ }));
4816
6941
  const format = formatOf(raw);
4817
6942
  if (format === "json" || format === "ndjson") render(context, raw, {
4818
6943
  kind: "source",
@@ -4828,14 +6953,14 @@ function registerSourceCommands(context, program) {
4828
6953
  const file = optionalString(raw, "file");
4829
6954
  const filename = optionalString(raw, "filename");
4830
6955
  const mimeType = optionalString(raw, "mime");
4831
- const value = file === void 0 ? await host.client.presignImageUpload(notebookId, sourceId, {
6956
+ const value = file === void 0 ? await submitCliMutation(async () => host.client.presignImageUpload(notebookId, sourceId, {
4832
6957
  filename: requiredString(filename, "--filename"),
4833
6958
  mimeType: requiredString(mimeType, "--mime"),
4834
6959
  size: numberOption(raw, "size", 0)
4835
- }) : await host.client.uploadImage(notebookId, sourceId, await host.createFileSource(file, {
6960
+ })) : await submitCliMutation(async () => host.client.uploadImage(notebookId, sourceId, await host.createFileSource(file, {
4836
6961
  ...filename === void 0 ? {} : { filename },
4837
6962
  ...mimeType === void 0 ? {} : { mimeType }
4838
- }));
6963
+ })));
4839
6964
  if (file !== void 0) context.io.stderr(`uploaded ${file} -> ossKey=${value.ossKey}\n`);
4840
6965
  context.io.stdout(renderQMindCliPresentation({
4841
6966
  kind: "imageUpload",
@@ -4880,11 +7005,11 @@ function registerTaskCommands(context, program) {
4880
7005
  const sourceIds = splitCsv(stringOption(raw, "sources"));
4881
7006
  render(context, raw, {
4882
7007
  kind: "json",
4883
- value: await host.client.createTaskRun(requiredString(raw.nb, "--nb"), {
7008
+ value: await submitCliMutation(async () => host.client.createTaskRun(requiredString(raw.nb, "--nb"), {
4884
7009
  ...sourceIds.length === 0 ? {} : { config: { sourceIds } },
4885
7010
  sceneType: scene,
4886
7011
  trigger: String(raw.trigger ?? "manual")
4887
- })
7012
+ }))
4888
7013
  });
4889
7014
  });
4890
7015
  withCommon(task.command("list").description("List notebook task runs")).option("--nb <id>", "notebook ID (required)").option("--scene <scene>", "filter by scene", "").option("--trigger <trigger>", "filter by trigger", "").option("--status <status>", "filter by status", "").option("--parent-run <id>", "filter by parent run ID", "").option("--scheduled-task <id>", "filter by scheduled task ID", "").option("--page <number>", "page number", integer, 0).option("--page-size <number>", "page size", integer, 20).action(async (raw) => {
@@ -4974,6 +7099,7 @@ function createQMindCliProgram(context) {
4974
7099
  registerSourceCommands(context, program);
4975
7100
  registerSceneCommands(context, program);
4976
7101
  registerTaskCommands(context, program);
7102
+ registerCanonicalCommands(context, program);
4977
7103
  registerSyncCommand(context, program);
4978
7104
  registerUpdateCommand(context, program);
4979
7105
  return program;
@@ -4990,7 +7116,7 @@ async function runQMindCli(argv, options = {}) {
4990
7116
  updater: options.updater ?? createQMindCliUpdater({ identity: {
4991
7117
  artifactKind: "npm",
4992
7118
  command: distribution.command,
4993
- currentVersion: "3.5.0",
7119
+ currentVersion: "4.1.0",
4994
7120
  distribution: distribution.id,
4995
7121
  executablePath: process.execPath,
4996
7122
  package: distribution.package,
@@ -5011,7 +7137,7 @@ async function runQMindCli(argv, options = {}) {
5011
7137
  } catch (error) {
5012
7138
  if (error instanceof CommanderError) exitCode = error.code === "commander.help" || error.code === "commander.helpDisplayed" || error.code === "commander.version" ? 0 : 2;
5013
7139
  else {
5014
- const rendered = renderQMindCliError(error, requestsJsonOutput(normalized));
7140
+ const rendered = renderQMindCliError(error, requestsJsonOutput(normalized), !requestsNdjsonOutput(normalized));
5015
7141
  if (rendered.stdout.length > 0) io.stdout(rendered.stdout);
5016
7142
  if (rendered.stderr.length > 0) io.stderr(rendered.stderr);
5017
7143
  exitCode = rendered.exitCode;