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
@@ -17,6 +17,12 @@ export function catalogRoutes(catalog, { jsonResponse, readJsonBody, resolveCode
17
17
  jsonResponse(response, 200, await catalog.dialogue(url.searchParams.get("key"), {
18
18
  before: url.searchParams.get("before"), version: url.searchParams.get("version"),
19
19
  }));
20
+ } else if (url.pathname === "/api/session-catalog/subagent-workflow" && request.method === "GET") {
21
+ response.setHeader("Cache-Control", "no-store");
22
+ jsonResponse(response, 200, await catalog.subagentWorkflow(url.searchParams.get("key"), {
23
+ subagentId: url.searchParams.get("subagentId"),
24
+ version: url.searchParams.get("version"),
25
+ }));
20
26
  } else if (url.pathname === "/api/session-catalog/select" && request.method === "POST") {
21
27
  const entry = catalog.get((await readJsonBody(request)).key);
22
28
  if (!entry || entry.provider !== "codex") throw new Error("不是 Codex 会话");
package/bridge/start.mjs CHANGED
@@ -1,205 +1,205 @@
1
- import { spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
3
- import { connect } from "node:net";
4
- import { fileURLToPath } from "node:url";
5
-
6
- const UI_PORT = Number(process.env.SCOPE_UI_PORT || 3000);
7
- const BRIDGE_PORT = Number(process.env.SCOPE_BRIDGE_PORT || 4815);
8
- const developmentMode = process.argv.includes("--dev");
9
- const forceBuild = process.argv.includes("--build");
10
- const skipBuild = process.argv.includes("--skip-build");
11
-
12
- function portIsOpen(port) {
13
- return new Promise((resolve) => {
14
- const socket = connect({ host: "127.0.0.1", port });
15
- const finish = (open) => {
16
- socket.removeAllListeners();
17
- socket.destroy();
18
- resolve(open);
19
- };
20
- socket.setTimeout(800);
21
- socket.once("connect", () => finish(true));
22
- socket.once("error", () => finish(false));
23
- socket.once("timeout", () => finish(false));
24
- });
25
- }
26
-
27
- async function isScopeBridge() {
28
- try {
29
- const healthResponse = await fetch(
30
- `http://127.0.0.1:${BRIDGE_PORT}/api/health`,
31
- {
32
- signal: AbortSignal.timeout(5_000),
33
- },
34
- );
35
- if (healthResponse.ok) {
36
- const health = await healthResponse.json();
37
- if (health?.service === "scope-bridge") return true;
38
- }
39
-
40
- const response = await fetch(`http://127.0.0.1:${BRIDGE_PORT}/api/snapshot`, {
41
- signal: AbortSignal.timeout(5_000),
42
- });
43
- if (!response.ok) return false;
44
- const snapshot = await response.json();
45
- return (
46
- typeof snapshot?.sshConfig === "string" && Array.isArray(snapshot?.hosts)
47
- );
48
- } catch {
49
- return false;
50
- }
51
- }
52
-
53
- async function isScopeUi() {
54
- try {
55
- const response = await fetch(`http://127.0.0.1:${UI_PORT}/`, {
56
- signal: AbortSignal.timeout(5_000),
57
- });
58
- if (!response.ok) return false;
59
- const html = await response.text();
60
- return html.includes("SCOPE") && (html.includes("跨项目 Agent 工作台") || html.includes("SSH Codex Monitor"));
61
- } catch {
62
- return false;
63
- }
64
- }
65
-
66
- const [uiPortOpen, bridgePortOpen] = await Promise.all([
67
- portIsOpen(UI_PORT),
68
- portIsOpen(BRIDGE_PORT),
69
- ]);
70
-
71
- if (uiPortOpen || bridgePortOpen) {
72
- const [scopeUi, scopeBridge] = await Promise.all([
73
- uiPortOpen ? isScopeUi() : false,
74
- bridgePortOpen ? isScopeBridge() : false,
75
- ]);
76
- if (scopeUi && scopeBridge) {
77
- console.log(
78
- `SCOPE 已在运行:http://localhost:${UI_PORT}(Bridge ${BRIDGE_PORT})`,
79
- );
80
- process.exit(0);
81
- }
82
-
83
- const occupied = [
84
- uiPortOpen ? UI_PORT : null,
85
- bridgePortOpen ? BRIDGE_PORT : null,
86
- ].filter(Boolean);
87
- console.error(
88
- `[scope] 无法启动:本机端口 ${occupied.join(", ")} 已被其他或不完整的服务占用。`,
89
- );
90
- process.exit(1);
91
- }
92
-
93
- const bridgeEntry = fileURLToPath(new URL("./server.mjs", import.meta.url));
94
- const vinextEntry = fileURLToPath(
95
- new URL("../node_modules/vinext/dist/cli.js", import.meta.url),
96
- );
97
- const uiEntry = fileURLToPath(new URL("./ui-server.mjs", import.meta.url));
98
- const prebuiltServerEntry = fileURLToPath(
99
- new URL("../dist/server/index.js", import.meta.url),
100
- );
101
- const shouldBuild =
102
- !developmentMode &&
103
- !skipBuild &&
104
- (forceBuild || !existsSync(prebuiltServerEntry) || existsSync(vinextEntry));
105
-
106
- if (shouldBuild && !existsSync(vinextEntry)) {
107
- if (existsSync(prebuiltServerEntry)) {
108
- console.log("[scope] Using prebuilt UI bundle.");
109
- } else {
110
- console.error("[scope] Missing prebuilt dist/ bundle and vinext build tool.");
111
- process.exit(1);
112
- }
113
- } else if (shouldBuild) {
114
- console.log("[scope] Building the stable local UI...");
115
- const buildCode = await new Promise((resolve, reject) => {
116
- const build = spawn(process.execPath, [vinextEntry, "build"], {
117
- stdio: "inherit",
118
- });
119
- build.once("error", reject);
120
- build.once("exit", (code) => resolve(code ?? 1));
121
- });
122
- if (buildCode !== 0) {
123
- console.error(`[scope] UI build failed with exit code ${buildCode}`);
124
- process.exit(buildCode);
125
- }
126
- }
127
-
128
- const childSpecs = [
129
- { name: "Bridge", args: [bridgeEntry] },
130
- {
131
- name: "UI",
132
- args: developmentMode
133
- ? [
134
- vinextEntry,
135
- "dev",
136
- "--hostname",
137
- "127.0.0.1",
138
- "--port",
139
- String(UI_PORT),
140
- ]
141
- : [
142
- uiEntry,
143
- "--hostname",
144
- "127.0.0.1",
145
- "--port",
146
- String(UI_PORT),
147
- ],
148
- },
149
- ];
150
- let stopping = false;
151
- const children = new Set();
152
- const restartAttempts = new Map();
153
- const restartTimers = new Set();
154
-
155
- function launchChild(spec) {
156
- if (stopping) return;
157
- const startedAt = Date.now();
158
- const child = spawn(process.execPath, spec.args, { stdio: "inherit" });
159
- children.add(child);
160
- child.on("exit", (code, signal) => {
161
- children.delete(child);
162
- if (stopping) return;
163
- const previousAttempts =
164
- Date.now() - startedAt >= 60_000
165
- ? 0
166
- : restartAttempts.get(spec.name) || 0;
167
- const attempts = previousAttempts + 1;
168
- restartAttempts.set(spec.name, attempts);
169
- if (attempts > 5) {
170
- console.error(
171
- `[scope] ${spec.name} 连续退出 ${attempts} 次;停止 SCOPE 以避免重启循环`,
172
- );
173
- stop(code ?? 1);
174
- return;
175
- }
176
- const delay = Math.min(10_000, 1_000 * 2 ** (attempts - 1));
177
- console.error(
178
- `[scope] ${spec.name} exited (${signal || `code ${code ?? 1}`}); ` +
179
- `${Math.round(delay / 1_000)} 秒后自动重启`,
180
- );
181
- const timer = setTimeout(() => {
182
- restartTimers.delete(timer);
183
- launchChild(spec);
184
- }, delay);
185
- restartTimers.add(timer);
186
- });
187
- }
188
-
189
- function stop(exitCode = 0) {
190
- if (stopping) return;
191
- stopping = true;
192
-
193
- for (const timer of restartTimers) clearTimeout(timer);
194
- restartTimers.clear();
195
- for (const child of children) {
196
- if (!child.killed) child.kill("SIGTERM");
197
- }
198
-
199
- setTimeout(() => process.exit(exitCode), 1_000);
200
- }
201
-
202
- for (const spec of childSpecs) launchChild(spec);
203
-
204
- process.on("SIGINT", () => stop(0));
205
- process.on("SIGTERM", () => stop(0));
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { connect } from "node:net";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const UI_PORT = Number(process.env.SCOPE_UI_PORT || 3000);
7
+ const BRIDGE_PORT = Number(process.env.SCOPE_BRIDGE_PORT || 4815);
8
+ const developmentMode = process.argv.includes("--dev");
9
+ const forceBuild = process.argv.includes("--build");
10
+ const skipBuild = process.argv.includes("--skip-build");
11
+
12
+ function portIsOpen(port) {
13
+ return new Promise((resolve) => {
14
+ const socket = connect({ host: "127.0.0.1", port });
15
+ const finish = (open) => {
16
+ socket.removeAllListeners();
17
+ socket.destroy();
18
+ resolve(open);
19
+ };
20
+ socket.setTimeout(800);
21
+ socket.once("connect", () => finish(true));
22
+ socket.once("error", () => finish(false));
23
+ socket.once("timeout", () => finish(false));
24
+ });
25
+ }
26
+
27
+ async function isScopeBridge() {
28
+ try {
29
+ const healthResponse = await fetch(
30
+ `http://127.0.0.1:${BRIDGE_PORT}/api/health`,
31
+ {
32
+ signal: AbortSignal.timeout(5_000),
33
+ },
34
+ );
35
+ if (healthResponse.ok) {
36
+ const health = await healthResponse.json();
37
+ if (health?.service === "scope-bridge") return true;
38
+ }
39
+
40
+ const response = await fetch(`http://127.0.0.1:${BRIDGE_PORT}/api/snapshot`, {
41
+ signal: AbortSignal.timeout(5_000),
42
+ });
43
+ if (!response.ok) return false;
44
+ const snapshot = await response.json();
45
+ return (
46
+ typeof snapshot?.sshConfig === "string" && Array.isArray(snapshot?.hosts)
47
+ );
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ async function isScopeUi() {
54
+ try {
55
+ const response = await fetch(`http://127.0.0.1:${UI_PORT}/`, {
56
+ signal: AbortSignal.timeout(5_000),
57
+ });
58
+ if (!response.ok) return false;
59
+ const html = await response.text();
60
+ return html.includes("SCOPE") && (html.includes("跨项目 Agent 工作台") || html.includes("SSH Codex Monitor"));
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ const [uiPortOpen, bridgePortOpen] = await Promise.all([
67
+ portIsOpen(UI_PORT),
68
+ portIsOpen(BRIDGE_PORT),
69
+ ]);
70
+
71
+ if (uiPortOpen || bridgePortOpen) {
72
+ const [scopeUi, scopeBridge] = await Promise.all([
73
+ uiPortOpen ? isScopeUi() : false,
74
+ bridgePortOpen ? isScopeBridge() : false,
75
+ ]);
76
+ if (scopeUi && scopeBridge) {
77
+ console.log(
78
+ `SCOPE 已在运行:http://localhost:${UI_PORT}(Bridge ${BRIDGE_PORT})`,
79
+ );
80
+ process.exit(0);
81
+ }
82
+
83
+ const occupied = [
84
+ uiPortOpen ? UI_PORT : null,
85
+ bridgePortOpen ? BRIDGE_PORT : null,
86
+ ].filter(Boolean);
87
+ console.error(
88
+ `[scope] 无法启动:本机端口 ${occupied.join(", ")} 已被其他或不完整的服务占用。`,
89
+ );
90
+ process.exit(1);
91
+ }
92
+
93
+ const bridgeEntry = fileURLToPath(new URL("./server.mjs", import.meta.url));
94
+ const vinextEntry = fileURLToPath(
95
+ new URL("../node_modules/vinext/dist/cli.js", import.meta.url),
96
+ );
97
+ const uiEntry = fileURLToPath(new URL("./ui-server.mjs", import.meta.url));
98
+ const prebuiltServerEntry = fileURLToPath(
99
+ new URL("../dist/server/index.js", import.meta.url),
100
+ );
101
+ const shouldBuild =
102
+ !developmentMode &&
103
+ !skipBuild &&
104
+ (forceBuild || !existsSync(prebuiltServerEntry) || existsSync(vinextEntry));
105
+
106
+ if (shouldBuild && !existsSync(vinextEntry)) {
107
+ if (existsSync(prebuiltServerEntry)) {
108
+ console.log("[scope] Using prebuilt UI bundle.");
109
+ } else {
110
+ console.error("[scope] Missing prebuilt dist/ bundle and vinext build tool.");
111
+ process.exit(1);
112
+ }
113
+ } else if (shouldBuild) {
114
+ console.log("[scope] Building the stable local UI...");
115
+ const buildCode = await new Promise((resolve, reject) => {
116
+ const build = spawn(process.execPath, [vinextEntry, "build"], {
117
+ stdio: "inherit",
118
+ });
119
+ build.once("error", reject);
120
+ build.once("exit", (code) => resolve(code ?? 1));
121
+ });
122
+ if (buildCode !== 0) {
123
+ console.error(`[scope] UI build failed with exit code ${buildCode}`);
124
+ process.exit(buildCode);
125
+ }
126
+ }
127
+
128
+ const childSpecs = [
129
+ { name: "Bridge", args: [bridgeEntry] },
130
+ {
131
+ name: "UI",
132
+ args: developmentMode
133
+ ? [
134
+ vinextEntry,
135
+ "dev",
136
+ "--hostname",
137
+ "127.0.0.1",
138
+ "--port",
139
+ String(UI_PORT),
140
+ ]
141
+ : [
142
+ uiEntry,
143
+ "--hostname",
144
+ "127.0.0.1",
145
+ "--port",
146
+ String(UI_PORT),
147
+ ],
148
+ },
149
+ ];
150
+ let stopping = false;
151
+ const children = new Set();
152
+ const restartAttempts = new Map();
153
+ const restartTimers = new Set();
154
+
155
+ function launchChild(spec) {
156
+ if (stopping) return;
157
+ const startedAt = Date.now();
158
+ const child = spawn(process.execPath, spec.args, { stdio: "inherit" });
159
+ children.add(child);
160
+ child.on("exit", (code, signal) => {
161
+ children.delete(child);
162
+ if (stopping) return;
163
+ const previousAttempts =
164
+ Date.now() - startedAt >= 60_000
165
+ ? 0
166
+ : restartAttempts.get(spec.name) || 0;
167
+ const attempts = previousAttempts + 1;
168
+ restartAttempts.set(spec.name, attempts);
169
+ if (attempts > 5) {
170
+ console.error(
171
+ `[scope] ${spec.name} 连续退出 ${attempts} 次;停止 SCOPE 以避免重启循环`,
172
+ );
173
+ stop(code ?? 1);
174
+ return;
175
+ }
176
+ const delay = Math.min(10_000, 1_000 * 2 ** (attempts - 1));
177
+ console.error(
178
+ `[scope] ${spec.name} exited (${signal || `code ${code ?? 1}`}); ` +
179
+ `${Math.round(delay / 1_000)} 秒后自动重启`,
180
+ );
181
+ const timer = setTimeout(() => {
182
+ restartTimers.delete(timer);
183
+ launchChild(spec);
184
+ }, delay);
185
+ restartTimers.add(timer);
186
+ });
187
+ }
188
+
189
+ function stop(exitCode = 0) {
190
+ if (stopping) return;
191
+ stopping = true;
192
+
193
+ for (const timer of restartTimers) clearTimeout(timer);
194
+ restartTimers.clear();
195
+ for (const child of children) {
196
+ if (!child.killed) child.kill("SIGTERM");
197
+ }
198
+
199
+ setTimeout(() => process.exit(exitCode), 1_000);
200
+ }
201
+
202
+ for (const spec of childSpecs) launchChild(spec);
203
+
204
+ process.on("SIGINT", () => stop(0));
205
+ process.on("SIGTERM", () => stop(0));
@@ -58,6 +58,7 @@ export function createStatePersistence({
58
58
  getGpuUsageHistory,
59
59
  getHistoryIndex,
60
60
  setHistoryIndex,
61
+ enrichAgentRelations = null,
61
62
  }) {
62
63
  let stateWritePromise = Promise.resolve();
63
64
  let gpuUsageWritePromise = Promise.resolve();
@@ -291,10 +292,17 @@ export function createStatePersistence({
291
292
  for (const alias of aliases) {
292
293
  const entry = historyIndex.hosts[alias]?.orders?.[requestedOrder];
293
294
  if (!entry) continue;
295
+ const liveHost = snapshot.hosts.find((item) => item.alias === alias);
294
296
  const hostSessions = excludeActiveSessions(
295
297
  entry.sessions,
296
298
  activeSessions,
297
- ).slice(0, limit);
299
+ )
300
+ .slice(0, limit)
301
+ .map((agent) =>
302
+ liveHost && enrichAgentRelations
303
+ ? enrichAgentRelations(liveHost, agent)
304
+ : agent,
305
+ );
298
306
  sessions.push(...hostSessions);
299
307
  hosts.push({
300
308
  host: alias,
@@ -1,29 +1,29 @@
1
- const MAX_TMUX_SESSION_NAME_LENGTH = 512;
2
-
3
- function posixShellQuote(value) {
4
- return `'${String(value).replaceAll("'", `'\"'\"'`)}'`;
5
- }
6
-
7
- export function normalizeTmuxSessionName(value) {
8
- if (typeof value !== "string") {
9
- throw new TypeError("tmux Session 名称必须是字符串");
10
- }
11
- if (!value || value.length > MAX_TMUX_SESSION_NAME_LENGTH) {
12
- throw new Error("tmux Session 名称为空或过长");
13
- }
14
- if (/[\0\r\n\t]/.test(value)) {
15
- throw new Error("tmux Session 名称包含非法控制字符");
16
- }
17
- return value;
18
- }
19
-
20
- export function buildExactTmuxTerminateCommand(value) {
21
- const sessionName = normalizeTmuxSessionName(value);
22
- const target = posixShellQuote(`=${sessionName}`);
23
- return [
24
- `tmux has-session -t ${target} 2>/dev/null || { printf '%s\\n' 'SCOPE_TMUX_SESSION_MISSING' >&2; exit 44; }`,
25
- `tmux kill-session -t ${target} 2>/dev/null || true`,
26
- `if tmux has-session -t ${target} 2>/dev/null; then printf '%s\\n' 'SCOPE_TMUX_SESSION_STILL_RUNNING' >&2; exit 45; fi`,
27
- `printf '%s\\n' 'SCOPE_TMUX_SESSION_TERMINATED'`,
28
- ].join("; ");
29
- }
1
+ const MAX_TMUX_SESSION_NAME_LENGTH = 512;
2
+
3
+ function posixShellQuote(value) {
4
+ return `'${String(value).replaceAll("'", `'\"'\"'`)}'`;
5
+ }
6
+
7
+ export function normalizeTmuxSessionName(value) {
8
+ if (typeof value !== "string") {
9
+ throw new TypeError("tmux Session 名称必须是字符串");
10
+ }
11
+ if (!value || value.length > MAX_TMUX_SESSION_NAME_LENGTH) {
12
+ throw new Error("tmux Session 名称为空或过长");
13
+ }
14
+ if (/[\0\r\n\t]/.test(value)) {
15
+ throw new Error("tmux Session 名称包含非法控制字符");
16
+ }
17
+ return value;
18
+ }
19
+
20
+ export function buildExactTmuxTerminateCommand(value) {
21
+ const sessionName = normalizeTmuxSessionName(value);
22
+ const target = posixShellQuote(`=${sessionName}`);
23
+ return [
24
+ `tmux has-session -t ${target} 2>/dev/null || { printf '%s\\n' 'SCOPE_TMUX_SESSION_MISSING' >&2; exit 44; }`,
25
+ `tmux kill-session -t ${target} 2>/dev/null || true`,
26
+ `if tmux has-session -t ${target} 2>/dev/null; then printf '%s\\n' 'SCOPE_TMUX_SESSION_STILL_RUNNING' >&2; exit 45; fi`,
27
+ `printf '%s\\n' 'SCOPE_TMUX_SESSION_TERMINATED'`,
28
+ ].join("; ");
29
+ }