Skip to content

feat(cli,tui): report session resume command via OSC 7577 - #5571

Merged
Grapedge merged 5 commits into
mainfrom
osc7577
Nov 27, 2026
Merged

Grapedge merged 5 commits into
mainfrom
osc7577

Conversation

@Grapedge

Copy link
Copy Markdown
Collaborator

Requirement or Bug

用户在支持 OSC 7577(Program Resume Protocol,程序恢复协议)的终端里重启终端或系统后,原先运行 Kimi Code 的面板会落回普通 shell,需要手动查找并重输恢复命令。本 PR 同步 @moonshot-ai/pi-tui 上游的 OSC 7577 编码工具,并在交互式 TUI 中上报带 SHA-256 签名的恢复命令 kimi -r <sessionId> 与工作目录 cwd。支持该协议的终端重开面板时会自动回到原会话与目录,用户主动退出或会话清空时则会清除记录。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路

终端通过环境变量 OSC7577_TOKEN 为每个面板注入独立密钥。CLI 在跨过原生安装包热更新重拉起之后,立即取走并从 process.env 中删除该令牌,只通过内存参数传给交互式 TUI,隔离所有子进程与非交互子命令。TUI 新增 ProgramResumeController 状态机,仅当会话同时具备 sessionId 和有效对话记录时向终端写出签名的 kimi -r <sessionId> 与本机 workDir,并在主动退出或会话变空时写出 clear=1。未设置 OSC7577_TOKEN 的终端与无界面模式不产生任何额外输出。

结构图

flowchart LR
    Term["终端 (注入 OSC7577_TOKEN)"] --> Swap["原生热更新检查 (native-swap)"]
    Swap -- "重拉起保留令牌,冒烟子进程剥离" --> Main["CLI 入口 (cli/main)"]
    Main -- "takeProgramResumeToken 删除环境变量" --> Shell["交互宿主 (run-shell 与 KimiTUI)"]
    Main -. "无令牌环境" .-> Sub["非交互命令与全部子进程"]
    Shell --> Ctrl["恢复状态机 (ProgramResumeController)"]
    Ctrl -- "签名上报 kimi -r <id> 或 clear=1" --> PiTui["协议编码器 (@moonshot-ai/pi-tui)"]
    PiTui --> Term
Loading

因为 OSC7577_TOKEN 代表向当前终端面板注册启动命令的权限,所以 CLI 在解析子命令之前就从 process.env 剥离令牌,而不是留到 TUI 启动后再清理。这样后续派生的 shell 工具、! 命令、外部编辑器和 MCP 子进程都无法伪造恢复序列覆盖当前会话。

关键决策

决策 选择 没选 理由
令牌剥离时机 在 maybeRelaunchWithStagedNativeUpdate 之后、bootstrap() 首行剥离 process.env.OSC7577_TOKEN,热更新 --version 冒烟检查在子进程环境副本中单独剥离 在 main() 首行剥离,或留到 KimiTUI 构造时剥离 热更新 reexec 需要把原令牌传给替换后的新二进制,而冒烟子进程与后续子进程都不应拿到令牌
多步异步切换防抖 ProgramResumeController 提供可重入词法锁 hold() 与 runHeld(),包裹启动、新建、恢复、切换、重载与删除会话流程 每次字段写入立即向终端输出 会话切换跨多个 await 分步修改 workDir、sessionId 和 transcriptEntries,加锁后只在最终状态收敛时发送一次序列,避免泄露中间状态或产生 clear=1 闪烁
退出清除策略 主动退出(/exit、Ctrl+C、Ctrl+D、/web、/remote-control 及关停期二次 Ctrl+C)发 clear=1;SIGTERM、SIGHUP 与终端断连调用 preserveForSignal() 保留上报 所有退出路径统一在 stop() 里发 clear=1 终端或系统关闭常通过 SIGTERM 或 SIGHUP 结束前台进程,若此时发送 clear=1 会擦除终端刚保存的恢复记录
空会话与 /undo 判定 用 hasResumableTranscriptContent 过滤空会话 /undo 提示条目 undo-limit-status,且从未上报过时退出不发 clear=1 只要 transcriptEntries 非空就上报,退出时无条件发 clear=1 在空白会话执行 /undo 只会产生提示文本,不应触发恢复上报;从未上报过却发 clear=1 还会误删同面板挂起程序留下的恢复记录

