fix(departments): bind caller workspace around every department operation
This commit is contained in:
parent
cae5c08a80
commit
22b2497e61
|
|
@ -229,6 +229,7 @@ export class BrainKernel {
|
|||
departmentToolDeps() {
|
||||
return {
|
||||
departments: () => this.departments,
|
||||
memory: () => this.localMemory,
|
||||
settings: () => ({ localMemoryEnabled: this.settingsOf().localMemoryEnabled, memoryEnabled: this.settingsOf().memoryEnabled }),
|
||||
workspace: (exec) => workspaceFromExec(exec),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@ import { renderJson } from "./tools.js";
|
|||
function snippet(text, limit = 600) {
|
||||
return text.length <= limit ? text : text.slice(0, limit) + '…';
|
||||
}
|
||||
function inDepartmentWorkspace(deps, exec, job) {
|
||||
return deps.memory().withWorkspace(deps.workspace(exec), job);
|
||||
}
|
||||
function requireEnabled(deps) {
|
||||
const settings = deps.settings();
|
||||
if (settings.memoryEnabled === false || settings.localMemoryEnabled === false) {
|
||||
|
|
@ -34,14 +37,16 @@ export function createDepartmentTools(deps) {
|
|||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
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 };
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 = {
|
||||
|
|
@ -49,11 +54,13 @@ export function createDepartmentTools(deps) {
|
|||
description: '列出部门及其精简状态;role 全文不返回,按需使用部门详情接口。',
|
||||
parameters: { type: 'object', properties: { scope: { type: 'string', enum: ['global', 'project'] } }, additionalProperties: false },
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
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 })) };
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 = {
|
||||
|
|
@ -66,16 +73,18 @@ export function createDepartmentTools(deps) {
|
|||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
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 };
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 = {
|
||||
|
|
@ -90,16 +99,19 @@ export function createDepartmentTools(deps) {
|
|||
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 ws = deps.workspace(exec);
|
||||
return deps.memory().withWorkspace(ws, async () => {
|
||||
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, ws);
|
||||
return { hits: hits.map((hit) => ({ id: hit.record.id, origin: hit.origin, content: snippet(hit.record.content) })) };
|
||||
});
|
||||
},
|
||||
};
|
||||
const department_checkpoint = {
|
||||
|
|
@ -112,13 +124,15 @@ export function createDepartmentTools(deps) {
|
|||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
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 };
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 = {
|
||||
|
|
@ -131,17 +145,19 @@ export function createDepartmentTools(deps) {
|
|||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args) {
|
||||
async execute(args, exec) {
|
||||
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 inDepartmentWorkspace(deps, exec, async () => {
|
||||
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];
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ export async function serveDepartments(deps, req, res) {
|
|||
fail(res, 503, 'local-memory-disabled');
|
||||
return;
|
||||
}
|
||||
const withWorkspace = (workspace, job) => deps.localMemory === undefined ? job() : deps.localMemory.withWorkspace(workspace, job);
|
||||
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||
const marker = '/departments';
|
||||
const at = url.pathname.indexOf(marker);
|
||||
|
|
@ -57,7 +58,8 @@ export async function serveDepartments(deps, req, res) {
|
|||
return;
|
||||
}
|
||||
const scope = url.searchParams.get('scope') === 'global' ? 'global' : url.searchParams.get('scope') === 'project' ? 'project' : undefined;
|
||||
json(res, 200, { ok: true, departments: await manager.list(scope) });
|
||||
const workspace = url.searchParams.get('workspace')?.trim() || undefined;
|
||||
json(res, 200, { ok: true, departments: await withWorkspace(workspace, () => manager.list(scope)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/create') {
|
||||
|
|
@ -72,6 +74,7 @@ export async function serveDepartments(deps, req, res) {
|
|||
const body = await bodyObject(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const workspace = stringField(body.workspace)?.trim() || undefined;
|
||||
const name = stringField(body.name)?.trim() ?? '';
|
||||
if (name === '') {
|
||||
fail(res, 400, 'name-required');
|
||||
|
|
@ -86,7 +89,7 @@ export async function serveDepartments(deps, req, res) {
|
|||
...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}),
|
||||
...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}),
|
||||
};
|
||||
json(res, 200, { ok: true, ...(await manager.create(input)) });
|
||||
json(res, 200, { ok: true, ...(await withWorkspace(workspace, () => manager.create(input))) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/update' || suffix === '/disable' || suffix === '/checkpoint' || suffix === '/resume') {
|
||||
|
|
@ -101,6 +104,7 @@ export async function serveDepartments(deps, req, res) {
|
|||
const body = await bodyObject(req, res);
|
||||
if (body === undefined)
|
||||
return;
|
||||
const workspace = stringField(body.workspace)?.trim() || undefined;
|
||||
const id = stringField(body.id)?.trim() ?? '';
|
||||
if (id === '') {
|
||||
fail(res, 400, 'id-required');
|
||||
|
|
@ -116,11 +120,11 @@ export async function serveDepartments(deps, req, res) {
|
|||
...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}),
|
||||
...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}),
|
||||
};
|
||||
json(res, 200, { ok: true, department: await manager.update(id, patch, expectedRevision) });
|
||||
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.update(id, patch, expectedRevision)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/disable') {
|
||||
json(res, 200, { ok: true, department: await manager.disable(id, expectedRevision) });
|
||||
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.disable(id, expectedRevision)) });
|
||||
return;
|
||||
}
|
||||
if (suffix === '/checkpoint') {
|
||||
|
|
@ -128,14 +132,14 @@ export async function serveDepartments(deps, req, res) {
|
|||
...(stringField(body.currentTask) === undefined ? {} : { currentTask: stringField(body.currentTask) }),
|
||||
...(stringField(body.handoff) === undefined ? {} : { handoff: stringField(body.handoff) }),
|
||||
};
|
||||
json(res, 200, { ok: true, department: await manager.checkpoint(id, input, expectedRevision) });
|
||||
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.checkpoint(id, input, expectedRevision)) });
|
||||
return;
|
||||
}
|
||||
const host = stringField(body.host)?.trim() || 'dsh';
|
||||
const hostSessionId = stringField(body.hostSessionId)?.trim();
|
||||
const sessionRef = hostSessionId !== undefined && hostSessionId !== ''
|
||||
? await manager.attachSession(id, host, hostSessionId)
|
||||
: await manager.resumeSession(id, host);
|
||||
const sessionRef = await withWorkspace(workspace, async () => hostSessionId !== undefined && hostSessionId !== ''
|
||||
? manager.attachSession(id, host, hostSessionId)
|
||||
: manager.resumeSession(id, host));
|
||||
json(res, 200, { ok: true, sessionRef });
|
||||
return;
|
||||
}
|
||||
|
|
@ -153,7 +157,8 @@ export async function serveDepartments(deps, req, res) {
|
|||
const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10);
|
||||
const k = Number.isFinite(requested) ? Math.max(1, Math.min(5, requested)) : 5;
|
||||
const workspace = url.searchParams.get('workspace')?.trim() || undefined;
|
||||
json(res, 200, { ok: true, hits: await manager.recall(id, query, k, workspace) });
|
||||
const hits = await withWorkspace(workspace, () => manager.recall(id, query, k, workspace));
|
||||
json(res, 200, { ok: true, hits });
|
||||
return;
|
||||
}
|
||||
fail(res, 404, 'unknown-department-route');
|
||||
|
|
|
|||
|
|
@ -259,6 +259,7 @@ export class BrainKernel {
|
|||
departmentToolDeps(): DepartmentToolDeps {
|
||||
return {
|
||||
departments: () => this.departments,
|
||||
memory: () => this.localMemory,
|
||||
settings: () => ({ localMemoryEnabled: this.settingsOf().localMemoryEnabled, memoryEnabled: this.settingsOf().memoryEnabled }),
|
||||
workspace: (exec?: unknown) => workspaceFromExec(exec),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
/** 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 { LocalMemoryManager } from '../local-memory/manager.ts'
|
||||
import type { DepartmentCreateInput, DepartmentRecallHit } from '../local-memory/departments/types.ts'
|
||||
import { renderJson } from './tools.ts'
|
||||
|
||||
export interface DepartmentToolDeps {
|
||||
departments: () => DepartmentManager
|
||||
memory: () => LocalMemoryManager
|
||||
settings: () => { localMemoryEnabled: boolean; memoryEnabled: boolean }
|
||||
workspace: (exec?: unknown) => string | undefined
|
||||
}
|
||||
|
|
@ -14,6 +16,10 @@ function snippet(text: string, limit = 600): string {
|
|||
return text.length <= limit ? text : text.slice(0, limit) + '…'
|
||||
}
|
||||
|
||||
function inDepartmentWorkspace<T>(deps: DepartmentToolDeps, exec: unknown, job: () => Promise<T>): Promise<T> {
|
||||
return deps.memory().withWorkspace(deps.workspace(exec), job)
|
||||
}
|
||||
|
||||
function requireEnabled(deps: DepartmentToolDeps): void {
|
||||
const settings = deps.settings()
|
||||
if (settings.memoryEnabled === false || settings.localMemoryEnabled === false) {
|
||||
|
|
@ -48,13 +54,15 @@ export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionL
|
|||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
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 }
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 }
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -63,11 +71,13 @@ export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionL
|
|||
description: '列出部门及其精简状态;role 全文不返回,按需使用部门详情接口。',
|
||||
parameters: { type: 'object', properties: { scope: { type: 'string', enum: ['global', 'project'] } }, additionalProperties: false },
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
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 })) }
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 })) }
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -81,14 +91,16 @@ export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionL
|
|||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
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 }
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 }
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -104,14 +116,17 @@ export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionL
|
|||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
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 ws = deps.workspace(exec)
|
||||
return deps.memory().withWorkspace(ws, async () => {
|
||||
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, ws)
|
||||
return { hits: hits.map((hit: DepartmentRecallHit) => ({ id: hit.record.id, origin: hit.origin, content: snippet(hit.record.content) })) }
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -125,12 +140,14 @@ export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionL
|
|||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
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 }
|
||||
return inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 }
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -144,16 +161,18 @@ export function createDepartmentTools(deps: DepartmentToolDeps): ToolDefinitionL
|
|||
additionalProperties: false,
|
||||
},
|
||||
output: { schema: { type: 'object' }, render: renderJson },
|
||||
async execute(args: Record<string, unknown>): Promise<unknown> {
|
||||
async execute(args: Record<string, unknown>, exec?: unknown): Promise<unknown> {
|
||||
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 inDepartmentWorkspace(deps, exec, async () => {
|
||||
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 }
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,12 +8,14 @@
|
|||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import type { SettingsStore } from '../store.ts'
|
||||
import type { DepartmentManager } from '../local-memory/departments/index.ts'
|
||||
import type { LocalMemoryManager } from '../local-memory/manager.ts'
|
||||
import type { DepartmentCreateInput, DepartmentUpdateInput } from '../local-memory/departments/types.ts'
|
||||
import { fail, json, readBody, sameOrigin } from '../http.ts'
|
||||
|
||||
export interface DepartmentRouteDeps {
|
||||
store: SettingsStore
|
||||
departments?: DepartmentManager
|
||||
localMemory?: LocalMemoryManager
|
||||
}
|
||||
|
||||
function errorStatus(message: string): number | undefined {
|
||||
|
|
@ -48,6 +50,8 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM
|
|||
const manager = deps.departments
|
||||
if (manager === undefined) { fail(res, 503, 'departments-unavailable'); return }
|
||||
if (deps.store.settings().localMemoryEnabled === false) { fail(res, 503, 'local-memory-disabled'); return }
|
||||
const withWorkspace = <T>(workspace: string | undefined, job: () => Promise<T>): Promise<T> =>
|
||||
deps.localMemory === undefined ? job() : deps.localMemory.withWorkspace(workspace, job)
|
||||
const url = new URL(req.url ?? '/', 'http://localhost')
|
||||
const marker = '/departments'
|
||||
const at = url.pathname.indexOf(marker)
|
||||
|
|
@ -56,13 +60,15 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM
|
|||
if (suffix === '' || suffix === '/' || suffix === '/list') {
|
||||
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
|
||||
const scope = url.searchParams.get('scope') === 'global' ? 'global' : url.searchParams.get('scope') === 'project' ? 'project' : undefined
|
||||
json(res, 200, { ok: true, departments: await manager.list(scope) })
|
||||
const workspace = url.searchParams.get('workspace')?.trim() || undefined
|
||||
json(res, 200, { ok: true, departments: await withWorkspace(workspace, () => manager.list(scope)) })
|
||||
return
|
||||
}
|
||||
if (suffix === '/create') {
|
||||
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
|
||||
if (!sameOrigin(req)) { fail(res, 403, 'origin-rejected'); return }
|
||||
const body = await bodyObject(req, res); if (body === undefined) return
|
||||
const workspace = stringField(body.workspace)?.trim() || undefined
|
||||
const name = stringField(body.name)?.trim() ?? ''
|
||||
if (name === '') { fail(res, 400, 'name-required'); return }
|
||||
const input: DepartmentCreateInput = {
|
||||
|
|
@ -74,13 +80,14 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM
|
|||
...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}),
|
||||
...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}),
|
||||
}
|
||||
json(res, 200, { ok: true, ...(await manager.create(input)) })
|
||||
json(res, 200, { ok: true, ...(await withWorkspace(workspace, () => manager.create(input))) })
|
||||
return
|
||||
}
|
||||
if (suffix === '/update' || suffix === '/disable' || suffix === '/checkpoint' || suffix === '/resume') {
|
||||
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
|
||||
if (!sameOrigin(req)) { fail(res, 403, 'origin-rejected'); return }
|
||||
const body = await bodyObject(req, res); if (body === undefined) return
|
||||
const workspace = stringField(body.workspace)?.trim() || undefined
|
||||
const id = stringField(body.id)?.trim() ?? ''
|
||||
if (id === '') { fail(res, 400, 'id-required'); return }
|
||||
const expectedRevision = revisionField(body.expectedRevision)
|
||||
|
|
@ -93,23 +100,23 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM
|
|||
...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}),
|
||||
...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}),
|
||||
}
|
||||
json(res, 200, { ok: true, department: await manager.update(id, patch, expectedRevision) })
|
||||
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.update(id, patch, expectedRevision)) })
|
||||
return
|
||||
}
|
||||
if (suffix === '/disable') { json(res, 200, { ok: true, department: await manager.disable(id, expectedRevision) }); return }
|
||||
if (suffix === '/disable') { json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.disable(id, expectedRevision)) }); return }
|
||||
if (suffix === '/checkpoint') {
|
||||
const input: { currentTask?: string; handoff?: string } = {
|
||||
...(stringField(body.currentTask) === undefined ? {} : { currentTask: stringField(body.currentTask) }),
|
||||
...(stringField(body.handoff) === undefined ? {} : { handoff: stringField(body.handoff) }),
|
||||
}
|
||||
json(res, 200, { ok: true, department: await manager.checkpoint(id, input, expectedRevision) })
|
||||
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.checkpoint(id, input, expectedRevision)) })
|
||||
return
|
||||
}
|
||||
const host = stringField(body.host)?.trim() || 'dsh'
|
||||
const hostSessionId = stringField(body.hostSessionId)?.trim()
|
||||
const sessionRef = hostSessionId !== undefined && hostSessionId !== ''
|
||||
? await manager.attachSession(id, host, hostSessionId)
|
||||
: await manager.resumeSession(id, host)
|
||||
const sessionRef = await withWorkspace(workspace, async () => hostSessionId !== undefined && hostSessionId !== ''
|
||||
? manager.attachSession(id, host, hostSessionId)
|
||||
: manager.resumeSession(id, host))
|
||||
json(res, 200, { ok: true, sessionRef })
|
||||
return
|
||||
}
|
||||
|
|
@ -121,7 +128,8 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM
|
|||
const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10)
|
||||
const k = Number.isFinite(requested) ? Math.max(1, Math.min(5, requested)) : 5
|
||||
const workspace = url.searchParams.get('workspace')?.trim() || undefined
|
||||
json(res, 200, { ok: true, hits: await manager.recall(id, query, k, workspace) })
|
||||
const hits = await withWorkspace(workspace, () => manager.recall(id, query, k, workspace))
|
||||
json(res, 200, { ok: true, hits })
|
||||
return
|
||||
}
|
||||
fail(res, 404, 'unknown-department-route')
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// P1.5 D1+D2 wiring verification.
|
||||
import http from 'node:http'
|
||||
import { mkdtempSync, mkdirSync } from 'node:fs'
|
||||
import { mkdtempSync, mkdirSync, existsSync, readFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
const root = mkdtempSync(join(tmpdir(), 'dep-wiring-'))
|
||||
|
|
@ -42,6 +42,19 @@ await kernel.departments.disable(created.id)
|
|||
let disabledToolError = ''
|
||||
try { await rememberTool.execute({ departmentId: created.id, content: 'must fail' }, { workspace: project }) } catch (error) { disabledToolError = String(error) }
|
||||
check('disabled department rejects remember with the library error', disabledToolError.includes('department_disabled'), disabledToolError.slice(0, 80))
|
||||
// Dual-workspace tool isolation (C8).
|
||||
const dualA = join(root, 'dual-a')
|
||||
const dualB = join(root, 'dual-b')
|
||||
mkdirSync(dualA, { recursive: true })
|
||||
mkdirSync(dualB, { recursive: true })
|
||||
const twinA = await createTool.execute({ name: 'Twin', scope: 'project' }, { workspace: dualA })
|
||||
const twinB = await createTool.execute({ name: 'Twin', scope: 'project' }, { workspace: dualB })
|
||||
check('project departments isolate caller workspaces', twinA.created === true && twinB.created === true && twinA.id !== twinB.id, JSON.stringify({ a: twinA, b: twinB }))
|
||||
await rememberTool.execute({ departmentId: twinA.id, content: 'twin-alpha-private' }, { workspace: dualA })
|
||||
const twinBRecall = await recallTool.execute({ departmentId: twinB.id, query: 'twin-alpha-private' }, { workspace: dualB })
|
||||
check('project department memory is not visible from another workspace', twinBRecall.hits.length === 0, JSON.stringify(twinBRecall.hits))
|
||||
const registryB = JSON.parse(readFileSync(join(dualB, '.dsh', 'brain', 'departments', 'registry.json'), 'utf8'))
|
||||
check('project registry belongs to the caller workspace', Array.isArray(registryB.departments) && registryB.departments.length === 1 && registryB.departments[0].id === twinB.id, JSON.stringify(registryB.departments))
|
||||
// HTTP routes
|
||||
function serverFor(routeDeps) { const routes = createCoreRoutes(routeDeps); return http.createServer((req, res) => { const path = (req.url || '/').split('?')[0]; const route = routes.find((candidate) => candidate.kind === 'prefix' ? path === candidate.path || path.startsWith(candidate.path + '/') : path === candidate.path); if (route) void route.handler(req, res); else { res.writeHead(404); res.end() } }) }
|
||||
function request(server, method, path, body, origin) { return new Promise((resolve) => { const port = server.address().port; const payload = body === undefined ? undefined : JSON.stringify(body); const headers = { ...(payload === undefined ? {} : { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) }), host: '127.0.0.1:' + port, ...(origin === undefined ? {} : { origin }) }; const req = http.request({ host: '127.0.0.1', port, method, path, headers }, (res) => { let raw = ''; res.on('data', (chunk) => { raw += chunk }); res.on('end', () => resolve({ status: res.statusCode, body: raw === '' ? null : JSON.parse(raw) })) }); if (payload !== undefined) req.write(payload); req.end() }) }
|
||||
|
|
@ -52,6 +65,12 @@ const crossOrigin = await request(server, 'POST', '/dsh-brain/departments/create
|
|||
check('POST create rejects a cross-origin request', crossOrigin.status === 403)
|
||||
const sameOrigin = await request(server, 'POST', '/dsh-brain/departments/create', { name: 'route-dept', scope: 'global' }, 'http://127.0.0.1:' + server.address().port)
|
||||
check('POST create accepts a same-origin request', sameOrigin.status === 200 && sameOrigin.body?.created === true)
|
||||
const httpA = await request(server, 'POST', '/dsh-brain/departments/create', { name: 'HttpTwin', scope: 'project', workspace: dualA }, 'http://127.0.0.1:' + server.address().port)
|
||||
const httpB = await request(server, 'POST', '/dsh-brain/departments/create', { name: 'HttpTwin', scope: 'project', workspace: dualB }, 'http://127.0.0.1:' + server.address().port)
|
||||
check('HTTP create isolates project departments by workspace', httpA.status === 200 && httpB.status === 200 && httpA.body?.created === true && httpB.body?.created === true && httpA.body?.department?.id !== httpB.body?.department?.id, JSON.stringify({ a: httpA.body, b: httpB.body }))
|
||||
const listA = await request(server, 'GET', '/dsh-brain/departments/list?scope=project&workspace=' + encodeURIComponent(dualA))
|
||||
const listB = await request(server, 'GET', '/dsh-brain/departments/list?scope=project&workspace=' + encodeURIComponent(dualB))
|
||||
check('HTTP list reads the requested workspace', listA.status === 200 && listB.status === 200 && listA.body?.departments?.some((d) => d.id === httpA.body.department.id) && !listA.body?.departments?.some((d) => d.id === httpB.body.department.id) && listB.body?.departments?.some((d) => d.id === httpB.body.department.id) && !listB.body?.departments?.some((d) => d.id === httpA.body.department.id), JSON.stringify({ a: listA.body, b: listB.body }))
|
||||
const missingName = await request(server, 'POST', '/dsh-brain/departments/create', {}, 'http://127.0.0.1:' + server.address().port)
|
||||
check('POST create rejects missing name', missingName.status === 400 && missingName.body?.error === 'name-required')
|
||||
const stale = await request(server, 'POST', '/dsh-brain/departments/update', { id: sameOrigin.body.department.id, expectedRevision: 0, role: 'stale' }, 'http://127.0.0.1:' + server.address().port)
|
||||
|
|
|
|||
Loading…
Reference in New Issue