Przeglądaj źródła

merge: align session toast fix with latest master

07akioni 5 dni temu
rodzic
commit
e297b75a5d
100 zmienionych plików z 2012 dodań i 151 usunięć
  1. 6 0
      .agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.i18n.yaml
  2. 29 0
      .agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.md
  3. 29 0
      .agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.zh.md
  4. 6 0
      .agents/notes/implemented/bug-fix/2026-09-16-messages-historical-tool-input.i18n.yaml
  5. 29 0
      .agents/notes/implemented/bug-fix/2026-09-16-messages-historical-tool-input.md
  6. 29 0
      .agents/notes/implemented/bug-fix/2026-09-16-messages-historical-tool-input.zh.md
  7. 2 2
      .agents/notes/implemented/feature/2026-09-07-deepseek-messages-adapter.i18n.yaml
  8. 1 1
      .agents/notes/implemented/feature/2026-09-07-deepseek-messages-adapter.md
  9. 1 1
      .agents/notes/implemented/feature/2026-09-07-deepseek-messages-adapter.zh.md
  10. 2 2
      .agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.i18n.yaml
  11. 2 2
      .agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.md
  12. 2 2
      .agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.zh.md
  13. 6 0
      .agents/notes/implemented/feature/2026-09-15-bundled-office-skills.i18n.yaml
  14. 31 0
      .agents/notes/implemented/feature/2026-09-15-bundled-office-skills.md
  15. 31 0
      .agents/notes/implemented/feature/2026-09-15-bundled-office-skills.zh.md
  16. 12 4
      apps/cli/tests/desktop-host.e2e.ts
  17. 2 1
      apps/desktop-host/package.json
  18. 2 2
      apps/desktop-host/src/index.ts
  19. 26 0
      apps/desktop-host/src/office.ts
  20. 58 0
      apps/desktop-host/tests/office.spec.ts
  21. 1 0
      apps/desktop-host/tsconfig.json
  22. 2 2
      apps/desktop/README.i18n.yaml
  23. 2 0
      apps/desktop/README.md
  24. 2 0
      apps/desktop/README.zh.md
  25. 17 2
      apps/desktop/scripts/prepare-primary-runtime.ts
  26. 9 0
      apps/desktop/scripts/smoke-primary-runtime.py
  27. 2 1
      apps/desktop/src/host-process.ts
  28. 24 2
      apps/desktop/tests/primary-runtime-preparation.spec.ts
  29. 55 5
      apps/web/tests/permission-policy-context.e2e.ts
  30. 2 2
      docs/capability-seams.i18n.yaml
  31. 3 1
      docs/capability-seams.md
  32. 3 1
      docs/capability-seams.zh.md
  33. 2 2
      docs/config-catalog.i18n.yaml
  34. 18 2
      docs/config-catalog.md
  35. 18 2
      docs/config-catalog.zh.md
  36. 2 2
      docs/event-producer-consumer.i18n.yaml
  37. 1 1
      docs/event-producer-consumer.md
  38. 1 1
      docs/event-producer-consumer.zh.md
  39. 2 2
      docs/module-graph.i18n.yaml
  40. 3 0
      docs/module-graph.md
  41. 3 0
      docs/module-graph.zh.md
  42. 2 2
      docs/persistence-catalog.i18n.yaml
  43. 3 3
      docs/persistence-catalog.md
  44. 3 3
      docs/persistence-catalog.zh.md
  45. 1 1
      docs/persistence-schema.json
  46. 2 2
      docs/subsystems/skills.i18n.yaml
  47. 2 2
      docs/subsystems/skills.md
  48. 2 2
      docs/subsystems/skills.zh.md
  49. 2 2
      docs/subsystems/workspace.i18n.yaml
  50. 1 1
      docs/subsystems/workspace.md
  51. 1 1
      docs/subsystems/workspace.zh.md
  52. 2 1
      package.json
  53. 2 2
      packages/api/terminal-controller/README.i18n.yaml
  54. 4 3
      packages/api/terminal-controller/README.md
  55. 4 3
      packages/api/terminal-controller/README.zh.md
  56. 7 25
      packages/api/terminal-controller/src/index.ts
  57. 24 29
      packages/api/terminal-controller/tests/controller.spec.ts
  58. 2 2
      packages/client/ui-sidebar-terminal/README.i18n.yaml
  59. 1 1
      packages/client/ui-sidebar-terminal/README.md
  60. 1 1
      packages/client/ui-sidebar-terminal/README.zh.md
  61. 1 1
      packages/extensions/tool-cordis/src/api-catalog.ts
  62. 2 2
      packages/llm/llm-deepseek/README.i18n.yaml
  63. 1 1
      packages/llm/llm-deepseek/README.md
  64. 1 1
      packages/llm/llm-deepseek/README.zh.md
  65. 6 4
      packages/llm/llm-deepseek/src/protocols/messages/serialize.ts
  66. 20 1
      packages/llm/llm-deepseek/tests/messages/adapter.e2e.ts
  67. 15 0
      packages/llm/llm-deepseek/tests/messages/fixtures/history.ts
  68. 22 5
      packages/llm/llm-deepseek/tests/messages/serialize.spec.ts
  69. 2 2
      packages/skill/README.i18n.yaml
  70. 2 1
      packages/skill/README.md
  71. 2 1
      packages/skill/README.zh.md
  72. 6 0
      packages/skill/skill-office/README.i18n.yaml
  73. 100 0
      packages/skill/skill-office/README.md
  74. 100 0
      packages/skill/skill-office/README.zh.md
  75. 46 0
      packages/skill/skill-office/assets/office-docx/SKILL.md
  76. 70 0
      packages/skill/skill-office/assets/office-pptx/SKILL.md
  77. 56 0
      packages/skill/skill-office/assets/office-xlsx/SKILL.md
  78. 279 0
      packages/skill/skill-office/assets/scripts/check_office.py
  79. 43 0
      packages/skill/skill-office/package.json
  80. 70 0
      packages/skill/skill-office/src/index.ts
  81. 278 0
      packages/skill/skill-office/tests/check_office_test.py
  82. 14 0
      packages/skill/skill-office/tests/checkers.spec.ts
  83. BIN
      packages/skill/skill-office/tests/fixtures/encrypted.xlsx
  84. 124 0
      packages/skill/skill-office/tests/skill-office.spec.ts
  85. 24 0
      packages/skill/skill-office/tsconfig.json
  86. 28 0
      pnpm-lock.yaml
  87. 8 0
      scripts/check-workspace-constraints.spec.ts
  88. 1 0
      scripts/check-workspace-constraints.ts
  89. 1 1
      scripts/gen-doc-graphs.ts
  90. 1 0
      scripts/verify-package-readme-model-experience.ts
  91. 47 0
      snapshots/session/deepseek-messages-invalid-tool-history/cordis.snapshot.yml
  92. 3 0
      snapshots/session/deepseek-messages-invalid-tool-history/cordis.yml
  93. 22 0
      snapshots/session/deepseek-messages-invalid-tool-history/session.v3.jsonl
  94. 10 0
      snapshots/session/deepseek-messages-invalid-tool-history/snapshot.yml
  95. 3 0
      snapshots/session/headless.snapshot.ts
  96. 22 0
      snapshots/session/office-skills-no-renderer/cordis.snapshot.yml
  97. 14 0
      snapshots/session/office-skills-no-renderer/cordis.yml
  98. 11 0
      snapshots/session/office-skills-no-renderer/session.v3.jsonl
  99. 12 0
      snapshots/session/office-skills-no-renderer/snapshot.yml
  100. 1 0
      snapshots/session/office-skills-no-renderer/system-prompt.expected.md

+ 6 - 0
.agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.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 .agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.md
+2026-09-16-user-terminal-permissions.md: f45b96419c34f8ebddc30431b42c9859c46de6b9
+2026-09-16-user-terminal-permissions.zh.md: 62bb152a1b899d026c8d7bddb350317ba12f14cf

+ 29 - 0
.agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.md

@@ -0,0 +1,29 @@
+# Agent Note: User-terminal permissions
+
+Status: implemented
+
+English | [中文](2026-09-16-user-terminal-permissions.zh.md)
+
+## Problem
+
+Users need to run commands themselves while keeping the Agent restricted. Sharing the Agent's sandbox mode forces a user to widen Agent access for manual work, and retaining an interactive shell prevents later mode changes because its process confinement cannot follow a new Session setting.
+
+## Decision
+
+The Web sidebar terminal runs directly through the Session's subprocess provider with the execution environment's system-user permissions. It neither confines the shell through the Agent sandbox nor requests Agent approval. Operating-system permissions, container isolation and the provider's credential-environment scrubbing continue to apply. Session identity owns access, process cleanup and the initial directory; sandbox policy supplies only the configured directory fallback when the Session has no cwd.
+
+Agent permission changes leave user terminals running. Agent-owned shell and terminal tools retain their own sandbox enforcement. User terminal input and output create no model input or Session events.
+
+This decision supersedes only the shared sandbox policy and mode-switch restriction in the [Web sidebar terminal decision](../feature/2026-09-09-web-sidebar-terminal.md). That note remains active for process ownership, transport, screen recovery and shell selection. OpenCode's `packages/core/src/pty.ts` and `packages/core/src/pty/pty.node.ts` provide adjacent evidence: its interactive terminal creates a PTY directly with the selected shell and working directory.
+
+## Alternatives considered
+
+**Inherit Agent permissions.** One Session mode describes both processes, but users must also grant the Agent access needed only for manual commands. Persistent user shells then obstruct changes to Agent permissions.
+
+**Add a separate terminal permission selector.** The product treats this terminal as a user-operated system shell. Another selector adds policy state and process-restart semantics without a current requirement; deployment and operating-system controls already determine the execution environment.
+
+## Consequences
+
+Access to the Web terminal grants command execution as the subprocess provider's system user, including writes outside the Session workspace where that user has permission. It does not grant root or escape a container. Session ownership remains useful for grouping and cleanup without implying Agent authority over user actions.
+
+Controller tests pin direct shell launch across all Agent sandbox modes and continued ownership during mode changes. The recorded Web permission-policy scenario keeps one real user PTY open across read-only, full-access and workspace-write transitions, verifies writes inside and outside the workspace, and retains the Agent's read-only denial and approval assertions. The Bash browser assertions run on macOS and Linux; Windows retains the portable controller checks and Agent-policy replay.

+ 29 - 0
.agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.zh.md

@@ -0,0 +1,29 @@
+# Agent Note: User-terminal permissions
+
+Status: implemented
+
+[English](2026-09-16-user-terminal-permissions.md) | 中文
+
+## 问题
+
+用户需要在限制 Agent(智能体)权限的同时亲自运行命令。共享 Agent 的沙箱模式会迫使用户为了手动操作而扩大 Agent 权限;保留交互式 shell 又会阻止后续模式切换,因为已有进程的沙箱限制无法跟随新的 Session 设置改变。
+
+## 决策
+
+Web 侧栏终端直接通过 Session 的 subprocess provider 运行,使用执行环境中系统用户的权限。它不通过 Agent 沙箱限制 shell,也不请求 Agent 审批。操作系统权限、容器隔离和 provider 对环境凭据的清除仍然生效。Session 标识负责访问范围、进程清理和初始目录;sandbox policy 仅在 Session 没有 cwd 时提供配置的默认目录。
+
+改变 Agent 权限时,用户终端继续运行。Agent 使用的 shell 和 terminal 工具保留各自的沙箱限制。用户终端的输入和输出不产生模型输入或 Session 事件。
+
+本决策仅取代 [Web 侧栏终端决策](../feature/2026-09-09-web-sidebar-terminal.zh.md)中的共享沙箱策略和模式切换限制。原记录继续负责进程所有权、传输、屏幕恢复和 shell 选择。OpenCode 的 `packages/core/src/pty.ts` 和 `packages/core/src/pty/pty.node.ts` 提供相邻实现依据:其交互式终端使用选定的 shell 和工作目录直接创建 PTY。
+
+## 考虑过的替代方案
+
+**继承 Agent 权限。** 一个 Session 模式可以描述两类进程,但用户必须同时授予 Agent 仅用于手动命令的权限。持久用户 shell 随之阻碍 Agent 权限切换。
+
+**增加独立的终端权限选择器。** 产品将此终端视为用户操作的系统 shell。另一个选择器会增加策略状态和进程重启语义,目前没有对应需求;部署和操作系统控制已经确定执行环境。
+
+## 影响
+
+访问 Web 终端即可作为 subprocess provider 的系统用户执行命令,包括在该用户有权限时写入 Session 工作区之外的路径。它不会授予 root 权限或逃逸容器。Session 所有权继续用于分组和清理,不意味着 Agent 决定用户操作的权限。
+
+Controller 测试覆盖全部 Agent 沙箱模式下的直接 shell 启动,以及模式改变后的持续所有权。录制的 Web 权限策略场景在只读、完全访问和工作区写入之间切换时保持同一个真实用户 PTY,验证工作区内外的写入,并保留 Agent 的只读拒绝和审批断言。Bash 浏览器断言在 macOS 和 Linux 运行;Windows 保留可移植的 controller 检查和 Agent 策略回放。

+ 6 - 0
.agents/notes/implemented/bug-fix/2026-09-16-messages-historical-tool-input.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 .agents/notes/implemented/bug-fix/2026-09-16-messages-historical-tool-input.md
+2026-09-16-messages-historical-tool-input.md: 201b0f21ad041395a4c4101d6919b2878e22c9ab
+2026-09-16-messages-historical-tool-input.zh.md: bcc637982420124b401ef65c668b068394b6d915

+ 29 - 0
.agents/notes/implemented/bug-fix/2026-09-16-messages-historical-tool-input.md

@@ -0,0 +1,29 @@
+# Agent Note: Replay malformed historical tool input through Messages
+
+Status: implemented
+
+English | [中文](2026-09-16-messages-historical-tool-input.zh.md)
+
+## Problem
+
+Chat Completions retains tool arguments as strings, including malformed JSON from failed calls. Switching that history to Messages requires an object for each `tool_use.input`. Rejecting one historical argument blocks every later request containing it, even after a successful tool retry; a summarization request containing the same call also fails.
+
+## Decision
+
+The [Messages serializer](../../../../packages/llm/llm-deepseek/src/protocols/messages/serialize.ts) follows the [pi-ai history conversion](../../../../packages/llm/llm-pi-ai/src/replay.ts): malformed JSON and non-object values become `{}` only in the outgoing historical tool input. Call ids, names, results, and original Session records remain intact. This applies with valid, absent, or unusable native replay metadata and does not execute the historical call again.
+
+This supersedes the historical argument rejection in the [Messages adapter decision](../feature/2026-09-07-deepseek-messages-adapter.md). New Messages responses still require valid object arguments before successful completion; output-limit truncation retains its existing pruning behavior. No Session event, persistence type, or protocol configuration changes.
+
+## Alternatives considered
+
+**Reject malformed history.** A failed call can remain relevant evidence without preventing all subsequent model requests.
+
+**Repair or overwrite stored arguments.** Guessing missing quotes or retaining a parsed prefix can change the requested operation. Request-only empty input preserves the original evidence and requires no migration.
+
+**Drop the call.** Its result still cites the call id; keeping both preserves the tool exchange without inventing arguments.
+
+## Consequences
+
+Messages continuation can omit unusable historical parameters without losing the call identity or result. The model sees `{}` rather than the original malformed text, and the fallback is silent, matching pi-ai. Original arguments remain available in the Session log; this does not claim lossless provider input or repair invalid newly generated calls.
+
+Verification covers object-only conversion, failed results followed by user input, JSON round trips, both valid and degraded replay metadata, a [recorded Session](../../../../snapshots/session/deepseek-messages-invalid-tool-history/snapshot.yml) through the shipped headless profile and real Messages serializer, and a credential-gated live Messages continuation.

+ 29 - 0
.agents/notes/implemented/bug-fix/2026-09-16-messages-historical-tool-input.zh.md

@@ -0,0 +1,29 @@
+# Agent Note: 通过 Messages 回放非法历史工具输入
+
+Status: implemented
+
+[English](2026-09-16-messages-historical-tool-input.md) | 中文
+
+## 问题
+
+Chat Completions 将工具参数保留为字符串,其中可能包含失败调用产生的非法 JSON。将这段历史切换到 Messages 时,每个 `tool_use.input` 都必须是对象。拒绝一条历史参数就会阻断包含它的所有后续请求,即使工具重试已经成功;包含同一调用的摘要请求也会失败。
+
+## 决策
+
+[Messages 序列化器](../../../../packages/llm/llm-deepseek/src/protocols/messages/serialize.ts) 遵循 [pi-ai 历史转换](../../../../packages/llm/llm-pi-ai/src/replay.ts)的做法:只在发出的历史工具输入中,将非法 JSON 和非对象值替换为 `{}`。调用 ID、名称、结果和原始 Session 记录保持不变。原生回放元数据有效、缺失或不可用时均采用此规则,也不会重新执行历史调用。
+
+这取代了 [Messages 适配器决策](../feature/2026-09-07-deepseek-messages-adapter.zh.md)中的历史参数拒绝规则。新生成的 Messages 响应在成功完成前仍要求工具参数是有效对象;达到输出上限时仍按现有规则裁剪。不改变 Session 事件、持久化类型或协议配置。
+
+## 考虑过的替代方案
+
+**拒绝非法历史。** 失败调用可以继续作为相关证据保留,而不必阻断所有后续模型请求。
+
+**修复或覆盖已存参数。** 猜测缺失的引号或保留部分解析结果可能改变请求的操作。只在请求中使用空输入可以保留原始证据,也不需要迁移。
+
+**删除调用。** 对应结果仍引用调用 ID;同时保留调用和结果,可以保留工具交互而不编造参数。
+
+## 后果
+
+Messages 可以在省略不可用历史参数的同时继续会话,并保留调用身份和结果。模型看到的是 `{}`,而不是原始非法文本;该兜底与 pi-ai 一样不产生诊断。原始参数仍可在 Session 日志中查阅;这不保证提供方输入无损,也不修复新生成的非法调用。
+
+验证覆盖仅接受对象的转换、失败结果后的用户输入、JSON 往返、有效与降级的回放元数据、通过已发布 headless profile 和真实 Messages 序列化器运行的[录制 Session](../../../../snapshots/session/deepseek-messages-invalid-tool-history/snapshot.yml),以及需要凭据的真实 Messages 续接。

+ 2 - 2
.agents/notes/implemented/feature/2026-09-07-deepseek-messages-adapter.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 .agents/notes/implemented/feature/2026-09-07-deepseek-messages-adapter.md
-2026-09-07-deepseek-messages-adapter.md: 6b7aff250aacd4bb7d0af3b4e68ee5b2002c13e3
-2026-09-07-deepseek-messages-adapter.zh.md: 829e2189cb48a2acaa1ec27f7ccade0f163b58ad
+2026-09-07-deepseek-messages-adapter.md: c667ec3afdd9956282a532e748ad2e2488d26f5b
+2026-09-07-deepseek-messages-adapter.zh.md: 0e3425e41d8a9585a1638eedeefcf6ead76a5a78

+ 1 - 1
.agents/notes/implemented/feature/2026-09-07-deepseek-messages-adapter.md

@@ -14,7 +14,7 @@ The [DeepSeek adapter](../../../../packages/llm/llm-deepseek/README.md) serves m
 
 The adapter follows the [DeepSeek compatibility documentation](https://api-docs.deepseek.com/zh-cn/guides/anthropic_api) and [Anthropic streaming protocol](https://platform.claude.com/docs/en/build-with-claude/streaming). The pi-ai Anthropic implementation informed the handling of adjacent user messages, cumulative usage, fragmented tool arguments, and optional thinking signatures. DeepSeek effort uses `output_config.effort`; an Anthropic thinking token budget does not control DeepSeek effort. Both protocols forward explicit `temperature` values; DeepSeek accepts that parameter with thinking enabled and ignores its value, so callers retain their existing thinking configuration.
 
-Assistant blocks remain the durable model-visible content. A versioned `ReplayEnvelope` stores only the protocol format, model identity, aligned block kinds, and signatures absent from those blocks. Same-model Messages continuation restores signatures verbatim, including empty signatures; foreign history carries no invented signature. Unusable metadata follows the existing [replay degradation rule](../architecture/2026-07-14-provider-routed-llm-adapters.md): the request omits signatures with a warning while preserving durable content; content validation such as tool argument parsing still fails explicitly. This keeps provider replay data opaque to the loop while preserving it through Session persistence and block pruning.
+Assistant blocks remain the durable model-visible content. A versioned `ReplayEnvelope` stores only the protocol format, model identity, aligned block kinds, and signatures absent from those blocks. Same-model Messages continuation restores signatures verbatim, including empty signatures; foreign history carries no invented signature. Unusable metadata follows the existing [replay degradation rule](../architecture/2026-07-14-provider-routed-llm-adapters.md): the request omits signatures with a warning while preserving durable content; historical tool arguments use the [empty-input fallback](../bug-fix/2026-09-16-messages-historical-tool-input.md) when Messages cannot represent them. This keeps provider replay data opaque to the loop while preserving it through Session persistence and block pruning.
 
 Both protocols prefer Files references for deterministic request images and share upload caching, refresh, quota recovery, and attachment offload. The Files client retains the selected protocol and configured endpoint: Messages follows the [exact `/v1` root rule](../bug-fix/2026-09-15-messages-v1-base-url.md), while Chat Completions appends `/files`. Messages Files requests carry the required beta header. Cached ids remain scoped by the resolved Files root and credential, so equivalent `/v1` and unversioned Messages roots share uploads. Messages metadata omits expiry, so local reuse is bounded from the original upload time without asserting remote deletion. A Files-resolution failure rebuilds the complete request under the independent inline-image budget; caller cancellation stops it. The shared image policy preserves the 128 MiB retained-image budget, 20 MiB inline base64 budget, and oldest-prefix offload in both requests and token measurement.
 

+ 1 - 1
.agents/notes/implemented/feature/2026-09-07-deepseek-messages-adapter.zh.md

@@ -14,7 +14,7 @@ Status: implemented
 
 适配器遵循 [DeepSeek 兼容文档](https://api-docs.deepseek.com/zh-cn/guides/anthropic_api) 和 [Anthropic 流协议](https://platform.claude.com/docs/en/build-with-claude/streaming)。pi-ai 的 Anthropic 实现为相邻用户消息、累计用量、工具参数分片和可选思考签名的处理提供参考。DeepSeek 通过 `output_config.effort` 设置思考强度;Anthropic 思考 token 预算不控制 DeepSeek 思考强度。两种协议都转发显式 `temperature` 值;DeepSeek 在启用思考时接受该参数但忽略其值,因此调用方可以保留已有思考配置。
 
-助手内容块保留持久化的模型可见内容。带版本的 `ReplayEnvelope` 仅保存协议格式、模型标识、对齐的块类型以及内容块未包含的签名。同模型续接原样恢复签名,包括空签名;外部历史不生成虚构签名。不可用的元数据遵循现有[回放降级规则](../architecture/2026-07-14-provider-routed-llm-adapters.zh.md):请求省略签名并记录警告,保留持久化内容;工具参数等内容校验仍会正常报错。提供者回放数据对循环保持不透明,同时能够随 Session 持久化和内容块裁剪保留。
+助手内容块保留持久化的模型可见内容。带版本的 `ReplayEnvelope` 仅保存协议格式、模型标识、对齐的块类型以及内容块未包含的签名。同模型续接原样恢复签名,包括空签名;外部历史不生成虚构签名。不可用的元数据遵循现有[回放降级规则](../architecture/2026-07-14-provider-routed-llm-adapters.zh.md):请求省略签名并记录警告,保留持久化内容;Messages 无法表示历史工具参数时使用[空输入兜底](../bug-fix/2026-09-16-messages-historical-tool-input.zh.md)。提供者回放数据对循环保持不透明,同时能够随 Session 持久化和内容块裁剪保留。
 
 两种协议均优先为确定性请求图片使用 Files 引用,并共享上传缓存、刷新、配额恢复和附件卸载。Files 客户端保留所选协议与已配置端点:Messages 遵循[严格匹配 `/v1` 的根地址规则](../bug-fix/2026-09-15-messages-v1-base-url.zh.md),Chat Completions 则追加 `/files`。Messages Files 请求携带必需的 beta 标头。缓存 id 按解析后的 Files 根地址和凭据限定作用域,因此等价的 `/v1` 与无版本 Messages 根地址可以复用上传。Messages 元数据不含过期时间,因此本地复用从原始上传时间起受限,但不宣称远端文件已删除。Files 解析失败会按独立的内联图片预算重建完整请求;调用方取消则停止请求。共享图片策略在请求与 token 计量中保留 128 MiB 的保留图片预算、20 MiB 的内联 base64 预算,以及最旧前缀卸载。
 

+ 2 - 2
.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.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 .agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.md
-2026-09-09-web-sidebar-terminal.md: 2649610e776029b10b11fc4ea87d75a24a58d32b
-2026-09-09-web-sidebar-terminal.zh.md: 9a3fd828ff52142cb945ff14d84d13c9e8522ecf
+2026-09-09-web-sidebar-terminal.md: 5757aed3702dbcc7752e99912714bd1356a96206
+2026-09-09-web-sidebar-terminal.zh.md: 39870d1ba26cbc1d655b35a3d2dba61692d0fdb9

+ 2 - 2
.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.md

@@ -14,7 +14,7 @@ Guide entries declare stable ids within their provider. A keyed `sidebar.right.t
 
 The application theme supplies terminal default colors. The body reads resolved CSS tokens, and updates xterm only when those colors change. Public OSC parser observers retain indexed and default-color overrides separately from the DSH defaults; resets remove the corresponding override before restoring the current theme. Observers delegate queries and color handling to xterm. xterm's minimum contrast adjustment improves text legibility without remapping ANSI backgrounds. The DOM cursor reads the rendered cell background after each render and uses a contrasting fill through scoped CSS variables, so cursor movement never resets the palette. Browser checks cover indexed, true-color and inverse cells, light/dark switching, OSC retention and reset, and blinking cursor styles.
 
-`api-terminal-controller` owns user terminals by Session and exposes the `terminal` Remote namespace. `ui-sidebar-terminal` registers native right-sidebar tabs, xterm.js rendering and FitAddon sizing. The terminal guide card has a primary action for the remembered available shell and a separate installed-shell menu. Selecting a menu item records its path and opens a new terminal immediately; discovery alone allocates no process. Each tab owns its startup and close lifecycle. Host discovery verifies the configured candidates, with the execution default first; creation accepts only a currently discovered path. The browser remembers the last selected shell path in origin-scoped localStorage and falls back to the current default if that path is unavailable. The terminal type declares independent instances, so ordinary page deduplication cannot collapse separate processes when opening or docking tabs. The existing sidebar controls open additional tabs; double-clicking a tab title renames its terminal. Terminal processes use the composed subprocess provider and Session sandbox policy. Shell resolution occurs during discovery and creation; reading limits and reconnecting an existing process do not depend on the default executable remaining available. Interactive shell configuration supplies Tab completion and optional inline suggestions.
+`api-terminal-controller` owns user terminals by Session and exposes the `terminal` Remote namespace. `ui-sidebar-terminal` registers native right-sidebar tabs, xterm.js rendering and FitAddon sizing. The terminal guide card has a primary action for the remembered available shell and a separate installed-shell menu. Selecting a menu item records its path and opens a new terminal immediately; discovery alone allocates no process. Each tab owns its startup and close lifecycle. Host discovery verifies the configured candidates, with the execution default first; creation accepts only a currently discovered path. The browser remembers the last selected shell path in origin-scoped localStorage and falls back to the current default if that path is unavailable. The terminal type declares independent instances, so ordinary page deduplication cannot collapse separate processes when opening or docking tabs. The existing sidebar controls open additional tabs; double-clicking a tab title renames its terminal. Terminal processes use the composed subprocess provider; [user-terminal permissions](../architecture/2026-09-16-user-terminal-permissions.md) govern their execution permissions independently of the Agent. Shell resolution occurs during discovery and creation; reading limits and reconnecting an existing process do not depend on the default executable remaining available. Interactive shell configuration supplies Tab completion and optional inline suggestions.
 
 Close and replacement remove the tab synchronously and run process cleanup in the background. The Client first records the unfinished close request under a terminal-specific localStorage key; success removes it, and startup retries requests that remain. A cleanup failure produces a lightweight notification with a retry action without reopening the tab. Independent keys prevent another window from overwriting unrelated cleanup requests. Collapse, tab/Session switching, floating, fullscreen and browser disconnection preserve the process. Component cleanup and `TabDomain.signal` only detach browser work because the same lifetime can end during plugin reload. Failed process cleanup retains ownership, including failures after allocation but before create publication. Session owner disposal and Host plugin disposal also clean up terminals. A definitive missing-Session response retires its saved close request because the Session owns process cleanup; transport failures remain retryable. Client plugin disposal awaits every detached stream so a replacement plugin does not inherit unfinished Client cleanup.
 
@@ -44,7 +44,7 @@ The latest attachment controls input and dimensions; other attachments remain re
 
 ## Consequences
 
-A kept-open terminal retains a process and bounded screen memory. Reload restores the sidebar layout and reconnects Host-retained terminals; Host restart does not restore processes. An exited shell remains visible without automatic respawn. Background cleanup may outlive its tab, and unavailable browser storage limits retry recovery to the current page. Native PTY support and descendant cleanup guarantees remain provider-specific. One writable attachment avoids competing resize and input streams, while explicit takeover permits recovery from another page. Changing sandbox mode requires closing retained terminals first.
+A kept-open terminal retains a process and bounded screen memory. Reload restores the sidebar layout and reconnects Host-retained terminals; Host restart does not restore processes. An exited shell remains visible without automatic respawn. Background cleanup may outlive its tab, and unavailable browser storage limits retry recovery to the current page. Native PTY support and descendant cleanup guarantees remain provider-specific. One writable attachment avoids competing resize and input streams, while explicit takeover permits recovery from another page. User terminals remain open when the Session sandbox mode changes.
 
 The implementation retains the Agent-terminal and portable-execution notes because their ownership and provider decisions remain independently useful; neither is superseded by browser terminals.
 

+ 2 - 2
.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.zh.md

@@ -14,7 +14,7 @@ Web 用户需要在 Session 旁使用交互式 shell 检查工作区和运行命
 
 应用主题提供终端的默认颜色。终端正文读取解析后的 CSS 令牌,仅在颜色变化时更新 xterm。公开的 OSC 解析观察器将索引色和默认颜色覆盖与 DSH 默认值分开保存;重置命令先删除对应覆盖,再恢复当前主题。观察器将查询和颜色处理交给 xterm。xterm 的最小对比度调整改善文字可读性,同时不重新映射 ANSI 背景色。DOM 光标在每次渲染后读取单元格实际背景,通过局部 CSS 变量使用有足够对比度的填充色,因此光标移动不会重置调色板。浏览器检查覆盖索引色、真彩色、反色单元格、明暗主题切换、OSC 保留和重置,以及闪烁光标样式。
 
-`api-terminal-controller` 按 Session 管理用户终端并提供 `terminal` Remote namespace。`ui-sidebar-terminal` 注册原生右侧栏标签页,使用 xterm.js 渲染和 FitAddon 测量尺寸。终端开始页卡片的主操作打开上次选择且仍可用的 shell,独立菜单提供已安装 shell。选择菜单项会记录路径并立即打开新终端;仅探测 shell 不分配进程。每个标签页拥有自己的启动和关闭生命周期。Host 探测会验证配置的候选,并把执行环境默认项放在首位;创建只接受当前探测返回的路径。浏览器在当前站点 localStorage 中记住上次选择的 shell 路径,该路径不可用时回到当前默认项。终端类型声明独立实例,因此打开或停靠标签页时,普通页面的去重规则不会合并不同进程。已有侧栏控件负责打开更多标签页,双击标签页标题可重命名终端。终端进程使用组合的 subprocess provider 和 Session sandbox policy。shell 在探测和创建时解析;读取限制和重新连接已有进程不依赖默认可执行文件仍然可用。交互式 shell 配置提供 Tab 补全和可选的内联建议。
+`api-terminal-controller` 按 Session 管理用户终端并提供 `terminal` Remote namespace。`ui-sidebar-terminal` 注册原生右侧栏标签页,使用 xterm.js 渲染和 FitAddon 测量尺寸。终端开始页卡片的主操作打开上次选择且仍可用的 shell,独立菜单提供已安装 shell。选择菜单项会记录路径并立即打开新终端;仅探测 shell 不分配进程。每个标签页拥有自己的启动和关闭生命周期。Host 探测会验证配置的候选,并把执行环境默认项放在首位;创建只接受当前探测返回的路径。浏览器在当前站点 localStorage 中记住上次选择的 shell 路径,该路径不可用时回到当前默认项。终端类型声明独立实例,因此打开或停靠标签页时,普通页面的去重规则不会合并不同进程。已有侧栏控件负责打开更多标签页,双击标签页标题可重命名终端。终端进程使用组合的 subprocess provider;[用户终端权限](../architecture/2026-09-16-user-terminal-permissions.zh.md)规定其独立于 Agent 的执行权限。shell 在探测和创建时解析;读取限制和重新连接已有进程不依赖默认可执行文件仍然可用。交互式 shell 配置提供 Tab 补全和可选的内联建议。
 
 关闭和替换会同步移除标签页,并在后台清理进程。Client 先以终端独立的 localStorage key 保存未完成的关闭请求;成功后删除,启动时重试剩余请求。清理失败时显示带重试操作的轻量通知,不重新打开标签页。独立 key 避免其他窗口覆盖无关的清理请求。折叠、切换标签页或 Session、浮动、全屏和浏览器断线均保留进程。组件清理和 `TabDomain.signal` 只停止浏览器工作,因为插件重新加载也会结束这些生命周期。进程清理失败时保留所有权,包括分配完成但 create 尚未发布时的失败。Session owner 和 Host 插件卸载也会清理终端。 明确的 Session 不存在响应会清除已保存的关闭请求,因为进程清理由 Session 负责;传输失败仍可重试。Client 插件卸载等待所有断开的流结束,避免替换插件继承未完成的 Client 清理。
 
@@ -44,7 +44,7 @@ Web 用户需要在 Session 旁使用交互式 shell 检查工作区和运行命
 
 ## 影响
 
-保留终端会保留进程和有界屏幕内存。刷新恢复侧栏布局并重连 Host 保留的终端;Host 重启不恢复进程。shell 退出后保持可见,不自动重启。后台清理可能比标签页存活更久,浏览器存储不可用时只能在当前页面保留重试能力。原生 PTY 支持和后代进程清理保证仍由 provider 决定。单一可写连接避免竞争的输入和尺寸流,显式接管允许从另一页面恢复操作。改变 sandbox mode 前需要关闭保留的终端
+保留终端会保留进程和有界屏幕内存。刷新恢复侧栏布局并重连 Host 保留的终端;Host 重启不恢复进程。shell 退出后保持可见,不自动重启。后台清理可能比标签页存活更久,浏览器存储不可用时只能在当前页面保留重试能力。原生 PTY 支持和后代进程清理保证仍由 provider 决定。单一可写连接避免竞争的输入和尺寸流,显式接管允许从另一页面恢复操作。Session 的沙箱模式改变时,用户终端保持打开
 
 Agent 终端和可移植执行环境两篇记录仍保留,其所有权与 provider 决策继续独立有效,不被浏览器终端取代。
 

+ 6 - 0
.agents/notes/implemented/feature/2026-09-15-bundled-office-skills.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 .agents/notes/implemented/feature/2026-09-15-bundled-office-skills.md
+2026-09-15-bundled-office-skills.md: 089ca0326a7c53d4ee023608010efd49a8616db2
+2026-09-15-bundled-office-skills.zh.md: cd10aa863b1149594e9eb6b6a8e479511424f20d

+ 31 - 0
.agents/notes/implemented/feature/2026-09-15-bundled-office-skills.md

@@ -0,0 +1,31 @@
+# Agent Note: Bundled Office skills with structural verification
+
+Status: implemented
+
+English | [中文](2026-09-15-bundled-office-skills.zh.md)
+
+## Problem
+
+Office tasks need format-specific editing guidance and dependable file checks. Requiring users to install interpreters, package managers, or rendering command-line tools interrupts ordinary document delivery. Structural heuristics can also reject valid merged tables, multi-section documents, or Chinese text without observing an actual layout defect.
+
+## Decision
+
+The [Office provider](../../../../packages/skill/skill-office/README.md) contributes three independently discoverable skills at the bundled rank. The default workflow uses `load_workspace_dependencies` and its Python executable; explicit user and AGENTS.md environment choices take precedence. A configurable absolute asset root lets Desktop expose Python-readable resources outside its application archive. Registration validates the required resources and YAML descriptions; loaded instructions exclude the metadata. Disposal removes every candidate.
+
+One standard-library checker recognizes Transitional and Strict OOXML namespaces, validates ZIP/XML integrity and internal relationships, reports format-specific structure, and checks only explicit text or count assertions. Corrupt or encrypted ZIP members produce the same JSON package-failure report as other invalid documents. DOCX table summaries count logical grid columns, including merged cells. Section geometry is reported rather than judged against the final section; font filenames do not establish glyph coverage. XLSX formula counts never imply recalculation. Text assertions follow section and note references and worksheet string indices, so retained headers, unused note definitions, comments, glossary entries, and unused strings cannot satisfy requested wording.
+
+Desktop mounts the skill provider and runtime query independently of document rendering. Word uses python-docx, PowerPoint creation and editing use python-pptx, and Excel uses openpyxl and pandas. The managed payload and the ordinary creation examples require neither a rendering engine nor a separate presentation authoring library.
+
+Office skills and the bundled-runtime query remain registered without a rendering service. Visual inspection depends on the active model accepting images and a rendering tool being available. Otherwise the skills complete structural and content checks and deliver with the unverified visual scope stated. `present` refers to the current workspace source file; it does not preserve a private copy.
+
+## Alternatives considered
+
+**Require a plan and a local renderer before every delivery.** Simple edits do not need a fixed planning artifact, and models without image input cannot judge rendered pages. Mandatory renderer installation would turn an optional quality signal into a dependency unrelated to many requests.
+
+**Judge layout using package structure and font-name guesses.** Merged cells, different section widths, font substitution, and application layout rules prevent those observations from establishing rendered correctness. The checker reports facts and leaves visual judgments to actual images.
+
+**Share one undifferentiated Office skill.** Format-specific discovery avoids loading spreadsheet formula guidance for a Word edit or presentation instructions for a cell update. The deterministic checker remains shared because all three formats use the same package relationship rules.
+
+## Consequences
+
+The provider supplies reusable instructions without selecting or installing a deployment runtime. The checker is portable wherever the supported Python standard library works, but it cannot establish Office rendering fidelity, advanced feature preservation, or formula results. Loader and disposal tests cover resource relocation, activation failures, and absent rendering services. A recorded Session pins the Office catalog and loaded instruction body. Checker tests cover structural failures and JSON diagnostics; native payload smoke executes the copied checker with the bundled interpreter.

+ 31 - 0
.agents/notes/implemented/feature/2026-09-15-bundled-office-skills.zh.md

@@ -0,0 +1,31 @@
+# Agent Note: Bundled Office skills with structural verification
+
+Status: implemented
+
+[English](2026-09-15-bundled-office-skills.md) | 中文
+
+## 问题
+
+Office 任务需要针对文件格式的编辑指引和可靠的文件检查。要求用户安装解释器、包管理器或渲染命令行工具,会中断普通文档交付。结构启发式规则也可能在未观察到实际版式缺陷时,误拒有效的合并表格、多分节文档或中文文本。
+
+## 决策
+
+[Office 提供方](../../../../packages/skill/skill-office/README.zh.md)以内置优先级提供三个可独立发现的 skill(技能)。默认工作流使用 `load_workspace_dependencies` 及其 Python 可执行文件;用户和 AGENTS.md 明确指定的环境优先。可配置的绝对资源根目录让 Desktop 在应用归档之外暴露 Python 可读取的资源。注册时验证必需资源与 YAML 描述;加载后的指令不包含元数据。卸载时移除全部候选项。
+
+一个仅依赖标准库的检查器识别 Transitional 与 Strict OOXML 命名空间,验证 ZIP/XML 完整性与包内引用,报告各格式的结构,并只检查明确指定的文本或数量断言。损坏或加密的 ZIP 成员与其他无效文档一样生成 JSON 包失败报告。DOCX 表格摘要计算逻辑网格列数,包含合并单元格。分节几何信息仅报告,不以最终分节判断全文;字体文件名不能证明字形覆盖范围。XLSX 公式数量不代表已执行重算。文本断言跟随分节与脚注/尾注引用及工作表字符串索引,因此保留的页眉、未使用的脚注/尾注定义、批注、词库条目和未使用的字符串不能满足措辞要求。
+
+Desktop 独立于文档渲染挂载技能提供者和运行时查询。Word 使用 python-docx,PowerPoint 创建和编辑使用 python-pptx,Excel 使用 openpyxl 和 pandas。受管理产物和普通创建示例都不要求渲染引擎或单独的演示文稿创作库。
+
+缺少渲染服务时,Office skills 与内置运行时查询仍保持注册。视觉检查取决于当前模型支持图片且有可用渲染工具。否则,skill 完成结构与内容检查,并在交付时说明未验证的视觉范围。`present` 引用工作区中的当前源文件,不保存私有副本。
+
+## 考虑过的替代方案
+
+**每次交付都强制要求计划与本地渲染器。** 简单编辑不需要固定计划文件,不支持图片的模型也无法判断渲染页面。强制安装渲染器会将可选质量信号变成与许多请求无关的依赖。
+
+**通过包结构与字体名猜测判断版式。** 合并单元格、不同分节宽度、字体替换和应用排版规则,使这些观察不足以证明渲染正确。检查器报告事实,将视觉判断留给实际图像。
+
+**共用一个不区分格式的 Office skill。** 按格式发现可避免在 Word 编辑时加载公式指引,或在单元格更新时加载演示文稿指令。确定性检查器仍然共享,因为三种格式采用相同的包引用规则。
+
+## 影响
+
+提供方提供可复用指令,不选择或安装部署运行时。检查器可在受支持的 Python 标准库可用之处运行,但不能证明 Office 渲染保真度、高级特性保留或公式结果。Loader 和卸载测试覆盖资源重定位、激活失败与渲染服务缺失。录制 Session 固定 Office 目录与加载后的指令正文。检查器测试覆盖结构错误与 JSON 诊断;原生产物冒烟检查通过内置解释器执行复制后的检查器。

+ 12 - 4
apps/cli/tests/desktop-host.e2e.ts

@@ -1,9 +1,9 @@
 /** Built Desktop Host lifecycle with Electron disconnecting before profile startup settles. */
 
 import { fork } from 'node:child_process'
-import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
 import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
 import { fileURLToPath } from 'node:url'
 import { finished } from 'node:stream/promises'
 import { expect, it, onTestFinished } from 'vitest'
@@ -11,7 +11,15 @@ import { expect, it, onTestFinished } from 'vitest'
 it.each([false, true])('settles startup after parent IPC disconnect (boot failure: %s)', async (fail) => {
   const root = mkdtempSync(join(tmpdir(), 'desktop-disconnect-'))
   const modules = join(root, 'node_modules', '@deepseek-ai')
-  for (const name of ['dsh-app-boot', 'dsh', 'dsh-home-paths', 'dsh-tools']) mkdirSync(join(modules, name), { recursive: true })
+  const hostDirectory = fileURLToPath(new URL('../../desktop-host/', import.meta.url))
+  const manifest = JSON.parse(readFileSync(join(hostDirectory, 'package.json'), 'utf8')) as { dependencies: Record<string, string> }
+  const stubbed = new Set(['@deepseek-ai/dsh-app-boot', '@deepseek-ai/dsh', '@deepseek-ai/dsh-home-paths', '@deepseek-ai/dsh-tools'])
+  for (const name of Object.keys(manifest.dependencies)) {
+    const destination = join(root, 'node_modules', name)
+    mkdirSync(dirname(destination), { recursive: true })
+    if (stubbed.has(name)) mkdirSync(destination)
+    else symlinkSync(realpathSync(join(hostDirectory, 'node_modules', name)), destination, 'junction')
+  }
   for (const [name, source] of [
     ['dsh-home-paths', `export const resolveDshHome = () => ${JSON.stringify(root)}`],
     ['dsh-tools', 'export const defineTool = value => value'],
@@ -35,7 +43,7 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
     }
   `)
   const entry = join(root, 'index.js')
-  copyFileSync(fileURLToPath(new URL('../../desktop-host/lib/index.js', import.meta.url)), entry)
+  copyFileSync(join(hostDirectory, 'lib', 'index.js'), entry)
   const child = fork(entry, [root, root], { execArgv: [], stdio: ['ignore', 'ignore', 'pipe', 'ipc'] })
   let stderr = ''
   child.stderr!.setEncoding('utf8').on('data', (chunk: string) => { stderr += chunk })

+ 2 - 1
apps/desktop-host/package.json

@@ -16,6 +16,7 @@
     "@deepseek-ai/dsh-client-connection": "workspace:^",
     "@deepseek-ai/dsh-home-paths": "workspace:^",
     "@deepseek-ai/dsh-host-webserver": "workspace:^",
-    "@deepseek-ai/dsh-tools": "workspace:^"
+    "@deepseek-ai/dsh-tools": "workspace:^",
+    "@deepseek-ai/dsh-skill-office": "workspace:^"
   }
 }

+ 2 - 2
apps/desktop-host/src/index.ts

@@ -6,7 +6,7 @@ import { runProfile } from '@deepseek-ai/dsh/profile-boot'
 import type {} from '@deepseek-ai/dsh-client-connection'
 import type {} from '@deepseek-ai/dsh-host-webserver'
 import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
-import * as workspaceDependencies from './workspace-dependencies.ts'
+import * as desktopOffice from './office.ts'
 
 async function main(): Promise<void> {
   const runtimeDir = process.argv[2] as string
@@ -32,7 +32,7 @@ async function main(): Promise<void> {
   })
   process.once('disconnect', () => { void stop() })
   const { ctx } = await application
-  await ctx.plugin(workspaceDependencies, {
+  await ctx.plugin(desktopOffice, {
     source: process.argv[4] ?? join(runtimeDir, '..', 'runtime', 'primary-runtime'),
     root: join(resolveDshHome(), 'dsh-runtimes', 'dsh-primary-runtime'),
   })

+ 26 - 0
apps/desktop-host/src/office.ts

@@ -0,0 +1,26 @@
+/** Desktop Office skills and bundled authoring dependencies. */
+
+import { dirname, join } from 'node:path'
+import type { Context } from '@deepseek-ai/cordis'
+import * as officeSkills from '@deepseek-ai/dsh-skill-office'
+import * as workspaceDependencies from './workspace-dependencies.ts'
+
+/** Loader identity for the application-owned Office composition. */
+export const name = 'desktop-office'
+/** Application-selected bundled payload and installation directories. */
+export interface Config {
+  /** Bundled payload directory. Missing sibling `office-skills` resources fail Host startup. */
+  readonly source: string
+  /** Harness-home directory where workspace dependencies are installed. */
+  readonly root: string
+}
+
+/**
+ * Enable offline Office authoring and structural checks in the Desktop profile.
+ * @param ctx - Profile scope; child plugins declare their own service requirements.
+ * @param config - Bundled payload source and Harness-home installation root.
+ */
+export async function apply(ctx: Context, config: Config): Promise<void> {
+  await ctx.plugin(workspaceDependencies, config)
+  await ctx.plugin(officeSkills, { assetRoot: join(dirname(config.source), 'office-skills') })
+}

+ 58 - 0
apps/desktop-host/tests/office.spec.ts

@@ -0,0 +1,58 @@
+import { cp, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { Context } from '@deepseek-ai/cordis'
+import Loader from '@deepseek-ai/cordis-plugin-loader'
+import Include from '@deepseek-ai/cordis-plugin-include'
+import AgentRegistry from '@deepseek-ai/dsh-agent'
+import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
+import SkillRegistry from '@deepseek-ai/dsh-skill'
+import ToolRuntime from '@deepseek-ai/dsh-tools'
+import { expect, it } from 'vitest'
+import * as desktopOffice from '../src/office.ts'
+
+it('loads Desktop Office skills without a document renderer and removes them on disposal', async () => {
+  const root = await mkdtemp(join(tmpdir(), 'desktop-office-'))
+  const ctx = new Context()
+  try {
+    const assets = join(root, 'runtime', 'office-skills')
+    await cp(new URL('../../../packages/skill/skill-office/assets/', import.meta.url), assets, { recursive: true })
+    ctx.baseUrl = pathToFileURL(root).href + '/'
+    await ctx.plugin(Loader)
+    ctx.loader.builtins.include = Include
+    expect('default' in desktopOffice).toBe(false)
+    expect(ctx.loader.unwrapExports(desktopOffice)).toBe(desktopOffice)
+    const modules = new Map<string, unknown>([
+      ['agents', AgentRegistry], ['systemPrompt', SystemPrompt], ['tools', ToolRuntime],
+      ['skills', SkillRegistry], ['office', desktopOffice],
+    ])
+    ctx.loader.internal = {
+      version: 'v2',
+      async import(specifier: string) {
+        if (!modules.has(specifier)) throw new Error(`unexpected plugin ${specifier}`)
+        return modules.get(specifier)
+      },
+    } as unknown as NonNullable<typeof ctx.loader.internal>
+    const config = join(root, 'cordis.yml')
+    await writeFile(config, [
+      '- name: agents', '- name: systemPrompt', '- name: tools', '- name: skills', '- name: office',
+      '  config:', `    source: ${JSON.stringify(join(root, 'runtime', 'primary-runtime'))}`,
+      `    root: ${JSON.stringify(join(root, 'installed'))}`, '',
+    ].join('\n'))
+    await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(config).href } })
+    await ctx.loader.await()
+    for (const entry of ctx.loader.entries()) await entry.fiber?.await()
+    expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['office-docx', 'office-pptx', 'office-xlsx'])
+    expect((await ctx.skills.get('office-pptx'))?.resourceBase).toEqual({ kind: 'directory', path: join(assets, 'office-pptx') })
+    expect(ctx.tools.schemas().map(tool => tool.name)).toEqual(['load_workspace_dependencies'])
+    const entry = [...ctx.loader.entries()].find(entry => entry.options.name === 'office')
+    expect(entry).toBeDefined()
+    await entry?.fiber?.dispose()
+    expect(await ctx.skills.list()).toEqual([])
+    expect(ctx.tools.schemas()).toEqual([])
+  } finally {
+    await ctx.fiber.dispose()
+    await rm(root, { recursive: true, force: true })
+  }
+})

+ 1 - 0
apps/desktop-host/tsconfig.json

@@ -8,6 +8,7 @@
     "src"
   ],
   "references": [
+    { "path": "../../packages/skill/skill-office" },
     { "path": "../../packages/util/home-paths" },
     { "path": "../../packages/core/tools" },
     {

+ 2 - 2
apps/desktop/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 apps/desktop/README.md
-README.md: bf4f22be5aafa1323433d2eb396e9a5417dc3511
-README.zh.md: 058e6b223a4522c993243b463bc7cbd5796529aa
+README.md: d19304ae123aefe57af649c5d6a02c4db867314e
+README.zh.md: 3d5b84c23701c4915fb1983fd6363c1ce2dc3059

+ 2 - 0
apps/desktop/README.md

@@ -18,6 +18,8 @@ The current Windows Python payload contains unsigned native extensions. Smart Ap
 
 Desktop carries independent Python, Node.js and pnpm distributions. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml and XlsxWriter with their complete dependencies. The `load_workspace_dependencies` tool installs this payload offline on first use under `$DSH_HOME/dsh-runtimes/dsh-primary-runtime` (normally `~/.dsh/dsh-runtimes/dsh-primary-runtime`) and returns absolute interpreter, pnpm script and library paths plus `pythonDistributions`, the bundled distribution names and versions. The version report excludes user-installed additions. Office tasks prefer these libraries unless user or workspace instructions select another environment. Execute the pnpm script with the returned Node executable. The returned Node library directory is reserved for bundled libraries, not pnpm's global installation directory.
 
+Desktop registers `office-docx`, `office-pptx`, and `office-xlsx` by default. The skills use the bundled Python libraries for creation and focused edits, then reopen the files and run a shared structural checker before delivery. PowerPoint creation and editing use python-pptx. Skill resources are copied to `runtime/office-skills` outside ASAR so Python can read the checker. An available `render_document` tool can add visual inspection; its absence does not prevent authoring or delivery. See the [Office skill package](../../packages/skill/skill-office/README.md) for checks and limitations.
+
 The payload follows the Desktop release. `runtime.json` records the Desktop version, target, component and Python distribution versions, and a digest of the selected target’s locked payload inputs and assembly format. Distribution names use PEP 503 normalization; duplicate normalized names and conflicting numpy/pandas component and distribution versions reject the manifest. Matching installations are reused; a dependency or archive change replaces the directory after a complete staged copy even when the Desktop version stays unchanged. Older manifests without a digest are replaced on their next installation. User-added Python packages remain only while the payload identity matches. A failed directory replacement retains the previous installation; Windows may refuse replacement while an interpreter is still running.
 
 The private Desktop `runtime/bin` directory is added only to package-installation processes, not the Host PATH inherited by PTC and agent shells. This tool does not change PATH, environment variables or user package-manager configuration. pnpm retains its own defaults and user settings for global packages, executable entries and its store, including native errors when the environment does not support global installation. There is no separate dependency updater. [The primary-runtime decision](../../.agents/notes/implemented/feature/2026-09-14-desktop-primary-runtime.md) records these choices.

+ 2 - 0
apps/desktop/README.zh.md

@@ -18,6 +18,8 @@ macOS PNG 使用带留白的圆角底板,供传统 ICNS 打包使用,包含
 
 Desktop 携带独立的 Python、Node.js 和 pnpm 分发包。Python 包含 numpy、pandas、python-docx、python-pptx、openpyxl、Pillow、lxml、XlsxWriter 及其完整依赖。`load_workspace_dependencies` 工具首次使用时,将该产物离线安装到 `$DSH_HOME/dsh-runtimes/dsh-primary-runtime`(通常为 `~/.dsh/dsh-runtimes/dsh-primary-runtime`),并返回解释器、pnpm 脚本和库目录的绝对路径,以及记录内置分发包名称与版本的 `pythonDistributions`。版本报告不包含用户自行安装的包。Office 任务默认使用这些库,用户或工作区指令指定其他环境时遵循其要求。pnpm 脚本通过返回的 Node 可执行文件运行。返回的 Node 库目录为随包交付的库预留,不是 pnpm 的全局安装目录。
 
+Desktop 默认注册 `office-docx`、`office-pptx` 和 `office-xlsx`。这些技能使用内置 Python 库创建文件和进行定点编辑,随后重新打开文件,并在交付前运行共享结构检查器。PowerPoint 的创建和编辑使用 python-pptx。技能资源复制到 ASAR 外的 `runtime/office-skills`,让 Python 可以读取检查器。可用的 `render_document` 工具可以补充视觉检查;缺少该工具不妨碍创作或交付。检查范围与限制见 [Office 技能包](../../packages/skill/skill-office/README.zh.md)。
+
 该产物随 Desktop 版本发布。`runtime.json` 记录 Desktop 版本、目标平台、组件与 Python 分发包版本,以及所选目标的锁定产物输入与组装格式的摘要。分发包名称按 PEP 503 归一化;名称归一化后重复,或 numpy/pandas 的组件版本与分发包版本冲突时,清单会被拒绝。匹配的安装会被复用;依赖或压缩包变化后,即使 Desktop 版本不变,也会在完整暂存副本完成后替换目录。不含摘要的旧清单会在下次安装时被替换。用户自行添加的 Python 包仅在产物身份一致时保留。目录替换失败时保留之前的安装;解释器仍在运行时,Windows 可能拒绝替换。
 
 Desktop 私有的 `runtime/bin` 目录仅添加到包安装进程,不进入 PTC 和 agent shell 从 Host 继承的 PATH。该工具不修改 PATH、环境变量或用户包管理器配置。pnpm 的全局包、命令入口和 store 保留自身默认值及用户设置,包括环境不支持全局安装时的原生错误。不提供独立依赖更新器。[第一方 Runtime 决策](../../.agents/notes/implemented/feature/2026-09-14-desktop-primary-runtime.zh.md)记录这些选择。

+ 17 - 2
apps/desktop/scripts/prepare-primary-runtime.ts

@@ -6,7 +6,7 @@ import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } f
 import { cp } from 'node:fs/promises'
 import { createRequire } from 'node:module'
 import { tmpdir } from 'node:os'
-import { dirname, join } from 'node:path'
+import { dirname, join, resolve } from 'node:path'
 import extractZip from 'extract-zip'
 import { x as extractTar } from 'tar'
 import { workspaceDependencyPaths, type PrimaryRuntimeManifest } from '../../desktop-host/src/primary-runtime.ts'
@@ -75,6 +75,17 @@ export async function unpackPrimaryRuntimeWheel(archive: string, destination: st
   })
 }
 
