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,33 +1,33 @@
1
- import { prepareProfileHome, profileHomeSelection } from "./remote-profile-home.mjs";
2
-
3
- function shellQuote(value) {
4
- return `'${String(value ?? "").replace(/'/g, `'"'"'`)}'`;
5
- }
6
-
7
- function safeKey(value) {
8
- return String(value || "default")
9
- .replace(/[^a-zA-Z0-9_.-]/g, "-")
1
+ import { prepareProfileHome, profileHomeSelection } from "./remote-profile-home.mjs";
2
+
3
+ function shellQuote(value) {
4
+ return `'${String(value ?? "").replace(/'/g, `'"'"'`)}'`;
5
+ }
6
+
7
+ function safeKey(value) {
8
+ return String(value || "default")
9
+ .replace(/[^a-zA-Z0-9_.-]/g, "-")
10
10
  .slice(0, 80);
11
- }
12
-
11
+ }
12
+
13
13
  export function durableRemoteAppServerCommand({
14
- executable = "codex",
15
- key = "default",
16
- codexHome = "",
14
+ executable = "codex",
15
+ key = "default",
16
+ codexHome = "",
17
17
  useActiveProfile = false,
18
18
  isolatedProfile = "",
19
- } = {}) {
20
- const id = safeKey(key);
19
+ } = {}) {
20
+ const id = safeKey(key);
21
21
  const setup = [
22
22
  "set -eu",
23
23
  'test ! -d "$HOME/.scope-codex-migration.lock" || { echo "SCOPE Codex storage migration in progress; retry after completion" >&2; exit 75; }',
24
- `scope_codex_exe=${shellQuote(executable)}`,
25
- ];
24
+ `scope_codex_exe=${shellQuote(executable)}`,
25
+ ];
26
26
  if (isolatedProfile) {
27
27
  if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,47}$/.test(isolatedProfile)) throw new Error("Invalid isolated profile");
28
28
  setup.push(
29
29
  `app_id=${shellQuote(id)}`,
30
- ...prepareProfileHome(isolatedProfile),
30
+ ...prepareProfileHome(isolatedProfile),
31
31
  // A shared rollout requires a shared writer lock across CODEX_HOME values.
32
32
  'mkdir -p "$HOME/.codex/thread-writer-locks"',
33
33
  'if test -d "$app_codex_home/thread-writer-locks" && test ! -L "$app_codex_home/thread-writer-locks"; then',
@@ -43,90 +43,90 @@ export function durableRemoteAppServerCommand({
43
43
  'done',
44
44
  );
45
45
  } else if (codexHome) {
46
- setup.push(`app_id=${shellQuote(id)}`, `app_codex_home="${codexHome}"`);
47
- } else if (useActiveProfile) {
48
- setup.push(
49
- 'root_codex_home="$HOME/.codex"',
50
- 'active_slug="$(cat "$root_codex_home/scope-auth-profiles/active" 2>/dev/null || true)"',
51
- "case \"$active_slug\" in",
52
- ' ""|*[!a-zA-Z0-9._-]*) app_id=default; app_codex_home="$root_codex_home" ;;',
53
- ' *) candidate_home="$root_codex_home/scope-auth-profiles/$active_slug/home"; if test -f "$candidate_home/auth.json"; then app_id="profile-$active_slug"; app_codex_home="$root_codex_home"; else app_id=default; app_codex_home="$root_codex_home"; fi ;;',
54
- "esac",
55
- );
46
+ setup.push(`app_id=${shellQuote(id)}`, `app_codex_home="${codexHome}"`);
47
+ } else if (useActiveProfile) {
48
+ setup.push(
49
+ 'root_codex_home="$HOME/.codex"',
50
+ 'active_slug="$(cat "$root_codex_home/scope-auth-profiles/active" 2>/dev/null || true)"',
51
+ "case \"$active_slug\" in",
52
+ ' ""|*[!a-zA-Z0-9._-]*) app_id=default; app_codex_home="$root_codex_home" ;;',
53
+ ' *) candidate_home="$root_codex_home/scope-auth-profiles/$active_slug/home"; if test -f "$candidate_home/auth.json"; then app_id="profile-$active_slug"; app_codex_home="$root_codex_home"; else app_id=default; app_codex_home="$root_codex_home"; fi ;;',
54
+ "esac",
55
+ );
56
56
  } else {
57
57
  setup.push(
58
58
  `app_id=${shellQuote(id)}`,
59
59
  'app_codex_home="$HOME/.codex"',
60
60
  );
61
61
  }
62
- return [
63
- ...setup,
64
- 'tmux_name="scope-app-server-$app_id"',
65
- 'state_dir="$app_codex_home/app-server-control"',
66
- 'socket_path="$state_dir/scope-$app_id.sock"',
67
- 'log_path="$state_dir/scope-$app_id.log"',
68
- 'lock_path="$state_dir/app-server-startup.lock"',
69
- 'mkdir -p "$state_dir"',
70
- 'lock_mode=none',
71
- 'if command -v flock >/dev/null 2>&1; then',
72
- ' exec 9>"$lock_path"',
73
- ' if ! flock -w 15 9; then echo "SCOPE app-server startup lock timed out" >&2; exit 73; fi',
74
- ' lock_mode=flock',
75
- 'else',
76
- ' lock_dir="$lock_path.d"',
77
- ' lock_attempt=0',
78
- ' while test "$lock_attempt" -lt 60; do',
79
- ' if mkdir "$lock_dir" 2>/dev/null; then lock_mode=mkdir; break; fi',
80
- ' lock_attempt=$((lock_attempt + 1))',
81
- ' sleep 0.25',
82
- ' done',
83
- ' if test "$lock_mode" != mkdir; then echo "SCOPE app-server startup lock timed out" >&2; exit 73; fi',
84
- 'fi',
85
- 'scope_unlock() {',
86
- ' if test "$lock_mode" = flock; then flock -u 9 || true; exec 9>&-; fi',
87
- ' if test "$lock_mode" = mkdir; then rmdir "$lock_dir" 2>/dev/null || true; fi',
88
- ' lock_mode=none',
89
- '}',
90
- 'trap scope_unlock EXIT',
91
- "trap 'scope_unlock; exit 74' HUP INT TERM",
92
- 'socket_is_live() {',
93
- ' test -S "$socket_path" || return 1',
94
- ' if command -v ss >/dev/null 2>&1; then',
95
- // Newer Codex daemons expose custom socket paths as symlinks into /tmp.
96
- // ss reports the bound target, not that public alias. Preserve live writers.
97
- ' scope_socket_target="$(readlink -f -- "$socket_path" 2>/dev/null || printf \'%s\' "$socket_path")"',
98
- ' ss -xlH 2>/dev/null | awk -v alias="$socket_path" -v target="$scope_socket_target" \'index($0, " " alias " ") || index($0, " " target " ") { found = 1 } END { exit !found }\'',
99
- ' else',
62
+ return [
63
+ ...setup,
64
+ 'tmux_name="scope-app-server-$app_id"',
65
+ 'state_dir="$app_codex_home/app-server-control"',
66
+ 'socket_path="$state_dir/scope-$app_id.sock"',
67
+ 'log_path="$state_dir/scope-$app_id.log"',
68
+ 'lock_path="$state_dir/app-server-startup.lock"',
69
+ 'mkdir -p "$state_dir"',
70
+ 'lock_mode=none',
71
+ 'if command -v flock >/dev/null 2>&1; then',
72
+ ' exec 9>"$lock_path"',
73
+ ' if ! flock -w 15 9; then echo "SCOPE app-server startup lock timed out" >&2; exit 73; fi',
74
+ ' lock_mode=flock',
75
+ 'else',
76
+ ' lock_dir="$lock_path.d"',
77
+ ' lock_attempt=0',
78
+ ' while test "$lock_attempt" -lt 60; do',
79
+ ' if mkdir "$lock_dir" 2>/dev/null; then lock_mode=mkdir; break; fi',
80
+ ' lock_attempt=$((lock_attempt + 1))',
81
+ ' sleep 0.25',
82
+ ' done',
83
+ ' if test "$lock_mode" != mkdir; then echo "SCOPE app-server startup lock timed out" >&2; exit 73; fi',
84
+ 'fi',
85
+ 'scope_unlock() {',
86
+ ' if test "$lock_mode" = flock; then flock -u 9 || true; exec 9>&-; fi',
87
+ ' if test "$lock_mode" = mkdir; then rmdir "$lock_dir" 2>/dev/null || true; fi',
88
+ ' lock_mode=none',
89
+ '}',
90
+ 'trap scope_unlock EXIT',
91
+ "trap 'scope_unlock; exit 74' HUP INT TERM",
92
+ 'socket_is_live() {',
93
+ ' test -S "$socket_path" || return 1',
94
+ ' if command -v ss >/dev/null 2>&1; then',
95
+ // Newer Codex daemons expose custom socket paths as symlinks into /tmp.
96
+ // ss reports the bound target, not that public alias. Preserve live writers.
97
+ ' scope_socket_target="$(readlink -f -- "$socket_path" 2>/dev/null || printf \'%s\' "$socket_path")"',
98
+ ' ss -xlH 2>/dev/null | awk -v alias="$socket_path" -v target="$scope_socket_target" \'index($0, " " alias " ") || index($0, " " target " ") { found = 1 } END { exit !found }\'',
99
+ ' else',
100
100
  ' tmux has-session -t "=$tmux_name" 2>/dev/null',
101
- ' fi',
102
- '}',
103
- 'if test -S "$socket_path" && ! socket_is_live; then',
101
+ ' fi',
102
+ '}',
103
+ 'if test -S "$socket_path" && ! socket_is_live; then',
104
104
  ' if tmux has-session -t "=$tmux_name" 2>/dev/null; then',
105
- ' echo "SCOPE app-server tmux $tmux_name exists but its socket is not listening; preserving it for inspection" >&2',
106
- ' exit 71',
107
- ' fi',
108
- ' rm -f -- "$socket_path"',
109
- 'fi',
110
- 'if ! socket_is_live; then',
105
+ ' echo "SCOPE app-server tmux $tmux_name exists but its socket is not listening; preserving it for inspection" >&2',
106
+ ' exit 71',
107
+ ' fi',
108
+ ' rm -f -- "$socket_path"',
109
+ 'fi',
110
+ 'if ! socket_is_live; then',
111
111
  ' if tmux has-session -t "=$tmux_name" 2>/dev/null; then',
112
- ' echo "SCOPE app-server tmux $tmux_name exists without a live socket; refusing to terminate or replace it" >&2',
113
- ' exit 71',
114
- ' fi',
112
+ ' echo "SCOPE app-server tmux $tmux_name exists without a live socket; refusing to terminate or replace it" >&2',
113
+ ' exit 71',
114
+ ' fi',
115
115
  ' tmux new-session -d -s "$tmux_name" "export CODEX_HOME=\"$app_codex_home\"; exec \"$scope_codex_exe\"' + (isolatedProfile ? ' -c cli_auth_credentials_store=file' : '') + ' app-server --listen \"unix://$socket_path\" >>\"$log_path\" 2>&1"',
116
- ' ready=0',
117
- ' ready_attempt=0',
118
- ' while test "$ready_attempt" -lt 60; do',
119
- ' if socket_is_live; then ready=1; break; fi',
120
- ' ready_attempt=$((ready_attempt + 1))',
121
- ' sleep 0.25',
122
- ' done',
123
- ' if test "$ready" != 1; then echo "SCOPE app-server $tmux_name did not create a live socket within 15 seconds; pane preserved for inspection" >&2; tail -n 20 "$log_path" >&2 || true; exit 72; fi',
124
- "fi",
125
- 'scope_unlock',
126
- 'trap - EXIT HUP INT TERM',
127
- 'export CODEX_HOME="$app_codex_home"',
128
- 'exec "$scope_codex_exe" app-server proxy --sock "$socket_path"',
129
- ].join("\n");
116
+ ' ready=0',
117
+ ' ready_attempt=0',
118
+ ' while test "$ready_attempt" -lt 60; do',
119
+ ' if socket_is_live; then ready=1; break; fi',
120
+ ' ready_attempt=$((ready_attempt + 1))',
121
+ ' sleep 0.25',
122
+ ' done',
123
+ ' if test "$ready" != 1; then echo "SCOPE app-server $tmux_name did not create a live socket within 15 seconds; pane preserved for inspection" >&2; tail -n 20 "$log_path" >&2 || true; exit 72; fi',
124
+ "fi",
125
+ 'scope_unlock',
126
+ 'trap - EXIT HUP INT TERM',
127
+ 'export CODEX_HOME="$app_codex_home"',
128
+ 'exec "$scope_codex_exe" app-server proxy --sock "$socket_path"',
129
+ ].join("\n");
130
130
  }
