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:
newbie 2026-11-27 17:16:44 +08:00
parent da562de002
commit 31037b0d31
31 changed files with 1563 additions and 465 deletions

View File

@ -1,14 +1,15 @@
# dsh-brain # dsh-brain
> **0.10.1**:插件按功能拆成五个可单独开关的子插件(见「五个子插件」); > **0.10.3**:插件按功能拆成六个可单独开关的子插件,新增可选的原始记录层
> 技能同步引入按内容与更新时间的自动冲突解决(0.9.9/0.9.10 语义); > `dsh-brain-raw`(见「六个子插件」);同步清理了不可达的防御性分支与重复
> 令牌环境变量改为**绑定服务地址**(见「配置」)。 > 响应校验。0.10.1 起技能同步按内容与更新时间自动解决冲突(0.9.9/0.9.10
> 语义),令牌环境变量**绑定服务地址**(见「配置」)。
把 DeepSeek Harness 接到 LongMemory 云端记忆服务:每轮对话结束自动上报一条 把 DeepSeek Harness 接到 LongMemory 云端记忆服务:每轮对话结束自动上报一条
活动记录(只上传元数据),并把云端记忆库变成 agent 可用的工具;同时双向 活动记录(只上传元数据),并把云端记忆库变成 agent 可用的工具;同时双向
同步云端技能中心与本机技能目录。 同步云端技能中心与本机技能目录。
当前版本 **0.10.1**,含宿主端与浏览器端两部分:宿主端负责活动上报、 当前版本 **0.10.3**,含宿主端与浏览器端两部分:宿主端负责活动上报、
记忆工具注册与技能同步。浏览器 UI 有三个入口: 记忆工具注册与技能同步。浏览器 UI 有三个入口:
- 左侧栏 **Brain** 展示全局运行状态,管理全局记忆与部门。 - 左侧栏 **Brain** 展示全局运行状态,管理全局记忆与部门。

File diff suppressed because it is too large Load Diff

View File

@ -200,7 +200,6 @@ function validateSkillListing(value) {
function validateSkillBundle(value) { function validateSkillBundle(value) {
const body = requireResponseObject(value, 'skill bundle response'); const body = requireResponseObject(value, 'skill bundle response');
requireResponseString(body, 'name'); requireResponseString(body, 'name');
optionalResponseNumber(body, 'revision');
if (typeof body.revision !== 'number' || !Number.isFinite(body.revision)) { if (typeof body.revision !== 'number' || !Number.isFinite(body.revision)) {
throw new Error('revision must be a number'); throw new Error('revision must be a number');
} }
@ -466,12 +465,8 @@ export class CloudClient {
if (base === '') if (base === '')
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }; return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } };
const headers = { Accept: 'application/json' }; const headers = { Accept: 'application/json' };
try { // authBase already parsed this exact URL successfully, so this cannot throw.
headers.Origin = new URL(baseUrl).origin; headers.Origin = new URL(baseUrl).origin;
}
catch {
return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } };
}
if (cookie !== undefined && cookie !== '') if (cookie !== undefined && cookie !== '')
headers.Cookie = cookie; headers.Cookie = cookie;
const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) }; const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) };

View File

@ -191,9 +191,7 @@ export class ClientRegistry {
if (software === undefined) if (software === undefined)
throw new Error('invalid_software'); throw new Error('invalid_software');
const path = typeof pathInput === 'string' ? pathInput.trim() : ''; const path = typeof pathInput === 'string' ? pathInput.trim() : '';
if (path === '' || !existsSync(path)) const stats = path === '' ? undefined : await stat(path).catch(() => undefined);
throw new Error('invalid_path');
const stats = await stat(path).catch(() => undefined);
if (stats === undefined || !stats.isDirectory()) if (stats === undefined || !stats.isDirectory())
throw new Error('invalid_path'); throw new Error('invalid_path');
const resolved = resolve(path); const resolved = resolve(path);
@ -232,7 +230,7 @@ export class ClientRegistry {
const frontmatter = parseSkillFrontmatter(markdown); const frontmatter = parseSkillFrontmatter(markdown);
out.push({ out.push({
folder: entry.name, 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), description: String(frontmatter.description ?? '').slice(0, 300),
path: skillDir, path: skillDir,
softwareId: software, softwareId: software,

View File

@ -72,7 +72,7 @@ async function serveTest(deps, req, res) {
id: 'memory', id: 'memory',
label: '记忆读写权限(memory:write)', label: '记忆读写权限(memory:write)',
state: probe.ok ? 'ok' : checkState(probe.error), 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(); 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 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); const summary = await client.mintToken(session.data.sessionCookie, 'summary:write', TOKEN_LABELS.summary, target);
if (!activity.ok && !memory.ok) { if (!activity.ok && !memory.ok) {
const first = activity.ok ? memory : activity; json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${describeError(activity.error)}` });
const reason = first.ok ? '无法创建令牌' : describeError(first.error);
json(res, 400, { ok: false, error: `登录成功,但创建令牌失败:${reason}` });
return; return;
} }
// Atomic account switch: a scope whose mint failed must not keep the token // Atomic account switch: a scope whose mint failed must not keep the token

View File

@ -70,13 +70,9 @@ export function isPlaceholderBaseUrl(value) {
const normalized = normalizeBaseUrl(value); const normalized = normalizeBaseUrl(value);
if (normalized === undefined) if (normalized === undefined)
return true; return true;
try { // normalized was built from a successfully parsed URL, so this cannot throw.
const host = new URL(normalized).hostname.toLowerCase(); const host = new URL(normalized).hostname.toLowerCase();
return host === 'your-memory-host' || host === 'example.com'; return host === 'your-memory-host' || host === 'example.com';
}
catch {
return true;
}
} }
/** Service origin of one base URL, or '' when it cannot be parsed. */ /** Service origin of one base URL, or '' when it cannot be parsed. */
export function originOf(value) { export function originOf(value) {

View File

@ -147,7 +147,6 @@ export class BrainLogger {
if (this.warned) if (this.warned)
return; return;
this.warned = true; 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');
} }
} }

115
lib/entries/raw.js Normal file
View File

@ -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');
}

View File

@ -3,6 +3,7 @@ import * as memory from "./entries/memory.js";
import * as skills from "./entries/skills.js"; import * as skills from "./entries/skills.js";
import * as mcp from "./entries/mcp.js"; import * as mcp from "./entries/mcp.js";
import * as ui from "./entries/ui.js"; import * as ui from "./entries/ui.js";
import * as raw from "./entries/raw.js";
/** Package name; also the client bundle id. */ /** Package name; also the client bundle id. */
export const name = 'dsh-brain'; export const name = 'dsh-brain';
/** Services required before `apply` runs. */ /** Services required before `apply` runs. */
@ -18,4 +19,5 @@ export function apply(ctx, config) {
skills.apply(ctx, config); skills.apply(ctx, config);
mcp.apply(ctx, config); mcp.apply(ctx, config);
ui.apply(ctx, config); ui.apply(ctx, config);
raw.apply(ctx, config);
} }

View File

@ -92,8 +92,6 @@ export class DepartmentManager {
} }
async update(id, patch, expectedRevision, scope) { async update(id, patch, expectedRevision, scope) {
const current = await this.required(id, 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)) if (patch.role !== undefined && containsSecret(patch.role))
throw new Error('secret_not_allowed'); throw new Error('secret_not_allowed');
return this.registry(current.scope).update(async (file) => { return this.registry(current.scope).update(async (file) => {
@ -166,8 +164,6 @@ export class DepartmentManager {
} }
async checkpoint(id, input, expectedRevision, scope) { async checkpoint(id, input, expectedRevision, scope) {
const current = await this.required(id, 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 currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000);
const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000); const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000);
if ((currentTask !== undefined && containsSecret(currentTask)) || (handoff !== undefined && containsSecret(handoff))) 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. */ /** Disable without deleting private memories or allowing automatic session recovery. */
async disable(id, expectedRevision, scope) { async disable(id, expectedRevision, scope) {
const current = await this.required(id, 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) if (expectedRevision !== undefined && current.revision !== expectedRevision)
throw new Error('revision_conflict'); throw new Error('revision_conflict');
const store = this.store(current); const store = this.store(current);

View File

@ -320,12 +320,9 @@ export class LocalMemoryManager {
return new JsonDocumentStore(join(root, 'documents')).list(); return new JsonDocumentStore(join(root, 'documents')).list();
} }
async addDocument(input, workspace) { async addDocument(input, workspace) {
const store = await this.ensureProject(workspace); await this.ensureProject(workspace);
void store; // ensureProject guarantees the workspace entry exists (the map is never pruned).
const root = this.projectRootFor(workspace); const documents = this.workspaces.get(this.projectRootFor(workspace)).documents;
const documents = this.workspaces.get(root)?.documents;
if (documents === undefined)
throw new Error('local_documents_unavailable');
return documents.add(input); return documents.add(input);
} }
async storageStatus(workspace, scope) { async storageStatus(workspace, scope) {
@ -425,9 +422,8 @@ export class LocalMemoryManager {
processedNext.add(turn.turnId); processedNext.add(turn.turnId);
let documentId; let documentId;
if (fresh.length > 0) { if (fresh.length > 0) {
const documents = this.workspaces.get(this.projectRootFor(workspace))?.documents; // ensureProject above guarantees the workspace entry exists (the map is never pruned).
if (documents === undefined) const documents = this.workspaces.get(this.projectRootFor(workspace)).documents;
throw new Error('local_documents_unavailable');
const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] }); const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] });
documentId = document.id; documentId = document.id;
} }

View File

@ -100,7 +100,7 @@ function searchTool(deps) {
const result = await deps.remote().search(query, k, project, workspace); const result = await deps.remote().search(query, k, project, workspace);
if (!result.ok) if (!result.ok)
throw new Error(`检索失败:${describeError(result.error)}`); throw new Error(`检索失败:${describeError(result.error)}`);
const matches = result.data.matches ?? []; const matches = result.data.matches;
return { return {
query, query,
total: result.data.total ?? matches.length, total: result.data.total ?? matches.length,
@ -237,7 +237,7 @@ function listTool(deps) {
const result = await deps.remote().list({ limit, offset, project }, workspace); const result = await deps.remote().list({ limit, offset, project }, workspace);
if (!result.ok) if (!result.ok)
throw new Error(`列表读取失败:${describeError(result.error)}`); 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) }; 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); const result = await deps.remote().projects(workspace);
if (!result.ok) if (!result.ok)
throw new Error(`项目列表读取失败:${describeError(result.error)}`); throw new Error(`项目列表读取失败:${describeError(result.error)}`);
return { projects: result.data.projects ?? [] }; return { projects: result.data.projects };
}, },
}; };
} }

View File

@ -150,7 +150,7 @@ export class LongMemoryProvider {
description: 'Account-wide default scope (no project filter).', description: 'Account-wide default scope (no project filter).',
connection: {}, connection: {},
}]; }];
for (const project of result.data.projects ?? []) { for (const project of result.data.projects) {
if (typeof project.id !== 'string' || project.id === '') if (typeof project.id !== 'string' || project.id === '')
continue; continue;
spaces.push({ spaces.push({
@ -183,7 +183,7 @@ export class LongMemoryProvider {
throw new Error(`LongMemory search failed: ${result.error.message}`); throw new Error(`LongMemory search failed: ${result.error.message}`);
} }
return { return {
results: (result.data.matches ?? []) results: result.data.matches
.map(insightFromHit) .map(insightFromHit)
.filter((item) => item !== undefined), .filter((item) => item !== undefined),
}; };
@ -201,7 +201,7 @@ export class LongMemoryProvider {
if (!result.ok) { if (!result.ok) {
throw new Error(`LongMemory list failed: ${result.error.message}`); throw new Error(`LongMemory list failed: ${result.error.message}`);
} }
return (result.data.items ?? []) return result.data.items
.map(insightFromHit) .map(insightFromHit)
.filter((item) => item !== undefined); .filter((item) => item !== undefined);
} }

View File

@ -28,8 +28,8 @@ export class LocalMnemonProvider {
} }
async status(body) { async status(body) {
try { try {
const status = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body))); 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: [] } }; return { healthy: true, stats: { totalInsights: 0, deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } };
} }
catch (error) { catch (error) {
return { healthy: false, error: error instanceof Error ? error.message : String(error) }; return { healthy: false, error: error instanceof Error ? error.message : String(error) };

26
lib/raw-memory/index.js Normal file
View File

@ -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";

109
lib/raw-memory/routes.js Normal file
View File

@ -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) },
];
}

View File

@ -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),
};
}

267
lib/raw-memory/store.js Normal file
View File

@ -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;
}
}

121
lib/raw-memory/tools.js Normal file
View File

@ -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)];
}

1
lib/raw-memory/types.js Normal file
View File

@ -0,0 +1 @@
export {};

View File

@ -311,7 +311,7 @@ export class Reporter {
/** Take this turn's messages out of the buffer, capped by the char budget. */ /** Take this turn's messages out of the buffer, capped by the char budget. */
takeTranscript(conversationId, turn) { takeTranscript(conversationId, turn) {
const { picked } = this.partitionTranscript(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; let total = 0;
const kept = []; const kept = [];
for (const message of picked) { for (const message of picked) {
@ -367,13 +367,13 @@ export class Reporter {
const client = this.clientFor(context); const client = this.clientFor(context);
const result = await client.submitSummary(payload, token); const result = await client.submitSummary(payload, token);
if (result.ok) { if (result.ok) {
this.summaryStaged += typeof result.data.staged === 'number' ? result.data.staged : 0; this.summaryStaged += result.data.staged ?? 0;
return; return;
} }
if (result.error.status === 0 || result.error.status >= 500) { if (result.error.status === 0 || result.error.status >= 500) {
const retry = await client.submitSummary(payload, token); const retry = await client.submitSummary(payload, token);
if (retry.ok) { if (retry.ok) {
this.summaryStaged += typeof retry.data.staged === 'number' ? retry.data.staged : 0; this.summaryStaged += retry.data.staged ?? 0;
return; return;
} }
} }
@ -482,9 +482,8 @@ export class Reporter {
// A queued entry belongs to the account that failed to send it. After a // 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 // token or endpoint switch the current credential must not replay old
// records to (or as) a different account, so stale entries are dropped. // 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]; const head = this.queue[0];
if (head === undefined)
break;
if (head.scope !== scope) { if (head.scope !== scope) {
this.queue.shift(); this.queue.shift();
this.options.log(`dsh-brain: dropping queued turn report for a switched account: ${head.payload.turn_id}`); this.options.log(`dsh-brain: dropping queued turn report for a switched account: ${head.payload.turn_id}`);

View File

@ -2,7 +2,7 @@ import { createSettingsUiRoutes } from "./settings-ui/routes.js";
import { serveDepartments } from "./settings-ui/departments-routes.js"; import { serveDepartments } from "./settings-ui/departments-routes.js";
import { brainStatus, migrateLegacyFiles } from "./brain-migration.js"; import { brainStatus, migrateLegacyFiles } from "./brain-migration.js";
import { mcpCapability } from "./mcp.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 { createCloudSyncRoutes, getLastCheck } from "./cloudsync-routes.js";
import { createSkillRoutes } from "./skills/routes.js"; import { createSkillRoutes } from "./skills/routes.js";
/** Route constants — kept in one place so the client half can reuse them. */ /** 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`. */ /** `PUT /dsh-brain/config`. */
async function serveConfig(deps, req, res) { async function serveConfig(deps, req, res) {
if (req.method !== 'PUT' && req.method !== 'POST') { const patch = await jsonBody(req, res);
fail(res, 405, 'method-not-allowed'); if (patch === undefined)
return; 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); const result = deps.store.patch(patch);
if (!result.ok) { if (!result.ok) {
fail(res, 400, result.error ?? 'invalid-patch'); fail(res, 400, result.error ?? 'invalid-patch');

View File

@ -209,7 +209,7 @@ export class SkillAdmin {
const source = await readSkillSourceRecord(dir); const source = await readSkillSourceRecord(dir);
return { return {
folder, folder,
name: typeof name === 'string' && name !== '' ? name : folder, name: name ?? folder,
description: String(frontmatter.description ?? '').slice(0, 300), description: String(frontmatter.description ?? '').slice(0, 300),
enabled, enabled,
origin, origin,
@ -484,7 +484,7 @@ export class SkillAdmin {
const name = frontmatter.name; const name = frontmatter.name;
candidates.push({ candidates.push({
folder: candidate.folder, folder: candidate.folder,
name: typeof name === 'string' && name !== '' ? name : candidate.folder, name: name ?? candidate.folder,
description: String(frontmatter.description ?? '').slice(0, 300), description: String(frontmatter.description ?? '').slice(0, 300),
files: files.length, files: files.length,
bytes, bytes,

View File

@ -314,7 +314,8 @@ export class SkillGroupManager {
catch { catch {
throw new SkillGroupError('not_found', `来源里没有这个技能:${folder}`); 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}`); throw new SkillGroupError('invalid_skill', `来源技能不是普通目录:${folder}`);
} }
const rootReal = realpathSync(source.root); const rootReal = realpathSync(source.root);
@ -329,7 +330,8 @@ export class SkillGroupManager {
catch { catch {
throw new SkillGroupError('invalid_skill', `来源技能缺少 SKILL.md:${folder}`); 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}`); throw new SkillGroupError('invalid_skill', `来源技能的 SKILL.md 不是普通文件:${folder}`);
} }
return this.deps.admin.importFolder(dirReal, folder); return this.deps.admin.importFolder(dirReal, folder);

View File

@ -403,7 +403,8 @@ export class SkillSync {
const listing = await client.listSkills(); const listing = await client.listSkills();
if (!listing.ok) if (!listing.ok)
throw new Error(`skill listing failed: ${describeError(listing.error)}`); 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])); const cloudByName = new Map(items.map((item) => [item.name, item]));
let stateDirty = false; let stateDirty = false;
// Self-heal: an uploaded folder whose delivery receipt reappeared (a // Self-heal: an uploaded folder whose delivery receipt reappeared (a
@ -451,8 +452,8 @@ export class SkillSync {
continue; continue;
} }
const removed = state.removed[item.name]; const removed = state.removed[item.name];
const uploaded = state.uploaded[item.name]; // Uploaded names were skipped above, so only a delivery receipt can name the folder here.
const localFolder = uploaded?.folder ?? state.delivered[item.name]?.folder ?? item.name; const localFolder = state.delivered[item.name]?.folder ?? item.name;
const local = await repo.read(localFolder); const local = await repo.read(localFolder);
const exists = local !== undefined; const exists = local !== undefined;
const delivery = local?.delivery; const delivery = local?.delivery;
@ -924,7 +925,7 @@ export class SkillSync {
try { try {
const listing = await active.client.listSkills(); const listing = await active.client.listSkills();
if (listing.ok) if (listing.ok)
cloudItems = listing.data.items ?? []; cloudItems = listing.data.items;
} }
catch { catch {
// Offline: report local sides only, never throw the list away. // Offline: report local sides only, never throw the list away.
@ -1007,14 +1008,14 @@ export class SkillSync {
const listing = await client.listSkills(); const listing = await client.listSkills();
if (!listing.ok) if (!listing.ok)
throw new Error(`skill listing failed: ${describeError(listing.error)}`); 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 state = await this.loadState(scope);
const localFolder = preview?.folder ?? state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name; const localFolder = preview?.folder ?? state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name;
const localNow = await repo.read(localFolder); const localNow = await repo.read(localFolder);
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n')); const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
if (localVersionNow !== confirmed.localVersion) if (localVersionNow !== confirmed.localVersion)
throw new Error('stale_conflict'); 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'); throw new Error('stale_conflict');
if (action === 'manual') { if (action === 'manual') {
return { return {

View File

@ -342,10 +342,6 @@ async function serveClients(deps, req, res) {
return; return;
} }
if (suffix === '/workspaces/add') { if (suffix === '/workspaces/add') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res); const body = await jsonBody(req, res);
if (body === undefined) if (body === undefined)
return; return;
@ -354,10 +350,6 @@ async function serveClients(deps, req, res) {
return; return;
} }
if (suffix === '/workspaces/remove') { if (suffix === '/workspaces/remove') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res); const body = await jsonBody(req, res);
if (body === undefined) if (body === undefined)
return; return;
@ -374,10 +366,6 @@ async function serveClients(deps, req, res) {
return; return;
} }
if (suffix === '/workspace/detail') { if (suffix === '/workspace/detail') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res); const body = await jsonBody(req, res);
if (body === undefined) if (body === undefined)
return; return;
@ -386,10 +374,6 @@ async function serveClients(deps, req, res) {
return; return;
} }
if (suffix === '/workspace/toggle') { if (suffix === '/workspace/toggle') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res); const body = await jsonBody(req, res);
if (body === undefined) if (body === undefined)
return; return;
@ -398,10 +382,6 @@ async function serveClients(deps, req, res) {
return; return;
} }
if (suffix === '/workspace/remove') { if (suffix === '/workspace/remove') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res); const body = await jsonBody(req, res);
if (body === undefined) if (body === undefined)
return; return;
@ -412,10 +392,6 @@ async function serveClients(deps, req, res) {
return; return;
} }
if (suffix === '/workspace/install/plan') { if (suffix === '/workspace/install/plan') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res); const body = await jsonBody(req, res);
if (body === undefined) if (body === undefined)
return; return;
@ -424,10 +400,6 @@ async function serveClients(deps, req, res) {
return; return;
} }
if (suffix === '/workspace/install/commit') { if (suffix === '/workspace/install/commit') {
if (req.method !== 'POST') {
fail(res, 405, 'method-not-allowed');
return;
}
const body = await jsonBody(req, res); const body = await jsonBody(req, res);
if (body === undefined) if (body === undefined)
return; return;

View File

@ -275,9 +275,9 @@ export class SettingsStore {
* marker blocks the env fallback until a new token is written. * marker blocks the env fallback until a new token is written.
*/ */
tokenFor(label, sidecar) { tokenFor(label, sidecar) {
if (sidecar !== undefined && sidecar !== '') if (sidecar !== undefined)
return sidecar; return sidecar;
if (this.state.clearedTokens?.includes(label) === true) if (this.state.clearedTokens?.includes(label))
return ''; return '';
const envPrefix = label === 'activity' ? 'DSH_BRAIN_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_BRAIN_MEMORY_TOKEN' : 'DSH_BRAIN_SUMMARY_TOKEN'; 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'; 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). */ /** Which layer currently supplies each token (drives the card's hint). */
tokenSource(label, sidecar) { tokenSource(label, sidecar) {
if (sidecar !== undefined && sidecar !== '') if (sidecar !== undefined)
return 'sidecar'; return 'sidecar';
if (this.tokenFor(label, sidecar) !== '') if (this.tokenFor(label, sidecar) !== '')
return 'env'; return 'env';

View File

@ -15,7 +15,7 @@ function skillListTool(deps) {
const result = await deps.client().listSkills(); const result = await deps.client().listSkills();
if (!result.ok) if (!result.ok)
throw new Error(`技能列表读取失败:${describeError(result.error)}`); throw new Error(`技能列表读取失败:${describeError(result.error)}`);
const skills = (result.data.items ?? []).map((item) => ({ const skills = result.data.items.map((item) => ({
name: item.name, name: item.name,
description: item.description ?? '', description: item.description ?? '',
revision: item.revision ?? null, revision: item.revision ?? null,

View File

@ -8,7 +8,7 @@
*/ */
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
const FALLBACK_VERSION = '0.10.2'; const FALLBACK_VERSION = '0.10.3';
function readVersion() { function readVersion() {
try { try {
const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')); const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'));

View File

@ -1,6 +1,6 @@
{ {
"name": "dsh-brain", "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.", "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", "type": "module",
"license": "MIT", "license": "MIT",

View File

@ -9,7 +9,7 @@
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
const FALLBACK_VERSION = '0.10.2' const FALLBACK_VERSION = '0.10.3'
function readVersion(): string { function readVersion(): string {
try { try {