+/**
+ * Copy the skill package's complete asset tree to ordinary filesystem resources.
+ * @param source - The package's assets directory.
+ * @param destination - Desktop runtime resource directory outside ASAR.
+ * @returns Resolves after replacing the external assets with the complete package tree.
+ */
+export async function prepareOfficeSkillAssets(source: string, destination: string): Promise<void> {
+  rmSync(destination, { recursive: true, force: true })
+  await cp(source, destination, { recursive: true, dereference: true })
+}
+
 /**
  * Materialize the selected Desktop target's primary runtime in its build resources.
  * @returns Resolves after dependency installation and native-target execution checks.
@@ -131,6 +142,9 @@ export async function preparePrimaryRuntime(): Promise<void> {
   } finally {
     rmSync(staging, { recursive: true, force: true })
   }
+  const hostRequire = createRequire(resolve(import.meta.dirname, '..', '..', 'desktop-host', 'package.json'))
+  await prepareOfficeSkillAssets(join(dirname(hostRequire.resolve('@deepseek-ai/dsh-skill-office/package.json')), 'assets'),
+    join(paths.runtime, 'office-skills'))
   smokePrimaryRuntime(join(paths.runtime, 'primary-runtime'))
 }
 
@@ -144,7 +158,8 @@ export function smokePrimaryRuntime(root: string): void {
   if (manifest.pythonPackages === undefined) throw new Error('primary runtime: missing Python distribution versions; prepare the payload before running its smoke checks.')
   const entries = workspaceDependencyPaths(root, manifest)
   const options = { stdio: 'inherit', timeout: 120_000 } as const
-  execFileSync(entries.python, ['-I', '-B', join(import.meta.dirname, 'smoke-primary-runtime.py'), JSON.stringify(manifest.pythonPackages), manifest.components.python], options)
+  execFileSync(entries.python, ['-I', '-B', join(import.meta.dirname, 'smoke-primary-runtime.py'), JSON.stringify(manifest.pythonPackages),
+    manifest.components.python, join(dirname(root), 'office-skills', 'scripts', 'check_office.py')], options)
   execFileSync(entries.python, ['-I', '-B', '-m', 'pip', 'check'], options)
   execFileSync(entries.node, ['-e', `if (process.versions.node !== ${JSON.stringify(manifest.components.node)}) process.exit(1)`], options)
   execFileSync(entries.node, [entries.pnpm, '--version'], options)

+ 9 - 0
apps/desktop/scripts/smoke-primary-runtime.py

@@ -4,6 +4,7 @@ import importlib.metadata
 import json
 from pathlib import Path
 import re
+import subprocess
 import sys
 import tempfile
 
@@ -83,6 +84,14 @@ def main():
         finally:
             reopened_workbook.close()
         assert pandas.read_excel(root / "workbook.xlsx")["Value"].iloc[0] == 42
+        for file, arguments in [
+            ("document.docx", ["--contains", "Office 文档"]),
+            ("presentation.pptx", ["--contains", "Office 演示", "--count", "1"]),
+            ("workbook.xlsx", ["--contains", "Value", "--count", "1"]),
+        ]:
+            checked = subprocess.run([sys.executable, "-I", "-B", sys.argv[3], str(root / file), *arguments],
+                                     check=False, capture_output=True, text=True, timeout=30)
+            assert checked.returncode == 0 and json.loads(checked.stdout)["verdict"] == "pass", checked.stdout + checked.stderr
     print("Office runtime versions and document round trips passed.")
 
 

+ 2 - 1
apps/desktop/src/host-process.ts

@@ -72,7 +72,8 @@ export class DesktopHostProcess {
    * @param inspectPort - Optional loopback inspector port for workspace development.
    * @param environment - Environment inherited by the Host and its plugin subprocesses.
    * @param onFailure - Receives the first unexpected child failure, including after readiness.
-   * @param primaryRuntime - Optional payload location for bundled script dependencies.
+   * @param primaryRuntime - Optional bundled dependency payload; when supplied, missing sibling
+   *   `office-skills` resources fail Host startup.
    * @param profileResolution - Package resolution mode for the application-owned profile.
    */
   constructor(

+ 24 - 2
apps/desktop/tests/primary-runtime-preparation.spec.ts

@@ -1,10 +1,10 @@
 import { createHash } from 'node:crypto'
-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
 import { tmpdir } from 'node:os'
 import { basename, join } from 'node:path'
 import { zipSync } from 'fflate'
 import { expect, it } from 'vitest'
-import { downloadPrimaryRuntimeAsset, primaryRuntimePayloadDigest, smokePrimaryRuntime, unpackPrimaryRuntimeWheel } from '../scripts/prepare-primary-runtime.ts'
+import { downloadPrimaryRuntimeAsset, prepareOfficeSkillAssets, primaryRuntimePayloadDigest, smokePrimaryRuntime, unpackPrimaryRuntimeWheel } from '../scripts/prepare-primary-runtime.ts'
 import lock from '../scripts/primary-runtime-lock.json' with { type: 'json' }
 
 const libraryWheel = Buffer.from('UEsDBAoAAAAAAASeLl0sYMPjDAAAAAwAAAAJAAAAc2FtcGxlLnB5c2FtcGxlID0gNDIKUEsBAh4DCgAAAAAABJ4uXSxgw+MMAAAADAAAAAkAAAAAAAAAAQAAAKSBAAAAAHNhbXBsZS5weVBLBQYAAAAAAQABADcAAAAzAAAAAAA=', 'base64')
@@ -107,3 +107,25 @@ it('rejects library files requiring an unsupported installation scheme', async (
     await rm(root, { recursive: true, force: true })
   }
 })
+
+it('copies complete Office resources outside the application archive and removes obsolete assets', async () => {
+  const root = await mkdtemp(join(tmpdir(), 'desktop-office-assets-'))
+  try {
+    const source = join(root, 'package', 'assets')
+    const destination = join(root, 'Contents', 'Resources', 'runtime', 'office-skills')
+    await mkdir(join(source, 'scripts'), { recursive: true })
+    await writeFile(join(source, 'scripts', 'check_office.py'), 'print("checker")\n')
+    for (const name of ['office-docx', 'office-pptx', 'office-xlsx']) {
+      await mkdir(join(source, name))
+      await writeFile(join(source, name, 'SKILL.md'), `# ${name}\n`)
+    }
+    await prepareOfficeSkillAssets(source, destination)
+    await writeFile(join(destination, 'obsolete.py'), 'old helper')
+    await prepareOfficeSkillAssets(source, destination)
+    for (const name of ['office-docx', 'office-pptx', 'office-xlsx']) {
+      expect(await readFile(join(destination, name, 'SKILL.md'), 'utf8')).toBe(`# ${name}\n`)
+    }
+    expect(await readFile(join(destination, 'scripts', 'check_office.py'), 'utf8')).toBe('print("checker")\n')
+    await expect(readFile(join(destination, 'obsolete.py'))).rejects.toMatchObject({ code: 'ENOENT' })
+  } finally { await rm(root, { recursive: true, force: true }) }
+})

+ 55 - 5
apps/web/tests/permission-policy-context.e2e.ts

@@ -3,7 +3,8 @@
 // the real provider, while replay keeps the same provider-authored behavior
 // keyless. Assertions read the exact durable header, runtime-context messages,
 // and tool calls, so assistant prose alone cannot satisfy the scenario.
