scoperail 0.3.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.
- bridge/__init__.py +8 -0
- bridge/__main__.py +110 -0
- bridge/admin.py +156 -0
- bridge/agent_outcomes.py +156 -0
- bridge/agents.py +838 -0
- bridge/audit_export.py +242 -0
- bridge/auth.py +336 -0
- bridge/browser.py +704 -0
- bridge/browser_broker.py +122 -0
- bridge/coding.py +421 -0
- bridge/config.py +173 -0
- bridge/db.py +95 -0
- bridge/desktop.py +245 -0
- bridge/execution_review.py +291 -0
- bridge/files.py +537 -0
- bridge/gitops.py +120 -0
- bridge/homelab.py +289 -0
- bridge/humanize.py +188 -0
- bridge/jobs.py +489 -0
- bridge/outline.py +132 -0
- bridge/pipelines.py +309 -0
- bridge/policy.py +296 -0
- bridge/public_cli.py +142 -0
- bridge/semantic_ui.py +1058 -0
- bridge/server.py +1484 -0
- bridge/shells.py +378 -0
- bridge/state.py +55 -0
- bridge/stdio.py +36 -0
- bridge/takeover.py +684 -0
- bridge/viewport.py +111 -0
- scoperail-0.3.0.dist-info/METADATA +149 -0
- scoperail-0.3.0.dist-info/RECORD +36 -0
- scoperail-0.3.0.dist-info/WHEEL +5 -0
- scoperail-0.3.0.dist-info/entry_points.txt +3 -0
- scoperail-0.3.0.dist-info/licenses/LICENSE +201 -0
- scoperail-0.3.0.dist-info/top_level.txt +1 -0
bridge/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""ScopeRail: local MCP runtime for the user's current ChatGPT session.
|
|
2
|
+
|
|
3
|
+
The server exposes auditable files/process/Git/browser/macOS-UI primitives plus
|
|
4
|
+
persistent shells, state and deterministic orchestration. It contains no model API
|
|
5
|
+
client: model reasoning remains in the active ChatGPT session or explicit
|
|
6
|
+
chatgpt.com sub-conversations.
|
|
7
|
+
"""
|
|
8
|
+
__version__ = "0.3.0"
|
bridge/__main__.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Entry point: `python -m bridge` runs the public MCP app (loopback, proxied by Funnel) and the loopback admin app
|
|
2
|
+
in one asyncio loop, plus the plain-process scheduler thread. Managed by launchd (io.github.hanpuli.scoperail; the old label is accepted during upgrades)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
import asyncio, logging, os, signal, subprocess, sys, threading, time
|
|
5
|
+
import uvicorn
|
|
6
|
+
from .config import load_config, LOGS_DIR, ensure_dirs
|
|
7
|
+
from . import jobs, db
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _activity_sidecar_supervisor(stop: threading.Event, executable: str) -> None:
|
|
11
|
+
"""Supervise an optional operator-configured sidecar without baking machine paths into source.
|
|
12
|
+
|
|
13
|
+
This exists for integrations that need to inherit the bridge process's macOS TCC identity.
|
|
14
|
+
The executable path comes only from local config and is never exposed as an MCP capability.
|
|
15
|
+
"""
|
|
16
|
+
path = os.path.abspath(os.path.expanduser(executable))
|
|
17
|
+
if not os.path.isfile(path) or not os.access(path, os.X_OK):
|
|
18
|
+
logging.warning("configured activity sidecar is unavailable: %s", path)
|
|
19
|
+
return
|
|
20
|
+
|
|
21
|
+
while not stop.is_set():
|
|
22
|
+
proc = None
|
|
23
|
+
try:
|
|
24
|
+
proc = subprocess.Popen(
|
|
25
|
+
[path],
|
|
26
|
+
stdin=subprocess.DEVNULL,
|
|
27
|
+
stdout=subprocess.DEVNULL,
|
|
28
|
+
stderr=subprocess.DEVNULL,
|
|
29
|
+
close_fds=True,
|
|
30
|
+
)
|
|
31
|
+
logging.info("activity sidecar started pid=%s", proc.pid)
|
|
32
|
+
while not stop.wait(1.0):
|
|
33
|
+
rc = proc.poll()
|
|
34
|
+
if rc is not None:
|
|
35
|
+
logging.warning("activity sidecar exited rc=%s; restarting", rc)
|
|
36
|
+
break
|
|
37
|
+
if stop.is_set() and proc.poll() is None:
|
|
38
|
+
proc.terminate()
|
|
39
|
+
try:
|
|
40
|
+
proc.wait(timeout=3)
|
|
41
|
+
except subprocess.TimeoutExpired:
|
|
42
|
+
proc.kill()
|
|
43
|
+
proc.wait(timeout=2)
|
|
44
|
+
break
|
|
45
|
+
except Exception:
|
|
46
|
+
logging.exception("activity sidecar supervisor error")
|
|
47
|
+
finally:
|
|
48
|
+
if proc is not None and proc.poll() is None and stop.is_set():
|
|
49
|
+
try:
|
|
50
|
+
proc.terminate()
|
|
51
|
+
except OSError:
|
|
52
|
+
pass
|
|
53
|
+
if not stop.wait(5.0):
|
|
54
|
+
continue
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def main() -> None:
|
|
58
|
+
ensure_dirs()
|
|
59
|
+
cfg = load_config()
|
|
60
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s", stream=sys.stderr)
|
|
61
|
+
for note in jobs.recover_on_startup():
|
|
62
|
+
logging.info("recovered job: %s", note)
|
|
63
|
+
from . import agents
|
|
64
|
+
for note in agents.recover_on_startup():
|
|
65
|
+
logging.info("interrupted sub-agent run: %s", note)
|
|
66
|
+
from . import pipelines
|
|
67
|
+
for note in pipelines.recover_on_startup():
|
|
68
|
+
logging.info("interrupted pipeline: %s", note)
|
|
69
|
+
from . import coding
|
|
70
|
+
for note in coding.recover_on_startup():
|
|
71
|
+
logging.info("interrupted coding task: %s", note)
|
|
72
|
+
from .server import build_app, scheduler_loop
|
|
73
|
+
from .admin import build_admin_app
|
|
74
|
+
stop = threading.Event()
|
|
75
|
+
threading.Thread(target=scheduler_loop, args=(stop,), daemon=True).start()
|
|
76
|
+
sidecar_thread = None
|
|
77
|
+
if cfg.get("activity_sidecar"):
|
|
78
|
+
sidecar_thread = threading.Thread(
|
|
79
|
+
target=_activity_sidecar_supervisor,
|
|
80
|
+
args=(stop, str(cfg["activity_sidecar"])),
|
|
81
|
+
daemon=True,
|
|
82
|
+
name="scoperail-sidecar",
|
|
83
|
+
)
|
|
84
|
+
sidecar_thread.start()
|
|
85
|
+
public = uvicorn.Server(uvicorn.Config(build_app(), host=cfg["listen_host"], port=cfg["listen_port"], log_level="info", proxy_headers=True, access_log=False,
|
|
86
|
+
forwarded_allow_ips="127.0.0.1", timeout_keep_alive=75))
|
|
87
|
+
admin = uvicorn.Server(uvicorn.Config(build_admin_app(), host=cfg["admin_host"], port=cfg["admin_port"], log_level="warning", access_log=False))
|
|
88
|
+
db.audit("server", f"start pid={os.getpid()} public={cfg['listen_port']} admin={cfg['admin_port']}")
|
|
89
|
+
|
|
90
|
+
async def run():
|
|
91
|
+
from . import browser_broker, takeover
|
|
92
|
+
broker = asyncio.create_task(browser_broker.serve())
|
|
93
|
+
handover = asyncio.create_task(takeover.serve()) # same loop as the browser: Playwright objects belong to it
|
|
94
|
+
try:
|
|
95
|
+
await asyncio.gather(public.serve(), admin.serve())
|
|
96
|
+
finally:
|
|
97
|
+
broker.cancel()
|
|
98
|
+
handover.cancel()
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
asyncio.run(run())
|
|
102
|
+
finally:
|
|
103
|
+
stop.set()
|
|
104
|
+
if sidecar_thread:
|
|
105
|
+
sidecar_thread.join(timeout=4)
|
|
106
|
+
db.audit("server", f"stop pid={os.getpid()}")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
if __name__ == "__main__":
|
|
110
|
+
main()
|
bridge/admin.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Loopback-only admin channel (127.0.0.1:<admin_port>, bearer = ~/.scoperail/secrets/admin.token, mode 0600).
|
|
2
|
+
It is never proxied by Funnel and is blocked from the managed browser. Everything here is a user decision made on the Mac:
|
|
3
|
+
workspaces, grants, token revocation, job control, kill switch. Remote (OAuth) identities cannot reach it."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
import hmac, json, os, shutil, subprocess, time
|
|
6
|
+
from starlette.applications import Starlette
|
|
7
|
+
from starlette.requests import Request
|
|
8
|
+
from starlette.responses import JSONResponse
|
|
9
|
+
from starlette.routing import Route
|
|
10
|
+
from . import db, policy, jobs, auth, browser, agents, pipelines, coding, shells
|
|
11
|
+
from .config import admin_token, load_config, STATE_DIR
|
|
12
|
+
|
|
13
|
+
CFG = load_config()
|
|
14
|
+
TS = next((
|
|
15
|
+
p for p in (
|
|
16
|
+
shutil.which("tailscale"),
|
|
17
|
+
"/usr/local/bin/tailscale",
|
|
18
|
+
"/opt/homebrew/bin/tailscale",
|
|
19
|
+
) if p and os.path.exists(p)
|
|
20
|
+
), None)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _authed(request: Request) -> bool:
|
|
24
|
+
h = request.headers.get("authorization", "")
|
|
25
|
+
return h.startswith("Bearer ") and hmac.compare_digest(h[7:], admin_token())
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _funnel_mounts() -> list[str]:
|
|
29
|
+
return [CFG["funnel_path"], *CFG.get("funnel_wellknown_paths", [])]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _funnel(action: str) -> dict:
|
|
33
|
+
"""Manage only the bridge's configured Funnel path mounts; unrelated mounts are untouched."""
|
|
34
|
+
if not TS:
|
|
35
|
+
return {"error": "tailscale executable not found", "rc": 127, "mounts": _funnel_mounts()}
|
|
36
|
+
port = str(CFG["funnel_port"])
|
|
37
|
+
if action == "status":
|
|
38
|
+
r = subprocess.run([TS, "funnel", "status", "--json"], capture_output=True, text=True, timeout=20)
|
|
39
|
+
return {"raw": r.stdout[:4000], "rc": r.returncode, "mounts": _funnel_mounts()}
|
|
40
|
+
if action not in ("on", "off"):
|
|
41
|
+
return {"error": "bad action"}
|
|
42
|
+
results = []
|
|
43
|
+
for mount in _funnel_mounts():
|
|
44
|
+
target = f"http://127.0.0.1:{CFG['listen_port']}" if action == "on" else "off"
|
|
45
|
+
r = subprocess.run([TS, "funnel", "--bg", "--yes", f"--https={port}", f"--set-path={mount}", target],
|
|
46
|
+
capture_output=True, text=True, timeout=30)
|
|
47
|
+
results.append({"mount": mount, "rc": r.returncode, "stdout": r.stdout[-500:], "stderr": r.stderr[-500:]})
|
|
48
|
+
return {"rc": max(x["rc"] for x in results), "mounts": results}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
async def handle(request: Request):
|
|
52
|
+
if not _authed(request):
|
|
53
|
+
return JSONResponse({"error": "unauthorized"}, 401)
|
|
54
|
+
op = request.path_params["op"]
|
|
55
|
+
body = {}
|
|
56
|
+
if request.method == "POST":
|
|
57
|
+
try:
|
|
58
|
+
body = await request.json()
|
|
59
|
+
except Exception:
|
|
60
|
+
body = {}
|
|
61
|
+
try:
|
|
62
|
+
if op == "status":
|
|
63
|
+
active = [j for j in jobs.list_jobs(limit=500) if j["status"] in jobs.STATUS_ACTIVE]
|
|
64
|
+
tokens = db.one("SELECT COUNT(*) c FROM tokens WHERE revoked=0 AND kind='access' AND expires_at>?", time.time())["c"]
|
|
65
|
+
clients = db.one("SELECT COUNT(*) c FROM oauth_clients")["c"]
|
|
66
|
+
return JSONResponse({"ok": True, "pid": os.getpid(), "state_dir": str(STATE_DIR), "workspaces": policy.workspace_list(True),
|
|
67
|
+
"active_jobs": active, "active_agents": [a for a in agents.list_runs(limit=100) if a["status"] in agents.STATUS_ACTIVE], "live_access_tokens": tokens, "oauth_clients": clients,
|
|
68
|
+
"login_configured": auth.passphrase_configured(), "browser_pages": browser.list_pages(), "public_url": CFG["public_url"]})
|
|
69
|
+
if op == "workspace_add":
|
|
70
|
+
return JSONResponse({"ok": True, "workspace": policy.workspace_add(body["root"], body.get("name") or os.path.basename(body["root"]),
|
|
71
|
+
body.get("profiles") or ["sandboxed"], body.get("network", "off"), body.get("days", 30), body.get("notes", ""))})
|
|
72
|
+
if op == "workspace_revoke":
|
|
73
|
+
policy.workspace_revoke(body["id"]); return JSONResponse({"ok": True})
|
|
74
|
+
if op == "workspace_profiles":
|
|
75
|
+
w = policy.workspace_get(body["id"], check=False)
|
|
76
|
+
profs = set(w["profiles"]) | set(body.get("add", [])); profs -= set(body.get("remove", []))
|
|
77
|
+
db.q("UPDATE workspaces SET profiles=?, network=COALESCE(?, network), revoked=0 WHERE id=?", json.dumps(sorted(profs)), body.get("network"), body["id"])
|
|
78
|
+
return JSONResponse({"ok": True, "workspace": policy.workspace_get(body["id"], check=False)})
|
|
79
|
+
if op == "grant_add":
|
|
80
|
+
return JSONResponse({"ok": True, "grant": policy.grant_add(body["workspace_id"], body["kind"], body.get("params", {}), body.get("hours", 24), body.get("max_uses"))})
|
|
81
|
+
if op == "grant_list":
|
|
82
|
+
return JSONResponse({"ok": True, "grants": policy.grant_list(body.get("workspace_id"))})
|
|
83
|
+
if op == "grant_revoke":
|
|
84
|
+
policy.grant_revoke(body["id"]); return JSONResponse({"ok": True})
|
|
85
|
+
if op == "tokens_revoke_all":
|
|
86
|
+
return JSONResponse({"ok": True, "revoked": auth.revoke_all_tokens()})
|
|
87
|
+
if op == "tokens_list":
|
|
88
|
+
rows = db.all_("SELECT client_id, subject, kind, expires_at, revoked, created_at FROM tokens ORDER BY created_at DESC LIMIT 50")
|
|
89
|
+
return JSONResponse({"ok": True, "tokens": [dict(r) for r in rows]})
|
|
90
|
+
if op == "clients_list":
|
|
91
|
+
rows = db.all_("SELECT client_id, data, created_at FROM oauth_clients")
|
|
92
|
+
return JSONResponse({"ok": True, "clients": [{"client_id": r["client_id"], "name": json.loads(r["data"]).get("client_name"), "redirect_uris": json.loads(r["data"]).get("redirect_uris"), "created_at": r["created_at"]} for r in rows]})
|
|
93
|
+
if op == "jobs":
|
|
94
|
+
return JSONResponse({"ok": True, "jobs": jobs.list_jobs(body.get("workspace_id"), body.get("limit", 50))})
|
|
95
|
+
if op == "job_cancel":
|
|
96
|
+
return JSONResponse({"ok": True, "job": jobs.cancel(body["id"], "admin")})
|
|
97
|
+
if op == "desktop_permissions":
|
|
98
|
+
from . import desktop
|
|
99
|
+
return JSONResponse({"ok": True, **(desktop.request_permissions() if body.get("request") else desktop.permissions())})
|
|
100
|
+
if op == "agents":
|
|
101
|
+
return JSONResponse({"ok": True, "runs": agents.list_runs(body.get("workspace_id"), body.get("limit", 50))})
|
|
102
|
+
if op == "pipelines":
|
|
103
|
+
return JSONResponse({"ok": True, "pipelines": pipelines.list_pipelines(body.get("workspace_id"), body.get("limit", 20))})
|
|
104
|
+
if op == "coding_tasks":
|
|
105
|
+
return JSONResponse({"ok": True, "tasks": coding.list_tasks(body.get("workspace_id"), body.get("limit", 20))})
|
|
106
|
+
if op == "coding_task":
|
|
107
|
+
return JSONResponse({"ok": True, "task": coding.info(body["id"])})
|
|
108
|
+
if op == "coding_task_start":
|
|
109
|
+
t = coding.start(body["workspace_id"], body["task"], body.get("repo_path", "."), body.get("test_command"), body.get("max_rounds", 3), body.get("effort", "extra_high"),
|
|
110
|
+
body.get("agent"), body.get("profile"), body.get("agent_timeout_seconds"), body.get("test_timeout_seconds", 900), body.get("baseline", True),
|
|
111
|
+
body.get("branch"), body.get("browser_sites"), body.get("notes"), body.get("protected_paths"), "admin")
|
|
112
|
+
return JSONResponse({"ok": True, "task": t})
|
|
113
|
+
if op == "coding_task_cancel":
|
|
114
|
+
return JSONResponse({"ok": True, "task": await coding.cancel(body["id"], "admin")})
|
|
115
|
+
if op == "pipeline_cancel":
|
|
116
|
+
return JSONResponse({"ok": True, "pipeline": await pipelines.cancel(body["id"], "admin")})
|
|
117
|
+
if op == "agent_cancel":
|
|
118
|
+
return JSONResponse({"ok": True, "run": await agents.cancel(body["id"], "admin")})
|
|
119
|
+
if op == "jobs_cancel_all":
|
|
120
|
+
return JSONResponse({"ok": True, "cancelled": jobs.cancel_all("admin")})
|
|
121
|
+
if op == "funnel":
|
|
122
|
+
return JSONResponse({"ok": True, **_funnel(body.get("action", "status"))})
|
|
123
|
+
if op == "killswitch":
|
|
124
|
+
closed_shells = shells.close_all("killswitch")
|
|
125
|
+
out = {"funnel": _funnel("off"), "tokens_revoked": auth.revoke_all_tokens(),
|
|
126
|
+
"shells_closed": closed_shells, "jobs_cancelled": jobs.cancel_all("killswitch")}
|
|
127
|
+
try:
|
|
128
|
+
for p in pipelines.list_pipelines(limit=100):
|
|
129
|
+
if p["status"] in pipelines.STATUS_ACTIVE:
|
|
130
|
+
await pipelines.cancel(p["pipeline_id"], "killswitch")
|
|
131
|
+
for t in coding.list_tasks(limit=100):
|
|
132
|
+
if t["status"] in coding.STATUS_ACTIVE:
|
|
133
|
+
await coding.cancel(t["task_id"], "killswitch")
|
|
134
|
+
out["agents_cancelled"] = await agents.cancel_all("killswitch")
|
|
135
|
+
except Exception as e:
|
|
136
|
+
out["agents_cancelled"] = str(e)
|
|
137
|
+
try:
|
|
138
|
+
out["browser"] = await browser.close()
|
|
139
|
+
except Exception as e:
|
|
140
|
+
out["browser"] = str(e)
|
|
141
|
+
db.audit("killswitch", json.dumps(out)[:1000])
|
|
142
|
+
return JSONResponse({"ok": True, **out})
|
|
143
|
+
if op == "audit":
|
|
144
|
+
rows = db.all_("SELECT ts, subject, tool, workspace_id, summary FROM audit ORDER BY id DESC LIMIT ?", body.get("limit", 100))
|
|
145
|
+
return JSONResponse({"ok": True, "audit": [dict(r) for r in rows]})
|
|
146
|
+
if op == "devports":
|
|
147
|
+
return JSONResponse({"ok": True, "ports": [dict(r) for r in db.all_("SELECT * FROM dev_ports")]})
|
|
148
|
+
return JSONResponse({"error": "unknown op"}, 404)
|
|
149
|
+
except policy.BridgeError as e:
|
|
150
|
+
return JSONResponse(e.payload(), 400)
|
|
151
|
+
except KeyError as e:
|
|
152
|
+
return JSONResponse({"error": "invalid_argument", "message": f"missing {e}"}, 400)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def build_admin_app() -> Starlette:
|
|
156
|
+
return Starlette(routes=[Route("/admin/{op}", handle, methods=["GET", "POST"])])
|
bridge/agent_outcomes.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Deterministic, conservative interpretation of sub-agent transcripts.
|
|
2
|
+
|
|
3
|
+
Conversation completion is not task verification. Tool text is evidence only when
|
|
4
|
+
it is an actual tool message; quoted errors in user prompts and file contents are
|
|
5
|
+
not platform errors. This module performs no I/O and never retries an action.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
SCHEMA_VERSION = 2
|
|
13
|
+
_SAFETY = re.compile(
|
|
14
|
+
r"^This tool call was blocked by OpenAI because (?:we couldn't determine the safety status of the request\.?|.*safety.*)$",
|
|
15
|
+
re.I | re.S,
|
|
16
|
+
)
|
|
17
|
+
_MARKER = re.compile(r"^CLB_TASK_STATUS=(done|blocked|failed|needs_user_action)$", re.M)
|
|
18
|
+
_HIDDEN = {"analysis", "reasoning", "thoughts", "reasoning_recap"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def validate_verification(value: Any) -> dict | None:
|
|
22
|
+
"""An opt-in exact command/stdout check, not a semantic task success claim."""
|
|
23
|
+
if value is None:
|
|
24
|
+
return None
|
|
25
|
+
if not isinstance(value, dict) or set(value) != {"kind", "argv", "stdout"}:
|
|
26
|
+
raise ValueError("verification must contain exactly kind, argv and stdout")
|
|
27
|
+
argv = value.get("argv")
|
|
28
|
+
if value.get("kind") != "exec" or not isinstance(argv, list) or not argv or not all(isinstance(a, str) for a in argv):
|
|
29
|
+
raise ValueError("verification.kind must be exec and argv must be a non-empty string list")
|
|
30
|
+
if not isinstance(value.get("stdout"), str) or len(value["stdout"].encode()) > 1024 * 1024:
|
|
31
|
+
raise ValueError("verification.stdout must be a string of at most 1 MiB")
|
|
32
|
+
return {"kind": "exec", "argv": list(argv), "stdout": value["stdout"]}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _envelopes(value: Any, depth: int = 0) -> list[dict]:
|
|
36
|
+
"""Unwrap MCP transport containers, never arbitrary file/output data."""
|
|
37
|
+
if depth > 5:
|
|
38
|
+
return []
|
|
39
|
+
if isinstance(value, str):
|
|
40
|
+
try:
|
|
41
|
+
return _envelopes(json.loads(value), depth + 1)
|
|
42
|
+
except (ValueError, TypeError):
|
|
43
|
+
return []
|
|
44
|
+
if isinstance(value, list):
|
|
45
|
+
return [e for part in value for e in _envelopes(part, depth + 1)]
|
|
46
|
+
if not isinstance(value, dict):
|
|
47
|
+
return []
|
|
48
|
+
if isinstance(value.get("ok"), bool) and isinstance(value.get("request_id"), str) and isinstance(value.get("provenance"), dict):
|
|
49
|
+
return [value]
|
|
50
|
+
out = []
|
|
51
|
+
for key in ("structured_content", "structuredContent", "content", "text", "result"):
|
|
52
|
+
if key in value:
|
|
53
|
+
out.extend(_envelopes(value[key], depth + 1))
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def digest(conv: dict, since_user_index: int) -> dict:
|
|
58
|
+
messages = [m for m in conv.get("msgs", [])[since_user_index + 1:]
|
|
59
|
+
if m.get("role") in ("assistant", "tool")
|
|
60
|
+
and m.get("channel") not in _HIDDEN and m.get("ct") not in _HIDDEN]
|
|
61
|
+
attempts, results, unanswered = [], [], []
|
|
62
|
+
for i, m in enumerate(messages):
|
|
63
|
+
text = m.get("text") or ""
|
|
64
|
+
if m.get("role") == "assistant" and m.get("recipient") not in (None, "all"):
|
|
65
|
+
name = m["recipient"].rsplit(".", 1)[-1]
|
|
66
|
+
try:
|
|
67
|
+
path = json.loads(text).get("path", "")
|
|
68
|
+
if path:
|
|
69
|
+
name = path.rsplit("/", 1)[-1]
|
|
70
|
+
except (ValueError, AttributeError, TypeError):
|
|
71
|
+
pass
|
|
72
|
+
attempt = {"message_id": m.get("id"), "recipient": m["recipient"], "tool": name, "ts": m.get("ts")}
|
|
73
|
+
attempts.append(attempt)
|
|
74
|
+
# A call OpenAI blocks before dispatch leaves no tool message at all: the next message is the assistant again (or nothing).
|
|
75
|
+
nxt = messages[i + 1] if i + 1 < len(messages) else None
|
|
76
|
+
if m["recipient"].startswith("api_tool") and (nxt is None or nxt.get("role") != "tool"):
|
|
77
|
+
unanswered.append(attempt)
|
|
78
|
+
if m.get("role") != "tool":
|
|
79
|
+
continue
|
|
80
|
+
common = {"message_id": m.get("id"), "name": m.get("name"), "ts": m.get("ts")}
|
|
81
|
+
envelopes = _envelopes(text)
|
|
82
|
+
if envelopes:
|
|
83
|
+
seen = set()
|
|
84
|
+
for env in envelopes:
|
|
85
|
+
rid = env["request_id"]
|
|
86
|
+
if rid in seen:
|
|
87
|
+
continue
|
|
88
|
+
seen.add(rid)
|
|
89
|
+
results.append({**common, "kind": "bridge_response", "request_id": rid,
|
|
90
|
+
"host_id": env["provenance"].get("host_id"),
|
|
91
|
+
"workspace_id": env["provenance"].get("workspace_id"),
|
|
92
|
+
"job_id": env.get("job_id"), "ok": env["ok"],
|
|
93
|
+
"error": env.get("error"), "raw_error": env.get("message") if not env["ok"] else None})
|
|
94
|
+
elif _SAFETY.fullmatch(text.strip()):
|
|
95
|
+
results.append({**common, "kind": "platform_safety_block", "raw_error": text})
|
|
96
|
+
else:
|
|
97
|
+
results.append({**common, "kind": "opaque_tool_result", "raw_error": None})
|
|
98
|
+
finals = [m for m in messages if m.get("role") == "assistant" and m.get("ct") == "text"
|
|
99
|
+
and m.get("recipient") in (None, "all") and m.get("text")]
|
|
100
|
+
final = finals[-1] if finals else None
|
|
101
|
+
return {"schema_version": SCHEMA_VERSION, "final_text": final["text"] if final else "",
|
|
102
|
+
"final_end_turn": bool(final and final.get("end_turn")),
|
|
103
|
+
"final_status": final.get("status") if final else None,
|
|
104
|
+
"messages": [{k: (m.get(k) or "")[:4000] if k == "text" else m.get(k)
|
|
105
|
+
for k in ("id", "role", "name", "recipient", "channel", "ct", "text", "status", "end_turn", "ts")}
|
|
106
|
+
| {"text_truncated": len(m.get("text") or "") > 4000} for m in messages],
|
|
107
|
+
"tool_calls": attempts, "tool_results": results, "unanswered_tool_calls": unanswered,
|
|
108
|
+
"tool_attempts": len(attempts), "tool_responses": len(results), "upstream_blocks_observed": len(unanswered),
|
|
109
|
+
"model_slug": conv.get("model"), "title": conv.get("title")}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def outcome(data: dict, verification: dict | None = None) -> dict:
|
|
113
|
+
"""Classify observed errors; verified success is assigned only by the host verifier."""
|
|
114
|
+
done = data.get("final_end_turn") and data.get("final_status") == "finished_successfully"
|
|
115
|
+
blocks = int(data.get("upstream_blocks_observed") or 0)
|
|
116
|
+
base = {"status": "completed" if done else "running", "conversation_status": "completed" if done else "running",
|
|
117
|
+
"task_status": "unverified", "error_code": None, "error": None,
|
|
118
|
+
"evidence_source": "transcript", "verification": "not_requested" if verification is None else "pending",
|
|
119
|
+
"upstream_blocks_observed": blocks,
|
|
120
|
+
# The worker may repeat a blocked call once, verbatim; a run that then finished is not a blocked run, but the block is on record.
|
|
121
|
+
"warnings": [f"{blocks} plugin call(s) were dropped by OpenAI's safety check before reaching the bridge (see unanswered_tool_calls)"] if blocks else []}
|
|
122
|
+
for result in data.get("tool_results", []):
|
|
123
|
+
if result["kind"] == "platform_safety_block":
|
|
124
|
+
return {**base, "status": "failed", "task_status": "blocked", "error_code": "upstream_safety_blocked",
|
|
125
|
+
"error": result["raw_error"], "evidence_source": "tool_return"}
|
|
126
|
+
text = data.get("final_text") or ""
|
|
127
|
+
# New workers report an exact terminal marker, outside code fences. Legacy short
|
|
128
|
+
# RESULT reports remain distinguishable from an observed platform tool error.
|
|
129
|
+
plain = re.sub(r"```.*?```", "", text, flags=re.S)
|
|
130
|
+
match = _MARKER.search(plain) if done else None
|
|
131
|
+
reported = match.group(1) if match else None
|
|
132
|
+
legacy = (done and reported is None and len(text) < 600 and "```" not in text and
|
|
133
|
+
re.search(r"(?:exec_start|工具调用|tool call)[^\n]{0,90}(?:被安全检查(?:拦截|阻止)|被(?:OpenAI|ChatGPT)[^\n]{0,30}拦截|was blocked by OpenAI)", text, re.I))
|
|
134
|
+
if reported == "blocked" or legacy:
|
|
135
|
+
return {**base, "status": "failed", "task_status": "blocked", "error_code": "reported_safety_blocked",
|
|
136
|
+
"error": text, "evidence_source": "assistant_report"}
|
|
137
|
+
if reported in ("failed", "needs_user_action"):
|
|
138
|
+
return {**base, "status": "failed", "task_status": reported,
|
|
139
|
+
"error_code": "reported_" + reported, "error": text, "evidence_source": "assistant_report"}
|
|
140
|
+
errors = [r for r in data.get("tool_results", []) if r["kind"] == "bridge_response" and r["ok"] is False]
|
|
141
|
+
if done and errors and verification is None:
|
|
142
|
+
last = errors[-1]
|
|
143
|
+
return {**base, "status": "failed", "task_status": "needs_review", "error_code": "tool_error",
|
|
144
|
+
"error": last.get("raw_error") or last.get("error"), "evidence_source": "tool_return"}
|
|
145
|
+
return base
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def legacy_outcome(data: dict) -> dict:
|
|
149
|
+
"""Read-only reinterpretation. Never mutate or relabel historical evidence on disk."""
|
|
150
|
+
messages = data.get("messages") or []
|
|
151
|
+
d = digest({"msgs": messages}, -1)
|
|
152
|
+
d.update(final_text=data.get("final_text", ""), final_end_turn=data.get("final_end_turn", True),
|
|
153
|
+
final_status=data.get("final_status", "finished_successfully"))
|
|
154
|
+
result = outcome(d)
|
|
155
|
+
result["legacy_reclassified"] = True
|
|
156
|
+
return result
|