Skip to content

feat(resume): experimental OSC 7577 program resume protocol - #9

Open
pi0x wants to merge 1 commit into
mainfrom
feat/osc-resume
Open

pi0x wants to merge 1 commit into
mainfrom
feat/osc-resume

Conversation

@pi0x

@pi0x pi0x commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Bring programs back after your terminal host restarts

If you build a terminal host on zigpty (an Electron/Tauri terminal, a web terminal, an agent dashboard), a restart normally drops every pane back to an empty shell. The user's editor session, git TUI, or agent conversation is gone.

This PR adds experimental support for the Program Resume Protocol (OSC 7577). With it, a program running in a pane can tell the host how to resume itself, e.g. nvim -S ~/.local/state/nvim/sessions/8f2c1d.vim or myagent --resume <session-id>. The host can then run that command when it starts again. The report is signed with a random per-pane token. Text that is just printed to the pane (cat-ed files, logs, output from ssh sessions) doesn't have the token, so it can't register a command.

Host side — zigpty/resume

import { spawn } from "zigpty";
import { ResumeTracker } from "zigpty/resume";

const resume = new ResumeTracker(); // one per pane, with a fresh random token
const pty = spawn(process.env.SHELL!, [], {
  env: { ...process.env, ...resume.env } as Record<string, string>, // sets OSC7577_TOKEN
});
pty.attach(resume); // ResumeTracker is an IPtyConsumer

// Save every change. A record is { pid, argv, cwd?, time }.
resume.onChange((record) => {
  if (record) savePane(paneId, record);
  else deletePane(paneId);
});

// The user closed the pane on purpose, so forget it. Don't call this when the host quits.
onPaneClosedByUser(() => resume.clear());

On the next start, read the saved record back. If you decide to restore it, spawn the user's shell in record.cwd and run record.argv there. Pass each element as a separate argument and never build a shell string from it. Use a new ResumeTracker for the restored pane, because tokens must not be reused. The resumed program is expected to report again.

const saved = loadPane(paneId); // whatever you persisted
const resume = new ResumeTracker();
const pty = spawn(process.env.SHELL!, [], {
  cwd: saved?.cwd,
  env: { ...process.env, ...resume.env } as Record<string, string>,
});
pty.attach(resume);
if (saved) {
  // Your own restore strategy, e.g. hand saved.argv to the shell as data at its first prompt.
}

Program side — formatResumeReport

This is for CLIs and TUIs that want to be resumable in any terminal that supports OSC 7577:

import { formatResumeReport } from "zigpty/resume";

const token = process.env.OSC7577_TOKEN;
if (token) {
  process.stdout.write(
    formatResumeReport({ pid: process.pid, argv: ["myagent", "--resume", sessionId] }, token),
  );
  // Later, when the user quits on purpose:
  process.stdout.write(formatResumeReport({ pid: process.pid, clear: true }, token));
}

It throws if the command can't be reported, for example a relative program path, control characters, or both argv and clear.

Decoder — zigpty/osc

decodeOSC() now decodes OSC 7577 into { kind: "resume", valid, pid, time, argv?, cwd?, clear, need?, mac, signed }. signed is the exact text the mac covers. A malformed report still decodes as kind: "resume" with valid: false and an error, and keeps whatever mac/pid/time could be parsed. The decoder has no token, so a decoded report is not proof of anything. Use verifyResumeReport(report, token) to get accepted / ignored / rejected.

What zigpty handles vs. what your app handles

zigpty Your app
Generates a per-pane token from a CSPRNG and gives you resume.env Gives resume.env only to the pane's first process, with one tracker per pane
Parses reports from the PTY stream, including reports split across chunks, ended by ESC \ or BEL Saves records from onChange somewhere only the user can read
Checks the mac with a constant-time compare, the time window (60s by default), and that time never goes backwards for a pid Decides whether to restore: opt-in, allow-lists, confirmation
Parses the body strictly. Bad reports are either ignored or rejected, and a rejected report removes that owner's record Does the restore itself: shell environment, cwd, running argv without shell-quoting
Optional owner check: the reported pid must be the PTY's process or one of its descendants (uses pty.stats()) Calls clear() when the user closes the pane on purpose

zigpty does not save records, restore or exec programs, integrate with shells, or clear a record when its owner process exits. The last one is deliberate: when the host shuts down, the PTY exits too, and that is exactly when the record is needed.

⚠️ Experimental

This follows spec rev 0.5 (2026-11-25), which is new and may change. The zigpty/resume API and the resume decoded shape may change with it in a future release.

Verification

  • New tests cover every valid example in the spec (their published hashes) and every row of its "Invalid reports" table with the expected ignored or rejected outcome. They also cover other strict-grammar failures, reports split across chunks, both terminators, replayed and older reports, expired times, a wrong token, clear, the owner check, a report at the spec's minimum limits (64 argv elements, 2048 bytes) and one too long to parse. formatResumeReport reproduces the spec examples byte-for-byte.
  • bun run test (zig build test + vitest) passes on Linux: 211 passed, 2 skipped. bun run fmt:check and bun run build are clean, and tsc reports no errors in src/.
  • Manual check with a real native PTY: a plain sh script using base64 and sha256sum (the spec's wrapper example, not zigpty code) reported its resume command, and ResumeTracker accepted it.

🤖 Generated with AI assistant

Add a stateless OSC 7577 decoder (kind: "resume") to zigpty/osc and a new zigpty/resume subpath with ResumeTracker (IPtyConsumer), verifyResumeReport, formatResumeReport and createResumeToken. Implements spec rev 0.5: SHA-256 mac with constant-time compare, time window + per-pid monotonic time, strict grammar, and ignored vs rejected semantics.
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