阅读指南

  1. packages/pi-tui/src/program-resume.ts 定义 OSC 7577 序列格式、参数数量与总字节上限(最多 64 个参数、总长 2048 字节、绝对路径 cwd)以及 SHA-256 mac 计算。
  2. apps/kimi-code/src/tui/controllers/program-resume.ts 实现 disabled | active | preserved | cleared 状态机、(sessionId, cwd) 去重、hold() 合并与信号保留逻辑。
  3. apps/kimi-code/src/main.ts、apps/kimi-code/src/cli/main.ts 与 apps/kimi-code/src/cli/update/native-swap.ts 划定 OSC7577_TOKEN 在快速入口、热更新、冒烟检查与交互入口之间的隔离边界。
  4. apps/kimi-code/src/tui/kimi-tui.ts 与 apps/kimi-code/src/tui/commands/undo.ts 负责会话生命周期、外部编辑器返回重报、信号处理与 /undo 清空时的接线。

其余参数透传(run-shell.ts、dispatch.ts)、tsconfig.json 的 ES2024 库声明、changeset 与测试夹具可略读。

状态迁移大纲

flowchart LR
    Start(("构造")) -- "无令牌" --> Disabled["disabled (静默)"]
    Start -- "非空 OSC7577_TOKEN" --> Active["active (同步恢复序列与 clear=1)"]
    Active -- "SIGTERM / SIGHUP / 启动异常" --> Preserved["preserved (冻结已上报记录)"]
    Active -- "主动退出 clearForExit()" --> Cleared["cleared (按需发送单次 clear=1)"]
    Preserved -- "二次 Ctrl+C clearForExit(force)" --> Cleared
Loading

状态机把“静默”“正常同步”“信号冻结”和“已清除”拆成互斥分支。正常退出最多发送一次 clear=1,信号关停期间即使后续清理逻辑清空界面也不会覆盖终端已保存的恢复命令。

Behavior Changes and Affected Users

行为 改动前 改动后 依赖旧行为的人群 退路
设置 OSC7577_TOKEN 时的交互式 TUI 终端输出 忽略 OSC7577_TOKEN,不输出 OSC 7577 序列 会话产生有效内容或恢复历史后向终端输出 OSC 7577 恢复序列(kimi -r <sessionId> 与 workDir),会话清空或用户主动退出时输出 clear=1,SIGTERM 和 SIGHUP 退出时保留记录 在注入 OSC7577_TOKEN 的终端中使用 kimi 交互式 TUI 的用户 启动前取消设置或清空环境变量 OSC7577_TOKEN
子进程与非交互入口中的 process.env.OSC7577_TOKEN 原样保留在 process.env 中并继承给子进程 原生热更新 reexec 保留该变量;热更新 --version 冒烟子进程及 bootstrap() 之后的所有入口(TUI 的 ! 命令、Bash 工具、外部编辑器、MCP stdio 子进程、kimi -p print 模式及其他 CLI 子命令)均从环境中剥离 OSC7577_TOKEN 在 kimi 内部通过 !、Bash 工具或插件子进程直接读取顶层终端 OSC7577_TOKEN 的脚本 无(按 OSC 7577 协议要求,宿主程序取走令牌后必须从环境移除,防止子进程冒用)
空白会话执行 /undo 后的 KimiTUI.hasSessionContent() 追加 Nothing to undo. 状态条目后返回 true 过滤 undo-limit-status 提示条目后仍返回 false,退出时不打印无内容的 kimi -r <sessionId> 提示 在新建空白会话中运行 /undo 后直接退出 TUI 的交互用户 无(空白会话无对话历史可恢复)

受影响模块与测试覆盖

  • @moonshot-ai/pi-tui(packages/pi-tui/src/program-resume.ts)新增 formatProgramResume、formatProgramResumeClear 与 takeProgramResumeToken,由 packages/pi-tui/test/program-resume.test.ts 覆盖协议测试向量、SHA-256 签名与不可携带输入的回退。
  • @moonshot-ai/kimi-code CLI 入口与热更新(apps/kimi-code/src/main.ts、src/cli/main.ts、src/cli/run-shell.ts、src/cli/update/native-swap.ts)负责令牌剥离、热更新重拉起保留与交互宿主透传,由 apps/kimi-code/test/cli/main.test.ts、exec-server.test.ts、run-shell.test.ts 与 update/native-swap.test.ts 覆盖。
  • @moonshot-ai/kimi-code TUI 控制器与会话接线(apps/kimi-code/src/tui/controllers/program-resume.ts、kimi-tui.ts、commands/undo.ts)负责会话上报、防抖合并、外部编辑器返回重报、/undo 清空清除与信号保留,由 apps/kimi-code/test/tui/controllers/program-resume.test.ts、kimi-tui-startup.test.ts、signal-handlers.test.ts 与 commands/undo.test.ts 覆盖。

验证结论

macOS 环境下已通过单元测试、TUI 集成测试与真实 POSIX PTY 双阶段端到端演练,覆盖无会话启动静默、子进程环境隔离、首轮发言签名上报、kimi -r 恢复历史回放、SIGTERM 保留记录以及 /exit 清除记录。Windows 下的信号与路径校验已由单测覆盖,未在真实 Windows 终端模拟器上实机验证。