-import { readFile } from 'node:fs/promises'
+import { mkdtemp, readFile, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
 import { join } from 'node:path'
 import { fileURLToPath } from 'node:url'
 import type { Browser, Page } from 'playwright'
@@ -11,6 +12,8 @@ import { chromium } from 'playwright'
 import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
 import { canonicalPath } from '@deepseek-ai/dsh-sandbox'
 import type { SessionEvent } from '@deepseek-ai/dsh-session'
+import type { WebTerminalId } from '@deepseek-ai/dsh-api-terminal-controller/types'
+import type {} from '@deepseek-ai/dsh-api-terminal-controller'
 import {
   assertFinalWorkspaceSnapshot, assertFixtureInventory, fixtureUserPrompts, launchWebScaffold, recordFixture,
   watchConsole, webSnapshotMode, type WebScaffold,
@@ -65,10 +68,18 @@ describe('web e2e: current sandbox policy reaches the model before tools', () =>
   let tripwire: ReturnType<typeof watchConsole>
   let disposeApproval: (() => void) | undefined
   let sessionWorkspace: string | undefined
+  let outsideWorkspace: string | undefined
+  let terminalId: WebTerminalId | undefined
   const sessionEvents: SessionEvent[] = []
 
   beforeAll(async () => {
-    scaffold = await launchWebScaffold(MODE === 'record' ? {} : { replayFixture: FIXTURE, compareReplaySession: true })
+    scaffold = await launchWebScaffold({
+      ...MODE === 'record' ? {} : { replayFixture: FIXTURE, compareReplaySession: true },
+      ...process.platform === 'win32' ? {} : {
+        extraOverlayPath: fileURLToPath(new URL('./fixtures/sidebar-terminal.patch.yml', import.meta.url)),
+      },
+    })
+    outsideWorkspace = await mkdtemp(join(tmpdir(), 'dsh-user-terminal-'))
     disposeApproval = scaffold.ctx.on('approval/request', () => Promise.resolve('allowed-once'), { prepend: true })
     scaffold.ctx.on('session/event', (session, event: SessionEvent) => {
       sessionWorkspace = session.header.cwd
@@ -83,11 +94,48 @@ describe('web e2e: current sandbox policy reaches the model before tools', () =>
   }, 120_000)
 
   afterAll(async () => {
-    await browser?.close()
-    disposeApproval?.()
-    await scaffold?.close()
+    try { await browser?.close() } finally {
+      disposeApproval?.()
+      try { await scaffold?.close() } finally {
+        if (outsideWorkspace !== undefined) await rm(outsideWorkspace, { recursive: true, force: true })
+      }
+    }
   })
 
+  async function verifyUserTerminal(preset: string): Promise<void> {
+    // The pinned interactive Bash profile is POSIX-only; Windows still replays every Agent policy assertion.
+    if (process.platform === 'win32') return
+    if (terminalId === undefined) {
+      const expand = page.locator('[data-sidebar-right-expand]')
+      if (await expand.isVisible()) await expand.click()
+      await page.locator('[data-sidebar-right-guide-entry="terminal"]').getByRole('button', { name: /^New terminal/u }).click()
+      await expect.poll(() => page.locator('.xterm-rows:visible').innerText()).toContain('bash-')
+    }
+    const agent = scaffold.ctx.agents.list()[0]
+    if (agent === undefined || sessionWorkspace === undefined || outsideWorkspace === undefined) throw new Error('Terminal test has no Session workspace')
+    const terminals = scaffold.ctx.terminalController.list(agent.id)
+    expect(terminals).toHaveLength(1)
+    terminalId ??= terminals[0]!.id
+    expect(terminals[0]).toMatchObject({ id: terminalId, state: 'running', cwd: sessionWorkspace })
+    const outsideFile = join(outsideWorkspace, 'terminal-access.txt')
+    const quotedOutside = `'${outsideFile.replaceAll("'", "'\\''")}'`
+    const beforeInput = sessionEvents.length
+    await page.locator('.xterm-helper-textarea:visible').click()
+    await page.keyboard.insertText(`printf '%s' '${preset}' > terminal-access.txt; printf '%s' '${preset}' > ${quotedOutside}`)
+    await page.keyboard.press('Enter')
+    await expect.poll(() => readFile(join(sessionWorkspace!, 'terminal-access.txt'), 'utf8')).toBe(preset)
+    await expect.poll(() => readFile(outsideFile, 'utf8')).toBe(preset)
+    expect(sessionEvents).toHaveLength(beforeInput)
+    await page.keyboard.insertText('rm terminal-access.txt')
+    await page.keyboard.press('Enter')
+    await expect.poll(async () => {
+      try { await readFile(join(sessionWorkspace!, 'terminal-access.txt')); return false } catch (error) {
+        if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+        return true
+      }
+    }).toBe(true)
+  }
+
   it('switches read-only, danger-full-access, and workspace-write through the real GUI command path', async () => {
     onTestFailed(() => saveFailureShot(page, 'web-e2e-permission-policy-context'))
     if (MODE !== 'record') {
@@ -107,11 +155,13 @@ describe('web e2e: current sandbox policy reaches the model before tools', () =>
       await input.press('Enter')
       sessionId = await settled
       await input.waitFor({ timeout: 10_000 })
+      await verifyUserTerminal(preset)
     }
 
     await writeComposerDraft(page, input, '/permission read-only')
     await input.press('Enter')
     await page.getByRole('button', { name: 'Access mode, current: Read Only' }).waitFor({ timeout: 10_000 })
+    await verifyUserTerminal('read-only')
     const settled = scaffold.whenTurnSettled()
     await writeComposerDraft(page, input, PROMPTS[3])
     await input.press('Enter')

+ 2 - 2
docs/capability-seams.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 docs/capability-seams.md
-capability-seams.md: 5db5d11195355330b3c0bf3f58c928bd3533cf85
-capability-seams.zh.md: bfcd60916f615f173bc167623462841e25eca2a2
+capability-seams.md: b40adeafe7cec40dfbbe6a65788e5888097ef57f
+capability-seams.zh.md: b33986f205c2e1352343c7c5ad3700efb027eb61

+ 3 - 1
docs/capability-seams.md

@@ -144,6 +144,7 @@ flowchart LR
   svc_skills["ctx.skills<br/>Skill provider registry"]
   pkg_skill_badge["skill-badge"]
   pkg_skill_filesystem["skill-filesystem"]
+  pkg_skill_office["skill-office"]
   svc_agents["ctx.agents<br/>Agent service"]
   pkg_acp["acp"]
   pkg_agent_default_model["agent-default-model"]
@@ -344,6 +345,7 @@ flowchart LR
   pkg_skill --> svc_skills
   pkg_skill_badge --> svc_skills
   pkg_skill_filesystem --> svc_skills
+  pkg_skill_office --> svc_skills
   pkg_spill --> svc_spillStore
   pkg_spill_local --> svc_spillStore
   pkg_ssh --> svc_ssh
@@ -570,7 +572,7 @@ flowchart LR
 | `ctx.commands` | `core` | [`commands`](../packages/interaction/commands) | - | - | - | Plugins register direct human commands without sending invocations to the model. |
 | `ctx.sessionProjections` | `core` | [`session-projection`](../packages/session/session-projection) | - | [`api-session-controller`](../packages/api/session-controller), [`tool-todo`](../packages/todo/tool-todo), [`session-title`](../packages/session/session-title) | - | Domains register state-driven fold units; the eager drive keeps per-session watermark states and the Session controller serves baselines and pushes changed values. |
 | `ctx.sessionProjectionCache` | `core` | [`session-projection-cache`](../packages/session/session-projection-cache) | - | [`api-session-controller`](../packages/api/session-controller), [`session-query`](../packages/session-query/session-query), [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent) | - | Durably checkpoints projection unit states per session (throttled + turn/end/detach mandatory points) and serves the cold-read ladder: cache row + persistence tail replay, so listings never load full logs. |
-| `ctx.skills` | `seam` | [`skill`](../packages/skill/skill) | [`skill-badge`](../packages/skill/skill-badge), [`skill-filesystem`](../packages/skill/skill-filesystem) | [`tool-skill`](../packages/skill/tool-skill) | - | Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies. |
+| `ctx.skills` | `seam` | [`skill`](../packages/skill/skill) | [`skill-badge`](../packages/skill/skill-badge), [`skill-filesystem`](../packages/skill/skill-filesystem), [`skill-office`](../packages/skill/skill-office) | [`tool-skill`](../packages/skill/tool-skill) | - | Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies. |
 | `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver) | - | Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation. |
 | `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Layers the default ModelSelection through settings so direct and Host-backed Agent entry points share one state owner. |
 | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. |

+ 3 - 1
docs/capability-seams.zh.md

@@ -146,6 +146,7 @@ flowchart LR
   svc_skills["ctx.skills<br/>Skill provider registry"]
   pkg_skill_badge["skill-badge"]
   pkg_skill_filesystem["skill-filesystem"]
+  pkg_skill_office["skill-office"]
   svc_agents["ctx.agents<br/>Agent service"]
   pkg_acp["acp"]
   pkg_agent_default_model["agent-default-model"]
@@ -346,6 +347,7 @@ flowchart LR
   pkg_skill --> svc_skills
   pkg_skill_badge --> svc_skills
   pkg_skill_filesystem --> svc_skills
+  pkg_skill_office --> svc_skills
   pkg_spill --> svc_spillStore
   pkg_spill_local --> svc_spillStore
   pkg_ssh --> svc_ssh
@@ -572,7 +574,7 @@ flowchart LR
 | `ctx.commands` | `core` | [`commands`](../packages/interaction/commands) | - | - | - | 插件注册直接面向人的命令,而不会把调用发送给模型。 |
 | `ctx.sessionProjections` | `core` | [`session-projection`](../packages/session/session-projection) | - | [`api-session-controller`](../packages/api/session-controller), [`tool-todo`](../packages/todo/tool-todo), [`session-title`](../packages/session/session-title) | - | 各领域注册由状态驱动的折叠单元;主动驱动过程维护每个会话的水位状态,Session controller 提供 baseline 并推送发生变化的值。 |
 | `ctx.sessionProjectionCache` | `core` | [`session-projection-cache`](../packages/session/session-projection-cache) | - | [`api-session-controller`](../packages/api/session-controller), [`session-query`](../packages/session-query/session-query), [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent) | - | 按会话持久保存投影单元状态的检查点(节流检查点,以及轮次/结束/分离时的必选检查点),并提供冷读取阶梯:缓存行加持久化尾部回放,因此列表读取永远不需要加载完整日志。 |
-| `ctx.skills` | `seam` | [`skill`](../packages/skill/skill) | [`skill-badge`](../packages/skill/skill-badge), [`skill-filesystem`](../packages/skill/skill-filesystem) | [`tool-skill`](../packages/skill/tool-skill) | - | 合并提供方的 skill(技能)目录;tool-skill 渲染会话前缀目录,并加载完整的 skill 正文。 |
+| `ctx.skills` | `seam` | [`skill`](../packages/skill/skill) | [`skill-badge`](../packages/skill/skill-badge), [`skill-filesystem`](../packages/skill/skill-filesystem), [`skill-office`](../packages/skill/skill-office) | [`tool-skill`](../packages/skill/tool-skill) | - | 合并提供方的 skill(技能)目录;tool-skill 渲染会话前缀目录,并加载完整的 skill 正文。 |
 | `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver) | - | 拥有实时 Agent 句柄、创建/恢复工厂 seam,以及进程本地的发起方传播。 |
 | `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | 通过 settings 分层默认 `ModelSelection`,让直接入口与 Host 支撑的 Agent 入口共享同一个状态所有者。 |
 | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | 唯一的具体循环插件;扩展包依赖 dsh-agent 的事件和服务,而不依赖此包。 |

+ 2 - 2
docs/config-catalog.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 docs/config-catalog.md
-config-catalog.md: 57cb0c6b5db3177dfd4a777448cbd726a8e0957c
-config-catalog.zh.md: b34da72c2f3496748073171aa0dd3cceefb019bc
+config-catalog.md: 08c7559f2d83826a850b4eb5c18351bfd24e1707
+config-catalog.zh.md: f29345293fa50a38a631d73f9ba5094bc7fd47b3

+ 18 - 2
docs/config-catalog.md

@@ -233,7 +233,7 @@ Source: [`packages/api/settings-controller/src/index.ts:36`](../packages/api/set
 
 ## `@deepseek-ai/dsh-api-terminal-controller`
 
-Requires: `subprocess` · `sandboxPolicy` · `sessionProjections` · `typert`
+Requires: `subprocess` · `sandboxPolicy` · `typert`
 
 ```ts config-catalog
 /** Deployment limits and an optional shell profile. */
@@ -272,7 +272,7 @@ export interface Config {
 }
 ```
 
-Source: [`packages/api/terminal-controller/src/index.ts:28`](../packages/api/terminal-controller/src/index.ts)
+Source: [`packages/api/terminal-controller/src/index.ts:26`](../packages/api/terminal-controller/src/index.ts)
 
 <a id="deepseek-aidsh-api-workspace-files"></a>
 
@@ -2402,6 +2402,22 @@ export interface Config {
 
 Source: [`packages/skill/skill-filesystem/src/index.ts:49`](../packages/skill/skill-filesystem/src/index.ts)
 
+<a id="deepseek-aidsh-skill-office"></a>
+
+## `@deepseek-ai/dsh-skill-office`
+
+Requires: `skills`
+
+```ts config-catalog
+/** Office skill resource location. */
+export interface Config {
+  /** Absolute assets directory containing the three skill folders and shared scripts; defaults to packaged assets. */
+  assetRoot?: string
+}
+```
+
+Source: [`packages/skill/skill-office/src/index.ts:15`](../packages/skill/skill-office/src/index.ts)
+
 <a id="deepseek-aidsh-spill-local"></a>
 
 ## `@deepseek-ai/dsh-spill-local`

+ 18 - 2
docs/config-catalog.zh.md

@@ -235,7 +235,7 @@ export interface Config {
 
 ## `@deepseek-ai/dsh-api-terminal-controller`
 
-Requires: `subprocess` · `sandboxPolicy` · `sessionProjections` · `typert`
+Requires: `subprocess` · `sandboxPolicy` · `typert`
 
 ```ts config-catalog
 /** Deployment limits and an optional shell profile. */
@@ -274,7 +274,7 @@ export interface Config {
 }
 ```
 
-来源: [`packages/api/terminal-controller/src/index.ts:28`](../packages/api/terminal-controller/src/index.ts)
+来源: [`packages/api/terminal-controller/src/index.ts:26`](../packages/api/terminal-controller/src/index.ts)
 
 <a id="deepseek-aidsh-api-workspace-files"></a>
 
@@ -2404,6 +2404,22 @@ export interface Config {
 
 来源:[`packages/skill/skill-filesystem/src/index.ts:49`](../packages/skill/skill-filesystem/src/index.ts)
 
+<a id="deepseek-aidsh-skill-office"></a>
+
+## `@deepseek-ai/dsh-skill-office`
+
+依赖:`skills`
+
+```ts config-catalog
+/** Office skill resource location. */
+export interface Config {
+  /** Absolute assets directory containing the three skill folders and shared scripts; defaults to packaged assets. */
+  assetRoot?: string
+}
+```
+
+来源:[`packages/skill/skill-office/src/index.ts:15`](../packages/skill/skill-office/src/index.ts)
+
 <a id="deepseek-aidsh-spill-local"></a>
 
 ## `@deepseek-ai/dsh-spill-local`

+ 2 - 2
docs/event-producer-consumer.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 docs/event-producer-consumer.md
-event-producer-consumer.md: d5696c4d0ab84c0fac81995bc9bb40de14b90fa7
-event-producer-consumer.zh.md: 05e21a08f6723326744b6a6785fc4e89c19fb942
+event-producer-consumer.md: 299566f64e7aed2e0beeee81ee1a61e664aafc9f
+event-producer-consumer.zh.md: f6613e29779f580f561b2080edf4bba9b9faa862

+ 1 - 1
docs/event-producer-consumer.md

@@ -86,7 +86,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac
 
 | Event string | Dispatchers | Listeners |
 | --- | --- | --- |
-| `internal/dispatch` | - | `agent-team`, [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission-presets`](../packages/interaction/permission-presets), [`plan-mode`](../packages/plan/plan-mode), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-log-deepseek`](../packages/session/session-log-deepseek), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`terminal-bash`](../packages/terminal/terminal-bash), `terminal-controller`, [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tool-workflow`](../packages/workflow/tool-workflow), [`tools`](../packages/core/tools), `ui-renderer`, [`user-approval`](../packages/interaction/user-approval), [`webhook`](../packages/webhook/webhook), [`workflow`](../packages/workflow/workflow) |
+| `internal/dispatch` | - | `agent-team`, [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission-presets`](../packages/interaction/permission-presets), [`plan-mode`](../packages/plan/plan-mode), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-log-deepseek`](../packages/session/session-log-deepseek), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`terminal-bash`](../packages/terminal/terminal-bash), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tool-workflow`](../packages/workflow/tool-workflow), [`tools`](../packages/core/tools), `ui-renderer`, [`user-approval`](../packages/interaction/user-approval), [`webhook`](../packages/webhook/webhook), [`workflow`](../packages/workflow/workflow) |
 | `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` |
 | `internal/service` | - | [`agent-presets`](../packages/preset/agent-presets), `gateway` |
 | `internal/status` | - | [`agent`](../packages/core/agent), `inspector`, [`web`](../packages/web/web) |

+ 1 - 1
docs/event-producer-consumer.zh.md

@@ -88,7 +88,7 @@
 
 | Event string | Dispatchers | Listeners |
 | --- | --- | --- |
-| `internal/dispatch` | - | `agent-team`, [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission-presets`](../packages/interaction/permission-presets), [`plan-mode`](../packages/plan/plan-mode), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-log-deepseek`](../packages/session/session-log-deepseek), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`terminal-bash`](../packages/terminal/terminal-bash), `terminal-controller`, [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tool-workflow`](../packages/workflow/tool-workflow), [`tools`](../packages/core/tools), `ui-renderer`, [`user-approval`](../packages/interaction/user-approval), [`webhook`](../packages/webhook/webhook), [`workflow`](../packages/workflow/workflow) |
+| `internal/dispatch` | - | `agent-team`, [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission-presets`](../packages/interaction/permission-presets), [`plan-mode`](../packages/plan/plan-mode), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-log-deepseek`](../packages/session/session-log-deepseek), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`terminal-bash`](../packages/terminal/terminal-bash), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tool-workflow`](../packages/workflow/tool-workflow), [`tools`](../packages/core/tools), `ui-renderer`, [`user-approval`](../packages/interaction/user-approval), [`webhook`](../packages/webhook/webhook), [`workflow`](../packages/workflow/workflow) |
 | `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` |
 | `internal/service` | - | [`agent-presets`](../packages/preset/agent-presets), `gateway` |
 | `internal/status` | - | [`agent`](../packages/core/agent), `inspector`, [`web`](../packages/web/web) |

+ 2 - 2
docs/module-graph.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 docs/module-graph.md
-module-graph.md: 719273c14784fcf5dd98b2fddabfb7666c666139
-module-graph.zh.md: b1098cc39fdc1d44f9d7edc3555d18a2f2c26bc5
+module-graph.md: ae72394aa8ab8cf0d00d9d6cf707a17281292517
+module-graph.zh.md: 65fac7e5ccf176d65a2b600c8652820c95884788

+ 3 - 0
docs/module-graph.md

@@ -64,6 +64,7 @@ flowchart TD
     pkg_skill["skill"]
     pkg_skill_badge["skill-badge"]
     pkg_skill_filesystem["skill-filesystem"]
+    pkg_skill_office["skill-office"]
     pkg_tool_skill["tool-skill"]
   end
   subgraph group_subagent["packages/subagent"]
@@ -456,6 +457,7 @@ flowchart TD
   pkg_subprocess_local --> pkg_subprocess
   pkg_subprocess_local --> pkg_timeout
   pkg_skill_badge --> pkg_skill
+  pkg_skill_office --> pkg_skill
   pkg_spill --> pkg_brand
   pkg_spill --> pkg_llm
   pkg_spill --> pkg_session
@@ -1418,6 +1420,7 @@ flowchart TD
 | [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`subprocess`](../packages/subprocess/subprocess) |
 | [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
 | [`skill-badge`](../packages/skill/skill-badge) | `skill` | [`skill`](../packages/skill/skill) |
+| [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) |
 | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
 | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`system-prompt`](../packages/core/system-prompt) |
 | [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |

+ 3 - 0
docs/module-graph.zh.md

@@ -66,6 +66,7 @@ flowchart TD
     pkg_skill["skill"]
     pkg_skill_badge["skill-badge"]
     pkg_skill_filesystem["skill-filesystem"]
+    pkg_skill_office["skill-office"]
     pkg_tool_skill["tool-skill"]
   end
   subgraph group_subagent["packages/subagent"]
@@ -458,6 +459,7 @@ flowchart TD
   pkg_subprocess_local --> pkg_subprocess
   pkg_subprocess_local --> pkg_timeout
   pkg_skill_badge --> pkg_skill
+  pkg_skill_office --> pkg_skill
   pkg_spill --> pkg_brand
   pkg_spill --> pkg_llm
   pkg_spill --> pkg_session
@@ -1420,6 +1422,7 @@ flowchart TD
 | [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`subprocess`](../packages/subprocess/subprocess) |
 | [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
 | [`skill-badge`](../packages/skill/skill-badge) | `skill` | [`skill`](../packages/skill/skill) |
+| [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) |
 | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
 | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`system-prompt`](../packages/core/system-prompt) |
 | [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |

+ 2 - 2
docs/persistence-catalog.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 docs/persistence-catalog.md
-persistence-catalog.md: 916227711b4f11dd4ba70882f41b71696674e4ba
-persistence-catalog.zh.md: b25d877c085221ed55f334c33b34c98f5012425d
+persistence-catalog.md: 323d29c0f348f7299c32a378df34e47e2ed83cb9
+persistence-catalog.zh.md: 29f36c6c51729ead2d4d140b0a7d72ce639cdb83

+ 3 - 3
docs/persistence-catalog.md

@@ -1784,9 +1784,9 @@ SHA-256: `0ddab4577db37a3e0d9e3a91761735c8ef6f5629d526ab8ecaeeea19c097c8f8`
 | `kind` | required | `"plugin"` |
 | `plugin` | required | `string` |
 
-<a id="persistence-type-eventagentinboxspliceddatainserted0source10"></a>
+<a id="persistence-type-eventagentinboxspliceddatainserted0source11"></a>
 
-### `event:agent/inbox/spliced.data.inserted[0].source[10]`
+### `event:agent/inbox/spliced.data.inserted[0].source[11]`
 
 SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7`
 
@@ -5140,7 +5140,7 @@ One of:
 
 - [`packages/context/agent-instructions/src/state.ts#AgentInstructionSource`](#persistence-type-packagescontextagent-instructionssrcstatetsagentinstructionsource)
 - [`packages/llm/llm/src/message.ts#ToolMessageSource`](#persistence-type-packagesllmllmsrcmessagetstoolmessagesource)
-- [`event:agent/inbox/spliced.data.inserted[0].source[10]`](#persistence-type-eventagentinboxspliceddatainserted0source10)
+- [`event:agent/inbox/spliced.data.inserted[0].source[11]`](#persistence-type-eventagentinboxspliceddatainserted0source11)
 - [`event:agent/inbox/spliced.data.inserted[0].source[19]`](#persistence-type-eventagentinboxspliceddatainserted0source19)
 - [`packages/skill/tool-skill/src/index.ts#SkillCatalogSource`](#persistence-type-packagesskilltool-skillsrcindextsskillcatalogsource)
 - [`packages/skill/skill/src/index.ts#SkillInvocationSource`](#persistence-type-packagesskillskillsrcindextsskillinvocationsource)

+ 3 - 3
docs/persistence-catalog.zh.md

@@ -1786,9 +1786,9 @@ SHA-256: `0ddab4577db37a3e0d9e3a91761735c8ef6f5629d526ab8ecaeeea19c097c8f8`
 | `kind` | 必需 | `"plugin"` |
 | `plugin` | 必需 | `string` |
 
-<a id="persistence-type-eventagentinboxspliceddatainserted0source10"></a>
+<a id="persistence-type-eventagentinboxspliceddatainserted0source11"></a>
 
-### `event:agent/inbox/spliced.data.inserted[0].source[10]`
+### `event:agent/inbox/spliced.data.inserted[0].source[11]`
 
 SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7`
 
@@ -5142,7 +5142,7 @@ SHA-256: `4c965666d5b42116945bc356087cd5e1fd549e6dece560785ed60511059a8283`
 
 - [`packages/context/agent-instructions/src/state.ts#AgentInstructionSource`](#persistence-type-packagescontextagent-instructionssrcstatetsagentinstructionsource)
 - [`packages/llm/llm/src/message.ts#ToolMessageSource`](#persistence-type-packagesllmllmsrcmessagetstoolmessagesource)
-- [`event:agent/inbox/spliced.data.inserted[0].source[10]`](#persistence-type-eventagentinboxspliceddatainserted0source10)
+- [`event:agent/inbox/spliced.data.inserted[0].source[11]`](#persistence-type-eventagentinboxspliceddatainserted0source11)
 - [`event:agent/inbox/spliced.data.inserted[0].source[19]`](#persistence-type-eventagentinboxspliceddatainserted0source19)
 - [`packages/skill/tool-skill/src/index.ts#SkillCatalogSource`](#persistence-type-packagesskilltool-skillsrcindextsskillcatalogsource)
 - [`packages/skill/skill/src/index.ts#SkillInvocationSource`](#persistence-type-packagesskillskillsrcindextsskillinvocationsource)

+ 1 - 1
docs/persistence-schema.json

@@ -37978,7 +37978,7 @@
         ]
       },
       "names": [
-        "event:agent/inbox/spliced.data.inserted[0].source[10]"
+        "event:agent/inbox/spliced.data.inserted[0].source[11]"
       ],
       "sources": [
         "packages/api/session-controller/src/types.ts:381"

+ 2 - 2
docs/subsystems/skills.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 docs/subsystems/skills.md
-skills.md: 84165578d37c0d947f20435d9605bb685a5b673b
-skills.zh.md: 02fd41d5bc3a93ea4aa6de2a9996bc91bd648859
+skills.md: 7e45418b8b63955619b1d964e0cfc40ee7264632
+skills.zh.md: ead07c09fe7174d960a36173d842c652fa544c07

+ 2 - 2
docs/subsystems/skills.md

@@ -2,9 +2,9 @@
 
 English | [中文](skills.zh.md)
 
-The [skill capability family](../../packages/skill) includes the Service Definition ([dsh-skill](../../packages/skill/skill), `ctx.skills`), the local Service Provider ([dsh-skill-filesystem](../../packages/skill/skill-filesystem)), the optional packaged badge provider ([dsh-skill-badge](../../packages/skill/skill-badge)), and the Consumer ([dsh-tool-skill](../../packages/skill/tool-skill)). The registry merges provider catalogs across its host and per-scope layers; providers contribute local or packaged skills; the Consumer owns the initial and replacement catalogs plus the model-facing `skill` tool. Skills are optional instructions, not session events, so their vocabulary lives here rather than in [core.md](core.md).
+The [skill capability family](../../packages/skill) includes the Service Definition ([dsh-skill](../../packages/skill/skill), `ctx.skills`), the local Service Provider ([dsh-skill-filesystem](../../packages/skill/skill-filesystem)), optional packaged providers ([dsh-skill-badge](../../packages/skill/skill-badge) and [dsh-skill-office](../../packages/skill/skill-office)), and the Consumer ([dsh-tool-skill](../../packages/skill/tool-skill)). The registry merges provider catalogs across its host and per-scope layers; providers contribute local or packaged skills; the Consumer owns the initial and replacement catalogs plus the model-facing `skill` tool. Skills are optional instructions, not session events, so their vocabulary lives here rather than in [core.md](core.md).
 
-Source: [`packages/skill/skill/src/index.ts`](../../packages/skill/skill/src/index.ts), [`packages/skill/skill-filesystem/src/index.ts`](../../packages/skill/skill-filesystem/src/index.ts), [`packages/skill/skill-badge/src/index.ts`](../../packages/skill/skill-badge/src/index.ts), and [`packages/skill/tool-skill/src/index.ts`](../../packages/skill/tool-skill/src/index.ts).
+Source: [`packages/skill/skill/src/index.ts`](../../packages/skill/skill/src/index.ts), [`packages/skill/skill-filesystem/src/index.ts`](../../packages/skill/skill-filesystem/src/index.ts), [`packages/skill/skill-badge/src/index.ts`](../../packages/skill/skill-badge/src/index.ts), [`packages/skill/skill-office/src/index.ts`](../../packages/skill/skill-office/src/index.ts), and [`packages/skill/tool-skill/src/index.ts`](../../packages/skill/tool-skill/src/index.ts).
 
 ## Provider registry
 

+ 2 - 2
docs/subsystems/skills.zh.md

@@ -2,9 +2,9 @@
 
 [English](skills.md) | 中文
 
-[skill(技能)能力族](../../packages/skill) 包含 Service Definition([dsh-skill](../../packages/skill/skill),`ctx.skills`)、本地 Service Provider([dsh-skill-filesystem](../../packages/skill/skill-filesystem))、可选的随包徽章提供方([dsh-skill-badge](../../packages/skill/skill-badge))和 Consumer([dsh-tool-skill](../../packages/skill/tool-skill))。注册表在其宿主层与各 scope 层之间合并各提供方的目录;提供方贡献本地或随包 skill;Consumer 拥有初始目录和替换目录,以及面向模型的 `skill` 工具。skill 是可选的指令而非会话事件,因此其词汇定义在此处而非 [core.md](core.zh.md)。
+[skill(技能)能力族](../../packages/skill) 包含 Service Definition([dsh-skill](../../packages/skill/skill),`ctx.skills`)、本地 Service Provider([dsh-skill-filesystem](../../packages/skill/skill-filesystem))、可选的随包提供方([dsh-skill-badge](../../packages/skill/skill-badge) 与 [dsh-skill-office](../../packages/skill/skill-office))和 Consumer([dsh-tool-skill](../../packages/skill/tool-skill))。注册表在其宿主层与各 scope 层之间合并各提供方的目录;提供方贡献本地或随包 skill;Consumer 拥有初始目录和替换目录,以及面向模型的 `skill` 工具。skill 是可选的指令而非会话事件,因此其词汇定义在此处而非 [core.md](core.zh.md)。
 
-源码:[`packages/skill/skill/src/index.ts`](../../packages/skill/skill/src/index.ts)、[`packages/skill/skill-filesystem/src/index.ts`](../../packages/skill/skill-filesystem/src/index.ts)、[`packages/skill/skill-badge/src/index.ts`](../../packages/skill/skill-badge/src/index.ts) 与 [`packages/skill/tool-skill/src/index.ts`](../../packages/skill/tool-skill/src/index.ts)。
+源码:[`packages/skill/skill/src/index.ts`](../../packages/skill/skill/src/index.ts)、[`packages/skill/skill-filesystem/src/index.ts`](../../packages/skill/skill-filesystem/src/index.ts)、[`packages/skill/skill-badge/src/index.ts`](../../packages/skill/skill-badge/src/index.ts)、[`packages/skill/skill-office/src/index.ts`](../../packages/skill/skill-office/src/index.ts) 与 [`packages/skill/tool-skill/src/index.ts`](../../packages/skill/tool-skill/src/index.ts)。
 
 ## 提供方注册表
 

+ 2 - 2
docs/subsystems/workspace.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 docs/subsystems/workspace.md
-workspace.md: 93cce66801d123edd3a4b27e79f025c6935121a2
-workspace.zh.md: 9727c2efa1f0d1abc840f5ce9a377f57af01985a
+workspace.md: 80ea3157dbd904e168e2809ce8aa0b8641c1b2d9
+workspace.zh.md: 727c612e58cdbe54b0ba0e6292803d4543e5a32e

+ 1 - 1
docs/subsystems/workspace.md

@@ -214,7 +214,7 @@ Typed Remote control of transient Session-owned terminal processes.
 @Remote list(sessionId: SessionId): WebTerminalInfo[]
 
 /**
- * Allocate an interactive shell once for a caller-generated identity.
+ * Allocate a user shell once for a caller-generated identity, without Agent sandbox or approval restrictions.
  * @param agent - Session owner supplied by the Gateway.
  * @param request - initial dimensions and idempotency identity.
  * @param signal - allocation cancellation; committed terminals survive disconnection.

+ 1 - 1
docs/subsystems/workspace.zh.md

@@ -214,7 +214,7 @@ Typed Remote control of transient Session-owned terminal processes.
 @Remote list(sessionId: SessionId): WebTerminalInfo[]
 
 /**
- * Allocate an interactive shell once for a caller-generated identity.
+ * Allocate a user shell once for a caller-generated identity, without Agent sandbox or approval restrictions.
  * @param agent - Session owner supplied by the Gateway.
  * @param request - initial dimensions and idempotency identity.
  * @param signal - allocation cancellation; committed terminals survive disconnection.

+ 2 - 1
package.json

@@ -239,6 +239,7 @@
     "tsx": "^4.22.4",
     "typescript": "^6.0.3",
     "vite-tsconfig-paths": "^6.1.1",
-    "vitest": "^4.1.8"
+    "vitest": "^4.1.8",
+    "@deepseek-ai/dsh-skill-office": "workspace:^"
   }
 }

+ 2 - 2
packages/api/terminal-controller/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 packages/api/terminal-controller/README.md
-README.md: bc73007faa1b846e327742d2bfd5b44dcd23737d
-README.zh.md: 4dfd2181c518234df9517ae7afbeb57e4438b75c
+README.md: dd93237a94f0cc9bdbd6e6d51f9a2762898399a7
+README.zh.md: b3bda5f4040ab6f9bb9cd74a8fd32f48dbdb1362

+ 4 - 3
packages/api/terminal-controller/README.md

@@ -25,9 +25,9 @@ Open the execution environment's default shell in a Session workspace from the W
 <a id="use-this-package"></a>
 ## Use this package
 
-The Web bundle mounts this package with the subprocess provider, sandbox policy and Typert Gateway. `remote.terminal` exposes `environment`, `shells`, `list`, `create`, `retain`, `follow`, `write`, `resize`, `rename` and `close`; each operation is scoped by Session identity. Listing reads retained Host terminals directly, so viewing an offline Session neither activates an Agent nor produces a recovery error.
+The Web bundle mounts this package with the subprocess provider, sandbox policy and Typert Gateway. Sandbox policy supplies only the fallback working directory for Sessions without a cwd. `remote.terminal` exposes `environment`, `shells`, `list`, `create`, `retain`, `follow`, `write`, `resize`, `rename` and `close`; each operation is scoped by Session identity. Listing reads retained Host terminals directly, so viewing an offline Session neither activates an Agent nor produces a recovery error.
 
-Shell discovery lists the execution environment's declared default shell first. Only when the provider omits that default does resolution use `/bin/sh` on POSIX or `cmd.exe` on Windows. An optional `shell` profile overrides that choice with executable `path`, display `name` and `args` (default `[]`). The selector also probes `shellCandidates` through the execution provider and omits only confirmed lookup misses. Creation accepts a discovered `shellPath` and verifies it again; resolution or transport failure is reported without launching a different shell. Environment lookup returns the working directory and limits without resolving a shell, so an unavailable default does not prevent reattaching to an existing process. Automatic POSIX profiles start interactively, and PowerShell uses `-NoLogo`, so completion and startup configuration remain shell-owned. The Session workspace supplies the initial directory; its sandbox policy also applies to the terminal.
+Shell discovery lists the execution environment's declared default shell first. Only when the provider omits that default does resolution use `/bin/sh` on POSIX or `cmd.exe` on Windows. An optional `shell` profile overrides that choice with executable `path`, display `name` and `args` (default `[]`). The selector also probes `shellCandidates` through the execution provider and omits only confirmed lookup misses. Creation accepts a discovered `shellPath` and verifies it again; resolution or transport failure is reported without launching a different shell. Environment lookup returns the working directory and limits without resolving a shell, so an unavailable default does not prevent reattaching to an existing process. Automatic POSIX profiles start interactively, and PowerShell uses `-NoLogo`, so completion and startup configuration remain shell-owned. The Session workspace supplies the initial directory. User terminals run with the execution environment’s system-user permissions, independently of the Agent’s sandbox mode and approval policy. Operating-system and container restrictions still apply; DSH does not elevate the user. The subprocess provider retains its credential-environment scrubbing.
 
 | Configuration | Default | Meaning |
 |---|---|---|
@@ -53,7 +53,7 @@ An open tab in any connected window retains its terminal, including hidden tabs
 
 The Host uses `ctx.subprocess.spawnTerminal` with `TERM=xterm-256color`; it never launches a desktop terminal application. Streaming UTF-8 decoding preserves split characters and leading BOMs, and replaces incomplete trailing bytes at EOF. Unary control uses the Gateway, and `follow` uses its multiplexed Remote stream transport. Headless xterm and its serializer produce each opening screen after all preceding output writes, then monotone output sequences identify subsequent frames. Slow followers fail explicitly; a new attachment restores the current screen.
 
-The latest attachment owns input and resize. Detachment releases input control without killing the process. Explicit close awaits process cleanup and final output; cleanup failure retains the resource for retry. The Session remembers closed identities and rejects their delayed or repeated creation, including creation already in progress when close arrives. A new terminal uses a new identity. Pending allocations remain owned even if cancellation and cleanup both fail. Session owner disposal and controller disposal also terminate owned processes. An open or pending terminal prevents changing that Session's sandbox mode. Input or resize refused after control transfer or process exit leaves the output attachment intact and disables input; rejected input is not replayed.
+The latest attachment owns input and resize. Detachment releases input control without killing the process. Explicit close awaits process cleanup and final output; cleanup failure retains the resource for retry. The Session remembers closed identities and rejects their delayed or repeated creation, including creation already in progress when close arrives. A new terminal uses a new identity. Pending allocations remain owned even if cancellation and cleanup both fail. Session owner disposal and controller disposal also terminate owned processes. Changing the Session’s sandbox mode leaves user terminals running with the same permissions. Input or resize refused after control transfer or process exit leaves the output attachment intact and disables input; rejected input is not replayed.
 
 The Client saves each Session/content-to-terminal association before allocation under its own `dsh.terminal.binding.v1.*` localStorage key. The content identity is globally unique; layout-local tab ids only identify live view occurrences. Independent record writes and deletes preserve other windows' bindings. Restored views reuse that identity; the sidebar terminal provider restores its views before querying unrepresented Host terminals. A new view may create a process, while a recovered view reports a missing target without creating a replacement. Explicit close removes the association after saving its cleanup request. The Host supplies current process metadata and screen contents; neither is saved in the browser. The Client model acknowledges screen writes after the browser emulator processes them, serializes input and ignores stale attachment responses. Client-owned errors carry locale keys. Plugin disposal awaits active and previously detached output streams without closing Host processes.
 
@@ -70,6 +70,7 @@ Closing saves an unfinished cleanup request before releasing the tab, then await
 
 - [Subprocess](../../subprocess/subprocess/README.md)
 - [Right Sidebar](../../client/ui-sidebar-right/README.md)
+- [User-terminal permissions](../../../.agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.md)
 - [Web terminal decision](../../../.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.md)
 
 <a id="model-experience"></a>

+ 4 - 3
packages/api/terminal-controller/README.zh.md

@@ -25,9 +25,9 @@ kind: "package-reference"
 <a id="use-this-package"></a>
 ## 使用此包
 
-Web bundle 将此包与 subprocess provider、sandbox policy 和 Typert Gateway 一起挂载。`remote.terminal` 提供 `environment`、`shells`、`list`、`create`、`retain`、`follow`、`write`、`resize`、`rename` 和 `close`;每个操作均按 Session 标识限定范围。列表直接读取 Host 保留的终端,因此查看离线 Session 不会激活 Agent,也不会产生恢复错误。
+Web bundle 将此包与 subprocess provider、sandbox policy 和 Typert Gateway 一起挂载。Sandbox policy 仅为没有 cwd 的 Session 提供默认工作目录。`remote.terminal` 提供 `environment`、`shells`、`list`、`create`、`retain`、`follow`、`write`、`resize`、`rename` 和 `close`;每个操作均按 Session 标识限定范围。列表直接读取 Host 保留的终端,因此查看离线 Session 不会激活 Agent,也不会产生恢复错误。
 
-Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provider 未声明默认值时,才在 POSIX 使用 `/bin/sh`,在 Windows 使用 `cmd.exe`。可选的 `shell` profile 通过可执行路径 `path`、显示名称 `name` 和参数 `args`(默认 `[]`)覆盖这一选择。选择器还会通过执行 provider 探测 `shellCandidates`,仅省略确定未找到的候选。创建请求接受探测返回的 `shellPath` 并再次验证;解析或传输失败会直接报告,不启动其他 shell。环境查询只返回工作目录和限制,不解析 shell,因此默认 shell 不可用时仍可重新连接已有进程。POSIX 自动 profile 以交互模式启动,PowerShell 使用 `-NoLogo`,补全和启动配置仍由 shell 提供。初始目录来自 Session 工作区,终端遵循同一 sandbox policy
+Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provider 未声明默认值时,才在 POSIX 使用 `/bin/sh`,在 Windows 使用 `cmd.exe`。可选的 `shell` profile 通过可执行路径 `path`、显示名称 `name` 和参数 `args`(默认 `[]`)覆盖这一选择。选择器还会通过执行 provider 探测 `shellCandidates`,仅省略确定未找到的候选。创建请求接受探测返回的 `shellPath` 并再次验证;解析或传输失败会直接报告,不启动其他 shell。环境查询只返回工作目录和限制,不解析 shell,因此默认 shell 不可用时仍可重新连接已有进程。POSIX 自动 profile 以交互模式启动,PowerShell 使用 `-NoLogo`,补全和启动配置仍由 shell 提供。初始目录来自 Session 工作区。用户终端使用执行环境中系统用户的权限,独立于 Agent 的沙箱模式和审批策略。操作系统和容器的限制仍然生效;DSH 不提升用户权限。Subprocess provider 继续清除环境中的凭据变量
 
 | 配置 | 默认值 | 含义 |
 |---|---|---|
@@ -53,7 +53,7 @@ Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provide
 
 Host 通过 `ctx.subprocess.spawnTerminal` 创建 `TERM=xterm-256color` 的终端,不启动桌面终端应用。流式 UTF-8 解码保留跨块字符和开头的 BOM,并在 EOF 将不完整的尾部字节替换为替代字符。控制请求走 Gateway,`follow` 使用其复用的 Remote stream。Headless xterm 和序列化 addon 在此前输出写入后生成初始屏幕,后续增量携带单调序号。过慢的订阅者明确失败;重新连接恢复当前屏幕。
 
-最新连接持有输入和尺寸控制权。断开连接只释放输入权,不结束进程。显式关闭等待进程清理和最后输出;清理失败时保留资源以便重试。Session 记住已关闭的标识并拒绝迟到或重复的创建请求,包括关闭到达时仍在进行的创建。新终端使用新标识。取消创建且清理失败时,已分配的进程仍有所有者。Session owner 和 controller 卸载也会终止所拥有的进程。存在终端或创建请求时不能改变该 Session 的 sandbox mode。 控制权转移或进程退出后被拒绝的输入和尺寸请求保留输出连接并禁用输入,不重发被拒绝的输入。
+最新连接持有输入和尺寸控制权。断开连接只释放输入权,不结束进程。显式关闭等待进程清理和最后输出;清理失败时保留资源以便重试。Session 记住已关闭的标识并拒绝迟到或重复的创建请求,包括关闭到达时仍在进行的创建。新终端使用新标识。取消创建且清理失败时,已分配的进程仍有所有者。Session owner 和 controller 卸载也会终止所拥有的进程。改变 Session 的沙箱模式时,用户终端继续以原有权限运行。控制权转移或进程退出后被拒绝的输入和尺寸请求保留输出连接并禁用输入,不重发被拒绝的输入。
 
 Client 在分配前将每条 Session/内容与终端身份的关联保存到独立的 localStorage key `dsh.terminal.binding.v1.*`。内容身份全局唯一;布局内的 tab id 只标识活动视图 occurrence。逐条记录的写入和删除会保留其他窗口的关联。恢复视图复用该身份;侧栏 terminal provider 先恢复自己的视图,再查询尚无视图的 Host 终端。新视图可以创建进程,恢复视图在目标缺失时显示错误,不创建替代进程。显式关闭先保存清理请求,再删除关联。当前进程元数据和屏幕内容由 Host 提供,不保存在浏览器中。Client 模型在浏览器完成屏幕解析后确认帧,按序发送输入,并忽略旧连接迟到的响应。Client 自产错误携带本地化键。插件卸载等待活跃及先前断开的输出流结束,不关闭 Host 进程。
 
@@ -70,6 +70,7 @@ Client 在分配前将每条 Session/内容与终端身份的关联保存到独
 
 - [Subprocess](../../subprocess/subprocess/README.zh.md)
 - [Right Sidebar](../../client/ui-sidebar-right/README.zh.md)
+- [用户终端权限](../../../.agents/notes/implemented/architecture/2026-09-16-user-terminal-permissions.zh.md)
 - [Web terminal decision](../../../.agents/notes/implemented/feature/2026-09-09-web-sidebar-terminal.zh.md)
 
 <a id="model-experience"></a>

+ 7 - 25
packages/api/terminal-controller/src/index.ts

@@ -1,11 +1,9 @@
-/** Session-scoped browser terminals over the composed subprocess and sandbox providers. */
+/** Session-owned user terminals with the execution environment's system-user permissions. */
 import type { Context } from '@deepseek-ai/cordis'
 import z from '@deepseek-ai/schemastery'
 import type { Agent } from '@deepseek-ai/dsh-agent'
-import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
+import type { SessionId } from '@deepseek-ai/dsh-session'
 import type {} from '@deepseek-ai/dsh-sandbox-policy'
-import type {} from '@deepseek-ai/dsh-sandbox'
-import type {} from '@deepseek-ai/dsh-session-projection'
 import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
 import { discoverShells, resolveShell } from './shells.ts'
 import { BrowserTerminal } from './terminal.ts'
@@ -75,7 +73,7 @@ interface OwnedSession {
 
 /** Typed Remote control of transient Session-owned terminal processes. */
 export class TerminalController extends TypertRemoteService {
-  static inject = ['subprocess', 'sandboxPolicy', 'sessionProjections', 'typert']
+  static inject = ['subprocess', 'sandboxPolicy', 'typert']
   static Config: z<Config> = z.object({
     shell: z.union([z.object({
       path: z.string().required(), name: z.string().required(), args: z.array(z.string()).default([]),
@@ -102,15 +100,6 @@ export class TerminalController extends TypertRemoteService {
    */
   constructor(ctx: Context, private readonly config: Config) {
     super(ctx, 'terminalController', { namespace: 'terminal' })
-    ctx.on('internal/dispatch', (_mode, eventName, args) => {
-      if (eventName !== 'session/event') return
-      const [session, event] = args as [Session, SessionEvent]
-      if (event.type !== 'sandbox/mode') return
-      const owner = this.owners.get(session.id)
-      if (owner === undefined || owner.terminals.size + owner.pending.size + owner.allocations.size === 0) return
-      const current = ctx.sessionProjections.stateOf(session, 'sandboxMode') ?? ctx.sandboxPolicy.defaultMode
-      if (event.data.mode !== current) throw new Error('Close browser terminals before changing the Session sandbox mode')
-    }, { global: true })
     ctx.effect(() => async () => {
       this.lifetime.abort(new Error('Terminal controller disposed'))
       const results = await Promise.allSettled([...this.owners].map(([id, owner]) => this.disposeOwner(id, owner)))
@@ -129,7 +118,7 @@ export class TerminalController extends TypertRemoteService {
   environment(agent: Agent, signal: AbortSignal): TerminalEnvironment {
     signal.throwIfAborted()
     const { sandboxPolicy } = this.execution(agent)
-    return { cwd: sandboxPolicy.resolve({ session: agent.session }).workspaceRoot,
+    return { cwd: agent.session.header.cwd ?? sandboxPolicy.workspaceRoot,
       maxInputBytes: this.config.maxInputBytes, maxCols: this.config.maxCols,
       maxRows: this.config.maxRows, scrollback: this.config.scrollback }
   }
@@ -159,7 +148,7 @@ export class TerminalController extends TypertRemoteService {
   }
 
   /**
-   * Allocate an interactive shell once for a caller-generated identity.
+   * Allocate a user shell once for a caller-generated identity, without Agent sandbox or approval restrictions.
    * @param agent - Session owner supplied by the Gateway.
    * @param request - initial dimensions and idempotency identity.
    * @param signal - allocation cancellation; committed terminals survive disconnection.
@@ -349,20 +338,13 @@ export class TerminalController extends TypertRemoteService {
 
   private async spawn(agent: Agent, owner: OwnedSession, request: TerminalCreateRequest, signal: AbortSignal): Promise<BrowserTerminal> {
     const environment = this.environment(agent, signal)
-    const { subprocess, sandboxPolicy } = this.execution(agent)
+    const { subprocess } = this.execution(agent)
     const shell = request.shellPath === undefined
       ? await resolveShell(subprocess, this.config.shell, signal)
       : (await this.shells(agent, signal)).find(candidate => candidate.path === request.shellPath)
     if (shell === undefined) throw new Error('Selected shell is not available in this execution environment')
-    const policy = sandboxPolicy.resolve({ session: agent.session })
-    let argv = [shell.path, ...shell.args]
-    if (policy.mode !== 'danger-full-access') {
-      const sandbox = agent.ctx.get('sandbox')
-      if (sandbox === undefined) throw new Error('The Session sandbox mode requires an execution sandbox provider')
-      argv = (await sandbox.confine(argv, { ...policy, mode: policy.mode }, signal)).argv
-    }
     const handle = await subprocess.spawnTerminal({
-      argv, cwd: environment.cwd, cols: request.cols, rows: request.rows,
+      argv: [shell.path, ...shell.args], cwd: environment.cwd, cols: request.cols, rows: request.rows,
       terminalType: 'xterm-256color', env: { DSH_SESSION_ID: agent.id },
       shellActivity: true,
       graceMs: this.config.disposeGraceMs, signal,

+ 24 - 29
packages/api/terminal-controller/tests/controller.spec.ts

@@ -1,4 +1,4 @@
-/** Session identity, allocation races, confinement and real PTY behavior. */
+/** Session identity, allocation races, human execution permissions and real PTY behavior. */
 import { mkdtemp, rm } from 'node:fs/promises'
 import { tmpdir } from 'node:os'
 import { join } from 'node:path'
@@ -21,18 +21,16 @@ const id = 'test-terminal' as WebTerminalId
 const request = { id, cols: 80, rows: 24 }
 const signal = (): AbortSignal => new AbortController().signal
 
-function owner(ctx: Context, id = 'session'): Agent {
-  return { id: id as SessionId, ctx, session: { id: id as SessionId } } as unknown as Agent
+function owner(ctx: Context, id = 'session', cwd?: string): Agent {
+  return { id: id as SessionId, ctx, session: { id: id as SessionId, header: { cwd } } } as unknown as Agent
 }
 
 function fixture(overrides: Partial<Config> = {}) {
   const ctx = new Context()
   roots.push(ctx)
   const effects = vi.spyOn(ctx.fiber, 'effect')
-  const sandboxPolicy = { defaultMode: 'danger-full-access', resolve: vi.fn((): SandboxExecutionPolicy => ({ mode: 'danger-full-access', workspaceRoot: '/workspace' })) }
-  const projections = { stateOf: vi.fn((): SandboxMode | null => null) }
+  const sandboxPolicy = { defaultMode: 'danger-full-access', workspaceRoot: '/workspace', resolve: vi.fn((): SandboxExecutionPolicy => ({ mode: 'danger-full-access', workspaceRoot: '/workspace' })) }
   ctx.provide('sandboxPolicy', sandboxPolicy as never)
-  ctx.provide('sessionProjections', projections as never)
   const output = new PassThrough()
   const done = Promise.withResolvers<{ exitCode: number; signal: null }>()
   const handle = {
@@ -50,7 +48,7 @@ function fixture(overrides: Partial<Config> = {}) {
     if (result?.type !== 'return' || typeof result.value !== 'function') throw new Error(`Missing effect: ${label}`)
     return result.value()
   }
-  return { ctx, agent: owner(ctx), controller, subprocess, handle, sandboxPolicy, projections, disposeEffect }
+  return { ctx, agent: owner(ctx), controller, subprocess, handle, sandboxPolicy, disposeEffect }
 }
 
 describe('TerminalController', () => {
@@ -282,22 +280,23 @@ describe('TerminalController', () => {
     expect(controller.list(agent.id)).toEqual([])
   })
 
-  it('uses the Session sandbox policy to confine its selected shell', async () => {
+  it.each(['read-only', 'workspace-write', 'danger-full-access'] as const)('starts a user shell without confinement under %s Agent permissions', async (mode) => {
     const { controller, agent, ctx, sandboxPolicy, subprocess } = fixture()
-    const policy: SandboxExecutionPolicy = { mode: 'workspace-write', workspaceRoot: '/workspace', sessionId: agent.id }
-    sandboxPolicy.resolve.mockReturnValue(policy)
+    sandboxPolicy.resolve.mockReturnValue({ mode, workspaceRoot: '/workspace', sessionId: agent.id })
     const confine = vi.fn((argv: readonly string[]) => ({ argv: ['sandbox-runner', ...argv] }))
     ctx.provide('sandbox', { confine } as never)
     await controller.create(agent, request, signal())
-    expect(confine).toHaveBeenCalledWith(['/bin/bash', '--noprofile', '--norc', '-i'], policy, expect.any(AbortSignal))
-    expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ argv: ['sandbox-runner', '/bin/bash', '--noprofile', '--norc', '-i'], env: { DSH_SESSION_ID: agent.id }, graceMs: 100 }))
+    expect(confine).not.toHaveBeenCalled()
+    expect(sandboxPolicy.resolve).not.toHaveBeenCalled()
+    expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ argv: ['/bin/bash', '--noprofile', '--norc', '-i'], env: { DSH_SESSION_ID: agent.id }, graceMs: 100 }))
   })
 
-  it('rejects a confined Session without a sandbox provider before spawning', async () => {
-    const { controller, agent, sandboxPolicy, subprocess } = fixture()
-    sandboxPolicy.resolve.mockReturnValue({ mode: 'read-only', workspaceRoot: '/workspace' })
-    await expect(controller.create(agent, request, signal())).rejects.toThrow('requires an execution sandbox provider')
-    expect(subprocess.spawnTerminal).not.toHaveBeenCalled()
+  it('uses the Session working directory without requiring a sandbox provider', async () => {
+    const { controller, ctx, subprocess } = fixture()
+    const agent = owner(ctx, 'workspace-session', '/another-workspace')
+    expect(controller.environment(agent, signal())).toMatchObject({ cwd: '/another-workspace' })
+    await controller.create(agent, request, signal())
+    expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/another-workspace' }))
   })
 
   it.each(['subprocess', 'sandboxPolicy'] as const)('fails clearly when the Session lacks %s', (missing) => {
@@ -309,20 +308,16 @@ describe('TerminalController', () => {
     expect(() => controller.environment(owner(isolated), signal())).toThrow('requires subprocess and sandbox policy providers')
   })
 
-  it('blocks sandbox-mode changes only while that Session retains a terminal', async () => {
-    const { controller, agent, ctx, projections } = fixture()
+  it('allows Agent sandbox-mode changes while retaining the same user terminal', async () => {
+    const { controller, agent, ctx, subprocess, handle } = fixture()
     const mode = (mode: SandboxMode): void => { ctx.emit('session/event', agent.session, { type: 'sandbox/mode', data: { mode } } as SessionEvent) }
-    ctx.emit('session/disposed', agent.session)
-    ctx.emit('session/event', agent.session, { type: 'turn/start', data: { turn: 1 } } as SessionEvent)
-    expect(() => { mode('workspace-write') }).not.toThrow()
     await controller.create(agent, request, signal())
-    expect(() => { mode('danger-full-access') }).not.toThrow()
-    expect(() => { mode('workspace-write') }).toThrow('Close browser terminals')
-    projections.stateOf.mockReturnValue('read-only')
-    expect(() => { mode('read-only') }).not.toThrow()
-    expect(() => { mode('danger-full-access') }).toThrow('Close browser terminals')
-    await controller.close(agent, id)
-    expect(() => { mode('workspace-write') }).not.toThrow()
+    for (const value of ['read-only', 'workspace-write', 'danger-full-access'] as const) {
+      expect(() => { mode(value) }).not.toThrow()
+      expect(controller.list(agent.id)).toMatchObject([{ id, state: 'running' }])
+    }
+    expect(subprocess.spawnTerminal).toHaveBeenCalledOnce()
+    expect(handle.terminate).not.toHaveBeenCalled()
   })
 
   it('terminates committed processes when the Session effect ends', async () => {

+ 2 - 2
packages/client/ui-sidebar-terminal/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 packages/client/ui-sidebar-terminal/README.md
-README.md: 37c3706996a7083c14f10e1b29603698f6dc8689
-README.zh.md: 45563a1d717ff51ffe371a6a894e4376466c6d7d
+README.md: a874eb3ce4fed4e66893bf309a36330c355ce843
+README.zh.md: f54c86f24158a1dcf68e82189c74e700cd8e94c5

+ 1 - 1
packages/client/ui-sidebar-terminal/README.md

@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
 
 ## Summary
 
-Choose an installed shell from the right sidebar's Start page to run commands in the Session workspace. Rename terminals in their tabs and recover retained processes after reloading the page. Collapse the sidebar to keep commands running; close a terminal tab to request process termination. Tab completion follows the shell configuration.
+Choose an installed shell from the right sidebar's Start page to run commands in the Session workspace. Rename terminals in their tabs and recover retained processes after reloading the page. Collapse the sidebar to keep commands running; close a terminal tab to request process termination. Tab completion follows the shell configuration. Commands use the execution environment’s system-user permissions independently of Agent permissions; see [user-terminal execution](../../api/terminal-controller/README.md#use-this-package).
 
 ## Table of Contents
 

+ 1 - 1
packages/client/ui-sidebar-terminal/README.zh.md

@@ -9,7 +9,7 @@ kind: "package-reference"
 
 ## 概述
 
-从右侧栏开始页选择已安装的 shell,在会话工作区运行命令。在标签页上重命名终端,并在刷新页面后恢复保留的进程。折叠侧栏让命令继续运行,关闭终端标签页则请求结束进程。Tab 补全使用 shell 的配置。
+从右侧栏开始页选择已安装的 shell,在会话工作区运行命令。在标签页上重命名终端,并在刷新页面后恢复保留的进程。折叠侧栏让命令继续运行,关闭终端标签页则请求结束进程。Tab 补全使用 shell 的配置。命令使用执行环境中系统用户的权限,独立于 Agent 权限;详见[用户终端执行](../../api/terminal-controller/README.zh.md#use-this-package)。
 
 ## 目录
 

+ 1 - 1
packages/extensions/tool-cordis/src/api-catalog.ts

@@ -2667,7 +2667,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
       },
       {
         signature: '@Remote async create(agent: Agent, request: TerminalCreateRequest, signal: AbortSignal): Promise<WebTerminalInfo>',
-        description: 'Allocate an interactive shell once for a caller-generated identity.',
+        description: 'Allocate a user shell once for a caller-generated identity, without Agent sandbox or approval restrictions.',
         parameters: [{ name: 'agent', description: 'Session owner supplied by the Gateway.' }, { name: 'request', description: 'initial dimensions and idempotency identity.' }, { name: 'signal', description: 'allocation cancellation; committed terminals survive disconnection.' }],
         returns: 'the existing or newly committed terminal.',
       },

+ 2 - 2
packages/llm/llm-deepseek/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 packages/llm/llm-deepseek/README.md
-README.md: f332d59b0fe63e5129e5205fbba1ab1901b34d7f
-README.zh.md: 26ce84e2497c637cbfe42bbbaf72fc07f27c3e82
+README.md: 18f1b3de48d554dbc2225cfcadf4900f8bb17b09
+README.zh.md: 38d288d233a84c3bbf8170d560ea42d372fab3fc

+ 1 - 1
packages/llm/llm-deepseek/README.md

@@ -171,7 +171,7 @@ Read these pages when the package-level contract is not enough. They move from t
 
 #### What the model sees
 
-The selected DeepSeek model receives the harness system prompt, message history, tool schemas, stop sequences, and call config (`maxTokens`, `reasoningEffort`, `temperature`) without adapter-authored prompt prose. Provider-specific request-extension fields remain outside model input. The vision model normally receives retained user and tool-result images as Files API references beside attachment handles and request-preview dimensions. It also receives a normalized-object path when the current execution filesystem maps the attachment provider's host object; the descriptor marks this copy read-only and warns that normalization may have resized or re-encoded the upload. A Files resolution failure sends all retained images as inline base64 instead, and an over-budget older image keeps the access resolved for that request in its placeholder. Reasoning content from a prior assistant turn is passed back verbatim, whether or not that turn called a tool.
+The selected DeepSeek model receives the harness system prompt, message history, tool schemas, stop sequences, and call config (`maxTokens`, `reasoningEffort`, `temperature`) without adapter-authored prompt prose. Provider-specific request-extension fields remain outside model input. The vision model normally receives retained user and tool-result images as Files API references beside attachment handles and request-preview dimensions. It also receives a normalized-object path when the current execution filesystem maps the attachment provider's host object; the descriptor marks this copy read-only and warns that normalization may have resized or re-encoded the upload. A Files resolution failure sends all retained images as inline base64 instead, and an over-budget older image keeps the access resolved for that request in its placeholder. Reasoning content from a prior assistant turn is passed back verbatim, whether or not that turn called a tool. Messages sends `{}` for historical tool arguments that are malformed JSON or are not objects. Call ids, tool names, and results remain intact; the original arguments stay in the Session log. This silent fallback also applies after switching from Chat Completions. Newly generated Messages tool arguments still require valid JSON objects.
 
 #### Token effect
 

+ 1 - 1
packages/llm/llm-deepseek/README.zh.md

@@ -171,7 +171,7 @@ Files 模式通过 `maxRequestFilesBytes` 与 `maxImagesPerRequest` 限制保留
 
 #### 模型看到什么
 
-所选 DeepSeek 模型会收到 harness 系统提示词、消息历史、工具 schema、停止序列与调用配置(`maxTokens`、`reasoningEffort`、`temperature`),不包含适配器撰写的提示词散文。提供方专用请求扩展字段留在模型输入之外。视觉模型通常接收 Files API 引用形式的用户与工具结果图片,其旁带附件句柄和请求预览尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,它还会收到规范化对象路径;描述符会把该副本标记为只读,并警告规范化可能缩放或重新编码上传内容。Files 解析失败时,全部保留图片改用内联 base64;超出预算的较旧图片则在占位文本中保留当前请求已解析的访问方式。此前 assistant 轮次的推理内容会原样传回,无论该轮次是否调用了工具。
+所选 DeepSeek 模型会收到 harness 系统提示词、消息历史、工具 schema、停止序列与调用配置(`maxTokens`、`reasoningEffort`、`temperature`),不包含适配器撰写的提示词散文。提供方专用请求扩展字段留在模型输入之外。视觉模型通常接收 Files API 引用形式的用户与工具结果图片,其旁带附件句柄和请求预览尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,它还会收到规范化对象路径;描述符会把该副本标记为只读,并警告规范化可能缩放或重新编码上传内容。Files 解析失败时,全部保留图片改用内联 base64;超出预算的较旧图片则在占位文本中保留当前请求已解析的访问方式。此前 assistant 轮次的推理内容会原样传回,无论该轮次是否调用了工具。 对于非法 JSON 或非对象的历史工具参数,Messages 发送 `{}`。调用 ID、工具名和结果保持不变,原始参数仍保留在 Session 日志中。从 Chat Completions 切换后也适用此静默兜底。新生成的 Messages 工具参数仍须是有效 JSON 对象。
 
 #### Token 影响
 

+ 6 - 4
packages/llm/llm-deepseek/src/protocols/messages/serialize.ts

@@ -5,20 +5,22 @@ import type { ContentBlock, GenerateOptions, ImageAttachmentAccessResolver, Mess
 import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment'
 import type { DeepSeekConnectionOptions as Connection } from '../../common/types.ts'
 import type { DeepSeekFileId } from '../../common/file-id.ts'
-import { object, readReplay } from './replay.ts'
+import { readReplay } from './replay.ts'
 import type { WireBlock, WireInput, WireMessage, WireRequest } from './types.ts'
 
 function unsupported(type: string): never {
   throw new LlmError(`DeepSeek Messages cannot represent ${type}`, 'UNSUPPORTED_CONTENT')
 }
 
-/** Parse tool input only when constructing an outgoing native tool_use block. */
+/** Historical arguments that Messages cannot represent use empty input; durable content stays unchanged. */
 function toolInput(raw: string): Record<string, unknown> {
   let value: unknown
   try { value = JSON.parse(raw) } catch (_invalidToolHistoryJson) {
-    throw new LlmError('DeepSeek Messages historical tool input is invalid JSON', 'INVALID_REQUEST')
+    return {}
   }
-  return object(value, 'INVALID_REQUEST')
+  return typeof value === 'object' && value !== null && !Array.isArray(value)
+    ? value as Record<string, unknown>
+    : {}
 }
 
 function assistant(message: Message, model: string, onReplayDegrade?: (reason: string) => void): WireBlock[] {

+ 20 - 1
packages/llm/llm-deepseek/tests/messages/adapter.e2e.ts

@@ -12,7 +12,7 @@ import Loader from '@deepseek-ai/cordis-plugin-loader'
 import AgentRegistry from '@deepseek-ai/dsh-agent'
 import LocalAttachments from '@deepseek-ai/dsh-attachment-local'
 import DeepSeekLlmApiExtensionRegistry from '@deepseek-ai/dsh-deepseek-llm-api-extensions'
-import LlmRuntime, { BlockAssembler, createSystemMessage, createToolResultMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
+import LlmRuntime, { BlockAssembler, createAssistantMessage, createSystemMessage, createToolResultMessage, ReasoningEffortId, ToolCallId } from '@deepseek-ai/dsh-llm'
 import type { Message } from '@deepseek-ai/dsh-llm'
 import * as PluginPackageInventoryDeepSeek from '@deepseek-ai/dsh-plugin-package-inventory-deepseek'
 import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
@@ -225,6 +225,25 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('DeepSeek Messages real API', ()
     expect(third.assembler.finish.kind).toBe('stop')
   })
 
+  it('continues persisted foreign history containing malformed tool arguments', async () => {
+    const ctx = await boot()
+    const callId = ToolCallId('historical_lookup')
+    const history = [
+      user('Look up the secret value.'),
+      createAssistantMessage({ source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, content: [
+        { type: 'tool-call', id: callId, name: 'lookup_value', arguments: '{"key":"the "secret""}' },
+      ] }),
+      createToolResultMessage({ callId, content: [{ type: 'text', text: 'Invalid arguments: expected an object' }], isError: true }),
+      user('Do not retry the lookup. Reply with exactly HISTORY_RECOVERED_731.'),
+    ]
+    const saved = JSON.stringify(history)
+    const restored = JSON.parse(saved) as Message[]
+    const response = await assemble(ctx.llm.stream(options({ messages: restored, tools: [tool], reasoningEffort: ReasoningEffortId('off') })))
+    expect(response.assembler.finish.kind).toBe('stop')
+    expect(response.message.content.filter(block => block.type === 'text').map(block => block.text).join('')).toContain('HISTORY_RECOVERED_731')
+    expect(JSON.stringify(restored)).toBe(saved)
+  })
+
   it('cancels an active stream without committing a successful response', async () => {
     const ctx = await boot()
     const controller = new AbortController()

+ 15 - 0
packages/llm/llm-deepseek/tests/messages/fixtures/history.ts

@@ -0,0 +1,15 @@
+/** Exercise Messages request conversion with recorded responses from another protocol. */
+import type { Context } from '@deepseek-ai/cordis'
+import { resolveAdapterOptions } from '../../../src/config.ts'
+import { serialize } from '../../../src/protocols/messages/serialize.ts'
+
+export const name = 'messages-history-snapshot'
+export const inject = ['llm']
+
+export function apply(ctx: Context): void {
+  const connection = resolveAdapterOptions({})
+  ctx.on('llm/stream', (options, next) => {
+    serialize(options, connection, options.messages, new Map(), () => undefined)
+    return next()
+  })
+}

+ 22 - 5
packages/llm/llm-deepseek/tests/messages/serialize.spec.ts

@@ -149,8 +149,20 @@ describe('Messages request conversion', () => {
     expect(() => body(messages)).toThrow(/tool/)
   })
 
-  it.each(['{', '[]'])('rejects invalid historical tool input %s', (arguments_) => {
-    expect(() => body([assistant([{ type: 'tool-call', id: ToolCallId('a'), name: 'read', arguments: arguments_ }]), result()])).toThrow()
+  it.each(['{', '', '[]', 'null', '42', 'true', '"text"', '{"description":"最快,但"某个说法"没有证据。"}'])('uses empty input for malformed or non-object historical tool arguments %s', (arguments_) => {
+    const message = assistant([{ type: 'tool-call', id: ToolCallId('a'), name: 'read', arguments: arguments_ }])
+    const history = [user(), message, createToolResultMessage({ callId: ToolCallId('a'), content: [{ type: 'text', text: 'Invalid arguments' }], isError: true }), user('Continue')]
+    const saved = JSON.stringify(history)
+    const restored = JSON.parse(saved) as Message[]
+    expect(body(restored).messages).toEqual([
+      { role: 'user', content: [{ type: 'text', text: 'hello' }] },
+      { role: 'assistant', content: [{ type: 'tool_use', id: 'a', name: 'read', input: {} }] },
+      { role: 'user', content: [
+        { type: 'tool_result', tool_use_id: 'a', content: [{ type: 'text', text: 'Invalid arguments' }], is_error: true },
+        { type: 'text', text: 'Continue' },
+      ] },
+    ])
+    expect(JSON.stringify(restored)).toBe(saved)
   })
 
   it('preserves own signed thinking, omits absent signatures and validates durable metadata', () => {
@@ -214,11 +226,16 @@ describe('Messages request conversion', () => {
     expect(() => readReplay(damaged, MODEL, () => { throw failure })).toThrow(failure)
   })
 
-  it('still rejects invalid tool JSON after discarding unusable replay metadata', () => {
+  it.each([1, 2])('uses empty historical tool input with replay version %s', (version) => {
     const message = createAssistantMessage({ content: [{ type: 'tool-call', id: ToolCallId('a'), name: 'read', arguments: '{' }], source: {
-      provider: 'deepseek-official', model: MODEL, replayState: { response: {}, blocks: [] },
+      provider: 'deepseek-official', model: MODEL, replayState: { response: { kind: 'deepseek-messages', version, model: MODEL }, blocks: [{ type: 'tool-call' }] },
     } })
-    expect(() => body([message, result()])).toThrow(/historical tool input is invalid JSON/)
+    const saved = JSON.stringify(message)
+    const onDegrade = vi.fn()
+    const request = serialize(options(), connection, [message, result()], new Map(), () => undefined, onDegrade)
+    expect(request.messages[0]?.content).toEqual([{ type: 'tool_use', id: 'a', name: 'read', input: {} }])
+    expect(onDegrade).toHaveBeenCalledTimes(version === 1 ? 0 : 1)
+    expect(JSON.stringify(message)).toBe(saved)
   })
 })
 

+ 2 - 2
packages/skill/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 packages/skill/README.md
-README.md: 963b8195b2240f22cb2df16ffccbb91365e62566
-README.zh.md: f11bd1be5ae005f23592ec479ae635ca28eebeeb
+README.md: 9546dfbfb2081480a1af8078d65481d0fc080ae3
+README.zh.md: eb1231b6fc7e110afdcc22fb25db3dd55b830092

+ 2 - 1
packages/skill/README.md

@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
 
 ## Summary
 
-The skill family lets agents and users discover and load reusable task instructions only when needed. Use `skill/` to combine catalogs and expose one instruction set per name; choose `skill-filesystem` for project, custom, or user-directory discovery, and `skill-badge` for the optional official badge. Add `tool-skill` when models should receive a sorted, durable session catalog, load full instructions through the `skill` tool, or accept direct `/name` invocation. Different sources produce the same model-visible format, and model access requires at least one source.
+The skill family lets agents and users discover and load reusable task instructions only when needed. Use `skill/` to combine catalogs and expose one instruction set per name; choose `skill-filesystem` for project, custom, or user-directory discovery, `skill-badge` for the optional official badge, and `skill-office` for Word, PowerPoint, and Excel workflows. Add `tool-skill` when models should receive a sorted, durable session catalog, load full instructions through the `skill` tool, or accept direct `/name` invocation. Different sources produce the same model-visible format, and model access requires at least one source.
 
 ## Table of Contents
 
@@ -27,6 +27,7 @@ The skill family lets agents and users discover and load reusable task instructi
 | [`skill/`](skill/README.md) | Registry that merges skill catalogs from any provider and resolves the winning skill for a name | `ctx.skills` |
 | [`skill-filesystem/`](skill-filesystem/README.md) | Discovers skills from project, custom, and user directories and watches them for changes | registers on `ctx.skills` |
 | [`skill-badge/`](skill-badge/README.md) | Bundles the official "powered by dsh" badge skill, disabled by default | registers on `ctx.skills` |
+| [`skill-office/`](skill-office/README.md) | Bundles Word, PowerPoint, and Excel workflows with structural file checks | registers on `ctx.skills` |
 | [`tool-skill/`](tool-skill/README.md) | Publishes the session skill catalog and the model-facing `skill` loader tool | registers on `ctx.tools` |
 
 -----

+ 2 - 1
packages/skill/README.zh.md

@@ -9,7 +9,7 @@ kind: "package-group"
 
 ## 概述
 
-skill 家族让 agent 和用户仅在需要时发现并加载可复用的任务指令。使用 `skill/` 合并目录并为每个名称提供一组指令;需要从项目、自定义或用户目录发现 skill 时选择 `skill-filesystem`,需要可选的官方徽章时选择 `skill-badge`。需要让模型获得排序且持久的会话目录、通过 `skill` 工具加载完整指令,或接受 `/name` 直接调用时,请添加 `tool-skill`。不同来源生成相同的模型可见格式,启用模型访问前必须配置至少一个来源。
+skill 家族让 agent 和用户仅在需要时发现并加载可复用的任务指令。使用 `skill/` 合并目录并为每个名称提供一组指令;需要从项目、自定义或用户目录发现 skill 时选择 `skill-filesystem`,需要可选的官方徽章时选择 `skill-badge`,需要 Word、PowerPoint 和 Excel 工作流时选择 `skill-office`。需要让模型获得排序且持久的会话目录、通过 `skill` 工具加载完整指令,或接受 `/name` 直接调用时,请添加 `tool-skill`。不同来源生成相同的模型可见格式,启用模型访问前必须配置至少一个来源。
 
 ## 目录
 
@@ -27,6 +27,7 @@ skill 家族让 agent 和用户仅在需要时发现并加载可复用的任务
 | [`skill/`](skill/README.zh.md) | 合并任意提供方的 skill 目录、并按名称解析出胜出 skill 的注册表 | `ctx.skills` |
 | [`skill-filesystem/`](skill-filesystem/README.zh.md) | 从项目、自定义与用户目录发现 skill,并监视其变更 | 注册到 `ctx.skills` |
 | [`skill-badge/`](skill-badge/README.zh.md) | 随包附带官方「powered by dsh」徽章 skill,默认禁用 | 注册到 `ctx.skills` |
+| [`skill-office/`](skill-office/README.zh.md) | 随包提供 Word、PowerPoint 和 Excel 工作流及文件结构检查 | 注册到 `ctx.skills` |
 | [`tool-skill/`](tool-skill/README.zh.md) | 发布会话 skill 目录与面向模型的 `skill` 加载工具 | 注册到 `ctx.tools` |
 
 -----

+ 6 - 0
packages/skill/skill-office/README.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 packages/skill/skill-office/README.md
+README.md: 41150b81daa4a38fcf5905f4d1e07d2745a7616f
+README.zh.md: 8b9342e137e526060fd072f0bfece904d2b7c1dc

+ 100 - 0
packages/skill/skill-office/README.md

@@ -0,0 +1,100 @@
+---
+description: "Bundled Word, PowerPoint, and Excel instructions for deployments providing Office file authoring and structural checks."
+kind: "package-reference"
+---
+
+# @deepseek-ai/dsh-skill-office
+
+English | [中文](README.zh.md)
+
+## Summary
+
+Agents can load Word, PowerPoint, and Excel workflows that use the bundled Python environment by default and respect explicit user or AGENTS.md environment choices. The skills cover creation, focused edits, structural checks, and file delivery. Visual inspection is conditional on image-capable models and an available rendering tool; ordinary document delivery does not require installing a renderer.
+
+## Table of Contents
+
+- [Use this package](#use-this-package)
+- [Understand the implementation](#understand-the-implementation)
+- [Further Exploration](#further-exploration)
+- [Model Experience](#model-experience)
+- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
+- [Dev Note](#dev-note)
+
+-----
+
+<a id="use-this-package"></a>
+## Use this package
+
+Mount this provider beside the skill registry and `dsh-tool-skill` to expose `office-docx`, `office-pptx`, and `office-xlsx` in the session catalog. The provider supplies instructions and scripts; the deployment supplies its interpreters, authoring libraries, execution tools, and file delivery tool.
+
+### Minimal configuration
+
+```yaml
+- name: '@deepseek-ai/dsh-skill-office'
+```
+
+| Field | Default | Meaning |
+|---|---|---|
+| `assetRoot` | Packaged `assets/` | Absolute resource directory containing the three skill folders and shared `scripts/`; deployments can place it outside an application archive. |
+
+Relative paths, missing resources, and skill files without a YAML frontmatter description reject activation. Disposing the plugin removes its candidates. Project and user skill precedence remains owned by the skill registry.
+
+### Structural checks
+
+The shared Python checker reads DOCX, PPTX, or XLSX without modifying the source. It recognizes Transitional and Strict OOXML namespaces, validates ZIP/XML and internal package relationships, reports document structure, and optionally checks required text or slide/sheet count. DOCX text assertions cover the main body, section-referenced headers and footers, and body-referenced footnotes and endnotes; comments, glossary text, and unreferenced parts or notes do not satisfy them. It uses only the Python standard library. Invalid packages, corrupt or encrypted ZIP members, and report-file write failures produce a JSON failure report on stdout. A passing report does not establish appearance, feature preservation, or calculated formula results.
+
+-----
+
+<a id="understand-the-implementation"></a>
+## Understand the implementation
+
+<details>
+<summary>Implementation internals — click to expand</summary>
+
+The provider registers three bundled candidates and reads their descriptions from the shipped YAML frontmatter at activation. Loaded instruction bodies exclude that metadata. Each loaded skill exposes its own filesystem directory, so the execution tool can resolve the shared checker without relying on the task working directory. Configurable external resources support carriers whose application archive is not readable by Python.
+
+| File | Responsibility |
+|---|---|
+| [`src/index.ts`](src/index.ts) | Provider registration and configured resource paths. |
+| [`assets/`](assets/) | Three workflows and the read-only OOXML checker. |
+| — | No runtime invariant companion is published: the provider owns immutable candidates, and the skill registry owns registration lifecycle and precedence. |
+
+</details>
+
+-----
+
+<a id="further-exploration"></a>
+## Further Exploration
+
+- [Skill registry](../skill/README.md) — discovery and precedence.
+- [Skill tool](../tool-skill/README.md) — model-visible catalogs and bodies.
+- [File delivery](../../fs/tool-present/README.md) — current source-path delivery.
+
+-----
+
+<a id="model-experience"></a>
+## Model Experience
+
+Indirectly, through `dsh-tool-skill`, which renders the catalog entries and selected instruction body.
+
+#### KV Cache effect
+
+Mounting the provider adds three catalog entries; loading a skill adds its body at the existing skill-tool insertion point. The provider does not add separate prompt sections.
+
+## Known Limitations and Deferred Work
+
+<a id="known-limitations-and-deferred-work"></a>
+
+- The provider does not install Python, authoring libraries, or a rendering engine. The checker requires Python 3.9 or later.
+- Structural checks do not judge pagination, clipping, fonts, chart appearance, or Excel recalculation.
+- The checker accepts DOCX, PPTX, and XLSX only; legacy, encrypted, and macro-enabled formats require an appropriate separate workflow.
+
+<a id="dev-note"></a>
+### Dev Note
+
+<details>
+<summary>Working context for maintainers — click to expand</summary>
+
+None.
+
+</details>

+ 100 - 0
packages/skill/skill-office/README.zh.md

@@ -0,0 +1,100 @@
+---
+description: "随包附带的 Word、PowerPoint 和 Excel 指令,供需要 Office 文件编写与结构检查能力的部署使用。"
+kind: "package-reference"
+---
+
+# @deepseek-ai/dsh-skill-office
+
+[English](README.md) | 中文
+
+## 概述
+
+Agent(智能体)可以加载 Word、PowerPoint 和 Excel 工作流,默认使用内置 Python 环境,并遵循用户或 AGENTS.md 明确指定的环境。这些 skill(技能)涵盖创建、局部编辑、结构检查和文件交付。视觉检查以模型支持图片且有可用渲染工具为前提;普通文档交付不要求安装渲染器。
+
+## 目录
+
+- [使用本包](#use-this-package)
+- [了解实现](#understand-the-implementation)
+- [延伸阅读](#further-exploration)
+- [模型体验](#model-experience)
+- [已知限制与暂缓事项](#known-limitations-and-deferred-work)
+- [开发备注](#dev-note)
+
+-----
+
+<a id="use-this-package"></a>
+## 使用本包
+
+将本提供方与 skill 注册表及 `dsh-tool-skill` 一同挂载,即可在会话目录中提供 `office-docx`、`office-pptx` 和 `office-xlsx`。提供方携带指令和脚本;部署提供解释器、编写库、执行工具与文件交付工具。
+
+### 最小配置
+
+```yaml
+- name: '@deepseek-ai/dsh-skill-office'
+```
+
+| 字段 | 默认值 | 含义 |
+|---|---|---|
+| `assetRoot` | 包内的 `assets/` | 包含三个 skill 文件夹和共享 `scripts/` 的绝对资源目录;部署可将其放在应用归档之外。 |
+
+相对路径、资源缺失或 skill 文件的 YAML frontmatter 缺少描述都会导致激活失败。卸载插件会移除其候选项。项目和用户 skill 的优先级仍由 skill 注册表负责。
+
+### 结构检查
+
+共享 Python 检查器读取 DOCX、PPTX 或 XLSX,不修改源文件。它识别 Transitional 与 Strict OOXML 命名空间,验证 ZIP/XML 和包内引用关系,报告文档结构,并可检查必需文本或幻灯片/工作表数量。DOCX 文本断言覆盖正文、分节引用的页眉和页脚,以及正文引用的脚注和尾注;批注、词库文本与未引用的部件或脚注/尾注不能满足断言。它只使用 Python 标准库。无效包、损坏或加密的 ZIP 成员和报告文件写入失败都会在标准输出中产生 JSON 失败报告。检查通过不代表外观、特性保留或公式计算结果已得到验证。
+
+-----
+
+<a id="understand-the-implementation"></a>
+## 了解实现
+
+<details>
+<summary>实现细节——点击展开</summary>
+
+提供方注册三个内置候选项,并在激活时从随包 YAML frontmatter 读取描述。加载后的指令正文不包含这些元数据。加载后的每个 skill 暴露自己的文件系统目录,因此执行工具可以定位共享检查器,而不依赖任务工作目录。可配置的外部资源支持 Python 无法读取应用归档的分发方式。
+
+| 文件 | 职责 |
+|---|---|
+| [`src/index.ts`](src/index.ts) | 提供方注册与配置资源路径。 |
+| [`assets/`](assets/) | 三种工作流和只读 OOXML 检查器。 |
+| — | 不发布运行时不变量伴随入口:提供方拥有不可变候选项,skill 注册表负责注册生命周期和优先级。 |
+
+</details>
+
+-----
+
+<a id="further-exploration"></a>
+## 延伸阅读
+
+- [skill 注册表](../skill/README.zh.md)——发现与优先级。
+- [skill 工具](../tool-skill/README.zh.md)——模型可见目录与正文。
+- [文件交付](../../fs/tool-present/README.zh.md)——当前源路径交付。
+
+-----
+
+<a id="model-experience"></a>
+## 模型体验
+
+通过 `dsh-tool-skill` 间接呈现,由其渲染目录项与选中的指令正文。
+
+#### KV 缓存影响
+
+挂载提供方会增加三个目录项;加载 skill 时,其正文进入既有 skill 工具的插入位置。提供方不另增提示词分区。
+
+## 已知限制与暂缓事项
+
+<a id="known-limitations-and-deferred-work"></a>
+
+- 提供方不安装 Python、编写库或渲染引擎。检查器要求 Python 3.9 或更高版本。
+- 结构检查不判断分页、裁切、字体、图表外观或 Excel 重算。
+- 检查器只接受 DOCX、PPTX 和 XLSX;传统格式、加密文件和启用宏的格式需要合适的其他工作流。
+
+<a id="dev-note"></a>
+### 开发备注
+
+<details>
+<summary>维护者的工作上下文——点击展开</summary>
+
+无。
+
+</details>

+ 46 - 0
packages/skill/skill-office/assets/office-docx/SKILL.md

@@ -0,0 +1,46 @@
+---
+name: office-docx
+description: Create, read, edit, and check Word documents (.docx), including reports, letters, and formatted tables. Use when a DOCX file is an input or requested deliverable.
+---
+
+# Word documents
+
+Use `python-docx` for DOCX creation and ordinary edits. Follow an explicit user or applicable AGENTS.md requirement for a project environment or another library. Otherwise call `load_workspace_dependencies` and execute the returned Python path with its bundled libraries. Do not install packages or discover a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.
+
+Keep source scripts, intermediate files, and final documents in the task workspace; the runtime and this skill directory are read-only resources. Use the user's requested language and preserve an existing document's design unless a redesign is requested.
+
+## Create and edit
+
+For existing files, inspect paragraphs, runs, tables, sections, headers, and footers before changing the affected content. Save to a new file unless the user requests an in-place edit. Replacing a paragraph's `.text` destroys its run formatting; change the relevant runs when formatting must survive. Reconstructing the whole document can lose features outside python-docx's supported editing API.
+
+Use paragraph styles for headings and body text. Size tables for the section that contains them, and account for merged cells and nested tables. Chinese, Japanese, and Korean text may need an explicit `w:eastAsia` font assignment in addition to `run.font.name`; font names alone do not establish glyph availability or rendered appearance.
+
+For a new document, use the selected Python executable:
+
+```python
+from docx import Document
+
+document = Document()
+document.add_heading("Project report", level=0)
+document.add_paragraph("Summary", style="Heading 1")
+document.add_paragraph("The requested findings go here.")
+document.save("report.docx")
+```
+
+python-docx does not paginate or render documents. Do not represent ordinary replacement, colored text, or comments as tracked changes. When real revisions or unsupported OOXML features matter, preserve their package parts and verify the requested operation rather than silently discarding them.
+
+## Check and deliver
+
+Run the shared checker with the selected Python executable; `<skill-directory>` is this loaded skill's resource base:
+
+```text
+<python> <skill-directory>/../scripts/check_office.py <document.docx> --out <checks.json>
+```
+
+It checks ZIP/XML integrity and internal relationships, and reports paragraphs, logical table dimensions, and sections. Optional `--contains TEXT` arguments assert required text. A successful structural check does not verify pagination, clipping, fonts, or visual appearance. Compare the summary and reopened document with the user's request, including unchanged content that matters to an edit.
+
+If `render_document` is available and visual inspection is useful, call it on the final DOCX without `pages` to prepare page 1 and learn `pageCount`. It checks the current main model's actual image capability; do not choose a second model. On `status: "skipped"`, complete structural and content checks and deliver the document, briefly stating that visual layout was not inspected. On a ready result, call `read_image` on `pages[].imagePath` and request remaining pages in small batches. Check page breaks, clipped text, headings, table widths, and consistency with the requested format or source design. Fix the source and render affected pages again.
+
+Use the available rendering tool for this check. Review `warnings` such as missing fonts. LibreOffice pagination can differ from Microsoft Word. If rendering is unavailable or fails, preserve the usable document and report the inspection limit; do not require the user to install a renderer.
+
+Call `present({"files":[{"path":"report.docx"}]})` with the actual final DOCX path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and do not present temporary QA reports unless requested. If `present` is unavailable, provide the final workspace path using the session's supported file delivery method.

+ 70 - 0
packages/skill/skill-office/assets/office-pptx/SKILL.md

@@ -0,0 +1,70 @@
+---
+name: office-pptx
+description: Create, read, edit, and check PowerPoint presentations (.pptx), including slide text, tables, images, and charts. Use when a PPTX file is an input or requested deliverable.
+---
+
+# PowerPoint presentations
+
+Follow an explicit user or applicable AGENTS.md requirement for an environment or library. Otherwise call `load_workspace_dependencies` and use its Python executable and bundled presentation libraries. Do not install npm or pip packages or locate a system interpreter for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.
+
+Keep scripts and output files in the task workspace. The runtime and skill directory contain shared read-only resources. Match the requested slide language and the supplied presentation's design when editing it.
+
+## Create and edit
+
+Use `python-pptx` to inspect or modify an existing presentation. Inspect slide layouts, text runs, images, tables, and charts before editing. Change only the requested content, preserve mixed text formatting, and save to a new file unless the user requests an in-place edit. Rebuilding slides can discard unsupported animation, SmartArt, or other extension content.
+
+For a new deck, use `python-pptx` with editable text, tables, and charts. Use local image assets rather than network-dependent image URLs. Set slide dimensions, text sizes, and chart data explicitly.
+
+A minimal editable deck, run with the selected Python executable:
+
+```python
+from pptx import Presentation
+from pptx.chart.data import CategoryChartData
+from pptx.enum.chart import XL_CHART_TYPE
+from pptx.util import Inches, Pt
+
+presentation = Presentation()
+presentation.slide_width = Inches(13.333)
+presentation.slide_height = Inches(7.5)
+slide = presentation.slides.add_slide(presentation.slide_layouts[6])
+title = slide.shapes.add_textbox(Inches(0.6), Inches(0.4), Inches(12), Inches(0.8))
+run = title.text_frame.paragraphs[0].add_run()
+run.text = "Quarterly report"
+run.font.size = Pt(30)
+data = CategoryChartData()
+data.categories = ["Q1", "Q2"]
+data.add_series("Revenue", [12, 18])
+slide.shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED,
+                       Inches(0.8), Inches(1.6), Inches(11.5), Inches(4.8), data)
+presentation.save("report.pptx")
+```
+
+Use `Inches` or `Cm` for positions and sizes and `Pt` for font sizes. To edit a generated title while retaining its other slides and charts:
+
+```python
+from pptx import Presentation
+
+presentation = Presentation("report.pptx")
+for shape in presentation.slides[0].shapes:
+    if shape.has_text_frame and shape.text == "Quarterly report":
+        shape.text_frame.paragraphs[0].runs[0].text = "Quarterly results"
+presentation.save("report-edited.pptx")
+```
+
+Check that text and images fit the slide dimensions, titles form a useful sequence, and chart labels agree with source values. A native chart's embedded workbook is part of the deliverable and must contain the intended data. Library support for writing PPTX is not a rendering engine or a guarantee that every PowerPoint feature survives editing.
+
+## Check and deliver
+
+Run the shared checker with the selected Python executable; `<skill-directory>` is this loaded skill's resource base:
+
+```text
+<python> <skill-directory>/../scripts/check_office.py <presentation.pptx> --out <checks.json>
+```
+
+It checks ZIP/XML integrity and internal relationships and reports slide count and extracted text. Use repeated `--contains TEXT` arguments for required slide text and `--count N` for a requested slide count; `--contains` excludes chart text and speaker notes. Reopen the file to check the requested edits, chart data, and notes. Structural success does not establish text fit, alignment, readable contrast, or rendering fidelity.
+
+If `render_document` is available and visual inspection is useful, call it on the final PPTX, initially omitting `pages` to prepare page 1 and obtain `pageCount`. The tool checks the current main model's actual image capability; do not choose a second model. If `status` is `skipped`, complete structural and content checks and deliver the PPTX, briefly stating that visual layout was not inspected. If ready, call `read_image` on its returned `pages[].imagePath`, then inspect remaining slides in small batches such as `pages: [2, 3, 4]`. Check clipping, alignment, contrast, chart labels, and consistency with the requested design or supplied reference; fix the source and render the affected pages again.
+
+Use the available rendering tool for this check. Inspect `warnings`, especially missing fonts. LibreOffice previews do not certify pixel-identical PowerPoint or Keynote output, animation, or media playback. If the rendering tool is unavailable or fails, retain the usable source and report the inspection limit; do not require the user to install another tool.
+
+Call `present({"files":[{"path":"report-edited.pptx"}]})` with the actual final PPTX path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and leave intermediate images and reports out of delivery unless requested. If `present` is unavailable, use the session's supported file delivery method.

+ 56 - 0
packages/skill/skill-office/assets/office-xlsx/SKILL.md

@@ -0,0 +1,56 @@
+---
+name: office-xlsx
+description: Read, create, and modify Excel workbooks (.xlsx), including cell values, formulas, formatting, and pandas analysis. Use when an Excel workbook is an input or deliverable.
+---
+
+# Excel workbooks
+
+Follow an explicit user or applicable AGENTS.md requirement for an environment or library. Otherwise call `load_workspace_dependencies` and run its Python executable with bundled `openpyxl` and `pandas`. Do not install packages or search for a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.
+
+Keep scripts, working files, and outputs in the task workspace. The runtime and skill directory are shared read-only resources. Save to a new workbook unless the user requests an in-place edit.
+
+## Read and modify
+
+Use `openpyxl` for existing XLSX workbooks and targeted cell or style changes. Load with `data_only=False` when formulas must survive. Inspect sheet names, the affected cell types, formulas, styles, merged ranges, and referenced ranges before editing. Check the saved file by reopening it, including unchanged content that the request requires preserving.
+
+Use pandas for data analysis and transformations. A DataFrame is not the workbook: exporting it over an existing file can lose sheets, formulas, charts, and formatting. Write analysis results back to the intended ranges with openpyxl. `XlsxWriter` can create new workbooks, but cannot read or modify existing ones.
+
+For a new workbook, the selected Python environment can write editable values, styles, and formulas directly:
+
+```python
+from openpyxl import Workbook
+from openpyxl.styles import Font
+
+workbook = Workbook()
+sheet = workbook.active
+sheet.title = "Revenue"
+for row in [("Quarter", "Revenue"), ("Q1", 12), ("Q2", 18), ("Total", "=SUM(B2:B3)")]:
+    sheet.append(row)
+for cell in sheet[1]:
+    cell.font = Font(bold=True)
+sheet.column_dimensions["A"].width = 18
+sheet.column_dimensions["B"].width = 18
+workbook.save("report.xlsx")
+```
+
+Preserve numbers, dates, booleans, and identifiers as the intended cell types; formatting is not a type conversion. For modifications, load the existing file with `openpyxl.load_workbook("input.xlsx", data_only=False)`, change the requested ranges, and save a separate result. Avoid a DataFrame round trip when workbook features must survive.
+
+Writing a formula does not calculate its result. openpyxl and XlsxWriter do not evaluate Excel formulas; `data_only=True` returns stored cached values that may be absent or stale. Verify formulas and inputs separately, and state when current results require recalculation in a spreadsheet application. Do not replace requested formulas with constants or report cached values as newly calculated results.
+
+Do not rename `.xls`, `.xlsb`, encrypted files, or macro-enabled files to `.xlsx`. They need an appropriate supported operation. `keep_vba=True` can preserve VBA package content in an XLSM workflow, but does not execute or edit macros and does not guarantee every advanced workbook feature survives. Preserve the original and verify such requirements explicitly.
+
+## Check and deliver
+
+Run the shared checker with the selected Python executable; `<skill-directory>` is this loaded skill's resource base:
+
+```text
+<python> <skill-directory>/../scripts/check_office.py <workbook.xlsx> --out <checks.json>
+```
+
+It checks ZIP/XML integrity and internal relationships, and reports sheet names, populated-cell counts, and formula counts. Repeated `--contains TEXT` arguments check string cells and sheet names, and `--count N` checks sheet count. `--contains` excludes numeric cells and does not validate formula results; verify those separately with openpyxl. The checker does not calculate formulas or judge workbook appearance. Compare relevant values, types, formulas, styles, and totals with the task's source data.
+
+If `render_document` is available and visual inspection is useful, call it on the final workbook without `pages` to prepare page 1 and learn `pageCount`. It checks the current main model's actual image capability; do not choose a second model. On `status: "skipped"`, complete structural and data checks and deliver the workbook, briefly stating that visual layout was not inspected. Otherwise call `read_image` on `pages[].imagePath` and request remaining pages in small batches. Check column widths, number formats, clipping, charts, and print areas; fix the workbook and review the affected pages again.
+
+Rendered pages follow spreadsheet print settings, so a page is not necessarily a worksheet. Set appropriate print areas and scaling when a readable printed layout is requested. Review `warnings` such as missing fonts. LibreOffice preview conversion neither updates the original workbook's cached formulas nor certifies native Excel calculation or appearance. If rendering is unavailable or fails, preserve the usable workbook and report the inspection limit; ordinary cell edits do not require installing an external renderer.
+
+Call `present({"files":[{"path":"report.xlsx"}]})` with the actual final workbook path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and omit intermediate scripts and reports unless requested. If `present` is unavailable, use the session's supported file delivery method.

+ 279 - 0
packages/skill/skill-office/assets/scripts/check_office.py

@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+"""Read-only OOXML checks and structural summaries; no rendering or formula evaluation.
+
+Run with INPUT.docx, INPUT.pptx, or INPUT.xlsx. Optional --contains assertions
+check extracted text; DOCX excludes comments, glossary text, and unreferenced parts or notes.
+--count checks slides or sheets. JSON escapes non-ASCII
+characters and goes to stdout and optionally --out. Exit 0 means the requested
+structural checks passed, 1 means a document, assertion, or report write failed, and 2 means
+invalid command-line arguments.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import posixpath
+import sys
+import zipfile
+import zlib
+from pathlib import Path
+from urllib.parse import unquote, urlsplit
+from xml.etree import ElementTree as ET
+
+W_NAMESPACES = (
+    "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
+    "http://purl.oclc.org/ooxml/wordprocessingml/main",
+)
+A_NAMESPACES = (
+    "http://schemas.openxmlformats.org/drawingml/2006/main",
+    "http://purl.oclc.org/ooxml/drawingml/main",
+)
+P_NAMESPACES = (
+    "http://schemas.openxmlformats.org/presentationml/2006/main",
+    "http://purl.oclc.org/ooxml/presentationml/main",
+)
+S_NAMESPACES = (
+    "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
+    "http://purl.oclc.org/ooxml/spreadsheetml/main",
+)
+R_NAMESPACES = (
+    "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
+    "http://purl.oclc.org/ooxml/officeDocument/relationships",
+)
+MAIN_PARTS = {
+    ".docx": ("word/document.xml", "wordprocessingml.document.main+xml"),
+    ".pptx": ("ppt/presentation.xml", "presentationml.presentation.main+xml"),
+    ".xlsx": ("xl/workbook.xml", "spreadsheetml.sheet.main+xml"),
+}
+
+
+def namespace(root: ET.Element, supported: tuple[str, ...], part: str) -> str:
+    """Return the main XML namespace after checking its OOXML variant."""
+    uri = root.tag[1:].split("}", 1)[0] if root.tag.startswith("{") else ""
+    if uri not in supported:
+        raise ValueError(f"{part} uses unsupported XML namespace: {uri or '(none)'}")
+    return "{" + uri + "}"
+
+
+def relationship_id(node: ET.Element, part: str) -> str:
+    """Read an office-document relationship id from Transitional or Strict OOXML."""
+    for uri in R_NAMESPACES:
+        value = node.get("{" + uri + "}id")
+        if value is not None:
+            return value
+    raise ValueError(f"{part} has a reference without a relationship id")
+
+
+def relationship_types(kind: str) -> set[str]:
+    """Return the Transitional and Strict relationship type names for one role."""
+    return {f"{uri}/{kind}" for uri in R_NAMESPACES}
+
+
+def iter_namespaces(root: ET.Element, namespaces: tuple[str, ...], local_name: str):
+    """Iterate matching elements across Transitional and Strict namespaces."""
+    for uri in namespaces:
+        yield from root.iter("{" + uri + "}" + local_name)
+
+
+def relationship_target(part: str, target: str) -> str:
+    """Resolve a package relationship without fetching external resources."""
+    path = unquote(urlsplit(target).path)
+    return posixpath.normpath(path.lstrip("/") if path.startswith("/") else posixpath.join(posixpath.dirname(part), path))
+
+
+def relationships(part: str, xml: dict[str, ET.Element], types: set[str] | None = None) -> dict[str, str]:
+    path = posixpath.join(posixpath.dirname(part), "_rels", posixpath.basename(part) + ".rels")
+    root = xml.get(path)
+    if root is None:
+        return {}
+    return {
+        rel.attrib["Id"]: relationship_target(part, rel.attrib["Target"])
+        for rel in root if rel.get("TargetMode") != "External" and (types is None or rel.get("Type") in types)
+    }
+
+
+def related_xml(part: str, reference: str, links: dict[str, str], xml: dict[str, ET.Element]) -> ET.Element:
+    """Read a related XML part with diagnostics naming its source and reference."""
+    if reference not in links:
+        raise ValueError(f"{part} references missing relationship: {reference}")
+    target = links[reference]
+    if target not in xml:
+        raise ValueError(f"{part} relationship {reference} targets a non-XML member: {target}")
+    return xml[target]
+
+
+def inspect_docx(xml: dict[str, ET.Element]) -> tuple[dict, str]:
+    part = "word/document.xml"
+    root = xml[part]
+    w = namespace(root, W_NAMESPACES, part)
+    body = root.find(f"{w}body")
+    if body is None:
+        raise ValueError("word/document.xml has no document body")
+    tables = []
+    for table in body.iter(f"{w}tbl"):
+        grid = table.findall(f"{w}tblGrid/{w}gridCol")
+        rows = table.findall(f"{w}tr")
+        # Merged cells span logical grid columns; counting physical cells loses them.
+        columns = len(grid) if grid else max((sum(
+            int(cell.find(f"{w}tcPr/{w}gridSpan").get(f"{w}val", "1"))
+            if cell.find(f"{w}tcPr/{w}gridSpan") is not None else 1
+            for cell in row.findall(f"{w}tc")
+        ) for row in rows), default=0)
+        tables.append({"rows": len(rows), "columns": columns})
+    sections = []
+    for section in body.iter(f"{w}sectPr"):
+        size = section.find(f"{w}pgSz")
+        margins = section.find(f"{w}pgMar")
+        sections.append({
+            "page_twips": {} if size is None else {key.removeprefix(w): value for key, value in size.attrib.items()},
+            "margins_twips": {} if margins is None else {key.removeprefix(w): value for key, value in margins.attrib.items()},
+        })
+    text_parts = [body]
+    for kind in ("header", "footer"):
+        links = relationships(part, xml, relationship_types(kind))
+        for section in body.iter(f"{w}sectPr"):
+            for reference in section.findall(f"{w}{kind}Reference"):
+                text_parts.append(related_xml(part, relationship_id(reference, part), links, xml))
+    for kind in ("footnote", "endnote"):
+        references = {node.attrib[f"{w}id"] for node in body.iter(f"{w}{kind}Reference")}
+        if not references:
+            continue
+        links = relationships(part, xml, relationship_types(f"{kind}s"))
+        for reference in links:
+            tree = related_xml(part, reference, links, xml)
+            text_parts.extend(note for note in tree.findall(f"{w}{kind}") if note.get(f"{w}id") in references)
+    text = "\n".join("".join(node.text or "" for node in paragraph.iter(f"{w}t")) for tree in text_parts
+                     for paragraph in tree.iter(f"{w}p"))
+    return {"paragraphs": len(list(body.iter(f"{w}p"))), "tables": tables, "sections": sections}, text
+
+
+def inspect_pptx(xml: dict[str, ET.Element]) -> tuple[dict, str]:
+    part = "ppt/presentation.xml"
+    links = relationships(part, xml)
+    root = xml[part]
+    p = namespace(root, P_NAMESPACES, part)
+    slides = root.findall(f"{p}sldIdLst/{p}sldId")
+    texts = []
+    for slide in slides:
+        reference = relationship_id(slide, part)
+        tree = related_xml(part, reference, links, xml)
+        texts.append("\n".join("".join(node.text or "" for node in iter_namespaces(paragraph, A_NAMESPACES, "t"))
+                               for paragraph in iter_namespaces(tree, A_NAMESPACES, "p")))
+    return {"slides": len(slides)}, "\n".join(texts)
+
+
+def inspect_xlsx(xml: dict[str, ET.Element]) -> tuple[dict, str]:
+    part = "xl/workbook.xml"
+    links = relationships(part, xml)
+    root = xml[part]
+    s = namespace(root, S_NAMESPACES, part)
+    sheets = []
+    texts = []
+    shared = xml.get("xl/sharedStrings.xml")
+    shared_s = s if shared is None else namespace(shared, S_NAMESPACES, "xl/sharedStrings.xml")
+    shared_strings = [] if shared is None else [
+        "".join(node.text or "" for node in item.iter(f"{shared_s}t")) for item in shared.iter(f"{shared_s}si")
+    ]
+    for sheet in root.findall(f"{s}sheets/{s}sheet"):
+        reference = relationship_id(sheet, part)
+        tree = related_xml(part, reference, links, xml)
+        sheet_s = namespace(tree, S_NAMESPACES, links[reference])
+        cells = list(tree.iter(f"{sheet_s}c"))
+        formulas = sum(cell.find(f"{sheet_s}f") is not None for cell in cells)
+        sheets.append({"name": sheet.attrib["name"], "cells": len(cells), "formulas": formulas})
+        for cell in cells:
+            if cell.get("t") == "s":
+                value = cell.findtext(f"{sheet_s}v", "")
+                location = f"{links[reference]} cell {cell.get('r', '(no reference)')}"
+                try:
+                    index = int(value)
+                except ValueError as error:
+                    raise ValueError(f"{location}: invalid shared string index {value!r}") from error
+                if not 0 <= index < len(shared_strings):
+                    raise ValueError(f"{location}: shared string index out of range: {index}")
+                texts.append(shared_strings[index])
+        texts.extend("".join(node.text or "" for node in cell.iter(f"{sheet_s}t")) for cell in cells)
+        texts.extend(cell.findtext(f"{sheet_s}v", "") for cell in cells if cell.get("t") == "str")
+        texts.append(sheet.attrib["name"])
+    return {"sheets": sheets, "formulas_evaluated": False}, "\n".join(texts)
+
+
+def inspect(path: Path) -> tuple[dict, str]:
+    """Validate package members and relationships before inspecting the main part."""
+    main, content_type = MAIN_PARTS[path.suffix.lower()]
+    with zipfile.ZipFile(path) as archive:
+        members = archive.namelist()
+        if len(members) != len(set(members)):
+            raise ValueError("ZIP contains duplicate member names")
+        corrupt = archive.testzip()
+        if corrupt is not None:
+            raise ValueError(f"ZIP member failed its CRC check: {corrupt}")
+        xml = {name: ET.fromstring(archive.read(name)) for name in members
+               if name.endswith((".xml", ".rels"))}
+    if main not in xml:
+        raise ValueError(f"missing main part: {main}")
+    types = xml.get("[Content_Types].xml")
+    if types is None or not any(node.get("PartName") == "/" + main
+                                and node.get("ContentType", "").endswith(content_type) for node in types):
+        raise ValueError(f"[Content_Types].xml does not declare {main} as {path.suffix.lower()}")
+    for name, tree in xml.items():
+        if not name.endswith(".rels"):
+            continue
+        source = "" if name == "_rels/.rels" else posixpath.join(posixpath.dirname(posixpath.dirname(name)), posixpath.basename(name)[:-5])
+        for rel in tree:
+            if rel.get("TargetMode") == "External":
+                continue
+            target = relationship_target(source, rel.attrib["Target"])
+            if target not in members:
+                raise ValueError(f"{name} references missing package member: {target}")
+    if path.suffix.lower() == ".docx":
+        return inspect_docx(xml)
+    if path.suffix.lower() == ".pptx":
+        return inspect_pptx(xml)
+    return inspect_xlsx(xml)
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("input", type=Path)
+    parser.add_argument("--out", type=Path)
+    parser.add_argument("--contains", action="append", default=[], metavar="TEXT")
+    parser.add_argument("--count", type=int, help="expected slide or sheet count")
+    args = parser.parse_args()
+    if args.input.suffix.lower() not in MAIN_PARTS:
+        parser.error("input must be .docx, .pptx, or .xlsx; converting the filename does not convert its contents")
+    if args.count is not None and (args.count < 0 or args.input.suffix.lower() == ".docx"):
+        parser.error("--count must be non-negative and applies only to slides or sheets")
+    if args.out is not None and args.out.resolve() == args.input.resolve():
+        parser.error("--out must differ from the input document")
+    checks = []
+    summary = {}
+    try:
+        summary, text = inspect(args.input)
+        checks.append({"id": "package", "status": "pass"})
+        for required in args.contains:
+            checks.append({"id": "contains", "status": "pass" if required in text else "fail", "text": required})
+        if args.count is not None:
+            actual = summary.get("slides", len(summary.get("sheets", [])))
+            checks.append({"id": "count", "status": "pass" if actual == args.count else "fail", "expected": args.count, "actual": actual})
+    except (OSError, ValueError, KeyError, RuntimeError, ET.ParseError, zipfile.BadZipFile, zlib.error) as error:
+        checks.append({"id": "package", "status": "fail", "detail": str(error)})
+    failed = any(check["status"] == "fail" for check in checks)
+    report = {"format": args.input.suffix.lower()[1:], "verdict": "fail" if failed else "pass", "checks": checks, "summary": summary}
+    output = json.dumps(report, ensure_ascii=True, indent=2) + "\n"
+    if args.out is not None:
+        try:
+            args.out.parent.mkdir(parents=True, exist_ok=True)
+            args.out.write_text(output, encoding="utf-8")
+        except OSError as error:
+            failed = True
+            report["verdict"] = "fail"
+            checks.append({"id": "output", "status": "fail", "detail": str(error)})
+            output = json.dumps(report, ensure_ascii=True, indent=2) + "\n"
+    sys.stdout.write(output)
+    return 1 if failed else 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 43 - 0
packages/skill/skill-office/package.json

@@ -0,0 +1,43 @@
+{
+  "name": "@deepseek-ai/dsh-skill-office",
+  "description": "Bundled Word, PowerPoint, and Excel workflows and structural checks",
+  "version": "0.1.6-alpha.1",
+  "publishConfig": {
+    "access": "public"
+  },
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
+    "directory": "packages/skill/skill-office"
+  },
+  "type": "module",
+  "main": "lib/index.js",
+  "types": "lib/types/index.d.ts",
+  "exports": {
+    ".": {
+      "types": "./lib/types/index.d.ts",
+      "default": "./lib/index.js"
+    },
+    "./package.json": "./package.json"
+  },
+  "files": [
+    "lib/index.js",
+    "assets",
+    "lib/types/**/*.d.ts"
+  ],
+  "license": "MIT",
+  "peerDependencies": {
+    "@deepseek-ai/dsh-skill": "workspace:^",
+    "@deepseek-ai/cordis": "workspace:^"
+  },
+  "devDependencies": {
+    "@deepseek-ai/dsh-skill": "workspace:^",
+    "@deepseek-ai/cordis": "workspace:^",
+    "@deepseek-ai/cordis-plugin-loader": "workspace:^",
+    "@deepseek-ai/cordis-plugin-include": "workspace:^"
+  },
+  "dependencies": {
+    "@deepseek-ai/schemastery": "workspace:^",
+    "yaml": "^2.4.2"
+  }
+}

+ 70 - 0
packages/skill/skill-office/src/index.ts

@@ -0,0 +1,70 @@
+/** Bundled Office workflows and filesystem resources for document authoring and checks. */
+
+import { readFileSync, statSync } from 'node:fs'
+import { readFile } from 'node:fs/promises'
+import { isAbsolute, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import type { Context } from '@deepseek-ai/cordis'
+import z from '@deepseek-ai/schemastery'
+import { BUNDLED_SKILL_RANK, type SkillCandidate, type SkillProvider } from '@deepseek-ai/dsh-skill'
+import { parse as parseYaml } from 'yaml'
+
+const SKILL_NAMES = ['office-docx', 'office-pptx', 'office-xlsx'] as const
+
+/** Office skill resource location. */
+export interface Config {
+  /** Absolute assets directory containing the three skill folders and shared scripts; defaults to packaged assets. */
+  assetRoot?: string
+}
+
+/** Validated resource configuration. */
+export const Config: z<Config> = z.object({ assetRoot: z.string().min(1) })
+
+/** Cordis plugin identity. */
+export const name = 'skill-office'
+/** Registry used by the bundled provider. */
+export const inject = ['skills']
+
+function parseSkill(raw: string, path: string): { description: string; content: string } {
+  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(raw)
+  if (frontmatter?.[1] === undefined) throw new Error(`skill-office: ${path} has no YAML frontmatter`)
+  const metadata: unknown = parseYaml(frontmatter[1])
+  const description = typeof metadata === 'object' && metadata !== null && 'description' in metadata
+    ? metadata.description : undefined
+  if (typeof description !== 'string' || description.length === 0) throw new Error(`skill-office: ${path} has no description`)
+  return { description, content: raw.slice(frontmatter[0].length).trim() }
+}
+
+/**
+ * Register Office skills with resources readable by the script interpreter.
+ * @param ctx - Context carrying the skill registry.
+ * @param config - Optional external assets directory for packaged applications.
+ */
+export function apply(ctx: Context, config: Config = {}): void {
+  const assetRoot = config.assetRoot ?? fileURLToPath(new URL('../assets/', import.meta.url))
+  if (!isAbsolute(assetRoot)) throw new Error('skill-office: assetRoot must be an absolute directory')
+  if (!statSync(join(assetRoot, 'scripts', 'check_office.py')).isFile()) {
+    throw new Error('skill-office: assets must contain scripts/check_office.py')
+  }
+  const candidates: SkillCandidate[] = SKILL_NAMES.map((skillName) => {
+    const directory = join(assetRoot, skillName)
+    const path = join(directory, 'SKILL.md')
+    const { description } = parseSkill(readFileSync(path, 'utf8'), path)
+    return {
+      name: skillName, description,
+      invocation: { modelInvocable: true, userInvocable: true },
+      provider: 'dsh-office', source: 'bundled', rank: BUNDLED_SKILL_RANK,
+      resourceBase: { kind: 'directory', path: directory }, locator: path,
+    }
+  })
+  const provider: SkillProvider = {
+    name: 'dsh-office',
+    list: () => Promise.resolve(candidates),
+    async get(candidate, options) {
+      const { rank: _rank, locator, ...summary } = candidate
+      const raw = await readFile(locator as string, { encoding: 'utf8', signal: options.signal })
+      return { ...summary, content: parseSkill(raw, locator as string).content }
+    },
+  }
+  ctx.skills.registerProvider(() => provider)
+}

+ 278 - 0
packages/skill/skill-office/tests/check_office_test.py

@@ -0,0 +1,278 @@
+"""Exercise the distributed checker without requiring external Office libraries."""
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+
+CHECKER = Path(__file__).resolve().parents[1] / "assets/scripts/check_office.py"
+W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+P = "http://schemas.openxmlformats.org/presentationml/2006/main"
+A = "http://schemas.openxmlformats.org/drawingml/2006/main"
+S = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
+R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+STRICT_W = "http://purl.oclc.org/ooxml/wordprocessingml/main"
+STRICT_P = "http://purl.oclc.org/ooxml/presentationml/main"
+STRICT_A = "http://purl.oclc.org/ooxml/drawingml/main"
+STRICT_S = "http://purl.oclc.org/ooxml/spreadsheetml/main"
+STRICT_R = "http://purl.oclc.org/ooxml/officeDocument/relationships"
+PKG = "http://schemas.openxmlformats.org/package/2006/relationships"
+
+
+class OfficeCheckTest(unittest.TestCase):
+    def setUp(self):
+        self.directory = tempfile.TemporaryDirectory(prefix="dsh-office-check-")
+        self.addCleanup(self.directory.cleanup)
+        self.root = Path(self.directory.name)
+
+    def package(self, suffix, parts, compression=zipfile.ZIP_STORED):
+        primary, mime = {
+            "docx": ("word/document.xml", "wordprocessingml.document.main+xml"),
+            "pptx": ("ppt/presentation.xml", "presentationml.presentation.main+xml"),
+            "xlsx": ("xl/workbook.xml", "spreadsheetml.sheet.main+xml"),
+        }[suffix]
+        path = self.root / ("中文 document." + suffix)
+        with zipfile.ZipFile(path, "w", compression=compression) as archive:
+            archive.writestr("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
+                             f'<Override PartName="/{primary}" ContentType="application/vnd.openxmlformats-officedocument.{mime}"/></Types>')
+            for name, content in parts.items():
+                archive.writestr(name, content)
+        return path
+
+    def run_check(self, path, *args):
+        before = path.read_bytes()
+        output = self.root / "checks.json"
+        result = subprocess.run([sys.executable, str(CHECKER), str(path), "--out", str(output), *args],
+                                capture_output=True, text=True, timeout=10)
+        self.assertEqual(path.read_bytes(), before)
+        self.assertEqual(result.stderr, "", result.stderr)
+        report = json.loads(result.stdout)
+        self.assertEqual(report, json.loads(output.read_text(encoding="utf-8")))
+        return result.returncode, report
+
+    def test_docx_merged_cells_distinct_sections_and_cjk_are_not_layout_failures(self):
+        path = self.package("docx", {"word/document.xml": f'''<w:document xmlns:w="{W}"><w:body>
+          <w:p><w:r><w:t>中文报告</w:t></w:r><w:pPr><w:sectPr><w:pgSz w:w="16000"/><w:pgMar w:left="1000" w:right="1000"/></w:sectPr></w:pPr></w:p>
+          <w:tbl><w:tblGrid><w:gridCol w:w="5000"/><w:gridCol w:w="5000"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:gridSpan w:val="2"/></w:tcPr><w:p><w:r><w:t>合并标题</w:t></w:r></w:p></w:tc></w:tr></w:tbl>
+          <w:sectPr><w:pgSz w:w="6000"/><w:pgMar w:left="1000" w:right="1000"/></w:sectPr>
+        </w:body></w:document>'''})
+        code, report = self.run_check(path, "--contains", "中文报告")
+        self.assertEqual(code, 0)
+        self.assertEqual(report["summary"]["tables"], [{"rows": 1, "columns": 2}])
+        self.assertEqual(len(report["summary"]["sections"]), 2)
+        code, report = self.run_check(path, "--contains", "Missing requested title")
+        self.assertEqual(code, 1)
+        self.assertEqual(report["checks"][-1]["status"], "fail")
+
+    def test_pptx_checks_slide_count_and_relationships(self):
+        parts = {
+            "ppt/presentation.xml": f'<p:presentation xmlns:p="{P}" xmlns:r="{R}"><p:sldIdLst><p:sldId id="256" r:id="r1"/></p:sldIdLst></p:presentation>',
+            "ppt/_rels/presentation.xml.rels": f'<Relationships xmlns="{PKG}"><Relationship Id="r1" Target="slides/slide1.xml"/></Relationships>',
+            "ppt/slides/slide1.xml": f'<p:sld xmlns:p="{P}" xmlns:a="{A}"><a:p><a:r><a:t>季度总结</a:t></a:r></a:p></p:sld>',
+        }
+        path = self.package("pptx", parts)
+        self.assertEqual(self.run_check(path, "--contains", "季度总结", "--count", "1")[0], 0)
+        self.assertEqual(self.run_check(path, "--count", "2")[0], 1)
+        parts["ppt/_rels/presentation.xml.rels"] = f'<Relationships xmlns="{PKG}"/>'
+        code, report = self.run_check(self.package("pptx", parts))
+        self.assertEqual(code, 1)
+        self.assertIn("ppt/presentation.xml", report["checks"][0]["detail"])
+        self.assertIn("r1", report["checks"][0]["detail"])
+        parts["ppt/_rels/presentation.xml.rels"] = f'<Relationships xmlns="{PKG}"><Relationship Id="r1" Target="slides/slide1.xml"/></Relationships>'
+        del parts["ppt/slides/slide1.xml"]
+        path = self.package("pptx", parts)
+        code, report = self.run_check(path)
+        self.assertEqual(code, 1)
+        self.assertIn("missing package member", report["checks"][0]["detail"])
+
+    def test_docx_content_follows_section_and_note_references(self):
+        parts = {
+            "word/document.xml": f'''<w:document xmlns:w="{W}" xmlns:r="{R}"><w:body>
+              <w:p><w:r><w:t>Main text</w:t><w:footnoteReference w:id="2"/><w:endnoteReference w:id="3"/></w:r></w:p>
+              <w:sectPr><w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/></w:sectPr>
+            </w:body></w:document>''',
+            "word/_rels/document.xml.rels": f'''<Relationships xmlns="{PKG}">
+              <Relationship Id="header" Type="{R}/header" Target="custom/header.xml"/>
+              <Relationship Id="footer" Type="{R}/footer" Target="custom/footer.xml"/>
+              <Relationship Id="unused-header" Type="{R}/header" Target="custom/unused-header.xml"/>
+              <Relationship Id="unused-footer" Type="{R}/footer" Target="custom/unused-footer.xml"/>
+              <Relationship Id="notes" Type="{R}/footnotes" Target="custom/notes.xml"/>
+              <Relationship Id="endnotes" Type="{R}/endnotes" Target="custom/endnotes.xml"/>
+              <Relationship Id="comments" Type="{R}/comments" Target="comments.xml"/>
+              <Relationship Id="glossary" Type="{R}/glossaryDocument" Target="glossary/document.xml"/>
+            </Relationships>''',
+            "word/custom/header.xml": f'<w:hdr xmlns:w="{W}"><w:p><w:r><w:t>Linked header</w:t></w:r></w:p></w:hdr>',
+            "word/custom/footer.xml": f'<w:ftr xmlns:w="{W}"><w:p><w:r><w:t>Linked footer</w:t></w:r></w:p></w:ftr>',
+            "word/custom/unused-header.xml": f'<w:hdr xmlns:w="{W}"><w:p><w:r><w:t>Retained header only</w:t></w:r></w:p></w:hdr>',
+            "word/custom/unused-footer.xml": f'<w:ftr xmlns:w="{W}"><w:p><w:r><w:t>Retained footer only</w:t></w:r></w:p></w:ftr>',
+            "word/custom/notes.xml": f'''<w:footnotes xmlns:w="{W}">
+              <w:footnote w:id="2"><w:p><w:r><w:t>Linked note</w:t></w:r></w:p></w:footnote>
+              <w:footnote w:id="4"><w:p><w:r><w:t>Unused note only</w:t></w:r></w:p></w:footnote>
+            </w:footnotes>''',
+            "word/custom/endnotes.xml": f'''<w:endnotes xmlns:w="{W}">
+              <w:endnote w:id="3"><w:p><w:r><w:t>Linked endnote</w:t></w:r></w:p></w:endnote>
+              <w:endnote w:id="5"><w:p><w:r><w:t>Unused endnote only</w:t></w:r></w:p></w:endnote>
+            </w:endnotes>''',
+            "word/comments.xml": f'<w:comments xmlns:w="{W}"><w:comment><w:p><w:r><w:t>Comment only</w:t></w:r></w:p></w:comment></w:comments>',
+            "word/glossary/document.xml": f'<w:glossaryDocument xmlns:w="{W}"><w:p><w:r><w:t>Building block only</w:t></w:r></w:p></w:glossaryDocument>',
+            "word/header9.xml": f'<w:hdr xmlns:w="{W}"><w:p><w:r><w:t>Unused header only</w:t></w:r></w:p></w:hdr>',
+        }
+        path = self.package("docx", parts)
+        self.assertEqual(self.run_check(path, "--contains", "Main text", "--contains", "Linked header", "--contains", "Linked footer",
+                                        "--contains", "Linked note", "--contains", "Linked endnote")[0], 0)
+        for text in ["Comment only", "Building block only", "Unused header only", "Retained header only", "Retained footer only",
+                     "Unused note only", "Unused endnote only"]:
+            with self.subTest(text=text):
+                code, report = self.run_check(path, "--contains", text)
+                self.assertEqual(code, 1)
+                self.assertEqual(report["checks"][-1]["status"], "fail")
+
+    def test_relationships_to_non_xml_members_report_source_reference_and_target(self):
+        for suffix, main, references in [
+            ("pptx", "ppt/presentation.xml", f'<p:presentation xmlns:p="{P}" xmlns:r="{R}"><p:sldIdLst><p:sldId id="256" r:id="r1"/></p:sldIdLst></p:presentation>'),
+            ("xlsx", "xl/workbook.xml", f'<workbook xmlns="{S}" xmlns:r="{R}"><sheets><sheet name="Data" sheetId="1" r:id="r1"/></sheets></workbook>'),
+        ]:
+            with self.subTest(format=suffix):
+                folder, filename = main.split("/")
+                target = f"{folder}/media/image1.png"
+                path = self.package(suffix, {
+                    main: references,
+                    f"{folder}/_rels/{filename}.rels": f'<Relationships xmlns="{PKG}"><Relationship Id="r1" Target="media/image1.png"/></Relationships>',
+                    target: b"image bytes",
+                })
+                code, report = self.run_check(path)
+                self.assertEqual(code, 1)
+                detail = report["checks"][0]["detail"]
+                for expected in [main, "r1", target]:
+                    self.assertIn(expected, detail)
+
+    def test_xlsx_counts_formulas_without_claiming_recalculation(self):
+        path = self.package("xlsx", {
+            "xl/workbook.xml": f'<workbook xmlns="{S}" xmlns:r="{R}"><sheets><sheet name="Data" sheetId="1" r:id="r1"/></sheets></workbook>',
+            "xl/_rels/workbook.xml.rels": f'<Relationships xmlns="{PKG}"><Relationship Id="r1" Target="/xl/worksheets/sheet1.xml"/></Relationships>',
+            "xl/worksheets/sheet1.xml": f'<worksheet xmlns="{S}"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>收入</t></is></c><c r="B1"><v>4</v></c><c r="C1"><f>B1*2</f><v/></c></row></sheetData></worksheet>',
+        })
+        code, report = self.run_check(path, "--contains", "收入", "--count", "1")
+        self.assertEqual(code, 0)
+        self.assertEqual(report["summary"], {"sheets": [{"name": "Data", "cells": 3, "formulas": 1}], "formulas_evaluated": False})
+
+    def test_strict_ooxml_namespaces_are_inspected(self):
+        docx = self.package("docx", {
+            "word/document.xml": f'<w:document xmlns:w="{STRICT_W}"><w:body><w:p><w:r><w:t>Strict Word</w:t></w:r></w:p></w:body></w:document>',
+        })
+        self.assertEqual(self.run_check(docx, "--contains", "Strict Word")[0], 0)
+
+        pptx = self.package("pptx", {
+            "ppt/presentation.xml": f'<p:presentation xmlns:p="{STRICT_P}" xmlns:r="{STRICT_R}"><p:sldIdLst><p:sldId id="256" r:id="r1"/></p:sldIdLst></p:presentation>',
+            "ppt/_rels/presentation.xml.rels": f'<Relationships xmlns="{PKG}"><Relationship Id="r1" Target="slides/slide1.xml"/></Relationships>',
+            "ppt/slides/slide1.xml": f'<p:sld xmlns:p="{STRICT_P}" xmlns:a="{STRICT_A}"><a:p><a:r><a:t>Strict Slides</a:t></a:r></a:p></p:sld>',
+        })
+        self.assertEqual(self.run_check(pptx, "--contains", "Strict Slides", "--count", "1")[0], 0)
+
+        xlsx = self.package("xlsx", {
+            "xl/workbook.xml": f'''<workbook xmlns="{STRICT_S}" xmlns:r="{STRICT_R}"><sheets>
+              <sheet name="First" sheetId="1" r:id="r1"/><sheet name="Second" sheetId="2" r:id="r2"/>
+            </sheets></workbook>''',
+            "xl/_rels/workbook.xml.rels": f'''<Relationships xmlns="{PKG}">
+              <Relationship Id="r1" Target="worksheets/sheet1.xml"/><Relationship Id="r2" Target="worksheets/sheet2.xml"/>
+            </Relationships>''',
+            "xl/worksheets/sheet1.xml": f'<worksheet xmlns="{STRICT_S}"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Strict Sheet</t></is></c></row></sheetData></worksheet>',
+            "xl/worksheets/sheet2.xml": f'<worksheet xmlns="{STRICT_S}"><sheetData/></worksheet>',
+        })
+        code, report = self.run_check(xlsx, "--contains", "Strict Sheet", "--count", "2")
+        self.assertEqual(code, 0)
+        self.assertEqual([sheet["name"] for sheet in report["summary"]["sheets"]], ["First", "Second"])
+
+    def test_xlsx_checks_only_cell_referenced_shared_strings(self):
+        parts = {
+            "xl/workbook.xml": f'<workbook xmlns="{S}" xmlns:r="{R}"><sheets><sheet name="Data" sheetId="1" r:id="r1"/></sheets></workbook>',
+            "xl/_rels/workbook.xml.rels": f'<Relationships xmlns="{PKG}"><Relationship Id="r1" Target="/xl/worksheets/sheet1.xml"/></Relationships>',
+            "xl/sharedStrings.xml": f'<sst xmlns="{S}"><si><t>Deleted value</t></si><si><r><t>实际</t></r><r><t>内容</t></r></si></sst>',
+            "xl/worksheets/sheet1.xml": f'<worksheet xmlns="{S}"><sheetData><row r="1"><c r="A1" t="s"><v>1</v></c><c r="B1" t="inlineStr"><is><t>Inline value</t></is></c></row></sheetData></worksheet>',
+        }
+        path = self.package("xlsx", parts)
+        self.assertEqual(self.run_check(path, "--contains", "实际内容", "--contains", "Inline value")[0], 0)
+        code, report = self.run_check(path, "--contains", "Deleted value")
+        self.assertEqual(code, 1)
+        self.assertEqual(report["checks"][-1]["status"], "fail")
+        for index in ["-1", "2", "invalid", ""]:
+            with self.subTest(index=index):
+                parts["xl/worksheets/sheet1.xml"] = f'<worksheet xmlns="{S}"><sheetData><row r="1"><c r="A1" t="s"><v>{index}</v></c></row></sheetData></worksheet>'
+                code, report = self.run_check(self.package("xlsx", parts))
+                self.assertEqual(code, 1)
+                self.assertEqual(report["checks"][0]["status"], "fail")
+                self.assertIn("xl/worksheets/sheet1.xml", report["checks"][0]["detail"])
+                self.assertIn("A1", report["checks"][0]["detail"])
+        parts["xl/_rels/workbook.xml.rels"] = f'<Relationships xmlns="{PKG}"/>'
+        code, report = self.run_check(self.package("xlsx", parts))
+        self.assertEqual(code, 1)
+        self.assertIn("xl/workbook.xml", report["checks"][0]["detail"])
+        self.assertIn("r1", report["checks"][0]["detail"])
+
+    def test_xlsx_empty_or_missing_string_values_remain_json_reports(self):
+        for cell_type, expected in [("s", 1), ("str", 0)]:
+            for value in ["<v/>", ""]:
+                with self.subTest(cell_type=cell_type, value=value):
+                    path = self.package("xlsx", {
+                        "xl/workbook.xml": f'<workbook xmlns="{S}" xmlns:r="{R}"><sheets><sheet name="Data" sheetId="1" r:id="r1"/></sheets></workbook>',
+                        "xl/_rels/workbook.xml.rels": f'<Relationships xmlns="{PKG}"><Relationship Id="r1" Target="worksheets/sheet1.xml"/></Relationships>',
+                        "xl/worksheets/sheet1.xml": f'<worksheet xmlns="{S}"><sheetData><row r="1"><c r="A1" t="{cell_type}">{value}</c></row></sheetData></worksheet>',
+                    })
+                    code, report = self.run_check(path)
+                    self.assertEqual(code, expected)
+                    self.assertEqual(report["verdict"], "fail" if expected else "pass")
+                    if cell_type == "s":
+                        self.assertIn("A1: invalid shared string index ''", report["checks"][0]["detail"])
+
+    def test_output_directory_failure_is_json_and_preserves_the_document(self):
+        path = self.package("docx", {"word/document.xml": f'<w:document xmlns:w="{W}"><w:body/></w:document>'})
+        before = path.read_bytes()
+        result = subprocess.run([sys.executable, str(CHECKER), str(path), "--out", str(self.root)], capture_output=True, text=True, timeout=10)
+        self.assertEqual(result.returncode, 1)
+        self.assertEqual(result.stderr, "")
+        report = json.loads(result.stdout)
+        self.assertEqual(report["verdict"], "fail")
+        self.assertEqual(report["checks"][-1]["id"], "output")
+        self.assertEqual(path.read_bytes(), before)
+
+    def test_encrypted_package_returns_json_failure(self):
+        path = Path(__file__).parent / "fixtures/encrypted.xlsx"
+        code, report = self.run_check(path)
+        self.assertEqual(code, 1)
+        self.assertIn("encrypted", report["checks"][0]["detail"])
+
+    def test_corrupt_deflate_member_returns_json_package_failure(self):
+        path = self.package("docx", {
+            "word/document.xml": f'<w:document xmlns:w="{W}"><w:body/></w:document>',
+        }, compression=zipfile.ZIP_DEFLATED)
+        with zipfile.ZipFile(path) as archive:
+            member = archive.getinfo("word/document.xml")
+        data = bytearray(path.read_bytes())
+        name_length = int.from_bytes(data[member.header_offset + 26:member.header_offset + 28], "little")
+        extra_length = int.from_bytes(data[member.header_offset + 28:member.header_offset + 30], "little")
+        compressed = member.header_offset + 30 + name_length + extra_length
+        data[compressed] = 0x07  # BTYPE=3 is reserved and invalid in a DEFLATE block.
+        path.write_bytes(data)
+        code, report = self.run_check(path)
+        self.assertEqual(code, 1)
+        self.assertEqual(report["checks"][0]["id"], "package")
+        self.assertEqual(report["checks"][0]["status"], "fail")
+        self.assertTrue(report["checks"][0]["detail"])
+
+    def test_invalid_zip_and_xml_fail_and_output_cannot_overwrite_input(self):
+        path = self.root / "broken.docx"
+        path.write_bytes(b"not an Office archive")
+        self.assertEqual(self.run_check(path)[0], 1)
+        path = self.package("docx", {"word/document.xml": "<broken>"})
+        self.assertEqual(self.run_check(path)[0], 1)
+        before = path.read_bytes()
+        result = subprocess.run([sys.executable, str(CHECKER), str(path), "--out", str(path)], capture_output=True, timeout=10)
+        self.assertEqual(result.returncode, 2)
+        self.assertEqual(path.read_bytes(), before)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 14 - 0
packages/skill/skill-office/tests/checkers.spec.ts

@@ -0,0 +1,14 @@
+import { spawnSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+import { expect, it } from 'vitest'
+
+it.each(['utf-8', 'cp1252'])('executes the shipped OOXML checker against valid, edited, and broken documents with %s stdout', (encoding) => {
+  const python = process.env.DSH_OFFICE_TEST_PYTHON ?? (process.platform === 'win32' ? 'python' : 'python3')
+  const result = spawnSync(python, [fileURLToPath(new URL('./check_office_test.py', import.meta.url))], {
+    env: { ...process.env, PYTHONIOENCODING: encoding },
+    encoding: 'utf8', timeout: 30_000,
+  })
+  expect(result.error).toBeUndefined()
+  expect(result.signal, result.stderr + result.stdout).toBeNull()
+  expect(result.status, result.stderr + result.stdout).toBe(0)
+})

BIN
packages/skill/skill-office/tests/fixtures/encrypted.xlsx


+ 124 - 0
packages/skill/skill-office/tests/skill-office.spec.ts

@@ -0,0 +1,124 @@
+import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { Context } from '@deepseek-ai/cordis'
+import Loader from '@deepseek-ai/cordis-plugin-loader'
+import Include from '@deepseek-ai/cordis-plugin-include'
+import SkillRegistry from '@deepseek-ai/dsh-skill'
+import * as SkillOffice from '@deepseek-ai/dsh-skill-office'
+import { describe, expect, it } from 'vitest'
+
+const assets = fileURLToPath(new URL('../assets/', import.meta.url))
+const names = ['office-docx', 'office-pptx', 'office-xlsx']
+
+describe('bundled Office skills', () => {
+  it('loads each packaged body and removes all candidates on disposal', async () => {
+    const ctx = new Context()
+    try {
+      await ctx.plugin(SkillRegistry)
+      const fiber = await ctx.plugin(SkillOffice)
+      const catalog = await ctx.skills.list()
+      expect(catalog.map(skill => skill.name)).toEqual(names)
+      for (const skill of catalog) {
+        expect(skill.description.length).toBeLessThanOrEqual(500)
+        expect(skill).toMatchObject({ source: 'bundled', provider: 'dsh-office', invocation: { modelInvocable: true, userInvocable: true } })
+        const loaded = await ctx.skills.get(skill.name)
+        expect(loaded?.resourceBase).toEqual({ kind: 'directory', path: join(assets, skill.name) })
+        const raw = await readFile(join(assets, skill.name, 'SKILL.md'), 'utf8')
+        expect(loaded?.content).toBe(raw.slice(raw.indexOf('\n---\n') + 5).trim())
+      }
+      await fiber.dispose()
+      expect(await ctx.skills.list()).toEqual([])
+    } finally {
+      await ctx.fiber.dispose()
+    }
+  })
+
+  it('loads relocated resources through a real cordis.yml composition', async () => {
+    const root = await mkdtemp(join(tmpdir(), 'dsh-office-skills-'))
+    const ctx = new Context()
+    try {
+      const external = join(root, '中文 assets')
+      await cp(assets, external, { recursive: true })
+      const configPath = join(root, 'cordis.yml')
+      await writeFile(configPath, [
+        "- name: '@deepseek-ai/dsh-skill'",
+        "- name: '@deepseek-ai/dsh-skill-office'",
+        '  config:',
+        `    assetRoot: ${JSON.stringify(external)}`,
+        '',
+      ].join('\n'))
+      ctx.baseUrl = pathToFileURL(root).href + '/'
+      await ctx.plugin(Loader)
+      ctx.loader.builtins.include = Include
+      const modules = new Map<string, unknown>([
+        ['@deepseek-ai/dsh-skill', SkillRegistry],
+        ['@deepseek-ai/dsh-skill-office', SkillOffice],
+      ])
+      ctx.loader.internal = {
+        version: 'v2',
+        async import(specifier: string) {
+          if (!modules.has(specifier)) throw new Error(`Unexpected Loader import: ${specifier}`)
+          return modules.get(specifier)
+        },
+      } as unknown as NonNullable<typeof ctx.loader.internal>
+      await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } })
+      await ctx.loader.await()
+      expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(names)
+      const loaded = await ctx.skills.get('office-xlsx')
+      expect(loaded?.resourceBase).toEqual({ kind: 'directory', path: join(external, 'office-xlsx') })
+      const raw = await readFile(join(external, 'office-xlsx', 'SKILL.md'), 'utf8')
+      expect(loaded?.content).toBe(raw.slice(raw.indexOf('\n---\n') + 5).trim())
+    } finally {
+      await ctx.fiber.dispose()
+      await rm(root, { recursive: true, force: true })
+    }
+  })
+
+  it.each([
+    ['description: "Quoted: description"', '\r\n', 'Quoted: description'],
+    ['description: >-\n  Folded\n  description', '\n', 'Folded description'],
+  ])('parses frontmatter %s and leaves body metadata-like lines intact', async (header, newline, description) => {
+    const root = await mkdtemp(join(tmpdir(), 'dsh-office-metadata-'))
+    const ctx = new Context()
+    try {
+      await cp(assets, root, { recursive: true })
+      const body = '# Office instructions\n\ndescription: instruction text'
+      await writeFile(join(root, 'office-docx', 'SKILL.md'), `---\n${header}\n---\n\n${body}\n`.replaceAll('\n', newline))
+      await ctx.plugin(SkillRegistry)
+      await ctx.plugin(SkillOffice, { assetRoot: root })
+      const skill = await ctx.skills.get('office-docx')
+      expect(skill?.description).toBe(description)
+      expect(skill?.content).toBe(body.replaceAll('\n', newline))
+    } finally {
+      await ctx.fiber.dispose()
+      await rm(root, { recursive: true, force: true })
+    }
+  })
+
+  it('rejects relative resource paths and incomplete asset trees before registration', async () => {
+    const root = await mkdtemp(join(tmpdir(), 'dsh-office-invalid-'))
+    const ctx = new Context()
+    try {
+      await ctx.plugin(SkillRegistry)
+      expect(() => { SkillOffice.apply(ctx, { assetRoot: 'assets' }) }).toThrow('absolute directory')
+      await cp(assets, root, { recursive: true })
+      await rm(join(root, 'scripts', 'check_office.py'))
+      await cp(join(assets, 'office-docx'), join(root, 'scripts', 'check_office.py'), { recursive: true })
+      expect(() => { SkillOffice.apply(ctx, { assetRoot: root }) }).toThrow('scripts/check_office.py')
+      await rm(join(root, 'scripts', 'check_office.py'), { recursive: true })
+      await cp(join(assets, 'scripts', 'check_office.py'), join(root, 'scripts', 'check_office.py'))
+      await writeFile(join(root, 'office-docx', 'SKILL.md'), '# Missing frontmatter\ndescription: body text\n')
+      expect(() => { SkillOffice.apply(ctx, { assetRoot: root }) }).toThrow('has no YAML frontmatter')
+      for (const header of ['', 'null', 'scalar', 'name: office-docx', 'description: 3', 'description: ""']) {
+        await writeFile(join(root, 'office-docx', 'SKILL.md'), `---\n${header}\n---\n# Instructions\n`)
+        expect(() => { SkillOffice.apply(ctx, { assetRoot: root }) }).toThrow('has no description')
+      }
+      expect(await ctx.skills.list()).toEqual([])
+    } finally {
+      await ctx.fiber.dispose()
+      await rm(root, { recursive: true, force: true })
+    }
+  })
+})

+ 24 - 0
packages/skill/skill-office/tsconfig.json

@@ -0,0 +1,24 @@
+{
+  "extends": "../../../tsconfig.base.json",
+  "compilerOptions": {
+    "rootDir": "src",
+    "outDir": "lib/types"
+  },
+  "include": [
+    "src"
+  ],
+  "references": [
+    {
+      "path": "../../../vendor/cosmokit"
+    },
+    {
+      "path": "../../../vendor/cordis"
+    },
+    {
+      "path": "../../../vendor/schemastery"
+    },
+    {
+      "path": "../skill"
+    }
+  ]
+}

+ 28 - 0
pnpm-lock.yaml

@@ -48,6 +48,9 @@ importers:
       '@deepseek-ai/dsh-llm-replay':
         specifier: workspace:^
         version: link:packages/test-support/llm-replay
+      '@deepseek-ai/dsh-skill-office':
+        specifier: workspace:^
+        version: link:packages/skill/skill-office
       '@deepseek-ai/dsh-tool-session-query':
         specifier: workspace:^
         version: link:packages/session-query/tool-session-query
@@ -608,6 +611,9 @@ importers:
       '@deepseek-ai/dsh-host-webserver':
         specifier: workspace:^
         version: link:../../packages/host/webserver
+      '@deepseek-ai/dsh-skill-office':
+        specifier: workspace:^
+        version: link:../../packages/skill/skill-office
       '@deepseek-ai/dsh-tools':
         specifier: workspace:^
         version: link:../../packages/core/tools
@@ -10006,6 +10012,28 @@ importers:
         specifier: workspace:^
         version: link:../skill
 
+  packages/skill/skill-office:
+    dependencies:
+      '@deepseek-ai/schemastery':
+        specifier: link:../../../vendor/schemastery
+        version: link:../../../vendor/schemastery
+      yaml:
+        specifier: ^2.4.2
+        version: 2.9.0
+    devDependencies:
+      '@deepseek-ai/cordis':
+        specifier: workspace:^
+        version: link:../../../vendor/cordis
+      '@deepseek-ai/cordis-plugin-include':
+        specifier: workspace:^
+        version: link:../../../vendor/include
+      '@deepseek-ai/cordis-plugin-loader':
+        specifier: workspace:^
+        version: link:../../../vendor/loader
+      '@deepseek-ai/dsh-skill':
+        specifier: workspace:^
+        version: link:../skill
+
   packages/skill/tool-skill:
     dependencies:
       '@deepseek-ai/schemastery':

+ 8 - 0
scripts/check-workspace-constraints.spec.ts

@@ -198,3 +198,11 @@ it('requires the shared Web injection entry in the published payload', () => {
     ...manifest, files: ['lib/index.js', 'lib/**/*.css', 'lib/types/**/*.d.ts'],
   } })).toEqual([expect.stringContaining('package.json files must be')])
 })
+
+it('requires Office skill bodies and helpers in the published payload', () => {
+  const manifest = JSON.parse(readFileSync(new URL('../packages/skill/skill-office/package.json', import.meta.url), 'utf8')) as WorkspaceManifest['manifest']
+  expect(checkWorkspaceManifest({ dir: 'packages/skill/skill-office', manifest })).toEqual([])
+  expect(checkWorkspaceManifest({ dir: 'packages/skill/skill-office', manifest: {
+    ...manifest, files: ['lib/index.js', 'lib/types/**/*.d.ts'],
+  } })).toEqual([expect.stringContaining('package.json files must be')])
+})

+ 1 - 0
scripts/check-workspace-constraints.ts

@@ -180,6 +180,7 @@ const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
   // also shares its generated FFI code through a hashed runtime chunk.
   '@deepseek-ai/dsh-sandbox-windows-acl': ['lib/runner.js', 'lib/types-*.js'],
   '@deepseek-ai/dsh-skill-badge': ['assets'],
+  '@deepseek-ai/dsh-skill-office': ['assets'],
   '@deepseek-ai/dsh-subprocess': ['lib/control.js'],
   // SSH launches a private helper and shares wire definitions and TLS setup
   // between that helper and the connection owner.

+ 1 - 1
scripts/gen-doc-graphs.ts

@@ -485,7 +485,7 @@ const SERVICE_ROLES: ServiceRole[] = [
     pkg: 'skill',
     title: 'Skill provider registry',
     mode: 'seam',
-    implementations: ['skill-badge', 'skill-filesystem'],
+    implementations: ['skill-badge', 'skill-filesystem', 'skill-office'],
     consumers: ['tool-skill'],
     note: 'Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies.',
   },

+ 1 - 0
scripts/verify-package-readme-model-experience.ts

@@ -175,6 +175,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
   'packages/identity/anonymous-user-id': { kind: 'none', reason: 'The shared identifier reaches DeepSeek only as model-hidden HTTP metadata; it registers nothing model-facing.' },
   'packages/skill/skill': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-skill.' },
   'packages/skill/skill-badge': { kind: 'indirect', reason: 'The bundled provider delegates model rendering to dsh-tool-skill.' },
+  'packages/skill/skill-office': { kind: 'indirect', reason: 'The bundled Office provider delegates model rendering to dsh-tool-skill.' },
   'packages/skill/skill-filesystem': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-skill.' },
   'packages/spill/spill': { kind: 'indirect', reason: 'The storage seam delegates model rendering to spill consumers.' },
   'packages/spill/spill-local': { kind: 'indirect', reason: 'The storage backend delegates model rendering to spill consumers.' },

+ 47 - 0
snapshots/session/deepseek-messages-invalid-tool-history/cordis.snapshot.yml

@@ -0,0 +1,47 @@
+# Replay patch shared by the ordinary headless snapshot composition. The model
+# script comes from the scenario's committed session JSONL.
+
+- id: llm-deepseek
+  name: '@deepseek-ai/dsh-llm-deepseek'
+  disabled: true
+
+- id: plugin-package-inventory-deepseek
+  disabled: true
+
+- id: session-title-llm
+  disabled: true
+
+- id: session-persistence-jsonl
+  name: '@deepseek-ai/dsh-session-persistence-jsonl'
+  config:
+    root: !!js dshHomePath('sessions')
+    compression: none
+
+- id: sandbox
+  name: '@deepseek-ai/dsh-sandbox-local'
+  config:
+    runnerCommand:
+      - bash
+      - -c
+      - while [ "$1" != "--" ]; do shift; done; shift; exec "$@"
+      - passthrough-runner
+    runnerFailureSignatures:
+      - 'passthrough-runner: profile rejected'
+
+- insert:
+    - id: llm-replay
+      name: '@deepseek-ai/dsh-llm-replay'
+      config:
+        providers:
+          - id: deepseek-official
+            name: DeepSeek
+            models:
+              - id: deepseek-v4-flash
+              - id: deepseek-v4-pro
+          - id: deepseek-messages
+            name: DeepSeek Messages
+            models:
+              - id: deepseek-v4-flash
+              - id: deepseek-v4-pro
+    - id: messages-history-snapshot
+      name: '../../../packages/llm/llm-deepseek/tests/messages/fixtures/history.ts'

+ 3 - 0
snapshots/session/deepseek-messages-invalid-tool-history/cordis.yml

@@ -0,0 +1,3 @@
+- insert:
+    - id: messages-history-snapshot
+      name: '../../../packages/llm/llm-deepseek/tests/messages/fixtures/history.ts'

+ 22 - 0
snapshots/session/deepseek-messages-invalid-tool-history/session.v3.jsonl

@@ -0,0 +1,22 @@
+{"type":"session","version":3,"id":"{{session:1}}","createdAt":1783352050748,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0}
+{"type":"permission/preset","data":{"preset":"danger-full-access"}}
+{"type":"sandbox/mode","data":{"mode":"danger-full-access"}}
+{"type":"approval/policy","data":{"policy":"never"}}
+{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use bash to print a quoted word. If the tool rejects the arguments, do not retry; reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}}
+{"type":"turn/start","data":{"turn":1}}
+{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
+{"type":"step/start","data":{"turn":1,"step":1}}
+{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"}
+{"type":"user/message","data":{"content":[{"type":"text","text":"Use bash to print a quoted word. If the tool rejects the arguments, do not retry; reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"}
+{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"}
+{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
+{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
+{"type":"session/title","data":{"title":"Use bash to print a","messageSeqs":[8],"source":{"kind":"fallback"}}}
+{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"I will ask bash to print a quoted word."},{"type":"tool-call","id":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","name":"bash","arguments":"{\"command\":\"echo \"QUOTED\"\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":2877,"outputTokens":90,"cacheReadTokens":0,"totalTokens":2967},"stream":[{"type":"chunk","time":1788882845159,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788882845159,"index":0,"dt":[],"texts":["I will ask bash to print a quoted word."]},{"type":"chunk","time":1788882845160,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788882845160,"index":1,"dt":[],"id":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","name":"bash","args":["{\"command\":\"echo \"QUOTED\"\"}"]},{"type":"chunk","time":1788882845160,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"I will ask bash to print a quoted word."}}},{"type":"chunk","time":1788882845160,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","name":"bash","arguments":"{\"command\":\"echo \"QUOTED\"\"}"}}},{"type":"chunk","time":1788882845160,"chunk":{"type":"usage","usage":{"inputTokens":2877,"outputTokens":90,"cacheReadTokens":0,"totalTokens":2967}}},{"type":"chunk","time":1788882845160,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
+{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","name":"bash","arguments":"{\"command\":\"echo \"QUOTED\"\"}"}}
+{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"call_00_fkbBRJsUrGKd1pWVc4Gn8233"},"content":[{"type":"tool-result","toolCallId":"call_00_fkbBRJsUrGKd1pWVc4Gn8233","content":[{"type":"text","text":"Error: invalid arguments: \"arguments\" must be an object"}],"isError":true}],"role":"user","id":"{{message:5}}"},"error":{"name":"ToolArgsError","code":"INVALID_ARGS"}},"sourceEventSeqs":[14],"surfaceOp":"append"}
+{"type":"step/end","data":{"turn":1,"step":1}}
+{"type":"step/start","data":{"turn":1,"step":2}}
+{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The tool rejected the malformed arguments. I can continue with the requested final reply."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":168,"outputTokens":25,"cacheReadTokens":2816,"totalTokens":3009},"stream":[{"type":"chunk","time":1788882845260,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788882845260,"index":0,"dt":[],"texts":["The tool rejected the malformed arguments. I can continue with the requested final reply."]},{"type":"chunk","time":1788882845260,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788882845260,"index":1,"dt":[0],"texts":["D","ONE"]},{"type":"chunk","time":1788882845260,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The tool rejected the malformed arguments. I can continue with the requested final reply."}}},{"type":"chunk","time":1788882845260,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1788882845260,"chunk":{"type":"usage","usage":{"inputTokens":168,"outputTokens":25,"cacheReadTokens":2816,"totalTokens":3009}}},{"type":"chunk","time":1788882845260,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
+{"type":"step/end","data":{"turn":1,"step":2}}
+{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}

+ 10 - 0
snapshots/session/deepseek-messages-invalid-tool-history/snapshot.yml

@@ -0,0 +1,10 @@
+version: 1
+scenario: deepseek-messages-invalid-tool-history
+profile: headless
+composition: deepseek-messages-invalid-tool-history
+recording: authored
+header:
+  class: deepseek-messages-invalid-tool-history
+  pin: true
+  systemPromptSource: text-turn
+  toolSchemasSource: text-turn

+ 3 - 0
snapshots/session/headless.snapshot.ts

@@ -459,6 +459,9 @@ async function seedWorkspace(scenario: HeadlessScenario, cwd: string): Promise<v
 }
 
 const workspaceSetups: Record<string, (cwd: string) => Promise<void>> = {
+  async 'office-skills'(cwd) {
+    await cp(join(repoRoot, 'packages/skill/skill-office/assets'), join(cwd, 'office-skills'), { recursive: true })
+  },
   async 'editing-cordis-skill'(cwd) {
     const target = join(cwd, '.dsh', 'skills', 'editing-cordis-compositions', 'SKILL.md')
     await mkdir(dirname(target), { recursive: true })

+ 22 - 0
snapshots/session/office-skills-no-renderer/cordis.snapshot.yml

@@ -0,0 +1,22 @@
+- id: llm-deepseek
+  disabled: true
+
+- insert:
+    - id: llm-replay
+      name: '@deepseek-ai/dsh-llm-replay'
+      config:
+        providers:
+          - id: deepseek-official
+            name: DeepSeek
+            models:
+              - id: deepseek-v4-flash
+                contextWindow: 1000000
+                defaultMaxTokens: 8192
+                reasoningEfforts: [off, low, high, max]
+                defaultReasoningEffort: high
+
+- insert:
+    - id: office-skills
+      name: '@deepseek-ai/dsh-skill-office'
+      config:
+        assetRoot: !!js process.cwd() + '/office-skills'

+ 14 - 0
snapshots/session/office-skills-no-renderer/cordis.yml

@@ -0,0 +1,14 @@
+- insert:
+    - id: office-skills
+      name: '@deepseek-ai/dsh-skill-office'
+      config:
+        assetRoot: !!js process.cwd() + '/office-skills'
+
+- id: llm-deepseek
+  config:
+    protocol: chat-completions
+    thinking: enabled
+    reasoningEffort: high
+    maxTokens: 8192
+    models:
+      - id: deepseek-v4-flash

Plik diff jest za duży
+ 11 - 0
snapshots/session/office-skills-no-renderer/session.v3.jsonl


+ 12 - 0
snapshots/session/office-skills-no-renderer/snapshot.yml

@@ -0,0 +1,12 @@
+version: 1
+scenario: office-skills-no-renderer
+profile: headless
+composition: office-skills-no-renderer
+recording: live
+header:
+  class: office-skills-no-renderer
+  pin: true
+  systemPromptSource: text-turn
+  toolSchemasSource: text-turn
+workspace:
+  setup: office-skills

+ 1 - 0
snapshots/session/office-skills-no-renderer/system-prompt.expected.md

@@ -0,0 +1 @@
+../text-turn/system-prompt.expected.md

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików