/** * dsh-better-sidebar host half: the /sidebar JSON API (explorer listing, file * read/write, git), the /sidebar/file media route (images), the /sidebar/html * preview route, the /sidebar/bundle lazy-chunk route (client code splits), * and the two WebSocket upgrades (sidebar_open pushes). Every route passes the same * browser-trust fence as the /api gateway — Host-header loopback or the * web runtime's `trustedHosts` (LAN IP literals sampled at boot plus * `--trusted-host` authorities), read per request from the live service * value so the fence tracks the same trust source the /api gateway derives * its list from. * * All operations are conversation-scoped: requests carry a sessionId and the * session's authoritative cwd comes from the session store. */ import { randomUUID } from 'node:crypto' import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises' import { basename, dirname, extname, isAbsolute, join, sep } from 'node:path' import type { IncomingMessage } from 'node:http' import type { Duplex } from 'node:stream' import { WebSocket, WebSocketServer } from 'ws' import { parse as parseYaml } from 'yaml' import type { Context, SidebarHttpRequest, SidebarSessionEvent, SidebarSettingsService } from './context-types.ts' import { Config, resolveSidebarConfig, SIDEBAR_PREFS_DEFAULTS, SIDEBAR_PREFS_NS, type ResolvedSidebarConfig, type SidebarConfig, type SidebarPrefs, } from './config.ts' import { invalidateDirectoryCache, listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts' import { resolveSessionPath } from './session-path.ts' import { createWorkspaceFile, mkdirWorkspaceEntry, renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceUpload } from './fs-operations.ts' import { ensureWorkspacePath, ensureWorkspaceWritePath } from './path-security.ts' import { searchFiles } from './fs-search.ts' import { compileExcludePatterns } from './exclude-patterns.ts' import { decodeHtmlUrl } from './html-route.ts' import { isTrustedApiRequest } from './trust-fence.ts' import { registerBundleRoute } from './bundle-route.ts' import { createDirectoryWatchers, type DirectoryWatchers } from './fs-watch.ts' import { launchExternal } from './open-external.ts' import { archiveNameOf, collectZipEntries, createArchiveTasks, disambiguateArchiveNames, respondArchiveDownload, type ArchiveTasks } from './archive-route.ts' import type { ZipEntry } from './zip.ts' import * as git from './git.ts' import { SettingsConflictError } from '@deepseek-ai/dsh-settings' import { AgentOpenRegistry, registerOpenTool, type AgentOpenRequest } from './agent-opens.ts' import { buildSubagentLiveApi, type SidebarSubagentLiveRoutes } from './subagent-live-route.ts' import { buildTeamsApi, type SidebarTeamsRoutes } from './team-routes.ts' import { buildWorkflowsApi, type SidebarWorkflowRoutes } from './workflow-routes.ts' import { buildSidechatApi } from './sidechat-routes.ts' import { createAssistantLiveBuffer, type AssistantLiveBuffer } from './assistant-live.ts' import { readJsonBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts' import { readPersistedSession } from './session-store.ts' import { BlockAssembler, createUserMessage, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm' import { buildCommitPrompt, cleanSuggestion, collectModelRoutes, defaultRouteOf, lowestReasoningEffortOf, modelEntryOf, normalizeLanguage, parseModelRoute, providerEntryOf, truncateDiff, type CommitModelRoute, } from './commit-message.ts' // Shared with the client's batch splitter: the two halves must agree on the // row bound, so it lives in a dependency-free module both can import. import { FS_TREES_MAX_PATHS } from './fs-batch.ts' import { activeWorktreeRootOf } from './active-worktree.ts' import { decodeTextBytes, encodeText, fileFormatOf, restoreEol } from './text-encoding.ts' export { Config } export type { SidebarConfig, ResolvedSidebarConfig } // Re-export the Context augmentation (`declare module '@deepseek-ai/cordis'`) // so consumers `import type {} from 'dsh-better-sidebar'` and gain // `ctx.betterSidebar`; the Context re-export below is the vendored cordis // Context intersected with the structural service faces. // Also re-export the service descriptor types so consumers can type their // registerTab / registerFileViewer arguments without reaching into /client. export type { Context } from './context-types.ts' export type { BetterSidebarService, TabDescriptor, TabComponentProps, FileViewerDescriptor, FileViewerProps, FileFetchStrategy, } from './client/service.ts' // The archive walk + name helpers are exercised directly by tests/zip.spec.ts: // their bounds live inside the collector, so the suite needs them observable // without creating 10 000 rows first. export { archiveNameOf, collectZipEntries, contentDispositionOf, disambiguateArchiveNames } from './archive-route.ts' /** Plugin identity for cordis.yml rows. */ export const name = 'dsh-better-sidebar' /** Row bound of one `fs.trees` batch request (a mount/refresh sends what it * shows, split into cap-sized batches by the client — see `fs-batch.ts`). */ export { FS_TREES_MAX_PATHS } /** One level of an `fs.trees` batch: either a listing or that level's failure. */ export interface SidebarFsLevel { path: string entries: SidebarFsEntry[] truncated: boolean /** Present only when THIS level failed (the batch itself still succeeded). */ error?: string } /** Services required before mounting: the webserver routes, the session store, the web runtime's trusted hosts, and the tool registry. */ export const inject = ['webServer', 'sessions', 'webRuntime', 'tools'] /** Content types for the media route, by extension. */ const MEDIA_TYPES: Record = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.bmp': 'image/bmp', '.ico': 'image/x-icon', '.avif': 'image/avif', '.pdf': 'application/pdf', '.html': 'text/html', '.htm': 'text/html', } /** Content type served by /sidebar/file (binary-safe fallback for unknowns). */ export function mediaTypeForPath(path: string): string { return MEDIA_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream' } /** * Resolve a session's authoritative working directory. The attached session * header wins; while the session is still hydrating from persistence (the * web client attaches the current conversation a moment after page load, so * the very first sidebar requests can arrive detached) the caller's own * list-summary cwd is used; the session-persistence index is queried as a * last resort for cold (not-yet-attached) sessions so a detached first * request still resolves the correct project instead of the host process * cwd (which on Windows is the DSH source root after `dsh.cmd`'s `pushd`, * causing every user-project path to be misclassified as "outside * workspace"). The host process cwd is the FINAL fallback for deployments * without persistence (tests / stripped-down hosts); production always * provides persistence, so the bug-fix path (header → client → persistence) * always resolves the real session cwd before reaching it. */ async function sessionCwdOf(ctx: Context, sessionId: string, clientCwd?: string): Promise { const session = ctx.sessions.get(sessionId) const headerCwd = session?.header.cwd if (headerCwd !== undefined && headerCwd !== '') return headerCwd if (clientCwd !== undefined && clientCwd !== '') { try { return requireAbsolute(clientCwd) } catch { throw new SidebarError('bad-request', `invalid working directory "${clientCwd}"`) } } const persistence = ctx.get('sessionPersistence') if (persistence !== undefined) { const persisted = await readPersistedSession(persistence, sessionId) const metaCwd = persisted.header.cwd if (metaCwd !== undefined && metaCwd !== '') { try { return requireAbsolute(metaCwd) } catch { throw new SidebarError('bad-request', `invalid working directory "${metaCwd}"`) } } } return process.cwd() } /** Optional repository selected by the Git panel when cwd is a container. */ function selectedRepoOf(payload: unknown): string | undefined { const record = payload as { repoRoot?: unknown } if (record.repoRoot === undefined) return undefined return requireAbsolute(requireString(payload, 'repoRoot')) } /** One required 1-based line number of a `git blame -L` request. */ function requireLineNumber(payload: unknown, key: string): number { const value = (payload as Record | null)?.[key] if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) { throw new SidebarError('bad-request', `"${key}" must be a positive integer line number`) } return value } /** * Resolve a relative path an EDITOR surface carried (the file tree, the * editor buffer, and `fs.read`, which the untracked-diff fallback reads * through): the session-relative interpretation wins when it names an * existing path, with the repository root as the fallback. Git's * status/diff ROWS deliberately do NOT come through here — they are * repository-root-relative by construction, see {@link resolveStatusPath}. */ async function resolveGitPath(cwd: string, raw: string, selected?: string): Promise { if (isAbsolute(raw)) return requireAbsolute(resolveSessionPath(cwd, raw)) // Prefer the session-relative interpretation when it names an existing // path. Git status reports repository-root-relative names, but the sidebar // security boundary is the session workspace; this preference keeps files // inside a nested session readable without reopening the repository root. const sessionPath = requireAbsolute(join(cwd, raw)) if (await stat(sessionPath).then(() => true).catch(() => false)) return sessionPath const root = await git.repoRoot(cwd, selected).catch(() => cwd) return requireAbsolute(join(root, raw)) } /** Max providers / per-provider models the `git.models` catalog answers with. * The catalog only feeds the Git card's pinned-model dropdown, so a huge * deployment still resolves to a bounded, fast reply. */ const MODEL_CATALOG_PROVIDER_LIMIT = 20 const MODEL_CATALOG_MODEL_LIMIT = 50 /** The Git card's plugin-owned settings key holding the pinned * `provider/model` route ('' or absent = follow the conversation). */ const COMMIT_MODEL_SETTING_KEY = 'commitModel' /** * The provider/model route the user PINNED for commit-message generation * (the Git card's settings write `pluginSettings.git.commitModel`). Absent, * empty or malformed means "follow the conversation" — a bad value must * never lock the feature out, it falls back. */ function pinnedCommitRouteOf(getSettings: () => SidebarSettingsFace | undefined): CommitModelRoute | undefined { const value = getSettings()?.get().value if (value === null || typeof value !== 'object') return undefined const pluginSettings = (value as { pluginSettings?: unknown }).pluginSettings if (pluginSettings === null || typeof pluginSettings !== 'object') return undefined const blob = (pluginSettings as Record).git if (blob === null || typeof blob !== 'object') return undefined return parseModelRoute((blob as Record)[COMMIT_MODEL_SETTING_KEY]) } /** * The provider/model route the CURRENT conversation runs on, read without * spawning anything: the live agent's own options are authoritative, and a * session that has not attached yet still carries its newest `request/header` * event (the record the agent loop writes). Undefined while neither is * available — a cold conversation with no request yet has no route to follow. */ function conversationModelRoute(ctx: Context, sessionId: string): CommitModelRoute | undefined { const agents = ctx.get('agents') as { get(id: string): { options?: { provider?: unknown; model?: unknown } } | undefined } | undefined const options = agents?.get(sessionId)?.options if (options !== undefined && typeof options.provider === 'string' && options.provider !== '' && typeof options.model === 'string' && options.model !== '') { return { provider: options.provider, model: options.model } } const events = ctx.sessions.get(sessionId)?.snapshotEvents() if (events === undefined) return undefined for (let index = events.length - 1; index >= 0; index--) { const event = events[index] if (event === undefined || event.type !== 'request/header') continue const config = (event.data as { header?: { config?: unknown } } | undefined)?.header?.config if (config === null || typeof config !== 'object') continue const provider = (config as { provider?: unknown }).provider const model = (config as { model?: unknown }).model if (typeof provider === 'string' && provider !== '' && typeof model === 'string' && model !== '') { return { provider, model } } } return undefined } /** * The harness's DEFAULT model route (settings namespace `agent-default-model`): * the route a brand-new conversation would use, so the suggestion still works * on a session that has not sent its first message (no `request/header` yet) * and in a deployment whose LLM adapters advertise no catalog. */ function defaultModelRoute(ctx: Context): CommitModelRoute | undefined { const service = ctx.get('agentDefaultModel') as { currentSelection(): unknown } | undefined return defaultRouteOf(service?.currentSelection()) } /** Output budget of one suggestion: enough for a subject plus a short body, * and (with reasoning pinned to the lowest level) no more. */ const SUGGEST_MAX_TOKENS = 512 /** Hard deadline of one suggestion (the panel shows the model as busy while * it runs, so a stalled provider must not leave it spinning forever). */ const SUGGEST_TIMEOUT_MS = 30_000 /** * The reasoning effort to request for one route: the LOWEST the model * advertises, or undefined when it advertises none. A one-line commit message * needs no deliberation, while a high default (the DeepSeek adapter defaults * to `high` unless the connection says otherwise) both delays the answer and * can consume the whole output budget, yielding an empty message. */ async function commitReasoningEffort( llm: LlmServiceFace, route: CommitModelRoute, ): Promise { if (llm.resolveModelInfo === undefined) return undefined const info = await Promise.resolve(llm.resolveModelInfo(route.provider, route.model)) .catch(() => undefined) return lowestReasoningEffortOf((info as { reasoning?: { efforts?: unknown } } | undefined)?.reasoning?.efforts) } /** The LLM service surface this route uses (all optional: the service is a * harness surface the plugin deliberately does not depend on). */ interface LlmServiceFace { stream(options: GenerateOptions): AsyncIterable resolveModelInfo?(provider: string, model: string): Promise } /** * One generation stream through the harness LLM service. The service is not * injected (the plugin must not require it), so it is read through `ctx.get` * and checked: a deployment without the LLM surface gets a clean 503 instead * of a TypeError. Chunks are assembled with the harness's own BlockAssembler * — the same chunk-to-message algorithm the agent loop uses. */ async function streamCommitMessage( ctx: Context, route: CommitModelRoute, system: string, user: string, ): Promise { const llm = ctx.get('llm') as LlmServiceFace | undefined if (llm === undefined) { throw new SidebarError('git-suggest-error', 'the harness LLM service is unavailable', 503) } // Reasoning capability is read from the model itself: requesting an effort // a non-reasoning model does not support is rejected by the harness // (UNSUPPORTED_REASONING_EFFORT), so the field is omitted in that case. const effort = await commitReasoningEffort(llm, route) const assembler = new BlockAssembler() try { for await (const chunk of llm.stream({ provider: route.provider, model: route.model, messages: [createUserMessage({ content: [{ type: 'text', text: user }], // The plugin's producer-owned source kind (0.1.7 removed the shared // `plugin` catch-all): see SIDE_INJECTION_SOURCE_KIND. source: { kind: 'plugin:dsh-better-sidebar' }, })], system, maxTokens: SUGGEST_MAX_TOKENS, signal: AbortSignal.timeout(SUGGEST_TIMEOUT_MS), ...(effort === undefined ? {} : { reasoningEffort: effort as GenerateOptions['reasoningEffort'] }), })) { assembler.push(chunk) } } catch (error) { if (error instanceof Error && error.name === 'AbortError') { throw new SidebarError( 'git-suggest-error', `the model did not answer within ${Math.round(SUGGEST_TIMEOUT_MS / 1000)}s`, 504, ) } throw error } const message = cleanSuggestion(assembler.blocks() .map(block => (block.type === 'text' ? block.text : '')) .join('')) if (message === '') { // The finish reason separates "the model stopped without text" (often a // reasoning model that spent its budget thinking) from a transport // failure, so the panel's error line stays actionable. const finish = (assembler.finish as { kind?: unknown } | undefined)?.kind throw new SidebarError( 'git-suggest-error', `the model returned an empty message (finish=${typeof finish === 'string' ? finish : 'unknown'})`, 500, ) } return message } /** * Resolve a path a git status/diff ROW carried: the changes tree's rows and * every action they offer (the inline diff preview, and the destructive * discard). Git prints those paths RELATIVE TO THE REPO TOP LEVEL, which may * sit above the session cwd, and the client forwards them verbatim — so a * relative name ALWAYS joins the repository root. Joining the session cwd * first instead hit a same-named file in the subdirectory the session sits * in (#765: `git.discard` on the row `README.md` restored the `pkg/README.md` * one level down and left the root `README.md` — the file the row names — * dirty). Absolute paths pass through; a cwd outside any repository falls * back to itself, where the git command fails exactly as it did before. */ async function resolveStatusPath(cwd: string, raw: string, selected?: string): Promise { if (isAbsolute(raw)) return requireAbsolute(resolveSessionPath(cwd, raw)) const root = await git.repoRoot(cwd, selected).catch(() => cwd) return requireAbsolute(join(root, raw)) } /** How many leading bytes a binary read returns for client-side detect sniffing. */ const READ_HEAD_LIMIT = 4096 /** Text read of a file with the size cap; text encoding is detected before * the NUL-based binary fallback so UTF-16/UTF-32 text remains editable. * Binary reads also return the first {@link READ_HEAD_LIMIT} bytes (base64) * so the client can re-match viewers by content (`detect`). */ async function readText(path: string, readLimit: number): Promise<{ content: string truncated: boolean binary: boolean size: number /** Last-modified time (ms) — the save route's conflict baseline. */ mtimeMs: number head?: string }> { const info = await stat(path).catch((error: unknown) => { throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400) }) if (info.isDirectory()) { throw new SidebarError('fs-error', `"${path}" is a directory`, 400) } const size = info.size const truncated = size > readLimit const handle = await open(path, 'r').catch((error: unknown) => { throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400) }) try { const buffer = Buffer.alloc(Math.min(size, readLimit)) const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0) const slice = buffer.subarray(0, bytesRead) const decoded = decodeTextBytes(slice, truncated) const binary = decoded === null const head = binary ? slice.subarray(0, Math.min(slice.length, READ_HEAD_LIMIT)).toString('base64') : undefined return { content: decoded?.content ?? '', truncated, binary, size, mtimeMs: info.mtimeMs, head, } } finally { await handle.close() } } /** One API method dispatch table entry. */ type ApiMethod = (payload: unknown) => Promise | unknown /** * The live face of the side card settings namespace, bound to the settings * service when it is mounted. The DSH settings RPC domain only serves * allowlisted namespaces (api-proxy exposedNamespaces), so the client reads * and writes THIS namespace through the plugin's own fenced /sidebar routes, * which call the seam in-process — no configuration-client gate involved. */ export interface SidebarSettingsFace { /** The current resolved value + revision (undefined while the settings service is absent). */ get(): { value?: unknown; revision?: number } /** * Whether the dsh-web-ui family's aionui-panel has been selected as the * right-panel provider (the `aionui-panel` settings namespace resolves * `rightPanel: 'aionui-panel'`). While true the sidebar must not mount — * the two right panels are mutually exclusive. False when the namespace is * absent (no aionui installed) or the provider is anything else. */ externalDisable(): boolean /** Merge a patch (revision-guarded) and return the fresh resolved view. */ update(patch: Record, expectedRevision?: number): Promise<{ value?: unknown; revision?: number }> } function buildApi( ctx: Context, resolved: ResolvedSidebarConfig, getSettings: () => SidebarSettingsFace | undefined, assistantLive: AssistantLiveBuffer, archiveTasks: ArchiveTasks, ): Record { const cwdOf = async (payload: unknown): Promise<{ sessionId: string; cwd: string }> => { const sessionId = requireString(payload, 'sessionId') const record = payload as { cwd?: unknown } | null const clientCwd = typeof record?.cwd === 'string' && record.cwd !== '' ? record.cwd : undefined return { sessionId, cwd: await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, clientCwd)) } } /** Resolve the optional Git-panel checkout selector against the selected * session repository. Unlike `cwd`, `worktree` is never trusted directly. */ const gitCwdOf = async (payload: unknown): Promise<{ sessionId: string; cwd: string }> => { const base = await cwdOf(payload) const record = payload as { worktree?: unknown } | null const requested = typeof record?.worktree === 'string' && record.worktree !== '' ? record.worktree : undefined if (requested === undefined) return base // A container workspace is not itself a repository. Validate the checkout // against the selected child (or the default discovered repository), just // as the inventory does, before accepting the requested worktree path. const root = await git.repoRoot(base.cwd, selectedRepoOf(payload)) return { sessionId: base.sessionId, cwd: await git.resolveWorktree(root, requested) } } // Subagent live previews: one batch request instead of N per-child // `subagents.history` calls. The route degrades to a 503 when the host // subagent runtime is absent (the page has no topology to show anyway). const subagentLiveApi: SidebarSubagentLiveRoutes = buildSubagentLiveApi(ctx) // Workflow runs: no service registry exists in DSH (runs are // holder-owned), so the route folds the `tool-workflow/*` session events // the tool's recorder appends — the same four types the official panel // folds in the browser. A deployment that never runs workflows simply // returns an empty list (absence is normal, never an error). const workflowsApi: SidebarWorkflowRoutes = buildWorkflowsApi(ctx) // Agent Teams (experimental layer): the routes degrade structurally — // service absent → `{available:false}` and the client hides the block; // the tree root leading no team → `{team:null}`. Mutations ride the // service's own CAS result union (conflicts stay distinct). const teamsApi: SidebarTeamsRoutes = buildTeamsApi(ctx) return { 'session.phase': async (payload) => { const sessionId = requireString(payload, 'sessionId') const session = ctx.sessions.get(sessionId) if (session === undefined) return { blank: false } // 与宿主会话列表投影同一规则:日志里没有 user/assistant message 即 blank —— // blank 会话里宿主不渲染会话头,插件挂在 header.utilities 的入口随之不可达, // 客户端据该字段把入口补到右上角(issue #698 / #623)。 const blank = !session .snapshotEvents() .some((event) => event.type === 'user/message' || event.type === 'assistant/message') return { blank } }, 'session.cwd': async (payload) => { const { sessionId, cwd } = await cwdOf(payload) return { sessionId, cwd, root: rootLabel(cwd), parent: parentOf(cwd) ?? null } }, 'fs.tree': async (payload) => { const { cwd } = await cwdOf(payload) const record = payload as { path?: unknown; exclude?: unknown } const target = record.path === undefined ? cwd : await ensureWorkspacePath(cwd, requireString(payload, 'path')) // The client's explorerExclude pref rides the request (compiled here so // the listing and the singleton fold probe share one matcher). const exclude = compileExcludePatterns(record.exclude, cwd) return listDirectory(target, resolved.listLimit, exclude) }, // Batch listing: one request for every level the tree has expanded, so a // mount/refresh costs one round trip instead of N. Each path rides the // SAME resolution + cache as `fs.tree` (so a level listed here is warm for // the single-path route and vice versa), and one failing level is reported // in place — the other levels still render. 'fs.trees': async (payload) => { const { cwd } = await cwdOf(payload) const record = payload as { paths?: unknown; exclude?: unknown } | null const paths = Array.isArray(record?.paths) ? record.paths.filter((value): value is string => typeof value === 'string' && value !== '') : [] if (paths.length === 0) throw new SidebarError('bad-request', 'paths must be a non-empty array') if (paths.length > FS_TREES_MAX_PATHS) { throw new SidebarError('bad-request', `too many paths (max ${FS_TREES_MAX_PATHS})`) } // The file tree's REAL entry (a mount/expand costs one POST): the // explorerExclude pref has to be compiled here too, or the exclude list // would simply not reach the only surface the explorer reads. const exclude = compileExcludePatterns(record?.exclude, cwd) const levels = await Promise.all(paths.map(async (raw): Promise => { // A session-relative path is accepted here (the tree already carries // cwd-relative paths); `fs.tree` itself keeps requiring absolute // input. A `~` target is home-relative (#713) and must reach the // shared resolver UNJOINED — pasting it after the cwd would hide the // marker from the home expansion. const homeRelative = raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\') const requested = isAbsolute(raw) || homeRelative ? raw : `${cwd}${sep}${raw}` try { return await listDirectory(await ensureWorkspacePath(cwd, requested), resolved.listLimit, exclude) } catch (error) { // Per-level failure: the batch itself stays a success (one unreadable // directory must not blank the whole tree). return { path: requested, entries: [], truncated: false, error: messageOf(error) } } })) return { levels } }, 'fs.search': async (payload) => { // The editor side panel's global search. Name queries stay rooted at // the session cwd (not caller-targetable — the walk is unbounded by // design), budgeted inside searchFiles. A query carrying a path // separator can never match a NAME, so searchFiles routes it // differently: an absolute query stats its target (the same // any-host-path reach fs.read has had since the workspace fence came // off) and a relative fragment matches by path. const { cwd } = await cwdOf(payload) const record = payload as { exclude?: unknown } const query = requireString(payload, 'query') return searchFiles(cwd, query, { exclude: compileExcludePatterns(record.exclude, cwd) }) }, 'fs.read': async (payload) => { const { cwd } = await cwdOf(payload) // Relative paths are git-derived (status/diff report repo-root-relative // names; the untracked diff view reads the file through this route). A // child-repo path is relative to the selected repoRoot, not the session // cwd; thread it so the path resolves inside the authorized workspace. const selected = selectedRepoOf(payload) const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), selected)) const { content, truncated, binary, size, mtimeMs, head } = await readText(path, resolved.readLimit) if (binary) return { kind: 'binary', size, truncated, mtimeMs, head } return { kind: 'text', content, truncated, mtimeMs } }, 'fs.write': async (payload) => { const { cwd } = await cwdOf(payload) const path = await ensureWorkspaceWritePath(cwd, requireString(payload, 'path')) const content = requireString(payload, 'content') // Detect the byte encoding AND the line ending BEFORE the temp write, so // the save round-trips what the file already used: GBK / UTF-16 / BOM'd // UTF-8 stay put, and a CRLF file stays CRLF. The second half matters // because the editor transports an LF document (CodeMirror has no other // line model), so writing it verbatim turns one edited line into a // whole-file diff for every Windows checkout (#871). const { encoding, eol } = await fileFormatOf(path) // Optimistic concurrency: the client sends the mtime its draft was based // on; a file that changed on disk since (the model wrote it, another tab // saved, an external editor touched it) refuses the write instead of // silently clobbering those bytes. Omitted (older callers) = no gate. const record = payload as { expectedMtimeMs?: unknown } | null const expected = typeof record?.expectedMtimeMs === 'number' && Number.isFinite(record.expectedMtimeMs) ? record.expectedMtimeMs : undefined if (expected !== undefined) { const current = await stat(path).then(info => info.mtimeMs).catch(() => undefined) if (current !== undefined && current !== expected) { throw new SidebarError( 'fs-conflict', `"${path}" changed on disk since it was loaded (expected mtime ${expected}, found ${current})`, 409, ) } } // Per-request temp name (same pattern as writeWorkspaceUpload): a // pid-suffixed name is shared by every concurrent save to the same // path, letting two writers interleave into one temp file — and the // failure-path rm could delete the other writer's in-flight temp. const tmp = join(dirname(path), `.${basename(path)}.dsh-sidebar-tmp-${randomUUID()}.tmp`) try { await mkdir(dirname(path), { recursive: true }) await writeFile(tmp, encodeText(restoreEol(content, eol), encoding), { flag: 'wx' }) await rename(tmp, path) } catch (error) { await rm(tmp, { force: true }).catch(() => {}) throw new SidebarError('fs-error', `cannot write "${path}": ${error instanceof Error ? error.message : String(error)}`, 400) } invalidateDirectoryCache(dirname(path)) // The fresh baseline the client adopts after a successful save. const mtimeMs = await stat(path).then(info => info.mtimeMs).catch(() => undefined) return { ok: true, ...(mtimeMs !== undefined ? { mtimeMs } : {}) } }, // The tree row's rename: single-segment name, destination-existence and // workspace-root refusals, link-aware (renames the row, not its target). // fs-operations.ts owns the containment and shape rules. 'fs.rename': async (payload) => { const { cwd } = await cwdOf(payload) return renameWorkspaceEntry({ cwd, path: requireString(payload, 'path'), name: requireString(payload, 'name'), }) }, // The tree's "new folder": one directory inside an existing row, with // the same single-segment/existence rules as rename. 'fs.mkdir': async (payload) => { const { cwd } = await cwdOf(payload) return mkdirWorkspaceEntry({ cwd, path: requireString(payload, 'path'), name: requireString(payload, 'name'), }) }, // The tree's "new file": one EMPTY file inside an existing row. Same // single-segment/existence rules as mkdir, plus the Windows-illegal and // reserved-device-name refusals a file name has to survive (fs-operations.ts // owns both), and a destination that is never truncated. 'fs.createFile': async (payload) => { const { cwd } = await cwdOf(payload) return createWorkspaceFile({ cwd, path: requireString(payload, 'path'), name: requireString(payload, 'name'), }) }, // The tree row's delete (permanent — the host has no trash): recursive // for directories, unlinks a symlink row without touching its target. 'fs.remove': async (payload) => { const { cwd } = await cwdOf(payload) return removeWorkspaceEntry({ cwd, path: requireString(payload, 'path'), }) }, 'git.worktrees': async (payload) => { const { cwd } = await gitCwdOf(payload) const selected = selectedRepoOf(payload) // A workspace container (no repo at cwd) has child repos; the worktree // list belongs to the SELECTED child, not the container. Thread the // validated repoRoot so linked checkouts of a chosen child appear. const base = selected !== undefined ? await git.repoRoot(cwd, selected).catch(() => cwd) : cwd return git.worktrees(base) }, 'git.status': async (payload) => { const { cwd } = await gitCwdOf(payload) return git.status(cwd, selectedRepoOf(payload)) }, 'git.diff': async (payload) => { const { cwd } = await gitCwdOf(payload) const record = payload as { path?: unknown; staged?: unknown } const repoRoot = selectedRepoOf(payload) const path = record.path === undefined ? undefined : await resolveStatusPath(cwd, requireString(payload, 'path'), repoRoot) return { diff: await git.diff(cwd, path, record.staged === true, repoRoot) } }, // The editor's change gutter asks for the WHOLE uncommitted change of one // file (worktree against HEAD, staged and unstaged together) — the two // existing `git.diff` sides would each report only half of a partly // staged file, and the gutter's line numbers are the worktree's. 'git.diff-head': async (payload) => { const { cwd } = await gitCwdOf(payload) const repoRoot = selectedRepoOf(payload) const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot)) return { diff: await git.diffHead(cwd, path, repoRoot) } }, 'git.stage': async (payload) => { const { cwd } = await gitCwdOf(payload) const record = payload as { path?: unknown } const path = record.path === undefined ? undefined : requireString(payload, 'path') await git.stage(cwd, path, selectedRepoOf(payload)) return { ok: true } }, 'git.unstage': async (payload) => { const { cwd } = await gitCwdOf(payload) const record = payload as { path?: unknown } const path = record.path === undefined ? undefined : requireString(payload, 'path') await git.unstage(cwd, path, selectedRepoOf(payload)) return { ok: true } }, 'git.commit': async (payload) => { const { cwd } = await gitCwdOf(payload) const message = requireString(payload, 'message') await git.commit(cwd, message, selectedRepoOf(payload)) return { ok: true } }, // Ship a commit without leaving the panel. Both target the selected // checkout through gitCwdOf/selectedRepoOf like every other git route, and // both report git's own stderr: a missing upstream (push) or a diverged // branch (pull is --ff-only) is the user's to resolve in a terminal. 'git.push': async (payload) => { const { cwd } = await gitCwdOf(payload) await git.push(cwd, selectedRepoOf(payload)) return { ok: true } }, 'git.pull': async (payload) => { const { cwd } = await gitCwdOf(payload) await git.pull(cwd, selectedRepoOf(payload)) return { ok: true } }, 'git.branch': async (payload) => { const { cwd } = await gitCwdOf(payload) return git.branches(cwd, selectedRepoOf(payload)) }, 'git.checkout': async (payload) => { const { cwd } = await gitCwdOf(payload) await git.checkout(cwd, requireString(payload, 'branch'), selectedRepoOf(payload)) return { ok: true } }, 'git.log': async (payload) => { const { cwd } = await gitCwdOf(payload) const record = payload as { count?: unknown; skip?: unknown } const count = typeof record.count === 'number' && Number.isInteger(record.count) && record.count > 0 ? record.count : undefined const skip = typeof record.skip === 'number' && Number.isInteger(record.skip) && record.skip >= 0 ? record.skip : undefined return git.log(cwd, count, skip, selectedRepoOf(payload)) }, 'git.commit-diff': async (payload) => { const { cwd } = await gitCwdOf(payload) return { diff: await git.commitDiff(cwd, requireString(payload, 'hash'), selectedRepoOf(payload)) } }, 'git.discard': async (payload) => { const { cwd } = await gitCwdOf(payload) const repoRoot = selectedRepoOf(payload) await git.discard(cwd, await resolveStatusPath(cwd, requireString(payload, 'path'), repoRoot), repoRoot) return { ok: true } }, 'git.revert': async (payload) => { const { cwd } = await gitCwdOf(payload) await git.revert(cwd, requireString(payload, 'hash'), selectedRepoOf(payload)) return { ok: true } }, 'git.cherry-pick': async (payload) => { const { cwd } = await gitCwdOf(payload) await git.cherryPick(cwd, requireString(payload, 'hash'), selectedRepoOf(payload)) return { ok: true } }, 'git.show': async (payload) => { const { cwd } = await gitCwdOf(payload) const repoRoot = selectedRepoOf(payload) // `git show :` addresses the path inside the revision TREE: // repository-relative, exactly the unified diff's own path form (after // the a// b/ prefix). The absolute filesystem paths resolveGitPath // produces would break the rev:path syntax and fail every read, so the // path passes through as-is — it can only address blobs of this repo's // own revisions, the same surface git.diff/git.log already expose. const path = requireString(payload, 'path') const rev = requireString(payload, 'rev') return { content: await git.show(cwd, rev, path, repoRoot) } }, // The editor's hover blame: ONE line range per request (the tooltip never // prefetches a file) and an empty list for every failure — see git.blame. 'git.blame': async (payload) => { const { cwd } = await gitCwdOf(payload) const repoRoot = selectedRepoOf(payload) const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot)) const startLine = requireLineNumber(payload, 'startLine') const endLine = requireLineNumber(payload, 'endLine') if (endLine < startLine) throw new SidebarError('bad-request', '"endLine" must not precede "startLine"') return { lines: await git.blame(cwd, path, startLine, endLine, repoRoot) } }, // Commit-message suggestion: build a prompt from the pending changes and // stream it through the harness LLM service (`ctx.llm`) — no agent is // spawned, no session event is written, and the sidebar never sees a // credential. The route is the one the user PINNED in the Git card's // settings when set, else the route the conversation itself runs on. // Staged changes win because they are exactly what `git commit` records; // with nothing staged the unstaged diff is used, and a lone untracked set // still yields a file-list-based message. 'git.suggest-message': async (payload) => { const { cwd, sessionId } = await gitCwdOf(payload) const repoRoot = selectedRepoOf(payload) const language = normalizeLanguage((payload as { language?: unknown }).language) // Pinned first, then the conversation's own route, then the harness // default: a session that has not sent its first message has no // `request/header` yet, but the default selection is still usable. const route = pinnedCommitRouteOf(getSettings) ?? conversationModelRoute(ctx, sessionId) ?? defaultModelRoute(ctx) if (route === undefined) { throw new SidebarError('git-suggest-error', 'cannot resolve a model route for this conversation', 503) } const status = await git.status(cwd, repoRoot) const staged = status.entries.filter(entry => entry.xy[0] !== ' ' && entry.xy[0] !== '?') const untracked = status.entries.filter(entry => entry.xy === '??') const unstaged = status.entries.filter(entry => entry.xy !== '??' && entry.xy[1] !== ' ' && entry.xy[1] !== '?') if (staged.length === 0 && unstaged.length === 0 && untracked.length === 0) { throw new SidebarError('git-suggest-empty', 'no pending changes', 400) } const focus = staged.length > 0 ? { diff: await git.diff(cwd, undefined, true, repoRoot), files: staged } : unstaged.length > 0 ? { diff: await git.diff(cwd, undefined, false, repoRoot), files: unstaged } : { diff: '', files: untracked } const prompt = buildCommitPrompt(language, focus.files.map(entry => entry.path), truncateDiff(focus.diff)) const message = await streamCommitMessage(ctx, route, prompt.system, prompt.user) return { message, provider: route.provider, model: route.model } }, // The route the NEXT suggestion would use (pinned → the conversation's own // → the harness default), which the generate button shows in its tooltip. // Deliberately separate from `git.models`: this is one settings read plus // one header scan, with no adapter catalog discovery. 'git.commit-model': (payload) => { const record = (payload ?? {}) as { sessionId?: unknown } const pinned = pinnedCommitRouteOf(getSettings) const sessionId = typeof record.sessionId === 'string' ? record.sessionId : '' const route = pinned ?? (sessionId === '' ? undefined : conversationModelRoute(ctx, sessionId)) ?? defaultModelRoute(ctx) return { ...(route === undefined ? {} : { route }), /** Whether the route above is a PINNED one (the panel may want to * label it differently from the conversation's own model). */ pinned: pinned !== undefined, } }, // The model catalog behind the Git card's pinned-route dropdown: every // registered provider with the models its adapter advertises. Discovery is // advisory and best-effort — a provider whose adapter cannot be asked // (or that advertises nothing) is reported with an empty model list // instead of failing the whole catalog. 'git.models': async (payload) => { const record = (payload ?? {}) as { sessionId?: unknown } const llm = ctx.get('llm') as { listProviders(): unknown listModels(provider: string): Promise } | undefined const providers = llm === undefined ? [] : await Promise.resolve(llm.listProviders()) .then(listed => (Array.isArray(listed) ? listed.slice(0, MODEL_CATALOG_PROVIDER_LIMIT) : [])) .then(entries => Promise.all(entries.map(async (entry: unknown) => { const parsed = providerEntryOf(entry) if (parsed === undefined) return { provider: '', name: '', models: [] } const models = await Promise.resolve(llm.listModels(parsed.provider)) .then(list => (Array.isArray(list) ? list.slice(0, MODEL_CATALOG_MODEL_LIMIT) : [])) .catch(() => []) return { provider: parsed.provider, name: parsed.label, models: models.flatMap((model: unknown) => { const item = modelEntryOf(model) return item === undefined ? [] : [{ id: item.id, name: item.name }] }), } }))) .catch(() => []) // The conversation-derived history: routes this session actually used // (newest first). It is the catalog's stand-in before the harness // advertises anything, and it is how a model the user picked in the // chat becomes pinnable here. const events = typeof record.sessionId === 'string' ? ctx.sessions.get(record.sessionId)?.snapshotEvents() ?? [] : [] return { // Whether the harness exposes an LLM surface at all: an empty // catalog is then "no adapters registered", not "the route failed". llm: llm !== undefined, providers: providers.filter(provider => provider.provider !== ''), recent: collectModelRoutes(events as readonly { type?: unknown; data?: unknown }[]), default: defaultModelRoute(ctx), } }, // The session's file-tool events for the changes tab's session lens // (and its badge): the CLIENT runtime's sessions face has no event-log // access, so the events cross the wire here — live session log first, // the persisted logical log for not-yet-hydrated sessions. Only the // two event types the lens folds are sent, narrowed to `seq > afterSeq` // so polling is a small delta, with the same recent-window cap the // client accumulator applies. 'changes.ops': async (payload) => { const sessionId = requireString(payload, 'sessionId') const rawAfter = (payload as { afterSeq?: unknown } | null)?.afterSeq if (rawAfter !== undefined && (typeof rawAfter !== 'number' || !Number.isSafeInteger(rawAfter) || rawAfter < 0)) { throw new SidebarError('bad-request', 'afterSeq must be a non-negative integer') } // An absent cursor means "from the very first event" — a session whose // log opens on a tool event (subagent seeds do) carries seq 0, which a // literal `> 0` comparison would drop, so the absent case floors at -1. const afterSeq = rawAfter ?? -1 let events: readonly SidebarSessionEvent[] | undefined = ctx.sessions.get(sessionId)?.snapshotEvents() if (events === undefined) { const persistence = ctx.get('sessionPersistence') if (persistence !== undefined) { try { events = (await readPersistedSession(persistence, sessionId)).events } catch { // Cold read unavailable (session never persisted): an empty // window is the honest answer, not a wire error. } } } if (events === undefined) return { events: [], lastSeq: Math.max(afterSeq, 0) } const CHANGES_EVENTS_CAP = 4000 const filtered = events.filter( event => (event.type === 'tool/call' || event.type === 'tool/result') && event.seq > afterSeq, ) const window = filtered.length > CHANGES_EVENTS_CAP ? filtered.slice(filtered.length - CHANGES_EVENTS_CAP) : filtered return { events: window, lastSeq: window.at(-1)?.seq ?? afterSeq } }, // Subagent live previews: one batch request per refresh; the route folds // the newest text/tool activity of every running child in the tree. 'subagents.live': (payload) => subagentLiveApi.live(payload), // Workflow runs of the whole tree (folded from `tool-workflow/*` // session events; empty list when the tree never ran one). 'workflows.list': (payload) => workflowsApi.list(payload), // Agent Teams (experimental): the task board's create/CAS-update // mutations. Reads ride the Lead Session's `agentTeam` projection, so // there is no `teams.view` route (see src/team-routes.ts). 'teams.taskCreate': (payload) => teamsApi.taskCreate(payload), 'teams.taskUpdate': (payload) => teamsApi.taskUpdate(payload), // The side card preferences. The settings service is optional in the // composition; while absent the routes report undefined and the client // keeps the schema defaults. Writes are revision-guarded: a stale editor // is refused with settings-conflict so a concurrent change is never // silently overwritten (mirror of the settings seam's own guard). 'settings.get': () => { const settings = getSettings() return settings === undefined ? { value: undefined, revision: undefined, externalDisable: false } : { ...settings.get(), externalDisable: settings.externalDisable() } }, 'settings.update': async (payload) => { const settings = getSettings() if (settings === undefined) { throw new SidebarError('settings-rejected', 'the settings service is not mounted in this deployment', 503) } const record = payload as { patch?: unknown; expectedRevision?: unknown } | null const patch = record?.patch if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { throw new SidebarError('bad-request', 'patch must be a plain object') } const expectedRevision = typeof record?.expectedRevision === 'number' ? record.expectedRevision : undefined try { return await settings.update(patch as Record, expectedRevision) } catch (error) { if (error instanceof SettingsConflictError) { throw new SidebarError('settings-conflict', error.message, 409) } throw new SidebarError('settings-rejected', error instanceof Error ? error.message : String(error), 400) } }, // External open for the file tree's "open with" menu: reveal a path in // the OS file manager, or hand a custom-scheme URL (vscode://, // cursor://, zed://, custom editors) to its registered handler. The // client is a browser renderer where raw scheme navigation is // unreliable, so the launch always goes through the host — the same // fence as every other route, argv-only (no shell interpolation). 'open.external': (payload) => { const record = payload as { action?: unknown } | null const action = record?.action if (action === 'reveal') return launchExternal('reveal', requireString(payload, 'path')) if (action === 'url') return launchExternal('url', requireString(payload, 'url')) throw new SidebarError('bad-request', 'action must be "reveal" or "url"') }, // Archive builds: collect the selection (fenced + disambiguated) and hand // the zipping to the background task table, so the tree can show progress // through `archive.status` and download the finished bytes from // GET /sidebar/archive?id=. 'archive.build': async (payload) => { const { sessionId, cwd } = await cwdOf(payload) const record = payload as { paths?: unknown; name?: unknown } | null const paths = Array.isArray(record?.paths) ? record.paths.filter((value): value is string => typeof value === 'string' && value !== '') : [] if (paths.length === 0) throw new SidebarError('bad-request', 'paths must be a non-empty array') const name = archiveNameOf(typeof record?.name === 'string' ? record.name : null) const selected: string[] = [] for (const raw of paths) selected.push(await ensureWorkspacePath(cwd, raw)) // Same-basename selections (a/index.ts + b/index.ts) get parent segments // prepended, so no two archive members collide. const entries: ZipEntry[] = [] const names = disambiguateArchiveNames(selected) for (const [index, absolute] of selected.entries()) { await collectZipEntries(absolute, names[index]!, entries) } return archiveTasks.start({ sessionId, name, entries }) }, 'archive.status': (payload) => archiveTasks.status(requireString(payload, 'id'), requireString(payload, 'sessionId')), // Side Chat: create a side-thread child seeded with the parent's full // log up to now, deliver follow-ups (cold-resuming when the thread's // agent is gone), abort a running thread, and release a thread's agent. // Every operation runs through these routes because subagent-origin // identities are fenced from the generic session RPCs (agent-lookup // ownership), and the thread is created with a CUSTOM seed the stock // fork APIs cannot express. ...buildSidechatApi(ctx, assistantLive), } } /** The npm package name of this plugin, exactly as its Loader row declares it. */ const SIDEBAR_PACKAGE_NAME = 'dsh-better-sidebar' /** * Profile entry id of the sibling `dsh-web-ui` right panel this sidebar yields * to when it is the active provider. Kept as a literal: it is that plugin's * own mount choice, not a contract this plugin can derive. */ const AIONUI_PANEL_ENTRY = 'aionui-panel' /** The file-backed settings document DSH 0.1.7 retired. */ const LEGACY_SETTINGS_FILE = 'settings.yaml' /** * The Loader entry id of this plugin's own row. * * DSH 0.1.7 addresses settings forms by profile entry id, and that id is a * mount choice rather than a package property: this bundle's patch uses * `better-sidebar`, while an aggregate bundle mounts the same package under * its own id. The row is therefore identified by the package name plus fiber * identity, with an enabled same-name row as the fallback for the moment * before the fiber is attached. * @param ctx - the plugin's own context. * @returns the row's configured id, or undefined when no row can be identified. */ function ownEntryId(ctx: Context): string | undefined { let fallback: string | undefined try { for (const entry of ctx.loader.entries()) { const id = entry.options.id if (entry.options.name !== SIDEBAR_PACKAGE_NAME || typeof id !== 'string' || id === '') continue if (entry.fiber === ctx.fiber) return id if (entry.disabled !== true && fallback === undefined) fallback = id } } catch { // A loader that does not expose its entries leaves the settings face // absent; the client keeps the schema defaults, which is also what a // deployment without the settings service does. return undefined } return fallback } /** * Read this plugin's preference section out of the retired `settings.yaml`. * * Both names are tried: the settings service renames the document before it * imports any section, so on a host that already booted once only the * `.imported` copy is left, while a host migrated for the first time may still * be mid-import. * @param home - the harness home the retired document lives under. * @returns the section's own fields, or undefined when no usable section exists. */ async function readLegacyPrefs(home: string): Promise | undefined> { const declared = new Set(Object.keys(Config.dict ?? {})) for (const name of [`${LEGACY_SETTINGS_FILE}.imported`, LEGACY_SETTINGS_FILE]) { let text: string try { text = await readFile(join(home, name), 'utf8') } catch { continue } let document: unknown try { document = parseYaml(text) } catch { continue } if (document === null || typeof document !== 'object' || Array.isArray(document)) continue const section = (document as Record)[SIDEBAR_PREFS_NS] if (section === null || typeof section !== 'object' || Array.isArray(section)) continue // Drop fields the current row schema no longer declares (the retired // terminal and browser keys, `defaultWidthPercent`, …). A form write // validates every key against the schema, so one unknown field would // reject the whole patch and lose exactly what this import exists to save. const filtered = Object.fromEntries( Object.entries(section as Record).filter(([key]) => declared.has(key)), ) if (Object.keys(filtered).length > 0) return filtered } return undefined } /** * Why a legacy preference import did or did not happen. * * Every one of these is a normal outcome on some deployment, but a silent * early return is exactly the failure shape this release is full of: an * operator upgrading a host cannot tell "there was nothing to migrate" from * "the import never ran". The caller therefore logs the outcome. */ type LegacyImportOutcome = /** The retired section was found and written into the row. */ | 'imported' /** No `profileContext`, so the home (and the document) cannot be located. */ | 'no-profile-home' /** The settings service exposes no form for this row. */ | 'no-form' /** The row already carries user values; the import must never overwrite them. */ | 'already-configured' /** Neither the live nor the migrated document carries a usable section. */ | 'no-legacy-section' /** The write itself failed; the caller's catch reports it. */ | 'rejected' /** * One-time import of the Side card preferences a pre-0.1.7 release persisted. * * The 0.1.6 line stored them through the file-backed settings provider, in * `$DSH_HOME/settings.yaml` under a `dsh-better-sidebar` section. This release * deletes that provider; its migration renames the document to * `settings.yaml.imported` and re-imports each section into the entry of the * SAME id — and because a section key is the package name while the row id is * a mount choice, DSH warns and leaves this section behind. Without this * import every existing user would silently lose their preferences. * * The import runs only while the row's user layer is still empty, so it can * never overwrite a value set after the upgrade, and re-running it is a no-op. * @param ctx - host plugin context (profile home, logger). * @param settings - the settings forms service. * @param ns - this plugin row's entry id. * @returns which outcome the import reached. */ async function importLegacyPrefs( ctx: Context, settings: SidebarSettingsService, ns: string, ): Promise { const home = ctx.profileContext?.home if (home === undefined) return 'no-profile-home' const row = settings.describe().find(candidate => candidate.ns === ns) if (row === undefined) return 'no-form' const user = row.user if (user !== null && typeof user === 'object' && Object.keys(user).length > 0) return 'already-configured' const section = await readLegacyPrefs(home) if (section === undefined) return 'no-legacy-section' await settings.update(ns, section) return 'imported' } /** * Plugin body: mount the fenced routes and the sidebar_open push socket. * @param ctx - host plugin context (webServer, sessions, webRuntime). * @param config - deployment-provided limits; the Loader validates against * {@link Config} and fills defaults, direct callers get them from * {@link resolveSidebarConfig}. */ export function apply(ctx: Context, config?: SidebarConfig): void { const resolved = resolveSidebarConfig(config) // The web runtime's bind-derived trust list (boot-sampled LAN literals // plus --trusted-host authorities) — the authoritative source the /api // gateway fence derives its list from. Read per request from the live // service value; a replaced list takes effect without a plugin restart. const fence = (req: SidebarHttpRequest): boolean => isTrustedApiRequest(req, ctx.webRuntime.trustedHosts) // The model-facing open-request registry: queues `sidebar_open` requests // per session and pushes them to connected sidebar views over the // `/sidebar/ws/agent-opens` socket. const agentOpenRegistry = new AgentOpenRegistry() // DSH 0.1.7 replaced the registrable settings namespace with a forms // service over the profile's own entries: a form is addressed by the plugin // ROW's Loader entry id, its schema is this module's exported `Config`, and // its value is the live fiber config. The client still reaches the // preferences through the plugin's own fenced routes below // ('settings.get'/'settings.update'), which now call `describe`/`update`. // Deployments without a settings service simply never fill the face and the // client falls back to the schema defaults. let settingsFace: SidebarSettingsFace | undefined // The model-facing `sidebar_open` tool is gated on the side-card setting // `agentOpenTools` (default off): nothing is injected until the user turns // the feature on; turning it off mid-session unregisters the tool. let openToolsDisposers: (() => void) | null = null ctx.inject(['settings'], (sctx) => { // The form is the plugin ROW, so the id is whatever mounted this package: // this bundle's patch uses `better-sidebar`, an aggregate bundle mounts // the same package under its own id. A row the loader cannot identify has // no form, so the face stays absent and the client keeps the defaults. const ns = ownEntryId(ctx) if (ns === undefined) { ctx.logger?.warn?.('dsh-better-sidebar: no loader row for this package; Side card preferences stay at defaults') return } // The plugin ships its own Side card settings section, so the native // auto-form is opted out — otherwise Settings would render the same ~30 // preference fields twice. The policy does not affect reads or writes. ctx.effect( () => sctx.settings.configure({ auto: false }, ctx.fiber), 'dsh-better-sidebar: settings page policy', ) const viewOf = (): { value?: unknown; revision?: number } => { const descriptor = sctx.settings.describe({ redactSecrets: true }).find(candidate => candidate.ns === ns) return descriptor === undefined ? { value: undefined, revision: undefined } : { value: descriptor.value, revision: descriptor.revision } } // Mutual exclusion with the dsh-web-ui family right panel: the aionui // panel's provider choice (`aionui-panel.rightPanel`) is the authority. // While it resolves to 'aionui-panel', this sidebar must not mount. A form // is addressed by its owner's profile entry id, which for that plugin is // the string its pre-0.1.7 section already used; absent row (no aionui // installed) = not disabled. const externalDisable = (): boolean => { const descriptor = sctx.settings.describe({ redactSecrets: true }) .find(candidate => candidate.ns === AIONUI_PANEL_ENTRY) const value = descriptor?.value as { rightPanel?: unknown } | undefined return value?.rightPanel === 'aionui-panel' } // The model-facing open tool is gated on `agentOpenTools` // (default off): nothing is injected until the user turns the feature // on, and turning it off mid-session unregisters the tool and drops the // queued (undelivered) open requests. Already-delivered opens keep their // tabs — the tools' only lever is the queue, not the rendered state. const prefsOf = (): SidebarPrefs => { const value = viewOf().value return value !== null && typeof value === 'object' ? value as SidebarPrefs : SIDEBAR_PREFS_DEFAULTS } const syncOpenToolsGate = (): void => { if (prefsOf().agentOpenTools === true) { if (openToolsDisposers === null) { openToolsDisposers = registerOpenTool( ctx, agentOpenRegistry, (sessionId) => sessionCwdOf(ctx, sessionId), prefsOf, ) } } else if (openToolsDisposers !== null) { openToolsDisposers() openToolsDisposers = null agentOpenRegistry.drainAll() } } settingsFace = { // Two triggers cover what the 0.1.6 namespace watch used to: the // plugin's own writes flow through `update`, and the client re-reads // this face on every `settings/document-updated` push. (The host emits // that event on the settings service's own context, which is not an // ancestor of this plugin's fiber, so a listener here would never run.) get: () => { syncOpenToolsGate(); return viewOf() }, externalDisable, update: async (patch, expectedRevision) => { await sctx.settings.update(ns, patch, expectedRevision) return viewOf() }, } syncOpenToolsGate() // A pre-0.1.7 release persisted these preferences through the file-backed // settings provider, which this release deleted. Import that section once. // // The loader must settle first: `describe()` only lists an entry whose // fiber is ACTIVE, and this callback runs the moment the settings SERVICE // appears — while the loader is still mounting rows, so this plugin's own // row is not in the form list yet and the import would silently find // "no form" and do nothing. Upstream's own settings migration waits the // same way (`ctx.root.loader.await().then(...)`). void Promise.resolve(ctx.loader?.await?.()).then( () => importLegacyPrefs(ctx, sctx.settings, ns), ).then((outcome) => { if (outcome === 'no-profile-home' || outcome === 'no-form') { ctx.logger.warn('dsh-better-sidebar: legacy preference import could not run (%s)', outcome) return } ctx.logger.info('dsh-better-sidebar: legacy preference import: %s', outcome) }).catch((error: unknown) => { ctx.logger.warn('dsh-better-sidebar: legacy preference import was rejected') ctx.logger.warn(error) }) }) // ── JSON API ──────────────────────────────────────────────────────────── // The live assistant stream buffer: DSH 0.1.5 publishes in-flight model // deltas as process-local `agent/assistant-stream` frames instead of the // durable `assistant/chunk` events 0.1.2 logged, so the side-chat // transcript and the inherited in-progress snapshot read them here. The // effect releases the listener on fiber disposal. const assistantLive = createAssistantLiveBuffer(ctx) ctx.effect(() => () => { assistantLive.dispose() }, 'dsh-better-sidebar: live assistant stream buffer') // One archive task table per mount: the `archive.build` / `archive.status` // API methods write it, the GET /sidebar/archive route reads it. const archiveTasks = createArchiveTasks() const api = buildApi(ctx, resolved, () => settingsFace, assistantLive, archiveTasks) ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: '/sidebar/api', handler: async (req, res) => { if (!fence(req)) { writeJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } }) return } if (req.method !== 'POST') { writeJson(res, 405, { ok: false, error: { code: 'method-error', message: 'method not allowed' } }) return } const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname const method = pathname.startsWith('/sidebar/api/') ? pathname.slice('/sidebar/api/'.length) : undefined if (method === undefined || method.includes('/')) { writeError(res, new SidebarError('not-found', 'unknown sidebar API method', 404)) return } try { const payload = await readJsonBody(req) // Own properties only. The dispatch table is an object literal, so a // bare lookup resolved Object.prototype members as "methods": // POST /sidebar/api/constructor answered 200 {}, toString answered // 200 "[object Undefined]", valueOf/hasOwnProperty answered 500. // The typeof guard also rejects a non-function own value. const handler = Object.hasOwn(api, method) ? api[method] : undefined if (typeof handler !== 'function') { throw new SidebarError('not-found', `unknown sidebar API method "${method}"`, 404) } writeOk(res, await handler(payload)) } catch (error) { writeError(res, error) } }, }), 'dsh-better-sidebar: /sidebar/api routes') // ── Raw upload route ─────────────────────────────────────────────────── // One request writes one file without JSON/base64 inflation. Folder uploads // send each file with a relativePath, preserving the selected directory // tree. Bytes stream to a temp sibling and are renamed into place, so a // failed or oversized upload never leaves a partial file (see // fs-operations.ts for the containment and shape rules). ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/sidebar/upload', handler: async (req, res) => { if (!fence(req)) { writeJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } }) return } if (req.method !== 'POST') { writeJson(res, 405, { ok: false, error: { code: 'method-error', message: 'method not allowed' } }) return } try { const url = new URL(req.url ?? '/', 'http://dsh.internal') const sessionId = url.searchParams.get('sessionId') const dir = url.searchParams.get('dir') const relativePath = url.searchParams.get('relativePath') if (sessionId === null || dir === null || relativePath === null || relativePath.trim() === '') { throw new SidebarError('bad-request', 'sessionId, dir, and relativePath are required') } const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)) const { path, size } = await writeWorkspaceUpload({ cwd, dir, relativePath, chunks: req, limit: resolved.uploadLimit, }) writeOk(res, { path, size }) } catch (error) { writeError(res, error) } }, }), 'dsh-better-sidebar: /sidebar/upload route') // ── Lazy chunk route (client bundle splits) ───────────────────────────── // Serves the client half's split bundles (lib/client-.js) so the // heavy preview/terminal libraries load on first use, not at page start // (see bundle-route.ts / src/client/chunk-loader.ts). ctx.effect(() => registerBundleRoute(ctx, fence), 'dsh-better-sidebar: /sidebar/bundle chunk route') // ── Archive routes (zip one selection, watch it build, download it) ───── // The file tree's "zip and download" action is a three-step flow: POST // `archive.build` fences every `path` through the SAME workspace fence as // fs.tree / /sidebar/file, walks the directories (a symlink is skipped, never // followed — no escape and no cycle) and returns an id IMMEDIATELY; the // background build reports progress through `archive.status`; and // GET /sidebar/archive serves the finished bytes once, with the RFC 5987 // disposition. `archiveTasks` owns the concurrency cap and the TTL. ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/sidebar/archive', handler: async (req, res) => { if (!fence(req)) { writeJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } }) return } if (req.method !== 'GET') { writeJson(res, 405, { ok: false, error: { code: 'method-error', message: 'method not allowed' } }) return } try { const url = new URL(req.url ?? '/', 'http://dsh.internal') respondArchiveDownload(archiveTasks, { sessionId: url.searchParams.get('sessionId'), id: url.searchParams.get('id'), }, res) } catch (error) { writeError(res, error) } }, }), 'dsh-better-sidebar: /sidebar/archive route') // ── Media route (images for the editor) ───────────────────────────────── ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: '/sidebar/file', handler: async (req, res) => { if (!fence(req)) { res.writeHead(403) res.end('forbidden') return } if (req.method !== 'GET') { res.writeHead(405) res.end() return } try { const url = new URL(req.url ?? '/', 'http://dsh.internal') const sessionId = url.searchParams.get('sessionId') const raw = url.searchParams.get('path') if (sessionId === null || raw === null) throw new SidebarError('bad-request', 'sessionId and path are required') const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)) // Resolution is the shared contract's alone: relative joins the // session cwd, absolute stays, `~` expands against the home (#713), // remote-mirror namespaces project. Pre-joining here would paste a // `~` target after the cwd and hide it from the resolver. // Resolution is the shared contract's alone: relative joins the // session cwd, absolute stays, `~` expands against the home (#713), // remote-mirror namespaces project. Pre-joining here would paste a // `~` target after the cwd and hide it from the resolver. const path = await ensureWorkspacePath(cwd, raw) const info = await stat(path) if (!info.isFile() || info.size > resolved.mediaLimit) { throw new SidebarError('fs-error', 'not a file or too large', 400) } const type = mediaTypeForPath(path) const body = await readFile(path) // Raw bytes either way (binary-safe); ?download=1 switches the // disposition so the browser saves the file instead of showing it. const headers: Record = { 'content-type': type, 'cache-control': 'no-cache' } // An SVG is a scriptable DOCUMENT, not an inert image: navigating to // this URL directly would run its