@qoder-ai/qmind-cli 4.0.0 → 4.2.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
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
2
  import { t as preflightSourceUpload } from "./source-upload-DlOLtECT.js";
3
- import { createInterface } from "node:readline/promises";
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
  };
@@ -389,6 +389,19 @@ function createAgentOperations(context) {
389
389
  schema: retrieveResultSchema
390
390
  });
391
391
  },
392
+ async retrieveFeatured(notebookId, input, options) {
393
+ const notebook = requiredString$2(notebookId, "notebookId");
394
+ return call(context, {
395
+ body: retrieveBody(input),
396
+ callOptions: options,
397
+ capability: "retrieval",
398
+ idempotent: false,
399
+ method: "POST",
400
+ operation: "retrieval.retrieveFeatured",
401
+ path: context.profile.apiPath("featured-notebooks", notebook, "retrieve"),
402
+ schema: retrieveResultSchema
403
+ });
404
+ },
392
405
  startAgentRun: (notebookId, input, options) => startAgentRunFor(notebookId, input, options, false),
393
406
  startFeaturedAgentRun: (notebookId, input, options) => startAgentRunFor(notebookId, input, options, true),
394
407
  streamFeaturedQuestion,
@@ -651,6 +664,16 @@ function qmindEmailSourceId(source) {
651
664
  return isQMindEmailSource(source) ? source?.id ?? "" : "";
652
665
  }
653
666
  /**
667
+ * Deleting an email body deletes the whole aggregate, so the folder is the real target. Attachments
668
+ * and emails without attachments delete themselves.
669
+ */
670
+ function qmindEmailDeleteTarget(source, siblings) {
671
+ if (!isQMindEmailSource(source) || source.parentSourceId.length === 0) return source;
672
+ const parent = siblings.find((item) => item.id === source.parentSourceId);
673
+ if (parent === void 0) return source;
674
+ return isQMindEmailFolder(parent) && qmindEmailSourceId(parent) === source.id ? parent : source;
675
+ }
676
+ /**
654
677
  * A body and its attachments cannot leave their email folder, because the folder is what carries
655
678
  * the email identity.
656
679
  */
@@ -674,6 +697,25 @@ function isQMindExternalSource(source) {
674
697
  return source?.externalBinding !== void 0 || provider === "aliding" || provider === "repowiki";
675
698
  }
676
699
  [.../* @__PURE__ */ new Set(["axls", "alxs"])];
700
+ /** Operations allowed by persisted ownership, independent of the visible tree position. */
701
+ function qmindSourceOperationPolicy(source) {
702
+ const binding = source?.externalBinding;
703
+ if (binding === void 0) return {
704
+ rename: true,
705
+ move: true,
706
+ delete: true,
707
+ addChildren: true,
708
+ menu: "ordinary"
709
+ };
710
+ const menu = binding.isRoot && binding.provider === "site_catalog" ? "site" : binding.isRoot && binding.provider === "aliding" ? "aliding" : "none";
711
+ return {
712
+ rename: false,
713
+ move: false,
714
+ delete: menu !== "none",
715
+ addChildren: false,
716
+ menu
717
+ };
718
+ }
677
719
  //#endregion
678
720
  //#region ../sdk/src/source-tree.ts
