diff --git a/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.i18n.yaml index 60f33a0e1e..0379a79e52 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.i18n.yaml @@ -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 -2026-07-19-package-invariant-runtime-contracts.md: 7d1fb1ad5a2e7563bdddffde1f49368b9f0c13f7 -2026-07-19-package-invariant-runtime-contracts.zh.md: 669eb02221aea4b0654497bb81327d725648dabe +2026-07-19-package-invariant-runtime-contracts.md: 40d152b2320ac65f9ea7d8732b1a667236d2780a +2026-07-19-package-invariant-runtime-contracts.zh.md: bd2f440d5dce15b352e7bcea0d1243400d290f11 diff --git a/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.md b/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.md index 7d1fb1ad5a..40d152b232 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.md +++ b/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.md @@ -59,7 +59,7 @@ Session-backed companions validate existing durable events when they load, using `verify-package-invariants` discovers every workspace package and enforces companion source, exact-name registration, named-only Loader shape, `./invariant` exports, publication files, dependencies, TypeScript references, and bundle entries. Its AST rule rejects generated markers, default exports, and unexplained empty installers. A non-empty installer must accept and use the failure reporter, and registration must pass that checked local `install` function. The gate deliberately does not infer semantic quality from method names or helper calls. -Vitest mounts `InvariantService` with `{ enabled: true }` for every package test topology and loads the owning companion. The invariant subpath path mapping resolves source companions instead of stale built output. Focused suites cover every executable companion's valid and invalid observations, and the exhaustive topology runs every source companion through the real Loader namespace normalization. An artifact gate stages each package's exact `npm pack` file inventory, imports its compiled `./invariant` self-reference under plain Node, and repeats that Loader-shape check, so an unpublished shared runtime chunk fails before release. Tests that synthesize event streams must produce a valid surrounding lifecycle unless the test is intentionally asserting a violation. +Vitest mounts `InvariantService` with `{ enabled: true }` for every package test topology and loads the owning companion. The invariant subpath path mapping resolves source companions instead of stale built output. Focused suites cover every executable companion's valid and invalid observations, and the exhaustive topology runs every source companion through the real Loader namespace normalization. After the structural gate validates each publication map, an artifact gate stages its manifest-declared `lib/` files, imports the compiled `./invariant` self-reference under plain Node, and repeats that Loader-shape check, so a companion that imports an undeclared runtime chunk fails before release. Tests that synthesize event streams must produce a valid surrounding lifecycle unless the test is intentionally asserting a violation. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.zh.md b/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.zh.md index 669eb02221..bd2f440d5d 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-19-package-invariant-runtime-contracts.zh.md @@ -59,7 +59,7 @@ Status: implemented `verify-package-invariants` 发现每个 workspace 包,并强制 companion 源文件、完整名称注册、仅含具名 export 的 Loader 形状、`./invariant` export、发布文件、依赖、TypeScript reference 和 bundle entry 完整。其 AST 规则拒绝生成标记、默认导出和没有解释的空安装器。非空安装器必须接收并使用失败报告器,注册时还必须传入该经检查的本地 `install` 函数。门禁不会通过方法名或 helper 调用推断语义质量。 -Vitest 为每个包测试拓扑使用 `{ enabled: true }` 挂载 `InvariantService`,并加载所有者 companion。不变量 subpath 的 path mapping 会解析源 companion,而不是陈旧的构建输出。聚焦 suite 覆盖每个可执行 companion 的有效和无效观测;穷举拓扑通过真实 Loader 命名空间归一化运行每个源 companion。产物门禁会按每个包的精确 `npm pack` 文件清单暂存文件,在 plain Node 下导入该包已编译的 `./invariant` 自引用,并重复执行该 Loader 形状检查;这样,未发布的共享运行时分片会在正式发布前导致门禁失败。合成事件流的测试必须构造有效的外围生命周期,除非测试本身就是在断言违规。 +Vitest 为每个包测试拓扑使用 `{ enabled: true }` 挂载 `InvariantService`,并加载所有者 companion。不变量 subpath 的 path mapping 会解析源 companion,而不是陈旧的构建输出。聚焦 suite 覆盖每个可执行 companion 的有效和无效观测;穷举拓扑通过真实 Loader 命名空间归一化运行每个源 companion。结构门禁验证每个包的发布映射后,产物门禁会暂存其 manifest(元数据清单)声明的 `lib/` 文件,在 plain Node 下导入已编译的 `./invariant` 自引用,并重复执行该 Loader 形状检查;这样,若 companion 导入未声明的运行时分片,门禁就会在发布前失败。合成事件流的测试必须构造有效的外围生命周期,除非测试本身就是在断言违规。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/feature/2026-06-24-workspace-context.md b/.agents/notes/implemented/feature/2026-06-24-workspace-context.md index a3eec63b8f..3bcb0c2bea 100644 --- a/.agents/notes/implemented/feature/2026-06-24-workspace-context.md +++ b/.agents/notes/implemented/feature/2026-06-24-workspace-context.md @@ -14,15 +14,15 @@ The lifecycle has two distinct classes of content. The initial applicable chain The implementation lives in `packages/context/workspace-context` as `@deepseek-ai/dsh-workspace-context`. It is a request-context extension, not a core service or a filesystem backend. `@deepseek-ai/dsh-agent-core` mounts it for both product front doors and forwards its config. The plugin consumes `agent/session-prefix`, `tools/post-execute`, and the optional `ctx.fs` capability. -The plugin does not statically inject `fs`. Providerless product trees therefore boot normally and the plugin no-ops until a filesystem provider exists. All production reads go through that provider. Candidate probes call `lstat` before `resolve`, so a repository-owned final-component symlink is rejected rather than followed outside the workspace. The session-prefix signal and dynamic tool execution signal propagate through resolution, metadata probes, and streaming reads, so cancellation does not wait for an unrelated filesystem scan. Once `lstat` identifies a regular-file winner, a provider exception or disagreement during resolve/stat is classified as unavailable: it is neither interpreted as a deletion nor allowed to fall through to a lower-priority candidate. +The plugin does not statically inject `fs`. Providerless product trees therefore boot normally and the plugin no-ops until a filesystem provider exists. All production reads go through that provider. Candidate probes resolve each path and stat the result, so a final-component symlink is followed to its target: a link to a regular file loads, while a missing path or a non-file target is a confirmed absence. Following repository-owned links across the trust boundary is a deliberate reversal of the original no-follow probe; the [instruction-symlink follow note](2026-07-21-follow-instruction-symlinks.md) owns that decision and its residual risk. The session-prefix signal and dynamic tool execution signal propagate through resolution, metadata probes, and streaming reads, so cancellation does not wait for an unrelated filesystem scan. A resolve or stat exception is classified as unavailable: it skips only that candidate and is never interpreted as the deletion of an already-loaded scope. ### File Names And Precedence -The default per-directory candidate list is `['AGENTS.md', 'CLAUDE.md']`. The list is configurable as `instructionFileCandidates`, and `AGENTS.md` is an ordinary first candidate rather than a hidden priority. In one directory, only the first existing regular-file candidate loads. With defaults, `AGENTS.md` is native and `CLAUDE.md` is a compatibility fallback. +The default per-directory candidate list is `['AGENTS.md', 'CLAUDE.md']`. The list is configurable as `instructionFileCandidates`, and `AGENTS.md` is an ordinary first candidate rather than a hidden priority. In one directory, only the first existing regular-file candidate loads. With defaults, `AGENTS.md` is native and `CLAUDE.md` is a compatibility fallback. A second list, `localInstructionFileCandidates` (default `['AGENTS.local.md', 'CLAUDE.local.md']`), loads an additive local overlay after the base file in the same directory; the [default local overlay](2026-07-21-local-instruction-overlay.md) owns that decision. -Candidate entries are same-directory file names. Empty entries, `.`/`..`, and entries containing `/` or `\` are ignored. Lowercase names, local variants, and other same-directory names can be opted into explicitly; rule directories and import semantics are outside this contract. +Candidate entries are same-directory file names. Empty entries, `.`/`..`, and entries containing `/` or `\` are ignored. Other same-directory names can be opted into explicitly; rule directories and import semantics are outside this contract. -The user-global file is fixed at `$DSH_HOME/AGENTS.md` and is not affected by `instructionFileCandidates`. `$DSH_HOME` defaults to `~/.dsh`, matching the harness-level home role of `~/.codex` or `~/.claude` rather than introducing a plugin-specific home. Tilde expansion and the default live in `dsh-paths` so future harness features share the same convention. +The user-global file is fixed at `$DSH_HOME/AGENTS.md`, is not affected by either candidate list, and has no local overlay. `$DSH_HOME` defaults to `~/.dsh`, matching the harness-level home role of `~/.codex` or `~/.claude` rather than introducing a plugin-specific home. Tilde expansion and the default live in `dsh-paths` so future harness features share the same convention. ### Baseline Prefix @@ -46,7 +46,7 @@ Shell commands are not discovery triggers. Local bash calls start fresh shells, ### Duplicate Suppression And Change Detection -Every dynamic workspace context event stores versioned metadata with `{ action, scope, path, previousPath?, digest? }`, where `digest` is SHA-1 over the loaded content. The model-facing prompt has no HTML comments, hidden markers, or headings that are parsed back into state. +Every dynamic workspace context event stores versioned metadata with `{ action, scope, path, digest? }`, where `digest` is SHA-1 over the loaded content. The model-facing prompt has no HTML comments, hidden markers, or headings that are parsed back into state. At reconciliation time the plugin scans plugin-owned `context/message` events and derives the latest state for each visible scope. A short per-session pending map begins only after the immutable top-level `tools/result` proves an `additionalContexts` entry survived every post-execute listener, then covers the interval before the loop appends that context to the log. Each entry records the open `{ turn, step }`: an equal durable `context/message` at or after its sequence boundary confirms and removes it, while a matching `step/end` arriving first means the loop discarded its context buffer, so the plugin removes both the pending entry and its version-cache fast path. A nested Code Mode result stages its changes under the parent's opaque execution token so repeated sub-dispatches in one run do not duplicate them; the parent result rolls that provisional state back and commits only contexts retained by outer policy. @@ -78,10 +78,10 @@ There is intentionally no watcher. Detection occurs at the next successful struc Workspace guidance is isolated per session and shared by both product front doors and every tool presentation mode. Initial instructions benefit from stable prefix caching, while nested and changed content remains durable and replayable. The generic session/agent context contract carries JSON metadata propagated through prompt-submit and post-tool `additionalContexts` arrays without flattening entries. -Repository text remains untrusted input. Lower-authority user-role framing, explicit precedence language, delimiter escaping, and symlink rejection reduce risk but do not eliminate prompt injection. Permission and sandbox layers treat workspace files as data rather than authority. +Repository text remains untrusted input. Lower-authority user-role framing, explicit precedence language, and delimiter escaping reduce risk but do not eliminate prompt injection. Following a candidate symlink to its target widens that surface to off-tree content, so the permission and sandbox layers that confine `ctx.fs` to trusted roots are the boundary that treats workspace files as data rather than authority (the [instruction-symlink follow note](2026-07-21-follow-instruction-symlinks.md) owns the residual risk). The system is event-driven rather than watch-driven. Edits are not visible at the exact filesystem mutation instant unless that mutation goes through a structured tool; externally changed files are noticed on the next successful structured touch or resume. This keeps the design deterministic and provider-neutral. ## Deferred -Bash-derived path reporting, recursive startup scans, file watchers, lowercase defaults, `.claude/CLAUDE.md`, `.claude/rules/*.md`, import directives, ACP `additionalDirectories`, trust acknowledgements, and model-generated summaries are deferred. Same-directory private variants can be configured today; directory rule systems and imports need their own precedence and trust designs. +Bash-derived path reporting, recursive startup scans, file watchers, lowercase defaults, `.claude/CLAUDE.md`, `.claude/rules/*.md`, import directives, ACP `additionalDirectories`, trust acknowledgements, and model-generated summaries are deferred. Project-directory `.local.` overlays now load by default (the [default local overlay](2026-07-21-local-instruction-overlay.md) owns that decision); a user-global overlay, directory rule systems, and imports still need their own precedence and trust designs. diff --git a/.agents/notes/implemented/feature/2026-07-05-skill-system.md b/.agents/notes/implemented/feature/2026-07-05-skill-system.md index e59013c0a8..eccc58f7c2 100644 --- a/.agents/notes/implemented/feature/2026-07-05-skill-system.md +++ b/.agents/notes/implemented/feature/2026-07-05-skill-system.md @@ -50,4 +50,4 @@ The catalog is deterministic for a fixed root set and runtime registration revis ## Deferred -Forked skill contexts (`context: fork`), direct user/slash invocation (`user-invocable`), parameter declarations and hints (`arguments` and `argument-hint`), and per-skill tool constraints (`allowed-tools` and `disallowed-tools`) are outside the shipped contract. The registry, local provider, and model-facing tool do not parse, advertise, or enforce these fields. +Forked skill contexts (`context: fork`), parameter declarations and hints (`arguments` and `argument-hint`), and per-skill tool constraints (`allowed-tools` and `disallowed-tools`) are outside the shipped contract. The registry, local provider, and model-facing tool do not parse, advertise, or enforce these fields, and the `user-invocable` frontmatter field is likewise unparsed. Direct user invocation itself ships as a consumer-side affordance instead: the TUI front door offers a manual `/skill:` command over the registry's existing `list()` and `get()` methods, without a registry, provider, or tool contract change — see [the TUI skill slash command](2026-07-21-tui-skill-slash-command.md). diff --git a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.i18n.yaml b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.i18n.yaml index 810f8863e5..8d6c7be831 100644 --- a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.i18n.yaml @@ -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 -2026-07-17-dedicated-full-screen-tui-front-door.md: 3e2b1e751001020eccc9193438daff23dd42518a -2026-07-17-dedicated-full-screen-tui-front-door.zh.md: 5f3632f43702e16ca9dec07c0bb8e42bf50499b7 +2026-07-17-dedicated-full-screen-tui-front-door.md: ecfda138593fc2b98ac42929acc586b11e437ee2 +2026-07-17-dedicated-full-screen-tui-front-door.zh.md: 6b8cc63f7657672a6da542e2033d765b54bd4f07 diff --git a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md index 3e2b1e7510..ecfda13859 100644 --- a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md +++ b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md @@ -22,7 +22,7 @@ The selected front door receives the exact generated or resumed `SessionId` used The TUI rebuilds the transcript from the active `session.surface` and reprojects it whenever an event carries a `surfaceOp`, so resumed and compacted history matches the model-visible conversation. It renders Markdown text and reasoning, token totals, the latest `todo/write` plan, and tool cards produced through each tool definition's `presentCall` and `presentResult` methods. Long card bodies retain a configurable head/tail preview with the hidden-line count; one terminal control expands or collapses every card. Pending chunks and tool calls update the same components that completed events settle. -Editor input calls `agent.send()` while idle and `agent.steer()` while a turn is running. Cancellation, reasoning visibility, tool-card expansion, redraw, transcript clearing, and exit are terminal-only controls. The idle footer derives context occupancy from `tokenMeter` and pairs the selected model with its reasoning state; during a run, elapsed activity and the Escape interrupt hint replace that summary. The plugin registers the shared `userInteraction` provider and presents queued questions in a wide bottom-left keyboard panel with batch progress, numbered options, and aligned descriptions; agent behavior and answer logging remain owned by their existing services. +Editor input calls `agent.send()` while idle and `agent.steer()` while a turn is running. Cancellation, reasoning visibility, tool-card expansion, redraw, transcript clearing, and exit are terminal-only controls. The idle footer derives context occupancy from `tokenMeter` and shows the selected model; during a run, elapsed activity and the Escape interrupt hint replace that summary. `/status` remains available in either state and appends a detailed terminal-only snapshot: session identity and timestamps, selected model and reasoning visibility, lifecycle counts folded from the event log, the same deduplicated usage buckets and KV-cache rate as the footer, and context use from `tokenMeter` plus the selected model's advertised capacity. The plugin registers the shared `userInteraction` provider and presents queued questions in a wide bottom-left keyboard panel with batch progress, numbered options, and aligned descriptions; agent behavior and answer logging remain owned by their existing services. The `/model` command presents the advisory `ctx.llm` catalog as a keyboard selector and changes only this TUI session's target; argument forms remain available for direct selection. Agent-scoped prompt-assembly and request waterfalls snapshot one provider/model pair per step, so `{{provider}}` / `{{model}}` interpolation and request routing cannot split when a command arrives during assembly. The latest logged request header restores a used target; a selection that never reaches a request remains process-local. diff --git a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.zh.md b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.zh.md index 5f3632f437..6b8cc63f76 100644 --- a/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.zh.md +++ b/.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.zh.md @@ -22,7 +22,7 @@ DeepSeek Harness 将 [`@deepseek-ai/dsh-tui`](../../../../packages/ui/tui/README TUI 从活跃的 `session.surface` 重建 transcript(文本记录),并在事件携带 `surfaceOp` 时重新投影,因此恢复或压缩后的历史与模型可见会话保持一致。TUI 渲染 Markdown 文本与推理、token 用量、最新 `todo/write` 计划,以及各工具定义通过 `presentCall` 和 `presentResult` 方法生成的工具卡片。较长的工具卡片正文会保留可配置的头尾预览,并显示隐藏行数;一个终端控制可以展开或收起全部卡片。进行中的分片与工具调用会更新同一组组件,随后由完成事件收束状态。 -agent 空闲时,编辑器输入调用 `agent.send()`;轮次运行中则调用 `agent.steer()`。取消、推理显隐、工具卡片展开、重绘、清空 transcript 和退出都只是终端控制。空闲态页脚根据 `tokenMeter` 得出上下文占用率,并将选中模型及其推理状态组合显示;agent 运行期间,该摘要会替换为带已用时长的活动指示和 Escape 中断提示。插件注册共享的 `userInteraction` 提供方,在左下角宽幅键盘操作面板中呈现排队的问题,面板显示批次进度、带编号的选项和对齐的描述;agent 行为和答案日志仍由既有服务负责。 +agent 空闲时,编辑器输入调用 `agent.send()`;轮次运行中则调用 `agent.steer()`。取消、推理显隐、工具卡片展开、重绘、清空 transcript 和退出都只是终端控制。空闲态页脚根据 `tokenMeter` 得出上下文占用率,并显示所选模型;agent 运行期间,该摘要会替换为带已用时长的活动指示和 Escape 中断提示。`/status` 在这两种状态下均可用,并会追加一份仅在终端显示的详细快照,其中包括会话标识与时间戳、所选模型及推理显隐状态、从事件日志归并得出的生命周期计数、与页脚一致的去重用量分项和 KV 缓存命中率,以及 `tokenMeter` 给出的上下文用量和所选模型公布的容量。插件注册共享的 `userInteraction` 提供方,在左下角宽幅键盘操作面板中呈现排队的问题,面板显示批次进度、带编号的选项和对齐的描述;agent 行为和答案日志仍由既有服务负责。 `/model` 命令将建议性的 `ctx.llm` 目录呈现为键盘选择器,并且只更改当前 TUI 会话的目标;带参数的形式仍可直接选择目标。agent 作用域内的 prompt 组装和请求两条 waterfall(瀑布式事件)会为每个 step 快照一次同一个提供方/模型字段组合,因此即使命令在组装期间到达,`{{provider}}` / `{{model}}` 插值与请求路由也不会分裂。系统通过日志中最新的请求头恢复已经使用过的目标;未被请求使用的选择只保留在当前进程中。 diff --git a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.i18n.yaml b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.i18n.yaml new file mode 100644 index 0000000000..a8c9c28d58 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.i18n.yaml @@ -0,0 +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 +2026-07-20-dsh-cli-personal-config.md: e349374a6bc7fc0137bf14836469aef8bae8d49d +2026-07-20-dsh-cli-personal-config.zh.md: 88210dc386a245002de927950dab2852e40218ea diff --git a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.md b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.md new file mode 100644 index 0000000000..e349374a6b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.md @@ -0,0 +1,47 @@ +# Agent Note: The dsh CLI and personal config overlays from the Harness home + +Status: implemented + +English | [中文](2026-07-20-dsh-cli-personal-config.zh.md) + +## Problem + +A developer's own preferences — which provider and model the TUI uses, personal credentials, a private adapter route — had nowhere to live except edits to committed files. Pointing the TUI demo at a personal Anthropic-proxy Opus route meant patching `examples/tui-agent/cordis.yml` and `.env` in the working tree, which risks committing secrets and repeats per checkout. There was also no installable command: running the agent in an arbitrary project directory required invoking the repo's demo script from the repo root. Loader metadata is static, so "conditional composition uses overlays" (AGENTS.md) — but overlays only existed as committed sibling files, not as a machine-level layer. + +## Decision + +Two coupled pieces, aligned with the `apps/` assembly tier proposed by the `dsh web` PR (#443): + +**The `dsh` CLI (`apps/cli`, npm name `@deepseek-ai/dsh`).** `apps/*` joins the workspaces as the product-assembly tier over `packages/*` libraries. The bin's dispatch reserves `web` and `-p`/`--prompt` for PR #443 (they exit with a pointer) so the two branches merge as a near-union; everything else runs the default surface: the interactive TUI, booting the shipped `examples/tui-agent/cordis.yml` (or an explicit config argument) with the invoking directory as the workspace. The committed `bin/dsh` launcher resolves the checkout through its own real path and runs the bin **from source** via the repo's tsx (with `--expose-internals` for the config's HMR entry), so `ln -sf "$(pwd)/bin/dsh" ~/.local/bin/dsh` installs a command that always executes the current working tree. `pnpm run demo:tui` runs the same entry. + +**Personal config (`dsh-app-boot`).** The personal overlay lives in the Harness home — `$DSH_HOME`, else `~/.dsh` — resolved by the shared [`resolveDshHome`](../architecture/2026-07-24-single-harness-home-resolver.md) (`@deepseek-ai/dsh-paths`), the same single root skills and AGENTS.md resolve against. The dsh TUI surface consumes its two optional files; the demo bins boot their committed trees verbatim: + +- `.env` — loaded after the invoking directory's `.env`; `process.loadEnvFile` never overrides, so precedence is ambient > project `.env` > personal `.env`. +- `config.yaml` — a top-level YAML array of `@cordisjs/plugin-include` `PatchOptions`, parsed with the include's own `!!js` dialect (`loadPersonalPatches`) and passed to `boot()`, which forwards it as the root include's `patches`. Patch semantics are exactly the committed overlay semantics (the Code Mode overlay is the template): an id-targeted patch replaces the named entry's whole `config`, `insert` appends entries, an unmatched id warns and is skipped. +- A missing file means no overlay; a present-but-unreadable, unparsable, or non-array file throws at boot (misconfiguration fails loud, never a silent skip). + +The PTY smoke's launcher isolates `$DSH_HOME` to a per-test directory, exactly as it already isolates `DSH_AGENTS_HOME`, so a developer's real personal overlay cannot leak into fixtures; only the dsh CLI reads personal config, so no other test launcher needed changes. + +## Alternatives considered + +**A standalone `bin/dsh` wrapper owning the `dsh` name.** Rejected after reading PR #443: that PR establishes `apps/cli` as the `dsh` CLI with subcommand dispatch (`web`, `-p`) and leaves the default slot unclaimed. Two competing `dsh` entrypoints would collide in `$PATH` and in product identity; claiming the default slot inside the same package shape confines the eventual merge conflict to the small dispatch chain. + +**A pi-style typed settings file (`defaultProvider`/`defaultModel`/`providers`).** Rejected by the user in favor of patch semantics: the personal file is a cordis overlay over the shipped default config, not a second config vocabulary to own and translate. + +**A personal full `cordis.yml` that includes the requested config.** Rejected: the personal file would have to name the leaf config's path, which varies per checkout; patches invert the dependency so the bin keeps choosing the tree and the personal layer only amends it. + +**Deep-merging personal patches into entry configs.** Rejected: it would fork the patch semantics from the committed overlays and the vendored include; whole-config replacement is already the documented contract. + +**Opt-in via env flag instead of presence.** Rejected: personal config that is off by default never gets used; presence plus explicit per-test isolation gives live runs the overlay and tests hermeticity. + +## Consequences + +- `dsh` from any directory (and `pnpm run demo:tui`) boots the personal provider/model with zero repo changes; verified end-to-end against a personal Anthropic proxy with Opus 4.8, including a bash tool round trip. +- Because an id-targeted patch replaces the whole `config`, a personal override restates the base fields it keeps and can drift when the base entry changes shape; the loader's entry-not-found/name-mismatch warnings are the only diagnostics. +- Personal patches resolve ids against the booted file's own tree, so nested-include overlays (Code Mode) are not personalized; live-run parity for those leaves is deferred. +- `dsh-app-boot` depends on `js-yaml` (plus a load-only copy of the include's `!!js` YAML type) and, like `apps/cli`, on `@deepseek-ai/dsh-paths` for `resolveDshHome`. +- When PR #443 lands, `apps/cli/src/bin.ts`'s dispatch chain and `apps/cli/package.json`'s dependency list conflict textually; both resolve as unions (their `web`/`-p` branches plus our default-TUI branch). + +## Testing + +`packages/ui/app-boot/tests/personal-config.spec.ts` pins `!!js` preservation and end-to-end interpolation through a booted tree, insert entries, the default directory resolving from `$DSH_HOME`, the absent/empty no-op paths, and the three fail-loud shapes (unreadable, unparsable, non-array). `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` boots the dsh bin in a PTY three ways: default config with no overlay, a personal `.env` + `config.yaml` chain whose patched welcome renders in the banner, and an invalid personal file failing the boot loudly. The pre-existing smokes and snapshot suites pass on a machine whose real `~/.dsh` overlay would change the booted model — the isolation, not luck. diff --git a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.zh.md b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.zh.md new file mode 100644 index 0000000000..88210dc386 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.zh.md @@ -0,0 +1,47 @@ +# Agent Note: dsh CLI 与来自 Harness home 的个人配置 overlay + +Status: implemented + +[English](2026-07-20-dsh-cli-personal-config.md) | 中文 + +## Problem + +开发者自己的偏好——TUI 使用哪个提供方和模型、个人凭证、私有的适配器路由——除了改动已提交的文件之外无处安放。要把 TUI 示例指向个人的 Anthropic 代理 Opus 路由,只能在工作区里改 `examples/tui-agent/cordis.yml` 和 `.env`,既有提交密钥的风险,又要在每个 checkout 里重复一遍。也没有可安装的命令:想在任意项目目录里运行这个 agent,必须回到仓库根目录调用示例脚本。Loader 元数据是静态的,所以「条件组合使用 overlay」(AGENTS.md)——但 overlay 此前只以已提交的同级文件形式存在,没有机器级的层。 + +## Decision + +两个耦合的部分,与 `dsh web` PR(#443)提出的 `apps/` 装配层对齐: + +**`dsh` CLI(`apps/cli`,npm 名 `@deepseek-ai/dsh`)。** `apps/*` 作为 `packages/*` 库之上的产品装配层加入 workspaces。bin 的分发把 `web` 和 `-p`/`--prompt` 保留给 PR #443(它们以指引退出),使两个分支能以接近并集的方式合并;其余一切都运行默认表面:交互式 TUI,加载随仓库提供的 `examples/tui-agent/cordis.yml`(或显式的配置参数),并以调用目录为工作区。已提交的 `bin/dsh` 启动器通过自身真实路径解析 checkout,用仓库的 tsx **从源码**运行该 bin(带 `--expose-internals`,供配置里的 HMR 配置项使用),因此 `ln -sf "$(pwd)/bin/dsh" ~/.local/bin/dsh` 安装的命令永远执行当前工作树。`pnpm run demo:tui` 运行同一入口。 + +**个人配置(`dsh-app-boot`)。** 个人 overlay 存放在 Harness home——`$DSH_HOME`,否则 `~/.dsh`——由共享的 [`resolveDshHome`](../architecture/2026-07-24-single-harness-home-resolver.md)(`@deepseek-ai/dsh-paths`)解析,与 skills、AGENTS.md 解析所依据的单一根目录相同。dsh 的 TUI 表面消费其中两个可选文件;各示例 bin 仍然逐字节按已提交的配置树启动: + +- `.env`——在调用目录的 `.env` 之后加载;`process.loadEnvFile` 从不覆盖已有值,因此优先级为环境变量 > 项目 `.env` > 个人 `.env`。 +- `config.yaml`——顶层 YAML 数组,元素为 `@cordisjs/plugin-include` 的 `PatchOptions`,用 include 自己的 `!!js` 方言解析(`loadPersonalPatches`)并传给 `boot()`,由它作为根 include 的 `patches` 转发。补丁语义与已提交 overlay 完全一致(Code Mode overlay 是模板):按 id 定位的补丁替换该配置项的整个 `config`,`insert` 追加配置项,未匹配的 id 记录警告并跳过。 +- 文件缺失即无 overlay;文件存在但不可读、不可解析或非数组则在启动时抛出(配置错误响亮失败,绝不静默跳过)。 + +PTY 冒烟测试的启动器把 `$DSH_HOME` 隔离到每个测试自己的目录,与它已有的 `DSH_AGENTS_HOME` 隔离方式完全一致,开发者真实的个人 overlay 不可能泄漏进 fixture;只有 dsh CLI 读取个人配置,因此其他测试启动器无需改动。 + +## Alternatives considered + +**独立的 `bin/dsh` 包装脚本占有 `dsh` 这个名字。** 读过 PR #443 后否决:该 PR 把 `apps/cli` 确立为带子命令分发(`web`、`-p`)的 `dsh` CLI,并且默认位空缺。两个互相竞争的 `dsh` 入口会在 `$PATH` 和产品身份上冲突;在同一包形态内认领默认位,把最终的合并冲突限制在小小的分发链上。 + +**pi 风格的类型化设置文件(`defaultProvider`/`defaultModel`/`providers`)。** 用户否决,选择补丁语义:个人文件是叠加在随仓库提供的默认配置之上的 cordis overlay,而不是需要另行拥有和翻译的第二套配置词汇。 + +**个人完整 `cordis.yml` 去 include 请求的配置。** 否决:个人文件将不得不写死叶子配置的路径,而该路径随 checkout 变化;补丁反转了依赖方向,bin 仍然选择配置树,个人层只做修正。 + +**把个人补丁深合并进配置项配置。** 否决:会使补丁语义与已提交 overlay 和 vendor 的 include 分叉;整个 `config` 替换已是成文契约。 + +**用环境变量开关代替存在性判断。** 否决:默认关闭的个人配置永远不会被用起来;存在即生效加上每个测试的显式隔离,让实际运行获得 overlay、测试获得封闭性。 + +## Consequences + +- 在任意目录运行 `dsh`(以及 `pnpm run demo:tui`)即可零仓库改动地使用个人提供方/模型;已针对个人 Anthropic 代理与 Opus 4.8 端到端验证,包括一次 bash 工具往返。 +- 由于按 id 定位的补丁替换整个 `config`,个人覆盖必须复述它保留的基础字段,并可能随基础配置项形态变化而漂移;loader 的「配置项未找到/名称不匹配」警告是仅有的诊断。 +- 个人补丁只在被启动文件自身的树里解析 id,因此嵌套 include 的 overlay(Code Mode)不会被个性化;这些叶子的实际运行等价性暂缓。 +- `dsh-app-boot` 依赖 `js-yaml`(外加一份只用于加载的 include `!!js` YAML 类型副本),并与 `apps/cli` 一样依赖 `@deepseek-ai/dsh-paths` 以获取 `resolveDshHome`。 +- PR #443 落地时,`apps/cli/src/bin.ts` 的分发链与 `apps/cli/package.json` 的依赖列表会产生文本冲突;两者都按并集解决(他们的 `web`/`-p` 分支加上我们的默认 TUI 分支)。 + +## Testing + +`packages/ui/app-boot/tests/personal-config.spec.ts` 固定 `!!js` 的保留与经真实启动树的端到端插值、insert 配置项、默认目录从 `$DSH_HOME` 解析、缺失/为空的无操作路径,以及三种响亮失败形态(不可读、不可解析、非数组)。`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 在 PTY 里以三种方式启动 dsh bin:无 overlay 的默认配置、个人 `.env` + `config.yaml` 链条(打补丁的欢迎语渲染进横幅)、以及无效个人文件导致的响亮启动失败。既有冒烟与快照套件在一台真实 `~/.dsh` overlay 会改变启动模型的机器上通过——靠隔离,不靠运气。 diff --git a/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.i18n.yaml b/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.i18n.yaml new file mode 100644 index 0000000000..3ed957d231 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.i18n.yaml @@ -0,0 +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 +2026-07-20-tui-startup-slogans.md: a2a22baafddd08145cec0d03b65ee56b2f8114b1 +2026-07-20-tui-startup-slogans.zh.md: 58fa5790f315845f27b810d62658bd79428b519b diff --git a/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.md b/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.md new file mode 100644 index 0000000000..a2a22baafd --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.md @@ -0,0 +1,39 @@ +# Agent Note: Startup slogans replace the configured TUI welcome line + +Status: implemented + +English | [中文](2026-07-20-tui-startup-slogans.zh.md) + +> **Superseded** for the slogan/animation half by the [banner sweep Agent Note](2026-07-21-tui-banner-sweep.md): the slogan bank and typewriter reveal shipped, read as weird in use, and were replaced by a subtitle-free banner with a whole-banner sweep. The removal of the configured demo welcome and the animation-lifecycle groundwork (start after `ui.start()`, clear through `detachListeners`) stand. + +## Problem + +The TUI header subtitle came from a `welcome` config the demo leaf set to "TUI agent ready. Give it a coding task." — instructional filler that told a returning user nothing, restated what the product is on every boot, and had a hardcoded twin (`'ready.'`) as the schema default in two packages. The product wanted a startup moment with some character instead of a static banner caption. + +## Decision + +- `examples/tui-agent/cordis.yml` no longer configures `welcome`; the config key stays for deployments and fixtures that need a fixed, deterministic subtitle (the Code Mode overlay and every snapshot/scripted fixture keep theirs). +- When `welcome` is unset, `dsh-tui` picks one member of an exported `STARTUP_SLOGANS` bank per boot (`pickStartupSlogan`, injectable random source) and reveals it with a typewriter animation: one character per 40 ms frame, a `▌` block cursor trailing until complete. The reveal starts only after `ui.start()` succeeds and its interval is cleared on dispose alongside the other listeners. +- The slogan bank is presentation copy, deliberately not config: deployments that want controlled wording already have `welcome`. Slogans are ASCII-only by contract because the reveal slices per character. +- `dsh-tui-demo` forwards `welcome` only when configured instead of defaulting it, so the app no longer decides the TUI's idle subtitle. +- The keyless PTY boot scenario now waits for the reveal cursor (`▌` — the only source of that glyph in an empty transcript) instead of the removed welcome text. + +The same change restores `packages/ui/tui/src/index.ts` to 100 % per-file coverage, which the color-scheme merge had broken on the integration branch: the editor border-color reassignment inside `applyColorScheme` was dead (the `setStatus` call right after re-derives it) and is removed, and the color-scheme query's `.then`/`.catch` arrows became named, tested handlers (`applyReportedScheme`, `ignoreSchemeQueryFailure` — the latter pinned by a test whose terminal throws on the DSR query write). + +## Alternatives considered + +**A fixed cooler slogan.** Rejected: one string re-read on every boot decays into wallpaper exactly like the line it replaces; a small rotating bank keeps the moment alive at no complexity cost. + +**Making the bank and reveal speed configurable.** Rejected: that is two new knobs for presentation copy; `welcome` is already the escape hatch for deployments with an opinion, and the no-hardcoded-tunables rule targets deployment-varying behavior, not brand copy. + +**Animating in `HeaderComponent` itself.** Rejected: the component would need a TUI handle and its own lifecycle; the chat already owns a render loop, timers, and a disposal path, so the reveal lives beside the other `createTuiChat` effects and `detachListeners` clears it. + +## Consequences + +- Boot output is no longer byte-deterministic when `welcome` is unset (random slogan, timed frames). Every recorded or snapshot surface pins `welcome` explicitly, so no snapshot changed; the PTY smoke anchors on the reveal cursor and the session-id line instead. +- The `welcome` schema default disappeared from both `dsh-tui` and `dsh-tui-demo`; a direct caller passing no welcome now gets a slogan, not `'ready.'`. +- Adding a slogan is a one-line bank edit; tests assert membership, not specific text. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` pins deterministic bank selection with an injected random source, the reveal (a bank member fully rendered, cursor frames observed), the configured-welcome path rendering verbatim with no cursor, and dispose stopping a mid-reveal animation. `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` boots the real tree in a PTY and waits on the reveal cursor. Verified live in tmux (mid-reveal frame `no map below▌` then the full slogan). diff --git a/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.zh.md b/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.zh.md new file mode 100644 index 0000000000..58fa5790f3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-20-tui-startup-slogans.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 启动 slogan 取代配置化的 TUI 欢迎语 + +Status: implemented + +[English](2026-07-20-tui-startup-slogans.md) | 中文 + +> **已被取代**:slogan/动画的那一半由[横幅扫入 Agent Note](2026-07-21-tui-banner-sweep.md)取代:slogan 库和打字机动画上线后实际使用中显得怪异,已替换为无副标题的横幅加整体扫入。移除示例配置中欢迎语的决定与动画生命周期基础设施(`ui.start()` 后启动、经 `detachListeners` 清除)保持不变。 + +## Problem + +TUI 头部副标题来自一个 `welcome` 配置,示例叶子配置把它设为 "TUI agent ready. Give it a coding task."——一句说明书式的填充语,对老用户毫无信息量,每次启动都在复述产品是什么,而且它还有一个硬编码的孪生兄弟(`'ready.'`)作为两个包里的 schema 默认值。产品需要的是一个有性格的启动时刻,而不是一条静态横幅说明。 + +## Decision + +- `examples/tui-agent/cordis.yml` 不再配置 `welcome`;该配置键保留给需要固定、确定性副标题的部署与 fixture(Code Mode overlay 和所有快照/脚本化 fixture 都保留各自的欢迎语)。 +- `welcome` 未设置时,`dsh-tui` 每次启动从导出的 `STARTUP_SLOGANS` 库里挑选一条(`pickStartupSlogan`,随机源可注入),并以打字机动画逐字显示:每帧 40 ms 一个字符,完成前尾随一个 `▌` 块状光标。动画只在 `ui.start()` 成功后启动,其定时器与其他监听器一起在 dispose 时清除。 +- slogan 库是展示文案,刻意不做成配置:想控制措辞的部署已经有 `welcome` 这个出口。按契约 slogan 只含 ASCII,因为逐字显示按字符切片。 +- `dsh-tui-demo` 只在配置了 `welcome` 时才转发它,不再填默认值,应用不再替 TUI 决定空闲副标题。 +- 无 key 的 PTY 启动场景改为等待逐字显示的光标(`▌`——空 transcript 里该字形的唯一来源),不再等待已删除的欢迎文本。 + +同一变更把 `packages/ui/tui/src/index.ts` 恢复到 100% 的单文件覆盖率(颜色方案合并曾在集成分支上破坏它):`applyColorScheme` 里对编辑器边框颜色的重新赋值是死代码(紧随其后的 `setStatus` 调用会重新推导它),已删除;颜色方案查询的 `.then`/`.catch` 箭头函数改为具名、有测试的处理器(`applyReportedScheme`、`ignoreSchemeQueryFailure`——后者由一个让终端在 DSR 查询写入时抛错的测试固定)。 + +## Alternatives considered + +**换一条更酷的固定 slogan。** 否决:一条每次启动都重读的字符串会和它取代的那行一样退化成墙纸;一个小的轮换库以零复杂度代价让这个时刻保持新鲜。 + +**把 slogan 库和显示速度做成配置。** 否决:那是为展示文案新增两个旋钮;对措辞有主张的部署已经有 `welcome` 这个出口,而「插件里不许硬编码可调参数」规则针对的是随部署变化的行为,不是品牌文案。 + +**在 `HeaderComponent` 内部做动画。** 否决:组件将需要持有 TUI 句柄和自己的生命周期;聊天层已经拥有渲染循环、定时器和释放路径,所以逐字显示与 `createTuiChat` 的其他资源放在一起,由 `detachListeners` 清除。 + +## Consequences + +- `welcome` 未设置时启动输出不再字节级确定(随机 slogan、定时帧)。所有录制或快照表面都显式固定 `welcome`,因此没有快照变化;PTY 冒烟测试改为锚定逐字显示光标和会话 id 行。 +- `welcome` 的 schema 默认值从 `dsh-tui` 和 `dsh-tui-demo` 中消失;不传 welcome 的直接调用方现在得到的是 slogan,而不是 `'ready.'`。 +- 新增一条 slogan 只需在库里加一行;测试断言成员归属,不断言具体文本。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 固定以下行为:注入随机源后的确定性选取、逐字显示(库中某条完整渲染、观察到光标帧)、配置了 welcome 时逐字动画不启动且原文渲染、以及 dispose 停止进行中的动画。`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 在 PTY 里启动真实配置树并等待显示光标。已在 tmux 中实机验证(中途帧 `no map below▌`,随后是完整 slogan)。 diff --git a/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.i18n.yaml new file mode 100644 index 0000000000..f1b9829b73 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.i18n.yaml @@ -0,0 +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 +2026-07-21-dsh-system-prompt-source-path.md: b54d01488fd7c0b49e06200c93af2b056c9fd00b +2026-07-21-dsh-system-prompt-source-path.zh.md: 208e3dce072f63c280999e15276dce62ff4e5c43 diff --git a/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.md b/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.md new file mode 100644 index 0000000000..b54d01488f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.md @@ -0,0 +1,37 @@ +# Agent Note: dsh tells the agent where its own source lives + +Status: implemented + +English | [中文](2026-07-21-dsh-system-prompt-source-path.zh.md) + +## Problem + +The `dsh` CLI is the self-referential surface: its `cordis` toolset lets the agent inspect and modify the very harness runtime it runs in. But the agent had no way to learn where that source lives on disk. `dsh` is normally symlinked onto PATH and launched from an arbitrary working directory — the project under work — so neither the cwd nor `argv` reliably points at the harness checkout. Without the path, "read your own source" is guesswork. + +## Decision + +The `dsh` launcher (`apps/cli/src/tui.ts`) computes the harness checkout root from its own module URL — `fileURLToPath(new URL('../../..', import.meta.url))`, three hops up from `apps/cli/{src,lib}` — so it resolves to the real source location however `dsh` is launched (a PATH symlink, an arbitrary cwd). After `boot()` settles the tree, the launcher calls the new `addHarnessSourceSection(ctx, sourceRoot)` helper from `dsh-app-boot`, which registers a global `harness:source` prompt section reading `Your own source code is the checkout at ; you can read it there to learn how dsh works and how to extend it.` The section orders at `-99`, just after the harness identity opener (`-100`) and before the deployment persona (`0`). + +The testable logic lives in `dsh-app-boot`, not in `apps/cli`, because `apps/*` are not coverage-gated and `packages/*` are. Resolving the optional `systemPrompt` service, registering the section, and returning the disposer belong where per-file 100% coverage applies; the launcher keeps only the thin glue — compute the path, call the helper — covered by the CLI's PTY e2e. When the booted tree has no `systemPrompt` service the helper is a no-op returning `undefined`. + +## Scope + +Only the `dsh` CLI adds this. The demo bins (`dsh-tui-demo`, `dsh-acp-demo`) boot their committed trees verbatim and gain no source section: they are not the self-modification surface, and their checkout root is not a fact the model needs. + +## HMR + +The section is registered against the booted `systemPrompt` service's own fiber (through `ctx.get('systemPrompt')`), so a dev HMR reload of the system-prompt plugin drops it until the next boot. Production HMR watches the config, not the built lib, so this is a dev-only wrinkle and acceptable. + +## Alternatives considered + +**Register the section inside the system-prompt service constructor.** It would then appear in every deployment, not just the self-referential CLI, and the source root would have to be threaded through config to reach the constructor. The path is a launcher fact, so the launcher owns injecting it. + +**Keep the whole thing in `apps/cli/src/tui.ts`.** Apps are not coverage-gated, so the registration and absent-service branches would ship untested. Extracting the tested helper into `dsh-app-boot` keeps the gate meaningful; the launcher glue is exercised by the CLI's keyless PTY smoke. + +**Add a cordis.yml config field for the path.** The path is not a deployment choice — it is mechanically the launcher's own location. A config field invites a stale hand-entered path and adds a knob with no legitimate variation. + +**Resolve from `process.cwd()` or `process.argv[1]`.** The cwd is the user's project, and a PATH symlink makes `argv[1]` the symlink path; `import.meta.url` is the only handle on the real source location. + +## Consequences + +The agent's system prompt now names its own checkout, so the `cordis` toolset can read and edit harness source with no discovery step. `dsh-app-boot` gains a type-only dependency on `dsh-system-prompt` (peer + dev, matching the acp package's side-effect type import) for the `ctx.get('systemPrompt')` declaration merge; there is no runtime dependency. The section is model-visible text, pinned verbatim in an app-boot unit test and asserted end to end through the CLI's keyless PTY smoke — which boots `dsh` against the scripted config, runs a turn, and reads the path back out of the persisted `request/header` system prompt. The line sits before per-request content, so it does not perturb the KV cache across turns. diff --git a/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.zh.md b/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.zh.md new file mode 100644 index 0000000000..208e3dce07 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-dsh-system-prompt-source-path.zh.md @@ -0,0 +1,37 @@ +# Agent Note: dsh 告知 agent 其自身源码所在位置 + +Status: implemented + +[English](2026-07-21-dsh-system-prompt-source-path.md) | 中文 + +## Problem + +`dsh` CLI 是自我引用的接口:其 `cordis` 工具包让 agent(智能体)得以查看并修改它自身运行其上的 harness(智能体框架)运行时。但 agent 此前无从得知这份源码在磁盘上的位置。`dsh` 通常以符号链接的形式挂到 PATH 上,并从任意工作目录(正在处理的项目)启动,因此无论是 cwd 还是 `argv` 都无法可靠地指向 harness 检出目录。缺了这个路径,"读取你自己的源码"便只能靠猜。 + +## Decision + +`dsh` 启动器(`apps/cli/src/tui.ts`)从它自身的模块 URL 计算 harness 检出根目录——`fileURLToPath(new URL('../../..', import.meta.url))`,从 `apps/cli/{src,lib}` 向上三级——因此无论 `dsh` 以何种方式启动(PATH 符号链接、任意 cwd),它都能解析到真实的源码位置。在 `boot()` 使插件树就位之后,启动器调用来自 `dsh-app-boot` 的新辅助函数 `addHarnessSourceSection(ctx, sourceRoot)`,它注册一个全局 `harness:source` 提示词段,内容为 `Your own source code is the checkout at ; you can read it there to learn how dsh works and how to extend it.`。该段的 order 为 `-99`,恰在 harness 身份开场(`-100`)之后、部署 persona(`0`)之前。 + +可测试的逻辑放在 `dsh-app-boot` 而非 `apps/cli` 中,因为 `apps/*` 不受覆盖率门禁约束,而 `packages/*` 受约束。解析可选的 `systemPrompt` 服务、注册该段、返回 dispose(资源释放)器,这些都属于按文件 100% 覆盖率生效的地方;启动器只保留那层薄薄的黏合——计算路径、调用辅助函数——由 CLI 的 PTY e2e 覆盖。当就位的插件树没有 `systemPrompt` 服务时,该辅助函数是一个返回 `undefined` 的空操作。 + +## Scope + +只有 `dsh` CLI 会加入这一段。demo bin(`dsh-tui-demo`、`dsh-acp-demo`)原样引导它们已提交的插件树,不会获得 source 段:它们不是自我修改的接口,其检出根目录也不是模型需要知道的事实。 + +## HMR + +该段是针对就位后的 `systemPrompt` 服务自身的 fiber 注册的(通过 `ctx.get('systemPrompt')`),因此对 system-prompt 插件做一次开发态 HMR(热模块替换)重载会丢弃它,直到下一次引导为止。生产环境的 HMR 监视的是配置而非构建产物 lib,所以这只是一个仅限开发态的小瑕疵,可以接受。 + +## Alternatives considered + +**在 system-prompt 服务的构造函数内注册该段。** 那样它会出现在每一个部署中,而不只是自我引用的 CLI,而且源码根目录还得穿过配置才能到达构造函数。这个路径是启动器的事实,所以由启动器负责注入它。 + +**把整件事都留在 `apps/cli/src/tui.ts` 里。** apps 不受覆盖率门禁约束,因此注册逻辑与服务缺失分支会以未受测的形式发布。把受测的辅助函数抽取到 `dsh-app-boot` 让门禁保持有效;启动器的黏合部分由 CLI 的无密钥 PTY 冒烟测试演练。 + +**为该路径新增一个 cordis.yml 配置键。** 这个路径不是一项部署选择——它在机制上就是启动器自身的位置。配置键会招致手工填入的路径变陈旧,并新增一个没有合理变化空间的旋钮。 + +**从 `process.cwd()` 或 `process.argv[1]` 解析。** cwd 是用户的项目,而 PATH 符号链接会使 `argv[1]` 成为符号链接自身的路径;`import.meta.url` 是唯一能抓住真实源码位置的把手。 + +## Consequences + +agent 的系统提示词现在会写明它自己的检出目录,因此 `cordis` 工具包无需一个发现步骤就能读取并编辑 harness 源码。`dsh-app-boot` 为 `ctx.get('systemPrompt')` 的声明合并新增了一个对 `dsh-system-prompt` 的仅类型依赖(peer dependency(对等依赖)+ dev,与 acp 包的副作用型类型 import 模式一致);不存在运行时依赖。该段是模型可见文本,在 app-boot 单元测试中逐字锁定,并通过 CLI 的无密钥 PTY 冒烟测试端到端断言——该测试以脚本化配置引导 `dsh`、运行一个轮次,再从持久化的 `request/header` 系统提示词中把路径读回来。这一行位于按请求变化的内容之前,所以它不会在多个轮次间扰动 KV Cache。 diff --git a/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.i18n.yaml new file mode 100644 index 0000000000..6d66a58813 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.i18n.yaml @@ -0,0 +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 +2026-07-21-follow-instruction-symlinks.md: 49b02c38fb49241f5941dc3431c43f031fb7193e +2026-07-21-follow-instruction-symlinks.zh.md: ba47325dde30cea899b2e038221f841bdfa2f1c6 diff --git a/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.md b/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.md new file mode 100644 index 0000000000..49b02c38fb --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.md @@ -0,0 +1,31 @@ +# Agent Note: Follow symlinked instruction files + +Status: implemented + +English | [中文](2026-07-21-follow-instruction-symlinks.zh.md) + +## Problem + +The [workspace-context plugin](2026-06-24-workspace-context.md) probed each instruction candidate with `ctx.fs.lstat` before resolving, rejecting any final-component symlink so a repository-owned link could not point instruction loading at content outside the workspace. That no-follow invariant blocked a deliberate, supported setup: a user who symlinks `$DSH_HOME/AGENTS.md` — or a project `AGENTS.md` — to a canonical instruction file kept elsewhere, sharing one house-style file across tools and homes, saw the link silently ignored. It also forced content dedup to treat the ubiquitous `CLAUDE.md → AGENTS.md` mirror as a special skipped case rather than an ordinary duplicate. The repository owner asked to follow symlinked instruction files unconditionally across every scope, accepting the residual trust-boundary risk recorded below. + +## Decision + +Instruction discovery no longer inspects the final component with `lstat`. Every candidate — the user-global `$DSH_HOME/AGENTS.md`, each base candidate, and each local-overlay candidate — is resolved and its resolved target is stat-ed, at baseline composition and at each `tools/post-execute` reconciliation alike. A symlink whose target is a regular file loads that target's content; a resolved non-file target (including a link to a directory) is a confirmed absence that removes the scope like a missing file; a `resolve` or `stat` exception is classified as temporarily unavailable and never removes an already-loaded scope. `nodeStatFile` calls `stat` (host path) and `fsStatFile` calls `resolve` then `stat` (provider path); neither calls `lstat`. + +A followed symlink is an ordinary file for every downstream step. It participates in per-directory content dedup ([load-all + dedup note](2026-07-21-instruction-load-all-dedup.md)), so a `CLAUDE.md` that symlinks its sibling `AGENTS.md` now resolves to identical content and collapses like any byte-identical real duplicate instead of being skipped as a special case. + +### Trust boundary and residual risk + +Following repository-owned links crosses the plugin's trust boundary: a cloned, untrusted repository can carry an `AGENTS.md` whose symlink target is any file the process can read, surfacing off-tree content as workspace guidance. That content enters only as a lower-authority user-role prefix framed by the system-reminder pattern; it never overrides system, developer, or direct user instructions, and it is treated as data, not authority. The mitigating boundary is the filesystem layer, not this plugin: confine `ctx.fs` with the `dsh-fs-policy` gate or an OS sandbox ([cross-family fs sandbox](2026-07-14-cross-family-fs-sandbox.md)) when a deployment loads untrusted repositories. This is an explicit, owner-accepted trade-off, not an oversight. + +## Alternatives considered + +**Keep the `lstat` no-follow invariant.** Rejected by the repository owner: it blocks the supported symlink-to-canonical-file setup and forces the symlink-mirror case to be a skipped special case rather than a plain duplicate. The read-authority boundary it approximated belongs in the filesystem policy and sandbox layer, which contains the same risk more precisely. + +**Follow only the user-global `$DSH_HOME` candidate and keep no-follow for project files.** Rejected: the owner asked for uniform behavior across every scope, and a split rule is harder to reason about than one consistently applied policy plus a documented boundary. A project the user chose to open is not meaningfully more trusted than the user's own home. + +**Follow symlinks but reject targets that resolve outside the project root.** Rejected: it reintroduces a partial trust boundary in the wrong layer — path geometry rather than read authority — breaks the legitimate `$DSH_HOME`-to-elsewhere case, and duplicates containment the filesystem policy gate already owns. + +## Consequences + +A symlinked instruction file is now loaded and rendered like its target, enabling shared canonical instruction files across tools and homes, and the `CLAUDE.md → AGENTS.md` mirror deduplicates through content instead of being skipped. The plugin no longer depends on `ctx.fs.lstat` for instruction loading; a resolved non-file is a confirmed absence and only a provider exception is temporarily unavailable. The trust boundary moves out of this plugin into the filesystem policy and sandbox layers, which must confine `ctx.fs` when a deployment loads untrusted repositories. The [workspace-context note](2026-06-24-workspace-context.md) and the package README carry the same follow behavior and residual-risk statement. diff --git a/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.zh.md b/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.zh.md new file mode 100644 index 0000000000..ba47325dde --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-follow-instruction-symlinks.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 跟随符号链接指向的指令文件 + +Status: implemented + +[English](2026-07-21-follow-instruction-symlinks.md) | 中文 + +## 问题 + +[workspace-context 插件](2026-06-24-workspace-context.md)在解析前用 `ctx.fs.lstat` 探测每个指令候选,拒绝任何末段的符号链接,从而使仓库自有的链接无法把指令加载指向工作区之外的内容。这条「不跟随」不变式挡住了一个有意为之、且受支持的配置:用户若把 `$DSH_HOME/AGENTS.md`(或某个项目的 `AGENTS.md`)符号链接到别处保存的一个规范指令文件,以便在多个工具与多个 home 之间共享同一份规范文件,就会看到该链接被悄悄忽略。它还迫使内容去重把无处不在的 `CLAUDE.md → AGENTS.md` 镜像当作一个被跳过的特例来处理,而非一个普通的重复文件。仓库所有者要求在每个 scope 上无条件跟随符号链接指向的指令文件,并接受下文记录的残余信任边界风险。 + +## 决策 + +指令发现不再用 `lstat` 检查末段。每个候选(用户全局的 `$DSH_HOME/AGENTS.md`、每个基础候选,以及每个本地覆盖候选)都会被解析,并对其解析后的目标做 stat,基线组合时与每一轮 `tools/post-execute` 协调时一视同仁。一个目标为常规文件的符号链接会加载该目标的内容;一个解析后的非文件目标(包括指向目录的链接)是被确认的缺失,会像缺失文件一样移除该 scope;一个 `resolve` 或 `stat` 异常被归类为暂时不可用,且从不移除已加载的 scope。`nodeStatFile` 调用 `stat`(宿主路径),`fsStatFile` 先 `resolve` 再 `stat`(提供方路径);两者都不调用 `lstat`。 + +一个被跟随的符号链接对下游每一步都是普通文件。它参与按目录的内容去重([加载全部并去重 note](2026-07-21-instruction-load-all-dedup.md)),因此一个符号链接指向其同级 `AGENTS.md` 的 `CLAUDE.md` 现在会解析到相同内容,并像任何逐字节相同的真实副本一样被合并,而不再作为特例被跳过。 + +### 信任边界与残余风险 + +跟随仓库自有的链接会越过插件的信任边界:一个被克隆的、不受信任的仓库可以携带一个 `AGENTS.md`,其符号链接目标是该进程能读取的任意文件,从而把树外内容作为工作区指导暴露出来。该内容仅作为一条被 system-reminder 模式框定的、较低权限的 user 角色前缀进入;它绝不覆盖 system、developer 或用户的直接指令,并被当作数据而非权限对待。起缓解作用的边界在文件系统层,而非本插件:在部署加载不受信任的仓库时,用 `dsh-fs-policy` 门或一个操作系统沙箱([跨家族 fs 沙箱](2026-07-14-cross-family-fs-sandbox.md))约束 `ctx.fs`。这是一个明确的、由所有者接受的取舍,而非疏漏。 + +## 备选方案 + +**保留 `lstat` 的「不跟随」不变式。** 被仓库所有者否决:它挡住了受支持的「符号链接到规范文件」配置,并迫使符号链接镜像场景成为一个被跳过的特例而非普通重复。它所近似的读取权限边界属于文件系统策略与沙箱层,那里能更精确地遏制同一风险。 + +**只跟随用户全局的 `$DSH_HOME` 候选,项目文件保持不跟随。** 否决:所有者要求在每个 scope 上行为一致,而一条分裂的规则比一条一致应用的策略加一条有文档记录的边界更难推理。用户选择打开的项目并不比用户自己的 home 更值得信任。 + +**跟随符号链接,但拒绝解析到项目根之外的目标。** 否决:这会在错误的层(路径几何而非读取权限)重新引入一条局部的信任边界,破坏合理的「`$DSH_HOME` 指向别处」场景,并重复文件系统策略门已经拥有的遏制。 + +## 影响 + +一个符号链接指向的指令文件现在会像其目标一样被加载和渲染,从而支持在多个工具与多个 home 之间共享规范指令文件,而 `CLAUDE.md → AGENTS.md` 镜像会通过内容去重而非被跳过。指令加载不再依赖 `ctx.fs.lstat`;一个解析后的非文件是被确认的缺失,只有提供方异常才是暂时不可用。信任边界从本插件移出,进入文件系统策略与沙箱层。当部署加载不受信任的仓库时,它们必须约束 `ctx.fs`。[workspace-context note](2026-06-24-workspace-context.md) 与包(package) README 承载相同的跟随行为与残余风险声明。 diff --git a/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.i18n.yaml new file mode 100644 index 0000000000..a9ac0bc6c3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.i18n.yaml @@ -0,0 +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 +2026-07-21-instruction-load-all-dedup.md: 4e895b0b7f14600adeaf8742e68eab088e3d6d24 +2026-07-21-instruction-load-all-dedup.zh.md: e27c2d2ad6e6fd291dc3344aab6ff96806fe405f diff --git a/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.md b/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.md new file mode 100644 index 0000000000..4e895b0b7f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.md @@ -0,0 +1,37 @@ +# Agent Note: Load all instruction candidates with per-directory dedup + +Status: implemented + +English | [中文](2026-07-21-instruction-load-all-dedup.zh.md) + +## Problem + +The [workspace-context plugin](2026-06-24-workspace-context.md) resolved one winning file per candidate list per directory: the first existing name in `instructionFileCandidates` won the base slot, and the [local overlay](2026-07-21-local-instruction-overlay.md) added one more winner. But `AGENTS.md` and `CLAUDE.md` routinely coexist in the same directory. In most repositories one is a symlink to the other, so they carry identical content; in repositories mid-migration they are two distinct real files that have drifted apart. First-wins silently dropped the non-winning committed file, so a directory that legitimately carried two distinct instruction files only ever surfaced one — and which one depended on candidate order, not on content. The request was to read both and deduplicate only when they are effectively the same file. + +## Decision + +Every existing candidate in each list loads — the base list first, then the local list — in configured order. Within one directory, candidates whose content is byte-identical after trimming leading and trailing whitespace collapse to the earliest candidate in that order, and the kept file's original bytes are rendered. Dedup is per-directory rather than global, and symmetric across the base and local lists. Trimming before comparison tolerates a trailing newline or indentation difference between a file and its near-copy while still rendering the survivor verbatim — the "extra safe" comparison the request asked for. + +Symlinks now flow through this uniformly. Instruction discovery resolves each candidate and stats its target instead of rejecting a final-component symlink, so a `CLAUDE.md` that symlinks its sibling `AGENTS.md` resolves to identical content and collapses here like any byte-identical real duplicate. Content dedup therefore renders the common symlink-mirror once through the same path as a real copy. The [follow-symlinks note](2026-07-21-follow-instruction-symlinks.md) owns that reversal and its residual trust-boundary risk. + +## Scope keys become per-candidate + +Each `(directory, candidateName)` pair is now its own logical scope, encoded `directory\u0000candidateName` with a NUL separator that cannot occur in a real path. `candidateScopeKey` / `decodeScopeKey` own the encoding, and `probeScopeInstruction` decodes the candidate name to read exactly that file. This replaces the tier-sentinel scope key the overlay note introduced: a directory no longer has a "base scope" and a "local scope" but one scope per candidate name, so `AGENTS.md` and `CLAUDE.md` in one directory are independent scopes that reconcile separately. + +Because a scope now names one fixed file, the previous "candidate switch within a scope" — an `AGENTS.md` scope that fell through to `CLAUDE.md` and recorded the old name in `previousPath` — can no longer occur. `previousPath` was removed from the change record, the serialized `context/message` metadata, and the render text; a change is now either `set`, a same-file `replace`, or a `remove`. Removing one candidate emits a `remove` for that candidate's own scope, leaving a distinct sibling as an independent scope. + +Dedup is enforced during reconciliation, not only at baseline composition. Each reconciliation pass rebuilds a per-directory set of kept trimmed-content digests in candidate order, so an unchanged file is removed when an earlier candidate converges on its content, and a newly duplicate sibling is dropped or removed. The version cache stores a `trimmedDigest` beside the full content digest so the fast path can re-evaluate duplication without re-reading content. + +## Alternatives considered + +**Keep first-wins per candidate list.** Rejected: it silently drops a directory's second committed instruction file and makes the survivor depend on candidate order rather than on whether the files actually differ, which is exactly the surprise the request set out to remove. + +**Global, cross-directory dedup.** Rejected: identical boilerplate under two different directories is legitimately in scope for each, and the deeper file must still surface for work under the deeper directory. Collapsing across directories would hide instructions the model should see. + +**Compare raw bytes without trimming.** Rejected: an editor that adds a trailing newline, or a copy that reflows indentation, would defeat dedup for files that are the same in substance. Trimming before comparison is the tolerant key the request asked for, and the survivor still renders its original bytes. + +**Follow symlinks so a mirror deduplicates through content.** Rejected for this change to preserve the no-follow invariant, then adopted separately: the [follow-symlinks note](2026-07-21-follow-instruction-symlinks.md) reverses that invariant, after which a symlinked mirror is resolved and deduplicated through content exactly like a real duplicate. + +## Consequences + +A directory with two distinct real instruction files now surfaces both; a directory whose second file merely mirrors the first still renders once, and the ubiquitous symlink case is unchanged. The visible behavior difference is confined to transition repositories that carry two distinct real files. The scope-key shape changed from a tier sentinel to a per-candidate key and `previousPath` disappeared from the durable change metadata; `dsh-session` keeps no compatibility promise for older sessions, so both are free changes. The version cache row grew a `trimmedDigest` field, and reconciliation now compares trimmed content per directory, so an unchanged file can be removed by a sibling's convergence — a transition the [state model](2026-06-24-workspace-context.md) previously could not produce. diff --git a/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.zh.md b/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.zh.md new file mode 100644 index 0000000000..e27c2d2ad6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-instruction-load-all-dedup.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 加载全部指令候选并按目录去重 + +Status: implemented + +[English](2026-07-21-instruction-load-all-dedup.md) | 中文 + +## 问题 + +[workspace-context 插件](2026-06-24-workspace-context.md)在每个目录中为每个候选列表只解析出一个胜出文件:`instructionFileCandidates` 中第一个存在的名字赢得基础槽位,[本地覆盖层](2026-07-21-local-instruction-overlay.md)再追加一个胜出者。但 `AGENTS.md` 与 `CLAUDE.md` 经常共处同一目录。在多数仓库里其中一个是另一个的符号链接,因此内容完全相同;在迁移中的仓库里它们则是两个已经产生分歧的、彼此独立的真实文件。先到先得会悄悄丢弃未胜出的已提交文件,于是一个合理地携带两个不同指令文件的目录最终只暴露其中一个——而暴露哪一个取决于候选顺序,而非内容。需求是把两者都读取,仅在它们实质上是同一文件时才去重。 + +## 决策 + +每个列表中每个存在的候选都会被加载——先基础列表,再本地列表——按配置顺序进行。在同一目录内,内容在去除首尾空白后逐字节相同的候选会合并到该顺序中最靠前的候选,并渲染被保留文件的原始字节。去重是按目录进行的,而非全局,并且在基础列表与本地列表之间对称。比较前先做去空白处理,可以容忍某文件与其近似副本之间的末尾换行或缩进差异,同时仍逐字节渲染保留下来的文件——这正是需求所要求的「格外稳妥」的比较。 + +符号链接现在会统一经此流转。指令发现会解析每个候选并对其目标做 stat,而非拒绝末段的符号链接,因此一个符号链接指向其同级 `AGENTS.md` 的 `CLAUDE.md` 会解析到相同内容,并在此像任何逐字节相同的真实副本一样被合并。因此内容去重会通过与真实副本相同的路径把常见的符号链接镜像只渲染一次。[跟随符号链接 note](2026-07-21-follow-instruction-symlinks.md) 拥有该反转决策及其残余的信任边界风险。 + +## scope 键改为按候选划分 + +现在每个 `(directory, candidateName)` 对都是各自独立的逻辑 scope,编码为 `directory\u0000candidateName`,其中 NUL 分隔符在真实路径中不可能出现。`candidateScopeKey` / `decodeScopeKey` 负责这套编码,`probeScopeInstruction` 则解码候选名以精确读取该文件。这取代了覆盖层 note 引入的层级哨兵 scope 键:一个目录不再有「基础 scope」和「本地 scope」,而是每个候选名一个 scope,因此同一目录中的 `AGENTS.md` 与 `CLAUDE.md` 是各自独立协调的 scope。 + +由于一个 scope 现在只对应一个固定文件,此前的「同一 scope 内的候选切换」——即一个 `AGENTS.md` scope 回退到 `CLAUDE.md` 并把旧名字记录在 `previousPath` 中——不再可能发生。`previousPath` 已从变更记录、序列化的 `context/message` 元数据以及渲染文本中移除;一次变更现在要么是 `set`、要么是同一文件的 `replace`、要么是 `remove`。移除某个候选会为该候选自己的 scope 发出一个 `remove`,而把不同的同级文件留作独立的 scope。 + +去重在协调过程中强制执行,而不仅仅在基线组合时。每一轮协调都会按候选顺序重建一个按目录的「已保留去空白摘要」集合,因此当更靠前的候选收敛到某文件的内容时,一个未变更的文件也会被移除,而新出现的重复同级文件会被丢弃或移除。版本缓存在完整内容摘要之外还存储一个 `trimmedDigest`,使快速路径无需重新读取内容即可重新判定是否重复。 + +## 备选方案 + +**每个候选列表保持先到先得。** 否决:这会悄悄丢弃一个目录的第二个已提交指令文件,并使胜出者取决于候选顺序、而非文件是否真的不同,而这恰恰是需求要消除的意外。 + +**全局的、跨目录的去重。** 否决:两个不同目录下相同的样板内容对各自而言都合理地在作用域内,而更深层的文件对于该更深目录下的工作仍必须暴露。跨目录合并会隐藏模型本应看到的指令。 + +**不做去空白、直接比较原始字节。** 否决:一个添加末尾换行的编辑器,或一个重排缩进的副本,都会让实质相同的文件无法去重。比较前去空白正是需求所要求的宽容键,而保留下来的文件仍渲染其原始字节。 + +**跟随符号链接,从而让镜像通过内容去重。** 为本次改动否决以保留「不跟随」不变式,随后另行采纳:[跟随符号链接 note](2026-07-21-follow-instruction-symlinks.md) 反转了该不变式,此后符号链接镜像会被解析,并像真实副本一样通过内容去重。 + +## 影响 + +一个携带两个不同真实指令文件的目录现在会把两者都暴露;一个第二个文件仅仅是镜像的目录仍只渲染一次,而无处不在的符号链接场景保持不变。可见的行为差异被限定在携带两个不同真实文件的迁移期仓库中。scope 键的形态从层级哨兵改为按候选划分,`previousPath` 也从持久的变更元数据中消失;`dsh-session` 对旧会话不作兼容承诺,因此两者都是无成本的改动。版本缓存行新增了一个 `trimmedDigest` 字段,协调过程现在按目录比较去空白后的内容,因此一个未变更的文件可以被同级文件的收敛所移除——这是[状态模型](2026-06-24-workspace-context.md)此前无法产生的转换。 diff --git a/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.i18n.yaml new file mode 100644 index 0000000000..42b09bc4f6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.i18n.yaml @@ -0,0 +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 +2026-07-21-local-instruction-overlay.md: 3c7b2141b0515b5e667be4add6ad765e26c88cd8 +2026-07-21-local-instruction-overlay.zh.md: 0fd45cfcdaf6db1ea6cb0746c8d8cfb3e86c76d7 diff --git a/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.md b/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.md new file mode 100644 index 0000000000..3c7b2141b0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.md @@ -0,0 +1,37 @@ +# Agent Note: Default local instruction overlay + +Status: implemented + +English | [中文](2026-07-21-local-instruction-overlay.zh.md) + +## Problem + +Personal, git-ignored guidance (`AGENTS.local.md` / `CLAUDE.local.md`) is a Claude Code convention for per-developer overrides that are deliberately not committed. The [workspace-context plugin](2026-06-24-workspace-context.md) loaded only one candidate per directory, so a `.local.` name could only be reached by adding it to `instructionFileCandidates`, where — because a directory has one winner — it would *shadow* the committed base file instead of supplementing it. That inverts the additive "base plus personal overlay" model the names evoke, and it was off by default. + +## Decision + +The plugin loads a second, independent candidate list per project directory. `localInstructionFileCandidates` defaults to `['AGENTS.local.md', 'CLAUDE.local.md']` and is resolved with the same same-directory validation as `instructionFileCandidates`. In every project directory from the root to the session cwd, the plugin loads the base candidates and then, additively, the local candidates; the local files are ordered after the base files so their guidance takes precedence within the byte budget. Both lists load in full under [per-directory content dedup](2026-07-21-instruction-load-all-dedup.md). An empty `localInstructionFileCandidates` disables the overlay. + +The default lives in the plugin `Config` schema rather than a product `cordis.yml`, so every embedder (TUI, ACP, headless) reads `.local.` files consistently and a deployment overrides or disables the behavior in one place. This is symmetric with the plugin-owned `instructionFileCandidates` default. + +The fixed user-global `$DSH_HOME/AGENTS.md` has no local overlay and stays base-only. + +## Independent scopes per candidate + +The base and local candidates in one directory must stay independent across baseline freezing, the pending window, the version cache, and reconciliation, so a change to one never suppresses the other. Each `(directory, candidateName)` pair is its own scope key — see [per-candidate scope keys](2026-07-21-instruction-load-all-dedup.md), which replaced the earlier base/local tier sentinel. Discovery iterates the base list and then the local list in each project directory, `reconcileInstructionContext` enumerates every configured candidate per directory, and `probeScopeInstruction` decodes the candidate name to read exactly that file. The model-facing prompt derives its human directory label from the file display path, so the scope key never reaches the model. + +## Alternatives considered + +**Higher-priority first-wins (`.local.` loaded instead of the base file).** Rejected: a personal overlay that replaces the committed file drops shared project guidance whenever the overlay exists, which is the opposite of the additive Claude Code model. + +**Keep it opt-in through `instructionFileCandidates`.** Rejected: one directory has a single winner, so a `.local.` name added to that list shadows the base file rather than supplementing it. The packages guidance to keep opt-ins out of shipped defaults is outweighed here by strong prior art and the user-facing expectation that `.local.` files are always read. + +**Default at the product `cordis.yml` level instead of the plugin schema.** Rejected: it would enable `.local.` only for whichever front door remembered to opt in, splitting behavior across TUI/ACP/headless and duplicating a value that belongs beside the existing candidate default. + +**Reuse the bare directory as the scope key for base and local files.** Rejected: base and local files in one directory would collide in every scope-keyed map, so a change to one would suppress or overwrite the other. A distinct scope key per candidate keeps them independent without widening the persisted metadata shape. + +**Extend the overlay to the user-global scope.** Deferred: `$DSH_HOME` is a single fixed `AGENTS.md` with no committed base to supplement, so it stays base-only until a concrete need appears. + +## Consequences + +`.local.` guidance is read by default across all products with no per-deployment configuration, matching neighboring tools. Each project directory can contribute a durable scope per existing candidate rather than one, so dynamic discovery, edits, and removals reconcile the base and local files independently. The scope key is now [per-candidate](2026-07-21-instruction-load-all-dedup.md); `dsh-session` keeps no compatibility promise for older sessions, so this is a free change. The user-global scope remains base-only, recorded as a Known Limitation in the package README. diff --git a/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.zh.md b/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.zh.md new file mode 100644 index 0000000000..0fd45cfcda --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-local-instruction-overlay.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 默认的本地指令覆盖层 + +Status: implemented + +[English](2026-07-21-local-instruction-overlay.md) | 中文 + +## 问题 + +个人的、被 git 忽略的指导文件(`AGENTS.local.md` / `CLAUDE.local.md`)是 Claude Code 的一项约定,用于存放刻意不提交、每位开发者各自的覆盖内容。[workspace-context 插件](2026-06-24-workspace-context.md)每个目录只加载一个候选,因此只有把某个 `.local.` 名字加进 `instructionFileCandidates` 才能读到它;而由于一个目录只有一个胜出者,这样做只会让它*遮蔽*已提交的基础文件,而不是补充它。这与这些名字所暗示的「基础文件加个人覆盖层」的叠加模型正好相反,而且它默认是关闭的。 + +## 决策 + +插件为每个项目目录额外加载第二个独立的候选列表。`localInstructionFileCandidates` 默认为 `['AGENTS.local.md', 'CLAUDE.local.md']`,并与 `instructionFileCandidates` 采用相同的同目录校验来解析。在从项目根到会话 cwd 的每个项目目录中,插件先加载基础候选,然后叠加加载本地候选;本地文件排在基础文件之后,因此在字节预算之内其内容优先级更高。两个列表都会在[按目录内容去重](2026-07-21-instruction-load-all-dedup.md)之下完整加载。将 `localInstructionFileCandidates` 置空即可关闭该覆盖层。 + +该默认值定义在插件的 `Config` schema 中,而非某个产品的 `cordis.yml` 里,因此每个嵌入方(TUI、ACP、headless)读取 `.local.` 文件的行为一致,部署方也可以在一处覆盖或关闭该行为。这与插件自身持有的 `instructionFileCandidates` 默认值保持对称。 + +固定的用户全局文件 `$DSH_HOME/AGENTS.md` 没有本地覆盖层,始终只有基础文件。 + +## 每个候选各自独立的 scope + +同一目录下的基础候选与本地候选,在基线冻结、待定窗口、版本缓存和协调过程中都必须彼此独立,因此对其中一个的改动绝不能抑制另一个。现在每个 `(directory, candidateName)` 对都是各自独立的 scope 键——参见[按候选划分的 scope 键](2026-07-21-instruction-load-all-dedup.md),它取代了此前基础/本地的层级哨兵。发现过程在每个项目目录中先遍历基础列表、再遍历本地列表,`reconcileInstructionContext` 为每个目录枚举每个配置的候选,`probeScopeInstruction` 则解码候选名以精确读取该文件。面向模型的提示词从文件的展示路径推导出供人阅读的目录标签,因此 scope 键永远不会到达模型。 + +## 备选方案 + +**更高优先级的先到先得(加载 `.local.` 而非基础文件)。** 否决:一个会替换已提交文件的个人覆盖层,会在覆盖层存在时丢弃共享的项目指导,这与 Claude Code 的叠加模型正好相反。 + +**通过 `instructionFileCandidates` 保持按需开启。** 否决:一个目录只有一个胜出者,因此加进该列表的 `.local.` 名字会遮蔽基础文件,而非补充它。packages 指引要求把按需开启项排除在出厂默认之外,但此处强有力的现有实践、以及用户对 `.local.` 文件总会被读取的预期,压过了这一考量。 + +**在产品 `cordis.yml` 层面设默认,而非在插件 schema 中。** 否决:这样只会为记得开启的那个前门启用 `.local.`,从而在 TUI/ACP/headless 之间割裂行为,并重复一个本应与既有候选默认值放在一起的取值。 + +**两个层级复用原始目录作为 scope 键。** 否决:同一目录下的基础文件与本地文件会在每个以 scope 为键的映射中冲突,于是对其中一个的改动会抑制或覆盖另一个。为每个候选设置各自独立的 scope 键让两者保持独立,且无需扩展持久化的元数据结构。 + +**将覆盖层扩展到用户全局 scope。** 暂缓:`$DSH_HOME` 是单个固定的 `AGENTS.md`,没有可供补充的已提交基础文件,因此在出现具体需求前始终只有基础文件。 + +## 影响 + +`.local.` 指导在所有产品中默认被读取,无需按部署单独配置,与邻近工具保持一致。每个项目目录可以为每个存在的候选贡献一个持久 scope 而非仅一个,因此动态发现、编辑和移除会分别独立地协调基础文件与本地文件。scope 键现在[按候选划分](2026-07-21-instruction-load-all-dedup.md);`dsh-session` 对旧会话不作兼容承诺,因此这是一次无成本的改动。用户全局 scope 仍然只有基础文件,这一点作为 Known Limitation 记录在包 README 中。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.i18n.yaml new file mode 100644 index 0000000000..737a9da6ca --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-auto-pane-title.md: 069fd33a8874d9ad3d4472dd13f5130b2df65f08 +2026-07-21-tui-auto-pane-title.zh.md: 580f36b2563e21231a22cab3f0c1689c6f3e8d9d diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.md b/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.md new file mode 100644 index 0000000000..069fd33a88 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.md @@ -0,0 +1,41 @@ +# Agent Note: Auto-titled terminal from the first message + +Status: implemented + +English | [中文](2026-07-21-tui-auto-pane-title.zh.md) + +> **Superseded** by the [session-title consolidation Agent Note](../simplification/2026-07-22-tui-titles-from-session-title-service.md): the TUI-local `autoTitle` generation is removed; titles come from the log-backed session-title service, and the terminal rename consumes `session/title` events. + +> **Superseded** for the default and the resume behavior by the [auto-title default-on Agent Note](2026-07-21-tui-auto-title-default-on.md): `autoTitle` now defaults on, and a resumed session re-derives its title from the stored first message instead of keeping the static one. The OSC 0 path, the one-shot latch, the model-summary shape, the fire-and-forget call, and every failure fallback below stand. + +## Problem + +The TUI's terminal title is a single static string (`title`, default `DeepSeek Harness`) shared by every session. A user who runs one agent per tmux pane or terminal tab sees the same label on all of them, so panes are indistinguishable at a glance and the tab bar carries no signal about what each session is doing. + +## Decision + +- `TuiConfig` gains an `autoTitle` boolean (default `false`). When it is on, the TUI issues one background model call after the first user message of a fresh session and replaces the terminal title with a short, model-generated label; the static `title` is the pre-title and the fallback. +- The label is a model summary, not a truncation of the prompt. The request carries a fixed task instruction (summarize the request as a short title of two to five lowercase words, no punctuation) plus the user's first message and no tools; the TUI takes the first non-empty line of the reply and caps it at 40 characters (39 plus an ellipsis). +- The title is set through `runtime.terminal.setTitle`, the same OSC 0 path the static `title` already uses. No new terminal-control surface is introduced, and pi-tui keeps ownership of terminal writes. +- The call is fire-and-forget and one-shot per session. A `titleSettled` latch guards it: with `autoTitle` off it is pre-settled and never runs; on a resumed session whose first `user/message` is already logged it is pre-settled so the static title stands; a whitespace-only first message is skipped without consuming the slot. Any failure, an empty reply, a missing `llm` service, or a missing agent provider/model leaves the static title untouched. A dedicated `AbortController` cancels an in-flight request on shutdown. +- The title call reaches `ctx.llm.stream` directly rather than through `agent.send`, so it never appends to the session or transcript and cannot perturb the agent loop. +- The feature defaults off and is enabled only in the interactive product config (`examples/tui-agent/cordis.yml`) and the scripted PTY fixture. Enabling it in the shared `dsh-tui-demo` schema default would fire an extra model call in keyless replay and boot scenarios that send no user message. + +## Alternatives considered + +**Truncate the first user message instead of a model title.** Rejected: the user chose a short model-made label; a truncated raw prompt is noisy, often begins with boilerplate, and rarely reads as a title. + +**Rename the window (OSC 2) or the tmux window.** Rejected: OSC 0 sets only `pane_title`, so it labels the pane without renaming or leaking into the user's window title; the user confirmed OSC is the right lever. + +**Default the feature on.** Rejected: enabling it in the shared demo schema perturbs keyless replay and boot snapshots and spends a model call on every fresh session; opt-in per deployment keeps the default surface inert. + +**Fold this into the log-backed session-title work (PR #451).** Rejected: that change is session metadata persisted to the log; this is a terminal label with no persistence. Keeping them independent leaves each self-contained and avoids a shared dependency. + +**Block the first turn until the title resolves.** Rejected: awaiting the title before sending the user's message adds latency to the actual request; fire-and-forget makes the rename invisible to the turn. + +## Consequences + +- When enabled, a fresh session spends one extra, tool-less model call with a single short user message and a few output tokens; off by default, it costs nothing. +- Because the title call stamps `sessionId`, it shares the session's `llm-replay` cursor: enabling `autoTitle` in a replay-backed snapshot scenario would consume a recorded script entry. This is why the default is off and the scripted PTY fixture answers the call with a tool-branching adapter rather than replay. +- `packages/ui/tui/tests/tui.spec.ts` pins the behavior with a mock `llm` adapter: a generated title replaces the static one, over-long output is truncated with an ellipsis, a whitespace-only first message keeps the one-shot slot, empty or failing replies leave the title, a resumed session never fires, and the feature-off / no-service / missing-provider / missing-model paths keep the static title. A shutdown test asserts the in-flight request is aborted. +- `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` proves the real Loader-booted path: the scripted adapter answers the tool-less title call with a fixed string, and the conversation scenario asserts the OSC 0 sequence reaches the PTY. Boot scenarios send no user message, so they never fire the call. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.zh.md new file mode 100644 index 0000000000..580f36b256 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-auto-pane-title.zh.md @@ -0,0 +1,41 @@ +# Agent Note: 从首条消息自动命名终端 + +Status: implemented + +[English](2026-07-21-tui-auto-pane-title.md) | 中文 + +> **已被取代**:见[标题归一 Agent Note](../simplification/2026-07-22-tui-titles-from-session-title-service.md)。TUI 本地的 `autoTitle` 生成已移除;标题来自日志承载的 session-title 服务,终端重命名消费 `session/title` 事件。 + +> **已被取代**(就默认值与恢复行为而言),见[自动标题默认开启 Agent Note](2026-07-21-tui-auto-title-default-on.md):`autoTitle` 现默认开启,恢复会话会从已存储的首条消息重新推导标题,而非保留静态标题。下文的 OSC 0 路径、一次性门闩、模型概括形态、发出后不等待其返回的调用,以及每一条失败兜底,均仍然成立。 + +## Problem + +TUI 的终端标题是一个所有会话共用的静态字符串(`title`,默认 `DeepSeek Harness`)。在 tmux 每个窗格或每个终端标签页各跑一个 agent(智能体)的用户看来,它们的标签全都一样,因此窗格一眼看去无从区分,标签栏也不携带任何关于各会话正在做什么的信号。 + +## Decision + +- `TuiConfig` 新增布尔字段 `autoTitle`(默认 `false`)。开启后,TUI 会在全新会话的首条用户消息之后发起一次后台模型调用,并用一个简短的、模型生成的标签替换终端标题;静态 `title` 是替换前的初值,也是兜底。 +- 该标签是模型概括,而非对提示词的截断。请求携带一段固定的任务指令(将该请求概括为两到五个小写单词、不含标点的简短标题)加上用户的首条消息,且不带工具;TUI 取回复的首个非空行并截断到 40 个字符(39 个字符加一个省略号)。 +- 标题通过 `runtime.terminal.setTitle` 设置——静态 `title` 已经在用的同一条 OSC 0 路径。不引入任何新的终端控制面,终端写入仍归 pi-tui 所有。 +- 该调用发出后不等待其返回,且每会话仅一次。一个 `titleSettled` 门闩守护它:`autoTitle` 关闭时它预先置为已结算、从不运行;在首条 `user/message` 已入日志的恢复会话中它预先结算,因此静态标题得以保留;仅含空白的首条消息被跳过且不消耗名额。任何失败、空回复、缺少 `llm` 服务、或缺少 agent 的 `provider` 或 `model`,都会让静态标题保持不动。一个专用的 `AbortController` 在关闭时取消尚在进行的请求。 +- 标题调用直接抵达 `ctx.llm.stream`,而非经由 `agent.send`,因此它从不追加进会话或 transcript(文本记录),也无法扰动 agent loop(智能体循环)。 +- 该功能默认关闭,仅在交互式产品配置(`examples/tui-agent/cordis.yml`)与脚本化 PTY fixture(测试前置数据)中开启。若在共享的 `dsh-tui-demo` schema 默认值里开启,会在不发送任何用户消息的无密钥回放与启动场景中多发一次模型调用。 + +## Alternatives considered + +**截断首条用户消息,而非用模型生成标题。** 否决:用户选择的是简短的、模型制作的标签;截断后的原始提示词嘈杂、常以样板文字开头,且很少读起来像标题。 + +**重命名窗口(OSC 2)或 tmux 窗口。** 否决:OSC 0 只设置 `pane_title`,因此它标记窗格而不重命名、也不泄漏进用户的窗口标题;用户确认 OSC 是正确的手段。 + +**让该功能默认开启。** 否决:在共享的 demo schema 里开启会扰动无密钥回放与启动快照,并在每个全新会话上花掉一次模型调用;按部署选择性开启可让默认面保持惰性。 + +**并入日志支撑的会话标题工作(PR #451)。** 否决:那项改动是持久化到日志的会话元数据;本项是不做持久化的终端标签。让二者相互独立可使各自自成一体,并避免共享依赖。 + +**阻塞首轮直到标题就绪。** 否决:在发送用户消息前先等待标题,会给实际请求增加延迟;发出后不等待其返回可让重命名对该轮次不可见。 + +## Consequences + +- 开启时,全新会话会多花一次无工具的模型调用,只带单条简短的用户消息和少量输出 token;默认关闭时它不产生任何开销。 +- 由于标题调用会打上 `sessionId`,它与会话的 `llm-replay` 游标共享:在以回放支撑的快照场景中开启 `autoTitle` 会消耗一条录制脚本条目。这正是它默认关闭、且脚本化 PTY fixture 用按工具分支的适配器而非回放来回答该调用的原因。 +- `packages/ui/tui/tests/tui.spec.ts` 用一个 mock `llm` 适配器固定该行为:生成的标题替换静态标题、过长输出以省略号截断、仅含空白的首条消息保留一次性名额、空回复或失败回复保留标题、恢复的会话从不触发,以及功能关闭 / 无服务 / 缺提供方 / 缺模型各路径都保留静态标题。一项关闭测试断言尚在进行的请求被中止。 +- `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 证明真实的经 Loader 启动的路径:脚本化适配器以固定字符串回答无工具的标题调用,对话场景断言 OSC 0 序列抵达 PTY。启动场景不发送用户消息,因此它们从不触发该调用。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.i18n.yaml new file mode 100644 index 0000000000..830ca3e2e0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-auto-title-default-on.md: 35809e1ef6bade3e09c34b17608eff5f8fb5bd22 +2026-07-21-tui-auto-title-default-on.zh.md: aa20cfde1359605f2ac5a8f0427f4518c611ecd1 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.md b/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.md new file mode 100644 index 0000000000..35809e1ef6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.md @@ -0,0 +1,32 @@ +# Agent Note: Auto-title on by default, re-derived on resume + +Status: implemented + +English | [中文](2026-07-21-tui-auto-title-default-on.zh.md) + +> **Superseded** by the [session-title consolidation Agent Note](../simplification/2026-07-22-tui-titles-from-session-title-service.md): the TUI-local `autoTitle` generation is removed; titles come from the log-backed session-title service, and the terminal rename consumes `session/title` events. + +## Problem + +The [auto-title Agent Note](2026-07-21-tui-auto-pane-title.md) shipped `autoTitle` off by default and, on a resumed session, kept the static title because the first `user/message` was already logged. In use both choices defeated the feature's purpose. A per-session descriptive pane title is what makes one tmux pane or terminal tab distinguishable from the next; leaving it off by default means the product ships an inert feature that almost no user turns on, and skipping re-derivation on resume means a resumed session — exactly the long-lived session most worth labelling — falls back to the shared static string. The user asked for a descriptive per-session name to be the normal experience. + +## Decision + +- `autoTitle` defaults **on** (`z.boolean().default(true)`, mirrored by `resolveTuiConfig`'s `?? true`). A deployment with an `llm` service and an agent provider/model gets a model-made pane title on every session without opting in; one without them keeps the static title, so default-on is inert where the call cannot run. +- A **resumed** session re-derives the title on mount from its already-logged first `user/message`: `createTuiChat` scans `agent.session.events` for the first such event and feeds its text to the same one-shot `generateTitle`. The title is never persisted (the session header carries no title field), so it is always derived, never restored. +- The one-shot latch is now simply `titleSettled = !resolved.autoTitle`. The prior pre-settle-on-resume clause is gone: on resume `generateTitle` runs once from the stored first message and then latches, so a message that arrives *after* the resume does not re-title. A fresh session has no stored `user/message` at mount, so the resume scan is a no-op and the live `session/event` listener titles the first message instead. +- Everything else from the [auto-title Agent Note](2026-07-21-tui-auto-pane-title.md) stands unchanged: the OSC 0 `runtime.terminal.setTitle` path, the model-summary shape (two-to-five lowercase words, first non-empty line, 40-char cap), the fire-and-forget `ctx.llm.stream` call that never touches the session or transcript, the shutdown `AbortController`, and every failure fallback (empty reply, missing `llm`, missing provider/model, whitespace-only prompt). + +## Alternatives considered + +**Keep the feature off by default.** Rejected: this is a direct reversal of the [auto-title Agent Note](2026-07-21-tui-auto-pane-title.md)'s "default off" decision at the user's request. Off-by-default ships an inert feature; the descriptive name is only useful if it is the normal experience. The keyless-replay concern that motivated off-by-default is addressed by pinning `autoTitle: false` in the replay-backed snapshot scenarios rather than by suppressing it for every deployment. + +**Persist the derived title in the session header.** Rejected: the header has no title field and adding one would make a terminal label into session metadata — the boundary the [auto-title Agent Note](2026-07-21-tui-auto-pane-title.md) already drew against the log-backed session-title work. Re-deriving from the stored first message costs one tool-less call on resume and keeps the label a pure function of the conversation. + +**Re-derive on resume from the latest message instead of the first.** Rejected: the title summarises what the session is *about*, which its opening request captures; a mid-conversation message would make the pane label drift as the work moves on. + +## Consequences + +- A fresh session with a working `llm` now spends one extra tool-less model call by default (previously only when opted in); a resumed session spends one on mount. Deployments without an `llm` or provider/model are unaffected. +- The replay-backed `examples/tui-agent/tests/tui.snapshot.ts` must opt **out**: it pins `autoTitle: false`, because a default-on title request is not among the recorded turns and `installLlmReplay` fails loud on an unrecorded request. The unit `packages/ui/tui/tests/tui.snapshot.ts` needs no opt-out — it mounts no `llm` service, so `generateTitle` short-circuits and the default flip is inert there. The interactive `examples/tui-agent/cordis.yml` and the scripted PTY fixture already set `autoTitle: true`, so the keyless smoke's OSC 0 assertion is unchanged. +- `packages/ui/tui/tests/tui.spec.ts` pins the new defaults: the config-default test expects `autoTitle: true`; the disabled-path test now sets `autoTitle: false` explicitly; and the former "resumed session never fires" test is rewritten to assert re-derivation from the stored first message and that a later live message does not re-title. `docs/config-catalog.md` regenerates to "On by default". diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.zh.md new file mode 100644 index 0000000000..aa20cfde13 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-auto-title-default-on.zh.md @@ -0,0 +1,32 @@ +# Agent Note: 自动标题默认开启,恢复时重新推导 + +Status: implemented + +[English](2026-07-21-tui-auto-title-default-on.md) | 中文 + +> **已被取代**:见[标题归一 Agent Note](../simplification/2026-07-22-tui-titles-from-session-title-service.md)。TUI 本地的 `autoTitle` 生成已移除;标题来自日志承载的 session-title 服务,终端重命名消费 `session/title` 事件。 + +## Problem + +[自动标题 Agent Note](2026-07-21-tui-auto-pane-title.md) 交付时 `autoTitle` 默认关闭,并且在恢复会话中因首条 `user/message` 已入日志而保留静态标题。实际使用中这两个选择都违背了该功能的初衷。让一个 tmux 窗格或终端标签页区别于下一个的,正是每会话各异的描述性窗格标题;默认关闭意味着产品交付了一个几乎无人开启的惰性功能,而恢复时不重新推导,则意味着恢复会话——恰恰是最值得标记的长命会话——退回到共用的静态字符串。用户要求把每会话的描述性名称做成常态体验。 + +## Decision + +- `autoTitle` 默认**开启**(`z.boolean().default(true)`,`resolveTuiConfig` 以 `?? true` 与之对齐)。带有 `llm` 服务与 agent 提供方/模型的部署无需选择性开启即可在每个会话获得模型制作的窗格标题;不具备它们的部署保留静态标题,因此在调用无法运行处,默认开启是惰性的。 +- **恢复**会话在挂载时从其已入日志的首条 `user/message` 重新推导标题:`createTuiChat` 在 `agent.session.events` 中扫描首个此类事件,并把其文本喂给同一个一次性的 `generateTitle`。标题从不持久化(会话头不携带标题字段),因此它始终是推导得来,而非恢复而来。 +- 一次性门闩现在只是 `titleSettled = !resolved.autoTitle`。此前"恢复即预先结算"的分句已删除:恢复时 `generateTitle` 从已存储的首条消息运行一次随后上闩,因此恢复*之后*到达的消息不会再改标题。全新会话在挂载时没有已存储的 `user/message`,因此恢复扫描是空操作,改由实时的 `session/event` 监听器为首条消息命名。 +- [自动标题 Agent Note](2026-07-21-tui-auto-pane-title.md) 的其余一切保持不变:OSC 0 的 `runtime.terminal.setTitle` 路径、模型概括形态(两到五个小写单词、首个非空行、40 字符上限)、从不触碰会话或 transcript(文本记录)的发出后不等待其返回的 `ctx.llm.stream` 调用、关闭时的 `AbortController`,以及每一条失败兜底(空回复、缺 `llm`、缺提供方/模型、仅含空白的提示词)。 + +## Alternatives considered + +**让该功能保持默认关闭。** 否决:这是应用户要求,对[自动标题 Agent Note](2026-07-21-tui-auto-pane-title.md)"默认关闭"决策的直接反转。默认关闭交付的是惰性功能;只有当描述性名称成为常态体验时它才有用。当初促成默认关闭的无密钥回放顾虑,改由在以回放支撑的快照场景中固定 `autoTitle: false` 来处理,而非为每个部署都压制该功能。 + +**把推导出的标题持久化进会话头。** 否决:会话头没有标题字段,加一个会把终端标签变成会话元数据——正是[自动标题 Agent Note](2026-07-21-tui-auto-pane-title.md)已经对日志支撑的会话标题工作划出的边界。从已存储的首条消息重新推导,代价是恢复时一次无工具调用,并让标签保持为对话的纯函数。 + +**恢复时从最新消息而非首条消息重新推导。** 否决:标题概括的是会话*关于什么*,而这由其开场请求捕获;一条对话中途的消息会让窗格标签随工作推进而漂移。 + +## Consequences + +- 带可用 `llm` 的全新会话现在默认多花一次无工具的模型调用(此前只在选择性开启时才有);恢复会话在挂载时花掉一次。不具备 `llm` 或提供方/模型的部署不受影响。 +- 以回放支撑的 `examples/tui-agent/tests/tui.snapshot.ts` 必须选择**关闭**:它固定 `autoTitle: false`,因为默认开启的标题请求不在录制轮次之列,而 `installLlmReplay` 对未录制的请求会显式报错。单元 `packages/ui/tui/tests/tui.snapshot.ts` 无需选择关闭——它不挂载 `llm` 服务,因此 `generateTitle` 提前短路,默认值的翻转在那里是惰性的。交互式的 `examples/tui-agent/cordis.yml` 与脚本化 PTY fixture(测试前置数据)已设 `autoTitle: true`,因此无密钥冒烟测试的 OSC 0 断言保持不变。 +- `packages/ui/tui/tests/tui.spec.ts` 固定新的默认值:config 默认测试期望 `autoTitle: true`;关闭路径测试现在显式设 `autoTitle: false`;此前的"恢复会话从不触发"测试改写为断言从已存储首条消息重新推导,并断言之后的实时消息不会再改标题。`docs/config-catalog.md` 重新生成为"On by default"。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.i18n.yaml new file mode 100644 index 0000000000..684f23438c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-banner-brand-gradient.md: 41edf5d0bcf856bc7695af6bf651ff04c11adc01 +2026-07-21-tui-banner-brand-gradient.zh.md: 9253c001e8df2a4d0f79f69f32d65c11afd13e22 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.md b/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.md new file mode 100644 index 0000000000..41edf5d0bc --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.md @@ -0,0 +1,39 @@ +# Agent Note: TUI banner brand gradient + +Status: implemented + +English | [中文](2026-07-21-tui-banner-brand-gradient.zh.md) + +## Problem + +The TUI startup banner rendered the product name `DEEPSEEK` in the palette's flat accent color, which carries no brand identity and does not resemble the wordmark on deepseek.com. The request was to make the banner match the site logo's blue gradient specifically — not to recolor the rest of the coding harness. + +The banner is the one surface where that matters, and it conflicts with a load-bearing invariant: the TUI palette is deliberately theme-agnostic. It uses only standard 16-color ANSI (SGR) codes and attributes so a user's terminal scheme remaps every color; the `themeViolations()` snapshot gate rejects any RGB, extended-palette, or explicit-background cell. A smooth logo-matching gradient cannot be built from 16 palette colors, so reproducing it requires 24-bit truecolor, which the gate flags by design. + +## Decision + +The banner paints `DEEPSEEK` with a per-letter 24-bit truecolor foreground sweeping the deepseek.com brand gradient — `#4D6BFE` → `#3982FF` → `#2498FF` — via piecewise-linear interpolation across those three stops; `HARNESS` stays bold with the default foreground. The gradient is foreground-only, so it stays legible on any terminal background, and it is confined to the banner's product name. This is the sole sanctioned exception to the theme-agnostic palette; every other surface remains standard-ANSI and theme-adaptive. + +The gradient is gated on `resolved.color && resolved.truecolor`. When truecolor is unavailable the banner falls back to the existing flat bright-blue accent, so nothing about the theme-agnostic guarantee or the recorded snapshots changes unless truecolor is explicitly in play. + +`truecolor` is a validated `Config` field with no schema default. When it is unset, `apply()` auto-detects it at the process boundary from `COLORTERM` (`truecolor` or `24bit`); an explicit config value always wins. Detection reads `process.env` only in `apply()` — never in the pure `resolveTuiConfig` resolver — keeping the resolver a pure function of its input. + +The gradient stops are fixed brand identity, treated like a protocol constant, so they are hardcoded in the plugin rather than exposed as a tunable. Whether truecolor is *enabled* is terminal- and deployment-varying, so that is the validated `Config` field. The banner text is UI-only and never reaches a model request, so no session event is required. + +## Testing + +A dedicated `banner-gradient` terminal snapshot pins the real per-letter RGB output in an xterm emulator (`fg=#4d6bfe`…`#2498ff`, each letter bold). The shared `checkpoint()` helper takes a `bannerGradient` flag: for that one checkpoint it asserts the theme violations are non-empty and that every violation ends in `rgb-fg` — i.e. truecolor is present but confined to the banner foreground, with no background or extended-palette leak. Every other checkpoint keeps the strict `themeViolations()` `.toEqual([])` assertion, so the fence is mechanically enforced. A `tui.spec.ts` unit test mounts with `color`+`truecolor` enabled to cover the header's gradient branch and the `gradientText`/`brandColorAt` helpers. + +## Alternatives considered + +**A theme-safe stepped gradient built from the 16-color palette.** Approximating the sweep with bright-blue palette variants would keep the banner fully theme-agnostic and avoid touching the gate. It was rejected by the requester: 16 fixed colors cannot reproduce the smooth logo gradient, and the request was explicitly to match the site wordmark. + +**Recoloring the whole harness palette blue.** The original phrasing was "update the harness color to blue." That was narrowed to the banner only; a global blue palette would break theme-agnosticism everywhere, not just on one brand surface. + +**Always emitting truecolor.** Many terminals lack 24-bit support and would render the raw or degraded codes. Gating on detection with an ANSI fallback keeps the banner correct everywhere while still showing the gradient where it works. + +**Detecting truecolor inside `resolveTuiConfig`.** The resolver is a pure defaulting step and must not read `process.env`. Environment probing belongs at the process boundary in `apply()`, so `mountTui`/`createTuiChat` stay driven purely by their config input and remain fully testable with a fake terminal. + +## Consequences + +The banner now carries the DeepSeek brand identity on truecolor terminals while the theme-agnostic guarantee holds everywhere else — and even on the banner itself when truecolor is unavailable. The cost is one narrow, documented crack in the theme-agnostic invariant: a fixed-color surface that will not adapt to a user's terminal scheme, accepted because it is brand identity and foreground-only, so it stays legible on both light and dark backgrounds. The crack is fenced by the `banner-gradient` snapshot assertion, which confines truecolor to the banner foreground and fails if any other RGB, extended-palette, or background color ever appears. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.zh.md new file mode 100644 index 0000000000..9253c001e8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-banner-brand-gradient.zh.md @@ -0,0 +1,39 @@ +# Agent Note: TUI 启动横幅品牌渐变 + +Status: implemented + +[English](2026-07-21-tui-banner-brand-gradient.md) | 中文 + +## 问题 + +TUI 启动横幅原本用调色板的扁平强调色渲染产品名 `DEEPSEEK`,它不承载任何品牌标识,也不像 deepseek.com 上的字标。需求明确是让横幅匹配站点 logo 的蓝色渐变——而不是给整个 coding harness 重新上色。 + +横幅是唯一在意这件事的界面,而它与一条承重不变量冲突:TUI 调色板刻意做到主题无关。它只使用标准 16 色 ANSI(SGR)代码与属性,好让用户的终端配色方案能够重映射每一种颜色;`themeViolations()` 快照门禁会拒绝任何 RGB、扩展调色板或显式背景色的单元格。用 16 种调色板颜色无法拼出平滑的、与 logo 一致的渐变,因此复现它需要 24 位真彩色(truecolor),而门禁按设计会将其标记出来。 + +## 决策 + +横幅用逐字母的 24 位真彩色前景色渲染 `DEEPSEEK`,沿 deepseek.com 品牌渐变——`#4D6BFE` → `#3982FF` → `#2498FF`——在这三个色标之间做分段线性插值;`HARNESS` 保持加粗并使用默认前景色。渐变仅作用于前景色,因此在任何终端背景上都保持可读,并且被限制在横幅的产品名内。这是主题无关调色板唯一获准的例外;其余每个界面都保持标准 ANSI 且随主题自适应。 + +渐变以 `resolved.color && resolved.truecolor` 为开关。当真彩色不可用时,横幅回退到既有的扁平亮蓝强调色,因此除非显式启用真彩色,主题无关保证与已录制的快照都不会改变。 + +`truecolor` 是一个经校验的 `Config` 字段,schema 不设默认值。当它未设置时,`apply()` 会在进程边界从 `COLORTERM`(`truecolor` 或 `24bit`)自动探测;显式的配置值始终优先。探测只在 `apply()` 中读取 `process.env`——绝不在纯粹的 `resolveTuiConfig` 解析器中——从而让解析器保持为其输入的纯函数。 + +渐变色标是固定的品牌标识,被当作协议常量对待,因此硬编码在插件里,而不作为可调项暴露。是否*启用*真彩色则随终端与部署而变,所以那才是经校验的 `Config` 字段。横幅文本仅面向界面,永不进入任何模型请求,因此不需要会话事件。 + +## 测试 + +一个专门的 `banner-gradient` 终端快照在 xterm 模拟器中固定了真实的逐字母 RGB 输出(`fg=#4d6bfe`…`#2498ff`,每个字母加粗)。共享的 `checkpoint()` 辅助函数接受一个 `bannerGradient` 标志:仅对该 checkpoint,它断言主题违规项非空,且每一项都以 `rgb-fg` 结尾——即真彩色确实存在,但被限制在横幅前景色,没有背景色或扩展调色板的泄漏。其余每个 checkpoint 都保持严格的 `themeViolations()` `.toEqual([])` 断言,因此这道围栏是机械强制的。一个 `tui.spec.ts` 单元测试在同时启用 `color` 与 `truecolor` 时挂载,以覆盖 header 的渐变分支以及 `gradientText`/`brandColorAt` 辅助函数。 + +## 曾考虑的替代方案 + +**用 16 色调色板拼出的主题安全阶梯渐变。** 用亮蓝的调色板变体近似这段渐变可以让横幅完全保持主题无关,并避免触碰门禁。它被需求方否决了:16 种固定颜色无法复现平滑的 logo 渐变,而需求明确是匹配站点字标。 + +**给整个 harness 调色板重新上蓝色。** 最初的说法是"把 harness 颜色改成蓝色"。它被收窄到只改横幅;全局蓝色调色板会在各处而非仅一个品牌界面上破坏主题无关性。 + +**始终发射真彩色。** 许多终端不支持 24 位,会渲染出原始或降级的代码。以探测为开关并配以 ANSI 回退,能让横幅在各处都正确,同时仍在支持的地方展示渐变。 + +**在 `resolveTuiConfig` 内探测真彩色。** 该解析器是纯粹的默认值填充步骤,绝不能读取 `process.env`。环境探测属于 `apply()` 中的进程边界,从而让 `mountTui`/`createTuiChat` 完全由其配置输入驱动,并在使用假终端时保持完全可测。 + +## 后果 + +现在横幅会在真彩色终端上承载 DeepSeek 品牌标识,而主题无关保证在其余各处依然成立——甚至当真彩色不可用时在横幅自身上也成立。代价是主题无关不变量上一道狭窄且有记录的裂缝:一个不会随用户终端配色方案自适应的固定颜色界面,之所以接受,是因为它是品牌标识且仅作用于前景色,从而在浅色与深色背景上都保持可读。这道裂缝由 `banner-gradient` 快照断言把守,它将真彩色限制在横幅前景色,一旦其他任何 RGB、扩展调色板或背景色出现就会失败。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.i18n.yaml new file mode 100644 index 0000000000..a06145f092 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-banner-sweep.md: c146424d53e75a72b63e346f87a5bbd206d67350 +2026-07-21-tui-banner-sweep.zh.md: 01cc153e88f067b7b8d2eb6317648f3892fe8a5a diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.md b/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.md new file mode 100644 index 0000000000..c146424d53 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.md @@ -0,0 +1,35 @@ +# Agent Note: The banner sweeps in; the subtitle line is gone + +Status: implemented + +English | [中文](2026-07-21-tui-banner-sweep.zh.md) + +> **Superseded** by the [no-banner Agent Note](2026-07-21-tui-no-banner.md): the banner itself was removed, taking the sweep with it. + +## Problem + +The [startup-slogans Agent Note](2026-07-20-tui-startup-slogans.md) replaced the instructional welcome line with a random slogan bank revealed by a per-character typewriter. In use the quotes read as weird — random flavor text in a tool's header — and the animation was slow (40 ms/char over a full sentence) while animating only one line of a four-line banner. This note supersedes that decision's slogan half; the removal of the configured demo welcome and the animation-lifecycle groundwork stand. + +## Decision + +- The slogan bank, `pickStartupSlogan`, and the typewriter reveal are deleted. When `welcome` is unset the banner simply has **no subtitle line** — title and model/session detail only. The `welcome` config remains for deployments and fixtures that want a fixed subtitle, rendered frame-deterministically with no animation. +- The startup animation is now the **whole banner**: `HeaderComponent` gains a `revealWidth` clip, and the header box wipes in left-to-right over ~24 frames at 15 ms (~360 ms total, ~60 fps), started after `ui.start()` succeeds and cleared through the same `detachListeners` path the typewriter used. `stopBannerReveal` also resets the clip so a disposed-mid-sweep header re-renders whole. +- The PTY smoke's boot marker changes from the typewriter cursor (`▌`) to the banner's top-right corner (`╮`), which only renders once the sweep completes. + +## Alternatives considered + +**Keep the animation as-is and only change the copy.** Rejected: any fixed or rotating phrase re-read on every boot decays into wallpaper; the user's judgment was that the quotes themselves, not just their content, were wrong for the surface. + +**Animate per banner line (top-down) instead of a left-right sweep.** Rejected: with only four lines the animation would have four visible steps — closer to a flicker than a reveal; the horizontal sweep uses the full terminal width for a smooth motion at the same total duration. + +**Character-level clipping via `revealWidth` on styled text.** Adopted with `truncateToWidth` from pi-tui, the same ANSI-aware clipper the header already uses for width overflow, so the sweep cannot tear escape sequences. + +## Consequences + +- Boot output with `welcome` unset is again animation-dependent but no longer random: every boot sweeps the same banner. Configured welcomes (all snapshot/scripted fixtures, the Code Mode overlay) stay frame-deterministic and unchanged. +- The `STARTUP_SLOGANS`/`pickStartupSlogan` exports are gone; no consumer outside the deleted tests referenced them. +- The default banner is one line shorter (no subtitle), so PTY assertions anchored on banner geometry use the corner glyph rather than any subtitle text. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` pins: the sweep completes to a full banner (both corners + title) and produced at least one clipped mid-sweep frame; a configured welcome renders verbatim with no clipped frames; the unset-welcome banner has no subtitle; and dispose clears the sweep's own interval handle. The PTY smoke boots on the `╮` completion marker across the tui-demo bin, the dsh CLI, and the personal-overlay scenarios. Verified live in tmux. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.zh.md new file mode 100644 index 0000000000..01cc153e88 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-banner-sweep.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 横幅整体扫入;副标题行移除 + +Status: implemented + +[English](2026-07-21-tui-banner-sweep.md) | 中文 + +> **已被取代**:由[移除启动横幅 Agent Note](2026-07-21-tui-no-banner.md)取代:横幅本身已移除,扫入动画随之移除。 + +## Problem + +[启动 slogan Agent Note](2026-07-20-tui-startup-slogans.md) 用随机 slogan 库加逐字打字机动画取代了说明书式的欢迎行。实际使用中这些引语显得怪异——工具头部出现随机的风味文案——而且动画很慢(每字符 40 ms,扫完一整句),却只动画四行横幅中的一行。本 note 取代该决定中 slogan 的那一半;移除示例配置中欢迎语的决定与动画生命周期的基础设施保持不变。 + +## Decision + +- 删除 slogan 库、`pickStartupSlogan` 和打字机动画。`welcome` 未设置时横幅直接**没有副标题行**——只有标题和模型/会话详情。`welcome` 配置保留给想要固定副标题的部署与 fixture,无动画、逐帧确定地渲染。 +- 启动动画现在作用于**整个横幅**:`HeaderComponent` 增加 `revealWidth` 裁剪,头部盒子以约 24 帧、每帧 15 ms(总计约 360 ms、约 60 fps)从左到右扫入,在 `ui.start()` 成功后启动,经打字机动画用过的同一条 `detachListeners` 路径清除。`stopBannerReveal` 同时重置裁剪,因此扫入中途被 dispose 的头部会重新完整渲染。 +- PTY 冒烟测试的启动标记从打字机光标(`▌`)改为横幅右上角(`╮`),它只在扫入完成后才渲染。 + +## Alternatives considered + +**保留动画原样、只改文案。** 否决:任何每次启动都被重读的固定或轮换语句都会退化成墙纸;用户的判断是引语本身——而不只是内容——对这个表面来说就是错的。 + +**按横幅行逐行(自上而下)动画而非左右扫入。** 否决:只有四行时动画只有四个可见步骤——更像闪烁而不是展开;水平扫入用满终端宽度,在相同总时长内动作更平滑。 + +**用 `revealWidth` 对带样式文本做字符级裁剪。** 采用 pi-tui 的 `truncateToWidth`——头部处理宽度溢出时已在使用的同一个 ANSI 感知裁剪器——因此扫入不可能撕裂转义序列。 + +## Consequences + +- `welcome` 未设置时启动输出再次依赖动画但不再随机:每次启动扫入同一幅横幅。配置了欢迎语的场景(全部快照/脚本化 fixture、Code Mode overlay)保持逐帧确定且不变。 +- `STARTUP_SLOGANS`/`pickStartupSlogan` 导出移除;除被删除的测试外没有消费者引用它们。 +- 默认横幅少一行(无副标题),因此锚定横幅几何的 PTY 断言使用角落字形而非任何副标题文本。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 固定:扫入完成为完整横幅(两个角 + 标题)且产生了至少一个裁剪的中途帧;配置的欢迎语原文渲染且无裁剪帧;未设置欢迎语的横幅没有副标题;dispose 清除扫入自己的定时器句柄。PTY 冒烟测试在 tui-demo bin、dsh CLI 和个人 overlay 场景中以 `╮` 完成标记启动。已在 tmux 中实机验证。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.i18n.yaml new file mode 100644 index 0000000000..8732101ab2 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-borderless-banner.md: 37263854b6cc77283215c3c1378f9908ff966611 +2026-07-21-tui-borderless-banner.zh.md: ca796e49cb9d3a9abc0acd64a39448bc3f9ad50e diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.md b/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.md new file mode 100644 index 0000000000..37263854b6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.md @@ -0,0 +1,39 @@ +# Agent Note: The banner returns, borderless + +Status: implemented + +English | [中文](2026-07-21-tui-borderless-banner.zh.md) + +## Problem + +The [no-banner Agent Note](2026-07-21-tui-no-banner.md) removed the boxed startup banner: it deleted `HeaderComponent` and its sweep, moved the model into the footer, dropped the session id, and rendered `welcome` as the transcript's first line. The user's verdict reversed that: bring the banner back — "just remove the border". The four-row box frame was the objectionable chrome, not the identifying facts it carried (model, session id) nor the sweep-in motion. + +## Decision + +- `HeaderComponent` and its left-to-right sweep return, but render **borderless**: no `╭─╮`/`╰─╯` corners and no `│` side bars. Each line is a single leading space plus `truncateToWidth`-clipped content, so the sweep's width clip can never tear an escape sequence and no fixed frame is drawn. +- The header carries the title (`DEEPSEEK HARNESS`), a `` detail line, and — when `welcome` is set — a muted subtitle. With `welcome` unset the header is title + detail only. +- The model **also** stays in the footer's left segment. The no-banner note's footer model prefix is kept, not reverted, so the driving model stays glanceable after the transient banner scrolls out of view. +- `welcome` reverts to a banner subtitle; the transcript-first-line notice is removed from `rebuildTranscript`. +- The sweep animates only when `welcome` is unset. A configured `welcome` renders the whole banner immediately, keeping fixtures and snapshots frame-deterministic. The sweep starts after `ui.start()` succeeds and is cleared through the same `detachListeners` path via `stopBannerReveal`, which also resets the clip so a header disposed mid-sweep re-renders whole. + +This supersedes the [no-banner Agent Note](2026-07-21-tui-no-banner.md) (which superseded the [banner-sweep Agent Note](2026-07-21-tui-banner-sweep.md)): the banner and its sweep return borderless, while the model's footer home the no-banner note added stays. + +## Alternatives considered + +**Keep the box but thin it or use lighter glyphs.** Rejected: the instruction was "just remove the border"; any surrounding glyph is the frame chrome the user objected to. + +**Drop the model from the footer now that the banner shows it again.** Rejected: the banner is transient and scrolls away with the transcript, while the footer keeps the model visible for the whole session — the reason the no-banner note put it there, deliberately preserved. + +**Leave the session id out, as the no-banner note decided.** Rejected: with the box gone the detail line costs one row, and the user asked for the banner "as before", which carried `model • session-id`. + +## Consequences + +- Boot output with `welcome` unset is animation-dependent again (the sweep); configured welcomes stay frame-deterministic, so every snapshot and scripted fixture keeps a fixed subtitle. +- The model now appears twice at boot — banner detail and footer — intended redundancy: the banner is transient, the footer persistent. +- `/clear` empties the transcript but not the header, so the banner and its configured subtitle survive `/clear`, unlike the no-banner welcome line that `/clear` wiped. +- All pi-tui terminal snapshots and the examples/tui-agent replay snapshots re-recorded (`test:snapshot:refresh`): banner rows return with no box glyphs; footer rows keep the model prefix. +- Anything that anchored on banner absence re-anchors on its presence: the PTY smoke boots on the detail line's `main-session-` id (revealed late in the sweep) and asserts `DEEPSEEK`/`HARNESS` present with no box corners. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` pins: the borderless banner sweeps to natural completion — no box corners, title and `main-session` detail present — with at least one clipped mid-sweep frame; a configured `welcome` renders the whole banner with no clipped frame; the unset-welcome banner has no subtitle; and dispose clears the sweep interval mid-sweep. The tui-agent and dsh-CLI PTY smokes boot on the `main-session-` detail marker and assert no box corners. Snapshots verify the full frames. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.zh.md new file mode 100644 index 0000000000..ca796e49cb --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-borderless-banner.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 横幅回归,无边框 + +Status: implemented + +[English](2026-07-21-tui-borderless-banner.md) | 中文 + +## Problem + +[移除横幅 Agent Note](2026-07-21-tui-no-banner.md) 删掉了带框的启动横幅:它删除了 `HeaderComponent` 及其扫入动画,把模型移入页脚,丢弃了会话 id,并把 `welcome` 渲染为 transcript 的第一行。用户的裁决把这一切反转:把横幅拿回来——"just remove the border"。令人反感的装饰是那四行盒子边框,而不是它承载的识别信息(模型、会话 id),也不是扫入动效。 + +## Decision + +- `HeaderComponent` 及其从左到右的扫入动画回归,但以**无边框**方式渲染:没有 `╭─╮`/`╰─╯` 边角,也没有 `│` 侧边。每一行都是一个前导空格加上经 `truncateToWidth` 裁剪的内容,因此扫入的宽度裁剪永远不会撕裂转义序列,也不绘制任何固定边框。 +- 头部承载标题(`DEEPSEEK HARNESS`)、一条 `` 详情行,以及——当设置了 `welcome` 时——一条弱化的副标题。`welcome` 未设置时头部只有标题加详情。 +- 模型**同时**保留在页脚的左段。移除横幅那版 note 加入的页脚模型前缀被保留而非回退,因此在短暂的横幅滚出视野后,会话使用的模型仍可一瞥可见。 +- `welcome` 恢复为横幅副标题;transcript 第一行的通知从 `rebuildTranscript` 中移除。 +- 仅当 `welcome` 未设置时才播放扫入动画。配置了 `welcome` 会立即渲染整个横幅,使 fixture 和快照保持帧确定性。扫入在 `ui.start()` 成功后启动,并经与之前相同的 `detachListeners` 路径通过 `stopBannerReveal` 清理;后者还会重置裁剪,使扫入中途被销毁的头部重新完整渲染。 + +本 note 取代[移除横幅 Agent Note](2026-07-21-tui-no-banner.md)(后者取代了[横幅扫入 Agent Note](2026-07-21-tui-banner-sweep.md)):横幅及其扫入动画以无边框方式回归,而移除横幅那版 note 为模型设立的页脚归宿得以保留。 + +## Alternatives considered + +**保留盒子但做细或改用更轻的字符。** 否决:指令是 "just remove the border";任何环绕的字符都是用户所反对的边框装饰。 + +**既然横幅重新显示模型,就把模型从页脚移除。** 否决:横幅是短暂的,会随 transcript 滚走,而页脚在整个会话中保持模型可见——这正是移除横幅那版 note 把它放在那里的原因,此处刻意保留。 + +**像移除横幅那版 note 那样,把会话 id 留在外面。** 否决:盒子去掉后详情行只占一行,且用户要求横幅"和以前一样",而以前它承载 `model • session-id`。 + +## Consequences + +- `welcome` 未设置时的启动输出再次依赖动画(扫入);配置了欢迎语则保持帧确定性,因此每个快照和脚本 fixture 都保留一个固定副标题。 +- 模型现在在启动时出现两次——横幅详情与页脚——这是有意的冗余:横幅短暂,页脚常驻。 +- `/clear` 清空 transcript 但不清头部,因此横幅及其配置的副标题在 `/clear` 后存活,不同于被 `/clear` 清掉的移除横幅那版的欢迎行。 +- 全部 pi-tui 终端快照与 examples/tui-agent 回放快照重新录制(`test:snapshot:refresh`):横幅行以无盒子字符方式回归;页脚行保留模型前缀。 +- 一切锚定横幅缺失的内容改为锚定其存在:PTY 冒烟测试以详情行的 `main-session-` id 为启动标记(它在扫入后段才被揭示),并断言 `DEEPSEEK`/`HARNESS` 出现且无盒子角。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 固定:无边框横幅扫入至自然完成——无盒子角、标题与 `main-session` 详情出现——且至少有一帧扫入中途被裁剪;配置的 `welcome` 完整渲染横幅且无裁剪帧;未设置 `welcome` 的横幅无副标题;销毁会在扫入中途清掉扫入定时器。tui-agent 与 dsh CLI 的 PTY 冒烟测试以 `main-session-` 详情标记为启动标记并断言无盒子角。快照验证完整帧。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.i18n.yaml new file mode 100644 index 0000000000..d7cdbb3c3c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-footer-cache-hit-rate.md: aaee8ed31ff8f20370f490d3ce27c8705cda3e16 +2026-07-21-tui-footer-cache-hit-rate.zh.md: 67a7aa474d98878a5bc0bc0a76a8c2ccad004e9b diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.md b/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.md new file mode 100644 index 0000000000..aaee8ed31f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.md @@ -0,0 +1,41 @@ +# Agent Note: TUI footer shows the session cache hit rate + +Status: implemented + +English | [中文](2026-07-21-tui-footer-cache-hit-rate.zh.md) + +## Problem + +The footer summed the session's token usage as `↑`, where `↑` is the uncached input reported by the model. `TokenUsage` counts are disjoint: billed prompt tokens are `inputTokens` (uncached) plus `cacheReadTokens` and `cacheWriteTokens`. With only the uncached number visible, a user could not tell how much of each turn's prompt the provider cache served — the signal that most directly reflects whether the reused request prefix is paying off. On a long session dominated by cache reads the `↑` figure stays small and hides that the prompt is large but cheap. + +## Decision + +The footer appends `cache %` after `↑`, where the rate is the share of billed prompt tokens served from the provider cache. + +- `TokenTotals` accumulates the four disjoint buckets (`input`, `output`, `cacheRead`, `cacheWrite`). `addUsage` folds one call's `TokenUsage` into the totals, treating a missing `cacheReadTokens`/`cacheWriteTokens` as zero. +- `cacheHitRate(totals)` is `round(cacheRead / (input + cacheRead + cacheWrite) * 100)`, and `undefined` before any input is billed. `FooterComponent` omits the whole ` cache N%` segment while the rate is `undefined`, so an empty session shows no meaningless zero. +- `↑` keeps meaning uncached input, not billed input: the disjoint-bucket convention holds across the footer, and the cache percent supplies the reuse signal the raw counts cannot. +- Totals are rebuilt on mount by `sessionTokens`, which sums usage over `assistant/message` events (never `assistant/chunk`, to avoid double counting), and updated live from each `assistant/message` event that carries usage. + +## Alternatives considered + +**Show billed input (`input + cacheRead + cacheWrite`) as `↑` instead of a separate percent.** Rejected: it would redefine `↑` away from the disjoint `inputTokens` bucket the rest of the harness reports, and it would still hide the reuse share the user actually wants; a derived percent adds the signal without overloading the count. + +**Compute the rate against all tokens (`input + output + cache`).** Rejected: output tokens are never cache-served, so folding them into the denominator understates the rate for no meaning; cache hit rate is a property of the prompt. + +**Drop `cacheWrite` from the denominator.** Rejected: cache writes are billed input the provider spent to populate the cache, so excluding them overstates the hit rate on a writing turn. DeepSeek reports no cache-write metric today, but the formula stays general and the write path is covered. + +**Render `cache 0%` on an empty session.** Rejected: the billed input is `0`, the ratio is `0/0`, and a `0%` badge on a fresh session is a lie about a value that does not exist yet; the segment stays hidden until input is billed. + +**Give the metric its own right-aligned footer element beside `tools:`.** Rejected: it derives from the adjacent token counts and reads best in the `input → output → cache` order; grouping it left also keeps the lower-priority `tools:` indicator as the element that clips first under width pressure, matching the footer's existing layout priority. + +## Consequences + +- The left group grew by ` cache N%`, so on a narrow footer the right-side `tools:` state clips sooner. This follows the footer's pre-existing left-priority truncation and is an accepted trade-off. +- The metric is best-effort live UI state derived from `assistant/message` usage: rebuilt from the session on mount, updated live, and never persisted. +- `packages/ui/tui/src/index.ts` stays at 100 % per-file coverage. +- The `examples/tui-agent` terminal snapshots carry the segment: a turn with cache reads renders e.g. `cache 49%`, and a first cold turn renders `cache 0%`. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` drives the footer through the real `createTuiChat`: an empty session renders `↑0 ↓0` with no cache segment (the hidden path), a cold turn (`inputTokens` only) renders `cache 0%`, and a live warm turn carrying `cacheReadTokens` and `cacheWriteTokens` updates it to `cache 60%` while no longer showing `cache 0%`. The `examples/tui-agent` snapshot suite replays green against the recorded expected output. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.zh.md new file mode 100644 index 0000000000..67a7aa474d --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-footer-cache-hit-rate.zh.md @@ -0,0 +1,41 @@ +# Agent Note: TUI 页脚展示会话缓存命中率 + +Status: implemented + +[English](2026-07-21-tui-footer-cache-hit-rate.md) | 中文 + +## Problem + +页脚原本把会话的 token 用量汇总为 `↑`,其中 `↑` 是模型上报的未缓存输入。`TokenUsage` 的各项计数互不重叠:计费的输入 token 由 `inputTokens`(未缓存)加上 `cacheReadTokens` 与 `cacheWriteTokens` 构成。只暴露未缓存的那个数字,用户就无从判断每轮提示词有多少由提供方缓存承接——而这恰是最能反映复用的请求前缀是否奏效的信号。在以缓存读取为主的长会话里,`↑` 始终很小,掩盖了提示词其实很大但很便宜的事实。 + +## Decision + +页脚在 `↑` 之后追加 `cache %`,该比率是计费输入 token 中由提供方缓存承接的占比。 + +- `TokenTotals` 累加四个互不重叠的桶(`input`、`output`、`cacheRead`、`cacheWrite`)。`addUsage` 把单次调用的 `TokenUsage` 折入总量,缺失的 `cacheReadTokens`/`cacheWriteTokens` 视为零。 +- `cacheHitRate(totals)` 为 `round(cacheRead / (input + cacheRead + cacheWrite) * 100)`,在尚无输入计费前返回 `undefined`。比率为 `undefined` 时 `FooterComponent` 整段略去 ` cache N%`,因此空会话不会显示无意义的零。 +- `↑` 仍表示未缓存输入,而非计费输入:页脚全程遵守互不重叠的桶约定,缺失的复用信号由缓存百分比补足。 +- 挂载时由 `sessionTokens` 重建总量,它对带 usage 的 `assistant/message` 事件求和(绝不用 `assistant/chunk`,以免重复计数);此后每条携带 usage 的 `assistant/message` 事件都会实时更新。 + +## Alternatives considered + +**把计费输入(`input + cacheRead + cacheWrite`)作为 `↑`,不单列百分比。** 否决:这会让 `↑` 偏离 harness 其余部分上报的互不重叠 `inputTokens` 桶,且仍旧藏住用户真正想要的复用占比;派生一个百分比既补上信号,又不给计数加载额外含义。 + +**用全部 token(`input + output + cache`)作分母计算比率。** 否决:输出 token 从不由缓存承接,把它折进分母只会无意义地拉低比率;缓存命中率是提示词的属性。 + +**从分母里去掉 `cacheWrite`。** 否决:缓存写入是提供方为填充缓存而付费的计费输入,剔除它会在写入的那一轮高估命中率。DeepSeek 目前不上报缓存写入指标,但公式保持通用,写入路径也有覆盖。 + +**在空会话上渲染 `cache 0%`。** 否决:此时计费输入为 `0`,比值是 `0/0`,在全新会话上打出 `0%` 是对一个尚不存在的值撒谎;在输入计费之前该段一直隐藏。 + +**给该指标单独一个右对齐的页脚元素,紧挨 `tools:`。** 否决:它派生自相邻的 token 计数,按 `input → output → cache` 的顺序阅读最顺;左置分组还让优先级更低的 `tools:` 指示成为宽度紧张时最先被裁剪的元素,与页脚既有的布局优先级一致。 + +## Consequences + +- 左段增加了 ` cache N%`,因此窄终端上右侧的 `tools:` 状态更早被裁剪。这沿用页脚既有的左段优先裁剪策略,是可接受的取舍。 +- 该指标是从 `assistant/message` 的 usage 派生的尽力而为实时 UI 状态:挂载时从会话重建、随后实时更新、从不持久化。 +- `packages/ui/tui/src/index.ts` 保持 100% 单文件覆盖率。 +- `examples/tui-agent` 终端快照带有该段:有缓存读取的一轮渲染为如 `cache 49%`,首个冷启动轮次渲染为 `cache 0%`。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 通过真实的 `createTuiChat` 驱动页脚:空会话渲染 `↑0 ↓0` 且无缓存段(隐藏路径),冷启动一轮(仅 `inputTokens`)渲染 `cache 0%`,随后实时的热轮次携带 `cacheReadTokens` 与 `cacheWriteTokens`,把它更新为 `cache 60%` 且不再显示 `cache 0%`。`examples/tui-agent` 快照套件对已录制的预期输出回放通过。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.i18n.yaml new file mode 100644 index 0000000000..56333563f5 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-no-banner.md: f5f4b1b847740e741ec3e33a6116e7497e955bd1 +2026-07-21-tui-no-banner.zh.md: 956fe03e2c0b09ea7378ffd53ffbe8d712d1e152 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.md b/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.md new file mode 100644 index 0000000000..f5f4b1b847 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.md @@ -0,0 +1,39 @@ +# Agent Note: No startup banner + +Status: implemented + +English | [中文](2026-07-21-tui-no-banner.zh.md) + +> **Superseded** by the [borderless-banner Agent Note](2026-07-21-tui-borderless-banner.md): the banner and its sweep return without the box. The model's footer home this note added stays. + +## Problem + +The TUI opened with a boxed product banner ("DEEPSEEK HARNESS" + model/session detail), most recently with a sweep-in animation ([banner sweep Agent Note](2026-07-21-tui-banner-sweep.md)). The user's verdict: remove it. A product title re-read on every boot is chrome, the box spends four rows before any content, and the identifying facts it carried (model, session) have better homes. + +## Decision + +- `HeaderComponent`, the sweep animation, and its lifecycle wiring are deleted. The TUI mounts straight into the transcript; startup renders nothing above the separator. +- The model name moves into the footer status line's left segment (` ↑tokens ↓tokens`), so the session's driving model stays visible at all times, not just at boot. The session id is no longer displayed — it lives in the session log and `./.sessions` filenames, and `RESUME_SESSION_ID` consumers retrieve it there. +- `welcome`, when configured, renders as the transcript's first line (a muted notice) inside `rebuildTranscript`, so palette swaps preserve it. Unset renders nothing. Fixtures keep their configured welcomes; the PTY smoke's boot marker becomes the footer's model name, the only mounted-TUI text guaranteed to render regardless of cwd length. + +This supersedes the [banner sweep Agent Note](2026-07-21-tui-banner-sweep.md) entirely: both the sweep and the banner it animated are gone. + +## Alternatives considered + +**Keep a one-line header (no box).** Rejected: the only load-bearing fact was the model name, and the footer already aggregates session status; a dedicated header row for one fact is the same chrome, smaller. + +**Show the session id in the footer too.** Rejected: a 36-char UUID dominates the 100-column footer and clips the status segment; it identifies the session for resume, which is a log/filesystem concern, not a glanceable one. + +**Print the welcome outside the transcript (above the separator).** Rejected: any fixed region above the transcript is a banner again; as a transcript line it scrolls away naturally and survives rebuilds through the same path as every other transcript element. + +## Consequences + +- Startup output is fully deterministic again — no animation frames at all; the interval-lifecycle machinery from the two animation iterations is gone. +- All 26 pi-tui terminal snapshots re-recorded (`test:snapshot:refresh`): banner rows gone, footer rows gain the model prefix. +- Anything that anchored on banner text (`DEEPSEEK`, box corners) re-anchors on the footer model name; `main-session-` no longer appears in boot output. +- `/clear` now wipes the welcome line too: it is an ordinary transcript line, and `/clear` empties the transcript (the old banner survived `/clear` only by sitting outside it). +- The footer's left segment is wider; on narrow terminals the right status segment clips earlier. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` pins: no box corners/product title and an empty transcript when `welcome` is unset, with the model in the footer; a configured welcome as the first transcript line without a banner; and the welcome surviving a palette-swap transcript rebuild. The PTY smoke boots on the footer model name and asserts `DEEPSEEK HARNESS` is absent. Snapshots verify the full frames. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.zh.md new file mode 100644 index 0000000000..956fe03e2c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-no-banner.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 移除启动横幅 + +Status: implemented + +[English](2026-07-21-tui-no-banner.md) | 中文 + +> **已被取代**,见[无边框横幅 Agent Note](2026-07-21-tui-borderless-banner.md):横幅及其扫入动画回归,只是去掉了盒子。本 note 为模型设立的页脚归宿得以保留。 + +## Problem + +TUI 启动时展示一个带框的产品横幅("DEEPSEEK HARNESS" + 模型/会话详情),最近一版还带扫入动画([横幅扫入 Agent Note](2026-07-21-tui-banner-sweep.md))。用户的裁决:删掉它。每次启动都被重读的产品标题是装饰,盒子在任何内容之前先占掉四行,而它承载的识别信息(模型、会话)有更好的去处。 + +## Decision + +- 删除 `HeaderComponent`、扫入动画及其生命周期接线。TUI 直接挂载进 transcript;启动时分隔线之上不渲染任何东西。 +- 模型名移入页脚状态行的左段(` ↑tokens ↓tokens`),会话使用的模型因此始终可见,而不只是启动时。会话 id 不再显示——它存在于会话日志和 `./.sessions` 文件名中,`RESUME_SESSION_ID` 的使用者从那里获取。 +- 配置了 `welcome` 时,它作为 transcript 的第一行(一条弱化的通知)在 `rebuildTranscript` 内渲染,因此调色板切换会保留它。未设置则什么也不渲染。fixture 保留各自配置的欢迎语;PTY 冒烟测试的启动标记改为页脚的模型名——无论 cwd 多长都保证渲染的唯一挂载后文本。 + +本 note 完全取代[横幅扫入 Agent Note](2026-07-21-tui-banner-sweep.md):扫入动画和它所动画的横幅都已移除。 + +## Alternatives considered + +**保留单行头部(去掉盒子)。** 否决:唯一有承载价值的信息是模型名,而页脚已经聚合会话状态;为一条信息保留专用头部行仍是同一种装饰,只是小一点。 + +**把会话 id 也放进页脚。** 否决:36 字符的 UUID 会占满 100 列页脚并裁掉状态段;它的用途是恢复会话的标识,属于日志/文件系统关注点,不是需要一瞥可见的信息。 + +**把欢迎语渲染在 transcript 之外(分隔线上方)。** 否决:transcript 上方任何固定区域都会再次变成横幅;作为 transcript 行它自然滚走,并通过与其他 transcript 元素相同的路径在重建后保留。 + +## Consequences + +- 启动输出再次完全确定——没有任何动画帧;两轮动画迭代留下的定时器生命周期机制全部移除。 +- 全部 26 个 pi-tui 终端快照重新录制(`test:snapshot:refresh`):横幅行消失,页脚行增加模型前缀。 +- 锚定横幅文本(`DEEPSEEK`、盒子角)的内容改为锚定页脚模型名;启动输出中不再出现 `main-session-`。 +- `/clear` 现在也会清掉欢迎行:它是普通的 transcript 行,而 `/clear` 清空 transcript(旧横幅能在 `/clear` 后存活只因为它在 transcript 之外)。 +- 页脚左段变宽;窄终端上右侧状态段更早被裁剪。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 固定:`welcome` 未设置时无盒子角/产品标题、transcript 为空、模型在页脚;配置的欢迎语作为 transcript 第一行且无横幅;欢迎语在调色板切换的 transcript 重建后保留。PTY 冒烟测试以页脚模型名为启动标记并断言 `DEEPSEEK HARNESS` 不出现。快照验证完整帧。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.i18n.yaml new file mode 100644 index 0000000000..321131ac96 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-reload-command.md: de9a5502214a610d88024730b1c0c1044a396c92 +2026-07-21-tui-reload-command.zh.md: 25d1d448459221698ca63377f8f18d05a0fa3d21 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.md b/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.md new file mode 100644 index 0000000000..de9a550221 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.md @@ -0,0 +1,35 @@ +# Agent Note: The /reload command re-reads loader configs on demand + +Status: implemented + +English | [中文](2026-07-21-tui-reload-command.zh.md) + +## Problem + +HMR's file watcher only reacts to in-place `change` events under its configured roots (the config leaf's directory in the shipped demos). Editors that replace files by rename (BSD `sed -i`, `git checkout`) produce no event, and runtimes without the HMR entry (or without `--expose-internals`) have no config reload path at all. During development that means restarting the TUI to apply a config edit the watcher missed. Widening the watch roots to the whole repo was considered and rejected in discussion: dense package sharing makes module-level HMR a remount-most-of-the-tree operation with unpredictable externals boundaries. + +## Decision + +`dsh-tui` gains an **experimental, dev-only** `/reload` slash command: it walks `ctx.loader.entries()` and calls `refresh()` on every file-backed subtree (`Include`), i.e. the exact code path the HMR watcher's config-change branch drives, invoked manually and watcher-independent. Unchanged files are no-ops (content comparison in `Include.read`). + +The TUI reaches the Loader **structurally** (`ctx.loader` via a local type, not `inject`): tests and embedders run the TUI without a Loader, where `/reload` degrades to a warning notice instead of failing the mount. Module-source hot reload stays watcher-owned; `/reload` refreshes configs only. + +## Alternatives considered + +**Widening the HMR watch roots to `packages/`/`apps/`.** Rejected for now: plugin-source changes reload every dependent plugin's fiber, and the repo's dense shared packages (`dsh-session`, `dsh-llm`, `dsh-tools`) make that a teardown of the spine and the UI mid-session — a restart in disguise with partial-reload hazards. A manual config-scope command captures the safe, predictable subset. + +**Declaring `loader` in `inject`.** Rejected: it would make the Loader a hard dependency of the TUI, breaking every Loader-less composition (unit harness, embedders) for a dev convenience. + +**A `cordis_reload` model-facing tool in dsh-tool-cordis.** Rejected: this is an operator action for the human at the terminal, not a capability the model should trigger; the cordis toolset's mount/unmount surface already covers the model's runtime-modification story. + +## Consequences + +- `/reload` appears in the help line, autocomplete (marked EXPERIMENTAL (dev)), and the two help-rendering snapshots (re-recorded). +- The command reports tree count and completion as transcript notices; per-file failures surface only in loader logs, which the TUI does not display — acceptable for a dev-only surface, noted in the completion message. +- A re-entrancy guard serializes reloads: `/reload` while one is in flight is refused with a warning, keeping the loader's unmutexed tree-update pass single-writer; the guard releases on completion or failure. +- `/reload` runs only while the agent is idle: a reload can dispose and re-mount entries, which under an active turn could tear tools or the adapter out from under in-flight calls. The check is advisory (a send can race in after it) but removes the common footgun. +- If any `refresh()` rejects, the command reports the failure instead of leaving an unhandled rejection. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` pins: `/reload` refreshes every file-backed subtree and skips plain entries (structural fake Loader), reports completion, refuses re-entry while a gated refresh is in flight and runs again after release, releases the guard on the failure arm, refuses a running agent and runs again at idle, reports a rejecting refresh, and degrades to a warning without a Loader — including mounted as a real plugin fiber, where a throwing service lookup would escape. Verified live in tmux against the real tree: a probe edit reloads successfully. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.zh.md new file mode 100644 index 0000000000..25d1d44845 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-reload-command.zh.md @@ -0,0 +1,35 @@ +# Agent Note: /reload 命令按需重读 loader 配置 + +Status: implemented + +[English](2026-07-21-tui-reload-command.md) | 中文 + +## Problem + +HMR 的文件监听器只对其配置根目录(示例中即配置叶子所在目录)下的就地 `change` 事件起反应。以重命名方式替换文件的编辑器(BSD `sed -i`、`git checkout`)不产生事件,而没有挂载 HMR 配置项(或没有 `--expose-internals`)的运行时则完全没有配置重载路径。开发时这意味着监听器漏掉一次配置编辑就得重启 TUI。曾考虑把监听根目录扩大到整个仓库,讨论后否决:包之间的密集共享使模块级 HMR 变成「重挂大半棵树」的操作,externals 边界也不可预测。 + +## Decision + +`dsh-tui` 增加一个**实验性、仅供开发**的 `/reload` 斜杠命令:遍历 `ctx.loader.entries()`,对每个文件后端的子树(`Include`)调用 `refresh()`——即 HMR 监听器配置变更分支所走的同一条代码路径,改为手动触发、不依赖监听器。未变化的文件是无操作(`Include.read` 做内容比较)。 + +TUI 以**结构方式**访问 Loader(通过局部类型访问 `ctx.loader`,而非 `inject`):测试和嵌入方在没有 Loader 的情况下运行 TUI,此时 `/reload` 退化为一条警告通知而不是挂载失败。模块源码热重载仍由监听器负责;`/reload` 只刷新配置。 + +## Alternatives considered + +**把 HMR 监听根目录扩大到 `packages/`/`apps/`。** 暂缓否决:插件源码变更会重载每个依赖插件的 fiber,而仓库中密集共享的包(`dsh-session`、`dsh-llm`、`dsh-tools`)使其等同于会话中途拆掉主干和 UI——伪装成热重载的重启,还带部分重载的隐患。手动的、只覆盖配置范围的命令抓住了安全、可预测的那个子集。 + +**在 `inject` 中声明 `loader`。** 否决:那会让 Loader 成为 TUI 的硬依赖,为了一个开发便利破坏所有无 Loader 的组合(单元测试 harness、嵌入方)。 + +**在 dsh-tool-cordis 里做一个面向模型的 `cordis_reload` 工具。** 否决:这是终端前人类操作者的动作,不是模型应当触发的能力;cordis 工具集的 mount/unmount 表面已经覆盖模型的运行时修改需求。 + +## Consequences + +- `/reload` 出现在帮助行、自动补全(标注 EXPERIMENTAL (dev))和两个渲染帮助的快照中(已重新录制)。 +- 命令以 transcript 通知报告树数量与完成;单文件失败只出现在 loader 日志里,TUI 不显示——对仅供开发的表面可以接受,完成消息中已注明。 +- 重入保护串行化重载:前一次进行中时 `/reload` 会被拒绝并提示警告,使 loader 无互斥的树更新过程保持单写者;保护在完成或失败时释放。 +- `/reload` 只在 agent 空闲时运行:重载可能卸载并重新挂载配置项,在活跃轮次下这会把工具或适配器从进行中的调用脚下抽掉。检查是建议性的(检查后仍可能有 send 竞争进来),但消除了常见的坑。 +- 任一 `refresh()` 若 reject,命令会报告失败而不是留下未处理的 rejection。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 固定:`/reload` 刷新每个文件后端子树并跳过普通配置项(结构化的假 Loader)、报告完成、在门控的刷新进行中拒绝重入并在释放后可再次运行、失败分支同样释放保护、拒绝运行中的 agent 并在空闲后可再次运行、报告 reject 的 refresh、无 Loader 时退化为警告——包括作为真实插件 fiber 挂载的情形,在那里会抛出的服务查找会泄露出去。已在 tmux 中对真实配置树实机验证:探针编辑后 reload 成功生效。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.i18n.yaml new file mode 100644 index 0000000000..210215eb3d --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-resume-command.md: 2282eaa9bff83fdb75bdce315d6b17bf8f9ea303 +2026-07-21-tui-resume-command.zh.md: f9d989a5b4e7eb106ff21c5a4fcfa770a5962343 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.md b/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.md new file mode 100644 index 0000000000..2282eaa9bf --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.md @@ -0,0 +1,41 @@ +# Agent Note: Resume command hint and `/resume` + +Status: implemented + +English | [中文](2026-07-21-tui-resume-command.zh.md) + +## Problem + +The TUI can resume a session by launch (`RESUME_SESSION_ID= dsh` feeding `dsh-tui-demo`'s `resumeSessionId`), but nothing told the user the command. On exit the session id survived only in the log and `./.sessions` filenames — the [no-banner Agent Note](2026-07-21-tui-no-banner.md) removed the last place it was shown — so resuming meant hunting for the id and reconstructing the invocation. There was also no in-session way to see which sessions in this workspace are resumable. + +## Decision + +A single optional `resumeCommand` config field on `dsh-tui` gates both surfaces: a shell command template whose every `{session}` is replaced with the live session id (e.g. `dsh --resume {session}`). Absent, neither surface appears. + +- **Exit hint.** Process-exiting shutdown prints `To resume this session: ` (muted label) via `runtime.terminal.write` after `ui.stop()`, before `runtime.exit`. It prints only once the session is durably persisted: `currentResumeCommand()` scans the session list for the current id and returns `undefined` if it is absent, so a session abandoned before its first flush advertises no command that would fail to load. +- **`/resume`.** Lists this workspace's persisted sessions newest-first, each with its resume command, marking the current one `(current)`. It warns when `resumeCommand` is unconfigured or no persistence backend is mounted, and notes when nothing is persisted yet. The listing is asynchronous, so the transcript updates a tick after submit. +- **Listing.** `listWorkspaceSessions()` reads the optional `sessionPersistence` service's `list()`, keeps headers whose `cwd === agent.session.header.cwd`, and sorts by `createdAt` descending. A `list()` rejection is swallowed to `[]` — a persistence failure must never block terminal exit or crash `/resume`. + +`sessionPersistence` is an optional injected service reached through `ctx.get('sessionPersistence')` (not `inject`), declared as an optional peer dependency. Without a backend the field still parses; the exit hint and `/resume` degrade to nothing and the unconfigured/no-backend warnings respectively. `dsh-tui-demo` forwards `resumeCommand` to `dsh-tui`, and the runnable `examples/tui-agent` leaves set `dsh --resume {session}`. The `dsh` CLI (`apps/cli`) parses that `--resume ` flag through `parseResumeArg` in [`dsh-app-boot`](../../../../packages/ui/app-boot/README.md), setting `RESUME_SESSION_ID` before boot so the printed command runs back through the config's existing `resumeSessionId` intake; a mistyped or repeated flag fails loud rather than silently starting fresh. + +## Alternatives considered + +**Hardcode or auto-detect the resume invocation.** Rejected: the launch command is deployment-specific — the env-var name, binary, and flags all vary — so a `DEFAULT_*` constant would be a fixed tunable, not configurability. A template owned by the leaf keeps the choice where the deployment lives, and `{session}` is the only substitution the TUI must know. + +**Two config fields, one per surface.** Rejected: both render the identical command, so one field keeps them symmetric and unable to drift; there is no deployment that wants the hint but not the listing. + +**Print the exit hint unconditionally.** Rejected: resuming a session id that never flushed fails to load, so advertising it is a broken instruction. Gating on the id appearing in `list()` costs one scan and only ever suppresses a dead command. + +**Resume in place from `/resume` (relaunch or reattach).** Rejected: the TUI does not own agent lifecycle or process spawning ([front-door Agent Note](2026-07-17-dedicated-full-screen-tui-front-door.md)). Printing a copyable command respects that boundary and matches the `pi --resume` affordance the request cited. + +**Make `sessionPersistence` a required `inject`.** Rejected: the TUI must run without persistence (fixtures, ephemeral runs). An optional service that degrades preserves that, and matches the [`session-query`](../../../../packages/session-query/session-query/package.json) precedent for the same optional peer. + +## Consequences + +- `dsh-tui` gains an optional peer dependency on `@deepseek-ai/dsh-session-persistence` (`peerDependenciesMeta.optional`), matching `session-query`; the package still loads and passes its coverage gate without a backend mounted. +- The help line and autocomplete gain `/resume`; two existing snapshots re-recorded for the wider help line, and a new `resume-sessions` checkpoint pins the rendered listing. +- `dsh-tui-demo` and both `examples/tui-agent` leaves carry `resumeCommand`, so a real TUI run now prints its own resume command on exit, and the `dsh` CLI accepts the printed `--resume ` flag to run it. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` pins the seven behaviors: the exit hint prints only when the current session is persisted, is omitted when it is not and when `list()` rejects; `/resume` lists workspace sessions newest-first with the `(current)` marker and cwd filter, warns when unconfigured and when no backend is mounted, and notes when nothing is persisted. The `resume-sessions` snapshot verifies the full rendered frame. The harness provides a fake `sessionPersistence` through `ctx.provide`. For the `--resume` flag, `packages/ui/app-boot/tests/app-boot.spec.ts` pins `parseResumeArg` (space and inline forms, position independence, and the fail-loud on a valueless, empty, or repeated flag), and `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` boots `apps/cli` with `--resume ` and asserts the config resume fails loud — proving the flag reaches the `resumeSessionId` intake. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.zh.md new file mode 100644 index 0000000000..f9d989a5b4 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-resume-command.zh.md @@ -0,0 +1,41 @@ +# Agent Note: Resume command hint and `/resume` + +Status: implemented + +[English](2026-07-21-tui-resume-command.md) | 中文 + +## Problem + +TUI 本就能通过启动参数恢复会话(`RESUME_SESSION_ID= dsh` 喂给 `dsh-tui-demo` 的 `resumeSessionId`),但没有任何地方告诉用户这条命令。退出时会话 id 只残留在会话日志和 `./.sessions` 文件名里——[移除启动横幅 Agent Note](2026-07-21-tui-no-banner.md) 移除了它最后一处显示位置——因此恢复意味着先翻出 id 再拼回调用命令。也没有任何会话内的方式查看当前 workspace 里哪些会话可恢复。 + +## Decision + +`dsh-tui` 上一个可选的 `resumeCommand` 配置字段同时管辖两处出口:一个 shell 命令模板,其中每一处 `{session}` 都会被替换为当前会话 id(例如 `dsh --resume {session}`)。未设置时两处都不出现。 + +- **退出提示。** 以退出进程方式关闭时,在 `ui.stop()` 之后、`runtime.exit` 之前,经由 `runtime.terminal.write` 打印 `To resume this session: `(弱化的标签)。仅当会话已持久化时才打印:`currentResumeCommand()` 在会话列表中查找当前 id,若不存在则返回 `undefined`,因此在首次刷盘前就被放弃的会话不会宣传一条注定加载失败的命令。 +- **`/resume`。** 按最新在前列出当前 workspace 里已持久化的会话,每条附带其恢复命令,并给当前会话标注 `(current)`。当 `resumeCommand` 未配置或未挂载持久化后端时给出告警,尚无任何会话被持久化时给出提示。列出是异步的,因此提交后文本记录会在下一个 tick 更新。 +- **列出逻辑。** `listWorkspaceSessions()` 读取可选的 `sessionPersistence` 服务的 `list()`,保留 `cwd === agent.session.header.cwd` 的头部,并按 `createdAt` 降序排序。`list()` 拒绝时吞掉为 `[]`——持久化失败绝不能阻塞终端退出或让 `/resume` 崩溃。 + +`sessionPersistence` 是一个通过 `ctx.get('sessionPersistence')`(而非 `inject`)获取的可选注入服务,声明为可选的对等依赖(peer dependency)。没有后端时该字段仍能解析;退出提示与 `/resume` 分别退化为不做任何事、以及给出未配置/无后端告警。`dsh-tui-demo` 将 `resumeCommand` 转发给 `dsh-tui`,可运行的 `examples/tui-agent` 叶子配置设为 `dsh --resume {session}`。`dsh` CLI(`apps/cli`)通过 [`dsh-app-boot`](../../../../packages/ui/app-boot/README.md) 中的 `parseResumeArg` 解析该 `--resume ` 标志,在启动前设置 `RESUME_SESSION_ID`,因此打印出的命令会重新走回配置中既有的 `resumeSessionId` 入口;拼写错误或重复的标志会直接报错退出,而非悄悄开启一个新会话。 + +## Alternatives considered + +**硬编码或自动探测恢复调用命令。** 否决:启动命令与部署强相关——环境变量名、可执行文件、参数都各不相同——因此一个 `DEFAULT_*` 常量只会是固定的可调项,而非可配置项。由叶子拥有的模板把这个选择留在部署所在之处,而 `{session}` 是 TUI 唯一需要知道的替换。 + +**两个配置字段,每处出口一个。** 否决:两处渲染的是完全相同的命令,因此单个字段让它们保持对称、不会漂移;不存在只想要提示而不想要列表的部署。 + +**无条件打印退出提示。** 否决:恢复一个从未刷盘的会话 id 会加载失败,宣传它就是一条错误指令。以 id 是否出现在 `list()` 中为条件仅需一次扫描,且只会抑制一条注定失败的命令。 + +**从 `/resume` 就地恢复(重启或重连)。** 否决:TUI 不拥有 agent 生命周期或进程创建([全屏 TUI 门面 Agent Note](2026-07-17-dedicated-full-screen-tui-front-door.md))。打印一条可复制的命令尊重这条边界,也契合需求所引用的 `pi --resume` 用法。 + +**把 `sessionPersistence` 设为必需的 `inject`。** 否决:TUI 必须能在无持久化时运行(fixture(测试前置数据)、临时运行)。一个会优雅退化的可选服务保住了这一点,也与 [`session-query`](../../../../packages/session-query/session-query/package.json) 对同一可选对等依赖的先例一致。 + +## Consequences + +- `dsh-tui` 新增对 `@deepseek-ai/dsh-session-persistence` 的可选对等依赖(`peerDependenciesMeta.optional`),与 `session-query` 一致;未挂载后端时该包仍能加载并通过其覆盖率门禁。 +- 帮助行和自动补全新增 `/resume`;两个既有快照因帮助行变宽而重新录制,新增的 `resume-sessions` 检查点固定渲染出的列表。 +- `dsh-tui-demo` 及两个 `examples/tui-agent` 叶子配置都带上 `resumeCommand`,因此真实的 TUI 运行现在退出时会打印自己的恢复命令,且 `dsh` CLI 接受打印出的 `--resume ` 标志来运行它。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 固定这七种行为:退出提示仅在当前会话已持久化时打印,未持久化时以及 `list()` 拒绝时都不打印;`/resume` 按最新在前列出 workspace 会话并带 `(current)` 标注与 cwd 过滤、未配置时告警、无后端时告警、尚无持久化时给出提示。`resume-sessions` 快照验证完整渲染帧。测试脚手架通过 `ctx.provide` 提供一个假的 `sessionPersistence`。对于 `--resume` 标志,`packages/ui/app-boot/tests/app-boot.spec.ts` 固定 `parseResumeArg`(空格形式与内联形式、位置无关性,以及在标志缺值、为空或重复时直接报错退出),`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 用 `--resume ` 启动 `apps/cli` 并断言配置恢复直接报错退出——证明该标志抵达了 `resumeSessionId` 入口。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.i18n.yaml new file mode 100644 index 0000000000..40dd8f463e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-skill-slash-command.md: d7532a05fce5605491ce42c87a2a523eb4c19acc +2026-07-21-tui-skill-slash-command.zh.md: 16930020bd404f7bc9476169cd1d063aa57b5c94 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.md b/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.md new file mode 100644 index 0000000000..d7532a05fc --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.md @@ -0,0 +1,33 @@ +# Agent Note: TUI skill slash command + +Status: implemented + +English | [中文](2026-07-21-tui-skill-slash-command.zh.md) + +## Problem + +The [skill system](2026-07-05-skill-system.md) shipped with model-initiated loading as its only path: the `skill({ name })` tool lets the model pull a skill body into a turn, but a person driving the TUI could not load a skill on demand. Other coding agents expose a `/skill:` slash command for exactly this — the user, not the model, decides a task matches a skill and injects its instructions. The skill-system note listed direct user invocation as deferred work, and the interactive front door is where it belongs. + +## Decision + +The [`@deepseek-ai/dsh-tui`](../../../../packages/ui/tui/README.md) front door owns a `/skill: [instructions]` command. On submit it loads the named skill and delivers one text block as a user turn — sent with `agent.send()` while idle and `agent.steer()` while running, the same rule as ordinary editor input. The block is `renderSkillInvocation(skill, instructions)`: a `` element wrapping the skill body, preceded by one resource-base line when the provider exposes one, with the user's trailing text appended after a blank line. The command is a TUI-only affordance; it adds no model-facing tool and changes no skill-system package contract. + +The TUI reads the skill service through `ctx.get('skills')`, not a declared injection, because skills mount conditionally: a deployment without the registry keeps a working front door, and `/skill:` there reports that skills are unavailable rather than failing to mount. `createTuiChat` is synchronous while `ctx.skills.list()` is async, so autocomplete seeds the static slash commands immediately and rebuilds the provider with `skill:` entries once the catalog resolves; a resolution that arrives after disposal is dropped, and a rejected lookup keeps the base commands. + +Autocomplete lists only model-invocable skills — it is built from `list()`, which omits `disableModelInvocation` skills — while manual submission resolves through `get()`, which the skill registry documents as the trusted-caller path that returns disabled skills too. So a person can load any skill by typing its exact name, but the completion menu never advertises a skill the model is meant not to see. An unknown name, an empty name after the prefix, and a lookup failure each surface as a transcript notice without sending anything. + +`renderSkillInvocation` and the resource-base line are the TUI's own, deliberately not reused from `dsh-tool-skill`'s `skill` tool result. The tool wraps a body in ``/``/`` for a *tool result*; a manual invocation is a *user turn*, and coupling the two renderers would force one model-facing shape to serve both surfaces. The cost is two renderers that both format a skill body; the benefit is that each surface's model-facing text evolves independently, and each is pinned where it is produced. + +## Alternatives considered + +**Add a `user-invocable` frontmatter field and enforce it in the registry.** Rejected for this change. The skill-system note defers that field, and manual invocation does not need it: the TUI is a trusted local caller, so `get()` already authorizes loading any skill, and autocomplete visibility keys off the existing `disableModelInvocation`. A new per-skill field would add a contract to the registry, local provider, and tool with no current consumer beyond visibility, which `disableModelInvocation` already covers. + +**Declare `skills` as a TUI injection.** Rejected because skills mount conditionally; a declared injection would make the front door require the registry and refuse to mount without it, contradicting the package's optional-service stance. `ctx.get('skills')` reads the global store and tolerates absence. + +**Reuse `dsh-tool-skill`'s renderer.** Rejected because its output is a tool-result shape (`` and siblings) written for the model's tool channel, while a slash invocation is a user message. Sharing it would either leak tool-result vocabulary into a user turn or fork the shared renderer on a `surface` flag — more coupling than two small formatters. + +**Route submissions through the model's `skill` tool.** Rejected because the user has already decided; a tool call would spend a model round-trip to fetch a body the front door can load directly, and would not work while the agent is mid-turn. + +## Consequences + +Manual invocation always reloads the full skill body: the TUI does not detect a skill already present in the conversation, so a repeated `/skill:` appends its instructions again — acceptable because re-injection is sometimes the intent, and documented under the package README's Known Limitations. The two-renderer duplication is a standing maintenance cost accepted above. The `` wrapper is stable model-visible text and is pinned verbatim in unit tests against a real `SkillService`; the help-panel line is pinned by the `errors-and-help` terminal snapshot. Autocomplete population and the disposed-lookup and failed-lookup branches are covered by unit tests that mount the real registry or a controllable service. End-to-end delivery is proven by a dedicated real-composition test: the `examples/tui-agent` keyless PTY smoke (`tui-keyless-smoke.e2e.ts`) boots the production TUI/agent/skill stack through the Loader under a genuine pseudo-terminal with only the model scripted, drops a fixture skill under the agents-home `skills/` root, types `/skill:` as live keystrokes, and asserts the scripted adapter echoes the fixture's body marker only when the rendered `` block arrives — exercising `ctx.get('skills')` resolution in the shipped tree, the client-side parse, the local provider load, and the user turn reaching the model together. That fixture's frontmatter description avoids a `: ` colon-space so its YAML stays a plain scalar; an invalid-frontmatter skill is silently dropped during discovery. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.zh.md new file mode 100644 index 0000000000..16930020bd --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-skill-slash-command.zh.md @@ -0,0 +1,33 @@ +# Agent Note: TUI skill slash command + +Status: implemented + +[English](2026-07-21-tui-skill-slash-command.md) | 中文 + +## Problem + +[skill 系统](2026-07-05-skill-system.md)交付时只有模型发起加载这一条路径:`skill({ name })` 工具让模型把某个 skill 正文拉进一个轮次,但操作 TUI 的人无法按需加载 skill。其他编码 agent(智能体)正是为此提供了 `/skill:` 斜杠命令——由用户而非模型判断某个任务与某个 skill 匹配,并注入其指令。skill 系统 note 把直接的用户发起调用列为待办工作,而交互式前门正是它该落地的地方。 + +## Decision + +[`@deepseek-ai/dsh-tui`](../../../../packages/ui/tui/README.md) 前门拥有一条 `/skill: [instructions]` 命令。提交时它加载指定的 skill,并投递一个文本块作为用户轮次——空闲时用 `agent.send()` 发送、运行中用 `agent.steer()` 中途引导,与普通编辑器输入遵循同一规则。该文本块由 `renderSkillInvocation(skill, instructions)` 生成:一个包裹 skill 正文的 `` 元素,当提供方暴露资源基址时在其前加一行资源基址行,用户尾随的文本在空行之后追加。该命令是 TUI 独有的能力;它不新增任何面向模型的工具,也不改动任何 skill 系统包的契约。 + +TUI 通过 `ctx.get('skills')` 读取 skill 服务,而非声明式注入,因为 skill 是条件挂载的:没有注册表的部署仍保有可用的前门,此时 `/skill:` 会报告 skill 不可用,而不是挂载失败。`createTuiChat` 是同步的,而 `ctx.skills.list()` 是异步的,所以自动补全先立即种入静态斜杠命令,待目录解析完成后再用 `skill:` 条目重建 provider(提供方);在 dispose(资源释放)之后才到达的解析结果会被丢弃,而被拒绝的查找会保留基础命令。 + +自动补全只列出模型可调用的 skill——它基于 `list()` 构建,而 `list()` 会略去 `disableModelInvocation` 的 skill——手动提交则通过 `get()` 解析,skill 注册表将其记录为返回被禁用 skill 的可信调用方路径。因此用户可以通过键入 skill 的确切名称加载任意 skill,但补全菜单绝不会宣传一个本不该让模型看见的 skill。未知名称、前缀之后为空的名称、以及查找失败,都会各自呈现为 transcript(文本记录)中的一条通知,且不发送任何内容。 + +`renderSkillInvocation` 及资源基址行是 TUI 自有的,刻意不复用 `dsh-tool-skill` 的 `skill` 工具结果。该工具把正文包进 ``/``/`` 是为了一个*工具结果*;而手动调用是一个*用户轮次*,把两个渲染器耦合起来会迫使一种面向模型的形态同时服务两个界面。代价是两个都在格式化 skill 正文的渲染器;收益是各界面面向模型的文本可以独立演进,且各自在其产出处被固定。 + +## Alternatives considered + +**新增 `user-invocable` frontmatter 字段并在注册表中强制执行。** 本次改动否决。skill 系统 note 把该字段列为待办,而手动调用并不需要它:TUI 是可信的本地调用方,`get()` 已经授权加载任意 skill,自动补全的可见性以既有的 `disableModelInvocation` 为准。新增一个逐 skill 字段会给注册表、本地提供方和工具都加上一条契约,而除了可见性之外没有任何现有消费方,可见性又已由 `disableModelInvocation` 覆盖。 + +**把 `skills` 声明为 TUI 注入。** 否决,因为 skill 是条件挂载的;声明式注入会使前门必须依赖注册表,缺少它就拒绝挂载,与本包可选服务的立场相悖。`ctx.get('skills')` 读取全局存储并容忍其缺失。 + +**复用 `dsh-tool-skill` 的渲染器。** 否决,因为它的输出是为模型的工具通道所写的工具结果形态(`` 及其同类),而斜杠调用是一条用户消息。共用它要么把工具结果词汇泄漏进用户轮次,要么按 `surface` 标志分叉共享渲染器——比两个小格式化器耦合更重。 + +**让提交经由模型的 `skill` 工具。** 否决,因为用户已经作出了判断;一次工具调用会花掉一个模型往返去取一份前门可以直接加载的正文,而且在 agent 处于轮次中途时也无法工作。 + +## Consequences + +手动调用总是重新加载完整的 skill 正文:TUI 不会检测某个 skill 是否已在对话中出现,因此重复的 `/skill:` 会再次追加其指令——这可以接受,因为重新注入有时正是意图所在,且已在本包 README 的已知限制中说明。上文接受的双渲染器重复是一项长期维护成本。`` 包裹是稳定的、模型可见的文本,并在单元测试中针对一个真实的 `SkillService` 逐字固定;帮助面板那一行由 `errors-and-help` 终端快照固定。自动补全的填充、dispose 后查找分支、以及查找失败分支,都由挂载真实注册表或可控服务的单元测试覆盖。端到端的投递由一项专门的真实组合测试证明:`examples/tui-agent` 的无密钥 PTY 冒烟测试(`tui-keyless-smoke.e2e.ts`)在真实伪终端下经由 loader 引导生产环境的 TUI/agent/skill 栈,仅对模型进行脚本化,把一个夹具 skill 放入 agents home 的 `skills/` 根下,以真实按键输入 `/skill:`,并断言:只有当渲染出的 `` 文本块抵达时,脚本化适配器才会回显该夹具的正文标记——从而一并演练了 `ctx.get('skills')` 在发布树中的解析、客户端解析、本地 provider 的加载,以及用户回合抵达模型。该夹具的 frontmatter 描述避免出现 `: ` 冒号加空格,使其 YAML 保持为纯标量;frontmatter 无效的 skill 会在发现阶段被静默丢弃。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.i18n.yaml new file mode 100644 index 0000000000..ddf4792769 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-steering-queue-badge.md: b29a4667e778e65b0678f946fcaa34b79c4d7da0 +2026-07-21-tui-steering-queue-badge.zh.md: 4bfce461e11bce1773d6e0b15aabecf6a6a6144c diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.md b/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.md new file mode 100644 index 0000000000..b29a4667e7 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.md @@ -0,0 +1,39 @@ +# Agent Note: TUI status line badges queued steering messages + +Status: implemented + +English | [中文](2026-07-21-tui-steering-queue-badge.zh.md) + +## Problem + +While a turn runs, an editor submission calls `agent.steer()` and joins the steering queue behind the running turn ([front-door Agent Note](2026-07-17-dedicated-full-screen-tui-front-door.md)). The running status line ended only with the `Enter sends steering, Esc cancels` hint, so pressing Enter gave no feedback that the message landed or how many were waiting to reach the model. A user steering several times could not tell the queue from a dropped keystroke. + +## Decision + +The agent's inbox is the authoritative steering queue but is not observable from the TUI, so the badge is a live count reconstructed from the public `agent/queued` and `steering/message` events rather than a projection of the queue itself. + +- The running status line composes through `formatTurnStatus`, which inserts a `${queued} queued · ` badge before the `Enter sends steering, Esc cancels` hint when `queued > 0` and shows the plain hint at zero; the phase label and elapsed timing before it are the [verbose status line](2026-07-21-tui-verbose-status-line.md)'s. +- `createTuiChat` owns a `pendingSteering` counter: `+1` on each `agent/queued` for this agent whose `info.steering` is set, `-1` (floored at zero) on each `steering/message` session event as the loop drains one, and reset to zero whenever the agent leaves `running`. +- The count refreshes onto the live `Loader` through `setMessage`; the refresh is a no-op while idle because the loader exists only during a running turn. +- The reset lives in the `agent/status` transition, not in `setStatus`, because `setStatus` also runs on mid-turn palette changes and must not clear a live count. + +## Alternatives considered + +**Derive the count from the session log alone** (enqueued minus drained, recomputed on replay). Rejected: a cancellation clears the inbox without logging a drain, so the log cannot distinguish a drained message from a discarded one; the reset-on-non-running anchor is simpler and self-correcting each turn. + +**Reset inside `setStatus`.** Rejected: `setStatus` re-runs on `applyColorScheme` mid-turn, which would wrongly zero a live count; the status transition is the only place a turn actually ends. + +**Drop the decrement clamp.** Rejected: loop-authored steering (e.g. continuation reasons) logs `steering/message` with no matching user-queued increment, which would drive the count negative; the zero floor keeps the badge a lower bound rather than a lie. + +**Make the wording or a threshold configurable.** Rejected: the no-hardcoded-tunables rule targets deployment-varying behavior, not brand copy; the `welcome`/hint strings are already fixed presentation. + +## Consequences + +- The badge is best-effort live UI state, not a logged surface: it is rebuilt from events and reset each turn, never persisted, so a resumed running turn starts its badge from zero. +- A cancellation mid-queue clears the badge cleanly through the non-running reset, and a drain past zero is a no-op — neither can strand a stale count. +- A loop continuation that keeps the agent `running` while re-enqueuing undrained late steering can transiently over-count until the next idle reset; the badge is advisory, so the window is acceptable. +- `packages/ui/tui/src/index.ts` stays at 100 % per-file coverage. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` drives the running status frame through the real `createTuiChat`: the plain hint at zero, a foreign-agent queue ignored, the increment to `2 queued`, a non-steering queue left untouched, the decrement as each message drains, the clamp on a drain past zero, and the reset when the turn ends. Verified live in tmux — the badge showed `3 queued` after three `agent.steer()` calls, then `1 queued` as two drained. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.zh.md new file mode 100644 index 0000000000..4bfce461e1 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-steering-queue-badge.zh.md @@ -0,0 +1,39 @@ +# Agent Note: TUI 状态行标示排队中的 steering 消息 + +Status: implemented + +[English](2026-07-21-tui-steering-queue-badge.md) | 中文 + +## Problem + +轮次运行期间,编辑器提交会调用 `agent.steer()`,在运行中的轮次后面加入 steering(中途引导)队列([前门 Agent Note](2026-07-17-dedicated-full-screen-tui-front-door.md))。运行时的状态行只以 `Enter sends steering, Esc cancels` 提示收尾,因此按下 Enter 后没有任何反馈表明消息已入队、也看不出有多少条正在等待送达模型。连续 steering 多次的用户无法把队列和被吞掉的按键区分开。 + +## Decision + +agent(智能体)的收件箱(inbox)才是权威的 steering 队列,但 TUI 无法观测它,因此徽标是从公开的 `agent/queued` 与 `steering/message` 事件重建出的实时计数,而非对队列本身的投影。 + +- 运行时的状态行经 `formatTurnStatus` 组装:`queued > 0` 时在 `Enter sends steering, Esc cancels` 提示前插入 `${queued} queued · ` 徽标,为零时是纯提示文本;其前的阶段标签与耗时归[详细状态行](2026-07-21-tui-verbose-status-line.md)所有。 +- `createTuiChat` 持有一个 `pendingSteering` 计数器:每收到一个针对本 agent 且 `info.steering` 为真的 `agent/queued` 就 `+1`,agent loop(智能体循环)每排空一条时随对应的 `steering/message` 会话事件 `-1`(下限为零),agent 一旦离开 `running` 状态即重置为零。 +- 计数通过 `setMessage` 刷新到实时的 `Loader` 上;空闲时刷新是空操作,因为 loader 只在运行中的轮次期间存在。 +- 重置放在 `agent/status` 状态切换里,而非 `setStatus` 中,因为 `setStatus` 在轮次中途的颜色方案变化时也会运行,绝不能清掉一个实时计数。 + +## Alternatives considered + +**仅从会话日志推导计数**(入队数减去排空数,回放时重算)。否决:取消会清空 inbox 而不记录排空,因此日志无法区分一条消息是被排空还是被丢弃;「离开运行态即重置」这个锚点更简单,且每轮自我校正。 + +**在 `setStatus` 内重置。** 否决:`setStatus` 会在轮次中途的 `applyColorScheme` 时重新运行,会错误地把实时计数清零;状态切换才是轮次真正结束的唯一位置。 + +**去掉递减的下限钳制。** 否决:agent loop 自行产生的 steering(如 continuation 续跑原因)会记录 `steering/message`,却没有对应的用户入队递增,这会把计数压到负数;零下限让徽标成为下界,而非谎报。 + +**把措辞或某个阈值做成配置。** 否决:「插件里不许硬编码可调参数」规则针对的是随部署变化的行为,不是品牌文案;`welcome`/提示字符串本就是固定的展示文案。 + +## Consequences + +- 徽标是尽力而为的实时 UI 状态,不写入日志:它由事件重建、每轮重置、从不持久化,因此恢复(resume)出的运行中轮次徽标从零开始。 +- 队列中途取消会经由「离开运行态即重置」干净地清掉徽标,排空到零以下则是空操作——两者都不会残留一个陈旧计数。 +- 如果 agent loop 续跑时让 agent 保持 `running`、同时把未排空的迟到 steering 重新入队,则可能短暂多计,直到下一次空闲重置;徽标只作参考,因此这个窗口可以接受。 +- `packages/ui/tui/src/index.ts` 保持 100% 的单文件覆盖率。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 通过真实的 `createTuiChat` 驱动运行时状态帧:为零时的纯提示、忽略他方 agent 的入队、递增到 `2 queued`、非 steering 的入队保持不变、每条消息排空时的递减、排空到零以下时的钳制、以及轮次结束时的重置。已在 tmux 中实机验证——三次 `agent.steer()` 调用后徽标显示 `3 queued`,随后两条排空时显示 `1 queued`。 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.i18n.yaml b/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.i18n.yaml new file mode 100644 index 0000000000..319f28ea61 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-verbose-status-line.md: f277afd3a874b30a29dc0ef193740f636d22290b +2026-07-21-tui-verbose-status-line.zh.md: 9fa7cf29c67245382bbee6b72f2710c5550d7f54 diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.md b/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.md new file mode 100644 index 0000000000..f277afd3a8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.md @@ -0,0 +1,36 @@ +# Agent Note: The running status line shows the turn phase and elapsed time + +Status: implemented + +English | [中文](2026-07-21-tui-verbose-status-line.zh.md) + +## Problem + +While a turn ran, the [full-screen TUI](2026-07-17-dedicated-full-screen-tui-front-door.md) showed a single static "Working" spinner. It conveyed neither how long the current step had taken nor what the agent was doing — waiting on the model, thinking, streaming a response, or running tools — so a slow or stalled turn was indistinguishable from a fast one. + +## Decision + +- While a turn runs, the status line above the editor shows a derived phase label with elapsed time, keeping the trailing `— Enter sends steering, Esc cancels` hint. The four phases and their labels are `waiting` → "Waiting for the first token", `thinking` → "Thinking", `responding` → "Responding", and `executing` → "Executing tools". +- The phase is presentation state the TUI derives from live session events, not a session event or agent status of its own. `step/start` enters `waiting`; an `assistant/chunk` reasoning delta or reasoning block-start enters `thinking`; a text delta or text block-start enters `responding`; a `tool/call` enters `executing`. The event map is merge-extensible, so every other event kind falls through a default and leaves the phase unchanged. +- The label reports two clocks — ` · total ` — except `waiting`, which shows only the step total. The phase clock resets on a genuine phase change or a new step; the step clock resets on `step/start`. Durations format as `8s` below a minute and `1m05s` at or above one. Tool time between `step/end` and the next `step/start` accrues to the finishing step's total. +- A single `RunningStatus` controller — the loader, the phase, the two baselines, and a refresh timer — exists only while a turn runs. A one-second `setInterval` refreshes the elapsed time; a phase event refreshes it immediately. `clearStatus` clears the interval, stops the loader, and drops the controller, so any transition to idle or disposed leaves no live timer, matching the [banner sweep](2026-07-21-tui-banner-sweep.md)'s timer hygiene. A mid-turn palette rebuild (`setStatus` re-derives the editor border on a terminal color-scheme change) carries the phase and both baselines across, so a running status never snaps back to `waiting`. + +## Alternatives considered + +**Emit the phase as a session event or agent status.** Rejected: the phase is a presentation detail the TUI reconstructs from events already logged. A durable, model-visible phase would demand a new session event under the model-visible ⟺ logged rule, for no model benefit. + +**Reuse pi-tui's `Loader` animation timer to refresh the elapsed text.** Not available: the vendored `Loader` animates only its spinner glyph, and its dist is not ours to change. The TUI owns a separate one-second interval, cleared on teardown. + +**Infer the phase from tool-drain or streaming-component state.** Rejected: the `step/start`, `assistant/chunk`, and `tool/call` lifecycle events are cleaner signals, already handled in the same live listener, and avoid coupling the status line to other components. + +**Show only elapsed time, or only the phase.** Rejected: both are wanted — the per-phase time answers what the agent is doing, the per-step total answers how long the step has taken. + +## Consequences + +- The status line reads, for example, `Thinking 4s · total 8s — Enter sends steering, Esc cancels`, so the agent's current activity and step duration are legible and a stall is visible. +- Phase detection is best-effort presentation: an unhandled future chunk or event kind leaves the last phase in place and never throws. +- Exactly one `setInterval` runs per active turn, cleared with the controller on every idle or disposed transition and on shutdown. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` pins each phase label against its triggering event (`step/start`, reasoning and text deltas and block-starts, `tool/call`), that a new step reopens the wait window, that the elapsed time advances on the controller's own timer past one second, that a step beyond a minute renders `1m…`, that a mid-turn color-scheme change preserves the phase and elapsed time, and that a live event arriving before the turn runs moves no status. Verified live in tmux. diff --git a/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.zh.md b/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.zh.md new file mode 100644 index 0000000000..9fa7cf29c6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-21-tui-verbose-status-line.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 运行状态行展示轮次阶段与已用时长 + +Status: implemented + +[English](2026-07-21-tui-verbose-status-line.md) | 中文 + +## 问题 + +在轮次运行期间,[全屏 TUI](2026-07-17-dedicated-full-screen-tui-front-door.md) 只显示一个静态的 "Working" loader 动画。它既不表明当前步骤已耗时多久,也不表明 agent(智能体)正在做什么——等待模型、思考、流式输出回复,还是运行工具——因此运行缓慢或卡住的轮次与运行很快的轮次无从区分。 + +## 决策 + +- 轮次运行期间,编辑器上方的状态行显示一个派生的阶段标签及已用时长,并保留末尾的 `— Enter sends steering, Esc cancels` 提示。四个阶段及其标签为 `waiting` → "Waiting for the first token"、`thinking` → "Thinking"、`responding` → "Responding"、`executing` → "Executing tools"。 +- 阶段是 TUI 从实时会话事件派生出的呈现状态,而非它自有的会话事件或 agent 状态。`step/start` 进入 `waiting`;`assistant/chunk` 的 reasoning 分片或 reasoning 块开始(`block-start`)进入 `thinking`;text 分片或 text 块开始进入 `responding`;`tool/call` 进入 `executing`。该事件映射可合并扩展,因此其余任何事件类型都落入默认分支,保持阶段不变。 +- 标签汇报两个时钟——` · total `——但 `waiting` 只显示步骤总时长。阶段时钟在真正发生阶段切换或进入新步骤时重置;步骤时钟在 `step/start` 时重置。时长在不足一分钟时格式化为 `8s`,达到或超过一分钟时格式化为 `1m05s`。`step/end` 与下一个 `step/start` 之间的工具时间计入结束步骤的总时长。 +- 单一的 `RunningStatus` 控制器——loader、阶段、两个基准时刻以及一个刷新定时器——仅在轮次运行期间存在。一个每秒触发的 `setInterval` 刷新已用时长;阶段事件则立即刷新。`clearStatus` 清除该 interval、停止 loader 并丢弃控制器,因此任何向 idle 或 disposed 的转变都不会遗留活动定时器,与 [banner 扫入动画](2026-07-21-tui-banner-sweep.md)的定时器清理保持一致。轮次进行中的调色板重建(终端颜色方案变化时 `setStatus` 会重新派生编辑器边框)会将阶段与两个基准时刻一并沿用过来,因此运行中的状态绝不会退回 `waiting`。 + +## 曾考虑的替代方案 + +**将阶段作为会话事件或 agent 状态发出。** 已否决:阶段是 TUI 从已记录事件重建出的呈现细节。一个持久、模型可见的阶段会依据 model-visible ⟺ logged 规则要求新增一个会话事件,而对模型没有任何好处。 + +**复用 pi-tui 的 `Loader` 动画定时器来刷新已用时长文本。** 不可行:`Loader` 是 vendored 依赖,只驱动其加载动画字形,其 dist 不归我们改动。TUI 自持一个独立的每秒 interval,并在拆卸时清除。 + +**从工具耗尽或流式组件状态推断阶段。** 已否决:`step/start`、`assistant/chunk` 和 `tool/call` 这些生命周期事件是更干净的信号,已在同一个实时监听器中处理,且避免让状态行与其他组件耦合。 + +**只显示已用时长,或只显示阶段。** 已否决:两者都需要——按阶段的时长回答 agent 在做什么,按步骤的总时长回答该步骤已耗时多久。 + +## 后果 + +- 状态行例如显示 `Thinking 4s · total 8s — Enter sends steering, Esc cancels`,从而 agent 的当前活动与步骤时长一目了然,卡顿也随之可见。 +- 阶段检测是尽力而为的呈现:未处理的未来分片或事件类型会保持上一个阶段不变,绝不抛错。 +- 每个活动轮次恰好运行一个 `setInterval`,在每次向 idle 或 disposed 的转变以及关停时随控制器一并清除。 + +## 测试 + +`packages/ui/tui/tests/tui.spec.ts` 针对触发事件锁定每个阶段标签(`step/start`、reasoning 与 text 的分片及块开始、`tool/call`),并锁定新步骤会重新开启等待窗口、已用时长在控制器自有定时器上超过一秒后递增、超过一分钟的步骤渲染为 `1m…`、轮次进行中的颜色方案变化会保留阶段与已用时长,以及轮次开始前到达的实时事件不移动任何状态。已在 tmux 中实机验证。 diff --git a/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md b/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md index 65ad437ca9..fef5852153 100644 --- a/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md +++ b/.agents/notes/implemented/process/2026-07-06-parallel-github-ci-gates.md @@ -4,36 +4,45 @@ Status: implemented ## Problem -The keyless GitHub CI gates are mostly orthogonal: typecheck, lint, documentation freshness, coverage, snapshot replay, build, package-publication hygiene, demo smoke, and built-bin smoke fail for different reasons and do not need each other's runtime state. Running them as one ordered command chain makes the workflow wall clock equal the sum of those gates, while splitting every leaf gate into its own GitHub job repeats checkout, Node setup, pnpm restore, and install work until orchestration overhead becomes the bottleneck. +The keyless GitHub CI gates are mostly orthogonal: typecheck, lint, documentation freshness, coverage, snapshot replay, build, package-publication hygiene, demo smoke, and built-bin smoke fail for different reasons and do not need each other's runtime state. Running them as one ordered command chain makes the workflow wall clock equal the sum of those gates, while splitting every short leaf into its own GitHub job repeats checkout, Node setup, pnpm restore, and install work until orchestration overhead becomes the bottleneck. -The hard part is the artifact boundary. `publint`, `verify-node-next-types`, and built-bin smoke tests need the built `lib/` outputs, while most gates only need source and dependencies. A blind fan-out either races those artifact consumers before `pnpm run build` has emitted declarations and bundles, or repeats the build in every artifact-dependent job. +The original broad-lane split stopped meeting that balance as the workspace grew. On the merge of PR #404, Linux static, coverage, snapshot, and artifact jobs took 148, 195, 94, and 230 seconds; Windows static and artifacts took 251 and 482 seconds. Package-manager packing once per package dominated both artifact validators, coverage needlessly rebuilt output before a source-only suite, and CPU-heavy gates contended inside the static and coverage lanes. + +The artifact boundary remains load-bearing. `publint`, `verify-node-next-types`, compiled invariant loading, and built-bin smoke tests need emitted `lib/` output. Sharding cannot race those consumers ahead of build or replace their published-artifact signal with source execution. ## Decision -[CI](../../../../.github/workflows/ci.yml) groups keyless checks into broad primary-runtime lanes plus a compatibility matrix. The workflow file owns the current lane and runtime inventory. +The production topology below is historical and is superseded by [Evidence-based larger hosted runners](2026-07-22-evidence-based-larger-hosted-runners.md). The larger-runner decision removes its shard selectors and workflow jobs; this note preserves why that earlier topology was implemented. -Each lane delegates to [scripts/run-gates.ts](../../../../scripts/run-gates.ts), which schedules independent gates with bounded concurrency and prints an attributable result block for each one. Artifact consumers depend on one build within their lane, while compatibility jobs combine typechecking with a real unbuilt worker launch to cover runtime-specific loader behavior. +[CI](../../../../.github/workflows/ci.yml) treats one minute for non-Windows jobs and three minutes for Windows jobs as observed performance targets, not cancellation deadlines. Hosted-runner variance should leave complete timing evidence and useful failure logs instead of cancelling an otherwise-correct gate. The [serial cross-platform CI reference](2026-07-21-serial-cross-platform-ci-reference.md) independently runs the complete unsharded primary Node aggregate on Linux, macOS, and Windows so the optimized lane inventory is not its own completeness oracle. -Generated `.sessions/` logs and `.doc-typecheck-*` temp directories are ignored by lint. The aggregate local CI mode still runs demo smoke after lint, while the split GitHub static lane can run demo smoke directly because lint is isolated in its own lane. +In that topology, [scripts/run-gates.ts](../../../../scripts/run-gates.ts) was the common bounded scheduler and GitHub supplied explicit shard names for the expensive gate families. `scripts/static-shards.ts` partitioned static gates into foundation, documentation-type, API-contract, catalog, prose, documentation-projection, and documentation-build ownership and rejected a missing or duplicate gate assignment. Linux lint used disjoint A-C, D-M, N-S, and T-Z package-source and package-test lanes, while Windows used complete package-source and package-test lanes; both included a repository complement starting from `.` so new top-level targets could not disappear between shards and owned the single cross-file duplication run. `scripts/coverage-shards.ts` assigned every workspace package to exactly one source-coverage lane. Directory filters retained a trailing separator because Vitest positional filters match substrings and would otherwise admit prefix-named siblings. Each coverage lane included only its owned source files, repeated the exhaustive companion topology test, and ran without a preceding build because the complete coverage suite passes from a tree with every generated `lib/` removed. -Build output is produced once inside the Node 24 artifact lane. The artifact consumers (`publint`, `verify-node-next-types`, and built-bin smoke) declare a dependency on `build`, so there is no upload/download handoff and no consumer can race ahead of declarations or bundles. The CI coverage reporter is text-only while local coverage keeps the HTML report. +Snapshot replay used two explicit multi-file lanes and eight scenario partitions of the large ACP file. `scripts/snapshot-shards.ts` owned that inventory, and its test discovered every file admitted by the snapshot config. Each snapshot job installed dependencies while its Linux runner prepared Bubblewrap, built the shipped runtime, and ran only its assigned replay surface. The suite retained bounded concurrency of five subprocesses because replay spent most of its time waiting on child protocol I/O. Fixture guards still inspected the complete ACP scenario table in every partition. -Both workflows cache the pnpm store. The real-API workflow uses the shared bounded Vitest file pool rather than a separate job per test group. +Cold standalone documentation typechecking rebuilds the complete project-reference graph, so a dedicated documentation-type lane builds once and checks Markdown blocks against those declarations. The Linux documentation lane uses VitePress's MPA build to retain page rendering and dead-link validation within the observed non-Windows target; separate blocking Windows build and production-site lanes preserve the emitted-package and shipped-site checks without putting both critical paths in one job. + +Artifacts use two lanes: one metadata lane for `publint`, NodeNext declarations, and compiled invariant loading, plus one built-bin smoke lane. Each lane produces its own build before its consumers. Repeating the short build costs runner minutes but avoids an upload/download dependency and keeps each job's critical path bounded. + +[scripts/publint-all.ts](../../../../scripts/publint-all.ts) calls publint's supported API in-process against an in-memory publication view made from each manifest's declared files and npm's mandatory metadata files. This preserves the distinction between workspace files and published files without spawning a package-manager pack command 103 times. [scripts/verify-built-package-invariants.mjs](../../../../scripts/verify-built-package-invariants.mjs) stages those structurally validated manifest-declared `lib/` files below the real package, then imports the compiled self-reference through plain Node and Cordis Loader normalization. A companion that reaches an undeclared runtime chunk still fails. + +Compatibility lanes run the source worker and Zstandard runtime smokes on every advertised Node line. TypeScript checks the source graph once in a dedicated primary Node 24 lane; repeating the same compiler analysis in runtime compatibility jobs added time without runtime-specific signal. + +The workflow caches the pnpm store, keys each immutable ESLint cache to its owning lint shard, preserves native PowerShell for Windows measurements, and retains one aggregate `all checks passed` status for branch protection. Windows reuses the three exhaustive lint partitions and groups foundation/catalog/prose plus documentation-type/API-contract gates behind shared runner setups; only scheduling differs from the Linux partitions. Windows build and production-site validation remain blocking, while the wider Windows static, lint, and artifact matrix remains observational. ## Alternatives considered -- **Keep the full serial chain in a Node matrix** - simplest to reason about, but it duplicates repo-wide gates that do not produce Node-version-specific signal and leaves every PR waiting for the sum of all gates. -- **Run every gate as a separate GitHub job** - maximizes GitHub-visible fan-out, but it creates too many checks and pays repeated setup/install overhead for gates whose runtime is shorter than the runner preparation. -- **Upload build artifacts to artifact-dependent jobs** - preserves correctness across many jobs, but it adds artifact upload/download time and keeps the workflow wide when the artifact consumers can run behind a local dependency in the primary job. -- **Run `typecheck` and `build` concurrently** - exposes more work to the scheduler, but both commands invoke `tsc -b`; sharing incremental build state between them is a needless race for a small wall-clock gain. -- **Use unbounded real-API e2e parallelism** - rejected because the suite includes many live model/tool scenarios; the worker pool needs an explicit `DSH_E2E_MAX_WORKERS` cap so CI and local runs can fan out without hiding quota or resource problems behind flaky rate-limit failures. +- **Keep the broad lanes** - minimizes workflow YAML, but it preserves the measured multi-minute feedback loop. +- **Run every leaf gate as a separate GitHub job** - maximizes fan-out, but short generators and prose checks would spend more time preparing a runner than checking the repository. +- **Upload one build to artifact consumers** - avoids repeated compilation, but upload/download and dependency scheduling lengthen wall time; the clean build is short enough to repeat inside bounded lanes. +- **Keep package-manager packing in both publication gates** - delegates inventory selection to pnpm, but repeats more than 200 package-manager processes. The manifest structural gate plus publication-view fixtures make the optimized inventory contract explicit and fail on an on-disk but unpublished dependency. +- **Keep build before coverage** - provides emitted output the source suite no longer consumes; a clean-tree coverage proof showed it was pure latency. +- **Typecheck on every Node version** - repeats compiler work while the compatibility smokes already exercise actual Node-specific loading and compression behavior. ## Consequences -PR feedback arrives as a few GitHub checks with structured per-gate log blocks inside each broad job. That keeps runner setup overhead bounded and the Actions UI compact, at the cost of losing one status check per leaf gate. +The shard inventories and matrix jobs described above are not part of the current repository contract. The superseding larger-runner decision keeps the complete primary inventory in one process and uses the serial suite as its independent completeness oracle. -The broad-lane split repeats checkout, setup, and install more often than a single primary job. That setup cost is intentional: on GitHub's hosted runner, running lint, coverage, and snapshot replay in one process pool oversubscribes CPU badly enough that the single-job critical path is longer than the repeated setup. +The optimized publication validators rely on the manifest `files` contract enforced by `verify-package-invariants`. If publication rules grow beyond that contract, the structural gate and both staged views must change together. -The split introduces a maintenance obligation: when `package.json` adds or removes a gate that belongs in CI, [scripts/run-gates.ts](../../../../scripts/run-gates.ts) needs the matching leaf. That obligation is intentional because the runner is the parallel execution plan for the same gate vocabulary, not a separate quality policy. - -The compatibility signal is narrower than the primary Node 24 signal. It proves that the source graph typechecks and that the real unbuilt workflow-worker launch path executes on every advertised runtime line without doubling documentation, coverage, publication, snapshot replay, and unrelated smoke checks whose failures are not expected to vary by Node version. +Compatibility jobs no longer claim that TypeScript itself was exercised under every Node runtime. They prove runtime-sensitive source loading on Node 22, 24, and 26, while the primary runtime owns the single source-graph typecheck. diff --git a/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.md b/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.md index 44d1b17a5b..a5c15686ae 100644 --- a/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.md +++ b/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.md @@ -18,6 +18,8 @@ Locale home projections retain only the canonical YAML frontmatter. The reposito The projector parses Markdown links without reserializing the document. A link to another published source becomes a site-relative route; a link to an unpublished repository file becomes a GitHub source link; a repository image becomes a raw GitHub URL. Missing relative targets fail projection. Unit tests pin these transformations, and `docs:check` runs the projector tests plus a production VitePress build as part of `doc-sync` and the parallel documentation gates. +`website/AGENTS.md` is the only maintained Markdown file in the website subtree. The projector test enumerates tracked and unignored files and rejects any other website Markdown, so site-specific locale, route, API, or generated source copies cannot bypass the publication manifest. + Mermaid renders the canonical diagrams. The website workspace explicitly declares the five packages that `vitepress-plugin-mermaid` asks Vite to prebundle because pnpm's strict dependency isolation otherwise makes those transitive packages unavailable to the local development server; Knip records this runtime-only use as an intentional dependency exception. Site publication remains separate from site construction. A dedicated GitHub Actions workflow runs the existing documentation gates, uploads `website/.dist` as a Pages artifact, and deploys only after the build succeeds. `actions/configure-pages` supplies the destination's base path to VitePress at build time, so the private Pages origin, a later public project path, and a custom domain do not require distinct checked-in configurations. Pages visibility remains a repository hosting setting rather than a workflow permission. @@ -38,6 +40,6 @@ Site publication remains separate from site construction. A dedicated GitHub Act ## Consequences -Documentation facts have one editable home, public routes remain stable across source moves, and the site can include generated references without committing another generated copy. Local development watches canonical inputs and regenerates the disposable projection. Merges that affect the documentation site deploy the checked result to Pages, while manual dispatch provides a recovery and validation entry point. +Documentation facts have one editable home, public routes remain stable across source moves, and the site can include generated references without committing another generated copy. Local development watches canonical inputs and regenerates the disposable projection. The layout gate makes an obsolete site-specific Markdown tree a merge failure instead of ignored build input. Merges that affect the documentation site deploy the checked result to Pages, while manual dispatch provides a recovery and validation entry point. The publication manifest is a maintained allowlist, and link projection adds a small repository-specific build adapter. A new kind of Markdown link behavior needs a projector test. Mermaid support also increases the client bundle size, but preserves diagrams already used by the canonical documentation. diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml new file mode 100644 index 0000000000..9922018569 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml @@ -0,0 +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 +2026-07-21-serial-cross-platform-ci-reference.md: ffc1fd5b37bc6c9e3427ee55a55300f93a1292f3 +2026-07-21-serial-cross-platform-ci-reference.zh.md: d7f87916865b83973abe6b0708203618cf536c8e diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md new file mode 100644 index 0000000000..ffc1fd5b37 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md @@ -0,0 +1,39 @@ +# Agent Note: Serial cross-platform CI reference + +Status: implemented + +English | [中文](2026-07-21-serial-cross-platform-ci-reference.zh.md) + +## Problem + +The pull-request workflow reaches its latency targets by scheduling the complete primary Node inventory concurrently inside one larger runner. The optimized scheduler still should not be its own only completeness oracle: a defect in its gate inventory or dependency graph could omit work while the optimized job stays green. + +Encoding the one-minute non-Windows target and three-minute Windows target as job timeouts creates a separate failure mode. Hosted-runner startup and performance vary, so a correct gate can be cancelled at the target boundary before it emits useful diagnostics. The performance objective needs measurement against GitHub timestamps, while correctness needs enough time to finish. + +Reviewers also need a direct answer to a simpler question: what happens when the repository's complete primary Node CI aggregate runs without matrix selection, shard variables, or concurrent gates on each selected hosted operating system? + +## Decision + +[CI](../../../../.github/workflows/ci.yml) gives pull-request and master-push events complementary responsibilities. Pull requests run only the optimized larger-runner and compatibility jobs. A push to `master` skips those jobs and runs three explicit references named `serial / linux`, `serial / macos`, and `serial / windows`. They intentionally duplicate their short checkout, runtime setup, and immutable install sequences instead of hiding the operating systems behind a matrix or reusable workflow. `workflow_dispatch` is reserved for runner benchmarks. + +Each reference job runs `pnpm run check:ci` without any shard selector. `DSH_GATE_CONCURRENCY=1` makes the top-level aggregate execute one ready gate at a time; coverage, snapshot replay, built-bin smoke, and publication validation also receive worker counts of one. The three operating-system jobs may run beside one another, but each host's repository gates are serial and complete. Linux installs bubblewrap before replaying snapshots, and Windows enables Developer Mode before installing the symlinked workspace. + +Master reference jobs are diagnostic and do not participate in the pull request's required `all checks passed` result. A pull request runs only the optimized jobs; a master push runs only the three serial references. The one-minute non-Windows and three-minute Windows objectives are evaluated from completed hosted-job timestamps and reported as measurements; they are not `timeout-minutes` values. + +The portable reference uses GitHub's standard `ubuntu-latest`, `macos-latest`, and `windows-2025` labels. A higher-core hosted runner remains a possible future benchmark, but it is not the default: larger runners require organization-owned labels and provisioning, while a reference oracle should remain runnable without repository-external runner configuration. Provisioning one later can change the performance experiment without changing this correctness baseline. + +## Alternatives considered + +- **Set each timeout equal to its latency target** - rejected because scheduling variance would cancel correct work and suppress the evidence needed to diagnose a regression. +- **Trust only the concurrent primary inventory** - rejected because scheduling and validation share implementation assumptions; a serial aggregate is an independent completeness check. +- **Run the serial references on every pull request** - rejected because they deliberately trade wall time and runner consumption for simplicity and are not needed in the fast feedback loop. +- **Use one operating-system matrix** - rejected because three named jobs make the reference surface visible without another selection mechanism. +- **Run the serial reference on larger runners** - rejected because the reference is the portable fallback for the organization-specific pull-request topology. The fast pull-request path uses provisioned larger runners; the serial master path keeps standard labels. + +## Consequences + +The workflow contains duplicated setup steps and a master reference run can take much longer than the optimized pull-request path. That duplication is deliberate: reviewers can inspect each operating system's complete command without resolving a matrix or concurrent scheduler. + +The reference may expose platform failures that the optimized blocking set does not yet claim to support, especially on Windows. Such a failure is evidence about current cross-platform behavior rather than a reason to weaken or silently skip the aggregate. + +Removing strict duration timeouts means a latency regression is observed rather than automatically cancelled. Hosted measurements must therefore accompany performance changes, while the completed logs retain the information needed to optimize the slow lane. diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md new file mode 100644 index 0000000000..d7f8791686 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md @@ -0,0 +1,39 @@ +# Agent Note: 跨平台串行 CI 参考流程 + +Status: implemented + +[English](2026-07-21-serial-cross-platform-ci-reference.md) | 中文 + +## 问题 + +拉取请求工作流通过在一台更大型运行器内并发调度完整的主 Node 门禁清单来达到延迟目标。优化调度器仍不应成为自身唯一的完整性判定基准:如果其门禁清单或依赖图存在缺陷,即使优化作业保持绿灯,也可能漏掉部分工作。 + +将非 Windows 作业的 1 分钟目标和 Windows 作业的 3 分钟目标写成作业超时,会引入另一种失败模式。托管运行器的启动时间和性能会波动,因此即使门禁本身正确,也可能在到达目标时间边界时被取消,来不及输出有用的诊断信息。性能目标需要根据 GitHub 时间戳衡量,而正确性验证需要给门禁留足完成时间。 + +评审人还需要直接回答一个更简单的问题:在每个选定的托管操作系统上,如果仓库完整的主 Node CI 聚合流程不使用矩阵选择、分片变量或并发门禁,运行结果会怎样? + +## 决策 + +[CI](../../../../.github/workflows/ci.yml) 为拉取请求事件与 master 推送事件赋予互补的职责。拉取请求只运行使用更大型运行器的优化作业和兼容性作业。向 `master` 推送时会跳过这些作业,改为运行三个显式参考作业,名称分别为 `serial / linux`、`serial / macos` 和 `serial / windows`。这些作业有意分别重复简短的代码检出、运行时设置和依赖锁定的安装步骤,不用矩阵或可复用工作流把操作系统差异隐藏起来。`workflow_dispatch` 仅用于运行器基准测试。 + +每个参考作业均在不设置任何分片选择器的情况下运行 `pnpm run check:ci`。`DSH_GATE_CONCURRENCY=1` 使顶层聚合每次只执行一个已经就绪的门禁;覆盖率、快照回放、built-bin 冒烟测试和发布验证的并发数也设为 1。三种操作系统的作业可以彼此并行,但每台主机上的仓库门禁都串行运行且完整执行。Linux 在回放快照前安装 bubblewrap,Windows 则在安装采用符号链接的工作区前启用开发人员模式。 + +master 分支的参考作业仅用于诊断,不参与拉取请求所要求的 `all checks passed` 结果。拉取请求只运行优化作业;向 master 推送时只运行三个串行参考作业。系统根据已完成托管作业的时间戳评估非 Windows 作业的 1 分钟目标和 Windows 作业的 3 分钟目标,并将其报告为测量结果,而不是写成 `timeout-minutes` 值。 + +可移植的参考流程使用 GitHub 标准的 `ubuntu-latest`、`macos-latest` 和 `windows-2025` 标签。仍可将更高核心数的托管运行器作为未来的基准测试,但不将其设为默认选择:更大型运行器需要组织自有的标签和预配,而参考判定基准应无需仓库外部的运行器配置即可运行。日后完成这类预配,可以改变性能实验而无需改变该正确性基线。 + +## 曾考虑的替代方案 + +- **将每个超时值设为相应延迟目标**:不予采纳,因为调度波动会中止原本正确的执行,并使诊断回归所需的证据无法产生。 +- **仅信任并发执行的主门禁清单**:不予采纳,因为调度逻辑与校验逻辑共享实现假设;串行聚合流程是一项独立的完整性检查。 +- **在每个拉取请求上运行串行参考作业**:不予采纳,因为这些作业有意以更长的总耗时和更多运行器用量换取简单性,快速反馈循环不需要它们。 +- **使用一个操作系统矩阵**:不予采纳,因为三个具名作业无需另一套选择机制,就能让参考流程的构成清晰可见。 +- **在更大型运行器上运行串行参考流程**:不予采纳,因为该参考流程是特定组织拉取请求拓扑的可移植后备方案。快速拉取请求路径使用已预配的更大型运行器;串行 master 路径保留标准标签。 + +## 后果 + +工作流包含重复的设置步骤,master 参考运行也可能比优化后的拉取请求路径耗时长得多。这些重复是有意保留的:评审人无需解析矩阵或并发调度器,就能直接检查每种操作系统执行的完整命令。 + +参考流程可能暴露某些平台上的故障,而优化后的阻塞门禁集合尚未声明支持这些平台,Windows 尤其如此。这类失败反映了当前的跨平台行为,不应成为削弱或静默跳过该聚合流程的理由。 + +移除严格的时长超时后,系统会观测到延迟回归,而不是在发生回归时自动取消运行。因此,性能改动必须附带托管环境测量结果,已完成的日志则保留优化最慢通道所需的信息。 diff --git a/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.i18n.yaml b/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.i18n.yaml new file mode 100644 index 0000000000..6277617a73 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.i18n.yaml @@ -0,0 +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 +2026-07-22-evidence-based-larger-hosted-runners.md: c0fae2841f21c431d6416cd5d421929d70197abb +2026-07-22-evidence-based-larger-hosted-runners.zh.md: 51c73a8a631af4f1254c795d09585770fc4e68bb diff --git a/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.md b/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.md new file mode 100644 index 0000000000..c0fae2841f --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.md @@ -0,0 +1,75 @@ +# Agent Note: Evidence-based larger hosted runners + +Status: implemented + +English | [中文](2026-07-22-evidence-based-larger-hosted-runners.zh.md) + +## Problem + +The shard-heavy CI topology met its latency targets by spreading primary Node work across 40 Linux jobs and Windows work across nine jobs. Most gates were shorter than checkout, runner setup, cache restore, and dependency installation, so repeated setup waves created both cost and latency variance. One hosted run finished its slowest Linux job in 49 seconds yet took 231 seconds for a Windows lint shard whose checkout, cache restore, and install alone consumed 158 seconds. + +Larger runners make it possible to pay setup once and parallelize inside the repository scheduler, but the useful size cannot be selected from core counts alone. Critical-lane benchmarks did not scale monotonically, and a whole-repository aggregate exposed different bottlenecks from isolated typecheck or site builds. + +## Decision + +The organization keeps twelve x64 larger-runner pools in the repo-restricted `dsh-larger-ci` group: Ubuntu 24.04 and Windows 2025 at 4, 8, 16, 32, 64, and 96 cores. Public IPs are disabled. Each pool has an autoscaling ceiling of 256; the ceiling does not allocate idle machines or remove the need to bound workflow demand. + +Production CI uses five larger-runner executions and one standard-runner aggregator. The primary Node inventory is not sharded: + +- `node 24 / complete` uses one 96-core Linux runner. One checkout, direct selection of the image's preinstalled Node 24 toolcache, pnpm- and ESLint-cache restore, and install feeds all 42 primary gates. `run-gates` starts up to 10 independent gates; ESLint and coverage use at most 16 workers, and snapshot replay uses at most 8. Build starts as soon as the first short gates release scheduler slots, while snapshot replay and publication consumers retain explicit dependencies on emitted `lib/` output. Pull requests restore both caches without saving them, so cache compression and upload do not extend the required job; the master serial reference refreshes those caches outside the pull-request critical path. An uncached exact-head trace put ESLint at 38.11 seconds and coverage at 37.10 seconds, so the small ESLint restore remains useful on the critical path. The read-only job does not persist checkout credentials. +- Node 22.19 and Node 26 use the 4- and 32-core Linux pools for their runtime compatibility smokes. Python 3.10 uses the 8-core Linux pool for the complete keyless SDK suite. These are environment contracts, not slices of the primary Node gate inventory. +- `windows node 24 / complete` uses one 32-core Windows runner. One preparation wave feeds the required package build, required production site build, and complete observational portability inventory. Required failures fail the job; observational failures are reported as non-blocking. ESLint stays single-threaded because 16 ESLint workers took 174.54 seconds, coverage uses at most 12 workers, and the outer scheduler retains 16 slots. The job restores only the small master-refreshed ESLint cache and performs a clean pnpm install instead of restoring or saving the many-file package store. All six Windows larger-runner sizes completed install and the production-site benchmark without mutating the machine-wide Developer Mode registry key, so the pull-request critical path omits that redundant step. + +The former gate-level and coarse primary shard jobs are absent from the workflow. Their static, lint, coverage, snapshot, and scenario shard selectors are also absent from the repository, so an unused diagnostic path cannot preserve a second CI architecture. + +An [exact-head all-size benchmark](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29908491351) ran the complete unsharded primary Node aggregate on every Linux pool before the eager-build correction: + +| Complete Linux primary | 4 cores | 8 cores | 16 cores | 32 cores | 64 cores | 96 cores | +|---|---:|---:|---:|---:|---:|---:| +| Active time | 243 s | 144 s | 103 s | 87 s | 62 s | 65 s | + +The 96-core trace spent 39.14 seconds in repository gates. Typecheck occupied 25.71 seconds, then a scheduler dependency delayed the 2.13-second build and 11.29-second snapshot replay until it finished. The same run already proved build and typecheck independently, and the former CPU lane ran them concurrently. Removing that dependency makes lint at 33.30 seconds the measured critical gate while preserving dependencies only for consumers of build output. The 64-core trace exposed the same idle chain: typecheck, build, and snapshot consumed 44.85 seconds in sequence while its independent lint and documentation builds finished in 36.83 and 36.15 seconds. More cores therefore become useful only after the repository scheduler can feed them. + +The same benchmark measured the required Windows build surfaces across every provisioned size: + +| Windows blocking builds | 4 cores | 8 cores | 16 cores | 32 cores | 64 cores | 96 cores | +|---|---:|---:|---:|---:|---:|---:| +| Active time | 152 s | 104 s | 104 s | 92 s | 103 s | 110 s | + +Repository work gains little above 16 Windows cores, but the 32-core pool can start the complete outer inventory together. A [retargeted production validation](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29907581119/attempts/2) completed the full one-box Windows inventory in 173 seconds, including coverage and snapshot replay, so Windows remains consolidated. + +The larger client package graph makes cache mechanics and scheduler pressure part of the measured workload. In [one exact-head production run](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29912577681), Linux spent 39 seconds in repository gates but 69 seconds in the complete job, while Windows spent 117 seconds in repository gates and 228 seconds in the complete job. The Windows pnpm cache downloaded its 154 MB archive in about two seconds but spent 27 seconds extracting it, followed by a 23-second install and a 14-second post-job save. A [cacheless all-size trace](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29913033155) completed the same 32-core Windows install in 27 seconds. Production therefore avoids the Windows package-store cache, uses restore-only caches on latency-critical pull-request jobs, and bounds outer concurrency so typecheck, lint, coverage, and build do not oversubscribe one host. + +Three host effects remain part of the decision. A standard Node 26 job once spent 36 of its 67 seconds in `Set up job`, which is why environment contracts use distinct larger-runner pools instead of standard capacity. The setup-node action later spent 3.68 seconds printing cached Linux environment details and 46.56 seconds doing the same on Windows after both had already found Node 24.18.0 in the hosted toolcache. The two latency-critical jobs select the newest preinstalled 24.x directory directly, verify its major, and fail loud if the image no longer carries it; compatibility jobs retain setup-node because selecting a non-default runtime is their contract. A Linux candidate also spent 18 seconds registering a 50 KB Bubblewrap package because the hosted image scanned 202,507 package-database files. [`scripts/prepare-ci-bubblewrap.sh`](../../../../scripts/prepare-ci-bubblewrap.sh) instead verifies and extracts the pinned payload into the ephemeral runner directory, runs a functional confinement probe, and overlaps that preparation with dependency installation. + +Inner and outer worker limits are separate controls. An [exact-head 32-worker ESLint experiment](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29918329463) slowed lint to 52.28 seconds and coverage to 42.71 seconds, where an adapter idle-timeout test failed. A later 8-gate trace reduced coverage to 35.17 seconds but delayed the production-site build until the aggregate reached 41.06 seconds. Production therefore retains 16 ESLint workers and admits 10 independent repository gates at once, leaving capacity for the worker pools owned by those gates without starving later independent work. + +Linux coverage caps each project at 16 workers, while Windows keeps the 12-worker cap. The process-bound project contains exactly five suite files, so its fork count cannot reach either cap. Thirty-two forks crashed Node 24's CJS lexer twice, and a later 16-fork run reproduced the worker loss and invalid coverage result. The single Vitest invocation therefore uses threads for the broad inventory and reserves forks for suites that exercise process-global state, `process` APIs, or timing-sensitive process I/O. That narrow fork inventory includes the local bash process-plumbing suite: under aggregate gate contention its thread worker completed every test but intermittently missed the stdin-error callback needed for per-file function coverage. It also includes the pi-ai adapter suite after two hosted aggregate runs delayed an idle-watchdog socket-close observation past its 100-millisecond test deadline. A 32-worker all-gate run on the 96-core host slowed coverage to 44.6 seconds and made a compute-budget regression cross its one-second threshold, so production stops at 16. This preserves the suites' isolation contracts and deterministic coverage while avoiding forked execution for ordinary test files. + +The workflow retains two manual measurement suites. `suite=larger-runner-benchmark` compares isolated critical lanes across every size, and `suite=consolidated-runner-benchmark` compares whole aggregates. Complete serial Linux, macOS, and Windows references run only when `master` moves; pull requests run only the optimized jobs. + +## Alternatives considered + +**Keep the three coarse primary Linux lanes.** The core, CPU, and production-site jobs met the latency targets, but they paid three setup waves and left primary Node work sharded after larger runners were available. The all-size trace showed that one unnecessary dependency, not a lack of host capacity, kept the single-box aggregate above one minute. + +**Keep the former gate-level shard topology as a manual reference.** A dormant second topology kept hundreds of workflow lines, selector modules, and scenario-partition behavior alive. The all-size and serial suites provide timing and completeness controls without preserving production code that no required job exercises. + +**Use the 64-core pool for the complete primary aggregate.** Its sampled active time was three seconds lower than the 96-core result because hosted setup was nine seconds faster, but its repository gates were 5.72 seconds slower. Production uses 96 cores for the shorter controllable critical path; the benchmark suite retains both pools so a sustained image or pricing change can reverse that choice with evidence. + +**Keep build behind typecheck.** This orders independent compiler invocations and turns snapshot replay into a three-stage critical chain. Build output has its own success dependency, so only snapshot and publication consumers wait for it. + +**Keep compatibility and Python on standard runners.** Warm standard runs can fit, but runner setup alone has crossed the non-Windows target. Distinct larger pools isolate these environment contracts from that allocation lottery. + +**Keep required and observational Windows checks in separate jobs.** The split preserves status semantics at the workflow level but pays setup twice. `run-gates` preserves the same required versus non-blocking distinction inside one process. + +**Install Bubblewrap through the system package manager.** This uses the host's package database and can dominate the job even when the payload is tiny. Pinned extraction plus a confinement probe preserves the runtime contract without mutating the hosted image. + +## Consequences + +Primary Node CI has one job, one setup wave, one complete gate inventory, and no shard selectors. Together with two Node compatibility executions, Python, and Windows, production has five paid larger-runner executions instead of seven coarse-lane executions or 49 gate-level executions. + +GitHub rounds each larger-runner execution up to a whole minute, so eliminating setup waves reduces billed time as well as workflow complexity. The final aggregator remains on a standard runner because it begins only after the paid jobs release capacity. + +The current targets are observed performance contracts, not cancellation deadlines. Exact-head production runs must show every non-Windows job below one minute and the consolidated Windows job below three minutes; manual all-size and serial suites remain available when image, dependency, scheduler, or pricing changes need remeasurement. + +Production CI depends on the organization-owned runner labels in [`.github/workflows/ci.yml`](../../../../.github/workflows/ci.yml). Missing or renamed pools leave jobs queued instead of falling back to standard capacity. All twelve pools remain provisioned so the manual benchmarks can re-evaluate the production size without an administrative setup cycle. diff --git a/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.zh.md b/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.zh.md new file mode 100644 index 0000000000..51c73a8a63 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-22-evidence-based-larger-hosted-runners.zh.md @@ -0,0 +1,75 @@ +# Agent Note: 基于实证选用 GitHub 托管大型运行器 + +Status: implemented + +[English](2026-07-22-evidence-based-larger-hosted-runners.md) | 中文 + +## 问题 + +高度分片的 CI 拓扑通过把主 Node 工作分散到 40 个 Linux 作业、把 Windows 工作分散到 9 个作业来达到延迟目标。大多数门禁本身的耗时短于代码检出、运行器设置、缓存恢复和依赖安装这些准备阶段,因此反复执行多轮设置既增加成本,也带来延迟波动。一次托管运行中最慢的 Linux 作业用时 49 秒,而一个 Windows lint 分片却耗时 231 秒,其中仅代码检出、缓存恢复和安装就占了 158 秒。 + +大型运行器可以让 CI 只承担一次设置开销,再由仓库调度器在内部并行执行,但无法仅凭核心数选出有实际价值的规格。关键通道基准测试的性能提升不呈单调变化,完整仓库聚合流程暴露出的瓶颈也不同于单独运行类型检查或网站构建时的瓶颈。 + +## 决策 + +组织在仅限本仓库使用的 `dsh-larger-ci` 运行器组中保留 12 个 x64 大型运行器池:Ubuntu 24.04 和 Windows 2025 各设 4、8、16、32、64、96 核规格。公网 IP 已禁用。每个池的自动扩缩容上限为 256;该上限既不会分配闲置机器,也不能免除限制工作流需求的必要性。 + +生产 CI 包含 5 次大型运行器执行和 1 个标准运行器聚合作业。主 Node 门禁清单不再分片: + +- `node 24 / complete` 使用一台 96 核 Linux 运行器。只需执行一次代码检出、直接选择托管映像中预装的 Node 24 toolcache、恢复 pnpm 和 ESLint 缓存以及安装,即可供全部 42 项主门禁使用。`run-gates` 最多同时启动 10 项相互独立的门禁;ESLint 和覆盖率最多使用 16 个工作线程,快照回放最多使用 8 个。第一批短门禁释放调度器槽位后,构建会立即启动,而快照回放和发布消费方仍显式依赖生成的 `lib/` 输出。拉取请求会恢复这两项缓存但不保存,因此缓存压缩和上传不会延长必需作业;master 上的串行参考会在拉取请求关键路径之外刷新这两项缓存。一次未使用缓存的分支头精确运行轨迹显示,ESLint 耗时 38.11 秒,覆盖率耗时 37.10 秒,因此在关键路径上恢复这个较小的 ESLint 缓存仍有价值。该只读作业不会持久化代码检出凭据。 +- Node 22.19 和 Node 26 分别使用 4 核和 32 核 Linux 池运行各自的运行时兼容性冒烟测试。Python 3.10 使用 8 核 Linux 池运行完整的无密钥 SDK 套件。这些作业属于环境契约,并非主 Node 门禁清单的分片。 +- `windows node 24 / complete` 使用一台 32 核 Windows 运行器。一轮准备工作供必需的包构建、必需的生产网站构建以及完整的观测性可移植性清单共用。任何必需项失败都会使作业失败;观测项失败则报告为非阻塞。ESLint 保持单线程,因为 16 个 ESLint 工作线程耗时 174.54 秒;覆盖率最多使用 12 个工作线程,外层调度器则保留 16 个槽位。该作业仅恢复由 master 刷新的较小 ESLint 缓存,并在干净环境中执行 pnpm 安装,而不恢复或保存包含大量文件的包存储。全部 6 种 Windows 大型运行器规格都在未修改系统级 Developer Mode 注册表项的情况下完成了安装和生产网站基准测试,因此拉取请求关键路径省略了这个多余步骤。 + +原有的门禁级和粗粒度主流程分片作业已从工作流中移除。相应的静态、lint、覆盖率、快照和场景分片选择器也已从仓库中移除,因此未使用的诊断路径无法继续维系第二套 CI 架构。 + +一次[分支头精确的全规格基准测试](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29908491351)在修正构建尽早启动逻辑前,对每种 Linux 池都运行了完整且未分片的主 Node 聚合流程: + +| Linux 完整主流程 | 4 核 | 8 核 | 16 核 | 32 核 | 64 核 | 96 核 | +|---|---:|---:|---:|---:|---:|---:| +| 活动耗时 | 243 秒 | 144 秒 | 103 秒 | 87 秒 | 62 秒 | 65 秒 | + +96 核运行轨迹中的仓库门禁耗时 39.14 秒。类型检查占用 25.71 秒,随后一项调度器依赖使耗时 2.13 秒的构建和耗时 11.29 秒的快照回放都要等到类型检查结束后才启动。同一次运行已经分别证明构建和类型检查可以独立执行,原 CPU 通道也曾让二者并发运行。移除这项依赖后,耗时 33.30 秒的 lint 成为实测关键门禁,而只有构建输出的消费方仍保留依赖关系。64 核运行轨迹暴露了相同的空闲链:类型检查、构建和快照依次执行,共耗时 44.85 秒,而相互独立的 lint 和文档构建分别在 36.83 秒和 36.15 秒内完成。因此,只有仓库调度器能够为更多核心持续提供工作时,增加核心数才有价值。 + +同一项基准测试还测量了每种已预配规格上的 Windows 必需构建项: + +| Windows 阻塞性构建 | 4 核 | 8 核 | 16 核 | 32 核 | 64 核 | 96 核 | +|---|---:|---:|---:|---:|---:|---:| +| 活动耗时 | 152 秒 | 104 秒 | 104 秒 | 92 秒 | 103 秒 | 110 秒 | + +Windows 仓库工作在超过 16 核后收益很小,但 32 核池可以让完整的外层清单同时启动。一次[重新定向的生产验证](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29907581119/attempts/2)在 173 秒内完成了单机 Windows 完整清单,其中包括覆盖率和快照回放,因此 Windows 继续采用合并执行方式。 + +客户端包依赖图增大后,缓存机制和调度器压力也成为实测工作负载的一部分。在[一次分支头精确的生产运行](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29912577681)中,Linux 的仓库门禁耗时 39 秒,完整作业耗时 69 秒;Windows 的仓库门禁耗时 117 秒,完整作业耗时 228 秒。Windows pnpm 缓存的 154 MB 归档下载耗时约 2 秒,但解压耗时 27 秒,随后安装耗时 23 秒,作业结束后的保存又耗时 14 秒。一次[无缓存的全规格运行轨迹](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29913033155)在 27 秒内完成了同一台 32 核 Windows 运行器上的安装。因此,生产环境不使用 Windows 包存储缓存,在对延迟敏感的拉取请求作业中使用只恢复不保存的缓存,并限制外层并发度,以免类型检查、lint、覆盖率和构建在同一台主机上过度争用资源。 + +3 项主机效应仍构成这项决策的依据。一个标准 Node 26 作业曾在总共 67 秒的耗时中,把 36 秒用在 `Set up job` 上,因此各项环境契约使用不同的大型运行器池,而非标准容量。setup-node action 在 Linux 和 Windows 均已从托管 toolcache 找到 Node 24.18.0 后,仍分别花费 3.68 秒和 46.56 秒输出缓存的环境详情。两个延迟关键作业会直接选择最新的预装 24.x 目录并验证其主版本号;如果映像不再提供该目录,作业会明确报错并失败。兼容性作业仍使用 setup-node,因为选择非默认运行时正是它们的契约。一个 Linux 候选作业还在注册 50 KB 的 Bubblewrap 包时耗时 18 秒,因为托管映像扫描了 202,507 个包数据库文件。[`scripts/prepare-ci-bubblewrap.sh`](../../../../scripts/prepare-ci-bubblewrap.sh) 改为验证固定包内容并将其解压到临时运行器目录,执行功能性隔离探针,并让这项准备工作与依赖安装重叠执行。 + +内层与外层工作线程上限是相互独立的控制机制。一次[分支头精确、使用 32 个工作线程的 ESLint 实验](https://github.com/deepseek-harness/deepseek-harness/actions/runs/29918329463)使 lint 耗时增至 52.28 秒、覆盖率耗时增至 42.71 秒;同一次运行中,一项适配器空闲超时测试失败。后来一次同时运行 8 项门禁的运行轨迹将覆盖率耗时降至 35.17 秒,但生产网站构建被延后,直到聚合流程耗时达到 41.06 秒时才完成。因此,生产环境将 ESLint 工作线程上限维持在 16 个,并且同时最多运行 10 项相互独立的仓库门禁,既为这些门禁自身的工作线程池留出容量,又避免后续独立工作因资源不足而迟迟无法启动。 + +Linux 覆盖率把每个项目的工作线程上限设为 16 个,Windows 则保留 12 个工作线程的上限。进程约束项目恰好包含 5 个套件文件,因此它的 fork 数量不可能达到任一上限。32 个 fork 曾两次导致 Node 24 的 CJS 词法分析器崩溃,后来一次使用 16 个 fork 的运行又复现了工作进程丢失和无效的覆盖率结果。因此,单次 Vitest 调用会对大范围测试清单使用线程,只为涉及进程全局状态、`process` API 或对时间敏感的进程 I/O 的套件保留 fork。这份有限的 fork 清单还包含本地 bash 进程通路套件:在聚合门禁争用资源时,该套件的工作线程虽然完成了所有测试,却会间歇性漏记逐文件函数覆盖率所需的 stdin 错误回调。两次托管聚合运行都将空闲看门狗对套接字关闭的观测延迟到超过其 100 毫秒测试截止时间,因此这份清单还包含 pi-ai 适配器套件。在 96 核主机上使用 32 个工作线程运行全部门禁时,覆盖率耗时变慢至 44.6 秒,还使一项计算预算回归超过其 1 秒阈值,因此生产环境将工作线程数限制在 16 个以内。这样既能保留这些套件的隔离契约和覆盖率结果的确定性,又能避免以 fork 方式执行普通测试文件。 + +工作流保留 2 项手动测量套件。`suite=larger-runner-benchmark` 比较所有规格下相互独立的关键通道,`suite=consolidated-runner-benchmark` 比较完整聚合流程。只有在 `master` 移动时,才运行完整的 Linux、macOS 和 Windows 串行参考;拉取请求只运行优化后的作业。 + +## 曾考虑的替代方案 + +**保留 3 个粗粒度 Linux 主流程通道。** 核心、CPU 和生产网站作业均达到延迟目标,但它们需要 3 轮设置,而且在大型运行器已经可用后仍对主 Node 工作进行分片。全规格运行轨迹表明,让单机聚合流程超过 1 分钟的是一项不必要的依赖,而非主机容量不足。 + +**将原有的门禁级分片拓扑保留为手动参考。** 一套闲置的第二拓扑会让数百行工作流、选择器模块和场景分区行为继续存活。全规格和串行套件无需保留任何必需作业都不执行的生产代码,也能提供计时与完整性对照。 + +**使用 64 核池运行完整主聚合流程。** 由于托管设置快了 9 秒,其采样活动耗时比 96 核结果少 3 秒,但仓库门禁慢了 5.72 秒。生产环境使用 96 核来缩短可控的关键路径;基准测试套件保留两种规格,因此如果映像或定价发生持续性变化,仍可根据证据反转这项选择。 + +**让构建继续等待类型检查。** 此方案会给相互独立的编译器调用排定先后顺序,并把快照回放变成 3 阶段关键链。构建输出本身有独立的成功依赖关系,因此只有快照和发布消费方需要等待它。 + +**让兼容性和 Python 继续使用标准运行器。** 标准运行器热运行可以达到目标,但仅运行器设置一项就曾超过非 Windows 目标。不同的大型运行器池可以让这些环境契约免受这种分配波动影响。 + +**将必需的 Windows 检查和观测性 Windows 检查保留在不同作业中。** 这种拆分在工作流层保留状态语义,却需要支付两次设置开销。`run-gates` 在一个进程内保留了相同的必需与非阻塞区别。 + +**通过系统包管理器安装 Bubblewrap。** 此方案会使用主机的包数据库,即使包内容很小,也可能主导整个作业耗时。固定版本的解压方式配合隔离探针,无需修改托管映像即可保留运行时契约。 + +## 后果 + +主 Node CI 只有 1 个作业、1 轮设置、1 份完整门禁清单,而且没有分片选择器。加上 2 次 Node 兼容性执行、Python 和 Windows,生产环境共有 5 次付费大型运行器执行,而非 7 次粗粒度通道执行或 49 次门禁级执行。 + +GitHub 会把每次大型运行器执行向上取整到整分钟计费,因此消除设置轮次既能减少计费时长,也能降低工作流复杂度。最终聚合作业仍使用标准运行器,因为它只会在付费作业释放容量后启动。 + +当前目标是基于观测得到的性能契约,而非取消截止时间。分支头精确的生产运行必须表明每个非 Windows 作业都低于 1 分钟,合并后的 Windows 作业低于 3 分钟;当映像、依赖、调度器或定价发生变化而需要重新测量时,仍可使用手动全规格和串行套件。 + +生产 CI 依赖 [`.github/workflows/ci.yml`](../../../../.github/workflows/ci.yml) 中由组织持有的运行器标签。池缺失或改名会让作业一直排队,不会回退到标准容量。全部 12 个池均保持已预配状态,因此手动基准测试无需再次经过管理配置周期,就能重新评估生产规格。 diff --git a/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.i18n.yaml b/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.i18n.yaml new file mode 100644 index 0000000000..a6becde554 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.i18n.yaml @@ -0,0 +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 +2026-07-22-installer-in-repo-skip-clone.md: f63c438205f7bd6aeb8dd78941bbe0880a8e31a1 +2026-07-22-installer-in-repo-skip-clone.zh.md: f9fe4865ad1090211c094fc8fba843b623512cc9 diff --git a/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.md b/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.md new file mode 100644 index 0000000000..f63c438205 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.md @@ -0,0 +1,27 @@ +# Agent Note: installer skips the clone when run from inside a checkout + +Status: implemented + +English | [中文](2026-07-22-installer-in-repo-skip-clone.zh.md) + +## Problem + +`scripts/install.sh` is written for the `curl ... | sh` path: it clones the harness into `~/.dsh/source`, then installs, links, and launches. Contributors who already have a checkout and run the same script directly (`sh scripts/install.sh`) got a second, unrelated clone at `~/.dsh/source` — installing and linking a different tree than the one they were working in, with no way to exercise the local script against the local source. + +## Decision + +The script detects when it is executing from inside a real checkout and, in that mode, reuses that checkout and skips the clone/update step entirely, leaving the working tree untouched. + +Detection keys on `$0`: under `curl ... | sh` the script text arrives on stdin, so `$0` is the shell name and no file path resolves; running a checked-out copy makes `$0` the script file. When `$0` is a readable file whose parent is a `scripts/` directory inside a tree that carries both the `bin/dsh` launcher and `scripts/install.sh`, the script sets `IN_REPO=1` and repoints `DSH_SOURCE` at that repo root. Step 2 then prints a "using existing checkout" line and does nothing else — no `git fetch`, no `git checkout -B`, so the user's working tree and branch are never mutated. `DSH_REF` is advisory and ignored in this mode. + +Explicit `DSH_SOURCE` wins over detection: the value is captured before defaulting, and in-repo detection only repoints an unset `DSH_SOURCE` (or one already equal to the detected repo root). Setting `DSH_SOURCE` to a different directory opts back into the normal clone/update path, so the escape hatch to install a separate tree from within a checkout still exists. + +## Alternatives considered + +**Detect via `git rev-parse --show-toplevel` on the current directory.** Rejected: `curl ... | sh` frequently runs from inside some unrelated git repo (the user's `cwd`), which would false-positive and skip the clone against a tree that is not dsh. Anchoring on `$0`'s own location ties the decision to where the script physically lives, and the `bin/dsh` + `scripts/install.sh` markers confirm it is actually a dsh checkout. + +**Always skip the clone whenever run from a file, ignoring `DSH_SOURCE`.** Rejected: a contributor may legitimately run the in-repo script to provision a separate `~/.dsh/source` install; honoring an explicit `DSH_SOURCE` that differs from the checkout preserves that path. + +## Consequences + +Running `sh scripts/install.sh` from a checkout now installs, links, and launches that checkout instead of cloning a parallel one, which also makes the local script testable against local source. The cost is a detection block that couples to the repo layout (`scripts/` beside `bin/dsh`); if the launcher or script ever moves, the markers must move with it. The behavior is documented in the script header and both README files, and verified by running the four paths (in-repo skip, curl-style clone, explicit `DSH_SOURCE` elsewhere opting back in, explicit `DSH_SOURCE` equal to repo root still skipping). diff --git a/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.zh.md b/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.zh.md new file mode 100644 index 0000000000..f9fe4865ad --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-22-installer-in-repo-skip-clone.zh.md @@ -0,0 +1,27 @@ +# Agent Note: 在检出目录内运行时安装脚本跳过克隆 + +Status: implemented + +[English](2026-07-22-installer-in-repo-skip-clone.md) | 中文 + +## 问题 + +`scripts/install.sh`是为`curl ... | sh`路径编写的:它把 harness 克隆到`~/.dsh/source`,然后安装、软链接并启动。已经有检出的贡献者若直接运行同一脚本(`sh scripts/install.sh`),会在`~/.dsh/source`得到第二份无关的克隆——安装并软链接的是与他们正在工作的树不同的另一棵树,且无从用本地脚本验证本地源码。 + +## 决策 + +脚本会检测自身是否在真实检出内执行;在该模式下,它复用该检出并完全跳过克隆/更新步骤,保持工作树不受影响。 + +检测依据是`$0`:在`curl ... | sh`下脚本文本经由 stdin 到达,因此`$0`是 shell 名称、无路径可解析;运行已检出的副本会使`$0`成为脚本文件本身。当`$0`是一个可读文件、其父目录是一个`scripts/`目录、且该树同时带有`bin/dsh`启动器和`scripts/install.sh`时,脚本会设置`IN_REPO=1`并把`DSH_SOURCE`重新指向该仓库根。步骤 2 随后打印一行"using existing checkout"并不做其他事——不执行`git fetch`、不执行`git checkout -B`,因此用户的工作树和分支绝不会被改动。`DSH_REF`在该模式下仅供参考、被忽略。 + +显式的`DSH_SOURCE`优先于检测:该值在默认化之前就被捕获,检测只会重新指向未设置的`DSH_SOURCE`(或已经等于检测到的仓库根的那个)。把`DSH_SOURCE`设为其他目录会重新回到正常的克隆/更新路径,因此在检出目录内安装另一棵独立树的退路依然存在。 + +## 备选方案 + +**通过对当前目录执行`git rev-parse --show-toplevel`来检测。** 已否决:`curl ... | sh`常常在某个无关的 git 仓库(用户的`cwd`)内运行,这会误判并对一棵并非 dsh 的树跳过克隆。把决策锚定在`$0`自身的位置,使其绑定到脚本实际所在之处,而`bin/dsh` + `scripts/install.sh`标记则确认它确实是一个 dsh 检出。 + +**只要从文件运行就总是跳过克隆,忽略`DSH_SOURCE`。** 已否决:贡献者可能合理地运行检出内脚本来配置一份独立的`~/.dsh/source`安装;尊重与检出不同的显式`DSH_SOURCE`保留了该路径。 + +## 影响 + +现在从检出目录运行`sh scripts/install.sh`会安装、软链接并启动该检出,而不是克隆一份平行副本,这也让本地脚本可以针对本地源码进行测试。代价是一段与仓库布局耦合的检测逻辑(`scripts/`与`bin/dsh`并列);若启动器或脚本将来移动,标记必须随之移动。该行为记录在脚本头部和两份 README 中,并通过运行四条路径来验证(检出内跳过、curl 式克隆、显式`DSH_SOURCE`指向他处而回到克隆、显式`DSH_SOURCE`等于仓库根仍跳过)。 diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml new file mode 100644 index 0000000000..232fec495b --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml @@ -0,0 +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 +2026-07-20-retire-readline-front-door.md: 7ebcfdc246bdf6971418609c61acbd4019aa90cb +2026-07-20-retire-readline-front-door.zh.md: cf4d03594ed3a0cf31bed96eb2133bd37959084a diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md new file mode 100644 index 0000000000..7ebcfdc246 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md @@ -0,0 +1,46 @@ +# Agent Note: Retire the readline front door and the repl-agent example + +Status: implemented + +English | [中文](2026-07-20-retire-readline-front-door.zh.md) + +## Problem + +The repo shipped two interactive terminal front doors: the line-oriented readline channel (`@deepseek-ai/dsh-stdio`) and the full-screen [`@deepseek-ai/dsh-tui`](../feature/2026-07-17-dedicated-full-screen-tui-front-door.md). After the TUI landed, readline's interactive role was redundant — `demo:tui` superseded `demo:repl` as the coding-agent experience — while its remaining real role, pipes and automation, was already served better by the one-shot `@deepseek-ai/dsh-cli-demo` app (task in, DSH-native `text`/`json`/`stream-json` out, durable persistence, signal handling). + +The duplication was structural, not just cosmetic: `dsh-stdio-demo` carried a `TerminalMode` (`auto`/`readline`/`tui`) selection seam, ~1,000 lines of readline unit tests, a readline transcript grammar (`[tool call] …` lines) that the CI demo smoke and two built-bin e2es grepped, and an inverted example composition where the flagship `tui-agent` leaf was defined as an include-patch over the `repl-agent` leaf it superseded. + +## Decision + +Delete the readline front door and the repl-agent example; keep exactly three front-door archetypes: **interactive TUI** (TTY-only, fails loud on pipes), **one-shot CLI** (`-p`/positional task, pipes and automation), and **servers** (ACP / JSON-RPC). + +- `packages/ui/stdio` and `examples/repl-agent` are gone. `packages/examples/stdio-demo` is renamed `@deepseek-ai/dsh-tui-demo` (`packages/examples/tui-demo`) and always mounts `dsh-tui`; the `TerminalMode`/`resolveTerminalMode`/`ui.mode` seam is deleted. The bin refuses non-TTY streams **before booting the Loader** (a compose-time throw inside a Loader tree is logged per-entry, not rethrown, so a piped launch would otherwise settle into an idle UI-less process instead of exiting nonzero). +- `examples/tui-agent/cordis.yml` now owns the coding composition inline (the include-patch inversion is gone); its Code Mode overlay includes its own base. `examples/cordis-agent` moved to the TUI app. +- `examples/echo-agent` moved to the one-shot `dsh-cli-demo` app; `dsh-cli-demo` gained `-p/--prompt` as the flag form of the single task (mutually exclusive with the positional). +- The UI-independent with-key coding e2es (`full-loop`, `coding-task`, `resume`, `compaction`, `todo-write`, `code-mode` and their shared harness) moved verbatim from `examples/repl-agent/tests/` to `examples/tui-agent/tests/` — they assemble the stack programmatically and never touched a UI. +- The SDK wizard's `stdio` run interface became `tui` (`RunInterface = 'acp' | 'tui' | 'embed'`), contributing a `dsh-tui` entry instead of `dsh-stdio`; the generated `index.ts` guards TTY before `startSDK` for the same pre-boot fail-loud reason as the tui-demo bin. + +### Testing policy: PTY only for the TUI + +Pipes remain the default test medium. PTY-driven subprocess tests are sanctioned **only** where the subject is the TUI itself: `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` (which gained the Code Mode overlay boot scenario, replacing repl-agent's pipe smoke as the overlay's keyless composition proof) and the minimal PTY boot smoke in `examples/cordis-agent` (whose front door IS the TUI). Everything else moved to pipes over the one-shot bin: + +- `examples/echo-agent/tests/echo.e2e.ts` proves the Loader boot + mock-model tool round-trip through `stream-json` records instead of readline transcript lines. +- The CI demo-smoke gate (`scripts/run-gates.ts`, AGENTS.md) runs `demo:echo --output-format stream-json -p "echo ci smoke"` and parses the records structurally. +- `packages/examples/tui-demo/tests/built-bin.e2e.ts` proves the built bin's piped-launch refusal (nonzero exit + pointer at `dsh-cli-demo`); the echo-round-trip-under-plain-Node and missing-config fail-loud proofs live in `cli-demo`'s built-bin suite. +- `packages/context/time-context/tests/time-context.e2e.ts` runs one one-shot turn; multi-turn elapsed rendering stays unit-covered in its spec. + +## Accepted losses + +- **Piped multi-turn in one process** — the readline channel could script several turns over stdin; the one-shot bin runs one task per process. Multi-turn continuity is covered by `RESUME_SESSION_ID`/resume e2es and the TUI's scripted PTY conversation. +- **Non-TTY `ask_user_question`** — the readline provider was the only non-TTY terminal implementation of `ctx.userInteraction`. A headless run whose model calls `ask_user_question` now fails that tool call (no provider); the ACP bridge remains the non-terminal provider. A future headless deployment that needs it composes its own provider. + +## Alternatives considered + +- **Keep `dsh-stdio` as a pipe/automation channel without the repl demo** — rejected: its automation role duplicated `dsh-cli-demo` with a weaker contract (unstructured transcript, EOF-exit heuristics vs. one durable turn ending and format-pure output). +- **Rewrite the piped smokes as PTY drivers** — rejected: PTY is the flakier, more complex medium and is reserved for the one surface pipes cannot prove (real TTY takeover/restore). + +## Consequences + +- One interactive front door (TUI), one automation front door (one-shot CLI), two servers; no mode-selection seam in the terminal app. +- ~1,000 lines of readline unit tests deleted with their behavior; the readline transcript grammar is gone from all gates. +- This supersedes the packaging half of [fold the stdio UI helper](2026-07-04-fold-stdio-ui-helper.md) (the folded package is now deleted) and amends the composition described in [the TUI front-door note](../feature/2026-07-17-dedicated-full-screen-tui-front-door.md) (no `auto` selection; `tui-agent` owns the coding composition). diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md new file mode 100644 index 0000000000..cf4d03594e --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md @@ -0,0 +1,46 @@ +# Agent Note: 退役 readline 前端与 repl-agent 示例 + +Status: implemented + +[English](2026-07-20-retire-readline-front-door.md) | 中文 + +## 问题 + +仓库同时提供两个交互式终端前端:面向行的 readline 通道(`@deepseek-ai/dsh-stdio`)和全屏的 [`@deepseek-ai/dsh-tui`](../feature/2026-07-17-dedicated-full-screen-tui-front-door.md)。TUI 落地之后,readline 的交互角色已经冗余——`demo:tui` 作为编码 agent 体验取代了 `demo:repl`——而它剩下的真实角色(管道与自动化)已由单次任务的 `@deepseek-ai/dsh-cli-demo` 应用以更好的方式承担(任务输入、DSH 原生 `text`/`json`/`stream-json` 输出、持久化、信号处理)。 + +这种重复是结构性的,不只是表面问题:`dsh-stdio-demo` 携带一个 `TerminalMode`(`auto`/`readline`/`tui`)选择接缝、约 1,000 行 readline 单元测试、一套被 CI 演示冒烟测试和两个 built-bin e2e 用 grep 匹配的 readline 文本记录语法(`[tool call] …` 行),以及一个倒置的示例组合:旗舰 `tui-agent` 叶节点被定义为对它所取代的 `repl-agent` 叶节点的 include patch。 + +## 决定 + +删除 readline 前端和 repl-agent 示例;只保留三类前端原型:**交互式 TUI**(仅 TTY,管道下快速失败)、**单次任务 CLI**(`-p`/位置参数任务,服务管道与自动化)以及**服务器**(ACP / JSON-RPC)。 + +- `packages/ui/stdio` 与 `examples/repl-agent` 已删除。`packages/examples/stdio-demo` 更名为 `@deepseek-ai/dsh-tui-demo`(`packages/examples/tui-demo`)并始终挂载 `dsh-tui`;`TerminalMode`/`resolveTerminalMode`/`ui.mode` 接缝随之删除。bin 在**启动 loader 之前**就拒绝非 TTY 流(Loader 树内组合期抛出的异常按条目记录日志而不会重新抛出,管道启动否则会沉降为一个空闲的无 UI 进程而不是以非零码退出)。 +- `examples/tui-agent/cordis.yml` 现在内联拥有编码组合(include patch 倒置消失);其 Code Mode 覆盖层 include 自己的基础配置。`examples/cordis-agent` 迁移到 TUI 应用。 +- `examples/echo-agent` 迁移到单次任务的 `dsh-cli-demo` 应用;`dsh-cli-demo` 新增 `-p/--prompt` 作为单个任务的旗标形式(与位置参数互斥)。 +- 与 UI 无关的带密钥编码 e2e(`full-loop`、`coding-task`、`resume`、`compaction`、`todo-write`、`code-mode` 及其共享 harness)原样从 `examples/repl-agent/tests/` 移入 `examples/tui-agent/tests/`——它们以编程方式组装整个栈,从不接触任何 UI。 +- SDK 向导的 `stdio` 运行接口改为 `tui`(`RunInterface = 'acp' | 'tui' | 'embed'`),贡献 `dsh-tui` 配置项而不是 `dsh-stdio`;生成的 `index.ts` 在 `startSDK` 之前检查 TTY,理由与 tui-demo bin 的启动前快速失败相同。 + +### 测试策略:PTY 仅用于 TUI + +管道仍是默认测试介质。PTY 驱动的子进程测试**仅**在被测对象就是 TUI 本身时获准使用:`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts`(新增 Code Mode 覆盖层启动场景,取代 repl-agent 的管道冒烟测试成为该覆盖层的无密钥组合证明)和 `examples/cordis-agent` 中最小的 PTY 启动冒烟测试(其前端就是 TUI)。其余全部改为通过单次任务 bin 走管道: + +- `examples/echo-agent/tests/echo.e2e.ts` 通过 `stream-json` 记录证明 Loader 启动 + mock 模型的工具往返,而不是匹配 readline 文本记录行。 +- CI 演示冒烟门禁(`scripts/run-gates.ts`、AGENTS.md)运行 `demo:echo --output-format stream-json -p "echo ci smoke"` 并结构化解析记录。 +- `packages/examples/tui-demo/tests/built-bin.e2e.ts` 证明构建产物 bin 对管道启动的拒绝(非零退出 + 指向 `dsh-cli-demo` 的提示);纯 Node 下的 echo 往返证明与缺失配置的快速失败证明位于 `cli-demo` 的 built-bin 套件。 +- `packages/context/time-context/tests/time-context.e2e.ts` 运行一个单次任务轮次;多轮 elapsed 渲染仍由其单元测试覆盖。 + +## 接受的损失 + +- **单进程内的管道多轮对话**——readline 通道可以通过 stdin 脚本化多个轮次;单次任务 bin 每个进程只运行一个任务。多轮连续性由 `RESUME_SESSION_ID`/resume e2e 和 TUI 的脚本化 PTY 对话覆盖。 +- **非 TTY 的 `ask_user_question`**——readline 提供方是 `ctx.userInteraction` 唯一的非 TTY 终端实现。模型调用 `ask_user_question` 的 headless 运行现在会让该工具调用失败(没有提供方);ACP 桥接仍是非终端提供方。未来需要它的 headless 部署自行组合提供方。 + +## 曾考虑的替代方案 + +- **保留 `dsh-stdio` 作为纯管道/自动化通道而只删 repl 演示**——不予采纳:它的自动化角色以更弱的契约重复了 `dsh-cli-demo`(非结构化文本记录、EOF 退出的启发式判断,对比后者的一次持久轮次结束和格式纯净输出)。 +- **把管道冒烟测试改写为 PTY 驱动**——不予采纳:PTY 是更易波动、更复杂的介质,仅保留给管道无法证明的那一个表面(真实 TTY 的接管/恢复)。 + +## 后果 + +- 一个交互式前端(TUI)、一个自动化前端(单次任务 CLI)、两个服务器;终端应用不再有模式选择接缝。 +- 约 1,000 行 readline 单元测试随其行为一起删除;readline 文本记录语法从所有门禁中消失。 +- 本决定取代 [fold the stdio UI helper](2026-07-04-fold-stdio-ui-helper.md) 的打包部分(被折叠的包现已删除),并修订 [TUI 前端 Agent Note](../feature/2026-07-17-dedicated-full-screen-tui-front-door.md) 描述的组合(不再有 `auto` 选择;`tui-agent` 拥有编码组合)。 diff --git a/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.i18n.yaml new file mode 100644 index 0000000000..62bf9574c0 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-remove-cancel-command.md: f9bad74e7b8f04a162a32e8045d2f874991b9d5d +2026-07-21-tui-remove-cancel-command.zh.md: 6a4c0af1d2ac345afd775566db21f7a7c0b262da diff --git a/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.md b/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.md new file mode 100644 index 0000000000..f9bad74e7b --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.md @@ -0,0 +1,25 @@ +# Agent Note: Drop the TUI `/cancel` slash command + +Status: implemented + +English | [中文](2026-07-21-tui-remove-cancel-command.zh.md) + +## Problem + +The TUI exposed two identical ways to cancel a running turn: the `Esc` (and `Ctrl+C`) keybinding and a `/cancel` slash command. Both called `agent.cancel('cancelled from terminal')` with the same reason; when idle, `/cancel` only printed a "The agent is already idle." notice while the keybindings stayed silent. The running status line already advertises the keybinding (`Enter sends steering, Esc cancels`), and cancelling by keystroke needs no editor submission, so the slash command was a second, less discoverable path to the same effect — surface area with no behavior of its own. + +## Decision + +`/cancel` is removed. Cancelling a running turn is a keybinding-only affordance (`Esc`, or `Ctrl+C` while running), which the status-line hint and the `/help` shortcut list already document. The `baseCommands` autocomplete entry, the `/help` command line, the `case '/cancel'` branch in the editor submit handler, and the "already idle" notice it owned are gone; every other slash command (`/help`, `/clear`, `/reasoning`, `/tools`, `/redraw`, `/reload`, `/resume`, `/exit`, `/skill:`) is unchanged. Typing `/cancel` now falls through to the generic `Unknown command:` warning like any other unrecognized slash input. + +## Alternatives considered + +**Keep `/cancel` as a discoverability alias** — rejected: the running status line and `/help` both name `Esc`, so a typed alias adds a maintained code path and a per-idle-state notice for an action a single keystroke already performs more directly. No consumer needed the editor-submission route to cancellation. + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` asserts `agent.cancelled` contains `'cancelled from terminal'`, driven by the `Esc`/`Ctrl+C` keystrokes in that turn — the sole cancel affordance. The `errors-and-help` and `disposed-terminal` snapshots pin the `/help` line without `/cancel`; per-file coverage on `packages/ui/tui/src` stays at 100%. + +## Consequences + +There is no way to cancel a turn by editor submission; cancellation is keybinding-only. This is a net removal of a redundant path and its idle-state notice, matching the single-primitive shape the rest of the stop surface already follows ([public stop surface](2026-06-20-public-agent-stop-surface.md)). Restoring a typed cancel would return with the autocomplete entry, the submit-handler branch, and its own test. diff --git a/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.zh.md b/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.zh.md new file mode 100644 index 0000000000..6a4c0af1d2 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-21-tui-remove-cancel-command.zh.md @@ -0,0 +1,25 @@ +# Agent Note: Drop the TUI `/cancel` slash command + +Status: implemented + +[English](2026-07-21-tui-remove-cancel-command.md) | 中文 + +## Problem + +TUI 提供了两条完全相同的取消运行中轮次的方式:`Esc`(以及 `Ctrl+C`)键位绑定,和一条 `/cancel` 斜杠命令。两者都以相同的原因调用 `agent.cancel('cancelled from terminal')`;空闲时 `/cancel` 只打印一条 "The agent is already idle." 通知,而键位绑定保持静默。运行状态行本就标示了该键位绑定(`Enter sends steering, Esc cancels`),且按键取消无需提交编辑器,因此这条斜杠命令只是通往同一效果的第二条、且更难被发现的路径——一块本身不含任何行为的界面。 + +## Decision + +`/cancel` 已移除。取消运行中的轮次是一项仅由键位绑定提供的能力(`Esc`,或运行中的 `Ctrl+C`),状态行提示与 `/help` 快捷键清单已对其作出说明。`baseCommands` 自动补全条目、`/help` 命令行、编辑器提交处理函数中的 `case '/cancel'` 分支,以及它拥有的 "already idle" 通知都已删去;其余每一条斜杠命令(`/help`、`/clear`、`/reasoning`、`/tools`、`/redraw`、`/reload`、`/resume`、`/exit`、`/skill:`)保持不变。键入 `/cancel` 会像任何其他无法识别的斜杠输入一样,落入通用的 `Unknown command:` 警告。 + +## Alternatives considered + +**保留 `/cancel` 作为便于发现的别名。** 否决:运行状态行与 `/help` 都已标示 `Esc`,因此一个键入式别名会为一项单个按键已能更直接完成的操作,增加一条需维护的代码路径和一条逐空闲状态的通知。没有任何消费方需要经由编辑器提交来触发取消。 + +## Testing + +`packages/ui/tui/tests/tui.spec.ts` 断言 `agent.cancelled` 包含 `'cancelled from terminal'`,由该轮次中的 `Esc`/`Ctrl+C` 按键驱动——这是唯一的取消能力。`errors-and-help` 与 `disposed-terminal` 快照固定了不含 `/cancel` 的 `/help` 行;`packages/ui/tui/src` 的逐文件覆盖率维持在 100%。 + +## Consequences + +无法再经由编辑器提交取消一个轮次;取消仅由键位绑定提供。这是对一条冗余路径及其空闲状态通知的净移除,与其余停止能力已遵循的单一原语形态一致([public stop surface](2026-06-20-public-agent-stop-surface.md))。若要恢复键入式取消,需连同自动补全条目、提交处理函数分支及其专属测试一并回归。 diff --git a/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.i18n.yaml new file mode 100644 index 0000000000..4e0393bede --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.i18n.yaml @@ -0,0 +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 +2026-07-21-tui-todo-write-opt-in.md: f89f76a462f4d30960254833ab71973f6a4f7655 +2026-07-21-tui-todo-write-opt-in.zh.md: f80d2639612819975f03aea9771019cd5237a2ee diff --git a/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.md b/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.md new file mode 100644 index 0000000000..f89f76a462 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.md @@ -0,0 +1,27 @@ +# Agent Note: Ship the TUI without `todo_write`; keep it a one-line opt-in + +Status: implemented + +English | [中文](2026-07-21-tui-todo-write-opt-in.zh.md) + +## Problem + +The shipped tui-agent `cordis.yml` loaded `@deepseek-ai/dsh-tool-todo`, exposing `todo_write` by default. The tool is a task-tracking convenience, not a core coding affordance like `bash` or the `read`/`write`/`edit` fs tools; most TUI sessions never call it, yet shipping it enlarges the wire tool list and system prompt for every turn. Meanwhile the TUI's plan rendering is event-driven: `packages/ui/tui/src/index.ts` listens for the `todo/write` session event and `TodoComponent.render` returns nothing when the list is empty, so the front door already tolerates the tool being absent or present with no runtime coupling to the plugin. + +## Decision + +The tui-agent `cordis.yml` no longer loads `tool-todo`; `todo_write` is opt-in. The `code-mode.cordis.yml` overlay inherits the base composition, so its generated SDK drops `todo_write` too. Enabling it is one entry — add `@deepseek-ai/dsh-tool-todo` to `cordis.yml` (or a `~/.dsh` personal overlay) — after which the model logs the whole-list `todo/write` snapshot and the TUI renders the plan, unchanged. The `TodoItem` type and the `todo/write` event stay in `@deepseek-ai/dsh-session` and the TUI's plan rendering stays wired, so both the default (disabled) and opt-in (enabled) paths are first-class. The sibling acp-agent, headless-agent, and jsonrpc-agent examples still ship the tool. + +## Alternatives considered + +**Keep `todo_write` in the shipped TUI default** — rejected: it is an opt-in convenience, not a core tool, and shipping it spends every turn's tool-list and prompt budget on a feature most sessions ignore. The examples that still ship it retain the plugin's real-composition coverage. + +**Drop the TUI's plan rendering and todo tests along with the default entry** — rejected: the requirement is to support both the enabled and disabled cases, and the event-driven `TodoComponent` already renders plans with zero plugin coupling, so deleting it would discard a working capability for no gain. The enabled path keeps dedicated coverage instead. + +## Testing + +`examples/tui-agent/tests/tui.snapshot.ts` mounts `ToolTodo` only when a scenario sets `enableTodo`: only the `todo-plan` scenario does (the enabled-path proof, whose `session.jsonl`/`terminal.expected.txt` pin the rendered plan), while every other scenario runs the default todo-free composition. `tests/harness.ts` makes `ToolTodo` a `todo` opt-in that only `tests/todo-write.e2e.ts` sets, so the with-key todo e2e still drives the real tool while the other suites match the shipped stack. The keyless `tests/tui-keyless-smoke.e2e.ts` boots the real `cordis.yml` and asserts nothing about todo, so the default boot is unaffected. + +## Consequences + +The default TUI wire tool list and system prompt shrink by one tool; a session that wants task tracking adds one plugin entry. `examples/tui-agent/composition.md` (regenerated) and its leaf-entry table no longer list `tool-todo`, and the curated summary in `scripts/gen-doc-graphs.ts` drops it. The `@deepseek-ai/dsh-tool-todo` package is unchanged and still shipped by the acp/headless/jsonrpc examples, so its coverage requirement is met there. Restoring the default would re-add the one `cordis.yml` entry and flip the snapshot/harness opt-in flags back on. diff --git a/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.zh.md b/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.zh.md new file mode 100644 index 0000000000..f80d263961 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-21-tui-todo-write-opt-in.zh.md @@ -0,0 +1,27 @@ +# Agent Note: Ship the TUI without `todo_write`; keep it a one-line opt-in + +Status: implemented + +[English](2026-07-21-tui-todo-write-opt-in.md) | 中文 + +## Problem + +出厂的 tui-agent `cordis.yml` 加载了 `@deepseek-ai/dsh-tool-todo`,默认向模型暴露 `todo_write`。这个工具是一项任务追踪的便利功能,而非像 `bash` 或 `read`/`write`/`edit` 文件系统工具那样的核心编码能力;多数 TUI 会话从不调用它,但出厂加载它会让每一轮的协议工具列表和系统提示词都随之变大。而 TUI 的计划渲染是事件驱动的:`packages/ui/tui/src/index.ts` 监听 `todo/write` 会话事件,`TodoComponent.render` 在列表为空时不返回任何内容,因此这个入口本就能容忍该工具的缺席或存在,与该插件没有任何运行时耦合。 + +## Decision + +tui-agent `cordis.yml` 不再加载 `tool-todo`;`todo_write` 改为可选启用。`code-mode.cordis.yml` 覆盖配置继承基础组合,因此它生成的 SDK 同样不再包含 `todo_write`。启用它只需一条配置项——把 `@deepseek-ai/dsh-tool-todo` 加入 `cordis.yml`(或 `~/.dsh` 的个人覆盖配置)——此后模型照旧记录整份清单的 `todo/write` 快照,TUI 照旧渲染该计划。`TodoItem` 类型与 `todo/write` 事件仍留在 `@deepseek-ai/dsh-session`,TUI 的计划渲染也保持接线,因此默认(禁用)与可选启用(启用)两条路径都是一等公民。同类的 acp-agent、headless-agent、jsonrpc-agent 示例仍然出厂携带该工具。 + +## Alternatives considered + +**在出厂的 TUI 默认配置中保留 `todo_write`。** 否决:它是一项可选启用的便利功能,而非核心工具,出厂加载它会为多数会话都忽略的功能花掉每一轮的工具列表与提示词预算。仍然携带它的示例保留了该插件的真实组合覆盖。 + +**连同默认配置项一起删掉 TUI 的计划渲染与 todo 测试。** 否决:需求是同时支持启用与禁用两种情形,而事件驱动的 `TodoComponent` 本就在零插件耦合下渲染计划,删掉它等于白白丢弃一项可用能力。取而代之,启用路径保留专门的覆盖。 + +## Testing + +`examples/tui-agent/tests/tui.snapshot.ts` 根据逐场景的 `enableTodo` 开关决定是否挂载 `ToolTodo`:只有 `todo-plan` 场景挂载它(启用路径的证明,其 `session.jsonl`/`terminal.expected.txt` 固定了渲染出的计划),其余每个场景都运行默认的无 todo 组合。`tests/harness.ts` 把 `ToolTodo` 做成一个 `todo` 可选项,只有 `tests/todo-write.e2e.ts` 会开启它,因此带密钥的 todo e2e 仍然驱动真实工具,而其余套件与出厂技术栈保持一致。无密钥的 `tests/tui-keyless-smoke.e2e.ts` 启动真实的 `cordis.yml`,且不对 todo 作任何断言,因此默认启动不受影响。 + +## Consequences + +默认 TUI 的协议工具列表和系统提示词少了一个工具;想要任务追踪的会话加一条插件配置项即可。`examples/tui-agent/composition.md`(已重新生成)及其叶子条目表不再列出 `tool-todo`,`scripts/gen-doc-graphs.ts` 中人工维护的摘要也去掉了它。`@deepseek-ai/dsh-tool-todo` 包本身没有变动,仍由 acp/headless/jsonrpc 示例出厂携带,因此它的覆盖需求在那里得到满足。若要恢复默认,只需重新加入那一条 `cordis.yml` 配置项,并把快照/harness 的可选开关重新打开。 diff --git a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.i18n.yaml new file mode 100644 index 0000000000..72e2341385 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.i18n.yaml @@ -0,0 +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 +2026-07-22-tui-titles-from-session-title-service.md: b54b99647230255cf241415f94aa21b2630c44cd +2026-07-22-tui-titles-from-session-title-service.zh.md: 67cc3332f0694887d5af0d71997d140b74669f46 diff --git a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.md b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.md new file mode 100644 index 0000000000..b54b996472 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.md @@ -0,0 +1,25 @@ +# Agent Note: TUI titles come from the session-title service + +Status: implemented + +English | [中文](2026-07-22-tui-titles-from-session-title-service.zh.md) + +## Problem + +Two model-title implementations coexisted after the tui-staging line merged onto master. The TUI carried its own `autoTitle` feature: a fire-and-forget `ctx.llm.stream` call after the first user message that set the terminal window title via OSC 0, with a one-shot latch, its own prompt, its own 40-character cap, and its own resume re-derivation ([auto-title Agent Note](../feature/2026-07-21-tui-auto-pane-title.md), [default-on Agent Note](../feature/2026-07-21-tui-auto-title-default-on.md)). Master had meanwhile landed [log-backed session titles](../feature/2026-07-21-log-backed-session-titles.md): a `sessionTitle` capability whose accepted revisions are durable `session/title` events, with a deterministic fallback and optional model providers. The TUI already consumed `session/title` for its header subtitle and window title, so a session could be titled twice by different strategies, and the TUI's process-local title was invisible to every other consumer (ACP, resume listings, forks). + +## Decision + +The TUI-local generation is removed; the session-title service is the one title source. `TuiConfig.autoTitle`, the latch, the abort controller, the title prompt, and `titleLine` are gone from `dsh-tui`. The terminal rename stays: the TUI folds the latest logged title on mount (`foldSessionTitle`), renders it as the banner subtitle, and sets the terminal window title to `` on every accepted `session/title` event — including resumed sessions, whose titles now replay from the log instead of being re-generated. + +Model-made titles are a composition choice: `examples/tui-agent/cordis.yml` (and the scripted PTY fixture) mount `@deepseek-ai/dsh-session-title-first-message-llm`, which inherits the main request's route and replaces the spine's deterministic fallback with a short model summary. Deployments without the provider keep the fallback title from `dsh-agent-spine-demo`'s bundled `SessionTitleService`. + +## Alternatives considered + +**Keep both, letting the logged title win.** This was the first merge resolution: auto-title owned the whole window title until a logged `session/title` arrived in suffix form. It preserved behavior but doubled the model calls on every fresh session and left the TUI's title unobservable in the log, violating model-visible ⟺ logged in spirit and splitting the title contract across two owners. + +**Port auto-title's prompt and cap into the service as a third provider.** The first-message-llm provider already exists with the same cadence, a reviewed prompt contract, durable request records, and supersession fencing; a second near-identical provider would be pure duplication. + +## Consequences + +One title pipeline: durable, replayable, visible to every consumer, and fenced against stale completions by the service. The TUI sheds ~90 lines and its `llm`-streaming path. The cost is that a title now requires the provider plugin in the composition for model quality — a leaf choice, not a TUI default — and the terminal title changes shape from the bare model summary to the suffixed ` — <product>` form the log-backed path always used. The superseded auto-title Agent Notes carry pointers here. diff --git a/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.zh.md b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.zh.md new file mode 100644 index 0000000000..67cc3332f0 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-07-22-tui-titles-from-session-title-service.zh.md @@ -0,0 +1,25 @@ +# Agent Note: TUI 标题来自 session-title 服务 + +Status: implemented + +[English](2026-07-22-tui-titles-from-session-title-service.md) | 中文 + +## 问题 + +tui-staging 分支合入 master 后,两套模型标题实现并存。TUI 自带 `autoTitle` 特性:在首条用户消息后发起一次 fire-and-forget 的 `ctx.llm.stream` 调用,通过 OSC 0 设置终端窗口标题,带有一次性闩锁、自己的提示词、自己的 40 字符截断和自己的恢复重推导([auto-title Agent Note](../feature/2026-07-21-tui-auto-pane-title.md)、[default-on Agent Note](../feature/2026-07-21-tui-auto-title-default-on.md))。而 master 已落地[日志承载的会话标题](../feature/2026-07-21-log-backed-session-titles.md):一个 `sessionTitle` 能力,其被接受的修订是持久的 `session/title` 事件,带确定性回退和可选的模型 provider。TUI 已经消费 `session/title` 作为横幅副标题和窗口标题,于是一个会话可能被两种策略各标题一次,且 TUI 的进程本地标题对其他所有消费者(ACP、恢复列表、fork)不可见。 + +## 决策 + +移除 TUI 本地生成;session-title 服务是唯一的标题来源。`TuiConfig.autoTitle`、闩锁、abort controller、标题提示词和 `titleLine` 全部从 `dsh-tui` 删除。终端重命名保留:TUI 在挂载时折叠最新的已记录标题(`foldSessionTitle`),将其渲染为横幅副标题,并在每个被接受的 `session/title` 事件上把终端窗口标题设为 `<会话标题> — <配置标题>` —— 包括恢复的会话,其标题现在从日志回放而不是重新生成。 + +模型生成的标题是组合选择:`examples/tui-agent/cordis.yml`(以及脚本化 PTY fixture)挂载 `@deepseek-ai/dsh-session-title-first-message-llm`,它继承主请求的确切路由,用简短的模型摘要替换 spine 的确定性回退。未挂载该 provider 的部署保留 `dsh-agent-spine-demo` 内置 `SessionTitleService` 的回退标题。 + +## 备选方案 + +**两者并存,已记录标题胜出。** 这是第一版合并决议:auto-title 独占整个窗口标题,直到已记录的 `session/title` 以后缀形式到达。它保留了行为,但每个新会话产生双倍模型调用,且 TUI 的标题在日志中不可观察,实质上违反 model-visible ⟺ logged,并把标题契约拆给两个所有者。 + +**把 auto-title 的提示词和截断移植为服务的第三个 provider。** first-message-llm provider 已经存在,节奏相同,且有经过评审的提示词契约、持久的请求记录和替换围栏;再造一个近乎相同的 provider 纯属重复。 + +## 影响 + +标题管线归一:持久、可回放、对所有消费者可见,并由服务对过期完成设防。TUI 削减约 90 行及其 `llm` 流式路径。代价是模型质量的标题现在需要在组合中挂载 provider 插件 —— 这是叶配置选择,不是 TUI 默认值 —— 且终端标题形状从裸模型摘要变为日志路径一贯使用的 `<标题> — <产品>` 后缀形式。被取代的 auto-title Agent Note 携带指向本文的指针。 diff --git a/.agents/skills/dsh-doc-site-sync/SKILL.md b/.agents/skills/dsh-doc-site-sync/SKILL.md index bee1b0dfe8..4d88d3f04f 100644 --- a/.agents/skills/dsh-doc-site-sync/SKILL.md +++ b/.agents/skills/dsh-doc-site-sync/SKILL.md @@ -24,7 +24,7 @@ Repository translations follow the sibling pairing contract: English `foo.md`, C - **Publish a generated catalog:** map the generated `docs/` file, but change its generator or source metadata rather than editing the catalog by hand. - **Change site structure:** update the manifest for ordinary pages; update VitePress configuration only when the existing sidebar, section, or locale model cannot express the change. -Never edit or commit `website/.generated/`, `website/.cache/`, or `website/.dist/`. Never copy a maintained `docs/` page into `website/`. +Never edit or commit `website/.generated/`, `website/.cache/`, or `website/.dist/`. Except for `website/AGENTS.md`, never add Markdown under `website/`; locale and route directories such as `website/zh-CN/`, `website/en/`, and `website/api/` are invalid source layouts. Keep generated catalogs under `docs/`, freshness-gate them there, and publish them through the manifest. ## Add or update a manifest entry diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index de9a03288b..f52274cddd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,8 +2,18 @@ name: CI on: push: - branches: [main, master] + branches: [master] pull_request: + workflow_dispatch: + inputs: + suite: + description: Manual CI suite to run + required: true + default: larger-runner-benchmark + type: choice + options: + - larger-runner-benchmark + - consolidated-runner-benchmark concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -16,106 +26,89 @@ env: PRIMARY_NODE_VERSION: '24' jobs: + + # One large runner pays hosted setup once, then the repository scheduler + # overlaps the complete unsharded primary Node inventory. Build starts eagerly; + # only consumers of emitted output wait for it. node-24: - runs-on: ubuntu-latest - name: node 24 / ${{ matrix.lane }} + if: github.event_name == 'pull_request' + runs-on: dsh-ubuntu-24-04-96core + name: node 24 / complete env: - DSH_GATE_CONCURRENCY: ${{ matrix.gate_concurrency }} - DSH_PUBLINT_CONCURRENCY: ${{ matrix.publint_concurrency }} - DSH_COVERAGE_MAX_WORKERS: ${{ matrix.coverage_max_workers }} - DSH_ESLINT_CACHE: ${{ matrix.eslint_cache }} - strategy: - fail-fast: false - matrix: - include: - - lane: static - command: pnpm run check:ci:static - gate_concurrency: '4' - publint_concurrency: '8' - coverage_max_workers: '' - eslint_cache: '' - - lane: lint - command: pnpm run check:ci:lint - gate_concurrency: '1' - publint_concurrency: '8' - coverage_max_workers: '' - eslint_cache: '1' - - lane: coverage - command: pnpm run check:ci:coverage - gate_concurrency: '1' - publint_concurrency: '8' - coverage_max_workers: '4' - eslint_cache: '' - - lane: snapshot - command: pnpm run check:ci:snapshot - gate_concurrency: '1' - publint_concurrency: '8' - coverage_max_workers: '' - eslint_cache: '' - - lane: artifacts - command: pnpm run check:ci:artifacts - gate_concurrency: '3' - publint_concurrency: '8' - coverage_max_workers: '' - eslint_cache: '' + DSH_COVERAGE_MAX_WORKERS: '16' + DSH_ESLINT_CACHE: '1' + DSH_ESLINT_CONCURRENCY: '16' + DSH_GATE_CONCURRENCY: '10' + DSH_PUBLINT_CONCURRENCY: '16' + DSH_SNAPSHOT_MAX_CONCURRENCY: '8' steps: - uses: actions/checkout@v6 - - - uses: actions/setup-node@v6 with: - node-version: ${{ env.PRIMARY_NODE_VERSION }} + persist-credentials: false - - name: Enable corepack (pnpm) - run: corepack enable - - - name: Resolve pnpm store path - id: pnpm-store - run: echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" - - - uses: actions/cache@v4 + # Pull requests consume the default-branch cache but do not put cache + # compression and upload on the paid latency-critical path. + - uses: actions/cache/restore@v4 with: - path: ${{ steps.pnpm-store.outputs.path }} + path: /home/runner/.local/share/pnpm/store/v11 key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- - - name: Install (immutable) - run: pnpm install --frozen-lockfile - - # The snapshot lane REPLAYS the sandbox example's recorded scenarios, - # re-executing their bash calls under a real runner. ubuntu-latest has - # no bubblewrap preinstalled and no built Landlock launcher, so without - # this the confined executions fail closed (SANDBOX_UNAVAILABLE). Same - # install as sandbox.yml's bwrap leg (incl. the Ubuntu 24.04 AppArmor - # userns knob). - - name: Install bubblewrap (unrestrict userns) - if: matrix.lane == 'snapshot' - run: | - sudo apt-get update -q - sudo apt-get install -yq bubblewrap - sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 \ - || echo "apparmor userns knob absent — the functional probe decides" - - - uses: actions/cache@v4 - if: matrix.lane == 'lint' + - uses: actions/cache/restore@v4 with: path: .cache/eslint - key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-${{ hashFiles('pnpm-lock.yaml', 'eslint.config.mjs', 'tsconfig.json', 'packages/*/*/tsconfig.json', 'examples/*/tsconfig.json') }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full-${{ hashFiles('pnpm-lock.yaml', 'eslint.config.mjs', 'tsconfig.json', 'packages/*/*/tsconfig.json', 'examples/*/tsconfig.json') }} restore-keys: | - ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint- + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full- + + - name: Select preinstalled Node, install dependencies, and prepare bubblewrap + run: | + node_root="$(printf '%s\n' "$RUNNER_TOOL_CACHE"/node/"${PRIMARY_NODE_VERSION}".*/x64 | sort -V | tail -n 1)" + if [[ ! -d "$node_root" ]]; then + echo "preinstalled Node ${PRIMARY_NODE_VERSION}.x not found in $RUNNER_TOOL_CACHE" >&2 + exit 1 + fi + echo "$node_root/bin" >> "$GITHUB_PATH" + export PATH="$node_root/bin:$PATH" + [[ "$(node --version)" == "v${PRIMARY_NODE_VERSION}."* ]] + corepack enable + pnpm install --frozen-lockfile & + install_pid=$! + bash scripts/prepare-ci-bubblewrap.sh & + sandbox_pid=$! + install_status=0 + wait "$install_pid" || install_status=$? + sandbox_status=0 + wait "$sandbox_pid" || sandbox_status=$? + if (( install_status != 0 )); then exit "$install_status"; fi + exit "$sandbox_status" + + - name: Run complete unsharded primary Node CI concurrently + run: pnpm run check:ci - - name: Run gates - run: ${{ matrix.command }} node-compat: - runs-on: ubuntu-latest - name: node ${{ matrix.node }} + if: github.event_name == 'pull_request' + # Distinct larger-runner pools avoid both standard-runner setup outliers and + # delayed allocation when independent environment contracts share one pool. + runs-on: ${{ matrix.runner }} + name: ${{ matrix.name }} env: - DSH_GATE_CONCURRENCY: '2' + DSH_GATE_CONCURRENCY: ${{ matrix.gate_concurrency }} + DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' strategy: fail-fast: false matrix: - node: ['22.19', 24, 26] + include: + - node: '22.19' + name: node 22.19 + runner: dsh-ubuntu-24-04-4core + gate_concurrency: '2' + - node: 26 + name: node 26 + runner: dsh-ubuntu-24-04-32core + gate_concurrency: '2' steps: - uses: actions/checkout@v6 @@ -123,12 +116,11 @@ jobs: with: node-version: ${{ matrix.node }} - - name: Enable corepack (pnpm) - run: corepack enable - - - name: Resolve pnpm store path + - name: Enable corepack and resolve pnpm store path id: pnpm-store - run: echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" + run: | + corepack enable + echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" - uses: actions/cache@v4 with: @@ -140,11 +132,12 @@ jobs: - name: Install (immutable) run: pnpm install --frozen-lockfile - - name: Run compatibility gates + - name: Run compatibility smokes run: pnpm run check:node-compat python-sdk: - runs-on: ubuntu-latest + if: github.event_name == 'pull_request' + runs-on: dsh-ubuntu-24-04-8core name: python 3.10 / keyless SDK steps: - uses: actions/checkout@v6 @@ -160,12 +153,114 @@ jobs: - name: Run complete keyless Python suite run: uv run --python 3.10 --group test --project python/sdk pytest - # Blocking Windows build lane: keep the already-green native build protected - # while the broader observational gate matrix below exposes the remaining - # portability work without blocking mainline merges. - windows-build: - runs-on: windows-2025 - name: windows / build + # One Windows box shares setup across the required build/site checks and the + # complete observational portability inventory. run-gates reports failures + # from observational gates without allowing them to fail the required job. + windows: + if: github.event_name == 'pull_request' + runs-on: dsh-windows-2025-32core + name: windows node 24 / complete + env: + # Keep ESLint itself single-threaded: 16 ESLint workers took 174 seconds on + # this image. The outer scheduler still overlaps lint with the other gates. + DSH_COVERAGE_MAX_WORKERS: '12' + DSH_ESLINT_CACHE: '1' + DSH_GATE_CONCURRENCY: '16' + DSH_PUBLINT_CONCURRENCY: '16' + steps: + - uses: actions/checkout@v6 + + - uses: actions/cache/restore@v4 + with: + path: .cache/eslint + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full-${{ hashFiles('pnpm-lock.yaml', 'eslint.config.mjs', 'tsconfig.json', 'packages/*/*/tsconfig.json', 'examples/*/tsconfig.json') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full- + + # Extracting the many-file pnpm store cache is slower on this image than + # a clean parallel install, and saving it adds more latency after gates. + - name: Select preinstalled Node and install (immutable) + shell: pwsh + run: | + $nodeRoot = Get-ChildItem -Path "$env:RUNNER_TOOL_CACHE\node" -Directory | + Where-Object { $_.Name -like "$env:PRIMARY_NODE_VERSION.*" } | + Sort-Object { [version]$_.Name } | + Select-Object -Last 1 + if ($null -eq $nodeRoot) { + throw "preinstalled Node $env:PRIMARY_NODE_VERSION.x not found in $env:RUNNER_TOOL_CACHE" + } + $nodeBin = Join-Path $nodeRoot.FullName 'x64' + if (-not (Test-Path $nodeBin -PathType Container)) { + throw "preinstalled Node x64 directory not found at $nodeBin" + } + Add-Content -Path $env:GITHUB_PATH -Value $nodeBin + $env:PATH = "$nodeBin;$env:PATH" + if ((node --version) -notlike "v$env:PRIMARY_NODE_VERSION.*") { + throw "selected unexpected Node version $(node --version)" + } + corepack enable + pnpm install --frozen-lockfile + + - name: Run blocking and observational Windows gates concurrently + shell: pwsh + run: pnpm run check:ci:windows-complete + + # Master pushes run only the serial reference jobs below. + # Each host executes the complete, unsharded primary Node aggregate with one + # gate worker, giving reviewers a simple cross-platform oracle for completeness + # and timing. + serial-linux: + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + name: serial / linux + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Enable corepack and resolve pnpm store path + id: pnpm-store + run: | + corepack enable + echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" + + # Master refreshes the caches that pull requests restore without saving. + - uses: actions/cache@v4 + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - uses: actions/cache@v4 + with: + path: .cache/eslint + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full-${{ hashFiles('pnpm-lock.yaml', 'eslint.config.mjs', 'tsconfig.json', 'packages/*/*/tsconfig.json', 'examples/*/tsconfig.json') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full- + + - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Prepare bubblewrap (unrestrict userns) + run: bash scripts/prepare-ci-bubblewrap.sh + + - name: Run complete unsharded primary Node CI serially + env: + DSH_COVERAGE_MAX_WORKERS: '1' + DSH_E2E_MAX_WORKERS: '1' + DSH_ESLINT_CACHE: '1' + DSH_GATE_CONCURRENCY: '1' + DSH_PUBLINT_CONCURRENCY: '1' + DSH_SNAPSHOT_MAX_CONCURRENCY: '1' + run: pnpm run check:ci + + serial-macos: + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + name: serial / macos + runs-on: macos-latest steps: - uses: actions/checkout@v6 @@ -179,55 +274,19 @@ jobs: - name: Install (immutable) run: pnpm install --frozen-lockfile - - name: Build (tsc -b + tsdown) - run: pnpm run build + - name: Run complete unsharded primary Node CI serially + env: + DSH_COVERAGE_MAX_WORKERS: '1' + DSH_E2E_MAX_WORKERS: '1' + DSH_GATE_CONCURRENCY: '1' + DSH_PUBLINT_CONCURRENCY: '1' + DSH_SNAPSHOT_MAX_CONCURRENCY: '1' + run: pnpm run check:ci - # Observational, non-blocking Windows mirror of the Linux gate lanes. Run the - # gates from native PowerShell: an MSYS parent would change the environment - # being measured. This job intentionally stays out of all-checks-passed.needs. - windows-gates: - continue-on-error: true + serial-windows: + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + name: serial / windows runs-on: windows-2025 - name: windows node 24 / ${{ matrix.lane }} - env: - DSH_GATE_CONCURRENCY: ${{ matrix.gate_concurrency }} - DSH_PUBLINT_CONCURRENCY: ${{ matrix.publint_concurrency }} - DSH_COVERAGE_MAX_WORKERS: ${{ matrix.coverage_max_workers }} - DSH_ESLINT_CACHE: ${{ matrix.eslint_cache }} - strategy: - fail-fast: false - matrix: - include: - - lane: static - command: pnpm run check:ci:static - gate_concurrency: '4' - publint_concurrency: '8' - coverage_max_workers: '' - eslint_cache: '' - - lane: lint - command: pnpm run check:ci:lint - gate_concurrency: '1' - publint_concurrency: '8' - coverage_max_workers: '' - eslint_cache: '1' - - lane: coverage - command: pnpm run check:ci:coverage - gate_concurrency: '1' - publint_concurrency: '8' - coverage_max_workers: '4' - eslint_cache: '' - - lane: snapshot - command: pnpm run check:ci:snapshot - gate_concurrency: '1' - publint_concurrency: '8' - coverage_max_workers: '' - eslint_cache: '' - - lane: artifacts - command: pnpm run check:ci:artifacts - gate_concurrency: '3' - publint_concurrency: '8' - coverage_max_workers: '' - eslint_cache: '' steps: - uses: actions/checkout@v6 @@ -245,12 +304,112 @@ jobs: shell: pwsh run: corepack enable - - name: Resolve pnpm store path - id: pnpm-store + # Master refreshes the small cache that pull requests restore without + # putting package-store extraction back on the Windows critical path. + - uses: actions/cache@v4 + with: + path: .cache/eslint + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full-${{ hashFiles('pnpm-lock.yaml', 'eslint.config.mjs', 'tsconfig.json', 'packages/*/*/tsconfig.json', 'examples/*/tsconfig.json') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full- + + - name: Install (immutable) shell: pwsh - run: '"path=$(pnpm store path --silent)" >> $env:GITHUB_OUTPUT' + run: pnpm install --frozen-lockfile + + - name: Run complete unsharded primary Node CI serially + shell: pwsh + env: + DSH_COVERAGE_MAX_WORKERS: '1' + DSH_E2E_MAX_WORKERS: '1' + DSH_ESLINT_CACHE: '1' + DSH_GATE_CONCURRENCY: '1' + DSH_PUBLINT_CONCURRENCY: '1' + DSH_SNAPSHOT_MAX_CONCURRENCY: '1' + run: pnpm run check:ci + + # Manual, bounded comparison of the actual critical Linux and Windows lanes. + # The named pools are restricted at the organization level to this repository. + larger-runner-benchmark: + if: github.event_name == 'workflow_dispatch' && inputs.suite == 'larger-runner-benchmark' + runs-on: ${{ matrix.runner }} + timeout-minutes: 15 + strategy: + fail-fast: false + max-parallel: 12 + matrix: + include: + - platform: linux + cores: '4' + runner: dsh-ubuntu-24-04-4core + workload: typecheck + - platform: linux + cores: '8' + runner: dsh-ubuntu-24-04-8core + workload: typecheck + - platform: linux + cores: '16' + runner: dsh-ubuntu-24-04-16core + workload: typecheck + - platform: linux + cores: '32' + runner: dsh-ubuntu-24-04-32core + workload: typecheck + - platform: linux + cores: '64' + runner: dsh-ubuntu-24-04-64core + workload: typecheck + - platform: linux + cores: '96' + runner: dsh-ubuntu-24-04-96core + workload: typecheck + - platform: windows + cores: '4' + runner: dsh-windows-2025-4core + workload: production-site + - platform: windows + cores: '8' + runner: dsh-windows-2025-8core + workload: production-site + - platform: windows + cores: '16' + runner: dsh-windows-2025-16core + workload: production-site + - platform: windows + cores: '32' + runner: dsh-windows-2025-32core + workload: production-site + - platform: windows + cores: '64' + runner: dsh-windows-2025-64core + workload: production-site + - platform: windows + cores: '96' + runner: dsh-windows-2025-96core + workload: production-site + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Report runner capacity + run: >- + node -e "const os = require('node:os'); + console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length, + memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))" + + - name: Enable corepack (pnpm) + run: corepack enable + + - name: Resolve pnpm store path + if: matrix.platform == 'linux' + id: pnpm-store + run: echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" - uses: actions/cache@v4 + if: matrix.platform == 'linux' with: path: ${{ steps.pnpm-store.outputs.path }} key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} @@ -258,26 +417,161 @@ jobs: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- - name: Install (immutable) + run: pnpm install --frozen-lockfile + + - name: Run critical Linux typecheck lane + if: matrix.platform == 'linux' + run: pnpm run typecheck + + - name: Run critical Windows production-site lane + if: matrix.platform == 'windows' + run: pnpm run docs:build + + # Manual comparison of the intended low-fanout topology. Linux runs the + # complete unsharded primary aggregate with bounded in-runner parallelism; + # Windows runs both blocking build surfaces concurrently through run-gates. + consolidated-runner-benchmark: + if: github.event_name == 'workflow_dispatch' && inputs.suite == 'consolidated-runner-benchmark' + runs-on: ${{ matrix.runner }} + timeout-minutes: 15 + strategy: + fail-fast: false + max-parallel: 12 + matrix: + include: + - platform: linux + cores: '4' + runner: dsh-ubuntu-24-04-4core + workers: '4' + - platform: linux + cores: '8' + runner: dsh-ubuntu-24-04-8core + workers: '8' + - platform: linux + cores: '16' + runner: dsh-ubuntu-24-04-16core + workers: '16' + - platform: linux + cores: '32' + runner: dsh-ubuntu-24-04-32core + workers: '32' + - platform: linux + cores: '64' + runner: dsh-ubuntu-24-04-64core + workers: '32' + - platform: linux + cores: '96' + runner: dsh-ubuntu-24-04-96core + workers: '32' + - platform: windows + cores: '4' + runner: dsh-windows-2025-4core + workers: '2' + - platform: windows + cores: '8' + runner: dsh-windows-2025-8core + workers: '2' + - platform: windows + cores: '16' + runner: dsh-windows-2025-16core + workers: '2' + - platform: windows + cores: '32' + runner: dsh-windows-2025-32core + workers: '2' + - platform: windows + cores: '64' + runner: dsh-windows-2025-64core + workers: '2' + - platform: windows + cores: '96' + runner: dsh-windows-2025-96core + workers: '2' + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Report runner capacity + run: >- + node -e "const os = require('node:os'); + console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length, + memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))" + + - name: Enable corepack (pnpm) + run: corepack enable + + - name: Resolve pnpm store path (Linux) + if: matrix.platform == 'linux' + id: pnpm-store-linux + run: echo "path=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" + + - name: Resolve pnpm store path (Windows) + if: matrix.platform == 'windows' + id: pnpm-store-windows + shell: pwsh + run: '"path=$(pnpm store path --silent)" >> $env:GITHUB_OUTPUT' + + - uses: actions/cache@v4 + with: + path: ${{ steps.pnpm-store-linux.outputs.path || steps.pnpm-store-windows.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - uses: actions/cache@v4 + if: matrix.platform == 'linux' + with: + path: .cache/eslint + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full-${{ hashFiles('pnpm-lock.yaml', 'eslint.config.mjs', 'tsconfig.json', 'packages/*/*/tsconfig.json', 'examples/*/tsconfig.json') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-full- + + - name: Install and prepare Linux + if: matrix.platform == 'linux' + run: | + pnpm install --frozen-lockfile & + install_pid=$! + bash scripts/prepare-ci-bubblewrap.sh & + sandbox_pid=$! + install_status=0 + wait "$install_pid" || install_status=$? + sandbox_status=0 + wait "$sandbox_pid" || sandbox_status=$? + if (( install_status != 0 )); then exit "$install_status"; fi + exit "$sandbox_status" + + - name: Install (immutable) + if: matrix.platform == 'windows' shell: pwsh run: pnpm install --frozen-lockfile - - uses: actions/cache@v4 - if: matrix.lane == 'lint' - with: - path: .cache/eslint - key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint-${{ hashFiles('pnpm-lock.yaml', 'eslint.config.mjs', 'tsconfig.json', 'packages/*/*/tsconfig.json', 'examples/*/tsconfig.json') }} - restore-keys: | - ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-eslint- + - name: Run complete unsharded primary Node CI concurrently + if: matrix.platform == 'linux' + env: + DSH_COVERAGE_MAX_WORKERS: ${{ matrix.workers }} + DSH_ESLINT_CACHE: '1' + DSH_ESLINT_CONCURRENCY: ${{ matrix.workers }} + DSH_GATE_CONCURRENCY: ${{ matrix.workers }} + DSH_PUBLINT_CONCURRENCY: ${{ matrix.workers }} + DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ matrix.workers }} + run: pnpm run check:ci - - name: Run gates + - name: Run blocking Windows builds concurrently + if: matrix.platform == 'windows' shell: pwsh - run: ${{ matrix.command }} + env: + DSH_GATE_CONCURRENCY: ${{ matrix.workers }} + run: pnpm run check:ci:windows-blocking # Single stable required check for branch protection: require "all checks # passed" instead of enumerating matrix legs whose names change as lanes and # node versions evolve. Every blocking job in THIS workflow must be listed in - # `needs`; explicitly observational jobs such as windows-gates stay out - # (`needs` cannot reach across workflow files; e2e.yml stays its own check). + # `needs`; observational Windows gates share the required Windows job but are + # marked non-blocking inside run-gates. (`needs` cannot reach across workflow + # files; e2e.yml stays its own check.) # `if: always()` is load-bearing: without it a failed dependency # would SKIP this job, and GitHub counts a skipped required check as passing # — so this job always runs and fails on any non-success result, including @@ -285,8 +579,8 @@ jobs: all-checks-passed: name: all checks passed runs-on: ubuntu-latest - needs: [node-24, node-compat, python-sdk, windows-build] - if: always() + needs: [node-24, node-compat, python-sdk, windows] + if: always() && github.event_name == 'pull_request' steps: - name: Fail if any needed job did not succeed if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') diff --git a/README.i18n.yaml b/README.i18n.yaml index d78213a292..020593bf20 100644 --- a/README.i18n.yaml +++ b/README.i18n.yaml @@ -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 -README.md: 32958db0e74bd14d6d41e8d7886b8d3257fe0f59 -README.zh.md: b28b175a8296347a7bed05b4e53c0d75dc51efed +README.md: 8b34d6177834e1c410b2c3ecaf32154de42520b4 +README.zh.md: cf029cc0bb8c5aa527d14753803eac4c28ab9de7 diff --git a/README.md b/README.md index 32958db0e7..8b34d61778 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,16 @@ English | [中文](README.zh.md) The **DeepSeek Harness SDK** is a plugin-based SDK for building agent harnesses. +## Install + +Install the `dsh` coding agent with one line — it needs `git` and Node `^22.19 || >=24`, and offers to install `pnpm` if it is missing: + +```sh +curl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh +``` + +It clones the harness to `~/.dsh/source`, runs `pnpm install`, symlinks `dsh` into `~/.local/bin` (offering to add it to your PATH), prompts once for your `DEEPSEEK_API_KEY`, and launches `dsh`; re-running it updates an existing checkout. Run from inside a checkout (`sh scripts/install.sh`) it reuses that checkout and skips the clone. The overridable `DSH_*` variables are documented in [`scripts/install.sh`](scripts/install.sh). + ## Development This monorepo is built on the [Cordis](https://github.com/cordiverse/cordis) framework (vendored as source under `vendor/`), microkernel-style: everything is a plugin. diff --git a/README.zh.md b/README.zh.md index b28b175a82..cf029cc0bb 100644 --- a/README.zh.md +++ b/README.zh.md @@ -4,6 +4,16 @@ **DeepSeek Harness SDK** 是用于构建 agent harness(智能体框架)的 SDK,采取基于插件的设计。 +## 安装 + +一行命令即可安装 `dsh` 编码智能体——需要 `git` 和 Node `^22.19 || >=24`,缺少 `pnpm` 时会询问是否代为安装: + +```sh +curl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh +``` + +脚本会把 harness 克隆到 `~/.dsh/source`,运行 `pnpm install`,把 `dsh` 软链接到 `~/.local/bin`(并询问是否加入 PATH),提示输入一次 `DEEPSEEK_API_KEY`,随后启动 `dsh`;再次运行会更新已有的检出。若在检出目录内运行(`sh scripts/install.sh`),脚本会复用当前检出并跳过克隆。可覆盖的 `DSH_*` 变量见 [`scripts/install.sh`](scripts/install.sh)。 + ## 开发 本 monorepo 基于 [Cordis](https://github.com/cordiverse/cordis) 框架构建(以源码形式收录在 `vendor/` 下),采用微内核风格:所有功能都以插件形式提供。 diff --git a/apps/cli/README.md b/apps/cli/README.md new file mode 100644 index 0000000000..b8ff616d59 --- /dev/null +++ b/apps/cli/README.md @@ -0,0 +1,21 @@ +# `@deepseek-ai/dsh` + +The `dsh` command-line entry, following the `apps/` assembly tier proposed by the `dsh web` PR (#443): `apps/*` are product assemblies over `packages/*` libraries. This branch ships one surface — plain `dsh [config.yml]` boots the interactive TUI coding agent — and reserves the `web` and `-p`/`--prompt` subcommands for that PR so the dispatch merges as a union. + +The TUI surface: + +- boots the shipped default config (`examples/tui-agent/cordis.yml`) or an explicit config argument, through [`dsh-app-boot`](../../packages/ui/app-boot/README.md); +- resumes a persisted session with `dsh --resume <session-id>` — the form the TUI prints on exit and lists under `/resume`; the flag sets `RESUME_SESSION_ID` before boot so the shipped config rehydrates that session, and a missing or unreadable id fails loud and exits nonzero; +- treats the **invoking directory** as the workspace — sessions, relative paths, and workspace instructions resolve from the cwd; +- tells the agent where its own source lives: after boot it adds a prompt section naming this harness checkout, resolved from the launcher's real path so it holds under a PATH symlink and an arbitrary cwd, so the self-referential `cordis` toolset can read and modify it; +- applies the personal overlay from `~/.dsh` (see [app-boot's Personal config](../../packages/ui/app-boot/README.md#personal-config)): `.env` fills environment gaps (ambient > project `.env` > personal `.env`), `config.yaml` patches the booted tree. + +## Install (developer machine) + +Symlink the source-running launcher onto your PATH; it resolves the checkout through its own real path, so code changes apply on the next launch with no build step: + +```sh +ln -sf "$(pwd)/bin/dsh" ~/.local/bin/dsh +``` + +`pnpm run demo:tui` runs the same entry from the repo root. The built form (`lib/bin.js`, via `pnpm run build`) needs `node --expose-internals` for the shipped config's HMR entry, exactly like the demo bins. diff --git a/apps/cli/package.json b/apps/cli/package.json index d245ebe705..fd744fa02c 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh", - "description": "dsh CLI: `dsh web` serves the built web UI over HTTP; `dsh -p` runs one headless task through the in-process ApiProxy carrier", + "description": "dsh CLI: interactive TUI, headless task, and browser UI surfaces", "version": "0.0.1", "private": true, "type": "module", @@ -18,6 +18,7 @@ "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-host-runtime": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", + "@deepseek-ai/dsh-paths": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^" } } diff --git a/apps/cli/src/bin.ts b/apps/cli/src/bin.ts index 672b5dfb9a..1192472b98 100644 --- a/apps/cli/src/bin.ts +++ b/apps/cli/src/bin.ts @@ -1,10 +1,13 @@ #!/usr/bin/env node /** - * dsh — command-line entry. Coarse dispatch only; each subcommand module owns - * its parseArgs. Dynamic imports keep the shapes independent: `web` never - * loads the headless consumer, `-p` never loads node:http or the static server. + * dsh — command-line entry. Coarse dispatch only; each surface module owns its + * argument handling. Dynamic imports keep unrelated surfaces out of each + * dispatch path; everything except `web` and headless prompts opens the TUI. + * @module @deepseek-ai/dsh/bin */ +/* v8 ignore file -- built-bin and PTY tests exercise this self-executing dispatch. */ + import { loadEnv } from '@deepseek-ai/dsh-app-boot' loadEnv('dsh') @@ -17,6 +20,6 @@ if (argv[0] === 'web') { const { runHeadless } = await import('./headless.ts') await runHeadless(argv) } else { - process.stderr.write('usage: dsh web [--port N] | dsh -p "task"\n') - process.exit(1) + const { runTui } = await import('./tui.ts') + await runTui(argv) } diff --git a/apps/cli/src/headless.ts b/apps/cli/src/headless.ts index 9c35c0e27a..dc1fa192a1 100644 --- a/apps/cli/src/headless.ts +++ b/apps/cli/src/headless.ts @@ -81,7 +81,7 @@ export async function runHeadless(argv: string[]): Promise<void> { const host = await startHost({ boot: { persistenceRoot: './.sessions' } }) const api = new InProcessApiClient(host.handler) - const created = await unwrap(await api.sessions.create({}), host.dispose) + const created = await unwrap(await api.sessions.create({}), () => host.dispose()) // Open the stream before prompting so no frame is lost — kept in this order // even though in-process delivery has no race, so the code survives a move @@ -94,7 +94,7 @@ export async function runHeadless(argv: string[]): Promise<void> { sessionId: created.sessionId, mode: 'queue', content: [{ type: 'text', text: task }], - }), host.dispose) + }), () => host.dispose()) const outcome = await done process.stdout.write(outcome.text + '\n') diff --git a/apps/cli/src/tui.ts b/apps/cli/src/tui.ts new file mode 100644 index 0000000000..6f97a68ad3 --- /dev/null +++ b/apps/cli/src/tui.ts @@ -0,0 +1,71 @@ +/** + * `dsh` default surface — the interactive TUI coding agent. Boots the shipped + * tui-agent config (or an explicit config argument) with the personal overlay + * from the Harness home (`~/.dsh`): its `.env` fills environment gaps (precedence: + * ambient environment, then the invoking directory's `.env`, then the personal one) + * and its `config.yaml` patches the booted tree. The workspace is the invoking + * directory: sessions, relative paths, and workspace instructions resolve from + * the cwd, so `dsh` acts on whatever project it is launched in. After boot, the + * agent's system prompt is told the path to this harness checkout so it can find + * its own source. + * @module @deepseek-ai/dsh/tui + */ + +import { fileURLToPath } from 'node:url' +import { + addHarnessSourceSection, + boot, + installFailLoud, + loadEnv, + loadPersonalPatches, + parseResumeArg, + resolveConfigPath, +} from '@deepseek-ai/dsh-app-boot' +import { resolveDshHome } from '@deepseek-ai/dsh-paths' + +const NAME = 'dsh' + +// The env var the shipped tui-agent config reads (`resumeSessionId: !!js +// process.env.RESUME_SESSION_ID`) to rehydrate a persisted session. The +// `--resume <id>` flag is CLI sugar that sets it before boot, so the printed +// `dsh --resume <id>` exit hint runs back through this same intake. +const RESUME_SESSION_ID_ENV = 'RESUME_SESSION_ID' + +// Both the source tree (apps/cli/src) and the bundled bin (apps/cli/lib) sit +// one directory under apps/cli, so the shipped default config resolves with +// the same relative hop from either artifact. +const DEFAULT_CONFIG = fileURLToPath(new URL('../../../examples/tui-agent/cordis.yml', import.meta.url)) + +// The harness checkout root: three hops up from apps/cli/{src,lib}, resolved +// from this bin's location so it holds however `dsh` is launched (a PATH +// symlink, an arbitrary cwd). The agent is told where its own source lives. +const SOURCE_ROOT = fileURLToPath(new URL('../../..', import.meta.url)) + +/* v8 ignore start -- composition over the unit-tested dsh-app-boot helpers; + the tui-agent PTY smoke drives this path end to end, personal overlay included */ +/** + * Run the interactive TUI from the invoking directory. + * @param argv - arguments after the subcommand dispatch; a `--resume <id>` flag + * resumes that persisted session, and the first non-flag argument may name a + * config to boot instead of the shipped default. + */ +export async function runTui(argv: string[]): Promise<void> { + // Refuse pipes BEFORE booting: a compose-time throw inside the Loader tree + // is logged per-entry rather than rethrown, so a piped launch would + // otherwise settle into an idle UI-less process instead of exiting nonzero. + if (!process.stdin.isTTY || !process.stdout.isTTY) { + process.stderr.write(`${NAME}: the TUI requires stdin and stdout to be interactive TTYs\n`) + process.exit(1) + } + installFailLoud(NAME) + // The bin already loaded the invoking directory's .env; the personal .env + // only fills what is still unset (process.loadEnvFile never overrides). + loadEnv(NAME, resolveDshHome()) + // An explicit `--resume` flag beats any ambient RESUME_SESSION_ID, so set it + // after loadEnv and before boot reads it through the config's `!!js`. + const { resumeSessionId, rest } = parseResumeArg(argv) + if (resumeSessionId !== undefined) process.env[RESUME_SESSION_ID_ENV] = resumeSessionId + const ctx = await boot(NAME, resolveConfigPath(rest[0] ?? DEFAULT_CONFIG, undefined), loadPersonalPatches(NAME)) + addHarnessSourceSection(ctx, SOURCE_ROOT) +} +/* v8 ignore stop */ diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json index 237de29279..ee9382171a 100644 --- a/apps/cli/tsconfig.json +++ b/apps/cli/tsconfig.json @@ -13,6 +13,7 @@ { "path": "../../packages/host/runtime" }, { "path": "../../packages/host/webserver" }, { "path": "../../packages/core/session" }, - { "path": "../../packages/ui/app-boot" } + { "path": "../../packages/ui/app-boot" }, + { "path": "../../packages/util/paths" } ] } diff --git a/apps/cli/tsdown.config.ts b/apps/cli/tsdown.config.ts new file mode 100644 index 0000000000..68ca2254e0 --- /dev/null +++ b/apps/cli/tsdown.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from 'tsdown' + +/** + * The dsh CLI ships one entry: the `bin` referenced by package.json `bin`. + * The root tsdown builds only `lib/types/index.js`, so this override points at + * `lib/types/bin.js` instead; the statically imported surface modules bundle + * into it. Declarations come from `tsc -b` (dts: false), matching every package. + */ +export default defineConfig({ + entry: ['lib/types/bin.js'], + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, +}) diff --git a/apps/web/tests/smoke-fixture.e2e.ts b/apps/web/tests/smoke-fixture.e2e.ts index 0c32be5310..291e871e63 100644 --- a/apps/web/tests/smoke-fixture.e2e.ts +++ b/apps/web/tests/smoke-fixture.e2e.ts @@ -49,12 +49,12 @@ describe('web boot chain (keyless, real carrier)', () => { apiHandler, webPlugins: { snapshot: () => ROWS, - clientPath: (id) => (id === ROWS[0]!.id ? LAYOUT_BUNDLE : undefined), + clientPath: id => (id === ROWS[0]!.id ? LAYOUT_BUNDLE : undefined), }, }, (err) => { pageErrors.push(`server: ${String(err)}`) }) browser = await chromium.launch() page = await browser.newPage() - page.on('pageerror', (e) => pageErrors.push(String(e))) + page.on('pageerror', e => pageErrors.push(String(e))) await page.goto(`http://127.0.0.1:${port}/`, { waitUntil: 'load' }) }) @@ -91,7 +91,7 @@ describe('web boot chain (keyless, real carrier)', () => { }) describe('web boot chain success pass (keyless, five real bundles, ?fixture)', () => { - const missing = REAL_PLUGINS.filter((p) => !existsSync(bundlePath(p.dir))) + const missing = REAL_PLUGINS.filter(p => !existsSync(bundlePath(p.dir))) let server: Awaited<ReturnType<typeof startWebServer>> let browser: Browser let page: Page @@ -99,25 +99,25 @@ describe('web boot chain success pass (keyless, five real bundles, ?fixture)', ( beforeAll(async () => { requireDist() - if (missing.length > 0) throw new Error(`client bundles not built (pnpm --filter <pkg> bundle): ${missing.map((m) => m.dir).join(', ')}`) + if (missing.length > 0) throw new Error(`client bundles not built (pnpm --filter <pkg> bundle): ${missing.map(m => m.dir).join(', ')}`) const port = await probeFreePort() const rows: WebPluginBootEntry[] = REAL_PLUGINS.map((p) => { const row: WebPluginBootEntry = { id: p.id, url: `/plugins/${p.id}/client.js`, inject: p.inject } if (p.immediately === true) row.immediately = true return row }) - const byId = new Map(REAL_PLUGINS.map((p) => [p.id, bundlePath(p.dir)])) + const byId = new Map(REAL_PLUGINS.map(p => [p.id, bundlePath(p.dir)])) // ?fixture never opens HTTP streams; /api is a tripwire like the first describe. const apiHandler = { fetch: () => Promise.resolve(new Response('fixture mode must not call /api', { status: 500 })) } server = await startWebServer({ port, distIndex: DIST_INDEX, apiHandler, - webPlugins: { snapshot: () => rows, clientPath: (id) => byId.get(id) }, + webPlugins: { snapshot: () => rows, clientPath: id => byId.get(id) }, }, (err) => { pageErrors.push(`server: ${String(err)}`) }) browser = await chromium.launch() page = await browser.newPage() - page.on('pageerror', (e) => pageErrors.push(String(e))) + page.on('pageerror', e => pageErrors.push(String(e))) await page.goto(`http://127.0.0.1:${port}/?fixture`, { waitUntil: 'load' }) }) @@ -131,13 +131,13 @@ describe('web boot chain success pass (keyless, five real bundles, ?fixture)', ( await page.waitForSelector('[class*="frame"]', { timeout: 15_000 }) // Loading page is gone; the grid carries the three tracks. expect(await page.locator('text=Failed to load plugins').count()).toBe(0) - const template = await page.locator('[class*="frame"]').evaluate((el) => getComputedStyle(el).gridTemplateColumns) + const template = await page.locator('[class*="frame"]').evaluate(el => getComputedStyle(el).gridTemplateColumns) expect(template.split(' ').length).toBe(3) }) it('every plugin CSS landed with its ownership tag', async () => { const owners = await page.evaluate(() => - [...document.querySelectorAll('style[data-plugin]')].map((s) => (s as HTMLElement).dataset['plugin'])) + [...document.querySelectorAll('style[data-plugin]')].map(s => (s as HTMLElement).dataset['plugin'])) expect(owners).toContain('@deepseek-ai/dsh-client-ui-layout') }) diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index 4e280af0c7..95b293d0e7 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -39,7 +39,7 @@ loadRootEnv() function waitForReadyLine(child: ChildProcess): Promise<string> { return new Promise((resolveReady, reject) => { let out = '' - const timer = setTimeout(() => reject(new Error(`dsh web not ready in 90s; output:\n${out}`)), 90_000) + const timer = setTimeout(() => { reject(new Error(`dsh web not ready in 90s; output:\n${out}`)) }, 90_000) const onData = (chunk: Buffer): void => { out += chunk.toString() const match = /dsh web: (http:\/\/[^\s]+)/.exec(out) @@ -65,13 +65,13 @@ async function screen(page: Page, name: string): Promise<void> { /** First column track (px string) of the frame grid. */ async function firstTrack(page: Page): Promise<string> { return (await page.locator('[class*="frame"]').evaluate( - (el) => getComputedStyle(el).gridTemplateColumns)).split(' ')[0]! + el => getComputedStyle(el).gridTemplateColumns)).split(' ')[0]! } /** Last column track (details) as a number of pixels. */ async function detailsTrack(page: Page): Promise<number> { const cols = await page.locator('[class*="frame"]').evaluate( - (el) => getComputedStyle(el).gridTemplateColumns) + el => getComputedStyle(el).gridTemplateColumns) return Number(cols.split(' ').pop()!.replace('px', '')) } @@ -113,16 +113,16 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke baseUrl = (await waitForReadyLine(child)).replace('0.0.0.0', '127.0.0.1') browser = await chromium.launch() page = await browser.newPage({ viewport: { width: 1680, height: 1000 } }) - page.on('pageerror', (e) => pageErrors.push(String(e))) + page.on('pageerror', e => pageErrors.push(String(e))) await page.goto(baseUrl, { waitUntil: 'load' }) }, 120_000) afterAll(async () => { await browser?.close() if (child !== undefined && child.exitCode === null) { - const gone = new Promise<void>((resolveExit) => child.once('exit', () => resolveExit())) + const gone = new Promise<void>(resolveExit => child.once('exit', () => { resolveExit() })) child.kill('SIGTERM') - await Promise.race([gone, new Promise((r) => setTimeout(r, 10_000).unref())]) + await Promise.race([gone, new Promise(r => setTimeout(r, 10_000).unref())]) if (child.exitCode === null) child.kill('SIGKILL') } if (sessionsDir !== undefined) rmSync(sessionsDir, { recursive: true, force: true }) @@ -132,7 +132,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke onTestFailed(() => saveFailureShot(page, 'w5-cold-start')) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) expect(await page.locator('text=Failed to load plugins').count()).toBe(0) - const template = await page.locator('[class*="frame"]').evaluate((el) => getComputedStyle(el).gridTemplateColumns) + const template = await page.locator('[class*="frame"]').evaluate(el => getComputedStyle(el).gridTemplateColumns) expect(template.split(' ').length).toBe(3) await screen(page, '01-cold-start') }) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index 7c56fc05c3..f4fbbb265f 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -27,10 +27,10 @@ export function probeFreePort(): Promise<number> { probe.listen(0, '127.0.0.1', () => { const address = probe.address() if (address === null || typeof address === 'string') { - probe.close(() => reject(new Error('port probe returned no address'))) + probe.close(() => { reject(new Error('port probe returned no address')) }) return } - probe.close(() => resolvePort(address.port)) + probe.close(() => { resolvePort(address.port) }) }) }) } diff --git a/bin/dsh b/bin/dsh new file mode 100755 index 0000000000..88eaa0ab71 --- /dev/null +++ b/bin/dsh @@ -0,0 +1,22 @@ +#!/bin/sh +# dsh launcher: runs the apps/cli `dsh` bin FROM SOURCE with this checkout's +# tsx, so a symlink from anywhere (e.g. ~/.local/bin/dsh) always executes the +# current working tree — code changes apply on the next launch, no build step. +# --expose-internals: the shipped config mounts HMR, which needs Loader internals. +set -eu + +# Resolve symlink chains without readlink -f (not on every macOS). +script=$0 +while [ -L "$script" ]; do + target=$(readlink "$script") + case $target in + /*) script=$target ;; + *) script=$(dirname "$script")/$target ;; + esac +done +root=$(CDPATH='' cd -- "$(dirname -- "$script")/.." && pwd) + +# tsx is imported by absolute path because bare `--import tsx` resolves from +# the invoking cwd, which is usually outside this repository. +export TSX_TSCONFIG_PATH="$root/tsconfig.json" +exec node --expose-internals --import "$root/node_modules/tsx/dist/loader.mjs" "$root/apps/cli/src/bin.ts" "$@" diff --git a/docs/config-catalog.md b/docs/config-catalog.md index c377425522..76afd7d68a 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1512,10 +1512,18 @@ Requires: `agents` · `commands` · `userInteraction` · `tools` · `llm` · `sy ```ts config-catalog /** Serializable plugin configuration. */ export interface Config extends TuiConfig { - /** Header subtitle. Defaults to `ready.`. */ + /** Banner subtitle line. When absent, the banner has no subtitle and sweeps in on start. */ welcome?: string /** Exact shared agent/session identity driven by this terminal. Defaults to `main`. */ sessionId?: string + /** + * Shell command template shown for resuming this session: printed on exit and + * listed by `/resume`, with every `{session}` occurrence replaced by the live + * session id. Absent disables both surfaces. Deployments set it only when a + * persistence backend makes the session resumable (e.g. + * `RESUME_SESSION_ID={session} dsh`). + */ + resumeCommand?: string } /** Presentation settings for the pi-tui terminal mode. */ @@ -1540,12 +1548,19 @@ export interface TuiConfig { showHardwareCursor?: boolean /** Apply the built-in ANSI color palette. */ color?: boolean - /** Terminal window title while the UI is mounted. */ + /** + * Paint the startup banner's product name in the DeepSeek brand gradient + * using 24-bit truecolor. Requires {@link TuiConfig.color}; falls back to the + * flat accent color when either is off. Unset auto-detects `COLORTERM` at the + * process boundary, so most deployments leave it unset. + */ + truecolor?: boolean + /** Terminal window title while the UI is mounted; a logged session title prefixes it. */ title?: string } ``` -Source: [`packages/ui/tui/src/index.ts:129`](../packages/ui/tui/src/index.ts) +Source: [`packages/ui/tui/src/index.ts:145`](../packages/ui/tui/src/index.ts) ## `@deepseek-ai/dsh-tui-demo` @@ -1572,8 +1587,15 @@ export interface Config { persistenceRoot?: string /** JSONL artifact encoding; defaults to checksummed Zstandard frames. */ persistenceCompression?: JsonlCompression - /** TUI subtitle rendered on start. Defaults to `ready.`. */ + /** TUI transcript's optional first line; absent renders nothing on start. */ welcome?: string + /** + * Shell command template the TUI prints on exit and lists under `/resume`, + * with `{session}` replaced by the live session id (forwarded to the front + * door). Set it to a command that resumes via this app's env var, e.g. + * `RESUME_SESSION_ID={session} dsh`. + */ + resumeCommand?: string /** Full-screen TUI presentation settings. */ ui?: uiTui.TuiConfig /** Skill registry, local-provider, and model-facing consumer config. */ @@ -1593,7 +1615,7 @@ export interface Config { Depends on: [`agentCore`](../packages/examples/agent-spine-demo/src/index.ts) · [`JsonlCompression`](../packages/session-persistence/session-persistence-jsonl/src/index.ts) · [`ToolsConfig`](#deepseek-aidsh-tools) · [`uiTui`](../packages/ui/tui/src/index.ts) -Source: [`packages/examples/tui-demo/src/index.ts:33`](../packages/examples/tui-demo/src/index.ts) +Source: [`packages/examples/tui-demo/src/index.ts:32`](../packages/examples/tui-demo/src/index.ts) ## `@deepseek-ai/dsh-user-approval` @@ -1778,12 +1800,20 @@ export interface Config { maxBytes: number /** Maximum UTF-8 bytes read from one instruction file; larger files are ignored. */ maxSourceBytes?: number - /** Ordered same-directory project candidates; the first existing regular file wins in each scope. */ + /** + * Ordered same-directory project candidates; every existing file loads, with + * per-directory trimmed-content duplicates collapsed to the earliest candidate. + */ instructionFileCandidates?: string[] + /** + * Ordered same-directory local-overlay candidates loaded after the base files + * under the same per-directory trimmed-content dedup; empty disables the overlay. + */ + localInstructionFileCandidates?: string[] } ``` -Source: [`packages/context/workspace-context/src/config.ts:16`](../packages/context/workspace-context/src/config.ts) +Source: [`packages/context/workspace-context/src/config.ts:17`](../packages/context/workspace-context/src/config.ts) ## Loadable plugins with no config diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index f8a01e84ae..d7f4123b91 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -15,7 +15,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/post-step` | `serial` | [`packages/core/agent/src/types.ts:296`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic) | | `agent/pre-step` | `serial` | [`packages/core/agent/src/types.ts:230`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`time-context`](../packages/context/time-context), [`user-approval`](../packages/ui/user-approval) | | `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:243`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`acp`](../packages/ui/acp), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | -| `agent/queued` | `emit` | [`packages/core/agent/src/types.ts:191`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session) | +| `agent/queued` | `emit` | [`packages/core/agent/src/types.ts:191`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | | `agent/request` | `waterfall` | [`packages/core/agent/src/types.ts:257`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/types.ts:311`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compact-basic`](../packages/compact/compact-basic), [`llm-retry`](../packages/llm/llm-retry), [`plan-mode`](../packages/plan/plan-mode) | | `agent/session-prefix` | `waterfall` | [`packages/core/agent/src/types.ts:272`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`tool-skill`](../packages/skill/tool-skill), [`workspace-context`](../packages/context/workspace-context) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 054694bfb7..ca4848477f 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -208,7 +208,6 @@ flowchart TD pkg_subagent_subprocess --> pkg_invariants pkg_acp_snapshot --> pkg_invariants pkg_loader_smoke --> pkg_invariants - pkg_app_boot --> pkg_invariants pkg_client_connection --> pkg_invariants pkg_client_i18n --> pkg_invariants pkg_client_runtime --> pkg_invariants @@ -232,8 +231,6 @@ flowchart TD pkg_code_runtime_worker --> pkg_invariants pkg_helper --> pkg_brand pkg_helper --> pkg_invariants - pkg_scripts --> pkg_app_boot - pkg_scripts --> pkg_invariants pkg_telemetry --> pkg_brand pkg_telemetry --> pkg_invariants pkg_telemetry --> pkg_paths @@ -300,6 +297,9 @@ flowchart TD pkg_llm_replay --> pkg_invariants pkg_llm_replay --> pkg_llm pkg_llm_replay --> pkg_session + pkg_app_boot --> pkg_invariants + pkg_app_boot --> pkg_paths + pkg_app_boot --> pkg_system_prompt pkg_lsp_local --> pkg_brand pkg_lsp_local --> pkg_invariants pkg_lsp_local --> pkg_llm @@ -380,6 +380,8 @@ flowchart TD pkg_pty --> pkg_agent pkg_pty --> pkg_brand pkg_pty --> pkg_invariants + pkg_scripts --> pkg_app_boot + pkg_scripts --> pkg_invariants pkg_tasks --> pkg_agent pkg_tasks --> pkg_brand pkg_tasks --> pkg_invariants @@ -632,7 +634,9 @@ flowchart TD pkg_tui --> pkg_llm pkg_tui --> pkg_llm_retry pkg_tui --> pkg_session + pkg_tui --> pkg_session_persistence pkg_tui --> pkg_session_title + pkg_tui --> pkg_skill pkg_tui --> pkg_system_prompt pkg_tui --> pkg_token_meter pkg_tui --> pkg_tools @@ -729,7 +733,6 @@ flowchart TD | [`subagent-subprocess`](../packages/subagent/subagent-subprocess) | `subagent` | [`invariants`](../packages/support/invariants) | | [`acp-snapshot`](../packages/support/acp-snapshot) | `support` | [`invariants`](../packages/support/invariants) | | [`loader-smoke`](../packages/support/loader-smoke) | `support` | [`invariants`](../packages/support/invariants) | -| [`app-boot`](../packages/ui/app-boot) | `ui` | [`invariants`](../packages/support/invariants) | | [`client-connection`](../packages/client/connection) | `client` | [`invariants`](../packages/support/invariants) | | [`client-i18n`](../packages/client/i18n) | `client` | [`invariants`](../packages/support/invariants) | | [`client-runtime`](../packages/client/runtime) | `client` | [`invariants`](../packages/support/invariants) | @@ -750,7 +753,6 @@ flowchart TD | [`llm`](../packages/llm/llm) | `llm` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants) | | [`code-runtime-worker`](../packages/code-runtime/code-runtime-worker) | `code-runtime` | [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/support/invariants) | | [`helper`](../packages/sdk/helper) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants) | -| [`scripts`](../packages/sdk/scripts) | `sdk` | [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants) | | [`telemetry`](../packages/sdk/telemetry) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths) | | [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) | | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) | @@ -773,6 +775,7 @@ flowchart TD | [`session-persistence`](../packages/session-persistence/session-persistence) | `session-persistence` | [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | | [`session-title`](../packages/session-title/session-title) | `session-title` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-replay`](../packages/support/llm-replay) | `support` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`app-boot`](../packages/ui/app-boot) | `ui` | [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`system-prompt`](../packages/core/system-prompt) | | [`lsp-local`](../packages/lsp/lsp-local) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`timeout`](../packages/util/timeout) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | @@ -794,6 +797,7 @@ flowchart TD | [`user-interaction`](../packages/ui/user-interaction) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | | [`pty`](../packages/pty/pty) | `pty` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants) | +| [`scripts`](../packages/sdk/scripts) | `sdk` | [`app-boot`](../packages/ui/app-boot), [`invariants`](../packages/support/invariants) | | [`tasks`](../packages/tasks/tasks) | `tasks` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/ui/user-approval) | @@ -834,7 +838,7 @@ flowchart TD | [`hooks-claude`](../packages/hooks/hooks-claude) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`acp`](../packages/ui/acp) | `ui` | [`agent`](../packages/core/agent), [`bash`](../packages/bash/bash), [`commands`](../packages/ui/commands), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`user-interaction`](../packages/ui/user-interaction) | | [`jsonrpc`](../packages/ui/jsonrpc) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | -| [`tui`](../packages/ui/tui) | `ui` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`commands`](../packages/ui/commands), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`system-prompt`](../packages/core/system-prompt), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | +| [`tui`](../packages/ui/tui) | `ui` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`commands`](../packages/ui/commands), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title), [`skill`](../packages/skill/skill), [`system-prompt`](../packages/core/system-prompt), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | | [`agent-spine-demo`](../packages/examples/agent-spine-demo) | `examples` | [`agent`](../packages/core/agent), [`agent-loop`](../packages/core/agent-loop), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`paths`](../packages/util/paths), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`skill`](../packages/skill/skill), [`skill-local`](../packages/skill/skill-local), [`system-prompt`](../packages/core/system-prompt), [`tasks`](../packages/tasks/tasks), [`tool-bash`](../packages/bash/tool-bash), [`tool-goal`](../packages/goal/tool-goal), [`tool-skill`](../packages/skill/tool-skill), [`tool-tasks`](../packages/tasks/tool-tasks), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | | [`tool-ralph`](../packages/workflow/tool-ralph) | `workflow` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | diff --git a/eslint.config.mjs b/eslint.config.mjs index 4961a569b5..334d3799af 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -18,6 +18,7 @@ export default tseslint.config( '**/*.js', '**/*.mjs', '*.config.ts', // root tool configs (vitest, tsdown) — no project service + 'apps/*/*.config.ts', // app build configs — outside their project programs '**/tsdown.config.ts', // package build configs — in no tsconfig program, and TS syntax breaks the parserless fallback 'packages/client/tsdown.client.ts', // shared client build preset, same standing ], @@ -25,7 +26,7 @@ export default tseslint.config( // --- our packages: full strictness ------------------------------------- { - files: ['packages/*/*/src/**/*.ts', 'examples/**/*.ts', 'scripts/**/*.ts', 'website/**/*.ts'], + files: ['packages/*/*/src/**/*.ts', 'apps/*/src/**/*.ts', 'examples/**/*.ts', 'scripts/**/*.ts', 'website/**/*.ts'], extends: [ ...tseslint.configs.strictTypeChecked, ], @@ -78,7 +79,7 @@ export default tseslint.config( // --- tests: same rules, minus the friction that fights test ergonomics -- { - files: ['packages/*/*/tests/**/*.ts', 'examples/*/tests/**/*.ts', 'scripts/**/*.spec.ts'], + files: ['packages/*/*/tests/**/*.ts', 'apps/*/tests/**/*.ts', 'examples/*/tests/**/*.ts', 'scripts/**/*.spec.ts'], extends: [ ...tseslint.configs.strictTypeChecked, ], @@ -126,7 +127,7 @@ export default tseslint.config( // --- file-local duplication (all owned TypeScript) --------------------- { - files: ['packages/**/*.ts', 'examples/**/*.ts', 'scripts/**/*.ts', 'website/**/*.ts'], + files: ['packages/**/*.ts', 'apps/**/*.ts', 'examples/**/*.ts', 'scripts/**/*.ts', 'website/**/*.ts'], plugins: { sonarjs }, rules: { // Cross-file clones are covered separately by jscpd. @@ -143,7 +144,7 @@ export default tseslint.config( // --- formatting (everything we own) ------------------------------------- { - files: ['packages/**/*.ts', 'examples/**/*.ts', 'scripts/**/*.ts', 'website/**/*.ts', 'eslint.config.mjs'], + files: ['packages/**/*.ts', 'apps/**/*.ts', 'examples/**/*.ts', 'scripts/**/*.ts', 'website/**/*.ts', 'eslint.config.mjs'], plugins: { '@stylistic': stylistic }, rules: { '@stylistic/indent': ['error', 2], diff --git a/examples/acp-agent/advanced.cordis.yml b/examples/acp-agent/advanced.cordis.yml index 2765b384fe..5aeacd3e22 100644 --- a/examples/acp-agent/advanced.cordis.yml +++ b/examples/acp-agent/advanced.cordis.yml @@ -9,7 +9,7 @@ name: '@deepseek-ai/dsh-acp-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" workspaceContext: diff --git a/examples/acp-agent/both-mode.cordis.yml b/examples/acp-agent/both-mode.cordis.yml index e44f3450de..cff9602684 100644 --- a/examples/acp-agent/both-mode.cordis.yml +++ b/examples/acp-agent/both-mode.cordis.yml @@ -11,7 +11,7 @@ name: '@deepseek-ai/dsh-acp-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" workspaceContext: diff --git a/examples/acp-agent/code-mode-workspace-context.cordis.yml b/examples/acp-agent/code-mode-workspace-context.cordis.yml index 807de9b3c3..b043869a65 100644 --- a/examples/acp-agent/code-mode-workspace-context.cordis.yml +++ b/examples/acp-agent/code-mode-workspace-context.cordis.yml @@ -9,7 +9,7 @@ name: '@deepseek-ai/dsh-acp-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" workspaceContext: diff --git a/examples/acp-agent/code-mode.cordis.yml b/examples/acp-agent/code-mode.cordis.yml index 38d8eb33cb..1192b284c0 100644 --- a/examples/acp-agent/code-mode.cordis.yml +++ b/examples/acp-agent/code-mode.cordis.yml @@ -12,7 +12,7 @@ name: '@deepseek-ai/dsh-acp-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" workspaceContext: diff --git a/examples/acp-agent/cordis.snapshot.yml b/examples/acp-agent/cordis.snapshot.yml index e4d717a399..2838127d52 100644 --- a/examples/acp-agent/cordis.snapshot.yml +++ b/examples/acp-agent/cordis.snapshot.yml @@ -1,6 +1,10 @@ # Keyless replay includes the live `cordis.yml`, disables the key-requiring # DeepSeek adapter, and inserts `llm-replay` to serve recorded JSONL without a key -# or network; every other app entry remains shared. +# or network; every other app entry remains shared. It also restates the acp-agent +# config to re-pin `deepseek-v4-flash`: `cordis.yml` ships `deepseek-v4-pro`, but the +# recorded corpus (request headers, provenance, system prompt) was captured on flash, +# so replay holds the recorded model to stay reproducible without a re-record. A config +# patch replaces the whole app config, so the base fields are restated verbatim. # With `DSH_SNAPSHOT=replay`, the app bin reads `DSH_SNAPSHOT_FILE` and optional # `DSH_SNAPSHOT_OVERRIDE` from the harness. The one-shot patch applies at include # load time, and stdout remains reserved for ACP JSON-RPC. @@ -15,6 +19,22 @@ - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' disabled: true + - id: acp-agent + name: '@deepseek-ai/dsh-acp-demo' + config: + provider: deepseek + model: deepseek-v4-flash + persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + # Replay fixtures are raw JSONL; the whole-config patch must restate + # the compression choice or the default zstd frames hide the logs + # from the harness's harvest. + persistenceCompression: none + workspaceContext: + maxBytes: 65536 + persona: | + You are a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + + Verify your work by running the code or tests. Keep answers brief and factual. - id: sandbox name: '@deepseek-ai/dsh-sandbox-local' config: diff --git a/examples/acp-agent/cordis.yml b/examples/acp-agent/cordis.yml index 1fc2c96e6d..4122867228 100644 --- a/examples/acp-agent/cordis.yml +++ b/examples/acp-agent/cordis.yml @@ -3,12 +3,15 @@ # log. The bin loads the gitignored root `.env` before this config. This tree has # no stdout logger or HMR because stdout carries ACP JSON-RPC. -# The DeepSeek adapter. +# The DeepSeek adapter. Shipped default: full thinking at max effort on every +# request (wire-only defaults; they never enter the request header). - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' config: apiKey: !!js process.env.DEEPSEEK_API_KEY baseURL: !!js process.env.DEEPSEEK_BASE_URL + thinking: enabled + reasoningEffort: max models: - id: deepseek-v4-flash contextWindow: 256000 @@ -51,7 +54,7 @@ name: '@deepseek-ai/dsh-acp-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" workspaceContext: diff --git a/examples/acp-agent/depth-two.cordis.snapshot.yml b/examples/acp-agent/depth-two.cordis.snapshot.yml index 16aa6f587c..d92a3cd304 100644 --- a/examples/acp-agent/depth-two.cordis.snapshot.yml +++ b/examples/acp-agent/depth-two.cordis.snapshot.yml @@ -24,6 +24,22 @@ provider: spawn toolName: subagent maxDepth: 2 + # Re-pin the recorded model: cordis.yml ships deepseek-v4-pro, but this + # scenario's corpus was captured on flash. A config patch replaces the + # whole app config, so the base fields are restated verbatim. + - id: acp-agent + name: '@deepseek-ai/dsh-acp-demo' + config: + provider: deepseek + model: deepseek-v4-flash + persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + persistenceCompression: none + workspaceContext: + maxBytes: 65536 + persona: | + You are a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + + Verify your work by running the code or tests. Keep answers brief and factual. - insert: - id: llm-replay name: '@deepseek-ai/dsh-llm-replay' diff --git a/examples/acp-agent/fs.cordis.snapshot.yml b/examples/acp-agent/fs.cordis.snapshot.yml index d55521a8dc..0417074edd 100644 --- a/examples/acp-agent/fs.cordis.snapshot.yml +++ b/examples/acp-agent/fs.cordis.snapshot.yml @@ -1,6 +1,9 @@ # Keyless filesystem snapshots apply the spill and replay overlays directly # because include patches cannot target entries behind a nested include. The -# sandboxed filesystem stack already lives in the base cordis.yml. +# sandboxed filesystem stack already lives in the base cordis.yml. This file also +# re-pins the acp-agent model to `deepseek-v4-flash`: `cordis.yml` ships +# `deepseek-v4-pro`, but the recorded corpus was captured on flash, and a config +# patch replaces the whole app config, so the base fields are restated verbatim. - id: base name: '@cordisjs/plugin-include' config: @@ -9,6 +12,19 @@ - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' disabled: true + - id: acp-agent + name: '@deepseek-ai/dsh-acp-demo' + config: + provider: deepseek + model: deepseek-v4-flash + persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + persistenceCompression: none + workspaceContext: + maxBytes: 65536 + persona: | + You are a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + + Verify your work by running the code or tests. Keep answers brief and factual. - insert: - id: spill-local name: '@deepseek-ai/dsh-spill-local' diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index d1cc910642..297a36da5f 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -125,8 +125,11 @@ const SCENARIOS: Scenario[] = [ { name: 'repeat-tool-guard', hasModelTurn: true, recorded: false }, // Authored replay: a root AGENTS.md pins the session prefix, then a read in // nested/ discovers its narrower AGENTS.md as a raw, metadata-bearing - // context/message. The scenario-specific config keeps home/root discovery - // hermetic, and the resulting prefix needs its own pinned header class. + // context/message. Both AGENTS.md fixtures are symlinks to a sibling + // AGENTS.canonical.md, so this scenario also guards that discovery follows a + // symlinked instruction file to its target's content. The scenario-specific + // config keeps home/root discovery hermetic, and the resulting prefix needs + // its own pinned header class. { name: 'workspace-context', hasModelTurn: true, diff --git a/examples/acp-agent/tests/escalation.e2e.ts b/examples/acp-agent/tests/escalation.e2e.ts index 59d6d75caa..ae53252743 100644 --- a/examples/acp-agent/tests/escalation.e2e.ts +++ b/examples/acp-agent/tests/escalation.e2e.ts @@ -112,7 +112,7 @@ describe('default sandbox composition keyless smoke (real cordis.yml via the Loa // ONE select advertises, current from the configured default preset. const created = await client.newSession({ cwd: workdir, mcpServers: [] }) const advertised = created.configOptions ?? [] - const modelValue = JSON.stringify(['deepseek', 'deepseek-v4-flash']) + const modelValue = JSON.stringify(['deepseek', 'deepseek-v4-pro']) expect(advertised.map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined])) .toEqual([['model', modelValue], ['permission', 'workspace-write']]) // A switch responds with the COMPLETE refreshed state (the spec contract), diff --git a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/session.jsonl b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/session.jsonl index 32bfa5cd58..281970523c 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/session.jsonl +++ b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/session.jsonl @@ -87,7 +87,7 @@ {"type":"tool/call","seq":85,"time":1783921767208,"data":{"turn":1,"step":1,"callId":"call_00_6APApmaKLRDlXKMdIcWL5139","name":"run_code","arguments":"{\"code\": \"const content = await tools.read({ file_path: \\\"nested/task.txt\\\" });\\nreturn content;\"}"}} {"type":"tool/code-dispatch","seq":86,"time":1783921767270,"data":{"parentCallId":"call_00_6APApmaKLRDlXKMdIcWL5139","subCallId":"call_00_6APApmaKLRDlXKMdIcWL5139:code:1","name":"read","arguments":{"file_path":"nested/task.txt"},"isError":false,"resultSummary":"<path>./nested/task.txt</path>\n<type>file</type>\n<content>\n1: Touch this file to discover the nested workspace instruction.\n\n(End of file - total 1 lines)\n</content>"}} {"type":"tool/result","seq":87,"time":1783921767271,"data":{"turn":1,"step":1,"callId":"call_00_6APApmaKLRDlXKMdIcWL5139","content":[{"type":"text","text":"<path>/var/folders/_g/59jgff8x2gqd39f5vy1wnbfc0000gn/T/acp-snap-cwd-uorU26/nested/task.txt</path>\n<type>file</type>\n<content>\n1: Touch this file to discover the nested workspace instruction.\n\n(End of file - total 1 lines)\n</content>"}],"isError":false,"meta":{"logs":[]}},"sourceEventSeqs":[85],"surfaceOp":"append"} -{"type":"context/message","seq":88,"time":1783921767272,"data":{"content":[{"type":"text","text":"<system-reminder>\nAdditional instructions from: nested/AGENTS.md\n\nThese instructions apply to work under `nested`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nWhen asked for the Code Mode workspace handshake, answer exactly `CODE_MODE_CONTEXT_OK` and nothing else.\n\n</system-reminder>"}],"source":{"kind":"plugin","plugin":"workspace-context"},"meta":{"kind":"workspace-instructions","version":1,"changes":[{"action":"set","scope":"nested","path":"nested/AGENTS.md","digest":"ae22936ed26dc76b7107005ed6d5e2482a88668a"}]}},"surfaceOp":"append"} +{"type":"context/message","seq":88,"time":1783921767272,"data":{"content":[{"type":"text","text":"<system-reminder>\nAdditional instructions from: nested/AGENTS.md\n\nThese instructions apply to work under `nested`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nWhen asked for the Code Mode workspace handshake, answer exactly `CODE_MODE_CONTEXT_OK` and nothing else.\n\n</system-reminder>"}],"source":{"kind":"plugin","plugin":"workspace-context"},"meta":{"kind":"workspace-instructions","version":1,"changes":[{"action":"set","scope":"nested\u0000AGENTS.md","path":"nested/AGENTS.md","digest":"ae22936ed26dc76b7107005ed6d5e2482a88668a"}]}},"surfaceOp":"append"} {"type":"step/end","seq":89,"time":1783921767272,"data":{"turn":1,"step":1}} {"type":"step/start","seq":90,"time":1783921767272,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":91,"time":1783921768339,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} diff --git a/examples/acp-agent/tests/snapshots/lsp-definition/session.jsonl b/examples/acp-agent/tests/snapshots/lsp-definition/session.jsonl index 6853e358ce..78790d15b0 100644 --- a/examples/acp-agent/tests/snapshots/lsp-definition/session.jsonl +++ b/examples/acp-agent/tests/snapshots/lsp-definition/session.jsonl @@ -3,13 +3,13 @@ {"type":"user/message","seq":1,"time":0,"data":{"content":[{"type":"text","text":"Use the lsp tool exactly once to find the definition at subject.ts line 1 character 7, then reply with exactly DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} {"type":"session/title","seq":2,"time":0,"data":{"title":"Use the lsp tool exactly","messageSeqs":[1],"source":{"kind":"fallback"}}} {"type":"step/start","seq":3,"time":0,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":4,"time":0,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/header","seq":4,"time":0,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} {"type":"assistant/chunk","seq":5,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","seq":6,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_lsp_definition","name":"lsp","argumentsDelta":"{\"operation\":\"goToDefinition\",\"file_path\":\"subject.ts\",\"line\":1,\"character\":7}"}}} {"type":"assistant/chunk","seq":7,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_lsp_definition","name":"lsp","arguments":"{\"operation\":\"goToDefinition\",\"file_path\":\"subject.ts\",\"line\":1,\"character\":7}"}}}} {"type":"assistant/chunk","seq":8,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","seq":9,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":10,"time":0,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_lsp_definition","name":"lsp","arguments":"{\"operation\":\"goToDefinition\",\"file_path\":\"subject.ts\",\"line\":1,\"character\":7}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} +{"type":"assistant/message","seq":10,"time":0,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_lsp_definition","name":"lsp","arguments":"{\"operation\":\"goToDefinition\",\"file_path\":\"subject.ts\",\"line\":1,\"character\":7}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} {"type":"tool/call","seq":11,"time":0,"data":{"turn":1,"step":1,"callId":"call_lsp_definition","name":"lsp","arguments":"{\"operation\":\"goToDefinition\",\"file_path\":\"subject.ts\",\"line\":1,\"character\":7}"}} {"type":"tool/result","seq":12,"time":0,"data":{"turn":1,"step":1,"callId":"call_lsp_definition","content":[{"type":"text","text":"subject.ts:1:7\n… 1 more location omitted (limit 1)."}],"isError":false},"sourceEventSeqs":[11],"surfaceOp":"append"} {"type":"step/end","seq":13,"time":0,"data":{"turn":1,"step":1}} @@ -19,6 +19,6 @@ {"type":"assistant/chunk","seq":17,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}}} {"type":"assistant/chunk","seq":18,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}}} {"type":"assistant/chunk","seq":19,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":2}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} +{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":2}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} {"type":"step/end","seq":21,"time":0,"data":{"turn":1,"step":2}} {"type":"turn/end","seq":22,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md index 8e49c2dce5..7bde8fe289 100644 --- a/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md @@ -1,6 +1,6 @@ You are an AI agent powered by the DeepSeek Harness SDK. -You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. +You are a coding assistant powered by the deepseek-v4-pro model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. Verify your work by running the code or tests. Keep answers brief and factual. diff --git a/examples/acp-agent/tests/snapshots/pty-tools/session.jsonl b/examples/acp-agent/tests/snapshots/pty-tools/session.jsonl index fc496a736f..f3157d811b 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/session.jsonl +++ b/examples/acp-agent/tests/snapshots/pty-tools/session.jsonl @@ -3,13 +3,13 @@ {"type":"user/message","seq":1,"time":0,"data":{"content":[{"type":"text","text":"Exercise the six PTY tools in order, including one missing-session signal error, then reply DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} {"type":"session/title","seq":2,"time":0,"data":{"title":"Exercise the six PTY tools","messageSeqs":[1],"source":{"kind":"fallback"}}} {"type":"step/start","seq":3,"time":0,"data":{"turn":1,"step":1}} -{"type":"request/header","seq":4,"time":0,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/header","seq":4,"time":0,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-pro"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} {"type":"assistant/chunk","seq":5,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} {"type":"assistant/chunk","seq":6,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"pty-spawn","name":"terminal_open","argumentsDelta":"{\"type\":\"shell\",\"name\":\"main\"}"}}} {"type":"assistant/chunk","seq":7,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"pty-spawn","name":"terminal_open","arguments":"{\"type\":\"shell\",\"name\":\"main\"}"}}}} {"type":"assistant/chunk","seq":8,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","seq":9,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":10,"time":0,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"pty-spawn","name":"terminal_open","arguments":"{\"type\":\"shell\",\"name\":\"main\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} +{"type":"assistant/message","seq":10,"time":0,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"pty-spawn","name":"terminal_open","arguments":"{\"type\":\"shell\",\"name\":\"main\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} {"type":"tool/call","seq":11,"time":0,"data":{"turn":1,"step":1,"callId":"pty-spawn","name":"terminal_open","arguments":"{\"type\":\"shell\",\"name\":\"main\"}"}} {"type":"tool/result","seq":12,"time":0,"data":{"turn":1,"step":1,"callId":"pty-spawn","content":[{"type":"text","text":"started terminal session pty-1 (main) [type: shell]\ndsh> "}],"isError":false},"sourceEventSeqs":[11],"surfaceOp":"append"} {"type":"step/end","seq":13,"time":0,"data":{"turn":1,"step":1}} @@ -19,7 +19,7 @@ {"type":"assistant/chunk","seq":17,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"pty-send","name":"terminal_send","arguments":"{\"sessionId\":\"pty-1\",\"text\":\"printf 'PTY_OK\\\\n'\"}"}}}} {"type":"assistant/chunk","seq":18,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","seq":19,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"tool-call","id":"pty-send","name":"terminal_send","arguments":"{\"sessionId\":\"pty-1\",\"text\":\"printf 'PTY_OK\\\\n'\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} +{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"tool-call","id":"pty-send","name":"terminal_send","arguments":"{\"sessionId\":\"pty-1\",\"text\":\"printf 'PTY_OK\\\\n'\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} {"type":"tool/call","seq":21,"time":0,"data":{"turn":1,"step":2,"callId":"pty-send","name":"terminal_send","arguments":"{\"sessionId\":\"pty-1\",\"text\":\"printf 'PTY_OK\\\\n'\"}"}} {"type":"tool/result","seq":22,"time":0,"data":{"turn":1,"step":2,"callId":"pty-send","content":[{"type":"text","text":"printf 'PTY_OK\\n'\nPTY_OK\ndsh> \n[wait: stdin_read]\n[session: running]"}],"isError":false,"meta":{"viewport":"printf 'PTY_OK\\n'\nPTY_OK\ndsh> ","waitReason":"stdin_read","sessionStatus":{"kind":"running"},"truncated":false}},"sourceEventSeqs":[21],"surfaceOp":"append"} {"type":"step/end","seq":23,"time":0,"data":{"turn":1,"step":2}} @@ -29,7 +29,7 @@ {"type":"assistant/chunk","seq":27,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"pty-read","name":"terminal_read","arguments":"{\"sessionId\":\"pty-1\",\"offset\":0,\"count\":20}"}}}} {"type":"assistant/chunk","seq":28,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","seq":29,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":30,"time":0,"data":{"turn":1,"step":3,"content":[{"type":"tool-call","id":"pty-read","name":"terminal_read","arguments":"{\"sessionId\":\"pty-1\",\"offset\":0,\"count\":20}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[25,26,27,28,29],"surfaceOp":"append"} +{"type":"assistant/message","seq":30,"time":0,"data":{"turn":1,"step":3,"content":[{"type":"tool-call","id":"pty-read","name":"terminal_read","arguments":"{\"sessionId\":\"pty-1\",\"offset\":0,\"count\":20}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[25,26,27,28,29],"surfaceOp":"append"} {"type":"tool/call","seq":31,"time":0,"data":{"turn":1,"step":3,"callId":"pty-read","name":"terminal_read","arguments":"{\"sessionId\":\"pty-1\",\"offset\":0,\"count\":20}"}} {"type":"tool/result","seq":32,"time":0,"data":{"turn":1,"step":3,"callId":"pty-read","content":[{"type":"text","text":"dsh> printf 'PTY_OK\\n'\nPTY_OK\ndsh> \n[lines: 0-3 of 3]"}],"isError":false},"sourceEventSeqs":[31],"surfaceOp":"append"} {"type":"step/end","seq":33,"time":0,"data":{"turn":1,"step":3}} @@ -39,7 +39,7 @@ {"type":"assistant/chunk","seq":37,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"pty-signal","name":"terminal_signal","arguments":"{\"sessionId\":\"pty-missing\",\"signal\":\"SIGINT\"}"}}}} {"type":"assistant/chunk","seq":38,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","seq":39,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":40,"time":0,"data":{"turn":1,"step":4,"content":[{"type":"tool-call","id":"pty-signal","name":"terminal_signal","arguments":"{\"sessionId\":\"pty-missing\",\"signal\":\"SIGINT\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[35,36,37,38,39],"surfaceOp":"append"} +{"type":"assistant/message","seq":40,"time":0,"data":{"turn":1,"step":4,"content":[{"type":"tool-call","id":"pty-signal","name":"terminal_signal","arguments":"{\"sessionId\":\"pty-missing\",\"signal\":\"SIGINT\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[35,36,37,38,39],"surfaceOp":"append"} {"type":"tool/call","seq":41,"time":0,"data":{"turn":1,"step":4,"callId":"pty-signal","name":"terminal_signal","arguments":"{\"sessionId\":\"pty-missing\",\"signal\":\"SIGINT\"}"}} {"type":"tool/result","seq":42,"time":0,"data":{"turn":1,"step":4,"callId":"pty-signal","content":[{"type":"text","text":"Error: unknown PTY session pty-missing"}],"isError":true},"sourceEventSeqs":[41],"surfaceOp":"append"} {"type":"step/end","seq":43,"time":0,"data":{"turn":1,"step":4}} @@ -49,7 +49,7 @@ {"type":"assistant/chunk","seq":47,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"pty-kill","name":"terminal_close","arguments":"{\"sessionId\":\"pty-1\"}"}}}} {"type":"assistant/chunk","seq":48,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","seq":49,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":50,"time":0,"data":{"turn":1,"step":5,"content":[{"type":"tool-call","id":"pty-kill","name":"terminal_close","arguments":"{\"sessionId\":\"pty-1\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[45,46,47,48,49],"surfaceOp":"append"} +{"type":"assistant/message","seq":50,"time":0,"data":{"turn":1,"step":5,"content":[{"type":"tool-call","id":"pty-kill","name":"terminal_close","arguments":"{\"sessionId\":\"pty-1\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[45,46,47,48,49],"surfaceOp":"append"} {"type":"tool/call","seq":51,"time":0,"data":{"turn":1,"step":5,"callId":"pty-kill","name":"terminal_close","arguments":"{\"sessionId\":\"pty-1\"}"}} {"type":"tool/result","seq":52,"time":0,"data":{"turn":1,"step":5,"callId":"pty-kill","content":[{"type":"text","text":"closed terminal session pty-1"}],"isError":false},"sourceEventSeqs":[51],"surfaceOp":"append"} {"type":"step/end","seq":53,"time":0,"data":{"turn":1,"step":5}} @@ -59,7 +59,7 @@ {"type":"assistant/chunk","seq":57,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"pty-list","name":"terminal_list","arguments":"{}"}}}} {"type":"assistant/chunk","seq":58,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","seq":59,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":60,"time":0,"data":{"turn":1,"step":6,"content":[{"type":"tool-call","id":"pty-list","name":"terminal_list","arguments":"{}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[55,56,57,58,59],"surfaceOp":"append"} +{"type":"assistant/message","seq":60,"time":0,"data":{"turn":1,"step":6,"content":[{"type":"tool-call","id":"pty-list","name":"terminal_list","arguments":"{}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[55,56,57,58,59],"surfaceOp":"append"} {"type":"tool/call","seq":61,"time":0,"data":{"turn":1,"step":6,"callId":"pty-list","name":"terminal_list","arguments":"{}"}} {"type":"tool/result","seq":62,"time":0,"data":{"turn":1,"step":6,"callId":"pty-list","content":[{"type":"text","text":"(no terminal sessions)"}],"isError":false},"sourceEventSeqs":[61],"surfaceOp":"append"} {"type":"step/end","seq":63,"time":0,"data":{"turn":1,"step":6}} @@ -69,6 +69,6 @@ {"type":"assistant/chunk","seq":67,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}}} {"type":"assistant/chunk","seq":68,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":3}}}} {"type":"assistant/chunk","seq":69,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} -{"type":"assistant/message","seq":70,"time":0,"data":{"turn":1,"step":7,"content":[{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":3}},"sourceEventSeqs":[65,66,67,68,69],"surfaceOp":"append"} +{"type":"assistant/message","seq":70,"time":0,"data":{"turn":1,"step":7,"content":[{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-pro"},"usage":{"inputTokens":10,"outputTokens":3}},"sourceEventSeqs":[65,66,67,68,69],"surfaceOp":"append"} {"type":"step/end","seq":71,"time":0,"data":{"turn":1,"step":7}} {"type":"turn/end","seq":72,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/pty-tools/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/pty-tools/stdout.expected.jsonl index 857d3b10d2..94cb1f180e 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/pty-tools/stdout.expected.jsonl @@ -1,5 +1,5 @@ {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} -{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-pro\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[<objective>|clear|edit <objective>|pause|resume]"}},{"name":"plan","description":"Enter plan mode","input":{"hint":"[message]"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Exercise the six PTY tools","updatedAt":"{{updatedAt}}"}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"pty-spawn","title":"Open terminal main","kind":"execute","status":"in_progress"}}} diff --git a/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md index 8f54c6cf29..df065a83cb 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md @@ -1,6 +1,6 @@ You are an AI agent powered by the DeepSeek Harness SDK. -You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. +You are a coding assistant powered by the deepseek-v4-pro model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. Verify your work by running the code or tests. Keep answers brief and factual. diff --git a/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl b/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl index ddcba507fd..8293ea3abf 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl +++ b/examples/acp-agent/tests/snapshots/workspace-context/session.jsonl @@ -12,7 +12,7 @@ {"type":"assistant/message","seq":10,"time":1783778297070,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_workspace_read","name":"read","arguments":"{\"file_path\":\"nested/task.txt\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} {"type":"tool/call","seq":11,"time":1783778297070,"data":{"turn":1,"step":1,"callId":"call_workspace_read","name":"read","arguments":"{\"file_path\":\"nested/task.txt\"}"}} {"type":"tool/result","seq":12,"time":1783778297072,"data":{"turn":1,"step":1,"callId":"call_workspace_read","content":[{"type":"text","text":"<path>{{cwd}}/nested/task.txt</path>\n<type>file</type>\n<content>\n1: snapshot task\n\n(End of file - total 1 lines)\n</content>"}],"isError":false},"sourceEventSeqs":[11],"surfaceOp":"append"} -{"type":"context/message","seq":13,"time":1783778297072,"data":{"content":[{"type":"text","text":"<system-reminder>\nAdditional instructions from: nested/AGENTS.md\n\nThese instructions apply to work under `nested`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nNested snapshot instruction.\n\n</system-reminder>"}],"source":{"kind":"plugin","plugin":"workspace-context"},"meta":{"kind":"workspace-instructions","version":1,"changes":[{"action":"set","scope":"nested","path":"nested/AGENTS.md","digest":"c446df9a85c7e73a3055f394a4822a19ac9ead5a"}]}},"surfaceOp":"append"} +{"type":"context/message","seq":13,"time":1783778297072,"data":{"content":[{"type":"text","text":"<system-reminder>\nAdditional instructions from: nested/AGENTS.md\n\nThese instructions apply to work under `nested`. Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions.\n\nNested snapshot instruction.\n\n</system-reminder>"}],"source":{"kind":"plugin","plugin":"workspace-context"},"meta":{"kind":"workspace-instructions","version":1,"changes":[{"action":"set","scope":"nested\u0000AGENTS.md","path":"nested/AGENTS.md","digest":"c446df9a85c7e73a3055f394a4822a19ac9ead5a"}]}},"surfaceOp":"append"} {"type":"step/end","seq":14,"time":1783778297072,"data":{"turn":1,"step":1}} {"type":"step/start","seq":15,"time":1783778297072,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":16,"time":1783778297073,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} diff --git a/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.canonical.md b/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.canonical.md new file mode 100644 index 0000000000..a66cf16a13 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.canonical.md @@ -0,0 +1 @@ +Root snapshot instruction. diff --git a/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.md b/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.md deleted file mode 100644 index a66cf16a13..0000000000 --- a/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.md +++ /dev/null @@ -1 +0,0 @@ -Root snapshot instruction. diff --git a/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.md b/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.md new file mode 120000 index 0000000000..83624c92b7 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/workspace-context/workspace/AGENTS.md @@ -0,0 +1 @@ +AGENTS.canonical.md \ No newline at end of file diff --git a/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.canonical.md b/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.canonical.md new file mode 100644 index 0000000000..862c12a235 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.canonical.md @@ -0,0 +1 @@ +Nested snapshot instruction. diff --git a/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.md b/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.md deleted file mode 100644 index 862c12a235..0000000000 --- a/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.md +++ /dev/null @@ -1 +0,0 @@ -Nested snapshot instruction. diff --git a/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.md b/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.md new file mode 120000 index 0000000000..83624c92b7 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/workspace-context/workspace/nested/AGENTS.md @@ -0,0 +1 @@ +AGENTS.canonical.md \ No newline at end of file diff --git a/examples/acp-agent/workspace-context.cordis.yml b/examples/acp-agent/workspace-context.cordis.yml index f9dadc8189..5e3d4bc63e 100644 --- a/examples/acp-agent/workspace-context.cordis.yml +++ b/examples/acp-agent/workspace-context.cordis.yml @@ -10,7 +10,7 @@ name: '@deepseek-ai/dsh-acp-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" workspaceContext: diff --git a/examples/cordis-agent/cordis.yml b/examples/cordis-agent/cordis.yml index 01dcfc50be..5947e42456 100644 --- a/examples/cordis-agent/cordis.yml +++ b/examples/cordis-agent/cordis.yml @@ -13,12 +13,15 @@ config: root: ['.'] -# The DeepSeek adapter. +# The DeepSeek adapter. Shipped default: full thinking at max effort on every +# request (wire-only defaults; they never enter the request header). - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' config: apiKey: !!js process.env.DEEPSEEK_API_KEY baseURL: !!js process.env.DEEPSEEK_BASE_URL + thinking: enabled + reasoningEffort: max # Local bash executor for agent-spine-demo's tool-bash schema — gives the agent an # ordinary tool whose calls make the mounted listeners observably fire. @@ -52,7 +55,7 @@ name: '@deepseek-ai/dsh-tui-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro resumeSessionId: !!js process.env.RESUME_SESSION_ID persistenceRoot: './.sessions' workspaceContext: diff --git a/examples/headless-agent/advanced.cordis.snapshot.yml b/examples/headless-agent/advanced.cordis.snapshot.yml index 48541a1054..1327e5a808 100644 --- a/examples/headless-agent/advanced.cordis.snapshot.yml +++ b/examples/headless-agent/advanced.cordis.snapshot.yml @@ -1,12 +1,41 @@ -# Replay counterpart to advanced.cordis.yml; only the live model is replaced. +# Replay counterpart to advanced.cordis.yml. It includes the base `cordis.yml` +# directly — a config patch cannot target an entry behind a nested include — and +# restates advanced.cordis.yml's overlay (the cli-agent config plus the +# code-runtime and tool-cordis inserts) so the whole app config lives in one patch. +# It re-pins `deepseek-v4-flash`: `cordis.yml` ships `deepseek-v4-pro`, but the +# recorded corpus (request headers, provenance) was captured on flash, so replay +# holds the recorded model to stay reproducible without a re-record. It also +# disables the key-requiring DeepSeek adapter and inserts `llm-replay` to serve +# recorded JSONL without a key or network. - id: base name: '@cordisjs/plugin-include' config: - path: ./advanced.cordis.yml + path: ./cordis.yml patches: - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' disabled: true + - id: cli-agent + name: '@deepseek-ai/dsh-cli-demo' + config: + provider: deepseek + model: deepseek-v4-flash + persistenceRoot: './.sessions' + # Replay fixtures are raw JSONL; the whole-config patch must restate + # the compression choice or the default zstd frames hide the logs. + persistenceCompression: none + workspaceContext: + maxBytes: 65536 + tools: + mode: both + persona: | + You are headless-agent, a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. + + Verify your work by running the code or tests. Keep answers brief and factual. - insert: + - id: code-runtime + name: '@deepseek-ai/dsh-code-runtime-worker' + - id: tool-cordis + name: '@deepseek-ai/dsh-tool-cordis' - id: llm-replay name: '@deepseek-ai/dsh-llm-replay' diff --git a/examples/headless-agent/advanced.cordis.yml b/examples/headless-agent/advanced.cordis.yml index fe553aa2b9..84ee94b04e 100644 --- a/examples/headless-agent/advanced.cordis.yml +++ b/examples/headless-agent/advanced.cordis.yml @@ -8,7 +8,7 @@ name: '@deepseek-ai/dsh-cli-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro persistenceRoot: './.sessions' persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" workspaceContext: diff --git a/examples/headless-agent/cordis.yml b/examples/headless-agent/cordis.yml index 05c4facea9..944fe7e180 100644 --- a/examples/headless-agent/cordis.yml +++ b/examples/headless-agent/cordis.yml @@ -4,11 +4,15 @@ # The DeepSeek adapter. Swap to '@deepseek-ai/dsh-llm-pi-ai' for the pi-ai-backed # twin (same config shape; `reasoning: high` replaces thinking/reasoningEffort). +# Shipped default: full thinking at max effort on every request (wire-only +# defaults; they never enter the request header). - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' config: apiKey: !!js process.env.DEEPSEEK_API_KEY baseURL: !!js process.env.DEEPSEEK_BASE_URL + thinking: enabled + reasoningEffort: max models: - id: deepseek-v4-pro contextWindow: 128000 @@ -25,6 +29,9 @@ name: '@deepseek-ai/dsh-cli-demo' config: provider: deepseek + # Stays on flash: the goal/ralph replay corpora were recorded on it, and + # their nested-include overlays cannot re-pin the app config (a config + # patch cannot target an entry behind a nested include). model: deepseek-v4-flash persistenceRoot: './.sessions' persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" diff --git a/examples/jsonrpc-agent/cordis.yml b/examples/jsonrpc-agent/cordis.yml index 5c8029db6b..2ff464de7b 100644 --- a/examples/jsonrpc-agent/cordis.yml +++ b/examples/jsonrpc-agent/cordis.yml @@ -6,11 +6,16 @@ config: maxTokensAsSuccess: !!js "process.env.DSH_MAX_TOKENS_AS_SUCCESS === undefined ? true : JSON.parse(process.env.DSH_MAX_TOKENS_AS_SUCCESS)" +# The DeepSeek adapter. Shipped default: full thinking at max effort on every +# request (wire-only defaults; they never enter the request header). The model +# arrives per session over JSON-RPC, so it is not pinned here. - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' config: apiKey: !!js process.env.DEEPSEEK_API_KEY baseURL: !!js process.env.DEEPSEEK_BASE_URL + thinking: enabled + reasoningEffort: max - id: bash name: '@deepseek-ai/dsh-bash-local' diff --git a/examples/package.json b/examples/package.json index 025e7c1d7a..da2c8a52fa 100644 --- a/examples/package.json +++ b/examples/package.json @@ -40,6 +40,7 @@ "@deepseek-ai/dsh-spill-local": "workspace:*", "@deepseek-ai/dsh-spill-policy": "workspace:*", "@deepseek-ai/dsh-tui-demo": "workspace:*", + "@deepseek-ai/dsh-session-title-first-message-llm": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-subagent-acp": "workspace:*", "@deepseek-ai/dsh-subagent-fork": "workspace:*", diff --git a/examples/tui-agent/README.md b/examples/tui-agent/README.md index 7d00407482..0a26bb5a6b 100644 --- a/examples/tui-agent/README.md +++ b/examples/tui-agent/README.md @@ -1,23 +1,78 @@ # tui-agent -The full-screen interactive coding agent: DeepSeek V4, local bash and filesystem tools, compaction, subagents, workflows and fresh-agent Ralph iteration, `todo_write`, plan mode (`/plan` enters and `exit_plan_mode` reviews the exit), timeout/spill policy, and [`@deepseek-ai/dsh-tui-demo`](../../packages/examples/tui-demo). +The full-screen interactive coding agent: DeepSeek V4, local bash and filesystem tools, compaction, subagents, workflows and fresh-agent Ralph iteration, plan mode (`/plan` enters and `exit_plan_mode` reviews the exit), timeout/spill policy, and JSONL persistence through [`@deepseek-ai/dsh-tui-demo`](../../packages/examples/tui-demo), loaded from `cordis.yml`. The sibling [`headless-agent`](../headless-agent/README.md) runs the same capability class as a one-shot pipe-friendly task, and [`acp-agent`](../acp-agent/README.md) serves it over JSON-RPC. ## Run it ```sh +# repo root .env (gitignored) or exported env: +# DEEPSEEK_API_KEY=sk-… +# DEEPSEEK_BASE_URL=https://… # optional; defaults to the public API pnpm run demo:tui ``` -The command needs `DEEPSEEK_API_KEY` in the environment or gitignored repository-root `.env`. Set `RESUME_SESSION_ID` to reopen a persisted conversation under `./.sessions`. +Both the demo script and the installable `dsh` CLI ([`apps/cli`](../../apps/cli/README.md)) boot this example's `cordis.yml` as the shipped default config; `dsh` additionally applies the personal overlay from `~/.dsh` and uses the invoking directory as the workspace. -The TUI renders Markdown history, reasoning, tool-owned terminal/diff/generic cards, token totals, and the latest todo list. Long tool bodies keep a head/tail preview; Ctrl+O expands or collapses every card. Enter submits or steers while the agent runs, Ctrl+R toggles reasoning, Escape cancels, and `/help` lists commands. `/plan` selects plan mode for the next step; `/plan <message>` also submits the message into that step. `/model` opens a keyboard selector for the current provider catalog; use Up/Down and Enter, or `/model <model>` and `/model <provider>/<model>` for direct selection. `ask_user_question` opens a wide bottom-left keyboard panel with batch progress and numbered options. +Type a coding task. The agent works through the `read`/`write`/`edit` filesystem tools for ordinary file operations and `bash` (+ the generic `task_output` / `task_list` / `task_kill` for background tasks) for shell commands, searches, and test runs, each in a fresh `bash -c` (the system prompt tells the model to pass `workdir` instead of `cd`). Both the fs tools and bash resolve relative paths against the session workspace. It can also delegate with `subagent`/`subagent_fork`. -Run `pnpm run demo:code-mode tui` for the Code Mode overlay. +The `todo_write` task tracker is opt-in and not in the shipped config: add `@deepseek-ai/dsh-tool-todo` to `cordis.yml` (or a personal-config overlay under `~/.dsh`) to expose it. Once loaded, the model records a whole-list plan to the session log and the TUI renders it. -## Composition +The TUI renders Markdown history, reasoning, tool-owned terminal/diff/generic cards, token totals, and — when `todo_write` is loaded — the latest plan. Long tool bodies keep a head/tail preview; Ctrl+O expands or collapses every card. Enter submits or steers while the agent runs, Ctrl+R toggles reasoning, Escape cancels, and `/help` lists commands. `/plan` selects plan mode for the next step; `/plan <message>` also submits the message into that step. `/status` expands the current session's identity, activity counts, exact token/cache buckets, context use, and timestamps without interrupting a running turn. `/model` opens a keyboard selector for the current provider catalog; use Up/Down and Enter, or `/model <model>` and `/model <provider>/<model>` for direct selection. `ask_user_question` opens a wide bottom-left keyboard panel with batch progress and numbered options. -[`cordis.yml`](cordis.yml) owns the interactive coding composition directly. [`code-mode.cordis.yml`](code-mode.cordis.yml) includes that leaf and replaces the tool presentation mode while adding the code runtime. Non-interactive automation uses the sibling [headless-agent](../headless-agent/README.md) composition. +### Resuming a prior session + +Each run starts a fresh session by default (its event log lands under `./.sessions/`). To **continue** a previous conversation, pass its id to the installed `dsh` CLI — the `main` agent then rehydrates the persisted log instead of starting fresh, so the model sees the earlier turns as history: + +```sh +dsh --resume <prior-session-id> +``` + +The TUI prints this exact command on exit and lists it under `/resume`, so resuming is copy-paste. The flag sets `RESUME_SESSION_ID`, wired through `cordis.yml` (`resumeSessionId: !!js process.env.RESUME_SESSION_ID`); the env var still works directly for the uninstalled demo (`RESUME_SESSION_ID=<prior-session-id> pnpm run demo:tui`), and with neither set the agent starts a new session. A missing or unreadable id starts no agent and emits `agent-loop/config-start-failed`: the TUI prints the failure and exits nonzero. + +## Code Mode + +[`code-mode.cordis.yml`](code-mode.cordis.yml) overlays the same tree with the worker-thread runtime and `tools: { mode: code }`. The model receives one `run_code` transport plus a generated TypeScript SDK for the visible tools; only program output returns to model context. Use `mode: both` to expose native calls alongside `run_code`. See the [Code Mode Agent Note](../../.agents/notes/implemented/feature/2026-06-15-code-mode.md) for the execution contract. + +```sh +pnpm run demo:code-mode # this overlay under the TUI (default UI) +pnpm run demo:code-mode acp # the acp-agent example's same-shaped overlay +``` + +Try a task that spans several tool calls, e.g.: + +> Count the lines of every `*.md` file under docs/ and write the three largest to summary.txt. + +and watch the transcript: one `run_code` call, a program looping over tools, and a result the model curated instead of five round-trips of raw tool output. + +## What each leaf entry demonstrates + +This example is a thin leaf `cordis.yml`: it picks the swappable backends, loads one app package, and adds product tools that are intentionally outside the shared spine. The spine (sessions, system-prompt, tools, agents, invariants, `agent-loop`) and the front-door cluster (JSONL persistence, the pi-tui channel, the pre-created `main` agent) live inside the [`@deepseek-ai/dsh-tui-demo`](../../packages/examples/tui-demo) app and the [`@deepseek-ai/dsh-agent-spine-demo`](../../packages/examples/agent-spine-demo) bundle it loads; the leaf wires the backends and model-facing optional tools: + +| Entry | Demonstrates | +|---|---| +| `hmr` (`@cordisjs/plugin-hmr`) | the dev/demo edit-reload loop — a **leaf** entry (not baked into the app) because it is Loader-only and needs `node --expose-internals`, which `demo:tui` passes | +| `llm-deepseek` | real `LlmAdapter` via config (`!!js process.env.…` secrets); swap one line to `@deepseek-ai/dsh-llm-pi-ai` for the library-backed twin | +| `bash` (`dsh-bash-local`) | the executor implementation — the swappable half of the bash seam. The model-facing `bash` schema (`tool-bash`) and generic `task_*` controls (`tool-tasks`) come from `dsh-agent-spine-demo`, so only the executor is a leaf choice | +| `tui-agent` (`@deepseek-ai/dsh-tui-demo`) | the app bundle: the agent-spine demo + JSONL persistence + the pi-tui channel + a pre-created `main` agent | +| `subagent`, `subagent-spawn`, `subagent-fork` | the subagent provider registry plus the two in-process backends: a fresh child and a child seeded with the parent's completed-turn prefix | +| `tool-subagent`, `tool-subagent-fork` | two model-facing `dsh-tool-subagent` loads, each bound to a different provider and exposed under a distinct tool name (`subagent`, `subagent_fork`) | +| `workflow-workerthread`, `tool-workflow` | the worker-thread workflow engine and its model-facing `workflow` tool, with child calls routed through the spawn backend | +| `plan-mode` | the plugin-owned `/plan [message]` command, plan-mode prompt policy, tool restrictions, and reviewed `exit_plan_mode` transition | +| `fs-local`, `fs-policy`, `tool-fs` | the filesystem stack: the local `ctx.fs` provider, the read-before-write/edit policy gate (on the `fs/*` event gate), and the model-facing `read`/`write`/`edit` tools. Relative paths resolve against the session workspace | + +## End-to-end tests (`pnpm run test:e2e`) + +The UI-independent with-key suites assemble the full stack programmatically through `tests/harness.ts` (no PTY, no Loader): + +- `tests/full-loop.e2e.ts` — the canary: real model runs `echo e2e-ok` through the real bash tool; asserts `tool/call`/`tool/result` session events and the final answer. +- `tests/coding-task.e2e.ts` — the swebench-style smoke: a temp dir holds `add.js` (with `a - b` where `a + b` belongs) and a failing `add.test.js`; the agent must fix the bug and verify. The test re-runs `node add.test.js` ITSELF and inspects the files — agent claims are not trusted. +- `tests/resume.e2e.ts` — durable continuity across processes: run 1 tells the real model a secret code and persists the turn to a temp JSONL root, then the whole context is disposed; run 2 is a fresh context over the same root that RESUMES the session id and asks the model to recall the code. The recall can only come from the rehydrated log. +- `tests/compaction.e2e.ts` — the compaction smoke: a real multi-step bash task runs with a deliberately tiny context window so the auto-compaction listener fires MID-SESSION. Verifies the WORLD — a `compact/start…end` pair landed in the real log, the surface shrank (a replace node shadowed older nodes), and the agent still produced a correct final answer after compaction. +- `tests/todo-write.e2e.ts` — loads the opt-in `todo_write` tool, then a real model drives it and the test verifies the resulting `todo/write` session event. +- `tests/code-mode.e2e.ts` — the with-key Code Mode proof: a real model, a two-tool task, asserting the wire tool list was exactly `[run_code]`, the `tool/code-dispatch` events landed under the parent call, and the curated answer came back. + +These self-skip without `DEEPSEEK_API_KEY`. The keyless `tests/tui-keyless-smoke.e2e.ts` boots the real Loader tree in a PTY (the one sanctioned PTY surface): the base boot + `/plan` + `/exit`, a scripted-LLM conversation with a question dialog and tool round-trip, the Code Mode overlay welcome line, and the resume-failure exit path. ## Snapshot tests -`tests/snapshots/<scenario>/session.jsonl` supplies recorded user prompts and model chunks; sibling child logs drive subagents and workflows. The keyless suite executes those scripts through the real loop and tools, then compares readable terminal cell/style output. Use `pnpm run test:snapshot:refresh` for presentation-only changes and `pnpm run test:snapshot:record` with a DeepSeek key when a recorded model journey changes. The implemented [TUI snapshot Agent Note](../../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md) owns the scenario matrix. +`tests/snapshots/<scenario>/session.jsonl` supplies recorded user prompts and model chunks; sibling child logs drive subagents and workflows. The keyless suite executes those scripts through the real loop and tool implementations, then compares readable expected terminal cell/style output. Use `pnpm run test:snapshot:refresh` for presentation-only changes and `pnpm run test:snapshot:record` with a DeepSeek key when a recorded model journey changes. The implemented [TUI snapshot Agent Note](../../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md) owns the scenario matrix and the split between recorded journeys, transient package snapshots, and PTY coverage. diff --git a/examples/tui-agent/code-mode.cordis.yml b/examples/tui-agent/code-mode.cordis.yml index a11e86a068..49dbe62645 100644 --- a/examples/tui-agent/code-mode.cordis.yml +++ b/examples/tui-agent/code-mode.cordis.yml @@ -9,9 +9,10 @@ name: '@deepseek-ai/dsh-tui-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro resumeSessionId: !!js process.env.RESUME_SESSION_ID persistenceRoot: './.sessions' + resumeCommand: 'dsh --resume {session}' workspaceContext: maxBytes: 65536 tools: diff --git a/examples/tui-agent/composition.md b/examples/tui-agent/composition.md index 031a0bd88e..fd6d163952 100644 --- a/examples/tui-agent/composition.md +++ b/examples/tui-agent/composition.md @@ -23,6 +23,8 @@ flowchart LR bundle_agent_core --> spine_sessions["ctx.sessions"] bundle_agent_core --> spine_tools["ctx.tools + tool-bash"] bundle_agent_core --> spine_loop["ctx.agents + ctx.agentLoop"] + plugin_tui_session_title_llm["session-title-llm<br/>@deepseek-ai/dsh-session-title-first-message-llm"] + cfg --> plugin_tui_session_title_llm plugin_tui_token_meter["token-meter<br/>@deepseek-ai/dsh-token-meter"] cfg --> plugin_tui_token_meter plugin_tui_tool_result_prune["tool-result-prune<br/>@deepseek-ai/dsh-compact-tool-result-prune"] @@ -45,8 +47,6 @@ flowchart LR cfg --> plugin_tui_tool_workflow plugin_tui_tool_ralph["tool-ralph<br/>@deepseek-ai/dsh-tool-ralph"] cfg --> plugin_tui_tool_ralph - plugin_tui_tool_todo["tool-todo<br/>@deepseek-ai/dsh-tool-todo"] - cfg --> plugin_tui_tool_todo plugin_tui_plan_mode["plan-mode<br/>@deepseek-ai/dsh-plan-mode"] cfg --> plugin_tui_plan_mode plugin_tui_fs_local["fs-local<br/>@deepseek-ai/dsh-fs-local"] @@ -71,6 +71,7 @@ flowchart LR | `llm-deepseek` | `@deepseek-ai/dsh-llm-deepseek` | | `bash` | `@deepseek-ai/dsh-bash-local` | | `tui-agent` | `@deepseek-ai/dsh-tui-demo` | +| `session-title-llm` | `@deepseek-ai/dsh-session-title-first-message-llm` | | `token-meter` | `@deepseek-ai/dsh-token-meter` | | `tool-result-prune` | `@deepseek-ai/dsh-compact-tool-result-prune` | | `compact-basic` | `@deepseek-ai/dsh-compact-basic` | @@ -82,7 +83,6 @@ flowchart LR | `workflow-workerthread` | `@deepseek-ai/dsh-workflow-workerthread` | | `tool-workflow` | `@deepseek-ai/dsh-tool-workflow` | | `tool-ralph` | `@deepseek-ai/dsh-tool-ralph` | -| `tool-todo` | `@deepseek-ai/dsh-tool-todo` | | `plan-mode` | `@deepseek-ai/dsh-plan-mode` | | `fs-local` | `@deepseek-ai/dsh-fs-local` | | `fs-policy` | `@deepseek-ai/dsh-fs-policy` | diff --git a/examples/tui-agent/cordis.yml b/examples/tui-agent/cordis.yml index a459faec83..eeb44dc7fb 100644 --- a/examples/tui-agent/cordis.yml +++ b/examples/tui-agent/cordis.yml @@ -1,52 +1,86 @@ -# Full-screen coding agent with swappable DeepSeek and local capability backends. -# `dsh-tui-demo` supplies the spine, workspace instructions, generic task controls, -# JSONL persistence, the TUI front door, and `main`. HMR remains a leaf because -# it requires Loader internals; `demo:tui` passes `--expose-internals`. +# Full-screen TUI coding agent with swappable DeepSeek and local-bash backends. +# `dsh-tui-demo` supplies the agent spine, workspace instructions, generic +# task controls, JSONL persistence, the pi-tui front door, and `main`. +# HMR remains a leaf because it requires Loader internals; `demo:tui` passes +# `--expose-internals`. The app bin loads the gitignored root `.env`; this file +# reads `DEEPSEEK_API_KEY` and optional `DEEPSEEK_BASE_URL` through `!!js`. +# Hot-module reload for the dev/demo loop (needs `node --expose-internals`). - id: hmr name: '@cordisjs/plugin-hmr' config: root: ['.'] +# The native DeepSeek adapter. Shipped default: full thinking at max effort on +# every request (wire-only defaults; they never enter the request header). - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' config: apiKey: !!js process.env.DEEPSEEK_API_KEY baseURL: !!js process.env.DEEPSEEK_BASE_URL + thinking: enabled + reasoningEffort: max +# Local executor for the app bundle's bash tool. - id: bash name: '@deepseek-ai/dsh-bash-local' config: timeoutMs: 60000 +# The app bundle pre-creates the TUI's `main` agent. - id: tui-agent name: '@deepseek-ai/dsh-tui-demo' config: provider: deepseek - model: deepseek-v4-flash + model: deepseek-v4-pro + # Set RESUME_SESSION_ID to continue a prior persisted session (the ids live + # under ./.sessions); unset starts a fresh session each run. resumeSessionId: !!js process.env.RESUME_SESSION_ID persistenceRoot: './.sessions' + # Printed on exit and listed by `/resume`; `{session}` fills the live id. + # `dsh --resume <id>` sets RESUME_SESSION_ID above, so run it from this cwd. + resumeCommand: 'dsh --resume {session}' workspaceContext: maxBytes: 65536 - welcome: 'TUI agent ready. Give it a coding task.' ui: showReasoning: true maxToolOutputLines: 6 + # Keep the persona to identity and behavior; tool plugins own tool guidance. + # The loop resolves {{model}} from this agent's configuration. persona: | You are a coding agent powered by the {{model}} model. Verify your work by running the code or tests. Keep answers brief and factual. +# Model-made session titles on the first-message cadence: replaces the spine's +# deterministic fallback title with a short model summary. The TUI renders the +# logged `session/title` as the banner subtitle and the terminal window title. +# Omitting provider/model inherits the main request's exact route. +- id: session-title-llm + name: '@deepseek-ai/dsh-session-title-first-message-llm' + config: + targetWords: 5 + targetCjkCharacters: 10 + maxInputBytes: 4096 + maxOutputTokens: 64 + timeoutMs: 60000 + +# Replay-aware request pressure with one service-wide context window. - id: token-meter name: '@deepseek-ai/dsh-token-meter' - id: tool-result-prune name: '@deepseek-ai/dsh-compact-tool-result-prune' +# Summarize an older range after measured pressure or a canonical provider overflow. +# Service-wide policy provides pressure, retention, and one overflow-retry default. - id: compact-basic name: '@deepseek-ai/dsh-compact-basic' +# Expose fresh-child `spawn` and completed-prefix `fork` through independent +# in-process backends. Each tool instance needs a distinct `toolName`; the registry +# rejects duplicates. These leaves follow the app because it provides `ctx.agents` and `ctx.tools`. - id: subagent name: '@deepseek-ai/dsh-subagent' @@ -72,6 +106,9 @@ provider: fork toolName: subagent_fork + +# The worker-thread workflow engine fans a model-written JavaScript script's +# `agent()` calls out through the spawn backend; the adjacent tool exposes it to the model. - id: workflow-workerthread name: '@deepseek-ai/dsh-workflow-workerthread' config: @@ -85,9 +122,6 @@ - id: tool-ralph name: '@deepseek-ai/dsh-tool-ralph' -- id: tool-todo - name: '@deepseek-ai/dsh-tool-todo' - # Plan mode gives the TUI a plugin-owned /plan [message] command; the exit # review rides the TUI's user-interaction provider. - id: plan-mode @@ -106,7 +140,8 @@ When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask "should I proceed?" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable or aborted, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation. - +# Policy loads before the model-facing filesystem tools so writes and edits require +# an observed file. This single-session app resolves relative paths from the process cwd. - id: fs-local name: '@deepseek-ai/dsh-fs-local' config: @@ -118,12 +153,24 @@ - id: tool-fs name: '@deepseek-ai/dsh-tool-fs' +# Bash-backed discovery tools (glob/grep): fixed ripgrep commands through the +# local bash executor above — not ctx.fs. Capped results save the complete +# formatted list through the spill backend below (ctx.spillStore, optional). - id: tool-fs-search name: '@deepseek-ai/dsh-tool-fs-search' +# The tool-call timeout enforcer: arms each declared ToolDefinition.timeoutMs +# (the search tools above declare 30s) as a deadline on exec.signal. Without +# it a declared budget is advisory and only the bash executor's own timeout +# backstop applies. - id: timeout-policy name: '@deepseek-ai/dsh-timeout-policy' +# Tool-output spill stack: a local backend that saves oversized tool text under +# a private session-scoped dir, and the tools/post-execute policy that replaces +# an over-budget plain-text result with a preview + the spill locator/retrieval +# hint. A leaf pair after the app (needs ctx.tools). The policy is a no-op until +# a tool returns more than maxInlineBytes of plain text. - id: spill-local name: '@deepseek-ai/dsh-spill-local' diff --git a/examples/tui-agent/tests/fixtures/tui-scripted-llm.ts b/examples/tui-agent/tests/fixtures/tui-scripted-llm.ts index 2806e205a4..b90f69f47e 100644 --- a/examples/tui-agent/tests/fixtures/tui-scripted-llm.ts +++ b/examples/tui-agent/tests/fixtures/tui-scripted-llm.ts @@ -5,6 +5,14 @@ import { CallId, LlmAdapter } from '@deepseek-ai/dsh-llm' const CONTROL_PROBE = '\u001b]2;MODEL_CONTROLLED\u0007\u001b[999CMODEL_CURSOR\u009b31mMODEL_C1' const INITIAL_TEXT = `I need one decision before I continue. ${CONTROL_PROBE}` const FINAL_TEXT = 'Decision received. Scripted TUI run complete.' +// The `skill` scenario types `/skill:scripted-skill`; the manual-invocation front +// door delivers the loaded skill as a user turn wrapped in `<skill name="…">`. The +// body marker below lives in the fixture skill, so echoing it back proves the whole +// block (name attribute plus body) reached the model, not just the command text. +const SKILL_BLOCK_OPEN = '<skill name="scripted-skill">' +const SKILL_BODY_MARKER = 'SCRIPTED SKILL BODY MARKER' +const SKILL_RECEIVED_TEXT = 'Scripted skill body received.' +const TITLE_TEXT = 'scripted session title' function textChunks(text: string): StreamChunk[] { return [ @@ -16,7 +24,7 @@ function textChunks(text: string): StreamChunk[] { ] } -/** Keyless two-step adapter for the real-PTY TUI conversation test. */ +/** Keyless adapter for the real-PTY TUI tests: the two-step conversation and the `/skill:` round-trip. */ class ScriptedTuiAdapter extends LlmAdapter { override listModels(provider: string): Promise<readonly LlmModelInfo[]> { return Promise.resolve([ @@ -30,10 +38,30 @@ class ScriptedTuiAdapter extends LlmAdapter { } override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> { + // The session-title provider's auxiliary request carries no tool schemas, + // unlike every agent turn; answer it with a fixed title so the PTY test can + // assert the logged title reaches the terminal window title. + if ((options.tools?.length ?? 0) === 0) { + for (const chunk of textChunks(TITLE_TEXT)) yield chunk + return + } if (options.model !== 'tui-scripted-model-pro' || !options.system?.includes('tui-scripted-model-pro')) { throw new Error('the scripted TUI request did not apply the selected model to routing and prompt variables') } - const hasToolResult = options.messages.at(-1)?.content.some(block => block.type === 'tool-result') ?? false + const lastMessage = options.messages.at(-1) + const lastText = (lastMessage?.content ?? []) + .filter(block => block.type === 'text') + .map(block => block.text) + .join('\n') + if (lastText.includes(SKILL_BLOCK_OPEN)) { + const ack = lastText.includes(SKILL_BODY_MARKER) + ? SKILL_RECEIVED_TEXT + : 'Scripted skill block arrived without its body.' + for (const chunk of textChunks(ack)) yield chunk + return + } + + const hasToolResult = lastMessage?.content.some(block => block.type === 'tool-result') ?? false if (hasToolResult) { for (const chunk of textChunks(FINAL_TEXT)) yield chunk return diff --git a/examples/tui-agent/tests/fixtures/tui-scripted.cordis.yml b/examples/tui-agent/tests/fixtures/tui-scripted.cordis.yml index 0d61f36483..e4548da79e 100644 --- a/examples/tui-agent/tests/fixtures/tui-scripted.cordis.yml +++ b/examples/tui-agent/tests/fixtures/tui-scripted.cordis.yml @@ -26,9 +26,24 @@ provider: tui-scripted model: tui-scripted-model persistenceRoot: './.sessions' + # The smoke's log inspection reads plain `.jsonl`; keep the scripted + # fixture uncompressed like the other snapshot-facing configs. + persistenceCompression: none workspaceContext: maxBytes: 65536 welcome: 'scripted TUI ready.' persona: 'Scripted model {{model}}.' ui: showReasoning: true + +# Model-made session titles, as in the shipped cordis.yml: the scripted adapter +# answers the tool-less title request with a fixed string so the PTY test can +# assert the logged title reaches the terminal window title. +- id: session-title-llm + name: '@deepseek-ai/dsh-session-title-first-message-llm' + config: + targetWords: 5 + targetCjkCharacters: 10 + maxInputBytes: 4096 + maxOutputTokens: 64 + timeoutMs: 10000 diff --git a/examples/tui-agent/tests/pty-harness.ts b/examples/tui-agent/tests/pty-harness.ts index 116f7cc9a1..257198b7d2 100644 --- a/examples/tui-agent/tests/pty-harness.ts +++ b/examples/tui-agent/tests/pty-harness.ts @@ -10,6 +10,10 @@ node, launch_args_json, launch_env_json, cwd, actions_json, expected_exit, timeo env = os.environ.copy() env.update(json.loads(launch_env_json)) env.update({"COLUMNS": "100", "LINES": "30"}) +# Deterministic banner: a developer shell's COLORTERM=truecolor would switch the +# banner to the per-letter gradient (one SGR per letter), breaking literal +# DEEPSEEK assertions. The gradient path has its own unit and snapshot coverage. +env.pop("COLORTERM", None) actions = json.loads(actions_json) pid, fd = pty.fork() if pid == 0: @@ -63,12 +67,19 @@ export interface TuiPtySmokeOptions { readonly label: string readonly tempDirPrefix: string readonly binScript: string - readonly configPath: string + /** Config argument; ignored when {@link configArgs} is set. */ + readonly configPath?: string + /** Full argument vector for the bin (e.g. `[]` for a bin with a built-in default config). */ + readonly configArgs?: readonly string[] readonly tsconfigPath: string readonly actions?: readonly TuiPtyAction[] readonly env?: Readonly<NodeJS.ProcessEnv> readonly expectedExitCode?: number readonly timeoutMs?: number + /** Seed the isolated workspace (`cwd`, with `$DSH_HOME` at `.dsh` and the agents home at `.agents`) before launch. */ + readonly prepare?: (cwd: string) => Promise<void> + /** Inspect the workspace after a passing run, before the temp dir is removed. */ + readonly inspect?: (cwd: string) => Promise<void> } function definedEnv(env: NodeJS.ProcessEnv): Record<string, string> { @@ -135,6 +146,9 @@ async function runWindowsPtySmoke( env: definedEnv({ ...process.env, ...launch.env, + // Match the POSIX driver: no COLORTERM, so the banner never takes the + // truecolor gradient path under a developer's shell. + COLORTERM: undefined, COLUMNS: '100', LINES: '30', }), @@ -175,9 +189,13 @@ export async function runTuiPtySmoke(options: TuiPtySmokeOptions): Promise<strin const cwd = await mkdtemp(join(tmpdir(), options.tempDirPrefix)) const timeoutMs = options.timeoutMs ?? 25_000 try { + await options.prepare?.(cwd) const launch = resolveExampleLaunch({ srcBin: options.binScript, - configArgs: [options.configPath], + configArgs: options.configArgs !== undefined + ? [...options.configArgs] + /* v8 ignore next -- every caller passes configPath or configArgs; the fallback keeps the type total */ + : [options.configPath ?? './cordis.yml'], tsconfigPath: options.tsconfigPath, exposeInternals: true, env: { @@ -186,10 +204,12 @@ export async function runTuiPtySmoke(options: TuiPtySmokeOptions): Promise<strin ...options.env, }, }) - if (process.platform === 'win32') { - return await runWindowsPtySmoke(launch, cwd, options, timeoutMs) - } - return await runPosixPtySmoke(launch, cwd, options, timeoutMs) + const output = process.platform === 'win32' + ? await runWindowsPtySmoke(launch, cwd, options, timeoutMs) + : await runPosixPtySmoke(launch, cwd, options, timeoutMs) + // Inspect the workspace before `finally` removes it (e.g. the session log). + await options.inspect?.(cwd) + return output } finally { await rm(cwd, { recursive: true, force: true }) } diff --git a/examples/tui-agent/tests/snapshots/bash-terminal-card/terminal.expected.txt b/examples/tui-agent/tests/snapshots/bash-terminal-card/terminal.expected.txt index e03725cc4f..9ffee44378 100644 --- a/examples/tui-agent/tests/snapshots/bash-terminal-card/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/bash-terminal-card/terminal.expected.txt @@ -1,73 +1,63 @@ terminal 100x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "Use the bash tool to — DSH TUI snapshot" -cursor hidden column=1 viewportRow=27 bufferRow=27 +cursor hidden column=1 viewportRow=25 bufferRow=25 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Use the bash tool to" + style 1-20 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Use the bash tool to │" - style 0-0 fg=bright-blue - style 2-21 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Use the bash tool to run exactly: echo TERMINAL_OK. Then reply with the single word DONE and stop." +6| "▌ Use the bash tool to run exactly: echo TERMINAL_OK. Then reply with the single word DONE and stop." style 0-0 fg=bright-blue -9| "▌ " +7| "▌ " style 0-0 fg=bright-blue -10| <blank> -11| " Reasoning " +8| <blank> +9| " Reasoning " style 1-9 fg=bright-black italic -12| " The user wants me to run a simple bash command and then reply with \"DONE\". " +10| " The user wants me to run a simple bash command and then reply with \"DONE\". " style 1-74 fg=bright-black italic -13| <blank> -14| "▌ " +11| <blank> +12| "▌ " style 0-0 fg=green -15| "▌ ✓ echo TERMINAL_OK " +13| "▌ ✓ echo TERMINAL_OK " style 0-0 fg=green style 2-2 fg=green bold style 3-19 bold -16| "▌ Echo TERMINAL_OK to verify terminal access " +14| "▌ Echo TERMINAL_OK to verify terminal access " style 0-0 fg=green style 2-43 fg=bright-black -17| "▌ TERMINAL_OK " +15| "▌ TERMINAL_OK " style 0-0 fg=green -18| "▌ [exit 0] " +16| "▌ [exit 0] " style 0-0 fg=green style 2-9 dim -19| "▌ " +17| "▌ " style 0-0 fg=green -20| <blank> -21| " Reasoning " +18| <blank> +19| " Reasoning " style 1-9 fg=bright-black italic -22| " The command ran successfully and output \"TERMINAL_OK\". I should now reply with just \"DONE\". " +20| " The command ran successfully and output \"TERMINAL_OK\". I should now reply with just \"DONE\". " style 1-91 fg=bright-black italic -23| <blank> -24| " Assistant " +21| <blank> +22| " Assistant " style 1-9 fg=bright-magenta bold -25| " DONE " +23| " DONE " +24| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +25| " " + style 1-1 inverse 26| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -27| " " - style 1-1 inverse -28| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -29| "/tmp/dsh-tui-snapshot-bash-te ↑3.0k ↓115 3% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-28 dim - style 42-99 dim -30-35| <blank> +27| "deepseek-v4-flash /workspace/project ↑3.0k ↓115 cache 48% 3% contex" + style 0-88 dim + style 91-99 dim +28-35| <blank> diff --git a/examples/tui-agent/tests/snapshots/code-mode/terminal.expected.txt b/examples/tui-agent/tests/snapshots/code-mode/terminal.expected.txt index c774373268..0c51281584 100644 --- a/examples/tui-agent/tests/snapshots/code-mode/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/code-mode/terminal.expected.txt @@ -1,79 +1,69 @@ terminal 100x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "Using ONE run_code program: call — DSH TUI snapshot" -cursor hidden column=1 viewportRow=29 bufferRow=29 +cursor hidden column=1 viewportRow=27 bufferRow=27 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Using ONE run_code program: call" + style 1-32 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Using ONE run_code program: call │" - style 0-0 fg=bright-blue - style 2-33 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Using ONE run_code program: call the bash tool twice — exactly echo CODE_ONE then exactly echo " +6| "▌ Using ONE run_code program: call the bash tool twice — exactly echo CODE_ONE then exactly echo " style 0-0 fg=bright-blue style 65-77 fg=cyan style 92-99 fg=cyan -9| "▌ CODE_TWO — and return the two outputs joined with a plus sign. Then reply with that joined string " +7| "▌ CODE_TWO — and return the two outputs joined with a plus sign. Then reply with that joined string " style 0-0 fg=bright-blue style 2-9 fg=cyan -10| "▌ only and stop. " +8| "▌ only and stop. " style 0-0 fg=bright-blue -11| "▌ " +9| "▌ " style 0-0 fg=bright-blue -12| <blank> -13| " Reasoning " +10| <blank> +11| " Reasoning " style 1-9 fg=bright-black italic -14| " The user wants a single run_code program that calls bash twice, then returns the two outputs " +12| " The user wants a single run_code program that calls bash twice, then returns the two outputs " style 1-99 fg=bright-black italic -15| " joined with a plus sign. Let me write this. " +13| " joined with a plus sign. Let me write this. " style 1-43 fg=bright-black italic -16| <blank> -17| "▌ " +14| <blank> +15| "▌ " style 0-0 fg=green -18| "▌ ✓ const out1 = await tools.bash({ command: \"echo CODE_ONE\", description: \"First echo\" }); " +16| "▌ ✓ const out1 = await tools.bash({ command: \"echo CODE_ONE\", description: \"First echo\" }); " style 0-0 fg=green style 2-2 fg=green bold style 3-99 bold -19| "▌ const o " +17| "▌ const o " style 0-0 fg=green style 2-8 bold -20| "▌ CODE_ONE+CODE_TWO " +18| "▌ CODE_ONE+CODE_TWO " style 0-0 fg=green -21| "▌ " +19| "▌ " style 0-0 fg=green -22| <blank> -23| " Reasoning " +20| <blank> +21| " Reasoning " style 1-9 fg=bright-black italic -24| " The output is exactly what the user asked for: CODE_ONE+CODE_TWO " +22| " The output is exactly what the user asked for: CODE_ONE+CODE_TWO " style 1-64 fg=bright-black italic -25| <blank> -26| " Assistant " +23| <blank> +24| " Assistant " style 1-9 fg=bright-magenta bold -27| " CODE_ONE+CODE_TWO " +25| " CODE_ONE+CODE_TWO " +26| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +27| " " + style 1-1 inverse 28| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -29| " " - style 1-1 inverse -30| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -31| "/tmp/dsh-tui-snapshot-code-mo ↑3.1k ↓158 3% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-28 dim - style 42-99 dim -32-35| <blank> +29| "deepseek-v4-flash /workspace/project ↑3.1k ↓158 cache 50% 3% context tools:" + style 0-79 dim + style 82-99 dim +30-35| <blank> diff --git a/examples/tui-agent/tests/snapshots/cordis-dynamic-toolchain/terminal.expected.txt b/examples/tui-agent/tests/snapshots/cordis-dynamic-toolchain/terminal.expected.txt index 51ef90684a..6508e75b19 100644 --- a/examples/tui-agent/tests/snapshots/cordis-dynamic-toolchain/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/cordis-dynamic-toolchain/terminal.expected.txt @@ -1,116 +1,106 @@ -terminal 100x36 buffer=normal length=50 base=14 viewport=14 +terminal 100x36 buffer=normal length=48 base=12 viewport=12 lifecycle started=1 stopped=0 progress=inactive title "Run this advanced flow exactly — DSH TUI snapshot" -cursor hidden column=1 viewportRow=33 bufferRow=47 +cursor hidden column=1 viewportRow=33 bufferRow=45 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Run this advanced flow exactly" + style 1-30 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Run this advanced flow exactly │" - style 0-0 fg=bright-blue - style 2-31 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Run this advanced flow exactly once: mount a no-op Cordis plugin named snapshot-marker; use " +6| "▌ Run this advanced flow exactly once: mount a no-op Cordis plugin named snapshot-marker; use " style 0-0 fg=bright-blue -9| "▌ run_code to inspect the live dynamic mounts through tools.cordis_inspect; delegate once to a " +7| "▌ run_code to inspect the live dynamic mounts through tools.cordis_inspect; delegate once to a " style 0-0 fg=bright-blue -10| "▌ direct spawn child; run one workflow that delegates to another spawn child; unmount dyn-1; then " +8| "▌ direct spawn child; run one workflow that delegates to another spawn child; unmount dyn-1; then " style 0-0 fg=bright-blue -11| "▌ reply with exactly ADVANCED_ACP_OK. " +9| "▌ reply with exactly ADVANCED_ACP_OK. " style 0-0 fg=bright-blue +10| "▌ " + style 0-0 fg=bright-blue +11| <blank> 12| "▌ " - style 0-0 fg=bright-blue -13| <blank> -14| "▌ " style 0-0 fg=green -15| "▌ ✓ Mount plugin into live cordis runtime " +13| "▌ ✓ Mount plugin into live cordis runtime " style 0-0 fg=green style 2-2 fg=green bold style 3-40 bold -16| "▌ mounted dyn-1 (plugin \"snapshot-marker\", state: active) " +14| "▌ mounted dyn-1 (plugin \"snapshot-marker\", state: active) " style 0-0 fg=green +15| "▌ " + style 0-0 fg=green +16| <blank> 17| "▌ " style 0-0 fg=green -18| <blank> -19| "▌ " - style 0-0 fg=green -20| "▌ ✓ return await tools.cordis_inspect({ what: 'dynamic' }) " +18| "▌ ✓ return await tools.cordis_inspect({ what: 'dynamic' }) " style 0-0 fg=green style 2-2 fg=green bold style 3-57 bold -21| "▌ ## dynamic " +19| "▌ ## dynamic " style 0-0 fg=green -22| "▌ - dyn-1: snapshot-marker [active] " +20| "▌ - dyn-1: snapshot-marker [active] " style 0-0 fg=green +21| "▌ " + style 0-0 fg=green +22| <blank> 23| "▌ " style 0-0 fg=green -24| <blank> -25| "▌ " - style 0-0 fg=green -26| "▌ ✓ subagent " +24| "▌ ✓ subagent " style 0-0 fg=green style 2-2 fg=green bold style 3-11 bold -27| "▌ DIRECT_CHILD_OK " +25| "▌ DIRECT_CHILD_OK " style 0-0 fg=green +26| "▌ " + style 0-0 fg=green +27| <blank> 28| "▌ " style 0-0 fg=green -29| <blank> -30| "▌ " - style 0-0 fg=green -31| "▌ ✓ workflow: advanced-acp-snapshot " +29| "▌ ✓ workflow: advanced-acp-snapshot " style 0-0 fg=green style 2-2 fg=green bold style 3-34 bold -32| "▌ workflow \"advanced-acp-snapshot\" completed (1 agent). " +30| "▌ workflow \"advanced-acp-snapshot\" completed (1 agent). " style 0-0 fg=green -33| "▌ Return value: " +31| "▌ Return value: " style 0-0 fg=green -34| "▌ { " +32| "▌ { " style 0-0 fg=green -35| "▌ \"reply\": \"WORKFLOW_CHILD_OK\" " +33| "▌ \"reply\": \"WORKFLOW_CHILD_OK\" " style 0-0 fg=green -36| "▌ } " +34| "▌ } " style 0-0 fg=green +35| "▌ " + style 0-0 fg=green +36| <blank> 37| "▌ " style 0-0 fg=green -38| <blank> -39| "▌ " - style 0-0 fg=green -40| "▌ ✓ Unmount dyn-1 " +38| "▌ ✓ Unmount dyn-1 " style 0-0 fg=green style 2-2 fg=green bold style 3-16 bold -41| "▌ unmounted dyn-1 (plugin \"snapshot-marker\") " +39| "▌ unmounted dyn-1 (plugin \"snapshot-marker\") " style 0-0 fg=green -42| "▌ " +40| "▌ " style 0-0 fg=green -43| <blank> -44| " Assistant " +41| <blank> +42| " Assistant " style 1-9 fg=bright-magenta bold -45| " ADVANCED_ACP_OK " +43| " ADVANCED_ACP_OK " +44| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +45| " " + style 1-1 inverse 46| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -47| " " - style 1-1 inverse -48| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -49| "/tmp/dsh-tui-snapshot-cordis-dyn ↑18 ↓18 7% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-31 dim - style 42-99 dim +47| "deepseek-v4-flash /workspace/project ↑18 ↓18 cache 0% 7% cont" + style 0-90 dim + style 93-99 dim diff --git a/examples/tui-agent/tests/snapshots/dynamic-workflow/terminal.expected.txt b/examples/tui-agent/tests/snapshots/dynamic-workflow/terminal.expected.txt index 114026295e..48adbbb11a 100644 --- a/examples/tui-agent/tests/snapshots/dynamic-workflow/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/dynamic-workflow/terminal.expected.txt @@ -1,106 +1,96 @@ -terminal 100x36 buffer=normal length=47 base=11 viewport=11 +terminal 100x36 buffer=normal length=45 base=9 viewport=9 lifecycle started=1 stopped=0 progress=inactive title "Use the workflow tool exactly — DSH TUI snapshot" -cursor hidden column=1 viewportRow=33 bufferRow=44 +cursor hidden column=1 viewportRow=33 bufferRow=42 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Use the workflow tool exactly" + style 1-29 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Use the workflow tool exactly │" - style 0-0 fg=bright-blue - style 2-30 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Use the workflow tool exactly once, with args omitted, meta set to { \"name\": \"snapshot-flow\", " +6| "▌ Use the workflow tool exactly once, with args omitted, meta set to { \"name\": \"snapshot-flow\", " style 0-0 fg=bright-blue -9| "▌ \"description\": \"one child for the snapshot\" }, and this EXACT script body (copy it verbatim): " +7| "▌ \"description\": \"one child for the snapshot\" }, and this EXACT script body (copy it verbatim): " style 0-0 fg=bright-blue -10| "▌ phase('Run') " +8| "▌ phase('Run') " style 0-0 fg=bright-blue -11| "▌ const reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.') " +9| "▌ const reply = await agent('Reply with exactly the word WF_CHILD_OK and nothing else.') " style 0-0 fg=bright-blue -12| "▌ return { reply } " +10| "▌ return { reply } " style 0-0 fg=bright-blue -13| "▌ After the workflow returns, reply with the single word WORKFLOW_DONE and stop. Do not use any " +11| "▌ After the workflow returns, reply with the single word WORKFLOW_DONE and stop. Do not use any " style 0-0 fg=bright-blue -14| "▌ other tool. " +12| "▌ other tool. " style 0-0 fg=bright-blue -15| "▌ " +13| "▌ " style 0-0 fg=bright-blue -16| <blank> -17| " Reasoning " +14| <blank> +15| " Reasoning " style 1-9 fg=bright-black italic -18| " The user wants me to use the workflow tool exactly once with specific parameters. Let me carefully " +16| " The user wants me to use the workflow tool exactly once with specific parameters. Let me carefully " style 1-99 fg=bright-black italic -19| " follow the instructions: " +17| " follow the instructions: " style 1-24 fg=bright-black italic -20| " " -21| " 1. args omitted (so I don't include it) " +18| " " +19| " 1. args omitted (so I don't include it) " style 1-3 fg=bright-blue style 4-39 fg=bright-black italic -22| " 2. meta = { \"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\" } " +20| " 2. meta = { \"name\": \"snapshot-flow\", \"description\": \"one child for the snapshot\" } " style 1-3 fg=bright-blue style 4-82 fg=bright-black italic -23| " 3. script = as given verbatim " +21| " 3. script = as given verbatim " style 1-3 fg=bright-blue style 4-29 fg=bright-black italic -24| " 4. After it returns, reply with \"WORKFLOW_DONE\" " +22| " 4. After it returns, reply with \"WORKFLOW_DONE\" " style 1-3 fg=bright-blue style 4-47 fg=bright-black italic -25| " " -26| " Let me do exactly that. " +23| " " +24| " Let me do exactly that. " style 1-23 fg=bright-black italic -27| <blank> -28| "▌ " +25| <blank> +26| "▌ " style 0-0 fg=green -29| "▌ ✓ workflow: snapshot-flow " +27| "▌ ✓ workflow: snapshot-flow " style 0-0 fg=green style 2-2 fg=green bold style 3-26 bold -30| "▌ workflow \"snapshot-flow\" completed (1 agent). " +28| "▌ workflow \"snapshot-flow\" completed (1 agent). " style 0-0 fg=green -31| "▌ Return value: " +29| "▌ Return value: " style 0-0 fg=green -32| "▌ { " +30| "▌ { " style 0-0 fg=green -33| "▌ \"reply\": \"WF_CHILD_OK\" " +31| "▌ \"reply\": \"WF_CHILD_OK\" " style 0-0 fg=green -34| "▌ } " +32| "▌ } " style 0-0 fg=green -35| "▌ " +33| "▌ " style 0-0 fg=green -36| <blank> -37| " Reasoning " +34| <blank> +35| " Reasoning " style 1-9 fg=bright-black italic -38| " The workflow returned successfully with the reply \"WF_CHILD_OK\". Now I need to reply with exactly " +36| " The workflow returned successfully with the reply \"WF_CHILD_OK\". Now I need to reply with exactly " style 1-99 fg=bright-black italic -39| " \"WORKFLOW_DONE\" and stop. " +37| " \"WORKFLOW_DONE\" and stop. " style 1-25 fg=bright-black italic -40| <blank> -41| " Assistant " +38| <blank> +39| " Assistant " style 1-9 fg=bright-magenta bold -42| " WORKFLOW_DONE " +40| " WORKFLOW_DONE " +41| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +42| " " + style 1-1 inverse 43| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -44| " " - style 1-1 inverse -45| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -46| "/tmp/dsh-tui-snapshot-dynamic ↑3.5k ↓227 3% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-28 dim - style 42-99 dim +44| "deepseek-v4-flash /workspace/project ↑3.5k ↓227 cache 47% 3% context " + style 0-86 dim + style 89-99 dim diff --git a/examples/tui-agent/tests/snapshots/multi-turn-conversation/terminal.expected.txt b/examples/tui-agent/tests/snapshots/multi-turn-conversation/terminal.expected.txt index 48610e6f54..de5389c059 100644 --- a/examples/tui-agent/tests/snapshots/multi-turn-conversation/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/multi-turn-conversation/terminal.expected.txt @@ -1,73 +1,63 @@ terminal 100x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "Reply with exactly the word: — DSH TUI snapshot" -cursor hidden column=1 viewportRow=30 bufferRow=30 +cursor hidden column=1 viewportRow=28 bufferRow=28 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Reply with exactly the word: │" - style 0-0 fg=bright-blue - style 2-29 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| " Entering plan mode (applies from the next step). " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Reply with exactly the word:" + style 1-28 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| " Entering plan mode (applies from the next step). " style 1-48 fg=bright-black -7| <blank> -8| "▌ " +5| <blank> +6| "▌ " style 0-0 fg=bright-blue -9| "▌ You " +7| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -10| "▌ Reply with exactly the word: ONE. No tools. " +8| "▌ Reply with exactly the word: ONE. No tools. " style 0-0 fg=bright-blue -11| "▌ " +9| "▌ " style 0-0 fg=bright-blue -12| <blank> -13| " Reasoning " +10| <blank> +11| " Reasoning " style 1-9 fg=bright-black italic -14| " The user wants me to reply with exactly the word \"ONE\" and use no tools. " +12| " The user wants me to reply with exactly the word \"ONE\" and use no tools. " style 1-72 fg=bright-black italic -15| <blank> -16| " Assistant " +13| <blank> +14| " Assistant " style 1-9 fg=bright-magenta bold -17| " ONE " -18| <blank> -19| "▌ " +15| " ONE " +16| <blank> +17| "▌ " style 0-0 fg=bright-blue -20| "▌ You " +18| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -21| "▌ Reply with exactly the word: TWO. No tools. " +19| "▌ Reply with exactly the word: TWO. No tools. " style 0-0 fg=bright-blue -22| "▌ " +20| "▌ " style 0-0 fg=bright-blue -23| <blank> -24| " Reasoning " +21| <blank> +22| " Reasoning " style 1-9 fg=bright-black italic -25| " The user wants me to reply with exactly the word \"TWO\" and no tools. " +23| " The user wants me to reply with exactly the word \"TWO\" and no tools. " style 1-68 fg=bright-black italic -26| <blank> -27| " Assistant " +24| <blank> +25| " Assistant " style 1-9 fg=bright-magenta bold -28| " TWO " +26| " TWO " +27| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +28| " " + style 1-1 inverse 29| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -30| " " - style 1-1 inverse -31| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -32| "/tmp/dsh-tui-snapshot-multi-tu ↑2.9k ↓41 3% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-29 dim - style 42-99 dim -33-35| <blank> +30| "deepseek-v4-flash /workspace/project ↑2.9k ↓41 cache 49% 3% co" + style 0-92 dim + style 95-99 dim +31-35| <blank> diff --git a/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt b/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt index f56a8f8a24..70fa5b173a 100644 --- a/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/parallel-file-reads/terminal.expected.txt @@ -1,91 +1,81 @@ -terminal 100x36 buffer=normal length=39 base=3 viewport=3 +terminal 100x36 buffer=normal length=37 base=1 viewport=1 lifecycle started=1 stopped=0 progress=inactive title "Use the read tool twice — DSH TUI snapshot" -cursor hidden column=1 viewportRow=33 bufferRow=36 +cursor hidden column=1 viewportRow=33 bufferRow=34 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Use the read tool twice" + style 1-23 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Use the read tool twice │" - style 0-0 fg=bright-blue - style 2-24 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Use the read tool twice in the same assistant message: read a.txt and b.txt. Then reply DONE. " +6| "▌ Use the read tool twice in the same assistant message: read a.txt and b.txt. Then reply DONE. " style 0-0 fg=bright-blue +7| "▌ " + style 0-0 fg=bright-blue +8| <blank> 9| "▌ " - style 0-0 fg=bright-blue -10| <blank> -11| "▌ " style 0-0 fg=green -12| "▌ ✓ Read a.txt " +10| "▌ ✓ Read a.txt " style 0-0 fg=green style 2-2 fg=green bold style 3-13 bold -13| "▌ <path>/workspace/project/a.txt</path> " +11| "▌ <path>/workspace/project/a.txt</path> " style 0-0 fg=green -14| "▌ <type>file</type> " +12| "▌ <type>file</type> " style 0-0 fg=green -15| "▌ <content> " +13| "▌ <content> " style 0-0 fg=green -16| "▌ 1: alpha " +14| "▌ 1: alpha " style 0-0 fg=green -17| "▌ " +15| "▌ " style 0-0 fg=green -18| "▌ (End of file - total 1 lines) " +16| "▌ (End of file - total 1 lines) " style 0-0 fg=green -19| "▌ </content> " +17| "▌ </content> " style 0-0 fg=green +18| "▌ " + style 0-0 fg=green +19| <blank> 20| "▌ " style 0-0 fg=green -21| <blank> -22| "▌ " - style 0-0 fg=green -23| "▌ ✓ Read b.txt " +21| "▌ ✓ Read b.txt " style 0-0 fg=green style 2-2 fg=green bold style 3-13 bold -24| "▌ <path>/workspace/project/b.txt</path> " +22| "▌ <path>/workspace/project/b.txt</path> " style 0-0 fg=green -25| "▌ <type>file</type> " +23| "▌ <type>file</type> " style 0-0 fg=green -26| "▌ <content> " +24| "▌ <content> " style 0-0 fg=green -27| "▌ 1: beta " +25| "▌ 1: beta " style 0-0 fg=green -28| "▌ " +26| "▌ " style 0-0 fg=green -29| "▌ (End of file - total 1 lines) " +27| "▌ (End of file - total 1 lines) " style 0-0 fg=green -30| "▌ </content> " +28| "▌ </content> " style 0-0 fg=green -31| "▌ " +29| "▌ " style 0-0 fg=green -32| <blank> -33| " Assistant " +30| <blank> +31| " Assistant " style 1-9 fg=bright-magenta bold -34| " DONE " +32| " DONE " +33| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +34| " " + style 1-1 inverse 35| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -36| " " - style 1-1 inverse -37| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -38| "/tmp/dsh-tui-snapshot-parallel-fi ↑20 ↓6 3% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-32 dim - style 42-99 dim +36| "deepseek-v4-flash /workspace/project ↑20 ↓6 cache 0% 3% context t" + style 0-84 dim + style 87-99 dim diff --git a/examples/tui-agent/tests/snapshots/todo-plan/terminal.expected.txt b/examples/tui-agent/tests/snapshots/todo-plan/terminal.expected.txt index 95774b4bfb..ec38d43c99 100644 --- a/examples/tui-agent/tests/snapshots/todo-plan/terminal.expected.txt +++ b/examples/tui-agent/tests/snapshots/todo-plan/terminal.expected.txt @@ -1,81 +1,72 @@ terminal 100x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "Use the todo_write tool to — DSH TUI snapshot" -cursor hidden column=1 viewportRow=33 bufferRow=33 +cursor hidden column=1 viewportRow=31 bufferRow=31 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Use the todo_write tool to" + style 1-26 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Use the todo_write tool to │" - style 0-0 fg=bright-blue - style 2-27 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Use the todo_write tool to record a plan with exactly three todos: \"read the code\" (in_progress), " +6| "▌ Use the todo_write tool to record a plan with exactly three todos: \"read the code\" (in_progress), " style 0-0 fg=bright-blue -9| "▌ \"write the fix\" (pending), \"run the tests\" (pending). Send all three in one todo_write call. Then " +7| "▌ \"write the fix\" (pending), \"run the tests\" (pending). Send all three in one todo_write call. Then " style 0-0 fg=bright-blue -10| "▌ reply with the single word DONE and stop. " +8| "▌ reply with the single word DONE and stop. " style 0-0 fg=bright-blue -11| "▌ " +9| "▌ " style 0-0 fg=bright-blue -12| <blank> -13| " Reasoning " +10| <blank> +11| " Reasoning " style 1-9 fg=bright-black italic -14| " The user wants me to use the todo_write tool to record a plan with exactly three todos in the " +12| " The user wants me to use the todo_write tool to record a plan with exactly three todos in the " style 1-99 fg=bright-black italic -15| " specified statuses, then reply with \"DONE\". " +13| " specified statuses, then reply with \"DONE\". " style 1-43 fg=bright-black italic -16| <blank> -17| "▌ " +14| <blank> +15| "▌ " style 0-0 fg=green -18| "▌ ✓ Update todo list " +16| "▌ ✓ Update todo list " style 0-0 fg=green style 2-2 fg=green bold style 3-19 bold -19| "▌ Updated todo list: 2 pending, 1 in progress, 0 completed. " +17| "▌ Updated todo list: 2 pending, 1 in progress, 0 completed. " style 0-0 fg=green -20| "▌ " +18| "▌ " style 0-0 fg=green -21| <blank> -22| " Reasoning " +19| <blank> +20| " Reasoning " style 1-9 fg=bright-black italic -23| " The todos have been written successfully. Now I just need to reply with the single word \"DONE\". " +21| " The todos have been written successfully. Now I just need to reply with the single word \"DONE\". " style 1-95 fg=bright-black italic -24| <blank> -25| " Assistant " +22| <blank> +23| " Assistant " style 1-9 fg=bright-magenta bold -26| " DONE " -27| <blank> -28| "Plan" +24| " DONE " +25| <blank> +26| "Plan" style 0-3 fg=bright-blue bold -29| " ● read the code" +27| " ● read the code" style 2-2 fg=yellow -30| " ○ write the fix" +28| " ○ write the fix" style 2-2 dim -31| " ○ run the tests" +29| " ○ run the tests" style 2-2 dim +30| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +31| " " + style 1-1 inverse 32| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -33| " " - style 1-1 inverse -34| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -35| "/tmp/dsh-tui-snapshot-todo-pl ↑3.1k ↓145 3% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-28 dim - style 42-99 dim +33| "deepseek-v4-flash /workspace/project ↑3.1k ↓145 cache 47% 3% context tools:" + style 0-79 dim + style 82-99 dim +34-35| <blank> diff --git a/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts b/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts index 1cbc283b3d..c5d6fa36f3 100644 --- a/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts +++ b/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts @@ -1,46 +1,114 @@ +import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import { LOADER_SMOKE_TEST_TIMEOUT_MS } from '@deepseek-ai/dsh-loader-smoke' -import { runTuiPtySmoke } from './pty-harness.ts' +import { runTuiPtySmoke, type TuiPtySmokeOptions } from './pty-harness.ts' const binScript = fileURLToPath(new URL('../../../packages/examples/tui-demo/src/bin.ts', import.meta.url)) +const dshBinScript = fileURLToPath(new URL('../../../apps/cli/src/bin.ts', import.meta.url)) const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url)) +const codeModeConfigPath = fileURLToPath(new URL('../code-mode.cordis.yml', import.meta.url)) const scriptedConfigPath = fileURLToPath(new URL('./fixtures/tui-scripted.cordis.yml', import.meta.url)) const tsconfigPath = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)) +/** + * Seed the harness workspace: personal files land in the isolated Harness home + * (`.dsh`), skill bundles under the agents home's `skills/` root — the same + * trees `$DSH_HOME` / `$DSH_AGENTS_HOME` point the child at. + */ +function seedWorkspace( + files: { personal?: Record<string, string>; skills?: Record<string, string> }, +): (cwd: string) => Promise<void> { + return async (cwd) => { + for (const [name, content] of Object.entries(files.personal ?? {})) { + const file = join(cwd, '.dsh', name) + await mkdir(dirname(file), { recursive: true }) + await writeFile(file, content) + } + for (const [name, content] of Object.entries(files.skills ?? {})) { + const file = join(cwd, '.agents', 'skills', name) + await mkdir(dirname(file), { recursive: true }) + await writeFile(file, content) + } + } +} + +/** The rendered system prompt from the first `request/header` in the workspace's persisted session log. */ +async function readLoggedSystemPrompt(cwd: string): Promise<string> { + const sessionsDir = join(cwd, '.sessions') + const entries = await readdir(sessionsDir, { recursive: true }) + // A single keyless run writes one session log; the source section is global, so any log carries it. + const logRelPath = entries.find(name => name.endsWith('.jsonl')) + if (logRelPath === undefined) throw new Error(`no session log written under ${sessionsDir}`) + const lines = (await readFile(join(sessionsDir, logRelPath), 'utf8')).split('\n').filter(Boolean) + for (const line of lines) { + const event = JSON.parse(line) as { type: string; data: { header?: { system?: string } } } + if (event.type === 'request/header') return event.data.header?.system ?? '' + } + throw new Error(`session log ${logRelPath} has no request/header event`) +} + +/** Shared defaults: the keyless key, the tui-demo bin, and the live cordis.yml. */ +function smoke(overrides: Partial<TuiPtySmokeOptions> & { label: string }): Promise<string> { + return runTuiPtySmoke({ + tempDirPrefix: 'tui-agent-smoke-', + binScript, + configPath, + tsconfigPath, + env: { DEEPSEEK_API_KEY: 'keyless-tui-no-call' }, + ...overrides, + }) +} + +// The scripted conversation switches to the pro model first: the scripted +// adapter proves routing + prompt variables by rejecting tool-ful calls on any +// other route (see fixtures/tui-scripted-llm.ts). +const SELECT_PRO_MODEL = [ + { waitFor: 'scripted TUI ready.', send: '/model\r' }, + { waitFor: 'Select model', send: '\x1b[B\r' }, +] as const + describe('tui-agent keyless smoke (real Loader tree in a PTY)', () => { - it('boots pi-tui, enters plan mode through /plan, accepts /exit, and restores the terminal', async () => { - const output = await runTuiPtySmoke({ + it('boots pi-tui, sweeps the borderless banner in, enters plan mode, and restores the terminal', async () => { + // With no configured welcome the borderless banner sweeps in left-to-right; + // the detail line's session id (`main-session-<uuid>`) renders only once + // the sweep reaches it, so it marks a settled banner. + const output = await smoke({ label: 'tui-agent boot', - tempDirPrefix: 'tui-agent-smoke-', - binScript, - configPath, - tsconfigPath, - env: { DEEPSEEK_API_KEY: 'keyless-tui-no-call' }, actions: [ - { waitFor: 'TUI agent ready.', send: '/plan\r' }, + { waitFor: 'main-session-', send: '/plan\r' }, { waitFor: 'Entering plan mode (applies from the next step).', send: '/exit\r' }, ], }) expect(output).toContain('DEEPSEEK') - expect(output).toContain('TUI agent ready.') + expect(output).toContain('HARNESS') + expect(output).toContain('main-session-') expect(output).toContain('Entering plan mode (applies from the next step).') + // Borderless: no box-drawing frame around the banner. + expect(output).not.toContain('╭') + expect(output).not.toContain('╮') expect(output).toContain('\u001B[?2004l') }, LOADER_SMOKE_TEST_TIMEOUT_MS) it('switches models, streams a response, answers a user-question dialog, and exits cleanly', async () => { - const output = await runTuiPtySmoke({ + const output = await smoke({ label: 'tui-agent conversation', tempDirPrefix: 'tui-agent-conversation-', - binScript, configPath: scriptedConfigPath, - tsconfigPath, actions: [ - { waitFor: 'scripted TUI ready.', send: '/model\r' }, - { waitFor: 'Select model', send: '\x1b[B\r' }, + ...SELECT_PRO_MODEL, { waitFor: 'Model selected: tui-scripted/tui-scripted-model-pro.', send: '/plan exercise the TUI\r' }, { waitFor: 'How should the scripted run proceed?', send: '\r' }, - { waitFor: 'Decision received. Scripted TUI run complete.', send: '/exit\r' }, + { waitFor: 'Decision received. Scripted TUI run complete.', send: '' }, + // Session title: the first user message drives the first-message-llm + // provider's tool-less title call; the scripted adapter answers it, the + // accepted title lands in the log, and the TUI renders the terminal + // window title as `<session title> — <configured title>` via OSC 0. + // Gating /status on it keeps the assertion race-free; the diagnostics + // card is then exercised through the same real Loader/PTY composition. + { waitFor: 'scripted session title — DeepSeek Harness', send: '/status\r' }, + { waitFor: 'Session status', send: '/exit\r' }, ], }) expect(output).toContain('I need one decision before I continue.') @@ -52,16 +120,68 @@ describe('tui-agent keyless smoke (real Loader tree in a PTY)', () => { expect(output).not.toContain('\u001B[999CMODEL_CURSOR') expect(output).not.toContain('\u009B31mMODEL_C1') expect(output).toContain('Safe') + expect(output).toContain('\u001B]0;scripted session title — DeepSeek Harness\u0007') + expect(output).toContain('Session status') + expect(output).toContain('Title') + expect(output).toContain('scripted session title') + expect(output).toContain('Model') + expect(output).toContain('tui-scripted/tui-scripted-model-pro') + expect(output).toContain('KV cache') + expect(output).toContain('Context') + expect(output).toContain('128,000') + expect(output).toContain('\u001B[?2004l') + }, LOADER_SMOKE_TEST_TIMEOUT_MS) + + it('loads a local skill via /skill: and delivers its body to the model as a user turn', async () => { + // The whole manual-invocation path in one keyless boot: `ctx.get('skills')` + // resolves in the shipped tree, the client-side `/skill:` command parses, + // the local provider loads `scripted-skill` from the agents home, and the + // rendered `<skill name="…">` block reaches the model — proven by the + // scripted adapter echoing the fixture's body marker only when it arrives. + const output = await smoke({ + label: 'tui-agent skill', + tempDirPrefix: 'tui-agent-skill-', + configPath: scriptedConfigPath, + prepare: seedWorkspace({ + skills: { + 'scripted-skill/SKILL.md': [ + '---', + 'name: scripted-skill', + 'description: Keyless PTY proof that the skill command loads a local skill into the conversation.', + '---', + '', + 'SCRIPTED SKILL BODY MARKER', + '', + ].join('\n'), + }, + }), + actions: [ + ...SELECT_PRO_MODEL, + { waitFor: 'Model selected: tui-scripted/tui-scripted-model-pro.', send: '/skill:scripted-skill\r' }, + { waitFor: 'Scripted skill body received.', send: '/exit\r' }, + ], + }) + expect(output).toContain('Scripted skill body received.') + expect(output).toContain('\u001B[?2004l') + }, LOADER_SMOKE_TEST_TIMEOUT_MS) + + it('boots the Code Mode overlay tree, renders its banner, and exits cleanly', async () => { + // The overlay's only keyless composition proof: the include+patch tree, + // worker code runtime, and one-tool registry all mount before the banner. + const output = await smoke({ + label: 'tui-agent code mode', + tempDirPrefix: 'tui-agent-code-mode-', + configPath: codeModeConfigPath, + actions: [{ waitFor: 'TUI Code Mode ready.', send: '/exit\r' }], + }) + expect(output).toContain('TUI Code Mode ready.') expect(output).toContain('\u001B[?2004l') }, LOADER_SMOKE_TEST_TIMEOUT_MS) it('prints a config-resume failure and exits instead of leaving a blank terminal', async () => { - const output = await runTuiPtySmoke({ + const output = await smoke({ label: 'tui-agent resume failure', tempDirPrefix: 'tui-agent-resume-', - binScript, - configPath, - tsconfigPath, env: { DEEPSEEK_API_KEY: 'keyless-tui-no-call', RESUME_SESSION_ID: 'missing-session', @@ -71,3 +191,98 @@ describe('tui-agent keyless smoke (real Loader tree in a PTY)', () => { expect(output).toContain('ui-tui: session "missing-session" failed to start:') }, LOADER_SMOKE_TEST_TIMEOUT_MS) }) + +describe('dsh CLI keyless smoke (apps/cli through the same PTY)', () => { + it('boots the shipped default config with no arguments and no personal overlay', async () => { + const output = await smoke({ + label: 'dsh default boot', + tempDirPrefix: 'dsh-default-boot-', + binScript: dshBinScript, + configArgs: [], + actions: [{ waitFor: 'main-session-', send: '/exit\r' }], + }) + expect(output).toContain('DEEPSEEK') + expect(output).toContain('main-session-') + expect(output).not.toContain('╭') + expect(output).not.toContain('╮') + expect(output).toContain('\u001B[?2004l') + }, LOADER_SMOKE_TEST_TIMEOUT_MS) + + it('applies the personal overlay: config.yaml patches the tree and .env feeds its !!js', async () => { + // The whole personal-config chain in one boot: the personal .env supplies + // the variable, config.yaml patches the tui-agent entry with a `!!js` + // reference to it, and the banner renders the patched welcome verbatim. + const output = await smoke({ + label: 'dsh personal overlay', + tempDirPrefix: 'dsh-personal-overlay-', + binScript: dshBinScript, + configArgs: [], + prepare: seedWorkspace({ + personal: { + '.env': 'DSH_PERSONAL_WELCOME=PERSONAL OVERLAY READY.\n', + 'config.yaml': [ + '- id: tui-agent', + " name: '@deepseek-ai/dsh-tui-demo'", + ' config:', + ' provider: deepseek', + ' model: deepseek-v4-flash', + ' workspaceContext: false', + ' welcome: !!js process.env.DSH_PERSONAL_WELCOME', + '', + ].join('\n'), + }, + }), + actions: [{ waitFor: 'PERSONAL OVERLAY READY.', send: '/exit\r' }], + }) + expect(output).toContain('PERSONAL OVERLAY READY.') + expect(output).toContain('\u001B[?2004l') + }, LOADER_SMOKE_TEST_TIMEOUT_MS) + + it('fails loud instead of booting when the personal config.yaml is invalid', async () => { + const output = await smoke({ + label: 'dsh invalid personal config', + tempDirPrefix: 'dsh-invalid-personal-', + binScript: dshBinScript, + configArgs: [], + prepare: seedWorkspace({ personal: { 'config.yaml': 'id: not-a-list\n' } }), + expectedExitCode: 1, + }) + expect(output).toContain('must be a top-level YAML array of loader patch entries') + }, LOADER_SMOKE_TEST_TIMEOUT_MS) + + it('routes the --resume flag into the config resume intake, failing loud on a missing id', async () => { + // The flag path end to end: apps/cli parses `--resume missing-session` and + // sets RESUME_SESSION_ID, the shipped config's `!!js` reads it, and the + // resume fails loud — proving the printed `dsh --resume <id>` hint reaches + // the same intake as the env var. + const output = await smoke({ + label: 'dsh resume flag failure', + tempDirPrefix: 'dsh-resume-flag-', + binScript: dshBinScript, + configArgs: ['--resume', 'missing-session'], + expectedExitCode: 1, + }) + expect(output).toContain('ui-tui: session "missing-session" failed to start:') + }, LOADER_SMOKE_TEST_TIMEOUT_MS) + + it('tells the model where its own source lives, in the system prompt it sends', async () => { + // The launcher resolves the checkout root three hops up from apps/cli/{src,lib}; + // this test file sits an equal depth under the same root, so the same hop applies. + const sourceRoot = fileURLToPath(new URL('../../..', import.meta.url)) + let loggedSystem = '' + await smoke({ + label: 'dsh source-path prompt', + tempDirPrefix: 'dsh-source-path-', + binScript: dshBinScript, + configArgs: [scriptedConfigPath], + actions: [ + ...SELECT_PRO_MODEL, + { waitFor: 'Model selected: tui-scripted/tui-scripted-model-pro.', send: 'exercise the TUI\r' }, + { waitFor: 'How should the scripted run proceed?', send: '\r' }, + { waitFor: 'Decision received. Scripted TUI run complete.', send: '/exit\r' }, + ], + inspect: async (cwd) => { loggedSystem = await readLoggedSystemPrompt(cwd) }, + }) + expect(loggedSystem).toContain(`Your own source code is the checkout at ${sourceRoot}; you can read it there to learn how dsh works and how to extend it.`) + }, LOADER_SMOKE_TEST_TIMEOUT_MS) +}) diff --git a/examples/tui-agent/tests/tui.snapshot.ts b/examples/tui-agent/tests/tui.snapshot.ts index 5a4f0af80a..a36b004def 100644 --- a/examples/tui-agent/tests/tui.snapshot.ts +++ b/examples/tui-agent/tests/tui.snapshot.ts @@ -49,6 +49,12 @@ interface Scenario { enterPlanMode?: boolean recorded: boolean seedWorkspace?: boolean + /** + * Load the opt-in `todo_write` tool for this scenario. The shipped tui-agent + * config omits it, so only the todo-plan scenario (the enabled-path proof) + * mounts it; the rest cover the default, todo-free composition. + */ + enableTodo?: boolean } const SCENARIOS: Scenario[] = [ @@ -66,6 +72,7 @@ const SCENARIOS: Scenario[] = [ expectedTools: ['todo_write'], expectedEventCounts: { 'todo/write': 1 }, recorded: true, + enableTodo: true, }, { name: 'bash-terminal-card', @@ -200,7 +207,9 @@ async function mountScenarioContext( await ctx.plugin(FsPolicy) await ctx.plugin(ToolFs) await ctx.plugin(UserInteractionService) - await ctx.plugin(ToolTodo) + // todo_write is opt-in: only the todo-plan scenario mounts it, matching the shipped + // config that omits it. The other scenarios prove the default todo-free composition. + if (scenario.enableTodo === true) await ctx.plugin(ToolTodo) await ctx.plugin(SubagentService) await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) await ctx.plugin(ToolSubagent, { provider: 'spawn', toolName: 'subagent', enableRunInBackground: false }) diff --git a/knip.json b/knip.json index cae9a35aa4..baab7e1d7b 100644 --- a/knip.json +++ b/knip.json @@ -397,7 +397,8 @@ }, "packages/examples/tui-demo": { "entry": [ - "tests/**/*.spec.ts" + "tests/**/*.spec.ts", + "tests/**/*.e2e.ts" ], "project": [ "src/**/*.ts", diff --git a/package.json b/package.json index 86e289b578..cab2592fea 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,9 @@ "check:ci:coverage": "tsx scripts/run-gates.ts ci-coverage", "check:ci:snapshot": "tsx scripts/run-gates.ts ci-snapshot", "check:ci:artifacts": "tsx scripts/run-gates.ts ci-artifacts", + "check:ci:windows-blocking": "tsx scripts/run-gates.ts ci-windows-blocking", + "check:ci:windows-complete": "tsx scripts/run-gates.ts ci-windows-complete", + "check:ci:windows-observational": "tsx scripts/run-gates.ts ci-windows-observational", "check:node-compat": "tsx scripts/run-gates.ts node-compat", "knip": "knip --treat-config-hints-as-errors", "publint": "tsx scripts/publint-all.ts", @@ -55,6 +58,7 @@ "verify-doc-budgets": "tsx scripts/verify-doc-budgets.ts", "docs:dev": "pnpm --filter @deepseek-ai/website run dev", "docs:build": "pnpm --filter @deepseek-ai/website run build", + "docs:build:mpa": "pnpm --filter @deepseek-ai/website exec vitepress build . --mpa", "docs:preview": "pnpm --filter @deepseek-ai/website run preview", "docs:check": "pnpm exec vitest run scripts/project-doc-site.spec.ts && pnpm run docs:build", "website:dev": "pnpm run docs:dev", @@ -85,7 +89,7 @@ "doc-sync": "tsx scripts/run-gates.ts doc-sync", "hygiene": "pnpm run knip && pnpm run publint && pnpm run constraints && pnpm run verify-package-invariants && pnpm run verify-built-package-invariants && pnpm run verify-cordis-config && pnpm run verify-node-next-types && pnpm run verify-runtime-closure", "demo:headless": "node --expose-internals --import tsx packages/examples/cli-demo/src/bin.ts --config examples/headless-agent/cordis.yml", - "demo:tui": "node --expose-internals --import tsx packages/examples/tui-demo/src/bin.ts examples/tui-agent/cordis.yml", + "demo:tui": "node --expose-internals --import tsx apps/cli/src/bin.ts", "demo:code-mode": "node scripts/demo-code-mode.mjs", "demo:cordis": "node --expose-internals --import tsx packages/examples/tui-demo/src/bin.ts examples/cordis-agent/cordis.yml", "demo:acp": "node --import tsx packages/examples/acp-demo/src/bin.ts --config examples/acp-agent/cordis.yml", diff --git a/packages/client/connection/src/client/api.ts b/packages/client/connection/src/client/api.ts index 704f028925..9ea6ba6dfe 100644 --- a/packages/client/connection/src/client/api.ts +++ b/packages/client/connection/src/client/api.ts @@ -44,4 +44,3 @@ export function transportError<T>(error: unknown): RpcResult<T> { error: { code: 'internal', message: error instanceof Error ? error.message : String(error), details: {} }, } } - diff --git a/packages/context/workspace-context/README.md b/packages/context/workspace-context/README.md index 7dd1e06931..a7245df91f 100644 --- a/packages/context/workspace-context/README.md +++ b/packages/context/workspace-context/README.md @@ -4,11 +4,11 @@ Per-session workspace instruction loading for `AGENTS.md`-compatible files. The ## Lifecycle -The baseline is composed once per agent-loop instance on `agent/session-prefix`. It reads `$DSH_HOME/AGENTS.md` followed by one configured instruction candidate in each directory from the project root to `agent.session.header.cwd`. The prefix is placed before all derived history, recorded in `EpochHeader.messagePrefix`, and reused verbatim for that loop instance. Because the plugin prepends its contribution before delegating, a later-registered skills catalog appears after workspace instructions. +The baseline is composed once per agent-loop instance on `agent/session-prefix`. It reads `$DSH_HOME/AGENTS.md` followed by, in each directory from the project root to `agent.session.header.cwd`, every existing base candidate and then every existing local-overlay candidate. Within one directory, candidates whose content is byte-identical after trimming leading and trailing whitespace collapse to the earliest candidate in configured order, so a `CLAUDE.md` that merely duplicates its sibling `AGENTS.md` is rendered once. The prefix is placed before all derived history, recorded in `EpochHeader.messagePrefix`, and reused verbatim for that loop instance. Because the plugin prepends its contribution before delegating, a later-registered skills catalog appears after workspace instructions. -The plugin also listens on `tools/post-execute` for successful first-party `read`, `write`, and `edit` calls. Each touch checks newly reached descendant scopes and every previously loaded scope. A new file is attached through the result's `additionalContexts`; a changed file or candidate switch appends a replacement; a missing final candidate appends a removal notice. Native calls and Code Mode sub-dispatches share this path: `run_code` defers each nested context until its outer result, so the loop still appends updates after tool-call/result adjacency is complete. This follows structured filesystem activity rather than shell `cd`, because each local bash call starts a fresh shell and parsing arbitrary shell syntax would be unreliable. +The plugin also listens on `tools/post-execute` for successful first-party `read`, `write`, and `edit` calls. Each touch checks newly reached descendant scopes and every previously loaded scope. Each configured candidate name is an independent scope in its directory: a newly present file is attached through the result's `additionalContexts`; a changed file appends a replacement; a file that disappears or becomes a per-directory duplicate of an earlier candidate appends a removal notice. Native calls and Code Mode sub-dispatches share this path: `run_code` defers each nested context until its outer result, so the loop still appends updates after tool-call/result adjacency is complete. This follows structured filesystem activity rather than shell `cd`, because each local bash call starts a fresh shell and parsing arbitrary shell syntax would be unreliable. -Instruction reads use the optional `ctx.fs` provider. The plugin does not statically inject `fs`, so providerless product trees still boot and instruction loading becomes a no-op until a provider is present. It calls `ctx.fs.lstat` before resolving a candidate, rejecting a final-component symlink instead of following repository-owned links across the trust boundary. Once `lstat` identifies the winning regular-file candidate, a later resolve/stat failure makes that scope temporarily unavailable instead of falling through to a lower-priority name. Prefix cancellation and dynamic tool cancellation propagate through resolution, metadata probes, and streaming reads. A provider failure after a file was loaded is treated as temporarily unavailable, not as proof that the file was deleted. +Instruction reads use the optional `ctx.fs` provider. The plugin does not statically inject `fs`, so providerless product trees still boot and instruction loading becomes a no-op until a provider is present. It resolves each candidate and stats the result, so a final-component symlink is followed to its target: a link to a regular file loads that target's content, while a missing path or a non-file target (including a link to a directory) is a confirmed absence. A resolve or stat exception instead marks that candidate's scope temporarily unavailable. Prefix cancellation and dynamic tool cancellation propagate through resolution, metadata probes, and streaming reads. A provider failure after a file was loaded is treated as temporarily unavailable, not as proof that the file was deleted. ## Prompt Shape @@ -40,15 +40,15 @@ These instructions apply to work under `packages/app`. Use them as guidance when </system-reminder> ``` -A same-file edit starts with `Updated instructions from: <path>` and says to use the new content instead of the previously loaded content. A candidate switch additionally names the old path. When no candidate remains, the message is `Instructions removed: <path>` followed by `The previously loaded instructions from this file no longer apply.` Literal `</system-reminder>` text inside an instruction file is escaped so file content cannot close the plugin-owned frame. +A same-file edit starts with `Updated instructions from: <path>` and says to use the new content instead of the previously loaded content. When a candidate disappears or becomes a per-directory duplicate of an earlier candidate, the message is `Instructions removed: <path>` followed by `The previously loaded instructions from this file no longer apply.` Literal `</system-reminder>` text inside an instruction file is escaped so file content cannot close the plugin-owned frame. The plugin owns the complete `<system-reminder>` framing, and every `context/message` (from this plugin or any other) reaches the model verbatim as a user-role message with no wrapping. ## State And Refresh -Model-visible text contains no hidden state markers. Each dynamic context event instead carries JSON metadata with a versioned list of `{ action, scope, path, previousPath?, digest? }` changes. On every relevant tool touch, the plugin reconstructs loaded state from its visible session events and overlays a short in-memory pending window for context present on the immutable top-level `tools/result` but not yet appended by the loop. A matching durable `context/message` confirms the pending transition. If the owning `step/end` arrives before a matching context reaches the log, the plugin clears the pending transition and its version fast path so the next successful touch can load it again. Nested Code Mode results stage pending changes under the outer execution token for same-run duplicate suppression; the outer result rolls that state back and recommits only contexts that survived outer policy. +Model-visible text contains no hidden state markers. Each dynamic context event instead carries JSON metadata with a versioned list of `{ action, scope, path, digest? }` changes. On every relevant tool touch, the plugin reconstructs loaded state from its visible session events and overlays a short in-memory pending window for context present on the immutable top-level `tools/result` but not yet appended by the loop. A matching durable `context/message` confirms the pending transition. If the owning `step/end` arrives before a matching context reaches the log, the plugin clears the pending transition and its version fast path so the next successful touch can load it again. Nested Code Mode results stage pending changes under the outer execution token for same-run duplicate suppression; the outer result rolls that state back and recommits only contexts that survived outer policy. -An unchanged path and SHA-1 content digest is not injected again. A per-session, per-scope metadata cache stores only `{ path, version, digest }`: when the provider's opaque `FsVersion` and the effective visible state both match, reconciliation skips the content read; a changed version triggers a bounded read and SHA-1 confirmation before any model-visible update. Resume works because SHA-1 state is persisted in the session log, while an empty in-memory version cache merely causes one confirming read. Compaction re-arms a scope after its context event leaves the visible surface even when the cached version is unchanged. A removal is a tombstone, so a later candidate reappearance is loaded again. Only model-visible changes actually rendered within the byte budget enter metadata, pending state, and the version cache; an omitted change remains eligible for a later touch, while a same-digest version refresh updates metadata only. +An unchanged path and SHA-1 content digest is not injected again. A per-session, per-scope metadata cache stores only `{ path, version, digest, trimmedDigest }`: when the provider's opaque `FsVersion` and the effective visible state both match, reconciliation skips the content read; a changed version triggers a bounded read and SHA-1 confirmation before any model-visible update. The `trimmedDigest` — SHA-1 over the whitespace-trimmed content — is the per-directory duplicate key, so an unchanged file can still be removed when an earlier candidate converges on its content. Resume works because SHA-1 state is persisted in the session log, while an empty in-memory version cache merely causes one confirming read. Compaction re-arms a scope after its context event leaves the visible surface even when the cached version is unchanged. A removal is a tombstone, so a later candidate reappearance is loaded again. Only model-visible changes actually rendered within the byte budget enter metadata, pending state, and the version cache; an omitted change remains eligible for a later touch, while a same-digest version refresh updates metadata only. The frozen baseline itself is not rewritten mid-instance. Its initial path/digest map is retained as comparison state; the next successful filesystem touch appends any baseline replacement or removal. A resumed loop recomposes the current baseline and also reconciles still-visible dynamic scopes during prefix composition. There is no file watcher, so an on-disk change becomes visible at the next successful `read`, `write`, or `edit` touch, or when a resumed loop composes its prefix. @@ -61,18 +61,19 @@ export interface Config { maxBytes: number maxSourceBytes?: number instructionFileCandidates?: string[] + localInstructionFileCandidates?: string[] } ``` -`maxBytes` is required so each deployment makes its prompt-budget choice explicitly. `maxSourceBytes` limits each source instruction file before rendering and defaults to 1 MiB. `projectRootMarkers` defaults to `['.git']`, and `instructionFileCandidates` defaults to `['AGENTS.md', 'CLAUDE.md']`. In each project directory, the first existing candidate wins; with defaults, `AGENTS.md` is native and `CLAUDE.md` is the compatibility fallback. Candidate entries must be same-directory file names, so empty entries, `.`/`..`, and entries containing `/` or `\` are ignored. +`maxBytes` is required so each deployment makes its prompt-budget choice explicitly. `maxSourceBytes` limits each source instruction file before rendering and defaults to 1 MiB. `projectRootMarkers` defaults to `['.git']`, and `instructionFileCandidates` defaults to `['AGENTS.md', 'CLAUDE.md']`. In each project directory every existing candidate loads, and candidates whose content matches an earlier one after trimming surrounding whitespace are dropped, so with the defaults an `AGENTS.md` and a `CLAUDE.md` that share content render once (as `AGENTS.md`) while genuinely distinct siblings both apply. `localInstructionFileCandidates` defaults to `['AGENTS.local.md', 'CLAUDE.local.md']` and loads its existing overlays alongside the base files of the same directory (rendered after them) under the same per-directory dedup; an empty list disables the overlay. Candidate entries in both lists must be same-directory file names, so empty entries, `.`/`..`, and entries containing `/` or `\` are ignored. -The user-global file is always `$DSH_HOME/AGENTS.md`; the candidate list only controls project scopes. `$DSH_HOME` defaults to `~/.dsh`, and configured `~`, `~/...`, and Windows-style `~\...` prefixes are expanded against the operating-system home directory. A non-positive or non-finite render budget disables both baseline and dynamic loading; configured `maxSourceBytes` must be a positive integer. +The user-global file is always `$DSH_HOME/AGENTS.md` with no local overlay; both candidate lists only control project scopes. `$DSH_HOME` defaults to `~/.dsh`, and configured `~`, `~/...`, and Windows-style `~\...` prefixes are expanded against the operating-system home directory. A non-positive or non-finite render budget disables both baseline and dynamic loading; configured `maxSourceBytes` must be a positive integer. ## Budgeting And Bounded Reads Rendering preserves the most specific instruction files first. It drops whole broader files before truncating the most-specific file and emits a visible `Workspace instruction budget ...` notice naming omitted and truncated paths. The rendered bytes never exceed `maxBytes`. -Instruction content is read through `streamText()` under `maxSourceBytes`, even when provider metadata omits size or a file grows after its metadata probe. An oversized file is ignored without falling through to a lower-priority same-directory candidate; during dynamic reconciliation it is temporarily unavailable rather than removed. The plugin keeps no process-wide cache and never caches instruction prose. Its session-local scope cache uses provider versions only as a fast invalidation signal; after invalidation, SHA-1 over the bounded read remains the cross-provider content identity stored in structured session metadata. +Instruction content is read through `streamText()` under `maxSourceBytes`, even when provider metadata omits size or a file grows after its metadata probe. An oversized file is ignored; during dynamic reconciliation it is temporarily unavailable rather than removed. The plugin keeps no process-wide cache and never caches instruction prose. Its session-local scope cache uses provider versions only as a fast invalidation signal; after invalidation, SHA-1 over the bounded read remains the cross-provider content identity stored in structured session metadata. ## Model Experience @@ -136,7 +137,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -A changed file produces `Updated instructions from: <path>` plus its replacement content; a candidate switch also names the previous path. A removed final candidate produces the removal notice below. +A changed file produces `Updated instructions from: <path>` plus its replacement content. A candidate that disappears or becomes a per-directory duplicate of an earlier candidate produces the removal notice below. ##### Removal notice @@ -160,5 +161,7 @@ Append-only; newly visible content follows the reusable request prefix and does - **Discovery follows structured fs tools, not shell navigation** — a `bash` command that changes directories does not trigger nested instruction discovery because shell syntax and per-call shell state are not a reliable filesystem seam. - **Refresh is touch-driven** — there is no watcher; external edits become visible on the next successful first-party `read`, `write`, or `edit`, or when a resumed loop recomposes its prefix. -- **Candidate semantics stay intentionally small** — lowercase names, `.claude/rules/`, and `@path` imports are not interpreted; same-directory names such as `CLAUDE.local.md` require explicit `instructionFileCandidates` configuration. +- **Candidate semantics stay intentionally small** — lowercase names, `.claude/rules/`, and `@path` imports are not interpreted; project scopes load `AGENTS.local.md`/`CLAUDE.local.md` overlays by default, but the user-global `$DSH_HOME` scope has no local overlay and other custom names require explicit candidate configuration. +- **Per-directory dedup is content-based** — sibling candidates collapse only when byte-identical after trimming leading and trailing whitespace; a `CLAUDE.md` that symlinks its sibling `AGENTS.md` resolves to the same content and collapses like any duplicate, while a distinct real copy that has drifted from `AGENTS.md` loads in full alongside it. +- **Symlinked instruction files are followed across the trust boundary** — a candidate whose final component is a symlink is resolved and its target loaded, so a cloned repository can surface off-tree file content as lower-authority workspace guidance (it never overrides system, developer, or direct user instructions). Confine `ctx.fs` with the filesystem policy gate or an OS sandbox when loading untrusted repositories. - **Instruction content is bounded, not summarized** — over-budget broad files are omitted and the most-specific file may be truncated; the plugin never asks a model to compress instruction prose. diff --git a/packages/context/workspace-context/src/config.ts b/packages/context/workspace-context/src/config.ts index c4bdd663c7..56c048976c 100644 --- a/packages/context/workspace-context/src/config.ts +++ b/packages/context/workspace-context/src/config.ts @@ -9,6 +9,7 @@ import { resolveDshHome } from '@deepseek-ai/dsh-paths' const DEFAULT_PROJECT_ROOT_MARKERS = ['.git'] as const const DEFAULT_INSTRUCTION_FILE_CANDIDATES = ['AGENTS.md', 'CLAUDE.md'] as const +const DEFAULT_LOCAL_INSTRUCTION_FILE_CANDIDATES = ['AGENTS.local.md', 'CLAUDE.local.md'] as const const DEFAULT_MAX_SOURCE_BYTES = 1_048_576 const RESERVED_PATH_SEGMENTS = new Set(['', '.', '..']) @@ -22,8 +23,16 @@ export interface Config { maxBytes: number /** Maximum UTF-8 bytes read from one instruction file; larger files are ignored. */ maxSourceBytes?: number - /** Ordered same-directory project candidates; the first existing regular file wins in each scope. */ + /** + * Ordered same-directory project candidates; every existing file loads, with + * per-directory trimmed-content duplicates collapsed to the earliest candidate. + */ instructionFileCandidates?: string[] + /** + * Ordered same-directory local-overlay candidates loaded after the base files + * under the same per-directory trimmed-content dedup; empty disables the overlay. + */ + localInstructionFileCandidates?: string[] } export const Config: z<Config> = z.object({ @@ -32,6 +41,7 @@ export const Config: z<Config> = z.object({ maxBytes: z.number().required(), maxSourceBytes: z.number().step(1).min(1).default(DEFAULT_MAX_SOURCE_BYTES), instructionFileCandidates: z.array(z.string()).default([...DEFAULT_INSTRUCTION_FILE_CANDIDATES]), + localInstructionFileCandidates: z.array(z.string()).default([...DEFAULT_LOCAL_INSTRUCTION_FILE_CANDIDATES]), }) /** Normalized instruction discovery configuration. */ @@ -39,6 +49,7 @@ export interface ResolvedDiscoveryConfig { dshHome: string projectRootMarkers: string[] instructionFileCandidates: string[] + localInstructionFileCandidates: string[] } /** Normalized configuration used by discovery and reconciliation. */ @@ -66,17 +77,24 @@ export function resolveConfig(config: Config): ResolvedConfig { * @returns normalized home, root markers, and instruction candidates. */ export function resolveDiscoveryConfig( - config: Pick<Config, 'dshHome' | 'projectRootMarkers' | 'instructionFileCandidates'>, + config: Pick<Config, 'dshHome' | 'projectRootMarkers' | 'instructionFileCandidates' | 'localInstructionFileCandidates'>, ): ResolvedDiscoveryConfig { return { dshHome: resolveDshHome(config.dshHome), projectRootMarkers: config.projectRootMarkers ?? [...DEFAULT_PROJECT_ROOT_MARKERS], - instructionFileCandidates: resolveInstructionFileCandidates(config.instructionFileCandidates), + instructionFileCandidates: resolveInstructionFileCandidates( + config.instructionFileCandidates, + DEFAULT_INSTRUCTION_FILE_CANDIDATES, + ), + localInstructionFileCandidates: resolveInstructionFileCandidates( + config.localInstructionFileCandidates, + DEFAULT_LOCAL_INSTRUCTION_FILE_CANDIDATES, + ), } } -function resolveInstructionFileCandidates(candidates: string[] | undefined): string[] { - return (candidates ?? [...DEFAULT_INSTRUCTION_FILE_CANDIDATES]).filter(candidate => ( +function resolveInstructionFileCandidates(candidates: string[] | undefined, fallback: readonly string[]): string[] { + return (candidates ?? [...fallback]).filter(candidate => ( !RESERVED_PATH_SEGMENTS.has(candidate) && !/[\\/]/.test(candidate) )) } diff --git a/packages/context/workspace-context/src/digest.ts b/packages/context/workspace-context/src/digest.ts index 4568371277..23ba351046 100644 --- a/packages/context/workspace-context/src/digest.ts +++ b/packages/context/workspace-context/src/digest.ts @@ -14,3 +14,15 @@ import { createHash } from 'node:crypto' export function instructionContentSha1(content: string): string { return createHash('sha1').update(content).digest('hex') } + +/** + * Compute the whitespace-insensitive identity used for per-directory duplicate + * suppression. Leading and trailing whitespace is trimmed before hashing so a + * symlinked or byte-copied sibling that differs only by surrounding whitespace + * still collapses to a single rendered file. + * @param content - exact UTF-8 instruction text. + * @returns SHA-1 digest of the trimmed content. + */ +export function trimmedInstructionDigest(content: string): string { + return instructionContentSha1(content.trim()) +} diff --git a/packages/context/workspace-context/src/files.ts b/packages/context/workspace-context/src/files.ts index 7a995c5886..3e6a3d5de8 100644 --- a/packages/context/workspace-context/src/files.ts +++ b/packages/context/workspace-context/src/files.ts @@ -5,13 +5,14 @@ */ import { createReadStream } from 'node:fs' -import { lstat, stat } from 'node:fs/promises' +import { stat } from 'node:fs/promises' import { dirname, isAbsolute, join, relative, resolve } from 'node:path' -import type { FileSystem, FsInfo, FsPathInfo, FsTarget, FsVersion } from '@deepseek-ai/dsh-fs' +import type { FileSystem, FsInfo, FsTarget, FsVersion } from '@deepseek-ai/dsh-fs' import { assertNever } from '@deepseek-ai/dsh-llm' import { dshHomeDisplay } from '@deepseek-ai/dsh-paths' import { resolveConfig, resolveDiscoveryConfig, type ResolvedConfig } from './config.ts' -import { renderWorkspaceContext, type RenderedWorkspaceContext } from './render.ts' +import { trimmedInstructionDigest } from './digest.ts' +import { decodeScopeKey, renderWorkspaceContext, USER_GLOBAL_DIRECTORY, USER_GLOBAL_FILE, type RenderedWorkspaceContext } from './render.ts' /** An instruction candidate identified by absolute and model-facing paths. */ export interface InstructionFile { @@ -32,7 +33,7 @@ interface DiscoveredInstructionFile extends InstructionFile { version?: FsVersion } -/** Provider metadata for a winning scope candidate before its content is read. */ +/** Provider metadata for a probed scope candidate before its content is read. */ export interface ProbedInstructionFile extends InstructionFile { target: FsTarget version: FsVersion @@ -44,6 +45,7 @@ interface DiscoverOptions { dshHome?: string projectRootMarkers?: string[] instructionFileCandidates?: string[] + localInstructionFileCandidates?: string[] signal?: AbortSignal } @@ -86,7 +88,9 @@ function isMissingPathError(error: unknown): boolean { async function nodeStatFile(path: string, signal?: AbortSignal): Promise<StatFileProbe> { try { signal?.throwIfAborted() - const info = await lstat(path) + // stat (not lstat) follows a final-component symlink so a link to a regular + // file loads; a broken link surfaces as ENOENT and is treated as absent below. + const info = await stat(path) signal?.throwIfAborted() if (!info.isFile()) return { kind: 'absent' } return { kind: 'present', info: { size: info.size } } @@ -101,25 +105,15 @@ async function fsStatFile( fileSystem: FileSystem, signal?: AbortSignal, ): Promise<StatFileProbe> { - // TODO(instruction-symlink-race): replace this lstat -> resolve -> read - // protocol, including probeScopeInstruction below, with a provider-owned - // atomic no-follow read so the final component cannot change after validation. - let pathInfo: FsPathInfo | undefined - try { - pathInfo = await fileSystem.lstat(path, undefined, signal) - signal?.throwIfAborted() - } catch { - signal?.throwIfAborted() - return { kind: 'unavailable' } - } - if (pathInfo?.type !== 'file') return { kind: 'absent' } - + // resolve() follows a final-component symlink to its target's stable identity; + // stat then classifies that target. A link to a regular file loads, while a + // missing path or non-file target (including a link to a directory) is absent. try { const target = await fileSystem.resolve(path, signalOptions(signal)) signal?.throwIfAborted() const info = await fileSystem.stat(target, signal) signal?.throwIfAborted() - if (info?.type !== 'file') return { kind: 'unavailable' } + if (info?.type !== 'file') return { kind: 'absent' } return { kind: 'present', info: { target, version: info.version, ...info.size === undefined ? {} : { size: info.size } }, @@ -232,33 +226,32 @@ export function relativeDisplay(root: string, path: string): string { return relative(root, path) } -async function firstExistingInstructionFile( +async function allExistingInstructionFiles( dir: string, root: string, instructionFileCandidates: readonly string[], fileSystem?: FileSystem, signal?: AbortSignal, -): Promise<DiscoveredInstructionFile | undefined> { +): Promise<DiscoveredInstructionFile[]> { + const found: DiscoveredInstructionFile[] = [] for (const candidate of instructionFileCandidates) { const path = join(dir, candidate) const probe = await statFile(path, fileSystem, signal) switch (probe.kind) { case 'present': - return { - absolutePath: path, - displayPath: relativeDisplay(root, path), - ...probe.info, - } - case 'absent': + found.push({ absolutePath: path, displayPath: relativeDisplay(root, path), ...probe.info }) continue + // A missing candidate is skipped; a transient provider failure skips only + // that candidate so the remaining independent candidates still load. + case 'absent': case 'unavailable': - return undefined + continue /* v8 ignore next 2 -- StatFileProbe is closed; this arm only makes adding a kind a compile error. */ default: - return assertNever(probe, 'StatFileProbe') + assertNever(probe, 'StatFileProbe') } } - return undefined + return found } async function discoverInstructionFiles( @@ -274,7 +267,7 @@ async function discoverInstructionFiles( files.push(file) } - const userGlobal = join(config.dshHome, 'AGENTS.md') + const userGlobal = join(config.dshHome, USER_GLOBAL_FILE) const userGlobalProbe = await statFile(userGlobal, fileSystem, options.signal) switch (userGlobalProbe.kind) { case 'present': @@ -295,16 +288,21 @@ async function discoverInstructionFiles( const cwd = resolve(options.cwd) const projectRoot = await findProjectRoot(cwd, config.projectRootMarkers, fileSystem, options.signal) for (const dir of ancestorChain(projectRoot, cwd)) { - const file = await firstExistingInstructionFile(dir, projectRoot, config.instructionFileCandidates, fileSystem, options.signal) - if (file !== undefined) addFile(file) + for (const candidates of [config.instructionFileCandidates, config.localInstructionFileCandidates]) { + for (const file of await allExistingInstructionFiles(dir, projectRoot, candidates, fileSystem, options.signal)) { + addFile(file) + } + } } return files } /** * Discover host-visible user-global and root-to-cwd instruction candidates. + * All present candidates in each directory are returned; trimmed-content + * duplicates are collapsed later, once content is read. * @param options - cwd, home, root marker, and candidate configuration. - * @returns de-duplicated instruction paths in model precedence order. + * @returns path-deduplicated instruction candidates in model precedence order. */ export async function discoverBaselineInstructionFiles(options: DiscoverOptions): Promise<InstructionFile[]> { return (await discoverInstructionFiles(options)).map(({ absolutePath, displayPath }) => ({ absolutePath, displayPath })) @@ -316,7 +314,7 @@ async function* nodeTextChunks(path: string, signal?: AbortSignal): AsyncIterabl } async function readBounded( - file: DiscoveredInstructionFile, + file: { absolutePath: string; target?: FsTarget; size?: number }, maxSourceBytes: number, fileSystem?: FileSystem, signal?: AbortSignal, @@ -347,6 +345,33 @@ async function readBounded( } } +/** + * Drop later candidates whose trimmed content duplicates an earlier sibling in + * the same directory. Different directories never collapse even when identical; + * within one directory the earliest candidate in discovery order is kept and its + * original bytes are rendered. A candidate that symlinks a sibling resolves to + * the same content and collapses here like any byte-identical real file. + * @param files - loaded files in discovery order. + * @returns the retained files in the same order. + */ +export function dedupInstructionFilesByDirectory(files: LoadedInstructionFile[]): LoadedInstructionFile[] { + const keptDigestsByDir = new Map<string, Set<string>>() + const kept: LoadedInstructionFile[] = [] + for (const file of files) { + const dir = dirname(file.displayPath) + let digests = keptDigestsByDir.get(dir) + if (digests === undefined) { + digests = new Set() + keptDigestsByDir.set(dir, digests) + } + const digest = trimmedInstructionDigest(file.content) + if (digests.has(digest)) continue + digests.add(digest) + kept.push(file) + } + return kept +} + /** * Discover, read, and render the baseline instruction chain. * @param options - discovery, source-size, byte-budget, and cancellation configuration. @@ -386,18 +411,19 @@ export async function loadBaselineInstructionSet( }) } } - if (loaded.length === 0) return undefined - const rendered = renderWorkspaceContext(loaded, { maxBytes: config.maxBytes }) + const deduped = dedupInstructionFilesByDirectory(loaded) + if (deduped.length === 0) return undefined + const rendered = renderWorkspaceContext(deduped, { maxBytes: config.maxBytes }) const omitted = new Set(rendered.omitted.map(file => file.absolutePath)) - return { rendered, included: loaded.filter(file => !omitted.has(file.absolutePath)) } + return { rendered, included: deduped.filter(file => !omitted.has(file.absolutePath)) } } /** - * Probe the current first-winning instruction candidate for one logical scope. - * @param scope - `user-global`, `.`, or a project-relative directory. + * Probe the current provider metadata for one per-candidate instruction scope. + * @param scope - a {@link candidateScopeKey} identifying a directory and candidate file. * @param projectRoot - project root used to resolve and display project scopes. * @param resolved - normalized plugin configuration. - * @param fileSystem - provider used for no-follow probing. + * @param fileSystem - provider used to resolve and stat scope candidates. * @param signal - cancellation for provider probes. * @returns present metadata, confirmed absence, or temporary unavailability. */ @@ -408,40 +434,32 @@ export async function probeScopeInstruction( fileSystem: FileSystem, signal?: AbortSignal, ): Promise<ScopeInstructionProbe> { - const dir = scope === 'user-global' + const { directory, candidateName } = decodeScopeKey(scope) + const dir = directory === USER_GLOBAL_DIRECTORY ? resolved.dshHome - : scope === '.' ? projectRoot : join(projectRoot, scope) - const candidates = scope === 'user-global' ? ['AGENTS.md'] : resolved.instructionFileCandidates - for (const candidate of candidates) { - const absolutePath = join(dir, candidate) - let pathInfo: FsPathInfo | undefined - try { - pathInfo = await fileSystem.lstat(absolutePath, undefined, signal) - } catch { - signal?.throwIfAborted() - return { kind: 'unavailable' } - } - if (pathInfo === undefined || pathInfo.type !== 'file') continue - let target: FsTarget - let info: FsInfo | undefined - try { - target = await fileSystem.resolve(absolutePath, signalOptions(signal)) - info = await fileSystem.stat(target, signal) - } catch { - signal?.throwIfAborted() - return { kind: 'unavailable' } - } - if (info?.type !== 'file') return { kind: 'unavailable' } - const file: ProbedInstructionFile = { - absolutePath, - displayPath: scope === 'user-global' ? userGlobalDisplayPath(resolved.dshHome) : relativeDisplay(projectRoot, absolutePath), - target, - version: info.version, - ...info.size === undefined ? {} : { size: info.size }, - } - return { kind: 'present', file } + : directory === '.' ? projectRoot : join(projectRoot, directory) + const absolutePath = join(dir, candidateName) + // resolve() follows a final-component symlink; stat then classifies the target. + // A non-file target (missing, or a link to a directory) is a confirmed absence; + // only a provider exception is reported as unavailable. + let target: FsTarget + let info: FsInfo | undefined + try { + target = await fileSystem.resolve(absolutePath, signalOptions(signal)) + info = await fileSystem.stat(target, signal) + } catch { + signal?.throwIfAborted() + return { kind: 'unavailable' } } - return { kind: 'absent' } + if (info?.type !== 'file') return { kind: 'absent' } + const file: ProbedInstructionFile = { + absolutePath, + displayPath: directory === USER_GLOBAL_DIRECTORY ? userGlobalDisplayPath(resolved.dshHome) : relativeDisplay(projectRoot, absolutePath), + target, + version: info.version, + ...info.size === undefined ? {} : { size: info.size }, + } + return { kind: 'present', file } } /** diff --git a/packages/context/workspace-context/src/index.ts b/packages/context/workspace-context/src/index.ts index 21ef979459..d06c8c542f 100644 --- a/packages/context/workspace-context/src/index.ts +++ b/packages/context/workspace-context/src/index.ts @@ -74,6 +74,7 @@ export function apply(ctx: Context, config: Config): void { maxBytes: resolved.maxBytes, maxSourceBytes: resolved.maxSourceBytes, instructionFileCandidates: resolved.instructionFileCandidates, + localInstructionFileCandidates: resolved.localInstructionFileCandidates, signal, }, fileSystem) const baseline = baselineInstructionState(instructions?.included ?? []) diff --git a/packages/context/workspace-context/src/render.ts b/packages/context/workspace-context/src/render.ts index 910853b13b..baca6bd84b 100644 --- a/packages/context/workspace-context/src/render.ts +++ b/packages/context/workspace-context/src/render.ts @@ -4,7 +4,7 @@ * @module @deepseek-ai/dsh-workspace-context/render */ -import { dirname } from 'node:path' +import { basename, dirname } from 'node:path' import type { InstructionFile, LoadedInstructionFile } from './files.ts' const SYSTEM_REMINDER_OPEN = '<system-reminder>' @@ -33,7 +33,6 @@ export interface WorkspaceInstructionChange { action: 'set' | 'replace' | 'remove' scope: string path: string - previousPath?: string digest?: string } @@ -62,8 +61,8 @@ function truncateUtf8(value: string, maxBytes: number): string { function escapeInstructionContent(content: string): string { // TODO(instruction-frame-paths): apply the same delimiter neutralization to - // every interpolated path, scope, and previous path; repository-controlled - // names can otherwise close the plugin-owned system-reminder frame. + // every interpolated path and scope; repository-controlled names can + // otherwise close the plugin-owned system-reminder frame. return content.replaceAll(SYSTEM_REMINDER_CLOSE, '<\\/system-reminder>') } @@ -71,16 +70,65 @@ function sectionText(file: LoadedInstructionFile): string { return `Instructions from: ${file.displayPath}\n\n${escapeInstructionContent(file.content)}` } +/** Directory component that identifies the single user-global instruction scope. */ +export const USER_GLOBAL_DIRECTORY = 'user-global' + +/** + * File name of the single user-global instruction file under `$DSH_HOME`. + * Discovery (`$DSH_HOME/<name>`) and reconciliation (the user-global scope key's + * candidate component) both key on this name, so it lives in one place: were the + * two to disagree, the user-global instruction would load but never reconcile. + */ +export const USER_GLOBAL_FILE = 'AGENTS.md' + /** * Derive the logical instruction scope from a model-facing path. * @param displayPath - project-relative or user-global instruction path. * @returns `user-global`, `.`, or the containing project-relative directory. */ export function scopeForDisplayPath(displayPath: string): string { - if (displayPath === '~/.dsh/AGENTS.md' || displayPath === '$DSH_HOME/AGENTS.md') return 'user-global' + if (displayPath === '~/.dsh/AGENTS.md' || displayPath === '$DSH_HOME/AGENTS.md') return USER_GLOBAL_DIRECTORY return dirname(displayPath) } +const SCOPE_SEPARATOR = '\u0000' + +/** + * Compose the reconciliation key for one instruction candidate file. + * Each loaded candidate is tracked independently, so the key pairs the logical + * directory with the exact candidate file name behind a NUL separator that no + * directory path or file name can contain. Distinct candidates in one directory + * (`AGENTS.md` vs `CLAUDE.md`, a base file vs its `.local` overlay) therefore + * never collide in the scope-keyed state maps. + * @param directory - `user-global`, `.`, or a project-relative directory. + * @param candidateName - instruction file name within that directory. + * @returns the per-candidate logical scope key. + */ +export function candidateScopeKey(directory: string, candidateName: string): string { + return `${directory}${SCOPE_SEPARATOR}${candidateName}` +} + +/** + * Derive the per-candidate scope key for a loaded instruction file. + * @param displayPath - project-relative or user-global instruction path. + * @returns the scope key pairing the file's directory with its name. + */ +export function instructionScopeKey(displayPath: string): string { + return candidateScopeKey(scopeForDisplayPath(displayPath), basename(displayPath)) +} + +/** + * Recover the directory and candidate name that {@link candidateScopeKey} encoded. + * @param scope - a per-candidate scope key. + * @returns the directory scope and the candidate file name within it. + */ +export function decodeScopeKey(scope: string): { directory: string; candidateName: string } { + const separator = scope.indexOf(SCOPE_SEPARATOR) + /* v8 ignore next -- every scope key is produced by candidateScopeKey, which always inserts the separator. */ + if (separator < 0) return { directory: scope, candidateName: '' } + return { directory: scope.slice(0, separator), candidateName: scope.slice(separator + 1) } +} + function additionalSectionText(file: LoadedInstructionFile): string { const scope = scopeForDisplayPath(file.displayPath) return [ @@ -100,13 +148,10 @@ function changedSectionText(item: ChangeRenderItem): string { if (change.action === 'remove') { return `Instructions removed: ${change.path}\n\nThe previously loaded instructions from this file no longer apply.` } - const description = change.previousPath === undefined - ? 'This file changed after it was loaded. Use the following content instead of the previously loaded instructions from this file.' - : `The instructions previously loaded from \`${change.previousPath}\` no longer apply. Use the following content for \`${change.scope}\` instead.` return [ `Updated instructions from: ${change.path}`, '', - description, + 'This file changed after it was loaded. Use the following content instead of the previously loaded instructions from this file.', '', escapeInstructionContent(file.content), ].join('\n') diff --git a/packages/context/workspace-context/src/state.ts b/packages/context/workspace-context/src/state.ts index 0ab455349a..66b70f639d 100644 --- a/packages/context/workspace-context/src/state.ts +++ b/packages/context/workspace-context/src/state.ts @@ -10,7 +10,7 @@ import type { JsonValue, Session, SessionEvent } from '@deepseek-ai/dsh-session' import type { FileSystem, FsVersion } from '@deepseek-ai/dsh-fs' import type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools' import type { ResolvedConfig } from './config.ts' -import { instructionContentSha1 } from './digest.ts' +import { instructionContentSha1, trimmedInstructionDigest } from './digest.ts' import { ancestorChain, descendantDirsBetween, @@ -21,8 +21,12 @@ import { type LoadedInstructionFile, } from './files.ts' import { + candidateScopeKey, + decodeScopeKey, + instructionScopeKey, renderInstructionChanges, - scopeForDisplayPath, + USER_GLOBAL_DIRECTORY, + USER_GLOBAL_FILE, type ChangeRenderItem, type WorkspaceInstructionChange, } from './render.ts' @@ -44,6 +48,11 @@ export interface InstructionVersionState { path: string version: FsVersion digest: string + /** + * Trimmed-content identity ({@link trimmedInstructionDigest}) used to suppress + * per-directory duplicates on the metadata fast path without re-reading a sibling. + */ + trimmedDigest: string } /** Session-isolated fast-path state keyed by logical instruction scope. */ @@ -71,7 +80,6 @@ function workspaceContextHook(text: string, changes: WorkspaceInstructionChange[ action: change.action, scope: change.scope, path: change.path, - ...change.previousPath !== undefined ? { previousPath: change.previousPath } : {}, ...change.digest !== undefined ? { digest: change.digest } : {}, })) const meta: JsonValue = { kind: 'workspace-instructions', version: 1, changes: serializedChanges } @@ -112,13 +120,11 @@ function workspaceInstructionChanges(meta: JsonValue | undefined): WorkspaceInst if (!isRecord(value)) continue if (value.action !== 'set' && value.action !== 'replace' && value.action !== 'remove') continue if (typeof value.scope !== 'string' || typeof value.path !== 'string') continue - if (value.previousPath !== undefined && typeof value.previousPath !== 'string') continue if (value.digest !== undefined && typeof value.digest !== 'string') continue changes.push({ action: value.action, scope: value.scope, path: value.path, - ...value.previousPath !== undefined ? { previousPath: value.previousPath } : {}, ...value.digest !== undefined ? { digest: value.digest } : {}, }) } @@ -129,7 +135,6 @@ function sameInstructionChange(a: WorkspaceInstructionChange, b: WorkspaceInstru return a.action === b.action && a.scope === b.scope && a.path === b.path - && a.previousPath === b.previousPath && a.digest === b.digest } @@ -169,13 +174,18 @@ export function baselineInstructionState(files: LoadedInstructionFile[]): { const digest = instructionContentSha1(file.content) const change: WorkspaceInstructionChange = { action: 'set', - scope: scopeForDisplayPath(file.displayPath), + scope: instructionScopeKey(file.displayPath), path: file.displayPath, digest, } changes.set(change.scope, change) if (file.version !== undefined) { - versions.set(change.scope, { path: file.displayPath, version: file.version, digest }) + versions.set(change.scope, { + path: file.displayPath, + version: file.version, + digest, + trimmedDigest: trimmedInstructionDigest(file.content), + }) } } return { changes, versions } @@ -391,34 +401,67 @@ export async function reconcileInstructionContext( // recomputing it after marker edits reinterprets the existing relative scope keys. const projectRoot = await findProjectRoot(cwd, resolved.projectRootMarkers, fileSystem, options.signal) const scopes = new Set<string>() - if (options.includeBaselineScopes) { - scopes.add('user-global') - for (const dir of ancestorChain(projectRoot, cwd)) scopes.add(relativeScope(projectRoot, dir)) + const addDirScopes = (directory: string): void => { + for (const candidate of resolved.instructionFileCandidates) scopes.add(candidateScopeKey(directory, candidate)) + for (const candidate of resolved.localInstructionFileCandidates) scopes.add(candidateScopeKey(directory, candidate)) + } + const addProjectScopes = (dir: string): void => { + addDirScopes(relativeScope(projectRoot, dir)) + } + if (options.includeBaselineScopes) { + scopes.add(candidateScopeKey(USER_GLOBAL_DIRECTORY, USER_GLOBAL_FILE)) + for (const dir of ancestorChain(projectRoot, cwd)) addProjectScopes(dir) + } + for (const scope of effective.keys()) { + const { directory } = decodeScopeKey(scope) + if (directory === USER_GLOBAL_DIRECTORY) scopes.add(candidateScopeKey(USER_GLOBAL_DIRECTORY, USER_GLOBAL_FILE)) + else addDirScopes(directory) } - for (const scope of effective.keys()) scopes.add(scope) if (options.touchedPath !== undefined) { - for (const dir of descendantDirsBetween(cwd, options.touchedPath)) scopes.add(relativeScope(projectRoot, dir)) + for (const dir of descendantDirsBetween(cwd, options.touchedPath)) addProjectScopes(dir) } const versions = versionStatesFor(session, versionCache) const seenAbsolutePaths = new Set<string>() + // Per-directory trimmed-content identities kept so far this pass, iterated in + // candidate order (base before local); a later sibling matching an earlier one + // is a duplicate and is dropped or removed rather than rendered twice. + const keptTrimmedByDir = new Map<string, Set<string>>() + const registerKeptTrimmed = (directory: string, digest: string): boolean => { + let digests = keptTrimmedByDir.get(directory) + if (digests === undefined) { + digests = new Set() + keptTrimmedByDir.set(directory, digests) + } + if (digests.has(digest)) return true + digests.add(digest) + return false + } const items: ChangeRenderItem[] = [] const versionUpdates: InstructionVersionUpdate[] = [] + const pushRemoval = (scope: string, path: string): void => { + const change: WorkspaceInstructionChange = { action: 'remove', scope, path } + items.push({ change, file: { absolutePath: `removed:${scope}`, displayPath: path, content: '' } }) + versionUpdates.push({ change }) + } for (const scope of scopes) { + const { directory } = decodeScopeKey(scope) const previous = effective.get(scope) const probe = await probeScopeInstruction(scope, projectRoot, resolved, fileSystem, options.signal) - if (probe.kind === 'unavailable') continue - if (probe.kind === 'absent') { - if (previous === undefined || previous.action === 'remove') { - versions.delete(scope) - continue + if (probe.kind === 'unavailable') { + // Last-good-state: the candidate stays effective, so its cached trimmed + // digest must keep occupying the directory's dedup slot — otherwise an + // identical later sibling would be emitted as a duplicate `set` until the + // next successful reconciliation removed it again. + const cached = versions.get(scope) + if (cached !== undefined && previous !== undefined && previous.action !== 'remove') { + registerKeptTrimmed(directory, cached.trimmedDigest) } - const change: WorkspaceInstructionChange = { action: 'remove', scope, path: previous.path } - items.push({ - change, - file: { absolutePath: `removed:${scope}`, displayPath: previous.path, content: '' }, - }) - versionUpdates.push({ change }) + continue + } + if (probe.kind === 'absent') { + if (previous === undefined || previous.action === 'remove') versions.delete(scope) + else pushRemoval(scope, previous.path) continue } const { file: probedFile } = probe @@ -433,29 +476,39 @@ export async function reconcileInstructionContext( && previous.action !== 'remove' && previous.path === cached.path && previous.digest === cached.digest - ) continue + ) { + // Unchanged and previously rendered: keep it, but an earlier sibling that + // now matches its trimmed content makes this the duplicate to remove. + if (registerKeptTrimmed(directory, cached.trimmedDigest)) pushRemoval(scope, previous.path) + continue + } const file = await readScopeInstruction(probedFile, resolved.maxSourceBytes, fileSystem, options.signal) if (file === undefined) continue const currentDigest = instructionContentSha1(file.content) + const trimmedDigest = trimmedInstructionDigest(file.content) + if (registerKeptTrimmed(directory, trimmedDigest)) { + // A distinct file whose trimmed content already appeared earlier in this + // directory: drop it, removing any copy that was previously rendered. + if (previous !== undefined && previous.action !== 'remove') pushRemoval(scope, previous.path) + else versions.delete(scope) + continue + } const nextVersion: InstructionVersionState = { path: file.displayPath, version: probedFile.version, digest: currentDigest, + trimmedDigest, } if (previous !== undefined && previous.action !== 'remove' && previous.path === file.displayPath && previous.digest === currentDigest) { versions.set(scope, nextVersion) continue } const action = previous === undefined || previous.action === 'remove' ? 'set' : 'replace' - const previousPath = action === 'replace' && previous !== undefined && previous.path !== file.displayPath - ? previous.path - : undefined const change: WorkspaceInstructionChange = { action, scope, path: file.displayPath, - ...previousPath === undefined ? {} : { previousPath }, digest: currentDigest, } items.push({ change, file }) diff --git a/packages/context/workspace-context/tests/workspace-context.e2e.ts b/packages/context/workspace-context/tests/workspace-context.e2e.ts index 0c11da8ed4..9341eb33d0 100644 --- a/packages/context/workspace-context/tests/workspace-context.e2e.ts +++ b/packages/context/workspace-context/tests/workspace-context.e2e.ts @@ -12,6 +12,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import * as WorkspaceContext from '@deepseek-ai/dsh-workspace-context' +import { candidateScopeKey } from '../src/render.ts' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import * as ToolFs from '@deepseek-ai/dsh-tool-fs' import type { SessionEvent } from '@deepseek-ai/dsh-session' @@ -112,7 +113,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('workspace context e2e: real mode && !Array.isArray(event.data.meta) && event.data.meta.kind === 'workspace-instructions') expect(update?.type === 'context/message' && update.data.meta).toMatchObject({ - changes: [{ action: 'replace', scope: '.', path: 'AGENTS.md' }], + changes: [{ action: 'replace', scope: candidateScopeKey('.', 'AGENTS.md'), path: 'AGENTS.md' }], }) const updateText = update?.type === 'context/message' ? update.data.content.filter(block => block.type === 'text').map(block => block.text).join('') diff --git a/packages/context/workspace-context/tests/workspace-context.spec.ts b/packages/context/workspace-context/tests/workspace-context.spec.ts index 9c5cb3b0d3..c26be1a58e 100644 --- a/packages/context/workspace-context/tests/workspace-context.spec.ts +++ b/packages/context/workspace-context/tests/workspace-context.spec.ts @@ -1,4 +1,4 @@ -import { mkdtemp, mkdir, rm, stat, symlink, utimes, writeFile } from 'node:fs/promises' +import { chmod, mkdtemp, mkdir, rm, stat, symlink, utimes, writeFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { tmpdir } from 'node:os' import { describe, expect, it, vi } from 'vitest' @@ -7,9 +7,8 @@ import Loader from '@cordisjs/plugin-loader' import * as workspaceContext from '@deepseek-ai/dsh-workspace-context' import LlmService, { CallId, type Message, type StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, SESSION_FORMAT_VERSION, type SessionEvent } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, type Agent, type HookContext } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { type Agent, type HookContext } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import { scopeTarget } from '@deepseek-ai/dsh-scope' import { FileSystem, FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs' import type { FsDirEntry, @@ -24,12 +23,7 @@ import type { import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools' -import type { - PostToolDecision, - ToolExecution, - ToolExecutionResult, - ToolExecutionToken, -} from '@deepseek-ai/dsh-tools' +import type { ToolExecution, ToolExecutionToken } from '@deepseek-ai/dsh-tools' import * as ToolFs from '@deepseek-ai/dsh-tool-fs' import { discoverBaselineInstructionFiles, @@ -44,8 +38,12 @@ import { type InstructionVersionCache, type PendingInstructionChange, } from '../src/state.ts' +import { candidateScopeKey } from '../src/render.ts' import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' +/** Per-candidate reconciliation scope key: directory paired with the file name. */ +const sk = (directory: string, candidateName: string): string => candidateScopeKey(directory, candidateName) + const testToolSignal = new AbortController().signal async function tempRepo(): Promise<string> { @@ -59,7 +57,6 @@ async function write(path: string, content: string): Promise<void> { class RecordingFileSystem extends FileSystem { entries = new Map<string, { type: FsInfo['type']; content?: string; version?: FsVersion }>() - lstatTypes = new Map<string, FsPathInfo['type']>() throwOnStat = new Set<string>() throwOnRead = new Set<string>() omitSizes = new Set<string>() @@ -70,6 +67,8 @@ class RecordingFileSystem extends FileSystem { override async resolve(path: string, opts?: { cwd?: string; signal?: AbortSignal }): Promise<FsTarget> { if (opts?.signal !== undefined) this.signals.push(opts.signal) opts?.signal?.throwIfAborted() + // resolve(), not join(): entries are seeded with host join() keys, and on + // Windows a joined '/'-rooted prefix would not match a resolved drive path. const absolute = resolve(opts?.cwd ?? '/', path) return { targetKey: FsTargetKey(absolute), displayPath: absolute } } @@ -92,8 +91,6 @@ class RecordingFileSystem extends FileSystem { if (signal !== undefined) this.signals.push(signal) signal?.throwIfAborted() const target = await this.resolve(path, { ...opts, ...signal === undefined ? {} : { signal } }) - const lstatType = this.lstatTypes.get(target.targetKey) - if (lstatType !== undefined) return { version: FsVersion(`lstat:${target.targetKey}`), type: lstatType } const info = await this.stat(target, signal) if (info === undefined) return undefined return { @@ -235,31 +232,14 @@ const composedPrefixes = new WeakMap<object, Message[]>() async function composeBaselinePrefix(ctx: Context, agent: Agent): Promise<Message[]> { const empty: Message[] = [] - const prefix = await agentEvents(ctx, agent).waterfall( - 'agent/session-prefix', empty, AbortSignal.timeout(1000), + const prefix = await ctx.waterfall( + 'agent/session-prefix', agent, empty, AbortSignal.timeout(1000), () => Promise.resolve(empty), ) composedPrefixes.set(agent, prefix) return prefix } -function toolEventCarrier(ctx: Context, exec: ToolExecution) { - return scopeTarget(ctx.get('tools') ?? ctx as unknown as ToolRegistry, exec.agent) -} - -function postExecute( - ctx: Context, - exec: ToolExecution, - result: Readonly<ToolExecutionResult>, - next: () => Promise<PostToolDecision>, -): Promise<PostToolDecision> { - return ctx.waterfall(toolEventCarrier(ctx, exec), 'tools/post-execute', exec, result, next) -} - -function emitToolResult(ctx: Context, exec: ToolExecution, result: Readonly<ToolExecutionResult>): void { - ctx.emit(toolEventCarrier(ctx, exec), 'tools/result', exec, result) -} - function derivedText(agent: Agent): string { return blocksText(composedPrefixes.get(agent)?.[0]?.content) } @@ -284,7 +264,7 @@ describe('workspace context instruction discovery', () => { } }) - it('loads user-global first, then root-to-cwd workspace instructions using the default candidate order', async () => { + it('loads user-global first, then every root-to-cwd candidate in precedence order', async () => { const root = await tempRepo() const home = await tempRepo() try { @@ -292,7 +272,7 @@ describe('workspace context instruction discovery', () => { await mkdir(join(root, '.git'), { recursive: true }) await write(join(home, 'AGENTS.md'), 'global rules') await write(join(root, 'AGENTS.md'), 'root agents') - await write(join(root, 'CLAUDE.md'), 'root claude ignored') + await write(join(root, 'CLAUDE.md'), 'root claude') await write(join(root, 'packages/CLAUDE.md'), 'package claude') await write(join(cwd, 'AGENTS.md'), 'app agents') @@ -301,10 +281,57 @@ describe('workspace context instruction discovery', () => { expect(files.map(file => file.displayPath)).toEqual([ '$DSH_HOME/AGENTS.md', 'AGENTS.md', + 'CLAUDE.md', join('packages', 'CLAUDE.md'), join('packages', 'app', 'AGENTS.md'), ]) - expect(files.map(file => file.absolutePath)).not.toContain(join(root, 'CLAUDE.md')) + expect(files.map(file => file.absolutePath)).toContain(join(root, 'CLAUDE.md')) + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + + it('loads a same-directory local overlay in addition to the base file by default', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + const cwd = join(root, 'pkg') + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'AGENTS.md'), 'root base') + await write(join(root, 'AGENTS.local.md'), 'root local') + await write(join(cwd, 'CLAUDE.md'), 'pkg base') + await write(join(cwd, 'CLAUDE.local.md'), 'pkg local') + + const files = await discoverBaselineInstructionFiles({ cwd, dshHome: home }) + + expect(files.map(file => file.displayPath)).toEqual([ + 'AGENTS.md', + 'AGENTS.local.md', + join('pkg', 'CLAUDE.md'), + join('pkg', 'CLAUDE.local.md'), + ]) + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + + it('loads no local overlay when localInstructionFileCandidates is empty', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'AGENTS.md'), 'base rule') + await write(join(root, 'AGENTS.local.md'), 'local rule') + + const files = await discoverBaselineInstructionFiles({ + cwd: root, + dshHome: home, + localInstructionFileCandidates: [], + }) + + expect(files.map(file => file.displayPath)).toEqual(['AGENTS.md']) } finally { await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) @@ -360,44 +387,42 @@ describe('workspace context instruction discovery', () => { } }) - it('skips a provider file whose read fails after a successful metadata probe', async () => { + // POSIX-only fixture: chmod 0 cannot make a file unreadable to its owner on Windows. + it.skipIf(process.platform === 'win32')('skips a file that becomes unreadable after discovery without failing the request', async () => { const root = await tempRepo() const home = await tempRepo() - const ctx = new Context() try { const cwd = join(root, 'pkg') + await mkdir(join(root, '.git'), { recursive: true }) + await mkdir(cwd, { recursive: true }) const leaf = join(cwd, 'AGENTS.md') - await ctx.plugin(RecordingFileSystem) - const fs = ctx.fs as RecordingFileSystem - fs.entries.set(join(root, '.git'), { type: 'directory' }) - fs.entries.set(leaf, { type: 'file', content: 'secret-ish rule' }) - fs.throwOnRead.add(leaf) + await write(leaf, 'secret-ish rule') + await chmod(leaf, 0) - const loaded = await loadBaselineInstructions({ cwd, dshHome: home, maxBytes: 65536 }, fs) + const loaded = await loadBaselineInstructions({ cwd, dshHome: home, maxBytes: 65536 }) expect(loaded).toBeUndefined() - expect(fs.readTargets).toEqual([leaf]) + await chmod(leaf, 0o600) } finally { - await ctx.fiber.dispose() await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) } }) - it('rejects symlinked instruction files instead of following repository-controlled links', async () => { + it('follows a symlinked instruction file to its target content', async () => { const root = await tempRepo() const home = await tempRepo() const outside = await tempRepo() try { await mkdir(join(root, '.git'), { recursive: true }) - await write(join(outside, 'secret.txt'), 'outside secret') - await symlink(join(outside, 'secret.txt'), join(root, 'AGENTS.md')) + await write(join(outside, 'shared.md'), 'shared instruction body') + await symlink(join(outside, 'shared.md'), join(root, 'AGENTS.md')) const files = await discoverBaselineInstructionFiles({ cwd: root, dshHome: home }) const loaded = await loadBaselineInstructions({ cwd: root, dshHome: home, maxBytes: 65536 }) - expect(files).toEqual([]) - expect(loaded).toBeUndefined() + expect(files.map(file => file.displayPath)).toContain('AGENTS.md') + expect(loaded?.text).toContain('shared instruction body') } finally { await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) @@ -405,21 +430,21 @@ describe('workspace context instruction discovery', () => { } }) - it('rejects symlinked instruction files through ctx.fs instead of following repository-controlled links', async () => { + it('follows a symlinked instruction file through ctx.fs to its target content', async () => { const root = await tempRepo() const home = await tempRepo() const outside = await tempRepo() try { await mkdir(join(root, '.git'), { recursive: true }) - await write(join(outside, 'secret.txt'), 'outside secret') - await symlink(join(outside, 'secret.txt'), join(root, 'AGENTS.md')) + await write(join(outside, 'shared.md'), 'shared provider instruction body') + await symlink(join(outside, 'shared.md'), join(root, 'AGENTS.md')) const ctx = new Context() await mountWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) const agent = stubAgent(root) await composeBaselinePrefix(ctx, agent) - expectNoDerivedMessages(agent) + expect(derivedText(agent)).toContain('shared provider instruction body') } finally { await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) @@ -465,7 +490,7 @@ describe('workspace context instruction discovery', () => { } }) - it('uses the configured instruction candidate order without hard-coding AGENTS.md priority', async () => { + it('loads every configured instruction candidate in configured order without hard-coding AGENTS.md priority', async () => { const root = await tempRepo() const home = await tempRepo() try { @@ -480,7 +505,7 @@ describe('workspace context instruction discovery', () => { instructionFileCandidates: ['CLAUDE.local.md', 'AGENTS.md', 'CLAUDE.md'], }) - expect(files.map(file => file.displayPath)).toEqual(['CLAUDE.local.md']) + expect(files.map(file => file.displayPath)).toEqual(['CLAUDE.local.md', 'AGENTS.md', 'CLAUDE.md']) } finally { await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) @@ -510,6 +535,12 @@ describe('workspace context instruction discovery', () => { it('defaults dshHome and uses cwd itself as root when no project marker exists', async () => { const root = await tempRepo() + const emptyHome = await tempRepo() + // Isolate the default-home fallback: blank DSH_HOME is treated as unset, and + // HOME points at an empty dir so the default ~/.dsh holds no global scope. + // Symlinks are now followed, so a real ~/.dsh/AGENTS.md would otherwise leak in. + vi.stubEnv('DSH_HOME', '') + vi.stubEnv('HOME', emptyHome) try { const cwd = join(root, 'child') await mkdir(cwd, { recursive: true }) @@ -521,7 +552,9 @@ describe('workspace context instruction discovery', () => { expect(files.map(file => file.displayPath)).toEqual(['AGENTS.md']) expect(files.map(file => file.absolutePath)).toEqual([join(cwd, 'AGENTS.md')]) } finally { + vi.unstubAllEnvs() await rm(root, { recursive: true, force: true }) + await rm(emptyHome, { recursive: true, force: true }) } }) @@ -550,7 +583,6 @@ describe('workspace context instruction discovery', () => { vi.resetModules() vi.doMock('node:os', () => ({ homedir: () => home })) - vi.stubEnv('DSH_HOME', undefined) const isolated = await import('@deepseek-ai/dsh-workspace-context') const files = await isolated.discoverBaselineInstructionFiles({ cwd: root }) @@ -558,7 +590,6 @@ describe('workspace context instruction discovery', () => { } finally { vi.doUnmock('node:os') vi.resetModules() - vi.unstubAllEnvs() await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) } @@ -825,11 +856,11 @@ describe('workspace context request injection', () => { try { await ctx.plugin(workspaceContext, { maxBytes: 65536 }) - const decision = await postExecute(ctx, stubToolExecution({ + const decision = await ctx.waterfall('tools/post-execute', stubToolExecution({ signal: testToolSignal, callId: CallId('no-fs-post-execute'), name: 'read', - arguments: { file_path: 'pkg/file.txt' }, + arguments: { file_path: join('pkg', 'file.txt') }, agent: stubAgent('/virtual/repo'), }), { isError: false, @@ -865,7 +896,7 @@ describe('workspace context request injection', () => { signal: testToolSignal, callId: CallId('read-blocked-post-execute'), name: 'read', - arguments: { file_path: 'pkg/file.txt' }, + arguments: { file_path: join('pkg', 'file.txt') }, agent, }) const result = { @@ -874,7 +905,7 @@ describe('workspace context request injection', () => { } // A later PostToolUse-style policy blocks this otherwise-successful read. - const blocked = await postExecute(ctx, exec, result, async () => ({ + const blocked = await ctx.waterfall('tools/post-execute', exec, result, async () => ({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'blocked by policy' }], })) @@ -888,7 +919,7 @@ describe('workspace context request injection', () => { // The same read, when the downstream accepts, DOES surface the nested // instructions — proving the block branch above is what suppressed them, // and that the block did not consume the pending nested change. - const accepted = await postExecute(ctx, exec, result, async () => ({ + const accepted = await ctx.waterfall('tools/post-execute', exec, result, async () => ({ kind: 'accept' as const, })) expect(accepted.kind).toBe('accept') @@ -1013,7 +1044,7 @@ describe('workspace context request injection', () => { }) expect(workspaceContextOf(result)?.meta).toMatchObject({ - changes: [{ action: 'replace', scope: '.', path: 'AGENTS.md' }], + changes: [{ action: 'replace', scope: sk('.', 'AGENTS.md'), path: 'AGENTS.md' }], }) expect(blocksText(workspaceContextOf(result)?.content)).toContain('Updated instructions from: AGENTS.md') expect(blocksText(workspaceContextOf(result)?.content)).toContain('new root rule with more detail') @@ -1042,7 +1073,7 @@ describe('workspace context request injection', () => { }) expect(workspaceContextOf(result)?.meta).toMatchObject({ - changes: [{ action: 'remove', scope: '.', path: 'AGENTS.md' }], + changes: [{ action: 'remove', scope: sk('.', 'AGENTS.md'), path: 'AGENTS.md' }], }) expect(blocksText(workspaceContextOf(result)?.content)).toContain('Instructions removed: AGENTS.md') } finally { @@ -1074,6 +1105,32 @@ describe('workspace context request injection', () => { } }) + it('deduplicates trimmed-identical sibling candidates in one directory and renders the earliest original bytes', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'AGENTS.md'), 'shared repo rule') + await write(join(root, 'CLAUDE.md'), ' shared repo rule\n\n') + await write(join(root, 'file.txt'), 'hello') + const ctx = new Context() + await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) + const agent = stubAgent(root) + + await composeBaselinePrefix(ctx, agent) + + const text = derivedText(agent) + expect(text.match(/shared repo rule/g)).toHaveLength(1) + expect(text).toContain('Instructions from: AGENTS.md') + expect(text).not.toContain('Instructions from: CLAUDE.md') + // The kept candidate's original bytes are rendered, not the whitespace-padded duplicate. + expect(text).not.toContain(' shared repo rule') + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + it('does not expose state markers when a tiny budget reduces the baseline contribution', async () => { const root = await tempRepo() const home = await tempRepo() @@ -1222,9 +1279,8 @@ describe('workspace context request injection', () => { const controller = new AbortController() const reason = new Error('cancel prefix') const empty: Message[] = [] - const agent = stubAgent(root) - const pending = agentEvents(ctx, agent).waterfall( - 'agent/session-prefix', empty, controller.signal, + const pending = ctx.waterfall( + 'agent/session-prefix', stubAgent(root), empty, controller.signal, () => Promise.resolve(empty), ) @@ -1291,30 +1347,6 @@ describe('workspace context request injection', () => { } }) - it('skips provider-visible instruction candidates when ctx.fs stat disagrees after no-follow preflight', async () => { - const root = await tempRepo() - const home = await tempRepo() - try { - await mkdir(join(root, '.git'), { recursive: true }) - await write(join(root, 'AGENTS.md'), 'node fs rule') - const ctx = new Context() - await ctx.plugin(RecordingFileSystem) - const fs = ctx.fs as RecordingFileSystem - fs.entries.set(join(root, '.git'), { type: 'directory' }) - fs.entries.set(join(root, 'AGENTS.md'), { type: 'directory' }) - fs.lstatTypes.set(join(root, 'AGENTS.md'), 'file') - await ctx.plugin(workspaceContext, { dshHome: home, maxBytes: 65536 }) - const agent = stubAgent(root) - - await composeBaselinePrefix(ctx, agent) - - expectNoDerivedMessages(agent) - } finally { - await rm(root, { recursive: true, force: true }) - await rm(home, { recursive: true, force: true }) - } - }) - it('loads instruction files when ctx.fs omits the metadata size', async () => { const root = await tempRepo() const home = await tempRepo() @@ -1361,7 +1393,7 @@ describe('workspace context request injection', () => { } }) - it('does not fall through to a lower-priority candidate when the winning provider file becomes unavailable', async () => { + it('skips a candidate whose provider probe fails while still loading its available sibling', async () => { const root = await tempRepo() const home = await tempRepo() try { @@ -1369,16 +1401,16 @@ describe('workspace context request injection', () => { await ctx.plugin(RecordingFileSystem) const fs = ctx.fs as RecordingFileSystem fs.entries.set(join(root, '.git'), { type: 'directory' }) - fs.lstatTypes.set(join(root, 'AGENTS.md'), 'file') fs.throwOnStat.add(join(root, 'AGENTS.md')) - fs.entries.set(join(root, 'CLAUDE.md'), { type: 'file', content: 'must not bypass AGENTS failure' }) + fs.entries.set(join(root, 'CLAUDE.md'), { type: 'file', content: 'claude sibling rule' }) await ctx.plugin(workspaceContext, { dshHome: home, maxBytes: 65536 }) const agent = stubAgent(root) await composeBaselinePrefix(ctx, agent) - expectNoDerivedMessages(agent) - expect(fs.readTargets).not.toContain(join(root, 'CLAUDE.md')) + expect(derivedText(agent)).toContain('claude sibling rule') + expect(fs.readTargets).toContain(join(root, 'CLAUDE.md')) + expect(fs.readTargets).not.toContain(join(root, 'AGENTS.md')) } finally { await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) @@ -1459,6 +1491,27 @@ describe('workspace context request injection', () => { } }) + it('renders a default local overlay alongside the base file in the baseline prefix', async () => { + const root = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'AGENTS.md'), 'base rule') + await write(join(root, 'AGENTS.local.md'), 'local rule') + const ctx = new Context() + await ctx.plugin(LocalFileSystem, { cwd: '/' }) + await ctx.plugin(workspaceContext, { maxBytes: 65536 }) + const agent = stubAgent(root) + + await composeBaselinePrefix(ctx, agent) + + expect(derivedText(agent)).toContain('Instructions from: AGENTS.md\n\nbase rule') + expect(derivedText(agent)).toContain('Instructions from: AGENTS.local.md\n\nlocal rule') + await ctx.fiber.dispose() + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + it('cleans up its agent/session-prefix listener when the plugin fiber is disposed', async () => { const root = await tempRepo() const home = await tempRepo() @@ -1562,9 +1615,9 @@ describe('workspace context request injection', () => { const actual = await importOriginal<typeof import('node:fs/promises')>() return { ...actual, - lstat: async (path: string) => { + stat: async (path: string) => { observedStats.set(path, (observedStats.get(path) ?? 0) + 1) - return actual.lstat(path) + return actual.stat(path) }, } }) @@ -1582,22 +1635,22 @@ describe('workspace context request injection', () => { } }) - it('does not bypass an unavailable host AGENTS.md with a lower-priority candidate', async () => { + it('skips an unavailable host candidate but still loads its available sibling', async () => { const root = await tempRepo() const home = await tempRepo() try { await mkdir(join(root, '.git'), { recursive: true }) - await write(join(root, 'CLAUDE.md'), 'must not bypass unavailable AGENTS') + await write(join(root, 'CLAUDE.md'), 'claude host sibling rule') vi.resetModules() vi.doMock('node:fs/promises', async (importOriginal) => { const actual = await importOriginal<typeof import('node:fs/promises')>() return { ...actual, - lstat: async (path: string) => { + stat: async (path: string) => { if (path === join(root, 'AGENTS.md')) { throw Object.assign(new Error('permission denied'), { code: 'EACCES' }) } - return actual.lstat(path) + return actual.stat(path) }, } }) @@ -1605,7 +1658,7 @@ describe('workspace context request injection', () => { const rendered = await isolated.loadBaselineInstructions({ cwd: root, dshHome: home, maxBytes: 65536 }) - expect(rendered).toBeUndefined() + expect(rendered?.text).toContain('claude host sibling rule') } finally { vi.doUnmock('node:fs/promises') vi.resetModules() @@ -1632,7 +1685,7 @@ describe('dynamic nested workspace context injection', () => { { type: 'block-end', index: 1, block: { type: 'tool-call', id: CallId('abort-after-read'), name: 'abort_step', arguments: '{}' } }, { type: 'finish', reason: { kind: 'tool-calls' } }, ] satisfies StreamChunk[], - toolCallResponse('read-after-abort', 'read', { file_path: 'pkg/deep/file.txt' }), + toolCallResponse('read-after-abort', 'read', { file_path: join('pkg', 'deep', 'file.txt') }), textResponse('done'), ]) await ctx.plugin(LlmService) @@ -1684,7 +1737,7 @@ describe('dynamic nested workspace context injection', () => { content: 'root rule', }]) - const change = state.changes.get('.') + const change = state.changes.get(sk('.', 'AGENTS.md')) expect(change).toMatchObject({ action: 'set', path: 'AGENTS.md', @@ -1709,12 +1762,12 @@ describe('dynamic nested workspace context injection', () => { const exec = stubToolExecution({ callId: CallId('cancelled-dynamic-read'), name: 'read', - arguments: { file_path: 'pkg/file.txt' }, + arguments: { file_path: join('pkg', 'file.txt') }, agent: stubAgent(root), signal: controller.signal, }) - const pending = postExecute(ctx, exec, { + const pending = ctx.waterfall('tools/post-execute', exec, { content: [{ type: 'text', text: 'ok' }], isError: false, }, () => Promise.resolve({ kind: 'accept' as const })) @@ -1744,7 +1797,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-nested'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) @@ -1755,7 +1808,7 @@ describe('dynamic nested workspace context injection', () => { version: 1, changes: [{ action: 'set', - scope: 'pkg', + scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md'), }], }) @@ -1785,7 +1838,7 @@ describe('dynamic nested workspace context injection', () => { } }) - it('uses configured instruction candidates for nested discovery', async () => { + it('loads every configured instruction candidate present in a nested scope', async () => { const root = await tempRepo() const home = await tempRepo() try { @@ -1804,14 +1857,87 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-configured-nested-candidate'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent: stubAgent(root), }) const text = blocksText(workspaceContextOf(result)?.content) expect(text).toContain(`Additional instructions from: ${join('pkg', 'CLAUDE.local.md')}`) expect(text).toContain('local package rule') - expect(text).not.toContain('native package rule') + expect(text).toContain(`Additional instructions from: ${join('pkg', 'AGENTS.md')}`) + expect(text).toContain('native package rule') + expect(text.indexOf(join('pkg', 'CLAUDE.local.md'))).toBeLessThan(text.indexOf(join('pkg', 'AGENTS.md'))) + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + + it('attaches a nested base file and its local overlay together by default', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'AGENTS.md'), 'baseline root rule') + await write(join(root, 'pkg/AGENTS.md'), 'nested base rule') + await write(join(root, 'pkg/AGENTS.local.md'), 'nested local rule') + await write(join(root, 'pkg/deep/file.txt'), 'hello') + const ctx = new Context() + await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) + + const result = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-nested-overlay'), + name: 'read', + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, + agent: stubAgent(root), + }) + + const meta = workspaceContextOf(result)?.meta + const changes = typeof meta === 'object' && meta !== null && !Array.isArray(meta) && Array.isArray(meta.changes) + ? meta.changes + : [] + expect(changes).toEqual(expect.arrayContaining([ + expect.objectContaining({ action: 'set', path: join('pkg', 'AGENTS.md') }), + expect.objectContaining({ action: 'set', path: join('pkg', 'AGENTS.local.md') }), + ])) + const text = blocksText(workspaceContextOf(result)?.content) + expect(text).toContain(`Additional instructions from: ${join('pkg', 'AGENTS.md')}`) + expect(text).toContain('nested base rule') + expect(text).toContain(`Additional instructions from: ${join('pkg', 'AGENTS.local.md')}`) + expect(text).toContain('nested local rule') + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + + it('does not attach a nested local overlay when the overlay is disabled', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'pkg/AGENTS.md'), 'nested base rule') + await write(join(root, 'pkg/AGENTS.local.md'), 'nested local rule') + await write(join(root, 'pkg/deep/file.txt'), 'hello') + const ctx = new Context() + await mountFileToolsAndWorkspaceContext(ctx, { + dshHome: home, + maxBytes: 65536, + localInstructionFileCandidates: [], + }) + + const result = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-nested-overlay-disabled'), + name: 'read', + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, + agent: stubAgent(root), + }) + + const text = blocksText(workspaceContextOf(result)?.content) + expect(text).toContain(`Additional instructions from: ${join('pkg', 'AGENTS.md')}`) + expect(text).not.toContain(join('pkg', 'AGENTS.local.md')) } finally { await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) @@ -1833,14 +1959,14 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-nested-1'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) const second = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('read-nested-2'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) @@ -1871,12 +1997,12 @@ describe('dynamic nested workspace context injection', () => { const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-before-version-fast-path'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-before-version-fast-path'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) const second = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-with-version-fast-path'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-with-version-fast-path'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) expect(first.additionalContexts).toBeDefined() @@ -1908,17 +2034,17 @@ describe('dynamic nested workspace context injection', () => { const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-before-same-digest-version-change'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-before-same-digest-version-change'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) fs.entries.set(instructionPath, { type: 'file', content: 'same package rule', version: FsVersion('revision-2') }) const afterVersionChange = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-after-same-digest-version-change'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-after-same-digest-version-change'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) const afterRefresh = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-after-version-cache-refresh'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-after-version-cache-refresh'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) expect(afterVersionChange.additionalContexts).toBeUndefined() @@ -1949,11 +2075,11 @@ describe('dynamic nested workspace context injection', () => { const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-from-first-session'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent: stubAgent(root), + callId: CallId('read-from-first-session'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent: stubAgent(root), }) const second = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-from-second-session'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent: stubAgent(root), + callId: CallId('read-from-second-session'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent: stubAgent(root), }) expect(first.additionalContexts).toBeDefined() @@ -1979,18 +2105,18 @@ describe('dynamic nested workspace context injection', () => { const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-before-change'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-before-change'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) await write(join(root, 'pkg/AGENTS.md'), 'new package rule with more detail') const changed = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-after-change'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-after-change'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) expect(workspaceContextOf(changed)?.meta).toMatchObject({ kind: 'workspace-instructions', - changes: [{ action: 'replace', scope: 'pkg', path: join('pkg', 'AGENTS.md') }], + changes: [{ action: 'replace', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }], }) expect(blocksText(workspaceContextOf(changed)?.content)).toBe([ '<system-reminder>', @@ -2007,13 +2133,13 @@ describe('dynamic nested workspace context injection', () => { } }) - it('replaces an AGENTS candidate with the configured fallback in the same scope', async () => { + it('reconciles distinct sibling candidates as independent scopes', async () => { const root = await tempRepo() const home = await tempRepo() try { await mkdir(join(root, '.git'), { recursive: true }) await write(join(root, 'pkg/AGENTS.md'), 'native package rule') - await write(join(root, 'pkg/CLAUDE.md'), 'fallback package rule') + await write(join(root, 'pkg/CLAUDE.md'), 'sibling package rule') await write(join(root, 'pkg/file.txt'), 'hello') const ctx = new Context() await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) @@ -2021,29 +2147,170 @@ describe('dynamic nested workspace context injection', () => { const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-before-fallback'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-both-siblings'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) + const firstText = blocksText(workspaceContextOf(first)?.content) + expect(firstText).toContain('native package rule') + expect(firstText).toContain('sibling package rule') appendAdditionalContexts(agent, first) await rm(join(root, 'pkg/AGENTS.md')) - const changed = await ctx.tools.execute({ + const removed = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-after-fallback'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, - }) - appendAdditionalContexts(agent, changed) - const unchanged = await ctx.tools.execute({ - signal: testToolSignal, - callId: CallId('read-after-logged-fallback'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-after-one-sibling-removed'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) - expect(workspaceContextOf(changed)?.meta).toMatchObject({ - changes: [{ - action: 'replace', scope: 'pkg', path: join('pkg', 'CLAUDE.md'), previousPath: join('pkg', 'AGENTS.md'), - }], + // Removing one candidate only removes its own scope; the sibling scope is untouched. + expect(workspaceContextOf(removed)?.meta).toMatchObject({ + changes: [{ action: 'remove', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }], }) - expect(blocksText(workspaceContextOf(changed)?.content)).toContain(`Updated instructions from: ${join('pkg', 'CLAUDE.md')}`) - expect(blocksText(workspaceContextOf(changed)?.content)).toContain(`The instructions previously loaded from \`${join('pkg', 'AGENTS.md')}\` no longer apply. Use the following content for \`pkg\` instead.`) - expect(blocksText(workspaceContextOf(changed)?.content)).toContain('fallback package rule') - expect(unchanged.additionalContexts).toBeUndefined() + expect(blocksText(workspaceContextOf(removed)?.content)).toContain(`Instructions removed: ${join('pkg', 'AGENTS.md')}`) + expect(blocksText(workspaceContextOf(removed)?.content)).not.toContain('sibling package rule') + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + + it('drops a newly discovered sibling whose content duplicates an earlier candidate in the scope', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'pkg/AGENTS.md'), 'nested rule') + await write(join(root, 'pkg/CLAUDE.md'), 'nested rule') + await write(join(root, 'pkg/deep/file.txt'), 'hello') + const ctx = new Context() + await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) + const agent = stubAgent(root) + + const result = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-nested-dup-siblings'), name: 'read', arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, + }) + + expect(workspaceContextOf(result)?.meta).toMatchObject({ + changes: [{ action: 'set', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }], + }) + const text = blocksText(workspaceContextOf(result)?.content) + expect(text.match(/nested rule/g)).toHaveLength(1) + expect(text).toContain(`Additional instructions from: ${join('pkg', 'AGENTS.md')}`) + expect(text).not.toContain(join('pkg', 'CLAUDE.md')) + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + + it('keeps deduplicating against a loaded candidate whose probe transiently fails', async () => { + const root = await tempRepo() + const home = await tempRepo() + const ctx = new Context() + try { + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(RecordingFileSystem) + const fs = ctx.fs as RecordingFileSystem + fs.entries.set(join(root, '.git'), { type: 'directory' }) + fs.entries.set(join(root, 'pkg/AGENTS.md'), { type: 'file', content: 'nested rule' }) + fs.entries.set(join(root, 'pkg/file.txt'), { type: 'file', content: 'hello' }) + await ctx.plugin(ToolFs) + await ctx.plugin(workspaceContext, { dshHome: home, maxBytes: 65536 }) + const agent = stubAgent(root) + + const first = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-before-transient-probe-failure'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, + }) + appendAdditionalContexts(agent, first) + expect(first.additionalContexts).toBeDefined() + + // The loaded candidate's probe fails while an identical sibling appears: + // the cached candidate stays effective (last good state), so the sibling + // must still deduplicate against it rather than land as a duplicate set. + fs.throwOnStat.add(join(root, 'pkg/AGENTS.md')) + fs.entries.set(join(root, 'pkg/CLAUDE.md'), { type: 'file', content: 'nested rule' }) + const duringFailure = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-during-transient-probe-failure'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, + }) + + expect(duringFailure.additionalContexts).toBeUndefined() + } finally { + await ctx.fiber.dispose() + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + + it('removes a previously rendered sibling once its content becomes a duplicate of an earlier candidate', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'pkg/AGENTS.md'), 'canonical nested rule') + await write(join(root, 'pkg/CLAUDE.md'), 'divergent nested rule') + await write(join(root, 'pkg/file.txt'), 'hello') + const ctx = new Context() + await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) + const agent = stubAgent(root) + + const first = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-before-dup-convergence'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, + }) + const firstText = blocksText(workspaceContextOf(first)?.content) + expect(firstText).toContain('canonical nested rule') + expect(firstText).toContain('divergent nested rule') + appendAdditionalContexts(agent, first) + await write(join(root, 'pkg/CLAUDE.md'), 'canonical nested rule') + const converged = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-after-dup-convergence'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, + }) + + expect(workspaceContextOf(converged)?.meta).toMatchObject({ + changes: [{ action: 'remove', scope: sk('pkg', 'CLAUDE.md'), path: join('pkg', 'CLAUDE.md') }], + }) + expect(blocksText(workspaceContextOf(converged)?.content)).toContain(`Instructions removed: ${join('pkg', 'CLAUDE.md')}`) + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + + it('removes an unchanged sibling when an earlier candidate changes to match its content', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'pkg/AGENTS.md'), 'primary nested rule') + await write(join(root, 'pkg/CLAUDE.md'), 'secondary nested rule') + await write(join(root, 'pkg/file.txt'), 'hello') + const ctx = new Context() + await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) + const agent = stubAgent(root) + + const first = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-before-earlier-converges'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, + }) + appendAdditionalContexts(agent, first) + // Only the earlier candidate changes; the sibling stays byte-identical but now duplicates it. + await write(join(root, 'pkg/AGENTS.md'), 'secondary nested rule') + const converged = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-after-earlier-converges'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, + }) + + expect(workspaceContextOf(converged)?.meta).toMatchObject({ + changes: [ + { action: 'replace', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }, + { action: 'remove', scope: sk('pkg', 'CLAUDE.md'), path: join('pkg', 'CLAUDE.md') }, + ], + }) + const text = blocksText(workspaceContextOf(converged)?.content) + expect(text).toContain(`Instructions removed: ${join('pkg', 'CLAUDE.md')}`) + expect(text).toContain(`Updated instructions from: ${join('pkg', 'AGENTS.md')}`) } finally { await rm(root, { recursive: true, force: true }) await rm(home, { recursive: true, force: true }) @@ -2063,19 +2330,19 @@ describe('dynamic nested workspace context injection', () => { const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-before-remove'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-before-remove'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) await rm(join(root, 'pkg/AGENTS.md')) const removed = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-after-remove'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-after-remove'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) expect(workspaceContextOf(removed)?.meta).toEqual({ kind: 'workspace-instructions', version: 1, - changes: [{ action: 'remove', scope: 'pkg', path: join('pkg', 'AGENTS.md') }], + changes: [{ action: 'remove', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }], }) expect(blocksText(workspaceContextOf(removed)?.content)).toBe([ '<system-reminder>', @@ -2090,6 +2357,45 @@ describe('dynamic nested workspace context injection', () => { } }) + it('removes a previously loaded instruction file once it resolves to a directory through a symlink', async () => { + const root = await tempRepo() + const home = await tempRepo() + try { + await mkdir(join(root, '.git'), { recursive: true }) + await write(join(root, 'pkg/AGENTS.md'), 'package rule') + await write(join(root, 'pkg/file.txt'), 'hello') + const ctx = new Context() + await mountFileToolsAndWorkspaceContext(ctx, { dshHome: home, maxBytes: 65536 }) + const agent = stubAgent(root) + + const first = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-before-symlink-dir'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, + }) + appendAdditionalContexts(agent, first) + expect(blocksText(workspaceContextOf(first)?.content)).toContain('package rule') + + // The candidate now resolves through a symlink to a directory. A non-file + // target is a confirmed absence (not unavailable), so the loaded scope is + // removed; an unavailable classification would emit no change at all. + await rm(join(root, 'pkg/AGENTS.md')) + await mkdir(join(root, 'pkg/elsewhere'), { recursive: true }) + await symlink(join(root, 'pkg/elsewhere'), join(root, 'pkg/AGENTS.md')) + const removed = await ctx.tools.execute({ + signal: testToolSignal, + callId: CallId('read-after-symlink-dir'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, + }) + + expect(workspaceContextOf(removed)?.meta).toMatchObject({ + changes: [{ action: 'remove', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }], + }) + expect(blocksText(workspaceContextOf(removed)?.content)).toContain(`Instructions removed: ${join('pkg', 'AGENTS.md')}`) + } finally { + await rm(root, { recursive: true, force: true }) + await rm(home, { recursive: true, force: true }) + } + }) + it('loads a candidate again after a logged removal tombstone', async () => { const root = await tempRepo() const home = await tempRepo() @@ -2103,24 +2409,24 @@ describe('dynamic nested workspace context injection', () => { const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-before-tombstone'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-before-tombstone'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) await rm(join(root, 'pkg/AGENTS.md')) const removed = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-to-create-tombstone'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-to-create-tombstone'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) appendAdditionalContexts(agent, removed) await write(join(root, 'pkg/AGENTS.md'), 'restored package rule') const restored = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-after-tombstone'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-after-tombstone'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) expect(workspaceContextOf(restored)?.meta).toMatchObject({ - changes: [{ action: 'set', scope: 'pkg', path: join('pkg', 'AGENTS.md') }], + changes: [{ action: 'set', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }], }) expect(blocksText(workspaceContextOf(restored)?.content)).toContain(`Additional instructions from: ${join('pkg', 'AGENTS.md')}`) expect(blocksText(workspaceContextOf(restored)?.content)).toContain('restored package rule') @@ -2148,13 +2454,13 @@ describe('dynamic nested workspace context injection', () => { const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-before-provider-failure'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-before-provider-failure'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) fs.throwOnStat.add(join(root, 'pkg/AGENTS.md')) const duringFailure = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-during-provider-failure'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('read-during-provider-failure'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }) expect(first.additionalContexts).toBeDefined() @@ -2180,7 +2486,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-before-resume'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) @@ -2193,7 +2499,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-after-resume'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent: resumed, }) @@ -2217,7 +2523,7 @@ describe('dynamic nested workspace context injection', () => { const original = stubAgent(root) const first = await ctx.tools.execute({ signal: testToolSignal, - callId: CallId('read-before-offline-change'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent: original, + callId: CallId('read-before-offline-change'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent: original, }) appendAdditionalContexts(original, first) await write(join(root, 'pkg/AGENTS.md'), 'new nested rule after resume') @@ -2227,7 +2533,7 @@ describe('dynamic nested workspace context injection', () => { const update = resumed.session.events.findLast(event => event.type === 'context/message') expect(update?.type === 'context/message' && update.data.meta).toMatchObject({ - changes: [{ action: 'replace', scope: 'pkg', path: join('pkg', 'AGENTS.md') }], + changes: [{ action: 'replace', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }], }) expect(update?.type === 'context/message' && blocksText(update.data.content)).toContain('new nested rule after resume') } finally { @@ -2250,7 +2556,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-before-compact'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) const contextSeq = appendAdditionalContexts(agent, first)! @@ -2258,7 +2564,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-while-visible'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) @@ -2274,7 +2580,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-after-compact'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) @@ -2304,7 +2610,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-package'), name: 'read', - arguments: { file_path: 'pkg/file.txt' }, + arguments: { file_path: join('pkg', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) @@ -2313,7 +2619,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-subtree'), name: 'read', - arguments: { file_path: 'pkg/sub/file.txt' }, + arguments: { file_path: join('pkg', 'sub', 'file.txt') }, agent, }) @@ -2341,7 +2647,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-subtree-omitting-parent'), name: 'read', - arguments: { file_path: 'pkg/sub/file.txt' }, + arguments: { file_path: join('pkg', 'sub', 'file.txt') }, agent, }) appendAdditionalContexts(agent, first) @@ -2350,7 +2656,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-parent-after-omit'), name: 'read', - arguments: { file_path: 'pkg/other.txt' }, + arguments: { file_path: join('pkg', 'other.txt') }, agent, }) @@ -2386,10 +2692,9 @@ describe('dynamic nested workspace context injection', () => { version: 1, changes: [ null, - { action: 'unknown', scope: 'pkg', path: 'pkg/AGENTS.md' }, + { action: 'unknown', scope: 'pkg', path: join('pkg', 'AGENTS.md') }, { action: 'set', scope: 'pkg', path: 42 }, - { action: 'replace', scope: 'pkg', path: 'pkg/AGENTS.md', previousPath: 42 }, - { action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 42 }, + { action: 'set', scope: 'pkg', path: join('pkg', 'AGENTS.md'), digest: 42 }, ], }, }, { surfaceOp: 'append' }) @@ -2404,7 +2709,7 @@ describe('dynamic nested workspace context injection', () => { meta: { kind: 'workspace-instructions', version: 1, - changes: [{ action: 'set', scope: 'pkg', path: 'pkg/AGENTS.md', digest: 'spoof' }], + changes: [{ action: 'set', scope: 'pkg', path: join('pkg', 'AGENTS.md'), digest: 'spoof' }], }, }, { surfaceOp: 'append' }) @@ -2412,7 +2717,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-after-spoofed-state'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) @@ -2458,7 +2763,7 @@ describe('dynamic nested workspace context injection', () => { } }) - it('treats provider failures and type disagreement after lstat as unavailable, not removed', async () => { + it('treats a reconciliation provider failure as unavailable and a resolved non-file as absent', async () => { const root = await tempRepo() const home = await tempRepo() const ctx = new Context() @@ -2466,7 +2771,6 @@ describe('dynamic nested workspace context injection', () => { await ctx.plugin(RecordingFileSystem) const fs = ctx.fs as RecordingFileSystem fs.entries.set(join(root, '.git'), { type: 'directory' }) - fs.lstatTypes.set(join(root, 'pkg/AGENTS.md'), 'file') fs.throwOnStat.add(join(root, 'pkg/AGENTS.md')) await ctx.plugin(workspaceContext, { dshHome: home, maxBytes: 65536 }) const agent = stubAgent(root) @@ -2476,15 +2780,15 @@ describe('dynamic nested workspace context injection', () => { isError: false, } - const failedStat = await postExecute(ctx, stubToolExecution({ + const failedStat = await ctx.waterfall('tools/post-execute', stubToolExecution({ signal: testToolSignal, - callId: CallId('provider-stat-failure'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('provider-stat-failure'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }), result, async () => ({ kind: 'accept' as const })) fs.throwOnStat.clear() fs.entries.set(join(root, 'pkg/AGENTS.md'), { type: 'directory' }) - const mismatchedStat = await postExecute(ctx, stubToolExecution({ + const mismatchedStat = await ctx.waterfall('tools/post-execute', stubToolExecution({ signal: testToolSignal, - callId: CallId('provider-stat-mismatch'), name: 'read', arguments: { file_path: 'pkg/file.txt' }, agent, + callId: CallId('provider-stat-mismatch'), name: 'read', arguments: { file_path: join('pkg', 'file.txt') }, agent, }), result, async () => ({ kind: 'accept' as const })) expect(failedStat).toEqual({ kind: 'accept' }) @@ -2497,6 +2801,8 @@ describe('dynamic nested workspace context injection', () => { }) it('skips unreadable nested instruction files without attaching empty context', async () => { + // Cross-platform unreadable fixture: the provider read throws (chmod 0 + // cannot make a file unreadable to its owner on Windows). const root = await tempRepo() const home = await tempRepo() const ctx = new Context() @@ -2517,7 +2823,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-with-unreadable-nested-instruction'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent: stubAgent(root), }) @@ -2553,7 +2859,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-with-downstream'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent: stubAgent(root), }) @@ -2562,7 +2868,7 @@ describe('dynamic nested workspace context injection', () => { expect(workspaceContextOf(result)?.source).toEqual({ kind: 'plugin', plugin: 'workspace-context' }) expect(workspaceContextOf(result)?.meta).toMatchObject({ kind: 'workspace-instructions', - changes: [{ action: 'set', scope: 'pkg', path: join('pkg', 'AGENTS.md') }], + changes: [{ action: 'set', scope: sk('pkg', 'AGENTS.md'), path: join('pkg', 'AGENTS.md') }], }) expect(blocksText(workspaceContextOf(result)?.content)).toContain('nested package rule') expect(blocksText(workspaceContextOf(result)?.content)).not.toContain('downstream context') @@ -2598,7 +2904,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-blocked-downstream'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent: stubAgent(root), }) @@ -2639,7 +2945,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('outer-block-first'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) shouldBlock = false @@ -2647,7 +2953,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('outer-block-retry'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent, }) @@ -2680,12 +2986,13 @@ describe('dynamic nested workspace context injection', () => { parameters: {}, async execute(_args, exec) { const nested = await ctx.tools.execute({ + signal: testToolSignal, callId: CallId(`${exec.callId}:nested`), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, ...exec.agent === undefined ? {} : { agent: exec.agent }, parent: exec.token, - signal: exec.signal, + ...exec.signal === undefined ? {} : { signal: exec.signal }, }) for (const context of nested.additionalContexts ?? []) exec.deferContext(context) return nested.content @@ -2730,23 +3037,23 @@ describe('dynamic nested workspace context injection', () => { const parent = Symbol('parent') as ToolExecutionToken const plainResult = { callId: CallId('plain'), content: [], isError: false } - emitToolResult(ctx, stubToolExecution({ + ctx.emit('tools/result', stubToolExecution({ signal: testToolSignal, callId: CallId('agentless-child'), name: 'read', arguments: {}, parent, }), plainResult) - emitToolResult(ctx, stubToolExecution({ + ctx.emit('tools/result', stubToolExecution({ signal: testToolSignal, callId: CallId('contextless-child'), name: 'read', arguments: {}, agent, parent, }), { ...plainResult, additionalContexts: [{ content: [], source: { kind: 'plugin', plugin: 'workspace-context' } }] }) - emitToolResult(ctx, stubToolExecution({ + ctx.emit('tools/result', stubToolExecution({ signal: testToolSignal, callId: CallId('first-child'), name: 'read', arguments: {}, agent, parent, }), { ...plainResult, additionalContexts: [workspaceChangeContext('first', 'one')] }) - emitToolResult(ctx, stubToolExecution({ + ctx.emit('tools/result', stubToolExecution({ signal: testToolSignal, callId: CallId('second-child'), name: 'read', arguments: {}, agent, parent, }), { ...plainResult, additionalContexts: [workspaceChangeContext('second', 'two')] }) - emitToolResult(ctx, { + ctx.emit('tools/result', { ...stubToolExecution({ signal: testToolSignal, callId: CallId('agentless-parent'), name: 'composite', arguments: {} }), token: parent, }, plainResult) @@ -2773,8 +3080,8 @@ describe('dynamic nested workspace context injection', () => { isError: false, } const cases = [ - { name: 'read', arguments: { file_path: 'pkg/deep/file.txt' }, agent: undefined }, - { name: 'bash', arguments: { file_path: 'pkg/deep/file.txt' }, agent }, + { name: 'read', arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent: undefined }, + { name: 'bash', arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent }, { name: 'read', arguments: null, agent }, { name: 'read', arguments: {}, agent }, { name: 'read', arguments: { file_path: 1 }, agent }, @@ -2782,7 +3089,7 @@ describe('dynamic nested workspace context injection', () => { ] for (const item of cases) { - const decision = await postExecute(ctx, stubToolExecution({ + const decision = await ctx.waterfall('tools/post-execute', stubToolExecution({ signal: testToolSignal, callId: CallId(`manual-${item.name}-${cases.indexOf(item)}`), name: item.name, @@ -2811,7 +3118,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-with-disabled-budget'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent: stubAgent(root), }) @@ -2836,7 +3143,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-missing'), name: 'read', - arguments: { file_path: 'pkg/missing.txt' }, + arguments: { file_path: join('pkg', 'missing.txt') }, agent: stubAgent(root), }) @@ -2863,7 +3170,7 @@ describe('dynamic nested workspace context injection', () => { signal: testToolSignal, callId: CallId('read-after-dispose'), name: 'read', - arguments: { file_path: 'pkg/deep/file.txt' }, + arguments: { file_path: join('pkg', 'deep', 'file.txt') }, agent: stubAgent(root), }) @@ -2906,7 +3213,7 @@ describe('workspace context pending state', () => { const [change] = commitPendingInstructionContexts(agent, [workspaceChangeContext('pkg', 'one')], pending) expect(change).toBeDefined() versions.set(agent.session, new Map([['pkg', { - path: 'pkg/AGENTS.md', version: FsVersion('v1'), digest: 'one', + path: join('pkg', 'AGENTS.md'), version: FsVersion('v1'), digest: 'one', trimmedDigest: 'one', }]])) const unrelated = agent.session.append('context/message', { @@ -2943,7 +3250,7 @@ describe('workspace context pending state', () => { agent.session.append('step/start', { turn: 1, step: 1 }) commitPendingInstructionContexts(agent, [workspaceChangeContext('pkg', 'one')], pending) versions.set(agent.session, new Map([['pkg', { - path: 'pkg/AGENTS.md', version: FsVersion('v1'), digest: 'one', + path: join('pkg', 'AGENTS.md'), version: FsVersion('v1'), digest: 'one', trimmedDigest: 'one', }]])) const ended = agent.session.append('step/end', { turn: 1, step: 1 }) diff --git a/packages/examples/cli-demo/src/cli.ts b/packages/examples/cli-demo/src/cli.ts index 7a6dfee8eb..66ce345520 100644 --- a/packages/examples/cli-demo/src/cli.ts +++ b/packages/examples/cli-demo/src/cli.ts @@ -14,7 +14,7 @@ import { boot, loadEnv, resolveConfigPath } from '@deepseek-ai/dsh-app-boot' const CLI_NAME = 'dsh-cli-demo' const DEFAULT_CONFIG_PATH = './cordis.yml' const OUTPUT_FORMATS = ['text', 'json', 'stream-json'] as const -const USAGE = `Usage: ${CLI_NAME} [--config path] [--output-format text|json|stream-json] <task>\n` +const USAGE = `Usage: ${CLI_NAME} [--config path] [--output-format text|json|stream-json] (-p <task> | <task>)\n` /** Supported CLI output encodings. */ export type OutputFormat = typeof OUTPUT_FORMATS[number] @@ -73,6 +73,7 @@ interface ParsedArguments { readonly config?: string readonly 'output-format'?: string readonly help?: boolean + readonly prompt?: string } readonly positionals: string[] } @@ -129,6 +130,7 @@ export function parseCliArgs(args: readonly string[]): CliCommand { config: { type: 'string' }, 'output-format': { type: 'string' }, help: { type: 'boolean' }, + prompt: { type: 'string', short: 'p' }, }, allowPositionals: true, strict: true, @@ -138,12 +140,16 @@ export function parseCliArgs(args: readonly string[]): CliCommand { } if (parsed.values.help === true) return { kind: 'help' } - if (parsed.positionals.length !== 1) { - throw new CliArgumentError(`expected exactly one positional task, received ${parsed.positionals.length}`) + const prompt = parsed.values.prompt + if (prompt !== undefined && parsed.positionals.length > 0) { + throw new CliArgumentError('-p/--prompt and a positional task are mutually exclusive') } - // Cardinality was checked above, so index zero exists. + if (prompt === undefined && parsed.positionals.length !== 1) { + throw new CliArgumentError(`expected exactly one positional task or -p, received ${parsed.positionals.length} positional(s)`) + } + // Cardinality was checked above, so the fallback index zero exists. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const task = parsed.positionals[0]! + const task = prompt ?? parsed.positionals[0]! if (task.trim().length === 0) throw new CliArgumentError('task must not be blank') const requestedFormat = parsed.values['output-format'] ?? 'text' diff --git a/packages/examples/cli-demo/tests/built-bin.e2e.ts b/packages/examples/cli-demo/tests/built-bin.e2e.ts index 3dadd32215..b6227d9702 100644 --- a/packages/examples/cli-demo/tests/built-bin.e2e.ts +++ b/packages/examples/cli-demo/tests/built-bin.e2e.ts @@ -8,6 +8,15 @@ import { fileURLToPath } from 'node:url' import { zstdDecompress } from 'node:zlib' import { afterEach, describe, expect, it } from 'vitest' +/** + * Published-entry smoke: run `lib/bin.js` under plain Node in a symlinked external consumer. + * The consumer's mock model is an example-local TypeScript plugin (Node 22.19+ — the engines + * floor — strips types natively, so plain `node` loads it), its config carries a `disabled: + * true` unresolvable entry (the fail-loud entry-load guard must not mistake an intentionally + * fiber-less entry for a failed import), and the optional spill pair loads from the consumer + * install — so every passing boot proves all three alongside the CLI's own output contract. + */ + const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url)) const cliBin = join(repoRoot, 'packages/examples/cli-demo/lib/bin.js') const decompress = promisify(zstdDecompress) @@ -17,6 +26,7 @@ const dshPackages = [ 'bash/bash-local', 'bash/tool-bash', 'support/invariants', 'ui/app-boot', 'session-persistence/session-persistence', 'session-persistence/session-persistence-jsonl', 'context/workspace-context', + 'spill/spill', 'spill/spill-local', 'spill/spill-policy', 'util/retention', ] const vendorPackages = ['cordis', 'loader', 'include', 'timer', 'schemastery', 'cosmokit'] @@ -35,15 +45,18 @@ async function makeConsumer(): Promise<string> { const nodeModules = join(dir, 'node_modules') for (const rel of dshPackages) await linkPackage(join(repoRoot, 'packages', rel), nodeModules) for (const rel of vendorPackages) await linkPackage(join(repoRoot, 'vendor', rel), nodeModules) - await writeFile(join(dir, 'mock-llm.mjs'), [ - "import { LlmAdapter } from '@deepseek-ai/dsh-llm'", + await writeFile(join(dir, 'mock-llm.ts'), [ + // Real type annotations: this file exists to prove plain Node's type + // stripping loads an example-local TS plugin from a built consumer. + "import { LlmAdapter, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm'", + "import type { Context } from 'cordis'", 'class Mock extends LlmAdapter {', - ' async * stream(options) {', - " const text = options.messages.flatMap(message => message.content).filter(block => block.type === 'text').at(-1)?.text ?? ''", + ' async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {', + " const text: string = options.messages.flatMap(message => message.content).filter(block => block.type === 'text').at(-1)?.text ?? ''", " yield { type: 'block-start', index: 0, blockType: 'text' }", " if (text === 'hang') {", " yield { type: 'text-delta', index: 0, text: 'partial' }", - ' await new Promise((resolve, reject) => {', + ' await new Promise<never>((resolve, reject) => {', " const timer = setTimeout(() => reject(new Error('hang timeout')), 30000)", " const onAbort = () => { clearTimeout(timer); reject(new Error('aborted')) }", ' if (options.signal.aborted) onAbort()', @@ -60,12 +73,12 @@ async function makeConsumer(): Promise<string> { '}', "export const name = 'built-cli-mock'", "export const inject = ['llm']", - "export function apply(ctx) { ctx.llm.registerAdapter(['built-cli-mock'], new Mock()) }", + "export function apply(ctx: Context) { ctx.llm.registerAdapter(['built-cli-mock'], new Mock()) }", '', ].join('\n')) await writeFile(join(dir, 'cordis.yml'), [ '- id: mock-llm', - " name: './mock-llm.mjs'", + " name: './mock-llm.ts'", '- id: bash', " name: '@deepseek-ai/dsh-bash-local'", '- id: cli-agent', @@ -76,6 +89,18 @@ async function makeConsumer(): Promise<string> { " persona: 'built CLI test'", " persistenceRoot: './.sessions'", ' workspaceContext: false', + '- id: spill-local', + " name: '@deepseek-ai/dsh-spill-local'", + '- id: spill-policy', + " name: '@deepseek-ai/dsh-spill-policy'", + ' config:', + ' maxInlineBytes: 50000', + // A `disabled: true` entry settles without a fiber by design; the fail-loud + // entry-load guard must not mistake it for a failed import. The nonexistent + // path makes that distinction observable while a clean run proves boot continued. + '- id: off', + " name: './does-not-exist.ts'", + ' disabled: true', '', ].join('\n')) return dir diff --git a/packages/examples/cli-demo/tests/cli.spec.ts b/packages/examples/cli-demo/tests/cli.spec.ts index f20697b827..e477924f3f 100644 --- a/packages/examples/cli-demo/tests/cli.spec.ts +++ b/packages/examples/cli-demo/tests/cli.spec.ts @@ -162,15 +162,19 @@ describe('parseCliArgs', () => { kind: 'run', configPath: 'custom.yml', outputFormat: 'stream-json', task: 'do it', }) expect(parseCliArgs(['--', '-task'])).toMatchObject({ task: '-task' }) + expect(parseCliArgs(['-p', 'flag task'])).toMatchObject({ task: 'flag task' }) + expect(parseCliArgs(['--prompt', 'long-flag task'])).toMatchObject({ task: 'long-flag task' }) expect(parseCliArgs(['--help', 'ignored'])).toEqual({ kind: 'help' }) }) it('rejects missing, blank, extra, invalid-format, and unsupported flags', () => { expect(() => parseCliArgs([])).toThrow('received 0') expect(() => parseCliArgs([' '])).toThrow('must not be blank') + expect(() => parseCliArgs(['-p', ' '])).toThrow('must not be blank') expect(() => parseCliArgs(['one', 'two'])).toThrow('received 2') + expect(() => parseCliArgs(['-p', 'task', 'positional'])).toThrow('mutually exclusive') expect(() => parseCliArgs(['--output-format', 'xml', 'task'])).toThrow('unsupported output format') - expect(() => parseCliArgs(['-p', 'task'])).toThrow('Unknown option') + expect(() => parseCliArgs(['-x', 'task'])).toThrow('Unknown option') }) }) diff --git a/packages/examples/tui-demo/src/bin.ts b/packages/examples/tui-demo/src/bin.ts index 237e4391b5..5073e203df 100644 --- a/packages/examples/tui-demo/src/bin.ts +++ b/packages/examples/tui-demo/src/bin.ts @@ -11,8 +11,16 @@ import { boot, installFailLoud, loadEnv, resolveConfigPath } from '@deepseek-ai/ const NAME = 'dsh-tui-demo' /* v8 ignore start -- thin self-executing composition over the unit-tested - dsh-app-boot helpers; exercised end-to-end by the keyless Loader-path and - built-bin smokes */ + dsh-app-boot helpers; exercised end-to-end by the tui-agent PTY smoke and + the built-bin fail-loud smoke */ +// Refuse pipes BEFORE booting: a compose-time throw inside the Loader tree is +// logged per-entry rather than rethrown, so a piped launch would otherwise +// settle into an idle UI-less process instead of exiting nonzero. +if (!process.stdin.isTTY || !process.stdout.isTTY) { + process.stderr.write(`${NAME}: the TUI requires stdin and stdout to be interactive TTYs; ` + + 'use the one-shot dsh-cli-demo bin for pipes and automation\n') + process.exit(1) +} installFailLoud(NAME) loadEnv(NAME) await boot(NAME, resolveConfigPath(process.argv[2] ?? './cordis.yml', undefined)) diff --git a/packages/examples/tui-demo/src/index.ts b/packages/examples/tui-demo/src/index.ts index 53d6d304a7..d602a233e3 100644 --- a/packages/examples/tui-demo/src/index.ts +++ b/packages/examples/tui-demo/src/index.ts @@ -27,7 +27,6 @@ import * as uiTui from '@deepseek-ai/dsh-tui' export const name = 'tui-demo' const DEFAULT_PERSISTENCE_ROOT = './.sessions' -const DEFAULT_WELCOME = 'ready.' /** App config routed to the spine, TUI, configured agent, and JSONL backend. */ export interface Config { @@ -51,8 +50,15 @@ export interface Config { persistenceRoot?: string /** JSONL artifact encoding; defaults to checksummed Zstandard frames. */ persistenceCompression?: JsonlCompression - /** TUI subtitle rendered on start. Defaults to `ready.`. */ + /** TUI transcript's optional first line; absent renders nothing on start. */ welcome?: string + /** + * Shell command template the TUI prints on exit and lists under `/resume`, + * with `{session}` replaced by the live session id (forwarded to the front + * door). Set it to a command that resumes via this app's env var, e.g. + * `RESUME_SESSION_ID={session} dsh`. + */ + resumeCommand?: string /** Full-screen TUI presentation settings. */ ui?: uiTui.TuiConfig /** Skill registry, local-provider, and model-facing consumer config. */ @@ -84,7 +90,8 @@ export const Config: z<Config> = z.object({ sessionTitle: agentCore.SessionTitleConfigSchema, persistenceRoot: z.string().default(DEFAULT_PERSISTENCE_ROOT), persistenceCompression: JsonlCompressionSchema, - welcome: z.string().default(DEFAULT_WELCOME), + welcome: z.string(), + resumeCommand: z.string(), ui: uiTui.TuiConfigSchema, skills: agentCore.SkillConfigSchema, toolBash: agentCore.ToolBashConfigSchema, @@ -115,7 +122,8 @@ export function composeTuiApp(ctx: Context, config: Config): void { ctx.plugin(UserInteractionService) ctx.plugin(uiTui, { ...config.ui, - welcome: config.welcome ?? DEFAULT_WELCOME, + ...config.welcome === undefined ? {} : { welcome: config.welcome }, + ...config.resumeCommand === undefined ? {} : { resumeCommand: config.resumeCommand }, sessionId, }) ctx.plugin(agentCore, { diff --git a/packages/examples/tui-demo/tests/built-bin.e2e.ts b/packages/examples/tui-demo/tests/built-bin.e2e.ts new file mode 100644 index 0000000000..904c75784a --- /dev/null +++ b/packages/examples/tui-demo/tests/built-bin.e2e.ts @@ -0,0 +1,98 @@ +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdtemp, mkdir, rm, symlink, readFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, it } from 'vitest' + +/** + * Published-entry smoke: run `lib/bin.js` under plain Node in a symlinked external consumer. + * The TUI app owns no non-TTY fallback, so the piped subprocess must refuse to boot with a + * nonzero exit and a stderr pointer at the one-shot CLI — the bin guards BEFORE the Loader + * because a compose-time throw inside the tree is logged per-entry, not rethrown. The consumer + * links only the bin's import chain (dsh-app-boot and its vendored Loader stack): the refusal + * fires before any config is read, so no plugin tree is needed. Missing-config fail-loud and + * full-boot coverage for the shared dsh-app-boot glue live in cli-demo's built-bin suite; it + * skips before build, and interactive TTY behavior is PTY-covered by examples/tui-agent (the + * one sanctioned PTY surface). + */ + +const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url)) +const tuiBin = join(repoRoot, 'packages/examples/tui-demo/lib/bin.js') + +// Symlink each package the bin imports at module load by package name so plain +// Node resolves its built `main`, matching an installed dependency rather than +// tsconfig paths. +const dshPackages = ['examples/tui-demo', 'ui/app-boot'] +const vendorPackages = ['cordis', 'loader', 'include', 'schemastery', 'cosmokit'] + +async function pkgName(absDir: string): Promise<string> { + const json = JSON.parse(await readFile(join(absDir, 'package.json'), 'utf8')) as { name: string } + return json.name +} + +/** Build a temporary external consumer with built workspace/vendor links. */ +async function makeConsumer(): Promise<string> { + const dir = await mkdtemp(join(tmpdir(), 'tui-built-bin-')) + const nm = join(dir, 'node_modules') + for (const rel of dshPackages) { + const abs = join(repoRoot, 'packages', rel) + const target = join(nm, await pkgName(abs)) + await mkdir(dirname(target), { recursive: true }) + await symlink(abs, target) + } + for (const v of vendorPackages) { + const abs = join(repoRoot, 'vendor', v) + const target = join(nm, await pkgName(abs)) + await mkdir(dirname(target), { recursive: true }) + await symlink(abs, target) + } + return dir +} + +/** Run the built bin in `cwd` with PIPED stdio; resolve with output + exit code. */ +function runBuiltBin(cwd: string): Promise<{ stdout: string; code: number; stderr: string }> { + return new Promise((resolve, reject) => { + // NO tsx — this is the published `node lib/bin.js` path (`--expose-internals` + // matches the demo command; the guard fires before the Loader needs it). + const child = spawn(process.execPath, ['--expose-internals', tuiBin, './cordis.yml'], { + cwd, + env: { ...process.env, DSH_HOME: join(cwd, '.dsh'), DSH_AGENTS_HOME: join(cwd, '.agents') }, + stdio: ['pipe', 'pipe', 'pipe'], + }) + let stdout = '' + let stderr = '' + child.stdout.setEncoding('utf8') + child.stdout.on('data', (c: string) => { stdout += c }) + child.stderr.setEncoding('utf8') + child.stderr.on('data', (c: string) => { stderr += c }) + const timer = setTimeout(() => { + child.kill('SIGKILL') + reject(new Error(`built bin did not exit within 25s. stdout:\n${stdout}\nstderr:\n${stderr}`)) + }, 25_000) + child.on('exit', (code) => { clearTimeout(timer); resolve({ stdout, code: code ?? -1, stderr }) }) + child.on('error', (err) => { clearTimeout(timer); reject(err) }) + child.stdin.end() + }) +} + +let consumer: string | undefined + +afterEach(async () => { + // Windows can briefly retain released handles after exit; retry removal. + if (consumer !== undefined) await rm(consumer, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) + consumer = undefined +}) + +describe.skipIf(!existsSync(tuiBin))('dsh-tui-demo BUILT bin (node lib/bin.js, no tsx)', () => { + it('refuses pipes LOUD (non-zero exit + stderr) before booting the Loader', async () => { + consumer = await makeConsumer() + const { stdout, code, stderr } = await runBuiltBin(consumer) + expect(code).not.toBe(0) + expect(stderr).toContain('requires stdin and stdout to be interactive TTYs') + expect(stderr).toContain('dsh-cli-demo') + // The refusal happens before any plugin mounts: stdout stays silent. + expect(stdout).toBe('') + }, 30_000) +}) diff --git a/packages/examples/tui-demo/tests/tui-agent.spec.ts b/packages/examples/tui-demo/tests/tui-agent.spec.ts index 73aa61430a..433eb5c0b7 100644 --- a/packages/examples/tui-demo/tests/tui-agent.spec.ts +++ b/packages/examples/tui-demo/tests/tui-agent.spec.ts @@ -33,6 +33,7 @@ describe('dsh-tui-demo app', () => { persistenceRoot: '/tmp/tui-sessions', persistenceCompression: 'none', welcome: 'TUI ready', + resumeCommand: 'dsh --resume {session}', ui: { color: false, maxToolOutputLines: 3 }, skills: { tool: { catalogDescriptionMaxLength: 8 } }, toolBash: { enableRunInBackground: false }, @@ -52,7 +53,12 @@ describe('dsh-tui-demo app', () => { expect(calls[0]?.config).toBeUndefined() expect(calls[2]?.config).toEqual({ root: '/tmp/tui-sessions', compression: 'none' }) const tuiConfig = calls[4]?.config as { sessionId: string } - expect(tuiConfig).toMatchObject({ welcome: 'TUI ready', color: false, maxToolOutputLines: 3 }) + expect(tuiConfig).toMatchObject({ + welcome: 'TUI ready', + resumeCommand: 'dsh --resume {session}', + color: false, + maxToolOutputLines: 3, + }) expect(tuiConfig.sessionId).toMatch(/^main-session-[0-9a-f-]{36}$/) const spineConfig = calls[5]?.config as { readonly agents: Array<Record<string, unknown>> @@ -88,7 +94,8 @@ describe('dsh-tui-demo app', () => { }) expect(calls[2]?.config).toEqual({ root: './.sessions' }) - expect(calls[4]?.config).toEqual({ welcome: 'ready.', sessionId: 'persisted-session' }) + // No configured welcome forwards none: the TUI banner sweeps in without a subtitle. + expect(calls[4]?.config).toEqual({ sessionId: 'persisted-session' }) expect((calls[5]?.config as { agents: Array<Record<string, unknown>> }).agents[0]).toMatchObject({ id: 'main', resumeSessionId: 'persisted-session', diff --git a/packages/llm/llm-pi-ai/package.json b/packages/llm/llm-pi-ai/package.json index 06b4cbeb3a..590e49f323 100644 --- a/packages/llm/llm-pi-ai/package.json +++ b/packages/llm/llm-pi-ai/package.json @@ -33,7 +33,7 @@ "cordis": "^4.0.0-rc.7" }, "dependencies": { - "@earendil-works/pi-ai": "^0.79.1", + "@earendil-works/pi-ai": "^0.81.1", "schemastery": "^3.18.0" }, "devDependencies": { diff --git a/packages/llm/llm-pi-ai/src/adapter.ts b/packages/llm/llm-pi-ai/src/adapter.ts index 7d91e9c351..ed0fb9fae4 100644 --- a/packages/llm/llm-pi-ai/src/adapter.ts +++ b/packages/llm/llm-pi-ai/src/adapter.ts @@ -4,13 +4,11 @@ * @module dsh-llm-pi-ai/adapter */ -import { - getModels, - streamSimple, -} from '@earendil-works/pi-ai' +import { streamSimple } from '@earendil-works/pi-ai/compat' +import { getBuiltinModels } from '@earendil-works/pi-ai/providers/all' +import type { BuiltinProvider } from '@earendil-works/pi-ai/providers/all' import type { Api, - KnownProvider, Model, SimpleStreamOptions, } from '@earendil-works/pi-ai' @@ -33,7 +31,7 @@ export interface PiAiAdapterOptions { * override, preserving the catalog's API/capability/compatibility metadata. */ function resolveModel(profile: PiAiProviderProfile, modelId: string): Model<Api> { - const model = getModels(profile.provider as KnownProvider).find(candidate => candidate.id === modelId) as Model<Api> | undefined + const model = getBuiltinModels(profile.provider as BuiltinProvider).find(candidate => candidate.id === modelId) as Model<Api> | undefined if (model === undefined) { throw new LlmError(`pi-ai provider "${profile.provider}" has no catalog model "${modelId}"`, 'UNKNOWN_MODEL') } @@ -82,7 +80,7 @@ export class PiAiAdapter extends LlmAdapter { if (profile === undefined) { return Promise.reject(new LlmError(`pi-ai adapter does not own provider "${provider}"`, 'NO_ADAPTER')) } - return Promise.resolve(getModels(profile.provider as KnownProvider).map(model => ({ + return Promise.resolve(getBuiltinModels(profile.provider as BuiltinProvider).map(model => ({ provider, id: model.id, name: model.name, diff --git a/packages/llm/llm-pi-ai/src/config.ts b/packages/llm/llm-pi-ai/src/config.ts index d5b5d70867..199463aaf6 100644 --- a/packages/llm/llm-pi-ai/src/config.ts +++ b/packages/llm/llm-pi-ai/src/config.ts @@ -4,7 +4,7 @@ * @module dsh-llm-pi-ai/config */ -import { getProviders } from '@earendil-works/pi-ai' +import { getBuiltinProviders } from '@earendil-works/pi-ai/providers/all' import type { CacheRetention, ThinkingBudgets, ThinkingLevel, Transport } from '@earendil-works/pi-ai' import z from 'schemastery' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' @@ -62,7 +62,7 @@ const profile = z.object({ apiKey: z.string(), baseURL: z.string(), headers: z.dict(z.string()), - reasoning: z.union(['minimal', 'low', 'medium', 'high', 'xhigh']), + reasoning: z.union(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']), thinkingBudgets, cacheRetention: z.union(['none', 'short', 'long']), transport: z.union(['sse', 'websocket', 'websocket-cached', 'auto']), @@ -84,7 +84,7 @@ export const Config: z<Config> = z.object({ */ export function resolveProfiles(profiles: readonly PiAiProviderProfile[]): ResolvedPiAiProviderProfile[] { if (profiles.length === 0) throw new Error('llm-pi-ai: providers must contain at least one profile') - const supported = new Set<string>(getProviders()) + const supported = new Set<string>(getBuiltinProviders()) const seen = new Set<string>() return profiles.map((source) => { const legacy = source as PiAiProviderProfile & { diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts index 7b28cdc1b5..f37b07f624 100644 --- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts +++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts @@ -5,8 +5,8 @@ import { Context } from 'cordis' import LlmService, { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError, userAgent } from '@deepseek-ai/dsh-llm' import * as LlmPiAi from '@deepseek-ai/dsh-llm-pi-ai' import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai' -import { getModels } from '@earendil-works/pi-ai' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' +import { getBuiltinModels } from '@earendil-works/pi-ai/providers/all' import { resolveProfiles } from '../src/config.ts' import { assemble } from './assemble.ts' @@ -244,7 +244,7 @@ describe('PiAiAdapter provider routing', () => { }) it('uses the resolved catalog context window for usage-based overflow detection', async () => { - const model = getModels('deepseek').find(candidate => candidate.id === 'deepseek-v4-flash') + const model = getBuiltinModels('deepseek').find(candidate => candidate.id === 'deepseek-v4-flash') if (model === undefined) throw new Error('deepseek-v4-flash missing from pi-ai test catalog') const events = [ '{"choices":[{"delta":{"role":"assistant","content":""},"index":0,"finish_reason":null}]}', diff --git a/packages/llm/llm-pi-ai/tests/sdk-options.spec.ts b/packages/llm/llm-pi-ai/tests/sdk-options.spec.ts index e85c44c110..d96297c242 100644 --- a/packages/llm/llm-pi-ai/tests/sdk-options.spec.ts +++ b/packages/llm/llm-pi-ai/tests/sdk-options.spec.ts @@ -2,8 +2,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const streamSimple = vi.hoisted(() => vi.fn()) -vi.mock('@earendil-works/pi-ai', async (importOriginal) => { - const actual = await importOriginal<typeof import('@earendil-works/pi-ai')>() +// The 0.81 SDK moved `streamSimple` to the compat entry; the adapter imports it +// from there, so the mock must target the same specifier. +vi.mock('@earendil-works/pi-ai/compat', async (importOriginal) => { + const actual = await importOriginal<typeof import('@earendil-works/pi-ai/compat')>() return { ...actual, streamSimple } }) diff --git a/packages/lsp/lsp-local/tests/lifecycle.spec.ts b/packages/lsp/lsp-local/tests/lifecycle.spec.ts index 47b8d78bb4..8a556a01e9 100644 --- a/packages/lsp/lsp-local/tests/lifecycle.spec.ts +++ b/packages/lsp/lsp-local/tests/lifecycle.spec.ts @@ -1,11 +1,11 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { realpath } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL, fileURLToPath } from 'node:url' import { Context } from 'cordis' -import Lsp, { type LspQueryRequest, type LspQueryResult } from '@deepseek-ai/dsh-lsp' +import Lsp, { type LspProvider, type LspQueryRequest, type LspQueryResult } from '@deepseek-ai/dsh-lsp' import { deadline } from '@deepseek-ai/dsh-timeout' import * as LspLocal from '@deepseek-ai/dsh-lsp-local' import type { LspLocalServerConfig } from '@deepseek-ai/dsh-lsp-local' @@ -38,12 +38,27 @@ function fakeServer(fakeEnv: Record<string, string> = {}, overrides: Partial<Lsp } /** Mount the real seam + lsp-local plugin driving one fake server. */ -async function mount(fakeEnv: Record<string, string> = {}, overrides: Partial<LspLocalServerConfig> = {}): Promise<Context> { +async function mount( + fakeEnv: Record<string, string> = {}, + overrides: Partial<LspLocalServerConfig> = {}, + captureProvider?: (provider: LspProvider) => void, +): Promise<Context> { const ctx = new Context() await ctx.plugin(Lsp) - await ctx.plugin(LspLocal, { - servers: { fake: fakeServer(fakeEnv, overrides) }, - }) + const register = ctx.lsp.registerProvider.bind(ctx.lsp) + const registrationSpy = captureProvider === undefined + ? undefined + : vi.spyOn(ctx.lsp, 'registerProvider').mockImplementation((provider) => { + captureProvider(provider) + return register(provider) + }) + try { + await ctx.plugin(LspLocal, { + servers: { fake: fakeServer(fakeEnv, overrides) }, + }) + } finally { + registrationSpy?.mockRestore() + } return ctx } @@ -247,10 +262,22 @@ describe('lsp-local end to end over a fake server', () => { // The first query succeeds, then the server exits before the second arrives, leaving a dead // instance in the pool. The next query must evict-and-replace it and still succeed, rather than // failing once on the closed connection first. - const ctx = await mount({ LSP_FAKE_EXIT_AFTER_REPLY: '1', LSP_FAKE_DEF: JSON.stringify(locationJson(0)) }) + let provider: LspProvider | undefined + const ctx = await mount( + { LSP_FAKE_EXIT_AFTER_REPLY: '1', LSP_FAKE_DEF: JSON.stringify(locationJson(0)) }, + {}, + (registered) => { provider = registered }, + ) expect(await ctx.lsp.query(query('goToDefinition'))).toMatchObject({ kind: 'locations' }) - // Wait past the fixture's post-reply exit so the pooled instance is observably dead. - await new Promise(resolve => setTimeout(resolve, 60)) + if (provider === undefined) throw new Error('expected lsp-local to register a provider') + // This implementation-local test reaches the private pool only to synchronize with its actual + // close state. A fixed wall-clock sleep can expire before a CPU-starved child runs its exit timer. + const instances = (provider as unknown as { + readonly instances: ReadonlyMap<string, { readonly dead: boolean }> + }).instances + const instance = [...instances.values()][0] + if (instance === undefined) throw new Error('expected one pooled LSP instance') + await waitFor(async () => instance.dead) expect(await ctx.lsp.query(query('goToDefinition'))).toMatchObject({ kind: 'locations' }) await ctx.fiber.dispose() }) diff --git a/packages/skill/skill-local/tests/skill-local.spec.ts b/packages/skill/skill-local/tests/skill-local.spec.ts index 43cc70c7ad..0c7d473b13 100644 --- a/packages/skill/skill-local/tests/skill-local.spec.ts +++ b/packages/skill/skill-local/tests/skill-local.spec.ts @@ -391,6 +391,9 @@ describe('LocalSkillProvider', () => { await empty.plugin(SkillService) SkillLocal.apply(empty, {}) expect(await empty.skills.list()).toEqual([]) + + delete process.env.DSH_AGENTS_HOME + expect(new SkillLocal.LocalSkillProvider(empty, { dshHome: join(envHome, 'empty-dsh') }).name).toBe('local') } finally { if (previousDshHome === undefined) { delete process.env.DSH_HOME diff --git a/packages/support/loader-smoke/src/index.ts b/packages/support/loader-smoke/src/index.ts index bcb27eb9d3..717e0c6a12 100644 --- a/packages/support/loader-smoke/src/index.ts +++ b/packages/support/loader-smoke/src/index.ts @@ -138,8 +138,6 @@ export interface LoaderSmokeOptions { readonly mode?: ExampleMode /** Environment overrides layered over the parent and isolated DSH homes. */ readonly env?: Readonly<NodeJS.ProcessEnv> - /** Lines written to stdin before EOF; omitted means immediate EOF. */ - readonly stdinLines?: readonly string[] /** Process deadline override for harness tests. */ readonly processTimeoutMs?: number /** Optional world-state setup run in the isolated cwd before process start. */ @@ -157,10 +155,10 @@ export interface LoaderSmokeResult { } /** - * Boot one real Loader tree from an isolated cwd, write the requested stdin - * script, close stdin, and await a clean exit. The helper owns process kill and - * temp-directory cleanup on every outcome, and picks src/lib via {@link resolveExampleLaunch}. - * @param options - example paths, mode, environment, stdin, and diagnostic identity. + * Boot one real Loader tree from an isolated cwd, close stdin immediately, and + * await a clean exit. The helper owns process kill and temp-directory cleanup on + * every outcome, and picks src/lib via {@link resolveExampleLaunch}. + * @param options - example paths, mode, environment, and diagnostic identity. * @returns captured stdout and stderr after a zero exit. */ export async function runLoaderSmoke(options: LoaderSmokeOptions): Promise<LoaderSmokeResult> { @@ -220,7 +218,7 @@ export async function runLoaderSmoke(options: LoaderSmokeOptions): Promise<Loade }) /* v8 ignore stop */ - child.stdin.end((options.stdinLines ?? []).map(line => `${line}\n`).join('')) + child.stdin.end() }) await options.inspect?.(cwd) return result diff --git a/packages/support/loader-smoke/tests/loader-smoke.spec.ts b/packages/support/loader-smoke/tests/loader-smoke.spec.ts index 1c80f9ee22..d1f764c69b 100644 --- a/packages/support/loader-smoke/tests/loader-smoke.spec.ts +++ b/packages/support/loader-smoke/tests/loader-smoke.spec.ts @@ -11,7 +11,7 @@ const fixture = (name: string): string => fileURLToPath(new URL(`./fixtures/${na const canonicalTempPath = (path: string): string => path.replace(/^\/private(?=\/var\/)/, '') describe('runLoaderSmoke', () => { - it('isolates the process, writes stdin, captures output, and removes the cwd', async () => { + it('isolates the process, closes stdin, captures output, and removes the cwd', async () => { const result = await runLoaderSmoke({ label: 'success fixture', tempDirPrefix: 'loader-smoke-success-', @@ -20,7 +20,6 @@ describe('runLoaderSmoke', () => { tsconfigPath, mode: 'src', env: { LOADER_SMOKE_MARKER: 'present' }, - stdinLines: ['one', 'two'], }) const output = JSON.parse(result.stdout) as { configPath: string @@ -35,7 +34,7 @@ describe('runLoaderSmoke', () => { configPath, args: [configPath], marker: 'present', - input: 'one\ntwo\n', + input: '', }) expect(canonicalTempPath(output.dshHome)).toBe(canonicalTempPath(join(output.cwd, '.dsh'))) expect(canonicalTempPath(output.agentsHome)).toBe(canonicalTempPath(join(output.cwd, '.agents'))) diff --git a/packages/ui/app-boot/README.md b/packages/ui/app-boot/README.md index d874d8c154..24840b7fda 100644 --- a/packages/ui/app-boot/README.md +++ b/packages/ui/app-boot/README.md @@ -5,10 +5,14 @@ Shared boot glue for the app bins ([`dsh-tui-demo`](../../examples/tui-demo/READ | Export | Role | |---|---| | `resolveConfigPath(path, snapshotMode, cwd?)` | Absolute config path; `snapshotMode === 'replay'` swaps a `cordis.yml`/`.yaml` basename for its sibling `cordis.snapshot.yml` | +| `parseResumeArg(argv)` | Split the `--resume <id>` / `--resume=<id>` flag out of the arguments, returning `{ resumeSessionId, rest }`; a valueless, empty, or repeated flag throws so a mistyped resume fails loud instead of silently starting fresh | | `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) | -| `boot(binName, absoluteConfigPath)` | Mount the Loader, mount the statically imported include plugin as the `cordis:include` builtin (so the config may live outside `node_modules` reach), include the config by absolute `file://` URL, await the whole tree, assert entries loaded, return the root context | +| `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?)` | Mount the Loader, mount the statically imported include plugin as the `cordis:include` builtin (so the config may live outside `node_modules` reach), include the config by absolute `file://` URL with the optional overlay patches, await the whole tree, assert entries loaded, return the root context | +| `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. @@ -16,16 +20,27 @@ Bare plugin specifiers in a config (`@deepseek-ai/dsh-*`, npm packages) resolve 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. +## Personal config + +A developer's machine-local preferences live outside every repository in the Harness home (default `~/.dsh`, overridable via `$DSH_HOME`; the single root [`resolveDshHome`](../../util/paths/README.md) resolves), consumed by the `dsh` CLI's TUI surface ([`apps/cli`](../../../apps/cli/README.md)); the demo bins boot their committed trees verbatim. Two optional files: + +- **`.env`** — loaded after the invoking directory's `.env`; `process.loadEnvFile` never overrides, so precedence is ambient environment > project `.env` > personal `.env`. +- **`config.yaml`** — loader overlay patches applied over the shipped default config, with the same semantics as an include entry's `patches` (the committed Code Mode overlay is the template): an id-targeted patch replaces the named entry's whole `config` (restate unchanged fields), `insert` adds entries, and `!!js` expressions interpolate at mount — so a personal `apiKey` can reference the personal `.env`. A patch naming an entry id absent from the booted tree is skipped with a loader warning. An empty or comments-only file throws (it parses to nothing, not to a list); disable the overlay with `[]` or by deleting the file. + +Subprocess test launchers point `DSH_HOME` at an isolated per-test directory so a developer's personal overlay can never leak into fixtures. + ## Model Experience -Indirectly, through the plugin tree it loads, which determines the prompts, schemas, messages, and model adapter in the resulting application. +Indirectly, through the plugin tree it loads, which determines the prompts, schemas, messages, and model adapter in the resulting application; the one export that contributes model-visible text, `addHarnessSourceSection`, does so only when a consumer calls it after boot. #### KV Cache effect -No direct invalidation; the named consumer owns any request-prefix changes. +No direct invalidation from `boot()`; a consumer that calls `addHarnessSourceSection` places one short line near the system prompt's head, before per-request content, so it does not invalidate the cache across turns, and any other request-prefix change is owned by the named consumer. ## Known Limitations and Deferred Work - **Bare package specifiers depend on Loader internals** — production bins need `node --expose-internals` or the Loader's optional native fallback; an in-process caller without either must use resolvable relative/file specifiers or tsx path mapping. - **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. +- **Personal patches see only the booted file's own entries** — an overlay leaf that reaches its base through a nested include entry (the Code Mode configs) resolves personal patch ids against the overlay's top-level entries, not the included subtree. diff --git a/packages/ui/app-boot/package.json b/packages/ui/app-boot/package.json index e2f0631e8b..ef267e8588 100644 --- a/packages/ui/app-boot/package.json +++ b/packages/ui/app-boot/package.json @@ -26,16 +26,24 @@ "src" ], "license": "BSD-3-Clause", + "dependencies": { + "js-yaml": "^4.2.0" + }, "peerDependencies": { "@cordisjs/plugin-include": "^1.0.4", "@cordisjs/plugin-loader": "^1.0.0-rc.5", "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-paths": "^0.0.1", + "@deepseek-ai/dsh-system-prompt": "^0.0.1", "cordis": "^4.0.0-rc.7" }, "devDependencies": { "@cordisjs/plugin-include": "workspace:^", "@cordisjs/plugin-loader": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-paths": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@types/js-yaml": "^4.0.9", "cordis": "^4.0.0-rc.7" } } diff --git a/packages/ui/app-boot/src/index.ts b/packages/ui/app-boot/src/index.ts index e2413fa736..2fd4ba4c05 100644 --- a/packages/ui/app-boot/src/index.ts +++ b/packages/ui/app-boot/src/index.ts @@ -1,15 +1,21 @@ /** * Shared boot glue for the app bins (`dsh-tui-demo`, `dsh-cli-demo`, `dsh-acp-demo`): load the gitignored - * `.env`, install the fail-loud Loader guards, resolve the config path (snapshot-aware), and - * drive the cordis Loader against a leaf `cordis.yml` until the whole tree has settled. + * `.env`, install the fail-loud Loader guards, resolve the config path (snapshot-aware), load the + * optional personal overlay patches from the Harness home (`~/.dsh`), and drive the cordis Loader + * against a leaf `cordis.yml` until the whole tree has settled. * @module @deepseek-ai/dsh-app-boot */ import { pathToFileURL } from 'node:url' -import { basename, dirname, resolve } from 'node:path' +import { readFileSync } from 'node:fs' +import { basename, dirname, join, resolve } from 'node:path' +import * as yaml from 'js-yaml' import { Context } from 'cordis' import Loader from '@cordisjs/plugin-loader' -import Include from '@cordisjs/plugin-include' +import Include, { type PatchOptions } from '@cordisjs/plugin-include' +import { resolveDshHome } from '@deepseek-ai/dsh-paths' +// Side-effect type import: resolves `ctx.get('systemPrompt')` to the service. +import type {} from '@deepseek-ai/dsh-system-prompt' /** * Resolve the config to boot. Replay swaps a `cordis.yml` basename for @@ -30,6 +36,50 @@ export function resolveConfigPath( return resolve(dir, replayName) } +/** CLI flag the interactive surface accepts to resume a persisted session by id. */ +const RESUME_FLAG = '--resume' + +/** + * Split a leading `--resume <id>` / `--resume=<id>` flag out of a CLI argument + * vector, returning the resumed session id (when the flag is present) and the + * remaining arguments with the flag and its value removed — so a positional + * config path stays readable regardless of the flag's position. A `--resume` + * with no following id, an empty id (`--resume=`), or a repeated `--resume` + * throws: a mistyped resume must fail loud, never silently start a fresh + * session. The id is not validated here; an unknown id fails loud downstream + * when the session cannot load. + * @param argv - the CLI arguments after subcommand dispatch. + * @returns the parsed resume id (or `undefined`) and the flag-stripped arguments. + */ +export function parseResumeArg( + argv: readonly string[], +): { resumeSessionId: string | undefined; rest: string[] } { + const rest: string[] = [] + let resumeSessionId: string | undefined + let skipNext = false + for (const [i, arg] of argv.entries()) { + if (skipNext) { + skipNext = false + continue + } + const inlineValue = arg.startsWith(`${RESUME_FLAG}=`) + if (arg === RESUME_FLAG || inlineValue) { + if (resumeSessionId !== undefined) throw new Error(`${RESUME_FLAG} may be given only once`) + const value = inlineValue ? arg.slice(RESUME_FLAG.length + 1) : argv[i + 1] + // A following token that is itself resume syntax (`--resume --resume x`) + // is a missing id, not a session literally named `--resume…`. + if (value === undefined || value === '' || value === RESUME_FLAG || value.startsWith(`${RESUME_FLAG}=`)) { + throw new Error(`${RESUME_FLAG} requires a session id (e.g. ${RESUME_FLAG} <session-id>)`) + } + resumeSessionId = value + skipNext = !inlineValue // the space form consumed the following token as its value + continue + } + rest.push(arg) + } + return { resumeSessionId, rest } +} + /** * Load the optional gitignored `.env` from `dir`. Missing files fall back to the * ambient environment; other read failures are reported through `warn`. @@ -51,6 +101,62 @@ export function loadEnv( } } +/** File inside the Harness home holding the personal loader overlay patches. */ +export const PERSONAL_CONFIG_FILENAME = 'config.yaml' + +// The include's YAML dialect: `!!js` scalars become expression nodes the +// Loader interpolates against each entry's context at mount time. Personal +// patches are parsed with the same schema so they may reference `process.env`. +// Load-only: this schema never dumps, so no `predicate`/`represent`. +const jsExprType = new yaml.Type('tag:yaml.org,2002:js', { + kind: 'scalar', + resolve: data => typeof data === 'string', + construct: data => ({ __jsExpr: String(data) }), +}) +const personalPatchesSchema = yaml.JSON_SCHEMA.extend(jsExprType) + +/** + * Load the optional personal overlay patches (`config.yaml` under the Harness + * home). The file is a top-level YAML array of loader patch entries + * (`@cordisjs/plugin-include`'s `PatchOptions`): id-targeted config overrides + * and `insert` lists, with `!!js` expressions allowed. A missing file means + * "no personal overlay"; an unreadable, unparsable, or non-array file throws — + * a present personal config that cannot apply is a misconfiguration and must + * fail loud at boot, never be silently skipped. + * @param binName - the diagnostic prefix on the thrown error. + * @param dir - the Harness home; defaults to {@link resolveDshHome} (`$DSH_HOME` or `~/.dsh`). + * @returns the parsed patches, or `undefined` when the file does not exist. + */ +export function loadPersonalPatches( + binName: string, dir: string = resolveDshHome(), +): PatchOptions[] | undefined { + const file = join(dir, PERSONAL_CONFIG_FILENAME) + let content: string + try { + content = readFileSync(file, 'utf8') + } catch (error) { + if ((error as NodeJS.ErrnoException | null)?.code === 'ENOENT') return undefined + throw new Error(`${binName}: failed to read personal patches ${file}: ${String(error)}`) + } + let parsed: unknown + try { + parsed = yaml.load(content, { schema: personalPatchesSchema }) + } catch (error) { + throw new Error(`${binName}: failed to parse personal patches ${file}: ${String(error)}`) + } + if (!Array.isArray(parsed)) { + throw new Error(`${binName}: personal patches ${file} must be a top-level YAML array of loader patch entries`) + } + // A present personal config that cannot apply is a misconfiguration and must + // fail loud here — the include only warns per entry at mount. + parsed.forEach((entry, index) => { + if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) { + throw new Error(`${binName}: personal patches entry ${index + 1} in ${file} must be a mapping (a loader patch entry)`) + } + }) + return parsed as PatchOptions[] +} + /** * The slice of `process` {@link installFailLoud} needs — injectable so tests * exercise the handler without registering on (or exiting) the real process. @@ -109,18 +215,52 @@ export function assertEntriesLoaded(ctx: Context, binName: string): void { * @param binName - the diagnostic prefix for load-failure errors. * @param absoluteConfigPath - the config to include; must already be absolute * (see {@link resolveConfigPath}). + * @param patches - optional overlay patches applied over the included tree + * (see {@link loadPersonalPatches}); an empty list mounts none. * @returns the root context once every entry has started. */ -export async function boot(binName: string, absoluteConfigPath: string): Promise<Context> { +export async function boot( + binName: string, absoluteConfigPath: string, patches?: PatchOptions[], +): Promise<Context> { const ctx = new Context() ctx.baseUrl = pathToFileURL(dirname(absoluteConfigPath)).href + '/' await ctx.plugin(Loader) ctx.loader.builtins.include = Include await ctx.loader.create({ name: 'cordis:include', - config: { path: pathToFileURL(absoluteConfigPath).href }, + config: { + path: pathToFileURL(absoluteConfigPath).href, + ...patches !== undefined && patches.length > 0 ? { patches } : {}, + }, }) await ctx.loader.await() assertEntriesLoaded(ctx, binName) return ctx } + +/** Prompt-section name for the harness-source location line an app bin adds after boot. */ +export const HARNESS_SOURCE_SECTION = 'harness:source' + +/** + * Add a global prompt section naming the on-disk path to the harness source + * checkout the running bin was launched from, so the agent knows where its own + * source lives (the self-referential `dsh-tool-cordis` toolset reads and edits + * it). Call once on the settled boot context ({@link boot}); the section orders + * just after the harness identity opener (`-100`) and before the deployment + * persona (`0`). A booted tree with no `systemPrompt` service has no prompt to + * augment, so this is then a no-op that returns `undefined`. The section is + * registered against the `systemPrompt` service's fiber, so a dev HMR reload of + * that plugin drops it until the next boot. + * @param ctx - the settled boot context whose global system prompt to augment. + * @param sourceRoot - the absolute path to the harness checkout root. + * @returns the section disposer, or `undefined` when no `systemPrompt` service is mounted. + */ +export function addHarnessSourceSection(ctx: Context, sourceRoot: string): (() => void) | undefined { + const systemPrompt = ctx.get('systemPrompt') + if (systemPrompt === undefined) return undefined + return systemPrompt.section({ + name: HARNESS_SOURCE_SECTION, + order: -99, + text: `Your own source code is the checkout at ${sourceRoot}; you can read it there to learn how dsh works and how to extend it.`, + }) +} diff --git a/packages/ui/app-boot/tests/app-boot.spec.ts b/packages/ui/app-boot/tests/app-boot.spec.ts index 510186ebb0..76e5238db7 100644 --- a/packages/ui/app-boot/tests/app-boot.spec.ts +++ b/packages/ui/app-boot/tests/app-boot.spec.ts @@ -2,10 +2,11 @@ import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve, sep } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import type { Context } from 'cordis' +import { Context } from 'cordis' +import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' import { - assertEntriesLoaded, boot, installFailLoud, loadEnv, resolveConfigPath, - type FailLoudProcess, + addHarnessSourceSection, assertEntriesLoaded, boot, HARNESS_SOURCE_SECTION, + installFailLoud, loadEnv, parseResumeArg, resolveConfigPath, type FailLoudProcess, } from '../src/index.ts' const NAME = 'dsh-test-bin' @@ -29,6 +30,31 @@ describe('resolveConfigPath', () => { }) }) +describe('parseResumeArg', () => { + it('returns no resume id and passes arguments through when the flag is absent', () => { + expect(parseResumeArg([])).toEqual({ resumeSessionId: undefined, rest: [] }) + expect(parseResumeArg(['custom.yml'])).toEqual({ resumeSessionId: undefined, rest: ['custom.yml'] }) + }) + + it('parses the space form, the inline form, and leaves a positional config path in any position', () => { + expect(parseResumeArg(['--resume', 'sess-1'])).toEqual({ resumeSessionId: 'sess-1', rest: [] }) + expect(parseResumeArg(['--resume=sess-2'])).toEqual({ resumeSessionId: 'sess-2', rest: [] }) + expect(parseResumeArg(['--resume', 'sess-3', 'app.yml'])).toEqual({ resumeSessionId: 'sess-3', rest: ['app.yml'] }) + expect(parseResumeArg(['app.yml', '--resume', 'sess-4'])).toEqual({ resumeSessionId: 'sess-4', rest: ['app.yml'] }) + }) + + it('fails loud on a valueless, empty, or repeated flag rather than silently starting fresh', () => { + expect(() => parseResumeArg(['--resume'])).toThrow('--resume requires a session id') + expect(() => parseResumeArg(['--resume='])).toThrow('--resume requires a session id') + expect(() => parseResumeArg(['--resume', 'a', '--resume', 'b'])).toThrow('--resume may be given only once') + }) + + it('rejects resume syntax used as the flag value instead of resuming a session named like the flag', () => { + expect(() => parseResumeArg(['--resume', '--resume', 'sess'])).toThrow('--resume requires a session id') + expect(() => parseResumeArg(['--resume', '--resume=sess'])).toThrow('--resume requires a session id') + }) +}) + describe('loadEnv', () => { it('loads variables from .env in the given dir', () => { const dir = tmp() @@ -176,3 +202,56 @@ describe('boot', () => { await expect(boot(NAME, join(dir, 'cordis.yml'))).rejects.toThrow(`${NAME}: plugin(s) failed to load: ./missing.mjs`) }) }) + +describe('addHarnessSourceSection', () => { + const SOURCE_ROOT = `${sep}opt${sep}harness-src` + const EXPECTED = `Your own source code is the checkout at ${SOURCE_ROOT}; you can read it there to learn how dsh works and how to extend it.` + + it('adds the source path between the harness identity and the deployment persona', async () => { + const ctx = new Context() + try { + await ctx.plugin(SystemPrompt, { persona: 'You are a coding agent.' }) + const dispose = addHarnessSourceSection(ctx, SOURCE_ROOT) + expect(dispose).toBeTypeOf('function') + const systemPrompt = ctx.get('systemPrompt')! + const rendered = renderPrompt(await systemPrompt.assemble()) + expect(rendered).toContain(EXPECTED) + // Harness-owned opener (-100) → source (-99) → persona (0). The >= 0 guards + // keep a drifted opener/persona string from a false pass through `-1 < n`. + const identityAt = rendered.indexOf('You are an AI agent powered by the DeepSeek Harness SDK.') + const sourceAt = rendered.indexOf(EXPECTED) + const personaAt = rendered.indexOf('You are a coding agent.') + expect(identityAt).toBeGreaterThanOrEqual(0) + expect(personaAt).toBeGreaterThanOrEqual(0) + expect(identityAt).toBeLessThan(sourceAt) + expect(sourceAt).toBeLessThan(personaAt) + } finally { + await ctx.fiber.dispose() + } + }) + + it('is a no-op returning undefined when no systemPrompt service is mounted', async () => { + const ctx = new Context() + try { + expect(addHarnessSourceSection(ctx, SOURCE_ROOT)).toBeUndefined() + } finally { + await ctx.fiber.dispose() + } + }) + + it('disposes the section it added, so a systemPrompt reload leaves no residue', async () => { + const ctx = new Context() + try { + await ctx.plugin(SystemPrompt, {}) + const systemPrompt = ctx.get('systemPrompt')! + const dispose = addHarnessSourceSection(ctx, SOURCE_ROOT)! + const present = await systemPrompt.assemble() + expect(present.sections.some(section => section.name === HARNESS_SOURCE_SECTION)).toBe(true) + dispose() + const gone = await systemPrompt.assemble() + expect(gone.sections.some(section => section.name === HARNESS_SOURCE_SECTION)).toBe(false) + } finally { + await ctx.fiber.dispose() + } + }) +}) diff --git a/packages/ui/app-boot/tests/personal-config.spec.ts b/packages/ui/app-boot/tests/personal-config.spec.ts new file mode 100644 index 0000000000..5d72238cfa --- /dev/null +++ b/packages/ui/app-boot/tests/personal-config.spec.ts @@ -0,0 +1,141 @@ +/** + * Personal-config behavior of `dsh-app-boot`: the Harness home (`~/.dsh`) + * `config.yaml` overlay loader and `boot()` applying the personal overlay over + * a real Loader tree. + */ + +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import type { Context } from 'cordis' +import { + boot, + loadPersonalPatches, + PERSONAL_CONFIG_FILENAME, +} from '../src/index.ts' + +const NAME = 'dsh-test-bin' + +const tmp = (): string => mkdtempSync(join(tmpdir(), 'dsh-personal-config-')) + +describe('loadPersonalPatches', () => { + afterEach(() => { + delete process.env.DSH_HOME + }) + + it('returns undefined when no personal patches file exists', () => { + expect(loadPersonalPatches(NAME, tmp())).toBeUndefined() + }) + + it('parses a patch list and preserves !!js expressions as loader expression nodes', () => { + const dir = tmp() + writeFileSync(join(dir, PERSONAL_CONFIG_FILENAME), [ + '- id: tui-agent', + " name: '@deepseek-ai/dsh-tui-demo'", + ' config:', + ' model: !!js process.env.DSH_SPEC_MODEL', + '- insert:', + ' - id: llm', + " name: '@deepseek-ai/dsh-llm-pi-ai'", + '', + ].join('\n')) + const patches = loadPersonalPatches(NAME, dir) + expect(patches).toHaveLength(2) + expect(patches?.[0]).toMatchObject({ + id: 'tui-agent', + config: { model: { __jsExpr: 'process.env.DSH_SPEC_MODEL' } }, + }) + expect(patches?.[1]?.insert).toHaveLength(1) + }) + + it('defaults its directory to the Harness home ($DSH_HOME)', () => { + const dir = tmp() + writeFileSync(join(dir, PERSONAL_CONFIG_FILENAME), '- id: x\n config:\n a: 1\n') + process.env.DSH_HOME = dir + expect(loadPersonalPatches(NAME)).toHaveLength(1) + }) + + it('fails loud on an unreadable file (a present personal config is never skipped)', () => { + const dir = tmp() + mkdirSync(join(dir, PERSONAL_CONFIG_FILENAME)) // a directory: present, unreadable as a file + expect(() => loadPersonalPatches(NAME, dir)) + .toThrow(new RegExp(`^${NAME}: failed to read personal patches `)) + }) + + it('fails loud on unparsable YAML and on a !!js tag with no expression body', () => { + const dir = tmp() + writeFileSync(join(dir, PERSONAL_CONFIG_FILENAME), 'invalid: [unclosed\n') + expect(() => loadPersonalPatches(NAME, dir)) + .toThrow(new RegExp(`^${NAME}: failed to parse personal patches `)) + writeFileSync(join(dir, PERSONAL_CONFIG_FILENAME), '- id: x\n config:\n a: !!js\n') + expect(() => loadPersonalPatches(NAME, dir)) + .toThrow(new RegExp(`^${NAME}: failed to parse personal patches `)) + }) + + it('fails loud when the file is not a top-level array or an entry is not an object', () => { + const dir = tmp() + writeFileSync(join(dir, PERSONAL_CONFIG_FILENAME), 'id: not-a-list\n') + expect(() => loadPersonalPatches(NAME, dir)) + .toThrow('must be a top-level YAML array of loader patch entries') + writeFileSync(join(dir, PERSONAL_CONFIG_FILENAME), '- just-a-string\n') + expect(() => loadPersonalPatches(NAME, dir)) + .toThrow(`${NAME}: personal patches entry 1 in`) + }) +}) + +describe('boot with personal patches', () => { + function writeTree(dir: string): string { + writeFileSync(join(dir, 'noop.mjs'), 'export const name = "noop"\nexport function apply() {}\n') + writeFileSync(join(dir, 'cordis.yml'), '- id: noop\n name: ./noop.mjs\n config:\n value: base\n') + return join(dir, 'cordis.yml') + } + + function entryConfig(ctx: Context, id: string): unknown { + return [...ctx.loader.entries()].find(entry => entry.options.id === id)?.options.config + } + + it('applies id-targeted overrides, inserts, and interpolates !!js from the environment', async () => { + const dir = tmp() + const personal = tmp() + writeFileSync(join(personal, PERSONAL_CONFIG_FILENAME), [ + '- id: noop', + ' name: ./noop.mjs', + ' config:', + ' value: !!js process.env.DSH_APP_BOOT_PERSONAL_SPEC', + '- insert:', + ' - id: personal-extra', + ' name: ./noop.mjs', + '', + ].join('\n')) + process.env['DSH_APP_BOOT_PERSONAL_SPEC'] = 'personal-value' + const ctx = await boot(NAME, writeTree(dir), loadPersonalPatches(NAME, personal)) + try { + const noop = [...ctx.loader.entries()].find(entry => entry.options.id === 'noop') + // The mounted plugin received the interpolated environment value. + expect(noop?.fiber?.config).toEqual({ value: 'personal-value' }) + expect([...ctx.loader.entries()].some(entry => entry.options.id === 'personal-extra')).toBe(true) + } finally { + await ctx.fiber.dispose() + delete process.env['DSH_APP_BOOT_PERSONAL_SPEC'] + } + }) + + it('mounts no patch layer for an absent or empty personal overlay', async () => { + const dir = tmp() + const ctx = await boot(NAME, writeTree(dir), loadPersonalPatches(NAME, tmp())) + try { + expect(entryConfig(ctx, 'noop')).toEqual({ value: 'base' }) + } finally { + await ctx.fiber.dispose() + } + const empty = tmp() + writeFileSync(join(empty, PERSONAL_CONFIG_FILENAME), '[]\n') + const ctxEmpty = await boot(NAME, writeTree(tmp()), loadPersonalPatches(NAME, empty)) + try { + expect(entryConfig(ctxEmpty, 'noop')).toEqual({ value: 'base' }) + } finally { + await ctxEmpty.fiber.dispose() + } + }) +}) diff --git a/packages/ui/app-boot/tsconfig.json b/packages/ui/app-boot/tsconfig.json index b85dc7f6a2..23f83dda51 100644 --- a/packages/ui/app-boot/tsconfig.json +++ b/packages/ui/app-boot/tsconfig.json @@ -19,6 +19,12 @@ }, { "path": "../../support/invariants" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../../util/paths" } ] } diff --git a/packages/ui/tui/README.md b/packages/ui/tui/README.md index 4750764ec1..0840ec7c9d 100644 --- a/packages/ui/tui/README.md +++ b/packages/ui/tui/README.md @@ -1,12 +1,12 @@ # @deepseek-ai/dsh-tui -The interactive terminal front door for DeepSeek Harness agents, built on [`@earendil-works/pi-tui`](https://www.npmjs.com/package/@earendil-works/pi-tui). It requires stdin and stdout TTYs; scripts and Loader pipes should use the headless [`@deepseek-ai/dsh-cli-demo`](../../examples/cli-demo/README.md) app instead. +The interactive terminal front door for DeepSeek Harness agents, built on [`@earendil-works/pi-tui`](https://www.npmjs.com/package/@earendil-works/pi-tui). It requires stdin and stdout TTYs; scripts and Loader pipes should use the one-shot [`@deepseek-ai/dsh-cli-demo`](../../examples/cli-demo/README.md) app instead. The implemented [TUI feature Agent Note](../../../.agents/notes/implemented/feature/2026-07-17-dedicated-full-screen-tui-front-door.md) owns the front-door decision; the [terminal-state snapshot Agent Note](../../../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md) owns its verification strategy. Interactive terminals on macOS, Linux, and Windows are supported. Windows uses pi-tui's native console VT-input handling, and the [Windows support Agent Note](../../../.agents/notes/implemented/feature/2026-07-20-windows-tui-support.md) owns the platform decision and ConPTY process verification. -This package owns interactive terminal presentation and input only. It injects `agents`, [`commands`](../commands/README.md), `llm`, `systemPrompt`, `tokenMeter`, `tools`, and `userInteraction`, then drives an agent created or resumed by app or developer code. Agent lifecycle, persistence, and the model-facing [`ask_user_question`](../tool-ask-user/README.md) tool remain separate composition entries. +This package owns interactive terminal presentation and input only. It injects `agents`, [`commands`](../commands/README.md), `llm`, `systemPrompt`, `tokenMeter`, `tools`, and `userInteraction`, optionally reads a `skills` service (present only when one is mounted), then drives an agent created or resumed by app or developer code. Agent lifecycle, persistence, and the model-facing [`ask_user_question`](../tool-ask-user/README.md) tool remain separate composition entries. 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.resolveModelContext()` for the current route, displays `context unknown` when the adapter has no capacity metadata, and also shows tool-card mode and the current model with reasoning state; 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. @@ -14,15 +14,23 @@ An embedding may provide `TuiRuntime.formatCwd` when its logical workspace label Before model output, session events, tool presenters, questions, configuration, or diagnostics reach pi-tui's ANSI-aware renderers or the terminal title, the TUI renders C0 and C1 controls other than line feeds as visible `\xNN` text. Those sources cannot add terminal control sequences; the TUI and pi-tui retain ownership of terminal rendering and styling. -While the agent is running, ordinary editor submissions call `agent.steer()`; otherwise they call `agent.send()`. A slash at the start of the submitted line enters `ctx.commands` instead: known commands execute directly and unknown commands produce a warning, with no automatic fallthrough to 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`, `/cancel`, `/reasoning`, `/tools`, `/redraw`, and `/exit` as agent-scoped definitions; every other effective command joins autocomplete and `/help` dynamically. 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.send()`. 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. `/model` opens the advisory `ctx.llm` catalog as a keyboard selector: Up/Down moves, Enter selects, and Escape closes it. `/model <model>` still selects an unambiguous model id directly, while `/model <provider>/<model>` selects an exact target. 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 pair 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. + +The footer sums the session's reported usage as `↑<uncached input> ↓<output>`, followed by `cache <rate>%` once any input has been billed — the share of billed prompt tokens (uncached input plus cache reads and writes) served from the provider cache, rounded to a percent. It also compares token-meter pressure with `ctx.llm.resolveModelContext()` for the current route (omitting the context share when the adapter has no capacity metadata) and shows the current model and tool-card mode; the right side clips first when the footer is narrow. + +`/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, 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. + +When `resumeCommand` is set and a `sessionPersistence` backend is mounted, exiting prints the resume command for the current session (once it has been persisted, so an abandoned session yields no hint), and `/resume` lists this workspace's persisted sessions newest-first, each with its resume command and a marker on the current one. `{session}` in the template expands to the session id; the TUI only prints commands to copy and never resumes in place. + ## Config | Key | Default | Meaning | |---|---|---| -| `welcome` | `ready.` | Header subtitle until the session has a logged title. | +| `welcome` | — | Banner subtitle line until the session has a logged title; unset, the banner sweeps in with no subtitle | | `sessionId` | `main` | Exact shared agent/session identity driven by the terminal | | `showReasoning` | `true` | Render reasoning blocks | | `maxToolOutputLines` | `6` | Output lines retained across a collapsed tool card's head/tail preview | @@ -35,6 +43,7 @@ While the agent is running, ordinary editor submissions call `agent.steer()`; ot | `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 `/resume`, with `{session}` expanded to the session id; unset disables both. Needs a `sessionPersistence` backend | ```yaml - id: terminal @@ -82,6 +91,20 @@ The selector adds no messages. A target change may alter interpolated system-pro Changing provider or model enters that target's cache domain; no cache reuse across distinct targets is assumed. +### Manual skill invocation + +#### What the model sees + +A `/skill:<name> [instructions]` submission loads the named skill and delivers one text block: a `<skill name="…">` element wrapping the skill's instructions — preceded, when the provider exposes a resource base, by a line locating the skill's relative resources — followed by any trailing instructions the user typed. Delivery follows the same send-while-idle / steer-while-running rule as ordinary input. The command, not the model, chooses the skill; model-disabled skills are omitted from autocomplete but stay loadable by exact name. + +#### Token effect + +The rendered skill block and trailing instructions are retained as one user turn under the agent loop's normal session-history and compaction rules; a repeated invocation appends the body again. + +#### KV Cache effect + +Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries. + ### Interactive user-question answers #### What the model sees @@ -100,4 +123,5 @@ Append-only; newly visible content follows the reusable request prefix and does - **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** — automation must use the headless app rather than expecting an internal fallback. +- **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. +- **Manual `/skill:` invocation always reloads the full skill body** — the TUI does not detect a skill already present in the conversation, so repeated invocations append its instructions again. diff --git a/packages/ui/tui/package.json b/packages/ui/tui/package.json index cb34aa6367..38c05a3d6f 100644 --- a/packages/ui/tui/package.json +++ b/packages/ui/tui/package.json @@ -34,13 +34,23 @@ "@deepseek-ai/dsh-llm": "^0.0.1", "@deepseek-ai/dsh-llm-retry": "^0.0.1", "@deepseek-ai/dsh-session": "^0.0.1", + "@deepseek-ai/dsh-session-persistence": "^0.0.1", "@deepseek-ai/dsh-session-title": "^0.0.1", + "@deepseek-ai/dsh-skill": "^0.0.1", "@deepseek-ai/dsh-system-prompt": "^0.0.1", "@deepseek-ai/dsh-token-meter": "^0.0.1", "@deepseek-ai/dsh-tools": "^0.0.1", "@deepseek-ai/dsh-user-interaction": "^0.0.1", "cordis": "^4.0.0-rc.7" }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-session-persistence": { + "optional": true + }, + "@deepseek-ai/dsh-skill": { + "optional": true + } + }, "dependencies": { "@earendil-works/pi-tui": "0.80.7", "schemastery": "^3.18.0" @@ -54,7 +64,9 @@ "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-retry": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-skill": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-token-meter": "workspace:^", "@deepseek-ai/dsh-tool-cordis": "workspace:^", diff --git a/packages/ui/tui/src/index.ts b/packages/ui/tui/src/index.ts index dde2775774..4e59747128 100644 --- a/packages/ui/tui/src/index.ts +++ b/packages/ui/tui/src/index.ts @@ -13,6 +13,7 @@ import { Editor, Input, Key, + Loader, Markdown, Spacer, Text, @@ -29,6 +30,7 @@ import { type MarkdownTheme, type OverlayHandle, type SelectListTheme, + type SlashCommand, type Terminal, type TerminalColorScheme, } from '@earendil-works/pi-tui' @@ -44,7 +46,7 @@ import { import type {} from '@deepseek-ai/dsh-agent-loop' import type {} from '@deepseek-ai/dsh-token-meter' import type {} from '@deepseek-ai/dsh-commands' -import { errorChain } from '@deepseek-ai/dsh-llm' +import { assertNever, errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, LlmModelInfo, @@ -52,8 +54,12 @@ import type { TokenUsage, } from '@deepseek-ai/dsh-llm' import type {} from '@deepseek-ai/dsh-llm-retry' -import { SessionId, type Session, type SessionEvent, type TodoItem } from '@deepseek-ai/dsh-session' +import { SessionId, type Session, type SessionEvent, type SessionHeader, type TodoItem } from '@deepseek-ai/dsh-session' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' +// Side-effect type import: declaration-merges the optional `sessionPersistence` +// service onto `Context` so `ctx.get('sessionPersistence')` is typed. +import type {} from '@deepseek-ai/dsh-session-persistence' +import type { SkillDefinition, SkillResourceBase, SkillService } from '@deepseek-ai/dsh-skill' import type { FileDiff, TerminalCallView, @@ -94,7 +100,14 @@ export interface TuiConfig { showHardwareCursor?: boolean /** Apply the built-in ANSI color palette. */ color?: boolean - /** Terminal window title while the UI is mounted. */ + /** + * Paint the startup banner's product name in the DeepSeek brand gradient + * using 24-bit truecolor. Requires {@link TuiConfig.color}; falls back to the + * flat accent color when either is off. Unset auto-detects `COLORTERM` at the + * process boundary, so most deployments leave it unset. + */ + truecolor?: boolean + /** Terminal window title while the UI is mounted; a logged session title prefixes it. */ title?: string } @@ -108,6 +121,8 @@ const modelDialogWidthSchema = z.number().step(1).min(20).default(72) const modelDialogMaxHeightSchema = z.number().step(1).min(6).default(20) const showHardwareCursorSchema = z.boolean().default(false) const colorSchema = z.boolean().default(true) +// No default: an unset value auto-detects truecolor from COLORTERM in `apply`. +const truecolorSchema = z.boolean() const titleSchema = z.string().default('DeepSeek Harness') /** Schemastery schema for presentation settings embedded by app bundles. */ @@ -122,20 +137,30 @@ export const TuiConfigSchema: z<TuiConfig> = z.object({ modelDialogMaxHeight: modelDialogMaxHeightSchema, showHardwareCursor: showHardwareCursorSchema, color: colorSchema, + truecolor: truecolorSchema, title: titleSchema, }) /** Serializable plugin configuration. */ export interface Config extends TuiConfig { - /** Header subtitle. Defaults to `ready.`. */ + /** Banner subtitle line. When absent, the banner has no subtitle and sweeps in on start. */ welcome?: string /** Exact shared agent/session identity driven by this terminal. Defaults to `main`. */ sessionId?: string + /** + * Shell command template shown for resuming this session: printed on exit and + * listed by `/resume`, with every `{session}` occurrence replaced by the live + * session id. Absent disables both surfaces. Deployments set it only when a + * persistence backend makes the session resumable (e.g. + * `RESUME_SESSION_ID={session} dsh`). + */ + resumeCommand?: string } export const Config: z<Config> = z.object({ - welcome: z.string().default('ready.'), + welcome: z.string(), sessionId: z.string().default('main'), + resumeCommand: z.string(), showReasoning: showReasoningSchema, maxToolOutputLines: maxToolOutputLinesSchema, maxQuestionOptions: maxQuestionOptionsSchema, @@ -146,6 +171,7 @@ export const Config: z<Config> = z.object({ modelDialogMaxHeight: modelDialogMaxHeightSchema, showHardwareCursor: showHardwareCursorSchema, color: colorSchema, + truecolor: truecolorSchema, title: titleSchema, }) @@ -161,6 +187,7 @@ export interface ResolvedTuiConfig { modelDialogMaxHeight: number showHardwareCursor: boolean color: boolean + truecolor: boolean title: string } @@ -198,6 +225,7 @@ export function resolveTuiConfig(config: TuiConfig | undefined): ResolvedTuiConf modelDialogMaxHeight: config?.modelDialogMaxHeight ?? 20, showHardwareCursor: config?.showHardwareCursor ?? false, color: config?.color ?? true, + truecolor: config?.truecolor ?? false, title: config?.title ?? 'DeepSeek Harness', } } @@ -269,6 +297,60 @@ function createPalette(enabled: boolean, scheme: TerminalColorScheme = 'dark'): } } +/** + * DeepSeek brand gradient stops (indigo → light blue) taken from the + * deepseek.com logo, painted across the startup banner's product name on + * truecolor terminals. Fixed brand identity, deliberately outside the + * theme-adaptive {@link Palette}. + */ +const BRAND_GRADIENT = [ + [77, 107, 254], // #4D6BFE + [57, 130, 255], // #3982FF + [36, 152, 255], // #2498FF +] as const + +/** + * Sample {@link BRAND_GRADIENT} at fraction `t` via piecewise-linear + * interpolation across its stops. + * + * @param t - Position along the gradient; clamped to [0, 1]. + * @returns The interpolated `[r, g, b]` channels, each rounded to 0–255. + */ +function brandColorAt(t: number): readonly [number, number, number] { + const span = Math.min(Math.max(t, 0), 1) * (BRAND_GRADIENT.length - 1) + const index = Math.min(Math.floor(span), BRAND_GRADIENT.length - 2) + const local = span - index + // `index` is clamped to a valid adjacent pair, so both lookups are in-bounds. + const from = BRAND_GRADIENT[index] as readonly [number, number, number] + const to = BRAND_GRADIENT[index + 1] as readonly [number, number, number] + return [ + Math.round(from[0] + (to[0] - from[0]) * local), + Math.round(from[1] + (to[1] - from[1]) * local), + Math.round(from[2] + (to[2] - from[2]) * local), + ] +} + +/** + * Paint `text` left-to-right in the DeepSeek brand gradient with per-character + * 24-bit foreground codes, resetting to the default foreground at the end. + * Foreground-only, so it stays legible on any terminal background; the caller + * gates it on truecolor support and wraps it in bold. + * + * @param text - Text to colorize; sampled once per character. + * @returns `text` wrapped in truecolor SGR foreground codes. + */ +function gradientText(text: string): string { + // The sole caller passes the ASCII product name, so UTF-16 unit iteration + // samples exactly one color per visible letter. + const last = Math.max(1, text.length - 1) + let painted = '' + for (let index = 0; index < text.length; index += 1) { + const [r, g, b] = brandColorAt(index / last) + painted += `\x1b[38;2;${r};${g};${b}m${text.charAt(index)}` + } + return `${painted}\x1b[39m` +} + function markdownTheme(palette: Palette): MarkdownTheme { return { heading: text => palette.accent(text), @@ -378,33 +460,126 @@ async function readModelChoices( return groups.flat() } +/** Milliseconds between banner sweep-reveal frames (~60 fps). */ +const BANNER_REVEAL_INTERVAL_MS = 15 + +/** Number of sweep frames the banner reveal spreads the terminal width over. */ +const BANNER_REVEAL_STEPS = 24 + +/** + * Borderless startup banner: product title, an optional configured subtitle, + * and the model/session detail line. No box frame — each line renders as plain + * left-padded text (matching transcript notices) so it reads on any theme. + */ class HeaderComponent implements Component { + /** Columns of the banner currently revealed; `undefined` renders it whole. */ + private revealWidth: number | undefined + constructor( private readonly agent: Agent, - private readonly subtitle: () => string, + private readonly subtitle: () => string | undefined, private readonly palette: Palette, + private readonly gradient: boolean, private readonly currentModel: () => string | undefined, ) {} + /** Clip the banner to `width` columns (the sweep reveal); `undefined` restores it. */ + setRevealWidth(width: number | undefined): void { + this.revealWidth = width + } + invalidate(): void {} render(width: number): string[] { - const usable = Math.max(1, width - 4) - const title = `${this.palette.bold(this.palette.accent('DEEPSEEK'))} ${this.palette.bold('HARNESS')}` + const usable = Math.max(1, width - 2) + const name = this.gradient + ? this.palette.bold(gradientText('DEEPSEEK')) + : this.palette.bold(this.palette.accent('DEEPSEEK')) + const title = `${name} ${this.palette.bold('HARNESS')}` const model = displayText(this.currentModel() ?? 'model unset') const detail = `${model} • ${displayText(this.agent.session.id)}` - const top = this.palette.accent(`╭${'─'.repeat(Math.max(0, width - 2))}╮`) - const bottom = this.palette.accent(`╰${'─'.repeat(Math.max(0, width - 2))}╯`) - const lines = [title, this.palette.muted(displayText(this.subtitle())), this.palette.dim(detail)] + const subtitle = this.subtitle() + const lines = [ + title, + ...subtitle === undefined ? [] : [this.palette.muted(displayText(subtitle))], + this.palette.dim(detail), + ] .flatMap(line => wrapTextWithAnsi(line, usable)) - .map((line) => { - const clipped = truncateToWidth(line, usable, '') - return `${this.palette.accent('│')} ${clipped}${' '.repeat(Math.max(0, usable - visibleWidth(clipped)))} ${this.palette.accent('│')}` - }) - return [top, ...lines, bottom] + .map(line => ` ${truncateToWidth(line, usable, '')}`) + if (this.revealWidth === undefined) return lines + const revealed = this.revealWidth + return lines.map(line => truncateToWidth(line, revealed, '')) } } +/** Milliseconds between elapsed-time refreshes of the running status line. */ +const STATUS_ELAPSED_INTERVAL_MS = 1000 + +/** Steering/cancel affordance shown on every running status line. */ +const STATUS_HINT = 'Enter sends steering, Esc cancels' + +/** + * Fine-grained activity of a running turn, derived in the TUI from session + * lifecycle events for the status line. It is presentation-only, not a durable + * agent state: `waiting` spans a step from its `step/start` until the first + * reasoning or text chunk, `thinking`/`responding` track reasoning/text deltas, + * and `executing` covers tool calls until the next step begins. + */ +type TurnPhase = 'waiting' | 'thinking' | 'responding' | 'executing' + +/** + * Live controller for the running status line: its {@link Loader}, the derived + * {@link TurnPhase}, the elapsed-time baselines the label reads, and the timer + * that refreshes it. Present only while the turn runs; `undefined` when idle. + */ +interface RunningStatus { + loader: Loader + phase: TurnPhase + phaseStartedAt: number + stepStartedAt: number + timer: ReturnType<typeof setInterval> +} + +/** Status-line label for each {@link TurnPhase}. */ +const TURN_PHASE_LABELS: Record<TurnPhase, string> = { + waiting: 'Waiting for the first token', + thinking: 'Thinking', + responding: 'Responding', + executing: 'Executing tools', +} + +/** + * Format a non-negative elapsed span as a compact status duration: whole + * seconds under a minute (`8s`), else minutes and zero-padded seconds + * (`1m05s`). + * @param elapsedMs - Elapsed time in milliseconds; negatives clamp to zero. + * @returns The compact duration string. + */ +function formatStatusDuration(elapsedMs: number): string { + const total = Math.floor(Math.max(0, elapsedMs) / 1000) + if (total < 60) return `${total}s` + return `${Math.floor(total / 60)}m${(total % 60).toString().padStart(2, '0')}s` +} + +/** + * Compose the running status-line text from the current phase, its timers, and + * the queued-steering badge. The waiting phase spans the whole step so it shows + * one duration; later phases show time in the phase plus the running step + * total, and a non-zero `queued` count surfaces as a badge before the hint. + * @param phase - The current turn phase. + * @param phaseMs - Elapsed time in the current phase, in milliseconds. + * @param stepMs - Elapsed time in the current step, in milliseconds. + * @param queued - Count of pending steering messages; zero hides the badge. + * @returns The status-line text, including the steering/cancel hint. + */ +function formatTurnStatus(phase: TurnPhase, phaseMs: number, stepMs: number, queued: number): string { + const timing = phase === 'waiting' + ? formatStatusDuration(stepMs) + : `${formatStatusDuration(phaseMs)} · total ${formatStatusDuration(stepMs)}` + const badge = queued > 0 ? `${queued} queued · ` : '' + return `${TURN_PHASE_LABELS[phase]} ${timing} — ${badge}${STATUS_HINT}` +} + /** * Groups children behind a colored left-gutter bar (`▌`). Foreground-only, so * it renders legibly on any terminal background — unlike a filled block whose @@ -709,9 +884,16 @@ function formatCwd(cwd: string | undefined): string { return cwd } +/** + * Running token totals for the footer, keyed per turn/step so replayed or + * re-emitted usage replaces rather than double-counts; `input` is uncached + * input, cache buckets are disjoint. + */ interface SessionTokenTotals { input: number output: number + cacheRead: number + cacheWrite: number readonly byStep: Map<string, TokenUsage> } @@ -721,10 +903,14 @@ function recordTokenUsage(totals: SessionTokenTotals, turn: number, step: number if (previous !== undefined) { totals.input -= previous.inputTokens totals.output -= previous.outputTokens + totals.cacheRead -= previous.cacheReadTokens ?? 0 + totals.cacheWrite -= previous.cacheWriteTokens ?? 0 } totals.byStep.set(key, usage) totals.input += usage.inputTokens totals.output += usage.outputTokens + totals.cacheRead += usage.cacheReadTokens ?? 0 + totals.cacheWrite += usage.cacheWriteTokens ?? 0 } function recordEventUsage(totals: SessionTokenTotals, event: SessionEvent): void { @@ -735,60 +921,126 @@ function recordEventUsage(totals: SessionTokenTotals, event: SessionEvent): void } } +/** + * Share of billed input (prompt) tokens served from the provider cache, as an + * integer percent, or `undefined` before any input is billed (avoids 0/0 and a + * meaningless rate on an empty session). + */ +function cacheHitRate(totals: SessionTokenTotals): number | undefined { + const billedInput = totals.input + totals.cacheRead + totals.cacheWrite + if (billedInput === 0) return undefined + return Math.round((totals.cacheRead / billedInput) * 100) +} + function sessionTokens(session: Session): SessionTokenTotals { - const totals: SessionTokenTotals = { input: 0, output: 0, byStep: new Map() } + const totals: SessionTokenTotals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, byStep: new Map() } for (const event of session.events) { recordEventUsage(totals, event) } return totals } +function formatDiagnosticNumber(value: number): string { + return value.toLocaleString('en-US') +} + +function formatDiagnosticTime(value: number): string { + return new Date(value).toISOString().replace('T', ' ').replace(/\.\d{3}Z$/u, ' UTC') +} + +function formatDiagnosticCount(value: number, singular: string): string { + return `${String(value)} ${singular}${value === 1 ? '' : 's'}` +} + +function diagnosticMeter(percent: number, palette: Palette): string { + const width = 16 + const filled = Math.round(Math.min(100, Math.max(0, percent)) / 100 * width) + return `${palette.dim('[')}${palette.accent('█'.repeat(filled))}${palette.dim(`${'░'.repeat(width - filled)}]`)}` +} + +type StatusCardRow = readonly [label: string, value: string] + +/** Bordered, grouped field card for one point-in-time status snapshot. */ +class StatusCardComponent implements Component { + constructor( + private readonly groups: readonly (readonly StatusCardRow[])[], + private readonly palette: Palette, + ) {} + + invalidate(): void {} + + render(width: number): string[] { + const labels = this.groups.flatMap(group => group.map(([label]) => `${label}:`)) + const naturalLabelWidth = Math.max(...labels.map(label => label.length)) + const naturalBodyWidth = Math.max(...this.groups.flatMap(group => group.map(([, value]) => + 1 + naturalLabelWidth + 2 + visibleWidth(value)))) + const cardWidth = Math.min( + Math.max(8, width), + Math.max('Session status'.length + 5, naturalBodyWidth + 4), + ) + const innerWidth = Math.max(1, cardWidth - 4) + const labelWidth = Math.min( + naturalLabelWidth, + Math.max(1, Math.floor(innerWidth / 3)), + ) + const body: string[] = [] + for (const [groupIndex, group] of this.groups.entries()) { + 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 continuation = ' '.repeat(1 + labelWidth + 2) + const valueWidth = Math.max(1, innerWidth - visibleWidth(prefix)) + const wrapped = wrapTextWithAnsi(value, valueWidth) + for (const [lineIndex, line] of wrapped.entries()) { + body.push(`${lineIndex === 0 ? prefix : continuation}${line}`) + } + } + } + + const title = truncateToWidth('Session status', Math.max(1, cardWidth - 5), '') + const topTail = '─'.repeat(Math.max(0, cardWidth - visibleWidth(title) - 5)) + const top = `${this.palette.dim('╭─ ')}${this.palette.bold(this.palette.accent(title))}${this.palette.dim(` ${topTail}╮`)}` + const lines = [top] + for (const line of body) { + const clipped = truncateToWidth(line, innerWidth, '') + lines.push(`${this.palette.dim('│')} ${clipped}${' '.repeat(Math.max(0, innerWidth - visibleWidth(clipped)))} ${this.palette.dim('│')}`) + } + lines.push(this.palette.dim(`╰${'─'.repeat(Math.max(0, cardWidth - 2))}╯`)) + return lines + } +} + class FooterComponent implements Component { constructor( private readonly agent: Agent, private readonly palette: Palette, private readonly toolsExpanded: () => boolean, - private readonly showReasoning: () => boolean, - private readonly tokens: () => { input: number; output: number }, + private readonly tokens: () => SessionTokenTotals, private readonly cwdFormatter: TuiRuntime['formatCwd'], private readonly currentModel: () => string | undefined, private readonly contextPercent: () => number | undefined, - private readonly runningSeconds: () => number, ) {} invalidate(): void {} render(width: number): string[] { - if (this.agent.status === 'running') { - const interrupt = this.palette.dim('esc interrupt') - const activityAvailable = Math.max(0, width - visibleWidth(interrupt) - 1) - const activity = truncateToWidth(this.palette.accent(`◒ Working · ${this.runningSeconds()}s`), activityAvailable, '') - const gap = ' '.repeat(Math.max(0, width - visibleWidth(activity) - visibleWidth(interrupt))) - return [`${activity}${gap}${interrupt}`] - } - const { input, output } = this.tokens() - const counters = `↑${formatTokens(input)} ↓${formatTokens(output)}` + const totals = this.tokens() const model = displayText(this.currentModel() ?? 'model unset') - const modelState = `${model}(reasoning:${this.showReasoning() ? 'on' : 'off'})` - const contextPercent = this.contextPercent() - const context = contextPercent === undefined ? 'context unknown' : `${contextPercent}% context` - const fullRight = `${context} tools:${this.toolsExpanded() ? 'expanded' : 'compact'} ${modelState}` - const compactRight = `${context} ${modelState}` + const rate = cacheHitRate(totals) + const cache = rate === undefined ? '' : ` cache ${rate}%` const formattedCwd = displayText( this.cwdFormatter?.(this.agent.session.header.cwd) ?? formatCwd(this.agent.session.header.cwd), ) - if (visibleWidth(counters) + visibleWidth(compactRight) + 1 > width) { - const compact = truncateToWidth(compactRight, width, '') - return [`${' '.repeat(Math.max(0, width - visibleWidth(compact)))}${this.palette.dim(compact)}`] - } - const rightAvailable = width - visibleWidth(counters) - 1 - const right = visibleWidth(fullRight) <= rightAvailable ? fullRight : compactRight - const rightClipped = truncateToWidth(right, rightAvailable, '') - const cwdAvailable = Math.max(0, width - visibleWidth(counters) - visibleWidth(rightClipped) - 3) - const cwd = truncateToWidth(formattedCwd, cwdAvailable, '') - const left = [cwd, counters].filter(Boolean).join(' ') - const gap = ' '.repeat(Math.max(0, width - visibleWidth(left) - visibleWidth(rightClipped))) - return [`${this.palette.dim(left)}${gap}${this.palette.dim(rightClipped)}`] + const left = `${model} ${formattedCwd} ↑${formatTokens(totals.input)} ↓${formatTokens(totals.output)}${cache}` + const contextPercent = this.contextPercent() + const context = contextPercent === undefined ? '' : `${contextPercent}% context ` + const right = `${context}tools:${this.toolsExpanded() ? 'expanded' : 'collapsed'}` + const leftStyled = this.palette.dim(left) + const available = Math.max(0, width - visibleWidth(left) - 2) + const rightClipped = truncateToWidth(right, available, '') + const gap = ' '.repeat(Math.max(1, width - visibleWidth(left) - visibleWidth(rightClipped))) + return [truncateToWidth(`${leftStyled}${gap}${this.palette.dim(rightClipped)}`, width, '')] } } @@ -1026,6 +1278,65 @@ export interface TuiController { dispose(): Promise<void> } +/** Prefix that marks an editor submission as a manual skill invocation. */ +const SKILL_COMMAND_PREFIX = '/skill:' + +/** Parsed `/skill:<name> [instructions]` submission; `name` is empty when the prefix carries no name. */ +interface ParsedSkillCommand { + /** Skill name typed after `/skill:`, up to the first space. */ + name: string + /** Trimmed text after the name; empty when none was typed. */ + instructions: string +} + +/** + * Split a `/skill:<name> [instructions]` submission into its name and trailing instructions. + * @param text - trimmed submission that starts with {@link SKILL_COMMAND_PREFIX}. + * @returns the skill name and any trailing instructions. + */ +function parseSkillCommand(text: string): ParsedSkillCommand { + const rest = text.slice(SKILL_COMMAND_PREFIX.length) + const spaceIndex = rest.indexOf(' ') + if (spaceIndex === -1) return { name: rest, instructions: '' } + return { name: rest.slice(0, spaceIndex), instructions: rest.slice(spaceIndex + 1).trim() } +} + +/** Model-visible line locating a manually invoked skill's relative resources, or `undefined` when the provider has no base. */ +function skillResourceReference(base: SkillResourceBase | undefined): string | undefined { + if (base === undefined) return undefined + switch (base.kind) { + case 'directory': + return `References in this skill are relative to ${base.path}.` + case 'url': + return `References in this skill are relative to ${base.url}.` + case 'opaque': + return base.description + default: + return assertNever(base, 'SkillResourceBase.kind') + } +} + +/** + * Render a manually invoked skill into the model-visible user-message text. The + * `<skill>` block carries the body and, when the provider supplies one, its + * resource base; the trimmed `instructions` follow the block as the user's + * request for this turn. The name is registry-validated kebab-case + * ({@link SkillService} rejects any other) and the resource base is trusted + * same-process provider prose, so — unlike the model-facing `dsh-tool-skill` + * result, which escapes for a tool channel — this user turn is assembled raw. + * @param skill - the loaded skill definition. + * @param instructions - trimmed text typed after `/skill:<name>`; empty when absent. + * @returns the user-message text delivered to the agent. + */ +export function renderSkillInvocation(skill: SkillDefinition, instructions: string): string { + const lines = [`<skill name="${skill.name}">`] + const reference = skillResourceReference(skill.resourceBase) + if (reference !== undefined) lines.push(reference, '') + lines.push(skill.content, '</skill>') + const block = lines.join('\n') + return instructions === '' ? block : `${block}\n\n${instructions}` +} + function activeSurfaceSeqs(session: Session): Set<number> { return new Set(session.surface.nodes) } @@ -1056,12 +1367,14 @@ 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 resolved = resolveTuiConfig(config) const palette = createPalette(resolved.color) const mdTheme = markdownTheme(palette) const ui = new TUI(runtime.terminal, resolved.showHardwareCursor) const chat = new Container() const todoContainer = new Container() + const statusContainer = new Container() const editor = new Editor(ui, { borderColor: palette.dim, selectList: selectTheme(palette), @@ -1070,10 +1383,23 @@ export function createTuiChat( let showReasoning = resolved.showReasoning let toolsExpanded = false let streaming: StreamingAssistantComponent | undefined - let runningStartedAt: number | undefined - let statusTicker: ReturnType<typeof setInterval> | undefined + let runningStatus: RunningStatus | undefined + // Steering messages queued during the running turn (`agent/queued`) that the + // loop has not yet drained, shown as a badge on the status line. Each entry is + // the queued message's serialized source: a drain (`steering/message`) removes + // one MATCHING entry, so loop-authored steering — continuation reasons enter + // the inbox without an `agent/queued` event — cannot consume a pending user + // message's slot. Cleared on leaving `running`, which also absorbs a + // cancellation that discards the queue without logging drains; the status + // line exists only while running, so idle carries no badge to keep current. + const pendingSteering: string[] = [] let disposed = false let shuttingDown: Promise<void> | undefined + // Optional: skills mount conditionally, so read the global service store + // rather than declaring an injection that would make the TUI require them. + const skills = ctx.get('skills') + const cwd = agent.session.header.cwd ?? process.cwd() + const skillAbort = new AbortController() const tokens = sessionTokens(agent.session) const toolCards = new Map<string, ToolCardComponent>() const allToolCards = new Set<ToolCardComponent>() @@ -1091,24 +1417,30 @@ export function createTuiChat( let modelCommands = Promise.resolve() const now = (): number => runtime.now?.() ?? Date.now() - const welcome = config.welcome ?? 'ready.' + // A configured subtitle renders as a banner line; when absent, the banner has + // no subtitle. The banner itself sweeps in on start (see startBannerReveal). let sessionTitle = foldSessionTitle(agent.session.events)?.title - const header = new HeaderComponent(agent, () => sessionTitle ?? welcome, palette, () => target.current?.model) + const header = new HeaderComponent( + agent, + () => sessionTitle ?? config.welcome, + palette, + resolved.color && resolved.truecolor, + () => target.current?.model, + ) const footer = new FooterComponent( agent, palette, () => toolsExpanded, - () => showReasoning, () => tokens, runtime.formatCwd, () => target.current?.model, () => contextWindow === undefined ? undefined : Math.min(100, Math.round(ctx.tokenMeter.measure(agent.session).totalTokens / contextWindow * 100)), - () => runningStartedAt === undefined ? 0 : Math.max(0, Math.floor((now() - runningStartedAt) / 1_000)), ) ui.addChild(header) ui.addChild(chat) + ui.addChild(statusContainer) todoContainer.addChild(todo) ui.addChild(todoContainer) ui.addChild(editor) @@ -1244,24 +1576,95 @@ export function createTuiChat( } const clearStatus = (): void => { - if (statusTicker !== undefined) clearInterval(statusTicker) - statusTicker = undefined - runningStartedAt = undefined + if (runningStatus !== undefined) { + clearInterval(runningStatus.timer) + runningStatus.loader.stop() + runningStatus = undefined + } + statusContainer.clear() runtime.terminal.setProgress(false) } + // Refresh the status line's elapsed timers and queued badge from the + // controller's phase and the current steering count. + const renderStatus = (running: RunningStatus): void => { + const at = now() + running.loader.setMessage( + formatTurnStatus(running.phase, at - running.phaseStartedAt, at - running.stepStartedAt, pendingSteering.length), + ) + } + + // Move to a derived phase, resetting the phase timer on a genuine change and + // the step timer when a new step begins; ignored unless a turn is running. + const enterPhase = (phase: TurnPhase, resetStep: boolean): void => { + const running = runningStatus + if (running === undefined) return + const at = now() + if (resetStep) running.stepStartedAt = at + if (phase !== running.phase || resetStep) running.phaseStartedAt = at + running.phase = phase + renderStatus(running) + } + const setStatus = (status: AgentStatus): void => { + // A running→running rebuild (a mid-turn palette swap re-derives the border) + // carries the derived phase and both elapsed baselines across; only a fresh + // idle→running turn starts at `waiting`. + const prior = runningStatus clearStatus() editor.borderColor = status === 'running' ? text => palette.accent(text) : text => palette.dim(text) if (status === 'running') { - runningStartedAt = now() - statusTicker = setInterval(requestRender, 1_000) - statusTicker.unref() + const at = now() + const phase = prior?.phase ?? 'waiting' + const phaseStartedAt = prior?.phaseStartedAt ?? at + const stepStartedAt = prior?.stepStartedAt ?? at + const message = formatTurnStatus(phase, at - phaseStartedAt, at - stepStartedAt, pendingSteering.length) + const loader = new Loader(ui, text => palette.accent(text), text => palette.muted(text), message) + statusContainer.addChild(loader) + const running: RunningStatus = { + loader, + phase, + phaseStartedAt, + stepStartedAt, + timer: setInterval(() => { renderStatus(running) }, STATUS_ELAPSED_INTERVAL_MS), + } + runningStatus = running runtime.terminal.setProgress(true) } requestRender() } + // Refresh the running status line's queued-steering badge from the current + // count; a no-op when idle because the controller only exists while running. + const refreshStatus = (): void => { + if (runningStatus !== undefined) renderStatus(runningStatus) + requestRender() + } + + // Derive the status-line phase from live session lifecycle events. The event + // map is merge-extensible, so unhandled types fall through the default. + const advanceTurnPhase = (event: SessionEvent): void => { + switch (event.type) { + case 'step/start': + enterPhase('waiting', true) + break + case 'assistant/chunk': { + const chunk = event.data.chunk + if (chunk.type === 'reasoning-delta' || (chunk.type === 'block-start' && chunk.blockType === 'reasoning')) { + enterPhase('thinking', false) + } else if (chunk.type === 'text-delta' || (chunk.type === 'block-start' && chunk.blockType === 'text')) { + enterPhase('responding', false) + } + break + } + case 'tool/call': + enterPhase('executing', false) + break + default: + break + } + } + const parsedTool = (event: Extract<SessionEvent, { type: 'tool/call' }>): ToolCardComponent => { const parsed = parseArguments(event.data.arguments) const card = new ToolCardComponent( @@ -1495,6 +1898,38 @@ export function createTuiChat( }, }) + /** + * 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) + .sort((a, b) => b.createdAt - a.createdAt) + } + + /** + * The resume command for the current session — the configured template with + * every `{session}` filled — but only once the session is durably persisted, + * so a session abandoned before its first flush yields no hint (resuming that + * id would fail to load). + */ + const 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) + } + const shutdown = (exitProcess: boolean): Promise<void> => { shuttingDown ??= (async () => { disposed = true @@ -1513,7 +1948,13 @@ export function createTuiChat( disposeUserInteraction() await runtime.terminal.drainInput(100, 20) ui.stop() - if (exitProcess) runtime.exit(0) + if (exitProcess) { + const command = await currentResumeCommand() + if (command !== undefined) { + runtime.terminal.write(`${palette.muted('To resume this session:')} ${displayText(command)}\n`) + } + runtime.exit(0) + } })() return shuttingDown } @@ -1534,6 +1975,7 @@ export function createTuiChat( currentScheme = scheme Object.assign(palette, createPalette(resolved.color, scheme)) Object.assign(mdTheme, markdownTheme(palette)) + // `setStatus` below re-derives `editor.borderColor` from the new palette. rebuildTranscript(false) setStatus(agent.status) requestRender() @@ -1583,22 +2025,99 @@ export function createTuiChat( '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'), 1, 0)) requestRender() } + const showStatus = (): void => { + const events = agent.session.events + const latestActivity = events.at(-1)?.time ?? agent.session.header.createdAt + const usedContext = Math.max(0, Math.round(ctx.tokenMeter.measure(agent.session).totalTokens)) + let context = `${formatDiagnosticNumber(usedContext)} used · capacity unknown` + if (contextWindow !== undefined) { + const contextPercent = Math.round(usedContext / contextWindow * 100) + context = `${diagnosticMeter(contextPercent, palette)} ${String(contextPercent)}% used (${formatDiagnosticNumber(usedContext)} / ${formatDiagnosticNumber(contextWindow)})` + } + const rate = cacheHitRate(tokens) + const turns = events.filter(event => event.type === 'turn/start').length + const steps = events.filter(event => event.type === 'step/start').length + const toolCalls = events.filter(event => event.type === 'tool/call').length + const model = target.current === undefined ? 'unset' : displayText(targetLabel(target.current)) + const groups: readonly (readonly StatusCardRow[])[] = [ + [ + ['Session', displayText(agent.session.id)], + ['Title', displayText(sessionTitle ?? 'untitled')], + ['Directory', displayText(cwd)], + ['Model', `${model} ${palette.dim(`(reasoning ${showReasoning ? 'shown' : 'hidden'})`)}`], + ], + [ + ['Agent', [ + agent.status, + formatDiagnosticCount(events.length, 'event'), + formatDiagnosticCount(turns, 'turn'), + formatDiagnosticCount(steps, 'step'), + formatDiagnosticCount(toolCalls, 'tool call'), + ].join(' · ')], + ], + [ + ['Tokens', `${formatDiagnosticNumber(tokens.input)} input + ${formatDiagnosticNumber(tokens.output)} output`], + ['KV cache', rate === undefined + ? `n/a (${formatDiagnosticNumber(tokens.cacheRead)} read + ${formatDiagnosticNumber(tokens.cacheWrite)} write)` + : `${diagnosticMeter(rate, palette)} ${String(rate)}% hit (${formatDiagnosticNumber(tokens.cacheRead)} read + ${formatDiagnosticNumber(tokens.cacheWrite)} write)`], + ['Context', context], + ], + [ + ['Created', formatDiagnosticTime(agent.session.header.createdAt)], + ['Active', formatDiagnosticTime(latestActivity)], + ], + ] + const card = new StatusCardComponent(groups, palette) + chat.addChild(new Spacer(1)) + chat.addChild(card) + requestRender() + } + + // Skill listing is async while `createTuiChat` is synchronous, so the + // completions rebuild once the catalog resolves. Disabled-for-model skills + // are absent from `list()`, so they never appear as completions; a user can + // still invoke one by typing its exact name. + let skillCommands: SlashCommand[] = [] const refreshCommandAutocomplete = (): void => { editor.setAutocompleteProvider(new CombinedAutocompleteProvider( - ctx.commands.list(agent).map(command => ({ - name: command.name, - description: command.description, - })), + [ + ...ctx.commands.list(agent).map(command => ({ + name: command.name, + description: command.description, + })), + ...skillCommands, + ], agent.session.header.cwd ?? process.cwd(), )) } const disposeCommandChanges = ctx.on('commands/change', refreshCommandAutocomplete) refreshCommandAutocomplete() + const loadSkillCommands = (service: SkillService): void => { + service.list({ cwd, signal: skillAbort.signal }).then( + (summaries) => { + if (disposed || summaries.length === 0) return + skillCommands = summaries.map(skill => ({ + name: `skill:${skill.name}`, + description: skill.description, + argumentHint: '[instructions]', + })) + refreshCommandAutocomplete() + requestRender() + }, + () => { + // Discovery failed or was aborted on dispose; keep the base slash + // commands so autocomplete still works without skill entries. + }, + ) + } + if (skills !== undefined) loadSkillCommands(skills) + // The agent scope is minted by agent-loop and intentionally inherits only // that core plugin's dependencies. A child command producer declares its own // UI-service dependency while retaining the parent agent scope and lifetime. @@ -1622,15 +2141,6 @@ export function createTuiChat( description: 'Clear the transcript view (session history is unchanged)', handler: () => { chat.clear(); requestRender(); return { kind: 'success' } }, }) - commandCtx.commands.register({ - name: 'cancel', - description: 'Cancel the active turn', - handler: () => { - if (agent.status !== 'running') return { kind: 'error', text: 'The agent is already idle.' } - agent.cancel({ kind: 'user' }) - return { kind: 'success', text: 'Cancellation requested.' } - }, - }) commandCtx.commands.register({ name: 'reasoning', description: 'Toggle reasoning blocks', @@ -1646,6 +2156,21 @@ export function createTuiChat( description: 'Invalidate components and redraw the terminal', handler: () => { ui.invalidate(); ui.requestRender(true); return { kind: 'success' } }, }) + commandCtx.commands.register({ + name: 'reload', + description: 'EXPERIMENTAL (dev): re-read loader config files and apply the diff (idle only)', + handler: () => { runReload(); return { kind: 'success' } }, + }) + commandCtx.commands.register({ + name: 'resume', + description: 'List this workspace\'s resumable sessions', + handler: () => { showResume(); return { kind: 'success' } }, + }) + commandCtx.commands.register({ + name: 'status', + description: 'Show detailed session diagnostics', + handler: () => { showStatus(); return { kind: 'success' } }, + }) commandCtx.commands.register({ name: 'exit', description: 'Exit after the active turn reaches idle', @@ -1673,22 +2198,140 @@ export function createTuiChat( ).finally(() => { commandControllers.delete(controller) }) } + /** Deliver a user turn to the agent: steer while running, send while idle, or report a disposed agent. */ + const deliver = (payload: string): void => { + if (agent.status === 'disposed') { + appendNotice(`Agent "${agent.id}" is disposed.`, 'error') + } else if (agent.status === 'running') { + agent.steer([{ type: 'text', text: payload }]) + } else { + agent.send([{ type: 'text', text: payload }]) + } + } + + /** Load a manually invoked skill and deliver its rendered body as a user turn, reporting lookup outcomes as notices. */ + const invokeSkill = (name: string, instructions: string): void => { + if (skills === undefined) { + appendNotice('Skills are not available in this session.', 'warning') + return + } + skills.get(name, { cwd, signal: skillAbort.signal }).then( + (skill) => { + if (disposed) return + if (skill === undefined) { + appendNotice(`Unknown skill: ${name}`, 'warning') + return + } + deliver(renderSkillInvocation(skill, instructions)) + }, + (error: unknown) => { + if (disposed) return + appendNotice(`Skill "${name}" failed to load: ${errorChain(error)}`, 'error') + }, + ) + } + + // EXPERIMENTAL, dev-only: manually re-read every file-backed loader config + // tree and apply the diff to the running app — the same path the HMR + // watcher's config-change branch drives, minus the watcher. Useful when the + // watcher misses an edit (replace-by-rename saves) or HMR is not mounted. + // Module-source hot reload stays watcher-owned; this refreshes configs only. + let reloadInFlight = false + const runReload = (): void => { + // Idle-only: a reload can dispose and re-mount entries mid-flight; doing + // that under an active turn could tear tools or the adapter out from + // under in-flight calls. Idleness is advisory (a send can race in after + // the check), but it removes the common footgun. + if (agent.status !== 'idle') { + appendNotice(`/reload requires an idle agent (status: ${agent.status}).`, 'warning') + return + } + // Re-entrancy guard: concurrent refreshes over a genuinely changed file + // would race unmutexed tree updates (create/remove interleaving); one + // reload at a time keeps the update pass single-writer. + if (reloadInFlight) { + appendNotice('A config reload is already running.', 'warning') + return + } + + // Optional-service lookup: the TUI must not depend on the Loader (tests + // and embedders run without one), so `loader` stays out of `inject` and + // is read through the non-throwing `ctx.get` accessor — a bare `ctx.loader` + // proxy read would throw `cannot get property without inject` in a fiber. + const loader = ctx.get('loader') as { entries(): Iterable<{ subtree?: { refresh?(): Promise<void> } }> } | undefined + if (loader === undefined) { + appendNotice('/reload needs the cordis Loader; this runtime has none.', 'warning') + return + } + const refreshes: Promise<void>[] = [] + for (const entry of loader.entries()) { + if (entry.subtree?.refresh !== undefined) refreshes.push(entry.subtree.refresh()) + } + reloadInFlight = true + appendNotice(`Reloading ${refreshes.length} config tree(s)… (experimental)`) + // refresh() never rejects (it warns and keeps the running tree), so the + // join can only fulfill; the catch arm guards a future contract change. + void Promise.all(refreshes).then(() => { + appendNotice('Config reload complete. Unchanged files were skipped; invalid files keep the running tree (see logs).') + }).catch((error: unknown) => { + appendNotice(`Config reload failed: ${errorChain(error)}`, 'error') + }).finally(() => { + reloadInFlight = false + }) + } + + /** + * List this workspace's resumable sessions, newest first, each with its + * resume command and a marker on the current one. Warns when resume is not + * configured or no persistence backend is mounted; notes when nothing is + * persisted yet. The listing is asynchronous (a persistence scan), so the + * transcript updates once it resolves. + */ + const showResume = (): void => { + const template = config.resumeCommand + if (template === undefined) { + appendNotice('Resume is not configured for this app.', 'warning') + return + } + if (persistence === undefined) { + appendNotice('Resume is not available: no persistence backend is mounted.', 'warning') + return + } + void listWorkspaceSessions().then((sessions) => { + if (sessions.length === 0) { + appendNotice('No resumable sessions found for this workspace yet.', 'info') + return + } + chat.addChild(new Spacer(1)) + chat.addChild(new Text(palette.bold(palette.accent('Resumable sessions')), 1, 0)) + const lines = sessions.map((header) => { + const when = new Date(header.createdAt).toISOString().slice(0, 16).replace('T', ' ') + const marker = header.id === agent.session.id ? palette.success(' (current)') : '' + return `${palette.muted(when)}${marker}\n ${displayText(template.replaceAll('{session}', header.id))}` + }) + chat.addChild(new Text(lines.join('\n'), 1, 0)) + requestRender() + }) + } + editor.onSubmit = (value: string) => { const text = value.trim() if (text === '') return editor.addToHistory(text) editor.setText('') + // `/skill:<name>` carries a colon, which the command registry's name + // grammar rejects, so it is intercepted before generic command routing. + if (text.startsWith(SKILL_COMMAND_PREFIX)) { + const { name, instructions } = parseSkillCommand(text) + if (name === '') appendNotice('Usage: /skill:<name> [instructions]', 'warning') + else invokeSkill(name, instructions) + return + } if (value.startsWith('/')) { runCommand(value) return } - if (agent.status === 'disposed') { - appendNotice(`Agent "${agent.id}" is disposed.`, 'error') - } else if (agent.status === 'running') { - agent.steer([{ type: 'text', text }]) - } else { - agent.send([{ type: 'text', text }]) - } + deliver(text) } const removeInputListener = ui.addInputListener((data) => { @@ -1731,6 +2374,18 @@ export function createTuiChat( const disposeSessionEvents = ctx.on('session/event', (session, event) => { if (session !== agent.session) return recordEventUsage(tokens, event) + advanceTurnPhase(event) + if (event.type === 'steering/message') { + // A queued steering message reached the model as it drained; drop its + // entry from the badge. Matching by source keeps loop-authored steering + // (e.g. continuation reasons), which logs here without a matching + // `agent/queued` increment, from consuming a pending user slot. + const drained = pendingSteering.indexOf(JSON.stringify(event.data.source)) + if (drained >= 0) { + pendingSteering.splice(drained, 1) + refreshStatus() + } + } if ('surfaceOp' in event && typeof event.surfaceOp === 'object') { rebuildTranscript(false) return @@ -1738,8 +2393,17 @@ export function createTuiChat( renderEvent(event, { addHistory: false, renderChunks: true }) requestRender() }) + const disposeQueued = ctx.on('agent/queued', (subject, _content, info) => { + if (subject !== agent || !info.steering) return + pendingSteering.push(JSON.stringify(info.source)) + refreshStatus() + }) const disposeStatus = ctx.on('agent/status', (subject, status) => { if (subject !== agent) return + // Leaving 'running' ends the turn's status line; clear any badge so the + // next running turn starts from zero (and a cancellation, which discards + // the queue without logging drains, cannot strand a stale count). + if (status !== 'running') pendingSteering.length = 0 setStatus(status) }) const disposeError = ctx.on('agent/error', (subject, turn, step, error) => { @@ -1756,9 +2420,12 @@ export function createTuiChat( }) const detachListeners = (): void => { + skillAbort.abort() removeInputListener() disposeCommandChanges() + stopBannerReveal() disposeSessionEvents() + disposeQueued() disposeStatus() disposeError() disposeAgent() @@ -1766,6 +2433,34 @@ export function createTuiChat( disposeTargetListeners() } + // Sweep reveal of the whole banner: the header wipes in left-to-right over + // ~BANNER_REVEAL_STEPS frames (started after `ui.start()` succeeds). + // Configured subtitles skip it so deployments (and snapshot fixtures) stay + // frame-deterministic. + let revealTimer: ReturnType<typeof setInterval> | undefined + const stopBannerReveal = (): void => { + if (revealTimer === undefined) return + clearInterval(revealTimer) + revealTimer = undefined + header.setRevealWidth(undefined) + } + const startBannerReveal = (): void => { + if (config.welcome !== undefined) return + const total = Math.max(1, runtime.terminal.columns) + const step = Math.max(1, Math.ceil(total / BANNER_REVEAL_STEPS)) + let shown = 0 + header.setRevealWidth(0) + revealTimer = setInterval(() => { + shown += step + if (shown >= total) { + stopBannerReveal() + } else { + header.setRevealWidth(shown) + } + requestRender() + }, BANNER_REVEAL_INTERVAL_MS) + } + rebuildTranscript(true) setStatus(agent.status) try { @@ -1784,6 +2479,7 @@ export function createTuiChat( ui.stop() throw error } + startBannerReveal() return { async dispose(): Promise<void> { @@ -1839,9 +2535,12 @@ export function mountTui(ctx: Context, config: Config, runtime: TuiRuntime): voi and the tui-agent PTY smoke covers the real entry */ export function apply(ctx: Context, config: Config): void { if (!process.stdin.isTTY || !process.stdout.isTTY) { - throw new Error('ui-tui: both stdin and stdout must be TTYs; use @deepseek-ai/dsh-cli-demo for non-interactive runs') + throw new Error('ui-tui: both stdin and stdout must be TTYs; use the one-shot @deepseek-ai/dsh-cli-demo app for pipes') } - mountTui(ctx, config, { + // Truecolor is a terminal capability, so detect it here at the process + // boundary from COLORTERM; an explicit `truecolor` config value still wins. + const truecolor = config.truecolor ?? ['truecolor', '24bit'].includes(process.env.COLORTERM ?? '') + mountTui(ctx, Object.assign({}, config, { truecolor }), { terminal: new ProcessTerminal(), exit: code => process.exit(code), }) diff --git a/packages/ui/tui/tests/harness.ts b/packages/ui/tui/tests/harness.ts index 1109895c3b..97db25b7ae 100644 --- a/packages/ui/tui/tests/harness.ts +++ b/packages/ui/tui/tests/harness.ts @@ -8,7 +8,7 @@ import AgentRegistry, { } from '@deepseek-ai/dsh-agent' import type { ContentBlock, LlmModelContext, LlmModelInfo, LlmProviderInfo } from '@deepseek-ai/dsh-llm' import CommandService from '@deepseek-ai/dsh-commands' -import SessionStore, { SessionId, type Session } from '@deepseek-ai/dsh-session' +import SessionStore, { SessionId, type Session, type SessionHeader } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import UserInteractionService from '@deepseek-ai/dsh-user-interaction' @@ -24,11 +24,16 @@ interface FakeAgent extends Agent { export interface TuiHarnessOptions { status?: AgentStatus config?: Config + /** Leave the session event log empty instead of seeding one turn and step. */ + omitInitialLifecycle?: boolean + /** Omit the harness's default `welcome`, exercising the banner sweep-reveal path. */ + omitWelcome?: boolean tools?: Record<string, ToolDefinition> configureContext?: (ctx: Context) => Promise<void> beforeMount?: (session: Session) => void cwd?: string | null formatCwd?: TuiRuntime['formatCwd'] + /** Fake-agent creation options (`provider`/`model` seed the model selector's initial target). */ agentOptions?: AgentOptions contextWindow?: number contextTokens?: number @@ -39,6 +44,8 @@ export interface TuiHarnessOptions { listModels?: (provider: string) => Promise<LlmModelInfo[]> resolveModelContext?: (provider: string, model: string) => Promise<LlmModelContext | undefined> } + /** Provide a fake `sessionPersistence` service so resume surfaces can list sessions. */ + sessionPersistence?: { list(): Promise<SessionHeader[]> } } export interface TuiHarness<TerminalType extends Terminal, Exit extends (code: number) => void> { @@ -74,19 +81,6 @@ export async function createTuiTestHarness<TerminalType extends Terminal, Exit e { provider: 'deepseek', id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' }, ], } - ctx.provide('llm', { - listProviders() { - return catalog.providers.map(provider => ({ ...provider })) - }, - listModels(provider: string) { - return catalog.listModels?.(provider) - ?? Promise.resolve(catalog.models.filter(model => model.provider === provider).map(model => ({ ...model }))) - }, - resolveModelContext(provider: string, model: string) { - return catalog.resolveModelContext?.(provider, model) - ?? Promise.resolve({ contextWindow: options.contextWindow ?? 128_000 }) - }, - } as never) ctx.provide('tokenMeter', { measure() { return { totalTokens: options.contextTokens ?? 0 } @@ -102,17 +96,39 @@ export async function createTuiTestHarness<TerminalType extends Terminal, Exit e } else { await options.configureContext(ctx) } + // A configureContext may mount the real LlmService; only fill the + // advisory-catalog stub when none was provided. + if (ctx.get('llm') === undefined) { + ctx.provide('llm', { + listProviders() { + return catalog.providers.map(provider => ({ ...provider })) + }, + listModels(provider: string) { + return catalog.listModels?.(provider) + ?? Promise.resolve(catalog.models.filter(model => model.provider === provider).map(model => ({ ...model }))) + }, + resolveModelContext(provider: string, model: string) { + return catalog.resolveModelContext?.(provider, model) + ?? Promise.resolve({ contextWindow: options.contextWindow ?? 128_000 }) + }, + } as never) + } if (ctx.get('systemPrompt') === undefined) await ctx.plugin(SystemPrompt) + if (options.sessionPersistence !== undefined) { + ctx.provide('sessionPersistence', options.sessionPersistence as never) + } const sessionId = SessionId('main-session') const session = ctx.sessions.create( sessionId, options.cwd === null ? undefined : { meta: { cwd: options.cwd ?? '/workspace' } }, ) - session.append('turn/start', { - turn: 1, - trigger: { kind: 'message', source: { kind: 'user' } }, - }) - session.append('step/start', { turn: 1, step: 1 }) + if (options.omitInitialLifecycle !== true) { + session.append('turn/start', { + turn: 1, + trigger: { kind: 'message', source: { kind: 'user' } }, + }) + session.append('step/start', { turn: 1, step: 1 }) + } options.beforeMount?.(session) const sent: ContentBlock[][] = [] const steered: ContentBlock[][] = [] @@ -142,13 +158,16 @@ export async function createTuiTestHarness<TerminalType extends Terminal, Exit e } ctx.agents.register(agent) const controller = createTuiChat(ctx, Object.assign({ - welcome: 'Coding agent ready.', + ...options.omitWelcome === true ? {} : { welcome: 'Coding agent ready.' }, sessionId, color: false, }, options.config), { terminal, exit, - now: options.now ?? (() => 0), + // Default to the real clock (runtime.now falls back to Date.now) so the + // elapsed-status suites can drive time via timers or Date.now spies; a + // test pins the clock only by passing `now` explicitly. + ...(options.now === undefined ? {} : { now: options.now }), ...(options.formatCwd === undefined ? {} : { formatCwd: options.formatCwd }), }) return { ctx, session, agent, terminal, exit, controller } @@ -174,7 +193,7 @@ export function appendUser(session: Session, text: string): void { export function appendAssistant( session: Session, content: ContentBlock[], - usage?: { inputTokens: number; outputTokens: number }, + usage?: { inputTokens: number; outputTokens: number; cacheReadTokens?: number; cacheWriteTokens?: number }, position: { turn: number; step: number } = { turn: 1, step: 1 }, ): void { session.append('assistant/message', { diff --git a/packages/ui/tui/tests/snapshots/advanced-cards-collapsed.expected.txt b/packages/ui/tui/tests/snapshots/advanced-cards-collapsed.expected.txt index b2c5547b3f..0e3c73750a 100644 --- a/packages/ui/tui/tests/snapshots/advanced-cards-collapsed.expected.txt +++ b/packages/ui/tui/tests/snapshots/advanced-cards-collapsed.expected.txt @@ -1,108 +1,99 @@ -terminal 100x40 buffer=normal length=41 base=1 viewport=1 +terminal 100x40 buffer=normal length=40 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=37 bufferRow=38 +cursor hidden column=1 viewportRow=36 bufferRow=36 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=green -7| "▌ ✓ pnpm run test:coverage " +5| "▌ ✓ pnpm run test:coverage " style 0-0 fg=green style 2-2 fg=green bold style 3-25 bold -8| "▌ Run the coverage gate " +6| "▌ Run the coverage gate " style 0-0 fg=green style 2-22 fg=bright-black -9| "▌ /workspace/project " +7| "▌ /workspace/project " style 0-0 fg=green style 2-19 dim -10| "▌ … +4 lines (Ctrl+O to expand) " +8| "▌ … +4 lines (Ctrl+O to expand) " style 0-0 fg=green style 2-30 dim -11| "▌ [exit 0] " +9| "▌ [exit 0] " style 0-0 fg=green style 2-9 dim +10| "▌ " + style 0-0 fg=green +11| <blank> 12| "▌ " style 0-0 fg=green -13| <blank> -14| "▌ " - style 0-0 fg=green -15| "▌ ✓ Edit renderer " +13| "▌ ✓ Edit renderer " style 0-0 fg=green style 2-2 fg=green bold style 3-16 bold -16| "▌ src/view.ts " +14| "▌ src/view.ts " style 0-0 fg=green style 2-12 bold -17| "▌ - old line " +15| "▌ - old line " style 0-0 fg=green style 2-11 fg=red -18| "▌ … +5 lines (Ctrl+O to expand) " +16| "▌ … +5 lines (Ctrl+O to expand) " style 0-0 fg=green style 2-30 dim -19| "▌ + expect(screen).toMatchSnapshot() " +17| "▌ + expect(screen).toMatchSnapshot() " style 0-0 fg=green style 2-35 fg=green +18| "▌ " + style 0-0 fg=green +19| <blank> 20| "▌ " style 0-0 fg=green -21| <blank> -22| "▌ " - style 0-0 fg=green -23| "▌ ✓ Delegate renderer audit " +21| "▌ ✓ Delegate renderer audit " style 0-0 fg=green style 2-2 fg=green bold style 3-26 bold -24| "▌ The renderer has explicit lifecycle ownership. " +22| "▌ The renderer has explicit lifecycle ownership. " style 0-0 fg=green +23| "▌ " + style 0-0 fg=green +24| <blank> 25| "▌ " style 0-0 fg=green -26| <blank> -27| "▌ " - style 0-0 fg=green -28| "▌ ✓ Read output from background task subagent-7 " +26| "▌ ✓ Read output from background task subagent-7 " style 0-0 fg=green style 2-2 fg=green bold style 3-46 bold -29| "▌ audit complete " +27| "▌ audit complete " style 0-0 fg=green -30| "▌ [status: completed] " +28| "▌ [status: completed] " style 0-0 fg=green +29| "▌ " + style 0-0 fg=green +30| <blank> 31| "▌ " style 0-0 fg=green -32| <blank> -33| "▌ " - style 0-0 fg=green -34| "▌ ✓ Load skill dsh-code-review " +32| "▌ ✓ Load skill dsh-code-review " style 0-0 fg=green style 2-2 fg=green bold style 3-29 bold -35| "▌ Loaded review instructions. " +33| "▌ Loaded review instructions. " style 0-0 fg=green -36| "▌ " +34| "▌ " style 0-0 fg=green +35| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +36| " " + style 1-1 inverse 37| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -38| " " - style 1-1 inverse -39| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -40| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 42-99 dim +38| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 73-99 dim +39| <blank> diff --git a/packages/ui/tui/tests/snapshots/advanced-cards-expanded.expected.txt b/packages/ui/tui/tests/snapshots/advanced-cards-expanded.expected.txt index 0f93629223..2321eff61d 100644 --- a/packages/ui/tui/tests/snapshots/advanced-cards-expanded.expected.txt +++ b/packages/ui/tui/tests/snapshots/advanced-cards-expanded.expected.txt @@ -1,127 +1,117 @@ -terminal 100x40 buffer=normal length=50 base=10 viewport=10 +terminal 100x40 buffer=normal length=48 base=8 viewport=8 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=37 bufferRow=47 +cursor hidden column=1 viewportRow=37 bufferRow=45 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=green -7| "▌ ✓ pnpm run test:coverage " +5| "▌ ✓ pnpm run test:coverage " style 0-0 fg=green style 2-2 fg=green bold style 3-25 bold -8| "▌ Run the coverage gate " +6| "▌ Run the coverage gate " style 0-0 fg=green style 2-22 fg=bright-black -9| "▌ /workspace/project " +7| "▌ /workspace/project " style 0-0 fg=green style 2-19 dim -10| "▌ packages/ui/tui 100% " +8| "▌ packages/ui/tui 100% " style 0-0 fg=green -11| "▌ 4016 tests passed " +9| "▌ 4016 tests passed " style 0-0 fg=green -12| "▌ 1 test skipped " +10| "▌ 1 test skipped " style 0-0 fg=green -13| "▌ coverage complete " +11| "▌ coverage complete " style 0-0 fg=green -14| "▌ [exit 0] " +12| "▌ [exit 0] " style 0-0 fg=green style 2-9 dim +13| "▌ " + style 0-0 fg=green +14| <blank> 15| "▌ " style 0-0 fg=green -16| <blank> -17| "▌ " - style 0-0 fg=green -18| "▌ ✓ Edit renderer " +16| "▌ ✓ Edit renderer " style 0-0 fg=green style 2-2 fg=green bold style 3-16 bold -19| "▌ src/view.ts " +17| "▌ src/view.ts " style 0-0 fg=green style 2-12 bold -20| "▌ - old line " +18| "▌ - old line " style 0-0 fg=green style 2-11 fg=red -21| "▌ - keep " +19| "▌ - keep " style 0-0 fg=green style 2-7 fg=red -22| "▌ + new line " +20| "▌ + new line " style 0-0 fg=green style 2-11 fg=green -23| "▌ + keep " +21| "▌ + keep " style 0-0 fg=green style 2-7 fg=green -24| "▌ " +22| "▌ " style 0-0 fg=green -25| "▌ tests/view.spec.ts " +23| "▌ tests/view.spec.ts " style 0-0 fg=green style 2-19 bold -26| "▌ + expect(screen).toMatchSnapshot() " +24| "▌ + expect(screen).toMatchSnapshot() " style 0-0 fg=green style 2-35 fg=green +25| "▌ " + style 0-0 fg=green +26| <blank> 27| "▌ " style 0-0 fg=green -28| <blank> -29| "▌ " - style 0-0 fg=green -30| "▌ ✓ Delegate renderer audit " +28| "▌ ✓ Delegate renderer audit " style 0-0 fg=green style 2-2 fg=green bold style 3-26 bold -31| "▌ The renderer has explicit lifecycle ownership. " +29| "▌ The renderer has explicit lifecycle ownership. " style 0-0 fg=green +30| "▌ " + style 0-0 fg=green +31| <blank> 32| "▌ " style 0-0 fg=green -33| <blank> -34| "▌ " - style 0-0 fg=green -35| "▌ ✓ Read output from background task subagent-7 " +33| "▌ ✓ Read output from background task subagent-7 " style 0-0 fg=green style 2-2 fg=green bold style 3-46 bold -36| "▌ audit complete " +34| "▌ audit complete " style 0-0 fg=green -37| "▌ [status: completed] " +35| "▌ [status: completed] " style 0-0 fg=green +36| "▌ " + style 0-0 fg=green +37| <blank> 38| "▌ " style 0-0 fg=green -39| <blank> -40| "▌ " - style 0-0 fg=green -41| "▌ ✓ Load skill dsh-code-review " +39| "▌ ✓ Load skill dsh-code-review " style 0-0 fg=green style 2-2 fg=green bold style 3-29 bold -42| "▌ Loaded review instructions. " +40| "▌ Loaded review instructions. " style 0-0 fg=green -43| "▌ " +41| "▌ " style 0-0 fg=green -44| <blank> -45| " Tool cards expanded. " +42| <blank> +43| " Tool cards expanded. " style 1-20 fg=bright-black +44| "────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-99 dim +45| " " + style 1-1 inverse 46| "────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-99 dim -47| " " - style 1-1 inverse -48| "────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-99 dim -49| "/workspace/project ↑0 ↓0 0% context tools:expanded deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 41-99 dim +47| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:expanded" + style 0-43 dim + style 74-99 dim diff --git a/packages/ui/tui/tests/snapshots/banner-gradient.expected.txt b/packages/ui/tui/tests/snapshots/banner-gradient.expected.txt new file mode 100644 index 0000000000..59d1377702 --- /dev/null +++ b/packages/ui/tui/tests/snapshots/banner-gradient.expected.txt @@ -0,0 +1,29 @@ +terminal 96x36 buffer=normal length=36 base=0 viewport=0 +lifecycle started=1 stopped=0 progress=inactive +title "DSH snapshot" +cursor hidden column=1 viewportRow=4 bufferRow=4 +viewport +0| " DEEPSEEK HARNESS" + style 1-1 fg=#4d6bfe bold + style 2-2 fg=#4772fe bold + style 3-3 fg=#4278ff bold + style 4-4 fg=#3c7fff bold + style 5-5 fg=#3685ff bold + style 6-6 fg=#308bff bold + style 7-7 fg=#2a92ff bold + style 8-8 fg=#2498ff bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +4| " " + style 1-1 inverse +5| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +6| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim +7-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/code-mode-pending.expected.txt b/packages/ui/tui/tests/snapshots/code-mode-pending.expected.txt index f52c197d51..2bfeb79449 100644 --- a/packages/ui/tui/tests/snapshots/code-mode-pending.expected.txt +++ b/packages/ui/tui/tests/snapshots/code-mode-pending.expected.txt @@ -1,52 +1,42 @@ terminal 96x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=15 bufferRow=15 +cursor hidden column=1 viewportRow=13 bufferRow=13 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-95 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 95-95 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 95-95 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 95-95 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-95 fg=bright-blue -5| <blank> -6| "▌ " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=yellow -7| "▌ ◌ const first = await tools.bash({ command: 'echo CODE_ONE' }) " +5| "▌ ◌ const first = await tools.bash({ command: 'echo CODE_ONE' }) " style 0-0 fg=yellow style 2-2 fg=yellow bold style 3-95 bold -8| "▌ const second = await tools.bas " +6| "▌ const second = await tools.bas " style 0-0 fg=yellow style 2-31 bold -9| "▌ const first = await tools.bash({ command: 'echo CODE_ONE' }) " +7| "▌ const first = await tools.bash({ command: 'echo CODE_ONE' }) " style 0-0 fg=yellow -10| "▌ const second = await tools.bash({ command: 'echo CODE_TWO' }) " +8| "▌ const second = await tools.bash({ command: 'echo CODE_TWO' }) " style 0-0 fg=yellow -11| "▌ console.log(first, second) " +9| "▌ console.log(first, second) " style 0-0 fg=yellow -12| "▌ return `${first}+${second}` " +10| "▌ return `${first}+${second}` " style 0-0 fg=yellow -13| "▌ " +11| "▌ " style 0-0 fg=yellow +12| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +13| " " + style 1-1 inverse 14| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 dim -15| " " - style 1-1 inverse -16| "────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-95 dim -17| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 38-95 dim -18-35| <blank> +15| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim +16-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/conversation-streaming.expected.txt b/packages/ui/tui/tests/snapshots/conversation-streaming.expected.txt index 3b84636ca8..52e003eea0 100644 --- a/packages/ui/tui/tests/snapshots/conversation-streaming.expected.txt +++ b/packages/ui/tui/tests/snapshots/conversation-streaming.expected.txt @@ -3,50 +3,44 @@ lifecycle started=1 stopped=0 progress=active title "DSH snapshot" cursor hidden column=1 viewportRow=17 bufferRow=17 viewport -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-95 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 95-95 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 95-95 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 95-95 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-95 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Show the live update. " +6| "▌ Show the live update. " style 0-0 fg=bright-blue -9| "▌ " +7| "▌ " style 0-0 fg=bright-blue -10| <blank> -11| " Reasoning " +8| <blank> +9| " Reasoning " style 1-9 fg=bright-black italic -12| " Inspecting width and styles. " +10| " Inspecting width and styles. " style 1-28 fg=bright-black italic -13| <blank> -14| " Assistant " +11| <blank> +12| " Assistant " style 1-9 fg=bright-magenta bold -15| " Streaming visible state… " +13| " Streaming visible state… " style 11-23 bold +14| <blank> +15| " ⠋ Responding 0s · total 0s — Enter sends steering, Esc cancels " + style 1-1 fg=bright-blue + style 3-62 fg=bright-black 16| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 fg=bright-blue 17| " " style 1-1 inverse 18| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 fg=bright-blue -19| "◒ Working · 0s esc interrupt" - style 0-13 fg=bright-blue - style 83-95 dim +19| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim 20-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/cordis-tools-pending.expected.txt b/packages/ui/tui/tests/snapshots/cordis-tools-pending.expected.txt index 01022fee8c..47c225008d 100644 --- a/packages/ui/tui/tests/snapshots/cordis-tools-pending.expected.txt +++ b/packages/ui/tui/tests/snapshots/cordis-tools-pending.expected.txt @@ -1,59 +1,49 @@ terminal 96x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=18 bufferRow=18 +cursor hidden column=1 viewportRow=16 bufferRow=16 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-95 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 95-95 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 95-95 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 95-95 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-95 fg=bright-blue -5| <blank> -6| "▌ ◌ Inspect cordis runtime: tools " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ ◌ Inspect cordis runtime: tools " style 0-0 fg=yellow style 2-2 fg=yellow bold style 3-32 bold -7| <blank> -8| "▌ " +5| <blank> +6| "▌ " style 0-0 fg=yellow -9| "▌ ◌ Mount plugin into live cordis runtime " +7| "▌ ◌ Mount plugin into live cordis runtime " style 0-0 fg=yellow style 2-2 fg=yellow bold style 3-40 bold -10| "▌ { " +8| "▌ { " style 0-0 fg=yellow -11| "▌ \"code\": \"return { name: 'snapshot-marker', apply(ctx) { ctx.provide('snapshotMarker', { " +9| "▌ \"code\": \"return { name: 'snapshot-marker', apply(ctx) { ctx.provide('snapshotMarker', { " style 0-0 fg=yellow -12| "▌ ready: true }) } }\" " +10| "▌ ready: true }) } }\" " style 0-0 fg=yellow -13| "▌ } " +11| "▌ } " style 0-0 fg=yellow -14| "▌ " +12| "▌ " style 0-0 fg=yellow -15| <blank> -16| "▌ ◌ Unmount dyn-1 " +13| <blank> +14| "▌ ◌ Unmount dyn-1 " style 0-0 fg=yellow style 2-2 fg=yellow bold style 3-16 bold +15| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +16| " " + style 1-1 inverse 17| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 dim -18| " " - style 1-1 inverse -19| "────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-95 dim -20| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 38-95 dim -21-35| <blank> +18| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim +19-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/disposed-terminal.expected.txt b/packages/ui/tui/tests/snapshots/disposed-terminal.expected.txt index 4aff2c9065..b6fb49135b 100644 --- a/packages/ui/tui/tests/snapshots/disposed-terminal.expected.txt +++ b/packages/ui/tui/tests/snapshots/disposed-terminal.expected.txt @@ -1,67 +1,63 @@ terminal 92x32 buffer=normal length=32 base=0 viewport=0 lifecycle started=1 stopped=1 progress=inactive title "DSH snapshot" -cursor visible column=0 viewportRow=30 bufferRow=30 +cursor visible column=0 viewportRow=31 bufferRow=31 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-91 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 91-91 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 91-91 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 91-91 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-91 fg=bright-blue -5| <blank> -6| " Keyboard shortcuts " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| " Keyboard shortcuts " style 1-18 fg=bright-blue bold -7| " Enter send • Shift/Alt+Enter newline • Up/Down prompt history " +5| " Enter send • Shift/Alt+Enter newline • Up/Down prompt history " style 1-61 fg=bright-black -8| " Esc cancel active turn • Ctrl+O toggle tool cards • Ctrl+R toggle reasoning " +6| " Esc cancel active turn • Ctrl+O toggle tool cards • Ctrl+R toggle reasoning " style 1-75 fg=bright-black -9| " Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit " +7| " Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit " style 1-73 fg=bright-black -10| " " -11| " /cancel — Cancel the active turn " - style 1-32 fg=bright-black -12| " /clear — Clear the transcript view (session history is unchanged) " +8| " " +9| " /clear — Clear the transcript view (session history is unchanged) " style 1-65 fg=bright-black -13| " /exit — Exit after the active turn reaches idle " +10| " /exit — Exit after the active turn reaches idle " style 1-47 fg=bright-black -14| " /help — Show keyboard shortcuts and commands " +11| " /help — Show keyboard shortcuts and commands " style 1-44 fg=bright-black -15| " /model [[provider/]model] — Show or switch this session's model " +12| " /model [[provider/]model] — Show or switch this session's model " style 1-63 fg=bright-black -16| " /reasoning — Toggle reasoning blocks " +13| " /reasoning — Toggle reasoning blocks " style 1-36 fg=bright-black -17| " /redraw — Invalidate components and redraw the terminal " +14| " /redraw — Invalidate components and redraw the terminal " style 1-55 fg=bright-black +15| " /reload — EXPERIMENTAL (dev): re-read loader config files and apply the diff (idle only) " + style 1-88 fg=bright-black +16| " /resume — List this workspace's resumable sessions " + style 1-50 fg=bright-black +17| " /status — Show detailed session diagnostics " + style 1-43 fg=bright-black 18| " /tools — Expand or collapse all tool cards " style 1-42 fg=bright-black -19| <blank> -20| " provider stream failed after partial output " +19| " /skill:<name> [instructions] — load a skill into the conversation " + style 1-65 fg=bright-black +20| <blank> +21| " provider stream failed after partial output " style 1-43 fg=red -21| <blank> -22| " The previous process ended during this turn. " +22| <blank> +23| " The previous process ended during this turn. " style 1-44 fg=yellow -23| <blank> -24| " Unknown command: /unknown-advanced-command " +24| <blank> +25| " Unknown command: /unknown-advanced-command " style 1-42 fg=yellow -25| "────────────────────────────────────────────────────────────────────────────────────────────" +26| "────────────────────────────────────────────────────────────────────────────────────────────" style 0-91 dim -26| " " +27| " " style 1-1 inverse -27| "────────────────────────────────────────────────────────────────────────────────────────────" +28| "────────────────────────────────────────────────────────────────────────────────────────────" style 0-91 dim -28| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 34-91 dim -29-31| <blank> +29| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 65-91 dim +30-31| <blank> diff --git a/packages/ui/tui/tests/snapshots/dynamic-workflow-pending.expected.txt b/packages/ui/tui/tests/snapshots/dynamic-workflow-pending.expected.txt index 31af6ce523..ace55782e9 100644 --- a/packages/ui/tui/tests/snapshots/dynamic-workflow-pending.expected.txt +++ b/packages/ui/tui/tests/snapshots/dynamic-workflow-pending.expected.txt @@ -1,56 +1,46 @@ terminal 96x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=17 bufferRow=17 +cursor hidden column=1 viewportRow=15 bufferRow=15 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-95 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 95-95 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 95-95 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 95-95 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-95 fg=bright-blue -5| <blank> -6| "▌ " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=yellow -7| "▌ ◌ workflow: tui-matrix " +5| "▌ ◌ workflow: tui-matrix " style 0-0 fg=yellow style 2-2 fg=yellow bold style 3-23 bold -8| "▌ phase('Inspect') " +6| "▌ phase('Inspect') " style 0-0 fg=yellow -9| "▌ const reports = await parallel([ " +7| "▌ const reports = await parallel([ " style 0-0 fg=yellow -10| "▌ () => agent('Audit layout', { label: 'layout', phase: 'Inspect' }), " +8| "▌ () => agent('Audit layout', { label: 'layout', phase: 'Inspect' }), " style 0-0 fg=yellow -11| "▌ … +1 lines (Ctrl+O to expand) " +9| "▌ … +1 lines (Ctrl+O to expand) " style 0-0 fg=yellow style 2-30 dim -12| "▌ ]) " +10| "▌ ]) " style 0-0 fg=yellow -13| "▌ phase('Verify') " +11| "▌ phase('Verify') " style 0-0 fg=yellow -14| "▌ return { reports, verdict: 'covered' } " +12| "▌ return { reports, verdict: 'covered' } " style 0-0 fg=yellow -15| "▌ " +13| "▌ " style 0-0 fg=yellow +14| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +15| " " + style 1-1 inverse 16| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 dim -17| " " - style 1-1 inverse -18| "────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-95 dim -19| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 38-95 dim -20-35| <blank> +17| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim +18-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/errors-and-help.expected.txt b/packages/ui/tui/tests/snapshots/errors-and-help.expected.txt index a01a0cb413..05c35e32e1 100644 --- a/packages/ui/tui/tests/snapshots/errors-and-help.expected.txt +++ b/packages/ui/tui/tests/snapshots/errors-and-help.expected.txt @@ -1,67 +1,63 @@ terminal 92x32 buffer=normal length=32 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=26 bufferRow=26 +cursor hidden column=1 viewportRow=27 bufferRow=27 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-91 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 91-91 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 91-91 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 91-91 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-91 fg=bright-blue -5| <blank> -6| " Keyboard shortcuts " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| " Keyboard shortcuts " style 1-18 fg=bright-blue bold -7| " Enter send • Shift/Alt+Enter newline • Up/Down prompt history " +5| " Enter send • Shift/Alt+Enter newline • Up/Down prompt history " style 1-61 fg=bright-black -8| " Esc cancel active turn • Ctrl+O toggle tool cards • Ctrl+R toggle reasoning " +6| " Esc cancel active turn • Ctrl+O toggle tool cards • Ctrl+R toggle reasoning " style 1-75 fg=bright-black -9| " Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit " +7| " Ctrl+C cancel while running; clear input or exit while idle • Ctrl+D exit " style 1-73 fg=bright-black -10| " " -11| " /cancel — Cancel the active turn " - style 1-32 fg=bright-black -12| " /clear — Clear the transcript view (session history is unchanged) " +8| " " +9| " /clear — Clear the transcript view (session history is unchanged) " style 1-65 fg=bright-black -13| " /exit — Exit after the active turn reaches idle " +10| " /exit — Exit after the active turn reaches idle " style 1-47 fg=bright-black -14| " /help — Show keyboard shortcuts and commands " +11| " /help — Show keyboard shortcuts and commands " style 1-44 fg=bright-black -15| " /model [[provider/]model] — Show or switch this session's model " +12| " /model [[provider/]model] — Show or switch this session's model " style 1-63 fg=bright-black -16| " /reasoning — Toggle reasoning blocks " +13| " /reasoning — Toggle reasoning blocks " style 1-36 fg=bright-black -17| " /redraw — Invalidate components and redraw the terminal " +14| " /redraw — Invalidate components and redraw the terminal " style 1-55 fg=bright-black +15| " /reload — EXPERIMENTAL (dev): re-read loader config files and apply the diff (idle only) " + style 1-88 fg=bright-black +16| " /resume — List this workspace's resumable sessions " + style 1-50 fg=bright-black +17| " /status — Show detailed session diagnostics " + style 1-43 fg=bright-black 18| " /tools — Expand or collapse all tool cards " style 1-42 fg=bright-black -19| <blank> -20| " provider stream failed after partial output " +19| " /skill:<name> [instructions] — load a skill into the conversation " + style 1-65 fg=bright-black +20| <blank> +21| " provider stream failed after partial output " style 1-43 fg=red -21| <blank> -22| " The previous process ended during this turn. " +22| <blank> +23| " The previous process ended during this turn. " style 1-44 fg=yellow -23| <blank> -24| " Unknown command: /unknown-advanced-command " +24| <blank> +25| " Unknown command: /unknown-advanced-command " style 1-42 fg=yellow -25| "────────────────────────────────────────────────────────────────────────────────────────────" +26| "────────────────────────────────────────────────────────────────────────────────────────────" style 0-91 dim -26| " " +27| " " style 1-1 inverse -27| "────────────────────────────────────────────────────────────────────────────────────────────" +28| "────────────────────────────────────────────────────────────────────────────────────────────" style 0-91 dim -28| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 34-91 dim -29-31| <blank> +29| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 65-91 dim +30-31| <blank> diff --git a/packages/ui/tui/tests/snapshots/model-selector.expected.txt b/packages/ui/tui/tests/snapshots/model-selector.expected.txt index 4bd9dcbbbc..f10c99d03a 100644 --- a/packages/ui/tui/tests/snapshots/model-selector.expected.txt +++ b/packages/ui/tui/tests/snapshots/model-selector.expected.txt @@ -3,33 +3,23 @@ lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" cursor hidden column=0 viewportRow=31 bufferRow=31 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-91 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 91-91 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 91-91 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 91-91 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-91 fg=bright-blue +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| "────────────────────────────────────────────────────────────────────────────────────────────" + style 0-91 dim +4| " " + style 1-1 inverse 5| "────────────────────────────────────────────────────────────────────────────────────────────" style 0-91 dim -6| " " - style 1-1 inverse -7| "────────────────────────────────────────────────────────────────────────────────────────────" - style 0-91 dim -8| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 34-91 dim -9-12| <blank> +6| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 65-91 dim +7-12| <blank> 13| " ╭ Select model ────────────────────────────────────────────────────────╮ " style 10-81 fg=bright-blue 14| " │ → deepseek/deepseek-v4-flash DeepSeek V4 Flash — current │ " diff --git a/packages/ui/tui/tests/snapshots/model-switching.expected.txt b/packages/ui/tui/tests/snapshots/model-switching.expected.txt index 7027c435db..5800901f08 100644 --- a/packages/ui/tui/tests/snapshots/model-switching.expected.txt +++ b/packages/ui/tui/tests/snapshots/model-switching.expected.txt @@ -1,35 +1,25 @@ terminal 92x32 buffer=normal length=32 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=8 bufferRow=8 +cursor hidden column=1 viewportRow=6 bufferRow=6 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-91 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 91-91 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 91-91 fg=bright-blue -3| "│ deepseek-v4-pro • main-session │" - style 0-0 fg=bright-blue - style 2-33 dim - style 91-91 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-91 fg=bright-blue -5| <blank> -6| " Model selected: deepseek/deepseek-v4-pro. New steps will use it. " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-pro • main-session" + style 1-32 dim +3| <blank> +4| " Model selected: deepseek/deepseek-v4-pro. New steps will use it. " style 1-64 fg=bright-black +5| "────────────────────────────────────────────────────────────────────────────────────────────" + style 0-91 dim +6| " " + style 1-1 inverse 7| "────────────────────────────────────────────────────────────────────────────────────────────" style 0-91 dim -8| " " - style 1-1 inverse -9| "────────────────────────────────────────────────────────────────────────────────────────────" - style 0-91 dim -10| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-pro(reasoning:on)" - style 0-24 dim - style 36-91 dim -11-31| <blank> +8| "deepseek-v4-pro /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-41 dim + style 65-91 dim +9-31| <blank> diff --git a/packages/ui/tui/tests/snapshots/question-dialog-validation.expected.txt b/packages/ui/tui/tests/snapshots/question-dialog-validation.expected.txt index 44bbecdd2a..4e17a0e652 100644 --- a/packages/ui/tui/tests/snapshots/question-dialog-validation.expected.txt +++ b/packages/ui/tui/tests/snapshots/question-dialog-validation.expected.txt @@ -3,23 +3,17 @@ lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" cursor hidden column=56 viewportRow=17 bufferRow=17 viewport -0| "╭──────────────────────────────────────────────────────╮" - style 0-55 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 55-55 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 55-55 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 55-55 fg=bright-blue -4| "╰──────────────────────────────────────────────────────╯" - style 0-55 fg=bright-blue +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| "────────────────────────────────────────────────────────" + style 0-55 dim +4| " " + style 1-1 inverse 5| " " 6| " Question 1/3 (3 unanswered) · Coverage " style 2-39 fg=bright-black diff --git a/packages/ui/tui/tests/snapshots/question-dialog.expected.txt b/packages/ui/tui/tests/snapshots/question-dialog.expected.txt index a761c2a3ab..220f5dc1c7 100644 --- a/packages/ui/tui/tests/snapshots/question-dialog.expected.txt +++ b/packages/ui/tui/tests/snapshots/question-dialog.expected.txt @@ -3,27 +3,22 @@ lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" cursor hidden column=0 viewportRow=19 bufferRow=19 viewport -0| "╭──────────────────────────────────────────────────────╮" - style 0-55 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 55-55 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 55-55 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 55-55 fg=bright-blue -4| "╰──────────────────────────────────────────────────────╯" - style 0-55 fg=bright-blue +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| "────────────────────────────────────────────────────────" + style 0-55 dim +4| " " + style 1-1 inverse 5| "────────────────────────────────────────────────────────" style 0-55 dim -6| " " - style 1-1 inverse +6| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context" + style 0-43 dim + style 46-55 dim 7| " " 8| " Question 1/3 (3 unanswered) · Coverage " style 2-39 fg=bright-black diff --git a/packages/ui/tui/tests/snapshots/resume-sessions.expected.txt b/packages/ui/tui/tests/snapshots/resume-sessions.expected.txt new file mode 100644 index 0000000000..7711b71636 --- /dev/null +++ b/packages/ui/tui/tests/snapshots/resume-sessions.expected.txt @@ -0,0 +1,32 @@ +terminal 92x32 buffer=normal length=32 base=0 viewport=0 +lifecycle started=1 stopped=0 progress=inactive +title "DSH snapshot" +cursor hidden column=1 viewportRow=10 bufferRow=10 +buffer +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| " Resumable sessions " + style 1-18 fg=bright-blue bold +5| " 2024-01-02 03:04 (current) " + style 1-16 fg=bright-black + style 17-26 fg=green +6| " RESUME_SESSION_ID=main-session dsh " +7| " 2024-01-01 00:00 " + style 1-16 fg=bright-black +8| " RESUME_SESSION_ID=earlier-session dsh " +9| "────────────────────────────────────────────────────────────────────────────────────────────" + style 0-91 dim +10| " " + style 1-1 inverse +11| "────────────────────────────────────────────────────────────────────────────────────────────" + style 0-91 dim +12| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 65-91 dim +13-31| <blank> diff --git a/packages/ui/tui/tests/snapshots/retry-cancelled.expected.txt b/packages/ui/tui/tests/snapshots/retry-cancelled.expected.txt index 2e6de69775..accef4fffc 100644 --- a/packages/ui/tui/tests/snapshots/retry-cancelled.expected.txt +++ b/packages/ui/tui/tests/snapshots/retry-cancelled.expected.txt @@ -1,48 +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=1 viewportRow=15 bufferRow=15 +cursor hidden column=1 viewportRow=13 bufferRow=13 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-95 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 95-95 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 95-95 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 95-95 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-95 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Start then cancel. " +6| "▌ Start then cancel. " style 0-0 fg=bright-blue -9| "▌ " +7| "▌ " style 0-0 fg=bright-blue -10| <blank> -11| " Retrying model request (1/2) in 1000ms: temporary transport failure " +8| <blank> +9| " Retrying model request (1/2) in 1000ms: temporary transport failure " style 1-67 fg=yellow -12| <blank> -13| " Turn cancelled. " +10| <blank> +11| " Turn cancelled. " style 1-15 fg=yellow +12| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +13| " " + style 1-1 inverse 14| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 dim -15| " " - style 1-1 inverse -16| "────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-95 dim -17| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 38-95 dim -18-35| <blank> +15| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim +16-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/retry-exhausted.expected.txt b/packages/ui/tui/tests/snapshots/retry-exhausted.expected.txt index c3be43370f..1b038d5a83 100644 --- a/packages/ui/tui/tests/snapshots/retry-exhausted.expected.txt +++ b/packages/ui/tui/tests/snapshots/retry-exhausted.expected.txt @@ -1,45 +1,35 @@ terminal 96x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=13 bufferRow=13 +cursor hidden column=1 viewportRow=11 bufferRow=11 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-95 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 95-95 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 95-95 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 95-95 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-95 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Let the bounded policy exhaust. " +6| "▌ Let the bounded policy exhaust. " style 0-0 fg=bright-blue -9| "▌ " +7| "▌ " style 0-0 fg=bright-blue -10| <blank> -11| " provider still unavailable " +8| <blank> +9| " provider still unavailable " style 1-26 fg=red +10| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +11| " " + style 1-1 inverse 12| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 dim -13| " " - style 1-1 inverse -14| "────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-95 dim -15| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 38-95 dim -16-35| <blank> +13| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim +14-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/retry-recovered.expected.txt b/packages/ui/tui/tests/snapshots/retry-recovered.expected.txt index e23e6aa6c7..c0ae86361c 100644 --- a/packages/ui/tui/tests/snapshots/retry-recovered.expected.txt +++ b/packages/ui/tui/tests/snapshots/retry-recovered.expected.txt @@ -1,49 +1,39 @@ terminal 96x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=16 bufferRow=16 +cursor hidden column=1 viewportRow=14 bufferRow=14 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-95 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 95-95 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 95-95 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 95-95 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-95 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Recover this request. " +6| "▌ Recover this request. " style 0-0 fg=bright-blue -9| "▌ " +7| "▌ " style 0-0 fg=bright-blue -10| <blank> -11| " Retrying model request (1/2) in 500ms: provider rate limit " +8| <blank> +9| " Retrying model request (1/2) in 500ms: provider rate limit " style 1-58 fg=yellow -12| <blank> -13| " Assistant " +10| <blank> +11| " Assistant " style 1-9 fg=bright-magenta bold -14| " Recovered on the next bounded attempt. " +12| " Recovered on the next bounded attempt. " +13| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +14| " " + style 1-1 inverse 15| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 dim -16| " " - style 1-1 inverse -17| "────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-95 dim -18| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 38-95 dim -19-35| <blank> +16| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim +17-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/retry-scheduled.expected.txt b/packages/ui/tui/tests/snapshots/retry-scheduled.expected.txt index 07f73cff2a..16dee8242a 100644 --- a/packages/ui/tui/tests/snapshots/retry-scheduled.expected.txt +++ b/packages/ui/tui/tests/snapshots/retry-scheduled.expected.txt @@ -1,45 +1,35 @@ terminal 96x36 buffer=normal length=36 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=13 bufferRow=13 +cursor hidden column=1 viewportRow=11 bufferRow=11 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-95 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 95-95 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 95-95 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 95-95 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-95 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Recover this request. " +6| "▌ Recover this request. " style 0-0 fg=bright-blue -9| "▌ " +7| "▌ " style 0-0 fg=bright-blue -10| <blank> -11| " Retrying model request (1/2) in 500ms: provider rate limit " +8| <blank> +9| " Retrying model request (1/2) in 500ms: provider rate limit " style 1-58 fg=yellow +10| "────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-95 dim +11| " " + style 1-1 inverse 12| "────────────────────────────────────────────────────────────────────────────────────────────────" style 0-95 dim -13| " " - style 1-1 inverse -14| "────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-95 dim -15| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 38-95 dim -16-35| <blank> +13| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 69-95 dim +14-35| <blank> diff --git a/packages/ui/tui/tests/snapshots/status-diagnostics-narrow.expected.txt b/packages/ui/tui/tests/snapshots/status-diagnostics-narrow.expected.txt new file mode 100644 index 0000000000..de46d59543 --- /dev/null +++ b/packages/ui/tui/tests/snapshots/status-diagnostics-narrow.expected.txt @@ -0,0 +1,110 @@ +terminal 56x36 buffer=normal length=36 base=0 viewport=0 +lifecycle started=1 stopped=0 progress=inactive +title "Inspect session diagnostics — DSH snapshot" +cursor hidden column=1 viewportRow=32 bufferRow=32 +buffer +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Inspect session diagnostics" + style 1-27 fg=bright-black +2| " deepseek-v4-pro • main-session" + style 1-32 dim +3| <blank> +4| "▌ " + style 0-0 fg=bright-blue +5| "▌ You " + style 0-0 fg=bright-blue + style 2-4 fg=bright-blue bold +6| "▌ inspect this session " + style 0-0 fg=bright-blue +7| "▌ " + style 0-0 fg=bright-blue +8| <blank> +9| " Assistant " + style 1-9 fg=bright-magenta bold +10| " Session inspected. " +11| <blank> +12| "╭─ Session status ─────────────────────────────────────╮" + style 0-2 dim + style 3-16 fg=bright-blue bold + style 17-55 dim +13| "│ Session: main-session │" + style 0-0 dim + style 3-12 fg=bright-black + style 55-55 dim +14| "│ Title: Inspect session diagnostics │" + style 0-0 dim + style 3-12 fg=bright-black + style 55-55 dim +15| "│ Directory: /workspace/project │" + style 0-0 dim + style 3-12 fg=bright-black + style 55-55 dim +16| "│ Model: deepseek/deepseek-v4-pro (reasoning │" + style 0-0 dim + style 3-12 fg=bright-black + style 40-55 dim +17| "│ shown) │" + style 0-0 dim + style 15-20 dim + style 55-55 dim +18| "│ │" + style 0-0 dim + style 55-55 dim +19| "│ Agent: idle · 6 events · 1 turn · 1 step · 1 │" + style 0-0 dim + style 3-12 fg=bright-black + style 55-55 dim +20| "│ tool call │" + style 0-0 dim + style 55-55 dim +21| "│ │" + style 0-0 dim + style 55-55 dim +22| "│ Tokens: 1,250 input + 340 output │" + style 0-0 dim + style 3-12 fg=bright-black + style 55-55 dim +23| "│ KV cache: [███████████░░░░░] 67% hit (3,000 read │" + style 0-0 dim + style 3-12 fg=bright-black + style 15-15 dim + style 16-26 fg=bright-blue + style 27-32 dim + style 55-55 dim +24| "│ + 250 write) │" + style 0-0 dim + style 55-55 dim +25| "│ Context: [█████░░░░░░░░░░░] 33% used (42,000 / │" + style 0-0 dim + style 3-12 fg=bright-black + style 15-15 dim + style 16-20 fg=bright-blue + style 21-32 dim + style 55-55 dim +26| "│ 128,000) │" + style 0-0 dim + style 55-55 dim +27| "│ │" + style 0-0 dim + style 55-55 dim +28| "│ Created: 2026-07-22 09:10:11 UTC │" + style 0-0 dim + style 3-12 fg=bright-black + style 55-55 dim +29| "│ Active: 2026-07-22 09:10:11 UTC │" + style 0-0 dim + style 3-12 fg=bright-black + style 55-55 dim +30| "╰──────────────────────────────────────────────────────╯" + style 0-55 dim +31| "────────────────────────────────────────────────────────" + style 0-55 dim +32| " " + style 1-1 inverse +33| "────────────────────────────────────────────────────────" + style 0-55 dim +34| "deepseek-v4-pro /workspace/project ↑1.3k ↓340 cache 6" + style 0-55 dim +35| <blank> diff --git a/packages/ui/tui/tests/snapshots/status-diagnostics.expected.txt b/packages/ui/tui/tests/snapshots/status-diagnostics.expected.txt new file mode 100644 index 0000000000..73d98953f6 --- /dev/null +++ b/packages/ui/tui/tests/snapshots/status-diagnostics.expected.txt @@ -0,0 +1,99 @@ +terminal 92x32 buffer=normal length=32 base=0 viewport=0 +lifecycle started=1 stopped=0 progress=inactive +title "Inspect session diagnostics — DSH snapshot" +cursor hidden column=1 viewportRow=28 bufferRow=28 +buffer +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Inspect session diagnostics" + style 1-27 fg=bright-black +2| " deepseek-v4-pro • main-session" + style 1-32 dim +3| <blank> +4| "▌ " + style 0-0 fg=bright-blue +5| "▌ You " + style 0-0 fg=bright-blue + style 2-4 fg=bright-blue bold +6| "▌ inspect this session " + style 0-0 fg=bright-blue +7| "▌ " + style 0-0 fg=bright-blue +8| <blank> +9| " Assistant " + style 1-9 fg=bright-magenta bold +10| " Session inspected. " +11| <blank> +12| "╭─ Session status ─────────────────────────────────────────────────╮" + style 0-2 dim + style 3-16 fg=bright-blue bold + style 17-67 dim +13| "│ Session: main-session │" + style 0-0 dim + style 3-12 fg=bright-black + style 67-67 dim +14| "│ Title: Inspect session diagnostics │" + style 0-0 dim + style 3-12 fg=bright-black + style 67-67 dim +15| "│ Directory: /workspace/project │" + style 0-0 dim + style 3-12 fg=bright-black + style 67-67 dim +16| "│ Model: deepseek/deepseek-v4-pro (reasoning shown) │" + style 0-0 dim + style 3-12 fg=bright-black + style 40-56 dim + style 67-67 dim +17| "│ │" + style 0-0 dim + style 67-67 dim +18| "│ Agent: idle · 6 events · 1 turn · 1 step · 1 tool call │" + style 0-0 dim + style 3-12 fg=bright-black + style 67-67 dim +19| "│ │" + style 0-0 dim + style 67-67 dim +20| "│ Tokens: 1,250 input + 340 output │" + style 0-0 dim + style 3-12 fg=bright-black + style 67-67 dim +21| "│ KV cache: [███████████░░░░░] 67% hit (3,000 read + 250 write) │" + style 0-0 dim + style 3-12 fg=bright-black + style 15-15 dim + style 16-26 fg=bright-blue + style 27-32 dim + style 67-67 dim +22| "│ Context: [█████░░░░░░░░░░░] 33% used (42,000 / 128,000) │" + style 0-0 dim + style 3-12 fg=bright-black + style 15-15 dim + style 16-20 fg=bright-blue + style 21-32 dim + style 67-67 dim +23| "│ │" + style 0-0 dim + style 67-67 dim +24| "│ Created: 2026-07-22 09:10:11 UTC │" + style 0-0 dim + style 3-12 fg=bright-black + style 67-67 dim +25| "│ Active: 2026-07-22 09:10:11 UTC │" + style 0-0 dim + style 3-12 fg=bright-black + style 67-67 dim +26| "╰──────────────────────────────────────────────────────────────────╯" + style 0-67 dim +27| "────────────────────────────────────────────────────────────────────────────────────────────" + style 0-91 dim +28| " " + style 1-1 inverse +29| "────────────────────────────────────────────────────────────────────────────────────────────" + style 0-91 dim +30| "deepseek-v4-pro /workspace/project ↑1.3k ↓340 cache 67% 33% context tools:collapsed" + style 0-57 dim + style 64-91 dim +31| <blank> diff --git a/packages/ui/tui/tests/snapshots/surface-after-compaction-narrow.expected.txt b/packages/ui/tui/tests/snapshots/surface-after-compaction-narrow.expected.txt index 28794f6d7f..cb629bbccd 100644 --- a/packages/ui/tui/tests/snapshots/surface-after-compaction-narrow.expected.txt +++ b/packages/ui/tui/tests/snapshots/surface-after-compaction-narrow.expected.txt @@ -1,40 +1,30 @@ terminal 44x18 buffer=normal length=18 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=11 bufferRow=11 +cursor hidden column=1 viewportRow=9 bufferRow=9 buffer -0| "╭──────────────────────────────────────────╮" - style 0-43 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 43-43 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 43-43 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 43-43 fg=bright-blue -4| "╰──────────────────────────────────────────╯" - style 0-43 fg=bright-blue -5| <blank> -6| " Context · compact " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| " Context · compact " style 1-17 dim -7| " Compacted summary: the prior command " +5| " Compacted summary: the prior command " style 1-43 fg=bright-black -8| " completed and its details were retired " +6| " completed and its details were retired " style 1-43 fg=bright-black -9| " from the active surface. " +7| " from the active surface. " style 1-24 fg=bright-black +8| "────────────────────────────────────────────" + style 0-43 dim +9| " " + style 1-1 inverse 10| "────────────────────────────────────────────" style 0-43 dim -11| " " - style 1-1 inverse -12| "────────────────────────────────────────────" +11| "deepseek-v4-flash /workspace/project ↑0 ↓0" style 0-43 dim -13| " 0% context deepseek-v4-flash(reasoning:on)" - style 1-43 dim -14-17| <blank> +12-17| <blank> diff --git a/packages/ui/tui/tests/snapshots/surface-after-compaction-wide.expected.txt b/packages/ui/tui/tests/snapshots/surface-after-compaction-wide.expected.txt index d2e86239f2..6acf1e0483 100644 --- a/packages/ui/tui/tests/snapshots/surface-after-compaction-wide.expected.txt +++ b/packages/ui/tui/tests/snapshots/surface-after-compaction-wide.expected.txt @@ -1,37 +1,27 @@ terminal 104x30 buffer=normal length=30 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=9 bufferRow=9 +cursor hidden column=1 viewportRow=7 bufferRow=7 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-103 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" - style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 103-103 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 103-103 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 103-103 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-103 fg=bright-blue -5| <blank> -6| " Context · compact " +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| " Context · compact " style 1-17 dim -7| " Compacted summary: the prior command completed and its details were retired from the active surface. " +5| " Compacted summary: the prior command completed and its details were retired from the active surface. " style 1-100 fg=bright-black +6| "────────────────────────────────────────────────────────────────────────────────────────────────────────" + style 0-103 dim +7| " " + style 1-1 inverse 8| "────────────────────────────────────────────────────────────────────────────────────────────────────────" style 0-103 dim -9| " " - style 1-1 inverse -10| "────────────────────────────────────────────────────────────────────────────────────────────────────────" - style 0-103 dim -11| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 46-103 dim -12-29| <blank> +9| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 77-103 dim +10-29| <blank> diff --git a/packages/ui/tui/tests/snapshots/surface-before-compaction.expected.txt b/packages/ui/tui/tests/snapshots/surface-before-compaction.expected.txt index bebdb78357..e69fb478b0 100644 --- a/packages/ui/tui/tests/snapshots/surface-before-compaction.expected.txt +++ b/packages/ui/tui/tests/snapshots/surface-before-compaction.expected.txt @@ -1,68 +1,59 @@ -terminal 80x24 buffer=normal length=25 base=1 viewport=1 +terminal 80x24 buffer=normal length=24 base=0 viewport=0 lifecycle started=1 stopped=0 progress=inactive title "DSH snapshot" -cursor hidden column=1 viewportRow=21 bufferRow=22 +cursor hidden column=1 viewportRow=20 bufferRow=20 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────╮" - style 0-79 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Snapshot agent ready." + style 1-21 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 79-79 fg=bright-blue -2| "│ Snapshot agent ready. │" - style 0-0 fg=bright-blue - style 2-22 fg=bright-black - style 79-79 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 79-79 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────╯" - style 0-79 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Old prompt with a long line that exercises wrapping before compaction. " +6| "▌ Old prompt with a long line that exercises wrapping before compaction. " style 0-0 fg=bright-blue +7| "▌ " + style 0-0 fg=bright-blue +8| <blank> 9| "▌ " - style 0-0 fg=bright-blue -10| <blank> -11| "▌ " style 0-0 fg=green -12| "▌ ✓ pnpm run test:coverage " +10| "▌ ✓ pnpm run test:coverage " style 0-0 fg=green style 2-2 fg=green bold style 3-25 bold -13| "▌ Run the coverage gate " +11| "▌ Run the coverage gate " style 0-0 fg=green style 2-22 fg=bright-black -14| "▌ /workspace/project " +12| "▌ /workspace/project " style 0-0 fg=green style 2-19 dim -15| "▌ packages/ui/tui 100% " +13| "▌ packages/ui/tui 100% " style 0-0 fg=green -16| "▌ … +1 lines (Ctrl+O to expand) " +14| "▌ … +1 lines (Ctrl+O to expand) " style 0-0 fg=green style 2-30 dim -17| "▌ 1 test skipped " +15| "▌ 1 test skipped " style 0-0 fg=green -18| "▌ coverage complete " +16| "▌ coverage complete " style 0-0 fg=green -19| "▌ [exit 0] " +17| "▌ [exit 0] " style 0-0 fg=green style 2-9 dim -20| "▌ " +18| "▌ " style 0-0 fg=green +19| "────────────────────────────────────────────────────────────────────────────────" + style 0-79 dim +20| " " + style 1-1 inverse 21| "────────────────────────────────────────────────────────────────────────────────" style 0-79 dim -22| " " - style 1-1 inverse -23| "────────────────────────────────────────────────────────────────────────────────" - style 0-79 dim -24| "/workspace/pro ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-13 dim - style 22-79 dim +22| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 53-79 dim +23| <blank> diff --git a/packages/ui/tui/tests/snapshots/untrusted-controls.expected.txt b/packages/ui/tui/tests/snapshots/untrusted-controls.expected.txt index 4d541b4687..fd2437a492 100644 --- a/packages/ui/tui/tests/snapshots/untrusted-controls.expected.txt +++ b/packages/ui/tui/tests/snapshots/untrusted-controls.expected.txt @@ -1,87 +1,77 @@ -terminal 100x34 buffer=normal length=40 base=6 viewport=6 +terminal 100x34 buffer=normal length=38 base=4 viewport=4 lifecycle started=1 stopped=0 progress=inactive title "Unsafe terminal title \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m" -cursor hidden column=100 viewportRow=33 bufferRow=39 +cursor hidden column=100 viewportRow=33 bufferRow=37 buffer -0| "╭──────────────────────────────────────────────────────────────────────────────────────────────────╮" - style 0-99 fg=bright-blue -1| "│ DEEPSEEK HARNESS │" +0| " DEEPSEEK HARNESS" + style 1-8 fg=bright-blue bold + style 10-16 bold +1| " Unsafe welcome \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m" + style 1-60 fg=bright-black +2| " deepseek-v4-flash • main-session" + style 1-34 dim +3| <blank> +4| "▌ " style 0-0 fg=bright-blue - style 2-9 fg=bright-blue bold - style 11-17 bold - style 99-99 fg=bright-blue -2| "│ Unsafe welcome \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m │" - style 0-0 fg=bright-blue - style 2-61 fg=bright-black - style 99-99 fg=bright-blue -3| "│ deepseek-v4-flash • main-session │" - style 0-0 fg=bright-blue - style 2-35 dim - style 99-99 fg=bright-blue -4| "╰──────────────────────────────────────────────────────────────────────────────────────────────────╯" - style 0-99 fg=bright-blue -5| <blank> -6| "▌ " - style 0-0 fg=bright-blue -7| "▌ You " +5| "▌ You " style 0-0 fg=bright-blue style 2-4 fg=bright-blue bold -8| "▌ Unsafe user \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +6| "▌ Unsafe user \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 0-0 fg=bright-blue -9| "▌ " +7| "▌ " style 0-0 fg=bright-blue -10| <blank> -11| " Reasoning " +8| <blank> +9| " Reasoning " style 1-9 fg=bright-black italic -12| " Unsafe reasoning \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +10| " Unsafe reasoning \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 1-62 fg=bright-black italic -13| <blank> -14| " Assistant " +11| <blank> +12| " Assistant " style 1-9 fg=bright-magenta bold -15| " Unsafe assistant \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " -16| <blank> -17| "▌ " +13| " Unsafe assistant \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +14| <blank> +15| "▌ " style 0-0 fg=green -18| "▌ ✓ Unsafe title \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +16| "▌ ✓ Unsafe title \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 0-0 fg=green style 2-2 fg=green bold style 3-61 bold -19| "▌ Unsafe description \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +17| "▌ Unsafe description \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 0-0 fg=green style 2-65 fg=bright-black -20| "▌ /unsafe/\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +18| "▌ /unsafe/\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 0-0 fg=green style 2-54 dim -21| "▌ Unsafe output \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +19| "▌ Unsafe output \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 0-0 fg=green -22| "▌ [signal SIG\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m] " +20| "▌ [signal SIG\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m] " style 0-0 fg=green style 2-58 fg=red -23| "▌ " +21| "▌ " style 0-0 fg=green -24| <blank> -25| " Context · unsafe-\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +22| <blank> +23| " Context · unsafe-\\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 1-62 dim -26| " Unsafe context \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +24| " Unsafe context \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 1-60 fg=bright-black -27| <blank> -28| " Prompt blocked: Unsafe policy \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +25| <blank> +26| " Prompt blocked: Unsafe policy \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 1-75 fg=yellow -29| <blank> -30| " Unsafe turn error \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +27| <blank> +28| " Unsafe turn error \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 1-63 fg=red -31| <blank> -32| " " -33| " Question 1/1 (1 unanswered) · Unsafe header \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +29| <blank> +30| " " +31| " Question 1/1 (1 unanswered) · Unsafe header \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " style 2-90 fg=bright-black -34| " Unsafe question \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " -35| " " -36| " › 1. Unsafe option \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m Unsafe detail \\x1b]2;snapshot-c " +32| " Unsafe question \\x1b]2;snapshot-controlled\\x07\\x09\\x7f\\x9b31m " +33| " " +34| " › 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 -37| " Tab custom answer • ↑/↓ navigate • Enter submit • Esc interrupt " +35| " Tab custom answer • ↑/↓ navigate • Enter submit • Esc interrupt " style 2-64 dim -38| " " -39| "/workspace/project ↑0 ↓0 0% context tools:compact deepseek-v4-flash(reasoning:on)" - style 0-24 dim - style 42-99 dim +36| " " +37| "deepseek-v4-flash /workspace/project ↑0 ↓0 0% context tools:collapsed" + style 0-43 dim + style 73-99 dim diff --git a/packages/ui/tui/tests/tui.snapshot.ts b/packages/ui/tui/tests/tui.snapshot.ts index 54d703d4a8..97617508ec 100644 --- a/packages/ui/tui/tests/tui.snapshot.ts +++ b/packages/ui/tui/tests/tui.snapshot.ts @@ -1,12 +1,13 @@ import { mkdir, readdir, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { afterAll, describe, expect, it } from 'vitest' +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 type {} from '@deepseek-ai/dsh-llm-retry' import type { Session } from '@deepseek-ai/dsh-session' +import { SessionId } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { type ToolDefinition, type ToolResultView } from '@deepseek-ai/dsh-tools' import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis' @@ -30,6 +31,7 @@ const CHECKPOINTS = [ 'retry-recovered', 'retry-cancelled', 'retry-exhausted', + 'banner-gradient', 'code-mode-pending', 'dynamic-workflow-pending', 'cordis-tools-pending', @@ -45,6 +47,9 @@ const CHECKPOINTS = [ 'model-switching', 'errors-and-help', 'disposed-terminal', + 'resume-sessions', + 'status-diagnostics', + 'status-diagnostics-narrow', ] as const type Checkpoint = typeof CHECKPOINTS[number] @@ -56,9 +61,23 @@ async function checkpoint( name: Checkpoint, terminal: HeadlessTerminal, options: TerminalSnapshotOptions = {}, + bannerGradient = false, ): Promise<void> { observedCheckpoints.add(name) - expect(terminal.themeViolations(), `${name} must remain theme-agnostic`).toEqual([]) + const violations = terminal.themeViolations() + if (bannerGradient) { + // The banner paints its product name in the DeepSeek brand gradient with + // 24-bit foreground codes: the sole sanctioned truecolor. Require it to be + // present and to never leak a background or extended-palette color into the + // otherwise theme-agnostic UI. + expect(violations, `${name} must render the banner gradient`).not.toEqual([]) + expect( + violations.every(entry => entry.endsWith('rgb-fg')), + `${name} must confine truecolor to the banner foreground`, + ).toBe(true) + } else { + expect(violations, `${name} must remain theme-agnostic`).toEqual([]) + } const snapshot = await terminal.snapshot(options) const path = join(SNAPSHOTS_DIR, `${name}.expected.txt`) if (REFRESHING) { @@ -308,6 +327,12 @@ describe('TUI terminal-state snapshots', () => { await disposeSnapshot(harness) }) + it('paints the startup banner product name in the DeepSeek brand gradient on truecolor terminals', async () => { + const harness = await setupSnapshot({ config: { truecolor: true } }) + await checkpoint('banner-gradient', harness.terminal, {}, true) + await disposeSnapshot(harness) + }) + it('pins Code Mode run_code with its production presenter', async () => { const harness = await setupSnapshot({ configureContext: configureAdvancedTools }) const call = { @@ -596,6 +621,63 @@ describe('TUI terminal-state snapshots', () => { await checkpoint('model-switching', harness.terminal, { includeScrollback: true }) await disposeSnapshot(harness) }) + + it('lists this workspace\'s resumable sessions with their commands', async () => { + const harness = await setupSnapshot({ + config: { resumeCommand: 'RESUME_SESSION_ID={session} dsh' }, + sessionPersistence: { list: async () => [ + { version: 0, id: SessionId('main-session'), createdAt: Date.parse('2024-01-02T03:04:00Z'), cwd: '/workspace/project' }, + { version: 0, id: SessionId('earlier-session'), createdAt: Date.parse('2024-01-01T00:00:00Z'), cwd: '/workspace/project' }, + ] }, + }, { columns: 92, rows: 32 }) + harness.terminal.send('/resume') + harness.terminal.send('\r') + // `/resume` scans persistence asynchronously, so the listing renders a tick + // after submit (the unit suite waits the same way); settle, then flush. + await new Promise(resolve => setTimeout(resolve, 60)) + await harness.terminal.flush() + await checkpoint('resume-sessions', harness.terminal, { includeScrollback: true }) + await disposeSnapshot(harness) + }) + + it('pins the detailed session diagnostics card', async () => { + const dateNow = vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-07-22T09:10:11.000Z')) + const harness = await setupSnapshot({ + contextWindow: 128_000, + contextTokens: 42_000, + agentOptions: { provider: 'deepseek', model: 'deepseek-v4-pro' }, + beforeMount(session) { + appendUser(session, 'inspect this session') + appendAssistant(session, [{ type: 'text', text: 'Session inspected.' }], { + inputTokens: 1_250, + outputTokens: 340, + cacheReadTokens: 3_000, + cacheWriteTokens: 250, + }) + session.append('tool/call', { + turn: 1, + step: 1, + callId: CallId('status-call'), + name: 'read', + arguments: '{"path":"README.md"}', + }) + session.append('session/title', { + title: 'Inspect session diagnostics', + messageSeqs: [1], + source: { kind: 'fallback' }, + }) + }, + }, { columns: 92, rows: 32 }) + await renderAfter(harness, () => { + harness.terminal.send('/status') + harness.terminal.send('\r') + }) + await checkpoint('status-diagnostics', harness.terminal, { includeScrollback: true }) + await renderAfter(harness, () => { harness.terminal.resize(56, 36) }) + await checkpoint('status-diagnostics-narrow', harness.terminal, { includeScrollback: true }) + await disposeSnapshot(harness) + dateNow.mockRestore() + }) }) afterAll(async () => { diff --git a/packages/ui/tui/tests/tui.spec.ts b/packages/ui/tui/tests/tui.spec.ts index 78bdc9023d..0c8450b04c 100644 --- a/packages/ui/tui/tests/tui.spec.ts +++ b/packages/ui/tui/tests/tui.spec.ts @@ -4,9 +4,10 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import type { Terminal } from '@earendil-works/pi-tui' import AgentRegistry, { agentEvents, assembleContextFor, type Agent } from '@deepseek-ai/dsh-agent' -import type { LlmCallConfig } from '@deepseek-ai/dsh-llm' +import { type LlmCallConfig } from '@deepseek-ai/dsh-llm' import CommandService, { type CommandInvocation } from '@deepseek-ai/dsh-commands' -import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import SessionStore, { SessionId, type SessionHeader } from '@deepseek-ai/dsh-session' +import SkillService, { type SkillDefinition, type SkillSummary } from '@deepseek-ai/dsh-skill' import type {} from '@deepseek-ai/dsh-session-title' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import UserInteractionService from '@deepseek-ai/dsh-user-interaction' @@ -14,6 +15,7 @@ import type {} from '@deepseek-ai/dsh-llm-retry' import { createTuiChat, mountTui, + renderSkillInvocation, resolveTuiConfig, type TuiRuntime, } from '../src/index.ts' @@ -122,6 +124,15 @@ function provideTokenMeter(ctx: Context): void { } as never) } +/** Minimal advisory-catalog llm stub for tests composing their own context. */ +function provideLlmCatalog(ctx: Context): void { + ctx.provide('llm', { + listProviders: () => [], + listModels: () => Promise.resolve([]), + resolveModelContext: () => Promise.resolve(undefined), + } as never) +} + describe('TUI config', () => { it('defaults every direct-call TUI option', () => { expect(resolveTuiConfig(undefined)).toEqual({ @@ -135,6 +146,7 @@ describe('TUI config', () => { modelDialogMaxHeight: 20, showHardwareCursor: false, color: true, + truecolor: false, title: 'DeepSeek Harness', }) expect(resolveTuiConfig({ @@ -148,6 +160,7 @@ describe('TUI config', () => { modelDialogMaxHeight: 16, showHardwareCursor: true, color: false, + truecolor: true, title: 'DSH', })).toEqual({ showReasoning: false, @@ -160,11 +173,121 @@ describe('TUI config', () => { modelDialogMaxHeight: 16, showHardwareCursor: true, color: false, + truecolor: true, title: 'DSH', }) }) }) +describe('resume command and /resume', () => { + const RESUME = 'RESUME_SESSION_ID={session} dsh' + const header = (id: string, createdAt: number, cwd: string): SessionHeader => + ({ version: 0, id: SessionId(id), createdAt, cwd }) + + it('prints the resume command on exit once the session is persisted', async () => { + const result = await setup({ + cwd: '/workspace', + config: { resumeCommand: RESUME }, + sessionPersistence: { list: async () => [header('main-session', 1000, '/workspace')] }, + }) + result.terminal.send('/exit') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('To resume this session: RESUME_SESSION_ID=main-session dsh') + expect(result.exit).toHaveBeenCalledWith(0) + await dispose(result) + }) + + it('omits the exit hint when the session is not yet persisted', async () => { + const result = await setup({ cwd: '/workspace', config: { resumeCommand: RESUME } }) + result.terminal.send('/exit') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).not.toContain('To resume this session') + expect(result.exit).toHaveBeenCalledWith(0) + await dispose(result) + }) + + it('omits the exit hint when the session listing fails', async () => { + const result = await setup({ + cwd: '/workspace', + config: { resumeCommand: RESUME }, + sessionPersistence: { list: () => Promise.reject(new Error('disk gone')) }, + }) + result.terminal.send('/exit') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).not.toContain('To resume this session') + expect(result.exit).toHaveBeenCalledWith(0) + await dispose(result) + }) + + it('lists this workspace\'s sessions newest-first and marks the current one', async () => { + const result = await setup({ + cwd: '/workspace', + config: { resumeCommand: RESUME }, + sessionPersistence: { + list: async () => [ + header('main-session', 1000, '/workspace'), + header('older-session', 500, '/workspace'), + header('newer-session', 2000, '/workspace'), + header('foreign-session', 3000, '/elsewhere'), + ], + }, + }) + result.terminal.send('/resume') + result.terminal.send('\r') + await tick() + const output = result.terminal.output + expect(output).toContain('Resumable sessions') + expect(output).toContain('RESUME_SESSION_ID=main-session dsh') + expect(output).toContain('(current)') + expect(output).toContain('RESUME_SESSION_ID=newer-session dsh') + expect(output).not.toContain('foreign-session') + // Newest-first: the newer session's command precedes the current session's. + // Match the full resume command, not the bare id: the banner detail line + // echoes the current session id (`main-session`) above the listing. + expect(output.indexOf('RESUME_SESSION_ID=newer-session')).toBeLessThan( + output.indexOf('RESUME_SESSION_ID=main-session'), + ) + expect(output.indexOf('RESUME_SESSION_ID=main-session')).toBeLessThan( + output.indexOf('RESUME_SESSION_ID=older-session'), + ) + await dispose(result) + }) + + it('warns from /resume when resume is not configured', async () => { + const result = await setup({ cwd: '/workspace' }) + result.terminal.send('/resume') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('Resume is not configured') + await dispose(result) + }) + + it('warns from /resume when no persistence backend is mounted', async () => { + const result = await setup({ cwd: '/workspace', config: { resumeCommand: RESUME } }) + result.terminal.send('/resume') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('no persistence backend is mounted') + await dispose(result) + }) + + it('notes from /resume when no workspace sessions are persisted yet', async () => { + const result = await setup({ + cwd: '/workspace', + config: { resumeCommand: RESUME }, + sessionPersistence: { list: async () => [header('foreign-session', 10, '/elsewhere')] }, + }) + result.terminal.send('/resume') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('No resumable sessions found') + await dispose(result) + }) +}) + describe('pi-tui chat lifecycle and transcript', () => { it('uses the latest log-backed title for the header subtitle and terminal window', async () => { const result = await setup({ @@ -203,6 +326,9 @@ describe('pi-tui chat lifecycle and transcript', () => { const result = await setup({ contextWindow: 100, contextTokens: 42, + // Short cwd: the footer clips its right (context/tools) segment first, + // and the default worktree path would swallow it at 88 columns. + cwd: '/opt', now: () => now, beforeMount(session) { appendUser(session, 'restored prompt') @@ -229,13 +355,14 @@ describe('pi-tui chat lifecycle and transcript', () => { expect(result.terminal.output).toContain('restored answer') expect(result.terminal.output).toContain('write tests') expect(result.terminal.output).toContain('↑1.3k ↓42') - expect(result.terminal.output).toContain('42% context tools:compact deepseek-v4-flash(reasoning:on)') + // Context resolution is async (resolveModelContext); settle before reading. + await tick() + expect(result.terminal.output).toContain('42% context tools:collapsed') + // Narrow terminals clip the right-hand context/tools segment first; the + // model-led left segment stays. result.terminal.resize(52) await tick() - expect(result.terminal.output).toContain('42% context deepseek-v4-flash(reasoning:on)') - result.terminal.resize(65) - await tick() - expect(result.terminal.output).toContain('↑1.3k ↓42 42% context deepseek-v4-flash(reasoning:on)') + expect(result.terminal.output).toContain('deepseek-v4-flash') result.terminal.resize(88) await tick() @@ -324,8 +451,7 @@ describe('pi-tui chat lifecycle and transcript', () => { expect(result.terminal.output).toContain('final live answer') }) - expect(result.terminal.output).toContain('◒ Working · 8s') - expect(result.terminal.output).toContain('esc interrupt') + expect(result.terminal.output).toContain('Enter sends steering, Esc cancels') expect(result.terminal.output).toContain('Steering') expect(result.terminal.output).toContain('user context') expect(result.terminal.output).toContain('Prompt blocked') @@ -347,7 +473,7 @@ describe('pi-tui chat lifecycle and transcript', () => { agentEvents(result.ctx, result.agent).emit('agent/status', 'idle') await tick() expect(result.terminal.output).toContain('↑1.8k ↓50') - expect(result.terminal.output).toContain('deepseek-v4-flash(reasoning:off)') + expect(result.terminal.output).toContain('deepseek-v4-flash') expect(result.terminal.progress.at(-1)).toBe(false) await dispose(result) expect(result.terminal.stopped).toBe(1) @@ -416,6 +542,170 @@ describe('pi-tui chat lifecycle and transcript', () => { await dispose(result) }) + it('badges queued steering on the running status line and clears it as each drains', async () => { + // Pin a cwd free of the substring under test; the footer renders the path. + const result = await setup({ status: 'running', cwd: '/workspace' }) + // Running with nothing queued: the plain steering hint, no badge. + expect(result.terminal.output).toContain('— Enter sends steering, Esc cancels') + expect(result.terminal.output).not.toContain('queued') + + const queueSteering = (text: string): void => { + result.ctx.emit('agent/queued', result.agent, [{ type: 'text', text }], { source: { kind: 'user' }, steering: true }) + } + const drainSteering = (text: string): void => { + result.session.append('steering/message', { turn: 1, content: [{ type: 'text', text }], source: { kind: 'user' } }, { surfaceOp: 'append' }) + } + + // A steering queue for a different agent never touches this status line. + const other = { ...result.agent, id: SessionId('other') } as Agent + result.terminal.output = '' + result.ctx.emit('agent/queued', other, [{ type: 'text', text: 'elsewhere' }], { source: { kind: 'user' }, steering: true }) + await tick() + expect(result.terminal.output).not.toContain('queued') + + // Two steering messages queue while the turn runs. + queueSteering('first') + result.terminal.output = '' + queueSteering('second') + await tick() + expect(result.terminal.output).toContain('2 queued · Enter sends steering, Esc cancels') + + // A non-steering queue (an idle-style send) leaves the badge untouched. + result.terminal.output = '' + result.ctx.emit('agent/queued', result.agent, [{ type: 'text', text: 'sent' }], { source: { kind: 'user' }, steering: false }) + drainSteering('first') + await tick() + expect(result.terminal.output).toContain('1 queued') + expect(result.terminal.output).not.toContain('2 queued') + + // Draining the last queued message returns the plain hint. + result.terminal.output = '' + drainSteering('second') + await tick() + expect(result.terminal.output).toContain('— Enter sends steering, Esc cancels') + expect(result.terminal.output).not.toContain('queued') + + // A drain with no matching queued entry is ignored rather than underflowing. + result.terminal.output = '' + drainSteering('continuation') + queueSteering('after') + await tick() + expect(result.terminal.output).toContain('1 queued') + + // A loop-authored steering event (plugin source, no matching agent/queued) + // cannot consume a pending user slot, even when it drains first. + result.terminal.output = '' + result.session.append('steering/message', { + turn: 1, + content: [{ type: 'text', text: 'continue: goal not reached' }], + source: { kind: 'plugin', plugin: 'hooks' }, + }, { surfaceOp: 'append' }) + await tick() + expect(result.terminal.output).toContain('1 queued') + result.terminal.output = '' + drainSteering('after') + await tick() + expect(result.terminal.output).not.toContain('queued') + + // The turn ending resets the badge, so the next running turn starts clean. + result.agent.status = 'idle' + result.ctx.emit('agent/status', result.agent, 'idle') + result.agent.status = 'running' + result.terminal.output = '' + result.ctx.emit('agent/status', result.agent, 'running') + await tick() + expect(result.terminal.output).toContain('— Enter sends steering, Esc cancels') + expect(result.terminal.output).not.toContain('queued') + + await dispose(result) + }) + + it('derives the fine-grained turn phase from session lifecycle events', async () => { + // A live event before the turn runs has no status controller to move. + const idle = await setup() + // A steering queue arriving while idle has no status line to badge, so the + // refresh is a no-op beyond requesting a render. + idle.ctx.emit('agent/queued', idle.agent, [{ type: 'text', text: 'early' }], { source: { kind: 'user' }, steering: true }) + idle.session.append('tool/call', { turn: 1, step: 0, callId: 'pre' as never, name: 'bash', arguments: '{}' }) + await tick() + expect(idle.terminal.output).not.toContain('Executing tools') + expect(idle.terminal.output).not.toContain('queued') + await dispose(idle) + + const result = await setup({ status: 'running' }) + expect(result.terminal.output).toContain('Waiting for the first token') + + result.terminal.output = '' + result.session.append('assistant/chunk', { turn: 1, step: 0, chunk: { type: 'block-start', index: 0, blockType: 'reasoning' } }) + result.session.append('assistant/chunk', { turn: 1, step: 0, chunk: { type: 'reasoning-delta', index: 0, text: 'mull it over' } }) + await tick() + expect(result.terminal.output).toContain('Thinking') + + result.terminal.output = '' + result.session.append('assistant/chunk', { turn: 1, step: 0, chunk: { type: 'block-start', index: 1, blockType: 'text' } }) + result.session.append('assistant/chunk', { turn: 1, step: 0, chunk: { type: 'text-delta', index: 1, text: 'answering' } }) + await tick() + expect(result.terminal.output).toContain('Responding') + + result.terminal.output = '' + result.session.append('tool/call', { turn: 1, step: 0, callId: 'c1' as never, name: 'bash', arguments: '{}' }) + await tick() + expect(result.terminal.output).toContain('Executing tools') + + // The next step reopens the wait window and resets the executing label. + result.terminal.output = '' + result.session.append('step/start', { turn: 1, step: 1 }) + await tick() + expect(result.terminal.output).toContain('Waiting for the first token') + expect(result.terminal.output).not.toContain('Executing tools') + + await dispose(result) + }) + + it('refreshes the running status elapsed time on its own timer', async () => { + const result = await setup({ status: 'running' }) + result.terminal.output = '' + // The loader repaints "0s" until the controller's own interval fires; a + // non-zero elapsed proves the refresh, not just the loader's animation. + await new Promise(resolve => setTimeout(resolve, 1_300)) + expect(result.terminal.output).toMatch(/Waiting for the first token [1-9]s/) + await dispose(result) + }) + + it('shows minutes and seconds once a step passes a minute', async () => { + const result = await setup({ status: 'running' }) + const base = Date.now() + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(base + 95_000) + result.terminal.output = '' + result.session.append('assistant/chunk', { turn: 1, step: 0, chunk: { type: 'text-delta', index: 0, text: 'hi' } }) + await tick() + expect(result.terminal.output).toContain('total 1m') + nowSpy.mockRestore() + await dispose(result) + }) + + it('preserves the turn phase and elapsed time across a mid-turn color-scheme change', async () => { + const result = await setup({ status: 'running' }) + const base = Date.now() + const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(base) + // Advance into `responding`, anchoring the phase clock at `base`. + result.session.append('assistant/chunk', { turn: 1, step: 0, chunk: { type: 'text-delta', index: 0, text: 'answering' } }) + await tick() + + // Four seconds later the terminal reports a light color scheme, rebuilding + // the status loader; the phase and its elapsed time must survive the rebuild. + nowSpy.mockReturnValue(base + 4_000) + result.terminal.output = '' + result.terminal.send('\x1b[?997;2n') + await tick() + await tick() + expect(result.terminal.output).toContain('Responding 4s') + expect(result.terminal.output).not.toContain('Waiting for the first token') + + nowSpy.mockRestore() + await dispose(result) + }) + it('renders the ANSI palette and every markdown/content style', async () => { const result = await setup({ cwd: '/workspace', @@ -519,6 +809,126 @@ describe('pi-tui chat lifecycle and transcript', () => { await dispose(logicalResult) }) + it('shows the session cache hit rate in the footer and updates it live', async () => { + // Empty session: no input billed yet, so the cache segment is hidden. + // A cwd without "cache" in it keeps the negative assertion unambiguous. + const empty = await setup({ cwd: '/opt' }) + expect(empty.terminal.output).toContain('↑0 ↓0') + expect(empty.terminal.output).not.toContain('cache') + await dispose(empty) + + const result = await setup({ + // Pin a short cwd so the footer never clips the cache segment: the + // default is process.cwd(), and a deep worktree path truncates + // `cache 60%` at the terminal width. + cwd: '/opt', + beforeMount(session) { + // Cold call: 10 billed input tokens, none served from cache. + appendAssistant(session, [{ type: 'text', text: 'cold' }], { inputTokens: 10, outputTokens: 5 }) + }, + }) + expect(result.terminal.output).toContain('cache 0%') + + result.terminal.output = '' + // Warm call lands live on the next step (same-step usage replaces rather + // than accumulates): 5 uncached + 30 cache-read + 5 cache-write billed + // input, so 30 of the 50 total prompt tokens are hits → 60%. + appendAssistant(result.session, [{ type: 'text', text: 'warm' }], { + inputTokens: 5, + outputTokens: 5, + cacheReadTokens: 30, + cacheWriteTokens: 5, + }, { turn: 1, step: 2 }) + await tick() + expect(result.terminal.output).toContain('cache 60%') + expect(result.terminal.output).not.toContain('cache 0%') + await dispose(result) + }) + + it('shows detailed session diagnostics while the agent is running', async () => { + const timestamp = Date.parse('2026-07-22T09:10:11.000Z') + const dateNow = vi.spyOn(Date, 'now').mockReturnValue(timestamp) + const result = await setup({ + cwd: '/workspace/status', + contextWindow: 128_000, + contextTokens: 42_000, + config: { showReasoning: false }, + agentOptions: { provider: 'deepseek', model: 'deepseek-v4-pro' }, + beforeMount(session) { + session.append('session/title', { + title: 'Inspect status \u001B]2;unsafe\u0007', + messageSeqs: [1], + source: { kind: 'fallback' }, + }) + appendAssistant(session, [{ type: 'text', text: 'measured' }], { + inputTokens: 1_250, + outputTokens: 340, + cacheReadTokens: 3_000, + cacheWriteTokens: 250, + }) + session.append('tool/call', { + turn: 1, step: 1, callId: 'status-call-1' as never, name: 'read', arguments: '{}', + }) + session.append('tool/call', { + turn: 1, step: 1, callId: 'status-call-2' as never, name: 'write', arguments: '{}', + }) + }, + }) + result.agent.status = 'running' + agentEvents(result.ctx, result.agent).emit('agent/status', 'running') + result.terminal.send('/status') + result.terminal.send('\r') + await tick() + + expect(result.terminal.output).toContain('Session status') + expect(result.terminal.output).toContain('main-session') + expect(result.terminal.output).toContain('Inspect status \\x1b]2;unsafe\\x07') + expect(result.terminal.output).toContain('/workspace/status') + expect(result.terminal.output).toContain('deepseek/deepseek-v4-pro (reasoning hidden)') + expect(result.terminal.output).toContain('running · 6 events · 1 turn · 1 step · 2 tool calls') + expect(result.terminal.output).toContain('1,250 input + 340 output') + expect(result.terminal.output).toContain('[███████████░░░░░] 67% hit (3,000 read + 250 write)') + expect(result.terminal.output).toContain('[█████░░░░░░░░░░░] 33% used (42,000 / 128,000)') + expect(result.terminal.output).toContain('2026-07-22 09:10:11 UTC') + expect(result.terminal.output).not.toContain('\u001B]2;unsafe\u0007') + + result.terminal.resize(56) + result.terminal.send('/redraw') + result.terminal.send('\r') + await tick() + + await dispose(result) + dateNow.mockRestore() + }) + + it('labels unavailable status diagnostics without inventing values', async () => { + const timestamp = Date.parse('2026-07-22T10:11:12.000Z') + const dateNow = vi.spyOn(Date, 'now').mockReturnValue(timestamp) + const result = await setup({ + cwd: null, + omitInitialLifecycle: true, + contextTokens: 7, + agentOptions: {}, + catalog: { + providers: [], + models: [], + resolveModelContext: () => Promise.resolve(undefined), + }, + }) + result.terminal.send('/status') + result.terminal.send('\r') + await tick() + + expect(result.terminal.output).toContain('untitled') + expect(result.terminal.output).toContain('unset (reasoning shown)') + expect(result.terminal.output).toContain('idle · 0 events · 0 turns · 0 steps · 0 tool calls') + expect(result.terminal.output).toContain('n/a (0 read + 0 write)') + expect(result.terminal.output).toContain('7 used · capacity unknown') + expect(result.terminal.output).toContain('2026-07-22 10:11:12 UTC') + await dispose(result) + dateNow.mockRestore() + }) + it('sends, steers, handles commands, global keys, and disposed-agent input', async () => { const result = await setup() @@ -540,17 +950,15 @@ describe('pi-tui chat lifecycle and transcript', () => { result.terminal.send('\x03') result.terminal.send('\x12') result.terminal.send('\x0f') - result.terminal.send('/cancel') - result.terminal.send('\r') expect(result.agent.cancelled).toContainEqual({ kind: 'user' }) result.agent.status = 'idle' - for (const command of ['/help', '/reasoning', '/tools', '/redraw']) { + for (const command of ['/help', '/reasoning', '/tools', '/redraw', '/reload']) { result.terminal.send(command) result.terminal.send('\r') await tick() } - for (const command of ['/clear', '/cancel', '/wat']) { + for (const command of ['/clear', '/wat']) { result.terminal.send(command) result.terminal.send('\r') } @@ -563,8 +971,9 @@ describe('pi-tui chat lifecycle and transcript', () => { expect(result.terminal.output).toContain('Keyboard shortcuts') expect(result.terminal.output).toContain('Reasoning blocks') expect(result.terminal.output).toContain('Tool cards') - expect(result.terminal.output).toContain('already idle') expect(result.terminal.output).toContain('Unknown command') + // /reload without a Loader in the context degrades to a warning. + expect(result.terminal.output).toContain('/reload needs the cordis Loader') expect(result.exit).toHaveBeenCalledWith(0) await result.controller.dispose() await result.ctx.fiber.dispose() @@ -630,7 +1039,7 @@ describe('pi-tui chat lifecycle and transcript', () => { expect(result.agent.steered).toEqual([]) initialContext.resolve({ contextWindow: 100 }) await tick() - expect(result.terminal.output).not.toContain('50% context tools:compact b1(reasoning:on)') + expect(result.terminal.output).not.toContain('50% context tools:collapsed') result.terminal.send('/model') result.terminal.send('\r') @@ -641,7 +1050,8 @@ describe('pi-tui chat lifecycle and transcript', () => { result.agent.status = 'idle' result.ctx.emit('agent/status', result.agent, 'idle') await tick() - expect(result.terminal.output).toContain('25% context tools:compact b1(reasoning:on)') + expect(result.terminal.output).toContain('b1 ') + expect(result.terminal.output).toContain('25% context tools:collapsed') const assembly = await result.ctx.systemPrompt.assemble(assembleContextFor(result.agent)) expect(assembly.variables).toMatchObject({ provider: 'beta', model: 'b1' }) @@ -686,7 +1096,8 @@ describe('pi-tui chat lifecycle and transcript', () => { unset.terminal.send('\r') await tick() expect(unset.terminal.output).toContain('Model selected: alpha/a1') - expect(unset.terminal.output).toContain('context unknown tools:compact a1(reasoning:on)') + expect(unset.terminal.output).toContain('a1 ') + expect(unset.terminal.output).not.toContain('% context') await dispose(unset) const empty = await setup({ agentOptions: {}, catalog: { providers: [], models: [] } }) @@ -785,6 +1196,11 @@ describe('pi-tui chat lifecycle and transcript', () => { description: 'Fail a plugin command', handler: () => { throw new Error('plugin command exploded') }, }) + result.ctx.commands.register({ + name: 'plugin-error', + description: 'Return an error result', + handler: () => ({ kind: 'error' as const, text: 'plugin error result' }), + }) result.terminal.send('/plugin-check value ') result.terminal.send('\r') @@ -801,6 +1217,10 @@ describe('pi-tui chat lifecycle and transcript', () => { result.terminal.send('\r') await tick() expect(result.terminal.output).toContain('Command failed: plugin command exploded') + result.terminal.send('/plugin-error') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('plugin error result') result.terminal.send('/help') result.terminal.send('\r') await tick() @@ -810,6 +1230,7 @@ describe('pi-tui chat lifecycle and transcript', () => { await result.controller.dispose() expect(result.ctx.commands.list(result.agent).map(command => command.name)).toEqual([ 'plugin-check', + 'plugin-error', 'plugin-fail', ]) await result.ctx.fiber.dispose() @@ -918,6 +1339,153 @@ describe('pi-tui chat lifecycle and transcript', () => { }) }) +describe('skill slash command', () => { + const withSkills = async (ctx: Context): Promise<void> => { + ctx.provide('tools', { get() { return undefined } } as never) + await ctx.plugin(SkillService) + const skills = ctx.get('skills') + if (skills === undefined) throw new Error('skills service not mounted') + skills.register({ name: 'demo-skill', description: 'Demo skill for tests', source: 'runtime', provider: 'runtime', content: 'Demo instructions body.' }) + skills.register({ name: 'hidden-skill', description: 'Model-hidden skill', source: 'runtime', provider: 'runtime', content: 'Hidden instructions body.', disableModelInvocation: true }) + } + + it('offers non-hidden skills as slash completions and hides model-disabled ones', async () => { + const result = await setup({ configureContext: withSkills }) + result.terminal.send('/skill') + await tick() + expect(result.terminal.output).toContain('demo-skill') + expect(result.terminal.output).not.toContain('hidden-skill') + await dispose(result) + }) + + it('loads a skill as a user turn, appending typed instructions', async () => { + const result = await setup({ configureContext: withSkills }) + result.terminal.send('/skill:demo-skill') + result.terminal.send('\r') + await tick() + expect(result.agent.sent).toEqual([[{ type: 'text', text: '<skill name="demo-skill">\nDemo instructions body.\n</skill>' }]]) + + result.agent.status = 'running' + result.terminal.send('/skill:demo-skill focus on tests') + result.terminal.send('\r') + await tick() + expect(result.agent.steered).toEqual([[{ type: 'text', text: '<skill name="demo-skill">\nDemo instructions body.\n</skill>\n\nfocus on tests' }]]) + await dispose(result) + }) + + it('invokes a model-disabled skill by its exact name', async () => { + const result = await setup({ configureContext: withSkills }) + result.terminal.send('/skill:hidden-skill') + result.terminal.send('\r') + await tick() + expect(result.agent.sent).toEqual([[{ type: 'text', text: '<skill name="hidden-skill">\nHidden instructions body.\n</skill>' }]]) + await dispose(result) + }) + + it('reports an unknown skill and an empty skill name without sending', async () => { + const result = await setup({ configureContext: withSkills }) + result.terminal.send('/skill:does-not-exist') + result.terminal.send('\r') + await tick() + result.terminal.send('/skill:') + result.terminal.send('\r') + await tick() + // A space right after the colon parses to an empty name, not a name of + // "focus"; the documented syntax puts the name immediately after the colon. + result.terminal.send('/skill: focus') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('Unknown skill: does-not-exist') + expect(result.terminal.output).toContain('Usage: /skill:<name>') + expect(result.agent.sent).toEqual([]) + await dispose(result) + }) + + it('warns when no skill service is mounted', async () => { + const result = await setup() + result.terminal.send('/skill:demo-skill') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('Skills are not available') + expect(result.agent.sent).toEqual([]) + await dispose(result) + }) + + it('surfaces skill lookup failures as an error notice', async () => { + const result = await setup({ + configureContext: async (ctx) => { + ctx.provide('tools', { get() { return undefined } } as never) + ctx.provide('skills', { + list: () => Promise.reject(new Error('list boom')), + get: () => Promise.reject(new Error('get boom')), + } as never) + }, + }) + result.terminal.send('/skill:demo-skill') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('failed to load') + expect(result.terminal.output).toContain('get boom') + await dispose(result) + }) + + it('drops skill list and lookup results that settle after disposal', async () => { + const pendingList: Array<(value: SkillSummary[]) => void> = [] + const pendingGet: Array<{ resolve: (value: SkillDefinition | undefined) => void; reject: (error: unknown) => void }> = [] + const result = await setup({ + configureContext: async (ctx) => { + ctx.provide('tools', { get() { return undefined } } as never) + ctx.provide('skills', { + list: () => new Promise<SkillSummary[]>((resolve) => { pendingList.push(resolve) }), + get: () => new Promise<SkillDefinition | undefined>((resolve, reject) => { pendingGet.push({ resolve, reject }) }), + } as never) + }, + }) + result.terminal.send('/skill:demo-skill') + result.terminal.send('\r') + await tick() + result.terminal.send('/skill:other-skill') + result.terminal.send('\r') + await tick() + await dispose(result) + + for (const resolve of pendingList) resolve([{ name: 'late', description: 'late', source: 'runtime', provider: 'runtime' }]) + pendingGet[0]?.resolve({ name: 'demo-skill', description: 'late', source: 'runtime', provider: 'runtime', content: 'late body' }) + pendingGet[1]?.reject(new Error('late failure')) + await tick() + expect(result.agent.sent).toEqual([]) + expect(result.terminal.output).not.toContain('late failure') + expect(result.terminal.output).not.toContain('late body') + }) +}) + +describe('renderSkillInvocation', () => { + const skill: SkillDefinition = { + name: 'demo-skill', + description: 'Demo skill', + source: 'runtime', + provider: 'runtime', + content: 'Body text.', + } + + it('renders directory, url, opaque, and absent resource bases', () => { + expect(renderSkillInvocation({ ...skill, resourceBase: { kind: 'directory', path: '/skills/demo' } }, '')).toBe( + '<skill name="demo-skill">\nReferences in this skill are relative to /skills/demo.\n\nBody text.\n</skill>', + ) + expect(renderSkillInvocation({ ...skill, resourceBase: { kind: 'url', url: 'https://x/y' } }, 'go')).toBe( + '<skill name="demo-skill">\nReferences in this skill are relative to https://x/y.\n\nBody text.\n</skill>\n\ngo', + ) + expect(renderSkillInvocation({ ...skill, resourceBase: { kind: 'opaque', description: 'held in memory' } }, '')).toBe( + '<skill name="demo-skill">\nheld in memory\n\nBody text.\n</skill>', + ) + expect(renderSkillInvocation(skill, '')).toBe('<skill name="demo-skill">\nBody text.\n</skill>') + }) + + it('throws on an unknown resource base kind', () => { + expect(() => renderSkillInvocation({ ...skill, resourceBase: { kind: 'future' } as never }, '')).toThrow('unreachable variant') + }) +}) + describe('tool cards and surface replay', () => { const tools: Record<string, ToolDefinition> = { bash: { @@ -1291,6 +1859,40 @@ describe('terminal mounting', () => { await ctx.fiber.dispose() }) + it('degrades /reload to a warning when mounted as a real plugin without a Loader', async () => { + // Production shape: the TUI runs inside a plugin fiber, where a bare + // `ctx.loader` proxy read would THROW `cannot get property without + // inject` — only the non-throwing `ctx.get` lookup degrades gracefully. + const ctx = new Context() + provideTokenMeter(ctx) + provideLlmCatalog(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(AgentRegistry) + await ctx.plugin(CommandService) + await ctx.plugin(UserInteractionService) + ctx.provide('tools', { get: () => undefined } as never) + const session = ctx.sessions.create(SessionId('main')) + ctx.agents.register({ + id: session.id, options: {}, session, status: 'idle', ctx, + send() {}, steer() {}, inject() {}, cancel() {}, whenIdle: () => Promise.resolve(), + }) + const terminal = new FakeTerminal() + // Mirror dsh-tui's own inject (minus loader, the absence under test). + await ctx.plugin({ + inject: ['agents', 'commands', 'userInteraction', 'tools', 'llm', 'tokenMeter'], + apply: (pluginCtx: Context) => { + mountTui(pluginCtx, { color: false }, { terminal, exit: vi.fn() }) + }, + }) + await tick() + expect(terminal.started).toBe(1) + terminal.send('/reload') + terminal.send('\r') + await tick() + expect(terminal.output).toContain('/reload needs the cordis Loader') + await ctx.fiber.dispose() + }) + it('waits for its configured agent before starting the TUI', async () => { const ctx = new Context() provideTokenMeter(ctx) @@ -1472,4 +2074,175 @@ describe('terminal mounting', () => { expect(terminal.output).toContain('\x1b[2mdeepseek-v4-flash') await disposeTuiTestHarness(result) }) + it('runs /reload against every file-backed loader subtree, reports completion, and rejects re-entry while in flight', async () => { + const refreshed: string[] = [] + let releaseRefresh!: () => void + const gate = new Promise<void>((resolve) => { releaseRefresh = resolve }) + const result = await setup({ + configureContext: async (ctx) => { + ctx.provide('tools', { get: () => undefined } as never) + // A structural Loader: two file-backed subtrees and one plain entry. + // The first subtree blocks on a gate so re-entry can be probed + // deterministically mid-flight. + ctx.provide('loader', { + entries: () => [ + { subtree: { refresh: async () => { refreshed.push('root'); await gate } } }, + {}, + { subtree: { refresh: async () => { refreshed.push('nested') } } }, + ], + } as never) + }, + }) + result.terminal.send('/reload') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('Reloading 2 config tree(s)') + // Second /reload while the first is gated: refused, no extra refreshes. + result.terminal.send('/reload') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('A config reload is already running.') + expect(refreshed.sort()).toEqual(['nested', 'root']) + releaseRefresh() + await tick() + expect(result.terminal.output).toContain('Config reload complete.') + // The guard released: a third /reload runs again. + result.terminal.send('/reload') + result.terminal.send('\r') + await tick() + expect(refreshed).toHaveLength(4) + await dispose(result) + }) + + it('reports a /reload failure if a refresh ever rejects', async () => { + const result = await setup({ + configureContext: async (ctx) => { + ctx.provide('tools', { get: () => undefined } as never) + ctx.provide('loader', { + entries: () => [{ subtree: { refresh: () => Promise.reject(new Error('disk gone')) } }], + } as never) + }, + }) + result.terminal.send('/reload') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('Config reload failed: disk gone') + // The failure arm also releases the re-entrancy guard. + result.terminal.send('/reload') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).not.toContain('A config reload is already running.') + await dispose(result) + }) + + it('refuses /reload while the agent is running and allows it back at idle', async () => { + const refreshed: string[] = [] + const result = await setup({ + status: 'running', + configureContext: async (ctx) => { + ctx.provide('tools', { get: () => undefined } as never) + ctx.provide('loader', { + entries: () => [{ subtree: { refresh: async () => { refreshed.push('tree') } } }], + } as never) + }, + }) + result.terminal.send('/reload') + result.terminal.send('\r') + await tick() + expect(result.terminal.output).toContain('/reload requires an idle agent (status: running).') + expect(refreshed).toHaveLength(0) + // Back at idle the same command runs. + result.agent.status = 'idle' + result.terminal.send('/reload') + result.terminal.send('\r') + await tick() + expect(refreshed).toHaveLength(1) + expect(result.terminal.output).toContain('Config reload complete.') + await dispose(result) + }) + +}) + +describe('banner sweep reveal', () => { + it('renders the product name through the brand-gradient path when truecolor is enabled', async () => { + // The product name carries a per-letter 24-bit gradient from the brand + // indigo to light blue; the per-letter layout is pinned by the + // `banner-gradient` terminal snapshot. + const result = await setup({ config: { color: true, truecolor: true } }) + expect(result.terminal.output).toContain('\x1b[38;2;77;107;254m') + expect(result.terminal.output).toContain('\x1b[38;2;36;152;255m') + expect(result.terminal.output).toContain('HARNESS') + await dispose(result) + }) + + it('sweeps the whole borderless banner in when no welcome is configured, ending complete', async () => { + const intervals = vi.spyOn(globalThis, 'setInterval') + const cleared = vi.spyOn(globalThis, 'clearInterval') + const result = await setup({ omitWelcome: true }) + const revealHandle = intervals.mock.results.at(-1)?.value as ReturnType<typeof setInterval> + // Run the sweep to natural completion — it clears its own timer at the end. + const done = (): boolean => cleared.mock.calls.some(call => call[0] === revealHandle) + const deadline = Date.now() + 5000 + while (!done() && Date.now() < deadline) await tick() + intervals.mockRestore() + cleared.mockRestore() + // The finished banner carries the title and the model • session detail. + expect(result.terminal.output).toContain('DEEPSEEK') + expect(result.terminal.output).toContain('HARNESS') + expect(result.terminal.output).toContain('main-session') + // Borderless: no box-drawing frame around the banner. + expect(result.terminal.output).not.toContain('╭') + expect(result.terminal.output).not.toContain('╮') + // A mid-sweep frame rendered a clipped title: `DEEPSEEK` with no `HARNESS` + // on the same line. + const clipped = result.terminal.output + .split('\n') + .some(line => line.includes('DEEPSEEK') && !line.includes('HARNESS')) + expect(clipped).toBe(true) + await dispose(result) + }) + + it('renders a configured welcome verbatim in a complete banner with no sweep', async () => { + const result = await setup() + await tick() + expect(result.terminal.output).toContain('Coding agent ready.') + expect(result.terminal.output).toContain('DEEPSEEK') + expect(result.terminal.output).not.toContain('╭') + // No reveal frames: the banner is drawn whole from the first render, so no + // clipped-title frame ever appears. + const clipped = result.terminal.output + .split('\n') + .some(line => line.includes('DEEPSEEK') && !line.includes('HARNESS')) + expect(clipped).toBe(false) + await dispose(result) + }) + + it('omits the subtitle line entirely when no welcome is configured', async () => { + const result = await setup({ omitWelcome: true }) + const deadline = Date.now() + 5000 + while (!result.terminal.output.includes('main-session') && Date.now() < deadline) await tick() + // Banner is title + detail only — no subtitle between them. + expect(result.terminal.output).toContain('deepseek-v4-flash') + expect(result.terminal.output).not.toContain('ready.') + await dispose(result) + }) + + it('stops a mid-sweep animation on dispose', async () => { + // The output-stability probe alone is insensitive to a leaked interval + // (pi-tui's stopped guard silences post-stop renders), so capture the + // reveal's own interval handle and assert dispose clears exactly it. + const intervals = vi.spyOn(globalThis, 'setInterval') + const result = await setup({ omitWelcome: true }) + const revealHandle = intervals.mock.results.at(-1)?.value as ReturnType<typeof setInterval> + expect(revealHandle).toBeDefined() + const cleared = vi.spyOn(globalThis, 'clearInterval') + await dispose(result) + expect(cleared.mock.calls.some(call => call[0] === revealHandle)).toBe(true) + intervals.mockRestore() + cleared.mockRestore() + const settled = result.terminal.output.length + await tick() + await tick() + expect(result.terminal.output.length).toBe(settled) + }) }) diff --git a/packages/ui/tui/tsconfig.json b/packages/ui/tui/tsconfig.json index b9aed2dbae..2d1bbb2477 100644 --- a/packages/ui/tui/tsconfig.json +++ b/packages/ui/tui/tsconfig.json @@ -23,6 +23,9 @@ { "path": "../../core/session" }, + { + "path": "../../session-persistence/session-persistence" + }, { "path": "../../session-title/session-title" }, @@ -41,6 +44,9 @@ { "path": "../commands" }, + { + "path": "../../skill/skill" + }, { "path": "../user-interaction" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 49c7af2b09..8f60725e0a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -97,7 +97,7 @@ importers: version: 6.1.1(typescript@6.0.3)(vite@8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) vitest: specifier: ^4.1.8 - version: 4.1.8(@types/node@22.20.0)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) + version: 4.1.8(@opentelemetry/api@1.9.0)(@types/node@22.20.0)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) apps/cli: dependencies: @@ -116,6 +116,9 @@ importers: '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../../packages/host/webserver + '@deepseek-ai/dsh-paths': + specifier: workspace:^ + version: link:../../packages/util/paths '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../packages/core/session @@ -270,6 +273,9 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:* version: link:../packages/session-persistence/session-persistence-jsonl + '@deepseek-ai/dsh-session-title-first-message-llm': + specifier: workspace:* + version: link:../packages/session-title/session-title-first-message-llm '@deepseek-ai/dsh-spill-local': specifier: workspace:* version: link:../packages/spill/spill-local @@ -2064,8 +2070,8 @@ importers: packages/llm/llm-pi-ai: dependencies: '@earendil-works/pi-ai': - specifier: ^0.79.1 - version: 0.79.3(@modelcontextprotocol/sdk@1.29.0(zod@4.4.3))(ws@8.21.0)(zod@4.4.3) + specifier: ^0.81.1 + version: 0.81.1(@modelcontextprotocol/sdk@1.29.0(zod@4.4.3))(ws@8.21.0)(zod@4.4.3) schemastery: specifier: ^3.18.0 version: 3.18.0 @@ -3144,7 +3150,7 @@ importers: version: link:../loader-smoke vitest: specifier: ^4.1.8 - version: 4.1.8(@types/node@25.9.3)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) + version: 4.1.8(@opentelemetry/api@1.9.0)(@types/node@25.9.3)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) devDependencies: '@deepseek-ai/dsh-invariants': specifier: workspace:^ @@ -3413,6 +3419,10 @@ importers: version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) packages/ui/app-boot: + dependencies: + js-yaml: + specifier: ^4.2.0 + version: 4.2.0 devDependencies: '@cordisjs/plugin-include': specifier: workspace:^ @@ -3423,6 +3433,15 @@ importers: '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@deepseek-ai/dsh-paths': + specifier: workspace:^ + version: link:../../util/paths + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../../core/system-prompt + '@types/js-yaml': + specifier: ^4.0.9 + version: 4.0.9 cordis: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@vendor+include)(@cordisjs/plugin-loader@vendor+loader) @@ -3570,9 +3589,15 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:^ + version: link:../../session-persistence/session-persistence '@deepseek-ai/dsh-session-title': specifier: workspace:^ version: link:../../session-title/session-title + '@deepseek-ai/dsh-skill': + specifier: workspace:^ + version: link:../../skill/skill '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt @@ -4790,8 +4815,8 @@ packages: search-insights: optional: true - '@earendil-works/pi-ai@0.79.3': - resolution: {integrity: sha512-lMSput/haP5uZAGbXhS5rAYd3GB7GYdJkoAUxg3VFummBeqGqGqllaTWrbHFN12kVGyVfWHhdySNXkiqVh65Iw==} + '@earendil-works/pi-ai@0.81.1': + resolution: {integrity: sha512-hzHE7Z8l5mgJk+ke67Lge0rwS2+wbKJrFKl9o5M1R1rh33+cCT7D1AHz1OAtX5wFs90E1/BTGhyJRTUHaMxGvQ==} engines: {node: '>=22.19.0'} hasBin: true @@ -5451,8 +5476,13 @@ packages: '@mermaid-js/parser@1.2.0': resolution: {integrity: sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==} - '@mistralai/mistralai@2.2.1': - resolution: {integrity: sha512-uKU8CZmL2RzYKmplsU01hii4p3pe4HqJefpWNRWXm1Tcm0Sm4xXfwSLIy4k7ZCPlbETCGcp69E7hZs+WOJ5itQ==} + '@mistralai/mistralai@2.2.6': + resolution: {integrity: sha512-W8pX7zHxjJvMIpw8JMxeJEleapXX0Q9NPszdNzqkM3MIEoIGPObdodujj+WHteXEvGfaP/AMwlNyRfEzSY6dQQ==} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + peerDependenciesMeta: + '@opentelemetry/api': + optional: true '@modelcontextprotocol/sdk@1.29.0': resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==} @@ -5481,6 +5511,14 @@ packages: '@nodable/entities@2.2.0': resolution: {integrity: sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg==} + '@opentelemetry/api@1.9.0': + resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==} + engines: {node: '>=8.0.0'} + + '@opentelemetry/semantic-conventions@1.43.0': + resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} + engines: {node: '>=14'} + '@oxc-parser/binding-android-arm-eabi@0.133.0': resolution: {integrity: sha512-l/44caGse+VpnY9gx0yvvc5QnnG3yG1FO3KZgYvNL1GZrfK86zIwAOgGEVlxDyRymzrU/KHiblPFpevKOmJmUA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -9779,12 +9817,13 @@ snapshots: transitivePeerDependencies: - '@algolia/client-search' - '@earendil-works/pi-ai@0.79.3(@modelcontextprotocol/sdk@1.29.0(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)': + '@earendil-works/pi-ai@0.81.1(@modelcontextprotocol/sdk@1.29.0(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)': dependencies: '@anthropic-ai/sdk': 0.91.1(zod@4.4.3) '@aws-sdk/client-bedrock-runtime': 3.1048.0 '@google/genai': 1.52.0(@modelcontextprotocol/sdk@1.29.0(zod@4.4.3)) - '@mistralai/mistralai': 2.2.1 + '@mistralai/mistralai': 2.2.6(@opentelemetry/api@1.9.0) + '@opentelemetry/api': 1.9.0 '@smithy/node-http-handler': 4.7.3 http-proxy-agent: 7.0.2 https-proxy-agent: 7.0.6 @@ -10226,11 +10265,14 @@ snapshots: dependencies: '@chevrotain/types': 11.1.2 - '@mistralai/mistralai@2.2.1': + '@mistralai/mistralai@2.2.6(@opentelemetry/api@1.9.0)': dependencies: + '@opentelemetry/semantic-conventions': 1.43.0 ws: 8.21.0 zod: 4.4.3 zod-to-json-schema: 3.25.2(zod@4.4.3) + optionalDependencies: + '@opentelemetry/api': 1.9.0 transitivePeerDependencies: - bufferutil - utf-8-validate @@ -10295,6 +10337,10 @@ snapshots: '@nodable/entities@2.2.0': {} + '@opentelemetry/api@1.9.0': {} + + '@opentelemetry/semantic-conventions@1.43.0': {} + '@oxc-parser/binding-android-arm-eabi@0.133.0': optional: true @@ -11112,7 +11158,7 @@ snapshots: obug: 2.1.3 std-env: 4.1.0 tinyrainbow: 3.1.0 - vitest: 4.1.8(@types/node@22.20.0)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) + vitest: 4.1.8(@opentelemetry/api@1.9.0)(@types/node@22.20.0)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) '@vitest/expect@4.1.8': dependencies: @@ -14018,7 +14064,7 @@ snapshots: transitivePeerDependencies: - msw - vitest@4.1.8(@types/node@22.20.0)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)): + vitest@4.1.8(@opentelemetry/api@1.9.0)(@types/node@22.20.0)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.8 '@vitest/mocker': 4.1.8(vite@8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) @@ -14041,13 +14087,14 @@ snapshots: vite: 8.0.16(@types/node@22.20.0)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: + '@opentelemetry/api': 1.9.0 '@types/node': 22.20.0 '@vitest/coverage-v8': 4.1.8(vitest@4.1.8) jsdom: 29.1.1 transitivePeerDependencies: - msw - vitest@4.1.8(@types/node@25.9.3)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)): + vitest@4.1.8(@opentelemetry/api@1.9.0)(@types/node@25.9.3)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.8 '@vitest/mocker': 4.1.8(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) @@ -14070,6 +14117,7 @@ snapshots: vite: 8.0.16(@types/node@25.9.3)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: + '@opentelemetry/api': 1.9.0 '@types/node': 25.9.3 '@vitest/coverage-v8': 4.1.8(vitest@4.1.8) jsdom: 29.1.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 6ba86c7d71..8da07afcf0 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,6 +1,7 @@ packages: - vendor/* - packages/*/* + # Product assemblies over the package tier; apps/cli owns the `dsh` bin. - apps/* - website # The runnable demo leaves join as ONE workspace member: examples/package.json @@ -50,3 +51,6 @@ minimumReleaseAgeExclude: # during the same-day sync that updates package manifests and the lockfile. - '@cordisjs/plugin-loader@1.0.0-rc.5' - cordis@4.0.0-rc.7 + # Fresh pi-ai releases carry the model catalog updates that are the whole + # point of bumping it; waiting out the release age would defeat that. + - '@earendil-works/pi-ai@0.81.1' diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 0000000000..bc60dee983 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,284 @@ +#!/bin/sh +# dsh one-line installer. +# +# curl -fsSL https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/master/scripts/install.sh | sh +# +# It clones the harness to ~/.dsh/source, checks host dependencies (git, Node, +# pnpm) and offers to install a missing pnpm, runs `pnpm install` (no build — +# the `bin/dsh` launcher runs the TypeScript source through the repo's own tsx), +# symlinks `dsh` onto PATH, records your API credentials in the Harness home +# (`~/.dsh`) dsh reads at boot, and drops you into `dsh`. +# +# When run from inside an existing checkout (e.g. `sh scripts/install.sh` rather +# than `curl ... | sh`) it reuses that checkout and skips the clone/update, leaving +# the working tree untouched; DSH_REF is ignored in that mode. Setting DSH_SOURCE +# to a different directory opts back into the normal clone/update path. +# +# When run through `curl | sh` the script text arrives on stdin, so every +# prompt and the final launch read the controlling terminal (/dev/tty) directly; +# with no terminal the script prints the manual next steps instead. +# +# Overridable via environment: +# DSH_REF branch or tag to clone/checkout (default: master) +# DSH_REPO clone URL (default: the GitHub repo) +# DSH_SOURCE checkout location (default: ~/.dsh/source) +# DSH_BIN_DIR directory the `dsh` symlink lands in (default: ~/.local/bin) +# DSH_HOME Harness home holding the personal config (default: ~/.dsh) +# FIXME(install-ts): Move the post-checkout workflow into a tested TypeScript +# entrypoint; keep this POSIX shell file as the curl/source bootstrap. +set -eu + +DSH_REF=${DSH_REF:-master} +DSH_REPO=${DSH_REPO:-https://github.com/deepseek-harness/deepseek-harness.git} +# Remember whether the caller pinned a source location before defaulting it, so +# in-repo detection only repoints an unset DSH_SOURCE. +if [ -n "${DSH_SOURCE:-}" ]; then DSH_SOURCE_EXPLICIT=1; else DSH_SOURCE_EXPLICIT=0; fi +DSH_SOURCE=${DSH_SOURCE:-$HOME/.dsh/source} +DSH_BIN_DIR=${DSH_BIN_DIR:-$HOME/.local/bin} + +# --- in-repo detection --------------------------------------------------------- +# Under `curl ... | sh` the script text arrives on stdin, so $0 is the shell +# name and no file path resolves; running a checked-out copy (`sh +# scripts/install.sh`) makes $0 the script file. When $0 is a readable file whose +# parent is a scripts/ dir inside a real dsh checkout (bin/dsh launcher present), +# reuse that checkout and skip the clone. An explicit DSH_SOURCE pointing +# elsewhere opts back into the clone/update path. +IN_REPO=0 +if [ -f "$0" ]; then + _self_dir=$(CDPATH= cd -- "$(dirname -- "$0")" 2>/dev/null && pwd -P) || _self_dir='' + if [ -n "$_self_dir" ]; then + _repo_root=$(dirname -- "$_self_dir") + if [ "$(basename -- "$_self_dir")" = scripts ] \ + && [ -x "$_repo_root/bin/dsh" ] && [ -f "$_repo_root/scripts/install.sh" ]; then + if [ "$DSH_SOURCE_EXPLICIT" = 0 ] || [ "$DSH_SOURCE" = "$_repo_root" ]; then + IN_REPO=1 + DSH_SOURCE=$_repo_root + fi + fi + fi +fi + +# --- terminal-aware prompting -------------------------------------------------- +# stdin is the piped script, so read the controlling terminal for input. +if { true </dev/tty; } 2>/dev/null; then + HAS_TTY=1 + # Restore terminal echo on exit or interrupt: ask_secret disables echo between + # its stty toggles, and dash (a common `sh`) does not run an EXIT trap when the + # shell is killed by a signal, so the fatal signals need their own handler. A + # successful run ends in exec, which replaces this process and drops the traps. + trap 'stty echo </dev/tty 2>/dev/null || true' EXIT + trap 'stty echo </dev/tty 2>/dev/null || true; exit 130' INT TERM HUP +else + HAS_TTY=0 +fi + +# Colour only when writing to a terminal. +if [ -t 1 ]; then + B=$(printf '\033[1m'); DIM=$(printf '\033[2m'); RED=$(printf '\033[31m') + GRN=$(printf '\033[32m'); YEL=$(printf '\033[33m'); RST=$(printf '\033[0m') +else + B=''; DIM=''; RED=''; GRN=''; YEL=''; RST='' +fi + +info() { printf '%s==>%s %s\n' "$GRN" "$RST" "$1"; } +step() { printf '\n%s==>%s %s%s%s\n' "$GRN" "$RST" "$B" "$1" "$RST"; } +warn() { printf '%s warn%s %s\n' "$YEL" "$RST" "$1" >&2; } +die() { printf '%serror%s %s\n' "$RED" "$RST" "$1" >&2; exit 1; } + +# ask PROMPT [DEFAULT] -> answer on stdout (plain-text line). +ask() { + [ "$HAS_TTY" = 1 ] || die "no terminal available for input; re-run in an interactive shell" + printf '%s%s%s ' "$B" "$1" "$RST" >/dev/tty + IFS= read -r _ans </dev/tty || _ans='' + [ -n "$_ans" ] || _ans=${2:-} + printf '%s' "$_ans" +} + +# ask_secret PROMPT -> answer on stdout, with terminal echo suppressed. +ask_secret() { + [ "$HAS_TTY" = 1 ] || die "no terminal available for input; re-run in an interactive shell" + printf '%s%s%s ' "$B" "$1" "$RST" >/dev/tty + stty -echo </dev/tty 2>/dev/null || true + IFS= read -r _sec </dev/tty || _sec='' + stty echo </dev/tty 2>/dev/null || true + printf '\n' >/dev/tty + printf '%s' "$_sec" +} + +# confirm PROMPT [Y] -> exit 0 on yes. Default is no unless second arg is "Y". +confirm() { + _def=${2:-N} + if [ "$HAS_TTY" != 1 ]; then + [ "$_def" = Y ] # non-interactive: take the default + return + fi + if [ "$_def" = Y ]; then _hint='[Y/n]'; else _hint='[y/N]'; fi + printf '%s%s%s %s ' "$B" "$1" "$RST" "$_hint" >/dev/tty + IFS= read -r _r </dev/tty || _r='' + [ -n "$_r" ] || _r=$_def + case "$_r" in [yY]|[yY][eE][sS]) return 0 ;; *) return 1 ;; esac +} + +printf '%s\n' "${B}DeepSeek Harness — dsh installer${RST}" +printf '%ssource %s @ %s%s\n' "$DIM" "$DSH_SOURCE" "$DSH_REF" "$RST" + +# --- 1. dependency check ------------------------------------------------------- +step "Checking dependencies" + +command -v git >/dev/null 2>&1 || die "git is required but not found. Install git, then re-run." +info "git ... ok" + +# Node ^22.19.0 || >=24.0.0 (see the root package.json "engines" field). +node_ok() { + command -v node >/dev/null 2>&1 || return 1 + _v=$(node -v 2>/dev/null) || return 1 + _v=${_v#v} + _major=${_v%%.*} + _rest=${_v#*.} + _minor=${_rest%%.*} + case "$_major" in ''|*[!0-9]*) return 1 ;; esac + case "$_minor" in ''|*[!0-9]*) _minor=0 ;; esac + [ "$_major" -ge 24 ] && return 0 + [ "$_major" -eq 22 ] && [ "$_minor" -ge 19 ] && return 0 + return 1 +} +if node_ok; then + info "node $(node -v) ... ok" +else + if command -v node >/dev/null 2>&1; then + die "Node $(node -v) is unsupported. dsh needs ^22.19.0 || >=24.0.0 — upgrade Node, then re-run." + fi + die "Node is required but not found. Install Node ^22.19.0 || >=24, then re-run." +fi + +# pnpm is the only dependency we offer to install for you. +if command -v pnpm >/dev/null 2>&1; then + info "pnpm $(pnpm --version 2>/dev/null) ... ok" +else + warn "pnpm is not installed." + if confirm "Install pnpm now?" Y; then + if command -v corepack >/dev/null 2>&1 && corepack enable pnpm >/dev/null 2>&1; then + info "enabled pnpm via corepack" + elif command -v npm >/dev/null 2>&1 && npm install -g pnpm >/dev/null 2>&1; then + info "installed pnpm via npm" + else + die "could not install pnpm automatically. Install it (https://pnpm.io/installation), then re-run." + fi + command -v pnpm >/dev/null 2>&1 || die "pnpm still not on PATH after install. Open a new shell, then re-run." + else + die "pnpm is required. Install it (https://pnpm.io/installation), then re-run." + fi +fi + +# --- 2. clone (or update) the source ------------------------------------------ +if [ "$IN_REPO" = 1 ]; then + step "Using existing checkout at $DSH_SOURCE" + info "running from inside the repo — skipping clone (DSH_REF ignored, working tree left untouched)" +else +step "Fetching source into $DSH_SOURCE" +if [ -d "$DSH_SOURCE/.git" ]; then + info "existing checkout found — updating" + git -C "$DSH_SOURCE" fetch --depth 1 origin "$DSH_REF" + # Reset the checkout to the freshly fetched tip. FETCH_HEAD (not + # origin/<ref>) so this resolves for a tag as well as a branch, and -B makes + # the re-run idempotent whether or not DSH_REF changed since the last install. + git -C "$DSH_SOURCE" checkout -q -B "$DSH_REF" FETCH_HEAD +else + mkdir -p "$(dirname "$DSH_SOURCE")" + git clone --depth 1 --branch "$DSH_REF" "$DSH_REPO" "$DSH_SOURCE" +fi +fi + +# --- 3. install dependencies (no build; the launcher runs from source) -------- +step "Installing dependencies with pnpm (this can take a while)" +( cd "$DSH_SOURCE" && pnpm install ) + +[ -x "$DSH_SOURCE/bin/dsh" ] || die "launcher $DSH_SOURCE/bin/dsh missing after install — is DSH_REF a branch that ships apps/cli?" + +# --- 4. put `dsh` on PATH ------------------------------------------------------ +step "Linking dsh into $DSH_BIN_DIR" +mkdir -p "$DSH_BIN_DIR" +ln -sf "$DSH_SOURCE/bin/dsh" "$DSH_BIN_DIR/dsh" +info "linked $DSH_BIN_DIR/dsh -> $DSH_SOURCE/bin/dsh" + +case ":$PATH:" in + *":$DSH_BIN_DIR:"*) ON_PATH=1 ;; + *) ON_PATH=0 ;; +esac +if [ "$ON_PATH" = 0 ]; then + warn "$DSH_BIN_DIR is not on your PATH." + _line="export PATH=\"$DSH_BIN_DIR:\$PATH\"" + _rc='' + _sh=${SHELL:-} # SHELL may be unset; word-removal on an unset var trips set -u under dash. + case "${_sh##*/}" in + zsh) _rc="$HOME/.zshrc" ;; + bash) _rc="$HOME/.bashrc" ;; + esac + if [ -n "$_rc" ] && [ -f "$_rc" ] && grep -qF "$_line" "$_rc" 2>/dev/null; then + info "$_rc already exports $DSH_BIN_DIR — open a new shell to pick it up" + elif [ -n "$_rc" ] && confirm "Add it to $_rc?" Y; then + printf '\n# Added by the dsh installer\n%s\n' "$_line" >>"$_rc" + info "updated $_rc — run 'source $_rc' or open a new shell to pick it up" + else + warn "add this line to your shell profile yourself:" + printf ' %s\n' "$_line" + fi +fi + +# --- 5. credentials ------------------------------------------------------------ +# Mirror app-boot's resolveDshHome precedence ($DSH_HOME, else ~/.dsh) so creds land where dsh reads them. +if [ -n "${DSH_HOME:-}" ]; then + CONF="$DSH_HOME" +else + CONF="$HOME/.dsh" +fi +ENV_FILE="$CONF/.env" + +step "Configuring credentials" +if [ -f "$ENV_FILE" ] && grep -q '^DEEPSEEK_API_KEY=' "$ENV_FILE" 2>/dev/null; then + info "DEEPSEEK_API_KEY already set in $ENV_FILE" + if ! confirm "Replace it?" N; then + SKIP_CREDS=1 + fi +fi +if [ "${SKIP_CREDS:-0}" != 1 ]; then + if [ "$HAS_TTY" = 1 ]; then + API_KEY=$(ask_secret "DeepSeek API key (input hidden):") + if [ -z "$API_KEY" ]; then + warn "no key entered — skipping. Set DEEPSEEK_API_KEY in $ENV_FILE before using dsh." + else + BASE_URL=$(ask "DeepSeek base URL (optional, Enter to skip):") + mkdir -p "$CONF" + # The installer owns exactly the two DEEPSEEK_* lines; any other lines the + # user keeps in this .env are preserved. The rewrite happens in a subshell + # so umask 077 (which closes the create-time permission race) does not leak + # into the exec'd dsh, and lands atomically via a same-dir temp + mv. + _tmp="$ENV_FILE.dsh.$$" + ( + umask 077 + if [ -f "$ENV_FILE" ]; then + grep -v -e '^DEEPSEEK_API_KEY=' -e '^DEEPSEEK_BASE_URL=' "$ENV_FILE" >"$_tmp" || true + else + : >"$_tmp" + fi + printf 'DEEPSEEK_API_KEY=%s\n' "$API_KEY" >>"$_tmp" + if [ -n "$BASE_URL" ]; then printf 'DEEPSEEK_BASE_URL=%s\n' "$BASE_URL" >>"$_tmp"; fi + ) + mv "$_tmp" "$ENV_FILE" + chmod 600 "$ENV_FILE" 2>/dev/null || true + info "wrote $ENV_FILE" + fi + else + warn "no terminal for credential input — set DEEPSEEK_API_KEY in $ENV_FILE before using dsh." + fi +fi + +# --- 6. launch ----------------------------------------------------------------- +step "Done" +if [ "$HAS_TTY" = 1 ]; then + info "launching dsh — run 'dsh' anytime to start again" + exec "$DSH_BIN_DIR/dsh" </dev/tty +else + info "install complete. Start it with:" + printf ' %s\n' "$DSH_BIN_DIR/dsh" +fi diff --git a/scripts/prepare-ci-bubblewrap.sh b/scripts/prepare-ci-bubblewrap.sh new file mode 100755 index 0000000000..00a513db8f --- /dev/null +++ b/scripts/prepare-ci-bubblewrap.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Ubuntu's package transaction scans the hosted image's full dpkg database and +# runs post-install hooks. CI needs only the signed-archive payload, so pin and +# verify that payload before extracting it into the ephemeral runner directory. +readonly BUBBLEWRAP_VERSION='0.9.0-1ubuntu0.1' +readonly BUBBLEWRAP_SHA256='1b506492bd9c7fd0cdb4f02ac822f1d3e336b0aead5113c1239baf8db5db562a' +readonly BUBBLEWRAP_URL="https://archive.ubuntu.com/ubuntu/pool/main/b/bubblewrap/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb" + +: "${RUNNER_TEMP:?prepare-ci-bubblewrap requires RUNNER_TEMP}" +: "${GITHUB_PATH:?prepare-ci-bubblewrap requires GITHUB_PATH}" + +if [[ "$(uname -s)" != 'Linux' || "$(uname -m)" != 'x86_64' ]]; then + echo 'prepare-ci-bubblewrap supports only Linux x86_64 hosted runners' >&2 + exit 1 +fi + +archive="${RUNNER_TEMP}/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb" +root="${RUNNER_TEMP}/dsh-bubblewrap" + +curl --fail --silent --show-error --location --retry 3 --output "$archive" "$BUBBLEWRAP_URL" +printf '%s %s\n' "$BUBBLEWRAP_SHA256" "$archive" | sha256sum --check --status +mkdir -p "$root" +dpkg-deb --extract "$archive" "$root" +printf '%s\n' "$root/usr/bin" >> "$GITHUB_PATH" + +sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 \ + || echo 'apparmor userns knob absent — the functional probe decides' +"$root/usr/bin/bwrap" --version +"$root/usr/bin/bwrap" --ro-bind / / --dev /dev --proc /proc --die-with-parent -- true +echo 'bubblewrap functional probe passed' diff --git a/scripts/project-doc-site.spec.ts b/scripts/project-doc-site.spec.ts index bd6cfb14c7..7d1c3c1550 100644 --- a/scripts/project-doc-site.spec.ts +++ b/scripts/project-doc-site.spec.ts @@ -1,13 +1,19 @@ /** Tests for the documentation website projection adapter. */ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { join, resolve } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { docsPages, type DocsPage } from '../website/docs.ts' import { addProjectionFrontmatter, projectedPageContent, rewriteMarkdown } from './project-doc-site.ts' const roots: string[] = [] +const repositoryRoot = resolve(import.meta.dirname, '..') + +function unexpectedWebsiteMarkdown(files: readonly string[]): string[] { + return files.filter(file => file.endsWith('.md') && file !== 'website/AGENTS.md').sort() +} afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) @@ -34,6 +40,29 @@ function fixture(): { root: string; pages: DocsPage[] } { } } +describe('website source layout', () => { + it('rejects Markdown outside the subtree instructions', () => { + expect(unexpectedWebsiteMarkdown([ + 'website/AGENTS.md', + 'website/docs.ts', + 'website/zh-CN/api/harness/service.md', + ])).toEqual(['website/zh-CN/api/harness/service.md']) + }) + + it('contains no tracked or unignored documentation copies', () => { + const files = execFileSync( + 'git', + ['ls-files', '--cached', '--others', '--exclude-standard', '--', 'website'], + { cwd: repositoryRoot, encoding: 'utf8' }, + ).split('\n').filter(file => file !== '' && existsSync(resolve(repositoryRoot, file))) + + expect( + unexpectedWebsiteMarkdown(files), + 'Keep canonical Markdown under docs/ and publish it through website/docs.ts.', + ).toEqual([]) + }) +}) + describe('rewriteMarkdown', () => { it('maps published pages and pins unpublished source links', () => { const { root, pages } = fixture() diff --git a/scripts/publint-all.spec.ts b/scripts/publint-all.spec.ts new file mode 100644 index 0000000000..22dd80d6b0 --- /dev/null +++ b/scripts/publint-all.spec.ts @@ -0,0 +1,61 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { spawnSync } from 'node:child_process' +import { afterEach, describe, expect, it } from 'vitest' + +const repositoryRoot = fileURLToPath(new URL('..', import.meta.url)) +const runner = fileURLToPath(new URL('./publint-all.ts', import.meta.url)) +const roots: string[] = [] + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +function fixture(exportPath = './lib/index.js'): string { + const root = mkdtempSync(join(tmpdir(), 'dsh-publint-all-')) + roots.push(root) + const packageDir = join(root, 'packages/core/probe') + mkdirSync(join(packageDir, 'lib'), { recursive: true }) + writeFileSync(join(packageDir, 'package.json'), `${JSON.stringify({ + name: '@deepseek-ai/dsh-probe', + version: '0.0.1', + type: 'module', + license: 'MIT', + engines: { node: '>=22.19' }, + sideEffects: false, + files: ['lib'], + exports: { '.': { default: exportPath } }, + }, null, 2)}\n`) + writeFileSync(join(packageDir, 'README.md'), '# Probe\n') + writeFileSync(join(packageDir, 'lib/index.js'), 'export const probe = true\n') + writeFileSync(join(packageDir, 'unpublished.js'), 'export const hidden = true\n') + return root +} + +function run(root: string) { + return spawnSync(process.execPath, [ + '--import', 'tsx', runner, + '--packages-root', root, + ], { + cwd: repositoryRoot, + encoding: 'utf8', + timeout: 5_000, + }) +} + +describe('publint package runner', () => { + it('lints recursively declared files from an in-memory publication view', () => { + const result = run(fixture()) + expect(result.status, result.stderr).toBe(0) + expect(result.stdout).toContain('linting 1 package(s)') + expect(result.stdout).toContain('All good!') + }) + + it('rejects an export that exists in the workspace but is not published', () => { + const result = run(fixture('./unpublished.js')) + expect(result.status).toBe(1) + expect(result.stdout).toContain('unpublished.js') + }) +}) diff --git a/scripts/publint-all.ts b/scripts/publint-all.ts index 0911316f18..2ed1906763 100644 --- a/scripts/publint-all.ts +++ b/scripts/publint-all.ts @@ -1,46 +1,53 @@ -import { execFile } from 'node:child_process' -import { existsSync, readdirSync } from 'node:fs' +/** Run publint over the exact manifest-declared publication view of every package. */ + +import { + globSync, + readFileSync, + readdirSync, + statSync, +} from 'node:fs' import { availableParallelism } from 'node:os' -import { resolve } from 'node:path' -import { promisify } from 'node:util' +import { dirname, relative, resolve, sep } from 'node:path' +import { publint, type Message, type PackFile } from 'publint' +import { formatMessage } from 'publint/utils' -const execFileAsync = promisify(execFile) const CONCURRENCY_ENV = 'DSH_PUBLINT_CONCURRENCY' +const repositoryRoot = resolve(import.meta.dirname, '..') +const options = parseOptions(process.argv.slice(2)) +const packagesRoot = resolve(options.get('--packages-root') ?? repositoryRoot) -// Discover harness packages at packages/<group>/<pkg>; group containers, -// examples, and private vendored sources are not package targets. -const root = resolve(import.meta.dirname, '..') -const packagesRoot = resolve(root, 'packages') +interface PackageTarget { + path: string + directory: string + manifest: PackageManifest +} -// Run publint's JS CLI through the current node, not the .bin shim: the -// extensionless shim isn't spawnable on Windows (CVE-2024-27980) and the .cmd -// variant needs shell:true, which space-joins args UNESCAPED (DEP0190) and -// breaks when the repo path contains spaces. The JS entry is identical on every -// platform (`bin` is `./src/cli.js` per publint's package.json). -const publintCli = resolve(root, 'node_modules/publint/src/cli.js') +interface PackageManifest { + name?: string + files?: unknown +} type PublintResult = - | { path: string; status: 'passed'; stdout: string; stderr: string } - | { path: string; status: 'failed'; stdout: string; stderr: string; message: string } + | { path: string; status: 'passed'; messages: Message[]; manifest: Record<string, unknown> } + | { path: string; status: 'failed'; messages: Message[]; manifest: Record<string, unknown>; failure?: string } -function workspacePackages(): string[] { - return readdirSync(packagesRoot, { withFileTypes: true }) - .filter(group => group.isDirectory()) - .flatMap(group => - readdirSync(resolve(packagesRoot, group.name), { withFileTypes: true }) - .filter(pkg => pkg.isDirectory()) - .filter(pkg => existsSync(resolve(packagesRoot, group.name, pkg.name, 'package.json'))) - .map(pkg => `packages/${group.name}/${pkg.name}`), - ) +function workspacePackages(): PackageTarget[] { + return globSync('packages/*/*/package.json', { cwd: packagesRoot }) + .sort() + .map((manifestPath) => { + const absoluteManifestPath = resolve(packagesRoot, manifestPath) + const manifest = JSON.parse(readFileSync(absoluteManifestPath, 'utf8')) as PackageManifest + return { path: dirname(manifestPath), directory: dirname(absoluteManifestPath), manifest } + }) } function publintConcurrency(total: number): number { if (total === 0) return 0 const raw = process.env[CONCURRENCY_ENV] - if (raw !== undefined) { + if (raw !== undefined && raw !== '') { const parsed = Number.parseInt(raw, 10) - if (!Number.isSafeInteger(parsed) || parsed < 1) { + if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) { throw new Error(`publint-all: ${CONCURRENCY_ENV} must be a positive integer, got ${JSON.stringify(raw)}.`) } return Math.min(total, parsed) @@ -49,57 +56,106 @@ function publintConcurrency(total: number): number { return Math.min(total, availableParallelism()) } -function outputText(value: unknown): string { - if (typeof value === 'string') return value - if (Buffer.isBuffer(value)) return value.toString() - return '' +function publicationFiles(target: PackageTarget): PackFile[] { + const paths = new Set<string>() + addPath(resolve(target.directory, 'package.json'), paths) + const declared = Array.isArray(target.manifest.files) + ? target.manifest.files.filter((value): value is string => typeof value === 'string') + : [] + for (const pattern of [ + ...declared, + 'README*', + 'LICENSE*', + 'LICENCE*', + 'CHANGELOG*', + 'CHANGES*', + 'HISTORY*', + 'NOTICE*', + ]) { + for (const match of globSync(pattern, { cwd: target.directory })) { + addPath(resolve(target.directory, match), paths) + } + } + + return [...paths] + .sort() + .map(path => ({ + name: `package/${relative(target.directory, path).split(sep).join('/')}`, + data: readFileSync(path), + })) } -async function runPublint(path: string): Promise<PublintResult> { +function addPath(path: string, paths: Set<string>): void { + const stat = statSync(path) + if (stat.isDirectory()) { + for (const entry of readdirSync(path)) addPath(resolve(path, entry), paths) + } else if (stat.isFile()) { + paths.add(path) + } +} + +async function runPublint(target: PackageTarget): Promise<PublintResult> { try { - const { stdout, stderr } = await execFileAsync(process.execPath, [publintCli, path], { - cwd: root, - encoding: 'utf8', - maxBuffer: 10 * 1024 * 1024, + const result = await publint({ + pkgDir: 'package', + pack: { files: publicationFiles(target) }, }) - return { path, status: 'passed', stdout, stderr } + const manifest = result.pkg as Record<string, unknown> + return result.messages.some(message => message.type === 'error') + ? { path: target.path, status: 'failed', messages: result.messages, manifest } + : { path: target.path, status: 'passed', messages: result.messages, manifest } } catch (error: unknown) { - const failed = error as { stdout?: unknown; stderr?: unknown; message?: string } return { - path, + path: target.path, status: 'failed', - stdout: outputText(failed.stdout), - stderr: outputText(failed.stderr), - message: failed.message ?? 'publint failed', + messages: [], + manifest: target.manifest as Record<string, unknown>, + failure: error instanceof Error ? error.message : String(error), } } } -async function runAll(paths: string[], concurrency: number): Promise<PublintResult[]> { +async function runAll(targets: PackageTarget[], concurrency: number): Promise<PublintResult[]> { let next = 0 const results: Array<PublintResult | undefined> = [] await Promise.all(Array.from({ length: concurrency }, async () => { for (;;) { const index = next next += 1 - const path = paths[index] - if (path === undefined) return - results[index] = await runPublint(path) + const target = targets[index] + if (target === undefined) return + results[index] = await runPublint(target) } })) - return paths.map((path, index) => { + return targets.map((target, index) => { const result = results[index] - if (result === undefined) throw new Error(`publint-all: missing result for ${path}.`) + if (result === undefined) throw new Error(`publint-all: missing result for ${target.path}.`) return result }) } function printResult(result: PublintResult): void { console.log(`Running publint for ${result.path}...`) - process.stdout.write(result.stdout) - process.stderr.write(result.stderr) - if (result.status === 'failed') console.error(result.message) + if ('failure' in result) console.error(result.failure) + for (const message of result.messages) { + console.log(formatMessage(message, result.manifest, { color: false }) ?? message.code) + } + if (result.status === 'passed' && result.messages.length === 0) console.log('All good!') +} + +function parseOptions(args: string[]): Map<string, string> { + const parsed = new Map<string, string>() + for (let index = 0; index < args.length; index += 2) { + const name = args[index] + const value = args[index + 1] + if (name !== '--packages-root' || value === undefined || value.startsWith('--')) { + throw new Error(`publint-all: expected [--packages-root PATH], got ${JSON.stringify(args)}.`) + } + if (parsed.has(name)) throw new Error(`publint-all: duplicate option ${name}.`) + parsed.set(name, value) + } + return parsed } const packages = workspacePackages() diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 964fe7ef7e..59ee171572 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -16,6 +16,9 @@ type Mode = | 'ci-coverage' | 'ci-snapshot' | 'ci-artifacts' + | 'ci-windows-blocking' + | 'ci-windows-complete' + | 'ci-windows-observational' | 'node-compat' | 'pre-push' | 'manual-push' @@ -32,6 +35,7 @@ interface Gate { env?: Record<string, string | undefined> input?: string verify?: (result: GateResult) => Promise<void> + allowFailure?: boolean } interface GateResult { @@ -77,7 +81,9 @@ console.log(`run-gates: ${mode} running ${gates.length} gate(s) with ${maxConcur const results = await runGates(gates, maxConcurrency) printSummary(results, performance.now() - startedAt) -if (results.some(result => result.status === 'failed' || result.status === 'skipped')) process.exit(1) +if (results.some(result => result.gate.allowFailure !== true && (result.status === 'failed' || result.status === 'skipped'))) { + process.exit(1) +} function parseMode(raw: string | undefined): Mode { switch (raw) { @@ -87,13 +93,17 @@ function parseMode(raw: string | undefined): Mode { case 'ci-coverage': case 'ci-snapshot': case 'ci-artifacts': + case 'ci-windows-blocking': + case 'ci-windows-complete': + case 'ci-windows-observational': case 'node-compat': case 'pre-push': + case 'manual-push': case 'doc-sync': return raw default: throw new Error( - `run-gates: expected mode ci-primary | ci-static | ci-lint | ci-coverage | ci-snapshot | ci-artifacts | node-compat | pre-push | doc-sync, got ${JSON.stringify(raw)}.`, + `run-gates: expected mode ci-primary | ci-static | ci-lint | ci-coverage | ci-snapshot | ci-artifacts | ci-windows-blocking | ci-windows-complete | ci-windows-observational | node-compat | pre-push | manual-push | doc-sync, got ${JSON.stringify(raw)}.`, ) } } @@ -167,31 +177,19 @@ function gatesForMode(selected: Mode): Gate[] { pnpmScript('duplication', 'duplication'), ] case 'ci-coverage': - return [ - pnpmScript('build', 'build'), - coverageGate(), - ] + return [coverageGate()] case 'ci-snapshot': - return [ - pnpmScript('build', 'build'), - snapshotGate(), - ] + return [pnpmScript('build', 'build'), snapshotGate()] case 'ci-artifacts': return ciArtifactGates() + case 'ci-windows-blocking': + return ciWindowsBlockingGates() + case 'ci-windows-complete': + return ciWindowsCompleteGates() + case 'ci-windows-observational': + return ciWindowsObservationalGates() case 'node-compat': - return [ - pnpmScript('typecheck', 'typecheck'), - pnpmExec('source-worker-smoke', [ - 'vitest', - 'run', - 'packages/workflow/workflow-workerthread/tests/source-worker.compat.spec.ts', - ], { label: 'source worker smoke' }), - pnpmExec('jsonl-zstd-smoke', [ - 'vitest', - 'run', - 'packages/session-persistence/session-persistence-jsonl/tests/zstd.compat.spec.ts', - ], { label: 'JSONL Zstandard smoke' }), - ] + return nodeCompatGates() case 'pre-push': return [] case 'manual-push': return [ @@ -225,11 +223,12 @@ function ciPrimaryGates(): Gate[] { lintGate(), pnpmScript('duplication', 'duplication'), coverageGate(), + ...nodeCompatSmokeGates(), snapshotGate(), ...docSyncLeafGates(), pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }), pnpmScript('knip', 'knip'), - pnpmScript('build', 'build', { needs: ['typecheck'] }), + pnpmScript('build', 'build'), pnpmScript('publint', 'publint', { needs: ['build'] }), pnpmScript('node-next-types', 'verify-node-next-types', { label: 'node-next types', @@ -240,13 +239,40 @@ function ciPrimaryGates(): Gate[] { ] } +function nodeCompatGates(): Gate[] { + return [ + ...flagEnabled('DSH_NODE_COMPAT_SKIP_TYPECHECK') ? [] : [pnpmScript('typecheck', 'typecheck')], + ...nodeCompatSmokeGates(), + ] +} + +function nodeCompatSmokeGates(): Gate[] { + return [ + pnpmExec('source-worker-smoke', [ + 'vitest', + 'run', + 'packages/workflow/workflow-workerthread/tests/source-worker.compat.spec.ts', + ], { label: 'source worker smoke' }), + pnpmExec('jsonl-zstd-smoke', [ + 'vitest', + 'run', + 'packages/session-persistence/session-persistence-jsonl/tests/zstd.compat.spec.ts', + ], { label: 'JSONL Zstandard smoke' }), + ] +} + function ciStaticGates(): Gate[] { return [ pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }), pnpmScript('constraints', 'constraints'), pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }), pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }), - ...docSyncLeafGates(), + pnpmScript('build', 'build'), + ...docSyncLeafGates({ + docTypecheckNeeds: ['build'], + docTypecheckEnv: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' }, + docsBuildScript: 'docs:build:mpa', + }), pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }), pnpmScript('knip', 'knip'), ] @@ -265,11 +291,54 @@ function ciArtifactGates(): Gate[] { ] } -function lintGate(): Gate { +function ciWindowsBlockingGates(): Gate[] { + return [ + pnpmScript('windows-build', 'build', { label: 'build' }), + pnpmScript('windows-site', 'docs:build', { label: 'production site' }), + ] +} + +function ciWindowsCompleteGates(): Gate[] { + const observational = ciWindowsObservationalGates() + // The required production site replaces the observational MPA build; both + // VitePress modes write the same output directory and cannot overlap. + .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build') + .map(gate => ({ ...gate, allowFailure: true })) + return [ + pnpmScript('build', 'build'), + pnpmScript('windows-site', 'docs:build', { label: 'production site' }), + ...observational, + ] +} + +function ciWindowsObservationalGates(): Gate[] { + return [ + ...ciStaticGates(), + lintGate(), + pnpmScript('duplication', 'duplication'), + { + ...coverageGate(), + env: { DSH_EXAMPLE_MODE: 'lib' }, + needs: ['build'], + }, + snapshotGate(), + pnpmScript('publint', 'publint', { needs: ['build'] }), + pnpmScript('node-next-types', 'verify-node-next-types', { + label: 'node-next types', + needs: ['build'], + }), + builtPackageInvariantsGate(['build']), + builtBinSmokeGate(), + ] +} + +function lintGate(eslintTargets: readonly string[] = ['.']): Gate { + const concurrencyArgs = eslintConcurrencyArgs() if (process.env.DSH_ESLINT_CACHE === '1') { return pnpmExec('lint', [ 'eslint', - '.', + ...eslintTargets, + ...concurrencyArgs, '--cache', '--cache-location', '.cache/eslint/', @@ -280,11 +349,28 @@ function lintGate(): Gate { env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') }, }) } + if (concurrencyArgs.length > 0) { + return pnpmExec('lint', ['eslint', ...eslintTargets, ...concurrencyArgs], { + label: 'lint', + env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') }, + }) + } return pnpmScript('lint', 'lint', { env: { NODE_OPTIONS: nodeOptions('--max-old-space-size=8192') }, }) } +function eslintConcurrencyArgs(): string[] { + const raw = process.env.DSH_ESLINT_CONCURRENCY + if (raw === undefined || raw === '') return [] + if (raw === 'auto') return ['--concurrency=auto'] + const parsed = Number.parseInt(raw, 10) + if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) { + throw new Error(`run-gates: DSH_ESLINT_CONCURRENCY must be a positive integer or auto, got ${JSON.stringify(raw)}.`) + } + return [`--concurrency=${raw}`] +} + function coverageGate(): Gate { return pnpmExec('coverage', [ 'vitest', @@ -293,8 +379,6 @@ function coverageGate(): Gate { ...positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers'), ], { label: 'test:coverage', - env: { DSH_EXAMPLE_MODE: 'lib' }, - needs: ['build'], }) } @@ -325,6 +409,13 @@ function positiveIntArg(envName: string, flag: string): string[] { return [`${flag}=${raw}`] } +function flagEnabled(envName: string): boolean { + const raw = process.env[envName] + if (raw === undefined || raw === '') return false + if (raw !== '1') throw new Error(`run-gates: ${envName} must be 1 when set, got ${JSON.stringify(raw)}.`) + return true +} + function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] { const artifactOptions = options.artifactNeeds === undefined ? {} : { needs: options.artifactNeeds } return [ @@ -343,6 +434,7 @@ function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] { function docSyncLeafGates(options: { docTypecheckNeeds?: string[] docTypecheckEnv?: Record<string, string | undefined> + docsBuildScript?: 'docs:build' | 'docs:build:mpa' } = {}): Gate[] { const docTypecheckOptions: Partial<Gate> = {} if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds @@ -369,8 +461,11 @@ function docSyncLeafGates(options: { pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }), pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }), pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }), - // Keep the VitePress build in this single gate because projection rewrites website/.generated. - pnpmScript('docs-site', 'docs:check', { label: 'documentation site' }), + pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts'], { + label: 'documentation projection', + }), + // Keep the VitePress build itself in one gate because projection rewrites website/.generated. + pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }), pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }), ] } @@ -540,7 +635,8 @@ function printSummary(results: GateResult[], durationMs: number): void { for (const result of unsuccessful) { const duration = (result.durationMs / 1000).toFixed(2) const reason = result.error ?? (result.exitCode === null ? 'no exit code' : `exit ${result.exitCode}`) - console.error(` - ${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`) + const disposition = result.gate.allowFailure === true ? 'NON-BLOCKING ' : '' + console.error(` - ${disposition}${result.status.toUpperCase()} ${result.gate.label} (${duration}s, ${reason})`) console.error(` ${result.gate.displayCommand}`) } } diff --git a/scripts/verify-built-package-invariants.mjs b/scripts/verify-built-package-invariants.mjs index 4b298946d1..9c672e05f0 100644 --- a/scripts/verify-built-package-invariants.mjs +++ b/scripts/verify-built-package-invariants.mjs @@ -1,102 +1,106 @@ -/** Verify every packed companion through its package self-reference under plain Node. */ +/** Verify every compiled companion through its staged package self-reference under plain Node. */ -import { spawnSync } from 'node:child_process' import { copyFileSync, + cpSync, + existsSync, globSync, mkdirSync, mkdtempSync, readFileSync, rmSync, + writeFileSync, } from 'node:fs' import { dirname, resolve } from 'node:path' import { pathToFileURL } from 'node:url' -const root = resolve(import.meta.dirname, '..') -const loaderUrl = pathToFileURL(resolve(root, 'vendor/loader/lib/index.js')).href +const repositoryRoot = resolve(import.meta.dirname, '..') +const options = parseOptions(process.argv.slice(2)) +const packagesRoot = resolve(options.get('--packages-root') ?? repositoryRoot) +const loaderUrl = options.get('--loader-url') + ?? pathToFileURL(resolve(repositoryRoot, 'vendor/loader/lib/index.js')).href const failures = [] -const manifests = globSync('packages/*/*/package.json', { cwd: root }).sort() -const packArgs = ['pack', '--dry-run', '--json', '--ignore-scripts'] -// Windows cannot spawn npm's .cmd shim directly; setup-node installs this JS -// entrypoint beside node.exe, so the probe stays shell-free on every runner. -const npmInvocation = process.platform === 'win32' - ? [process.execPath, [resolve(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'), ...packArgs]] - : ['npm', packArgs] +const manifests = globSync('packages/*/*/package.json', { cwd: packagesRoot }).sort() +const { default: Loader } = await import(loaderUrl) +const loader = Object.create(Loader.prototype) for (const manifestPath of manifests) { - const packageDir = dirname(resolve(root, manifestPath)) - const manifest = JSON.parse(readFileSync(resolve(root, manifestPath), 'utf8')) + const packageDir = dirname(resolve(packagesRoot, manifestPath)) + const manifest = JSON.parse(readFileSync(resolve(packagesRoot, manifestPath), 'utf8')) const packageName = manifest.name if (typeof packageName !== 'string' || packageName.length === 0) { failures.push(`${manifestPath}: missing package name`) continue } - - const pack = spawnSync(npmInvocation[0], npmInvocation[1], { - cwd: packageDir, - encoding: 'utf8', - }) - if (pack.status !== 0) { - const detail = pack.error?.message - ?? (pack.stderr.trim() || pack.stdout.trim() || `npm pack exited ${pack.status}`) - failures.push(`${packageName}: ${detail}`) + const invariantExport = manifest.exports?.['./invariant'] + if (typeof invariantExport !== 'object' + || invariantExport.default !== './lib/invariant.js' + || !manifest.files?.includes('lib/invariant.js')) { + failures.push(`${packageName}: manifest does not publish ./lib/invariant.js as ./invariant`) continue } - let files - try { - const result = JSON.parse(pack.stdout) - files = result[0]?.files - if (!Array.isArray(files)) throw new Error('npm pack returned no file inventory') - } catch (error) { - failures.push(`${packageName}: cannot parse npm pack inventory: ${String(error)}`) - continue - } - - // Keep the packed view below its owning package so Node reaches the real + // Keep the staged view below its owning package so Node reaches the real // pnpm dependency links. Junctioning node_modules elsewhere breaks pnpm's - // relative workspace links on Windows. - const stagedPackageDir = mkdtempSync(resolve(packageDir, '.dsh-packed-invariant-')) + // relative workspace links on Windows. Copy the manifest-declared lib view + // so a companion that imports an undeclared runtime chunk fails here. + const stagedPackageDir = mkdtempSync(resolve(packageDir, '.dsh-built-invariant-')) try { - for (const file of files) { - if (typeof file.path !== 'string' - || (file.path !== 'package.json' && !file.path.startsWith('lib/'))) continue - const target = resolve(stagedPackageDir, file.path) - mkdirSync(dirname(target), { recursive: true }) - copyFileSync(resolve(packageDir, file.path), target) - } - - const probe = ` - const companion = await import(${JSON.stringify(`${packageName}/invariant`)}); - const { default: Loader } = await import(${JSON.stringify(loaderUrl)}); - if ('default' in companion) throw new Error('companion has a default export'); - const loader = Object.create(Loader.prototype); - const unwrapped = loader.unwrapExports(companion); - if (unwrapped !== companion) throw new Error('Loader collapsed the companion namespace'); - if (typeof unwrapped.name !== 'string') throw new Error('companion name is missing'); - if (!Array.isArray(unwrapped.inject) || !unwrapped.inject.includes('invariants')) { - throw new Error('companion does not inject invariants'); - } - if (typeof unwrapped.apply !== 'function') throw new Error('companion apply is missing'); - ` - const result = spawnSync(process.execPath, ['--input-type=module', '--eval', probe], { - cwd: stagedPackageDir, - encoding: 'utf8', - }) - if (result.status !== 0) { - const detail = result.error?.message - ?? (result.stderr.trim() || result.stdout.trim() || `node exited ${result.status}`) - failures.push(`${packageName}: ${detail}`) + copyFileSync(resolve(packageDir, 'package.json'), resolve(stagedPackageDir, 'package.json')) + copyDeclaredLibFiles(packageDir, stagedPackageDir, manifest.files) + const probePath = resolve(stagedPackageDir, 'probe.mjs') + writeFileSync( + probePath, + `import * as companion from ${JSON.stringify(`${packageName}/invariant`)}\nexport default companion\n`, + ) + const { default: companion } = await import(pathToFileURL(probePath).href) + if ('default' in companion) throw new Error('companion has a default export') + const unwrapped = loader.unwrapExports(companion) + if (unwrapped !== companion) throw new Error('Loader collapsed the companion namespace') + if (typeof unwrapped.name !== 'string') throw new Error('companion name is missing') + if (!Array.isArray(unwrapped.inject) || !unwrapped.inject.includes('invariants')) { + throw new Error('companion does not inject invariants') } + if (typeof unwrapped.apply !== 'function') throw new Error('companion apply is missing') + } catch (error) { + failures.push(`${packageName}: ${error instanceof Error ? error.message : String(error)}`) } finally { rmSync(stagedPackageDir, { recursive: true, force: true }) } } if (failures.length > 0) { - console.error('verify-built-package-invariants: packed companion failures:') + console.error('verify-built-package-invariants: compiled companion failures:') for (const failure of failures) console.error(` ${failure}`) process.exit(1) } -console.log(`verify-built-package-invariants: ${manifests.length} packed companion(s) passed plain-Node Loader checks.`) +console.log(`verify-built-package-invariants: ${manifests.length} compiled companion(s) passed plain-Node Loader checks.`) + +function parseOptions(args) { + const allowed = new Set(['--packages-root', '--loader-url']) + const parsed = new Map() + for (let index = 0; index < args.length; index += 2) { + const name = args[index] + const value = args[index + 1] + if (!allowed.has(name) || value === undefined || value.startsWith('--')) { + throw new Error(`verify-built-package-invariants: expected [--packages-root PATH] [--loader-url URL], got ${JSON.stringify(args)}.`) + } + if (parsed.has(name)) throw new Error(`verify-built-package-invariants: duplicate option ${name}.`) + parsed.set(name, value) + } + return parsed +} + +function copyDeclaredLibFiles(packageDir, stagedPackageDir, files) { + for (const pattern of files) { + if (!pattern.startsWith('lib/')) continue + for (const relativePath of globSync(pattern, { cwd: packageDir })) { + const source = resolve(packageDir, relativePath) + if (!existsSync(source)) continue + const target = resolve(stagedPackageDir, relativePath) + mkdirSync(dirname(target), { recursive: true }) + cpSync(source, target, { recursive: true }) + } + } +} diff --git a/scripts/verify-built-package-invariants.spec.ts b/scripts/verify-built-package-invariants.spec.ts new file mode 100644 index 0000000000..4863e30c54 --- /dev/null +++ b/scripts/verify-built-package-invariants.spec.ts @@ -0,0 +1,88 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { spawnSync } from 'node:child_process' +import { afterEach, describe, expect, it } from 'vitest' + +const verifier = fileURLToPath(new URL('./verify-built-package-invariants.mjs', import.meta.url)) +const roots: string[] = [] + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +function fixture(options: { + invariantSource?: string + invariantExport?: string + runtimeChunk?: string +} = {}): { root: string; loaderUrl: string } { + const root = mkdtempSync(join(tmpdir(), 'dsh-built-package-invariants-')) + roots.push(root) + const packageDir = join(root, 'packages/core/probe') + mkdirSync(join(packageDir, 'lib'), { recursive: true }) + writeFileSync(join(packageDir, 'package.json'), `${JSON.stringify({ + name: '@deepseek-ai/dsh-probe', + type: 'module', + files: ['lib/invariant.js'], + exports: { + './invariant': { + default: options.invariantExport ?? './lib/invariant.js', + }, + }, + }, null, 2)}\n`) + writeFileSync( + join(packageDir, 'lib/invariant.js'), + options.invariantSource ?? "export const name = 'probe-invariant'\nexport const inject = ['invariants']\nexport const apply = () => {}\n", + ) + if (options.runtimeChunk !== undefined) { + writeFileSync(join(packageDir, 'lib/chunk.js'), options.runtimeChunk) + } + const loaderPath = join(root, 'loader.mjs') + writeFileSync(loaderPath, 'export default class Loader { unwrapExports(value) { return value } }\n') + return { root, loaderUrl: pathToFileURL(loaderPath).href } +} + +function verify(root: string, loaderUrl: string) { + return spawnSync(process.execPath, [ + verifier, + '--packages-root', root, + '--loader-url', loaderUrl, + ], { + encoding: 'utf8', + timeout: 5_000, + }) +} + +describe('built package invariant verifier', () => { + it('loads the staged compiled self-reference through plain Node and Loader normalization', () => { + const { root, loaderUrl } = fixture() + const result = verify(root, loaderUrl) + expect(result.status, result.stderr).toBe(0) + expect(result.stdout).toContain('1 compiled companion(s) passed plain-Node Loader checks') + }) + + it('rejects a default export and a broken invariant export map', () => { + const withDefault = fixture({ + invariantSource: "export default {}\nexport const name = 'probe-invariant'\nexport const inject = ['invariants']\nexport const apply = () => {}\n", + }) + const defaultResult = verify(withDefault.root, withDefault.loaderUrl) + expect(defaultResult.status).toBe(1) + expect(defaultResult.stderr).toContain('companion has a default export') + + const brokenExport = fixture({ invariantExport: './lib/missing.js' }) + const exportResult = verify(brokenExport.root, brokenExport.loaderUrl) + expect(exportResult.status).toBe(1) + expect(exportResult.stderr).toContain('@deepseek-ai/dsh-probe') + }) + + it('rejects an invariant bundle that needs an unstaged runtime chunk', () => { + const { root, loaderUrl } = fixture({ + invariantSource: "export * from './chunk.js'\n", + runtimeChunk: "export const name = 'probe-invariant'\nexport const inject = ['invariants']\nexport const apply = () => {}\n", + }) + const result = verify(root, loaderUrl) + expect(result.status).toBe(1) + expect(result.stderr).toContain('chunk.js') + }) +}) diff --git a/tsconfig.build.json b/tsconfig.build.json index 2c7d719ff5..4e22d615a2 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -133,6 +133,7 @@ { "path": "./packages/sdk/telemetry" }, { "path": "./packages/lsp/lsp" }, { "path": "./packages/lsp/lsp-local" }, - { "path": "./packages/lsp/tool-lsp" } + { "path": "./packages/lsp/tool-lsp" }, + { "path": "./apps/cli" } ] } diff --git a/tsconfig.json b/tsconfig.json index fe738727c6..f5c65c396f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -141,6 +141,7 @@ { "path": "./packages/sdk/telemetry" }, { "path": "./packages/lsp/lsp" }, { "path": "./packages/lsp/lsp-local" }, - { "path": "./packages/lsp/tool-lsp" } + { "path": "./packages/lsp/tool-lsp" }, + { "path": "./apps/cli" } ] } diff --git a/tsdown.config.ts b/tsdown.config.ts index 31fa53c675..8ad1a5c41c 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -11,10 +11,10 @@ import { defineConfig } from 'tsdown' * (schemastery: dual ESM+CJS; logger-console: extra browser entry). */ export default defineConfig({ - // Explicit globs keep bundling to vendored Cordis and the TypeScript package tree; - // `workspace: true` would discover package manifests outside that bundle set. Landlock - // platform packages contain only a prebuilt native binary, so they have no JS entry. - workspace: ['vendor/*', 'packages/*/*'], + // Explicit globs keep bundling to vendored Cordis, the TypeScript package tree, and + // the Node CLI assembly. `apps/web` is a Vite application with no lib/types entry; + // `workspace: true` or `apps/*` would incorrectly treat it as a package bundle. + workspace: ['vendor/*', 'packages/*/*', 'apps/cli'], // The brace glob admits the package companion when present while retaining the // index-only build for vendored Cordis packages outside the Harness package tree. entry: ['lib/types/{index,invariant}.js'], diff --git a/vitest.config.ts b/vitest.config.ts index c2a6d09c2c..2f3f80220e 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -22,6 +22,23 @@ const windowsCoverageExclusions = process.platform === 'win32' ] : [] +const testIncludes = [ + 'packages/*/*/tests/**/*.spec.{ts,tsx}', + 'examples/*/tests/**/*.spec.ts', + 'scripts/**/*.spec.ts', +] + +// These suites exercise process-global state, process APIs, or timing-sensitive process I/O +// that worker threads cannot isolate reliably under aggregate gate contention. +// Keep the narrow exception in forks while the rest of the inventory avoids per-file processes. +const processBoundTests = [ + 'packages/bash/bash-local/tests/run.spec.ts', + 'packages/context/time-context/tests/time-context.spec.ts', + 'packages/llm/llm-pi-ai/tests/adapter.spec.ts', + 'packages/ui/app-boot/tests/app-boot.spec.ts', + 'packages/workflow/workflow-workerthread/tests/session.spec.ts', +] + export default defineConfig({ // Native path resolution reads each package's nearest tsconfig, but only the root defines // workspace paths. Keep this plugin pinned to the root map so bare package imports resolve @@ -32,8 +49,35 @@ export default defineConfig({ test: { setupFiles: ['./scripts/test-invariants.ts'], // .tsx: client component specs (jsdom via per-file @vitest-environment pragma). - include: ['packages/*/*/tests/**/*.spec.{ts,tsx}', 'examples/*/tests/**/*.spec.ts', 'scripts/**/*.spec.ts'], + include: testIncludes, exclude: windowsUnsupportedPackages.map(path => `${path}/tests/**/*.spec.ts`), + // One coverage invocation aggregates both projects. Most suites use threads + // for lower startup/IPC overhead; only explicit process-bound suites fork. + projects: [ + { + plugins: [tsconfigPaths({ projects: ['./tsconfig.vitest.json'] })], + test: { + name: 'thread-safe', + pool: 'threads', + setupFiles: ['./scripts/test-invariants.ts'], + include: testIncludes, + exclude: [ + ...windowsUnsupportedPackages.map(path => `${path}/tests/**/*.spec.ts`), + ...processBoundTests, + ], + }, + }, + { + plugins: [tsconfigPaths({ projects: ['./tsconfig.vitest.json'] })], + test: { + name: 'process-bound', + pool: 'forks', + setupFiles: ['./scripts/test-invariants.ts'], + include: processBoundTests, + exclude: windowsUnsupportedPackages.map(path => `${path}/tests/**/*.spec.ts`), + }, + }, + ], coverage: { provider: 'v8', // Coverage measures OUR runtime source. Types-only files carry no @@ -44,11 +88,8 @@ export default defineConfig({ // Types-only files have no runtime coverage. Importing self-executing bins/workers would boot // them inside the unit process, so real subprocess/Worker tests cover their thin entry glue. exclude: [ - 'packages/*/*/src/types.ts', - 'packages/*/*/src/bin.ts', - 'packages/*/*/src/worker.ts', // GUI step-1 skeleton (PR #500): client/web UI files whose remaining // branches need a browser-grade harness the jsdom lane doesn't cover diff --git a/website/AGENTS.md b/website/AGENTS.md new file mode 100644 index 0000000000..333041fd28 --- /dev/null +++ b/website/AGENTS.md @@ -0,0 +1,13 @@ +# AGENTS.md — Documentation website adapter + +Follow the [root instructions](../AGENTS.md), the [documentation standard](../docs/AGENTS.md), and the [documentation-site sync workflow](../.agents/skills/dsh-doc-site-sync/SKILL.md). + +## Keep documentation content out of this tree + +`website/` owns only VitePress configuration, presentation assets, and the publication manifest. This file is the only maintained Markdown file in this subtree. + +Keep canonical prose and generated catalogs in their owning `docs/` tier, then expose selected pages through [docs.ts](docs.ts). Never add locale, route, API, or copied documentation trees such as `website/zh-CN/`, `website/en/`, or `website/api/`. + +The projector writes disposable Markdown to the ignored `website/.generated/` directory. Never edit or commit `.generated/`, `.cache/`, or `.dist/`. + +Run `pnpm docs:check` after changing this subtree; the gate rejects additional non-ignored Markdown under `website/`. diff --git a/website/docs.ts b/website/docs.ts index 12cdc05225..9346670806 100644 --- a/website/docs.ts +++ b/website/docs.ts @@ -256,6 +256,7 @@ const reference = mirroredPages([ ['core.md', '核心数据结构', 'Core data structures'], ['scope.md', '作用域', 'Scopes'], ['session.md', '会话', 'Sessions'], + ['goal.md', '目标', 'Goals'], ['system-prompt.md', '系统提示词', 'System prompts'], ['tools.md', '工具', 'Tools'], ['llm-streaming.md', 'LLM 流式响应', 'LLM streaming'], @@ -269,6 +270,7 @@ const reference = mirroredPages([ ['skills.md', '技能', 'Skills'], ['approval.md', '审批', 'Approvals'], ['user-interaction.md', '用户交互', 'User interaction'], + ['commands.md', '命令', 'Human commands'], ['sandbox.md', '沙箱', 'Sandboxing'], ['web.md', 'Web 访问', 'Web access'], ['persistence.md', '会话持久化', 'Session persistence'], diff --git a/website/zh-CN/api/harness/commands.md b/website/zh-CN/api/harness/commands.md deleted file mode 100644 index 3b92682dac..0000000000 --- a/website/zh-CN/api/harness/commands.md +++ /dev/null @@ -1,91 +0,0 @@ -<!-- Generated by scripts/gen-website-api.ts — do not edit by hand. Run `pnpm run gen-website-api` to regenerate. --> - -# ctx.commands - -`CommandService` — provided by `@deepseek-ai/dsh-commands`. - -Human-command registry. Plain-context definitions are global; definitions registered through a command-injected child of an agent context shadow globals for that agent. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/ui/commands/src/index.ts#L207) - -### ctx.commands.register(definition) - -```ts website-api -/** - * Register a global or calling-agent-scoped command. - * @param definition - discovery metadata and direct UI handler. - * @returns the exact effect disposer that unregisters this definition. - */ -register(definition: CommandDefinition): () => void -``` - -Register a global or calling-agent-scoped command. - -- `definition` — discovery metadata and direct UI handler. - -**Returns** the exact effect disposer that unregisters this definition. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/ui/commands/src/index.ts#L220) - -### ctx.commands.list(agent) - -```ts website-api -/** - * List the effective immutable command descriptors for one agent. - * @param agent - exact receiving agent and scoped-layer key. - * @returns name-sorted descriptors after scoped shadowing. - */ -list(agent: Agent): readonly CommandDescriptor[] -``` - -List the effective immutable command descriptors for one agent. - -- `agent` — exact receiving agent and scoped-layer key. - -**Returns** name-sorted descriptors after scoped shadowing. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/ui/commands/src/index.ts#L247) - -### ctx.commands.find(agent, name) - -```ts website-api -/** - * Resolve one effective command definition. - * @param agent - exact receiving agent and scoped-layer key. - * @param name - command name without a slash. - * @returns the scoped shadow or global definition. - */ -find(agent: Agent, name: string): CommandDefinition | undefined -``` - -Resolve one effective command definition. - -- `agent` — exact receiving agent and scoped-layer key. -- `name` — command name without a slash. - -**Returns** the scoped shadow or global definition. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/ui/commands/src/index.ts#L260) - -### ctx.commands.execute(agent, line, signal) - -```ts website-api -/** - * Parse and execute a known command without sending it to the model. - * @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. - */ -async execute( agent: Agent, line: string, signal: AbortSignal, ): Promise<CommandResult | undefined> -``` - -Parse and execute a known command without sending it to the model. - -- `agent` — exact receiving agent. -- `line` — complete slash-command line. -- `signal` — cancellation signal owned by the UI request. - -**Returns** a detached result, or `undefined` when syntax or name does not resolve. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/ui/commands/src/index.ts#L271) diff --git a/website/zh-CN/api/harness/goals.md b/website/zh-CN/api/harness/goals.md deleted file mode 100644 index 828a5eced3..0000000000 --- a/website/zh-CN/api/harness/goals.md +++ /dev/null @@ -1,203 +0,0 @@ -<!-- Generated by scripts/gen-website-api.ts — do not edit by hand. Run `pnpm run gen-website-api` to regenerate. --> - -# ctx.goals - -`GoalService` — provided by `@deepseek-ai/dsh-goal`. - -Goal service (`ctx.goals`) backed exclusively by the owning session log. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L135) - -### ctx.goals.get(agent) - -```ts website-api -/** - * Read the current goal for one exact live agent. - * @param agent - owning live agent. - * @returns a fresh view or `undefined` when no goal is current. - * @throws {@link GoalError} when the agent is not the registry's live instance. - */ -get(agent: Agent): GoalView | undefined -``` - -Read the current goal for one exact live agent. - -- `agent` — owning live agent. - -**Returns** a fresh view or `undefined` when no goal is current. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L161) - -### ctx.goals.disarm(agent) - -```ts website-api -/** - * Remove process-local continuation authority without changing durable goal - * phase or revision. Lifecycle owners use this before unloading a driver; - * a later human-authorized {@link resume} records the new activation edge. - * @param agent - owning live agent. - * @returns a fresh disarmed view, or `undefined` when no goal is current. - */ -disarm(agent: Agent): GoalView | undefined -``` - -Remove process-local continuation authority without changing durable goal phase or revision. Lifecycle owners use this before unloading a driver; a later human-authorized resume records the new activation edge. - -- `agent` — owning live agent. - -**Returns** a fresh disarmed view, or `undefined` when no goal is current. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L175) - -### ctx.goals.create(agent, request) - -```ts website-api -/** - * Create and arm a goal. A completed goal may be replaced; every other - * current phase must be cleared or resumed instead. - * @param agent - owning live agent. - * @param request - objective and optional round cap. - * @returns the created live view. - */ -create(agent: Agent, request: CreateGoalRequest): GoalView -``` - -Create and arm a goal. A completed goal may be replaced; every other current phase must be cleared or resumed instead. - -- `agent` — owning live agent. -- `request` — objective and optional round cap. - -**Returns** the created live view. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L190) - -### ctx.goals.edit(agent, ref, request) - -```ts website-api -/** - * Edit objective and/or round cap without changing phase. - * @param agent - owning live agent. - * @param ref - expected current revision. - * @param request - at least one replacement field. - * @returns the edited view. - */ -edit(agent: Agent, ref: GoalRef, request: EditGoalRequest): GoalView -``` - -Edit objective and/or round cap without changing phase. - -- `agent` — owning live agent. -- `ref` — expected current revision. -- `request` — at least one replacement field. - -**Returns** the edited view. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L215) - -### ctx.goals.pause(agent, ref) - -```ts website-api -/** - * Pause an active goal and disarm automatic continuation. - * @param agent - owning live agent. - * @param ref - expected current revision. - * @returns the paused view. - */ -pause(agent: Agent, ref: GoalRef): GoalView -``` - -Pause an active goal and disarm automatic continuation. - -- `agent` — owning live agent. -- `ref` — expected current revision. - -**Returns** the paused view. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L236) - -### ctx.goals.resume(agent, ref) - -```ts website-api -/** - * Resume and arm a stopped goal, or rearm an active goal after a - * session-start edge, while its round budget still has capacity. - * @param agent - owning live agent. - * @param ref - expected current revision. - * @returns the active view. - */ -resume(agent: Agent, ref: GoalRef): GoalView -``` - -Resume and arm a stopped goal, or rearm an active goal after a session-start edge, while its round budget still has capacity. - -- `agent` — owning live agent. -- `ref` — expected current revision. - -**Returns** the active view. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L247) - -### ctx.goals.complete(agent, ref) - -```ts website-api -/** - * Mark a current non-complete goal complete and disarm it. - * @param agent - owning live agent. - * @param ref - expected current revision. - * @returns the completed view. - */ -complete(agent: Agent, ref: GoalRef): GoalView -``` - -Mark a current non-complete goal complete and disarm it. - -- `agent` — owning live agent. -- `ref` — expected current revision. - -**Returns** the completed view. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L272) - -### ctx.goals.block(agent, ref, reason) - -```ts website-api -/** - * Mark an active goal blocked and disarm it. - * @param agent - owning live agent. - * @param ref - expected current revision. - * @param reason - policy-owned stable code and human-readable explanation. - * @returns the blocked view with its durable reason. - */ -block(agent: Agent, ref: GoalRef, reason: GoalBlockReason): GoalView -``` - -Mark an active goal blocked and disarm it. - -- `agent` — owning live agent. -- `ref` — expected current revision. -- `reason` — policy-owned stable code and human-readable explanation. - -**Returns** the blocked view with its durable reason. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L290) - -### ctx.goals.clear(agent, ref) - -```ts website-api -/** - * Clear the current goal while retaining a durable tombstone and history. - * @param agent - owning live agent. - * @param ref - expected current revision. - * @returns the tombstone ref whose revision is one past the cleared snapshot. - */ -clear(agent: Agent, ref: GoalRef): GoalRef -``` - -Clear the current goal while retaining a durable tombstone and history. - -- `agent` — owning live agent. -- `ref` — expected current revision. - -**Returns** the tombstone ref whose revision is one past the cleared snapshot. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/goal/goal/src/index.ts#L311) diff --git a/website/zh-CN/api/harness/invariants.md b/website/zh-CN/api/harness/invariants.md deleted file mode 100644 index e2f582a566..0000000000 --- a/website/zh-CN/api/harness/invariants.md +++ /dev/null @@ -1,32 +0,0 @@ -<!-- Generated by scripts/gen-website-api.ts — do not edit by hand. Run `pnpm run gen-website-api` to regenerate. --> - -# ctx.invariants - -`InvariantService` — provided by `@deepseek-ai/dsh-invariants`. - -Package-owned invariant registry with global and regex-based selection. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/support/invariants/src/index.ts#L388) - -### ctx.invariants.register(packageName, installer) - -```ts website-api -/** - * Register one package's invariant installer. The package name is reserved - * even when filtering disables its checks. Enabled installers run in a child - * fiber; failure disposes that fiber and releases the reservation. - * @param packageName - full npm package name that owns the contribution. - * @param installer - listener or startup-check installer for the child context. - * @returns an effect-scoped disposer for the registration. - */ -register(packageName: string, installer: InvariantInstaller): () => void -``` - -Register one package's invariant installer. The package name is reserved even when filtering disables its checks. Enabled installers run in a child fiber; failure disposes that fiber and releases the reservation. - -- `packageName` — full npm package name that owns the contribution. -- `installer` — listener or startup-check installer for the child context. - -**Returns** an effect-scoped disposer for the registration. - -[Source](https://github.com/deepseek-harness/deepseek-harness/blob/master/packages/support/invariants/src/index.ts#L430)