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,38 +1,38 @@
1
- /**
2
- * Return every known work directory for the selected host. Callers can merge
3
- * active and already-scanned historical sessions before applying a view filter.
4
- *
5
- * @param {Array<{host?: string, cwd?: string}>} sessions
6
- * @param {string} hostFilter
7
- */
8
- export function collectCwdOptions(sessions, hostFilter) {
9
- return Array.from(
10
- new Set(
11
- sessions
12
- .filter(
13
- (session) =>
14
- hostFilter === "all" || session.host === hostFilter,
15
- )
16
- .map((session) => session.cwd?.trim())
17
- .filter(Boolean),
18
- ),
19
- ).sort((left, right) => left.localeCompare(right));
20
- }
21
-
22
- /**
23
- * Remove cached history rows for Sessions that are currently controlled by a
24
- * live CLI process, tmux, or the app-server bridge.
25
- *
26
- * @template {{host?: string, sessionId?: string, rollout?: {id?: string} | null}} T
27
- * @param {Array<T>} sessions
28
- * @param {Array<{host?: string, sessionId?: string, rollout?: {id?: string} | null}>} activeSessions
29
- */
30
- export function excludeActiveSessions(sessions, activeSessions) {
31
- const identity = (session) => {
32
- const host = session?.host?.trim();
33
- const sessionId = session?.sessionId || session?.rollout?.id;
34
- return host && sessionId ? `${host}:${sessionId}` : "";
35
- };
36
- const activeKeys = new Set(activeSessions.map(identity).filter(Boolean));
37
- return sessions.filter((session) => !activeKeys.has(identity(session)));
38
- }
1
+ /**
2
+ * Return every known work directory for the selected host. Callers can merge
3
+ * active and already-scanned historical sessions before applying a view filter.
4
+ *
5
+ * @param {Array<{host?: string, cwd?: string}>} sessions
6
+ * @param {string} hostFilter
7
+ */
8
+ export function collectCwdOptions(sessions, hostFilter) {
9
+ return Array.from(
10
+ new Set(
11
+ sessions
12
+ .filter(
13
+ (session) =>
14
+ hostFilter === "all" || session.host === hostFilter,
15
+ )
16
+ .map((session) => session.cwd?.trim())
17
+ .filter(Boolean),
18
+ ),
19
+ ).sort((left, right) => left.localeCompare(right));
20
+ }
21
+
22
+ /**
23
+ * Remove cached history rows for Sessions that are currently controlled by a
24
+ * live CLI process, tmux, or the app-server bridge.
25
+ *
26
+ * @template {{host?: string, sessionId?: string, rollout?: {id?: string} | null}} T
27
+ * @param {Array<T>} sessions
28
+ * @param {Array<{host?: string, sessionId?: string, rollout?: {id?: string} | null}>} activeSessions
29
+ */
30
+ export function excludeActiveSessions(sessions, activeSessions) {
31
+ const identity = (session) => {
32
+ const host = session?.host?.trim();
33
+ const sessionId = session?.sessionId || session?.rollout?.id;
34
+ return host && sessionId ? `${host}:${sessionId}` : "";
35
+ };
36
+ const activeKeys = new Set(activeSessions.map(identity).filter(Boolean));
37
+ return sessions.filter((session) => !activeKeys.has(identity(session)));
38
+ }
package/lib/ssh-config.js CHANGED
@@ -1,26 +1,26 @@
1
- /**
2
- * Return concrete SSH aliases whose own Host block points at a hostname.
3
- * Wildcard blocks are intentionally ignored: DLC ownership is scoped to the
4
- * explicitly configured submission host, not every reachable host.
5
- *
6
- * @param {string} source OpenSSH config text
7
- * @param {string} expectedHostname configured HostName value
8
- */
9
- export function sshAliasesForHostname(source, expectedHostname) {
10
- const aliases = new Set();
11
- let current = [];
12
- for (const line of source.split(/\r?\n/)) {
13
- const hostMatch = line.match(/^\s*Host\s+(.+?)\s*$/i);
14
- if (hostMatch) {
15
- current = hostMatch[1]
16
- .split(/\s+/)
17
- .filter((value) => value && !/[*?!]/.test(value));
18
- continue;
19
- }
20
- const hostnameMatch = line.match(/^\s*HostName\s+(.+?)\s*$/i);
21
- if (!hostnameMatch || hostnameMatch[1] !== expectedHostname) continue;
22
- for (const alias of current) aliases.add(alias);
23
- }
24
- aliases.add(expectedHostname);
25
- return aliases;
26
- }
1
+ /**
2
+ * Return concrete SSH aliases whose own Host block points at a hostname.
3
+ * Wildcard blocks are intentionally ignored: DLC ownership is scoped to the
4
+ * explicitly configured submission host, not every reachable host.
5
+ *
6
+ * @param {string} source OpenSSH config text
7
+ * @param {string} expectedHostname configured HostName value
8
+ */
9
+ export function sshAliasesForHostname(source, expectedHostname) {
10
+ const aliases = new Set();
11
+ let current = [];
12
+ for (const line of source.split(/\r?\n/)) {
13
+ const hostMatch = line.match(/^\s*Host\s+(.+?)\s*$/i);
14
+ if (hostMatch) {
15
+ current = hostMatch[1]
16
+ .split(/\s+/)
17
+ .filter((value) => value && !/[*?!]/.test(value));
18
+ continue;
19
+ }
20
+ const hostnameMatch = line.match(/^\s*HostName\s+(.+?)\s*$/i);
21
+ if (!hostnameMatch || hostnameMatch[1] !== expectedHostname) continue;
22
+ for (const alias of current) aliases.add(alias);
23
+ }
24
+ aliases.add(expectedHostname);
25
+ return aliases;
26
+ }
@@ -1,39 +1,39 @@
1
- /**
2
- * Keep the relative order the user is currently browsing while still
3
- * removing vanished rows and appending newly discovered rows.
4
- *
5
- * Passing an empty previousKeys array deliberately adopts nextItems' current
6
- * order, which lets callers expose an explicit "refresh order" action.
7
- *
8
- * @template T
9
- * @param {T[]} nextItems
10
- * @param {string[]} previousKeys
11
- * @param {(item: T) => string} keyOf
12
- * @returns {{ items: T[], keys: string[] }}
13
- */
14
- export function retainStableOrder(nextItems, previousKeys, keyOf) {
15
- const itemsByKey = new Map();
16
- for (const item of nextItems) {
17
- itemsByKey.set(keyOf(item), item);
18
- }
19
-
20
- const keys = [];
21
- const seen = new Set();
22
- for (const key of previousKeys) {
23
- if (!itemsByKey.has(key) || seen.has(key)) continue;
24
- keys.push(key);
25
- seen.add(key);
26
- }
27
- for (const item of nextItems) {
28
- const key = keyOf(item);
29
- if (seen.has(key)) continue;
30
- keys.push(key);
31
- seen.add(key);
32
- }
33
-
34
- return {
35
- items: keys.map((key) => itemsByKey.get(key)),
36
- keys,
37
- };
38
- }
39
-
1
+ /**
2
+ * Keep the relative order the user is currently browsing while still
3
+ * removing vanished rows and appending newly discovered rows.
4
+ *
5
+ * Passing an empty previousKeys array deliberately adopts nextItems' current
6
+ * order, which lets callers expose an explicit "refresh order" action.
7
+ *
8
+ * @template T
9
+ * @param {T[]} nextItems
10
+ * @param {string[]} previousKeys
11
+ * @param {(item: T) => string} keyOf
12
+ * @returns {{ items: T[], keys: string[] }}
13
+ */
14
+ export function retainStableOrder(nextItems, previousKeys, keyOf) {
15
+ const itemsByKey = new Map();
16
+ for (const item of nextItems) {
17
+ itemsByKey.set(keyOf(item), item);
18
+ }
19
+
20
+ const keys = [];
21
+ const seen = new Set();
22
+ for (const key of previousKeys) {
23
+ if (!itemsByKey.has(key) || seen.has(key)) continue;
24
+ keys.push(key);
25
+ seen.add(key);
26
+ }
27
+ for (const item of nextItems) {
28
+ const key = keyOf(item);
29
+ if (seen.has(key)) continue;
30
+ keys.push(key);
31
+ seen.add(key);
32
+ }
33
+
34
+ return {
35
+ items: keys.map((key) => itemsByKey.get(key)),
36
+ keys,
37
+ };
38
+ }
39
+
@@ -0,0 +1,130 @@
1
+ "use client";
2
+ import { useSyncExternalStore } from "react";
3
+
4
+ export type SubagentDisplayPrefs = {
5
+ showInlineCards: boolean;
6
+ showInteractions: boolean;
7
+ showHeaderBadge: boolean;
8
+ autoExpandInteractions: boolean;
9
+ };
10
+
11
+ export const DEFAULT_SUBAGENT_DISPLAY_PREFS: SubagentDisplayPrefs = {
12
+ showInlineCards: true,
13
+ showInteractions: true,
14
+ showHeaderBadge: true,
15
+ autoExpandInteractions: false,
16
+ };
17
+
18
+ const STORAGE_KEY = "scope:subagent-display";
19
+ const PREFS_EVENT = "scope:subagent-display-change";
20
+
21
+ let cachedRaw: string | null = null;
22
+ let cachedSnapshot: SubagentDisplayPrefs = DEFAULT_SUBAGENT_DISPLAY_PREFS;
23
+
24
+ export function normalizeSubagentDisplayPrefs(
25
+ raw: unknown,
26
+ ): SubagentDisplayPrefs {
27
+ if (!raw || typeof raw !== "object") return DEFAULT_SUBAGENT_DISPLAY_PREFS;
28
+ const obj = raw as Record<string, unknown>;
29
+ return {
30
+ showInlineCards:
31
+ typeof obj.showInlineCards === "boolean"
32
+ ? obj.showInlineCards
33
+ : DEFAULT_SUBAGENT_DISPLAY_PREFS.showInlineCards,
34
+ showInteractions:
35
+ typeof obj.showInteractions === "boolean"
36
+ ? obj.showInteractions
37
+ : DEFAULT_SUBAGENT_DISPLAY_PREFS.showInteractions,
38
+ showHeaderBadge:
39
+ typeof obj.showHeaderBadge === "boolean"
40
+ ? obj.showHeaderBadge
41
+ : DEFAULT_SUBAGENT_DISPLAY_PREFS.showHeaderBadge,
42
+ autoExpandInteractions:
43
+ typeof obj.autoExpandInteractions === "boolean"
44
+ ? obj.autoExpandInteractions
45
+ : DEFAULT_SUBAGENT_DISPLAY_PREFS.autoExpandInteractions,
46
+ };
47
+ }
48
+
49
+ function readPrefs(): SubagentDisplayPrefs {
50
+ try {
51
+ const saved = window.localStorage.getItem(STORAGE_KEY);
52
+ if (saved === cachedRaw) return cachedSnapshot;
53
+ cachedRaw = saved;
54
+ cachedSnapshot = saved
55
+ ? normalizeSubagentDisplayPrefs(JSON.parse(saved))
56
+ : DEFAULT_SUBAGENT_DISPLAY_PREFS;
57
+ return cachedSnapshot;
58
+ } catch {
59
+ return DEFAULT_SUBAGENT_DISPLAY_PREFS;
60
+ }
61
+ }
62
+
63
+ function subscribePrefs(notify: () => void) {
64
+ window.addEventListener("storage", notify);
65
+ window.addEventListener(PREFS_EVENT, notify);
66
+ return () => {
67
+ window.removeEventListener("storage", notify);
68
+ window.removeEventListener(PREFS_EVENT, notify);
69
+ };
70
+ }
71
+
72
+ export function setSubagentDisplayPrefs(
73
+ patch: Partial<SubagentDisplayPrefs>,
74
+ ): SubagentDisplayPrefs {
75
+ const next: SubagentDisplayPrefs = {
76
+ ...readPrefs(),
77
+ ...patch,
78
+ };
79
+ const serialized = JSON.stringify(next);
80
+ cachedRaw = serialized;
81
+ cachedSnapshot = next;
82
+ try {
83
+ window.localStorage.setItem(STORAGE_KEY, serialized);
84
+ } catch {
85
+ /* ignore storage errors */
86
+ }
87
+ if (typeof window !== "undefined") {
88
+ window.dispatchEvent(new Event(PREFS_EVENT));
89
+ }
90
+ return next;
91
+ }
92
+
93
+ export function resetSubagentDisplayPrefs(): SubagentDisplayPrefs {
94
+ cachedRaw = null;
95
+ cachedSnapshot = DEFAULT_SUBAGENT_DISPLAY_PREFS;
96
+ try {
97
+ window.localStorage.removeItem(STORAGE_KEY);
98
+ } catch {
99
+ /* ignore storage errors */
100
+ }
101
+ if (typeof window !== "undefined") {
102
+ window.dispatchEvent(new Event(PREFS_EVENT));
103
+ }
104
+ return DEFAULT_SUBAGENT_DISPLAY_PREFS;
105
+ }
106
+
107
+ export function isDefaultSubagentDisplayPrefs(
108
+ prefs: SubagentDisplayPrefs,
109
+ ): boolean {
110
+ return (
111
+ prefs.showInlineCards === DEFAULT_SUBAGENT_DISPLAY_PREFS.showInlineCards &&
112
+ prefs.showInteractions === DEFAULT_SUBAGENT_DISPLAY_PREFS.showInteractions &&
113
+ prefs.showHeaderBadge === DEFAULT_SUBAGENT_DISPLAY_PREFS.showHeaderBadge &&
114
+ prefs.autoExpandInteractions ===
115
+ DEFAULT_SUBAGENT_DISPLAY_PREFS.autoExpandInteractions
116
+ );
117
+ }
118
+
119
+ export function useSubagentDisplayPrefs() {
120
+ const prefs = useSyncExternalStore<SubagentDisplayPrefs>(
121
+ subscribePrefs,
122
+ readPrefs,
123
+ () => DEFAULT_SUBAGENT_DISPLAY_PREFS,
124
+ );
125
+ return {
126
+ prefs,
127
+ updatePrefs: setSubagentDisplayPrefs,
128
+ resetPrefs: resetSubagentDisplayPrefs,
129
+ };
130
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scope-agent-workbench",
3
- "version": "0.2.0",
3
+ "version": "0.2.3",
4
4
  "description": "SCOPE: One monitor for all agent sessions — unified web workbench for coding agents across local and SSH GPU hosts",
5
5
  "homepage": "https://github.com/securityCFS/SCOPE#readme",
6
6
  "repository": {
@@ -1,104 +1,104 @@
1
- import { spawn } from "node:child_process";
2
- import { appendFile, mkdir } from "node:fs/promises";
3
- import path from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import {
6
- createAgentEmailRelayServer,
7
- loadOrCreateAgentEmailRelayState,
8
- } from "../bridge/agent-email-relay.mjs";
9
- import { createEmailNotifier } from "../bridge/email-notifier.mjs";
10
-
11
- const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
12
- const stateDirectory = path.join(repoRoot, ".scope");
13
- const relayStatePath = path.join(stateDirectory, "agent-email-relay.json");
14
- const logPath = path.join(stateDirectory, "agent-email-relay.log");
15
- const localHost = "127.0.0.1";
16
- const localPort = Number(process.env.SCOPE_AGENT_EMAIL_LOCAL_PORT || 4822);
17
- const remotePort = Number(process.env.SCOPE_AGENT_EMAIL_REMOTE_PORT || 4922);
18
- const remoteHost = process.env.SCOPE_AGENT_EMAIL_REMOTE_HOST || "";
19
-
20
- await mkdir(stateDirectory, { recursive: true });
21
- const relayState = await loadOrCreateAgentEmailRelayState(relayStatePath, {
22
- remoteHost,
23
- localPort,
24
- remotePort,
25
- });
26
- const notifier = await createEmailNotifier({
27
- configPath: path.join(stateDirectory, "email-notifications.json"),
28
- statePath: path.join(stateDirectory, "agent-email-notification-state.json"),
29
- });
30
- if (!notifier.publicState().configured) {
31
- throw new Error(notifier.publicState().lastError || "SCOPE email is not configured");
32
- }
33
-
34
- const server = createAgentEmailRelayServer({ token: relayState.token, notifier });
35
- await new Promise((resolve, reject) => {
36
- server.once("error", reject);
37
- server.listen(localPort, localHost, resolve);
38
- });
39
- console.log(`[scope-agent-email] relay listening on http://${localHost}:${localPort}`);
40
- if (remoteHost) {
41
- console.log(`[scope-agent-email] forwarding ${remoteHost}:127.0.0.1:${remotePort}`);
42
- } else {
43
- console.log("[scope-agent-email] running local relay without standalone SSH tunnel (use SCOPE Web UI or SCOPE_AGENT_EMAIL_REMOTE_HOST to forward hosts)");
44
- }
45
-
46
- let stopping = false;
47
- let tunnel = null;
48
- let retryTimer = null;
49
- let failures = 0;
50
-
51
- async function log(message) {
52
- const line = `${new Date().toISOString()} ${String(message).trim()}\n`;
53
- await appendFile(logPath, line, "utf8").catch(() => {});
54
- }
55
-
56
- function launchTunnel() {
57
- if (stopping) return;
58
- const startedAt = Date.now();
59
- tunnel = spawn(
60
- "ssh",
61
- [
62
- "-N",
63
- "-T",
64
- "-o",
65
- "BatchMode=yes",
66
- "-o",
67
- "ExitOnForwardFailure=yes",
68
- "-o",
69
- "ServerAliveInterval=30",
70
- "-o",
71
- "ServerAliveCountMax=3",
72
- "-R",
73
- `127.0.0.1:${remotePort}:127.0.0.1:${localPort}`,
74
- remoteHost,
75
- ],
76
- { stdio: ["ignore", "ignore", "pipe"], windowsHide: true },
77
- );
78
- tunnel.stderr.setEncoding("utf8");
79
- tunnel.stderr.on("data", (chunk) => log(chunk));
80
- tunnel.once("error", (error) => log(`ssh error: ${error.message}`));
81
- tunnel.once("exit", (code, signal) => {
82
- tunnel = null;
83
- if (stopping) return;
84
- failures = Date.now() - startedAt > 60_000 ? 0 : failures + 1;
85
- const delay = Math.min(60_000, 1_000 * 2 ** Math.min(failures, 6));
86
- log(`ssh exited (${signal || `code ${code ?? 1}`}); retry in ${delay}ms`);
87
- retryTimer = setTimeout(launchTunnel, delay);
88
- });
89
- }
90
-
91
- function stop(exitCode = 0) {
92
- if (stopping) return;
93
- stopping = true;
94
- if (retryTimer) clearTimeout(retryTimer);
95
- if (tunnel && !tunnel.killed) tunnel.kill("SIGTERM");
96
- server.close(() => process.exit(exitCode));
97
- setTimeout(() => process.exit(exitCode), 1_500).unref();
98
- }
99
-
100
- if (remoteHost) {
101
- launchTunnel();
102
- }
103
- process.on("SIGINT", () => stop(0));
104
- process.on("SIGTERM", () => stop(0));
1
+ import { spawn } from "node:child_process";
2
+ import { appendFile, mkdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import {
6
+ createAgentEmailRelayServer,
7
+ loadOrCreateAgentEmailRelayState,
8
+ } from "../bridge/agent-email-relay.mjs";
9
+ import { createEmailNotifier } from "../bridge/email-notifier.mjs";
10
+
11
+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
12
+ const stateDirectory = path.join(repoRoot, ".scope");
13
+ const relayStatePath = path.join(stateDirectory, "agent-email-relay.json");
14
+ const logPath = path.join(stateDirectory, "agent-email-relay.log");
15
+ const localHost = "127.0.0.1";
16
+ const localPort = Number(process.env.SCOPE_AGENT_EMAIL_LOCAL_PORT || 4822);
17
+ const remotePort = Number(process.env.SCOPE_AGENT_EMAIL_REMOTE_PORT || 4922);
18
+ const remoteHost = process.env.SCOPE_AGENT_EMAIL_REMOTE_HOST || "";
19
+
20
+ await mkdir(stateDirectory, { recursive: true });
21
+ const relayState = await loadOrCreateAgentEmailRelayState(relayStatePath, {
22
+ remoteHost,
23
+ localPort,
24
+ remotePort,
25
+ });
26
+ const notifier = await createEmailNotifier({
27
+ configPath: path.join(stateDirectory, "email-notifications.json"),
28
+ statePath: path.join(stateDirectory, "agent-email-notification-state.json"),
29
+ });
30
+ if (!notifier.publicState().configured) {
31
+ throw new Error(notifier.publicState().lastError || "SCOPE email is not configured");
32
+ }
33
+
34
+ const server = createAgentEmailRelayServer({ token: relayState.token, notifier });
35
+ await new Promise((resolve, reject) => {
36
+ server.once("error", reject);
37
+ server.listen(localPort, localHost, resolve);
38
+ });
39
+ console.log(`[scope-agent-email] relay listening on http://${localHost}:${localPort}`);
40
+ if (remoteHost) {
41
+ console.log(`[scope-agent-email] forwarding ${remoteHost}:127.0.0.1:${remotePort}`);
42
+ } else {
43
+ console.log("[scope-agent-email] running local relay without standalone SSH tunnel (use SCOPE Web UI or SCOPE_AGENT_EMAIL_REMOTE_HOST to forward hosts)");
44
+ }
45
+
46
+ let stopping = false;
47
+ let tunnel = null;
48
+ let retryTimer = null;
49
+ let failures = 0;
50
+
51
+ async function log(message) {
52
+ const line = `${new Date().toISOString()} ${String(message).trim()}\n`;
53
+ await appendFile(logPath, line, "utf8").catch(() => {});
54
+ }
55
+
56
+ function launchTunnel() {
57
+ if (stopping) return;
58
+ const startedAt = Date.now();
59
+ tunnel = spawn(
60
+ "ssh",
61
+ [
62
+ "-N",
63
+ "-T",
64
+ "-o",
65
+ "BatchMode=yes",
66
+ "-o",
67
+ "ExitOnForwardFailure=yes",
68
+ "-o",
69
+ "ServerAliveInterval=30",
70
+ "-o",
71
+ "ServerAliveCountMax=3",
72
+ "-R",
73
+ `127.0.0.1:${remotePort}:127.0.0.1:${localPort}`,
74
+ remoteHost,
75
+ ],
76
+ { stdio: ["ignore", "ignore", "pipe"], windowsHide: true },
77
+ );
78
+ tunnel.stderr.setEncoding("utf8");
79
+ tunnel.stderr.on("data", (chunk) => log(chunk));
80
+ tunnel.once("error", (error) => log(`ssh error: ${error.message}`));
81
+ tunnel.once("exit", (code, signal) => {
82
+ tunnel = null;
83
+ if (stopping) return;
84
+ failures = Date.now() - startedAt > 60_000 ? 0 : failures + 1;
85
+ const delay = Math.min(60_000, 1_000 * 2 ** Math.min(failures, 6));
86
+ log(`ssh exited (${signal || `code ${code ?? 1}`}); retry in ${delay}ms`);
87
+ retryTimer = setTimeout(launchTunnel, delay);
88
+ });
89
+ }
90
+
91
+ function stop(exitCode = 0) {
92
+ if (stopping) return;
93
+ stopping = true;
94
+ if (retryTimer) clearTimeout(retryTimer);
95
+ if (tunnel && !tunnel.killed) tunnel.kill("SIGTERM");
96
+ server.close(() => process.exit(exitCode));
97
+ setTimeout(() => process.exit(exitCode), 1_500).unref();
98
+ }
99
+
100
+ if (remoteHost) {
101
+ launchTunnel();
102
+ }
103
+ process.on("SIGINT", () => stop(0));
104
+ process.on("SIGTERM", () => stop(0));
@@ -1,28 +1,28 @@
1
- import path from "node:path";
2
- import { createEmailNotifier } from "../bridge/email-notifier.mjs";
3
-
4
- const action = process.argv[2] || "status";
5
- const stateDirectory = path.resolve(process.cwd(), ".scope");
6
- const notifier = await createEmailNotifier({
7
- configPath: path.join(stateDirectory, "email-notifications.json"),
8
- statePath: path.join(stateDirectory, "email-notification-state.json"),
9
- });
10
-
11
- if (action === "status") {
12
- console.log(JSON.stringify(notifier.publicState(), null, 2));
13
- } else if (action === "verify") {
14
- console.log(JSON.stringify(await notifier.verify(), null, 2));
15
- } else if (action === "test") {
16
- const result = await notifier.notify({
17
- key: `manual-test:${Date.now()}`,
18
- severity: "test",
19
- title: "SCOPE 邮件通知测试",
20
- summary: "邮件通知 hook 已成功连接并可发送重要告警。",
21
- details: ["这是一封手动触发的测试邮件。"],
22
- timestamp: new Date().toISOString(),
23
- });
24
- console.log(JSON.stringify(result, null, 2));
25
- if (!result.sent) process.exitCode = 1;
26
- } else {
27
- throw new Error("Usage: email-notification-cli.mjs [status|verify|test]");
28
- }
1
+ import path from "node:path";
2
+ import { createEmailNotifier } from "../bridge/email-notifier.mjs";
3
+
4
+ const action = process.argv[2] || "status";
5
+ const stateDirectory = path.resolve(process.cwd(), ".scope");
6
+ const notifier = await createEmailNotifier({
7
+ configPath: path.join(stateDirectory, "email-notifications.json"),
8
+ statePath: path.join(stateDirectory, "email-notification-state.json"),
9
+ });
10
+
11
+ if (action === "status") {
12
+ console.log(JSON.stringify(notifier.publicState(), null, 2));
13
+ } else if (action === "verify") {
14
+ console.log(JSON.stringify(await notifier.verify(), null, 2));
15
+ } else if (action === "test") {
16
+ const result = await notifier.notify({
17
+ key: `manual-test:${Date.now()}`,
18
+ severity: "test",
19
+ title: "SCOPE 邮件通知测试",
20
+ summary: "邮件通知 hook 已成功连接并可发送重要告警。",
21
+ details: ["这是一封手动触发的测试邮件。"],
22
+ timestamp: new Date().toISOString(),
23
+ });
24
+ console.log(JSON.stringify(result, null, 2));
25
+ if (!result.sent) process.exitCode = 1;
26
+ } else {
27
+ throw new Error("Usage: email-notification-cli.mjs [status|verify|test]");
28
+ }