@reinsjs/brain 0.7.0 → 0.7.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @reinsjs/brain
2
2
 
3
+ ## 0.7.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Republish with the built output: 0.7.0 was published from a stale build and does not contain the `memory({ directories })` option.
8
+
3
9
  ## 0.7.0
4
10
 
5
11
  ### Minor Changes
package/dist/index.d.ts CHANGED
@@ -750,6 +750,8 @@ declare function humanSize(bytes: number): string;
750
750
  * - `create` 对已存在的文件是**覆盖**(工具说明本来就写"creates or overwrites"),回执里说明替换了旧内容
751
751
  * - `view` 超长文件按字符上限截断并提示用 `view_range` 续读;写类操作有单文件大小上限
752
752
  * - 目录在 KV 式存储里是隐含的(有以它为前缀的文件就算存在),所以 `create` 到目录路径、对目录 `str_replace` 都报错
753
+ * - 宿主可声明常设目录(`memory({ directories })`):下面还没有文件也算存在,`view` 返回空列表而不是"不存在",
754
+ * 上级目录的列表里也列出它;删 / 改名一个空的常设目录如实说"是空的"(目录本身由宿主声明,模型删不掉)
753
755
  *
754
756
  * 全部是纯的存储操作,不知道 Socket / 事件 / 命名空间:命名空间由 memory.ts 用 `bindMemoryFs` 包一层。
755
757
  * `rename` 目录与 `delete` 目录不是原子的(MemoryStore 没有事务);顺序都是"先写后删",中途失败最多多出重复,不会丢。
@@ -846,12 +848,19 @@ interface MemoryFs {
846
848
  delete(path: string): Promise<void>;
847
849
  /** 目录下任意深度的全部文件路径,字典序 */
848
850
  listUnder(dir: string): Promise<string[]>;
851
+ /** 宿主声明的常设目录(模型可见的规范路径,已含祖先、不含根):没有文件也算存在。缺省没有 */
852
+ readonly directories?: ReadonlySet<string>;
849
853
  }
854
+ /**
855
+ * 常设目录展开成"自己 + 全部祖先"(不含根):声明 `/memories/team/shared` 时 `/memories/team` 也必须是目录,
856
+ * 否则 view 上级说不存在、view 下级却有内容,自相矛盾。入参须是已规范的模型可见路径。
857
+ */
858
+ declare function expandMemoryDirectories(dirs: readonly string[]): ReadonlySet<string>;
850
859
  /**
851
860
  * 把 MemoryStore 绑到一个命名空间前缀上:存储里的键 = prefix + 模型可见路径。
852
861
  * 多用户宿主用它给每个 principal 一块独立的 /memories(`memory({ namespace })`)。
853
862
  */