679
721
  function sourceTreeNodeOrder(left, right) {
@@ -1381,16 +1423,16 @@ const sashCapabilities = Object.freeze({
1381
1423
  chat: true,
1382
1424
  "featuredChat.delete": false,
1383
1425
  compilation: false,
1384
- "featuredNotebooks.read": false,
1426
+ "featuredNotebooks.read": true,
1385
1427
  "featuredNotebooks.copy": true,
1386
1428
  "images.presignUpload": true,
1387
1429
  "images.presignUrls": true,
1388
- "imports.aliDing": false,
1389
- "imports.discover": false,
1430
+ "imports.aliDing": true,
1431
+ "imports.discover": true,
1390
1432
  "imports.fullSiteURL": false,
1391
- members: false,
1433
+ members: true,
1392
1434
  "members.search": false,
1393
- "members.resolve": false,
1435
+ "members.resolve": true,
1394
1436
  "notebooks.filterByClient": true,
1395
1437
  "notebooks.read": true,
1396
1438
  "notebooks.write": true,
@@ -1694,7 +1736,7 @@ function createLazyNoteOperations(context) {
1694
1736
  function createLazyImportOperations(context) {
1695
1737
  let operations;
1696
1738
  const load = () => {
1697
- operations ??= import("./imports-Cmd6ys9g.js").then(({ createImportOperations }) => createImportOperations(context));
1739
+ operations ??= import("./imports-BZyUf1pq.js").then(({ createImportOperations }) => createImportOperations(context));
1698
1740
  return operations;
1699
1741
  };
1700
1742
  return Object.fromEntries(importOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
@@ -1702,7 +1744,7 @@ function createLazyImportOperations(context) {
1702
1744
  function createLazyManagementOperations(context) {
1703
1745
  let operations;
1704
1746
  const load = () => {
1705
- operations ??= import("./management-CgWDLle_.js").then(({ createManagementOperations }) => createManagementOperations(context));
1747
+ operations ??= import("./management-DQVj17Hn.js").then(({ createManagementOperations }) => createManagementOperations(context));
1706
1748
  return operations;
1707
1749
  };
1708
1750
  return Object.fromEntries(managementOperationNames.map((name) => [name, (...args) => load().then((loaded) => Reflect.apply(loaded[name], loaded, args))]));
@@ -1734,9 +1776,31 @@ function createQMindClient(options) {
1734
1776
  });
1735
1777
  }
1736
1778
  //#endregion
1779
+ //#region ../sdk/src/source-title-policy.ts
1780
+ const PATH_SEPARATORS = /[/\\\0]/u;
1781
+ /** A Source title doubles as its last path segment; this is the local shape check, not a server limit. */
1782
+ function qmindSourceTitlePolicy(value) {
1783
+ const title = value.trim();
1784
+ if (!title) return {
1785
+ allowed: false,
1786
+ reason: "empty"
1787
+ };
1788
+ if (title === "." || title === ".." || PATH_SEPARATORS.test(title)) return {
1789
+ allowed: false,
1790
+ reason: "notSingleSegment"
1791
+ };
1792
+ return {
1793
+ allowed: true,
1794
+ title
1795
+ };
1796
+ }
1797
+ //#endregion
1737
1798
  //#region ../node-host/src/auth.ts
1738
1799
  const responseRecordSchema = z.record(z.string(), z.unknown());
1739
- const personalTokenExchangeSchema = z.object({ token: z.string().min(1) });
1800
+ const personalTokenExchangeSchema = z.object({
1801
+ token: z.string().min(1),
1802
+ expires_at: z.string().refine((value) => value.length === 0 || Number.isFinite(Date.parse(value))).default("")
1803
+ });
1740
1804
  const devicePollSchema = z.object({
1741
1805
  expires_at: z.string().default(""),
1742
1806
  refresh_token: z.string().default(""),
@@ -1796,7 +1860,7 @@ function authResponseError(response, operation) {
1796
1860
  ...upstreamCode === void 0 ? {} : { upstreamCode }
1797
1861
  });
1798
1862
  }
1799
- async function authRequest(transport, method, path, operation, body) {
1863
+ async function authRequest(transport, method, path, operation, body, signal) {
1800
1864
  const request = {
1801
1865
  ...body === void 0 ? {} : { body: {
1802
1866
  kind: "json",
@@ -1807,15 +1871,20 @@ async function authRequest(transport, method, path, operation, body) {
1807
1871
  path
1808
1872
  },
1809
1873
  idempotent: method === "GET",
1810
- method
1874
+ method,
1875
+ ...signal === void 0 ? {} : { signal }
1811
1876
  };
1812
1877
  let response;
1813
1878
  try {
1814
1879
  response = await transport.request(request);
1815
1880
  } catch (cause) {
1881
+ const abortError = aborted(signal);
1882
+ if (abortError !== void 0) throw abortError;
1816
1883
  if (cause instanceof QMindError) throw cause;
1817
1884
  throw new QMindError("NETWORK_ERROR", `${operation} failed`);
1818
1885
  }
1886
+ const abortError = aborted(signal);
1887
+ if (abortError !== void 0) throw abortError;
1819
1888
  if (response.status < 200 || response.status >= 300) throw authResponseError(response, operation);
1820
1889
  const parsed = responseRecordSchema.safeParse(response.body);
1821
1890
  if (!parsed.success) throw new QMindError("PROTOCOL_ERROR", `${operation} returned an invalid response`, {
@@ -1870,9 +1939,70 @@ function createQMindCliAuthManager(options) {
1870
1939
  let credentials = options.credentials;
1871
1940
  let explicitToken = options.explicitToken;
1872
1941
  let token = "";
1942
+ let tokenExpiresAt = "";
1873
1943
  let refreshPromise;
1944
+ let sessionGeneration = 0;
1945
+ let credentialWrite = Promise.resolve();
1946
+ const assertCurrentSession = (generation, operation = "refresh") => {
1947
+ if (generation !== sessionGeneration) throw new QMindError("AUTH_REQUIRED", `credentials changed during ${operation}`);
1948
+ };
1949
+ const serializeCredentialWrite = (operation) => {
1950
+ const pending = credentialWrite.then(operation);
1951
+ credentialWrite = pending.then(() => void 0, () => void 0);
1952
+ return pending;
1953
+ };
1954
+ const commitLogin = async (saved, generation, signal) => await serializeCredentialWrite(async () => {
1955
+ assertCurrentSession(generation, "login");
1956
+ const abortError = aborted(signal);
1957
+ if (abortError !== void 0) throw abortError;
1958
+ await options.vault.save(saved);
1959
+ if (generation !== sessionGeneration) {
1960
+ await options.vault.deleteIf(saved);
1961
+ assertCurrentSession(generation, "login");
1962
+ }
1963
+ sessionGeneration++;
1964
+ refreshPromise = void 0;
1965
+ credentials = saved;
1966
+ explicitToken = "";
1967
+ token = saved.deviceToken;
1968
+ tokenExpiresAt = saved.personalToken === void 0 ? "" : saved.expiresAt;
1969
+ return {
1970
+ expiresAt: saved.expiresAt,
1971
+ sashOrigin: saved.sashOrigin
1972
+ };
1973
+ });
1974
+ const exchangePersonalToken = async (personalToken, signal) => {
1975
+ const raw = await authRequest(options.transport, "POST", "/api/v1/jobToken/exchange", "personal token exchange", { personal_token: personalToken }, signal);
1976
+ const parsed = personalTokenExchangeSchema.safeParse(raw);
1977
+ if (!parsed.success) throw new QMindError("PROTOCOL_ERROR", "personal token exchange returned an invalid response");
1978
+ return parsed.data;
1979
+ };
1874
1980
  const login = async (loginOptions = {}) => {
1875
- if (options.config.nonInteractive) throw new QMindError("AUTH_REQUIRED", "login requires an interactive terminal");
1981
+ const personalToken = loginOptions.personalToken?.trim() ?? (explicitToken.startsWith("pt-") ? explicitToken : void 0);
1982
+ if (personalToken !== void 0) {
1983
+ if (!personalToken.startsWith("pt-") || personalToken.length <= 3 || /\s/.test(personalToken)) throw new QMindError("INVALID_ARGUMENT", "Qoder PAT must be a non-empty pt- token");
1984
+ if (loginOptions.clientId !== void 0) throw new QMindError("INVALID_ARGUMENT", "client_id cannot be combined with PAT login");
1985
+ const abortError = aborted(loginOptions.signal);
1986
+ if (abortError !== void 0) throw abortError;
1987
+ const generation = ++sessionGeneration;
1988
+ refreshPromise = void 0;
1989
+ const exchanged = await exchangePersonalToken(personalToken, loginOptions.signal);
1990
+ assertCurrentSession(generation, "login");
1991
+ const saved = {
1992
+ deviceToken: exchanged.token,
1993
+ personalToken,
1994
+ expiresAt: exchanged.expires_at,
1995
+ refreshToken: "",
1996
+ refreshTokenExpiresAt: "",
1997
+ sashOrigin: options.config.sashOrigin,
1998
+ savedAt: "",
1999
+ schemaVersion: 2
2000
+ };
2001
+ return await commitLogin(saved, generation, loginOptions.signal);
2002
+ }
2003
+ if (options.config.nonInteractive) throw new QMindError("AUTH_REQUIRED", "browser login requires an interactive terminal; use PAT login with --pat-stdin or a Qoder PAT environment variable");
2004
+ const generation = ++sessionGeneration;
2005
+ refreshPromise = void 0;
1876
2006
  const pkce = createPkce();
1877
2007
  const browserUrl = new URL("/device/selectAccounts", options.config.dashboardOrigin);
1878
2008
  browserUrl.searchParams.set("nonce", pkce.nonce);
@@ -1901,14 +2031,7 @@ function createQMindCliAuthManager(options) {
1901
2031
  const raw = await authRequest(options.transport, "GET", pollPath, "device authorization polling");
1902
2032
  const parsed = devicePollSchema.safeParse(raw);
1903
2033
  if (!parsed.success) throw new QMindError("PROTOCOL_ERROR", "device authorization returned an invalid response");
1904
- credentials = credentialsFromLogin(parsed.data, options.config.sashOrigin);
1905
- await options.vault.save(credentials);
1906
- explicitToken = "";
1907
- token = credentials.deviceToken;
1908
- return {
1909
- expiresAt: credentials.expiresAt,
1910
- sashOrigin: credentials.sashOrigin
1911
- };
2034
+ return await commitLogin(credentialsFromLogin(parsed.data, options.config.sashOrigin), generation, loginOptions.signal);
1912
2035
  } catch (error) {
1913
2036
  if (error instanceof QMindError && error.status === 404) continue;
1914
2037
  throw error;
@@ -1917,20 +2040,55 @@ function createQMindCliAuthManager(options) {
1917
2040
  throw new QMindError("AUTH_REQUIRED", "authorization timed out after 5m");
1918
2041
  };
1919
2042
  const refreshInternal = async (reason) => {
2043
+ const generation = sessionGeneration;
2044
+ const sourceToken = explicitToken || credentials?.deviceToken || "";
2045
+ const personalToken = sourceToken.startsWith("pt-") ? sourceToken : explicitToken.length === 0 ? credentials?.personalToken : void 0;
2046
+ if (personalToken !== void 0) {
2047
+ const basis = credentials;
2048
+ const explicitBasis = explicitToken;
2049
+ const exchanged = await exchangePersonalToken(personalToken);
2050
+ assertCurrentSession(generation);
2051
+ if (credentials !== basis || explicitToken !== explicitBasis) throw new QMindError("AUTH_REQUIRED", "credentials changed during refresh");
2052
+ if (explicitToken.length === 0 && basis !== void 0) {
2053
+ const refreshed = {
2054
+ ...basis,
2055
+ personalToken,
2056
+ deviceToken: exchanged.token,
2057
+ expiresAt: exchanged.expires_at
2058
+ };
2059
+ const committed = await options.vault.compareAndSwap(basis, refreshed);
2060
+ assertCurrentSession(generation);
2061
+ const current = committed ? refreshed : await options.vault.load();
2062
+ assertCurrentSession(generation);
2063
+ credentials = current;
2064
+ token = "";
2065
+ tokenExpiresAt = "";
2066
+ if (credentials === void 0) throw new QMindError("AUTH_REQUIRED", "credentials changed during refresh");
2067
+ token = credentials.deviceToken;
2068
+ tokenExpiresAt = credentials.personalToken === void 0 ? "" : credentials.expiresAt;
2069
+ if (token.length === 0) throw new QMindError("AUTH_REQUIRED", "credentials changed during refresh");
2070
+ return token;
2071
+ }
2072
+ token = exchanged.token;
2073
+ tokenExpiresAt = exchanged.expires_at;
2074
+ return token;
2075
+ }
1920
2076
  if (credentials === void 0 || credentials.refreshToken.length === 0) {
1921
2077
  token = "";
1922
2078
  throw new QMindError("AUTH_REQUIRED", `credentials cannot be refreshed after ${reason}`);
1923
2079
  }
1924
2080
  if (isExpired(credentials.refreshTokenExpiresAt, options.clock.now())) {
1925
2081
  await options.vault.deleteIf(credentials);
2082
+ assertCurrentSession(generation);
1926
2083
  credentials = void 0;
1927
2084
  token = "";
1928
2085
  throw new QMindError("AUTH_REQUIRED", "stored refresh credentials have expired");
1929
2086
  }
1930
- const raw = await authRequest(options.transport, "POST", "/api/v1/deviceToken/refresh", "credential refresh", { refresh_token: credentials.refreshToken });
2087
+ const basis = credentials;
2088
+ const raw = await authRequest(options.transport, "POST", "/api/v1/deviceToken/refresh", "credential refresh", { refresh_token: basis.refreshToken });
2089
+ assertCurrentSession(generation);
1931
2090
  const parsed = refreshSchema.safeParse(raw);
1932
2091
  if (!parsed.success) throw new QMindError("PROTOCOL_ERROR", "credential refresh returned an invalid response");
1933
- const basis = credentials;
1934
2092
  const legacy = basis.schemaVersion !== 2;
1935
2093
  const refreshed = {
1936
2094
  ...basis,
@@ -1941,7 +2099,10 @@ function createQMindCliAuthManager(options) {
1941
2099
  sashOrigin: options.config.sashOrigin,
1942
2100
  schemaVersion: 2
1943
2101
  };
1944
- const current = await options.vault.compareAndSwap(basis, refreshed, { migrateLegacy: legacy }) ? refreshed : await options.vault.load();
2102
+ const committed = await options.vault.compareAndSwap(basis, refreshed, { migrateLegacy: legacy });
2103
+ assertCurrentSession(generation);
2104
+ const current = committed ? refreshed : await options.vault.load();
2105
+ assertCurrentSession(generation);
1945
2106
  if (current === void 0) {
1946
2107
  credentials = void 0;
1947
2108
  token = "";
@@ -1953,37 +2114,40 @@ function createQMindCliAuthManager(options) {
1953
2114
  };
1954
2115
  const manager = {
1955
2116
  async getToken() {
1956
- if (token.length > 0) return token;
2117
+ if (token.length > 0) {
2118
+ if (isExpired(tokenExpiresAt, options.clock.now(), EXPIRY_SKEW_MS)) return manager.refreshToken("expired", token);
2119
+ return token;
2120
+ }
1957
2121
  const candidate = explicitToken || credentials?.deviceToken || "";
1958
2122
  if (candidate.length === 0) {
1959
- if (options.config.nonInteractive) throw new QMindError("AUTH_REQUIRED", `no credentials found; run '${options.loginCommand ?? "qmind login"}' in an interactive terminal`);
2123
+ if (options.config.nonInteractive) throw new QMindError("AUTH_REQUIRED", `no credentials found; run '${options.loginCommand ?? "qmind login"}' in an interactive terminal or use PAT login with --pat-stdin`);
1960
2124
  await login();
1961
2125
  return token;
1962
2126
  }
1963
- if (candidate.startsWith("pt-")) {
1964
- const raw = await authRequest(options.transport, "POST", "/api/v1/jobToken/exchange", "personal token exchange", { personal_token: candidate });
1965
- const parsed = personalTokenExchangeSchema.safeParse(raw);
1966
- if (!parsed.success) throw new QMindError("PROTOCOL_ERROR", "personal token exchange returned an invalid response");
1967
- token = parsed.data.token;
1968
- return token;
1969
- }
2127
+ if (candidate.startsWith("pt-")) return manager.refreshToken("expired");
1970
2128
  if (credentials !== void 0 && candidate === credentials.deviceToken && isExpired(credentials.expiresAt, options.clock.now(), EXPIRY_SKEW_MS)) return manager.refreshToken("expired", candidate);
1971
2129
  token = candidate;
2130
+ tokenExpiresAt = credentials?.personalToken !== void 0 && explicitToken.length === 0 ? credentials.expiresAt : "";
1972
2131
  return token;
1973
2132
  },
1974
2133
  login,
1975
2134
  async logout() {
1976
- await options.vault.delete();
2135
+ sessionGeneration++;
1977
2136
  credentials = void 0;
1978
2137
  explicitToken = "";
1979
2138
  token = "";
2139
+ tokenExpiresAt = "";
1980
2140
  refreshPromise = void 0;
2141
+ await serializeCredentialWrite(() => options.vault.delete());
1981
2142
  },
1982
2143
  async refreshToken(reason, rejectedToken) {
1983
2144
  if (rejectedToken !== void 0 && token.length > 0 && token !== rejectedToken) return token;
1984
- refreshPromise ??= refreshInternal(reason).finally(() => {
1985
- refreshPromise = void 0;
1986
- });
2145
+ if (refreshPromise === void 0) {
2146
+ const pending = refreshInternal(reason).finally(() => {
2147
+ if (refreshPromise === pending) refreshPromise = void 0;
2148
+ });
2149
+ refreshPromise = pending;
2150
+ }
1987
2151
  return await refreshPromise;
1988
2152
  }
1989
2153
  };
@@ -2253,6 +2417,7 @@ async function loadQMindCliConfig(options = {}) {
2253
2417
  //#region ../node-host/src/credentials.ts
2254
2418
  const serializedCredentialsSchema = z.object({
2255
2419
  device_token: z.string().default(""),
2420
+ personal_token: z.string().min(4).startsWith("pt-").regex(/^\S+$/).optional(),
2256
2421
  expires_at: z.string().default(""),
2257
2422
  refresh_token: z.string().default(""),
2258
2423
  refresh_token_expires_at: z.string().default(""),
@@ -2279,6 +2444,7 @@ function normalizeStoredCredentials(value) {
2279
2444
  if (parsed.schema_version !== void 0 && parsed.schema_version > 2 || parsed.device_token.length === 0 && parsed.refresh_token.length === 0 || !isValidOptionalTimestamp(parsed.expires_at) || !isValidOptionalTimestamp(parsed.refresh_token_expires_at)) throw storedCredentialsInvalid();
2280
2445
  return {
2281
2446
  deviceToken: parsed.device_token,
2447
+ ...parsed.personal_token === void 0 ? {} : { personalToken: parsed.personal_token },
2282
2448
  expiresAt: parsed.expires_at,
2283
2449
  refreshToken: parsed.refresh_token,
2284
2450
  refreshTokenExpiresAt: parsed.refresh_token_expires_at,
@@ -2290,6 +2456,7 @@ function normalizeStoredCredentials(value) {
2290
2456
  function serializedCredentials(credentials, now) {
2291
2457
  return `${JSON.stringify({
2292
2458
  device_token: credentials.deviceToken,
2459
+ ...credentials.personalToken === void 0 ? {} : { personal_token: credentials.personalToken },
2293
2460
  expires_at: credentials.expiresAt,
2294
2461
  refresh_token: credentials.refreshToken,
2295
2462
  refresh_token_expires_at: credentials.refreshTokenExpiresAt,
@@ -2299,7 +2466,7 @@ function serializedCredentials(credentials, now) {
2299
2466
  }, null, 2)}\n`;
2300
2467
  }
2301
2468
  function sameCredentials(left, right) {
2302
- return left !== void 0 && right !== void 0 && left.deviceToken === right.deviceToken && left.expiresAt === right.expiresAt && left.refreshToken === right.refreshToken && left.refreshTokenExpiresAt === right.refreshTokenExpiresAt && left.sashOrigin === right.sashOrigin && left.schemaVersion === right.schemaVersion;
2469
+ return left !== void 0 && right !== void 0 && left.deviceToken === right.deviceToken && left.personalToken === right.personalToken && left.expiresAt === right.expiresAt && left.refreshToken === right.refreshToken && left.refreshTokenExpiresAt === right.refreshTokenExpiresAt && left.sashOrigin === right.sashOrigin && left.schemaVersion === right.schemaVersion;
2303
2470
  }
2304
2471
  async function secureDirectory(path) {
2305
2472
  await mkdir(path, {
@@ -3301,9 +3468,7 @@ function normalizeLegacyArgv(argv) {
3301
3468
  return argument;
3302
3469
  });
3303
3470
  }
3304
- /** Runtime errors use the JSON error envelope only when the caller explicitly
3305
- * selected JSON, except folder sync whose compatibility default is JSON. */
3306
- function requestsJsonOutput(argv) {
3471
+ function requestedFormat(argv) {
3307
3472
  let explicitFormat;
3308
3473
  let positionalOnly = false;
3309
3474
  for (let index = 0; index < argv.length; index += 1) {
@@ -3321,15 +3486,23 @@ function requestsJsonOutput(argv) {
3321
3486
  const match = argument?.match(/^--?format=(.*)$/);
3322
3487
  if (match !== null && match !== void 0) explicitFormat = match[1];
3323
3488
  }
3324
- if (explicitFormat !== void 0) return explicitFormat === "json";
3489
+ return explicitFormat;
3490
+ }
3491
+ /** Machine formats keep errors on stdout; folder sync also defaults to JSON. */
3492
+ function requestsJsonOutput(argv) {
3493
+ const format = requestedFormat(argv);
3494
+ if (format !== void 0) return format === "json" || format === "ndjson";
3325
3495
  return argv[0] === "upload-folder" || argv[0] === "sync";
3326
3496
  }
3497
+ function requestsNdjsonOutput(argv) {
3498
+ return requestedFormat(argv) === "ndjson";
3499
+ }
3327
3500
  //#endregion
3328
3501
  //#region src/build-info.ts
3329
3502
  /** Bundled identity, never inferred from argv, environment, or an endpoint. */
3330
3503
  const QMIND_CLI_DISTRIBUTION = "global";
3331
- const QMIND_CLI_VERSION = "4.0.0";
3332
- const QMIND_CLI_BUILD_TIME = "2026-10-19T13:00:47.000Z";
3504
+ const QMIND_CLI_VERSION = "4.2.0";
3505
+ const QMIND_CLI_BUILD_TIME = "2026-10-27T06:23:11.000Z";
3333
3506
  function qmindCliPlatform() {
3334
3507
  return process.platform === "win32" ? "windows" : process.platform;
3335
3508
  }
@@ -3368,31 +3541,6 @@ const CLI_DISTRIBUTIONS = Object.freeze({
3368
3541
  }
3369
3542
  });
3370
3543
  //#endregion
3371
- //#region src/config.ts
3372
- function cliHostConfiguration(distribution, flags, environment, stateRoot) {
3373
- const { productId, command } = CLI_DISTRIBUTIONS[distribution];
3374
- const custom = flags.sash !== void 0 || flags.dashboard !== void 0;
3375
- 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");
3376
- const preset = typeof flags.env === "string" ? flags.env.trim() : "prod";
3377
- const endpoints = custom ? {
3378
- dashboardOrigin: normalizeQMindOrigin(String(flags.dashboard).trim(), "--dashboard"),
3379
- sashOrigin: normalizeQMindOrigin(String(flags.sash).trim(), "--sash")
3380
- } : resolveQMindProductEndpoints(productId, preset);
3381
- const target = custom ? `custom-${createHash("sha256").update(JSON.stringify([endpoints.dashboardOrigin, endpoints.sashOrigin])).digest("hex")}` : preset;
3382
- return {
3383
- environment: {
3384
- ...environment,
3385
- QMIND_TOKEN: target === "prod" ? environment.QMIND_TOKEN : environment.QMIND_DEBUG_TOKEN
3386
- },
3387
- flags,
3388
- fixedEndpoints: endpoints,
3389
- homeDirectory: join(resolve(stateRoot ?? (environment.QMIND_HOME?.trim() || join(homedir(), ".qmind"))), "cli", distribution, target),
3390
- legacyEnvironmentPath: false,
3391
- loginCommand: `${command} login${custom ? ` --sash ${endpoints.sashOrigin} --dashboard ${endpoints.dashboardOrigin}` : target === "prod" ? "" : ` --env ${target}`}`,
3392
- productId
3393
- };
3394
- }
3395
- //#endregion
3396
3544
  //#region src/folder-sync.ts
3397
3545
  const QMIND_FOLDER_SYNC_DEFAULT_EXTENSIONS = Object.freeze([
3398
3546
  ".mdx",
@@ -3701,6 +3849,32 @@ async function synchronizeQMindFolder(host, options) {
3701
3849
  };
3702
3850
  }
3703
3851
  //#endregion
3852
+ //#region src/mutations.ts
3853
+ /** Preserve SDK diagnostics while distinguishing an unconfirmed legacy command write. */
3854
+ var CliMutationOutcomeUnknown = class extends Error {
3855
+ original;
3856
+ retryable = false;
3857
+ outcome = "outcome_unknown";
3858
+ constructor(original) {
3859
+ super("The write outcome is unknown. Inspect current state before another call; do not retry automatically.", { cause: original });
3860
+ this.original = original;
3861
+ }
3862
+ };
3863
+ async function submitCliMutation(submit) {
3864
+ try {
3865
+ return await submit();
3866
+ } catch (error) {
3867
+ if (error instanceof QMindError && error.operation !== "sources.uploadPreflight" && error.upstreamCode !== "QMindDisabledByOrganization" && (error.status === 408 || [
3868
+ "TIMEOUT",
3869
+ "ABORTED",
3870
+ "NETWORK_ERROR",
3871
+ "REMOTE_ERROR",
3872
+ "PROTOCOL_ERROR"
3873
+ ].includes(error.code))) throw new CliMutationOutcomeUnknown(error);
3874
+ throw error;
3875
+ }
3876
+ }
3877
+ //#endregion
3704
3878
  //#region src/output.ts
3705
3879
  var TextWriter = class {
3706
3880
  #chunks = [];
@@ -3793,6 +3967,9 @@ function goNotebook(value) {
3793
3967
  orgId: stringValue(source.orgId),
3794
3968
  userId: stringValue(source.userId),
3795
3969
  title: stringValue(source.title),
3970
+ sourceCount: value.sourceCount,
3971
+ materialCount: value.materialCount,
3972
+ ...value.overview === void 0 ? {} : { overview: value.overview },
3796
3973
  description: stringValue(source.description),
3797
3974
  client: stringValue(source.client),
3798
3975
  status: stringValue(source.status),
@@ -3913,6 +4090,10 @@ function renderAgentNotebook(writer, value, index = 0) {
3913
4090
  agentField(writer, "createdAt", timestamp(value.createdAt));
3914
4091
  agentField(writer, "updatedAt", timestamp(value.updatedAt));
3915
4092
  agentText(writer, "description", value.description);
4093
+ agentField(writer, "sourceCount", value.sourceCount);
4094
+ agentField(writer, "materialCount", value.materialCount);
4095
+ agentText(writer, "summary", value.overview?.summary);
4096
+ if (value.overview?.topics) agentField(writer, "topics", value.overview.topics.join(", "));
3916
4097
  }
3917
4098
  function renderAgentSource(writer, value, index = 0) {
3918
4099
  writer.line("---");
@@ -3950,6 +4131,9 @@ function renderNotebook(value, format) {
3950
4131
  writer.line(`CreatedAt: ${timestamp(value.createdAt)}`);
3951
4132
  writer.line(`UpdatedAt: ${timestamp(value.updatedAt)}`);
3952
4133
  if (value.description.length > 0) writer.line(`\n${value.description}`);
4134
+ writer.line(`Sources: ${value.sourceCount} (materials: ${value.materialCount})`);
4135
+ if (value.overview?.summary) writer.line(`Summary: ${value.overview.summary}`);
4136
+ if (value.overview?.topics?.length) writer.line(`Topics: ${value.overview.topics.join(", ")}`);
3953
4137
  }
3954
4138
  return writer.toString();
3955
4139
  }
@@ -3971,6 +4155,8 @@ function renderNotebookList(value, format) {
3971
4155
  "USER",
3972
4156
  "PERMISSION",
3973
4157
  "MEMBERS",
4158
+ "SOURCES",
4159
+ "SUMMARY",
3974
4160
  "UPDATED"
3975
4161
  ], value.notebooks.map((item) => [
3976
4162
  truncate(item.id, 36),
@@ -3979,6 +4165,8 @@ function renderNotebookList(value, format) {
3979
4165
  truncate(item.userId, 18),
3980
4166
  item.access?.currentUserPermission ?? item.permission ?? "unknown",
3981
4167
  item.access?.memberCount ?? "-",
4168
+ item.sourceCount,
4169
+ truncate(oneLine(item.overview?.summary), 40),
3982
4170
  timestamp(item.updatedAt)
3983
4171
  ]), [
3984
4172
  36,
@@ -3987,8 +4175,10 @@ function renderNotebookList(value, format) {
3987
4175
  18,
3988
4176
  12,
3989
4177
  7,
4178
+ 7,
4179
+ 40,
3990
4180
  20
3991
- ], 143);
4181
+ ], 194);
3992
4182
  }
3993
4183
  return writer.toString();
3994
4184
  }
@@ -4162,42 +4352,49 @@ function renderQMindCliPresentation(presentation, format) {
4162
4352
  case "text": return presentation.value;
4163
4353
  }
4164
4354
  }
4165
- function renderQMindCliError(error, jsonOutput) {
4166
- const source = error instanceof QMindError ? {
4167
- code: error.code,
4168
- details: error.details,
4169
- message: error.message,
4170
- rawBody: error.rawBody,
4171
- requestId: error.requestId,
4172
- status: error.status,
4173
- upstreamCode: error.upstreamCode
4355
+ function renderQMindCliError(error, jsonOutput, pretty = true) {
4356
+ const unknownWrite = error instanceof CliMutationOutcomeUnknown ? error : void 0;
4357
+ const cause = unknownWrite?.original ?? error;
4358
+ const source = cause instanceof QMindError ? {
4359
+ code: cause.code,
4360
+ details: cause.details,
4361
+ message: cause.message,
4362
+ rawBody: cause.rawBody,
4363
+ requestId: cause.requestId,
4364
+ status: cause.status,
4365
+ upstreamCode: cause.upstreamCode
4174
4366
  } : {
4175
4367
  code: "INTERNAL_ERROR",
4176
4368
  details: void 0,
4177
- message: error instanceof Error ? error.message : String(error),
4369
+ message: cause instanceof Error ? cause.message : String(cause),
4178
4370
  rawBody: void 0,
4179
4371
  requestId: void 0,
4180
4372
  status: void 0,
4181
4373
  upstreamCode: void 0
4182
4374
  };
4183
- const exitCode = source.code === "INVALID_ARGUMENT" ? 2 : 1;
4375
+ const exitCode = unknownWrite === void 0 && source.code === "INVALID_ARGUMENT" ? 2 : 1;
4184
4376
  if (!jsonOutput) return {
4185
4377
  exitCode,
4186
- stderr: `error: ${source.message}\n`,
4378
+ stderr: `error: ${unknownWrite ? `outcome_unknown: ${unknownWrite.message}` : source.message}\n`,
4187
4379
  stdout: ""
4188
4380
  };
4189
4381
  return {
4190
4382
  exitCode,
4191
4383
  stderr: "",
4192
4384
  stdout: json({ error: {
4193
- code: source.code,
4194
- message: source.message,
4385
+ code: unknownWrite ? "outcome_unknown" : source.code,
4386
+ message: unknownWrite?.message ?? source.message,
4387
+ ...unknownWrite ? {
4388
+ causeCode: source.code,
4389
+ outcome: unknownWrite.outcome,
4390
+ retryable: unknownWrite.retryable
4391
+ } : {},
4195
4392
  status: source.status,
4196
4393
  errorCode: source.upstreamCode,
4197
4394
  requestId: source.requestId,
4198
4395
  rawBody: source.rawBody,
4199
4396
  details: source.details
4200
- } }, true)
4397
+ } }, pretty)
4201
4398
  };
4202
4399
  }
4203
4400
  function compatibilityQuestionEvent(event) {
@@ -4524,12 +4721,64 @@ function createQMindCliUpdater(options) {
4524
4721
  } });
4525
4722
  }
4526
4723
  //#endregion
4527
- //#region src/application.ts
4528
- const distribution = CLI_DISTRIBUTIONS[QMIND_CLI_DISTRIBUTION];
4724
+ //#region src/config.ts
4725
+ function cliHostConfiguration(distribution, flags, environment, stateRoot) {
4726
+ const { productId, command } = CLI_DISTRIBUTIONS[distribution];
4727
+ const custom = flags.sash !== void 0 || flags.dashboard !== void 0;
4728
+ 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");
4729
+ const preset = typeof flags.env === "string" ? flags.env.trim() : "prod";
4730
+ const endpoints = custom ? {
4731
+ dashboardOrigin: normalizeQMindOrigin(String(flags.dashboard).trim(), "--dashboard"),
4732
+ sashOrigin: normalizeQMindOrigin(String(flags.sash).trim(), "--sash")
4733
+ } : resolveQMindProductEndpoints(productId, preset);
4734
+ const target = custom ? `custom-${createHash("sha256").update(JSON.stringify([endpoints.dashboardOrigin, endpoints.sashOrigin])).digest("hex")}` : preset;
4735
+ const modeToken = (target === "prod" ? environment.QMIND_TOKEN : environment.QMIND_DEBUG_TOKEN)?.trim();
4736
+ const patVariable = !custom && (preset === "prod" || preset === "test") ? {
4737
+ global: {
4738
+ prod: "QODER_PROD_PAT",
4739
+ test: "QODER_TEST_PAT"
4740
+ },
4741
+ cn: {
4742
+ prod: "QODER_PROD_CN_PAT",
4743
+ test: "QODER_TEST_CN_PAT"
4744
+ }
4745
+ }[distribution][preset] : void 0;
4746
+ const personalToken = custom ? void 0 : (patVariable === void 0 ? void 0 : environment[patVariable]?.trim()) || environment.QODER_PERSONAL_ACCESS_TOKEN?.trim();
4747
+ if (!flags.token?.trim() && !modeToken && personalToken && (!personalToken.startsWith("pt-") || personalToken.length <= 3 || /\s/.test(personalToken))) throw new QMindError("INVALID_ARGUMENT", "Qoder PAT environment variable must contain a non-empty pt- token");
4748
+ return {
4749
+ environment: {
4750
+ ...environment,
4751
+ QMIND_TOKEN: modeToken || personalToken
4752
+ },
4753
+ flags,
4754
+ fixedEndpoints: endpoints,
4755
+ homeDirectory: join(resolve(stateRoot ?? (environment.QMIND_HOME?.trim() || join(homedir(), ".qmind"))), "cli", distribution, target),
4756
+ legacyEnvironmentPath: false,
4757
+ loginCommand: `${command} login${custom ? ` --sash ${endpoints.sashOrigin} --dashboard ${endpoints.dashboardOrigin}` : target === "prod" ? "" : ` --env ${target}`}`,
4758
+ productId
4759
+ };
4760
+ }
4761
+ //#endregion
4762
+ //#region src/command-context.ts
4529
4763
  function processIO() {
4530
4764
  return Object.freeze({
4531
4765
  stdinIsTTY: process.stdin.isTTY === true,
4532
4766
  stderrIsTTY: process.stderr.isTTY === true,
4767
+ async readStdin() {
4768
+ const chunks = [];
4769
+ let size = 0;
4770
+ try {
4771
+ for await (const chunk of process.stdin) {
4772
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
4773
+ size += bytes.length;
4774
+ if (size > 16384) throw new Error("input too large");
4775
+ chunks.push(bytes);
4776
+ }
4777
+ } catch {
4778
+ throw new QMindError("INVALID_ARGUMENT", "unable to read PAT from stdin (maximum 16 KiB)");
4779
+ }
4780
+ return Buffer.concat(chunks).toString("utf8");
4781
+ },
4533
4782
  stderr(value) {
4534
4783
  process.stderr.write(value);
4535
4784
  },
@@ -4635,137 +4884,2517 @@ function withCommon(command, output = true) {
4635
4884
  if (output) command.option("--format <format>", "output format: table | json | agent | ndjson", "table");
4636
4885
  return command;
4637
4886
  }
4638
- function registerCoreCommands(context, program) {
4639
- withCommon(program.command("login").description("Authorize via browser and save credentials"), false).option("--client-id <id>", "OAuth App client_id").action(async (raw) => {
4640
- const host = await hostFor(context, raw);
4641
- const clientId = optionalString(raw, "clientId");
4642
- const result = await host.login({ ...clientId === void 0 ? {} : { clientId } });
4643
- context.io.stdout(`Logged in successfully [${result.sashOrigin} -> ${host.config.dashboardOrigin}]\nToken saved to ${host.config.homeDirectory}/credentials.json\nDevice token expires at: ${result.expiresAt}\n`);
4644
- });
4645
- withCommon(program.command("logout").description("Remove saved credentials"), false).action(async (raw) => {
4646
- await (await hostFor(context, raw)).logout();
4647
- context.io.stdout("Logged out. Credentials removed.\n");
4648
- });
4649
- const notebook = program.command("notebook").description("Manage notebooks");
4650
- withCommon(notebook.command("create").description("Create a notebook")).option("--title <title>", "notebook title (required)").option("--desc <description>", "notebook description", "").action(async (raw) => {
4651
- render(context, raw, {
4652
- kind: "notebook",
4653
- value: await (await hostFor(context, raw)).client.createNotebook({
4654
- description: String(raw.desc ?? ""),
4655
- title: requiredString(raw.title, "--title")
4656
- })
4657
- });
4658
- });
4659
- 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) => {
4660
- const host = await hostFor(context, raw);
4661
- const client = optionalString(raw, "filterClient");
4662
- const pagination = {
4663
- ...raw.page === void 0 ? {} : { page: Number(raw.page) },
4664
- ...raw.pageSize === void 0 ? {} : { pageSize: Number(raw.pageSize) }
4665
- };
4666
- if (raw.shared === true) render(context, raw, {
4667
- kind: "sharedNotebookList",
4668
- value: await host.client.listSharedNotebooks(pagination)
4669
- });
4670
- else render(context, raw, {
4671
- kind: "notebookList",
4672
- value: await host.client.listNotebooks({
4673
- ...pagination,
4674
- ...client === void 0 ? {} : { client }
4675
- })
4676
- });
4677
- });
4678
- withCommon(notebook.command("get <notebook_id>").description("Get a notebook")).action(async (notebookId, raw) => {
4679
- render(context, raw, {
4680
- kind: "notebook",
4681
- value: await (await hostFor(context, raw)).client.getNotebook(notebookId)
4682
- });
4683
- });
4684
- withCommon(notebook.command("delete <notebook_id>").description("Delete a notebook"), false).action(async (notebookId, raw) => {
4685
- await (await hostFor(context, raw)).client.deleteNotebook(notebookId);
4686
- context.io.stdout("deleted\n");
4687
- });
4688
- 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) => {
4689
- const notebookIds = raw.nb;
4690
- const [notebookId] = notebookIds;
4691
- if (notebookId === void 0) throw new QMindError("INVALID_ARGUMENT", "--nb is required");
4692
- if (notebookIds.length > 5) throw new QMindError("INVALID_ARGUMENT", "--nb accepts at most 5 distinct notebook IDs");
4693
- const input = {
4694
- maxResults: numberOption(raw, "maxResults", 0),
4695
- query: requiredString(raw.query || query, "--query or positional query"),
4696
- sourceIds: splitCsv(stringOption(raw, "sources")),
4697
- topK: numberOption(raw, "topK", 0)
4698
- };
4699
- if (input.maxResults < 0 || input.topK < 0) throw new QMindError("INVALID_ARGUMENT", "--top-k and --max-results must be non-negative");
4700
- if (notebookIds.length > 1 && input.sourceIds.length > 0) throw new QMindError("INVALID_ARGUMENT", "--sources requires a single notebook");
4701
- const host = await hostFor(context, raw);
4702
- if (notebookIds.length === 1) {
4703
- render(context, raw, {
4704
- kind: "retrieve",
4705
- value: await host.client.retrieve(notebookId, input)
4706
- });
4707
- return;
4708
- }
4709
- render(context, raw, {
4710
- kind: "multiRetrieve",
4711
- value: await host.client.retrieveNotebooks({
4712
- query: input.query,
4713
- topK: input.topK,
4714
- maxResults: input.maxResults,
4715
- targets: notebookIds.map((notebookId) => ({ notebookId }))
4716
- })
4717
- });
4718
- });
4887
+ //#endregion
4888
+ //#region ../agent-core/src/scheduled-task-inputs.ts
4889
+ const id = z.string().trim().min(1).max(512);
4890
+ const scheduledTaskScene = z.enum([
4891
+ "compilation",
4892
+ "condensation",
4893
+ "lint",
4894
+ "source_refresh",
4895
+ "source_binding_sync"
4896
+ ]);
4897
+ const schedule = z.string().trim().min(1).max(512).refine((value) => {
4898
+ const fields = value.split(/\s+/u);
4899
+ const zone = /^(?:CRON_TZ|TZ)=(.+)$/u.exec(fields[0] ?? "")?.[1];
4900
+ if (!zone || !/^[A-Za-z][A-Za-z0-9_+/-]*$/u.test(zone) || fields.length !== 6 && fields.length !== 7) return false;
4901
+ try {
4902
+ new Intl.DateTimeFormat("en-US", { timeZone: zone }).format();
4903
+ return true;
4904
+ } catch {
4905
+ return false;
4906
+ }
4907
+ }, "schedule requires an explicit CRON_TZ/TZ IANA zone and five or six cron fields");
4908
+ const createScheduledTaskInputSchema = z.object({
4909
+ notebookId: id,
4910
+ sceneType: scheduledTaskScene,
4911
+ schedule
4912
+ }).strict();
4913
+ const updateScheduledTaskInputSchema = z.object({
4914
+ notebookId: id,
4915
+ taskId: id,
4916
+ schedule: schedule.optional(),
4917
+ enabled: z.boolean().optional()
4918
+ }).strict().refine((input) => input.schedule !== void 0 || input.enabled !== void 0, "Empty patch");
4919
+ const deleteScheduledTaskInputSchema = z.object({
4920
+ notebookId: id,
4921
+ taskId: id
4922
+ }).strict();
4923
+ const listScheduledTasksInputSchema = z.object({
4924
+ notebookId: id,
4925
+ taskId: id.optional(),
4926
+ sceneType: scheduledTaskScene.optional(),
4927
+ enabled: z.boolean().optional(),
4928
+ page: z.number().int().min(1).max(1e6).default(1),
4929
+ pageSize: z.number().int().min(1).max(20).default(20)
4930
+ }).strict();
4931
+ //#endregion
4932
+ //#region ../../node_modules/.pnpm/canonicalize@4.0.0/node_modules/canonicalize/lib/canonicalize.js
4933
+ function hasLoneSurrogate(value) {
4934
+ for (let i = 0; i < value.length; i++) {
4935
+ const code = value.charCodeAt(i);
4936
+ if (code >= 55296 && code <= 56319) {
4937
+ if (i === value.length - 1) return true;
4938
+ const next = value.charCodeAt(i + 1);
4939
+ if (!(next >= 56320 && next <= 57343)) return true;
4940
+ i++;
4941
+ } else if (code >= 56320 && code <= 57343) return true;
4942
+ }
4943
+ return false;
4719
4944
  }
4720
- function registerSourceCommands(context, program) {
4721
- const source = program.command("source").description("Manage notebook sources");
4722
- 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) => {
4723
- render(context, raw, {
4724
- kind: "source",
4725
- value: await (await hostFor(context, raw)).client.createSource(requiredString(raw.nb, "--nb"), {
4726
- isDir: raw.isDir === true ? true : void 0,
4727
- parentSourceId: String(raw.parent ?? ""),
4728
- path: String(raw.path ?? ""),
4729
- sourceType: String(raw.type ?? ""),
4730
- status: String(raw.status ?? ""),
4731
- title: requiredString(raw.title, "--title")
4732
- })
4733
- });
4734
- });
4735
- 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) => {
4736
- render(context, raw, {
4737
- kind: "source",
4738
- value: await (await hostFor(context, raw)).client.createDirectory(requiredString(raw.nb, "--nb"), {
4739
- parentSourceId: String(raw.parent ?? ""),
4740
- path: String(raw.path ?? ""),
4741
- title: requiredString(raw.title, "--title")
4742
- })
4743
- });
4744
- });
4745
- 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) => {
4746
- const host = await hostFor(context, raw);
4747
- const notebookId = requiredString(raw.nb, "--nb");
4748
- let value;
4749
- if (raw.all === true) {
4750
- const pageSize = positiveNumberOption(raw, "pageSize", 0) ?? 100;
4751
- value = { sources: await host.client.listAllSources(notebookId, {
4752
- maxPages: numberOption(raw, "maxPages", 1e4),
4753
- pageSize
4754
- }) };
4755
- } else {
4756
- const page = positiveNumberOption(raw, "page", 0);
4757
- const pageSize = positiveNumberOption(raw, "pageSize", 0);
4758
- value = await host.client.listSources(notebookId, {
4759
- ...page === void 0 ? {} : { page },
4760
- ...pageSize === void 0 ? {} : { pageSize }
4761
- });
4945
+ function canonicalize(object, seen = /* @__PURE__ */ new Set()) {
4946
+ if (typeof object === "number" && isNaN(object)) throw new Error("NaN is not allowed");
4947
+ if (typeof object === "number" && !isFinite(object)) throw new Error("Infinity is not allowed");
4948
+ if (typeof object === "string" && hasLoneSurrogate(object)) throw new Error("Lone surrogate is not allowed");
4949
+ if (object === null || typeof object !== "object") return JSON.stringify(object);
4950
+ if (typeof object.toJSON === "function") {
4951
+ if (seen.has(object)) throw new Error("Circular reference detected");
4952
+ seen.add(object);
4953
+ const result = canonicalize(object.toJSON(), seen);
4954
+ seen.delete(object);
4955
+ return result;
4956
+ }
4957
+ if (seen.has(object)) throw new Error("Circular reference detected");
4958
+ seen.add(object);
4959
+ let result;
4960
+ if (Array.isArray(object)) result = `[${object.map((cv) => {
4961
+ return canonicalize(cv === void 0 || typeof cv === "symbol" ? null : cv, seen);
4962
+ }).join(",")}]`;
4963
+ else {
4964
+ const parts = [];
4965
+ for (const key of Object.keys(object).sort()) {
4966
+ if (object[key] === void 0 || typeof object[key] === "symbol") continue;
4967
+ parts.push(`${canonicalize(key)}:${canonicalize(object[key], seen)}`);
4762
4968
  }
4763
- render(context, raw, {
4764
- kind: "sourceList",
4765
- value
4766
- });
4767
- });
4768
- withCommon(source.command("get <source_id>").description("Get a source")).option("--nb <id>", "notebook ID (required)").action(async (sourceId, raw) => {
4969
+ result = `{${parts.join(",")}}`;
4970
+ }
4971
+ seen.delete(object);
4972
+ return result;
4973
+ }
4974
+ //#endregion
4975
+ //#region ../agent-core/src/contract.ts
4976
+ const CONTRACT_VERSION = "6.0.0";
4977
+ const AGENT_ERROR_CODES = Object.freeze([
4978
+ "invalid_input",
4979
+ "selection_required",
4980
+ "not_found",
4981
+ "already_exists",
4982
+ "source_conflict",
4983
+ "quota_exceeded",
4984
+ "capability_unavailable",
4985
+ "source_not_ready",
4986
+ "source_unsupported",
4987
+ "source_failed",
4988
+ "unauthenticated",
4989
+ "permission_denied",
4990
+ "rate_limited",
4991
+ "upstream_unavailable",
4992
+ "timeout",
4993
+ "cancelled",
4994
+ "outcome_unknown",
4995
+ "internal",
4996
+ "source_deletion_failed"
4997
+ ]);
4998
+ const retryableCodes = /* @__PURE__ */ new Set([
4999
+ "source_not_ready",
5000
+ "rate_limited",
5001
+ "upstream_unavailable",
5002
+ "timeout"
5003
+ ]);
5004
+ function isRetryableAgentError(code) {
5005
+ return retryableCodes.has(code);
5006
+ }
5007
+ const opaqueId = z.string().trim().min(1).max(512);
5008
+ const page = z.number().int().min(1).default(1);
5009
+ const pageSize = z.number().int().min(1).max(50).default(20);
5010
+ const createNotebookInputSchema = z.object({
5011
+ title: z.string().trim().min(1).max(500),
5012
+ description: z.string().max(2e3).optional()
5013
+ }).strict();
5014
+ const deleteNotebookInputSchema = z.object({ notebookId: opaqueId }).strict();
5015
+ const listNotebooksInputSchema = z.object({
5016
+ page,
5017
+ pageSize,
5018
+ relationship: z.enum([
5019
+ "owned",
5020
+ "shared",
5021
+ "featured",
5022
+ "all"
5023
+ ]).optional(),
5024
+ cursor: z.string().min(1).max(512).optional()
5025
+ }).strict();
5026
+ const retrieveInputSchema = z.object({
5027
+ maxResults: z.number().int().min(1).max(50).default(8),
5028
+ notebookId: opaqueId.optional(),
5029
+ targets: z.array(z.object({
5030
+ notebookId: opaqueId,
5031
+ sourceIds: z.array(opaqueId).min(1).max(100).refine((ids) => new Set(ids).size === ids.length).optional()
5032
+ }).strict()).min(1).max(5).refine((targets) => new Set(targets.map((target) => target.notebookId)).size === targets.length).optional(),
5033
+ query: z.string().trim().min(1).max(2e3),
5034
+ scoreThreshold: z.number().min(0).max(1).optional(),
5035
+ sourceIds: z.array(opaqueId).min(1).max(50).refine((values) => new Set(values).size === values.length, { message: "sourceIds must be unique" }).optional(),
5036
+ topK: z.number().int().min(1).max(100).optional()
5037
+ }).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" });
5038
+ const listSourcesInputSchema = z.object({
5039
+ notebookId: opaqueId,
5040
+ page,
5041
+ pageSize,
5042
+ parentSourceId: opaqueId.optional()
5043
+ }).strict();
5044
+ const getSourceInputSchema = z.object({
5045
+ notebookId: opaqueId,
5046
+ sourceId: opaqueId
5047
+ }).strict();
5048
+ const readSourceInputSchema = z.object({
5049
+ maxChars: z.number().int().min(1).max(5e4).default(2e4),
5050
+ notebookId: opaqueId,
5051
+ offset: z.number().int().min(0).default(0),
5052
+ sourceId: opaqueId
5053
+ }).strict();
5054
+ const sourceInputSchema = z.discriminatedUnion("kind", [
5055
+ z.object({
5056
+ kind: z.literal("text"),
5057
+ content: z.string().min(1).max(2e6).refine((value) => value.trim().length > 0),
5058
+ title: z.string().trim().min(1).max(500)
5059
+ }).strict(),
5060
+ z.object({
5061
+ kind: z.literal("url"),
5062
+ title: z.string().trim().min(1).max(500).optional(),
5063
+ url: z.string().trim().url().max(4096).refine((value) => {
5064
+ const url = new URL(value);
5065
+ return url.protocol === "https:" && url.username.length === 0 && url.password.length === 0;
5066
+ }, { message: "url must use HTTPS without embedded credentials" })
5067
+ }).strict(),
5068
+ z.object({
5069
+ filePath: z.string().trim().min(1).max(4096),
5070
+ kind: z.literal("file"),
5071
+ title: z.string().trim().min(1).max(500).optional()
5072
+ }).strict()
5073
+ ]);
5074
+ const addSourceInputSchema = z.object({
5075
+ notebookId: opaqueId,
5076
+ source: sourceInputSchema,
5077
+ parentSourceId: opaqueId.optional(),
5078
+ path: z.string().trim().min(1).max(4096).optional()
5079
+ }).strict().refine((value) => !value.parentSourceId || !!value.path, { message: "parentSourceId requires a logical path" });
5080
+ const deleteSourceInputSchema = z.object({
5081
+ notebookId: opaqueId,
5082
+ sourceIds: z.array(opaqueId).min(1).max(100).refine((ids) => new Set(ids).size === ids.length)
5083
+ }).strict();
5084
+ const directoryName = z.string().trim().min(1).max(500).refine((value) => qmindSourceTitlePolicy(value).allowed, { message: "title must be one path segment" });
5085
+ const createDirectoryInputSchema = z.object({
5086
+ notebookId: opaqueId,
5087
+ title: directoryName,
5088
+ parentSourceId: opaqueId.optional()
5089
+ }).strict();
5090
+ const moveSourceInputSchema = z.object({
5091
+ notebookId: opaqueId,
5092
+ sourceId: opaqueId,
5093
+ targetParentSourceId: opaqueId.nullable()
5094
+ }).strict();
5095
+ const agentToolInputSchemas = Object.freeze({
5096
+ "qmind.update_source_content": z.object({
5097
+ notebookId: opaqueId,
5098
+ sourceId: opaqueId,
5099
+ content: z.string().min(1).max(2e6).refine((value) => value.trim().length > 0),
5100
+ title: z.string().trim().min(1).max(500).optional(),
5101
+ baseUpdatedAt: z.string().trim().min(1).max(128),
5102
+ baseContentHash: z.string().regex(/^[a-f0-9]{64}$/).optional()
5103
+ }).strict(),
5104
+ "qmind.refresh_source": getSourceInputSchema,
5105
+ "qmind.list_task_runs": z.object({
5106
+ notebookId: opaqueId,
5107
+ sourceId: opaqueId.optional(),
5108
+ page,
5109
+ pageSize
5110
+ }).strict(),
5111
+ "qmind.create_notebook": createNotebookInputSchema,
5112
+ "qmind.delete_notebook": deleteNotebookInputSchema,
5113
+ "qmind.create_scheduled_task": createScheduledTaskInputSchema,
5114
+ "qmind.update_scheduled_task": updateScheduledTaskInputSchema,
5115
+ "qmind.delete_scheduled_task": deleteScheduledTaskInputSchema,
5116
+ "qmind.list_scheduled_tasks": listScheduledTasksInputSchema,
5117
+ "qmind.create_directory": createDirectoryInputSchema,
5118
+ "qmind.move_source": moveSourceInputSchema,
5119
+ "qmind.add_source": addSourceInputSchema,
5120
+ "qmind.delete_source": deleteSourceInputSchema,
5121
+ "qmind.get_source": getSourceInputSchema,
5122
+ "qmind.list_notebooks": listNotebooksInputSchema,
5123
+ "qmind.list_sources": listSourcesInputSchema,
5124
+ "qmind.read_source": readSourceInputSchema,
5125
+ "qmind.retrieve": retrieveInputSchema
5126
+ });
5127
+ const agentToolDefinitions = Object.freeze([
5128
+ {
5129
+ id: "qmind.update_source_content",
5130
+ leaf: "update_source_content",
5131
+ intent: "write",
5132
+ destructive: true,
5133
+ deadlineMs: 12e4,
5134
+ description: "Update source text using baseUpdatedAt from a fresh read and optionally a SHA-256 content snapshot. This preflight is not atomic compare-and-swap. Then request source refresh. Partial success means the content was saved; never rewrite it to retry refresh. Reconcile outcome_unknown before any new write."
5135
+ },
5136
+ {
5137
+ id: "qmind.refresh_source",
5138
+ leaf: "refresh_source",
5139
+ intent: "write",
5140
+ deadlineMs: 3e4,
5141
+ description: "Request a source_refresh task for an existing source. Success acknowledges task creation, not completed ingestion. Observe list_task_runs. Never replay an unknown task creation automatically."
5142
+ },
5143
+ {
5144
+ id: "qmind.list_task_runs",
5145
+ leaf: "list_task_runs",
5146
+ intent: "read",
5147
+ deadlineMs: 3e4,
5148
+ description: "List remote QMind task executions, optionally for one source. These are not host edit sessions or Agent operation IDs. Paginated results report observed upstream state, not a new execution."
5149
+ },
5150
+ {
5151
+ deadlineMs: 3e4,
5152
+ 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.",
5153
+ id: "qmind.create_notebook",
5154
+ intent: "write",
5155
+ leaf: "create_notebook"
5156
+ },
5157
+ {
5158
+ deadlineMs: 3e4,
5159
+ 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.",
5160
+ id: "qmind.delete_notebook",
5161
+ intent: "write",
5162
+ destructive: true,
5163
+ leaf: "delete_notebook"
5164
+ },
5165
+ {
5166
+ deadlineMs: 6e4,
5167
+ 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.",
5168
+ id: "qmind.retrieve",
5169
+ intent: "read",
5170
+ leaf: "retrieve"
5171
+ },
5172
+ {
5173
+ deadlineMs: 3e4,
5174
+ description: "Discover QMind notebooks using summary/topics and relationship (owned/shared/featured). The host can default to owned plus shared plus Featured; 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 then Featured, 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.",
5175
+ id: "qmind.list_notebooks",
5176
+ intent: "read",
5177
+ leaf: "list_notebooks"
5178
+ },
5179
+ {
5180
+ deadlineMs: 3e4,
5181
+ description: "List sources in a QMind notebook.",
5182
+ id: "qmind.list_sources",
5183
+ intent: "read",
5184
+ leaf: "list_sources"
5185
+ },
5186
+ {
5187
+ deadlineMs: 3e4,
5188
+ description: "Get one source in a QMind notebook.",
5189
+ id: "qmind.get_source",
5190
+ intent: "read",
5191
+ leaf: "get_source"
5192
+ },
5193
+ {
5194
+ deadlineMs: 6e4,
5195
+ description: "Read a bounded slice of a ready QMind source.",
5196
+ id: "qmind.read_source",
5197
+ intent: "read",
5198
+ leaf: "read_source"
5199
+ },
5200
+ {
5201
+ deadlineMs: 12e4,
5202
+ description: "Add an HTTPS URL, authorized local file, or UTF-8 Markdown text to QMind. Text requires title and content; filePath must be readable by the host. parentSourceId requires a logical path. Success means source creation, not completed ingestion. Never replay outcome_unknown automatically.",
5203
+ id: "qmind.add_source",
5204
+ intent: "write",
5205
+ leaf: "add_source"
5206
+ },
5207
+ {
5208
+ deadlineMs: 3e4,
5209
+ 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.",
5210
+ id: "qmind.delete_source",
5211
+ intent: "write",
5212
+ destructive: true,
5213
+ leaf: "delete_source"
5214
+ },
5215
+ {
5216
+ deadlineMs: 3e4,
5217
+ 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.",
5218
+ id: "qmind.create_directory",
5219
+ intent: "write",
5220
+ leaf: "create_directory"
5221
+ },
5222
+ {
5223
+ deadlineMs: 3e4,
5224
+ 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.",
5225
+ id: "qmind.move_source",
5226
+ intent: "write",
5227
+ destructive: true,
5228
+ leaf: "move_source"
5229
+ },
5230
+ {
5231
+ deadlineMs: 3e4,
5232
+ 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.",
5233
+ id: "qmind.create_scheduled_task",
5234
+ intent: "write",
5235
+ leaf: "create_scheduled_task"
5236
+ },
5237
+ {
5238
+ deadlineMs: 3e4,
5239
+ 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.",
5240
+ id: "qmind.update_scheduled_task",
5241
+ intent: "write",
5242
+ destructive: true,
5243
+ leaf: "update_scheduled_task"
5244
+ },
5245
+ {
5246
+ deadlineMs: 3e4,
5247
+ 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.",
5248
+ id: "qmind.delete_scheduled_task",
5249
+ intent: "write",
5250
+ destructive: true,
5251
+ leaf: "delete_scheduled_task"
5252
+ },
5253
+ {
5254
+ deadlineMs: 3e4,
5255
+ 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.",
5256
+ id: "qmind.list_scheduled_tasks",
5257
+ intent: "read",
5258
+ leaf: "list_scheduled_tasks"
5259
+ }
5260
+ ]);
5261
+ function deadlineFor(toolId, input) {
5262
+ 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;
5263
+ return agentToolDefinitions.find((tool) => tool.id === toolId)?.deadlineMs ?? 3e4;
5264
+ }
5265
+ function deepFreeze(value) {
5266
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
5267
+ for (const nested of Object.values(value)) deepFreeze(nested);
5268
+ return Object.freeze(value);
5269
+ }
5270
+ const canonicalDescriptor = canonicalize(deepFreeze({
5271
+ contractVersion: CONTRACT_VERSION,
5272
+ definitions: {
5273
+ TaskRun: {
5274
+ id: "opaqueId",
5275
+ notebookId: "opaqueId",
5276
+ sourceId: "opaqueId?",
5277
+ sceneType: "string",
5278
+ status: "pending|running|completed|failed|cancelled|unknown",
5279
+ createdAt: "iso8601?",
5280
+ finishedAt: "iso8601?"
5281
+ },
5282
+ ScheduledTask: {
5283
+ id: "opaqueId",
5284
+ notebookId: "opaqueId",
5285
+ sceneType: "compilation|condensation|lint|source_refresh|source_binding_sync",
5286
+ schedule: "string:1..512",
5287
+ enabled: "boolean",
5288
+ nextRunAt: "iso8601",
5289
+ lastRunAt: "iso8601|empty",
5290
+ createdAt: "iso8601|empty",
5291
+ updatedAt: "iso8601|empty",
5292
+ config: "object; omitted contents if JSON exceeds 2000 UTF-8 bytes",
5293
+ configTruncated: "boolean"
5294
+ },
5295
+ SourceDeletionTarget: {
5296
+ sourceId: "opaqueId",
5297
+ title: "string",
5298
+ scope: "source|subtree",
5299
+ revision: "sha256"
5300
+ },
5301
+ Source: {
5302
+ createdAt: "iso8601?",
5303
+ errorCode: "source_unsupported|source_failed?",
5304
+ id: "opaqueId",
5305
+ isDir: "boolean",
5306
+ notebookId: "opaqueId",
5307
+ parentSourceId: "opaqueId?",
5308
+ path: "string?",
5309
+ sourceType: "string",
5310
+ status: "pending|processing|ready|unsupported|failed",
5311
+ title: "string",
5312
+ updatedAt: "iso8601?"
5313
+ }
5314
+ },
5315
+ errorCatalog: AGENT_ERROR_CODES.map((code) => ({
5316
+ code,
5317
+ retryable: isRetryableAgentError(code),
5318
+ ...code === "source_deletion_failed" ? { details: {
5319
+ successCount: "0",
5320
+ failureCount: "integer:1..100"
5321
+ } } : {}
5322
+ })),
5323
+ invocation: {
5324
+ defaultRetrievalMode: "all?; explicit host opt-in searches each authorized target with concurrency at most 3 and bounded partial results",
5325
+ defaultNotebookRelationship: "owned|shared|featured|all?; host discovery default independent of notebookPolicy; omitted means owned",
5326
+ approvedDeletionTargets: "SourceDeletionTarget[1..100]?; host-only, must match fresh targets",
5327
+ notebookPolicy: { selectNotebook: "host callback: excluded|allowed|preferred; request-local; intersects server ACL" },
5328
+ notebookScope: {
5329
+ allowedNotebookIds: "uniqueOpaqueId[]",
5330
+ preferredNotebookIds: "uniqueOpaqueId[]?; subset of allowedNotebookIds",
5331
+ enforcement: "all-tools-before-qmind-client-call",
5332
+ omitted: "authenticated-account-scope",
5333
+ present: "restricted-upper-bound"
5334
+ }
5335
+ },
5336
+ lifecycle: {
5337
+ finished: {
5338
+ fields: [
5339
+ "eventId",
5340
+ "operationId",
5341
+ "toolId",
5342
+ "intent",
5343
+ "occurredAt",
5344
+ "outcome",
5345
+ "durationMs",
5346
+ "notebookIds?",
5347
+ "partial?",
5348
+ "warningCodes?",
5349
+ "errorCode?"
5350
+ ],
5351
+ outcomes: [
5352
+ "succeeded",
5353
+ "failed",
5354
+ "cancelled",
5355
+ "outcome_unknown"
5356
+ ],
5357
+ type: "qmind.operation.finished"
5358
+ },
5359
+ started: {
5360
+ fields: [
5361
+ "eventId",
5362
+ "operationId",
5363
+ "toolId",
5364
+ "intent",
5365
+ "occurredAt"
5366
+ ],
5367
+ type: "qmind.operation.started"
5368
+ }
5369
+ },
5370
+ resultEnvelope: {
5371
+ failure: [
5372
+ "ok",
5373
+ "error.code",
5374
+ "error.message",
5375
+ "error.retryable",
5376
+ "error.details?",
5377
+ "meta.operationId"
5378
+ ],
5379
+ success: [
5380
+ "ok",
5381
+ "data",
5382
+ "meta.operationId",
5383
+ "meta.partial?",
5384
+ "meta.warnings?"
5385
+ ]
5386
+ },
5387
+ tools: [
5388
+ {
5389
+ id: "qmind.update_source_content",
5390
+ intent: "write",
5391
+ timeoutMs: 12e4,
5392
+ annotations: {
5393
+ destructiveHint: true,
5394
+ idempotentHint: false,
5395
+ openWorldHint: true,
5396
+ readOnlyHint: false
5397
+ },
5398
+ input: {
5399
+ notebookId: "opaqueId",
5400
+ sourceId: "opaqueId",
5401
+ content: "nonblank-string:1..2000000",
5402
+ title: "string:1..500?",
5403
+ baseUpdatedAt: "string:1..128",
5404
+ baseContentHash: "sha256?"
5405
+ },
5406
+ output: {
5407
+ sourceId: "opaqueId",
5408
+ contentUpdated: true,
5409
+ refresh: "accepted|failed|outcome_unknown",
5410
+ taskRun: "TaskRun?"
5411
+ }
5412
+ },
5413
+ {
5414
+ id: "qmind.refresh_source",
5415
+ intent: "write",
5416
+ timeoutMs: 3e4,
5417
+ annotations: {
5418
+ destructiveHint: false,
5419
+ idempotentHint: false,
5420
+ openWorldHint: true,
5421
+ readOnlyHint: false
5422
+ },
5423
+ input: {
5424
+ notebookId: "opaqueId",
5425
+ sourceId: "opaqueId"
5426
+ },
5427
+ output: "TaskRun"
5428
+ },
5429
+ {
5430
+ id: "qmind.list_task_runs",
5431
+ intent: "read",
5432
+ timeoutMs: 3e4,
5433
+ annotations: {
5434
+ destructiveHint: false,
5435
+ idempotentHint: true,
5436
+ openWorldHint: true,
5437
+ readOnlyHint: true
5438
+ },
5439
+ input: {
5440
+ notebookId: "opaqueId",
5441
+ sourceId: "opaqueId?",
5442
+ page: "integer:1..?",
5443
+ pageSize: "integer:1..50?"
5444
+ },
5445
+ output: {
5446
+ runs: ["TaskRun"],
5447
+ totalSize: "integer:0..",
5448
+ page: "integer:1..",
5449
+ pageSize: "integer:1..50"
5450
+ }
5451
+ },
5452
+ {
5453
+ annotations: {
5454
+ destructiveHint: false,
5455
+ idempotentHint: false,
5456
+ openWorldHint: true,
5457
+ readOnlyHint: false
5458
+ },
5459
+ id: "qmind.create_notebook",
5460
+ intent: "write",
5461
+ input: {
5462
+ title: "trimmed-string:1..500",
5463
+ description: "string:0..2000?"
5464
+ },
5465
+ output: {
5466
+ id: "opaqueId",
5467
+ title: "string",
5468
+ description: "string"
5469
+ },
5470
+ scope: "requires omitted notebookScope and notebookPolicy; does not bind or expand scope",
5471
+ timeoutMs: 3e4
5472
+ },
5473
+ {
5474
+ annotations: {
5475
+ destructiveHint: true,
5476
+ idempotentHint: false,
5477
+ openWorldHint: true,
5478
+ readOnlyHint: false
5479
+ },
5480
+ id: "qmind.delete_notebook",
5481
+ intent: "write",
5482
+ input: { notebookId: "opaqueId" },
5483
+ output: {
5484
+ notebookId: "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
+ defaults: { maxResults: 8 },
5497
+ id: "qmind.retrieve",
5498
+ input: {
5499
+ maxResults: "integer:1..50?",
5500
+ notebookId: "opaqueId?; exclusive with targets",
5501
+ targets: "[{notebookId, sourceIds?}][1..5]?; unique notebooks",
5502
+ query: "string:1..2000",
5503
+ scoreThreshold: "number:0..1?",
5504
+ sourceIds: "uniqueOpaqueId[1..50]?",
5505
+ topK: "integer:1..100?"
5506
+ },
5507
+ intent: "read",
5508
+ output: {
5509
+ chunks: [{
5510
+ chunkId: "opaqueId",
5511
+ chunkIndex: "integer:0..",
5512
+ content: "string",
5513
+ notebookId: "opaqueId",
5514
+ notebookTitle: "string",
5515
+ originUrl: "string?",
5516
+ score: "number",
5517
+ sourceId: "opaqueId",
5518
+ sourceTitle: "string",
5519
+ tokenCount: "integer:0..",
5520
+ lineStart: "positiveInteger?; validated chunk or matching citation metadata",
5521
+ lineEnd: "positiveInteger?; at least lineStart"
5522
+ }],
5523
+ promptContext: "string",
5524
+ reranked: "boolean",
5525
+ total: "integer:0.."
5526
+ },
5527
+ timeoutMs: 6e4
5528
+ },
5529
+ {
5530
+ annotations: {
5531
+ destructiveHint: false,
5532
+ idempotentHint: true,
5533
+ openWorldHint: true,
5534
+ readOnlyHint: true
5535
+ },
5536
+ defaults: {
5537
+ page: 1,
5538
+ pageSize: 20
5539
+ },
5540
+ discovery: { eligibility: "server filters before pagination; deploy server and gateway before clients" },
5541
+ id: "qmind.list_notebooks",
5542
+ input: {
5543
+ page: "integer:1..?",
5544
+ pageSize: "integer:1..50?",
5545
+ relationship: "owned|shared|featured|all?",
5546
+ cursor: "opaqueString?; continuation for filtered discovery"
5547
+ },
5548
+ intent: "read",
5549
+ output: {
5550
+ notebooks: [{
5551
+ description: "string?",
5552
+ id: "opaqueId",
5553
+ materialCount: "integer",
5554
+ sourceCount: "integer",
5555
+ status: "string",
5556
+ preferred: "boolean",
5557
+ relationship: "owned|shared|featured?",
5558
+ summary: "string?",
5559
+ title: "string",
5560
+ topics: "string[]?",
5561
+ updatedAt: "iso8601?"
5562
+ }],
5563
+ page: "integer:1..; legacy listing only",
5564
+ pageSize: "integer:1..50",
5565
+ totalSize: "integer:0..; legacy listing only",
5566
+ hasMore: "boolean; discovery only",
5567
+ nextCursor: "opaqueString?; discovery continuation",
5568
+ retrievalSelection: "{maxTargets:5, overviewSelectionRequired:boolean}"
5569
+ },
5570
+ timeoutMs: 3e4
5571
+ },
5572
+ {
5573
+ annotations: {
5574
+ destructiveHint: false,
5575
+ idempotentHint: true,
5576
+ openWorldHint: true,
5577
+ readOnlyHint: true
5578
+ },
5579
+ defaults: {
5580
+ page: 1,
5581
+ pageSize: 20
5582
+ },
5583
+ id: "qmind.list_sources",
5584
+ input: {
5585
+ notebookId: "opaqueId",
5586
+ page: "integer:1..?",
5587
+ pageSize: "integer:1..50?",
5588
+ parentSourceId: "opaqueId?"
5589
+ },
5590
+ intent: "read",
5591
+ output: {
5592
+ page: "integer:1..",
5593
+ pageSize: "integer:1..50",
5594
+ sources: ["Source"],
5595
+ totalSize: "integer:0..?"
5596
+ },
5597
+ timeoutMs: 3e4
5598
+ },
5599
+ {
5600
+ annotations: {
5601
+ destructiveHint: false,
5602
+ idempotentHint: true,
5603
+ openWorldHint: true,
5604
+ readOnlyHint: true
5605
+ },
5606
+ id: "qmind.get_source",
5607
+ input: {
5608
+ notebookId: "opaqueId",
5609
+ sourceId: "opaqueId"
5610
+ },
5611
+ intent: "read",
5612
+ output: "Source & { deletion: SourceDeletionTarget }",
5613
+ timeoutMs: 3e4
5614
+ },
5615
+ {
5616
+ annotations: {
5617
+ destructiveHint: false,
5618
+ idempotentHint: true,
5619
+ openWorldHint: true,
5620
+ readOnlyHint: true
5621
+ },
5622
+ defaults: {
5623
+ maxChars: 2e4,
5624
+ offset: 0
5625
+ },
5626
+ id: "qmind.read_source",
5627
+ input: {
5628
+ maxChars: "integer:1..50000?",
5629
+ notebookId: "opaqueId",
5630
+ offset: "integer:0..?",
5631
+ sourceId: "opaqueId"
5632
+ },
5633
+ intent: "read",
5634
+ output: {
5635
+ content: "string:0..50000",
5636
+ contentType: "string",
5637
+ nextOffset: "integer:0..?",
5638
+ sourceId: "opaqueId",
5639
+ truncated: "boolean"
5640
+ },
5641
+ timeoutMs: 6e4
5642
+ },
5643
+ {
5644
+ annotations: {
5645
+ destructiveHint: false,
5646
+ idempotentHint: false,
5647
+ openWorldHint: true,
5648
+ readOnlyHint: false
5649
+ },
5650
+ id: "qmind.add_source",
5651
+ input: {
5652
+ notebookId: "opaqueId",
5653
+ source: [
5654
+ {
5655
+ kind: "url",
5656
+ title: "string:1..500?",
5657
+ url: "credential-free-https:1..4096"
5658
+ },
5659
+ {
5660
+ filePath: "string:1..4096",
5661
+ kind: "file",
5662
+ title: "string:1..500?"
5663
+ },
5664
+ {
5665
+ kind: "text",
5666
+ title: "string:1..500",
5667
+ content: "nonblank-string:1..2000000"
5668
+ }
5669
+ ]
5670
+ },
5671
+ intent: "write",
5672
+ output: "Source",
5673
+ timeoutMs: {
5674
+ file: 3e5,
5675
+ url: 12e4,
5676
+ text: 12e4
5677
+ }
5678
+ },
5679
+ {
5680
+ annotations: {
5681
+ destructiveHint: true,
5682
+ idempotentHint: false,
5683
+ openWorldHint: true,
5684
+ readOnlyHint: false
5685
+ },
5686
+ id: "qmind.delete_source",
5687
+ input: {
5688
+ notebookId: "opaqueId",
5689
+ sourceIds: "uniqueOpaqueId[1..100]"
5690
+ },
5691
+ intent: "write",
5692
+ output: {
5693
+ notebookId: "opaqueId",
5694
+ sourceIds: "uniqueOpaqueId[1..100]",
5695
+ successCount: "integer:0..",
5696
+ failureCount: "integer:0.."
5697
+ },
5698
+ timeoutMs: 3e4
5699
+ },
5700
+ {
5701
+ annotations: {
5702
+ destructiveHint: false,
5703
+ idempotentHint: false,
5704
+ openWorldHint: true,
5705
+ readOnlyHint: false
5706
+ },
5707
+ id: "qmind.create_directory",
5708
+ input: {
5709
+ notebookId: "opaqueId",
5710
+ title: "single-path-segment:1..500; trimmed",
5711
+ parentSourceId: "opaqueId?; omitted means root"
5712
+ },
5713
+ intent: "write",
5714
+ output: "Source",
5715
+ timeoutMs: 3e4
5716
+ },
5717
+ {
5718
+ annotations: {
5719
+ destructiveHint: true,
5720
+ idempotentHint: false,
5721
+ openWorldHint: true,
5722
+ readOnlyHint: false
5723
+ },
5724
+ id: "qmind.move_source",
5725
+ input: {
5726
+ notebookId: "opaqueId",
5727
+ sourceId: "opaqueId",
5728
+ targetParentSourceId: "opaqueId|null; required, null means root"
5729
+ },
5730
+ intent: "write",
5731
+ output: "Source",
5732
+ timeoutMs: 3e4
5733
+ },
5734
+ {
5735
+ annotations: {
5736
+ destructiveHint: false,
5737
+ idempotentHint: false,
5738
+ openWorldHint: true,
5739
+ readOnlyHint: false
5740
+ },
5741
+ id: "qmind.create_scheduled_task",
5742
+ intent: "write",
5743
+ input: {
5744
+ notebookId: "opaqueId",
5745
+ sceneType: "ScheduledTask.sceneType",
5746
+ schedule: "explicit-IANA-zone-prefixed-cron:1..512; server validates syntax and scene interval"
5747
+ },
5748
+ output: "ScheduledTask; enabled=true",
5749
+ timeoutMs: 3e4
5750
+ },
5751
+ {
5752
+ annotations: {
5753
+ destructiveHint: true,
5754
+ idempotentHint: false,
5755
+ openWorldHint: true,
5756
+ readOnlyHint: false
5757
+ },
5758
+ id: "qmind.update_scheduled_task",
5759
+ intent: "write",
5760
+ input: {
5761
+ notebookId: "opaqueId",
5762
+ taskId: "opaqueId",
5763
+ schedule: "explicit-IANA-zone-prefixed-cron:1..512?",
5764
+ enabled: "boolean?; at least one patch field"
5765
+ },
5766
+ output: "ScheduledTask",
5767
+ timeoutMs: 3e4
5768
+ },
5769
+ {
5770
+ annotations: {
5771
+ destructiveHint: true,
5772
+ idempotentHint: false,
5773
+ openWorldHint: true,
5774
+ readOnlyHint: false
5775
+ },
5776
+ id: "qmind.delete_scheduled_task",
5777
+ intent: "write",
5778
+ input: {
5779
+ notebookId: "opaqueId",
5780
+ taskId: "opaqueId"
5781
+ },
5782
+ output: {
5783
+ notebookId: "opaqueId",
5784
+ taskId: "opaqueId",
5785
+ deleted: true
5786
+ },
5787
+ timeoutMs: 3e4
5788
+ },
5789
+ {
5790
+ annotations: {
5791
+ destructiveHint: false,
5792
+ idempotentHint: true,
5793
+ openWorldHint: true,
5794
+ readOnlyHint: true
5795
+ },
5796
+ id: "qmind.list_scheduled_tasks",
5797
+ intent: "read",
5798
+ input: {
5799
+ notebookId: "opaqueId",
5800
+ taskId: "opaqueId?",
5801
+ sceneType: "ScheduledTask.sceneType?",
5802
+ enabled: "boolean?",
5803
+ page: "integer:1..1000000?",
5804
+ pageSize: "integer:1..20?"
5805
+ },
5806
+ output: {
5807
+ tasks: ["ScheduledTask"],
5808
+ page: "integer:1..1000000",
5809
+ pageSize: "integer:1..20",
5810
+ totalSize: "integer:0..",
5811
+ hasMore: "boolean"
5812
+ },
5813
+ timeoutMs: 3e4,
5814
+ defaults: {
5815
+ page: 1,
5816
+ pageSize: 20
5817
+ }
5818
+ }
5819
+ ],
5820
+ warningCatalog: [
5821
+ {
5822
+ code: "source_refresh_failed",
5823
+ fields: ["code", "notebookId"]
5824
+ },
5825
+ {
5826
+ code: "source_refresh_unknown",
5827
+ fields: ["code", "notebookId"]
5828
+ },
5829
+ {
5830
+ code: "notebook_search_failed",
5831
+ fields: ["code", "notebookId"]
5832
+ },
5833
+ {
5834
+ code: "source_deletion_failed",
5835
+ fields: ["code", "notebookId"]
5836
+ }
5837
+ ]
5838
+ }));
5839
+ if (canonicalDescriptor === void 0) throw new Error("QMind Agent Contract is not serializable");
5840
+ createHash("sha256").update(canonicalDescriptor, "utf8").digest("hex");
5841
+ //#endregion
5842
+ //#region ../agent-core/src/client-operation.ts
5843
+ function failure$1(operationId, code, message) {
5844
+ return {
5845
+ error: {
5846
+ code,
5847
+ message,
5848
+ retryable: isRetryableAgentError(code)
5849
+ },
5850
+ meta: { operationId },
5851
+ ok: false
5852
+ };
5853
+ }
5854
+ function errorCode(error, mutationStarted = false) {
5855
+ if (typeof error === "object" && error !== null) {
5856
+ const candidate = error;
5857
+ if (candidate.upstreamCode === "NotebookSourceQuotaExceeded") return "quota_exceeded";
5858
+ if (candidate.code === "AUTH_REQUIRED") return "unauthenticated";
5859
+ if (candidate.code === "FORBIDDEN") return "permission_denied";
5860
+ if (candidate.code === "NOT_FOUND") return "not_found";
5861
+ if (candidate.code === "CONFLICT") return "already_exists";
5862
+ if (candidate.code === "RATE_LIMITED") return "rate_limited";
5863
+ if (candidate.code === "UNSUPPORTED_OPERATION") return "capability_unavailable";
5864
+ if (candidate.status === 408) return mutationStarted ? "outcome_unknown" : "timeout";
5865
+ if (candidate.code === "FILE_TOO_LARGE" || candidate.code === "INVALID_ARGUMENT") return "invalid_input";
5866
+ if (candidate.code === "TIMEOUT") return mutationStarted ? "outcome_unknown" : "timeout";
5867
+ if (candidate.name === "TimeoutError") return mutationStarted ? "outcome_unknown" : "timeout";
5868
+ if (candidate.code === "ABORTED" || candidate.name === "AbortError") return mutationStarted ? "outcome_unknown" : "cancelled";
5869
+ if (candidate.code === "NETWORK_ERROR" || candidate.code === "REMOTE_ERROR") return mutationStarted ? "outcome_unknown" : "upstream_unavailable";
5870
+ }
5871
+ return "internal";
5872
+ }
5873
+ /**
5874
+ * Per-call options forwarded to every client method: the operation signal plus, when the host
5875
+ * pushed a per-operation identity, its bearer token as the request authorization override.
5876
+ */
5877
+ function callOptions(invocation) {
5878
+ invocation.assertCurrent?.();
5879
+ return {
5880
+ ...invocation.token === void 0 ? {} : { authorization: invocation.token },
5881
+ signal: invocation.signal
5882
+ };
5883
+ }
5884
+ //#endregion
5885
+ //#region ../agent-core/src/organizationPolicy.ts
5886
+ /** 企业策略仅保留白名单业务含义,不暴露上游正文。 */
5887
+ function qmindOrganizationPolicyError(error) {
5888
+ if (typeof error !== "object" || error === null || !("upstreamCode" in error)) return void 0;
5889
+ if (error.upstreamCode === "QMindPolicyUnavailable") return {
5890
+ code: "upstream_unavailable",
5891
+ message: "知识库管控服务暂时不可用,请稍后重试。",
5892
+ retryable: true
5893
+ };
5894
+ if (error.upstreamCode !== "QMindDisabledByOrganization") return void 0;
5895
+ return {
5896
+ code: "permission_denied",
5897
+ message: "企业管理员已禁用知识库功能,暂时无法使用。请联系企业管理员开启知识库功能后再试;重复调用无法恢复访问。",
5898
+ retryable: false
5899
+ };
5900
+ }
5901
+ //#endregion
5902
+ //#region ../agent-core/src/source-content.ts
5903
+ function taskData$1(run) {
5904
+ return {
5905
+ id: run.id,
5906
+ notebookId: run.notebookId,
5907
+ sourceId: run.sourceId,
5908
+ sceneType: run.sceneType,
5909
+ status: run.status,
5910
+ createdAt: run.createdAt,
5911
+ finishedAt: run.finishedAt
5912
+ };
5913
+ }
5914
+ function mutationFailure(error, invocation) {
5915
+ const policy = qmindOrganizationPolicyError(error);
5916
+ if (policy) return {
5917
+ ok: false,
5918
+ error: policy,
5919
+ meta: { operationId: invocation.operationId }
5920
+ };
5921
+ const code = errorCode(error, true);
5922
+ return failure$1(invocation.operationId, code === "internal" ? "outcome_unknown" : code, "The source operation did not return a confirmed result. Reconcile before another write.");
5923
+ }
5924
+ async function refreshSource(client, input, invocation) {
5925
+ if (!client.createTaskRun) return failure$1(invocation.operationId, "capability_unavailable", "Source refresh is unavailable.");
5926
+ const options = callOptions(invocation);
5927
+ invocation.signal?.throwIfAborted();
5928
+ try {
5929
+ const run = await client.createTaskRun(input.notebookId, {
5930
+ sceneType: "source_refresh",
5931
+ trigger: "manual",
5932
+ sourceId: input.sourceId
5933
+ }, options);
5934
+ if (!run.id || run.notebookId !== input.notebookId || run.sourceId !== input.sourceId) throw new TypeError("Unconfirmed source refresh.");
5935
+ return {
5936
+ ok: true,
5937
+ data: taskData$1(run),
5938
+ meta: { operationId: invocation.operationId }
5939
+ };
5940
+ } catch (error) {
5941
+ return mutationFailure(error, invocation);
5942
+ }
5943
+ }
5944
+ async function listTaskRuns(client, input, invocation) {
5945
+ if (!client.listTaskRuns) return failure$1(invocation.operationId, "capability_unavailable", "Task history is unavailable.");
5946
+ const result = await client.listTaskRuns(input.notebookId, {
5947
+ page: input.page,
5948
+ pageSize: input.pageSize,
5949
+ ...input.sourceId === void 0 ? {} : { sourceId: input.sourceId }
5950
+ }, callOptions(invocation));
5951
+ return {
5952
+ ok: true,
5953
+ data: {
5954
+ runs: result.runs.map(taskData$1),
5955
+ totalSize: result.totalSize,
5956
+ page: input.page,
5957
+ pageSize: input.pageSize
5958
+ },
5959
+ meta: { operationId: invocation.operationId }
5960
+ };
5961
+ }
5962
+ async function updateSourceContent(client, input, invocation) {
5963
+ if (!client.updateSource || !client.createTaskRun) return failure$1(invocation.operationId, "capability_unavailable", "Source writeback is unavailable.");
5964
+ const current = await client.getSource(input.notebookId, input.sourceId, callOptions(invocation));
5965
+ if (current.isDir) return failure$1(invocation.operationId, "invalid_input", "Directory content cannot be updated.");
5966
+ if (current.updatedAt !== input.baseUpdatedAt) return failure$1(invocation.operationId, "source_conflict", "Source changed; read it before editing.");
5967
+ if (input.baseContentHash !== void 0) {
5968
+ const content = await client.getSourceContent(input.notebookId, input.sourceId, callOptions(invocation));
5969
+ if (createHash("sha256").update(content.content).digest("hex") !== input.baseContentHash) return failure$1(invocation.operationId, "source_conflict", "Source content changed before editing.");
5970
+ }
5971
+ invocation.signal?.throwIfAborted();
5972
+ const options = callOptions(invocation);
5973
+ let updated;
5974
+ try {
5975
+ updated = await client.updateSource(input.notebookId, input.sourceId, {
5976
+ content: input.content,
5977
+ sourceType: "markdown",
5978
+ status: "ready",
5979
+ ...input.title === void 0 ? {} : { title: input.title }
5980
+ }, options);
5981
+ if (updated.id !== input.sourceId || updated.notebookId !== input.notebookId) throw new TypeError("Unconfirmed source update.");
5982
+ } catch (error) {
5983
+ return mutationFailure(error, invocation);
5984
+ }
5985
+ let refresh;
5986
+ try {
5987
+ refresh = await refreshSource(client, input, invocation);
5988
+ } catch (error) {
5989
+ refresh = failure$1(invocation.operationId, errorCode(error), "Refresh was not submitted.");
5990
+ }
5991
+ const unknown = !refresh.ok && refresh.error.code === "outcome_unknown";
5992
+ return {
5993
+ ok: true,
5994
+ data: {
5995
+ notebookId: input.notebookId,
5996
+ sourceId: updated.id,
5997
+ title: updated.title,
5998
+ updatedAt: updated.updatedAt,
5999
+ contentUpdated: true,
6000
+ refresh: refresh.ok ? "accepted" : unknown ? "outcome_unknown" : "failed",
6001
+ ...refresh.ok ? { taskRun: refresh.data } : {}
6002
+ },
6003
+ meta: {
6004
+ operationId: invocation.operationId,
6005
+ ...!refresh.ok ? {
6006
+ partial: true,
6007
+ warnings: [{
6008
+ code: unknown ? "source_refresh_unknown" : "source_refresh_failed",
6009
+ notebookId: input.notebookId
6010
+ }]
6011
+ } : {}
6012
+ }
6013
+ };
6014
+ }
6015
+ //#endregion
6016
+ //#region ../agent-core/src/notebook-mutations.ts
6017
+ async function runNotebookMutation(client, tool, rawInput, invocation) {
6018
+ 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.");
6019
+ let mutationStarted = false;
6020
+ try {
6021
+ const options = callOptions(invocation);
6022
+ invocation.signal?.throwIfAborted();
6023
+ if (tool === "qmind.create_notebook") {
6024
+ const input = rawInput;
6025
+ mutationStarted = true;
6026
+ const notebook = await client.createNotebook(input, options);
6027
+ invocation.signal?.throwIfAborted();
6028
+ 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.");
6029
+ return {
6030
+ ok: true,
6031
+ data: {
6032
+ id: notebook.id,
6033
+ title: notebook.title,
6034
+ description: notebook.description
6035
+ },
6036
+ meta: { operationId: invocation.operationId }
6037
+ };
6038
+ }
6039
+ const input = rawInput;
6040
+ mutationStarted = true;
6041
+ const response = await client.deleteNotebook(input.notebookId, options);
6042
+ invocation.signal?.throwIfAborted();
6043
+ if (response !== void 0) throw new TypeError("Unconfirmed notebook deletion.");
6044
+ return {
6045
+ ok: true,
6046
+ data: {
6047
+ notebookId: input.notebookId,
6048
+ deleted: true
6049
+ },
6050
+ meta: { operationId: invocation.operationId }
6051
+ };
6052
+ } catch (error) {
6053
+ const policy = qmindOrganizationPolicyError(error);
6054
+ if (policy) return {
6055
+ ok: false,
6056
+ error: policy,
6057
+ meta: { operationId: invocation.operationId }
6058
+ };
6059
+ const mapped = errorCode(error, mutationStarted);
6060
+ const code = mutationStarted && mapped === "internal" ? "outcome_unknown" : mapped;
6061
+ 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.");
6062
+ }
6063
+ }
6064
+ //#endregion
6065
+ //#region ../agent-core/src/scheduled-tasks.ts
6066
+ function taskData(task, notebookId) {
6067
+ 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)) || [
6068
+ task.createdAt,
6069
+ task.updatedAt,
6070
+ task.lastRunAt,
6071
+ task.nextRunAt
6072
+ ].some((value) => typeof value !== "string" || value.length > 128)) throw new TypeError("Unconfirmed scheduled task.");
6073
+ const config = JSON.stringify(task.config);
6074
+ if (config === void 0 || typeof task.config !== "object" || task.config === null || Array.isArray(task.config)) throw new TypeError("Invalid task config.");
6075
+ const configTruncated = new TextEncoder().encode(config).byteLength > 2e3;
6076
+ return {
6077
+ id: task.id,
6078
+ notebookId,
6079
+ sceneType: task.sceneType,
6080
+ schedule: task.schedule,
6081
+ enabled: task.enabled,
6082
+ nextRunAt: task.nextRunAt,
6083
+ lastRunAt: task.lastRunAt,
6084
+ createdAt: task.createdAt,
6085
+ updatedAt: task.updatedAt,
6086
+ config: configTruncated ? {} : JSON.parse(config),
6087
+ configTruncated
6088
+ };
6089
+ }
6090
+ async function runScheduledTask(client, tool, rawInput, invocation) {
6091
+ const input = rawInput;
6092
+ 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.");
6093
+ let mutationStarted = false;
6094
+ try {
6095
+ const options = callOptions(invocation);
6096
+ invocation.signal?.throwIfAborted();
6097
+ if (tool === "qmind.create_scheduled_task") {
6098
+ const create = rawInput;
6099
+ mutationStarted = true;
6100
+ const task = await client.createScheduledTask(input.notebookId, {
6101
+ sceneType: create.sceneType,
6102
+ schedule: create.schedule,
6103
+ config: {}
6104
+ }, options);
6105
+ invocation.signal?.throwIfAborted();
6106
+ const data = taskData(task, input.notebookId);
6107
+ if (data.sceneType !== create.sceneType || data.schedule !== create.schedule || !data.enabled) throw new TypeError("Unconfirmed creation.");
6108
+ return {
6109
+ ok: true,
6110
+ data,
6111
+ meta: { operationId: invocation.operationId }
6112
+ };
6113
+ }
6114
+ const { tasks } = await client.listScheduledTasks(input.notebookId, options);
6115
+ invocation.signal?.throwIfAborted();
6116
+ if (new Set(tasks.map((task) => task.id)).size !== tasks.length || tasks.some((task) => task.notebookId !== input.notebookId)) throw new TypeError("Invalid task list.");
6117
+ if (tool === "qmind.list_scheduled_tasks") {
6118
+ const query = rawInput;
6119
+ 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);
6120
+ const offset = (query.page - 1) * query.pageSize;
6121
+ return {
6122
+ ok: true,
6123
+ data: {
6124
+ tasks: filtered.slice(offset, offset + query.pageSize).map((task) => taskData(task, input.notebookId)),
6125
+ page: query.page,
6126
+ pageSize: query.pageSize,
6127
+ totalSize: filtered.length,
6128
+ hasMore: offset + query.pageSize < filtered.length
6129
+ },
6130
+ meta: { operationId: invocation.operationId }
6131
+ };
6132
+ }
6133
+ const current = tasks.find((task) => task.id === input.taskId);
6134
+ if (!current) return failure$1(invocation.operationId, "not_found", "The scheduled task was not found in this notebook.");
6135
+ taskData(current, input.notebookId);
6136
+ invocation.signal?.throwIfAborted();
6137
+ if (tool === "qmind.delete_scheduled_task") {
6138
+ mutationStarted = true;
6139
+ const response = await client.deleteScheduledTask(input.notebookId, input.taskId, options);
6140
+ invocation.signal?.throwIfAborted();
6141
+ if (response !== void 0) throw new TypeError("Unconfirmed deletion.");
6142
+ return {
6143
+ ok: true,
6144
+ data: {
6145
+ notebookId: input.notebookId,
6146
+ taskId: input.taskId,
6147
+ deleted: true
6148
+ },
6149
+ meta: { operationId: invocation.operationId }
6150
+ };
6151
+ }
6152
+ const update = rawInput;
6153
+ const patch = {
6154
+ ...update.schedule === void 0 ? {} : { schedule: update.schedule },
6155
+ ...update.enabled === void 0 ? {} : { enabled: update.enabled }
6156
+ };
6157
+ mutationStarted = true;
6158
+ const task = await client.updateScheduledTask(input.notebookId, input.taskId, patch, options);
6159
+ invocation.signal?.throwIfAborted();
6160
+ const data = taskData(task, input.notebookId);
6161
+ 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.");
6162
+ return {
6163
+ ok: true,
6164
+ data,
6165
+ meta: { operationId: invocation.operationId }
6166
+ };
6167
+ } catch (error) {
6168
+ const policy = qmindOrganizationPolicyError(error);
6169
+ if (policy) return {
6170
+ ok: false,
6171
+ error: policy,
6172
+ meta: { operationId: invocation.operationId }
6173
+ };
6174
+ const mapped = errorCode(error, mutationStarted);
6175
+ const code = mutationStarted && mapped === "internal" ? "outcome_unknown" : mapped;
6176
+ 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.");
6177
+ }
6178
+ }
6179
+ //#endregion
6180
+ //#region ../agent-core/src/source-organization.ts
6181
+ var SourceOrganizationPreflightError = class extends Error {
6182
+ agentCode;
6183
+ constructor(agentCode, message) {
6184
+ super(message);
6185
+ this.agentCode = agentCode;
6186
+ }
6187
+ };
6188
+ function reject(code, message) {
6189
+ throw new SourceOrganizationPreflightError(code, message);
6190
+ }
6191
+ function segment(value) {
6192
+ if (value.trim() !== value || !qmindSourceTitlePolicy(value).allowed) reject("invalid_input", "The source path must contain valid single path segments.");
6193
+ return value;
6194
+ }
6195
+ function directoryPath(source) {
6196
+ const path = source.path;
6197
+ if (!path.startsWith("/") || path === "/") reject("invalid_input", "The target directory has no valid absolute path.");
6198
+ path.slice(1).split("/").forEach(segment);
6199
+ return path;
6200
+ }
6201
+ function reader(client, notebookId, options) {
6202
+ const cache = /* @__PURE__ */ new Map();
6203
+ return async (id) => {
6204
+ options.signal?.throwIfAborted();
6205
+ const cached = cache.get(id);
6206
+ if (cached) return cached;
6207
+ const source = await client.getSource(notebookId, id, options);
6208
+ if (source.id !== id || source.notebookId !== notebookId) reject("invalid_input", "The source does not match the requested Notebook and ID.");
6209
+ cache.set(id, source);
6210
+ return source;
6211
+ };
6212
+ }
6213
+ async function targetPath(read, id) {
6214
+ if (id === void 0) return "";
6215
+ const target = await read(id);
6216
+ if (!target.isDir) reject("invalid_input", "The target must be a directory.");
6217
+ if (!qmindSourceOperationPolicy(target).addChildren || isQMindExternalSource(target) || isQMindEmailFolder(target)) reject("permission_denied", "This directory cannot accept children.");
6218
+ if (target.status !== "ready") reject("source_not_ready", "The target directory is not ready.");
6219
+ return directoryPath(target);
6220
+ }
6221
+ async function prepareDirectoryCreation(client, input, options) {
6222
+ const parentPath = await targetPath(reader(client, input.notebookId, options), input.parentSourceId);
6223
+ return {
6224
+ title: input.title,
6225
+ path: `${parentPath}/${segment(input.title)}`,
6226
+ ...input.parentSourceId === void 0 ? {} : { parentSourceId: input.parentSourceId }
6227
+ };
6228
+ }
6229
+ /** Snapshot preflight only: the existing endpoint has no revision CAS or atomic path derivation. */
6230
+ async function prepareSourceMove(client, input, options) {
6231
+ const read = reader(client, input.notebookId, options);
6232
+ const source = await read(input.sourceId);
6233
+ if (source.isDir) reject("invalid_input", "Only leaf documents can be moved.");
6234
+ if (!qmindSourceOperationPolicy(source).move || isQMindExternalSource(source)) reject("permission_denied", "This managed source cannot be moved.");
6235
+ if (source.status === "failed") reject("source_failed", "The source failed during ingestion.");
6236
+ if (source.status !== "ready" && source.status !== "unsupported") reject("source_not_ready", "The source is not ready to move.");
6237
+ const parent = source.parentSourceId ? await read(source.parentSourceId) : void 0;
6238
+ if (parent && isQMindEmailFolder(parent) || isQMindEmailAggregateMember(source, parent ? [parent] : [])) reject("permission_denied", "Email aggregate members cannot be moved.");
6239
+ options.signal?.throwIfAborted();
6240
+ const children = await client.listSources(input.notebookId, {
6241
+ view: "children",
6242
+ parentSourceId: source.id,
6243
+ page: 1,
6244
+ pageSize: 1
6245
+ }, options);
6246
+ 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.");
6247
+ const parentSourceId = input.targetParentSourceId ?? "";
6248
+ const patch = {
6249
+ parentSourceId,
6250
+ path: `${await targetPath(read, parentSourceId || void 0)}/${segment(source.path.split("/").filter(Boolean).at(-1) ?? source.title)}`
6251
+ };
6252
+ const noop = source.parentSourceId === parentSourceId;
6253
+ 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.");
6254
+ return {
6255
+ source,
6256
+ patch,
6257
+ noop
6258
+ };
6259
+ }
6260
+ //#endregion
6261
+ //#region ../agent-core/src/notebook-discovery.ts
6262
+ const upstreamPageSize = 50;
6263
+ const maxPagesPerCall = 4;
6264
+ const cursorSchema = z.object({
6265
+ version: z.literal(1),
6266
+ relationship: z.enum([
6267
+ "owned",
6268
+ "shared",
6269
+ "featured",
6270
+ "all"
6271
+ ]),
6272
+ collection: z.enum([
6273
+ "owned",
6274
+ "shared",
6275
+ "featured"
6276
+ ]),
6277
+ page: z.number().int().min(1).max(1e6),
6278
+ offset: z.number().int().min(0).max(49)
6279
+ }).strict();
6280
+ function invalidCursor() {
6281
+ throw Object.assign(/* @__PURE__ */ new Error("invalid notebook cursor"), { code: "INVALID_ARGUMENT" });
6282
+ }
6283
+ function initialPosition(input) {
6284
+ const relationship = input.relationship ?? "owned";
6285
+ if (input.cursor === void 0) return {
6286
+ version: 1,
6287
+ relationship,
6288
+ collection: relationship === "all" ? "owned" : relationship,
6289
+ page: 1,
6290
+ offset: 0
6291
+ };
6292
+ try {
6293
+ if (!/^[A-Za-z0-9_-]+$/.test(input.cursor)) return invalidCursor();
6294
+ const position = cursorSchema.parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")));
6295
+ if (position.relationship !== relationship || relationship !== "all" && position.collection !== relationship) return invalidCursor();
6296
+ return position;
6297
+ } catch {
6298
+ return invalidCursor();
6299
+ }
6300
+ }
6301
+ /** 动态目录依次遍历 owned、shared、featured;游标只记录位置,每页重新经过 ACL 与宿主过滤。 */
6302
+ async function discoverNotebooks(client, input, options, includes) {
6303
+ let position = initialPosition(input);
6304
+ if (["shared", "all"].includes(position.relationship) && client.listSharedNotebooks === void 0) throw Object.assign(/* @__PURE__ */ new Error("shared notebook listing is unavailable"), { code: "UNSUPPORTED_OPERATION" });
6305
+ if (["featured", "all"].includes(position.relationship) && client.listFeaturedNotebooks === void 0) throw Object.assign(/* @__PURE__ */ new Error("featured notebook listing is unavailable"), { code: "UNSUPPORTED_OPERATION" });
6306
+ const notebooks = [];
6307
+ const seen = /* @__PURE__ */ new Set();
6308
+ for (let requests = 0; position && requests < maxPagesPerCall && notebooks.length < input.pageSize; requests += 1) {
6309
+ options.signal?.throwIfAborted();
6310
+ const collection = position.collection;
6311
+ const page = position.page;
6312
+ const offset = position.offset;
6313
+ const relationship = position.relationship;
6314
+ const pagination = {
6315
+ page,
6316
+ pageSize: upstreamPageSize,
6317
+ retrievalEligibleOnly: true
6318
+ };
6319
+ const response = collection === "owned" ? await client.listNotebooks(pagination, options) : collection === "shared" ? await client.listSharedNotebooks(pagination, options) : await client.listFeaturedNotebooks(pagination, options);
6320
+ options.signal?.throwIfAborted();
6321
+ const items = response.notebooks.map((item) => "notebook" in item ? item.notebook : item);
6322
+ 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" });
6323
+ let index = offset;
6324
+ for (; index < items.length && notebooks.length < input.pageSize; index += 1) {
6325
+ const notebook = items[index];
6326
+ if (!notebook.id || typeof notebook.id !== "string") throw Object.assign(/* @__PURE__ */ new Error("invalid notebook entry"), { code: "REMOTE_ERROR" });
6327
+ if (!seen.has(notebook.id) && includes(notebook.id)) notebooks.push({
6328
+ notebook,
6329
+ relationship: collection
6330
+ });
6331
+ seen.add(notebook.id);
6332
+ }
6333
+ if (index < items.length) position = {
6334
+ ...position,
6335
+ offset: index
6336
+ };
6337
+ else if (items.length === upstreamPageSize) position = {
6338
+ ...position,
6339
+ page: page + 1,
6340
+ offset: 0
6341
+ };
6342
+ else position = collection !== "featured" && relationship === "all" ? {
6343
+ ...position,
6344
+ collection: collection === "owned" ? "shared" : "featured",
6345
+ page: 1,
6346
+ offset: 0
6347
+ } : void 0;
6348
+ }
6349
+ return {
6350
+ notebooks,
6351
+ hasMore: position !== void 0,
6352
+ ...position === void 0 ? {} : { nextCursor: Buffer.from(JSON.stringify(position)).toString("base64url") }
6353
+ };
6354
+ }
6355
+ //#endregion
6356
+ //#region ../agent-core/src/source-deletion.ts
6357
+ /** 仅绑定删除范围与展示身份;正文或索引状态变化不改变批准的对象。 */
6358
+ function sourceDeletionTarget(source) {
6359
+ return {
6360
+ sourceId: source.id,
6361
+ title: source.title,
6362
+ scope: source.isDir ? "subtree" : "source",
6363
+ revision: createHash("sha256").update(canonicalize({
6364
+ id: source.id,
6365
+ notebookId: source.notebookId,
6366
+ title: source.title,
6367
+ parentSourceId: source.parentSourceId,
6368
+ isDir: source.isDir,
6369
+ sourceType: source.sourceType,
6370
+ externalBinding: source.externalBinding ?? null
6371
+ })).digest("hex")
6372
+ };
6373
+ }
6374
+ /** 整批预检完成后才能提交;不替换邮件正文、不重复删除父子目标。 */
6375
+ async function prepareSourceDeletion(client, input, invocation) {
6376
+ const cache = /* @__PURE__ */ new Map();
6377
+ const selected = new Set(input.sourceIds);
6378
+ const read = async (id) => {
6379
+ invocation.signal?.throwIfAborted();
6380
+ const cached = cache.get(id);
6381
+ if (cached) return cached;
6382
+ const source = await client.getSource(input.notebookId, id, {
6383
+ signal: invocation.signal,
6384
+ ...invocation.token === void 0 ? {} : { authorization: invocation.token }
6385
+ });
6386
+ if (source.id !== id || source.notebookId !== input.notebookId) throw Object.assign(/* @__PURE__ */ new Error("Source identity changed."), { code: "INVALID_ARGUMENT" });
6387
+ cache.set(id, source);
6388
+ return source;
6389
+ };
6390
+ const targets = [];
6391
+ for (const id of input.sourceIds) {
6392
+ const source = await read(id);
6393
+ if (!qmindSourceOperationPolicy(source).delete) throw Object.assign(/* @__PURE__ */ new Error("This managed source cannot be deleted."), { code: "FORBIDDEN" });
6394
+ const family = [source];
6395
+ const seen = /* @__PURE__ */ new Set([id]);
6396
+ let parentId = source.parentSourceId;
6397
+ while (parentId) {
6398
+ if (selected.has(parentId) || seen.has(parentId) || seen.size > 100) throw Object.assign(/* @__PURE__ */ new Error("Overlapping or invalid source ancestry."), { code: "INVALID_ARGUMENT" });
6399
+ seen.add(parentId);
6400
+ const parent = await read(parentId);
6401
+ family.push(parent);
6402
+ parentId = parent.parentSourceId;
6403
+ }
6404
+ if (qmindEmailDeleteTarget(source, family).id !== id) throw Object.assign(/* @__PURE__ */ new Error("Select the email folder explicitly."), { code: "INVALID_ARGUMENT" });
6405
+ targets.push(sourceDeletionTarget(source));
6406
+ }
6407
+ return targets;
6408
+ }
6409
+ //#endregion
6410
+ //#region ../agent-core/src/core.ts
6411
+ const sourceStatus = /* @__PURE__ */ new Set([
6412
+ "pending",
6413
+ "processing",
6414
+ "ready",
6415
+ "unsupported",
6416
+ "failed"
6417
+ ]);
6418
+ /**
6419
+ * Snapshots and validates host policy at the Core boundary. Invocation context is not model input,
6420
+ * but it still crosses an adapter seam and must fail closed when malformed.
6421
+ */
6422
+ function scopedNotebookIds(invocation) {
6423
+ if (invocation.notebookScope === void 0) return void 0;
6424
+ const values = invocation.notebookScope.allowedNotebookIds;
6425
+ if (!Array.isArray(values)) throw new TypeError("The Agent Notebook scope is invalid.");
6426
+ const seen = /* @__PURE__ */ new Set();
6427
+ const snapshot = [];
6428
+ for (const value of values) {
6429
+ 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.");
6430
+ seen.add(value);
6431
+ snapshot.push(value);
6432
+ }
6433
+ const preferred = invocation.notebookScope.preferredNotebookIds;
6434
+ 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.");
6435
+ return Object.freeze(snapshot);
6436
+ }
6437
+ function targetedNotebookIds(toolId, input, invocation) {
6438
+ if (toolId === "qmind.list_notebooks" || toolId === "qmind.create_notebook") return void 0;
6439
+ if (toolId === "qmind.retrieve") {
6440
+ const value = input;
6441
+ return value.targets?.map((target) => target.notebookId) ?? (value.notebookId === void 0 ? invocation.defaultNotebookIds : [value.notebookId]);
6442
+ }
6443
+ return [input.notebookId];
6444
+ }
6445
+ function enforceNotebookScope(toolId, input, invocation, allowedNotebookIds) {
6446
+ 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.");
6447
+ const targets = targetedNotebookIds(toolId, input, invocation);
6448
+ if (targets === void 0) return void 0;
6449
+ const allowed = allowedNotebookIds === void 0 ? void 0 : new Set(allowedNotebookIds);
6450
+ if (targets.every((notebookId) => (allowed === void 0 || allowed.has(notebookId)) && notebookSelection(invocation, notebookId) !== "excluded")) return void 0;
6451
+ return failure$1(invocation.operationId, "permission_denied", "The notebook is outside the current Agent Notebook scope.");
6452
+ }
6453
+ function notebookSelection(invocation, notebookId) {
6454
+ if (invocation.notebookPolicy === void 0) return invocation.notebookScope?.preferredNotebookIds?.includes(notebookId) ? "preferred" : "allowed";
6455
+ const selection = invocation.notebookPolicy.selectNotebook(notebookId);
6456
+ if (![
6457
+ "excluded",
6458
+ "allowed",
6459
+ "preferred"
6460
+ ].includes(selection)) throw new TypeError("Invalid Notebook policy result.");
6461
+ return selection;
6462
+ }
6463
+ function notebookData(notebook, invocation, relationship) {
6464
+ const updatedAt = notebook.updatedAt ?? void 0;
6465
+ return {
6466
+ description: notebook.description,
6467
+ preferred: notebookSelection(invocation, notebook.id) === "preferred",
6468
+ ...relationship === void 0 ? {} : { relationship },
6469
+ id: notebook.id,
6470
+ materialCount: notebook.materialCount,
6471
+ ...notebook.overview?.summary ? { summary: notebook.overview.summary } : {},
6472
+ sourceCount: notebook.sourceCount,
6473
+ status: notebook.status,
6474
+ title: notebook.title,
6475
+ ...notebook.overview?.topics ? { topics: notebook.overview.topics } : {},
6476
+ ...updatedAt === void 0 ? {} : { updatedAt }
6477
+ };
6478
+ }
6479
+ function normalizedSourceStatus(value) {
6480
+ const normalized = value.trim().toLowerCase();
6481
+ if (!sourceStatus.has(normalized)) throw new TypeError("QMind returned an unsupported Source ingestion state.");
6482
+ return normalized;
6483
+ }
6484
+ function sourceData(source) {
6485
+ const status = normalizedSourceStatus(source.status);
6486
+ const createdAt = source.createdAt ?? void 0;
6487
+ const updatedAt = source.updatedAt ?? void 0;
6488
+ return {
6489
+ ...createdAt === void 0 ? {} : { createdAt },
6490
+ ...status === "failed" ? { errorCode: "source_failed" } : {},
6491
+ ...status === "unsupported" ? { errorCode: "source_unsupported" } : {},
6492
+ id: source.id,
6493
+ isDir: source.isDir,
6494
+ notebookId: source.notebookId,
6495
+ ...source.parentSourceId.length === 0 ? {} : { parentSourceId: source.parentSourceId },
6496
+ ...source.path.length === 0 ? {} : { path: source.path },
6497
+ sourceType: source.sourceType,
6498
+ status,
6499
+ title: source.title,
6500
+ ...updatedAt === void 0 ? {} : { updatedAt }
6501
+ };
6502
+ }
6503
+ function abortedCode(signal) {
6504
+ if (signal?.aborted !== true) return void 0;
6505
+ return signal.reason?.name === "TimeoutError" ? "timeout" : "cancelled";
6506
+ }
6507
+ function chunkData(chunk) {
6508
+ const originUrl = chunk.originUrl ?? void 0;
6509
+ return {
6510
+ notebookId: chunk.notebookId,
6511
+ notebookTitle: chunk.notebookTitle,
6512
+ chunkId: chunk.chunkId,
6513
+ chunkIndex: chunk.chunkIndex,
6514
+ content: chunk.content,
6515
+ ...originUrl === void 0 || originUrl.length === 0 ? {} : { originUrl },
6516
+ score: chunk.score,
6517
+ sourceId: chunk.sourceId,
6518
+ sourceTitle: chunk.sourceTitle,
6519
+ tokenCount: chunk.tokenCount,
6520
+ ...chunkLineRange(chunk.metadata)
6521
+ };
6522
+ }
6523
+ function chunkLineRange(metadata) {
6524
+ const positive = (value) => {
6525
+ const number = typeof value === "string" && value.trim() ? Number(value) : value;
6526
+ return typeof number === "number" && Number.isSafeInteger(number) && number > 0 ? number : void 0;
6527
+ };
6528
+ const lineStart = positive(metadata?.lineStart ?? metadata?.line_start);
6529
+ const lineEnd = positive(metadata?.lineEnd ?? metadata?.line_end);
6530
+ return lineStart === void 0 ? {} : {
6531
+ lineStart,
6532
+ ...lineEnd !== void 0 && lineEnd >= lineStart ? { lineEnd } : {}
6533
+ };
6534
+ }
6535
+ function chunkPromptContext(chunks) {
6536
+ 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");
6537
+ }
6538
+ async function retrieve(client, input, invocation) {
6539
+ const targets = input.targets ?? (input.notebookId === void 0 ? invocation.defaultNotebookIds?.map((notebookId) => ({ notebookId })) : [{
6540
+ notebookId: input.notebookId,
6541
+ ...input.sourceIds === void 0 ? {} : { sourceIds: input.sourceIds }
6542
+ }]);
6543
+ if (targets === void 0 || targets.length === 0 || targets.length > 5 && invocation.defaultRetrievalMode !== "all") return failure$1(invocation.operationId, "selection_required", "Use list_notebooks overview to select one to five relevant notebooks.");
6544
+ const batches = [];
6545
+ const batchSize = invocation.defaultRetrievalMode === "all" ? 1 : 5;
6546
+ for (let offset = 0; offset < targets.length; offset += batchSize) batches.push(targets.slice(offset, offset + batchSize));
6547
+ const results = [];
6548
+ const warnings = [];
6549
+ const request = async (batch) => {
6550
+ return client.retrieveNotebooks({
6551
+ targets: batch.map(({ notebookId, sourceIds }) => ({
6552
+ notebookId,
6553
+ ...sourceIds === void 0 ? {} : { sourceIds },
6554
+ ...notebookSelection(invocation, notebookId) === "preferred" ? { preference: "preferred" } : {}
6555
+ })),
6556
+ maxResults: input.maxResults,
6557
+ query: input.query,
6558
+ ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold },
6559
+ ...input.topK === void 0 ? {} : { topK: input.topK }
6560
+ }, callOptions(invocation));
6561
+ };
6562
+ for (let offset = 0; offset < batches.length; offset += 3) {
6563
+ invocation.signal?.throwIfAborted();
6564
+ const current = batches.slice(offset, offset + 3);
6565
+ const settled = await Promise.allSettled(current.map(request));
6566
+ invocation.signal?.throwIfAborted();
6567
+ invocation.assertCurrent?.();
6568
+ settled.forEach((entry, index) => {
6569
+ if (entry.status === "fulfilled") results.push(entry.value);
6570
+ else {
6571
+ if (batches.length === 1 || qmindOrganizationPolicyError(entry.reason) || ["unauthenticated", "permission_denied"].includes(errorCode(entry.reason))) throw entry.reason;
6572
+ for (const target of current[index]) warnings.push({
6573
+ code: "notebook_search_failed",
6574
+ notebookId: target.notebookId
6575
+ });
6576
+ }
6577
+ });
6578
+ }
6579
+ if (results.length === 0) return failure$1(invocation.operationId, "upstream_unavailable", "Notebook retrieval failed.");
6580
+ const result = {
6581
+ chunks: results.flatMap((item) => item.chunks.map((chunk) => {
6582
+ if (chunkLineRange(chunk.metadata).lineStart !== void 0) return chunk;
6583
+ const citation = item.citations.find((entry) => entry.notebookId === chunk.notebookId && entry.sourceId === chunk.sourceId && (entry.chunkId === chunk.chunkId || entry.chunkIndex === chunk.chunkIndex) && chunkLineRange(entry.metadata).lineStart !== void 0);
6584
+ return citation ? {
6585
+ ...chunk,
6586
+ metadata: {
6587
+ ...chunk.metadata,
6588
+ ...chunkLineRange(citation.metadata)
6589
+ }
6590
+ } : chunk;
6591
+ })).sort((a, b) => b.score - a.score),
6592
+ total: results.reduce((sum, item) => sum + item.total, 0),
6593
+ reranked: results.length === 1 && results[0].reranked
6594
+ };
6595
+ const bounded = result.chunks.slice(0, input.maxResults);
6596
+ return {
6597
+ data: {
6598
+ chunks: bounded.map(chunkData),
6599
+ promptContext: chunkPromptContext(bounded),
6600
+ reranked: result.reranked,
6601
+ total: result.total
6602
+ },
6603
+ meta: {
6604
+ operationId: invocation.operationId,
6605
+ ...warnings.length ? {
6606
+ partial: true,
6607
+ warnings
6608
+ } : {}
6609
+ },
6610
+ ok: true
6611
+ };
6612
+ }
6613
+ async function listNotebooks(client, input, invocation, allowedNotebookIds) {
6614
+ if (invocation.notebookPolicy !== void 0 || invocation.defaultNotebookRelationship !== void 0 || input.relationship !== void 0 || input.cursor !== void 0) {
6615
+ if (input.page !== 1) return failure$1(invocation.operationId, "invalid_input", "Use nextCursor to continue notebook discovery instead of page.");
6616
+ const allowed = allowedNotebookIds === void 0 ? void 0 : new Set(allowedNotebookIds);
6617
+ const relationship = input.relationship ?? invocation.defaultNotebookRelationship ?? "owned";
6618
+ if (![
6619
+ "owned",
6620
+ "shared",
6621
+ "featured",
6622
+ "all"
6623
+ ].includes(relationship)) throw new TypeError("Invalid default Notebook relationship.");
6624
+ const result = allowed?.size === 0 ? {
6625
+ notebooks: [],
6626
+ hasMore: false
6627
+ } : await discoverNotebooks(client, {
6628
+ ...input,
6629
+ relationship
6630
+ }, callOptions(invocation), (id) => (allowed === void 0 || allowed.has(id)) && notebookSelection(invocation, id) !== "excluded");
6631
+ return {
6632
+ ok: true,
6633
+ data: {
6634
+ ...result,
6635
+ notebooks: result.notebooks.map(({ notebook, relationship }) => notebookData(notebook, invocation, relationship)),
6636
+ pageSize: input.pageSize,
6637
+ retrievalSelection: {
6638
+ maxTargets: 5,
6639
+ overviewSelectionRequired: true
6640
+ }
6641
+ },
6642
+ meta: { operationId: invocation.operationId }
6643
+ };
6644
+ }
6645
+ if (allowedNotebookIds !== void 0) {
6646
+ const start = (input.page - 1) * input.pageSize;
6647
+ return {
6648
+ ok: true,
6649
+ data: {
6650
+ notebooks: (await Promise.all(allowedNotebookIds.slice(start, start + input.pageSize).map((id) => client.getNotebook(id, callOptions(invocation))))).map((notebook) => notebookData(notebook, invocation)),
6651
+ page: input.page,
6652
+ pageSize: input.pageSize,
6653
+ totalSize: allowedNotebookIds.length,
6654
+ retrievalSelection: {
6655
+ maxTargets: 5,
6656
+ overviewSelectionRequired: allowedNotebookIds.length >= 5
6657
+ }
6658
+ },
6659
+ meta: { operationId: invocation.operationId }
6660
+ };
6661
+ }
6662
+ const result = await client.listNotebooks({
6663
+ page: input.page,
6664
+ pageSize: input.pageSize
6665
+ }, callOptions(invocation));
6666
+ return {
6667
+ data: {
6668
+ notebooks: result.notebooks.map((notebook) => notebookData(notebook, invocation, "owned")),
6669
+ page: result.currentPage ?? input.page,
6670
+ pageSize: result.pageSize ?? input.pageSize,
6671
+ totalSize: result.totalSize,
6672
+ retrievalSelection: {
6673
+ maxTargets: 5,
6674
+ overviewSelectionRequired: result.totalSize >= 5
6675
+ }
6676
+ },
6677
+ meta: { operationId: invocation.operationId },
6678
+ ok: true
6679
+ };
6680
+ }
6681
+ async function listSources(client, input, invocation) {
6682
+ const result = await client.listSources(input.notebookId, {
6683
+ page: input.page,
6684
+ pageSize: input.pageSize,
6685
+ ...input.parentSourceId === void 0 ? {} : {
6686
+ parentSourceId: input.parentSourceId,
6687
+ view: "children"
6688
+ }
6689
+ }, callOptions(invocation));
6690
+ return {
6691
+ data: {
6692
+ page: result.currentPage ?? input.page,
6693
+ pageSize: result.pageSize ?? input.pageSize,
6694
+ sources: result.sources.map(sourceData),
6695
+ ...result.totalSize === void 0 ? {} : { totalSize: result.totalSize }
6696
+ },
6697
+ meta: { operationId: invocation.operationId },
6698
+ ok: true
6699
+ };
6700
+ }
6701
+ async function getSource(client, input, invocation) {
6702
+ const source = await client.getSource(input.notebookId, input.sourceId, callOptions(invocation));
6703
+ return {
6704
+ data: {
6705
+ ...sourceData(source),
6706
+ deletion: sourceDeletionTarget(source)
6707
+ },
6708
+ meta: { operationId: invocation.operationId },
6709
+ ok: true
6710
+ };
6711
+ }
6712
+ async function readSource(client, input, invocation) {
6713
+ const source = await client.getSource(input.notebookId, input.sourceId, callOptions(invocation));
6714
+ const status = normalizedSourceStatus(source.status);
6715
+ if (status === "pending" || status === "processing") return failure$1(invocation.operationId, "source_not_ready", "The source is not ready to read.");
6716
+ if (status === "unsupported") return failure$1(invocation.operationId, "source_unsupported", "The source format is unsupported.");
6717
+ if (status === "failed") return failure$1(invocation.operationId, "source_failed", "The source failed during ingestion.");
6718
+ const result = await client.getSourceContent(input.notebookId, input.sourceId, callOptions(invocation));
6719
+ const content = result.content.slice(input.offset, input.offset + input.maxChars);
6720
+ const nextOffset = input.offset + content.length;
6721
+ const truncated = nextOffset < result.content.length;
6722
+ return {
6723
+ data: {
6724
+ content,
6725
+ contentType: result.contentType,
6726
+ ...truncated ? { nextOffset } : {},
6727
+ sourceId: input.sourceId,
6728
+ notebookId: input.notebookId,
6729
+ updatedAt: source.updatedAt,
6730
+ truncated
6731
+ },
6732
+ meta: { operationId: invocation.operationId },
6733
+ ok: true
6734
+ };
6735
+ }
6736
+ async function addSource(client, input, invocation) {
6737
+ const cancelledBeforeMutation = abortedCode(invocation.signal);
6738
+ 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.");
6739
+ try {
6740
+ if (input.source.kind === "url") {
6741
+ const imported = (await client.importWebLinks(input.notebookId, {
6742
+ urls: [input.source.url],
6743
+ ...input.parentSourceId === void 0 ? {} : { parentSourceId: input.parentSourceId },
6744
+ ...input.path === void 0 ? {} : { path: input.path }
6745
+ }, callOptions(invocation)))[0];
6746
+ if (imported?.source === void 0) {
6747
+ if (imported?.error !== void 0) return failure$1(invocation.operationId, "upstream_unavailable", "QMind could not import the URL source.");
6748
+ return failure$1(invocation.operationId, "outcome_unknown", "The URL source result could not be confirmed.");
6749
+ }
6750
+ return {
6751
+ data: sourceData(imported.source),
6752
+ meta: { operationId: invocation.operationId },
6753
+ ok: true
6754
+ };
6755
+ }
6756
+ const textBytes = input.source.kind === "text" ? new TextEncoder().encode(input.source.content) : void 0;
6757
+ const binary = textBytes === void 0 ? invocation.fileSource : {
6758
+ filename: "content.md",
6759
+ mimeType: "text/markdown",
6760
+ size: textBytes.byteLength,
6761
+ async *open() {
6762
+ yield textBytes;
6763
+ }
6764
+ };
6765
+ if (binary === void 0) return failure$1(invocation.operationId, "internal", "The local file source was not prepared.");
6766
+ const title = input.source.title;
6767
+ return {
6768
+ data: sourceData(await client.uploadSource(input.notebookId, binary, {
6769
+ ...title === void 0 ? {} : { title },
6770
+ sourceType: input.source.kind === "text" ? "markdown" : "file",
6771
+ ...input.parentSourceId === void 0 ? {} : { parentSourceId: input.parentSourceId },
6772
+ ...input.path === void 0 ? {} : { path: input.path }
6773
+ }, callOptions(invocation))),
6774
+ meta: { operationId: invocation.operationId },
6775
+ ok: true
6776
+ };
6777
+ } catch (error) {
6778
+ const policyError = qmindOrganizationPolicyError(error);
6779
+ if (policyError) return {
6780
+ ok: false,
6781
+ error: policyError,
6782
+ meta: { operationId: invocation.operationId }
6783
+ };
6784
+ const mapped = errorCode(error, true);
6785
+ const code = mapped === "internal" ? "outcome_unknown" : mapped;
6786
+ return failure$1(invocation.operationId, code, code === "outcome_unknown" ? "The source mutation outcome is unknown." : "QMind could not add the source.");
6787
+ }
6788
+ }
6789
+ async function deleteSource(client, input, invocation) {
6790
+ if (client.batchDeleteSources === void 0) return failure$1(invocation.operationId, "capability_unavailable", "This client does not support source deletion.");
6791
+ const targets = await prepareSourceDeletion(client, input, invocation);
6792
+ if (invocation.approvedDeletionTargets !== void 0 && (targets.length !== invocation.approvedDeletionTargets.length || targets.some((target, index) => {
6793
+ const approved = invocation.approvedDeletionTargets?.[index];
6794
+ return !approved || target.sourceId !== approved.sourceId || target.title !== approved.title || target.scope !== approved.scope || target.revision !== approved.revision;
6795
+ }))) return failure$1(invocation.operationId, "permission_denied", "Deletion targets changed. Request fresh approval.");
6796
+ invocation.signal?.throwIfAborted();
6797
+ try {
6798
+ const result = await client.batchDeleteSources(input.notebookId, input.sourceIds, callOptions(invocation));
6799
+ 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.");
6800
+ if (result.successCount === 0) return {
6801
+ ok: false,
6802
+ error: {
6803
+ code: "source_deletion_failed",
6804
+ message: "No source was deleted.",
6805
+ retryable: false,
6806
+ details: {
6807
+ successCount: result.successCount,
6808
+ failureCount: result.failureCount
6809
+ }
6810
+ },
6811
+ meta: { operationId: invocation.operationId }
6812
+ };
6813
+ return {
6814
+ ok: true,
6815
+ data: {
6816
+ notebookId: input.notebookId,
6817
+ sourceIds: input.sourceIds,
6818
+ successCount: result.successCount,
6819
+ failureCount: result.failureCount
6820
+ },
6821
+ meta: {
6822
+ operationId: invocation.operationId,
6823
+ ...result.failureCount > 0 ? {
6824
+ partial: true,
6825
+ warnings: [{
6826
+ code: "source_deletion_failed",
6827
+ notebookId: input.notebookId
6828
+ }]
6829
+ } : {}
6830
+ }
6831
+ };
6832
+ } catch (error) {
6833
+ const policyError = qmindOrganizationPolicyError(error);
6834
+ if (policyError) return {
6835
+ ok: false,
6836
+ error: policyError,
6837
+ meta: { operationId: invocation.operationId }
6838
+ };
6839
+ const code = errorCode(error, true);
6840
+ 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.");
6841
+ }
6842
+ }
6843
+ async function organizeSource(client, tool, input, invocation) {
6844
+ 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.");
6845
+ let mutationStarted = false;
6846
+ try {
6847
+ const options = callOptions(invocation);
6848
+ invocation.signal?.throwIfAborted();
6849
+ let source;
6850
+ let expectedParent;
6851
+ let expectedPath;
6852
+ if (tool === "qmind.create_directory") {
6853
+ const prepared = await prepareDirectoryCreation(client, input, options);
6854
+ invocation.signal?.throwIfAborted();
6855
+ mutationStarted = true;
6856
+ source = await client.createDirectory(input.notebookId, prepared, options);
6857
+ expectedParent = prepared.parentSourceId ?? "";
6858
+ expectedPath = prepared.path;
6859
+ if (!source.isDir || source.title !== prepared.title || source.status !== "ready") throw new TypeError("Unconfirmed directory result.");
6860
+ } else {
6861
+ const moveInput = input;
6862
+ const prepared = await prepareSourceMove(client, moveInput, options);
6863
+ invocation.signal?.throwIfAborted();
6864
+ if (prepared.noop) return {
6865
+ ok: true,
6866
+ data: sourceData(prepared.source),
6867
+ meta: { operationId: invocation.operationId }
6868
+ };
6869
+ mutationStarted = true;
6870
+ source = await client.moveSource(input.notebookId, moveInput.sourceId, prepared.patch, options);
6871
+ expectedParent = prepared.patch.parentSourceId;
6872
+ expectedPath = prepared.patch.path;
6873
+ if (source.id !== moveInput.sourceId || source.isDir) throw new TypeError("Unconfirmed move result.");
6874
+ }
6875
+ invocation.signal?.throwIfAborted();
6876
+ if (!source.id || source.notebookId !== input.notebookId || source.parentSourceId !== expectedParent || source.path !== expectedPath) throw new TypeError("Unconfirmed source location.");
6877
+ return {
6878
+ ok: true,
6879
+ data: sourceData(source),
6880
+ meta: { operationId: invocation.operationId }
6881
+ };
6882
+ } catch (error) {
6883
+ const policyError = qmindOrganizationPolicyError(error);
6884
+ if (policyError) return {
6885
+ ok: false,
6886
+ error: policyError,
6887
+ meta: { operationId: invocation.operationId }
6888
+ };
6889
+ const code = error instanceof SourceOrganizationPreflightError ? error.agentCode : errorCode(error, mutationStarted);
6890
+ 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.");
6891
+ }
6892
+ }
6893
+ function validateQMindAgentInvocation(toolId, input, invocation) {
6894
+ const parsed = agentToolInputSchemas[toolId].safeParse(input);
6895
+ if (!parsed.success) return failure$1(invocation.operationId, "invalid_input", "The tool input is invalid.");
6896
+ try {
6897
+ invocation.assertCurrent?.();
6898
+ return enforceNotebookScope(toolId, parsed.data, invocation, scopedNotebookIds(invocation));
6899
+ } catch {
6900
+ return failure$1(invocation.operationId, "permission_denied", "The host context is no longer valid.");
6901
+ }
6902
+ }
6903
+ function createQMindAgentCore(client) {
6904
+ if (typeof client !== "object" || client === null) throw new TypeError("client is required");
6905
+ return Object.freeze({ async invoke(toolId, rawInput, invocation) {
6906
+ const parsed = agentToolInputSchemas[toolId].safeParse(rawInput);
6907
+ if (!parsed.success) return failure$1(invocation.operationId, "invalid_input", "The tool input is invalid.");
6908
+ try {
6909
+ if (invocation.notebookPolicy !== void 0 && typeof invocation.notebookPolicy.selectNotebook !== "function") throw new TypeError("Invalid Notebook policy.");
6910
+ const allowedNotebookIds = scopedNotebookIds(invocation);
6911
+ const denied = enforceNotebookScope(toolId, parsed.data, invocation, allowedNotebookIds);
6912
+ if (denied !== void 0) return denied;
6913
+ invocation.assertCurrent?.();
6914
+ switch (toolId) {
6915
+ case "qmind.update_source_content": return await updateSourceContent(client, parsed.data, invocation);
6916
+ case "qmind.refresh_source": return await refreshSource(client, parsed.data, invocation);
6917
+ case "qmind.list_task_runs": return await listTaskRuns(client, parsed.data, invocation);
6918
+ case "qmind.create_notebook":
6919
+ case "qmind.delete_notebook": return await runNotebookMutation(client, toolId, parsed.data, invocation);
6920
+ case "qmind.create_scheduled_task":
6921
+ case "qmind.update_scheduled_task":
6922
+ case "qmind.delete_scheduled_task":
6923
+ case "qmind.list_scheduled_tasks": return await runScheduledTask(client, toolId, parsed.data, invocation);
6924
+ case "qmind.retrieve": return await retrieve(client, parsed.data, invocation);
6925
+ case "qmind.list_notebooks": return await listNotebooks(client, parsed.data, invocation, allowedNotebookIds);
6926
+ case "qmind.list_sources": return await listSources(client, parsed.data, invocation);
6927
+ case "qmind.get_source": return await getSource(client, parsed.data, invocation);
6928
+ case "qmind.read_source": return await readSource(client, parsed.data, invocation);
6929
+ case "qmind.delete_source": return await deleteSource(client, parsed.data, invocation);
6930
+ case "qmind.create_directory":
6931
+ case "qmind.move_source": return await organizeSource(client, toolId, parsed.data, invocation);
6932
+ case "qmind.add_source": return await addSource(client, parsed.data, invocation);
6933
+ }
6934
+ } catch (error) {
6935
+ const policyError = qmindOrganizationPolicyError(error);
6936
+ if (policyError) return {
6937
+ ok: false,
6938
+ error: policyError,
6939
+ meta: { operationId: invocation.operationId }
6940
+ };
6941
+ const code = errorCode(error);
6942
+ return failure$1(invocation.operationId, code, "The QMind operation failed.");
6943
+ }
6944
+ } });
6945
+ }
6946
+ //#endregion
6947
+ //#region ../agent-core/src/operation.ts
6948
+ function failure(operationId, code, message) {
6949
+ return {
6950
+ error: {
6951
+ code,
6952
+ message,
6953
+ retryable: isRetryableAgentError(code)
6954
+ },
6955
+ meta: { operationId },
6956
+ ok: false
6957
+ };
6958
+ }
6959
+ function accept(sink, event) {
6960
+ try {
6961
+ sink.accept(event);
6962
+ } catch {}
6963
+ }
6964
+ function notebookIds(toolId, input, defaultNotebookIds) {
6965
+ if (toolId === "qmind.list_notebooks" || toolId === "qmind.create_notebook") return void 0;
6966
+ if (typeof input !== "object" || input === null) return void 0;
6967
+ 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] : []);
6968
+ if ("notebookId" in input && typeof input.notebookId === "string") return [input.notebookId];
6969
+ return defaultNotebookIds;
6970
+ }
6971
+ function filePath(toolId, input) {
6972
+ if (toolId !== "qmind.add_source") return void 0;
6973
+ const parsed = agentToolInputSchemas[toolId].safeParse(input);
6974
+ if (!parsed.success || parsed.data.source.kind !== "file") return void 0;
6975
+ return parsed.data.source.filePath;
6976
+ }
6977
+ function abortCode(signal, timedOut) {
6978
+ return timedOut ? "timeout" : signal.aborted ? "cancelled" : "internal";
6979
+ }
6980
+ function fileSourceErrorCode(error) {
6981
+ if (typeof error !== "object" || error === null || !("code" in error)) return "internal";
6982
+ const code = error.code;
6983
+ return code === "INVALID_ARGUMENT" || code === "FILE_TOO_LARGE" ? "invalid_input" : "internal";
6984
+ }
6985
+ function outcomeFor(result) {
6986
+ if (result.ok) return "succeeded";
6987
+ if (result.error.code === "cancelled") return "cancelled";
6988
+ if (result.error.code === "outcome_unknown") return "outcome_unknown";
6989
+ return "failed";
6990
+ }
6991
+ async function runQMindAgentOperation(dependencies, toolId, input, runtimeSignal, perRequestToken, operationContext = {}) {
6992
+ const createId = dependencies.createId ?? randomUUID;
6993
+ const now = dependencies.now ?? Date.now;
6994
+ const operationId = createId();
6995
+ const definition = agentToolDefinitions.find((tool) => tool.id === toolId);
6996
+ if (definition === void 0) return failure(operationId, "internal", "Unknown QMind tool.");
6997
+ const startedAt = now();
6998
+ const started = {
6999
+ eventId: createId(),
7000
+ intent: definition.intent,
7001
+ occurredAt: new Date(startedAt).toISOString(),
7002
+ operationId,
7003
+ toolId,
7004
+ type: "qmind.operation.started"
7005
+ };
7006
+ accept(dependencies.auditSink, started);
7007
+ const deadlineController = new AbortController();
7008
+ let timedOut = false;
7009
+ const timer = setTimeout(() => {
7010
+ timedOut = true;
7011
+ deadlineController.abort(new DOMException("QMind Agent deadline exceeded", "TimeoutError"));
7012
+ }, deadlineFor(toolId, input));
7013
+ timer.unref?.();
7014
+ const signal = runtimeSignal === void 0 ? deadlineController.signal : AbortSignal.any([runtimeSignal, deadlineController.signal]);
7015
+ let result = failure(operationId, "internal", "The QMind operation did not produce a result.");
7016
+ try {
7017
+ if (signal.aborted) {
7018
+ const code = abortCode(signal, timedOut);
7019
+ result = failure(operationId, code, code === "timeout" ? "The QMind operation timed out." : "The QMind operation was cancelled.");
7020
+ } else {
7021
+ const denied = validateQMindAgentInvocation(toolId, input, {
7022
+ ...operationContext,
7023
+ operationId,
7024
+ ...dependencies.defaultNotebookIds === void 0 ? {} : { defaultNotebookIds: dependencies.defaultNotebookIds }
7025
+ });
7026
+ if (denied) result = denied;
7027
+ else {
7028
+ let fileSource;
7029
+ const requestedPath = filePath(toolId, input);
7030
+ if (requestedPath !== void 0) try {
7031
+ signal.throwIfAborted();
7032
+ fileSource = await dependencies.createFileSource(requestedPath);
7033
+ signal.throwIfAborted();
7034
+ } catch (error) {
7035
+ const code = signal.aborted ? abortCode(signal, timedOut) : fileSourceErrorCode(error);
7036
+ 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.");
7037
+ }
7038
+ if (requestedPath === void 0 || fileSource !== void 0) try {
7039
+ operationContext.assertCurrent?.();
7040
+ result = await dependencies.core.invoke(toolId, input, {
7041
+ assertCurrent: operationContext.assertCurrent,
7042
+ defaultRetrievalMode: dependencies.defaultRetrievalMode,
7043
+ ...operationContext.notebookPolicy === void 0 ? {} : { notebookPolicy: operationContext.notebookPolicy },
7044
+ ...operationContext.defaultNotebookRelationship === void 0 ? {} : { defaultNotebookRelationship: operationContext.defaultNotebookRelationship },
7045
+ ...fileSource === void 0 ? {} : { fileSource },
7046
+ ...dependencies.defaultNotebookIds === void 0 ? {} : { defaultNotebookIds: dependencies.defaultNotebookIds },
7047
+ ...operationContext.approvedDeletionTargets === void 0 ? {} : { approvedDeletionTargets: operationContext.approvedDeletionTargets },
7048
+ ...operationContext.notebookScope === void 0 ? {} : { notebookScope: operationContext.notebookScope },
7049
+ operationId,
7050
+ signal,
7051
+ ...perRequestToken === void 0 ? {} : { token: perRequestToken }
7052
+ });
7053
+ if (timedOut && definition.intent === "read" && result.ok === false && result.error.code === "cancelled") result = failure(operationId, "timeout", "The QMind operation timed out.");
7054
+ } catch {
7055
+ result = failure(operationId, "internal", "The QMind operation failed.");
7056
+ }
7057
+ }
7058
+ }
7059
+ } finally {
7060
+ clearTimeout(timer);
7061
+ }
7062
+ const finishedAt = now();
7063
+ const resultErrorCode = result.ok === false ? result.error.code : void 0;
7064
+ const partial = result.ok === true ? result.meta.partial : void 0;
7065
+ const warningCodes = result.ok === true && result.meta.warnings !== void 0 ? result.meta.warnings.map((warning) => warning.code) : void 0;
7066
+ const operationNotebookIds = notebookIds(toolId, input, dependencies.defaultNotebookIds);
7067
+ const finished = {
7068
+ durationMs: Math.max(0, finishedAt - startedAt),
7069
+ ...resultErrorCode === void 0 ? {} : { errorCode: resultErrorCode },
7070
+ eventId: createId(),
7071
+ intent: definition.intent,
7072
+ ...operationNotebookIds === void 0 ? {} : { notebookIds: operationNotebookIds },
7073
+ occurredAt: new Date(finishedAt).toISOString(),
7074
+ operationId,
7075
+ outcome: outcomeFor(result),
7076
+ ...partial === true ? { partial: true } : {},
7077
+ toolId,
7078
+ type: "qmind.operation.finished",
7079
+ ...warningCodes === void 0 ? {} : { warningCodes }
7080
+ };
7081
+ accept(dependencies.auditSink, finished);
7082
+ return result;
7083
+ }
7084
+ //#endregion
7085
+ //#region src/canonical-commands.ts
7086
+ /** New CLI workflows use the same validation, deadlines and mutation receipts as MCP. */
7087
+ async function runCanonicalCommand(context, raw, tool, input) {
7088
+ const parsed = agentToolInputSchemas[tool].safeParse(input);
7089
+ if (!parsed.success) {
7090
+ const fields = [...new Set(parsed.error.issues.map((issue) => issue.path.join(".") || "input"))];
7091
+ throw new QMindError("INVALID_ARGUMENT", `Invalid ${tool} arguments: ${fields.join(", ")}`);
7092
+ }
7093
+ const host = await hostFor(context, raw);
7094
+ const result = await runQMindAgentOperation({
7095
+ core: createQMindAgentCore(host.client),
7096
+ createFileSource: (path) => host.createFileSource(path),
7097
+ auditSink: { accept: () => {} }
7098
+ }, tool, parsed.data);
7099
+ render(context, raw, {
7100
+ kind: "json",
7101
+ value: result
7102
+ });
7103
+ if (!result.ok) context.exitCode = result.error.code === "invalid_input" ? 2 : 1;
7104
+ else if (result.meta.partial) context.exitCode = 1;
7105
+ }
7106
+ function scoreThreshold(value) {
7107
+ const result = Number(value);
7108
+ if (!value.trim() || !Number.isFinite(result) || result < 0 || result > 1) throw new QMindError("INVALID_ARGUMENT", "--score-threshold must be between 0 and 1");
7109
+ return result;
7110
+ }
7111
+ function parseTargets(value) {
7112
+ try {
7113
+ return JSON.parse(value);
7114
+ } catch {
7115
+ throw new QMindError("INVALID_ARGUMENT", "--targets must be a JSON array of retrieval targets");
7116
+ }
7117
+ }
7118
+ function enabled(value) {
7119
+ if (value === "true") return true;
7120
+ if (value === "false") return false;
7121
+ throw new QMindError("INVALID_ARGUMENT", "--enabled must be true or false");
7122
+ }
7123
+ function notebookId(raw) {
7124
+ return requiredString(raw.nb, "--nb");
7125
+ }
7126
+ function registerCanonicalCommands(context, program) {
7127
+ 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) => {
7128
+ await runCanonicalCommand(context, raw, "qmind.list_notebooks", {
7129
+ relationship: raw.relationship,
7130
+ cursor: raw.cursor,
7131
+ pageSize: raw.pageSize
7132
+ });
7133
+ });
7134
+ const source = program.commands.find((command) => command.name() === "source");
7135
+ 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) => {
7136
+ await runCanonicalCommand(context, raw, "qmind.add_source", {
7137
+ notebookId: notebookId(raw),
7138
+ source: {
7139
+ kind: "url",
7140
+ url: raw.url
7141
+ }
7142
+ });
7143
+ });
7144
+ 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) => {
7145
+ await runCanonicalCommand(context, raw, "qmind.read_source", {
7146
+ notebookId: notebookId(raw),
7147
+ sourceId,
7148
+ offset: raw.offset,
7149
+ maxChars: raw.maxChars
7150
+ });
7151
+ });
7152
+ 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) => {
7153
+ const input = {
7154
+ notebookId: notebookId(raw),
7155
+ sourceIds
7156
+ };
7157
+ if (!agentToolInputSchemas["qmind.delete_source"].safeParse(input).success) throw new QMindError("INVALID_ARGUMENT", "Provide 1..100 distinct source IDs");
7158
+ if (raw.force !== true && !await context.confirm.confirm(`Delete Sources ${JSON.stringify(sourceIds)} and ALL descendants of selected directories? Type 'y' to proceed: `)) {
7159
+ context.io.stderr("aborted; pass --force to confirm non-interactively\n");
7160
+ context.exitCode = 1;
7161
+ return;
7162
+ }
7163
+ await runCanonicalCommand(context, raw, "qmind.delete_source", input);
7164
+ });
7165
+ const scheduled = program.command("scheduled-task").description("Manage notebook schedule configurations (not task runs)");
7166
+ 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) => {
7167
+ await runCanonicalCommand(context, raw, "qmind.create_scheduled_task", {
7168
+ notebookId: notebookId(raw),
7169
+ sceneType: raw.scene,
7170
+ schedule: raw.schedule
7171
+ });
7172
+ });
7173
+ 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) => {
7174
+ await runCanonicalCommand(context, raw, "qmind.update_scheduled_task", {
7175
+ notebookId: notebookId(raw),
7176
+ taskId,
7177
+ schedule: raw.schedule,
7178
+ enabled: raw.enabled
7179
+ });
7180
+ });
7181
+ 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) => {
7182
+ await runCanonicalCommand(context, raw, "qmind.update_scheduled_task", {
7183
+ notebookId: notebookId(raw),
7184
+ taskId,
7185
+ enabled: state
7186
+ });
7187
+ });
7188
+ withCommon(scheduled.command("delete <task_id>").description("Delete schedule configuration; dispatched runs are not cancelled")).requiredOption("--nb <id>", "notebook ID").action(async (taskId, raw) => {
7189
+ await runCanonicalCommand(context, raw, "qmind.delete_scheduled_task", {
7190
+ notebookId: notebookId(raw),
7191
+ taskId
7192
+ });
7193
+ });
7194
+ 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) => {
7195
+ await runCanonicalCommand(context, raw, "qmind.list_scheduled_tasks", {
7196
+ notebookId: notebookId(raw),
7197
+ taskId: raw.task,
7198
+ sceneType: raw.scene,
7199
+ enabled: raw.enabled,
7200
+ page: raw.page,
7201
+ pageSize: raw.pageSize
7202
+ });
7203
+ });
7204
+ }
7205
+ //#endregion
7206
+ //#region src/application.ts
7207
+ const distribution = CLI_DISTRIBUTIONS[QMIND_CLI_DISTRIBUTION];
7208
+ function registerCoreCommands(context, program) {
7209
+ withCommon(program.command("login").description("Sign in with a Qoder PAT or browser and save credentials"), false).option("--client-id <id>", "OAuth App client_id").option("--pat <token>", "Qoder personal access token (prefer --pat-stdin or environment variables)").option("--pat-stdin", "read a Qoder personal access token from standard input").option("--no-browser", "print the browser authorization URL without opening it").action(async (raw) => {
7210
+ const clientId = optionalString(raw, "clientId");
7211
+ if (raw.patStdin === true && (raw.pat !== void 0 || raw.token !== void 0)) throw new QMindError("INVALID_ARGUMENT", "--pat-stdin cannot be combined with --pat or --token");
7212
+ if (raw.pat !== void 0 && raw.token !== void 0) throw new QMindError("INVALID_ARGUMENT", "--pat cannot be combined with --token");
7213
+ let personalToken = stringOption(raw, "pat");
7214
+ if (raw.patStdin === true) {
7215
+ if (context.io.stdinIsTTY) throw new QMindError("INVALID_ARGUMENT", "--pat-stdin requires piped or redirected input");
7216
+ const readStdin = context.io.readStdin ?? processIO().readStdin;
7217
+ if (readStdin === void 0) throw new QMindError("INVALID_ARGUMENT", "stdin reader is unavailable");
7218
+ personalToken = await readStdin();
7219
+ }
7220
+ if (personalToken !== void 0) {
7221
+ personalToken = personalToken.trim();
7222
+ if (personalToken.length > 16384 || !personalToken.startsWith("pt-") || personalToken.length <= 3 || /\s/.test(personalToken)) throw new QMindError("INVALID_ARGUMENT", "Qoder PAT must be a single non-empty pt- token (maximum 16 KiB)");
7223
+ if (clientId !== void 0) throw new QMindError("INVALID_ARGUMENT", "--client-id cannot be combined with PAT login");
7224
+ }
7225
+ const host = await hostFor(context, personalToken === void 0 ? raw : {
7226
+ ...raw,
7227
+ token: personalToken
7228
+ });
7229
+ const result = await host.login({
7230
+ ...clientId === void 0 ? {} : { clientId },
7231
+ ...personalToken === void 0 ? {} : { personalToken },
7232
+ ...raw.browser === false ? { openBrowser: false } : {}
7233
+ });
7234
+ context.io.stdout(`Logged in successfully [${result.sashOrigin} -> ${host.config.dashboardOrigin}]\nToken saved to ${host.config.homeDirectory}/credentials.json\n` + (result.expiresAt.length === 0 ? "" : `Access token expires at: ${result.expiresAt}\n`));
7235
+ });
7236
+ withCommon(program.command("logout").description("Remove saved credentials"), false).action(async (raw) => {
7237
+ await (await hostFor(context, raw)).logout();
7238
+ context.io.stdout("Logged out. Credentials removed.\n");
7239
+ });
7240
+ const notebook = program.command("notebook").description("Manage notebooks");
7241
+ withCommon(notebook.command("create").description("Create a notebook")).option("--title <title>", "notebook title (required)").option("--desc <description>", "notebook description", "").action(async (raw) => {
7242
+ const host = await hostFor(context, raw);
7243
+ render(context, raw, {
7244
+ kind: "notebook",
7245
+ value: await submitCliMutation(async () => host.client.createNotebook({
7246
+ description: String(raw.desc ?? ""),
7247
+ title: requiredString(raw.title, "--title")
7248
+ }))
7249
+ });
7250
+ });
7251
+ 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) => {
7252
+ const host = await hostFor(context, raw);
7253
+ const client = optionalString(raw, "filterClient");
7254
+ const pagination = {
7255
+ ...raw.page === void 0 ? {} : { page: Number(raw.page) },
7256
+ ...raw.pageSize === void 0 ? {} : { pageSize: Number(raw.pageSize) }
7257
+ };
7258
+ if (raw.shared === true) render(context, raw, {
7259
+ kind: "sharedNotebookList",
7260
+ value: await host.client.listSharedNotebooks(pagination)
7261
+ });
7262
+ else render(context, raw, {
7263
+ kind: "notebookList",
7264
+ value: await host.client.listNotebooks({
7265
+ ...pagination,
7266
+ ...client === void 0 ? {} : { client }
7267
+ })
7268
+ });
7269
+ });
7270
+ withCommon(notebook.command("get <notebook_id>").description("Get a notebook")).action(async (notebookId, raw) => {
7271
+ render(context, raw, {
7272
+ kind: "notebook",
7273
+ value: await (await hostFor(context, raw)).client.getNotebook(notebookId)
7274
+ });
7275
+ });
7276
+ withCommon(notebook.command("delete <notebook_id>").description("Delete a notebook")).action(async (notebookId, raw) => {
7277
+ const host = await hostFor(context, raw);
7278
+ await submitCliMutation(() => host.client.deleteNotebook(notebookId));
7279
+ if (raw.format === "json" || raw.format === "ndjson") render(context, raw, {
7280
+ kind: "json",
7281
+ value: {
7282
+ notebookId,
7283
+ deleted: true
7284
+ }
7285
+ });
7286
+ else context.io.stdout("deleted\n");
7287
+ });
7288
+ 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) => {
7289
+ const notebookIds = raw.nb;
7290
+ const [notebookId] = notebookIds;
7291
+ if (raw.targets === void 0 && notebookId === void 0) throw new QMindError("INVALID_ARGUMENT", "--nb is required");
7292
+ if (notebookIds.length > 5) throw new QMindError("INVALID_ARGUMENT", "--nb accepts at most 5 distinct notebook IDs");
7293
+ const input = {
7294
+ maxResults: numberOption(raw, "maxResults", 0),
7295
+ query: requiredString(raw.query || query, "--query or positional query"),
7296
+ sourceIds: splitCsv(stringOption(raw, "sources")),
7297
+ topK: numberOption(raw, "topK", 0),
7298
+ ...raw.scoreThreshold === void 0 ? {} : { scoreThreshold: Number(raw.scoreThreshold) }
7299
+ };
7300
+ if (input.maxResults < 0 || input.topK < 0) throw new QMindError("INVALID_ARGUMENT", "--top-k and --max-results must be non-negative");
7301
+ if (notebookIds.length > 1 && input.sourceIds.length > 0) throw new QMindError("INVALID_ARGUMENT", "--sources requires a single notebook");
7302
+ if (raw.unified === true || raw.targets !== void 0) {
7303
+ await runCanonicalCommand(context, raw, "qmind.retrieve", {
7304
+ query: input.query,
7305
+ ...raw.targets !== void 0 ? { targets: raw.targets } : notebookIds.length === 1 ? {
7306
+ notebookId,
7307
+ ...input.sourceIds.length ? { sourceIds: input.sourceIds } : {}
7308
+ } : { targets: notebookIds.map((id) => ({ notebookId: id })) },
7309
+ ...input.maxResults === 0 ? {} : { maxResults: input.maxResults },
7310
+ ...input.topK === 0 ? {} : { topK: input.topK },
7311
+ ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold }
7312
+ });
7313
+ return;
7314
+ }
7315
+ const host = await hostFor(context, raw);
7316
+ if (notebookIds.length === 1 && notebookId !== void 0) {
7317
+ render(context, raw, {
7318
+ kind: "retrieve",
7319
+ value: await host.client.retrieve(notebookId, input)
7320
+ });
7321
+ return;
7322
+ }
7323
+ render(context, raw, {
7324
+ kind: "multiRetrieve",
7325
+ value: await host.client.retrieveNotebooks({
7326
+ query: input.query,
7327
+ topK: input.topK,
7328
+ maxResults: input.maxResults,
7329
+ ...input.scoreThreshold === void 0 ? {} : { scoreThreshold: input.scoreThreshold },
7330
+ targets: notebookIds.map((notebookId) => ({ notebookId }))
7331
+ })
7332
+ });
7333
+ });
7334
+ }
7335
+ function registerSourceCommands(context, program) {
7336
+ const source = program.command("source").description("Manage notebook sources");
7337
+ 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) => {
7338
+ const host = await hostFor(context, raw);
7339
+ render(context, raw, {
7340
+ kind: "source",
7341
+ value: await submitCliMutation(async () => host.client.createSource(requiredString(raw.nb, "--nb"), {
7342
+ isDir: raw.isDir === true ? true : void 0,
7343
+ parentSourceId: String(raw.parent ?? ""),
7344
+ path: String(raw.path ?? ""),
7345
+ sourceType: String(raw.type ?? ""),
7346
+ status: String(raw.status ?? ""),
7347
+ title: requiredString(raw.title, "--title")
7348
+ }))
7349
+ });
7350
+ });
7351
+ 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) => {
7352
+ if (raw.derivePath === true) {
7353
+ await runCanonicalCommand(context, raw, "qmind.create_directory", {
7354
+ notebookId: requiredString(raw.nb, "--nb"),
7355
+ title: requiredString(raw.title, "--title"),
7356
+ ...optionalString(raw, "parent") === void 0 ? {} : { parentSourceId: optionalString(raw, "parent") }
7357
+ });
7358
+ return;
7359
+ }
7360
+ const host = await hostFor(context, raw);
7361
+ render(context, raw, {
7362
+ kind: "source",
7363
+ value: await submitCliMutation(async () => host.client.createDirectory(requiredString(raw.nb, "--nb"), {
7364
+ parentSourceId: String(raw.parent ?? ""),
7365
+ path: String(raw.path ?? ""),
7366
+ title: requiredString(raw.title, "--title")
7367
+ }))
7368
+ });
7369
+ });
7370
+ 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) => {
7371
+ const host = await hostFor(context, raw);
7372
+ const notebookId = requiredString(raw.nb, "--nb");
7373
+ let value;
7374
+ if (raw.all === true) {
7375
+ const pageSize = positiveNumberOption(raw, "pageSize", 0) ?? 100;
7376
+ value = { sources: await host.client.listAllSources(notebookId, {
7377
+ maxPages: numberOption(raw, "maxPages", 1e4),
7378
+ pageSize
7379
+ }) };
7380
+ } else {
7381
+ const page = positiveNumberOption(raw, "page", 0);
7382
+ const pageSize = positiveNumberOption(raw, "pageSize", 0);
7383
+ value = await host.client.listSources(notebookId, {
7384
+ ...page === void 0 ? {} : { page },
7385
+ ...pageSize === void 0 ? {} : { pageSize },
7386
+ ...raw.parent === void 0 ? {} : {
7387
+ parentSourceId: requiredString(raw.parent, "--parent"),
7388
+ view: "children"
7389
+ }
7390
+ });
7391
+ }
7392
+ render(context, raw, {
7393
+ kind: "sourceList",
7394
+ value
7395
+ });
7396
+ });
7397
+ withCommon(source.command("get <source_id>").description("Get a source")).option("--nb <id>", "notebook ID (required)").action(async (sourceId, raw) => {
4769
7398
  render(context, raw, {
4770
7399
  kind: "source",
4771
7400
  value: await (await hostFor(context, raw)).client.getSource(requiredString(raw.nb, "--nb"), sourceId)
@@ -4776,12 +7405,12 @@ function registerSourceCommands(context, program) {
4776
7405
  const file = requiredString(raw.file, "--file");
4777
7406
  render(context, raw, {
4778
7407
  kind: "source",
4779
- value: await host.client.uploadSource(requiredString(raw.nb, "--nb"), await host.createFileSource(file), {
7408
+ value: await submitCliMutation(async () => host.client.uploadSource(requiredString(raw.nb, "--nb"), await host.createFileSource(file), {
4780
7409
  ...optionalString(raw, "title") === void 0 ? {} : { title: optionalString(raw, "title") },
4781
7410
  ...optionalString(raw, "type") === void 0 ? {} : { sourceType: optionalString(raw, "type") },
4782
7411
  ...optionalString(raw, "parent") === void 0 ? {} : { parentSourceId: optionalString(raw, "parent") },
4783
7412
  ...optionalString(raw, "path") === void 0 ? {} : { path: optionalString(raw, "path") }
4784
- })
7413
+ }))
4785
7414
  });
4786
7415
  });
4787
7416
  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) => {
@@ -4796,7 +7425,27 @@ function registerSourceCommands(context, program) {
4796
7425
  });
4797
7426
  context.io.stderr(`Downloaded ${output} (${bytes} bytes)\n`);
4798
7427
  });
