"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
fix(browser): anchor absolute paths via cd %here% multi-line wrap (PR #308 round 6)
apirenob688f6af188a
diff --git a/browser/agent-harness/HARNESS.md b/browser/agent-harness/HARNESS.mdindex 0ba611ddc..7a2dbf66b 100644--- a/browser/agent-harness/HARNESS.md+++ b/browser/agent-harness/HARNESS.md@@ -58,22 +58,29 @@ DOMShell 2.0.0+ exposes a single MCP tool:|------|-------------|| `domshell_execute` | Runs a shell-style command string. Multi-line input is supported — each line runs in order in the same shell state. |-The harness builds command strings from the public CLI commands:--| CLI Command | Command string sent to `domshell_execute` |-|-------------|--------------------------------------------|-| `fs ls <path>` | `ls <path>` |-| `fs cd <path>` | `cd <path>` |-| `fs cat <path>` | `cat <path>` |-| `fs grep <pat>` | `grep <pat>` |-| `fs grep <pat> <path>` | `cd <path>\ngrep <pat>\ncd <prev>` (single call) |-| `act click <path>` | `click <path>` |-| `act type <path> <text>` | `focus <path>\ntype <text>` (single call) |+The harness builds command strings from the public CLI commands. Harness+absolute paths (leading `/`) are anchored at the tab root via+`cd %here%` since DOMShell's lane cwd may have drifted; relative paths+are passed through unchanged.++| CLI Command (path is absolute) | Command string sent to `domshell_execute` |+|--------------------------------|--------------------------------------------|+| `fs ls /<sub>` | `cd %here%/<sub>` then bare `ls`, then `cd <restore>` (single multi-line call) |+| `fs cd /<sub>` | `cd %here%/<sub>` (single line — `cd` is the desired new state) |+| `fs cat /<sub>` | `cd %here%`, `cat <sub>`, `cd <restore>` (single multi-line call) |+| `fs grep <pat>` | `grep <pat>` (operates on lane cwd) |+| `fs grep <pat> /<sub>` | `cd %here%/<sub>`, `grep <pat>`, `cd <restore>` (single multi-line call) |+| `act click /<sub>` | `cd %here%`, `click <sub>`, `cd <restore>` (single multi-line call) |+| `act type /<sub> <text>` | `cd %here%`, `focus <sub>`, `cd <restore>` — then, on success, `type <text>` (two calls, shared lane via `group_id`) || `page open <url>` | `open <url>` || `page reload` | `refresh` || `page back` | `back` || `page forward` | `forward` |+`<restore>` resolves to `cd %here%/<harness-working-dir>` (or `cd %here%`+when the harness is at the tab root) so the lane's cwd ends up where+the harness expects.+## Key Design Decisions### 1. MCP Backend Pattern (First in CLI-Anything)diff --git a/browser/agent-harness/cli_anything/browser/tests/test_domshell_backend.py b/browser/agent-harness/cli_anything/browser/tests/test_domshell_backend.pyindex 978c2e4b1..ee947edfc 100644--- a/browser/agent-harness/cli_anything/browser/tests/test_domshell_backend.py+++ b/browser/agent-harness/cli_anything/browser/tests/test_domshell_backend.py@@ -18,63 +18,125 @@ from cli_anything.browser.utils import domshell_backend as backend# ── Path translation: harness `/` vs DOMShell `~/` ───────────────────-def test_translate_path_root_maps_to_empty():- """Harness `/` (focused-tab AX root) → DOMShell empty (lane cwd)."""- assert backend._translate_path("/") == ""- assert backend._translate_path("") == ""+def test_translate_path_root_is_absolute_empty():+ """`/` → ("", True). Absolute target with no further subdir."""+ assert backend._translate_path("/") == ("", True)-def test_translate_path_strips_leading_slash():- assert backend._translate_path("/main") == "main"- assert backend._translate_path("/main/article") == "main/article"+def test_translate_path_empty_is_relative_empty():+ """`""` → ("", False). Bare/relative no-op; caller decides what to do."""+ assert backend._translate_path("") == ("", False)+++def test_translate_path_strips_all_leading_slashes():+ """`//main` collapses to `("main", True)` via lstrip."""+ assert backend._translate_path("/main") == ("main", True)+ assert backend._translate_path("//main") == ("main", True)+ assert backend._translate_path("///main") == ("main", True)def test_translate_path_preserves_relative():"""Relative paths pass through unchanged — DOMShell handles them."""- assert backend._translate_path("main") == "main"- assert backend._translate_path("..") == ".."- assert backend._translate_path(".") == "."+ assert backend._translate_path("main") == ("main", False)+ assert backend._translate_path("..") == ("..", False)+ assert backend._translate_path(".") == (".", False)+++# ── ls / cd / cat / click: absolute paths anchor at %here% ───────────@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_ls_root_sends_bare_ls(mock_call):- """`ls /` (harness) → bare `ls` (DOMShell), operating on lane cwd."""+def test_ls_absolute_path_wraps_with_cd_anchor_and_restore(mock_call):+ """`ls /main` from a `/main` session: cd-anchor + bare ls + restore."""mock_call.return_value = _make_result("[lane: 1]")- backend.ls("/")- assert mock_call.call_args.args[0] == "ls"+ sess = _make_session(working_dir="/main")+ backend.ls("/main", session=sess)+ cmd = mock_call.call_args.args[0]+ assert "cd %here%/main" in cmd+ assert "\nls\n" in cmd+ assert cmd.endswith("cd %here%/main")@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_ls_subpath_strips_leading_slash(mock_call):+def test_ls_root_from_drifted_cwd_anchors_at_here(mock_call):+ """The Codex P1 case: `ls /` from a drifted `/main` cwd anchors at tab root."""mock_call.return_value = _make_result("[lane: 1]")- backend.ls("/main")+ sess = _make_session(working_dir="/main")+ backend.ls("/", session=sess)+ cmd = mock_call.call_args.args[0]+ assert cmd == "cd %here%\nls\ncd %here%/main"++[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_ls_relative_path_no_wrap(mock_call):+ """Relative `ls main` runs against lane cwd — no anchor, no restore."""+ mock_call.return_value = _make_result("[lane: 1]")+ backend.ls("main")assert mock_call.call_args.args[0] == "ls main"[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_ls_absolute_path_with_spaces_quoted(mock_call):+ """The `%here%/<deeper>` token is shell-quoted as one unit.++ Upstream-smoked: `cd '%here%/<path>'` works in DOMShell 2.0.x — so+ whitespace and other shell metachars in absolute targets are safe.+ """+ mock_call.return_value = _make_result("[lane: 1]")+ backend.ls("/path with spaces", session=_make_session(working_dir="/"))+ cmd = mock_call.call_args.args[0]+ assert "cd '%here%/path with spaces'" in cmd++@patch.object(backend, "_call_execute", new_callable=AsyncMock)def test_cd_root_uses_here(mock_call):- """`cd /` (harness) → `cd %here%` (DOMShell jump-to-tab-root)."""+ """`cd /` → `cd %here%`. Single line — cd's purpose IS the new state."""mock_call.return_value = _make_result("[lane: 1]")backend.cd("/")assert mock_call.call_args.args[0] == "cd %here%"@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_cd_subpath_strips_leading_slash(mock_call):+def test_cd_absolute_is_single_line_no_restore(mock_call):+ """`cd /main` → `cd %here%/main`. One line, no restore."""+ mock_call.return_value = _make_result("[lane: 1]")+ backend.cd("/main")+ assert mock_call.call_args.args[0] == "cd %here%/main"++[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_cd_subpath_with_indexing(mock_call):+ """Brackets are shell-metachars — `_here_path` quotes the full token."""mock_call.return_value = _make_result("[lane: 1]")backend.cd("/main/div[0]")- assert mock_call.call_args.args[0] == "cd 'main/div[0]'"+ assert mock_call.call_args.args[0] == "cd '%here%/main/div[0]'"++[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_cd_relative_quoted(mock_call):+ """Relative `cd main` is quoted via _q (handles spaces / metachars)."""+ mock_call.return_value = _make_result("[lane: 1]")+ backend.cd("main")+ assert mock_call.call_args.args[0] == "cd main"++[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_cat_absolute_path_wraps(mock_call):+ """`cat /main/btn`: anchor at tab root, run relative cat, restore."""+ mock_call.return_value = _make_result("[lane: 1]")+ sess = _make_session(working_dir="/")+ backend.cat("/main/btn", session=sess)+ assert mock_call.call_args.args[0] == "cd %here%\ncat main/btn\ncd %here%"@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_cat_strips_leading_slash(mock_call):+def test_cat_relative_no_wrap(mock_call):mock_call.return_value = _make_result("[lane: 1]")- backend.cat("/main/button[0]")- assert mock_call.call_args.args[0] == "cat 'main/button[0]'"+ backend.cat("main/btn")+ assert mock_call.call_args.args[0] == "cat main/btn"def test_cat_root_raises_value_error():- """Calling cat against the tab root is a programming error — fail clearly."""with pytest.raises(ValueError, match="element name is required"):backend.cat("/")with pytest.raises(ValueError, match="element name is required"):@@ -82,10 +144,21 @@ def test_cat_root_raises_value_error():@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_click_strips_leading_slash(mock_call):+def test_click_absolute_path_wraps(mock_call):mock_call.return_value = _make_result("[lane: 1]")- backend.click("/main/button[0]")- assert mock_call.call_args.args[0] == "click 'main/button[0]'"+ sess = _make_session(working_dir="/main")+ backend.click("/main/button[0]", session=sess)+ assert (+ mock_call.call_args.args[0]+ == "cd %here%\nclick 'main/button[0]'\ncd %here%/main"+ )++[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_click_relative_no_wrap(mock_call):+ mock_call.return_value = _make_result("[lane: 1]")+ backend.click("button[0]")+ assert mock_call.call_args.args[0] == "click 'button[0]'"def test_click_root_raises_value_error():@@ -95,20 +168,32 @@ def test_click_root_raises_value_error():backend.click("")-def test_type_text_root_raises_value_error():- """Focusing the tab root is a programming error — same class as cat/click."""- with pytest.raises(ValueError, match="element name is required"):- backend.type_text("/", "hello")- with pytest.raises(ValueError, match="element name is required"):- backend.type_text("", "hello")+# ── grep absolute-path anchoring ─────────────────────────────────────@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_grep_rooted_with_subpath_prev_keeps_translated_restore(mock_call):- """A non-`/` prev should also be translated, not sent verbatim."""+def test_grep_rooted_absolute_anchors_at_here(mock_call):+ """Rooted grep with absolute path anchors at tab root + restores wd."""mock_call.return_value = _make_result("[lane: 1]")- backend.grep("Login", path="/main/dialog", prev="/main")- assert mock_call.call_args.args[0] == "cd main/dialog\ngrep Login\ncd main"+ backend.grep(+ "Login", path="/main", prev="/", session=_make_session(working_dir="/"),+ )+ assert (+ mock_call.call_args.args[0]+ == "cd %here%/main\ngrep Login\ncd %here%"+ )++[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_grep_rooted_absolute_restores_to_session_wd(mock_call):+ """Restore line follows session.working_dir, not the `prev` kwarg, when+ the path is absolute — the lane cwd needs to end up where the harness+ thinks it is, regardless of what `prev` was originally."""+ mock_call.return_value = _make_result("[lane: 1]")+ backend.grep(+ "Login", path="/main", prev="/", session=_make_session(working_dir="/main"),+ )+ assert mock_call.call_args.args[0].endswith("cd %here%/main")# ── _is_error helper ─────────────────────────────────────────────────@@ -163,10 +248,10 @@ def test_grep_rooted_emits_single_multiline_call(mock_call):backend.grep("Login", path="/main", prev="/")- # Harness `/main` translates to DOMShell `main`; harness `/` (the- # default prev) translates to `cd %here%`.+ # Absolute path anchors at %here%/main; restore comes from+ # _restore_cwd_cmd(session=None) → `cd %here%` (defaults to harness `/`).assert mock_call.call_args_list == [- call("cd main\ngrep Login\ncd %here%", False, session=None),+ call("cd %here%/main\ngrep Login\ncd %here%", False, session=None),]@@ -188,16 +273,16 @@ def test_grep_rooted_uses_single_call_for_lane_isolation(mock_call):@patch.object(backend, "_call_execute", new_callable=AsyncMock)def test_grep_rooted_quotes_path_with_spaces(mock_call):- """Paths with whitespace are shell-quoted inside the multi-line command."""+ """Absolute paths with whitespace are quoted as `cd '%here%/path with spaces'`.++ Upstream-smoked: DOMShell's `cd` accepts the quoted form cleanly.+ """mock_call.return_value = {}backend.grep("Login", path="/path with spaces", prev="/")cmd = mock_call.call_args.args[0]- # _translate_path strips the leading "/", then shlex.quote single-- # quotes the remainder; the multi-line layout (grep + cd back) stays- # intact, with the restore using `cd %here%` for the harness-`/` prev.- assert cmd.startswith("cd 'path with spaces'\n")+ assert cmd.startswith("cd '%here%/path with spaces'\n")assert "\ngrep Login\n" in cmdassert cmd.endswith("\ncd %here%")@@ -242,7 +327,7 @@ def test_grep_keyword_use_daemon_still_works():@patch.object(backend, "_call_execute", new_callable=AsyncMock)-def test_type_text_uses_two_separate_calls(mock_call):+def test_type_text_emits_focus_then_type_with_session(mock_call):"""type_text issues focus + type as two separate execute calls.The split is for safety: DOMShell's multi-line splitter continues@@ -250,32 +335,67 @@ def test_type_text_uses_two_separate_calls(mock_call):would dispatch keys into stale focus if ``focus`` failed. Two callswith an error check between them prevents that."""+ sess = _make_session(working_dir="/")mock_call.return_value = _make_result("✓ Focused\n[lane: 1]")- backend.type_text("search_input", "machine learning")+ backend.type_text("search_input", "machine learning", session=sess)assert mock_call.call_count == 2+ # Relative path → no anchor wrap.assert mock_call.call_args_list[0].args[0] == "focus search_input"assert mock_call.call_args_list[1].args[0] == "type 'machine learning'"[email protected](backend, "_call_execute", new_callable=AsyncMock)+def test_type_text_absolute_path_wraps_focus(mock_call):+ """Absolute focus path is anchored at %here% and restores wd."""+ sess = _make_session(working_dir="/main")+ mock_call.return_value = _make_result("✓\n[lane: 1]")++ backend.type_text("/main/input", "text", session=sess)++ assert mock_call.call_count == 2+ assert (+ mock_call.call_args_list[0].args[0]+ == "cd %here%\nfocus main/input\ncd %here%/main"+ )+ assert mock_call.call_args_list[1].args[0] == "type text"++@patch.object(backend, "_call_execute", new_callable=AsyncMock)def test_type_text_skips_type_on_focus_error(mock_call):"""If focus errors, type MUST NOT run — would land in stale focus."""+ sess = _make_session(working_dir="/")mock_call.side_effect = [_make_result("Error: focus: No such element"),_make_result("✓ Typed"), # should NOT be reached]- result = backend.type_text("/stale/path", "secret_password")+ result = backend.type_text("/stale/path", "secret_password", session=sess)# Only the focus call was made; the focus result was returned.assert mock_call.call_count == 1- assert mock_call.call_args_list[0].args[0] == "focus stale/path"+ # Absolute path → wrapped in anchor + restore.+ assert mock_call.call_args_list[0].args[0] == (+ "cd %here%\nfocus stale/path\ncd %here%"+ )# The focus result is returned verbatim so callers see the error.assert result.content[0].text == "Error: focus: No such element"+def test_type_text_raises_without_session():+ """The two halves must share a lane; require a session up front."""+ with pytest.raises(ValueError, match="session"):+ backend.type_text("search_input", "text", session=None)+++def test_type_text_raises_with_empty_path():+ with pytest.raises(ValueError, match="input path is required"):+ backend.type_text("", "text", session=_make_session())+ with pytest.raises(ValueError, match="input path is required"):+ backend.type_text("/", "text", session=_make_session())++def test_type_text_rejects_newline_in_text():"""``\\n`` in text would inject a new DOMShell command — must raise."""with pytest.raises(ValueError, match="newline"):@@ -381,6 +501,20 @@ def test_cd_rejects_newlines(mock_call):# on every subsequent call.+def _make_session(+ working_dir: str = "/",+ daemon_mode: bool = False,+ lane_id=None,+):+ """Build a minimal session fixture compatible with the backend's+ ``getattr``-style access (working_dir, daemon_mode, domshell_lane_id)."""+ return SimpleNamespace(+ working_dir=working_dir,+ daemon_mode=daemon_mode,+ domshell_lane_id=lane_id,+ )++def _make_result(text: str):"""Build a fake CallToolResult whose ``content[0].text`` is ``text``."""return SimpleNamespace(content=[SimpleNamespace(text=text)])@@ -572,10 +706,13 @@ def test_session_is_keyword_only_on_open_url():@patch.object(backend, "_call_execute", new_callable=AsyncMock)def test_use_daemon_positional_on_ls(mock_call):- mock_call.return_value = {}+ mock_call.return_value = _make_result("[lane: 1]")backend.ls("/", True) # use_daemon=True positionally- # Harness `/` translates to "" so ls sends the bare command.- assert mock_call.call_args == call("ls", True, session=None)+ # Absolute `/` with no session → anchor at %here%, bare ls, restore+ # to %here% (the default for session=None).+ assert mock_call.call_args == call(+ "cd %here%\nls\ncd %here%", True, session=None,+ )@patch.object(backend, "_call_execute", new_callable=AsyncMock)@@ -594,11 +731,15 @@ def test_use_daemon_positional_on_reload(mock_call):@patch.object(backend, "_call_execute", new_callable=AsyncMock)def test_use_daemon_positional_on_type_text(mock_call):- """Positional ``use_daemon`` flows through both halves of the split."""+ """Positional ``use_daemon`` flows through both halves of the split.++ type_text now requires a session, so pass one explicitly.+ """+ sess = _make_session(working_dir="/")mock_call.return_value = _make_result("✓\n[lane: 1]")- backend.type_text("input", "hello", True)+ backend.type_text("input", "hello", True, session=sess)# Two calls (focus then type), both with use_daemon=True positionally.assert mock_call.call_args_list == [- call("focus input", True, session=None),- call("type hello", True, session=None),+ call("focus input", True, session=sess),+ call("type hello", True, session=sess),]diff --git a/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py b/browser/agent-harness/cli_anything/browser/utils/domshell_backend.pyindex 80de67a8b..41fca7fa0 100644--- a/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py+++ b/browser/agent-harness/cli_anything/browser/utils/domshell_backend.py@@ -186,27 +186,102 @@ def _capture_lane(session: Any, result: Any) -> None:session.domshell_lane_id = lane-def _translate_path(harness_path: str) -> str:- """Translate a harness DOM path to a DOMShell command path.+def _translate_path(harness_path: str) -> tuple[str, bool]:+ """Translate a harness DOM path into ``(stripped, is_absolute)``.The harness models ``/`` as the focused tab's AX root. DOMShell models- ``~/`` (and bare ``/``) as the BROWSER root — windows and tabs.- Sending ``ls /`` verbatim would list tabs, not page elements. Strip- the leading ``/`` so harness ``/main`` becomes DOMShell ``main``- (relative to the lane's cwd, which IS the focused tab's AX root once- ``page open`` has put the lane inside the tab).-- - ``""`` and ``"/"`` → ``""`` (signal: operate on lane cwd; the- wrappers turn this into a bare command, e.g. ``ls`` or ``cd %here%``).- - ``"/main"`` → ``"main"``- - ``"/main/article"`` → ``"main/article"``- - ``"main"``, ``".."``, ``"."`` → passed through unchanged.+ ``/`` and ``~/`` as the BROWSER root (windows/tabs). DOMShell also+ keeps a per-lane cwd that persists between commands — so after+ ``fs cd /main`` the lane cwd is no longer the tab root, and a+ subsequent ``ls main`` (the naive strip-one-slash form) would resolve+ against the drifted cwd as ``/main/main``. Wrong target.++ The fix: distinguish *absolute* from *relative* harness paths so+ callers can wrap the operation in ``cd %here%[/deeper]\\n<op>\\ncd+ <restore>`` for the absolute case (anchoring at the tab root), and+ pass relative paths through unchanged (the lane cwd is the right+ reference for them).++ Uses ``lstrip("/")`` so accidental ``//main`` collapses to ``main``.++ Examples:+ ``""`` → ``("", False)``+ ``"/"`` → ``("", True)``+ ``"/main"`` → ``("main", True)``+ ``"//main"`` → ``("main", True)``+ ``"/main/btn"`` → ``("main/btn", True)``+ ``"main"`` → ``("main", False)``+ ``".."`` → ``("..", False)``"""- if not harness_path or harness_path == "/":- return ""+ # Newline guard at the translation boundary: absolute-path branches+ # interpolate `%here%/<translated>` without going through `_q`+ # (DOMShell's path-variable expander runs before quote parsing on+ # `cd`, so quoting would defeat it). Catching newlines here means+ # every wrapper that consumes the translated path is protected+ # against injection, even if the wrapper skips `_q`.+ if "\n" in harness_path or "\r" in harness_path:+ raise ValueError(+ "Newline characters are not allowed in path arguments — "+ "DOMShell's domshell_execute treats them as command separators, "+ f"so a newline in a path would inject additional commands. "+ f"Got ({len(harness_path)} chars): "+ f"{(harness_path[:80] + ('…' if len(harness_path) > 80 else ''))!r}"+ )+ if not harness_path:+ return "", Falseif harness_path.startswith("/"):- return harness_path[1:]- return harness_path+ return harness_path.lstrip("/"), True+ return harness_path, False+++def _here_path(deeper: str) -> str:+ """Build a ``%here%[/<deeper>]`` token, shell-quoted as a single unit.++ DOMShell's ``cd`` accepts quoted ``%here%`` cleanly+ (``cd '%here%/main'`` was upstream-smoked: ``✓ Entered tab …``), so+ we quote uniformly via ``_q``. Whitespace, brackets, ``$`` etc. in+ the ``<deeper>`` portion survive the wrap correctly.++ For simple cases (no shell metacharacters) ``_q`` returns the input+ unchanged, so ``_here_path("main")`` is still ``%here%/main``.+ """+ return _q(f"%here%/{deeper}") if deeper else _q("%here%")+++def _restore_cwd_cmd(session: Any) -> str:+ """Build the trailing ``cd <wd>`` line for an absolute-path wrap.++ Uses the harness's tracked ``working_dir`` (translated to DOMShell+ form) so after the wrapped operation the lane's cwd matches what the+ harness thinks it is. Without this restore, a wrapped operation+ against ``/`` would leave the lane parked at ``%here%`` even though+ the harness's ``working_dir`` is something like ``/main``.++ The harness ``working_dir`` is always absolute in normal use, so the+ common output shape is ``cd %here%/<stripped>``. The relative+ branch is a defensive fallback for an unusual session shape.+ """+ wd = getattr(session, "working_dir", None) or "/"+ stripped, is_abs = _translate_path(wd)+ if is_abs:+ return f"cd {_here_path(stripped)}"+ return f"cd {_q(stripped)}" if stripped else f"cd {_here_path('')}"+++def _wrap_absolute(operation: str, session: Any, *, deeper: str = "") -> str:+ """Build a ``cd %here%[/deeper]\\n<operation>\\n<restore>`` triplet.++ ``deeper`` is the optional tab-root-relative subdir to ``cd`` into+ BEFORE the operation. Used for ``ls /main`` where the operation is+ bare ``ls`` (and the ``/main`` needs to become the anchored cwd) as+ opposed to ``cat /main/btn`` where the operation already carries the+ relative path and we just anchor at the tab root.++ The ``%here%/<deeper>`` token is shell-quoted as a single unit via+ ``_here_path``, so paths containing whitespace or other shell+ metacharacters survive the wrap correctly.+ """+ return f"cd {_here_path(deeper)}\n{operation}\n{_restore_cwd_cmd(session)}"def _is_error(result: Any) -> bool:@@ -407,8 +482,15 @@ def ls(path: str = "/", use_daemon: bool = False, *, session: Any = None) -> dic>>> ls("/"){"path": "/", "entries": [{"name": "main", "role": "landmark", ...}]}"""- translated = _translate_path(path)- command = f"ls {_q(translated)}" if translated else "ls"+ translated, is_absolute = _translate_path(path)+ if is_absolute:+ # `ls /main`: cd to %here%/main, run bare ls, restore.+ # `ls /`: cd to %here%, run bare ls, restore.+ command = _wrap_absolute("ls", session, deeper=translated)+ elif translated:+ command = f"ls {_q(translated)}"+ else:+ command = "ls"return asyncio.run(_call_execute(command, use_daemon, session=session))@@ -427,11 +509,17 @@ def cd(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:>>> cd("/main/div[0]"){"path": "/main/div[0]", "element": {...}}"""- translated = _translate_path(path)- # Harness `cd /` means "back to focused-tab AX root" — DOMShell's- # equivalent is `cd %here%`, which jumps to the tab root regardless- # of where the lane wandered to.- command = "cd %here%" if not translated else f"cd {_q(translated)}"+ translated, is_absolute = _translate_path(path)+ # cd is the rare case where the operation IS the new state — no+ # restore needed. Absolute targets anchor via `cd %here%/<rest>` so+ # the result is independent of the lane's current cwd.+ if is_absolute:+ command = f"cd {_here_path(translated)}"+ elif translated:+ command = f"cd {_q(translated)}"+ else:+ # Bare/empty `cd` → back to tab root.+ command = f"cd {_here_path('')}"return asyncio.run(_call_execute(command, use_daemon, session=session))@@ -450,13 +538,19 @@ def cat(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:>>> cat("/main/button[0]"){"name": "Submit", "role": "button", "text": "Submit", ...}"""- translated = _translate_path(path)+ translated, is_absolute = _translate_path(path)if not translated:raise ValueError("cat: an element name is required — cannot cat the tab root. ""Use `ls` to list the root's children, or pass a specific name.")- return asyncio.run(_call_execute(f"cat {_q(translated)}", use_daemon, session=session))+ if is_absolute:+ # `cat /main/btn`: anchor at tab root, run `cat main/btn` relative,+ # restore the harness's tracked cwd.+ command = _wrap_absolute(f"cat {_q(translated)}", session)+ else:+ command = f"cat {_q(translated)}"+ return asyncio.run(_call_execute(command, use_daemon, session=session))def grep(@@ -502,22 +596,39 @@ def grep({"matches": ["/main/button[0]"]}"""_assert_single_line("pattern", pattern)- translated_path = _translate_path(path)- translated_prev = _translate_path(prev)- if translated_path:- _assert_single_line("path", path)- _assert_single_line("prev", prev)- # Harness `/` (the default for `prev`) means "back to focused-tab- # AX root", which is DOMShell's `cd %here%`. Any other restore- # path becomes `cd <translated>`.- restore = (- f"cd {_q(translated_prev)}" if translated_prev else "cd %here%"+ translated_path, path_abs = _translate_path(path)+ if not translated_path:+ # Unrooted grep — operate on lane cwd, no cd, no restore.+ return asyncio.run(+ _call_execute(f"grep {_q(pattern)}", use_daemon, session=session))- command = f"cd {_q(translated_path)}\ngrep {_q(pattern)}\n{restore}"- return asyncio.run(_call_execute(command, use_daemon, session=session))- return asyncio.run(- _call_execute(f"grep {_q(pattern)}", use_daemon, session=session)- )++ _assert_single_line("path", path)+ _assert_single_line("prev", prev)++ if path_abs:+ # Absolute path: anchor at `%here%/<target>`, grep, restore to the+ # harness's tracked working_dir (so the lane cwd doesn't drift).+ # The `%here%/<target>` token is quoted as a single unit by+ # `_here_path` — survives whitespace / shell metachars cleanly.+ cd_line = f"cd {_here_path(translated_path)}"+ restore = _restore_cwd_cmd(session)+ else:+ # Relative path: lane cwd is the right reference. `prev` defaults+ # to "/" — for relative grep we just go back to whatever caller+ # asked, shell-quoted (or `%here%/...` for absolute prev).+ translated_prev, prev_abs = _translate_path(prev)+ cd_line = f"cd {_q(translated_path)}"+ if prev_abs:+ restore = f"cd {_here_path(translated_prev)}"+ else:+ restore = (+ f"cd {_q(translated_prev)}"+ if translated_prev+ else f"cd {_here_path('')}"+ )+ command = f"{cd_line}\ngrep {_q(pattern)}\n{restore}"+ return asyncio.run(_call_execute(command, use_daemon, session=session))def click(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:@@ -535,14 +646,16 @@ def click(path: str, use_daemon: bool = False, *, session: Any = None) -> dict:>>> click("/main/button[0]"){"action": "click", "path": "/main/button[0]", "status": "success"}"""- translated = _translate_path(path)+ translated, is_absolute = _translate_path(path)if not translated:raise ValueError("click: an element name is required — cannot click the tab root.")- return asyncio.run(- _call_execute(f"click {_q(translated)}", use_daemon, session=session)- )+ if is_absolute:+ command = _wrap_absolute(f"click {_q(translated)}", session)+ else:+ command = f"click {_q(translated)}"+ return asyncio.run(_call_execute(command, use_daemon, session=session))def open_url(url: str, use_daemon: bool = False, *, session: Any = None) -> dict:@@ -644,18 +757,37 @@ def type_text("""_assert_single_line("path", path)_assert_single_line("text", text)- translated_path = _translate_path(path)++ # A session is required: the focus and type halves split across two+ # _call_execute calls, and without `session.domshell_lane_id` the+ # second call would land in a different DOMShell lane and miss the+ # focus state from the first.+ if session is None:+ raise ValueError(+ "type_text: a session argument is required so the focus and type "+ "calls share a DOMShell lane. Otherwise the focus state from the "+ "first call would not apply to the second."+ )++ translated_path, is_absolute = _translate_path(path)if not translated_path:raise ValueError(- "type_text: an element name is required — cannot focus the tab root."+ "type_text: an input path is required — cannot focus the tab root.")+# Relies on DOMShell serializing commands within a lane: the `type`# call below cannot be preempted by another agent's `focus` on the# same lane between these two _call_execute boundaries. If that# contract ever changes upstream, this needs to revert to a single# multi-line call with an alternative safety story.+ if is_absolute:+ # Anchor + focus + restore as one multi-line call, so the focus+ # lands against the tab root regardless of lane cwd drift.+ focus_cmd = _wrap_absolute(f"focus {_q(translated_path)}", session)+ else:+ focus_cmd = f"focus {_q(translated_path)}"focus_result = asyncio.run(_call_execute(- f"focus {_q(translated_path)}", use_daemon, session=session,+ focus_cmd, use_daemon, session=session,))if _is_error(focus_result):return focus_result # don't type — focus didn't land