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.
Files changed (88) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/bridge/agent-email-relay.mjs +160 -160
  3. package/bridge/app-server-websocket-transport.mjs +219 -219
  4. package/bridge/archive/service.mjs +130 -130
  5. package/bridge/auth-profile-failover.mjs +58 -58
  6. package/bridge/auth-profile-manager.mjs +215 -215
  7. package/bridge/capacity-recovery.mjs +90 -90
  8. package/bridge/gpu-usage-history.mjs +322 -322
  9. package/bridge/local/history.mjs +20 -5
  10. package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -236
  11. package/bridge/plugins/aliyun-dlc/probe.mjs +701 -701
  12. package/bridge/private-gateway.mjs +371 -371
  13. package/bridge/private-start.mjs +22 -22
  14. package/bridge/probes/app-server-handoff-probe.mjs +87 -87
  15. package/bridge/probes/app-server-writer-probe.mjs +69 -69
  16. package/bridge/probes/assistant-search-probe.mjs +321 -321
  17. package/bridge/probes/dialogue-probe.mjs +462 -462
  18. package/bridge/probes/history-probe.mjs +430 -345
  19. package/bridge/probes/new-session-preflight.mjs +14 -14
  20. package/bridge/probes/profile-cancel-probe.mjs +17 -17
  21. package/bridge/probes/profile-delete-probe.mjs +26 -26
  22. package/bridge/probes/profile-list-probe.mjs +114 -114
  23. package/bridge/probes/profile-write-probe.mjs +109 -109
  24. package/bridge/probes/raw-context-probe.mjs +51 -51
  25. package/bridge/probes/remote-probe.mjs +627 -626
  26. package/bridge/probes/submission-probe.mjs +2 -2
  27. package/bridge/probes/takeover-probe.mjs +326 -326
  28. package/bridge/probes/vscode-open-preflight.mjs +21 -21
  29. package/bridge/providers/claude-interactive.py +463 -341
  30. package/bridge/providers/cli-command.mjs +103 -103
  31. package/bridge/providers/conversations.mjs +231 -231
  32. package/bridge/providers/native-commands.py +38 -38
  33. package/bridge/providers/native-session-state.mjs +14 -14
  34. package/bridge/providers/native-session-state.py +96 -96
  35. package/bridge/providers/remote-job.py +130 -130
  36. package/bridge/remote-app-server-command.mjs +121 -121
  37. package/bridge/remote-directory-listing.mjs +148 -148
  38. package/bridge/rollout-summary.mjs +20 -2
  39. package/bridge/routes/dialogue.mjs +48 -3
  40. package/bridge/routes/models.mjs +312 -312
  41. package/bridge/server.mjs +3357 -3332
  42. package/bridge/session-attachments.mjs +150 -150
  43. package/bridge/session-catalog/agy-history.py +141 -2
  44. package/bridge/session-catalog/catalog.mjs +17 -0
  45. package/bridge/session-catalog/probe.py +1207 -331
  46. package/bridge/session-catalog/routes.mjs +6 -0
  47. package/bridge/start.mjs +205 -205
  48. package/bridge/state-persistence.mjs +9 -1
  49. package/bridge/tmux-session-control.mjs +29 -29
  50. package/bridge/vscode-opener.mjs +157 -157
  51. package/bridge/web-terminal.mjs +52 -52
  52. package/bridge/workbench/manager-context.mjs +51 -51
  53. package/bridge/workbench/service.mjs +301 -301
  54. package/dist/client/.vite/manifest.json +4 -4
  55. package/dist/client/assets/{index-Enu1x0PS.js → index-BMior55c.js} +2 -2
  56. package/dist/client/assets/{layout-segment-context-CmJzExWq.js → layout-segment-context-DjGudgXn.js} +1 -1
  57. package/dist/client/assets/page-CJqXlhDs.js +551 -0
  58. package/dist/client/assets/page-LYzRz6_S.css +1 -0
  59. package/dist/client/favicon.svg +6 -6
  60. package/dist/server/__vite_rsc_assets_manifest.js +8 -8
  61. package/dist/server/index.js +7 -7
  62. package/dist/server/ssr/__vite_rsc_assets_manifest.js +8 -8
  63. package/dist/server/ssr/assets/{page-CYYyCnKD.js → page-BB9Dri2u.js} +2416 -271
  64. package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -0
  65. package/dist/server/ssr/index.js +1 -1
  66. package/dist/server/ssr/vinext-server.json +1 -1
  67. package/dist/server/vinext-server.json +1 -1
  68. package/dist/server/wrangler.json +1 -1
  69. package/lib/browser-snapshot-cache.js +53 -53
  70. package/lib/formula-preview.js +1 -1
  71. package/lib/incremental-snapshot.js +300 -300
  72. package/lib/markdown-math.js +151 -151
  73. package/lib/remote-links.js +95 -95
  74. package/lib/runtime-config.js +70 -70
  75. package/lib/session-filters.js +38 -38
  76. package/lib/ssh-config.js +26 -26
  77. package/lib/stable-order.js +39 -39
  78. package/lib/subagent-display-prefs.ts +130 -0
  79. package/package.json +1 -1
  80. package/scripts/agent-email-relay.mjs +104 -104
  81. package/scripts/email-notification-cli.mjs +28 -28
  82. package/scripts/enable-private-access.ps1 +109 -109
  83. package/scripts/fixtures/native-conversations.mjs +164 -6
  84. package/scripts/fixtures/workbench-conversations.mjs +475 -352
  85. package/scripts/preview-workbench.mjs +669 -669
  86. package/dist/client/assets/page-COBv6VWj.css +0 -1
  87. package/dist/client/assets/page-DVjU6VG_.js +0 -550
  88. 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
