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,341 +1,463 @@
|
|
|
1
|
-
"""One owned Claude stream-json process, with durable UI control and event snapshots."""
|
|
2
|
-
import fcntl
|
|
3
|
-
import json
|
|
4
|
-
import os
|
|
5
|
-
from pathlib import Path
|
|
6
|
-
import selectors
|
|
7
|
-
import signal
|
|
8
|
-
import subprocess
|
|
9
|
-
import sys
|
|
10
|
-
import time
|
|
11
|
-
|
|
12
|
-
root = Path.home() / ".local/state/scope/runs" / sys.argv[1]
|
|
13
|
-
config = json.loads((root / "claude-config.json").read_text(encoding="utf-8"))
|
|
14
|
-
controls = root / "controls"
|
|
15
|
-
controls.mkdir(mode=0o700, exist_ok=True)
|
|
16
|
-
mutex = (root / "control.lock").open("a")
|
|
17
|
-
state = {"status": "running", "sessionId": config.get("resumeSessionId"), "events": [],
|
|
18
|
-
"permissions": [], "controlResults": [], "text": "", "interactive": True}
|
|
19
|
-
pending = {}
|
|
20
|
-
queue = []
|
|
21
|
-
seen = set()
|
|
22
|
-
subagents = {}
|
|
23
|
-
finished = False
|
|
24
|
-
stopping = None
|
|
25
|
-
closing = None
|
|
26
|
-
initialized = False
|
|
27
|
-
partial = ""
|
|
28
|
-
result_value = None
|
|
29
|
-
last_snapshot = None
|
|
30
|
-
signal_stage = 0
|
|
31
|
-
inflight = set()
|
|
32
|
-
session_state = None
|
|
33
|
-
|
|
34
|
-
def save():
|
|
35
|
-
global last_snapshot
|
|
36
|
-
state["permissions"] = list(pending.values())
|
|
37
|
-
state["events"] = state["events"][-300:]
|
|
38
|
-
while len(state["events"]) > 1 and len(json.dumps(state["events"])) > 800_000:
|
|
39
|
-
state["events"].pop(0)
|
|
40
|
-
state["truncated"] = True
|
|
41
|
-
state["controlResults"] = state["controlResults"][-30:]
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
def
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
"
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
"
|
|
130
|
-
"
|
|
131
|
-
"
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
if
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
if
|
|
233
|
-
|
|
234
|
-
if
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
if
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
1
|
+
"""One owned Claude stream-json process, with durable UI control and event snapshots."""
|
|
2
|
+
import fcntl
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import selectors
|
|
7
|
+
import signal
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
root = Path.home() / ".local/state/scope/runs" / sys.argv[1]
|
|
13
|
+
config = json.loads((root / "claude-config.json").read_text(encoding="utf-8"))
|
|
14
|
+
controls = root / "controls"
|
|
15
|
+
controls.mkdir(mode=0o700, exist_ok=True)
|
|
16
|
+
mutex = (root / "control.lock").open("a")
|
|
17
|
+
state = {"status": "running", "sessionId": config.get("resumeSessionId"), "events": [],
|
|
18
|
+
"permissions": [], "controlResults": [], "text": "", "interactive": True}
|
|
19
|
+
pending = {}
|
|
20
|
+
queue = []
|
|
21
|
+
seen = set()
|
|
22
|
+
subagents = {}
|
|
23
|
+
finished = False
|
|
24
|
+
stopping = None
|
|
25
|
+
closing = None
|
|
26
|
+
initialized = False
|
|
27
|
+
partial = ""
|
|
28
|
+
result_value = None
|
|
29
|
+
last_snapshot = None
|
|
30
|
+
signal_stage = 0
|
|
31
|
+
inflight = set()
|
|
32
|
+
session_state = None
|
|
33
|
+
|
|
34
|
+
def save():
|
|
35
|
+
global last_snapshot
|
|
36
|
+
state["permissions"] = list(pending.values())
|
|
37
|
+
state["events"] = state["events"][-300:]
|
|
38
|
+
while len(state["events"]) > 1 and len(json.dumps(state["events"])) > 800_000:
|
|
39
|
+
state["events"].pop(0)
|
|
40
|
+
state["truncated"] = True
|
|
41
|
+
state["controlResults"] = state["controlResults"][-30:]
|
|
42
|
+
sub_list = list(subagents.values())[-24:]
|
|
43
|
+
# Keep total subagent workflow buffer bounded inside interactive.json
|
|
44
|
+
while len(json.dumps(sub_list)) > 240_000:
|
|
45
|
+
trimmed = False
|
|
46
|
+
for item in sub_list:
|
|
47
|
+
steps = item.get("steps")
|
|
48
|
+
if isinstance(steps, list) and len(steps) > 4:
|
|
49
|
+
item["steps"] = ([steps[0]] + steps[2:]) if steps[0].get("kind") == "prompt" else steps[1:]
|
|
50
|
+
trimmed = True
|
|
51
|
+
if not trimmed:
|
|
52
|
+
break
|
|
53
|
+
state["subagents"] = sub_list
|
|
54
|
+
state["partial"] = partial[-60000:]
|
|
55
|
+
encoded = json.dumps(state)
|
|
56
|
+
if encoded == last_snapshot: return
|
|
57
|
+
temporary = root / "interactive.tmp"
|
|
58
|
+
temporary.write_text(encoded, encoding="utf-8")
|
|
59
|
+
temporary.replace(root / "interactive.json")
|
|
60
|
+
last_snapshot = encoded
|
|
61
|
+
|
|
62
|
+
def event(kind, **data):
|
|
63
|
+
state["events"].append({"kind": kind, "at": int(time.time() * 1000), **data})
|
|
64
|
+
|
|
65
|
+
def send(value):
|
|
66
|
+
child.stdin.write((json.dumps(value) + "\n").encode())
|
|
67
|
+
child.stdin.flush()
|
|
68
|
+
|
|
69
|
+
def user(prompt):
|
|
70
|
+
send({"type": "user", "message": {"role": "user", "content": prompt},
|
|
71
|
+
"parent_tool_use_id": None, "session_id": state.get("sessionId") or ""})
|
|
72
|
+
|
|
73
|
+
def respond(request_id, response):
|
|
74
|
+
send({"type": "control_response", "response": {"subtype": "success", "request_id": request_id, "response": response}})
|
|
75
|
+
|
|
76
|
+
def find_subagent(task_id=None, tool_id=None):
|
|
77
|
+
if tool_id and tool_id in subagents:
|
|
78
|
+
return subagents[tool_id]
|
|
79
|
+
if task_id and task_id in subagents:
|
|
80
|
+
return subagents[task_id]
|
|
81
|
+
if task_id:
|
|
82
|
+
for entry in subagents.values():
|
|
83
|
+
if entry.get("taskId") == task_id:
|
|
84
|
+
return entry
|
|
85
|
+
if tool_id:
|
|
86
|
+
for entry in subagents.values():
|
|
87
|
+
if entry.get("toolUseId") == tool_id:
|
|
88
|
+
return entry
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
def subagent_tool_summary(name, raw_input):
|
|
92
|
+
if isinstance(raw_input, dict):
|
|
93
|
+
for key in ("description", "file_path", "path", "command", "cmd", "pattern", "query", "url", "glob", "prompt"):
|
|
94
|
+
val = raw_input.get(key)
|
|
95
|
+
if isinstance(val, str) and val.strip():
|
|
96
|
+
line = val.strip().splitlines()[0].strip()
|
|
97
|
+
if key in ("file_path", "path") and ("/" in line or "\\" in line):
|
|
98
|
+
return (line.replace("\\", "/").split("/")[-1] or line)[:80]
|
|
99
|
+
return line[:80]
|
|
100
|
+
return ""
|
|
101
|
+
|
|
102
|
+
def append_subagent_step(entry, step):
|
|
103
|
+
steps = entry.setdefault("steps", [])
|
|
104
|
+
steps.append(step)
|
|
105
|
+
if len(steps) > 40:
|
|
106
|
+
if steps[0].get("kind") == "prompt":
|
|
107
|
+
entry["steps"] = [steps[0]] + steps[-39:]
|
|
108
|
+
else:
|
|
109
|
+
entry["steps"] = steps[-40:]
|
|
110
|
+
entry["hasWorkflow"] = True
|
|
111
|
+
|
|
112
|
+
def frame(value):
|
|
113
|
+
global initialized, partial, result_value, finished, session_state
|
|
114
|
+
kind = value.get("type")
|
|
115
|
+
now_ms = int(time.time() * 1000)
|
|
116
|
+
if value.get("session_id"):
|
|
117
|
+
state["sessionId"] = value["session_id"]
|
|
118
|
+
if kind == "system":
|
|
119
|
+
subtype = value.get("subtype")
|
|
120
|
+
if subtype == "init": state["commands"] = [{"name": name} for name in value.get("slash_commands", [])]
|
|
121
|
+
task_id = value.get("task_id")
|
|
122
|
+
if subtype == "session_state_changed": session_state = value.get("state")
|
|
123
|
+
elif subtype == "task_started" and value.get("task_type") in ("local_agent", "local_workflow"):
|
|
124
|
+
inflight.add(task_id)
|
|
125
|
+
tool_id = value.get("tool_use_id")
|
|
126
|
+
entry = find_subagent(task_id=task_id, tool_id=tool_id)
|
|
127
|
+
if entry is None:
|
|
128
|
+
entry = {
|
|
129
|
+
"id": str(tool_id or task_id),
|
|
130
|
+
"toolUseId": str(tool_id) if tool_id else "",
|
|
131
|
+
"taskId": str(task_id),
|
|
132
|
+
"role": str(value.get("description") or "后台子代理")[:120],
|
|
133
|
+
"typeName": str(value.get("task_type") or "agent")[:60],
|
|
134
|
+
"background": True,
|
|
135
|
+
"status": "working",
|
|
136
|
+
"lastAction": "后台运行中",
|
|
137
|
+
"updatedAt": now_ms,
|
|
138
|
+
"hasWorkflow": True,
|
|
139
|
+
"steps": [],
|
|
140
|
+
"partial": "",
|
|
141
|
+
}
|
|
142
|
+
subagents[entry["id"]] = entry
|
|
143
|
+
else:
|
|
144
|
+
entry["taskId"] = str(task_id)
|
|
145
|
+
if tool_id and not entry.get("toolUseId"):
|
|
146
|
+
entry["toolUseId"] = str(tool_id)
|
|
147
|
+
entry["background"] = True
|
|
148
|
+
entry["status"] = "working"
|
|
149
|
+
entry["updatedAt"] = now_ms
|
|
150
|
+
elif subtype in ("task_progress", "task_updated"):
|
|
151
|
+
patch_status = value.get("patch", {}).get("status") if isinstance(value.get("patch"), dict) else None
|
|
152
|
+
if subtype == "task_updated" and patch_status in ("completed", "failed", "stopped"):
|
|
153
|
+
inflight.discard(task_id)
|
|
154
|
+
entry = find_subagent(task_id=task_id, tool_id=value.get("tool_use_id"))
|
|
155
|
+
if entry is not None:
|
|
156
|
+
action = value.get("last_tool_name") or value.get("description") or patch_status
|
|
157
|
+
if action: entry["lastAction"] = str(action)[:120]
|
|
158
|
+
if patch_status in ("completed", "failed", "stopped"):
|
|
159
|
+
entry["status"] = patch_status
|
|
160
|
+
entry["updatedAt"] = now_ms
|
|
161
|
+
elif subtype == "task_notification":
|
|
162
|
+
inflight.discard(task_id)
|
|
163
|
+
entry = find_subagent(task_id=task_id, tool_id=value.get("tool_use_id"))
|
|
164
|
+
if entry is None and task_id:
|
|
165
|
+
entry = {
|
|
166
|
+
"id": str(task_id),
|
|
167
|
+
"taskId": str(task_id),
|
|
168
|
+
"role": str(value.get("description") or "后台子代理")[:120],
|
|
169
|
+
"typeName": "local_agent",
|
|
170
|
+
"background": True,
|
|
171
|
+
"status": "completed",
|
|
172
|
+
"lastAction": "已完成",
|
|
173
|
+
"updatedAt": now_ms,
|
|
174
|
+
}
|
|
175
|
+
subagents[entry["id"]] = entry
|
|
176
|
+
if entry is not None:
|
|
177
|
+
done_status = value.get("status")
|
|
178
|
+
entry["status"] = done_status if done_status in ("completed", "failed", "stopped") else "completed"
|
|
179
|
+
entry["lastAction"] = str(value.get("summary") or "已完成")[:120]
|
|
180
|
+
entry["updatedAt"] = now_ms
|
|
181
|
+
if kind in ("assistant", "stream_event") and value.get("parent_tool_use_id") is None:
|
|
182
|
+
finished = False
|
|
183
|
+
if kind == "control_response" and value.get("response", {}).get("request_id") == "scope-init":
|
|
184
|
+
if value["response"].get("subtype") == "error":
|
|
185
|
+
raise RuntimeError(value["response"].get("error", "Claude initialization failed"))
|
|
186
|
+
initialized = True
|
|
187
|
+
state["commands"] = value["response"].get("response", {}).get("commands", [])
|
|
188
|
+
user(config["prompt"])
|
|
189
|
+
elif kind == "control_request":
|
|
190
|
+
request = value.get("request", {})
|
|
191
|
+
rid = value["request_id"]
|
|
192
|
+
if request.get("subtype") == "can_use_tool" and not stopping:
|
|
193
|
+
if len(json.dumps(request)) > 500_000:
|
|
194
|
+
respond(rid, {"behavior": "deny", "message": "Approval input exceeds display limit; split the operation"})
|
|
195
|
+
event("permission", text="审批内容过大,已拒绝;请拆分操作")
|
|
196
|
+
return
|
|
197
|
+
pending[rid] = {"id": rid, "tool": request.get("tool_name", "Tool"),
|
|
198
|
+
"input": request.get("input", {}), "description": request.get("description", ""),
|
|
199
|
+
"reason": request.get("decision_reason", ""), "path": request.get("blocked_path", "")}
|
|
200
|
+
state["status"] = "waiting_permission"
|
|
201
|
+
else:
|
|
202
|
+
respond(rid, {"behavior": "deny", "message": "SCOPE cannot handle this request or is stopping"})
|
|
203
|
+
elif kind == "control_cancel_request":
|
|
204
|
+
pending.pop(value.get("request_id"), None)
|
|
205
|
+
if not pending and not stopping: state["status"] = "running"
|
|
206
|
+
elif kind == "stream_event":
|
|
207
|
+
parent_id = value.get("parent_tool_use_id")
|
|
208
|
+
data = value.get("event", {})
|
|
209
|
+
if parent_id:
|
|
210
|
+
entry = find_subagent(tool_id=parent_id)
|
|
211
|
+
if entry is not None and data.get("type") == "content_block_delta" and data.get("delta", {}).get("type") == "text_delta":
|
|
212
|
+
entry["partial"] = (entry.get("partial", "") + data["delta"].get("text", ""))[-8000:]
|
|
213
|
+
entry["updatedAt"] = now_ms
|
|
214
|
+
entry["hasWorkflow"] = True
|
|
215
|
+
return
|
|
216
|
+
if data.get("type") == "content_block_delta" and data.get("delta", {}).get("type") == "text_delta":
|
|
217
|
+
partial += data["delta"].get("text", "")
|
|
218
|
+
elif kind == "assistant":
|
|
219
|
+
parent_id = value.get("parent_tool_use_id")
|
|
220
|
+
if parent_id:
|
|
221
|
+
entry = find_subagent(tool_id=parent_id)
|
|
222
|
+
if entry is not None:
|
|
223
|
+
entry["updatedAt"] = now_ms
|
|
224
|
+
entry["partial"] = ""
|
|
225
|
+
msg = value.get("message") if isinstance(value.get("message"), dict) else {}
|
|
226
|
+
if isinstance(msg.get("model"), str) and not entry.get("model"):
|
|
227
|
+
entry["model"] = msg["model"][:80]
|
|
228
|
+
for block in msg.get("content", []):
|
|
229
|
+
if not isinstance(block, dict):
|
|
230
|
+
continue
|
|
231
|
+
btype = block.get("type")
|
|
232
|
+
if btype == "thinking":
|
|
233
|
+
tval = str(block.get("thinking") or block.get("text") or "").strip()
|
|
234
|
+
if tval:
|
|
235
|
+
append_subagent_step(entry, {
|
|
236
|
+
"id": f"live-think-{now_ms}-{len(entry.get('steps', []))}",
|
|
237
|
+
"kind": "thinking",
|
|
238
|
+
"title": "思考过程",
|
|
239
|
+
"text": tval[:2500],
|
|
240
|
+
"timestamp": now_ms,
|
|
241
|
+
})
|
|
242
|
+
elif btype == "tool_use":
|
|
243
|
+
tname = str(block.get("name") or "工具调用")[:80]
|
|
244
|
+
tinput = block.get("input")
|
|
245
|
+
summary = subagent_tool_summary(tname, tinput)
|
|
246
|
+
entry["lastAction"] = f"{tname} · {summary}"[:96] if summary else tname
|
|
247
|
+
try:
|
|
248
|
+
in_str = json.dumps(tinput, ensure_ascii=False, indent=2) if tinput is not None else ""
|
|
249
|
+
except (TypeError, ValueError):
|
|
250
|
+
in_str = str(tinput)
|
|
251
|
+
append_subagent_step(entry, {
|
|
252
|
+
"id": str(block.get("id") or f"live-tool-{now_ms}-{len(entry.get('steps', []))}"),
|
|
253
|
+
"kind": "tool",
|
|
254
|
+
"toolName": tname,
|
|
255
|
+
"title": tname,
|
|
256
|
+
"summary": summary,
|
|
257
|
+
"inputPreview": in_str[:2500],
|
|
258
|
+
"output": "",
|
|
259
|
+
"isError": False,
|
|
260
|
+
"status": "running",
|
|
261
|
+
"timestamp": now_ms,
|
|
262
|
+
})
|
|
263
|
+
elif btype == "text":
|
|
264
|
+
tval = str(block.get("text") or "").strip()
|
|
265
|
+
if tval:
|
|
266
|
+
if not entry.get("lastAction"):
|
|
267
|
+
entry["lastAction"] = "生成回复中"
|
|
268
|
+
append_subagent_step(entry, {
|
|
269
|
+
"id": f"live-asst-{now_ms}-{len(entry.get('steps', []))}",
|
|
270
|
+
"kind": "assistant",
|
|
271
|
+
"title": "回复",
|
|
272
|
+
"text": tval[:6000],
|
|
273
|
+
"timestamp": now_ms,
|
|
274
|
+
})
|
|
275
|
+
return
|
|
276
|
+
partial = ""
|
|
277
|
+
for block in value.get("message", {}).get("content", []):
|
|
278
|
+
if block.get("type") == "text":
|
|
279
|
+
event("assistant", text=block.get("text", "")[-60000:])
|
|
280
|
+
elif block.get("type") == "tool_use":
|
|
281
|
+
tool_name = block.get("name")
|
|
282
|
+
tool_input = block.get("input", {})
|
|
283
|
+
if tool_name in ("Agent", "Task") and isinstance(tool_input, dict):
|
|
284
|
+
tid = str(block.get("id") or f"sub-{len(subagents) + 1}")
|
|
285
|
+
prompt_val = str(tool_input.get("prompt") or "").strip()
|
|
286
|
+
subagents[tid] = {
|
|
287
|
+
"id": tid,
|
|
288
|
+
"toolUseId": tid,
|
|
289
|
+
"role": str(tool_input.get("description") or prompt_val or "子代理任务")[:120],
|
|
290
|
+
"typeName": str(tool_input.get("subagent_type") or "agent")[:60],
|
|
291
|
+
"background": bool(tool_input.get("run_in_background")),
|
|
292
|
+
"status": "working",
|
|
293
|
+
"lastAction": "启动中",
|
|
294
|
+
"updatedAt": now_ms,
|
|
295
|
+
"hasWorkflow": True,
|
|
296
|
+
"steps": ([{"id": f"prompt-{tid}", "kind": "prompt", "title": "子代理任务", "text": prompt_val[:4000], "timestamp": now_ms}] if prompt_val else []),
|
|
297
|
+
"partial": "",
|
|
298
|
+
}
|
|
299
|
+
if len(json.dumps(tool_input)) > 60000: tool_input = {"preview": json.dumps(tool_input, ensure_ascii=False)[:60000], "truncated": True}
|
|
300
|
+
event("tool", id=block.get("id"), name=tool_name, input=tool_input)
|
|
301
|
+
elif kind == "user" and isinstance(value.get("message", {}).get("content"), list):
|
|
302
|
+
if value.get("parent_tool_use_id"):
|
|
303
|
+
entry = find_subagent(tool_id=value.get("parent_tool_use_id"))
|
|
304
|
+
if entry is not None:
|
|
305
|
+
entry["updatedAt"] = now_ms
|
|
306
|
+
for block in value["message"]["content"]:
|
|
307
|
+
if isinstance(block, dict) and block.get("type") == "tool_result":
|
|
308
|
+
tid = str(block.get("tool_use_id") or "")
|
|
309
|
+
raw_out = block.get("content", "")
|
|
310
|
+
if isinstance(raw_out, list):
|
|
311
|
+
out_text = "\n".join(
|
|
312
|
+
(p.get("text", "") if isinstance(p, dict) else str(p))
|
|
313
|
+
for p in raw_out
|
|
314
|
+
if not (isinstance(p, dict) and p.get("type") == "image")
|
|
315
|
+
)
|
|
316
|
+
elif isinstance(raw_out, str):
|
|
317
|
+
out_text = raw_out
|
|
318
|
+
else:
|
|
319
|
+
out_text = json.dumps(raw_out, ensure_ascii=False)
|
|
320
|
+
is_err = bool(block.get("is_error"))
|
|
321
|
+
for step in reversed(entry.get("steps", [])):
|
|
322
|
+
if step.get("kind") == "tool" and step.get("id") == tid:
|
|
323
|
+
step["output"] = out_text[:3000]
|
|
324
|
+
step["isError"] = is_err
|
|
325
|
+
step["status"] = "failed" if is_err else "completed"
|
|
326
|
+
break
|
|
327
|
+
return
|
|
328
|
+
for block in value["message"]["content"]:
|
|
329
|
+
if block.get("type") == "tool_result":
|
|
330
|
+
content = block.get("content", "")
|
|
331
|
+
tid = block.get("tool_use_id")
|
|
332
|
+
text_val = content if isinstance(content, str) else json.dumps(content)
|
|
333
|
+
if tid and tid in subagents:
|
|
334
|
+
entry = subagents[tid]
|
|
335
|
+
if "Async agent launched" in text_val or (entry.get("taskId") and entry["taskId"] in inflight):
|
|
336
|
+
entry["background"] = True
|
|
337
|
+
entry["lastAction"] = "后台运行中"
|
|
338
|
+
entry["updatedAt"] = now_ms
|
|
339
|
+
else:
|
|
340
|
+
entry["status"] = "failed" if block.get("is_error") else "completed"
|
|
341
|
+
entry["lastAction"] = "失败" if block.get("is_error") else "已完成"
|
|
342
|
+
entry["updatedAt"] = now_ms
|
|
343
|
+
event("tool_result", id=tid, text=text_val[-12000:])
|
|
344
|
+
elif kind == "result":
|
|
345
|
+
partial = ""
|
|
346
|
+
result_value = value
|
|
347
|
+
state["text"] = value.get("result", "")[-120000:]
|
|
348
|
+
state["error"] = (value.get("result") or "; ".join(value.get("errors", []))) if value.get("is_error") else None
|
|
349
|
+
finished = True
|
|
350
|
+
|
|
351
|
+
args = [config["executable"], "-p", "--input-format", "stream-json", "--output-format", "stream-json",
|
|
352
|
+
"--verbose", "--include-partial-messages", "--permission-prompt-tool", "stdio",
|
|
353
|
+
"--permission-mode", "acceptEdits" if config["permissionMode"] == "workspace" else config["permissionMode"]]
|
|
354
|
+
if config.get("model"): args += ["--model", config["model"]]
|
|
355
|
+
if config.get("effort"): args += ["--effort", config["effort"]]
|
|
356
|
+
if config.get("resumeSessionId"): args += ["--resume", config["resumeSessionId"]]
|
|
357
|
+
child = None
|
|
358
|
+
try:
|
|
359
|
+
with (root / "claude-stderr").open("wb") as errors:
|
|
360
|
+
child = subprocess.Popen(args, cwd=config["cwd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
361
|
+
stderr=errors, start_new_session=True,
|
|
362
|
+
env={**os.environ, "CLAUDE_CODE_SDK_READS_SESSION_STATE": "1"})
|
|
363
|
+
save()
|
|
364
|
+
selector = selectors.DefaultSelector()
|
|
365
|
+
selector.register(child.stdout, selectors.EVENT_READ)
|
|
366
|
+
send({"type": "control_request", "request_id": "scope-init", "request": {"subtype": "initialize", "hooks": {}}})
|
|
367
|
+
buffer = b""
|
|
368
|
+
started = time.monotonic()
|
|
369
|
+
while child.poll() is None:
|
|
370
|
+
for key, _ in selector.select(0.15):
|
|
371
|
+
chunk = os.read(key.fd, 65536)
|
|
372
|
+
if not chunk: continue
|
|
373
|
+
buffer += chunk
|
|
374
|
+
if len(buffer) > 8_000_000: raise RuntimeError("Claude event exceeds size limit")
|
|
375
|
+
while b"\n" in buffer:
|
|
376
|
+
line, buffer = buffer.split(b"\n", 1)
|
|
377
|
+
try: value = json.loads(line)
|
|
378
|
+
except ValueError: continue
|
|
379
|
+
frame(value)
|
|
380
|
+
fcntl.flock(mutex, fcntl.LOCK_EX)
|
|
381
|
+
try:
|
|
382
|
+
incoming = [(file, json.loads(file.read_text())) for file in controls.glob("*.json") if file.name not in seen]
|
|
383
|
+
for file, command in sorted(incoming, key=lambda item: (item[1].get("_sequence", 0), item[0].stat().st_mtime_ns, item[0].name)):
|
|
384
|
+
seen.add(file.name)
|
|
385
|
+
try:
|
|
386
|
+
action = command["action"]
|
|
387
|
+
if closing or stopping: raise ValueError("本轮正在结束,请等待后重新发送")
|
|
388
|
+
if action == "message":
|
|
389
|
+
queue.append(command["prompt"])
|
|
390
|
+
event("user", text=command["prompt"], queued=True)
|
|
391
|
+
elif action == "permission":
|
|
392
|
+
request = pending.get(command["requestId"])
|
|
393
|
+
if not request: raise ValueError("权限请求已失效或已处理")
|
|
394
|
+
response = {"behavior": "deny", "message": "用户拒绝了这次操作"}
|
|
395
|
+
if command["decision"] == "allow":
|
|
396
|
+
original = request["input"]
|
|
397
|
+
if request["tool"] == "AskUserQuestion":
|
|
398
|
+
answers = command.get("answers", {})
|
|
399
|
+
questions = original.get("questions", [])
|
|
400
|
+
if not questions or any(not isinstance(answers.get(q["question"]), str) or not answers[q["question"]].strip() for q in questions):
|
|
401
|
+
raise ValueError("请回答所有问题后提交")
|
|
402
|
+
original = {**original, "answers": {q["question"]: answers[q["question"]] for q in questions}}
|
|
403
|
+
response = {"behavior": "allow", "updatedInput": original}
|
|
404
|
+
respond(request["id"], response)
|
|
405
|
+
pending.pop(command["requestId"], None)
|
|
406
|
+
event("permission", text=f'{request["tool"]}: ' + ("允许这次" if command["decision"] == "allow" else "已拒绝"))
|
|
407
|
+
state["status"] = "waiting_permission" if pending else "running"
|
|
408
|
+
elif action == "stop":
|
|
409
|
+
stopping = time.monotonic()
|
|
410
|
+
if queue: event("permission", text=f"已取消 {len(queue)} 条尚未执行的追加消息")
|
|
411
|
+
queue.clear()
|
|
412
|
+
for request in list(pending.values()): respond(request["id"], {"behavior": "deny", "message": "用户已停止", "interrupt": True})
|
|
413
|
+
pending.clear()
|
|
414
|
+
send({"type": "control_request", "request_id": "scope-stop", "request": {"subtype": "interrupt"}})
|
|
415
|
+
state["status"] = "stopping"
|
|
416
|
+
state["controlResults"].append({"id": command["id"], "status": "accepted"})
|
|
417
|
+
except (KeyError, ValueError) as error:
|
|
418
|
+
state["controlResults"].append({"id": command.get("id"), "status": "rejected", "error": str(error)})
|
|
419
|
+
if finished and not stopping and not closing and not pending and not inflight and session_state in (None, "idle"):
|
|
420
|
+
if queue:
|
|
421
|
+
user(queue.pop(0))
|
|
422
|
+
finished = False
|
|
423
|
+
state["status"] = "running"
|
|
424
|
+
else:
|
|
425
|
+
closing = time.monotonic()
|
|
426
|
+
state["status"] = "finishing"
|
|
427
|
+
child.stdin.close()
|
|
428
|
+
save()
|
|
429
|
+
finally: fcntl.flock(mutex, fcntl.LOCK_UN)
|
|
430
|
+
now = time.monotonic()
|
|
431
|
+
if not initialized and now - started > 30: raise RuntimeError("Claude initialization timed out")
|
|
432
|
+
if stopping:
|
|
433
|
+
elapsed = now - stopping
|
|
434
|
+
stage = 3 if elapsed > 12 else 2 if elapsed > 8 else 1 if elapsed > 2 else 0
|
|
435
|
+
if stage > signal_stage and child.poll() is None:
|
|
436
|
+
os.killpg(child.pid, [None, signal.SIGINT, signal.SIGTERM, signal.SIGKILL][stage])
|
|
437
|
+
signal_stage = stage
|
|
438
|
+
elif closing and now - closing > 15:
|
|
439
|
+
# The completed turn's CLI is owned by this worker only.
|
|
440
|
+
os.killpg(child.pid, signal.SIGTERM)
|
|
441
|
+
child.wait()
|
|
442
|
+
state["status"] = "stopped" if stopping else "failed" if not result_value or result_value.get("is_error") else "completed"
|
|
443
|
+
if state["status"] == "stopped":
|
|
444
|
+
for entry in subagents.values():
|
|
445
|
+
if entry.get("status") == "working": entry["status"] = "stopped"
|
|
446
|
+
elif state["status"] in ("completed", "failed") and not inflight:
|
|
447
|
+
for entry in subagents.values():
|
|
448
|
+
if entry.get("status") == "working":
|
|
449
|
+
entry["status"] = "completed" if state["status"] == "completed" else "failed"
|
|
450
|
+
if state["status"] == "failed" and not state.get("error"):
|
|
451
|
+
state["error"] = (root / "claude-stderr").read_text(errors="replace")[-2000:] or "Claude exited without a result"
|
|
452
|
+
except Exception as error:
|
|
453
|
+
state["status"] = "failed"
|
|
454
|
+
state["error"] = str(error)
|
|
455
|
+
finally:
|
|
456
|
+
if child and child.poll() is None:
|
|
457
|
+
os.killpg(child.pid, signal.SIGTERM)
|
|
458
|
+
try: child.wait(timeout=3)
|
|
459
|
+
except subprocess.TimeoutExpired:
|
|
460
|
+
os.killpg(child.pid, signal.SIGKILL)
|
|
461
|
+
child.wait()
|
|
462
|
+
pending.clear()
|
|
463
|
+
save()
|