refactor: 项目更名 WeKnora → Academy
Build & Publish (dsh-academy) / End-to-end inside dsh (latest, advisory) (push) Skipped
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Frontend / Docker multi-stage image (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-academy) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-academy) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-academy) / Publish to npm (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Helm / chart (push) Canceled after 0s

- 全量替换代码/配置/文档中的项目名(保留上游 GitHub 链接、weixin 文档域名、Docker Hub 镜像名)
- 重命名 32 个含项目名的文件/目录;Go module 路径改为 academy(含 client/cli 子模块)
- docreader proto 描述符采用等长替换,保持序列化字节布局有效
- Dockerfile.app 构建网络修复: browserskill 离线产物通道、PyPI/apt 国内镜像
- 运行验证: go build ✓ docker compose up ✓ 健康检查 ✓
This commit is contained in:
runny committed 2026-11-13 20:52:51 +08:00
1 parent 9097ee699d
commit 9058149576
3136 files changed
+18018 -18004

No files matched your search

+433
View File
@@ -0,0 +1,433 @@
/** Minimal Academy REST client: JSON endpoints plus the SSE chat streams. */
import type { ResolvedConfig } from './config.ts'
/** One retrieval hit, as returned by Academy's `SearchResult`. */
export interface SearchResult {
id?: string
content?: string
knowledge_id?: string
chunk_index?: number
knowledge_title?: string
knowledge_filename?: string
score?: number
match_type?: number | string
[key: string]: unknown
}
/** A knowledge base as listed by `GET /knowledge-bases`. */
export interface KnowledgeBaseSummary {
id?: string
name?: string
description?: string
[key: string]: unknown
}
/** One stored chunk as returned by `GET /chunks/:knowledge_id`. */
export interface ChunkRecord {
id?: string
content?: string
chunk_index?: number
knowledge_id?: string
[key: string]: unknown
}
/** A document as returned by the by-name search and by `GET /knowledge/:id`. */
export interface DocumentRecord {
id?: string
title?: string
file_name?: string
file_type?: string
description?: string
knowledge_base_id?: string
knowledge_base_name?: string
[key: string]: unknown
}
/** A page of chunks plus its pagination envelope. */
export interface ChunkPage {
chunks: ChunkRecord[]
total: number
page: number
pageSize: number
}
/** The assembled outcome of one streamed answer. */
export interface StreamedAnswer {
answer: string
references: SearchResult[]
sessionId: string
toolCalls: string[]
}
/** Raised for any non-2xx response or transport failure, with the key redacted. */
export class AcademyApiError extends Error {
readonly status: number | undefined
constructor(message: string, status?: number) {
super(message)
this.name = 'AcademyApiError'
this.status = status
}
}
interface Envelope<T> {
success?: boolean
data?: T
error?: unknown
message?: string
total?: number
page?: number
page_size?: number
}
/** Trim a response body for an error message without leaking a whole page. */
function snippet(body: string): string {
const collapsed = body.replace(/\s+/g, ' ').trim()
return collapsed.length > 300 ? `${collapsed.slice(0, 300)}…` : collapsed
}
/** Extract a human-readable reason from Academy's error envelope. */
function reasonOf(body: string): string {
try {
const parsed = JSON.parse(body) as { error?: { message?: string } | string, message?: string }
if (typeof parsed.error === 'string') return parsed.error
if (parsed.error?.message !== undefined) return parsed.error.message
if (parsed.message !== undefined) return parsed.message
} catch {
// Fall through to the raw snippet: a proxy may answer with HTML.
}
return snippet(body)
}
/**
* Combine the caller's cancellation with this call's deadline. The tool body
* must abort when the harness aborts, and a hung backend must not hold a turn
* open forever.
*/
function deadline(signal: AbortSignal, timeoutMs: number): AbortSignal {
return AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])
}
export class AcademyClient {
/**
* A knowledge-base-restricted API key rejects `resource_urls=public` with
* 403. After the first such refusal this client stays on handle mode so
* later calls do not pay the same round trip.
*/
private publicModeBlocked = false
constructor(private readonly config: ResolvedConfig) {}
private headers(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
if (this.config.apiKey !== undefined) headers['X-API-Key'] = this.config.apiKey
if (this.config.tenantId !== undefined) headers['X-Tenant-ID'] = this.config.tenantId
return headers
}
private resourceMode(): 'handle' | 'public' {
return this.config.resourceUrls === 'public' && !this.publicModeBlocked ? 'public' : 'handle'
}
private url(path: string, query?: Record<string, string | number | undefined>): string {
const url = new URL(`${this.config.baseUrl}${path}`)
for (const [key, value] of Object.entries(query ?? {})) {
if (value !== undefined) url.searchParams.set(key, String(value))
}
if (this.resourceMode() === 'public') url.searchParams.set('resource_urls', 'public')
return url.toString()
}
private isPublicModeForbidden(error: unknown): boolean {
return error instanceof AcademyApiError
&& this.config.resourceUrls === 'public'
&& !this.publicModeBlocked
&& error.status === 403
&& error.message.includes('resource_urls=public')
}
private async fetchJson<T>(
path: string,
init: { method: 'GET' | 'POST', body?: unknown, query?: Record<string, string | number | undefined> },
signal: AbortSignal,
): Promise<Envelope<T>> {
try {
return await this.fetchJsonOnce(path, init, signal)
} catch (error) {
if (!this.isPublicModeForbidden(error)) throw error
this.publicModeBlocked = true
return await this.fetchJsonOnce(path, init, signal)
}
}
private async fetchJsonOnce<T>(
path: string,
init: { method: 'GET' | 'POST', body?: unknown, query?: Record<string, string | number | undefined> },
signal: AbortSignal,
): Promise<Envelope<T>> {
const url = this.url(path, init.query)
let response: Response
try {
response = await fetch(url, {
method: init.method,
headers: this.headers(),
...init.body === undefined ? {} : { body: JSON.stringify(init.body) },
signal: deadline(signal, this.config.requestTimeoutMs),
})
} catch (cause) {
throw new AcademyApiError(`${init.method} ${path} failed: ${describeTransportFailure(cause, signal)}`)
}
const text = await response.text()
if (!response.ok) {
throw new AcademyApiError(`${init.method} ${path} failed with HTTP ${response.status}: ${reasonOf(text)}`, response.status)
}
try {
return JSON.parse(text) as Envelope<T>
} catch {
throw new AcademyApiError(`${init.method} ${path} returned a non-JSON body: ${snippet(text)}`, response.status)
}
}
/** List the knowledge bases this credential can retrieve from. */
async listKnowledgeBases(signal: AbortSignal): Promise<KnowledgeBaseSummary[]> {
const envelope = await this.fetchJson<KnowledgeBaseSummary[]>('/knowledge-bases', { method: 'GET' }, signal)
return Array.isArray(envelope.data) ? envelope.data : []
}
/** Hybrid (vector + keyword) retrieval across one or more knowledge bases. */
async search(
input: { query: string, knowledgeBaseIds: string[], knowledgeIds: string[] },
signal: AbortSignal,
): Promise<SearchResult[]> {
const envelope = await this.fetchJson<SearchResult[]>('/knowledge-search', {
method: 'POST',
body: {
query: input.query,
...input.knowledgeBaseIds.length > 0 ? { knowledge_base_ids: input.knowledgeBaseIds } : {},
...input.knowledgeIds.length > 0 ? { knowledge_ids: input.knowledgeIds } : {},
},
}, signal)
return Array.isArray(envelope.data) ? envelope.data : []
}
/**
* Find documents by title or filename. Unlike `search` this spans every
* knowledge base the credential can see and needs no scope, so it is what
* answers "where is the document called X".
*/
async findDocuments(
input: { keyword: string, limit: number },
signal: AbortSignal,
): Promise<DocumentRecord[]> {
const envelope = await this.fetchJson<DocumentRecord[]>('/knowledge/search', {
method: 'GET',
query: { keyword: input.keyword, limit: input.limit },
}, signal)
return Array.isArray(envelope.data) ? envelope.data : []
}
/** A document's metadata, including the generated summary Academy stores as `description`. */
async getDocument(knowledgeId: string, signal: AbortSignal): Promise<DocumentRecord> {
const envelope = await this.fetchJson<DocumentRecord>(
`/knowledge/${encodeURIComponent(knowledgeId)}`,
{ method: 'GET' },
signal,
)
return envelope.data ?? {}
}
/** One page of a document's stored chunks, in storage order. */
async listChunks(
input: { knowledgeId: string, page: number, pageSize: number },
signal: AbortSignal,
): Promise<ChunkPage> {
const envelope = await this.fetchJson<ChunkRecord[]>(`/chunks/${encodeURIComponent(input.knowledgeId)}`, {
method: 'GET',
query: { page: input.page, page_size: input.pageSize },
}, signal)
const chunks = Array.isArray(envelope.data) ? envelope.data : []
return {
chunks,
total: typeof envelope.total === 'number' ? envelope.total : chunks.length,
page: typeof envelope.page === 'number' ? envelope.page : input.page,
pageSize: typeof envelope.page_size === 'number' ? envelope.page_size : input.pageSize,
}
}
/** Create a conversation container to hold one or more asked questions. */
async createSession(title: string, signal: AbortSignal): Promise<string> {
const envelope = await this.fetchJson<{ id?: string }>('/sessions', {
method: 'POST',
body: { title },
}, signal)
const id = envelope.data?.id
if (typeof id !== 'string' || id === '') {
throw new AcademyApiError('POST /sessions returned no session id')
}
return id
}
/**
* Ask a question and assemble the streamed answer. `agentId` selects the
* ReAct pipeline (`/agent-chat`); without it the RAG pipeline answers
* (`/knowledge-chat`).
*/
async ask(
input: {
sessionId: string
query: string
knowledgeBaseIds: string[]
agentId: string | undefined
webSearch: boolean
},
signal: AbortSignal,
): Promise<StreamedAnswer> {
const route = input.agentId === undefined ? 'knowledge-chat' : 'agent-chat'
const path = `/${route}/${encodeURIComponent(input.sessionId)}`
const body = {
query: input.query,
channel: 'api',
...input.knowledgeBaseIds.length > 0 ? { knowledge_base_ids: input.knowledgeBaseIds } : {},
...input.agentId === undefined ? {} : { agent_id: input.agentId, agent_enabled: true },
...input.webSearch ? { web_search_enabled: true } : {},
}
const open = async (): Promise<Response> => {
const combined = deadline(signal, this.config.chatTimeoutMs)
try {
return await fetch(this.url(path), {
method: 'POST',
headers: { ...this.headers(), Accept: 'text/event-stream' },
body: JSON.stringify(body),
signal: combined,
})
} catch (cause) {
throw new AcademyApiError(`POST ${path} failed: ${describeTransportFailure(cause, signal)}`)
}
}
let response = await open()
if (!response.ok) {
const text = await response.text()
const error = new AcademyApiError(`POST ${path} failed with HTTP ${response.status}: ${reasonOf(text)}`, response.status)
if (!this.isPublicModeForbidden(error)) throw error
this.publicModeBlocked = true
response = await open()
}
if (!response.ok) {
const text = await response.text()
throw new AcademyApiError(`POST ${path} failed with HTTP ${response.status}: ${reasonOf(text)}`, response.status)
}
if (response.body === null) {
throw new AcademyApiError(`POST ${path} returned no response body`)
}
return await assembleStream(response.body, input.sessionId, path, signal)
}
}
/** Turn an aborted or refused fetch into a message that names the real cause. */
function describeTransportFailure(cause: unknown, callerSignal: AbortSignal): string {
if (cause instanceof Error && cause.name === 'AbortError') {
return callerSignal.aborted ? 'the call was cancelled' : 'the request timed out'
}
if (cause instanceof Error && cause.name === 'TimeoutError') return 'the request timed out'
return cause instanceof Error ? cause.message : String(cause)
}
/** One decoded `data:` payload of the Academy stream. */
interface StreamEvent {
response_type?: string
content?: string
knowledge_references?: SearchResult[]
session_id?: string
tool_calls?: { function?: { name?: string }, name?: string }[]
}
/**
* Consume Academy's `text/event-stream` and assemble the parts a tool result
* needs: the answer text, its citations, and the tool names the agent used.
* Server-side `error` events become a thrown failure so the model is never
* handed a silently empty answer.
*/
async function assembleStream(
body: ReadableStream<Uint8Array>,
sessionId: string,
path: string,
callerSignal: AbortSignal,
): Promise<StreamedAnswer> {
const decoder = new TextDecoder()
const reader = body.getReader()
const answer: string[] = []
const toolCalls: string[] = []
let references: SearchResult[] = []
let resolvedSessionId = sessionId
let buffer = ''
let completed = false
const consumeLine = (line: string): void => {
if (!line.startsWith('data:')) return
const payload = line.slice(5).trim()
if (payload === '' || payload === '[DONE]') return
let event: StreamEvent
try {
event = JSON.parse(payload) as StreamEvent
} catch {
return
}
if (typeof event.session_id === 'string' && event.session_id !== '') resolvedSessionId = event.session_id
switch (event.response_type) {
case 'answer':
if (typeof event.content === 'string') answer.push(event.content)
break
case 'references':
if (Array.isArray(event.knowledge_references)) references = event.knowledge_references
break
case 'tool_call':
for (const call of event.tool_calls ?? []) {
const name = call.function?.name ?? call.name
if (typeof name === 'string' && name !== '' && !toolCalls.includes(name)) toolCalls.push(name)
}
break
case 'error':
throw new AcademyApiError(`POST ${path} streamed an error: ${event.content ?? 'unknown error'}`)
case 'complete':
completed = true
break
default:
break
}
}
try {
while (!completed) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
let newline = buffer.indexOf('\n')
while (newline >= 0) {
consumeLine(buffer.slice(0, newline).replace(/\r$/, ''))
buffer = buffer.slice(newline + 1)
if (completed) break
newline = buffer.indexOf('\n')
}
}
if (!completed && buffer !== '') consumeLine(buffer.replace(/\r$/, ''))
} catch (cause) {
if (cause instanceof AcademyApiError) throw cause
throw new AcademyApiError(`POST ${path} stream failed: ${describeTransportFailure(cause, callerSignal)}`)
} finally {
await reader.cancel().catch(() => undefined)
}
// Academy ends every answer with a `complete` event. Without it the stream was
// cut short, and handing the model the partial text would present a truncated
// answer as a whole one.
if (!completed) {
throw new AcademyApiError(`POST ${path} ended before Academy completed the answer; `
+ `${answer.join('').length} character(s) had streamed`)
}
return { answer: answer.join(''), references, sessionId: resolvedSessionId, toolCalls }
}
+192
View File
@@ -0,0 +1,192 @@
/** Plugin configuration: shape, defaults, and load-time validation. */
/** Which tools the plugin registers. Omitted entries keep their default. */
export interface ToolToggles {
listKnowledgeBases?: boolean
search?: boolean
readDocument?: boolean
ask?: boolean
}
/** User-supplied configuration, as written in a Cordis patch row. */
export interface Config {
/** Academy API root, with or without the `/api/v1` suffix. */
baseUrl?: string
/** Tenant or platform API key, sent as `X-API-Key`. */
apiKey?: string
/** Workspace id, required only for platform-scoped API keys (`X-Tenant-ID`). */
tenantId?: string
/** Default knowledge-base scope when a call names none. */
knowledgeBaseIds?: string[]
/** Default custom agent for `academy_ask`; omitted uses the RAG pipeline. */
agentId?: string
/** Default and maximum number of chunks a search returns. */
maxResults?: number
/** Per-chunk character budget before the plugin truncates content. */
maxChunkChars?: number
/** Timeout for non-streaming requests. */
requestTimeoutMs?: number
/** Timeout for a streamed answer, which includes model and tool time. */
chatTimeoutMs?: number
/**
* `public` asks Academy for directly loadable file URLs in answers and
* citations (the default: dsh can render `https://` Markdown images, not
* `resource://` handles). `handle` keeps the internal references.
*/
resourceUrls?: 'handle' | 'public'
/** Tool-name prefix, so two instances can serve two deployments. */
toolPrefix?: string
/** Per-tool registration switches. */
tools?: ToolToggles
}
/** Configuration after defaults and validation. */
export interface ResolvedConfig {
baseUrl: string
apiKey: string | undefined
tenantId: string | undefined
knowledgeBaseIds: string[]
agentId: string | undefined
maxResults: number
maxChunkChars: number
requestTimeoutMs: number
chatTimeoutMs: number
resourceUrls: 'handle' | 'public'
toolPrefix: string
tools: Required<ToolToggles>
}
const DEFAULTS = {
baseUrl: 'http://localhost:8080/api/v1',
maxResults: 8,
maxChunkChars: 1200,
requestTimeoutMs: 30_000,
chatTimeoutMs: 300_000,
resourceUrls: 'public',
toolPrefix: 'academy',
} as const
/** Thrown when a patch row configures this plugin in a way it cannot serve. */
export class ConfigError extends Error {
constructor(violations: string[]) {
super(`dsh-academy configuration is invalid:\n - ${violations.join('\n - ')}`)
this.name = 'ConfigError'
}
}
const API_ROOT = /\/api\/v\d+$/
const TOOL_PREFIX = /^[a-z][a-z0-9_]*$/
/**
* Normalize a Academy base URL to an API root. Both `https://kb.example.com`
* and `https://kb.example.com/api/v1` are accepted, because a deployment's
* documented address is usually the bare origin.
*/
export function normalizeBaseUrl(raw: string): string {
const trimmed = raw.trim().replace(/\/+$/, '')
return API_ROOT.test(trimmed) ? trimmed : `${trimmed}/api/v1`
}
function positiveInt(value: unknown, field: string, violations: string[]): number | undefined {
if (value === undefined) return undefined
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
violations.push(`${field} must be a positive number, received ${JSON.stringify(value)}`)
return undefined
}
return Math.floor(value)
}
function stringList(value: unknown, field: string, violations: string[]): string[] | undefined {
if (value === undefined) return undefined
if (!Array.isArray(value) || value.some(entry => typeof entry !== 'string' || entry.trim() === '')) {
violations.push(`${field} must be an array of non-empty strings`)
return undefined
}
return (value as string[]).map(entry => entry.trim())
}
function optionalString(value: unknown, field: string, violations: string[]): string | undefined {
if (value === undefined || value === null || value === '') return undefined
if (typeof value !== 'string') {
violations.push(`${field} must be a string`)
return undefined
}
const trimmed = value.trim()
return trimmed === '' ? undefined : trimmed
}
function toggle(value: unknown, field: string, fallback: boolean, violations: string[]): boolean {
if (value === undefined) return fallback
if (typeof value !== 'boolean') {
violations.push(`${field} must be a boolean`)
return fallback
}
return value
}
/**
* Apply defaults and reject an unusable row while the plugin loads, so a typo
* surfaces at boot rather than inside the first tool call the model makes.
* @param raw - the `config` value from the Cordis row.
* @returns configuration every consumer can read without re-checking.
*/
export function resolveConfig(raw: Config | undefined): ResolvedConfig {
const violations: string[] = []
const config = raw ?? {}
if (typeof config !== 'object' || Array.isArray(config)) {
throw new ConfigError(['config must be an object'])
}
const baseUrlInput = optionalString(config.baseUrl, 'baseUrl', violations) ?? DEFAULTS.baseUrl
let baseUrl: string = DEFAULTS.baseUrl
try {
const url = new URL(normalizeBaseUrl(baseUrlInput))
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
violations.push(`baseUrl must use http or https, received ${url.protocol}`)
}
baseUrl = url.toString().replace(/\/+$/, '')
} catch {
violations.push(`baseUrl must be an absolute URL, received ${JSON.stringify(baseUrlInput)}`)
}
const resourceUrls = config.resourceUrls ?? DEFAULTS.resourceUrls
if (resourceUrls !== 'handle' && resourceUrls !== 'public') {
violations.push(`resourceUrls must be "handle" or "public", received ${JSON.stringify(resourceUrls)}`)
}
const toolPrefix = optionalString(config.toolPrefix, 'toolPrefix', violations) ?? DEFAULTS.toolPrefix
if (!TOOL_PREFIX.test(toolPrefix)) {
violations.push(`toolPrefix must match ${String(TOOL_PREFIX)}, received ${JSON.stringify(toolPrefix)}`)
}
const toolToggles = config.tools ?? {}
if (typeof toolToggles !== 'object' || Array.isArray(toolToggles)) {
violations.push('tools must be an object of booleans')
}
const resolved: ResolvedConfig = {
baseUrl,
apiKey: optionalString(config.apiKey, 'apiKey', violations),
tenantId: optionalString(config.tenantId, 'tenantId', violations),
knowledgeBaseIds: stringList(config.knowledgeBaseIds, 'knowledgeBaseIds', violations) ?? [],
agentId: optionalString(config.agentId, 'agentId', violations),
maxResults: positiveInt(config.maxResults, 'maxResults', violations) ?? DEFAULTS.maxResults,
maxChunkChars: positiveInt(config.maxChunkChars, 'maxChunkChars', violations) ?? DEFAULTS.maxChunkChars,
requestTimeoutMs: positiveInt(config.requestTimeoutMs, 'requestTimeoutMs', violations) ?? DEFAULTS.requestTimeoutMs,
chatTimeoutMs: positiveInt(config.chatTimeoutMs, 'chatTimeoutMs', violations) ?? DEFAULTS.chatTimeoutMs,
resourceUrls: resourceUrls === 'public' ? 'public' : 'handle',
toolPrefix,
tools: {
listKnowledgeBases: toggle(toolToggles.listKnowledgeBases, 'tools.listKnowledgeBases', true, violations),
search: toggle(toolToggles.search, 'tools.search', true, violations),
readDocument: toggle(toolToggles.readDocument, 'tools.readDocument', true, violations),
ask: toggle(toolToggles.ask, 'tools.ask', true, violations),
},
}
if (!Object.values(resolved.tools).some(Boolean)) {
violations.push('at least one tool must stay enabled; remove the plugin row instead of disabling all of them')
}
if (violations.length > 0) throw new ConfigError(violations)
return resolved
}
+62
View File
@@ -0,0 +1,62 @@
/**
* Structural types for the slice of the DeepSeek Harness contract this plugin
* uses. Declaring them here keeps the package free of runtime dependencies on
* harness internals: the shipped code only ever hands `ctx.tools.register()` a
* plain object, so a harness release that adds optional definition fields does
* not require a republish of this plugin.
*
* The shapes mirror `@deepseek-ai/dsh-tools` (`ToolDefinition`) and
* `@deepseek-ai/dsh-llm` (`ContentBlock`, `ToolSchema`) as of dsh 0.1.0-rc.8.
*/
/** Supported subset of JSON Schema that the harness tool registry accepts. */
export interface JsonSchemaNode {
type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null'
properties?: Record<string, JsonSchemaNode>
required?: string[]
additionalProperties?: boolean
items?: JsonSchemaNode
enum?: (string | number | boolean | null)[]
const?: string | number | boolean | null
description?: string
title?: string
}
/** Model-facing content block returned by `output.render`. */
export interface TextContentBlock {
type: 'text'
text: string
}
/** Execution context handed to a tool body. */
export interface ToolRunContext {
readonly signal: AbortSignal
}
/** One registered model-facing tool. */
export interface ToolDefinition {
readonly name: string
readonly description: string
readonly parameters: JsonSchemaNode
readonly output: {
readonly schema: JsonSchemaNode
render(args: unknown, value: unknown): TextContentBlock[]
}
execute(args: unknown, exec: ToolRunContext): Promise<unknown>
readonly timeoutMs?: number
isConcurrencySafe?(args: unknown): boolean
}
/** The `ctx.tools` service seam. */
export interface ToolRegistry {
register(definition: ToolDefinition): () => void
}
/** The slice of the Cordis context this plugin injects. */
export interface HarnessContext {
readonly tools: ToolRegistry
readonly logger?: {
info(...args: unknown[]): void
warn(...args: unknown[]): void
}
}
+37
View File
@@ -0,0 +1,37 @@
/**
* dsh-academy: a DeepSeek Harness plugin that gives the agent retrieval,
* document reading and composed answers from a Academy knowledge base.
* @module dsh-academy
*/
import { AcademyClient } from './client.ts'
import { resolveConfig } from './config.ts'
import type { HarnessContext } from './harness.ts'
import { createTools } from './tools.ts'
export const name = 'dsh-academy'
/** Cordis waits for the tool registry before applying this plugin. */
export const inject = ['tools'] as const
export type { Config } from './config.ts'
export { ConfigError, normalizeBaseUrl, resolveConfig } from './config.ts'
export { AcademyApiError, AcademyClient } from './client.ts'
export { createTools } from './tools.ts'
/**
* Register the configured tools. Each registration is an effect, so unloading
* or reconfiguring the plugin withdraws the tools without a restart.
* @param ctx - the Cordis context, with `ctx.tools` injected.
* @param config - the plugin's `config` row; validated here so a typo fails the load.
*/
export function apply(ctx: HarnessContext, config: unknown): void {
const resolved = resolveConfig(config as never)
const client = new AcademyClient(resolved)
const registered: string[] = []
for (const definition of createTools(client, resolved)) {
ctx.tools.register(definition)
registered.push(definition.name)
}
ctx.logger?.info(`dsh-academy: registered ${registered.join(', ')} against ${resolved.baseUrl}`)
}
+25
View File
@@ -0,0 +1,25 @@
/** Pure projections from a tool's canonical value to model-facing text. */
/** Clip text to a character budget, reporting whether anything was dropped. */
export function clip(text: string, maxChars: number): { text: string, truncated: boolean } {
const normalized = text.replace(/\r\n/g, '\n').trim()
if (normalized.length <= maxChars) return { text: normalized, truncated: false }
return { text: `${normalized.slice(0, maxChars).trimEnd()}…`, truncated: true }
}
/** Human-readable score, tolerant of a backend that omits it. */
export function formatScore(score: number): string {
return Number.isFinite(score) ? score.toFixed(3) : 'n/a'
}
/**
* Name a retrieval scope without spending the model's context on it. A
* deployment can hold dozens of knowledge bases, and spelling out every id on
* every search costs far more than the count is worth; the ids stay in the
* tool's canonical value for anything that needs them.
*/
export function describeScope(ids: string[]): string {
if (ids.length === 0) return '(deployment default)'
if (ids.length <= 3) return ids.join(', ')
return `${ids.length} knowledge bases`
}
+562
View File
@@ -0,0 +1,562 @@
/** The model-facing tools this plugin contributes to `ctx.tools`. */
import type { ChunkRecord, DocumentRecord, SearchResult, AcademyClient } from './client.ts'
import type { ResolvedConfig } from './config.ts'
import type { JsonSchemaNode, TextContentBlock, ToolDefinition } from './harness.ts'
import { clip, describeScope, formatScore } from './render.ts'
/** A retrieval hit projected onto the fields the model and follow-up calls need. */
interface SearchHit {
rank: number
chunk_id: string
knowledge_id: string
document: string
chunk_index: number
score: number
content: string
truncated: boolean
}
/** A document whose name matched, which passage retrieval alone would miss. */
interface DocumentMatch {
knowledge_id: string
title: string
knowledge_base_id: string
knowledge_base: string
}
interface SearchValue {
query: string
knowledge_base_ids: string[]
count: number
results: SearchHit[]
documents: DocumentMatch[]
}
interface KnowledgeBasesValue {
count: number
knowledge_bases: { id: string, name: string, description: string }[]
}
interface DocumentValue {
knowledge_id: string
title: string
summary: string
page: number
page_size: number
total_chunks: number
returned_chunks: number
has_more: boolean
truncated: boolean
content: string
}
interface AskValue {
answer: string
session_id: string
pipeline: 'rag' | 'agent'
tool_calls: string[]
references: { knowledge_id: string, document: string, chunk_index: number, content: string }[]
}
const text = (value: string): TextContentBlock[] => [{ type: 'text', text: value }]
const STRING_ARRAY: JsonSchemaNode = { type: 'array', items: { type: 'string' } }
/** Read an argument the harness passes as `unknown` without trusting its shape. */
function argRecord(args: unknown): Record<string, unknown> {
return typeof args === 'object' && args !== null && !Array.isArray(args) ? args as Record<string, unknown> : {}
}
function requiredString(args: unknown, field: string, toolName: string): string {
const value = argRecord(args)[field]
if (typeof value !== 'string' || value.trim() === '') {
throw new Error(`${toolName}: "${field}" is required and must be a non-empty string`)
}
return value.trim()
}
function optionalStringArg(args: unknown, field: string): string | undefined {
const value = argRecord(args)[field]
return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
}
function stringArrayArg(args: unknown, field: string): string[] {
const value = argRecord(args)[field]
if (!Array.isArray(value)) return []
return value.filter((entry): entry is string => typeof entry === 'string' && entry.trim() !== '').map(entry => entry.trim())
}
function boundedIntArg(args: unknown, field: string, fallback: number, max: number): number {
const value = argRecord(args)[field]
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return fallback
return Math.min(Math.floor(value), max)
}
/** Prefer a human title, then the source filename, then the opaque id. */
function documentLabel(result: SearchResult): string {
const title = typeof result.knowledge_title === 'string' ? result.knowledge_title.trim() : ''
if (title !== '') return title
const filename = typeof result.knowledge_filename === 'string' ? result.knowledge_filename.trim() : ''
if (filename !== '') return filename
return typeof result.knowledge_id === 'string' && result.knowledge_id !== '' ? result.knowledge_id : '(untitled)'
}
function projectHit(result: SearchResult, rank: number, maxChunkChars: number): SearchHit {
const clipped = clip(typeof result.content === 'string' ? result.content : '', maxChunkChars)
return {
rank,
chunk_id: typeof result.id === 'string' ? result.id : '',
knowledge_id: typeof result.knowledge_id === 'string' ? result.knowledge_id : '',
document: documentLabel(result),
chunk_index: typeof result.chunk_index === 'number' ? result.chunk_index : -1,
// 0 rather than NaN: the canonical value must stay lossless JSON.
score: typeof result.score === 'number' && Number.isFinite(result.score) ? result.score : 0,
content: clipped.text,
truncated: clipped.truncated,
}
}
/**
* Keep the by-name matches worth showing: inside the scope the caller asked
* for, and not already represented by a passage hit. Academy's by-name search
* spans the whole tenant, so the scope filter is what stops a narrowed call
* from reporting documents outside it.
*/
function projectNamedDocuments(
named: DocumentRecord[],
passages: SearchHit[],
knowledgeBaseIds: string[],
knowledgeIds: string[],
): DocumentMatch[] {
const already = new Set(passages.map(hit => hit.knowledge_id))
const scope = new Set(knowledgeBaseIds)
const wanted = new Set(knowledgeIds)
const out: DocumentMatch[] = []
for (const document of named) {
const id = typeof document.id === 'string' ? document.id : ''
const kbId = typeof document.knowledge_base_id === 'string' ? document.knowledge_base_id : ''
if (id === '' || already.has(id)) continue
if (wanted.size > 0 ? !wanted.has(id) : !scope.has(kbId)) continue
const title = typeof document.title === 'string' && document.title.trim() !== ''
? document.title.trim()
: typeof document.file_name === 'string' ? document.file_name : id
out.push({
knowledge_id: id,
title,
knowledge_base_id: kbId,
knowledge_base: typeof document.knowledge_base_name === 'string' ? document.knowledge_base_name : kbId,
})
already.add(id)
}
return out
}
/** Assemble the four tool definitions for one configured deployment. */
export function createTools(client: AcademyClient, config: ResolvedConfig): ToolDefinition[] {
const name = (suffix: string): string => `${config.toolPrefix}_${suffix}`
const scopeNote = config.knowledgeBaseIds.length > 0
? ` Searches knowledge base(s) ${config.knowledgeBaseIds.join(', ')} unless you name others.`
: ' Searches every knowledge base this credential can see unless you narrow it with knowledge_base_ids.'
// An unscoped call reaches Academy as a refusal on the retrieval route and as
// an answer grounded in nothing on the RAG route, so an unconfigured
// deployment resolves the full visible set once and reuses it. Making the
// model pick a scope first is worse: knowledge bases are often named too
// poorly to choose between, and fanning out across them is cheap while they
// share a vector store.
let everyId: Promise<string[]> | undefined
const allKnowledgeBaseIds = async (signal: AbortSignal): Promise<string[]> => {
everyId ??= client.listKnowledgeBases(signal).then(
bases => bases.map(kb => typeof kb.id === 'string' ? kb.id : '').filter(id => id !== ''),
(error: unknown) => {
everyId = undefined
throw error
},
)
return await everyId
}
const resolveScope = async (requested: string[], knowledgeIds: string[], signal: AbortSignal): Promise<string[]> => {
if (requested.length > 0) return requested
if (config.knowledgeBaseIds.length > 0) return config.knowledgeBaseIds
if (knowledgeIds.length > 0) return []
return await allKnowledgeBaseIds(signal)
}
const definitions: ToolDefinition[] = []
if (config.tools.listKnowledgeBases) {
definitions.push({
name: name('list_knowledge_bases'),
description: 'List the Academy knowledge bases this deployment can retrieve from, with their ids. '
+ `${name('search')} already spans them all, so reach for this only to report what is available or to `
+ 'narrow a later search to one of them.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
timeoutMs: config.requestTimeoutMs,
isConcurrencySafe: () => true,
output: {
schema: {
type: 'object',
properties: {
count: { type: 'integer' },
knowledge_bases: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
description: { type: 'string' },
},
required: ['id', 'name', 'description'],
additionalProperties: false,
},
},
},
required: ['count', 'knowledge_bases'],
additionalProperties: false,
},
render: (_args, value) => {
const result = value as KnowledgeBasesValue
if (result.count === 0) return text('No knowledge base is available to this Academy credential.')
const lines = result.knowledge_bases.map(kb => {
const description = kb.description === '' ? '' : ` — ${kb.description}`
return `- ${kb.name} (id: ${kb.id})${description}`
})
return text(`${result.count} knowledge base(s):\n${lines.join('\n')}`)
},
},
async execute(_args, exec): Promise<KnowledgeBasesValue> {
const bases = await client.listKnowledgeBases(exec.signal)
return {
count: bases.length,
knowledge_bases: bases.map(kb => ({
id: typeof kb.id === 'string' ? kb.id : '',
name: typeof kb.name === 'string' ? kb.name : '',
description: typeof kb.description === 'string' ? kb.description : '',
})),
}
},
})
}
if (config.tools.search) {
definitions.push({
name: name('search'),
description: 'Search Academy knowledge bases and return the matching passages verbatim (hybrid vector + keyword '
+ 'retrieval, no model summarization). Use this to ground an answer in the organization\'s own documents, and '
+ 'also to locate a document by name — a query that reads like a title additionally returns the documents it '
+ 'names.' + scopeNote
+ ` Every hit carries a knowledge_id you can pass to ${name('read_document')} for the full document.`,
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'Natural-language query; a full question retrieves better than keywords.' },
knowledge_base_ids: { ...STRING_ARRAY, description: 'Restrict the search to these knowledge base ids.' },
knowledge_ids: { ...STRING_ARRAY, description: 'Restrict the search to these document ids.' },
max_results: { type: 'integer', description: `Maximum passages to return (default ${config.maxResults}).` },
},
required: ['query'],
additionalProperties: false,
},
timeoutMs: config.requestTimeoutMs,
isConcurrencySafe: () => true,
output: {
schema: {
type: 'object',
properties: {
query: { type: 'string' },
knowledge_base_ids: STRING_ARRAY,
count: { type: 'integer' },
results: {
type: 'array',
items: {
type: 'object',
properties: {
rank: { type: 'integer' },
chunk_id: { type: 'string' },
knowledge_id: { type: 'string' },
document: { type: 'string' },
chunk_index: { type: 'integer' },
score: { type: 'number' },
content: { type: 'string' },
truncated: { type: 'boolean' },
},
required: ['rank', 'chunk_id', 'knowledge_id', 'document', 'chunk_index', 'score', 'content', 'truncated'],
additionalProperties: false,
},
},
documents: {
type: 'array',
items: {
type: 'object',
properties: {
knowledge_id: { type: 'string' },
title: { type: 'string' },
knowledge_base_id: { type: 'string' },
knowledge_base: { type: 'string' },
},
required: ['knowledge_id', 'title', 'knowledge_base_id', 'knowledge_base'],
additionalProperties: false,
},
},
},
required: ['query', 'knowledge_base_ids', 'count', 'results', 'documents'],
additionalProperties: false,
},
render: (_args, value) => {
const result = value as SearchValue
const named = result.documents.length === 0
? ''
: `\n\nDocuments named "${result.query}" (read them with ${name('read_document')}):\n`
+ result.documents.map(document =>
`- ${document.title} · knowledge_id: ${document.knowledge_id} · in ${document.knowledge_base}`).join('\n')
if (result.count === 0) {
if (named === '') {
return text(`Nothing in Academy matched "${result.query}" `
+ `(searched: ${describeScope(result.knowledge_base_ids)}). `
+ 'Try a differently worded query, or widen the knowledge base scope.')
}
return text(`No passage matched "${result.query}", but its name matches document(s).${named}`)
}
const blocks = result.results.map(hit =>
`[${hit.rank}] ${hit.document} · score ${formatScore(hit.score)} · chunk ${hit.chunk_index} `
+ `· knowledge_id: ${hit.knowledge_id}\n${hit.content}${hit.truncated ? '\n(passage truncated)' : ''}`)
return text(`${result.count} passage(s) for "${result.query}" `
+ `(searched: ${describeScope(result.knowledge_base_ids)}):\n\n${blocks.join('\n\n')}${named}`)
},
},
async execute(args, exec): Promise<SearchValue> {
const toolName = name('search')
const query = requiredString(args, 'query', toolName)
const knowledgeIds = stringArrayArg(args, 'knowledge_ids')
const knowledgeBaseIds = await resolveScope(
stringArrayArg(args, 'knowledge_base_ids'),
knowledgeIds,
exec.signal,
)
// Fail here rather than let Academy answer 400: the model can act on a
// message naming the argument to supply, not on a transport error.
if (knowledgeBaseIds.length === 0 && knowledgeIds.length === 0) {
throw new Error(`${toolName}: this Academy credential can see no knowledge base, so there is `
+ 'nothing to search. Check the deployment\'s API key scope.')
}
const limit = boundedIntArg(args, 'max_results', config.maxResults, config.maxResults)
const [hits, named] = await Promise.all([
client.search({ query, knowledgeBaseIds, knowledgeIds }, exec.signal),
// By-name matching is an enrichment, and older Academy builds may not
// route it. Losing it must not cost the model its passages.
client.findDocuments({ keyword: query, limit }, exec.signal).catch(() => []),
])
const results = hits.slice(0, limit).map((hit, index) => projectHit(hit, index + 1, config.maxChunkChars))
return {
query,
knowledge_base_ids: knowledgeBaseIds,
count: results.length,
results,
documents: projectNamedDocuments(named, results, knowledgeBaseIds, knowledgeIds),
}
},
})
}
if (config.tools.readDocument) {
definitions.push({
name: name('read_document'),
description: 'Read a Academy document\'s stored passages in order, reassembled into text. '
+ `Use it after ${name('search')} when one passage is not enough context; page through long documents.`,
parameters: {
type: 'object',
properties: {
knowledge_id: { type: 'string', description: 'Document id, as returned in a search hit.' },
page: { type: 'integer', description: 'Page of passages, starting at 1.' },
page_size: { type: 'integer', description: 'Passages per page (max 100).' },
},
required: ['knowledge_id'],
additionalProperties: false,
},
timeoutMs: config.requestTimeoutMs,
isConcurrencySafe: () => true,
output: {
schema: {
type: 'object',
properties: {
knowledge_id: { type: 'string' },
title: { type: 'string' },
summary: { type: 'string' },
page: { type: 'integer' },
page_size: { type: 'integer' },
total_chunks: { type: 'integer' },
returned_chunks: { type: 'integer' },
has_more: { type: 'boolean' },
truncated: { type: 'boolean' },
content: { type: 'string' },
},
required: [
'knowledge_id', 'title', 'summary', 'page', 'page_size',
'total_chunks', 'returned_chunks', 'has_more', 'truncated', 'content',
],
additionalProperties: false,
},
render: (_args, value) => {
const result = value as DocumentValue
const label = result.title === '' ? result.knowledge_id : `${result.title} (${result.knowledge_id})`
if (result.returned_chunks === 0) {
return text(`Document ${label} has no passage on page ${result.page} `
+ `(${result.total_chunks} passage(s) in total).`)
}
// The summary lets the model judge a long document from page 1
// instead of paging blindly to find out what it is holding.
const summary = result.summary === '' ? '' : `\n\nSummary: ${result.summary}`
const more = result.has_more ? `\n\n(more passages available: request page ${result.page + 1})` : ''
const cut = result.truncated ? '\n(content truncated)' : ''
return text(`Document ${label}, passages ${result.returned_chunks} of ${result.total_chunks} `
+ `(page ${result.page}):${summary}\n\n${result.content}${cut}${more}`)
},
},
async execute(args, exec): Promise<DocumentValue> {
const toolName = name('read_document')
const knowledgeId = requiredString(args, 'knowledge_id', toolName)
const page = boundedIntArg(args, 'page', 1, 10_000)
const pageSize = boundedIntArg(args, 'page_size', 20, 100)
const [result, metadata] = await Promise.all([
client.listChunks({ knowledgeId, page, pageSize }, exec.signal),
// Only page 1 is worth the extra call and the summary's tokens: by
// page 2 the model has already seen what this document is. Metadata
// is context, not the payload, so a deployment that cannot serve it
// must still hand over the text.
page === 1
? client.getDocument(knowledgeId, exec.signal).catch(() => ({}) as DocumentRecord)
: Promise.resolve({} as DocumentRecord),
])
const ordered = [...result.chunks].sort(orderByChunkIndex)
const joined = ordered.map(chunk => typeof chunk.content === 'string' ? chunk.content : '').join('\n\n')
const clipped = clip(joined, config.maxChunkChars * Math.max(1, Math.min(ordered.length, 10)))
const title = typeof metadata.title === 'string' && metadata.title.trim() !== ''
? metadata.title.trim()
: typeof metadata.file_name === 'string' ? metadata.file_name.trim() : ''
return {
knowledge_id: knowledgeId,
title,
summary: clip(typeof metadata.description === 'string' ? metadata.description.trim() : '', config.maxChunkChars).text,
page: result.page,
page_size: result.pageSize,
total_chunks: result.total,
returned_chunks: ordered.length,
has_more: result.page * result.pageSize < result.total,
truncated: clipped.truncated,
content: clipped.text,
}
},
})
}
if (config.tools.ask) {
const pipeline = config.agentId === undefined ? 'RAG' : 'agent'
definitions.push({
name: name('ask'),
description: `Ask Academy a question and get its own composed answer with citations (${pipeline} pipeline runs `
+ 'server-side: query rewriting, retrieval, reranking and summarization). Reserve it for broad or '
+ 'synthesis questions whose answer spans many documents, where retrieving passages yourself would take '
+ `several rounds. For anything you can answer from specific passages, prefer ${name('search')}: it is far `
+ 'faster and leaves you the evidence to reason over rather than another model\'s conclusion.',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'The question to answer.' },
knowledge_base_ids: { ...STRING_ARRAY, description: 'Restrict retrieval to these knowledge base ids.' },
agent_id: { type: 'string', description: 'Custom agent id; selects the server-side ReAct pipeline.' },
session_id: { type: 'string', description: 'Continue an earlier Academy session instead of starting one.' },
web_search: { type: 'boolean', description: 'Let Academy also search the web, when its deployment allows it.' },
},
required: ['query'],
additionalProperties: false,
},
timeoutMs: config.chatTimeoutMs,
output: {
schema: {
type: 'object',
properties: {
answer: { type: 'string' },
session_id: { type: 'string' },
pipeline: { type: 'string', enum: ['rag', 'agent'] },
tool_calls: STRING_ARRAY,
references: {
type: 'array',
items: {
type: 'object',
properties: {
knowledge_id: { type: 'string' },
document: { type: 'string' },
chunk_index: { type: 'integer' },
content: { type: 'string' },
},
required: ['knowledge_id', 'document', 'chunk_index', 'content'],
additionalProperties: false,
},
},
},
required: ['answer', 'session_id', 'pipeline', 'tool_calls', 'references'],
additionalProperties: false,
},
render: (_args, value) => {
const result = value as AskValue
const parts: string[] = []
parts.push(result.answer === ''
? 'Academy returned an empty answer. Retry with a more specific question, or retrieve passages instead.'
: result.answer)
if (result.references.length > 0) {
const cited = result.references.map((reference, index) =>
`[${index + 1}] ${reference.document} · chunk ${reference.chunk_index} · knowledge_id: ${reference.knowledge_id}`)
parts.push(`Citations:\n${cited.join('\n')}`)
}
if (result.tool_calls.length > 0) parts.push(`Academy tools used: ${result.tool_calls.join(', ')}`)
parts.push(`Academy session: ${result.session_id} (pass session_id to ask a follow-up in context)`)
return text(parts.join('\n\n'))
},
},
async execute(args, exec): Promise<AskValue> {
const toolName = name('ask')
const query = requiredString(args, 'query', toolName)
const requested = stringArrayArg(args, 'knowledge_base_ids')
const agentId = optionalStringArg(args, 'agent_id') ?? config.agentId
// A custom agent resolves its own scope server-side from its
// KBSelectionMode, and ids sent here would override that as an explicit
// mention. The RAG pipeline has no such default: it retrieves only what
// the request names, and answers from nothing when it names nothing.
const knowledgeBaseIds = agentId === undefined
? await resolveScope(requested, [], exec.signal)
: requested.length > 0 ? requested : config.knowledgeBaseIds
if (agentId === undefined && knowledgeBaseIds.length === 0) {
throw new Error(`${toolName}: this Academy credential can see no knowledge base, so there is `
+ 'nothing to answer from. Check the deployment\'s API key scope.')
}
const webSearch = argRecord(args)['web_search'] === true
const sessionId = optionalStringArg(args, 'session_id')
?? await client.createSession(`dsh: ${clip(query, 60).text}`, exec.signal)
const streamed = await client.ask({ sessionId, query, knowledgeBaseIds, agentId, webSearch }, exec.signal)
return {
answer: streamed.answer.trim(),
session_id: streamed.sessionId,
pipeline: agentId === undefined ? 'rag' : 'agent',
tool_calls: streamed.toolCalls,
references: streamed.references.slice(0, config.maxResults).map(reference => ({
knowledge_id: typeof reference.knowledge_id === 'string' ? reference.knowledge_id : '',
document: documentLabel(reference),
chunk_index: typeof reference.chunk_index === 'number' ? reference.chunk_index : -1,
content: clip(typeof reference.content === 'string' ? reference.content : '', config.maxChunkChars).text,
})),
}
},
})
}
return definitions
}
/** Storage order, so a reassembled document reads top to bottom. */
function orderByChunkIndex(left: ChunkRecord, right: ChunkRecord): number {
const a = typeof left.chunk_index === 'number' ? left.chunk_index : 0
const b = typeof right.chunk_index === 'number' ? right.chunk_index : 0
return a - b
}