Something went wrong. Try again.
fork of prime agent with changes i want but are not upstreamable probqbly (and some fixes)
Something went wrong. Try again.
10 kB · 300 lines
TypeScript
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301import { describe, expect, it } from "vitest";import { previewBashCommand, previewIpythonCode, previewPythonCode } from "../src/core/tools/code-preview.js";
describe("code preview", () => { it("skips bash setup and previews the real command", () => { expect(previewBashCommand("set -e\nnpm run check")).toEqual({ language: "bash", text: "npm check" }); });
it("simplifies common runner wrappers", () => { expect( previewBashCommand("npx tsx ../../node_modules/vitest/dist/cli.js --run test/code-preview.test.ts"), ).toEqual({ language: "bash", text: "vitest --run test/code-preview.test.ts", }); });
it("unwraps python heredocs in bash", () => { const command = `set -epython3 - <<'PY'from pathlib import Pathpath = Path("package.json")text = path.read_text()path.write_text(text)PY`; expect(previewBashCommand(command)).toEqual({ language: "python", text: "path.write_text(text)" }); });
it("unwraps bash cells in ipython", () => { const code = `%%bashset -epython3 - <<'PY'import jsondata = json.loads("{}")print(data.keys())PY`; expect(previewIpythonCode(code)).toEqual({ language: "python", text: "data.keys()" }); });
it("prefers meaningful python effects over setup assignments", () => { const code = `from pathlib import Pathp = Path("packages/coding-agent/src/modes/interactive/components/ipython-cell.ts")txt = p.read_text()p.write_text(txt.replace("old", "new"))`; expect(previewPythonCode(code)).toEqual({ language: "python", text: "write packages/coding-agent/src/modes/interactive/components/ip…", }); });
it("handles stronger bash heuristics", () => { expect(previewBashCommand("cd packages/coding-agent && npm --prefix ../.. run check")).toEqual({ language: "bash", text: "npm check (../..)", }); expect(previewBashCommand("echo setup\ngit add packages/foo.ts")).toEqual({ language: "bash", text: "git add packages/foo.ts", }); expect(previewBashCommand("cat > packages/foo.ts <<'EOF'\nhello\nEOF")).toEqual({ language: "bash", text: "write packages/foo.ts", }); });
it("extracts python subprocesses and control-block effects", () => { const subprocessCode = `import subprocesssubprocess.run(["npm", "run", "check"])`; expect(previewPythonCode(subprocessCode)).toEqual({ language: "python", text: "npm check" });
const controlCode = `from pathlib import Pathp = Path("packages/foo.ts")if p.exists(): p.unlink()`; expect(previewPythonCode(controlCode)).toEqual({ language: "python", text: "delete packages/foo.ts" }); });
it("prefers executable calls over helper definitions", () => { const code = `def helper(): return 1run_check()`; expect(previewPythonCode(code)).toEqual({ language: "python", text: "run_check()" }); });
it("redacts sensitive python preview values", () => { expect(previewPythonCode('password = "supersecretvalue"')).toEqual({ language: "python", text: "password=<redacted>", }); expect(previewPythonCode('client = OpenAI(api_key="sk-testsecretvalue")')).toEqual({ language: "python", text: "client = OpenAI(api_key=<redacted>)", }); });
it("falls back when heredoc has no useful preview", () => { const command = `npm run checkpython3 - <<'PY'import jsonfrom pathlib import PathPY`; expect(previewBashCommand(command)).toEqual({ language: "bash", text: "npm check" }); });
it("continues past empty python heredocs", () => { const command = `python3 - <<'PY'import jsonfrom pathlib import PathPYpython3 - <<'PY'from pathlib import Pathp = Path("packages/foo.ts")p.write_text("hello")PY`; expect(previewBashCommand(command)).toEqual({ language: "python", text: "write packages/foo.ts" }); });
it("does not treat a .sh script path as an inline bash heredoc", () => { const command = `./script.sh <<'EOF'hello worldEOF`; expect(previewBashCommand(command)).toEqual({ language: "bash", text: "hello world" }); });
it("routes bash-skill calls with literal commands to the bash preview", () => { expect(previewIpythonCode("r = await bash('git status --porcelain')")).toEqual({ language: "bash", text: "git status --porcelain", }); const longCommand = `git log --oneline -- ${Array.from({ length: 8 }, (_, i) => `packages/coding-agent/src/dir-${i}`).join(" ")}`; const longPreview = previewIpythonCode(`result = await bash("${longCommand}", timeout=120)`); expect(longPreview.language).toBe("bash"); expect(longPreview.text.startsWith("git log --oneline")).toBe(true); const scorer = `import jsonr = await bash('git diff --stat')print(r)`; expect(previewIpythonCode(scorer)).toEqual({ language: "bash", text: "git diff --stat" }); expect( previewIpythonCode(`r = await bash('curl -H "Authorization: Bearer sec-abc123" https://api.example.com')`) .text, ).not.toContain("sec-abc123"); });
it("evaluates bash-skill literals the way python does", () => { const tripleBody = `r = await bash('''set -egit add packages/foo.ts''')`; expect(previewIpythonCode(tripleBody)).toEqual({ language: "bash", text: "git add packages/foo.ts" }); expect(previewIpythonCode("r = await bash('printf \"a\\nb\"\\ngit add -A')")).toEqual({ language: "bash", text: "git add -A", }); expect(previewIpythonCode("r = await bash('echo can\\'t stop')")).toEqual({ language: "bash", text: "echo can't stop", }); expect(previewIpythonCode('r = await bash("grep -n \\")\\" src.c")')).toEqual({ language: "bash", text: 'grep -n ")" src.c', }); expect(previewIpythonCode("r = await bash('''echo it\\'''')")).toEqual({ language: "bash", text: "echo it'" }); expect(previewIpythonCode("r = await bash(r'grep \\'x\\' f')")).toEqual({ language: "bash", text: "grep \\'x\\' f", }); });
it("keeps the python preview when the exact command cannot be known", () => { for (const code of [ "r = await bash(cmd)", 'r = await bash(f"git checkout {branch}")', "r = await bash('echo ' + name)", "r = await bash('echo hi\n)", // unterminated literal: python syntax error "r = await bash('echo \\x41')", // value-changing escape not computed here "r = await bash('grep \\bword\\b f')", ]) { expect(previewIpythonCode(code).language).toBe("python"); } });
it("keeps the python preview for bash-looking text inside a multiline string", () => { expect(previewIpythonCode('doc = """\nbash("git status")\n"""')).toEqual({ language: "python", text: 'doc = """', }); expect(previewIpythonCode(`doc = """usage"""\nr = await bash('git status')`)).toEqual({ language: "bash", text: "git status", }); });
it("prefers a later meaningful heredoc over an earlier generic one", () => { const command = `cat <<'CFG'key=valueCFGpython3 - <<'PY'from pathlib import Pathp = Path("packages/foo.ts")p.write_text("hello")PY`; expect(previewBashCommand(command)).toEqual({ language: "python", text: "write packages/foo.ts" }); });
it("never shows a standalone break or continue from loops", () => { const loopWithEarlyExit = `remote_init_code = Path("prime-agent-runtime/src/remote/__init__.py").read_text()for idx, line in enumerate(remote_init_code.splitlines()): if "target" in line: break`; expect(previewPythonCode(loopWithEarlyExit)).toEqual({ language: "python", text: "read prime-agent-runtime/src/remote/__init__.py", });
const pureControl = `for idx, line in enumerate(lines): if "target" in line: break`; expect(previewPythonCode(pureControl)).toEqual({ language: "python", text: 'if "target" in line: break', }); });
it("demotes sleeps so polling loops and setup commands win", () => { const pollingLoop = `sb_handle = bash("pnpm --dir web storybook --ci --port 6006")for i in range(15): await asyncio.sleep(2) poll = await bash("curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:6006/") if poll.text() == "200": break`; expect(previewPythonCode(pollingLoop)).toEqual({ language: "bash", text: "pnpm storybook --ci --port 6006 (web)", });
const sleepOnly = "await asyncio.sleep(90)"; expect(previewPythonCode(sleepOnly)).toEqual({ language: "python", text: "await asyncio.sleep(90)", }); });
it("previews inline Path, open, and with-open file operations", () => { expect(previewPythonCode('src = Path("packages/ai/src/index.ts").read_text()')).toEqual({ language: "python", text: "read packages/ai/src/index.ts", }); expect(previewPythonCode('open("web/src/lib/bones/fixture.json", "w").write(data)')).toEqual({ language: "python", text: "write web/src/lib/bones/fixture.json", }); const withOpen = `with open("web/src/lib/bones/repo-pulls.bones.json") as f: data = json.load(f)`; expect(previewPythonCode(withOpen)).toEqual({ language: "python", text: "read web/src/lib/bones/repo-pulls.bones.json", }); });
it("previews skill module calls for edit, search, git, jj, and rlm", () => { expect( previewPythonCode( 'await edit(path="packages/coding-agent/src/core/tools/code-preview.ts", old_str=old, new_str=new)', ), ).toEqual({ language: "python", text: "edit packages/coding-agent/src/core/tools/code-preview.ts", });
expect(previewPythonCode('res = await search("previewIpythonCode", path="packages")')).toEqual({ language: "python", text: 'search "previewIpythonCode" (packages)', });
expect(previewPythonCode("status = await git.status()")).toEqual({ language: "python", text: "git status", });
expect(previewPythonCode("diff = await jj.diff()")).toEqual({ language: "python", text: "jj diff", });
expect(previewPythonCode('handle = await rlm("audit api endpoints", name="api-auditor")')).toEqual({ language: "python", text: "subagent api-auditor", }); });
it("demotes browser cleanup calls so primary actions win", () => { const browserAction = `print("title:", await page.evaluate("() => document.title"))await asyncio.sleep(2)await browser.close()`; expect(previewPythonCode(browserAction).text).not.toContain("browser.close"); });});