Release Brain 0.10.6 with bundled Mnemon
This commit is contained in:
parent
645e47bd59
commit
12d9cabe1d
49
README.md
49
README.md
|
|
@ -1,17 +1,15 @@
|
|||
# dsh-brain
|
||||
|
||||
> **0.10.5**:记忆界面改为读取 Mnemon——Brain 面板的概览与记忆页签通过宿主里
|
||||
> Mnemon 的只读通道取数,dsh-brain 不再自存记忆(旧本地库保留作兜底,后续移除)。
|
||||
> 其余见下。
|
||||
> Brain 内置 Mnemon 后端。Brain 页面和普通记忆工具使用同一套 Mnemon 数据。
|
||||
> 旧 Brain 本地和 LongMemory 记忆数据保留原处。
|
||||
>
|
||||
> **0.10.3**:插件按功能拆成六个可单独开关的子插件,新增可选的原始记录层
|
||||
> `dsh-brain-raw`(见「六个子插件」);同步清理了不可达的防御性分支与重复
|
||||
> 响应校验。0.10.1 起技能同步按内容与更新时间自动解决冲突(0.9.9/0.9.10
|
||||
> 语义),令牌环境变量**绑定服务地址**(见「配置」)。
|
||||
|
||||
把 DeepSeek Harness 接到 LongMemory 云端记忆服务:每轮对话结束自动上报一条
|
||||
活动记录(只上传元数据),并把云端记忆库变成 agent 可用的工具;同时双向
|
||||
同步云端技能中心与本机技能目录。
|
||||
Brain 为 DeepSeek Harness 提供 Mnemon 记忆和项目文档浏览,可通过 LongMemory
|
||||
上报回合活动元数据,并在云端技能中心和本机技能目录之间双向同步。
|
||||
|
||||
当前版本 **0.10.5**,含宿主端与浏览器端两部分:宿主端负责活动上报、
|
||||
记忆工具注册与技能同步。浏览器 UI 有三个入口:
|
||||
|
|
@ -27,7 +25,7 @@
|
|||
| 活动上报 | 监听 `session/event` 的 `turn/start`、`turn/end`,每个结束的回合调用一次 `POST /activity/turn`。上报字段只有 6 个:`client_id`、`conversation_id`、`turn_id`、`status`、`started_at`、`completed_at`。 |
|
||||
| 幂等 | `turn_id` 为 `<sessionId>:<turn>`,服务端按 `turn_id` 去重,重试不会重复计数。 |
|
||||
| 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试。切换账号或换服务地址后,旧队列条目会被丢弃,不会发到新账号。 |
|
||||
| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具实时读写云端记忆库。 |
|
||||
| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具通过内置 Mnemon 读写记忆。 |
|
||||
| 技能同步 | 云端技能中心 ↔ 本机技能目录双向同步,冲突按内容与时间自动取较新(详见「技能同步」)。 |
|
||||
| 配置页 | 设置中的「云端记忆」提供完整配置,另有独立页面 `GET /dsh-brain`。 |
|
||||
|
||||
|
|
@ -51,8 +49,7 @@
|
|||
| `dsh-brain-mcp` | MCP 管理页开关(页签与宿主桥接能力声明;MCP 连接本身由宿主 `dsh-mcp-connector` 管理,本插件不做 MCP 云同步)。 |
|
||||
| `dsh-brain-ui` | 左侧栏 Brain 总面板与 better-sidebar 项目记忆页签;配置页与状态/能力/配置路由。 |
|
||||
|
||||
- 停掉 `dsh-brain-cloudsync` 后活动上报与技能同步停止,但记忆读写工具
|
||||
仍可用(它们实时访问云端)。停掉 `dsh-brain-memory` 才会移除记忆工具。
|
||||
- `dsh-brain-cloudsync` 控制活动上报与云端技能同步。`dsh-brain-memory` 注册记忆工具,`dsh-brain-mnemon` 提供工具和页面读取的后端。
|
||||
- 共享服务(设置、客户端、同步引擎)由进程级内核统一构造,关掉再开不会
|
||||
重复实例;设置持久化在 `$DSH_HOME/dsh-brain.json`(侧车文件为权威,
|
||||
插件行的 config 只作首次种子)。
|
||||
|
|
@ -71,8 +68,7 @@ dsh plugin --profile desktop add dsh-brain
|
|||
`http://127.0.0.1:<当次端口>/dsh-brain` 使用完整配置,旧 `/cloud-memory` 路由保留为别名。
|
||||
|
||||
> `baseUrl` 默认是占位符 `https://your-memory-host/api/longmemory`。
|
||||
> **首次使用必须先把它改成你自己的 LongMemory 服务地址**(配置页里填,
|
||||
> 或写进 `$DSH_HOME/dsh-brain.json`),否则上报与工具都会连接失败。
|
||||
> 配置自己的 LongMemory 地址后可使用云端活动上报和技能同步。内置 Mnemon 可独立使用。
|
||||
|
||||
## 登录(推荐)
|
||||
|
||||
|
|
@ -128,19 +124,9 @@ dsh plugin --profile desktop add dsh-brain
|
|||
> 一个 key 只有一种 scope,所以需要三个令牌:只做上报就只填活动令牌,
|
||||
> 只做检索就只填记忆令牌。
|
||||
|
||||
## 本地优先记忆
|
||||
## 旧版 Brain 本地记忆
|
||||
|
||||
第一阶段默认使用本地记忆,不需要账号、令牌或网络:全局数据在
|
||||
`$DSH_HOME/brain`,项目数据在 `<项目>/.dsh/brain`,不会创建 `.mnemon`。
|
||||
全局与项目空间在第一次使用记忆工具时自动创建,重启和多窗口复用已有空间;
|
||||
项目 `.dsh/.gitignore` 只忽略 `brain/`,不会忽略整个 `.dsh`。
|
||||
|
||||
记忆工具默认走本地存储;只有当 `cloudMemoryEnabled=true` 且配置了
|
||||
memory 令牌时才切换为云端适配器。自动总结只保存用户明确表达的长期信息,
|
||||
自动画像只把明确偏好写入 USER.md,推测内容留在待确认区。Provider SDK
|
||||
来自 `src/mnemon/fork`,完整上游源码保存在 `vendor/dsh-mnemon`(独立 fork,
|
||||
包名 `dsh-brain-mnemon`)。详见 `docs/LOCAL_MEMORY_IMPLEMENTATION.md` 与
|
||||
`docs/MNEMON_FORK.md`;验收对照见 `docs/LOCAL_MEMORY_ACCEPTANCE.md`。
|
||||
旧版全局数据位于 `$DSH_HOME/brain`,项目数据位于 `<项目>/.dsh/brain`。Brain 保留这套存储供旧版记录、部门记忆和自动摘要使用。当前普通 `memory_*` 工具通过内置 Mnemon 读写。相关实现见 `docs/LOCAL_MEMORY_IMPLEMENTATION.md`、`docs/LOCAL_MEMORY_ACCEPTANCE.md` 和 `docs/MNEMON_FORK.md`。
|
||||
|
||||
## 原始记录层(dsh-brain-raw)
|
||||
|
||||
|
|
@ -167,8 +153,21 @@ memory 令牌时才切换为云端适配器。自动总结只保存用户明确
|
|||
- `memory_raw_read`:按 `session_id` + `seq` 读某一条原话,或按 `offset/limit` 浏览;
|
||||
- `memory_raw_status`:查看保存目录、会话数、记录数、占用空间和保留天数。
|
||||
|
||||
原始记录只保存在本地,不参与云端同步;写入前会经过现有的密钥脱敏规则,
|
||||
默认保留 90 天。停用 `dsh-brain-raw` 行即停止采集。
|
||||
原始记录写入本地 JSONL。采集范围是用户和助手的消息文本,每条先经密钥脱敏,再按默认 16,000 字符上限保存。原文文件默认保留 90 天。停用 `dsh-brain-raw` 行即停止采集。Mnemon 的外部 Provider 和 Git 同步都使用 Mnemon 自己的数据源。
|
||||
|
||||
## 内置 Mnemon 后端
|
||||
|
||||
Brain 内含 Mnemon Host、四个数据源(Runtime、Documents、Memory Spaces、Skills)、五个策略(默认三层、通用、范围限定、轻上下文、自动捕获)以及九个 Memory Spaces Provider。默认启用三层策略,其他策略可在 Mnemon 工作台按需选择。Mnemon 设置和工作台随 Brain 的 Web 客户端加载。
|
||||
|
||||
- 全局 Brain 页和不带 `project_id` 的记忆工具使用 Mnemon Runtime。全局 `memory_add` 写入工作记忆,省略 `tags` 和 `sector`。
|
||||
- 项目记忆页使用当前会话的工作区。工具调用时用 `memory_projects` 返回的 ID 指定 `project_id`。项目写入使用工作区的可写默认记忆空间,或唯一可写空间。新工作区需要先配置一个可写的 Mnemon 记忆空间。
|
||||
- `memory_read` 接受 `memory_search`、`memory_list`、`memory_add` 返回的 Mnemon ID。旧 Brain 本地和 LongMemory 数据没有自动迁入。
|
||||
|
||||
## Mnemon 远程接入
|
||||
|
||||
- Brain 内置 Mnemon 默认设置 `remoteAccess: disabled`,关闭 DSH 远程 Mnemon 服务。本地工作台和记忆工具仍可使用。需要远程读取时,可在宿主配置 `remoteAccess: read-only` 并重启。远程写入记忆、修改配置和发起同步需要 `remoteAccess: trusted-host`,仍受 Mnemon 的写入设置和能力限制。Brain 的 LongMemory 云同步默认关闭。
|
||||
- Memory Spaces 支持外部服务。内置适配器包括 OpenViking、Honcho、Mem0、Hindsight、Holographic、RetainDB、ByteRover、Supermemory,以及本地 Mnemon Native。服务按 Provider 配置端点、权限和空间。
|
||||
- Mnemon 还提供 Git 备份和同步,可配置仓库和同步范围。Brain 的原始对话 JSONL 由独立记录层管理。
|
||||
|
||||
## Mnemon 集成(记忆空间 Provider)
|
||||
|
||||
|
|
|
|||
46332
client/index.js
46332
client/index.js
File diff suppressed because one or more lines are too long
108
cordis.patch.yml
108
cordis.patch.yml
|
|
@ -1,10 +1,5 @@
|
|||
# dsh-brain bundle patch — six toggleable sub-plugins.
|
||||
#
|
||||
# Local-only build: this package is never published, so these rows are the
|
||||
# only way the plugin reaches the desktop profile tree. The host Loader
|
||||
# resolves each row `name` as a subpath export of this package; all rows
|
||||
# load in one process and share the kernel (src/kernel.ts), so each row
|
||||
# only registers its own routes / tools / timers.
|
||||
# dsh-brain bundle patch. The original six entries share the Brain kernel.
|
||||
# The Mnemon backend has its own Loader entry and contribution graph.
|
||||
#
|
||||
# Toggling: the host Settings → Plugins page (and dshmarket) write
|
||||
# `- id: <row> / disabled: true` lines into the profile patch, keyed by row
|
||||
|
|
@ -22,7 +17,7 @@
|
|||
- id: dsh-brain-cloudsync
|
||||
name: dsh-brain/cloudsync
|
||||
config:
|
||||
enabled: true
|
||||
enabled: false
|
||||
baseUrl: https://your-memory-host/api/longmemory
|
||||
clientId: dsh-desktop
|
||||
skillsSyncEnabled: true
|
||||
|
|
@ -43,3 +38,100 @@
|
|||
name: dsh-brain
|
||||
config:
|
||||
entry: ui
|
||||
# Mount the tracked fork and its components through this package's host exports.
|
||||
- id: dsh-brain-mnemon-bundle
|
||||
name: cordis:group
|
||||
group: true
|
||||
disabled: !!js >-
|
||||
(() => {
|
||||
let bundle = ctx[Symbol.for('cordis.entry')];
|
||||
while (bundle && !/(?:^|-)mnemon-bundle$/.test(bundle.options.id)) {
|
||||
bundle = bundle.parent?.ctx.fiber.entry;
|
||||
}
|
||||
if (!bundle?.subgroup) return false;
|
||||
const coreId = bundle.options.id.replace(/-bundle$/, '');
|
||||
const core = [...loader.entries()].find(entry =>
|
||||
entry.parent === bundle.subgroup && entry.options.id === coreId);
|
||||
const disabled = core?.options.disabled;
|
||||
return disabled?.__jsExpr
|
||||
? Boolean(core.evaluate(disabled.__jsExpr))
|
||||
: Boolean(disabled);
|
||||
})()
|
||||
config:
|
||||
- id: dsh-brain-mnemon
|
||||
# Core/Host and default settings. Sources own their independent Entries.
|
||||
name: dsh-brain/mnemon
|
||||
config:
|
||||
routingGuidance: true
|
||||
lifecycleEnabled: true
|
||||
recallMode: guided
|
||||
writebackMode: guided
|
||||
idleReviewMs: 30000
|
||||
storageScope: workspaces
|
||||
tabEnabled: true
|
||||
writeEnabled: true
|
||||
remoteAccess: disabled
|
||||
timeoutMs: 10000
|
||||
defaultRecallLimit: 10
|
||||
embedding:
|
||||
enabled: false
|
||||
endpoint: http://localhost:11434
|
||||
model: nomic-embed-text
|
||||
recallQuality:
|
||||
policy: strict-v1
|
||||
lowScoreThreshold: 0.25
|
||||
highScoreThreshold: 0.6
|
||||
candidateMultiplier: 3
|
||||
maxMediumResults: 4
|
||||
maxRankedResults: 4
|
||||
maxUnknownResults: 2
|
||||
- id: dsh-brain-mnemon-source-runtime
|
||||
name: dsh-brain/mnemon/source-runtime
|
||||
- id: dsh-brain-mnemon-source-documents
|
||||
name: dsh-brain/mnemon/source-documents
|
||||
- id: dsh-brain-mnemon-source-memory-spaces
|
||||
name: dsh-brain/mnemon/source-memory-spaces
|
||||
config:
|
||||
# Every default Provider is an
|
||||
# explicit child. A custom parent composition may choose a subset.
|
||||
providers:
|
||||
- use: dsh-brain/mnemon/provider-mnemon-native
|
||||
instanceId: mnemon-native
|
||||
- use: dsh-brain/mnemon/provider-openviking
|
||||
instanceId: openviking
|
||||
- use: dsh-brain/mnemon/provider-honcho
|
||||
instanceId: honcho
|
||||
- use: dsh-brain/mnemon/provider-mem0
|
||||
instanceId: mem0
|
||||
- use: dsh-brain/mnemon/provider-hindsight
|
||||
instanceId: hindsight
|
||||
- use: dsh-brain/mnemon/provider-holographic
|
||||
instanceId: holographic
|
||||
- use: dsh-brain/mnemon/provider-retaindb
|
||||
instanceId: retaindb
|
||||
- use: dsh-brain/mnemon/provider-byterover
|
||||
instanceId: byterover
|
||||
- use: dsh-brain/mnemon/provider-supermemory
|
||||
instanceId: supermemory
|
||||
# Skills keep DSH's own files and their evolution data; the page lives
|
||||
# in the Memory System and nothing joins a model View.
|
||||
- id: dsh-brain-mnemon-source-skills
|
||||
name: dsh-brain/mnemon/source-skills
|
||||
- id: dsh-brain-mnemon-strategy-default-three-tier
|
||||
name: dsh-brain/mnemon/strategy-default-three-tier
|
||||
# A second main Strategy; memoryView.strategyTypeId selects which one
|
||||
# composes the View. It stays off until selected.
|
||||
- id: dsh-brain-mnemon-strategy-general
|
||||
name: dsh-brain/mnemon/strategy-general
|
||||
disabled: true
|
||||
# v0.5 ships these narrowly scoped enhancements with the Starter so the
|
||||
# Settings switches are always available. They remain opt-in.
|
||||
- id: dsh-brain-mnemon-strategy-auto-capture
|
||||
name: dsh-brain/mnemon/strategy-auto-capture
|
||||
disabled: true
|
||||
- id: dsh-brain-mnemon-strategy-light-context
|
||||
name: dsh-brain/mnemon/strategy-light-context
|
||||
disabled: true
|
||||
- id: dsh-brain-mnemon-strategy-scoped
|
||||
name: dsh-brain/mnemon/strategy-scoped
|
||||
disabled: true
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { brainKernel } from "../kernel.js";
|
||||
import { createMemoryTools } from "../memory/tools.js";
|
||||
import { createMnemonMemoryRemote } from "../memory/mnemon-remote.js";
|
||||
import { mnemonToolsFromContext } from "../mnemon/read-service.js";
|
||||
import { createDepartmentTools } from "../memory/departments-tools.js";
|
||||
import { conversationIdOf, redactSecrets, textOf, turnOf } from "../reporter.js";
|
||||
export const name = 'dsh-brain-memory';
|
||||
|
|
@ -16,7 +18,14 @@ export function apply(ctx, config) {
|
|||
const tools = toolsCtx.tools;
|
||||
if (tools === undefined)
|
||||
return;
|
||||
for (const tool of createMemoryTools(kernel.toolDeps())) {
|
||||
const remote = createMnemonMemoryRemote(() => mnemonToolsFromContext(toolsCtx));
|
||||
for (const tool of createMemoryTools({
|
||||
remote: () => remote,
|
||||
settings: () => {
|
||||
const settings = kernel.settings();
|
||||
return { enabled: settings.memoryEnabled, defaultK: settings.localMemoryK };
|
||||
},
|
||||
})) {
|
||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-memory: tool ${tool.name}`);
|
||||
}
|
||||
for (const tool of createDepartmentTools(kernel.departmentToolDeps())) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,200 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
const PROJECT_LIST_LIMIT = 1000;
|
||||
const CATEGORY_BY_SECTOR = {
|
||||
semantic: 'fact',
|
||||
episodic: 'context',
|
||||
procedural: 'general',
|
||||
emotional: 'general',
|
||||
reflective: 'insight',
|
||||
};
|
||||
function row(value) {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
||||
throw new Error('Mnemon 返回了意外的结果格式。');
|
||||
return value;
|
||||
}
|
||||
function rows(value) {
|
||||
if (!Array.isArray(value))
|
||||
throw new Error('Mnemon 返回了意外的条目列表格式。');
|
||||
return value.map(row);
|
||||
}
|
||||
function text(value) {
|
||||
return typeof value === 'string' && value !== '' ? value : undefined;
|
||||
}
|
||||
function time(value) {
|
||||
const timestamp = typeof value === 'string' ? Date.parse(value) : value;
|
||||
return typeof timestamp === 'number' && Number.isFinite(timestamp) ? timestamp : undefined;
|
||||
}
|
||||
function rpcValue(result) {
|
||||
if (!result.ok)
|
||||
throw new Error(result.error.message ?? result.error.code ?? 'Mnemon 请求失败。');
|
||||
return result.value;
|
||||
}
|
||||
function failure(status, code, message) {
|
||||
return { ok: false, error: { status, code, message } };
|
||||
}
|
||||
function runtimeId(entry) {
|
||||
const identity = JSON.stringify([entry.target, entry.created_at, entry.content]);
|
||||
return 'mnemon-rt:' + createHash('sha256').update(identity).digest('hex');
|
||||
}
|
||||
function projectId(workspaceId, memoryBodyId, id) {
|
||||
return 'mnemon-sp:' + Buffer.from(JSON.stringify([workspaceId, memoryBodyId, id])).toString('base64url');
|
||||
}
|
||||
function decodeProjectId(id) {
|
||||
if (!/^mnemon-sp:[A-Za-z0-9_-]{1,16000}$/.test(id))
|
||||
return undefined;
|
||||
try {
|
||||
const decoded = JSON.parse(Buffer.from(id.slice(10), 'base64url').toString('utf8'));
|
||||
if (!Array.isArray(decoded) || decoded.length !== 3 || !decoded.every(value => typeof value === 'string' && value !== ''))
|
||||
return undefined;
|
||||
const [workspaceId, memoryBodyId, memoryId] = decoded;
|
||||
if (id !== projectId(workspaceId, memoryBodyId, memoryId))
|
||||
return undefined;
|
||||
return { workspaceId, memoryBodyId, id: memoryId };
|
||||
}
|
||||
catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
function runtimeHit(entry) {
|
||||
const content = text(entry.content);
|
||||
if (content === undefined)
|
||||
throw new Error('Mnemon Runtime 条目缺少正文。');
|
||||
const created = time(entry.created_at);
|
||||
const updated = time(entry.updated_at);
|
||||
return {
|
||||
id: runtimeId(entry), content, project_id: null,
|
||||
...(created === undefined ? {} : { created_at: created }),
|
||||
...(updated === undefined ? {} : { updated_at: updated }),
|
||||
...(text(entry.target) === undefined ? {} : { target: entry.target }),
|
||||
};
|
||||
}
|
||||
function projectHit(entry, workspaceId) {
|
||||
const id = text(entry.id);
|
||||
const memoryBodyId = text(entry.memoryBodyId);
|
||||
const content = text(entry.content);
|
||||
if (id === undefined || memoryBodyId === undefined || content === undefined)
|
||||
throw new Error('Mnemon 项目条目缺少可读取的标识或正文。');
|
||||
const created = time(entry.created_at ?? entry.createdAt);
|
||||
const updated = time(entry.updated_at ?? entry.updatedAt);
|
||||
return {
|
||||
id: projectId(workspaceId, memoryBodyId, id), content, project_id: workspaceId,
|
||||
tags: Array.isArray(entry.tags) ? entry.tags.filter((tag) => typeof tag === 'string') : [],
|
||||
...(created === undefined ? {} : { created_at: created }),
|
||||
...(updated === undefined ? {} : { updated_at: updated }),
|
||||
...(text(entry.category) === undefined ? {} : { category: entry.category }),
|
||||
};
|
||||
}
|
||||
function newestFirst(hits) {
|
||||
return hits.sort((left, right) => (right.created_at ?? 0) - (left.created_at ?? 0) || (left.id ?? '').localeCompare(right.id ?? ''));
|
||||
}
|
||||
function matchingWorkspace(bridge, project) {
|
||||
if (!bridge.workspaces().some(workspace => workspace.id === project))
|
||||
throw new Error('找不到该 DSH 工作区,请先用 memory_projects 查找项目 ID。');
|
||||
return project;
|
||||
}
|
||||
async function runtimeHits(bridge) {
|
||||
const snapshot = row(rpcValue(await bridge.read('runtime-memory', {})));
|
||||
return newestFirst(rows(snapshot.entries).map(runtimeHit));
|
||||
}
|
||||
async function writableSpace(bridge, workspaceId) {
|
||||
const directory = row(rpcValue(await bridge.read('body-directory', { workspaceId })));
|
||||
const spaces = rows(directory.items).filter(space => {
|
||||
const provider = row(space.provider);
|
||||
return text(space.id) !== undefined && space.active === true && space.providerEnabled !== false
|
||||
&& row(provider.capabilities).remember === true;
|
||||
});
|
||||
const defaults = spaces.filter(space => space.mnemonDefault === true);
|
||||
const candidates = defaults.length > 0 ? defaults : spaces;
|
||||
const selected = candidates.length === 1 ? text(candidates[0]?.id) : undefined;
|
||||
if (selected === undefined)
|
||||
throw new Error('该工作区没有唯一可写的 Mnemon 记忆空间。请在 Mnemon 中配置默认空间。');
|
||||
return selected;
|
||||
}
|
||||
/** Use the same live Mnemon sources as Brain's global and project views. */
|
||||
export function createMnemonMemoryRemote(resolveBridge) {
|
||||
async function invoke(operation) {
|
||||
try {
|
||||
const bridge = resolveBridge();
|
||||
if (bridge === undefined)
|
||||
return failure(503, 'mnemon_unavailable', '当前宿主没有可用的 Mnemon 服务。');
|
||||
return await operation(bridge);
|
||||
}
|
||||
catch (error) {
|
||||
return failure(502, 'mnemon_error', error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
return {
|
||||
search: (query, k, project) => invoke(async (bridge) => {
|
||||
if (project === undefined) {
|
||||
const needle = query.toLocaleLowerCase();
|
||||
const matched = (await runtimeHits(bridge)).filter(hit => hit.content?.toLocaleLowerCase().includes(needle));
|
||||
return { ok: true, status: 200, data: { matches: matched.slice(0, k), total: matched.length, search_mode: 'keyword' } };
|
||||
}
|
||||
const workspaceId = matchingWorkspace(bridge, project);
|
||||
const result = row(rpcValue(await bridge.read('search', { workspaceId, query, mode: 'keyword', limit: k })));
|
||||
const matches = rows(result.results).map(entry => projectHit(entry, workspaceId));
|
||||
return { ok: true, status: 200, data: { matches, total: matches.length, search_mode: text(result.mode) ?? 'keyword' } };
|
||||
}),
|
||||
read: id => invoke(async (bridge) => {
|
||||
const missing = () => failure(404, 'mnemon_memory_not_found', '没有找到该 Mnemon 记忆。');
|
||||
if (/^mnemon-rt:[a-f0-9]{64}$/.test(id)) {
|
||||
const matches = (await runtimeHits(bridge)).filter(hit => hit.id === id);
|
||||
if (matches.length > 1)
|
||||
return failure(409, 'mnemon_memory_ambiguous', '有多条 Mnemon Runtime 条目匹配此 ID。');
|
||||
return matches[0] === undefined ? missing() : { ok: true, status: 200, data: matches[0] };
|
||||
}
|
||||
const target = decodeProjectId(id);
|
||||
if (target === undefined)
|
||||
return missing();
|
||||
matchingWorkspace(bridge, target.workspaceId);
|
||||
const result = rpcValue(await bridge.read('memory-exact', target));
|
||||
if (result === null)
|
||||
return missing();
|
||||
const hit = projectHit(row(result), target.workspaceId);
|
||||
if (hit.id !== id)
|
||||
return missing();
|
||||
return { ok: true, status: 200, data: hit };
|
||||
}),
|
||||
add: input => invoke(async (bridge) => {
|
||||
const { content, operationId, project, tags, sector } = input;
|
||||
if (project === undefined) {
|
||||
if ((tags?.length ?? 0) !== 0 || sector !== undefined)
|
||||
return failure(400, 'mnemon_runtime_metadata_unsupported', '全局 Mnemon Runtime 条目不支持标签或分类。请省略 tags 和 sector。');
|
||||
const result = row(rpcValue(await bridge.append('runtime-memory', { action: 'add', target: 'memory', content, operationId })));
|
||||
if (result.success !== true || text(result.added) === undefined)
|
||||
throw new Error('Mnemon 没有确认保存该 Runtime 条目。');
|
||||
const matches = (await runtimeHits(bridge)).filter(hit => hit.target === 'memory' && hit.content === result.added);
|
||||
const id = matches.length === 1 ? matches[0]?.id : undefined;
|
||||
if (id === undefined)
|
||||
throw new Error('Mnemon 返回了保存回执,但 Runtime 中无法唯一定位该条目。');
|
||||
return { ok: true, status: 200, data: { id, operation_id: operationId, state: 'saved' } };
|
||||
}
|
||||
const workspaceId = matchingWorkspace(bridge, project);
|
||||
const memoryBodyId = await writableSpace(bridge, workspaceId);
|
||||
const category = sector === undefined ? undefined : CATEGORY_BY_SECTOR[sector];
|
||||
const result = row(rpcValue(await bridge.append('remember', { workspaceId, memoryBodyId, content, tags, category, operationId })));
|
||||
const id = text(result.id);
|
||||
if (id === undefined || result.memoryBodyId !== memoryBodyId || result.committed !== true) {
|
||||
throw new Error('Mnemon 没有返回可验证的项目记忆保存回执。');
|
||||
}
|
||||
return { ok: true, status: 200, data: { id: projectId(workspaceId, memoryBodyId, id), operation_id: operationId, state: 'saved' } };
|
||||
}),
|
||||
list: (options = {}) => invoke(async (bridge) => {
|
||||
const { offset = 0, limit = 20, project } = options;
|
||||
if (project === undefined) {
|
||||
const hits = await runtimeHits(bridge);
|
||||
return { ok: true, status: 200, data: { items: hits.slice(offset, offset + limit), total: hits.length } };
|
||||
}
|
||||
const workspaceId = matchingWorkspace(bridge, project);
|
||||
const result = row(rpcValue(await bridge.read('list', { workspaceId, limit: PROJECT_LIST_LIMIT })));
|
||||
const hits = newestFirst(rows(result.items).map(entry => projectHit(entry, workspaceId)));
|
||||
return { ok: true, status: 200, data: { items: hits.slice(offset, offset + limit), total: typeof result.total === 'number' ? result.total : hits.length } };
|
||||
}),
|
||||
projects: () => invoke(async (bridge) => ({
|
||||
ok: true, status: 200, data: { projects: bridge.workspaces().map(({ id, name }) => ({ id, name })) },
|
||||
})),
|
||||
storageStatus: () => invoke(async (bridge) => ({
|
||||
ok: true, status: 200, data: row(rpcValue(await bridge.read('status', {}))),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
|
@ -1,8 +1,7 @@
|
|||
/**
|
||||
* Agent-facing memory tools — the memory bundle's tool face.
|
||||
*
|
||||
* Bundle rule: the remote is injected via MemoryRemoteFactory; this module
|
||||
* imports neither the concrete cloud client nor the settings sidecar.
|
||||
* The entry injects a narrow MemoryRemote adapter.
|
||||
*
|
||||
* These definitions are hand-written `ToolDefinition` objects rather than
|
||||
* `defineTool(...)` calls: `defineTool` only compiles an authoring DSL into the
|
||||
|
|
@ -11,8 +10,7 @@
|
|||
* plugin.
|
||||
*
|
||||
* Failure contract: `execute` throws and the registry turns that into
|
||||
* `isError: true`. A missing token is a normal, explainable failure — never a
|
||||
* crash in the host.
|
||||
* `isError: true`.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { describeError } from "../api.js";
|
||||
|
|
@ -36,6 +34,8 @@ function toHitView(hit) {
|
|||
sector: hit.primary_sector ?? null,
|
||||
revision: hit.revision ?? null,
|
||||
created_at: hit.created_at ?? null,
|
||||
...(typeof hit.category === 'string' ? { category: hit.category } : {}),
|
||||
...(typeof hit.target === 'string' ? { target: hit.target } : {}),
|
||||
};
|
||||
}
|
||||
/** Render any tool value as one JSON text block. */
|
||||
|
|
@ -58,18 +58,29 @@ export function requireMemoryToken(deps) {
|
|||
return token;
|
||||
throw new Error('记忆功能未启用或未配置令牌。请在 /dsh-brain 页面开启本地记忆,或填入 mem_… / cmt_… 记忆令牌。');
|
||||
}
|
||||
function requireMemoryEnabled(deps) {
|
||||
if (!deps.settings().enabled)
|
||||
throw new Error('记忆工具当前已禁用。请在 /dsh-brain 页面开启后再试。');
|
||||
}
|
||||
function projectId(value) {
|
||||
if (value === undefined)
|
||||
return undefined;
|
||||
if (typeof value !== 'string' || value.trim() === '')
|
||||
throw new Error('project_id 必须是 memory_projects 返回的工作区 ID。');
|
||||
return value.trim();
|
||||
}
|
||||
/** Search stored memories by keyword. */
|
||||
function searchTool(deps) {
|
||||
return {
|
||||
name: 'memory_search',
|
||||
description: '在云端长期记忆库中按关键词检索历史记忆片段。返回命中的记忆 id、内容摘要、标签与所属项目;' +
|
||||
'需要更多正文时用 memory_read 按 id 取全文。纯关键词匹配,不会做语义相似度检索。',
|
||||
description: '按关键词检索 Mnemon 记忆。默认检索全局 Runtime,指定 project_id 时检索对应 DSH 工作区的记忆空间。' +
|
||||
'需要全文时用 memory_read 读取返回的 id。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
||||
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
|
||||
project_id: { type: 'string', description: '可选:只在这些项目 id 内检索。' },
|
||||
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。省略时检索全局。' },
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
|
|
@ -88,16 +99,15 @@ function searchTool(deps) {
|
|||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
async execute(args) {
|
||||
requireMemoryEnabled(deps);
|
||||
const query = typeof args.query === 'string' ? args.query.trim() : '';
|
||||
if (query === '')
|
||||
throw new Error('query 不能为空。');
|
||||
const requested = typeof args.k === 'number' && Number.isFinite(args.k) ? Math.trunc(args.k) : deps.settings().defaultK;
|
||||
const k = Math.min(1000, Math.max(1, requested));
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const result = await deps.remote().search(query, k, project, workspace);
|
||||
const project = projectId(args.project_id);
|
||||
const result = await deps.remote().search(query, k, project);
|
||||
if (!result.ok)
|
||||
throw new Error(`检索失败:${describeError(result.error)}`);
|
||||
const matches = result.data.matches;
|
||||
|
|
@ -114,7 +124,7 @@ function searchTool(deps) {
|
|||
function readTool(deps) {
|
||||
return {
|
||||
name: 'memory_read',
|
||||
description: '按 id 读取一条云端记忆的完整内容(正文、标签、项目、修订号与时间戳)。id 可先用 memory_search 或 memory_list 获得。',
|
||||
description: '按 memory_search、memory_list 或 memory_add 返回的 id 读取 Mnemon 条目全文及其可用元数据。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
|
|
@ -127,13 +137,12 @@ function readTool(deps) {
|
|||
schema: { type: 'object', properties: { id: { type: 'string' }, content: { type: 'string' } }, required: ['id'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
async execute(args) {
|
||||
requireMemoryEnabled(deps);
|
||||
const id = typeof args.id === 'string' ? args.id.trim() : '';
|
||||
if (id === '')
|
||||
throw new Error('id 不能为空。');
|
||||
const result = await deps.remote().read(id, workspace);
|
||||
const result = await deps.remote().read(id);
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 404)
|
||||
throw new Error(`没有找到 id=${id} 的记忆(可能已删除)。`);
|
||||
|
|
@ -147,15 +156,15 @@ function readTool(deps) {
|
|||
function addTool(deps) {
|
||||
return {
|
||||
name: 'memory_add',
|
||||
description: '向云端长期记忆库写入一条新记忆。content 上限 7000 字节,适合存结论、决策、待办与可复用事实;' +
|
||||
'不要写入密钥、令牌或完整源码。写入用 operation_id 保证幂等,重复调用不会产生重复条目。',
|
||||
description: '追加一条 Mnemon 记忆。默认写入全局 Runtime,指定 project_id 时写入对应 DSH 工作区的记忆空间。正文上限 7000 字节。' +
|
||||
'不要保存密钥、令牌或完整源码。重试同一次写入请复用 operation_id。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '可选标签,最多 30 个,每个不超过 100 字符。' },
|
||||
project_id: { type: 'string', description: '可选:归属项目 id(≤128 字符)。' },
|
||||
sector: { type: 'string', enum: [...SECTORS], description: '可选:记忆分类(semantic/episodic/procedural/emotional/reflective)。' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '项目条目可选标签,最多 30 个。全局 Runtime 不支持标签。' },
|
||||
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。省略时写入全局。' },
|
||||
sector: { type: 'string', enum: [...SECTORS], description: '项目条目可选分类。全局 Runtime 不支持分类。' },
|
||||
operation_id: { type: 'string', description: '可选:幂等键(uuid);省略时自动生成。重试同一次写入时请复用同一个值。' },
|
||||
},
|
||||
required: ['content'],
|
||||
|
|
@ -176,9 +185,8 @@ function addTool(deps) {
|
|||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
async execute(args) {
|
||||
requireMemoryEnabled(deps);
|
||||
const content = typeof args.content === 'string' ? args.content : '';
|
||||
if (content.trim() === '')
|
||||
throw new Error('content 不能为空。');
|
||||
|
|
@ -187,22 +195,22 @@ function addTool(deps) {
|
|||
throw new Error(`content 过大:${bytes} 字节,上限 7000 字节。`);
|
||||
const rawTags = Array.isArray(args.tags) ? args.tags : [];
|
||||
const tags = rawTags.filter((tag) => typeof tag === 'string' && tag !== '').slice(0, 30);
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const project = projectId(args.project_id);
|
||||
const sector = typeof args.sector === 'string' && SECTORS.includes(args.sector) ? args.sector : undefined;
|
||||
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : '';
|
||||
const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID();
|
||||
const result = await deps.remote().add({ content, tags, project, sector, operationId }, workspace);
|
||||
if (args.operation_id !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(candidate)) {
|
||||
throw new Error('operation_id 必须是 UUID。');
|
||||
}
|
||||
const operationId = candidate.toLowerCase() || randomUUID();
|
||||
const result = await deps.remote().add({ content, tags, project, sector, operationId });
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。');
|
||||
}
|
||||
throw new Error(`写入失败:${describeError(result.error)}`);
|
||||
throw new Error(`写入失败(operation_id=${operationId}):${describeError(result.error)}`);
|
||||
}
|
||||
return {
|
||||
id: result.data.id,
|
||||
revision: result.data.revision,
|
||||
remote_saved: result.data.remote_saved,
|
||||
state: result.data.state,
|
||||
...(result.data.revision === undefined ? {} : { revision: result.data.revision }),
|
||||
...(result.data.remote_saved === undefined ? {} : { remote_saved: result.data.remote_saved }),
|
||||
...(result.data.state === undefined ? {} : { state: result.data.state }),
|
||||
operation_id: result.data.operation_id ?? operationId,
|
||||
};
|
||||
},
|
||||
|
|
@ -212,13 +220,13 @@ function addTool(deps) {
|
|||
function listTool(deps) {
|
||||
return {
|
||||
name: 'memory_list',
|
||||
description: '按时间倒序列出云端记忆(可分页,可按项目过滤)。适合浏览最近保存了什么,再决定是否 memory_read 取全文。',
|
||||
description: '按时间倒序列出 Mnemon 记忆。省略 project_id 时列出全局 Runtime 条目。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
|
||||
offset: { type: 'integer', description: '跳过条数,默认 0。' },
|
||||
project_id: { type: 'string', description: '可选:只看某个项目。' },
|
||||
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
|
|
@ -226,15 +234,14 @@ function listTool(deps) {
|
|||
schema: { type: 'object', properties: { total: { type: 'number' }, items: { type: 'array', items: { type: 'object' } } }, required: ['items'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
async execute(args) {
|
||||
requireMemoryEnabled(deps);
|
||||
const rawLimit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : 20;
|
||||
const limit = Math.min(100, Math.max(1, rawLimit));
|
||||
const rawOffset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0;
|
||||
const offset = Math.max(0, rawOffset);
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const result = await deps.remote().list({ limit, offset, project }, workspace);
|
||||
const project = projectId(args.project_id);
|
||||
const result = await deps.remote().list({ limit, offset, project });
|
||||
if (!result.ok)
|
||||
throw new Error(`列表读取失败:${describeError(result.error)}`);
|
||||
const items = result.data.items;
|
||||
|
|
@ -246,16 +253,15 @@ function listTool(deps) {
|
|||
function projectsTool(deps) {
|
||||
return {
|
||||
name: 'memory_projects',
|
||||
description: '列出云端账号下的记忆项目(project_id 与名称),用于给 memory_add 选择归属项目。',
|
||||
description: '列出 DSH 注册的工作区 ID 和名称。将返回的 id 用作其他记忆工具的 project_id。',
|
||||
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
||||
output: {
|
||||
schema: { type: 'object', properties: { projects: { type: 'array', items: { type: 'object' } } }, required: ['projects'], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(_args, exec) {
|
||||
const workspace = deps.workspace?.(exec);
|
||||
requireMemoryToken(deps);
|
||||
const result = await deps.remote().projects(workspace);
|
||||
async execute(_args) {
|
||||
requireMemoryEnabled(deps);
|
||||
const result = await deps.remote().projects();
|
||||
if (!result.ok)
|
||||
throw new Error(`项目列表读取失败:${describeError(result.error)}`);
|
||||
return { projects: result.data.projects };
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
# dsh-brain Mnemon fork
|
||||
|
||||
- Display name: Dsh Brain Mnemon
|
||||
- Fork package name: dsh-brain-mnemon
|
||||
- Fork version: 0.5.54-dsh.1
|
||||
- Upstream: https://github.com/omdsh-dev/dsh-mnemon.git
|
||||
- Upstream revision: 8b650ab5ef33522e03887b250b13336593daa26f
|
||||
- Upstream version: 0.5.54
|
||||
- License: MIT (see LICENSE)
|
||||
|
||||
This directory is a source snapshot, not a git submodule. The tree keeps the upstream
|
||||
MIT license, copyright notice and third-party notices. Package names, import
|
||||
specifiers, runtime schema ids, bundle entry ids and the repair-session bin name
|
||||
are rewritten from dsh-mnemon to dsh-brain-mnemon so the fork can coexist with
|
||||
the upstream plugin without registering the same package or entry ids.
|
||||
|
||||
Regenerate with:
|
||||
|
||||
node scripts/fork-mnemon.mjs --source <upstream-checkout> --target vendor/dsh-mnemon --force
|
||||
|
||||
Update procedure: check out the desired upstream revision, run the command above,
|
||||
then bump PINNED_REVISION / PINNED_VERSION in scripts/fork-mnemon.mjs.
|
||||
Review the diff before committing; do not rewrite upstream docs or license files.
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2026 dsh-external contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# Third-party notices
|
||||
|
||||
`dsh-mnemon` is licensed under the MIT License. Its provider adapters are original TypeScript integrations adapted to DSH's contracts and verified against the relevant public API or CLI behavior. This package does not bundle provider SDKs or provider services.
|
||||
|
||||
Honcho's open-source server is licensed under AGPL-3.0. dsh-mnemon does not copy or bundle that server; its Honcho adapter communicates with a separately operated v3 HTTP API. Other external providers and hosted services—including OpenViking, Mem0, Hindsight, Holographic, RetainDB, ByteRover, and Supermemory—remain separate products governed by their own licenses and service terms.
|
||||
|
||||
Provider marks displayed by the Web UI are sourced from each provider's official website or source repository and bundled solely to identify the configured integration. Holographic is a built-in provider without an independent brand asset, so the UI uses its canonical mirror motif. Names, marks, and trademarks belong to their respective owners. Inclusion identifies interoperability only and does not imply endorsement.
|
||||
|
|
@ -0,0 +1,803 @@
|
|||
#!/usr/bin/env node
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createReadStream, realpathSync } from 'node:fs'
|
||||
import { link, mkdtemp, open, rm } from 'node:fs/promises'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import * as zlib from 'node:zlib'
|
||||
|
||||
const maximumBytes = 128 * 1024 * 1024
|
||||
const summaries = {
|
||||
recall: ['Memory View snapshot', 'Runtime memory snapshot'],
|
||||
instructions: ['Optional memory recall and remember reminder'],
|
||||
}
|
||||
const sha256 = value => createHash('sha256').update(value).digest('hex')
|
||||
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
const nonempty = value => typeof value === 'string' && value.length > 0
|
||||
const integer = value => Number.isSafeInteger(value) && !Object.is(value, -0)
|
||||
const count = value => integer(value) && value >= 0
|
||||
const exactKeys = (value, required, optional = []) => record(value) && required.every(key => Object.hasOwn(value, key)) &&
|
||||
Object.keys(value).every(key => required.includes(key) || optional.includes(key))
|
||||
|
||||
function supportedDescriptorV2(value) {
|
||||
if (!record(value) || value.version !== 2 || !nonempty(value.provider)) return false
|
||||
const base = ['version', 'mode', 'provider', 'label']
|
||||
if (value.mode === 'one-shot') return Object.keys(value).every(key => base.includes(key)) &&
|
||||
(!Object.hasOwn(value, 'label') || typeof value.label === 'string')
|
||||
if (value.mode !== 'continuable' || !nonempty(value.label)) return false
|
||||
if (!Object.keys(value).every(key => [...base, 'agentProvider', 'agentModel', 'persona', 'toolFilter'].includes(key))) return false
|
||||
for (const key of ['agentProvider', 'agentModel', 'persona']) if (Object.hasOwn(value, key) && !nonempty(value[key])) return false
|
||||
if (Object.hasOwn(value, 'agentProvider') !== Object.hasOwn(value, 'agentModel')) return false
|
||||
if (!Object.hasOwn(value, 'toolFilter')) return true
|
||||
const filter = value.toolFilter
|
||||
return record(filter) && Object.keys(filter).length > 0 && Object.keys(filter).every(key =>
|
||||
['allow', 'deny'].includes(key) && Array.isArray(filter[key]) && filter[key].every(nonempty))
|
||||
}
|
||||
|
||||
function supportedPackedToolRun(row, placeholdersOnly = true) {
|
||||
if (!exactKeys(row, ['type', 'seq0', 'time0', 'data']) || !count(row.seq0) || !integer(row.time0)) return false
|
||||
const data = row.data
|
||||
if (!exactKeys(data, ['turn', 'step', 'index', 'id', 'dt', 'args'], ['name']) || typeof data.id !== 'string' || (placeholdersOnly && data.id !== '' && data.name !== '' && data.name !== null) ||
|
||||
(Object.hasOwn(data, 'name') && data.name !== null && typeof data.name !== 'string')) return false
|
||||
if (![data.turn, data.step, data.index].every(count) || !Array.isArray(data.args) || data.args.length === 0 ||
|
||||
!data.args.every(value => typeof value === 'string') || !Array.isArray(data.dt) || data.dt.length !== data.args.length - 1 ||
|
||||
data.args.length - 1 > Number.MAX_SAFE_INTEGER - row.seq0) return false
|
||||
let time = row.time0
|
||||
return data.dt.every(gap => integer(gap) && integer(time += gap))
|
||||
}
|
||||
|
||||
const rawChunkEnvelope = row => exactKeys(row, ['type', 'seq', 'time', 'data'], ['ignorable']) && count(row.seq) && integer(row.time) &&
|
||||
(!Object.hasOwn(row, 'ignorable') || row.ignorable === true) && exactKeys(row.data, ['turn', 'step', 'chunk']) && [row.data.turn, row.data.step].every(count)
|
||||
const surfaceEnvelope = row => exactKeys(row, ['type', 'seq', 'time', 'data'], ['surfaceOp', 'sourceEventSeqs', 'ignorable']) && count(row.seq) && integer(row.time) &&
|
||||
(!Object.hasOwn(row, 'ignorable') || row.ignorable === true)
|
||||
const messageShape = value => exactKeys(value, ['role', 'id', 'source', 'content']) && nonempty(value.id) && Array.isArray(value.content)
|
||||
const toolBlockShape = value => exactKeys(value, ['type', 'id', 'name', 'arguments']) && value.type === 'tool-call' && typeof value.id === 'string' && nonempty(value.name) && typeof value.arguments === 'string'
|
||||
|
||||
function supportedPackedTextRun(row) {
|
||||
const data = row.data
|
||||
return exactKeys(data, ['turn', 'step', 'index', 'dt', 'texts']) && supportedPackedToolRun({ ...row,
|
||||
data: { turn: data.turn, step: data.step, index: data.index, id: 'unchanged-text-run', dt: data.dt, args: data.texts } }, false)
|
||||
}
|
||||
|
||||
function supportedNullToolDelta(row) {
|
||||
if (!rawChunkEnvelope(row)) return false
|
||||
const chunk = row.data.chunk
|
||||
return exactKeys(chunk, ['type', 'index', 'id', 'name', 'argumentsDelta']) && chunk.type === 'tool-call-delta' &&
|
||||
chunk.name === null && count(chunk.index) && typeof chunk.id === 'string' && typeof chunk.argumentsDelta === 'string'
|
||||
}
|
||||
|
||||
function recoverRecordedToolIdentities(entries) {
|
||||
const rawPatches = new Map()
|
||||
const packedIds = new Map()
|
||||
const refusals = { occurrences: 0, samples: [] }
|
||||
let chains = 0
|
||||
let fields = 0
|
||||
const emptyBlock = block => block?.type === 'tool-call' && block.id === '' || block?.type === 'tool-result' && block.toolCallId === ''
|
||||
const emptyDurable = row => row.type === 'tool/call' && row.data?.callId === '' ||
|
||||
row.type === 'assistant/chunk' && row.data?.chunk?.type === 'block-end' && emptyBlock(row.data.chunk.block) ||
|
||||
['assistant/message', 'tool/result'].includes(row.type) && (row.data?.message?.content?.some?.(emptyBlock) || row.data?.message?.source?.callId === '')
|
||||
const result = () => ({ rawPatches, packedIds, chains, fields, refusals })
|
||||
if (!entries.some(entry => emptyDurable(entry.row))) return result()
|
||||
const require = (condition, reason) => { if (!condition) throw reason }
|
||||
const refuse = (entry, reason) => {
|
||||
refusals.occurrences++
|
||||
if (refusals.samples.length < 10) refusals.samples.push({ line: entry.index + 1, ...(count(entry.row.seq) ? { seq: entry.row.seq } : {}), reason })
|
||||
}
|
||||
const logical = []
|
||||
let turn, step
|
||||
try {
|
||||
for (const entry of entries.slice(1)) {
|
||||
const row = entry.row
|
||||
objectMembers(entry.line, 0)
|
||||
if (row.type === 'turn/start') turn = row.data?.turn
|
||||
if (row.type === 'step/start') { turn = row.data?.turn; step = row.data?.step }
|
||||
entry.scope = { turn: row.data?.turn ?? turn, step: row.data?.step ?? step }
|
||||
if (['tool-call-chunks', 'text-chunks', 'reasoning-chunks'].includes(row.type)) {
|
||||
const tool = row.type === 'tool-call-chunks'
|
||||
require(tool ? supportedPackedToolRun(row, false) : supportedPackedTextRun(row), 'A packed source has unsupported fields or coordinates.')
|
||||
const fragments = tool ? row.data.args : row.data.texts
|
||||
let time = row.time0
|
||||
for (let offset = 0; offset < fragments.length; offset++) {
|
||||
if (offset) time += row.data.dt[offset - 1]
|
||||
require(logical.length < maximumBytes / 128, 'The identity proof exceeds its bounded event count.')
|
||||
logical.push({ entry, offset, row: { type: 'assistant/chunk', seq: row.seq0 + offset, time,
|
||||
data: { turn: row.data.turn, step: row.data.step, chunk: tool ? { type: 'tool-call-delta', index: row.data.index, id: row.data.id,
|
||||
...(Object.hasOwn(row.data, 'name') ? { name: row.data.name } : {}), argumentsDelta: fragments[offset] }
|
||||
: { type: row.type === 'text-chunks' ? 'text-delta' : 'reasoning-delta', index: row.data.index, text: fragments[offset] } } } })
|
||||
}
|
||||
} else logical.push({ entry, row })
|
||||
if (row.type === 'step/end') step = undefined
|
||||
if (row.type === 'turn/end') { turn = undefined; step = undefined }
|
||||
}
|
||||
require(logical.every((value, index) => value.row.seq === index && integer(value.row.time)), 'Logical events must have unique complete sequence coordinates and safe times.')
|
||||
} catch (error) {
|
||||
if (typeof error !== 'string') throw error
|
||||
refuse(entries.find(entry => emptyDurable(entry.row)), error)
|
||||
return result()
|
||||
}
|
||||
const sourceSeqs = (row, nonempty = true) => {
|
||||
const values = row.sourceEventSeqs
|
||||
require(Array.isArray(values), 'Tool history needs explicit, valid assistant chunk provenance.')
|
||||
const selected = new Set()
|
||||
const hasRanges = values.some(Array.isArray)
|
||||
let previous = -1
|
||||
for (const member of values) {
|
||||
const range = Array.isArray(member)
|
||||
require(!range || member.length === 2, 'A provenance range must contain exactly two coordinates.')
|
||||
const start = range ? member[0] : member
|
||||
const end = range ? member[1] : member
|
||||
require(count(start) && count(end) && start <= end && end < row.seq && end - start < logical.length - selected.size,
|
||||
'Provenance contains an unsafe, missing or excessive source range.')
|
||||
require((!hasRanges && row.type !== 'assistant/message') || start > previous, 'Chunk provenance is not one complete ordered attempt.')
|
||||
for (let seq = start; seq <= end; seq++) {
|
||||
require(!selected.has(seq), 'Provenance contains duplicate or overlapping source coordinates.')
|
||||
selected.add(seq)
|
||||
}
|
||||
previous = end
|
||||
}
|
||||
require(!nonempty || selected.size > 0, 'A completed tool stream needs nonempty chunk provenance.')
|
||||
return [...selected].sort((left, right) => left - right)
|
||||
}
|
||||
const sameStep = (left, right) => left?.turn === right?.turn && left?.step === right?.step
|
||||
const messages = entries.filter(entry => entry.row.type === 'assistant/message')
|
||||
for (const assistant of messages) {
|
||||
const row = assistant.row
|
||||
const data = row.data
|
||||
const content = data?.message?.content
|
||||
if (!Array.isArray(content) || !content.some(block => block?.type === 'tool-call') ||
|
||||
!entries.some(entry => sameStep(entry.scope, data) && emptyDurable(entry.row))) continue
|
||||
try {
|
||||
require(surfaceEnvelope(row) && row.surfaceOp === 'append' && exactKeys(data, ['turn', 'step', 'message'], ['usage']) && count(data.turn) && count(data.step) &&
|
||||
messageShape(data.message) && data.message.role === 'assistant' && exactKeys(data.message.source, ['kind', 'provider', 'model']) &&
|
||||
data.message.source.kind === 'model' && data.message.source.provider === 'deepseek-official' && nonempty(data.message.source.model),
|
||||
'Only the uninterrupted recorded DeepSeek append-message shape without owner replay state is supported.')
|
||||
const sources = sourceSeqs(row)
|
||||
const selected = new Set(sources)
|
||||
const stream = sources.map(seq => logical[seq])
|
||||
require(stream.every(value => value?.row.type === 'assistant/chunk' && sameStep(value.row.data, data)), 'Chunk provenance cites another event, turn or step.')
|
||||
require(logical.slice(sources[0], sources.at(-1) + 1).every(value => value.row.type !== 'assistant/chunk' || !sameStep(value.row.data, data) || selected.has(value.row.seq)),
|
||||
'Chunk provenance omits a delta inside this stream attempt.')
|
||||
for (const other of messages) if (other !== assistant && Object.hasOwn(other.row, 'sourceEventSeqs')) {
|
||||
require(!sourceSeqs(other.row, false).some(seq => selected.has(seq)), 'Two assistant messages share source chunks.')
|
||||
}
|
||||
const blocks = new Map()
|
||||
let finished = false
|
||||
let usage
|
||||
for (const value of stream) {
|
||||
const current = value.row
|
||||
const chunk = current.data.chunk
|
||||
require(rawChunkEnvelope(current) && record(chunk) && !finished, 'The stream has unsupported fields or chunks after finish.')
|
||||
assertUniqueJson(value.entry.line, value.entry.row)
|
||||
if (chunk.type === 'usage') {
|
||||
require(exactKeys(chunk, ['type', 'usage']) && record(chunk.usage), 'An unrecognized usage chunk prevents identity recovery.')
|
||||
usage = chunk.usage
|
||||
continue
|
||||
}
|
||||
if (chunk.type === 'finish') {
|
||||
require(exactKeys(chunk, ['type', 'reason']) && exactKeys(chunk.reason, ['kind']) && chunk.reason.kind === 'tool-calls', 'The tool stream is interrupted, truncated or has owner replay state.')
|
||||
finished = true
|
||||
continue
|
||||
}
|
||||
require(count(chunk.index), 'A stream block index is unsafe.')
|
||||
let block = blocks.get(chunk.index)
|
||||
if (chunk.type === 'block-start') {
|
||||
require(exactKeys(chunk, ['type', 'index', 'blockType']) && ['text', 'reasoning', 'tool-call'].includes(chunk.blockType) && !block,
|
||||
'A block start is repeated or unsupported.')
|
||||
blocks.set(chunk.index, { type: chunk.blockType, started: true, text: '', arguments: '', deltas: [] })
|
||||
continue
|
||||
}
|
||||
const type = chunk.type === 'text-delta' ? 'text' : chunk.type === 'reasoning-delta' ? 'reasoning' : chunk.type === 'tool-call-delta' ? 'tool-call' : chunk.block?.type
|
||||
require(['text', 'reasoning', 'tool-call'].includes(type), 'A stream chunk has an unsupported block type.')
|
||||
if (!block) {
|
||||
require(type !== 'tool-call', 'A tool delta or end is missing its block start.')
|
||||
block = { type, text: '', arguments: '', deltas: [] }
|
||||
blocks.set(chunk.index, block)
|
||||
}
|
||||
require(block.type === type && !block.end, 'A block changes type, repeats its end or receives a late delta.')
|
||||
if (chunk.type === 'block-end') {
|
||||
require(exactKeys(chunk, ['type', 'index', 'block']) && record(chunk.block), 'A block end has unsupported fields.')
|
||||
block.end = value
|
||||
block.content = chunk.block
|
||||
if (type === 'tool-call') require(toolBlockShape(chunk.block) &&
|
||||
chunk.block.name === block.name && chunk.block.arguments === block.arguments, 'The final tool name or arguments disagree with its deltas.')
|
||||
continue
|
||||
}
|
||||
if (type === 'tool-call') {
|
||||
require(exactKeys(chunk, ['type', 'index', 'id', 'argumentsDelta'], ['name']) && typeof chunk.id === 'string' && typeof chunk.argumentsDelta === 'string' &&
|
||||
(!Object.hasOwn(chunk, 'name') || chunk.name === null || typeof chunk.name === 'string'), 'A tool delta has unsupported identity or argument fields.')
|
||||
if (chunk.name) block.name = chunk.name
|
||||
block.arguments += chunk.argumentsDelta
|
||||
block.deltas.push(value)
|
||||
} else {
|
||||
require(exactKeys(chunk, ['type', 'index', 'text']) && typeof chunk.text === 'string', 'A text or reasoning delta has unsupported fields.')
|
||||
block.text += chunk.text
|
||||
}
|
||||
}
|
||||
require(finished && blocks.size === content.length, 'The completed stream and assistant block list do not match.')
|
||||
require(isDeepStrictEqual(usage, data.usage), 'The completed stream and assistant usage do not match.')
|
||||
const ordered = [...blocks.values()]
|
||||
const advertised = messages.filter(entry => sameStep(entry.row.data, data)).flatMap(entry => entry.row.data?.message?.content ?? []).filter(block => block?.type === 'tool-call')
|
||||
const calls = entries.filter(entry => entry.row.type === 'tool/call' && sameStep(entry.row.data, data))
|
||||
const results = entries.filter(entry => entry.row.type === 'tool/result' && sameStep(entry.row.data, data))
|
||||
const proposals = []
|
||||
const provenChains = []
|
||||
for (const [position, block] of ordered.entries()) {
|
||||
const actual = block.content ?? { type: block.type, text: block.text }
|
||||
const declared = content[position]
|
||||
if (block.type !== 'tool-call') {
|
||||
require(isDeepStrictEqual(actual, declared), 'Text or reasoning differs between the stream and assistant message.')
|
||||
continue
|
||||
}
|
||||
require(block.end && toolBlockShape(declared) &&
|
||||
isDeepStrictEqual({ ...actual, id: '' }, { ...declared, id: '' }), 'The tool block and assistant advertisement disagree.')
|
||||
const matchingCalls = calls.filter(entry => entry.row.data.name === actual.name && entry.row.data.arguments === actual.arguments)
|
||||
require(matchingCalls.length === 1 && advertised.filter(value => value.name === actual.name && value.arguments === actual.arguments).length === 1,
|
||||
'The tool advertisement and execution cannot be paired uniquely by name and arguments.')
|
||||
const call = matchingCalls[0]
|
||||
require(surfaceEnvelope(call.row) && !Object.hasOwn(call.row, 'surfaceOp') && !Object.hasOwn(call.row, 'sourceEventSeqs') &&
|
||||
exactKeys(call.row.data, ['turn', 'step', 'callId', 'name', 'arguments']) && row.seq < call.row.seq && typeof call.row.data.callId === 'string',
|
||||
'The tool execution has unsupported fields, precedes its advertisement or has an invalid ID.')
|
||||
const matchingResults = results.filter(entry => Object.hasOwn(entry.row, 'sourceEventSeqs') && sourceSeqs(entry.row).includes(call.row.seq))
|
||||
let toolResult
|
||||
if (matchingResults.length === 1) {
|
||||
toolResult = matchingResults[0]
|
||||
require(isDeepStrictEqual(sourceSeqs(toolResult.row), [call.row.seq]), 'The result provenance does not select exactly this tool execution.')
|
||||
} else {
|
||||
require(matchingResults.length === 0 && advertised.length === 1 && calls.length === 1 && results.length === 1 && !Object.hasOwn(results[0].row, 'sourceEventSeqs'),
|
||||
'The tool result is missing, ambiguous or has conflicting provenance.')
|
||||
require(!logical.some(value => value.row.type === 'assistant/chunk' && sameStep(value.row.data, data) && !selected.has(value.row.seq)),
|
||||
'A result without provenance cannot be matched across a retry or another stream attempt.')
|
||||
toolResult = results[0]
|
||||
}
|
||||
const resultMessage = toolResult.row.data?.message
|
||||
const resultBlock = resultMessage?.content?.[0]
|
||||
require(surfaceEnvelope(toolResult.row) && exactKeys(toolResult.row.data, ['turn', 'step', 'message'], ['error', 'meta']) &&
|
||||
call.row.seq < toolResult.row.seq && toolResult.row.surfaceOp === 'append' && messageShape(resultMessage) && resultMessage.role === 'user' &&
|
||||
exactKeys(resultMessage.source, ['kind', 'callId']) && resultMessage.source.kind === 'tool' && typeof resultMessage.source.callId === 'string' && resultMessage.content.length === 1 &&
|
||||
exactKeys(resultBlock, ['type', 'toolCallId', 'content'], ['isError']) && resultBlock.type === 'tool-result' && typeof resultBlock.toolCallId === 'string' &&
|
||||
Array.isArray(resultBlock.content) && (!Object.hasOwn(resultBlock, 'isError') || typeof resultBlock.isError === 'boolean'), 'The tool result is not a complete append result with a single identity.')
|
||||
const slots = [
|
||||
[block.end, ['data', 'chunk', 'block', 'id'], actual.id],
|
||||
[{ entry: assistant, row }, ['data', 'message', 'content', position, 'id'], declared.id],
|
||||
[{ entry: call, row: call.row }, ['data', 'callId'], call.row.data.callId],
|
||||
[{ entry: toolResult, row: toolResult.row }, ['data', 'message', 'source', 'callId'], resultMessage.source.callId],
|
||||
[{ entry: toolResult, row: toolResult.row }, ['data', 'message', 'content', 0, 'toolCallId'], resultMessage.content[0].toolCallId],
|
||||
]
|
||||
if (!slots.some(slot => slot[2] === '')) {
|
||||
require(slots.every(slot => slot[2] === actual.id) && block.deltas.every(value => value.row.data.chunk.id === '' || value.row.data.chunk.id === actual.id),
|
||||
'An already nonempty tool chain contains conflicting recorded identities.')
|
||||
provenChains.push(slots)
|
||||
continue
|
||||
}
|
||||
const candidates = new Set(block.deltas.map(value => value.row.data.chunk.id).filter(nonempty))
|
||||
require(candidates.size === 1, 'The tool stream has no unique previously recorded provider ID.')
|
||||
const candidate = [...candidates][0]
|
||||
require(slots.every(slot => slot[2] === '' || slot[2] === candidate), 'A durable ID conflicts with the recorded provider ID.')
|
||||
require(advertised.every(value => value === declared || value.id !== candidate), 'The recorded ID is already advertised by another tool in this step.')
|
||||
let seen = false
|
||||
const deltas = []
|
||||
for (const value of block.deltas) {
|
||||
if (value.row.data.chunk.id === candidate) seen = true
|
||||
else if (seen) deltas.push([value, ['data', 'chunk', 'id'], ''])
|
||||
}
|
||||
require(deltas.length > 0, 'No empty continuation delta follows the recorded provider ID.')
|
||||
provenChains.push(slots)
|
||||
proposals.push({ candidate, name: actual.name, assistant, call, toolResult, block, slots: [...deltas, ...slots.filter(slot => slot[2] === '')], sources })
|
||||
}
|
||||
require(new Set(proposals.map(value => value.candidate)).size === proposals.length, 'Multiple tools claim the same recorded provider ID.')
|
||||
for (const proposal of proposals) {
|
||||
const owned = new Map()
|
||||
const allow = (entry, path) => {
|
||||
if (!owned.has(entry)) owned.set(entry, new Set())
|
||||
owned.get(entry).add(JSON.stringify(path))
|
||||
}
|
||||
for (const slots of provenChains) for (const [value, path] of slots) allow(value.entry, path)
|
||||
const linkedSeqs = new Set([...sources, row.seq, proposal.call.row.seq, proposal.toolResult.row.seq])
|
||||
const linkedMessages = new Set([data.message.id, proposal.toolResult.row.data.message.id])
|
||||
const cites = value => {
|
||||
if (!record(value) && !Array.isArray(value)) return false
|
||||
return Object.entries(value).some(([key, child]) => {
|
||||
if (key === 'sourceEventSeq' && linkedSeqs.has(child)) return true
|
||||
if ((/^(?:messageId|.*MessageId)s?$/.test(key) || key === 'id' && ['assistant', 'user'].includes(value.role)) &&
|
||||
(linkedMessages.has(child) || Array.isArray(child) && child.some(id => linkedMessages.has(id)))) return true
|
||||
if (key === 'shadowedRange' && record(child) && [...linkedSeqs].some(seq => count(child.start) && count(child.end) && child.start <= seq && seq <= child.end)) return true
|
||||
if (['sourceEventSeqs', 'shadowedSeqs', 'shadowedRange'].includes(key) && Array.isArray(child)) {
|
||||
if (key === 'shadowedRange' && child.length === 2 && [...linkedSeqs].some(seq => count(child[0]) && count(child[1]) && child[0] <= seq && seq <= child[1])) return true
|
||||
if (child.some(member => linkedSeqs.has(member) || Array.isArray(member) && member.length === 2 && [...linkedSeqs].some(seq => count(member[0]) && count(member[1]) && member[0] <= seq && seq <= member[1]))) return true
|
||||
}
|
||||
return cites(child)
|
||||
})
|
||||
}
|
||||
for (const entry of entries.slice(1)) {
|
||||
const value = entry.row
|
||||
const replacement = value.surfaceOp
|
||||
const surfaces = [row.seq, proposal.toolResult.row.seq]
|
||||
const replaces = record(replacement) && replacement.op === 'replace' && surfaces.some(seq => count(replacement.start) && count(replacement.end) && replacement.start <= seq && seq <= replacement.end)
|
||||
require(!replaces, 'A surface replacement also owns the affected historical message.')
|
||||
const copiesMessage = [data.message.id, proposal.toolResult.row.data.message.id].includes(value.data?.message?.id) && entry !== assistant && entry !== proposal.toolResult
|
||||
require(!copiesMessage, 'A copied message identity needs owner-aware recovery.')
|
||||
if (!sameStep(entry.scope, data) && !cites(value)) continue
|
||||
assertUniqueJson(entry.line, value)
|
||||
require(!(value.type === 'approval/asked' && value.data?.toolName === proposal.name &&
|
||||
(value.data.callId === undefined || value.data.callId === '' || value.data.callId === proposal.candidate)), 'An associated approval retains the historical tool identity.')
|
||||
const visit = (current, path = []) => {
|
||||
if (!record(current) && !Array.isArray(current)) return
|
||||
for (const [key, child] of Object.entries(current)) {
|
||||
const next = [...path, Array.isArray(current) ? Number(key) : key]
|
||||
const identity = ['callId', 'toolCallId', 'rootCallId', 'parentCallId', 'subCallId'].includes(key) || key === 'id' && current.type === 'tool-call'
|
||||
if (key === 'replayState') require(false, 'Owner replay state needs owner-aware identity recovery.')
|
||||
if (identity && (child === '' || child === proposal.candidate || typeof child === 'string' && (child.startsWith(`${proposal.candidate}:code:`) || child.startsWith(':code:')))) {
|
||||
require(owned.get(entry)?.has(JSON.stringify(next)), 'An additional approval, dispatch, plugin or copied-content identity reference remains.')
|
||||
}
|
||||
visit(child, next)
|
||||
}
|
||||
}
|
||||
visit(value)
|
||||
}
|
||||
}
|
||||
for (const proposal of proposals) {
|
||||
chains++
|
||||
for (const [value, path] of proposal.slots) {
|
||||
fields++
|
||||
if (value.offset !== undefined) {
|
||||
if (!packedIds.has(value.entry.index)) packedIds.set(value.entry.index, new Map())
|
||||
packedIds.get(value.entry.index).set(value.offset, proposal.candidate)
|
||||
} else {
|
||||
if (!rawPatches.has(value.entry.index)) rawPatches.set(value.entry.index, [])
|
||||
rawPatches.get(value.entry.index).push({ path, value: proposal.candidate })
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (typeof error !== 'string') throw error
|
||||
refuse(assistant, error)
|
||||
}
|
||||
}
|
||||
if (refusals.occurrences > 0) { rawPatches.clear(); packedIds.clear(); chains = 0; fields = 0 }
|
||||
return result()
|
||||
}
|
||||
|
||||
function legacyBlockers() {
|
||||
const issues = new Map()
|
||||
const add = (code, message, row, line, path) => {
|
||||
if (!issues.has(code)) issues.set(code, { code, message, occurrences: 0, samples: [] })
|
||||
const issue = issues.get(code)
|
||||
issue.occurrences++
|
||||
const seq = row.seq ?? row.seq0
|
||||
if (issue.samples.length < 10) issue.samples.push({ line, type: row.type, ...(count(seq) ? { seq } : {}), path })
|
||||
}
|
||||
const identifier = (value, row, line, path) => {
|
||||
if (value === '') add('empty-durable-tool-id', 'An empty durable tool ID lacks a proven closed chain to its recorded provider identity; new identities are not synthesized.', row, line, path)
|
||||
}
|
||||
const block = (value, row, line, path) => {
|
||||
if (value?.type === 'tool-call') identifier(value.id, row, line, `${path}.id`)
|
||||
if (value?.type === 'tool-result') identifier(value.toolCallId, row, line, `${path}.toolCallId`)
|
||||
}
|
||||
const message = (value, row, line, path) => {
|
||||
if (value?.source?.kind === 'tool') identifier(value.source.callId, row, line, `${path}.source.callId`)
|
||||
if (Array.isArray(value?.content)) value.content.forEach((value, index) => block(value, row, line, `${path}.content[${index}]`))
|
||||
}
|
||||
return {
|
||||
inspect(row, line) {
|
||||
const data = row?.data
|
||||
if (row?.type === 'subagent/descriptor' && data?.version !== 3 && !supportedDescriptorV2(data)) {
|
||||
add('unsupported-subagent-descriptor', 'Only exact historical v2 descriptors with equivalent v3 composition are supported; this descriptor needs recovery by its original writer.', row, line, 'data.version')
|
||||
}
|
||||
if (row?.type === 'tool-call-chunks') {
|
||||
if ((data?.id === '' || data?.name === '' || data?.name === null) && !supportedPackedToolRun(row)) add('unsupported-packed-tool-chunks', 'The packed row cannot be expanded losslessly: it needs exact fields, string deltas and safe sequence/time coordinates.', row, line, 'data')
|
||||
}
|
||||
if (row?.type === 'assistant/chunk') {
|
||||
if (data?.chunk?.type === 'tool-call-delta' && data.chunk.name === null && !supportedNullToolDelta(row)) {
|
||||
add('null-stream-tool-name', 'A null streaming tool name needs exact raw fields, string ID/arguments and safe coordinates before normalization.', row, line, 'data.chunk.name')
|
||||
}
|
||||
if (data?.chunk?.type === 'block-end') block(data.chunk.block, row, line, 'data.chunk.block')
|
||||
}
|
||||
if (row?.type === 'assistant/message') {
|
||||
message(data?.message, row, line, 'data.message')
|
||||
if (record(data) && !Object.hasOwn(data, 'message') && Object.hasOwn(data, 'content') && Object.hasOwn(data, 'provenance')) {
|
||||
message(data, row, line, 'data')
|
||||
}
|
||||
}
|
||||
if (row?.type === 'tool/call') identifier(data?.callId, row, line, 'data.callId')
|
||||
if (row?.type === 'tool/result') {
|
||||
identifier(data?.callId, row, line, 'data.callId')
|
||||
message(data?.message, row, line, 'data.message')
|
||||
}
|
||||
},
|
||||
report: () => [...issues.values()],
|
||||
}
|
||||
}
|
||||
|
||||
function objectMembers(text, start, array = false) {
|
||||
let cursor = start
|
||||
const space = () => { while (/\s/.test(text[cursor] ?? '') && cursor < text.length) cursor++ }
|
||||
const stringEnd = () => {
|
||||
cursor++
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor++] === '"') return
|
||||
if (text[cursor - 1] === '\\') cursor++
|
||||
}
|
||||
}
|
||||
const valueEnd = () => {
|
||||
if (text[cursor] === '"') return stringEnd()
|
||||
if (text[cursor] === '{' || text[cursor] === '[') {
|
||||
let depth = 0
|
||||
do {
|
||||
if (text[cursor] === '"') stringEnd()
|
||||
else {
|
||||
if ('{['.includes(text[cursor])) depth++
|
||||
if ('}]'.includes(text[cursor])) depth--
|
||||
cursor++
|
||||
}
|
||||
} while (depth > 0)
|
||||
} else {
|
||||
while (cursor < text.length && !/[\s,}\]]/.test(text[cursor])) cursor++
|
||||
}
|
||||
}
|
||||
space()
|
||||
if (text[cursor++] !== (array ? '[' : '{')) throw new Error('Expected a JSON container in the legacy message path.')
|
||||
const members = []
|
||||
const names = new Set()
|
||||
space()
|
||||
const close = array ? ']' : '}'
|
||||
while (text[cursor] !== close) {
|
||||
const start = cursor
|
||||
let name = members.length
|
||||
if (!array) {
|
||||
stringEnd()
|
||||
name = JSON.parse(text.slice(start, cursor))
|
||||
if (names.has(name)) throw new Error('Duplicate JSON property in the legacy message path; refusing ambiguous repair.')
|
||||
names.add(name)
|
||||
space()
|
||||
cursor++
|
||||
space()
|
||||
}
|
||||
const valueStart = cursor
|
||||
valueEnd()
|
||||
members.push({ name, start, end: cursor, valueStart })
|
||||
space()
|
||||
if (text[cursor] === close) break
|
||||
cursor++
|
||||
space()
|
||||
}
|
||||
return members
|
||||
}
|
||||
|
||||
function assertUniqueJson(line, row, start = 0) {
|
||||
if (!record(row) && !Array.isArray(row)) return
|
||||
for (const member of objectMembers(line, start, Array.isArray(row))) assertUniqueJson(line, row[member.name], member.valueStart)
|
||||
}
|
||||
|
||||
function replaceIdentityValues(line, patches) {
|
||||
for (const patch of patches) {
|
||||
let start = 0
|
||||
let member
|
||||
for (const key of patch.path) {
|
||||
member = objectMembers(line, start, typeof key === 'number').find(value => value.name === key)
|
||||
if (!member) throw new Error('An identity patch no longer matches its proven JSON path.')
|
||||
start = member.valueStart
|
||||
}
|
||||
line = line.slice(0, member.valueStart) + JSON.stringify(patch.value) + line.slice(member.end)
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
function removeSummary(line) {
|
||||
const data = objectMembers(line, 0).find(member => member.name === 'data')
|
||||
const source = objectMembers(line, data.valueStart).find(member => member.name === 'source')
|
||||
const members = objectMembers(line, source.valueStart)
|
||||
const index = members.findIndex(member => member.name === 'summary')
|
||||
const member = members[index]
|
||||
const start = index === members.length - 1 && index > 0 ? members[index - 1].end : member.start
|
||||
const end = index < members.length - 1 ? members[index + 1].start : member.end
|
||||
return line.slice(0, start) + line.slice(end)
|
||||
}
|
||||
|
||||
function promoteDescriptor(line) {
|
||||
const data = objectMembers(line, 0).find(member => member.name === 'data')
|
||||
const members = objectMembers(line, data.valueStart)
|
||||
const filter = members.find(member => member.name === 'toolFilter')
|
||||
if (filter) objectMembers(line, filter.valueStart)
|
||||
const version = members.find(member => member.name === 'version')
|
||||
return line.slice(0, version.valueStart) + '3' + line.slice(version.end)
|
||||
}
|
||||
|
||||
function normalizeNullToolName(line) {
|
||||
const data = objectMembers(line, 0).find(member => member.name === 'data')
|
||||
const chunk = objectMembers(line, data.valueStart).find(member => member.name === 'chunk')
|
||||
const name = objectMembers(line, chunk.valueStart).find(member => member.name === 'name')
|
||||
return line.slice(0, name.valueStart) + '""' + line.slice(name.end)
|
||||
}
|
||||
|
||||
function expandPackedToolRun(line, row, retain, recoveredIds) {
|
||||
const data = objectMembers(line, 0).find(member => member.name === 'data')
|
||||
objectMembers(line, data.valueStart)
|
||||
let time = row.time0
|
||||
const expanded = []
|
||||
for (let index = 0; index < row.data.args.length; index++) {
|
||||
if (index > 0) time += row.data.dt[index - 1]
|
||||
expanded.push(retain(JSON.stringify({
|
||||
type: 'assistant/chunk', seq: row.seq0 + index, time,
|
||||
data: { turn: row.data.turn, step: row.data.step, chunk: {
|
||||
type: 'tool-call-delta', index: row.data.index, id: recoveredIds?.get(index) ?? row.data.id,
|
||||
...(Object.hasOwn(row.data, 'name') ? { name: row.data.name ?? '' } : {}), argumentsDelta: row.data.args[index],
|
||||
} },
|
||||
}) + (line.endsWith('\r\n') ? '\r\n' : '\n')))
|
||||
}
|
||||
return expanded.join('')
|
||||
}
|
||||
|
||||
async function readBounded(path) {
|
||||
const chunks = []
|
||||
let length = 0
|
||||
for await (const chunk of createReadStream(path)) {
|
||||
length += chunk.length
|
||||
if (length > maximumBytes) throw new Error('Session exceeds the 128 MiB repair limit.')
|
||||
chunks.push(chunk)
|
||||
}
|
||||
return Buffer.concat(chunks)
|
||||
}
|
||||
|
||||
function frameLength(input, start) {
|
||||
const requireBytes = end => { if (end > input.length) throw new Error('Truncated Zstandard frame; no output written.') }
|
||||
requireBytes(start + 5)
|
||||
if (input.readUInt32LE(start) !== 0xfd2fb528) throw new Error('Unsupported Zstandard frame; only ordinary DSH frames are accepted.')
|
||||
const descriptor = input[start + 4]
|
||||
if (descriptor & 0x18) throw new Error('Reserved Zstandard frame header bits are set.')
|
||||
const single = (descriptor & 0x20) !== 0
|
||||
const sizeFlag = descriptor >>> 6
|
||||
const contentSizeBytes = sizeFlag === 0 ? (single ? 1 : 0) : [0, 2, 4, 8][sizeFlag]
|
||||
let offset = start + 5 + (single ? 0 : 1) + [0, 1, 2, 4][descriptor & 3] + contentSizeBytes
|
||||
requireBytes(offset)
|
||||
let last = false
|
||||
while (!last) {
|
||||
requireBytes(offset + 3)
|
||||
const block = input.readUIntLE(offset, 3)
|
||||
last = (block & 1) !== 0
|
||||
const type = (block >>> 1) & 3
|
||||
if (type === 3) throw new Error('Reserved Zstandard block type.')
|
||||
offset += 3 + (type === 1 ? 1 : block >>> 3)
|
||||
requireBytes(offset)
|
||||
}
|
||||
offset += descriptor & 4 ? 4 : 0
|
||||
requireBytes(offset)
|
||||
return offset - start
|
||||
}
|
||||
|
||||
function decodeFrames(input) {
|
||||
const chunks = []
|
||||
let offset = 0
|
||||
let length = 0
|
||||
while (offset < input.length) {
|
||||
const lengthOnDisk = frameLength(input, offset)
|
||||
const { buffer, engine } = zlib.zstdDecompressSync(input.subarray(offset, offset + lengthOnDisk), {
|
||||
info: true, maxOutputLength: maximumBytes - length,
|
||||
})
|
||||
if (engine.bytesWritten !== lengthOnDisk) throw new Error('Invalid Zstandard frame length.')
|
||||
offset += engine.bytesWritten
|
||||
length += buffer.length
|
||||
chunks.push(buffer)
|
||||
}
|
||||
return Buffer.concat(chunks)
|
||||
}
|
||||
|
||||
function encodeFrames(text) {
|
||||
const end = text.indexOf('\n') + 1
|
||||
const options = { params: { [zlib.constants.ZSTD_c_checksumFlag]: 1 } }
|
||||
return Buffer.concat([text.slice(0, end), text.slice(end)].filter(Boolean).map(part => zlib.zstdCompressSync(part, options)))
|
||||
}
|
||||
|
||||
async function writeRepairCopy(input, output, result) {
|
||||
if (resolve(input) === resolve(output)) throw new Error('Output must be a new copy; the input cannot be overwritten.')
|
||||
const temporary = await mkdtemp(join(dirname(resolve(output)), '.mnemon-repair-'))
|
||||
try {
|
||||
const path = join(temporary, 'session')
|
||||
const file = await open(path, 'wx', 0o600)
|
||||
try { await file.writeFile(result); await file.sync() } finally { await file.close() }
|
||||
await link(path, output)
|
||||
} finally { await rm(temporary, { recursive: true, force: true }) }
|
||||
}
|
||||
|
||||
async function repairIdleProbeSession(entries, original, compressed, input, output) {
|
||||
const header = entries[0].row
|
||||
assertUniqueJson(entries[0].line, header)
|
||||
if (header.type !== 'session' || header.version !== 4 || header.isSeeded !== false || header.delegationDepth !== 0 ||
|
||||
header.parentSession !== undefined || header.origin !== undefined) throw new Error('Idle probe recovery requires an unseeded v4 root Session.')
|
||||
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
|
||||
const recovered = new Set()
|
||||
const pending = new Map()
|
||||
const roots = new Set()
|
||||
let openTurn
|
||||
let openStep
|
||||
let completedStep = false
|
||||
let completed = false
|
||||
const refuse = () => { throw new Error('Unrecognized or incomplete out-of-turn PTC audit; no output written.') }
|
||||
for (const entry of entries.slice(1)) {
|
||||
const row = entry.row
|
||||
if (row.type === 'turn/start' || row.type === 'turn/end') {
|
||||
assertUniqueJson(entry.line, row)
|
||||
if (pending.size || !count(row.data?.turn)) refuse()
|
||||
if (row.type === 'turn/start') {
|
||||
if (openTurn !== undefined) refuse()
|
||||
openTurn = row.data.turn
|
||||
completedStep = false
|
||||
} else {
|
||||
if (openTurn !== row.data.turn) refuse()
|
||||
openTurn = undefined
|
||||
completed = true
|
||||
}
|
||||
openStep = undefined
|
||||
}
|
||||
if (row.type === 'step/start' || row.type === 'step/end') {
|
||||
assertUniqueJson(entry.line, row)
|
||||
if (pending.size || openTurn !== row.data?.turn || !count(row.data?.step)) refuse()
|
||||
if (row.type === 'step/start') {
|
||||
if (openStep !== undefined) refuse()
|
||||
openStep = row.data.step
|
||||
} else {
|
||||
if (openStep !== row.data.step) refuse()
|
||||
openStep = undefined
|
||||
completedStep = true
|
||||
}
|
||||
}
|
||||
if (!['tool/ptc-dispatch-start', 'tool/ptc-dispatch'].includes(row.type) || openStep !== undefined) continue
|
||||
assertUniqueJson(entry.line, row)
|
||||
const data = row.data
|
||||
const start = row.type === 'tool/ptc-dispatch-start'
|
||||
if (!(openTurn === undefined ? completed : completedStep) || !exactKeys(row, ['type', 'seq', 'time', 'data']) || !count(row.seq) || !integer(row.time) ||
|
||||
!exactKeys(data, ['rootCallId', 'parentCallId', 'subCallId', 'name', 'arguments', ...(start ? [] : ['isError', 'content'])], start ? [] : ['error', 'meta']) ||
|
||||
!uuid.test(data.rootCallId) || data.parentCallId !== data.rootCallId || data.subCallId !== `${data.rootCallId}:ptc:1` ||
|
||||
data.name !== 'mnemon_subagent_result' || !exactKeys(data.arguments, ['requestId', 'result']) ||
|
||||
!uuid.test(data.arguments.requestId) || !exactKeys(data.arguments.result, [])) refuse()
|
||||
if (start) {
|
||||
if (roots.has(data.rootCallId)) refuse()
|
||||
roots.add(data.rootCallId)
|
||||
pending.set(data.rootCallId, entry)
|
||||
} else {
|
||||
const previous = pending.get(data.rootCallId)
|
||||
if (!previous || !isDeepStrictEqual(previous.row.data.arguments, data.arguments) || previous.row.seq >= row.seq ||
|
||||
typeof data.isError !== 'boolean' || !Array.isArray(data.content) ||
|
||||
!data.isError && !isDeepStrictEqual(data.content, [{ type: 'text', text: 'Mnemon subagent result recorded.' }])) refuse()
|
||||
pending.delete(data.rootCallId)
|
||||
recovered.add(previous)
|
||||
recovered.add(entry)
|
||||
}
|
||||
}
|
||||
if (pending.size) refuse()
|
||||
const changedSeqs = new Set([...recovered].map(entry => entry.row.seq))
|
||||
for (const { row } of entries.slice(1)) {
|
||||
for (const range of row.sourceEventSeqs ?? []) {
|
||||
if (typeof range === 'number' ? changedSeqs.has(range) : Array.isArray(range) && [...changedSeqs].some(seq => seq >= range[0] && seq <= range[1])) refuse()
|
||||
}
|
||||
}
|
||||
const text = entries.map(entry => recovered.has(entry)
|
||||
? JSON.stringify({ type: 'dsh-brain-mnemon/recovered-idle-probe', seq: entry.row.seq, time: entry.row.time, ignorable: true,
|
||||
data: { originalType: entry.row.type, originalData: entry.row.data } }) + '\n'
|
||||
: entry.line).join('')
|
||||
const plain = Buffer.from(text)
|
||||
if (plain.length > maximumBytes) throw new Error('Repaired Session exceeds the 128 MiB repair limit; no output written.')
|
||||
const result = recovered.size === 0 ? original : compressed ? encodeFrames(text) : plain
|
||||
if (result.length > maximumBytes) throw new Error('Repaired Session exceeds the 128 MiB repair limit; no output written.')
|
||||
if (output !== undefined) await writeRepairCopy(input, output, result)
|
||||
return { mode: output === undefined ? 'preview' : 'copy', format: 4, encoding: compressed ? 'zstd' : 'jsonl',
|
||||
recoveredIdleProbeEvents: recovered.size, inputSha256: sha256(original), outputSha256: sha256(result),
|
||||
originalPreserved: true, migrationValidated: false, blockers: [] }
|
||||
}
|
||||
|
||||
export async function repairLegacySession(input, output) {
|
||||
const original = await readBounded(input)
|
||||
const compressed = original.subarray(0, 4).equals(Buffer.from([0x28, 0xb5, 0x2f, 0xfd]))
|
||||
if (compressed && (typeof zlib.zstdDecompressSync !== 'function' || typeof zlib.zstdCompressSync !== 'function')) {
|
||||
throw new Error('Zstandard sessions require Node 22.19 or newer (or Node 24+).')
|
||||
}
|
||||
const decoded = compressed ? decodeFrames(original) : original
|
||||
const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(decoded)
|
||||
if (!text.endsWith('\n')) throw new Error('Session must end with a complete newline-terminated JSON record.')
|
||||
const lines = text.match(/[^\n]*\n/g) ?? []
|
||||
const entries = lines.map((line, index) => {
|
||||
try { return { line, index, row: JSON.parse(line) } } catch { throw new Error(`Invalid JSON at line ${index + 1}; no output written.`) }
|
||||
})
|
||||
if (entries[0]?.row?.version === 4) return repairIdleProbeSession(entries, original, compressed, input, output)
|
||||
const recovery = recoverRecordedToolIdentities(entries)
|
||||
let changes = 0
|
||||
let descriptors = 0
|
||||
let expandedRows = 0
|
||||
let expandedChunks = 0
|
||||
let normalizedNames = 0
|
||||
let outputBytes = 0
|
||||
const retain = line => {
|
||||
outputBytes += Buffer.byteLength(line)
|
||||
if (outputBytes > maximumBytes) throw new Error('Expanded Session exceeds the 128 MiB repair limit; no output written.')
|
||||
return line
|
||||
}
|
||||
const diagnostics = legacyBlockers()
|
||||
const repaired = entries.map(entry => {
|
||||
const { index } = entry
|
||||
let { line, row } = entry
|
||||
if (index === 0) {
|
||||
objectMembers(line, 0)
|
||||
if (row.type !== 'session' || row.version !== 0 || typeof row.id !== 'string' || !row.id ||
|
||||
!Number.isSafeInteger(row.createdAt) || row.createdAt < 0 ||
|
||||
!Number.isSafeInteger(row.delegationDepth) || row.delegationDepth < 0) {
|
||||
throw new Error('Only a legacy DSH format v0 Session header is supported.')
|
||||
}
|
||||
return retain(line)
|
||||
}
|
||||
const patches = recovery.rawPatches.get(index)
|
||||
if (patches) { line = replaceIdentityValues(line, patches); row = JSON.parse(line) }
|
||||
diagnostics.inspect(row, index + 1)
|
||||
if (row?.type === 'subagent/descriptor' && supportedDescriptorV2(row.data)) {
|
||||
descriptors++
|
||||
return retain(promoteDescriptor(line))
|
||||
}
|
||||
if (row?.type === 'tool-call-chunks' && supportedPackedToolRun(row)) {
|
||||
expandedRows++
|
||||
expandedChunks += row.data.args.length
|
||||
if (row.data.name === null) normalizedNames += row.data.args.length
|
||||
return expandPackedToolRun(line, row, retain, recovery.packedIds.get(index))
|
||||
}
|
||||
if (row?.type === 'assistant/chunk' && supportedNullToolDelta(row)) {
|
||||
normalizedNames++
|
||||
return retain(normalizeNullToolName(line))
|
||||
}
|
||||
const source = row?.data?.source
|
||||
if (row?.type !== 'user/message' || source?.kind !== 'plugin' || source.plugin !== 'dsh-brain-mnemon' ||
|
||||
!Object.hasOwn(summaries, source.form) || !summaries[source.form].includes(source.summary)) return retain(line)
|
||||
changes++
|
||||
return retain(removeSummary(line))
|
||||
}).join('')
|
||||
const plain = Buffer.from(repaired)
|
||||
const result = changes + descriptors + expandedRows + normalizedNames + recovery.fields === 0 ? original : compressed ? encodeFrames(repaired) : plain
|
||||
if (result.length > maximumBytes) throw new Error('Repaired Session exceeds the 128 MiB repair limit; no output written.')
|
||||
const blockers = diagnostics.report()
|
||||
if (output !== undefined && blockers.length === 0) {
|
||||
await writeRepairCopy(input, output, result)
|
||||
}
|
||||
return {
|
||||
mode: output === undefined ? 'preview' : blockers.length === 0 ? 'copy' : 'refused',
|
||||
format: 0,
|
||||
encoding: compressed ? 'zstd' : 'jsonl',
|
||||
repairedMessages: changes,
|
||||
repairedDescriptors: descriptors,
|
||||
expandedToolChunkRows: expandedRows,
|
||||
expandedToolChunks: expandedChunks,
|
||||
normalizedToolChunkNames: normalizedNames,
|
||||
recoveredToolIdentityChains: recovery.chains,
|
||||
recoveredToolIdentityFields: recovery.fields,
|
||||
toolIdentityRecoveryRefusals: recovery.refusals,
|
||||
inputSha256: sha256(original),
|
||||
outputSha256: blockers.length === 0 ? sha256(result) : null,
|
||||
originalPreserved: true,
|
||||
migrationValidated: false,
|
||||
blockers,
|
||||
}
|
||||
}
|
||||
|
||||
async function main(args) {
|
||||
const usage = 'Usage: dsh-brain-mnemon-repair-session --input FILE [--output NEW_FILE]\nWithout --output, preview recognized v4 idle-review probe audit recovery or the three known Mnemon v0 summary repairs, exact compatible v2 subagent descriptors, packed deltas with empty IDs/names, property-preserving null-to-empty delta names and proven DeepSeek chains with a previously recorded provider ID. Unsupported descriptor/tool shapes are reported with exit status 1 and prevent output. DSH must still validate the repaired copy. Stop DSH and work on a backup copy. The input and existing output files are never overwritten.'
|
||||
if (args.length === 1 && args[0] === '--help') { console.log(usage); return }
|
||||
const options = new Map()
|
||||
for (let index = 0; index < args.length; index += 2) {
|
||||
const name = args[index]
|
||||
const value = args[index + 1]
|
||||
if (!['--input', '--output'].includes(name) || !value || value.startsWith('--') || options.has(name)) throw new Error(usage)
|
||||
options.set(name, value)
|
||||
}
|
||||
if (!options.has('--input')) throw new Error(usage)
|
||||
const report = await repairLegacySession(options.get('--input'), options.get('--output'))
|
||||
console.log(JSON.stringify(report, null, 2))
|
||||
if (report.blockers.length > 0) {
|
||||
console.error('Unsupported legacy descriptor/tool data remains; no output written. Review blockers and request recovery from the original DSH writer with a sanitized reproducer.')
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
|
||||
function isEntrypoint() {
|
||||
try { return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)) }
|
||||
catch { return false }
|
||||
}
|
||||
|
||||
if (isEntrypoint()) {
|
||||
main(process.argv.slice(2)).catch(error => { console.error(error.message); process.exitCode = 1 })
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as descriptor } from "../../../lib/descriptor-B535Gkvl.js";
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, ot as MemoryProviderConnection, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import { ProcessRunner } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
interface ByteRoverProviderOptions {
|
||||
process?: ProcessRunner;
|
||||
queryTimeoutMs?: number;
|
||||
curateTimeoutMs?: number;
|
||||
}
|
||||
declare class ByteRoverProvider implements MemoryProviderAdapter {
|
||||
private readonly memorySpaces;
|
||||
readonly id: "byterover";
|
||||
readonly scoreSemantics: Readonly<{
|
||||
kind: "provider-native";
|
||||
}>;
|
||||
private readonly process;
|
||||
private readonly queryTimeoutMs;
|
||||
private readonly curateTimeoutMs;
|
||||
private readonly statusCache;
|
||||
private readonly statusInFlight;
|
||||
constructor(memorySpaces: MemorySpaceAuthority, options?: ByteRoverProviderOptions);
|
||||
discover(connection: MemoryProviderConnection): Promise<ProviderMemorySpace[]>;
|
||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
||||
invalidateStatus(memoryBodyId?: string): void;
|
||||
private checkStatus;
|
||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
||||
graph(body: MemoryBody): Promise<MemoryGraphSnapshot>;
|
||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
private connection;
|
||||
private run;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { ByteRoverProvider, _default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,264 @@
|
|||
import { i as runProcess } from "../../../lib/adapter-CF9Q9xOa.js";
|
||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { t as descriptor } from "../../../lib/descriptor-B535Gkvl.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
||||
import { mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-byterover/src/cli.ts
|
||||
const INSTALL_GUIDANCE = "Install ByteRover with npm install -g byterover-cli or pnpm add -g byterover-cli. Ensure DSH can see PATH or PNPM_HOME, or set cliPath to its brv.cmd or executable.";
|
||||
function isFile(path) {
|
||||
try {
|
||||
return statSync(path).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function globalBins(env) {
|
||||
const directory = (name) => {
|
||||
const value = Object.entries(env).find(([key]) => key.toUpperCase() === name)?.[1]?.trim().replace(/^"(.*)"$/, "$1");
|
||||
return value !== void 0 && isAbsolute(value) ? value : void 0;
|
||||
};
|
||||
const pnpm = directory("PNPM_HOME");
|
||||
const local = directory("LOCALAPPDATA") ?? join(homedir(), "AppData", "Local");
|
||||
const roaming = directory("APPDATA") ?? join(homedir(), "AppData", "Roaming");
|
||||
return [
|
||||
pnpm,
|
||||
pnpm === void 0 ? void 0 : join(pnpm, "bin"),
|
||||
directory("NVM_SYMLINK"),
|
||||
join(local, "pnpm"),
|
||||
join(local, "pnpm", "bin"),
|
||||
join(roaming, "npm")
|
||||
].filter((value) => value !== void 0);
|
||||
}
|
||||
function resolveByteRoverInvocation(command, args, env, cwd = process.cwd()) {
|
||||
if (process.platform !== "win32") return {
|
||||
command,
|
||||
args: [...args],
|
||||
env
|
||||
};
|
||||
if (/^brv(?:\.cmd)?$/i.test(command)) {
|
||||
const path = Object.entries(env).find(([key]) => key.toUpperCase() === "PATH")?.[1] ?? "";
|
||||
let found;
|
||||
for (const directory of [...path.split(";"), ...globalBins(env)]) {
|
||||
if (directory === "") continue;
|
||||
const root = directory.replace(/^"(.*)"$/, "$1");
|
||||
for (const name of /\.cmd$/i.test(command) ? ["brv.cmd"] : ["brv.exe", "brv.cmd"]) {
|
||||
const candidate = resolve(cwd, root, name);
|
||||
if (isFile(candidate)) {
|
||||
found = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found !== void 0) break;
|
||||
}
|
||||
if (found === void 0) throw new Error(`ByteRover brv was not found. ${INSTALL_GUIDANCE}`);
|
||||
command = found;
|
||||
}
|
||||
if (!/\.cmd$/i.test(command)) return {
|
||||
command,
|
||||
args: [...args],
|
||||
env
|
||||
};
|
||||
command = resolve(cwd, command);
|
||||
try {
|
||||
const shim = readFileSync(command, "utf8").replaceAll("\\", "/");
|
||||
const launchers = /* @__PURE__ */ new Set();
|
||||
for (const match of shim.matchAll(/"([^"\r\n]+)"/g)) {
|
||||
let target = match[1];
|
||||
if (!target.endsWith("/bin/run.js")) continue;
|
||||
if (/^%(?:dp0%|~dp0)\//i.test(target)) target = target.replace(/^%(?:dp0%|~dp0)\//i, "");
|
||||
else if (!isAbsolute(target)) continue;
|
||||
if (target.includes("%")) continue;
|
||||
const launcher = resolve(dirname(command), target);
|
||||
const pkg = JSON.parse(readFileSync(join(dirname(dirname(launcher)), "package.json"), "utf8"));
|
||||
const bin = pkg.bin?.brv;
|
||||
if (pkg.name === "byterover-cli" && typeof bin === "string" && bin.replace(/^\.\//, "") === "bin/run.js" && isFile(launcher)) launchers.add(realpathSync(launcher));
|
||||
}
|
||||
if (launchers.size === 1) {
|
||||
const inherited = Object.fromEntries(Object.entries(env).filter(([key]) => key.toUpperCase() !== "ELECTRON_RUN_AS_NODE"));
|
||||
return {
|
||||
command: process.execPath,
|
||||
args: [[...launchers][0], ...args],
|
||||
env: {
|
||||
...inherited,
|
||||
ELECTRON_RUN_AS_NODE: "1"
|
||||
}
|
||||
};
|
||||
}
|
||||
} catch {}
|
||||
throw new Error(`ByteRover cliPath is not a recognized npm/pnpm brv.cmd launcher. ${INSTALL_GUIDANCE}`);
|
||||
}
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-byterover/src/driver.ts
|
||||
var ByteRoverProvider = class {
|
||||
memorySpaces;
|
||||
id = "byterover";
|
||||
scoreSemantics = Object.freeze({ kind: "provider-native" });
|
||||
process;
|
||||
queryTimeoutMs;
|
||||
curateTimeoutMs;
|
||||
statusCache = /* @__PURE__ */ new Map();
|
||||
statusInFlight = /* @__PURE__ */ new Map();
|
||||
constructor(memorySpaces, options = {}) {
|
||||
this.memorySpaces = memorySpaces;
|
||||
this.process = options.process ?? runProcess;
|
||||
this.queryTimeoutMs = options.queryTimeoutMs ?? 1e4;
|
||||
this.curateTimeoutMs = options.curateTimeoutMs ?? 12e4;
|
||||
}
|
||||
async discover(connection) {
|
||||
const configured = String(connection.defaultDirectory ?? "").trim();
|
||||
const existingDirectory = this.memorySpaces.list().find((body) => (body.provider.typeId ?? body.provider.id) === this.id)?.provider.settings.workingDirectory;
|
||||
const directory = configured === "" ? String(existingDirectory ?? "").trim() || join(this.memorySpaces.runner.effectiveDataDir(), "state", "byterover", "default") : isAbsolute(configured) ? configured : resolve(this.memorySpaces.runner.effectiveDataDir(), configured);
|
||||
return [{
|
||||
externalId: directory,
|
||||
name: basename(directory) || "ByteRover",
|
||||
description: `ByteRover knowledge directory at ${directory}`,
|
||||
connection: { workingDirectory: directory }
|
||||
}];
|
||||
}
|
||||
async status(body, signal) {
|
||||
if (signal !== void 0) return this.checkStatus(body, signal);
|
||||
const cached = this.statusCache.get(body.id);
|
||||
if (cached !== void 0 && Date.now() - cached.checkedAt < 6e4) return cached.value;
|
||||
const running = this.statusInFlight.get(body.id);
|
||||
if (running !== void 0) return running;
|
||||
const pending = this.checkStatus(body);
|
||||
this.statusInFlight.set(body.id, pending);
|
||||
try {
|
||||
const value = await pending;
|
||||
this.statusCache.set(body.id, {
|
||||
checkedAt: Date.now(),
|
||||
value
|
||||
});
|
||||
return value;
|
||||
} finally {
|
||||
if (this.statusInFlight.get(body.id) === pending) this.statusInFlight.delete(body.id);
|
||||
}
|
||||
}
|
||||
invalidateStatus(memoryBodyId) {
|
||||
if (memoryBodyId === void 0) this.statusCache.clear();
|
||||
else this.statusCache.delete(memoryBodyId);
|
||||
}
|
||||
async checkStatus(body, signal) {
|
||||
try {
|
||||
await this.run(body, ["status"], 15e3, signal);
|
||||
return { healthy: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
async search(body, request, signal) {
|
||||
const output = await this.run(body, [
|
||||
"query",
|
||||
"--",
|
||||
request.query.slice(0, 5e3)
|
||||
], this.queryTimeoutMs, signal);
|
||||
if (output.length < 20 || /^no relevant (?:context|memories)\b/iu.test(output)) return {
|
||||
results: [],
|
||||
hint: "ByteRover found no relevant memories."
|
||||
};
|
||||
const content = output.length > 8e3 ? `${output.slice(0, 8e3)}\n\n[... truncated]` : output;
|
||||
return { results: [{
|
||||
id: `byterover:${createHash("sha256").update(content).digest("hex").slice(0, 24)}`,
|
||||
content,
|
||||
category: "context",
|
||||
source: "external"
|
||||
}] };
|
||||
}
|
||||
async graph(body) {
|
||||
this.connection(body);
|
||||
return {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
||||
};
|
||||
}
|
||||
async list(body, request, signal) {
|
||||
if (request.query === void 0 || request.query.trim() === "") {
|
||||
this.connection(body);
|
||||
return [];
|
||||
}
|
||||
return (await this.search(body, {
|
||||
query: request.query,
|
||||
...request.limit === void 0 ? {} : { limit: request.limit }
|
||||
}, signal)).results;
|
||||
}
|
||||
async remember(body, request, signal) {
|
||||
await this.run(body, [
|
||||
"curate",
|
||||
"--",
|
||||
request.content
|
||||
], this.curateTimeoutMs, signal);
|
||||
this.invalidateStatus(body.id);
|
||||
return {
|
||||
action: "stored",
|
||||
provider: this.id,
|
||||
summary: "ByteRover curated the memory into its knowledge tree."
|
||||
};
|
||||
}
|
||||
connection(body) {
|
||||
if ((body.provider.typeId ?? body.provider.id) !== this.id) throw new Error(`ByteRover cannot serve provider ${body.provider.id}`);
|
||||
return this.memorySpaces.providerConnection(body.id, body.provider.id);
|
||||
}
|
||||
async run(body, args, timeoutMs, signal) {
|
||||
const connection = this.connection(body);
|
||||
const command = String(connection.cliPath ?? "brv");
|
||||
const configuredDirectory = String(connection.workingDirectory ?? connection.defaultDirectory ?? "").trim();
|
||||
const defaultDirectory = join(this.memorySpaces.runner.effectiveDataDir(), "state", "byterover", "default");
|
||||
const cwd = configuredDirectory === "" ? defaultDirectory : isAbsolute(configuredDirectory) ? configuredDirectory : resolve(this.memorySpaces.runner.effectiveDataDir(), configuredDirectory);
|
||||
mkdirSync(cwd, {
|
||||
recursive: true,
|
||||
mode: 448
|
||||
});
|
||||
const apiKey = String(connection.apiKey ?? "").trim();
|
||||
const invocation = resolveByteRoverInvocation(command, args, {
|
||||
...process.env,
|
||||
...apiKey === "" ? {} : { BRV_API_KEY: apiKey }
|
||||
}, cwd);
|
||||
const result = await this.process(invocation.command, invocation.args, {
|
||||
timeoutMs,
|
||||
maxOutputBytes: 262144,
|
||||
...signal === void 0 ? {} : { signal },
|
||||
cwd,
|
||||
label: "ByteRover",
|
||||
env: invocation.env
|
||||
});
|
||||
const stdout = result.stdout.trim();
|
||||
const stderr = result.stderr.trim();
|
||||
if (result.exitCode !== 0) throw new Error(stderr || stdout || `ByteRover exited with code ${String(result.exitCode)}`);
|
||||
return stdout;
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-byterover/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-byterover",
|
||||
version: "0.5.9",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "provider-native"
|
||||
},
|
||||
create: (context) => new ByteRoverProvider(context.memorySpaces ?? context.memoryBodies, { queryTimeoutMs: context.config.timeoutMs })
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { ByteRoverProvider, src_default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-byterover",
|
||||
"version": "0.5.9",
|
||||
"description": "ByteRover Provider child for the Memory Spaces Source.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-byterover"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-byterover#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as descriptor } from "../../../lib/descriptor-BBhLI7C8.js";
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight, y as EdgeType } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
declare class HindsightProvider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
||||
readonly id: "hindsight";
|
||||
readonly scoreSemantics: Readonly<{
|
||||
kind: "provider-native";
|
||||
}>;
|
||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
graph(body: MemoryBody, signal?: AbortSignal): Promise<MemoryGraphSnapshot>;
|
||||
related(body: MemoryBody, id: string, depth: number, _edge?: EdgeType, signal?: AbortSignal): Promise<Insight[]>;
|
||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
private bankPath;
|
||||
private headers;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { HindsightProvider, _default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,283 @@
|
|||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import { HttpMemoryProvider, firstArray, jsonArray, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { t as descriptor } from "../../../lib/descriptor-BBhLI7C8.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-hindsight/src/driver.ts
|
||||
function withoutTrailingNote(entry) {
|
||||
const trimmed = entry.trimEnd();
|
||||
if (!trimmed.endsWith(")")) return entry.trim();
|
||||
const close = trimmed.length - 1;
|
||||
const open = trimmed.indexOf("(", trimmed.lastIndexOf(")", close - 1) + 1);
|
||||
return open < 0 || open >= close ? entry.trim() : trimmed.slice(0, open).trim();
|
||||
}
|
||||
function insight(value) {
|
||||
const item = jsonObject(value);
|
||||
const id = jsonString(item?.id);
|
||||
const content = jsonString(item?.text) ?? jsonString(item?.content) ?? jsonString(item?.label);
|
||||
if (id === void 0 || content === void 0) return void 0;
|
||||
const scores = jsonObject(item?.scores);
|
||||
const score = jsonNumber(scores?.final) ?? jsonNumber(item?.score);
|
||||
const createdAt = jsonString(item?.mentioned_at) ?? jsonString(item?.date) ?? jsonString(item?.occurred_start);
|
||||
const rawEntities = item?.entities;
|
||||
const entities = Array.isArray(rawEntities) ? rawEntities.filter((entry) => typeof entry === "string") : typeof rawEntities === "string" ? rawEntities.split(",").map(withoutTrailingNote).filter(Boolean) : [];
|
||||
const tags = jsonArray(item?.tags).filter((entry) => typeof entry === "string");
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
category: jsonString(item?.type) ?? jsonString(item?.fact_type) ?? "general",
|
||||
source: "external",
|
||||
...score === void 0 ? {} : { score },
|
||||
...createdAt === void 0 ? {} : { createdAt },
|
||||
...entities.length === 0 ? {} : { entities },
|
||||
...tags.length === 0 ? {} : { tags }
|
||||
};
|
||||
}
|
||||
function edgeType(value) {
|
||||
return value === "temporal" || value === "semantic" || value === "causal" || value === "entity" ? value : void 0;
|
||||
}
|
||||
var HindsightProvider = class extends HttpMemoryProvider {
|
||||
id = "hindsight";
|
||||
scoreSemantics = Object.freeze({ kind: "provider-native" });
|
||||
constructor(memorySpaces, options = {}) {
|
||||
super(memorySpaces, {
|
||||
label: descriptor.label,
|
||||
...options
|
||||
});
|
||||
}
|
||||
async discover(connection, signal) {
|
||||
const payload = await this.requestConnection(connection, "/v1/default/banks", {
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
});
|
||||
return firstArray(payload, "banks", "items").flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const id = jsonString(item?.bank_id) ?? jsonString(item?.id);
|
||||
if (id === void 0) return [];
|
||||
const description = jsonString(item?.mission)?.trim() || jsonString(item?.description)?.trim() || `Hindsight memory bank ${id}`;
|
||||
return [{
|
||||
externalId: id,
|
||||
name: jsonString(item?.name) ?? id,
|
||||
description,
|
||||
connection: {
|
||||
bankId: id,
|
||||
budget: "mid"
|
||||
}
|
||||
}];
|
||||
});
|
||||
}
|
||||
async status(body, signal) {
|
||||
try {
|
||||
const connection = this.connection(body);
|
||||
await this.request(body, "/health/live", {
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
});
|
||||
try {
|
||||
const [statsPayload, entitiesPayload] = await Promise.all([this.request(body, `${this.bankPath(connection)}/stats`, {
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
}), this.request(body, `${this.bankPath(connection)}/entities?limit=100&offset=0`, {
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
})]);
|
||||
const stats = jsonObject(statsPayload) ?? {};
|
||||
const byFactType = jsonObject(stats.nodes_by_fact_type) ?? {};
|
||||
const byCategory = Object.fromEntries(Object.entries(byFactType).flatMap(([category, count]) => {
|
||||
const value = jsonNumber(count);
|
||||
return value === void 0 ? [] : [[category, value]];
|
||||
}));
|
||||
const operations = jsonObject(stats.operations_by_status) ?? {};
|
||||
const topEntities = firstArray(entitiesPayload, "items").flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const entity = jsonString(item?.canonical_name);
|
||||
const count = jsonNumber(item?.mention_count);
|
||||
return entity === void 0 || count === void 0 ? [] : [{
|
||||
entity,
|
||||
count
|
||||
}];
|
||||
});
|
||||
return {
|
||||
healthy: true,
|
||||
stats: {
|
||||
totalInsights: jsonNumber(stats.total_nodes) ?? 0,
|
||||
deletedInsights: 0,
|
||||
edgeCount: jsonNumber(stats.total_links) ?? 0,
|
||||
oplogCount: Object.values(operations).reduce((total, value) => total + (jsonNumber(value) ?? 0), 0),
|
||||
dbSizeBytes: 0,
|
||||
byCategory,
|
||||
topEntities
|
||||
}
|
||||
};
|
||||
} catch {
|
||||
return { healthy: true };
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
async search(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const payload = await this.request(body, `${this.bankPath(connection)}/memories/recall`, {
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
query: request.query,
|
||||
budget: String(connection.budget ?? "mid"),
|
||||
max_tokens: Math.min(Math.max((request.limit ?? 10) * 400, 400), 8e3),
|
||||
types: [
|
||||
"world",
|
||||
"experience",
|
||||
"observation"
|
||||
],
|
||||
prefer_observations: true
|
||||
},
|
||||
signal
|
||||
});
|
||||
return { results: firstArray(payload, "results", "items").map(insight).filter((item) => item !== void 0).slice(0, request.limit ?? 10) };
|
||||
}
|
||||
async list(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const params = new URLSearchParams({
|
||||
limit: String(Math.min(Math.max(request.limit ?? 200, 1), 1e3)),
|
||||
offset: "0",
|
||||
state: "valid"
|
||||
});
|
||||
if (request.query !== void 0 && request.query.trim() !== "") params.set("q", request.query.trim());
|
||||
const payload = await this.request(body, `${this.bankPath(connection)}/memories/list?${params}`, {
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
});
|
||||
return firstArray(payload, "items", "results").map(insight).filter((item) => item !== void 0).filter((item) => request.category === void 0 || item.category === request.category);
|
||||
}
|
||||
async graph(body, signal) {
|
||||
const connection = this.connection(body);
|
||||
const payload = jsonObject(await this.request(body, `${this.bankPath(connection)}/graph?limit=1000`, {
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
})) ?? {};
|
||||
return {
|
||||
nodes: jsonArray(payload.nodes).flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const data = jsonObject(item?.data) ?? item;
|
||||
const projected = insight(data);
|
||||
return projected === void 0 ? [] : [{
|
||||
...projected,
|
||||
color: jsonString(data?.color) ?? "#6574d9"
|
||||
}];
|
||||
}),
|
||||
edges: jsonArray(payload.edges).flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const data = jsonObject(item?.data) ?? item;
|
||||
const sourceId = jsonString(data?.from) ?? jsonString(data?.source);
|
||||
const targetId = jsonString(data?.to) ?? jsonString(data?.target);
|
||||
if (sourceId === void 0 || targetId === void 0) return [];
|
||||
const rawType = jsonString(data?.type) ?? jsonString(data?.linkType);
|
||||
const type = edgeType(rawType);
|
||||
return [{
|
||||
sourceId,
|
||||
targetId,
|
||||
label: rawType ?? "related",
|
||||
color: type === "causal" ? "#e74c3c" : type === "entity" ? "#2ecc71" : type === "temporal" ? "#aaaaaa" : "#3498db",
|
||||
...type === void 0 ? {} : { type }
|
||||
}];
|
||||
}),
|
||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
||||
};
|
||||
}
|
||||
async related(body, id, depth, _edge, signal) {
|
||||
const graph = await this.graph(body, signal);
|
||||
let frontier = /* @__PURE__ */ new Set([id]);
|
||||
const visited = /* @__PURE__ */ new Set([id]);
|
||||
for (let level = 0; level < depth; level += 1) {
|
||||
const next = /* @__PURE__ */ new Set();
|
||||
for (const edge of graph.edges) {
|
||||
if (frontier.has(edge.sourceId) && !visited.has(edge.targetId)) next.add(edge.targetId);
|
||||
if (frontier.has(edge.targetId) && !visited.has(edge.sourceId)) next.add(edge.sourceId);
|
||||
}
|
||||
for (const value of next) visited.add(value);
|
||||
frontier = next;
|
||||
}
|
||||
return graph.nodes.filter((node) => node.id !== id && visited.has(node.id)).map(({ color: _color, ...node }) => node);
|
||||
}
|
||||
async remember(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const operationId = randomUUID();
|
||||
const payload = jsonObject(await this.request(body, `${this.bankPath(connection)}/memories`, {
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
items: [{
|
||||
content: request.content,
|
||||
context: request.category ?? "dsh-brain-mnemon",
|
||||
metadata: { source: "dsh-brain-mnemon" },
|
||||
...request.tags === void 0 ? {} : { tags: request.tags },
|
||||
...request.entities === void 0 ? {} : { entities: request.entities.map((text) => ({ text })) }
|
||||
}],
|
||||
async: true,
|
||||
operation_id: operationId
|
||||
},
|
||||
signal
|
||||
})) ?? {};
|
||||
return {
|
||||
action: "queued",
|
||||
provider: this.id,
|
||||
summary: "Hindsight queued the content for structured memory extraction.",
|
||||
operationId: jsonString(payload.operation_id) ?? operationId,
|
||||
...jsonNumber(payload.items_count) === void 0 ? {} : { itemsCount: jsonNumber(payload.items_count) }
|
||||
};
|
||||
}
|
||||
async forget(body, id, signal) {
|
||||
const connection = this.connection(body);
|
||||
await this.request(body, `${this.bankPath(connection)}/memories/${encodeURIComponent(id)}`, {
|
||||
method: "PATCH",
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
state: "invalidated",
|
||||
reason: "Forgotten from dsh-brain-mnemon"
|
||||
},
|
||||
signal
|
||||
});
|
||||
return {
|
||||
action: "invalidated",
|
||||
provider: this.id,
|
||||
id
|
||||
};
|
||||
}
|
||||
bankPath(connection) {
|
||||
return `/v1/default/banks/${encodeURIComponent(String(connection.bankId))}`;
|
||||
}
|
||||
headers(connection) {
|
||||
const token = String(connection.apiKey ?? "").replace(/^Bearer\s+/iu, "");
|
||||
return token === "" ? {} : { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-hindsight/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-hindsight",
|
||||
version: "0.5.8",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "provider-native"
|
||||
},
|
||||
create: (context) => new HindsightProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { HindsightProvider, src_default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-hindsight",
|
||||
"version": "0.5.8",
|
||||
"description": "Hindsight Provider child for the Memory Spaces Source.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-hindsight"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-hindsight#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as descriptor } from "../../../lib/descriptor-Bo7K54GN.js";
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, ot as MemoryProviderConnection, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
declare class HolographicProvider implements MemoryProviderAdapter {
|
||||
private readonly memorySpaces;
|
||||
readonly id: "holographic";
|
||||
readonly scoreSemantics: ProviderScoreSemantics;
|
||||
constructor(memorySpaces: MemorySpaceAuthority);
|
||||
discover(connection: MemoryProviderConnection): Promise<ProviderMemorySpace[]>;
|
||||
status(body: MemoryBody): Promise<ProviderBodyStatus>;
|
||||
search(body: MemoryBody, request: SearchRequest): Promise<ProviderSearchResult>;
|
||||
list(body: MemoryBody, request: MemoryListRequest): Promise<Insight[]>;
|
||||
graph(body: MemoryBody): Promise<MemoryGraphSnapshot>;
|
||||
related(body: MemoryBody, id: string, _depth: number): Promise<Insight[]>;
|
||||
remember(body: MemoryBody, request: RememberRequest): Promise<MemoryJsonValue>;
|
||||
forget(body: MemoryBody, id: string): Promise<MemoryJsonValue>;
|
||||
private connection;
|
||||
private path;
|
||||
private load;
|
||||
private loadFromPath;
|
||||
private save;
|
||||
private stats;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { HolographicProvider, _default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,335 @@
|
|||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { t as descriptor } from "../../../lib/descriptor-Bo7K54GN.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-holographic/src/top-scored.ts
|
||||
function topScored(values, limit) {
|
||||
const count = Math.min(values.length, Math.max(0, Math.trunc(limit) || 0));
|
||||
if (count === 0) return [];
|
||||
if (values.length <= Math.max(64, count * 2) || values.some((value) => !Number.isFinite(value.score))) return values.sort((left, right) => right.score - left.score).slice(0, count);
|
||||
const compare = (left, right) => values[right].score - values[left].score || left - right;
|
||||
const heap = [];
|
||||
for (let index = 0; index < values.length; index++) if (heap.length < count) {
|
||||
let child = heap.length;
|
||||
heap.push(index);
|
||||
while (child > 0) {
|
||||
const parent = child - 1 >>> 1;
|
||||
if (compare(heap[parent], index) >= 0) break;
|
||||
heap[child] = heap[parent];
|
||||
child = parent;
|
||||
}
|
||||
heap[child] = index;
|
||||
} else if (compare(index, heap[0]) < 0) {
|
||||
let parent = 0;
|
||||
while (parent * 2 + 1 < count) {
|
||||
let child = parent * 2 + 1;
|
||||
if (child + 1 < count && compare(heap[child + 1], heap[child]) > 0) child += 1;
|
||||
if (compare(index, heap[child]) >= 0) break;
|
||||
heap[parent] = heap[child];
|
||||
parent = child;
|
||||
}
|
||||
heap[parent] = index;
|
||||
}
|
||||
return heap.sort(compare).map((index) => values[index]);
|
||||
}
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-holographic/src/driver.ts
|
||||
const WORD = /[\p{L}\p{N}_-]+/gu;
|
||||
const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
|
||||
const HAS_CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
||||
const QUOTED = /["“”'‘’]([^"“”'‘’]{2,100})["“”'‘’]/gu;
|
||||
const CAPITALIZED = /\b([A-Z][\p{L}\p{N}_-]+(?:\s+[A-Z][\p{L}\p{N}_-]+)*)\b/gu;
|
||||
function clampTrust(value) {
|
||||
return Math.min(1, Math.max(0, value));
|
||||
}
|
||||
function matchesEntity(queryLower, queryWords, rawEntity) {
|
||||
const entity = rawEntity.trim().toLocaleLowerCase();
|
||||
if (entity === "") return false;
|
||||
if (HAS_CJK.test(entity)) return queryLower.includes(entity);
|
||||
const entityWords = entity.match(WORD) ?? [];
|
||||
if (entityWords.length === 0) return queryLower.includes(entity);
|
||||
if (entityWords.length === 1 && entityWords[0] === entity) return queryWords.has(entity);
|
||||
const escaped = entity.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
||||
return new RegExp(`(?<![\\p{L}\\p{N}_-])${escaped}(?![\\p{L}\\p{N}_-])`, "u").test(queryLower);
|
||||
}
|
||||
function terms(value) {
|
||||
const normalized = value.toLocaleLowerCase();
|
||||
const output = new Set((normalized.match(WORD) ?? []).filter((token) => token.length > 1));
|
||||
for (const run of normalized.match(CJK) ?? []) {
|
||||
for (const character of run) output.add(character);
|
||||
for (let index = 0; index < run.length - 1; index += 1) output.add(run.slice(index, index + 2));
|
||||
}
|
||||
return output;
|
||||
}
|
||||
function overlap(left, right) {
|
||||
if (left.size === 0 || right.size === 0) return 0;
|
||||
let shared = 0;
|
||||
const [smaller, larger] = left.size <= right.size ? [left, right] : [right, left];
|
||||
for (const value of smaller) if (larger.has(value)) shared += 1;
|
||||
return shared / (left.size + right.size - shared);
|
||||
}
|
||||
function extractEntities(content, supplied = []) {
|
||||
const values = [...supplied];
|
||||
for (const match of content.matchAll(QUOTED)) values.push(match[1]);
|
||||
for (const match of content.matchAll(CAPITALIZED)) values.push(match[1]);
|
||||
return [...new Set(values.map((value) => value.trim()).filter((value) => value.length >= 2 && value.length <= 100))].slice(0, 50);
|
||||
}
|
||||
function insight(fact, score) {
|
||||
return {
|
||||
id: fact.id,
|
||||
content: fact.content,
|
||||
category: fact.category,
|
||||
...fact.importance === void 0 ? {} : { importance: fact.importance },
|
||||
tags: fact.tags,
|
||||
entities: fact.entities,
|
||||
source: "external",
|
||||
createdAt: fact.createdAt,
|
||||
...score === void 0 ? {} : { score }
|
||||
};
|
||||
}
|
||||
var HolographicProvider = class {
|
||||
memorySpaces;
|
||||
id = "holographic";
|
||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
||||
constructor(memorySpaces) {
|
||||
this.memorySpaces = memorySpaces;
|
||||
}
|
||||
async discover(connection) {
|
||||
const configured = String(connection.dataPath ?? "").trim();
|
||||
const path = configured === "" ? join(this.memorySpaces.runner.effectiveDataDir(), "state", "holographic", "store.json") : isAbsolute(configured) ? configured : resolve(this.memorySpaces.runner.effectiveDataDir(), configured);
|
||||
const label = basename(path).replace(/\.json$/iu, "") || "Holographic";
|
||||
return [{
|
||||
externalId: path,
|
||||
name: label === "store" ? "Holographic" : label,
|
||||
description: `Holographic fact store at ${path}`,
|
||||
connection: {
|
||||
defaultTrust: .5,
|
||||
minTrust: .3
|
||||
}
|
||||
}];
|
||||
}
|
||||
async status(body) {
|
||||
try {
|
||||
const path = this.path(body);
|
||||
const store = this.loadFromPath(path);
|
||||
return {
|
||||
healthy: true,
|
||||
stats: this.stats(store, path)
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
async search(body, request) {
|
||||
const store = this.load(body);
|
||||
const connection = this.connection(body);
|
||||
const minTrust = clampTrust(Number(connection.minTrust ?? .3));
|
||||
const queryTerms = terms(request.query);
|
||||
const query = request.query.toLocaleLowerCase();
|
||||
const queryWords = new Set(query.match(WORD) ?? []);
|
||||
const limit = Math.min(Math.max(request.limit ?? 10, 1), 50);
|
||||
return { results: topScored(store.facts.flatMap((fact) => {
|
||||
if (fact.trustScore < minTrust || request.category !== void 0 && fact.category !== request.category) return [];
|
||||
const lexical = overlap(queryTerms, terms(`${fact.content} ${fact.tags.join(" ")} ${fact.entities.join(" ")}`));
|
||||
const phrase = fact.content.toLocaleLowerCase().includes(query) ? 1 : 0;
|
||||
const entity = fact.entities.some((value) => matchesEntity(query, queryWords, value)) ? 1 : 0;
|
||||
const relevance = Math.max(lexical, phrase * .9, entity * .8);
|
||||
return relevance <= 0 ? [] : [{
|
||||
fact,
|
||||
score: relevance * fact.trustScore
|
||||
}];
|
||||
}), limit).map((result) => insight(result.fact, result.score)) };
|
||||
}
|
||||
async list(body, request) {
|
||||
if (request.query !== void 0 && request.query.trim() !== "") return (await this.search(body, {
|
||||
query: request.query,
|
||||
...request.category === void 0 ? {} : { category: request.category },
|
||||
...request.limit === void 0 ? {} : { limit: request.limit }
|
||||
})).results;
|
||||
const store = this.load(body);
|
||||
const minTrust = clampTrust(Number(this.connection(body).minTrust ?? .3));
|
||||
return store.facts.filter((fact) => fact.trustScore >= minTrust && (request.category === void 0 || fact.category === request.category)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)).slice(0, Math.min(Math.max(request.limit ?? 200, 1), 1e3)).map((fact) => insight(fact));
|
||||
}
|
||||
async graph(body) {
|
||||
const facts = await this.list(body, { limit: 500 });
|
||||
const entities = [...new Set(facts.flatMap((fact) => fact.entities ?? []))];
|
||||
return {
|
||||
nodes: [...facts.map((fact) => ({
|
||||
...fact,
|
||||
color: "#6574d9",
|
||||
kind: "memory"
|
||||
})), ...entities.map((entity) => ({
|
||||
id: `entity:${encodeURIComponent(entity)}`,
|
||||
content: entity,
|
||||
color: "#2ecc71",
|
||||
kind: "entity"
|
||||
}))],
|
||||
edges: facts.flatMap((fact) => (fact.entities ?? []).map((entity) => ({
|
||||
sourceId: fact.id,
|
||||
targetId: `entity:${encodeURIComponent(entity)}`,
|
||||
label: "entity",
|
||||
color: "#2ecc71",
|
||||
type: "entity"
|
||||
}))),
|
||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
||||
};
|
||||
}
|
||||
async related(body, id, _depth) {
|
||||
const store = this.load(body);
|
||||
const source = store.facts.find((fact) => fact.id === id);
|
||||
if (source === void 0) return [];
|
||||
const sourceEntities = new Set(source.entities.map((value) => value.toLocaleLowerCase()));
|
||||
const sourceTerms = terms(source.content);
|
||||
const minTrust = clampTrust(Number(this.connection(body).minTrust ?? .3));
|
||||
return topScored(store.facts.flatMap((fact) => {
|
||||
if (fact.id === id || fact.trustScore < minTrust) return [];
|
||||
const sharedEntities = fact.entities.filter((value) => sourceEntities.has(value.toLocaleLowerCase())).length;
|
||||
const score = Math.max(sharedEntities === 0 ? 0 : Math.min(1, .5 + sharedEntities * .2), overlap(sourceTerms, terms(fact.content))) * fact.trustScore;
|
||||
return score <= 0 ? [] : [{
|
||||
fact,
|
||||
score
|
||||
}];
|
||||
}), 20).map((result) => insight(result.fact, result.score));
|
||||
}
|
||||
async remember(body, request) {
|
||||
if (request.importance !== void 0 && (!Number.isInteger(request.importance) || request.importance < 1 || request.importance > 5)) throw new Error("importance must be an integer from 1 through 5");
|
||||
const store = this.load(body);
|
||||
const existing = store.facts.find((fact) => fact.content === request.content.trim());
|
||||
if (existing !== void 0) return {
|
||||
action: "skipped",
|
||||
provider: this.id,
|
||||
id: existing.id,
|
||||
content: existing.content,
|
||||
summary: "Holographic already contains this fact."
|
||||
};
|
||||
const now = (/* @__PURE__ */ new Date()).toISOString();
|
||||
const connection = this.connection(body);
|
||||
const fact = {
|
||||
id: `holo-${randomUUID()}`,
|
||||
content: request.content.trim(),
|
||||
category: request.category ?? "general",
|
||||
tags: [...new Set(request.tags ?? [])],
|
||||
entities: extractEntities(request.content, request.entities),
|
||||
trustScore: request.importance === void 0 ? clampTrust(Number(connection.defaultTrust ?? .5)) : request.importance / 5,
|
||||
importance: request.importance ?? 3,
|
||||
createdAt: now,
|
||||
updatedAt: now
|
||||
};
|
||||
store.facts.push(fact);
|
||||
this.save(body, store);
|
||||
return {
|
||||
action: "stored",
|
||||
provider: this.id,
|
||||
id: fact.id,
|
||||
summary: "Holographic stored the structured fact."
|
||||
};
|
||||
}
|
||||
async forget(body, id) {
|
||||
const store = this.load(body);
|
||||
const before = store.facts.length;
|
||||
store.facts = store.facts.filter((fact) => fact.id !== id);
|
||||
if (store.facts.length === before) throw new Error(`unknown Holographic fact: ${id}`);
|
||||
this.save(body, store);
|
||||
return {
|
||||
action: "deleted",
|
||||
provider: this.id,
|
||||
id
|
||||
};
|
||||
}
|
||||
connection(body) {
|
||||
if ((body.provider.typeId ?? body.provider.id) !== this.id) throw new Error(`Holographic cannot serve provider ${body.provider.id}`);
|
||||
return this.memorySpaces.providerConnection(body.id, body.provider.id);
|
||||
}
|
||||
path(body) {
|
||||
const configured = String(this.connection(body).dataPath ?? "").trim();
|
||||
if (configured === "") return join(this.memorySpaces.runner.effectiveDataDir(), "state", "holographic", "store.json");
|
||||
return isAbsolute(configured) ? configured : resolve(this.memorySpaces.runner.effectiveDataDir(), configured);
|
||||
}
|
||||
load(body) {
|
||||
return this.loadFromPath(this.path(body));
|
||||
}
|
||||
loadFromPath(path) {
|
||||
if (!existsSync(path)) return {
|
||||
version: 1,
|
||||
facts: []
|
||||
};
|
||||
const value = JSON.parse(readFileSync(path, "utf8"));
|
||||
if (value.version !== 1 || !Array.isArray(value.facts)) throw new Error(`invalid Holographic fact store: ${path}`);
|
||||
return {
|
||||
version: 1,
|
||||
facts: value.facts
|
||||
};
|
||||
}
|
||||
save(body, store) {
|
||||
const path = this.path(body);
|
||||
mkdirSync(dirname(path), {
|
||||
recursive: true,
|
||||
mode: 448
|
||||
});
|
||||
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
writeFileSync(temporary, `${JSON.stringify(store, null, 2)}\n`, {
|
||||
encoding: "utf8",
|
||||
mode: 384
|
||||
});
|
||||
renameSync(temporary, path);
|
||||
chmodSync(path, 384);
|
||||
} finally {
|
||||
rmSync(temporary, { force: true });
|
||||
}
|
||||
}
|
||||
stats(store, path) {
|
||||
const byCategory = {};
|
||||
const entityCounts = /* @__PURE__ */ new Map();
|
||||
for (const fact of store.facts) {
|
||||
byCategory[fact.category] = (byCategory[fact.category] ?? 0) + 1;
|
||||
for (const entity of fact.entities) entityCounts.set(entity, (entityCounts.get(entity) ?? 0) + 1);
|
||||
}
|
||||
return {
|
||||
totalInsights: store.facts.length,
|
||||
deletedInsights: 0,
|
||||
edgeCount: store.facts.reduce((total, fact) => total + fact.entities.length, 0),
|
||||
oplogCount: 0,
|
||||
dbSizeBytes: existsSync(path) ? statSync(path).size : 0,
|
||||
byCategory,
|
||||
topEntities: [...entityCounts].map(([entity, count]) => ({
|
||||
entity,
|
||||
count
|
||||
})).sort((left, right) => right.count - left.count).slice(0, 20)
|
||||
};
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-holographic/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-holographic",
|
||||
version: "0.5.9",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "normalized-relevance"
|
||||
},
|
||||
create: (context) => new HolographicProvider(context.memorySpaces ?? context.memoryBodies)
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { HolographicProvider, src_default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-holographic",
|
||||
"version": "0.5.9",
|
||||
"description": "Holographic Provider child for the Memory Spaces Source.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-holographic"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-holographic#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as descriptor } from "../../../lib/descriptor-Ck-nyEdk.js";
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
declare class HonchoProvider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
||||
readonly id: "honcho";
|
||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
private basePath;
|
||||
private scope;
|
||||
private headers;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { HonchoProvider, _default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import { HttpMemoryProvider, firstArray, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { t as descriptor } from "../../../lib/descriptor-Ck-nyEdk.js";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-honcho/src/driver.ts
|
||||
function insight(value) {
|
||||
const item = jsonObject(value);
|
||||
const id = jsonString(item?.id);
|
||||
const content = jsonString(item?.content);
|
||||
if (id === void 0 || content === void 0) return void 0;
|
||||
const observer = jsonString(item?.observer_id) ?? jsonString(item?.observer);
|
||||
const observed = jsonString(item?.observed_id) ?? jsonString(item?.observed);
|
||||
const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt);
|
||||
const entities = [observer, observed].filter((entry) => entry !== void 0);
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
category: jsonString(item?.level) ?? "insight",
|
||||
source: "external",
|
||||
...createdAt === void 0 ? {} : { createdAt },
|
||||
...entities.length === 0 ? {} : { entities }
|
||||
};
|
||||
}
|
||||
var HonchoProvider = class extends HttpMemoryProvider {
|
||||
id = "honcho";
|
||||
constructor(memorySpaces, options = {}) {
|
||||
super(memorySpaces, {
|
||||
label: descriptor.label,
|
||||
...options
|
||||
});
|
||||
}
|
||||
async discover(connection, signal) {
|
||||
const payload = await this.requestConnection(connection, "/v3/workspaces/list?page=1&size=100", {
|
||||
headers: this.headers(connection),
|
||||
json: {},
|
||||
signal
|
||||
});
|
||||
return firstArray(payload, "items", "results").flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const id = jsonString(item?.id);
|
||||
if (id === void 0) return [];
|
||||
const metadata = jsonObject(item?.metadata);
|
||||
return [{
|
||||
externalId: id,
|
||||
name: jsonString(metadata?.name) ?? jsonString(metadata?.title) ?? id,
|
||||
description: jsonString(metadata?.description) ?? `Honcho workspace ${id}`,
|
||||
connection: {
|
||||
workspace: id,
|
||||
userId: "*",
|
||||
agentId: "*"
|
||||
}
|
||||
}];
|
||||
});
|
||||
}
|
||||
async status(body, signal) {
|
||||
try {
|
||||
await this.list(body, { limit: 1 }, signal);
|
||||
return { healthy: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
async search(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const payload = await this.request(body, `${this.basePath(connection)}/conclusions/query`, {
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
query: request.query,
|
||||
top_k: Math.min(request.limit ?? 10, 100),
|
||||
filters: this.scope(connection, true)
|
||||
},
|
||||
signal
|
||||
});
|
||||
return { results: firstArray(payload, "items", "results").map(insight).filter((item) => item !== void 0) };
|
||||
}
|
||||
async list(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const limit = Math.min(Math.max(request.limit ?? 200, 1), 100);
|
||||
const payload = await this.request(body, `${this.basePath(connection)}/conclusions/list?page=1&size=${limit}`, {
|
||||
headers: this.headers(connection),
|
||||
json: { filters: {
|
||||
...this.scope(connection),
|
||||
...request.category === void 0 ? {} : { level: request.category }
|
||||
} },
|
||||
signal
|
||||
});
|
||||
return firstArray(payload, "items", "results").map(insight).filter((item) => item !== void 0);
|
||||
}
|
||||
async remember(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const payload = await this.request(body, `${this.basePath(connection)}/conclusions`, {
|
||||
headers: this.headers(connection),
|
||||
json: { conclusions: [{
|
||||
content: request.content,
|
||||
observer_id: String(connection.agentId) === "*" ? "dsh" : String(connection.agentId),
|
||||
observed_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
|
||||
session_id: null
|
||||
}] },
|
||||
signal
|
||||
});
|
||||
const created = firstArray(payload, "items", "results").map(jsonObject).find((item) => item !== void 0);
|
||||
return {
|
||||
action: "stored",
|
||||
provider: this.id,
|
||||
summary: "Honcho stored an explicit peer conclusion.",
|
||||
...jsonString(created?.id) === void 0 ? {} : { id: jsonString(created?.id) }
|
||||
};
|
||||
}
|
||||
async forget(body, id, signal) {
|
||||
const connection = this.connection(body);
|
||||
await this.request(body, `${this.basePath(connection)}/conclusions/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
});
|
||||
return {
|
||||
action: "deleted",
|
||||
provider: this.id,
|
||||
id
|
||||
};
|
||||
}
|
||||
basePath(connection) {
|
||||
return `/v3/workspaces/${encodeURIComponent(String(connection.workspace))}`;
|
||||
}
|
||||
scope(connection, requirePeers = false) {
|
||||
const agentId = String(connection.agentId);
|
||||
const userId = String(connection.userId);
|
||||
return {
|
||||
...agentId === "*" ? requirePeers ? { observer_id: "dsh" } : {} : { observer_id: agentId },
|
||||
...userId === "*" ? requirePeers ? { observed_id: "dsh-user" } : {} : { observed_id: userId }
|
||||
};
|
||||
}
|
||||
headers(connection) {
|
||||
const token = String(connection.apiKey ?? "").replace(/^Bearer\s+/iu, "");
|
||||
return token === "" ? {} : { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-honcho/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-honcho",
|
||||
version: "0.5.6",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "provider-native"
|
||||
},
|
||||
create: (context) => new HonchoProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { HonchoProvider, src_default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-honcho",
|
||||
"version": "0.5.6",
|
||||
"description": "Honcho Provider child for the Memory Spaces Source.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-honcho"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-honcho#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as descriptor } from "../../../lib/descriptor-DIAMITdX.js";
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
declare class Mem0Provider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
||||
readonly id: "mem0";
|
||||
readonly scoreSemantics: ProviderScoreSemantics;
|
||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
private filters;
|
||||
private headers;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { Mem0Provider, _default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,202 @@
|
|||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import { HttpMemoryProvider, firstArray, jsonArray, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { t as descriptor } from "../../../lib/descriptor-DIAMITdX.js";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mem0/src/driver.ts
|
||||
function category(item) {
|
||||
const categories = jsonArray(item.categories).filter((value) => typeof value === "string");
|
||||
return jsonString(item.category) ?? categories[0] ?? "general";
|
||||
}
|
||||
function insight(value) {
|
||||
const item = jsonObject(value);
|
||||
const id = jsonString(item?.id);
|
||||
const content = jsonString(item?.memory) ?? jsonString(item?.text) ?? jsonString(item?.content);
|
||||
if (id === void 0 || content === void 0) return void 0;
|
||||
const score = jsonNumber(item?.score);
|
||||
const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt) ?? jsonString(item?.updated_at);
|
||||
const tags = jsonArray(item?.categories).filter((entry) => typeof entry === "string");
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
category: category(item),
|
||||
source: "external",
|
||||
...score === void 0 ? {} : { score },
|
||||
...createdAt === void 0 ? {} : { createdAt },
|
||||
...tags.length === 0 ? {} : { tags }
|
||||
};
|
||||
}
|
||||
var Mem0Provider = class extends HttpMemoryProvider {
|
||||
id = "mem0";
|
||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
||||
constructor(memorySpaces, options = {}) {
|
||||
super(memorySpaces, {
|
||||
label: descriptor.label,
|
||||
...options
|
||||
});
|
||||
}
|
||||
async discover(connection, signal) {
|
||||
const mode = String(connection.mode ?? "platform");
|
||||
const payload = await this.requestConnection(connection, mode === "self-hosted" ? "/entities" : "/v1/entities", {
|
||||
headers: this.headers(connection, mode),
|
||||
signal
|
||||
});
|
||||
return firstArray(payload, "entities", "results").flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const id = jsonString(item?.id);
|
||||
const type = jsonString(item?.type);
|
||||
if (id === void 0 || type !== "user" && type !== "agent") return [];
|
||||
const metadata = jsonObject(item?.metadata);
|
||||
const count = jsonNumber(item?.total_memories);
|
||||
return [{
|
||||
externalId: `${type}:${id}`,
|
||||
name: jsonString(item?.name) ?? jsonString(metadata?.name) ?? id,
|
||||
description: jsonString(metadata?.description) ?? `${type === "user" ? "User" : "Agent"} memory${count === void 0 ? "" : ` · ${count} memories`}`,
|
||||
connection: type === "user" ? {
|
||||
userId: id,
|
||||
agentId: "*",
|
||||
rerank: false
|
||||
} : {
|
||||
userId: "*",
|
||||
agentId: id,
|
||||
rerank: false
|
||||
}
|
||||
}];
|
||||
});
|
||||
}
|
||||
async status(body, signal) {
|
||||
try {
|
||||
await this.list(body, { limit: 1 }, signal);
|
||||
return { healthy: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
async search(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const mode = String(connection.mode ?? "platform");
|
||||
const filters = this.filters(connection);
|
||||
const payload = await this.request(body, mode === "self-hosted" ? "/search" : "/v3/memories/search/", {
|
||||
headers: this.headers(connection, mode),
|
||||
json: {
|
||||
query: request.query,
|
||||
filters,
|
||||
top_k: request.limit ?? 10,
|
||||
...mode === "platform" && connection.rerank === true ? { rerank: true } : {}
|
||||
},
|
||||
signal
|
||||
});
|
||||
return { results: firstArray(payload, "results", "memories").map(insight).filter((item) => item !== void 0) };
|
||||
}
|
||||
async list(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const mode = String(connection.mode ?? "platform");
|
||||
const limit = Math.min(Math.max(request.limit ?? 200, 1), 200);
|
||||
const payload = mode === "self-hosted" ? await this.request(body, `/memories?${new URLSearchParams({
|
||||
...this.filters(connection),
|
||||
limit: String(limit)
|
||||
})}`, {
|
||||
headers: this.headers(connection, mode),
|
||||
signal
|
||||
}) : await this.request(body, `/v3/memories/?page=1&page_size=${limit}`, {
|
||||
headers: this.headers(connection, mode),
|
||||
json: {
|
||||
filters: this.filters(connection),
|
||||
...request.category === void 0 ? {} : { categories: [request.category] }
|
||||
},
|
||||
signal
|
||||
});
|
||||
return firstArray(payload, "results", "memories").map(insight).filter((item) => item !== void 0);
|
||||
}
|
||||
async remember(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const mode = String(connection.mode ?? "platform");
|
||||
const payload = await this.request(body, mode === "self-hosted" ? "/memories" : "/v3/memories/add/", {
|
||||
headers: this.headers(connection, mode),
|
||||
json: {
|
||||
messages: [{
|
||||
role: "user",
|
||||
content: request.content
|
||||
}],
|
||||
user_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
|
||||
agent_id: String(connection.agentId) === "*" ? "dsh" : String(connection.agentId),
|
||||
...mode === "self-hosted" ? { infer: false } : {},
|
||||
metadata: {
|
||||
source: "dsh-brain-mnemon",
|
||||
...request.category === void 0 ? {} : { category: request.category },
|
||||
...request.importance === void 0 ? {} : { importance: request.importance },
|
||||
...request.tags === void 0 ? {} : { tags: request.tags },
|
||||
...request.entities === void 0 ? {} : { entities: request.entities }
|
||||
}
|
||||
},
|
||||
signal
|
||||
});
|
||||
const result = jsonObject(payload) ?? {};
|
||||
return {
|
||||
action: mode === "platform" ? "queued" : "stored",
|
||||
provider: this.id,
|
||||
summary: mode === "platform" ? "Mem0 queued the memory for extraction." : "Mem0 stored the explicit memory.",
|
||||
...jsonString(result.event_id) === void 0 ? {} : { eventId: jsonString(result.event_id) },
|
||||
...jsonString(result.status) === void 0 ? {} : { status: jsonString(result.status) }
|
||||
};
|
||||
}
|
||||
async forget(body, id, signal) {
|
||||
const connection = this.connection(body);
|
||||
const mode = String(connection.mode ?? "platform");
|
||||
const path = mode === "self-hosted" ? `/memories/${encodeURIComponent(id)}` : `/v1/memories/${encodeURIComponent(id)}`;
|
||||
await this.request(body, path, {
|
||||
method: "DELETE",
|
||||
headers: this.headers(connection, mode),
|
||||
signal
|
||||
});
|
||||
return {
|
||||
action: "deleted",
|
||||
provider: this.id,
|
||||
id
|
||||
};
|
||||
}
|
||||
filters(connection) {
|
||||
const userId = String(connection.userId);
|
||||
const agentId = String(connection.agentId ?? "");
|
||||
return {
|
||||
...userId === "*" ? {} : { user_id: userId },
|
||||
...agentId === "" || agentId === "*" ? {} : { agent_id: agentId }
|
||||
};
|
||||
}
|
||||
headers(connection, mode) {
|
||||
const apiKey = String(connection.apiKey ?? "").replace(/^(?:Token|Bearer)\s+/iu, "");
|
||||
if (apiKey === "") return {};
|
||||
return mode === "self-hosted" ? { "X-API-Key": apiKey } : { Authorization: `Token ${apiKey}` };
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mem0/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-mem0",
|
||||
version: "0.5.6",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "normalized-relevance"
|
||||
},
|
||||
create: (context) => new Mem0Provider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { Mem0Provider, src_default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-mem0",
|
||||
"version": "0.5.6",
|
||||
"description": "Mem0 Provider child for the Memory Spaces Source.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-mem0"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-mem0#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mnemon-native/src/descriptor.ts
|
||||
const descriptor = {
|
||||
"id": "mnemon-native",
|
||||
"label": "Mnemon Native",
|
||||
"icon": {
|
||||
"kind": "brand",
|
||||
"value": "mnemon"
|
||||
},
|
||||
"kind": "local",
|
||||
"workspaceBinding": "automatic",
|
||||
"summary": "Official local-first memory with exact writes, typed graph relations, and soft deletion.",
|
||||
"summaryI18nKey": "overview.providerSummary.mnemon-native",
|
||||
"origin": "native",
|
||||
"capabilities": {
|
||||
"search": true,
|
||||
"browse": true,
|
||||
"graph": true,
|
||||
"entities": true,
|
||||
"related": true,
|
||||
"remember": true,
|
||||
"link": true,
|
||||
"forget": true,
|
||||
"writeMode": "exact",
|
||||
"deletionMode": "soft"
|
||||
},
|
||||
"fields": []
|
||||
};
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight, y as EdgeType } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, _ as MemorySpaceNativeRunner, f as MemoryProviderAdapter, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
declare function parseMemoryGraph(html: string, now?: Date): MemoryGraphSnapshot;
|
||||
declare class MnemonNativeProvider implements MemoryProviderAdapter {
|
||||
private readonly runner;
|
||||
private readonly config;
|
||||
readonly id = "mnemon-native";
|
||||
readonly scoreSemantics: ProviderScoreSemantics;
|
||||
constructor(runner: MemorySpaceNativeRunner, config?: {
|
||||
defaultRecallLimit: number;
|
||||
});
|
||||
list(body: MemoryBody, _request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
||||
private parseStats;
|
||||
graph(body: MemoryBody, signal?: AbortSignal): Promise<MemoryGraphSnapshot>;
|
||||
private allNativeInsights;
|
||||
metadataSample(body: MemoryBody, limit: number, signal?: AbortSignal): Promise<Insight[]>;
|
||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
rememberMany(body: MemoryBody, requests: readonly RememberRequest[], signal?: AbortSignal): Promise<MemoryJsonValue[]>;
|
||||
private importExact;
|
||||
get(body: MemoryBody, id: string, signal?: AbortSignal): Promise<Insight | undefined>;
|
||||
related(body: MemoryBody, id: string, depth: number, edge?: EdgeType, signal?: AbortSignal): Promise<Insight[]>;
|
||||
link(body: MemoryBody, sourceId: string, targetId: string, type: EdgeType, weight: number, reason?: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { MnemonNativeProvider, _default as default, definition, descriptor, parseMemoryGraph };
|
||||
|
|
@ -0,0 +1,496 @@
|
|||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
import { join } from "node:path";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mnemon-native/src/driver.ts
|
||||
const STORE_DUMP_MAX_OUTPUT_BYTES = 134217728;
|
||||
function record(value) {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
||||
}
|
||||
function text(value) {
|
||||
return typeof value === "string" ? value : void 0;
|
||||
}
|
||||
function number(value) {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
||||
}
|
||||
function stringArray(value) {
|
||||
if (!Array.isArray(value)) return void 0;
|
||||
return value.filter((entry) => typeof entry === "string");
|
||||
}
|
||||
function normalizeInsight(value) {
|
||||
const item = record(value);
|
||||
if (item === void 0) return void 0;
|
||||
const core = record(item.insight) ?? item;
|
||||
const id = text(core.id);
|
||||
const content = text(core.content);
|
||||
if (id === void 0 || content === void 0) return void 0;
|
||||
const insight = {
|
||||
id,
|
||||
content
|
||||
};
|
||||
const optionalText = {
|
||||
category: text(core.category),
|
||||
source: text(core.source),
|
||||
confidence: text(item.confidence),
|
||||
intent: text(item.intent),
|
||||
matchedVia: text(item.matched_via ?? item.via ?? item.via_edge_type),
|
||||
createdAt: text(core.created_at),
|
||||
edgeType: text(item.via_edge_type)
|
||||
};
|
||||
for (const [key, value] of Object.entries(optionalText)) if (value !== void 0) Object.assign(insight, { [key]: value });
|
||||
const optionalNumbers = {
|
||||
importance: number(core.importance),
|
||||
score: number(item.score),
|
||||
depth: number(item.depth)
|
||||
};
|
||||
for (const [key, value] of Object.entries(optionalNumbers)) if (value !== void 0) Object.assign(insight, { [key]: value });
|
||||
const tags = stringArray(core.tags);
|
||||
const entities = stringArray(core.entities);
|
||||
if (tags !== void 0) insight.tags = tags;
|
||||
if (entities !== void 0) insight.entities = entities;
|
||||
return insight;
|
||||
}
|
||||
const JS_STRING = "\"(?:\\\\.|[^\"\\\\])*\"";
|
||||
const VIZ_NODE_PATTERN = new RegExp(`\\{id:(${JS_STRING}),label:(${JS_STRING}),title:(${JS_STRING}),color:(${JS_STRING}),font:\\{color:"white"\\}\\}`, "g");
|
||||
const VIZ_EDGE_PATTERN = new RegExp(`\\{from:(${JS_STRING}),to:(${JS_STRING}),label:(${JS_STRING}),color:\\{color:(${JS_STRING})\\},arrows:"to"`, "g");
|
||||
const EDGE_COLORS = {
|
||||
"#aaaaaa": "temporal",
|
||||
"#3498db": "semantic",
|
||||
"#e74c3c": "causal",
|
||||
"#2ecc71": "entity"
|
||||
};
|
||||
function decodeJsString(value) {
|
||||
const decoded = JSON.parse(value);
|
||||
if (typeof decoded !== "string") throw new Error("Mnemon viz contained an invalid string");
|
||||
return decoded;
|
||||
}
|
||||
function parseMemoryGraph(html, now = /* @__PURE__ */ new Date()) {
|
||||
const nodes = [];
|
||||
const edges = [];
|
||||
for (const match of html.matchAll(VIZ_NODE_PATTERN)) {
|
||||
const id = decodeJsString(match[1]);
|
||||
const label = decodeJsString(match[2]);
|
||||
const content = decodeJsString(match[3]).replaceAll("\\n", "\n");
|
||||
const color = decodeJsString(match[4]);
|
||||
const category = /\[([a-z_]+)\]/i.exec(label)?.[1] ?? "general";
|
||||
nodes.push({
|
||||
id,
|
||||
content,
|
||||
category,
|
||||
color
|
||||
});
|
||||
}
|
||||
for (const match of html.matchAll(VIZ_EDGE_PATTERN)) {
|
||||
const color = decodeJsString(match[4]);
|
||||
const type = EDGE_COLORS[color.toLowerCase()];
|
||||
edges.push({
|
||||
sourceId: decodeJsString(match[1]),
|
||||
targetId: decodeJsString(match[2]),
|
||||
label: decodeJsString(match[3]),
|
||||
color,
|
||||
...type === void 0 ? {} : { type }
|
||||
});
|
||||
}
|
||||
if (!html.includes("var nodes = new vis.DataSet([")) throw new Error("Mnemon viz returned an unexpected HTML payload");
|
||||
return {
|
||||
nodes,
|
||||
edges,
|
||||
generatedAt: now.toISOString()
|
||||
};
|
||||
}
|
||||
function commaList(values, label, limit) {
|
||||
if (values === void 0) return void 0;
|
||||
const normalized = values.map((value) => value.trim()).filter((value) => value !== "");
|
||||
if (normalized.length > limit) throw new Error(`${label} accepts at most ${limit} values`);
|
||||
if (normalized.some((value) => value.includes(","))) throw new Error(`${label} values cannot contain commas`);
|
||||
return normalized.length === 0 ? void 0 : normalized.join(",");
|
||||
}
|
||||
var MnemonNativeProvider = class {
|
||||
runner;
|
||||
config;
|
||||
id = "mnemon-native";
|
||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
||||
constructor(runner, config = { defaultRecallLimit: 10 }) {
|
||||
this.runner = runner;
|
||||
this.config = config;
|
||||
}
|
||||
list(body, _request, signal) {
|
||||
return this.allNativeInsights(body, signal, true);
|
||||
}
|
||||
async status(body, signal) {
|
||||
try {
|
||||
const status = record(await this.runner.runJson(["status"], {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
}));
|
||||
if (status === void 0) throw new Error("mnemon status returned an unexpected payload");
|
||||
return {
|
||||
healthy: true,
|
||||
stats: this.parseStats(status)
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
parseStats(status) {
|
||||
const byCategoryRecord = record(status.by_category) ?? {};
|
||||
const byCategory = {};
|
||||
for (const [category, count] of Object.entries(byCategoryRecord)) if (typeof count === "number") byCategory[category] = count;
|
||||
const topEntities = Array.isArray(status.top_entities) ? status.top_entities.flatMap((entry) => {
|
||||
const entity = record(entry);
|
||||
const name = text(entity?.entity);
|
||||
const count = number(entity?.count);
|
||||
return name === void 0 || count === void 0 ? [] : [{
|
||||
entity: name,
|
||||
count
|
||||
}];
|
||||
}) : [];
|
||||
return {
|
||||
totalInsights: number(status.total_insights) ?? 0,
|
||||
deletedInsights: number(status.deleted_insights) ?? 0,
|
||||
edgeCount: number(status.edge_count) ?? 0,
|
||||
oplogCount: number(status.oplog_count) ?? 0,
|
||||
dbSizeBytes: number(status.db_size_bytes) ?? 0,
|
||||
byCategory,
|
||||
topEntities
|
||||
};
|
||||
}
|
||||
async graph(body, signal) {
|
||||
const [html, insights] = await Promise.all([this.runner.runText([
|
||||
"viz",
|
||||
"--format",
|
||||
"html",
|
||||
"--output",
|
||||
"-"
|
||||
], {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id,
|
||||
maxOutputBytes: STORE_DUMP_MAX_OUTPUT_BYTES
|
||||
}), this.allNativeInsights(body, signal, true)]);
|
||||
const snapshot = parseMemoryGraph(html);
|
||||
const metadata = new Map(insights.map((insight) => [insight.id, insight]));
|
||||
return {
|
||||
...snapshot,
|
||||
nodes: snapshot.nodes.map((node) => {
|
||||
const insight = metadata.get(node.id);
|
||||
return insight === void 0 ? node : {
|
||||
...node,
|
||||
...insight,
|
||||
id: node.id,
|
||||
content: node.content,
|
||||
color: node.color
|
||||
};
|
||||
})
|
||||
};
|
||||
}
|
||||
async allNativeInsights(body, signal, readonly = false) {
|
||||
const payload = await this.runner.runJson([
|
||||
...readonly ? ["--readonly"] : [],
|
||||
"recall",
|
||||
"",
|
||||
"--basic",
|
||||
"--limit",
|
||||
"100000"
|
||||
], {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id,
|
||||
maxOutputBytes: STORE_DUMP_MAX_OUTPUT_BYTES
|
||||
});
|
||||
return (Array.isArray(payload) ? payload : Array.isArray(record(payload)?.results) ? record(payload).results : []).map(normalizeInsight).filter((entry) => entry !== void 0);
|
||||
}
|
||||
async metadataSample(body, limit, signal) {
|
||||
const payload = await this.runner.runJson([
|
||||
"--readonly",
|
||||
"recall",
|
||||
"",
|
||||
"--basic",
|
||||
"--limit",
|
||||
String(limit)
|
||||
], {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
});
|
||||
const wrapper = record(payload);
|
||||
return (Array.isArray(payload) ? payload : Array.isArray(wrapper?.results) ? wrapper.results : []).map(normalizeInsight).filter((entry) => entry !== void 0);
|
||||
}
|
||||
async search(body, request, signal) {
|
||||
const mode = request.mode ?? "smart";
|
||||
const semantic = mode === "smart";
|
||||
const limit = request.limit ?? this.config.defaultRecallLimit;
|
||||
const candidateLimit = semantic ? Math.max(limit, Math.min(50, Math.max(20, limit * 4))) : limit;
|
||||
const readonly = request.inspect === true ? ["--readonly"] : [];
|
||||
const args = mode === "keyword" ? [
|
||||
...readonly,
|
||||
"search",
|
||||
request.query,
|
||||
"--limit",
|
||||
String(candidateLimit)
|
||||
] : [
|
||||
...readonly,
|
||||
"recall",
|
||||
request.query,
|
||||
"--limit",
|
||||
String(candidateLimit)
|
||||
];
|
||||
if (semantic) args.push("--verbose");
|
||||
if (mode === "basic") args.push("--basic");
|
||||
if (mode !== "keyword") {
|
||||
if (request.category !== void 0) args.push("--cat", request.category);
|
||||
if (request.source !== void 0) args.push("--source", request.source);
|
||||
if (request.intent !== void 0) args.push("--intent", request.intent);
|
||||
}
|
||||
const options = {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
};
|
||||
let payload;
|
||||
try {
|
||||
payload = await this.runner.runJson(args, options);
|
||||
} catch (error) {
|
||||
if (!semantic || signal?.aborted || !(error instanceof Error)) throw error;
|
||||
const prefix = `mnemon ${args.join(" ")} exited `;
|
||||
const detail = error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message;
|
||||
if (!/^(?:[1-9]\d*:\s*)?(?:Error:\s*)?unknown flag: --verbose[ \t]*(?:\r?\n|$)/u.test(detail)) throw error;
|
||||
const legacyArgs = [...args];
|
||||
legacyArgs.splice(readonly.length + 4, 1);
|
||||
payload = await this.runner.runJson(legacyArgs, options);
|
||||
}
|
||||
const wrapper = record(payload);
|
||||
const candidates = (Array.isArray(payload) ? payload : Array.isArray(wrapper?.results) ? wrapper.results : []).flatMap((value) => {
|
||||
const insight = normalizeInsight(value);
|
||||
if (insight === void 0) return [];
|
||||
const item = record(value);
|
||||
return [{
|
||||
insight,
|
||||
similarity: number(record(item?.signals)?.similarity),
|
||||
superseded: item?.superseded === true
|
||||
}];
|
||||
});
|
||||
if (semantic && candidates.some((candidate) => candidate.similarity !== void 0 && candidate.similarity > 0)) {
|
||||
for (const candidate of candidates) {
|
||||
const { insight, similarity } = candidate;
|
||||
delete insight.confidence;
|
||||
if (similarity === void 0) {
|
||||
if (!candidate.superseded) delete insight.score;
|
||||
} else {
|
||||
const relevance = Math.min(1, Math.max(0, similarity));
|
||||
insight.score = candidate.superseded ? Math.min(relevance, insight.score ?? 0) : relevance;
|
||||
}
|
||||
}
|
||||
candidates.sort((left, right) => (right.insight.score ?? -1) - (left.insight.score ?? -1));
|
||||
}
|
||||
const hint = text(wrapper?.hint) ?? text(record(wrapper?.meta)?.hint);
|
||||
return {
|
||||
results: candidates.slice(0, limit).map((candidate) => candidate.insight),
|
||||
...hint === void 0 ? {} : { hint }
|
||||
};
|
||||
}
|
||||
async remember(body, request, signal) {
|
||||
const args = [
|
||||
"remember",
|
||||
request.content,
|
||||
"--cat",
|
||||
request.category ?? "general",
|
||||
"--imp",
|
||||
String(request.importance ?? 3),
|
||||
"--source",
|
||||
request.source ?? "user"
|
||||
];
|
||||
const tags = commaList(request.tags, "tags", 20);
|
||||
const entities = commaList(request.entities, "entities", 50);
|
||||
if (tags !== void 0) args.push("--tags", tags);
|
||||
if (entities !== void 0) args.push("--entities", entities);
|
||||
return this.runner.runJson(args, {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
});
|
||||
}
|
||||
async rememberMany(body, requests, signal) {
|
||||
if (requests.length === 0) return [];
|
||||
const existing = new Map((await this.allNativeInsights(body, signal, true)).map((entry) => [entry.content, entry]));
|
||||
const ordered = new Array(requests.length);
|
||||
const reused = /* @__PURE__ */ new Set();
|
||||
let pending = /* @__PURE__ */ new Map();
|
||||
const queue = (index) => {
|
||||
const request = requests[index];
|
||||
const group = pending.get(request.content);
|
||||
if (group === void 0) pending.set(request.content, {
|
||||
request,
|
||||
indexes: [index]
|
||||
});
|
||||
else group.indexes.push(index);
|
||||
};
|
||||
for (const [index, request] of requests.entries()) {
|
||||
const exact = existing.get(request.content);
|
||||
if (exact === void 0) queue(index);
|
||||
else {
|
||||
ordered[index] = {
|
||||
action: "skipped",
|
||||
id: exact.id,
|
||||
content: exact.content
|
||||
};
|
||||
reused.add(index);
|
||||
}
|
||||
}
|
||||
while (pending.size > 0) {
|
||||
const pruned = await this.importExact(body, [...pending.values()], ordered, signal);
|
||||
pending = /* @__PURE__ */ new Map();
|
||||
for (const index of reused) {
|
||||
const id = record(ordered[index])?.id;
|
||||
if (typeof id === "string" && pruned.has(id)) {
|
||||
reused.delete(index);
|
||||
queue(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
async importExact(body, batch, ordered, signal) {
|
||||
const temporary = mkdtempSync(join(tmpdir(), "dsh-brain-mnemon-runtime-archive-"));
|
||||
const draftPath = join(temporary, "memory-draft.json");
|
||||
try {
|
||||
writeFileSync(draftPath, JSON.stringify({
|
||||
schema_version: "1",
|
||||
source: "dsh-brain-mnemon-runtime-archive",
|
||||
insights: batch.map(({ request }) => ({
|
||||
content: request.content,
|
||||
category: request.category,
|
||||
importance: request.importance ?? 3,
|
||||
source: request.source,
|
||||
...request.tags === void 0 ? {} : { tags: request.tags },
|
||||
...request.entities === void 0 ? {} : { entities: request.entities }
|
||||
}))
|
||||
}), {
|
||||
encoding: "utf8",
|
||||
mode: 384
|
||||
});
|
||||
const summary = record(await this.runner.runJson([
|
||||
"import",
|
||||
draftPath,
|
||||
"--no-diff"
|
||||
], {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
}));
|
||||
const rows = Array.isArray(summary?.results) ? summary.results : void 0;
|
||||
const errors = number(summary?.errors);
|
||||
const imported = number(summary?.imported);
|
||||
const updated = number(summary?.updated);
|
||||
const skipped = number(summary?.skipped);
|
||||
const invalid = () => /* @__PURE__ */ new Error(`Mnemon runtime archive import returned an invalid or partial result for Memory Space ${body.id}`);
|
||||
if (errors !== 0 || imported === void 0 || updated === void 0 || skipped === void 0 || rows === void 0 || ![
|
||||
imported,
|
||||
updated,
|
||||
skipped
|
||||
].every((value) => Number.isInteger(value) && value >= 0) || imported !== batch.length || updated !== 0 || skipped !== 0 || rows.length !== batch.length) throw invalid();
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
for (const candidate of rows) {
|
||||
const row = record(candidate);
|
||||
const index = number(row?.index);
|
||||
const action = text(row?.action)?.trim().toLocaleLowerCase();
|
||||
if (index === void 0 || !Number.isInteger(index) || index < 0 || index >= batch.length || seen.has(index)) throw invalid();
|
||||
if (row?.content !== batch[index].request.content || action !== "added") throw invalid();
|
||||
seen.add(index);
|
||||
for (const [offset, originalIndex] of batch[index].indexes.entries()) ordered[originalIndex] = offset === 0 ? row : {
|
||||
...row,
|
||||
action: "skipped"
|
||||
};
|
||||
}
|
||||
return new Set(stringArray(summary?.auto_pruned_ids) ?? []);
|
||||
} finally {
|
||||
rmSync(temporary, {
|
||||
recursive: true,
|
||||
force: true
|
||||
});
|
||||
}
|
||||
}
|
||||
async get(body, id, signal) {
|
||||
try {
|
||||
return normalizeInsight(await this.runner.runJson([
|
||||
"--readonly",
|
||||
"show",
|
||||
id
|
||||
], {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
}));
|
||||
} catch (error) {
|
||||
if (error instanceof Error && /no rows in result set/u.test(error.message)) return void 0;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async related(body, id, depth, edge, signal) {
|
||||
const args = [
|
||||
"related",
|
||||
id,
|
||||
"--depth",
|
||||
String(depth)
|
||||
];
|
||||
if (edge !== void 0) args.push("--edge", edge);
|
||||
const payload = await this.runner.runJson(args, {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
});
|
||||
return Array.isArray(payload) ? payload.map(normalizeInsight).filter((entry) => entry !== void 0) : [];
|
||||
}
|
||||
async link(body, sourceId, targetId, type, weight, reason, signal) {
|
||||
const args = [
|
||||
"link",
|
||||
sourceId,
|
||||
targetId,
|
||||
"--type",
|
||||
type,
|
||||
"--weight",
|
||||
String(weight)
|
||||
];
|
||||
if (reason !== void 0) args.push("--meta", JSON.stringify({ reason }));
|
||||
return this.runner.runJson(args, {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
});
|
||||
}
|
||||
forget(body, id, signal) {
|
||||
return this.runner.runJson(["forget", id], {
|
||||
...signal === void 0 ? {} : { signal },
|
||||
store: body.id
|
||||
});
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-mnemon-native/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-mnemon-native",
|
||||
version: "0.5.12",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "normalized-relevance"
|
||||
},
|
||||
create(context) {
|
||||
if (context.nativeRunner === void 0) throw new Error("Mnemon Native requires the Memory Spaces nativeRunner capability");
|
||||
return new MnemonNativeProvider(context.nativeRunner, { defaultRecallLimit: context.config.defaultRecallLimit ?? 10 });
|
||||
}
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { MnemonNativeProvider, src_default as default, definition, descriptor, parseMemoryGraph };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-mnemon-native",
|
||||
"version": "0.5.12",
|
||||
"description": "Native Mnemon CLI Provider child for Memory Spaces.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-mnemon-native"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-mnemon-native#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as descriptor } from "../../../lib/descriptor-D_OcOjAK.js";
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, J as MemoryGraphSnapshot, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, ot as MemoryProviderConnection, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
interface OpenVikingProviderOptions {
|
||||
fetch?: typeof fetch;
|
||||
requestTimeoutMs?: number;
|
||||
}
|
||||
declare class OpenVikingProvider implements MemoryProviderAdapter {
|
||||
private readonly memorySpaces;
|
||||
readonly id: "openviking";
|
||||
readonly scoreSemantics: Readonly<{
|
||||
kind: "provider-native";
|
||||
}>;
|
||||
private readonly requestFetch;
|
||||
private readonly requestTimeoutMs;
|
||||
constructor(memorySpaces: MemorySpaceAuthority, options?: OpenVikingProviderOptions);
|
||||
discover(connection: MemoryProviderConnection, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
||||
graph(body: MemoryBody, signal?: AbortSignal): Promise<MemoryGraphSnapshot>;
|
||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
private readAll;
|
||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
private tag;
|
||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
private connection;
|
||||
private validateUserNamespace;
|
||||
private memoryRoot;
|
||||
private readContent;
|
||||
private request;
|
||||
private requestConnection;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { OpenVikingProvider, _default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,446 @@
|
|||
import { CATEGORIES } from "../../source-memory-spaces/lib/contracts.js";
|
||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import { bearerAuthHeader, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { t as descriptor } from "../../../lib/descriptor-D_OcOjAK.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-openviking/src/driver.ts
|
||||
function normalizeBearerHeader(apiKey) {
|
||||
if (typeof bearerAuthHeader === "function") return bearerAuthHeader(apiKey);
|
||||
if (typeof apiKey !== "string") return void 0;
|
||||
const stripped = apiKey.trim().replace(/^Bearer(?:\s+|$)/iu, "").trim();
|
||||
return stripped === "" ? void 0 : `Bearer ${stripped}`;
|
||||
}
|
||||
const CATEGORY_NAMES = new Set(CATEGORIES);
|
||||
function categoryOf(value) {
|
||||
const category = jsonString(value)?.trim().toLowerCase();
|
||||
return category !== void 0 && CATEGORY_NAMES.has(category) ? category : "general";
|
||||
}
|
||||
const MEMORY_FOLDERS = {
|
||||
preference: "preferences",
|
||||
insight: "experiences",
|
||||
decision: "experiences",
|
||||
context: "events",
|
||||
fact: "entities",
|
||||
general: "entities"
|
||||
};
|
||||
const SLUG_BYTES = 180;
|
||||
function memoryUri(root, category, content) {
|
||||
const folder = Object.hasOwn(MEMORY_FOLDERS, category) ? MEMORY_FOLDERS[category] : "entities";
|
||||
const firstLine = content.split("\n").find((line) => line.trim().length > 0) ?? "memory";
|
||||
const characters = Array.from(firstLine.replace(/^#+\s*/u, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/gu, "")).slice(0, 48);
|
||||
while (Buffer.byteLength(characters.join("").toLowerCase()) > SLUG_BYTES) characters.pop();
|
||||
const slug = characters.join("").toLowerCase() || "memory";
|
||||
return `${root}/${folder}/${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/gu, "").slice(0, 14)}-${slug}_${category}-${randomUUID()}.md`;
|
||||
}
|
||||
function safeUser(user) {
|
||||
return /^[a-zA-Z0-9_.@-]+$/u.test(user) && user !== "." && user !== ".." && (user.match(/@/gu)?.length ?? 0) <= 1;
|
||||
}
|
||||
function discoveryUser(connection) {
|
||||
const user = String(connection.discoveryUser ?? "").trim();
|
||||
if (user === "") return void 0;
|
||||
if (!safeUser(user) || !safeUser(String(connection.account ?? "").trim())) throw new Error("OpenViking user-key discovery requires an explicit account and a safe discovery user");
|
||||
if (normalizeBearerHeader(connection.apiKey) === void 0) throw new Error("OpenViking user-key discovery requires a user API key");
|
||||
return user;
|
||||
}
|
||||
function isMemoryFile(uri, root) {
|
||||
if (!uri.startsWith(`${root}/`) || !uri.endsWith(".md") || /[%?#\\\u0000-\u001f\u007f]/u.test(uri)) return false;
|
||||
return uri.slice(root.length + 1).split("/").every((part) => part !== "" && !part.startsWith(".") && part.trim() === part);
|
||||
}
|
||||
function queueFailed(value) {
|
||||
return Object.values(jsonObject(value) ?? {}).some((entry) => {
|
||||
const queue = jsonObject(entry);
|
||||
return (jsonNumber(queue?.error_count) ?? 0) > 0 || Array.isArray(queue?.errors) && queue.errors.length > 0;
|
||||
});
|
||||
}
|
||||
const FOLDER_CATEGORIES = {
|
||||
preferences: "preference",
|
||||
experiences: "insight",
|
||||
events: "context",
|
||||
entities: "fact"
|
||||
};
|
||||
function categoryFromUri(uri, reported) {
|
||||
const named = /_([a-z]+)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.md$/u.exec(uri)?.[1];
|
||||
if (named !== void 0 && CATEGORY_NAMES.has(named)) return named;
|
||||
const stated = jsonString(reported);
|
||||
if (stated !== void 0 && CATEGORY_NAMES.has(stated)) return stated;
|
||||
const marker = "/memories/";
|
||||
const folder = (uri.includes(marker) ? uri.slice(uri.indexOf(marker) + 10) : "").split("/")[0] ?? "";
|
||||
return Object.hasOwn(FOLDER_CATEGORIES, folder) ? FOLDER_CATEGORIES[folder] : "general";
|
||||
}
|
||||
function refused(error) {
|
||||
const status = error?.status;
|
||||
return typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 409;
|
||||
}
|
||||
var OpenVikingProvider = class {
|
||||
memorySpaces;
|
||||
id = "openviking";
|
||||
scoreSemantics = Object.freeze({ kind: "provider-native" });
|
||||
requestFetch;
|
||||
requestTimeoutMs;
|
||||
constructor(memorySpaces, options = {}) {
|
||||
this.memorySpaces = memorySpaces;
|
||||
this.requestFetch = options.fetch ?? globalThis.fetch;
|
||||
this.requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
|
||||
}
|
||||
async discover(connection, signal) {
|
||||
signal?.throwIfAborted();
|
||||
let account = String(connection.account ?? "").trim();
|
||||
const selectedUser = discoveryUser(connection);
|
||||
if (selectedUser !== void 0) {
|
||||
const targetUri = await this.validateUserNamespace(connection, selectedUser, signal);
|
||||
return [{
|
||||
externalId: `${account}:${selectedUser}`,
|
||||
name: selectedUser,
|
||||
description: `OpenViking memory namespace for ${selectedUser}`,
|
||||
connection: {
|
||||
targetUri,
|
||||
user: selectedUser,
|
||||
actorPeerId: "dsh"
|
||||
}
|
||||
}];
|
||||
}
|
||||
if (account === "") {
|
||||
const accounts = await this.requestConnection(connection, "/api/v1/admin/accounts", {}, { signal });
|
||||
const ids = (Array.isArray(accounts) ? accounts : []).flatMap((value) => {
|
||||
const id = jsonString(jsonObject(value)?.account_id) ?? jsonString(jsonObject(value)?.id);
|
||||
return id === void 0 ? [] : [id];
|
||||
});
|
||||
if (ids.length > 1) throw new Error("OpenViking exposes multiple accounts; configure the account to select one discovery scope");
|
||||
account = ids[0] ?? "default";
|
||||
}
|
||||
const users = await this.requestConnection({
|
||||
...connection,
|
||||
account
|
||||
}, `/api/v1/admin/accounts/${encodeURIComponent(account)}/users?limit=100`, {}, { signal });
|
||||
return (Array.isArray(users) ? users : []).flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const user = jsonString(item?.user_id) ?? jsonString(item?.id) ?? jsonString(item?.name);
|
||||
if (user === void 0 || !safeUser(user)) return [];
|
||||
return [{
|
||||
externalId: `${account}:${user}`,
|
||||
name: jsonString(item?.display_name) ?? jsonString(item?.name) ?? user,
|
||||
description: jsonString(item?.description) ?? jsonString(item?.role) ?? `OpenViking memory namespace for ${user}`,
|
||||
connection: {
|
||||
targetUri: `viking://user/${user}/memories`,
|
||||
user,
|
||||
actorPeerId: "dsh"
|
||||
}
|
||||
}];
|
||||
});
|
||||
}
|
||||
async status(body, signal) {
|
||||
try {
|
||||
const connection = this.connection(body);
|
||||
const selectedUser = discoveryUser(connection);
|
||||
if (selectedUser === void 0) await this.request(body, "/health", {}, {
|
||||
signal,
|
||||
timeoutMs: 5e3
|
||||
});
|
||||
else {
|
||||
await this.memoryRoot(body, signal);
|
||||
await this.validateUserNamespace(connection, selectedUser, signal);
|
||||
}
|
||||
return { healthy: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
async search(body, request, signal) {
|
||||
const keyword = request.mode === "keyword";
|
||||
signal?.throwIfAborted();
|
||||
if (keyword && request.query.trim() === "") return { results: [] };
|
||||
const limit = keyword ? Math.min(50, Math.max(1, Math.floor(jsonNumber(request.limit) ?? 10))) : request.limit;
|
||||
const memoryRoot = await this.memoryRoot(body, signal);
|
||||
const result = await this.request(body, keyword ? "/api/v1/search/grep" : "/api/v1/search/find", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(keyword ? {
|
||||
uri: memoryRoot,
|
||||
pattern: request.query.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"),
|
||||
case_insensitive: true,
|
||||
node_limit: limit
|
||||
} : {
|
||||
query: request.query,
|
||||
target_uri: memoryRoot,
|
||||
context_type: ["memory"],
|
||||
limit: request.limit
|
||||
})
|
||||
}, { signal });
|
||||
const root = jsonObject(result);
|
||||
if (keyword && !Array.isArray(root?.matches)) throw new Error("OpenViking keyword search did not return matches");
|
||||
const values = keyword ? root?.matches : root?.memories;
|
||||
const entries = Array.isArray(values) ? values : [];
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
const matches = entries.flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const uri = jsonString(item?.uri);
|
||||
if (uri === void 0 || !isMemoryFile(uri, memoryRoot)) return [];
|
||||
if (keyword && seen.has(uri)) return [];
|
||||
seen.add(uri);
|
||||
const score = keyword ? void 0 : jsonNumber(item?.score);
|
||||
return [{
|
||||
id: uri,
|
||||
externalUri: uri,
|
||||
content: jsonString(item?.overview) ?? jsonString(item?.abstract) ?? uri,
|
||||
category: categoryFromUri(uri, item?.category),
|
||||
source: "external",
|
||||
...score === void 0 ? {} : { score }
|
||||
}];
|
||||
}).slice(0, limit);
|
||||
const { read, skipped } = await this.readAll(body, matches, signal);
|
||||
return {
|
||||
results: read,
|
||||
...skipped === 0 ? {} : { hint: `${skipped} OpenViking ${skipped === 1 ? "result" : "results"} could not be read and ${skipped === 1 ? "was" : "were"} left out; the server can list a file it no longer holds.` }
|
||||
};
|
||||
}
|
||||
async graph(body, signal) {
|
||||
return {
|
||||
nodes: (await this.list(body, { limit: 200 }, signal)).map((item) => ({
|
||||
...item,
|
||||
color: "#5568d9"
|
||||
})),
|
||||
edges: [],
|
||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
||||
};
|
||||
}
|
||||
async list(body, request, signal) {
|
||||
const memoryRoot = await this.memoryRoot(body, signal);
|
||||
const query = new URLSearchParams({
|
||||
uri: memoryRoot,
|
||||
recursive: "true",
|
||||
output: "original"
|
||||
});
|
||||
const result = await this.request(body, `/api/v1/fs/ls?${query}`, {}, { signal });
|
||||
const entries = Array.isArray(result) ? result : [];
|
||||
const limit = Math.min(Math.max(request.limit ?? 200, 1), 1e3);
|
||||
const files = entries.flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const uri = jsonString(item?.uri);
|
||||
return item === void 0 || uri === void 0 || item.isDir === true || !isMemoryFile(uri, memoryRoot) ? [] : [{
|
||||
item,
|
||||
uri
|
||||
}];
|
||||
}).slice(0, limit);
|
||||
const { read } = await this.readAll(body, files.map(({ item, uri }) => ({
|
||||
id: uri,
|
||||
item
|
||||
})), signal);
|
||||
return read.map(({ item, id, content }) => {
|
||||
const createdAt = jsonString(item.modTime);
|
||||
return {
|
||||
id,
|
||||
externalUri: id,
|
||||
content,
|
||||
category: categoryFromUri(id),
|
||||
source: "external",
|
||||
...createdAt === void 0 ? {} : { createdAt }
|
||||
};
|
||||
});
|
||||
}
|
||||
async readAll(body, items, signal) {
|
||||
const settled = await Promise.allSettled(items.map(async (item) => ({
|
||||
...item,
|
||||
content: await this.readContent(body, item.id, signal)
|
||||
})));
|
||||
signal?.throwIfAborted();
|
||||
const read = settled.flatMap((outcome) => outcome.status === "fulfilled" ? [outcome.value] : []);
|
||||
const failed = settled.find((outcome) => outcome.status === "rejected");
|
||||
if (read.length === 0 && failed !== void 0) throw failed.reason;
|
||||
return {
|
||||
read,
|
||||
skipped: settled.length - read.length
|
||||
};
|
||||
}
|
||||
async remember(body, request, signal) {
|
||||
const root = await this.memoryRoot(body, signal);
|
||||
const category = categoryOf(request.category);
|
||||
const uri = memoryUri(root, category, request.content);
|
||||
const tags = ["source=mnemon", `category=${category}`];
|
||||
const importance = jsonNumber(request.importance);
|
||||
if (importance !== void 0) tags.push(`importance=${importance}`);
|
||||
const writtenBytes = Buffer.byteLength(request.content, "utf8");
|
||||
let written;
|
||||
try {
|
||||
written = jsonObject(await this.request(body, "/api/v1/content/write", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
uri,
|
||||
content: request.content,
|
||||
mode: "create",
|
||||
wait: true
|
||||
})
|
||||
}, { signal }));
|
||||
} catch (error) {
|
||||
if (refused(error)) throw new Error(`OpenViking refused the write at ${uri}; nothing was stored. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
throw new Error(`OpenViking write was not verified at ${uri}; remote content may remain. Inspect this URI before retrying. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
}
|
||||
try {
|
||||
if (written?.uri !== uri || written.content_updated !== true || (jsonNumber(written.written_bytes) ?? -1) < writtenBytes || written.mode !== "create" || written.context_type !== "memory" || written.vector_status !== "complete" || !["complete", "skipped"].includes(String(written.semantic_status)) || queueFailed(written.queue_status)) throw new Error("content API did not confirm this exact memory and completed indexing");
|
||||
if (await this.readContent(body, uri, signal) !== request.content) throw new Error("stored content does not match the requested text");
|
||||
signal?.throwIfAborted();
|
||||
} catch (error) {
|
||||
throw new Error(`OpenViking write was not verified at ${uri}; remote content may remain. Inspect this URI before retrying. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
||||
}
|
||||
return {
|
||||
action: "stored",
|
||||
provider: "openviking",
|
||||
id: uri,
|
||||
uri,
|
||||
externalUri: uri,
|
||||
summary: `OpenViking stored the memory at ${uri} (category ${category}).`,
|
||||
writtenBytes,
|
||||
vectorStatus: "complete",
|
||||
tagsApplied: await this.tag(body, uri, tags, signal)
|
||||
};
|
||||
}
|
||||
async tag(body, uri, tags, signal) {
|
||||
try {
|
||||
return jsonObject(await this.request(body, "/api/v1/content/set_tags", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
uri,
|
||||
tags,
|
||||
mode: "replace"
|
||||
})
|
||||
}, {
|
||||
signal,
|
||||
timeoutMs: Math.min(this.requestTimeoutMs, 5e3)
|
||||
}))?.tags_updated === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
async forget(body, id, signal) {
|
||||
const root = await this.memoryRoot(body, signal);
|
||||
const uri = id.trim();
|
||||
if (!isMemoryFile(uri, root)) throw new Error("OpenViking forget requires an exact non-generated .md memory URI inside this Memory Space");
|
||||
const query = new URLSearchParams({
|
||||
uri,
|
||||
recursive: "false"
|
||||
});
|
||||
const result = jsonObject(await this.request(body, `/api/v1/fs?${query}`, { method: "DELETE" }, { signal })) ?? {};
|
||||
if (result.uri !== uri) throw new Error("OpenViking did not confirm deletion of the requested memory URI");
|
||||
return {
|
||||
action: "deleted",
|
||||
provider: this.id,
|
||||
id: uri,
|
||||
uri,
|
||||
...jsonNumber(result.estimated_deleted_count) === void 0 ? {} : { estimatedDeletedCount: jsonNumber(result.estimated_deleted_count) }
|
||||
};
|
||||
}
|
||||
connection(body) {
|
||||
if ((body.provider.typeId ?? body.provider.id) !== this.id) throw new Error(`OpenViking cannot serve provider ${body.provider.id}`);
|
||||
const connection = this.memorySpaces.providerConnection(body.id, body.provider.id);
|
||||
return {
|
||||
endpoint: String(connection.endpoint ?? ""),
|
||||
targetUri: String(connection.targetUri ?? ""),
|
||||
apiKey: String(connection.apiKey ?? ""),
|
||||
account: String(connection.account ?? ""),
|
||||
user: String(connection.user ?? ""),
|
||||
actorPeerId: String(connection.actorPeerId ?? ""),
|
||||
discoveryUser: String(connection.discoveryUser ?? "")
|
||||
};
|
||||
}
|
||||
async validateUserNamespace(connection, user, signal) {
|
||||
const root = `viking://user/${user}/memories`;
|
||||
const query = new URLSearchParams({
|
||||
uri: root,
|
||||
recursive: "false",
|
||||
output: "original"
|
||||
});
|
||||
const result = await this.requestConnection(connection, `/api/v1/fs/ls?${query}`, {}, { signal });
|
||||
if (!Array.isArray(result) || result.some((item) => !jsonString(jsonObject(item)?.uri)?.startsWith(`${root}/`))) throw new Error("OpenViking could not validate the selected memory namespace");
|
||||
return root;
|
||||
}
|
||||
async memoryRoot(body, signal) {
|
||||
signal?.throwIfAborted();
|
||||
const connection = this.connection(body);
|
||||
const root = connection.targetUri.replace(/\/+$/u, "");
|
||||
const match = /^viking:\/\/user(?:\/([^/]+))?\/memories$/u.exec(root);
|
||||
if (match === null || match[1] !== void 0 && !safeUser(match[1])) throw new Error("OpenViking memory URI must be a safe viking://user/<user>/memories root");
|
||||
const selectedUser = discoveryUser(connection);
|
||||
if (selectedUser !== void 0) {
|
||||
if (match[1] !== void 0 && match[1] !== selectedUser || connection.user?.trim() && connection.user.trim() !== selectedUser) throw new Error("OpenViking memory owner must match the configured discovery user");
|
||||
return `viking://user/${selectedUser}/memories`;
|
||||
}
|
||||
if (match[1] !== void 0) return root;
|
||||
const user = connection.user?.trim() || jsonString(jsonObject(await this.request(body, "/api/v1/system/status", {}, { signal }))?.user) || "";
|
||||
if (!safeUser(user)) throw new Error("OpenViking could not resolve the memory owner; configure an explicit user memory URI");
|
||||
return `viking://user/${user}/memories`;
|
||||
}
|
||||
async readContent(body, uri, signal) {
|
||||
const result = await this.request(body, `/api/v1/content/read?${new URLSearchParams({ uri })}`, {}, { signal });
|
||||
if (typeof result !== "string") throw new Error("OpenViking content read did not return text");
|
||||
return result;
|
||||
}
|
||||
async request(body, path, init = {}, options = {}) {
|
||||
const connection = this.connection(body);
|
||||
return this.requestConnection(connection, path, init, options);
|
||||
}
|
||||
async requestConnection(connection, path, init = {}, options = {}) {
|
||||
options.signal?.throwIfAborted();
|
||||
const keyBound = discoveryUser(connection) !== void 0;
|
||||
const controller = new AbortController();
|
||||
const relay = () => controller.abort(options.signal?.reason);
|
||||
options.signal?.addEventListener("abort", relay, { once: true });
|
||||
const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("OpenViking request timed out")), options.timeoutMs ?? this.requestTimeoutMs);
|
||||
try {
|
||||
const auth = normalizeBearerHeader(connection.apiKey);
|
||||
const response = await this.requestFetch(`${connection.endpoint}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...auth === void 0 ? {} : { Authorization: auth },
|
||||
...keyBound || connection.account === void 0 || connection.account === "" ? {} : { "X-OpenViking-Account": String(connection.account) },
|
||||
...keyBound || connection.user === void 0 || connection.user === "" ? {} : { "X-OpenViking-User": String(connection.user) },
|
||||
...connection.actorPeerId === void 0 || connection.actorPeerId === "" ? {} : { "X-OpenViking-Actor-Peer": String(connection.actorPeerId) },
|
||||
...init.headers
|
||||
},
|
||||
signal: controller.signal
|
||||
});
|
||||
const envelope = await response.json().catch(() => ({}));
|
||||
if (!response.ok || envelope.status === "error") {
|
||||
const trace = envelope.error?.trace_id ?? envelope.trace_id;
|
||||
throw Object.assign(/* @__PURE__ */ new Error(`${envelope.error?.message ?? `OpenViking HTTP ${response.status}`}${trace === void 0 ? "" : ` (trace ${trace})`}`), { status: response.status });
|
||||
}
|
||||
return envelope.result ?? envelope;
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted && options.signal?.aborted !== true) throw new Error(`OpenViking request timed out after ${options.timeoutMs ?? this.requestTimeoutMs}ms`);
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
options.signal?.removeEventListener("abort", relay);
|
||||
}
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-openviking/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-openviking",
|
||||
version: "0.5.12",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "provider-native"
|
||||
},
|
||||
create: (context) => new OpenVikingProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { OpenVikingProvider, src_default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-openviking",
|
||||
"version": "0.5.12",
|
||||
"description": "OpenViking Provider child for the Memory Spaces Source.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-openviking"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-openviking#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as descriptor } from "../../../lib/descriptor-C2HZA_V0.js";
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
declare class RetainDbProvider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
||||
readonly id: "retaindb";
|
||||
readonly scoreSemantics: ProviderScoreSemantics;
|
||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
private headers;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { RetainDbProvider, _default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,211 @@
|
|||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import { HttpMemoryProvider, bearerAuthHeader, firstArray, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { t as descriptor } from "../../../lib/descriptor-C2HZA_V0.js";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-retaindb/src/driver.ts
|
||||
function insight(value) {
|
||||
const item = jsonObject(value);
|
||||
const id = jsonString(item?.id) ?? jsonString(item?.memory_id);
|
||||
const content = jsonString(item?.content) ?? jsonString(item?.memory) ?? jsonString(item?.text);
|
||||
if (id === void 0 || content === void 0) return void 0;
|
||||
const score = jsonNumber(item?.score) ?? jsonNumber(item?.similarity);
|
||||
const createdAt = jsonString(item?.created_at) ?? jsonString(item?.createdAt) ?? jsonString(item?.updated_at);
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
category: jsonString(item?.memory_type) ?? jsonString(item?.category) ?? "general",
|
||||
source: "external",
|
||||
...score === void 0 ? {} : { score },
|
||||
...createdAt === void 0 ? {} : { createdAt }
|
||||
};
|
||||
}
|
||||
function isEndpointMissing(error) {
|
||||
const status = typeof error === "object" && error !== null ? error.status : void 0;
|
||||
if (typeof status === "number") return status === 404;
|
||||
return error instanceof Error && /^[^:]+ HTTP 404\b/u.test(error.message);
|
||||
}
|
||||
var RetainDbProvider = class extends HttpMemoryProvider {
|
||||
id = "retaindb";
|
||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
||||
constructor(memorySpaces, options = {}) {
|
||||
super(memorySpaces, {
|
||||
label: descriptor.label,
|
||||
...options
|
||||
});
|
||||
}
|
||||
async discover(connection, signal) {
|
||||
const payload = await this.requestConnection(connection, "/v1/projects", {
|
||||
headers: this.headers(connection, "/v1/projects"),
|
||||
signal
|
||||
});
|
||||
return firstArray(payload, "projects", "items").flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const project = jsonString(item?.slug) ?? jsonString(item?.name) ?? jsonString(item?.id);
|
||||
if (project === void 0) return [];
|
||||
return [{
|
||||
externalId: jsonString(item?.id) ?? project,
|
||||
name: jsonString(item?.name) ?? project,
|
||||
description: jsonString(item?.description) ?? `RetainDB project ${project}`,
|
||||
connection: {
|
||||
project,
|
||||
userId: "*"
|
||||
}
|
||||
}];
|
||||
});
|
||||
}
|
||||
async status(body, signal) {
|
||||
try {
|
||||
await this.list(body, { limit: 1 }, signal);
|
||||
return { healthy: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
async search(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const payload = await this.request(body, "/v1/memory/search", {
|
||||
headers: this.headers(connection, "/v1/memory/search"),
|
||||
json: {
|
||||
project: String(connection.project),
|
||||
query: request.query,
|
||||
...String(connection.userId) === "*" ? {} : { user_id: String(connection.userId) },
|
||||
session_id: `dsh-${body.id}`,
|
||||
top_k: request.limit ?? 10,
|
||||
include_pending: true
|
||||
},
|
||||
signal
|
||||
});
|
||||
return { results: firstArray(payload, "results", "memories").map(insight).filter((item) => item !== void 0) };
|
||||
}
|
||||
async list(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const params = new URLSearchParams({
|
||||
project: String(connection.project),
|
||||
include_pending: "true"
|
||||
});
|
||||
let payload;
|
||||
if (String(connection.userId) === "*") {
|
||||
params.set("limit", String(Math.min(Math.max(request.limit ?? 200, 1), 200)));
|
||||
payload = await this.request(body, `/v1/memories?${params}`, {
|
||||
headers: this.headers(connection, "/v1/memories"),
|
||||
signal
|
||||
});
|
||||
} else try {
|
||||
payload = await this.request(body, `/v1/memory/profile/${encodeURIComponent(String(connection.userId))}?${params}`, {
|
||||
headers: this.headers(connection, "/v1/memory/profile"),
|
||||
signal
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isEndpointMissing(error)) throw error;
|
||||
params.set("user_id", String(connection.userId));
|
||||
params.set("limit", String(Math.min(Math.max(request.limit ?? 200, 1), 200)));
|
||||
payload = await this.request(body, `/v1/memories?${params}`, {
|
||||
headers: this.headers(connection, "/v1/memories"),
|
||||
signal
|
||||
});
|
||||
}
|
||||
return firstArray(payload, "memories", "results").map(insight).filter((item) => item !== void 0).filter((item) => request.category === void 0 || item.category === request.category).slice(0, Math.min(Math.max(request.limit ?? 200, 1), 200));
|
||||
}
|
||||
async remember(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const json = {
|
||||
project: String(connection.project),
|
||||
content: request.content,
|
||||
memory_type: request.category ?? "factual",
|
||||
user_id: String(connection.userId) === "*" ? "dsh-user" : String(connection.userId),
|
||||
session_id: `dsh-${body.id}`,
|
||||
importance: request.importance ?? .7,
|
||||
write_mode: "sync"
|
||||
};
|
||||
let payload;
|
||||
try {
|
||||
payload = await this.request(body, "/v1/memory", {
|
||||
headers: this.headers(connection, "/v1/memory"),
|
||||
json,
|
||||
signal
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isEndpointMissing(error)) throw error;
|
||||
const { write_mode: _writeMode, ...legacy } = json;
|
||||
payload = await this.request(body, "/v1/memories", {
|
||||
headers: this.headers(connection, "/v1/memories"),
|
||||
json: legacy,
|
||||
signal
|
||||
});
|
||||
}
|
||||
const result = jsonObject(payload) ?? {};
|
||||
return {
|
||||
action: "stored",
|
||||
provider: this.id,
|
||||
summary: "RetainDB stored the memory synchronously.",
|
||||
...jsonString(result.id) === void 0 ? {} : { id: jsonString(result.id) }
|
||||
};
|
||||
}
|
||||
async forget(body, id, signal) {
|
||||
const connection = this.connection(body);
|
||||
try {
|
||||
await this.request(body, `/v1/memory/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers: this.headers(connection, "/v1/memory"),
|
||||
signal
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isEndpointMissing(error)) throw error;
|
||||
await this.request(body, `/v1/memories/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers: this.headers(connection, "/v1/memories"),
|
||||
signal
|
||||
});
|
||||
}
|
||||
return {
|
||||
action: "deleted",
|
||||
provider: this.id,
|
||||
id
|
||||
};
|
||||
}
|
||||
headers(connection, path) {
|
||||
const rawKey = String(connection.apiKey ?? "").trim();
|
||||
const auth = typeof bearerAuthHeader === "function" ? bearerAuthHeader(rawKey) : (() => {
|
||||
const stripped = rawKey.replace(/^Bearer(?:\s+|$)/iu, "").trim();
|
||||
return stripped === "" ? void 0 : `Bearer ${stripped}`;
|
||||
})();
|
||||
const token = auth?.slice(7);
|
||||
return {
|
||||
...auth === void 0 ? {} : { Authorization: auth },
|
||||
"x-sdk-runtime": "dsh-brain-mnemon",
|
||||
...token !== void 0 && (path.startsWith("/v1/memory") || path.startsWith("/v1/context")) ? { "X-API-Key": token } : {}
|
||||
};
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-retaindb/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-retaindb",
|
||||
version: "0.5.8",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "normalized-relevance"
|
||||
},
|
||||
create: (context) => new RetainDbProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { RetainDbProvider, src_default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-retaindb",
|
||||
"version": "0.5.8",
|
||||
"description": "RetainDB Provider child for the Memory Spaces Source.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-retaindb"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-retaindb#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { ct as MemoryProviderDescriptor } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
declare const descriptor: MemoryProviderDescriptor;
|
||||
export { descriptor };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as descriptor } from "../../../lib/descriptor-CWQp36w1.js";
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, Jt as RememberRequest, L as MemoryBody, Y as MemoryListRequest, w as Insight } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, f as MemoryProviderAdapter, h as MemorySpaceAuthority, n as MemorySpaceProviderDefinition, s as MemorySpaceProviderModule, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
import { HttpMemoryProvider, HttpProviderOptions } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
declare class SupermemoryProvider extends HttpMemoryProvider implements MemoryProviderAdapter {
|
||||
readonly id: "supermemory";
|
||||
readonly scoreSemantics: ProviderScoreSemantics;
|
||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
||||
discover(connection: Record<string, string | number | boolean>, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
|
||||
status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
|
||||
search(body: MemoryBody, request: SearchRequest, signal?: AbortSignal): Promise<ProviderSearchResult>;
|
||||
list(body: MemoryBody, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<MemoryJsonValue>;
|
||||
private headers;
|
||||
}
|
||||
declare const definition: MemorySpaceProviderDefinition;
|
||||
declare const _default: MemorySpaceProviderModule<undefined>;
|
||||
export { SupermemoryProvider, _default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,221 @@
|
|||
import { t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import { HttpMemoryProvider, bearerAuthHeader, firstArray, jsonNumber, jsonObject, jsonString } from "../../source-memory-spaces/lib/provider-sdk.js";
|
||||
import { t as descriptor } from "../../../lib/descriptor-CWQp36w1.js";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-supermemory/src/driver.ts
|
||||
function isHttpNotFound(error) {
|
||||
const status = typeof error === "object" && error !== null ? error.status : void 0;
|
||||
if (typeof status === "number") return status === 404;
|
||||
return error instanceof Error && /^[^:]+ HTTP 404\b/u.test(error.message);
|
||||
}
|
||||
function insight(value) {
|
||||
const item = jsonObject(value);
|
||||
const id = jsonString(item?.id);
|
||||
const content = jsonString(item?.memory) ?? jsonString(item?.chunk) ?? jsonString(item?.content);
|
||||
if (id === void 0 || content === void 0) return void 0;
|
||||
const metadata = jsonObject(item?.metadata);
|
||||
const score = jsonNumber(item?.similarity) ?? jsonNumber(item?.score);
|
||||
const createdAt = jsonString(item?.updatedAt) ?? jsonString(item?.createdAt);
|
||||
return {
|
||||
id,
|
||||
content,
|
||||
category: jsonString(metadata?.category) ?? "general",
|
||||
source: "external",
|
||||
...score === void 0 ? {} : { score },
|
||||
...createdAt === void 0 ? {} : { createdAt }
|
||||
};
|
||||
}
|
||||
var SupermemoryProvider = class extends HttpMemoryProvider {
|
||||
id = "supermemory";
|
||||
scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
|
||||
constructor(memorySpaces, options = {}) {
|
||||
super(memorySpaces, {
|
||||
label: descriptor.label,
|
||||
...options
|
||||
});
|
||||
}
|
||||
async discover(connection, signal) {
|
||||
const payload = await this.requestConnection(connection, "/v3/container-tags/list", {
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
});
|
||||
return firstArray(payload, "containerTags", "items").flatMap((value) => {
|
||||
const item = jsonObject(value);
|
||||
const tag = jsonString(item?.containerTag) ?? jsonString(item?.container_tag);
|
||||
if (tag === void 0) return [];
|
||||
return [{
|
||||
externalId: jsonString(item?.id) ?? tag,
|
||||
name: jsonString(item?.name) ?? tag,
|
||||
description: jsonString(item?.description) ?? `Supermemory space ${tag}`,
|
||||
connection: {
|
||||
containerTag: tag,
|
||||
searchMode: "hybrid"
|
||||
}
|
||||
}];
|
||||
});
|
||||
}
|
||||
async status(body, signal) {
|
||||
try {
|
||||
const connection = this.connection(body);
|
||||
await this.request(body, "/v4/memories/list", {
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
containerTags: [String(connection.containerTag)],
|
||||
limit: 1,
|
||||
page: 1,
|
||||
sort: "createdAt",
|
||||
order: "desc"
|
||||
},
|
||||
signal
|
||||
});
|
||||
return { healthy: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
healthy: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
};
|
||||
}
|
||||
}
|
||||
async search(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const payload = await this.request(body, "/v4/search", {
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
q: request.query,
|
||||
containerTag: String(connection.containerTag),
|
||||
searchMode: String(connection.searchMode ?? "hybrid"),
|
||||
limit: request.limit ?? 10
|
||||
},
|
||||
signal
|
||||
});
|
||||
return { results: firstArray(payload, "results").map(insight).filter((item) => item !== void 0) };
|
||||
}
|
||||
async list(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const limit = Math.min(Math.max(request.limit ?? 200, 1), 200);
|
||||
const payload = await this.request(body, "/v4/memories/list", {
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
containerTags: [String(connection.containerTag)],
|
||||
limit,
|
||||
page: 1,
|
||||
sort: "createdAt",
|
||||
order: "desc"
|
||||
},
|
||||
signal
|
||||
});
|
||||
const memories = firstArray(payload, "memoryEntries", "results").map(insight).filter((item) => item !== void 0);
|
||||
const documents = await this.request(body, "/v3/documents/documents", {
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
containerTags: [String(connection.containerTag)],
|
||||
limit,
|
||||
page: 1,
|
||||
sort: "createdAt",
|
||||
order: "desc"
|
||||
},
|
||||
signal
|
||||
});
|
||||
const projectedDocuments = firstArray(documents, "documents", "memories", "results").map(insight).filter((item) => item !== void 0);
|
||||
return [...new Map([...memories, ...projectedDocuments].map((item) => [item.id, item])).values()].filter((item) => request.category === void 0 || item.category === request.category).slice(0, limit);
|
||||
}
|
||||
async remember(body, request, signal) {
|
||||
const connection = this.connection(body);
|
||||
const payload = await this.request(body, "/v3/documents", {
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
content: request.content,
|
||||
containerTag: String(connection.containerTag),
|
||||
taskType: "memory",
|
||||
metadata: {
|
||||
sm_source: "dsh-brain-mnemon",
|
||||
...request.category === void 0 ? {} : { category: request.category },
|
||||
...request.importance === void 0 ? {} : { importance: request.importance }
|
||||
}
|
||||
},
|
||||
signal
|
||||
});
|
||||
const result = jsonObject(payload) ?? {};
|
||||
return {
|
||||
action: "queued",
|
||||
provider: this.id,
|
||||
summary: "Supermemory accepted the memory document for extraction.",
|
||||
...jsonString(result.id) === void 0 ? {} : { id: jsonString(result.id) },
|
||||
...jsonString(result.status) === void 0 ? {} : { status: jsonString(result.status) }
|
||||
};
|
||||
}
|
||||
async forget(body, id, signal) {
|
||||
const connection = this.connection(body);
|
||||
try {
|
||||
const payload = await this.request(body, "/v4/memories", {
|
||||
method: "DELETE",
|
||||
headers: this.headers(connection),
|
||||
json: {
|
||||
id,
|
||||
containerTag: String(connection.containerTag),
|
||||
reason: "Deleted from dsh-brain-mnemon"
|
||||
},
|
||||
signal
|
||||
});
|
||||
return {
|
||||
action: "deleted",
|
||||
provider: this.id,
|
||||
id,
|
||||
...jsonObject(payload)?.forgotten === void 0 ? {} : { forgotten: jsonObject(payload).forgotten }
|
||||
};
|
||||
} catch (error) {
|
||||
if (!isHttpNotFound(error)) throw error;
|
||||
await this.request(body, `/v3/documents/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers: this.headers(connection),
|
||||
signal
|
||||
});
|
||||
return {
|
||||
action: "deleted",
|
||||
provider: this.id,
|
||||
id,
|
||||
document: true
|
||||
};
|
||||
}
|
||||
}
|
||||
headers(connection) {
|
||||
const rawKey = String(connection.apiKey ?? "").trim();
|
||||
const auth = typeof bearerAuthHeader === "function" ? bearerAuthHeader(rawKey) : (() => {
|
||||
const stripped = rawKey.replace(/^Bearer(?:\s+|$)/iu, "").trim();
|
||||
return stripped === "" ? void 0 : `Bearer ${stripped}`;
|
||||
})();
|
||||
return {
|
||||
...auth === void 0 ? {} : { Authorization: auth },
|
||||
"x-sm-source": "dsh-brain-mnemon"
|
||||
};
|
||||
}
|
||||
};
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-provider-supermemory/src/index.ts
|
||||
const definition = defineMemorySpaceProviderDefinition({
|
||||
manifest: {
|
||||
apiVersion: MEMORY_SPACE_PROVIDER_API_VERSION,
|
||||
kind: "provider",
|
||||
typeId: descriptor.id,
|
||||
packageName: "dsh-brain-mnemon-provider-supermemory",
|
||||
version: "0.5.7",
|
||||
label: descriptor.label,
|
||||
icon: descriptor.icon,
|
||||
summary: descriptor.summary,
|
||||
...descriptor.summaryI18nKey === void 0 ? {} : { summaryI18nKey: descriptor.summaryI18nKey },
|
||||
origin: descriptor.origin,
|
||||
locality: descriptor.kind,
|
||||
workspaceBinding: descriptor.workspaceBinding,
|
||||
capabilities: descriptor.capabilities,
|
||||
fields: descriptor.fields,
|
||||
secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
|
||||
scoreSemantics: "normalized-relevance"
|
||||
},
|
||||
create: (context) => new SupermemoryProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
|
||||
});
|
||||
var src_default = defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
apply(ctx, host) {
|
||||
host.install(ctx, definition);
|
||||
}
|
||||
});
|
||||
export { SupermemoryProvider, src_default as default, definition, descriptor };
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-provider-supermemory",
|
||||
"version": "0.5.7",
|
||||
"description": "Supermemory Provider child for the Memory Spaces Source.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./descriptor": {
|
||||
"types": "./lib/descriptor.d.ts",
|
||||
"default": "./lib/descriptor.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"dsh-brain-mnemon-source-memory-spaces": "^0.5.33",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-provider-supermemory"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-provider-supermemory#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
import { ft as installMemorySourceUI, gt as MnemonSourceManagementClient, ht as MemorySourcePageProps, xt as MnemonTranslate } from "../../../lib/client-extension-sdk-BX83D8r5.js";
|
||||
import { JSX, ReactNode } from "react";
|
||||
type DocumentStatus = 'active' | 'archived';
|
||||
interface DocumentRecord {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
status: DocumentStatus;
|
||||
filename: string;
|
||||
relativePath: string;
|
||||
sourcePaths: string[];
|
||||
sessionIds: string[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
lastAccessedAt: string;
|
||||
revision: number;
|
||||
contentHash: string;
|
||||
sizeBytes: number;
|
||||
archivedAt?: string;
|
||||
archiveSummary?: string;
|
||||
memoryBodyIds: string[];
|
||||
}
|
||||
interface DocumentView extends DocumentRecord {
|
||||
content: string;
|
||||
fileRevision?: string;
|
||||
}
|
||||
interface DocumentSnapshot {
|
||||
workspaceRoot: string;
|
||||
directory: string;
|
||||
indexPath: string;
|
||||
generatedAt: string;
|
||||
revision: string;
|
||||
limitBytes: number;
|
||||
activeBytes: number;
|
||||
activeCount: number;
|
||||
archivedCount: number;
|
||||
total: number;
|
||||
documents: Array<DocumentRecord & {
|
||||
healthy: boolean;
|
||||
excerpt: string;
|
||||
}>;
|
||||
}
|
||||
interface DocumentSearchResult {
|
||||
query: string;
|
||||
includeArchived: boolean;
|
||||
total: number;
|
||||
generatedAt: string;
|
||||
results: Array<DocumentView & {
|
||||
score: number;
|
||||
excerpt: string;
|
||||
}>;
|
||||
}
|
||||
type DocumentMutation = {
|
||||
action: 'create';
|
||||
title: string;
|
||||
description?: string;
|
||||
content: string;
|
||||
sourcePaths?: string[];
|
||||
sessionIds?: string[];
|
||||
} | {
|
||||
action: 'update';
|
||||
id: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
content?: string;
|
||||
sourcePaths?: string[];
|
||||
sessionIds?: string[];
|
||||
} | {
|
||||
action: 'delete';
|
||||
id: string;
|
||||
fileRevision?: string;
|
||||
};
|
||||
interface DocumentMutationResult {
|
||||
success: true;
|
||||
action: 'created' | 'updated' | 'archived' | 'deleted';
|
||||
document: DocumentView;
|
||||
snapshot: DocumentSnapshot;
|
||||
maintenance?: {
|
||||
runId: string;
|
||||
provider: string;
|
||||
summary: string;
|
||||
memoryBodyIds: string[];
|
||||
archivedDocumentIds: string[];
|
||||
};
|
||||
}
|
||||
interface DocumentsPageClient {
|
||||
documents(): Promise<DocumentSnapshot>;
|
||||
document(id: string): Promise<DocumentView>;
|
||||
searchDocuments(query: string, includeArchived?: boolean, limit?: number): Promise<DocumentSearchResult & {
|
||||
revision?: string;
|
||||
}>;
|
||||
mutateDocument(request: DocumentMutation): Promise<DocumentMutationResult>;
|
||||
archiveDocument(id: string): Promise<DocumentMutationResult>;
|
||||
deleteDocument?(id: string, expectedRevision: string, fileRevision: string): Promise<DocumentMutationResult>;
|
||||
}
|
||||
declare function DocumentsPage(props: {
|
||||
client: DocumentsPageClient;
|
||||
revision: number;
|
||||
writeEnabled: boolean;
|
||||
sessionId?: string;
|
||||
canCreate?: boolean;
|
||||
documentId?: string;
|
||||
onMutate?: () => void;
|
||||
}): JSX.Element;
|
||||
declare function documentsPageClient(management: MnemonSourceManagementClient): DocumentsPageClient;
|
||||
declare function DocumentsSourcePage(props: MemorySourcePageProps): ReactNode;
|
||||
declare function installDocumentsMemoryUI(ctx: Parameters<typeof installMemorySourceUI>[0], t?: MnemonTranslate): () => void;
|
||||
declare const inject: string[];
|
||||
declare function apply(ctx: Parameters<typeof installMemorySourceUI>[0]): void;
|
||||
export { DocumentsPage, type DocumentsPageClient, DocumentsSourcePage, apply, documentsPageClient, inject, installDocumentsMemoryUI };
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,109 @@
|
|||
type DocumentStatus = 'active' | 'archived';
|
||||
interface DocumentRecord {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
status: DocumentStatus;
|
||||
filename: string;
|
||||
relativePath: string;
|
||||
sourcePaths: string[];
|
||||
sessionIds: string[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
lastAccessedAt: string;
|
||||
revision: number;
|
||||
contentHash: string;
|
||||
sizeBytes: number;
|
||||
archivedAt?: string;
|
||||
archiveSummary?: string;
|
||||
memoryBodyIds: string[];
|
||||
}
|
||||
interface DocumentView extends DocumentRecord {
|
||||
content: string;
|
||||
fileRevision?: string;
|
||||
}
|
||||
interface DocumentSnapshot {
|
||||
workspaceRoot: string;
|
||||
directory: string;
|
||||
indexPath: string;
|
||||
generatedAt: string;
|
||||
revision: string;
|
||||
limitBytes: number;
|
||||
activeBytes: number;
|
||||
activeCount: number;
|
||||
archivedCount: number;
|
||||
total: number;
|
||||
documents: Array<DocumentRecord & {
|
||||
healthy: boolean;
|
||||
excerpt: string;
|
||||
}>;
|
||||
}
|
||||
interface DocumentSearchResult {
|
||||
query: string;
|
||||
includeArchived: boolean;
|
||||
total: number;
|
||||
generatedAt: string;
|
||||
results: Array<DocumentView & {
|
||||
score: number;
|
||||
excerpt: string;
|
||||
}>;
|
||||
}
|
||||
type DocumentMutation = {
|
||||
action: 'create';
|
||||
title: string;
|
||||
description?: string;
|
||||
content: string;
|
||||
sourcePaths?: string[];
|
||||
sessionIds?: string[];
|
||||
} | {
|
||||
action: 'update';
|
||||
id: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
content?: string;
|
||||
sourcePaths?: string[];
|
||||
sessionIds?: string[];
|
||||
} | {
|
||||
action: 'delete';
|
||||
id: string;
|
||||
fileRevision?: string;
|
||||
};
|
||||
interface DocumentMutationResult {
|
||||
success: true;
|
||||
action: 'created' | 'updated' | 'archived' | 'deleted';
|
||||
document: DocumentView;
|
||||
snapshot: DocumentSnapshot;
|
||||
maintenance?: {
|
||||
runId: string;
|
||||
provider: string;
|
||||
summary: string;
|
||||
memoryBodyIds: string[];
|
||||
archivedDocumentIds: string[];
|
||||
};
|
||||
}
|
||||
interface DocumentCapacityPlan {
|
||||
projected: number;
|
||||
limit: number;
|
||||
fits: boolean;
|
||||
candidates: DocumentRecord[];
|
||||
}
|
||||
declare const DOCUMENTS_VERSION = 1;
|
||||
declare const DOCUMENTS_ACTIVE_LIMIT_BYTES: number;
|
||||
declare const DOCUMENTS_DIRECTORY = "documents";
|
||||
declare const DOCUMENTS_INDEX_FILE = "index.json";
|
||||
declare const DOCUMENTS_LOCK_FILE = ".index.lock";
|
||||
declare const DOCUMENTS_LOCK_STALE_MS = 30000;
|
||||
declare const DOCUMENT_FILENAME_PATTERN: RegExp;
|
||||
interface DocumentIndex {
|
||||
version: typeof DOCUMENTS_VERSION;
|
||||
documents: DocumentRecord[];
|
||||
}
|
||||
declare function parseDocumentIndex(value: unknown): DocumentIndex;
|
||||
interface DocumentIndexSummary {
|
||||
valid: boolean;
|
||||
documents: number;
|
||||
active: number;
|
||||
archived: number;
|
||||
}
|
||||
declare function summarizeDocumentIndex(value: unknown): DocumentIndexSummary;
|
||||
export { DOCUMENTS_ACTIVE_LIMIT_BYTES, DOCUMENTS_DIRECTORY, DOCUMENTS_INDEX_FILE, DOCUMENTS_LOCK_FILE, DOCUMENTS_LOCK_STALE_MS, DOCUMENTS_VERSION, DOCUMENT_FILENAME_PATTERN, DocumentCapacityPlan, DocumentIndex, DocumentIndexSummary, DocumentMutation, DocumentMutationResult, DocumentRecord, DocumentSearchResult, DocumentSnapshot, DocumentStatus, DocumentView, parseDocumentIndex, summarizeDocumentIndex };
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-documents/src/contracts.ts
|
||||
const DOCUMENTS_VERSION = 1;
|
||||
const DOCUMENTS_ACTIVE_LIMIT_BYTES = 10485760;
|
||||
const DOCUMENTS_DIRECTORY = "documents";
|
||||
const DOCUMENTS_INDEX_FILE = "index.json";
|
||||
const DOCUMENTS_LOCK_FILE = ".index.lock";
|
||||
const DOCUMENTS_LOCK_STALE_MS = 3e4;
|
||||
const DOCUMENT_FILENAME_PATTERN = /^[a-zA-Z0-9._-]+\.md$/u;
|
||||
function isObject(value) {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
function parseDocumentIndex(value) {
|
||||
const index = isObject(value) ? value : void 0;
|
||||
if (index?.version !== 1 || !Array.isArray(index.documents)) throw new Error("Documents index.json is invalid");
|
||||
const ids = /* @__PURE__ */ new Set();
|
||||
return {
|
||||
version: 1,
|
||||
documents: index.documents.map((raw) => {
|
||||
const item = isObject(raw) ? raw : void 0;
|
||||
if (typeof item?.id !== "string" || item.id.trim() === "" || ids.has(item.id)) throw new Error("Documents index contains an invalid or duplicate id");
|
||||
if (typeof item.title !== "string" || typeof item.description !== "string" || item.status !== "active" && item.status !== "archived") throw new Error("Documents index contains an invalid record");
|
||||
if (typeof item.filename !== "string" || !DOCUMENT_FILENAME_PATTERN.test(item.filename)) throw new Error("Documents index contains an unsafe filename");
|
||||
if (typeof item.createdAt !== "string" || typeof item.updatedAt !== "string" || typeof item.lastAccessedAt !== "string" || !Number.isSafeInteger(item.revision) || typeof item.contentHash !== "string" || !Number.isSafeInteger(item.sizeBytes)) throw new Error("Documents index contains invalid metadata");
|
||||
if (!Array.isArray(item.sourcePaths) || !Array.isArray(item.sessionIds) || !Array.isArray(item.memoryBodyIds)) throw new Error("Documents index contains invalid lists");
|
||||
ids.add(item.id);
|
||||
return {
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
description: item.description,
|
||||
status: item.status,
|
||||
filename: item.filename,
|
||||
relativePath: `${DOCUMENTS_DIRECTORY}/${item.status}/${item.filename}`,
|
||||
sourcePaths: item.sourcePaths.filter((entry) => typeof entry === "string"),
|
||||
sessionIds: item.sessionIds.filter((entry) => typeof entry === "string"),
|
||||
createdAt: item.createdAt,
|
||||
updatedAt: item.updatedAt,
|
||||
lastAccessedAt: item.lastAccessedAt,
|
||||
revision: Number(item.revision),
|
||||
contentHash: item.contentHash,
|
||||
sizeBytes: Number(item.sizeBytes),
|
||||
...typeof item.archivedAt === "string" ? { archivedAt: item.archivedAt } : {},
|
||||
...typeof item.archiveSummary === "string" ? { archiveSummary: item.archiveSummary } : {},
|
||||
memoryBodyIds: item.memoryBodyIds.filter((entry) => typeof entry === "string")
|
||||
};
|
||||
})
|
||||
};
|
||||
}
|
||||
function summarizeDocumentIndex(value) {
|
||||
const documents = isObject(value) && Array.isArray(value.documents) ? value.documents.filter(isObject) : [];
|
||||
return {
|
||||
valid: isObject(value) && Array.isArray(value.documents),
|
||||
documents: documents.length,
|
||||
active: documents.filter((document) => document.status === "active").length,
|
||||
archived: documents.filter((document) => document.status === "archived").length
|
||||
};
|
||||
}
|
||||
export { DOCUMENTS_ACTIVE_LIMIT_BYTES, DOCUMENTS_DIRECTORY, DOCUMENTS_INDEX_FILE, DOCUMENTS_LOCK_FILE, DOCUMENTS_LOCK_STALE_MS, DOCUMENTS_VERSION, DOCUMENT_FILENAME_PATTERN, parseDocumentIndex, summarizeDocumentIndex };
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import "../../../lib/index-C00l82Ug.js";
|
||||
import { b as MemoryPluginDescriptor, q as MemorySourceDefinition } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { DOCUMENTS_ACTIVE_LIMIT_BYTES, DOCUMENTS_DIRECTORY, DOCUMENTS_INDEX_FILE, DOCUMENTS_LOCK_FILE, DOCUMENTS_LOCK_STALE_MS, DOCUMENTS_VERSION, DOCUMENT_FILENAME_PATTERN, DocumentCapacityPlan, DocumentIndex, DocumentIndexSummary, DocumentMutation, DocumentMutationResult, DocumentRecord, DocumentSearchResult, DocumentSnapshot, DocumentStatus, DocumentView, parseDocumentIndex, summarizeDocumentIndex } from "./contracts.js";
|
||||
import { Context } from "@deepseek-ai/cordis";
|
||||
import z from "@deepseek-ai/schemastery";
|
||||
interface Config {
|
||||
dataDir?: string;
|
||||
limitBytes?: number;
|
||||
bm25Recall?: boolean;
|
||||
bm25IndexPush?: boolean;
|
||||
}
|
||||
declare const Config: z<Config>;
|
||||
declare function createDocumentsMemorySource(config?: Config): MemorySourceDefinition;
|
||||
declare const DOCUMENTS_MEMORY_SOURCE: MemorySourceDefinition;
|
||||
declare const name = "dsh-brain-mnemon-source-documents";
|
||||
declare const inject: string[];
|
||||
declare const memoryPlugin: MemoryPluginDescriptor;
|
||||
declare function apply(ctx: Context, config?: Config): void;
|
||||
export { Config, type DOCUMENTS_ACTIVE_LIMIT_BYTES, type DOCUMENTS_DIRECTORY, type DOCUMENTS_INDEX_FILE, type DOCUMENTS_LOCK_FILE, type DOCUMENTS_LOCK_STALE_MS, DOCUMENTS_MEMORY_SOURCE, type DOCUMENTS_VERSION, type DOCUMENT_FILENAME_PATTERN, type DocumentCapacityPlan, type DocumentIndex, type DocumentIndexSummary, type DocumentMutation, type DocumentMutationResult, type DocumentRecord, type DocumentSearchResult, type DocumentSnapshot, type DocumentStatus, type DocumentView, apply, createDocumentsMemorySource, inject, memoryPlugin, name, type parseDocumentIndex, type summarizeDocumentIndex };
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Projektdokumente",
|
||||
"description": "Versionierte narrative Dokumente, die zuerst durchsucht und bei Bedarf vollständig gelesen werden."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Project Documents",
|
||||
"description": "Versioned narrative documents searched first and read in full on demand."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Documentos del proyecto",
|
||||
"description": "Documentos narrativos versionados que se buscan primero y se leen completos bajo demanda."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Documents du projet",
|
||||
"description": "Documents narratifs versionnés, d'abord recherchés puis lus intégralement à la demande."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "プロジェクトドキュメント",
|
||||
"description": "先に検索し、必要に応じて全文を読み込むバージョン管理付きドキュメント。"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Documentos do projeto",
|
||||
"description": "Documentos narrativos versionados, pesquisados primeiro e lidos na íntegra sob demanda."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Документы проекта",
|
||||
"description": "Версионируемые повествовательные документы: сначала поиск, затем чтение полного текста по запросу."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "项目档案",
|
||||
"description": "可版本化的叙事文档,先检索,再按需阅读全文。"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-source-documents",
|
||||
"version": "0.6.6",
|
||||
"description": "Self-contained documents Source for Composable View Memory.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./package.json": "./package.json",
|
||||
"./locale/*.json": "./locale/*.json",
|
||||
"./client": {
|
||||
"types": "./lib/client.d.ts",
|
||||
"default": "./lib/client.js"
|
||||
},
|
||||
"./contracts": {
|
||||
"types": "./lib/contracts.d.ts",
|
||||
"default": "./lib/contracts.js"
|
||||
},
|
||||
"./presentation/locales.json": "./presentation/locales.json",
|
||||
"./presentation/page.module.css": "./presentation/page.module.css",
|
||||
"./presentation/sidebar.module.css": "./presentation/sidebar.module.css"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"locale",
|
||||
"README.md",
|
||||
"presentation"
|
||||
],
|
||||
"dsh": {
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"external": [
|
||||
"dsh-brain-mnemon/client"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown && tsc -p tsconfig.client-types.json",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/schemastery": "^3.18.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon": "^0.5.40",
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "0.2.1-rc.5",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/react": "^18.3.0",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"dsh-brain-mnemon": "^0.5.53",
|
||||
"jsdom": "^26.0.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0",
|
||||
"lightningcss": "^1.33.0",
|
||||
"clsx": "^2.1.1",
|
||||
"@shikijs/langs": "^4.3.1",
|
||||
"anser": "^2.3.5",
|
||||
"katex": "^0.16.47",
|
||||
"mdast-util-from-markdown": "^2.0.3",
|
||||
"mdast-util-gfm": "^3.1.0",
|
||||
"mdast-util-math": "^3.0.0",
|
||||
"micromark-core-commonmark": "^2.0.3",
|
||||
"micromark-extension-gfm": "^3.0.0",
|
||||
"micromark-extension-math": "^3.1.0",
|
||||
"micromark-factory-space": "^2.0.1",
|
||||
"micromark-util-character": "^2.1.1",
|
||||
"micromark-util-classify-character": "^2.0.1",
|
||||
"micromark-util-sanitize-uri": "^2.0.1",
|
||||
"micromark-util-symbol": "^2.0.1",
|
||||
"shiki": "^4.3.1",
|
||||
"@deepseek-ai/dsh-client-store": "0.2.1-rc.5",
|
||||
"@deepseek-ai/dsh-util-code-language": "0.2.1-rc.5",
|
||||
"@deepseek-ai/dsh-util-workspace-path": "0.2.1-rc.5",
|
||||
"diff": "^9.0.0",
|
||||
"immer": "^10.1.1",
|
||||
"simple-icons": "16.31.0",
|
||||
"zustand": "~4.4.7"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-source-documents"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-source-documents#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,570 @@
|
|||
{
|
||||
"zh": {
|
||||
"nav.documents": "档案",
|
||||
"documents.title": "项目档案",
|
||||
"documents.description": "按需检索的工作区文档,超限时自动归档。",
|
||||
"documents.capacity": "{used} / {limit}",
|
||||
"documents.summary": "档案存储摘要",
|
||||
"documents.active": "活跃档案",
|
||||
"documents.activeHint": "近场检索范围",
|
||||
"documents.archivedCount": "归档",
|
||||
"documents.archivedHint": "不占活跃容量",
|
||||
"documents.activeCapacity": "活跃容量",
|
||||
"documents.capacityHint": "按实际 UTF-8 文件大小计算",
|
||||
"documents.searchAria": "检索项目档案",
|
||||
"documents.searchPlaceholder": "搜索档案…",
|
||||
"documents.search": "检索",
|
||||
"documents.scope": "档案范围",
|
||||
"documents.new": "新建",
|
||||
"documents.newTitle": "创建托管档案",
|
||||
"documents.editTitle": "编辑活跃档案",
|
||||
"documents.editorHint": "自动维护元数据与修订号,不修改项目源文件。",
|
||||
"documents.managedCopy": "托管副本",
|
||||
"documents.name": "标题",
|
||||
"documents.routing": "检索说明",
|
||||
"documents.sources": "来源路径",
|
||||
"documents.sourcesPlaceholder": "src/index.ts, docs/architecture.md",
|
||||
"documents.markdown": "Markdown 内容",
|
||||
"documents.saving": "保存中…",
|
||||
"documents.create": "创建",
|
||||
"documents.save": "保存",
|
||||
"documents.created": "已创建活跃档案。",
|
||||
"documents.createdAfterArchive": "已先迁移 {count} 份旧档案,再创建活跃档案。",
|
||||
"documents.updated": "已保存新的档案修订。",
|
||||
"documents.updatedAfterArchive": "已先迁移 {count} 份旧档案,再保存修订。",
|
||||
"documents.archived": "已建立 Mnemon 冷索引并归档;关联记忆空间:{spaces}",
|
||||
"documents.archivedLocally": "已归档到本地:原文移入归档目录,没有建立 Mnemon 冷索引。",
|
||||
"documents.list": "项目档案列表",
|
||||
"documents.activeList": "活跃目录",
|
||||
"documents.archiveList": "归档目录",
|
||||
"documents.noDescription": "暂无检索说明。",
|
||||
"documents.missing": "文件缺失",
|
||||
"documents.emptyActive": "还没有活跃档案",
|
||||
"documents.emptyActiveText": "复杂对话达到活动评分门槛后会自动审阅并整理档案,也可以在上方手动创建。",
|
||||
"documents.emptyArchived": "还没有归档",
|
||||
"documents.emptyArchivedText": "只有完成 Mnemon 索引的档案才会迁移到这里。",
|
||||
"documents.reader": "档案阅读器",
|
||||
"documents.selectTitle": "选择一份档案",
|
||||
"documents.selectText": "在左侧查看活跃项目知识或沿 Mnemon 引用打开归档原文。",
|
||||
"documents.coldArchive": "归档原文",
|
||||
"documents.edit": "编辑",
|
||||
"documents.delete": "删除",
|
||||
"documents.deleteConfirm": "永久删除这份档案?",
|
||||
"documents.deleteDescription": "永久移除托管副本,项目源文件与记忆空间不受影响,且无法撤销。",
|
||||
"documents.deleteNow": "确认删除",
|
||||
"documents.deleting": "删除中…",
|
||||
"documents.deleted": "档案已永久删除。",
|
||||
"documents.path": "托管路径",
|
||||
"documents.revision": "修订",
|
||||
"documents.hash": "内容哈希",
|
||||
"documents.size": "文件大小",
|
||||
"documents.archiveReceipt": "Mnemon 冷索引回执",
|
||||
"documents.archiveNote": "归档说明",
|
||||
"documents.archiveTitle": "迁入归档",
|
||||
"documents.archiveDescription": "生成摘要索引并移入归档,释放活跃容量。",
|
||||
"documents.archive": "归档",
|
||||
"documents.archiveConfirm": "确认归档这份档案?",
|
||||
"documents.archiving": "归档中…",
|
||||
"documents.archiveNow": "确认归档",
|
||||
"documents.markdown.copy": "复制",
|
||||
"documents.markdown.copied": "已复制",
|
||||
"documents.markdown.footnotes": "脚注"
|
||||
},
|
||||
"en": {
|
||||
"nav.documents": "Documents",
|
||||
"documents.title": "Project Documents",
|
||||
"documents.description": "Workspace documents searched on demand and archived when full.",
|
||||
"documents.capacity": "{used} / {limit}",
|
||||
"documents.summary": "Document storage summary",
|
||||
"documents.active": "Active",
|
||||
"documents.activeHint": "Near-field search scope",
|
||||
"documents.archivedCount": "Archive",
|
||||
"documents.archivedHint": "Excluded from active capacity",
|
||||
"documents.activeCapacity": "Active capacity",
|
||||
"documents.capacityHint": "Measured from actual UTF-8 files",
|
||||
"documents.searchAria": "Search project documents",
|
||||
"documents.searchPlaceholder": "Search documents…",
|
||||
"documents.search": "Search",
|
||||
"documents.scope": "Document scope",
|
||||
"documents.new": "New",
|
||||
"documents.newTitle": "Create managed document",
|
||||
"documents.editTitle": "Edit active document",
|
||||
"documents.editorHint": "Metadata and revisions are managed automatically; source files stay untouched.",
|
||||
"documents.managedCopy": "Managed copy",
|
||||
"documents.name": "Title",
|
||||
"documents.routing": "Retrieval description",
|
||||
"documents.sources": "Source paths",
|
||||
"documents.sourcesPlaceholder": "src/index.ts, docs/architecture.md",
|
||||
"documents.markdown": "Markdown content",
|
||||
"documents.saving": "Saving…",
|
||||
"documents.create": "Create",
|
||||
"documents.save": "Save",
|
||||
"documents.created": "Active document created.",
|
||||
"documents.createdAfterArchive": "Archived {count} older document(s), then created the active document.",
|
||||
"documents.updated": "New document revision saved.",
|
||||
"documents.updatedAfterArchive": "Archived {count} older document(s), then saved the revision.",
|
||||
"documents.archived": "Mnemon cold index created and document archived; Memory Spaces: {spaces}",
|
||||
"documents.archivedLocally": "Archived locally: the original moved to the archive, without a Mnemon cold index.",
|
||||
"documents.list": "Project document list",
|
||||
"documents.activeList": "Active directory",
|
||||
"documents.archiveList": "Archive directory",
|
||||
"documents.noDescription": "No retrieval description.",
|
||||
"documents.missing": "File missing",
|
||||
"documents.emptyActive": "No active documents yet",
|
||||
"documents.emptyActiveText": "Complex work is reviewed after it reaches the activity-score gate, or you can create a Document above.",
|
||||
"documents.emptyArchived": "No archives yet",
|
||||
"documents.emptyArchivedText": "Only documents with a completed Mnemon index are moved here.",
|
||||
"documents.reader": "Document reader",
|
||||
"documents.selectTitle": "Select a document",
|
||||
"documents.selectText": "Read active project knowledge or follow a Mnemon reference to an archived original.",
|
||||
"documents.coldArchive": "Archived original",
|
||||
"documents.edit": "Edit",
|
||||
"documents.delete": "Delete",
|
||||
"documents.deleteConfirm": "Permanently delete this document?",
|
||||
"documents.deleteDescription": "Permanently removes the managed copy; project files and Memory Space notes stay untouched. This cannot be undone.",
|
||||
"documents.deleteNow": "Confirm delete",
|
||||
"documents.deleting": "Deleting…",
|
||||
"documents.deleted": "Document permanently deleted.",
|
||||
"documents.path": "Managed path",
|
||||
"documents.revision": "Revision",
|
||||
"documents.hash": "Content hash",
|
||||
"documents.size": "File size",
|
||||
"documents.archiveReceipt": "Mnemon cold-index receipt",
|
||||
"documents.archiveNote": "Archive note",
|
||||
"documents.archiveTitle": "Move to archive",
|
||||
"documents.archiveDescription": "Index a summary in Memory Spaces and move the full text to archive.",
|
||||
"documents.archive": "Archive",
|
||||
"documents.archiveConfirm": "Archive this document?",
|
||||
"documents.archiving": "Archiving…",
|
||||
"documents.archiveNow": "Confirm archive",
|
||||
"documents.markdown.copy": "Copy",
|
||||
"documents.markdown.copied": "Copied",
|
||||
"documents.markdown.footnotes": "Footnotes"
|
||||
},
|
||||
"ja": {
|
||||
"nav.documents": "ドキュメント",
|
||||
"documents.title": "プロジェクトドキュメント",
|
||||
"documents.description": "必要に応じて検索され、容量超過時に自動アーカイブされるワークスペース文書。",
|
||||
"documents.capacity": "{used} / {limit}",
|
||||
"documents.summary": "ドキュメントストレージ概要",
|
||||
"documents.active": "アクティブ",
|
||||
"documents.activeHint": "近接検索の対象",
|
||||
"documents.archivedCount": "アーカイブ",
|
||||
"documents.archivedHint": "アクティブ容量の対象外",
|
||||
"documents.activeCapacity": "アクティブ容量",
|
||||
"documents.capacityHint": "実際の UTF-8 ファイルサイズで計測",
|
||||
"documents.searchAria": "プロジェクトドキュメントを検索",
|
||||
"documents.searchPlaceholder": "ドキュメントを検索…",
|
||||
"documents.search": "検索",
|
||||
"documents.scope": "ドキュメントの範囲",
|
||||
"documents.new": "新規",
|
||||
"documents.newTitle": "管理対象ドキュメントを作成",
|
||||
"documents.editTitle": "アクティブドキュメントを編集",
|
||||
"documents.editorHint": "メタデータとリビジョンは自動管理されます。プロジェクトの元ファイルは変更されません。",
|
||||
"documents.managedCopy": "管理コピー",
|
||||
"documents.name": "タイトル",
|
||||
"documents.routing": "検索用の説明",
|
||||
"documents.sources": "参照元パス",
|
||||
"documents.sourcesPlaceholder": "src/index.ts, docs/architecture.md",
|
||||
"documents.markdown": "Markdown 本文",
|
||||
"documents.saving": "保存中…",
|
||||
"documents.create": "作成",
|
||||
"documents.save": "保存",
|
||||
"documents.created": "アクティブドキュメントを作成しました。",
|
||||
"documents.createdAfterArchive": "古いドキュメント {count} 件をアーカイブしたあと、アクティブドキュメントを作成しました。",
|
||||
"documents.updated": "新しいドキュメントリビジョンを保存しました。",
|
||||
"documents.updatedAfterArchive": "古いドキュメント {count} 件をアーカイブしたあと、リビジョンを保存しました。",
|
||||
"documents.archived": "Mnemon コールドインデックスを作成してアーカイブしました(メモリスペース:{spaces})",
|
||||
"documents.archivedLocally": "ローカルにアーカイブしました:原文をアーカイブへ移動しました(Mnemon コールドインデックスなし)。",
|
||||
"documents.list": "プロジェクトドキュメント一覧",
|
||||
"documents.activeList": "アクティブディレクトリ",
|
||||
"documents.archiveList": "アーカイブディレクトリ",
|
||||
"documents.noDescription": "検索用の説明はまだありません。",
|
||||
"documents.missing": "ファイルが見つかりません",
|
||||
"documents.emptyActive": "アクティブドキュメントはまだありません",
|
||||
"documents.emptyActiveText": "複雑な作業は活動スコアのしきい値を超えると自動でレビュー・整理されます。上から手動作成もできます。",
|
||||
"documents.emptyArchived": "アーカイブはまだありません",
|
||||
"documents.emptyArchivedText": "Mnemon インデックスが完了したドキュメントのみここに移動されます。",
|
||||
"documents.reader": "ドキュメントビューアー",
|
||||
"documents.selectTitle": "ドキュメントを選択",
|
||||
"documents.selectText": "アクティブなプロジェクト知識を読むか、Mnemon の参照からアーカイブ原文を開けます。",
|
||||
"documents.coldArchive": "アーカイブ原文",
|
||||
"documents.edit": "編集",
|
||||
"documents.delete": "削除",
|
||||
"documents.deleteConfirm": "このドキュメントを完全に削除しますか?",
|
||||
"documents.deleteDescription": "管理コピーを完全に削除します。プロジェクトの元ファイルとメモリスペースの記録は影響を受けません。この操作は元に戻せません。",
|
||||
"documents.deleteNow": "削除を確定",
|
||||
"documents.deleting": "削除中…",
|
||||
"documents.deleted": "ドキュメントを完全に削除しました。",
|
||||
"documents.path": "管理パス",
|
||||
"documents.revision": "リビジョン",
|
||||
"documents.hash": "コンテンツハッシュ",
|
||||
"documents.size": "ファイルサイズ",
|
||||
"documents.archiveReceipt": "Mnemon コールドインデックス記録",
|
||||
"documents.archiveNote": "アーカイブメモ",
|
||||
"documents.archiveTitle": "アーカイブへ移動",
|
||||
"documents.archiveDescription": "要約をメモリスペースに索引付けし、本文をアーカイブへ移動します。",
|
||||
"documents.archive": "アーカイブ",
|
||||
"documents.archiveConfirm": "このドキュメントをアーカイブしますか?",
|
||||
"documents.archiving": "アーカイブ中…",
|
||||
"documents.archiveNow": "アーカイブを確定",
|
||||
"documents.markdown.copy": "コピー",
|
||||
"documents.markdown.copied": "コピーしました",
|
||||
"documents.markdown.footnotes": "脚注"
|
||||
},
|
||||
"es": {
|
||||
"nav.documents": "Documentos",
|
||||
"documents.title": "Documentos del proyecto",
|
||||
"documents.description": "Documentos del espacio de trabajo consultados bajo demanda y archivados al llenarse.",
|
||||
"documents.capacity": "{used} / {limit}",
|
||||
"documents.summary": "Resumen de almacenamiento de documentos",
|
||||
"documents.active": "Activos",
|
||||
"documents.activeHint": "Ámbito de búsqueda cercana",
|
||||
"documents.archivedCount": "Archivo",
|
||||
"documents.archivedHint": "Excluido de la capacidad activa",
|
||||
"documents.activeCapacity": "Capacidad activa",
|
||||
"documents.capacityHint": "Calculado según los archivos UTF-8 reales",
|
||||
"documents.searchAria": "Buscar documentos del proyecto",
|
||||
"documents.searchPlaceholder": "Buscar documentos…",
|
||||
"documents.search": "Buscar",
|
||||
"documents.scope": "Ámbito de documentos",
|
||||
"documents.new": "Nuevo",
|
||||
"documents.newTitle": "Crear documento gestionado",
|
||||
"documents.editTitle": "Editar documento activo",
|
||||
"documents.editorHint": "Los metadatos y las revisiones se gestionan automáticamente; los archivos fuente permanecen intactos.",
|
||||
"documents.managedCopy": "Copia gestionada",
|
||||
"documents.name": "Título",
|
||||
"documents.routing": "Descripción de recuperación",
|
||||
"documents.sources": "Rutas de origen",
|
||||
"documents.sourcesPlaceholder": "src/index.ts, docs/architecture.md",
|
||||
"documents.markdown": "Contenido Markdown",
|
||||
"documents.saving": "Guardando…",
|
||||
"documents.create": "Crear",
|
||||
"documents.save": "Guardar",
|
||||
"documents.created": "Documento activo creado.",
|
||||
"documents.createdAfterArchive": "Se archivaron {count} documento(s) anterior(es) y se creó el documento activo.",
|
||||
"documents.updated": "Nueva revisión del documento guardada.",
|
||||
"documents.updatedAfterArchive": "Se archivaron {count} documento(s) anterior(es) y se guardó la revisión.",
|
||||
"documents.archived": "Índice frío de Mnemon creado y documento archivado; Espacios de memoria: {spaces}",
|
||||
"documents.archivedLocally": "Archivado localmente: el original se movió al archivo, sin índice frío de Mnemon.",
|
||||
"documents.list": "Lista de documentos del proyecto",
|
||||
"documents.activeList": "Directorio activo",
|
||||
"documents.archiveList": "Directorio de archivo",
|
||||
"documents.noDescription": "Sin descripción de recuperación.",
|
||||
"documents.missing": "Archivo faltante",
|
||||
"documents.emptyActive": "Aún no hay documentos activos",
|
||||
"documents.emptyActiveText": "El trabajo complejo se revisa al superar el umbral de puntuación de actividad, o puedes crear un Documento arriba.",
|
||||
"documents.emptyArchived": "Aún no hay archivos",
|
||||
"documents.emptyArchivedText": "Solo los documentos con un índice de Mnemon completado se mueven aquí.",
|
||||
"documents.reader": "Lector de documentos",
|
||||
"documents.selectTitle": "Selecciona un documento",
|
||||
"documents.selectText": "Consulta el conocimiento activo del proyecto o sigue una referencia de Mnemon hacia un original archivado.",
|
||||
"documents.coldArchive": "Original archivado",
|
||||
"documents.edit": "Editar",
|
||||
"documents.delete": "Eliminar",
|
||||
"documents.deleteConfirm": "¿Eliminar permanentemente este documento?",
|
||||
"documents.deleteDescription": "Elimina permanentemente la copia gestionada; los archivos del proyecto y las notas de Espacios de memoria permanecen intactos. No se puede deshacer.",
|
||||
"documents.deleteNow": "Confirmar eliminación",
|
||||
"documents.deleting": "Eliminando…",
|
||||
"documents.deleted": "Documento eliminado permanentemente.",
|
||||
"documents.path": "Ruta gestionada",
|
||||
"documents.revision": "Revisión",
|
||||
"documents.hash": "Hash de contenido",
|
||||
"documents.size": "Tamaño del archivo",
|
||||
"documents.archiveReceipt": "Recibo de índice frío de Mnemon",
|
||||
"documents.archiveNote": "Nota de archivo",
|
||||
"documents.archiveTitle": "Mover al archivo",
|
||||
"documents.archiveDescription": "Indexa un resumen en Espacios de memoria y mueve el texto completo al archivo.",
|
||||
"documents.archive": "Archivar",
|
||||
"documents.archiveConfirm": "¿Archivar este documento?",
|
||||
"documents.archiving": "Archivando…",
|
||||
"documents.archiveNow": "Confirmar archivo",
|
||||
"documents.markdown.copy": "Copiar",
|
||||
"documents.markdown.copied": "Copiado",
|
||||
"documents.markdown.footnotes": "Notas al pie"
|
||||
},
|
||||
"fr": {
|
||||
"nav.documents": "Documents",
|
||||
"documents.title": "Documents du projet",
|
||||
"documents.description": "Documents d'espace de travail recherchés à la demande et archivés une fois pleins.",
|
||||
"documents.capacity": "{used} / {limit}",
|
||||
"documents.summary": "Résumé du stockage documentaire",
|
||||
"documents.active": "Actifs",
|
||||
"documents.activeHint": "Portée de recherche proche",
|
||||
"documents.archivedCount": "Archives",
|
||||
"documents.archivedHint": "Exclus de la capacité active",
|
||||
"documents.activeCapacity": "Capacité active",
|
||||
"documents.capacityHint": "Calculée sur la taille réelle des fichiers UTF-8",
|
||||
"documents.searchAria": "Rechercher dans les Documents du projet",
|
||||
"documents.searchPlaceholder": "Rechercher des documents…",
|
||||
"documents.search": "Rechercher",
|
||||
"documents.scope": "Portée des documents",
|
||||
"documents.new": "Nouveau",
|
||||
"documents.newTitle": "Créer un document géré",
|
||||
"documents.editTitle": "Modifier le document actif",
|
||||
"documents.editorHint": "Les métadonnées et révisions sont gérées automatiquement ; les fichiers sources restent intacts.",
|
||||
"documents.managedCopy": "Copie gérée",
|
||||
"documents.name": "Titre",
|
||||
"documents.routing": "Description de récupération",
|
||||
"documents.sources": "Chemins sources",
|
||||
"documents.sourcesPlaceholder": "src/index.ts, docs/architecture.md",
|
||||
"documents.markdown": "Contenu Markdown",
|
||||
"documents.saving": "Enregistrement…",
|
||||
"documents.create": "Créer",
|
||||
"documents.save": "Enregistrer",
|
||||
"documents.created": "Document actif créé.",
|
||||
"documents.createdAfterArchive": "{count} ancien(s) document(s) archivé(s), puis document actif créé.",
|
||||
"documents.updated": "Nouvelle révision du document enregistrée.",
|
||||
"documents.updatedAfterArchive": "{count} ancien(s) document(s) archivé(s), puis révision enregistrée.",
|
||||
"documents.archived": "Index froid Mnemon créé et document archivé ; Espaces de mémoire : {spaces}",
|
||||
"documents.archivedLocally": "Archivé localement : l'original a été déplacé vers les archives, sans index froid Mnemon.",
|
||||
"documents.list": "Liste des Documents du projet",
|
||||
"documents.activeList": "Répertoire actif",
|
||||
"documents.archiveList": "Répertoire d'archives",
|
||||
"documents.noDescription": "Aucune description de récupération.",
|
||||
"documents.missing": "Fichier manquant",
|
||||
"documents.emptyActive": "Aucun document actif",
|
||||
"documents.emptyActiveText": "Les tâches complexes sont révisées dès que le seuil de score d'activité est atteint, ou vous pouvez créer un document ci-dessus.",
|
||||
"documents.emptyArchived": "Aucune archive",
|
||||
"documents.emptyArchivedText": "Seuls les documents disposant d'un index Mnemon complet sont déplacés ici.",
|
||||
"documents.reader": "Lecteur de document",
|
||||
"documents.selectTitle": "Sélectionner un document",
|
||||
"documents.selectText": "Consultez les connaissances actives du projet ou suivez une référence Mnemon vers un original archivé.",
|
||||
"documents.coldArchive": "Original archivé",
|
||||
"documents.edit": "Modifier",
|
||||
"documents.delete": "Supprimer",
|
||||
"documents.deleteConfirm": "Supprimer définitivement ce document ?",
|
||||
"documents.deleteDescription": "Supprime définitivement la copie gérée ; les fichiers du projet et les notes d'Espaces de mémoire restent intacts. Cette action est irréversible.",
|
||||
"documents.deleteNow": "Confirmer la suppression",
|
||||
"documents.deleting": "Suppression…",
|
||||
"documents.deleted": "Document supprimé définitivement.",
|
||||
"documents.path": "Chemin géré",
|
||||
"documents.revision": "Révision",
|
||||
"documents.hash": "Empreinte du contenu",
|
||||
"documents.size": "Taille du fichier",
|
||||
"documents.archiveReceipt": "Reçu d'index froid Mnemon",
|
||||
"documents.archiveNote": "Note d'archivage",
|
||||
"documents.archiveTitle": "Déplacer vers les archives",
|
||||
"documents.archiveDescription": "Indexer un résumé dans les Espaces de mémoire et déplacer le texte complet vers les archives.",
|
||||
"documents.archive": "Archiver",
|
||||
"documents.archiveConfirm": "Archiver ce document ?",
|
||||
"documents.archiving": "Archivage…",
|
||||
"documents.archiveNow": "Confirmer l'archivage",
|
||||
"documents.markdown.copy": "Copier",
|
||||
"documents.markdown.copied": "Copié",
|
||||
"documents.markdown.footnotes": "Notes de bas de page"
|
||||
},
|
||||
"de": {
|
||||
"nav.documents": "Dokumente",
|
||||
"documents.title": "Projektdokumente",
|
||||
"documents.description": "Arbeitsbereich-Dokumente, die bei Bedarf durchsucht und bei voller Kapazität archiviert werden.",
|
||||
"documents.capacity": "{used} / {limit}",
|
||||
"documents.summary": "Übersicht der Dokumentspeicherung",
|
||||
"documents.active": "Aktiv",
|
||||
"documents.activeHint": "Nahbereichs-Suchumfang",
|
||||
"documents.archivedCount": "Archiv",
|
||||
"documents.archivedHint": "Von der aktiven Kapazität ausgenommen",
|
||||
"documents.activeCapacity": "Aktive Kapazität",
|
||||
"documents.capacityHint": "Gemessen an den tatsächlichen UTF-8-Dateien",
|
||||
"documents.searchAria": "Projektdokumente durchsuchen",
|
||||
"documents.searchPlaceholder": "Dokumente durchsuchen…",
|
||||
"documents.search": "Suchen",
|
||||
"documents.scope": "Dokumentbereich",
|
||||
"documents.new": "Neu",
|
||||
"documents.newTitle": "Verwaltetes Dokument erstellen",
|
||||
"documents.editTitle": "Aktives Dokument bearbeiten",
|
||||
"documents.editorHint": "Metadaten und Revisionen werden automatisch verwaltet; Quelldateien bleiben unverändert.",
|
||||
"documents.managedCopy": "Verwaltete Kopie",
|
||||
"documents.name": "Titel",
|
||||
"documents.routing": "Abrufbeschreibung",
|
||||
"documents.sources": "Quellpfade",
|
||||
"documents.sourcesPlaceholder": "src/index.ts, docs/architecture.md",
|
||||
"documents.markdown": "Markdown-Inhalt",
|
||||
"documents.saving": "Wird gespeichert…",
|
||||
"documents.create": "Erstellen",
|
||||
"documents.save": "Speichern",
|
||||
"documents.created": "Aktives Dokument erstellt.",
|
||||
"documents.createdAfterArchive": "{count} ältere Dokumente archiviert, dann aktives Dokument erstellt.",
|
||||
"documents.updated": "Neue Dokumentrevision gespeichert.",
|
||||
"documents.updatedAfterArchive": "{count} ältere Dokumente archiviert, dann Revision gespeichert.",
|
||||
"documents.archived": "Mnemon-Kaltindex erstellt und Dokument archiviert; Speicherbereiche: {spaces}",
|
||||
"documents.archivedLocally": "Lokal archiviert: Das Original wurde ohne Mnemon-Kaltindex ins Archiv verschoben.",
|
||||
"documents.list": "Liste der Projektdokumente",
|
||||
"documents.activeList": "Aktives Verzeichnis",
|
||||
"documents.archiveList": "Archivverzeichnis",
|
||||
"documents.noDescription": "Keine Abrufbeschreibung.",
|
||||
"documents.missing": "Datei fehlt",
|
||||
"documents.emptyActive": "Noch keine aktiven Dokumente",
|
||||
"documents.emptyActiveText": "Komplexe Arbeiten werden geprüft, sobald sie die Aktivitätsschwelle erreichen, oder Sie können oben ein Dokument erstellen.",
|
||||
"documents.emptyArchived": "Noch keine Archive",
|
||||
"documents.emptyArchivedText": "Nur Dokumente mit vollständigem Mnemon-Index werden hierher verschoben.",
|
||||
"documents.reader": "Dokumentanzeige",
|
||||
"documents.selectTitle": "Dokument auswählen",
|
||||
"documents.selectText": "Lesen Sie aktives Projektwissen oder folgen Sie einer Mnemon-Referenz zu einem archivierten Original.",
|
||||
"documents.coldArchive": "Archiviertes Original",
|
||||
"documents.edit": "Bearbeiten",
|
||||
"documents.delete": "Löschen",
|
||||
"documents.deleteConfirm": "Dieses Dokument dauerhaft löschen?",
|
||||
"documents.deleteDescription": "Entfernt die verwaltete Kopie dauerhaft; Projektdateien und Notizen in Speicherbereichen bleiben unberührt. Dies kann nicht rückgängig gemacht werden.",
|
||||
"documents.deleteNow": "Löschen bestätigen",
|
||||
"documents.deleting": "Wird gelöscht…",
|
||||
"documents.deleted": "Dokument dauerhaft gelöscht.",
|
||||
"documents.path": "Verwalteter Pfad",
|
||||
"documents.revision": "Revision",
|
||||
"documents.hash": "Inhalts-Hash",
|
||||
"documents.size": "Dateigröße",
|
||||
"documents.archiveReceipt": "Mnemon-Kaltindex-Quittung",
|
||||
"documents.archiveNote": "Archivnotiz",
|
||||
"documents.archiveTitle": "Ins Archiv verschieben",
|
||||
"documents.archiveDescription": "Zusammenfassung in Speicherbereichen indizieren und Volltext ins Archiv verschieben.",
|
||||
"documents.archive": "Archivieren",
|
||||
"documents.archiveConfirm": "Dieses Dokument archivieren?",
|
||||
"documents.archiving": "Wird archiviert…",
|
||||
"documents.archiveNow": "Archivierung bestätigen",
|
||||
"documents.markdown.copy": "Kopieren",
|
||||
"documents.markdown.copied": "Kopiert",
|
||||
"documents.markdown.footnotes": "Fußnoten"
|
||||
},
|
||||
"ru": {
|
||||
"nav.documents": "Документы",
|
||||
"documents.title": "Документы проекта",
|
||||
"documents.description": "Документы рабочей области с поиском по запросу и автоматической архивацией при заполнении.",
|
||||
"documents.capacity": "{used} / {limit}",
|
||||
"documents.summary": "Сводка хранилища документов",
|
||||
"documents.active": "Активные",
|
||||
"documents.activeHint": "Область быстрого поиска",
|
||||
"documents.archivedCount": "Архив",
|
||||
"documents.archivedHint": "Не учитываются в активном объёме",
|
||||
"documents.activeCapacity": "Активный объём",
|
||||
"documents.capacityHint": "Рассчитывается по фактическим файлам UTF-8",
|
||||
"documents.searchAria": "Поиск по документам проекта",
|
||||
"documents.searchPlaceholder": "Поиск документов…",
|
||||
"documents.search": "Поиск",
|
||||
"documents.scope": "Область документов",
|
||||
"documents.new": "Создать",
|
||||
"documents.newTitle": "Создать управляемый документ",
|
||||
"documents.editTitle": "Редактировать активный документ",
|
||||
"documents.editorHint": "Метаданные и ревизии ведутся автоматически; исходные файлы не затрагиваются.",
|
||||
"documents.managedCopy": "Управляемая копия",
|
||||
"documents.name": "Заголовок",
|
||||
"documents.routing": "Описание для поиска",
|
||||
"documents.sources": "Пути к источникам",
|
||||
"documents.sourcesPlaceholder": "src/index.ts, docs/architecture.md",
|
||||
"documents.markdown": "Содержимое Markdown",
|
||||
"documents.saving": "Сохранение…",
|
||||
"documents.create": "Создать",
|
||||
"documents.save": "Сохранить",
|
||||
"documents.created": "Активный документ создан.",
|
||||
"documents.createdAfterArchive": "Старые документы отправлены в архив ({count}), затем создан активный документ.",
|
||||
"documents.updated": "Сохранена новая ревизия документа.",
|
||||
"documents.updatedAfterArchive": "Старые документы отправлены в архив ({count}), затем сохранена ревизия.",
|
||||
"documents.archived": "Создан холодный индекс Mnemon, документ заархивирован; Пространства памяти: {spaces}",
|
||||
"documents.archivedLocally": "Заархивировано локально: оригинал перемещён в архив без холодного индекса Mnemon.",
|
||||
"documents.list": "Список документов проекта",
|
||||
"documents.activeList": "Каталог активных",
|
||||
"documents.archiveList": "Каталог архива",
|
||||
"documents.noDescription": "Нет описания для поиска.",
|
||||
"documents.missing": "Файл отсутствует",
|
||||
"documents.emptyActive": "Активных документов пока нет",
|
||||
"documents.emptyActiveText": "Сложная работа проверяется после достижения порога активности, либо вы можете создать Документ выше.",
|
||||
"documents.emptyArchived": "Архивов пока нет",
|
||||
"documents.emptyArchivedText": "Сюда переносятся только документы с завершённым индексом Mnemon.",
|
||||
"documents.reader": "Просмотр документа",
|
||||
"documents.selectTitle": "Выберите документ",
|
||||
"documents.selectText": "Читайте активные знания проекта или перейдите по ссылке Mnemon к архивному оригиналу.",
|
||||
"documents.coldArchive": "Архивный оригинал",
|
||||
"documents.edit": "Редактировать",
|
||||
"documents.delete": "Удалить",
|
||||
"documents.deleteConfirm": "Удалить этот документ навсегда?",
|
||||
"documents.deleteDescription": "Управляемая копия будет удалена навсегда; файлы проекта и заметки в Пространствах памяти не затронутся. Это действие нельзя отменить.",
|
||||
"documents.deleteNow": "Подтвердить удаление",
|
||||
"documents.deleting": "Удаление…",
|
||||
"documents.deleted": "Документ удалён навсегда.",
|
||||
"documents.path": "Управляемый путь",
|
||||
"documents.revision": "Ревизия",
|
||||
"documents.hash": "Хеш содержимого",
|
||||
"documents.size": "Размер файла",
|
||||
"documents.archiveReceipt": "Квитанция холодного индекса Mnemon",
|
||||
"documents.archiveNote": "Примечание к архиву",
|
||||
"documents.archiveTitle": "Переместить в архив",
|
||||
"documents.archiveDescription": "Проиндексировать сводку в Пространствах памяти и переместить полный текст в архив.",
|
||||
"documents.archive": "В архив",
|
||||
"documents.archiveConfirm": "Архивировать этот документ?",
|
||||
"documents.archiving": "Архивация…",
|
||||
"documents.archiveNow": "Подтвердить архивацию",
|
||||
"documents.markdown.copy": "Копировать",
|
||||
"documents.markdown.copied": "Скопировано",
|
||||
"documents.markdown.footnotes": "Сноски"
|
||||
},
|
||||
"pt": {
|
||||
"nav.documents": "Documentos",
|
||||
"documents.title": "Documentos do projeto",
|
||||
"documents.description": "Documentos do espaço de trabalho pesquisados sob demanda e arquivados quando atingem o limite.",
|
||||
"documents.capacity": "{used} / {limit}",
|
||||
"documents.summary": "Resumo do armazenamento de documentos",
|
||||
"documents.active": "Ativos",
|
||||
"documents.activeHint": "Escopo de pesquisa imediata",
|
||||
"documents.archivedCount": "Arquivo",
|
||||
"documents.archivedHint": "Fora da capacidade ativa",
|
||||
"documents.activeCapacity": "Capacidade ativa",
|
||||
"documents.capacityHint": "Medida a partir dos arquivos UTF-8 reais",
|
||||
"documents.searchAria": "Pesquisar documentos do projeto",
|
||||
"documents.searchPlaceholder": "Pesquisar documentos…",
|
||||
"documents.search": "Pesquisar",
|
||||
"documents.scope": "Escopo de documentos",
|
||||
"documents.new": "Novo",
|
||||
"documents.newTitle": "Criar documento gerenciado",
|
||||
"documents.editTitle": "Editar documento ativo",
|
||||
"documents.editorHint": "Metadados e revisões são gerenciados automaticamente; os arquivos de origem não são alterados.",
|
||||
"documents.managedCopy": "Cópia gerenciada",
|
||||
"documents.name": "Título",
|
||||
"documents.routing": "Descrição de recuperação",
|
||||
"documents.sources": "Caminhos de origem",
|
||||
"documents.sourcesPlaceholder": "src/index.ts, docs/architecture.md",
|
||||
"documents.markdown": "Conteúdo Markdown",
|
||||
"documents.saving": "Salvando…",
|
||||
"documents.create": "Criar",
|
||||
"documents.save": "Salvar",
|
||||
"documents.created": "Documento ativo criado.",
|
||||
"documents.createdAfterArchive": "{count} documento(s) antigo(s) arquivado(s) e documento ativo criado.",
|
||||
"documents.updated": "Nova revisão do documento salva.",
|
||||
"documents.updatedAfterArchive": "{count} documento(s) antigo(s) arquivado(s) e revisão salva.",
|
||||
"documents.archived": "Índice frio do Mnemon criado e documento arquivado; Espaços de memória: {spaces}",
|
||||
"documents.archivedLocally": "Arquivado localmente: o original foi movido para o arquivo, sem índice frio do Mnemon.",
|
||||
"documents.list": "Lista de documentos do projeto",
|
||||
"documents.activeList": "Diretório ativo",
|
||||
"documents.archiveList": "Diretório de arquivo",
|
||||
"documents.noDescription": "Sem descrição de recuperação.",
|
||||
"documents.missing": "Arquivo ausente",
|
||||
"documents.emptyActive": "Ainda não há documentos ativos",
|
||||
"documents.emptyActiveText": "Trabalhos complexos são revisados após atingir o limiar de atividade, ou você pode criar um Documento acima.",
|
||||
"documents.emptyArchived": "Ainda não há arquivos",
|
||||
"documents.emptyArchivedText": "Apenas documentos com índice do Mnemon concluído são movidos para cá.",
|
||||
"documents.reader": "Leitor de documentos",
|
||||
"documents.selectTitle": "Selecione um documento",
|
||||
"documents.selectText": "Leia o conhecimento ativo do projeto ou siga uma referência do Mnemon até o original arquivado.",
|
||||
"documents.coldArchive": "Original arquivado",
|
||||
"documents.edit": "Editar",
|
||||
"documents.delete": "Excluir",
|
||||
"documents.deleteConfirm": "Excluir este documento permanentemente?",
|
||||
"documents.deleteDescription": "Remove permanentemente a cópia gerenciada; os arquivos do projeto e as notas dos Espaços de memória permanecem intactos. Esta ação não pode ser desfeita.",
|
||||
"documents.deleteNow": "Confirmar exclusão",
|
||||
"documents.deleting": "Excluindo…",
|
||||
"documents.deleted": "Documento excluído permanentemente.",
|
||||
"documents.path": "Caminho gerenciado",
|
||||
"documents.revision": "Revisão",
|
||||
"documents.hash": "Hash do conteúdo",
|
||||
"documents.size": "Tamanho do arquivo",
|
||||
"documents.archiveReceipt": "Recibo do índice frio do Mnemon",
|
||||
"documents.archiveNote": "Nota de arquivamento",
|
||||
"documents.archiveTitle": "Mover para o arquivo",
|
||||
"documents.archiveDescription": "Indexa um resumo nos Espaços de memória e move o texto completo para o arquivo.",
|
||||
"documents.archive": "Arquivar",
|
||||
"documents.archiveConfirm": "Arquivar este documento?",
|
||||
"documents.archiving": "Arquivando…",
|
||||
"documents.archiveNow": "Confirmar arquivamento",
|
||||
"documents.markdown.copy": "Copiar",
|
||||
"documents.markdown.copied": "Copiado",
|
||||
"documents.markdown.footnotes": "Notas de rodapé"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,224 @@
|
|||
.documentSummary { display: grid; grid-template-columns: .7fr .7fr 1.6fr; gap: 12px; margin-bottom: 14px; }
|
||||
.documentSummary article { display: flex; min-width: 0; min-height: 88px; flex-direction: column; padding: 14px 16px; border: .5px solid var(--mn-card-line); border-radius: var(--dsw-radius-lg); }
|
||||
.documentSummary article > span { display: block; color: var(--mn-faint); font-size: 12px; line-height: 18px; }
|
||||
.documentSummary article > strong { display: block; margin: 4px 0 2px; font-size: 20px; font-weight: 500; line-height: 28px; font-variant-numeric: tabular-nums; }
|
||||
.documentSummary article > small { margin-top: auto; color: var(--mn-faint); font-size: 12px; line-height: 18px; }
|
||||
.documentCapacity > div { height: 4px; margin: 8px 0 6px; overflow: hidden; border-radius: 999px; background: var(--mn-fill); }
|
||||
.documentCapacity > div i { display: block; height: 100%; border-radius: inherit; background: var(--dsw-alias-brand-primary); transition: width .3s ease; }
|
||||
|
||||
.documentToolbar { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
|
||||
.documentToolbar form { display: flex; min-width: 260px; flex: 1; align-items: center; gap: 8px; }
|
||||
.documentToolbar form > button { min-height: 36px; }
|
||||
.documentSearch { flex: 1; }
|
||||
.documentEditor input,
|
||||
.documentEditor textarea { width: 100%; border: .5px solid var(--mn-field-line); border-radius: var(--dsw-radius-md); outline: 0; padding: 6px 10px; color: var(--mn-text); background: var(--mn-input); font-size: 13px; line-height: 20px; }
|
||||
.documentEditor input:focus,
|
||||
.documentEditor textarea:focus { border-color: var(--mn-accent); }
|
||||
/* Filter, matching DSH SegmentedControl sliding indicator mechanics. */
|
||||
.documentToolbar > div {
|
||||
--dsh-segment-count: 2;
|
||||
--dsh-segment-index: 0;
|
||||
position: relative;
|
||||
display: inline-grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: 1fr;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 4px;
|
||||
border-radius: var(--dsw-radius-md);
|
||||
background: var(--mn-hover);
|
||||
}
|
||||
.documentToolbar > div::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
width: calc((100% - 8px - 2px * (var(--dsh-segment-count) - 1)) / var(--dsh-segment-count));
|
||||
height: calc(100% - 8px);
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
background: var(--mn-layer-1);
|
||||
box-shadow: var(--dsw-elevation-soft);
|
||||
transform: translateX(calc(var(--dsh-segment-index) * (100% + 2px)));
|
||||
transition: transform 160ms cubic-bezier(.22, 1, .36, 1);
|
||||
pointer-events: none;
|
||||
}
|
||||
.documentToolbar > div button {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
height: 28px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
padding: 0 12px;
|
||||
color: var(--mn-muted);
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: color 120ms ease;
|
||||
}
|
||||
.documentToolbar > div button:hover,
|
||||
.documentToolbar > div button[data-active] { color: var(--mn-text); }
|
||||
.documentToolbar > div button:focus-visible { outline: var(--dsw-focus-ring-width, 2px) solid var(--mn-focus); outline-offset: -2px; }
|
||||
.documentToolbar > div b { margin-left: 6px; color: var(--mn-faint); font-size: 12px; font-weight: 400; line-height: 1; font-variant-numeric: tabular-nums; }
|
||||
|
||||
.documentWorkspace { display: grid; min-height: 590px; grid-template-columns: minmax(250px, 310px) minmax(0, 1fr); gap: 12px; }
|
||||
.documentList,
|
||||
.documentReader { min-width: 0; overflow: hidden; border: .5px solid var(--mn-card-line); border-radius: var(--dsw-radius-lg); }
|
||||
.documentList { align-self: stretch; padding-bottom: 8px; }
|
||||
.documentList > header { display: flex; min-height: 44px; align-items: center; justify-content: space-between; padding: 0 14px; border-bottom: .5px solid var(--mn-line); color: var(--mn-faint); font-size: 12px; line-height: 18px; }
|
||||
.documentList > header code { color: var(--mn-muted); font-variant-numeric: tabular-nums; }
|
||||
.documentList > button { --mn-provider-color: var(--mn-faint); display: block; width: calc(100% - 12px); margin: 6px 6px 0; border: 0; border-radius: var(--dsw-radius-md); padding: 10px 12px; color: var(--mn-text); background: transparent; text-align: left; cursor: pointer; transition: background-color .15s; }
|
||||
.documentList > button:hover { background: var(--mn-hover); }
|
||||
.documentList > button[data-selected] { background: var(--mn-fill); }
|
||||
.documentList > button > div { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.documentList > button strong { overflow: hidden; font-size: 13px; font-weight: 500; line-height: 20px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.documentList > button time { flex: 0 0 auto; color: var(--mn-faint); font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||
.documentList > button p { display: -webkit-box; margin: 4px 0 6px; overflow: hidden; color: var(--mn-faint); font-size: 12px; line-height: 18px; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
|
||||
.documentList > button footer { display: flex; align-items: center; gap: 8px; color: var(--mn-faint); font-size: 11px; line-height: 16px; font-variant-numeric: tabular-nums; }
|
||||
.documentList > button footer code { margin-left: auto; }
|
||||
.documentList > button footer em { color: var(--mn-danger); font-style: normal; }
|
||||
.documentListEmpty { display: grid; min-height: 230px; place-items: center; align-content: center; gap: 4px; padding: 24px; color: var(--mn-muted); text-align: center; }
|
||||
.documentListEmpty > span { margin-bottom: 6px; color: var(--mn-faint); font-size: 24px; line-height: 1; }
|
||||
.documentListEmpty p { margin: 0; color: var(--mn-faint); font-size: 12px; line-height: 18px; }
|
||||
|
||||
.documentReader { padding: clamp(16px, 2vw, 24px); }
|
||||
.documentReader > .emptyState { height: 100%; border: 0; background: transparent; }
|
||||
.documentReader > .loading { display: flex; height: 100%; min-height: 240px; align-items: center; justify-content: center; gap: 8px; }
|
||||
.documentReader > .loading [class*='sectionSpinner'] { position: static; }
|
||||
.documentDetail > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding-bottom: 14px; border-bottom: .5px solid var(--mn-line); }
|
||||
.documentDetail > header > div:first-child > span { display: inline-flex; height: 20px; align-items: center; margin-bottom: 4px; padding: 0 8px; border-radius: 999px; color: var(--mn-muted); background: var(--mn-fill); font-size: 11px; font-weight: 500; line-height: 1; }
|
||||
.documentDetail > header h3 { margin: 2px 0; font-size: 16px; font-weight: 500; line-height: 24px; }
|
||||
.documentDetail > header p { margin: 0; color: var(--mn-faint); font-size: 12px; line-height: 18px; }
|
||||
.documentActions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
|
||||
.documentDetail > dl { display: grid; grid-template-columns: 2fr .45fr .8fr .55fr; margin: 12px 0 4px; border: 0; border-radius: var(--dsw-radius-md); background: var(--mn-block-fill); overflow: hidden; }
|
||||
.documentDetail > dl > div { min-width: 0; padding: 8px 12px; }
|
||||
.documentDetail > dl > div + div { border-left: .5px solid var(--mn-line); }
|
||||
.documentDetail dt { margin-bottom: 2px; color: var(--mn-faint); font-size: 11px; line-height: 16px; }
|
||||
.documentDetail dd { margin: 0; overflow: hidden; font-family: var(--mn-code); font-size: 12px; line-height: 18px; text-overflow: ellipsis; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.documentDetail dd code { font-size: inherit; }
|
||||
.documentDetail dd [data-path-label] { font-size: inherit; line-height: inherit; }
|
||||
.documentSources { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 12px 0; }
|
||||
.documentSources > span { margin-right: 4px; color: var(--mn-faint); font-size: 12px; }
|
||||
.documentSources code,
|
||||
.documentArchiveReceipt code { display: inline-flex; height: 20px; max-width: 100%; align-items: center; padding: 0 8px; border-radius: 999px; color: var(--mn-muted); background: var(--mn-fill); font-size: 11px; line-height: 1; }
|
||||
.markdownBody { min-height: 280px; margin: 14px 0 0; overflow-wrap: anywhere; padding: 4px 0 0; border: 0; border-radius: 0; color: var(--mn-text); font-size: 14px; line-height: 1.75; }
|
||||
.markdownBody > :first-child { margin-top: 0; }
|
||||
.markdownBody > :last-child { margin-bottom: 0; }
|
||||
.markdownBody h1,
|
||||
.markdownBody h2,
|
||||
.markdownBody h3,
|
||||
.markdownBody h4 { margin: 1.5em 0 .6em; color: var(--mn-text); font-weight: 500; line-height: 1.35; }
|
||||
.markdownBody h1 { padding-bottom: .35em; border-bottom: .5px solid var(--mn-line); font-size: 1.6em; }
|
||||
.markdownBody h2 { padding-bottom: .3em; border-bottom: .5px solid var(--mn-line); font-size: 1.35em; }
|
||||
.markdownBody h3 { font-size: 1.15em; }
|
||||
.markdownBody p,
|
||||
.markdownBody ul,
|
||||
.markdownBody ol,
|
||||
.markdownBody blockquote,
|
||||
.markdownBody table,
|
||||
.markdownBody pre { margin: .85em 0; }
|
||||
.markdownBody ul,
|
||||
.markdownBody ol { padding-left: 1.6em; }
|
||||
.markdownBody li + li { margin-top: .3em; }
|
||||
.markdownBody blockquote { margin-inline: 0; padding: .1em 1em; border-left: 2px solid var(--mn-line-strong); color: var(--mn-muted); }
|
||||
.markdownBody code { padding: .15em .4em; border-radius: var(--dsw-radius-xs); color: var(--mn-text); background: var(--dsw-alias-markdown-inline-code, var(--mn-fill)); font: .88em/1.55 var(--mn-code); }
|
||||
.markdownBody pre { max-width: 100%; overflow: auto; padding: 12px 16px; border-radius: var(--dsw-radius-md); background: var(--dsw-alias-markdown-code-block, var(--mn-fill)); }
|
||||
.markdownBody pre code { padding: 0; background: transparent; font-size: 12px; }
|
||||
.markdownBody a { color: var(--dsw-alias-link, var(--mn-accent)); text-decoration-thickness: 1px; text-underline-offset: 3px; }
|
||||
.markdownBody hr { margin: 1.8em 0; border: 0; border-top: .5px solid var(--mn-line); }
|
||||
.markdownBody table { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }
|
||||
.markdownBody th,
|
||||
.markdownBody td { padding: 8px 10px; border: .5px solid var(--mn-line); text-align: left; vertical-align: top; }
|
||||
.markdownBody th { background: var(--mn-fill); font-weight: 500; }
|
||||
.markdownBody img { max-width: 100%; height: auto; border-radius: var(--dsw-radius-sm); }
|
||||
.documentArchiveReceipt { margin: 12px 0; padding: 10px 12px; border-radius: var(--dsw-radius-md); background: color-mix(in srgb, var(--mn-success) 8%, transparent); }
|
||||
.documentArchiveReceipt p { margin: 2px 0 8px; color: var(--mn-muted); font-size: 12px; line-height: 18px; }
|
||||
.documentArchiveReceipt div { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.documentDanger { display: flex; min-height: 56px; align-items: center; justify-content: flex-end; gap: 8px; margin-top: 12px; padding-top: 12px; border-top: .5px solid var(--mn-line); }
|
||||
.documentDanger > div { margin-right: auto; }
|
||||
.documentDanger strong { display: block; font-size: 13px; font-weight: 500; line-height: 20px; }
|
||||
.documentDanger p { margin: 2px 0 0; color: var(--mn-faint); font-size: 12px; line-height: 18px; }
|
||||
.documentDanger > span { margin-right: auto; color: var(--mn-danger); font-size: 12px; }
|
||||
|
||||
.documentEditor { margin-bottom: 12px; padding: 16px; border: .5px solid var(--mn-card-line); border-radius: var(--dsw-radius-lg); }
|
||||
.documentReader > .documentEditor { margin: 0; border: 0; padding: 0; background: transparent; }
|
||||
.documentEditor > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 12px; }
|
||||
.documentEditor h3 { margin: 0; font-size: 14px; font-weight: 500; line-height: 22px; }
|
||||
.documentEditor header p { margin: 2px 0 0; color: var(--mn-faint); font-size: 12px; line-height: 18px; }
|
||||
.documentEditor header > span,
|
||||
.documentEditor header > code { padding: 1px 8px; border-radius: 999px; color: var(--mn-muted); background: var(--mn-fill); font-size: 11px; font-weight: 500; line-height: 17px; }
|
||||
.documentEditor label { display: grid; gap: 6px; margin-top: 12px; color: var(--mn-muted); font-size: 12px; font-weight: 500; line-height: 18px; }
|
||||
.documentEditor textarea { resize: vertical; line-height: 1.65; }
|
||||
.documentEditorMeta { display: grid; grid-template-columns: .8fr 1.2fr; gap: 12px; }
|
||||
.documentEditorMeta label { margin: 0; }
|
||||
.documentEditor footer { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; }
|
||||
|
||||
@container mnemon-workbench (max-width: 880px) {
|
||||
.documentWorkspace { grid-template-columns: minmax(220px, 270px) minmax(0, 1fr); }
|
||||
.documentDetail > dl { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.documentDetail > dl > div + div { border-left: 0; }
|
||||
.documentDetail > dl > div:nth-child(even) { border-left: .5px solid var(--mn-line); }
|
||||
.documentDetail > dl > div:nth-child(n + 3) { border-top: .5px solid var(--mn-line); }
|
||||
}
|
||||
|
||||
@container mnemon-workbench (max-width: 640px) {
|
||||
.documentSummary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.documentCapacity { grid-column: 1 / -1; }
|
||||
.documentToolbar { align-items: stretch; flex-direction: column; }
|
||||
.documentToolbar form { min-width: 0; }
|
||||
.documentToolbar > div,
|
||||
.documentToolbar > button { width: 100%; }
|
||||
.documentToolbar > div button { flex: 1; }
|
||||
.documentWorkspace { min-height: 0; grid-template-columns: 1fr; }
|
||||
.documentList { max-height: 330px; overflow: auto; -webkit-overflow-scrolling: touch; }
|
||||
.documentReader { min-height: 430px; }
|
||||
.documentEditorMeta { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
.documentWorkspace { grid-template-columns: minmax(220px, 270px) minmax(0, 1fr); }
|
||||
.documentDetail > dl { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.documentDetail > dl > div + div { border-left: 0; }
|
||||
.documentDetail > dl > div:nth-child(even) { border-left: .5px solid var(--mn-line); }
|
||||
.documentDetail > dl > div:nth-child(n + 3) { border-top: .5px solid var(--mn-line); }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.documentSummary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.documentCapacity { grid-column: 1 / -1; }
|
||||
.documentToolbar { align-items: stretch; flex-direction: column; }
|
||||
.documentToolbar form { min-width: 0; }
|
||||
.documentToolbar > div,
|
||||
.documentToolbar > button { width: 100%; }
|
||||
.documentToolbar > div button { flex: 1; }
|
||||
.documentWorkspace { min-height: 0; grid-template-columns: 1fr; }
|
||||
.documentList { max-height: 330px; overflow: auto; -webkit-overflow-scrolling: touch; }
|
||||
.documentReader { min-height: 430px; }
|
||||
.documentEditorMeta { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.documentDetail > header,
|
||||
.documentDanger { align-items: flex-start; flex-direction: column; }
|
||||
.documentDetail > header > div:last-child,
|
||||
.documentDetail > header button { width: 100%; }
|
||||
.documentDanger > div,
|
||||
.documentDanger > span { margin-right: 0; }
|
||||
.documentDanger > button { width: 100%; }
|
||||
.documentDetail > dl { grid-template-columns: 1fr; }
|
||||
.documentDetail > dl > div:nth-child(even) { border-left: 0; }
|
||||
.documentDetail > dl > div + div { border-top: .5px solid var(--mn-line); }
|
||||
.markdownBody { padding: 4px 0 0; font-size: 13px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.documentCapacity > div i,
|
||||
.documentToolbar > div::before,
|
||||
.documentToolbar > div button,
|
||||
.documentList > button { transition: none; }
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
.shell .modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: min(86vh, 760px);
|
||||
max-height: min(86dvh, 760px);
|
||||
overflow: hidden;
|
||||
}
|
||||
.shell .modal > [class*='modalBody'] {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.shell .modal > [class*='modalFooter'] {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 0 0 auto;
|
||||
background: var(--dsw-alias-bg-layer-2, var(--mn-surface));
|
||||
}
|
||||
.shell .modal form[class*='documentEditor'] {
|
||||
flex-shrink: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
}
|
||||
.shell .modal form[class*='documentEditor'] > header { display: none; }
|
||||
|
||||
.shell [class*='documentWorkspace'] {
|
||||
height: clamp(420px, calc(100dvh - var(--dsh-frame-top-clearance, 0px) - 344px), 720px);
|
||||
min-height: 420px;
|
||||
align-items: stretch;
|
||||
}
|
||||
.shell [class*='documentList'],
|
||||
.shell [class*='documentReader'] {
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
@container mnemon-workbench (max-width: 640px) {
|
||||
.shell [class*='documentWorkspace'] { height: auto; min-height: 0; }
|
||||
.shell [class*='documentList'] { overflow-y: auto; scrollbar-gutter: auto; }
|
||||
.shell [class*='documentReader'] { overflow: visible; scrollbar-gutter: auto; }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.shell [class*='documentWorkspace'] { height: auto; min-height: 0; }
|
||||
.shell [class*='documentList'] { overflow-y: auto; scrollbar-gutter: auto; }
|
||||
.shell [class*='documentReader'] { overflow: visible; scrollbar-gutter: auto; }
|
||||
}
|
||||
|
|
@ -0,0 +1,563 @@
|
|||
import { Z as MemoryComponentSettingsProps, bt as MnemonKey, et as MemoryComponentUIContext, ft as installMemorySourceUI, gt as MnemonSourceManagementClient, ht as MemorySourcePageProps, xt as MnemonTranslate } from "../../../lib/client-extension-sdk-BX83D8r5.js";
|
||||
import { JSX, ReactNode } from "react";
|
||||
type MemoryProviderId = string;
|
||||
declare const NATIVE_PROVIDER_ID = "mnemon-native";
|
||||
type MemoryProviderConnectionValue = string | number | boolean;
|
||||
type MemoryProviderConnection = Record<string, MemoryProviderConnectionValue>;
|
||||
interface MemoryProviderIcon {
|
||||
kind: 'brand' | 'data-url' | 'glyph';
|
||||
value: string;
|
||||
}
|
||||
interface MemoryProviderConfigOption {
|
||||
value: string;
|
||||
label: string;
|
||||
i18nKey?: string;
|
||||
}
|
||||
interface MemoryProviderConfigField {
|
||||
key: string;
|
||||
label: string;
|
||||
i18nKey?: string;
|
||||
scope: 'service' | 'memory';
|
||||
role?: 'global-location';
|
||||
input: 'text' | 'url' | 'secret' | 'number' | 'boolean' | 'select' | 'path';
|
||||
required: boolean;
|
||||
defaultValue?: MemoryProviderConnectionValue;
|
||||
placeholder?: string;
|
||||
help?: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
maxLength?: number;
|
||||
pattern?: string;
|
||||
normalize?: 'trim-trailing-slash';
|
||||
validationMessage?: string;
|
||||
discoveryDefaultFrom?: string;
|
||||
options?: MemoryProviderConfigOption[];
|
||||
}
|
||||
declare const MEMORY_PLACEMENT_CAPABILITIES: readonly ["graph", "entities", "related", "exact-write", "link", "forget"];
|
||||
type MemoryPlacementCapability = (typeof MEMORY_PLACEMENT_CAPABILITIES)[number];
|
||||
type MemoryPlacementPreference = 'balanced' | 'local-first' | 'shared-first';
|
||||
interface MemoryPlacementRules {
|
||||
allowedProviderIds?: MemoryProviderId[];
|
||||
dataBoundary?: 'allow-remote' | 'local-only';
|
||||
requiredCapabilities?: MemoryPlacementCapability[];
|
||||
preference?: MemoryPlacementPreference;
|
||||
}
|
||||
interface MemoryPersistenceStrategy {
|
||||
mode?: 'manual' | 'automatic';
|
||||
providerId?: MemoryProviderId;
|
||||
prompt?: string;
|
||||
rules?: MemoryPlacementRules;
|
||||
providerConnections?: Partial<Record<MemoryProviderId, MemoryProviderConnection>>;
|
||||
}
|
||||
interface ResolvedMemoryPersistenceStrategy {
|
||||
mode: 'manual' | 'automatic';
|
||||
providerId: MemoryProviderId;
|
||||
providerDefaulted?: true;
|
||||
prompt: string;
|
||||
rules: {
|
||||
allowedProviderIds: MemoryProviderId[];
|
||||
dataBoundary: 'allow-remote' | 'local-only';
|
||||
requiredCapabilities: MemoryPlacementCapability[];
|
||||
preference: MemoryPlacementPreference;
|
||||
};
|
||||
providerConnections: Partial<Record<MemoryProviderId, MemoryProviderConnection>>;
|
||||
}
|
||||
interface AutomaticMemoryPlacementRequest {
|
||||
mode: 'automatic';
|
||||
prompt?: string;
|
||||
rules?: MemoryPlacementRules;
|
||||
}
|
||||
interface MemoryPlacementDecision {
|
||||
mode: 'automatic';
|
||||
providerId: MemoryProviderId;
|
||||
decidedBy: 'rules' | 'llm';
|
||||
reason: string;
|
||||
confidence: 'high' | 'medium' | 'low';
|
||||
candidateProviderIds: MemoryProviderId[];
|
||||
appliedRules: string[];
|
||||
decidedAt: string;
|
||||
runId?: string;
|
||||
subagentProvider?: string;
|
||||
}
|
||||
interface MemoryProviderCapabilities {
|
||||
search: boolean;
|
||||
browse: boolean;
|
||||
graph: boolean;
|
||||
entities: boolean;
|
||||
related: boolean;
|
||||
remember: boolean;
|
||||
link: boolean;
|
||||
forget: boolean;
|
||||
writeMode: 'exact' | 'async-extracting';
|
||||
deletionMode: 'soft' | 'hard' | 'unsupported';
|
||||
}
|
||||
interface MemoryProviderDescriptor {
|
||||
typeId?: string;
|
||||
id: MemoryProviderId;
|
||||
label: string;
|
||||
icon?: MemoryProviderIcon;
|
||||
kind: 'local' | 'remote';
|
||||
workspaceBinding: 'automatic' | 'optional-override' | 'provider-global';
|
||||
summary: string;
|
||||
summaryI18nKey?: string;
|
||||
origin: 'native' | 'third-party';
|
||||
capabilities: MemoryProviderCapabilities;
|
||||
fields: MemoryProviderConfigField[];
|
||||
serviceConfigured?: boolean;
|
||||
}
|
||||
interface MemoryProviderRuntimeStatus {
|
||||
providerId: MemoryProviderId;
|
||||
label: string;
|
||||
icon?: MemoryProviderIcon;
|
||||
enabled: boolean;
|
||||
configured: boolean;
|
||||
status: 'disabled' | 'idle' | 'healthy' | 'unhealthy';
|
||||
memoryBodyCount: number;
|
||||
activeMemoryBodyCount: number;
|
||||
error?: string;
|
||||
}
|
||||
interface MemorySpaceProvider {
|
||||
id: MemoryProviderId;
|
||||
typeId?: string;
|
||||
label: string;
|
||||
icon?: MemoryProviderIcon;
|
||||
origin?: 'native' | 'third-party';
|
||||
kind: 'local' | 'remote';
|
||||
location: string;
|
||||
targetUri?: string;
|
||||
account?: string;
|
||||
user?: string;
|
||||
actorPeerId?: string;
|
||||
apiKeyConfigured: boolean;
|
||||
settings: MemoryProviderConnection;
|
||||
configuredSecrets: string[];
|
||||
capabilities: MemoryProviderCapabilities;
|
||||
}
|
||||
interface OpenVikingSpaceConnection {
|
||||
endpoint: string;
|
||||
targetUri: string;
|
||||
apiKey?: string;
|
||||
account?: string;
|
||||
user?: string;
|
||||
actorPeerId?: string;
|
||||
}
|
||||
interface MemorySpace {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
active: boolean;
|
||||
dbPath: string;
|
||||
provider: MemorySpaceProvider;
|
||||
placement?: MemoryPlacementDecision;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
interface CreateMemorySpaceRequest {
|
||||
name: string;
|
||||
description: string;
|
||||
active?: boolean;
|
||||
providerId?: MemoryProviderId;
|
||||
connection?: MemoryProviderConnection;
|
||||
providerConnections?: Partial<Record<MemoryProviderId, MemoryProviderConnection>>;
|
||||
openViking?: OpenVikingSpaceConnection;
|
||||
placement?: AutomaticMemoryPlacementRequest;
|
||||
}
|
||||
interface UpdateMemorySpaceRequest {
|
||||
name?: string;
|
||||
description?: string;
|
||||
active?: boolean;
|
||||
connection?: MemoryProviderConnection;
|
||||
clearSecrets?: string[];
|
||||
openViking?: Partial<OpenVikingSpaceConnection> & {
|
||||
clearApiKey?: boolean;
|
||||
};
|
||||
}
|
||||
interface MemorySpaceMetadataUpdate {
|
||||
memoryBodyId: string;
|
||||
title: string;
|
||||
description: string;
|
||||
}
|
||||
interface MemorySpaceMetadataMaintenanceResult {
|
||||
delegated: true;
|
||||
runId: string;
|
||||
provider: string;
|
||||
summary: string;
|
||||
updates: MemorySpaceMetadataUpdate[];
|
||||
}
|
||||
type Category = 'preference' | 'decision' | 'fact' | 'insight' | 'context' | 'general';
|
||||
type Source = 'user' | 'agent' | 'external';
|
||||
type EdgeType = 'temporal' | 'semantic' | 'causal' | 'entity';
|
||||
type Intent = 'WHY' | 'WHEN' | 'ENTITY' | 'GENERAL';
|
||||
type RecallRelevanceTier = 'high' | 'medium' | 'ranked' | 'low' | 'unknown';
|
||||
interface Insight {
|
||||
id: string;
|
||||
content: string;
|
||||
category?: string;
|
||||
importance?: number;
|
||||
tags?: string[];
|
||||
entities?: string[];
|
||||
source?: string;
|
||||
score?: number;
|
||||
normalizedScore?: number;
|
||||
relevanceTier?: RecallRelevanceTier;
|
||||
federatedScore?: number;
|
||||
confidence?: string;
|
||||
intent?: string;
|
||||
matchedVia?: string;
|
||||
createdAt?: string;
|
||||
depth?: number;
|
||||
edgeType?: string;
|
||||
memoryBodyId?: string;
|
||||
memoryBodyName?: string;
|
||||
memoryProviderId?: MemoryProviderId;
|
||||
memoryProviderLabel?: string;
|
||||
memoryCapabilities?: MemoryProviderCapabilities;
|
||||
externalUri?: string;
|
||||
}
|
||||
interface SearchRequest {
|
||||
query: string;
|
||||
mode?: 'smart' | 'keyword' | 'basic';
|
||||
limit?: number;
|
||||
category?: Category;
|
||||
source?: Source;
|
||||
intent?: Intent;
|
||||
memoryBodyIds?: string[];
|
||||
inspect?: boolean;
|
||||
}
|
||||
interface RememberRequest {
|
||||
content: string;
|
||||
category?: Category;
|
||||
importance?: number;
|
||||
tags?: string[];
|
||||
entities?: string[];
|
||||
source?: Source;
|
||||
memoryBodyId?: string;
|
||||
}
|
||||
interface MemorySpaceStats {
|
||||
totalInsights: number;
|
||||
deletedInsights: number;
|
||||
edgeCount: number;
|
||||
oplogCount: number;
|
||||
dbSizeBytes: number;
|
||||
byCategory: Record<string, number>;
|
||||
topEntities: Array<{
|
||||
entity: string;
|
||||
count: number;
|
||||
}>;
|
||||
}
|
||||
interface MemorySpaceView extends MemorySpace {
|
||||
mnemonDefault: boolean;
|
||||
providerEnabled?: boolean;
|
||||
healthy: boolean;
|
||||
statusLoading?: boolean;
|
||||
error?: string;
|
||||
stats?: MemorySpaceStats;
|
||||
}
|
||||
interface MemorySpaceWriteScope {
|
||||
viewId: string;
|
||||
sourceInstanceKey: string;
|
||||
memoryBodyIds: string[];
|
||||
}
|
||||
interface MemorySpaceCatalog {
|
||||
items: MemorySpaceView[];
|
||||
providers: MemoryProviderDescriptor[];
|
||||
persistenceStrategy?: Omit<ResolvedMemoryPersistenceStrategy, 'providerConnections'>;
|
||||
total: number;
|
||||
activeCount: number;
|
||||
directory: string;
|
||||
generatedAt: string;
|
||||
writeScope?: MemorySpaceWriteScope;
|
||||
rediscovery?: {
|
||||
running: boolean;
|
||||
last?: MemorySpaceRediscovery;
|
||||
};
|
||||
}
|
||||
interface MemorySpaceRediscoveryResult {
|
||||
providerId: MemoryProviderId;
|
||||
label: string;
|
||||
found: number;
|
||||
added: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
}>;
|
||||
disconnected: number;
|
||||
error?: string;
|
||||
timedOut?: boolean;
|
||||
}
|
||||
interface MemorySpaceRediscovery {
|
||||
at: string;
|
||||
trigger: 'startup' | 'manual';
|
||||
results: MemorySpaceRediscoveryResult[];
|
||||
}
|
||||
interface MemoryGraphNode extends Insight {
|
||||
color: string;
|
||||
graphId?: string;
|
||||
kind?: 'memory' | 'entity' | 'space';
|
||||
memoryBodyIds?: string[];
|
||||
memoryBodyNames?: string[];
|
||||
occurrenceCount?: number;
|
||||
}
|
||||
interface MemoryGraphEdge {
|
||||
sourceId: string;
|
||||
targetId: string;
|
||||
label: string;
|
||||
color: string;
|
||||
type?: EdgeType | 'scope';
|
||||
}
|
||||
interface MemoryGraphSnapshot {
|
||||
nodes: MemoryGraphNode[];
|
||||
edges: MemoryGraphEdge[];
|
||||
generatedAt: string;
|
||||
memoryBodies?: Array<Pick<MemorySpace, 'id' | 'name' | 'active'>>;
|
||||
sources?: MemoryReadSource[];
|
||||
}
|
||||
type MemoryReadMode = 'search' | 'graph' | 'projection' | 'enumerable' | 'query-only' | 'entities' | 'unsupported';
|
||||
type MemoryReadStatus = 'ready' | 'empty' | 'query-required' | 'unsupported' | 'unavailable' | 'loading';
|
||||
interface MemoryReadSource {
|
||||
memoryBodyId: string;
|
||||
memoryBodyName: string;
|
||||
providerId: MemoryProviderId;
|
||||
providerLabel: string;
|
||||
mode: MemoryReadMode;
|
||||
status: MemoryReadStatus;
|
||||
itemCount: number;
|
||||
edgeCount?: number;
|
||||
memoryCount?: number;
|
||||
complete?: boolean;
|
||||
hint?: string;
|
||||
quality?: RecallQualityStats;
|
||||
}
|
||||
interface RecallQualityStats {
|
||||
policyId: string;
|
||||
fallbackFrom?: string;
|
||||
fetched: number;
|
||||
retained: number;
|
||||
selected: number;
|
||||
droppedLowScore: number;
|
||||
droppedNonPositiveScore: number;
|
||||
droppedInvalidScore: number;
|
||||
unscored: number;
|
||||
unscaled: number;
|
||||
ranked?: number;
|
||||
outOfRange?: number;
|
||||
}
|
||||
interface MemoryListRequest {
|
||||
query?: string;
|
||||
category?: Category;
|
||||
limit?: number;
|
||||
memoryBodyIds?: string[];
|
||||
}
|
||||
interface MemoryListView {
|
||||
items: MemoryGraphNode[];
|
||||
total: number;
|
||||
generatedAt: string;
|
||||
sources?: MemoryReadSource[];
|
||||
}
|
||||
interface ResolvedRecallQualityConfig {
|
||||
policy: string;
|
||||
lowScoreThreshold: number;
|
||||
highScoreThreshold: number;
|
||||
candidateMultiplier: number;
|
||||
maxMediumResults: number;
|
||||
maxRankedResults: number;
|
||||
maxUnknownResults: number;
|
||||
}
|
||||
interface MemorySpacesStatus {
|
||||
healthy: boolean;
|
||||
error?: string;
|
||||
version?: string;
|
||||
cliPath: string;
|
||||
commandFound: boolean;
|
||||
dataDir: string;
|
||||
store: string;
|
||||
mnemonDefaultStore: string;
|
||||
dshActiveStores: string[];
|
||||
writeEnabled: boolean;
|
||||
timeoutMs: number;
|
||||
defaultRecallLimit: number;
|
||||
recallQuality: ResolvedRecallQualityConfig;
|
||||
embeddingManaged?: boolean;
|
||||
memoryBodyDirectory: string;
|
||||
memoryBodies: MemorySpaceView[];
|
||||
providerServices?: MemoryProviderRuntimeStatus[];
|
||||
stats?: MemorySpaceStats & {
|
||||
dbPath?: string;
|
||||
};
|
||||
}
|
||||
interface EntityView {
|
||||
items: Array<{
|
||||
entity: string;
|
||||
count: number;
|
||||
}>;
|
||||
insights: Insight[];
|
||||
selected?: string;
|
||||
sources?: MemoryReadSource[];
|
||||
total?: number;
|
||||
complete?: boolean;
|
||||
}
|
||||
interface EntityMemoriesView {
|
||||
entity: string;
|
||||
total: number;
|
||||
offset: number;
|
||||
items: Insight[];
|
||||
complete: boolean;
|
||||
sources: MemoryReadSource[];
|
||||
}
|
||||
interface EntityRelatedView {
|
||||
entity: string;
|
||||
items: Insight[];
|
||||
sources: MemoryReadSource[];
|
||||
}
|
||||
interface MemorySpacesPageClient {
|
||||
bodies(): Promise<MemorySpaceCatalog>;
|
||||
bodyDirectory(): Promise<MemorySpaceCatalog>;
|
||||
graph(memoryBodyIds?: string[]): Promise<MemoryGraphSnapshot>;
|
||||
list(request?: MemoryListRequest): Promise<MemoryListView>;
|
||||
entities(entity?: string, limit?: number): Promise<EntityView>;
|
||||
entityMemories?(entity: string, offset?: number, limit?: number): Promise<EntityMemoriesView>;
|
||||
entityRelated?(entity: string, limit?: number, view?: string): Promise<EntityRelatedView>;
|
||||
search(request: SearchRequest): Promise<SearchResponse>;
|
||||
agentSearch(request: SearchRequest): Promise<AgentSearchResponse>;
|
||||
related(id: string, memoryBodyId?: string): Promise<Insight[]>;
|
||||
remember(request: RememberRequest): Promise<Record<string, unknown>>;
|
||||
supervise(content: string, idempotencyKey?: string): Promise<{
|
||||
delegated: true;
|
||||
sessionId: string;
|
||||
runId: string;
|
||||
provider: string;
|
||||
summary: string;
|
||||
action: string;
|
||||
memoryBodyIds: string[];
|
||||
unembedded?: Array<{
|
||||
memoryBodyId?: string;
|
||||
id?: string;
|
||||
}>;
|
||||
}>;
|
||||
forget(id: string, memoryBodyId?: string): Promise<Record<string, unknown>>;
|
||||
createBody(request: CreateMemorySpaceRequest): Promise<MemorySpace>;
|
||||
updateBody(memoryBodyId: string, request: UpdateMemorySpaceRequest): Promise<MemorySpace>;
|
||||
reconnectBody(memoryBodyId: string): Promise<MemorySpaceView>;
|
||||
maintainBodyMetadata(memoryBodyIds: string[]): Promise<MemorySpaceMetadataMaintenanceResult>;
|
||||
deleteBody(memoryBodyId: string): Promise<MemorySpace>;
|
||||
rediscoverBodies?(): Promise<MemorySpaceRediscovery>;
|
||||
}
|
||||
interface SearchResponse {
|
||||
results: Insight[];
|
||||
sources?: MemoryReadSource[];
|
||||
}
|
||||
interface AgentSearchResponse extends SearchResponse {
|
||||
answer: string;
|
||||
citations: string[];
|
||||
delegation: {
|
||||
runId: string;
|
||||
};
|
||||
}
|
||||
declare function OverviewPage(props: {
|
||||
client: MemorySpacesPageClient;
|
||||
active?: boolean;
|
||||
metadataClient: MemorySpacesPageClient;
|
||||
revision: number;
|
||||
reloadKey?: number;
|
||||
activationEnabled: boolean;
|
||||
writeEnabled: boolean;
|
||||
agentAvailable: boolean;
|
||||
fallbackBodies: MemorySpaceView[];
|
||||
fallbackDirectory: string | undefined;
|
||||
catalogKnown: boolean;
|
||||
onMutate: () => void;
|
||||
onAgentRefresh: () => void;
|
||||
onBodyReconnect: (body: MemorySpaceView) => void;
|
||||
onBodyMetadata: (updates: readonly MemorySpaceMetadataUpdate[]) => void;
|
||||
onExplore: (query: string) => void;
|
||||
onOpenSettings?: ((section?: string) => void) | undefined;
|
||||
}): JSX.Element;
|
||||
interface MemorySpacesPageStatus {
|
||||
defaultRecallLimit?: number;
|
||||
}
|
||||
declare function ExplorePage(props: {
|
||||
client: MemorySpacesPageClient;
|
||||
agentClient: MemorySpacesPageClient;
|
||||
agentAvailable: boolean;
|
||||
status: MemorySpacesPageStatus | null;
|
||||
seed: string;
|
||||
writeEnabled: boolean;
|
||||
onForget: (insight: Insight) => Promise<void>;
|
||||
onRevealElement?(element: HTMLElement): void;
|
||||
}): JSX.Element;
|
||||
declare function EntitiesPage(props: {
|
||||
client: MemorySpacesPageClient;
|
||||
revision: number;
|
||||
writeEnabled: boolean;
|
||||
onForget: (insight: Insight) => Promise<void>;
|
||||
onExplore: (query: string) => void;
|
||||
}): JSX.Element;
|
||||
interface MemoryPlacementSettings {
|
||||
setPath(path: string[], value: unknown): Promise<void>;
|
||||
}
|
||||
interface MemoryPlacementPageConfig {
|
||||
persistenceStrategy?: MemoryPersistenceStrategy;
|
||||
}
|
||||
declare function PersistenceStrategyDialog(props: {
|
||||
client: MemorySpacesPageClient;
|
||||
settingsScope: MemoryPlacementSettings;
|
||||
config: MemoryPlacementPageConfig | undefined;
|
||||
writable: boolean;
|
||||
agentAvailable: boolean;
|
||||
onClose: () => void;
|
||||
}): JSX.Element;
|
||||
declare function RememberPage(props: {
|
||||
client: MemorySpacesPageClient;
|
||||
agentAvailable: boolean;
|
||||
memoryBodies: MemorySpaceView[];
|
||||
writeEnabled: boolean;
|
||||
seed: string;
|
||||
embeddingManaged?: boolean | undefined;
|
||||
onMutate: () => void;
|
||||
onClose: () => void;
|
||||
onView?: () => void;
|
||||
}): JSX.Element;
|
||||
declare function ListPage(props: {
|
||||
client: MemorySpacesPageClient;
|
||||
revision: number;
|
||||
writeEnabled: boolean;
|
||||
onForget: (insight: Insight) => Promise<void>;
|
||||
onClone: (insight: Insight) => void;
|
||||
onExplore: (query: string) => void;
|
||||
}): JSX.Element;
|
||||
declare function nativeSpaceProvider(provider: MemorySpaceProvider): boolean;
|
||||
/** @deprecated Use nativeSpaceProvider. */
|
||||
declare const nativeBodyProvider: typeof nativeSpaceProvider;
|
||||
declare function memorySpacesPageClient(management: MnemonSourceManagementClient): MemorySpacesPageClient & {
|
||||
status(): Promise<MemorySpacesStatus>;
|
||||
canAssist(operation: string): boolean;
|
||||
};
|
||||
type Page = 'spaces' | 'explore' | 'entities' | 'remember' | 'content';
|
||||
declare function MemorySpacesSourcePage(props: MemorySourcePageProps & {
|
||||
page: Page;
|
||||
}): ReactNode;
|
||||
declare function installMemorySpacesUI(ctx: Parameters<typeof installMemorySourceUI>[0], t?: MnemonTranslate): () => void;
|
||||
declare const inject: string[];
|
||||
declare function apply(ctx: Parameters<typeof installMemorySourceUI>[0] & MemoryComponentUIContext): void;
|
||||
interface DshLocale {
|
||||
bind(namespace: 'mnemon'): (key: MnemonKey, params?: Record<string, unknown>) => string;
|
||||
getSnapshot?(): DshLocaleSnapshot;
|
||||
subscribe?(listener: () => void): () => void;
|
||||
}
|
||||
interface DshLocaleSnapshot {
|
||||
active: string;
|
||||
locales: readonly {
|
||||
id: string;
|
||||
fallback?: string;
|
||||
}[];
|
||||
}
|
||||
declare function MemorySpacesSettings(props: MemoryComponentSettingsProps & {
|
||||
locale?: DshLocale | undefined;
|
||||
}): ReactNode;
|
||||
interface ProviderIconProps {
|
||||
providerId: MemoryProviderId;
|
||||
icon?: MemoryProviderIcon | undefined;
|
||||
className?: string | undefined;
|
||||
title?: string | undefined;
|
||||
}
|
||||
declare function ProviderIcon({ providerId, icon, className, title }: ProviderIconProps): JSX.Element;
|
||||
export { type AgentSearchResponse, EntitiesPage, ExplorePage, ListPage, type MemoryPlacementPageConfig, type MemoryPlacementSettings, type MemorySpacesPageClient, type MemorySpacesPageStatus, MemorySpacesSettings, MemorySpacesSourcePage, NATIVE_PROVIDER_ID, OverviewPage, PersistenceStrategyDialog, ProviderIcon, type ProviderIconProps, RememberPage, type SearchResponse, apply, inject, installMemorySpacesUI, memorySpacesPageClient, nativeBodyProvider, nativeSpaceProvider };
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,3 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $ as MemoryPlacementCapability, $t as SearchRequest, A as MEMORY_SPACE_DATABASE_FILE, At as MemorySpaceView, B as MemoryBodyMetadataMaintenanceResult, Bt as MnemonEmbeddingStatus, C as INTENTS, Ct as MemorySpaceProvider, D as MEMORY_PLACEMENT_CAPABILITIES, Dt as MemorySpaceRegistryFile, E as LlmMemoryPlacementSelection, Et as MemorySpaceRegistryEntry, F as MNEMON_ACTIVE_STORE_FILE, Ft as MnemonEmbeddingCredential, G as MemoryBodyView, Gt as RecallQualityConfig, H as MemoryBodyMetadataUpdate, Ht as OpenVikingBodyConnection, I as MNEMON_EMBEDDING_PROTOCOLS, It as MnemonEmbeddingFill, J as MemoryGraphSnapshot, Jt as RememberRequest, K as MemoryGraphEdge, Kt as RecallQualityStats, L as MemoryBody, Lt as MnemonEmbeddingProtocol, M as MEMORY_SPACE_ID_PATTERN, Mt as MemorySpaceWriteScopeRequest, N as MEMORY_SPACE_NAME_MAX_LENGTH, Nt as MemorySpacesStatus, O as MEMORY_PROVIDER_REGISTRY_FILE, Ot as MemorySpaceRegistrySummary, P as MEMORY_SPACE_REGISTRY_FILE, Pt as MnemonEmbeddingConfig, Q as MemoryPlacementCandidate, Qt as SOURCES, R as MemoryBodyCatalog, Rt as MnemonEmbeddingSettingsView, S as EntityView, St as MemorySpaceMetadataUpdate, T as Intent, Tt as MemorySpaceRediscoveryResult, U as MemoryBodyProvider, Ut as OpenVikingSpaceConnection, V as MemoryBodyMetadataSample, Vt as NATIVE_PROVIDER_ID, W as MemoryBodyStats, Wt as PreparedMemoryPlacement, X as MemoryListView, Xt as ResolvedMnemonEmbeddingConfig, Y as MemoryListRequest, Yt as ResolvedMemoryPersistenceStrategy, Z as MemoryPersistenceStrategy, Zt as ResolvedRecallQualityConfig, _ as EMBEDDING_PROTOCOL_OLLAMA, _t as MemoryReadStatus, a as CreateMemorySpaceRequest, an as normalizeEntityKey, at as MemoryProviderConfigOption, b as EntityMemoriesView, bt as MemorySpaceMetadataMaintenanceResult, c as DEFAULT_EMBEDDING_PROTOCOL, cn as summarizeMemorySpaceRegistry, ct as MemoryProviderDescriptor, d as DEFAULT_TIMEOUT_MS, dt as MemoryProviderRegistrySummary, en as Source, et as MemoryPlacementDecision, f as EDGE_TYPES, ft as MemoryProviderRuntimeStatus, g as EMBEDDING_PROTOCOL_AUTO, gt as MemoryReadSource, h as EMBEDDING_ENVIRONMENT_NAME, ht as MemoryReadMode, i as CreateMemoryBodyRequest, in as isNativeProvider, it as MemoryProviderConfigField, j as MEMORY_SPACE_DESCRIPTION_MAX_LENGTH, jt as MemorySpaceWriteScope, k as MEMORY_SPACES_DIRECTORY, kt as MemorySpaceStats, l as DEFAULT_RECALL_LIMIT, lt as MemoryProviderIcon, m as EMBEDDING_CREDENTIAL_REFERENCE, mt as MemoryProviderServiceView, n as CATEGORIES, nn as UpdateMemoryProviderServiceRequest, nt as MemoryPlacementRules, o as DEFAULT_EMBEDDING_ENDPOINT, on as parseMemorySpaceRegistry, ot as MemoryProviderConnection, p as EMBEDDING_CREDENTIAL_PREFIX, pt as MemoryProviderServiceCatalog, q as MemoryGraphNode, qt as RecallRelevanceTier, r as Category, rn as UpdateMemorySpaceRequest, rt as MemoryProviderCapabilities, s as DEFAULT_EMBEDDING_MODEL, sn as summarizeMemoryProviderRegistry, st as MemoryProviderConnectionValue, t as AutomaticMemoryPlacementRequest, tn as UpdateMemoryBodyRequest, tt as MemoryPlacementPreference, u as DEFAULT_RECALL_QUALITY_POLICY, ut as MemoryProviderId, v as EMBEDDING_PROTOCOL_OPENAI, vt as MemorySpace, w as Insight, wt as MemorySpaceRediscovery, x as EntityRelatedView, xt as MemorySpaceMetadataSample, y as EdgeType, yt as MemorySpaceCatalog, z as MemoryBodyDirectory, zt as MnemonEmbeddingSpaceStatus } from "../../../lib/contracts-DuGgDm58.js";
|
||||
export { AutomaticMemoryPlacementRequest, CATEGORIES, Category, CreateMemoryBodyRequest, CreateMemorySpaceRequest, DEFAULT_EMBEDDING_ENDPOINT, DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_PROTOCOL, DEFAULT_RECALL_LIMIT, DEFAULT_RECALL_QUALITY_POLICY, DEFAULT_TIMEOUT_MS, EDGE_TYPES, EMBEDDING_CREDENTIAL_PREFIX, EMBEDDING_CREDENTIAL_REFERENCE, EMBEDDING_ENVIRONMENT_NAME, EMBEDDING_PROTOCOL_AUTO, EMBEDDING_PROTOCOL_OLLAMA, EMBEDDING_PROTOCOL_OPENAI, EdgeType, EntityMemoriesView, EntityRelatedView, EntityView, INTENTS, Insight, Intent, type MemoryJsonValue as JsonValue, LlmMemoryPlacementSelection, MEMORY_PLACEMENT_CAPABILITIES, MEMORY_PROVIDER_REGISTRY_FILE, MEMORY_SPACES_DIRECTORY, MEMORY_SPACE_DATABASE_FILE, MEMORY_SPACE_DESCRIPTION_MAX_LENGTH, MEMORY_SPACE_ID_PATTERN, MEMORY_SPACE_NAME_MAX_LENGTH, MEMORY_SPACE_REGISTRY_FILE, MNEMON_ACTIVE_STORE_FILE, MNEMON_EMBEDDING_PROTOCOLS, MemoryBody, MemoryBodyCatalog, MemoryBodyDirectory, MemoryBodyMetadataMaintenanceResult, MemoryBodyMetadataSample, MemoryBodyMetadataUpdate, MemoryBodyProvider, MemoryBodyStats, MemoryBodyView, MemoryGraphEdge, MemoryGraphNode, MemoryGraphSnapshot, MemoryListRequest, MemoryListView, MemoryPersistenceStrategy, MemoryPlacementCandidate, MemoryPlacementCapability, MemoryPlacementDecision, MemoryPlacementPreference, MemoryPlacementRules, MemoryProviderCapabilities, MemoryProviderConfigField, MemoryProviderConfigOption, MemoryProviderConnection, MemoryProviderConnectionValue, MemoryProviderDescriptor, MemoryProviderIcon, MemoryProviderId, MemoryProviderRegistrySummary, MemoryProviderRuntimeStatus, MemoryProviderServiceCatalog, MemoryProviderServiceView, MemoryReadMode, MemoryReadSource, MemoryReadStatus, MemorySpace, MemorySpaceCatalog, MemorySpaceMetadataMaintenanceResult, MemorySpaceMetadataSample, MemorySpaceMetadataUpdate, MemorySpaceProvider, MemorySpaceRediscovery, MemorySpaceRediscoveryResult, MemorySpaceRegistryEntry, MemorySpaceRegistryFile, MemorySpaceRegistrySummary, MemorySpaceStats, MemorySpaceView, MemorySpaceWriteScope, MemorySpaceWriteScopeRequest, MemorySpacesStatus, MnemonEmbeddingConfig, MnemonEmbeddingCredential, MnemonEmbeddingFill, MnemonEmbeddingProtocol, MnemonEmbeddingSettingsView, MnemonEmbeddingSpaceStatus, MnemonEmbeddingStatus, NATIVE_PROVIDER_ID, OpenVikingBodyConnection, OpenVikingSpaceConnection, PreparedMemoryPlacement, RecallQualityConfig, RecallQualityStats, RecallRelevanceTier, RememberRequest, ResolvedMemoryPersistenceStrategy, ResolvedMnemonEmbeddingConfig, ResolvedRecallQualityConfig, SOURCES, SearchRequest, Source, UpdateMemoryBodyRequest, UpdateMemoryProviderServiceRequest, UpdateMemorySpaceRequest, isNativeProvider, normalizeEntityKey, parseMemorySpaceRegistry, summarizeMemoryProviderRegistry, summarizeMemorySpaceRegistry };
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-memory-spaces/src/contracts.ts
|
||||
const NATIVE_PROVIDER_ID = "mnemon-native";
|
||||
const DEFAULT_TIMEOUT_MS = 1e4;
|
||||
const DEFAULT_RECALL_LIMIT = 10;
|
||||
const DEFAULT_RECALL_QUALITY_POLICY = "strict-v1";
|
||||
function isNativeProvider(provider) {
|
||||
return (provider.typeId ?? provider.id) === NATIVE_PROVIDER_ID;
|
||||
}
|
||||
const MEMORY_PLACEMENT_CAPABILITIES = [
|
||||
"graph",
|
||||
"entities",
|
||||
"related",
|
||||
"exact-write",
|
||||
"link",
|
||||
"forget"
|
||||
];
|
||||
const CATEGORIES = [
|
||||
"preference",
|
||||
"decision",
|
||||
"fact",
|
||||
"insight",
|
||||
"context",
|
||||
"general"
|
||||
];
|
||||
const SOURCES = [
|
||||
"user",
|
||||
"agent",
|
||||
"external"
|
||||
];
|
||||
const EDGE_TYPES = [
|
||||
"temporal",
|
||||
"semantic",
|
||||
"causal",
|
||||
"entity"
|
||||
];
|
||||
const INTENTS = [
|
||||
"WHY",
|
||||
"WHEN",
|
||||
"ENTITY",
|
||||
"GENERAL"
|
||||
];
|
||||
function normalizeEntityKey(entity) {
|
||||
return entity.normalize("NFKC").trim().toLocaleLowerCase();
|
||||
}
|
||||
const DEFAULT_EMBEDDING_ENDPOINT = "http://localhost:11434";
|
||||
const DEFAULT_EMBEDDING_MODEL = "nomic-embed-text";
|
||||
const EMBEDDING_PROTOCOL_AUTO = "auto";
|
||||
const EMBEDDING_PROTOCOL_OLLAMA = "ollama";
|
||||
const EMBEDDING_PROTOCOL_OPENAI = "openai";
|
||||
const DEFAULT_EMBEDDING_PROTOCOL = EMBEDDING_PROTOCOL_AUTO;
|
||||
const MNEMON_EMBEDDING_PROTOCOLS = [
|
||||
EMBEDDING_PROTOCOL_AUTO,
|
||||
EMBEDDING_PROTOCOL_OLLAMA,
|
||||
EMBEDDING_PROTOCOL_OPENAI
|
||||
];
|
||||
const EMBEDDING_CREDENTIAL_PREFIX = "dsh-brain-mnemon/embedding-";
|
||||
const EMBEDDING_CREDENTIAL_REFERENCE = /^dsh-brain-mnemon\/embedding-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
|
||||
const EMBEDDING_ENVIRONMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u;
|
||||
const MEMORY_SPACES_DIRECTORY = "data";
|
||||
const MEMORY_SPACE_REGISTRY_FILE = ".dsh-memory-bodies.json";
|
||||
const MEMORY_SPACE_DATABASE_FILE = "mnemon.db";
|
||||
const MEMORY_SPACE_ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
|
||||
const MEMORY_SPACE_NAME_MAX_LENGTH = 100;
|
||||
const MEMORY_SPACE_DESCRIPTION_MAX_LENGTH = 1e3;
|
||||
const MNEMON_ACTIVE_STORE_FILE = "active";
|
||||
const MEMORY_PROVIDER_REGISTRY_FILE = "memory-providers.json";
|
||||
function isObject(value) {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
function parseMemorySpaceRegistry(value) {
|
||||
const registry = isObject(value) ? value : void 0;
|
||||
if (registry?.version !== 1 || !Array.isArray(registry.bodies)) throw new Error("Memory Space registry is invalid");
|
||||
const ids = /* @__PURE__ */ new Set();
|
||||
return {
|
||||
version: 1,
|
||||
bodies: registry.bodies.map((raw) => {
|
||||
const body = isObject(raw) ? raw : void 0;
|
||||
if (typeof body?.id !== "string" || !MEMORY_SPACE_ID_PATTERN.test(body.id) || ids.has(body.id)) throw new Error("Memory Space registry contains an invalid or duplicate id");
|
||||
if (typeof body.name !== "string" || body.name.trim() === "" || body.name.length > 100 || typeof body.description !== "string" || body.description.length > 1e3) throw new Error("Memory Space registry contains invalid metadata");
|
||||
if (typeof body.createdAt !== "string" || typeof body.updatedAt !== "string") throw new Error("Memory Space registry contains invalid timestamps");
|
||||
ids.add(body.id);
|
||||
return {
|
||||
id: body.id,
|
||||
name: body.name,
|
||||
description: body.description,
|
||||
active: body.active === true,
|
||||
createdAt: body.createdAt,
|
||||
updatedAt: body.updatedAt
|
||||
};
|
||||
})
|
||||
};
|
||||
}
|
||||
function summarizeMemorySpaceRegistry(value) {
|
||||
const registry = isObject(value) ? value : void 0;
|
||||
const listed = registry?.bodies;
|
||||
const spaces = Array.isArray(listed) ? listed.filter(isObject) : [];
|
||||
return {
|
||||
valid: registry?.version === 1 && Array.isArray(listed),
|
||||
spaces: spaces.length,
|
||||
active: spaces.filter((space) => space.active === true).length
|
||||
};
|
||||
}
|
||||
function summarizeMemoryProviderRegistry(value) {
|
||||
const registry = isObject(value) ? value : void 0;
|
||||
const services = registry?.services;
|
||||
const listed = registry?.bodies;
|
||||
return {
|
||||
valid: registry !== void 0,
|
||||
services: isObject(services) ? Object.keys(services).length : 0,
|
||||
connections: Array.isArray(listed) ? listed.length : 0
|
||||
};
|
||||
}
|
||||
export { CATEGORIES, DEFAULT_EMBEDDING_ENDPOINT, DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_PROTOCOL, DEFAULT_RECALL_LIMIT, DEFAULT_RECALL_QUALITY_POLICY, DEFAULT_TIMEOUT_MS, EDGE_TYPES, EMBEDDING_CREDENTIAL_PREFIX, EMBEDDING_CREDENTIAL_REFERENCE, EMBEDDING_ENVIRONMENT_NAME, EMBEDDING_PROTOCOL_AUTO, EMBEDDING_PROTOCOL_OLLAMA, EMBEDDING_PROTOCOL_OPENAI, INTENTS, MEMORY_PLACEMENT_CAPABILITIES, MEMORY_PROVIDER_REGISTRY_FILE, MEMORY_SPACES_DIRECTORY, MEMORY_SPACE_DATABASE_FILE, MEMORY_SPACE_DESCRIPTION_MAX_LENGTH, MEMORY_SPACE_ID_PATTERN, MEMORY_SPACE_NAME_MAX_LENGTH, MEMORY_SPACE_REGISTRY_FILE, MNEMON_ACTIVE_STORE_FILE, MNEMON_EMBEDDING_PROTOCOLS, NATIVE_PROVIDER_ID, SOURCES, isNativeProvider, normalizeEntityKey, parseMemorySpaceRegistry, summarizeMemoryProviderRegistry, summarizeMemorySpaceRegistry };
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
import { a as MemoryJsonValue, b as MemoryPluginDescriptor } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import "../../../lib/index-C00l82Ug.js";
|
||||
import { i as MemorySpaceProviderEntry } from "../../../lib/definitions-C41Daez1.js";
|
||||
import { $ as MemoryPlacementCapability, $t as SearchRequest, A as MEMORY_SPACE_DATABASE_FILE, At as MemorySpaceView, B as MemoryBodyMetadataMaintenanceResult, Bt as MnemonEmbeddingStatus, C as INTENTS, Ct as MemorySpaceProvider, D as MEMORY_PLACEMENT_CAPABILITIES, Dt as MemorySpaceRegistryFile, E as LlmMemoryPlacementSelection, Et as MemorySpaceRegistryEntry, F as MNEMON_ACTIVE_STORE_FILE, Ft as MnemonEmbeddingCredential, G as MemoryBodyView, Gt as RecallQualityConfig, H as MemoryBodyMetadataUpdate, Ht as OpenVikingBodyConnection, I as MNEMON_EMBEDDING_PROTOCOLS, It as MnemonEmbeddingFill, J as MemoryGraphSnapshot, Jt as RememberRequest, K as MemoryGraphEdge, Kt as RecallQualityStats, L as MemoryBody, Lt as MnemonEmbeddingProtocol, M as MEMORY_SPACE_ID_PATTERN, Mt as MemorySpaceWriteScopeRequest, N as MEMORY_SPACE_NAME_MAX_LENGTH, Nt as MemorySpacesStatus, O as MEMORY_PROVIDER_REGISTRY_FILE, Ot as MemorySpaceRegistrySummary, P as MEMORY_SPACE_REGISTRY_FILE, Pt as MnemonEmbeddingConfig, Q as MemoryPlacementCandidate, Qt as SOURCES, R as MemoryBodyCatalog, Rt as MnemonEmbeddingSettingsView, S as EntityView, St as MemorySpaceMetadataUpdate, T as Intent, Tt as MemorySpaceRediscoveryResult, U as MemoryBodyProvider, Ut as OpenVikingSpaceConnection, V as MemoryBodyMetadataSample, Vt as NATIVE_PROVIDER_ID, W as MemoryBodyStats, Wt as PreparedMemoryPlacement, X as MemoryListView, Xt as ResolvedMnemonEmbeddingConfig, Y as MemoryListRequest, Yt as ResolvedMemoryPersistenceStrategy, Z as MemoryPersistenceStrategy, Zt as ResolvedRecallQualityConfig, _ as EMBEDDING_PROTOCOL_OLLAMA, _t as MemoryReadStatus, a as CreateMemorySpaceRequest, an as normalizeEntityKey, at as MemoryProviderConfigOption, b as EntityMemoriesView, bt as MemorySpaceMetadataMaintenanceResult, c as DEFAULT_EMBEDDING_PROTOCOL, cn as summarizeMemorySpaceRegistry, ct as MemoryProviderDescriptor, d as DEFAULT_TIMEOUT_MS, dt as MemoryProviderRegistrySummary, en as Source, et as MemoryPlacementDecision, f as EDGE_TYPES, ft as MemoryProviderRuntimeStatus, g as EMBEDDING_PROTOCOL_AUTO, gt as MemoryReadSource, h as EMBEDDING_ENVIRONMENT_NAME, ht as MemoryReadMode, i as CreateMemoryBodyRequest, in as isNativeProvider, it as MemoryProviderConfigField, j as MEMORY_SPACE_DESCRIPTION_MAX_LENGTH, jt as MemorySpaceWriteScope, k as MEMORY_SPACES_DIRECTORY, kt as MemorySpaceStats, l as DEFAULT_RECALL_LIMIT, lt as MemoryProviderIcon, m as EMBEDDING_CREDENTIAL_REFERENCE, mt as MemoryProviderServiceView, n as CATEGORIES, nn as UpdateMemoryProviderServiceRequest, nt as MemoryPlacementRules, o as DEFAULT_EMBEDDING_ENDPOINT, on as parseMemorySpaceRegistry, ot as MemoryProviderConnection, p as EMBEDDING_CREDENTIAL_PREFIX, pt as MemoryProviderServiceCatalog, q as MemoryGraphNode, qt as RecallRelevanceTier, r as Category, rn as UpdateMemorySpaceRequest, rt as MemoryProviderCapabilities, s as DEFAULT_EMBEDDING_MODEL, sn as summarizeMemoryProviderRegistry, st as MemoryProviderConnectionValue, t as AutomaticMemoryPlacementRequest, tn as UpdateMemoryBodyRequest, tt as MemoryPlacementPreference, u as DEFAULT_RECALL_QUALITY_POLICY, ut as MemoryProviderId, v as EMBEDDING_PROTOCOL_OPENAI, vt as MemorySpace, w as Insight, wt as MemorySpaceRediscovery, x as EntityRelatedView, xt as MemorySpaceMetadataSample, y as EdgeType, yt as MemorySpaceCatalog, z as MemoryBodyDirectory, zt as MnemonEmbeddingSpaceStatus } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { Context } from "@deepseek-ai/cordis";
|
||||
import z from "@deepseek-ai/schemastery";
|
||||
interface MemorySpacesConfig {
|
||||
dataDir?: string;
|
||||
cliPath?: string;
|
||||
store?: string;
|
||||
timeoutMs?: number;
|
||||
defaultRecallLimit?: number;
|
||||
writeEnabled?: boolean;
|
||||
bm25IndexPush?: boolean;
|
||||
embedding?: MnemonEmbeddingConfig;
|
||||
recallQuality?: RecallQualityConfig;
|
||||
persistenceStrategy?: MemoryPersistenceStrategy;
|
||||
}
|
||||
interface ResolvedMemorySpacesConfig {
|
||||
storageScope: 'global' | 'workspace' | 'custom';
|
||||
dataDir?: string;
|
||||
cliPath?: string;
|
||||
store?: string;
|
||||
timeoutMs: number;
|
||||
defaultRecallLimit: number;
|
||||
writeEnabled: boolean;
|
||||
bm25IndexPush: boolean;
|
||||
embedding: ResolvedMnemonEmbeddingConfig;
|
||||
recallQuality: ResolvedRecallQualityConfig;
|
||||
persistenceStrategy: ResolvedMemoryPersistenceStrategy;
|
||||
}
|
||||
declare const MemorySpacesConfig: z<MemorySpacesConfig>;
|
||||
declare function resolvePersistenceStrategy(value: MemoryPersistenceStrategy | undefined): ResolvedMemorySpacesConfig['persistenceStrategy'];
|
||||
declare function resolveEmbedding(value: MemorySpacesConfig['embedding']): ResolvedMemorySpacesConfig['embedding'];
|
||||
declare function resolveRecallQuality(value: RecallQualityConfig | undefined): ResolvedMemorySpacesConfig['recallQuality'];
|
||||
declare const name = "dsh-brain-mnemon-source-memory-spaces";
|
||||
declare const inject: string[];
|
||||
declare const memoryPlugin: MemoryPluginDescriptor;
|
||||
interface Config extends MemorySpacesConfig {
|
||||
providers: Array<string | MemorySpaceProviderDeclaration>;
|
||||
}
|
||||
declare const MemorySpaceProviderDeclarationSchema: z<MemorySpaceProviderDeclaration>;
|
||||
declare const Config: z<Config>;
|
||||
interface InstallMemorySpacesOptions {
|
||||
config?: MemorySpacesConfig;
|
||||
instanceId?: string;
|
||||
}
|
||||
interface MemorySpaceProviderDeclaration {
|
||||
use: string;
|
||||
instanceId?: string;
|
||||
config?: unknown;
|
||||
}
|
||||
declare function resolveMemorySpaceProviderEntries(ctx: Context, declarations: readonly (string | MemorySpaceProviderDeclaration)[]): Promise<MemorySpaceProviderEntry[]>;
|
||||
declare function installMemorySpaces(ctx: Context, entries: readonly MemorySpaceProviderEntry[], options?: InstallMemorySpacesOptions): Promise<void>;
|
||||
declare function apply(ctx: Context, config?: Config): Promise<void>;
|
||||
export { type AutomaticMemoryPlacementRequest, type CATEGORIES, type Category, Config, type CreateMemoryBodyRequest, type CreateMemorySpaceRequest, type DEFAULT_EMBEDDING_ENDPOINT, type DEFAULT_EMBEDDING_MODEL, type DEFAULT_EMBEDDING_PROTOCOL, type DEFAULT_RECALL_LIMIT, type DEFAULT_RECALL_QUALITY_POLICY, type DEFAULT_TIMEOUT_MS, type EDGE_TYPES, type EMBEDDING_CREDENTIAL_PREFIX, type EMBEDDING_CREDENTIAL_REFERENCE, type EMBEDDING_ENVIRONMENT_NAME, type EMBEDDING_PROTOCOL_AUTO, type EMBEDDING_PROTOCOL_OLLAMA, type EMBEDDING_PROTOCOL_OPENAI, type EdgeType, type EntityMemoriesView, type EntityRelatedView, type EntityView, type INTENTS, type Insight, InstallMemorySpacesOptions, type Intent, type MemoryJsonValue as JsonValue, type LlmMemoryPlacementSelection, type MEMORY_PLACEMENT_CAPABILITIES, type MEMORY_PROVIDER_REGISTRY_FILE, type MEMORY_SPACES_DIRECTORY, type MEMORY_SPACE_DATABASE_FILE, type MEMORY_SPACE_DESCRIPTION_MAX_LENGTH, type MEMORY_SPACE_ID_PATTERN, type MEMORY_SPACE_NAME_MAX_LENGTH, type MEMORY_SPACE_REGISTRY_FILE, type MNEMON_ACTIVE_STORE_FILE, type MNEMON_EMBEDDING_PROTOCOLS, type MemoryBody, type MemoryBodyCatalog, type MemoryBodyDirectory, type MemoryBodyMetadataMaintenanceResult, type MemoryBodyMetadataSample, type MemoryBodyMetadataUpdate, type MemoryBodyProvider, type MemoryBodyStats, type MemoryBodyView, type MemoryGraphEdge, type MemoryGraphNode, type MemoryGraphSnapshot, type MemoryListRequest, type MemoryListView, type MemoryPersistenceStrategy, type MemoryPlacementCandidate, type MemoryPlacementCapability, type MemoryPlacementDecision, type MemoryPlacementPreference, type MemoryPlacementRules, type MemoryProviderCapabilities, type MemoryProviderConfigField, type MemoryProviderConfigOption, type MemoryProviderConnection, type MemoryProviderConnectionValue, type MemoryProviderDescriptor, type MemoryProviderIcon, type MemoryProviderId, type MemoryProviderRegistrySummary, type MemoryProviderRuntimeStatus, type MemoryProviderServiceCatalog, type MemoryProviderServiceView, type MemoryReadMode, type MemoryReadSource, type MemoryReadStatus, type MemorySpace, type MemorySpaceCatalog, type MemorySpaceMetadataMaintenanceResult, type MemorySpaceMetadataSample, type MemorySpaceMetadataUpdate, type MemorySpaceProvider, MemorySpaceProviderDeclaration, MemorySpaceProviderDeclarationSchema, type MemorySpaceRediscovery, type MemorySpaceRediscoveryResult, type MemorySpaceRegistryEntry, type MemorySpaceRegistryFile, type MemorySpaceRegistrySummary, type MemorySpaceStats, type MemorySpaceView, type MemorySpaceWriteScope, type MemorySpaceWriteScopeRequest, type MemorySpacesStatus, type MnemonEmbeddingConfig, type MnemonEmbeddingCredential, type MnemonEmbeddingFill, type MnemonEmbeddingProtocol, type MnemonEmbeddingSettingsView, type MnemonEmbeddingSpaceStatus, type MnemonEmbeddingStatus, type NATIVE_PROVIDER_ID, type OpenVikingBodyConnection, type OpenVikingSpaceConnection, type PreparedMemoryPlacement, type RecallQualityConfig, type RecallQualityStats, type RecallRelevanceTier, type RememberRequest, type ResolvedMemoryPersistenceStrategy, type ResolvedMnemonEmbeddingConfig, type ResolvedRecallQualityConfig, type SOURCES, type SearchRequest, type Source, type UpdateMemoryBodyRequest, type UpdateMemoryProviderServiceRequest, type UpdateMemorySpaceRequest, apply, inject, installMemorySpaces, type isNativeProvider, memoryPlugin, name, type normalizeEntityKey, type parseMemorySpaceRegistry, resolveEmbedding, resolveMemorySpaceProviderEntries, resolvePersistenceStrategy, resolveRecallQuality, type summarizeMemoryProviderRegistry, type summarizeMemorySpaceRegistry };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as Config, n as MemorySpaceProviderDeclarationSchema, r as apply, i as inject, a as installMemorySpaces, o as memoryPlugin, s as name, l as resolveEmbedding, c as resolveMemorySpaceProviderEntries, u as resolvePersistenceStrategy, d as resolveRecallQuality } from "../../../lib/src-Bm-xFPnZ.js";
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
declare function nodeLauncherEnvironment(environment?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
||||
declare function mnemonNpmLauncher(command: string): string | undefined;
|
||||
declare function resolveMnemonInvocation(command: string, args: readonly string[], env?: NodeJS.ProcessEnv): {
|
||||
command: string;
|
||||
args: string[];
|
||||
env?: NodeJS.ProcessEnv;
|
||||
};
|
||||
interface CommandDiscoveryOptions {
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
home?: string;
|
||||
isExecutable?: (path: string) => boolean;
|
||||
}
|
||||
declare function isMnemonExecutable(path: string, platform?: NodeJS.Platform): boolean;
|
||||
declare function invalidateMnemonCommandCache(): void;
|
||||
declare function findMnemonCommand(config: {
|
||||
cliPath?: string | undefined;
|
||||
}, options?: CommandDiscoveryOptions): string | undefined;
|
||||
export { CommandDiscoveryOptions, findMnemonCommand, invalidateMnemonCommandCache, isMnemonExecutable, mnemonNpmLauncher, nodeLauncherEnvironment, resolveMnemonInvocation };
|
||||
|
|
@ -0,0 +1,233 @@
|
|||
import { createRequire } from "node:module";
|
||||
import { dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
|
||||
import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-memory-spaces/src/native-cli.ts
|
||||
function manifest(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
function samePath(left, right) {
|
||||
try {
|
||||
return realpathSync(left) === realpathSync(right);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const MNEMON_NPM_PACKAGE = "@mnemon-dev/mnemon";
|
||||
function verifiedLauncher(path) {
|
||||
const root = dirname(dirname(path));
|
||||
const pkg = manifest(join(root, "package.json"));
|
||||
const bin = typeof pkg?.bin === "string" ? pkg.bin : pkg?.bin?.mnemon;
|
||||
if (pkg?.name !== MNEMON_NPM_PACKAGE || pkg.bin !== void 0 && (typeof bin !== "string" || bin.replace(/^\.\//, "") !== "bin/mnemon.js")) return void 0;
|
||||
try {
|
||||
return samePath(path, join(root, "bin/mnemon.js")) ? realpathSync(path) : void 0;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
function nodeLauncherEnvironment(environment = process.env) {
|
||||
return {
|
||||
...Object.fromEntries(Object.entries(environment).filter(([key]) => key.toUpperCase() !== "ELECTRON_RUN_AS_NODE")),
|
||||
ELECTRON_RUN_AS_NODE: "1"
|
||||
};
|
||||
}
|
||||
function mnemonNpmLauncher(command) {
|
||||
let realCommand = command;
|
||||
try {
|
||||
realCommand = realpathSync(command);
|
||||
} catch {}
|
||||
const direct = verifiedLauncher(realCommand);
|
||||
if (direct !== void 0) return direct;
|
||||
if (/\.cmd$/i.test(command)) try {
|
||||
const launchers = /* @__PURE__ */ new Set();
|
||||
for (const match of readFileSync(command, "utf8").replaceAll("\\", "/").matchAll(/"([^"\r\n]+)"/g)) {
|
||||
let target = match[1];
|
||||
if (!target.endsWith("/bin/mnemon.js")) continue;
|
||||
if (/^%(?:dp0%|~dp0)\//i.test(target)) target = target.replace(/^%(?:dp0%|~dp0)\//i, "");
|
||||
else if (!isAbsolute(target)) continue;
|
||||
if (target.includes("%")) continue;
|
||||
const launcher = verifiedLauncher(resolve(dirname(command), target));
|
||||
if (launcher !== void 0) launchers.add(launcher);
|
||||
}
|
||||
if (launchers.size === 1) return [...launchers][0];
|
||||
} catch {}
|
||||
}
|
||||
function npmNativeBinary(launcher) {
|
||||
const pkg = manifest(join(dirname(dirname(launcher)), "package.json"));
|
||||
const target = `${process.platform}-${process.arch}`;
|
||||
const alias = `${MNEMON_NPM_PACKAGE}-${target}`;
|
||||
const version = typeof pkg?.version === "string" ? `${pkg.version}-${target}` : void 0;
|
||||
if (version === void 0 || pkg?.optionalDependencies?.[alias] !== `npm:${MNEMON_NPM_PACKAGE}@${version}`) return void 0;
|
||||
try {
|
||||
const packagePath = createRequire(launcher).resolve.paths(alias)?.map((path) => join(path, alias, "package.json")).find(existsSync);
|
||||
if (packagePath === void 0) return void 0;
|
||||
const native = manifest(packagePath);
|
||||
if (native?.name !== MNEMON_NPM_PACKAGE || native.version !== version) return void 0;
|
||||
const binary = join(dirname(packagePath), "bin", process.platform === "win32" ? "mnemon.exe" : "mnemon");
|
||||
return isMnemonExecutable(binary) ? binary : void 0;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
function packagedMnemonLauncher() {
|
||||
try {
|
||||
const verified = verifiedLauncher(createRequire(import.meta.url).resolve("@mnemon-dev/mnemon/bin/mnemon.js"));
|
||||
return verified !== void 0 && npmNativeBinary(verified) !== void 0 ? verified : void 0;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
function resolveMnemonInvocation(command, args, env) {
|
||||
const launcher = mnemonNpmLauncher(command);
|
||||
if (launcher !== void 0) {
|
||||
const binary = args.length === 1 && args[0] === "update" ? void 0 : npmNativeBinary(launcher);
|
||||
if (binary === void 0) return {
|
||||
command: process.execPath,
|
||||
args: [launcher, ...args],
|
||||
env: nodeLauncherEnvironment(env)
|
||||
};
|
||||
command = binary;
|
||||
}
|
||||
return {
|
||||
command,
|
||||
args: [...args],
|
||||
...env === void 0 ? {} : { env }
|
||||
};
|
||||
}
|
||||
const UNIX_COMMON_CLI_PATHS = [
|
||||
"~/.local/bin/mnemon",
|
||||
"/opt/homebrew/bin/mnemon",
|
||||
"/usr/local/bin/mnemon",
|
||||
"/usr/bin/mnemon"
|
||||
];
|
||||
function pathApi(platform) {
|
||||
return platform === "win32" ? win32 : posix;
|
||||
}
|
||||
function expandHome(path, home = homedir(), platform = process.platform) {
|
||||
if (path === "~") return home;
|
||||
return path.startsWith("~/") || path.startsWith("~\\") ? pathApi(platform).join(home, path.slice(2)) : path;
|
||||
}
|
||||
function envValue(env, name, platform) {
|
||||
if (platform !== "win32") return env[name];
|
||||
const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
|
||||
return key === void 0 ? void 0 : env[key];
|
||||
}
|
||||
function isMnemonExecutable(path, platform = process.platform) {
|
||||
if (platform === "win32" && win32.extname(path).toLowerCase() !== ".exe" && mnemonNpmLauncher(path) === void 0) return false;
|
||||
try {
|
||||
accessSync(path, platform === "win32" ? constants.F_OK : constants.X_OK);
|
||||
return statSync(path).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function windowsCommonCliPaths(env, home) {
|
||||
const candidates = [];
|
||||
const goBin = envValue(env, "GOBIN", "win32")?.trim();
|
||||
if (goBin !== void 0 && win32.isAbsolute(goBin)) candidates.push(win32.join(goBin, "mnemon.exe"));
|
||||
const goInstallRoot = (envValue(env, "GOPATH", "win32")?.trim())?.split(win32.delimiter).map((candidate) => candidate.trim()).find((candidate) => candidate !== "" && win32.isAbsolute(candidate)) ?? win32.join(home, "go");
|
||||
candidates.push(win32.join(goInstallRoot, "bin", "mnemon.exe"));
|
||||
const localAppData = envValue(env, "LOCALAPPDATA", "win32")?.trim();
|
||||
if (localAppData !== void 0 && win32.isAbsolute(localAppData)) candidates.push(win32.join(localAppData, "Programs", "mnemon", "mnemon.exe"));
|
||||
const programFiles = envValue(env, "ProgramFiles", "win32")?.trim();
|
||||
if (programFiles !== void 0 && win32.isAbsolute(programFiles)) candidates.push(win32.join(programFiles, "mnemon", "mnemon.exe"));
|
||||
const directory = (name) => {
|
||||
const value = envValue(env, name, "win32")?.trim().replace(/^"(.*)"$/, "$1");
|
||||
return value !== void 0 && win32.isAbsolute(value) ? value : void 0;
|
||||
};
|
||||
const pnpmHome = directory("PNPM_HOME");
|
||||
const local = directory("LOCALAPPDATA") ?? win32.join(home, "AppData", "Local");
|
||||
const roaming = directory("APPDATA") ?? win32.join(home, "AppData", "Roaming");
|
||||
const globalBins = [
|
||||
pnpmHome,
|
||||
pnpmHome === void 0 ? void 0 : win32.join(pnpmHome, "bin"),
|
||||
directory("NVM_SYMLINK"),
|
||||
win32.join(local, "pnpm"),
|
||||
win32.join(local, "pnpm", "bin"),
|
||||
win32.join(roaming, "npm")
|
||||
];
|
||||
for (const bin of globalBins) if (bin !== void 0 && win32.isAbsolute(bin)) candidates.push(win32.join(bin, "mnemon.exe"), win32.join(bin, "mnemon.cmd"));
|
||||
return [...new Set(candidates)];
|
||||
}
|
||||
function commonCliPaths(platform, env, home) {
|
||||
if (platform === "win32") return windowsCommonCliPaths(env, home);
|
||||
return UNIX_COMMON_CLI_PATHS.map((candidate) => expandHome(candidate, home, platform));
|
||||
}
|
||||
const MNEMON_COMMAND_CACHE_TTL_MS = 5e3;
|
||||
const WINDOWS_CACHE_ENV_KEYS = [
|
||||
"GOBIN",
|
||||
"GOPATH",
|
||||
"LOCALAPPDATA",
|
||||
"ProgramFiles",
|
||||
"PNPM_HOME",
|
||||
"APPDATA",
|
||||
"NVM_SYMLINK"
|
||||
];
|
||||
const mnemonCommandCache = /* @__PURE__ */ new Map();
|
||||
function invalidateMnemonCommandCache() {
|
||||
mnemonCommandCache.clear();
|
||||
}
|
||||
function commandCacheKey(cliPath, platform, env, home) {
|
||||
const pathValue = envValue(env, "PATH", platform) ?? "";
|
||||
const envCliPath = envValue(env, "MNEMON_CLI_PATH", platform)?.trim() ?? "";
|
||||
const winExtras = platform === "win32" ? WINDOWS_CACHE_ENV_KEYS.map((name) => envValue(env, name, "win32") ?? "").join("\0") : "";
|
||||
return `${platform}\u0000${home}\u0000${cliPath ?? ""}\u0000${envCliPath}\u0000${pathValue}\u0000${winExtras}`;
|
||||
}
|
||||
function findMnemonCommand(config, options = {}) {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const home = options.home ?? homedir();
|
||||
const customCheck = options.isExecutable !== void 0;
|
||||
const isExecutable = options.isExecutable ?? ((path) => isMnemonExecutable(path, platform));
|
||||
const paths = pathApi(platform);
|
||||
const pathEntries = (envValue(env, "PATH", platform) ?? "").split(paths.delimiter).filter((directory) => directory !== "");
|
||||
const envPath = envValue(env, "MNEMON_CLI_PATH", platform)?.trim();
|
||||
const cacheKey = customCheck ? void 0 : commandCacheKey(config.cliPath, platform, env, home);
|
||||
const now = Date.now();
|
||||
if (cacheKey !== void 0) {
|
||||
const cached = mnemonCommandCache.get(cacheKey);
|
||||
if (cached !== void 0 && now < cached.expiresAt) {
|
||||
if (cached.found !== void 0) {
|
||||
if (config.cliPath !== void 0 && (config.cliPath.includes("/") || config.cliPath.includes("\\")) || isMnemonExecutable(cached.found, platform)) return cached.found;
|
||||
mnemonCommandCache.delete(cacheKey);
|
||||
} else if ((envPath === void 0 || envPath === "") && pathEntries.length > 2) return;
|
||||
}
|
||||
}
|
||||
const resolveCommand = (command) => {
|
||||
const expanded = expandHome(command, home, platform);
|
||||
if (expanded.includes("/") || expanded.includes("\\")) return expanded;
|
||||
const names = platform === "win32" && paths.extname(expanded) === "" ? [`${expanded}.exe`, `${expanded}.cmd`] : [expanded];
|
||||
for (const directory of pathEntries) for (const name of names) {
|
||||
const path = paths.join(platform === "win32" ? directory.replace(/^"(.*)"$/, "$1") : directory, name);
|
||||
if (/\.cmd$/i.test(name) && mnemonNpmLauncher(path) === void 0) continue;
|
||||
if (isExecutable(path)) return path;
|
||||
}
|
||||
};
|
||||
const remember = (found) => {
|
||||
if (cacheKey !== void 0) {
|
||||
if (mnemonCommandCache.size >= 64) mnemonCommandCache.clear();
|
||||
mnemonCommandCache.set(cacheKey, {
|
||||
found,
|
||||
expiresAt: now + MNEMON_COMMAND_CACHE_TTL_MS
|
||||
});
|
||||
}
|
||||
return found;
|
||||
};
|
||||
if (config.cliPath !== void 0) return remember(resolveCommand(config.cliPath));
|
||||
if (envPath !== void 0 && envPath !== "") {
|
||||
const path = resolveCommand(envPath);
|
||||
if (path !== void 0 && isExecutable(path)) return remember(path);
|
||||
}
|
||||
const fromPath = resolveCommand("mnemon");
|
||||
if (fromPath !== void 0) return remember(fromPath);
|
||||
for (const path of commonCliPaths(platform, env, home)) {
|
||||
if (/\.cmd$/i.test(path) && mnemonNpmLauncher(path) === void 0) continue;
|
||||
if (isExecutable(path)) return remember(path);
|
||||
}
|
||||
return remember(platform === process.platform ? packagedMnemonLauncher() : void 0);
|
||||
}
|
||||
export { findMnemonCommand, invalidateMnemonCommandCache, isMnemonExecutable, mnemonNpmLauncher, nodeLauncherEnvironment, resolveMnemonInvocation };
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
import { a as MemoryJsonValue } from "../../../lib/index-3Wnpy9oQ.js";
|
||||
import { $t as SearchRequest, C as INTENTS, Ct as MemorySpaceProvider, Ht as OpenVikingBodyConnection, J as MemoryGraphSnapshot, Jt as RememberRequest, K as MemoryGraphEdge, L as MemoryBody, Qt as SOURCES, T as Intent, U as MemoryBodyProvider, Ut as OpenVikingSpaceConnection, W as MemoryBodyStats, Y as MemoryListRequest, at as MemoryProviderConfigOption, ct as MemoryProviderDescriptor, en as Source, f as EDGE_TYPES, it as MemoryProviderConfigField, kt as MemorySpaceStats, lt as MemoryProviderIcon, n as CATEGORIES, ot as MemoryProviderConnection, q as MemoryGraphNode, r as Category, rt as MemoryProviderCapabilities, st as MemoryProviderConnectionValue, ut as MemoryProviderId, vt as MemorySpace, w as Insight, y as EdgeType } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { C as ProviderSearchResult, S as ProviderScoreSemantics, _ as MemorySpaceNativeRunner, a as MemorySpaceProviderHost, b as ProviderEntityIndex, c as MemorySpaceProviderRuntimeContext, d as defineMemorySpaceProviderDefinition, f as MemoryProviderAdapter, g as MemorySpaceNativeRunOptions, h as MemorySpaceAuthority, i as MemorySpaceProviderEntry, l as MemorySpaceProviderScoreSemantics, m as MemoryProviderScoreSemantics, n as MemorySpaceProviderDefinition, o as MemorySpaceProviderManifest, p as MemoryProviderAdapterFactoryContext, r as MemorySpaceProviderDisposer, s as MemorySpaceProviderModule, t as MEMORY_SPACE_PROVIDER_API_VERSION, u as defineMemorySpaceProvider, v as NORMALIZED_RELEVANCE_SCORE, w as ProviderSpaceStatus, x as ProviderMemorySpace, y as ProviderBodyStatus } from "../../../lib/definitions-C41Daez1.js";
|
||||
interface HttpProviderOptions {
|
||||
label?: string;
|
||||
fetch?: typeof fetch;
|
||||
requestTimeoutMs?: number;
|
||||
}
|
||||
interface JsonRequestOptions {
|
||||
method?: string;
|
||||
headers?: HeadersInit;
|
||||
json?: MemoryJsonValue;
|
||||
signal?: AbortSignal | undefined;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
type HttpRequestInit = JsonRequestOptions;
|
||||
declare function bearerAuthHeader(apiKey: unknown): string | undefined;
|
||||
declare function jsonObject(value: unknown): Record<string, unknown> | undefined;
|
||||
declare function jsonString(value: unknown): string | undefined;
|
||||
declare function jsonNumber(value: unknown): number | undefined;
|
||||
declare function jsonArray(value: unknown): unknown[];
|
||||
declare function firstArray(value: unknown, ...keys: string[]): unknown[];
|
||||
declare abstract class HttpMemoryProvider {
|
||||
protected readonly memorySpaces: MemorySpaceAuthority;
|
||||
abstract readonly id: MemoryProviderId;
|
||||
protected readonly label: string | undefined;
|
||||
protected readonly requestFetch: typeof fetch;
|
||||
protected readonly requestTimeoutMs: number;
|
||||
/** @deprecated Use memorySpaces. */
|
||||
protected readonly memoryBodies: MemorySpaceAuthority;
|
||||
constructor(memorySpaces: MemorySpaceAuthority, options?: HttpProviderOptions);
|
||||
abstract list(body: MemorySpace, request: MemoryListRequest, signal?: AbortSignal): Promise<Insight[]>;
|
||||
graph(body: MemorySpace, signal?: AbortSignal): Promise<MemoryGraphSnapshot>;
|
||||
protected connection(body: MemorySpace): MemoryProviderConnection;
|
||||
protected request(body: MemorySpace, path: string, options?: JsonRequestOptions): Promise<unknown>;
|
||||
protected requestConnection(connection: MemoryProviderConnection, path: string, options?: JsonRequestOptions): Promise<unknown>;
|
||||
}
|
||||
interface ProcessResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number | null;
|
||||
}
|
||||
interface ProcessOptions {
|
||||
signal?: AbortSignal | undefined;
|
||||
timeoutMs: number;
|
||||
maxOutputBytes?: number;
|
||||
cwd?: string | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
label?: string | undefined;
|
||||
}
|
||||
type ProcessRunner = (command: string, args: readonly string[], options: ProcessOptions) => Promise<ProcessResult>;
|
||||
type ProcessFailureReason = 'launch' | 'timeout' | 'aborted' | 'output-limit';
|
||||
declare class ProcessError extends Error {
|
||||
readonly reason: ProcessFailureReason;
|
||||
constructor(message: string, reason: ProcessFailureReason);
|
||||
}
|
||||
declare const DEFAULT_MAX_OUTPUT_BYTES: number;
|
||||
declare const runProcess: ProcessRunner;
|
||||
export { CATEGORIES, type Category, DEFAULT_MAX_OUTPUT_BYTES, EDGE_TYPES, type EdgeType, HttpMemoryProvider, HttpProviderOptions, HttpRequestInit, INTENTS, type Insight, type Intent, JsonRequestOptions, type MemoryJsonValue as JsonValue, MEMORY_SPACE_PROVIDER_API_VERSION, type MemoryBody, type MemoryBodyProvider, type MemoryBodyStats, type MemoryGraphEdge, type MemoryGraphNode, type MemoryGraphSnapshot, type MemoryListRequest, MemoryProviderAdapter, MemoryProviderAdapterFactoryContext, type MemoryProviderCapabilities, type MemoryProviderConfigField, type MemoryProviderConfigOption, type MemoryProviderConnection, type MemoryProviderConnectionValue, type MemoryProviderDescriptor, type MemoryProviderIcon, type MemoryProviderId, MemoryProviderScoreSemantics, type MemorySpace, MemorySpaceAuthority, MemorySpaceNativeRunOptions, MemorySpaceNativeRunner, type MemorySpaceProvider, type MemorySpaceProviderDefinition, type MemorySpaceProviderDisposer, type MemorySpaceProviderEntry, type MemorySpaceProviderHost, type MemorySpaceProviderManifest, type MemorySpaceProviderModule, type MemorySpaceProviderRuntimeContext, type MemorySpaceProviderScoreSemantics, type MemorySpaceStats, NORMALIZED_RELEVANCE_SCORE, type OpenVikingBodyConnection, type OpenVikingSpaceConnection, ProcessError, ProcessFailureReason, ProcessOptions, ProcessResult, ProcessRunner, ProviderBodyStatus, ProviderEntityIndex, ProviderMemorySpace, ProviderScoreSemantics, ProviderSearchResult, ProviderSpaceStatus, type RememberRequest, SOURCES, type SearchRequest, type Source, bearerAuthHeader, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition, firstArray, jsonArray, jsonNumber, jsonObject, jsonString, runProcess };
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
import { CATEGORIES, EDGE_TYPES, INTENTS, SOURCES } from "./contracts.js";
|
||||
import { i as runProcess, n as DEFAULT_MAX_OUTPUT_BYTES, r as ProcessError, t as NORMALIZED_RELEVANCE_SCORE } from "../../../lib/adapter-CF9Q9xOa.js";
|
||||
import { i as defineMemorySpaceProviderDefinition, r as defineMemorySpaceProvider, t as MEMORY_SPACE_PROVIDER_API_VERSION } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-memory-spaces/src/providers/http.ts
|
||||
function bearerAuthHeader(apiKey) {
|
||||
if (typeof apiKey !== "string") return void 0;
|
||||
const token = apiKey.trim().replace(/^Bearer(?:\s+|$)/iu, "").trim();
|
||||
return token === "" ? void 0 : `Bearer ${token}`;
|
||||
}
|
||||
function jsonObject(value) {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
||||
}
|
||||
function jsonString(value) {
|
||||
return typeof value === "string" ? value : void 0;
|
||||
}
|
||||
function jsonNumber(value) {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
||||
}
|
||||
function jsonArray(value) {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
function firstArray(value, ...keys) {
|
||||
if (Array.isArray(value)) return value;
|
||||
const root = jsonObject(value);
|
||||
for (const key of keys) if (Array.isArray(root?.[key])) return root[key];
|
||||
const nested = jsonObject(root?.data);
|
||||
for (const key of keys) if (Array.isArray(nested?.[key])) return nested[key];
|
||||
return [];
|
||||
}
|
||||
function errorDetail(payload) {
|
||||
if (typeof payload === "string") return payload.trim() || void 0;
|
||||
const root = jsonObject(payload);
|
||||
const direct = jsonString(root?.message) ?? jsonString(root?.error) ?? jsonString(root?.detail);
|
||||
if (direct !== void 0) return direct;
|
||||
const error = jsonObject(root?.error);
|
||||
return jsonString(error?.message) ?? jsonString(error?.detail);
|
||||
}
|
||||
var HttpMemoryProvider = class {
|
||||
memorySpaces;
|
||||
label;
|
||||
requestFetch;
|
||||
requestTimeoutMs;
|
||||
/** @deprecated Use memorySpaces. */
|
||||
memoryBodies;
|
||||
constructor(memorySpaces, options = {}) {
|
||||
this.memorySpaces = memorySpaces;
|
||||
this.memoryBodies = memorySpaces;
|
||||
this.label = options.label;
|
||||
this.requestFetch = options.fetch ?? globalThis.fetch;
|
||||
this.requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
|
||||
}
|
||||
async graph(body, signal) {
|
||||
return {
|
||||
nodes: (await this.list(body, { limit: 200 }, signal)).map((item) => ({
|
||||
...item,
|
||||
color: "#6574d9"
|
||||
})),
|
||||
edges: [],
|
||||
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
||||
};
|
||||
}
|
||||
connection(body) {
|
||||
if ((body.provider.typeId ?? body.provider.id) !== this.id) throw new Error(`${this.id} cannot serve provider ${body.provider.id}`);
|
||||
return this.memorySpaces.providerConnection(body.id, body.provider.id);
|
||||
}
|
||||
async request(body, path, options = {}) {
|
||||
const connection = this.connection(body);
|
||||
return this.requestConnection(connection, path, options);
|
||||
}
|
||||
async requestConnection(connection, path, options = {}) {
|
||||
const endpoint = String(connection.endpoint ?? "").replace(/\/+$/u, "");
|
||||
const label = this.label ?? this.id;
|
||||
if (endpoint === "") throw new Error(`${label} endpoint is not configured`);
|
||||
if (!path.startsWith("/")) throw new Error(`${label} request path must be absolute`);
|
||||
options.signal?.throwIfAborted();
|
||||
const controller = new AbortController();
|
||||
const relay = () => controller.abort(options.signal?.reason);
|
||||
options.signal?.addEventListener("abort", relay, { once: true });
|
||||
const timeoutMs = options.timeoutMs ?? this.requestTimeoutMs;
|
||||
const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error(`${label} request timed out`)), timeoutMs);
|
||||
const headers = new Headers(options.headers);
|
||||
if (options.json !== void 0 && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
|
||||
try {
|
||||
const response = await this.requestFetch(`${endpoint}${path}`, {
|
||||
method: options.method ?? (options.json === void 0 ? "GET" : "POST"),
|
||||
headers,
|
||||
...options.json === void 0 ? {} : { body: JSON.stringify(options.json) },
|
||||
signal: controller.signal
|
||||
});
|
||||
const raw = await response.text();
|
||||
let payload = {};
|
||||
if (raw !== "") try {
|
||||
payload = JSON.parse(raw);
|
||||
} catch {
|
||||
payload = raw;
|
||||
}
|
||||
if (!response.ok) {
|
||||
const detail = errorDetail(payload);
|
||||
throw Object.assign(/* @__PURE__ */ new Error(`${label} HTTP ${response.status}${detail === void 0 ? "" : `: ${detail}`}`), { status: response.status });
|
||||
}
|
||||
return payload;
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted && options.signal?.aborted !== true) throw new Error(`${label} request timed out after ${timeoutMs}ms`);
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
options.signal?.removeEventListener("abort", relay);
|
||||
}
|
||||
}
|
||||
};
|
||||
export { CATEGORIES, DEFAULT_MAX_OUTPUT_BYTES, EDGE_TYPES, HttpMemoryProvider, INTENTS, MEMORY_SPACE_PROVIDER_API_VERSION, NORMALIZED_RELEVANCE_SCORE, ProcessError, SOURCES, bearerAuthHeader, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition, firstArray, jsonArray, jsonNumber, jsonObject, jsonString, runProcess };
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
declare class MemorySpaceIdentity {
|
||||
#private;
|
||||
constructor(parent: string);
|
||||
of(bytes: Uint8Array): string;
|
||||
contains(outer: Uint8Array, inner: Uint8Array): boolean;
|
||||
merge(local: Uint8Array, incoming: Uint8Array): Uint8Array | undefined;
|
||||
dispose(): void;
|
||||
}
|
||||
export { MemorySpaceIdentity };
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { t as MemorySpaceIdentity } from "../../../lib/space-identity-CXZWDVij.js";
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import { ct as MemoryProviderDescriptor, ot as MemoryProviderConnection, vt as MemorySpace } from "../../../lib/contracts-DuGgDm58.js";
|
||||
import { f as MemoryProviderAdapter, h as MemorySpaceAuthority, o as MemorySpaceProviderManifest, p as MemoryProviderAdapterFactoryContext, s as MemorySpaceProviderModule } from "../../../lib/definitions-C41Daez1.js";
|
||||
interface MemorySpaceProviderTest {
|
||||
readonly registered: boolean;
|
||||
readonly descriptor: MemoryProviderDescriptor;
|
||||
readonly manifest: MemorySpaceProviderManifest;
|
||||
createAdapter(context: MemoryProviderAdapterFactoryContext): MemoryProviderAdapter;
|
||||
dispose(): Promise<void>;
|
||||
}
|
||||
declare function mountMemorySpaceProvider<C>(module: MemorySpaceProviderModule<C>, options: {
|
||||
instanceId?: string;
|
||||
sourceInstanceId?: string;
|
||||
config: C;
|
||||
}): Promise<MemorySpaceProviderTest>;
|
||||
declare function createMemorySpaceProviderFixture(descriptor: MemoryProviderDescriptor, input: MemoryProviderConnection | undefined, options: {
|
||||
dataDir: string;
|
||||
instanceId?: string;
|
||||
memoryBodyId?: string;
|
||||
}): {
|
||||
body: MemorySpace;
|
||||
authority: MemorySpaceAuthority;
|
||||
connection: MemoryProviderConnection;
|
||||
};
|
||||
export { MemorySpaceProviderTest, createMemorySpaceProviderFixture, mountMemorySpaceProvider };
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import { a as MemoryProviderCatalog, n as PrivateMemorySpaceProviderHost, t as createMemorySpaceProviderPlugin } from "../../../lib/plugin-CdGWz_Vo.js";
|
||||
import { n as deepFreeze } from "../../../lib/definitions-Du9KQuKM.js";
|
||||
import { Context } from "@deepseek-ai/cordis";
|
||||
// vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-memory-spaces/src/testing.ts
|
||||
async function mountMemorySpaceProvider(module, options) {
|
||||
const context = new Context();
|
||||
const host = new PrivateMemorySpaceProviderHost(options.sourceInstanceId ?? "test-memory-spaces");
|
||||
const instanceId = options.instanceId ?? module.id;
|
||||
const plugin = createMemorySpaceProviderPlugin({
|
||||
instanceId,
|
||||
module,
|
||||
config: options.config
|
||||
}, host);
|
||||
const bound = {
|
||||
...plugin,
|
||||
apply: (ctx, config) => plugin.apply(ctx, config)
|
||||
};
|
||||
const child = context.plugin(bound, options.config);
|
||||
try {
|
||||
await child.await();
|
||||
if (!host.has(instanceId)) throw new Error(`Memory Space Provider child did not install a definition: ${instanceId}`);
|
||||
const snapshot = host.snapshot();
|
||||
const adapters = /* @__PURE__ */ new Set();
|
||||
let closing;
|
||||
return Object.freeze({
|
||||
get registered() {
|
||||
return host.has(instanceId);
|
||||
},
|
||||
descriptor: deepFreeze(snapshot.descriptors()[0]),
|
||||
manifest: snapshot.entries[0].definition.manifest,
|
||||
createAdapter: (input) => {
|
||||
if (closing !== void 0) throw new Error("Memory Space Provider test is disposed");
|
||||
const adapter = snapshot.adapterRegistry().create(input).get(instanceId);
|
||||
adapters.add(adapter);
|
||||
return adapter;
|
||||
},
|
||||
dispose: () => {
|
||||
closing ??= Promise.resolve().then(async () => {
|
||||
const failures = [];
|
||||
for (const adapter of adapters) try {
|
||||
await adapter.dispose?.();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
adapters.clear();
|
||||
try {
|
||||
await context.fiber.dispose();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
if (failures.length > 0) throw new AggregateError(failures, "Memory Space Provider test cleanup failed");
|
||||
});
|
||||
return closing;
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
await context.fiber.dispose();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function createMemorySpaceProviderFixture(descriptor, input = {}, options) {
|
||||
const instanceId = options.instanceId ?? descriptor.id;
|
||||
const catalog = new MemoryProviderCatalog([{
|
||||
...descriptor,
|
||||
id: instanceId,
|
||||
...instanceId === descriptor.id ? {} : { typeId: descriptor.id }
|
||||
}]);
|
||||
const connection = catalog.normalize(instanceId, input);
|
||||
const publicConnection = catalog.public(instanceId, connection);
|
||||
const body = {
|
||||
id: options.memoryBodyId ?? "test-memory",
|
||||
name: "Test memory",
|
||||
description: "Provider-owned test fixture",
|
||||
active: true,
|
||||
dbPath: "",
|
||||
createdAt: "2026-08-30T00:00:00.000Z",
|
||||
updatedAt: "2026-08-30T00:00:00.000Z",
|
||||
provider: {
|
||||
id: instanceId,
|
||||
...instanceId === descriptor.id ? {} : { typeId: descriptor.id },
|
||||
label: descriptor.label,
|
||||
kind: descriptor.kind,
|
||||
origin: descriptor.origin,
|
||||
location: String(connection.endpoint ?? options.dataDir),
|
||||
apiKeyConfigured: publicConnection.configuredSecrets.includes("apiKey"),
|
||||
...publicConnection,
|
||||
capabilities: structuredClone(descriptor.capabilities)
|
||||
}
|
||||
};
|
||||
return {
|
||||
body,
|
||||
authority: {
|
||||
runner: { effectiveDataDir: () => options.dataDir },
|
||||
list: () => [body],
|
||||
providerConnection(id, expectedProviderId) {
|
||||
if (id !== body.id || expectedProviderId !== void 0 && expectedProviderId !== instanceId) throw new Error("Provider attempted to cross its test authority boundary");
|
||||
return structuredClone(connection);
|
||||
}
|
||||
},
|
||||
connection
|
||||
};
|
||||
}
|
||||
export { createMemorySpaceProviderFixture, mountMemorySpaceProvider };
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Speicherbereiche",
|
||||
"description": "Anbieter-gestützte dauerhafte Belege, die bei Bedarf aufgaben- und sitzungsübergreifend abgerufen werden."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Memory Spaces",
|
||||
"description": "Provider-backed durable evidence recalled on demand across tasks and sessions."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Espacios de memoria",
|
||||
"description": "Evidencia duradera respaldada por Proveedores, recuperada bajo demanda entre tareas y sesiones."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Espaces de mémoire",
|
||||
"description": "Preuves durables adossées à des Fournisseurs, rappelées à la demande entre tâches et sessions."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "メモリスペース",
|
||||
"description": "プロバイダーが保持する永続的な記憶を、タスクやセッションを跨いでオンデマンドに検索。"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Espaços de memória",
|
||||
"description": "Evidências duráveis mantidas por Provedores e recuperadas sob demanda entre tarefas e sessões."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "Пространства памяти",
|
||||
"description": "Долгосрочные данные на базе Провайдеров, извлекаемые по запросу между задачами и сессиями."
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"meta": {
|
||||
"title": "记忆空间",
|
||||
"description": "由 Provider 支撑的持久证据,按需跨任务与会话召回。"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
{
|
||||
"name": "dsh-brain-mnemon-source-memory-spaces",
|
||||
"version": "0.5.34",
|
||||
"description": "Memory Spaces Source and its private Provider SDK.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./provider-sdk": {
|
||||
"types": "./lib/provider-sdk.d.ts",
|
||||
"default": "./lib/provider-sdk.js"
|
||||
},
|
||||
"./package.json": "./package.json",
|
||||
"./locale/*.json": "./locale/*.json",
|
||||
"./testing": {
|
||||
"types": "./lib/testing.d.ts",
|
||||
"default": "./lib/testing.js"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./lib/client.d.ts",
|
||||
"default": "./lib/client.js"
|
||||
},
|
||||
"./contracts": {
|
||||
"types": "./lib/contracts.d.ts",
|
||||
"default": "./lib/contracts.js"
|
||||
},
|
||||
"./presentation/locales.json": "./presentation/locales.json",
|
||||
"./presentation/page.module.css": "./presentation/page.module.css",
|
||||
"./presentation/sidebar.module.css": "./presentation/sidebar.module.css",
|
||||
"./native-cli": {
|
||||
"types": "./lib/native-cli.d.ts",
|
||||
"default": "./lib/native-cli.js"
|
||||
},
|
||||
"./space-identity": {
|
||||
"types": "./lib/space-identity.d.ts",
|
||||
"default": "./lib/space-identity.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"locale",
|
||||
"README.md",
|
||||
"presentation"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "tsdown && tsc -p tsconfig.client-types.json",
|
||||
"test": "vitest run",
|
||||
"verify": "pnpm typecheck && pnpm test && pnpm build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/schemastery": "^3.18.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"dsh-brain-mnemon": "^0.5.19",
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "0.2.1-rc.5",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/react": "^18.3.0",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"dsh-brain-mnemon": "^0.5.53",
|
||||
"jsdom": "^26.0.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0",
|
||||
"lightningcss": "^1.33.0",
|
||||
"clsx": "^2.1.1",
|
||||
"@shikijs/langs": "^4.3.1",
|
||||
"anser": "^2.3.5",
|
||||
"katex": "^0.16.47",
|
||||
"mdast-util-from-markdown": "^2.0.3",
|
||||
"mdast-util-gfm": "^3.1.0",
|
||||
"mdast-util-math": "^3.0.0",
|
||||
"micromark-core-commonmark": "^2.0.3",
|
||||
"micromark-extension-gfm": "^3.0.0",
|
||||
"micromark-extension-math": "^3.1.0",
|
||||
"micromark-factory-space": "^2.0.1",
|
||||
"micromark-util-character": "^2.1.1",
|
||||
"micromark-util-classify-character": "^2.0.1",
|
||||
"micromark-util-sanitize-uri": "^2.0.1",
|
||||
"micromark-util-symbol": "^2.0.1",
|
||||
"shiki": "^4.3.1",
|
||||
"@deepseek-ai/dsh-client-store": "0.2.1-rc.5",
|
||||
"@deepseek-ai/dsh-util-code-language": "0.2.1-rc.5",
|
||||
"@deepseek-ai/dsh-util-workspace-path": "0.2.1-rc.5",
|
||||
"diff": "^9.0.0",
|
||||
"immer": "^10.1.1",
|
||||
"simple-icons": "16.31.0",
|
||||
"zustand": "~4.4.7"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"dsh": {
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"external": [
|
||||
"dsh-brain-mnemon/client"
|
||||
]
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"tag": "latest"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/omdsh-dev/dsh-mnemon.git",
|
||||
"directory": "plugins/dsh-brain-mnemon-source-memory-spaces"
|
||||
},
|
||||
"homepage": "https://github.com/omdsh-dev/dsh-mnemon/tree/main/plugins/dsh-brain-mnemon-source-memory-spaces#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/omdsh-dev/dsh-mnemon/issues"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,277 @@
|
|||
.shell .memoryWorkspace {
|
||||
position: sticky;
|
||||
z-index: 12;
|
||||
top: 0;
|
||||
flex: 0 0 auto;
|
||||
margin: -20px -24px 16px;
|
||||
padding: 20px 24px 0;
|
||||
border-bottom: .5px solid var(--dsw-alias-border-l2);
|
||||
background: var(--mn-surface);
|
||||
}
|
||||
.shell .memoryWorkspace > [class*='pageHeader'] { margin-bottom: 12px; }
|
||||
/* A page under the Memory Spaces tabs titles its section rather than the page: the DSH group heading scale. */
|
||||
.shell .memoryWorkspace ~ [class*='page'] > [class*='pageHeader'] { margin-bottom: 12px; }
|
||||
.shell .memoryWorkspace ~ [class*='page'] > [class*='pageHeader'] h2 { font-size: 14px; line-height: 22px; }
|
||||
.shell .memoryWorkspace ~ [class*='page'] > [class*='pageHeader'] p { color: var(--dsw-alias-label-tertiary); font-size: 12px; line-height: 18px; }
|
||||
/* Keep secondary controls in flow beneath the one pinned Source header. */
|
||||
.shell [class*='relatedPane'], .shell [class*='entityRail'] { position: static; }
|
||||
|
||||
/* Secondary tabs, as the DSH settings tabs: monochrome underline. */
|
||||
.shell .memoryNavigation {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex: 0 0 auto;
|
||||
align-items: flex-end;
|
||||
gap: 12px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.shell .memoryTabs {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
gap: 22px;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.shell .memoryTabs::-webkit-scrollbar { display: none; }
|
||||
.shell .memoryTabs button {
|
||||
position: relative;
|
||||
min-width: max-content;
|
||||
min-height: 0;
|
||||
margin-bottom: -.5px;
|
||||
padding: 6px 1px 9px;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
cursor: pointer;
|
||||
transition: color 140ms ease, border-bottom-color 140ms ease;
|
||||
}
|
||||
.shell .memoryTabs button:hover { color: var(--dsw-alias-label-primary); }
|
||||
.shell .memoryTabs button[data-active] {
|
||||
border-bottom-color: var(--dsw-alias-label-primary);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
.shell .memoryWriteButton { flex: none; }
|
||||
.shell .modal {
|
||||
display: flex;
|
||||
max-height: min(82vh, 720px);
|
||||
max-height: min(82dvh, 720px);
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.shell .modal > [class*='modalBody'] {
|
||||
min-height: 0;
|
||||
flex: 1 1 auto;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.shell .modal > [class*='modalFooter'] {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 0 0 auto;
|
||||
background: var(--dsw-alias-bg-layer-2, var(--mn-surface));
|
||||
}
|
||||
.shell .modal section[class*='supervisedComposer'] { overflow: visible; border: 0; }
|
||||
.shell .modal form[class*='supervisedForm'] { padding: 0; }
|
||||
.shell .modal [class*='supervisedHeading'] { margin-bottom: 12px; }
|
||||
.shell .modal [class*='supervisedHeading'] h3 { display: none; }
|
||||
.shell .modal details[class*='advancedWrite'] {
|
||||
margin-top: 16px;
|
||||
overflow: hidden;
|
||||
border: .5px solid var(--dsw-alias-settings-card-stroke);
|
||||
border-radius: var(--dsw-radius-md);
|
||||
}
|
||||
|
||||
.shell [class*='inspectorEye'],
|
||||
.shell [class*='inspectorHeading'] button {
|
||||
display: inline-flex;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
min-height: 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
color: var(--dsw-alias-label-caption);
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition: background-color 120ms ease, color 120ms ease;
|
||||
}
|
||||
.shell [class*='inspectorEye']:hover:not(:disabled),
|
||||
.shell [class*='inspectorHeading'] button:hover:not(:disabled) {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
.shell [class*='inspectorEye']:disabled {
|
||||
cursor: default;
|
||||
opacity: .4;
|
||||
}
|
||||
|
||||
.shell [class*='bodyGrid'] {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(320px, 100%), 1fr));
|
||||
}
|
||||
.shell article[class*='bodyCard'] {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
flex-direction: column;
|
||||
}
|
||||
.shell .bodyCardHeader {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.shell .bodyDirectoryActions {
|
||||
display: flex;
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.shell .bodyCardIdentity {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
.shell .bodyCardIdentity > [class*='bodySignal'] {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
flex: 0 0 auto;
|
||||
margin-top: 7px;
|
||||
}
|
||||
.shell article[class*='bodyCard'][data-reconnecting] .bodyCardIdentity > [class*='bodySignal'] {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.shell .bodyCardIdentity > div { display: grid; min-width: 0; flex: 1; gap: 2px; }
|
||||
.shell .bodyCardIdentity strong {
|
||||
overflow: hidden;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.shell .bodyCardMeta {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 8px;
|
||||
}
|
||||
.shell .bodyCardMeta code {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 11px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.shell .bodyCardMeta [class*='bodyHealth'] { flex: 0 0 auto; }
|
||||
.shell .bodyCardHeader > [role='switch'] { flex: 0 0 auto; }
|
||||
.shell article[class*='bodyCard'] > p {
|
||||
display: -webkit-box;
|
||||
min-height: 40px;
|
||||
max-height: 40px;
|
||||
margin: 10px 0;
|
||||
overflow: hidden;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
}
|
||||
.shell .bodyCardFooter {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) max-content;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: auto;
|
||||
padding-top: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.shell .bodyCardStats {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.shell .bodyCardFooter [class*='bodyCardActions'] {
|
||||
display: flex;
|
||||
flex: 0 0 auto;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.shell [class*='cardActions'] { gap: 8px; }
|
||||
|
||||
.shell .inspectorGlyph {
|
||||
display: grid;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
margin-bottom: 12px;
|
||||
place-items: center;
|
||||
border: .5px solid var(--dsw-alias-border-l3);
|
||||
border-radius: var(--dsw-radius-lg);
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.shell .memoryWorkspace { margin: -16px -16px 16px; padding: 16px 16px 0; }
|
||||
}
|
||||
|
||||
@container mnemon-workbench (max-width: 560px) {
|
||||
.shell .bodyCardFooter {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 8px;
|
||||
white-space: normal;
|
||||
}
|
||||
.shell .bodyCardStats {
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
overflow: visible;
|
||||
}
|
||||
.shell .bodyCardFooter [class*='bodyCardActions'] {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.shell .bodyCardFooter {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 8px;
|
||||
white-space: normal;
|
||||
}
|
||||
.shell .bodyCardStats {
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
overflow: visible;
|
||||
}
|
||||
.shell .bodyCardFooter [class*='bodyCardActions'] {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.shell .memoryTabs { gap: 18px; }
|
||||
.shell .memoryWriteButton { flex: 1 1 0; justify-content: center; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.shell .memoryTabs button,
|
||||
.shell [class*='inspectorEye'],
|
||||
.shell [class*='inspectorHeading'] button {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
import { ft as installMemorySourceUI, gt as MnemonSourceManagementClient, ht as MemorySourcePageProps, xt as MnemonTranslate } from "../../../lib/client-extension-sdk-BX83D8r5.js";
|
||||
import { JSX, ReactNode } from "react";
|
||||
type RuntimeMemoryTarget = 'memory' | 'user';
|
||||
type RuntimeMemoryImportance = 'critical' | 'normal' | 'low';
|
||||
interface RuntimeMemoryEntryOrigin {
|
||||
machine: string;
|
||||
label: string;
|
||||
at: string;
|
||||
}
|
||||
interface RuntimeMemoryEntry {
|
||||
content: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
target: RuntimeMemoryTarget;
|
||||
importance: RuntimeMemoryImportance;
|
||||
pinned?: boolean;
|
||||
branches?: string[];
|
||||
origin?: RuntimeMemoryEntryOrigin;
|
||||
}
|
||||
interface RuntimeMemoryUsage {
|
||||
used: number;
|
||||
limit: number;
|
||||
}
|
||||
interface RuntimeMemoryTargetView extends RuntimeMemoryUsage {
|
||||
target: RuntimeMemoryTarget;
|
||||
entryCount: number;
|
||||
markdownPath: string;
|
||||
pinned?: {
|
||||
count: number;
|
||||
characters: number;
|
||||
limit: number;
|
||||
};
|
||||
}
|
||||
interface RuntimeMemorySnapshot {
|
||||
directory: string;
|
||||
sourcePath: string;
|
||||
revision: string;
|
||||
generatedAt: string;
|
||||
entries: RuntimeMemoryEntry[];
|
||||
targets: Record<RuntimeMemoryTarget, RuntimeMemoryTargetView>;
|
||||
}
|
||||
type RuntimeMemoryMutationResult = {
|
||||
success: true;
|
||||
message: string;
|
||||
target: RuntimeMemoryTarget;
|
||||
entryCount: number;
|
||||
usage: RuntimeMemoryUsage;
|
||||
added?: string;
|
||||
replaced?: {
|
||||
from: string;
|
||||
to: string;
|
||||
};
|
||||
removed?: string;
|
||||
archived?: {
|
||||
entries: number;
|
||||
path: string;
|
||||
};
|
||||
maintenance?: {
|
||||
kind: 'local-compaction' | 'mnemon-archive' | 'local-archive';
|
||||
runId: string;
|
||||
provider: string;
|
||||
summary: string;
|
||||
memoryBodyIds: string[];
|
||||
};
|
||||
};
|
||||
interface RuntimePageClient {
|
||||
runtimeMemory(): Promise<RuntimeMemorySnapshot>;
|
||||
pinRuntimeMemory?(request: {
|
||||
target: RuntimeMemoryTarget;
|
||||
content: string;
|
||||
pinned: boolean;
|
||||
matchBranches?: string[];
|
||||
}): Promise<RuntimeMemorySnapshot>;
|
||||
mutateRuntimeMemory(request: {
|
||||
action: 'add' | 'replace' | 'remove';
|
||||
target: RuntimeMemoryTarget;
|
||||
content?: string;
|
||||
old_text?: string;
|
||||
importance?: RuntimeMemoryImportance;
|
||||
matchBranches?: string[];
|
||||
branches?: string[];
|
||||
}): Promise<RuntimeMemoryMutationResult>;
|
||||
}
|
||||
declare function RuntimePage(props: {
|
||||
client: RuntimePageClient;
|
||||
revision: number;
|
||||
writeEnabled: boolean;
|
||||
focusText?: string;
|
||||
onRevealElement?(element: HTMLElement): void;
|
||||
onMutate?: () => void;
|
||||
}): JSX.Element;
|
||||
declare function runtimePageClient(management: MnemonSourceManagementClient): RuntimePageClient;
|
||||
declare function RuntimeSourcePage(props: MemorySourcePageProps): ReactNode;
|
||||
declare function installRuntimeMemoryUI(ctx: Parameters<typeof installMemorySourceUI>[0], t?: MnemonTranslate): () => void;
|
||||
declare const inject: string[];
|
||||
declare function apply(ctx: Parameters<typeof installMemorySourceUI>[0]): void;
|
||||
export { RuntimePage, type RuntimePageClient, RuntimeSourcePage, apply, inject, installRuntimeMemoryUI, runtimePageClient };
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue