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,701 +1,701 @@
1
- /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const SUBMISSION_PROBE = String.raw`
3
- import ast
4
- import concurrent.futures
5
- import glob
6
- import json
7
- import os
8
- import re
9
- import shlex
10
- import subprocess
11
- import sys
12
- import time
13
-
14
- display_limit = max(20, min(500, int(sys.argv[1]) if len(sys.argv) > 1 else 200))
15
- window_days = max(0, min(3650, int(sys.argv[2]) if len(sys.argv) > 2 else 1))
16
- summary_mode = len(sys.argv) > 3 and sys.argv[3] == "summary"
17
- all_paths = glob.glob(os.path.expanduser("~/.codex/sessions/**/*.jsonl"), recursive=True)
18
- cutoff = time.time() - window_days * 86400 if window_days else 0
19
- paths = [
20
- item for item in all_paths
21
- if not cutoff or os.path.getmtime(item) >= cutoff
22
- ]
23
- paths.sort(key=lambda item: os.path.getmtime(item), reverse=True)
24
- submit_pattern = re.compile(
25
- r"SUBMITTED\s+job=(?P<name>[^\s]+)\s+job_id=(?P<job>[A-Za-z0-9._:-]+)"
26
- )
27
- submitted_arrow_pattern = re.compile(
28
- r"(?im)^\s*\[(?:submitted|submit)\]\s+(?P<name>.+?)\s+->\s+"
29
- r"(?P<job>dlc[A-Za-z0-9]+)\s*$"
30
- )
31
- submit_table_pattern = re.compile(
32
- r"(?im)^\|\s*JobId\s*\|\s*RequestId\s*\|\s*$\n"
33
- r"(?:^\+[-+]+\+\s*$\n)?^\|\s*(?P<job>dlc[A-Za-z0-9]+)\s*\|"
34
- )
35
- submitting_pattern = re.compile(r"SUBMITTING\s+job=(?P<name>[^\s]+)")
36
- named_job_pattern = re.compile(
37
- r"(?i)['\"]?(?:job[_\s-]*id|jobid|dlc\s+job)['\"]?\s*[:=]\s*['\"]?"
38
- r"(?P<job>dlc[A-Za-z0-9]+)"
39
- )
40
- programmatic_submit_patterns = (
41
- re.compile(
42
- r"(?is)[\[(]\s*(?:[A-Za-z0-9_]*dlc[A-Za-z0-9_]*|"
43
- r"['\"][^'\"]*(?:/|^)dlc['\"])\s*,\s*['\"]submit['\"]"
44
- ),
45
- re.compile(
46
- r"(?is)(?:subprocess\.(?:run|Popen|call|check_call|check_output)|"
47
- r"os\.system)\s*\(\s*[furb]*['\"](?:[^'\"]*/)?dlc\s+submit\b"
48
- ),
49
- )
50
- training_pattern = re.compile(
51
- r"(?i)(?:\bsbatch\b|\bsrun\b|"
52
- r"\btorchrun\b|(?:python\S*\s+|bash\s+)\S*(?:train|launch|submit)\S*)"
53
- )
54
- context_prefixes = (
55
- "<environment_context>",
56
- "<permissions",
57
- "<collaboration_mode>",
58
- "<apps_instructions>",
59
- "<plugins_instructions>",
60
- "<skills_instructions>",
61
- "<recommended_plugins>",
62
- "<in-app-browser-context",
63
- "# AGENTS.md instructions",
64
- )
65
- submissions = {}
66
- launches = []
67
- calls = []
68
- calls_by_rpc = {}
69
- synthetic_job_ids = set()
70
-
71
- def readable(value):
72
- if isinstance(value, str):
73
- return value
74
- if isinstance(value, list):
75
- parts = []
76
- for item in value:
77
- if isinstance(item, str):
78
- parts.append(item)
79
- elif isinstance(item, dict):
80
- for key in ("text", "content", "output"):
81
- if isinstance(item.get(key), str):
82
- parts.append(item[key])
83
- break
84
- return "\n".join(parts)
85
- if isinstance(value, dict):
86
- return json.dumps(value, ensure_ascii=False)
87
- return str(value or "")
88
-
89
- def parse_tool_value(value):
90
- current = value
91
- for _ in range(2):
92
- if not isinstance(current, str):
93
- break
94
- try:
95
- current = json.loads(current)
96
- except Exception:
97
- break
98
- return current
99
-
100
- def walk_commands(value, results, inherited_cwd=""):
101
- value = parse_tool_value(value)
102
- if isinstance(value, dict):
103
- cwd = value.get("workdir") if isinstance(value.get("workdir"), str) else inherited_cwd
104
- for key in ("cmd", "command"):
105
- if isinstance(value.get(key), str):
106
- results.append((value[key], cwd))
107
- for key, nested in value.items():
108
- if key not in ("cmd", "command", "workdir"):
109
- walk_commands(nested, results, cwd)
110
- elif isinstance(value, list):
111
- for nested in value:
112
- walk_commands(nested, results, inherited_cwd)
113
-
114
- def quoted_js_value(raw, start):
115
- backtick = chr(96)
116
- if start >= len(raw) or raw[start] not in "\"'" + backtick:
117
- return None, start
118
- quote = raw[start]
119
- if quote == '"':
120
- try:
121
- value, consumed = json.JSONDecoder().raw_decode(raw[start:])
122
- return value, start + consumed
123
- except Exception:
124
- return None, start
125
- index = start + 1
126
- escaped = False
127
- while index < len(raw):
128
- char = raw[index]
129
- if escaped:
130
- escaped = False
131
- elif char == "\\":
132
- escaped = True
133
- elif char == quote:
134
- literal = raw[start:index + 1]
135
- if quote == "'":
136
- try:
137
- return ast.literal_eval(literal), index + 1
138
- except Exception:
139
- return None, index + 1
140
- body = literal[1:-1]
141
- body = body.replace("\\" + backtick, backtick).replace("\\\\", "\\")
142
- return body, index + 1
143
- index += 1
144
- return None, start
145
-
146
- def tool_commands(payload):
147
- raw_value = payload.get("input")
148
- if raw_value is None:
149
- raw_value = payload.get("arguments")
150
- results = []
151
- walk_commands(raw_value, results)
152
- name = str(payload.get("name") or "")
153
- raw = readable(raw_value)
154
- if name in ("exec", "shell", "bash", "terminal") and not results:
155
- for match in re.finditer(r"(?:\"cmd\"|(?<![\w])cmd)\s*:\s*", raw):
156
- value, _ = quoted_js_value(raw, match.end())
157
- if isinstance(value, str):
158
- results.append((value, ""))
159
- if name in ("shell", "bash", "terminal") and not results and isinstance(raw_value, str):
160
- results.append((raw_value, ""))
161
- unique = []
162
- seen = set()
163
- for command, workdir in results:
164
- key = (command, workdir)
165
- if command and key not in seen:
166
- seen.add(key)
167
- unique.append(key)
168
- return unique
169
-
170
- def shell_tokens(command):
171
- try:
172
- lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|")
173
- lexer.whitespace_split = True
174
- lexer.commenters = ""
175
- return list(lexer)
176
- except Exception:
177
- return command.split()
178
-
179
- def command_name(token):
180
- token = str(token or "").strip()
181
- if "$(" in token:
182
- token = token.rsplit("$(", 1)[-1]
183
- token = token.strip("(){}[]'\"")
184
- token = token.rstrip(";,")
185
- return os.path.basename(token)
186
-
187
- def shell_submit_counts(command, depth=0):
188
- if depth > 2:
189
- return 0, 0
190
- tokens = shell_tokens(command)
191
- direct = 0
192
- scripts = 0
193
- for index, token in enumerate(tokens):
194
- name = command_name(token)
195
- next_name = command_name(tokens[index + 1]) if index + 1 < len(tokens) else ""
196
- if name == "dlc" and next_name == "submit":
197
- direct += 1
198
- if name in ("bash", "sh", "zsh") or re.fullmatch(r"python(?:\d+(?:\.\d+)*)?", name):
199
- cursor = index + 1
200
- nested_shell = False
201
- no_execute = False
202
- while cursor < len(tokens) and str(tokens[cursor]).startswith("-"):
203
- option = str(tokens[cursor])
204
- cursor += 1
205
- if name in ("bash", "sh", "zsh") and (
206
- option == "--noexec"
207
- or (
208
- option.startswith("-")
209
- and not option.startswith("--")
210
- and "n" in option[1:]
211
- )
212
- ):
213
- no_execute = True
214
- if "c" in option and cursor < len(tokens):
215
- if not no_execute:
216
- nested_direct, nested_scripts = shell_submit_counts(
217
- str(tokens[cursor]), depth + 1
218
- )
219
- direct += nested_direct
220
- scripts += nested_scripts
221
- nested_shell = True
222
- break
223
- if nested_shell or no_execute:
224
- continue
225
- if cursor < len(tokens):
226
- candidate = command_name(tokens[cursor]).lower()
227
- if (
228
- ("submit" in candidate or "submission" in candidate)
229
- and candidate.endswith((".sh", ".py"))
230
- ):
231
- scripts += 1
232
- return direct, scripts
233
-
234
- def classify_dlc_command(command):
235
- direct_count, script_count = shell_submit_counts(command)
236
- programmatic_count = sum(
237
- len(list(pattern.finditer(command)))
238
- for pattern in programmatic_submit_patterns
239
- )
240
- if direct_count:
241
- kind = "direct-shell"
242
- count = direct_count
243
- elif programmatic_count:
244
- kind = "programmatic"
245
- count = programmatic_count
246
- elif script_count:
247
- kind = "submit-script"
248
- count = script_count
249
- else:
250
- return None
251
- inspection = bool(
252
- (
253
- direct_count
254
- and re.search(r"(?i)\bdlc\s+submit\b[^\n;&|]*--help\b", command)
255
- )
256
- or (
257
- script_count
258
- and re.search(
259
- r"(?i)\b[^\s;&|]*(?:submit|submission)[^\s;&|]*\.(?:sh|py)\b"
260
- r"[^\n;&|]*--help\b",
261
- command,
262
- )
263
- )
264
- )
265
- dry_run = bool(re.search(
266
- r"(?i)(?:--dry-run\b|--mode[=\s]+(?:plan|dry-run)\b|"
267
- r"\bDRY_RUN=1\b|\bSUBMIT=0\b|"
268
- r"\bDLC=[^\s;&|]*(?:fake|mock|capture|stub)[^\s;&|]*)",
269
- command,
270
- ))
271
- explicit_submit = bool(
272
- kind != "submit-script"
273
- or re.search(
274
- r"(?i)(?:--submit\b|--mode[=\s]+submit\b|"
275
- r"\bSUBMIT=1\b|\bDRY_RUN=0\b)",
276
- command,
277
- )
278
- )
279
- return kind, max(1, count), inspection, dry_run, explicit_submit
280
-
281
- def exit_code_from(output):
282
- patterns = (
283
- r"(?i)process exited with code\s+(-?\d+)",
284
- r"(?i)exit[_ ]code[\"']?\s*[:=]\s*(-?\d+)",
285
- r"(?i)script failed with code\s+(-?\d+)",
286
- )
287
- for pattern in patterns:
288
- match = re.search(pattern, output)
289
- if match:
290
- return int(match.group(1))
291
- if "Script completed" in output or "Process exited with code 0" in output:
292
- return 0
293
- return None
294
-
295
- def plausible_job_id(value):
296
- return bool(
297
- re.fullmatch(r"(?i)dlc[A-Za-z0-9]{8,}", str(value or ""))
298
- and not re.search(r"(?i)(?:fake|mock|stub|capture)", str(value))
299
- )
300
-
301
- for filename in paths:
302
- try:
303
- with open(filename, "r", encoding="utf-8", errors="replace") as handle:
304
- first = json.loads(handle.readline())
305
- meta = (
306
- first.get("payload", {})
307
- if first.get("type") == "session_meta"
308
- else {}
309
- )
310
- source = meta.get("source")
311
- subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
312
- session_id = meta.get("id") or meta.get("session_id") or ""
313
- cwd = meta.get("cwd") or ""
314
- parent_thread_id = meta.get("parent_thread_id") or ""
315
- is_subagent = bool(subagent or parent_thread_id)
316
- first_user = ""
317
- for line_number, raw in enumerate(handle, 2):
318
- try:
319
- event = json.loads(raw)
320
- except Exception:
321
- continue
322
- payload = event.get("payload", {})
323
- if not isinstance(payload, dict):
324
- continue
325
- event_type = event.get("type")
326
- kind = payload.get("type")
327
- timestamp = event.get("timestamp")
328
- if not first_user and event_type == "response_item":
329
- if kind == "message" and payload.get("role") == "user":
330
- candidate = readable(payload.get("content")).strip()
331
- if candidate and not candidate.startswith(context_prefixes):
332
- first_user = " ".join(candidate.split())[:240]
333
- if event_type != "response_item":
334
- continue
335
- if kind in ("function_call_output", "custom_tool_call_output"):
336
- output = readable(payload.get("output"))
337
- rpc_id = payload.get("call_id") or payload.get("id") or ""
338
- matching_calls = calls_by_rpc.get((filename, rpc_id), [])
339
- submitted_matches = list(submit_pattern.finditer(output))
340
- arrow_matches = list(submitted_arrow_pattern.finditer(output))
341
- table_matches = list(submit_table_pattern.finditer(output))
342
- strong_submission_pairs = [
343
- (match.group("name"), match.group("job"), match.group(0))
344
- for match in submitted_matches
345
- ] + [
346
- (match.group("name").strip(), match.group("job"), match.group(0))
347
- for match in arrow_matches
348
- ] + [
349
- (match.group("job"), match.group("job"), match.group(0))
350
- for match in table_matches
351
- ]
352
- unique_submission_pairs = {}
353
- for pair in strong_submission_pairs:
354
- if plausible_job_id(pair[1]):
355
- unique_submission_pairs.setdefault(pair[1], pair)
356
- strong_submission_pairs = list(unique_submission_pairs.values())
357
- submitting_names = [
358
- match.group("name")
359
- for match in submitting_pattern.finditer(output)
360
- ]
361
- explicit_job_ids = list(dict.fromkeys(
362
- pair[1] for pair in strong_submission_pairs
363
- ))
364
- named_id_calls = [
365
- call for call in matching_calls
366
- if call["invocationKind"] in ("direct-shell", "programmatic")
367
- and call["syntacticInvocations"] == 1
368
- and not re.search(
369
- r"(?i)\bdlc\s+(?:get|list|stop)\b",
370
- call["command"],
371
- )
372
- ]
373
- if named_id_calls and not explicit_job_ids:
374
- explicit_job_ids = list(dict.fromkeys(
375
- match.group("job")
376
- for match in named_job_pattern.finditer(output)
377
- ))
378
- submission_pairs = list(strong_submission_pairs)
379
- if not submission_pairs:
380
- for index, job_id in enumerate(explicit_job_ids):
381
- name = (
382
- submitting_names[index]
383
- if index < len(submitting_names)
384
- else job_id
385
- )
386
- submission_pairs.append((name, job_id, job_id))
387
- exit_code = exit_code_from(output)
388
- for call in matching_calls:
389
- call["resultLine"] = line_number
390
- call["exitCode"] = exit_code
391
- call["jobNames"] = list(dict.fromkeys(
392
- call["jobNames"]
393
- + submitting_names
394
- + [pair[0] for pair in strong_submission_pairs]
395
- ))
396
- call["jobIds"] = list(dict.fromkeys(
397
- call["jobIds"] + explicit_job_ids
398
- ))
399
- call["observedInvocations"] = max(
400
- call["syntacticInvocations"],
401
- len(submitting_names),
402
- len(strong_submission_pairs),
403
- len(explicit_job_ids),
404
- )
405
- if call["inspection"]:
406
- call["outcome"] = "inspection"
407
- elif call["dryRun"]:
408
- call["outcome"] = "dry-run"
409
- elif call["jobIds"]:
410
- call["outcome"] = "submitted"
411
- elif exit_code not in (None, 0):
412
- call["outcome"] = "failed"
413
- elif submitting_names:
414
- call["outcome"] = "unresolved"
415
- else:
416
- call["outcome"] = "unknown"
417
- call["resultEvidence"] = " ".join(output.split())[:1200]
418
- ownership_pairs = (
419
- submission_pairs
420
- if not matching_calls
421
- or any(
422
- not call["inspection"] and not call["dryRun"]
423
- for call in matching_calls
424
- )
425
- else []
426
- )
427
- if ownership_pairs and not matching_calls:
428
- synthetic_ids = [
429
- job_id for _, job_id, _ in ownership_pairs
430
- if job_id not in synthetic_job_ids
431
- ]
432
- synthetic_job_ids.update(synthetic_ids)
433
- else:
434
- synthetic_ids = []
435
- if synthetic_ids:
436
- synthetic = {
437
- "id": f"{session_id}:{rpc_id or 'output'}:output-{line_number}",
438
- "timestamp": timestamp,
439
- "sessionId": session_id,
440
- "cwd": cwd,
441
- "rolloutPath": filename,
442
- "line": line_number,
443
- "sessionObjective": first_user,
444
- "toolName": "output-only",
445
- "callId": rpc_id,
446
- "invocationKind": "output-only",
447
- "syntacticInvocations": 0,
448
- "observedInvocations": len(synthetic_ids),
449
- "inspection": False,
450
- "dryRun": False,
451
- "explicitSubmit": True,
452
- "outcome": "submitted",
453
- "exitCode": exit_code,
454
- "jobIds": synthetic_ids,
455
- "jobNames": list(dict.fromkeys(
456
- submitting_names
457
- + [pair[0] for pair in strong_submission_pairs]
458
- )),
459
- "resultLine": line_number,
460
- "resultEvidence": " ".join(output.split())[:1200],
461
- "command": "",
462
- "isSubagent": is_subagent,
463
- "parentThreadId": parent_thread_id,
464
- }
465
- calls.append(synthetic)
466
- for job_name, job_id, job_evidence in ownership_pairs:
467
- candidate = {
468
- "jobId": job_id,
469
- "name": job_name,
470
- "submittedAt": timestamp,
471
- "sessionId": session_id,
472
- "cwd": cwd,
473
- "rolloutPath": filename,
474
- "line": line_number,
475
- "sessionObjective": first_user,
476
- "evidence": " ".join(job_evidence.split())[:500],
477
- "callId": rpc_id,
478
- "command": matching_calls[0]["command"] if matching_calls else "",
479
- "commandLine": matching_calls[0]["line"] if matching_calls else None,
480
- "exitCode": exit_code,
481
- "invocationKind": (
482
- matching_calls[0]["invocationKind"]
483
- if matching_calls else "output-only"
484
- ),
485
- "isSubagent": is_subagent,
486
- "parentThreadId": parent_thread_id,
487
- "ownershipSource": (
488
- "tool-call" if matching_calls else "output-only"
489
- ),
490
- "ownershipRank": 3 if matching_calls else 2,
491
- }
492
- existing = submissions.get(job_id)
493
- replace = not existing
494
- if existing:
495
- candidate_rank = candidate["ownershipRank"]
496
- existing_rank = existing.get("ownershipRank", 0)
497
- if candidate_rank > existing_rank:
498
- replace = True
499
- elif candidate_rank == existing_rank:
500
- candidate_time = candidate.get("submittedAt") or ""
501
- existing_time = existing.get("submittedAt") or ""
502
- replace = bool(
503
- candidate_time
504
- and (not existing_time or candidate_time < existing_time)
505
- )
506
- if replace:
507
- submissions[job_id] = candidate
508
- elif kind in ("function_call", "custom_tool_call"):
509
- rpc_id = (
510
- payload.get("call_id")
511
- or payload.get("id")
512
- or f"line-{line_number}"
513
- )
514
- for command_index, (command, command_cwd) in enumerate(
515
- tool_commands(payload)
516
- ):
517
- classification = classify_dlc_command(command)
518
- if classification:
519
- (
520
- invocation_kind,
521
- syntactic_count,
522
- inspection,
523
- dry_run,
524
- explicit_submit,
525
- ) = classification
526
- record = {
527
- "id": f"{session_id}:{rpc_id}:{command_index}",
528
- "timestamp": timestamp,
529
- "sessionId": session_id,
530
- "cwd": command_cwd or cwd,
531
- "rolloutPath": filename,
532
- "line": line_number,
533
- "sessionObjective": first_user,
534
- "toolName": payload.get("name") or "",
535
- "callId": rpc_id,
536
- "invocationKind": invocation_kind,
537
- "syntacticInvocations": syntactic_count,
538
- "observedInvocations": syntactic_count,
539
- "inspection": inspection,
540
- "dryRun": dry_run,
541
- "explicitSubmit": explicit_submit,
542
- "outcome": (
543
- "inspection" if inspection
544
- else "dry-run" if dry_run
545
- else "pending"
546
- ),
547
- "exitCode": None,
548
- "jobIds": [],
549
- "jobNames": [],
550
- "resultLine": None,
551
- "resultEvidence": "",
552
- "command": " ".join(command.split())[:4000],
553
- "isSubagent": is_subagent,
554
- "parentThreadId": parent_thread_id,
555
- }
556
- calls.append(record)
557
- calls_by_rpc.setdefault((filename, rpc_id), []).append(record)
558
- raw_input = readable(
559
- payload.get("input") or payload.get("arguments")
560
- )
561
- if training_pattern.search(raw_input):
562
- launches.append({
563
- "kind": (
564
- "dlc"
565
- if re.search(r"(?i)\bdlc\b", raw_input)
566
- else "scheduler"
567
- if re.search(r"(?i)\b(?:sbatch|srun)\b", raw_input)
568
- else "training"
569
- ),
570
- "timestamp": timestamp,
571
- "sessionId": session_id,
572
- "cwd": cwd,
573
- "rolloutPath": filename,
574
- "line": line_number,
575
- "sessionObjective": first_user,
576
- "command": " ".join(raw_input.split())[:1200],
577
- "isSubagent": is_subagent,
578
- "parentThreadId": parent_thread_id,
579
- })
580
- except Exception:
581
- continue
582
-
583
- dlc = "/etc/dsw/runtime/export_bin/dlc"
584
- def status_for(item):
585
- job_id, record = item
586
- status = {
587
- "status": "Unknown",
588
- "reason": "",
589
- "message": "",
590
- "duration": None,
591
- }
592
- if not os.path.isfile(dlc) or not re.fullmatch(r"dlc[A-Za-z0-9]+", job_id):
593
- return job_id, status
594
- try:
595
- completed = subprocess.run(
596
- [dlc, "get", "job", job_id],
597
- stdout=subprocess.PIPE,
598
- stderr=subprocess.PIPE,
599
- text=True,
600
- timeout=18,
601
- )
602
- if completed.returncode == 0:
603
- payload = json.loads(completed.stdout)
604
- status = {
605
- "status": payload.get("Status") or "Unknown",
606
- "reason": payload.get("ReasonCode") or "",
607
- "message": payload.get("ReasonMessage") or "",
608
- "duration": payload.get("Duration"),
609
- }
610
- else:
611
- status["message"] = (completed.stderr or completed.stdout).strip()[:500]
612
- except Exception as error:
613
- status["message"] = str(error)[:500]
614
- return job_id, status
615
-
616
- direct_job_ids = {
617
- job_id
618
- for call in calls
619
- if call["invocationKind"] != "output-only"
620
- for job_id in call["jobIds"]
621
- }
622
- calls = [
623
- call for call in calls
624
- if call["invocationKind"] != "output-only"
625
- or any(job_id not in direct_job_ids for job_id in call["jobIds"])
626
- ]
627
- for record in submissions.values():
628
- record.pop("ownershipRank", None)
629
-
630
- ordered = sorted(
631
- submissions.values(),
632
- key=lambda item: item.get("submittedAt") or "",
633
- reverse=True,
634
- )
635
- for record in ordered:
636
- record.update({
637
- "status": "Unknown",
638
- "reason": "",
639
- "message": "",
640
- "duration": None,
641
- })
642
- status_items = [
643
- (record["jobId"], record)
644
- for record in ordered[:min(display_limit, 120)]
645
- ]
646
- if status_items:
647
- with concurrent.futures.ThreadPoolExecutor(max_workers=min(8, len(status_items))) as pool:
648
- for job_id, status in pool.map(status_for, status_items):
649
- submissions[job_id].update(status)
650
-
651
- ordered = sorted(
652
- submissions.values(),
653
- key=lambda item: item.get("submittedAt") or "",
654
- reverse=True,
655
- )[:500]
656
- calls.sort(key=lambda item: item.get("timestamp") or "", reverse=True)
657
- launches.sort(key=lambda item: item.get("timestamp") or "", reverse=True)
658
- result = {
659
- "filesScanned": len(paths),
660
- "totalFiles": len(all_paths),
661
- "scanScope": "all-rollouts" if not window_days else f"recent-{window_days}d",
662
- "windowDays": window_days,
663
- "calls": calls,
664
- "totalCalls": len(calls),
665
- "submissions": ordered,
666
- "totalSubmissions": len(submissions),
667
- "launches": launches[:display_limit],
668
- }
669
- if summary_mode:
670
- result = {
671
- "filesScanned": result["filesScanned"],
672
- "totalCalls": result["totalCalls"],
673
- "totalSubmissions": result["totalSubmissions"],
674
- "byKind": {
675
- kind: sum(1 for call in calls if call["invocationKind"] == kind)
676
- for kind in (
677
- "direct-shell", "programmatic", "submit-script", "output-only"
678
- )
679
- },
680
- "byOutcome": {
681
- outcome: sum(1 for call in calls if call["outcome"] == outcome)
682
- for outcome in (
683
- "submitted", "failed", "unresolved", "unknown",
684
- "inspection", "dry-run"
685
- )
686
- },
687
- "subagentCalls": sum(1 for call in calls if call["isSubagent"]),
688
- "latest": [
689
- {
690
- "timestamp": call["timestamp"],
691
- "invocationKind": call["invocationKind"],
692
- "outcome": call["outcome"],
693
- "jobs": len(call["jobIds"]),
694
- "isSubagent": call["isSubagent"],
695
- "command": call["command"][:180],
696
- }
697
- for call in calls[:12]
698
- ],
699
- }
700
- print(json.dumps(result, ensure_ascii=False, separators=(",", ":")))
701
- `;
1
+ /** Remote probe, kept independent of HTTP and local mutable state. */
2
+ export const SUBMISSION_PROBE = String.raw`
3
+ import ast
4
+ import concurrent.futures
5
+ import glob
6
+ import json
7
+ import os
8
+ import re
9
+ import shlex
10
+ import subprocess
11
+ import sys
12
+ import time
13
+
14
+ display_limit = max(20, min(500, int(sys.argv[1]) if len(sys.argv) > 1 else 200))
15
+ window_days = max(0, min(3650, int(sys.argv[2]) if len(sys.argv) > 2 else 1))
16
+ summary_mode = len(sys.argv) > 3 and sys.argv[3] == "summary"
17
+ all_paths = glob.glob(os.path.expanduser("~/.codex/sessions/**/*.jsonl"), recursive=True)
18
+ cutoff = time.time() - window_days * 86400 if window_days else 0
19
+ paths = [
20
+ item for item in all_paths
21
+ if not cutoff or os.path.getmtime(item) >= cutoff
22
+ ]
23
+ paths.sort(key=lambda item: os.path.getmtime(item), reverse=True)
24
+ submit_pattern = re.compile(
25
+ r"SUBMITTED\s+job=(?P<name>[^\s]+)\s+job_id=(?P<job>[A-Za-z0-9._:-]+)"
26
+ )
27
+ submitted_arrow_pattern = re.compile(
28
+ r"(?im)^\s*\[(?:submitted|submit)\]\s+(?P<name>.+?)\s+->\s+"
29
+ r"(?P<job>dlc[A-Za-z0-9]+)\s*$"
30
+ )
31
+ submit_table_pattern = re.compile(
32
+ r"(?im)^\|\s*JobId\s*\|\s*RequestId\s*\|\s*$\n"
33
+ r"(?:^\+[-+]+\+\s*$\n)?^\|\s*(?P<job>dlc[A-Za-z0-9]+)\s*\|"
34
+ )
35
+ submitting_pattern = re.compile(r"SUBMITTING\s+job=(?P<name>[^\s]+)")
36
+ named_job_pattern = re.compile(
37
+ r"(?i)['\"]?(?:job[_\s-]*id|jobid|dlc\s+job)['\"]?\s*[:=]\s*['\"]?"
38
+ r"(?P<job>dlc[A-Za-z0-9]+)"
39
+ )
40
+ programmatic_submit_patterns = (
41
+ re.compile(
42
+ r"(?is)[\[(]\s*(?:[A-Za-z0-9_]*dlc[A-Za-z0-9_]*|"
43
+ r"['\"][^'\"]*(?:/|^)dlc['\"])\s*,\s*['\"]submit['\"]"
44
+ ),
45
+ re.compile(
46
+ r"(?is)(?:subprocess\.(?:run|Popen|call|check_call|check_output)|"
47
+ r"os\.system)\s*\(\s*[furb]*['\"](?:[^'\"]*/)?dlc\s+submit\b"
48
+ ),
49
+ )
50
+ training_pattern = re.compile(
51
+ r"(?i)(?:\bsbatch\b|\bsrun\b|"
52
+ r"\btorchrun\b|(?:python\S*\s+|bash\s+)\S*(?:train|launch|submit)\S*)"
53
+ )
54
+ context_prefixes = (
55
+ "<environment_context>",
56
+ "<permissions",
57
+ "<collaboration_mode>",
58
+ "<apps_instructions>",
59
+ "<plugins_instructions>",
60
+ "<skills_instructions>",
61
+ "<recommended_plugins>",
62
+ "<in-app-browser-context",
63
+ "# AGENTS.md instructions",
64
+ )
65
+ submissions = {}
66
+ launches = []
67
+ calls = []
68
+ calls_by_rpc = {}
69
+ synthetic_job_ids = set()
70
+
71
+ def readable(value):
72
+ if isinstance(value, str):
73
+ return value
74
+ if isinstance(value, list):
75
+ parts = []
76
+ for item in value:
77
+ if isinstance(item, str):
78
+ parts.append(item)
79
+ elif isinstance(item, dict):
80
+ for key in ("text", "content", "output"):
81
+ if isinstance(item.get(key), str):
82
+ parts.append(item[key])
83
+ break
84
+ return "\n".join(parts)
85
+ if isinstance(value, dict):
86
+ return json.dumps(value, ensure_ascii=False)
87
+ return str(value or "")
88
+
89
+ def parse_tool_value(value):
90
+ current = value
91
+ for _ in range(2):
92
+ if not isinstance(current, str):
93
+ break
94
+ try:
95
+ current = json.loads(current)
96
+ except Exception:
97
+ break
98
+ return current
99
+
100
+ def walk_commands(value, results, inherited_cwd=""):
101
+ value = parse_tool_value(value)
102
+ if isinstance(value, dict):
103
+ cwd = value.get("workdir") if isinstance(value.get("workdir"), str) else inherited_cwd
104
+ for key in ("cmd", "command"):
105
+ if isinstance(value.get(key), str):
106
+ results.append((value[key], cwd))
107
+ for key, nested in value.items():
108
+ if key not in ("cmd", "command", "workdir"):
109
+ walk_commands(nested, results, cwd)
110
+ elif isinstance(value, list):
111
+ for nested in value:
112
+ walk_commands(nested, results, inherited_cwd)
113
+
114
+ def quoted_js_value(raw, start):
115
+ backtick = chr(96)
116
+ if start >= len(raw) or raw[start] not in "\"'" + backtick:
117
+ return None, start
118
+ quote = raw[start]
119
+ if quote == '"':
120
+ try:
121
+ value, consumed = json.JSONDecoder().raw_decode(raw[start:])
122
+ return value, start + consumed
123
+ except Exception:
124
+ return None, start
125
+ index = start + 1
126
+ escaped = False
127
+ while index < len(raw):
128
+ char = raw[index]
129
+ if escaped:
130
+ escaped = False
131
+ elif char == "\\":
132
+ escaped = True
133
+ elif char == quote:
134
+ literal = raw[start:index + 1]
135
+ if quote == "'":
136
+ try:
137
+ return ast.literal_eval(literal), index + 1
138
+ except Exception:
139
+ return None, index + 1
140
+ body = literal[1:-1]
141
+ body = body.replace("\\" + backtick, backtick).replace("\\\\", "\\")
142
+ return body, index + 1
143
+ index += 1
144
+ return None, start
145
+
146
+ def tool_commands(payload):
147
+ raw_value = payload.get("input")
148
+ if raw_value is None:
149
+ raw_value = payload.get("arguments")
150
+ results = []
151
+ walk_commands(raw_value, results)
152
+ name = str(payload.get("name") or "")
153
+ raw = readable(raw_value)
154
+ if name in ("exec", "shell", "bash", "terminal") and not results:
155
+ for match in re.finditer(r"(?:\"cmd\"|(?<![\w])cmd)\s*:\s*", raw):
156
+ value, _ = quoted_js_value(raw, match.end())
157
+ if isinstance(value, str):
158
+ results.append((value, ""))
159
+ if name in ("shell", "bash", "terminal") and not results and isinstance(raw_value, str):
160
+ results.append((raw_value, ""))
161
+ unique = []
162
+ seen = set()
163
+ for command, workdir in results:
164
+ key = (command, workdir)
165
+ if command and key not in seen:
166
+ seen.add(key)
167
+ unique.append(key)
168
+ return unique
169
+
170
+ def shell_tokens(command):
171
+ try:
172
+ lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|")
173
+ lexer.whitespace_split = True
174
+ lexer.commenters = ""
175
+ return list(lexer)
176
+ except Exception:
177
+ return command.split()
178
+
179
+ def command_name(token):
180
+ token = str(token or "").strip()
181
+ if "$(" in token:
182
+ token = token.rsplit("$(", 1)[-1]
183
+ token = token.strip("(){}[]'\"")
184
+ token = token.rstrip(";,")
185
+ return os.path.basename(token)
186
+
187
+ def shell_submit_counts(command, depth=0):
188
+ if depth > 2:
189
+ return 0, 0
190
+ tokens = shell_tokens(command)
191
+ direct = 0
192
+ scripts = 0
193
+ for index, token in enumerate(tokens):
194
+ name = command_name(token)
195
+ next_name = command_name(tokens[index + 1]) if index + 1 < len(tokens) else ""
196
+ if name == "dlc" and next_name == "submit":
197
+ direct += 1
198
+ if name in ("bash", "sh", "zsh") or re.fullmatch(r"python(?:\d+(?:\.\d+)*)?", name):
199
+ cursor = index + 1
200
+ nested_shell = False
201
+ no_execute = False
202
+ while cursor < len(tokens) and str(tokens[cursor]).startswith("-"):
203
+ option = str(tokens[cursor])
204
+ cursor += 1
205
+ if name in ("bash", "sh", "zsh") and (
206
+ option == "--noexec"
207
+ or (
208
+ option.startswith("-")
209
+ and not option.startswith("--")
210
+ and "n" in option[1:]
211
+ )
212
+ ):
213
+ no_execute = True
214
+ if "c" in option and cursor < len(tokens):
215
+ if not no_execute:
216
+ nested_direct, nested_scripts = shell_submit_counts(
217
+ str(tokens[cursor]), depth + 1
218
+ )
219
+ direct += nested_direct
220
+ scripts += nested_scripts
221
+ nested_shell = True
222
+ break
223
+ if nested_shell or no_execute:
224
+ continue
225
+ if cursor < len(tokens):
226
+ candidate = command_name(tokens[cursor]).lower()
227
+ if (
228
+ ("submit" in candidate or "submission" in candidate)
229
+ and candidate.endswith((".sh", ".py"))
230
+ ):
231
+ scripts += 1
232
+ return direct, scripts
233
+
234
+ def classify_dlc_command(command):
235
+ direct_count, script_count = shell_submit_counts(command)
236
+ programmatic_count = sum(
237
+ len(list(pattern.finditer(command)))
238
+ for pattern in programmatic_submit_patterns
239
+ )
240
+ if direct_count:
241
+ kind = "direct-shell"
242
+ count = direct_count
243
+ elif programmatic_count:
244
+ kind = "programmatic"
245
+ count = programmatic_count
246
+ elif script_count:
247
+ kind = "submit-script"
248
+ count = script_count
249
+ else:
250
+ return None
251
+ inspection = bool(
252
+ (
253
+ direct_count
254
+ and re.search(r"(?i)\bdlc\s+submit\b[^\n;&|]*--help\b", command)
255
+ )
256
+ or (
257
+ script_count
258
+ and re.search(
259
+ r"(?i)\b[^\s;&|]*(?:submit|submission)[^\s;&|]*\.(?:sh|py)\b"
260
+ r"[^\n;&|]*--help\b",
261
+ command,
262
+ )
263
+ )
264
+ )
265
+ dry_run = bool(re.search(
266
+ r"(?i)(?:--dry-run\b|--mode[=\s]+(?:plan|dry-run)\b|"
267
+ r"\bDRY_RUN=1\b|\bSUBMIT=0\b|"
268
+ r"\bDLC=[^\s;&|]*(?:fake|mock|capture|stub)[^\s;&|]*)",
269
+ command,
270
+ ))
271
+ explicit_submit = bool(
272
+ kind != "submit-script"
273
+ or re.search(
274
+ r"(?i)(?:--submit\b|--mode[=\s]+submit\b|"
275
+ r"\bSUBMIT=1\b|\bDRY_RUN=0\b)",
276
+ command,
277
+ )
278
+ )
279
+ return kind, max(1, count), inspection, dry_run, explicit_submit
280
+
281
+ def exit_code_from(output):
282
+ patterns = (
283
+ r"(?i)process exited with code\s+(-?\d+)",
284
+ r"(?i)exit[_ ]code[\"']?\s*[:=]\s*(-?\d+)",
285
+ r"(?i)script failed with code\s+(-?\d+)",
286
+ )
287
+ for pattern in patterns:
288
+ match = re.search(pattern, output)
289
+ if match:
290
+ return int(match.group(1))
291
+ if "Script completed" in output or "Process exited with code 0" in output:
292
+ return 0
293
+ return None
294
+
295
+ def plausible_job_id(value):
296
+ return bool(
297
+ re.fullmatch(r"(?i)dlc[A-Za-z0-9]{8,}", str(value or ""))
298
+ and not re.search(r"(?i)(?:fake|mock|stub|capture)", str(value))
299
+ )
300
+
301
+ for filename in paths:
302
+ try:
303
+ with open(filename, "r", encoding="utf-8", errors="replace") as handle:
304
+ first = json.loads(handle.readline())
305
+ meta = (
306
+ first.get("payload", {})
307
+ if first.get("type") == "session_meta"
308
+ else {}
309
+ )
310
+ source = meta.get("source")
311
+ subagent = source.get("subagent", {}) if isinstance(source, dict) else {}
312
+ session_id = meta.get("id") or meta.get("session_id") or ""
313
+ cwd = meta.get("cwd") or ""
314
+ parent_thread_id = meta.get("parent_thread_id") or ""
315
+ is_subagent = bool(subagent or parent_thread_id)
316
+ first_user = ""
317
+ for line_number, raw in enumerate(handle, 2):
318
+ try:
319
+ event = json.loads(raw)
320
+ except Exception:
321
+ continue
322
+ payload = event.get("payload", {})
323
+ if not isinstance(payload, dict):
324
+ continue
325
+ event_type = event.get("type")
326
+ kind = payload.get("type")
327
+ timestamp = event.get("timestamp")
328
+ if not first_user and event_type == "response_item":
329
+ if kind == "message" and payload.get("role") == "user":
330
+ candidate = readable(payload.get("content")).strip()
331
+ if candidate and not candidate.startswith(context_prefixes):
332
+ first_user = " ".join(candidate.split())[:240]
333
+ if event_type != "response_item":
334
+ continue
335
+ if kind in ("function_call_output", "custom_tool_call_output"):
336
+ output = readable(payload.get("output"))
337
+ rpc_id = payload.get("call_id") or payload.get("id") or ""
338
+ matching_calls = calls_by_rpc.get((filename, rpc_id), [])
339
+ submitted_matches = list(submit_pattern.finditer(output))
340
+ arrow_matches = list(submitted_arrow_pattern.finditer(output))
341
+ table_matches = list(submit_table_pattern.finditer(output))
342
+ strong_submission_pairs = [
343
+ (match.group("name"), match.group("job"), match.group(0))
344
+ for match in submitted_matches
345
+ ] + [
346
+ (match.group("name").strip(), match.group("job"), match.group(0))
347
+ for match in arrow_matches
348
+ ] + [
349
+ (match.group("job"), match.group("job"), match.group(0))
350
+ for match in table_matches
351
+ ]
352
+ unique_submission_pairs = {}
353
+ for pair in strong_submission_pairs:
354
+ if plausible_job_id(pair[1]):
355
+ unique_submission_pairs.setdefault(pair[1], pair)
356
+ strong_submission_pairs = list(unique_submission_pairs.values())
357
+ submitting_names = [
358
+ match.group("name")
359
+ for match in submitting_pattern.finditer(output)
360
+ ]
361
+ explicit_job_ids = list(dict.fromkeys(
362
+ pair[1] for pair in strong_submission_pairs
363
+ ))
364
+ named_id_calls = [
365
+ call for call in matching_calls
366
+ if call["invocationKind"] in ("direct-shell", "programmatic")
367
+ and call["syntacticInvocations"] == 1
368
+ and not re.search(
369
+ r"(?i)\bdlc\s+(?:get|list|stop)\b",
370
+ call["command"],
371
+ )
372
+ ]
373
+ if named_id_calls and not explicit_job_ids:
374
+ explicit_job_ids = list(dict.fromkeys(
375
+ match.group("job")
376
+ for match in named_job_pattern.finditer(output)
377
+ ))
378
+ submission_pairs = list(strong_submission_pairs)
379
+ if not submission_pairs:
380
+ for index, job_id in enumerate(explicit_job_ids):
381
+ name = (
382
+ submitting_names[index]
383
+ if index < len(submitting_names)
384
+ else job_id
385
+ )
386
+ submission_pairs.append((name, job_id, job_id))
387
+ exit_code = exit_code_from(output)
388
+ for call in matching_calls:
389
+ call["resultLine"] = line_number
390
+ call["exitCode"] = exit_code
391
+ call["jobNames"] = list(dict.fromkeys(
392
+ call["jobNames"]
393
+ + submitting_names
394
+ + [pair[0] for pair in strong_submission_pairs]
395
+ ))
396
+ call["jobIds"] = list(dict.fromkeys(
397
+ call["jobIds"] + explicit_job_ids
398
+ ))
399
+ call["observedInvocations"] = max(
400
+ call["syntacticInvocations"],
401
+ len(submitting_names),
402
+ len(strong_submission_pairs),
403
+ len(explicit_job_ids),
404
+ )
405
+ if call["inspection"]:
406
+ call["outcome"] = "inspection"
407
+ elif call["dryRun"]:
408
+ call["outcome"] = "dry-run"
409
+ elif call["jobIds"]:
410
+ call["outcome"] = "submitted"
411
+ elif exit_code not in (None, 0):
412
+ call["outcome"] = "failed"
413
+ elif submitting_names:
414
+ call["outcome"] = "unresolved"
415
+ else:
416
+ call["outcome"] = "unknown"
417
+ call["resultEvidence"] = " ".join(output.split())[:1200]
418
+ ownership_pairs = (
419
+ submission_pairs
420
+ if not matching_calls
421
+ or any(
422
+ not call["inspection"] and not call["dryRun"]
423
+ for call in matching_calls
424
+ )
425
+ else []
426
+ )
427
+ if ownership_pairs and not matching_calls:
428
+ synthetic_ids = [
429
+ job_id for _, job_id, _ in ownership_pairs
430
+ if job_id not in synthetic_job_ids
431
+ ]
432
+ synthetic_job_ids.update(synthetic_ids)
433
+ else:
434
+ synthetic_ids = []
435
+ if synthetic_ids:
436
+ synthetic = {
437
+ "id": f"{session_id}:{rpc_id or 'output'}:output-{line_number}",
438
+ "timestamp": timestamp,
439
+ "sessionId": session_id,
440
+ "cwd": cwd,
441
+ "rolloutPath": filename,
442
+ "line": line_number,
443
+ "sessionObjective": first_user,
444
+ "toolName": "output-only",
445
+ "callId": rpc_id,
446
+ "invocationKind": "output-only",
447
+ "syntacticInvocations": 0,
448
+ "observedInvocations": len(synthetic_ids),
449
+ "inspection": False,
450
+ "dryRun": False,
451
+ "explicitSubmit": True,
452
+ "outcome": "submitted",
453
+ "exitCode": exit_code,
454
+ "jobIds": synthetic_ids,
455
+ "jobNames": list(dict.fromkeys(
456
+ submitting_names
457
+ + [pair[0] for pair in strong_submission_pairs]
458
+ )),
459
+ "resultLine": line_number,
460
+ "resultEvidence": " ".join(output.split())[:1200],
461
+ "command": "",
462
+ "isSubagent": is_subagent,
463
+ "parentThreadId": parent_thread_id,
464
+ }
465
+ calls.append(synthetic)
466
+ for job_name, job_id, job_evidence in ownership_pairs:
467
+ candidate = {
468
+ "jobId": job_id,
469
+ "name": job_name,
470
+ "submittedAt": timestamp,
471
+ "sessionId": session_id,
472
+ "cwd": cwd,
473
+ "rolloutPath": filename,
474
+ "line": line_number,
475
+ "sessionObjective": first_user,
476
+ "evidence": " ".join(job_evidence.split())[:500],
477
+ "callId": rpc_id,
478
+ "command": matching_calls[0]["command"] if matching_calls else "",
479
+ "commandLine": matching_calls[0]["line"] if matching_calls else None,
480
+ "exitCode": exit_code,
481
+ "invocationKind": (
482
+ matching_calls[0]["invocationKind"]
483
+ if matching_calls else "output-only"
484
+ ),
485
+ "isSubagent": is_subagent,
486
+ "parentThreadId": parent_thread_id,
487
+ "ownershipSource": (
488
+ "tool-call" if matching_calls else "output-only"
489
+ ),
490
+ "ownershipRank": 3 if matching_calls else 2,
491
+ }
492
+ existing = submissions.get(job_id)
493
+ replace = not existing
494
+ if existing:
495
+ candidate_rank = candidate["ownershipRank"]
496
+ existing_rank = existing.get("ownershipRank", 0)
497
+ if candidate_rank > existing_rank:
498
+ replace = True
499
+ elif candidate_rank == existing_rank:
500
+ candidate_time = candidate.get("submittedAt") or ""
501
+ existing_time = existing.get("submittedAt") or ""
502
+ replace = bool(
503
+ candidate_time
504
+ and (not existing_time or candidate_time < existing_time)
505
+ )
506
+ if replace:
507
+ submissions[job_id] = candidate
508
+ elif kind in ("function_call", "custom_tool_call"):
509
+ rpc_id = (
510
+ payload.get("call_id")
511
+ or payload.get("id")
512
+ or f"line-{line_number}"
513
+ )
514
+ for command_index, (command, command_cwd) in enumerate(
515
+ tool_commands(payload)
516
+ ):
517
+ classification = classify_dlc_command(command)
518
+ if classification:
519
+ (
520
+ invocation_kind,
521
+ syntactic_count,
522
+ inspection,
523
+ dry_run,
524
+ explicit_submit,
525
+ ) = classification
526
+ record = {
527
+ "id": f"{session_id}:{rpc_id}:{command_index}",
528
+ "timestamp": timestamp,
529
+ "sessionId": session_id,
530
+ "cwd": command_cwd or cwd,
531
+ "rolloutPath": filename,
532
+ "line": line_number,
533
+ "sessionObjective": first_user,
534
+ "toolName": payload.get("name") or "",
535
+ "callId": rpc_id,
536
+ "invocationKind": invocation_kind,
537
+ "syntacticInvocations": syntactic_count,
538
+ "observedInvocations": syntactic_count,
539
+ "inspection": inspection,
540
+ "dryRun": dry_run,
541
+ "explicitSubmit": explicit_submit,
542
+ "outcome": (
543
+ "inspection" if inspection
544
+ else "dry-run" if dry_run
545
+ else "pending"
546
+ ),
547
+ "exitCode": None,
548
+ "jobIds": [],
549
+ "jobNames": [],
550
+ "resultLine": None,
551
+ "resultEvidence": "",
552
+ "command": " ".join(command.split())[:4000],
553
+ "isSubagent": is_subagent,
554
+ "parentThreadId": parent_thread_id,
555
+ }
556
+ calls.append(record)
557
+ calls_by_rpc.setdefault((filename, rpc_id), []).append(record)
558
+ raw_input = readable(
559
+ payload.get("input") or payload.get("arguments")
560
+ )
561
+ if training_pattern.search(raw_input):
562
+ launches.append({
563
+ "kind": (
564
+ "dlc"
565
+ if re.search(r"(?i)\bdlc\b", raw_input)
566
+ else "scheduler"
567
+ if re.search(r"(?i)\b(?:sbatch|srun)\b", raw_input)
568
+ else "training"
569
+ ),
570
+ "timestamp": timestamp,
571
+ "sessionId": session_id,
572
+ "cwd": cwd,
573
+ "rolloutPath": filename,
574
+ "line": line_number,
575
+ "sessionObjective": first_user,
576
+ "command": " ".join(raw_input.split())[:1200],
577
+ "isSubagent": is_subagent,
578
+ "parentThreadId": parent_thread_id,
579
+ })
580
+ except Exception:
581
+ continue
582
+
583
+ dlc = "/etc/dsw/runtime/export_bin/dlc"
584
+ def status_for(item):
585
+ job_id, record = item
586
+ status = {
587
+ "status": "Unknown",
588
+ "reason": "",
589
+ "message": "",
590
+ "duration": None,
591
+ }
592
+ if not os.path.isfile(dlc) or not re.fullmatch(r"dlc[A-Za-z0-9]+", job_id):
593
+ return job_id, status
594
+ try:
595
+ completed = subprocess.run(
596
+ [dlc, "get", "job", job_id],
597
+ stdout=subprocess.PIPE,
598
+ stderr=subprocess.PIPE,
599
+ text=True,
600
+ timeout=18,
601
+ )
602
+ if completed.returncode == 0:
603
+ payload = json.loads(completed.stdout)
604
+ status = {
605
+ "status": payload.get("Status") or "Unknown",
606
+ "reason": payload.get("ReasonCode") or "",
607
+ "message": payload.get("ReasonMessage") or "",
608
+ "duration": payload.get("Duration"),
609
+ }
610
+ else:
611
+ status["message"] = (completed.stderr or completed.stdout).strip()[:500]
612
+ except Exception as error:
613
+ status["message"] = str(error)[:500]
614
+ return job_id, status
615
+
616
+ direct_job_ids = {
617
+ job_id
618
+ for call in calls
619
+ if call["invocationKind"] != "output-only"
620
+ for job_id in call["jobIds"]
621
+ }
622
+ calls = [
623
+ call for call in calls
624
+ if call["invocationKind"] != "output-only"
625
+ or any(job_id not in direct_job_ids for job_id in call["jobIds"])
626
+ ]
627
+ for record in submissions.values():
628
+ record.pop("ownershipRank", None)
629
+
630
+ ordered = sorted(
631
+ submissions.values(),
632
+ key=lambda item: item.get("submittedAt") or "",
633
+ reverse=True,
634
+ )
635
+ for record in ordered:
636
+ record.update({
637
+ "status": "Unknown",
638
+ "reason": "",
639
+ "message": "",
640
+ "duration": None,
641
+ })
642
+ status_items = [
643
+ (record["jobId"], record)
644
+ for record in ordered[:min(display_limit, 120)]
645
+ ]
646
+ if status_items:
647
+ with concurrent.futures.ThreadPoolExecutor(max_workers=min(8, len(status_items))) as pool:
648
+ for job_id, status in pool.map(status_for, status_items):
649
+ submissions[job_id].update(status)
650
+
651
+ ordered = sorted(
652
+ submissions.values(),
653
+ key=lambda item: item.get("submittedAt") or "",
654
+ reverse=True,
655
+ )[:500]
656
+ calls.sort(key=lambda item: item.get("timestamp") or "", reverse=True)
657
+ launches.sort(key=lambda item: item.get("timestamp") or "", reverse=True)
658
+ result = {
659
+ "filesScanned": len(paths),
660
+ "totalFiles": len(all_paths),
661
+ "scanScope": "all-rollouts" if not window_days else f"recent-{window_days}d",
662
+ "windowDays": window_days,
663
+ "calls": calls,
664
+ "totalCalls": len(calls),
665
+ "submissions": ordered,
666
+ "totalSubmissions": len(submissions),
667
+ "launches": launches[:display_limit],
668
+ }
669
+ if summary_mode:
670
+ result = {
671
+ "filesScanned": result["filesScanned"],
672
+ "totalCalls": result["totalCalls"],
673
+ "totalSubmissions": result["totalSubmissions"],
674
+ "byKind": {
675
+ kind: sum(1 for call in calls if call["invocationKind"] == kind)
676
+ for kind in (
677
+ "direct-shell", "programmatic", "submit-script", "output-only"
678
+ )
679
+ },
680
+ "byOutcome": {
681
+ outcome: sum(1 for call in calls if call["outcome"] == outcome)
682
+ for outcome in (
683
+ "submitted", "failed", "unresolved", "unknown",
684
+ "inspection", "dry-run"
685
+ )
686
+ },
687
+ "subagentCalls": sum(1 for call in calls if call["isSubagent"]),
688
+ "latest": [
689
+ {
690
+ "timestamp": call["timestamp"],
691
+ "invocationKind": call["invocationKind"],
692
+ "outcome": call["outcome"],
693
+ "jobs": len(call["jobIds"]),
694
+ "isSubagent": call["isSubagent"],
695
+ "command": call["command"][:180],
696
+ }
697
+ for call in calls[:12]
698
+ ],
699
+ }
700
+ print(json.dumps(result, ensure_ascii=False, separators=(",", ":")))
701
+ `;