854
- declare function bindMemoryFs(store: MemoryStore, prefix?: string): MemoryFs;
863
+ declare function bindMemoryFs(store: MemoryStore, prefix?: string, directories?: ReadonlySet<string>): MemoryFs;
855
864
  interface MemoryLimits {
856
865
  /** 单文件上限(UTF-8 字节):create / str_replace / insert 写出的结果超过即拒绝 */
857
866
  maxFileBytes: number;
@@ -900,6 +909,13 @@ interface MemoryOptions {
900
909
  maxFileBytes?: number;
901
910
  /** view 单次最多返回的字符数(正文部分),超过按行截断并提示用 view_range 续读。缺省 16000(与 Anthropic 工具说明一致) */
902
911
  maxViewChars?: number;
912
+ /**
913
+ * 常设目录(模型可见路径,如 `["/memories/personal", "/memories/project"]`):宿主把记忆分层挂载时,
914
+ * 某层还没有文件也让模型看得见——`view` 它返回空列表而不是"不存在",`view /memories` 也列出它;
915
+ * 祖先目录自动算进来。只改"存不存在"的判定,不放宽任何写操作:常设目录不能被当文件写,模型也删不掉它。
916
+ * 缺省没有(与参考实现一致:没有文件的目录不存在)
917
+ */
918
+ directories?: readonly string[];
903
919
  /** 规则提示:缺省内置英文文案;传字符串替换;false 则不碰系统提示 */
904
920
  rules?: string | false;
905
921
  /** 没有 MemoryStore 时的告警出口(每个 memory() 实例只告警一次)。缺省 console.warn */
@@ -1512,4 +1528,4 @@ declare function parseFetchBlobArgs(raw: unknown): FetchBlobArgs;
1512
1528
  declare function isTextMime(mime: string): boolean;
1513
1529
  declare function spill(opts?: SpillOptions): Socket;
1514
1530
 
1515
- export { APPROVAL_EXPIRY_RULE, APPROVAL_POLICY_IDS, APPROVAL_RULES, APPROVAL_SOCKET_NAME, type ApprovalOptions, BUDGET_SOCKET_NAME, type BudgetDimension, type BudgetHit, type BudgetLimits, type BudgetOptions, COMPACT_INPUT_SCHEMA, COMPACT_REQUEST_RULE, COMPACT_RULES, COMPACT_SOCKET_NAME, COMPACT_TOOL_DESCRIPTION, COMPACT_TOOL_NAME, type CompactArgs, type CompactOptions, type CompactPlan, type CompactRequestInfo, DEFAULT_FORCE_AT, DEFAULT_HANDOFF_REASON, DEFAULT_LAZY_SUMMARY_CHARS, DEFAULT_MAX_CONSECUTIVE_COMPACTIONS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_PIN_TEXT_LENGTH, DEFAULT_MAX_RESULT_TOKENS, DEFAULT_MAX_SUMMARY_CHARS, DEFAULT_MAX_VIEW_CHARS, DEFAULT_PERCEPTION_THRESHOLDS, DEFAULT_PIN_OVERSHOOT_TOLERANCE, DEFAULT_PREVIEW_CHARS, DEFAULT_PREVIEW_LINES, DEFAULT_SKILLS_ROOT, DEFAULT_SKILL_READ_CHARS, DEFAULT_TOOL_FIND_MAX, type ExpiredApproval, FETCH_BLOB_INPUT_SCHEMA, FETCH_BLOB_TOOL_DESCRIPTION, FETCH_BLOB_TOOL_NAME, type FetchBlobArgs, type ForceOptions, HANDOFF_INPUT_SCHEMA, HANDOFF_RULES, HANDOFF_SOCKET_NAME, HANDOFF_TOOL_DESCRIPTION, HANDOFF_TOOL_NAME, type HandoffArgs, type HandoffOptions, type InlineSkill, type InlineSkillsOptions, LAZY_TOOLS_SOCKET_NAME, LAZY_TOOL_RULES, type LazyToolMenu, type LazyToolMenuEntry, type LazyToolsOptions, type LimitDimension, type LoadedSkill, MANIFEST_DEFAULT_EXCLUDE, MANIFEST_HEADING, MAX_MEMORY_PATH_LENGTH, MAX_SKILL_DESCRIPTION_CHARS, MEMORY_COMMANDS, MEMORY_INPUT_SCHEMA, MEMORY_ROOT, MEMORY_RULES, MEMORY_SOCKET_NAME, MEMORY_TOOL_DESCRIPTION, MEMORY_TOOL_NAME, type ManifestOptions, type MemoryCommand, type MemoryFs, type MemoryLimits, type MemoryOp, type MemoryOptions, type MemoryOutcome, PERCEPTION_SOCKET_NAME, PINS_SOCKET_NAME, PIN_INPUT_SCHEMA, PIN_RULES, PIN_TOOL_DESCRIPTION, PIN_TOOL_NAME, type ParsedSkill, type PerceptionLimits, type PerceptionOptions, type PerceptionReading, type PinArgs, type PinMeta, type PinNote, type PinSpec, type PinsOptions, type PlanOptions, type PolicyCall, type PolicyOutcome, type PolicyRule, type PolicyRuleSpec, type PolicyVerdict, type Preview, type PreviewOptions, RECALL_INPUT_SCHEMA, RECALL_TOOL_DESCRIPTION, RECALL_TOOL_NAME, type ReadingOptions, type ReadingThresholds, type RecallArgs, SKILLS_SOCKET_NAME, SKILL_FILE_NAME, SKILL_NAME_RE, SKILL_READ_INPUT_SCHEMA, SKILL_READ_TOOL_DESCRIPTION, SKILL_READ_TOOL_NAME, SKILL_RULES, SPILL_BLOB_MIME, SPILL_RULES, SPILL_SOCKET_NAME, type SkillFrontmatter, type SkillMenu, type SkillMenuEntry, type SkillReadInput, type SkillsOptions, type SpillOptions, TOOL_FIND_INPUT_SCHEMA, TOOL_FIND_TOOL_DESCRIPTION, TOOL_FIND_TOOL_NAME, type TextMeasure, type TextTokenEstimator, type Tier, type ToolFindInput, approval, assertAscending, assertLimits, assertSkillsRoot, bindMemoryFs, budget, budgetUsedOf, byteLength, carriedPins, checkBudget, clipEndByTokens, compact, compactNumber, compactRequestedSinceLastCompaction, compactRequestsSinceLastCompaction, composeHandoffNote, contextUsageRatio, countLines, countModelTurns, countTier, defaultBudgetNote, defaultSummary, defaultTextTokens, evaluatePolicy, executeMemoryCommand, findExpiredApproval, findModelPin, fmt, globToRegExp, handoff, humanSize, inlineSkills, isCompactRequest, isModelCompaction, isPinNoteEvent, isSnapshotPin, isTextMime, isUnder, lastHostPin, lastVisiblePerceptionNote, lastVisibleUserMessage, lazyMenuOf, lazyTools, loadSkillMenu, measureText, memory, modelActedSinceLastCompaction, normalizeRule, parseCompactArgs, parseFetchBlobArgs, parseHandoffArgs, parseMemoryCommand, parsePinArgs, parseRecallArgs, parseSkillMarkdown, parseSkillReadInput, parseToolFindInput, percent, perception, pinInputSchema, pinMetaOf, pinToolDescription, pins, planCompaction, previewOf, rangeTier, readPerception, recallResult, recallTool, renderCompactRequest, renderCompactionSummary, renderLazyToolMenu, renderLoadedTool, renderPerception, renderSkillMenu, renderToolFindResult, resolveMemoryPath, revealedLazyTools, segmentTimelineByTurn, skills, spill, sumSessionTokens, summarizeTool, timelineSoFar, toolFindResultBound, toolReferenceOf, trailingCompactionRun, unfinishedHandoffArgs };
1531
+ export { APPROVAL_EXPIRY_RULE, APPROVAL_POLICY_IDS, APPROVAL_RULES, APPROVAL_SOCKET_NAME, type ApprovalOptions, BUDGET_SOCKET_NAME, type BudgetDimension, type BudgetHit, type BudgetLimits, type BudgetOptions, COMPACT_INPUT_SCHEMA, COMPACT_REQUEST_RULE, COMPACT_RULES, COMPACT_SOCKET_NAME, COMPACT_TOOL_DESCRIPTION, COMPACT_TOOL_NAME, type CompactArgs, type CompactOptions, type CompactPlan, type CompactRequestInfo, DEFAULT_FORCE_AT, DEFAULT_HANDOFF_REASON, DEFAULT_LAZY_SUMMARY_CHARS, DEFAULT_MAX_CONSECUTIVE_COMPACTIONS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_PIN_TEXT_LENGTH, DEFAULT_MAX_RESULT_TOKENS, DEFAULT_MAX_SUMMARY_CHARS, DEFAULT_MAX_VIEW_CHARS, DEFAULT_PERCEPTION_THRESHOLDS, DEFAULT_PIN_OVERSHOOT_TOLERANCE, DEFAULT_PREVIEW_CHARS, DEFAULT_PREVIEW_LINES, DEFAULT_SKILLS_ROOT, DEFAULT_SKILL_READ_CHARS, DEFAULT_TOOL_FIND_MAX, type ExpiredApproval, FETCH_BLOB_INPUT_SCHEMA, FETCH_BLOB_TOOL_DESCRIPTION, FETCH_BLOB_TOOL_NAME, type FetchBlobArgs, type ForceOptions, HANDOFF_INPUT_SCHEMA, HANDOFF_RULES, HANDOFF_SOCKET_NAME, HANDOFF_TOOL_DESCRIPTION, HANDOFF_TOOL_NAME, type HandoffArgs, type HandoffOptions, type InlineSkill, type InlineSkillsOptions, LAZY_TOOLS_SOCKET_NAME, LAZY_TOOL_RULES, type LazyToolMenu, type LazyToolMenuEntry, type LazyToolsOptions, type LimitDimension, type LoadedSkill, MANIFEST_DEFAULT_EXCLUDE, MANIFEST_HEADING, MAX_MEMORY_PATH_LENGTH, MAX_SKILL_DESCRIPTION_CHARS, MEMORY_COMMANDS, MEMORY_INPUT_SCHEMA, MEMORY_ROOT, MEMORY_RULES, MEMORY_SOCKET_NAME, MEMORY_TOOL_DESCRIPTION, MEMORY_TOOL_NAME, type ManifestOptions, type MemoryCommand, type MemoryFs, type MemoryLimits, type MemoryOp, type MemoryOptions, type MemoryOutcome, PERCEPTION_SOCKET_NAME, PINS_SOCKET_NAME, PIN_INPUT_SCHEMA, PIN_RULES, PIN_TOOL_DESCRIPTION, PIN_TOOL_NAME, type ParsedSkill, type PerceptionLimits, type PerceptionOptions, type PerceptionReading, type PinArgs, type PinMeta, type PinNote, type PinSpec, type PinsOptions, type PlanOptions, type PolicyCall, type PolicyOutcome, type PolicyRule, type PolicyRuleSpec, type PolicyVerdict, type Preview, type PreviewOptions, RECALL_INPUT_SCHEMA, RECALL_TOOL_DESCRIPTION, RECALL_TOOL_NAME, type ReadingOptions, type ReadingThresholds, type RecallArgs, SKILLS_SOCKET_NAME, SKILL_FILE_NAME, SKILL_NAME_RE, SKILL_READ_INPUT_SCHEMA, SKILL_READ_TOOL_DESCRIPTION, SKILL_READ_TOOL_NAME, SKILL_RULES, SPILL_BLOB_MIME, SPILL_RULES, SPILL_SOCKET_NAME, type SkillFrontmatter, type SkillMenu, type SkillMenuEntry, type SkillReadInput, type SkillsOptions, type SpillOptions, TOOL_FIND_INPUT_SCHEMA, TOOL_FIND_TOOL_DESCRIPTION, TOOL_FIND_TOOL_NAME, type TextMeasure, type TextTokenEstimator, type Tier, type ToolFindInput, approval, assertAscending, assertLimits, assertSkillsRoot, bindMemoryFs, budget, budgetUsedOf, byteLength, carriedPins, checkBudget, clipEndByTokens, compact, compactNumber, compactRequestedSinceLastCompaction, compactRequestsSinceLastCompaction, composeHandoffNote, contextUsageRatio, countLines, countModelTurns, countTier, defaultBudgetNote, defaultSummary, defaultTextTokens, evaluatePolicy, executeMemoryCommand, expandMemoryDirectories, findExpiredApproval, findModelPin, fmt, globToRegExp, handoff, humanSize, inlineSkills, isCompactRequest, isModelCompaction, isPinNoteEvent, isSnapshotPin, isTextMime, isUnder, lastHostPin, lastVisiblePerceptionNote, lastVisibleUserMessage, lazyMenuOf, lazyTools, loadSkillMenu, measureText, memory, modelActedSinceLastCompaction, normalizeRule, parseCompactArgs, parseFetchBlobArgs, parseHandoffArgs, parseMemoryCommand, parsePinArgs, parseRecallArgs, parseSkillMarkdown, parseSkillReadInput, parseToolFindInput, percent, perception, pinInputSchema, pinMetaOf, pinToolDescription, pins, planCompaction, previewOf, rangeTier, readPerception, recallResult, recallTool, renderCompactRequest, renderCompactionSummary, renderLazyToolMenu, renderLoadedTool, renderPerception, renderSkillMenu, renderToolFindResult, resolveMemoryPath, revealedLazyTools, segmentTimelineByTurn, skills, spill, sumSessionTokens, summarizeTool, timelineSoFar, toolFindResultBound, toolReferenceOf, trailingCompactionRun, unfinishedHandoffArgs };
package/dist/index.js CHANGED
@@ -1761,8 +1761,18 @@ function parseMemoryCommand(raw) {
1761
1761
  };
1762
1762
  }
1763
1763
  }
