text
stringlengths
0
1.47k
if self._client is None:
self._client = httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=5.0))
return self._client
def _headers(self) -> dict:
return {"X-Harness-Internal": self.key} if self.key else {}
async def read(self, sid: str, path: str) -> bytes | None:
member = _safe_member(path)
if not member or not self.endpoint:
return None
try:
r = await self._c().get(f"{self.endpoint}/file", params={"identifier": sid, "path": member},
headers=self._headers())
except Exception: # noqa: BLE001 — a runner that is down reads as "no file", never a 500
return None
return r.content if r.status_code == 200 else None
async def write(self, sid: str, path: str, data: bytes) -> bool:
member = _safe_member(path)
if not member or not self.endpoint:
return False
try:
r = await self._c().put(f"{self.endpoint}/file", params={"identifier": sid, "path": member},
headers={**self._headers(), "content-type": "application/octet-stream"},
content=data)
except Exception: # noqa: BLE001
return False
if r.status_code != 200:
return False
await self._capture(sid, member, data)
return True
async def _capture(self, sid: str, member: str, data: bytes) -> None:
"""Persist the app's copy of this file so it outlives the live directory.
THIS is why the class takes a blob store. The live workspace is reaped after
HR_WORKSPACE_TTL_HOURS and is only ever refreshed by a TURN's checkpoint, so a file an app
wrote BETWEEN turns lived in exactly one place and was deleted with it: a sheet somebody
typed into and never asked the agent about again came back empty, and so did every agent
column they had bound by hand. The hosted sibling writes straight into the durable tarball
and never had the hole, which is the tell — one Protocol, two meanings for `write`.
The id is derived from the path, so a sheet saved a thousand times keeps ONE blob instead
of leaking one per save. `written_at` is what makes the read side deterministic: the
agent's own capture of the same filename carries one too, and the newer of the two wins
rather than whichever the blob listing happened to return last."""
if not self.blob or not self.kb:
return
cfile = "cfile_" + hashlib.sha256(f"app:{member}".encode()).hexdigest()[:32]
meta = json.dumps({"filename": member,
"media_type": mimetypes.guess_type(member)[0] or "application/octet-stream",
"written_at": time.time(),
"source": "app"}).encode()
try:
if await self.blob.put(self.kb, f"containers/{sid}/{cfile}", data):
await self.blob.put(self.kb, f"containers/{sid}/{cfile}.meta", meta)
return
except Exception as e: # noqa: BLE001
print(f"[workspace] durable capture failed sid={sid} path={member}: {e}", flush=True)
return
# A live write that was not captured is the old silent-loss shape. Say so rather than
# letting it look like a clean save.
print(f"[workspace] durable capture rejected sid={sid} path={member}", flush=True)
class CheckpointWorkspaceFiles:
"""Hosted: between turns the workspace is only the checkpoint tarball, so a write rewrites
that archive — copy every member across, substituting the one being written.
Rewriting rather than appending is deliberate: tar allows duplicate names and readers take the
LAST one, so appending would work until something read the archive differently, and the bug
would be a stale file appearing at random."""
def __init__(self, blob, kb: str, key_for):
self.blob, self.kb, self.key_for = blob, kb, key_for
async def read(self, sid: str, path: str) -> bytes | None:
member = _safe_member(path)
if not member:
return None
raw = await self.blob.get(self.kb, self.key_for(sid))
if not raw:
return None
def _extract() -> bytes | None:
with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tf:
for name in (member, f"./{member}"):
try:
f = tf.extractfile(name)
except KeyError:
continue
if f:
return f.read()
return None
try:
return await asyncio.to_thread(_extract)
except Exception: # noqa: BLE001 — a corrupt archive reads as "not there"
return None