Raise the whole baseline to the alpha line and stop carrying code that only exists for older hosts (no runtime compatibility layer, per AGENTS §4): - peers/engines: 14 DSH peers and engines.dsh -> 0.2.3-alpha.2, Cordis -> 4.2.0-alpha.1, group/include 1.2.0-alpha.1, schemastery 3.20.0-alpha.1; dev pins and CI/e2e/install scripts move with them; plugin version 0.34.0-alpha.0. - admission: DSH 0.2.3 deleted `requestRejection`, so only the injected `connection.authentication` provider can call `admit`; the legacy branch and the direct-admit fallback are gone and the fence fails loudly. - directory events: the projection authority is `workspace-root/change`; the side-chat cwd stamp emits it and the worktree scan no longer reads the retired `working-directory/change`. - llm types: `@deepseek-ai/dsh-llm` no longer exports `./brand`, so MessageId comes from `./types`. - client anchors: only `[data-slot="main.conversation"]`; the alpha.1 `conversation` key is retired. `webServer.getOrigin` is called directly. Gates: peers check, typecheck, lint, test (366 files / 4615 passed), build, check:consumer-types.
2095 lines
103 KiB
TypeScript
2095 lines
103 KiB
TypeScript
/**
|
||
* 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 WebSocket upgrades. Every route delegates admission to the same
|
||
* public Connection service as the /api gateway (Host/Origin and browser
|
||
* authentication), read per request.
|
||
*
|
||
* All operations are conversation-scoped: requests carry a sessionId and the
|
||
* session's authoritative cwd comes from the session store.
|
||
*/
|
||
import { readFile, stat } from 'node:fs/promises'
|
||
import { basename, extname, isAbsolute, join, sep } from 'node:path'
|
||
import type { Stats } from 'node:fs'
|
||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||
import type { Duplex } from 'node:stream'
|
||
import { WebSocket, WebSocketServer } from 'ws'
|
||
import { parse as parseYaml } from 'yaml'
|
||
import type { Context, SidebarHttpRequest, SidebarSettingsService } from './context-types.ts'
|
||
import {
|
||
Config,
|
||
resolveSidebarConfig,
|
||
SIDEBAR_PREFS_DEFAULTS,
|
||
SIDEBAR_PREFS_NS,
|
||
type ResolvedSidebarConfig,
|
||
type SidebarConfig,
|
||
type SidebarPrefs,
|
||
} from './config.ts'
|
||
import { createProbeGate, listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts'
|
||
import { resolveSessionPath } from './session-path.ts'
|
||
import { createWorkspaceFile, mkdirWorkspaceEntry, renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceText, writeWorkspaceUpload } from './fs-operations.ts'
|
||
import { resolveTarget } from './path-security.ts'
|
||
import { searchFiles } from './fs-search.ts'
|
||
import { compileExcludePatterns } from './exclude-patterns.ts'
|
||
import { decodeHtmlUrl } from './html-route.ts'
|
||
import { registerBundleRoute } from './bundle-route.ts'
|
||
import { createDirectoryWatchers, type DirectoryWatchers } from './fs-watch.ts'
|
||
import { createSidechatPushHub } from './sidechat-push.ts'
|
||
import { createSelectionTranslationHandler } from './selection-translation.ts'
|
||
import { parentModelSelection, type SidechatLogEvent } from './sidechat-core.ts'
|
||
import { launchExternal } from './open-external.ts'
|
||
import { createArchiveTasks, respondArchiveDownload, type ArchiveTasks } from './archive-route.ts'
|
||
import * as git from './git.ts'
|
||
import { gitGraph, gitHistory, type GitGraphOptions, type GitHistoryOptions } from './git-graph.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 { readSidechatImage } from './sidechat-routes.ts'
|
||
import { SIDECHAT_METADATA_BYTES, sidechatPromptBodyLimit } from './sidechat-image-admission.ts'
|
||
import { MAX_CLUE_SAVE_BODY_BYTES, readJsonBody, readTextBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts'
|
||
import { byteRangeOf, streamFileToResponse } from './file-stream.ts'
|
||
import { fileReadError } from './fs-read-error.ts'
|
||
import { createChangesOpsApi } from './changes-ops.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 { WRITE_BODY_GUARD_BYTES } from './editor-limits.ts'
|
||
import { installClueStack } from './clues/install-stack.ts'
|
||
import { installClueAgentRead } from './clues/agent-read.ts'
|
||
import { installClueActions } from './clues/install-actions.ts'
|
||
import { createClueSessionDelivery } from './clues/session-delivery.ts'
|
||
import { ClueError } from './clues/error.ts'
|
||
import { readPage, readText } from './fs-read.ts'
|
||
|
||
export { Config }
|
||
// Re-exported for consumers that referenced the read shape from the package root.
|
||
export type { SidebarReadResult } from './fs-read.ts'
|
||
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,
|
||
SidechatSurface,
|
||
SidechatSurfaceAdapter,
|
||
TabDescriptor,
|
||
TabComponentProps,
|
||
FileViewerDescriptor,
|
||
FileViewerProps,
|
||
FileFetchStrategy,
|
||
} from './client/service.ts'
|
||
// The archive disposition helper is exercised directly by the archive specs:
|
||
// the RFC 5987 header shape is its own contract, testable without a mount.
|
||
export { contentDispositionOf } 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: routes, sessions, native request admission, and tools. */
|
||
export const inject = ['webServer', 'sessions', 'connection', 'tools']
|
||
|
||
/** Content types for media files and HTML preview resources, by extension. */
|
||
const MEDIA_TYPES: Record<string, string> = {
|
||
'.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',
|
||
'.css': 'text/css',
|
||
'.js': 'text/javascript',
|
||
'.mjs': 'text/javascript',
|
||
'.json': 'application/json',
|
||
'.woff': 'font/woff',
|
||
'.woff2': 'font/woff2',
|
||
'.ttf': 'font/ttf',
|
||
'.otf': 'font/otf',
|
||
'.wasm': 'application/wasm',
|
||
// Media containers: `<video>` / `<audio>` pick their demuxer from this
|
||
// header, so a media file answered as octet-stream is a coin flip even when
|
||
// the browser can decode it. `.ogg` is audio on purpose — a Theora video in
|
||
// Ogg is vanishingly rare next to Vorbis/Opus audio.
|
||
'.mp4': 'video/mp4',
|
||
'.m4v': 'video/mp4',
|
||
'.webm': 'video/webm',
|
||
'.ogv': 'video/ogg',
|
||
'.mov': 'video/quicktime',
|
||
'.mp3': 'audio/mpeg',
|
||
'.m4a': 'audio/mp4',
|
||
'.aac': 'audio/aac',
|
||
'.wav': 'audio/wav',
|
||
'.flac': 'audio/flac',
|
||
'.ogg': 'audio/ogg',
|
||
'.oga': 'audio/ogg',
|
||
'.opus': 'audio/ogg',
|
||
}
|
||
|
||
/** Content type served by /sidebar/file and /sidebar/html; unknowns use a binary-safe fallback. */
|
||
export function mediaTypeForPath(path: string): string {
|
||
return MEDIA_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream'
|
||
}
|
||
|
||
/**
|
||
* Stored header cwd per session id, kept for the process lifetime.
|
||
*
|
||
* A session header is immutable, so once read the workspace address cannot
|
||
* change. The map is bounded and every entry is a short string; it exists so
|
||
* the sidebar's re-asks (every watch frame, every 5 s poll, every route) do
|
||
* not even pay the header read.
|
||
*/
|
||
const storedCwdCache = new Map<string, string>()
|
||
/** Per-session in-flight header read (the same-key sharing for a cold burst). */
|
||
const storedCwdInFlight = new Map<string, Promise<string | undefined>>()
|
||
/** Bound on {@link storedCwdCache}; well above any plausible open-session set. */
|
||
const STORED_CWD_CACHE_MAX = 256
|
||
|
||
/**
|
||
* The workspace address of a session the host has not attached: the cwd stored
|
||
* in its immutable header.
|
||
*
|
||
* This is a HEADER-ONLY read (`sessionPersistence.stat` reads the first zstd
|
||
* frame, never the log). It is deliberately not `sessionQuery.observeSession`:
|
||
* that public cold-cwd API decodes the WHOLE artifact and hydrates every
|
||
* projection to answer with one string, and a startup burst asks dozens of
|
||
* times in parallel (0.28.0: 39 MB × 44 ≈ 1.7 GB, OOM). The committed
|
||
* working_directory is adopted again the moment the host attaches the session
|
||
* (see {@link sessionCwdOf}).
|
||
* @param ctx - host plugin context.
|
||
* @param sessionId - the detached session to locate.
|
||
* @returns the stored header cwd, or undefined when the host cannot answer.
|
||
*/
|
||
async function storedHeaderCwdOf(ctx: Context, sessionId: string): Promise<string | undefined> {
|
||
const cached = storedCwdCache.get(sessionId)
|
||
if (cached !== undefined) return cached
|
||
const pending = storedCwdInFlight.get(sessionId)
|
||
if (pending !== undefined) return pending
|
||
const promise = (async (): Promise<string | undefined> => {
|
||
const persistence = ctx.get('sessionPersistence')
|
||
if (persistence?.stat === undefined) return undefined
|
||
try {
|
||
const snapshot = await persistence.stat(sessionId)
|
||
const cwd = snapshot?.header.cwd
|
||
if (cwd === undefined || cwd === '') return undefined
|
||
storedCwdCache.set(sessionId, cwd)
|
||
while (storedCwdCache.size > STORED_CWD_CACHE_MAX) {
|
||
const oldest = storedCwdCache.keys().next()
|
||
if (oldest.done) break
|
||
storedCwdCache.delete(oldest.value)
|
||
}
|
||
return cwd
|
||
} catch (error) {
|
||
// A header read that fails must not take a whole route down: the client
|
||
// hint below is the same workspace address in every normal deployment.
|
||
ctx.logger.warn('dsh-better-sidebar: cannot stat stored session %s', sessionId)
|
||
ctx.logger.warn(error)
|
||
return undefined
|
||
}
|
||
})()
|
||
storedCwdInFlight.set(sessionId, promise)
|
||
try {
|
||
return await promise
|
||
} finally {
|
||
storedCwdInFlight.delete(sessionId)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Resolve the directory a session's file/Git routes are rooted at.
|
||
*
|
||
* An attached session answers from the host's committed working directory
|
||
* (following `cd` and linked worktrees), synchronously. A DETACHED session
|
||
* answers from its stored header — the workspace address — because the only
|
||
* public cold-cwd API decodes the whole log for that one string (see
|
||
* {@link storedHeaderCwdOf}); the committed directory takes over again on the
|
||
* next ask after the host attaches the session.
|
||
* @param ctx - host plugin context.
|
||
* @param sessionId - the session whose workspace is resolved.
|
||
* @param clientCwd - the client's summary cwd, used only when the host cannot
|
||
* answer at all.
|
||
* @returns the absolute workspace directory.
|
||
*/
|
||
async function sessionCwdOf(ctx: Context, sessionId: string, clientCwd?: string): Promise<string> {
|
||
const session = ctx.sessions.get(sessionId)
|
||
// The immutable header here is the fallback, not the authority: the host's
|
||
// committed value tracks `cd` and wins whenever it is available.
|
||
if (session !== undefined) {
|
||
const cwd = ctx.get('workingDirectory')?.get(session) ?? session.header.cwd
|
||
if (cwd !== undefined && cwd !== '') return cwd
|
||
}
|
||
const stored = await storedHeaderCwdOf(ctx, sessionId)
|
||
if (stored !== undefined) {
|
||
// A corrupt relative cwd must be refused here: resolving it against the
|
||
// host process cwd is exactly the "outside workspace" misclassification
|
||
// the header read exists to avoid.
|
||
try {
|
||
return requireAbsolute(stored)
|
||
} catch {
|
||
throw new SidebarError('bad-request', `invalid working directory "${stored}"`)
|
||
}
|
||
}
|
||
const defaultDirectory = ctx.get('workingDirectory')?.defaultDirectory
|
||
if (defaultDirectory !== undefined && defaultDirectory !== '') return requireAbsolute(defaultDirectory)
|
||
if (clientCwd !== undefined && clientCwd !== '') {
|
||
try {
|
||
return requireAbsolute(clientCwd)
|
||
} catch {
|
||
throw new SidebarError('bad-request', `invalid working directory "${clientCwd}"`)
|
||
}
|
||
}
|
||
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<string, unknown> | 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 path a GIT surface carried (git.blame, git.diff-head): the
|
||
* session-relative interpretation wins when it names an existing path, with
|
||
* the repository root as the fallback — git's own paths are repo-root
|
||
* relative, so the root is a real fallback here, never a silent one for a
|
||
* missing session file. File links do NOT come through here: `fs.read` and
|
||
* `fs.readPage` resolve from the session cwd only, missing is missing.
|
||
*/
|
||
async function resolveGitPath(cwd: string, raw: string, selected?: string): Promise<string> {
|
||
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<string, unknown>).git
|
||
if (blob === null || typeof blob !== 'object') return undefined
|
||
return parseModelRoute((blob as Record<string, unknown>)[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()
|
||
// The newest route, through the same `request/header` reader the picker's
|
||
// candidate list uses — the shape is parsed in exactly one place.
|
||
return events === undefined ? undefined : collectModelRoutes(events, 1)[0]
|
||
}
|
||
|
||
/**
|
||
* 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<string | undefined> {
|
||
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<StreamChunk>
|
||
resolveModelInfo?(provider: string, model: string): Promise<unknown>
|
||
}
|
||
|
||
/**
|
||
* 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<string> {
|
||
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<string> {
|
||
if (isAbsolute(raw)) return requireAbsolute(resolveSessionPath(cwd, raw))
|
||
const root = await git.repoRoot(cwd, selected).catch(() => cwd)
|
||
return requireAbsolute(join(root, raw))
|
||
}
|
||
|
||
/**
|
||
* `stat` one path for a raw byte route, turning an unreadable path into the
|
||
* route's own error shape.
|
||
*
|
||
* A bare `stat` rejection escaped as a 500 "internal", which reads as a plugin
|
||
* fault; a file the user asked for that does not exist (or cannot be read) is
|
||
* a 400 with a usable message. The streaming helper opens the file BEFORE
|
||
* committing the response for the same reason — the error has to stay
|
||
* deliverable.
|
||
*/
|
||
async function statFileForRoute(path: string): Promise<Stats> {
|
||
return await stat(path).catch((error: unknown) => {
|
||
throw fileReadError(path, error)
|
||
})
|
||
}
|
||
|
||
/** One API method dispatch table entry. */
|
||
type ApiMethod = (payload: unknown, signal?: AbortSignal) => Promise<unknown> | 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<string, unknown>, expectedRevision?: number): Promise<{ value?: unknown; revision?: number }>
|
||
}
|
||
|
||
function buildApi(
|
||
ctx: Context,
|
||
resolved: ResolvedSidebarConfig,
|
||
getSettings: () => SidebarSettingsFace | undefined,
|
||
assistantLive: AssistantLiveBuffer,
|
||
archiveTasks: ArchiveTasks,
|
||
sidechatSignal: AbortSignal,
|
||
): Record<string, ApiMethod> {
|
||
/**
|
||
* Same-key sharing for the shared cwd path. Every file/Git route below
|
||
* resolves the session cwd through here, and a session switch fires them at
|
||
* once. Cold resolution is now a header-only read (see `storedHeaderCwdOf`),
|
||
* but the whole resolution still folds the active-worktree scan, so sharing
|
||
* one leader keeps a burst from repeating that too. Concurrent asks for the
|
||
* same session + client hint share ONE resolution; the hint is part of the
|
||
* key because it is a fallback the result depends on. No TTL: the stored
|
||
* header is memoized, and a live session's committed directory is re-read on
|
||
* every ask after this short-lived entry is dropped.
|
||
*/
|
||
const cwdInFlight = new Map<string, Promise<{ sessionId: string; cwd: string }>>()
|
||
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
|
||
const key = `${sessionId}\u0000${clientCwd ?? ''}`
|
||
const pending = cwdInFlight.get(key)
|
||
if (pending !== undefined) return pending
|
||
const resolved = (async (): Promise<{ sessionId: string; cwd: string }> => ({
|
||
sessionId,
|
||
cwd: await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, clientCwd)),
|
||
}))()
|
||
cwdInFlight.set(key, resolved)
|
||
try {
|
||
return await resolved
|
||
} finally {
|
||
cwdInFlight.delete(key)
|
||
}
|
||
}
|
||
/** 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)
|
||
const changesOps = createChangesOpsApi(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 : resolveTarget(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)
|
||
// One request-wide probe gate, exactly like the batch route below: a
|
||
// single-level listing bounds its own probe pools anyway (the shared
|
||
// budget equals them on purpose — see PROBE_BUDGET), but building one
|
||
// here keeps the two listing routes the same shape, so neither can ever
|
||
// fan out per row without a budget.
|
||
return listDirectory(target, resolved.listLimit, exclude, createProbeGate())
|
||
},
|
||
// 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)
|
||
// ONE probe budget for the whole request: every level keeps its own
|
||
// per-level probe bound, but a batch of up to FS_TREES_MAX_PATHS levels
|
||
// shares one gate, so the bounds do not multiply (64 × 32 opendirs on a
|
||
// cold mount of a wide tree). Cache hits never touch the gate.
|
||
const gate = createProbeGate()
|
||
const levels = await Promise.all(paths.map(async (raw): Promise<SidebarFsLevel> => {
|
||
// 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(resolveTarget(cwd, requested), resolved.listLimit, exclude, gate)
|
||
} 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)
|
||
// File links are session-relative. Git callers must provide an absolute
|
||
// path or explicitly select a repository; missing files never change base.
|
||
const selected = selectedRepoOf(payload)
|
||
const base = selected === undefined ? cwd : await git.repoRoot(cwd, selected)
|
||
const path = resolveTarget(base, requireString(payload, 'path'))
|
||
return await readText(path)
|
||
},
|
||
// One byte window of a large text file, for the read-only paged preview.
|
||
// The window is line-aligned by the host, so the client can treat each
|
||
// response as whole lines (and, for a `.jsonl`, whole records) without
|
||
// having to re-split anything.
|
||
'fs.readPage': async (payload) => {
|
||
const { cwd } = await cwdOf(payload)
|
||
const selected = selectedRepoOf(payload)
|
||
const base = selected === undefined ? cwd : await git.repoRoot(cwd, selected)
|
||
const path = resolveTarget(base, requireString(payload, 'path'))
|
||
const record = payload as { offset?: unknown } | null
|
||
const offset = typeof record?.offset === 'number' && Number.isFinite(record.offset) && record.offset >= 0
|
||
? Math.floor(record.offset)
|
||
: 0
|
||
return await readPage(path, offset)
|
||
},
|
||
// 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 = resolveTarget(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.graph': async (payload) => {
|
||
const { cwd } = await gitCwdOf(payload)
|
||
try {
|
||
return await gitGraph(cwd, payload as GitGraphOptions, selectedRepoOf(payload))
|
||
} catch (error) {
|
||
// The shared Git mapper collapses legacy command codes. Preserve the
|
||
// graph cursor's refresh signal rather than reporting a generic error.
|
||
if (error instanceof git.GitCommandError && (error.code === 'graph-stale' || error.code === 'graph-limit' || error.code === 'bad-request')) {
|
||
throw new SidebarError(error.code, error.message, error.code === 'graph-stale' ? 409 : 400)
|
||
}
|
||
throw error
|
||
}
|
||
},
|
||
'git.history': async (payload) => {
|
||
const { cwd } = await gitCwdOf(payload)
|
||
try { return await gitHistory(cwd, payload as GitHistoryOptions, selectedRepoOf(payload)) }
|
||
catch (error) {
|
||
if (error instanceof git.GitCommandError && (error.code === 'graph-stale' || error.code === 'graph-limit' || error.code === 'bad-request')) {
|
||
throw new SidebarError(error.code, error.message, error.code === 'graph-stale' ? 409 : 400)
|
||
}
|
||
throw error
|
||
}
|
||
},
|
||
'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 <rev>:<path>` 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 = resolveTarget(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) }
|
||
},
|
||
'selection.translate': async (payload, signal) => {
|
||
const llm = ctx.get('llm') as LlmServiceFace | undefined
|
||
if (llm === undefined) throw new SidebarError('selection-error', 'the harness LLM service is unavailable', 503)
|
||
return createSelectionTranslationHandler({ llm, resolveModel: sessionId => {
|
||
const events = ctx.sessions.get(sessionId)?.snapshotEvents()
|
||
const selected = events === undefined ? undefined : parentModelSelection(events as unknown as readonly SidechatLogEvent[])
|
||
return selected ?? conversationModelRoute(ctx, sessionId) ?? defaultModelRoute(ctx)
|
||
} })(payload, signal)
|
||
},
|
||
// 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<unknown>
|
||
} | 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 event
|
||
// types the lens folds are sent (a plain `tool/call` + `tool/result` pair,
|
||
// or a PTC `tool/ptc-dispatch-start` / `tool/ptc-dispatch` pair), narrowed
|
||
// to `seq > afterSeq` so polling is a small delta. A primed client asks the
|
||
// host to WAIT for the next tool event instead of re-reading an unchanged
|
||
// window (see `src/changes-ops.ts`).
|
||
'changes.ops': changesOps,
|
||
// 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<string, unknown>, 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: resolve the selection lexically and hand the packing to
|
||
// the background task table, which runs the system's zip/tar into a temp file.
|
||
// The tree watches it through `archive.status` and downloads the finished
|
||
// bytes from GET /sidebar/archive?id=.
|
||
//
|
||
// The selection arrives as absolute paths and is passed to the tool as
|
||
// paths relative to the selections' common ancestor — the tool decides the
|
||
// in-archive layout from the real directory structure, so there is no walk
|
||
// and no name disambiguation here any more.
|
||
'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 = typeof record?.name === 'string' ? record.name : ''
|
||
const selected: string[] = []
|
||
for (const raw of paths) selected.push(resolveTarget(cwd, raw))
|
||
return await archiveTasks.start({ sessionId, name, paths: selected })
|
||
},
|
||
'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, resolved, sidechatSignal),
|
||
}
|
||
}
|
||
|
||
/** 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<Record<string, unknown> | 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<string, unknown>)[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<string, unknown>).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<LegacyImportOutcome> {
|
||
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, connection).
|
||
* @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)
|
||
// Connection owns both deployment trust and authentication; never infer or
|
||
// bypass its policy from invocation flags or a copied trust list.
|
||
// DSH 0.2.3 deleted `requestRejection`; `admit` is the only admission call and
|
||
// it verifies credentials with the verifier registered under the NESTED
|
||
// `connection.authentication` service. Cordis refuses that read unless the
|
||
// caller declares the dependency, so admission lives in the injected child
|
||
// fiber — the only path this build supports. Never rebuild a trust list here:
|
||
// without the provider the request fails loudly.
|
||
/** `admit` refuses by carrying `rejection`; nothing else counts as a refusal. */
|
||
const admitted = (verdict: unknown): boolean =>
|
||
!(verdict !== null && typeof verdict === 'object' && 'rejection' in verdict)
|
||
let admit: ((req: SidebarHttpRequest) => boolean) | undefined
|
||
ctx.inject(['connection.authentication'], (providerCtx) => {
|
||
const connection = (providerCtx as Context).connection
|
||
const call = connection.admit
|
||
admit = (req) => admitted(call.call(connection, req))
|
||
})
|
||
const fence = (req: SidebarHttpRequest): boolean => {
|
||
if (admit !== undefined) return admit(req)
|
||
throw new TypeError('connection admission requires the injected authentication provider')
|
||
}
|
||
// The clue stack's context injection reads the live Side card preferences
|
||
// (source switches). The settings face is filled by the `ctx.inject` below,
|
||
// which runs after this body, so every read is lazy and a deployment
|
||
// without the settings service keeps the schema defaults.
|
||
let settingsFace: SidebarSettingsFace | undefined
|
||
const readCluePrefs = (): SidebarPrefs => {
|
||
const value = settingsFace?.get().value
|
||
return value !== null && typeof value === 'object' ? value as SidebarPrefs : SIDEBAR_PREFS_DEFAULTS
|
||
}
|
||
// Clue collection (S1–S9): the complete stack — durable store, the built-in
|
||
// file/GitHub/Feishu sources, the one dependency/connection runtime, the
|
||
// first-turn context injection, the share service with its raw routes, and
|
||
// the client's workspace lookup. Installed before the routes so the
|
||
// dispatcher's fallback sees it; every registration owns an effect-based
|
||
// teardown.
|
||
const clueStack = installClueStack(ctx, { readPrefs: readCluePrefs, fence })
|
||
// The ONE deliberate loopback authentication exception: a fixed read-only
|
||
// route that accepts a cookie-less local POST (the injected `curl` command)
|
||
// after checking the real peer socket, the OS-assigned listener port, the
|
||
// literal loopback Host, and the absence of browser/proxy headers. Every
|
||
// other /sidebar route keeps the ordinary fence above.
|
||
ctx.effect(
|
||
() => installClueAgentRead(ctx, clueStack.clues),
|
||
'dsh-better-sidebar: clue agent read route',
|
||
)
|
||
// 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.
|
||
// 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
|
||
}
|
||
/**
|
||
* The live `agentOpenTools` switch, or `undefined` when the form cannot be
|
||
* read right now. The host's settings service only lists entries whose
|
||
* fiber is ACTIVE, so a row missing from `describe()` is a NORMAL state
|
||
* during (re)mount and live-commit windows; a thrown read is the same
|
||
* unknown. `prefsOf()` maps that absence to the schema default (`false`),
|
||
* which is right for consumers but WRONG for this gate: it would read
|
||
* "unknown" as "the user turned the tool off" and unregister a live tool
|
||
* mid-session (issue #951). Only an explicit boolean is a user decision.
|
||
*/
|
||
const openToolsSetting = (): boolean | undefined => {
|
||
let value: unknown
|
||
try {
|
||
value = viewOf().value
|
||
} catch {
|
||
return undefined
|
||
}
|
||
if (value === null || typeof value !== 'object') return undefined
|
||
const flag = (value as { agentOpenTools?: unknown }).agentOpenTools
|
||
return typeof flag === 'boolean' ? flag : undefined
|
||
}
|
||
const syncOpenToolsGate = (): void => {
|
||
const enabled = openToolsSetting()
|
||
// Unknown (absent row / failed read) keeps the current registration.
|
||
// Explicit false unregisters once: the null guard also makes repeated
|
||
// syncs idempotent (no double-registration, no second disposal).
|
||
if (enabled === true) {
|
||
if (openToolsDisposers === null) {
|
||
openToolsDisposers = registerOpenTool(
|
||
ctx,
|
||
agentOpenRegistry,
|
||
(sessionId) => sessionCwdOf(ctx, sessionId),
|
||
prefsOf,
|
||
)
|
||
}
|
||
} else if (enabled === false && 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)
|
||
// The write IS the user's decision landing; re-read now instead of
|
||
// waiting for some later `settings.get` to happen to run (issue #951).
|
||
syncOpenToolsGate()
|
||
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(async () => {
|
||
// The row is addressable only after the loader mounts it, so the
|
||
// injection-time sync above ran before the user's value could be read
|
||
// (issue #951: the first turn after a restart missed the tool). Re-read
|
||
// AFTER the import too: the imported section may carry this very switch.
|
||
const outcome = await importLegacyPrefs(ctx, sctx.settings, ns)
|
||
syncOpenToolsGate()
|
||
return outcome
|
||
}).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. Teardown
|
||
// kills a build still running and deletes the temp files it was holding —
|
||
// an unmounted plugin must not leave orphan archives in the OS temp dir.
|
||
const archiveTasks = createArchiveTasks()
|
||
// Return the teardown promise itself: Cordis awaits async disposers, and
|
||
// closing the in-flight descriptor before the unlink is what keeps a
|
||
// Windows temp file from becoming undeletable.
|
||
ctx.effect(() => () => archiveTasks.dispose(), 'dsh-better-sidebar: archive task table')
|
||
const sidechatLifetime = new AbortController()
|
||
ctx.effect(() => () => { sidechatLifetime.abort() }, 'dsh-better-sidebar: sidechat admissions')
|
||
const api = buildApi(ctx, resolved, () => settingsFace, assistantLive, archiveTasks, sidechatLifetime.signal)
|
||
// Concurrent LARGE-prompt admissions. Only a prompt body that may carry
|
||
// encoded images is counted: the prompt's JSON metadata is capped at
|
||
// SIDECHAT_METADATA_BYTES, so a body past that threshold is the only one
|
||
// that can hold image bytes. Pure-text prompts never reach it — an earlier
|
||
// counter charged EVERY `sidechat.prompt` and rejected plain text with a
|
||
// bogus 503 "Too many image admissions".
|
||
//
|
||
// A slot is taken from the declared `content-length` before reading, or
|
||
// while streaming bytes for a chunked body. Exceeding the cap answers 413
|
||
// `too-large` — the repo's status for an over-cap body (see readJsonBody) —
|
||
// instead of a retryable 503.
|
||
const SIDECHAT_LARGE_PROMPT_ADMISSIONS = 2
|
||
let largePromptAdmissions = 0
|
||
const reserveLargePrompt = (): (() => void) => {
|
||
if (largePromptAdmissions >= SIDECHAT_LARGE_PROMPT_ADMISSIONS) {
|
||
throw new SidebarError('too-large', 'Too many image admissions; try again', 413)
|
||
}
|
||
largePromptAdmissions++
|
||
let released = false
|
||
return () => { if (!released) { released = true; largePromptAdmissions-- } }
|
||
}
|
||
const deliverClueOperation = createClueSessionDelivery(ctx, async payload => {
|
||
const agents = ctx.get('agents') as { get(id: string): unknown } | undefined
|
||
if (agents?.get(payload.sessionId) === undefined) {
|
||
const controller = ctx.get('sessionController') as {
|
||
resolveAgent?(id: string): Promise<{ agent: unknown } | { error: unknown }>
|
||
} | undefined
|
||
if (controller?.resolveAgent === undefined) throw new ClueError('unsupported', 'the parent conversation cannot be resumed')
|
||
const restored = await controller.resolveAgent(payload.sessionId)
|
||
if ('error' in restored) throw restored.error
|
||
}
|
||
return await api['sidechat.start']!(payload) as { childId: string }
|
||
})
|
||
installClueActions(ctx, {
|
||
clues: clueStack.clues,
|
||
runtime: clueStack.runtime,
|
||
deliver: async operation => {
|
||
const receipt = await deliverClueOperation({ sessionId: operation.sessionId, target: operation.target,
|
||
requestId: operation.requestId, prompt: operation.prompt, signal: operation.signal })
|
||
return { deliveryId: receipt.sessionId }
|
||
},
|
||
})
|
||
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
|
||
}
|
||
const imagePrompt = method === 'sidechat.prompt'
|
||
let releaseImagePrompt: (() => void) | undefined
|
||
const admitLargePrompt = (): void => { releaseImagePrompt ??= reserveLargePrompt() }
|
||
// Clue methods are cancellable too: the dispatcher below is the one
|
||
// route that serves them (no second route, no second fence).
|
||
const clueService = ctx.get('betterSidebarClues') as import('./clues/service.ts').CluesService | undefined
|
||
const controller = method === 'changes.ops' || method === 'selection.translate' || clueService?.hasApi(method) === true
|
||
? new AbortController()
|
||
: undefined
|
||
const response = controller === undefined ? undefined : res as ServerResponse
|
||
const abort = (): void => { controller?.abort() }
|
||
response?.once('close', abort)
|
||
try {
|
||
// Browsers send content-length for a string-body fetch; refuse before
|
||
// reading when the declared size can already carry image bytes.
|
||
if (imagePrompt) {
|
||
const declared = Number(req.headers['content-length'])
|
||
if (Number.isFinite(declared) && declared > SIDECHAT_METADATA_BYTES) admitLargePrompt()
|
||
}
|
||
// The ordinary JSON bound (1 MiB) is right for every control payload,
|
||
// but an EDIT document carries the user's text: `clues.saveEdit` gets
|
||
// the editable-size-derived bound so a 1–5 MiB source document can be
|
||
// written back (see MAX_CLUE_SAVE_BODY_BYTES).
|
||
// The enlarged bound applies only while the clue service actually
|
||
// claims `clues.saveEdit`; a disposed/absent service must not turn the
|
||
// method into a 16 MiB body sink (the dispatcher then answers 404).
|
||
const payload = await readJsonBody(
|
||
req,
|
||
imagePrompt
|
||
? sidechatPromptBodyLimit(ctx)
|
||
: method === 'clues.saveEdit' && clueService?.hasApi(method) === true
|
||
? MAX_CLUE_SAVE_BODY_BYTES
|
||
: undefined,
|
||
// A chunked (or lying-header) body is counted as soon as the bytes
|
||
// it delivered could hold an image.
|
||
imagePrompt ? total => { if (total > SIDECHAT_METADATA_BYTES) admitLargePrompt() } : undefined,
|
||
)
|
||
// 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') {
|
||
const result = await handler(payload, controller?.signal)
|
||
if (controller?.signal.aborted !== true) writeOk(res, result)
|
||
} else if (clueService !== undefined && clueService.hasApi(method)) {
|
||
// The clue service's API seam: later specs (S2+) register their own
|
||
// methods on it, so this is the only dispatcher fallback they need.
|
||
// Caller is the interactive UI; the abort signal is forwarded.
|
||
// S6/S2 integrations may serialize only the payload: forward an
|
||
// optional string `sessionId` exactly like the service's own read
|
||
// methods do. Non-string values are ignored, never coerced.
|
||
const payloadRecord = payload !== null && typeof payload === 'object'
|
||
? payload as Record<string, unknown>
|
||
: undefined
|
||
const payloadSessionId = payloadRecord?.sessionId
|
||
const result = await clueService.invokeApi(method, payload, {
|
||
caller: 'ui',
|
||
...(typeof payloadSessionId === 'string' ? { sessionId: payloadSessionId } : {}),
|
||
...(controller?.signal === undefined ? {} : { signal: controller.signal }),
|
||
})
|
||
if (controller?.signal.aborted !== true) writeOk(res, result)
|
||
} else {
|
||
throw new SidebarError('not-found', `unknown sidebar API method "${method}"`, 404)
|
||
}
|
||
} catch (error) {
|
||
if (controller?.signal.aborted !== true) writeError(res, error)
|
||
} finally {
|
||
releaseImagePrompt?.()
|
||
response?.off('close', abort)
|
||
}
|
||
},
|
||
}), 'dsh-better-sidebar: /sidebar/api routes')
|
||
|
||
ctx.effect(() => ctx.webServer.register({
|
||
kind: 'exact',
|
||
path: '/sidebar/sidechat-image',
|
||
handler: async (req, res) => {
|
||
if (!fence(req)) { writeError(res, new SidebarError('forbidden', 'forbidden', 403)); return }
|
||
if (req.method !== 'GET') { writeError(res, new SidebarError('method-error', 'method not allowed', 405)); return }
|
||
try {
|
||
const params = new URL(req.url ?? '/', 'http://dsh.internal').searchParams
|
||
const childId = params.get('childId')
|
||
const messageId = params.get('messageId')
|
||
const index = params.get('blockIndex')
|
||
if (!childId || !messageId || index === null || !/^\d+$/.test(index)) throw new SidebarError('bad-request', 'childId, messageId and blockIndex are required')
|
||
const image = await readSidechatImage(ctx, childId, messageId, Number(index))
|
||
res.writeHead(200, { 'content-type': image.ref.mediaType, 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' })
|
||
res.end(image.data)
|
||
} catch (error) { writeError(res, error) }
|
||
},
|
||
}), 'dsh-better-sidebar: sidechat image route')
|
||
|
||
// ── 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,
|
||
})
|
||
writeOk(res, { path, size })
|
||
} catch (error) {
|
||
writeError(res, error)
|
||
}
|
||
},
|
||
}), 'dsh-better-sidebar: /sidebar/upload route')
|
||
|
||
// ── Editor save route ──────────────────────────────────────────────────
|
||
// The document IS the body: no JSON string-escaping, so the 1 MiB JSON
|
||
// envelope no longer caps what an editor can write back. The encoding and
|
||
// line-ending round-trip lives in writeWorkspaceText, unchanged.
|
||
ctx.effect(() => ctx.webServer.register({
|
||
kind: 'exact',
|
||
path: '/sidebar/write',
|
||
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 path = url.searchParams.get('path')
|
||
if (sessionId === null || path === null || path === '') {
|
||
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))
|
||
// Optimistic concurrency: the client sends the mtime its draft was
|
||
// based on. Absent = no gate (a brand-new file has no baseline).
|
||
const raw = url.searchParams.get('expectedMtimeMs')
|
||
const parsed = raw === null ? Number.NaN : Number(raw)
|
||
const expectedMtimeMs = Number.isFinite(parsed) ? parsed : undefined
|
||
const content = await readTextBody(req, WRITE_BODY_GUARD_BYTES)
|
||
const result = await writeWorkspaceText({
|
||
cwd,
|
||
path,
|
||
content,
|
||
...(expectedMtimeMs === undefined ? {} : { expectedMtimeMs }),
|
||
})
|
||
writeOk(res, { ok: true, ...result })
|
||
} catch (error) {
|
||
writeError(res, error)
|
||
}
|
||
},
|
||
}), 'dsh-better-sidebar: /sidebar/write route')
|
||
|
||
// ── Lazy chunk route (client bundle splits) ─────────────────────────────
|
||
// Serves the client half's split bundles (lib/client-<name>.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` resolves every `path` through the same lexical resolver as
|
||
// fs.tree / /sidebar/file and returns an id IMMEDIATELY; the system's zip
|
||
// (or tar) packs the selection into a temp file in the background, reported
|
||
// through `archive.status`; and GET /sidebar/archive STREAMS the finished
|
||
// file once, with the RFC 5987 disposition. `archiveTasks` owns the
|
||
// concurrency cap, the TTL, and deleting the temp file.
|
||
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')
|
||
await 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 = resolveTarget(cwd, raw)
|
||
const info = await statFileForRoute(path)
|
||
if (!info.isFile()) {
|
||
throw new SidebarError('fs-error', 'not a file', 400)
|
||
}
|
||
const type = mediaTypeForPath(path)
|
||
// Raw bytes either way (binary-safe); ?download=1 switches the
|
||
// disposition so the browser saves the file instead of showing it.
|
||
// Only scriptable DOCUMENT types get an opaque-origin CSP. An inert
|
||
// image/binary keeps its existing response surface: the CSP sandbox
|
||
// does nothing for an <img>, and a directly opened image must not gain
|
||
// a needless behaviour change. nosniff + no-referrer are safe everywhere.
|
||
const documentType = type === 'text/html' || type === 'application/xhtml+xml' || type === 'image/svg+xml'
|
||
const headers: Record<string, string> = {
|
||
'content-type': type,
|
||
'cache-control': 'no-cache',
|
||
// Advertised on every media response: a media element asks for
|
||
// `bytes=0-` first, and only a 206 tells it that seeking is a byte
|
||
// question rather than "download the rest and hope".
|
||
'accept-ranges': 'bytes',
|
||
'x-content-type-options': 'nosniff',
|
||
'referrer-policy': 'no-referrer',
|
||
}
|
||
if (documentType) {
|
||
headers['content-security-policy'] = type === 'image/svg+xml'
|
||
? "sandbox; object-src 'none'"
|
||
: "sandbox allow-scripts allow-popups allow-downloads allow-modals; object-src 'none'"
|
||
}
|
||
if (url.searchParams.get('download') === '1') {
|
||
headers['content-disposition'] = `attachment; filename*=UTF-8''${encodeURIComponent(basename(path))}`
|
||
}
|
||
// A byte window is honoured for ANY file — the media route is the one
|
||
// place a browser talks HTTP range against this plugin (downloads
|
||
// resume through it too). Unsatisfiable means the header named a window
|
||
// past EOF: 416 with `bytes */size` is the RFC 7233 answer, and the
|
||
// response carries no body.
|
||
const rawRange = req.headers.range
|
||
const range = byteRangeOf(typeof rawRange === 'string' ? rawRange : undefined, info.size)
|
||
if (range === 'unsatisfiable') {
|
||
res.writeHead(416, { ...headers, 'content-range': `bytes */${info.size}` })
|
||
res.end()
|
||
return
|
||
}
|
||
// Streamed, not buffered: there is no size gate left, and the host's
|
||
// memory stays flat whatever the file weighs (see file-stream.ts).
|
||
await streamFileToResponse(path, info.size, res, headers, range)
|
||
} catch (error) {
|
||
writeError(res, error)
|
||
}
|
||
},
|
||
}), 'dsh-better-sidebar: /sidebar/file media route')
|
||
|
||
|
||
// ── HTML preview route (sandboxed HTML + its relative assets) ───────────
|
||
// Serves files under the session cwd for the built-in HTML previewer. The
|
||
// URL is path-encoded (see html-route.ts) so the previewed page's relative
|
||
// assets (./style.css, img/x.png) resolve back into this route with the
|
||
// session scope intact — a query-encoded URL would drop the scope when the
|
||
// browser resolves relatives. Every response carries the CSP `sandbox`
|
||
// directive: inside the editor's iframe the sandbox ATTRIBUTE is the
|
||
// boundary, this header is defense-in-depth so even a top-level load of
|
||
// the URL (e.g. a popup opened by a previewed page) stays in an opaque
|
||
// origin with no same-origin access to the GUI.
|
||
ctx.effect(() => ctx.webServer.register({
|
||
kind: 'prefix',
|
||
path: '/sidebar/html',
|
||
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 decoded = decodeHtmlUrl(url.pathname)
|
||
if (!decoded.ok) {
|
||
writeError(res, new SidebarError('bad-request', decoded.message, decoded.status))
|
||
return
|
||
}
|
||
const { sessionId, path } = decoded.ref
|
||
// The session's authoritative cwd (client cwd cannot ride in the URL
|
||
// — the path encoding has no query; a detached first request falls
|
||
// back to the process cwd and is normally refused by the workspace
|
||
// real-path guard, with the same semantics as the media route's
|
||
// fallback.
|
||
const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId))
|
||
const absolute = resolveTarget(cwd, path)
|
||
const info = await statFileForRoute(absolute)
|
||
if (!info.isFile()) {
|
||
throw new SidebarError('fs-error', 'not a file', 400)
|
||
}
|
||
const type = mediaTypeForPath(absolute)
|
||
// Streamed for the same reason as the media route: the previewed page
|
||
// and every relative asset it pulls through here are unbounded now.
|
||
await streamFileToResponse(absolute, info.size, res, {
|
||
'content-type': type === 'text/html' ? 'text/html; charset=utf-8' : type,
|
||
'cache-control': 'no-cache',
|
||
'x-content-type-options': 'nosniff',
|
||
'referrer-policy': 'no-referrer',
|
||
// The sandbox directive (no allow-same-origin → opaque origin) is
|
||
// the previewer's security boundary even for top-level loads;
|
||
// object-src 'none' blocks plugin embeds.
|
||
'content-security-policy': "sandbox allow-scripts allow-popups allow-downloads allow-modals; object-src 'none'",
|
||
})
|
||
} catch (error) {
|
||
writeError(res, error)
|
||
}
|
||
},
|
||
}), 'dsh-better-sidebar: /sidebar/html preview route')
|
||
|
||
// ── Agent opens push WebSocket ─────────────────────────────────────────
|
||
// Pushes `sidebar_open` requests for one session to the sidebar view: the
|
||
// host queues each request in the registry (consume-on-send), so a
|
||
// connected view applies it immediately and a disconnected one gets the
|
||
// replay when it attaches. The client mirrors each request into an
|
||
// editor / folder-window / browser tab open.
|
||
const agentOpenWss = new WebSocketServer({ noServer: true })
|
||
ctx.effect(() => ctx.webServer.registerUpgrade({
|
||
path: '/sidebar/ws/agent-opens',
|
||
handler: (req, socket, head) => {
|
||
if (!fence(req)) {
|
||
socket.destroy()
|
||
return
|
||
}
|
||
agentOpenWss.handleUpgrade(req as unknown as IncomingMessage, socket as unknown as Duplex, head as Buffer, (ws) => {
|
||
void attachAgentOpen(agentOpenRegistry, ws, req)
|
||
})
|
||
},
|
||
}), 'dsh-better-sidebar: agent-opens push WebSocket')
|
||
|
||
// ── File-tree directory watch WebSocket ────────────────────────────────
|
||
// The file tree lists a folder when it is expanded and would otherwise stay
|
||
// stale for the rest of the session. One socket per session carries the
|
||
// reader's expanded-folder set; the host watches exactly those directories
|
||
// and pushes a debounced notice per change, so the tree re-lists in place.
|
||
// Paths are resolved exactly like `fs.tree`'s (same resolution, same
|
||
// lexical rules), so the watch observes what the tree can list.
|
||
const fsWatchWss = new WebSocketServer({ noServer: true })
|
||
ctx.effect(() => ctx.webServer.registerUpgrade({
|
||
path: '/sidebar/ws/fs-watch',
|
||
handler: (req, socket, head) => {
|
||
if (!fence(req)) {
|
||
socket.destroy()
|
||
return
|
||
}
|
||
fsWatchWss.handleUpgrade(req as unknown as IncomingMessage, socket as unknown as Duplex, head as Buffer, (ws) => {
|
||
void attachFsWatch(ctx, ws, req)
|
||
})
|
||
},
|
||
}), 'dsh-better-sidebar: file-tree watch WebSocket')
|
||
|
||
// ── Side-chat live push WebSocket ──────────────────────────────────────
|
||
// The side-chat transcript polls `sidechat.events`; this socket tells it
|
||
// WHEN to pull instead, so a streaming answer, a just-claimed message and a
|
||
// finished tool call appear immediately rather than on the next 2s tick.
|
||
// Frames carry only the stale thread id (never event bodies), so the
|
||
// transcript transport, its afterSeq deltas and its tail cap are unchanged.
|
||
const sidechatWss = new WebSocketServer({ noServer: true })
|
||
const sidechatPush = createSidechatPushHub(ctx)
|
||
ctx.effect(() => () => { sidechatPush.dispose() }, 'dsh-better-sidebar: side-chat push hub')
|
||
ctx.effect(() => ctx.webServer.registerUpgrade({
|
||
path: '/sidebar/ws/sidechat',
|
||
handler: (req, socket, head) => {
|
||
if (!fence(req)) {
|
||
socket.destroy()
|
||
return
|
||
}
|
||
sidechatWss.handleUpgrade(req as unknown as IncomingMessage, socket as unknown as Duplex, head as Buffer, (ws) => {
|
||
sidechatPush.attach(ws)
|
||
})
|
||
},
|
||
}), 'dsh-better-sidebar: side-chat push WebSocket')
|
||
|
||
ctx.effect(() => () => {
|
||
openToolsDisposers?.()
|
||
agentOpenRegistry.dispose()
|
||
// `WebSocketServer.close()` on a `noServer` server only stops accepting
|
||
// upgrades: with ws@8 an already-upgraded socket is NOT terminated (the
|
||
// server just waits for it), so the accepted sockets must be closed
|
||
// explicitly or every fs-watch `fs.watch` handle and the agent-opens
|
||
// subscriber set survives the plugin unmount until the browser disconnects.
|
||
// The sockets' own `close` handlers stay the ones releasing those
|
||
// resources (they are idempotent, and a socket already closing ignores a
|
||
// second close).
|
||
for (const wss of [agentOpenWss, fsWatchWss, sidechatWss]) {
|
||
for (const client of wss.clients) client.close()
|
||
wss.close()
|
||
}
|
||
}, 'dsh-better-sidebar: teardown')
|
||
}
|
||
|
||
/** One `watch` / `unwatch` frame from the file tree. */
|
||
interface FsWatchFrame {
|
||
op?: unknown
|
||
path?: unknown
|
||
}
|
||
|
||
/**
|
||
* Serve one session's directory-watch socket until it closes.
|
||
*
|
||
* Frames are `{ op: 'watch' | 'unwatch', path }`, where `path` is relative to
|
||
* the session's workspace exactly like `fs.tree`'s. A path that fails
|
||
* resolution, or a rejection past the watcher cap, is answered with
|
||
* `{ dir, ok: false }` so the client can stop asking rather than retry.
|
||
* @param ctx - host plugin context (session cwd).
|
||
* @param ws - the accepted socket.
|
||
* @param req - the upgrade request carrying `?sessionId=`.
|
||
*/
|
||
async function attachFsWatch(
|
||
ctx: Context,
|
||
ws: WebSocket,
|
||
req: SidebarHttpRequest,
|
||
): Promise<void> {
|
||
try {
|
||
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
||
const sessionId = url.searchParams.get('sessionId')
|
||
if (sessionId === null) {
|
||
ws.close(1008, 'sessionId is required')
|
||
return
|
||
}
|
||
const watchers = createDirectoryWatchers(
|
||
(event) => {
|
||
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ dir: event.dir }))
|
||
},
|
||
(dir, error) => {
|
||
ctx.logger.warn('dsh-better-sidebar: cannot watch %s', dir)
|
||
ctx.logger.warn(error)
|
||
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ dir, ok: false }))
|
||
},
|
||
)
|
||
ws.on('close', () => { watchers.close() })
|
||
ws.on('error', () => { watchers.close() })
|
||
ws.on('message', (data) => {
|
||
void handleFsWatchFrame(ctx, ws, watchers, sessionId, data)
|
||
})
|
||
} catch (error) {
|
||
ws.close(1011, error instanceof Error ? error.message : String(error))
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Apply one watch frame.
|
||
* @param ctx - host plugin context.
|
||
* @param ws - the owning socket.
|
||
* @param watchers - the socket's watcher set.
|
||
* @param sessionId - the session the socket was opened for.
|
||
* @param data - the raw frame text.
|
||
*/
|
||
async function handleFsWatchFrame(
|
||
ctx: Context,
|
||
ws: WebSocket,
|
||
watchers: DirectoryWatchers,
|
||
sessionId: string,
|
||
data: unknown,
|
||
): Promise<void> {
|
||
let frame: FsWatchFrame
|
||
try {
|
||
frame = JSON.parse(typeof data === 'string' ? data : String(data)) as FsWatchFrame
|
||
} catch {
|
||
return
|
||
}
|
||
const path = typeof frame.path === 'string' ? frame.path : undefined
|
||
if (path === undefined || path === '') return
|
||
try {
|
||
const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId))
|
||
const dir = resolveTarget(cwd, path)
|
||
if (frame.op === 'unwatch') {
|
||
watchers.remove(dir)
|
||
return
|
||
}
|
||
if (frame.op !== 'watch') return
|
||
const ok = watchers.add(dir)
|
||
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ dir, ok }))
|
||
} catch (error) {
|
||
// The tree keeps working without live refresh; a refused path is reported
|
||
// once so the client stops asking for it.
|
||
if (ws.readyState === WebSocket.OPEN) {
|
||
ws.send(JSON.stringify({ dir: path, ok: false, reason: error instanceof Error ? error.message : String(error) }))
|
||
}
|
||
}
|
||
}
|
||
|
||
/** Push queued `sidebar_open` requests for one session to a connected view. */
|
||
async function attachAgentOpen(
|
||
registry: AgentOpenRegistry,
|
||
ws: WebSocket,
|
||
req: SidebarHttpRequest,
|
||
): Promise<void> {
|
||
try {
|
||
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
||
const sessionId = url.searchParams.get('sessionId')
|
||
if (sessionId === null) {
|
||
ws.close(1008, 'sessionId is required')
|
||
return
|
||
}
|
||
const send = (request: AgentOpenRequest): void => {
|
||
if (ws.readyState === WebSocket.OPEN) {
|
||
ws.send(JSON.stringify(request))
|
||
}
|
||
}
|
||
// Attach replays the queued (undelivered) requests for this session; the
|
||
// disposer detaches the view on socket close/error so later opens queue
|
||
// instead of accumulating on a dead socket.
|
||
const unsubscribe = registry.attach(sessionId, send)
|
||
ws.on('close', () => { unsubscribe() })
|
||
ws.on('error', () => { unsubscribe() })
|
||
} catch (error) {
|
||
ws.close(1011, error instanceof Error ? error.message : String(error))
|
||
}
|
||
}
|