/** * 宿主侧 DSH 契约的**结构性窄化投影**。 * * 本仓库规范(AGENTS.md §3.1)要求插件不引入对官方包的编译期/运行时依赖, * 因此这里只保留本插件真正读取的叶子字段。字段形状以官方 **DSH 0.2.0 – 0.2.1** * 的 d.ts + 运行时源码为准(两个版本都核对过),可用 * `node scripts/compatcheck.mjs --fetch <版本>` 复核: * * - `agent/created` / `Agent.ctx`(事件名常量在 `host/replace.ts`):`dsh-agent/lib/types/runtime-types.d.ts` * ⚠️ 旧事件名 `agent/session-start` 已从官方事件表移除(issue #1),不要再写回去 * - `tools.register` / `tools.restrict`(`restrict` 实现见 `lib/index.js`)、 * `ToolExecution.rootCallId`、`output.presentationMeta`:`dsh-tools/lib/types/index.d.ts` * - `systemPrompt.section` / `getSectionOrder`:`dsh-system-prompt/lib/types/index.d.ts` * - `sandboxPolicy.resolve`:`dsh-sandbox-policy/lib/types/index.d.ts` * - `sandbox.confine`:`dsh-sandbox/lib/types/index.d.ts` * - `subprocess.spawn`:`dsh-subprocess/lib/types/{index,types}.d.ts` * - `jobs.start`(含 0.2.1 的 `toolCall`):`dsh-jobs/lib/types/{index,types}.d.ts` * - `workingDirectory.ensure`(0.2.1 的会话当前目录):`dsh-working-directory/lib/types/index.d.ts` * - `shellEnv.collect`:`dsh-shell-env/lib/types/index.d.ts` * - `approval.request`:`dsh-user-approval/lib/types/index.d.ts` * - `connection.fetch.register`:`dsh-client-connection/lib/types/rpc.d.ts` * - entry Config 的 volatile 字段:`@deepseek-ai/schemastery` 的 `Schema.prototype.volatile`, * 表单投影见 `dsh-settings/lib/types/schema.js` 的 `volatileForm` / `plainConfig`; * `apply(ctx, config)` 收到的 config 形状见 `cordis-plugin-loader` 的 `fiber.config` * * ⚠️ 契约变了集中改这里,不要散落到各文件。 */ import type { Dialect } from '../shared/protocol.js' /** cordis 宿主上下文的最小面。 */ export interface HostContextLike { /** 读取可选服务;未挂载时为 undefined。 */ get(name: string): unknown /** 监听事件;返回 disposer 由当前 fiber 自动回收。 */ on(name: string, listener: (...args: any[]) => unknown): unknown /** 注册 effect(可返回 disposer),随插件 fiber 回收。 */ effect(execute: () => unknown, label?: string): unknown /** 等待依赖服务就绪后执行回调。 */ inject?(names: string[], callback: (scoped: HostContextLike) => unknown): unknown } /** `ctx.logger` 的最小面。 */ export interface LoggerLike { info?(message: string): void warn?(message: string): void error?(message: string): void } // --------------------------------------------------------------------------- // agent / 事件 // --------------------------------------------------------------------------- /** 会话头(只读 `cwd`)。 */ export interface SessionHeaderLike { readonly cwd?: string | undefined } /** 会话的最小面。 */ export interface SessionLike { readonly id: string readonly header?: SessionHeaderLike | undefined } /** * agent 的最小面。 * * `ctx` 是 **agent 自己的 scope context**(`dsh-agent` 的 `Agent.ctx`): * 通过它注册的工具与提示词 section 只覆盖这个 agent,且随 agent 释放而撤销。 */ export interface AgentLike { readonly id: string readonly session?: SessionLike | undefined readonly ctx: AgentContextLike } /** agent scope context:与宿主上下文同形,但注册会带上该 agent 的 scope。 */ export type AgentContextLike = HostContextLike // --------------------------------------------------------------------------- // tools // --------------------------------------------------------------------------- /** 沙箱模式。 */ export type SandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access' /** 输出流投影(`CollectedOutput`)。 */ export interface CollectedOutputLike { readonly text: string readonly truncated: boolean readonly spillPath?: string | undefined } /** 内容块(只用到文本块)。 */ export interface ContentBlockLike { readonly type: 'text' readonly text: string } /** `tools.register` 的入参(`ToolDefinition` 的窄化)。 */ export interface ToolDefinitionLike { readonly name: string readonly description: string /** 原始 JSON Schema(`ToolSchema.parameters`;register 不校验该字段)。 */ readonly parameters: Record /** 规范输出契约;`schema` 会被 `assertSupportedJsonSchema` 校验。 */ readonly output: { readonly schema: Record readonly render: (args: unknown, value: unknown) => ContentBlockLike[] /** * 可重放的表现层元数据(DSH 0.2.x 起对 native 与嵌套调用都会计算并持久化到 * `tool/result.meta`,d.ts 与运行时已核对)。终端卡片从 `meta.cwd` * 读取「命令实际在哪个目录执行」,没有它就只能退回会话原始工作区。 */ readonly presentationMeta?: ((args: unknown, value: unknown) => unknown) | undefined } execute(args: unknown, exec: ToolRunContextLike): Promise presentCall?(args: unknown): unknown presentResult?(args: unknown, result: ToolResultLike): unknown } /** `presentResult` 收到的结果视图。 */ export interface ToolResultLike { readonly content: readonly ContentBlockLike[] readonly isError: boolean /** 结构化输出值(`output.schema` 那一份);`presentResult` 靠 `kind` 决定卡片形态。 */ readonly value?: unknown } /** 一次工具执行(`ToolRunContext` 的窄化)。 */ export interface ToolRunContextLike { readonly callId: string /** * 根调用 id(0.2.x 起 `ToolExecution.rootCallId` 必有)。 * * PTC 的嵌套子调用有独立的 `callId`,但后台任务要归属到模型真正发起的那次根调用; * 更低版本没有该字段,退回 `callId`。 */ readonly rootCallId?: string | undefined readonly signal: AbortSignal readonly agent?: AgentLike | undefined } /** 工具过滤器(`ToolRestriction`)。 */ export interface ToolRestrictionLike { readonly allow?: readonly string[] readonly deny?: readonly string[] } /** `ctx.tools` 的最小面。 */ export interface ToolRuntimeLike { /** 在当前 scope 注册工具;返回精确 disposer(由 effect 收回)。 */ register(definition: ToolDefinitionLike): () => void /** * 限制**继承来的**全局工具(自己这一层注册的不受限制)。 * ⚠️ 必须是 scoped context(`agent.ctx`);名字未知时**抛错**。 */ restrict(filter: ToolRestrictionLike): () => void } // --------------------------------------------------------------------------- // systemPrompt // --------------------------------------------------------------------------- /** 一个提示词 section(`PromptSection`)。 */ export interface PromptSectionLike { readonly name: string readonly order: number readonly text: string | ((context: unknown) => string) } /** `ctx.systemPrompt` 的最小面。 */ export interface SystemPromptLike { /** 在当前 scope 注册 section;同名会 shadow 更靠外的 section(空文本会被丢弃)。 */ section(section: PromptSectionLike): () => void /** 读取集中分配的 section 顺序名。 */ getSectionOrder(name: string): number } // --------------------------------------------------------------------------- // sandbox / sandboxPolicy // --------------------------------------------------------------------------- /** 一次能力调用的沙箱策略(`SandboxExecutionPolicy` 的窄化)。 */ export interface SandboxPolicyLike { readonly mode: SandboxMode readonly workspaceRoot: string readonly sessionId?: unknown } /** 受限策略(`mode` 已收窄为非 `danger-full-access`)。 */ export interface ConfinedSandboxPolicyLike { readonly mode: 'read-only' | 'workspace-write' readonly workspaceRoot: string readonly sessionId?: unknown } /** `ctx.sandboxPolicy` 的最小面。 */ export interface SandboxPolicyServiceLike { readonly defaultMode?: SandboxMode readonly workspaceRoot?: string resolve(request?: { session?: object; mode?: SandboxMode }): SandboxPolicyLike } /** 沙箱 runner 生效度(`SandboxEnforcement`)。 */ export type SandboxEnforcement = 'full' | 'partial' /** runner 失败判据(`RunnerFailureRule`)。 */ export interface RunnerFailureRuleLike { readonly allowedExitCodes?: readonly number[] readonly fatalSignatures: readonly string[] readonly informationalLines?: readonly string[] } /** `ctx.sandbox.confine` 的返回(`ConfinedArgv` 的窄化)。 */ export interface ConfinedArgvLike { readonly argv: string[] readonly enforcement: SandboxEnforcement readonly denialSignatures: readonly string[] readonly runnerFailureRules: readonly RunnerFailureRuleLike[] } /** `ctx.sandbox` 的最小面。 */ export interface SandboxProviderLike { /** * 用 runner 包住 caller 的 argv;无法强制时 fail closed(抛错)。 * * ⚠️ **async**:必须 await,否则拿到 Promise。 */ confine(argv: readonly string[], policy: ConfinedSandboxPolicyLike): Promise } /** 一次运行后的沙箱事实(`ShellSandboxInfo` 的窄化)。 */ export interface SandboxInfoLike { readonly mode: SandboxMode readonly denied: boolean readonly enforcement?: SandboxEnforcement | undefined readonly runnerFailed?: boolean | undefined } // --------------------------------------------------------------------------- // workingDirectory // --------------------------------------------------------------------------- /** * 会话当前工作目录服务(DSH 0.2.1 新增,`@deepseek-ai/dsh-working-directory`)。 * * ⚠️ `session.header.cwd` 是**不可变的原始项目目录**;用户/模型通过 * `working_directory` 工具 `cd` 之后,真正生效的是这个服务里的 projection。 * 终端工具必须用它,否则命令会继续跑在旧目录,而模型以为自己已经换了目录。 * * 老版本 DSH 没有该服务:调用方用 `ctx.get` 判空后退回 header cwd。 */ export interface WorkingDirectoryServiceLike { /** * 校验当前目录;目录消失时回退到原始项目。**async**,必须 await。 * @param agent - 会话所属 agent。 * @param signal - 取消信号。 * @returns 当前生效的绝对目录。 */ ensure(agent: object, signal?: AbortSignal): Promise } // --------------------------------------------------------------------------- // subprocess // --------------------------------------------------------------------------- /** 单流的有界收集配置。 */ export interface SubprocessCollectLike { readonly maxBytes: number readonly spill?: { readonly maxBytes: number } | undefined } /** `SubprocessSpawnSpec` 的窄化。 */ export interface SubprocessSpawnSpecLike { readonly argv: readonly string[] readonly cwd: string readonly stdio: { readonly stdin: 'ignore' | 'pipe' | { readonly data: string } readonly stdout: 'pipe' | 'inherit' | SubprocessCollectLike readonly stderr: 'pipe' | 'inherit' | SubprocessCollectLike } readonly graceMs: number readonly signal?: AbortSignal | undefined readonly env?: NodeJS.ProcessEnv | undefined } /** 一次增量读取(`SubprocessOutputRead`)。 */ export interface SubprocessOutputReadLike { readonly text: string readonly nextOffset: number readonly lossy: boolean readonly spillPath?: string | undefined } /** 一个收集流的增量读取器。 */ export interface SubprocessOutputReaderLike { readFrom(fromByte: number): SubprocessOutputReadLike } /** 进程退出事实(`SubprocessOutcome`)。 */ export interface SubprocessOutcomeLike { readonly exitCode: number | null readonly signal: NodeJS.Signals | null } /** `SubprocessHandle` 的窄化。 */ export interface SubprocessHandleLike { readonly collected: { readonly stdout?: SubprocessOutputReaderLike | undefined readonly stderr?: SubprocessOutputReaderLike | undefined } readonly done: Promise terminate(): void } /** `ctx.subprocess` 的最小面。 */ export interface SubprocessRuntimeLike { spawn(spec: SubprocessSpawnSpecLike): SubprocessHandleLike } // --------------------------------------------------------------------------- // jobs // --------------------------------------------------------------------------- /** 一个后台任务的终态(`JobOutcome` 的窄化)。 */ export interface JobOutcomeLike { readonly status: 'completed' | 'killed' | 'failed' readonly detail?: string | undefined readonly output?: string | undefined } /** * `ctx.jobs` 的投影在**使用点**(`src/host/bash-tool.ts` 的 `BashJobsLike` / `BashJobSourceLike`)。 * * ⚠️ 注册表只认 `start({ output: [...] })` 的拉取源,**没有** `readOutput` 这类钩子; * 别把后台输出接在 hooks 上(表现是任务跑完但 `job_output` 永远为空)。 */ // --------------------------------------------------------------------------- // shellEnv / approval // --------------------------------------------------------------------------- /** `ctx.shellEnv` 的最小面。 */ export interface ShellEnvRegistryLike { /** 收集本次执行的受管 `DSH_*` 环境。 */ collect(execution: { readonly agent?: AgentLike | undefined }): Readonly> } /** `ctx.approval` 的最小面(`ApprovalService.request` 的结构形状)。 */ export interface ApprovalServiceLike { request(request: { agent: AgentLike toolName: string callId: string reason: string signal?: AbortSignal | undefined }): Promise<'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'> } // --------------------------------------------------------------------------- // connection // --------------------------------------------------------------------------- /** 一条精确 Fetch 路由(`ConnectionFetchRoute` 的窄化)。 */ export interface FetchRouteLike { readonly path: string readonly methods: readonly string[] readonly requestBody: 'buffered' | 'streaming' readonly fetch: (request: Request) => Promise } /** `ctx.connection` 的最小面(只用精确 Fetch 路由,绝不碰 `rpc.handle`)。 */ export interface ConnectionServiceLike { readonly fetch?: { register(route: FetchRouteLike): () => Promise } } /** * volatile Config 字段的稳定引用(`cosmokit` 的 `Volatile` 的结构投影)。 * * ⚠️ 与旧模型的 `settings.register` 返回的 scope 完全不同:这是**同一个对象**, * Loader 落盘后就地更新它的快照,所以每次 `.get()` 都拿到最新值,不需要 watch, * 也不需要重启。`apply(ctx, config)` 的 config 里每个 volatile 字段都是它。 */ export interface VolatileLike { get(): T } // --------------------------------------------------------------------------- // 本插件自己的类型 // --------------------------------------------------------------------------- /** 本插件 entry Config 解析后的值(三个 volatile 字段的普通快照)。 */ export interface TerminalToolSettings { readonly dialect: Dialect readonly bashPath: string /** * 上一次「自动发现」扫到的可用路径(用户主动点出来的结果)。 * * 只用于设置行的下拉列表:持久化它,重启 dsh 后仍然能直接在下拉里换路径, * 不必为了「多看几条」再点一次自动发现。**绝不**用它自动改写 `dialect`。 */ readonly bashCandidates: readonly string[] } /** capability 探测的输入(可注入,便于自测)。 */ export interface CapabilityProbeInput { readonly platform: string readonly hasTools: boolean readonly hasSystemPrompt: boolean readonly hasSettings: boolean }