osc7577 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
osc7577/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """Program Resume Protocol (OSC 7577) for Python: tell the terminal how to bring your program back."""
2
+
3
+ from osc7577.encode import TOKEN_ENV, ReportError, build_body, compute_mac, encode
4
+ from osc7577.paths import is_absolute, is_bare_command
5
+ from osc7577.terminal import clear, report, scrub_env, supported
6
+ from osc7577.verify import Ignored, Rejected, Report, verify
7
+
8
+ __all__ = [
9
+ "TOKEN_ENV", "ReportError", "build_body", "compute_mac", "encode",
10
+ "is_absolute", "is_bare_command",
11
+ "clear", "report", "scrub_env", "supported",
12
+ "Ignored", "Rejected", "Report", "verify",
13
+ ]
14
+ __version__ = "1.0.0"
osc7577/__main__.py ADDED
@@ -0,0 +1,55 @@
1
+ """CLI: osc7577 report|clear|wrap|claude-hook."""
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+
7
+ from osc7577.encode import ReportError
8
+ from osc7577.terminal import clear, report, scrub_env
9
+
10
+
11
+ def main(argv: list[str] | None = None) -> int:
12
+ parser = argparse.ArgumentParser(prog="osc7577", description="Program Resume Protocol (OSC 7577) helper")
13
+ sub = parser.add_subparsers(dest="cmd", required=True)
14
+ rep = sub.add_parser("report", help="report a resume command")
15
+ rep.add_argument("--pid", type=int, default=None, help="owning pid (default: the parent shell)")
16
+ rep.add_argument("--cwd", default=None)
17
+ rep.add_argument("command", nargs=argparse.REMAINDER)
18
+ clr = sub.add_parser("clear", help="remove the record")
19
+ clr.add_argument("--pid", type=int, default=None)
20
+ wrap = sub.add_parser("wrap", help="report 'osc7577 wrap CMD...' then exec CMD without the token")
21
+ wrap.add_argument("command", nargs=argparse.REMAINDER)
22
+ sub.add_parser("claude-hook", help="Claude Code SessionStart/SessionEnd hook (reads JSON on stdin)")
23
+ args = parser.parse_args(argv)
24
+
25
+ if args.cmd == "claude-hook":
26
+ from osc7577.claude_hook import main as hook_main
27
+ return hook_main()
28
+
29
+ command = [a for a in getattr(args, "command", [])]
30
+ if command and command[0] == "--":
31
+ command = command[1:]
32
+ try:
33
+ if args.cmd == "report":
34
+ if not command:
35
+ parser.error("report needs a command after --")
36
+ ok = report(command, cwd=args.cwd or os.getcwd(), pid=args.pid or os.getppid())
37
+ return 0 if ok else 3
38
+ if args.cmd == "clear":
39
+ return 0 if clear(pid=args.pid or os.getppid()) else 3
40
+ if args.cmd == "wrap":
41
+ if not command:
42
+ parser.error("wrap needs a command after --")
43
+ try:
44
+ report(["osc7577", "wrap", *command], cwd=os.getcwd(), pid=os.getpid())
45
+ except ReportError as exc:
46
+ print(f"osc7577: not reported: {exc}", file=sys.stderr)
47
+ os.execvpe(command[0], command, scrub_env())
48
+ except ReportError as exc:
49
+ print(f"osc7577: {exc}", file=sys.stderr)
50
+ return 2
51
+ return 0
52
+
53
+
54
+ if __name__ == "__main__":
55
+ sys.exit(main())
osc7577/claude_hook.py ADDED
@@ -0,0 +1,93 @@
1
+ """Claude Code SessionStart / SessionEnd hook that reports OSC 7577 for the session.
2
+
3
+ Hook output is captured by Claude Code, so the report is written straight to the
4
+ tty of the claude process, and the record is owned by the claude pid.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import subprocess
10
+ import sys
11
+ from collections.abc import Callable, Mapping
12
+ from typing import IO
13
+
14
+ from osc7577.encode import ReportError
15
+ from osc7577.terminal import clear, report
16
+
17
+ # SessionEnd reasons that mean the user quit on purpose.
18
+ QUIT_REASONS = frozenset({"prompt_input_exit", "logout", "exit"})
19
+
20
+
21
+ def _ps(pid: int) -> tuple[int, str, str] | None:
22
+ try:
23
+ out = subprocess.run(
24
+ ["ps", "-o", "ppid=,tty=,comm=", "-p", str(pid)],
25
+ capture_output=True, text=True, timeout=2, check=False,
26
+ ).stdout.strip()
27
+ except (OSError, subprocess.SubprocessError):
28
+ return None
29
+ parts = out.split(None, 2)
30
+ if len(parts) < 3:
31
+ return None
32
+ return int(parts[0]), parts[1], parts[2]
33
+
34
+
35
+ def find_claude(start: int, ps: Callable[[int], tuple[int, str, str] | None] = _ps) -> tuple[int, str | None]:
36
+ """Walk up from the hook's parent to the claude process; return (pid, tty path)."""
37
+ pid, first = start, None
38
+ for _ in range(8):
39
+ info = ps(pid)
40
+ if info is None:
41
+ break
42
+ ppid, tty, comm = info
43
+ if first is None:
44
+ first = (pid, tty)
45
+ name = os.path.basename(comm)
46
+ if name in ("claude", "node", "bun") or "claude" in name:
47
+ return pid, (None if tty in ("?", "??", "") else "/dev/" + tty)
48
+ if ppid <= 1:
49
+ break
50
+ pid = ppid
51
+ if first is None:
52
+ return start, None
53
+ return first[0], (None if first[1] in ("?", "??", "") else "/dev/" + first[1])
54
+
55
+
56
+ def handle(
57
+ event: Mapping[str, object],
58
+ *,
59
+ env: Mapping[str, str] | None = None,
60
+ parent: int | None = None,
61
+ ps: Callable[[int], tuple[int, str, str] | None] = _ps,
62
+ stream: IO[str] | None = None,
63
+ ) -> str:
64
+ """Return what was done: 'report', 'clear', 'skip' or 'unsupported'."""
65
+ pid, tty = find_claude(os.getppid() if parent is None else parent, ps)
66
+ name = event.get("hook_event_name")
67
+ session = event.get("session_id")
68
+ if name == "SessionStart" and isinstance(session, str) and session:
69
+ cwd = event.get("cwd")
70
+ try:
71
+ sent = report(
72
+ ["claude", "--resume", session],
73
+ cwd=cwd if isinstance(cwd, str) and cwd.startswith("/") else None,
74
+ pid=pid, stream=stream, tty_path=tty, env=env,
75
+ )
76
+ except ReportError:
77
+ return "clear"
78
+ return "report" if sent else "unsupported"
79
+ if name == "SessionEnd":
80
+ if event.get("reason") in QUIT_REASONS:
81
+ return "clear" if clear(pid=pid, stream=stream, tty_path=tty, env=env) else "unsupported"
82
+ return "skip"
83
+ return "skip"
84
+
85
+
86
+ def main(stdin: IO[str] | None = None) -> int:
87
+ try:
88
+ event = json.load(stdin or sys.stdin)
89
+ except (ValueError, OSError):
90
+ return 0
91
+ if isinstance(event, dict):
92
+ handle(event)
93
+ return 0 # never block Claude Code
osc7577/encode.py ADDED
@@ -0,0 +1,115 @@
1
+ """Build OSC 7577 (Program Resume Protocol, rev 0.6) report bodies and sequences."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import os
6
+ import re
7
+ import time as _time
8
+ from collections.abc import Sequence
9
+
10
+ from osc7577.paths import is_absolute, is_bare_command
11
+
12
+ TOKEN_ENV = "OSC7577_TOKEN"
13
+ MIN_TOTAL_LIMIT = 2048
14
+ MIN_ARGV_LIMIT = 64
15
+
16
+ _TOKEN_RE = re.compile(r"[A-Za-z0-9_-]{22,64}")
17
+ _CONTROL_RE = re.compile("[\x00-\x1f\x7f-\x9f]")
18
+
19
+
20
+ class ReportError(ValueError):
21
+ """The command or directory cannot be reported under the spec."""
22
+
23
+
24
+ def check_token(token: str) -> str:
25
+ if not isinstance(token, str) or not _TOKEN_RE.fullmatch(token):
26
+ raise ReportError("token must be 22 to 64 characters of [A-Za-z0-9_-]")
27
+ return token
28
+
29
+
30
+ def _b64(text: str) -> str:
31
+ if _CONTROL_RE.search(text):
32
+ raise ReportError(f"control character in {text!r}; send clear() instead")
33
+ return base64.b64encode(text.encode("utf-8")).decode("ascii")
34
+
35
+
36
+ def check_argv(argv: Sequence[str], *, windows: bool | None = None) -> list[str]:
37
+ items = list(argv)
38
+ if not items:
39
+ raise ReportError("argv needs at least one element")
40
+ if any(not isinstance(a, str) for a in items):
41
+ raise ReportError("argv elements must be str")
42
+ first = items[0]
43
+ if first == "":
44
+ raise ReportError("the first argv element cannot be empty")
45
+ if not is_bare_command(first, windows) and not is_absolute(first, windows):
46
+ raise ReportError(f"{first!r} is a relative path; use a bare command name or an absolute path")
47
+ if first.startswith("-"):
48
+ raise ReportError(f"a bare command name cannot start with '-': {first!r}")
49
+ return items
50
+
51
+
52
+ def check_cwd(cwd: str, *, windows: bool | None = None) -> str:
53
+ if not is_absolute(cwd, windows):
54
+ raise ReportError(f"cwd must be an absolute path: {cwd!r}")
55
+ return cwd
56
+
57
+
58
+ def compute_mac(body: str, token: str) -> str:
59
+ """SHA-256 of body + ':' + token, as the spec defines (not an HMAC)."""
60
+ return hashlib.sha256(f"{body}:{token}".encode("utf-8")).hexdigest()
61
+
62
+
63
+ def build_body(
64
+ *,
65
+ pid: int | None = None,
66
+ argv: Sequence[str] | None = None,
67
+ cwd: str | None = None,
68
+ clear: bool = False,
69
+ time: int | None = None,
70
+ windows: bool | None = None,
71
+ ) -> str:
72
+ """Return the body without the final ':mac=' pair."""
73
+ if clear == (argv is not None):
74
+ raise ReportError("a report has exactly one of argv and clear")
75
+ pid = os.getpid() if pid is None else int(pid)
76
+ if pid < 1:
77
+ raise ReportError("pid must be a positive integer")
78
+ when = int(_time.time()) if time is None else int(time)
79
+ if when < 1:
80
+ raise ReportError("time must be a positive integer")
81
+ pairs = [f"pid={pid}", f"time={when}"]
82
+ if clear:
83
+ pairs.append("clear=1")
84
+ else:
85
+ assert argv is not None
86
+ pairs.append("argv=" + ",".join(_b64(a) for a in check_argv(argv, windows=windows)))
87
+ if cwd is not None:
88
+ pairs.append("cwd=" + _b64(check_cwd(cwd, windows=windows)))
89
+ return ":".join(pairs)
90
+
91
+
92
+ def encode(
93
+ *,
94
+ token: str,
95
+ pid: int | None = None,
96
+ argv: Sequence[str] | None = None,
97
+ cwd: str | None = None,
98
+ clear: bool = False,
99
+ time: int | None = None,
100
+ terminator: str = "\x1b\\",
101
+ strict_limits: bool = True,
102
+ windows: bool | None = None,
103
+ ) -> str:
104
+ """Return the full escape sequence: ESC ] 7577 ; body :mac=... ST."""
105
+ check_token(token)
106
+ if terminator not in ("\x1b\\", "\x07"):
107
+ raise ReportError("terminator must be ESC \\ or BEL")
108
+ body = build_body(pid=pid, argv=argv, cwd=cwd, clear=clear, time=time, windows=windows)
109
+ seq = f"\x1b]7577;{body}:mac={compute_mac(body, token)}{terminator}"
110
+ if strict_limits and not clear:
111
+ if argv is not None and len(argv) > MIN_ARGV_LIMIT:
112
+ raise ReportError(f"argv has {len(argv)} elements; terminals only promise {MIN_ARGV_LIMIT}")
113
+ if len(seq.encode("utf-8")) > MIN_TOTAL_LIMIT:
114
+ raise ReportError(f"report is {len(seq.encode())} bytes; terminals only promise {MIN_TOTAL_LIMIT}")
115
+ return seq
osc7577/paths.py ADDED
@@ -0,0 +1,31 @@
1
+ """Absolute paths and bare command names (spec rev 0.6).
2
+
3
+ Paths in a report are paths on the system where the program and the terminal
4
+ run. On POSIX an absolute path starts with "/". On Windows it starts with a
5
+ drive letter and a separator (C:\\x or C:/x) or a network share (\\\\server\\share);
6
+ \\x, /x, C:x and /C:/x are not absolute there. A bare command name contains no
7
+ "/", no "\\" and no drive letter.
8
+ """
9
+
10
+ import re
11
+ import sys
12
+
13
+ _WIN_ABS_RE = re.compile(r"[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+")
14
+ _DRIVE_RE = re.compile(r"[A-Za-z]:")
15
+
16
+
17
+ def on_windows(windows: bool | None = None) -> bool:
18
+ """Resolve the windows flag: None means the platform this code runs on."""
19
+ return sys.platform == "win32" if windows is None else bool(windows)
20
+
21
+
22
+ def is_absolute(path: str, windows: bool | None = None) -> bool:
23
+ if on_windows(windows):
24
+ return bool(_WIN_ABS_RE.match(path))
25
+ return path.startswith("/")
26
+
27
+
28
+ def is_bare_command(name: str, windows: bool | None = None) -> bool:
29
+ if on_windows(windows):
30
+ return "/" not in name and "\\" not in name and not _DRIVE_RE.match(name)
31
+ return "/" not in name
osc7577/py.typed ADDED
File without changes
osc7577/terminal.py ADDED
@@ -0,0 +1,82 @@
1
+ """Send OSC 7577 reports to the terminal and keep the token away from children."""
2
+
3
+ import os
4
+ import sys
5
+ from collections.abc import Mapping, Sequence
6
+ from typing import IO
7
+
8
+ from osc7577.encode import TOKEN_ENV, ReportError, check_token, encode
9
+
10
+
11
+ def supported(env: Mapping[str, str] | None = None) -> bool:
12
+ """True when the terminal set OSC7577_TOKEN (the spec's only feature test)."""
13
+ return bool((os.environ if env is None else env).get(TOKEN_ENV))
14
+
15
+
16
+ def scrub_env(env: Mapping[str, str] | None = None) -> dict[str, str]:
17
+ """Copy of the environment without OSC7577_TOKEN, for child processes."""
18
+ return {k: v for k, v in (os.environ if env is None else env).items() if k != TOKEN_ENV}
19
+
20
+
21
+ def _write(seq: str, stream: IO[str] | None, tty_path: str | None) -> bool:
22
+ if stream is not None:
23
+ stream.write(seq)
24
+ stream.flush()
25
+ return True
26
+ try:
27
+ with open(tty_path or "/dev/tty", "w", encoding="utf-8") as tty:
28
+ tty.write(seq)
29
+ return True
30
+ except OSError:
31
+ if sys.stderr is not None and sys.stderr.isatty():
32
+ sys.stderr.write(seq)
33
+ sys.stderr.flush()
34
+ return True
35
+ return False
36
+
37
+
38
+ def _token(token: str | None, env: Mapping[str, str] | None) -> str | None:
39
+ value = token if token is not None else (os.environ if env is None else env).get(TOKEN_ENV)
40
+ return check_token(value) if value else None
41
+
42
+
43
+ def report(
44
+ argv: Sequence[str],
45
+ *,
46
+ cwd: str | None = None,
47
+ pid: int | None = None,
48
+ token: str | None = None,
49
+ stream: IO[str] | None = None,
50
+ tty_path: str | None = None,
51
+ env: Mapping[str, str] | None = None,
52
+ ) -> bool:
53
+ """Tell the terminal how to resume this program. Returns False when unsupported.
54
+
55
+ If the command cannot be reported (control characters, too long), a clear
56
+ is sent instead so that an older command is not resumed in its place, and
57
+ ReportError is raised.
58
+ """
59
+ tok = _token(token, env)
60
+ if tok is None:
61
+ return False
62
+ try:
63
+ seq = encode(token=tok, pid=pid, argv=argv, cwd=cwd)
64
+ except ReportError:
65
+ _write(encode(token=tok, pid=pid, clear=True), stream, tty_path)
66
+ raise
67
+ return _write(seq, stream, tty_path)
68
+
69
+
70
+ def clear(
71
+ *,
72
+ pid: int | None = None,
73
+ token: str | None = None,
74
+ stream: IO[str] | None = None,
75
+ tty_path: str | None = None,
76
+ env: Mapping[str, str] | None = None,
77
+ ) -> bool:
78
+ """Remove this program's record (send on a normal quit)."""
79
+ tok = _token(token, env)
80
+ if tok is None:
81
+ return False
82
+ return _write(encode(token=tok, pid=pid, clear=True), stream, tty_path)
osc7577/verify.py ADDED
@@ -0,0 +1,131 @@
1
+ """Parse and verify an OSC 7577 report the way a terminal must (rev 0.6).
2
+
3
+ Useful for terminal authors and for testing a program's reports.
4
+ """
5
+
6
+ import base64
7
+ import binascii
8
+ import re
9
+ import time as _time
10
+ from dataclasses import dataclass, field
11
+
12
+ from osc7577.encode import compute_mac
13
+ from osc7577.paths import is_absolute, is_bare_command
14
+
15
+ _KEY_RE = re.compile(r"[a-z]+")
16
+ _VALUE_RE = re.compile(r"[A-Za-z0-9_.,+/=-]*")
17
+ _HEX_RE = re.compile(r"[0-9a-f]{64}")
18
+ _INT_RE = re.compile(r"[1-9][0-9]*")
19
+ _CONTROL_RE = re.compile("[\x00-\x1f\x7f-\x9f]")
20
+ KNOWN_KEYS = frozenset({"pid", "time", "argv", "cwd", "clear", "need", "mac"})
21
+
22
+
23
+ class Ignored(Exception):
24
+ """The report has no effect (bad mac, stale time, cut short)."""
25
+
26
+
27
+ class Rejected(Exception):
28
+ """The report is verified but invalid; the owner's records are removed."""
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Report:
33
+ pid: int
34
+ time: int
35
+ argv: list[str] | None = None
36
+ cwd: str | None = None
37
+ clear: bool = False
38
+ extra: dict[str, str] = field(default_factory=dict)
39
+
40
+
41
+ def strip_sequence(data: str) -> str:
42
+ """Accept a whole sequence or a bare body; return the body."""
43
+ if data.startswith("\x1b]7577;"):
44
+ data = data[len("\x1b]7577;"):]
45
+ if data.endswith("\x1b\\"):
46
+ data = data[:-2]
47
+ elif data.endswith("\x07"):
48
+ data = data[:-1]
49
+ else:
50
+ raise Ignored("sequence is not terminated")
51
+ return data
52
+
53
+
54
+ def _decode(value: str, what: str) -> str:
55
+ pad = (-len(value)) % 4
56
+ if "=" in value and pad:
57
+ raise Rejected(f"{what}: wrong padding")
58
+ try:
59
+ raw = base64.b64decode(value + "=" * pad, validate=True)
60
+ text = raw.decode("utf-8")
61
+ except (binascii.Error, ValueError) as exc:
62
+ raise Rejected(f"{what}: bad base64 or UTF-8") from exc
63
+ if _CONTROL_RE.search(text):
64
+ raise Rejected(f"{what}: control character")
65
+ return text
66
+
67
+
68
+ def verify(
69
+ data: str,
70
+ token: str,
71
+ *,
72
+ now: int | None = None,
73
+ window: int = 60,
74
+ implemented: frozenset[str] = KNOWN_KEYS,
75
+ windows: bool | None = None,
76
+ ) -> Report:
77
+ body = strip_sequence(data)
78
+ head, sep, mac = body.rpartition(":mac=")
79
+ if not sep or not _HEX_RE.fullmatch(mac):
80
+ raise Ignored("the report does not end with a mac")
81
+ if compute_mac(head, token) != mac:
82
+ raise Ignored("the mac does not match")
83
+ pairs: dict[str, str] = {}
84
+ for pair in head.split(":"):
85
+ key, eq, value = pair.partition("=")
86
+ if not eq or not _KEY_RE.fullmatch(key) or not _VALUE_RE.fullmatch(value):
87
+ if key == "mac":
88
+ raise Ignored("the mac is not the last key")
89
+ raise Rejected(f"malformed pair {pair!r}")
90
+ if key == "mac":
91
+ raise Ignored("the mac is not the last key")
92
+ if key in pairs:
93
+ raise Rejected(f"key {key!r} repeats")
94
+ pairs[key] = value
95
+ when = pairs.get("time")
96
+ if when is None or not _INT_RE.fullmatch(when):
97
+ raise Ignored("no valid time")
98
+ clock = int(_time.time()) if now is None else now
99
+ if abs(int(when) - clock) > window:
100
+ raise Ignored("time is outside the window")
101
+ pid = pairs.get("pid")
102
+ if pid is None or not _INT_RE.fullmatch(pid):
103
+ raise Rejected("no valid pid")
104
+ if "need" in pairs:
105
+ missing = [k for k in pairs["need"].split(",") if k not in implemented]
106
+ if missing:
107
+ raise Rejected(f"needs unimplemented keys {missing}")
108
+ has_argv, has_clear = "argv" in pairs, "clear" in pairs
109
+ if has_argv == has_clear:
110
+ raise Rejected("a report has exactly one of argv and clear")
111
+ if has_clear:
112
+ if pairs["clear"] != "1":
113
+ raise Rejected("clear must be 1")
114
+ return Report(pid=int(pid), time=int(when), clear=True)
115
+ if pairs["argv"] == "":
116
+ raise Rejected("argv is empty")
117
+ argv = [_decode(v, "argv") if v else "" for v in pairs["argv"].split(",")]
118
+ first = argv[0]
119
+ if first == "":
120
+ raise Rejected("the first argv element is empty")
121
+ if not is_bare_command(first, windows) and not is_absolute(first, windows):
122
+ raise Rejected("the first argv element is a relative path")
123
+ if first.startswith("-"):
124
+ raise Rejected("a bare command name cannot start with '-'")
125
+ cwd = None
126
+ if "cwd" in pairs:
127
+ cwd = _decode(pairs["cwd"], "cwd")
128
+ if not is_absolute(cwd, windows):
129
+ raise Rejected("cwd is a relative path")
130
+ extra = {k: v for k, v in pairs.items() if k not in KNOWN_KEYS}
131
+ return Report(pid=int(pid), time=int(when), argv=argv, cwd=cwd, extra=extra)
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.5
2
+ Name: osc7577
3
+ Version: 1.0.0
4
+ Summary: Tell the terminal how to resume your program, with OSC 7577 (Program Resume Protocol).
5
+ Project-URL: Homepage, https://github.com/ysskrishna/osc7577
6
+ Project-URL: Repository, https://github.com/ysskrishna/osc7577.git
7
+ Project-URL: Issues, https://github.com/ysskrishna/osc7577/issues
8
+ Project-URL: Changelog, https://github.com/ysskrishna/osc7577/blob/main/CHANGELOG.md
9
+ Author-email: "Y. Siva Sai Krishna" <sivasaikrishnassk@gmail.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: claude-code,cli,osc,osc7577,resume,session,terminal
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: POSIX
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Topic :: Terminals
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.11
26
+ Description-Content-Type: text/markdown
27
+
28
+ # OSC 7577
29
+
30
+
31
+ [![Python Version](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
32
+ [![License](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/ysskrishna/osc7577/blob/main/LICENSE)
33
+ [![Tests](https://github.com/ysskrishna/osc7577/actions/workflows/test.yml/badge.svg)](https://github.com/ysskrishna/osc7577/actions/workflows/test.yml)
34
+ [![PyPI](https://img.shields.io/pypi/v/osc7577)](https://pypi.org/project/osc7577/)
35
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/osc7577?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=BLUE&left_text=downloads)](https://pepy.tech/projects/osc7577)
36
+ [![Author site](https://img.shields.io/badge/author-ysskrishna.space-informational)](https://ysskrishna.space)
37
+ [![Context7](https://img.shields.io/badge/Context7-docs-18181B)](https://context7.com/ysskrishna/osc7577)
38
+ [![Ask DeepWiki](https://img.shields.io/badge/DeepWiki-ask-18181B)](https://deepwiki.com/ysskrishna/osc7577)
39
+
40
+ Tell the terminal how to bring your program back after it restarts, with OSC 7577.
41
+
42
+ ## Features
43
+
44
+ - **Report and clear**: `report(argv, cwd=...)` and `clear()`, with the spec's `time` and token hash (`mac`)
45
+ - **Spec checks before sending**: relative paths, control characters, an empty first argument, and the 2048-byte and 64-element limits. A command that cannot be reported sends `clear`, so an older command is not resumed in its place
46
+ - **Token hygiene**: the token never appears in output, and `scrub_env()` drops `OSC7577_TOKEN` for child processes
47
+ - **Verifier**: `verify()` parses and checks a report the way a terminal must (ignored or rejected), for terminal authors and tests
48
+ - **CLI**: `osc7577 report`, `osc7577 clear`, `osc7577 wrap -- CMD`, and `osc7577 claude-hook`
49
+ - **Windows paths**: `C:\...`, `C:/...` and `\\server\share` count as absolute; `\code`, `/code`, `C:code` and `/C:/...` do not
50
+ - **Zero dependencies**: the library only uses the Python standard library
51
+ - **Spec examples as tests**: every published example in the spec is reproduced byte for byte
52
+
53
+ ## Why OSC 7577?
54
+
55
+ When a terminal restarts, it can reopen its tabs and their directories, but not the programs that ran in them. A shell does not know that your REPL was open on session 42, or that an agent was in the middle of a conversation.
56
+
57
+ OSC 7577 lets the program tell the terminal the exact command that brings it back. The terminal hands each program a random token in `OSC7577_TOKEN`, and every report carries a hash of that token, so another program cannot register a command in your name. A terminal that does not know the sequence never sets the token, and this library then sends nothing.
58
+
59
+ Spec: [Program Resume Protocol, revision 0.6](https://www.superlogical.com/rex/docs/build/program-resume) (2026-12-01).
60
+
61
+ Sibling of [osc7501](https://github.com/ysskrishna/osc7501), which reports program status.
62
+
63
+ ## Installation
64
+
65
+ ```bash
66
+ pip install osc7577
67
+ ```
68
+
69
+ ## Usage Examples
70
+
71
+ ### Report and clear
72
+
73
+ ```python
74
+ import atexit
75
+ from osc7577 import clear, report, supported
76
+
77
+ if supported(): # the terminal set OSC7577_TOKEN
78
+ report(["myrepl", "--session", "/home/me/.local/state/myrepl/42.json"], cwd="/home/me/proj")
79
+ atexit.register(clear) # a normal quit should not be resumed
80
+ ```
81
+
82
+ The first argument must be an absolute path or a bare command name, and `cwd` must be an absolute path. A command that breaks a rule sends `clear` and raises `ReportError`.
83
+
84
+ `report()` and `clear()` write to `/dev/tty`. They return `True` only when bytes were written, and `False` when the terminal did not set the token.
85
+
86
+ ### Child processes
87
+
88
+ ```python
89
+ import subprocess
90
+ from osc7577 import scrub_env
91
+
92
+ subprocess.run(["git", "--version"], env=scrub_env(), check=True)
93
+ ```
94
+
95
+ Start children with `env=scrub_env()` so they cannot see the token or report commands in your place.
96
+
97
+ ### Wrap any command
98
+
99
+ ```bash
100
+ osc7577 wrap -- ssh devbox
101
+ ```
102
+
103
+ `wrap` reports `osc7577 wrap ssh devbox` with the current directory, then runs the command without the token. `osc7577 report -- CMD` and `osc7577 clear` report for the parent shell.
104
+
105
+ ### Claude Code
106
+
107
+ Until Claude Code reports OSC 7577 itself ([anthropics/claude-code#112408](https://github.com/anthropics/claude-code/issues/112408)), add a hook in `~/.claude/settings.json`:
108
+
109
+ ```json
110
+ {
111
+ "hooks": {
112
+ "SessionStart": [{"hooks": [{"type": "command", "command": "osc7577 claude-hook"}]}],
113
+ "SessionEnd": [{"hooks": [{"type": "command", "command": "osc7577 claude-hook"}]}]
114
+ }
115
+ }
116
+ ```
117
+
118
+ On start, resume and clear it reports `claude --resume <session id>` with the session's directory, owned by the `claude` process and written to its tty (hook output is captured, so stdout would not reach the terminal). On a normal quit it clears the record. Other endings leave it, so the terminal can resume.
119
+
120
+ ### Verify (terminal side)
121
+
122
+ ```python
123
+ from osc7577 import Ignored, Rejected, encode, verify
124
+
125
+ token = "dummy-token-replace-me"
126
+ sequence = encode(token=token, pid=74877, argv=["lazygit"], cwd="/home/user/src/project")
127
+
128
+ try:
129
+ rep = verify(sequence, token) # checks mac first, then time (60 s window), then keys
130
+ print(rep.pid, rep.argv, rep.cwd)
131
+ except Ignored:
132
+ pass # no effect
133
+ except Rejected:
134
+ pass # remove this owner's records
135
+ ```
136
+
137
+ ## API Reference
138
+
139
+ | Name | Description |
140
+ |------|-------------|
141
+ | `report(argv, *, cwd, pid, token, stream, tty_path, env) -> bool` | Write a resume report. Sends `clear` and raises `ReportError` when the command cannot be reported. |
142
+ | `clear(*, pid, token, stream, tty_path, env) -> bool` | Remove this program's record. Send it on a normal quit. |
143
+ | `supported(env=None) -> bool` | True when the terminal set `OSC7577_TOKEN`. |
144
+ | `scrub_env(env=None) -> dict` | A copy of the environment without `OSC7577_TOKEN`. |
145
+ | `encode(*, token, pid, argv, cwd, clear, time, terminator, strict_limits, windows) -> str` | Build one full sequence. Does not write. |
146
+ | `build_body(*, pid, argv, cwd, clear, time, windows) -> str` | The body without the final `:mac=` pair. |
147
+ | `compute_mac(body, token) -> str` | SHA-256 of `body:token` as 64 hex characters (not an HMAC). |
148
+ | `verify(data, token, *, now, window, implemented, windows) -> Report` | Check a report as a terminal must. Raises `Ignored` or `Rejected`. |
149
+ | `Report` | `pid`, `time`, `argv`, `cwd`, `clear`, `extra`. |
150
+ | `is_absolute(path, windows=None)`, `is_bare_command(name, windows=None)` | The spec's path rules. `windows` defaults to the running platform. |
151
+ | `ReportError`, `Ignored`, `Rejected` | Errors. `ReportError` is a `ValueError`. |
152
+ | `TOKEN_ENV` | `"OSC7577_TOKEN"`. |
153
+
154
+ ## Learn More
155
+
156
+ - [Program Resume Protocol (OSC 7577)](https://www.superlogical.com/rex/docs/build/program-resume)
157
+ - [Rex](https://www.superlogical.com/rex)
158
+ - [osc7501](https://github.com/ysskrishna/osc7501), the Program Status Protocol for Python
159
+
160
+ ## Acknowledgments
161
+
162
+ - [Superlogical](https://www.superlogical.com/rex), for the Rex terminal and the Program Resume Protocol
163
+
164
+ ## Contributing
165
+
166
+ We welcome contributions! Please see our [Contributing Guide](https://github.com/ysskrishna/osc7577/blob/main/CONTRIBUTING.md) for details.
167
+
168
+ ## Built and maintained by
169
+
170
+ OSC 7577 is built and maintained by:
171
+
172
+ | | Name | GitHub | Role |
173
+ |---|------|--------|------|
174
+ | <img src="https://github.com/ysskrishna.png?size=120" width="60" height="60" alt="Y. Siva Sai Krishna"> | **Y. Siva Sai Krishna** | [@ysskrishna](https://github.com/ysskrishna) | Creator |
175
+
176
+ ## Changelog
177
+
178
+ See [CHANGELOG](CHANGELOG.md) for release history.
179
+
180
+ ## Support
181
+
182
+ If you find this library helpful:
183
+
184
+ - ⭐ Star the repository
185
+ - 🐛 [Report issues](https://github.com/ysskrishna/osc7577/issues)
186
+ - 🔀 Submit pull requests
187
+ - 💝 [Sponsor on GitHub](https://github.com/sponsors/ysskrishna)
188
+
189
+ ## License
190
+
191
+ MIT © [Y. Siva Sai Krishna](https://github.com/ysskrishna) - see [LICENSE](LICENSE) for details.
192
+
193
+ ---
194
+
195
+ <p align="left">
196
+ <a href="https://github.com/ysskrishna">Author's GitHub</a> •
197
+ <a href="https://linkedin.com/in/ysskrishna">Author's LinkedIn</a> •
198
+ <a href="https://ysskrishna.space">Author's site</a> •
199
+ <a href="https://pypi.org/project/osc7577/">Package on PyPI</a> •
200
+ <a href="https://github.com/ysskrishna/osc7577/issues">Report Issues</a>
201
+ </p>
@@ -0,0 +1,13 @@
1
+ osc7577/__init__.py,sha256=tKIK1CZdjPutm4ggwQJ6RNc0oe6MtG7AKE6geLQuJxU,610
2
+ osc7577/__main__.py,sha256=7iJAHVxC2SYCujaow9YULVtC6hGL5uEimtt84_b6Gbw,2247
3
+ osc7577/claude_hook.py,sha256=VClazCK2yFyAXU1fmV1TD_DDuSD09WnMyH7d-zY07P4,3168
4
+ osc7577/encode.py,sha256=eWSEMVRxls-nSpvypfXI3JIfmB56qttOhBSupF4DDYQ,4082
5
+ osc7577/paths.py,sha256=Uj1pcNmk6OExqMJlOJFsnYzN76E6_hvTE7lpdRwTNfc,1128
6
+ osc7577/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ osc7577/terminal.py,sha256=BwYCsLob8jWR-XR8Do92_WgFsqDjfmSUhXcRX3S13Zs,2646
8
+ osc7577/verify.py,sha256=Vo3z3EwFbFKDJGLtMikukgw61KmhSuhR7AEulN7Qlnc,4610
9
+ osc7577-1.0.0.dist-info/METADATA,sha256=pPw-Cp3NU5v652YPQepRu-CKs7excjuM30GO_SH5e88,9459
10
+ osc7577-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ osc7577-1.0.0.dist-info/entry_points.txt,sha256=0AklXKXdI27opxc-H37SJQ2MIR8rBC7NhdDZ7k6KBC4,50
12
+ osc7577-1.0.0.dist-info/licenses/LICENSE,sha256=Szx3imxJ9EtUI6_eYtQa6jNMVK_1jhrbjMSaHOzIsVE,1076
13
+ osc7577-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ osc7577 = osc7577.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Y. Siva Sai Krishna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.