@sparkelf/dsh-knowledge-base 0.5.3 → 0.6.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/lib/index.js CHANGED
@@ -16352,62 +16352,129 @@ var MemoryStore = class {
16352
16352
  //#endregion
16353
16353
  //#region src/memorySettings.ts
16354
16354
  /**
16355
- * Per-user memory settings: whether personal memory learning is enabled.
16355
+ * Per-user memory settings: whether personal memory learning is enabled and how
16356
+ * often the guardian consolidates what it learned.
16356
16357
  *
16357
16358
  * The product rule (design §22.2) is deliberately conservative:
16358
16359
  *
16359
16360
  * - a new user is **paused** (`memoryEnabled: false`), so no extraction starts
16360
16361
  * until the user explicitly confirms the enable dialog;
16362
+ * - an administrator or super administrator (a holder of the configured DataOps
16363
+ * permission, by default `kb:config:manage`) starts **enabled** on the first
16364
+ * read when no settings file exists yet. The global default is never flipped:
16365
+ * the administrator decision is injected through {@link MemorySettingsDefaultPolicy},
16366
+ * and an explicit `false` written by that administrator always wins;
16361
16367
  * - the switch is per user, not per session, and survives restarts;
16362
16368
  * - the file is local state under `<usersRoot>/<userId>/settings.json`, never
16363
16369
  * knowledge content and never Git content;
16364
16370
  * - a missing or unreadable file is a valid "paused" answer, not an error. Only
16365
16371
  * a filesystem permission failure is surfaced.
16366
16372
  *
16373
+ * The persisted shape is version 2 (`memoryEnabled` + `consolidationIntervalMinutes`).
16374
+ * Version 1 files (only `memoryEnabled`, or even a hand-written bare boolean) are
16375
+ * still read: a missing interval falls back to 60 minutes, and a malformed
16376
+ * interval never turns a remembered enable/disable decision into a different one.
16377
+ *
16367
16378
  * The route/UI layer reads `read()` or `isEnabled()` and writes through
16368
- * `setEnabled()`; every write is atomic (tmp + rename).
16379
+ * `save()`; every write is atomic (tmp + rename) and persists both fields in one
16380
+ * rename so a page save can never leave the switch and the interval disagreeing.
16369
16381
  *
16370
16382
  * @module @sparkelf/dsh-knowledge-base/memory-settings
16371
16383
  */
16372
16384
  /** File name inside one user's directory. */
16373
16385
  const MEMORY_SETTINGS_FILE = "settings.json";
16386
+ /** Longest allowed consolidation interval, in minutes. */
16387
+ const MEMORY_CONSOLIDATION_INTERVAL_MAX = 1440;
16374
16388
  /** The paused default for a user who has never confirmed the enable dialog. */
16375
16389
  const DEFAULT_MEMORY_SETTINGS = Object.freeze({
16376
- version: 1,
16377
- memoryEnabled: false
16390
+ version: 2,
16391
+ memoryEnabled: false,
16392
+ consolidationIntervalMinutes: 60
16378
16393
  });
16394
+ /** A malformed interval or write patch; the route maps this to HTTP 400. */
16395
+ var MemorySettingsError = class extends Error {
16396
+ code;
16397
+ name = "MemorySettingsError";
16398
+ constructor(code, message) {
16399
+ super(message);
16400
+ this.code = code;
16401
+ }
16402
+ };
16403
+ /**
16404
+ * Validate one consolidation interval.
16405
+ *
16406
+ * The guard is strict on purpose: a fractional value or a value outside
16407
+ * 15–1440 is a client bug, not a number to clamp silently. The route turns this
16408
+ * error into a 400 so the page can show the allowed range.
16409
+ *
16410
+ * @param value - raw value from an API body or a hand-edited file.
16411
+ * @returns the accepted integer.
16412
+ * @throws {MemorySettingsError} when the value is not an integer in range.
16413
+ */
16414
+ function normalizeConsolidationInterval(value) {
16415
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new MemorySettingsError("invalid-interval", "consolidationIntervalMinutes must be an integer");
16416
+ if (value < 15 || value > 1440) throw new MemorySettingsError("invalid-interval", `consolidationIntervalMinutes must be between ${String(15)} and ${String(MEMORY_CONSOLIDATION_INTERVAL_MAX)}`);
16417
+ return value;
16418
+ }
16419
+ /** Read a stored interval leniently: an invalid legacy value falls back to 60. */
16420
+ function readStoredInterval(value) {
16421
+ try {
16422
+ return normalizeConsolidationInterval(value);
16423
+ } catch {
16424
+ return 60;
16425
+ }
16426
+ }
16379
16427
  /**
16380
16428
  * Atomic settings store over `<usersRoot>/<userId>/settings.json`.
16381
16429
  *
16382
16430
  * `read()` tolerates a corrupt file by returning the paused default; the next
16383
- * `setEnabled()` rewrites it. This keeps the memory page usable after a partial
16384
- * write or a hand-edited file instead of failing the whole route.
16431
+ * write rewrites it. This keeps the memory page usable after a partial write or
16432
+ * a hand-edited file instead of failing the whole route.
16385
16433
  */
16386
16434
  var MemorySettingsStore = class {
16387
16435
  usersRoot;
16388
- constructor(usersRoot) {
16436
+ defaultPolicy;
16437
+ constructor(usersRoot, defaultPolicy) {
16389
16438
  if (typeof usersRoot !== "string" || usersRoot.trim() === "") throw new Error("memory-settings: usersRoot must be a non-empty path");
16390
16439
  this.usersRoot = usersRoot;
16440
+ this.defaultPolicy = defaultPolicy;
16391
16441
  }
16392
16442
  /** Absolute settings file for one user. */
16393
16443
  filePath(userId) {
16394
16444
  assertPathSegment(userId, "userId");
16395
16445
  return join(this.usersRoot, userId, MEMORY_SETTINGS_FILE);
16396
16446
  }
16447
+ /** The first-read default for one user, from the injected policy. */
16448
+ async defaultFor(userId, options) {
16449
+ if (options.defaultEnabled !== void 0) return {
16450
+ ...DEFAULT_MEMORY_SETTINGS,
16451
+ memoryEnabled: options.defaultEnabled === true
16452
+ };
16453
+ if (this.defaultPolicy === void 0) return { ...DEFAULT_MEMORY_SETTINGS };
16454
+ try {
16455
+ return {
16456
+ ...DEFAULT_MEMORY_SETTINGS,
16457
+ memoryEnabled: await this.defaultPolicy.memoryEnabled(userId) === true
16458
+ };
16459
+ } catch {
16460
+ return { ...DEFAULT_MEMORY_SETTINGS };
16461
+ }
16462
+ }
16397
16463
  /**
16398
16464
  * Read one user's settings.
16399
16465
  *
16400
- * Missing, malformed, or schema-invalid content returns the paused default.
16401
- * A file with a boolean `memoryEnabled` is accepted even if `version` is
16402
- * missing, so an older/hand-written settings file does not silently turn
16403
- * memory on (the boolean still decides).
16466
+ * Missing content uses {@link MemorySettingsReadOptions.defaultEnabled} or the
16467
+ * injected policy. Malformed content stays paused even for an administrator:
16468
+ * a corrupt file is not evidence that the administrator opted in. A file with
16469
+ * a boolean `memoryEnabled` is accepted even if `version`/the interval is
16470
+ * missing, so old settings files keep their explicit choice.
16404
16471
  */
16405
- async read(userId) {
16472
+ async read(userId, options = {}) {
16406
16473
  let source;
16407
16474
  try {
16408
16475
  source = await readFile(this.filePath(userId), "utf8");
16409
16476
  } catch (error) {
16410
- if (isErrno$1(error, "ENOENT") || isErrno$1(error, "ENOTDIR")) return { ...DEFAULT_MEMORY_SETTINGS };
16477
+ if (isErrno$1(error, "ENOENT") || isErrno$1(error, "ENOTDIR")) return this.defaultFor(userId, options);
16411
16478
  throw error;
16412
16479
  }
16413
16480
  let parsed;
@@ -16420,28 +16487,50 @@ var MemorySettingsStore = class {
16420
16487
  const memoryEnabled = parsed.memoryEnabled;
16421
16488
  if (typeof memoryEnabled !== "boolean") return { ...DEFAULT_MEMORY_SETTINGS };
16422
16489
  return {
16423
- version: 1,
16424
- memoryEnabled
16490
+ version: 2,
16491
+ memoryEnabled,
16492
+ consolidationIntervalMinutes: readStoredInterval(parsed.consolidationIntervalMinutes)
16425
16493
  };
16426
16494
  }
16427
16495
  /** Whether learning is enabled for this user (default `false`). */
16428
- async isEnabled(userId) {
16429
- return (await this.read(userId)).memoryEnabled;
16496
+ async isEnabled(userId, options = {}) {
16497
+ return (await this.read(userId, options)).memoryEnabled;
16430
16498
  }
16431
16499
  /**
16432
- * Persist the enable/pause switch atomically.
16500
+ * Persist a partial settings change in one atomic write.
16501
+ *
16502
+ * The current value is read first so a page that saves only the interval
16503
+ * cannot accidentally pause memory (nor enable it). An explicit boolean in
16504
+ * the patch always wins; an absent field is preserved.
16433
16505
  *
16434
16506
  * @returns the normalized settings actually written.
16435
16507
  */
16436
- async setEnabled(userId, enabled) {
16437
- if (typeof enabled !== "boolean") throw new Error("memory-settings: memoryEnabled must be a boolean");
16508
+ async save(userId, patch, options = {}) {
16509
+ if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) throw new MemorySettingsError("invalid-settings", "at least one memory setting must be supplied");
16510
+ if (patch.memoryEnabled !== void 0 && typeof patch.memoryEnabled !== "boolean") throw new MemorySettingsError("invalid-settings", "memoryEnabled must be a boolean");
16511
+ const interval = patch.consolidationIntervalMinutes === void 0 ? void 0 : normalizeConsolidationInterval(patch.consolidationIntervalMinutes);
16512
+ const current = await this.read(userId, options);
16438
16513
  const settings = {
16439
- version: 1,
16440
- memoryEnabled: enabled
16514
+ version: 2,
16515
+ memoryEnabled: patch.memoryEnabled ?? current.memoryEnabled,
16516
+ consolidationIntervalMinutes: interval ?? current.consolidationIntervalMinutes
16441
16517
  };
16442
16518
  await writeFileAtomic(this.filePath(userId), `${JSON.stringify(settings, null, 2)}\n`, { mode: 384 });
16443
16519
  return settings;
16444
16520
  }
16521
+ /**
16522
+ * Persist the enable/pause switch atomically, preserving the interval.
16523
+ *
16524
+ * @returns the normalized settings actually written.
16525
+ */
16526
+ async setEnabled(userId, enabled, options = {}) {
16527
+ if (typeof enabled !== "boolean") throw new MemorySettingsError("invalid-settings", "memoryEnabled must be a boolean");
16528
+ return this.save(userId, { memoryEnabled: enabled }, options);
16529
+ }
16530
+ /** Persist one interval while preserving the switch. */
16531
+ async setConsolidationInterval(userId, minutes, options = {}) {
16532
+ return this.save(userId, { consolidationIntervalMinutes: minutes }, options);
16533
+ }
16445
16534
  };
16446
16535
  function isErrno$1(error, code) {
16447
16536
  return typeof error === "object" && error !== null && "code" in error && error.code === code;
@@ -16478,6 +16567,20 @@ const fail = (status, error, code, extra) => ({
16478
16567
  ...extra
16479
16568
  }
16480
16569
  });
16570
+ /** The settings shape the page reads; bounds travel with the value so the UI never guesses. */
16571
+ function settingsPayload(settings) {
16572
+ return {
16573
+ enabled: settings.memoryEnabled,
16574
+ consolidationIntervalMinutes: settings.consolidationIntervalMinutes,
16575
+ intervalMin: 15,
16576
+ intervalMax: MEMORY_CONSOLIDATION_INTERVAL_MAX,
16577
+ intervalDefault: 60
16578
+ };
16579
+ }
16580
+ /** Options for a settings read that already knows the caller's first-read default. */
16581
+ function readOptions(defaultEnabled) {
16582
+ return defaultEnabled === void 0 ? {} : { defaultEnabled };
16583
+ }
16481
16584
  /** One short line for the table; whitespace collapsed and bounded. */
16482
16585
  function clipLine(value, max = 80) {
16483
16586
  const clean = value.replace(/\s+/gu, " ").trim();
@@ -16624,6 +16727,29 @@ function readUpdatePatch(body, entry) {
16624
16727
  }
16625
16728
  return { patch };
16626
16729
  }
16730
+ /** Extract and validate the settings write, translating `enabled` to the stored field. */
16731
+ function readSettingsPatch(body, options) {
16732
+ if (Object.prototype.hasOwnProperty.call(body, "userId")) return { error: fail(400, "userId must not be supplied; the caller is resolved from the request", "invalid") };
16733
+ const unknown = Object.keys(body).filter((key) => key !== "enabled" && key !== "consolidationIntervalMinutes");
16734
+ if (unknown.length > 0) return { error: fail(400, `unsupported settings field(s): ${unknown.join(", ")}`, "invalid") };
16735
+ if (options.requireEnabled && body.enabled === void 0) return { error: fail(400, "enabled must be a boolean", "invalid") };
16736
+ const patch = {};
16737
+ if (body.enabled !== void 0) {
16738
+ if (typeof body.enabled !== "boolean") return { error: fail(400, "enabled must be a boolean", "invalid") };
16739
+ patch.memoryEnabled = body.enabled;
16740
+ }
16741
+ if (body.consolidationIntervalMinutes !== void 0) try {
16742
+ patch.consolidationIntervalMinutes = normalizeConsolidationInterval(body.consolidationIntervalMinutes);
16743
+ } catch (error) {
16744
+ if (error instanceof MemorySettingsError) return { error: fail(400, error.message, error.code, {
16745
+ min: 15,
16746
+ max: MEMORY_CONSOLIDATION_INTERVAL_MAX
16747
+ }) };
16748
+ throw error;
16749
+ }
16750
+ if (patch.memoryEnabled === void 0 && patch.consolidationIntervalMinutes === void 0) return { error: fail(400, "at least one memory setting must be supplied", "invalid") };
16751
+ return { patch };
16752
+ }
16627
16753
  /** Reconcile the personal-memory graph; a derived failure must not undo the write. */
16628
16754
  async function syncGraph(graphWriter) {
16629
16755
  try {
@@ -16635,6 +16761,7 @@ async function syncGraph(graphWriter) {
16635
16761
  }
16636
16762
  /** Map a store/validation failure to an actionable status; unknown errors escape. */
16637
16763
  function failureOf(error) {
16764
+ if (error instanceof MemorySettingsError) return fail(400, error.message, error.code);
16638
16765
  if (error instanceof MemoryValidationError) return fail(400, error.message, "invalid-memory", { issues: error.issues });
16639
16766
  if (error instanceof MemoryStoreError) {
16640
16767
  const status = error.code === "not-found" || error.code === "sop-not-found" ? 404 : error.code === "invalid-memory-file" || error.code === "duplicate-id" || error.code === "duplicate-key" || error.code === "sop-exists" || error.code === "sop-terminal" ? 409 : 400;
@@ -16657,9 +16784,9 @@ async function handleMemoryRoute(input) {
16657
16784
  try {
16658
16785
  switch (method) {
16659
16786
  case "memory.list": {
16660
- const [enabled, entries] = await Promise.all([settings.isEnabled(caller.userId), store.listEntries()]);
16787
+ const [settingsState, entries] = await Promise.all([settings.read(caller.userId, readOptions(input.defaultEnabled)), store.listEntries()]);
16661
16788
  return ok({
16662
- enabled,
16789
+ enabled: settingsState.memoryEnabled,
16663
16790
  entries: entries.map(listRow)
16664
16791
  });
16665
16792
  }
@@ -16694,11 +16821,18 @@ async function handleMemoryRoute(input) {
16694
16821
  ...graphSyncWarning === void 0 ? {} : { graphSyncWarning }
16695
16822
  });
16696
16823
  }
16697
- case "memory.settings": return ok({ enabled: await settings.isEnabled(caller.userId) });
16824
+ case "memory.settings": return ok(settingsPayload(await settings.read(caller.userId, readOptions(input.defaultEnabled))));
16698
16825
  case "memory.set-enabled": {
16699
- if (typeof body.enabled !== "boolean") return fail(400, "enabled must be a boolean", "invalid");
16700
- const next = await settings.setEnabled(caller.userId, body.enabled);
16701
- return ok({ enabled: next.memoryEnabled });
16826
+ const built = readSettingsPatch(body, { requireEnabled: true });
16827
+ if ("error" in built) return built.error;
16828
+ const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
16829
+ return ok(settingsPayload(next));
16830
+ }
16831
+ case "memory.save-settings": {
16832
+ const built = readSettingsPatch(body, { requireEnabled: false });
16833
+ if ("error" in built) return built.error;
16834
+ const next = await settings.save(caller.userId, built.patch, readOptions(input.defaultEnabled));
16835
+ return ok(settingsPayload(next));
16702
16836
  }
16703
16837
  default: return fail(404, `unknown memory method: ${method}`, "not-found");
16704
16838
  }
@@ -17030,6 +17164,40 @@ async function syncPersonalMemoryGraph(options) {
17030
17164
  *
17031
17165
  * @module @sparkelf/dsh-knowledge-base/guardian-session
17032
17166
  */
17167
+ /**
17168
+ * Default bound for guardian session resolution and message delivery.
17169
+ *
17170
+ * The guardian TURN itself is asynchronous (DSH's own inbox is the queue), so
17171
+ * this cannot bound model latency. What it does bound is the plugin's wait for
17172
+ * a standard-mode agent to be created/resumed or for `followup` to accept the
17173
+ * message; without it a hung agent loop can block a normal session's tool call
17174
+ * indefinitely.
17175
+ */
17176
+ const DEFAULT_GUARDIAN_TIMEOUT_MS = 3e4;
17177
+ /** A guardian operation exceeded its bounded wait. */
17178
+ var GuardianTimeoutError = class extends Error {
17179
+ name = "GuardianTimeoutError";
17180
+ code = "unreachable";
17181
+ constructor(message) {
17182
+ super(message);
17183
+ }
17184
+ };
17185
+ /** Bound one promise without cancelling the underlying operation. */
17186
+ function withGuardianTimeout(operation, timeoutMs, label) {
17187
+ if (timeoutMs === void 0 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return operation;
17188
+ return new Promise((resolve, reject) => {
17189
+ const timer = setTimeout(() => {
17190
+ reject(new GuardianTimeoutError(`${label} timed out after ${String(timeoutMs)}ms`));
17191
+ }, timeoutMs);
17192
+ operation.then((value) => {
17193
+ clearTimeout(timer);
17194
+ resolve(value);
17195
+ }, (error) => {
17196
+ clearTimeout(timer);
17197
+ reject(error);
17198
+ });
17199
+ });
17200
+ }
17033
17201
  /** Title is display-only but stable, so an operator can recognize the session. */
17034
17202
  const GUARDIAN_SESSION_TITLE = "记忆守护会话";
17035
17203
  /** Skill the guardian must load before doing anything else. */
@@ -17244,8 +17412,8 @@ async function resolveOrCreateGuardianUncached(host, userId) {
17244
17412
  * session. This is the ONLY send path used by the tool and the triggers.
17245
17413
  */
17246
17414
  async function sendToGuardian(host, userId, message) {
17247
- const resolved = await resolveOrCreateGuardian(host, userId);
17248
- const delivery = await host.deliverText(resolved.agent, renderGuardianMessage(message));
17415
+ const resolved = await withGuardianTimeout(resolveOrCreateGuardian(host, userId), host.timeoutMs, "guardian session resolution");
17416
+ const delivery = await withGuardianTimeout(Promise.resolve(host.deliverText(resolved.agent, renderGuardianMessage(message))), host.timeoutMs, "guardian message delivery");
17249
17417
  await new GuardianSessionStore(host.usersRoot).write({
17250
17418
  ...resolved.state,
17251
17419
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -21134,6 +21302,7 @@ const Config = z.object({
21134
21302
  memoryUsersRoot: z.string().default(""),
21135
21303
  memorySkillsRoot: z.string().default(""),
21136
21304
  memoryIdleMinutes: z.number().default(30),
21305
+ memoryDefaultEnabledPermission: z.string().default("kb:config:manage"),
21137
21306
  permitted: z.string().default("*"),
21138
21307
  nfsServer: z.string().default(""),
21139
21308
  storageProtocol: z.union([z.const("nfs"), z.const("sshfs")]).default("nfs"),
@@ -22243,7 +22412,8 @@ async function fetchCaller(ctx, config) {
22243
22412
  if (!isTeamDeployment(config)) return {
22244
22413
  userId: LOCAL_USER_ID,
22245
22414
  label: "本地用户",
22246
- roleCodes: []
22415
+ roleCodes: [],
22416
+ permissions: []
22247
22417
  };
22248
22418
  const body = await request(ctx, config, ENDPOINTS.me);
22249
22419
  const profile = body.user ?? body;
@@ -22251,6 +22421,7 @@ async function fetchCaller(ctx, config) {
22251
22421
  if (userId === "") throw new KnowledgeError("DataOps did not report the caller id", "not-configured");
22252
22422
  const label = typeof profile.displayName === "string" ? profile.displayName : typeof profile.username === "string" ? profile.username : userId;
22253
22423
  const roleCodes = Array.isArray(profile.roles) ? profile.roles.map((role) => role.code).filter((code) => typeof code === "string" && code !== "") : [];
22424
+ const permissions = Array.isArray(profile.permissions) ? profile.permissions.filter((key) => typeof key === "string" && key !== "") : [];
22254
22425
  let department = readDepartmentOf(profile.department);
22255
22426
  if (department !== void 0 && department.pathCodes === void 0) {
22256
22427
  const recovered = await readDepartmentPathFromCatalog(ctx, config, department.code).catch(() => void 0);
@@ -22263,6 +22434,7 @@ async function fetchCaller(ctx, config) {
22263
22434
  userId,
22264
22435
  label,
22265
22436
  roleCodes,
22437
+ permissions,
22266
22438
  ...department === void 0 ? {} : {
22267
22439
  departmentCode: department.code,
22268
22440
  departmentName: department.name,
@@ -23052,7 +23224,7 @@ function permissionForKbRoute(method) {
23052
23224
  if (method === "create" || method === "edit" || method === "move" || method === "upload" || method === "rename") return "kb:file:write";
23053
23225
  if (method === "trash" || method === "trash.remove" || method === "trash.restore") return "kb:file:delete";
23054
23226
  if (method === "memory.list" || method === "memory.get" || method === "memory.settings") return "kb:file:read";
23055
- if (method === "memory.update" || method === "memory.set-enabled") return "kb:file:write";
23227
+ if (method === "memory.update" || method === "memory.set-enabled" || method === "memory.save-settings") return "kb:file:write";
23056
23228
  if (method === "memory.forget") return "kb:file:delete";
23057
23229
  if (method === "index" || method === "extract.retry") return "kb:file:extract";
23058
23230
  if (method === "index.status") return "kb:file:read";
@@ -25649,11 +25821,13 @@ function apply(ctx, deploymentConfig) {
25649
25821
  case "memory.update":
25650
25822
  case "memory.forget":
25651
25823
  case "memory.settings":
25652
- case "memory.set-enabled": {
25824
+ case "memory.set-enabled":
25825
+ case "memory.save-settings": {
25653
25826
  const caller = await fetchCaller(host, config);
25654
25827
  if (!isSafeUserId(caller.userId)) return writeJson(res, 400, { error: "unsafe caller id; memory is scoped to the authenticated user" });
25655
25828
  const body = await readJsonBody(req);
25656
25829
  const personalScope = personalScopeRootFor(caller.userId);
25830
+ const defaultEnabled = config.memoryDefaultEnabledPermission.trim() !== "" && (caller.permissions ?? []).includes(config.memoryDefaultEnabledPermission);
25657
25831
  const result = await handleMemoryRoute({
25658
25832
  method,
25659
25833
  body,
@@ -25663,6 +25837,7 @@ function apply(ctx, deploymentConfig) {
25663
25837
  },
25664
25838
  store: new MemoryStore(join(personalScope, PERSONAL_MEMORY_FOLDER)),
25665
25839
  settings: new MemorySettingsStore(memoryUsersRoot),
25840
+ defaultEnabled,
25666
25841
  graphWriter: new MemoryGraphWriter({ scopeRoot: personalScope })
25667
25842
  });
25668
25843
  return writeJson(res, result.status, result.body);
@@ -27007,7 +27182,16 @@ function apply(ctx, deploymentConfig) {
27007
27182
  const configured = (config.memoryUsersRoot ?? "").trim();
27008
27183
  return configured === "" ? join(localConfig(config).actualRoot, ".memory", "users") : resolveStorageRoot(configured);
27009
27184
  })();
27010
- const memorySettings = new MemorySettingsStore(memoryUsersRoot);
27185
+ const memorySettings = new MemorySettingsStore(memoryUsersRoot, { memoryEnabled: async (userId) => {
27186
+ const permission = config.memoryDefaultEnabledPermission.trim();
27187
+ if (permission === "" || !isTeamDeployment(config)) return false;
27188
+ try {
27189
+ const caller = await fetchCaller(host, config);
27190
+ return caller.userId === userId && (caller.permissions ?? []).includes(permission);
27191
+ } catch {
27192
+ return false;
27193
+ }
27194
+ } });
27011
27195
  const memoryToolHost = {
27012
27196
  resolveCaller: async () => {
27013
27197
  const caller = await managementHost.context();
@@ -27073,6 +27257,7 @@ function apply(ctx, deploymentConfig) {
27073
27257
  const guardianSessionHost = {
27074
27258
  usersRoot: memoryUsersRoot,
27075
27259
  cwd: process.cwd(),
27260
+ timeoutMs: DEFAULT_GUARDIAN_TIMEOUT_MS,
27076
27261
  getAgent: (sessionId) => guardianRegistry?.get(sessionId),
27077
27262
  createAgent: async ({ sessionId, cwd, title }) => {
27078
27263
  if (guardianLoop === void 0) throw new Error("the DSH agent loop is not available");
@@ -76,8 +76,26 @@ export interface KnowledgeContextMenuProps {
76
76
  shareCopy: ShareDialogCopy;
77
77
  /** Close the menu. */
78
78
  onClose: () => void;
79
+ /** Open one file for preview. Absent on a surface with no preview. */
80
+ onOpen?: (path: string) => void;
81
+ /**
82
+ * Move one row into a destination directory, both tree-relative.
83
+ *
84
+ * The destination is typed by the reader and resolved by the caller, because only the
85
+ * page knows the caller's authoritative `personal/<id>/...` path. Absent means this
86
+ * surface has no move route and the entry is not offered.
87
+ */
88
+ onMove?: (row: ContextTarget, destination: string) => Promise<void> | void;
79
89
  /** Open the permission surface for this path. */
80
- onGrant: (path: string) => void;
90
+ onGrant?: (path: string) => void;
91
+ /**
92
+ * Whether the caller may manage grants.
93
+ *
94
+ * The permission entry is hidden unless this is exactly true AND `onGrant` is present:
95
+ * a row that opens a surface the backend will refuse is worse than no row, and the
96
+ * answer comes from the Host rather than being derived here.
97
+ */
98
+ canManageGrants?: boolean;
81
99
  /** Toggle the pin state for this path. */
82
100
  onPin: (path: string, pinned: boolean) => void;
83
101
  /** Whether this path is currently pinned. */
@@ -177,6 +177,29 @@ export interface KnowledgeFileTreeProps {
177
177
  * reports where the click landed.
178
178
  */
179
179
  onPasteInto?: (directory: string) => void;
180
+ /**
181
+ * Open the page's own row menu at the pointer.
182
+ *
183
+ * This is how the KNOWLEDGE menu reaches a tree row. The explorer builds a workspace
184
+ * file menu inside itself (copy path, new folder, upload here), which is the wrong
185
+ * vocabulary for a curated knowledge export and cannot carry knowledge actions such
186
+ * as preview, permissions, or trash. When this hook is present the wrapper suppresses
187
+ * that menu for a row and hands the gesture to the page, which renders the same
188
+ * `KnowledgeContextMenu` the table uses. Omitted (the upload destination picker), the
189
+ * explorer menu is left untouched.
190
+ */
191
+ onRowContextMenu?: (target: {
192
+ relPath: string;
193
+ name: string;
194
+ isDir: boolean;
195
+ }, at: {
196
+ x: number;
197
+ y: number;
198
+ }, selection?: readonly {
199
+ relPath: string;
200
+ name: string;
201
+ isDir: boolean;
202
+ }[]) => void;
180
203
  /**
181
204
  * Called the moment an extraction is REQUESTED for one document, before it settles.
182
205
  *
@@ -65,6 +65,19 @@ export interface KnowledgeMemoryViewProps {
65
65
  enabled: boolean;
66
66
  settingsLoading: boolean;
67
67
  settingsError?: string;
68
+ /** Saved consolidation interval, in minutes. */
69
+ consolidationIntervalMinutes: number;
70
+ /** Allowed interval bounds; reported by the host so the page never guesses. */
71
+ intervalMin: number;
72
+ intervalMax: number;
73
+ /** The number currently typed in the interval field. */
74
+ intervalDraft: string;
75
+ intervalBusy: boolean;
76
+ intervalError?: string;
77
+ /** True after a successful save until the field changes again. */
78
+ intervalSaved: boolean;
79
+ onIntervalDraftChange: (value: string) => void;
80
+ onSaveInterval: () => void;
68
81
  list: MemoryListSnapshot;
69
82
  query: string;
70
83
  typeFilter: string;
@@ -45,6 +45,7 @@ export declare const en: {
45
45
  readonly grantsManaged: "Authorization is managed in DataOps.";
46
46
  readonly menu: "Sections";
47
47
  readonly 'menu.search': "Search";
48
+ readonly actionOpen: "Open preview";
48
49
  readonly actionDownload: "Download";
49
50
  readonly actionRename: "Rename…";
50
51
  readonly actionPin: "Pin";
@@ -678,6 +679,12 @@ export declare const en: {
678
679
  readonly memoryEnabled: "On";
679
680
  readonly memoryPaused: "Paused";
680
681
  readonly memoryPausedNotice: "Memory is paused. No new memories are learned; existing memories stay visible and can still be forgotten.";
682
+ readonly memoryIntervalLabel: "Consolidation interval";
683
+ readonly memoryIntervalHint: "15–1440 minutes. When the interval elapses, the guardian consolidates memory.";
684
+ readonly memoryIntervalMinutes: "min";
685
+ readonly memorySaveInterval: "Save";
686
+ readonly memoryIntervalSaved: "Saved";
687
+ readonly memoryIntervalInvalid: "Enter a whole number between 15 and 1440 minutes.";
681
688
  readonly memorySettingsFailed: "Could not read the memory setting.";
682
689
  readonly memoryEnableTitle: "Turn on memory";
683
690
  readonly memoryEnableBody: "When memory is on, the assistant learns preferences, facts, pitfalls and methods from your conversations, and they may affect later answers and actions. Existing memories are kept, and you can pause or forget any single memory at any time.";
@@ -44,6 +44,13 @@ export interface GuardianSessionHost {
44
44
  usersRoot: string;
45
45
  /** Absolute session cwd; defaults to the host process cwd. */
46
46
  cwd?: string;
47
+ /**
48
+ * Optional bound for session resolution and message delivery.
49
+ *
50
+ * Omitted keeps the previous unbounded behavior for embedders that already
51
+ * impose their own timeout; the plugin passes {@link DEFAULT_GUARDIAN_TIMEOUT_MS}.
52
+ */
53
+ timeoutMs?: number;
47
54
  /** `ctx.agents.get(sessionId)`. */
48
55
  getAgent(sessionId: string): GuardianAgentRef | undefined;
49
56
  /** `ctx.agentLoop.createAgent(ctx, { sessionId, meta: { cwd } })` with NO agentPreset. */
@@ -82,6 +89,22 @@ export interface GuardianSendResult {
82
89
  /** True when this call lazily created or recreated the session. */
83
90
  created: boolean;
84
91
  }
92
+ /**
93
+ * Default bound for guardian session resolution and message delivery.
94
+ *
95
+ * The guardian TURN itself is asynchronous (DSH's own inbox is the queue), so
96
+ * this cannot bound model latency. What it does bound is the plugin's wait for
97
+ * a standard-mode agent to be created/resumed or for `followup` to accept the
98
+ * message; without it a hung agent loop can block a normal session's tool call
99
+ * indefinitely.
100
+ */
101
+ export declare const DEFAULT_GUARDIAN_TIMEOUT_MS = 30000;
102
+ /** A guardian operation exceeded its bounded wait. */
103
+ export declare class GuardianTimeoutError extends Error {
104
+ readonly name = "GuardianTimeoutError";
105
+ readonly code = "unreachable";
106
+ constructor(message: string);
107
+ }
85
108
  /** Title is display-only but stable, so an operator can recognize the session. */
86
109
  export declare const GUARDIAN_SESSION_TITLE = "\u8BB0\u5FC6\u5B88\u62A4\u4F1A\u8BDD";
87
110
  /** Skill the guardian must load before doing anything else. */
@@ -92,6 +92,18 @@ export interface Config {
92
92
  memorySkillsRoot: string;
93
93
  /** Idle minutes before a normal session notifies the memory guardian. */
94
94
  memoryIdleMinutes: number;
95
+ /**
96
+ * DataOps permission whose holders start memory enabled when they have no
97
+ * settings file yet.
98
+ *
99
+ * The default `kb:config:manage` is granted by the DataOps permission
100
+ * manifest to the global administrator and super administrator roles only.
101
+ * A deployment can point this at a stricter key, or set it to an empty string
102
+ * to disable the default entirely; the KB package never hard-codes a role
103
+ * name. An explicit `memoryEnabled: false` in the user's settings file always
104
+ * wins over this default.
105
+ */
106
+ memoryDefaultEnabledPermission: string;
95
107
  /** Comma-separated export spec of clients allowed to mount the NFS export. */
96
108
  permitted: string;
97
109
  /** Host serving the export, as an address or `address:/path` pseudo root. */
@@ -707,6 +719,15 @@ export interface KnowledgeCaller {
707
719
  departmentPathCodes?: string[];
708
720
  /** The organization path's display names, index-aligned with the codes. */
709
721
  departmentPathNames?: string[];
722
+ /**
723
+ * DataOps permission keys resolved for the caller by `/auth/me`.
724
+ *
725
+ * Used by product defaults that must follow the existing permission model
726
+ * (for example the administrator memory default). Authorization decisions
727
+ * still go through the backend; this is the projection the plugin already
728
+ * receives, not a second policy source.
729
+ */
730
+ permissions?: string[];
710
731
  }
711
732
  /**
712
733
  * Read a `{ code, name }` pair DataOps nests under the profile.
@@ -17,7 +17,7 @@
17
17
  * `source.sessionId` only because the detail drawer needs it for 「查看原文」.
18
18
  *
19
19
  * Methods: `memory.list`, `memory.get`, `memory.update`, `memory.forget`,
20
- * `memory.settings`, `memory.set-enabled`.
20
+ * `memory.settings`, `memory.set-enabled`, `memory.save-settings`.
21
21
  *
22
22
  * @module @sparkelf/dsh-knowledge-base/memory-routes
23
23
  */
@@ -38,6 +38,12 @@ export interface MemoryRouteInput {
38
38
  caller: MemoryRouteCaller;
39
39
  store: MemoryStore;
40
40
  settings: MemorySettingsStore;
41
+ /**
42
+ * First-read default for this caller, already resolved from the DataOps
43
+ * principal by the host. Omitted means the store's injected policy decides;
44
+ * `false` is a real value and must not be confused with "not supplied".
45
+ */
46
+ defaultEnabled?: boolean;
41
47
  /** Manifest reconciliation after a write/delete; failure never undoes the memory write. */
42
48
  graphWriter: Pick<MemoryGraphWriter, 'syncAll'>;
43
49
  }