okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221integrations/harness: the Strata profile and the agent bridge090e45adf

main
8.5 KiB191 linesraw
1#!/usr/bin/env python3
2"""One bounded Harness revision attempt, for Time-skip's `--revise-command`.
3
4Time-skip owns the job: it checkpoints, isolates a candidate directory, and decides from checks.
5This script owns only the *revision step* — it asks the pinned DeepSeek Harness for one bounded
6agent turn inside the candidate directory and returns when the turn reaches a terminal state.
7
8```
9strata timeskip run --workspace DIR --prompt "..." \
10    --revise-command "python integrations/harness/revise_once.py"
11```
12
13The contract Time-skip depends on:
14
15* the process runs with the **candidate directory** as its cwd, and only ever writes there;
16* the prompt arrives in `STRATA_TIMESKIP_PROMPT` and the attempt number in `STRATA_TIMESKIP_ATTEMPT`;
17* exit 0 means "an attempt was made" — *not* "the attempt succeeded". Whether it improved anything is
18  decided by the checks, never by this script. A non-zero exit reports that the attempt itself could
19  not be made (for example the Harness is not installed), which Time-skip records as a failed run
20  rather than a rejected candidate.
21
22A bounded turn means all of: a wall-clock deadline, a per-attempt session, and a Harness that is
23stopped when the deadline passes — so a stuck agent cannot hold a Time-skip run open forever.
24"""
25
26from __future__ import annotations
27
28import argparse
29import json
30import os
31import re
32import shutil
33import signal
34import subprocess
35import sys
36import tempfile
37import time
38from pathlib import Path
39
40HERE = Path(__file__).resolve().parent
41sys.path.insert(0, str(HERE))
42
43from _bridge import (  # noqa: E402
44    DEFAULT_DSH,
45    PROFILE_PATCH,
46    BridgeError,
47    gateway_call,
48    http_json,
49    read_session_events,
50    wait_for_agent_url,
51)
52
53#: The whole attempt's wall-clock bound. Time-skip's own phases are unbounded by design; the bound
54#: belongs to the thing that can run away, which is the agent turn.
55DEFAULT_DEADLINE_S = 240.0
56
57INSTRUCTIONS = """You are revising a copy of a user's work. Follow these rules exactly.
58
591. Work only inside the current directory. It is an isolated copy: the user's original is safe and
60   you cannot see it. Never try to read or write outside this directory.
612. Make the smallest change that achieves the goal. Do not reorganise, rename or reformat anything
62   that is not needed for the goal.
633. Do not add commentary files, notes, README files or explanations of what you did. Change the
64   work itself.
654. If the goal cannot be achieved from what is here, change nothing and say so in one sentence.
66
67When you are finished, reply with a single short sentence describing what you changed."""
68
69
70def main() -> int:
71    ap = argparse.ArgumentParser(description=__doc__,
72                                 formatter_class=argparse.RawDescriptionHelpFormatter)
73    ap.add_argument("--dsh", default=os.environ.get("DSH_CLI", DEFAULT_DSH))
74    ap.add_argument("--workspace", default=None,
75                    help="the candidate directory (default: the current directory)")
76    ap.add_argument("--deadline", type=float,
77                    default=float(os.environ.get("STRATA_TIMESKIP_DEADLINE_S", DEFAULT_DEADLINE_S)))
78    ap.add_argument("--keep", action="store_true",
79                    help="keep the per-attempt Harness home for inspection")
80    ap.add_argument("--print-session", action="store_true",
81                    help="print the session id and its event types, for diagnosis")
82    args = ap.parse_args()
83
84    candidate = Path(args.workspace or os.getcwd()).resolve()
85    prompt = os.environ.get("STRATA_TIMESKIP_PROMPT", "").strip()
86    attempt = os.environ.get("STRATA_TIMESKIP_ATTEMPT", "1")
87    if not prompt:
88        print("revise_once: STRATA_TIMESKIP_PROMPT is empty; nothing to ask for", file=sys.stderr)
89        return 2
90    if not candidate.is_dir():
91        print(f"revise_once: {candidate} is not a directory", file=sys.stderr)
92        return 2
93
94    dsh = Path(args.dsh)
95    if not dsh.exists():
96        print(f"revise_once: the Harness CLI is not at {dsh}; set DSH_CLI or --dsh", file=sys.stderr)
97        return 3
98    if not PROFILE_PATCH.exists():
99        print(f"revise_once: the Strata profile is not at {PROFILE_PATCH}", file=sys.stderr)
100        return 3
101
102    # Each attempt gets its own Harness home. That keeps sessions and approvals scoped to the
103    # attempt, and means a crashed attempt cannot corrupt the next one's state.
104    home = Path(tempfile.mkdtemp(prefix=f"strata-revise-a{attempt}-"))
105    (home / "sessions").mkdir(parents=True, exist_ok=True)
106    agent = None
107    deadline = time.time() + args.deadline
108    try:
109        env = dict(os.environ)
110        env["DSH_HOME"] = str(home)
111        log = (home / "dsh.log").open("w")
112        agent = subprocess.Popen(
113            [str(dsh), "--profile", "web", "--patch", str(PROFILE_PATCH), "--port", "0", "--no-open"],
114            cwd=str(candidate), env=env, stdout=log, stderr=subprocess.STDOUT)
115        text = wait_for_agent_url(home / "dsh.log", agent, timeout=min(120.0, args.deadline))
116        m = re.search(r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)", text)
117        if not m:
118            raise BridgeError("the Harness printed no usable URL")
119        port, token = int(m.group(1)), m.group(2)
120
121        # `interactions=answer` is required, or every approval request fails closed as
122        # 'unavailable'. A revision attempt that needs to run a command must be able to be approved.
123        _, _, set_cookie = http_json("GET", "127.0.0.1", port,
124                                     f"/?token={token}&interactions=answer")
125        cookie = set_cookie.split(";", 1)[0]
126        if not cookie.startswith("dsh-auth-"):
127            raise BridgeError("no operator cookie was issued")
128
129        created = gateway_call("127.0.0.1", port, cookie, "c1", "session/create",
130                               {"request": {"cwd": str(candidate)}})
131        session_id = created["sessionId"]
132        gateway_call("127.0.0.1", port, cookie, "p1", "session/prompt",
133                     {"request": {"requestId": f"timeskip-{attempt}", "sessionId": session_id,
134                                  "mode": "queue",
135                                  "content": [{"type": "text",
136                                               "text": f"{INSTRUCTIONS}\n\nGoal:\n{prompt}"}]}})
137
138        # Wait for a terminal state, or the deadline, whichever comes first.
139        events: list[dict] = []
140        note = ""
141        while time.time() < deadline:
142            events = read_session_events(session_id, home=home)
143            end = next((e for e in events if e.get("type") == "turn/end"), None)
144            if end is not None:
145                reason = (end.get("data") or {}).get("reason") or {}
146                if reason.get("kind") != "completed":
147                    print(f"revise_once: the turn ended as {json.dumps(reason)[:200]}", file=sys.stderr)
148                    return 1
149                assistant = next((e for e in events if e.get("type") == "assistant/message"), None)
150                if assistant:
151                    message = (assistant.get("data") or {}).get("message") or {}
152                    parts = message.get("content") or []
153                    note = " ".join(p.get("text", "") for p in parts
154                                    if isinstance(p, dict) and p.get("type") in ("text", "reasoning"))
155                break
156            time.sleep(0.5)
157        else:
158            print(f"revise_once: the attempt did not finish within {args.deadline:.0f}s; "
159                  "stopping the Harness and reporting a made attempt", file=sys.stderr)
160            return 1
161
162        if args.print_session:
163            print(f"session {session_id}: {[e.get('type') for e in events]}", file=sys.stderr)
164        # Exit 0 means an attempt was made. What it achieved is the checks' business.
165        print((note or f"attempt {attempt} completed").strip()[:500])
166        return 0
167
168    except BridgeError as e:
169        print(f"revise_once: {e}", file=sys.stderr)
170        return 1
171    except Exception as e:  # noqa: BLE001 - report, and let Time-skip record a failed run
172        print(f"revise_once: {type(e).__name__}: {e}", file=sys.stderr)
173        return 1
174    finally:
175        if agent is not None and agent.poll() is None:
176            try:
177                agent.send_signal(signal.SIGTERM)
178                agent.wait(timeout=8)
179            except Exception:
180                try:
181                    agent.kill()
182                except Exception:
183                    pass
184        if not args.keep:
185            shutil.rmtree(home, ignore_errors=True)
186        else:
187            print(f"revise_once: kept {home}", file=sys.stderr)
188
189
190if __name__ == "__main__":
191    sys.exit(main())