diff --git a/lib/kernel.js b/lib/kernel.js index 0a58009..fcafde9 100644 --- a/lib/kernel.js +++ b/lib/kernel.js @@ -226,6 +226,13 @@ export class BrainKernel { return this.active.has(bundle); } /** Tool deps shared by the memory and skill entries. */ + departmentToolDeps() { + return { + departments: () => this.departments, + settings: () => ({ localMemoryEnabled: this.settingsOf().localMemoryEnabled, memoryEnabled: this.settingsOf().memoryEnabled }), + workspace: (exec) => workspaceFromExec(exec), + }; + } toolDeps() { const store = this.store; const settings = this.settingsOf; diff --git a/lib/memory/departments-tools.js b/lib/memory/departments-tools.js new file mode 100644 index 0000000..8c04ad9 --- /dev/null +++ b/lib/memory/departments-tools.js @@ -0,0 +1,148 @@ +import { renderJson } from "./tools.js"; +function snippet(text, limit = 600) { + return text.length <= limit ? text : text.slice(0, limit) + '…'; +} +function requireEnabled(deps) { + const settings = deps.settings(); + if (settings.memoryEnabled === false || settings.localMemoryEnabled === false) { + throw new Error('部门功能当前已禁用。请在 /dsh-brain 页面开启本地记忆和记忆功能后再试。'); + } +} +function list(value) { + if (!Array.isArray(value)) + return undefined; + return value.filter((item) => typeof item === 'string').slice(0, 50); +} +function text(value) { return typeof value === 'string' ? value : undefined; } +function revision(value) { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined; } +export function createDepartmentTools(deps) { + const department_create = { + name: 'department_create', + description: '创建一个部门工作身份。部门拥有私有记忆空间;同名同 scope 幂等返回已有部门,不覆盖。', + parameters: { + type: 'object', + properties: { + name: { type: 'string', description: '部门名称(必填)' }, + role: { type: 'string', description: '部门角色说明(可选,最多 12000 字符)' }, + scope: { type: 'string', enum: ['global', 'project'], description: '部门空间范围,默认 project' }, + skills: { type: 'array', items: { type: 'string' }, description: '关联技能名列表' }, + allowedTools: { type: 'array', items: { type: 'string' }, description: '允许使用的工具名列表' }, + readGlobal: { type: 'boolean', description: '是否允许读取全局记忆,默认 true' }, + readProject: { type: 'boolean', description: '是否允许读取项目记忆,默认 true' }, + }, + required: ['name'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args) { + requireEnabled(deps); + const name = text(args.name)?.trim() ?? ''; + if (name === '') + throw new Error('部门名称不能为空。'); + const input = { name, ...(text(args.role) === undefined ? {} : { role: text(args.role) }), ...(args.scope === 'global' || args.scope === 'project' ? { scope: args.scope } : {}), ...(list(args.skills) === undefined ? {} : { skills: list(args.skills) }), ...(list(args.allowedTools) === undefined ? {} : { allowedTools: list(args.allowedTools) }), ...(typeof args.readGlobal === 'boolean' ? { readGlobal: args.readGlobal } : {}), ...(typeof args.readProject === 'boolean' ? { readProject: args.readProject } : {}) }; + const result = await deps.departments().create(input); + return { id: result.department.id, name: result.department.name, scope: result.department.scope, created: result.created }; + }, + }; + const department_list = { + name: 'department_list', + description: '列出部门及其精简状态;role 全文不返回,按需使用部门详情接口。', + parameters: { type: 'object', properties: { scope: { type: 'string', enum: ['global', 'project'] } }, additionalProperties: false }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args) { + requireEnabled(deps); + const scope = args.scope === 'global' || args.scope === 'project' ? args.scope : undefined; + const rows = await deps.departments().list(scope); + return { departments: rows.map((department) => ({ id: department.id, name: department.name, scope: department.scope, active: department.active, ...(department.currentTask === undefined ? {} : { currentTask: department.currentTask }), revision: department.revision })) }; + }, + }; + const department_remember = { + name: 'department_remember', + description: '向一个部门的私有记忆空间写入记忆。秘密、令牌和密钥不得写入。', + parameters: { + type: 'object', + properties: { departmentId: { type: 'string' }, content: { type: 'string' }, category: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } }, + required: ['departmentId', 'content'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args) { + requireEnabled(deps); + const id = text(args.departmentId)?.trim() ?? ''; + const content = text(args.content)?.trim() ?? ''; + if (id === '') + throw new Error('departmentId 不能为空。'); + if (content === '') + throw new Error('content 不能为空。'); + const result = await deps.departments().remember(id, { content, ...(text(args.category) === undefined ? {} : { category: text(args.category) }), ...(list(args.tags) === undefined ? {} : { tags: list(args.tags) }) }); + return { id: result.record.id, duplicate: result.duplicate }; + }, + }; + const department_recall = { + name: 'department_recall', + description: '从部门私有空间召回相关记忆,最多 5 条;返回内容为去敏后的短片段。', + parameters: { + type: 'object', + properties: { departmentId: { type: 'string' }, query: { type: 'string' }, k: { type: 'integer', minimum: 1, maximum: 5 } }, + required: ['departmentId', 'query'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args, exec) { + requireEnabled(deps); + const id = text(args.departmentId)?.trim() ?? ''; + const query = text(args.query)?.trim() ?? ''; + if (id === '') + throw new Error('departmentId 不能为空。'); + if (query === '') + throw new Error('query 不能为空。'); + const requested = revision(args.k) ?? 5; + const k = Math.max(1, Math.min(5, requested)); + const hits = await deps.departments().recall(id, query, k, deps.workspace(exec)); + return { hits: hits.map((hit) => ({ id: hit.record.id, origin: hit.origin, content: snippet(hit.record.content) })) }; + }, + }; + const department_checkpoint = { + name: 'department_checkpoint', + description: '更新部门当前任务或交接说明,并返回新 revision。', + parameters: { + type: 'object', + properties: { departmentId: { type: 'string' }, currentTask: { type: 'string' }, handoff: { type: 'string' }, expectedRevision: { type: 'integer' } }, + required: ['departmentId'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args) { + requireEnabled(deps); + const id = text(args.departmentId)?.trim() ?? ''; + if (id === '') + throw new Error('departmentId 不能为空。'); + const department = await deps.departments().checkpoint(id, { ...(text(args.currentTask) === undefined ? {} : { currentTask: text(args.currentTask) }), ...(text(args.handoff) === undefined ? {} : { handoff: text(args.handoff) }) }, revision(args.expectedRevision)); + return { revision: department.revision, updatedAt: department.updatedAt }; + }, + }; + const department_resume = { + name: 'department_resume', + description: '获取部门可复用会话引用;传入 hostSessionId 时显式绑定宿主会话。', + parameters: { + type: 'object', + properties: { departmentId: { type: 'string' }, host: { type: 'string' }, hostSessionId: { type: 'string' } }, + required: ['departmentId'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args) { + requireEnabled(deps); + const id = text(args.departmentId)?.trim() ?? ''; + if (id === '') + throw new Error('departmentId 不能为空。'); + const host = text(args.host)?.trim() || 'dsh'; + const hostSessionId = text(args.hostSessionId)?.trim(); + const sessionRef = hostSessionId !== undefined && hostSessionId !== '' + ? await deps.departments().attachSession(id, host, hostSessionId) + : await deps.departments().resumeSession(id, host); + return { sessionRef }; + }, + }; + return [department_create, department_list, department_remember, department_recall, department_checkpoint, department_resume]; +} diff --git a/src/kernel.ts b/src/kernel.ts index 1f0afd9..2a148cb 100644 --- a/src/kernel.ts +++ b/src/kernel.ts @@ -23,6 +23,7 @@ import { CloudClient } from './api.ts' import { DepartmentManager, LocalMemoryManager, LocalMemoryRemote } from './local-memory/index.ts' import { VERSION } from './version.ts' import { createCloudMemoryRemoteFactory } from './cloudsync.ts' +import type { DepartmentToolDeps } from './memory/departments-tools.ts' import { ClientRegistry } from './clients.ts' import { ClaudePluginMarketplaceProvider, MarketService } from './market.ts' import { Reporter } from './reporter.ts' @@ -255,6 +256,14 @@ export class BrainKernel { } /** Tool deps shared by the memory and skill entries. */ + departmentToolDeps(): DepartmentToolDeps { + return { + departments: () => this.departments, + settings: () => ({ localMemoryEnabled: this.settingsOf().localMemoryEnabled, memoryEnabled: this.settingsOf().memoryEnabled }), + workspace: (exec?: unknown) => workspaceFromExec(exec), + } + } + toolDeps() { const store = this.store const settings = this.settingsOf diff --git a/src/memory/departments-tools.ts b/src/memory/departments-tools.ts new file mode 100644 index 0000000..820f445 --- /dev/null +++ b/src/memory/departments-tools.ts @@ -0,0 +1,161 @@ +/** Agent-facing department tools. Hand-written definitions; no dsh-tools import. */ +import type { ToolDefinitionLike } from '../context-types.ts' +import type { DepartmentManager } from '../local-memory/departments/index.ts' +import type { DepartmentCreateInput, DepartmentRecallHit } from '../local-memory/departments/types.ts' +import { renderJson } from './tools.ts' + +export interface DepartmentToolDeps { + departments: () => DepartmentManager + settings: () => { localMemoryEnabled: boolean; memoryEnabled: boolean } + workspace: (exec?: unknown) => string | undefined +} + +function snippet(text: string, limit = 600): string { + return text.length <= limit ? text : text.slice(0, limit) + '…' +} + +function requireEnabled(deps: DepartmentToolDeps): void { + const settings = deps.settings() + if (settings.memoryEnabled === false || settings.localMemoryEnabled === false) { + throw new Error('部门功能当前已禁用。请在 /dsh-brain 页面开启本地记忆和记忆功能后再试。') + } +} + +function list(value: unknown): string[] | undefined { + if (!Array.isArray(value)) return undefined + return value.filter((item): item is string => typeof item === 'string').slice(0, 50) +} + +function text(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined } +function revision(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined } + +export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionLike[] { + const department_create: ToolDefinitionLike = { + name: 'department_create', + description: '创建一个部门工作身份。部门拥有私有记忆空间;同名同 scope 幂等返回已有部门,不覆盖。', + parameters: { + type: 'object', + properties: { + name: { type: 'string', description: '部门名称(必填)' }, + role: { type: 'string', description: '部门角色说明(可选,最多 12000 字符)' }, + scope: { type: 'string', enum: ['global', 'project'], description: '部门空间范围,默认 project' }, + skills: { type: 'array', items: { type: 'string' }, description: '关联技能名列表' }, + allowedTools: { type: 'array', items: { type: 'string' }, description: '允许使用的工具名列表' }, + readGlobal: { type: 'boolean', description: '是否允许读取全局记忆,默认 true' }, + readProject: { type: 'boolean', description: '是否允许读取项目记忆,默认 true' }, + }, + required: ['name'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args: Record): Promise { + requireEnabled(deps) + const name = text(args.name)?.trim() ?? '' + if (name === '') throw new Error('部门名称不能为空。') + const input: DepartmentCreateInput = { name, ...(text(args.role) === undefined ? {} : { role: text(args.role) }), ...(args.scope === 'global' || args.scope === 'project' ? { scope: args.scope } : {}), ...(list(args.skills) === undefined ? {} : { skills: list(args.skills) }), ...(list(args.allowedTools) === undefined ? {} : { allowedTools: list(args.allowedTools) }), ...(typeof args.readGlobal === 'boolean' ? { readGlobal: args.readGlobal } : {}), ...(typeof args.readProject === 'boolean' ? { readProject: args.readProject } : {}) } + const result = await deps.departments().create(input) + return { id: result.department.id, name: result.department.name, scope: result.department.scope, created: result.created } + }, + } + + const department_list: ToolDefinitionLike = { + name: 'department_list', + description: '列出部门及其精简状态;role 全文不返回,按需使用部门详情接口。', + parameters: { type: 'object', properties: { scope: { type: 'string', enum: ['global', 'project'] } }, additionalProperties: false }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args: Record): Promise { + requireEnabled(deps) + const scope = args.scope === 'global' || args.scope === 'project' ? args.scope : undefined + const rows = await deps.departments().list(scope) + return { departments: rows.map((department) => ({ id: department.id, name: department.name, scope: department.scope, active: department.active, ...(department.currentTask === undefined ? {} : { currentTask: department.currentTask }), revision: department.revision })) } + }, + } + + const department_remember: ToolDefinitionLike = { + name: 'department_remember', + description: '向一个部门的私有记忆空间写入记忆。秘密、令牌和密钥不得写入。', + parameters: { + type: 'object', + properties: { departmentId: { type: 'string' }, content: { type: 'string' }, category: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } }, + required: ['departmentId', 'content'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args: Record): Promise { + requireEnabled(deps) + const id = text(args.departmentId)?.trim() ?? '' + const content = text(args.content)?.trim() ?? '' + if (id === '') throw new Error('departmentId 不能为空。') + if (content === '') throw new Error('content 不能为空。') + const result = await deps.departments().remember(id, { content, ...(text(args.category) === undefined ? {} : { category: text(args.category) }), ...(list(args.tags) === undefined ? {} : { tags: list(args.tags) }) }) + return { id: result.record.id, duplicate: result.duplicate } + }, + } + + const department_recall: ToolDefinitionLike = { + name: 'department_recall', + description: '从部门私有空间召回相关记忆,最多 5 条;返回内容为去敏后的短片段。', + parameters: { + type: 'object', + properties: { departmentId: { type: 'string' }, query: { type: 'string' }, k: { type: 'integer', minimum: 1, maximum: 5 } }, + required: ['departmentId', 'query'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args: Record, exec?: unknown): Promise { + requireEnabled(deps) + const id = text(args.departmentId)?.trim() ?? '' + const query = text(args.query)?.trim() ?? '' + if (id === '') throw new Error('departmentId 不能为空。') + if (query === '') throw new Error('query 不能为空。') + const requested = revision(args.k) ?? 5 + const k = Math.max(1, Math.min(5, requested)) + const hits = await deps.departments().recall(id, query, k, deps.workspace(exec)) + return { hits: hits.map((hit: DepartmentRecallHit) => ({ id: hit.record.id, origin: hit.origin, content: snippet(hit.record.content) })) } + }, + } + + const department_checkpoint: ToolDefinitionLike = { + name: 'department_checkpoint', + description: '更新部门当前任务或交接说明,并返回新 revision。', + parameters: { + type: 'object', + properties: { departmentId: { type: 'string' }, currentTask: { type: 'string' }, handoff: { type: 'string' }, expectedRevision: { type: 'integer' } }, + required: ['departmentId'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args: Record): Promise { + requireEnabled(deps) + const id = text(args.departmentId)?.trim() ?? '' + if (id === '') throw new Error('departmentId 不能为空。') + const department = await deps.departments().checkpoint(id, { ...(text(args.currentTask) === undefined ? {} : { currentTask: text(args.currentTask) }), ...(text(args.handoff) === undefined ? {} : { handoff: text(args.handoff) }) }, revision(args.expectedRevision)) + return { revision: department.revision, updatedAt: department.updatedAt } + }, + } + + const department_resume: ToolDefinitionLike = { + name: 'department_resume', + description: '获取部门可复用会话引用;传入 hostSessionId 时显式绑定宿主会话。', + parameters: { + type: 'object', + properties: { departmentId: { type: 'string' }, host: { type: 'string' }, hostSessionId: { type: 'string' } }, + required: ['departmentId'], + additionalProperties: false, + }, + output: { schema: { type: 'object' }, render: renderJson }, + async execute(args: Record): Promise { + requireEnabled(deps) + const id = text(args.departmentId)?.trim() ?? '' + if (id === '') throw new Error('departmentId 不能为空。') + const host = text(args.host)?.trim() || 'dsh' + const hostSessionId = text(args.hostSessionId)?.trim() + const sessionRef = hostSessionId !== undefined && hostSessionId !== '' + ? await deps.departments().attachSession(id, host, hostSessionId) + : await deps.departments().resumeSession(id, host) + return { sessionRef } + }, + } + + return [department_create, department_list, department_remember, department_recall, department_checkpoint, department_resume] +}