refactor: drop dead defensive code and duplicate response checks
Removes branches proven unreachable (double URL parse, re-checks of values the response validators already enforce, unreachable null guards), collapses redundant request-method/origin/content-type gates onto jsonBody, and makes the validated response fields required so downstream \?? []\ fallbacks cannot come back.
This commit is contained in:
parent
b889897dae
commit
129571d96e
25
src/api.ts
25
src/api.ts
|
|
@ -74,24 +74,25 @@ export interface MemoryHit {
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `POST /memory/query` response. */
|
/** `POST /memory/query` response. `matches` is required: validateSearchResponse
|
||||||
|
* rejects a 2xx without it, so downstream code must not re-guard with `?? []`. */
|
||||||
export interface SearchResponse {
|
export interface SearchResponse {
|
||||||
matches?: MemoryHit[]
|
matches: MemoryHit[]
|
||||||
total?: number
|
total?: number
|
||||||
search_mode?: string
|
search_mode?: string
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `GET /memory/all` response. */
|
/** `GET /memory/all` response. `items` is required (validateListResponse). */
|
||||||
export interface ListResponse {
|
export interface ListResponse {
|
||||||
items?: MemoryHit[]
|
items: MemoryHit[]
|
||||||
total?: number
|
total?: number
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `GET /dashboard/projects` response. */
|
/** `GET /dashboard/projects` response. `projects` is required (validateProjectsResponse). */
|
||||||
export interface ProjectsResponse {
|
export interface ProjectsResponse {
|
||||||
projects?: { id?: string; name?: string; [key: string]: unknown }[]
|
projects: { id?: string; name?: string; [key: string]: unknown }[]
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -125,9 +126,9 @@ export interface SkillSummary {
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `GET /skills` response. */
|
/** `GET /skills` response. `items` is required (validateSkillListing). */
|
||||||
export interface SkillListing {
|
export interface SkillListing {
|
||||||
items?: SkillSummary[]
|
items: SkillSummary[]
|
||||||
total?: number
|
total?: number
|
||||||
trash_total?: number
|
trash_total?: number
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
|
|
@ -429,7 +430,6 @@ function validateSkillListing(value: unknown): SkillListing {
|
||||||
function validateSkillBundle(value: unknown): SkillBundle {
|
function validateSkillBundle(value: unknown): SkillBundle {
|
||||||
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')
|
||||||
}
|
}
|
||||||
|
|
@ -704,11 +704,8 @@ export class CloudClient {
|
||||||
const base = authBase(baseUrl)
|
const base = authBase(baseUrl)
|
||||||
if (base === '') return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }
|
if (base === '') return { ok: false, error: { status: 0, code: 'invalid_base_url', message: '服务地址无效,无法登录' } }
|
||||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
const headers: Record<string, string> = { 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 !== '') headers.Cookie = cookie
|
if (cookie !== undefined && cookie !== '') headers.Cookie = cookie
|
||||||
const init: RequestInit = { method, headers, signal: AbortSignal.timeout(timeoutMs) }
|
const init: RequestInit = { method, headers, signal: AbortSignal.timeout(timeoutMs) }
|
||||||
if (body !== undefined) {
|
if (body !== undefined) {
|
||||||
|
|
|
||||||
|
|
@ -263,8 +263,7 @@ export class ClientRegistry {
|
||||||
const software = SOFTWARE.includes(softwareInput as SoftwareId) ? softwareInput as SoftwareId : undefined
|
const software = SOFTWARE.includes(softwareInput as SoftwareId) ? softwareInput as SoftwareId : undefined
|
||||||
if (software === undefined) throw new Error('invalid_software')
|
if (software === undefined) throw new Error('invalid_software')
|
||||||
const path = typeof pathInput === 'string' ? pathInput.trim() : ''
|
const path = typeof pathInput === 'string' ? pathInput.trim() : ''
|
||||||
if (path === '' || !existsSync(path)) throw new Error('invalid_path')
|
const stats = path === '' ? undefined : await stat(path).catch(() => undefined)
|
||||||
const stats = await stat(path).catch(() => undefined)
|
|
||||||
if (stats === undefined || !stats.isDirectory()) throw new Error('invalid_path')
|
if (stats === undefined || !stats.isDirectory()) throw new Error('invalid_path')
|
||||||
const resolved = resolve(path)
|
const resolved = resolve(path)
|
||||||
const file = await this.readManual()
|
const file = await this.readManual()
|
||||||
|
|
@ -300,7 +299,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,
|
||||||
|
|
|
||||||
|
|
@ -109,7 +109,7 @@ async function serveTest(deps: CloudSyncRouteDeps, req: IncomingMessage, res: Se
|
||||||
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),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -219,9 +219,7 @@ async function serveLogin(deps: CloudSyncRouteDeps, req: IncomingMessage, res: S
|
||||||
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
|
||||||
|
|
|
||||||
|
|
@ -112,12 +112,9 @@ export function normalizeBaseUrl(value: unknown): string | undefined {
|
||||||
export function isPlaceholderBaseUrl(value: string): boolean {
|
export function isPlaceholderBaseUrl(value: string): boolean {
|
||||||
const normalized = normalizeBaseUrl(value)
|
const normalized = normalizeBaseUrl(value)
|
||||||
if (normalized === undefined) return true
|
if (normalized === undefined) 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. */
|
||||||
|
|
|
||||||
|
|
@ -165,6 +165,6 @@ export class BrainLogger {
|
||||||
private warnOnce(): void {
|
private warnOnce(): void {
|
||||||
if (this.warned) return
|
if (this.warned) 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')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -95,7 +95,6 @@ export class DepartmentManager {
|
||||||
|
|
||||||
async update(id: string, patch: DepartmentUpdateInput, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
|
async update(id: string, patch: DepartmentUpdateInput, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
|
||||||
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)) throw new Error('secret_not_allowed')
|
if (patch.role !== undefined && containsSecret(patch.role)) throw new Error('secret_not_allowed')
|
||||||
return this.registry(current.scope).update(async (file) => {
|
return this.registry(current.scope).update(async (file) => {
|
||||||
const department = file.departments.find((item) => item.id === id)
|
const department = file.departments.find((item) => item.id === id)
|
||||||
|
|
@ -160,7 +159,6 @@ export class DepartmentManager {
|
||||||
|
|
||||||
async checkpoint(id: string, input: { currentTask?: string; handoff?: string }, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
|
async checkpoint(id: string, input: { currentTask?: string; handoff?: string }, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
|
||||||
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))) throw new Error('secret_not_allowed')
|
if ((currentTask !== undefined && containsSecret(currentTask)) || (handoff !== undefined && containsSecret(handoff))) throw new Error('secret_not_allowed')
|
||||||
|
|
@ -227,6 +225,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: string, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
|
async disable(id: string, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
|
||||||
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) throw new Error('revision_conflict')
|
if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict')
|
||||||
const store = this.store(current)
|
const store = this.store(current)
|
||||||
if (await store.spaceMeta() !== undefined) await store.setActive(false)
|
if (await store.spaceMeta() !== undefined) await store.setActive(false)
|
||||||
|
|
|
||||||
|
|
@ -283,11 +283,9 @@ export class LocalMemoryManager {
|
||||||
return new JsonDocumentStore(join(root, 'documents')).list()
|
return new JsonDocumentStore(join(root, 'documents')).list()
|
||||||
}
|
}
|
||||||
async addDocument(input: { title: string; content: string; source?: string; tags?: string[] }, workspace?: string): Promise<LocalDocument> {
|
async addDocument(input: { title: string; content: string; source?: string; tags?: string[] }, workspace?: string): Promise<LocalDocument> {
|
||||||
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?: string, scope?: LocalMemoryScope): Promise<Record<string, unknown>> {
|
async storageStatus(workspace?: string, scope?: LocalMemoryScope): Promise<Record<string, unknown>> {
|
||||||
|
|
@ -366,8 +364,8 @@ export class LocalMemoryManager {
|
||||||
for (const turn of fresh) if (turn.turnId !== undefined) processedNext.add(turn.turnId)
|
for (const turn of fresh) if (turn.turnId !== undefined) processedNext.add(turn.turnId)
|
||||||
let documentId: string | undefined
|
let documentId: string | undefined
|
||||||
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) throw new Error('local_documents_unavailable')
|
const documents = this.workspaces.get(this.projectRootFor(workspace))!.documents
|
||||||
const document = await documents.add({ title: '会话总结 ' + input.sessionId, content: input.summary ?? ('本次会话共 ' + String(nextCount) + ' 轮,已更新增量检查点。'), source: 'session:' + input.sessionId, tags: ['auto-summary'] })
|
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
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -124,7 +124,7 @@ function searchTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
||||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||||
const result = await deps.remote().search(query, k, project, workspace)
|
const result = await deps.remote().search(query, k, project, workspace)
|
||||||
if (!result.ok) throw new Error(`检索失败:${describeError(result.error)}`)
|
if (!result.ok) 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,
|
||||||
|
|
@ -260,7 +260,7 @@ function listTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
||||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||||
const result = await deps.remote().list({ limit, offset, project }, workspace)
|
const result = await deps.remote().list({ limit, offset, project }, workspace)
|
||||||
if (!result.ok) throw new Error(`列表读取失败:${describeError(result.error)}`)
|
if (!result.ok) throw new Error(`列表读取失败:${describeError(result.error)}`)
|
||||||
const items = result.data.items ?? []
|
const items = result.data.items
|
||||||
return { total: result.data.total ?? items.length, items: items.map(toHitView) }
|
return { total: result.data.total ?? items.length, items: items.map(toHitView) }
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
@ -282,7 +282,7 @@ function projectsTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
||||||
const result = await deps.remote().projects(workspace)
|
const result = await deps.remote().projects(workspace)
|
||||||
|
|
||||||
if (!result.ok) throw new Error(`项目列表读取失败:${describeError(result.error)}`)
|
if (!result.ok) throw new Error(`项目列表读取失败:${describeError(result.error)}`)
|
||||||
return { projects: result.data.projects ?? [] }
|
return { projects: result.data.projects }
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -169,7 +169,7 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
||||||
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 === '') continue
|
if (typeof project.id !== 'string' || project.id === '') continue
|
||||||
spaces.push({
|
spaces.push({
|
||||||
externalId: `project:${project.id}`,
|
externalId: `project:${project.id}`,
|
||||||
|
|
@ -203,7 +203,7 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
||||||
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 is Insight => item !== undefined),
|
.filter((item): item is Insight => item !== undefined),
|
||||||
}
|
}
|
||||||
|
|
@ -222,7 +222,7 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
||||||
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 is Insight => item !== undefined)
|
.filter((item): item is Insight => item !== undefined)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ export class LocalMnemonProvider implements MemoryProviderAdapter {
|
||||||
readonly scoreSemantics = { kind: 'provider-native' as const }
|
readonly scoreSemantics = { kind: 'provider-native' as const }
|
||||||
constructor(private readonly manager: LocalMemoryManager) {}
|
constructor(private readonly manager: LocalMemoryManager) {}
|
||||||
async status(body: MemorySpace): Promise<ProviderSpaceStatus> {
|
async status(body: MemorySpace): Promise<ProviderSpaceStatus> {
|
||||||
try { const status = await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body))); return { healthy: true, stats: { totalInsights: Number((status as any).spaces?.project ? 0 : 0), deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } } }
|
try { await this.manager.withWorkspace(workspaceOf(body), () => this.manager.storageStatus(workspaceOf(body))); return { healthy: true, stats: { totalInsights: 0, deletedInsights: 0, edgeCount: 0, oplogCount: 0, dbSizeBytes: 0, byCategory: {}, topEntities: [] } } }
|
||||||
catch (error) { return { healthy: false, error: error instanceof Error ? error.message : String(error) } }
|
catch (error) { return { healthy: false, error: error instanceof Error ? error.message : String(error) } }
|
||||||
}
|
}
|
||||||
async search(body: MemorySpace, request: SearchRequest): Promise<ProviderSearchResult> {
|
async search(body: MemorySpace, request: SearchRequest): Promise<ProviderSearchResult> {
|
||||||
|
|
|
||||||
|
|
@ -403,7 +403,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. */
|
||||||
private takeTranscript(conversationId: string, turn: number): SummaryMessage[] {
|
private takeTranscript(conversationId: string, turn: number): SummaryMessage[] {
|
||||||
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: SummaryMessage[] = []
|
const kept: SummaryMessage[] = []
|
||||||
for (const message of picked) {
|
for (const message of picked) {
|
||||||
|
|
@ -457,13 +457,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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -570,8 +570,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.
|
||||||
const head = this.queue[0]
|
// The loop condition guarantees a head; no await runs between them.
|
||||||
if (head === undefined) break
|
const head = this.queue[0]!
|
||||||
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}`)
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,7 @@ import type { SkillUpdater } from './skill-update.ts'
|
||||||
import type { ClientRegistry } from './clients.ts'
|
import type { ClientRegistry } from './clients.ts'
|
||||||
import { brainStatus, migrateLegacyFiles } from './brain-migration.ts'
|
import { brainStatus, migrateLegacyFiles } from './brain-migration.ts'
|
||||||
import { mcpCapability, type McpCapability } from './mcp.ts'
|
import { mcpCapability, type McpCapability } from './mcp.ts'
|
||||||
import { fail, json, readBody, sameOrigin } from './http.ts'
|
import { fail, json, jsonBody, readBody, sameOrigin } from './http.ts'
|
||||||
import { createCloudSyncRoutes, getLastCheck } from './cloudsync-routes.ts'
|
import { createCloudSyncRoutes, getLastCheck } from './cloudsync-routes.ts'
|
||||||
import { createSkillRoutes } from './skills/routes.ts'
|
import { createSkillRoutes } from './skills/routes.ts'
|
||||||
|
|
||||||
|
|
@ -219,31 +219,9 @@ function serveCapabilities(deps: RouteDeps, req: IncomingMessage, res: ServerRes
|
||||||
|
|
||||||
/** `PUT /dsh-brain/config`. */
|
/** `PUT /dsh-brain/config`. */
|
||||||
async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
async function serveConfig(deps: RouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||||
if (req.method !== 'PUT' && req.method !== 'POST') {
|
const patch = await jsonBody(req, res)
|
||||||
fail(res, 405, 'method-not-allowed')
|
if (patch === undefined) return
|
||||||
return
|
const result = deps.store.patch(patch)
|
||||||
}
|
|
||||||
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: unknown
|
|
||||||
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 as Record<string, unknown>)
|
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
fail(res, 400, result.error ?? 'invalid-patch')
|
fail(res, 400, result.error ?? 'invalid-patch')
|
||||||
return
|
return
|
||||||
|
|
|
||||||
|
|
@ -322,7 +322,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,
|
||||||
|
|
@ -606,7 +606,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,
|
||||||
|
|
|
||||||
|
|
@ -386,7 +386,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)
|
||||||
|
|
@ -400,7 +401,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)
|
||||||
|
|
|
||||||
|
|
@ -534,8 +534,9 @@ export class SkillSync implements SkillSyncGate {
|
||||||
const state = await this.loadState(run.scope)
|
const state = await this.loadState(run.scope)
|
||||||
const listing = await client.listSkills()
|
const listing = await client.listSkills()
|
||||||
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
|
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
|
||||||
const items = (listing.data.items ?? []).filter((item) => typeof item.name === 'string' && CLOUD_SKILL_NAME.test(item.name))
|
// validateSkillListing already guarantees items is an array of summaries with non-empty string names.
|
||||||
const cloudByName = new Map(items.map((item) => [item.name as string, item]))
|
const items = listing.data.items.filter((item) => CLOUD_SKILL_NAME.test(item.name))
|
||||||
|
const cloudByName = new Map(items.map((item) => [item.name, item]))
|
||||||
let stateDirty = false
|
let stateDirty = false
|
||||||
|
|
||||||
// Self-heal: an uploaded folder whose delivery receipt reappeared (a
|
// Self-heal: an uploaded folder whose delivery receipt reappeared (a
|
||||||
|
|
@ -578,8 +579,8 @@ export class SkillSync implements SkillSyncGate {
|
||||||
if (item.enabled === false) { stats.skipped += 1; continue }
|
if (item.enabled === false) { stats.skipped += 1; continue }
|
||||||
if (state.uploaded[item.name] !== undefined) { stats.skipped += 1; continue }
|
if (state.uploaded[item.name] !== undefined) { stats.skipped += 1; 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
|
||||||
|
|
@ -1069,7 +1070,7 @@ export class SkillSync implements SkillSyncGate {
|
||||||
let cloudItems: SkillSummary[] = []
|
let cloudItems: SkillSummary[] = []
|
||||||
try {
|
try {
|
||||||
const listing = await active.client.listSkills()
|
const listing = await active.client.listSkills()
|
||||||
if (listing.ok) cloudItems = listing.data.items ?? []
|
if (listing.ok) 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.
|
||||||
}
|
}
|
||||||
|
|
@ -1145,13 +1146,13 @@ export class SkillSync implements SkillSyncGate {
|
||||||
const preview = this.previews.get(expectedConflictId)
|
const preview = this.previews.get(expectedConflictId)
|
||||||
const listing = await client.listSkills()
|
const listing = await client.listSkills()
|
||||||
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
|
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
|
||||||
const cloud = (listing.data.items ?? []).find((item) => item.name === name)
|
const cloud = listing.data.items.find((item) => item.name === name)
|
||||||
const state = await this.loadState(scope)
|
const 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) throw new Error('stale_conflict')
|
if (localVersionNow !== confirmed.localVersion) throw new Error('stale_conflict')
|
||||||
if ((cloud?.revision ?? undefined) !== (confirmed.cloud?.revision ?? undefined) || (cloud?.manifest_sha256 ?? undefined) !== (confirmed.cloud?.manifest ?? undefined)) throw new Error('stale_conflict')
|
if (cloud?.revision !== confirmed.cloud?.revision || cloud?.manifest_sha256 !== confirmed.cloud?.manifest) throw new Error('stale_conflict')
|
||||||
|
|
||||||
if (action === 'manual') {
|
if (action === 'manual') {
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -360,7 +360,6 @@ async function serveClients(deps: SkillRouteDeps, req: IncomingMessage, res: Ser
|
||||||
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) return
|
if (body === undefined) return
|
||||||
const workspace = await registry.addWorkspace(body.software, body.path, body.name)
|
const workspace = await registry.addWorkspace(body.software, body.path, body.name)
|
||||||
|
|
@ -368,7 +367,6 @@ async function serveClients(deps: SkillRouteDeps, req: IncomingMessage, res: Ser
|
||||||
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) return
|
if (body === undefined) return
|
||||||
json(res, 200, { ok: true, ...(await registry.removeWorkspace(body.software, body.id)) })
|
json(res, 200, { ok: true, ...(await registry.removeWorkspace(body.software, body.id)) })
|
||||||
|
|
@ -381,7 +379,6 @@ async function serveClients(deps: SkillRouteDeps, req: IncomingMessage, res: Ser
|
||||||
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) return
|
if (body === undefined) return
|
||||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
|
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
|
||||||
|
|
@ -389,7 +386,6 @@ async function serveClients(deps: SkillRouteDeps, req: IncomingMessage, res: Ser
|
||||||
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) return
|
if (body === undefined) return
|
||||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
|
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
|
||||||
|
|
@ -397,7 +393,6 @@ async function serveClients(deps: SkillRouteDeps, req: IncomingMessage, res: Ser
|
||||||
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) return
|
if (body === undefined) return
|
||||||
if (body.confirmed !== true) throw new SkillAdminError('confirmation_required', '工作区技能删除必须显式 confirmed:true。')
|
if (body.confirmed !== true) throw new SkillAdminError('confirmation_required', '工作区技能删除必须显式 confirmed:true。')
|
||||||
|
|
@ -406,7 +401,6 @@ async function serveClients(deps: SkillRouteDeps, req: IncomingMessage, res: Ser
|
||||||
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) return
|
if (body === undefined) return
|
||||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
|
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
|
||||||
|
|
@ -414,7 +408,6 @@ async function serveClients(deps: SkillRouteDeps, req: IncomingMessage, res: Ser
|
||||||
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) return
|
if (body === undefined) return
|
||||||
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
|
const { admin } = await registry.workspaceSkillAdmin(body.software, body.workspaceId)
|
||||||
|
|
|
||||||
|
|
@ -292,8 +292,8 @@ 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.
|
||||||
*/
|
*/
|
||||||
private tokenFor(label: 'activity' | 'memory' | 'summary', sidecar: string | undefined): string {
|
private tokenFor(label: 'activity' | 'memory' | 'summary', sidecar: string | undefined): string {
|
||||||
if (sidecar !== undefined && sidecar !== '') return sidecar
|
if (sidecar !== undefined) return sidecar
|
||||||
if (this.state.clearedTokens?.includes(label) === true) return ''
|
if (this.state.clearedTokens?.includes(label)) return ''
|
||||||
const envPrefix = label === 'activity' ? 'DSH_BRAIN_ACTIVITY_TOKEN' : label === 'memory' ? 'DSH_BRAIN_MEMORY_TOKEN' : 'DSH_BRAIN_SUMMARY_TOKEN'
|
const 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'
|
||||||
const boundOrigin = envToken('DSH_BRAIN_TOKEN_ORIGIN') ?? envToken('DSH_CLOUD_MEMORY_TOKEN_ORIGIN')
|
const boundOrigin = envToken('DSH_BRAIN_TOKEN_ORIGIN') ?? envToken('DSH_CLOUD_MEMORY_TOKEN_ORIGIN')
|
||||||
|
|
@ -304,7 +304,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). */
|
||||||
private tokenSource(label: 'activity' | 'memory' | 'summary', sidecar: string | undefined): 'sidecar' | 'env' | 'none' {
|
private tokenSource(label: 'activity' | 'memory' | 'summary', sidecar: string | undefined): 'sidecar' | 'env' | 'none' {
|
||||||
if (sidecar !== undefined && sidecar !== '') return 'sidecar'
|
if (sidecar !== undefined) return 'sidecar'
|
||||||
if (this.tokenFor(label, sidecar) !== '') return 'env'
|
if (this.tokenFor(label, sidecar) !== '') return 'env'
|
||||||
return 'none'
|
return 'none'
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,7 @@ function skillListTool(deps: SkillToolDeps): ToolDefinitionLike {
|
||||||
requireMemoryToken(deps)
|
requireMemoryToken(deps)
|
||||||
const result = await deps.client().listSkills()
|
const result = await deps.client().listSkills()
|
||||||
if (!result.ok) throw new Error(`技能列表读取失败:${describeError(result.error)}`)
|
if (!result.ok) throw new Error(`技能列表读取失败:${describeError(result.error)}`)
|
||||||
const skills = (result.data.items ?? []).map((item) => ({
|
const skills = result.data.items.map((item) => ({
|
||||||
name: item.name,
|
name: item.name,
|
||||||
description: item.description ?? '',
|
description: item.description ?? '',
|
||||||
revision: item.revision ?? null,
|
revision: item.revision ?? null,
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue