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,323 +1,323 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const ASSISTANT_SEARCH_PROBE = String.raw`
3
- import base64
4
- import glob
5
- import json
6
- import os
7
- import re
8
- import subprocess
9
- import sys
10
-
11
- if hasattr(sys.stdout, "reconfigure"):
12
- try:
13
- sys.stdout.reconfigure(encoding="utf-8")
14
- except Exception:
15
- pass
16
-
17
- config = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "==").decode("utf-8"))
18
- question = str(config.get("question") or "").strip()
19
- result_limit = max(3, min(20, int(config.get("limit") or 10)))
20
- max_files = max(50, min(1000, int(config.get("maxFiles") or 600)))
21
-
22
- ascii_stops = {
23
- "a", "an", "and", "are", "can", "codex", "confirm", "did", "do", "does",
24
- "find", "for", "from", "i", "in", "is", "it", "me", "my", "now", "of",
25
- "on", "one", "please", "session", "sessions", "that", "the", "this", "to",
26
- "use", "using", "want", "which", "with",
27
- }
28
- chinese_stops = (
29
- "我现在想确认", "我想确认", "请帮我", "帮我", "现在", "对应", "使用",
30
- "哪个", "哪一个", "是什么", "是哪", "这个", "那个", "会话", "任务",
31
- "去做",
32
- )
33
-
34
- lowered_question = question.lower()
35
- ascii_terms = []
36
- for term in re.findall(r"[a-z0-9][a-z0-9_.-]*", lowered_question):
37
- cleaned = term.strip("._-")
38
- if not cleaned or cleaned in ascii_stops:
39
- continue
40
- if len(cleaned) == 1 and cleaned not in {"x", "y", "z"}:
41
- continue
42
- if cleaned not in ascii_terms:
43
- ascii_terms.append(cleaned)
44
-
45
- chinese_query = lowered_question
46
- for stop in chinese_stops:
47
- chinese_query = chinese_query.replace(stop, " ")
48
- chinese_terms = []
49
- for run in re.findall(r"[\u3400-\u9fff]{2,}", chinese_query):
50
- candidates = [run]
51
- if len(run) > 6:
52
- candidates.extend(run[index:index + 3] for index in range(len(run) - 2))
53
- for candidate in candidates:
54
- if candidate not in chinese_terms:
55
- chinese_terms.append(candidate)
56
-
57
- terms = (ascii_terms + chinese_terms)[:24]
58
- if not terms:
59
- terms = [question.lower()[:80]]
60
-
61
- sessions_root = os.path.expanduser("~/.codex/sessions")
62
- all_paths = glob.glob(os.path.join(sessions_root, "**", "*.jsonl"), recursive=True)
63
- all_paths.sort(key=lambda item: os.path.getmtime(item), reverse=True)
64
-
65
- matching_paths = []
66
- if all_paths:
67
- if os.name == "nt":
68
- matching_paths = all_paths[:max_files]
69
- else:
70
- pattern = "|".join(re.escape(term) for term in terms if term)
71
- try:
72
- grep = subprocess.run(
73
- ["grep", "-RIilE", pattern, sessions_root],
74
- stdout=subprocess.PIPE,
75
- stderr=subprocess.DEVNULL,
76
- text=True,
77
- timeout=15,
78
- )
79
- if grep.returncode in (0, 1):
80
- matching = {
81
- os.path.normcase(os.path.normpath(line))
82
- for line in grep.stdout.splitlines()
83
- if line.endswith(".jsonl")
84
- }
85
- matching_paths = [
86
- item
87
- for item in all_paths
88
- if os.path.normcase(os.path.normpath(item)) in matching
89
- ][:max_files]
90
- else:
91
- matching_paths = all_paths[:max_files]
92
- except Exception:
93
- matching_paths = all_paths[:max_files]
94
-
95
- def text_from_content(content):
96
- if isinstance(content, str):
97
- return content
98
- if not isinstance(content, list):
99
- return ""
100
- parts = []
101
- for item in content:
102
- if not isinstance(item, dict) or item.get("type") == "encrypted_content":
103
- continue
104
- text = item.get("text")
105
- if isinstance(text, str):
106
- parts.append(text)
107
- return "\n".join(parts)
108
-
109
- def is_context_message(value):
110
- if not isinstance(value, str):
111
- return True
112
- return value.lstrip().startswith((
113
- "<environment_context>",
114
- "<permissions",
115
- "<INSTRUCTIONS>",
116
- "<collaboration_mode>",
117
- "<apps_instructions>",
118
- "<plugins_instructions>",
119
- "<skills_instructions>",
120
- "<recommended_plugins>",
121
- "<in-app-browser-context",
122
- "# AGENTS.md instructions",
123
- "A previous agent produced",
124
- "You are Codex",
125
- ))
126
-
127
- def clean(value, limit=1200):
128
- if not isinstance(value, str):
129
- value = json.dumps(value, ensure_ascii=False)
130
- return " ".join(value.replace("\x00", "").split())[:limit]
131
-
132
- def snippets_for(value, hits):
133
- normalized = " ".join(value.replace("\x00", "").split())
134
- lowered = normalized.lower()
135
- positions = [lowered.find(term) for term in hits if lowered.find(term) >= 0]
136
- start = max(0, (min(positions) if positions else 0) - 150)
137
- return normalized[start:start + 700]
138
-
139
- def event_texts(event):
140
- payload = event.get("payload", {})
141
- if not isinstance(payload, dict):
142
- return []
143
- timestamp = event.get("timestamp")
144
- event_type = event.get("type")
145
- output = []
146
- if event_type == "event_msg":
147
- kind = payload.get("type")
148
- if kind in ("user_message", "user_input"):
149
- text = payload.get("message") or payload.get("text") or payload.get("content")
150
- if isinstance(text, str) and not is_context_message(text):
151
- output.append(("user", text, timestamp, 8))
152
- elif kind in ("agent_message", "task_complete", "turn_complete", "task_completed"):
153
- text = payload.get("message") or payload.get("text") or payload.get("last_agent_message")
154
- if isinstance(text, str):
155
- output.append(("assistant", text, timestamp, 6))
156
- return output
157
- if event_type != "response_item":
158
- return output
159
- kind = payload.get("type")
160
- role = payload.get("role")
161
- if kind == "message" and role in ("user", "assistant"):
162
- text = text_from_content(payload.get("content"))
163
- if text and (role != "user" or not is_context_message(text)):
164
- output.append((role, text, timestamp, 8 if role == "user" else 6))
165
- elif kind in ("function_call", "custom_tool_call"):
166
- arguments = payload.get("arguments") or payload.get("input") or ""
167
- output.append(("command", clean(arguments, 20000), timestamp, 7))
168
- elif kind in ("function_call_output", "custom_tool_call_output"):
169
- value = payload.get("output") or ""
170
- output.append(("output", clean(value, 20000), timestamp, 3))
171
- return output
172
-
173
- records = []
174
- for filename in matching_paths:
175
- try:
176
- with open(filename, "r", encoding="utf-8", errors="replace") as handle:
177
- first_raw = handle.readline()
178
- first_obj = json.loads(first_raw)
179
- meta = (
180
- first_obj.get("payload", {})
181
- if first_obj.get("type") == "session_meta"
182
- else {}
183
- )
184
- if not isinstance(meta, dict):
185
- meta = {}
186
- source = meta.get("source")
187
- subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
188
- spawn = subagent.get("thread_spawn", {}) if isinstance(subagent, dict) else {}
189
- record = {
190
- "id": meta.get("id") or meta.get("session_id") or os.path.basename(filename),
191
- "rootSessionId": meta.get("session_id") or meta.get("id") or "",
192
- "parentThreadId": meta.get("parent_thread_id") or spawn.get("parent_thread_id") or "",
193
- "agentPath": spawn.get("agent_path") or "",
194
- "agentNickname": spawn.get("agent_nickname") or "",
195
- "isSubagent": bool(spawn or meta.get("parent_thread_id")),
196
- "cwd": meta.get("cwd") or "",
197
- "startedAt": meta.get("timestamp") or first_obj.get("timestamp"),
198
- "cliVersion": meta.get("cli_version") or "",
199
- "path": filename,
200
- "mtimeMs": int(os.path.getmtime(filename) * 1000),
201
- "firstUser": "",
202
- "lastUser": "",
203
- "lastAssistant": "",
204
- "lastAction": "",
205
- "lastError": "",
206
- "userMessages": [],
207
- "assistantMessages": [],
208
- "model": "",
209
- "reasoningEffort": "",
210
- "approvalPolicy": "",
211
- "sandboxPolicy": "",
212
- "collaborationMode": "",
213
- "launches": [],
214
- "account": None,
215
- "tokenUsage": None,
216
- "turnState": "idle",
217
- "lastEventAt": first_obj.get("timestamp"),
218
- }
219
- matched = set()
220
- evidence = []
221
- term_weights = {}
222
- best_event_hits = 0
223
- best_event_weight = 0
224
- proximity_bonus = 0
225
- for raw in handle:
226
- try:
227
- event = json.loads(raw)
228
- except Exception:
229
- continue
230
- for kind, text, timestamp, weight in event_texts(event):
231
- lowered = text.lower()
232
- hits = [term for term in terms if term and term in lowered]
233
- if not hits:
234
- continue
235
- unique_hits = list(dict.fromkeys(hits))
236
- matched.update(unique_hits)
237
- for term in unique_hits:
238
- term_weights[term] = max(
239
- term_weights.get(term, 0),
240
- weight * (0.6 if len(term) == 1 else 1),
241
- )
242
- best_event_hits = max(best_event_hits, len(unique_hits))
243
- best_event_weight = max(
244
- best_event_weight,
245
- weight if len(unique_hits) == best_event_hits else 0,
246
- )
247
- positions = [lowered.find(term) for term in unique_hits]
248
- if len(positions) >= 3:
249
- span = max(positions) - min(positions)
250
- proximity_bonus = max(
251
- proximity_bonus,
252
- 80 if span <= 500 else 45 if span <= 1600 else 20,
253
- )
254
- snippet = snippets_for(text, hits)
255
- if snippet and all(item["text"] != snippet for item in evidence):
256
- evidence.append({
257
- "kind": kind,
258
- "timestamp": timestamp,
259
- "text": snippet,
260
- "terms": list(dict.fromkeys(hits)),
261
- "weight": weight,
262
- })
263
- if kind == "user":
264
- record["firstUser"] = record["firstUser"] or clean(text)
265
- record["lastUser"] = clean(text)
266
- record["userMessages"].append(clean(text))
267
- record["userMessages"] = record["userMessages"][-4:]
268
- elif kind == "assistant":
269
- record["lastAssistant"] = clean(text)
270
- record["assistantMessages"].append(clean(text))
271
- record["assistantMessages"] = record["assistantMessages"][-4:]
272
- elif kind == "command":
273
- record["lastAction"] = clean(text)
274
- if not matched:
275
- continue
276
- coverage = len(matched) / max(1, len(terms))
277
- phrase_bonus = 0
278
- ascii_phrase = " ".join(ascii_terms)
279
- combined_evidence = " ".join(item["text"].lower() for item in evidence)
280
- if len(ascii_terms) >= 2 and ascii_phrase in combined_evidence:
281
- phrase_bonus = 18
282
- score = (
283
- sum(term_weights.values()) * 4
284
- + coverage * coverage * 55
285
- + best_event_hits * best_event_hits * 6
286
- + best_event_weight
287
- + proximity_bonus
288
- + phrase_bonus
289
- )
290
- evidence.sort(
291
- key=lambda item: (len(item["terms"]), item["weight"]),
292
- reverse=True,
293
- )
294
- records.append({
295
- "rollout": record,
296
- "score": round(score, 2),
297
- "coverage": round(coverage, 3),
298
- "bestEventHits": best_event_hits,
299
- "matchedTerms": sorted(matched),
300
- "evidence": [
301
- {key: value for key, value in item.items() if key != "weight"}
302
- for item in evidence[:6]
303
- ],
304
- })
305
- except Exception:
306
- continue
307
-
308
- records.sort(
309
- key=lambda item: (
310
- item["coverage"],
311
- item["bestEventHits"],
312
- item["score"],
313
- item["rollout"]["mtimeMs"],
314
- ),
315
- reverse=True,
316
- )
317
- print(json.dumps({
318
- "terms": terms,
319
- "filesScanned": len(matching_paths),
320
- "totalFiles": len(all_paths),
321
- "results": records[:result_limit],
322
- }, ensure_ascii=False, separators=(",", ":")))
2
+ export const ASSISTANT_SEARCH_PROBE = String.raw`
3
+ import base64
4
+ import glob
5
+ import json
6
+ import os
7
+ import re
8
+ import subprocess
9
+ import sys
10
+
11
+ if hasattr(sys.stdout, "reconfigure"):
12
+ try:
13
+ sys.stdout.reconfigure(encoding="utf-8")
14
+ except Exception:
15
+ pass
16
+
17
+ config = json.loads(base64.urlsafe_b64decode(sys.argv[1] + "==").decode("utf-8"))
18
+ question = str(config.get("question") or "").strip()
19
+ result_limit = max(3, min(20, int(config.get("limit") or 10)))
20
+ max_files = max(50, min(1000, int(config.get("maxFiles") or 600)))
21
+
22
+ ascii_stops = {
23
+ "a", "an", "and", "are", "can", "codex", "confirm", "did", "do", "does",
24
+ "find", "for", "from", "i", "in", "is", "it", "me", "my", "now", "of",
25
+ "on", "one", "please", "session", "sessions", "that", "the", "this", "to",
26
+ "use", "using", "want", "which", "with",
27
+ }
28
+ chinese_stops = (
29
+ "我现在想确认", "我想确认", "请帮我", "帮我", "现在", "对应", "使用",
30
+ "哪个", "哪一个", "是什么", "是哪", "这个", "那个", "会话", "任务",
31
+ "去做",
32
+ )
33
+
34
+ lowered_question = question.lower()
35
+ ascii_terms = []
36
+ for term in re.findall(r"[a-z0-9][a-z0-9_.-]*", lowered_question):
37
+ cleaned = term.strip("._-")
38
+ if not cleaned or cleaned in ascii_stops:
39
+ continue
40
+ if len(cleaned) == 1 and cleaned not in {"x", "y", "z"}:
41
+ continue
42
+ if cleaned not in ascii_terms:
43
+ ascii_terms.append(cleaned)
44
+
45
+ chinese_query = lowered_question
46
+ for stop in chinese_stops:
47
+ chinese_query = chinese_query.replace(stop, " ")
48
+ chinese_terms = []
49
+ for run in re.findall(r"[\u3400-\u9fff]{2,}", chinese_query):
50
+ candidates = [run]
51
+ if len(run) > 6:
52
+ candidates.extend(run[index:index + 3] for index in range(len(run) - 2))
53
+ for candidate in candidates:
54
+ if candidate not in chinese_terms:
55
+ chinese_terms.append(candidate)
56
+
57
+ terms = (ascii_terms + chinese_terms)[:24]
58
+ if not terms:
59
+ terms = [question.lower()[:80]]
60
+
61
+ sessions_root = os.path.expanduser("~/.codex/sessions")
62
+ all_paths = glob.glob(os.path.join(sessions_root, "**", "*.jsonl"), recursive=True)
63
+ all_paths.sort(key=lambda item: os.path.getmtime(item), reverse=True)
64
+
65
+ matching_paths = []
66
+ if all_paths:
67
+ if os.name == "nt":
68
+ matching_paths = all_paths[:max_files]
69
+ else:
70
+ pattern = "|".join(re.escape(term) for term in terms if term)
71
+ try:
72
+ grep = subprocess.run(
73
+ ["grep", "-RIilE", pattern, sessions_root],
74
+ stdout=subprocess.PIPE,
75
+ stderr=subprocess.DEVNULL,
76
+ text=True,
77
+ timeout=15,
78
+ )
79
+ if grep.returncode in (0, 1):
80
+ matching = {
81
+ os.path.normcase(os.path.normpath(line))
82
+ for line in grep.stdout.splitlines()
83
+ if line.endswith(".jsonl")
84
+ }
85
+ matching_paths = [
86
+ item
87
+ for item in all_paths
88
+ if os.path.normcase(os.path.normpath(item)) in matching
89
+ ][:max_files]
90
+ else:
91
+ matching_paths = all_paths[:max_files]
92
+ except Exception:
93
+ matching_paths = all_paths[:max_files]
94
+
95
+ def text_from_content(content):
96
+ if isinstance(content, str):
97
+ return content
98
+ if not isinstance(content, list):
99
+ return ""
100
+ parts = []
101
+ for item in content:
102
+ if not isinstance(item, dict) or item.get("type") == "encrypted_content":
103
+ continue
104
+ text = item.get("text")
105
+ if isinstance(text, str):
106
+ parts.append(text)
107
+ return "\n".join(parts)
108
+
109
+ def is_context_message(value):
110
+ if not isinstance(value, str):
111
+ return True
112
+ return value.lstrip().startswith((
113
+ "<environment_context>",
114
+ "<permissions",
115
+ "<INSTRUCTIONS>",
116
+ "<collaboration_mode>",
117
+ "<apps_instructions>",
118
+ "<plugins_instructions>",
119
+ "<skills_instructions>",
120
+ "<recommended_plugins>",
121
+ "<in-app-browser-context",
122
+ "# AGENTS.md instructions",
123
+ "A previous agent produced",
124
+ "You are Codex",
125
+ ))
126
+
127
+ def clean(value, limit=1200):
128
+ if not isinstance(value, str):
129
+ value = json.dumps(value, ensure_ascii=False)
130
+ return " ".join(value.replace("\x00", "").split())[:limit]
131
+
132
+ def snippets_for(value, hits):
133
+ normalized = " ".join(value.replace("\x00", "").split())
134
+ lowered = normalized.lower()
135
+ positions = [lowered.find(term) for term in hits if lowered.find(term) >= 0]
136
+ start = max(0, (min(positions) if positions else 0) - 150)
137
+ return normalized[start:start + 700]
138
+
139
+ def event_texts(event):
140
+ payload = event.get("payload", {})
141
+ if not isinstance(payload, dict):
142
+ return []
143
+ timestamp = event.get("timestamp")
144
+ event_type = event.get("type")
145
+ output = []
146
+ if event_type == "event_msg":
147
+ kind = payload.get("type")
148
+ if kind in ("user_message", "user_input"):
149
+ text = payload.get("message") or payload.get("text") or payload.get("content")
150
+ if isinstance(text, str) and not is_context_message(text):
151
+ output.append(("user", text, timestamp, 8))
152
+ elif kind in ("agent_message", "task_complete", "turn_complete", "task_completed"):
153
+ text = payload.get("message") or payload.get("text") or payload.get("last_agent_message")
154
+ if isinstance(text, str):
155
+ output.append(("assistant", text, timestamp, 6))
156
+ return output
157
+ if event_type != "response_item":
158
+ return output
159
+ kind = payload.get("type")
160
+ role = payload.get("role")
161
+ if kind == "message" and role in ("user", "assistant"):
162
+ text = text_from_content(payload.get("content"))
163
+ if text and (role != "user" or not is_context_message(text)):
164
+ output.append((role, text, timestamp, 8 if role == "user" else 6))
165
+ elif kind in ("function_call", "custom_tool_call"):
166
+ arguments = payload.get("arguments") or payload.get("input") or ""
167
+ output.append(("command", clean(arguments, 20000), timestamp, 7))
168
+ elif kind in ("function_call_output", "custom_tool_call_output"):
169
+ value = payload.get("output") or ""
170
+ output.append(("output", clean(value, 20000), timestamp, 3))
171
+ return output
172
+
173
+ records = []
174
+ for filename in matching_paths:
175
+ try:
176
+ with open(filename, "r", encoding="utf-8", errors="replace") as handle:
177
+ first_raw = handle.readline()
178
+ first_obj = json.loads(first_raw)
179
+ meta = (
180
+ first_obj.get("payload", {})
181
+ if first_obj.get("type") == "session_meta"
182
+ else {}
183
+ )
184
+ if not isinstance(meta, dict):
185
+ meta = {}
186
+ source = meta.get("source")
187
+ subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
188
+ spawn = subagent.get("thread_spawn", {}) if isinstance(subagent, dict) else {}
189
+ record = {
190
+ "id": meta.get("id") or meta.get("session_id") or os.path.basename(filename),
191
+ "rootSessionId": meta.get("session_id") or meta.get("id") or "",
192
+ "parentThreadId": meta.get("parent_thread_id") or spawn.get("parent_thread_id") or "",
193
+ "agentPath": spawn.get("agent_path") or "",
194
+ "agentNickname": spawn.get("agent_nickname") or "",
195
+ "isSubagent": bool(spawn or meta.get("parent_thread_id")),
196
+ "cwd": meta.get("cwd") or "",
197
+ "startedAt": meta.get("timestamp") or first_obj.get("timestamp"),
198
+ "cliVersion": meta.get("cli_version") or "",
199
+ "path": filename,
200
+ "mtimeMs": int(os.path.getmtime(filename) * 1000),
201
+ "firstUser": "",
202
+ "lastUser": "",
203
+ "lastAssistant": "",
204
+ "lastAction": "",
205
+ "lastError": "",
206
+ "userMessages": [],
207
+ "assistantMessages": [],
208
+ "model": "",
209
+ "reasoningEffort": "",
210
+ "approvalPolicy": "",
211
+ "sandboxPolicy": "",
212
+ "collaborationMode": "",
213
+ "launches": [],
214
+ "account": None,
215
+ "tokenUsage": None,
216
+ "turnState": "idle",
217
+ "lastEventAt": first_obj.get("timestamp"),
218
+ }
219
+ matched = set()
220
+ evidence = []
221
+ term_weights = {}
222
+ best_event_hits = 0
223
+ best_event_weight = 0
224
+ proximity_bonus = 0
225
+ for raw in handle:
226
+ try:
227
+ event = json.loads(raw)
228
+ except Exception:
229
+ continue
230
+ for kind, text, timestamp, weight in event_texts(event):
231
+ lowered = text.lower()
232
+ hits = [term for term in terms if term and term in lowered]
233
+ if not hits:
234
+ continue
235
+ unique_hits = list(dict.fromkeys(hits))
236
+ matched.update(unique_hits)
237
+ for term in unique_hits:
238
+ term_weights[term] = max(
239
+ term_weights.get(term, 0),
240
+ weight * (0.6 if len(term) == 1 else 1),
241
+ )
242
+ best_event_hits = max(best_event_hits, len(unique_hits))
243
+ best_event_weight = max(
244
+ best_event_weight,
245
+ weight if len(unique_hits) == best_event_hits else 0,
246
+ )
247
+ positions = [lowered.find(term) for term in unique_hits]
248
+ if len(positions) >= 3:
249
+ span = max(positions) - min(positions)
250
+ proximity_bonus = max(
251
+ proximity_bonus,
252
+ 80 if span <= 500 else 45 if span <= 1600 else 20,
253
+ )
254
+ snippet = snippets_for(text, hits)
255
+ if snippet and all(item["text"] != snippet for item in evidence):
256
+ evidence.append({
257
+ "kind": kind,
258
+ "timestamp": timestamp,
259
+ "text": snippet,
260
+ "terms": list(dict.fromkeys(hits)),
261
+ "weight": weight,
262
+ })
263
+ if kind == "user":
264
+ record["firstUser"] = record["firstUser"] or clean(text)
265
+ record["lastUser"] = clean(text)
266
+ record["userMessages"].append(clean(text))
267
+ record["userMessages"] = record["userMessages"][-4:]
268
+ elif kind == "assistant":
269
+ record["lastAssistant"] = clean(text)
270
+ record["assistantMessages"].append(clean(text))
271
+ record["assistantMessages"] = record["assistantMessages"][-4:]
272
+ elif kind == "command":
273
+ record["lastAction"] = clean(text)
274
+ if not matched:
275
+ continue
276
+ coverage = len(matched) / max(1, len(terms))
277
+ phrase_bonus = 0
278
+ ascii_phrase = " ".join(ascii_terms)
279
+ combined_evidence = " ".join(item["text"].lower() for item in evidence)
280
+ if len(ascii_terms) >= 2 and ascii_phrase in combined_evidence:
281
+ phrase_bonus = 18
282
+ score = (
283
+ sum(term_weights.values()) * 4
284
+ + coverage * coverage * 55
285
+ + best_event_hits * best_event_hits * 6
286
+ + best_event_weight
287
+ + proximity_bonus
288
+ + phrase_bonus
289
+ )
290
+ evidence.sort(
291
+ key=lambda item: (len(item["terms"]), item["weight"]),
292
+ reverse=True,
293
+ )
294
+ records.append({
295
+ "rollout": record,
296
+ "score": round(score, 2),
297
+ "coverage": round(coverage, 3),
298
+ "bestEventHits": best_event_hits,
299
+ "matchedTerms": sorted(matched),
300
+ "evidence": [
301
+ {key: value for key, value in item.items() if key != "weight"}
302
+ for item in evidence[:6]
303
+ ],
304
+ })
305
+ except Exception:
306
+ continue
307
+
308
+ records.sort(
309
+ key=lambda item: (
310
+ item["coverage"],
311
+ item["bestEventHits"],
312
+ item["score"],
313
+ item["rollout"]["mtimeMs"],
314
+ ),
315
+ reverse=True,
316
+ )
317
+ print(json.dumps({
318
+ "terms": terms,
319
+ "filesScanned": len(matching_paths),
320
+ "totalFiles": len(all_paths),
321
+ "results": records[:result_limit],
322
+ }, ensure_ascii=False, separators=(",", ":")))
323
323
  `;