chore(release): 0.10.3
Bumps the manifest, version fallback and README, and rebuilds lib/ and client/ so the committed artifacts match the sources.
This commit is contained in:
parent
da562de002
commit
31037b0d31
|
|
@ -1,14 +1,15 @@
|
|||
# dsh-brain
|
||||
|
||||
> **0.10.1**:插件按功能拆成五个可单独开关的子插件(见「五个子插件」);
|
||||
> 技能同步引入按内容与更新时间的自动冲突解决(0.9.9/0.9.10 语义);
|
||||
> 令牌环境变量改为**绑定服务地址**(见「配置」)。
|
||||
> **0.10.3**:插件按功能拆成六个可单独开关的子插件,新增可选的原始记录层
|
||||
> `dsh-brain-raw`(见「六个子插件」);同步清理了不可达的防御性分支与重复
|
||||
> 响应校验。0.10.1 起技能同步按内容与更新时间自动解决冲突(0.9.9/0.9.10
|
||||
> 语义),令牌环境变量**绑定服务地址**(见「配置」)。
|
||||
|
||||
把 DeepSeek Harness 接到 LongMemory 云端记忆服务:每轮对话结束自动上报一条
|
||||
活动记录(只上传元数据),并把云端记忆库变成 agent 可用的工具;同时双向
|
||||
同步云端技能中心与本机技能目录。
|
||||
|
||||
当前版本 **0.10.1**,含宿主端与浏览器端两部分:宿主端负责活动上报、
|
||||
当前版本 **0.10.3**,含宿主端与浏览器端两部分:宿主端负责活动上报、
|
||||
记忆工具注册与技能同步。浏览器 UI 有三个入口:
|
||||
|
||||
- 左侧栏 **Brain** 展示全局运行状态,管理全局记忆与部门。
|
||||
|
|
|
|||
1166
client/index.js
1166
client/index.js
File diff suppressed because it is too large
Load Diff
|
|
@ -200,7 +200,6 @@ function validateSkillListing(value) {
|
|||
function validateSkillBundle(value) {
|
||||
const body = requireResponseObject(value, 'skill bundle response');
|
||||
requireResponseString(body, 'name');
|
||||
optionalResponseNumber(body, 'revision');
|
||||
if (typeof body.revision !== 'number' || !Number.isFinite(body.revision)) {
|
||||
throw new Error('revision must be a number');
|
||||
}
|
||||
|
|
@ -466,12 +465,8 @@ export class CloudClient {
|
|||
if (base === '')
|
||||
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } };
|
||||
const headers = { Accept: 'application/json' };
|
||||
try {
|
||||
headers.Origin = new URL(baseUrl).origin;
|
||||
}
|
||||
catch {
|
||||
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } };
|
||||
}
|
||||
// authBase already parsed this exact URL successfully, so this cannot throw.
|
||||
headers.Origin = new URL(baseUrl).origin;
|
||||
if (cookie !== undefined && cookie !== '')
|
||||
headers.Cookie = cookie;
|
||||
const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) };
|
||||
|
|
|
|||
|
|
@ -191,9 +191,7 @@ export class ClientRegistry {
|
|||
if (software === undefined)
|
||||
throw new Error('invalid_software');
|
||||
const path = typeof pathInput === 'string' ? pathInput.trim() : '';
|
||||
if (path === '' || !existsSync(path))
|
||||
throw new Error('invalid_path');
|
||||
const stats = await stat(path).catch(() => undefined);
|
||||
const stats = path === '' ? undefined : await stat(path).catch(() => undefined);
|
||||
if (stats === undefined || !stats.isDirectory())
|
||||
throw new Error('invalid_path');
|
||||
const resolved = resolve(path);
|
||||
|
|
@ -232,7 +230,7 @@ export class ClientRegistry {
|
|||
const frontmatter = parseSkillFrontmatter(markdown);
|
||||
out.push({
|
||||
folder: entry.name,
|
||||
name: typeof frontmatter.name === 'string' && frontmatter.name !== '' ? frontmatter.name : entry.name,
|
||||
name: frontmatter.name ?? entry.name,
|
||||
description: String(frontmatter.description ?? '').slice(0, 300),
|
||||
path: skillDir,
|
||||
softwareId: software,
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ async function serveTest(deps, req, res) {
|
|||
id: 'memory',
|
||||
label: '记忆读写权限(memory:write)',
|
||||
state: probe.ok ? 'ok' : checkState(probe.error),
|
||||
message: probe.ok ? `鉴权通过(${(probe.data.projects ?? []).length} 个项目)` : describeError(probe.error),
|
||||
message: probe.ok ? `鉴权通过(${probe.data.projects.length} 个项目)` : describeError(probe.error),
|
||||
});
|
||||
}
|
||||
const summaryToken = deps.store.summaryToken();
|
||||
|
|
@ -183,9 +183,7 @@ async function serveLogin(deps, req, res) {
|
|||
const memory = await client.mintToken(session.data.sessionCookie, 'memory:write', TOKEN_LABELS.memory, target);
|
||||
const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary, target);
|
||||
if (!activity.ok && !memory.ok) {
|
||||
const first = activity.ok ? memory : activity;
|
||||
const reason = first.ok ? '无法创建令牌' : describeError(first.error);
|
||||
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` });
|
||||
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${describeError(activity.error)}` });
|
||||
return;
|
||||
}
|
||||
// Atomic account switch: a scope whose mint failed must not keep the token
|
||||
|
|
|
|||
|
|
@ -70,13 +70,9 @@ export function isPlaceholderBaseUrl(value) {
|
|||
const normalized = normalizeBaseUrl(value);
|
||||
if (normalized === undefined)
|
||||
return true;
|
||||
try {
|
||||
const host = new URL(normalized).hostname.toLowerCase();
|
||||
return host === 'your-memory-host' || host === 'example.com';
|
||||
}
|
||||
catch {
|
||||
return true;
|
||||
}
|
||||
// normalized was built from a successfully parsed URL, so this cannot throw.
|
||||
const host = new URL(normalized).hostname.toLowerCase();
|
||||
return host === 'your-memory-host' || host === 'example.com';
|
||||
}
|
||||
/** Service origin of one base URL, or '' when it cannot be parsed. */
|
||||
export function originOf(value) {
|
||||
|
|
|
|||
|
|
@ -147,7 +147,6 @@ export class BrainLogger {
|
|||
if (this.warned)
|
||||
return;
|
||||
this.warned = true;
|
||||
if (typeof console !== 'undefined')
|
||||
console.warn('[dsh-brain] diagnostic log write failed; continuing without logs');
|
||||
console.warn('[dsh-brain] diagnostic log write failed; continuing without logs');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,115 @@
|
|||
import { createRawMemoryRuntime } from "../raw-memory/index.js";
|
||||
import { createRawMemoryRoutes } from "../raw-memory/routes.js";
|
||||
import { conversationIdOf, redactSecrets, textOf, turnOf } from "../reporter.js";
|
||||
export const name = 'dsh-brain-raw';
|
||||
/** Services required before `apply` runs. */
|
||||
export const inject = ['tools'];
|
||||
function isInjected(value) {
|
||||
if (value === null || typeof value !== 'object')
|
||||
return false;
|
||||
const source = value.source;
|
||||
if (source === null || typeof source !== 'object')
|
||||
return false;
|
||||
const kind = source.kind;
|
||||
return typeof kind === 'string' && kind !== 'user';
|
||||
}
|
||||
function workspaceOf(session) {
|
||||
return session.cwd ?? session.workspace ?? session.header?.cwd ?? session.header?.workspace;
|
||||
}
|
||||
function messageIdOf(value) {
|
||||
if (value === null || typeof value !== 'object')
|
||||
return undefined;
|
||||
const id = value.id;
|
||||
return typeof id === 'string' && id !== '' ? id : undefined;
|
||||
}
|
||||
function epochOf(time) {
|
||||
if (typeof time === 'number' && Number.isFinite(time))
|
||||
return time;
|
||||
if (typeof time === 'string' && time.trim() !== '') {
|
||||
const parsed = Date.parse(time);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
/** Register the raw recorder with the host. */
|
||||
export function apply(ctx, config) {
|
||||
const runtime = createRawMemoryRuntime(config);
|
||||
const logger = ctx.logger('dsh-brain');
|
||||
ctx.inject(['tools'], (toolsCtx) => {
|
||||
const tools = toolsCtx.tools;
|
||||
if (tools === undefined)
|
||||
return;
|
||||
for (const tool of runtime.tools) {
|
||||
toolsCtx.effect(() => tools.register(tool), `dsh-brain-raw: tool ${tool.name}`);
|
||||
}
|
||||
});
|
||||
ctx.inject(['webServer'], (webCtx) => {
|
||||
const webServer = webCtx.webServer;
|
||||
if (webServer === undefined)
|
||||
return;
|
||||
for (const route of createRawMemoryRoutes({ store: runtime.store, settings: () => runtime.settings })) {
|
||||
webCtx.effect(() => webServer.register(route), `dsh-brain-raw: route ${route.path}`);
|
||||
}
|
||||
});
|
||||
const seen = new Map();
|
||||
const onEvent = ctx.on;
|
||||
ctx.effect(() => {
|
||||
const dispose = onEvent('session/event', (session, event) => {
|
||||
if (!runtime.settings.enabled)
|
||||
return;
|
||||
if (event === null || typeof event !== 'object')
|
||||
return;
|
||||
if (event.type !== 'user/message' && event.type !== 'assistant/message')
|
||||
return;
|
||||
if (event.type === 'assistant/message' && !runtime.settings.captureAssistant)
|
||||
return;
|
||||
const sessionId = conversationIdOf(session);
|
||||
if (sessionId === undefined)
|
||||
return;
|
||||
const value = event.data?.message ?? event.data;
|
||||
if (event.type === 'user/message' && isInjected(value))
|
||||
return;
|
||||
const raw = textOf(value);
|
||||
if (raw === undefined || raw.trim() === '')
|
||||
return;
|
||||
const seq = typeof event.seq === 'number' && Number.isFinite(event.seq) ? event.seq : undefined;
|
||||
const dedupe = `${sessionId}:${seq === undefined ? event.type + ':' + raw.slice(0, 120) : String(seq)}:${event.type}`;
|
||||
if (seen.has(dedupe))
|
||||
return;
|
||||
seen.set(dedupe, Date.now());
|
||||
if (seen.size > 10_000) {
|
||||
const oldest = seen.keys().next();
|
||||
if (oldest.done !== true)
|
||||
seen.delete(oldest.value);
|
||||
}
|
||||
const turn = turnOf(event.data);
|
||||
const messageId = messageIdOf(value);
|
||||
const time = epochOf(event.time);
|
||||
const workspace = workspaceOf(session);
|
||||
const record = {
|
||||
v: 1,
|
||||
sessionId,
|
||||
...(seq === undefined ? {} : { seq }),
|
||||
...(turn === undefined ? {} : { turn }),
|
||||
role: event.type === 'user/message' ? 'user' : 'assistant',
|
||||
text: redactSecrets(raw).slice(0, runtime.settings.maxTextChars),
|
||||
...(time === undefined ? {} : { time }),
|
||||
...(messageId === undefined ? {} : { messageId }),
|
||||
createdAt: Date.now(),
|
||||
...(workspace === undefined ? {} : { workspace }),
|
||||
};
|
||||
void runtime.store.append(record).catch((error) => {
|
||||
logger.warn('dsh-brain-raw capture failed: ' + (error instanceof Error ? error.message : String(error)));
|
||||
});
|
||||
});
|
||||
return () => dispose();
|
||||
}, 'dsh-brain-raw: session capture');
|
||||
// Retention is checked once on load and then every six hours; it only deletes
|
||||
// whole session files whose last write is older than the configured window.
|
||||
ctx.effect(() => {
|
||||
void runtime.store.prune(runtime.settings.retentionDays).catch(() => undefined);
|
||||
const timer = setInterval(() => { void runtime.store.prune(runtime.settings.retentionDays); }, 6 * 60 * 60 * 1000);
|
||||
timer.unref?.();
|
||||
return () => clearInterval(timer);
|
||||
}, 'dsh-brain-raw: retention');
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import * as memory from "./entries/memory.js";
|
|||
import * as skills from "./entries/skills.js";
|
||||
import * as mcp from "./entries/mcp.js";
|
||||
import * as ui from "./entries/ui.js";
|
||||
import * as raw from "./entries/raw.js";
|
||||
/** Package name; also the client bundle id. */
|
||||
export const name = 'dsh-brain';
|
||||
/** Services required before `apply` runs. */
|
||||
|
|
@ -18,4 +19,5 @@ export function apply(ctx, config) {
|
|||
skills.apply(ctx, config);
|
||||
mcp.apply(ctx, config);
|
||||
ui.apply(ctx, config);
|
||||
raw.apply(ctx, config);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -92,8 +92,6 @@ export class DepartmentManager {
|
|||
}
|
||||
async update(id, patch, expectedRevision, scope) {
|
||||
const current = await this.required(id, scope);
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
if (patch.role !== undefined && containsSecret(patch.role))
|
||||
throw new Error('secret_not_allowed');
|
||||
return this.registry(current.scope).update(async (file) => {
|
||||
|
|
@ -166,8 +164,6 @@ export class DepartmentManager {
|
|||
}
|
||||
async checkpoint(id, input, expectedRevision, scope) {
|
||||
const current = await this.required(id, scope);
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000);
|
||||
const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000);
|
||||
if ((currentTask !== undefined && containsSecret(currentTask)) || (handoff !== undefined && containsSecret(handoff)))
|
||||
|
|
@ -243,6 +239,9 @@ export class DepartmentManager {
|
|||
/** Disable without deleting private memories or allowing automatic session recovery. */
|
||||
async disable(id, expectedRevision, scope) {
|
||||
const current = await this.required(id, scope);
|
||||
// Fail on a stale revision before deactivating the space below: the update
|
||||
// callback re-checks under the registry lock, but the deactivation has
|
||||
// already happened by then.
|
||||
if (expectedRevision !== undefined && current.revision !== expectedRevision)
|
||||
throw new Error('revision_conflict');
|
||||
const store = this.store(current);
|
||||
|
|
|
|||
|
|
@ -320,12 +320,9 @@ export class LocalMemoryManager {
|
|||
return new JsonDocumentStore(join(root, 'documents')).list();
|
||||
}
|
||||
async addDocument(input, workspace) {
|
||||
const store = await this.ensureProject(workspace);
|
||||
void store;
|
||||
const root = this.projectRootFor(workspace);
|
||||
const documents = this.workspaces.get(root)?.documents;
|
||||
if (documents === undefined)
|
||||
throw new Error('local_documents_unavailable');
|
||||
await this.ensureProject(workspace);
|
||||
// ensureProject guarantees the workspace entry exists (the map is never pruned).
|
||||
const documents = this.workspaces.get(this.projectRootFor(workspace)).documents;
|
||||
return documents.add(input);
|
||||
}
|
||||
async storageStatus(workspace, scope) {
|
||||
|
|
@ -425,9 +422,8 @@ export class LocalMemoryManager {
|
|||
processedNext.add(turn.turnId);
|
||||
let documentId;
|
||||
if (fresh.length > 0) {
|
||||
const documents = this.workspaces.get(this.projectRootFor(workspace))?.documents;
|
||||
if (documents === undefined)
|
||||
throw new Error('local_documents_unavailable');
|
||||
// ensureProject above guarantees the workspace entry exists (the map is never pruned).
|
||||
const documents = this.workspaces.get(this.projectRootFor(workspace)).documents;
|
||||
const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] });
|
||||
documentId = document.id;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ function searchTool(deps) {
|
|||
const result = await deps.remote().search(query, k, project, workspace);
|
||||
if (!result.ok)
|
||||
throw new Error(`检索失败:${describeError(result.error)}`);
|
||||
const matches = result.data.matches ?? [];
|
||||
const matches = result.data.matches;
|
||||
return {
|
||||
query,
|
||||
total: result.data.total ?? matches.length,
|
||||
|
|
@ -237,7 +237,7 @@ function listTool(deps) {
|
|||
const result = await deps.remote().list({ limit, offset, project }, workspace);
|
||||
if (!result.ok)
|
||||
throw new Error(`列表读取失败:${describeError(result.error)}`);
|
||||
const items = result.data.items ?? [];
|
||||
const items = result.data.items;
|
||||
return { total: result.data.total ?? items.length, items: items.map(toHitView) };
|
||||
},
|
||||
};
|
||||
|
|
@ -258,7 +258,7 @@ function projectsTool(deps) {
|
|||
const result = await deps.remote().projects(workspace);
|
||||
if (!result.ok)
|
||||
throw new Error(`项目列表读取失败:${describeError(result.error)}`);
|
||||
return { projects: result.data.projects ?? [] };
|
||||
return { projects: result.data.projects };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -150,7 +150,7 @@ export class LongMemoryProvider {
|
|||
description: 'Account-wide default scope (no project filter).',
|
||||
connection: {},
|
||||
}];
|
||||
for (const project of result.data.projects ?? []) {
|
||||
for (const project of result.data.projects) {
|
||||
if (typeof project.id !== 'string' || project.id === '')
|
||||
continue;
|
||||
spaces.push({
|
||||
|
|
@ -183,7 +183,7 @@ export class LongMemoryProvider {
|
|||
throw new Error(`LongMemory search failed: ${result.error.message}`);
|
||||
}
|
||||
return {
|
||||
results: (result.data.matches ?? [])
|
||||
results: result.data.matches
|
||||
.map(insightFromHit)
|
||||
.filter((item) => item !== undefined),
|
||||
};
|
||||
|
|
@ -201,7 +201,7 @@ export class LongMemoryProvider {
|
|||
if (!result.ok) {
|
||||
throw new Error(`LongMemory list failed: ${result.error.message}`);
|
||||
}
|
||||
return (result.data.items ?? [])
|
||||
return result.data.items
|
||||
.map(insightFromHit)
|
||||
.filter((item) => item !== undefined);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,8 +28,8 @@ export class LocalMnemonProvider {
|
|||
}
|
||||
async status(body) {
|
||||
try {
|
||||
const status = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body)));
|
||||
return { healthy: true, stats: { totalInsights: Number(status.spaces?.project ? 0 : 0), deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } };
|
||||
await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body)));
|
||||
return { healthy: true, stats: { totalInsights: 0, deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } };
|
||||
}
|
||||
catch (error) {
|
||||
return { healthy: false, error: error instanceof Error ? error.message : String(error) };
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
/**
|
||||
* Original-record layer public surface.
|
||||
*
|
||||
* This module deliberately has no dependency on Mnemon's core: a host entry
|
||||
* can create the recorder, register its three tools, and feed it session
|
||||
* events without changing any Mnemon source, database or UI.
|
||||
*/
|
||||
import { RawMemoryStore } from "./store.js";
|
||||
import { rawMemorySettingsFromConfig } from "./settings.js";
|
||||
import { createRawMemoryTools } from "./tools.js";
|
||||
/** Build the raw recorder and its tools from one row config. */
|
||||
export function createRawMemoryRuntime(config) {
|
||||
const settings = rawMemorySettingsFromConfig(config);
|
||||
const store = new RawMemoryStore({
|
||||
root: settings.dir,
|
||||
maxBytesPerSession: settings.maxBytesPerSession,
|
||||
});
|
||||
return {
|
||||
settings,
|
||||
store,
|
||||
tools: createRawMemoryTools({ store, settings: () => settings }),
|
||||
};
|
||||
}
|
||||
export { RawMemoryStore } from "./store.js";
|
||||
export { createRawMemoryTools } from "./tools.js";
|
||||
export { rawMemorySettingsFromConfig } from "./settings.js";
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
import { fail, json } from "../http.js";
|
||||
function urlOf(req) {
|
||||
return new URL(req.url ?? '/', 'http://localhost');
|
||||
}
|
||||
function method(req, res, allowed) {
|
||||
if (req.method === allowed || (allowed === 'GET' && req.method === 'HEAD'))
|
||||
return true;
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return false;
|
||||
}
|
||||
function numberParam(url, name, fallback, min, max) {
|
||||
const parsed = Number.parseInt(url.searchParams.get(name) ?? '', 10);
|
||||
if (!Number.isFinite(parsed))
|
||||
return fallback;
|
||||
return Math.min(max, Math.max(min, parsed));
|
||||
}
|
||||
function serveStatus(deps, req, res) {
|
||||
if (!method(req, res, 'GET'))
|
||||
return;
|
||||
const settings = deps.settings();
|
||||
void deps.store.status(settings.enabled, settings.retentionDays).then((status) => {
|
||||
json(res, 200, { ok: true, ...status });
|
||||
}).catch((error) => {
|
||||
fail(res, 500, error instanceof Error ? error.message : 'raw-status-failed');
|
||||
});
|
||||
}
|
||||
function serveSessions(deps, req, res) {
|
||||
if (!method(req, res, 'GET'))
|
||||
return;
|
||||
const settings = deps.settings();
|
||||
if (!settings.enabled) {
|
||||
fail(res, 503, 'raw-disabled');
|
||||
return;
|
||||
}
|
||||
const url = urlOf(req);
|
||||
const limit = numberParam(url, 'limit', 30, 1, 100);
|
||||
void deps.store.listSessions(limit).then((sessions) => {
|
||||
json(res, 200, { ok: true, sessions });
|
||||
}).catch((error) => {
|
||||
fail(res, 500, error instanceof Error ? error.message : 'raw-sessions-failed');
|
||||
});
|
||||
}
|
||||
function serveSearch(deps, req, res) {
|
||||
if (!method(req, res, 'GET'))
|
||||
return;
|
||||
const settings = deps.settings();
|
||||
if (!settings.enabled) {
|
||||
fail(res, 503, 'raw-disabled');
|
||||
return;
|
||||
}
|
||||
const url = urlOf(req);
|
||||
const query = (url.searchParams.get('q') ?? '').trim();
|
||||
if (query === '') {
|
||||
fail(res, 400, 'query-required');
|
||||
return;
|
||||
}
|
||||
const roleValue = url.searchParams.get('role');
|
||||
const role = roleValue === 'user' || roleValue === 'assistant' ? roleValue : undefined;
|
||||
const k = numberParam(url, 'k', settings.maxSearchResults, 1, 50);
|
||||
const sessionId = (url.searchParams.get('session_id') ?? '').trim() || undefined;
|
||||
void deps.store.search(query, { k, ...(role === undefined ? {} : { role }), ...(sessionId === undefined ? {} : { sessionId }) }).then((result) => {
|
||||
json(res, 200, {
|
||||
ok: true,
|
||||
query,
|
||||
total: result.total,
|
||||
truncated: result.truncated,
|
||||
sessions_scanned: result.sessionsScanned,
|
||||
matches: result.matches,
|
||||
});
|
||||
}).catch((error) => {
|
||||
fail(res, 500, error instanceof Error ? error.message : 'raw-search-failed');
|
||||
});
|
||||
}
|
||||
function serveSession(deps, req, res) {
|
||||
if (!method(req, res, 'GET'))
|
||||
return;
|
||||
const settings = deps.settings();
|
||||
if (!settings.enabled) {
|
||||
fail(res, 503, 'raw-disabled');
|
||||
return;
|
||||
}
|
||||
const url = urlOf(req);
|
||||
const sessionId = (url.searchParams.get('session_id') ?? '').trim();
|
||||
if (sessionId === '') {
|
||||
fail(res, 400, 'session-id-required');
|
||||
return;
|
||||
}
|
||||
const seqValue = url.searchParams.get('seq');
|
||||
const seq = seqValue === null ? undefined : Number.parseInt(seqValue, 10);
|
||||
const offset = numberParam(url, 'offset', 0, 0, 1000000);
|
||||
const limit = numberParam(url, 'limit', settings.maxReadRecords, 1, 500);
|
||||
void deps.store.readSession(sessionId, {
|
||||
...(seq === undefined || !Number.isFinite(seq) ? {} : { seq }),
|
||||
...(seq === undefined ? { offset } : {}),
|
||||
limit,
|
||||
}).then((result) => {
|
||||
json(res, 200, { ok: true, session_id: result.sessionId, total: result.total, items: result.items });
|
||||
}).catch((error) => {
|
||||
fail(res, 500, error instanceof Error ? error.message : 'raw-session-failed');
|
||||
});
|
||||
}
|
||||
export function createRawMemoryRoutes(deps) {
|
||||
return [
|
||||
{ kind: 'exact', path: '/dsh-brain/raw/status', handler: (req, res) => serveStatus(deps, req, res) },
|
||||
{ kind: 'exact', path: '/dsh-brain/raw/sessions', handler: (req, res) => serveSessions(deps, req, res) },
|
||||
{ kind: 'exact', path: '/dsh-brain/raw/search', handler: (req, res) => serveSearch(deps, req, res) },
|
||||
{ kind: 'exact', path: '/dsh-brain/raw/session', handler: (req, res) => serveSession(deps, req, res) },
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
/**
|
||||
* Raw-layer configuration.
|
||||
*
|
||||
* The row config in cordis.patch.yml is the first-boot seed. Keeping the
|
||||
* parser here (rather than in the five-bundle Settings store) lets the raw
|
||||
* recorder stay an optional, self-contained row: disabling the row stops all
|
||||
* capture, and changing its config changes the recorder without touching
|
||||
* Mnemon or the existing memory bundles.
|
||||
*/
|
||||
import { join, resolve } from 'node:path';
|
||||
import { dshHome } from "../store.js";
|
||||
function asRecord(value) {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
||||
return {};
|
||||
return value;
|
||||
}
|
||||
function bool(value, fallback) {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
function integer(value, fallback, min, max) {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value))
|
||||
return fallback;
|
||||
return Math.min(max, Math.max(min, Math.trunc(value)));
|
||||
}
|
||||
/** Parse one raw-row config defensively; every field is optional. */
|
||||
export function rawMemorySettingsFromConfig(config) {
|
||||
const source = asRecord(config);
|
||||
const rawDir = typeof source.rawDir === 'string' ? source.rawDir.trim() : '';
|
||||
return {
|
||||
enabled: bool(source.rawEnabled, true),
|
||||
captureAssistant: bool(source.rawCaptureAssistant, true),
|
||||
dir: rawDir === '' ? join(dshHome(), 'brain', 'raw') : resolve(rawDir),
|
||||
retentionDays: integer(source.rawRetentionDays, 90, 1, 3650),
|
||||
maxBytesPerSession: integer(source.rawMaxBytesPerSession, 20_000_000, 100_000, 1_000_000_000),
|
||||
maxTextChars: integer(source.rawMaxTextChars, 16_000, 1_000, 200_000),
|
||||
maxSearchResults: integer(source.rawMaxSearchResults, 10, 1, 50),
|
||||
maxReadRecords: integer(source.rawMaxReadRecords, 50, 1, 500),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,267 @@
|
|||
/**
|
||||
* Append-only original-record store.
|
||||
*
|
||||
* One JSONL file per session, under a separate directory from Mnemon's
|
||||
* mnemon.db. The raw layer deliberately does not join Mnemon's identity /
|
||||
* merge tables: those walk every non-oplog row and would become slower with
|
||||
* every captured message. Rotation keeps one session bounded; retention is
|
||||
* enforced by the entry's maintenance timer.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { appendFile, mkdir, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
function sizeOf(path) {
|
||||
return stat(path).then((info) => info.size).catch(() => 0);
|
||||
}
|
||||
function snippetFor(text, terms) {
|
||||
const lower = text.toLowerCase();
|
||||
let first = -1;
|
||||
for (const term of terms) {
|
||||
const found = lower.indexOf(term);
|
||||
if (found >= 0 && (first < 0 || found < first))
|
||||
first = found;
|
||||
}
|
||||
const start = first <= 80 ? 0 : first - 80;
|
||||
const end = Math.min(text.length, start + 500);
|
||||
return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`;
|
||||
}
|
||||
function isRecord(value) {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
||||
return false;
|
||||
const record = value;
|
||||
return record.v === 1
|
||||
&& typeof record.sessionId === 'string'
|
||||
&& typeof record.text === 'string'
|
||||
&& (record.role === 'user' || record.role === 'assistant')
|
||||
&& typeof record.createdAt === 'number';
|
||||
}
|
||||
export class RawMemoryStore {
|
||||
options;
|
||||
queues = new Map();
|
||||
sizes = new Map();
|
||||
constructor(options) {
|
||||
this.options = { ...options, maxScanBytes: options.maxScanBytes ?? 128 * 1024 * 1024 };
|
||||
}
|
||||
get dir() {
|
||||
return this.options.root;
|
||||
}
|
||||
safeSessionName(sessionId) {
|
||||
const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80) || 'session';
|
||||
const hash = createHash('sha256').update(sessionId).digest('hex').slice(0, 8);
|
||||
return `${readable}-${hash}`;
|
||||
}
|
||||
fileFor(sessionId) {
|
||||
return join(this.options.root, `${this.safeSessionName(sessionId)}.jsonl`);
|
||||
}
|
||||
rotatedFor(file) {
|
||||
return file.replace(/\.jsonl$/, '.1.jsonl');
|
||||
}
|
||||
async listFiles() {
|
||||
try {
|
||||
const entries = await readdir(this.options.root, { withFileTypes: true });
|
||||
return entries
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl'))
|
||||
.map((entry) => join(this.options.root, entry.name))
|
||||
.sort();
|
||||
}
|
||||
catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
async readRecords(file) {
|
||||
let text;
|
||||
try {
|
||||
text = await readFile(file, 'utf8');
|
||||
}
|
||||
catch {
|
||||
return [];
|
||||
}
|
||||
const records = [];
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
if (line.trim() === '')
|
||||
continue;
|
||||
try {
|
||||
const value = JSON.parse(line);
|
||||
if (isRecord(value))
|
||||
records.push(value);
|
||||
}
|
||||
catch {
|
||||
// A torn final line must not make the rest of the file unreadable.
|
||||
}
|
||||
}
|
||||
return records;
|
||||
}
|
||||
/** Append one message, serialized per session so concurrent turns cannot interleave. */
|
||||
async append(record) {
|
||||
const file = this.fileFor(record.sessionId);
|
||||
const line = `${JSON.stringify(record)}\n`;
|
||||
const incoming = Buffer.byteLength(line, 'utf8');
|
||||
const previous = this.queues.get(file) ?? Promise.resolve();
|
||||
const next = previous.then(async () => {
|
||||
await mkdir(this.options.root, { recursive: true });
|
||||
let size = this.sizes.get(file);
|
||||
if (size === undefined)
|
||||
size = await sizeOf(file);
|
||||
if (size > 0 && size + incoming > this.options.maxBytesPerSession) {
|
||||
const rotated = this.rotatedFor(file);
|
||||
await rm(rotated, { force: true }).catch(() => undefined);
|
||||
await rename(file, rotated).catch(() => undefined);
|
||||
size = 0;
|
||||
}
|
||||
await appendFile(file, line, { encoding: 'utf8', mode: 0o600 });
|
||||
this.sizes.set(file, size + incoming);
|
||||
}).finally(() => {
|
||||
if (this.queues.get(file) === next)
|
||||
this.queues.delete(file);
|
||||
});
|
||||
this.queues.set(file, next);
|
||||
await next;
|
||||
}
|
||||
/** Keyword search over original text, newest / best match first. */
|
||||
async search(query, options = {}) {
|
||||
const normalized = query.trim().toLowerCase();
|
||||
const terms = normalized.split(/\s+/).filter((term) => term !== '');
|
||||
if (terms.length === 0)
|
||||
return { matches: [], total: 0, truncated: false, sessionsScanned: 0 };
|
||||
// Boundary responsibility: callers (raw tools and routes) validate and clamp k.
|
||||
const k = options.k ?? 10;
|
||||
const files = await this.listFiles();
|
||||
const matches = [];
|
||||
const seenSessions = new Set();
|
||||
let total = 0;
|
||||
let scannedBytes = 0;
|
||||
let truncated = false;
|
||||
for (const file of files) {
|
||||
// The scan cap is always set by the constructor; hitting it is reported
|
||||
// explicitly through `truncated`, never silently.
|
||||
if (scannedBytes >= this.options.maxScanBytes) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
scannedBytes += await sizeOf(file);
|
||||
for (const record of await this.readRecords(file)) {
|
||||
seenSessions.add(record.sessionId);
|
||||
if (options.sessionId !== undefined && record.sessionId !== options.sessionId)
|
||||
continue;
|
||||
if (options.role !== undefined && record.role !== options.role)
|
||||
continue;
|
||||
const haystack = `${record.text.toLowerCase()}\n${record.sessionId.toLowerCase()}`;
|
||||
let score = 0;
|
||||
for (const term of terms)
|
||||
if (haystack.includes(term))
|
||||
score += 1;
|
||||
if (score === 0)
|
||||
continue;
|
||||
if (haystack.includes(normalized))
|
||||
score += 2;
|
||||
total += 1;
|
||||
matches.push({
|
||||
sessionId: record.sessionId,
|
||||
...(record.seq === undefined ? {} : { seq: record.seq }),
|
||||
...(record.turn === undefined ? {} : { turn: record.turn }),
|
||||
role: record.role,
|
||||
...(record.time === undefined ? {} : { time: record.time }),
|
||||
createdAt: record.createdAt,
|
||||
...(record.messageId === undefined ? {} : { messageId: record.messageId }),
|
||||
snippet: snippetFor(record.text, terms),
|
||||
score,
|
||||
});
|
||||
}
|
||||
}
|
||||
matches.sort((left, right) => right.score - left.score || right.createdAt - left.createdAt);
|
||||
return { matches: matches.slice(0, k), total, truncated, sessionsScanned: seenSessions.size };
|
||||
}
|
||||
/** Read one session, either by exact event seq or by record offset. */
|
||||
async readSession(sessionId, options = {}) {
|
||||
const file = this.fileFor(sessionId);
|
||||
const records = [...await this.readRecords(this.rotatedFor(file)), ...await this.readRecords(file)];
|
||||
let selected = records;
|
||||
if (options.seq !== undefined) {
|
||||
selected = records.filter((record) => record.seq === options.seq);
|
||||
}
|
||||
else {
|
||||
// Boundary responsibility: callers (raw tools and routes) validate and clamp offset/limit.
|
||||
const offset = options.offset ?? 0;
|
||||
const limit = options.limit ?? 50;
|
||||
selected = records.slice(offset, offset + limit);
|
||||
}
|
||||
return { sessionId, total: records.length, items: selected };
|
||||
}
|
||||
/** Aggregate counts for the status tool. */
|
||||
async status(enabled, retentionDays) {
|
||||
const files = await this.listFiles();
|
||||
let records = 0;
|
||||
let bytes = 0;
|
||||
const sessions = new Set();
|
||||
let oldest;
|
||||
let newest;
|
||||
for (const file of files) {
|
||||
bytes += await sizeOf(file);
|
||||
for (const record of await this.readRecords(file)) {
|
||||
records += 1;
|
||||
sessions.add(record.sessionId);
|
||||
if (oldest === undefined || record.createdAt < oldest)
|
||||
oldest = record.createdAt;
|
||||
if (newest === undefined || record.createdAt > newest)
|
||||
newest = record.createdAt;
|
||||
}
|
||||
}
|
||||
return {
|
||||
enabled,
|
||||
dir: this.options.root,
|
||||
sessions: sessions.size,
|
||||
records,
|
||||
bytes,
|
||||
...(oldest === undefined ? {} : { oldestAt: new Date(oldest).toISOString() }),
|
||||
...(newest === undefined ? {} : { newestAt: new Date(newest).toISOString() }),
|
||||
retentionDays,
|
||||
maxBytesPerSession: this.options.maxBytesPerSession,
|
||||
};
|
||||
}
|
||||
/** Session rows for the Brain panel's session browser, newest first. */
|
||||
async listSessions(limit = 30) {
|
||||
const files = await this.listFiles();
|
||||
const sessions = new Map();
|
||||
for (const file of files) {
|
||||
const bytes = await sizeOf(file);
|
||||
const records = await this.readRecords(file);
|
||||
if (records.length === 0)
|
||||
continue;
|
||||
const sessionId = records[0].sessionId;
|
||||
const summary = sessions.get(sessionId) ?? { sessionId, records: 0, bytes: 0 };
|
||||
summary.records += records.length;
|
||||
summary.bytes += bytes;
|
||||
for (const record of records) {
|
||||
const stamp = record.time ?? record.createdAt;
|
||||
if (summary.firstAt === undefined || stamp < summary.firstAt)
|
||||
summary.firstAt = stamp;
|
||||
if (summary.lastAt === undefined || stamp > summary.lastAt)
|
||||
summary.lastAt = stamp;
|
||||
summary.latestSnippet = record.text.slice(0, 160);
|
||||
}
|
||||
sessions.set(sessionId, summary);
|
||||
}
|
||||
return [...sessions.values()]
|
||||
.sort((left, right) => (right.lastAt ?? 0) - (left.lastAt ?? 0))
|
||||
.slice(0, Math.max(1, Math.min(200, Math.trunc(limit))));
|
||||
}
|
||||
/** Delete session files whose last write is older than the retention window. */
|
||||
async prune(retentionDays) {
|
||||
const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1000;
|
||||
let removed = 0;
|
||||
for (const file of await this.listFiles()) {
|
||||
try {
|
||||
const info = await stat(file);
|
||||
if (info.mtimeMs < cutoff) {
|
||||
await rm(file, { force: true });
|
||||
removed += 1;
|
||||
this.sizes.delete(file);
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// A file removed concurrently is already in the desired state.
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
function renderJson(_args, value) {
|
||||
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
|
||||
return [{ type: 'text', text }];
|
||||
}
|
||||
function searchTool(deps) {
|
||||
return {
|
||||
name: 'memory_raw_search',
|
||||
description: '在原始对话记录中按关键词搜索原话(不是记忆条目,也不是摘要)。返回会话 id、事件 seq、说话角色、时间和原文片段;' +
|
||||
'需要完整上下文时用 memory_raw_read 按 session_id + seq 读取。纯本地关键词匹配。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
||||
k: { type: 'integer', description: '最多返回条数(1..50,默认取配置值)。' },
|
||||
session_id: { type: 'string', description: '可选:只在这个会话内搜索。' },
|
||||
role: { type: 'string', enum: ['user', 'assistant'], description: '可选:只看用户或助手原话。' },
|
||||
},
|
||||
required: ['query'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string' },
|
||||
total: { type: 'number' },
|
||||
truncated: { type: 'boolean' },
|
||||
sessions_scanned: { type: 'number' },
|
||||
matches: { type: 'array', items: { type: 'object' } },
|
||||
},
|
||||
required: ['query', 'matches'],
|
||||
additionalProperties: true,
|
||||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
const settings = deps.settings();
|
||||
if (!settings.enabled)
|
||||
throw new Error('原始记录层当前已禁用(dsh-brain-raw 行未启用)。');
|
||||
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) : settings.maxSearchResults;
|
||||
const k = Math.min(50, Math.max(1, requested));
|
||||
const sessionId = typeof args.session_id === 'string' && args.session_id !== '' ? args.session_id : undefined;
|
||||
const role = args.role === 'user' || args.role === 'assistant' ? args.role : undefined;
|
||||
const result = await deps.store.search(query, { k, ...(sessionId === undefined ? {} : { sessionId }), ...(role === undefined ? {} : { role }) });
|
||||
return {
|
||||
query,
|
||||
total: result.total,
|
||||
truncated: result.truncated,
|
||||
sessions_scanned: result.sessionsScanned,
|
||||
matches: result.matches,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
function readTool(deps) {
|
||||
return {
|
||||
name: 'memory_raw_read',
|
||||
description: '读取某个会话的原始记录:给 seq 时返回那一条原话,否则按 offset/limit 分页浏览。' +
|
||||
'返回 sessionId、seq、turn、role、text 与时间。用于核对记忆条目、追查原话出处。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
session_id: { type: 'string', description: '会话 id(必填,可用 memory_raw_search 获得)。' },
|
||||
seq: { type: 'integer', description: '可选:精确读取该事件 seq 对应的那一条。' },
|
||||
offset: { type: 'integer', description: '可选:从第几条开始(默认 0)。' },
|
||||
limit: { type: 'integer', description: '可选:读取条数(1..500,默认取配置值)。' },
|
||||
},
|
||||
required: ['session_id'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
output: {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
session_id: { type: 'string' },
|
||||
total: { type: 'number' },
|
||||
items: { type: 'array', items: { type: 'object' } },
|
||||
},
|
||||
required: ['session_id', 'items'],
|
||||
additionalProperties: true,
|
||||
},
|
||||
render: renderJson,
|
||||
},
|
||||
async execute(args) {
|
||||
const settings = deps.settings();
|
||||
if (!settings.enabled)
|
||||
throw new Error('原始记录层当前已禁用(dsh-brain-raw 行未启用)。');
|
||||
const sessionId = typeof args.session_id === 'string' ? args.session_id.trim() : '';
|
||||
if (sessionId === '')
|
||||
throw new Error('session_id 不能为空。');
|
||||
const seq = typeof args.seq === 'number' && Number.isFinite(args.seq) ? Math.trunc(args.seq) : undefined;
|
||||
const offset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0;
|
||||
const requested = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : settings.maxReadRecords;
|
||||
const limit = Math.min(500, Math.max(1, requested));
|
||||
const result = await deps.store.readSession(sessionId, { ...(seq === undefined ? {} : { seq }), offset, limit });
|
||||
return { session_id: result.sessionId, total: result.total, items: result.items };
|
||||
},
|
||||
};
|
||||
}
|
||||
function statusTool(deps) {
|
||||
return {
|
||||
name: 'memory_raw_status',
|
||||
description: '查看原始记录层状态:保存目录、会话数、记录数、占用空间、最早/最新时间与保留天数。',
|
||||
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
||||
output: {
|
||||
schema: { type: 'object', properties: {}, required: [], additionalProperties: true },
|
||||
render: renderJson,
|
||||
},
|
||||
async execute() {
|
||||
const settings = deps.settings();
|
||||
return deps.store.status(settings.enabled, settings.retentionDays);
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Build the three raw-layer tools. */
|
||||
export function createRawMemoryTools(deps) {
|
||||
return [searchTool(deps), readTool(deps), statusTool(deps)];
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export {};
|
||||
|
|
@ -311,7 +311,7 @@ export class Reporter {
|
|||
/** Take this turn's messages out of the buffer, capped by the char budget. */
|
||||
takeTranscript(conversationId, turn) {
|
||||
const { picked } = this.partitionTranscript(conversationId, turn);
|
||||
const maxChars = Math.max(1000, this.options.summary().maxChars);
|
||||
const maxChars = this.options.summary().maxChars;
|
||||
let total = 0;
|
||||
const kept = [];
|
||||
for (const message of picked) {
|
||||
|
|
@ -367,13 +367,13 @@ export class Reporter {
|
|||
const client = this.clientFor(context);
|
||||
const result = await client.submitSummary(payload, token);
|
||||
if (result.ok) {
|
||||
this.summaryStaged += typeof result.data.staged === 'number' ? result.data.staged : 0;
|
||||
this.summaryStaged += result.data.staged ?? 0;
|
||||
return;
|
||||
}
|
||||
if (result.error.status === 0 || result.error.status >= 500) {
|
||||
const retry = await client.submitSummary(payload, token);
|
||||
if (retry.ok) {
|
||||
this.summaryStaged += typeof retry.data.staged === 'number' ? retry.data.staged : 0;
|
||||
this.summaryStaged += retry.data.staged ?? 0;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
|
@ -482,9 +482,8 @@ export class Reporter {
|
|||
// A queued entry belongs to the account that failed to send it. After a
|
||||
// token or endpoint switch the current credential must not replay old
|
||||
// records to (or as) a different account, so stale entries are dropped.
|
||||
// The loop condition guarantees a head; no await runs between them.
|
||||
const head = this.queue[0];
|
||||
if (head === undefined)
|
||||
break;
|
||||
if (head.scope !== scope) {
|
||||
this.queue.shift();
|
||||
this.options.log(`dsh-brain: dropping queued turn report for a switched account: ${head.payload.turn_id}`);
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { createSettingsUiRoutes } from "./settings-ui/routes.js";
|
|||
import { serveDepartments } from "./settings-ui/departments-routes.js";
|
||||
import { brainStatus, migrateLegacyFiles } from "./brain-migration.js";
|
||||
import { mcpCapability } from "./mcp.js";
|
||||
import { fail, json, readBody, sameOrigin } from "./http.js";
|
||||
import { fail, json, jsonBody, readBody, sameOrigin } from "./http.js";
|
||||
import { createCloudSyncRoutes, getLastCheck } from "./cloudsync-routes.js";
|
||||
import { createSkillRoutes } from "./skills/routes.js";
|
||||
/** Route constants — kept in one place so the client half can reuse them. */
|
||||
|
|
@ -121,31 +121,9 @@ function serveCapabilities(deps, req, res) {
|
|||
}
|
||||
/** `PUT /dsh-brain/config`. */
|
||||
async function serveConfig(deps, req, res) {
|
||||
if (req.method !== 'PUT' && req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
const patch = await jsonBody(req, res);
|
||||
if (patch === undefined)
|
||||
return;
|
||||
}
|
||||
if (!sameOrigin(req)) {
|
||||
fail(res, 403, 'origin-rejected');
|
||||
return;
|
||||
}
|
||||
const type = (req.headers['content-type'] ?? '').toLowerCase();
|
||||
if (!type.startsWith('application/json')) {
|
||||
fail(res, 415, 'json-required');
|
||||
return;
|
||||
}
|
||||
let patch;
|
||||
try {
|
||||
patch = JSON.parse(await readBody(req));
|
||||
}
|
||||
catch (error) {
|
||||
fail(res, 400, error instanceof Error && error.message === 'request-too-large' ? 'request-too-large' : 'invalid-json');
|
||||
return;
|
||||
}
|
||||
if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) {
|
||||
fail(res, 400, 'invalid-patch');
|
||||
return;
|
||||
}
|
||||
const result = deps.store.patch(patch);
|
||||
if (!result.ok) {
|
||||
fail(res, 400, result.error ?? 'invalid-patch');
|
||||
|
|
|
|||
|
|
@ -209,7 +209,7 @@ export class SkillAdmin {
|
|||
const source = await readSkillSourceRecord(dir);
|
||||
return {
|
||||
folder,
|
||||
name: typeof name === 'string' && name !== '' ? name : folder,
|
||||
name: name ?? folder,
|
||||
description: String(frontmatter.description ?? '').slice(0, 300),
|
||||
enabled,
|
||||
origin,
|
||||
|
|
@ -484,7 +484,7 @@ export class SkillAdmin {
|
|||
const name = frontmatter.name;
|
||||
candidates.push({
|
||||
folder: candidate.folder,
|
||||
name: typeof name === 'string' && name !== '' ? name : candidate.folder,
|
||||
name: name ?? candidate.folder,
|
||||
description: String(frontmatter.description ?? '').slice(0, 300),
|
||||
files: files.length,
|
||||
bytes,
|
||||
|
|
|
|||
|
|
@ -314,7 +314,8 @@ export class SkillGroupManager {
|
|||
catch {
|
||||
throw new SkillGroupError('not_found', `来源里没有这个技能:${folder}`);
|
||||
}
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
||||
// lstat never reports a symlink as a directory, so this also rejects links.
|
||||
if (!stat.isDirectory()) {
|
||||
throw new SkillGroupError('invalid_skill', `来源技能不是普通目录:${folder}`);
|
||||
}
|
||||
const rootReal = realpathSync(source.root);
|
||||
|
|
@ -329,7 +330,8 @@ export class SkillGroupManager {
|
|||
catch {
|
||||
throw new SkillGroupError('invalid_skill', `来源技能缺少 SKILL.md:${folder}`);
|
||||
}
|
||||
if (!marker.isFile() || marker.isSymbolicLink()) {
|
||||
// lstat never reports a symlink as a regular file, so this also rejects links.
|
||||
if (!marker.isFile()) {
|
||||
throw new SkillGroupError('invalid_skill', `来源技能的 SKILL.md 不是普通文件:${folder}`);
|
||||
}
|
||||
return this.deps.admin.importFolder(dirReal, folder);
|
||||
|
|
|
|||
|
|
@ -403,7 +403,8 @@ export class SkillSync {
|
|||
const listing = await client.listSkills();
|
||||
if (!listing.ok)
|
||||
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
|
||||
const items = (listing.data.items ?? []).filter((item) => typeof item.name === 'string' && CLOUD_SKILL_NAME.test(item.name));
|
||||
// validateSkillListing already guarantees items is an array of summaries with non-empty string names.
|
||||
const items = listing.data.items.filter((item) => CLOUD_SKILL_NAME.test(item.name));
|
||||
const cloudByName = new Map(items.map((item) => [item.name, item]));
|
||||
let stateDirty = false;
|
||||
// Self-heal: an uploaded folder whose delivery receipt reappeared (a
|
||||
|
|
@ -451,8 +452,8 @@ export class SkillSync {
|
|||
continue;
|
||||
}
|
||||
const removed = state.removed[item.name];
|
||||
const uploaded = state.uploaded[item.name];
|
||||
const localFolder = uploaded?.folder ?? state.delivered[item.name]?.folder ?? item.name;
|
||||
// Uploaded names were skipped above, so only a delivery receipt can name the folder here.
|
||||
const localFolder = state.delivered[item.name]?.folder ?? item.name;
|
||||
const local = await repo.read(localFolder);
|
||||
const exists = local !== undefined;
|
||||
const delivery = local?.delivery;
|
||||
|
|
@ -924,7 +925,7 @@ export class SkillSync {
|
|||
try {
|
||||
const listing = await active.client.listSkills();
|
||||
if (listing.ok)
|
||||
cloudItems = listing.data.items ?? [];
|
||||
cloudItems = listing.data.items;
|
||||
}
|
||||
catch {
|
||||
// Offline: report local sides only, never throw the list away.
|
||||
|
|
@ -1007,14 +1008,14 @@ export class SkillSync {
|
|||
const listing = await client.listSkills();
|
||||
if (!listing.ok)
|
||||
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
|
||||
const cloud = (listing.data.items ?? []).find((item) => item.name === name);
|
||||
const cloud = listing.data.items.find((item) => item.name === name);
|
||||
const state = await this.loadState(scope);
|
||||
const localFolder = preview?.folder ?? state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name;
|
||||
const localNow = await repo.read(localFolder);
|
||||
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
|
||||
if (localVersionNow !== confirmed.localVersion)
|
||||
throw new Error('stale_conflict');
|
||||
if ((cloud?.revision ?? undefined) !== (confirmed.cloud?.revision ?? undefined) || (cloud?.manifest_sha256 ?? undefined) !== (confirmed.cloud?.manifest ?? undefined))
|
||||
if (cloud?.revision !== confirmed.cloud?.revision || cloud?.manifest_sha256 !== confirmed.cloud?.manifest)
|
||||
throw new Error('stale_conflict');
|
||||
if (action === 'manual') {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -342,10 +342,6 @@ async function serveClients(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
if (suffix === '/workspaces/add') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
|
|
@ -354,10 +350,6 @@ async function serveClients(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
if (suffix === '/workspaces/remove') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
|
|
@ -374,10 +366,6 @@ async function serveClients(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
if (suffix === '/workspace/detail') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
|
|
@ -386,10 +374,6 @@ async function serveClients(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
if (suffix === '/workspace/toggle') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
|
|
@ -398,10 +382,6 @@ async function serveClients(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
if (suffix === '/workspace/remove') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
|
|
@ -412,10 +392,6 @@ async function serveClients(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
if (suffix === '/workspace/install/plan') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
|
|
@ -424,10 +400,6 @@ async function serveClients(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
if (suffix === '/workspace/install/commit') {
|
||||
if (req.method !== 'POST') {
|
||||
fail(res, 405, 'method-not-allowed');
|
||||
return;
|
||||
}
|
||||
const body = await jsonBody(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -275,9 +275,9 @@ export class SettingsStore {
|
|||
* marker blocks the env fallback until a new token is written.
|
||||
*/
|
||||
tokenFor(label, sidecar) {
|
||||
if (sidecar !== undefined && sidecar !== '')
|
||||
if (sidecar !== undefined)
|
||||
return sidecar;
|
||||
if (this.state.clearedTokens?.includes(label) === true)
|
||||
if (this.state.clearedTokens?.includes(label))
|
||||
return '';
|
||||
const envPrefix = label === 'activity' ? 'DSH_BRAIN_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_BRAIN_MEMORY_TOKEN' : 'DSH_BRAIN_SUMMARY_TOKEN';
|
||||
const legacyPrefix = label === 'activity' ? 'DSH_CLOUD_MEMORY_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_CLOUD_MEMORY_MEMORY_TOKEN' : 'DSH_CLOUD_MEMORY_SUMMARY_TOKEN';
|
||||
|
|
@ -290,7 +290,7 @@ export class SettingsStore {
|
|||
}
|
||||
/** Which layer currently supplies each token (drives the card's hint). */
|
||||
tokenSource(label, sidecar) {
|
||||
if (sidecar !== undefined && sidecar !== '')
|
||||
if (sidecar !== undefined)
|
||||
return 'sidecar';
|
||||
if (this.tokenFor(label, sidecar) !== '')
|
||||
return 'env';
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ function skillListTool(deps) {
|
|||
const result = await deps.client().listSkills();
|
||||
if (!result.ok)
|
||||
throw new Error(`技能列表读取失败:${describeError(result.error)}`);
|
||||
const skills = (result.data.items ?? []).map((item) => ({
|
||||
const skills = result.data.items.map((item) => ({
|
||||
name: item.name,
|
||||
description: item.description ?? '',
|
||||
revision: item.revision ?? null,
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const FALLBACK_VERSION = '0.10.2';
|
||||
const FALLBACK_VERSION = '0.10.3';
|
||||
function readVersion() {
|
||||
try {
|
||||
const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'));
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-brain",
|
||||
"version": "0.10.2",
|
||||
"version": "0.10.3",
|
||||
"description": "Cloud memory for DSH: report one activity turn per conversation round and expose memory_search / memory_read / memory_add tools against a LongMemory cloud endpoint.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const FALLBACK_VERSION = '0.10.2'
|
||||
const FALLBACK_VERSION = '0.10.3'
|
||||
|
||||
function readVersion(): string {
|
||||
try {
|
||||
|
|
|
|||
Loading…
Reference in New Issue