1764
- function bindMemoryFs(store, prefix = "") {
1764
+ function expandMemoryDirectories(dirs) {
1765
+ const out = /* @__PURE__ */ new Set();
1766
+ for (const d of dirs) {
1767
+ for (let p = d; p !== MEMORY_ROOT && p.length > MEMORY_ROOT.length; p = p.slice(0, p.lastIndexOf("/"))) {
1768
+ out.add(p);
1769
+ }
1770
+ }
1771
+ return out;
1772
+ }
1773
+ function bindMemoryFs(store, prefix = "", directories) {
1765
1774
  return {
1775
+ ...directories !== void 0 && directories.size > 0 ? { directories } : {},
1766
1776
  read: (path) => store.read(prefix + path),
1767
1777
  write: (path, content) => store.write(prefix + path, content),
1768
1778
  delete: (path) => store.delete(prefix + path),
@@ -1792,7 +1802,7 @@ var ok = (text, op) => ({
1792
1802
  var fail2 = (text) => ({ text, isError: true });
1793
1803
  var notFound = (path) => fail2(`The path ${path} does not exist. Please provide a valid path.`);
1794
1804
  async function isDirectory(fs, path) {
1795
- if (path === MEMORY_ROOT) return true;
1805
+ if (path === MEMORY_ROOT || fs.directories?.has(path) === true) return true;
1796
1806
  return (await fs.listUnder(path)).length > 0;
1797
1807
  }
1798
1808
  async function readForEdit(fs, path) {
@@ -1858,6 +1868,10 @@ async function listing(fs, dir) {
1858
1868
  const second = `${first}/${rel[1]}`;
1859
1869
  if (rel.length >= 2) entries.set(second, (entries.get(second) ?? 0) + size);
1860
1870
  }
1871
+ for (const d of fs.directories ?? []) {
1872
+ if (isUnder(dir, d) && d.slice(dir.length + 1).split("/").length <= 2 && !entries.has(d))
1873
+ entries.set(d, 0);
1874
+ }
1861
1875
  const rows = [`${humanSize(total)} ${dir}`];
1862
1876
  for (const p of [...entries.keys()].sort()) rows.push(`${humanSize(entries.get(p) ?? 0)} ${p}`);
1863
1877
  return ok(`Here're the files and directories up to 2 levels deep in ${dir}:
@@ -1944,7 +1958,11 @@ async function remove(fs, path) {
1944
1958
  return ok(`Successfully deleted ${path}`, { op: "delete", path, bytes: byteLength(content) });
1945
1959
  }
1946
1960
  const children = await fs.listUnder(path);
1947
- if (children.length === 0) return fail2(`Error: The path ${path} does not exist`);
1961
+ if (children.length === 0) {
1962
+ if (fs.directories?.has(path))
1963
+ return fail2(`Error: The directory ${path} is empty; there is nothing to delete`);
1964
+ return fail2(`Error: The path ${path} does not exist`);
1965
+ }
1948
1966
  let bytes = 0;
1949
1967
  for (const child of children) {
1950
1968
  bytes += byteLength(await fs.read(child) ?? "");
@@ -1971,7 +1989,12 @@ async function rename(fs, oldPath, newPath) {
1971
1989
  });
1972
1990
  }
1973
1991
  const children = await fs.listUnder(oldPath);
1974
- if (children.length === 0) return fail2(`Error: The path ${oldPath} does not exist`);
1992
+ if (children.length === 0) {
1993
+ if (fs.directories?.has(oldPath)) {
1994
+ return fail2(`Error: The directory ${oldPath} is empty; there is nothing to rename`);
1995
+ }
1996
+ return fail2(`Error: The path ${oldPath} does not exist`);
1997
+ }
1975
1998
  if (isUnder(oldPath, newPath)) return fail2(`Error: Cannot move ${oldPath} into itself (${newPath})`);
1976
1999
  let bytes = 0;
1977
2000
  for (const child of children) {
@@ -2024,6 +2047,7 @@ function memory(opts = {}) {
2024
2047
  if (opts.namespace !== void 0 && typeof opts.namespace !== "function") {
2025
2048
  throw new RangeError("memory.namespace must be a function");
2026
2049
  }
2050
+ const directories = expandMemoryDirectories(resolveDirectories(opts.directories));
2027
2051
  const namespace = opts.namespace ?? (() => "");
2028
2052
  const warn = opts.warn ?? ((message) => console.warn(message));
2029
2053
  let warned = false;
@@ -2042,7 +2066,7 @@ function memory(opts = {}) {
2042
2066
  isError: true
2043
2067
  };
2044
2068
  }
2045
- const fs = bindMemoryFs(ctx.memory, namespace(ctx));
2069
+ const fs = bindMemoryFs(ctx.memory, namespace(ctx), directories);
2046
2070
  const outcome = await executeMemoryCommand(fs, cmd, limits);
2047
2071
  if (outcome.op) {
2048
2072
  ctx.emit({
@@ -2075,6 +2099,27 @@ function memory(opts = {}) {
2075
2099
  }
2076
2100
  return socket;
2077
2101
  }
2102
+ function resolveDirectories(dirs) {
2103
+ if (dirs === void 0) return [];
2104
+ if (!Array.isArray(dirs))
2105
+ throw new RangeError(`memory.directories must be an array of paths, got ${typeof dirs}`);
2106
+ return dirs.map((d, i) => {
2107
+ let p;
2108
+ try {
2109
+ p = resolveMemoryPath(d);
2110
+ } catch {
2111
+ throw new RangeError(
2112
+ `memory.directories[${i}] must be a path under ${MEMORY_ROOT}, got ${JSON.stringify(d)}`
2113
+ );
2114
+ }
2115
+ if (p === MEMORY_ROOT) {
2116
+ throw new RangeError(
2117
+ `memory.directories[${i}] must be a path under ${MEMORY_ROOT}, not the root itself`
2118
+ );
2119
+ }
2120
+ return p;
2121
+ });
2122
+ }
2078
2123
 
2079
2124
  // src/perception/reading.ts
2080
2125
  import { contextOverheadOf as contextOverheadOf2 } from "@reinsjs/core";
@@ -2913,6 +2958,7 @@ export {
2913
2958
  defaultTextTokens,
2914
2959
  evaluatePolicy,
2915
2960
  executeMemoryCommand,
2961
+ expandMemoryDirectories,
2916
2962
  findExpiredApproval,
2917
2963
  findModelPin,
2918
2964
  fmt,