131
131
 
132
132
  export function retireProfileAppServerCommand(connectionKey) {
@@ -171,33 +171,33 @@ export function retireScopedAppServerCommand(connectionKey) {
171
171
  const base = retireProfileAppServerCommand(account ? `profile-${account[1]}` : id);
172
172
  return account ? base
173
173
  .replace(`app_id=${shellQuote(`profile-${account[1]}`)}`, `app_id=${shellQuote(id)}`)
174
- .replace('state_dir="$HOME/.codex/app-server-control"',
175
- [...profileHomeSelection(account[1]), 'state_dir="$app_codex_home/app-server-control"'].join("\n"))
174
+ .replace('state_dir="$HOME/.codex/app-server-control"',
175
+ [...profileHomeSelection(account[1]), 'state_dir="$app_codex_home/app-server-control"'].join("\n"))
176
176
  .replace('*"codex app-server --listen unix://$socket_path"*', '*"codex -c cli_auth_credentials_store=file app-server --listen unix://$socket_path"*') : base;
177
177
  }
178
-
179
- /** Run the bootstrap handler in the host's preferred interactive shell.
180
- *
181
- * `-c` is important for app-server: it keeps the shell from reading JSONL from
182
- * stdin as another command. The final exec gives that unchanged stream to
183
- * Codex. Hosts without zsh retain the established Bash bootstrap path.
184
- */
185
- export function wrapBootstrapAppServer(command, preLaunchCommand = "") {
186
- const startup = String(preLaunchCommand || "").trim();
187
- const zshHandler = [startup, command].filter(Boolean).join("; ");
188
- const bashHandler = [
189
- "source ~/.bashrc >/dev/null 2>&1 || true",
190
- startup,
191
- command,
192
- ].filter(Boolean).join("; ");
193
- return [
194
- "if command -v zsh >/dev/null 2>&1",
195
- `then exec zsh -ic ${shellQuote(zshHandler)}`,
196
- `else exec bash -ic ${shellQuote(bashHandler)}`,
197
- "fi",
198
- ].join("; ");
199
- }
200
-
201
- export function wrapProxyBootstrapAppServer(command, preLaunchCommand = "") {
202
- return wrapBootstrapAppServer(command, preLaunchCommand);
203
- }
178
+
179
+ /** Run the bootstrap handler in the host's preferred interactive shell.
180
+ *
181
+ * `-c` is important for app-server: it keeps the shell from reading JSONL from
182
+ * stdin as another command. The final exec gives that unchanged stream to
183
+ * Codex. Hosts without zsh retain the established Bash bootstrap path.
184
+ */
185
+ export function wrapBootstrapAppServer(command, preLaunchCommand = "") {
186
+ const startup = String(preLaunchCommand || "").trim();
187
+ const zshHandler = [startup, command].filter(Boolean).join("; ");
188
+ const bashHandler = [
189
+ "source ~/.bashrc >/dev/null 2>&1 || true",
190
+ startup,
191
+ command,
192
+ ].filter(Boolean).join("; ");
193
+ return [
194
+ "if command -v zsh >/dev/null 2>&1",
195
+ `then exec zsh -ic ${shellQuote(zshHandler)}`,
196
+ `else exec bash -ic ${shellQuote(bashHandler)}`,
197
+ "fi",
198
+ ].join("; ");
199
+ }
200
+
201
+ export function wrapProxyBootstrapAppServer(command, preLaunchCommand = "") {
202
+ return wrapBootstrapAppServer(command, preLaunchCommand);
203
+ }
@@ -1,148 +1,148 @@
1
- import { spawn } from "node:child_process";
2
- import os from "node:os";
3
- import path from "node:path";
4
-
5
- const DIRECTORY_TIMEOUT_MS = 20_000;
6
- const MAX_OUTPUT_BYTES = 2_000_000;
7
-
8
- const DIRECTORY_PROBE = String.raw`
9
- import json
10
- import os
11
- import sys
12
-
13
- requested = sys.argv[1]
14
- if not requested.startswith("/") or "\n" in requested or "\r" in requested:
15
- print("工作目录必须是远端绝对路径", file=sys.stderr)
16
- raise SystemExit(2)
17
- resolved = os.path.realpath(requested)
18
- if not os.path.isdir(resolved):
19
- print("工作目录不存在:" + resolved, file=sys.stderr)
20
- raise SystemExit(3)
21
-
22
- directories = []
23
- truncated = False
24
- try:
25
- names = sorted(os.listdir(resolved), key=lambda value: value.lower())
26
- for name in names:
27
- candidate = os.path.join(resolved, name)
28
- try:
29
- if os.path.isdir(candidate):
30
- directories.append({"name": name, "path": candidate})
31
- except OSError:
32
- continue
33
- if len(directories) >= 300:
34
- truncated = True
35
- break
36
- except OSError as error:
37
- print("无法读取工作目录:" + str(error), file=sys.stderr)
38
- raise SystemExit(4)
39
-
40
- parent = os.path.dirname(resolved)
41
- print(json.dumps({
42
- "cwd": resolved,
43
- "parent": parent if parent != resolved else None,
44
- "directories": directories,
45
- "truncated": truncated,
46
- }, ensure_ascii=False, separators=(",", ":")))
47
- `;
48
-
49
- function shellQuote(value) {
50
- return `'${String(value).replaceAll("'", `'"'"'`)}'`;
51
- }
52
-
53
- function cleanError(value) {
54
- return String(value || "")
55
- .replace(/\x1b\[[0-9;]*m/g, "")
56
- .trim()
57
- .slice(0, 2_000);
58
- }
59
-
60
- export function listRemoteDirectories({
61
- host,
62
- requestedPath,
63
- sshConfig = path.join(os.homedir(), ".ssh", "config"),
64
- timeoutMs = DIRECTORY_TIMEOUT_MS,
65
- } = {}) {
66
- const alias = String(host || "").trim();
67
- const remotePath = String(requestedPath || "/").trim();
68
- if (!alias || !/^[a-zA-Z0-9_.:@-]+$/.test(alias)) {
69
- return Promise.reject(new Error("SSH 主机名无效"));
70
- }
71
- if (!remotePath.startsWith("/") || /[\r\n]/.test(remotePath)) {
72
- return Promise.reject(new Error("工作目录必须是远端绝对路径"));
73
- }
74
-
75
- return new Promise((resolve, reject) => {
76
- const child = spawn(
77
- "ssh",
78
- [
79
- "-F",
80
- sshConfig,
81
- "-o",
82
- "BatchMode=yes",
83
- "-o",
84
- "ConnectTimeout=8",
85
- "--",
86
- alias,
87
- `python3 - ${shellQuote(remotePath)}`,
88
- ],
89
- { stdio: ["pipe", "pipe", "pipe"], windowsHide: true },
90
- );
91
- const stdout = [];
92
- const stderr = [];
93
- let outputBytes = 0;
94
- let settled = false;
95
- let timer = null;
96
- const finish = (error, value) => {
97
- if (settled) return;
98
- settled = true;
99
- if (timer) clearTimeout(timer);
100
- if (error) reject(error);
101
- else resolve(value);
102
- };
103
- const collect = (target) => (chunk) => {
104
- outputBytes += chunk.length;
105
- if (outputBytes > MAX_OUTPUT_BYTES) {
106
- child.kill();
107
- finish(new Error("远端目录列表过大"));
108
- return;
109
- }
110
- target.push(chunk);
111
- };
112
- child.stdout.on("data", collect(stdout));
113
- child.stderr.on("data", collect(stderr));
114
- child.once("error", (error) => finish(error));
115
- child.once("exit", (code) => {
116
- const output = Buffer.concat(stdout).toString("utf8").trim();
117
- const errorOutput = cleanError(Buffer.concat(stderr).toString("utf8"));
118
- if (code !== 0) {
119
- finish(new Error(errorOutput || `SSH 目录读取退出码 ${code}`));
120
- return;
121
- }
122
- try {
123
- const listing = JSON.parse(output);
124
- finish(null, {
125
- host: alias,
126
- cwd: String(listing.cwd || remotePath),
127
- parent: listing.parent ? String(listing.parent) : null,
128
- directories: Array.isArray(listing.directories)
129
- ? listing.directories
130
- .filter((entry) => entry?.name && entry?.path)
131
- .map((entry) => ({
132
- name: String(entry.name),
133
- path: String(entry.path),
134
- }))
135
- : [],
136
- truncated: Boolean(listing.truncated),
137
- });
138
- } catch {
139
- finish(new Error("远端目录结果无法解析"));
140
- }
141
- });
142
- timer = setTimeout(() => {
143
- child.kill();
144
- finish(new Error("读取远端目录超时"));
145
- }, timeoutMs);
146
- child.stdin.end(DIRECTORY_PROBE);
147
- });
148
- }
1
+ import { spawn } from "node:child_process";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ const DIRECTORY_TIMEOUT_MS = 20_000;
6
+ const MAX_OUTPUT_BYTES = 2_000_000;
7
+
8
+ const DIRECTORY_PROBE = String.raw`
9
+ import json
10
+ import os
11
+ import sys
12
+
13
+ requested = sys.argv[1]
14
+ if not requested.startswith("/") or "\n" in requested or "\r" in requested:
15
+ print("工作目录必须是远端绝对路径", file=sys.stderr)
16
+ raise SystemExit(2)
17
+ resolved = os.path.realpath(requested)
18
+ if not os.path.isdir(resolved):
19
+ print("工作目录不存在:" + resolved, file=sys.stderr)
20
+ raise SystemExit(3)
21
+
22
+ directories = []
23
+ truncated = False
24
+ try:
25
+ names = sorted(os.listdir(resolved), key=lambda value: value.lower())
26
+ for name in names:
27
+ candidate = os.path.join(resolved, name)
28
+ try:
29
+ if os.path.isdir(candidate):
30
+ directories.append({"name": name, "path": candidate})
31
+ except OSError:
32
+ continue
33
+ if len(directories) >= 300:
34
+ truncated = True
35
+ break
36
+ except OSError as error:
37
+ print("无法读取工作目录:" + str(error), file=sys.stderr)
38
+ raise SystemExit(4)
39
+
40
+ parent = os.path.dirname(resolved)
41
+ print(json.dumps({
42
+ "cwd": resolved,
43
+ "parent": parent if parent != resolved else None,
44
+ "directories": directories,
45
+ "truncated": truncated,
46
+ }, ensure_ascii=False, separators=(",", ":")))
47
+ `;
48
+
49
+ function shellQuote(value) {
50
+ return `'${String(value).replaceAll("'", `'"'"'`)}'`;
51
+ }
52
+
53
+ function cleanError(value) {
54
+ return String(value || "")
55
+ .replace(/\x1b\[[0-9;]*m/g, "")
56
+ .trim()
57
+ .slice(0, 2_000);
58
+ }
59
+
60
+ export function listRemoteDirectories({
61
+ host,
62
+ requestedPath,
63
+ sshConfig = path.join(os.homedir(), ".ssh", "config"),
64
+ timeoutMs = DIRECTORY_TIMEOUT_MS,
65
+ } = {}) {
66
+ const alias = String(host || "").trim();
67
+ const remotePath = String(requestedPath || "/").trim();
68
+ if (!alias || !/^[a-zA-Z0-9_.:@-]+$/.test(alias)) {
69
+ return Promise.reject(new Error("SSH 主机名无效"));
70
+ }
71
+ if (!remotePath.startsWith("/") || /[\r\n]/.test(remotePath)) {
72
+ return Promise.reject(new Error("工作目录必须是远端绝对路径"));
73
+ }
74
+
75
+ return new Promise((resolve, reject) => {
76
+ const child = spawn(
77
+ "ssh",
78
+ [
79
+ "-F",
80
+ sshConfig,
81
+ "-o",
82
+ "BatchMode=yes",
83
+ "-o",
84
+ "ConnectTimeout=8",
85
+ "--",
86
+ alias,
87
+ `python3 - ${shellQuote(remotePath)}`,
88
+ ],
89
+ { stdio: ["pipe", "pipe", "pipe"], windowsHide: true },
90
+ );
91
+ const stdout = [];
92
+ const stderr = [];
93
+ let outputBytes = 0;
94
+ let settled = false;
95
+ let timer = null;
96
+ const finish = (error, value) => {
97
+ if (settled) return;
98
+ settled = true;
99
+ if (timer) clearTimeout(timer);
100
+ if (error) reject(error);
101
+ else resolve(value);
102
+ };
103
+ const collect = (target) => (chunk) => {
104
+ outputBytes += chunk.length;
105
+ if (outputBytes > MAX_OUTPUT_BYTES) {
106
+ child.kill();
107
+ finish(new Error("远端目录列表过大"));
108
+ return;
109
+ }
110
+ target.push(chunk);
111
+ };
112
+ child.stdout.on("data", collect(stdout));
113
+ child.stderr.on("data", collect(stderr));
114
+ child.once("error", (error) => finish(error));
115
+ child.once("exit", (code) => {
116
+ const output = Buffer.concat(stdout).toString("utf8").trim();
117
+ const errorOutput = cleanError(Buffer.concat(stderr).toString("utf8"));
118
+ if (code !== 0) {
119
+ finish(new Error(errorOutput || `SSH 目录读取退出码 ${code}`));
120
+ return;
121
+ }
122
+ try {
123
+ const listing = JSON.parse(output);
124
+ finish(null, {
125
+ host: alias,
126
+ cwd: String(listing.cwd || remotePath),
127
+ parent: listing.parent ? String(listing.parent) : null,
128
+ directories: Array.isArray(listing.directories)
129
+ ? listing.directories
130
+ .filter((entry) => entry?.name && entry?.path)
131
+ .map((entry) => ({
132
+ name: String(entry.name),
133
+ path: String(entry.path),
134
+ }))
135
+ : [],
136
+ truncated: Boolean(listing.truncated),
137
+ });
138
+ } catch {
139
+ finish(new Error("远端目录结果无法解析"));
140
+ }
141
+ });
142
+ timer = setTimeout(() => {
143
+ child.kill();
144
+ finish(new Error("读取远端目录超时"));
145
+ }, timeoutMs);
146
+ child.stdin.end(DIRECTORY_PROBE);
147
+ });
148
+ }
@@ -101,7 +101,7 @@ export function historicalAgent(host, rollout) {
101
101
  status: "idle",
102
102
  pane: null,
103
103
  rollout,
104
- subagents: [],
104
+ subagents: Array.isArray(rollout.subagents) ? rollout.subagents : [],
105
105
  historical: true,
106
106
  mapping: {
107
107
  rollout: "history",
@@ -120,9 +120,26 @@ export function historicalAgent(host, rollout) {
120
120
  export function createAgentEnricher({ getSubmissionItems }) {
121
121
  return function enrichAgentRelations(host, agent) {
122
122
  const sessionId = agent.rollout?.id || "";
123
+ const subagentById = new Map();
124
+ for (const sub of Array.isArray(agent.subagents) ? agent.subagents : []) {
125
+ if (sub?.id) subagentById.set(sub.id, sub);
126
+ }
127
+ if (sessionId) {
128
+ for (const session of Array.isArray(host.sessions) ? host.sessions : []) {
129
+ if (!session?.isSubagent || !session.id) continue;
130
+ if (session.parentThreadId !== sessionId) continue;
131
+ const prev = subagentById.get(session.id);
132
+ if (!prev || (session.mtimeMs || 0) >= (prev.mtimeMs || 0)) {
133
+ subagentById.set(session.id, session);
134
+ }
135
+ }
136
+ }
137
+ const mergedSubagents = Array.from(subagentById.values()).sort(
138
+ (a, b) => (b.mtimeMs || 0) - (a.mtimeMs || 0),
139
+ );
123
140
  const relatedSessionIds = new Set([
124
141
  sessionId,
125
- ...(agent.subagents || []).map((subagent) => subagent.id),
142
+ ...mergedSubagents.map((subagent) => subagent.id),
126
143
  ]);
127
144
  const localWorkloads = (host.workloads || []).filter(
128
145
  (workload) => workload.ownerSessionId === sessionId,
@@ -151,6 +168,7 @@ export function createAgentEnricher({ getSubmissionItems }) {
151
168
  for (const workload of localWorkloads) addPane(workload.pane);
152
169
  return {
153
170
  ...agent,
171
+ subagents: mergedSubagents,
154
172
  localWorkloads,
155
173
  remoteJobs,
156
174
  relatedPanes,