scope-agent-workbench 0.2.0 → 0.2.3
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.
- package/CHANGELOG.md +41 -0
- package/bridge/agent-email-relay.mjs +160 -160
- package/bridge/app-server-websocket-transport.mjs +219 -219
- package/bridge/archive/service.mjs +130 -130
- package/bridge/auth-profile-failover.mjs +58 -58
- package/bridge/auth-profile-manager.mjs +215 -215
- package/bridge/capacity-recovery.mjs +90 -90
- package/bridge/gpu-usage-history.mjs +322 -322
- package/bridge/local/history.mjs +20 -5
- package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -236
- package/bridge/plugins/aliyun-dlc/probe.mjs +701 -701
- package/bridge/private-gateway.mjs +371 -371
- package/bridge/private-start.mjs +22 -22
- package/bridge/probes/app-server-handoff-probe.mjs +87 -87
- package/bridge/probes/app-server-writer-probe.mjs +69 -69
- package/bridge/probes/assistant-search-probe.mjs +321 -321
- package/bridge/probes/dialogue-probe.mjs +462 -462
- package/bridge/probes/history-probe.mjs +430 -345
- package/bridge/probes/new-session-preflight.mjs +14 -14
- package/bridge/probes/profile-cancel-probe.mjs +17 -17
- package/bridge/probes/profile-delete-probe.mjs +26 -26
- package/bridge/probes/profile-list-probe.mjs +114 -114
- package/bridge/probes/profile-write-probe.mjs +109 -109
- package/bridge/probes/raw-context-probe.mjs +51 -51
- package/bridge/probes/remote-probe.mjs +627 -626
- package/bridge/probes/submission-probe.mjs +2 -2
- package/bridge/probes/takeover-probe.mjs +326 -326
- package/bridge/probes/vscode-open-preflight.mjs +21 -21
- package/bridge/providers/claude-interactive.py +463 -341
- package/bridge/providers/cli-command.mjs +103 -103
- package/bridge/providers/conversations.mjs +231 -231
- package/bridge/providers/native-commands.py +38 -38
- package/bridge/providers/native-session-state.mjs +14 -14
- package/bridge/providers/native-session-state.py +96 -96
- package/bridge/providers/remote-job.py +130 -130
- package/bridge/remote-app-server-command.mjs +121 -121
- package/bridge/remote-directory-listing.mjs +148 -148
- package/bridge/rollout-summary.mjs +20 -2
- package/bridge/routes/dialogue.mjs +48 -3
- package/bridge/routes/models.mjs +312 -312
- package/bridge/server.mjs +3357 -3332
- package/bridge/session-attachments.mjs +150 -150
- package/bridge/session-catalog/agy-history.py +141 -2
- package/bridge/session-catalog/catalog.mjs +17 -0
- package/bridge/session-catalog/probe.py +1207 -331
- package/bridge/session-catalog/routes.mjs +6 -0
- package/bridge/start.mjs +205 -205
- package/bridge/state-persistence.mjs +9 -1
- package/bridge/tmux-session-control.mjs +29 -29
- package/bridge/vscode-opener.mjs +157 -157
- package/bridge/web-terminal.mjs +52 -52
- package/bridge/workbench/manager-context.mjs +51 -51
- package/bridge/workbench/service.mjs +301 -301
- package/dist/client/.vite/manifest.json +4 -4
- package/dist/client/assets/{index-Enu1x0PS.js → index-BMior55c.js} +2 -2
- package/dist/client/assets/{layout-segment-context-CmJzExWq.js → layout-segment-context-DjGudgXn.js} +1 -1
- package/dist/client/assets/page-CJqXlhDs.js +551 -0
- package/dist/client/assets/page-LYzRz6_S.css +1 -0
- package/dist/client/favicon.svg +6 -6
- package/dist/server/__vite_rsc_assets_manifest.js +8 -8
- package/dist/server/index.js +7 -7
- package/dist/server/ssr/__vite_rsc_assets_manifest.js +8 -8
- package/dist/server/ssr/assets/{page-CYYyCnKD.js → page-BB9Dri2u.js} +2416 -271
- package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -0
- package/dist/server/ssr/index.js +1 -1
- package/dist/server/ssr/vinext-server.json +1 -1
- package/dist/server/vinext-server.json +1 -1
- package/dist/server/wrangler.json +1 -1
- package/lib/browser-snapshot-cache.js +53 -53
- package/lib/formula-preview.js +1 -1
- package/lib/incremental-snapshot.js +300 -300
- package/lib/markdown-math.js +151 -151
- package/lib/remote-links.js +95 -95
- package/lib/runtime-config.js +70 -70
- package/lib/session-filters.js +38 -38
- package/lib/ssh-config.js +26 -26
- package/lib/stable-order.js +39 -39
- package/lib/subagent-display-prefs.ts +130 -0
- package/package.json +1 -1
- package/scripts/agent-email-relay.mjs +104 -104
- package/scripts/email-notification-cli.mjs +28 -28
- package/scripts/enable-private-access.ps1 +109 -109
- package/scripts/fixtures/native-conversations.mjs +164 -6
- package/scripts/fixtures/workbench-conversations.mjs +475 -352
- package/scripts/preview-workbench.mjs +669 -669
- package/dist/client/assets/page-COBv6VWj.css +0 -1
- package/dist/client/assets/page-DVjU6VG_.js +0 -550
- package/dist/server/ssr/assets/page-COBv6VWj.css +0 -1
|
@@ -1,96 +1,96 @@
|
|
|
1
|
-
"""Reversible SCOPE visibility state; never move/delete native agent history."""
|
|
2
|
-
import base64
|
|
3
|
-
import fcntl
|
|
4
|
-
import json
|
|
5
|
-
import os
|
|
6
|
-
from pathlib import Path
|
|
7
|
-
import re
|
|
8
|
-
import subprocess
|
|
9
|
-
import sys
|
|
10
|
-
import time
|
|
11
|
-
|
|
12
|
-
config = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "==="))
|
|
13
|
-
provider = config.get("provider", "claude")
|
|
14
|
-
if provider not in ("claude", "antigravity"):
|
|
15
|
-
raise ValueError("Unsupported provider")
|
|
16
|
-
label = "Claude" if provider == "claude" else "Antigravity"
|
|
17
|
-
sid = config.get("sessionId", "")
|
|
18
|
-
if not re.fullmatch(r"[a-fA-F0-9-]{36}", sid):
|
|
19
|
-
raise ValueError("Invalid native session ID")
|
|
20
|
-
root = Path.home() / ".local/state/scope" / (provider + "-sessions")
|
|
21
|
-
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
22
|
-
lock = (root / (sid + ".lock")).open("a")
|
|
23
|
-
try:
|
|
24
|
-
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
25
|
-
except BlockingIOError:
|
|
26
|
-
raise RuntimeError("此 Agent 会话正在被 SCOPE 使用,请等待本轮结束")
|
|
27
|
-
filename = root / (sid + ".json")
|
|
28
|
-
state = json.loads(filename.read_text()) if filename.exists() else {"sessionId": sid, "phase": "active"}
|
|
29
|
-
|
|
30
|
-
def active_writer():
|
|
31
|
-
if provider == "antigravity":
|
|
32
|
-
# Probe native presence locks; stale files alone do not mean active.
|
|
33
|
-
native_lock = Path.home() / ".gemini/antigravity-cli/presence" / (sid + ".lock")
|
|
34
|
-
if native_lock.exists():
|
|
35
|
-
with native_lock.open("r") as presence:
|
|
36
|
-
try:
|
|
37
|
-
fcntl.flock(presence, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
38
|
-
except BlockingIOError:
|
|
39
|
-
return "native presence lock"
|
|
40
|
-
finally:
|
|
41
|
-
fcntl.flock(presence, fcntl.LOCK_UN)
|
|
42
|
-
for entry in Path("/proc").glob("[0-9]*/cmdline"):
|
|
43
|
-
try:
|
|
44
|
-
args = entry.read_bytes().decode(errors="replace").split("\0")
|
|
45
|
-
if sid in args and any(Path(a).name == "agy" or "antigravity" in a for a in args[:2]):
|
|
46
|
-
return entry.parent.name
|
|
47
|
-
except (FileNotFoundError, ProcessLookupError):
|
|
48
|
-
continue
|
|
49
|
-
return None
|
|
50
|
-
registry = Path(os.environ.get("CLAUDE_CONFIG_DIR", str(Path.home() / ".claude"))) / "sessions"
|
|
51
|
-
for entry in registry.glob("*.json"):
|
|
52
|
-
try:
|
|
53
|
-
record = json.loads(entry.read_text())
|
|
54
|
-
if record.get("sessionId") != sid:
|
|
55
|
-
continue
|
|
56
|
-
pid = int(record["pid"])
|
|
57
|
-
if pid <= 0:
|
|
58
|
-
continue
|
|
59
|
-
os.kill(pid, 0)
|
|
60
|
-
# Reject conservatively on a live registered PID; never signal it.
|
|
61
|
-
return pid
|
|
62
|
-
except (FileNotFoundError, ProcessLookupError, ValueError, KeyError):
|
|
63
|
-
continue
|
|
64
|
-
# Older CLIs can lack registry files. Check explicit --resume/--session-id arguments.
|
|
65
|
-
for entry in Path("/proc").glob("[0-9]*/cmdline"):
|
|
66
|
-
try:
|
|
67
|
-
args = entry.read_bytes().decode(errors="replace").split("\0")
|
|
68
|
-
if sid in args and any("claude" in a for a in args[:2]):
|
|
69
|
-
return int(entry.parent.name)
|
|
70
|
-
except (FileNotFoundError, ProcessLookupError):
|
|
71
|
-
continue
|
|
72
|
-
return None
|
|
73
|
-
|
|
74
|
-
action = config["action"]
|
|
75
|
-
if action != "status":
|
|
76
|
-
writer = active_writer()
|
|
77
|
-
if writer:
|
|
78
|
-
raise RuntimeError("%s 会话仍被远端终端或其他客户端使用(%s),请先正常退出该会话" % (label, writer))
|
|
79
|
-
if action == "run":
|
|
80
|
-
if state["phase"] != "active":
|
|
81
|
-
raise RuntimeError("会话已归档或在回收站,请先恢复")
|
|
82
|
-
# This lock is held throughout the child turn, serializing SCOPE clients on the same host.
|
|
83
|
-
sys.exit(subprocess.call(["bash", "-ic", config["command"]], stdin=subprocess.DEVNULL))
|
|
84
|
-
elif action in ("archive", "delete", "restore"):
|
|
85
|
-
if action == "delete" and state["phase"] not in ("archived", "deleted"):
|
|
86
|
-
raise RuntimeError("请先归档,再移入回收站")
|
|
87
|
-
state.update(phase={"archive": "archived", "delete": "deleted", "restore": "active"}[action],
|
|
88
|
-
updatedAt=int(time.time() * 1000))
|
|
89
|
-
temporary = filename.with_suffix(".tmp")
|
|
90
|
-
temporary.write_text(json.dumps(state))
|
|
91
|
-
temporary.replace(filename)
|
|
92
|
-
elif action not in ("status", "check"):
|
|
93
|
-
raise ValueError("Unsupported action")
|
|
94
|
-
elif action == "check" and state["phase"] != "active":
|
|
95
|
-
raise RuntimeError("会话已归档或在回收站,请先恢复")
|
|
96
|
-
print(json.dumps(state))
|
|
1
|
+
"""Reversible SCOPE visibility state; never move/delete native agent history."""
|
|
2
|
+
import base64
|
|
3
|
+
import fcntl
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
config = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "==="))
|
|
13
|
+
provider = config.get("provider", "claude")
|
|
14
|
+
if provider not in ("claude", "antigravity"):
|
|
15
|
+
raise ValueError("Unsupported provider")
|
|
16
|
+
label = "Claude" if provider == "claude" else "Antigravity"
|
|
17
|
+
sid = config.get("sessionId", "")
|
|
18
|
+
if not re.fullmatch(r"[a-fA-F0-9-]{36}", sid):
|
|
19
|
+
raise ValueError("Invalid native session ID")
|
|
20
|
+
root = Path.home() / ".local/state/scope" / (provider + "-sessions")
|
|
21
|
+
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
22
|
+
lock = (root / (sid + ".lock")).open("a")
|
|
23
|
+
try:
|
|
24
|
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
25
|
+
except BlockingIOError:
|
|
26
|
+
raise RuntimeError("此 Agent 会话正在被 SCOPE 使用,请等待本轮结束")
|
|
27
|
+
filename = root / (sid + ".json")
|
|
28
|
+
state = json.loads(filename.read_text()) if filename.exists() else {"sessionId": sid, "phase": "active"}
|
|
29
|
+
|
|
30
|
+
def active_writer():
|
|
31
|
+
if provider == "antigravity":
|
|
32
|
+
# Probe native presence locks; stale files alone do not mean active.
|
|
33
|
+
native_lock = Path.home() / ".gemini/antigravity-cli/presence" / (sid + ".lock")
|
|
34
|
+
if native_lock.exists():
|
|
35
|
+
with native_lock.open("r") as presence:
|
|
36
|
+
try:
|
|
37
|
+
fcntl.flock(presence, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
38
|
+
except BlockingIOError:
|
|
39
|
+
return "native presence lock"
|
|
40
|
+
finally:
|
|
41
|
+
fcntl.flock(presence, fcntl.LOCK_UN)
|
|
42
|
+
for entry in Path("/proc").glob("[0-9]*/cmdline"):
|
|
43
|
+
try:
|
|
44
|
+
args = entry.read_bytes().decode(errors="replace").split("\0")
|
|
45
|
+
if sid in args and any(Path(a).name == "agy" or "antigravity" in a for a in args[:2]):
|
|
46
|
+
return entry.parent.name
|
|
47
|
+
except (FileNotFoundError, ProcessLookupError):
|
|
48
|
+
continue
|
|
49
|
+
return None
|
|
50
|
+
registry = Path(os.environ.get("CLAUDE_CONFIG_DIR", str(Path.home() / ".claude"))) / "sessions"
|
|
51
|
+
for entry in registry.glob("*.json"):
|
|
52
|
+
try:
|
|
53
|
+
record = json.loads(entry.read_text())
|
|
54
|
+
if record.get("sessionId") != sid:
|
|
55
|
+
continue
|
|
56
|
+
pid = int(record["pid"])
|
|
57
|
+
if pid <= 0:
|
|
58
|
+
continue
|
|
59
|
+
os.kill(pid, 0)
|
|
60
|
+
# Reject conservatively on a live registered PID; never signal it.
|
|
61
|
+
return pid
|
|
62
|
+
except (FileNotFoundError, ProcessLookupError, ValueError, KeyError):
|
|
63
|
+
continue
|
|
64
|
+
# Older CLIs can lack registry files. Check explicit --resume/--session-id arguments.
|
|
65
|
+
for entry in Path("/proc").glob("[0-9]*/cmdline"):
|
|
66
|
+
try:
|
|
67
|
+
args = entry.read_bytes().decode(errors="replace").split("\0")
|
|
68
|
+
if sid in args and any("claude" in a for a in args[:2]):
|
|
69
|
+
return int(entry.parent.name)
|
|
70
|
+
except (FileNotFoundError, ProcessLookupError):
|
|
71
|
+
continue
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
action = config["action"]
|
|
75
|
+
if action != "status":
|
|
76
|
+
writer = active_writer()
|
|
77
|
+
if writer:
|
|
78
|
+
raise RuntimeError("%s 会话仍被远端终端或其他客户端使用(%s),请先正常退出该会话" % (label, writer))
|
|
79
|
+
if action == "run":
|
|
80
|
+
if state["phase"] != "active":
|
|
81
|
+
raise RuntimeError("会话已归档或在回收站,请先恢复")
|
|
82
|
+
# This lock is held throughout the child turn, serializing SCOPE clients on the same host.
|
|
83
|
+
sys.exit(subprocess.call(["bash", "-ic", config["command"]], stdin=subprocess.DEVNULL))
|
|
84
|
+
elif action in ("archive", "delete", "restore"):
|
|
85
|
+
if action == "delete" and state["phase"] not in ("archived", "deleted"):
|
|
86
|
+
raise RuntimeError("请先归档,再移入回收站")
|
|
87
|
+
state.update(phase={"archive": "archived", "delete": "deleted", "restore": "active"}[action],
|
|
88
|
+
updatedAt=int(time.time() * 1000))
|
|
89
|
+
temporary = filename.with_suffix(".tmp")
|
|
90
|
+
temporary.write_text(json.dumps(state))
|
|
91
|
+
temporary.replace(filename)
|
|
92
|
+
elif action not in ("status", "check"):
|
|
93
|
+
raise ValueError("Unsupported action")
|
|
94
|
+
elif action == "check" and state["phase"] != "active":
|
|
95
|
+
raise RuntimeError("会话已归档或在回收站,请先恢复")
|
|
96
|
+
print(json.dumps(state))
|
|
@@ -1,130 +1,130 @@
|
|
|
1
|
-
"""Small Linux SSH spool. No agent is invoked by status requests.
|
|
2
|
-
|
|
3
|
-
A UUID directory is claimed before launching. Repeating launch returns the same
|
|
4
|
-
receipt; an incomplete claim is unknown and never launches a duplicate process.
|
|
5
|
-
"""
|
|
6
|
-
import base64
|
|
7
|
-
import hashlib
|
|
8
|
-
import json
|
|
9
|
-
import os
|
|
10
|
-
from pathlib import Path
|
|
11
|
-
import re
|
|
12
|
-
import subprocess
|
|
13
|
-
import sys
|
|
14
|
-
|
|
15
|
-
if hasattr(sys.stdout, "reconfigure"):
|
|
16
|
-
sys.stdout.reconfigure(encoding="utf-8")
|
|
17
|
-
|
|
18
|
-
WORKER = r'''
|
|
19
|
-
import json, os, subprocess, sys, time
|
|
20
|
-
from pathlib import Path
|
|
21
|
-
root = Path(sys.argv[1])
|
|
22
|
-
def save(value):
|
|
23
|
-
temporary = root / "status.tmp"
|
|
24
|
-
temporary.write_text(json.dumps(value), encoding="utf-8")
|
|
25
|
-
temporary.replace(root / "status.json")
|
|
26
|
-
try:
|
|
27
|
-
request = json.loads((root / "request.json").read_text(encoding="utf-8"))
|
|
28
|
-
save({"status": "running", "pid": os.getpid(), "startedAt": time.time()})
|
|
29
|
-
with (root / "stdout").open("wb") as out, (root / "stderr").open("wb") as err:
|
|
30
|
-
child = subprocess.Popen(["bash", "-ic", request["command"]], stdin=subprocess.PIPE, stdout=out, stderr=err)
|
|
31
|
-
# No remote timeout kill: a disconnected observer must not terminate work.
|
|
32
|
-
child.communicate(request["input"].encode("utf-8"))
|
|
33
|
-
save({"status": "completed" if child.returncode == 0 else "failed", "code": child.returncode, "endedAt": time.time()})
|
|
34
|
-
except Exception as error:
|
|
35
|
-
save({"status": "unknown", "error": str(error)})
|
|
36
|
-
'''
|
|
37
|
-
|
|
38
|
-
request = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "==="))
|
|
39
|
-
task_id = request.get("id", "")
|
|
40
|
-
if not re.fullmatch(r"[a-f0-9-]{36}", task_id):
|
|
41
|
-
raise ValueError("invalid task id")
|
|
42
|
-
base = Path.home() / ".local" / "state" / "scope"
|
|
43
|
-
active = base / "runs" / task_id
|
|
44
|
-
archived = base / "archives" / task_id
|
|
45
|
-
root = archived if archived.exists() else active
|
|
46
|
-
if active.exists() and archived.exists():
|
|
47
|
-
raise ValueError("conflicting archive receipts; inspect remote state")
|
|
48
|
-
if request["operation"] in ("archive", "restore"):
|
|
49
|
-
status = root / "status.json"
|
|
50
|
-
record = json.loads(status.read_text()) if status.exists() else {}
|
|
51
|
-
if record.get("status") not in ("completed", "failed"):
|
|
52
|
-
raise ValueError("remote task is not confirmed finished; not archived")
|
|
53
|
-
target = archived if request["operation"] == "archive" else active
|
|
54
|
-
if root != target:
|
|
55
|
-
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
56
|
-
root.rename(target)
|
|
57
|
-
root = target
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if request["operation"] == "launch":
|
|
61
|
-
payload = {"command": request["command"], "input": request["input"]}
|
|
62
|
-
if "interactiveConfig" in request: payload["interactiveConfig"] = request["interactiveConfig"]
|
|
63
|
-
fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
|
|
64
|
-
root.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
65
|
-
try:
|
|
66
|
-
root.mkdir(mode=0o700)
|
|
67
|
-
except FileExistsError:
|
|
68
|
-
existing = root / "fingerprint"
|
|
69
|
-
if existing.exists() and existing.read_text() != fingerprint:
|
|
70
|
-
raise ValueError("task id already belongs to a different request")
|
|
71
|
-
else:
|
|
72
|
-
(root / "fingerprint").write_text(fingerprint)
|
|
73
|
-
(root / "request.json").write_text(json.dumps(payload), encoding="utf-8")
|
|
74
|
-
if "interactiveConfig" in request:
|
|
75
|
-
(root / "claude-config.json").write_text(json.dumps(request["interactiveConfig"]), encoding="utf-8")
|
|
76
|
-
subprocess.Popen([sys.executable, "-c", WORKER, str(root)], stdin=subprocess.DEVNULL,
|
|
77
|
-
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
|
|
78
|
-
elif request["operation"] == "control":
|
|
79
|
-
import fcntl
|
|
80
|
-
with (root / "control.lock").open("a") as mutex:
|
|
81
|
-
fcntl.flock(mutex, fcntl.LOCK_EX)
|
|
82
|
-
snapshot = json.loads((root / "interactive.json").read_text())
|
|
83
|
-
if snapshot.get("status") not in ("running", "waiting_permission"):
|
|
84
|
-
raise ValueError("会话已结束或正在停止,请刷新后重试")
|
|
85
|
-
control = request["control"]
|
|
86
|
-
if not re.fullmatch(r"[a-f0-9-]{36}", control["id"]):
|
|
87
|
-
raise ValueError("invalid control id")
|
|
88
|
-
if control["action"] not in ("message", "permission", "stop"):
|
|
89
|
-
raise ValueError("unsupported control")
|
|
90
|
-
if control["action"] == "permission" and not any(p["id"] == control.get("requestId") for p in snapshot.get("permissions", [])):
|
|
91
|
-
raise ValueError("权限请求已失效或已处理")
|
|
92
|
-
target = root / "controls" / (control["id"] + ".json")
|
|
93
|
-
if target.exists():
|
|
94
|
-
prior = json.loads(target.read_text())
|
|
95
|
-
prior.pop("_sequence", None)
|
|
96
|
-
if prior != control: raise ValueError("conflicting control id")
|
|
97
|
-
else:
|
|
98
|
-
# Filesystem timestamp resolution is insufficient for ordered inputs.
|
|
99
|
-
counter = root / "control-sequence"
|
|
100
|
-
sequence = int(counter.read_text()) + 1 if counter.exists() else 1
|
|
101
|
-
counter.write_text(str(sequence))
|
|
102
|
-
target.write_text(json.dumps({**control, "_sequence": sequence}))
|
|
103
|
-
elif request["operation"] not in ("status", "archive", "restore"):
|
|
104
|
-
raise ValueError("unsupported operation")
|
|
105
|
-
|
|
106
|
-
status_file = root / "status.json"
|
|
107
|
-
result = json.loads(status_file.read_text()) if status_file.exists() else {"status": "unknown", "error": "等待启动回执;不会重复启动"}
|
|
108
|
-
if result.get("status") == "running":
|
|
109
|
-
try:
|
|
110
|
-
os.kill(result["pid"], 0)
|
|
111
|
-
except ProcessLookupError:
|
|
112
|
-
result = {"status": "unknown", "error": "远端监督进程已退出,执行结果待核实"}
|
|
113
|
-
|
|
114
|
-
for name in ("stdout", "stderr"):
|
|
115
|
-
filename = root / name
|
|
116
|
-
if filename.exists():
|
|
117
|
-
with filename.open("rb") as handle:
|
|
118
|
-
size = filename.stat().st_size
|
|
119
|
-
if size > 512_000:
|
|
120
|
-
handle.seek(size - 512_000)
|
|
121
|
-
result["truncated"] = True
|
|
122
|
-
result[name] = handle.read(512_000).decode("utf-8", errors="replace")
|
|
123
|
-
result["remotePath"] = str(root)
|
|
124
|
-
snapshot_file = root / "interactive.json"
|
|
125
|
-
if snapshot_file.exists():
|
|
126
|
-
snapshot = json.loads(snapshot_file.read_text(encoding="utf-8"))
|
|
127
|
-
if result.get("status") == "unknown" and snapshot.get("status") in ("running", "waiting_permission", "stopping", "finishing"):
|
|
128
|
-
snapshot.update(status="unknown", error=result.get("error"))
|
|
129
|
-
result["interactive"] = snapshot
|
|
130
|
-
print(json.dumps(result, ensure_ascii=False))
|
|
1
|
+
"""Small Linux SSH spool. No agent is invoked by status requests.
|
|
2
|
+
|
|
3
|
+
A UUID directory is claimed before launching. Repeating launch returns the same
|
|
4
|
+
receipt; an incomplete claim is unknown and never launches a duplicate process.
|
|
5
|
+
"""
|
|
6
|
+
import base64
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import re
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
16
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
17
|
+
|
|
18
|
+
WORKER = r'''
|
|
19
|
+
import json, os, subprocess, sys, time
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
root = Path(sys.argv[1])
|
|
22
|
+
def save(value):
|
|
23
|
+
temporary = root / "status.tmp"
|
|
24
|
+
temporary.write_text(json.dumps(value), encoding="utf-8")
|
|
25
|
+
temporary.replace(root / "status.json")
|
|
26
|
+
try:
|
|
27
|
+
request = json.loads((root / "request.json").read_text(encoding="utf-8"))
|
|
28
|
+
save({"status": "running", "pid": os.getpid(), "startedAt": time.time()})
|
|
29
|
+
with (root / "stdout").open("wb") as out, (root / "stderr").open("wb") as err:
|
|
30
|
+
child = subprocess.Popen(["bash", "-ic", request["command"]], stdin=subprocess.PIPE, stdout=out, stderr=err)
|
|
31
|
+
# No remote timeout kill: a disconnected observer must not terminate work.
|
|
32
|
+
child.communicate(request["input"].encode("utf-8"))
|
|
33
|
+
save({"status": "completed" if child.returncode == 0 else "failed", "code": child.returncode, "endedAt": time.time()})
|
|
34
|
+
except Exception as error:
|
|
35
|
+
save({"status": "unknown", "error": str(error)})
|
|
36
|
+
'''
|
|
37
|
+
|
|
38
|
+
request = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "==="))
|
|
39
|
+
task_id = request.get("id", "")
|
|
40
|
+
if not re.fullmatch(r"[a-f0-9-]{36}", task_id):
|
|
41
|
+
raise ValueError("invalid task id")
|
|
42
|
+
base = Path.home() / ".local" / "state" / "scope"
|
|
43
|
+
active = base / "runs" / task_id
|
|
44
|
+
archived = base / "archives" / task_id
|
|
45
|
+
root = archived if archived.exists() else active
|
|
46
|
+
if active.exists() and archived.exists():
|
|
47
|
+
raise ValueError("conflicting archive receipts; inspect remote state")
|
|
48
|
+
if request["operation"] in ("archive", "restore"):
|
|
49
|
+
status = root / "status.json"
|
|
50
|
+
record = json.loads(status.read_text()) if status.exists() else {}
|
|
51
|
+
if record.get("status") not in ("completed", "failed"):
|
|
52
|
+
raise ValueError("remote task is not confirmed finished; not archived")
|
|
53
|
+
target = archived if request["operation"] == "archive" else active
|
|
54
|
+
if root != target:
|
|
55
|
+
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
56
|
+
root.rename(target)
|
|
57
|
+
root = target
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if request["operation"] == "launch":
|
|
61
|
+
payload = {"command": request["command"], "input": request["input"]}
|
|
62
|
+
if "interactiveConfig" in request: payload["interactiveConfig"] = request["interactiveConfig"]
|
|
63
|
+
fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
|
|
64
|
+
root.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
65
|
+
try:
|
|
66
|
+
root.mkdir(mode=0o700)
|
|
67
|
+
except FileExistsError:
|
|
68
|
+
existing = root / "fingerprint"
|
|
69
|
+
if existing.exists() and existing.read_text() != fingerprint:
|
|
70
|
+
raise ValueError("task id already belongs to a different request")
|
|
71
|
+
else:
|
|
72
|
+
(root / "fingerprint").write_text(fingerprint)
|
|
73
|
+
(root / "request.json").write_text(json.dumps(payload), encoding="utf-8")
|
|
74
|
+
if "interactiveConfig" in request:
|
|
75
|
+
(root / "claude-config.json").write_text(json.dumps(request["interactiveConfig"]), encoding="utf-8")
|
|
76
|
+
subprocess.Popen([sys.executable, "-c", WORKER, str(root)], stdin=subprocess.DEVNULL,
|
|
77
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
|
|
78
|
+
elif request["operation"] == "control":
|
|
79
|
+
import fcntl
|
|
80
|
+
with (root / "control.lock").open("a") as mutex:
|
|
81
|
+
fcntl.flock(mutex, fcntl.LOCK_EX)
|
|
82
|
+
snapshot = json.loads((root / "interactive.json").read_text())
|
|
83
|
+
if snapshot.get("status") not in ("running", "waiting_permission"):
|
|
84
|
+
raise ValueError("会话已结束或正在停止,请刷新后重试")
|
|
85
|
+
control = request["control"]
|
|
86
|
+
if not re.fullmatch(r"[a-f0-9-]{36}", control["id"]):
|
|
87
|
+
raise ValueError("invalid control id")
|
|
88
|
+
if control["action"] not in ("message", "permission", "stop"):
|
|
89
|
+
raise ValueError("unsupported control")
|
|
90
|
+
if control["action"] == "permission" and not any(p["id"] == control.get("requestId") for p in snapshot.get("permissions", [])):
|
|
91
|
+
raise ValueError("权限请求已失效或已处理")
|
|
92
|
+
target = root / "controls" / (control["id"] + ".json")
|
|
93
|
+
if target.exists():
|
|
94
|
+
prior = json.loads(target.read_text())
|
|
95
|
+
prior.pop("_sequence", None)
|
|
96
|
+
if prior != control: raise ValueError("conflicting control id")
|
|
97
|
+
else:
|
|
98
|
+
# Filesystem timestamp resolution is insufficient for ordered inputs.
|
|
99
|
+
counter = root / "control-sequence"
|
|
100
|
+
sequence = int(counter.read_text()) + 1 if counter.exists() else 1
|
|
101
|
+
counter.write_text(str(sequence))
|
|
102
|
+
target.write_text(json.dumps({**control, "_sequence": sequence}))
|
|
103
|
+
elif request["operation"] not in ("status", "archive", "restore"):
|
|
104
|
+
raise ValueError("unsupported operation")
|
|
105
|
+
|
|
106
|
+
status_file = root / "status.json"
|
|
107
|
+
result = json.loads(status_file.read_text()) if status_file.exists() else {"status": "unknown", "error": "等待启动回执;不会重复启动"}
|
|
108
|
+
if result.get("status") == "running":
|
|
109
|
+
try:
|
|
110
|
+
os.kill(result["pid"], 0)
|
|
111
|
+
except ProcessLookupError:
|
|
112
|
+
result = {"status": "unknown", "error": "远端监督进程已退出,执行结果待核实"}
|
|
113
|
+
|
|
114
|
+
for name in ("stdout", "stderr"):
|
|
115
|
+
filename = root / name
|
|
116
|
+
if filename.exists():
|
|
117
|
+
with filename.open("rb") as handle:
|
|
118
|
+
size = filename.stat().st_size
|
|
119
|
+
if size > 512_000:
|
|
120
|
+
handle.seek(size - 512_000)
|
|
121
|
+
result["truncated"] = True
|
|
122
|
+
result[name] = handle.read(512_000).decode("utf-8", errors="replace")
|
|
123
|
+
result["remotePath"] = str(root)
|
|
124
|
+
snapshot_file = root / "interactive.json"
|
|
125
|
+
if snapshot_file.exists():
|
|
126
|
+
snapshot = json.loads(snapshot_file.read_text(encoding="utf-8"))
|
|
127
|
+
if result.get("status") == "unknown" and snapshot.get("status") in ("running", "waiting_permission", "stopping", "finishing"):
|
|
128
|
+
snapshot.update(status="unknown", error=result.get("error"))
|
|
129
|
+
result["interactive"] = snapshot
|
|
130
|
+
print(json.dumps(result, ensure_ascii=False))
|