4799
- 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) => {
7428
+ 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([
7429
+ "parent",
7430
+ "path",
7431
+ "rename",
7432
+ "status",
7433
+ "toRoot"
7434
+ ])).addOption(new Option("--to-root", "move a leaf document to root and derive its path").conflicts([
7435
+ "parent",
7436
+ "path",
7437
+ "rename",
7438
+ "status",
7439
+ "to"
7440
+ ])).action(async (sourceId, raw) => {
7441
+ if (raw.to !== void 0 || raw.toRoot === true) {
7442
+ await runCanonicalCommand(context, raw, "qmind.move_source", {
7443
+ notebookId: requiredString(raw.nb, "--nb"),
7444
+ sourceId,
7445
+ targetParentSourceId: raw.toRoot === true ? null : requiredString(raw.to, "--to")
7446
+ });
7447
+ return;
7448
+ }
4800
7449
  const patch = {
4801
7450
  ...raw.parent === void 0 ? {} : { parentSourceId: String(raw.parent) },
4802
7451
  ...raw.path === void 0 ? {} : { path: String(raw.path) },
@@ -4804,9 +7453,10 @@ function registerSourceCommands(context, program) {
4804
7453
  ...raw.status === void 0 ? {} : { status: String(raw.status) }
4805
7454
  };
4806
7455
  if (Object.keys(patch).length === 0) throw new QMindError("INVALID_ARGUMENT", "at least one of --parent, --path, --rename or --status is required");
7456
+ const host = await hostFor(context, raw);
4807
7457
  render(context, raw, {
4808
7458
  kind: "source",
4809
- value: await (await hostFor(context, raw)).client.moveSource(requiredString(raw.nb, "--nb"), sourceId, patch)
7459
+ value: await submitCliMutation(async () => host.client.moveSource(requiredString(raw.nb, "--nb"), sourceId, patch))
4810
7460
  });
4811
7461
  });
4812
7462
  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) => {
@@ -4818,24 +7468,32 @@ function registerSourceCommands(context, program) {
4818
7468
  context.io.stdout(`content saved to ${path}\n`);
4819
7469
  }
4820
7470
  });