执行的验证命令与结果
  • pnpm --filter @moonshot-ai/pi-tui test 通过(1257 个通过,1 个既有跳过)。
  • pnpm --filter @moonshot-ai/pi-tui run typecheck 通过。
  • pnpm exec tsc -p apps/kimi-code/tsconfig.json --noEmit 通过。
  • pnpm exec vitest run --reporter=agent apps/kimi-code/test/tui/controllers/program-resume.test.ts apps/kimi-code/test/tui/commands/undo.test.ts apps/kimi-code/test/cli/main.test.ts apps/kimi-code/test/cli/run-shell.test.ts apps/kimi-code/test/cli/exec-server.test.ts apps/kimi-code/test/cli/update/native-swap.test.ts apps/kimi-code/test/tui/signal-handlers.test.ts apps/kimi-code/test/tui/kimi-tui-startup.test.ts 通过。
  • pnpm lint 通过。
  • pnpm run check:duplication <base-sha> 通过。
  • POSIX PTY 双阶段端到端测试(pty.openpty() 加本地假 OpenAI SSE 服务)通过。阶段一验证无会话启动 0 条 OSC 7577、! 子进程 OSC7577_TOKEN 为空、首轮对话后发出 1 条合法 SHA-256 签名的 ['kimi', '-r', sessionId] 与 cwd、/exit 发出 clear=1。阶段二验证 kimi -r <sessionId> 恢复历史后立即上报、SIGTERM 退出不发 clear=1。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c336848

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@moonshot-ai/kimi-code Minor
@moonshot-ai/pi-tui Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T16:41:23.770316Z c336848 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Grapedge

Copy link
Copy Markdown
Collaborator Author

@codex review

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@c336848
npx https://pkg.pr.new/@moonshot-ai/kimi-code@c336848

commit: c336848

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 92200f7ff8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/pi-tui/src/program-resume.ts Resolved
Comment thread apps/kimi-code/src/tui/kimi-tui.ts Resolved
@Grapedge

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c336848f6f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@Grapedge
Grapedge merged commit 9f18936 into main Nov 27, 2026
21 checks passed
@Grapedge
Grapedge deleted the osc7577 branch November 27, 2026 06:14
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Dec 2, 2026
`bun scripts/upstream-ledger.mjs --refresh` at upstream/main 4eb2919
added 126 rows, so every open upstream commit and every PR it references
now has a ledger row: 0/596, down from 125 at 8bf8ba3 and 126 at the
fetched tip. The refresh only reads `upstream/main ^ main`, so the three
release-2.6.2 commits named by the mission (MoonshotAI#4875/MoonshotAI#4905/MoonshotAI#4922) gained
rows with the refresh's row shape.

Settled with live probes in this tree:

- ported: MoonshotAI#5533 (docs 2.8.1 changelog), MoonshotAI#4875 (registry search_url and
  feedback_url plus the feedback service), MoonshotAI#4905 (Kimi upload status
  validation in packages/core), MoonshotAI#4922 (swarm task events in
  sessionTaskFeed), MoonshotAI#5438 (unload only declared dynamic tools), MoonshotAI#5592
  (dynamic tool replacement order), MoonshotAI#5595 (append-log known length),
  MoonshotAI#5573 (skill roots for every work dir), MoonshotAI#5576 (date reminder cwd
  comparison), MoonshotAI#5618 (session titles for skill openers), MoonshotAI#5638 (frozen
  loop tool baseline), MoonshotAI#5626 (legacy turn-input origins)
- partial: MoonshotAI#5505 (processLiveness source and consumers present; the
  upstream unit test file was never carried), MoonshotAI#5571 (program-resume and
  OSC 7577 present; the upstream test helper was never carried), MoonshotAI#5532
  (gitService half present; fsService still leaks the environment lease
  at fsService.ts:1133 and :1267), MoonshotAI#5557 (app-client icon registry kept;
  the move to app-ui was never carried)
- not-applicable: MoonshotAI#4655 (upstream reverted auto review in MoonshotAI#5649), MoonshotAI#5333
  (PLAYBOOK:111 deliberate flat experimental flags)

M39's "likely present" list was checked, not trusted: MoonshotAI#5438 is present
(upstream test passes), MoonshotAI#5487 is not (nativeStartSettleMs/leg.nativeSettled
absent), MoonshotAI#5635 is not (ToolsSettled absent), MoonshotAI#5429 needs a visual probe.
The remaining 194 pending rows stay open with their reasons; no feature
was ported and no upstream-drift allowlist entry was added.

Verification: verify -> 332 closed rows, 332 carry every file of their
PR; 317 probes pass, 2 foreign-runner skips, 0 fail; a second verify is
byte-identical (ledger sha256 cbf53638...). Probe tests 29 pass; bun run
lint and node scripts/checks/ratchet.mjs green.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants