Merge origin/master into worktree/skill-catalog-hot-refresh

This commit is contained in:
Tianyi Cui
2026-07-29 16:40:40 +08:00
1089 changed files with 35627 additions and 9637 deletions

View File

@@ -1,6 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
README.md: 59fc4ed46f047ee8f72aa237ec3a47b21091358f
README.zh.md: 596392a8eb11469a9f3afb34046c2c37521a4ed6
# pnpm run verify-translation-pairing --write packages/ui/app-boot/README.md
README.md: 0282d3e9559d55c3fe5b07df133747750c06ebad
README.zh.md: b7121bbd288cd6e3f9ef2301de6018ceb380eb06

View File

@@ -9,18 +9,18 @@ Shared boot glue for the app bins ([`dsh`](../../../apps/cli/README.md), [`dsh-c
| `resolveConfigPath(path, snapshotMode, cwd?)` | Absolute config path; `snapshotMode === 'replay'` swaps a `cordis.yml`/`.yaml` basename for its sibling `cordis.snapshot.yml` |
| `loadEnv(binName, dir?, warn?)` | Load the gitignored `.env` (Node `process.loadEnvFile`); absent file is fine, an unloadable one warns a single labelled line (default: stderr) |
| `installFailLoud(binName, proc?)` | Turn a post-`boot()` unhandled Loader rejection into one labelled stderr line + `exit(1)`; returns the uninstaller (for tests) |
| `assertEntriesLoaded(ctx, binName)` | Throw when a settled tree holds an enabled entry with no fiber (a plugin module that failed to import) |
| `assertEntriesLoaded(ctx, binName)` | Throw when a settled tree holds an enabled entry with no fiber, reporting every unresolved plugin name as a Cordis startup failure |
| `loadPersonalPatches(binName, dir?)` | Parse the optional `config.yaml` in the Harness home (default [`resolveDshHome()`](../../util/paths/README.md): `$DSH_HOME`, else `~/.dsh`) — a top-level YAML array of include `PatchOptions` (id-targeted config overrides, `insert` lists, `!!js` allowed); absent file → `undefined`, an unreadable/unparsable/non-array file throws |
| `boot(binName, absoluteConfigPath, patches?, prepare?)` | Create the root context, run optional host preparation before plugins mount (e.g. `ctx.provide(RESUME_SESSION_ID_KEY, id)`), then mount the Loader/include tree, await it, assert entries loaded, and return the root context |
| `RESUME_SESSION_ID_KEY` | Context key a bin sets through `boot`'s `prepare` hook to hand a resume session id to the booted config; the config reads it as the bare identifier `resumeSessionId` in a `!!js` expression, so resuming needs no environment variable |
| `addHarnessSourceSection(ctx, sourceRoot)` | Add a global `harness:source` prompt section (ordered just after the harness identity, before the persona) telling the agent the on-disk path to its own source checkout; a no-op returning `undefined` when the booted tree has no `systemPrompt` service. The section is registered against that service's fiber, so a dev HMR reload of the system prompt drops it until the next boot |
| `HARNESS_SOURCE_SECTION` | The `'harness:source'` section name `addHarnessSourceSection` registers under |
Two failure classes the guards handle: `loader.await()` swallows init rejections (`Promise.allSettled`) — Node still exits non-zero on the resulting unhandled rejection, and `installFailLoud` replaces the noisy dump with one labelled line and a guaranteed `exit(1)`; a failed plugin IMPORT is only logged by the Loader (the process would otherwise exit 0 on a usable config typo), leaving a fiber-less entry that `assertEntriesLoaded` turns into a `boot()` rejection.
Two failure classes the guards handle: `loader.await()` swallows init rejections (`Promise.allSettled`) — Node still exits non-zero on the resulting unhandled rejection, and `installFailLoud` replaces the noisy dump with one labelled line and a guaranteed `exit(1)`; a failed plugin import is only logged by the Loader (the process would otherwise exit 0 on a usable config typo), leaving a fiber-less entry that `assertEntriesLoaded` turns into a `boot()` rejection naming every failed plugin.
Bare plugin specifiers in a config (`@deepseek-ai/dsh-*`, npm packages) resolve through the Cordis Loader's internal module loader. Repository bins install Loader's optional `node-addon-require-builtin` peer; external callers must supply it or install plugins where plain Node import resolution can find them. Relative specifiers resolve against the config directory without the native helper. The bins' subprocess smokes exercise the internal-loader path, while this package's unit suite drives `boot()` in-process against configs with relative specifiers.
Bare plugin specifiers in a config (`@deepseek-ai/dsh-*`, npm packages) resolve through the Cordis Loader's internal module loader. Repository bins install Loader's optional `node-addon-require-builtin` peer; external callers must supply it or install plugins where plain Node import resolution can find them. Relative specifiers resolve against the config directory without the native helper. The `dsh` source launcher additionally maps manifest-declared workspace packages to their TypeScript source; its configuration gate requires every TUI/Web bare plugin to appear in the resolver manifest's `dependencies`. The bins' subprocess smokes exercise the internal-loader path, while this package's unit suite drives `boot()` in-process against configs with relative specifiers.
This package carries no loader hooks and no dev-mode surface: the `dsh-scripts` launcher ([`sdk/scripts`](../../sdk/scripts/README.md), with the shared project model in [`sdk/helper`](../../sdk/helper/README.md)) owns process startup, tsx registration, and local-plugin source resolution, and consumes these helpers for the boot sequence itself.
This package carries no loader hooks and no dev-mode surface. The [`dsh` app](../../../apps/cli/README.md) owns its Node source-launch hook and consumes these helpers for the boot sequence; built consumers continue to use plain Node package resolution.
## Personal config
@@ -41,7 +41,7 @@ No direct invalidation from `boot()`; a consumer that calls `addHarnessSourceSec
## Known Limitations and Deferred Work
- **Bare package specifiers depend on Loader internals** — production bins need Loader's optional native helper; an in-process caller without it must use resolvable relative/file specifiers or tsx path mapping.
- **Bare package specifiers depend on Loader internals** — production bins need Loader's optional native helper; an in-process caller without it must use resolvable relative/file specifiers or provide its own module-resolution hook.
- **Snapshot replay swapping is basename-specific** — only a config ending in `cordis.yml` or `cordis.yaml` maps to the sibling `cordis.snapshot.yml`; custom config names require caller-managed selection.
- **Environment loading is cwd-scoped and optional** — the helper loads one `.env` file and warns on failure; it does not search parents, merge profiles, or validate required variables.
- **Personal config is patch-shaped** — an id-targeted patch replaces the entry's whole `config` rather than deep-merging, so a personal override restates the base fields it keeps.

View File

@@ -9,18 +9,18 @@
| `resolveConfigPath(path, snapshotMode, cwd?)` | 生成绝对配置路径;当 `snapshotMode === 'replay'` 时,把 basename 为 `cordis.yml`/`.yaml` 的文件替换为同级 `cordis.snapshot.yml` |
| `loadEnv(binName, dir?, warn?)` | 加载已被 git 忽略的 `.env`Node `process.loadEnvFile`);文件不存在不影响启动,文件无法加载时输出一行带标签的警告(默认写入 stderr |
| `installFailLoud(binName, proc?)` | 将 `boot()` 之后未处理的 Loader rejection 转换为一行带标签的 stderr 消息并执行 `exit(1)`;返回卸载函数(供测试使用) |
| `assertEntriesLoaded(ctx, binName)` | 树结算后,如果其中存在已启用但没有 fiber 的条目(即导入失败的插件模块),则抛出异常 |
| `assertEntriesLoaded(ctx, binName)` | 树结算后,如果其中存在已启用但没有 fiber 的条目,则抛出异常,并以 Cordis 启动故障的形式报告每个未解析插件的名称 |
| `loadPersonalPatches(binName, dir?)` | 解析 Harness home 中可选的 `config.yaml`(默认使用 [`resolveDshHome()`](../../util/paths/README.md):先取 `$DSH_HOME`,否则取 `~/.dsh`):其顶层是一个 YAML 数组,内容为 include 的 `PatchOptions`(按 id 定位的配置覆盖、`insert` 列表,允许 `!!js`);文件不存在时返回 `undefined`,文件不可读、不可解析或内容不是数组时抛出异常 |
| `boot(binName, absoluteConfigPath, patches?, prepare?)` | 创建根上下文,在插件挂载前执行可选的宿主准备操作(例如 `ctx.provide(RESUME_SESSION_ID_KEY, id)`),再挂载 Loader/include 树并等待其结算,断言所有条目均已加载,最后返回根上下文 |
| `RESUME_SESSION_ID_KEY` | bin 通过 `boot``prepare` 钩子设置的上下文键,用于把要恢复的会话 id 交给已启动配置;配置以裸标识符 `resumeSessionId``!!js` 表达式中读取它,因此恢复操作无需环境变量 |
| `addHarnessSourceSection(ctx, sourceRoot)` | 添加全局 `harness:source` 提示词段落(顺序紧随 harness 身份、位于 persona 之前),告知 agent智能体自身源代码 checkout 的磁盘路径;如果已启动树没有此项服务,则不执行操作并返回 `undefined`。这里的服务是 `systemPrompt`;该段落注册到它的 fiber因此开发环境 HMR热模块替换重新加载系统提示词后它会消失直至下次启动 |
| `HARNESS_SOURCE_SECTION` | `'harness:source'` 段落名称,供 `addHarnessSourceSection` 注册使用 |
这些保护处理两类故障。`loader.await()` 会吞掉初始化 rejection`Promise.allSettled`Node 仍会因随后产生的未处理 rejection 以非零状态退出,而 `installFailLoud` 会把冗长转储替换为一行带标签的消息,并确保执行 `exit(1)`。插件导入失败则只会由 Loader 记录日志(否则,即使配置存在拼写错误,进程也会以代码 0 退出),并留下没有 fiber 的条目;`assertEntriesLoaded` 会将其转换为 `boot()` rejection。
这些保护处理两类故障。`loader.await()` 会吞掉初始化 rejection`Promise.allSettled`Node 仍会因随后产生的未处理 rejection 以非零状态退出,而 `installFailLoud` 会把冗长转储替换为一行带标签的消息,并确保执行 `exit(1)`。插件导入失败则只会由 Loader 记录日志(否则,即使配置存在拼写错误,进程也会以代码 0 退出),并留下没有 fiber 的条目;`assertEntriesLoaded` 会将其转换为 `boot()` rejection,并在其中列出每个导入失败插件的名称
配置中的裸插件 specifier`@deepseek-ai/dsh-*`、npm 包package通过 Cordis Loader 的内部模块 loader 解析。仓库 bin 会安装 Loader 的可选 peer `node-addon-require-builtin`;外部调用方必须提供该组件,或者把插件安装到普通 Node import 解析可以找到的位置。相对 specifier 无需原生 helper并以配置目录为基准解析。bin 的子进程冒烟测试覆盖内部 loader 路径,而本包的单元测试套件会在进程内使用相对 specifier 配置驱动 `boot()`
配置中的裸插件 specifier`@deepseek-ai/dsh-*`、npm 包package通过 Cordis Loader 的内部模块 loader 解析。仓库 bin 会安装 Loader 的可选 peer `node-addon-require-builtin`;外部调用方必须提供该组件,或者把插件安装到普通 Node import 解析可以找到的位置。相对 specifier 无需原生 helper并以配置目录为基准解析。`dsh` 源码启动器还会将 manifest元数据清单声明的 workspace 包映射到其 TypeScript 源码;其配置门禁要求每个 TUIWeb 裸插件都出现在解析所用 manifest 的 `dependencies` 中。bin 的子进程冒烟测试覆盖内部 loader 路径,而本包的单元测试套件会在进程内使用相对 specifier 配置驱动 `boot()`
此包不包含 loader 钩子,也不提供开发模式接口`dsh-scripts` launcher[`sdk/scripts`](../../sdk/scripts/README.md),共享项目模型见 [`sdk/helper`](../../sdk/helper/README.md)持有进程启动、tsx 注册和本地插件源代码解析,并在自身的启动序列中使用这些 helper
此包不包含 loader 钩子,也不提供开发模式接口。[`dsh` 应用](../../../apps/cli/README.md)持有自己的 Node 源码启动钩子,并在启动序列中使用这些 helper构建后的消费方仍使用普通 Node 包解析
## 个人配置
@@ -41,7 +41,7 @@
## 已知限制与延期工作
- **裸包 specifier 依赖 Loader 内部机制**:生产 bin 需要 Loader 的可选原生 helper没有该 helper 的进程内调用方必须使用可解析的相对file specifier使用 tsx 路径映射
- **裸包 specifier 依赖 Loader 内部机制**:生产 bin 需要 Loader 的可选原生 helper没有该 helper 的进程内调用方必须使用可解析的相对file specifier提供自己的模块解析钩子
- **快照回放替换仅识别特定 basename**:只有以 `cordis.yml``cordis.yaml` 结尾的配置会映射到同级 `cordis.snapshot.yml`;自定义配置名称需要调用方自行选择。
- **环境加载局限于 cwd 且为可选操作**helper 只加载一个 `.env` 文件,并在失败时发出警告;它不会搜索父目录、合并 profile 或验证必需变量。
- **个人配置采用 patch 形式**:按 id 定位的 patch 会替换条目的整个 `config`,而不是深度合并,因此个人覆盖必须重述需要保留的基础字段。

View File

@@ -142,8 +142,8 @@ export function installFailLoud(binName: string, proc: FailLoudProcess = process
}
/**
* After the tree settles, reject entries with no fiber, which indicates a
* swallowed module-import failure. Disabled entries are the only valid
* After the tree settles, reject entries with no fiber and name every plugin
* whose module failed to resolve. Disabled entries are the only valid
* fiber-less state.
* @param ctx - the settled context whose loader entries to audit.
* @param binName - the diagnostic prefix on the thrown error.
@@ -152,7 +152,7 @@ export function assertEntriesLoaded(ctx: Context, binName: string): void {
const failed = [...ctx.loader.entries()].filter(entry => entry.fiber === undefined && !entry.disabled)
if (failed.length > 0) {
const names = failed.map(entry => entry.options.name).join(', ')
throw new Error(`${binName}: plugin(s) failed to load: ${names} (see the error(s) logged above)`)
throw new Error(`${binName}: plugin(s) failed to load: ${names}; Cordis startup failed because these plugin(s) could not be resolved (see the error(s) logged above)`)
}
}

View File

@@ -1,6 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
README.md: 8fd49723c4b0534eebd2e590c647caadd63136a7
README.zh.md: e2ad8ad80d002d769cf6a2c9f4f09c37ce960935
# pnpm run verify-translation-pairing --write packages/ui/commands/README.md
README.md: 4ad72cf9e232c8d41e525f42eecde5637032a391
README.zh.md: bace8f6346ac737a838d802dfc5c6ffe52c56edd

View File

@@ -8,7 +8,7 @@ Plugin-owned human-command registry consumed by interactive UI adapters. The [pl
`ctx.commands.register(definition)` registers one lowercase command name, description, optional unstructured-input hint, and abortable handler. A registered command is available to every composed command adapter; a plugin that is incompatible with a deployment does not register there. A plain-context registration is global. A command-producing plugin mounted beneath `agent.ctx` declares its own `commands` injection and creates an exact agent-scoped definition; it shadows a global definition with the same name. This child-injection shape preserves the agent scope without making the core agent loop depend on a UI service. Duplicate names within one layer fail during registration. Every disposer is the exact Cordis effect disposer, and registration or removal notifies every `commands/change` observer so live adapters can refresh discovery; observer failures are logged and cannot veto the registry mutation or starve later observers.
`list(agent)` returns immutable, name-sorted descriptors after scoped shadowing. `find(agent, name)` returns the corresponding definition. `execute(agent, line, signal)` uses `parseCommand()` and runs only a known command, returning `undefined` for invalid syntax or unknown names.
`list(agent)` returns immutable, name-sorted descriptors after scoped shadowing. `find(agent, name)` returns the corresponding definition. `execute(agent, line, signal)` uses `parseCommand()` and runs only a known command, returning the settled `CommandExecution` (the normalized result plus the lifecycle pairing `commandId`) or `undefined` for invalid syntax or unknown names. A resolved command's lifecycle is logged on the receiving agent's session as the log-only pair `command/run` (before the handler, with a minted `commandId`, the parser's structured `name`/`args` split, and the issuing `CommandSource`) and `command/done` (at settlement, with the outcome kind and verbatim text; a thrown or aborted handler settles as `kind: 'error'`). Admission misses log nothing. Both are direct standalone appends on the receiving agent's session: no turn wraps them, and persistence drains them through ordinary checkpoints and teardown.
`parseCommand()` recognizes a slash at byte zero, a lowercase name containing letters, digits, `_`, or `-`, and either end-of-input or whitespace. It returns every byte after the name as `rawInput`, including separator whitespace; consumers own their command-specific grammar and may normalize only what that grammar permits.
@@ -37,5 +37,4 @@ Registry metadata, command input, and direct output never enter a model request
## Known Limitations and Deferred Work
- **Only unstructured text input** — forms, completion schemas, and typed arguments remain command-owned parsing concerns.
- **No persisted command output** — adapters display results live, but the generic registry does not add them to the session log or reconstruct them after reconnect.
- **Cooperative side-effect cancellation** — dispatch stops awaiting on abort; handlers must honor the signal to stop work that has already escaped into external systems.

View File

@@ -8,7 +8,7 @@
`ctx.commands.register(definition)` 注册一个小写命令名称、描述、可选的非结构化输入提示,以及可中止的处理器。每个已注册命令都可供所有已组合的命令适配器使用;与某项部署不兼容的插件不会在此注册。普通上下文中的注册全局生效。在 `agent.ctx` 下挂载的命令生产插件会声明自身的 `commands` 注入,并创建精确限定到该 agent 的定义;该定义会遮蔽同名的全局定义。这种子级注入形态保留了 agent 作用域,同时不会让核心 agent loop 依赖 UI 服务。同一层中的名称重复会在注册时失败。每个 disposer 都是 Cordis effect 返回的确切 disposer注册或移除命令时系统会通知每个 `commands/change` 观察者,使实时适配器能够刷新发现结果。观察者失败会写入日志,既不能否决注册表变更,也不能阻止后续观察者运行。
`list(agent)` 在应用作用域遮蔽后,返回按名称排序的不可变描述符。`find(agent, name)` 返回相应定义。`execute(agent, line, signal)` 使用 `parseCommand()`,且只运行已知命令;语法无效或名称未知时返回 `undefined`
`list(agent)` 在应用作用域遮蔽后,返回按名称排序的不可变描述符。`find(agent, name)` 返回相应定义。`execute(agent, line, signal)` 使用 `parseCommand()`,且只运行已知命令,返回已结算的 `CommandExecution`(规范化结果加生命周期配对 `commandId`);语法无效或名称未知时返回 `undefined`。已解析命令的生命周期会以 log-only 事件对的形式记录在接收 agent 的会话日志中:`command/run`(进入处理器前记录,携带铸造的 `commandId`、解析器的结构化 `name`/`args` 切分和发起方 `CommandSource`)与 `command/done`(结算时记录,携带结局种类与原样文本;处理器抛出或被中止时以 `kind: 'error'` 结算)。未通过准入的输入不记录任何事件。两者都是直接独立追加:没有轮次包裹它们,持久化在常规检查点与 teardown 时排空它们
`parseCommand()` 识别位于字节零位置的斜杠、由小写字母、数字、`_``-` 构成的名称,以及名称后紧接输入末尾或空白的形式。它将名称后的每个字节作为 `rawInput` 返回,其中包括分隔空白;消费方拥有各命令专用的语法,只能执行该语法允许的规范化。
@@ -37,5 +37,4 @@
## 已知限制与延期工作
- **仅支持非结构化文本输入**:表单、补全 schema 和类型化参数仍由各命令自行解析。
- **不持久化命令输出**:适配器会实时显示结果,但通用注册表不会将结果加入会话日志,也不会在重新连接后重建结果。
- **副作用采用协作式取消**:中止后,分发会停止等待;处理器必须遵循信号,才能停止已经进入外部系统的工作。

View File

@@ -15,12 +15,17 @@
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./brand": {
"types": "./lib/types/brand.d.ts",
"default": "./lib/types/brand.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/types/**/*.js",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"src"
@@ -28,12 +33,15 @@
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-agent": "^0.0.1",
"@deepseek-ai/dsh-brand": "^0.0.1",
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-scope": "^0.0.1",
"@deepseek-ai/dsh-session": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"devDependencies": {
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-brand": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-scope": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",

View File

@@ -0,0 +1,29 @@
/**
* dsh-commands' owned branded id: command lifecycle pairing across the
* session log, the wire admission response, and client-side flow pairing.
*
* The `Branded<B>` primitive lives in `@deepseek-ai/dsh-brand`; this module
* is a pure type/constructor outlet (no cordis imports, no module
* augmentation) so wire and client programs can name the brand without
* loading the host plugin's Context merges — the `dsh-llm/brand` shape.
*
* @module @deepseek-ai/dsh-commands/brand
*/
import type { Branded } from '@deepseek-ai/dsh-brand'
/**
* Pairs one command execution's `command/run`/`command/done` lifecycle
* records with each other and with the `command.execute` admission response.
* Minted by the executor, monotonic per service instance.
*/
export type CommandId = Branded<'CommandId'>
/**
* Brand a string as a {@link CommandId}.
* @param id - the executor-minted pairing id.
* @returns the same string, branded; no validation is performed.
*/
export function CommandId(id: string): CommandId {
return id as CommandId
}

View File

@@ -7,11 +7,28 @@ import { Context, Service } from 'cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { NamedEntries, ScopedLayers } from '@deepseek-ai/dsh-scope'
import type { ScopeKey, ScopeLayer } from '@deepseek-ai/dsh-scope'
import type { Session, SessionEvent, SessionEventMap } from '@deepseek-ai/dsh-session'
import { CommandId } from './brand.ts'
export { CommandId } from './brand.ts'
export const name = 'commands'
const COMMAND_NAME = /^[a-z][a-z0-9_-]*$/u
/**
* Producer record for one command invocation (the `command/run` event's
* provenance slot). Merge-extensible sum type mirroring `MessageSourceMap`'s
* shape; minimal today because every executor caller is a human-facing UI
* surface dispatching a human-typed line, so the sole variant is `user`.
*/
export interface CommandSourceMap {
user: { kind: 'user' }
}
/** The union over {@link CommandSourceMap} — who issued a command line. */
export type CommandSource = CommandSourceMap[keyof CommandSourceMap]
/** Immutable metadata for a command's optional unstructured input. */
export interface CommandInputDescriptor {
/** Placeholder shown before the user supplies free-form input. */
@@ -33,6 +50,19 @@ export type CommandResult =
| { readonly kind: 'success'; readonly text?: string }
| { readonly kind: 'error'; readonly text: string }
/**
* One settled command execution: the handler's normalized result plus the
* lifecycle pairing id minted for its `command/run`/`command/done` records,
* so a dispatching surface can correlate the RPC-level acknowledgment with
* the flow node those events produce.
*/
export interface CommandExecution {
/** Pairing id carried by this execution's lifecycle events. */
readonly commandId: CommandId
/** The handler's normalized outcome. */
readonly result: CommandResult
}
/** Plugin-owned command registration. */
export interface CommandDefinition {
/** Lowercase command name without the leading slash. */
@@ -88,6 +118,27 @@ class CommandLayer implements ScopeLayer {
}
}
declare module '@deepseek-ai/dsh-session' {
interface SessionEventMap {
/**
* A resolved slash command entered its handler. Log-only (never model
* surface); paired with `command/done` by `commandId`, mirroring the
* `tool/call`↔`tool/result` pairing. The payload is structured — `name`
* and `args` are `parseCommand`'s own split (name and verbatim rawInput,
* separator whitespace included), so a consumer (a projection unit
* folding its own command records, a rich command card) never re-parses
* a line.
*/
'command/run': { commandId: CommandId; name: string; args: string; source: CommandSource }
/**
* The paired command settled. `kind`/`text` carry the handler's verbatim
* outcome (a thrown/aborted handler settles as `kind: 'error'` with the
* rendered failure); presentation stays client-computed at render time.
*/
'command/done': { commandId: CommandId; kind: 'success' | 'error'; text?: string }
}
}
declare module 'cordis' {
interface Context {
commands: CommandService
@@ -230,6 +281,11 @@ export class CommandService extends Service {
() => { this.notifyChange() },
)
/** Monotonic per-instance counter behind {@link mintCommandId}. */
private commandSeq = 0
/** Instance token keeping minted ids unique across process restarts over one resumed log. */
private readonly instanceToken = crypto.randomUUID().slice(0, 8)
constructor(ctx: Context) {
super(ctx, 'commands')
}
@@ -272,24 +328,82 @@ export class CommandService extends Service {
/**
* Parse and execute a known command without sending it to the model.
*
* A resolved command's lifecycle is logged: `command/run` is appended
* before the handler is invoked and `command/done` after settlement (a
* thrown or aborted handler settles as `kind: 'error'`). Both are direct
* log-only appends — no turn wraps them, and persistence drains them at
* ordinary checkpoints. Admission misses (syntax or unknown name) log
* nothing — they never entered a handler. A `command/run` append failure
* fails the execution loud; a `command/done` append failure on the
* handler-failure path is contained so the handler's own error stays the
* reported failure.
*
* @param agent - exact receiving agent.
* @param line - complete slash-command line.
* @param signal - cancellation signal owned by the UI request.
* @returns a detached result, or `undefined` when syntax or name does not resolve.
* @returns the settled execution (result + lifecycle pairing id), or
* `undefined` when syntax or name does not resolve.
*/
async execute(
agent: Agent,
line: string,
signal: AbortSignal,
): Promise<CommandResult | undefined> {
): Promise<CommandExecution | undefined> {
const parsed = parseCommand(line)
if (parsed === undefined) return undefined
const command = this.view(agent).get(parsed.name)
if (command === undefined) return undefined
if (signal.aborted) throw abortError(signal)
const commandId = this.mintCommandId()
this.appendLifecycle(agent.session, 'command/run', {
commandId, name: parsed.name, args: parsed.rawInput, source: { kind: 'user' },
})
const invocation = Object.freeze({ agent, rawInput: parsed.rawInput, signal })
const output = command.definition.handler(invocation)
return normalizeResult(parsed.name, await withAbort(Promise.resolve(output), signal))
let result: CommandResult
try {
const output = command.definition.handler(invocation)
result = normalizeResult(parsed.name, await withAbort(Promise.resolve(output), signal))
} catch (error: unknown) {
try {
this.appendLifecycle(agent.session, 'command/done', {
commandId, kind: 'error',
text: error instanceof Error ? error.message : renderThrown(error),
})
} catch (appendError: unknown) {
this.ctx.logger.warn(`command "${parsed.name}": command/done append failed: ${renderThrown(appendError)}`)
}
throw error
}
this.appendLifecycle(agent.session, 'command/done', {
commandId, kind: result.kind,
...result.text === undefined ? {} : { text: result.text },
})
return Object.freeze({ commandId, result })
}
/** Mint the next pairing id (monotonic; instance-token-prefixed so a resumed log never repeats one). */
private mintCommandId(): CommandId {
this.commandSeq += 1
return CommandId(`cmd-${this.instanceToken}-${this.commandSeq}`)
}
/**
* Append one log-only lifecycle event directly: no turn is opened for it and
* no flush is forced — persistence observes the eager `session/event` path
* and drains at ordinary checkpoints and teardown, like every other
* standalone plugin event.
*/
private appendLifecycle<T extends 'command/run' | 'command/done'>(
session: Session,
type: T,
data: SessionEventMap[T],
): SessionEvent<T> {
// Both admitted types are log-only (non-surface), but TypeScript does not
// reduce Session.append's conditional rest parameter through a generic
// type parameter. Preserve the proven two-argument call shape.
const appendLogOnly = session.append.bind(session) as (eventType: T, eventData: SessionEventMap[T]) => SessionEvent<T>
return appendLogOnly(type, data)
}
/** Resolve global definitions followed by exact scoped shadows. */

View File

@@ -1,11 +1,12 @@
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-commands`.
* Package-owned invariant companion for `@deepseek-ai/dsh-commands`:
* command lifecycle events pair by commandId within one session log.
* @module @deepseek-ai/dsh-commands/invariant
*/
/* jscpd:ignore-start */
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-commands'
@@ -14,11 +15,36 @@ export const name = 'commands-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/**
* No runtime invariant: registry notifications intentionally hide mutation details and contain
* observers, so list/find self-comparisons would duplicate implementation rather than detect drift.
*/
const install: InvariantInstaller = () => {}
/* jscpd:ignore-start -- package companions share replay and dispatch plumbing */
/** Install pairing validation over loaded logs and newly appended lifecycle events. */
const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
// Install-scoped so a dispose/re-register cycle re-sweeps from a clean slate.
const runIds = new WeakMap<Session, Set<string>>()
const validateEvent = (session: Session, event: SessionEvent): void => {
if (event.type === 'command/run') {
const ids = runIds.get(session) ?? new Set<string>()
if (ids.has(event.data.commandId)) {
fail(`command/run repeats commandId ${JSON.stringify(event.data.commandId)}`)
}
ids.add(event.data.commandId)
runIds.set(session, ids)
return
}
if (event.type !== 'command/done') return
if (runIds.get(session)?.has(event.data.commandId) !== true) {
fail(`command/done ${JSON.stringify(event.data.commandId)} pairs no prior command/run in this log`)
}
}
for (const session of ctx.sessions.list()) {
for (const event of session.events) validateEvent(session, event)
}
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const [session, event] = args as [Session, SessionEvent]
validateEvent(session, event)
}, { global: true })
}, { inject: ['sessions'] })
/* jscpd:ignore-end */
/**
* Register this package's invariant companion.
@@ -27,4 +53,3 @@ const install: InvariantInstaller = () => {}
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -3,7 +3,7 @@ import { Context } from 'cordis'
import { createScope } from '@deepseek-ai/dsh-scope'
import type { Scope } from '@deepseek-ai/dsh-scope'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { SessionId } from '@deepseek-ai/dsh-session'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import CommandService, { parseCommand, type CommandDefinition } from '@deepseek-ai/dsh-commands'
function command(name: string, text = `ran:${name}`): CommandDefinition {
@@ -16,18 +16,27 @@ function command(name: string, text = `ran:${name}`): CommandDefinition {
async function mount(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(CommandService)
return ctx
}
/** Mint a scope whose key is sufficient for registry lookup and invocation. */
/** Mint a scope whose key is a live agent (real session: the executor logs lifecycle events on it). */
async function mintAgentScope(ctx: Context, name: string): Promise<{ scope: Scope; agent: Agent }> {
const agent = { id: name as SessionId } as Agent
const session = ctx.sessions.create(SessionId(name))
const agent = { id: session.id, session } as Agent
let scope!: Scope
await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, { inject: ['commands'] }))
return { scope, agent }
}
/** The lifecycle slice of one agent's log (boundary markers stripped). */
function lifecycleOf(agent: Agent): Array<{ type: string; data: unknown }> {
return agent.session.events
.filter(event => event.type === 'command/run' || event.type === 'command/done')
.map(event => ({ type: event.type, data: event.data }))
}
describe('parseCommand()', () => {
it.each([
['/goal', { name: 'goal', rawInput: '' }],
@@ -87,11 +96,11 @@ describe('CommandService', () => {
expect(ctx.commands.list(agent).map(item => item.name)).toEqual(['shared'])
expect(ctx.commands.find(agent, 'shared')?.handler).toBeDefined()
expect(ctx.commands.list(other).map(item => item.name)).toEqual(['shared'])
expect(await ctx.commands.execute(agent, '/shared', new AbortController().signal))
expect((await ctx.commands.execute(agent, '/shared', new AbortController().signal))?.result)
.toEqual({ kind: 'success', text: 'scoped' })
await scope.dispose()
expect((await ctx.commands.execute(agent, '/shared', new AbortController().signal))?.text).toBe('global')
expect((await ctx.commands.execute(agent, '/shared', new AbortController().signal))?.result.text).toBe('global')
})
it('removes a registration when its contributing plugin fiber is disposed', async () => {
@@ -167,10 +176,12 @@ describe('CommandService', () => {
ctx.commands.register({ name: 'run', description: 'Run it', handler: seen })
const controller = new AbortController()
const result = await ctx.commands.execute(agent, '/run untouched ', controller.signal)
const execution = await ctx.commands.execute(agent, '/run untouched ', controller.signal)
expect(result).toEqual({ kind: 'success', text: 'ok' })
expect(Object.isFrozen(result)).toBe(true)
expect(execution?.result).toEqual({ kind: 'success', text: 'ok' })
expect(execution?.commandId).toBeTruthy()
expect(Object.isFrozen(execution)).toBe(true)
expect(Object.isFrozen(execution?.result)).toBe(true)
expect(seen).toHaveBeenCalledWith(expect.objectContaining({
agent,
rawInput: ' untouched ',
@@ -262,9 +273,9 @@ describe('CommandService', () => {
description: 'Denied',
handler: () => ({ kind: 'error', text: 'not now' }),
})
const result = await ctx.commands.execute(agent, '/denied', new AbortController().signal)
expect(result).toEqual({ kind: 'error', text: 'not now' })
expect(Object.isFrozen(result)).toBe(true)
const execution = await ctx.commands.execute(agent, '/denied', new AbortController().signal)
expect(execution?.result).toEqual({ kind: 'error', text: 'not now' })
expect(Object.isFrozen(execution?.result)).toBe(true)
ctx.commands.register({
name: 'silent',
@@ -272,8 +283,8 @@ describe('CommandService', () => {
handler: () => ({ kind: 'success' }),
})
const silent = await ctx.commands.execute(agent, '/silent', new AbortController().signal)
expect(silent).toEqual({ kind: 'success' })
expect(Object.isFrozen(silent)).toBe(true)
expect(silent?.result).toEqual({ kind: 'success' })
expect(Object.isFrozen(silent?.result)).toBe(true)
})
it.each([
@@ -286,6 +297,112 @@ describe('CommandService', () => {
expect(() => ctx.commands.register(definition as unknown as CommandDefinition)).toThrow(expected)
})
it('logs a paired command/run + command/done around a successful handler', async () => {
const ctx = await mount()
const { agent } = await mintAgentScope(ctx, 'a')
ctx.commands.register(command('deploy', 'deployed'))
const execution = await ctx.commands.execute(agent, '/deploy now', new AbortController().signal)
const lifecycle = lifecycleOf(agent)
expect(lifecycle).toMatchObject([
{ type: 'command/run', data: { name: 'deploy', args: ' now', source: { kind: 'user' } } },
{ type: 'command/done', data: { kind: 'success', text: 'deployed' } },
])
const ids = lifecycle.map(event => (event.data as { commandId: string }).commandId)
expect(ids[0]).toBeTruthy()
expect(ids[0]).toBe(ids[1])
// The execution's pairing id is the logged one (RPC-level correlation).
expect(execution?.commandId).toBe(ids[0])
// Direct log-only appends: no turn is opened for the pair on an idle log.
expect(agent.session.events.map(event => event.type)).toEqual([
'command/run', 'command/done',
])
})
it('mints distinct monotonic commandIds across executions', async () => {
const ctx = await mount()
const { agent } = await mintAgentScope(ctx, 'a')
ctx.commands.register(command('first'))
ctx.commands.register(command('second'))
await ctx.commands.execute(agent, '/first', new AbortController().signal)
await ctx.commands.execute(agent, '/second', new AbortController().signal)
const ids = lifecycleOf(agent)
.filter(event => event.type === 'command/run')
.map(event => (event.data as { commandId: string }).commandId)
expect(new Set(ids).size).toBe(2)
})
it('logs command/done kind error for an expected error result', async () => {
const ctx = await mount()
const { agent } = await mintAgentScope(ctx, 'a')
ctx.commands.register({ name: 'denied', description: 'Denied', handler: () => ({ kind: 'error', text: 'not now' }) })
await ctx.commands.execute(agent, '/denied', new AbortController().signal)
expect(lifecycleOf(agent)).toMatchObject([
{ type: 'command/run', data: { name: 'denied' } },
{ type: 'command/done', data: { kind: 'error', text: 'not now' } },
])
})
it('logs command/done kind error when the handler throws, and preserves the throw', async () => {
const ctx = await mount()
const { agent } = await mintAgentScope(ctx, 'a')
ctx.commands.register({
name: 'boom',
description: 'Throw',
handler: () => { throw new Error('handler exploded') },
})
await expect(ctx.commands.execute(agent, '/boom', new AbortController().signal))
.rejects.toThrow('handler exploded')
expect(lifecycleOf(agent)).toMatchObject([
{ type: 'command/run', data: { name: 'boom' } },
{ type: 'command/done', data: { kind: 'error', text: 'handler exploded' } },
])
})
it('logs command/done kind error when the signal aborts a hanging handler', async () => {
const ctx = await mount()
const { agent } = await mintAgentScope(ctx, 'a')
ctx.commands.register({
name: 'hang',
description: 'Hang',
handler: () => new Promise(() => undefined),
})
const controller = new AbortController()
const pending = ctx.commands.execute(agent, '/hang', controller.signal)
// The run append must land before the abort so the pair stays complete.
await vi.waitFor(() => { expect(lifecycleOf(agent)).toHaveLength(1) })
controller.abort('operator cancelled command')
await expect(pending).rejects.toThrow('operator cancelled command')
await vi.waitFor(() => {
expect(lifecycleOf(agent)).toMatchObject([
{ type: 'command/run', data: { name: 'hang' } },
{ type: 'command/done', data: { kind: 'error', text: 'operator cancelled command' } },
])
})
})
it('logs nothing for admission misses (syntax or unknown name)', async () => {
const ctx = await mount()
const { agent } = await mintAgentScope(ctx, 'a')
ctx.commands.register(command('real'))
const signal = new AbortController().signal
await ctx.commands.execute(agent, 'not a command', signal)
await ctx.commands.execute(agent, '/missing', signal)
expect(agent.session.events).toEqual([])
})
it('joins an open turn without wrapping the lifecycle pair in synthetic turns', async () => {
const ctx = await mount()
const { agent } = await mintAgentScope(ctx, 'a')
ctx.commands.register(command('mid'))
agent.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
await ctx.commands.execute(agent, '/mid', new AbortController().signal)
expect(agent.session.events.map(event => event.type)).toEqual([
'turn/start', 'command/run', 'command/done',
])
})
it.each([
[undefined, /CommandResult/],
[null, /CommandResult/],

View File

@@ -20,6 +20,12 @@
{
"path": "../../core/scope"
},
{
"path": "../../core/session"
},
{
"path": "../../util/brand"
},
{
"path": "../../support/invariants"
}

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/ui/jsonrpc/README.md
README.md: 48eb6106fe4b015f114b264a312249a92128266f
README.zh.md: 8ec2d57a206d770d0b77ee69036457e3b2864303
README.md: b1219ba10269fc7d046da22c280ff1b91424a5ae
README.zh.md: 63615654769bf4ed7a69c09dc818af034c3a3c3c

View File

@@ -22,7 +22,7 @@ The plugin answers `shutdown`, disposes SDK-owned agents and subscriptions to qu
## Wire notes
`initialize.serverInfo.name` is the wire-stable `deepseek-harness-sdk-runtime`. A session accepts one in-flight prompt; overlap fails immediately, other sessions remain independent, and the session is reusable after settlement. `session.finished` reports that prompt's message-triggered turn outcome; later between-turn records still stream as `session.event` notifications but cannot replace the prompt status. Persistence roots and persona come from `cordis.yml`.
`initialize.serverInfo.name` is the wire-stable `deepseek-harness-sdk-runtime`. An optional positive `initialize.maxTokens` becomes the request output cap of each SDK-created agent and its in-process descendants; invalid values reject initialization, while omission sends no cap and preserves provider defaults. A session accepts one in-flight prompt; overlap fails immediately, other sessions remain independent, and the session is reusable after settlement. `session.finished` reports that prompt's message-triggered turn outcome; later between-turn records still stream as `session.event` notifications but cannot replace the prompt status. Persistence roots and persona come from `cordis.yml`.
## Model Experience

View File

@@ -22,7 +22,7 @@ Stdout 只承载 JSON-RPC 帧。部署不得组合 stdout logger诊断应写
## 协议说明
`initialize.serverInfo.name` 的协议稳定值为 `deepseek-harness-sdk-runtime`。一个会话只接受一个进行中的提示词;重叠请求会立即失败,其他会话保持独立,当前请求结算后该会话可再次使用。`session.finished` 报告由该提示词消息触发的轮次结果;后续轮次间记录仍会作为 `session.event` 通知流式发出,但不能替换该提示词的状态。持久化根目录和 persona 由 `cordis.yml` 提供。
`initialize.serverInfo.name` 的协议稳定值为 `deepseek-harness-sdk-runtime`可选的正整数 `initialize.maxTokens` 会成为每个 SDK 创建的 agent 及其进程内后代的请求输出上限;非法值会使初始化失败,省略时则不发送上限并保留提供方默认值。一个会话只接受一个进行中的提示词;重叠请求会立即失败,其他会话保持独立,当前请求结算后该会话可再次使用。`session.finished` 报告由该提示词消息触发的轮次结果;后续轮次间记录仍会作为 `session.event` 通知流式发出,但不能替换该提示词的状态。持久化根目录和 persona 由 `cordis.yml` 提供。
## 模型体验

View File

@@ -8,6 +8,7 @@
import type { Context } from 'cordis'
import { resolve } from 'node:path'
import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { carrierKeyOf, type Scoped } from '@deepseek-ai/dsh-scope'
import { findLastMessageTurnEnd, SessionId, type TurnEndReason } from '@deepseek-ai/dsh-session'
import type SubagentService from '@deepseek-ai/dsh-subagent'
@@ -56,6 +57,7 @@ export class HarnessSdkServer {
private cwd = process.cwd()
private provider = 'deepseek'
private model = 'deepseek'
private maxTokens: number | undefined
private llmFiber: { dispose(): Promise<void> } | undefined
private readonly sessions = new Map<string, SessionRecord>()
private readonly sessionCreations = new Map<string, Promise<SessionRecord>>()
@@ -113,9 +115,14 @@ export class HarnessSdkServer {
* @returns server identity for the handshake.
*/
async initialize(params: InitializeParams): Promise<InitializeResult> {
if (params.maxTokens !== undefined
&& (!Number.isSafeInteger(params.maxTokens) || params.maxTokens <= 0)) {
throw new TypeError('initialize maxTokens must be a positive safe integer')
}
this.cwd = resolve(params.cwd)
this.provider = params.provider
this.model = params.model
this.maxTokens = params.maxTokens
if (!this.hasAdapterFor(this.provider)) {
if (this.provider !== 'deepseek') throw new Error(`no adapter registered for provider "${this.provider}"`)
this.llmFiber = await this.ctx.plugin(LlmDeepSeek, {})
@@ -140,7 +147,7 @@ export class HarnessSdkServer {
rec.activePrompt = true
try {
rec.lastTurnEnd = undefined
rec.handle.agent.followup({ content: params.contentBlocks, source: { kind: 'user' } })
rec.handle.agent.followup(createUserMessage({ content: params.contentBlocks, source: { kind: 'user' } }))
await rec.handle.agent.whenIdle()
const payload: SessionFinishedNotification = {
sessionId: params.sessionId,
@@ -231,7 +238,11 @@ export class HarnessSdkServer {
const handle = await this.ctx.agents.create({
sessionId: SessionId(sessionId),
meta: { cwd: this.cwd },
agentOptions: { provider: this.provider, model: this.model },
agentOptions: {
provider: this.provider,
model: this.model,
...this.maxTokens === undefined ? {} : { maxTokens: this.maxTokens },
},
})
const rec: SessionRecord = { handle, lastTurnEnd: undefined, activePrompt: false }
this.sessions.set(sessionId, rec)

View File

@@ -1,3 +1,4 @@
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { createServer } from 'node:http'
import type { IncomingMessage, Server, ServerResponse } from 'node:http'
import { mkdtemp, rm } from 'node:fs/promises'
@@ -5,9 +6,9 @@ import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import AgentRegistry, { AgentMessageId, type Agent, type AgentHandle } from '@deepseek-ai/dsh-agent'
import AgentRegistry, { type Agent, type AgentHandle } from '@deepseek-ai/dsh-agent'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import SessionStore, { SessionId, type UserMessage } from '@deepseek-ai/dsh-session'
import * as agentCore from '@deepseek-ai/dsh-agent-spine-demo'
import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek'
@@ -122,6 +123,7 @@ describe('HarnessSdkServer', () => {
cwd: storageDir,
provider: 'deepseek',
model: 'dsagent-model',
maxTokens: 321,
}) as { serverInfo: { name: string } }
expect(init.serverInfo.name).toBe('deepseek-harness-sdk-runtime')
@@ -131,8 +133,9 @@ describe('HarnessSdkServer', () => {
})
expect(llmServer.requests).toHaveLength(1)
const body = llmServer.requests[0] as { model: string; messages: { role: string }[] }
const body = llmServer.requests[0] as { model: string; messages: { role: string }[]; max_tokens?: number }
expect(body.model).toBe('dsagent-model')
expect(body.max_tokens).toBe(321)
expect(body.messages[0]?.role).toBe('system')
expect(body.messages.at(-1)?.role).toBe('user')
expect(llmServer.headers[0]?.authorization).toBe('Bearer test-key')
@@ -153,7 +156,7 @@ describe('HarnessSdkServer', () => {
meta: { cwd: storageDir },
agentOptions: { provider: 'deepseek', model: 'dsagent-model' },
})
orphanHandle.agent.followup({ content: [{ type: 'text', text: 'outside the sdk session map' }], source: { kind: 'user' } })
orphanHandle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'outside the sdk session map' }], source: { kind: 'user' } }))
await orphanHandle.agent.whenIdle()
await orphanHandle.dispose()
expect(llmServer.requests).toHaveLength(3)
@@ -171,13 +174,13 @@ describe('HarnessSdkServer', () => {
const mainWhenIdle = vi.fn<() => Promise<void>>()
.mockReturnValueOnce(firstMainIdle)
.mockResolvedValue(undefined)
const mainFollowup = vi.fn<Agent['followup']>().mockReturnValue(AgentMessageId('main-followup'))
const mainFollowup = vi.fn<Agent['followup']>()
const mainAgent = ({
id: SessionId('main'),
followup: mainFollowup,
whenIdle: mainWhenIdle,
} satisfies Pick<Agent, 'id' | 'followup' | 'whenIdle'>) as unknown as Agent
const otherFollowup = vi.fn<Agent['followup']>().mockReturnValue(AgentMessageId('other-followup'))
const otherFollowup = vi.fn<Agent['followup']>()
const otherAgent = ({
id: SessionId('other'),
followup: otherFollowup,
@@ -220,7 +223,7 @@ describe('HarnessSdkServer', () => {
})
it('rejects a prompt for a session whose agent was disposed outside the server', async () => {
const followup = vi.fn<Agent['followup']>().mockReturnValue(AgentMessageId('stub'))
const followup = vi.fn<Agent['followup']>()
const agent = ({
id: SessionId('zombie'),
followup,
@@ -266,7 +269,7 @@ describe('HarnessSdkServer', () => {
const agent = ({
id: SessionId('message-outcome'),
session,
followup(input: { content: { type: 'text'; text: string }[]; source: { kind: 'user' } }) {
followup(input: UserMessage) {
session.append('turn/start', {
turn: 1,
trigger: { kind: 'message', source: input.source },
@@ -277,12 +280,12 @@ describe('HarnessSdkServer', () => {
turn: 2,
trigger: { kind: 'injection', source: { kind: 'plugin', plugin: 'late-metadata' } },
})
session.append('user/message', {
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'late metadata' }],
source: { kind: 'plugin', plugin: 'late-metadata' },
}, { surfaceOp: 'append' })
}), { surfaceOp: 'append' })
session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
return AgentMessageId('message-outcome')
return input.id
},
whenIdle: () => Promise.resolve(),
} satisfies Pick<Agent, 'id' | 'session' | 'followup' | 'whenIdle'>) as unknown as Agent
@@ -859,6 +862,27 @@ describe('HarnessSdkServer', () => {
}
})
it.each([0, -1, 1.5, Number.NaN, Number.MAX_SAFE_INTEGER + 1])(
'rejects invalid initialize maxTokens %s at the wire boundary',
async (maxTokens) => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-invalid-max-tokens-'))
const ctx = await makeHarness(storageDir)
try {
const server = new HarnessSdkServer(ctx, new FakeTransport())
await expect(server.initialize({
cwd: storageDir,
provider: 'deepseek',
model: 'model',
maxTokens,
})).rejects.toThrow('initialize maxTokens must be a positive safe integer')
await server.shutdown()
} finally {
await ctx.fiber.dispose()
await rm(storageDir, { recursive: true, force: true })
}
},
)
it('classifies defensive finish states', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-finish-states-'))
const ctx = await makeHarness(storageDir)
@@ -973,15 +997,18 @@ describe('HarnessSdkServer', () => {
get: () => ({ listProviders: () => [{ id: 'mock', name: 'Mock' }] }),
} as unknown as Context
const server = new HarnessSdkServer(ctx, new FakeTransport()) as unknown as {
initialize(params: { cwd: string; provider: string; model: string }): Promise<unknown>
initialize(params: { cwd: string; provider: string; model: string; maxTokens?: number }): Promise<unknown>
getOrCreateSession(sessionId: string): Promise<unknown>
shutdown(): Promise<Record<string, never>>
}
await server.initialize({ cwd: '.', provider: 'mock', model: 'model' })
await server.initialize({ cwd: '.', provider: 'mock', model: 'model', maxTokens: 123 })
await server.getOrCreateSession('relative')
expect(create).toHaveBeenCalledWith(expect.objectContaining({ meta: { cwd: process.cwd() } }))
expect(create).toHaveBeenCalledWith(expect.objectContaining({
meta: { cwd: process.cwd() },
agentOptions: { provider: 'mock', model: 'model', maxTokens: 123 },
}))
await server.shutdown()
})

View File

@@ -1,6 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
README.md: 6a59ad9425bf5bfeb89e9798304a2eb90ee55bfa
README.zh.md: 0e7db1bd41a15ac4be18d33db7b9011a5bc24e7e
# pnpm run verify-translation-pairing --write packages/ui/permission/README.md
README.md: 814085ed6f2c9650854f377e1c97e442fc4211a4
README.zh.md: 36880d6b8c3f0b39b88db1abb02534f30e3355fa

View File

@@ -8,6 +8,8 @@ User-facing permission presets through `ctx.permission` ([`PermissionService`](s
The service requires a confining `ctx.bash` executor and `ctx.approval`. A table entry named `custom` throws at load; composition defaults outside the table instead make a zero-event session derive `custom`. See the [sandbox switching design](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md).
Two optional children ship the product surfaces over the same service: a `permissions` session-projection unit (`src/types.ts` declares the key; the unit folds the three whole-value knob events and views the select — table options plus a current-only `custom` — over the composition defaults) and the `/permission` command (bare invocation reports the current preset and the table; a preset argument switches through `set`). Each child activates only when its registry (`ctx.sessionProjections` / `ctx.commands`) is composed.
## Model Experience
Indirectly, through `dsh-user-approval` and `dsh-tool-bash`, which render the approval-policy prompt, switch notice, and sandboxed tool outcomes selected by this service's knob events; `permission/preset` itself is log-only.
@@ -18,7 +20,6 @@ No direct invalidation; the named consumer owns any request-prefix changes.
## Known Limitations and Deferred Work
- **No shipped composition currently mounts the service** — the ACP bridge was its only selector before [ACP became automation-only](../../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md); the preset table is kept for the interactive front door that next exposes a runtime policy switch.
- **Only two mechanism knobs are bundled** — presets select sandbox mode and approval policy; an agent/profile choice is not part of `PresetSpec` yet.
- **`custom` is derived-only** — callers can switch away from an unmatched knob combination but cannot target or persist a named custom preset through this service.
- **The preset table is process-level** — configuration is fixed for the plugin lifetime; changing available presets requires reloading the plugin.

View File

@@ -8,6 +8,8 @@
该服务要求存在具有约束能力的 `ctx.bash` 执行器和 `ctx.approval`。表中名为 `custom` 的条目会在加载时抛出异常;如果组合在表外指定默认值,则零事件会话会推导出 `custom`。详见[沙箱切换设计](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md)。
两个可选子件在同一服务之上交付产品界面:`permissions` 会话投影单元(`src/types.ts` 声明该 key单元折叠三个全量值旋钮事件在组合默认值之上视图出 select——表内选项加仅作当前值的 `custom`)与 `/permission` 命令(裸调用报告当前预设与表;预设参数经 `set` 切换)。每个子件仅在其注册表(`ctx.sessionProjections` / `ctx.commands`)被组合时激活。
## 模型体验
间接地,通过 `dsh-user-approval``dsh-tool-bash`:二者会渲染由此服务的调节项事件所选择的审批策略提示词、切换通知和沙箱工具结果;`permission/preset` 本身只写入日志。
@@ -18,7 +20,6 @@
## 已知限制与延期工作
- **当前没有已交付的组合挂载此服务**:在 [ACP 变为仅用于自动化](../../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md)之前ACP 桥接层是唯一的选择器preset 表为下一个公开运行时策略切换的交互式入口保留。
- **只组合两个机制调节项**preset 选择沙箱模式和审批策略agent智能体profile 选择尚未纳入 `PresetSpec`
- **`custom` 只能推导得出**:调用方可以从不匹配的调节项组合切换出去,但无法通过此服务选中或持久化一个具名 custom preset。
- **preset 表位于进程级别**:配置在插件生命周期内固定;更改可用 preset 必须重新加载插件。

View File

@@ -15,12 +15,21 @@
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./types": {
"types": "./lib/types/types.d.ts",
"default": "./lib/types/types.js"
},
"./client": {
"types": "./lib/types/client.d.ts",
"default": "./lib/types/client.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/types/**/*.js",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"src"
@@ -28,22 +37,27 @@
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-bash": "^0.0.1",
"@deepseek-ai/dsh-commands": "^0.0.1",
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-sandbox": "^0.0.1",
"@deepseek-ai/dsh-sandbox-policy": "^0.0.1",
"@deepseek-ai/dsh-session": "^0.0.1",
"@deepseek-ai/dsh-session-projection": "^0.0.1",
"@deepseek-ai/dsh-user-approval": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"dependencies": {
"schemastery": "^3.18.0"
"schemastery": "^3.18.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@deepseek-ai/dsh-bash": "workspace:^",
"@deepseek-ai/dsh-commands": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-sandbox": "workspace:^",
"@deepseek-ai/dsh-sandbox-policy": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-session-projection": "workspace:^",
"@deepseek-ai/dsh-user-approval": "workspace:^",
"cordis": "^4.0.0-rc.7"
}

View File

@@ -0,0 +1,10 @@
/**
* Client-namespace projection of the permission domain: a pure re-export of
* the package's types outlet. Client code imports ONLY the client namespace
* (repo discipline), so `./client` projects the same single-source content
* `./types` serves to host consumers — zero duplication.
*
* @module @deepseek-ai/dsh-permission/client
*/
export type * from './types.ts'

View File

@@ -3,13 +3,16 @@
* approval-policy knobs. A switch records the selected preset, then writes
* changed knobs through their canonical setters. Execution, prompt narration,
* and replay keep reading their knob folds. The preset event preserves user
* intent when two presets share a bundle.
* intent when two presets share a bundle. The read side ships as the
* `permissions` session projection; the write side ships as the
* `/permission` command — both optional children over the same service.
*
* @module dsh-permission
*/
import { Context, Service } from 'cordis'
import z from 'schemastery'
import { z as zod } from 'zod'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
import { SANDBOX_MODES, effectiveSandboxMode, setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy'
@@ -18,6 +21,16 @@ import { SANDBOX_MODES, effectiveSandboxMode, setSandboxMode } from '@deepseek-a
import type {} from '@deepseek-ai/dsh-bash'
import type { ApprovalPolicy } from '@deepseek-ai/dsh-user-approval'
import { APPROVAL_POLICIES, effectiveApprovalPolicy, setApprovalPolicy } from '@deepseek-ai/dsh-user-approval'
// Type-only: resolves ctx.sessionProjections / ctx.commands for the optional children.
import type {} from '@deepseek-ai/dsh-session-projection'
import type {} from '@deepseek-ai/dsh-commands'
import type { PermissionSelect, PresetOption } from './types.ts'
// The `permissions` projection-key declaration lives in src/types.ts (its one
// home); this re-export projects the type face onto the package root AND
// keeps the module edge in the emitted index.d.ts, so aggregate programs
// consuming the declarations still receive the SessionProjectionMap merge.
export type * from './types.ts'
declare module 'cordis' {
interface Context {
@@ -49,16 +62,6 @@ export interface PresetSpec {
description?: string
}
/** The select-option shape a presentation layer advertises for one preset (or for the derived `custom` state). */
export interface PresetOption {
/** Stable option value: the table key, or `custom`. */
value: string
/** The display label. */
name: string
/** One user-facing sentence on what the value means. */
description?: string
}
/**
* Returned when effective knob values match no table entry. Clients may show
* it as the current value, but it is never a switch target or event payload.
@@ -79,6 +82,50 @@ export function effectivePermissionPreset(events: readonly SessionEvent[]): stri
return undefined
}
/**
* The projection unit's state: the last seen value of each knob event, null
* before an override (composition defaults apply at view time). Plain JSON
* (persisted-cache precondition).
*/
export interface KnobState {
/** Last `permission/preset` payload, or null. */
preset: string | null
/** Last `sandbox/mode` payload, or null. */
sandbox: SandboxMode | null
/** Last `approval/policy` payload, or null. */
approval: ApprovalPolicy | null
}
/** State for the empty log: every knob at its composition default. */
const EMPTY_KNOBS: KnobState = { preset: null, sandbox: null, approval: null }
/**
* One-event knob transition (the projection unit's `apply`). Uninterested
* events return the same reference — the registry's change gate.
* @param state - the folded knob state before `event`.
* @param event - one committed session event.
* @returns the next state; the same reference when the event is not a knob.
*/
export function applyKnobEvent(state: KnobState, event: SessionEvent): KnobState {
switch (event.type) {
case 'permission/preset':
return { ...state, preset: event.data.preset }
case 'sandbox/mode':
return { ...state, sandbox: event.data.mode }
case 'approval/policy':
return { ...state, approval: event.data.policy }
default:
return state
}
}
/** Whole-log knob fold (the cold-read parallel of {@link applyKnobEvent}). */
function foldKnobs(events: readonly SessionEvent[]): KnobState {
let state = EMPTY_KNOBS
for (const event of events) state = applyKnobEvent(state, event)
return state
}
/** The {@link PermissionService} config: the deployment's preset table. */
export interface Config {
/**
@@ -128,6 +175,55 @@ export class PermissionService extends Service {
if (ctx.bash.sandboxMode === undefined) {
throw new Error('permission: the mounted bash executor does not confine (no sandboxMode) — presets bundle a sandbox mode, so composing this plugin over an unconfined executor is a misconfiguration')
}
// The permissions projection unit: fold the three whole-value knob
// events; view derives the select over the composition defaults this
// service already owns. The unit child activates only when a projection
// registry is composed (headless assemblies stay unaffected).
// zod `.optional()` types the key `string | undefined` while the domain
// says `description?: string`; on the JSON wire the two serialize
// identically (absent), so the cast records exactly that
// exactOptionalPropertyTypes widening (the Wire<T> precedent).
const selectSchema = zod.object({
options: zod.array(zod.object({
value: zod.string().min(1),
name: zod.string().min(1),
description: zod.string().optional(),
})),
currentValue: zod.string().min(1),
}) as unknown as zod.ZodType<PermissionSelect>
ctx.inject(['sessionProjections'], (projectionCtx) => {
projectionCtx.sessionProjections.register<'permissions', KnobState>({
key: 'permissions',
schema: selectSchema,
init: () => EMPTY_KNOBS,
apply: applyKnobEvent,
view: state => this.selectFor(state),
stateVersion: 1,
})
})
// The /permission command: the one write path a web client uses (the
// popup contribution submits the picked preset as this line). The child
// activates only when a command registry is composed.
ctx.inject(['commands'], (commandCtx) => {
commandCtx.commands.register({
name: 'permission',
description: 'Switch the permission preset (sandbox mode + approval policy)',
input: { hint: '<preset>' },
handler: ({ agent, rawInput }) => {
const name = rawInput.trim()
if (name === '') {
return { kind: 'success', text: `Current permission preset: ${this.current(agent.session.events)}. Available: ${this.names.join(', ')}.` }
}
if (!this.names.includes(name)) {
return { kind: 'error', text: `unknown permission preset "${name}" (available: ${this.names.join(', ')})` }
}
this.set(agent.session, name)
return { kind: 'success', text: `Permission preset: ${name}.` }
},
})
})
}
/**
@@ -146,13 +242,17 @@ export class PermissionService extends Service {
* @returns the effective preset name, or `custom` when nothing matches.
*/
current(events: readonly SessionEvent[]): string {
const sandbox = effectiveSandboxMode(events) ?? this.ctx.bash.sandboxMode
const approval = effectiveApprovalPolicy(events) ?? this.ctx.approval.config.policy ?? 'ask'
return this.derive(foldKnobs(events))
}
/** Resolve the preset for one folded knob state (the shared mathematics of `current` and the projection unit). */
private derive(state: KnobState): string {
const sandbox = state.sandbox ?? this.ctx.bash.sandboxMode
const approval = state.approval ?? this.ctx.approval.config.policy ?? 'ask'
const matches = (spec: PresetSpec): boolean => spec.sandbox === sandbox && spec.approval === approval
const folded = effectivePermissionPreset(events)
if (folded !== undefined) {
const spec = this.presets[folded]
if (spec !== undefined && matches(spec)) return folded
if (state.preset !== null) {
const spec = this.presets[state.preset]
if (spec !== undefined && matches(spec)) return state.preset
}
for (const [name, spec] of Object.entries(this.presets)) {
if (matches(spec)) return name
@@ -160,6 +260,23 @@ export class PermissionService extends Service {
return CUSTOM_PRESET
}
/**
* Build the whole select value for one folded knob state: every table
* option in declaration order, `custom` appended exactly while derived.
* @param state - the folded knob overrides.
* @returns the `permissions` projection payload.
*/
selectFor(state: KnobState): PermissionSelect {
const currentValue = this.derive(state)
return {
options: [
...this.names.map(name => this.optionOf(name)),
...currentValue === CUSTOM_PRESET ? [this.optionOf(CUSTOM_PRESET)] : [],
],
currentValue,
}
}
/**
* Resolve a preset's knob bundle.
* @param name - the preset name to resolve.

View File

@@ -0,0 +1,44 @@
/**
* Pure types of the permission domain: the ONE home of the `permissions`
* projection-key declaration plus its payload types, free of this package's
* host-side value imports (cordis, schemastery). Two namespace projections
* serve it — the package root re-export for host consumers, `./client` (the
* browser half-entry's re-export) for client aggregates — with zero content
* duplication.
*
* @module @deepseek-ai/dsh-permission/types
*/
/** The select-option shape a presentation layer advertises for one preset (or for the derived `custom` state). */
export interface PresetOption {
/** Stable option value: the table key, or `custom`. */
value: string
/** The display label. */
name: string
/** One user-facing sentence on what the value means; omitted when not configured. */
description?: string
}
/**
* Whole `permissions` projection value: every switchable preset in table
* order (plus the derived current-only `custom` when the knobs match no
* entry) and the effective current value.
*/
export interface PermissionSelect {
/** Switchable presets, plus `custom` appended exactly while it is current. */
options: PresetOption[]
/** The effective current value: a preset table key, or `custom`. */
currentValue: string
}
declare module '@deepseek-ai/dsh-session-projection/types' {
interface SessionProjectionMap {
/**
* The session's permission select, folded from the three whole-value
* knob events (`permission/preset`, `sandbox/mode`, `approval/policy`)
* over the composition defaults. Key absence means no permission service
* is composed — clients hide the control.
*/
permissions: PermissionSelect
}
}

View File

@@ -34,6 +34,9 @@ describe('effectivePermissionPreset', () => {
session.append('permission/preset', { preset: 'danger-full-access' })
session.append('permission/preset', { preset: 'workspace-write' })
expect(effectivePermissionPreset(session.events)).toBe('workspace-write')
// The backward scan steps over non-preset events to the latest selection.
session.append('sandbox/mode', { mode: 'read-only' })
expect(effectivePermissionPreset(session.events)).toBe('workspace-write')
})
})

View File

@@ -0,0 +1,116 @@
/**
* The `permissions` projection unit and the `/permission` command: mounting
* the permission service beside the projection registry serves the whole
* select (table options + effective current value, `custom` appended exactly
* while derived) folded from the three knob events over the composition
* defaults; the command child registers `/permission` whose handler switches
* through `permission.set` (bare invocation reports, unknown names error);
* compositions without either registry are unaffected; unmounting the
* service removes the key (HMR safety).
*/
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import type { Session } from '@deepseek-ai/dsh-session'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { createScope } from '@deepseek-ai/dsh-scope'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import CommandService from '@deepseek-ai/dsh-commands'
import PermissionService from '@deepseek-ai/dsh-permission'
import type { Config } from '@deepseek-ai/dsh-permission'
async function harness(options: { withPermission?: boolean; config?: Config } = {}): Promise<{ ctx: Context; session: Session }> {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
await ctx.plugin(CommandService)
ctx.provide('bash', {
sandboxMode: 'workspace-write',
resolve() { throw new Error('permission tests do not execute bash') },
run() { throw new Error('permission tests do not execute bash') },
start() { throw new Error('permission tests do not execute bash') },
})
ctx.provide('approval', { config: { policy: 'ask' } })
if (options.withPermission !== false) await ctx.plugin(PermissionService, options.config ?? {})
return { ctx, session: ctx.sessions.create(SessionId('perm-projected')) }
}
/** Mint a scoped agent over a live session (the command executor's addressing shape). */
async function agentFor(ctx: Context, session: Session): Promise<Agent> {
const agent = { id: session.id, session } as Agent
await ctx.plugin(Object.assign((inner: Context) => { createScope(inner, agent) }, { inject: ['commands'] }))
return agent
}
describe('permissions projection unit', () => {
it('serves the composition-default select at zero events', async () => {
const { ctx, session } = await harness()
const value = ctx.sessionProjections.snapshot(session).values.permissions
expect(value).toMatchObject({ currentValue: 'workspace-write' })
expect(value?.options.map(option => option.value)).toEqual(['workspace-write', 'danger-full-access'])
})
it('folds the knob events and notifies the change feed per knob append', async () => {
const { ctx, session } = await harness()
const changes: { key: string; value: unknown; seq: number }[] = []
ctx.sessionProjections.onChanged((_session, key, value, seq) => {
changes.push({ key, value, seq })
})
ctx.permission.set(session, 'danger-full-access')
// set() appends preset + sandbox/mode + approval/policy: three knob transitions.
expect(changes).toHaveLength(3)
expect(changes.at(-1)).toMatchObject({ key: 'permissions', value: { currentValue: 'danger-full-access' } })
// Unrelated event: same-reference apply, no notification.
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
expect(changes).toHaveLength(3)
})
it('appends custom as a current-only option when the knobs match no preset', async () => {
const { ctx, session } = await harness()
session.append('sandbox/mode', { mode: 'read-only' })
const value = ctx.sessionProjections.snapshot(session).values.permissions
expect(value?.currentValue).toBe('custom')
expect(value?.options.at(-1)).toMatchObject({ value: 'custom', name: 'Custom' })
})
it('has no permissions key without the service, and drops it on unload (HMR safety)', async () => {
const { ctx, session } = await harness({ withPermission: false })
expect('permissions' in ctx.sessionProjections.snapshot(session).values).toBe(false)
const fiber = await ctx.plugin(PermissionService, {})
expect(ctx.sessionProjections.snapshot(session).values.permissions).toMatchObject({ currentValue: 'workspace-write' })
await fiber.dispose()
expect('permissions' in ctx.sessionProjections.snapshot(session).values).toBe(false)
})
})
describe('/permission command', () => {
it('switches through permission.set and logs the lifecycle pair', async () => {
const { ctx, session } = await harness()
const agent = await agentFor(ctx, session)
const execution = await ctx.commands.execute(agent, '/permission danger-full-access', new AbortController().signal)
expect(execution?.result).toEqual({ kind: 'success', text: 'Permission preset: danger-full-access.' })
expect(ctx.permission.current(session.events)).toBe('danger-full-access')
const run = session.events.find(event => event.type === 'command/run')
expect(run?.data).toMatchObject({ name: 'permission', args: ' danger-full-access' })
})
it('reports the current preset and the table on bare invocation', async () => {
const { ctx, session } = await harness()
const agent = await agentFor(ctx, session)
const execution = await ctx.commands.execute(agent, '/permission', new AbortController().signal)
expect(execution?.result).toEqual({
kind: 'success',
text: 'Current permission preset: workspace-write. Available: workspace-write, danger-full-access.',
})
expect(session.events.filter(event => event.type === 'permission/preset')).toHaveLength(0)
})
it('rejects an unknown preset without touching the log', async () => {
const { ctx, session } = await harness()
const agent = await agentFor(ctx, session)
const execution = await ctx.commands.execute(agent, '/permission yolo', new AbortController().signal)
expect(execution?.result).toMatchObject({ kind: 'error' })
expect(session.events.filter(event => event.type !== 'command/run' && event.type !== 'command/done')).toHaveLength(0)
})
})

View File

@@ -34,6 +34,12 @@
},
{
"path": "../../support/invariants"
},
{
"path": "../../session-projection/session-projection"
},
{
"path": "../commands"
}
]
}

View File

@@ -0,0 +1,5 @@
# AGENTS.md — TUI package
These rules supplement the package conventions in [packages/AGENTS.md](../../AGENTS.md).
- **Present TUI designs in tmux, not in the session transcript.** When tmux is available, run the assembled TUI in a pane of the same window the session runs in and point the user at it; print a rendering into the transcript only as a fallback.

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/ui/tui/README.md
README.md: e2bd8534ab1bdc2b0f89006cae77cbcb572f6154
README.zh.md: 8920e84ad796bcb9fb371d7554340518272beb29
README.md: 1a46e7d0557939df77ca27cc4bd09842c9db72ac
README.zh.md: 45353bdc52446d6864f4e365eb4329201432a33b

View File

@@ -12,7 +12,7 @@ This package owns interactive terminal presentation and input only. It injects `
After terminal startup succeeds, the package provides the terminal-local `ctx.tui` extension service. A plugin that injects it can call `openOverlay()` with a component factory and constrained layout options; the host exposes the viewport, semantic theme, display-text escaping, redraw, close, and a lifetime signal, but not the pi-tui tree, terminal, focus controller, or overlay handle. Plugin overlays, the model selector, and user questions share one FIFO modal queue. Each request is an effect of the calling plugin fiber, so unload removes queued work or closes visible work before cleanup settles; terminal shutdown unloads dependents before stopping pi-tui. Overlay state is not logged or replayed. Component code is trusted and may render ANSI styling, but must pass untrusted text through `host.display()`. The [interactive-extension Agent Note](../../../.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.md) owns the boundary and rejected alternatives.
The TUI rebuilds resumed history from the active session surface, renders Markdown responses and reasoning, applies each tool's `presentCall` / `presentResult` intent to terminal, diff, or generic cards, keeps the latest `todo/write` plan above the editor, and presents `ctx.userInteraction` questions in a wide bottom-left keyboard panel with progress, numbered options, and aligned descriptions. The latest logged session title becomes the header subtitle, with `welcome` before a title exists, and the terminal window title becomes `<session title> — <configured title>`. A durable `llm/retry` event retracts the failed step's live chunks and renders the scheduled retry count, delay, and failure in the transcript; success, exhaustion, and cancellation then settle through ordinary session events. The footer totals each logged model step's usage once, including failed attempts, while treating committed-message usage as a fallback for logs without a usage chunk. Its idle view compares token-meter pressure with `ctx.llm.resolveModelInfo()` context for the current route, displays `context unknown` when the adapter has no capacity metadata, and also shows tool-card mode plus the current model and any explicitly selected reasoning effort; while the agent runs, an elapsed working indicator and `esc interrupt` replace that summary. Surface replacement events rebuild the transcript so compacted history does not reappear.
The TUI rebuilds resumed history from the active session surface, renders Markdown responses and reasoning, applies each tool's `presentCall` / `presentResult` intent to terminal, diff, or generic cards, keeps the standing `todo/write` plan above the editor (cleared on the next `turn/start`), and presents `ctx.userInteraction` questions in a wide bottom-left keyboard panel with progress, numbered options, and aligned descriptions. The latest logged session title becomes the header subtitle, with `welcome` before a title exists, and the terminal window title becomes `<session title> — <configured title>`. A durable `llm/retry` event retracts the failed step's live chunks and renders the scheduled retry count, delay, and failure in the transcript; success, exhaustion, and cancellation then settle through ordinary session events. The footer totals each logged model step's usage once, including failed attempts, while treating committed-message usage as a fallback for logs without a usage chunk. Its idle view compares token-meter pressure with `ctx.llm.resolveModelInfo()` context for the current route, displays `context unknown` when the adapter has no capacity metadata, and also shows tool-card mode plus the current model and any explicitly selected reasoning effort; while the agent runs, an elapsed working indicator and `esc interrupt` replace that summary. Surface replacement events rebuild the transcript so compacted history does not reappear.
An embedding may provide `TuiRuntime.formatCwd` when its logical workspace label differs from the session's host directory. The override changes only the footer label; tools continue to use the session `cwd`.
@@ -22,9 +22,9 @@ Typing `@` at a token boundary searches files and directories under the session
When optional `ctx.sessionReferences` is mounted, the same `@` menu also offers metadata-only session candidates, inserts `@[label](dsh-session:<payload>)`, and prepares the selected snapshots before dispatch. Session references remain structured because the model has no filesystem-like tool for retrieving session snapshots later. Preparation disables duplicate submission and restores the editor input on failure. The TUI chooses `agent.steer()` or `agent.followup()` from the status after that asynchronous preparation, so idle follow-ups still dispatch `agent/prompt-submit` while in-turn steering joins at a checkpoint without that hook.
While the agent is running, ordinary editor submissions call `agent.steer()`; otherwise they call `agent.followup()`. A slash at the start of the submitted line enters `ctx.commands` instead: known commands execute directly, unknown commands produce a warning, and neither path automatically reaches the model. A command producer may explicitly schedule agent work; [`dsh-plan-mode`](../../plan/plan-mode/README.md#model-and-human-surfaces) uses that contract for `/plan [message]`. The TUI registers `/help`, `/model`, `/clear`, `/reasoning`, `/tools`, `/redraw`, `/reload`, `/resume`, `/status`, and `/exit` as agent-scoped definitions; every other effective command joins autocomplete and `/help` dynamically, as do `/skill:` completions. A status line above the editor reports the turn phase the TUI derives from session events — waiting for the first token, thinking, responding, or executing tools — with the elapsed time in that phase and the running step total, refreshed each second, and ends with the `Enter sends steering, Esc cancels` hint; while steering messages wait to reach the model it inserts a `N queued ·` badge before the hint that clears as each drains. Ctrl+C or Escape cancels a running turn. Tool cards collapse long bodies into a configurable head/tail preview; Ctrl+O toggles every card between its preview and full output. Ctrl+R toggles reasoning, Ctrl+L redraws, and Ctrl+D exits while idle.
While the agent is running, ordinary editor submissions call `agent.steer()`; otherwise they call `agent.followup()`. A slash at the start of the submitted line enters `ctx.commands` instead: known commands execute directly, unknown commands produce a warning, and neither path automatically reaches the model. A command producer may explicitly schedule agent work; [`dsh-plan-mode`](../../plan/plan-mode/README.md#model-and-human-surfaces) uses that contract for `/plan [message]`. The TUI registers `/help`, `/model`, `/clear`, `/palette`, `/reload`, `/resume`, `/status`, and `/exit` as agent-scoped definitions; every other effective command joins autocomplete and `/help` dynamically, as do `/skill:` completions. A status line above the editor reports the turn phase the TUI derives from session events — waiting for the first token, thinking, responding, or executing tools — with the elapsed time in that phase and the running step total, refreshed each second, and ends with the `Enter sends steering, Esc cancels` hint; while steering messages wait to reach the model it inserts a `N queued ·` badge before the hint that clears as each drains. Ctrl+C or Escape cancels a running turn. Tool and injected-context cards collapse long bodies into a configurable head/tail preview; Ctrl+O cycles tool cards through collapsed preview, full output, and hidden — the hidden phase drops tool cards from the transcript entirely while context cards stay at their preview, since injected instructions are not tool traffic. An injected-context card renders its message as prose with the producer's outer reminder frame stripped, so neither the fold nor the frame stripping depends on the payload's syntax. Ctrl+R toggles reasoning, Ctrl+L redraws, and Ctrl+D exits while idle.
`/model` opens the advisory `ctx.llm` catalog as a keyboard selector: Up/Down moves, Shift+Tab cycles the focused model's adapter-advertised reasoning efforts in display order, Enter selects the model and effort, and Escape closes it. When an adapter does not advertise a default effort, the cycle also includes `provider default`, which clears an explicit selection; models without selectable effort metadata ignore Shift+Tab. The selector renders the exact advertised effort list—including `off` when present—and does not synthesize, clamp, or transfer an effort between models. `/model <model>` still selects an unambiguous model id directly, while `/model <provider>/<model>` selects an exact target and uses its adapter default when one exists. The configured target or latest logged request header initializes the selector, and an unlisted current model remains visible because catalogs are advisory. Selection is local to this TUI session. Prompt assembly snapshots the target for one step, replaces `{{provider}}` and `{{model}}`, and applies the same provider/model/reasoning-effort target through `agent/request`; a switch during assembly therefore starts with a later step. The request header durably records targets that reach the model, while an unused selection remains process-local.
`/model` opens the advisory `ctx.llm` catalog as a keyboard selector: a filter box above the list narrows rows by a case-insensitive substring over each row's `provider/model` label, model name, and description, keeping the highlighted row selected when it survives the filter; Up/Down moves, Shift+Tab cycles the focused model's adapter-advertised reasoning efforts in display order, Enter selects the model and effort, and Escape clears a non-empty filter before a second Escape closes it. When an adapter does not advertise a default effort, the cycle also includes `provider default`, which clears an explicit selection; models without selectable effort metadata ignore Shift+Tab. The selector renders the exact advertised effort list—including `off` when present—and does not synthesize, clamp, or transfer an effort between models. `/model <model>` still selects an unambiguous model id directly, while `/model <provider>/<model>` selects an exact target and uses its adapter default when one exists. The configured target or latest logged request header initializes the selector, and an unlisted current model remains visible because catalogs are advisory. Selection is local to this TUI session. Prompt assembly snapshots the target for one step, replaces `{{provider}}` and `{{model}}`, and applies the same provider/model/reasoning-effort target through `agent/request`; a switch during assembly therefore starts with a later step. The request header durably records targets that reach the model, while an unused selection remains process-local.
`/reload` (EXPERIMENTAL, dev-only) re-reads every file-backed loader config tree and applies the diff to the running app — the HMR watcher's config path, invoked manually; it needs the cordis Loader in the context and degrades to a warning without one, runs only while the agent is idle, and refuses re-entry while a reload is in flight. Module-source hot reload remains watcher-owned. When a `skills` service is mounted, `/skill:<name> [instructions]` loads that skill's instructions into the conversation as a user turn; autocomplete lists the model-invocable skills, and any skill (including a model-disabled one) is loadable by its exact name.
@@ -32,9 +32,15 @@ The footer sums the session's reported usage as `↑<uncached input> ↓<output>
`/status` adds a point-in-time diagnostics card to the transcript and remains available while the agent runs. It reports the session id, title, working directory, selected provider/model, selected reasoning effort or default behavior, reasoning-block visibility, agent state, event/turn/step/tool-call counts, exact input/output/cache token buckets, KV-cache hit rate, token-meter context use and capacity, creation time, and latest event time. Missing titles, models, cache input, or context capacity are labeled instead of inferred. The card is terminal-only and does not duplicate the compact footer.
`/resume` opens a full-viewport keyboard selector over the current workspace instead of a centered dialog. Its focused search field starts immediately after the search glyph and emits pi-tui's cursor marker, so terminal IME composition remains anchored inside the field. Candidates are sorted by last logged activity and searchable by log-backed title or session id; each row reports current/live/persisted state, last turn outcome, recent provider/model, and durable goal phase when present. Up/Down and Page Up/Page Down navigate, Enter resumes, Escape clears a non-empty search before a second Escape cancels, and Ctrl+C cancels directly. The current session, a session already live in this runtime, an unreadable log, a mismatched cwd, or a session whose logged provider has no current adapter remains visible but disabled. Selection repeats those checks and requires the current agent to be idle before flushing the current session. The TUI then stops the terminal UI and calls the optional host-owned `TuiRuntime.handoffResume`; where `process.execve` is available, the shipped `dsh` host disposes the app and replaces its process. Resume restores the same `SessionId`, transcript, title, todos, and durable goal; goal activation remains disarmed and the TUI asks for human confirmation or `/goal resume`.
`/resume` opens a full-viewport keyboard selector instead of a centered dialog. Two scopes cover the same candidate set: the current workspace, which it opens on, and all workspaces, which Tab toggles to. The scope line under the search field names the active scope and the count the other holds, and each row in the all-workspaces scope also reports its own workspace. Toggling clears the search and selection so the highlighted row always belongs to the visible list.
`resumeCommand` remains the deployment-owned fallback: exiting prints it only after the current session is durable, and a host without in-place handoff shows the selected session's command. `{session}` expands to the session id. TUI code never executes the template or arbitrary shell text.
Its focused search field starts immediately after the search glyph and emits pi-tui's cursor marker, so terminal IME composition remains anchored inside the field. Candidates are sorted by last logged activity and searchable by log-backed title or session id, and by workspace label in the all-workspaces scope; each row reports current/live/persisted state, last turn outcome, recent provider/model, and durable goal phase when present. Up/Down and Page Up/Page Down navigate, Enter resumes, Escape clears a non-empty search before a second Escape cancels, and Ctrl+C cancels directly. The current session, a session already live in this runtime, an unreadable log, a session with no recorded workspace to run in, or a session whose logged provider has no current adapter remains visible but disabled; a workspace other than the current one is a scope rather than a disabled reason, because resume enters that directory.
Selection repeats those checks and requires the current agent to be idle before flushing the current session. The TUI then stops the terminal UI and calls the optional host-owned `TuiRuntime.handoffResume` with the selected id and the workspace re-read at preflight: process cwd, not the restored session header, is what filesystem and shell tools resolve against, so the host must enter that directory. Where `process.execve` is available, the shipped `dsh` host chdirs into it before disposing the app and replacing its process, and rejects an unreachable directory while the terminal can still be restored. Resume restores the same `SessionId`, transcript, title, todos, and durable goal; goal activation remains disarmed and the TUI asks for human confirmation or `/goal resume`.
The exit line is launcher-owned, not configurable. A launcher provides `TUI_GOODBYE_MESSAGE_KEY` on the boot context — for the shipped `dsh`, the command that resumes this session — and exiting prints it verbatim after the terminal is released; absent, exiting prints nothing. Only the launcher knows how it was invoked, so only it can name a command that works. The TUI escapes terminal controls before rendering and never executes the text. A launcher that also supplies `MAIN_SESSION_ID_KEY` fixes which session the mounted app binds to, so resume survives any config-level patch.
A launcher can seed a fresh session's first turn by providing `INITIAL_SKILL_KEY` (the skill name) on the boot context; the TUI auto-invokes it exactly as a typed `/skill:<name>`, once the chat is live. The shipped `dsh migrate`/`dsh upgrade` set it and only for a fresh session, so a resumed session never re-invokes the skill; an unknown name is reported as a notice.
## Config
@@ -57,7 +63,6 @@ The footer sums the session's reported usage as `↑<uncached input> ↓<output>
| `showHardwareCursor` | `false` | Show the hardware cursor at pi-tui's IME marker |
| `color` | `true` | Apply the built-in ANSI palette (see [Color](#color)) |
| `title` | `DeepSeek Harness` | Product suffix for the terminal window title. |
| `resumeCommand` | — | Shell command template for the exit hint and hosts without in-place handoff, with `{session}` expanded to the session id |
```yaml
- id: terminal
@@ -74,7 +79,11 @@ Startup fails before mounting when either process stream is not a TTY. The compo
## Color
The palette uses the standard 16-color ANSI foregrounds and SGR attributes, which every terminal remaps to its active color scheme, so it stays readable on light and dark backgrounds alike. Body text keeps the terminal's default foreground rather than a fixed shade. Grouped regions (user prompts, assistant replies, tool cards) are separated by a bold, underlined role header in the role color and blank-line spacing rather than a filled block or a per-line prefix, so a mouse drag-select copies the message text without any leading bar or indent; a tool card's status (pending, error, success) shows in its colored, underlined title glyph and title. The question panel emphasizes its active row with bold accent text, while selectors use reverse video. These treatments are foreground-only, so they never collide with the terminal background. Set `color: false` to strip all styling.
Every SGR code the TUI emits lives in one table, `paletteSpec` in `components/theme.ts`, which `createPalette` derives its wrappers from and `/palette` prints; no component writes an escape of its own. The table holds only the standard 16-color ANSI foregrounds and SGR attributes, which every terminal remaps to its active color scheme, so the TUI stays readable on light and dark backgrounds alike — the startup banner's brand gradient is the one deliberate exception. Body text keeps the terminal's default foreground rather than a fixed shade.
There is one role per visual meaning: `dim` is the single recessed tone and `accent` the single emphasis color, while `success` and `error` double as a diff's added and removed lines. Colors and attributes are separately typed, so `bold(accent(x))` compiles and `accent(error(x))` does not — SGR has no color stack, so nesting one color inside another silently drops the outer color at the inner one's close. Attributes occupy independent SGR groups and compose with any color in either order. Run `/palette` to see every role as your terminal renders it, with its SGR pair.
Grouped regions (user prompts, assistant replies, tool cards) are separated by a bold, underlined role header in the role color and blank-line spacing rather than a filled block or a per-line prefix, so a mouse drag-select copies the message text without any leading bar or indent; a tool card's status (pending, error, success) shows in its colored, underlined title glyph and title. Inside a tool card, the whole body — presenter title, a terminal `$` command and cwd, and the tool's own output — renders in one dim tone, so only the status-colored header carries color and the body reads as one recessed block instead of a run of competing shades; an injected-context card's prose is the same tone as its header. A diff card's `+`/`-` lines and a `[signal …]` marker stay colored, because there the color is the meaning rather than emphasis. The question panel emphasizes its active row with bold accent text, while selectors use reverse video. These treatments are foreground-only, so they never collide with the terminal background. Set `color: false` to strip all styling.
## Model Experience
@@ -156,7 +165,7 @@ Append-only; newly visible content follows the reusable request prefix and does
## Known Limitations and Deferred Work
- **Resume has no cross-process session lock** — the selector rejects sessions known to be live in its own runtime, but another process can resume the same persisted id before or during handoff. Deployments that can run concurrent hosts must coordinate ownership outside the TUI.
- **Resume has no cross-process session lock** — the selector rejects sessions known to be live in its own runtime, but another process can resume the same persisted id before or during handoff. The all-workspaces scope makes this reachable in one step, since a session another host is driving in a different directory is now selectable. Deployments that can run concurrent hosts must coordinate ownership outside the TUI.
- **One configured session owns the transcript and editor** — questions from other agents can still use the shared overlay provider, but session rendering and prompt input remain bound to `sessionId`.
- **Tool cards are text terminal presentations** — terminal, diff, and generic cards use tool-owned titles/content, but session content currently has no image block for inline image rendering.
- **Non-TTY operation is intentionally unsupported** — app bundles that need automation must compose a one-shot or server front door (`dsh-cli-demo`, `dsh-acp`) rather than expecting an internal fallback.

View File

@@ -12,7 +12,7 @@ DeepSeek Harness agent智能体的交互式终端入口基于 [`@earend
终端成功启动后,本包会提供终端本地的 `ctx.tui` 扩展服务。注入该服务的插件可以使用组件工厂和受限布局选项调用 `openOverlay()`;宿主会公开 viewport、语义化主题、显示文本转义、重绘、关闭和生命周期信号但不公开 pi-tui 树、终端、焦点控制器或 overlay 句柄。插件 overlay、模型选择器和用户问题共用一个 FIFO 模态队列。每个请求都是调用方插件 fiber 的 effect因此卸载会移除排队工作或在清理结算前关闭可见工作终端关闭会先卸载依赖项再停止 pi-tui。Overlay 状态不会记录或回放。组件代码受信任,可以渲染 ANSI 样式,但必须通过 `host.display()` 处理不受信任文本。[交互式扩展 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-22-tui-interactive-extension-service.md)持有该边界和未采用的替代方案。
TUI 从活跃会话表层重建已恢复历史,渲染 Markdown 响应与 reasoning将每个工具的 `presentCall` / `presentResult` 意图应用到终端、diff 或通用卡片,把最新`todo/write` 计划保留在编辑器上方,并在左下方宽键盘面板中展示 `ctx.userInteraction` 问题,包含进度、编号选项和对齐说明。最新记录的会话标题成为 header 副标题;标题不存在时使用 `welcome`,终端窗口标题则变为 `<session title> — <configured title>`。持久 `llm/retry` 事件会撤回失败步骤的实时 chunk并在 transcript文本记录中渲染计划重试次数、延迟和失败成功、耗尽与取消随后通过普通会话事件结算。Footer 会对每个已记录模型步骤的用量只计一次,包括失败尝试;对于没有用量 chunk 的日志,以已提交消息的用量回退。其空闲视图会将 token-meter 压力与 `ctx.llm.resolveModelInfo()` 为当前路由返回的上下文容量进行比较;适配器没有容量元数据时显示 `context unknown`并显示工具卡片模式、当前模型以及任何显式选择的推理强度。Agent 运行时,这些摘要会替换为已经过工作时间指示器和 `esc interrupt`。表层替换事件会重建 transcript使经过压缩compaction的历史不会再次出现。
TUI 从活跃会话表层重建已恢复历史,渲染 Markdown 响应与 reasoning将每个工具的 `presentCall` / `presentResult` 意图应用到终端、diff 或通用卡片,把站立`todo/write` 计划保留在编辑器上方(下一个 `turn/start` 时清空),并在左下方宽键盘面板中展示 `ctx.userInteraction` 问题,包含进度、编号选项和对齐说明。最新记录的会话标题成为 header 副标题;标题不存在时使用 `welcome`,终端窗口标题则变为 `<session title> — <configured title>`。持久 `llm/retry` 事件会撤回失败步骤的实时 chunk并在 transcript文本记录中渲染计划重试次数、延迟和失败成功、耗尽与取消随后通过普通会话事件结算。Footer 会对每个已记录模型步骤的用量只计一次,包括失败尝试;对于没有用量 chunk 的日志,以已提交消息的用量回退。其空闲视图会将 token-meter 压力与 `ctx.llm.resolveModelInfo()` 为当前路由返回的上下文容量进行比较;适配器没有容量元数据时显示 `context unknown`并显示工具卡片模式、当前模型以及任何显式选择的推理强度。Agent 运行时,这些摘要会替换为已经过工作时间指示器和 `esc interrupt`。表层替换事件会重建 transcript使经过压缩compaction的历史不会再次出现。
如果逻辑工作区标签与会话宿主目录不同,嵌入方可以提供 `TuiRuntime.formatCwd`。该覆盖只改变 footer 标签;工具仍使用会话 `cwd`
@@ -22,9 +22,9 @@ TUI 从活跃会话表层重建已恢复历史,渲染 Markdown 响应与 reaso
挂载可选的 `ctx.sessionReferences` 后,同一个 `@` 菜单还会提供仅含元数据的会话候选项,插入 `@[label](dsh-session:<payload>)`并在分派前准备所选快照。会话引用保持结构化因为模型没有类似文件系统的工具可在稍后检索会话快照。准备期间会禁止重复提交并在失败时恢复编辑器输入。TUI 会在异步准备后根据状态选择 `agent.steer()``agent.followup()`,因此空闲 followup 仍会分派 `agent/prompt-submit`,而轮次中的 steering 会在检查点加入且不触发该 hook。
Agent 运行时,普通编辑器提交会调用 `agent.steer()`;其他时候调用 `agent.followup()`。提交行以斜杠开头时会改为进入 `ctx.commands`:已知命令直接执行,未知命令产生警告,两条路径都不会自动到达模型。命令生产方可以显式调度 agent 工作;[`dsh-plan-mode`](../../plan/plan-mode/README.md#model-and-human-surfaces) 使用该契约实现 `/plan [message]`。TUI 将 `/help``/model``/clear``/reasoning``/tools``/redraw``/reload``/resume``/status``/exit` 注册为 agent 作用域定义;其他所有有效命令都会动态加入自动补全与 `/help``/skill:` 补全也相同。编辑器上方的状态行会报告 TUI 从会话事件派生的轮次阶段,包括等待首个 token、思考、响应或执行工具它显示该阶段已经过时间和运行中的步骤总数每秒刷新并以 `Enter sends steering, Esc cancels` 提示结尾。Steering 消息等待到达模型期间,会在提示前插入 `N queued ·` 徽标每条消息排空后随即清除。Ctrl+C 或 Escape 会取消运行中的轮次。工具卡片把长主体折叠为可配置的头尾预览Ctrl+O 预览完整输出之间切换所有卡片。Ctrl+R 切换 reasoningCtrl+L 重绘Ctrl+D 在空闲时退出。
Agent 运行时,普通编辑器提交会调用 `agent.steer()`;其他时候调用 `agent.followup()`。提交行以斜杠开头时会改为进入 `ctx.commands`:已知命令直接执行,未知命令产生警告,两条路径都不会自动到达模型。命令生产方可以显式调度 agent 工作;[`dsh-plan-mode`](../../plan/plan-mode/README.md#model-and-human-surfaces) 使用该契约实现 `/plan [message]`。TUI 将 `/help``/model``/clear``/palette``/reload``/resume``/status``/exit` 注册为 agent 作用域定义;其他所有有效命令都会动态加入自动补全与 `/help``/skill:` 补全也相同。编辑器上方的状态行会报告 TUI 从会话事件派生的轮次阶段,包括等待首个 token、思考、响应或执行工具它显示该阶段已经过时间和运行中的步骤总数每秒刷新并以 `Enter sends steering, Esc cancels` 提示结尾。Steering 消息等待到达模型期间,会在提示前插入 `N queued ·` 徽标每条消息排空后随即清除。Ctrl+C 或 Escape 会取消运行中的轮次。工具卡片与注入上下文卡片都把长主体折叠为可配置的头尾预览Ctrl+O 让工具卡片在折叠预览完整输出、隐藏三种状态间循环——隐藏阶段把工具卡片从 transcript 中完全去掉,而上下文卡片保持预览,因为注入的指令不属于工具流量。注入上下文卡片把消息渲染为文本,并去掉生产方的外层提醒外框,因此折叠与去外框都不依赖载荷的语法。Ctrl+R 切换 reasoningCtrl+L 重绘Ctrl+D 在空闲时退出。
`/model` 将建议性的 `ctx.llm` catalog 打开为键盘选择器Up/Down 移动Shift+Tab 按显示顺序循环切换适配器为焦点模型公布的推理强度Enter 选择模型和推理强度Escape 关闭。适配器未公布默认推理强度时,循环还会包含 `provider default`,该项会清除显式选择;没有可选推理强度元数据的模型会忽略 Shift+Tab。选择器会原样呈现公布的推理强度列表包括存在时的 `off`),不会合成、自动调整或在模型之间转移推理强度。`/model <model>` 仍可直接选择无歧义的模型 id`/model <provider>/<model>` 则选择精确目标,并在存在时使用其适配器默认值。已配置目标或最新记录的请求 header 会初始化选择器;由于 catalog 仅提供建议,未列出的当前模型仍会显示。选择仅对本 TUI 会话有效。提示词组装会为一个步骤建立目标快照,替换 `{{provider}}``{{model}}`,并通过 `agent/request` 应用同一个提供方/模型/推理强度目标;因此组装期间的切换会从后续步骤开始生效。请求 header 会持久记录真正到达模型的目标,未使用的选择则只存在于进程本地。
`/model` 将建议性的 `ctx.llm` catalog 打开为键盘选择器:列表上方设有一个过滤框,按对每行 `provider/model` 标签、模型名称和描述的大小写不敏感子串匹配来缩小行集,并在高亮行仍通过过滤时保持其选中状态;Up/Down 移动Shift+Tab 按显示顺序循环切换适配器为焦点模型公布的推理强度Enter 选择模型和推理强度Escape 会先清除非空过滤内容,再次按下才关闭选择器。适配器未公布默认推理强度时,循环还会包含 `provider default`,该项会清除显式选择;没有可选推理强度元数据的模型会忽略 Shift+Tab。选择器会原样呈现公布的推理强度列表包括存在时的 `off`),不会合成、自动调整或在模型之间转移推理强度。`/model <model>` 仍可直接选择无歧义的模型 id`/model <provider>/<model>` 则选择精确目标,并在存在时使用其适配器默认值。已配置目标或最新记录的请求 header 会初始化选择器;由于 catalog 仅提供建议,未列出的当前模型仍会显示。选择仅对本 TUI 会话有效。提示词组装会为一个步骤建立目标快照,替换 `{{provider}}``{{model}}`,并通过 `agent/request` 应用同一个提供方/模型/推理强度目标;因此组装期间的切换会从后续步骤开始生效。请求 header 会持久记录真正到达模型的目标,未使用的选择则只存在于进程本地。
`/reload`(实验性,仅开发环境)会重新读取所有基于文件的 loader 配置树,并把 diff 应用到运行中 app它手动调用 HMR热模块替换watcher 的配置路径;上下文中必须有 cordis Loader否则退化为警告。它只在 agent 空闲时运行,并拒绝 reload 进行期间的再次进入。模块源代码热重载仍由 watcher 持有。挂载 `skills` 服务后,`/skill:<name> [instructions]` 会把该 skill 的指令作为一个 user 轮次加载到会话中;自动补全列出模型可调用的 skill任何 skill包括模型禁用的 skill都可通过精确名称加载。
@@ -32,9 +32,15 @@ Footer 将会话报告的用量汇总为 `↑<uncached input> ↓<output>`;任
`/status` 会向 transcript 添加一张时间点诊断卡片,并在 agent 运行时保持可用。它报告会话 id、标题、工作目录、所选提供方模型、所选推理强度或默认行为、reasoning 块可见性、agent 状态、事件/轮次/步骤/工具调用计数、精确输入/输出/缓存 token bucket、KV-cache 命中率、token-meter 上下文用量与容量、创建时间和最新事件时间。缺失标题、模型、缓存输入或上下文容量时会明确标记,而非推断。该卡片只存在于终端,不会重复紧凑 footer。
`/resume`针对当前工作区打开全 viewport 键盘选择器,而非居中对话框。获得焦点的搜索字段紧跟搜索 glyph 开始,并发出 pi-tui 的 cursor marker使终端 IME 组合保持锚定在字段内。候选项按最近记录的活动排序,可按日志支持的标题或会话 id 搜索;每行报告 current/live/persisted 状态、上一轮次结果、近期提供方模型以及存在时的持久目标阶段。Up/Down 与 Page Up/Page Down 导航Enter 恢复Escape 会先清除非空搜索再次按下才取消Ctrl+C 则直接取消。当前会话、已在本运行时中活跃的会话、不可读日志、cwd 不匹配或日志所记提供方没有当前适配器的会话仍会显示,但不可选择。选择时会重复这些检查,并要求当前 agent 空闲,随后 flush 当前会话。TUI 接着停止终端 UI并调用由宿主持有的可选 `TuiRuntime.handoffResume`;存在 `process.execve` 时,发布的 `dsh` 宿主会对 app 执行 dispose资源释放并替换自身进程。恢复操作保留相同的 `SessionId`、transcript、标题、todo 和持久目标目标激活仍保持解除TUI 会要求用户确认或执行 `/goal resume`
`/resume` 会打开全 viewport 键盘选择器,而非居中对话框。两个作用域覆盖同一候选项集合:打开时所处的当前工作区,以及按 Tab 切换到的所有工作区。搜索字段下方的作用域行会给出当前作用域的名称以及另一个作用域包含的数量,且在所有工作区作用域中每行还会报告自身所属的工作区。切换会清除搜索与选择,使高亮行始终属于可见列表
`resumeCommand` 仍是部署持有的回退行为:只有当前会话已持久化后,退出才会打印它;不支持原地 handoff 的宿主会显示所选会话的命令。`{session}` 展开为会话 id。TUI 代码绝不会执行模板或任意 shell 文本
获得焦点的搜索字段紧跟搜索 glyph 开始,并发出 pi-tui 的 cursor marker使终端 IME 组合保持锚定在字段内。候选项按最近记录的活动排序,可按日志支持的标题或会话 id 搜索,在所有工作区作用域中还可按工作区标签搜索;每行报告 current/live/persisted 状态、上一轮次结果、近期提供方模型以及存在时的持久目标阶段。Up/Down 与 Page Up/Page Down 导航Enter 恢复Escape 会先清除非空搜索再次按下才取消Ctrl+C 则直接取消。当前会话、已在本运行时中活跃的会话、不可读日志、没有可运行的已记录工作区的会话,或日志所记提供方没有当前适配器的会话仍会显示,但不可选择;不同于当前工作区的工作区属于作用域而非禁用原因,因为恢复会进入该目录
选择时会重复这些检查,并要求当前 agent 空闲,随后 flush 当前会话。TUI 接着停止终端 UI并以所选 id 和在预检时重新读取的工作区调用由宿主持有的可选 `TuiRuntime.handoffResume`:文件系统与 shell 工具解析所依据的是进程 cwd而非恢复出的会话头部因此宿主必须进入该目录。存在 `process.execve` 时,发布的 `dsh` 宿主会先 chdir 进入该目录,再对 app 执行 dispose 并替换自身进程,并在终端仍可恢复时拒绝不可达的目录。恢复操作保留相同的 `SessionId`、transcript、标题、todo 和持久目标目标激活仍保持解除TUI 会要求用户确认或执行 `/goal resume`
退出时打印的行由启动器拥有,不可通过配置指定。启动器在启动上下文上提供 `TUI_GOODBYE_MESSAGE_KEY`(对于随附的 `dsh`即恢复本会话的命令释放终端后退出会原样打印它未提供时退出不打印任何内容。只有启动器知道自己是如何被调用的因此只有它能给出可用的命令。TUI 在渲染前会转义终端控制字符,且绝不执行该文本。若启动器同时提供 `MAIN_SESSION_ID_KEY`,则会固定已挂载应用绑定的会话,因此恢复功能不受配置层修补影响。
启动器可通过在启动上下文上提供 `INITIAL_SKILL_KEY`skill 名称来播种全新会话的首轮聊天就绪后TUI 会像用户手动键入 `/skill:<name>` 一样自动调用它。随附的 `dsh migrate`/`dsh upgrade` 会设置该键,且仅对全新会话设置,因此恢复的会话绝不会重复调用该 skill未知名称会以通知形式报告。
## 配置
@@ -57,7 +63,6 @@ Footer 将会话报告的用量汇总为 `↑<uncached input> ↓<output>`;任
| `showHardwareCursor` | `false` | 在 pi-tui 的 IME marker 处显示硬件 cursor |
| `color` | `true` | 应用内置 ANSI palette参见[颜色](#color) |
| `title` | `DeepSeek Harness` | 终端窗口标题的产品后缀。 |
| `resumeCommand` | 未设置 | 供退出提示和不支持原地 handoff 的宿主使用的 shell 命令模板,其中 `{session}` 会展开为会话 id |
```yaml
- id: terminal
@@ -70,11 +75,15 @@ Footer 将会话报告的用量汇总为 `↑<uncached input> ↓<output>`;任
fileSearchExcludedDirectories: ['.git', 'node_modules', 'dist']
```
任一进程流不是 TTY 时,启动会在挂载前失败。组合 app 必须先挂载 TUI再挂载由配置创建的 agent使入口能够观察 `agent-loop/config-start-failed`;完全匹配会话的失败会在全屏模式启动前写出并以状态 1 退出而不是留下空白终端。dispose 会停止接收扩展请求,卸载 `ctx.tui` 提供方及其依赖插件,中止运行中的命令,移除 TUI 定义,停止 loader拒绝待处理问题排空终端输入恢复终端状态注销事件 listener 和用户交互提供方,并且绝不会在 HMR 期间退出替换进程。
任一进程流不是 TTY 时,启动会在挂载前失败。组合 app 必须先挂载 TUI再挂载由配置创建的 agent使入口能够观察 `agent-loop/config-start-failed`;完全匹配会话的失败会在全屏模式启动前写出并以状态 1 退出而不是留下空白终端。dispose(资源释放)会停止接收扩展请求,卸载 `ctx.tui` 提供方及其依赖插件,中止运行中的命令,移除 TUI 定义,停止 loader拒绝待处理问题排空终端输入恢复终端状态注销事件 listener 和用户交互提供方,并且绝不会在 HMR 期间退出替换进程。
## 颜色
Palette 使用标准 16 色 ANSI 前景色和 SGR 属性每个终端都会将重新映射到当前配色方案,因此浅色与深色背景下都保持可读。正文使用终端默认前景色,而非固定色调。成组区域用户提示词、assistant 回复、工具卡片)通过以角色色渲染的粗体带下划线角色标题和空行分隔,而非填充背景块或逐行前缀,因此用鼠标框选复制时不会带上任何左侧竖条或缩进;工具卡片的状态(进行中、错误、成功)由其彩色带下划线的标题字形与标题体现。问题面板使用粗体强调色文本突出活跃行,选择器则使用反色。所有效果都只作用于前景色,因此不会与终端背景冲突。设置 `color: false` 可移除所有样式
TUI 发出的所有 SGR 代码都集中在一个表中,即 `components/theme.ts` 内的 `paletteSpec``createPalette` 从该表派生包装层,`/palette` 则打印该表,任何组件都不会自行写入转义序列。该表仅包含标准 16 色 ANSI 前景色和 SGR 属性每个终端都会将它们重新映射到当前配色方案,因此 TUI 在浅色与深色背景下都保持可读——启动 banner 的品牌渐变是唯一一个有意保留的例外。正文使用终端默认前景色,而非固定色调。
每种视觉语义只对应一个角色:`dim` 是唯一的弱化色调,`accent` 是唯一的强调色,`success``error` 还分别充当 diff 的新增行与删除行。颜色和属性分属不同类型,因此 `bold(accent(x))` 可以通过编译,`accent(error(x))` 则不行——SGR 没有颜色栈;在一种颜色内嵌套另一种颜色时,内层颜色闭合时会静默丢弃外层颜色。各属性占用彼此独立的 SGR 组,可以按任一顺序与任何颜色组合。运行 `/palette` 可查看每个角色在你的终端上的实际渲染效果及其 SGR 码对。
成组区域用户提示词、assistant 回复、工具卡片通过以角色色渲染的粗体带下划线角色标题和空行分隔而非填充背景块或逐行前缀因此用鼠标框选复制时不会带上任何左侧竖条或缩进工具卡片的状态进行中、错误、成功由其彩色带下划线的标题字形与标题体现。在工具卡片内部整个正文——presenter 标题、终端 `$` 命令与 cwd以及工具自身的输出——统一以同一种暗色渲染因此只有带状态色的表头携带颜色正文读作一个整体弱化的区块而不是一串互相竞争的色调注入上下文卡片的正文与其表头也是同一种色调。diff 卡片的 `+`/`-` 行与 `[signal …]` 标记保留颜色,因为那里的颜色本身就是语义,而非强调。问题面板使用粗体强调色文本突出活跃行,选择器则使用反色。所有效果都只作用于前景色,因此不会与终端背景冲突。设置 `color: false` 可移除所有样式。
## 模型体验
@@ -156,7 +165,7 @@ Paths prefixed with @ are files explicitly referenced by the user. Use the read
## 已知限制与延期工作
- **恢复功能没有跨进程会话锁**:选择器会拒绝本运行时中已知处于活跃状态的会话,但另一个进程可以在 handoff 之前或期间恢复同一持久 id。能够运行并发宿主的部署必须在 TUI 外协调所有权。
- **恢复功能没有跨进程会话锁**:选择器会拒绝本运行时中已知处于活跃状态的会话,但另一个进程可以在 handoff 之前或期间恢复同一持久 id。所有工作区作用域让这一情形一步即可触及,因为另一个宿主正在其他目录驱动的会话现在也可被选中。能够运行并发宿主的部署必须在 TUI 外协调所有权。
- **一个已配置会话持有 transcript 和编辑器**:其他 agent 的问题仍可使用共享 overlay 提供方,但会话渲染与提示词输入仍绑定到 `sessionId`
- **工具卡片是文本终端展示**终端、diff 与通用卡片使用工具持有的标题/内容,但会话内容目前没有用于内联图像渲染的图像块。
- **有意不支持非 TTY 运行**:需要自动化的 app bundle 必须组合单次执行或服务器入口(`dsh-cli-demo``dsh-acp`),而不能依赖内部回退。

View File

@@ -101,7 +101,7 @@ export function activeToolCallIds(session: Session, active: ReadonlySet<number>)
const ids = new Set<string>()
for (const event of session.events) {
if (event.type !== 'assistant/message' || !active.has(event.seq)) continue
for (const block of event.data.content) {
for (const block of event.data.message.content) {
if (block.type === 'tool-call') ids.add(block.id)
}
}

View File

@@ -1,26 +1,23 @@
/**
* Session-resume sub-controller for the interactive chat channel: the
* `/resume` selector, per-candidate summary reads that tolerate a corrupt
* neighbor, the pre-handoff preflight, the terminal handoff itself, and the
* durable resume-hint command printed on exit.
* neighbor, the pre-handoff preflight, and the terminal handoff itself.
* @module @deepseek-ai/dsh-tui/chat/resume
*/
import type { TUI } from '@earendil-works/pi-tui'
import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
import { errorChain } from '@deepseek-ai/dsh-llm'
import { SessionId, type SessionHeader } from '@deepseek-ai/dsh-session'
import type { SessionId } from '@deepseek-ai/dsh-session'
import type {
SessionLogSnapshot,
SessionQueryService,
SessionRecord,
} from '@deepseek-ai/dsh-session-query'
import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
import type { HintEditor } from './helpers.ts'
import { formatCwd } from './helpers.ts'
import type { TuiOverlaySession } from '../extension/types.ts'
import type { TuiRuntime } from '../runtime.ts'
import type { Config } from '../config.ts'
import {
ResumePicker,
summarizeResumeCandidate,
@@ -31,9 +28,7 @@ import type { ChannelNotice, ChatChannelDeps } from './channel.ts'
/** Collaborators the resume controller needs from the chat channel. */
export interface ResumeControllerDeps extends ChatChannelDeps, ChannelNotice {
readonly agent: Agent
readonly config: Config
readonly runtime: TuiRuntime
readonly persistence: SessionPersistence | undefined
readonly sessionQuery: SessionQueryService | undefined
readonly ui: TUI
readonly editor: HintEditor
@@ -43,47 +38,27 @@ export interface ResumeControllerDeps extends ChatChannelDeps, ChannelNotice {
/** Session-resume controller for one chat channel. */
export interface ResumeController {
/** Open the current-workspace searchable session selector. */
/** Open the searchable session selector, scoped to this workspace until the user widens it. */
showResume(): void
/**
* The resume command for the current session — the configured template with
* every `{session}` filled — but only once the session is durably persisted;
* `undefined` otherwise.
*/
currentResumeCommand(): Promise<string | undefined>
}
/**
* Build the session-resume controller for one chat channel.
* @param deps - channel collaborators, terminal handles, and optional services.
* @returns the controller wired to the `/resume` command and exit hint.
* @returns the controller wired to the `/resume` command.
*/
export function createResumeController(deps: ResumeControllerDeps): ResumeController {
const {
ctx, agent, config, runtime, resolved, palette, overlayManager,
persistence, sessionQuery, ui, editor,
ctx, agent, runtime, resolved, palette, overlayManager,
sessionQuery, ui, editor,
} = deps
let resumeOverlay: TuiOverlaySession | undefined
let resumeInFlight = false
let resumeScan = 0
/**
* Persisted sessions for this workspace, newest first. Empty when no
* persistence backend is mounted or a listing failure would otherwise block
* exit or crash `/resume`; the resume hint is best-effort convenience.
*/
const listWorkspaceSessions = async (): Promise<SessionHeader[]> => {
if (persistence === undefined) return []
let all: readonly SessionHeader[]
try {
all = await persistence.list()
} catch {
// A listing failure must never block terminal exit or crash `/resume`.
return []
}
return all
.filter(header => header.cwd === agent.session.header.cwd)
}
/** Label any session's own workspace the way the prompt labels the current one. */
const workspaceLabel = (cwd: string | undefined): string =>
runtime.formatCwd?.(cwd) ?? formatCwd(cwd)
/** Build one display candidate without letting a corrupt neighbor abort the selector. */
const readResumeCandidate = async (
@@ -109,6 +84,7 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
agent.session.id,
agent.session.header.cwd,
providers,
workspaceLabel,
)
} catch (error: unknown) {
return {
@@ -116,13 +92,18 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
title: 'Unreadable session',
lastActivityAt: record.header.createdAt,
lastTurn: 'log unavailable',
currentWorkspace: record.header.cwd === agent.session.header.cwd,
workspaceLabel: workspaceLabel(record.header.cwd),
disabledReason: `session cannot be loaded: ${errorChain(error)}`,
}
}
}
/** Re-read every mutable precondition immediately before terminal handoff. */
const preflightResume = async (sessionId: SessionId): Promise<ResumeCandidate> => {
/**
* Re-read every mutable precondition immediately before terminal handoff and
* resolve the exact identity and workspace the host will re-exec into.
*/
const preflightResume = async (sessionId: SessionId): Promise<{ id: SessionId; cwd: string }> => {
/* v8 ignore next -- only showResume can call this closure, after proving the optional service exists */
if (sessionQuery === undefined) throw new Error('Resume is unavailable: session query is not mounted.')
const initialStatus = deps.agentStatus()
@@ -134,9 +115,12 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
new Set(ctx.llm.listProviders().map(provider => provider.id)),
)
if (candidate.disabledReason !== undefined) throw new Error(candidate.disabledReason)
const cwd = candidate.record.header.cwd
/* v8 ignore next -- summarizeResumeCandidate disables a cwd-less record, so the check above already rejected it */
if (cwd === undefined) throw new Error(`Session "${sessionId}" has no recorded workspace to resume in.`)
const finalStatus = deps.agentStatus()
if (finalStatus !== 'idle') throw new Error(`Resume requires an idle agent (status: ${finalStatus}).`)
return candidate
return { id: candidate.record.header.id, cwd }
}
const handoffResume = async (candidate: ResumeCandidate, overlay: TuiOverlaySession): Promise<void> => {
@@ -147,13 +131,9 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
const checked = await preflightResume(candidate.record.header.id)
const hostHandoff = runtime.handoffResume
if (hostHandoff === undefined) {
const template = config.resumeCommand
const fallback = template?.replaceAll('{session}', checked.record.header.id)
await overlay.close()
resumeOverlay = undefined
deps.appendNotice(fallback === undefined
? 'Session is resumable, but this host cannot hand it off in place.'
: `This host cannot hand off in place. Exit and run: ${fallback}`, 'warning')
deps.appendNotice('Session is resumable, but this host cannot hand it off in place.', 'warning')
return
}
/* v8 ignore next -- shutdown during preflight invalidates an awaited service read or reaches this guard */
@@ -169,7 +149,10 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
if (deps.isDisposed()) return
ui.stop()
terminalReleased = true
await hostHandoff(checked.record.header.id)
// The host re-execs into the session's own workspace: process cwd, not the
// restored session header, is what the filesystem and shell tools resolve
// against.
await hostHandoff(checked.id, checked.cwd)
throw new Error('resume host returned without replacing the process')
} catch (error: unknown) {
if (!deps.isDisposed()) {
@@ -189,12 +172,6 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
}
return {
currentResumeCommand: async (): Promise<string | undefined> => {
if (config.resumeCommand === undefined) return undefined
const sessions = await listWorkspaceSessions()
if (!sessions.some(header => header.id === agent.session.id)) return undefined
return config.resumeCommand.replaceAll('{session}', agent.session.id)
},
showResume(): void {
if (agent.status !== 'idle') {
deps.appendNotice('Resume requires the current turn to finish or be cancelled first.', 'warning')
@@ -208,9 +185,10 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
void resumeOverlay?.close()
void sessionQuery.listSessions().then(async (records) => {
if (deps.isDisposed() || scan !== resumeScan) return
const workspace = records.filter(record => record.header.cwd === agent.session.header.cwd)
// Every workspace in the store is summarized; the picker owns the
// current-workspace/all-workspaces scope split over the whole set.
const providers = new Set(ctx.llm.listProviders().map(provider => provider.id))
const candidates = await Promise.all(workspace.map(record => readResumeCandidate(record, providers)))
const candidates = await Promise.all(records.map(record => readResumeCandidate(record, providers)))
candidates.sort((a, b) => b.lastActivityAt - a.lastActivityAt
|| a.record.header.id.localeCompare(b.record.header.id))
if (deps.isDisposed() || scan !== resumeScan) return
@@ -218,7 +196,7 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro
create: host => new ResumePicker(
candidates,
resolved.maxResumeOptions,
runtime.formatCwd?.(agent.session.header.cwd) ?? formatCwd(agent.session.header.cwd),
workspaceLabel(agent.session.header.cwd),
() => host.viewport.rows,
palette,
(candidate) => { void handoffResume(candidate, session) },

View File

@@ -290,7 +290,7 @@ export function fadeGlyph(
return `\x1b[38;2;${r};${g};${b}m${glyph}\x1b[39m`
}
if (!visible) return ' '
return colorEnabled ? palette.muted(glyph) : glyph
return colorEnabled ? palette.dim(glyph) : glyph
}
/**

View File

@@ -205,7 +205,7 @@ export class StatusCardComponent implements Component {
if (groupIndex > 0) body.push('')
for (const [label, value] of group) {
const plainLabel = truncateToWidth(`${label}:`, labelWidth, '')
const prefix = ` ${this.palette.muted(plainLabel.padEnd(labelWidth))} `
const prefix = ` ${this.palette.dim(plainLabel.padEnd(labelWidth))} `
const continuation = ' '.repeat(1 + labelWidth + 2)
const valueWidth = Math.max(1, innerWidth - visibleWidth(prefix))
const wrapped = wrapTextWithAnsi(value, valueWidth)
@@ -281,9 +281,10 @@ export function renderDialog(
return lines
}
/** Keyboard model selector rendered as a bordered overlay, with per-model reasoning-effort cycling. */
/** Keyboard model selector rendered as a bordered overlay, with a filter box and per-model reasoning-effort cycling. */
export class ModelDialog implements Component {
private readonly list: SelectList
private list: SelectList
private readonly filter = new Input()
private readonly items: Map<string, SelectItem>
private readonly choices: Map<string, ModelChoice>
private readonly efforts: Map<string, ReasoningEffortId | undefined>
@@ -292,10 +293,10 @@ export class ModelDialog implements Component {
constructor(
choices: readonly ModelChoice[],
current: AgentLlmTarget | undefined,
maxVisible: number,
private readonly maxVisible: number,
private readonly palette: Palette,
done: (selection: ModelDialogSelection) => void,
cancel: () => void,
private readonly done: (selection: ModelDialogSelection) => void,
private readonly cancel: () => void,
) {
this.items = new Map()
this.choices = new Map()
@@ -317,18 +318,38 @@ export class ModelDialog implements Component {
description: this.describeChoice(choice, isCurrent),
})
}
this.list = new SelectList([...this.items.values()], maxVisible, dialogSelectTheme(palette))
const currentIndex = current === undefined
? 0
: choices.findIndex(choice => choice.provider === current.provider && choice.model === current.model)
this.list.setSelectedIndex(currentIndex)
this.list.onSelect = (item) => {
const selected = choices.find(choice => targetLabel(choice) === item.value)
/* v8 ignore next -- SelectList only returns values built from `choices`. */
if (selected === undefined) return
done({ choice: selected, reasoningEffort: this.efforts.get(item.value) })
}
this.list.onCancel = cancel
this.list = this.buildList(this.currentValue)
}
/** Build a SelectList over the currently filtered items, selecting `selectValue` when present. */
private buildList(selectValue: string | undefined): SelectList {
const items = this.filteredItems()
const list = new SelectList(items, this.maxVisible, dialogSelectTheme(this.palette))
const index = selectValue === undefined ? 0 : items.findIndex(item => item.value === selectValue)
list.setSelectedIndex(Math.max(0, index))
list.onSelect = (item) => { this.confirm(item) }
list.onCancel = this.cancel
return list
}
/** Items matching the filter box, as a case-insensitive substring over the label, model name, and description. */
private filteredItems(): SelectItem[] {
const query = this.filter.getValue().trim().toLocaleLowerCase()
if (query === '') return [...this.items.values()]
return [...this.items.values()].filter((item) => {
const choice = this.choices.get(item.value)
/* v8 ignore next -- items and choices share the same keys. */
if (choice === undefined) return false
return [item.value, choice.modelName, choice.description ?? '']
.some(field => field.toLocaleLowerCase().includes(query))
})
}
private confirm(item: SelectItem): void {
const selected = this.choices.get(item.value)
/* v8 ignore next -- SelectList only returns values built from `choices`. */
if (selected === undefined) return
this.done({ choice: selected, reasoningEffort: this.efforts.get(item.value) })
}
private describeChoice(choice: ModelChoice, isCurrent: boolean): string {
@@ -362,24 +383,50 @@ export class ModelDialog implements Component {
}
invalidate(): void {
this.filter.invalidate()
this.list.invalidate()
}
handleInput(data: string): void {
if (matchesKey(data, Key.shift(Key.tab))) {
this.cycleReasoningEffort()
} else {
} else if (matchesKey(data, Key.escape)) {
if (this.filter.getValue() === '') this.cancel()
else {
this.filter.setValue('')
this.list = this.buildList(undefined)
}
} else if (
matchesKey(data, Key.up)
|| matchesKey(data, Key.down)
|| matchesKey(data, Key.enter)
) {
this.list.handleInput(data)
} else {
const previous = this.filter.getValue()
this.filter.focused = true
this.filter.handleInput(data)
if (this.filter.getValue() !== previous) {
const selected = this.list.getSelectedItem()
this.list = this.buildList(selected?.value)
}
}
this.invalidate()
}
render(width: number): string[] {
const innerWidth = Math.max(1, width - 4)
this.filter.focused = true
const results = this.filteredItems()
const filterContent = truncateToWidth(this.filter.render(innerWidth).join(''), innerWidth, '')
return renderDialog('Select model', [
...this.list.render(innerWidth),
filterContent,
'',
this.palette.dim('↑/↓ navigate • Shift+Tab reasoning • Enter select • Esc cancel'),
...results.length === 0
? [this.palette.dim(' No models match the filter')]
: this.list.render(innerWidth),
'',
this.palette.dim('type to filter • ↑/↓ move • Shift+Tab reasoning • Enter select • Esc'),
], width, this.palette)
}
}
@@ -396,6 +443,10 @@ export interface ResumeCandidate {
title: string
lastActivityAt: number
lastTurn: string
/** Whether the session's workspace is the one the current session runs in, which selects the picker scope that lists it. */
currentWorkspace: boolean
/** The session's own workspace as a prompt-style label; the all-workspaces scope shows it per row. */
workspaceLabel: string
route?: ResumeRoute
goalPhase?: GoalPhase
disabledReason?: string
@@ -423,18 +474,21 @@ function resumeRoute(snapshot: SessionLogSnapshot): ResumeRoute | undefined {
}
const assistant = snapshot.events.findLast(item => item.type === 'assistant/message')
return assistant?.type === 'assistant/message'
? { provider: assistant.data.provenance.provider, model: assistant.data.provenance.model }
? { provider: assistant.data.message.source.provider, model: assistant.data.message.source.model }
: undefined
}
/**
* Build one resume selector row from a record and its log snapshot, deriving the
* title, route, goal phase, and any reason the session cannot be resumed here.
* title, route, goal phase, workspace scope, and any reason the session cannot
* be resumed here. A workspace other than the current one is a scope, not a
* disabled reason: resuming it hands the process off into that directory.
* @param record - The session record.
* @param snapshot - The session's log snapshot.
* @param currentId - The current session id.
* @param cwd - The current workspace directory.
* @param cwd - The CURRENT session's workspace, which decides the picker scope this row falls in.
* @param availableProviders - Providers registered in this runtime.
* @param formatWorkspace - Renders THIS record's own cwd as its prompt-style label.
* @returns The summarized resume candidate.
*/
export function summarizeResumeCandidate(
@@ -443,6 +497,7 @@ export function summarizeResumeCandidate(
currentId: SessionId,
cwd: string | undefined,
availableProviders: ReadonlySet<string>,
formatWorkspace: (cwd: string | undefined) => string,
): ResumeCandidate {
const title = foldSessionTitle(snapshot.events)?.title ?? 'Untitled session'
const route = resumeRoute(snapshot)
@@ -450,7 +505,7 @@ export function summarizeResumeCandidate(
let disabledReason: string | undefined
if (record.header.id === currentId) disabledReason = 'current session'
else if (record.live) disabledReason = 'session is already live in this runtime'
else if (record.header.cwd !== cwd) disabledReason = 'different workspace'
else if (record.header.cwd === undefined) disabledReason = 'session has no recorded workspace'
else if (route !== undefined && !availableProviders.has(route.provider)) {
disabledReason = `session is complete, but route is currently unavailable (${route.provider}/${route.model})`
}
@@ -459,6 +514,8 @@ export function summarizeResumeCandidate(
title,
lastActivityAt: snapshot.events.at(-1)?.time ?? snapshot.session.createdAt,
lastTurn: resumeTurnLabel(snapshot),
currentWorkspace: record.header.cwd === cwd,
workspaceLabel: formatWorkspace(record.header.cwd),
...route === undefined ? {} : { route },
/* v8 ignore next -- goal-bearing resume records are covered by the goal/session integration surface. */
...foldedGoal === undefined ? {} : { goalPhase: foldedGoal.phase },
@@ -466,12 +523,23 @@ export function summarizeResumeCandidate(
}
}
/** Full-viewport keyboard selector over detached, preflighted resume summaries. */
/** Which workspaces the resume picker currently lists. */
export type ResumeScope = 'workspace' | 'all'
/**
* Full-viewport keyboard selector over detached, preflighted resume summaries.
*
* Two scopes over one candidate set: `workspace` (the default) lists only the
* current session's workspace, `all` lists every workspace and labels each row
* with its own. Tab toggles between them; the search query and selection reset
* on a scope change so the highlighted row always belongs to the visible list.
*/
export class ResumePicker implements Component, Focusable {
private readonly search = new Input()
private pasteBuffer: string | undefined
private selectedIndex = 0
private error = ''
private scope: ResumeScope = 'workspace'
focused = false
constructor(
@@ -488,15 +556,29 @@ export class ResumePicker implements Component, Focusable {
this.search.invalidate()
}
/** Candidates in the active scope, before the search query narrows them. */
private scoped(): ResumeCandidate[] {
return this.scope === 'all'
? [...this.candidates]
: this.candidates.filter(candidate => candidate.currentWorkspace)
}
private filtered(): ResumeCandidate[] {
const query = this.search.getValue().trim().toLocaleLowerCase()
if (query === '') return [...this.candidates]
return this.candidates.filter(candidate => candidate.title.toLocaleLowerCase().includes(query)
|| candidate.record.header.id.toLocaleLowerCase().includes(query))
const scoped = this.scoped()
if (query === '') return scoped
// The workspace label only distinguishes rows once it is on screen, so it
// joins the searchable text exactly in the scope that shows it.
return scoped.filter(candidate => candidate.title.toLocaleLowerCase().includes(query)
|| candidate.record.header.id.toLocaleLowerCase().includes(query)
|| (this.scope === 'all' && candidate.workspaceLabel.toLocaleLowerCase().includes(query)))
}
private visibleCandidateCount(): number {
const candidateBudget = Math.max(1, Math.floor((Math.max(1, this.viewportRows()) - 13) / 4))
// The all-workspaces scope adds a per-row workspace line, so a row costs
// one more terminal row there than in the single-workspace scope.
const rowHeight = this.scope === 'all' ? 5 : 4
const candidateBudget = Math.max(1, Math.floor((Math.max(1, this.viewportRows()) - 13) / rowHeight))
return Math.min(this.maxVisible, candidateBudget)
}
@@ -553,6 +635,11 @@ export class ResumePicker implements Component, Focusable {
Math.max(0, filtered.length - 1),
this.selectedIndex + this.visibleCandidateCount(),
)
} else if (matchesKey(data, Key.tab)) {
this.scope = this.scope === 'workspace' ? 'all' : 'workspace'
this.search.setValue('')
this.selectedIndex = 0
this.error = ''
} else if (matchesKey(data, Key.enter)) {
const selected = filtered[this.selectedIndex]
if (selected === undefined) this.error = 'No session matches this search.'
@@ -570,6 +657,21 @@ export class ResumePicker implements Component, Focusable {
this.invalidate()
}
/**
* The scope line under the search box: the active scope with the current
* workspace it means, and the inactive scope with the count Tab would reveal.
*/
private renderScopeLine(): string {
const inWorkspace = this.candidates.filter(candidate => candidate.currentWorkspace).length
const active = this.scope === 'workspace'
? `this workspace ${displayText(this.workspaceLabel)}`
: `all workspaces (${this.candidates.length})`
const other = this.scope === 'workspace'
? `all workspaces (${this.candidates.length})`
: `this workspace (${inWorkspace})`
return `${this.palette.accent(active)}${this.palette.dim(`${other}`)}`
}
render(width: number): string[] {
this.search.focused = this.focused
const height = Math.max(1, this.viewportRows())
@@ -594,7 +696,7 @@ export class ResumePicker implements Component, Focusable {
`${indent}${this.palette.dim('│')} ${clippedSearch}${' '.repeat(Math.max(0, searchInnerWidth - visibleWidth(clippedSearch)))} ${this.palette.dim('│')}`,
`${indent}${this.palette.dim(`${'─'.repeat(Math.max(0, contentWidth - 2))}`)}`,
'',
`${indent}${this.palette.muted(displayText(this.workspaceLabel))}`,
`${indent}${this.renderScopeLine()}`,
'',
)
@@ -620,8 +722,13 @@ export class ResumePicker implements Component, Focusable {
const route = candidate.route === undefined ? 'route unavailable' : `${candidate.route.provider}/${candidate.route.model}`
/* v8 ignore next -- only goal-bearing resume records add this integration-owned suffix. */
const goal = candidate.goalPhase === undefined ? '' : ` · goal ${candidate.goalPhase}`
push(this.palette.muted(` ${new Date(candidate.lastActivityAt).toISOString()} · ${candidate.lastTurn} · ${route}${goal}`))
push(this.palette.dim(` ${new Date(candidate.lastActivityAt).toISOString()} · ${candidate.lastTurn} · ${route}${goal}`))
push(this.palette.dim(` ${status} · ${displayText(candidate.record.header.id)}`))
// Only the all-workspaces scope mixes directories, so the per-row
// workspace is redundant in the scope that already names one.
if (this.scope === 'all') {
push(this.palette.dim(` workspace ${displayText(candidate.workspaceLabel)}`))
}
if (candidate.disabledReason !== undefined) {
push(this.palette.warning(` unavailable: ${displayText(candidate.disabledReason)}`))
}
@@ -632,7 +739,7 @@ export class ResumePicker implements Component, Focusable {
push(this.palette.error(displayText(this.error)))
}
const footer = `${indent}${this.palette.dim('Type to search • ↑/↓ navigate • Enter resume • Esc clear/cancel')}`
const footer = `${indent}${this.palette.dim('Type to search • ↑/↓ navigate • Tab scope • Enter resume • Esc clear/cancel')}`
while (lines.length < height - 2) lines.push('')
lines.push(footer, '')
return lines.slice(0, height)
@@ -720,7 +827,7 @@ export class QuestionDialog implements Component, Focusable {
const innerWidth = Math.max(1, width - 4)
const header = `Question ${this.position}/${this.total} (${this.unanswered} unanswered)${this.question.header === undefined ? '' : ` · ${displayText(this.question.header)}`}`
const lines = [
this.palette.muted(header),
this.palette.dim(header),
...wrapTextWithAnsi(this.palette.text(displayText(this.question.question)), innerWidth),
]
const push = (line: string): void => { lines.push(line) }
@@ -764,7 +871,7 @@ export class QuestionDialog implements Component, Focusable {
: left
const description = option.description === undefined
? ''
: `${' '.repeat(Math.max(1, descriptionColumn - visibleWidth(left)))}${this.palette.muted(displayText(option.description))}`
: `${' '.repeat(Math.max(1, descriptionColumn - visibleWidth(left)))}${this.palette.dim(displayText(option.description))}`
push(`${leftStyled}${description}`)
}
if (options.length > this.maxVisible) push(this.palette.dim(`${this.selectedIndex + 1}/${options.length}`))

View File

@@ -11,67 +11,149 @@ import type {
TerminalColorScheme,
} from '@earendil-works/pi-tui'
/** Theme-agnostic role colors and SGR attribute wrappers. */
/**
* Text carrying exactly one palette color. Branded so the compiler rejects
* wrapping it in a second color: SGR has no color stack, so an inner span's
* close reverts to the default foreground rather than the outer color, which
* silently drops the outer color for the remainder of the line.
*/
export type Colored = string & { readonly __coloredBy: unique symbol }
/**
* Text a color may still be applied to: a bare string, or one already carrying
* SGR attributes. Attributes (bold, italic, underline, strike, reverse) occupy
* independent SGR groups from the foreground color, so they compose in either
* order without either side clobbering the other.
*/
export type Colorable = string & { readonly __coloredBy?: undefined }
/** Applies one color role; rejects input that already carries a color. */
export type ColorRole = (text: Colorable) => Colored
/** Applies one SGR attribute; accepts colored or uncolored text and preserves its color. */
export type AttributeRole = <T extends string>(text: T) => T
/**
* Theme-agnostic role colors and SGR attribute wrappers.
*
* One role per visual meaning: `dim` is the single recessed tone, `accent` the
* single emphasis color, and `success`/`error` double as a diff's added/removed
* pair. Roles that resolved to the same escape were merged rather than kept as
* aliases, so a reader cannot pick a name that silently renders as another.
*
* Colors and attributes are separately typed: `bold(accent(x))` and
* `accent(bold(x))` both compile, while `accent(error(x))` does not.
*/
export interface Palette {
accent: (text: string) => string
accent2: (text: string) => string
text: (text: string) => string
muted: (text: string) => string
dim: (text: string) => string
success: (text: string) => string
warning: (text: string) => string
error: (text: string) => string
code: (text: string) => string
added: (text: string) => string
removed: (text: string) => string
bold: (text: string) => string
italic: (text: string) => string
underline: (text: string) => string
strike: (text: string) => string
accent: ColorRole
/** The terminal's own default foreground; still a color, so it does not stack. */
text: ColorRole
/** The one recessed tone, below `text`: tool-card bodies, chrome, reasoning, footers. */
dim: ColorRole
success: ColorRole
warning: ColorRole
error: ColorRole
code: ColorRole
bold: AttributeRole
italic: AttributeRole
underline: AttributeRole
strike: AttributeRole
/** Reverse video for the active selection; swaps the theme's own fg/bg so it reads on any scheme. */
selected: (text: string) => string
selected: AttributeRole
}
function ansi(open: string, close: string, enabled: boolean): (text: string) => string {
return enabled ? text => `\x1b[${open}m${text}\x1b[${close}m` : text => text
/** Names of the palette's color roles, in the order `/palette` prints them. */
export const COLOR_ROLES = ['text', 'dim', 'accent', 'code', 'success', 'warning', 'error'] as const
/** Names of the palette's attribute roles, in the order `/palette` prints them. */
export const ATTRIBUTE_ROLES = ['bold', 'italic', 'underline', 'strike', 'selected'] as const
/** One role's SGR parameters and the reason it carries them. */
export interface RoleSpec {
/** SGR parameters that open the span, without the `ESC [` prefix or `m` suffix. */
readonly open: string
/** SGR parameters that close it; MUST reset every group `open` sets. */
readonly close: string
/** What the role means, shown by `/palette`. */
readonly purpose: string
}
/**
* Theme-agnostic palette built from the standard 16-color ANSI set plus SGR
* attributes, which every terminal remaps to its active color scheme. Body
* `text` stays the terminal's default foreground so it reads on light and dark
* backgrounds alike; grouping uses foreground-only bold, underlined role
* headers and reverse video rather than fixed background fills or per-line
* prefixes, so a transcript drag-select copies message text without stray
* glyphs.
* Every SGR code the TUI is allowed to emit, keyed by role. This table is the
* single source: {@link createPalette} derives the wrappers from it and
* `/palette` prints it, so a role cannot exist in one and not the other, and no
* component hand-writes an escape.
*
* Only the standard 16-color set and SGR attributes appear here. Terminals remap
* those to the user's active theme, so the TUI stays legible on any background;
* a fixed 24-bit color would not. The brand gradient is the one deliberate
* exception ({@link gradientText}).
*
* @param scheme - Active terminal color scheme; only `code` differs between them.
* @returns The SGR spec for every color and attribute role.
*/
export function paletteSpec(scheme: TerminalColorScheme): {
readonly colors: Readonly<Record<typeof COLOR_ROLES[number], RoleSpec>>
readonly attributes: Readonly<Record<typeof ATTRIBUTE_ROLES[number], RoleSpec>>
} {
return {
colors: {
// The terminal's own foreground, emitted as no escape at all: ordinary body
// text must inherit whatever the user's theme uses.
text: { open: '', close: '', purpose: 'Body text, the terminal default foreground' },
// SGR 2 over an explicit default foreground, closing both groups it sets.
// The attribute fades relative to whatever the terminal's own foreground is,
// which is the only way to land *below* `text` on both schemes: ANSI 90
// (bright black) is a fixed hue that many light themes render heavier than
// their default foreground, which made every "dim" surface the most
// prominent text on screen.
dim: { open: '2;39', close: '22;39', purpose: 'The one recessed tone: tool bodies, chrome, footers' },
accent: { open: '95', close: '39', purpose: 'The one emphasis color: role headers, prompt, borders' },
// ANSI 36 (cyan) is difficult to read on a light background — use ANSI 34
// (blue) which is legible on both light and dark schemes.
code: scheme === 'light'
? { open: '34', close: '39', purpose: 'Inline code and code blocks in prose' }
: { open: '36', close: '39', purpose: 'Inline code and code blocks in prose' },
success: { open: '32', close: '39', purpose: 'Succeeded calls, and a diff\'s added lines' },
warning: { open: '33', close: '39', purpose: 'Pending calls and warnings' },
error: { open: '31', close: '39', purpose: 'Failures, signals, and a diff\'s removed lines' },
},
attributes: {
bold: { open: '1', close: '22', purpose: 'Emphasis; composes with any color' },
italic: { open: '3', close: '23', purpose: 'Reasoning text' },
underline: { open: '4', close: '24', purpose: 'Role-header banding' },
strike: { open: '9', close: '29', purpose: 'Struck-through Markdown' },
selected: { open: '7', close: '27', purpose: 'Reverse video for the active selection' },
},
}
}
/**
* Wrap text in an SGR pair, or pass it through when color is disabled.
* An empty `open` emits nothing, so the `text` role costs no escape.
*/
function ansi(spec: RoleSpec, enabled: boolean): (text: string) => string {
if (!enabled || spec.open === '') return text => text
return text => `\x1b[${spec.open}m${text}\x1b[${spec.close}m`
}
/**
* Theme-agnostic palette derived from {@link paletteSpec}. Body `text` stays the
* terminal's default foreground so it reads on light and dark backgrounds alike;
* grouping uses foreground-only bold, underlined role headers and reverse video
* rather than fixed background fills or per-line prefixes, so a transcript
* drag-select copies message text without stray glyphs.
*
* @param enabled - Whether ANSI is emitted at all.
* @param scheme - Active terminal color scheme; adjusts dim and code roles.
* @param scheme - Active terminal color scheme; adjusts the code role.
* @returns The role palette for the given scheme.
*/
export function createPalette(enabled: boolean, scheme: TerminalColorScheme = 'dark'): Palette {
return {
accent: ansi('94', '39', enabled),
accent2: ansi('95', '39', enabled),
text: text => text,
muted: ansi('90', '39', enabled),
// SGR 2 (dim) lightens text on a light background — substitute ANSI 90
// (bright black / gray) which renders as a readable muted tone on any scheme.
dim: scheme === 'light' ? ansi('90', '39', enabled) : ansi('2', '22', enabled),
success: ansi('32', '39', enabled),
warning: ansi('33', '39', enabled),
error: ansi('31', '39', enabled),
// ANSI 36 (cyan) is difficult to read on a light background — use
// ANSI 34 (blue) which is legible on both light and dark schemes.
code: scheme === 'light' ? ansi('34', '39', enabled) : ansi('36', '39', enabled),
added: ansi('32', '39', enabled),
removed: ansi('31', '39', enabled),
bold: ansi('1', '22', enabled),
italic: ansi('3', '23', enabled),
underline: ansi('4', '24', enabled),
strike: ansi('9', '29', enabled),
selected: ansi('7', '27', enabled),
}
const spec = paletteSpec(scheme)
const roles = {} as Record<string, unknown>
for (const name of COLOR_ROLES) roles[name] = ansi(spec.colors[name], enabled)
for (const name of ATTRIBUTE_ROLES) roles[name] = ansi(spec.attributes[name], enabled)
return roles as unknown as Palette
}
/**
@@ -145,8 +227,8 @@ export function markdownTheme(palette: Palette): MarkdownTheme {
// pi-tui presents both fence rows through this callback. Keep the opening
// language label, but hide Markdown syntax and the otherwise-empty close.
codeBlockBorder: text => palette.dim(text.slice(3)),
quote: text => palette.muted(text),
quoteBorder: text => palette.accent2(text),
quote: text => palette.dim(text),
quoteBorder: text => palette.accent(text),
hr: text => palette.dim(text),
listBullet: text => palette.accent(text),
bold: text => palette.bold(text),
@@ -165,7 +247,7 @@ export function selectTheme(palette: Palette): SelectListTheme {
return {
selectedPrefix: palette.accent,
selectedText: palette.accent,
description: palette.muted,
description: palette.dim,
scrollInfo: palette.dim,
noMatch: palette.warning,
}
@@ -182,3 +264,49 @@ export function dialogSelectTheme(palette: Palette): SelectListTheme {
selectedText: text => palette.selected(palette.accent(text)),
}
}
/** Sample text every `/palette` row renders, long enough to judge a tone against its neighbours. */
const PALETTE_SAMPLE = 'The quick brown fox 0123'
/**
* Render every palette role as a labelled sample row, each painted by the role
* it names, so a reader compares the actual tones their terminal produces rather
* than reading SGR numbers. Colors print first and attributes second because the
* two groups compose in that order; every row shows its SGR pair so a mismatch
* between the table and the screen is visible.
*
* @param palette - Active role palette, used to paint each sample.
* @param scheme - Active color scheme, reported in the heading and selecting the spec.
* @param colorEnabled - Whether ANSI is emitted; reported so an unstyled listing is not confusing.
* @returns The rendered rows, without a trailing blank.
*/
export function renderPalette(
palette: Palette,
scheme: TerminalColorScheme,
colorEnabled: boolean,
): string[] {
const spec = paletteSpec(scheme)
const width = Math.max(...[...COLOR_ROLES, ...ATTRIBUTE_ROLES].map(name => name.length))
// Two rows per role: the painted sample beside its name and SGR pair, then the
// purpose indented under it. Splitting the purpose onto its own row keeps every
// sample on one visual line at the narrow widths a side-by-side pane gives.
const head = (name: string, role: RoleSpec, sample: string): string => {
const pair = role.open === '' ? 'no escape' : `ESC[${role.open}m ESC[${role.close}m`
return ` ${sample} ${palette.dim(`${name.padEnd(width)} ${pair}`)}`
}
const purpose = (role: RoleSpec): string => ` ${palette.dim(` ${role.purpose}`)}`
const rows = [
palette.bold(palette.accent('Palette')),
palette.dim(`${scheme} scheme · color ${colorEnabled ? 'on' : 'off'}`),
'',
palette.dim('Colors — exactly one per span; they never nest inside each other.'),
]
for (const name of COLOR_ROLES) {
rows.push(head(name, spec.colors[name], palette[name](PALETTE_SAMPLE)), purpose(spec.colors[name]))
}
rows.push('', palette.dim('Attributes — compose with any color, in either order.'))
for (const name of ATTRIBUTE_ROLES) {
rows.push(head(name, spec.attributes[name], palette[name](PALETTE_SAMPLE)), purpose(spec.attributes[name]))
}
return rows
}

View File

@@ -25,7 +25,7 @@ import type {
ToolResultView,
} from '@deepseek-ai/dsh-tools'
import type { FileDiff } from '@deepseek-ai/dsh-tools'
import { renderUnknownXml } from './xml-tool-output.ts'
import { preview, renderUnknownXml } from './xml-tool-output.ts'
import { displayInlineText, displayText } from './text.ts'
import { gradientText, type Palette } from './theme.ts'
import { contentText, type ParsedArguments } from './content.ts'
@@ -58,9 +58,9 @@ function diffLines(diff: FileDiff, palette: Palette): string[] {
// each hunk always carries its own path header (no redundancy to suppress).
const lines = [palette.bold(displayText(diff.path))]
if (diff.oldText !== null) {
for (const line of displayText(diff.oldText).split('\n')) lines.push(palette.removed(`- ${line}`))
for (const line of displayText(diff.oldText).split('\n')) lines.push(palette.error(`- ${line}`))
}
for (const line of displayText(diff.newText).split('\n')) lines.push(palette.added(`+ ${line}`))
for (const line of displayText(diff.newText).split('\n')) lines.push(palette.success(`+ ${line}`))
return lines
}
@@ -109,7 +109,7 @@ export class HeaderComponent implements Component {
const subtitle = this.subtitle()
const lines = [
title,
...subtitle === undefined ? [] : [this.palette.muted(displayText(subtitle))],
...subtitle === undefined ? [] : [this.palette.dim(displayText(subtitle))],
this.palette.dim(detail),
]
.flatMap(line => wrapTextWithAnsi(line, usable))
@@ -147,12 +147,12 @@ function assistantMessageChildren(
const text = displayText(textBlocks(content, 'text').trim())
const children: Component[] = [
new Spacer(1),
new Text(messageHeader('Assistant', palette.accent2, palette), 0, 0),
new Text(messageHeader('Assistant', palette.accent, palette), 0, 0),
]
if (reasoning && showReasoning) {
children.push(
new Text(palette.italic(palette.muted('Reasoning')), 0, 0),
new Markdown(reasoning, 0, 0, mdTheme, { color: value => palette.muted(value), italic: true }),
new Text(palette.italic(palette.dim('Reasoning')), 0, 0),
new Markdown(reasoning, 0, 0, mdTheme, { color: value => palette.dim(value), italic: true }),
)
}
if (text) children.push(new Markdown(text, 0, 0, mdTheme, { color: value => palette.text(value) }))
@@ -301,10 +301,27 @@ export class StreamingAssistantComponent extends Container {
}
}
/**
* A tool card's body split at the Markdown boundary. `prelude` rows are already
* styled and render verbatim (a terminal `$` command, its cwd, a diff's hunks);
* `lines` is the tool's own text. A generic card renders both as one Markdown
* document under the dim body tone.
*/
interface CardBody {
readonly prelude: readonly string[]
readonly lines: readonly string[]
}
/**
* Ctrl+O card-visibility cycle: `hidden` drops tool cards from the transcript,
* `collapsed` previews the first body lines, `expanded` shows everything.
*/
export type ToolCardVisibility = 'hidden' | 'collapsed' | 'expanded'
/** A tool call and its result, rendered as a collapsible status card. */
export class ToolCardComponent implements Component {
private result: { content: ContentBlock[]; isError: boolean; meta?: JsonValue } | undefined
private expanded = false
private visibility: ToolCardVisibility = 'collapsed'
private callView: ToolCallView
private resultView: ToolResultView | undefined
@@ -336,9 +353,10 @@ export class ToolCardComponent implements Component {
* @param event - The `tool/result` event payload.
*/
updateResult(event: Extract<SessionEvent, { type: 'tool/result' }>['data']): void {
const result = event.message.content[0]
this.result = {
content: [...event.content],
isError: event.isError,
content: [...result.content],
isError: result.isError === true,
...event.meta !== undefined ? { meta: event.meta } : {},
}
if (this.parsed.valid && this.definition?.presentResult) {
@@ -352,16 +370,19 @@ export class ToolCardComponent implements Component {
}
/**
* Expand or collapse the card's body preview.
* @param expanded - Whether the full body is shown.
* Set the card's visibility state.
* @param visibility - Hidden, collapsed preview, or full body.
*/
setExpanded(expanded: boolean): void {
this.expanded = expanded
setVisibility(visibility: ToolCardVisibility): void {
this.visibility = visibility
}
invalidate(): void {}
render(width: number): string[] {
// Hidden renders nothing — not even the leading gap — so the transcript
// keeps only the conversation, the way Codex hides tool calls.
if (this.visibility === 'hidden') return []
const isError = this.result?.isError ?? false
// A ring marker: hollow while the call is pending, filled once it settles;
// the header color (warning/success/error) tells pending from ok from error.
@@ -373,25 +394,23 @@ export class ToolCardComponent implements Component {
? renderUnknownXml(
displayText(contentText(genericContent)),
this.maxOutputLines,
this.expanded,
this.visibility === 'expanded',
displayText,
text => this.palette.muted(text),
text => this.palette.dim(text),
text => this.palette.dim(text),
/* v8 ignore next -- renderUnknownXml calls the collapsed summary only when hidden XML children exceed this card's limit. */
count => this.palette.dim(` … +${count} lines (Ctrl+O to expand)`),
)
: undefined
const body = unknownXml ?? (genericContent !== undefined && rawBody.length > 0
? new Markdown(rawBody.join('\n'), 0, 0, this.mdTheme, { color: value => this.palette.text(value) }).render(width)
: rawBody)
const headLines = Math.ceil(this.maxOutputLines / 2)
const tailLines = this.maxOutputLines - headLines
const visibleBody = unknownXml !== undefined || this.expanded || body.length <= this.maxOutputLines
// A generic card renders title and result as one Markdown document, so the
// document's own block spacing is preserved, then dims every row — the whole
// card body reads as one dim block under the status-colored header.
const body = unknownXml ?? (genericContent !== undefined && rawBody.lines.length > 0
? this.dimBody(rawBody, width)
: [...rawBody.prelude, ...rawBody.lines])
const visibleBody = unknownXml !== undefined || this.visibility === 'expanded'
? body
: [
...body.slice(0, headLines),
this.palette.dim(`… +${body.length - this.maxOutputLines} lines (Ctrl+O to expand)`),
...body.slice(body.length - tailLines),
]
: preview(body, this.maxOutputLines, count => this.palette.dim(`… +${count} lines (Ctrl+O to expand)`))
// The header is a fixed `Tool / <name>` frame in the status color (warning
// pending / success ok / error), flat — no bold or underline, so one color
// reads consistently across the whole row. Every tool-specific detail (a
@@ -408,7 +427,9 @@ export class ToolCardComponent implements Component {
const desc = this.headerDescription()
const headerText = `${glyph} Tool / ${displayText(this.name)}${desc === undefined ? '' : ` / ${displayInlineText(desc)}`}`
const header = truncateToWidth(headerText, Math.max(1, width - 2), '')
const lines = [statusColor(header)]
// The blank first row is the card's own paragraph gap (no external Spacer),
// so the hidden state removes the gap together with the card.
const lines: string[] = ['', statusColor(header)]
if (visibleBody.length > 0) lines.push(...new Text(visibleBody.join('\n'), 0, 0).render(width))
return lines
}
@@ -437,10 +458,11 @@ export class ToolCardComponent implements Component {
return this.resultView?.title ?? this.callView.title
}
private renderBody(): string[] {
private renderBody(): CardBody {
const view = this.resultView ?? this.callView
if (view.card === 'terminal') {
const pending = this.terminalPending()
const prelude: string[] = []
const lines: string[] = []
// The command shows as a $-line here whenever it is not the header: either a
// description headlines the row (the command still belongs somewhere) or the row
@@ -451,18 +473,18 @@ export class ToolCardComponent implements Component {
// rows and collide with the output below.
const headlined = pending?.description !== undefined && pending.description !== ''
const commandInBody = pending !== undefined && (headlined || this.result === undefined)
if (commandInBody) lines.push(this.palette.code(`$ ${displayInlineText(pending.title)}`))
if (pending?.cwd) lines.push(this.palette.dim(displayInlineText(pending.cwd)))
if (commandInBody) prelude.push(this.palette.dim(`$ ${displayInlineText(pending.title)}`))
if (pending?.cwd) prelude.push(this.palette.dim(displayInlineText(pending.cwd)))
if (this.resultView?.card === 'terminal') {
if (this.resultView.output) lines.push(...displayText(this.resultView.output).split('\n'))
if (this.resultView.output) lines.push(...this.dimOutput(this.resultView.output))
if (this.resultView.exitCode !== undefined) lines.push(this.palette.dim(`[exit ${this.resultView.exitCode}]`))
if (this.resultView.signal !== undefined) {
lines.push(this.palette.error(`[signal ${displayText(this.resultView.signal)}]`))
}
} else if (this.result !== undefined) {
lines.push(...displayText(contentText(this.result.content)).split('\n'))
lines.push(...this.dimOutput(contentText(this.result.content)))
}
return lines.filter(Boolean)
return { prelude: prelude.filter(Boolean), lines: lines.filter(Boolean) }
}
if (view.card === 'diff') {
// The header no longer names the file, so each diff keeps its own path
@@ -476,22 +498,138 @@ export class ToolCardComponent implements Component {
})
const files = view.diffs.length
const footer = this.palette.dim(`└ +${added} -${removed} · ${files} file${files === 1 ? '' : 's'}`)
return [...hunks, footer]
// A diff's own `+`/`-` colors carry its meaning, so it renders verbatim
// rather than under the dim result-output color.
return { prelude: [...hunks, footer], lines: [] }
}
const content = view.content ?? this.result?.content
const prelude: string[] = []
const lines: string[] = []
// The presenter title headlines the body now that the header is a fixed
// `Tool / <name>` frame (a terminal card keeps its command $-line instead).
// Skip it when it only repeats the tool name (the fallback presenter for a
// tool with no presentCall, or an unknown tool), which the header already shows.
const bodyTitle = this.bodyTitle()
if (bodyTitle !== displayText(this.name)) lines.push(displayInlineText(bodyTitle))
if (bodyTitle !== displayText(this.name)) prelude.push(displayInlineText(bodyTitle))
if (content !== undefined) lines.push(...displayText(contentText(content)).split('\n'))
const rawInput = this.result === undefined && this.callView.card === 'generic'
? this.callView.rawInput
: undefined
if (rawInput !== undefined) lines.push(...pretty(rawInput).split('\n'))
return lines.filter((line, index, all) => line.length > 0 || (index > 0 && index < all.length - 1))
// Blank-line trimming spans the whole body, so the title counts as a row:
// interior blanks (a result's own paragraph break) survive while the body's
// leading and trailing ones are dropped.
const total = prelude.length + lines.length
return {
prelude,
lines: lines.filter((line, index) => {
const row = prelude.length + index
return line.length > 0 || (row > 0 && row < total - 1)
}),
}
}
/**
* A tool's own output text as dim rows — the card's result-output color, which
* separates what the tool produced from the card's own framing. A blank row
* stays the empty string so the terminal branch's blank-row filter still reads
* it as blank instead of as an ANSI-wrapped value.
*/
private dimOutput(text: string): string[] {
return displayText(text).split('\n').map(line => line === '' ? line : this.palette.dim(line))
}
/**
* Render a generic card's prelude and result as one Markdown document under the
* dim body tone. Rendering both together preserves the document's own block
* spacing (Markdown's blank row before a heading); dimming every row keeps the
* card body one uniform tone, so only the status-colored header carries color.
*/
private dimBody(body: CardBody, width: number): string[] {
const rows = new Markdown([...body.prelude, ...body.lines].join('\n'), 0, 0, this.mdTheme, {
color: value => this.palette.text(value),
}).render(width)
// A whitespace-only row carries no output to dim; leaving it unwrapped keeps
// Markdown's padding out of the styled ranges.
return rows.map(row => row.trim() === '' ? row : this.palette.dim(row))
}
}
/**
* Matches a lone reminder-frame tag on its own line, capturing the element name.
* Producers emit the frame as whole lines (`workspace-context`, `dsh-tool-skill`),
* so anchoring the whole line keeps a tag mentioned inside prose from matching.
*/
const REMINDER_FRAME_LINE = /^<(\/?)([a-zA-Z][\w:.-]*)>$/u
/**
* Drop a producer's outer reminder frame, keeping the instruction body verbatim.
* The card header already names the source, so the frame lines carry nothing.
* Only a matched open/close pair on the first and last lines is removed, so a
* body that merely starts with a tag-like line is left intact.
* @param text - Complete model-facing context text.
* @returns The body without its outer frame lines, trimmed of the blank lines they leave.
*/
function stripReminderFrame(text: string): string {
// A frame needs an open line and a distinct close line, so anything shorter than
// two lines is already frameless.
const [first = '', ...rest] = text.split('\n')
const last = rest.at(-1)
if (last === undefined) return text
const open = REMINDER_FRAME_LINE.exec(first.trim())
const close = REMINDER_FRAME_LINE.exec(last.trim())
if (open?.[1] !== '' || close?.[1] !== '/' || open[2] !== close[2]) return text
return rest.slice(0, -1).join('\n').replace(/^\n+|\n+$/gu, '')
}
/**
* Injected context (plugin/goal source, e.g. `workspace-context`), rendered as a
* collapsible dim card that shares the tool-card `Ctrl+O` toggle. The header is
* `Context · <label>`; the body is the message text as dim prose, one tone with
* the header and the fold marker, folded to `maxOutputLines`, with a surrounding
* reminder frame stripped because the source label already names the context.
*
* Injected context is prose, not markup, so this card does not parse it. The
* `<system-reminder>` frame is a prompting convention no model is trained on
* ([envelope rationale](../../../../../.agents/notes/implemented/simplification/2026-07-20-unwrap-injected-content-envelopes.md)),
* and instruction bodies legitimately contain a raw `&` or angle-bracket
* placeholders (`packages/<group>/<pkg>/`, `-t <name>`) that are prose rather than
* elements. Tree-rendering such a payload depended on whether it happened to be
* well-formed XML, which made both the fold and the frame-line suppression
* content-dependent.
*/
export class ContextCardComponent implements Component {
private expanded = false
constructor(
private readonly label: string,
private readonly text: string,
private readonly maxOutputLines: number,
private readonly palette: Palette,
) {}
/**
* Expand or collapse the card body.
* @param expanded - Whether the full body is shown.
*/
setExpanded(expanded: boolean): void {
this.expanded = expanded
}
invalidate(): void {}
render(width: number): string[] {
const header = this.palette.dim(`Context · ${displayText(this.label)}`)
// Emptiness is decided on the stripped text: styling a blank body would yield
// one escape-only row, which reads as a stray blank line under the header.
const stripped = stripReminderFrame(this.text)
if (stripped === '') return [header]
const body = stripped.split('\n')
.map(line => line === '' ? line : this.palette.dim(displayText(line)))
const visibleBody = this.expanded
? body
: preview(body, this.maxOutputLines, count => this.palette.dim(`… +${count} lines (Ctrl+O to expand)`))
return [header, ...new Text(visibleBody.join('\n'), 0, 0).render(width)]
}
}
@@ -513,7 +651,7 @@ export class TodoComponent implements Component {
render(width: number): string[] {
if (this.todos.length === 0) return []
const lines = [this.palette.bold(this.palette.accent('Plan'))]
const lines: string[] = [this.palette.bold(this.palette.accent('Plan'))]
for (const todo of this.todos) {
const prefix = todo.status === 'completed'
? this.palette.success('✓')
@@ -521,7 +659,7 @@ export class TodoComponent implements Component {
? this.palette.warning('●')
: this.palette.dim('○')
const content = displayText(todo.content)
const text = todo.status === 'completed' ? this.palette.muted(content) : content
const text: string = todo.status === 'completed' ? this.palette.dim(content) : content
lines.push(truncateToWidth(` ${prefix} ${text}`, width, ''))
}
return ['', ...lines]

View File

@@ -1,6 +1,7 @@
/**
* Conservative readable-tree rendering for model-facing text containing one XML
* document, used by the transcript's tool and context cards.
* document, used by the transcript's tool cards for unknown tool results. Injected
* context is prose and is not parsed; only {@link preview} is shared with its card.
* @module @deepseek-ai/dsh-tui/components/xml-tool-output
*/
@@ -76,26 +77,42 @@ function meaningfulChildren(element: XmlElement): readonly XmlNode[] {
return element.children.filter(child => typeof child !== 'string' || child.trim() !== '')
}
function textBlock(text: string, depth: number): string[] {
return text.replace(/^\n|\n$/gu, '').split('\n').map(line => `${' '.repeat(depth)}${line}`)
function textBlock(text: string, depth: number, body: (text: string) => string): string[] {
return text.replace(/^\n|\n$/gu, '').split('\n')
.map(line => line === '' ? line : `${' '.repeat(depth)}${body(line)}`)
}
function treeLines(element: XmlElement, depth: number, label: (text: string) => string): string[] {
function treeLines(
element: XmlElement,
depth: number,
label: (text: string) => string,
body: (text: string) => string,
): string[] {
const indent = ' '.repeat(depth)
const children = meaningfulChildren(element)
if (children.length === 0) return [`${indent}${label(elementLabel(element))}`]
if (children.length === 1 && typeof children[0] === 'string' && !children[0].includes('\n')) {
return [`${indent}${label(`${elementLabel(element)}:`)} ${children[0].trim()}`]
return [`${indent}${label(`${elementLabel(element)}:`)} ${body(children[0].trim())}`]
}
const lines = [`${indent}${label(elementLabel(element))}`]
for (const child of children) {
if (typeof child === 'string') lines.push(...textBlock(child, depth + 1))
else lines.push(...treeLines(child, depth + 1, label))
if (typeof child === 'string') lines.push(...textBlock(child, depth + 1, body))
else lines.push(...treeLines(child, depth + 1, label, body))
}
return lines
}
function preview(lines: readonly string[], limit: number, omitted: (count: number) => string): string[] {
/**
* Collapse `lines` to a head/tail preview around one omitted-count marker.
* The single fold rule for every transcript card, so a card's fold never depends
* on how its body was rendered: tool cards share it with their tree output and
* context cards apply it to prose rows.
* @param lines - Fully rendered body rows.
* @param limit - Maximum retained rows, excluding the marker.
* @param omitted - Renders the marker for the omitted row count.
* @returns `lines` unchanged when within `limit`, else head rows, the marker, and tail rows.
*/
export function preview(lines: readonly string[], limit: number, omitted: (count: number) => string): string[] {
if (lines.length <= limit) return [...lines]
const head = Math.ceil(limit / 2)
const tail = limit - head
@@ -104,13 +121,15 @@ function preview(lines: readonly string[], limit: number, omitted: (count: numbe
/**
* Render a complete XML document as an indented tree, or decline without changing partial/mixed text.
* @param source - Raw model-facing text from a context message or unknown tool result.
* @param source - Raw model-facing text from an unknown tool result.
* @param maxChildLines - Collapsed budget independently applied to each top-level child's lines and
* to the number of top-level children, so many siblings cannot grow the collapsed card without bound.
* @param expanded - Whether to retain every rendered child line.
* @param display - Escapes parsed text and attribute values for terminal output; character references
* can expand to control characters that pre-parse escaping never saw.
* @param label - Styles element names and attributes.
* @param body - Styles the text content under those elements; the card's body tone, so tree
* content matches the surrounding card rows instead of falling back to the default foreground.
* @param omitted - Renders the omitted-line marker for a collapsed child or child range.
* @returns Tree rows, or `undefined` when `source` is not one supported complete XML document.
*/
@@ -120,12 +139,13 @@ export function renderUnknownXml(
expanded: boolean,
display: (text: string) => string,
label: (text: string) => string,
body: (text: string) => string,
omitted: (count: number) => string,
): string[] | undefined {
const root = parseXml(source, display)
if (root === undefined) return undefined
const blocks = meaningfulChildren(root).map(child =>
typeof child === 'string' ? textBlock(child, 1) : treeLines(child, 1, label))
typeof child === 'string' ? textBlock(child, 1, body) : treeLines(child, 1, label, body))
const rootLine = label(elementLabel(root))
if (expanded) return [rootLine, ...blocks.flat()]
const previewed = blocks.map(block => preview(block, maxChildLines, omitted))

View File

@@ -79,7 +79,7 @@ const colorSchema = z.boolean().default(true)
// No default: an unset value auto-detects truecolor from COLORTERM in `apply`.
const truecolorSchema = z.boolean()
const DEFAULT_LEFT_PROMPT = '${cwd}${git/worktree}${model}${token_meter/cache_hit_rate}${context}'
const DEFAULT_RIGHT_PROMPT = '${timing}'
const DEFAULT_RIGHT_PROMPT = '${queued}'
const DEFAULT_INPUT_PROMPT = '${symbol} ${indicator}'
const DEFAULT_INPUT_PLACEHOLDER = 'press enter to steer and esc to cancel'
const TuiThemeConfigSchema: z<TuiThemeConfig> = z.object({
@@ -120,19 +120,19 @@ export interface Config extends TuiConfig {
/** Exact shared agent/session identity driven by this terminal. Defaults to `main`. */
sessionId?: string
/**
* Shell command fallback printed on exit or after selecting a session when
* the host cannot hand off in place. Every `{session}` becomes the selected
* id; the TUI never executes this text. Absent disables only the fallback,
* not the interactive selector.
* Skill name auto-invoked as this session's first user turn, exactly as if
* the user typed `/skill:<name>`. Set only by a launcher for a fresh
* skill-guided session (`dsh migrate`/`dsh upgrade`); absent leaves the first
* turn to the user.
*/
resumeCommand?: string
initialSkill?: string
}
/** Schemastery schema for the full plugin configuration. */
export const Config: z<Config> = z.object({
welcome: z.string(),
sessionId: z.string().default('main'),
resumeCommand: z.string(),
initialSkill: z.string(),
showReasoning: tuiConfigSchemaFields.showReasoning,
maxToolOutputLines: tuiConfigSchemaFields.maxToolOutputLines,
maxQuestionOptions: tuiConfigSchemaFields.maxQuestionOptions,

View File

@@ -37,9 +37,7 @@ export interface TuiFocusable {
export interface TuiTheme {
/** Render ordinary foreground text. */
readonly text: (value: string) => string
/** Render secondary information. */
readonly muted: (value: string) => string
/** Render low-emphasis hints. */
/** Render secondary information and low-emphasis hints, the one tone below `text`. */
readonly dim: (value: string) => string
/** Render the active accent role. */
readonly accent: (value: string) => string

View File

@@ -24,22 +24,20 @@ import {
assembleContextFor,
installAgentLlmTarget,
type Agent,
type AgentMessageId,
type AgentLlmTargetRef,
type AgentStatus,
} from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-agent-loop'
import type {} from '@deepseek-ai/dsh-token-meter'
import type { CommandResult } from '@deepseek-ai/dsh-commands'
import { errorChain } from '@deepseek-ai/dsh-llm'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import { renderUnknownXml } from './components/xml-tool-output.ts'
import { createUserMessage, errorChain } from '@deepseek-ai/dsh-llm'
import type { ContentBlock, MessageId } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/dsh-llm-retry'
import { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
import {
SessionId,
type SessionEvent,
type UserMessageData,
type UserMessage,
} from '@deepseek-ai/dsh-session'
import { foldGoal } from '@deepseek-ai/dsh-goal'
import {
@@ -68,7 +66,7 @@ import type {
TuiTheme,
} from './extension/types.ts'
import { displayInlineText, displayText } from './components/text.ts'
import { createPalette, markdownTheme, selectTheme } from './components/theme.ts'
import { createPalette, markdownTheme, renderPalette, selectTheme } from './components/theme.ts'
import { contentText, parseArguments } from './components/content.ts'
import {
cacheHitRate,
@@ -93,6 +91,8 @@ import {
type Config,
} from './config.ts'
import {
ContextCardComponent,
type ToolCardVisibility,
HeaderComponent,
StreamingAssistantComponent,
ToolCardComponent,
@@ -176,9 +176,68 @@ declare module 'cordis' {
tui: TuiExtensionService
/** Optional process host that can replace this TUI with a resumed session. */
tuiResumeHost: TuiResumeHost
/** Launcher-owned `main` session identity; absent lets the app mint one. */
mainSessionId: MainSessionIdentity | undefined
/** Line the launcher wants printed on exit; absent prints nothing. */
tuiGoodbyeMessage: string | undefined
/** Skill the launcher wants auto-invoked as the fresh session's first turn; absent leaves it to the user. */
tuiInitialSkill: string | undefined
/** Launcher-owned session-store root the app bundle defaults to; absent keeps the bundle's project-local default. */
launcherSessionsRoot: string | undefined
}
}
/** Launcher-chosen identity for the app's `main` session. */
export interface MainSessionIdentity {
/** Exact session id `main` binds to. */
readonly id: SessionId
/**
* Whether that session already has persisted history to load. `true` requires
* an existing log and fails loud when absent; `false` creates it fresh.
*/
readonly resume: boolean
}
/**
* Context key a launcher sets before any Loader entry mounts
* (`ctx.provide(MAIN_SESSION_ID_KEY, identity)`) to fix the `main` agent's
* session identity, so an app bundle mounted from a `cordis.yml` binds a
* launcher-selected session without a config key. `ctx.provide` is the only
* channel from launcher argv into a Loader-mounted plugin, because config
* `!!js` expressions evaluate against the entry's context. Absent leaves the
* choice to the app.
*/
export const MAIN_SESSION_ID_KEY = 'mainSessionId'
/**
* Context key a launcher sets before any Loader entry mounts
* (`ctx.provide(TUI_GOODBYE_MESSAGE_KEY, line)`) to supply the line the TUI
* prints once the terminal is released on exit — for the shipped CLI, the
* command that resumes this session. The launcher owns the wording because only
* it knows how it was invoked; the TUI escapes terminal controls before
* rendering. Absent prints nothing.
*/
export const TUI_GOODBYE_MESSAGE_KEY = 'tuiGoodbyeMessage'
/**
* Context key a launcher sets before any Loader entry mounts
* (`ctx.provide(INITIAL_SKILL_KEY, name)`) to seed a fresh session's first user
* turn with `/skill:<name>` — the `dsh migrate`/`dsh upgrade` guided-session
* entry. The launcher sets it only when minting a fresh session, so it never
* re-fires on a resumed one. Absent leaves the first turn to the user.
*/
export const INITIAL_SKILL_KEY = 'tuiInitialSkill'
/**
* Context key a launcher sets before any Loader entry mounts
* (`ctx.provide(SESSIONS_ROOT_KEY, root)`) to supply its session-store root as
* the app bundle's default persistence root. Shared-store policy (one store
* across every cwd) belongs to the launcher — the dsh CLI resolves it under the
* Harness home — never to a plugin; a bundle without this slot keeps its own
* project-local default, and an explicit `persistenceRoot` config still wins.
*/
export const SESSIONS_ROOT_KEY = 'launcherSessionsRoot'
/**
* Optional terminal-local interaction service provided by one mounted TUI.
*
@@ -247,7 +306,6 @@ export function createTuiChat(
const sessionId = SessionId(config.sessionId ?? 'main')
const agent = ctx.agents.get(sessionId)
if (agent === undefined) throw new Error(`ui-tui: session "${sessionId}" is not running`)
const persistence = ctx.get('sessionPersistence')
const sessionQuery = ctx.get('sessionQuery')
const resolved = resolveTuiConfig(config)
const palette = createPalette(resolved.theme.color)
@@ -272,7 +330,9 @@ export function createTuiChat(
editor.hintPrefix = initialInputPrompt
const todo = new TodoComponent(palette)
let showReasoning = resolved.showReasoning
let toolsExpanded = false
// Ctrl+O cycles collapsed -> expanded -> hidden. Codex-style: hidden drops
// tool cards entirely, collapsed previews, expanded shows full bodies.
let toolsVisibility: ToolCardVisibility = 'collapsed'
let streaming: StreamingAssistantComponent | undefined
let completedStreaming: StreamingAssistantComponent | undefined
let runningStatus: RunningStatus | undefined
@@ -280,7 +340,7 @@ export function createTuiChat(
// TUI steering submissions that the inbox has not yet claimed or discarded.
// Correlation ids avoid guessing whether a running-state submission actually
// joined steering or fell back to the queued-turn FIFO during turn close.
const pendingSteering = new Set<AgentMessageId>()
const pendingSteering = new Set<MessageId>()
let disposed = false
let shuttingDown: Promise<void> | undefined
// Optional: skills mount conditionally, so read the global service store
@@ -296,6 +356,7 @@ export function createTuiChat(
const tokens = sessionTokens(agent.session)
const toolCards = new Map<string, ToolCardComponent>()
const allToolCards = new Set<ToolCardComponent>()
const contextCards = new Set<ContextCardComponent>()
const liveErrors = new Set<string>()
const commandControllers = new Set<AbortController>()
const referenceControllers = new Set<AbortController>()
@@ -324,33 +385,33 @@ export function createTuiChat(
const branch = runtime.gitBranch?.(cwd) ?? gitBranch(cwd)
const promptValues: TuiPromptValueHandle[] = [
ctx.tuiPrompt.register('cwd', palette.bold(palette.accent(formattedCwd))),
ctx.tuiPrompt.register('git/worktree', branch === undefined ? undefined : palette.muted(` (${displayText(branch)})`)),
ctx.tuiPrompt.register('git/worktree', branch === undefined ? undefined : palette.dim(` (${displayText(branch)})`)),
ctx.tuiPrompt.register('token_meter/cache_hit_rate'),
ctx.tuiPrompt.register('model'),
ctx.tuiPrompt.register('context'),
ctx.tuiPrompt.register('timing'),
ctx.tuiPrompt.register('queued'),
ctx.tuiPrompt.register('symbol', palette.bold(palette.accent('dsh'))),
ctx.tuiPrompt.register('indicator', palette.muted('> ')),
ctx.tuiPrompt.register('indicator', palette.dim('> ')),
]
const [cwdValue, gitValue, tokenValue, modelValue, contextValue, timingValue, symbolValue, indicatorValue] = promptValues
const [cwdValue, gitValue, tokenValue, modelValue, contextValue, queuedValue, symbolValue, indicatorValue] = promptValues
/* v8 ignore next -- the fixed built-in registration list always supplies each handle. */
if (cwdValue === undefined || gitValue === undefined || tokenValue === undefined || modelValue === undefined
|| contextValue === undefined || timingValue === undefined || symbolValue === undefined || indicatorValue === undefined) {
|| contextValue === undefined || queuedValue === undefined || symbolValue === undefined || indicatorValue === undefined) {
throw new Error('TUI prompt built-ins failed to initialize')
}
const updatePromptValues = (): void => {
cwdValue.set(palette.bold(palette.accent(formattedCwd)))
gitValue.set(branch === undefined ? undefined : palette.muted(` (${displayText(branch)})`))
gitValue.set(branch === undefined ? undefined : palette.dim(` (${displayText(branch)})`))
const rate = cacheHitRate(tokens)
const usage = `${formatTokens(tokens.input)}${formatTokens(tokens.output)}`
modelValue.set(` ${palette.muted(displayText(target.current === undefined ? 'model unset' : compactTargetLabel(target.current)))}`)
tokenValue.set(` ${palette.muted(rate === undefined ? usage : `${usage} cache ${rate}%`)}`)
modelValue.set(` ${palette.dim(displayText(target.current === undefined ? 'model unset' : compactTargetLabel(target.current)))}`)
tokenValue.set(` ${palette.dim(rate === undefined ? usage : `${usage} cache ${rate}%`)}`)
const contextWindow = modelController.contextWindow()
contextValue.set(contextWindow === undefined ? undefined : ` ${palette.muted(
contextValue.set(contextWindow === undefined ? undefined : ` ${palette.dim(
`${Math.min(100, Math.round(ctx.tokenMeter.measure(agent.session).totalTokens / contextWindow * 100))}% context`,
)}`)
const queued = runningStatus === undefined ? undefined : formatQueuedStatus(pendingSteering.size)
timingValue.set(queued === undefined ? undefined : palette.dim(queued))
queuedValue.set(queued === undefined ? undefined : palette.dim(queued))
symbolValue.set(palette.bold(palette.accent('dsh')))
// `${indicator}` owns the caret column and its trailing gap before the
// cursor. The phase glyph replaces the `>` caret in place — same width
@@ -371,7 +432,7 @@ export function createTuiChat(
? { glyph: fadingStatus.glyph, level: Math.max(0, 1 - (now() - fadingStatus.endedAt) / STATUS_FADE_MS) }
: undefined
const caret = envelope === undefined
? palette.muted('>')
? palette.dim('>')
: fadeGlyph(
envelope.glyph,
palette,
@@ -380,7 +441,7 @@ export function createTuiChat(
envelope.level * pulseLevel(now()),
envelope.level >= 0.5,
)
indicatorValue.set(`${caret}${palette.muted(' ')}`)
indicatorValue.set(`${caret}${palette.dim(' ')}`)
}
const promptContext = new PromptContextComponent(
parseTuiPromptTemplate(displayInlineText(resolved.theme.leftPrompt)),
@@ -417,7 +478,7 @@ export function createTuiChat(
const disposePromptChanges = ctx.tuiPrompt.subscribe(requestRender)
const appendNotice = (message: string, kind: 'info' | 'warning' | 'error' = 'info'): void => {
const color = kind === 'error' ? palette.error : kind === 'warning' ? palette.warning : palette.muted
const color = kind === 'error' ? palette.error : kind === 'warning' ? palette.warning : palette.dim
chat.addChild(new Spacer(1))
chat.addChild(new Text(color(displayText(message)), 0, 0))
requestRender()
@@ -425,7 +486,6 @@ export function createTuiChat(
const extensionTheme: TuiTheme = Object.freeze({
text: (value: string) => palette.text(value),
muted: (value: string) => palette.muted(value),
dim: (value: string) => palette.dim(value),
accent: (value: string) => palette.accent(value),
success: (value: string) => palette.success(value),
@@ -548,7 +608,7 @@ export function createTuiChat(
palette,
mdTheme,
)
card.setExpanded(toolsExpanded)
card.setVisibility(toolsVisibility)
toolCards.set(event.data.callId, card)
allToolCards.add(card)
return card
@@ -627,22 +687,18 @@ export function createTuiChat(
/* v8 ignore next -- context events with empty content are rejected by their owning producers. */
if (text) {
// The tui type view lacks plugin-augmented source kinds (e.g. goal),
// so read the display label without narrowing on `kind`.
const labelled = source as { kind: string; plugin?: string }
/* v8 ignore next -- current plugin-augmented context sources always carry their display label. */
const label = labelled.plugin ?? labelled.kind
const xml = renderUnknownXml(
text,
resolved.maxToolOutputLines,
true,
displayText,
value => palette.muted(value),
/* v8 ignore next -- expanded context XML never asks renderUnknownXml for a collapsed summary. */
() => '',
)
// so read the display label without narrowing on `kind`. The session
// log is a durable/replay boundary: a corrupt or foreign injected
// source may not match the typed shape, so fall back to `context`.
const labelled = source as { kind?: unknown; plugin?: unknown }
const label = typeof labelled.plugin === 'string' ? labelled.plugin
: typeof labelled.kind === 'string' ? labelled.kind
: 'context'
const card = new ContextCardComponent(label, text, resolved.maxToolOutputLines, palette)
card.setExpanded(toolsVisibility === 'expanded')
contextCards.add(card)
chat.addChild(new Spacer(1))
chat.addChild(new Text(palette.dim(`Context · ${displayText(label)}`), 0, 0))
chat.addChild(new Text(xml?.join('\n') ?? palette.muted(displayText(text)), 0, 0))
chat.addChild(card)
}
break
}
@@ -655,7 +711,7 @@ export function createTuiChat(
break
}
case 'steering/message': {
const text = displayText(contentText(event.data.content).trim())
const text = displayText(contentText(event.data.message.content).trim())
if (text) {
chat.addChild(new Spacer(1))
chat.addChild(new UserMessageComponent(text, palette, mdTheme, 'Steering'))
@@ -671,7 +727,7 @@ export function createTuiChat(
case 'assistant/message':
completedStreaming = undefined
if (streaming === undefined || !chat.children.includes(streaming)) startAssistantStep(event.data)
streaming?.settle(event.data.content)
streaming?.settle(event.data.message.content)
break
case 'llm/retry': {
retractFailedStreaming()
@@ -682,27 +738,33 @@ export function createTuiChat(
)
break
}
// No external Spacer for tool cards: the card renders its own leading
// gap, so the hidden state removes the row and the gap together.
case 'tool/call':
chat.addChild(new Spacer(1))
chat.addChild(parsedTool(event))
trailStreamingTiming()
break
case 'tool/result': {
let card = toolCards.get(event.data.callId)
const callId = event.data.message.source.callId
let card = toolCards.get(callId)
if (card === undefined) {
card = new ToolCardComponent('tool', { value: {}, valid: true }, undefined, resolved.maxToolOutputLines, palette, mdTheme)
chat.addChild(new Spacer(1))
card.setVisibility(toolsVisibility)
chat.addChild(card)
allToolCards.add(card)
}
card.updateResult(event.data)
toolCards.delete(event.data.callId)
toolCards.delete(callId)
trailStreamingTiming()
break
}
case 'todo/write':
todo.update(event.data.todos)
break
case 'turn/start':
// Plan strip is turn-scoped: keep it after turn/end for reading, clear on the next turn.
todo.update([])
break
case 'session/title':
sessionTitle = event.data.title
header.invalidate()
@@ -758,7 +820,9 @@ export function createTuiChat(
chat.clear()
toolCards.clear()
allToolCards.clear()
contextCards.clear()
streaming = undefined
todo.update([])
const active = activeSurfaceSeqs(agent.session)
const activeCalls = activeToolCallIds(agent.session, active)
for (const event of agent.session.events) {
@@ -785,12 +849,10 @@ export function createTuiChat(
const resume = createResumeController({
ctx,
agent,
config,
runtime,
resolved,
palette,
overlayManager,
persistence,
sessionQuery,
ui,
editor,
@@ -819,9 +881,8 @@ export function createTuiChat(
await runtime.terminal.drainInput(100, 20)
ui.stop()
if (exitProcess) {
const command = await resume.currentResumeCommand()
if (command !== undefined) {
runtime.terminal.write(`${palette.muted('To resume this session:')} ${displayText(command)}\n`)
if (runtime.goodbyeMessage !== undefined) {
runtime.terminal.write(`${palette.dim(displayText(runtime.goodbyeMessage))}\n`)
}
runtime.exit(0)
}
@@ -865,9 +926,15 @@ export function createTuiChat(
ui.queryTerminalColorScheme({ timeoutMs: 2000 }).catch(() => {})
const toggleTools = (): void => {
toolsExpanded = !toolsExpanded
for (const card of allToolCards) card.setExpanded(toolsExpanded)
appendNotice(`Tool cards ${toolsExpanded ? 'expanded' : 'collapsed'}.`)
// The cycle order puts the two common reading modes adjacent: preview ->
// full detail -> conversation-only, then back to the preview default.
toolsVisibility = toolsVisibility === 'collapsed' ? 'expanded'
: toolsVisibility === 'expanded' ? 'hidden' : 'collapsed'
for (const card of allToolCards) card.setVisibility(toolsVisibility)
// Context cards carry injected instructions rather than tool traffic, so
// they never hide: the hidden phase reads as their collapsed preview.
for (const card of contextCards) card.setExpanded(toolsVisibility === 'expanded')
appendNotice(toolsVisibility === 'hidden' ? 'Tool cards hidden.' : `Tool and context cards ${toolsVisibility}.`)
}
const toggleReasoning = (): void => {
@@ -893,12 +960,20 @@ export function createTuiChat(
chat.addChild(new Text(palette.bold(palette.accent('Keyboard shortcuts')), 0, 0))
chat.addChild(new Text([
'Enter send • Shift/Alt+Enter newline • Up/Down prompt history',
'Esc cancel active turn • Ctrl+O toggle tool cards • Ctrl+R toggle reasoning',
'Esc cancel turn • Ctrl+O cycle cards (collapse/expand/hide) • Ctrl+R toggle reasoning • Ctrl+L redraw',
'Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit',
'',
...commandLines,
'/skill:<name> [instructions] — load a skill into the conversation',
].map(line => palette.muted(line)).join('\n'), 0, 0))
].map(line => palette.dim(line)).join('\n'), 0, 0))
requestRender()
}
const showPalette = (): void => {
chat.addChild(new Spacer(1))
chat.addChild(new Text(
renderPalette(palette, currentScheme, resolved.theme.color).join('\n'), 0, 0,
))
requestRender()
}
@@ -1062,19 +1137,9 @@ export function createTuiChat(
handler: () => { chat.clear(); requestRender(); return { kind: 'success' } },
})
commandCtx.commands.register({
name: 'reasoning',
description: 'Toggle reasoning blocks',
handler: () => { toggleReasoning(); return { kind: 'success' } },
})
commandCtx.commands.register({
name: 'tools',
description: 'Expand or collapse all tool cards',
handler: () => { toggleTools(); return { kind: 'success' } },
})
commandCtx.commands.register({
name: 'redraw',
description: 'Invalidate components and redraw the terminal',
handler: () => { ui.invalidate(); ui.requestRender(true); return { kind: 'success' } },
name: 'palette',
description: 'Show every color and attribute role this terminal renders',
handler: () => { showPalette(); return { kind: 'success' } },
})
commandCtx.commands.register({
name: 'reload',
@@ -1121,12 +1186,12 @@ export function createTuiChat(
const controller = new AbortController()
commandControllers.add(controller)
void ctx.commands.execute(agent, text, controller.signal).then(
(result) => {
(execution) => {
if (disposed) return
if (result === undefined) {
if (execution === undefined) {
appendNotice(`Unknown command: ${text}`, 'warning')
} else if (result.text !== undefined && result.text !== '') {
appendNotice(result.text, result.kind === 'error' ? 'error' : 'info')
} else if (execution.result.text !== undefined && execution.result.text !== '') {
appendNotice(execution.result.text, execution.result.kind === 'error' ? 'error' : 'info')
}
},
(error: unknown) => {
@@ -1137,7 +1202,7 @@ export function createTuiChat(
).finally(() => { commandControllers.delete(controller) })
}
const dispatchMessage = (content: ContentBlock[], attachedContext?: UserMessageData): void => {
const dispatchMessage = (content: ContentBlock[], attachedContext?: UserMessage): void => {
if (disposed) {
appendNotice(`Agent "${agent.id}" is disposed.`, 'error')
return
@@ -1146,43 +1211,37 @@ export function createTuiChat(
// Steering is never subject to prompt admission; an attached snapshot
// drains beside it at the same step boundary through the outbox.
if (attachedContext !== undefined) {
agent.inject({ content: attachedContext.content, source: attachedContext.source })
agent.inject(attachedContext)
}
pendingSteering.add(agent.steer({ content, source: { kind: 'user' } }))
const message = createUserMessage({ content, source: { kind: 'user' } })
agent.steer(message)
pendingSteering.add(message.id)
refreshStatus()
return
}
if (attachedContext === undefined) {
agent.followup({ content, source: { kind: 'user' } })
agent.followup(createUserMessage({ content, source: { kind: 'user' } }))
return
}
// Idle: the snapshot rides the prompt's admission transaction so a
// blocking hook discards both together.
let cleanedUp = false
let acceptedId: AgentMessageId | undefined
let acceptedContent: ContentBlock[] | undefined
const enqueued = new Map<AgentMessageId, ContentBlock[]>()
const discarded = new Set<AgentMessageId>()
const message: UserMessage = createUserMessage({ content, source: { kind: 'user' } })
const acceptedId = message.id
const discarded = new Set<MessageId>()
const cleanup = (): void => {
// Every completion path detaches all three listeners. Keep this
// Every completion path detaches both listeners. Keep this
// idempotent so later cleanup paths cannot double-release them.
/* v8 ignore next -- unreachable idempotence guard, see above */
if (cleanedUp) return
cleanedUp = true
detachEnqueue()
detachSubmit()
detachDiscard()
}
// send() snapshots input before publishing it, and publishes enqueue
// before returning its id. Capture that snapshot by id so admission can
// use exact reference identity without depending on caller-owned input.
const detachEnqueue = ctx.on('agent/inbox/enqueue', (subject, message) => {
if (subject === agent) enqueued.set(message.id, message.content)
})
// Prepended so this wrapper is outermost: it observes the admission
// whether a downstream hook allows or blocks, and detaches either way.
const detachSubmit = ctx.on('agent/prompt-submit', async (subject, submitted, _source, _signal, next) => {
if (subject !== agent || submitted !== acceptedContent) return next()
// Prepended so this wrapper is outermost: it observes the exact accepted
// message identity whether a downstream hook allows or blocks, then detaches.
const detachSubmit = ctx.on('agent/prompt-submit', async (subject, submitted, _signal, next) => {
if (subject !== agent || submitted.id !== message.id) return next()
cleanup()
const decision = await next()
if (decision.kind !== 'allow') return decision
@@ -1193,15 +1252,13 @@ export function createTuiChat(
const detachDiscard = ctx.on('agent/inbox/discard', (subject, messages) => {
if (subject !== agent) return
for (const message of messages) discarded.add(message.id)
if (acceptedId !== undefined && discarded.has(acceptedId)) cleanup()
if (discarded.has(acceptedId)) cleanup()
})
// followup() accepts any typed input and contains listener failures;
// this guards a future synchronous throw so the wrapper cannot leak.
/* v8 ignore start -- future-proofing guard, see above */
try {
acceptedId = agent.followup({ content, source: { kind: 'user' } })
acceptedContent = enqueued.get(acceptedId) ?? content
detachEnqueue()
agent.followup(message)
if (discarded.has(acceptedId)) cleanup()
} catch (error: unknown) {
cleanup()
@@ -1405,7 +1462,7 @@ export function createTuiChat(
renderEvent(event, { addHistory: false, renderChunks: true })
requestRender()
})
const settlePendingSteering = (id: AgentMessageId): void => {
const settlePendingSteering = (id: MessageId): void => {
if (pendingSteering.delete(id)) refreshStatus()
}
const disposeDequeued = ctx.on('agent/inbox/dequeue', (subject, message) => {
@@ -1525,6 +1582,13 @@ export function createTuiChat(
})
startBannerReveal()
// A launcher-seeded first turn (`dsh migrate`/`dsh upgrade`): invoke the
// named skill exactly as a typed `/skill:<name>` would, once the chat is live
// and the agent is idle. The launcher sets this only for a fresh session, so
// there is no prior turn to collide with; invokeSkill reports an unknown skill
// as a notice.
if (config.initialSkill !== undefined) invokeSkill(config.initialSkill, '')
return {
async dispose(): Promise<void> {
detachListeners()
@@ -1588,10 +1652,20 @@ export function apply(ctx: Context, config: Config): void {
// boundary from COLORTERM; an explicit theme value still wins.
const truecolor = config.theme?.truecolor ?? ['truecolor', '24bit'].includes(process.env.COLORTERM ?? '')
const resumeHost = ctx.get('tuiResumeHost')
mountTui(ctx, Object.assign({}, config, { theme: Object.assign({}, config.theme, { truecolor }) }), {
const goodbyeMessage = ctx.get('tuiGoodbyeMessage')
// The launcher seeds a guided fresh session's first turn through this key; a
// config value still wins. Consumed in createTuiChat via config.initialSkill.
const initialSkill = config.initialSkill ?? ctx.get('tuiInitialSkill')
mountTui(ctx, Object.assign(
{},
config,
{ theme: Object.assign({}, config.theme, { truecolor }) },
initialSkill === undefined ? {} : { initialSkill },
), {
terminal: new ProcessTerminal(),
exit: code => process.exit(code),
...resumeHost === undefined ? {} : { handoffResume: sessionId => resumeHost.handoff(sessionId) },
...resumeHost === undefined ? {} : { handoffResume: (sessionId, cwd) => resumeHost.handoff(sessionId, cwd) },
...goodbyeMessage === undefined ? {} : { goodbyeMessage },
})
}
/* v8 ignore stop */

View File

@@ -12,12 +12,17 @@ import type { SessionId } from '@deepseek-ai/dsh-session'
/** Process-lifecycle owner used by the shipped CLI for an atomic resume handoff. */
export interface TuiResumeHost {
/**
* Dispose the current app and replace it with a runtime for `sessionId`.
* Success does not return. A host may reject before it commits teardown;
* after commit it owns fatal reporting and process exit.
* Dispose the current app and replace it with a runtime for `sessionId` in
* `cwd`. Success does not return. A host may reject before it commits
* teardown; after commit it owns fatal reporting and process exit.
* @param sessionId - validated persisted session selected by the user.
* @param cwd - the selected session's own workspace, which the replacement
* process must run in: process cwd, not the restored session header, is what
* filesystem and shell tools resolve against. It may differ from the current
* workspace, so a host that cannot enter it must reject before committing
* teardown.
*/
handoff(sessionId: SessionId): Promise<never>
handoff(sessionId: SessionId, cwd: string): Promise<never>
}
/** Runtime boundary used by the interactive TUI. */
@@ -40,6 +45,13 @@ export interface TuiRuntime {
gitBranch?: (cwd: string) => string | undefined
/** Monotonic-enough wall clock for elapsed status rendering. Defaults to `Date.now`. */
now?(): number
/** Host-owned process handoff; absent leaves `resumeCommand` as the fallback. */
/** Host-owned process handoff; absent leaves the session selectable but not resumable in place. */
handoffResume?: TuiResumeHost['handoff']
/**
* Line the host wants printed once the terminal is released on exit, such as
* the command that resumes this session. Absent prints nothing. The host owns
* the wording; the TUI owns rendering and escapes terminal controls, so
* embedded ANSI is shown literally rather than applied.
*/
goodbyeMessage?: string
}

View File

@@ -1,7 +1,7 @@
import { createUserMessage, MessageId , createMessage } from '@deepseek-ai/dsh-llm'
import { Context } from 'cordis'
import type { Terminal } from '@earendil-works/pi-tui'
import AgentRegistry, {
AgentMessageId,
type Agent,
type AgentCancelCause,
type AgentOptions,
@@ -15,7 +15,7 @@ import type {
LlmResolvedModelInfo,
} from '@deepseek-ai/dsh-llm'
import CommandService from '@deepseek-ai/dsh-commands'
import SessionStore, { SessionId, type Session, type SessionHeader, type UserMessageData } from '@deepseek-ai/dsh-session'
import SessionStore, { SessionId, type Session, type SessionHeader, type UserMessage } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry, { type ToolDefinition } from '@deepseek-ai/dsh-tools'
import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
@@ -26,12 +26,13 @@ import TuiPromptService from '../src/prompt.ts'
interface FakeAgent extends Agent {
status: AgentStatus
sent: ContentBlock[][]
sentMessages: UserMessage[]
sentOptions: (SendOptions | undefined)[]
steered: ContentBlock[][]
steeredIds: AgentMessageId[]
steeredOptions: UserMessageData[]
steeredIds: MessageId[]
steeredOptions: UserMessage[]
injected: ContentBlock[][]
injectedOptions: UserMessageData[]
injectedOptions: UserMessage[]
cancelled: AgentCancelCause[]
}
@@ -70,6 +71,8 @@ export interface TuiHarnessOptions {
load?(id: ReturnType<typeof SessionId>): Promise<{ meta: SessionHeader; events: Session['events'] }>
}
handoffResume?: TuiRuntime['handoffResume']
/** Host-supplied exit line; absent exercises the no-message path. */
goodbyeMessage?: TuiRuntime['goodbyeMessage']
/** Set false to exercise the optional session-query degradation path. */
mountSessionQuery?: boolean
}
@@ -181,12 +184,13 @@ export async function createTuiTestHarness<TerminalType extends Terminal, Exit e
}
options.beforeMount?.(session)
const sent: ContentBlock[][] = []
const sentMessages: UserMessage[] = []
const steered: ContentBlock[][] = []
const steeredIds: AgentMessageId[] = []
const steeredIds: MessageId[] = []
const sentOptions: (SendOptions | undefined)[] = []
const steeredOptions: UserMessageData[] = []
const steeredOptions: UserMessage[] = []
const injected: ContentBlock[][] = []
const injectedOptions: UserMessageData[] = []
const injectedOptions: UserMessage[] = []
const cancelled: AgentCancelCause[] = []
const agent: FakeAgent = {
id: sessionId,
@@ -198,6 +202,7 @@ export async function createTuiTestHarness<TerminalType extends Terminal, Exit e
},
ctx,
sent,
sentMessages,
sentOptions,
steered,
steeredIds,
@@ -207,25 +212,27 @@ export async function createTuiTestHarness<TerminalType extends Terminal, Exit e
cancelled,
send(input, options) {
sent.push(input.content)
sentMessages.push(input)
sentOptions.push(options)
return AgentMessageId('stub')
return input.id
},
followup(input) {
sent.push(input.content)
sentMessages.push(input)
sentOptions.push(undefined)
return AgentMessageId('stub')
return input.id
},
steer(input) {
steered.push(input.content)
steeredOptions.push(input)
const id = AgentMessageId(`steering-${steeredIds.length + 1}`)
const id = input.id
steeredIds.push(id)
return id
},
inject(input) {
injected.push(input.content)
injectedOptions.push(input)
return AgentMessageId('stub')
return input.id
},
cancel(cause) {
cancelled.push(cause)
@@ -248,6 +255,7 @@ export async function createTuiTestHarness<TerminalType extends Terminal, Exit e
...(options.now === undefined ? {} : { now: options.now }),
...(options.formatCwd === undefined ? {} : { formatCwd: options.formatCwd }),
...(options.handoffResume === undefined ? {} : { handoffResume: options.handoffResume }),
...(options.goodbyeMessage === undefined ? {} : { goodbyeMessage: options.goodbyeMessage }),
gitBranch: options.gitBranch ?? (() => 'tui-staging'),
})
return { ctx, session, agent, terminal, exit, controller }
@@ -263,10 +271,10 @@ export async function disposeTuiTestHarness(
/** Append a production-shaped user message to the active session surface. */
export function appendUser(session: Session, text: string): void {
session.append('user/message', {
session.append('user/message', createUserMessage({
content: [{ type: 'text', text }],
source: { kind: 'user' },
}, { surfaceOp: 'append' })
}), { surfaceOp: 'append' })
}
/** Append a production-shaped assistant message to the active session surface. */
@@ -278,8 +286,11 @@ export function appendAssistant(
): void {
session.append('assistant/message', {
...position,
provenance: { provider: 'mock', model: 'deepseek-v4-flash' },
content,
message: createMessage({
role: 'assistant',
content,
source: { kind: 'model', provider: 'mock', model: 'deepseek-v4-flash' },
}),
...usage === undefined ? {} : { usage },
}, { surfaceOp: 'append' })
}

View File

@@ -3,7 +3,7 @@ import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import LlmService, { LlmAdapter, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm'
import LlmService, { createUserMessage, LlmAdapter, type GenerateOptions, type StreamChunk , createMessage } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
@@ -68,27 +68,33 @@ describe('TUI session-reference snapshot', () => {
const adapter = new SnapshotAdapter()
ctx.llm.registerAdapter(['mock'], adapter)
const source = ctx.sessions.create(SessionId('source-session'), { meta: { cwd: '/workspace/project', createdAt: 1 } })
const oldUser = source.append('user/message', {
const oldUser = source.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'SHADOWED OLD USER' }],
source: { kind: 'user' },
}, { surfaceOp: 'append' })
}), { surfaceOp: 'append' })
const oldAssistant = source.append('assistant/message', {
turn: 1,
step: 1,
provenance: { provider: 'mock', model: 'mock' },
content: [{ type: 'text', text: 'SHADOWED OLD ASSISTANT' }],
message: createMessage({
role: 'assistant',
content: [{ type: 'text', text: 'SHADOWED OLD ASSISTANT' }],
source: {
kind: 'model',
...{ provider: 'mock', model: 'mock' },
},
}),
}, { surfaceOp: 'append' })
source.append('user/message', {
source.append('user/message', createUserMessage({
content: [{ type: 'text', text: '<compacted-summary>Retained checkpoint.</compacted-summary>' }],
source: { kind: 'plugin', plugin: 'compact' },
}, {
}), {
surfaceOp: { op: 'replace', start: oldUser.seq, end: oldAssistant.seq },
sourceEventSeqs: [oldUser.seq, oldAssistant.seq],
})
source.append('user/message', {
source.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'Recent retained question.' }],
source: { kind: 'user' },
}, { surfaceOp: 'append' })
}), { surfaceOp: 'append' })
const target = ctx.agentLoop.create(
SessionId('target-session'),

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=34 bufferRow=34
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,7 +17,7 @@ buffer
6| "● Tool / bash / Run the coverage gate"
style 0-36 fg=green
7| "$ pnpm run test:coverage "
style 0-23 fg=cyan
style 0-23 dim
8| "/workspace/project "
style 0-17 dim
9| "… +4 lines (Ctrl+O to expand) "
@@ -39,11 +39,14 @@ buffer
18| "● Tool / subagent"
style 0-16 fg=green
19| "Delegate renderer audit "
style 0-99 dim
20| "The renderer has explicit lifecycle ownership. "
style 0-99 dim
21| <blank>
22| "● Tool / task_output"
style 0-19 fg=green
23| "Read output from background task subagent-7 "
style 0-99 dim
24| " "
25| "… +2 lines (Ctrl+O to expand) "
style 0-28 dim
@@ -52,18 +55,20 @@ buffer
28| "● Tool / skill"
style 0-13 fg=green
29| "Load skill dsh-code-review "
style 0-99 dim
30| "Loaded review instructions. "
style 0-99 dim
31| "Model wait 0.0s "
style 0-14 dim
32| <blank>
33| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
34| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
35-39| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=39 bufferRow=42
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,13 +17,17 @@ buffer
6| "● Tool / bash / Run the coverage gate"
style 0-36 fg=green
7| "$ pnpm run test:coverage "
style 0-23 fg=cyan
style 0-23 dim
8| "/workspace/project "
style 0-17 dim
9| "packages/ui/tui 100% "
style 0-19 dim
10| "4016 tests passed "
style 0-16 dim
11| "1 test skipped "
style 0-13 dim
12| "coverage complete "
style 0-16 dim
13| "[exit 0] "
style 0-7 dim
14| <blank>
@@ -45,35 +49,42 @@ buffer
23| "● Tool / subagent"
style 0-16 fg=green
24| "Delegate renderer audit "
style 0-99 dim
25| "The renderer has explicit lifecycle ownership. "
style 0-99 dim
26| <blank>
27| "● Tool / task_output"
style 0-19 fg=green
28| "Read output from background task subagent-7 "
style 0-99 dim
29| " "
30| "console "
style 0-6 dim
31| " started background task bash-5 "
style 2-31 fg=cyan
style 0-1 dim
style 2-31 fg=cyan dim
style 32-99 dim
32| " "
33| <blank>
34| "● Tool / skill"
style 0-13 fg=green
35| "Load skill dsh-code-review "
style 0-99 dim
36| "Loaded review instructions. "
style 0-99 dim
37| "Model wait 0.0s "
style 0-14 dim
38| <blank>
39| "Tool cards expanded. "
style 0-19 fg=bright-black
39| "Tool and context cards expanded. "
style 0-31 dim
40| <blank>
41| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
42| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse

View File

@@ -14,7 +14,7 @@ viewport
style 8-8 fg=#2498ff bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -24,13 +24,13 @@ viewport
style 0-14 dim
6| <blank>
7| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
8| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
9-35| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=15 bufferRow=15
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -25,13 +25,13 @@ buffer
style 0-14 dim
13| <blank>
14| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
15| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
16-35| <blank>

View File

@@ -4,19 +4,19 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=18 bufferRow=18
viewport
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
4| "Assistant "
style 0-8 fg=bright-magenta bold underline
5| "Reasoning "
style 0-8 fg=bright-black italic
style 0-8 dim italic
6| "Inspecting width and styles. "
style 0-27 fg=bright-black italic
style 0-27 dim italic
7| "Streaming visible state… "
style 10-22 bold
8| " "
@@ -29,17 +29,16 @@ viewport
style 0-30 dim
13| <blank>
14| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
15| "Show the live update. "
16| <blank>
17| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
18| " dsh ● press enter to steer and esc to cancel "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 7-44 dim
style 1-3 fg=bright-magenta bold
style 5-44 dim
19-35| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=21 bufferRow=21
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -33,13 +33,13 @@ buffer
style 0-14 dim
19| <blank>
20| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
21| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
22-35| <blank>

View File

@@ -1,13 +1,13 @@
terminal 92x32 buffer=normal length=38 base=6 viewport=6
terminal 92x32 buffer=normal length=37 base=5 viewport=5
lifecycle started=1 stopped=1 progress=inactive
title "DSH snapshot"
cursor visible column=0 viewportRow=31 bufferRow=37
cursor visible column=0 viewportRow=31 bufferRow=36
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,62 +17,60 @@ buffer
style 0-46 dim
6| <blank>
7| "Keyboard shortcuts "
style 0-17 fg=bright-blue bold
style 0-17 fg=bright-magenta bold
8| "Enter send • Shift/Alt+Enter newline • Up/Down prompt history "
style 0-60 fg=bright-black
9| "Esc cancel active turn • Ctrl+O toggle tool cards • Ctrl+R toggle reasoning "
style 0-74 fg=bright-black
10| "Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit "
style 0-72 fg=bright-black
11| " "
12| "/clear — Clear the transcript view (session history is unchanged) "
style 0-64 fg=bright-black
13| "/exit — Exit after the active turn reaches idle "
style 0-46 fg=bright-black
14| "/help — Show keyboard shortcuts and commands "
style 0-43 fg=bright-black
15| "/model [[provider/]model] — Show or switch this session's model "
style 0-62 fg=bright-black
16| "/quit — Exit after the active turn reaches idle "
style 0-46 fg=bright-black
17| "/reasoning — Toggle reasoning blocks "
style 0-35 fg=bright-black
18| "/redraw — Invalidate components and redraw the terminal "
style 0-54 fg=bright-black
style 0-60 dim
9| "Esc cancel turn • Ctrl+O cycle cards (collapse/expand/hide) • Ctrl+R toggle reasoning "
style 0-91 dim
10| "Ctrl+L redraw "
style 0-12 dim
11| "Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit "
style 0-72 dim
12| " "
13| "/clear — Clear the transcript view (session history is unchanged) "
style 0-64 dim
14| "/exit — Exit after the active turn reaches idle "
style 0-46 dim
15| "/help — Show keyboard shortcuts and commands "
style 0-43 dim
16| "/model [[provider/]model] — Show or switch this session's model "
style 0-62 dim
17| "/palette — Show every color and attribute role this terminal renders "
style 0-67 dim
18| "/quit — Exit after the active turn reaches idle "
style 0-46 dim
19| "/reload — EXPERIMENTAL (dev): re-read loader config files and apply the diff (idle only) "
style 0-87 fg=bright-black
style 0-87 dim
20| "/resume — List this workspace's resumable sessions "
style 0-49 fg=bright-black
style 0-49 dim
21| "/status — Show session diagnostics, system prompt, and registered tools "
style 0-70 fg=bright-black
22| "/tools — Expand or collapse all tool cards "
style 0-41 fg=bright-black
23| "/skill:<name> [instructions] — load a skill into the conversation "
style 0-64 fg=bright-black
24| <blank>
25| "provider stream failed after partial output "
style 0-70 dim
22| "/skill:<name> [instructions] — load a skill into the conversation "
style 0-64 dim
23| <blank>
24| "provider stream failed after partial output "
style 0-42 fg=red
26| <blank>
27| "The previous process ended during this turn. "
25| <blank>
26| "The previous process ended during this turn. "
style 0-43 fg=yellow
28| <blank>
29| "Turn stopped: the agent was disposed. "
27| <blank>
28| "Turn stopped: the agent was disposed. "
style 0-36 fg=yellow
30| <blank>
31| "Turn ended: plugin-policy. "
29| <blank>
30| "Turn ended: plugin-policy. "
style 0-25 fg=yellow
32| <blank>
33| "Unknown command: /unknown-advanced-command "
31| <blank>
32| "Unknown command: /unknown-advanced-command "
style 0-41 fg=yellow
34| <blank>
35| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
36| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
33| <blank>
34| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
35| " dsh > "
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
37| <blank>
36| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=17 bufferRow=17
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -28,13 +28,13 @@ buffer
style 0-14 dim
15| <blank>
16| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
17| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
18-35| <blank>

View File

@@ -1,13 +1,13 @@
terminal 92x32 buffer=normal length=37 base=5 viewport=5
terminal 92x32 buffer=normal length=36 base=4 viewport=4
lifecycle started=1 stopped=0 progress=inactive
title "DSH snapshot"
cursor hidden column=7 viewportRow=31 bufferRow=36
cursor hidden column=7 viewportRow=31 bufferRow=35
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,61 +17,59 @@ buffer
style 0-46 dim
6| <blank>
7| "Keyboard shortcuts "
style 0-17 fg=bright-blue bold
style 0-17 fg=bright-magenta bold
8| "Enter send • Shift/Alt+Enter newline • Up/Down prompt history "
style 0-60 fg=bright-black
9| "Esc cancel active turn • Ctrl+O toggle tool cards • Ctrl+R toggle reasoning "
style 0-74 fg=bright-black
10| "Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit "
style 0-72 fg=bright-black
11| " "
12| "/clear — Clear the transcript view (session history is unchanged) "
style 0-64 fg=bright-black
13| "/exit — Exit after the active turn reaches idle "
style 0-46 fg=bright-black
14| "/help — Show keyboard shortcuts and commands "
style 0-43 fg=bright-black
15| "/model [[provider/]model] — Show or switch this session's model "
style 0-62 fg=bright-black
16| "/quit — Exit after the active turn reaches idle "
style 0-46 fg=bright-black
17| "/reasoning — Toggle reasoning blocks "
style 0-35 fg=bright-black
18| "/redraw — Invalidate components and redraw the terminal "
style 0-54 fg=bright-black
style 0-60 dim
9| "Esc cancel turn • Ctrl+O cycle cards (collapse/expand/hide) • Ctrl+R toggle reasoning "
style 0-91 dim
10| "Ctrl+L redraw "
style 0-12 dim
11| "Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit "
style 0-72 dim
12| " "
13| "/clear — Clear the transcript view (session history is unchanged) "
style 0-64 dim
14| "/exit — Exit after the active turn reaches idle "
style 0-46 dim
15| "/help — Show keyboard shortcuts and commands "
style 0-43 dim
16| "/model [[provider/]model] — Show or switch this session's model "
style 0-62 dim
17| "/palette — Show every color and attribute role this terminal renders "
style 0-67 dim
18| "/quit — Exit after the active turn reaches idle "
style 0-46 dim
19| "/reload — EXPERIMENTAL (dev): re-read loader config files and apply the diff (idle only) "
style 0-87 fg=bright-black
style 0-87 dim
20| "/resume — List this workspace's resumable sessions "
style 0-49 fg=bright-black
style 0-49 dim
21| "/status — Show session diagnostics, system prompt, and registered tools "
style 0-70 fg=bright-black
22| "/tools — Expand or collapse all tool cards "
style 0-41 fg=bright-black
23| "/skill:<name> [instructions] — load a skill into the conversation "
style 0-64 fg=bright-black
24| <blank>
25| "provider stream failed after partial output "
style 0-70 dim
22| "/skill:<name> [instructions] — load a skill into the conversation "
style 0-64 dim
23| <blank>
24| "provider stream failed after partial output "
style 0-42 fg=red
26| <blank>
27| "The previous process ended during this turn. "
25| <blank>
26| "The previous process ended during this turn. "
style 0-43 fg=yellow
28| <blank>
29| "Turn stopped: the agent was disposed. "
27| <blank>
28| "Turn stopped: the agent was disposed. "
style 0-36 fg=yellow
30| <blank>
31| "Turn ended: plugin-policy. "
29| <blank>
30| "Turn ended: plugin-policy. "
style 0-25 fg=yellow
32| <blank>
33| "Unknown command: /unknown-advanced-command "
31| <blank>
32| "Unknown command: /unknown-advanced-command "
style 0-41 fg=yellow
34| <blank>
35| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
36| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
33| <blank>
34| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
35| " dsh > "
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=11 viewportRow=8 bufferRow=8
viewport
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,15 +17,15 @@ viewport
style 0-14 dim
6| <blank>
7| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
8| " dsh > @tsc "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 11-11 inverse
9| " → File · terminal-special-case.t src/terminal-special-case.ts "
style 7-38 fg=bright-blue
style 7-38 fg=bright-magenta
10-35| <blank>

View File

@@ -0,0 +1,52 @@
terminal 92x32 buffer=normal length=32 base=0 viewport=0
lifecycle started=1 stopped=0 progress=inactive
title "DSH snapshot"
cursor hidden column=15 viewportRow=13 bufferRow=13
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
4| "Assistant "
style 0-8 fg=bright-magenta bold underline
5| "Model wait 0.0s "
style 0-14 dim
6| <blank>
7| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
8| " dsh > "
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
9-11| <blank>
12| " ╭ Select model ────────────────────────────────────────────────────────────╮ "
style 8-83 fg=bright-magenta
13| " │ > pro │ "
style 8-8 fg=bright-magenta
style 15-15 inverse
style 83-83 fg=bright-magenta
14| " │ │ "
style 8-8 fg=bright-magenta
style 83-83 fg=bright-magenta
15| " │ → deepseek/deepseek-v4-pro DeepSeek V4 Pro │ "
style 8-8 fg=bright-magenta
style 10-58 fg=bright-magenta inverse
style 83-83 fg=bright-magenta
16| " │ │ "
style 8-8 fg=bright-magenta
style 83-83 fg=bright-magenta
17| " │ type to filter • ↑/↓ move • Shift+Tab reasoning • Enter select • Esc │ "
style 8-8 fg=bright-magenta
style 10-77 dim
style 83-83 fg=bright-magenta
18| " ╰──────────────────────────────────────────────────────────────────────────╯ "
style 8-83 fg=bright-magenta
19-31| <blank>

View File

@@ -1,13 +1,13 @@
terminal 92x32 buffer=normal length=32 base=0 viewport=0
lifecycle started=1 stopped=0 progress=inactive
title "DSH snapshot"
cursor hidden column=0 viewportRow=31 bufferRow=31
cursor hidden column=12 viewportRow=13 bufferRow=13
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,33 +17,40 @@ buffer
style 0-14 dim
6| <blank>
7| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
8| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
9-12| <blank>
13| " ╭ Select model ────────────────────────────────────────────────────────────╮ "
style 8-83 fg=bright-blue
14| " │ → deepseek/deepseek-v4-flash DeepSeek V4 Flash — current │ "
style 8-8 fg=bright-blue
style 10-70 fg=bright-blue inverse
style 83-83 fg=bright-blue
15| " │ deepseek/deepseek-v4-pro DeepSeek V4 Pro │ "
style 8-8 fg=bright-blue
style 36-58 fg=bright-black
style 83-83 fg=bright-blue
16| " │ │ "
style 8-8 fg=bright-blue
style 83-83 fg=bright-blue
17| " │ ↑/↓ navigate • Shift+Tab reasoning • Enter select • Esc cancel │ "
style 8-8 fg=bright-blue
style 10-71 dim
style 83-83 fg=bright-blue
18| " ╰──────────────────────────────────────────────────────────────────────────╯ "
style 8-83 fg=bright-blue
19-31| <blank>
9-11| <blank>
12| " ╭ Select model ────────────────────────────────────────────────────────────╮ "
style 8-83 fg=bright-magenta
13| " │ > │ "
style 8-8 fg=bright-magenta
style 12-12 inverse
style 83-83 fg=bright-magenta
14| " │ │ "
style 8-8 fg=bright-magenta
style 83-83 fg=bright-magenta
15| " │ → deepseek/deepseek-v4-flash DeepSeek V4 Flash — current │ "
style 8-8 fg=bright-magenta
style 10-70 fg=bright-magenta inverse
style 83-83 fg=bright-magenta
16| " │ deepseek/deepseek-v4-pro DeepSeek V4 Pro │ "
style 8-8 fg=bright-magenta
style 36-58 dim
style 83-83 fg=bright-magenta
17| " │ │ "
style 8-8 fg=bright-magenta
style 83-83 fg=bright-magenta
18| " │ type to filter • ↑/↓ move • Shift+Tab reasoning • Enter select • Esc │ "
style 8-8 fg=bright-magenta
style 10-77 dim
style 83-83 fg=bright-magenta
19| " ╰──────────────────────────────────────────────────────────────────────────╯ "
style 8-83 fg=bright-magenta
20-31| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=10 bufferRow=10
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,16 +17,16 @@ buffer
style 0-14 dim
6| <blank>
7| "Model selected: deepseek/deepseek-v4-pro. New steps will use it. "
style 0-63 fg=bright-black
style 0-63 dim
8| <blank>
9| "/workspace/project (tui-staging) deepseek-v4-pro ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-48 fg=bright-black
style 51-55 fg=bright-black
style 58-67 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-48 dim
style 51-55 dim
style 58-67 dim
10| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
11-31| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=0 viewportRow=19 bufferRow=19
viewport
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,23 +17,23 @@ viewport
style 0-14 dim
6| <blank>
7| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 "
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-55 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-55 dim
8| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
9-11| <blank>
12| " "
13| " Question 1/1 (1 unanswered) · Confirm "
style 2-38 fg=bright-black
style 2-38 dim
14| " Continue with this change? "
15| " "
16| " 1. Proceed Apply the proposed change "
style 2-13 fg=bright-blue bold
style 16-40 fg=bright-black
style 2-13 fg=bright-magenta bold
style 16-40 dim
17| " Tab custom answer • Enter submit • Esc interrupt "
style 2-49 dim
18| " "

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=56 viewportRow=17 bufferRow=17
viewport
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -15,17 +15,17 @@ viewport
style 0-8 fg=bright-magenta bold underline
5| " "
6| " Question 1/3 (3 unanswered) · Coverage "
style 2-39 fg=bright-black
style 2-39 dim
7| " Which advanced TUI states belong in the required "
8| " matrix? "
9| " "
10| " 1. [ ] Code Mode run_code programs and capture "
style 2-19 fg=bright-blue bold
style 25-53 fg=bright-black
style 2-19 fg=bright-magenta bold
style 25-53 dim
11| " 2. [ ] Workflows phases and parallel agents "
style 25-50 fg=bright-black
style 25-50 dim
12| " 3. [ ] Cordis tools inspect, mount, and unmount "
style 25-51 fg=bright-black
style 25-51 dim
13| " 1/4 "
style 2-4 dim
14| " Tab custom answer • ↑/↓ navigate • Space toggle • "

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=0 viewportRow=19 bufferRow=19
viewport
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -18,17 +18,17 @@ viewport
6| <blank>
7| " "
8| " Question 1/3 (3 unanswered) · Coverage "
style 2-39 fg=bright-black
style 2-39 dim
9| " Which advanced TUI states belong in the required "
10| " matrix? "
11| " "
12| " 1. [ ] Code Mode run_code programs and capture "
style 2-19 fg=bright-blue bold
style 25-53 fg=bright-black
style 2-19 fg=bright-magenta bold
style 25-53 dim
13| " 2. [ ] Workflows phases and parallel agents "
style 25-50 fg=bright-black
style 25-50 dim
14| " 3. [ ] Cordis tools inspect, mount, and unmount "
style 25-51 fg=bright-black
style 25-51 dim
15| " 1/4 "
style 2-4 dim
16| " Tab custom answer • ↑/↓ navigate • Space toggle • "

View File

@@ -0,0 +1,57 @@
terminal 92x32 buffer=normal length=32 base=0 viewport=0
lifecycle started=1 stopped=0 progress=inactive
title "DSH snapshot"
cursor hidden column=6 viewportRow=4 bufferRow=4
buffer
0| " "
1| " Resume session (1 of 3) "
style 2-24 fg=bright-magenta bold
2| " "
3| " ╭──────────────────────────────────────────────────────────────────────────────────────╮ "
style 2-89 dim
4| " │ ⌕ │ "
style 2-2 dim
style 6-6 inverse
style 89-89 dim
5| " ╰──────────────────────────────────────────────────────────────────────────────────────╯ "
style 2-89 dim
6| " "
7| " all workspaces (3) ⇥ this workspace (2) "
style 2-19 fg=bright-magenta
style 20-41 dim
8| " "
9| " Untitled session "
style 2-19 fg=bright-magenta bold
10| " 2026-07-23T08:00:00.000Z · no completed turn · route unavailable "
style 2-67 dim
11| " current · live · main-session "
style 2-32 dim
12| " workspace /workspace/project "
style 2-31 dim
13| " unavailable: current session "
style 2-31 fg=yellow
14| " Other workspace work "
15| " 2024-02-02T00:00:08.000Z · turn 1: completed · deepseek/deepseek-v4-pro "
style 2-74 dim
16| " persisted · elsewhere-session "
style 2-32 dim
17| " workspace /workspace/other "
style 2-29 dim
18| " Resume selector design "
19| " 2024-01-01T00:00:08.000Z · turn 1: completed · deepseek/deepseek-v4-pro "
style 2-74 dim
20| " persisted · earlier-session "
style 2-30 dim
21| " workspace /workspace/project "
style 2-31 dim
22| " "
23| " "
24| " "
25| " "
26| " "
27| " "
28| " "
29| " "
30| " Type to search • ↑/↓ navigate • Tab scope • Enter resume • Esc clear/cancel "
style 2-84 dim
31| " "

View File

@@ -5,7 +5,7 @@ cursor hidden column=6 viewportRow=4 bufferRow=4
buffer
0| " "
1| " Resume session (1 of 2) "
style 2-24 fg=bright-blue bold
style 2-24 fg=bright-magenta bold
2| " "
3| " ╭──────────────────────────────────────────────────────────────────────────────────────╮ "
style 2-89 dim
@@ -16,20 +16,21 @@ buffer
5| " ╰──────────────────────────────────────────────────────────────────────────────────────╯ "
style 2-89 dim
6| " "
7| " /workspace/project "
style 2-19 fg=bright-black
7| " this workspace /workspace/project ⇥ all workspaces (3) "
style 2-34 fg=bright-magenta
style 35-56 dim
8| " "
9| " Untitled session "
style 2-19 fg=bright-blue bold
style 2-19 fg=bright-magenta bold
10| " 2026-07-23T08:00:00.000Z · no completed turn · route unavailable "
style 2-67 fg=bright-black
style 2-67 dim
11| " current · live · main-session "
style 2-32 dim
12| " unavailable: current session "
style 2-31 fg=yellow
13| " Resume selector design "
14| " 2024-01-01T00:00:08.000Z · turn 1: completed · deepseek/deepseek-v4-pro "
style 2-74 fg=bright-black
style 2-74 dim
15| " persisted · earlier-session "
style 2-30 dim
16| " "
@@ -46,6 +47,6 @@ buffer
27| " "
28| " "
29| " "
30| " Type to search • ↑/↓ navigate • Enter resume • Esc clear/cancel "
style 2-70 dim
30| " Type to search • ↑/↓ navigate • Tab scope • Enter resume • Esc clear/cancel "
style 2-84 dim
31| " "

View File

@@ -4,15 +4,15 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=12 bufferRow=12
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
4| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
5| "Start then cancel. "
6| <blank>
7| "Retrying model request (1/∞) in 1000ms: temporary transport failure "
@@ -22,13 +22,13 @@ buffer
style 0-14 fg=yellow
10| <blank>
11| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
12| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
13-35| <blank>

View File

@@ -4,28 +4,28 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=10 bufferRow=10
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
4| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
5| "Let the bounded policy exhaust. "
6| <blank>
7| "provider still unavailable "
style 0-25 fg=red
8| <blank>
9| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
10| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
11-35| <blank>

View File

@@ -4,28 +4,28 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=10 bufferRow=10
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
4| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
5| "Recover this request. "
6| <blank>
7| "Retrying model request (1/2) in 500ms: provider rate limit "
style 0-57 fg=yellow
8| <blank>
9| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
10| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
11-35| <blank>

View File

@@ -4,28 +4,28 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=10 bufferRow=10
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
4| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
5| "Recover this request. "
6| <blank>
7| "Retrying model request (1/2) in 500ms: provider rate limit "
style 0-57 fg=yellow
8| <blank>
9| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
10| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
11-35| <blank>

View File

@@ -4,15 +4,15 @@ title "DSH session reference"
cursor hidden column=7 viewportRow=14 bufferRow=14
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Session reference snapshot."
style 1-27 fg=bright-black
style 1-27 dim
2| " target-session"
style 1-14 dim
3| <blank>
4| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
5| "Use @Source session "
6| <blank>
7| "Referenced sessions · Source session (source-session) "
@@ -25,11 +25,11 @@ buffer
style 0-46 dim
12| <blank>
13| "/workspace/project mock ↑0 ↓0"
style 0-17 fg=bright-blue bold
style 20-23 fg=bright-black
style 26-30 fg=bright-black
style 0-17 fg=bright-magenta bold
style 20-23 dim
style 26-30 dim
14| " dsh ◍ "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
15-23| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=14 viewportRow=8 bufferRow=8
viewport
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,15 +17,15 @@ viewport
style 0-14 dim
6| <blank>
7| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
8| " dsh > @design "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 14-14 inverse
9| " → Session · Searchable design re opaque-source-id · /workspace/project · 1970-01-01T0 "
style 7-38 fg=bright-blue
style 7-38 fg=bright-magenta
10-35| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=38 viewportRow=13 bufferRow=13
viewport
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -17,9 +17,9 @@ viewport
style 0-14 dim
6| <blank>
7| "/workspace/project (tui-staging) deepseek-v"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-43 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-43 dim
8| " ↑ 1 more "
style 1-14 dim
9| " enough detail to wrap across multiple "

View File

@@ -4,10 +4,10 @@ title "Inspect session diagnostics — DSH snapshot"
cursor hidden column=7 viewportRow=35 bufferRow=43
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Inspect session diagnostics"
style 1-27 fg=bright-black
style 1-27 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -18,28 +18,28 @@ buffer
style 0-14 dim
7| <blank>
8| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
9| "inspect this session "
10| <blank>
11| "╭─ Session status ─────────────────────────────────────╮"
style 0-2 dim
style 3-16 fg=bright-blue bold
style 3-16 fg=bright-magenta bold
style 17-55 dim
12| "│ Session: main-session │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 55-55 dim
13| "│ Title: Inspect session diagnostics │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 55-55 dim
14| "│ Directory: /workspace/project │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 55-55 dim
15| "│ Model: deepseek/deepseek-v4-pro (effort │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 40-55 dim
16| "│ default; reasoning blocks shown) │"
style 0-0 dim
@@ -48,9 +48,9 @@ buffer
17| "│ │"
style 0-0 dim
style 55-55 dim
18| "│ Agent: idle · 6 events · 1 turn · 1 step · 1 │"
18| "│ Agent: idle · 7 events · 1 turn · 1 step · 1 │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 55-55 dim
19| "│ tool call │"
style 0-0 dim
@@ -60,13 +60,13 @@ buffer
style 55-55 dim
21| "│ Tokens: 1,250 input + 340 output │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 55-55 dim
22| "│ KV cache: [███████████░░░░░] 67% hit (3,000 read │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 15-15 dim
style 16-26 fg=bright-blue
style 16-26 fg=bright-magenta
style 27-32 dim
style 55-55 dim
23| "│ + 250 write) │"
@@ -74,9 +74,9 @@ buffer
style 55-55 dim
24| "│ Context: [█████░░░░░░░░░░░] 33% used (42,000 / │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 15-15 dim
style 16-20 fg=bright-blue
style 16-20 fg=bright-magenta
style 21-32 dim
style 55-55 dim
25| "│ 128,000) │"
@@ -87,17 +87,17 @@ buffer
style 55-55 dim
27| "│ Created: 2026-07-22 09:10:11 UTC │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 55-55 dim
28| "│ Active: 2026-07-22 09:10:11 UTC │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 55-55 dim
29| "╰──────────────────────────────────────────────────────╯"
style 0-55 dim
30| <blank>
31| "System prompt "
style 0-12 fg=bright-blue bold
style 0-12 fg=bright-magenta bold
32| "You are an AI agent powered by the DeepSeek Harness SDK."
33| " "
34| "Paths prefixed with @ are files explicitly referenced by"
@@ -106,15 +106,15 @@ buffer
37| "reading it. "
38| <blank>
39| "Registered tools "
style 0-15 fg=bright-blue bold
style 0-15 fg=bright-magenta bold
40| "read, write "
41| <blank>
42| "/workspace/project (tui-staging) deepseek-v4-pro ↑1.3k"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-48 fg=bright-black
style 51-55 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-48 dim
style 51-55 dim
43| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse

View File

@@ -4,10 +4,10 @@ title "Inspect session diagnostics — DSH snapshot"
cursor hidden column=7 viewportRow=31 bufferRow=37
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Inspect session diagnostics"
style 1-27 fg=bright-black
style 1-27 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -18,56 +18,56 @@ buffer
style 0-14 dim
7| <blank>
8| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
9| "inspect this session "
10| <blank>
11| "╭─ Session status ───────────────────────────────────────────────────────────────╮"
style 0-2 dim
style 3-16 fg=bright-blue bold
style 3-16 fg=bright-magenta bold
style 17-81 dim
12| "│ Session: main-session │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 81-81 dim
13| "│ Title: Inspect session diagnostics │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 81-81 dim
14| "│ Directory: /workspace/project │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 81-81 dim
15| "│ Model: deepseek/deepseek-v4-pro (effort default; reasoning blocks shown) │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 40-79 dim
style 81-81 dim
16| "│ │"
style 0-0 dim
style 81-81 dim
17| "│ Agent: idle · 6 events · 1 turn · 1 step · 1 tool call │"
17| "│ Agent: idle · 7 events · 1 turn · 1 step · 1 tool call │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 81-81 dim
18| "│ │"
style 0-0 dim
style 81-81 dim
19| "│ Tokens: 1,250 input + 340 output │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 81-81 dim
20| "│ KV cache: [███████████░░░░░] 67% hit (3,000 read + 250 write) │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 15-15 dim
style 16-26 fg=bright-blue
style 16-26 fg=bright-magenta
style 27-32 dim
style 81-81 dim
21| "│ Context: [█████░░░░░░░░░░░] 33% used (42,000 / 128,000) │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 15-15 dim
style 16-20 fg=bright-blue
style 16-20 fg=bright-magenta
style 21-32 dim
style 81-81 dim
22| "│ │"
@@ -75,33 +75,33 @@ buffer
style 81-81 dim
23| "│ Created: 2026-07-22 09:10:11 UTC │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 81-81 dim
24| "│ Active: 2026-07-22 09:10:11 UTC │"
style 0-0 dim
style 3-12 fg=bright-black
style 3-12 dim
style 81-81 dim
25| "╰────────────────────────────────────────────────────────────────────────────────╯"
style 0-81 dim
26| <blank>
27| "System prompt "
style 0-12 fg=bright-blue bold
style 0-12 fg=bright-magenta bold
28| "You are an AI agent powered by the DeepSeek Harness SDK. "
29| " "
30| "Paths prefixed with @ are files explicitly referenced by the user. Use the read tool when "
31| "their contents are needed; do not claim to have inspected a file before reading it. "
32| <blank>
33| "Registered tools "
style 0-15 fg=bright-blue bold
style 0-15 fg=bright-magenta bold
34| "read, write "
35| <blank>
36| "/workspace/project (tui-staging) deepseek-v4-pro ↑1.3k ↓340 cache 67% 33% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-48 fg=bright-black
style 51-71 fg=bright-black
style 74-84 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-48 dim
style 51-71 dim
style 74-84 dim
37| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse

View File

@@ -4,31 +4,31 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=11 bufferRow=11
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
4| "Assistant "
style 0-8 fg=bright-magenta bold underline
5| "Reasoning "
style 0-8 fg=bright-black italic
style 0-8 dim italic
6| "Checking the result. "
style 0-19 fg=bright-black italic
style 0-19 dim italic
7| "The result is ready. "
8| "Model wait 1.0s · Thinking 2.0s · Response 3.0s · Completed 2026-07-21 14:32:12 "
style 0-78 dim
9| <blank>
10| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
11| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
12-35| <blank>

View File

@@ -1,13 +1,13 @@
terminal 44x18 buffer=normal length=18 base=0 viewport=0
lifecycle started=1 stopped=0 progress=inactive
title "DSH snapshot"
cursor hidden column=7 viewportRow=15 bufferRow=15
cursor hidden column=7 viewportRow=14 bufferRow=14
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -16,21 +16,22 @@ buffer
5| "Model wait 0.0s "
style 0-14 dim
6| <blank>
7| "Context · workspace-context "
7| "Context · workspace-context"
style 0-26 dim
8| "system-reminder "
style 0-14 fg=bright-black
9| " Additional instructions from: "
10| "nested/AGENTS.md "
11| " "
12| " Render workspace context XML clearly. "
13| <blank>
14| "/workspace/project (tui-staging) deepseek-v"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-43 fg=bright-black
15| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
8| "Additional instructions from: "
style 0-43 dim
9| "nested/AGENTS.md "
style 0-15 dim
10| " "
11| "Render workspace context XML clearly. "
style 0-36 dim
12| <blank>
13| "/workspace/project (tui-staging) deepseek-v"
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-43 dim
14| " dsh > "
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
16-17| <blank>
15-17| <blank>

View File

@@ -1,13 +1,13 @@
terminal 104x30 buffer=normal length=30 base=0 viewport=0
lifecycle started=1 stopped=0 progress=inactive
title "DSH snapshot"
cursor hidden column=7 viewportRow=14 bufferRow=14
cursor hidden column=7 viewportRow=13 bufferRow=13
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -16,22 +16,22 @@ buffer
5| "Model wait 0.0s "
style 0-14 dim
6| <blank>
7| "Context · workspace-context "
7| "Context · workspace-context"
style 0-26 dim
8| "system-reminder "
style 0-14 fg=bright-black
9| " Additional instructions from: nested/AGENTS.md "
10| " "
11| " Render workspace context XML clearly. "
12| <blank>
13| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
14| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
8| "Additional instructions from: nested/AGENTS.md "
style 0-45 dim
9| " "
10| "Render workspace context XML clearly. "
style 0-36 dim
11| <blank>
12| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
13| " dsh > "
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
15-29| <blank>
14-29| <blank>

View File

@@ -4,10 +4,10 @@ title "DSH snapshot"
cursor hidden column=7 viewportRow=20 bufferRow=20
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 fg=bright-black
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -15,33 +15,36 @@ buffer
style 0-8 fg=bright-magenta bold underline
5| <blank>
6| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
7| "Old prompt with a long line that exercises wrapping before compaction. "
8| <blank>
9| "● Tool / bash / Run the coverage gate"
style 0-36 fg=green
10| "$ pnpm run test:coverage "
style 0-23 fg=cyan
style 0-23 dim
11| "/workspace/project "
style 0-17 dim
12| "packages/ui/tui 100% "
style 0-19 dim
13| "… +1 lines (Ctrl+O to expand) "
style 0-28 dim
14| "1 test skipped "
style 0-13 dim
15| "coverage complete "
style 0-16 dim
16| "[exit 0] "
style 0-7 dim
17| "Model wait 0.0s "
style 0-14 dim
18| <blank>
19| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
20| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
21-23| <blank>

View File

@@ -0,0 +1,38 @@
terminal 96x36 buffer=normal length=36 base=0 viewport=0
lifecycle started=1 stopped=0 progress=inactive
title "DSH snapshot"
cursor hidden column=7 viewportRow=15 bufferRow=15
viewport
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Snapshot agent ready."
style 1-21 dim
2| " main-session"
style 1-12 dim
3| <blank>
4| "Assistant "
style 0-8 fg=bright-magenta bold underline
5| "Tracking the steps. "
6| "Model wait 0.0s · Completed 2026-07-21 14:45:00 "
style 0-46 dim
7| <blank>
8| "You "
style 0-2 fg=bright-magenta bold underline
9| "Plan the work. "
10| <blank>
11| "You "
style 0-2 fg=bright-magenta bold underline
12| "Next question. "
13| <blank>
14| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
15| " dsh > "
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
16-35| <blank>

View File

@@ -4,10 +4,10 @@ title "Unsafe terminal title \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m"
cursor hidden column=0 viewportRow=33 bufferRow=33
buffer
0| " DEEPSEEK HARNESS"
style 1-8 fg=bright-blue bold
style 1-8 fg=bright-magenta bold
style 10-16 bold
1| " Unsafe welcome \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m"
style 1-60 fg=bright-black
style 1-60 dim
2| " main-session"
style 1-12 dim
3| <blank>
@@ -15,51 +15,52 @@ buffer
style 0-8 fg=bright-magenta bold underline
5| <blank>
6| "You "
style 0-2 fg=bright-blue bold underline
style 0-2 fg=bright-magenta bold underline
7| "Unsafe user \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
8| <blank>
9| "● Tool / unsafe / Unsafe description \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m"
style 0-81 fg=green
10| "$ Unsafe title \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
style 0-59 fg=cyan
style 0-59 dim
11| "/unsafe/\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
style 0-52 dim
12| "Unsafe output \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
style 0-58 dim
13| "[signal SIG\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m] "
style 0-56 fg=red
14| "Model wait 0.0s · Completed 2026-07-21 15:00:00 "
style 0-46 dim
15| <blank>
16| "Context · unsafe-\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
16| "Context · unsafe-\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m"
style 0-61 dim
17| "Unsafe context \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
style 0-59 fg=bright-black
style 0-59 dim
18| <blank>
19| "Unsafe turn error \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
style 0-62 fg=red
20-21| <blank>
22| "Plan"
style 0-3 fg=bright-blue bold
style 0-3 fg=bright-magenta bold
23| " ● Unsafe todo \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m"
style 2-2 fg=yellow
24| "/workspace/project (tui-staging) deepseek-v4-flash ↑0 ↓0 0% context"
style 0-17 fg=bright-blue bold
style 18-31 fg=bright-black
style 34-50 fg=bright-black
style 53-57 fg=bright-black
style 60-69 fg=bright-black
style 0-17 fg=bright-magenta bold
style 18-31 dim
style 34-50 dim
style 53-57 dim
style 60-69 dim
25| " dsh > "
style 1-3 fg=bright-blue bold
style 5-6 fg=bright-black
style 1-3 fg=bright-magenta bold
style 5-6 dim
style 7-7 inverse
26| " "
27| " Question 1/1 (1 unanswered) · Unsafe header \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
style 2-90 fg=bright-black
style 2-90 dim
28| " Unsafe question \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m "
29| " "
30| " 1. Unsafe option \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m Unsafe detail \\x1b]2;snapshot-c "
style 2-65 fg=bright-blue bold
style 67-97 fg=bright-black
style 2-65 fg=bright-magenta bold
style 67-97 dim
31| " Tab custom answer • Enter submit • Esc interrupt "
style 2-49 dim
32| " "

View File

@@ -5,9 +5,9 @@ import { fileURLToPath } from 'node:url'
import { afterAll, describe, expect, it, vi } from 'vitest'
import type { Context } from 'cordis'
import { agentEvents } from '@deepseek-ai/dsh-agent'
import { CallId, type ContentBlock } from '@deepseek-ai/dsh-llm'
import { createUserMessage, CallId, type ContentBlock , createMessage, createToolResultMessage } from '@deepseek-ai/dsh-llm'
import type {} from '@deepseek-ai/dsh-llm-retry'
import { SessionId, type JsonValue, type Session } from '@deepseek-ai/dsh-session'
import { SessionId, type JsonValue, type Session, type SessionEvent } from '@deepseek-ai/dsh-session'
import SessionReferenceService from '@deepseek-ai/dsh-session-reference'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry, { type ToolDefinition, type ToolResultView } from '@deepseek-ai/dsh-tools'
@@ -51,12 +51,15 @@ const CHECKPOINTS = [
'surface-after-compaction-narrow',
'surface-after-compaction-wide',
'model-selector',
'model-selector-filtered',
'model-switching',
'errors-and-help',
'disposed-terminal',
'resume-sessions',
'resume-sessions-all-workspaces',
'status-diagnostics',
'status-diagnostics-narrow',
'todo-plan-cleared',
] as const
// Real-loop scenarios own their assertions in separate snapshot suites but
@@ -169,9 +172,11 @@ function appendToolResult(
session.append('tool/result', {
turn: 1,
step: 1,
callId: CallId(id),
content,
isError: options.isError ?? false,
message: createToolResultMessage({
callId: CallId(id),
content,
isError: options.isError ?? false,
}),
...options.meta === undefined ? {} : { meta: options.meta },
}, { surfaceOp: 'append' })
}
@@ -299,6 +304,34 @@ describe('TUI terminal-state snapshots', () => {
await disposeSnapshot(harness)
})
it('clears the plan strip when the next turn starts', async () => {
// Freeze Completed-at formatting: the first turn ends before the next starts,
// so the assistant timing line still appears without a Plan strip below it.
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(new Date(2026, 6, 21, 14, 45, 0).getTime())
const harness = await setupSnapshot({
beforeMount(session) {
appendUser(session, 'Plan the work.')
appendAssistant(session, [{ type: 'text', text: 'Tracking the steps.' }])
session.append('todo/write', {
todos: [
{ content: 'read code', status: 'completed' },
{ content: 'write tests', status: 'in_progress' },
],
})
session.append('step/end', { turn: 1, step: 1 })
session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
session.append('turn/start', {
turn: 2,
trigger: { kind: 'message', source: { kind: 'user' } },
})
appendUser(session, 'Next question.')
},
})
await checkpoint('todo-plan-cleared', harness.terminal)
nowSpy.mockRestore()
await disposeSnapshot(harness)
})
it('pins failed-stream retraction, scheduled retry, and eventual success', async () => {
const harness = await setupSnapshot()
await renderAfter(harness, () => {
@@ -325,8 +358,14 @@ describe('TUI terminal-state snapshots', () => {
harness.session.append('assistant/message', {
turn: 1,
step: 2,
provenance: { provider: 'mock', model: 'deepseek-v4-flash' },
content: [{ type: 'text', text: 'Recovered on the next bounded attempt.' }],
message: createMessage({
role: 'assistant',
content: [{ type: 'text', text: 'Recovered on the next bounded attempt.' }],
source: {
kind: 'model',
...{ provider: 'mock', model: 'deepseek-v4-flash' },
},
}),
}, { surfaceOp: 'append' })
harness.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
await checkpoint('retry-recovered', harness.terminal, { includeScrollback: true })
@@ -542,10 +581,10 @@ describe('TUI terminal-state snapshots', () => {
session.append('todo/write', {
todos: [{ content: `Unsafe todo ${CONTROL_PROBE}`, status: 'in_progress' }],
})
session.append('user/message', {
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: `Unsafe context ${CONTROL_PROBE}` }],
source: { kind: 'plugin', plugin: `unsafe-${CONTROL_PROBE}` },
}, { surfaceOp: 'append' })
}), { surfaceOp: 'append' })
session.append('step/end', { turn: 1, step: 1 })
session.append('turn/end', {
turn: 1,
@@ -656,23 +695,31 @@ describe('TUI terminal-state snapshots', () => {
const harness = await setupSnapshot({
tools: ADVANCED_CARD_TOOLS,
beforeMount(session) {
const user = session.append('user/message', {
const user = session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'Old prompt with a long line that exercises wrapping before compaction.' }],
source: { kind: 'user' },
}, { surfaceOp: 'append' })
}), { surfaceOp: 'append' })
const assistant = session.append('assistant/message', {
turn: 1,
step: 1,
provenance: { provider: 'mock', model: 'deepseek-v4-flash' },
content: [{ type: 'tool-call', id: CallId('old-tool'), name: 'bash', arguments: '{}' }],
message: createMessage({
role: 'assistant',
content: [{ type: 'tool-call', id: CallId('old-tool'), name: 'bash', arguments: '{}' }],
source: {
kind: 'model',
...{ provider: 'mock', model: 'deepseek-v4-flash' },
},
}),
}, { surfaceOp: 'append' })
session.append('tool/call', { turn: 1, step: 1, callId: CallId('old-tool'), name: 'bash', arguments: '{}' })
const result = session.append('tool/result', {
turn: 1,
step: 1,
callId: CallId('old-tool'),
content: [{ type: 'text', text: 'obsolete output that must disappear' }],
isError: false,
message: createToolResultMessage({
callId: CallId('old-tool'),
content: [{ type: 'text', text: 'obsolete output that must disappear' }],
isError: false,
}),
}, { surfaceOp: 'append' })
replacementStart = user.seq
replacementEnd = result.seq
@@ -682,13 +729,13 @@ describe('TUI terminal-state snapshots', () => {
await checkpoint('surface-before-compaction', harness.terminal, { includeScrollback: true })
await renderAfter(harness, () => {
harness.session.append('user/message', {
harness.session.append('user/message', createUserMessage({
content: [{
type: 'text',
text: '<system-reminder>\nAdditional instructions from: nested/AGENTS.md\n\nRender workspace context XML clearly.\n</system-reminder>',
}],
source: { kind: 'plugin', plugin: 'workspace-context' },
}, {
}), {
surfaceOp: { op: 'replace', start: replacementStart, end: replacementEnd },
sourceEventSeqs: replacementSources,
})
@@ -756,6 +803,10 @@ describe('TUI terminal-state snapshots', () => {
harness.terminal.send('\r')
})
await checkpoint('model-selector', harness.terminal, { includeScrollback: true })
await renderAfter(harness, () => {
harness.terminal.send('pro')
})
await checkpoint('model-selector-filtered', harness.terminal, { includeScrollback: true })
await renderAfter(harness, () => {
harness.terminal.send('\x1b[B')
harness.terminal.send('\r')
@@ -767,23 +818,33 @@ describe('TUI terminal-state snapshots', () => {
it('opens the searchable resume selector with log-backed session summaries', async () => {
const dateNow = vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-07-23T08:00:00.000Z'))
const earlier = { version: 0, id: SessionId('earlier-session'), createdAt: Date.parse('2024-01-01T00:00:00Z'), cwd: '/workspace/project' }
const elsewhere = { version: 0, id: SessionId('elsewhere-session'), createdAt: Date.parse('2024-02-02T00:00:00Z'), cwd: '/workspace/other' }
const log = (meta: typeof earlier, title: string, day: string): { meta: typeof earlier; events: SessionEvent[] } => ({
meta,
events: [
{ type: 'turn/start', seq: 0, time: Date.parse(`${day}T00:00:01Z`), data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
{ type: 'user/message', seq: 1, time: Date.parse(`${day}T00:00:02Z`), data: createUserMessage({ content: [{ type: 'text', text: 'restore the selector' }], source: { kind: 'user' } }), surfaceOp: 'append' },
{ type: 'step/start', seq: 2, time: Date.parse(`${day}T00:00:03Z`), data: { turn: 1, step: 1 } },
{ type: 'request/header', seq: 3, time: Date.parse(`${day}T00:00:04Z`), data: { header: { config: { provider: 'deepseek', model: 'deepseek-v4-pro' } }, reason: 'initial' } },
{ type: 'assistant/message', seq: 4, time: Date.parse(`${day}T00:00:05Z`), data: {
turn: 1, step: 1,
message: createMessage({
role: 'assistant',
content: [{ type: 'text', text: 'ready' }],
source: { kind: 'model', provider: 'deepseek', model: 'deepseek-v4-pro' },
}),
}, surfaceOp: 'append' },
{ type: 'step/end', seq: 5, time: Date.parse(`${day}T00:00:06Z`), data: { turn: 1, step: 1 } },
{ type: 'turn/end', seq: 6, time: Date.parse(`${day}T00:00:07Z`), data: { turn: 1, reason: { kind: 'completed' } } },
{ type: 'session/title', seq: 7, time: Date.parse(`${day}T00:00:08Z`), data: { title, messageSeqs: [1], source: { kind: 'fallback' } } },
],
})
const harness = await setupSnapshot({
config: { resumeCommand: 'dsh --resume {session}' },
sessionPersistence: {
list: async () => [earlier],
load: async () => ({
meta: earlier,
events: [
{ type: 'turn/start', seq: 0, time: Date.parse('2024-01-01T00:00:01Z'), data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
{ type: 'user/message', seq: 1, time: Date.parse('2024-01-01T00:00:02Z'), data: { content: [{ type: 'text', text: 'restore the selector' }], source: { kind: 'user' } }, surfaceOp: 'append' },
{ type: 'step/start', seq: 2, time: Date.parse('2024-01-01T00:00:03Z'), data: { turn: 1, step: 1 } },
{ type: 'request/header', seq: 3, time: Date.parse('2024-01-01T00:00:04Z'), data: { header: { config: { provider: 'deepseek', model: 'deepseek-v4-pro' } }, reason: 'initial' } },
{ type: 'assistant/message', seq: 4, time: Date.parse('2024-01-01T00:00:05Z'), data: { turn: 1, step: 1, content: [{ type: 'text', text: 'ready' }], provenance: { provider: 'deepseek', model: 'deepseek-v4-pro' } }, surfaceOp: 'append' },
{ type: 'step/end', seq: 5, time: Date.parse('2024-01-01T00:00:06Z'), data: { turn: 1, step: 1 } },
{ type: 'turn/end', seq: 6, time: Date.parse('2024-01-01T00:00:07Z'), data: { turn: 1, reason: { kind: 'completed' } } },
{ type: 'session/title', seq: 7, time: Date.parse('2024-01-01T00:00:08Z'), data: { title: 'Resume selector design', messageSeqs: [1], source: { kind: 'fallback' } } },
],
}),
list: async () => [earlier, elsewhere],
load: async id => id === elsewhere.id
? log(elsewhere, 'Other workspace work', '2024-02-02')
: log(earlier, 'Resume selector design', '2024-01-01'),
},
}, { columns: 92, rows: 32 })
harness.terminal.send('/resume')
@@ -793,6 +854,12 @@ describe('TUI terminal-state snapshots', () => {
await new Promise(resolve => setTimeout(resolve, 60))
await harness.terminal.flush()
await checkpoint('resume-sessions', harness.terminal, { includeScrollback: true })
// Tab switches to the all-workspaces scope, which adds the other workspace's
// session and labels every row with the directory it belongs to.
harness.terminal.send('\t')
await new Promise(resolve => setTimeout(resolve, 60))
await harness.terminal.flush()
await checkpoint('resume-sessions-all-workspaces', harness.terminal, { includeScrollback: true })
await disposeSnapshot(harness)
dateNow.mockRestore()
})

File diff suppressed because it is too large Load Diff

View File

@@ -8,6 +8,7 @@ const render = (source: string, limit = 4, expanded = false): string[] | undefin
text => text.replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/gu, control =>
`\\x${control.charCodeAt(0).toString(16).padStart(2, '0')}`),
text => `[label]${text}[/label]`,
text => `[body]${text}[/body]`,
count => ` … +${count} lines`,
)
@@ -22,30 +23,38 @@ describe('unknown-tool XML rendering', () => {
</content>
</result>`)).toEqual([
'[label]result[/label]',
' [label]path:[/label] /tmp/a.txt',
' [label]type:[/label] file',
' [label]path:[/label] [body]/tmp/a.txt[/body]',
' [label]type:[/label] [body]file[/body]',
' [label]content[/label]',
' [label]line (number="1"):[/label] hello',
' [label]line (number="2"):[/label] world',
' [label]line (number="1"):[/label] [body]hello[/body]',
' [label]line (number="2"):[/label] [body]world[/body]',
])
})
it('renders root text, CDATA, empty elements, and multiline nested text', () => {
expect(render(' <result>\nfirst\nsecond\n</result> ')).toEqual([
'[label]result[/label]',
' first',
' second',
' [body]first[/body]',
' [body]second[/body]',
])
expect(render('<result>\nfirst\nsecond\n</result>', 1, true)).toEqual([
'[label]result[/label]',
' first',
' second',
' [body]first[/body]',
' [body]second[/body]',
])
expect(render('<result><value><![CDATA[literal <xml>]]></value><empty /></result>')).toEqual([
'[label]result[/label]',
' [label]value:[/label] literal <xml>',
' [label]value:[/label] [body]literal <xml>[/body]',
' [label]empty[/label]',
])
// An interior blank line stays the empty string: styling it would emit an
// escape-only row, which reads as a stray indented blank rather than a gap.
expect(render('<result>\nfirst\n\nsecond\n</result>', 4, true)).toEqual([
'[label]result[/label]',
' [body]first[/body]',
'',
' [body]second[/body]',
])
})
it('previews each top-level child independently and expands all rows', () => {
@@ -53,13 +62,13 @@ describe('unknown-tool XML rendering', () => {
expect(render(xml, 3)).toEqual([
'[label]result[/label]',
' [label]first[/label]',
' a',
' [body]a[/body]',
' … +4 lines',
' f',
' [body]f[/body]',
' [label]second[/label]',
' g',
' [body]g[/body]',
' … +4 lines',
' l',
' [body]l[/body]',
])
expect(render(xml, 3, true)).toHaveLength(15)
})
@@ -68,10 +77,10 @@ describe('unknown-tool XML rendering', () => {
const xml = `<result>${Array.from({ length: 8 }, (_, index) => `<item>${index}</item>`).join('')}</result>`
expect(render(xml, 3)).toEqual([
'[label]result[/label]',
' [label]item:[/label] 0',
' [label]item:[/label] 1',
' [label]item:[/label] [body]0[/body]',
' [label]item:[/label] [body]1[/body]',
' … +5 lines',
' [label]item:[/label] 7',
' [label]item:[/label] [body]7[/body]',
])
expect(render(xml, 3, true)).toHaveLength(9)
})
@@ -79,11 +88,11 @@ describe('unknown-tool XML rendering', () => {
it('escapes control characters expanded from character references', () => {
expect(render('<result attr="a&#155;b">tab&#9;csi&#155;</result>')).toEqual([
'[label]result (attr="a\\\\x9bb")[/label]',
' tab\\x09csi\\x9b',
' [body]tab\\x09csi\\x9b[/body]',
])
expect(render('<result><value><![CDATA[del\u007f]]></value></result>')).toEqual([
'[label]result[/label]',
' [label]value:[/label] del\\x7f',
' [label]value:[/label] [body]del\\x7f[/body]',
])
})

View File

@@ -8,7 +8,7 @@ import { randomUUID } from 'node:crypto'
import { Context, Service } from 'cordis'
import z from 'schemastery'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { CallId } from '@deepseek-ai/dsh-llm'
import { createUserMessage, type CallId } from '@deepseek-ai/dsh-llm'
import { scopeTarget } from '@deepseek-ai/dsh-scope'
import type { Scoped } from '@deepseek-ai/dsh-scope'
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
@@ -60,11 +60,15 @@ declare module '@deepseek-ai/dsh-session' {
* The session's approval policy was switched — log-only, durable,
* replayable, never in the model transcript (the model learns the policy
* from the prompt section and the narrator's notices). The LAST such
* event is the session's override ({@link effectiveApprovalPolicy});
* who asked for it is derivable from position (an event after the log's
* last `request/header` was a runtime switch by the user).
* event is the session's override ({@link effectiveApprovalPolicy}).
* `source: 'delegation'` marks an override seeded into a child; an absent
* source is a runtime switch.
*/
'approval/policy': { policy: ApprovalPolicy }
'approval/policy': {
policy: ApprovalPolicy
/** Marks an override seeded into a child at delegation. */
source?: 'delegation'
}
}
}
@@ -250,11 +254,13 @@ export class ApprovalService extends Service {
const session = agent.session
const events = session.events
let overrideIndex = -1
let overrideSource: 'delegation' | undefined
let headerIndex = -1
for (let index = events.length - 1; index >= 0 && (overrideIndex < 0 || headerIndex < 0); index -= 1) {
const event = events[index] as (typeof events)[number]
if (overrideIndex < 0 && event.type === 'approval/policy') {
overrideIndex = index
overrideSource = event.data.source
} else if (headerIndex < 0 && event.type === 'request/header') {
headerIndex = index
}
@@ -268,11 +274,13 @@ export class ApprovalService extends Service {
// Cold start (nothing ever told) narrates nothing — the section about
// to go out states the truth, and there is no delta to explain.
if (told === undefined || told === current) return
const cause = overrideIndex > headerIndex ? 'changed by the user' : 'changed by the operator/config'
agent.inject({
const cause = overrideSource === 'delegation'
? 'inherited from the delegating session'
: overrideIndex > headerIndex ? 'changed by the user' : 'changed by the operator/config'
agent.inject(createUserMessage({
content: [{ type: 'text', text: `The approval policy changed from "${told}" to "${current}" (${cause}).` }],
source: { kind: 'plugin', plugin: 'user-approval' },
})
}))
})
}
@@ -323,7 +331,16 @@ export class ApprovalService extends Service {
* @returns the policy every ask for this session resolves under right now.
*/
private effectivePolicy(session: Session): ApprovalPolicy {
return effectiveApprovalPolicy(session.events) ?? this.config.policy ?? 'ask'
return this.overrideOf(session) ?? this.config.policy ?? 'ask'
}
/**
* Read the session override without applying the configured default.
* @param session - session whose log supplies the override.
* @returns the last logged policy, or `undefined` without one.
*/
overrideOf(session: Session): ApprovalPolicy | undefined {
return effectiveApprovalPolicy(session.events)
}
/**

View File

@@ -456,7 +456,9 @@ describe('approval policy (the approval/policy fold)', () => {
await ctx.plugin(ApprovalService, { policy: 'never' })
ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
const { agent, session } = sessionAgent('sess-gate-3')
expect(ctx.approval.overrideOf(session)).toBeUndefined()
setApprovalPolicy(session, 'ask')
expect(ctx.approval.overrideOf(session)).toBe('ask')
await expect(ctx.approval.request({ agent, toolName: 'bash' })).resolves.toBe('allowed-once')
setApprovalPolicy(session, 'never')
await expect(ctx.approval.request({ agent, toolName: 'bash' })).resolves.toBe('rejected')
@@ -507,6 +509,18 @@ describe('approval policy (the approval/policy fold)', () => {
expect(injected).toEqual(['The approval policy changed from "never" to "ask" (changed by the operator/config).'])
})
it('attributes a constructor-seeded policy event to delegation', async () => {
const ctx = new Context()
await ctx.plugin(ApprovalService)
const { agent, session, injected } = sessionAgent('sess-narr-inherited')
appendHeader(session, ASK_MARKER)
session.append('approval/policy', { policy: 'never', source: 'delegation' })
await preStep(ctx, agent)
expect(injected).toEqual(['The approval policy changed from "ask" to "never" (inherited from the delegating session).'])
})
it('narrates a config default drift from the logged ask marker', async () => {
const ctx = new Context()
await ctx.plugin(ApprovalService, { policy: 'never' })