4821
- 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) => {
7471
+ 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) => {
4822
7472
  const host = await hostFor(context, raw);
4823
7473
  const notebookId = requiredString(raw.nb, "--nb");
4824
7474
  if (raw.force !== true) {
4825
- const record = await host.client.getSource(notebookId, sourceId).catch(() => void 0);
7475
+ const record = await host.client.getSource(notebookId, sourceId);
4826
7476
  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: `)) {
4827
7477
  context.io.stderr("aborted\n");
4828
7478
  context.exitCode = 1;
4829
7479
  return;
4830
7480
  }
4831
7481
  }
4832
- await host.client.deleteSource(notebookId, sourceId);
4833
- context.io.stdout("deleted\n");
7482
+ await submitCliMutation(() => host.client.deleteSource(notebookId, sourceId));
7483
+ if (raw.format === "json" || raw.format === "ndjson") render(context, raw, {
7484
+ kind: "json",
7485
+ value: {
7486
+ notebookId,
7487
+ sourceId,
7488
+ deleted: true
7489
+ }
7490
+ });
7491
+ else context.io.stdout("deleted\n");
4834
7492
  });
4835
7493
  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) => {
4836
7494
  const host = await hostFor(context, raw);
4837
7495
  const rootUrl = requiredString(raw.url, "--url");
4838
- const value = await host.client.importSite(requiredString(raw.nb, "--nb"), {
7496
+ const value = await submitCliMutation(async () => host.client.importSite(requiredString(raw.nb, "--nb"), {
4839
7497
  excludePaths: splitCsv(stringOption(raw, "exclude")),
4840
7498
  includePaths: splitCsv(stringOption(raw, "include")),
4841
7499
  maxPages: numberOption(raw, "maxPages", 50),
@@ -4844,7 +7502,7 @@ function registerSourceCommands(context, program) {
4844
7502
  rootUrl,
4845
7503
  sitemapUrl: optionalString(raw, "sitemap"),
4846
7504
  title: optionalString(raw, "title")
4847
- });
7505
+ }));
4848
7506
  const format = formatOf(raw);
4849
7507
  if (format === "json" || format === "ndjson") render(context, raw, {
4850
7508
  kind: "source",
@@ -4860,14 +7518,14 @@ function registerSourceCommands(context, program) {
4860
7518
  const file = optionalString(raw, "file");
4861
7519
  const filename = optionalString(raw, "filename");
4862
7520
  const mimeType = optionalString(raw, "mime");
4863
- const value = file === void 0 ? await host.client.presignImageUpload(notebookId, sourceId, {
7521
+ const value = file === void 0 ? await submitCliMutation(async () => host.client.presignImageUpload(notebookId, sourceId, {
4864
7522
  filename: requiredString(filename, "--filename"),
4865
7523
  mimeType: requiredString(mimeType, "--mime"),
4866
7524
  size: numberOption(raw, "size", 0)
4867
- }) : await host.client.uploadImage(notebookId, sourceId, await host.createFileSource(file, {
7525
+ })) : await submitCliMutation(async () => host.client.uploadImage(notebookId, sourceId, await host.createFileSource(file, {
4868
7526
  ...filename === void 0 ? {} : { filename },
4869
7527
  ...mimeType === void 0 ? {} : { mimeType }
4870
- }));
7528
+ })));
4871
7529
  if (file !== void 0) context.io.stderr(`uploaded ${file} -> ossKey=${value.ossKey}\n`);
4872
7530
  context.io.stdout(renderQMindCliPresentation({
4873
7531
  kind: "imageUpload",
@@ -4912,11 +7570,11 @@ function registerTaskCommands(context, program) {
4912
7570
  const sourceIds = splitCsv(stringOption(raw, "sources"));
4913
7571
  render(context, raw, {
4914
7572
  kind: "json",
4915
- value: await host.client.createTaskRun(requiredString(raw.nb, "--nb"), {
7573
+ value: await submitCliMutation(async () => host.client.createTaskRun(requiredString(raw.nb, "--nb"), {
4916
7574
  ...sourceIds.length === 0 ? {} : { config: { sourceIds } },
4917
7575
  sceneType: scene,
4918
7576
  trigger: String(raw.trigger ?? "manual")
4919
- })
7577
+ }))
4920
7578
  });
4921
7579
  });
4922
7580
  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) => {
@@ -5006,6 +7664,7 @@ function createQMindCliProgram(context) {
5006
7664
  registerSourceCommands(context, program);
5007
7665
  registerSceneCommands(context, program);
5008
7666
  registerTaskCommands(context, program);
7667
+ registerCanonicalCommands(context, program);
5009
7668
  registerSyncCommand(context, program);
5010
7669
  registerUpdateCommand(context, program);
5011
7670
  return program;
@@ -5022,7 +7681,7 @@ async function runQMindCli(argv, options = {}) {
5022
7681
  updater: options.updater ?? createQMindCliUpdater({ identity: {
5023
7682
  artifactKind: "npm",
5024
7683
  command: distribution.command,
5025
- currentVersion: "4.0.0",
7684
+ currentVersion: "4.2.0",
5026
7685
  distribution: distribution.id,
5027
7686
  executablePath: process.execPath,
5028
7687
  package: distribution.package,
@@ -5043,7 +7702,7 @@ async function runQMindCli(argv, options = {}) {
5043
7702
  } catch (error) {
5044
7703
  if (error instanceof CommanderError) exitCode = error.code === "commander.help" || error.code === "commander.helpDisplayed" || error.code === "commander.version" ? 0 : 2;
5045
7704
  else {
5046
- const rendered = renderQMindCliError(error, requestsJsonOutput(normalized));
7705
+ const rendered = renderQMindCliError(error, requestsJsonOutput(normalized), !requestsNdjsonOutput(normalized));
5047
7706
  if (rendered.stdout.length > 0) io.stdout(rendered.stdout);
5048
7707
  if (rendered.stderr.length > 0) io.stderr(rendered.stderr);
5049
7708
  exitCode = rendered.exitCode;