- state["subagents"] = list(subagents.values())[-24:]
43
- state["partial"] = partial[-60000:]
44
- encoded = json.dumps(state)
45
- if encoded == last_snapshot: return
46
- temporary = root / "interactive.tmp"
47
- temporary.write_text(encoded, encoding="utf-8")
48
- temporary.replace(root / "interactive.json")
49
- last_snapshot = encoded
50
-
51
- def event(kind, **data):
52
- state["events"].append({"kind": kind, "at": int(time.time() * 1000), **data})
53
-
54
- def send(value):
55
- child.stdin.write((json.dumps(value) + "\n").encode())
56
- child.stdin.flush()
57
-
58
- def user(prompt):
59
- send({"type": "user", "message": {"role": "user", "content": prompt},
60
- "parent_tool_use_id": None, "session_id": state.get("sessionId") or ""})
61
-
62
- def respond(request_id, response):
63
- send({"type": "control_response", "response": {"subtype": "success", "request_id": request_id, "response": response}})
64
-
65
- def find_subagent(task_id=None, tool_id=None):
66
- if tool_id and tool_id in subagents:
67
- return subagents[tool_id]
68
- if task_id and task_id in subagents:
69
- return subagents[task_id]
70
- if task_id:
71
- for entry in subagents.values():
72
- if entry.get("taskId") == task_id:
73
- return entry
74
- return None
75
-
76
- def frame(value):
77
- global initialized, partial, result_value, finished, session_state
78
- kind = value.get("type")
79
- now_ms = int(time.time() * 1000)
80
- if value.get("session_id"):
81
- state["sessionId"] = value["session_id"]
82
- if kind == "system":
83
- subtype = value.get("subtype")
84
- if subtype == "init": state["commands"] = [{"name": name} for name in value.get("slash_commands", [])]
85
- task_id = value.get("task_id")
86
- if subtype == "session_state_changed": session_state = value.get("state")
87
- elif subtype == "task_started" and value.get("task_type") in ("local_agent", "local_workflow"):
88
- inflight.add(task_id)
89
- tool_id = value.get("tool_use_id")
90
- entry = find_subagent(task_id=task_id, tool_id=tool_id)
91
- if entry is None:
92
- entry = {
93
- "id": str(tool_id or task_id),
94
- "taskId": str(task_id),
95
- "role": str(value.get("description") or "后台子代理")[:120],
96
- "typeName": str(value.get("task_type") or "agent")[:60],
97
- "background": True,
98
- "status": "working",
99
- "lastAction": "后台运行中",
100
- "updatedAt": now_ms,
101
- }
102
- subagents[entry["id"]] = entry
103
- else:
104
- entry["taskId"] = str(task_id)
105
- entry["background"] = True
106
- entry["status"] = "working"
107
- entry["updatedAt"] = now_ms
108
- elif subtype in ("task_progress", "task_updated"):
109
- patch_status = value.get("patch", {}).get("status") if isinstance(value.get("patch"), dict) else None
110
- if subtype == "task_updated" and patch_status in ("completed", "failed", "stopped"):
111
- inflight.discard(task_id)
112
- entry = find_subagent(task_id=task_id, tool_id=value.get("tool_use_id"))
113
- if entry is not None:
114
- action = value.get("last_tool_name") or value.get("description") or patch_status
115
- if action: entry["lastAction"] = str(action)[:120]
116
- if patch_status in ("completed", "failed", "stopped"):
117
- entry["status"] = patch_status
118
- entry["updatedAt"] = now_ms
119
- elif subtype == "task_notification":
120
- inflight.discard(task_id)
121
- entry = find_subagent(task_id=task_id, tool_id=value.get("tool_use_id"))
122
- if entry is None and task_id:
123
- entry = {
124
- "id": str(task_id),
125
- "taskId": str(task_id),
126
- "role": str(value.get("description") or "后台子代理")[:120],
127
- "typeName": "local_agent",
128
- "background": True,
129
- "status": "completed",
130
- "lastAction": "已完成",
131
- "updatedAt": now_ms,
132
- }
133
- subagents[entry["id"]] = entry
134
- if entry is not None:
135
- done_status = value.get("status")
136
- entry["status"] = done_status if done_status in ("completed", "failed", "stopped") else "completed"
137
- entry["lastAction"] = str(value.get("summary") or "已完成")[:120]
138
- entry["updatedAt"] = now_ms
139
- if kind in ("assistant", "stream_event") and value.get("parent_tool_use_id") is None:
140
- finished = False
141
- if kind == "control_response" and value.get("response", {}).get("request_id") == "scope-init":
142
- if value["response"].get("subtype") == "error":
143
- raise RuntimeError(value["response"].get("error", "Claude initialization failed"))
144
- initialized = True
145
- state["commands"] = value["response"].get("response", {}).get("commands", [])
146
- user(config["prompt"])
147
- elif kind == "control_request":
148
- request = value.get("request", {})
149
- rid = value["request_id"]
150
- if request.get("subtype") == "can_use_tool" and not stopping:
151
- if len(json.dumps(request)) > 500_000:
152
- respond(rid, {"behavior": "deny", "message": "Approval input exceeds display limit; split the operation"})
153
- event("permission", text="审批内容过大,已拒绝;请拆分操作")
154
- return
155
- pending[rid] = {"id": rid, "tool": request.get("tool_name", "Tool"),
156
- "input": request.get("input", {}), "description": request.get("description", ""),
157
- "reason": request.get("decision_reason", ""), "path": request.get("blocked_path", "")}
158
- state["status"] = "waiting_permission"
159
- else:
160
- respond(rid, {"behavior": "deny", "message": "SCOPE cannot handle this request or is stopping"})
161
- elif kind == "control_cancel_request":
162
- pending.pop(value.get("request_id"), None)
163
- if not pending and not stopping: state["status"] = "running"
164
- elif kind == "stream_event":
165
- if value.get("parent_tool_use_id"): return
166
- data = value.get("event", {})
167
- if data.get("type") == "content_block_delta" and data.get("delta", {}).get("type") == "text_delta":
168
- partial += data["delta"].get("text", "")
169
- elif kind == "assistant":
170
- parent_id = value.get("parent_tool_use_id")
171
- if parent_id:
172
- entry = find_subagent(tool_id=parent_id)
173
- if entry is not None:
174
- entry["updatedAt"] = now_ms
175
- for block in value.get("message", {}).get("content", []):
176
- if block.get("type") == "tool_use":
177
- entry["lastAction"] = str(block.get("name") or "工具调用")[:80]
178
- elif block.get("type") == "text" and not entry.get("lastAction"):
179
- entry["lastAction"] = "生成回复中"
180
- return
181
- partial = ""
182
- for block in value.get("message", {}).get("content", []):
183
- if block.get("type") == "text":
184
- event("assistant", text=block.get("text", "")[-60000:])
185
- elif block.get("type") == "tool_use":
186
- tool_name = block.get("name")
187
- tool_input = block.get("input", {})
188
- if tool_name in ("Agent", "Task") and isinstance(tool_input, dict):
189
- tid = str(block.get("id") or f"sub-{len(subagents) + 1}")
190
- subagents[tid] = {
191
- "id": tid,
192
- "role": str(tool_input.get("description") or tool_input.get("prompt") or "子代理任务")[:120],
193
- "typeName": str(tool_input.get("subagent_type") or "agent")[:60],
194
- "background": bool(tool_input.get("run_in_background")),
195
- "status": "working",
196
- "lastAction": "启动中",
197
- "updatedAt": now_ms,
198
- }
199
- if len(json.dumps(tool_input)) > 60000: tool_input = {"preview": json.dumps(tool_input, ensure_ascii=False)[:60000], "truncated": True}
200
- event("tool", id=block.get("id"), name=tool_name, input=tool_input)
201
- elif kind == "user" and isinstance(value.get("message", {}).get("content"), list):
202
- if value.get("parent_tool_use_id"):
203
- entry = find_subagent(tool_id=value.get("parent_tool_use_id"))
204
- if entry is not None: entry["updatedAt"] = now_ms
205
- return
206
- for block in value["message"]["content"]:
207
- if block.get("type") == "tool_result":
208
- content = block.get("content", "")
209
- tid = block.get("tool_use_id")
210
- text_val = content if isinstance(content, str) else json.dumps(content)
211
- if tid and tid in subagents:
212
- entry = subagents[tid]
213
- if "Async agent launched" in text_val or (entry.get("taskId") and entry["taskId"] in inflight):
214
- entry["background"] = True
215
- entry["lastAction"] = "后台运行中"
216
- entry["updatedAt"] = now_ms
217
- else:
218
- entry["status"] = "failed" if block.get("is_error") else "completed"
219
- entry["lastAction"] = "失败" if block.get("is_error") else "已完成"
220
- entry["updatedAt"] = now_ms
221
- event("tool_result", id=tid, text=text_val[-12000:])
222
- elif kind == "result":
223
- partial = ""
224
- result_value = value
225
- state["text"] = value.get("result", "")[-120000:]
226
- state["error"] = (value.get("result") or "; ".join(value.get("errors", []))) if value.get("is_error") else None
227
- finished = True
228
-
229
- args = [config["executable"], "-p", "--input-format", "stream-json", "--output-format", "stream-json",
230
- "--verbose", "--include-partial-messages", "--permission-prompt-tool", "stdio",
231
- "--permission-mode", "acceptEdits" if config["permissionMode"] == "workspace" else config["permissionMode"]]
232
- if config.get("model"): args += ["--model", config["model"]]
233
- if config.get("effort"): args += ["--effort", config["effort"]]
234
- if config.get("resumeSessionId"): args += ["--resume", config["resumeSessionId"]]
235
- child = None
236
- try:
237
- with (root / "claude-stderr").open("wb") as errors:
238
- child = subprocess.Popen(args, cwd=config["cwd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
239
- stderr=errors, start_new_session=True,
240
- env={**os.environ, "CLAUDE_CODE_SDK_READS_SESSION_STATE": "1"})
241
- save()
242
- selector = selectors.DefaultSelector()
243
- selector.register(child.stdout, selectors.EVENT_READ)
244
- send({"type": "control_request", "request_id": "scope-init", "request": {"subtype": "initialize", "hooks": {}}})
245
- buffer = b""
246
- started = time.monotonic()
247
- while child.poll() is None:
248
- for key, _ in selector.select(0.15):
249
- chunk = os.read(key.fd, 65536)
250
- if not chunk: continue
251
- buffer += chunk
252
- if len(buffer) > 8_000_000: raise RuntimeError("Claude event exceeds size limit")
253
- while b"\n" in buffer:
254
- line, buffer = buffer.split(b"\n", 1)
255
- try: value = json.loads(line)
256
- except ValueError: continue
257
- frame(value)
258
- fcntl.flock(mutex, fcntl.LOCK_EX)
259
- try:
260
- incoming = [(file, json.loads(file.read_text())) for file in controls.glob("*.json") if file.name not in seen]
261
- for file, command in sorted(incoming, key=lambda item: (item[1].get("_sequence", 0), item[0].stat().st_mtime_ns, item[0].name)):
262
- seen.add(file.name)
263
- try:
264
- action = command["action"]
265
- if closing or stopping: raise ValueError("本轮正在结束,请等待后重新发送")
266
- if action == "message":
267
- queue.append(command["prompt"])
268
- event("user", text=command["prompt"], queued=True)
269
- elif action == "permission":
270
- request = pending.get(command["requestId"])
271
- if not request: raise ValueError("权限请求已失效或已处理")
272
- response = {"behavior": "deny", "message": "用户拒绝了这次操作"}
273
- if command["decision"] == "allow":
274
- original = request["input"]
275
- if request["tool"] == "AskUserQuestion":
276
- answers = command.get("answers", {})
277
- questions = original.get("questions", [])
278
- if not questions or any(not isinstance(answers.get(q["question"]), str) or not answers[q["question"]].strip() for q in questions):
279
- raise ValueError("请回答所有问题后提交")
280
- original = {**original, "answers": {q["question"]: answers[q["question"]] for q in questions}}
281
- response = {"behavior": "allow", "updatedInput": original}
282
- respond(request["id"], response)
283
- pending.pop(command["requestId"], None)
284
- event("permission", text=f'{request["tool"]}: ' + ("允许这次" if command["decision"] == "allow" else "已拒绝"))
285
- state["status"] = "waiting_permission" if pending else "running"
286
- elif action == "stop":
287
- stopping = time.monotonic()
288
- if queue: event("permission", text=f"已取消 {len(queue)} 条尚未执行的追加消息")
289
- queue.clear()
290
- for request in list(pending.values()): respond(request["id"], {"behavior": "deny", "message": "用户已停止", "interrupt": True})
291
- pending.clear()
292
- send({"type": "control_request", "request_id": "scope-stop", "request": {"subtype": "interrupt"}})
293
- state["status"] = "stopping"
294
- state["controlResults"].append({"id": command["id"], "status": "accepted"})
295
- except (KeyError, ValueError) as error:
296
- state["controlResults"].append({"id": command.get("id"), "status": "rejected", "error": str(error)})
297
- if finished and not stopping and not closing and not pending and not inflight and session_state in (None, "idle"):
298
- if queue:
299
- user(queue.pop(0))
300
- finished = False
301
- state["status"] = "running"
302
- else:
303
- closing = time.monotonic()
304
- state["status"] = "finishing"
305
- child.stdin.close()
306
- save()
307
- finally: fcntl.flock(mutex, fcntl.LOCK_UN)
308
- now = time.monotonic()
309
- if not initialized and now - started > 30: raise RuntimeError("Claude initialization timed out")
310
- if stopping:
311
- elapsed = now - stopping
312
- stage = 3 if elapsed > 12 else 2 if elapsed > 8 else 1 if elapsed > 2 else 0
313
- if stage > signal_stage and child.poll() is None:
314
- os.killpg(child.pid, [None, signal.SIGINT, signal.SIGTERM, signal.SIGKILL][stage])
315
- signal_stage = stage
316
- elif closing and now - closing > 15:
317
- # The completed turn's CLI is owned by this worker only.
318
- os.killpg(child.pid, signal.SIGTERM)
319
- child.wait()
320
- state["status"] = "stopped" if stopping else "failed" if not result_value or result_value.get("is_error") else "completed"
321
- if state["status"] == "stopped":
322
- for entry in subagents.values():
323
- if entry.get("status") == "working": entry["status"] = "stopped"
324
- elif state["status"] in ("completed", "failed") and not inflight:
325
- for entry in subagents.values():
326
- if entry.get("status") == "working":
327
- entry["status"] = "completed" if state["status"] == "completed" else "failed"
328
- if state["status"] == "failed" and not state.get("error"):
329
- state["error"] = (root / "claude-stderr").read_text(errors="replace")[-2000:] or "Claude exited without a result"
330
- except Exception as error:
331
- state["status"] = "failed"
332
- state["error"] = str(error)
333
- finally:
334
- if child and child.poll() is None:
335
- os.killpg(child.pid, signal.SIGTERM)
336
- try: child.wait(timeout=3)
337
- except subprocess.TimeoutExpired:
338
- os.killpg(child.pid, signal.SIGKILL)
339
- child.wait()
340
- pending.clear()
341
- save()
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()